You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Build a { text, values } object for use with
brianc/node-postgres.
Supports nesting.
Example
Write the query as-is inside template literals, use ${} interpolation to
supply values.
varSQL=require("pg-template-tag");connection.query(SQL`select name from user where id=${id}`);connection.query(SQL`select value from record where ${lower===null ? SQL`true` : SQL`time > ${lower}`}`);
Pieces are reusable, so you can:
varfields=SQL`name, time, score, history_avg(score) as "scoreAvg"`;connection.query(SQL`select ${fields} from scores where time > current_date`);connection.query(SQL`select ${fields} from scores where score > ${minScore}`);
Values are reused within the query if the piece is reused.
varids=SQL`${[1,2,3]}`;varquery=SQL` select name from a where id = any(${ids}) union all select name from b where id = any(${ids})`;query.text;// 'select ... where id = any($1) union all select ... where id = any($1)'query.values;// [[1, 2, 3]]
There's a .join function analog to Array.prototype.join to join together literals.
functionfilterUsers(filter){varconditions=[];if(filter.email)conditions.push(SQL`email like ${filter.email}`);if(filter.minAge)conditions.push(SQL`age > ${filter.minAge}`);if(filter.maxAge)conditions.push(SQL`age < ${filter.maxAge}`);returnconnection.query(SQL`select * from users where ${SQL.join(conditions,' and ')}`);}