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
The design for v5, recorded 2026-10-15 so that whoever builds it has the details. Decided by the maintainer: the tag ships with 5.0. It is synchronous by default, with .async beside it. A ${} is never pasted into the SQL text. The string forms alasql(sql, params) and alasql.promise(sql, params) stay. The code of #1512 pastes values and collapses whitespace, which alters string literals, so it cannot be the base. The thread, the test file and this issue are the base, and the people who opened and pushed #1512 are credited on what lands.
The rule: never pasted
There are two things a tag can do with a ${}.
Paste it into the SQL text. The query becomes … WHERE age > 18 and is parsed with the value inside it. This is what Calling parser with backtick #1512's code does, and what an ordinary template string does.
Keep it outside the text and hand it to the query as data. The query text stays … WHERE age > ?, and 18 travels beside it. This is what alasql('… WHERE age > ?', [18]) does today. "Bound value" and "parameter" are the names for this.
Position: alasql never pastes. A ${} never becomes SQL text. Three reasons:
Safety. A pasted value can change the query. ${name} holding x' OR '1'='1 is the classic injection. A value that is handed over as data cannot.
Speed. If nothing is pasted, the text of a call site never changes, so it is parsed and compiled once (see the cache below). If values are pasted, every new value is a new query to parse: 140 µs instead of 1 µs.
Precompile. A build tool can only compile a query ahead of time if its text is fixed.
This is the rule every library that ships this feature has. What it means in each is under "What others are doing".
Do I write quotes? Where the ${} stands decides what it is
No quotes are needed. The value arrives as the JavaScript value it is: a string is a string, a number a number, an array a table. alasql does not have to guess a type from text.
alasql`SELECT a FROM b WHERE ${eur} = region`// right: eur is compared as the value it is
People will write '${eur}' out of habit, and telling them to wrap things is cumbersome. alasql has an advantage the other libraries do not: alasql owns its parser. The Postgres libraries send text to a server and cannot know that a placeholder sits inside quotes; postgres.js documents the trap ("If you wrap that in a string, Postgres will see '$1' and interpret it as a string as opposed to a parameter"). alasql knows its own syntax, so it can see exactly where each hole stands and give it a meaning that is both what the user expects and still not pasted.
Written as
Meaning
How
WHERE region = ${eur}
the value as it is
a parameter
WHERE region = '${eur}' or "${eur}"
the value as a string
still a parameter, converted to a string
WHERE name LIKE '%${term}%'
a string built from text and a value
rewritten to ('%' + ? + '%') before parsing: the value is still a parameter
FROM ${rows}, JOIN ${other}
the array is the table
a parameter (works today as FROM ?)
INTO ${target}, INTO CSV(${path})
target array, or an argument to an output function
a parameter (works today)
ORDER BY [${column}] or `${column}`
a column or table name
the name is escaped by alasql and the statement is cached per name
IN (${list})
each element of the array
should expand; today IN (?) with an array matches nothing (measured), IN @(?) works
${fn}(age)
a JavaScript function used in the query
later; today ?(col) is a parse error
So the quotes and brackets the user writes anyway are the markers. No ~, no :, no wrapper for the ordinary cases.
Does the parser still get valid SQL? Is this a change to the parser? The parser gets ordinary, valid SQL with ? in it, the same as today, and it is not changed. What is needed is a scanner in front of the parser:
Walk the fixed text pieces once per call site, keeping track of one thing: am I in plain SQL, inside '…', inside "…", inside […], or inside a comment.
At each hole, look at that state. In plain SQL, write ?. Inside quotes, close the quote, write + ? +, open it again, and put brackets around the whole: '%${term}%' becomes ('%' + ? + '%'). Inside […], the value is a name: check it, put it in the text, and keep one compiled statement per name. Inside a comment, throw.
Hand the resulting text to alasql.compile as today.
So it is the existing ? used in more places, plus a rewrite of quoted holes into a concatenation the parser already understands. The meaning of each hole is still fixed by the text around it, so the cache and precompile are unaffected.
This was built to check that it is real: a prototype of about 125 lines on the public 4.x API (below, folded), the scanner about 60 of them. Measured with it on v4.20.0:
Query
Result
WHERE city = ${city} AND age > ${min}
correct rows
WHERE city = '${city}'
correct rows
WHERE name LIKE '%${term}%' (with a doubled quote earlier in the text)
correct rows
SELECT [${col}] … ORDER BY [${col}], and the same call site with another name
correct, one statement per name
WHERE name = '${"x' OR 1=1 --"}'
no rows: the value stays a value
a name holding age] FROM x; DROP TABLE y; --
refused
a ${} inside /* … */
refused
a ? inside a string literal
stays text
Timing, the same 10-row query as in the cache table below: alasql(sql, params) 1,768 ns, the tag with bare holes 827 ns, the tag with a quoted hole and a name hole 1,099 ns.
What the prototype does not settle, for whoever builds the real one:
The scanner must agree exactly with alasql's lexer about where a string, a bracket name and a comment begin and end. Brackets are the delicate one, because [ also appears in @[1, 2] arrays and in ->[0] access. A test that feeds the same texts to both and compares is the guard. It is also a reason to settle the backslash rule first (Fix backslash escape handling in SQL string literals with performance optimization #2335), since \' changes where a string ends.
A hole inside quotes is turned into a string with String(value); what null and objects should give there needs a decision.
A name hole makes the SQL differ per name, so such a call site cannot be precompiled as one statement.
Should this be in the parser instead? Or a parser of its own for the tag? A scanner of its own means two pieces of code that must agree on where a string ends. A later finding removes most of that risk: alasql's own lexer can be the scanner.
The generated parser exposes its lexer (alasql.parser.lexer), and it can be run on its own. Join the fixed pieces with a marker character that cannot occur in SQL (a private-use character such as U+E000), lex the text once, and look at which token each marker lands in. Measured on v4.20.0:
Text given to the lexer (◆ is the marker)
Token the marker lands in
Meaning
WHERE e = ◆
a token of its own (the lexer does not know the character)
plain SQL: a parameter
LIKE '%◆%'
STRING'%◆%'
inside quotes: rewrite to a concatenation
SELECT [x◆]
BRALITERAL[x◆]
a name
@[1, ◆]
a token of its own, after ATLBRA
plain SQL: the array brackets are not mistaken for a name
-- ◆
gone: the lexer drops the comment
a hole in a comment: refuse
So the classification comes from the same rules that later parse the statement, and they cannot disagree. Nothing in the grammar changes. Block comments /* */ are removed before the lexer by alasql.utils.uncomment, so that function is the second place to ask. The scanner of the prototype becomes about twenty lines of "lex, then look up each marker". This is a finding for whoever builds it, not a decision.
A separate parser for the tag is the option to avoid: two grammars for one language, which is the same disagreement problem made permanent.
What is left for an explicit wrapper is only SQL syntax that is itself dynamic, which is rare:
alasql`SELECT * FROM ${rows}${alasql.raw(extraClause)}`// a whole clause from a trusted string
alasql.raw() is not what people use for values. For color = '${selectedColor}' nobody needs it: that works as written, and so does color = ${selectedColor}. raw exists so that the one dangerous thing, pasting text, has a name that can be searched for in a code review.
sql is not raw. Two names came up that are easy to mix up.
sql is the tag itself under a second name: import { sql } from 'alasql' and then sql`SELECT …` is exactly alasql`SELECT …`. It runs the query, and every ${} is a parameter. The only reason for the second name is that editors colour and format SQL inside a template when the tag is called sql.
alasql.raw(text) is not a tag and runs nothing. It wraps a string so that, placed in a ${}, it is pasted into the SQL text. It is the one exception to "never pasted", and it has to be asked for by name.
Two things the tag must check, once per call site:
A ${} in a comment: an error, since it would silently be dropped.
A fixed piece that already contains a ?: an error, as in Node's SQLite tag store ("do not add parameter binding placeholders to the SQL query string itself").
One layer of escaping
The tag can read the text exactly as typed (strings.raw). '\d+' reaches the lexer as '\d+', not as 'd+'. Measured: for 'C:\users' JavaScript's own interpretation is undefined (an invalid \u escape) while the raw text is intact, so raw is the only correct choice. Together with standard string literals in v5 (a backslash is an ordinary character; escapes move to E'…', see #2335), a backslash in a tagged query is a backslash, with nothing to double. One wrinkle: a backtick inside the template has to be written \`, so brackets are the comfortable identifier quote in this form.
The cache, and what a WeakMap is
A Map is a lookup table from keys to values. A WeakMap is the same, with two differences: its keys are objects, and an entry disappears by itself when nothing else holds the key object any more. It never needs clearing and cannot grow without bound.
Does an entry disappear when the code leaves the scope that held the object? For a WeakMap in general, yes: once no variable anywhere refers to the key object, the entry can be collected. For this cache there is a detail. The key is the array of fixed pieces, and JavaScript itself keeps that array for as long as the piece of source code that contains the template is loaded. A function returning does not drop it; the next call of the same line gets the same array. So in practice the cache holds one entry per tagged query written in the program, for the life of the program, and entries go away only when the code itself is unloaded (a module that is discarded, code made with eval). The size of the cache is bounded by the size of the source, not by the data or the number of calls.
JavaScript guarantees that the array of fixed pieces is the same object every time one call site runs (measured: three passes through one call site, one object). So that array can be the key:
constcache=newWeakMap();functiontag(strings, ...values){letstatement=cache.get(strings);// "have I seen this call site?"if(!statement)cache.set(strings,statement=compile(strings));returnstatement(values);}
Is that not hashing inside? It is, but of a different thing. Today's cache computes a hash of the SQL text on every call: a loop over every character of the query, plus a string concatenation for the joinstar option. A WeakMap looks the object up by its identity, which costs the same for a 20-character query and a 2,000-character one.
Measured (a 10-row source with WHERE and ORDER BY, median of five runs, indicative):
Form
Per call
alasql(sql, params), cache on
1,686 ns
alasql.compile(sql) once, then fn(params)
997 ns
tag with a WeakMap call-site cache (prototype)
830 ns
alasql(sql, params), cache off
139,308 ns
Today's string cache has a collision fault: #2587. The call-site cache cannot have it, because identity does not collide.
What it returns
Decided: the plain tag is synchronous. That also follows from the positioning in "The next twelve years": alasql is the engine that answers at once over values the program already holds.
The design that gives "choose your default and still reach the other":
alasql.sync and alasql.async are two views of the same engine. Each is the whole of alasql, callable as a tag and as a function. Each has .sync and .async on it, so the other is always one word away.
The default export is the sync view.
The same two views exist on a database object.
importalasqlfrom'alasql';constrows=alasql`SELECT name FROM ${people} WHERE age > ${18}`;// rows, at onceconstmore=awaitalasql.async`SELECT * FROM CSV(${url})`;// a promise
importafrom'alasql';constalasql=a.async;// my default is asyncconstrows=awaitalasql`SELECT name FROM ${people} WHERE age > ${18}`;constn=alasql.sync`SELECT VALUE COUNT(*) FROM ${people}`;// the other is still here
constdb=newalasql.Database().async;awaitdb`INSERT INTO orders SELECT * FROM ${rows}`;console.log(db.sync`SELECT * FROM orders WHERE total > ${100}`);
Details that follow from this:
A promise, so .then() works.alasql.async`…`.then(rows => render(rows)).
A sync query with an asynchronous source (a file, IndexedDB, a URL) throws, with a message that says to use .async. Today it returns undefined.
alasql.async(sql, params) is then the same thing as alasql.promise(sql, params); the old name stays as an alias.
Result shapes are tag names beside the plain one, replacing the VALUE OF / ROW OF / COLUMN OF / MATRIX OF prefixes with something a type checker and a build tool can see: alasql.value`…` , alasql.row`…` , alasql.column`…` , alasql.matrix`…` , and the same on .async. Node's SQLite tag store does this with sql.get, sql.all, sql.run.
A tag bound to a database runs against that database without the global USE.
Not lazy. postgres.js and Bun return an object that does nothing until awaited. For alasql, alasql`CREATE TABLE t (a INT)`; on a line of its own must run.
The names sync, async, value, row, column, matrix, raw are free on the alasql object today (checked).
Fragments are for later (5.1). A fragment is a piece of a query that is kept in a variable and put into other queries. It does not run by itself:
constminAge=18;constadults=alasql.fragment`age >= ${minAge}`;// a piece of a WHERE clause; nothing runs herealasql`SELECT * FROM ${people} WHERE ${adults}`;alasql`SELECT COUNT(*) FROM ${staff} WHERE ${adults}`;
The value (minAge) is in the fragment because the fragment needs it: "age at least this". The fragment carries its text and its value together, so the value is still handed over as data when the fragment is used.
The string forms. "String form" means calling alasql the way everyone does today, with the SQL as an ordinary string argument: alasql('SELECT * FROM ? WHERE a > ?', [rows, 1]) and alasql.promise(sql, params). The "tag form" is the backtick call. The string forms stay, for backward compatibility, and move to second place in the documentation.
TypeScript.alasql<User[]>`…` is valid and enough for hand-written types. TypeScript does not show the text of a tagged template to the type system, so types cannot be derived from the SQL through the tag; that needs a build step.
The prerequisite: statements that can run twice at once
The tag keeps one compiled statement per call site and makes the async form ordinary, so await Promise.all(ids.map(id => alasql.async`… ${id} …`)) becomes everyday code. Today that breaks when the SQL text is the same: #1953, with three reproductions and a three-step proposal in its latest comment. It must be fixed first. The dbversion check that exists for cached statements must apply to the call-site cache too.
When to build it
Not as an afterthought, and not before everything else either. Three moves:
Now, outside the core. A prototype of the tag on top of the public 4.x API exists (below). It touches nothing in the engine and handles bare holes, holes in quotes and names in brackets. Its purpose is to be used for a while to settle the ergonomics: the views, the shape names, how quotes feel.
First in the 5.0 work, straight after the two things it depends on: re-entrant statements, and the string-literal grammar change (the scanner has to agree with the lexer on where a string ends, so the backslash rule comes first). Before the dialect and function work, not after.
Then write the new 5.0 tests in the tag form. Dialect modules and behaviour modules need hundreds of new tests. If they are written with the tag, the tag is exercised by all of them before release, without anyone writing "tag tests".
Why early: it is the headline, so it needs the longest time in use. It forces the two riskiest pieces (re-entrancy, grammar) to the front. And features designed after it (iterables, INTO) should be designed in its terms.
Precompiling tagged queries at build time is #2592. It depends on the rule above: what a tagged call does is decided by the fixed text and by where each ${} stands, never by looking inside a value.
What others are doing
The rule they share: a ${} is sent as a parameter, not pasted. What each did with it, and what went well and badly. The quotations are from each project's own documentation, read for this design.
Library
What it looks like
Good
Not so good
postgres.js
await sql`select * from users where age > ${age}`
One function does everything: sql(column) for a name, sql([1, 2, 3]) for an IN list, sql(object) for an insert, a nested sql`…` for a fragment. Very little to learn.
Quotes break it, and the README has to warn: "If you wrap that in a string, Postgres will see '$1' and interpret it as a string as opposed to a parameter." Queries are lazy ("first executed when awaited"), so a statement that is not awaited does nothing. sql.unsafe is the paste escape hatch, and its name does not stop people.
Bun sql
The postgres.js design, built into the runtime
Shows the design became a platform convention. Same helpers.
Same laziness ("will only start executing when awaited or executed with .execute()").
Node node:sqlite (v24.9)
const sql = db.createTagStore(); sql.get`SELECT * FROM users WHERE name = ${name}`
Synchronous. The result shape is the tag's name: sql.get, sql.all, sql.run, sql.iterate. The tag is the front of a cache of prepared statements. In Node itself.
The cache is keyed on the query text, an LRU of 1,000, not on the call site. No way to interpolate a name or a fragment at all: "The only way of binding parameters in tagged statements is with the ${value} syntax."
PGlite
await pg.sql`SELECT * FROM test WHERE name = ${'test'}`
The tag lives on the database object. Clear helper names: identifier`test`, raw`WHERE 1=1`, nested sql`…`. A query tag that returns the text and parameters without running, for inspection.
Four imports to learn for anything dynamic.
Slonik
pool.query(sql.type(schema)`SELECT id FROM person WHERE name = ${name}`)
Strictness as the product: a plain string is refused ("Query must be constructed using sql tagged template literal"). A schema on the tag gives typed, validated rows.
A large vocabulary: sql.fragment, sql.identifier, sql.join, sql.array, sql.unnest, sql.literalValue, and more. Too heavy for a library whose users want one line.
Drizzle, Kysely
Typed query builders with a sql tag for what the builder cannot express
Named placeholders for statements prepared once and run with different arguments.
The tag is the back door, not the front. Not a model for alasql.
Prisma
prisma.$queryRaw`SELECT …` , and TypedSQL: .sql files turned into typed functions at build time
Evidence that types come from a build step, not from the tag.
Two systems side by side.
lit-html (not SQL)
html`<p>${text}</p>`
Caches its templates by the identity of the pieces array. The cache above is this trick.
DuckDB (not a tag)
In Python, a query can name a local dataframe variable
Data as an operand of the query, which is alasql's own strength. Also a source of friendlier SQL to copy later: FROM-first, GROUP BY ALL, SELECT * EXCLUDE.
What alasql takes: the shared rule; shape as tag name and synchronous use from Node; the tag on the database object from PGlite; one small vocabulary rather than Slonik's. What alasql does better than all of them, because the parser is its own: quotes that work, and data as a first-class operand.
The prototype (v4.x public API, about 125 lines)
// Prototype for #1723. Not part of the build.// Run from the repository root after a build: node tag-prototype.js//// Position-aware tagged template on the public 4.x API.// No grammar change. A scanner walks the fixed text pieces and notes// where each hole stands. The parser only ever sees ordinary SQL with `?`.constalasql=require('./dist/alasql.js');constCODE=0,SQ=1,DQ=2,BR=3,LINE=4,BLOCK=5;functionscan(raw){// returns {parts: [...], holes: [{kind:'value'|'string'|'name'}]}letstate=CODE;letout='';letlitStart=-1;// index in `out` where the current string literal openedletlitHasHole=false;constholes=[];constsegments=[];// sql text split at each name holefor(lets=0;s<raw.length;s++){constt=raw[s];for(leti=0;i<t.length;i++){constc=t[i],n=t[i+1];if(state===CODE){if(c==="'"){state=SQ;litStart=out.length;litHasHole=false;}elseif(c==='"'){state=DQ;litStart=out.length;litHasHole=false;}elseif(c==='[')state=BR;elseif(c==='-'&&n==='-')state=LINE;elseif(c==='/'&&n==='*')state=BLOCK;out+=c;}elseif(state===SQ||state===DQ){constq=state===SQ ? "'" : '"';out+=c;if(c===q){if(n===q){out+=n;i++;}// doubled quote stays insideelse{if(litHasHole){out=out.slice(0,litStart)+'('+out.slice(litStart)+')';}state=CODE;}}}elseif(state===BR){out+=c;if(c===']')state=CODE;}elseif(state===LINE){out+=c;if(c==='\n')state=CODE;}elseif(state===BLOCK){out+=c;if(c==='*'&&n==='/'){out+=n;i++;state=CODE;}}}if(s===raw.length-1)break;// a holeif(state===CODE){out+='?';holes.push('value');}elseif(state===SQ||state===DQ){constq=state===SQ ? "'" : '"';out+=q+' + ? + '+q;litHasHole=true;holes.push('string');}elseif(state===BR){segments.push(out);out='';litStart=-1;holes.push('name');}elsethrownewError('A ${} cannot stand inside a comment');}if(state===SQ||state===DQ||state===BR)thrownewError('Unclosed quote or bracket in the query text');segments.push(out);return{ segments, holes };}constsites=newWeakMap();functiontag(strings, ...values){letsite=sites.get(strings);if(!site){site=scan(strings.raw);site.hasNames=site.holes.includes('name');site.byNames=newMap();sites.set(strings,site);}constparams=[];letkey='';constnames=[];for(leti=0;i<values.length;i++){constkind=site.holes[i],v=values[i];if(kind==='name'){if(typeofv!=='string'||v.includes(']'))thrownewError('A name in [${}] must be a string without "]"');names.push(v);key+=v+']';}elseif(kind==='string')params.push(v==null ? '' : String(v));elseparams.push(v);}letst=site.byNames.get(key);if(!st){letsql=site.segments[0];for(leti=0;i<names.length;i++)sql+=names[i]+site.segments[i+1];st=alasql.compile(sql);st.sqlText=sql;site.byNames.set(key,st);}returnst(params);}tag.show=(strings)=>scan(strings.raw);module.exports=tag;if(require.main===module){constsql=tag;constpeople=[{name: 'Ann',age: 31,city: 'Oslo'},{name: "O'Brien",age: 25,city: 'Cork'},{name: 'Bo',age: 19,city: 'Oslo'},];constj=(x)=>JSON.stringify(x);construn=(label,f)=>{try{console.log(label.padEnd(46),'=>',j(f()));}catch(e){console.log(label.padEnd(46),'!!',e.message.slice(0,90));}};constcity='Oslo',term='O',col='age',evil="x' OR 1=1 --",min=20;run('bare value + table',()=>sql`SELECT COLUMN name FROM ${people} WHERE city = ${city} AND age > ${min}`);run("value inside quotes '${city}'",()=>sql`SELECT COLUMN name FROM ${people} WHERE city = '${city}'`);run("LIKE '${term}%'",()=>sql`SELECT COLUMN name FROM ${people} WHERE name LIKE '${term}%'`);run("LIKE '%${term}%' with a doubled quote before",()=>sql`SELECT COLUMN name FROM ${people} WHERE 'it''s' = 'it''s' AND name LIKE '%${'ri'}%'`);run('name inside brackets [${col}]',()=>sql`SELECT COLUMN [${col}] FROM ${people} ORDER BY [${col}]`);run('same call site, other name',()=>{constf=(c)=>sql`SELECT COLUMN [${c}] FROM ${people}`;return[f('name'),f('city')];});run('value with a quote in it, bare',()=>sql`SELECT COLUMN name FROM ${people} WHERE name = ${"O'Brien"}`);run('value with a quote in it, in quotes',()=>sql`SELECT COLUMN name FROM ${people} WHERE name = '${"O'Brien"}'`);run('injection attempt in quotes',()=>sql`SELECT COLUMN name FROM ${people} WHERE name = '${evil}'`);run('injection attempt bare',()=>sql`SELECT COLUMN name FROM ${people} WHERE name = ${evil}`);run('injection attempt as a name',()=>sql`SELECT COLUMN [${'age] FROM x; DROP TABLE y; --'}] FROM ${people}`);run('hole inside a comment',()=>sql`SELECT 1 /* ${city} */`);run('question mark inside a string is text',()=>sql`SELECT VALUE 'why? ${city}'`);console.log('\nWhat the parser is given for name LIKE \'%${term}%\' AND [${col}] > ${min}:');constshown=tag.show`SELECT * FROM ${people} WHERE name LIKE '%${term}%' AND [${col}] > ${min}`;console.log(' text pieces:',j(shown.segments),'\n holes:',j(shown.holes));// timingconstdata=[];for(leti=0;i<10;i++)data.push({name: 'n'+i,age: 18+i,city: i%2 ? 'A' : 'B'});consttime=(label,f)=>{for(leti=0;i<20000;i++)f();constN=200000;consts=process.hrtime.bigint();for(leti=0;i<N;i++)f();constns=Number(process.hrtime.bigint()-s)/N;console.log(label.padEnd(46),ns.toFixed(0),'ns');};console.log();time('alasql(sql, params)',()=>alasql('SELECT name, age FROM ? WHERE age > ? AND city = ? ORDER BY age DESC',[data,23,'A']));time('tag, bare holes',()=>sql`SELECT name, age FROM ${data} WHERE age > ${23} AND city = ${'A'} ORDER BY age DESC`);time("tag, quoted hole + name hole",()=>sql`SELECT name, [${'age'}] FROM ${data} WHERE age > ${23} AND city = '${'A'}' ORDER BY age DESC`);}
Activity
mathiasrw commentedon Oct 14, 2026
The design for v5, recorded 2026-10-15 so that whoever builds it has the details. Decided by the maintainer: the tag ships with 5.0. It is synchronous by default, with
.asyncbeside it. A${}is never pasted into the SQL text. The string formsalasql(sql, params)andalasql.promise(sql, params)stay. The code of #1512 pastes values and collapses whitespace, which alters string literals, so it cannot be the base. The thread, the test file and this issue are the base, and the people who opened and pushed #1512 are credited on what lands.The rule: never pasted
There are two things a tag can do with a
${}.… WHERE age > 18and is parsed with the value inside it. This is what Calling parser with backtick #1512's code does, and what an ordinary template string does.… WHERE age > ?, and18travels beside it. This is whatalasql('… WHERE age > ?', [18])does today. "Bound value" and "parameter" are the names for this.Position: alasql never pastes. A
${}never becomes SQL text. Three reasons:${name}holdingx' OR '1'='1is the classic injection. A value that is handed over as data cannot.This is the rule every library that ships this feature has. What it means in each is under "What others are doing".
Do I write quotes? Where the
${}stands decides what it isNo quotes are needed. The value arrives as the JavaScript value it is: a string is a string, a number a number, an array a table. alasql does not have to guess a type from text.
People will write
'${eur}'out of habit, and telling them to wrap things is cumbersome. alasql has an advantage the other libraries do not: alasql owns its parser. The Postgres libraries send text to a server and cannot know that a placeholder sits inside quotes; postgres.js documents the trap ("If you wrap that in a string, Postgres will see'$1'and interpret it as a string as opposed to a parameter"). alasql knows its own syntax, so it can see exactly where each hole stands and give it a meaning that is both what the user expects and still not pasted.WHERE region = ${eur}WHERE region = '${eur}'or"${eur}"WHERE name LIKE '%${term}%'('%' + ? + '%')before parsing: the value is still a parameterFROM ${rows},JOIN ${other}FROM ?)INTO ${target},INTO CSV(${path})ORDER BY [${column}]or`${column}`IN (${list})IN (?)with an array matches nothing (measured),IN @(?)works${fn}(age)?(col)is a parse errorSo the quotes and brackets the user writes anyway are the markers. No
~, no:, no wrapper for the ordinary cases.Does the parser still get valid SQL? Is this a change to the parser? The parser gets ordinary, valid SQL with
?in it, the same as today, and it is not changed. What is needed is a scanner in front of the parser:'…', inside"…", inside[…], or inside a comment.?. Inside quotes, close the quote, write+ ? +, open it again, and put brackets around the whole:'%${term}%'becomes('%' + ? + '%'). Inside[…], the value is a name: check it, put it in the text, and keep one compiled statement per name. Inside a comment, throw.alasql.compileas today.So it is the existing
?used in more places, plus a rewrite of quoted holes into a concatenation the parser already understands. The meaning of each hole is still fixed by the text around it, so the cache and precompile are unaffected.This was built to check that it is real: a prototype of about 125 lines on the public 4.x API (below, folded), the scanner about 60 of them. Measured with it on v4.20.0:
WHERE city = ${city} AND age > ${min}WHERE city = '${city}'WHERE name LIKE '%${term}%'(with a doubled quote earlier in the text)SELECT [${col}] … ORDER BY [${col}], and the same call site with another nameWHERE name = '${"x' OR 1=1 --"}'age] FROM x; DROP TABLE y; --${}inside/* … */?inside a string literalTiming, the same 10-row query as in the cache table below:
alasql(sql, params)1,768 ns, the tag with bare holes 827 ns, the tag with a quoted hole and a name hole 1,099 ns.What the prototype does not settle, for whoever builds the real one:
[also appears in@[1, 2]arrays and in->[0]access. A test that feeds the same texts to both and compares is the guard. It is also a reason to settle the backslash rule first (Fix backslash escape handling in SQL string literals with performance optimization #2335), since\'changes where a string ends.String(value); whatnulland objects should give there needs a decision.Should this be in the parser instead? Or a parser of its own for the tag? A scanner of its own means two pieces of code that must agree on where a string ends. A later finding removes most of that risk: alasql's own lexer can be the scanner.
The generated parser exposes its lexer (
alasql.parser.lexer), and it can be run on its own. Join the fixed pieces with a marker character that cannot occur in SQL (a private-use character such asU+E000), lex the text once, and look at which token each marker lands in. Measured on v4.20.0:WHERE e = ◆LIKE '%◆%'STRING'%◆%'SELECT [x◆]BRALITERAL[x◆]@[1, ◆]ATLBRA-- ◆So the classification comes from the same rules that later parse the statement, and they cannot disagree. Nothing in the grammar changes. Block comments
/* */are removed before the lexer byalasql.utils.uncomment, so that function is the second place to ask. The scanner of the prototype becomes about twenty lines of "lex, then look up each marker". This is a finding for whoever builds it, not a decision.A separate parser for the tag is the option to avoid: two grammars for one language, which is the same disagreement problem made permanent.
What is left for an explicit wrapper is only SQL syntax that is itself dynamic, which is rare:
alasql.raw()is not what people use for values. Forcolor = '${selectedColor}'nobody needs it: that works as written, and so doescolor = ${selectedColor}.rawexists so that the one dangerous thing, pasting text, has a name that can be searched for in a code review.sqlis notraw. Two names came up that are easy to mix up.sqlis the tag itself under a second name:import { sql } from 'alasql'and thensql`SELECT …`is exactlyalasql`SELECT …`. It runs the query, and every${}is a parameter. The only reason for the second name is that editors colour and format SQL inside a template when the tag is calledsql.alasql.raw(text)is not a tag and runs nothing. It wraps a string so that, placed in a${}, it is pasted into the SQL text. It is the one exception to "never pasted", and it has to be asked for by name.Two things the tag must check, once per call site:
${}in a comment: an error, since it would silently be dropped.?: an error, as in Node's SQLite tag store ("do not add parameter binding placeholders to the SQL query string itself").One layer of escaping
The tag can read the text exactly as typed (
strings.raw).'\d+'reaches the lexer as'\d+', not as'd+'. Measured: for'C:\users'JavaScript's own interpretation isundefined(an invalid\uescape) while the raw text is intact, so raw is the only correct choice. Together with standard string literals in v5 (a backslash is an ordinary character; escapes move toE'…', see #2335), a backslash in a tagged query is a backslash, with nothing to double. One wrinkle: a backtick inside the template has to be written\`, so brackets are the comfortable identifier quote in this form.The cache, and what a WeakMap is
A
Mapis a lookup table from keys to values. AWeakMapis the same, with two differences: its keys are objects, and an entry disappears by itself when nothing else holds the key object any more. It never needs clearing and cannot grow without bound.Does an entry disappear when the code leaves the scope that held the object? For a WeakMap in general, yes: once no variable anywhere refers to the key object, the entry can be collected. For this cache there is a detail. The key is the array of fixed pieces, and JavaScript itself keeps that array for as long as the piece of source code that contains the template is loaded. A function returning does not drop it; the next call of the same line gets the same array. So in practice the cache holds one entry per tagged query written in the program, for the life of the program, and entries go away only when the code itself is unloaded (a module that is discarded, code made with
eval). The size of the cache is bounded by the size of the source, not by the data or the number of calls.JavaScript guarantees that the array of fixed pieces is the same object every time one call site runs (measured: three passes through one call site, one object). So that array can be the key:
Is that not hashing inside? It is, but of a different thing. Today's cache computes a hash of the SQL text on every call: a loop over every character of the query, plus a string concatenation for the
joinstaroption. A WeakMap looks the object up by its identity, which costs the same for a 20-character query and a 2,000-character one.Measured (a 10-row source with WHERE and ORDER BY, median of five runs, indicative):
alasql(sql, params), cache onalasql.compile(sql)once, thenfn(params)alasql(sql, params), cache offToday's string cache has a collision fault: #2587. The call-site cache cannot have it, because identity does not collide.
What it returns
Decided: the plain tag is synchronous. That also follows from the positioning in "The next twelve years": alasql is the engine that answers at once over values the program already holds.
The design that gives "choose your default and still reach the other":
alasql.syncandalasql.asyncare two views of the same engine. Each is the whole of alasql, callable as a tag and as a function. Each has.syncand.asyncon it, so the other is always one word away.Details that follow from this:
.then()works.alasql.async`…`.then(rows => render(rows))..async. Today it returnsundefined.alasql.async(sql, params)is then the same thing asalasql.promise(sql, params); the old name stays as an alias.VALUE OF/ROW OF/COLUMN OF/MATRIX OFprefixes with something a type checker and a build tool can see:alasql.value`…`,alasql.row`…`,alasql.column`…`,alasql.matrix`…`, and the same on.async. Node's SQLite tag store does this withsql.get,sql.all,sql.run.USE.alasql`CREATE TABLE t (a INT)`;on a line of its own must run.sync,async,value,row,column,matrix,raware free on thealasqlobject today (checked).Fragments are for later (5.1). A fragment is a piece of a query that is kept in a variable and put into other queries. It does not run by itself:
The value (
minAge) is in the fragment because the fragment needs it: "age at least this". The fragment carries its text and its value together, so the value is still handed over as data when the fragment is used.The string forms. "String form" means calling alasql the way everyone does today, with the SQL as an ordinary string argument:
alasql('SELECT * FROM ? WHERE a > ?', [rows, 1])andalasql.promise(sql, params). The "tag form" is the backtick call. The string forms stay, for backward compatibility, and move to second place in the documentation.TypeScript.
alasql<User[]>`…`is valid and enough for hand-written types. TypeScript does not show the text of a tagged template to the type system, so types cannot be derived from the SQL through the tag; that needs a build step.The prerequisite: statements that can run twice at once
The tag keeps one compiled statement per call site and makes the async form ordinary, so
await Promise.all(ids.map(id => alasql.async`… ${id} …`))becomes everyday code. Today that breaks when the SQL text is the same: #1953, with three reproductions and a three-step proposal in its latest comment. It must be fixed first. Thedbversioncheck that exists for cached statements must apply to the call-site cache too.When to build it
Not as an afterthought, and not before everything else either. Three moves:
Why early: it is the headline, so it needs the longest time in use. It forces the two riskiest pieces (re-entrancy, grammar) to the front. And features designed after it (iterables,
INTO) should be designed in its terms.Precompiling tagged queries at build time is #2592. It depends on the rule above: what a tagged call does is decided by the fixed text and by where each
${}stands, never by looking inside a value.What others are doing
The rule they share: a
${}is sent as a parameter, not pasted. What each did with it, and what went well and badly. The quotations are from each project's own documentation, read for this design.await sql`select * from users where age > ${age}`sql(column)for a name,sql([1, 2, 3])for anINlist,sql(object)for an insert, a nestedsql`…`for a fragment. Very little to learn.'$1'and interpret it as a string as opposed to a parameter." Queries are lazy ("first executed when awaited"), so a statement that is not awaited does nothing.sql.unsafeis the paste escape hatch, and its name does not stop people.sql.execute()").node:sqlite(v24.9)const sql = db.createTagStore(); sql.get`SELECT * FROM users WHERE name = ${name}`sql.get,sql.all,sql.run,sql.iterate. The tag is the front of a cache of prepared statements. In Node itself.${value}syntax."await pg.sql`SELECT * FROM test WHERE name = ${'test'}`identifier`test`,raw`WHERE 1=1`, nestedsql`…`. Aquerytag that returns the text and parameters without running, for inspection.pool.query(sql.type(schema)`SELECT id FROM person WHERE name = ${name}`)sqltagged template literal"). A schema on the tag gives typed, validated rows.sql.fragment,sql.identifier,sql.join,sql.array,sql.unnest,sql.literalValue, and more. Too heavy for a library whose users want one line.sqltag for what the builder cannot expressprisma.$queryRaw`SELECT …`, and TypedSQL:.sqlfiles turned into typed functions at build timehtml`<p>${text}</p>`FROM-first,GROUP BY ALL,SELECT * EXCLUDE.What alasql takes: the shared rule; shape as tag name and synchronous use from Node; the tag on the database object from PGlite; one small vocabulary rather than Slonik's. What alasql does better than all of them, because the parser is its own: quotes that work, and data as a first-class operand.
The prototype (v4.x public API, about 125 lines)