@sigil-dev/plugin-sql 0.9.13
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +314 -0
- package/package.json +30 -0
- package/src/bun.ts +265 -0
- package/src/contract.ts +249 -0
- package/src/database.ts +750 -0
- package/src/fragment.ts +275 -0
- package/src/index.ts +65 -0
- package/src/testing.ts +148 -0
package/README.md
ADDED
|
@@ -0,0 +1,314 @@
|
|
|
1
|
+
# @sigil-dev/plugin-sql
|
|
2
|
+
|
|
3
|
+
A database for Grimoire: opened once per worker, shared by every request,
|
|
4
|
+
closed on shutdown — plus a contract for adapters, a conformance kit that
|
|
5
|
+
proves one behaves, and an official adapter for `Bun.SQL`.
|
|
6
|
+
|
|
7
|
+
```ts
|
|
8
|
+
// sigil.config.ts
|
|
9
|
+
import { adapter } from "@sigil-dev/plugin-sql/bun";
|
|
10
|
+
|
|
11
|
+
export default {
|
|
12
|
+
plugins: [adapter(process.env.DATABASE_URL!, { maxTotal: 20 })],
|
|
13
|
+
};
|
|
14
|
+
```
|
|
15
|
+
|
|
16
|
+
```ts
|
|
17
|
+
// a route
|
|
18
|
+
const users = await locals.db`select id, name from users where id = ${id}`;
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
```ts
|
|
22
|
+
// anything else on the server: hooks.server.ts, a websocket, a timer, lib/
|
|
23
|
+
import { database } from "@sigil-dev/plugin-sql";
|
|
24
|
+
|
|
25
|
+
export const byId = (id: number) =>
|
|
26
|
+
database().sql<User>`select * from users where id = ${id}`;
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
`Bun.SQL` speaks postgres, mysql and sqlite from one class and infers the
|
|
30
|
+
dialect from the DSN. That is why this package has no dialect parameter, no
|
|
31
|
+
placeholder handling and no timestamp rewriting: those are the driver's job,
|
|
32
|
+
and it already does them.
|
|
33
|
+
|
|
34
|
+
The connection may be one object, budget included, and a database the app
|
|
35
|
+
can run without is `optional`:
|
|
36
|
+
|
|
37
|
+
```ts
|
|
38
|
+
adapter({ url: env.DB_URL, idleTimeout: 30, maxTotal: 12 })
|
|
39
|
+
adapter(env.USER_DB_URL, { key: "userDb", optional: true }) // hasDatabase("userDb")
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
`max` in the connection is refused (it is per worker; use `maxTotal`), and a
|
|
43
|
+
missing URL fails the boot naming the database instead of connecting to
|
|
44
|
+
localhost.
|
|
45
|
+
|
|
46
|
+
Rows are `any` unless you name them — `db.sql<User>` — as with `Bun.SQL`, so
|
|
47
|
+
existing `as Row[]` casts keep compiling. A fragment is a full `Promise`.
|
|
48
|
+
|
|
49
|
+
## Typing `locals.db`
|
|
50
|
+
|
|
51
|
+
```ts
|
|
52
|
+
// src/app.d.ts
|
|
53
|
+
import type { BunSqlHandle } from "@sigil-dev/plugin-sql/bun";
|
|
54
|
+
declare global {
|
|
55
|
+
namespace App {
|
|
56
|
+
interface Locals { db: BunSqlHandle }
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
export {};
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
## Per-request transactions
|
|
63
|
+
|
|
64
|
+
```ts
|
|
65
|
+
adapter(url, { maxTotal: 20, perRequestTx: true })
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
Every query made through `locals.db` during a request — the tagged
|
|
69
|
+
template, `locals.db.sql`, `unsafe()`, a Drizzle builder — and through
|
|
70
|
+
`database()` from code the request calls, runs in one transaction. A 5xx
|
|
71
|
+
response rolls it back; anything else commits. `db.transaction(fn)` inside
|
|
72
|
+
it is a savepoint (or joins, for an adapter without one), never a second
|
|
73
|
+
connection. A write that must survive a rollback uses `database().pool()`.
|
|
74
|
+
|
|
75
|
+
## Outside a request
|
|
76
|
+
|
|
77
|
+
`database(name = "db")` returns the database registered under that name,
|
|
78
|
+
looked up when a query runs, so it is safe at module scope. There, the
|
|
79
|
+
accessors are the pool and `transaction()` opens a real transaction. The
|
|
80
|
+
name is the `locals` key for `adapter()`/`sql()`, and the first argument of
|
|
81
|
+
`createDatabase(name, adapter)`, which returns the same thing as a value.
|
|
82
|
+
|
|
83
|
+
A script that runs without the server opens and closes it itself:
|
|
84
|
+
|
|
85
|
+
```ts
|
|
86
|
+
const db = createDatabase("db", bunSqlAdapter(url));
|
|
87
|
+
await db.open();
|
|
88
|
+
await db.sql`insert into users (name) values (${"ada"})`;
|
|
89
|
+
await db.close();
|
|
90
|
+
```
|
|
91
|
+
|
|
92
|
+
## `db.sql`
|
|
93
|
+
|
|
94
|
+
A query that has been described but not run: building one needs no
|
|
95
|
+
connection, awaiting one runs it — in the request's transaction if there
|
|
96
|
+
is one. Fragments compose and every value stays a bound parameter. The
|
|
97
|
+
driver picks the placeholders, so the same fragment runs on every dialect.
|
|
98
|
+
`.runTx()` and `.runPool()` pick the side explicitly.
|
|
99
|
+
|
|
100
|
+
Called as a function, the tag is the driver's helper, built lazily too:
|
|
101
|
+
`${db.sql(ids)}` for an `IN` list, `${db.sql.array(xs, "text")}` for
|
|
102
|
+
`= any(...)`, `${db.sql(row, "a", "b")}` for an insert, `${db.sql(name)}`
|
|
103
|
+
for an escaped identifier.
|
|
104
|
+
|
|
105
|
+
`hasDatabase(name)` says whether an optional database was registered.
|
|
106
|
+
|
|
107
|
+
## The contract
|
|
108
|
+
|
|
109
|
+
```ts
|
|
110
|
+
interface SqlAdapter<C, Tx = C> {
|
|
111
|
+
contract: 1; // bump on a breaking change
|
|
112
|
+
name: string;
|
|
113
|
+
create(ctx: WorkerContext): C | Promise<C>;
|
|
114
|
+
close(client: C): void | Promise<void>;
|
|
115
|
+
transaction<R>(client: C, fn: (tx: Tx) => Promise<R>): Promise<R>;
|
|
116
|
+
ping(client: C): Promise<void>;
|
|
117
|
+
capabilities?: {
|
|
118
|
+
query?(target, sql, values, strings): Promise<unknown[]>; // enables db.sql
|
|
119
|
+
savepoint?(tx, fn): Promise<R>; // nested transactions
|
|
120
|
+
setLocal?, listen?, instrument?
|
|
121
|
+
};
|
|
122
|
+
}
|
|
123
|
+
```
|
|
124
|
+
|
|
125
|
+
`contract` is checked when the plugin is constructed, so an adapter written
|
|
126
|
+
against a different version fails where you configured it rather than inside
|
|
127
|
+
a transaction where the stack trace points somewhere else.
|
|
128
|
+
|
|
129
|
+
`ping()` runs at startup. **A database unreachable at boot fails the
|
|
130
|
+
server start**, not the first request — a health check returning 200 while
|
|
131
|
+
every query fails is worse than a deploy that stops.
|
|
132
|
+
|
|
133
|
+
The client opens once per worker — in `services()`, which runs under
|
|
134
|
+
`sigil dev` and in each `sigil start` worker but never in the coordinator or
|
|
135
|
+
`sigil build` — and is shared by every request on it. Routes reach it as
|
|
136
|
+
`locals.db`, with nothing imported from the config file.
|
|
137
|
+
|
|
138
|
+
## Connection budget
|
|
139
|
+
|
|
140
|
+
```ts
|
|
141
|
+
adapter(url, { maxTotal: 20 }) // 5 per worker on 4 workers
|
|
142
|
+
```
|
|
143
|
+
|
|
144
|
+
`maxTotal` is deployment-wide, divided by the real worker count. Without that
|
|
145
|
+
division every worker opens the full amount, and a 4-worker deployment
|
|
146
|
+
quietly asks the database for 80 connections and gets refused. The count
|
|
147
|
+
comes from `workerContext()`, which reads what the coordinator set at spawn.
|
|
148
|
+
|
|
149
|
+
## Writing an adapter
|
|
150
|
+
|
|
151
|
+
```ts
|
|
152
|
+
import { defineSqlAdapter, sql } from "@sigil-dev/plugin-sql";
|
|
153
|
+
|
|
154
|
+
const myAdapter = defineSqlAdapter<MyClient>({
|
|
155
|
+
contract: 1,
|
|
156
|
+
name: "my-driver",
|
|
157
|
+
create: (ctx) => connect({ pool: Math.ceil(20 / ctx.workers) }),
|
|
158
|
+
close: (db) => db.end(),
|
|
159
|
+
transaction: (db, fn) => db.tx(fn),
|
|
160
|
+
ping: async (db) => { await db.ping(); },
|
|
161
|
+
});
|
|
162
|
+
```
|
|
163
|
+
|
|
164
|
+
Then prove it:
|
|
165
|
+
|
|
166
|
+
```ts
|
|
167
|
+
import { runAdapterConformance } from "@sigil-dev/plugin-sql/testing";
|
|
168
|
+
|
|
169
|
+
runAdapterConformance(myAdapter, {
|
|
170
|
+
exec: (db, q) => db.exec(q),
|
|
171
|
+
count: async (db, t) => Number((await db.query(`select count(*) n from ${t}`))[0].n),
|
|
172
|
+
});
|
|
173
|
+
```
|
|
174
|
+
|
|
175
|
+
The kit checks that `transaction` commits on success, **rolls back and
|
|
176
|
+
rethrows the same error object** on failure, returns the callback's result,
|
|
177
|
+
and that `close` releases the client. No type can check any of that, and a
|
|
178
|
+
transaction that silently does not roll back passes every type check.
|
|
179
|
+
|
|
180
|
+
Pass `isolation: false` for a single-connection driver. SQLite through
|
|
181
|
+
`Bun.SQL` genuinely has no isolation — measured, in transaction 2 rows /
|
|
182
|
+
outside 2 rows, against postgres 2 / 1 — so the kit skips that assertion
|
|
183
|
+
rather than asserting something untrue.
|
|
184
|
+
|
|
185
|
+
## What this replaced
|
|
186
|
+
|
|
187
|
+
This package previously exported `bunSqlite` / `bunPg` / `bunMysql` and a
|
|
188
|
+
`SqlExecutor` with `query(sql, params)`. That layer existed to bridge
|
|
189
|
+
`Bun.sql`'s positional-parameter API, and every bug in it came from guessing
|
|
190
|
+
a dialect out of a string: `sqlite://app.db` became the absolute path
|
|
191
|
+
`//app.db`, postgres and mysql were assumed to share a placeholder style
|
|
192
|
+
when they are opposites, and `toISOString()` timestamps were rejected by
|
|
193
|
+
MySQL. It also needed a per-dialect placeholder rewriter, and a timestamp
|
|
194
|
+
normaliser, both of which `Bun.SQL` makes unnecessary.
|
|
195
|
+
|
|
196
|
+
## Drizzle
|
|
197
|
+
|
|
198
|
+
Drizzle wraps a driver rather than replacing one, so the adapter creates
|
|
199
|
+
`Bun.SQL`, hands it to `drizzle()`, and gives you back the Drizzle instance.
|
|
200
|
+
It is about ten lines in user land, which is why it lives here instead of in
|
|
201
|
+
a package.
|
|
202
|
+
|
|
203
|
+
```ts
|
|
204
|
+
// sigil.config.ts
|
|
205
|
+
import { SQL } from "bun";
|
|
206
|
+
import { drizzle } from "drizzle-orm/bun-sql";
|
|
207
|
+
import { sql as q } from "drizzle-orm";
|
|
208
|
+
import { defineSqlAdapter, sql } from "@sigil-dev/plugin-sql";
|
|
209
|
+
import * as schema from "./src/db/schema";
|
|
210
|
+
|
|
211
|
+
// Named, because `Tx` is not re-inferred from a bare `db.transaction(fn)`:
|
|
212
|
+
// the callback parameter is contravariant, so TypeScript will not solve for
|
|
213
|
+
// it there and falls back to `Tx = C`, which is the unsound version. Naming
|
|
214
|
+
// the transaction type is what makes the cast unnecessary.
|
|
215
|
+
type DrizzleDb = ReturnType<typeof drizzle<typeof schema>>;
|
|
216
|
+
type DrizzleTx = Parameters<Parameters<DrizzleDb["transaction"]>[0]>[0];
|
|
217
|
+
|
|
218
|
+
const drizzleAdapter = defineSqlAdapter({
|
|
219
|
+
contract: 1,
|
|
220
|
+
name: "drizzle-bun-sql",
|
|
221
|
+
create: ({ workers }) =>
|
|
222
|
+
drizzle({
|
|
223
|
+
client: new SQL({
|
|
224
|
+
url: Bun.env.DATABASE_URL!,
|
|
225
|
+
// 20 is a deployment total, not a per-worker count.
|
|
226
|
+
max: Math.ceil(20 / workers),
|
|
227
|
+
}),
|
|
228
|
+
schema,
|
|
229
|
+
}),
|
|
230
|
+
close: (db) => db.$client.close(),
|
|
231
|
+
transaction: <R>(db: DrizzleDb, fn: (tx: DrizzleTx) => Promise<R>) =>
|
|
232
|
+
db.transaction(fn),
|
|
233
|
+
ping: async (db) => {
|
|
234
|
+
await db.execute(q`select 1`);
|
|
235
|
+
},
|
|
236
|
+
capabilities: {
|
|
237
|
+
// db.transaction() inside a transaction becomes a savepoint.
|
|
238
|
+
savepoint: (tx, fn) => tx.transaction(fn),
|
|
239
|
+
},
|
|
240
|
+
});
|
|
241
|
+
|
|
242
|
+
export default {
|
|
243
|
+
plugins: [sql(drizzleAdapter)],
|
|
244
|
+
};
|
|
245
|
+
```
|
|
246
|
+
|
|
247
|
+
Then in a route:
|
|
248
|
+
|
|
249
|
+
```ts
|
|
250
|
+
export const load = async ({ locals }) =>
|
|
251
|
+
locals.db.query.users.findMany({ with: { posts: true } });
|
|
252
|
+
```
|
|
253
|
+
|
|
254
|
+
### `tx` is not the database
|
|
255
|
+
|
|
256
|
+
Drizzle's transaction handle has no `$client` and no `batch`, so typing the
|
|
257
|
+
callback's parameter as the client type is false:
|
|
258
|
+
|
|
259
|
+
```ts
|
|
260
|
+
transaction: (db, fn) => db.transaction(fn as any) // what you had to write
|
|
261
|
+
```
|
|
262
|
+
|
|
263
|
+
That cast is why `SqlAdapter` has two type parameters:
|
|
264
|
+
|
|
265
|
+
```ts
|
|
266
|
+
export interface SqlAdapter<C, Tx = C> { /* ... */ }
|
|
267
|
+
```
|
|
268
|
+
|
|
269
|
+
`Tx` defaults to `C`, which is right for a raw driver — `Bun.SQL`'s
|
|
270
|
+
transaction handle *is* a `Bun.SQL`. For anything that wraps a driver it is
|
|
271
|
+
wrong, and Kysely has the same shape. With `Tx` inferred properly, the cast
|
|
272
|
+
disappears and `locals.db` is typed as whatever a route actually receives.
|
|
273
|
+
|
|
274
|
+
### Two Drizzle facts, measured
|
|
275
|
+
|
|
276
|
+
Both against drizzle-orm 0.45.3 with a real `Bun.SQL` on real MariaDB and
|
|
277
|
+
real postgres:
|
|
278
|
+
|
|
279
|
+
- **`db.execute` does not bind parameters.** It takes a `SQLWrapper`; a
|
|
280
|
+
second argument is silently ignored, so `?` reaches the server as literal
|
|
281
|
+
SQL. The type checker catches it too — *"Expected 1 arguments, but got
|
|
282
|
+
2."*
|
|
283
|
+
- **`db.execute(q`SELECT ${n}`)` is not portable.** The bun-sql driver emits
|
|
284
|
+
`$1` placeholders unconditionally, so the identical call on the identical
|
|
285
|
+
object works on postgres and fails on MySQL with *"Unknown column '$1'"*.
|
|
286
|
+
|
|
287
|
+
Neither affects the recipe above, because Drizzle's tagged templates are how
|
|
288
|
+
*you* write queries and the plugin only ever calls `ping`. They do mean a
|
|
289
|
+
Drizzle adapter should not try to expose raw `query(sql, params)` — which is
|
|
290
|
+
why `runAdapterConformance` takes hooks:
|
|
291
|
+
|
|
292
|
+
```ts
|
|
293
|
+
runAdapterConformance(drizzleAdapter, {
|
|
294
|
+
exec: async (db, s) => {
|
|
295
|
+
await db.execute(q.raw(s));
|
|
296
|
+
},
|
|
297
|
+
count: async (db, t) => {
|
|
298
|
+
const rows = (await db.execute(
|
|
299
|
+
q.raw(`select count(*) as n from ${t}`),
|
|
300
|
+
)) as Array<{ n: number | string }>;
|
|
301
|
+
return Number(rows[0]?.n ?? 0);
|
|
302
|
+
},
|
|
303
|
+
});
|
|
304
|
+
```
|
|
305
|
+
|
|
306
|
+
The hook parameters are `C | Tx`, because the kit calls them with both: it
|
|
307
|
+
runs `exec` inside `adapter.transaction` to prove rollback works, and
|
|
308
|
+
outside it to set up. The row-indexing in `count` is deliberate — drizzle's
|
|
309
|
+
`execute` return shape has changed between drivers and releases, and it is
|
|
310
|
+
the kind of thing a conformance run catches and a mock never will.
|
|
311
|
+
|
|
312
|
+
## License
|
|
313
|
+
|
|
314
|
+
MIT
|
package/package.json
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@sigil-dev/plugin-sql",
|
|
3
|
+
"description": "A contract and conformance kit for SQL adapters in Grimoire",
|
|
4
|
+
"module": "src/index.ts",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"private": false,
|
|
7
|
+
"version": "0.9.13",
|
|
8
|
+
"keywords": [
|
|
9
|
+
"grimoire",
|
|
10
|
+
"sigil",
|
|
11
|
+
"sql",
|
|
12
|
+
"postgres",
|
|
13
|
+
"sqlite",
|
|
14
|
+
"database"
|
|
15
|
+
],
|
|
16
|
+
"files": [
|
|
17
|
+
"src",
|
|
18
|
+
"README.md"
|
|
19
|
+
],
|
|
20
|
+
"peerDependencies": {
|
|
21
|
+
"typescript": "^5",
|
|
22
|
+
"@sigil-dev/grimoire": "0.9.13"
|
|
23
|
+
},
|
|
24
|
+
"exports": {
|
|
25
|
+
".": "./src/index.ts",
|
|
26
|
+
"./bun": "./src/bun.ts",
|
|
27
|
+
"./testing": "./src/testing.ts",
|
|
28
|
+
"./package.json": "./package.json"
|
|
29
|
+
}
|
|
30
|
+
}
|
package/src/bun.ts
ADDED
|
@@ -0,0 +1,265 @@
|
|
|
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 { GrimoirePlugin } from "@sigil-dev/grimoire";
|
|
24
|
+
import type { SqlHandle } from "./database.ts";
|
|
25
|
+
|
|
26
|
+
/** The client `Bun.SQL` produces. Named as a type only — the class is a
|
|
27
|
+
* runtime value reached through `Bun`, so importing it as a type keeps this
|
|
28
|
+
* module from assuming a Bun build exposes it at module scope.
|
|
29
|
+
*
|
|
30
|
+
* `InstanceType<typeof Bun.SQL>` rather than `ReturnType<typeof Bun.SQL>`:
|
|
31
|
+
* Bun.SQL is a constructor, so its type parameter is the instance, and
|
|
32
|
+
* `ReturnType` of a class type is the class itself — which is why tsc
|
|
33
|
+
* complained that "typeof SQL" does not satisfy the client constraint. */
|
|
34
|
+
type SQL = InstanceType<typeof Bun.SQL>;
|
|
35
|
+
|
|
36
|
+
/** The client type, exported so a test hook can be typed without `any`. */
|
|
37
|
+
export type BunSqlClient = SQL;
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* What `locals.db` is with this adapter: the `Bun.SQL` client plus the
|
|
41
|
+
* `sql` tag. Put it on `App.Locals` in `src/app.d.ts`.
|
|
42
|
+
*/
|
|
43
|
+
export type BunSqlHandle = SqlHandle<SQL>;
|
|
44
|
+
|
|
45
|
+
export interface BunSqlOptions {
|
|
46
|
+
/**
|
|
47
|
+
* Total connections across the whole deployment, divided by the worker
|
|
48
|
+
* count. So 20 across 4 workers is 5 each.
|
|
49
|
+
*
|
|
50
|
+
* Dividing matters: without it every worker opens the full number, and a
|
|
51
|
+
* 4-worker deployment quietly asks the database for 80 connections and
|
|
52
|
+
* gets refused. `ctx.workers` is why that is correct rather than a
|
|
53
|
+
* guess — see `workerContext()`.
|
|
54
|
+
*
|
|
55
|
+
* May also be given in the connection object, beside the driver options.
|
|
56
|
+
*/
|
|
57
|
+
maxTotal?: number;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* A connection: a DSN, or `Bun.SQL`'s options object. The object may carry
|
|
62
|
+
* `maxTotal` beside the driver's own options, so one object is the whole
|
|
63
|
+
* database:
|
|
64
|
+
*
|
|
65
|
+
* ```ts
|
|
66
|
+
* { url: env.DB_URL, idleTimeout: 30, maxTotal: 12 }
|
|
67
|
+
* ```
|
|
68
|
+
*/
|
|
69
|
+
export type BunSqlConnection =
|
|
70
|
+
| string
|
|
71
|
+
| ({ url?: string; maxTotal?: number } & Record<string, unknown>);
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* Split a connection into driver options and the budget, refusing the one
|
|
75
|
+
* spelling that silently does the wrong thing.
|
|
76
|
+
*/
|
|
77
|
+
function connectionOf(
|
|
78
|
+
dsn: BunSqlConnection,
|
|
79
|
+
opts: BunSqlOptions,
|
|
80
|
+
): { driver: Record<string, unknown>; maxTotal: number | undefined } {
|
|
81
|
+
if (typeof dsn === "string") return { driver: { url: dsn }, maxTotal: opts.maxTotal };
|
|
82
|
+
const { maxTotal: inline, ...driver } = dsn;
|
|
83
|
+
if ("max" in driver) {
|
|
84
|
+
// `max` is Bun.SQL's per-client pool size. Passed here it goes
|
|
85
|
+
// straight to the driver in every worker, so `max: 12` on four
|
|
86
|
+
// workers is 48 connections — the budget looks set and is not.
|
|
87
|
+
throw new Error(
|
|
88
|
+
"bunSqlAdapter: `max` is a per-worker pool size, so every worker " +
|
|
89
|
+
"would open that many. Use `maxTotal` for a budget across the " +
|
|
90
|
+
"deployment; it is divided by the worker count for you.",
|
|
91
|
+
);
|
|
92
|
+
}
|
|
93
|
+
if (inline !== undefined && opts.maxTotal !== undefined && inline !== opts.maxTotal) {
|
|
94
|
+
throw new Error(
|
|
95
|
+
`bunSqlAdapter: maxTotal is ${inline} in the connection and ` +
|
|
96
|
+
`${opts.maxTotal} in the options. Give it once.`,
|
|
97
|
+
);
|
|
98
|
+
}
|
|
99
|
+
return { driver, maxTotal: inline ?? opts.maxTotal };
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/**
|
|
103
|
+
* A `Bun.SQL` adapter.
|
|
104
|
+
*
|
|
105
|
+
* ```ts
|
|
106
|
+
* sql(bunSqlAdapter(process.env.DATABASE_URL!))
|
|
107
|
+
* sql(bunSqlAdapter({ url: "app.db" })) // sqlite, one connection
|
|
108
|
+
* sql(bunSqlAdapter(url, { maxTotal: 20 })) // 5 per worker on 4 workers
|
|
109
|
+
* ```
|
|
110
|
+
*/
|
|
111
|
+
export function bunSqlAdapter(
|
|
112
|
+
dsn: BunSqlConnection,
|
|
113
|
+
opts: BunSqlOptions = {},
|
|
114
|
+
): SqlAdapter<SQL> {
|
|
115
|
+
// Split now, so a wrong spelling fails where the config is written.
|
|
116
|
+
const { driver, maxTotal } = connectionOf(dsn, opts);
|
|
117
|
+
return defineSqlAdapter<SQL>({
|
|
118
|
+
contract: 1,
|
|
119
|
+
name: "bun-sql",
|
|
120
|
+
create({ workers }) {
|
|
121
|
+
const total = maxTotal;
|
|
122
|
+
// Bun.SQL is a value, and this module is type-only about it
|
|
123
|
+
// otherwise — naming the type keeps the public signature honest.
|
|
124
|
+
const Ctor = Bun.SQL as unknown as new (
|
|
125
|
+
opts: Record<string, unknown>,
|
|
126
|
+
) => SQL;
|
|
127
|
+
// Only divide when there is a budget to divide. `max: undefined`
|
|
128
|
+
// is Bun.SQL's own default and must be left alone.
|
|
129
|
+
const max =
|
|
130
|
+
total === undefined
|
|
131
|
+
? undefined
|
|
132
|
+
: Math.max(1, Math.ceil(total / Math.max(1, workers)));
|
|
133
|
+
return new Ctor({
|
|
134
|
+
...driver,
|
|
135
|
+
...(max === undefined ? {} : { max }),
|
|
136
|
+
});
|
|
137
|
+
},
|
|
138
|
+
close(db) {
|
|
139
|
+
db.close();
|
|
140
|
+
},
|
|
141
|
+
transaction: (db, fn) =>
|
|
142
|
+
// Bun's `begin` hands its callback a transaction handle, which is
|
|
143
|
+
// the same client type. The cast is here because `begin` is typed
|
|
144
|
+
// against its own overloads rather than a generic callback, and
|
|
145
|
+
// one cast in the adapter is better than `as any` at every call
|
|
146
|
+
// site in a plugin.
|
|
147
|
+
db.begin(((tx: SQL) => fn(tx)) as never) as never,
|
|
148
|
+
async ping(db) {
|
|
149
|
+
await db`select 1`;
|
|
150
|
+
},
|
|
151
|
+
capabilities: {
|
|
152
|
+
/**
|
|
153
|
+
* Through Bun.SQL's own tagged template, not `unsafe(text)`.
|
|
154
|
+
*
|
|
155
|
+
* `text` has `$1` placeholders, which MySQL reads as a column name
|
|
156
|
+
* ("Unknown column '$1'"). The template parts let Bun.SQL choose
|
|
157
|
+
* the placeholder for its own dialect — the job this package
|
|
158
|
+
* handed to the driver precisely because it got it wrong itself.
|
|
159
|
+
* It also means a helper built by `helper` below binds the way
|
|
160
|
+
* Bun.SQL's own does.
|
|
161
|
+
*/
|
|
162
|
+
async query(target, _sql, values, strings) {
|
|
163
|
+
return (await (target as SQL)(
|
|
164
|
+
templateOf(strings),
|
|
165
|
+
...(values as never[]),
|
|
166
|
+
)) as unknown[];
|
|
167
|
+
},
|
|
168
|
+
/**
|
|
169
|
+
* `db.sql(ids)` → `client(ids)`, `db.sql.array(xs, t)` →
|
|
170
|
+
* `client.array(xs, t)`, on the client that runs the query.
|
|
171
|
+
*/
|
|
172
|
+
helper(target, method, args) {
|
|
173
|
+
const c = target as unknown as Record<string, (...a: unknown[]) => unknown> &
|
|
174
|
+
((...a: unknown[]) => unknown);
|
|
175
|
+
if (method === undefined) return c(...args);
|
|
176
|
+
const fn = c[method];
|
|
177
|
+
if (typeof fn !== "function") {
|
|
178
|
+
throw new Error(`Bun.SQL has no helper "${method}".`);
|
|
179
|
+
}
|
|
180
|
+
return fn.apply(c, args as unknown[]);
|
|
181
|
+
},
|
|
182
|
+
/** `SAVEPOINT`, so a nested transaction can roll back alone. */
|
|
183
|
+
savepoint: (tx, fn) =>
|
|
184
|
+
(tx as unknown as {
|
|
185
|
+
savepoint<R>(fn: (sp: SQL) => Promise<R>): Promise<R>;
|
|
186
|
+
}).savepoint(fn),
|
|
187
|
+
},
|
|
188
|
+
});
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
/**
|
|
192
|
+
* The parts of a fragment as a `TemplateStringsArray`, built once per
|
|
193
|
+
* fragment: Bun.SQL reads `raw`, and a stable array lets it reuse what it
|
|
194
|
+
* derived from the last run.
|
|
195
|
+
*/
|
|
196
|
+
const templates = new WeakMap<readonly string[], TemplateStringsArray>();
|
|
197
|
+
function templateOf(strings: readonly string[]): TemplateStringsArray {
|
|
198
|
+
let t = templates.get(strings);
|
|
199
|
+
if (!t) {
|
|
200
|
+
t = Object.freeze(
|
|
201
|
+
Object.assign([...strings], { raw: Object.freeze([...strings]) }),
|
|
202
|
+
) as unknown as TemplateStringsArray;
|
|
203
|
+
templates.set(strings, t);
|
|
204
|
+
}
|
|
205
|
+
return t;
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
export interface AdapterOptions extends BunSqlOptions, SqlPluginOptions<SQL> {
|
|
209
|
+
/**
|
|
210
|
+
* Register nothing when the connection is missing, instead of failing
|
|
211
|
+
* the boot. For a database a feature can live without; the feature asks
|
|
212
|
+
* `hasDatabase(key)`.
|
|
213
|
+
*/
|
|
214
|
+
optional?: boolean;
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
/**
|
|
218
|
+
* A ready-to-register `Bun.SQL` plugin.
|
|
219
|
+
*
|
|
220
|
+
* `sql(bunSqlAdapter(dsn))` is two imports and a nested call for what is
|
|
221
|
+
* one decision, and the nesting is what makes it look like there is more
|
|
222
|
+
* to it than there is. This is that call, applied.
|
|
223
|
+
*
|
|
224
|
+
* ```ts
|
|
225
|
+
* import { adapter } from "@sigil-dev/plugin-sql/bun";
|
|
226
|
+
*
|
|
227
|
+
* export default {
|
|
228
|
+
* plugins: [adapter(Bun.env.DATABASE_URL!, { maxTotal: 20 })],
|
|
229
|
+
* };
|
|
230
|
+
* ```
|
|
231
|
+
*
|
|
232
|
+
* `bunSqlAdapter` stays exported, and is what you want when you need the
|
|
233
|
+
* adapter itself — naming a `key`, wrapping it in your own plugin, or
|
|
234
|
+
* handing it to `runAdapterConformance`. This is the common case and it
|
|
235
|
+
* should be the short one.
|
|
236
|
+
*
|
|
237
|
+
* Both are the same object underneath: `bunSql` calls `sql(bunSqlAdapter(..))`
|
|
238
|
+
* rather than reimplementing the lifecycle, so there is one code path to be
|
|
239
|
+
* wrong about.
|
|
240
|
+
*/
|
|
241
|
+
export function adapter(
|
|
242
|
+
dsn: BunSqlConnection | undefined,
|
|
243
|
+
options: AdapterOptions = {},
|
|
244
|
+
): GrimoirePlugin {
|
|
245
|
+
const { optional, perRequestTx, key, ...budget } = options;
|
|
246
|
+
const missing =
|
|
247
|
+
dsn === undefined ||
|
|
248
|
+
dsn === "" ||
|
|
249
|
+
(typeof dsn === "object" && "url" in dsn && !dsn.url);
|
|
250
|
+
if (missing) {
|
|
251
|
+
const name = key ?? "db";
|
|
252
|
+
if (optional) return { name: `sql:${name} (not configured)` };
|
|
253
|
+
// Bun.SQL with no url connects to localhost with the OS user, which
|
|
254
|
+
// fails later with a credentials error that never mentions the
|
|
255
|
+
// variable that was empty.
|
|
256
|
+
throw new Error(
|
|
257
|
+
`adapter: database "${name}" has no connection URL — the environment ` +
|
|
258
|
+
"variable is probably unset. Pass { optional: true } if the app " +
|
|
259
|
+
"should start without it.",
|
|
260
|
+
);
|
|
261
|
+
}
|
|
262
|
+
return sql(bunSqlAdapter(dsn, budget), { perRequestTx, key });
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
export default adapter;
|