Skip to content

Capstone: a typed SQL query builder

Relay’s dashboard reads jobs, webhooks and sources with hand-written SQL. The query function is query(sql: string): Promise<any[]>. Last week someone wrote SELECT id, staus FROM jobs. It type-checked, the database returned no such column, and the dashboard showed a table of undefined. The row type was a guess typed by hand next to the query, and the two drifted apart.

The SQL string already contains everything the row type needs: which table, which columns, which aliases. In this lesson the compiler reads it. db.query("SELECT id, status FROM jobs WHERE source = ?", "github") gets rows of type { id: string; status: "queued" | ... }, a parameter list of [string], and an error naming the column if you misspell one. It uses what the last two lessons built: template-literal parsing from lesson 6, and the accumulator style that keeps recursion shallow from lesson 7.

SELECT <columns> FROM <table> [WHERE <column> = ? [AND <column> = ?]...]
<columns> = * | <column> [AS <alias>] [, <column> [AS <alias>]]...

Keywords are upper case, separators are single spaces, = is the only operator and every value is a ?. There are no joins, no quoting, no OR, no LIMIT. That is a deliberate cut. Each feature you add at the type level adds a parser branch, an error message and more checker time, and a SQL parser the size of a real one belongs in a build step, not in the type system. This grammar is enough to see every technique.

The schema is one interface, and everything else is derived from it:

interface Schema {
readonly jobs: { id: string; status: "queued" | "running" | "done" | "failed"; source: string; attempts: number }
readonly webhooks: { id: string; source: string; event: string; received_at: number }
readonly sources: { name: string; secret: string; enabled: boolean }
}
type Tables = { readonly [T in keyof Schema]: ReadonlyArray<Schema[T]> }
export const tables: Tables = {
jobs: [{ id: "j1", status: "queued", source: "github", attempts: 0 }],
webhooks: [],
sources: [{ name: "github", secret: "s1", enabled: true }]
}

Tables is the in-memory database: one array of rows per table, typed by the same schema, so the interpreter and the types cannot disagree about what a row looks like.

The parser needs two operations: cut a string at a delimiter, and remove padding. Both are template-literal patterns. infer matches the shortest prefix before the delimiter, so one pattern peels one piece off:

type Equal<X, Y> = (<T>() => T extends X ? 1 : 2) extends (<T>() => T extends Y ? 1 : 2) ? true : false
type Expect<T extends true> = T
type Trim<S extends string> = S extends ` ${infer R}` ? Trim<R> : S extends `${infer R} ` ? Trim<R> : S
type Split<S extends string, D extends string, Acc extends string[] = []> = S extends `${infer H}${D}${infer T}`
? Split<T, D, [...Acc, Trim<H>]>
: [...Acc, Trim<S>]
export type Columns = Expect<Equal<Split<"id, status ,source", ",">, ["id", "status", "source"]>>
export type Conditions = Expect<Equal<Split<"a = ? AND b = ?", " AND ">, ["a = ?", "b = ?"]>>
export type Single = Expect<Equal<Split<"id", ",">, ["id"]>>

Split carries its result in Acc, and the recursive call is the whole branch. That is the tail position from lesson 7. I measured the depth: on tsc 7.0.2 and 5.9.3, a query with 500 columns and one with 500 conditions both type-check, and 1000 stops with TS2589: Type instantiation is excessively deep. No Relay query is near that, but the shape of the code decides which side of the limit it lands on.

Each item is column or column AS alias. Parse it into a pair, check the column exists on the table, and otherwise produce an error type. The row is then a mapped type that renames keys with as:

