Created
April 8, 2019 15:27
-
-
Save vituchon/d208835074e79f523558026e18d09716 to your computer and use it in GitHub Desktop.
Example usage of Postgres Array within a golang app
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"database/sql" | |
"fmt" | |
"log" | |
"github.com/lib/pq" | |
) | |
const ( | |
host = "localhost" | |
port = 5432 | |
user = "a_user" | |
password = "xxxxx" | |
dbname = "a_db" | |
) | |
type SampleRow struct { | |
Id int | |
MultiplesIds []int64 | |
MultiplesString []string | |
} | |
func ensureSampleTableExists(db *sql.DB) { | |
_, err := db.Exec(` | |
CREATE TABLE IF NOT EXISTS sample ( id serial NOT NULL, | |
multiples_ids bigint[], | |
multiples_string text[], | |
CONSTRAINT sample_pk PRIMARY KEY (id) | |
)`) | |
if err != nil { | |
panic(err) | |
} | |
} | |
func main() { | |
psqlInfo := fmt.Sprintf("host=%s port=%d user=%s "+ | |
"password=%s dbname=%s sslmode=disable", | |
host, port, user, password, dbname) | |
db, err := sql.Open("postgres", psqlInfo) | |
if err != nil { | |
panic(err) | |
} | |
defer db.Close() | |
ensureSampleTableExists(db) | |
/*var x []int64 // must be int64 to work when reading... compatibility issues i guess... | |
db.QueryRow("SELECT ARRAY[235, 401]").Scan(pq.Array(&x)) | |
log.Println(x)*/ | |
insertRow(db, SampleRow{MultiplesIds: []int64{2, 3}, MultiplesString: []string{"aaaa", "bbbbb"}}) | |
samples, err := getRows(db) | |
if err != nil { | |
log.Panicln(err) | |
} else { | |
log.Println(samples) | |
} | |
/*defer func() { | |
if r := recover(); r != nil { | |
fmt.Println("Recovered in f", r) | |
} | |
}() | |
slice := []string{} | |
for i := 0; i < 100000000; i++ { | |
slice = append(slice, "BLA ") | |
} | |
fmt.Println(slice)*/ | |
} | |
func insertRow(Db *sql.DB, s SampleRow) (SampleRow, error) { | |
err := Db.QueryRow(` | |
INSERT INTO sample(multiples_ids, multiples_string) | |
VALUES ($1, $2) RETURNING id`, pq.Array(s.MultiplesIds), pq.Array(s.MultiplesString)).Scan(&s.Id) | |
return s, err | |
} | |
func getRows(Db *sql.DB) ([]SampleRow, error) { | |
rows, err := Db.Query(` | |
SELECT id, multiples_ids,multiples_string | |
FROM sample`) | |
if err != nil { | |
if err == sql.ErrNoRows { | |
return nil, nil | |
} | |
return nil, err | |
} | |
defer rows.Close() | |
samples := []SampleRow{} | |
for rows.Next() { | |
var sample SampleRow | |
err = rows.Scan(&sample.Id, pq.Array(&sample.MultiplesIds), pq.Array(&sample.MultiplesString)) | |
if err != nil { | |
log.Panicln("Error while scanning feched results", err) | |
return nil, err | |
} | |
samples = append(samples, sample) | |
} | |
return samples, nil | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment