Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inserting an array into a Postgresql database

Tags:

I want to be able to write an array of bigints into a table that I am using for history in Go. Unfortunately, I can't and when I do the error sql: converting Exec argument #1's type: unsupported type []int64, a slice is thrown. Here's what I'm doing, edited for brevity:

type Card struct {
    cid int64
}

type Transaction struct {
        tid, cardid int64
        productids []int64
        salepoint int
        cardkey string
}

func logPurchase(card *Card, t *Transaction) {
     _, err := db.Exec("INSERT INTO history VALUES ($1, $2, $3, $4)", rand.Int63(), t.productids, card.cid, t.salepoint);
}

This is the structure of the table that I wish to insert into: tid bigint primary key, productids bigint[] not null, cardid bigint not null, salepoint int

like image 815
ShrekTheDinosaur Avatar asked Nov 03 '14 03:11

ShrekTheDinosaur


2 Answers

Arrays are supported in github.com/lib/pq since 2016 Aug 6th. OP's statement could be written as:

_, err := db.Exec(
    "INSERT INTO history VALUES ($1, $2, $3, $4)", 
    rand.Int63(), 
    pq.Array(t.productids),   // <------- 
    card.cid, 
    t.salepoint,
)
like image 180
kennytm Avatar answered Oct 22 '22 22:10

kennytm


Implement database/sql/driver.Valuer with a custom type:

type int64array []int64

func (a int64array) Value() (driver.Value, error) {
    // Format a in PostgreSQL's array input format {1,2,3} and return it as as string or []byte.
}
like image 36
andybalholm Avatar answered Oct 22 '22 21:10

andybalholm