node-postgres: how to execute "WHERE col IN (<dynamic value list>)" query?
It looks like you may have been close based on your comment to @ebohlman's answer. You can use WHERE id = ANY($1::int[])
. PostgreSQL will convert the array to the type the parameter is cast to in $1::int[]
. So here's a contrived example that works for me:
var ids = [1,3,4];
var q = client.query('SELECT Id FROM MyTable WHERE Id = ANY($1::int[])',[ids]);
q.on('row', function(row) {
console.log(row);
})
// outputs: { id: 1 }
// { id: 3 }
// { id: 4 }
We've seen this question before on the github issues list. The correct way is to dynamically generate your list of parameters based on the array. Something like this:
var arr = [1, 2, "hello"];
var params = [];
for(var i = 1; i <= arr.length; i++) {
params.push('$' + i);
}
var queryText = 'SELECT id FROM my_table WHERE something IN (' + params.join(',') + ')';
client.query(queryText, arr, function(err, cb) {
...
});
That way you get the postgres parameterized escaping.