node-postgres icon indicating copy to clipboard operation
node-postgres copied to clipboard

Multiple values macros

Open UltraDosaaf opened this issue 7 years ago • 4 comments

let result = await pgQuery("SELECT date, city FROM test WHERE date IN ($1, $2)", [ 2018, 2019 ]); What if I have more than 2 values? Is there some macros or some method to skip this kind of routine (like (?) in mysql module) and keep all the good like auto-sanitizing the input data?

UltraDosaaf avatar Jul 02 '19 14:07 UltraDosaaf

let placeholders = []; myArgs.forEach((value,idx) => { placeholders.push('$'+(idx+1)) });

let query = SELECT ... WHERE column IN (${placeholders.join(',')}) const {rows} = await dbPool.query(query, myArgs);

ngervasi avatar Jul 02 '19 14:07 ngervasi

Postgres supports array parameters which are perfect for this:

// Usually need to cast the parameter via ::type[] to ensure the server knows what you want it to be
const sql = 'SELECT data, city FROM test WHERE date = ANY($1::int[])';

// The parameter value itself is a JS array
const values = [2018, 2019, 2020,];

// NOTE: Second parameter to query(...) (i.e. the params) is an array with index zero as the array of date values
const result = await pool.query(sql, [values]); 

Search the GitHub issues for this repo for "array parameter" and you'll find a bunch of other examples and benefits to using them.

sehrope avatar Jul 02 '19 14:07 sehrope

Nice! Didn't know this one!

ngervasi avatar Jul 02 '19 14:07 ngervasi

@sehrope OMG, that works!

UltraDosaaf avatar Jul 02 '19 14:07 UltraDosaaf