@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/CHANGELOG.md +20 -0
- package/README.md +488 -364
- package/dist/generate.d.mts +19 -0
- package/dist/generate.d.ts +19 -0
- package/dist/generate.js +83 -0
- package/dist/generate.js.map +1 -0
- package/dist/generate.mjs +80 -0
- package/dist/generate.mjs.map +1 -0
- package/dist/index.d.mts +54 -18
- package/dist/index.d.ts +54 -18
- package/dist/index.js +44 -3
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +43 -4
- package/dist/index.mjs.map +1 -1
- package/package.json +24 -1
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
|
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
|
|
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
|
-
|
|
78
|
+
---
|
|
54
79
|
|
|
55
|
-
|
|
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
|
-
|
|
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
|
-
|
|
88
|
+
```ts
|
|
89
|
+
import { schema } from '@vanit-co/sql-ts'
|
|
67
90
|
|
|
68
|
-
|
|
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
|
-
|
|
94
|
+
users.email // a column you can interpolate; users.emial is a compile error
|
|
95
|
+
```
|
|
71
96
|
|
|
72
|
-
|
|
97
|
+
### 2. Write a query
|
|
73
98
|
|
|
74
|
-
|
|
99
|
+
Write SQL as usual and interpolate the schema and your values. Tables and columns become quoted names; values become placeholders.
|
|
75
100
|
|
|
76
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
114
|
+
### 3. Run it
|
|
115
|
+
|
|
116
|
+
Hand the query to your driver. sql-ts never opens a connection.
|
|
83
117
|
|
|
84
118
|
```ts
|
|
85
|
-
|
|
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
|
-
|
|
129
|
+
### 4. Read the rows
|
|
88
130
|
|
|
89
|
-
|
|
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
|
-
|
|
92
|
-
|
|
133
|
+
```ts
|
|
134
|
+
import { selectAs, join, all, as } from '@vanit-co/sql-ts'
|
|
93
135
|
|
|
94
|
-
|
|
95
|
-
|
|
136
|
+
const q = selectAs`SELECT ${all(users, posts)} FROM ${posts}`
|
|
137
|
+
.append(join` JOIN ${users} ON ${users.id} = ${posts.user_id}`)
|
|
96
138
|
|
|
97
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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 {
|
|
158
|
+
import { selectAs, where, orderBy, all, empty } from '@vanit-co/sql-ts'
|
|
106
159
|
|
|
107
|
-
const
|
|
108
|
-
|
|
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
|
-
|
|
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
|
-
//
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
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
|
-
|
|
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
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
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
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
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
|
-
##
|
|
200
|
+
## Which tag do I use?
|
|
138
201
|
|
|
139
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
|
156
|
-
| `columns` | `string[]` |
|
|
157
|
-
| `alias` | `string` (optional) |
|
|
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
|
-
|
|
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
|
-
####
|
|
260
|
+
#### The same table twice: `alias`
|
|
162
261
|
|
|
163
|
-
`alias(table, newAlias)` returns a copy of a schema under
|
|
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
|
|
169
|
-
const
|
|
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(
|
|
172
|
-
const reviewer = alias(
|
|
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 ${
|
|
175
|
-
.append(join` JOIN ${author} ON ${
|
|
176
|
-
.append(join` JOIN ${reviewer} ON ${
|
|
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 "
|
|
180
|
-
// JOIN "users" "author" ON "
|
|
181
|
-
// JOIN "users" "reviewer" ON "
|
|
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
|
|
285
|
+
Every tag and statement builder returns the same kind of value:
|
|
189
286
|
|
|
190
287
|
| property | description |
|
|
191
288
|
|----------|-------------|
|
|
192
|
-
| `.
|
|
193
|
-
| `.
|
|
194
|
-
| `.values` |
|
|
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
|
-
|
|
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
|
|
200
|
-
await
|
|
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
|
-
|
|
210
|
-
|
|
211
|
-
---
|
|
212
|
-
|
|
213
|
-
## Template tag functions
|
|
303
|
+
### Template tags
|
|
214
304
|
|
|
215
|
-
|
|
305
|
+
#### `sql`
|
|
216
306
|
|
|
217
|
-
The base tag
|
|
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
|
|
223
|
-
|
|
224
|
-
//
|
|
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
|
-
|
|
317
|
+
#### `select` (short: `s`)
|
|
239
318
|
|
|
240
|
-
|
|
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
|
|
322
|
+
import { select } from '@vanit-co/sql-ts'
|
|
244
323
|
|
|
245
|
-
|
|
246
|
-
|
|
324
|
+
select`SELECT ${users.email} FROM ${users}`.text
|
|
325
|
+
// SELECT "u"."email" FROM "users" "u"
|
|
326
|
+
```
|
|
247
327
|
|
|
248
|
-
|
|
249
|
-
select`FROM ${users}`.text // FROM "users" "users"
|
|
250
|
-
select`FROM ${u}`.text // FROM "users" "u"
|
|
328
|
+
#### `selectAs` (short: `sa`)
|
|
251
329
|
|
|
252
|
-
|
|
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
|
-
|
|
257
|
-
|
|
258
|
-
select`SELECT ${users.id} WHERE id = ${7}`.values // [7]
|
|
332
|
+
```ts
|
|
333
|
+
import { selectAs } from '@vanit-co/sql-ts'
|
|
259
334
|
|
|
260
|
-
|
|
261
|
-
|
|
335
|
+
selectAs`SELECT ${users.email} FROM ${users}`.text
|
|
336
|
+
// SELECT "u"."email" as "u_email" FROM "users" "u"
|
|
262
337
|
```
|
|
263
338
|
|
|
264
|
-
|
|
339
|
+
#### `where`, `join`, `orderBy`, `groupBy`, `having`
|
|
265
340
|
|
|
266
|
-
|
|
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 {
|
|
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
|
-
|
|
275
|
-
|
|
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
|
-
|
|
278
|
-
|
|
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
|
-
###
|
|
359
|
+
### Column helpers: `all`, `pick` and `as`
|
|
360
|
+
|
|
361
|
+
#### `all(...tables)`
|
|
282
362
|
|
|
283
|
-
|
|
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,
|
|
366
|
+
import { select, selectAs, all } from '@vanit-co/sql-ts'
|
|
287
367
|
|
|
288
|
-
|
|
289
|
-
|
|
368
|
+
select`SELECT ${all(users)}`.text
|
|
369
|
+
// SELECT "u"."id" ,"u"."email" ,"u"."name"
|
|
290
370
|
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
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
|
-
|
|
378
|
+
Expands only the columns you name, from any tables.
|
|
305
379
|
|
|
306
|
-
|
|
380
|
+
```ts
|
|
381
|
+
import { selectAs, pick } from '@vanit-co/sql-ts'
|
|
307
382
|
|
|
308
|
-
|
|
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
|
-
|
|
311
|
-
import { select, selectAs, schema, all } from '@vanit-co/sql-ts'
|
|
387
|
+
#### `as(column)`
|
|
312
388
|
|
|
313
|
-
|
|
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
|
-
|
|
317
|
-
|
|
318
|
-
// SELECT "users"."id" ,"users"."email"
|
|
391
|
+
```ts
|
|
392
|
+
import { as } from '@vanit-co/sql-ts'
|
|
319
393
|
|
|
320
|
-
//
|
|
321
|
-
|
|
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
|
-
|
|
325
|
-
|
|
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
|
-
###
|
|
401
|
+
### Typed result rows
|
|
330
402
|
|
|
331
|
-
|
|
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 {
|
|
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', '
|
|
337
|
-
const posts = schema({ table: 'posts', columns: ['
|
|
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
|
-
|
|
340
|
-
|
|
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
|
-
|
|
344
|
-
|
|
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
|
-
|
|
348
|
-
|
|
349
|
-
//
|
|
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
|
-
|
|
422
|
+
The examples in this section use these typed `users` and `posts`.
|
|
353
423
|
|
|
354
|
-
|
|
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 {
|
|
438
|
+
import { select, selectAs, where, all, pick, type RowOf } from '@vanit-co/sql-ts'
|
|
358
439
|
|
|
359
|
-
const
|
|
360
|
-
|
|
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
|
-
|
|
363
|
-
|
|
444
|
+
const q2 = select`SELECT ${pick(users.email)} FROM ${users}`
|
|
445
|
+
type R2 = RowOf<typeof q2> // { email: string }
|
|
364
446
|
|
|
365
|
-
|
|
366
|
-
|
|
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
|
-
|
|
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
|
-
|
|
459
|
+
import { selectAs, select, all, expr, type RowOf } from '@vanit-co/sql-ts'
|
|
373
460
|
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
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
|
-
|
|
472
|
+
#### Generating the type records from your database
|
|
383
473
|
|
|
384
|
-
|
|
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 {
|
|
477
|
+
import { writeFileSync } from 'node:fs'
|
|
478
|
+
import { postgresColumns, generate } from '@vanit-co/sql-ts/generate'
|
|
388
479
|
|
|
389
|
-
const
|
|
390
|
-
|
|
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
|
-
|
|
397
|
-
|
|
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
|
-
|
|
400
|
-
|
|
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
|
-
- `
|
|
404
|
-
- `
|
|
405
|
-
-
|
|
406
|
-
-
|
|
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
|
-
|
|
504
|
+
### Statement builders: `insert`, `update` and `updateAs`
|
|
411
505
|
|
|
412
|
-
|
|
506
|
+
#### `insert(table, ...rows)`
|
|
413
507
|
|
|
414
|
-
Builds
|
|
508
|
+
Builds an `INSERT` from one or more row objects. The columns come from the first row.
|
|
415
509
|
|
|
416
510
|
```ts
|
|
417
|
-
import {
|
|
418
|
-
|
|
419
|
-
const users = schema({ table: 'users', columns: ['id', 'email'] })
|
|
511
|
+
import { insert, raw } from '@vanit-co/sql-ts'
|
|
420
512
|
|
|
421
|
-
|
|
422
|
-
|
|
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
|
-
|
|
427
|
-
|
|
428
|
-
|
|
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
|
-
//
|
|
435
|
-
const
|
|
436
|
-
|
|
437
|
-
|
|
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
|
-
|
|
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
|
-
|
|
528
|
+
#### `update(table, colsVals)`
|
|
443
529
|
|
|
444
|
-
Builds
|
|
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 {
|
|
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
|
-
|
|
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
|
-
|
|
452
|
-
q.text // update "users" set "email" = $1
|
|
453
|
-
q.values // ['new@example.com']
|
|
548
|
+
#### `updateAs(table, colsVals)`
|
|
454
549
|
|
|
455
|
-
|
|
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
|
-
|
|
461
|
-
|
|
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
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
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
|
-
|
|
567
|
+
### Composing queries: `append`, `concat` and `empty`
|
|
474
568
|
|
|
475
|
-
|
|
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
|
-
|
|
571
|
+
#### `append` and `concat`
|
|
478
572
|
|
|
479
|
-
|
|
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
|
|
576
|
+
import { select, where, concat } from '@vanit-co/sql-ts'
|
|
483
577
|
|
|
484
|
-
const
|
|
578
|
+
const base = select`SELECT ${users.id} FROM ${users}`
|
|
485
579
|
|
|
486
|
-
|
|
487
|
-
|
|
580
|
+
base.append(where` WHERE ${users.id} = ${5}`).text
|
|
581
|
+
// SELECT "u"."id" FROM "users" "u" WHERE "u"."id" = $1
|
|
488
582
|
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
full.values // [5]
|
|
583
|
+
concat(where` WHERE ${users.id} = ${5}`)(base).text
|
|
584
|
+
// the same
|
|
492
585
|
```
|
|
493
586
|
|
|
494
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
620
|
+
```ts
|
|
621
|
+
import { select, where } from '@vanit-co/sql-ts'
|
|
504
622
|
|
|
505
|
-
|
|
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 {
|
|
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
|
-
|
|
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
|
-
### `
|
|
657
|
+
### Arrays and `IN` lists
|
|
544
658
|
|
|
545
|
-
An
|
|
659
|
+
An array is bound as a single parameter, which is what the drivers expect:
|
|
546
660
|
|
|
547
661
|
```ts
|
|
548
|
-
|
|
549
|
-
import { schema, select, join, where, concat, empty, all } from '@vanit-co/sql-ts'
|
|
662
|
+
const ids = [1, 2, 3]
|
|
550
663
|
|
|
551
|
-
|
|
552
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
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
|
-
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
q.
|
|
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
|
-
|
|
692
|
+
### Prepared statements: `preparedStatementName`
|
|
585
693
|
|
|
586
|
-
|
|
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
|
-
|
|
697
|
+
import { sql, all, preparedStatementName } from '@vanit-co/sql-ts'
|
|
590
698
|
|
|
591
|
-
|
|
592
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
602
|
-
|
|
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
|
-
##
|
|
722
|
+
## Safety
|
|
608
723
|
|
|
609
|
-
|
|
724
|
+
sql-ts is built so that the easy way to write a query is also the safe way:
|
|
610
725
|
|
|
611
|
-
|
|
612
|
-
|
|
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
|
-
|
|
615
|
-
|
|
730
|
+
```ts
|
|
731
|
+
const name = "'; DROP TABLE users; --"
|
|
616
732
|
|
|
617
|
-
const
|
|
618
|
-
//
|
|
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
|
-
##
|
|
740
|
+
## Common pitfalls
|
|
624
741
|
|
|
625
|
-
|
|
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
|
-
|
|
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
|
-
|
|
631
|
-
|
|
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
|
-
`
|
|
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
|
-
|
|
758
|
+
selectAs`SELECT ${all(users)} FROM ${users}`.append(orderBy` ORDER BY ${users.id}`).text
|
|
759
|
+
// ... ORDER BY "u"."id" ← fine
|
|
760
|
+
```
|
|
640
761
|
|
|
641
|
-
|
|
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
|
-
|
|
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
|
-
|
|
650
|
-
|
|
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
|
-
|
|
654
|
-
|
|
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
|
-
`
|
|
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
|
|