@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/src/index.ts CHANGED
@@ -1,66 +1,67 @@
1
- /**
2
- * @sigil-dev/plugin-sql
3
- *
4
- * A contract for SQL adapters, a conformance kit that proves one behaves,
5
- * and an official adapter for `Bun.SQL`.
6
- *
7
- * ```ts
8
- * import { sql } from "@sigil-dev/plugin-sql";
9
- * import { bunSqlAdapter } from "@sigil-dev/plugin-sql/bun";
10
- *
11
- * // sigil.config.ts
12
- * export default { plugins: [sql(bunSqlAdapter(process.env.DATABASE_URL!))] };
13
- * ```
14
- *
15
- * ```ts
16
- * // a route
17
- * const rows = await locals.db`select id, name from users`;
18
- *
19
- * // any other server module: a websocket handler, a timer, hooks.server.ts
20
- * import { database } from "@sigil-dev/plugin-sql";
21
- * const rows = await database().sql`select id, name from users`;
22
- * ```
23
- *
24
- * This package previously exported `bunSqlite` / `bunPg` / `bunMysql` and a
25
- * `SqlExecutor` interface with `query(sql, params)`. That layer existed to
26
- * bridge `Bun.sql`'s positional-parameter API, and every bug in it came
27
- * from guessing a dialect from a string: `sqlite://app.db` became the
28
- * absolute path `//app.db`, postgres and mysql were assumed to share a
29
- * placeholder style when they are opposites, and `toISOString()` timestamps
30
- * were rejected by MySQL. `Bun.SQL` infers the dialect correctly and
31
- * serialises timestamps itself, so the guessing has nothing left to do.
32
- *
33
- * @module
34
- */
35
-
36
- export {
37
- defineSqlAdapter,
38
- sql,
39
- SQL_CONTRACT_VERSION,
40
- workerContext,
41
- type ClientOf,
42
- type SqlAdapter,
43
- type SqlCapabilities,
44
- type SqlPluginOptions,
45
- type TxOf,
46
- type WorkerContext,
47
- } from "./contract.ts";
48
-
49
- export {
50
- createDatabase,
51
- database,
52
- hasDatabase,
53
- type CreateDatabaseOptions,
54
- type Database,
55
- type SqlHandle,
56
- type SqlTag,
57
- } from "./database.ts";
58
- export {
59
- fragmentParts,
60
- isFragment,
61
- isHelper,
62
- SQL_FRAGMENT,
63
- SQL_HELPER,
64
- type Fragment,
65
- type SqlHelper,
66
- } from "./fragment.ts";
1
+ /**
2
+ * @sigil-dev/plugin-sql
3
+ *
4
+ * A contract for SQL adapters, a conformance kit that proves one behaves,
5
+ * and an official adapter for `Bun.SQL`.
6
+ *
7
+ * ```ts
8
+ * import { sql } from "@sigil-dev/plugin-sql";
9
+ * import { bunSqlAdapter } from "@sigil-dev/plugin-sql/bun";
10
+ *
11
+ * // sigil.config.ts
12
+ * export default { plugins: [sql(bunSqlAdapter(process.env.DATABASE_URL!))] };
13
+ * ```
14
+ *
15
+ * ```ts
16
+ * // a route
17
+ * const rows = await locals.db`select id, name from users`;
18
+ *
19
+ * // any other server module: a websocket handler, a timer, hooks.server.ts
20
+ * import { database } from "@sigil-dev/plugin-sql";
21
+ * const rows = await database().sql`select id, name from users`;
22
+ * ```
23
+ *
24
+ * This package previously exported `bunSqlite` / `bunPg` / `bunMysql` and a
25
+ * `SqlExecutor` interface with `query(sql, params)`. That layer existed to
26
+ * bridge `Bun.sql`'s positional-parameter API, and every bug in it came
27
+ * from guessing a dialect from a string: `sqlite://app.db` became the
28
+ * absolute path `//app.db`, postgres and mysql were assumed to share a
29
+ * placeholder style when they are opposites, and `toISOString()` timestamps
30
+ * were rejected by MySQL. `Bun.SQL` infers the dialect correctly and
31
+ * serialises timestamps itself, so the guessing has nothing left to do.
32
+ *
33
+ * @module
34
+ */
35
+
36
+ export {
37
+ defineSqlAdapter,
38
+ sql,
39
+ SQL_CONTRACT_VERSION,
40
+ workerContext,
41
+ type ClientOf,
42
+ type SqlAdapter,
43
+ type SqlCapabilities,
44
+ type SqlPluginOptions,
45
+ type TxOf,
46
+ type WorkerContext,
47
+ } from "./contract.ts";
48
+
49
+ export {
50
+ createDatabase,
51
+ database,
52
+ hasDatabase,
53
+ type CreateDatabaseOptions,
54
+ type Database,
55
+ type DatabasePlugin,
56
+ type SqlHandle,
57
+ type SqlTag,
58
+ } from "./database.ts";
59
+ export {
60
+ fragmentParts,
61
+ isFragment,
62
+ isHelper,
63
+ SQL_FRAGMENT,
64
+ SQL_HELPER,
65
+ type Fragment,
66
+ type SqlHelper,
67
+ } from "./fragment.ts";
package/src/testing.ts CHANGED
@@ -1,148 +1,148 @@
1
- /**
2
- * A conformance kit for SQL adapters.
3
- *
4
- * The type catches shape mistakes. It cannot catch a transaction that
5
- * silently does not roll back, which is the failure that loses data and
6
- * passes every type check. So an adapter author runs this suite and can say
7
- * their adapter behaves, rather than that it type-checks.
8
- *
9
- * ```ts
10
- * runAdapterConformance(bunSqlAdapter(url), {
11
- * exec: (db, q) => db.unsafe(q),
12
- * count: async (db, t) => Number((await db.unsafe(`select count(*) as n from ${t}`))[0].n),
13
- * });
14
- * ```
15
- *
16
- * Point CI at a Postgres (and MySQL) service and the same file checks every
17
- * dialect. It is `bun:test`-only, which suits a Bun-first framework.
18
- */
19
-
20
- import { afterAll, beforeAll, beforeEach, describe, expect, test } from "bun:test";
21
- import type { SqlAdapter, WorkerContext } from "./contract.ts";
22
-
23
- /**
24
- * Hooks the kit uses to drive an adapter.
25
- *
26
- * The client parameter is `C | Tx` because the kit genuinely calls them
27
- * with both: `exec` runs inside `adapter.transaction` to prove rollback
28
- * works, and outside it to set up. A hook typed for `C` alone has to
29
- * narrow at every call site, and the natural way to do that — cast — is
30
- * how a kit stops testing what it claims to.
31
- *
32
- * A library whose transaction handle is genuinely the same type sees no
33
- * difference, because `Tx` defaults to `C` and the union collapses.
34
- */
35
- export interface ConformanceHooks<C, Tx = C> {
36
- exec(client: C | Tx, sql: string): Promise<void>;
37
- count(client: C | Tx, table: string): Promise<number>;
38
- }
39
-
40
- export interface ConformanceOptions {
41
- ctx?: WorkerContext;
42
- /**
43
- * Whether an in-transaction read is invisible to a read outside it.
44
- *
45
- * False for single-connection drivers. SQLite through `Bun.SQL` is one
46
- * connection, so it genuinely does not isolate — measured, in tx: 2
47
- * outside: 2, against postgres: in tx 2, outside 1. Asserting isolation
48
- * for a driver that has none would be asserting a lie, so the test is
49
- * skipped and the flag records why.
50
- */
51
- isolation?: boolean;
52
- }
53
-
54
- /** Plain SQL, so the same statements run on postgres, mysql and sqlite. */
55
- const T = "sigil_conformance";
56
-
57
- export function runAdapterConformance<C, Tx = C>(
58
- adapter: SqlAdapter<C, Tx>,
59
- hooks: ConformanceHooks<C, Tx>,
60
- {
61
- ctx = { workerId: 0, workers: 1, dev: false },
62
- isolation = true,
63
- }: ConformanceOptions = {},
64
- ): void {
65
- describe(`sql adapter: ${adapter.name}`, () => {
66
- let db: C;
67
-
68
- beforeAll(async () => {
69
- db = await adapter.create(ctx);
70
- await hooks.exec(db, `create table if not exists ${T} (id integer)`);
71
- });
72
-
73
- beforeEach(async () => {
74
- await hooks.exec(db, `delete from ${T}`);
75
- });
76
-
77
- afterAll(async () => {
78
- // Drop before close: a client that cannot take statements may still
79
- // hold a table, and a leaked conformance table in a shared CI
80
- // database makes the next run's counts wrong.
81
- try {
82
- await hooks.exec(db, `drop table if exists ${T}`);
83
- } catch {
84
- // the client may already be unusable; close regardless
85
- }
86
- await adapter.close(db);
87
- });
88
-
89
- test("declares the contract this build expects", () => {
90
- expect(adapter.contract).toBe(1);
91
- });
92
-
93
- test("create received the worker context it was promised", () => {
94
- // An adapter that ignores ctx.workers opens a full-size pool per
95
- // worker, and nothing else here would notice.
96
- expect(ctx.workers).toBeGreaterThanOrEqual(1);
97
- });
98
-
99
- test("ping resolves", async () => {
100
- await adapter.ping(db);
101
- });
102
-
103
- test("transaction returns the callback's result", async () => {
104
- expect(await adapter.transaction(db, async () => 42)).toBe(42);
105
- });
106
-
107
- test("transaction commits on success", async () => {
108
- await adapter.transaction(db, (tx) =>
109
- hooks.exec(tx, `insert into ${T} (id) values (1)`),
110
- );
111
- expect(await hooks.count(db, T)).toBe(1);
112
- });
113
-
114
- test("transaction rolls back and rethrows the same error", async () => {
115
- const boom = new Error("boom");
116
- const thrown = await adapter
117
- .transaction(db, async (tx) => {
118
- await hooks.exec(tx, `insert into ${T} (id) values (1)`);
119
- throw boom;
120
- })
121
- .catch((e: unknown) => e);
122
- // Identity, not just "it threw": an adapter that wrapped the
123
- // error would hide the real cause behind its own message.
124
- expect(thrown).toBe(boom);
125
- expect(await hooks.count(db, T)).toBe(0);
126
- });
127
-
128
- test.if(isolation)(
129
- "uncommitted writes are invisible outside the transaction",
130
- async () => {
131
- await adapter.transaction(db, async (tx) => {
132
- await hooks.exec(tx, `insert into ${T} (id) values (1)`);
133
- expect(await hooks.count(tx, T)).toBe(1);
134
- // The line that fails for a single-connection driver, which
135
- // is why the whole test is behind the flag.
136
- expect(await hooks.count(db, T)).toBe(0);
137
- });
138
- },
139
- );
140
-
141
- test("close releases the client", async () => {
142
- // A separate client so this cannot close the shared one the other
143
- // tests use.
144
- const spare = await adapter.create(ctx);
145
- await adapter.close(spare);
146
- });
147
- });
148
- }
1
+ /**
2
+ * A conformance kit for SQL adapters.
3
+ *
4
+ * The type catches shape mistakes. It cannot catch a transaction that
5
+ * silently does not roll back, which is the failure that loses data and
6
+ * passes every type check. So an adapter author runs this suite and can say
7
+ * their adapter behaves, rather than that it type-checks.
8
+ *
9
+ * ```ts
10
+ * runAdapterConformance(bunSqlAdapter(url), {
11
+ * exec: (db, q) => db.unsafe(q),
12
+ * count: async (db, t) => Number((await db.unsafe(`select count(*) as n from ${t}`))[0].n),
13
+ * });
14
+ * ```
15
+ *
16
+ * Point CI at a Postgres (and MySQL) service and the same file checks every
17
+ * dialect. It is `bun:test`-only, which suits a Bun-first framework.
18
+ */
19
+
20
+ import { afterAll, beforeAll, beforeEach, describe, expect, test } from "bun:test";
21
+ import type { SqlAdapter, WorkerContext } from "./contract.ts";
22
+
23
+ /**
24
+ * Hooks the kit uses to drive an adapter.
25
+ *
26
+ * The client parameter is `C | Tx` because the kit genuinely calls them
27
+ * with both: `exec` runs inside `adapter.transaction` to prove rollback
28
+ * works, and outside it to set up. A hook typed for `C` alone has to
29
+ * narrow at every call site, and the natural way to do that — cast — is
30
+ * how a kit stops testing what it claims to.
31
+ *
32
+ * A library whose transaction handle is genuinely the same type sees no
33
+ * difference, because `Tx` defaults to `C` and the union collapses.
34
+ */
35
+ export interface ConformanceHooks<C, Tx = C> {
36
+ exec(client: C | Tx, sql: string): Promise<void>;
37
+ count(client: C | Tx, table: string): Promise<number>;
38
+ }
39
+
40
+ export interface ConformanceOptions {
41
+ ctx?: WorkerContext;
42
+ /**
43
+ * Whether an in-transaction read is invisible to a read outside it.
44
+ *
45
+ * False for single-connection drivers. SQLite through `Bun.SQL` is one
46
+ * connection, so it genuinely does not isolate — measured, in tx: 2
47
+ * outside: 2, against postgres: in tx 2, outside 1. Asserting isolation
48
+ * for a driver that has none would be asserting a lie, so the test is
49
+ * skipped and the flag records why.
50
+ */
51
+ isolation?: boolean;
52
+ }
53
+
54
+ /** Plain SQL, so the same statements run on postgres, mysql and sqlite. */
55
+ const T = "sigil_conformance";
56
+
57
+ export function runAdapterConformance<C, Tx = C>(
58
+ adapter: SqlAdapter<C, Tx>,
59
+ hooks: ConformanceHooks<C, Tx>,
60
+ {
61
+ ctx = { workerId: 0, workers: 1, dev: false },
62
+ isolation = true,
63
+ }: ConformanceOptions = {},
64
+ ): void {
65
+ describe(`sql adapter: ${adapter.name}`, () => {
66
+ let db: C;
67
+
68
+ beforeAll(async () => {
69
+ db = await adapter.create(ctx);
70
+ await hooks.exec(db, `create table if not exists ${T} (id integer)`);
71
+ });
72
+
73
+ beforeEach(async () => {
74
+ await hooks.exec(db, `delete from ${T}`);
75
+ });
76
+
77
+ afterAll(async () => {
78
+ // Drop before close: a client that cannot take statements may still
79
+ // hold a table, and a leaked conformance table in a shared CI
80
+ // database makes the next run's counts wrong.
81
+ try {
82
+ await hooks.exec(db, `drop table if exists ${T}`);
83
+ } catch {
84
+ // the client may already be unusable; close regardless
85
+ }
86
+ await adapter.close(db);
87
+ });
88
+
89
+ test("declares the contract this build expects", () => {
90
+ expect(adapter.contract).toBe(1);
91
+ });
92
+
93
+ test("create received the worker context it was promised", () => {
94
+ // An adapter that ignores ctx.workers opens a full-size pool per
95
+ // worker, and nothing else here would notice.
96
+ expect(ctx.workers).toBeGreaterThanOrEqual(1);
97
+ });
98
+
99
+ test("ping resolves", async () => {
100
+ await adapter.ping(db);
101
+ });
102
+
103
+ test("transaction returns the callback's result", async () => {
104
+ expect(await adapter.transaction(db, async () => 42)).toBe(42);
105
+ });
106
+
107
+ test("transaction commits on success", async () => {
108
+ await adapter.transaction(db, (tx) =>
109
+ hooks.exec(tx, `insert into ${T} (id) values (1)`),
110
+ );
111
+ expect(await hooks.count(db, T)).toBe(1);
112
+ });
113
+
114
+ test("transaction rolls back and rethrows the same error", async () => {
115
+ const boom = new Error("boom");
116
+ const thrown = await adapter
117
+ .transaction(db, async (tx) => {
118
+ await hooks.exec(tx, `insert into ${T} (id) values (1)`);
119
+ throw boom;
120
+ })
121
+ .catch((e: unknown) => e);
122
+ // Identity, not just "it threw": an adapter that wrapped the
123
+ // error would hide the real cause behind its own message.
124
+ expect(thrown).toBe(boom);
125
+ expect(await hooks.count(db, T)).toBe(0);
126
+ });
127
+
128
+ test.if(isolation)(
129
+ "uncommitted writes are invisible outside the transaction",
130
+ async () => {
131
+ await adapter.transaction(db, async (tx) => {
132
+ await hooks.exec(tx, `insert into ${T} (id) values (1)`);
133
+ expect(await hooks.count(tx, T)).toBe(1);
134
+ // The line that fails for a single-connection driver, which
135
+ // is why the whole test is behind the flag.
136
+ expect(await hooks.count(db, T)).toBe(0);
137
+ });
138
+ },
139
+ );
140
+
141
+ test("close releases the client", async () => {
142
+ // A separate client so this cannot close the shared one the other
143
+ // tests use.
144
+ const spare = await adapter.create(ctx);
145
+ await adapter.close(spare);
146
+ });
147
+ });
148
+ }