← All Exercises

Type-Safe Query Builder with Parameters

advancedtypescript~15min

Background

String-concatenated SQL is a classic injection risk. Parameterized builders keep values out of the SQL text and let TypeScript reject unknown columns before the query ever runs.

Problem

Implement QueryBuilder<Row> with from, select, where, order, limit, and build. Columns must be keys of Row, where values must match the row type, and build returns a SQL string with $1, $2 placeholders plus the matching params array. Preserve WHERE key order and support limit 0.

Input

A JSON object with table, select columns, optional where conditions, optional orderBy, and optional limit.

Output

A JSON object with a sql string containing numbered placeholders and a params array in matching order.

Sample tests

Sample 1

Input: {"table":"users","select":["id","name"],"where":{"status":"active"},"orderBy":{"column":"name","direction":"asc"},"limit":10}
Expected: {"sql":"SELECT id, name FROM users WHERE status = $1 ORDER BY name ASC LIMIT 10","params":["active"]}

Sample 2

Input: {"table":"users","select":["id"],"where":{"status":"active","age":30}}
Expected: {"sql":"SELECT id FROM users WHERE status = $1 AND age = $2","params":["active",30]}

Sample 3

Input: {"table":"users","select":["id"],"orderBy":{"column":"id","direction":"desc"}}
Expected: {"sql":"SELECT id FROM users ORDER BY id DESC","params":[]}

Your solution

Learning objective

Practice generic classes, keyof column types, and safe parameterized query construction.