@statewalker/db-sqlite 0.1.2 → 0.1.3

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
@@ -5,7 +5,9 @@
5
5
  Transactions for SQLite databases behind `Db` from `@statewalker/db-api`:
6
6
  `inTransaction(db, cb)` runs `cb` so that every statement issued through its `tx` handle commits
7
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.
8
+ (`db-sqlite-node`, `db-sqlite-browser`, `db-sqlite-do`) builds its `Db` with, and
9
+ `newSerialisedDb`, the engine-neutral lifecycle wrapper the DuckDB and PGlite drivers use. Both
10
+ keep the lifecycle that the `Db` JSDoc in `@statewalker/db-api` promises.
9
11
 
10
12
  ## Why it exists
11
13
 
@@ -22,7 +24,16 @@ pnpm add @statewalker/db-sqlite
22
24
 
23
25
  | Import | Gives | Environment |
24
26
  | --- | --- | --- |
25
- | `@statewalker/db-sqlite` | `inTransaction`, `newSerialisedSqliteDb`, `SQLITE_TRANSACTION`; types `SqliteEngine`, `SqliteTransactionHook` | any |
27
+ | `@statewalker/db-sqlite` | `inTransaction`, `newSerialisedDb`, `newSerialisedSqliteDb`, `SQLITE_TRANSACTION`; types `SerialisedDbEngine`, `SqliteEngine`, `SqliteTransactionHook` | any |
28
+
29
+ `newSerialisedDb(engine, { name })` wraps an asynchronous `SerialisedDbEngine` (`query(sql,
30
+ params)`, `exec(sql)`, optional `flush()`, `close()`) as a `Db`: calls run one at a time in call
31
+ order; `close()` waits for the calls made before it, then closes the engine once; a call made once
32
+ `close()` has started rejects with `<name>: the database is closed`; a second `close()` is a
33
+ no-op; integers in rows come back as numbers within ±(2^53 - 1) and as bigints beyond, also
34
+ inside arrays and plain objects. It lives here, not in `@statewalker/db-api`, because that
35
+ package is types-only; it has no SQLite code in it, so a DuckDB or PGlite driver depends on this
36
+ package without pulling in any engine.
26
37
 
27
38
  `inTransaction(db, cb)` returns what `cb` returns. If `cb` throws, everything it wrote is rolled
