prepare-sql
SQL template strings
Usage
var SQL = const username = 'emilbayes'// Query with template stringconst select = SQL`SELECT * FROM users WHERE username = ` const insertRows = 'mafintosh' 'chm-diederichs' // SQL.join can combine queriesconst insert = SQL`INSERT INTO users (username, create_at) VALUES ` // You can also nest queries inside each otherconst statement = SQL`DO $$ BEGIN END $$` // Or use append to perform a mix of safe and unsafe query buildingvar updateKey = 'username'var updateValue = 'emil' const update = SQL`UPDATE users SET ` // Unsafe! // Safe // Also safe
API
``var prepared = SQL`statement```
prepared.text
Returns a prepared query statement in PostgreSQL format (eg. $1
for placeholders).
Works directly with pg
const Client = const SQL = const client = client client
prepared.sql
Returns a prepared query statement in MySQL format (eg. ?
for placeholders).
Works directly with mysql
:
connection;
prepared.values
List of extracted values from the template string. Note that nested queries will
be collapsed, eg.
SQL`SELECT * FROM users WHERE name = ${'emil'} AND ${SQLusername = ${'emilbayes'}`}
will result in ['emil', 'emilbayes']
despite them being nested.
prepared.append(sqlOrString)
Append to the original query. Can be either a string for unsafe query parts eg. static SQL, or another SQL tagged template.
SQL.join(queriesArray, [separator = ','])
Join together multiple SQL tagged templates. Useful with key-values in UPDATE
statements or combining many rows for INSERT
. Default separator is ','
(like Array.prototype.join
), but can be any string.
Install
npm install prepare-sql