@vanit-co/sql-ts 1.1.0 → 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
@@ -8,15 +8,20 @@
8
8
 
9
9
  **Write plain SQL. Get quoted identifiers, qualified columns and bound parameters for free. Compose queries like data.**
10
10
 
11
- A TypeScript SQL builder using tagged template literals. No DSL to learn, no magic, no ORM. **Zero dependencies, ~2 KB gzipped, ESM and CommonJS.**
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:
12
12
 
13
- Supports **PostgreSQL** (`$n` placeholders, `"` identifiers), **MySQL** (`?` placeholders, `` ` `` identifiers) and **SQLite** (through the MySQL format, see [Result object](#result-object)), all from the same query.
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.
17
+
18
+ Zero dependencies, under 2 KB minified and gzipped, ESM and CommonJS. Works with **PostgreSQL**, **MySQL** and **SQLite**, all from the same query.
14
19
 
15
20
  ```sh
16
21
  npm install @vanit-co/sql-ts
17
22
  ```
18
23
 
19
- ### In 30 seconds
24
+ ## In 30 seconds
20
25
 
21
26
  Without it, you hand-qualify every column, alias every result key to avoid collisions, and track placeholder numbers yourself:
22
27
 
@@ -42,496 +47,605 @@ const postsQuery = (userId?: number) =>
42
47
 
43
48
  const q = postsQuery(7)
44
49
  q.text // SELECT "u"."id" as "u_id" ,"u"."email" as "u_email" ,"p"."id" as "p_id" ... WHERE "u"."id" = $1
45
- q.sql // same query for MySQL / SQLite: `u`.`id` ... WHERE `u`.`id` = ?
50
+ q.sql // the same query for MySQL and SQLite: SELECT `u`.`id` as `u_id` ... WHERE `u`.`id` = ?
46
51
  q.values // [7]
47
52
 
48
53
  await pg.query(q) // node-postgres reads { text, values }
49
54
  ```
50
55
 
51
- A typo like `users.emial` is a compile error, and every query is an immutable value you can pass around, `reduce` over or `pipe` through.
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)
52
77
 
53
- ### How it compares
78
+ ---
54
79
 
55
- | | sql-ts | [sql-template-tag](https://github.com/blakeembrey/sql-template-tag) | [slonik](https://github.com/gajus/slonik) | [kysely](https://kysely.dev) |
56
- |-----------------------------------------|:------:|:----------------:|:------:|:------:|
57
- | Plain SQL is the primary API | ✅ | ✅ | ✅ | ❌ (method-chain DSL) |
58
- | Identifiers quoted from a typed schema | ✅ | ❌ | manual `sql.identifier` | ✅ |
59
- | Automatic `alias.column` / `AS alias_column` | ✅ | ❌ | ❌ | ❌ |
60
- | One query → PostgreSQL *and* MySQL/SQLite | ✅ | ✅ | ❌ (PostgreSQL only) | per-dialect instance |
61
- | Composable as a monoid (`concat` / `empty`) | ✅ | partial (`join`, `empty`) | ❌ | ❌ |
62
- | Executes queries itself (wraps the driver) | ❌ (use your driver) | ❌ | ✅ | ✅ |
80
+ ## Getting started
63
81
 
64
- 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.
82
+ Six short steps, from describing your tables to writing data. The examples build on each other.
83
+
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.
65
87
 
66
- ## Why this library?
88
+ ```ts
89
+ import { schema } from '@vanit-co/sql-ts'
67
90
 
68
- Writing raw SQL in TypeScript runs into a set of recurring friction points that this library addresses directly:
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' })
69
93
 
70
- - **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.
94
+ users.email // a column you can interpolate; users.emial is a compile error
95
+ ```
71
96
 
72
- - **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.
97
+ ### 2. Write a query
73
98
 
74
- - **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.
99
+ Write SQL as usual and interpolate the schema and your values. Tables and columns become quoted names; values become placeholders.
75
100
 
76
- - **`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.
101
+ ```ts
102
+ import { select, where } from '@vanit-co/sql-ts'
103
+
104
+ const q = select`SELECT ${users.id}, ${users.email} FROM ${users}`
105
+ .append(where` WHERE ${users.email} = ${'ada@example.com'}`)
77
106
 
78
- - **`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.
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']
110
+ ```
79
111
 
80
- ## Quick 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.
81
113
 
82
- **sql** tag takes care of quoting the identifiers (tables and columns) with the proper quotes `` ` `` for MySQL and `"` for PostgreSQL.
114
+ ### 3. Run it
115
+
116
+ Hand the query to your driver. sql-ts never opens a connection.
83
117
 
84
118
  ```ts
85
- import { schema, sql, all } from '@vanit-co/sql-ts'
119
+ // node-postgres: reads .text and .values
120
+ const { rows } = await client.query(q)
121
+
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
+ ```
86
128
 
87
- const users = schema({ table: 'users', columns: ['id', 'email'] })
129
+ ### 4. Read the rows
88
130
 
89
- const query = sql`SELECT ${all(users)} FROM ${users} WHERE ${users.id} = ${42}`
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.
90
132
 
91
- // PostgreSQL
92
- console.log(query.text) // SELECT "id" ,"email" FROM "users" WHERE "id" = $1
133
+ ```ts
134
+ import { selectAs, join, all, as } from '@vanit-co/sql-ts'
93
135
 
94
- // MySQL
95
- console.log(query.sql) // SELECT `id` ,`email` FROM `users` WHERE `id` = ?
136
+ const q = selectAs`SELECT ${all(users, posts)} FROM ${posts}`
137
+ .append(join` JOIN ${users} ON ${users.id} = ${posts.user_id}`)
96
138
 
97
- console.log(query.values) // [42]
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
+ }))
98
149
  ```
99
150
 
100
- ## Full query example
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).
101
152
 
