@statewalker/db-sqlite 0.0.0-stage → 0.1.0

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Mikhail Kotelnikov
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,80 @@
1
- # Temporary Holding Version
1
+ # @statewalker/db-sqlite
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ ## What it is
4
+
5
+ Transactions for SQLite databases behind `Db` from `@statewalker/db-api`:
6
+ `inTransaction(db, cb)` runs `cb` so that every statement issued through its `tx` handle commits
7
+ together or not at all. It also holds `newSerialisedSqliteDb`, the wrapper every SQLite driver
8
+ (`db-sqlite-node`, `db-sqlite-browser`, `db-sqlite-do`) builds its `Db` with.
9
+
10
+ ## Why it exists
11
+
12
+ `Db` has no transaction method, and SQLite runtimes disagree on how to open one: Node.js and the
13
+ browser accept `BEGIN IMMEDIATE`, while a Durable Object rejects `BEGIN` ("not authorized") and
14
+ only offers `storage.transaction(async fn)`. Keeping transactions here leaves `Db` unchanged for
15
+ every engine, and gives SQLite callers one call that works in all three runtimes.
16
+
17
+ ## How to use
18
+
19
+ ```sh
20
+ pnpm add @statewalker/db-sqlite
21
+ ```
22
+
23
+ | Import | Gives | Environment |
24
+ | --- | --- | --- |
25
+ | `@statewalker/db-sqlite` | `inTransaction`, `newSerialisedSqliteDb`, `SQLITE_TRANSACTION`; types `SqliteEngine`, `SqliteTransactionHook` | any |
26
+
27
+ `inTransaction(db, cb)` returns what `cb` returns. If `cb` throws, everything it wrote is rolled
28
+ back and the same error is rethrown. While it runs, other calls on `db` wait for it.
29
+
30
+ ## Examples
31
+
32
+ ```ts
33
+ import { inTransaction } from "@statewalker/db-sqlite";
34
+ import { newNodeSqliteDb } from "@statewalker/db-sqlite-node";
35
+
36
+ const db = await newNodeSqliteDb({ path: "./data.db" });
37
+ await db.exec(`
38
+ CREATE TABLE IF NOT EXISTS docs (id INTEGER PRIMARY KEY, body TEXT);
39
+ CREATE TABLE IF NOT EXISTS log (doc_id INTEGER);
40
+ `);
41
+ const id = await inTransaction(db, async (tx) => {
42
+ const [row] = await tx.query<{ id: number }>("INSERT INTO docs (body) VALUES (?) RETURNING id", ["x"]);
43
+ await tx.query("INSERT INTO log (doc_id) VALUES (?)", [row?.id]);
44
+ return row?.id;
45
+ });
46
+ await db.close();
47
+ ```
48
+
49
+ ## Internals
50
+
51
+ - **The hook travels on the Db object.** `newSerialisedSqliteDb` stores the transaction function
52
+ under `Symbol.for("@statewalker/db-sqlite:transaction")`; `inTransaction` looks it up. A Db
53
+ without it rejects with
54
+ `inTransaction: this Db has no SQLite transaction hook. ...`. That happens for a DuckDB or PGlite
55
+ Db, for **an object that wraps a SQLite Db** (copying `query`/`exec`/`close` drops the hook —
56
+ pass the driver's Db, or a spread copy `{ ...db }`, which keeps symbol keys), and for the `tx`
57
+ handle itself: **nested transactions are not supported**.
58
+ - **One call at a time.** Every `query`, `exec`, `close` and transaction goes through one queue,
59
+ in call order. A plain `db.exec` issued while another flow's transaction is open waits; it never
60
+ joins that transaction, so a rollback cannot take it down. `close` waits for a running
61
+ transaction.
62
+ - **The `tx` handle expires.** After the callback settles, `tx.query` rejects with
63
+ `db-sqlite: the transaction is finished; use the outer Db`; `tx.close` always rejects, with
64
+ `db-sqlite: close the outer Db, not the transaction handle`.
65
+ - **Inside `cb`, use only `tx`.** Calling the outer `db` (`db.query`, or `inTransaction(db, ...)`)
66
+ from inside `cb` queues behind the very transaction it belongs to, so the call never resolves
67
+ and no error is raised. Nothing detects this at runtime.
68
+ - **Callback rules.** No external I/O inside `cb` (the queue is held for its whole duration), and
69
+ `cb` must be idempotent: a Durable Object can run it more than once.
70
+ - **Row counts.** There is no "rows changed" result: use `SELECT changes()` or `RETURNING` inside
71
+ the transaction. Id lists longer than 100 go in one JSON parameter through `json_each(?)` —
72
+ Durable Objects reject more than 100 bound parameters with `too many SQL variables`.
73
+ - **`SqliteEngine` is the driver seam.** `all` must run exactly one statement and return BLOBs as
74
+ `Uint8Array`; `exec` must run every statement of the string; `transaction` is given only by
75
+ engines that cannot run `BEGIN IMMEDIATE`.
76
+ - **Dependencies:** `@statewalker/db-api` (types only).
77
+
78
+ ## License
79
+
80
+ MIT
@@ -0,0 +1,34 @@
1
+ import { Db } from "@statewalker/db-api";
2
+ //#region src/serialised-sqlite-db.d.ts
3
+ /**
4
+ * The synchronous engine a SQLite driver wraps. `all` returns rows (BLOBs as Uint8Array) and must
5
+ * run exactly one statement; `exec` runs every statement of a string. `transaction`, when present,
6
+ * replaces `BEGIN IMMEDIATE`/`COMMIT`/`ROLLBACK` (Durable Objects forbid them in SQL).
7
+ */
8
+ type SqliteEngine = {
9
+ all(sql: string, params: unknown[]): Record<string, unknown>[];
10
+ exec(sql: string): void;
11
+ close(): void;
12
+ transaction?<T>(fn: () => Promise<T>): Promise<T>;
13
+ };
14
+ /**
15
+ * Wrap an engine as a `Db` whose calls run one at a time, in call order, and which carries the
16
+ * `inTransaction` hook. The `tx` handed to a transaction callback bypasses the queue, has no hook
17
+ * (so nesting is rejected) and rejects once its transaction has finished.
18
+ */
19
+ export declare function newSerialisedSqliteDb(engine: SqliteEngine): Db;
20
+ //#endregion
21
+ //#region src/sqlite-transaction.d.ts
22
+ /** Key under which a SQLite Db carries its transaction hook. Shared across bundles via Symbol.for. */
23
+ export declare const SQLITE_TRANSACTION: unique symbol;
24
+ /** Runs `cb` inside one transaction of the Db that carries it. */
25
+ type SqliteTransactionHook = <T>(cb: (tx: Db) => Promise<T>) => Promise<T>;
26
+ /**
27
+ * Run `cb` in one SQLite transaction: every statement issued through `tx` commits together, or
28
+ * none does if `cb` throws. Other calls on `db` wait until the transaction ends. `cb` must not do
29
+ * external I/O and must be idempotent: a Durable Object may run it more than once.
30
+ */
31
+ export declare function inTransaction<T>(db: Db, cb: (tx: Db) => Promise<T>): Promise<T>;
32
+ //#endregion
33
+ export type { SqliteEngine, SqliteTransactionHook };
34
+ //# sourceMappingURL=index.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.mts","names":[],"sources":["../src/serialised-sqlite-db.ts","../src/sqlite-transaction.ts"],"mappings":";;;;;;;KAQY;EACV,IAAI,aAAa,oBAAoB;EACrC,KAAK;EACL;EACA,aAAa,GAAG,UAAU,QAAQ,KAAK,QAAQ;;;;;;;wBAiBjC,sBAAsB,QAAQ,eAAe;;;;qBC1BhD;;KAGD,yBAAyB,GAAG,KAAK,IAAI,OAAO,QAAQ,OAAO,QAAQ;;;;;;wBAY/D,cAAc,GAAG,IAAI,IAAI,KAAK,IAAI,OAAO,QAAQ,KAAK,QAAQ"}
package/dist/index.mjs ADDED
@@ -0,0 +1,94 @@
1
+ //#region src/sqlite-transaction.ts
2
+ /** Key under which a SQLite Db carries its transaction hook. Shared across bundles via Symbol.for. */
3
+ const SQLITE_TRANSACTION = Symbol.for("@statewalker/db-sqlite:transaction");
4
+ const NO_HOOK = "inTransaction: this Db has no SQLite transaction hook. It is not a @statewalker/db-sqlite* Db, or it wraps one (a wrapper object loses the hook - pass the driver's Db itself), or it is the handle of a running transaction (nesting is not supported).";
5
+ /**
6
+ * Run `cb` in one SQLite transaction: every statement issued through `tx` commits together, or
7
+ * none does if `cb` throws. Other calls on `db` wait until the transaction ends. `cb` must not do
8
+ * external I/O and must be idempotent: a Durable Object may run it more than once.
9
+ */
10
+ function inTransaction(db, cb) {
11
+ const hook = db[SQLITE_TRANSACTION];
12
+ if (typeof hook !== "function") return Promise.reject(/* @__PURE__ */ new Error(NO_HOOK));
13
+ return hook(cb);
14
+ }
15
+ //#endregion
16
+ //#region src/serialised-sqlite-db.ts
17
+ function newLock() {
18
+ let tail = Promise.resolve();
19
+ return (fn) => {
20
+ const run = tail.then(fn);
21
+ tail = run.catch(() => void 0);
22
+ return run;
23
+ };
24
+ }
25
+ /**
26
+ * Wrap an engine as a `Db` whose calls run one at a time, in call order, and which carries the
27
+ * `inTransaction` hook. The `tx` handed to a transaction callback bypasses the queue, has no hook
28
+ * (so nesting is rejected) and rejects once its transaction has finished.
29
+ */
30
+ function newSerialisedSqliteDb(engine) {
31
+ const lock = newLock();
32
+ let closed = false;
33
+ const live = () => {
34
+ if (closed) throw new Error("db-sqlite: the database is closed");
35
+ };
36
+ const runTransaction = engine.transaction?.bind(engine) ?? (async (fn) => {
37
+ engine.exec("BEGIN IMMEDIATE");
38
+ try {
39
+ const result = await fn();
40
+ engine.exec("COMMIT");
41
+ return result;
42
+ } catch (error) {
43
+ try {
44
+ engine.exec("ROLLBACK");
45
+ } catch {}
46
+ throw error;
47
+ }
48
+ });
49
+ const transaction = (cb) => lock(async () => {
50
+ live();
51
+ let finished = false;
52
+ const open = () => {
53
+ if (finished) throw new Error("db-sqlite: the transaction is finished; use the outer Db");
54
+ };
55
+ const tx = {
56
+ async query(sql, params = []) {
57
+ open();
58
+ return engine.all(sql, params);
59
+ },
60
+ async exec(sql) {
61
+ open();
62
+ engine.exec(sql);
63
+ },
64
+ async close() {
65
+ throw new Error("db-sqlite: close the outer Db, not the transaction handle");
66
+ }
67
+ };
68
+ try {
69
+ return await runTransaction(() => cb(tx));
70
+ } finally {
71
+ finished = true;
72
+ }
73
+ });
74
+ return {
75
+ query: (sql, params = []) => lock(async () => {
76
+ live();
77
+ return engine.all(sql, params);
78
+ }),
79
+ exec: (sql) => lock(async () => {
80
+ live();
81
+ engine.exec(sql);
82
+ }),
83
+ close: () => lock(async () => {
84
+ if (closed) return;
85
+ closed = true;
86
+ engine.close();
87
+ }),
88
+ [SQLITE_TRANSACTION]: transaction
89
+ };
90
+ }
91
+ //#endregion
92
+ export { SQLITE_TRANSACTION, inTransaction, newSerialisedSqliteDb };
93
+
94
+ //# sourceMappingURL=index.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.mjs","names":[],"sources":["../src/sqlite-transaction.ts","../src/serialised-sqlite-db.ts"],"sourcesContent":["import type { Db } from \"@statewalker/db-api\";\n\n/** Key under which a SQLite Db carries its transaction hook. Shared across bundles via Symbol.for. */\nexport const SQLITE_TRANSACTION: unique symbol = Symbol.for(\"@statewalker/db-sqlite:transaction\");\n\n/** Runs `cb` inside one transaction of the Db that carries it. */\nexport type SqliteTransactionHook = <T>(cb: (tx: Db) => Promise<T>) => Promise<T>;\n\nconst NO_HOOK =\n \"inTransaction: this Db has no SQLite transaction hook. It is not a @statewalker/db-sqlite* Db, \" +\n \"or it wraps one (a wrapper object loses the hook - pass the driver's Db itself), \" +\n \"or it is the handle of a running transaction (nesting is not supported).\";\n\n/**\n * Run `cb` in one SQLite transaction: every statement issued through `tx` commits together, or\n * none does if `cb` throws. Other calls on `db` wait until the transaction ends. `cb` must not do\n * external I/O and must be idempotent: a Durable Object may run it more than once.\n */\nexport function inTransaction<T>(db: Db, cb: (tx: Db) => Promise<T>): Promise<T> {\n const hook = (db as { [SQLITE_TRANSACTION]?: SqliteTransactionHook })[SQLITE_TRANSACTION];\n if (typeof hook !== \"function\") return Promise.reject(new Error(NO_HOOK));\n return hook(cb);\n}\n","import type { Db, DbEntry } from \"@statewalker/db-api\";\nimport { SQLITE_TRANSACTION, type SqliteTransactionHook } from \"./sqlite-transaction.js\";\n\n/**\n * The synchronous engine a SQLite driver wraps. `all` returns rows (BLOBs as Uint8Array) and must\n * run exactly one statement; `exec` runs every statement of a string. `transaction`, when present,\n * replaces `BEGIN IMMEDIATE`/`COMMIT`/`ROLLBACK` (Durable Objects forbid them in SQL).\n */\nexport type SqliteEngine = {\n all(sql: string, params: unknown[]): Record<string, unknown>[];\n exec(sql: string): void;\n close(): void;\n transaction?<T>(fn: () => Promise<T>): Promise<T>;\n};\n\nfunction newLock() {\n let tail: Promise<unknown> = Promise.resolve();\n return <T>(fn: () => Promise<T>): Promise<T> => {\n const run = tail.then(fn);\n tail = run.catch(() => undefined);\n return run;\n };\n}\n\n/**\n * Wrap an engine as a `Db` whose calls run one at a time, in call order, and which carries the\n * `inTransaction` hook. The `tx` handed to a transaction callback bypasses the queue, has no hook\n * (so nesting is rejected) and rejects once its transaction has finished.\n */\nexport function newSerialisedSqliteDb(engine: SqliteEngine): Db {\n const lock = newLock();\n let closed = false;\n const live = () => {\n if (closed) throw new Error(\"db-sqlite: the database is closed\");\n };\n const runTransaction =\n engine.transaction?.bind(engine) ??\n (async <T>(fn: () => Promise<T>): Promise<T> => {\n engine.exec(\"BEGIN IMMEDIATE\");\n try {\n const result = await fn();\n engine.exec(\"COMMIT\");\n return result;\n } catch (error) {\n try {\n engine.exec(\"ROLLBACK\");\n } catch {\n // SQLite already ended the transaction itself (ON CONFLICT ROLLBACK, auto-rollback)\n }\n throw error;\n }\n });\n\n const transaction: SqliteTransactionHook = (cb) =>\n lock(async () => {\n live();\n let finished = false;\n const open = () => {\n if (finished) throw new Error(\"db-sqlite: the transaction is finished; use the outer Db\");\n };\n const tx: Db = {\n async query<T = DbEntry>(sql: string, params: unknown[] = []): Promise<T[]> {\n open();\n return engine.all(sql, params) as T[];\n },\n async exec(sql: string): Promise<void> {\n open();\n engine.exec(sql);\n },\n async close(): Promise<void> {\n throw new Error(\"db-sqlite: close the outer Db, not the transaction handle\");\n },\n };\n try {\n return await runTransaction(() => cb(tx));\n } finally {\n finished = true;\n }\n });\n\n return {\n query: <T = DbEntry>(sql: string, params: unknown[] = []) =>\n lock(async () => {\n live();\n return engine.all(sql, params) as T[];\n }),\n exec: (sql: string) =>\n lock(async () => {\n live();\n engine.exec(sql);\n }),\n close: () =>\n lock(async () => {\n if (closed) return;\n closed = true;\n engine.close();\n }),\n [SQLITE_TRANSACTION]: transaction,\n } as Db;\n}\n"],"mappings":";;AAGA,MAAa,qBAAoC,OAAO,IAAI,oCAAoC;AAKhG,MAAM,UACJ;;;;;;AASF,SAAgB,cAAiB,IAAQ,IAAwC;CAC/E,MAAM,OAAQ,GAAwD;CACtE,IAAI,OAAO,SAAS,YAAY,OAAO,QAAQ,uBAAO,IAAI,MAAM,OAAO,CAAC;CACxE,OAAO,KAAK,EAAE;AAChB;;;ACPA,SAAS,UAAU;CACjB,IAAI,OAAyB,QAAQ,QAAQ;CAC7C,QAAW,OAAqC;EAC9C,MAAM,MAAM,KAAK,KAAK,EAAE;EACxB,OAAO,IAAI,YAAY,KAAA,CAAS;EAChC,OAAO;CACT;AACF;;;;;;AAOA,SAAgB,sBAAsB,QAA0B;CAC9D,MAAM,OAAO,QAAQ;CACrB,IAAI,SAAS;CACb,MAAM,aAAa;EACjB,IAAI,QAAQ,MAAM,IAAI,MAAM,mCAAmC;CACjE;CACA,MAAM,iBACJ,OAAO,aAAa,KAAK,MAAM,MAC9B,OAAU,OAAqC;EAC9C,OAAO,KAAK,iBAAiB;EAC7B,IAAI;GACF,MAAM,SAAS,MAAM,GAAG;GACxB,OAAO,KAAK,QAAQ;GACpB,OAAO;EACT,SAAS,OAAO;GACd,IAAI;IACF,OAAO,KAAK,UAAU;GACxB,QAAQ,CAER;GACA,MAAM;EACR;CACF;CAEF,MAAM,eAAsC,OAC1C,KAAK,YAAY;EACf,KAAK;EACL,IAAI,WAAW;EACf,MAAM,aAAa;GACjB,IAAI,UAAU,MAAM,IAAI,MAAM,0DAA0D;EAC1F;EACA,MAAM,KAAS;GACb,MAAM,MAAmB,KAAa,SAAoB,CAAC,GAAiB;IAC1E,KAAK;IACL,OAAO,OAAO,IAAI,KAAK,MAAM;GAC/B;GACA,MAAM,KAAK,KAA4B;IACrC,KAAK;IACL,OAAO,KAAK,GAAG;GACjB;GACA,MAAM,QAAuB;IAC3B,MAAM,IAAI,MAAM,2DAA2D;GAC7E;EACF;EACA,IAAI;GACF,OAAO,MAAM,qBAAqB,GAAG,EAAE,CAAC;EAC1C,UAAU;GACR,WAAW;EACb;CACF,CAAC;CAEH,OAAO;EACL,QAAqB,KAAa,SAAoB,CAAC,MACrD,KAAK,YAAY;GACf,KAAK;GACL,OAAO,OAAO,IAAI,KAAK,MAAM;EAC/B,CAAC;EACH,OAAO,QACL,KAAK,YAAY;GACf,KAAK;GACL,OAAO,KAAK,GAAG;EACjB,CAAC;EACH,aACE,KAAK,YAAY;GACf,IAAI,QAAQ;GACZ,SAAS;GACT,OAAO,MAAM;EACf,CAAC;GACF,qBAAqB;CACxB;AACF"}
package/package.json CHANGED
@@ -1,6 +1,55 @@
1
1
  {
2
2
  "name": "@statewalker/db-sqlite",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.0",
4
+ "private": false,
5
+ "type": "module",
6
+ "description": "SQLite transactions for @statewalker/db-api: inTransaction(db, cb) and the serialised engine wrapper every SQLite driver uses.",
7
+ "bugs": {
8
+ "url": "https://github.com/statewalker/statewalker-db/issues"
9
+ },
10
+ "homepage": "https://github.com/statewalker/statewalker-db/tree/main/packages/db-sqlite#readme",
11
+ "author": {
12
+ "name": "Mikhail Kotelnikov",
13
+ "email": "mikhail.kotelnikov@gmail.com"
14
+ },
15
+ "license": "MIT",
16
+ "repository": {
17
+ "type": "git",
18
+ "url": "git+https://github.com/statewalker/statewalker-db.git",
19
+ "directory": "packages/db-sqlite"
20
+ },
21
+ "exports": {
22
+ ".": {
23
+ "source": "./src/index.ts",
24
+ "types": "./dist/index.d.mts",
25
+ "import": "./dist/index.mjs"
26
+ }
27
+ },
28
+ "files": [
29
+ "dist",
30
+ "src"
31
+ ],
32
+ "dependencies": {
33
+ "@statewalker/db-api": "^0.1.4"
34
+ },
35
+ "devDependencies": {
36
+ "@types/node": "^26.6.4",
37
+ "rimraf": "^6.1.3",
38
+ "tsdown": "^0.23.0",
39
+ "typescript": "^7.0.2",
40
+ "vitest": "^5.0.3"
41
+ },
42
+ "sideEffects": false,
43
+ "publishConfig": {
44
+ "access": "public"
45
+ },
46
+ "scripts": {
47
+ "build": "tsdown",
48
+ "dev": "tsdown --watch",
49
+ "test": "vitest run --passWithNoTests",
50
+ "typecheck": "tsc --noEmit",
51
+ "clean": "rimraf dist",
52
+ "lint": "biome check --write .",
53
+ "format": "biome format --write ."
54
+ }
6
55
  }
package/src/index.ts ADDED
@@ -0,0 +1,9 @@
1
+ export {
2
+ newSerialisedSqliteDb,
3
+ type SqliteEngine,
4
+ } from "./serialised-sqlite-db.js";
5
+ export {
6
+ inTransaction,
7
+ SQLITE_TRANSACTION,
8
+ type SqliteTransactionHook,
9
+ } from "./sqlite-transaction.js";
@@ -0,0 +1,100 @@
1
+ import type { Db, DbEntry } from "@statewalker/db-api";
2
+ import { SQLITE_TRANSACTION, type SqliteTransactionHook } from "./sqlite-transaction.js";
3
+
4
+ /**
5
+ * The synchronous engine a SQLite driver wraps. `all` returns rows (BLOBs as Uint8Array) and must
6
+ * run exactly one statement; `exec` runs every statement of a string. `transaction`, when present,
7
+ * replaces `BEGIN IMMEDIATE`/`COMMIT`/`ROLLBACK` (Durable Objects forbid them in SQL).
8
+ */
9
+ export type SqliteEngine = {
10
+ all(sql: string, params: unknown[]): Record<string, unknown>[];
11
+ exec(sql: string): void;
12
+ close(): void;
13
+ transaction?<T>(fn: () => Promise<T>): Promise<T>;
14
+ };
15
+
16
+ function newLock() {
17
+ let tail: Promise<unknown> = Promise.resolve();
18
+ return <T>(fn: () => Promise<T>): Promise<T> => {
19
+ const run = tail.then(fn);
20
+ tail = run.catch(() => undefined);
21
+ return run;
22
+ };
23
+ }
24
+
25
+ /**
26
+ * Wrap an engine as a `Db` whose calls run one at a time, in call order, and which carries the
27
+ * `inTransaction` hook. The `tx` handed to a transaction callback bypasses the queue, has no hook
28
+ * (so nesting is rejected) and rejects once its transaction has finished.
29
+ */
30
+ export function newSerialisedSqliteDb(engine: SqliteEngine): Db {
31
+ const lock = newLock();
32
+ let closed = false;
33
+ const live = () => {
34
+ if (closed) throw new Error("db-sqlite: the database is closed");
35
+ };
36
+ const runTransaction =
37
+ engine.transaction?.bind(engine) ??
38
+ (async <T>(fn: () => Promise<T>): Promise<T> => {
39
+ engine.exec("BEGIN IMMEDIATE");
40
+ try {
41
+ const result = await fn();
42
+ engine.exec("COMMIT");
43
+ return result;
44
+ } catch (error) {
45
+ try {
46
+ engine.exec("ROLLBACK");
47
+ } catch {
48
+ // SQLite already ended the transaction itself (ON CONFLICT ROLLBACK, auto-rollback)
49
+ }
50
+ throw error;
51
+ }
52
+ });
53
+
54
+ const transaction: SqliteTransactionHook = (cb) =>
55
+ lock(async () => {
56
+ live();
57
+ let finished = false;
58
+ const open = () => {
59
+ if (finished) throw new Error("db-sqlite: the transaction is finished; use the outer Db");
60
+ };
61
+ const tx: Db = {
62
+ async query<T = DbEntry>(sql: string, params: unknown[] = []): Promise<T[]> {
63
+ open();
64
+ return engine.all(sql, params) as T[];
65
+ },
66
+ async exec(sql: string): Promise<void> {
67
+ open();
68
+ engine.exec(sql);
69
+ },
70
+ async close(): Promise<void> {
71
+ throw new Error("db-sqlite: close the outer Db, not the transaction handle");
72
+ },
73
+ };
74
+ try {
75
+ return await runTransaction(() => cb(tx));
76
+ } finally {
77
+ finished = true;
78
+ }
79
+ });
80
+
81
+ return {
82
+ query: <T = DbEntry>(sql: string, params: unknown[] = []) =>
83
+ lock(async () => {
84
+ live();
85
+ return engine.all(sql, params) as T[];
86
+ }),
87
+ exec: (sql: string) =>
88
+ lock(async () => {
89
+ live();
90
+ engine.exec(sql);
91
+ }),
92
+ close: () =>
93
+ lock(async () => {
94
+ if (closed) return;
95
+ closed = true;
96
+ engine.close();
97
+ }),
98
+ [SQLITE_TRANSACTION]: transaction,
99
+ } as Db;
100
+ }
@@ -0,0 +1,23 @@
1
+ import type { Db } from "@statewalker/db-api";
2
+
3
+ /** Key under which a SQLite Db carries its transaction hook. Shared across bundles via Symbol.for. */
4
+ export const SQLITE_TRANSACTION: unique symbol = Symbol.for("@statewalker/db-sqlite:transaction");
5
+
6
+ /** Runs `cb` inside one transaction of the Db that carries it. */
7
+ export type SqliteTransactionHook = <T>(cb: (tx: Db) => Promise<T>) => Promise<T>;
8
+
9
+ const NO_HOOK =
10
+ "inTransaction: this Db has no SQLite transaction hook. It is not a @statewalker/db-sqlite* Db, " +
11
+ "or it wraps one (a wrapper object loses the hook - pass the driver's Db itself), " +
12
+ "or it is the handle of a running transaction (nesting is not supported).";
13
+
14
+ /**
15
+ * Run `cb` in one SQLite transaction: every statement issued through `tx` commits together, or
16
+ * none does if `cb` throws. Other calls on `db` wait until the transaction ends. `cb` must not do
17
+ * external I/O and must be idempotent: a Durable Object may run it more than once.
18
+ */
19
+ export function inTransaction<T>(db: Db, cb: (tx: Db) => Promise<T>): Promise<T> {
20
+ const hook = (db as { [SQLITE_TRANSACTION]?: SqliteTransactionHook })[SQLITE_TRANSACTION];
21
+ if (typeof hook !== "function") return Promise.reject(new Error(NO_HOOK));
22
+ return hook(cb);
23
+ }