Sub topic 3
Practical Pattern: Parameterized SQL Queries
This chapter assumes you already know how a tag receives strings and ...values, and how reduce interleaves them.
Returning a Query Object
A SQL tag should not paste values into the query text. It returns the text with numbered placeholders and keeps the values in a separate list, so the database driver can bind them safely:
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'] }Frozen Strings Arrays and Call-Site Caching
JavaScript creates the strings array once for each place in the source where the tag appears, then freezes it. A loop that runs the same call site reuses the same array:
const seen = new Set();
function tag(strings) { seen.add(strings); }
for (let i = 0; i < 3; i++) tag`item ${i}`;
console.log(seen.size); // 1
tag`item ${0}`;
console.log(seen.size); // 2
console.log(Object.isFrozen([...seen][0])); // trueLibraries use the array as a cache key, so they parse each template only once.
Member Tags, this, and Chained Tags
When the tag is written as obj.method, it is called as a method and this is obj. If a tag returns a function, you can chain a second template after it: ` taga`b ``.
const formatter = {
prefix: '[log] ',
tag(strings, ...values) {
return this.prefix + String.raw(strings, ...values);
},
};
console.log(formatter.tag`count=${3}`); // '[log] count=3'Invalid Escapes
An untagged ` \unicode is a SyntaxError. Since ES2018, a tagged template accepts it: the cooked string becomes undefined` and the raw string keeps the text. This lets DSLs such as LaTeX snippets contain backslashes freely.
const show = (s) => ({ cooked: s[0], raw: s.raw[0] });
console.log(show`\unicode`); // { cooked: undefined, raw: '\\unicode' }In the Ecosystem
| Library | Tag | Returns |
|---|---|---|
| styled-components | `` styled.div`...` `` | A React component |
| lit | `` html`...` `` | A TemplateResult cached by strings array |
| graphql-tag | `` gql`...` `` | A parsed GraphQL AST |
Typing in TypeScript
function upper(strings: TemplateStringsArray, ...values: unknown[]): string {
return strings.reduce(
(out, str, i) => out + String(values[i - 1]).toUpperCase() + str,
);
}TemplateStringsArray is a readonly string array with a readonly raw property.
Pitfalls
- A tag cannot make values safe on its own. Escaping or binding is your job.
- `
obj?.tagx` is a SyntaxError, because optional chaining cannot be combined with a tagged template. - Cooked strings may be
undefinedwhen a template contains an invalid escape. - A SQL tag can only parameterize values. Table and column names cannot be bound as placeholders.
Exercise
Why does seen.size stay at 1 after the loop runs tag three times?
Show answer
All three calls come from the same call site, so JavaScript passes the same frozen strings array each time, and the Set stores it only once.
Exercise
What does sql return for sqlDELETE FROM t WHERE x = ${5}?
Show answer
{ text: 'DELETE FROM t WHERE x = $1', values: [5] }