interface Schema {
readonly jobs: { id: string; status: "queued" | "running" | "done"; attempts: number }
}
type Trim<S extends string> = S extends ` ${infer R}` ? Trim<R> : S extends `${infer R} ` ? Trim<R> : S
type SqlError<M extends string> = { readonly error: M }
type Pair<T extends keyof Schema, Item extends string> = Item extends `${infer C} AS ${infer A}`
? Lookup<T, Trim<C>, Trim<A>>
: Lookup<T, Item, Item>
type Lookup<T extends keyof Schema, C extends string, A extends string> = C extends keyof Schema[T]
? readonly [A, C]
: SqlError<`unknown column '${C}' in table '${T}'`>
type RowOf<T extends keyof Schema, Pairs extends readonly [string, string]> = {
[P in Pairs as P[0]]: P[1] extends keyof Schema[T] ? Schema[T][P[1]] : never
}
type Equal<X, Y> = (<T>() => T extends X ? 1 : 2) extends (<T>() => T extends Y ? 1 : 2) ? true : false
type Expect<T extends true> = T
export type Renamed = Expect<
Equal<RowOf<"jobs", Pair<"jobs", "id"> | Pair<"jobs", "status AS state">>, { id: string; state: "queued" | "running" | "done" }>
>
type ByIntersection = { id: string } & { state: "queued" | "running" | "done" }
// @ts-expect-error: Equal tells an intersection apart from the flat object type
export type NotEqual = Expect<Equal<ByIntersection, { id: string; state: "queued" | "running" | "done" }>>
export type Misspelled = Expect<Equal<Pair<"jobs", "staus">, SqlError<"unknown column 'staus' in table 'jobs'">>>

Two decisions are worth noting. First, the column list is a union of pairs, and the mapped type’s as P[0] turns each pair into one key. That avoids building the object with intersections, which would not compare equal to a plain object type in Equal. Second, errors are values: a failed lookup returns SqlError<...>, a normal object type that carries a message, and the code that walks the list checks for it. The error never throws. It travels to the end of the parse, where a final step turns it into something the user sees.

When you walk a list of pairs, wrap checks in tuples ([C] extends [SqlError<string>]). A bare C extends ... distributes over a union of pairs and tests each one alone, which silently builds a different result per column.

Each condition is <column> = ?. The parameters are a tuple with one entry per ?, typed as the column it is compared to. The tuple is built by recursion with an accumulator, one condition at a time:

interface Schema {
readonly jobs: { id: string; status: "queued" | "running" | "done"; attempts: number }
}
type Trim<S extends string> = S extends ` ${infer R}` ? Trim<R> : S extends `${infer R} ` ? Trim<R> : S
type SqlError<M extends string> = { readonly error: M }
type ParamsOf<T extends keyof Schema, Conditions extends string[], Acc extends unknown[] = []> =
Conditions extends [infer H extends string, ...infer R extends string[]]
? H extends `${infer C} = ?`
? Trim<C> extends keyof Schema[T]
? ParamsOf<T, R, [...Acc, Schema[T][Trim<C>]]>
: SqlError<`unknown column '${Trim<C>}' in table '${T}'`>
: SqlError<`expected '<column> = ?' but found '${H}'`>
: Acc
type Equal<X, Y> = (<T>() => T extends X ? 1 : 2) extends (<T>() => T extends Y ? 1 : 2) ? true : false
type Expect<T extends true> = T
export type Two = Expect<Equal<ParamsOf<"jobs", ["status = ?", "attempts = ?"]>, ["queued" | "running" | "done", number]>>
export type None = Expect<Equal<ParamsOf<"jobs", []>, []>>
export type Bad = Expect<Equal<ParamsOf<"jobs", ["attempts > ?"]>, SqlError<"expected '<column> = ?' but found 'attempts > ?'">>>

infer H extends string (TypeScript 4.7) gives the head a usable type without a second check. The parameter tuple becomes the rest parameter of query, so a missing argument, an extra one and a wrong type are all ordinary call errors, with no special code for any of them.

An error type in the middle of a parse is useless unless the user sees it where they made the mistake. Put a conditional type in the parameter position, and let it evaluate to the message when the query is invalid:

type Tables = "jobs" | "webhooks"
type Check<Q extends string> = Q extends `SELECT * FROM ${infer T}`
? T extends Tables
? Q
: `error: unknown table '${T}'`
: "error: expected SELECT * FROM <table>"
declare function query<const Q extends string>(sql: Check<Q>): Q
export const ok = query("SELECT * FROM jobs")
// @ts-expect-error: the parameter's type is the message "error: unknown table 'job'"
export const bad = query("SELECT * FROM job")

