@vanit-co/sql-ts 1.0.4 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,454 +1,651 @@
1
1
  # @vanit-co/sql-ts
2
2
 
3
- A TypeScript SQL query builder using tagged template literals. Write plain SQL with safe, automatic parameter binding and properly quoted identifiers. No DSL to learn, no magic, no ORM.
3
+ [![npm](https://img.shields.io/npm/v/@vanit-co/sql-ts)](https://www.npmjs.com/package/@vanit-co/sql-ts)
4
+ [![CI](https://github.com/vanit-co/sql-ts/actions/workflows/ci.yml/badge.svg)](https://github.com/vanit-co/sql-ts/actions/workflows/ci.yml)
5
+ [![minzipped size](https://img.shields.io/bundlephobia/minzip/@vanit-co/sql-ts)](https://bundlephobia.com/package/@vanit-co/sql-ts)
6
+ ![types included](https://img.shields.io/npm/types/@vanit-co/sql-ts)
7
+ [![license](https://img.shields.io/npm/l/@vanit-co/sql-ts)](./LICENSE)
4
8
 
5
- Supports **MySQL** (`?` placeholders, `` ` `` backtick identifiers), **PostgreSQL** (`$n` placeholders, `"` double-quote identifiers) and **SQLite** (through the MySQL format, see [Result object](#result-object)) out of the box.
9
+ **Write plain SQL. Get quoted identifiers, qualified columns and bound parameters for free. Compose queries like data.**
6
10
 
7
- ## Why this library?
11
+ sql-ts is a small TypeScript library for building SQL with tagged template literals. You keep writing SQL; it takes care of the tedious and risky parts:
8
12
 
9
- Writing raw SQL in TypeScript runs into a set of recurring friction points that this library addresses directly:
13
+ - **Safe by default.** Every value you interpolate becomes a bound parameter, and table and column names come from your schema, properly quoted. No string concatenation, no injection.
14
+ - **Your SQL, your driver.** sql-ts only builds `{ text, values }`. Run it with node-postgres, mysql2 or SQLite, exactly as you do today. No DSL to learn, no ORM.
15
+ - **Composes like data.** Every query is an immutable value. Add a `WHERE` only when a filter is set, share fragments between queries, build them with `reduce` or `pipe`.
16
+ - **Typed when you want it.** Typos in column names are compile errors, and with a typed schema each query knows the shape of the rows it returns.
10
17
 
11
- - **Automatic identifier quoting** - table and column names are interpolated as properly quoted identifiers (`` `name` `` for MySQL, `"name"` for PostgreSQL), never as bind parameters. No manual quoting, no dialect-specific escaping scattered across your codebase.
18
+ Zero dependencies, under 2 KB minified and gzipped, ESM and CommonJS. Works with **PostgreSQL**, **MySQL** and **SQLite**, all from the same query.
12
19
 
13
- - **Table alias and qualified column references** - the `select` tag (and its aliases `groupBy`, `having`, `join`, `orderBy`, `where`) automatically expands schema tables as `"table" "alias"` and columns as `"alias"."column"`, so JOIN-heavy queries stay unambiguous without hand-writing every qualified reference.
20
+ ```sh
21
+ npm install @vanit-co/sql-ts
22
+ ```
14
23
 
15
- - **Column alias expansion** - `selectAs` goes further, rendering each column as `"alias"."column" as "alias_column"`. When querying multiple joined tables, result-set keys no longer collide.
24
+ ## In 30 seconds
16
25
 
17
- - **`concat` and `empty` as a monoid** - every tagged template and statement builder returns a `Fragment`. `concat` joins two fragments into one, and `empty` is the identity element. This lets you accumulate query fragments conditionally with `reduce`, compose them with `pipe`, or chain them with `.append` - treating query construction as plain data transformation.
26
+ Without it, you hand-qualify every column, alias every result key to avoid collisions, and track placeholder numbers yourself:
18
27
 
19
- - **`all` and `pick` helpers** - expand an entire table's columns or a chosen subset into a comma-separated list inside any tag, so `SELECT ${all(users, posts)}` replaces repetitive column lists without losing type safety.
28
+ ```ts
29
+ let text = `SELECT "u"."id" AS "u_id", "u"."email" AS "u_email", "p"."id" AS "p_id", "p"."title" AS "p_title"
30
+ FROM "posts" "p" JOIN "users" "u" ON "p"."user_id" = "u"."id"`
31
+ const values = []
32
+ if (userId) { values.push(userId); text += ` WHERE "u"."id" = $${values.length}` }
33
+ ```
20
34
 
21
- ## Installation
35
+ With it, you declare the tables once and the rest follows:
22
36
 
23
- ```sh
24
- npm install @vanit-co/sql-ts
37
+ ```ts
38
+ import { schema, selectAs, join, where, all, empty } from '@vanit-co/sql-ts'
39
+
40
+ const users = schema({ table: 'users', columns: ['id', 'email'], alias: 'u' })
41
+ const posts = schema({ table: 'posts', columns: ['id', 'user_id', 'title'], alias: 'p' })
42
+
43
+ const postsQuery = (userId?: number) =>
44
+ selectAs`SELECT ${all(users, posts)} FROM ${posts}`
45
+ .append(join` JOIN ${users} ON ${posts.user_id} = ${users.id}`)
46
+ .append(userId ? where` WHERE ${users.id} = ${userId}` : empty)
47
+
48
+ const q = postsQuery(7)
49
+ q.text // SELECT "u"."id" as "u_id" ,"u"."email" as "u_email" ,"p"."id" as "p_id" ... WHERE "u"."id" = $1
50
+ q.sql // the same query for MySQL and SQLite: SELECT `u`.`id` as `u_id` ... WHERE `u`.`id` = ?
51
+ q.values // [7]
52
+
53
+ await pg.query(q) // node-postgres reads { text, values }
25
54
  ```
26
55
 
27
- ## Quick example
56
+ A typo like `users.emial` is a compile error, and `q` is a plain value you can pass around and extend.
57
+
58
+ ## Contents
59
+
60
+ - [Getting started](#getting-started)
61
+ - [Which tag do I use?](#which-tag-do-i-use)
62
+ - [How it compares](#how-it-compares)
63
+ - [Reference](#reference)
64
+ - [Schema](#schema)
65
+ - [The result object](#the-result-object)
66
+ - [Template tags](#template-tags)
67
+ - [Column helpers: `all`, `pick` and `as`](#column-helpers-all-pick-and-as)
68
+ - [Typed result rows](#typed-result-rows)
69
+ - [Statement builders: `insert`, `update` and `updateAs`](#statement-builders-insert-update-and-updateas)
70
+ - [Composing queries: `append`, `concat` and `empty`](#composing-queries-append-concat-and-empty)
71
+ - [Arrays and `IN` lists](#arrays-and-in-lists)
72
+ - [Raw SQL: `raw`](#raw-sql-raw)
73
+ - [Prepared statements: `preparedStatementName`](#prepared-statements-preparedstatementname)
74
+ - [Dialect functions: `toPostgres` and `toMysql`](#dialect-functions-topostgres-and-tomysql)
75
+ - [Safety](#safety)
76
+ - [Common pitfalls](#common-pitfalls)
77
+
78
+ ---
79
+
80
+ ## Getting started
81
+
82
+ Six short steps, from describing your tables to writing data. The examples build on each other.
28
83
 
29
- **sql** tag takes care of quoting the identifiers (tables and columns) with the proper quotes `` ` `` for MySQL and `"` for PostgreSQL.
84
+ ### 1. Describe your tables
85
+
86
+ A schema says what a table is called, which columns you will use, and the short alias queries refer to it by. You write it once and import it wherever you query that table.
30
87
 
31
88
  ```ts
32
- import { schema, sql, all } from '@vanit-co/sql-ts'
89
+ import { schema } from '@vanit-co/sql-ts'
90
+
91
+ const users = schema({ table: 'users', columns: ['id', 'email', 'name'], alias: 'u' })
92
+ const posts = schema({ table: 'posts', columns: ['id', 'user_id', 'title'], alias: 'p' })
33
93
 
34
- const users = schema({ table: 'users', columns: ['id', 'email'] })
94
+ users.email // a column you can interpolate; users.emial is a compile error
95
+ ```
35
96
 
36
- const query = sql`SELECT ${all(users)} FROM ${users} WHERE ${users.id} = ${42}`
97
+ ### 2. Write a query
37
98
 
38
- // PostgreSQL
39
- console.log(query.text) // SELECT "id" ,"email" FROM "users" WHERE "id" = $1
99
+ Write SQL as usual and interpolate the schema and your values. Tables and columns become quoted names; values become placeholders.
40
100
 
41
- // MySQL
42
- console.log(query.sql) // SELECT `id` ,`email` FROM `users` WHERE `id` = ?
101
+ ```ts
102
+ import { select, where } from '@vanit-co/sql-ts'
43
103
 
44
- console.log(query.values) // [42]
104
+ const q = select`SELECT ${users.id}, ${users.email} FROM ${users}`
105
+ .append(where` WHERE ${users.email} = ${'ada@example.com'}`)
106
+
107
+ q.text // SELECT "u"."id", "u"."email" FROM "users" "u" WHERE "u"."email" = $1
108
+ q.sql // SELECT `u`.`id`, `u`.`email` FROM `users` `u` WHERE `u`.`email` = ?
109
+ q.values // ['ada@example.com']
45
110
  ```
46
111
 
47
- ## Full query example
112
+ `.text` is the PostgreSQL form (`$1` placeholders, `"` quotes), `.sql` the MySQL and SQLite form (`?` placeholders, `` ` `` quotes), and `.values` the parameters, in order. `.append` adds a fragment at the end, and `where` is the same tag as `select`, named after the clause it builds. Note the space at the start of `` ` WHERE ...` ``: appending joins the text as-is.
113
+
114
+ ### 3. Run it
48
115
 
49
- **select** tag works like **sql** but automatically adds table aliases and column prefixes. The other tags **groupBy**, **having**, **join**, **orderBy** and **where** are just aliases to **select** with the aim of maintaining semantics. The **selectAs** tag besides the column prefixes will also add the column alias using the format `$prefix_$columnName`.
116
+ Hand the query to your driver. sql-ts never opens a connection.
50
117
 
51
118
  ```ts
52
- import { schema, select, selectAs, join, where, all, insert, update, empty } from '@vanit-co/sql-ts'
119
+ // node-postgres: reads .text and .values
120
+ const { rows } = await client.query(q)
53
121
 
54
- const users = schema({ table: 'users', columns: ['id', 'email'], alias: 'u' })
55
- const posts = schema({ table: 'posts', columns: ['id', 'user_id', 'title'], alias: 'p' })
122
+ // mysql2: reads .sql and .values
123
+ const [rows] = await connection.query(q)
124
+
125
+ // SQLite (better-sqlite3, node:sqlite): use .sql and spread the values
126
+ const rows = db.prepare(q.sql).all(...q.values)
127
+ ```
128
+
129
+ ### 4. Read the rows
130
+
131
+ When you join tables, both may have an `id`. The `selectAs` tag names every column `alias_column` in the result, so nothing collides, and `as(column)` gives you that key back.
132
+
133
+ ```ts
134
+ import { selectAs, join, all, as } from '@vanit-co/sql-ts'
135
+
136
+ const q = selectAs`SELECT ${all(users, posts)} FROM ${posts}`
137
+ .append(join` JOIN ${users} ON ${users.id} = ${posts.user_id}`)
138
+
139
+ q.text
140
+ // SELECT "u"."id" as "u_id" ,"u"."email" as "u_email" ,"u"."name" as "u_name"
141
+ // ,"p"."id" as "p_id" ,"p"."user_id" as "p_user_id" ,"p"."title" as "p_title"
142
+ // FROM "posts" "p" JOIN "users" "u" ON "u"."id" = "p"."user_id" (wrapped)
143
+
144
+ const { rows } = await client.query(q)
145
+ rows.map(row => ({
146
+ title: row[as(posts.title)], // row.p_title
147
+ author: row[as(users.email)], // row.u_email
148
+ }))
149
+ ```
150
+
151
+ `all(...)` expands every column of the tables you give it. To have TypeScript know the shape of `rows` too, see [Typed result rows](#typed-result-rows).
152
+
153
+ ### 5. Add conditions
154
+
155
+ Because a query is a value, optional filters are just `append` with a condition. `empty` is the fragment that adds nothing.
156
+
157
+ ```ts
158
+ import { selectAs, where, orderBy, all, empty } from '@vanit-co/sql-ts'
159
+
160
+ const findPosts = ({ userId, title }: { userId?: number; title?: string }) =>
161
+ selectAs`SELECT ${all(posts)} FROM ${posts}`
162
+ .append(where` WHERE true`)
163
+ .append(userId !== undefined ? where` AND ${posts.user_id} = ${userId}` : empty)
164
+ .append(title !== undefined ? where` AND ${posts.title} ILIKE ${`%${title}%`}` : empty)
165
+ .append(orderBy` ORDER BY ${posts.id} DESC`)
56
166
 
57
- const id = 42
167
+ findPosts({ userId: 7 }).text
168
+ // SELECT "p"."id" as "p_id" ,"p"."user_id" as "p_user_id" ,"p"."title" as "p_title" FROM "posts" "p"
169
+ // WHERE true AND "p"."user_id" = $1 ORDER BY "p"."id" DESC (wrapped)
58
170
 
59
- // SELECT with JOIN
60
- const query = selectAs`SELECT ${all(users, posts)} FROM ${posts}`
61
- .append(join`JOIN ${users} ON ${posts.user_id} = ${users.id}`)
62
- .append(id ? where`WHERE ${users.id} = ${42}` : empty)
171
+ findPosts({ userId: 7, title: 'sql' }).values // [7, '%sql%']
172
+ ```
173
+
174
+ An `undefined` interpolation is dropped, so `${cond ? fragment : undefined}` works as well as `empty`. `null` is different: it is bound, and reaches the database as `NULL`.
175
+
176
+ ### 6. Write data
63
177
 
64
- query.text
65
- // SELECT "u"."id" as "u_id" ,"u"."email" as "u_email" ,"p"."id" as "p_id" ,"p"."user_id" as "p_user_id" ,"p"."title" as "p_title"
66
- // FROM "posts" "p"
67
- // JOIN "users" "u" ON "p"."user_id" = "u"."id"
68
- // WHERE "u"."id" = $1
69
- query.values // [42]
178
+ `insert` and `update` build the statement from an object of column → value. Columns you leave `undefined` are skipped, so a partial update is just a partial object.
70
179
 
71
- // INSERT
72
- const ins = insert(users, { id: 1, email: 'alice@example.com' })
73
- ins.text // insert into "users" ("id" ,"email") values ($1 ,$2)
74
- ins.values // [1, 'alice@example.com']
180
+ ```ts
181
+ import { insert, updateAs, where, sql } from '@vanit-co/sql-ts'
182
+
183
+ const add = insert(users, { email: 'ada@example.com', name: 'Ada' })
184
+ .append(sql` RETURNING ${users.id}`)
185
+ add.text // insert into "users" ("email" ,"name") values ($1 ,$2) RETURNING "id"
186
+ add.values // ['ada@example.com', 'Ada']
75
187
 
76
- // UPDATE
77
- const upd = update(users, { email: 'new@example.com' }).append(sql` where ${users.id} = ${id}`)
78
- upd.text // update "users" set "email" = $1 where "id" = $2
79
- upd.values // ['new@example.com', 42]
188
+ const rename = updateAs(users, { name: 'Ada Lovelace', email: undefined })
189
+ .append(where` WHERE ${users.id} = ${1}`)
190
+ rename.text // update "users" as "u" set "name" = $1 WHERE "u"."id" = $2
191
+ rename.values // ['Ada Lovelace', 1]
80
192
  ```
81
193
 
194
+ `updateAs` gives the table its alias, so the `where` tag's `"u"."id"` resolves. With plain `update`, build the `WHERE` with the `sql` tag instead (see [Common pitfalls](#common-pitfalls)).
195
+
196
+ That's the whole workflow. The rest of this page is the detail of each piece.
197
+
82
198
  ---
83
199
 
84
- ## Core concepts
200
+ ## Which tag do I use?
85
201
 
86
- ### Schema
202
+ The tags differ only in how they write the tables and columns you interpolate. Values are always bound.
203
+
204
+ | tag | `${users}` becomes | `${users.email}` becomes | use it for |
205
+ |-----|-------------------|-------------------------|------------|
206
+ | `sql` | `"users"` | `"email"` | single-table statements, `RETURNING`, the `WHERE` after `update` |
207
+ | `select` (`s`) | `"users" "u"` | `"u"."email"` | queries with aliases: `FROM`, `JOIN`, `WHERE`, `ORDER BY` |
208
+ | `where` (`w`), `join` (`j`), `orderBy` (`o`), `groupBy` (`g`), `having` (`h`) | `"users" "u"` | `"u"."email"` | the same tag as `select`, named after the clause you are writing |
209
+ | `selectAs` (`sa`) | `"users" "u"` | `"u"."email" as "u_email"` | the select list only, when joined tables share column names |
210
+
211
+ And the helpers you interpolate into them:
212
+
213
+ - `all(users, posts)` expands every column of the tables; `pick(users.id, posts.title)` the ones you name.
214
+ - `as(users.email)` is the result key `selectAs` gives a column: `'u_email'`.
215
+ - `expr<number>()(fragment, 'name')` is a computed column, `(...) as "name"`.
216
+ - `raw('now()')` puts trusted SQL text in as-is, never bound.
217
+
218
+ ---
219
+
220
+ ## How it compares
221
+
222
+ | | sql-ts | [sql-template-tag](https://github.com/blakeembrey/sql-template-tag) | [slonik](https://github.com/gajus/slonik) | [kysely](https://kysely.dev) |
223
+ |-----------------------------------------|:------:|:----------------:|:------:|:------:|
224
+ | Plain SQL is the primary API | ✅ | ✅ | ✅ | ❌ (method-chain DSL) |
225
+ | Identifiers quoted from a typed schema | ✅ | ❌ | manual `sql.identifier` | ✅ |
226
+ | Automatic `alias.column` / `AS alias_column` | ✅ | ❌ | ❌ | ❌ |
227
+ | One query → PostgreSQL *and* MySQL/SQLite | ✅ | ✅ | ❌ (PostgreSQL only) | per-dialect instance |
228
+ | Composable as a monoid (`concat` / `empty`) | ✅ | partial (`join`, `empty`) | ❌ | ❌ |
229
+ | Executes queries itself (wraps the driver) | ❌ (use your driver) | ❌ | ✅ | ✅ |
230
+
231
+ Pick **sql-ts** if you like SQL, use your driver directly, and want query building that fits functional code. Pick **kysely** or an ORM if you'd rather not write SQL at all.
232
+
233
+ ---
87
234
 
88
- Define your tables once. The schema carries table and column metadata used by the template tags to produce properly quoted, prefixed identifiers.
235
+ ## Reference
236
+
237
+ Unless an example declares its own, the examples below use these two tables:
89
238
 
90
239
  ```ts
91
240
  import { schema } from '@vanit-co/sql-ts'
92
241
 
93
- const users = schema({ table: 'users', columns: ['id', 'email'] })
94
-
95
- // With a table alias (useful for self-joins or verbose table names)
96
- const u = schema({ table: 'users', columns: ['id', 'email'], alias: 'u' })
242
+ const users = schema({ table: 'users', columns: ['id', 'email', 'name'], alias: 'u' })
243
+ const posts = schema({ table: 'posts', columns: ['id', 'user_id', 'title'], alias: 'p' })
97
244
  ```
98
245
 
99
- `schema` takes:
246
+ ### Schema
247
+
248
+ `schema` describes a table once, for every query that uses it.
249
+
100
250
  | field | type | description |
101
251
  |-------|------|-------------|
102
- | `table` | `string` | The actual table name in the database |
103
- | `columns` | `string[]` | Column names to expose as typed properties |
104
- | `alias` | `string` (optional) | Alias used for prefixing columns; defaults to `table` |
252
+ | `table` | `string` | The table's name in the database |
253
+ | `columns` | `string[]` | The columns you query; each becomes a property (`users.email`) |
254
+ | `alias` | `string` (optional) | The name queries use for the table; defaults to `table` |
105
255
 
106
- After calling `schema`, the returned object has a typed property for each column (`users.id`, `users.email`, etc.).
256
+ Without an alias, the table's own name is used: `"users" "users"` and `"users"."email"`. That works, but a short alias keeps long queries readable.
107
257
 
108
- #### Multiple aliases for the same table: `alias`
258
+ To have the columns typed, give `schema` a type record (note the extra `()`): `schema<{ id: number; email: string }>()({ ... })`. See [Typed result rows](#typed-result-rows).
109
259
 
110
- `alias(table, newAlias)` returns a copy of a schema under a different alias, keeping the same table and typed columns. The original schema is left untouched, so it is handy in local scope for self-joins or joining the same table more than once.
260
+ #### The same table twice: `alias`
261
+
262
+ `alias(table, newAlias)` returns a copy of a schema under another alias, for self-joins or joining a table more than once. The original is left as it was.
111
263
 
112
264
  ```ts
113
265
  import { schema, alias, selectAs, join, pick } from '@vanit-co/sql-ts'
114
266
 
115
- const users = schema({ table: 'users', columns: ['id', 'email'] })
116
- const posts = schema({ table: 'posts', columns: ['author_id', 'reviewer_id'], alias: 'p' })
267
+ const people = schema({ table: 'users', columns: ['id', 'email'] })
268
+ const reviews = schema({ table: 'reviews', columns: ['author_id', 'reviewer_id'], alias: 'r' })
117
269
 
118
- const author = alias(users, 'author')
119
- const reviewer = alias(users, 'reviewer')
270
+ const author = alias(people, 'author')
271
+ const reviewer = alias(people, 'reviewer')
120
272
 
121
- const q = selectAs`SELECT ${pick(author.email, reviewer.email)} FROM ${posts}`
122
- .append(join` JOIN ${author} ON ${posts.author_id} = ${author.id}`)
123
- .append(join` JOIN ${reviewer} ON ${posts.reviewer_id} = ${reviewer.id}`)
273
+ const q = selectAs`SELECT ${pick(author.email, reviewer.email)} FROM ${reviews}`
274
+ .append(join` JOIN ${author} ON ${reviews.author_id} = ${author.id}`)
275
+ .append(join` JOIN ${reviewer} ON ${reviews.reviewer_id} = ${reviewer.id}`)
124
276
 
125
277
  q.text
126
- // SELECT "author"."email" as "author_email" ,"reviewer"."email" as "reviewer_email" FROM "posts" "p"
127
- // JOIN "users" "author" ON "p"."author_id" = "author"."id"
128
- // JOIN "users" "reviewer" ON "p"."reviewer_id" = "reviewer"."id"
278
+ // SELECT "author"."email" as "author_email" ,"reviewer"."email" as "reviewer_email" FROM "reviews" "r"
279
+ // JOIN "users" "author" ON "r"."author_id" = "author"."id"
280
+ // JOIN "users" "reviewer" ON "r"."reviewer_id" = "reviewer"."id" (wrapped)
129
281
  ```
130
282
 
131
- ---
132
-
133
- ### Result object
283
+ ### The result object
134
284
 
135
- Every template tag and statement builder returns a `Result` object with three properties:
285
+ Every tag and statement builder returns the same kind of value:
136
286
 
137
287
  | property | description |
138
288
  |----------|-------------|
139
- | `.sql` | Query string in MySQL format (`?` placeholders, backtick-quoted identifiers), also used for SQLite |
140
- | `.text` | Query string in PostgreSQL format (`$n` placeholders, double-quote identifiers) |
141
- | `.values` | Array of bind values in order, ready to pass to your database driver |
289
+ | `.text` | The query for PostgreSQL: `$1` placeholders, `"` quoted names |
290
+ | `.sql` | The query for MySQL and SQLite: `?` placeholders, `` ` `` quoted names |
291
+ | `.values` | The bound values, in order |
292
+ | `.append(fragment)` | A new query with `fragment` added at the end (the original is unchanged) |
293
+ | `.name` | Set by [`preparedStatementName`](#prepared-statements-preparedstatementname) |
142
294
 
143
- Pass these directly to your driver:
295
+ node-postgres reads `{ text, values }` and mysql2 reads `{ sql, values }`, so you pass the query itself. With SQLite, pass `.sql` and spread `.values`: SQLite reads `$1` as a named parameter, so `.text` would leave the values unbound.
144
296
 
145
297
  ```ts
146
- // node-postgres (pg)
147
- await client.query(query)
148
-
149
- // mysql2
150
- await connection.query(query)
151
-
152
- // better-sqlite3 / node:sqlite
153
- db.prepare(query.sql).all(...query.values)
298
+ await client.query(q) // node-postgres
299
+ await connection.query(q) // mysql2
300
+ db.prepare(q.sql).all(...q.values) // better-sqlite3, node:sqlite
154
301
  ```
155
302
 
156
- SQLite accepts backtick-quoted identifiers and `?` placeholders, so use `.sql` with it. Do not use `.text`: SQLite reads `$1` as a named parameter, so positional values won't bind.
157
-
158
- ---
159
-
160
- ## Template tag functions
303
+ ### Template tags
161
304
 
162
- ### `sql`
305
+ #### `sql`
163
306
 
164
- The base tag. Interpolated plain values become bind parameters. Interpolated schema tables become their bare name identifier; columns become their bare column name identifier (no table prefix).
307
+ The base tag: tables and columns become their bare quoted names.
165
308
 
166
309
  ```ts
167
310
  import { sql } from '@vanit-co/sql-ts'
168
311
 
169
- const users = schema({ table: 'users', columns: ['id', 'email'] })
312
+ const q = sql`SELECT ${users.email} FROM ${users} WHERE ${users.id} = ${42}`
313
+ q.text // SELECT "email" FROM "users" WHERE "id" = $1
314
+ q.values // [42]
315
+ ```
316
+
317
+ #### `select` (short: `s`)
170
318
 
171
- // Plain values → bind parameters
172
- const q1 = sql`SELECT * FROM users WHERE id = ${42}`
173
- q1.text // SELECT * FROM users WHERE id = $1
174
- q1.values // [42]
319
+ Tables are written with their alias, and columns qualified by it. Use it whenever a query names more than one table, and for the `WHERE`, `JOIN` and `ORDER BY` of one that does.
175
320
 
176
- // Schema table → quoted identifier (name only)
177
- const q2 = sql`FROM ${users}`
178
- q2.text // FROM "users"
321
+ ```ts
322
+ import { select } from '@vanit-co/sql-ts'
179
323
 
180
- // Schema column → quoted identifier (name only, no prefix)
181
- const q3 = sql`SELECT ${users.id}`
182
- q3.text // SELECT "id"
324
+ select`SELECT ${users.email} FROM ${users}`.text
325
+ // SELECT "u"."email" FROM "users" "u"
183
326
  ```
184
327
 
185
- ### `select` (alias: `s`)
328
+ #### `selectAs` (short: `sa`)
186
329
 
187
- Like `sql`, but schema tables are rendered as `"name" "alias"` and columns are rendered as `"alias"."column"`. Use this for `SELECT`, `FROM`, `JOIN`, and `WHERE` clauses when you want fully qualified column references.
330
+ Like `select`, and each column is also named `alias_column` in the result, so columns of joined tables don't collide. It belongs in the select list only: anywhere else, the `as` it adds is a syntax error (see [Common pitfalls](#common-pitfalls)).
188
331
 
189
332
  ```ts
190
- import { select, s, schema } from '@vanit-co/sql-ts'
333
+ import { selectAs } from '@vanit-co/sql-ts'
191
334
 
192
- const users = schema({ table: 'users', columns: ['id', 'email'] })
193
- const u = schema({ table: 'users', columns: ['id', 'email'], alias: 'u' })
335
+ selectAs`SELECT ${users.email} FROM ${users}`.text
336
+ // SELECT "u"."email" as "u_email" FROM "users" "u"
337
+ ```
194
338
 
195
- // Table → name + alias
196
- select`FROM ${users}`.text // FROM "users" "users"
197
- select`FROM ${u}`.text // FROM "users" "u"
339
+ #### `where`, `join`, `orderBy`, `groupBy`, `having`
198
340
 
199
- // Column → alias.column
200
- select`SELECT ${users.email}`.text // SELECT "users"."email"
201
- select`SELECT ${u.email}`.text // SELECT "u"."email"
341
+ The same tag as `select`, under the name of the clause you are writing, so a query reads the way it runs. Short forms: `w`, `j`, `o`, `g`, `h`.
202
342
 
203
- // Mix with values
204
- select`SELECT ${users.id} WHERE id = ${7}`.text // SELECT "users"."id" WHERE id = $1
205
- select`SELECT ${users.id} WHERE id = ${7}`.values // [7]
343
+ ```ts
344
+ import { select, join, where, groupBy, having, orderBy } from '@vanit-co/sql-ts'
345
+
346
+ const q = select`SELECT ${users.email}, COUNT(*) FROM ${posts}`
347
+ .append(join` JOIN ${users} ON ${users.id} = ${posts.user_id}`)
348
+ .append(where` WHERE ${posts.title} ILIKE ${'%sql%'}`)
349
+ .append(groupBy` GROUP BY ${users.email}`)
350
+ .append(having` HAVING COUNT(*) > ${1}`)
351
+ .append(orderBy` ORDER BY ${users.email}`)
206
352
 
207
- // Short alias
208
- s`SELECT ${users.id}`.text // SELECT "users"."id"
353
+ q.text
354
+ // SELECT "u"."email", COUNT(*) FROM "posts" "p" JOIN "users" "u" ON "u"."id" = "p"."user_id"
355
+ // WHERE "p"."title" ILIKE $1 GROUP BY "u"."email" HAVING COUNT(*) > $2 ORDER BY "u"."email" (wrapped)
356
+ q.values // ['%sql%', 1]
209
357
  ```
210
358
 
211
- ### `selectAs` (alias: `sa`)
359
+ ### Column helpers: `all`, `pick` and `as`
212
360
 
213
- Same as `select` for tables, but columns are rendered as `"alias"."column" as "alias_column"`. Use this when fetching from multiple joined tables and you want unambiguous aliased column names in the result set.
361
+ #### `all(...tables)`
214
362
 
215
- ```ts
216
- import { selectAs, sa, schema } from '@vanit-co/sql-ts'
363
+ Expands every column of one or more tables, written the way the surrounding tag writes columns.
217
364
 
218
- const users = schema({ table: 'users', columns: ['id', 'email'] })
219
- const u = schema({ table: 'users', columns: ['id', 'email'], alias: 'u' })
365
+ ```ts
366
+ import { select, selectAs, all } from '@vanit-co/sql-ts'
220
367
 
221
- selectAs`SELECT ${users.id}`.text // SELECT "users"."id" as "users_id"
222
- selectAs`SELECT ${users.email}`.text // SELECT "users"."email" as "users_email"
368
+ select`SELECT ${all(users)}`.text
369
+ // SELECT "u"."id" ,"u"."email" ,"u"."name"
223
370
 
224
- // With alias
225
- sa`SELECT ${u.email}`.text // SELECT "u"."email" as "u_email"
371
+ selectAs`SELECT ${all(users, posts)}`.text
372
+ // SELECT "u"."id" as "u_id" ,"u"."email" as "u_email" ,"u"."name" as "u_name"
373
+ // ,"p"."id" as "p_id" ,"p"."user_id" as "p_user_id" ,"p"."title" as "p_title" (wrapped)
226
374
  ```
227
375
 
228
- ### `groupBy` (alias: `g`), `having` (alias: `h`), `join` (alias: `j`), `orderBy` (alias: `o`) and `where` (alias: `w`)
376
+ #### `pick(...columns)`
229
377
 
230
- These are all identical to `select`. They exist as semantic aliases so your query construction reads naturally - each tag signals which SQL clause it belongs to.
378
+ Expands only the columns you name, from any tables.
231
379
 
232
380
  ```ts
233
- import { select, join, j, where, w, groupBy, g, having, h, orderBy, o, schema } from '@vanit-co/sql-ts'
381
+ import { selectAs, pick } from '@vanit-co/sql-ts'
234
382
 
235
- const posts = schema({ table: 'posts', columns: ['id', 'user_id', 'title'] })
236
- const users = schema({ table: 'users', columns: ['id', 'email'] })
237
-
238
- const q = select`SELECT ${posts.title}, ${users.email}`
239
- const fromClause = join` FROM ${posts}`
240
- const joinClause = join` JOIN ${users} ON ${posts.user_id} = ${users.id}`
241
- const whereClause = where` WHERE ${users.id} = ${99}`
242
- const groupClause = groupBy` GROUP BY ${posts.title}`
243
- const havingClause = having` HAVING COUNT(${posts.id}) > ${1}`
244
- const orderClause = orderBy` ORDER BY ${posts.title}`
383
+ selectAs`SELECT ${pick(users.email, posts.title)}`.text
384
+ // SELECT "u"."email" as "u_email" ,"p"."title" as "p_title"
245
385
  ```
246
386
 
247
- ---
387
+ #### `as(column)`
388
+
389
+ The key `selectAs` gives a column in the result, so you read rows without spelling `'u_email'` by hand.
390
+
391
+ ```ts
392
+ import { as } from '@vanit-co/sql-ts'
248
393
 
249
- ## Column helpers: `all` and `pick`
394
+ as(users.email) // 'u_email'
395
+ as(posts.title) // 'p_title'
250
396
 
251
- Use these inside any template tag to expand multiple columns at once.
397
+ const { rows } = await client.query(q)
398
+ rows.map(row => row[as(users.email)])
399
+ ```
252
400
 
253
- ### `all(...tables)`
401
+ ### Typed result rows
254
402
 
255
- Expands every column from one or more schema tables.
403
+ Give `schema` a type record (note the extra `()`) and each query knows the shape of the rows it returns. This is opt-in: a plain `schema({...})` works exactly as before.
256
404
 
257
405
  ```ts
258
- import { select, selectAs, schema, all } from '@vanit-co/sql-ts'
406
+ import { schema, selectAs, join, all, as, type RowOf } from '@vanit-co/sql-ts'
259
407
 
260
- const users = schema({ table: 'users', columns: ['id', 'email'] })
261
- const posts = schema({ table: 'posts', columns: ['title', 'body'] })
408
+ const users = schema<{ id: number; email: string }>()({ table: 'users', columns: ['id', 'email'], alias: 'u' })
409
+ const posts = schema<{ id: number; user_id: number; title: string | null }>()({ table: 'posts', columns: ['id', 'user_id', 'title'], alias: 'p' })
262
410
 
263
- // Single table
264
- select`SELECT ${all(users)}`.text
265
- // SELECT "users"."id" ,"users"."email"
411
+ const q = selectAs`SELECT ${all(users, posts)} FROM ${posts}`
412
+ .append(join` JOIN ${users} ON ${posts.user_id} = ${users.id}`)
266
413
 
267
- // Multiple tables
268
- select`SELECT ${all(users, posts)}`.text
269
- // SELECT "users"."id" ,"users"."email" ,"posts"."title" ,"posts"."body"
414
+ type Row = RowOf<typeof q>
415
+ // { u_id: number; u_email: string; p_id: number; p_user_id: number; p_title: string | null }
270
416
 
271
- // With selectAs for aliased columns
272
- selectAs`SELECT ${all(users)}`.text
273
- // SELECT "users"."id" as "users_id" ,"users"."email" as "users_email"
417
+ const { rows } = await pg.query<RowOf<typeof q>>(q)
418
+ rows[0].p_title // string | null
419
+ rows[0][as(posts.title)] // the same: as(posts.title) is typed as 'p_title'
274
420
  ```
275
421
 
276
- ### `pick(...columns)`
422
+ The examples in this section use these typed `users` and `posts`.
277
423
 
278
- Expands a specific subset of columns from any tables.
424
+ - `columns` must be keys of the type record, so `columns: ['id', 'emial']` is a compile error.
425
+ - `alias(users, 'author')` keeps the types and renames the keys (`author_id`, ...).
426
+ - You can name a row shape without a query: `SelectAsRow<typeof users | typeof posts.title>` gives `alias_column` keys, `Row<typeof users>` bare column names.
279
427
 
280
- ```ts
281
- import { select, selectAs, schema, pick } from '@vanit-co/sql-ts'
428
+ #### What a query's row contains: `RowOf`
282
429
 
283
- const users = schema({ table: 'users', columns: ['id', 'email', 'name'] })
284
- const posts = schema({ table: 'posts', columns: ['title', 'body'] })
430
+ `RowOf<typeof q>` is the row the query selects. Only some interpolations add to it, because the same column reads the same in a select list and in a `WHERE`:
431
+
432
+ - `all(...)` and `pick(...)` of typed tables add their columns: `alias_column` under `selectAs`, the bare name under `sql` and `select`.
433
+ - `expr<V>()(fragment, name)` adds `name: V` (see below).
434
+ - Bare columns (`${users.id}`), tables, values and nested fragments add nothing. To select one column and have it typed, use `pick(users.id)`.
435
+ - `append` and `concat` merge both sides, so a `WHERE` or `ORDER BY` appended to a select keeps its row.
436
+
437
+ ```ts
438
+ import { select, selectAs, where, all, pick, type RowOf } from '@vanit-co/sql-ts'
285
439
 
286
- // Pick from one table
287
- select`SELECT ${pick(users.id, users.email)}`.text
288
- // SELECT "users"."id" ,"users"."email"
440
+ const q = selectAs`SELECT ${all(users)} FROM ${users}`
441
+ .append(where` WHERE ${users.id} = ${7}`)
442
+ type R = RowOf<typeof q> // { u_id: number; u_email: string }
289
443
 
290
- // Pick from different tables
291
- select`SELECT ${pick(users.id, posts.title)}`.text
292
- // SELECT "users"."id" ,"posts"."title"
444
+ const q2 = select`SELECT ${pick(users.email)} FROM ${users}`
445
+ type R2 = RowOf<typeof q2> // { email: string }
293
446
 
294
- // With selectAs
295
- selectAs`SELECT ${pick(users.id, users.email)}`.text
296
- // SELECT "users"."id" as "users_id" ,"users"."email" as "users_email"
447
+ const { rows } = await pg.query<RowOf<typeof q>>(q)
448
+ rows[0].u_email // string
449
+ rows[0].u_name // compile error: the query doesn't select it
297
450
  ```
298
451
 
299
- ### `as(column)`
452
+ An untyped table in `all(...)` or `pick(...)` leaves the row open (`Record<string, any>`), and so does a query nothing was inferred for, as before. `Result`, the type of any query, still accepts every typed one.
300
453
 
301
- Returns the aliased column name as a plain string - the same `prefix_name` string that `selectAs` writes into the SQL `AS` clause. Use this to read a column out of query results by its aliased key without repeating the string manually.
454
+ #### Computed columns: `expr`
302
455
 
303
- ```ts
304
- import { schema, as, selectAs, all } from '@vanit-co/sql-ts'
456
+ `expr<V>()(fragment, name)` writes `(<fragment>) as "name"` and adds `name: V` to the row. It is curried like `schema<R>()`, so you give `V` and the name is inferred.
305
457
 
306
- const users = schema({ table: 'users', columns: ['id', 'email'] })
307
- const u = schema({ table: 'users', columns: ['id', 'email'], alias: 'u' })
458
+ ```ts
459
+ import { selectAs, select, all, expr, type RowOf } from '@vanit-co/sql-ts'
308
460
 
309
- as(users.id) // 'users_id'
310
- as(users.email) // 'users_email'
461
+ const postCount = select`select count(*)::int from ${posts} where ${posts.user_id} = ${users.id}`
311
462
 
312
- as(u.id) // 'u_id'
313
- as(u.email) // 'u_email'
463
+ const q = selectAs`SELECT ${all(users)} ,${expr<number>()(postCount, 'post_count')} FROM ${users}`
464
+ q.text
465
+ // SELECT "u"."id" as "u_id" ,"u"."email" as "u_email"
466
+ // ,(select count(*)::int from "posts" "p" where "p"."user_id" = "u"."id") as "post_count" FROM "users" "u" (wrapped)
467
+ type R = RowOf<typeof q> // { u_id: number; u_email: string; post_count: number }
314
468
  ```
315
469
 
316
- This is particularly useful when mapping over result rows:
470
+ `V` is what your driver hands back, which isn't always what the SQL computes: node-postgres returns `count(*)`, a `bigint`, as a string. Hence the `::int` above.
471
+
472
+ #### Generating the type records from your database
473
+
474
+ Writing the type records by hand means keeping them in step with the database. The `@vanit-co/sql-ts/generate` entry point writes them for you: run its query with your own driver, and turn the rows into a type.
317
475
 
318
476
  ```ts
319
- const rows = await client.query(selectAs`SELECT ${all(users)} FROM ${users}`)
477
+ import { writeFileSync } from 'node:fs'
478
+ import { postgresColumns, generate } from '@vanit-co/sql-ts/generate'
320
479
 
321
- rows.map(row => ({
322
- id: row[as(users.id)], // row['users_id']
323
- email: row[as(users.email)], // row['users_email']
324
- }))
480
+ const { rows } = await pg.query(postgresColumns, [['public']]) // $1: the schemas to read
481
+ writeFileSync('src/db/rows.ts', generate(rows))
325
482
  ```
326
483
 
327
- ---
484
+ ```ts
485
+ // src/db/rows.ts, generated
486
+ export type Rows = {
487
+ users: {
488
+ id: number
489
+ email: string
490
+ created_at: Date
491
+ }
492
+ }
493
+
494
+ // your schema file
495
+ import type { Rows } from './rows'
496
+ const users = schema<Rows['users']>()({ table: 'users', columns: ['id', 'email', 'created_at'], alias: 'u' })
497
+ ```
328
498
 
329
- ## Statement builders: `insert` and `update`
499
+ - The types are what node-postgres returns with its default parsers, which isn't always what the column holds: `int8`, `numeric` and `money` arrive as `string`, `date` and the timestamps as `Date`, `json`/`jsonb` as `unknown`. Arrays follow the same parsers (`numeric[]` arrives as `number[]`), and an array node-postgres has no parser for, enum arrays included, arrives as its text (`string`).
500
+ - If you set your own parsers, or use another driver, override by type name (`udt_name`, with a leading `_` for an array): `generate(rows, { types: { timestamptz: 'string', int8: 'number' } })`.
501
+ - Nullable columns get `| null`, enums become a union of their labels, and a domain is read as its base type. A table is keyed `schema.table` only when you read more than one schema, and `typeName` renames the type (`Rows` by default).
502
+ - Tables and views are read. Materialized views aren't in `information_schema`, so they aren't.
330
503
 
331
- ### `insert(table, ...rows)`
504
+ ### Statement builders: `insert`, `update` and `updateAs`
332
505
 
333
- Builds a parameterised `INSERT` statement. Accepts one or more row objects. Column names from the first row are used; table and column names are properly quoted identifiers (never bind params).
506
+ #### `insert(table, ...rows)`
334
507
 
335
- ```ts
336
- import { schema, insert, raw } from '@vanit-co/sql-ts'
508
+ Builds an `INSERT` from one or more row objects. The columns come from the first row.
337
509
 
338
- const users = schema({ table: 'users', columns: ['id', 'email'] })
510
+ ```ts
511
+ import { insert, raw } from '@vanit-co/sql-ts'
339
512
 
340
- // Single row
341
- const q1 = insert(users, { id: 1, email: 'alice@example.com' })
342
- q1.text // insert into "users" ("id" ,"email") values ($1 ,$2)
343
- q1.values // [1, 'alice@example.com']
513
+ insert(users, { id: 1, email: 'alice@example.com' }).text
514
+ // insert into "users" ("id" ,"email") values ($1 ,$2)
344
515
 
345
- // Multiple rows
346
- const q2 = insert(users,
347
- { id: 1, email: 'alice@example.com' },
348
- { id: 2, email: 'bob@example.com' }
349
- )
350
- q2.text // insert into "users" ("id" ,"email") values ($1 ,$2) ,($3 ,$4)
351
- q2.values // [1, 'alice@example.com', 2, 'bob@example.com']
516
+ const many = insert(users, { id: 1, email: 'alice@example.com' }, { id: 2, email: 'bob@example.com' })
517
+ many.text // insert into "users" ("id" ,"email") values ($1 ,$2) ,($3 ,$4)
518
+ many.values // [1, 'alice@example.com', 2, 'bob@example.com']
352
519
 
353
- // Raw SQL expressions instead of bind params
354
- const q3 = insert(users, { id: raw("nextval('users_id_seq')"), email: 'alice@example.com' })
355
- q3.text // insert into "users" ("id" ,"email") values (nextval('users_id_seq') ,$1)
356
- q3.values // ['alice@example.com']
520
+ // raw SQL instead of a bound value
521
+ const q = insert(users, { id: raw("nextval('users_id_seq')"), email: 'alice@example.com' })
522
+ q.text // insert into "users" ("id" ,"email") values (nextval('users_id_seq') ,$1)
523
+ q.values // ['alice@example.com']
357
524
  ```
358
525
 
359
- Column objects used as values are resolved to quoted identifiers rather than bound. They render unprefixed, since the statement has no alias in scope. Referencing a column inside `values (...)` is only accepted by MySQL; PostgreSQL and SQLite reject it.
526
+ A column used as a value is written as its name rather than bound. Inside `values (...)` only MySQL accepts that; PostgreSQL and SQLite reject it.
360
527
 
361
- ### `update(table, colsVals)`
528
+ #### `update(table, colsVals)`
362
529
 
363
- Builds a parameterised `UPDATE ... SET ...` statement (without a `WHERE` clause - compose that separately using `concat`).
530
+ Builds `UPDATE ... SET ...`; you append the `WHERE`. The table is written without its alias, so build that `WHERE` with the `sql` tag, or use [`updateAs`](#updateastable-colsvals) to use the `where` tag.
364
531
 
365
532
  ```ts
366
- import { schema, update, raw } from '@vanit-co/sql-ts'
533
+ import { update, sql, raw } from '@vanit-co/sql-ts'
534
+
535
+ const q = update(users, { email: 'new@example.com' }).append(sql` WHERE ${users.id} = ${7}`)
536
+ q.text // update "users" set "email" = $1 WHERE "id" = $2
537
+ q.values // ['new@example.com', 7]
367
538
 
368
- const users = schema({ table: 'users', columns: ['id', 'email'] })
539
+ update(users, { id: raw('id + 1'), email: null }).text
540
+ // update "users" set "id" = id + 1 ,"email" = $1 (values: [null])
369
541
 
370
- const q = update(users, { email: 'new@example.com' })
371
- q.text // update "users" set "email" = $1
372
- q.values // ['new@example.com']
542
+ update(users, { email: users.id }).text
543
+ // update "users" set "email" = "id" (a column as the value)
544
+ ```
373
545
 
374
- // Multiple columns
375
- const q2 = update(users, { id: 99, email: 'updated@example.com' })
376
- q2.text // update "users" set "id" = $1 ,"email" = $2
377
- q2.values // [99, 'updated@example.com']
546
+ `undefined` values are left out of the `SET`, and `null` is bound, setting the column to `NULL`.
378
547
 
379
- // Raw SQL expressions instead of bind params
380
- const q3 = update(users, { id: raw('id + 1'), email: 'updated@example.com' })
381
- q3.text // update "users" set "id" = id + 1 ,"email" = $1
382
- q3.values // ['updated@example.com']
548
+ #### `updateAs(table, colsVals)`
383
549
 
384
- // Column objects as values, resolved to quoted identifiers
385
- const q4 = update(users, { email: users.id })
386
- q4.text // update "users" set "email" = "id"
387
- q4.values // []
550
+ The same as `update`, but the table carries its alias, so a `WHERE` built with the `where` tag resolves against it.
551
+
552
+ ```ts
553
+ import { updateAs, where } from '@vanit-co/sql-ts'
554
+
555
+ const q = updateAs(users, { email: 'new@example.com' })
556
+ .append(where` WHERE ${users.id} = ${42}`)
557
+ q.text // update "users" as "u" set "email" = $1 WHERE "u"."id" = $2
558
+ q.sql // update `users` as `u` set `email` = ? WHERE `u`.`id` = ?
559
+ q.values // ['new@example.com', 42]
388
560
  ```
389
561
 
390
- ---
562
+ - The `SET` columns stay unqualified, because PostgreSQL rejects `set "u"."email"`. Columns you append to the `SET` list yourself have to be unqualified as well, so add them with the `sql` tag.
563
+ - `as` is written out because SQLite only accepts the alias with it. PostgreSQL and MySQL accept it either way.
564
+ - A table without an alias uses its name: `update "users" as "users"`.
565
+ - `RETURNING` can name the alias in PostgreSQL (`returning "u"."id"`). SQLite only takes bare column names there, so for SQLite build it with the `sql` tag.
566
+
567
+ ### Composing queries: `append`, `concat` and `empty`
391
568
 
392
- ## Fragment utilities: `concat` and `empty`
569
+ Queries never change once built: `append` returns a new one. That makes them safe to share. A base query can be extended in different ways without one use leaking into another.
393
570
 
394
- ### `concat`
571
+ #### `append` and `concat`
395
572
 
396
- Joins two `Fragment` objects into one. `concat` is curried - `concat(right)(left)` appends `right` after `left`.
573
+ `q.append(fragment)` adds a fragment at the end. `concat(fragment)(q)` does the same as a curried function, which fits `pipe`.
397
574
 
398
575
  ```ts
399
- import { select, where, concat, schema } from '@vanit-co/sql-ts'
576
+ import { select, where, concat } from '@vanit-co/sql-ts'
400
577
 
401
- const users = schema({ table: 'users', columns: ['id', 'email'] })
578
+ const base = select`SELECT ${users.id} FROM ${users}`
402
579
 
403
- const base = select`SELECT ${users.id} FROM ${users}`
404
- const clause = where`WHERE ${users.id} = ${5}`
580
+ base.append(where` WHERE ${users.id} = ${5}`).text
581
+ // SELECT "u"."id" FROM "users" "u" WHERE "u"."id" = $1
405
582
 
406
- const full = concat(clause)(base)
407
- full.text // SELECT "users"."id" FROM "users" "users" WHERE "users"."id" = $1
408
- full.values // [5]
583
+ concat(where` WHERE ${users.id} = ${5}`)(base).text
584
+ // the same
409
585
  ```
410
586
 
411
- You can also use the `.append` method on a `Result`:
587
+ #### `empty`
588
+
589
+ The fragment that adds nothing: the "no filter" branch of a condition, and the starting value when you build a query from a list.
412
590
 
413
591
  ```ts
414
- const full = base.append(where`WHERE ${users.id} = ${5}`)
592
+ import { selectAs, join, where, concat, empty, all } from '@vanit-co/sql-ts'
593
+
594
+ type Filters = { userId?: number; titleLike?: string }
595
+
596
+ const buildPostsQuery = ({ userId, titleLike }: Filters) =>
597
+ [
598
+ selectAs`SELECT ${all(users, posts)} FROM ${posts}`,
599
+ join` JOIN ${users} ON ${posts.user_id} = ${users.id}`,
600
+ where` WHERE true`,
601
+ userId ? where` AND ${users.id} = ${userId}` : empty,
602
+ titleLike ? where` AND ${posts.title} LIKE ${titleLike}` : empty,
603
+ ].reduce((query, clause) => concat(clause)(query), empty)
604
+
605
+ const q = buildPostsQuery({ userId: 7, titleLike: '%TypeScript%' })
606
+ q.text
607
+ // SELECT "u"."id" as "u_id" ,"u"."email" as "u_email" ,"u"."name" as "u_name"
608
+ // ,"p"."id" as "p_id" ,"p"."user_id" as "p_user_id" ,"p"."title" as "p_title"
609
+ // FROM "posts" "p" JOIN "users" "u" ON "p"."user_id" = "u"."id"
610
+ // WHERE true AND "u"."id" = $1 AND "p"."title" LIKE $2 (wrapped)
611
+ q.values // [7, '%TypeScript%']
415
612
  ```
416
613
 
614
+ In math terms, queries form a monoid: `concat` is associative and `empty` is its identity. In practice it means any way of combining fragments (`reduce`, `pipe`, `.append` chains) gives the same query.
417
615
 
418
- **Composing queries with `pipe`**
616
+ #### Fragments inside fragments
419
617
 
420
- Because `concat` is curried, it fits naturally into a `pipe`. Each `concat(fragment)` call becomes one step in the pipeline, appending a fragment to the result of the previous step.
618
+ A fragment can be interpolated into another tag. It is spliced in: its text keeps what its own tag wrote, and its values are numbered among the outer ones. Handy for a condition you reuse.
421
619
 
422
- Using **ramda** (already a dependency of this package):
620
+ ```ts
621
+ import { select, where } from '@vanit-co/sql-ts'
622
+
623
+ const byEmail = where`${users.email} = ${'a@b.com'}`
624
+
625
+ const q = select`SELECT ${users.id} FROM ${users} WHERE ${byEmail} AND ${users.id} > ${10}`
626
+ q.text // SELECT "u"."id" FROM "users" "u" WHERE "u"."email" = $1 AND "u"."id" > $2
627
+ q.values // ['a@b.com', 10]
628
+ ```
629
+
630
+ #### With `pipe`
631
+
632
+ Because `concat` is curried, each `concat(fragment)` is one step of a pipeline. With **ramda** (installed separately; sql-ts doesn't need it):
423
633
 
424
634
  ```ts
425
635
  import { pipe } from 'ramda'
426
- import { schema, selectAs, join, where, concat, all } from '@vanit-co/sql-ts'
427
-
428
- const users = schema({ table: 'users', columns: ['id', 'email'], alias: 'u' })
429
- const posts = schema({ table: 'posts', columns: ['id', 'user_id', 'title'], alias: 'p' })
636
+ import { selectAs, join, where, concat, all } from '@vanit-co/sql-ts'
430
637
 
431
638
  const buildQuery = (userId: number) =>
432
639
  pipe(
433
640
  concat(join` JOIN ${users} ON ${posts.user_id} = ${users.id}`),
434
641
  concat(where` WHERE ${users.id} = ${userId}`)
435
642
  )(selectAs`SELECT ${all(users, posts)} FROM ${posts}`)
436
-
437
- const q = buildQuery(42)
438
- q.text
439
- // SELECT "u"."id" as "u_id" ,"u"."email" as "u_email"
440
- // ,"p"."id" as "p_id" ,"p"."user_id" as "p_user_id" ,"p"."title" as "p_title"
441
- // FROM "posts" "p"
442
- // JOIN "users" "u" ON "p"."user_id" = "u"."id"
443
- // WHERE "u"."id" = $1
444
- q.values // [42]
445
643
  ```
446
644
 
447
- Using **Effect** (`pipe` is data-first, which many find more readable):
645
+ Or with **Effect**, whose `pipe` takes the value first:
448
646
 
449
647
  ```ts
450
648
  import { pipe } from 'effect'
451
- import { schema, selectAs, join, where, concat, all } from '@vanit-co/sql-ts'
452
649
 
453
650
  const q = pipe(
454
651
  selectAs`SELECT ${all(users, posts)} FROM ${posts}`,
@@ -457,98 +654,131 @@ const q = pipe(
457
654
  )
458
655
  ```
459
656
 
460
- ### `empty`
657
+ ### Arrays and `IN` lists
461
658
 
462
- An empty fragment. Acts as the identity element for `concat` - useful as the starting value when accumulating fragments conditionally.
659
+ An array is bound as a single parameter, which is what the drivers expect:
463
660
 
464
661
  ```ts
465
- import { pipe, reduce } from 'ramda'
466
- import { schema, select, join, where, concat, empty, all } from '@vanit-co/sql-ts'
662
+ const ids = [1, 2, 3]
467
663
 
468
- const users = schema({ table: 'users', columns: ['id', 'email'], alias: 'u' })
469
- const posts = schema({ table: 'posts', columns: ['id', 'user_id', 'title'], alias: 'p' })
664
+ // PostgreSQL (node-postgres): use = ANY(...)
665
+ where`WHERE ${users.id} = ANY(${ids})`.text // WHERE "u"."id" = ANY($1) values: [[1, 2, 3]]
470
666
 
471
- type Filters = { userId?: number; titleLike?: string }
667
+ // MySQL (mysql2, with .query): IN (?) expands the array
668
+ where`WHERE ${users.id} IN (${ids})`.sql // WHERE `u`.`id` IN (?) values: [[1, 2, 3]]
669
+ ```
472
670
 
473
- const buildPostsQuery = ({ userId, titleLike }: Filters) => {
474
- const clauses = [
475
- select`SELECT ${all(users, posts)} FROM ${posts}`,
476
- join` JOIN ${users} ON ${posts.user_id} = ${users.id}`,
477
- userId ? where` WHERE ${users.id} = ${userId}` : empty,
478
- titleLike ? where` AND ${posts.title} LIKE ${titleLike}` : empty,
479
- ]
671
+ SQLite drivers don't expand arrays. Bind the list as JSON instead:
480
672
 
481
- return reduce(
482
- (acc, clause) => concat(clause)(acc),
483
- empty,
484
- clauses
485
- )
486
- }
673
+ ```ts
674
+ sql`WHERE ${users.id} IN (SELECT value FROM json_each(${JSON.stringify(ids)}))`.sql
675
+ // WHERE `id` IN (SELECT value FROM json_each(?)) values: ['[1,2,3]']
676
+ ```
487
677
 
488
- const q = buildPostsQuery({ userId: 7, titleLike: '%TypeScript%' })
489
- q.text
490
- // SELECT "u"."id" as "u_id" ,"u"."email" as "u_email"
491
- // ,"p"."id" as "p_id" ,"p"."user_id" as "p_user_id" ,"p"."title" as "p_title"
492
- // FROM "posts" "p"
493
- // JOIN "users" "u" ON "p"."user_id" = "u"."id"
494
- // WHERE "u"."id" = $1
495
- // AND "p"."title" LIKE $2
496
- q.values // [7, '%TypeScript%']
678
+ ### Raw SQL: `raw`
679
+
680
+ `raw` puts a piece of SQL text in exactly as written, never bound. It is how you write what a value can't be: a function call, a sequence, an expression. **Only pass it strings you wrote yourself, never user input.**
681
+
682
+ ```ts
683
+ import { sql, raw } from '@vanit-co/sql-ts'
684
+
685
+ const q = sql`SELECT ${raw('COUNT(*)')} AS total FROM ${users}`
686
+ q.text // SELECT COUNT(*) AS total FROM "users"
687
+ q.values // []
497
688
  ```
498
689
 
499
- ---
690
+ `raw` works anywhere a value does, including the values you pass to `insert`, `update` and `updateAs`.
500
691
 
501
- ## Dialect functions: `toMysql` and `toPostgres`
692
+ ### Prepared statements: `preparedStatementName`
502
693
 
503
- Convert any `Fragment` directly to a dialect-specific result. The template tags already expose `.sql` and `.text` on their return value, but you can call these directly when working with raw fragments.
694
+ Gives a query a name, for node-postgres' named prepared statements (`{ name, text, values }`). It returns a new query and leaves the original alone.
504
695
 
505
696
  ```ts
506
- import { toMysql, toPostgres } from '@vanit-co/sql-ts'
697
+ import { sql, all, preparedStatementName } from '@vanit-co/sql-ts'
507
698
 
508
- const result = toPostgres(someFragment)
509
- // { text: 'SELECT ... WHERE id = $1', values: [42] }
699
+ const q = preparedStatementName(sql`SELECT ${all(users)} FROM ${users} WHERE ${users.id} = ${1}`, 'get-user-by-id')
700
+ q.name // 'get-user-by-id'
701
+ q.text // SELECT "id" ,"email" ,"name" FROM "users" WHERE "id" = $1
702
+ q.values // [1]
510
703
 
511
- const mysqlResult = toMysql(someFragment)
512
- // { sql: 'SELECT ... WHERE id = ?', values: [42] }
704
+ await client.query(q)
705
+ ```
706
+
707
+ ### Dialect functions: `toPostgres` and `toMysql`
708
+
709
+ `.text` and `.sql` are these two functions. Call them directly if you hold a bare `Fragment` (`{ strings, binds }`) rather than a query.
710
+
711
+ ```ts
712
+ import { sql, toPostgres, toMysql } from '@vanit-co/sql-ts'
713
+
714
+ const f = sql`SELECT ${users.id} FROM ${users} WHERE ${users.id} = ${42}`
715
+
716
+ toPostgres(f) // { text: 'SELECT "id" FROM "users" WHERE "id" = $1', values: [42] }
717
+ toMysql(f) // { sql: 'SELECT `id` FROM `users` WHERE `id` = ?', values: [42] }
513
718
  ```
514
719
 
515
720
  ---
516
721
 
517
- ## Escaping and raw SQL: `raw`
722
+ ## Safety
723
+
724
+ sql-ts is built so that the easy way to write a query is also the safe way:
518
725
 
519
- By default, every interpolated value is treated as a bind parameter. Use `raw` to inject an unescaped SQL snippet directly into the query string. **Only use `raw` with trusted, static strings.**
726
+ - **Values are always bound.** Anything you interpolate that isn't a schema table, a column, a helper or another query is sent as a parameter, never as SQL text. A malicious string stays a string.
727
+ - **Names are quoted and escaped.** Table and column names come from your schema, and quotes inside them are doubled, so even an odd name can't end the identifier early.
728
+ - **`raw` is the only door for text.** It is the one way to put text into the SQL itself, and it is meant for strings you wrote, never for user input.
520
729
 
521
730
  ```ts
522
- import { sql, raw } from '@vanit-co/sql-ts'
731
+ const name = "'; DROP TABLE users; --"
523
732
 
524
- const q = sql`SELECT ${raw('COUNT(*)')} AS total FROM users`
525
- q.text // SELECT COUNT(*) AS total FROM users
526
- q.values // []
733
+ const q = sql`SELECT ${users.id} FROM ${users} WHERE ${users.email} = ${name}`
734
+ q.text // SELECT "id" FROM "users" WHERE "email" = $1
735
+ q.values // ["'; DROP TABLE users; --"] (just a value)
527
736
  ```
528
737
 
529
- `raw` works anywhere a value is accepted, including the column values passed to `insert` and `update`.
530
-
531
738
  ---
532
739
 
533
- ## Prepared statements: `preparedStatementName`
740
+ ## Common pitfalls
534
741
 
535
- Attach a name to a `Result` for use with named prepared statements (e.g., `pg`'s `{ name, text, values }` query format).
742
+ **Start every appended fragment with a space.** `append` joins the text as-is, so a missing space glues words together:
536
743
 
537
744
  ```ts
538
- import { sql, preparedStatementName } from '@vanit-co/sql-ts'
745
+ select`SELECT ${users.id} FROM ${users}`.append(where`WHERE ${users.id} = ${1}`).text
746
+ // SELECT "u"."id" FROM "users" "u"WHERE "u"."id" = $1 ← broken
539
747
 
540
- const q = sql`SELECT * FROM ${users} WHERE id = ${1}`
541
- const named = preparedStatementName(q, 'get-user-by-id')
748
+ select`SELECT ${users.id} FROM ${users}`.append(where` WHERE ${users.id} = ${1}`).text
749
+ // SELECT "u"."id" FROM "users" "u" WHERE "u"."id" = $1 ← fine
750
+ ```
542
751
 
543
- named.name // 'get-user-by-id'
544
- named.text // SELECT * FROM users WHERE id = $1
545
- named.values // [1]
752
+ **Use `selectAs` for the select list only.** It names every column it writes, so in an `ORDER BY` or a `WHERE` the `as` is a syntax error. Append the rest with `orderBy`, `where` and friends:
546
753
 
547
- // Pass to pg:
548
- await client.query(named)
754
+ ```ts
755
+ selectAs`SELECT ${all(users)} FROM ${users} ORDER BY ${users.id}`.text
756
+ // ... ORDER BY "u"."id" as "u_id" ← broken
757
+
758
+ selectAs`SELECT ${all(users)} FROM ${users}`.append(orderBy` ORDER BY ${users.id}`).text
759
+ // ... ORDER BY "u"."id" ← fine
549
760
  ```
550
761
 
551
- `preparedStatementName` does not mutate the original result - it returns a new object.
762
+ **After `update`, build the `WHERE` with `sql`, or use `updateAs`.** `update` writes the table without its alias, so the `where` tag's `"u"."id"` refers to nothing:
763
+
764
+ ```ts
765
+ update(users, { name: 'Ada' }).append(where` WHERE ${users.id} = ${1}`).text
766
+ // update "users" set "name" = $1 WHERE "u"."id" = $2 ← broken
767
+
768
+ update(users, { name: 'Ada' }).append(sql` WHERE ${users.id} = ${1}`).text
769
+ // update "users" set "name" = $1 WHERE "id" = $2 ← fine
770
+
771
+ updateAs(users, { name: 'Ada' }).append(where` WHERE ${users.id} = ${1}`).text
772
+ // update "users" as "u" set "name" = $1 WHERE "u"."id" = $2 ← fine
773
+ ```
774
+
775
+ **node-postgres returns big numbers as strings.** `bigint` (including `count(*)`) and `numeric` columns arrive as strings, so they can't lose precision. Cast in SQL (`count(*)::int`) or convert in code.
776
+
777
+ **With SQLite, use `.sql` and keep `RETURNING` unqualified.** SQLite reads `$1` as a named parameter, so `.text` leaves the values unbound. And its `RETURNING` only takes bare column names, so build it with the `sql` tag.
778
+
779
+ **`undefined` and `null` are not the same.** An `undefined` interpolation, or an `undefined` column in `insert`/`update`, is left out. `null` is bound and becomes `NULL`.
780
+
781
+ **Arrays bind as one parameter.** In PostgreSQL write `= ANY(${ids})`, not `IN (${ids})`. See [Arrays and `IN` lists](#arrays-and-in-lists).
552
782
 
553
783
  ---
554
784