@sigil-dev/plugin-sql 0.9.29 → 0.9.30

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 CHANGED
@@ -9,7 +9,7 @@ proves one behaves, and an official adapter for `Bun.SQL`.
9
9
  import { adapter } from "@sigil-dev/plugin-sql/bun";
10
10
 
11
11
  export default {
12
- plugins: [adapter(process.env.DATABASE_URL!, { maxTotal: 20 })],
12
+ plugins: [adapter({ env: "DATABASE_URL", maxTotal: 20 })],
13
13
  };
14
14
  ```
15
15
 
package/package.json CHANGED
@@ -11,7 +11,7 @@
11
11
  "module": "src/index.ts",
12
12
  "type": "module",
13
13
  "private": false,
14
- "version": "0.9.29",
14
+ "version": "0.9.30",
15
15
  "keywords": [
16
16
  "grimoire",
17
17
  "sigil",
@@ -26,7 +26,7 @@
26
26
  ],
27
27
  "peerDependencies": {
28
28
  "typescript": "^5",
29
- "@sigil-dev/grimoire": "0.9.29"
29
+ "@sigil-dev/grimoire": "0.9.30"
30
30
  },
31
31
  "exports": {
32
32
  ".": "./src/index.ts",
package/src/bun.ts CHANGED
@@ -1,300 +1,414 @@
1
- /**
2
- * The official adapter for `Bun.SQL`.
3
- *
4
- * `Bun.SQL` speaks postgres, mysql and sqlite from one class and infers the
5
- * dialect from the DSN, including a `sqlite://` file. That is why this
6
- * adapter has no dialect parameter and no placeholder handling: those are
7
- * the driver's job, and the previous hand-written layer got three of them
8
- * wrong (`?` vs `$1`, ISO timestamps, `sqlite://` becoming `//`).
9
- *
10
- * One thing it deliberately does not paper over: SQLite through `Bun.SQL` is
11
- * a single connection, so an in-transaction read sees uncommitted rows.
12
- * `runAdapterConformance` takes `isolation: false` for it, and the reason is
13
- * in that file rather than here.
14
- */
15
-
16
-
17
- import {
18
- defineSqlAdapter,
19
- sql,
20
- type SqlAdapter,
21
- type SqlPluginOptions,
22
- } from "./contract.ts";
23
- import type { DatabasePlugin, SqlHandle } from "./database.ts";
24
-
25
- /** The client `Bun.SQL` produces. Named as a type only — the class is a
26
- * runtime value reached through `Bun`, so importing it as a type keeps this
27
- * module from assuming a Bun build exposes it at module scope.
28
- *
29
- * `InstanceType<typeof Bun.SQL>` rather than `ReturnType<typeof Bun.SQL>`:
30
- * Bun.SQL is a constructor, so its type parameter is the instance, and
31
- * `ReturnType` of a class type is the class itself — which is why tsc
32
- * complained that "typeof SQL" does not satisfy the client constraint. */
33
- type SQL = InstanceType<typeof Bun.SQL>;
34
-
35
- /** The client type, exported so a test hook can be typed without `any`. */
36
- export type BunSqlClient = SQL;
37
-
38
- /**
39
- * What `locals.db` is with this adapter: the `Bun.SQL` client plus the
40
- * `sql` tag. Put it on `App.Locals` in `src/app.d.ts`.
41
- */
42
- export type BunSqlHandle = SqlHandle<SQL>;
43
-
44
- export interface BunSqlOptions {
45
- /**
46
- * Total connections across the whole deployment, divided by the worker
47
- * count. So 20 across 4 workers is 5 each.
48
- *
49
- * Dividing matters: without it every worker opens the full number, and a
50
- * 4-worker deployment quietly asks the database for 80 connections and
51
- * gets refused. `ctx.workers` is why that is correct rather than a
52
- * guess — see `workerContext()`.
53
- *
54
- * May also be given in the connection object, beside the driver options.
55
- */
56
- maxTotal?: number;
57
- }
58
-
59
- /**
60
- * A connection: a DSN, or `Bun.SQL`'s options object. The object may carry
61
- * `maxTotal` beside the driver's own options, so one object is the whole
62
- * database:
63
- *
64
- * ```ts
65
- * { url: env.DB_URL, idleTimeout: 30, maxTotal: 12 }
66
- * ```
67
- */
68
- export type BunSqlConnection =
69
- | string
70
- | ({ url?: string; maxTotal?: number } & Record<string, unknown>);
71
-
72
- /**
73
- * Split a connection into driver options and the budget, refusing the one
74
- * spelling that silently does the wrong thing.
75
- */
76
- function connectionOf(
77
- dsn: BunSqlConnection,
78
- opts: BunSqlOptions,
79
- ): { driver: Record<string, unknown>; maxTotal: number | undefined } {
80
- if (typeof dsn === "string") return { driver: { url: dsn }, maxTotal: opts.maxTotal };
81
- const { maxTotal: inline, ...driver } = dsn;
82
- if ("max" in driver) {
83
- // `max` is Bun.SQL's per-client pool size. Passed here it goes
84
- // straight to the driver in every worker, so `max: 12` on four
85
- // workers is 48 connections — the budget looks set and is not.
86
- throw new Error(
87
- "bunSqlAdapter: `max` is a per-worker pool size, so every worker " +
88
- "would open that many. Use `maxTotal` for a budget across the " +
89
- "deployment; it is divided by the worker count for you.",
90
- );
91
- }
92
- if (inline !== undefined && opts.maxTotal !== undefined && inline !== opts.maxTotal) {
93
- throw new Error(
94
- `bunSqlAdapter: maxTotal is ${inline} in the connection and ` +
95
- `${opts.maxTotal} in the options. Give it once.`,
96
- );
97
- }
98
- return { driver, maxTotal: inline ?? opts.maxTotal };
99
- }
100
-
101
- /**
102
- * A `Bun.SQL` adapter.
103
- *
104
- * ```ts
105
- * sql(bunSqlAdapter(process.env.DATABASE_URL!))
106
- * sql(bunSqlAdapter({ url: "app.db" })) // sqlite, one connection
107
- * sql(bunSqlAdapter(url, { maxTotal: 20 })) // 5 per worker on 4 workers
108
- * ```
109
- */
110
- export function bunSqlAdapter(
111
- dsn: BunSqlConnection,
112
- opts: BunSqlOptions = {},
113
- ): SqlAdapter<SQL> {
114
- // Split now, so a wrong spelling fails where the config is written.
115
- const { driver, maxTotal } = connectionOf(dsn, opts);
116
- return defineSqlAdapter<SQL>({
117
- contract: 1,
118
- name: "bun-sql",
119
- create({ workers }) {
120
- const total = maxTotal;
121
- // Bun.SQL is a value, and this module is type-only about it
122
- // otherwise — naming the type keeps the public signature honest.
123
- const Ctor = Bun.SQL as unknown as new (
124
- opts: Record<string, unknown>,
125
- ) => SQL;
126
- // Only divide when there is a budget to divide. `max: undefined`
127
- // is Bun.SQL's own default and must be left alone.
128
- const max =
129
- total === undefined
130
- ? undefined
131
- : Math.max(1, Math.ceil(total / Math.max(1, workers)));
132
- return new Ctor({
133
- ...driver,
134
- ...(max === undefined ? {} : { max }),
135
- });
136
- },
137
- close(db) {
138
- db.close();
139
- },
140
- transaction: (db, fn) =>
141
- // Bun's `begin` hands its callback a transaction handle, which is
142
- // the same client type. The cast is here because `begin` is typed
143
- // against its own overloads rather than a generic callback, and
144
- // one cast in the adapter is better than `as any` at every call
145
- // site in a plugin.
146
- db.begin(((tx: SQL) => fn(tx)) as never) as never,
147
- async ping(db) {
148
- await db`select 1`;
149
- },
150
- capabilities: {
151
- /**
152
- * Through Bun.SQL's own tagged template, not `unsafe(text)`.
153
- *
154
- * `text` has `$1` placeholders, which MySQL reads as a column name
155
- * ("Unknown column '$1'"). The template parts let Bun.SQL choose
156
- * the placeholder for its own dialect — the job this package
157
- * handed to the driver precisely because it got it wrong itself.
158
- * It also means a helper built by `helper` below binds the way
159
- * Bun.SQL's own does.
160
- */
161
- async query(target, _sql, values, strings) {
162
- return (await (target as SQL)(
163
- templateOf(strings),
164
- ...(values as never[]),
165
- )) as unknown[];
166
- },
167
- /**
168
- * `db.sql(ids)` → `client(ids)`, `db.sql.array(xs, t)` →
169
- * `client.array(xs, t)`, on the client that runs the query.
170
- */
171
- helper(target, method, args) {
172
- const c = target as unknown as Record<string, (...a: unknown[]) => unknown> &
173
- ((...a: unknown[]) => unknown);
174
- if (method === undefined) return c(...args);
175
- const fn = c[method];
176
- if (typeof fn !== "function") {
177
- throw new Error(`Bun.SQL has no helper "${method}".`);
178
- }
179
- return fn.apply(c, args as unknown[]);
180
- },
181
- /** `SAVEPOINT`, so a nested transaction can roll back alone. */
182
- savepoint: (tx, fn) =>
183
- (tx as unknown as {
184
- savepoint<R>(fn: (sp: SQL) => Promise<R>): Promise<R>;
185
- }).savepoint(fn),
186
- },
187
- });
188
- }
189
-
190
- /**
191
- * The parts of a fragment as a `TemplateStringsArray`, built once per
192
- * fragment: Bun.SQL reads `raw`, and a stable array lets it reuse what it
193
- * derived from the last run.
194
- */
195
- const templates = new WeakMap<readonly string[], TemplateStringsArray>();
196
- function templateOf(strings: readonly string[]): TemplateStringsArray {
197
- let t = templates.get(strings);
198
- if (!t) {
199
- // Shaped like a real template object: `raw` must be non-enumerable
200
- // (Bun >= 1.4's `isTemplateObject` rejects an enumerable one), and
201
- // both arrays frozen. `Object.assign` would make `raw` enumerable.
202
- const arr = [...strings];
203
- Object.defineProperty(arr, "raw", {
204
- value: Object.freeze([...strings]),
205
- enumerable: false,
206
- writable: false,
207
- configurable: false,
208
- });
209
- t = Object.freeze(arr) as unknown as TemplateStringsArray;
210
- templates.set(strings, t);
211
- }
212
- return t;
213
- }
214
-
215
- export interface AdapterOptions extends BunSqlOptions, SqlPluginOptions<SQL> {
216
- /**
217
- * Register nothing when the connection is missing, instead of failing
218
- * the boot. For a database a feature can live without; the feature asks
219
- * `hasDatabase(key)`, or is handed the plugin (`jobs({ database: plugin })`).
220
- */
221
- optional?: boolean;
222
- }
223
-
224
- /**
225
- * A ready-to-register `Bun.SQL` plugin.
226
- *
227
- * `sql(bunSqlAdapter(dsn))` is two imports and a nested call for what is
228
- * one decision, and the nesting is what makes it look like there is more
229
- * to it than there is. This is that call, applied.
230
- *
231
- * ```ts
232
- * import { adapter } from "@sigil-dev/plugin-sql/bun";
233
- *
234
- * export default {
235
- * plugins: [adapter(Bun.env.DATABASE_URL!, { maxTotal: 20 })],
236
- * };
237
- * ```
238
- *
239
- * The connection may be one object that also carries the plugin's identity,
240
- * which is the form to prefer when there is more than one database:
241
- *
242
- * ```ts
243
- * adapter({ key: "userDb", url: env.VIEWER_DB_URL, maxTotal: 4, optional: true })
244
- * ```
245
- *
246
- * The result is a plugin with a `.database` handle, so another plugin can be
247
- * handed the database itself (`jobs({ database: userDb })`) instead of its name.
248
- *
249
- * `bunSqlAdapter` stays exported, and is what you want when you need the
250
- * adapter itself — naming a `key`, wrapping it in your own plugin, or
251
- * handing it to `runAdapterConformance`. This is the common case and it
252
- * should be the short one.
253
- *
254
- * Both are the same object underneath: `bunSql` calls `sql(bunSqlAdapter(..))`
255
- * rather than reimplementing the lifecycle, so there is one code path to be
256
- * wrong about.
257
- */
258
- export function adapter(
259
- dsn: BunSqlConnection | undefined,
260
- options: AdapterOptions = {},
261
- ): DatabasePlugin<SQL> {
262
- // Plugin identity may ride in the connection object. Pull it out so it
263
- // never reaches Bun.SQL, and so a second place to say it is not a second
264
- // answer: a key given twice must agree.
265
- if (dsn && typeof dsn === "object") {
266
- const { key: k, optional: o, perRequestTx: p, ...rest } = dsn as Record<string, unknown>;
267
- if (k !== undefined && options.key !== undefined && k !== options.key) {
268
- throw new Error(`adapter: key is "${String(k)}" in the connection and "${options.key}" in the options. Give it once.`);
269
- }
270
- options = {
271
- ...options,
272
- key: (k as string | undefined) ?? options.key,
273
- optional: (o as boolean | undefined) ?? options.optional,
274
- perRequestTx: (p as boolean | undefined) ?? options.perRequestTx,
275
- };
276
- dsn = rest as BunSqlConnection;
277
- }
278
- const { optional, perRequestTx, key, ...budget } = options;
279
- const missing =
280
- dsn === undefined ||
281
- dsn === "" ||
282
- (typeof dsn === "object" && "url" in dsn && !dsn.url);
283
- if (missing) {
284
- const name = key ?? "db";
285
- if (optional) {
286
- return { name: `sql:${name} (not configured)`, key: name, database: undefined };
287
- }
288
- // Bun.SQL with no url connects to localhost with the OS user, which
289
- // fails later with a credentials error that never mentions the
290
- // variable that was empty.
291
- throw new Error(
292
- `adapter: database "${name}" has no connection URL — the environment ` +
293
- "variable is probably unset. Pass { optional: true } if the app " +
294
- "should start without it.",
295
- );
296
- }
297
- return sql(bunSqlAdapter(dsn as BunSqlConnection, budget), { perRequestTx, key });
298
- }
299
-
300
- export default adapter;
1
+ /**
2
+ * The official adapter for `Bun.SQL`.
3
+ *
4
+ * `Bun.SQL` speaks postgres, mysql and sqlite from one class and infers the
5
+ * dialect from the DSN, including a `sqlite://` file. That is why this
6
+ * adapter has no dialect parameter and no placeholder handling: those are
7
+ * the driver's job, and the previous hand-written layer got three of them
8
+ * wrong (`?` vs `$1`, ISO timestamps, `sqlite://` becoming `//`).
9
+ *
10
+ * One thing it deliberately does not paper over: SQLite through `Bun.SQL` is
11
+ * a single connection, so an in-transaction read sees uncommitted rows.
12
+ * `runAdapterConformance` takes `isolation: false` for it, and the reason is
13
+ * in that file rather than here.
14
+ */
15
+
16
+ import {
17
+ defineSqlAdapter,
18
+ type SqlAdapter,
19
+ type SqlPluginOptions,
20
+ sql,
21
+ } from "./contract.ts";
22
+ import type { DatabasePlugin, SqlHandle } from "./database.ts";
23
+
24
+ /** The client `Bun.SQL` produces. Named as a type only — the class is a
25
+ * runtime value reached through `Bun`, so importing it as a type keeps this
26
+ * module from assuming a Bun build exposes it at module scope.
27
+ *
28
+ * `InstanceType<typeof Bun.SQL>` rather than `ReturnType<typeof Bun.SQL>`:
29
+ * Bun.SQL is a constructor, so its type parameter is the instance, and
30
+ * `ReturnType` of a class type is the class itself — which is why tsc
31
+ * complained that "typeof SQL" does not satisfy the client constraint. */
32
+ type SQL = InstanceType<typeof Bun.SQL>;
33
+
34
+ /** The client type, exported so a test hook can be typed without `any`. */
35
+ export type BunSqlClient = SQL;
36
+
37
+ /**
38
+ * What `locals.db` is with this adapter: the `Bun.SQL` client plus the
39
+ * `sql` tag. Put it on `App.Locals` in `src/app.d.ts`.
40
+ */
41
+ export type BunSqlHandle = SqlHandle<SQL>;
42
+
43
+ export interface BunSqlOptions {
44
+ /**
45
+ * Total connections across the whole deployment, divided by the worker
46
+ * count. So 20 across 4 workers is 5 each.
47
+ *
48
+ * Dividing matters: without it every worker opens the full number, and a
49
+ * 4-worker deployment quietly asks the database for 80 connections and
50
+ * gets refused. `ctx.workers` is why that is correct rather than a
51
+ * guess — see `workerContext()`.
52
+ *
53
+ * May also be given in the connection object, beside the driver options.
54
+ */
55
+ maxTotal?: number;
56
+ }
57
+
58
+ /**
59
+ * A connection: a DSN, or `Bun.SQL`'s options object. The object may carry
60
+ * `maxTotal` beside the driver's own options, so one object is the whole
61
+ * database:
62
+ *
63
+ * ```ts
64
+ * { url: env.DB_URL, idleTimeout: 30, maxTotal: 12 }
65
+ * ```
66
+ */
67
+ export type BunSqlConnection =
68
+ | string
69
+ | ({ url?: string; maxTotal?: number } & Record<string, unknown>)
70
+ | ({
71
+ /** The variable holding the URL, read when the server starts. */
72
+ env: string;
73
+ maxTotal?: number;
74
+ } & Record<string, unknown>);
75
+
76
+ /**
77
+ * Split a connection into driver options and the budget, refusing the one
78
+ * spelling that silently does the wrong thing.
79
+ */
80
+ function connectionOf(
81
+ dsn: BunSqlConnection,
82
+ opts: BunSqlOptions,
83
+ ): { driver: Record<string, unknown>; maxTotal: number | undefined } {
84
+ if (typeof dsn === "string")
85
+ return { driver: { url: dsn }, maxTotal: opts.maxTotal };
86
+ const { maxTotal: inline, ...driver } = dsn;
87
+ if ("max" in driver) {
88
+ // `max` is Bun.SQL's per-client pool size. Passed here it goes
89
+ // straight to the driver in every worker, so `max: 12` on four
90
+ // workers is 48 connections — the budget looks set and is not.
91
+ throw new Error(
92
+ "bunSqlAdapter: `max` is a per-worker pool size, so every worker " +
93
+ "would open that many. Use `maxTotal` for a budget across the " +
94
+ "deployment; it is divided by the worker count for you.",
95
+ );
96
+ }
97
+ if (
98
+ inline !== undefined &&
99
+ opts.maxTotal !== undefined &&
100
+ inline !== opts.maxTotal
101
+ ) {
102
+ throw new Error(
103
+ `bunSqlAdapter: maxTotal is ${inline} in the connection and ` +
104
+ `${opts.maxTotal} in the options. Give it once.`,
105
+ );
106
+ }
107
+ return { driver, maxTotal: inline ?? opts.maxTotal };
108
+ }
109
+
110
+ /**
111
+ * A `Bun.SQL` adapter.
112
+ *
113
+ * ```ts
114
+ * sql(bunSqlAdapter(process.env.DATABASE_URL!))
115
+ * sql(bunSqlAdapter({ url: "app.db" })) // sqlite, one connection
116
+ * sql(bunSqlAdapter(url, { maxTotal: 20 })) // 5 per worker on 4 workers
117
+ * ```
118
+ */
119
+ export function bunSqlAdapter(
120
+ dsn: BunSqlConnection | (() => BunSqlConnection),
121
+ opts: BunSqlOptions = {},
122
+ ): SqlAdapter<SQL> {
123
+ // Split now, so a wrong spelling fails where the config is written. A
124
+ // function is a connection read when the server starts (`adapter()`
125
+ // reading DATABASE_URL), so it is split then.
126
+ const eager = typeof dsn === "function" ? undefined : connectionOf(dsn, opts);
127
+ return defineSqlAdapter<SQL>({
128
+ contract: 1,
129
+ name: "bun-sql",
130
+ create({ workers }) {
131
+ const { driver, maxTotal } =
132
+ eager ?? connectionOf((dsn as () => BunSqlConnection)(), opts);
133
+ const total = maxTotal;
134
+ // Bun.SQL is a value, and this module is type-only about it
135
+ // otherwise — naming the type keeps the public signature honest.
136
+ const Ctor = Bun.SQL as unknown as new (
137
+ opts: Record<string, unknown>,
138
+ ) => SQL;
139
+ // Only divide when there is a budget to divide. `max: undefined`
140
+ // is Bun.SQL's own default and must be left alone.
141
+ const max =
142
+ total === undefined
143
+ ? undefined
144
+ : Math.max(1, Math.ceil(total / Math.max(1, workers)));
145
+ return new Ctor({
146
+ ...driver,
147
+ ...(max === undefined ? {} : { max }),
148
+ });
149
+ },
150
+ close(db) {
151
+ db.close();
152
+ },
153
+ transaction: (db, fn) =>
154
+ // Bun's `begin` hands its callback a transaction handle, which is
155
+ // the same client type. The cast is here because `begin` is typed
156
+ // against its own overloads rather than a generic callback, and
157
+ // one cast in the adapter is better than `as any` at every call
158
+ // site in a plugin.
159
+ db.begin(((tx: SQL) => fn(tx)) as never) as never,
160
+ async ping(db) {
161
+ await db`select 1`;
162
+ },
163
+ capabilities: {
164
+ /**
165
+ * Through Bun.SQL's own tagged template, not `unsafe(text)`.
166
+ *
167
+ * `text` has `$1` placeholders, which MySQL reads as a column name
168
+ * ("Unknown column '$1'"). The template parts let Bun.SQL choose
169
+ * the placeholder for its own dialect — the job this package
170
+ * handed to the driver precisely because it got it wrong itself.
171
+ * It also means a helper built by `helper` below binds the way
172
+ * Bun.SQL's own does.
173
+ */
174
+ async query(target, _sql, values, strings) {
175
+ return (await (target as SQL)(
176
+ templateOf(strings),
177
+ ...(values as never[]),
178
+ )) as unknown[];
179
+ },
180
+ /**
181
+ * `db.sql(ids)` → `client(ids)`, `db.sql.array(xs, t)` →
182
+ * `client.array(xs, t)`, on the client that runs the query.
183
+ */
184
+ helper(target, method, args) {
185
+ const c = target as unknown as Record<
186
+ string,
187
+ (...a: unknown[]) => unknown
188
+ > &
189
+ ((...a: unknown[]) => unknown);
190
+ if (method === undefined) return c(...args);
191
+ const fn = c[method];
192
+ if (typeof fn !== "function") {
193
+ throw new Error(`Bun.SQL has no helper "${method}".`);
194
+ }
195
+ return fn.apply(c, args as unknown[]);
196
+ },
197
+ /** `SAVEPOINT`, so a nested transaction can roll back alone. */
198
+ savepoint: (tx, fn) =>
199
+ (
200
+ tx as unknown as {
201
+ savepoint<R>(fn: (sp: SQL) => Promise<R>): Promise<R>;
202
+ }
203
+ ).savepoint(fn),
204
+ },
205
+ });
206
+ }
207
+
208
+ /**
209
+ * The parts of a fragment as a `TemplateStringsArray`, built once per
210
+ * fragment: Bun.SQL reads `raw`, and a stable array lets it reuse what it
211
+ * derived from the last run.
212
+ */
213
+ const templates = new WeakMap<readonly string[], TemplateStringsArray>();
214
+ function templateOf(strings: readonly string[]): TemplateStringsArray {
215
+ let t = templates.get(strings);
216
+ if (!t) {
217
+ // Shaped like a real template object: `raw` must be non-enumerable
218
+ // (Bun >= 1.4's `isTemplateObject` rejects an enumerable one), and
219
+ // both arrays frozen. `Object.assign` would make `raw` enumerable.
220
+ const arr = [...strings];
221
+ Object.defineProperty(arr, "raw", {
222
+ value: Object.freeze([...strings]),
223
+ enumerable: false,
224
+ writable: false,
225
+ configurable: false,
226
+ });
227
+ t = Object.freeze(arr) as unknown as TemplateStringsArray;
228
+ templates.set(strings, t);
229
+ }
230
+ return t;
231
+ }
232
+
233
+ export interface AdapterOptions extends BunSqlOptions, SqlPluginOptions<SQL> {
234
+ /**
235
+ * Register nothing when the connection is missing, instead of failing
236
+ * the boot. For a database a feature can live without; the feature asks
237
+ * `hasDatabase(key)`, or is handed the plugin (`jobs({ database: plugin })`).
238
+ */
239
+ optional?: boolean;
240
+ }
241
+
242
+ /**
243
+ * A ready-to-register `Bun.SQL` plugin.
244
+ *
245
+ * `sql(bunSqlAdapter(dsn))` is two imports and a nested call for what is
246
+ * one decision, and the nesting is what makes it look like there is more
247
+ * to it than there is. This is that call, applied.
248
+ *
249
+ * ```ts
250
+ * import { adapter } from "@sigil-dev/plugin-sql/bun";
251
+ *
252
+ * export default {
253
+ * plugins: [adapter()], // DATABASE_URL, read when the server starts
254
+ * };
255
+ * ```
256
+ *
257
+ * Name the variable to use another one, or to add options:
258
+ * `adapter({ env: "VIEWER_DB_URL", maxTotal: 20 })`. It is read when the
259
+ * server starts, not while the config loads, so `sigil build` and the CLI
260
+ * never need the secret.
261
+ *
262
+ * The connection may be one object that also carries the plugin's identity,
263
+ * which is the form to prefer when there is more than one database:
264
+ *
265
+ * ```ts
266
+ * adapter({ key: "userDb", env: "VIEWER_DB_URL", maxTotal: 4, optional: true })
267
+ * ```
268
+ *
269
+ * The result is a plugin with a `.database` handle, so another plugin can be
270
+ * handed the database itself (`jobs({ database: userDb })`) instead of its name.
271
+ *
272
+ * `bunSqlAdapter` stays exported, and is what you want when you need the
273
+ * adapter itself — naming a `key`, wrapping it in your own plugin, or
274
+ * handing it to `runAdapterConformance`. This is the common case and it
275
+ * should be the short one.
276
+ *
277
+ * Both are the same object underneath: `bunSql` calls `sql(bunSqlAdapter(..))`
278
+ * rather than reimplementing the lifecycle, so there is one code path to be
279
+ * wrong about.
280
+ */
281
+ /** The key a database lands on in `locals`: the options' `key`, the connection's, or "db". */
282
+ type KeyOf<D, O> = O extends { key: infer K extends string }
283
+ ? K
284
+ : D extends { key: infer K extends string }
285
+ ? K
286
+ : "db";
287
+ type IsOptional<D, O> = O extends { optional: true }
288
+ ? true
289
+ : D extends { optional: true }
290
+ ? true
291
+ : false;
292
+
293
+ /** What `adapter()` returns: the plugin, typed with what it puts on `locals`. */
294
+ export type BunDatabasePlugin<
295
+ K extends string = "db",
296
+ Optional = false,
297
+ > = DatabasePlugin<SQL> & {
298
+ readonly $locals?: Optional extends true
299
+ ? { [P in K]?: BunSqlHandle }
300
+ : { [P in K]: BunSqlHandle };
301
+ };
302
+
303
+ export function adapter<
304
+ const D extends BunSqlConnection | undefined = undefined,
305
+ const O extends AdapterOptions = {},
306
+ >(dsn?: D, options?: O): BunDatabasePlugin<KeyOf<D, O>, IsOptional<D, O>>;
307
+ export function adapter(
308
+ dsn?: BunSqlConnection | undefined,
309
+ options: AdapterOptions = {},
310
+ ): DatabasePlugin<SQL> {
311
+ // `adapter()` with nothing is `adapter({ env: "DATABASE_URL" })`.
312
+ if (arguments.length === 0) dsn = { env: "DATABASE_URL" };
313
+ // Plugin identity may ride in the connection object. Pull it out so it
314
+ // never reaches Bun.SQL, and so a second place to say it is not a second
315
+ // answer: a key given twice must agree.
316
+ let envName: string | undefined;
317
+ if (dsn && typeof dsn === "object") {
318
+ const {
319
+ key: k,
320
+ optional: o,
321
+ perRequestTx: p,
322
+ env: e,
323
+ ...rest
324
+ } = dsn as Record<string, unknown>;
325
+ if (k !== undefined && options.key !== undefined && k !== options.key) {
326
+ throw new Error(
327
+ `adapter: key is "${String(k)}" in the connection and "${options.key}" in the options. Give it once.`,
328
+ );
329
+ }
330
+ if (e !== undefined && "url" in rest) {
331
+ throw new Error("adapter: give either `url` or `env`, not both.");
332
+ }
333
+ options = {
334
+ ...options,
335
+ key: (k as string | undefined) ?? options.key,
336
+ optional: (o as boolean | undefined) ?? options.optional,
337
+ perRequestTx: (p as boolean | undefined) ?? options.perRequestTx,
338
+ };
339
+ envName = e as string | undefined;
340
+ dsn = rest as BunSqlConnection;
341
+ }
342
+ const { optional, perRequestTx, key, ...budget } = options;
343
+ const name = key ?? "db";
344
+
345
+ // `env`: the URL is read when the server starts, not here. This config
346
+ // is also imported by `sigil build` and the CLI, where the server's
347
+ // secrets are usually unset, and reading them here broke the build.
348
+ if (envName !== undefined) {
349
+ const variable = envName;
350
+ const driver = dsn as Record<string, unknown>;
351
+ // The URL waits; a wrong spelling of the options still fails here.
352
+ connectionOf({ ...driver, url: "" }, budget);
353
+ // Optional means "start without it", which has to be decided now:
354
+ // hasDatabase() answers from the registry as soon as this returns.
355
+ if (optional && !process.env[variable]) {
356
+ return {
357
+ name: `sql:${name} (not configured)`,
358
+ key: name,
359
+ database: undefined,
360
+ };
361
+ }
362
+ const plugin = sql(
363
+ bunSqlAdapter(() => {
364
+ const url = process.env[variable];
365
+ if (!url) throw missingUrl(name, variable);
366
+ return { ...driver, url };
367
+ }, budget),
368
+ { perRequestTx, key },
369
+ );
370
+ return optional
371
+ ? plugin
372
+ : Object.assign(plugin, { requiredEnv: [variable] });
373
+ }
374
+
375
+ const missing =
376
+ dsn === undefined ||
377
+ dsn === "" ||
378
+ (typeof dsn === "object" && "url" in dsn && !dsn.url);
379
+ if (missing) {
380
+ if (optional) {
381
+ return {
382
+ name: `sql:${name} (not configured)`,
383
+ key: name,
384
+ database: undefined,
385
+ };
386
+ }
387
+ // Bun.SQL with no url connects to localhost with the OS user, which
388
+ // fails later with a credentials error that never mentions the
389
+ // variable that was empty. So it fails, but when the server starts:
390
+ // failing here also failed `sigil build` and every CLI command.
391
+ return sql(
392
+ bunSqlAdapter(() => {
393
+ throw missingUrl(name);
394
+ }),
395
+ { perRequestTx, key },
396
+ );
397
+ }
398
+ return sql(bunSqlAdapter(dsn as BunSqlConnection, budget), {
399
+ perRequestTx,
400
+ key,
401
+ });
402
+ }
403
+
404
+ function missingUrl(name: string, variable?: string): Error {
405
+ return new Error(
406
+ `adapter: database "${name}" has no connection URL — ` +
407
+ (variable
408
+ ? `${variable} is unset`
409
+ : "the environment variable is probably unset") +
410
+ ". Pass { optional: true } if the app should start without it.",
411
+ );
412
+ }
413
+
414
+ export default adapter;
package/src/contract.ts CHANGED
@@ -18,12 +18,16 @@
18
18
  * ```
19
19
  */
20
20
 
21
- import { type GrimoirePlugin } from "@sigil-dev/grimoire";
22
- import { createDatabase, type Database, type DatabasePlugin } from "./database.ts";
23
21
  import {
24
- workerContext,
22
+ type GrimoirePlugin,
25
23
  type WorkerContext,
24
+ workerContext,
26
25
  } from "@sigil-dev/grimoire";
26
+ import {
27
+ createDatabase,
28
+ type Database,
29
+ type DatabasePlugin,
30
+ } from "./database.ts";
27
31
 
28
32
  export type { WorkerContext };
29
33
  export { workerContext };
@@ -107,10 +111,17 @@ export interface SqlCapabilities<C, Tx> {
107
111
  setLocal?(tx: Tx, key: string, value: string): Promise<void>;
108
112
 
109
113
  /** Subscribe to `LISTEN`/`NOTIFY`. Returns an unsubscribe function. */
110
- listen?(client: C, channel: string, cb: (payload: string) => void): Promise<() => void>;
114
+ listen?(
115
+ client: C,
116
+ channel: string,
117
+ cb: (payload: string) => void,
118
+ ): Promise<() => void>;
111
119
 
112
120
  /** Called after every query with its text and duration. */
113
- instrument?(client: C, onQuery: (q: { sql: string; ms: number }) => void): void;
121
+ instrument?(
122
+ client: C,
123
+ onQuery: (q: { sql: string; ms: number }) => void,
124
+ ): void;
114
125
 
115
126
  /**
116
127
  * Run a parameterised query and return rows.
@@ -155,7 +166,11 @@ export interface SqlCapabilities<C, Tx> {
155
166
  * Without this, `db.sql(...)` and `db.sql.array(...)` throw when called,
156
167
  * rather than binding an object the driver does not understand.
157
168
  */
158
- helper?(target: C | Tx, method: string | undefined, args: readonly unknown[]): unknown;
169
+ helper?(
170
+ target: C | Tx,
171
+ method: string | undefined,
172
+ args: readonly unknown[],
173
+ ): unknown;
159
174
  }
160
175
 
161
176
  /**
@@ -245,5 +260,8 @@ export function sql<C, Tx = C>(
245
260
  perRequestTx: opts.perRequestTx,
246
261
  key,
247
262
  });
248
- return Object.assign(db.plugin, { key, database: db as Database<C, Tx> | undefined });
263
+ return Object.assign(db.plugin, {
264
+ key,
265
+ database: db as Database<C, Tx> | undefined,
266
+ });
249
267
  }
package/src/database.ts CHANGED
@@ -1,18 +1,18 @@
1
1
  import { AsyncLocalStorage } from "node:async_hooks";
2
+ import { type GrimoirePlugin, workerContext } from "@sigil-dev/grimoire";
3
+ import {
4
+ SQL_CONTRACT_VERSION,
5
+ type SqlAdapter,
6
+ type SqlCapabilities,
7
+ } from "./contract.ts";
2
8
  import {
3
9
  createFragment,
4
10
  createHelper,
5
- isHelper,
6
11
  type Fragment,
7
12
  type FragmentRunner,
13
+ isHelper,
8
14
  type SqlHelper,
9
15
  } 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
16
 
17
17
  /**
18
18
  * The `db.sql` tag. `T` is the row type; a run resolves to `T[]`.
@@ -29,10 +29,7 @@ import {
29
29
  */
30
30
  export interface SqlTag {
31
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>;
32
+ <T = any>(strings: TemplateStringsArray, ...values: unknown[]): Fragment<T>;
36
33
  (value: unknown, ...columns: string[]): SqlHelper;
37
34
  /** A postgres array parameter, e.g. for `= any(...)`. */
38
35
  array(values: readonly unknown[], type?: string): SqlHelper;
@@ -48,7 +45,10 @@ const isTemplate = (v: unknown): v is TemplateStringsArray =>
48
45
  */
49
46
  function buildTag(
50
47
  name: string,
51
- caps: () => { adapter: string; capabilities: SqlCapabilities<unknown, unknown> },
48
+ caps: () => {
49
+ adapter: string;
50
+ capabilities: SqlCapabilities<unknown, unknown>;
51
+ },
52
52
  pick: Pick<FragmentRunner, "run" | "runTx" | "runPool">,
53
53
  ): SqlTag {
54
54
  const runner: FragmentRunner = {
@@ -85,7 +85,10 @@ function buildTag(
85
85
  if (!capabilities.query || !capabilities.helper) {
86
86
  refuse("sql helpers", "helper");
87
87
  }
88
- return createHelper("array", type === undefined ? [values] : [values, type]);
88
+ return createHelper(
89
+ "array",
90
+ type === undefined ? [values] : [values, type],
91
+ );
89
92
  };
90
93
  return tag;
91
94
  }
@@ -265,7 +268,7 @@ export interface CreateDatabaseOptions {
265
268
  *
266
269
  * Held here rather than in the Database object so that every object with
267
270
  * 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
271
+ * the dev server re-evaluating `src/db/index.ts` after an edit, and a
269
272
  * bundle that inlines its own copy of that module. Without this, either one
270
273
  * holds a Database whose client was never opened, and fails with "used
271
274
  * before its client was opened" while the one the config registered works.
@@ -555,9 +558,9 @@ export function createDatabase<C, Tx = C>(
555
558
  if (typeof fn !== "function") {
556
559
  // Not the callback form (`begin()` with no callback, say):
557
560
  // leave it to the driver.
558
- return (active() as Record<PropertyKey, (...a: unknown[]) => unknown>)[
559
- prop as string
560
- ]!(...args);
561
+ return (
562
+ active() as Record<PropertyKey, (...a: unknown[]) => unknown>
563
+ )[prop as string]!(...args);
561
564
  }
562
565
  const body = fn as (tx: Tx) => Promise<unknown>;
563
566
  if (args.length === 1 || current() !== undefined) {
package/src/fragment.ts CHANGED
@@ -257,8 +257,7 @@ export function createFragment<T = any>(
257
257
  // `x.runTx().catch()` does not.
258
258
  const exec = (pick: () => unknown): Promise<T[]> =>
259
259
  Promise.resolve().then(
260
- () =>
261
- resolve.query(pick(), text, s.values, s.strings) as Promise<T[]>,
260
+ () => resolve.query(pick(), text, s.values, s.strings) as Promise<T[]>,
262
261
  );
263
262
 
264
263
  const frag: Fragment<T> = {
package/src/index.ts CHANGED
@@ -34,34 +34,34 @@
34
34
  */
35
35
 
36
36
  export {
37
+ type ClientOf,
37
38
  defineSqlAdapter,
38
- sql,
39
39
  SQL_CONTRACT_VERSION,
40
- workerContext,
41
- type ClientOf,
42
40
  type SqlAdapter,
43
41
  type SqlCapabilities,
44
42
  type SqlPluginOptions,
43
+ sql,
45
44
  type TxOf,
46
45
  type WorkerContext,
46
+ workerContext,
47
47
  } from "./contract.ts";
48
48
 
49
49
  export {
50
- createDatabase,
51
- database,
52
- hasDatabase,
53
50
  type CreateDatabaseOptions,
51
+ createDatabase,
54
52
  type Database,
55
53
  type DatabasePlugin,
54
+ database,
55
+ hasDatabase,
56
56
  type SqlHandle,
57
57
  type SqlTag,
58
58
  } from "./database.ts";
59
59
  export {
60
+ type Fragment,
60
61
  fragmentParts,
61
62
  isFragment,
62
63
  isHelper,
63
64
  SQL_FRAGMENT,
64
65
  SQL_HELPER,
65
- type Fragment,
66
66
  type SqlHelper,
67
67
  } from "./fragment.ts";
package/src/testing.ts CHANGED
@@ -17,7 +17,14 @@
17
17
  * dialect. It is `bun:test`-only, which suits a Bun-first framework.
18
18
  */
19
19
 
20
- import { afterAll, beforeAll, beforeEach, describe, expect, test } from "bun:test";
20
+ import {
21
+ afterAll,
22
+ beforeAll,
23
+ beforeEach,
24
+ describe,
25
+ expect,
26
+ test,
27
+ } from "bun:test";
21
28
  import type { SqlAdapter, WorkerContext } from "./contract.ts";
22
29
 
23
30
  /**