102
- **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`.
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.
103
156
 
104
157
  ```ts
105
- import { schema, select, selectAs, join, where, all, insert, update, empty } from '@vanit-co/sql-ts'
158
+ import { selectAs, where, orderBy, all, empty } from '@vanit-co/sql-ts'
106
159
 
107
- const users = schema({ table: 'users', columns: ['id', 'email'], alias: 'u' })
108
- const posts = schema({ table: 'posts', columns: ['id', 'user_id', 'title'], alias: 'p' })
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`)
109
166
 
110
- 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)
111
170
 
112
- // SELECT with JOIN
113
- const query = selectAs`SELECT ${all(users, posts)} FROM ${posts}`
114
- .append(join`JOIN ${users} ON ${posts.user_id} = ${users.id}`)
115
- .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
116
177
 
117
- query.text
118
- // 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"
119
- // FROM "posts" "p"
120
- // JOIN "users" "u" ON "p"."user_id" = "u"."id"
121
- // WHERE "u"."id" = $1
122
- 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.
123
179
 
124
- // INSERT
125
- const ins = insert(users, { id: 1, email: 'alice@example.com' })
126
- ins.text // insert into "users" ("id" ,"email") values ($1 ,$2)
127
- 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']
128
187
 
129
- // UPDATE
130
- const upd = update(users, { email: 'new@example.com' }).append(sql` where ${users.id} = ${id}`)
131
- upd.text // update "users" set "email" = $1 where "id" = $2
132
- 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]
133
192
  ```
134
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
+
135
198
  ---
136
199
 
137
- ## Core concepts
200
+ ## Which tag do I use?
138
201
 
139
- ### 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
+ ---
140
219
 
141
- Define your tables once. The schema carries table and column metadata used by the template tags to produce properly quoted, prefixed identifiers.
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
+ ---
234
+
235
+ ## Reference
236
+
237
+ Unless an example declares its own, the examples below use these two tables:
142
238
 
143
239
  ```ts
144
240
  import { schema } from '@vanit-co/sql-ts'
145
241
 
146
- const users = schema({ table: 'users', columns: ['id', 'email'] })
147
-
148
- // With a table alias (useful for self-joins or verbose table names)
149
- 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' })
150
244
  ```
151
245
 
152
- `schema` takes:
246
+ ### Schema
247
+
248
+ `schema` describes a table once, for every query that uses it.
249
+
153
250
  | field | type | description |
154
251
  |-------|------|-------------|
155
- | `table` | `string` | The actual table name in the database |
156
- | `columns` | `string[]` | Column names to expose as typed properties |
157
- | `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` |
255
+
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.
158
257
 
159
- After calling `schema`, the returned object has a typed property for each column (`users.id`, `users.email`, etc.).
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).
160
259
 
161
- #### Multiple aliases for the same table: `alias`
260
+ #### The same table twice: `alias`
162
261
 
163
- `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.
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.
164
263
 
165
264
  ```ts
166
265
  import { schema, alias, selectAs, join, pick } from '@vanit-co/sql-ts'
167
266
 
168
- const users = schema({ table: 'users', columns: ['id', 'email'] })
169
- 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' })
170
269
 
