Reputation: 3
I have a problem with inserting slice into postgres array directly and can't find a simple solution.
Given:
favorites := []int{1,2,3,4,5}
// need to
_, err = db.Exec(fmt.Sprintf("UPDATE users SET favorites = '{%v}';", favorites))
Because of input is '{[1,2,3,4,5]}' instead of '{1,2,3,4,5}' I have an error. I am using default SQL package and "github.com/lib/pq" postgres driver.
Upvotes: 0
Views: 2034
Reputation: 41
using pq.array to the respective golang slice will help you to insert the array.
q = q.Values(result.Id, result.Text, result.CreatedAt, pq.Array(result.EditHistoryTweetIds))
here EditHistoryTweetIds will be golang slice.
Upvotes: 0
Reputation: 891
You should use pq.Array(favorites) to insert it correctly. As you can see in the source code
It would be like:
favorites := []int{1,2,3,4,5}
query:= "UPDATE users SET favorites = $1;"
_, err = db.Exec(query, pq.Array(favorites))
Upvotes: 3