@sigil-dev/plugin-sql 0.9.27 → 0.9.29

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.
Files changed (2) hide show
  1. package/package.json +2 -2
  2. package/src/bun.ts +300 -292
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.27",
14
+ "version": "0.9.29",
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.27"
29
+ "@sigil-dev/grimoire": "0.9.29"
30
30
  },
31
31
  "exports": {
32
32
  ".": "./src/index.ts",
package/src/bun.ts CHANGED
@@ -1,292 +1,300 @@
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
- t = Object.freeze(
200
- Object.assign([...strings], { raw: Object.freeze([...strings]) }),
201
- ) as unknown as TemplateStringsArray;
202
- templates.set(strings, t);
203
- }
204
- return t;
205
- }
206
-
207
- export interface AdapterOptions extends BunSqlOptions, SqlPluginOptions<SQL> {
208
- /**
209
- * Register nothing when the connection is missing, instead of failing
210
- * the boot. For a database a feature can live without; the feature asks
211
- * `hasDatabase(key)`, or is handed the plugin (`jobs({ database: plugin })`).
212
- */
213
- optional?: boolean;
214
- }
215
-
216
- /**
217
- * A ready-to-register `Bun.SQL` plugin.
218
- *
219
- * `sql(bunSqlAdapter(dsn))` is two imports and a nested call for what is
220
- * one decision, and the nesting is what makes it look like there is more
221
- * to it than there is. This is that call, applied.
222
- *
223
- * ```ts
224
- * import { adapter } from "@sigil-dev/plugin-sql/bun";
225
- *
226
- * export default {
227
- * plugins: [adapter(Bun.env.DATABASE_URL!, { maxTotal: 20 })],
228
- * };
229
- * ```
230
- *
231
- * The connection may be one object that also carries the plugin's identity,
232
- * which is the form to prefer when there is more than one database:
233
- *
234
- * ```ts
235
- * adapter({ key: "userDb", url: env.VIEWER_DB_URL, maxTotal: 4, optional: true })
236
- * ```
237
- *
238
- * The result is a plugin with a `.database` handle, so another plugin can be
239
- * handed the database itself (`jobs({ database: userDb })`) instead of its name.
240
- *
241
- * `bunSqlAdapter` stays exported, and is what you want when you need the
242
- * adapter itself — naming a `key`, wrapping it in your own plugin, or
243
- * handing it to `runAdapterConformance`. This is the common case and it
244
- * should be the short one.
245
- *
246
- * Both are the same object underneath: `bunSql` calls `sql(bunSqlAdapter(..))`
247
- * rather than reimplementing the lifecycle, so there is one code path to be
248
- * wrong about.
249
- */
250
- export function adapter(
251
- dsn: BunSqlConnection | undefined,
252
- options: AdapterOptions = {},
253
- ): DatabasePlugin<SQL> {
254
- // Plugin identity may ride in the connection object. Pull it out so it
255
- // never reaches Bun.SQL, and so a second place to say it is not a second
256
- // answer: a key given twice must agree.
257
- if (dsn && typeof dsn === "object") {
258
- const { key: k, optional: o, perRequestTx: p, ...rest } = dsn as Record<string, unknown>;
259
- if (k !== undefined && options.key !== undefined && k !== options.key) {
260
- throw new Error(`adapter: key is "${String(k)}" in the connection and "${options.key}" in the options. Give it once.`);
261
- }
262
- options = {
263
- ...options,
264
- key: (k as string | undefined) ?? options.key,
265
- optional: (o as boolean | undefined) ?? options.optional,
266
- perRequestTx: (p as boolean | undefined) ?? options.perRequestTx,
267
- };
268
- dsn = rest as BunSqlConnection;
269
- }
270
- const { optional, perRequestTx, key, ...budget } = options;
271
- const missing =
272
- dsn === undefined ||
273
- dsn === "" ||
274
- (typeof dsn === "object" && "url" in dsn && !dsn.url);
275
- if (missing) {
276
- const name = key ?? "db";
277
- if (optional) {
278
- return { name: `sql:${name} (not configured)`, key: name, database: undefined };
279
- }
280
- // Bun.SQL with no url connects to localhost with the OS user, which
281
- // fails later with a credentials error that never mentions the
282
- // variable that was empty.
283
- throw new Error(
284
- `adapter: database "${name}" has no connection URL — the environment ` +
285
- "variable is probably unset. Pass { optional: true } if the app " +
286
- "should start without it.",
287
- );
288
- }
289
- return sql(bunSqlAdapter(dsn as BunSqlConnection, budget), { perRequestTx, key });
290
- }
291
-
292
- 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
+
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;