@sigil-dev/plugin-sql 0.9.20 → 0.9.22
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +324 -314
- package/package.json +2 -2
- package/src/bun.ts +292 -265
- package/src/contract.ts +249 -249
- package/src/database.ts +764 -750
- package/src/fragment.ts +304 -304
- package/src/index.ts +67 -66
- package/src/testing.ts +148 -148
package/src/database.ts
CHANGED
|
@@ -1,750 +1,764 @@
|
|
|
1
|
-
import { AsyncLocalStorage } from "node:async_hooks";
|
|
2
|
-
import {
|
|
3
|
-
createFragment,
|
|
4
|
-
createHelper,
|
|
5
|
-
isHelper,
|
|
6
|
-
type Fragment,
|
|
7
|
-
type FragmentRunner,
|
|
8
|
-
type SqlHelper,
|
|
9
|
-
} from "./fragment.ts";
|
|
10
|
-
import { workerContext, type GrimoirePlugin } from "@sigil-dev/grimoire";
|
|
11
|
-
import {
|
|
12
|
-
SQL_CONTRACT_VERSION,
|
|
13
|
-
type SqlAdapter,
|
|
14
|
-
type SqlCapabilities,
|
|
15
|
-
} from "./contract.ts";
|
|
16
|
-
|
|
17
|
-
/**
|
|
18
|
-
* The `db.sql` tag. `T` is the row type; a run resolves to `T[]`.
|
|
19
|
-
*
|
|
20
|
-
* Called as a function rather than a tag it is the driver's helper, built
|
|
21
|
-
* lazily like a fragment so it is safe at module scope:
|
|
22
|
-
*
|
|
23
|
-
* ```ts
|
|
24
|
-
* db.sql`select * from cards where id in ${db.sql(ids)}`
|
|
25
|
-
* db.sql`select * from cards where attr = any(${db.sql.array(attrs, "text")})`
|
|
26
|
-
* db.sql`insert into t ${db.sql(row, "a", "b")}`
|
|
27
|
-
* db.sql`select * from ${db.sql("table_name")}` // an escaped identifier
|
|
28
|
-
* ```
|
|
29
|
-
*/
|
|
30
|
-
export interface SqlTag {
|
|
31
|
-
// biome-ignore lint/suspicious/noExplicitAny: the default row, as in Bun.SQL
|
|
32
|
-
<T = any>(
|
|
33
|
-
strings: TemplateStringsArray,
|
|
34
|
-
...values: unknown[]
|
|
35
|
-
): Fragment<T>;
|
|
36
|
-
(value: unknown, ...columns: string[]): SqlHelper;
|
|
37
|
-
/** A postgres array parameter, e.g. for `= any(...)`. */
|
|
38
|
-
array(values: readonly unknown[], type?: string): SqlHelper;
|
|
39
|
-
}
|
|
40
|
-
|
|
41
|
-
const isTemplate = (v: unknown): v is TemplateStringsArray =>
|
|
42
|
-
Array.isArray(v) && "raw" in v;
|
|
43
|
-
|
|
44
|
-
/**
|
|
45
|
-
* The tag, built once per database handle. `caps` is read when the tag is
|
|
46
|
-
* used, so a lazy `database(name)` handle can build one before the database
|
|
47
|
-
* it names is registered.
|
|
48
|
-
*/
|
|
49
|
-
function buildTag(
|
|
50
|
-
name: string,
|
|
51
|
-
caps: () => { adapter: string; capabilities: SqlCapabilities<unknown, unknown> },
|
|
52
|
-
pick: Pick<FragmentRunner, "run" | "runTx" | "runPool">,
|
|
53
|
-
): SqlTag {
|
|
54
|
-
const runner: FragmentRunner = {
|
|
55
|
-
...pick,
|
|
56
|
-
query: (target, text, values, strings) => {
|
|
57
|
-
const { capabilities } = caps();
|
|
58
|
-
const resolved = values.some(isHelper)
|
|
59
|
-
? values.map((v) =>
|
|
60
|
-
isHelper(v) ? capabilities.helper!(target, v.method, v.args) : v,
|
|
61
|
-
)
|
|
62
|
-
: values;
|
|
63
|
-
return capabilities.query!(target, text, resolved, strings);
|
|
64
|
-
},
|
|
65
|
-
};
|
|
66
|
-
|
|
67
|
-
const refuse = (what: string, capability: string): never => {
|
|
68
|
-
throw new Error(
|
|
69
|
-
`sql database "${name}" has no ${what}: adapter ` +
|
|
70
|
-
`"${caps().adapter}" does not declare capabilities.${capability}, ` +
|
|
71
|
-
"so it cannot bind parameters safely. Use the client's own " +
|
|
72
|
-
"query API, or an adapter that declares the capability.",
|
|
73
|
-
);
|
|
74
|
-
};
|
|
75
|
-
|
|
76
|
-
const tag = ((first: unknown, ...rest: unknown[]) => {
|
|
77
|
-
const { capabilities } = caps();
|
|
78
|
-
if (!capabilities.query) refuse("sql tag", "query");
|
|
79
|
-
if (isTemplate(first)) return createFragment(first, rest, runner);
|
|
80
|
-
if (!capabilities.helper) refuse("sql helpers", "helper");
|
|
81
|
-
return createHelper(undefined, [first, ...rest]);
|
|
82
|
-
}) as SqlTag;
|
|
83
|
-
tag.array = (values, type) => {
|
|
84
|
-
const { capabilities } = caps();
|
|
85
|
-
if (!capabilities.query || !capabilities.helper) {
|
|
86
|
-
refuse("sql helpers", "helper");
|
|
87
|
-
}
|
|
88
|
-
return createHelper("array", type === undefined ? [values] : [values, type]);
|
|
89
|
-
};
|
|
90
|
-
return tag;
|
|
91
|
-
}
|
|
92
|
-
|
|
93
|
-
/**
|
|
94
|
-
* What `locals.db` is: the client, plus the `sql` tag.
|
|
95
|
-
*
|
|
96
|
-
* Declare it on `App.Locals` once and every route gets it typed:
|
|
97
|
-
*
|
|
98
|
-
* ```ts
|
|
99
|
-
* // src/app.d.ts
|
|
100
|
-
* import type { BunSqlHandle } from "@sigil-dev/plugin-sql/bun";
|
|
101
|
-
* declare global {
|
|
102
|
-
* namespace App {
|
|
103
|
-
* interface Locals { db: BunSqlHandle }
|
|
104
|
-
* }
|
|
105
|
-
* }
|
|
106
|
-
* export {};
|
|
107
|
-
* ```
|
|
108
|
-
*/
|
|
109
|
-
export type SqlHandle<C> = C & { sql: SqlTag };
|
|
110
|
-
|
|
111
|
-
/**
|
|
112
|
-
* One database, as a value you pass around.
|
|
113
|
-
*
|
|
114
|
-
* Every database is its own instance with its own client and its own
|
|
115
|
-
* AsyncLocalStorage, so two of them in one config cannot overwrite each
|
|
116
|
-
* other: an app with a primary and a read-only replica needs both.
|
|
117
|
-
*
|
|
118
|
-
* ## Which accessor to use
|
|
119
|
-
*
|
|
120
|
-
* db() whatever is active: the request transaction if there is one,
|
|
121
|
-
* otherwise the pool. For reads, and for writes that do not
|
|
122
|
-
* need to be atomic with anything.
|
|
123
|
-
* tx() must be inside a transaction. Throws otherwise, naming this
|
|
124
|
-
* database. For writes that must roll back with the request.
|
|
125
|
-
* pool() always the pool, deliberately outside any transaction. For
|
|
126
|
-
* writes that must survive a rollback — audit records for a
|
|
127
|
-
* failed payment, that kind of thing.
|
|
128
|
-
*
|
|
129
|
-
* `db()` falling back to the pool is convenient and dangerous in equal
|
|
130
|
-
* measure, which is exactly why `tx()` exists: a job enqueue that assumes
|
|
131
|
-
* it is in the request's transaction and silently is not will happily
|
|
132
|
-
* enqueue jobs for an order that rolled back.
|
|
133
|
-
*
|
|
134
|
-
* ## Outside a request
|
|
135
|
-
*
|
|
136
|
-
* A Database is a value, so any server module can import it — or look it
|
|
137
|
-
* up with `database(name)` — and use it from a websocket handler, a timer,
|
|
138
|
-
* `hooks.server.ts` or a script. There the accessors resolve to the pool,
|
|
139
|
-
* and `transaction()` opens a real one. A script that runs without the
|
|
140
|
-
* server calls `open()` and `close()` itself.
|
|
141
|
-
*/
|
|
142
|
-
export interface Database<C, Tx> {
|
|
143
|
-
/** The name this database was created with. */
|
|
144
|
-
name: string;
|
|
145
|
-
|
|
146
|
-
/**
|
|
147
|
-
* The request transaction when one is in scope, otherwise the pool.
|
|
148
|
-
*
|
|
149
|
-
* Typed `C | Tx` because the two share a surface for ordinary queries
|
|
150
|
-
* and a union is what that is. Use `tx()` or `pool()` when the
|
|
151
|
-
* difference matters.
|
|
152
|
-
*/
|
|
153
|
-
db(): C | Tx;
|
|
154
|
-
|
|
155
|
-
/**
|
|
156
|
-
* The current transaction, or a throw naming this database.
|
|
157
|
-
*
|
|
158
|
-
* Throwing is the point. The alternative is a pool fallback that makes
|
|
159
|
-
* a non-atomic write look atomic.
|
|
160
|
-
*/
|
|
161
|
-
tx(): Tx;
|
|
162
|
-
|
|
163
|
-
/** The pool, always. Escapes any transaction deliberately. */
|
|
164
|
-
pool(): C;
|
|
165
|
-
|
|
166
|
-
/** Whether a transaction is currently in scope on this async chain. */
|
|
167
|
-
inTransaction(): boolean;
|
|
168
|
-
|
|
169
|
-
/**
|
|
170
|
-
* Run `fn` in a transaction. `tx()`, `db()` and `locals.db` are that
|
|
171
|
-
* transaction inside it, and nothing needs threading to get that right.
|
|
172
|
-
*
|
|
173
|
-
* Inside another transaction — including the request's own under
|
|
174
|
-
* `perRequestTx` — this nests: a savepoint when the adapter declares
|
|
175
|
-
* `capabilities.savepoint`, otherwise it joins the outer transaction.
|
|
176
|
-
* It never opens a second, independent one: that would commit even if
|
|
177
|
-
* the request rolled back, and deadlock on the request's own row locks.
|
|
178
|
-
*/
|
|
179
|
-
transaction<R>(fn: (tx: Tx) => Promise<R>): Promise<R>;
|
|
180
|
-
|
|
181
|
-
/** Optional driver features, declared by the adapter. */
|
|
182
|
-
capabilities: SqlCapabilities<C, Tx>;
|
|
183
|
-
|
|
184
|
-
/**
|
|
185
|
-
* A lazy, composable query tag.
|
|
186
|
-
*
|
|
187
|
-
* ```ts
|
|
188
|
-
* const active = db.sql`deleted_at is null`;
|
|
189
|
-
* const rows = await db.sql<User>`select * from t where ${active}`;
|
|
190
|
-
* ```
|
|
191
|
-
*
|
|
192
|
-
* Building one does not touch a connection, so it is safe at module
|
|
193
|
-
* scope — which is what a shared query in `lib/` has to be. Running it
|
|
194
|
-
* resolves the client at that moment, so the same constant runs inside
|
|
195
|
-
* the request's transaction and does not re-use a result.
|
|
196
|
-
*
|
|
197
|
-
* Only works when the adapter really binds parameters. Throws at
|
|
198
|
-
* construction otherwise, rather than handing back something that looks
|
|
199
|
-
* like it interpolates safely and does not.
|
|
200
|
-
*/
|
|
201
|
-
sql: SqlTag;
|
|
202
|
-
|
|
203
|
-
/**
|
|
204
|
-
* Open the client and check it answers. Idempotent, and concurrent
|
|
205
|
-
* callers share one attempt.
|
|
206
|
-
*
|
|
207
|
-
* The server calls this for you at startup. Call it yourself only where
|
|
208
|
-
* no server runs — a migration script, a seed, a test.
|
|
209
|
-
*/
|
|
210
|
-
open(): Promise<void>;
|
|
211
|
-
|
|
212
|
-
/** Close the client. The server calls this on shutdown. */
|
|
213
|
-
close(): Promise<void>;
|
|
214
|
-
|
|
215
|
-
/**
|
|
216
|
-
* What this database publishes as `locals[key]`: an object that behaves
|
|
217
|
-
* like the client, while running against the request's transaction when
|
|
218
|
-
* there is one. Every method is resolved when it is called, so
|
|
219
|
-
* `locals.db.unsafe()` and a Drizzle builder join the transaction the
|
|
220
|
-
* same way the tagged template does.
|
|
221
|
-
*/
|
|
222
|
-
localsHandle(): SqlHandle<C>;
|
|
223
|
-
|
|
224
|
-
/** Register this database with Grimoire. */
|
|
225
|
-
plugin: GrimoirePlugin;
|
|
226
|
-
}
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
key
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
*
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
/**
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
*/
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
//
|
|
355
|
-
//
|
|
356
|
-
//
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
};
|
|
390
|
-
|
|
391
|
-
/**
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
//
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
const
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
//
|
|
590
|
-
//
|
|
591
|
-
//
|
|
592
|
-
//
|
|
593
|
-
//
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
*
|
|
638
|
-
*
|
|
639
|
-
*
|
|
640
|
-
*
|
|
641
|
-
*
|
|
642
|
-
*
|
|
643
|
-
*
|
|
644
|
-
*
|
|
645
|
-
|
|
646
|
-
|
|
647
|
-
|
|
648
|
-
|
|
649
|
-
|
|
650
|
-
|
|
651
|
-
*
|
|
652
|
-
*
|
|
653
|
-
*
|
|
654
|
-
*
|
|
655
|
-
|
|
656
|
-
|
|
657
|
-
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
|
|
661
|
-
|
|
662
|
-
|
|
663
|
-
|
|
664
|
-
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
|
|
673
|
-
|
|
674
|
-
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
|
|
689
|
-
|
|
690
|
-
|
|
691
|
-
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
{
|
|
695
|
-
|
|
696
|
-
|
|
697
|
-
|
|
698
|
-
|
|
699
|
-
|
|
700
|
-
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
|
|
706
|
-
|
|
707
|
-
|
|
708
|
-
|
|
709
|
-
|
|
710
|
-
|
|
711
|
-
|
|
712
|
-
|
|
713
|
-
|
|
714
|
-
|
|
715
|
-
|
|
716
|
-
|
|
717
|
-
|
|
718
|
-
|
|
719
|
-
|
|
720
|
-
|
|
721
|
-
): unknown {
|
|
722
|
-
const
|
|
723
|
-
if (!
|
|
724
|
-
throw new Error(
|
|
725
|
-
`sql database "${name}" has no sql
|
|
726
|
-
"declare capabilities.
|
|
727
|
-
);
|
|
728
|
-
}
|
|
729
|
-
return
|
|
730
|
-
}
|
|
731
|
-
|
|
732
|
-
|
|
733
|
-
|
|
734
|
-
|
|
735
|
-
|
|
736
|
-
|
|
737
|
-
|
|
738
|
-
|
|
739
|
-
|
|
740
|
-
|
|
741
|
-
|
|
742
|
-
|
|
743
|
-
|
|
744
|
-
|
|
745
|
-
|
|
746
|
-
|
|
747
|
-
|
|
748
|
-
|
|
749
|
-
|
|
750
|
-
|
|
1
|
+
import { AsyncLocalStorage } from "node:async_hooks";
|
|
2
|
+
import {
|
|
3
|
+
createFragment,
|
|
4
|
+
createHelper,
|
|
5
|
+
isHelper,
|
|
6
|
+
type Fragment,
|
|
7
|
+
type FragmentRunner,
|
|
8
|
+
type SqlHelper,
|
|
9
|
+
} from "./fragment.ts";
|
|
10
|
+
import { workerContext, type GrimoirePlugin } from "@sigil-dev/grimoire";
|
|
11
|
+
import {
|
|
12
|
+
SQL_CONTRACT_VERSION,
|
|
13
|
+
type SqlAdapter,
|
|
14
|
+
type SqlCapabilities,
|
|
15
|
+
} from "./contract.ts";
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* The `db.sql` tag. `T` is the row type; a run resolves to `T[]`.
|
|
19
|
+
*
|
|
20
|
+
* Called as a function rather than a tag it is the driver's helper, built
|
|
21
|
+
* lazily like a fragment so it is safe at module scope:
|
|
22
|
+
*
|
|
23
|
+
* ```ts
|
|
24
|
+
* db.sql`select * from cards where id in ${db.sql(ids)}`
|
|
25
|
+
* db.sql`select * from cards where attr = any(${db.sql.array(attrs, "text")})`
|
|
26
|
+
* db.sql`insert into t ${db.sql(row, "a", "b")}`
|
|
27
|
+
* db.sql`select * from ${db.sql("table_name")}` // an escaped identifier
|
|
28
|
+
* ```
|
|
29
|
+
*/
|
|
30
|
+
export interface SqlTag {
|
|
31
|
+
// biome-ignore lint/suspicious/noExplicitAny: the default row, as in Bun.SQL
|
|
32
|
+
<T = any>(
|
|
33
|
+
strings: TemplateStringsArray,
|
|
34
|
+
...values: unknown[]
|
|
35
|
+
): Fragment<T>;
|
|
36
|
+
(value: unknown, ...columns: string[]): SqlHelper;
|
|
37
|
+
/** A postgres array parameter, e.g. for `= any(...)`. */
|
|
38
|
+
array(values: readonly unknown[], type?: string): SqlHelper;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
const isTemplate = (v: unknown): v is TemplateStringsArray =>
|
|
42
|
+
Array.isArray(v) && "raw" in v;
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* The tag, built once per database handle. `caps` is read when the tag is
|
|
46
|
+
* used, so a lazy `database(name)` handle can build one before the database
|
|
47
|
+
* it names is registered.
|
|
48
|
+
*/
|
|
49
|
+
function buildTag(
|
|
50
|
+
name: string,
|
|
51
|
+
caps: () => { adapter: string; capabilities: SqlCapabilities<unknown, unknown> },
|
|
52
|
+
pick: Pick<FragmentRunner, "run" | "runTx" | "runPool">,
|
|
53
|
+
): SqlTag {
|
|
54
|
+
const runner: FragmentRunner = {
|
|
55
|
+
...pick,
|
|
56
|
+
query: (target, text, values, strings) => {
|
|
57
|
+
const { capabilities } = caps();
|
|
58
|
+
const resolved = values.some(isHelper)
|
|
59
|
+
? values.map((v) =>
|
|
60
|
+
isHelper(v) ? capabilities.helper!(target, v.method, v.args) : v,
|
|
61
|
+
)
|
|
62
|
+
: values;
|
|
63
|
+
return capabilities.query!(target, text, resolved, strings);
|
|
64
|
+
},
|
|
65
|
+
};
|
|
66
|
+
|
|
67
|
+
const refuse = (what: string, capability: string): never => {
|
|
68
|
+
throw new Error(
|
|
69
|
+
`sql database "${name}" has no ${what}: adapter ` +
|
|
70
|
+
`"${caps().adapter}" does not declare capabilities.${capability}, ` +
|
|
71
|
+
"so it cannot bind parameters safely. Use the client's own " +
|
|
72
|
+
"query API, or an adapter that declares the capability.",
|
|
73
|
+
);
|
|
74
|
+
};
|
|
75
|
+
|
|
76
|
+
const tag = ((first: unknown, ...rest: unknown[]) => {
|
|
77
|
+
const { capabilities } = caps();
|
|
78
|
+
if (!capabilities.query) refuse("sql tag", "query");
|
|
79
|
+
if (isTemplate(first)) return createFragment(first, rest, runner);
|
|
80
|
+
if (!capabilities.helper) refuse("sql helpers", "helper");
|
|
81
|
+
return createHelper(undefined, [first, ...rest]);
|
|
82
|
+
}) as SqlTag;
|
|
83
|
+
tag.array = (values, type) => {
|
|
84
|
+
const { capabilities } = caps();
|
|
85
|
+
if (!capabilities.query || !capabilities.helper) {
|
|
86
|
+
refuse("sql helpers", "helper");
|
|
87
|
+
}
|
|
88
|
+
return createHelper("array", type === undefined ? [values] : [values, type]);
|
|
89
|
+
};
|
|
90
|
+
return tag;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/**
|
|
94
|
+
* What `locals.db` is: the client, plus the `sql` tag.
|
|
95
|
+
*
|
|
96
|
+
* Declare it on `App.Locals` once and every route gets it typed:
|
|
97
|
+
*
|
|
98
|
+
* ```ts
|
|
99
|
+
* // src/app.d.ts
|
|
100
|
+
* import type { BunSqlHandle } from "@sigil-dev/plugin-sql/bun";
|
|
101
|
+
* declare global {
|
|
102
|
+
* namespace App {
|
|
103
|
+
* interface Locals { db: BunSqlHandle }
|
|
104
|
+
* }
|
|
105
|
+
* }
|
|
106
|
+
* export {};
|
|
107
|
+
* ```
|
|
108
|
+
*/
|
|
109
|
+
export type SqlHandle<C> = C & { sql: SqlTag };
|
|
110
|
+
|
|
111
|
+
/**
|
|
112
|
+
* One database, as a value you pass around.
|
|
113
|
+
*
|
|
114
|
+
* Every database is its own instance with its own client and its own
|
|
115
|
+
* AsyncLocalStorage, so two of them in one config cannot overwrite each
|
|
116
|
+
* other: an app with a primary and a read-only replica needs both.
|
|
117
|
+
*
|
|
118
|
+
* ## Which accessor to use
|
|
119
|
+
*
|
|
120
|
+
* db() whatever is active: the request transaction if there is one,
|
|
121
|
+
* otherwise the pool. For reads, and for writes that do not
|
|
122
|
+
* need to be atomic with anything.
|
|
123
|
+
* tx() must be inside a transaction. Throws otherwise, naming this
|
|
124
|
+
* database. For writes that must roll back with the request.
|
|
125
|
+
* pool() always the pool, deliberately outside any transaction. For
|
|
126
|
+
* writes that must survive a rollback — audit records for a
|
|
127
|
+
* failed payment, that kind of thing.
|
|
128
|
+
*
|
|
129
|
+
* `db()` falling back to the pool is convenient and dangerous in equal
|
|
130
|
+
* measure, which is exactly why `tx()` exists: a job enqueue that assumes
|
|
131
|
+
* it is in the request's transaction and silently is not will happily
|
|
132
|
+
* enqueue jobs for an order that rolled back.
|
|
133
|
+
*
|
|
134
|
+
* ## Outside a request
|
|
135
|
+
*
|
|
136
|
+
* A Database is a value, so any server module can import it — or look it
|
|
137
|
+
* up with `database(name)` — and use it from a websocket handler, a timer,
|
|
138
|
+
* `hooks.server.ts` or a script. There the accessors resolve to the pool,
|
|
139
|
+
* and `transaction()` opens a real one. A script that runs without the
|
|
140
|
+
* server calls `open()` and `close()` itself.
|
|
141
|
+
*/
|
|
142
|
+
export interface Database<C, Tx> {
|
|
143
|
+
/** The name this database was created with. */
|
|
144
|
+
name: string;
|
|
145
|
+
|
|
146
|
+
/**
|
|
147
|
+
* The request transaction when one is in scope, otherwise the pool.
|
|
148
|
+
*
|
|
149
|
+
* Typed `C | Tx` because the two share a surface for ordinary queries
|
|
150
|
+
* and a union is what that is. Use `tx()` or `pool()` when the
|
|
151
|
+
* difference matters.
|
|
152
|
+
*/
|
|
153
|
+
db(): C | Tx;
|
|
154
|
+
|
|
155
|
+
/**
|
|
156
|
+
* The current transaction, or a throw naming this database.
|
|
157
|
+
*
|
|
158
|
+
* Throwing is the point. The alternative is a pool fallback that makes
|
|
159
|
+
* a non-atomic write look atomic.
|
|
160
|
+
*/
|
|
161
|
+
tx(): Tx;
|
|
162
|
+
|
|
163
|
+
/** The pool, always. Escapes any transaction deliberately. */
|
|
164
|
+
pool(): C;
|
|
165
|
+
|
|
166
|
+
/** Whether a transaction is currently in scope on this async chain. */
|
|
167
|
+
inTransaction(): boolean;
|
|
168
|
+
|
|
169
|
+
/**
|
|
170
|
+
* Run `fn` in a transaction. `tx()`, `db()` and `locals.db` are that
|
|
171
|
+
* transaction inside it, and nothing needs threading to get that right.
|
|
172
|
+
*
|
|
173
|
+
* Inside another transaction — including the request's own under
|
|
174
|
+
* `perRequestTx` — this nests: a savepoint when the adapter declares
|
|
175
|
+
* `capabilities.savepoint`, otherwise it joins the outer transaction.
|
|
176
|
+
* It never opens a second, independent one: that would commit even if
|
|
177
|
+
* the request rolled back, and deadlock on the request's own row locks.
|
|
178
|
+
*/
|
|
179
|
+
transaction<R>(fn: (tx: Tx) => Promise<R>): Promise<R>;
|
|
180
|
+
|
|
181
|
+
/** Optional driver features, declared by the adapter. */
|
|
182
|
+
capabilities: SqlCapabilities<C, Tx>;
|
|
183
|
+
|
|
184
|
+
/**
|
|
185
|
+
* A lazy, composable query tag.
|
|
186
|
+
*
|
|
187
|
+
* ```ts
|
|
188
|
+
* const active = db.sql`deleted_at is null`;
|
|
189
|
+
* const rows = await db.sql<User>`select * from t where ${active}`;
|
|
190
|
+
* ```
|
|
191
|
+
*
|
|
192
|
+
* Building one does not touch a connection, so it is safe at module
|
|
193
|
+
* scope — which is what a shared query in `lib/` has to be. Running it
|
|
194
|
+
* resolves the client at that moment, so the same constant runs inside
|
|
195
|
+
* the request's transaction and does not re-use a result.
|
|
196
|
+
*
|
|
197
|
+
* Only works when the adapter really binds parameters. Throws at
|
|
198
|
+
* construction otherwise, rather than handing back something that looks
|
|
199
|
+
* like it interpolates safely and does not.
|
|
200
|
+
*/
|
|
201
|
+
sql: SqlTag;
|
|
202
|
+
|
|
203
|
+
/**
|
|
204
|
+
* Open the client and check it answers. Idempotent, and concurrent
|
|
205
|
+
* callers share one attempt.
|
|
206
|
+
*
|
|
207
|
+
* The server calls this for you at startup. Call it yourself only where
|
|
208
|
+
* no server runs — a migration script, a seed, a test.
|
|
209
|
+
*/
|
|
210
|
+
open(): Promise<void>;
|
|
211
|
+
|
|
212
|
+
/** Close the client. The server calls this on shutdown. */
|
|
213
|
+
close(): Promise<void>;
|
|
214
|
+
|
|
215
|
+
/**
|
|
216
|
+
* What this database publishes as `locals[key]`: an object that behaves
|
|
217
|
+
* like the client, while running against the request's transaction when
|
|
218
|
+
* there is one. Every method is resolved when it is called, so
|
|
219
|
+
* `locals.db.unsafe()` and a Drizzle builder join the transaction the
|
|
220
|
+
* same way the tagged template does.
|
|
221
|
+
*/
|
|
222
|
+
localsHandle(): SqlHandle<C>;
|
|
223
|
+
|
|
224
|
+
/** Register this database with Grimoire. */
|
|
225
|
+
plugin: GrimoirePlugin;
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
/**
|
|
229
|
+
* What `sql()` and `adapter()` return: the plugin, plus the database it
|
|
230
|
+
* registers, so another plugin can be handed the value instead of a name.
|
|
231
|
+
*
|
|
232
|
+
* `database` is undefined for an `optional` adapter that was not configured
|
|
233
|
+
* (no URL). Such a plugin registers nothing, and anything handed it should
|
|
234
|
+
* turn itself off rather than look the name up and fail later.
|
|
235
|
+
*/
|
|
236
|
+
export type DatabasePlugin<C = unknown, Tx = C> = GrimoirePlugin & {
|
|
237
|
+
/** The key this database is registered under, and published on in `locals`. */
|
|
238
|
+
readonly key: string;
|
|
239
|
+
readonly database: Database<C, Tx> | undefined;
|
|
240
|
+
};
|
|
241
|
+
|
|
242
|
+
export interface CreateDatabaseOptions {
|
|
243
|
+
/**
|
|
244
|
+
* The key this database is published on in `locals`. Defaults to
|
|
245
|
+
* "db", which is what a single-database app expects.
|
|
246
|
+
*
|
|
247
|
+
* A second database must pass a different one: two adapters on the
|
|
248
|
+
* same key would have the second overwrite the first, silently, and
|
|
249
|
+
* the app would read the wrong database with no error anywhere.
|
|
250
|
+
*/
|
|
251
|
+
key?: string;
|
|
252
|
+
/**
|
|
253
|
+
* Wrap every request in a transaction, so `locals.db`, `db()` and
|
|
254
|
+
* `tx()` are that transaction for the duration of the request.
|
|
255
|
+
*
|
|
256
|
+
* Costs one round trip per request (BEGIN/COMMIT) and holds a
|
|
257
|
+
* connection for the whole request. That is a real cost, which is why
|
|
258
|
+
* it is opt-in rather than the default.
|
|
259
|
+
*/
|
|
260
|
+
perRequestTx?: boolean;
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
/**
|
|
264
|
+
* The per-process state of a database, keyed by its name.
|
|
265
|
+
*
|
|
266
|
+
* Held here rather than in the Database object so that every object with
|
|
267
|
+
* the same name sees the same client. Two things create a second object:
|
|
268
|
+
* the dev server re-evaluating `src/lib/server/db.ts` after an edit, and a
|
|
269
|
+
* bundle that inlines its own copy of that module. Without this, either one
|
|
270
|
+
* holds a Database whose client was never opened, and fails with "used
|
|
271
|
+
* before its client was opened" while the one the config registered works.
|
|
272
|
+
*/
|
|
273
|
+
interface Slot {
|
|
274
|
+
client: unknown;
|
|
275
|
+
opening: Promise<void> | undefined;
|
|
276
|
+
als: AsyncLocalStorage<{ tx: unknown }>;
|
|
277
|
+
/** The most recently created Database with this name. */
|
|
278
|
+
current: Database<unknown, unknown> | undefined;
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
const REGISTRY = Symbol.for("sigil.sql.registry");
|
|
282
|
+
const registry: Map<string, Slot> = ((globalThis as Record<symbol, unknown>)[
|
|
283
|
+
REGISTRY
|
|
284
|
+
] ??= new Map<string, Slot>()) as Map<string, Slot>;
|
|
285
|
+
|
|
286
|
+
function slotFor(name: string): Slot {
|
|
287
|
+
let slot = registry.get(name);
|
|
288
|
+
if (!slot) {
|
|
289
|
+
slot = {
|
|
290
|
+
client: undefined,
|
|
291
|
+
opening: undefined,
|
|
292
|
+
als: new AsyncLocalStorage(),
|
|
293
|
+
current: undefined,
|
|
294
|
+
};
|
|
295
|
+
registry.set(name, slot);
|
|
296
|
+
}
|
|
297
|
+
return slot;
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
/** Carries a 5xx response out of a transaction that has to roll back. */
|
|
301
|
+
class RollbackWith {
|
|
302
|
+
constructor(readonly response: Response) {}
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
/** Methods that belong to the pool, whatever transaction is in scope. */
|
|
306
|
+
const POOL_ONLY = new Set<PropertyKey>([
|
|
307
|
+
"close",
|
|
308
|
+
"end",
|
|
309
|
+
"reserve",
|
|
310
|
+
"connect",
|
|
311
|
+
"flush",
|
|
312
|
+
"$client",
|
|
313
|
+
"batch",
|
|
314
|
+
]);
|
|
315
|
+
|
|
316
|
+
/** Methods that open a transaction, routed through `transaction()`. */
|
|
317
|
+
const TX_OPENERS = new Set<PropertyKey>(["begin", "transaction"]);
|
|
318
|
+
|
|
319
|
+
/**
|
|
320
|
+
* Create a database.
|
|
321
|
+
*
|
|
322
|
+
* This is the single implementation; `sql()` is a thin wrapper over it so
|
|
323
|
+
* that the locals-based API and this one cannot disagree about when the
|
|
324
|
+
* client opens, what a transaction is, or who closes it.
|
|
325
|
+
*
|
|
326
|
+
* `name` identifies the database for this process: creating two with the
|
|
327
|
+
* same name gives two handles on one client, which is what makes a
|
|
328
|
+
* re-imported module keep working. Use distinct names for distinct
|
|
329
|
+
* databases.
|
|
330
|
+
*/
|
|
331
|
+
export function createDatabase<C, Tx = C>(
|
|
332
|
+
name: string,
|
|
333
|
+
adapter: SqlAdapter<C, Tx>,
|
|
334
|
+
opts: CreateDatabaseOptions = {},
|
|
335
|
+
): Database<C, Tx> {
|
|
336
|
+
if (adapter.contract !== SQL_CONTRACT_VERSION) {
|
|
337
|
+
throw new Error(
|
|
338
|
+
`sql adapter "${adapter.name}" targets contract ${adapter.contract}, ` +
|
|
339
|
+
`but this build expects ${SQL_CONTRACT_VERSION}. Update the ` +
|
|
340
|
+
"adapter, not the framework: an adapter written for a different " +
|
|
341
|
+
"contract would be called with the wrong shape and fail inside a " +
|
|
342
|
+
"transaction, where the stack trace points at the plugin instead.",
|
|
343
|
+
);
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
const capabilities = (adapter.capabilities ?? {}) as SqlCapabilities<C, Tx>;
|
|
347
|
+
const key = opts.key ?? "db";
|
|
348
|
+
|
|
349
|
+
// Refuse the one combination that cannot work, at construction, where
|
|
350
|
+
// the stack trace points at the config that asked for it.
|
|
351
|
+
//
|
|
352
|
+
// `setLocal` is Postgres `SET LOCAL`: session state that is scoped to a
|
|
353
|
+
// transaction and discarded at COMMIT. Called on the pool it is an
|
|
354
|
+
// ordinary `SET`, and on a pooled connection that outlives the request
|
|
355
|
+
// the next borrower runs with the previous one's `app.user_id` and
|
|
356
|
+
// silently sees the wrong rows.
|
|
357
|
+
if (capabilities.setLocal && !opts.perRequestTx) {
|
|
358
|
+
throw new Error(
|
|
359
|
+
`sql database "${name}": the driver supports setLocal, which needs ` +
|
|
360
|
+
"a transaction, but this database was created without " +
|
|
361
|
+
"perRequestTx. Either enable it, or do not use setLocal. Calling " +
|
|
362
|
+
"setLocal on the pool would set session state that the next " +
|
|
363
|
+
"borrower of that connection inherits.",
|
|
364
|
+
);
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
const slot = slotFor(name);
|
|
368
|
+
// The store is a mutable box, not the transaction itself. ALS keeps a
|
|
369
|
+
// store alive for every async resource created inside it — including
|
|
370
|
+
// continuations that outlive the transaction, like a deferred load
|
|
371
|
+
// resolving after a streamed response flushed. A box cleared in place
|
|
372
|
+
// makes those see nothing and fall back to the pool instead of a
|
|
373
|
+
// transaction that has already committed.
|
|
374
|
+
const als = slot.als as AsyncLocalStorage<{ tx: Tx | undefined }>;
|
|
375
|
+
const current = (): Tx | undefined => als.getStore()?.tx;
|
|
376
|
+
|
|
377
|
+
const ready = (): C => {
|
|
378
|
+
if (slot.client === undefined) {
|
|
379
|
+
throw new Error(
|
|
380
|
+
`sql database "${name}" was used before its client was opened. ` +
|
|
381
|
+
"The server opens it at startup, before any request or " +
|
|
382
|
+
"hooks.server.ts init(). Outside a server — a script, a test — " +
|
|
383
|
+
`call \`await ${name === "db" ? "db" : name}.open()\` first. At ` +
|
|
384
|
+
"module scope, build a query with `.sql` instead of running one: " +
|
|
385
|
+
"a fragment does not need a client until it is awaited.",
|
|
386
|
+
);
|
|
387
|
+
}
|
|
388
|
+
return slot.client as C;
|
|
389
|
+
};
|
|
390
|
+
|
|
391
|
+
/** Run `fn` with `tx` as the transaction in scope, and clear it after. */
|
|
392
|
+
const enter = <R>(tx: Tx, fn: () => Promise<R>): Promise<R> => {
|
|
393
|
+
// One box per transaction, so a nested one gets its own scope and
|
|
394
|
+
// clearing the inner one does not release the outer.
|
|
395
|
+
const box: { tx: Tx | undefined } = { tx };
|
|
396
|
+
return als.run(box, async () => {
|
|
397
|
+
try {
|
|
398
|
+
return await fn();
|
|
399
|
+
} finally {
|
|
400
|
+
box.tx = undefined;
|
|
401
|
+
}
|
|
402
|
+
});
|
|
403
|
+
};
|
|
404
|
+
|
|
405
|
+
/**
|
|
406
|
+
* The tag, shared by `db.sql` and `locals.db.sql`. `db.sql` is only
|
|
407
|
+
* honest on a driver that binds parameters, so it refuses otherwise —
|
|
408
|
+
* when called, where the stack trace is still legible.
|
|
409
|
+
*/
|
|
410
|
+
const tag = buildTag(
|
|
411
|
+
name,
|
|
412
|
+
() => ({
|
|
413
|
+
adapter: adapter.name,
|
|
414
|
+
capabilities: capabilities as SqlCapabilities<unknown, unknown>,
|
|
415
|
+
}),
|
|
416
|
+
{
|
|
417
|
+
run: () => self.db(),
|
|
418
|
+
runTx: () => self.tx(),
|
|
419
|
+
runPool: () => self.pool(),
|
|
420
|
+
},
|
|
421
|
+
);
|
|
422
|
+
|
|
423
|
+
const self: Database<C, Tx> = {
|
|
424
|
+
name,
|
|
425
|
+
|
|
426
|
+
db: () => current() ?? ready(),
|
|
427
|
+
|
|
428
|
+
tx: () => {
|
|
429
|
+
const tx = current();
|
|
430
|
+
if (tx === undefined) {
|
|
431
|
+
throw new Error(
|
|
432
|
+
`sql database "${name}": tx() was called outside a ` +
|
|
433
|
+
"transaction. Either this code runs outside a request, or " +
|
|
434
|
+
"the database was created without perRequestTx. Wrap it in " +
|
|
435
|
+
"transaction(), or use pool() if the write must not be part " +
|
|
436
|
+
"of one.",
|
|
437
|
+
);
|
|
438
|
+
}
|
|
439
|
+
return tx;
|
|
440
|
+
},
|
|
441
|
+
|
|
442
|
+
pool: ready,
|
|
443
|
+
|
|
444
|
+
inTransaction: () => current() !== undefined,
|
|
445
|
+
|
|
446
|
+
transaction: <R>(fn: (tx: Tx) => Promise<R>): Promise<R> => {
|
|
447
|
+
const outer = current();
|
|
448
|
+
if (outer !== undefined) {
|
|
449
|
+
const savepoint = capabilities.savepoint;
|
|
450
|
+
if (savepoint) {
|
|
451
|
+
return savepoint(outer, (inner) => enter(inner, () => fn(inner)));
|
|
452
|
+
}
|
|
453
|
+
// Join. An error still propagates, and still rolls back the
|
|
454
|
+
// outer transaction unless something catches it.
|
|
455
|
+
return fn(outer);
|
|
456
|
+
}
|
|
457
|
+
return adapter.transaction(ready(), (tx) => enter(tx, () => fn(tx)));
|
|
458
|
+
},
|
|
459
|
+
|
|
460
|
+
capabilities,
|
|
461
|
+
|
|
462
|
+
sql: tag,
|
|
463
|
+
|
|
464
|
+
open() {
|
|
465
|
+
if (slot.client !== undefined) return Promise.resolve();
|
|
466
|
+
if (slot.opening) return slot.opening;
|
|
467
|
+
slot.opening = (async () => {
|
|
468
|
+
// The framework's own reader: a missing variable means one
|
|
469
|
+
// worker, which is what `sigil dev` and a script are.
|
|
470
|
+
const client = await adapter.create(workerContext());
|
|
471
|
+
try {
|
|
472
|
+
// Fail the boot, not the first request.
|
|
473
|
+
await adapter.ping(client);
|
|
474
|
+
} catch (e) {
|
|
475
|
+
// A half-open client still holds a socket.
|
|
476
|
+
try {
|
|
477
|
+
await adapter.close(client);
|
|
478
|
+
} catch {}
|
|
479
|
+
throw e;
|
|
480
|
+
}
|
|
481
|
+
slot.client = client;
|
|
482
|
+
})().finally(() => {
|
|
483
|
+
slot.opening = undefined;
|
|
484
|
+
});
|
|
485
|
+
return slot.opening;
|
|
486
|
+
},
|
|
487
|
+
|
|
488
|
+
async close() {
|
|
489
|
+
if (slot.opening) await slot.opening.catch(() => {});
|
|
490
|
+
const client = slot.client;
|
|
491
|
+
if (client === undefined) return;
|
|
492
|
+
slot.client = undefined;
|
|
493
|
+
await adapter.close(client as C);
|
|
494
|
+
},
|
|
495
|
+
|
|
496
|
+
localsHandle() {
|
|
497
|
+
const pool = ready();
|
|
498
|
+
const target = pool as unknown as object;
|
|
499
|
+
const active = (): unknown => current() ?? pool;
|
|
500
|
+
const wrappers = new Map<PropertyKey, unknown>();
|
|
501
|
+
|
|
502
|
+
const handler: ProxyHandler<object> = {
|
|
503
|
+
get(_t, prop) {
|
|
504
|
+
// Anything awaited must not be forwarded: a proxy that
|
|
505
|
+
// answers `then` would hang whatever awaited it.
|
|
506
|
+
if (prop === "then") return undefined;
|
|
507
|
+
if (prop === "sql") return tag;
|
|
508
|
+
|
|
509
|
+
const own = Reflect.get(pool as object, prop, pool);
|
|
510
|
+
// The proxy invariant: a fixed own property must be
|
|
511
|
+
// returned as-is.
|
|
512
|
+
const d = Reflect.getOwnPropertyDescriptor(target, prop);
|
|
513
|
+
if (d && !d.configurable && d.writable === false) return own;
|
|
514
|
+
|
|
515
|
+
if (POOL_ONLY.has(prop)) {
|
|
516
|
+
return typeof own === "function" ? own.bind(pool) : own;
|
|
517
|
+
}
|
|
518
|
+
|
|
519
|
+
const cur = active();
|
|
520
|
+
const value =
|
|
521
|
+
cur === pool
|
|
522
|
+
? own
|
|
523
|
+
: prop in Object(cur)
|
|
524
|
+
? Reflect.get(cur as object, prop, cur)
|
|
525
|
+
: own;
|
|
526
|
+
if (typeof value !== "function") return value;
|
|
527
|
+
|
|
528
|
+
// Resolved at call time, not at `get` time, so a method
|
|
529
|
+
// read once and kept still follows the transaction.
|
|
530
|
+
let w = wrappers.get(prop);
|
|
531
|
+
if (!w) {
|
|
532
|
+
w = TX_OPENERS.has(prop)
|
|
533
|
+
? (...args: unknown[]) => openTx(prop, args)
|
|
534
|
+
: (...args: unknown[]) => {
|
|
535
|
+
const c = active() as Record<PropertyKey, unknown>;
|
|
536
|
+
const f = (
|
|
537
|
+
prop in Object(c) ? c[prop] : (pool as never)[prop]
|
|
538
|
+
) as (...a: unknown[]) => unknown;
|
|
539
|
+
return f.apply(c, args);
|
|
540
|
+
};
|
|
541
|
+
wrappers.set(prop, w);
|
|
542
|
+
}
|
|
543
|
+
return w;
|
|
544
|
+
},
|
|
545
|
+
};
|
|
546
|
+
|
|
547
|
+
/**
|
|
548
|
+
* `locals.db.begin(fn)` and `locals.db.transaction(fn)` go
|
|
549
|
+
* through `transaction()`, so they nest inside the request's
|
|
550
|
+
* transaction instead of opening a second one on another
|
|
551
|
+
* connection, and `locals.db` inside them is the new scope.
|
|
552
|
+
*/
|
|
553
|
+
const openTx = (prop: PropertyKey, args: unknown[]): unknown => {
|
|
554
|
+
const fn = args[args.length - 1];
|
|
555
|
+
if (typeof fn !== "function") {
|
|
556
|
+
// Not the callback form (`begin()` with no callback, say):
|
|
557
|
+
// leave it to the driver.
|
|
558
|
+
return (active() as Record<PropertyKey, (...a: unknown[]) => unknown>)[
|
|
559
|
+
prop as string
|
|
560
|
+
]!(...args);
|
|
561
|
+
}
|
|
562
|
+
const body = fn as (tx: Tx) => Promise<unknown>;
|
|
563
|
+
if (args.length === 1 || current() !== undefined) {
|
|
564
|
+
return self.transaction(body);
|
|
565
|
+
}
|
|
566
|
+
// Options before the callback (`begin("read only", fn)`), outside
|
|
567
|
+
// any transaction: the driver opens it, and we scope it.
|
|
568
|
+
const opener = (pool as Record<PropertyKey, unknown>)[prop] as (
|
|
569
|
+
...a: unknown[]
|
|
570
|
+
) => unknown;
|
|
571
|
+
return opener.call(pool, ...args.slice(0, -1), (tx: Tx) =>
|
|
572
|
+
enter(tx, () => body(tx)),
|
|
573
|
+
);
|
|
574
|
+
};
|
|
575
|
+
|
|
576
|
+
if (typeof pool === "function") {
|
|
577
|
+
handler.apply = (_t, _this, args: unknown[]) =>
|
|
578
|
+
// A Bun.SQL transaction handle is itself callable, so the
|
|
579
|
+
// tagged-template form works on either side unchanged.
|
|
580
|
+
(active() as (...a: unknown[]) => unknown)(...args);
|
|
581
|
+
}
|
|
582
|
+
|
|
583
|
+
return new Proxy(target, handler) as SqlHandle<C>;
|
|
584
|
+
},
|
|
585
|
+
|
|
586
|
+
plugin: {
|
|
587
|
+
name: `sql:${name}`,
|
|
588
|
+
|
|
589
|
+
// Opened here, and not in config(). config() also runs in the
|
|
590
|
+
// `sigil start` coordinator and in `sigil build`, neither of which
|
|
591
|
+
// serves a request, and a pool opened there is never used or
|
|
592
|
+
// freed. services() runs exactly where requests are served —
|
|
593
|
+
// `sigil dev`, and each worker — and before hooks.server.ts init().
|
|
594
|
+
async services() {
|
|
595
|
+
await self.open();
|
|
596
|
+
return { [key]: self.localsHandle() };
|
|
597
|
+
},
|
|
598
|
+
|
|
599
|
+
// onRequest(req, next) receives nothing but a continuation, and
|
|
600
|
+
// everything the route does happens inside it — so a transaction
|
|
601
|
+
// opened here is in scope for the whole request.
|
|
602
|
+
//
|
|
603
|
+
// A route that throws does not make `next()` reject: the server
|
|
604
|
+
// turns the error into a 500 and resolves with that. So the
|
|
605
|
+
// status is what decides, and any 5xx rolls back. Committing
|
|
606
|
+
// because the error had already been rendered was the bug a real
|
|
607
|
+
// server found and every test that made `next()` throw missed.
|
|
608
|
+
onRequest: opts.perRequestTx
|
|
609
|
+
? async (_req, next) => {
|
|
610
|
+
try {
|
|
611
|
+
return await self.transaction(async () => {
|
|
612
|
+
const res = await next();
|
|
613
|
+
if (res.status >= 500) throw new RollbackWith(res);
|
|
614
|
+
return res;
|
|
615
|
+
});
|
|
616
|
+
} catch (e) {
|
|
617
|
+
if (e instanceof RollbackWith) return e.response;
|
|
618
|
+
throw e;
|
|
619
|
+
}
|
|
620
|
+
}
|
|
621
|
+
: undefined,
|
|
622
|
+
|
|
623
|
+
async onStop() {
|
|
624
|
+
await self.close();
|
|
625
|
+
},
|
|
626
|
+
},
|
|
627
|
+
};
|
|
628
|
+
|
|
629
|
+
slot.current = self as Database<unknown, unknown>;
|
|
630
|
+
return self;
|
|
631
|
+
}
|
|
632
|
+
|
|
633
|
+
/**
|
|
634
|
+
* Whether a database is registered under `name` — for a feature that runs
|
|
635
|
+
* only when its optional database is configured:
|
|
636
|
+
*
|
|
637
|
+
* ```ts
|
|
638
|
+
* // sigil.config.ts registers adapter({ key: "userDb", url }) only
|
|
639
|
+
* // when VIEWER_DB_URL is set
|
|
640
|
+
* export const storiesEnabled = () => hasDatabase("userDb");
|
|
641
|
+
* ```
|
|
642
|
+
*
|
|
643
|
+
* Answered from the registry, so it is right as soon as the config has been
|
|
644
|
+
* imported — before the client opens, and in a process that never opens it.
|
|
645
|
+
*/
|
|
646
|
+
export function hasDatabase(name = "db"): boolean {
|
|
647
|
+
return registry.get(name)?.current !== undefined;
|
|
648
|
+
}
|
|
649
|
+
|
|
650
|
+
/**
|
|
651
|
+
* The database registered under `name`, from anywhere in the server.
|
|
652
|
+
*
|
|
653
|
+
* ```ts
|
|
654
|
+
* // src/lib/server/users.ts
|
|
655
|
+
* import { database } from "@sigil-dev/plugin-sql";
|
|
656
|
+
* import type { BunSqlClient } from "@sigil-dev/plugin-sql/bun";
|
|
657
|
+
*
|
|
658
|
+
* const db = database<BunSqlClient>(); // the one adapter(url) opened
|
|
659
|
+
* export const byId = (id: number) =>
|
|
660
|
+
* db.sql<User>`select * from users where id = ${id}`;
|
|
661
|
+
* ```
|
|
662
|
+
*
|
|
663
|
+
* For a database opened by `adapter(url)` or `sql(...)`, the name is its
|
|
664
|
+
* `locals` key — "db" unless you passed one. For `createDatabase(name, ...)`
|
|
665
|
+
* it is that name, and importing the value itself is usually clearer.
|
|
666
|
+
*
|
|
667
|
+
* Resolved on every call rather than once, so this is safe at module scope
|
|
668
|
+
* even if the module is imported before the config registers the database.
|
|
669
|
+
*/
|
|
670
|
+
export function database<C = unknown, Tx = C>(name = "db"): Database<C, Tx> {
|
|
671
|
+
const get = (): Database<C, Tx> => {
|
|
672
|
+
const db = registry.get(name)?.current;
|
|
673
|
+
if (!db) {
|
|
674
|
+
const known = [...registry.keys()].filter(
|
|
675
|
+
(k) => registry.get(k)?.current,
|
|
676
|
+
);
|
|
677
|
+
throw new Error(
|
|
678
|
+
`no sql database named "${name}". ` +
|
|
679
|
+
(known.length
|
|
680
|
+
? `Registered: ${known.map((k) => `"${k}"`).join(", ")}.`
|
|
681
|
+
: "None is registered — add adapter(url) or createDatabase(...) " +
|
|
682
|
+
"to the plugins in sigil.config.ts."),
|
|
683
|
+
);
|
|
684
|
+
}
|
|
685
|
+
return db as Database<C, Tx>;
|
|
686
|
+
};
|
|
687
|
+
|
|
688
|
+
// Capabilities are read when the tag is used, not now: building a
|
|
689
|
+
// fragment must not need the database to be registered yet. So a missing
|
|
690
|
+
// capability is reported at run time here, where it would have been at
|
|
691
|
+
// build time on the database itself.
|
|
692
|
+
const tag = buildTag(
|
|
693
|
+
name,
|
|
694
|
+
() => {
|
|
695
|
+
if (!registry.get(name)?.current) {
|
|
696
|
+
// Let the fragment be built; running it looks the database
|
|
697
|
+
// up again and says what is missing.
|
|
698
|
+
return {
|
|
699
|
+
adapter: "(not registered yet)",
|
|
700
|
+
capabilities: { query: lateQuery, helper: lateHelper },
|
|
701
|
+
};
|
|
702
|
+
}
|
|
703
|
+
return {
|
|
704
|
+
adapter: `of database "${name}"`,
|
|
705
|
+
capabilities: get().capabilities as SqlCapabilities<unknown, unknown>,
|
|
706
|
+
};
|
|
707
|
+
},
|
|
708
|
+
{
|
|
709
|
+
run: () => get().db(),
|
|
710
|
+
runTx: () => get().tx(),
|
|
711
|
+
runPool: () => get().pool(),
|
|
712
|
+
},
|
|
713
|
+
);
|
|
714
|
+
|
|
715
|
+
/** Stand-ins used only if a fragment is built before registration. */
|
|
716
|
+
function lateQuery(
|
|
717
|
+
target: unknown,
|
|
718
|
+
text: string,
|
|
719
|
+
values: readonly unknown[],
|
|
720
|
+
strings: readonly string[],
|
|
721
|
+
): Promise<unknown[]> {
|
|
722
|
+
const q = get().capabilities.query;
|
|
723
|
+
if (!q) {
|
|
724
|
+
throw new Error(
|
|
725
|
+
`sql database "${name}" has no sql tag: its adapter does not ` +
|
|
726
|
+
"declare capabilities.query, so it cannot bind parameters.",
|
|
727
|
+
);
|
|
728
|
+
}
|
|
729
|
+
return q(target as C | Tx, text, values, strings);
|
|
730
|
+
}
|
|
731
|
+
function lateHelper(
|
|
732
|
+
target: unknown,
|
|
733
|
+
method: string | undefined,
|
|
734
|
+
args: readonly unknown[],
|
|
735
|
+
): unknown {
|
|
736
|
+
const h = get().capabilities.helper;
|
|
737
|
+
if (!h) {
|
|
738
|
+
throw new Error(
|
|
739
|
+
`sql database "${name}" has no sql helpers: its adapter does not ` +
|
|
740
|
+
"declare capabilities.helper.",
|
|
741
|
+
);
|
|
742
|
+
}
|
|
743
|
+
return h(target as C | Tx, method, args);
|
|
744
|
+
}
|
|
745
|
+
|
|
746
|
+
return {
|
|
747
|
+
name,
|
|
748
|
+
db: () => get().db(),
|
|
749
|
+
tx: () => get().tx(),
|
|
750
|
+
pool: () => get().pool(),
|
|
751
|
+
inTransaction: () => get().inTransaction(),
|
|
752
|
+
transaction: (fn) => get().transaction(fn),
|
|
753
|
+
get capabilities() {
|
|
754
|
+
return get().capabilities;
|
|
755
|
+
},
|
|
756
|
+
sql: tag,
|
|
757
|
+
open: () => get().open(),
|
|
758
|
+
close: () => get().close(),
|
|
759
|
+
localsHandle: () => get().localsHandle(),
|
|
760
|
+
get plugin() {
|
|
761
|
+
return get().plugin;
|
|
762
|
+
},
|
|
763
|
+
};
|
|
764
|
+
}
|