171
- const author = alias(users, 'author')
172
- const reviewer = alias(users, 'reviewer')
270
+ const author = alias(people, 'author')
271
+ const reviewer = alias(people, 'reviewer')
173
272
 
174
- const q = selectAs`SELECT ${pick(author.email, reviewer.email)} FROM ${posts}`
175
- .append(join` JOIN ${author} ON ${posts.author_id} = ${author.id}`)
176
- .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}`)
177
276
 
178
277
  q.text
179
- // SELECT "author"."email" as "author_email" ,"reviewer"."email" as "reviewer_email" FROM "posts" "p"
180
- // JOIN "users" "author" ON "p"."author_id" = "author"."id"
181
- // 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)
182
281
  ```
183
282
 
184
- ---
185
-
186
- ### Result object
283
+ ### The result object
187
284
 
188
- 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:
189
286
 
190
287
  | property | description |
191
288
  |----------|-------------|
192
- | `.sql` | Query string in MySQL format (`?` placeholders, backtick-quoted identifiers), also used for SQLite |
193
- | `.text` | Query string in PostgreSQL format (`$n` placeholders, double-quote identifiers) |
194
- | `.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) |
195
294
 
196
- 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.
197
296
 
198
297
  ```ts
199
- // node-postgres (pg)
200
- await client.query(query)
201
-
202
- // mysql2
203
- await connection.query(query)
204
-
205
- // better-sqlite3 / node:sqlite
206
- 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
207
301
  ```
208
302
 
209
- 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.
210
-
211
- ---
212
-
213
- ## Template tag functions
303
+ ### Template tags
214
304
 
215
- ### `sql`
305
+ #### `sql`
216
306
 
217
- 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.
218
308
 
219
309
  ```ts
220
310
  import { sql } from '@vanit-co/sql-ts'
221
311
 
222
- const users = schema({ table: 'users', columns: ['id', 'email'] })
223
-
224
- // Plain values → bind parameters
225
- const q1 = sql`SELECT * FROM users WHERE id = ${42}`
226
- q1.text // SELECT * FROM users WHERE id = $1
227
- q1.values // [42]
228
-
229
- // Schema table → quoted identifier (name only)
230
- const q2 = sql`FROM ${users}`
231
- q2.text // FROM "users"
232
-
233
- // Schema column → quoted identifier (name only, no prefix)
234
- const q3 = sql`SELECT ${users.id}`
235
- q3.text // SELECT "id"
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]
236
315
  ```
237
316
 
238
- ### `select` (alias: `s`)
317
+ #### `select` (short: `s`)
239
318
 
240
- 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.
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.
241
320
 
242
321
  ```ts
243
- import { select, s, schema } from '@vanit-co/sql-ts'
322
+ import { select } from '@vanit-co/sql-ts'
244
323
 
245
- const users = schema({ table: 'users', columns: ['id', 'email'] })
246
- const u = schema({ table: 'users', columns: ['id', 'email'], alias: 'u' })
324
+ select`SELECT ${users.email} FROM ${users}`.text
325
+ // SELECT "u"."email" FROM "users" "u"
326
+ ```
247
327
 
248
- // Table → name + alias
249
- select`FROM ${users}`.text // FROM "users" "users"
250
- select`FROM ${u}`.text // FROM "users" "u"
328
+ #### `selectAs` (short: `sa`)
251
329
 
252
- // Column → alias.column
253
- select`SELECT ${users.email}`.text // SELECT "users"."email"
254
- select`SELECT ${u.email}`.text // SELECT "u"."email"
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)).
255
331
 
256
- // Mix with values
257
- select`SELECT ${users.id} WHERE id = ${7}`.text // SELECT "users"."id" WHERE id = $1
258
- select`SELECT ${users.id} WHERE id = ${7}`.values // [7]
332
+ ```ts
333
+ import { selectAs } from '@vanit-co/sql-ts'
259
334
 
260
- // Short alias
261
- s`SELECT ${users.id}`.text // SELECT "users"."id"
335
+ selectAs`SELECT ${users.email} FROM ${users}`.text
336
+ // SELECT "u"."email" as "u_email" FROM "users" "u"
262
337
  ```
263
338
 
264
- ### `selectAs` (alias: `sa`)
339
+ #### `where`, `join`, `orderBy`, `groupBy`, `having`
265
340
 
266
- 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.
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`.
267
342
 