Q still gets inferred from the argument, because it appears in a branch of the conditional. I checked this on tsc 7.0.2 and on 5.9.3, the playground’s version. For a valid query the parameter type is Q itself, so the call is accepted. Otherwise it is a string literal type that no query string can match. The error you see in the editor is the message, quoted:

Argument of type '"SELECT idd FROM jobs"' is not assignable to parameter of type '"error: unknown column 'idd' in table 'jobs'"'.

That is the best a type-level parser can do: the diagnostic is the checker’s, and the text is yours. You cannot point at the exact character, and you cannot change the wording of “is not assignable”. The error: prefix tells a reader that the type is a message, not a literal they were expected to write.

The interpreter has the same grammar at runtime: a small parser, a check that every table and column exists, a filter for each WHERE column and a projection for each pair. It is about 60 lines in the reference solution and it throws the same messages as the types, minus the error: prefix. Nothing connects the two parsers except tests, so the tests run both on the same strings: the types reject the query with @ts-expect-error, and the runtime throws when the query is run anyway.

The function’s return type is the one place the compiler cannot help. query promises Row<Q>[], and the body builds Record<string, unknown> objects with Object.fromEntries. A cast would silence this, but an overload hides it more honestly: the public signature says what callers see, and the implementation signature is compatible but looser.

type Row<Q extends string> = Q extends `SELECT ${infer C} FROM ${string}` ? { [K in C]: string } : never
export function run<const Q extends string>(sql: Q): { rows: Array<Row<Q>> }
export function run(sql: string): { rows: Array<Record<string, unknown>> } {
return { rows: [] }
}
export function liar<const Q extends string>(sql: Q): { rows: Array<Row<Q>> }
export function liar(sql: string): { rows: Array<Record<string, unknown>> } {
return { rows: [{ id: sql.length }] }
}

liar compiles. Its body returns a number where Row<Q> promises a string, and the compiler accepts it. This is the one seam in the design. The type-level parser and the runtime must agree, and the checker does not verify that. The Expect<Equal<...>> tests pin the types, the runtime tests pin the behavior, and the shared strings tie them together. A seam like this is fine when it is one function, documented, and covered by tests on both sides.

The starter gives you the schema, Trim, Split, the runtime parser plan and the table and column checks. The types are loose (Row<Q> is a plain record, Params<Q> is unknown[], Checked<Q> accepts everything) and the interpreter returns every row untouched. Write the type-level parser that fills in Row, Params and Checked, then make the interpreter project columns, filter by WHERE and check the parameter count. The type tests are the heart: exact row and parameter types, and @ts-expect-error on every bad column, table and argument list. The rules at the top of the file give the exact messages. It runs on TypeScript 5.9 here and on 7 locally, and both give the same results.

In the Relay project, put your main.ts at src/sql.ts and the test next to it. Then run both checks, because the type tests only fail in the compiler:

Terminal window
bun test src/sql.test.ts
bunx tsc --noEmit

The dashboard builds its database from rows it already holds, and the query strings are checked where they are written:

src/dashboard.ts
import { createDb } from "./sql.ts"
const db = createDb({ jobs: [], webhooks: [], sources: [] })
const failed = db.query("SELECT id, source AS origin FROM jobs WHERE status = ?", "failed")
const origins: string[] = failed.rows.map((row) => row.origin)

Rename source to sourc in the query and the editor underlines the string with error: unknown column 'sourc' in table 'jobs'. Pass "paused" as the status and it rejects the argument, because status is a union of four literals.

  • A SQL string is parsed with template-literal types: Split and Trim cut it up, and tuples of [alias, column] carry the result.
  • Mapped types with as build the row, without intersections, so Equal tests see a plain object.
  • Errors are values (SqlError<M>) that travel through the parse. Check them with [C] extends [...], never a bare C extends, to avoid distribution.
  • The parameter list is a rest-parameter tuple, so argument count and type errors come from the ordinary call check.
  • A conditional type in the parameter position turns a failed parse into a readable message, and inference of Q still works through it.
  • The runtime and the type-level parser agree only by tests. An overload keeps that one seam out of the public signature without a cast.
  • Parse strings at the type level only for a small grammar. Large ones belong in generated types.