28
39
  back and the same error is rethrown; so is a failing `COMMIT` (a deferred foreign key, for
@@ -39,10 +50,13 @@ sees the call (on the Db and on the `tx` handle alike):
39
50
  | `undefined` parameter | binds `NULL` |
40
51
  | `Date` parameter | binds its ISO 8601 UTC text, `date.toISOString()` (`"2026-01-02T03:04:05.006Z"`), which SQLite date functions read; an invalid Date rejects with `db-sqlite: parameter N is an invalid Date` |
41
52
  | `bigint` parameter | binds as an integer |
53
+ | `null`, `number`, `string` parameter | binds as given (an integer-valued number as an integer, any other as a real) |
54
+ | `ArrayBuffer`, or any ArrayBuffer view (`Uint8Array`, `DataView`, `Float32Array`, …) parameter | binds a BLOB of exactly the view's bytes (`byteOffset` to `byteOffset + byteLength`) |
55
+ | any other parameter: a plain object, `Map`, array, function, symbol, boxed primitive (`new String(…)`) | rejects with a `TypeError`, `db-sqlite: parameter N has type <type>, which SQLite cannot bind; …`, and nothing runs. node:sqlite would otherwise read a leading object as named parameters and bind the rest one place to the left. SQLite has no array type: bind a list as JSON text, `JSON.stringify(ids)`, and read it with `json_each(?)` |
42
56
  | integer in a result | a `number` within ±(2^53 - 1), a `bigint` beyond, so no value loses precision |
43
57
 
44
58
  A trailing `;`, comments, and semicolons inside literals or a `CREATE TRIGGER … BEGIN … END` body
45
- do not count as a second statement. Other parameter types go to the engine unchanged.
59
+ do not count as a second statement. Parameter indexes in messages count from 1.
46
60
 
47
61
  ## Examples
48
62
 
@@ -72,8 +86,10 @@ await db.close();
72
86
  Db, for **an object that wraps a SQLite Db** (copying `query`/`exec`/`close` drops the hook —
73
87
  pass the driver's Db, or a spread copy `{ ...db }`, which keeps symbol keys), and for the `tx`
74
88
  handle itself: **nested transactions are not supported**.
75
- - **One call at a time.** Every `query`, `exec`, `close` and transaction goes through one queue,
76
- in call order. A plain `db.exec` issued while another flow's transaction is open waits; it never
89
+ - **One call at a time.** Every `query`, `exec`, `close` and transaction goes through one queue
90
+ (the one `newSerialisedDb` uses), in call order. A call made once `close()` has started rejects
91
+ at once with `db-sqlite: the database is closed`; `close()` itself waits for earlier calls,
92
+ and a second `close()` is a no-op. A plain `db.exec` issued while another flow's transaction is open waits; it never
77
93
  joins that transaction, so a rollback cannot take it down. `close` waits for a running
78
94
  transaction.
79
95
  - **The `tx` handle expires.** After the callback settles, `tx.query` rejects with
package/dist/index.d.mts CHANGED
@@ -1,11 +1,35 @@
1
1
  import { Db } from "@statewalker/db-api";
2
+ //#region src/serialised-db.d.ts
3
+ /**
4
+ * The asynchronous engine a driver wraps with {@link newSerialisedDb}. It is called one call at a
5
+ * time and never after `close`; `query` returns rows with integers as numbers or bigints (the
6
+ * wrapper turns safe bigints into numbers).
7
+ */
8
+ type SerialisedDbEngine = {
9
+ query(sql: string, params: unknown[]): Promise<Record<string, unknown>[]>;
10
+ exec(sql: string): Promise<void>;
11
+ flush?(): Promise<void>;
12
+ close(): void | Promise<void>;
13
+ };
14
+ /**
15
+ * Wrap an engine as a `Db` that keeps the lifecycle every driver shares: calls run one at a time,
16
+ * in call order; `close()` waits for the calls made before it, then closes the engine; calls made
17
+ * once `close()` has started reject with `<name>: the database is closed`; closing twice is a
18
+ * no-op. Integers come back as numbers when safe and as bigints beyond (see
19
+ * {@link toSafeIntegers}). `name` prefixes the error, e.g. `"db-pglite"`.
20
+ */
21
+ export declare function newSerialisedDb(engine: SerialisedDbEngine, options: {
22
+ name: string;
23
+ }): Db;
24
+ //#endregion
2
25
  //#region src/serialised-sqlite-db.d.ts
3
26
  /**
4
27
  * The synchronous engine a SQLite driver wraps. `all` returns rows (BLOBs as Uint8Array; integers
5
28
  * as numbers or bigints, which the wrapper turns into numbers when they are safe) and is given
6
- * exactly one non-empty statement and parameters already normalised (no boolean, undefined or
7
- * Date); `exec` runs every statement of a non-empty string. `transaction`, when present, replaces
8
- * `BEGIN IMMEDIATE`/`COMMIT`/`ROLLBACK` (Durable Objects forbid them in SQL).
29
+ * exactly one non-empty statement and parameters already normalised and checked (only null,
30
+ * number, bigint, string and Uint8Array); `exec` runs every statement of a non-empty string.
31
+ * `transaction`, when present, replaces `BEGIN IMMEDIATE`/`COMMIT`/`ROLLBACK` (Durable Objects
32
+ * forbid them in SQL).
9
33
  */
10
34
  type SqliteEngine = {
11
35
  all(sql: string, params: unknown[]): Record<string, unknown>[];
@@ -14,11 +38,13 @@ type SqliteEngine = {
14
38
  transaction?<T>(fn: () => Promise<T>): Promise<T>;
15
39
  };
16
40
  /**
17
- * Wrap an engine as a `Db` whose calls run one at a time, in call order, and which carries the
18
- * `inTransaction` hook. Every SQLite driver gets the same input handling here: empty SQL rejects,
19
- * `query` rejects a second statement, parameters are normalised and safe integers come back as
20
- * numbers. The `tx` handed to a transaction callback bypasses the queue, has no hook
21
- * (so nesting is rejected) and rejects once its transaction has finished.
41
+ * Wrap an engine as a `Db` with the lifecycle of `newSerialisedDb` (calls run one at a time, in
42
+ * call order; `close()` waits for earlier calls; later calls reject with
43
+ * `db-sqlite: the database is closed`; closing twice is a no-op) and the `inTransaction` hook.
44
+ * Every SQLite driver gets the same input handling here: empty SQL rejects, `query` rejects a
45
+ * second statement, parameters are normalised (one SQLite cannot bind rejects) and safe integers come back as numbers. The `tx`
46
+ * handed to a transaction callback bypasses the queue, has no hook (so nesting is rejected) and
47
+ * rejects once its transaction has finished.
22
48
  */
23
49
  export declare function newSerialisedSqliteDb(engine: SqliteEngine): Db;
24
50
  //#endregion
@@ -34,5 +60,5 @@ type SqliteTransactionHook = <T>(cb: (tx: Db) => Promise<T>) => Promise<T>;
34
60
  */
35
61
  export declare function inTransaction<T>(db: Db, cb: (tx: Db) => Promise<T>): Promise<T>;
36
62
  //#endregion
37
- export type { SqliteEngine, SqliteTransactionHook };
63
+ export type { SerialisedDbEngine, SqliteEngine, SqliteTransactionHook };
38
64
  //# sourceMappingURL=index.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.mts","names":[],"sources":["../src/serialised-sqlite-db.ts","../src/sqlite-transaction.ts"],"mappings":";;;;;;;;;KAWY;EACV,IAAI,aAAa,oBAAoB;EACrC,KAAK;EACL;EACA,aAAa,GAAG,UAAU,QAAQ,KAAK,QAAQ;;;;;;;;;wBAuEjC,sBAAsB,QAAQ,eAAe;;;;qBCnFhD;;KAGD,yBAAyB,GAAG,KAAK,IAAI,OAAO,QAAQ,OAAO,QAAQ;;;;;;wBAY/D,cAAc,GAAG,IAAI,IAAI,KAAK,IAAI,OAAO,QAAQ,KAAK,QAAQ"}
1
+ {"version":3,"file":"index.d.mts","names":[],"sources":["../src/serialised-db.ts","../src/serialised-sqlite-db.ts","../src/sqlite-transaction.ts"],"mappings":";;;;;;;KAqEY;EACV,MAAM,aAAa,oBAAoB,QAAQ;EAC/C,KAAK,cAAc;EACnB,UAAU;EACV,gBAAgB;;;;;;;;;wBAUF,gBAAgB,QAAQ,oBAAoB;EAAW;IAAiB;;;;;;;;;;;KCtE5E;EACV,IAAI,aAAa,oBAAoB;EACrC,KAAK;EACL;EACA,aAAa,GAAG,UAAU,QAAQ,KAAK,QAAQ;;;;;;;;;;;wBA8EjC,sBAAsB,QAAQ,eAAe;;;;qBC5FhD;;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 CHANGED
@@ -1,3 +1,66 @@
1
+ //#region src/serialised-db.ts
2
+ function newDbCallQueue(name, closeEngine) {
3
+ let tail = Promise.resolve();
4
+ let closing;
5
+ const enqueue = (fn) => {
6
+ const result = tail.then(fn);
7
+ tail = result.catch(() => void 0);
8
+ return result;
9
+ };
10
+ return {
11
+ run: (fn) => closing ? Promise.reject(/* @__PURE__ */ new Error(`${name}: the database is closed`)) : enqueue(fn),
12
+ close: () => {
13
+ closing ??= enqueue(closeEngine);
14
+ return closing;
15
+ }
16
+ };
17
+ }
18
+ const MIN_SAFE = BigInt(Number.MIN_SAFE_INTEGER);
19
+ const MAX_SAFE = BigInt(Number.MAX_SAFE_INTEGER);
20
+ const isPlainObject = (value) => {
21
+ const proto = Object.getPrototypeOf(value);
22
+ return proto === Object.prototype || proto === null;
23
+ };
24
+ /** A bigint within ±(2^53 - 1) as a number; arrays and plain objects converted in place. */
25
+ function safeInteger(value) {
26
+ if (typeof value === "bigint") return value >= MIN_SAFE && value <= MAX_SAFE ? Number(value) : value;
27
+ if (Array.isArray(value)) for (let i = 0; i < value.length; i++) value[i] = safeInteger(value[i]);
28
+ else if (value !== null && typeof value === "object" && isPlainObject(value)) {
29
+ const record = value;
30
+ for (const key in record) record[key] = safeInteger(record[key]);
31
+ }
32
+ return value;
33
+ }
34
+ /**
35
+ * Integers within ±(2^53 - 1) become numbers, larger ones stay bigints (no precision loss), in
36
+ * every column and inside list, struct and map values. The rows are converted in place.
37
+ */
38
+ function toSafeIntegers(rows) {
39
+ for (const row of rows) {
40
+ const record = row;
41
+ for (const key in record) record[key] = safeInteger(record[key]);
42
+ }
43
+ return rows;
44
+ }
45
+ /**
46
+ * Wrap an engine as a `Db` that keeps the lifecycle every driver shares: calls run one at a time,
47
+ * in call order; `close()` waits for the calls made before it, then closes the engine; calls made
48
+ * once `close()` has started reject with `<name>: the database is closed`; closing twice is a
49
+ * no-op. Integers come back as numbers when safe and as bigints beyond (see
50
+ * {@link toSafeIntegers}). `name` prefixes the error, e.g. `"db-pglite"`.
51
+ */
52
+ function newSerialisedDb(engine, options) {
53
+ const queue = newDbCallQueue(options.name, () => engine.close());
54
+ const db = {
55
+ query: (sql, params = []) => queue.run(async () => toSafeIntegers(await engine.query(sql, params))),
56
+ exec: (sql) => queue.run(() => engine.exec(sql)),
57
+ close: () => queue.close()
58
+ };
59
+ const flush = engine.flush?.bind(engine);
60
+ if (flush) db.flush = () => queue.run(flush);
61
+ return db;
62
+ }
63
+ //#endregion
1
64
  //#region src/sql-statements.ts
2
65
  const SEMI = 0;
3
66
  const WS = 1;
@@ -184,14 +247,6 @@ function inTransaction(db, cb) {
184
247
  }
185
248
  //#endregion
186
249
  //#region src/serialised-sqlite-db.ts
187
- function newLock() {
188
- let tail = Promise.resolve();
189
- return (fn) => {
190
- const run = tail.then(fn);
191
- tail = run.catch(() => void 0);
192
- return run;
193
- };
194
- }
195
250
  const EMPTY_SQL = "db-sqlite: the SQL is empty (only whitespace, comments or semicolons)";
196
251
  const MANY_STATEMENTS = "db-sqlite: query runs one statement, and this SQL has more after the first; run them one query at a time, or use exec (no parameters, no rows)";
197
252
  function checkSql(sql, one) {
@@ -200,47 +255,54 @@ function checkSql(sql, one) {
200
255
  if (count === "empty") throw new Error(EMPTY_SQL);
201
256
  if (one && count === "many") throw new Error(MANY_STATEMENTS);
202
257
  }
203
- /** boolean → 1/0, undefined → NULL, Date → ISO 8601 UTC text; anything else is left as given. */
258
+ /** The type a rejected parameter is named by: `symbol`, `function`, or the object's class. */
259
+ function typeName(value) {
260
+ if (typeof value !== "object" || value === null) return typeof value;
261
+ const name = value.constructor?.name;
262
+ return typeof name === "string" && name ? name : "Object";
263
+ }
264
+ /**
265
+ * boolean → 1/0, undefined → NULL, Date → ISO 8601 UTC text, ArrayBuffer or any ArrayBuffer view →
266
+ * a Uint8Array over exactly its bytes; null, number, bigint and string are left as given. Anything
267
+ * else (a plain object, Map, array, function, symbol, boxed primitive) rejects: node:sqlite would
268
+ * take a leading object as named parameters and bind the rest one place to the left, and SQLite
269
+ * has no array type (bind a list as JSON text and read it with `json_each`).
270
+ */
204
271
  function toSqliteParam(value, index) {
272
+ if (value === null || typeof value === "string" || typeof value === "number") return value;
273
+ if (typeof value === "bigint") return value;
205
274
  if (typeof value === "boolean") return value ? 1 : 0;
206
275
  if (value === void 0) return null;
207
276
  if (value instanceof Date) {
208
277
  if (Number.isNaN(value.getTime())) throw new RangeError(`db-sqlite: parameter ${index + 1} is an invalid Date`);
209
278
  return value.toISOString();
210
279
  }
211
- return value;
212
- }
213
- const MIN_SAFE = BigInt(Number.MIN_SAFE_INTEGER);
214
- const MAX_SAFE = BigInt(Number.MAX_SAFE_INTEGER);
215
- /** Integers within ±(2^53 - 1) become numbers; larger ones stay bigints (no precision loss). */
216
- function fromSqliteRows(rows) {
217
- for (const row of rows) for (const key in row) {
218
- const value = row[key];
219
- if (typeof value === "bigint" && value >= MIN_SAFE && value <= MAX_SAFE) row[key] = Number(value);
220
- }
221
- return rows;
280
+ if ((ArrayBuffer.isView(value) || value instanceof ArrayBuffer) && value.byteLength === 0) return (/* @__PURE__ */ new Uint8Array(1)).subarray(0, 0);
281
+ if (value instanceof Uint8Array && value.constructor === Uint8Array) return value;
282
+ if (ArrayBuffer.isView(value)) return new Uint8Array(value.buffer, value.byteOffset, value.byteLength);
283
+ if (value instanceof ArrayBuffer) return new Uint8Array(value);
284
+ const hint = Array.isArray(value) ? "; bind a list as JSON text and read it with json_each" : "";
285
+ throw new TypeError(`db-sqlite: parameter ${index + 1} has type ${typeName(value)}, which SQLite cannot bind; pass null, undefined, a boolean, number, bigint, string, Date, ArrayBuffer or ArrayBuffer view${hint}`);
222
286
  }
223
287
  function runAll(engine, sql, params) {
224
288
  checkSql(sql, true);
225
- return fromSqliteRows(engine.all(firstSqlStatement(sql), params.map(toSqliteParam)));
289
+ return toSafeIntegers(engine.all(firstSqlStatement(sql), params.map(toSqliteParam)));
226
290
  }
227
291
  function runExec(engine, sql) {
228
292
  checkSql(sql, false);
229
293
  engine.exec(sql);
230
294
  }
231
295
  /**
232
- * Wrap an engine as a `Db` whose calls run one at a time, in call order, and which carries the
233
- * `inTransaction` hook. Every SQLite driver gets the same input handling here: empty SQL rejects,
234
- * `query` rejects a second statement, parameters are normalised and safe integers come back as
235
- * numbers. The `tx` handed to a transaction callback bypasses the queue, has no hook
236
- * (so nesting is rejected) and rejects once its transaction has finished.
296
+ * Wrap an engine as a `Db` with the lifecycle of `newSerialisedDb` (calls run one at a time, in
297
+ * call order; `close()` waits for earlier calls; later calls reject with
298
+ * `db-sqlite: the database is closed`; closing twice is a no-op) and the `inTransaction` hook.
299
+ * Every SQLite driver gets the same input handling here: empty SQL rejects, `query` rejects a
300
+ * second statement, parameters are normalised (one SQLite cannot bind rejects) and safe integers come back as numbers. The `tx`
301
+ * handed to a transaction callback bypasses the queue, has no hook (so nesting is rejected) and
302
+ * rejects once its transaction has finished.
237
303
  */
238
304
  function newSerialisedSqliteDb(engine) {
239
- const lock = newLock();
240
- let closed = false;
241
- const live = () => {
242
- if (closed) throw new Error("db-sqlite: the database is closed");
243
- };
305
+ const queue = newDbCallQueue("db-sqlite", () => engine.close());
244
306
  const runTransaction = engine.transaction?.bind(engine) ?? (async (fn) => {
245
307
  engine.exec("BEGIN IMMEDIATE");
246
308
  try {
@@ -254,8 +316,7 @@ function newSerialisedSqliteDb(engine) {
254
316
  throw error;
255
317
  }
256
318
  });
257
- const transaction = (cb) => lock(async () => {
258
- live();
319
+ const transaction = (cb) => queue.run(async () => {
259
320
  let finished = false;
260
321
  const open = () => {
261
322
  if (finished) throw new Error("db-sqlite: the transaction is finished; use the outer Db");
@@ -280,23 +341,13 @@ function newSerialisedSqliteDb(engine) {
280
341
  }
281
342
  });
282
343
  return {
283
- query: (sql, params = []) => lock(async () => {
284
- live();
285
- return runAll(engine, sql, params);
286
- }),
287
- exec: (sql) => lock(async () => {
288
- live();
289
- runExec(engine, sql);
290
- }),
291
- close: () => lock(async () => {
292
- if (closed) return;
293
- closed = true;
294
- engine.close();
295
- }),
344
+ query: (sql, params = []) => queue.run(() => runAll(engine, sql, params)),
345
+ exec: (sql) => queue.run(() => runExec(engine, sql)),
346
+ close: () => queue.close(),
296
347
  [SQLITE_TRANSACTION]: transaction
297
348
  };
298
349
  }
299
350
  //#endregion
300
- export { SQLITE_TRANSACTION, inTransaction, newSerialisedSqliteDb };
351
+ export { SQLITE_TRANSACTION, inTransaction, newSerialisedDb, newSerialisedSqliteDb };
301
352
 
302
353
  //# sourceMappingURL=index.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":[],"sources":["../src/sql-statements.ts","../src/sqlite-transaction.ts","../src/serialised-sqlite-db.ts"],"sourcesContent":["/**\n * How many SQL statements a string holds, without running it: \"empty\" (only whitespace, comments\n * and semicolons), \"one\" (one statement, maybe followed by such a tail) or \"many\".\n *\n * A port of SQLite's own `sqlite3_complete()` state machine (src/complete.c): it knows string\n * literals ('…'), quoted identifiers (\"…\", `…`, […]), `--` and `/* … *\\/` comments, and that\n * the semicolons inside a `CREATE TRIGGER … BEGIN … END` body do not end the statement. An\n * unterminated literal is content (SQLite reports the syntax error); an unterminated comment runs\n * to the end of the text.\n */\nexport type SqlStatementCount = \"empty\" | \"one\" | \"many\";\n\nconst SEMI = 0;\nconst WS = 1;\nconst OTHER = 2;\nconst EXPLAIN = 3;\nconst CREATE = 4;\nconst TEMP = 5;\nconst TRIGGER = 6;\nconst END = 7;\n\n/** trans[state][token]; states 0 INVALID, 1 START, 2 NORMAL, 3 EXPLAIN, 4 CREATE, 5 TRIGGER, 6 SEMI, 7 END. */\nconst TRANS = [\n [1, 0, 2, 3, 4, 2, 2, 2],\n [1, 1, 2, 3, 4, 2, 2, 2],\n [1, 2, 2, 2, 2, 2, 2, 2],\n [1, 3, 3, 2, 4, 2, 2, 2],\n [1, 4, 2, 2, 2, 4, 5, 2],\n [6, 5, 5, 5, 5, 5, 5, 5],\n [6, 6, 5, 5, 5, 5, 5, 7],\n [1, 7, 5, 5, 5, 5, 5, 5],\n];\n\nconst KEYWORDS: Record<string, number> = {\n create: CREATE,\n temp: TEMP,\n temporary: TEMP,\n trigger: TRIGGER,\n end: END,\n explain: EXPLAIN,\n};\n\nconst isIdChar = (c: string) => /[A-Za-z0-9_$]/.test(c) || c.charCodeAt(0) >= 0x80;\n\nexport function countSqlStatements(sql: string): SqlStatementCount {\n return scanSqlStatements(sql).count;\n}\n\n/**\n * The first statement of `sql` without the semicolon that ends it and without the empty tail\n * after it (whitespace, comments, semicolons), for engines that reject such a tail (Durable\n * Object SQLite: \"SQL code did not contain a statement\"). Meant for SQL that\n * {@link countSqlStatements} counts as \"one\"; SQL without an ending semicolon comes back as is.\n */\nexport function firstSqlStatement(sql: string): string {\n const { firstEnd } = scanSqlStatements(sql);\n return firstEnd < 0 ? sql : sql.slice(0, firstEnd);\n}\n\nfunction scanSqlStatements(sql: string): { count: SqlStatementCount; firstEnd: number } {\n let firstEnd = -1; // index of the \";\" that ends the first statement\n let state = 0;\n let content = false; // a token other than whitespace or \";\" was seen\n let firstEnded = false; // the first statement with content has reached its \";\"\n let i = 0;\n const n = sql.length;\n while (i < n) {\n const c = sql[i] as string;\n let token: number;\n if (c === \";\") {\n token = SEMI;\n } else if (c === \" \" || c === \"\\t\" || c === \"\\n\" || c === \"\\r\" || c === \"\\f\") {\n token = WS;\n } else if (c === \"/\" && sql[i + 1] === \"*\") {\n const close = sql.indexOf(\"*/\", i + 2);\n if (close < 0) break; // an unterminated comment runs to the end, like whitespace\n i = close + 1;\n token = WS;\n } else if (c === \"-\" && sql[i + 1] === \"-\") {\n const eol = sql.indexOf(\"\\n\", i);\n if (eol < 0) break;\n i = eol;\n token = WS;\n } else if (c === \"[\" || c === \"`\" || c === '\"' || c === \"'\") {\n const close = sql.indexOf(c === \"[\" ? \"]\" : c, i + 1);\n if (close < 0) return { count: firstEnded ? \"many\" : \"one\", firstEnd };\n i = close;\n token = OTHER;\n } else if (isIdChar(c)) {\n let j = i + 1;\n while (j < n && isIdChar(sql[j] as string)) j++;\n token = KEYWORDS[sql.slice(i, j).toLowerCase()] ?? OTHER;\n i = j - 1;\n } else {\n token = OTHER;\n }\n if (token !== SEMI && token !== WS) {\n if (firstEnded) return { count: \"many\", firstEnd };\n content = true;\n }\n state = TRANS[state]?.[token] ?? 2;\n if (token === SEMI && state === 1 && content && !firstEnded) {\n firstEnded = true;\n firstEnd = i;\n }\n i++;\n }\n return { count: content ? \"one\" : \"empty\", firstEnd };\n}\n","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 { countSqlStatements, firstSqlStatement } from \"./sql-statements.js\";\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; integers\n * as numbers or bigints, which the wrapper turns into numbers when they are safe) and is given\n * exactly one non-empty statement and parameters already normalised (no boolean, undefined or\n * Date); `exec` runs every statement of a non-empty string. `transaction`, when present, replaces\n * `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\nconst EMPTY_SQL = \"db-sqlite: the SQL is empty (only whitespace, comments or semicolons)\";\nconst MANY_STATEMENTS =\n \"db-sqlite: query runs one statement, and this SQL has more after the first; \" +\n \"run them one query at a time, or use exec (no parameters, no rows)\";\n\nfunction checkSql(sql: string, one: boolean): void {\n if (typeof sql !== \"string\") throw new TypeError(\"db-sqlite: the SQL must be a string\");\n const count = countSqlStatements(sql);\n if (count === \"empty\") throw new Error(EMPTY_SQL);\n if (one && count === \"many\") throw new Error(MANY_STATEMENTS);\n}\n\n/** boolean → 1/0, undefined → NULL, Date → ISO 8601 UTC text; anything else is left as given. */\nfunction toSqliteParam(value: unknown, index: number): unknown {\n if (typeof value === \"boolean\") return value ? 1 : 0;\n if (value === undefined) return null;\n if (value instanceof Date) {\n if (Number.isNaN(value.getTime())) {\n throw new RangeError(`db-sqlite: parameter ${index + 1} is an invalid Date`);\n }\n return value.toISOString();\n }\n return value;\n}\n\nconst MIN_SAFE = BigInt(Number.MIN_SAFE_INTEGER);\nconst MAX_SAFE = BigInt(Number.MAX_SAFE_INTEGER);\n\n/** Integers within ±(2^53 - 1) become numbers; larger ones stay bigints (no precision loss). */\nfunction fromSqliteRows(rows: Record<string, unknown>[]): Record<string, unknown>[] {\n for (const row of rows) {\n for (const key in row) {\n const value = row[key];\n if (typeof value === \"bigint\" && value >= MIN_SAFE && value <= MAX_SAFE) {\n row[key] = Number(value);\n }\n }\n }\n return rows;\n}\n\nfunction runAll(engine: SqliteEngine, sql: string, params: unknown[]): Record<string, unknown>[] {\n checkSql(sql, true);\n // Only the statement itself reaches the engine: DO SQLite rejects an empty tail (\"; -- c ;\").\n return fromSqliteRows(engine.all(firstSqlStatement(sql), params.map(toSqliteParam)));\n}\n\nfunction runExec(engine: SqliteEngine, sql: string): void {\n checkSql(sql, false);\n engine.exec(sql);\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. Every SQLite driver gets the same input handling here: empty SQL rejects,\n * `query` rejects a second statement, parameters are normalised and safe integers come back as\n * numbers. 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 runAll(engine, sql, params) as T[];\n },\n async exec(sql: string): Promise<void> {\n open();\n runExec(engine, 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 runAll(engine, sql, params) as T[];\n }),\n exec: (sql: string) =>\n lock(async () => {\n live();\n runExec(engine, 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":";AAYA,MAAM,OAAO;AACb,MAAM,KAAK;AACX,MAAM,QAAQ;AACd,MAAM,UAAU;AAChB,MAAM,SAAS;AACf,MAAM,OAAO;AACb,MAAM,UAAU;AAChB,MAAM,MAAM;;AAGZ,MAAM,QAAQ;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ised-db.ts","../src/sql-statements.ts","../src/sqlite-transaction.ts","../src/serialised-sqlite-db.ts"],"sourcesContent":["import type { Db, DbEntry } from \"@statewalker/db-api\";\n\n/**\n * The calls of one `Db`, run one at a time in call order. Once `close()` has started, `run`\n * rejects at once with `<name>: the database is closed`; `close()` itself queues behind every\n * earlier call, closes the engine once, and returns the same promise to every later caller.\n */\nexport type DbCallQueue = {\n run<T>(fn: () => T | Promise<T>): Promise<T>;\n close(): Promise<void>;\n};\n\nexport function newDbCallQueue(name: string, closeEngine: () => void | Promise<void>): DbCallQueue {\n let tail: Promise<unknown> = Promise.resolve();\n let closing: Promise<void> | undefined;\n const enqueue = <T>(fn: () => T | Promise<T>): Promise<T> => {\n const result = tail.then(fn);\n tail = result.catch(() => undefined);\n return result;\n };\n return {\n run: (fn) =>\n closing ? Promise.reject(new Error(`${name}: the database is closed`)) : enqueue(fn),\n close: () => {\n closing ??= enqueue(closeEngine);\n return closing;\n },\n };\n}\n\nconst MIN_SAFE = BigInt(Number.MIN_SAFE_INTEGER);\nconst MAX_SAFE = BigInt(Number.MAX_SAFE_INTEGER);\n\nconst isPlainObject = (value: object): boolean => {\n const proto = Object.getPrototypeOf(value);\n return proto === Object.prototype || proto === null;\n};\n\n/** A bigint within ±(2^53 - 1) as a number; arrays and plain objects converted in place. */\nfunction safeInteger(value: unknown): unknown {\n if (typeof value === \"bigint\") {\n return value >= MIN_SAFE && value <= MAX_SAFE ? Number(value) : value;\n }\n if (Array.isArray(value)) {\n for (let i = 0; i < value.length; i++) value[i] = safeInteger(value[i]);\n } else if (value !== null && typeof value === \"object\" && isPlainObject(value)) {\n const record = value as Record<string, unknown>;\n for (const key in record) record[key] = safeInteger(record[key]);\n }\n return value;\n}\n\n/**\n * Integers within ±(2^53 - 1) become numbers, larger ones stay bigints (no precision loss), in\n * every column and inside list, struct and map values. The rows are converted in place.\n */\nexport function toSafeIntegers<T extends Record<string, unknown>>(rows: T[]): T[] {\n for (const row of rows) {\n const record = row as Record<string, unknown>;\n for (const key in record) record[key] = safeInteger(record[key]);\n }\n return rows;\n}\n\n/**\n * The asynchronous engine a driver wraps with {@link newSerialisedDb}. It is called one call at a\n * time and never after `close`; `query` returns rows with integers as numbers or bigints (the\n * wrapper turns safe bigints into numbers).\n */\nexport type SerialisedDbEngine = {\n query(sql: string, params: unknown[]): Promise<Record<string, unknown>[]>;\n exec(sql: string): Promise<void>;\n flush?(): Promise<void>;\n close(): void | Promise<void>;\n};\n\n/**\n * Wrap an engine as a `Db` that keeps the lifecycle every driver shares: calls run one at a time,\n * in call order; `close()` waits for the calls made before it, then closes the engine; calls made\n * once `close()` has started reject with `<name>: the database is closed`; closing twice is a\n * no-op. Integers come back as numbers when safe and as bigints beyond (see\n * {@link toSafeIntegers}). `name` prefixes the error, e.g. `\"db-pglite\"`.\n */\nexport function newSerialisedDb(engine: SerialisedDbEngine, options: { name: string }): Db {\n const queue = newDbCallQueue(options.name, () => engine.close());\n const db: Db = {\n query: <T = DbEntry>(sql: string, params: unknown[] = []) =>\n queue.run(async () => toSafeIntegers(await engine.query(sql, params)) as T[]),\n exec: (sql: string) => queue.run(() => engine.exec(sql)),\n close: () => queue.close(),\n };\n const flush = engine.flush?.bind(engine);\n if (flush) db.flush = () => queue.run(flush);\n return db;\n}\n","/**\n * How many SQL statements a string holds, without running it: \"empty\" (only whitespace, comments\n * and semicolons), \"one\" (one statement, maybe followed by such a tail) or \"many\".\n *\n * A port of SQLite's own `sqlite3_complete()` state machine (src/complete.c): it knows string\n * literals ('…'), quoted identifiers (\"…\", `…`, […]), `--` and `/* … *\\/` comments, and that\n * the semicolons inside a `CREATE TRIGGER … BEGIN … END` body do not end the statement. An\n * unterminated literal is content (SQLite reports the syntax error); an unterminated comment runs\n * to the end of the text.\n */\nexport type SqlStatementCount = \"empty\" | \"one\" | \"many\";\n\nconst SEMI = 0;\nconst WS = 1;\nconst OTHER = 2;\nconst EXPLAIN = 3;\nconst CREATE = 4;\nconst TEMP = 5;\nconst TRIGGER = 6;\nconst END = 7;\n\n/** trans[state][token]; states 0 INVALID, 1 START, 2 NORMAL, 3 EXPLAIN, 4 CREATE, 5 TRIGGER, 6 SEMI, 7 END. */\nconst TRANS = [\n [1, 0, 2, 3, 4, 2, 2, 2],\n [1, 1, 2, 3, 4, 2, 2, 2],\n [1, 2, 2, 2, 2, 2, 2, 2],\n [1, 3, 3, 2, 4, 2, 2, 2],\n [1, 4, 2, 2, 2, 4, 5, 2],\n [6, 5, 5, 5, 5, 5, 5, 5],\n [6, 6, 5, 5, 5, 5, 5, 7],\n [1, 7, 5, 5, 5, 5, 5, 5],\n];\n\nconst KEYWORDS: Record<string, number> = {\n create: CREATE,\n temp: TEMP,\n temporary: TEMP,\n trigger: TRIGGER,\n end: END,\n explain: EXPLAIN,\n};\n\nconst isIdChar = (c: string) => /[A-Za-z0-9_$]/.test(c) || c.charCodeAt(0) >= 0x80;\n\nexport function countSqlStatements(sql: string): SqlStatementCount {\n return scanSqlStatements(sql).count;\n}\n\n/**\n * The first statement of `sql` without the semicolon that ends it and without the empty tail\n * after it (whitespace, comments, semicolons), for engines that reject such a tail (Durable\n * Object SQLite: \"SQL code did not contain a statement\"). Meant for SQL that\n * {@link countSqlStatements} counts as \"one\"; SQL without an ending semicolon comes back as is.\n */\nexport function firstSqlStatement(sql: string): string {\n const { firstEnd } = scanSqlStatements(sql);\n return firstEnd < 0 ? sql : sql.slice(0, firstEnd);\n}\n\nfunction scanSqlStatements(sql: string): { count: SqlStatementCount; firstEnd: number } {\n let firstEnd = -1; // index of the \";\" that ends the first statement\n let state = 0;\n let content = false; // a token other than whitespace or \";\" was seen\n let firstEnded = false; // the first statement with content has reached its \";\"\n let i = 0;\n const n = sql.length;\n while (i < n) {\n const c = sql[i] as string;\n let token: number;\n if (c === \";\") {\n token = SEMI;\n } else if (c === \" \" || c === \"\\t\" || c === \"\\n\" || c === \"\\r\" || c === \"\\f\") {\n token = WS;\n } else if (c === \"/\" && sql[i + 1] === \"*\") {\n const close = sql.indexOf(\"*/\", i + 2);\n if (close < 0) break; // an unterminated comment runs to the end, like whitespace\n i = close + 1;\n token = WS;\n } else if (c === \"-\" && sql[i + 1] === \"-\") {\n const eol = sql.indexOf(\"\\n\", i);\n if (eol < 0) break;\n i = eol;\n token = WS;\n } else if (c === \"[\" || c === \"`\" || c === '\"' || c === \"'\") {\n const close = sql.indexOf(c === \"[\" ? \"]\" : c, i + 1);\n if (close < 0) return { count: firstEnded ? \"many\" : \"one\", firstEnd };\n i = close;\n token = OTHER;\n } else if (isIdChar(c)) {\n let j = i + 1;\n while (j < n && isIdChar(sql[j] as string)) j++;\n token = KEYWORDS[sql.slice(i, j).toLowerCase()] ?? OTHER;\n i = j - 1;\n } else {\n token = OTHER;\n }\n if (token !== SEMI && token !== WS) {\n if (firstEnded) return { count: \"many\", firstEnd };\n content = true;\n }\n state = TRANS[state]?.[token] ?? 2;\n if (token === SEMI && state === 1 && content && !firstEnded) {\n firstEnded = true;\n firstEnd = i;\n }\n i++;\n }\n return { count: content ? \"one\" : \"empty\", firstEnd };\n}\n","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 { newDbCallQueue, toSafeIntegers } from \"./serialised-db.js\";\nimport { countSqlStatements, firstSqlStatement } from \"./sql-statements.js\";\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; integers\n * as numbers or bigints, which the wrapper turns into numbers when they are safe) and is given\n * exactly one non-empty statement and parameters already normalised and checked (only null,\n * number, bigint, string and Uint8Array); `exec` runs every statement of a non-empty string.\n * `transaction`, when present, replaces `BEGIN IMMEDIATE`/`COMMIT`/`ROLLBACK` (Durable Objects\n * 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\nconst EMPTY_SQL = \"db-sqlite: the SQL is empty (only whitespace, comments or semicolons)\";\nconst MANY_STATEMENTS =\n \"db-sqlite: query runs one statement, and this SQL has more after the first; \" +\n \"run them one query at a time, or use exec (no parameters, no rows)\";\n\nfunction checkSql(sql: string, one: boolean): void {\n if (typeof sql !== \"string\") throw new TypeError(\"db-sqlite: the SQL must be a string\");\n const count = countSqlStatements(sql);\n if (count === \"empty\") throw new Error(EMPTY_SQL);\n if (one && count === \"many\") throw new Error(MANY_STATEMENTS);\n}\n\n/** The type a rejected parameter is named by: `symbol`, `function`, or the object's class. */\nfunction typeName(value: unknown): string {\n if (typeof value !== \"object\" || value === null) return typeof value;\n const name = (value as { constructor?: { name?: unknown } }).constructor?.name;\n return typeof name === \"string\" && name ? name : \"Object\";\n}\n\n/**\n * boolean → 1/0, undefined → NULL, Date → ISO 8601 UTC text, ArrayBuffer or any ArrayBuffer view →\n * a Uint8Array over exactly its bytes; null, number, bigint and string are left as given. Anything\n * else (a plain object, Map, array, function, symbol, boxed primitive) rejects: node:sqlite would\n * take a leading object as named parameters and bind the rest one place to the left, and SQLite\n * has no array type (bind a list as JSON text and read it with `json_each`).\n */\nfunction toSqliteParam(value: unknown, index: number): unknown {\n if (value === null || typeof value === \"string\" || typeof value === \"number\") return value;\n if (typeof value === \"bigint\") return value;\n if (typeof value === \"boolean\") return value ? 1 : 0;\n if (value === undefined) return null;\n if (value instanceof Date) {\n if (Number.isNaN(value.getTime())) {\n throw new RangeError(`db-sqlite: parameter ${index + 1} is an invalid Date`);\n }\n return value.toISOString();\n }\n // node:sqlite (Node 22) binds a view over a buffer with no backing store (any zero-length\n // ArrayBuffer) as NULL: give an empty value a fresh empty Uint8Array, which binds as a BLOB.\n if ((ArrayBuffer.isView(value) || value instanceof ArrayBuffer) && value.byteLength === 0) {\n return new Uint8Array(1).subarray(0, 0);\n }\n if (value instanceof Uint8Array && value.constructor === Uint8Array) return value;\n if (ArrayBuffer.isView(value)) {\n return new Uint8Array(value.buffer, value.byteOffset, value.byteLength);\n }\n if (value instanceof ArrayBuffer) return new Uint8Array(value);\n const hint = Array.isArray(value) ? \"; bind a list as JSON text and read it with json_each\" : \"\";\n throw new TypeError(\n `db-sqlite: parameter ${index + 1} has type ${typeName(value)}, which SQLite cannot bind; ` +\n \"pass null, undefined, a boolean, number, bigint, string, Date, ArrayBuffer or \" +\n `ArrayBuffer view${hint}`,\n );\n}\n\nfunction runAll(engine: SqliteEngine, sql: string, params: unknown[]): Record<string, unknown>[] {\n checkSql(sql, true);\n // Only the statement itself reaches the engine: DO SQLite rejects an empty tail (\"; -- c ;\").\n return toSafeIntegers(engine.all(firstSqlStatement(sql), params.map(toSqliteParam)));\n}\n\nfunction runExec(engine: SqliteEngine, sql: string): void {\n checkSql(sql, false);\n engine.exec(sql);\n}\n\n/**\n * Wrap an engine as a `Db` with the lifecycle of `newSerialisedDb` (calls run one at a time, in\n * call order; `close()` waits for earlier calls; later calls reject with\n * `db-sqlite: the database is closed`; closing twice is a no-op) and the `inTransaction` hook.\n * Every SQLite driver gets the same input handling here: empty SQL rejects, `query` rejects a\n * second statement, parameters are normalised (one SQLite cannot bind rejects) and safe integers come back as numbers. The `tx`\n * handed to a transaction callback bypasses the queue, has no hook (so nesting is rejected) and\n * rejects once its transaction has finished.\n */\nexport function newSerialisedSqliteDb(engine: SqliteEngine): Db {\n const queue = newDbCallQueue(\"db-sqlite\", () => engine.close());\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 queue.run(async () => {\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 runAll(engine, sql, params) as T[];\n },\n async exec(sql: string): Promise<void> {\n open();\n runExec(engine, 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 queue.run(() => runAll(engine, sql, params) as T[]),\n exec: (sql: string) => queue.run(() => runExec(engine, sql)),\n close: () => queue.close(),\n [SQLITE_TRANSACTION]: transaction,\n } as Db;\n}\n"],"mappings":";AAYA,SAAgB,eAAe,MAAc,aAAsD;CACjG,IAAI,OAAyB,QAAQ,QAAQ;CAC7C,IAAI;CACJ,MAAM,WAAc,OAAyC;EAC3D,MAAM,SAAS,KAAK,KAAK,EAAE;EAC3B,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,GAAG;GACrB;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,MAAM,UAAU,OAAO,QAAQ,KAAK,MAAM,CAAQ;EACpD,OAAO,QAAgB,MAAM,UAAU,QAAQ,QAAQ,GAAG,CAAC;EAC3D,aAAa,MAAM,MAAM;GACxB,qBAAqB;CACxB;AACF"}
package/package.json CHANGED
@@ -1,9 +1,9 @@
1
1
  {
2
2
  "name": "@statewalker/db-sqlite",
3
- "version": "0.1.2",
3
+ "version": "0.1.3",
4
4
  "private": false,
5
5
  "type": "module",
6
- "description": "SQLite transactions for @statewalker/db-api: inTransaction(db, cb) and the serialised engine wrapper every SQLite driver uses.",
6
+ "description": "SQLite transactions for @statewalker/db-api: inTransaction(db, cb), and the serialised Db wrappers every driver builds its lifecycle on.",
7
7
  "bugs": {
8
8
  "url": "https://github.com/statewalker/statewalker-db/issues"
9
9
  },
@@ -32,7 +32,7 @@
32
32
  "!src/**/*.test.ts"
33
33
  ],
34
34
  "dependencies": {
35
- "@statewalker/db-api": "^0.1.6"
35
+ "@statewalker/db-api": "^0.1.7"
36
36
  },
37
37
  "devDependencies": {
38
38
  "@types/node": "^26.6.4",
package/src/index.ts CHANGED
@@ -1,3 +1,7 @@
1
+ export {
2
+ newSerialisedDb,
3
+ type SerialisedDbEngine,
4
+ } from "./serialised-db.js";
1
5
  export {
2
6
  newSerialisedSqliteDb,
3
7
  type SqliteEngine,
@@ -0,0 +1,95 @@
1
+ import type { Db, DbEntry } from "@statewalker/db-api";
2
+
3
+ /**
4
+ * The calls of one `Db`, run one at a time in call order. Once `close()` has started, `run`
5
+ * rejects at once with `<name>: the database is closed`; `close()` itself queues behind every
6
+ * earlier call, closes the engine once, and returns the same promise to every later caller.
7
+ */
8
+ export type DbCallQueue = {
9
+ run<T>(fn: () => T | Promise<T>): Promise<T>;
10
+ close(): Promise<void>;
11
+ };
12
+
13
+ export function newDbCallQueue(name: string, closeEngine: () => void | Promise<void>): DbCallQueue {
14
+ let tail: Promise<unknown> = Promise.resolve();
15
+ let closing: Promise<void> | undefined;
16
+ const enqueue = <T>(fn: () => T | Promise<T>): Promise<T> => {
17
+ const result = tail.then(fn);
18
+ tail = result.catch(() => undefined);
19
+ return result;
20
+ };
21
+ return {
22
+ run: (fn) =>
23
+ closing ? Promise.reject(new Error(`${name}: the database is closed`)) : enqueue(fn),
24
+ close: () => {
25
+ closing ??= enqueue(closeEngine);
26
+ return closing;
27
+ },
28
+ };
29
+ }
30
+
31
+ const MIN_SAFE = BigInt(Number.MIN_SAFE_INTEGER);
32
+ const MAX_SAFE = BigInt(Number.MAX_SAFE_INTEGER);
33
+
34
+ const isPlainObject = (value: object): boolean => {
35
+ const proto = Object.getPrototypeOf(value);
36
+ return proto === Object.prototype || proto === null;
37
+ };
38
+
39
+ /** A bigint within ±(2^53 - 1) as a number; arrays and plain objects converted in place. */
40
+ function safeInteger(value: unknown): unknown {
41
+ if (typeof value === "bigint") {
42
+ return value >= MIN_SAFE && value <= MAX_SAFE ? Number(value) : value;
43
+ }
44
+ if (Array.isArray(value)) {
45
+ for (let i = 0; i < value.length; i++) value[i] = safeInteger(value[i]);
46
+ } else if (value !== null && typeof value === "object" && isPlainObject(value)) {
47
+ const record = value as Record<string, unknown>;
48
+ for (const key in record) record[key] = safeInteger(record[key]);
49
+ }
50
+ return value;
51
+ }
52
+
53
+ /**
54
+ * Integers within ±(2^53 - 1) become numbers, larger ones stay bigints (no precision loss), in
55
+ * every column and inside list, struct and map values. The rows are converted in place.
56
+ */
57
+ export function toSafeIntegers<T extends Record<string, unknown>>(rows: T[]): T[] {
58
+ for (const row of rows) {
59
+ const record = row as Record<string, unknown>;
60
+ for (const key in record) record[key] = safeInteger(record[key]);
61
+ }
62
+ return rows;
63
+ }
64
+
65
+ /**
66
+ * The asynchronous engine a driver wraps with {@link newSerialisedDb}. It is called one call at a
67
+ * time and never after `close`; `query` returns rows with integers as numbers or bigints (the
68
+ * wrapper turns safe bigints into numbers).
69
+ */
70
+ export type SerialisedDbEngine = {
71
+ query(sql: string, params: unknown[]): Promise<Record<string, unknown>[]>;
72
+ exec(sql: string): Promise<void>;
73
+ flush?(): Promise<void>;
74
+ close(): void | Promise<void>;
75
+ };
76
+
77
+ /**
78
+ * Wrap an engine as a `Db` that keeps the lifecycle every driver shares: calls run one at a time,
79
+ * in call order; `close()` waits for the calls made before it, then closes the engine; calls made
80
+ * once `close()` has started reject with `<name>: the database is closed`; closing twice is a
81
+ * no-op. Integers come back as numbers when safe and as bigints beyond (see
82
+ * {@link toSafeIntegers}). `name` prefixes the error, e.g. `"db-pglite"`.
83
+ */
84
+ export function newSerialisedDb(engine: SerialisedDbEngine, options: { name: string }): Db {
85
+ const queue = newDbCallQueue(options.name, () => engine.close());
86
+ const db: Db = {
87
+ query: <T = DbEntry>(sql: string, params: unknown[] = []) =>
88
+ queue.run(async () => toSafeIntegers(await engine.query(sql, params)) as T[]),
89
+ exec: (sql: string) => queue.run(() => engine.exec(sql)),
90
+ close: () => queue.close(),
91
+ };
92
+ const flush = engine.flush?.bind(engine);
93
+ if (flush) db.flush = () => queue.run(flush);
94
+ return db;
95
+ }
@@ -1,13 +1,15 @@
1
1
  import type { Db, DbEntry } from "@statewalker/db-api";
2
+ import { newDbCallQueue, toSafeIntegers } from "./serialised-db.js";
2
3
  import { countSqlStatements, firstSqlStatement } from "./sql-statements.js";
3
4
  import { SQLITE_TRANSACTION, type SqliteTransactionHook } from "./sqlite-transaction.js";
4
5
 
5
6
  /**
6
7
  * The synchronous engine a SQLite driver wraps. `all` returns rows (BLOBs as Uint8Array; integers
7
8
  * as numbers or bigints, which the wrapper turns into numbers when they are safe) and is given
8
- * exactly one non-empty statement and parameters already normalised (no boolean, undefined or
9
- * Date); `exec` runs every statement of a non-empty string. `transaction`, when present, replaces
10
- * `BEGIN IMMEDIATE`/`COMMIT`/`ROLLBACK` (Durable Objects forbid them in SQL).
9
+ * exactly one non-empty statement and parameters already normalised and checked (only null,
10
+ * number, bigint, string and Uint8Array); `exec` runs every statement of a non-empty string.
11
+ * `transaction`, when present, replaces `BEGIN IMMEDIATE`/`COMMIT`/`ROLLBACK` (Durable Objects
12
+ * forbid them in SQL).
11
13
  */
12
14
  export type SqliteEngine = {
13
15
  all(sql: string, params: unknown[]): Record<string, unknown>[];
@@ -16,15 +18,6 @@ export type SqliteEngine = {
16
18
  transaction?<T>(fn: () => Promise<T>): Promise<T>;
17
19
  };
18
20
 
19
- function newLock() {
20
- let tail: Promise<unknown> = Promise.resolve();
21
- return <T>(fn: () => Promise<T>): Promise<T> => {
22
- const run = tail.then(fn);
23
- tail = run.catch(() => undefined);
24
- return run;
25
- };
26
- }
27
-
28
21
  const EMPTY_SQL = "db-sqlite: the SQL is empty (only whitespace, comments or semicolons)";
29
22
  const MANY_STATEMENTS =
30
23
  "db-sqlite: query runs one statement, and this SQL has more after the first; " +
@@ -37,8 +30,23 @@ function checkSql(sql: string, one: boolean): void {
37
30
  if (one && count === "many") throw new Error(MANY_STATEMENTS);
38
31
  }
39
32
 
40
- /** boolean → 1/0, undefined → NULL, Date → ISO 8601 UTC text; anything else is left as given. */
33
+ /** The type a rejected parameter is named by: `symbol`, `function`, or the object's class. */
34
+ function typeName(value: unknown): string {
35
+ if (typeof value !== "object" || value === null) return typeof value;
36
+ const name = (value as { constructor?: { name?: unknown } }).constructor?.name;
37
+ return typeof name === "string" && name ? name : "Object";
38
+ }
39
+
40
+ /**
41
+ * boolean → 1/0, undefined → NULL, Date → ISO 8601 UTC text, ArrayBuffer or any ArrayBuffer view →
42
+ * a Uint8Array over exactly its bytes; null, number, bigint and string are left as given. Anything
43
+ * else (a plain object, Map, array, function, symbol, boxed primitive) rejects: node:sqlite would
44
+ * take a leading object as named parameters and bind the rest one place to the left, and SQLite
45
+ * has no array type (bind a list as JSON text and read it with `json_each`).
46
+ */
41
47
  function toSqliteParam(value: unknown, index: number): unknown {
48
+ if (value === null || typeof value === "string" || typeof value === "number") return value;
49
+ if (typeof value === "bigint") return value;
42
50
  if (typeof value === "boolean") return value ? 1 : 0;
43
51
  if (value === undefined) return null;
44
52
  if (value instanceof Date) {
@@ -47,29 +55,28 @@ function toSqliteParam(value: unknown, index: number): unknown {
47
55
  }
48
56
  return value.toISOString();
49
57
  }
50
- return value;
51
- }
52
-
53
- const MIN_SAFE = BigInt(Number.MIN_SAFE_INTEGER);
54
- const MAX_SAFE = BigInt(Number.MAX_SAFE_INTEGER);
55
-
56
- /** Integers within ±(2^53 - 1) become numbers; larger ones stay bigints (no precision loss). */
57
- function fromSqliteRows(rows: Record<string, unknown>[]): Record<string, unknown>[] {
58
- for (const row of rows) {
59
- for (const key in row) {
60
- const value = row[key];
61
- if (typeof value === "bigint" && value >= MIN_SAFE && value <= MAX_SAFE) {
62
- row[key] = Number(value);
63
- }
64
- }
58
+ // node:sqlite (Node 22) binds a view over a buffer with no backing store (any zero-length
59
+ // ArrayBuffer) as NULL: give an empty value a fresh empty Uint8Array, which binds as a BLOB.
60
+ if ((ArrayBuffer.isView(value) || value instanceof ArrayBuffer) && value.byteLength === 0) {
61
+ return new Uint8Array(1).subarray(0, 0);
62
+ }
63
+ if (value instanceof Uint8Array && value.constructor === Uint8Array) return value;
64
+ if (ArrayBuffer.isView(value)) {
65
+ return new Uint8Array(value.buffer, value.byteOffset, value.byteLength);
65
66
  }
66
- return rows;
67
+ if (value instanceof ArrayBuffer) return new Uint8Array(value);
68
+ const hint = Array.isArray(value) ? "; bind a list as JSON text and read it with json_each" : "";
69
+ throw new TypeError(
70
+ `db-sqlite: parameter ${index + 1} has type ${typeName(value)}, which SQLite cannot bind; ` +
71
+ "pass null, undefined, a boolean, number, bigint, string, Date, ArrayBuffer or " +
72
+ `ArrayBuffer view${hint}`,
73
+ );
67
74
  }
68
75
 
69
76
  function runAll(engine: SqliteEngine, sql: string, params: unknown[]): Record<string, unknown>[] {
70
77
  checkSql(sql, true);
71
78
  // Only the statement itself reaches the engine: DO SQLite rejects an empty tail ("; -- c ;").
72
- return fromSqliteRows(engine.all(firstSqlStatement(sql), params.map(toSqliteParam)));
79
+ return toSafeIntegers(engine.all(firstSqlStatement(sql), params.map(toSqliteParam)));
73
80
  }
74
81
 
75
82
  function runExec(engine: SqliteEngine, sql: string): void {
@@ -78,18 +85,16 @@ function runExec(engine: SqliteEngine, sql: string): void {
78
85
  }
79
86
 
80
87
  /**
81
- * Wrap an engine as a `Db` whose calls run one at a time, in call order, and which carries the
82
- * `inTransaction` hook. Every SQLite driver gets the same input handling here: empty SQL rejects,
83
- * `query` rejects a second statement, parameters are normalised and safe integers come back as
84
- * numbers. The `tx` handed to a transaction callback bypasses the queue, has no hook
85
- * (so nesting is rejected) and rejects once its transaction has finished.
88
+ * Wrap an engine as a `Db` with the lifecycle of `newSerialisedDb` (calls run one at a time, in
89
+ * call order; `close()` waits for earlier calls; later calls reject with
90
+ * `db-sqlite: the database is closed`; closing twice is a no-op) and the `inTransaction` hook.
91
+ * Every SQLite driver gets the same input handling here: empty SQL rejects, `query` rejects a
92
+ * second statement, parameters are normalised (one SQLite cannot bind rejects) and safe integers come back as numbers. The `tx`
93
+ * handed to a transaction callback bypasses the queue, has no hook (so nesting is rejected) and
94
+ * rejects once its transaction has finished.
86
95
  */
87
96
  export function newSerialisedSqliteDb(engine: SqliteEngine): Db {
88
- const lock = newLock();
89
- let closed = false;
90
- const live = () => {
91
- if (closed) throw new Error("db-sqlite: the database is closed");
92
- };
97
+ const queue = newDbCallQueue("db-sqlite", () => engine.close());
93
98
  const runTransaction =
94
99
  engine.transaction?.bind(engine) ??
95
100
  (async <T>(fn: () => Promise<T>): Promise<T> => {
@@ -109,8 +114,7 @@ export function newSerialisedSqliteDb(engine: SqliteEngine): Db {
109
114
  });
110
115
 
111
116
  const transaction: SqliteTransactionHook = (cb) =>
112
- lock(async () => {
113
- live();
117
+ queue.run(async () => {
114
118
  let finished = false;
115
119
  const open = () => {
116
120
  if (finished) throw new Error("db-sqlite: the transaction is finished; use the outer Db");
@@ -137,21 +141,9 @@ export function newSerialisedSqliteDb(engine: SqliteEngine): Db {
137
141
 
138
142
  return {
139
143
  query: <T = DbEntry>(sql: string, params: unknown[] = []) =>
140
- lock(async () => {
141
- live();
142
- return runAll(engine, sql, params) as T[];
143
- }),
144
- exec: (sql: string) =>
145
- lock(async () => {
146
- live();
147
- runExec(engine, sql);
148
- }),
149
- close: () =>
150
- lock(async () => {
151
- if (closed) return;
152
- closed = true;
153
- engine.close();
154
- }),
144
+ queue.run(() => runAll(engine, sql, params) as T[]),
145
+ exec: (sql: string) => queue.run(() => runExec(engine, sql)),
146
+ close: () => queue.close(),
155
147
  [SQLITE_TRANSACTION]: transaction,
156
148
  } as Db;
157
149
  }