268
343
  ```ts
269
- import { selectAs, sa, schema } from '@vanit-co/sql-ts'
270
-
271
- const users = schema({ table: 'users', columns: ['id', 'email'] })
272
- const u = schema({ table: 'users', columns: ['id', 'email'], alias: 'u' })
344
+ import { select, join, where, groupBy, having, orderBy } from '@vanit-co/sql-ts'
273
345
 
274
- selectAs`SELECT ${users.id}`.text // SELECT "users"."id" as "users_id"
275
- selectAs`SELECT ${users.email}`.text // SELECT "users"."email" as "users_email"
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}`)
276
352
 
277
- // With alias
278
- sa`SELECT ${u.email}`.text // SELECT "u"."email" as "u_email"
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]
279
357
  ```
280
358
 
281
- ### `groupBy` (alias: `g`), `having` (alias: `h`), `join` (alias: `j`), `orderBy` (alias: `o`) and `where` (alias: `w`)
359
+ ### Column helpers: `all`, `pick` and `as`
360
+
361
+ #### `all(...tables)`
282
362
 
283
- 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.
363
+ Expands every column of one or more tables, written the way the surrounding tag writes columns.
284
364
 
285
365
  ```ts
286
- import { select, join, j, where, w, groupBy, g, having, h, orderBy, o, schema } from '@vanit-co/sql-ts'
366
+ import { select, selectAs, all } from '@vanit-co/sql-ts'
287
367
 
288
- const posts = schema({ table: 'posts', columns: ['id', 'user_id', 'title'] })
289
- const users = schema({ table: 'users', columns: ['id', 'email'] })
368
+ select`SELECT ${all(users)}`.text
369
+ // SELECT "u"."id" ,"u"."email" ,"u"."name"
290
370
 
291
- const q = select`SELECT ${posts.title}, ${users.email}`
292
- const fromClause = join` FROM ${posts}`
293
- const joinClause = join` JOIN ${users} ON ${posts.user_id} = ${users.id}`
294
- const whereClause = where` WHERE ${users.id} = ${99}`
295
- const groupClause = groupBy` GROUP BY ${posts.title}`
296
- const havingClause = having` HAVING COUNT(${posts.id}) > ${1}`
297
- const orderClause = orderBy` ORDER BY ${posts.title}`
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)
298
374
  ```
299
375
 
300
- ---
301
-
302
- ## Column helpers: `all` and `pick`
376
+ #### `pick(...columns)`
303
377
 
304
- Use these inside any template tag to expand multiple columns at once.
378
+ Expands only the columns you name, from any tables.
305
379
 
306
- ### `all(...tables)`
380
+ ```ts
381
+ import { selectAs, pick } from '@vanit-co/sql-ts'
307
382
 
308
- Expands every column from one or more schema tables.
383
+ selectAs`SELECT ${pick(users.email, posts.title)}`.text
384
+ // SELECT "u"."email" as "u_email" ,"p"."title" as "p_title"
385
+ ```
309
386
 
310
- ```ts
311
- import { select, selectAs, schema, all } from '@vanit-co/sql-ts'
387
+ #### `as(column)`
312
388
 
313
- const users = schema({ table: 'users', columns: ['id', 'email'] })
314
- const posts = schema({ table: 'posts', columns: ['title', 'body'] })
389
+ The key `selectAs` gives a column in the result, so you read rows without spelling `'u_email'` by hand.
315
390
 
316
- // Single table
317
- select`SELECT ${all(users)}`.text
318
- // SELECT "users"."id" ,"users"."email"
391
+ ```ts
392
+ import { as } from '@vanit-co/sql-ts'
319
393
 
320
- // Multiple tables
321
- select`SELECT ${all(users, posts)}`.text
322
- // SELECT "users"."id" ,"users"."email" ,"posts"."title" ,"posts"."body"
394
+ as(users.email) // 'u_email'
395
+ as(posts.title) // 'p_title'
323
396
 
324
- // With selectAs for aliased columns
325
- selectAs`SELECT ${all(users)}`.text
326
- // SELECT "users"."id" as "users_id" ,"users"."email" as "users_email"
397
+ const { rows } = await client.query(q)
398
+ rows.map(row => row[as(users.email)])
327
399
  ```
328
400
 
329
- ### `pick(...columns)`
401
+ ### Typed result rows
330
402
 
331
- Expands a specific subset of columns from any 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.
332
404
 
333
405
  ```ts
334
- import { select, selectAs, schema, pick } from '@vanit-co/sql-ts'
406
+ import { schema, selectAs, join, all, as, type RowOf } from '@vanit-co/sql-ts'
335
407
 
336
- const users = schema({ table: 'users', columns: ['id', 'email', 'name'] })
337
- 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' })
338
410
 
339
- // Pick from one table
340
- select`SELECT ${pick(users.id, users.email)}`.text
341
- // 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}`)
342
413
 
