Skip to curriculum
Jump to the editor

24.6. A chainable SQL query builder

Medium
Topics

This question is in

24. Build a small library
30–45 min

Building 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

JAVASCRIPT
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

  1. 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.
  2. 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 an Error with the message Invalid identifier: <name>, as soon as it is passed in (query, select, where, orderBy).
  3. select adds columns to the list, in order; with no select, the list is *.
  4. where adds a condition "<column>" <op> $<n>; several conditions are joined with AND. Each value goes into values, and $n is its position there (from $1). like is written LIKE.
  5. in takes a non-empty array and writes "<column>" IN ($a, $b, …), one placeholder per item. Anything else throws an Error with the message in needs a non-empty array.
  6. A null value with = writes "<column>" IS NULL, and with != writes "<column>" IS NOT NULL, with no placeholder. With any other operator it throws null only works with = and !=.
  7. An undefined value throws Missing value for "<column>". An operator not in the list throws Unknown operator: <op>.
  8. Values are passed through unchanged (a Date stays the same object). Values never appear in the text.
  9. orderBy writes "<column>" ASC or "<column>" DESC; several are joined with , . Any other direction throws Invalid direction: <direction>.
  10. limit(n) and offset(n) take a non-negative integer (0 included), written into the text; the last call wins. Anything else throws a RangeError with the message limit must be a non-negative integer (or offset …).
  11. 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 in afterwards does not change the query.
  12. toSQL can be called any number of times; each call returns a new values array.

Examples

JAVASCRIPT
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"] }
JAVASCRIPT
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: [] }
JAVASCRIPT
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 users

Environment

  • Plain JavaScript in a browser page; the tests call the global query from query.js. Nothing is sent to a database.
  • OR, joins, GROUP BY, INSERT and UPDATE, and dotted names like users.id are out of scope.

Hints

  1. Placeholders are numbered by position in values. When is the right moment to give a value its number: when where is called, or when toSQL runs? Think of a base query reused by two others.
  2. 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
Back to the question
Loading the editor…