@vanit-co/sql-ts 0.10.0 → 1.0.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/dist/LICENSE +21 -0
- package/dist/README.md +529 -0
- package/package.json +1 -1
package/dist/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 vanit
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/dist/README.md
ADDED
|
@@ -0,0 +1,529 @@
|
|
|
1
|
+
# @vanit-co/sql-ts
|
|
2
|
+
|
|
3
|
+
A TypeScript SQL query builder using tagged template literals. Write plain SQL with safe, automatic parameter binding and properly quoted identifiers. No DSL to learn, no magic, no ORM.
|
|
4
|
+
|
|
5
|
+
Supports **MySQL** (`?` placeholders, `` ` `` backtick identifiers) and **PostgreSQL** (`$n` placeholders, `"` double-quote identifiers) out of the box.
|
|
6
|
+
|
|
7
|
+
## Why this library?
|
|
8
|
+
|
|
9
|
+
Writing raw SQL in TypeScript runs into a set of recurring friction points that this library addresses directly:
|
|
10
|
+
|
|
11
|
+
- **Automatic identifier quoting** - table and column names are interpolated as properly quoted identifiers (`` `name` `` for MySQL, `"name"` for PostgreSQL), never as bind parameters. No manual quoting, no dialect-specific escaping scattered across your codebase.
|
|
12
|
+
|
|
13
|
+
- **Table alias and qualified column references** - the `select` tag (and its aliases `groupBy`, `having`, `join`, `orderBy`, `where`) automatically expands schema tables as `"table" "alias"` and columns as `"alias"."column"`, so JOIN-heavy queries stay unambiguous without hand-writing every qualified reference.
|
|
14
|
+
|
|
15
|
+
- **Column alias expansion** - `selectAs` goes further, rendering each column as `"alias"."column" as "alias_column"`. When querying multiple joined tables, result-set keys no longer collide.
|
|
16
|
+
|
|
17
|
+
- **`concat` and `empty` as a monoid** - every tagged template and statement builder returns a `Fragment`. `concat` joins two fragments into one, and `empty` is the identity element. This lets you accumulate query fragments conditionally with `reduce`, compose them with `pipe`, or chain them with `.append` - treating query construction as plain data transformation.
|
|
18
|
+
|
|
19
|
+
- **`all` and `pick` helpers** - expand an entire table's columns or a chosen subset into a comma-separated list inside any tag, so `SELECT ${all(users, posts)}` replaces repetitive column lists without losing type safety.
|
|
20
|
+
|
|
21
|
+
## Installation
|
|
22
|
+
|
|
23
|
+
```sh
|
|
24
|
+
npm install @vanit-co/sql-ts
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
## Quick example
|
|
28
|
+
|
|
29
|
+
**sql** tag takes care of quoting the identifiers (tables and columns) with the proper quotes `` ` `` for MySQL and `"` for PostgreSQL.
|
|
30
|
+
|
|
31
|
+
```ts
|
|
32
|
+
import { schema, sql, all } from '@vanit-co/sql-ts'
|
|
33
|
+
|
|
34
|
+
const users = schema({ table: 'users', columns: ['id', 'email'] })
|
|
35
|
+
|
|
36
|
+
const query = sql`SELECT ${all(users)} FROM ${users} WHERE ${users.id} = ${42}`
|
|
37
|
+
|
|
38
|
+
// PostgreSQL
|
|
39
|
+
console.log(query.text) // SELECT "id" ,"email" FROM "users" WHERE "id" = $1
|
|
40
|
+
|
|
41
|
+
// MySQL
|
|
42
|
+
console.log(query.sql) // SELECT `id` ,`email` FROM `users` WHERE `id` = ?
|
|
43
|
+
|
|
44
|
+
console.log(query.values) // [42]
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
## Full query example
|
|
48
|
+
|
|
49
|
+
**select** tag works like **sql** but automatically adds table aliases and column prefixes. The other tags **groupBy**, **having**, **join**, **orderBy** and **where** are just aliases to **select** with the aim of maintaining semantics. The **selectAs** tag besides the column prefixes will also add the column alias using the format `$prefix_$columnName`.
|
|
50
|
+
|
|
51
|
+
```ts
|
|
52
|
+
import { schema, select, selectAs, join, where, all, insert, update, empty } from '@vanit-co/sql-ts'
|
|
53
|
+
|
|
54
|
+
const users = schema({ table: 'users', columns: ['id', 'email'], alias: 'u' })
|
|
55
|
+
const posts = schema({ table: 'posts', columns: ['id', 'user_id', 'title'], alias: 'p' })
|
|
56
|
+
|
|
57
|
+
const id = 42
|
|
58
|
+
|
|
59
|
+
// SELECT with JOIN
|
|
60
|
+
const query = selectAs`SELECT ${all(users, posts)} FROM ${posts}`
|
|
61
|
+
.append(join`JOIN ${users} ON ${posts.user_id} = ${users.id}`)
|
|
62
|
+
.append(id ? where`WHERE ${users.id} = ${42}` : empty)
|
|
63
|
+
|
|
64
|
+
query.text
|
|
65
|
+
// SELECT "u"."id" as "u_id" ,"u"."email" as "u_email" ,"p"."id" as "p_id" ,"p"."user_id" as "p_user_id" ,"p"."title" as "p_title"
|
|
66
|
+
// FROM "posts" "p"
|
|
67
|
+
// JOIN "users" "u" ON "p"."user_id" = "u"."id"
|
|
68
|
+
// WHERE "u"."id" = $1
|
|
69
|
+
query.values // [42]
|
|
70
|
+
|
|
71
|
+
// INSERT
|
|
72
|
+
const ins = insert(users, { id: 1, email: 'alice@example.com' })
|
|
73
|
+
ins.text // insert into "users" ("id" ,"email") values ($1 ,$2)
|
|
74
|
+
ins.values // [1, 'alice@example.com']
|
|
75
|
+
|
|
76
|
+
// UPDATE
|
|
77
|
+
const upd = update(users, { email: 'new@example.com' }).append(sql` where ${users.id} = ${id}`)
|
|
78
|
+
upd.text // update "users" set "email" = $1 where "id" = $2
|
|
79
|
+
upd.values // ['new@example.com', 42]
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
---
|
|
83
|
+
|
|
84
|
+
## Core concepts
|
|
85
|
+
|
|
86
|
+
### Schema
|
|
87
|
+
|
|
88
|
+
Define your tables once. The schema carries table and column metadata used by the template tags to produce properly quoted, prefixed identifiers.
|
|
89
|
+
|
|
90
|
+
```ts
|
|
91
|
+
import { schema } from '@vanit-co/sql-ts'
|
|
92
|
+
|
|
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' })
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
`schema` takes:
|
|
100
|
+
| field | type | description |
|
|
101
|
+
|-------|------|-------------|
|
|
102
|
+
| `table` | `string` | The actual table name in the database |
|
|
103
|
+
| `columns` | `string[]` | Column names to expose as typed properties |
|
|
104
|
+
| `alias` | `string` (optional) | Alias used for prefixing columns; defaults to `table` |
|
|
105
|
+
|
|
106
|
+
After calling `schema`, the returned object has a typed property for each column (`users.id`, `users.email`, etc.).
|
|
107
|
+
|
|
108
|
+
---
|
|
109
|
+
|
|
110
|
+
### Result object
|
|
111
|
+
|
|
112
|
+
Every template tag and statement builder returns a `Result` object with three properties:
|
|
113
|
+
|
|
114
|
+
| property | description |
|
|
115
|
+
|----------|-------------|
|
|
116
|
+
| `.sql` | Query string in MySQL format (`?` placeholders, backtick-quoted identifiers) |
|
|
117
|
+
| `.text` | Query string in PostgreSQL format (`$n` placeholders, double-quote identifiers) |
|
|
118
|
+
| `.values` | Array of bind values in order, ready to pass to your database driver |
|
|
119
|
+
|
|
120
|
+
Pass these directly to your driver:
|
|
121
|
+
|
|
122
|
+
```ts
|
|
123
|
+
// node-postgres (pg)
|
|
124
|
+
await client.query(query)
|
|
125
|
+
|
|
126
|
+
// mysql2
|
|
127
|
+
await connection.query(query)
|
|
128
|
+
```
|
|
129
|
+
|
|
130
|
+
---
|
|
131
|
+
|
|
132
|
+
## Template tag functions
|
|
133
|
+
|
|
134
|
+
### `sql`
|
|
135
|
+
|
|
136
|
+
The base tag. Interpolated plain values become bind parameters. Interpolated schema tables become their bare name identifier; columns become their bare column name identifier (no table prefix).
|
|
137
|
+
|
|
138
|
+
```ts
|
|
139
|
+
import { sql } from '@vanit-co/sql-ts'
|
|
140
|
+
|
|
141
|
+
const users = schema({ table: 'users', columns: ['id', 'email'] })
|
|
142
|
+
|
|
143
|
+
// Plain values → bind parameters
|
|
144
|
+
const q1 = sql`SELECT * FROM users WHERE id = ${42}`
|
|
145
|
+
q1.text // SELECT * FROM users WHERE id = $1
|
|
146
|
+
q1.values // [42]
|
|
147
|
+
|
|
148
|
+
// Schema table → quoted identifier (name only)
|
|
149
|
+
const q2 = sql`FROM ${users}`
|
|
150
|
+
q2.text // FROM "users"
|
|
151
|
+
|
|
152
|
+
// Schema column → quoted identifier (name only, no prefix)
|
|
153
|
+
const q3 = sql`SELECT ${users.id}`
|
|
154
|
+
q3.text // SELECT "id"
|
|
155
|
+
```
|
|
156
|
+
|
|
157
|
+
### `select` (alias: `s`)
|
|
158
|
+
|
|
159
|
+
Like `sql`, but schema tables are rendered as `"name" "alias"` and columns are rendered as `"alias"."column"`. Use this for `SELECT`, `FROM`, `JOIN`, and `WHERE` clauses when you want fully qualified column references.
|
|
160
|
+
|
|
161
|
+
```ts
|
|
162
|
+
import { select, s, schema } from '@vanit-co/sql-ts'
|
|
163
|
+
|
|
164
|
+
const users = schema({ table: 'users', columns: ['id', 'email'] })
|
|
165
|
+
const u = schema({ table: 'users', columns: ['id', 'email'], alias: 'u' })
|
|
166
|
+
|
|
167
|
+
// Table → name + alias
|
|
168
|
+
select`FROM ${users}`.text // FROM "users" "users"
|
|
169
|
+
select`FROM ${u}`.text // FROM "users" "u"
|
|
170
|
+
|
|
171
|
+
// Column → alias.column
|
|
172
|
+
select`SELECT ${users.email}`.text // SELECT "users"."email"
|
|
173
|
+
select`SELECT ${u.email}`.text // SELECT "u"."email"
|
|
174
|
+
|
|
175
|
+
// Mix with values
|
|
176
|
+
select`SELECT ${users.id} WHERE id = ${7}`.text // SELECT "users"."id" WHERE id = $1
|
|
177
|
+
select`SELECT ${users.id} WHERE id = ${7}`.values // [7]
|
|
178
|
+
|
|
179
|
+
// Short alias
|
|
180
|
+
s`SELECT ${users.id}`.text // SELECT "users"."id"
|
|
181
|
+
```
|
|
182
|
+
|
|
183
|
+
### `selectAs` (alias: `sa`)
|
|
184
|
+
|
|
185
|
+
Same as `select` for tables, but columns are rendered as `"alias"."column" as "alias_column"`. Use this when fetching from multiple joined tables and you want unambiguous aliased column names in the result set.
|
|
186
|
+
|
|
187
|
+
```ts
|
|
188
|
+
import { selectAs, sa, schema } from '@vanit-co/sql-ts'
|
|
189
|
+
|
|
190
|
+
const users = schema({ table: 'users', columns: ['id', 'email'] })
|
|
191
|
+
const u = schema({ table: 'users', columns: ['id', 'email'], alias: 'u' })
|
|
192
|
+
|
|
193
|
+
selectAs`SELECT ${users.id}`.text // SELECT "users"."id" as "users_id"
|
|
194
|
+
selectAs`SELECT ${users.email}`.text // SELECT "users"."email" as "users_email"
|
|
195
|
+
|
|
196
|
+
// With alias
|
|
197
|
+
sa`SELECT ${u.email}`.text // SELECT "u"."email" as "u_email"
|
|
198
|
+
```
|
|
199
|
+
|
|
200
|
+
### `groupBy` (alias: `g`), `having` (alias: `h`), `join` (alias: `j`), `orderBy` (alias: `o`) and `where` (alias: `w`)
|
|
201
|
+
|
|
202
|
+
These are all identical to `select`. They exist as semantic aliases so your query construction reads naturally - each tag signals which SQL clause it belongs to.
|
|
203
|
+
|
|
204
|
+
```ts
|
|
205
|
+
import { select, join, j, where, w, groupBy, g, having, h, orderBy, o, schema } from '@vanit-co/sql-ts'
|
|
206
|
+
|
|
207
|
+
const posts = schema({ table: 'posts', columns: ['id', 'user_id', 'title'] })
|
|
208
|
+
const users = schema({ table: 'users', columns: ['id', 'email'] })
|
|
209
|
+
|
|
210
|
+
const q = select`SELECT ${posts.title}, ${users.email}`
|
|
211
|
+
const fromClause = join` FROM ${posts}`
|
|
212
|
+
const joinClause = join` JOIN ${users} ON ${posts.user_id} = ${users.id}`
|
|
213
|
+
const whereClause = where` WHERE ${users.id} = ${99}`
|
|
214
|
+
const groupClause = groupBy` GROUP BY ${posts.title}`
|
|
215
|
+
const havingClause = having` HAVING COUNT(${posts.id}) > ${1}`
|
|
216
|
+
const orderClause = orderBy` ORDER BY ${posts.title}`
|
|
217
|
+
```
|
|
218
|
+
|
|
219
|
+
---
|
|
220
|
+
|
|
221
|
+
## Column helpers: `all` and `pick`
|
|
222
|
+
|
|
223
|
+
Use these inside any template tag to expand multiple columns at once.
|
|
224
|
+
|
|
225
|
+
### `all(...tables)`
|
|
226
|
+
|
|
227
|
+
Expands every column from one or more schema tables.
|
|
228
|
+
|
|
229
|
+
```ts
|
|
230
|
+
import { select, selectAs, schema, all } from '@vanit-co/sql-ts'
|
|
231
|
+
|
|
232
|
+
const users = schema({ table: 'users', columns: ['id', 'email'] })
|
|
233
|
+
const posts = schema({ table: 'posts', columns: ['title', 'body'] })
|
|
234
|
+
|
|
235
|
+
// Single table
|
|
236
|
+
select`SELECT ${all(users)}`.text
|
|
237
|
+
// SELECT "users"."id" ,"users"."email"
|
|
238
|
+
|
|
239
|
+
// Multiple tables
|
|
240
|
+
select`SELECT ${all(users, posts)}`.text
|
|
241
|
+
// SELECT "users"."id" ,"users"."email" ,"posts"."title" ,"posts"."body"
|
|
242
|
+
|
|
243
|
+
// With selectAs for aliased columns
|
|
244
|
+
selectAs`SELECT ${all(users)}`.text
|
|
245
|
+
// SELECT "users"."id" as "users_id" ,"users"."email" as "users_email"
|
|
246
|
+
```
|
|
247
|
+
|
|
248
|
+
### `pick(...columns)`
|
|
249
|
+
|
|
250
|
+
Expands a specific subset of columns from any tables.
|
|
251
|
+
|
|
252
|
+
```ts
|
|
253
|
+
import { select, selectAs, schema, pick } from '@vanit-co/sql-ts'
|
|
254
|
+
|
|
255
|
+
const users = schema({ table: 'users', columns: ['id', 'email', 'name'] })
|
|
256
|
+
const posts = schema({ table: 'posts', columns: ['title', 'body'] })
|
|
257
|
+
|
|
258
|
+
// Pick from one table
|
|
259
|
+
select`SELECT ${pick(users.id, users.email)}`.text
|
|
260
|
+
// SELECT "users"."id" ,"users"."email"
|
|
261
|
+
|
|
262
|
+
// Pick from different tables
|
|
263
|
+
select`SELECT ${pick(users.id, posts.title)}`.text
|
|
264
|
+
// SELECT "users"."id" ,"posts"."title"
|
|
265
|
+
|
|
266
|
+
// With selectAs
|
|
267
|
+
selectAs`SELECT ${pick(users.id, users.email)}`.text
|
|
268
|
+
// SELECT "users"."id" as "users_id" ,"users"."email" as "users_email"
|
|
269
|
+
```
|
|
270
|
+
|
|
271
|
+
### `as(column)`
|
|
272
|
+
|
|
273
|
+
Returns the aliased column name as a plain string - the same `prefix_name` string that `selectAs` writes into the SQL `AS` clause. Use this to read a column out of query results by its aliased key without repeating the string manually.
|
|
274
|
+
|
|
275
|
+
```ts
|
|
276
|
+
import { schema, as, selectAs, all } from '@vanit-co/sql-ts'
|
|
277
|
+
|
|
278
|
+
const users = schema({ table: 'users', columns: ['id', 'email'] })
|
|
279
|
+
const u = schema({ table: 'users', columns: ['id', 'email'], alias: 'u' })
|
|
280
|
+
|
|
281
|
+
as(users.id) // 'users_id'
|
|
282
|
+
as(users.email) // 'users_email'
|
|
283
|
+
|
|
284
|
+
as(u.id) // 'u_id'
|
|
285
|
+
as(u.email) // 'u_email'
|
|
286
|
+
```
|
|
287
|
+
|
|
288
|
+
This is particularly useful when mapping over result rows:
|
|
289
|
+
|
|
290
|
+
```ts
|
|
291
|
+
const rows = await client.query(selectAs`SELECT ${all(users)} FROM ${users}`)
|
|
292
|
+
|
|
293
|
+
rows.map(row => ({
|
|
294
|
+
id: row[as(users.id)], // row['users_id']
|
|
295
|
+
email: row[as(users.email)], // row['users_email']
|
|
296
|
+
}))
|
|
297
|
+
```
|
|
298
|
+
|
|
299
|
+
---
|
|
300
|
+
|
|
301
|
+
## Statement builders: `insert` and `update`
|
|
302
|
+
|
|
303
|
+
### `insert(table, ...rows)`
|
|
304
|
+
|
|
305
|
+
Builds a parameterised `INSERT` statement. Accepts one or more row objects. Column names from the first row are used; table and column names are properly quoted identifiers (never bind params).
|
|
306
|
+
|
|
307
|
+
```ts
|
|
308
|
+
import { schema, insert, raw } from '@vanit-co/sql-ts'
|
|
309
|
+
|
|
310
|
+
const users = schema({ table: 'users', columns: ['id', 'email'] })
|
|
311
|
+
|
|
312
|
+
// Single row
|
|
313
|
+
const q1 = insert(users, { id: 1, email: 'alice@example.com' })
|
|
314
|
+
q1.text // insert into "users" ("id" ,"email") values ($1 ,$2)
|
|
315
|
+
q1.values // [1, 'alice@example.com']
|
|
316
|
+
|
|
317
|
+
// Multiple rows
|
|
318
|
+
const q2 = insert(users,
|
|
319
|
+
{ id: 1, email: 'alice@example.com' },
|
|
320
|
+
{ id: 2, email: 'bob@example.com' }
|
|
321
|
+
)
|
|
322
|
+
q2.text // insert into "users" ("id" ,"email") values ($1 ,$2) ,($3 ,$4)
|
|
323
|
+
q2.values // [1, 'alice@example.com', 2, 'bob@example.com']
|
|
324
|
+
|
|
325
|
+
// Raw SQL expressions instead of bind params
|
|
326
|
+
const q3 = insert(users, { id: raw("nextval('users_id_seq')"), email: 'alice@example.com' })
|
|
327
|
+
q3.text // insert into "users" ("id" ,"email") values (nextval('users_id_seq') ,$1)
|
|
328
|
+
q3.values // ['alice@example.com']
|
|
329
|
+
```
|
|
330
|
+
|
|
331
|
+
Column objects used as values are resolved to quoted identifiers rather than bound. They render unprefixed, since the statement has no alias in scope.
|
|
332
|
+
|
|
333
|
+
### `update(table, colsVals)`
|
|
334
|
+
|
|
335
|
+
Builds a parameterised `UPDATE ... SET ...` statement (without a `WHERE` clause - compose that separately using `concat`).
|
|
336
|
+
|
|
337
|
+
```ts
|
|
338
|
+
import { schema, update, raw } from '@vanit-co/sql-ts'
|
|
339
|
+
|
|
340
|
+
const users = schema({ table: 'users', columns: ['id', 'email'] })
|
|
341
|
+
|
|
342
|
+
const q = update(users, { email: 'new@example.com' })
|
|
343
|
+
q.text // update "users" set "email" = $1
|
|
344
|
+
q.values // ['new@example.com']
|
|
345
|
+
|
|
346
|
+
// Multiple columns
|
|
347
|
+
const q2 = update(users, { id: 99, email: 'updated@example.com' })
|
|
348
|
+
q2.text // update "users" set "id" = $1 ,"email" = $2
|
|
349
|
+
q2.values // [99, 'updated@example.com']
|
|
350
|
+
|
|
351
|
+
// Raw SQL expressions instead of bind params
|
|
352
|
+
const q3 = update(users, { id: raw('id + 1'), email: 'updated@example.com' })
|
|
353
|
+
q3.text // update "users" set "id" = id + 1 ,"email" = $1
|
|
354
|
+
q3.values // ['updated@example.com']
|
|
355
|
+
|
|
356
|
+
// Column objects as values, resolved to quoted identifiers
|
|
357
|
+
const q4 = update(users, { email: users.id })
|
|
358
|
+
q4.text // update "users" set "email" = "id"
|
|
359
|
+
q4.values // []
|
|
360
|
+
```
|
|
361
|
+
|
|
362
|
+
---
|
|
363
|
+
|
|
364
|
+
## Fragment utilities: `concat` and `empty`
|
|
365
|
+
|
|
366
|
+
### `concat`
|
|
367
|
+
|
|
368
|
+
Joins two `Fragment` objects into one. `concat` is curried - `concat(right)(left)` appends `right` after `left`.
|
|
369
|
+
|
|
370
|
+
```ts
|
|
371
|
+
import { select, where, concat, schema } from '@vanit-co/sql-ts'
|
|
372
|
+
|
|
373
|
+
const users = schema({ table: 'users', columns: ['id', 'email'] })
|
|
374
|
+
|
|
375
|
+
const base = select`SELECT ${users.id} FROM ${users}`
|
|
376
|
+
const clause = where`WHERE ${users.id} = ${5}`
|
|
377
|
+
|
|
378
|
+
const full = concat(clause)(base)
|
|
379
|
+
full.text // SELECT "users"."id" FROM "users" "users" WHERE "users"."id" = $1
|
|
380
|
+
full.values // [5]
|
|
381
|
+
```
|
|
382
|
+
|
|
383
|
+
You can also use the `.append` method on a `Result`:
|
|
384
|
+
|
|
385
|
+
```ts
|
|
386
|
+
const full = base.append(where`WHERE ${users.id} = ${5}`)
|
|
387
|
+
```
|
|
388
|
+
|
|
389
|
+
|
|
390
|
+
**Composing queries with `pipe`**
|
|
391
|
+
|
|
392
|
+
Because `concat` is curried, it fits naturally into a `pipe`. Each `concat(fragment)` call becomes one step in the pipeline, appending a fragment to the result of the previous step.
|
|
393
|
+
|
|
394
|
+
Using **ramda** (already a dependency of this package):
|
|
395
|
+
|
|
396
|
+
```ts
|
|
397
|
+
import { pipe } from 'ramda'
|
|
398
|
+
import { schema, selectAs, join, where, concat, all } from '@vanit-co/sql-ts'
|
|
399
|
+
|
|
400
|
+
const users = schema({ table: 'users', columns: ['id', 'email'], alias: 'u' })
|
|
401
|
+
const posts = schema({ table: 'posts', columns: ['id', 'user_id', 'title'], alias: 'p' })
|
|
402
|
+
|
|
403
|
+
const buildQuery = (userId: number) =>
|
|
404
|
+
pipe(
|
|
405
|
+
concat(join` JOIN ${users} ON ${posts.user_id} = ${users.id}`),
|
|
406
|
+
concat(where` WHERE ${users.id} = ${userId}`)
|
|
407
|
+
)(selectAs`SELECT ${all(users, posts)} FROM ${posts}`)
|
|
408
|
+
|
|
409
|
+
const q = buildQuery(42)
|
|
410
|
+
q.text
|
|
411
|
+
// SELECT "u"."id" as "u_id" ,"u"."email" as "u_email"
|
|
412
|
+
// ,"p"."id" as "p_id" ,"p"."user_id" as "p_user_id" ,"p"."title" as "p_title"
|
|
413
|
+
// FROM "posts" "p"
|
|
414
|
+
// JOIN "users" "u" ON "p"."user_id" = "u"."id"
|
|
415
|
+
// WHERE "u"."id" = $1
|
|
416
|
+
q.values // [42]
|
|
417
|
+
```
|
|
418
|
+
|
|
419
|
+
Using **Effect** (`pipe` is data-first, which many find more readable):
|
|
420
|
+
|
|
421
|
+
```ts
|
|
422
|
+
import { pipe } from 'effect'
|
|
423
|
+
import { schema, selectAs, join, where, concat, all } from '@vanit-co/sql-ts'
|
|
424
|
+
|
|
425
|
+
const q = pipe(
|
|
426
|
+
selectAs`SELECT ${all(users, posts)} FROM ${posts}`,
|
|
427
|
+
concat(join` JOIN ${users} ON ${posts.user_id} = ${users.id}`),
|
|
428
|
+
concat(where` WHERE ${users.id} = ${42}`)
|
|
429
|
+
)
|
|
430
|
+
```
|
|
431
|
+
|
|
432
|
+
### `empty`
|
|
433
|
+
|
|
434
|
+
An empty fragment. Acts as the identity element for `concat` - useful as the starting value when accumulating fragments conditionally.
|
|
435
|
+
|
|
436
|
+
```ts
|
|
437
|
+
import { pipe, reduce } from 'ramda'
|
|
438
|
+
import { schema, select, join, where, concat, empty, all } from '@vanit-co/sql-ts'
|
|
439
|
+
|
|
440
|
+
const users = schema({ table: 'users', columns: ['id', 'email'], alias: 'u' })
|
|
441
|
+
const posts = schema({ table: 'posts', columns: ['id', 'user_id', 'title'], alias: 'p' })
|
|
442
|
+
|
|
443
|
+
type Filters = { userId?: number; titleLike?: string }
|
|
444
|
+
|
|
445
|
+
const buildPostsQuery = ({ userId, titleLike }: Filters) => {
|
|
446
|
+
const clauses = [
|
|
447
|
+
select`SELECT ${all(users, posts)} FROM ${posts}`,
|
|
448
|
+
join` JOIN ${users} ON ${posts.user_id} = ${users.id}`,
|
|
449
|
+
userId ? where` WHERE ${users.id} = ${userId}` : empty,
|
|
450
|
+
titleLike ? where` AND ${posts.title} LIKE ${titleLike}` : empty,
|
|
451
|
+
]
|
|
452
|
+
|
|
453
|
+
return reduce(
|
|
454
|
+
(acc, clause) => concat(clause)(acc),
|
|
455
|
+
empty,
|
|
456
|
+
clauses
|
|
457
|
+
)
|
|
458
|
+
}
|
|
459
|
+
|
|
460
|
+
const q = buildPostsQuery({ userId: 7, titleLike: '%TypeScript%' })
|
|
461
|
+
q.text
|
|
462
|
+
// SELECT "u"."id" as "u_id" ,"u"."email" as "u_email"
|
|
463
|
+
// ,"p"."id" as "p_id" ,"p"."user_id" as "p_user_id" ,"p"."title" as "p_title"
|
|
464
|
+
// FROM "posts" "p"
|
|
465
|
+
// JOIN "users" "u" ON "p"."user_id" = "u"."id"
|
|
466
|
+
// WHERE "u"."id" = $1
|
|
467
|
+
// AND "p"."title" LIKE $2
|
|
468
|
+
q.values // [7, '%TypeScript%']
|
|
469
|
+
```
|
|
470
|
+
|
|
471
|
+
---
|
|
472
|
+
|
|
473
|
+
## Dialect functions: `toMysql` and `toPostgres`
|
|
474
|
+
|
|
475
|
+
Convert any `Fragment` directly to a dialect-specific result. The template tags already expose `.sql` and `.text` on their return value, but you can call these directly when working with raw fragments.
|
|
476
|
+
|
|
477
|
+
```ts
|
|
478
|
+
import { toMysql, toPostgres } from '@vanit-co/sql-ts'
|
|
479
|
+
|
|
480
|
+
const result = toPostgres(someFragment)
|
|
481
|
+
// { text: 'SELECT ... WHERE id = $1', values: [42] }
|
|
482
|
+
|
|
483
|
+
const mysqlResult = toMysql(someFragment)
|
|
484
|
+
// { sql: 'SELECT ... WHERE id = ?', values: [42] }
|
|
485
|
+
```
|
|
486
|
+
|
|
487
|
+
---
|
|
488
|
+
|
|
489
|
+
## Escaping and raw SQL: `raw`
|
|
490
|
+
|
|
491
|
+
By default, every interpolated value is treated as a bind parameter. Use `raw` to inject an unescaped SQL snippet directly into the query string. **Only use `raw` with trusted, static strings.**
|
|
492
|
+
|
|
493
|
+
```ts
|
|
494
|
+
import { sql, raw } from '@vanit-co/sql-ts'
|
|
495
|
+
|
|
496
|
+
const q = sql`SELECT ${raw('COUNT(*)')} AS total FROM users`
|
|
497
|
+
q.text // SELECT COUNT(*) AS total FROM users
|
|
498
|
+
q.values // []
|
|
499
|
+
```
|
|
500
|
+
|
|
501
|
+
`raw` works anywhere a value is accepted, including the column values passed to `insert` and `update`.
|
|
502
|
+
|
|
503
|
+
---
|
|
504
|
+
|
|
505
|
+
## Prepared statements: `preparedStatementName`
|
|
506
|
+
|
|
507
|
+
Attach a name to a `Result` for use with named prepared statements (e.g., `pg`'s `{ name, text, values }` query format).
|
|
508
|
+
|
|
509
|
+
```ts
|
|
510
|
+
import { sql, preparedStatementName } from '@vanit-co/sql-ts'
|
|
511
|
+
|
|
512
|
+
const q = sql`SELECT * FROM ${users} WHERE id = ${1}`
|
|
513
|
+
const named = preparedStatementName(q, 'get-user-by-id')
|
|
514
|
+
|
|
515
|
+
named.name // 'get-user-by-id'
|
|
516
|
+
named.text // SELECT * FROM users WHERE id = $1
|
|
517
|
+
named.values // [1]
|
|
518
|
+
|
|
519
|
+
// Pass to pg:
|
|
520
|
+
await client.query(named)
|
|
521
|
+
```
|
|
522
|
+
|
|
523
|
+
`preparedStatementName` does not mutate the original result - it returns a new object.
|
|
524
|
+
|
|
525
|
+
---
|
|
526
|
+
|
|
527
|
+
## License
|
|
528
|
+
|
|
529
|
+
MIT
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@vanit-co/sql-ts",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "1.0.0",
|
|
4
4
|
"description": "A TypeScript SQL query builder using tagged template literals. Write plain SQL with safe, automatic parameter binding and properly quoted identifiers. No DSL to learn, no magic, no ORM.",
|
|
5
5
|
"type": "commonjs",
|
|
6
6
|
"main": "./dist/index.js",
|