@sigil-dev/plugin-sql 0.9.20 → 0.9.22

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/src/contract.ts CHANGED
@@ -1,249 +1,249 @@
1
- /**
2
- * The contract between a SQL adapter and the framework.
3
- *
4
- * An adapter is anything that can produce a client, close it, run a
5
- * transaction and answer a health check. That is deliberately small: the
6
- * point is not to abstract SQL, it is to let a plugin hold a client it does
7
- * not know how to open, and to let anyone *prove* their adapter behaves.
8
- *
9
- * ```ts
10
- * sql(defineSqlAdapter<MyClient>({
11
- * contract: 1,
12
- * name: "my-driver",
13
- * create: () => connect(),
14
- * close: (db) => db.end(),
15
- * transaction: (db, fn) => db.tx(fn),
16
- * ping: async (db) => { await db.ping(); },
17
- * }));
18
- * ```
19
- */
20
-
21
- import { type GrimoirePlugin } from "@sigil-dev/grimoire";
22
- import { createDatabase } from "./database.ts";
23
- import {
24
- workerContext,
25
- type WorkerContext,
26
- } from "@sigil-dev/grimoire";
27
-
28
- export type { WorkerContext };
29
- export { workerContext };
30
-
31
- /**
32
- * Bumped when the adapter interface changes incompatibly.
33
- *
34
- * The field exists so an old adapter against a new plugin fails loudly at
35
- * construction rather than being silently mis-called. Without it, a
36
- * signature change is a runtime surprise inside somebody's transaction,
37
- * which is the worst place to find one.
38
- */
39
- export const SQL_CONTRACT_VERSION = 1 as const;
40
-
41
- /**
42
- * @typeParam Tx - what a route actually receives inside `transaction`.
43
- *
44
- * Defaults to `C`, and that default is right for a raw driver: Bun.SQL's
45
- * transaction handle *is* a Bun.SQL. It is wrong for anything that wraps a
46
- * driver, and those are the popular libraries. Drizzle is the case that
47
- * forced this: its `tx` has no `$client` and no `batch`, so
48
- * `fn: (tx: C) => ...` is a lie that only compiles because the author
49
- * writes `as any` over it. Kysely has the same shape.
50
- *
51
- * So the type says what it means. An adapter whose transaction handle is
52
- * genuinely the same type passes one argument; one that differs passes two
53
- * and gets `locals.db` typed as the thing a route will hold.
54
- */
55
- export interface SqlAdapter<C, Tx = C> {
56
- contract: typeof SQL_CONTRACT_VERSION;
57
- /** Shown in errors and logs. */
58
- name: string;
59
- /**
60
- * Open a client. Called once per worker process, so anything sized from
61
- * `ctx.workers` here is sized for the whole deployment.
62
- */
63
- create(ctx: WorkerContext): C | Promise<C>;
64
- /** Release the client. Called on shutdown. */
65
- close(client: C): void | Promise<void>;
66
- /**
67
- * Run `fn` in a transaction: commit when it resolves, roll back when it
68
- * throws, and rethrow that same error.
69
- */
70
- transaction<R>(client: C, fn: (tx: Tx) => Promise<R>): Promise<R>;
71
- /**
72
- * Prove the client is usable. Called at startup so an unreachable
73
- * database fails the deploy rather than the first request.
74
- */
75
- ping(client: C): Promise<void>;
76
-
77
- /**
78
- * Optional features this driver supports, checked before use rather
79
- * than discovered when a query fails.
80
- *
81
- * Optional on the adapter and so part of contract 1: an adapter written
82
- * before this field existed is still valid, and still works. The
83
- * framework treats an absent `capabilities` as "supports nothing",
84
- * which is the safe direction — the alternative is a plugin calling
85
- * `setLocal` on a driver that would have ignored it.
86
- */
87
- capabilities?: SqlCapabilities<C, Tx>;
88
- }
89
-
90
- /**
91
- * Driver features a plugin can ask for.
92
- *
93
- * Every one of these is about the *session* rather than a query, which is
94
- * why they are worth declaring instead of assuming: on a pooled connection
95
- * they either do not work or they leak to the next borrower.
96
- */
97
- export interface SqlCapabilities<C, Tx> {
98
- /**
99
- * `SET LOCAL` inside a transaction — Postgres row-level security,
100
- * `app.user_id`, that sort of thing.
101
- *
102
- * Only meaningful inside a transaction: outside one it would be a
103
- * plain `SET` on a pooled connection, and the next borrower inherits
104
- * it. So this is only safe when the caller uses `tx()`, and the
105
- * framework cannot check that for you.
106
- */
107
- setLocal?(tx: Tx, key: string, value: string): Promise<void>;
108
-
109
- /** Subscribe to `LISTEN`/`NOTIFY`. Returns an unsubscribe function. */
110
- listen?(client: C, channel: string, cb: (payload: string) => void): Promise<() => void>;
111
-
112
- /** Called after every query with its text and duration. */
113
- instrument?(client: C, onQuery: (q: { sql: string; ms: number }) => void): void;
114
-
115
- /**
116
- * Run a parameterised query and return rows.
117
- *
118
- * This is what backs `db.sql` — the lazy, composable template tag — so
119
- * it is only for adapters whose driver really binds parameters. A
120
- * driver's `execute` is not enough: Drizzle's ignores the params array
121
- * and inlines `?` literally, which would turn every fragment
122
- * composition into a silent injection. An adapter without this does not
123
- * get `db.sql` at all, rather than a version that looks like it works.
124
- *
125
- * `sql` uses `$1` placeholders, which only postgres reads. `strings` is
126
- * the same query as template parts, one longer than `values`: an adapter
127
- * whose driver has a tagged template should pass it that, so the driver
128
- * picks its own placeholders and MySQL gets `?`.
129
- */
130
- query?(
131
- target: C | Tx,
132
- sql: string,
133
- values: readonly unknown[],
134
- strings: readonly string[],
135
- ): Promise<unknown[]>;
136
-
137
- /**
138
- * Run `fn` in a savepoint inside the transaction `tx`: roll back to it
139
- * when `fn` throws, and rethrow.
140
- *
141
- * This is what `db.transaction()` does when a transaction is already in
142
- * scope — under `perRequestTx`, that is every transaction a route opens.
143
- * Without it the inner call joins the outer transaction instead. What it
144
- * must never do is open a second transaction on another connection: that
145
- * one commits even when the request rolls back, and it deadlocks the
146
- * moment it touches a row the request already wrote.
147
- */
148
- savepoint?<R>(tx: Tx, fn: (tx: Tx) => Promise<R>): Promise<R>;
149
-
150
- /**
151
- * Build a driver helper on the client that is about to run the query:
152
- * `db.sql(ids)` becomes `client(ids)`, `db.sql.array(xs, "text")` becomes
153
- * `client.array(xs, "text")`. `method` is undefined for the first form.
154
- *
155
- * Without this, `db.sql(...)` and `db.sql.array(...)` throw when called,
156
- * rather than binding an object the driver does not understand.
157
- */
158
- helper?(target: C | Tx, method: string | undefined, args: readonly unknown[]): unknown;
159
- }
160
-
161
- /**
162
- * Identity function, so an adapter literal keeps its inferred type.
163
- *
164
- * Both parameters infer from the object, so `Tx` is picked up from a
165
- * `transaction` that annotates it and left as `C` otherwise.
166
- */
167
- export function defineSqlAdapter<C, Tx = C>(
168
- adapter: SqlAdapter<C, Tx>,
169
- ): SqlAdapter<C, Tx> {
170
- return adapter;
171
- }
172
-
173
- /**
174
- * The transaction handle type of an adapter, for a caller that needs to
175
- * name it — a route's `locals.db`, or a test hook.
176
- *
177
- * `SqlAdapter<C>` alone gives `C` for `Tx` unless the adapter's
178
- * `transaction` was written with the handle annotated. A bare
179
- * `db.transaction(fn)` does not re-infer it, because the parameter is
180
- * contravariant and TypeScript will not solve for it from that position.
181
- * That is a property of the compiler, not of this package, and it is why a
182
- * Drizzle adapter annotates the parameter explicitly:
183
- *
184
- * ```ts
185
- * transaction: <R>(db: DrizzleDb, fn: (tx: DrizzleTx) => Promise<R>) =>
186
- * db.transaction(fn)
187
- * ```
188
- */
189
- export type TxOf<A> = A extends SqlAdapter<infer _C, infer T> ? T : never;
190
-
191
- /** The client type of an adapter. */
192
- export type ClientOf<A> = A extends SqlAdapter<infer C, infer _T> ? C : never;
193
-
194
- export interface SqlPluginOptions<Tx> {
195
- /**
196
- * Wrap each request in a transaction.
197
- *
198
- * Every query made through `locals.db` during the request — the tagged
199
- * template, `locals.db.sql`, `unsafe()`, a Drizzle builder — runs in
200
- * that transaction and rolls back with it. Costs a BEGIN/COMMIT per
201
- * request and holds a connection for its duration, so each worker's
202
- * pool must be larger than the requests it serves at once.
203
- */
204
- perRequestTx?: boolean;
205
- /** The key `locals` receives. Defaults to "db". */
206
- key?: string;
207
- }
208
-
209
- /**
210
- * The shape of `locals` this plugin contributes.
211
- *
212
- * `Tx` and not `C`: when `perRequestTx` is on, a route holds the
213
- * transaction handle, and a library that wraps a driver hands out a
214
- * different type inside the transaction than outside it. Typing
215
- * `locals.db` as `C` would be the same lie `as any` was hiding, one level
216
- * up where nothing would flag it.
217
- */
218
- export interface SqlLocals<Tx> {
219
- [key: string]: Tx;
220
- }
221
-
222
- /**
223
- * Publish an adapter's client on `locals`, and close it on shutdown.
224
- *
225
- * The client opens once per worker at startup and is shared by every
226
- * request on that worker, which is what a connection pool is for. Per-request
227
- * work reaches it as `locals.db`, with nothing imported from
228
- * sigil.config.ts.
229
- */
230
- export function sql<C, Tx = C>(
231
- adapter: SqlAdapter<C, Tx>,
232
- opts: SqlPluginOptions<Tx> = {},
233
- ): GrimoirePlugin {
234
- // Implemented in terms of createDatabase rather than beside it. The two
235
- // used to be separate bodies, which meant the locals-based plugin and the
236
- // Database object could disagree about when the client opens, who closes
237
- // it, and what a transaction is — and they did, at least once, when one
238
- // gained a shutdown path the other did not.
239
- //
240
- // Named after its key, so `database("db")` finds the one `adapter(url)`
241
- // registered, and a second plugin on another key is a second database
242
- // rather than a second copy of the first.
243
- const key = opts.key ?? "db";
244
- const db = createDatabase(key, adapter, {
245
- perRequestTx: opts.perRequestTx,
246
- key,
247
- });
248
- return db.plugin;
249
- }
1
+ /**
2
+ * The contract between a SQL adapter and the framework.
3
+ *
4
+ * An adapter is anything that can produce a client, close it, run a
5
+ * transaction and answer a health check. That is deliberately small: the
6
+ * point is not to abstract SQL, it is to let a plugin hold a client it does
7
+ * not know how to open, and to let anyone *prove* their adapter behaves.
8
+ *
9
+ * ```ts
10
+ * sql(defineSqlAdapter<MyClient>({
11
+ * contract: 1,
12
+ * name: "my-driver",
13
+ * create: () => connect(),
14
+ * close: (db) => db.end(),
15
+ * transaction: (db, fn) => db.tx(fn),
16
+ * ping: async (db) => { await db.ping(); },
17
+ * }));
18
+ * ```
19
+ */
20
+
21
+ import { type GrimoirePlugin } from "@sigil-dev/grimoire";
22
+ import { createDatabase, type Database, type DatabasePlugin } from "./database.ts";
23
+ import {
24
+ workerContext,
25
+ type WorkerContext,
26
+ } from "@sigil-dev/grimoire";
27
+
28
+ export type { WorkerContext };
29
+ export { workerContext };
30
+
31
+ /**
32
+ * Bumped when the adapter interface changes incompatibly.
33
+ *
34
+ * The field exists so an old adapter against a new plugin fails loudly at
35
+ * construction rather than being silently mis-called. Without it, a
36
+ * signature change is a runtime surprise inside somebody's transaction,
37
+ * which is the worst place to find one.
38
+ */
39
+ export const SQL_CONTRACT_VERSION = 1 as const;
40
+
41
+ /**
42
+ * @typeParam Tx - what a route actually receives inside `transaction`.
43
+ *
44
+ * Defaults to `C`, and that default is right for a raw driver: Bun.SQL's
45
+ * transaction handle *is* a Bun.SQL. It is wrong for anything that wraps a
46
+ * driver, and those are the popular libraries. Drizzle is the case that
47
+ * forced this: its `tx` has no `$client` and no `batch`, so
48
+ * `fn: (tx: C) => ...` is a lie that only compiles because the author
49
+ * writes `as any` over it. Kysely has the same shape.
50
+ *
51
+ * So the type says what it means. An adapter whose transaction handle is
52
+ * genuinely the same type passes one argument; one that differs passes two
53
+ * and gets `locals.db` typed as the thing a route will hold.
54
+ */
55
+ export interface SqlAdapter<C, Tx = C> {
56
+ contract: typeof SQL_CONTRACT_VERSION;
57
+ /** Shown in errors and logs. */
58
+ name: string;
59
+ /**
60
+ * Open a client. Called once per worker process, so anything sized from
61
+ * `ctx.workers` here is sized for the whole deployment.
62
+ */
63
+ create(ctx: WorkerContext): C | Promise<C>;
64
+ /** Release the client. Called on shutdown. */
65
+ close(client: C): void | Promise<void>;
66
+ /**
67
+ * Run `fn` in a transaction: commit when it resolves, roll back when it
68
+ * throws, and rethrow that same error.
69
+ */
70
+ transaction<R>(client: C, fn: (tx: Tx) => Promise<R>): Promise<R>;
71
+ /**
72
+ * Prove the client is usable. Called at startup so an unreachable
73
+ * database fails the deploy rather than the first request.
74
+ */
75
+ ping(client: C): Promise<void>;
76
+
77
+ /**
78
+ * Optional features this driver supports, checked before use rather
79
+ * than discovered when a query fails.
80
+ *
81
+ * Optional on the adapter and so part of contract 1: an adapter written
82
+ * before this field existed is still valid, and still works. The
83
+ * framework treats an absent `capabilities` as "supports nothing",
84
+ * which is the safe direction — the alternative is a plugin calling
85
+ * `setLocal` on a driver that would have ignored it.
86
+ */
87
+ capabilities?: SqlCapabilities<C, Tx>;
88
+ }
89
+
90
+ /**
91
+ * Driver features a plugin can ask for.
92
+ *
93
+ * Every one of these is about the *session* rather than a query, which is
94
+ * why they are worth declaring instead of assuming: on a pooled connection
95
+ * they either do not work or they leak to the next borrower.
96
+ */
97
+ export interface SqlCapabilities<C, Tx> {
98
+ /**
99
+ * `SET LOCAL` inside a transaction — Postgres row-level security,
100
+ * `app.user_id`, that sort of thing.
101
+ *
102
+ * Only meaningful inside a transaction: outside one it would be a
103
+ * plain `SET` on a pooled connection, and the next borrower inherits
104
+ * it. So this is only safe when the caller uses `tx()`, and the
105
+ * framework cannot check that for you.
106
+ */
107
+ setLocal?(tx: Tx, key: string, value: string): Promise<void>;
108
+
109
+ /** Subscribe to `LISTEN`/`NOTIFY`. Returns an unsubscribe function. */
110
+ listen?(client: C, channel: string, cb: (payload: string) => void): Promise<() => void>;
111
+
112
+ /** Called after every query with its text and duration. */
113
+ instrument?(client: C, onQuery: (q: { sql: string; ms: number }) => void): void;
114
+
115
+ /**
116
+ * Run a parameterised query and return rows.
117
+ *
118
+ * This is what backs `db.sql` — the lazy, composable template tag — so
119
+ * it is only for adapters whose driver really binds parameters. A
120
+ * driver's `execute` is not enough: Drizzle's ignores the params array
121
+ * and inlines `?` literally, which would turn every fragment
122
+ * composition into a silent injection. An adapter without this does not
123
+ * get `db.sql` at all, rather than a version that looks like it works.
124
+ *
125
+ * `sql` uses `$1` placeholders, which only postgres reads. `strings` is
126
+ * the same query as template parts, one longer than `values`: an adapter
127
+ * whose driver has a tagged template should pass it that, so the driver
128
+ * picks its own placeholders and MySQL gets `?`.
129
+ */
130
+ query?(
131
+ target: C | Tx,
132
+ sql: string,
133
+ values: readonly unknown[],
134
+ strings: readonly string[],
135
+ ): Promise<unknown[]>;
136
+
137
+ /**
138
+ * Run `fn` in a savepoint inside the transaction `tx`: roll back to it
139
+ * when `fn` throws, and rethrow.
140
+ *
141
+ * This is what `db.transaction()` does when a transaction is already in
142
+ * scope — under `perRequestTx`, that is every transaction a route opens.
143
+ * Without it the inner call joins the outer transaction instead. What it
144
+ * must never do is open a second transaction on another connection: that
145
+ * one commits even when the request rolls back, and it deadlocks the
146
+ * moment it touches a row the request already wrote.
147
+ */
148
+ savepoint?<R>(tx: Tx, fn: (tx: Tx) => Promise<R>): Promise<R>;
149
+
150
+ /**
151
+ * Build a driver helper on the client that is about to run the query:
152
+ * `db.sql(ids)` becomes `client(ids)`, `db.sql.array(xs, "text")` becomes
153
+ * `client.array(xs, "text")`. `method` is undefined for the first form.
154
+ *
155
+ * Without this, `db.sql(...)` and `db.sql.array(...)` throw when called,
156
+ * rather than binding an object the driver does not understand.
157
+ */
158
+ helper?(target: C | Tx, method: string | undefined, args: readonly unknown[]): unknown;
159
+ }
160
+
161
+ /**
162
+ * Identity function, so an adapter literal keeps its inferred type.
163
+ *
164
+ * Both parameters infer from the object, so `Tx` is picked up from a
165
+ * `transaction` that annotates it and left as `C` otherwise.
166
+ */
167
+ export function defineSqlAdapter<C, Tx = C>(
168
+ adapter: SqlAdapter<C, Tx>,
169
+ ): SqlAdapter<C, Tx> {
170
+ return adapter;
171
+ }
172
+
173
+ /**
174
+ * The transaction handle type of an adapter, for a caller that needs to
175
+ * name it — a route's `locals.db`, or a test hook.
176
+ *
177
+ * `SqlAdapter<C>` alone gives `C` for `Tx` unless the adapter's
178
+ * `transaction` was written with the handle annotated. A bare
179
+ * `db.transaction(fn)` does not re-infer it, because the parameter is
180
+ * contravariant and TypeScript will not solve for it from that position.
181
+ * That is a property of the compiler, not of this package, and it is why a
182
+ * Drizzle adapter annotates the parameter explicitly:
183
+ *
184
+ * ```ts
185
+ * transaction: <R>(db: DrizzleDb, fn: (tx: DrizzleTx) => Promise<R>) =>
186
+ * db.transaction(fn)
187
+ * ```
188
+ */
189
+ export type TxOf<A> = A extends SqlAdapter<infer _C, infer T> ? T : never;
190
+
191
+ /** The client type of an adapter. */
192
+ export type ClientOf<A> = A extends SqlAdapter<infer C, infer _T> ? C : never;
193
+
194
+ export interface SqlPluginOptions<Tx> {
195
+ /**
196
+ * Wrap each request in a transaction.
197
+ *
198
+ * Every query made through `locals.db` during the request — the tagged
199
+ * template, `locals.db.sql`, `unsafe()`, a Drizzle builder — runs in
200
+ * that transaction and rolls back with it. Costs a BEGIN/COMMIT per
201
+ * request and holds a connection for its duration, so each worker's
202
+ * pool must be larger than the requests it serves at once.
203
+ */
204
+ perRequestTx?: boolean;
205
+ /** The key `locals` receives. Defaults to "db". */
206
+ key?: string;
207
+ }
208
+
209
+ /**
210
+ * The shape of `locals` this plugin contributes.
211
+ *
212
+ * `Tx` and not `C`: when `perRequestTx` is on, a route holds the
213
+ * transaction handle, and a library that wraps a driver hands out a
214
+ * different type inside the transaction than outside it. Typing
215
+ * `locals.db` as `C` would be the same lie `as any` was hiding, one level
216
+ * up where nothing would flag it.
217
+ */
218
+ export interface SqlLocals<Tx> {
219
+ [key: string]: Tx;
220
+ }
221
+
222
+ /**
223
+ * Publish an adapter's client on `locals`, and close it on shutdown.
224
+ *
225
+ * The client opens once per worker at startup and is shared by every
226
+ * request on that worker, which is what a connection pool is for. Per-request
227
+ * work reaches it as `locals.db`, with nothing imported from
228
+ * sigil.config.ts.
229
+ */
230
+ export function sql<C, Tx = C>(
231
+ adapter: SqlAdapter<C, Tx>,
232
+ opts: SqlPluginOptions<Tx> = {},
233
+ ): DatabasePlugin<C, Tx> {
234
+ // Implemented in terms of createDatabase rather than beside it. The two
235
+ // used to be separate bodies, which meant the locals-based plugin and the
236
+ // Database object could disagree about when the client opens, who closes
237
+ // it, and what a transaction is — and they did, at least once, when one
238
+ // gained a shutdown path the other did not.
239
+ //
240
+ // Named after its key, so `database("db")` finds the one `adapter(url)`
241
+ // registered, and a second plugin on another key is a second database
242
+ // rather than a second copy of the first.
243
+ const key = opts.key ?? "db";
244
+ const db = createDatabase(key, adapter, {
245
+ perRequestTx: opts.perRequestTx,
246
+ key,
247
+ });
248
+ return Object.assign(db.plugin, { key, database: db as Database<C, Tx> | undefined });
249
+ }