343
- // Pick from different tables
344
- select`SELECT ${pick(users.id, posts.title)}`.text
345
- // SELECT "users"."id" ,"posts"."title"
414
+ type Row = RowOf<typeof q>
415
+ // { u_id: number; u_email: string; p_id: number; p_user_id: number; p_title: string | null }
346
416
 
347
- // With selectAs
348
- selectAs`SELECT ${pick(users.id, users.email)}`.text
349
- // 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'
350
420
  ```
351
421
 
352
- ### `as(column)`
422
+ The examples in this section use these typed `users` and `posts`.
353
423
 
354
- 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.
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.
427
+
428
+ #### What a query's row contains: `RowOf`
429
+
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.
355
436
 
356
437
  ```ts
357
- import { schema, as, selectAs, all } from '@vanit-co/sql-ts'
438
+ import { select, selectAs, where, all, pick, type RowOf } from '@vanit-co/sql-ts'
358
439
 
359
- const users = schema({ table: 'users', columns: ['id', 'email'] })
360
- const u = schema({ table: 'users', columns: ['id', 'email'], alias: 'u' })
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 }
361
443
 
362
- as(users.id) // 'users_id'
363
- as(users.email) // 'users_email'
444
+ const q2 = select`SELECT ${pick(users.email)} FROM ${users}`
445
+ type R2 = RowOf<typeof q2> // { email: string }
364
446
 
365
- as(u.id) // 'u_id'
366
- as(u.email) // 'u_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
367
450
  ```
368
451
 
369
- This is particularly useful when mapping over result rows:
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.
453
+
454
+ #### Computed columns: `expr`
455
+
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.
370
457
 
371
458
  ```ts
372
- const rows = await client.query(selectAs`SELECT ${all(users)} FROM ${users}`)
459
+ import { selectAs, select, all, expr, type RowOf } from '@vanit-co/sql-ts'
373
460
 
374
- rows.map(row => ({
375
- id: row[as(users.id)], // row['users_id']
376
- email: row[as(users.email)], // row['users_email']
377
- }))
461
+ const postCount = select`select count(*)::int from ${posts} where ${posts.user_id} = ${users.id}`
462
+
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 }
378
468
  ```
379
469
 
380
- ---
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.
381
471
 
382
- ## Typed result rows
472
+ #### Generating the type records from your database
383
473
 
384
- Pass a type record to `schema` (note the extra `()`) and the library can derive the row type of your queries. This is opt-in: plain `schema({...})` works exactly as before.
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.
385
475
 
386
476
  ```ts
387
- import { schema, selectAs, join, all, as, type SelectAsRow, type Row } from '@vanit-co/sql-ts'
477
+ import { writeFileSync } from 'node:fs'
478
+ import { postgresColumns, generate } from '@vanit-co/sql-ts/generate'
388
479
 
389
- const users = schema<{ id: number; email: string }>()({ table: 'users', columns: ['id', 'email'], alias: 'u' })
390
- const posts = schema<{ id: number; user_id: number; title: string | null }>()({ table: 'posts', columns: ['id', 'user_id', 'title'], alias: 'p' })
391
-
392
- // selectAs keys: alias_column
393
- type PostWithAuthor = SelectAsRow<typeof users | typeof posts>
394
- // { u_id: number; u_email: string; p_id: number; p_user_id: number; p_title: string | null }
480
+ const { rows } = await pg.query(postgresColumns, [['public']]) // $1: the schemas to read
481
+ writeFileSync('src/db/rows.ts', generate(rows))
482
+ ```
395
483
 
396
- const q = selectAs`SELECT ${all(users, posts)} FROM ${posts}`
397
- .append(join` JOIN ${users} ON ${posts.user_id} = ${users.id}`)
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
+ }
398
493
 
399
- const { rows } = await pg.query<PostWithAuthor>(q)
400
- rows[0][as(posts.title)] // string | null, and as(posts.title) is typed as 'p_title'
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' })
401
497
  ```
402
498
 
403
- - `SelectAsRow<...>` takes tables or single columns (`typeof users.email | typeof posts.title`), matching `all(...)` and `pick(...)`.
404
- - `Row<typeof users>` gives bare column names (`{ id: number; email: string }`), matching `sql` / `select`.
405
- - `columns` must be keys of the type record, so `columns: ['id', 'emial']` is a compile error.
406
- - `alias(users, 'author')` keeps the types and re-prefixes the keys (`author_id`, ...).
407
-
408
- ---
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.
409
503
 
