Sub topic 9
Practical Pattern: Parameterized SQL Queries
This chapter assumes you already know how a tag receives its strings array and its values, and how reduce without an initial value interleaves them. It also assumes you know that a tag may return something other than a string. Basic SQL and some experience with a Node.js database driver will help, but you can run every example here without a database.
The Problem: Building SQL with Interpolation
The easiest way to write a query is also the most dangerous one:
const email = "x' OR '1'='1";
const query = `SELECT * FROM users WHERE email = '${email}'`;
console.log(query);
// SELECT * FROM users WHERE email = 'x' OR '1'='1'The user's input closed the quote and added a condition that is always true. This is SQL injection. Escaping quotes by hand is fragile. The correct fix is a parameterized query: you send the SQL text with placeholders such as $1 and send the values separately. The database parses the text first and then binds the values as data, so a value can never change the structure of the query.
Tagged templates suit this well. The static parts of the literal are written by the developer and can be trusted. The substitutions are the values that may come from outside. The tag receives the two already separated, so it never has to work out which part is which.
The Basic `sql` Tag
The tag below returns an object instead of a string. The object holds numbered placeholders in the text and keeps the values in a separate array:
function sql(strings, ...values) {
return {
text: strings.reduce((query, str, i) => query + '$' + i + str),
values,
};
}
const id = 42;
const status = 'active';
console.log(sql`SELECT * FROM users WHERE id = ${id} AND status = ${status}`);
// { text: 'SELECT * FROM users WHERE id = $1 AND status = $2', values: [42, 'active'] }reduce has no initial value, so it starts from strings[0] and begins with i = 1. That index lines up with the PostgreSQL placeholder numbering, which starts at $1. The values never get into text.
The returned shape { text, values } is the query config object that node-postgres (pg) accepts directly:
const { Client } = require('pg');
async function findUser(email) {
const client = new Client(); // reads PGHOST, PGUSER, etc. from the environment
await client.connect();
try {
const result = await client.query(sql`SELECT * FROM users WHERE email = ${email}`);
return result.rows;
} finally {
await client.end();
}
}If you pass the injection string from earlier to this function, it searches for a user whose email is literally x' OR '1'='1. It finds nobody.
Adapting to Other Placeholder Styles
Each database driver expects its own placeholder syntax. The tag is the only place that needs to know which one to use.
| Driver / database | Placeholder | Tag body |
|---|---|---|
| `pg` (PostgreSQL) | `$1`, `$2`, ... | `strings.reduce((q, s, i) => q + '$' + i + s)` |
| `mysql2`, `sqlite3`, `better-sqlite3` | `?` | `strings.join('?')` |
| Oracle (`oracledb`) | `:1`, `:2`, ... | `strings.reduce((q, s, i) => q + ':' + i + s)` |
The positional ? style is the simplest to generate, because the strings array always has exactly one more element than the values array:
function mysql(strings, ...values) {
return { sql: strings.join('?'), values };
}
console.log(mysql`UPDATE posts SET title = ${'Hi'} WHERE id = ${7}`);
// { sql: 'UPDATE posts SET title = ? WHERE id = ?', values: [ 'Hi', 7 ] }mysql2 accepts this { sql, values } shape as an options object in connection.query.
Composing Queries from Fragments
Real queries are often built from smaller pieces, such as an optional filter. The basic tag cannot nest. If you place one sql result inside another, the inner object becomes a single bound value, which is wrong.
The fix is to return a marker object and delay numbering until the whole query is assembled. A separate compile step walks the tree. Fragments are inlined and plain values become placeholders:
class SqlFragment {
constructor(strings, values) {
this.strings = strings;
this.values = values;
}
}
function sql(strings, ...values) {
return new SqlFragment(strings, values);
}
function compile(fragment) {
const params = [];
function walk(frag) {
let text = frag.strings[0];
frag.values.forEach((value, i) => {
if (value instanceof SqlFragment) {
text += walk(value);
} else {
params.push(value);
text += '$' + params.length;
}
text += frag.strings[i + 1];
});
return text;
}
return { text: walk(fragment), values: params };
}
const minAge = 18;
const filter = sql`age >= ${minAge}`;
console.log(compile(sql`SELECT * FROM users WHERE ${filter} AND status = ${'active'}`));
// { text: 'SELECT * FROM users WHERE age >= $1 AND status = $2', values: [ 18, 'active' ] }The numbering comes from params.length and not from i, so placeholders stay sequential across every level of nesting. Only objects made by the sql tag are inlined. A string can never pass for a fragment, so composing queries does not reopen the injection hole.
Lists for `IN (...)`
One placeholder binds one value, so IN (${ids}) with an array does not expand into several placeholders. You can build a fragment with one slot per item:
function list(items) {
if (items.length === 0) {
throw new Error('list() needs at least one item');
}
const strings = ['', ...Array(items.length - 1).fill(', '), ''];
return new SqlFragment(strings, items);
}
console.log(compile(sql`SELECT * FROM users WHERE id IN (${list([3, 5, 8])})`));
// { text: 'SELECT * FROM users WHERE id IN ($1, $2, $3)', values: [ 3, 5, 8 ] }The function builds a strings array of length n + 1 by hand. That matches the invariant every tag relies on. An empty list would produce IN (), which is a syntax error, so the function rejects it up front. In real code you would usually skip the query and return no rows.
Identifiers Cannot Be Parameters
Placeholders stand for values only. A table name, a column name, or a sort direction such as ASC cannot be bound. If you need a dynamic identifier, check it against an allowlist and then wrap it in a fragment that contains no values:
const SORTABLE = new Set(['name', 'created_at']);
function column(name) {
if (!SORTABLE.has(name)) {
throw new Error(`Cannot sort by ${name}`);
}
return new SqlFragment(['"' + name + '"'], []);
}
console.log(compile(sql`SELECT * FROM users ORDER BY ${column('name')}`).text);
// SELECT * FROM users ORDER BY "name"Common Mistakes
- Calling the tag with parentheses.
sql(\... ${email}\)evaluates an ordinary template literal first and then passes a single, already-interpolated string. Some libraries check for this. The minimal tag above does not: it receivesstrings = "SELECT ..."andvalues = [], and with only one elementreducereturns that string untouched, so the injection goes through silently. A defensive tag checksArray.isArray(strings) && Array.isArray(strings.raw). - Quoting placeholders. Writing
WHERE email = '${email}'produces'$1', which is a string literal containing the characters$1. It is not a parameter. Leave the quotes out, because the driver handles types. - Expecting
undefinedto mean "no filter". A missing value is usually sent asNULL. Sinceemail = NULLis never true, the query quietly returns no rows. Build optional conditions as fragments instead. - Logging
textand assuming it is the query. The text alone is not the query. For debugging, logtextandvaluestogether.
Several production libraries follow this design, including postgres (postgres.js), slonik, sql-template-strings, and Prisma's $queryRaw. If you know the { text, values } model, you can understand how each of them works.
Exercise
Using the composable sql and compile from this chapter, what does compile(sql\SELECT * FROM t WHERE a = ${1} AND ${sql\b = ${2} OR c = ${3}\}\) return, and why does $3 refer to the value 3?
Show answer
It returns { text: 'SELECT * FROM t WHERE a = $1 AND b = $2 OR c = $3', values: [1, 2, 3] }. Placeholder numbers come from params.length after each push, not from the per-fragment index i, so numbering continues through the nested fragment in the order the values are visited.
Exercise
A teammate writes db.query(sql(\DELETE FROM sessions WHERE token = ${token}\)) with the basic { text, values } tag. What reaches the database, and what one-line check inside the tag would catch the bug?
Show answer
The parentheses make an untagged template literal evaluate first, so the tag receives one finished string and no values. reduce returns that string unchanged, so the token is spliced into the SQL and can inject. Adding if (!Array.isArray(strings?.raw)) throw new TypeError('sql must be used as a tag'); at the top of the tag rejects plain strings.
Exercise
Why can't you write sql\SELECT * FROM users ORDER BY ${sortColumn}\`` to let the user pick the sort column, and what is the safe alternative?
Show answer
Placeholders bind values, not identifiers, so the database would sort by a constant string, or reject the query, instead of by a column. The safe approach checks the column name against an allowlist and inserts it as a value-free fragment, like the column() helper in this chapter.