I have to use an SQL query like the one below in a Node.js app.
SELECT * FROM my_table
WHERE my_column IN ['name1','name2']
The array ['name1', 'name2'] is inputted by the user. And it may contain more than 2 names sometimes. How do I format this query using the pg-format package to avoid SQL injection?
Aren't the IN
clause arguments supposed to be wrapped using parentheses?
Anyway, here's an example on formatting using pg-format,
var format = require('pg-format');
var sql = format("SELECT * FROM my_table WHERE my_column IN (%L, %L)", 'Alice', 'Bob'); // name1, name2
console.log(sql);
Edit 1: With dynamic names using an array,
var format = require('pg-format');
var names = ['Alice', 'Bob', 'Charlie'];
var inCaluseStr = '(' + Array(names.length).fill('%L').join(',') + ')';
var sql = format.withArray("SELECT * FROM my_table WHERE my_column IN " + inCaluseStr, names);
console.log(sql);
I hope this helps.