410
- ## Statement builders: `insert` and `update`
504
+ ### Statement builders: `insert`, `update` and `updateAs`
411
505
 
412
- ### `insert(table, ...rows)`
506
+ #### `insert(table, ...rows)`
413
507
 
414
- 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).
508
+ Builds an `INSERT` from one or more row objects. The columns come from the first row.
415
509
 
416
510
  ```ts
417
- import { schema, insert, raw } from '@vanit-co/sql-ts'
418
-
419
- const users = schema({ table: 'users', columns: ['id', 'email'] })
511
+ import { insert, raw } from '@vanit-co/sql-ts'
420
512
 
421
- // Single row
422
- const q1 = insert(users, { id: 1, email: 'alice@example.com' })
423
- q1.text // insert into "users" ("id" ,"email") values ($1 ,$2)
424
- 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)
425
515
 
426
- // Multiple rows
427
- const q2 = insert(users,
428
- { id: 1, email: 'alice@example.com' },
429
- { id: 2, email: 'bob@example.com' }
430
- )
431
- q2.text // insert into "users" ("id" ,"email") values ($1 ,$2) ,($3 ,$4)
432
- 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']
433
519
 
434
- // Raw SQL expressions instead of bind params
435
- const q3 = insert(users, { id: raw("nextval('users_id_seq')"), email: 'alice@example.com' })
436
- q3.text // insert into "users" ("id" ,"email") values (nextval('users_id_seq') ,$1)
437
- 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']
438
524
  ```
439
525
 
440
- 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.
441
527
 
442
- ### `update(table, colsVals)`
528
+ #### `update(table, colsVals)`
443
529
 
444
- 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.
445
531
 
446
532
  ```ts
447
- 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]
538
+
539
+ update(users, { id: raw('id + 1'), email: null }).text
540
+ // update "users" set "id" = id + 1 ,"email" = $1 (values: [null])
448
541
 
449
- const users = schema({ table: 'users', columns: ['id', 'email'] })
542
+ update(users, { email: users.id }).text
543
+ // update "users" set "email" = "id" (a column as the value)
544
+ ```
545
+
546
+ `undefined` values are left out of the `SET`, and `null` is bound, setting the column to `NULL`.
450
547
 
451
- const q = update(users, { email: 'new@example.com' })
452
- q.text // update "users" set "email" = $1
453
- q.values // ['new@example.com']
548
+ #### `updateAs(table, colsVals)`
454
549
 
455
- // Multiple columns
456
- const q2 = update(users, { id: 99, email: 'updated@example.com' })
457
- q2.text // update "users" set "id" = $1 ,"email" = $2
458
- q2.values // [99, 'updated@example.com']
550
+ The same as `update`, but the table carries its alias, so a `WHERE` built with the `where` tag resolves against it.
459
551
 
460
- // Raw SQL expressions instead of bind params
461
- const q3 = update(users, { id: raw('id + 1'), email: 'updated@example.com' })
462
- q3.text // update "users" set "id" = id + 1 ,"email" = $1
463
- q3.values // ['updated@example.com']
552
+ ```ts
553
+ import { updateAs, where } from '@vanit-co/sql-ts'
464
554
 
465
- // Column objects as values, resolved to quoted identifiers
466
- const q4 = update(users, { email: users.id })
467
- q4.text // update "users" set "email" = "id"
468
- q4.values // []
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]
469
560
  ```
470
561
 
471
- ---
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.
472
566
 
473
- ## Composing queries (functional by design): `concat` and `empty`
567
+ ### Composing queries: `append`, `concat` and `empty`
474
568
 
475
- Every tag and statement builder returns an immutable value, and fragments form a monoid: `concat` is associative and `empty` is its identity. Query building becomes ordinary data transformation, so it works with `reduce`, `pipe` (ramda, Effect, fp-ts) or plain `.append` chains.
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.
476
570
 
477
- ### `concat`
571
+ #### `append` and `concat`
478
572
 
479
- 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`.
480
574
 
481
575
  ```ts
482
- import { select, where, concat, schema } from '@vanit-co/sql-ts'
576
+ import { select, where, concat } from '@vanit-co/sql-ts'
483
577
 
484
- const users = schema({ table: 'users', columns: ['id', 'email'] })
578
+ const base = select`SELECT ${users.id} FROM ${users}`
485
579
 
486
- const base = select`SELECT ${users.id} FROM ${users}`
487
- 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
488
582
 
