@vanit-co/sql-ts 1.0.4 → 1.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +87 -0
- package/README.md +550 -320
- 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 +150 -0
- package/dist/index.d.ts +101 -22
- package/dist/index.js +63 -17
- package/dist/index.js.map +1 -0
- package/dist/index.mjs +223 -0
- package/dist/index.mjs.map +1 -0
- package/package.json +72 -12
package/README.md
CHANGED
|
@@ -1,454 +1,651 @@
|
|
|
1
1
|
# @vanit-co/sql-ts
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
[](https://www.npmjs.com/package/@vanit-co/sql-ts)
|
|
4
|
+
[](https://github.com/vanit-co/sql-ts/actions/workflows/ci.yml)
|
|
5
|
+
[](https://bundlephobia.com/package/@vanit-co/sql-ts)
|
|
6
|
+

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