0

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.

2 Answers 2

4

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))
Sign up to request clarification or add additional context in comments.

3 Comments

Maybe I have this behaviour because of the type of the slice (it is initially pq.Int64Array)?
In that case your slice should be []int64{1,2,3,4,5}
@ArthurBerg pq.Array used properly, i.e. passed directly to db.Exec and with $1 instead of fmt and {%v} does not produce {[1,2,3,4,5]}. First you may want to read up on SQL injections, then you should stop using fmt and plain string interpolation for query construction, and finally try to follow the suggestions in an answer thoroughly.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.