489
- const full = concat(clause)(base)
490
- full.text // SELECT "users"."id" FROM "users" "users" WHERE "users"."id" = $1
491
- full.values // [5]
583
+ concat(where` WHERE ${users.id} = ${5}`)(base).text
584
+ // the same
492
585
  ```
493
586
 
494
- 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.
495
590
 
496
591
  ```ts
497
- 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%']
498
612
  ```
499
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.
615
+
616
+ #### Fragments inside fragments
500
617
 
501
- **Composing queries with `pipe`**
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.
502
619
 
503
- 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.
620
+ ```ts
621
+ import { select, where } from '@vanit-co/sql-ts'
504
622
 
505
- Using **ramda** (`npm install ramda`, not needed by this package itself):
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):
506
633
 
507
634
  ```ts
508
635
  import { pipe } from 'ramda'
509
- import { schema, selectAs, join, where, concat, all } from '@vanit-co/sql-ts'
510
-
511
- const users = schema({ table: 'users', columns: ['id', 'email'], alias: 'u' })
512
- const posts = schema({ table: 'posts', columns: ['id', 'user_id', 'title'], alias: 'p' })
636
+ import { selectAs, join, where, concat, all } from '@vanit-co/sql-ts'
513
637
 
514
638
  const buildQuery = (userId: number) =>
515
639
  pipe(
516
640
  concat(join` JOIN ${users} ON ${posts.user_id} = ${users.id}`),
517
641
  concat(where` WHERE ${users.id} = ${userId}`)
518
642
  )(selectAs`SELECT ${all(users, posts)} FROM ${posts}`)
519
-
520
- const q = buildQuery(42)
521
- q.text
522
- // SELECT "u"."id" as "u_id" ,"u"."email" as "u_email"
523
- // ,"p"."id" as "p_id" ,"p"."user_id" as "p_user_id" ,"p"."title" as "p_title"
524
- // FROM "posts" "p"
525
- // JOIN "users" "u" ON "p"."user_id" = "u"."id"
526
- // WHERE "u"."id" = $1
527
- q.values // [42]
528
643
  ```
529
644
 
530
- Using **Effect** (`pipe` is data-first, which many find more readable):
645
+ Or with **Effect**, whose `pipe` takes the value first:
531
646
 
532
647
  ```ts
533
648
  import { pipe } from 'effect'
534
- import { schema, selectAs, join, where, concat, all } from '@vanit-co/sql-ts'
535
649
 
536
650
  const q = pipe(
537
651
  selectAs`SELECT ${all(users, posts)} FROM ${posts}`,
@@ -540,121 +654,131 @@ const q = pipe(
540
654
  )
541
655
  ```
542
656
 
543
- ### `empty`
657
+ ### Arrays and `IN` lists
544
658
 
545
- 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:
546
660
 
547
661
  ```ts
548
- import { pipe, reduce } from 'ramda'
549
- import { schema, select, join, where, concat, empty, all } from '@vanit-co/sql-ts'
662
+ const ids = [1, 2, 3]
550
663
 
551
- const users = schema({ table: 'users', columns: ['id', 'email'], alias: 'u' })
552
- 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]]
553
666
 
554
- 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
+ ```
555
670
 
556
- const buildPostsQuery = ({ userId, titleLike }: Filters) => {
557
- const clauses = [
558
- select`SELECT ${all(users, posts)} FROM ${posts}`,
559
- join` JOIN ${users} ON ${posts.user_id} = ${users.id}`,
560
- userId ? where` WHERE ${users.id} = ${userId}` : empty,
561
- titleLike ? where` AND ${posts.title} LIKE ${titleLike}` : empty,
562
- ]
671
+ SQLite drivers don't expand arrays. Bind the list as JSON instead:
563
672
 
564
- return reduce(
565
- (acc, clause) => concat(clause)(acc),
566
- empty,
567
- clauses
568
- )
569
- }
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
+ ```
570
677
 
571
- const q = buildPostsQuery({ userId: 7, titleLike: '%TypeScript%' })
572
- q.text
573
- // SELECT "u"."id" as "u_id" ,"u"."email" as "u_email"
574
- // ,"p"."id" as "p_id" ,"p"."user_id" as "p_user_id" ,"p"."title" as "p_title"
575
- // FROM "posts" "p"
576
- // JOIN "users" "u" ON "p"."user_id" = "u"."id"
577
- // WHERE "u"."id" = $1
578
- // AND "p"."title" LIKE $2
579
- 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 // []
580
688
  ```
581
689
 
