You can use pq.Array with slice parameters nowadays. So the query would look like:
rows, err := db.Query("SELECT * FROM table WHERE id in $1", pq.Array([]int{1, 2, 3}))
Domanda
I'm trying to write a query that takes a list parameter (ie, a single parameter which is a list of values). It appears that this is at least sometimes possible in Postgres (https://stackoverflow.com/a/10829760/836390). What I want is something like this:
rows, err := db.Query("SELECT * FROM table WHERE id in $1", []int{1, 2, 3})
However, when I execute this using the pq driver, I get an error:
sql: converting Exec argument #0's type: unsupported type []int, a slice
Is this simply not supported in pq
yet, or is this not supported in database/sql
, or not in Postgres at all, or what? Thanks!
Soluzione
You can use pq.Array with slice parameters nowadays. So the query would look like:
rows, err := db.Query("SELECT * FROM table WHERE id in $1", pq.Array([]int{1, 2, 3}))
Altri suggerimenti
So it looks like pq uses database/sql's default ValueConverter, which has no ability to handle slices (see the documentation for DefaultParameterConverter).
I couldn't get the accepted answer to work due to a syntax error. I modified the answer a bit and got it to work for me.
The resource I used was the pq.Array function documentation.
rows, err := db.Query("SELECT * FROM table WHERE id = ANY($1)", pq.Array([]int{1, 2, 3}))
Look at using an alternative Postgres client: https://github.com/vmihailenco/pg
The readme details array support and includes an example of using a slice.
_, err := db.Query(users,
`WITH users (name, emails) AS (VALUES (?, ?), (?, ?))
SELECT * FROM users`,
"admin", []string{"admin1@admin", "admin2@admin"},
"root", []string{"root1@root", "root2@root"},
)
(I've not used this myself, but a look over it shows promise).
This does in fact appear to be 'temperamental'. Here are two I would attempt:
rows, err := db.Query("SELECT * FROM table WHERE id in ($1)", []int{1, 2, 3})
or
rows, err := db.Query("SELECT * FROM table WHERE id = ANY($1::[]int)", []int{1, 2, 3})