Reputation: 1999
I'm saving an array of integers into PostgreSQL table, and when trying to retrieve it, I always get []uint8 instead of []int. I tried to user []integer, []bigint, []smallint. nothing works. The array represent a maximum of four items, each one between 1-100, no floating point.
I'm using Go, and I have an object that is an []int, this is the field:
Quantity []int `json:"quantity" db:"quantity"`
I'm trying to fix it but can't find a way to make PostgreSQL to return an []int.
All the other table fields working great. the Quantity
field is of type integer[]
This is the insertion query:
"INSERT INTO products (product_id, name, manufacturer, image_url, quantity, amount, notes, store_id, store_name, owner_id) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)", newProduct.UID, newProduct.Name, newProduct.Manufacturer, newProduct.Image, pq.Array(newProduct.Quantity), newProduct.Amount, newProduct.Notes, newProduct.StoreID, newProduct.StoreName, newProduct.OwnerID);
This is how I try and get the data.
err := rows.Scan(&temp.ID, &temp.UID, &temp.Name, &temp.Manufacturer,
&temp.Image, &temp.Amount, &temp.Notes,
&temp.StoreID, &temp.OwnerID, &temp.StoreName, &temp.Quantity)
The problem is only with Quantity.
If I change my temp object
to []uint8
instead of []int
I do get the bytes.
Upvotes: 2
Views: 1938
Reputation: 18430
Use pq.Array(&temp.Quantity)
The way you store, you have to retrieve also that way.
err := rows.Scan(&temp.ID, &temp.UID, &temp.Name, &temp.Manufacturer,
&temp.Image, &temp.Amount, &temp.Notes,
&temp.StoreID, &temp.OwnerID, &temp.StoreName, pq.Array(&temp.Quantity))
And you have to use supported types for pq.Array()
also or implement Scanner interface. For integer you can use []sql.NullInt64
or []int64
. But it's better to use the same supported type for Scanner and Valuer interface.
Find more details here.
Upvotes: 5