@sigil-dev/plugin-sql 0.9.21 → 0.9.23

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
@@ -1,314 +1,324 @@
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
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({ key: "userDb", url: env.USER_DB_URL, maxTotal: 4, 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
+ `adapter()` returns the plugin with a `.database` handle (`undefined` when an
108
+ optional adapter was not configured). Hand the plugin to something that needs
109
+ the database, rather than its name:
110
+
111
+ ```ts
112
+ const userDb = adapter({ key: "userDb", url: env.VIEWER_DB_URL, optional: true });
113
+ const queue = jobs({ database: userDb, handlers }); // off when userDb is not configured
114
+ export default { plugins: [master, userDb, queue] };
115
+ ```
116
+
117
+ ## The contract
118
+
119
+ ```ts
120
+ interface SqlAdapter<C, Tx = C> {
121
+ contract: 1; // bump on a breaking change
122
+ name: string;
123
+ create(ctx: WorkerContext): C | Promise<C>;
124
+ close(client: C): void | Promise<void>;
125
+ transaction<R>(client: C, fn: (tx: Tx) => Promise<R>): Promise<R>;
126
+ ping(client: C): Promise<void>;
127
+ capabilities?: {
128
+ query?(target, sql, values, strings): Promise<unknown[]>; // enables db.sql
129
+ savepoint?(tx, fn): Promise<R>; // nested transactions
130
+ setLocal?, listen?, instrument?
131
+ };
132
+ }
133
+ ```
134
+
135
+ `contract` is checked when the plugin is constructed, so an adapter written
136
+ against a different version fails where you configured it rather than inside
137
+ a transaction where the stack trace points somewhere else.
138
+
139
+ `ping()` runs at startup. **A database unreachable at boot fails the
140
+ server start**, not the first request — a health check returning 200 while
141
+ every query fails is worse than a deploy that stops.
142
+
143
+ The client opens once per worker — in `services()`, which runs under
144
+ `sigil dev` and in each `sigil start` worker but never in the coordinator or
145
+ `sigil build` — and is shared by every request on it. Routes reach it as
146
+ `locals.db`, with nothing imported from the config file.
147
+
148
+ ## Connection budget
149
+
150
+ ```ts
151
+ adapter(url, { maxTotal: 20 }) // 5 per worker on 4 workers
152
+ ```
153
+
154
+ `maxTotal` is deployment-wide, divided by the real worker count. Without that
155
+ division every worker opens the full amount, and a 4-worker deployment
156
+ quietly asks the database for 80 connections and gets refused. The count
157
+ comes from `workerContext()`, which reads what the coordinator set at spawn.
158
+
159
+ ## Writing an adapter
160
+
161
+ ```ts
162
+ import { defineSqlAdapter, sql } from "@sigil-dev/plugin-sql";
163
+
164
+ const myAdapter = defineSqlAdapter<MyClient>({
165
+ contract: 1,
166
+ name: "my-driver",
167
+ create: (ctx) => connect({ pool: Math.ceil(20 / ctx.workers) }),
168
+ close: (db) => db.end(),
169
+ transaction: (db, fn) => db.tx(fn),
170
+ ping: async (db) => { await db.ping(); },
171
+ });
172
+ ```
173
+
174
+ Then prove it:
175
+
176
+ ```ts
177
+ import { runAdapterConformance } from "@sigil-dev/plugin-sql/testing";
178
+
179
+ runAdapterConformance(myAdapter, {
180
+ exec: (db, q) => db.exec(q),
181
+ count: async (db, t) => Number((await db.query(`select count(*) n from ${t}`))[0].n),
182
+ });
183
+ ```
184
+
185
+ The kit checks that `transaction` commits on success, **rolls back and
186
+ rethrows the same error object** on failure, returns the callback's result,
187
+ and that `close` releases the client. No type can check any of that, and a
188
+ transaction that silently does not roll back passes every type check.
189
+
190
+ Pass `isolation: false` for a single-connection driver. SQLite through
191
+ `Bun.SQL` genuinely has no isolation — measured, in transaction 2 rows /
192
+ outside 2 rows, against postgres 2 / 1 — so the kit skips that assertion
193
+ rather than asserting something untrue.
194
+
195
+ ## What this replaced
196
+
197
+ This package previously exported `bunSqlite` / `bunPg` / `bunMysql` and a
198
+ `SqlExecutor` with `query(sql, params)`. That layer existed to bridge
199
+ `Bun.sql`'s positional-parameter API, and every bug in it came from guessing
200
+ a dialect out of a string: `sqlite://app.db` became the absolute path
201
+ `//app.db`, postgres and mysql were assumed to share a placeholder style
202
+ when they are opposites, and `toISOString()` timestamps were rejected by
203
+ MySQL. It also needed a per-dialect placeholder rewriter, and a timestamp
204
+ normaliser, both of which `Bun.SQL` makes unnecessary.
205
+
206
+ ## Drizzle
207
+
208
+ Drizzle wraps a driver rather than replacing one, so the adapter creates
209
+ `Bun.SQL`, hands it to `drizzle()`, and gives you back the Drizzle instance.
210
+ It is about ten lines in user land, which is why it lives here instead of in
211
+ a package.
212
+
213
+ ```ts
214
+ // sigil.config.ts
215
+ import { SQL } from "bun";
216
+ import { drizzle } from "drizzle-orm/bun-sql";
217
+ import { sql as q } from "drizzle-orm";
218
+ import { defineSqlAdapter, sql } from "@sigil-dev/plugin-sql";
219
+ import * as schema from "./src/db/schema";
220
+
221
+ // Named, because `Tx` is not re-inferred from a bare `db.transaction(fn)`:
222
+ // the callback parameter is contravariant, so TypeScript will not solve for
223
+ // it there and falls back to `Tx = C`, which is the unsound version. Naming
224
+ // the transaction type is what makes the cast unnecessary.
225
+ type DrizzleDb = ReturnType<typeof drizzle<typeof schema>>;
226
+ type DrizzleTx = Parameters<Parameters<DrizzleDb["transaction"]>[0]>[0];
227
+
228
+ const drizzleAdapter = defineSqlAdapter({
229
+ contract: 1,
230
+ name: "drizzle-bun-sql",
231
+ create: ({ workers }) =>
232
+ drizzle({
233
+ client: new SQL({
234
+ url: Bun.env.DATABASE_URL!,
235
+ // 20 is a deployment total, not a per-worker count.
236
+ max: Math.ceil(20 / workers),
237
+ }),
238
+ schema,
239
+ }),
240
+ close: (db) => db.$client.close(),
241
+ transaction: <R>(db: DrizzleDb, fn: (tx: DrizzleTx) => Promise<R>) =>
242
+ db.transaction(fn),
243
+ ping: async (db) => {
244
+ await db.execute(q`select 1`);
245
+ },
246
+ capabilities: {
247
+ // db.transaction() inside a transaction becomes a savepoint.
248
+ savepoint: (tx, fn) => tx.transaction(fn),
249
+ },
250
+ });
251
+
252
+ export default {
253
+ plugins: [sql(drizzleAdapter)],
254
+ };
255
+ ```
256
+
257
+ Then in a route:
258
+
259
+ ```ts
260
+ export const load = async ({ locals }) =>
261
+ locals.db.query.users.findMany({ with: { posts: true } });
262
+ ```
263
+
264
+ ### `tx` is not the database
265
+
266
+ Drizzle's transaction handle has no `$client` and no `batch`, so typing the
267
+ callback's parameter as the client type is false:
268
+
269
+ ```ts
270
+ transaction: (db, fn) => db.transaction(fn as any) // what you had to write
271
+ ```
272
+
273
+ That cast is why `SqlAdapter` has two type parameters:
274
+
275
+ ```ts
276
+ export interface SqlAdapter<C, Tx = C> { /* ... */ }
277
+ ```
278
+
279
+ `Tx` defaults to `C`, which is right for a raw driver — `Bun.SQL`'s
280
+ transaction handle *is* a `Bun.SQL`. For anything that wraps a driver it is
281
+ wrong, and Kysely has the same shape. With `Tx` inferred properly, the cast
282
+ disappears and `locals.db` is typed as whatever a route actually receives.
283
+
284
+ ### Two Drizzle facts, measured
285
+
286
+ Both against drizzle-orm 0.45.3 with a real `Bun.SQL` on real MariaDB and
287
+ real postgres:
288
+
289
+ - **`db.execute` does not bind parameters.** It takes a `SQLWrapper`; a
290
+ second argument is silently ignored, so `?` reaches the server as literal
291
+ SQL. The type checker catches it too — *"Expected 1 arguments, but got
292
+ 2."*
293
+ - **`db.execute(q`SELECT ${n}`)` is not portable.** The bun-sql driver emits
294
+ `$1` placeholders unconditionally, so the identical call on the identical
295
+ object works on postgres and fails on MySQL with *"Unknown column '$1'"*.
296
+
297
+ Neither affects the recipe above, because Drizzle's tagged templates are how
298
+ *you* write queries and the plugin only ever calls `ping`. They do mean a
299
+ Drizzle adapter should not try to expose raw `query(sql, params)` — which is
300
+ why `runAdapterConformance` takes hooks:
301
+
302
+ ```ts
303
+ runAdapterConformance(drizzleAdapter, {
304
+ exec: async (db, s) => {
305
+ await db.execute(q.raw(s));
306
+ },
307
+ count: async (db, t) => {
308
+ const rows = (await db.execute(
309
+ q.raw(`select count(*) as n from ${t}`),
310
+ )) as Array<{ n: number | string }>;
311
+ return Number(rows[0]?.n ?? 0);
312
+ },
313
+ });
314
+ ```
315
+
316
+ The hook parameters are `C | Tx`, because the kit calls them with both: it
317
+ runs `exec` inside `adapter.transaction` to prove rollback works, and
318
+ outside it to set up. The row-indexing in `count` is deliberate — drizzle's
319
+ `execute` return shape has changed between drivers and releases, and it is
320
+ the kind of thing a conformance run catches and a mock never will.
321
+
322
+ ## License
323
+
324
+ MIT