582
- ---
690
+ `raw` works anywhere a value does, including the values you pass to `insert`, `update` and `updateAs`.
583
691
 
584
- ## Arrays and `IN` lists
692
+ ### Prepared statements: `preparedStatementName`
585
693
 
586
- An array is bound as a single parameter, which is what the drivers expect:
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.
587
695
 
588
696
  ```ts
589
- const ids = [1, 2, 3]
697
+ import { sql, all, preparedStatementName } from '@vanit-co/sql-ts'
590
698
 
591
- // PostgreSQL (node-postgres): use = ANY(...)
592
- where`WHERE ${users.id} = ANY(${ids})`.text // WHERE "u"."id" = ANY($1) values: [[1, 2, 3]]
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]
593
703
 
594
- // MySQL (mysql2, with .query): IN (?) expands the array
595
- where`WHERE ${users.id} IN (${ids})`.sql // WHERE `u`.`id` IN (?) values: [[1, 2, 3]]
704
+ await client.query(q)
596
705
  ```
597
706
 
598
- SQLite drivers don't expand arrays. Bind the list as JSON instead:
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.
599
710
 
600
711
  ```ts
601
- sql`WHERE ${users.id} IN (SELECT value FROM json_each(${JSON.stringify(ids)}))`.sql
602
- // WHERE `id` IN (SELECT value FROM json_each(?)) values: ['[1,2,3]']
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] }
603
718
  ```
604
719
 
605
720
  ---
606
721
 
607
- ## Dialect functions: `toMysql` and `toPostgres`
722
+ ## Safety
608
723
 
609
- 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.
724
+ sql-ts is built so that the easy way to write a query is also the safe way:
610
725
 
611
- ```ts
612
- import { toMysql, toPostgres } from '@vanit-co/sql-ts'
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.
613
729
 
614
- const result = toPostgres(someFragment)
615
- // { text: 'SELECT ... WHERE id = $1', values: [42] }
730
+ ```ts
731
+ const name = "'; DROP TABLE users; --"
616
732
 
617
- const mysqlResult = toMysql(someFragment)
618
- // { sql: 'SELECT ... WHERE id = ?', values: [42] }
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)
619
736
  ```
620
737
 
621
738
  ---
622
739
 
623
- ## Escaping and raw SQL: `raw`
740
+ ## Common pitfalls
624
741
 
625
- 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.**
742
+ **Start every appended fragment with a space.** `append` joins the text as-is, so a missing space glues words together:
626
743
 
627
744
  ```ts
628
- import { sql, raw } 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
629
747
 
630
- const q = sql`SELECT ${raw('COUNT(*)')} AS total FROM users`
631
- q.text // SELECT COUNT(*) AS total FROM users
632
- q.values // []
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
633
750
  ```
634
751
 
635
- `raw` works anywhere a value is accepted, including the column values passed to `insert` and `update`.
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:
636
753
 
637
- ---
754
+ ```ts
755
+ selectAs`SELECT ${all(users)} FROM ${users} ORDER BY ${users.id}`.text
756
+ // ... ORDER BY "u"."id" as "u_id" ← broken
638
757
 
639
- ## Prepared statements: `preparedStatementName`
758
+ selectAs`SELECT ${all(users)} FROM ${users}`.append(orderBy` ORDER BY ${users.id}`).text
759
+ // ... ORDER BY "u"."id" ← fine
760
+ ```
640
761
 
641
- Attach a name to a `Result` for use with named prepared statements (e.g., `pg`'s `{ name, text, values }` query format).
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:
642
763
 
643
764
  ```ts
644
- import { sql, preparedStatementName } from '@vanit-co/sql-ts'
645
-
646
- const q = sql`SELECT * FROM ${users} WHERE id = ${1}`
647
- const named = preparedStatementName(q, 'get-user-by-id')
765
+ update(users, { name: 'Ada' }).append(where` WHERE ${users.id} = ${1}`).text
766
+ // update "users" set "name" = $1 WHERE "u"."id" = $2 ← broken
648
767
 
649
- named.name // 'get-user-by-id'
650
- named.text // SELECT * FROM users WHERE id = $1
651
- named.values // [1]
768
+ update(users, { name: 'Ada' }).append(sql` WHERE ${users.id} = ${1}`).text
769
+ // update "users" set "name" = $1 WHERE "id" = $2 ← fine
652
770
 
653
- // Pass to pg:
654
- await client.query(named)
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
655
773
  ```
656
774
 
657
- `preparedStatementName` does not mutate the original result - it returns a new object.
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).
658
782
 
659
783
  ---
660
784