ECMAScript 6 (2015) template tag function to write queries for node-postgres.
npm install @stf8/pg-template-tagNote :
This is a fork of https://github.com/XeCycle/pg-template-tag with updated dependencies and few addons.
Build a { text, values } object for use with
brianc/node-postgres.
Supports nesting.
Write the query as-is inside template literals, use ${} interpolation to
supply values.
``javascriptselect name from user where id=${id}
var SQL = require("pg-template-tag");
connection.query(SQL);select value from record where ${ lower===null ? SQL
connection.query(SQLtrue : SQLtime > ${lower}});`
Pieces are reusable, so you can:
`javascriptname, time, score, history_avg(score) as "scoreAvg"
var fields = SQL;select ${fields} from scores where time > current_date
connection.query(SQL);select ${fields} from scores where score > ${minScore}
connection.query(SQL);`
Values are reused within the query if the piece is reused.
`javascript${[1, 2, 3]}
var ids = SQL;
var query = 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.
`javascriptemail like ${filter.email}
function filterUsers(filter) {
var conditions = [];
if (filter.email) conditions.push(SQL);age > ${filter.minAge}
if (filter.minAge) conditions.push(SQL);age < ${filter.maxAge}
if (filter.maxAge) conditions.push(SQL);select * from users where ${SQL.join(conditions, ' and ')}
return connection.query(SQL);`
}.id
There's an function to espace table name, and other identifiers.
`javascriptSELECT * FROM ${SQL.id('foo')} where ${SQL.id('foo.bar')} = ${'baz'}
SQL;`.id can take either a string (it will be split if there is any dot in it) or an array, eg "foo.bar" is equivalent to ["foo","bar"]`.