@sigil-dev/plugin-sql 0.9.29 → 0.9.31
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 +1 -1
- package/package.json +2 -2
- package/src/bun.ts +414 -300
- package/src/contract.ts +25 -7
- package/src/database.ts +20 -17
- package/src/fragment.ts +1 -2
- package/src/index.ts +7 -7
- package/src/testing.ts +8 -1
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(
|
|
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.
|
|
14
|
+
"version": "0.9.31",
|
|
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
|
+
"@sigil-dev/grimoire": "0.9.31"
|
|
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
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
} from "./
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
*
|
|
27
|
-
*
|
|
28
|
-
*
|
|
29
|
-
*
|
|
30
|
-
*
|
|
31
|
-
*
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
*
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
*
|
|
47
|
-
*
|
|
48
|
-
*
|
|
49
|
-
*
|
|
50
|
-
*
|
|
51
|
-
*
|
|
52
|
-
*
|
|
53
|
-
*
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
*
|
|
61
|
-
*
|
|
62
|
-
*
|
|
63
|
-
*
|
|
64
|
-
*
|
|
65
|
-
*
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
| string
|
|
70
|
-
| ({
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
},
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
*
|
|
169
|
-
*
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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?(
|
|
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?(
|
|
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?(
|
|
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, {
|
|
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: () => {
|
|
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(
|
|
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/
|
|
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 (
|
|
559
|
-
|
|
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 {
|
|
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
|
/**
|