24.6. A chainable SQL query builder
Topics
This question is in
24. Build a small libraryBuilding SQL by gluing strings together is how injection bugs are born: one name like x' OR '1'='1 typed into a search box, and the query means something else. A query builder avoids that. Each method adds one piece, values never enter the SQL text (they travel separately, as numbered placeholders $1, $2…), and table and column names are checked before they are quoted. Because each method returns a new builder, a base query can be reused safely.
Write query(table) in query.js. It returns a builder whose methods chain, and toSQL() turns it into SQL text and its values.
Signature
function query(table) // returns a builder
builder.select(...columns)
builder.where(column, op, value) // op: "=", "!=", "<", "<=", ">", ">=", "in", "like"
builder.orderBy(column, direction) // "asc" (default) or "desc", any case
builder.limit(n)
builder.offset(n)
builder.toSQL() // returns { text, values }Every method except toSQL returns a new builder.
Requirements
- The text is
SELECT <columns> FROM <table>, then, when set,WHERE …,ORDER BY …,LIMIT n,OFFSET n, separated by single spaces, always in that order whatever order the methods were called in. - Table and column names are written in double quotes. A name must be a string of letters, digits and
_that does not start with a digit; any other name throws anErrorwith the messageInvalid identifier: <name>, as soon as it is passed in (query,select,where,orderBy). selectadds columns to the list, in order; with noselect, the list is*.whereadds a condition"<column>" <op> $<n>; several conditions are joined withAND. Each value goes intovalues, and$nis its position there (from$1).likeis writtenLIKE.intakes a non-empty array and writes"<column>" IN ($a, $b, …), one placeholder per item. Anything else throws anErrorwith the messagein needs a non-empty array.- A
nullvalue with=writes"<column>" IS NULL, and with!=writes"<column>" IS NOT NULL, with no placeholder. With any other operator it throwsnull only works with = and !=. - An
undefinedvalue throwsMissing value for "<column>". An operator not in the list throwsUnknown operator: <op>. - Values are passed through unchanged (a
Datestays the same object). Values never appear in the text. orderBywrites"<column>" ASCor"<column>" DESC; several are joined with,. Any other direction throwsInvalid direction: <direction>.limit(n)andoffset(n)take a non-negative integer (0included), written into the text; the last call wins. Anything else throws aRangeErrorwith the messagelimit must be a non-negative integer(oroffset …).- A builder never changes after it is made: calling a method on it returns a new builder and leaves the old one as it was. Changing an array passed to
inafterwards does not change the query. toSQLcan be called any number of times; each call returns a newvaluesarray.
Examples
query("users")
.select("id", "name")
.where("age", ">=", 18)
.where("role", "in", ["admin", "editor"])
.orderBy("name")
.limit(10)
.toSQL();
// { text: 'SELECT "id", "name" FROM "users" WHERE "age" >= $1 AND "role" IN ($2, $3) ORDER BY "name" ASC LIMIT 10',
// values: [18, "admin", "editor"] }const active = query("users").where("deleted_at", "=", null);
const page2 = active.orderBy("id", "DESC").limit(20).offset(20);
active.toSQL(); // { text: 'SELECT * FROM "users" WHERE "deleted_at" IS NULL', values: [] }
page2.toSQL(); // { text: 'SELECT * FROM "users" WHERE "deleted_at" IS NULL ORDER BY "id" DESC LIMIT 20 OFFSET 20', values: [] }query("users").where("name", "=", "x' OR '1'='1").toSQL();
// { text: 'SELECT * FROM "users" WHERE "name" = $1', values: ["x' OR '1'='1"] }
query("users; DROP TABLE users"); // throws Error: Invalid identifier: users; DROP TABLE usersEnvironment
- Plain JavaScript in a browser page; the tests call the global
queryfromquery.js. Nothing is sent to a database. OR, joins,GROUP BY,INSERTandUPDATE, and dotted names likeusers.idare out of scope.
Hints
- Placeholders are numbered by position in
values. When is the right moment to give a value its number: whenwhereis called, or whentoSQLruns? Think of a base query reused by two others. - How can a method "add" a condition without changing the builder it was called on?
The explanation comes with the course
A walkthrough of every line of a solution, the mistakes the tests catch, other ways to write it, and links to the lessons that teach each idea.
- Every line explained
- The mistakes each test catches
- Links to the lessons behind it