@sigil-dev/plugin-sql 0.9.13

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.
@@ -0,0 +1,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
+ export interface CreateDatabaseOptions {
229
+ /**
230
+ * The key this database is published on in `locals`. Defaults to
231
+ * "db", which is what a single-database app expects.
232
+ *
233
+ * A second database must pass a different one: two adapters on the
234
+ * same key would have the second overwrite the first, silently, and
235
+ * the app would read the wrong database with no error anywhere.
236
+ */
237
+ key?: string;
238
+ /**
239
+ * Wrap every request in a transaction, so `locals.db`, `db()` and
240
+ * `tx()` are that transaction for the duration of the request.
241
+ *
242
+ * Costs one round trip per request (BEGIN/COMMIT) and holds a
243
+ * connection for the whole request. That is a real cost, which is why
244
+ * it is opt-in rather than the default.
245
+ */
246
+ perRequestTx?: boolean;
247
+ }
248
+
249
+ /**
250
+ * The per-process state of a database, keyed by its name.
251
+ *
252
+ * Held here rather than in the Database object so that every object with
253
+ * the same name sees the same client. Two things create a second object:
254
+ * the dev server re-evaluating `src/lib/server/db.ts` after an edit, and a
255
+ * bundle that inlines its own copy of that module. Without this, either one
256
+ * holds a Database whose client was never opened, and fails with "used
257
+ * before its client was opened" while the one the config registered works.
258
+ */
259
+ interface Slot {
260
+ client: unknown;
261
+ opening: Promise<void> | undefined;
262
+ als: AsyncLocalStorage<{ tx: unknown }>;
263
+ /** The most recently created Database with this name. */
264
+ current: Database<unknown, unknown> | undefined;
265
+ }
266
+
267
+ const REGISTRY = Symbol.for("sigil.sql.registry");
268
+ const registry: Map<string, Slot> = ((globalThis as Record<symbol, unknown>)[
269
+ REGISTRY
270
+ ] ??= new Map<string, Slot>()) as Map<string, Slot>;
271
+
272
+ function slotFor(name: string): Slot {
273
+ let slot = registry.get(name);
274
+ if (!slot) {
275
+ slot = {
276
+ client: undefined,
277
+ opening: undefined,
278
+ als: new AsyncLocalStorage(),
279
+ current: undefined,
280
+ };
281
+ registry.set(name, slot);
282
+ }
283
+ return slot;
284
+ }
285
+
286
+ /** Carries a 5xx response out of a transaction that has to roll back. */
287
+ class RollbackWith {
288
+ constructor(readonly response: Response) {}
289
+ }
290
+
291
+ /** Methods that belong to the pool, whatever transaction is in scope. */
292
+ const POOL_ONLY = new Set<PropertyKey>([
293
+ "close",
294
+ "end",
295
+ "reserve",
296
+ "connect",
297
+ "flush",
298
+ "$client",
299
+ "batch",
300
+ ]);
301
+
302
+ /** Methods that open a transaction, routed through `transaction()`. */
303
+ const TX_OPENERS = new Set<PropertyKey>(["begin", "transaction"]);
304
+
305
+ /**
306
+ * Create a database.
307
+ *
308
+ * This is the single implementation; `sql()` is a thin wrapper over it so
309
+ * that the locals-based API and this one cannot disagree about when the
310
+ * client opens, what a transaction is, or who closes it.
311
+ *
312
+ * `name` identifies the database for this process: creating two with the
313
+ * same name gives two handles on one client, which is what makes a
314
+ * re-imported module keep working. Use distinct names for distinct
315
+ * databases.
316
+ */
317
+ export function createDatabase<C, Tx = C>(
318
+ name: string,
319
+ adapter: SqlAdapter<C, Tx>,
320
+ opts: CreateDatabaseOptions = {},
321
+ ): Database<C, Tx> {
322
+ if (adapter.contract !== SQL_CONTRACT_VERSION) {
323
+ throw new Error(
324
+ `sql adapter "${adapter.name}" targets contract ${adapter.contract}, ` +
325
+ `but this build expects ${SQL_CONTRACT_VERSION}. Update the ` +
326
+ "adapter, not the framework: an adapter written for a different " +
327
+ "contract would be called with the wrong shape and fail inside a " +
328
+ "transaction, where the stack trace points at the plugin instead.",
329
+ );
330
+ }
331
+
332
+ const capabilities = (adapter.capabilities ?? {}) as SqlCapabilities<C, Tx>;
333
+ const key = opts.key ?? "db";
334
+
335
+ // Refuse the one combination that cannot work, at construction, where
336
+ // the stack trace points at the config that asked for it.
337
+ //
338
+ // `setLocal` is Postgres `SET LOCAL`: session state that is scoped to a
339
+ // transaction and discarded at COMMIT. Called on the pool it is an
340
+ // ordinary `SET`, and on a pooled connection that outlives the request
341
+ // the next borrower runs with the previous one's `app.user_id` and
342
+ // silently sees the wrong rows.
343
+ if (capabilities.setLocal && !opts.perRequestTx) {
344
+ throw new Error(
345
+ `sql database "${name}": the driver supports setLocal, which needs ` +
346
+ "a transaction, but this database was created without " +
347
+ "perRequestTx. Either enable it, or do not use setLocal. Calling " +
348
+ "setLocal on the pool would set session state that the next " +
349
+ "borrower of that connection inherits.",
350
+ );
351
+ }
352
+
353
+ const slot = slotFor(name);
354
+ // The store is a mutable box, not the transaction itself. ALS keeps a
355
+ // store alive for every async resource created inside it — including
356
+ // continuations that outlive the transaction, like a deferred load
357
+ // resolving after a streamed response flushed. A box cleared in place
358
+ // makes those see nothing and fall back to the pool instead of a
359
+ // transaction that has already committed.
360
+ const als = slot.als as AsyncLocalStorage<{ tx: Tx | undefined }>;
361
+ const current = (): Tx | undefined => als.getStore()?.tx;
362
+
363
+ const ready = (): C => {
364
+ if (slot.client === undefined) {
365
+ throw new Error(
366
+ `sql database "${name}" was used before its client was opened. ` +
367
+ "The server opens it at startup, before any request or " +
368
+ "hooks.server.ts init(). Outside a server — a script, a test — " +
369
+ `call \`await ${name === "db" ? "db" : name}.open()\` first. At ` +
370
+ "module scope, build a query with `.sql` instead of running one: " +
371
+ "a fragment does not need a client until it is awaited.",
372
+ );
373
+ }
374
+ return slot.client as C;
375
+ };
376
+
377
+ /** Run `fn` with `tx` as the transaction in scope, and clear it after. */
378
+ const enter = <R>(tx: Tx, fn: () => Promise<R>): Promise<R> => {
379
+ // One box per transaction, so a nested one gets its own scope and
380
+ // clearing the inner one does not release the outer.
381
+ const box: { tx: Tx | undefined } = { tx };
382
+ return als.run(box, async () => {
383
+ try {
384
+ return await fn();
385
+ } finally {
386
+ box.tx = undefined;
387
+ }
388
+ });
389
+ };
390
+
391
+ /**
392
+ * The tag, shared by `db.sql` and `locals.db.sql`. `db.sql` is only
393
+ * honest on a driver that binds parameters, so it refuses otherwise —
394
+ * when called, where the stack trace is still legible.
395
+ */
396
+ const tag = buildTag(
397
+ name,
398
+ () => ({
399
+ adapter: adapter.name,
400
+ capabilities: capabilities as SqlCapabilities<unknown, unknown>,
401
+ }),
402
+ {
403
+ run: () => self.db(),
404
+ runTx: () => self.tx(),
405
+ runPool: () => self.pool(),
406
+ },
407
+ );
408
+
409
+ const self: Database<C, Tx> = {
410
+ name,
411
+
412
+ db: () => current() ?? ready(),
413
+
414
+ tx: () => {
415
+ const tx = current();
416
+ if (tx === undefined) {
417
+ throw new Error(
418
+ `sql database "${name}": tx() was called outside a ` +
419
+ "transaction. Either this code runs outside a request, or " +
420
+ "the database was created without perRequestTx. Wrap it in " +
421
+ "transaction(), or use pool() if the write must not be part " +
422
+ "of one.",
423
+ );
424
+ }
425
+ return tx;
426
+ },
427
+
428
+ pool: ready,
429
+
430
+ inTransaction: () => current() !== undefined,
431
+
432
+ transaction: <R>(fn: (tx: Tx) => Promise<R>): Promise<R> => {
433
+ const outer = current();
434
+ if (outer !== undefined) {
435
+ const savepoint = capabilities.savepoint;
436
+ if (savepoint) {
437
+ return savepoint(outer, (inner) => enter(inner, () => fn(inner)));
438
+ }
439
+ // Join. An error still propagates, and still rolls back the
440
+ // outer transaction unless something catches it.
441
+ return fn(outer);
442
+ }
443
+ return adapter.transaction(ready(), (tx) => enter(tx, () => fn(tx)));
444
+ },
445
+
446
+ capabilities,
447
+
448
+ sql: tag,
449
+
450
+ open() {
451
+ if (slot.client !== undefined) return Promise.resolve();
452
+ if (slot.opening) return slot.opening;
453
+ slot.opening = (async () => {
454
+ // The framework's own reader: a missing variable means one
455
+ // worker, which is what `sigil dev` and a script are.
456
+ const client = await adapter.create(workerContext());
457
+ try {
458
+ // Fail the boot, not the first request.
459
+ await adapter.ping(client);
460
+ } catch (e) {
461
+ // A half-open client still holds a socket.
462
+ try {
463
+ await adapter.close(client);
464
+ } catch {}
465
+ throw e;
466
+ }
467
+ slot.client = client;
468
+ })().finally(() => {
469
+ slot.opening = undefined;
470
+ });
471
+ return slot.opening;
472
+ },
473
+
474
+ async close() {
475
+ if (slot.opening) await slot.opening.catch(() => {});
476
+ const client = slot.client;
477
+ if (client === undefined) return;
478
+ slot.client = undefined;
479
+ await adapter.close(client as C);
480
+ },
481
+
482
+ localsHandle() {
483
+ const pool = ready();
484
+ const target = pool as unknown as object;
485
+ const active = (): unknown => current() ?? pool;
486
+ const wrappers = new Map<PropertyKey, unknown>();
487
+
488
+ const handler: ProxyHandler<object> = {
489
+ get(_t, prop) {
490
+ // Anything awaited must not be forwarded: a proxy that
491
+ // answers `then` would hang whatever awaited it.
492
+ if (prop === "then") return undefined;
493
+ if (prop === "sql") return tag;
494
+
495
+ const own = Reflect.get(pool as object, prop, pool);
496
+ // The proxy invariant: a fixed own property must be
497
+ // returned as-is.
498
+ const d = Reflect.getOwnPropertyDescriptor(target, prop);
499
+ if (d && !d.configurable && d.writable === false) return own;
500
+
501
+ if (POOL_ONLY.has(prop)) {
502
+ return typeof own === "function" ? own.bind(pool) : own;
503
+ }
504
+
505
+ const cur = active();
506
+ const value =
507
+ cur === pool
508
+ ? own
509
+ : prop in Object(cur)
510
+ ? Reflect.get(cur as object, prop, cur)
511
+ : own;
512
+ if (typeof value !== "function") return value;
513
+
514
+ // Resolved at call time, not at `get` time, so a method
515
+ // read once and kept still follows the transaction.
516
+ let w = wrappers.get(prop);
517
+ if (!w) {
518
+ w = TX_OPENERS.has(prop)
519
+ ? (...args: unknown[]) => openTx(prop, args)
520
+ : (...args: unknown[]) => {
521
+ const c = active() as Record<PropertyKey, unknown>;
522
+ const f = (
523
+ prop in Object(c) ? c[prop] : (pool as never)[prop]
524
+ ) as (...a: unknown[]) => unknown;
525
+ return f.apply(c, args);
526
+ };
527
+ wrappers.set(prop, w);
528
+ }
529
+ return w;
530
+ },
531
+ };
532
+
533
+ /**
534
+ * `locals.db.begin(fn)` and `locals.db.transaction(fn)` go
535
+ * through `transaction()`, so they nest inside the request's
536
+ * transaction instead of opening a second one on another
537
+ * connection, and `locals.db` inside them is the new scope.
538
+ */
539
+ const openTx = (prop: PropertyKey, args: unknown[]): unknown => {
540
+ const fn = args[args.length - 1];
541
+ if (typeof fn !== "function") {
542
+ // Not the callback form (`begin()` with no callback, say):
543
+ // leave it to the driver.
544
+ return (active() as Record<PropertyKey, (...a: unknown[]) => unknown>)[
545
+ prop as string
546
+ ]!(...args);
547
+ }
548
+ const body = fn as (tx: Tx) => Promise<unknown>;
549
+ if (args.length === 1 || current() !== undefined) {
550
+ return self.transaction(body);
551
+ }
552
+ // Options before the callback (`begin("read only", fn)`), outside
553
+ // any transaction: the driver opens it, and we scope it.
554
+ const opener = (pool as Record<PropertyKey, unknown>)[prop] as (
555
+ ...a: unknown[]
556
+ ) => unknown;
557
+ return opener.call(pool, ...args.slice(0, -1), (tx: Tx) =>
558
+ enter(tx, () => body(tx)),
559
+ );
560
+ };
561
+
562
+ if (typeof pool === "function") {
563
+ handler.apply = (_t, _this, args: unknown[]) =>
564
+ // A Bun.SQL transaction handle is itself callable, so the
565
+ // tagged-template form works on either side unchanged.
566
+ (active() as (...a: unknown[]) => unknown)(...args);
567
+ }
568
+
569
+ return new Proxy(target, handler) as SqlHandle<C>;
570
+ },
571
+
572
+ plugin: {
573
+ name: `sql:${name}`,
574
+
575
+ // Opened here, and not in config(). config() also runs in the
576
+ // `sigil start` coordinator and in `sigil build`, neither of which
577
+ // serves a request, and a pool opened there is never used or
578
+ // freed. services() runs exactly where requests are served —
579
+ // `sigil dev`, and each worker — and before hooks.server.ts init().
580
+ async services() {
581
+ await self.open();
582
+ return { [key]: self.localsHandle() };
583
+ },
584
+
585
+ // onRequest(req, next) receives nothing but a continuation, and
586
+ // everything the route does happens inside it — so a transaction
587
+ // opened here is in scope for the whole request.
588
+ //
589
+ // A route that throws does not make `next()` reject: the server
590
+ // turns the error into a 500 and resolves with that. So the
591
+ // status is what decides, and any 5xx rolls back. Committing
592
+ // because the error had already been rendered was the bug a real
593
+ // server found and every test that made `next()` throw missed.
594
+ onRequest: opts.perRequestTx
595
+ ? async (_req, next) => {
596
+ try {
597
+ return await self.transaction(async () => {
598
+ const res = await next();
599
+ if (res.status >= 500) throw new RollbackWith(res);
600
+ return res;
601
+ });
602
+ } catch (e) {
603
+ if (e instanceof RollbackWith) return e.response;
604
+ throw e;
605
+ }
606
+ }
607
+ : undefined,
608
+
609
+ async onStop() {
610
+ await self.close();
611
+ },
612
+ },
613
+ };
614
+
615
+ slot.current = self as Database<unknown, unknown>;
616
+ return self;
617
+ }
618
+
619
+ /**
620
+ * Whether a database is registered under `name` — for a feature that runs
621
+ * only when its optional database is configured:
622
+ *
623
+ * ```ts
624
+ * // sigil.config.ts registers adapter(url, {}, { key: "userDb" }) only
625
+ * // when VIEWER_DB_URL is set
626
+ * export const storiesEnabled = () => hasDatabase("userDb");
627
+ * ```
628
+ *
629
+ * Answered from the registry, so it is right as soon as the config has been
630
+ * imported — before the client opens, and in a process that never opens it.
631
+ */
632
+ export function hasDatabase(name = "db"): boolean {
633
+ return registry.get(name)?.current !== undefined;
634
+ }
635
+
636
+ /**
637
+ * The database registered under `name`, from anywhere in the server.
638
+ *
639
+ * ```ts
640
+ * // src/lib/server/users.ts
641
+ * import { database } from "@sigil-dev/plugin-sql";
642
+ * import type { BunSqlClient } from "@sigil-dev/plugin-sql/bun";
643
+ *
644
+ * const db = database<BunSqlClient>(); // the one adapter(url) opened
645
+ * export const byId = (id: number) =>
646
+ * db.sql<User>`select * from users where id = ${id}`;
647
+ * ```
648
+ *
649
+ * For a database opened by `adapter(url)` or `sql(...)`, the name is its
650
+ * `locals` key — "db" unless you passed one. For `createDatabase(name, ...)`
651
+ * it is that name, and importing the value itself is usually clearer.
652
+ *
653
+ * Resolved on every call rather than once, so this is safe at module scope
654
+ * even if the module is imported before the config registers the database.
655
+ */
656
+ export function database<C = unknown, Tx = C>(name = "db"): Database<C, Tx> {
657
+ const get = (): Database<C, Tx> => {
658
+ const db = registry.get(name)?.current;
659
+ if (!db) {
660
+ const known = [...registry.keys()].filter(
661
+ (k) => registry.get(k)?.current,
662
+ );
663
+ throw new Error(
664
+ `no sql database named "${name}". ` +
665
+ (known.length
666
+ ? `Registered: ${known.map((k) => `"${k}"`).join(", ")}.`
667
+ : "None is registered — add adapter(url) or createDatabase(...) " +
668
+ "to the plugins in sigil.config.ts."),
669
+ );
670
+ }
671
+ return db as Database<C, Tx>;
672
+ };
673
+
674
+ // Capabilities are read when the tag is used, not now: building a
675
+ // fragment must not need the database to be registered yet. So a missing
676
+ // capability is reported at run time here, where it would have been at
677
+ // build time on the database itself.
678
+ const tag = buildTag(
679
+ name,
680
+ () => {
681
+ if (!registry.get(name)?.current) {
682
+ // Let the fragment be built; running it looks the database
683
+ // up again and says what is missing.
684
+ return {
685
+ adapter: "(not registered yet)",
686
+ capabilities: { query: lateQuery, helper: lateHelper },
687
+ };
688
+ }
689
+ return {
690
+ adapter: `of database "${name}"`,
691
+ capabilities: get().capabilities as SqlCapabilities<unknown, unknown>,
692
+ };
693
+ },
694
+ {
695
+ run: () => get().db(),
696
+ runTx: () => get().tx(),
697
+ runPool: () => get().pool(),
698
+ },
699
+ );
700
+
701
+ /** Stand-ins used only if a fragment is built before registration. */
702
+ function lateQuery(
703
+ target: unknown,
704
+ text: string,
705
+ values: readonly unknown[],
706
+ strings: readonly string[],
707
+ ): Promise<unknown[]> {
708
+ const q = get().capabilities.query;
709
+ if (!q) {
710
+ throw new Error(
711
+ `sql database "${name}" has no sql tag: its adapter does not ` +
712
+ "declare capabilities.query, so it cannot bind parameters.",
713
+ );
714
+ }
715
+ return q(target as C | Tx, text, values, strings);
716
+ }
717
+ function lateHelper(
718
+ target: unknown,
719
+ method: string | undefined,
720
+ args: readonly unknown[],
721
+ ): unknown {
722
+ const h = get().capabilities.helper;
723
+ if (!h) {
724
+ throw new Error(
725
+ `sql database "${name}" has no sql helpers: its adapter does not ` +
726
+ "declare capabilities.helper.",
727
+ );
728
+ }
729
+ return h(target as C | Tx, method, args);
730
+ }
731
+
732
+ return {
733
+ name,
734
+ db: () => get().db(),
735
+ tx: () => get().tx(),
736
+ pool: () => get().pool(),
737
+ inTransaction: () => get().inTransaction(),
738
+ transaction: (fn) => get().transaction(fn),
739
+ get capabilities() {
740
+ return get().capabilities;
741
+ },
742
+ sql: tag,
743
+ open: () => get().open(),
744
+ close: () => get().close(),
745
+ localsHandle: () => get().localsHandle(),
746
+ get plugin() {
747
+ return get().plugin;
748
+ },
749
+ };
750
+ }