@statewalker/db-sqlite 0.1.2 → 0.1.4

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/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;
@@ -99,6 +162,31 @@ const KEYWORDS = {
99
162
  explain: EXPLAIN
100
163
  };
101
164
  const isIdChar = (c) => /[A-Za-z0-9_$]/.test(c) || c.charCodeAt(0) >= 128;
165
+ /** SQLite's whitespace (sqlite3Isspace): space, \t, \n, \v, \f, \r. */
166
+ const isSpace = (c) => c === " " || c === " " || c === "\n" || c === "\v" || c === "\f" || c === "\r";
167
+ /**
168
+ * The end (exclusive) of a variable token starting at `i` (`$`, `:`, `@` or `#`), as SQLite's
169
+ * tokenizer reads it: identifier characters and `::`, and the Tcl form `$name(…)`, which runs to
170
+ * the first `)` (included) or whitespace, quotes and semicolons included.
171
+ */
172
+ function variableEnd(sql, i) {
173
+ let j = i + 1;
174
+ let n = 0;
175
+ while (j < sql.length) {
176
+ const c = sql[j];
177
+ if (isIdChar(c)) {
178
+ n++;
179
+ j++;
180
+ } else if (c === "(" && n > 0) {
181
+ j++;
182
+ while (j < sql.length && !isSpace(sql[j]) && sql[j] !== ")") j++;
183
+ if (sql[j] === ")") j++;
184
+ break;
185
+ } else if (c === ":" && sql[j + 1] === ":") j += 2;
186
+ else break;
187
+ }
188
+ return j;
189
+ }
102
190
  function countSqlStatements(sql) {
103
191
  return scanSqlStatements(sql).count;
104
192
  }
@@ -112,18 +200,44 @@ function firstSqlStatement(sql) {
112
200
  const { firstEnd } = scanSqlStatements(sql);
113
201
  return firstEnd < 0 ? sql : sql.slice(0, firstEnd);
114
202
  }
203
+ /**
204
+ * The first word of every statement of `sql`, lowercased, in order ("" for a statement that does
205
+ * not start with a word, such as `(SELECT 1)`). Statements are split as SQLite splits them, so a
206
+ * keyword inside a literal, a comment or a trigger body is not a head. Empty statements are
207
+ * skipped.
208
+ */
209
+ function sqlStatementHeads(sql) {
210
+ return scanSqlStatements(sql).heads;
211
+ }
212
+ /**
213
+ * The statements of `sql`, split as {@link sqlStatementHeads} splits them: each from its first
214
+ * token to just before the semicolon that ends it (the last to the end of the text).
215
+ */
216
+ function splitSqlStatements(sql) {
217
+ return scanSqlStatements(sql).statements;
218
+ }
115
219
  function scanSqlStatements(sql) {
220
+ const heads = [];
221
+ const statements = [];
222
+ let start = 0;
116
223
  let firstEnd = -1;
117
224
  let state = 0;
118
- let content = false;
119
- let firstEnded = false;
225
+ let inStatement = false;
120
226
  let i = 0;
121
227
  const n = sql.length;
228
+ const result = () => ({
229
+ count: heads.length === 0 ? "empty" : heads.length === 1 ? "one" : "many",
230
+ firstEnd,
231
+ heads,
232
+ statements: inStatement ? [...statements, sql.slice(start)] : statements
233
+ });
122
234
  while (i < n) {
123
235
  const c = sql[i];
236
+ const tokenStart = i;
124
237
  let token;
238
+ let word = "";
125
239
  if (c === ";") token = SEMI;
126
- else if (c === " " || c === " " || c === "\n" || c === "\r" || c === "\f") token = WS;
240
+ else if (isSpace(c)) token = WS;
127
241
  else if (c === "/" && sql[i + 1] === "*") {
128
242
  const close = sql.indexOf("*/", i + 2);
129
243
  if (close < 0) break;
@@ -136,41 +250,50 @@ function scanSqlStatements(sql) {
136
250
  token = WS;
137
251
  } else if (c === "[" || c === "`" || c === "\"" || c === "'") {
138
252
  const close = sql.indexOf(c === "[" ? "]" : c, i + 1);
139
- if (close < 0) return {
140
- count: firstEnded ? "many" : "one",
141
- firstEnd
142
- };
253
+ if (close < 0) {
254
+ if (!inStatement) {
255
+ heads.push("");
256
+ start = tokenStart;
257
+ inStatement = true;
258
+ }
259
+ return result();
260
+ }
143
261
  i = close;
144
262
  token = OTHER;
263
+ } else if (c === "$" || c === ":" || c === "@" || c === "#") {
264
+ i = variableEnd(sql, i) - 1;
265
+ token = OTHER;
145
266
  } else if (isIdChar(c)) {
146
267
  let j = i + 1;
147
268
  while (j < n && isIdChar(sql[j])) j++;
148
- token = KEYWORDS[sql.slice(i, j).toLowerCase()] ?? OTHER;
269
+ word = sql.slice(i, j).toLowerCase();
270
+ token = KEYWORDS[word] ?? OTHER;
149
271
  i = j - 1;
150
272
  } else token = OTHER;
151
- if (token !== SEMI && token !== WS) {
152
- if (firstEnded) return {
153
- count: "many",
154
- firstEnd
155
- };
156
- content = true;
273
+ if (token !== SEMI && token !== WS && !inStatement) {
274
+ inStatement = true;
275
+ heads.push(word);
276
+ start = tokenStart;
157
277
  }
158
278
  state = TRANS[state]?.[token] ?? 2;
159
- if (token === SEMI && state === 1 && content && !firstEnded) {
160
- firstEnded = true;
161
- firstEnd = i;
279
+ if (token === SEMI && state === 1 && inStatement) {
280
+ inStatement = false;
281
+ statements.push(sql.slice(start, i));
282
+ if (firstEnd < 0) firstEnd = i;
162
283
  }
163
284
  i++;
164
285
  }
165
- return {
166
- count: content ? "one" : "empty",
167
- firstEnd
168
- };
286
+ return result();
169
287
  }
170
288
  //#endregion
171
289
  //#region src/sqlite-transaction.ts
172
290
  /** Key under which a SQLite Db carries its transaction hook. Shared across bundles via Symbol.for. */
173
291
  const SQLITE_TRANSACTION = Symbol.for("@statewalker/db-sqlite:transaction");
292
+ /**
293
+ * Key under which a SQLite Db carries its read-only transaction hook (a separate key, so that a Db
294
+ * from an older db-sqlite, which has only the committing hook, is refused rather than committed).
295
+ */
296
+ const SQLITE_READ_ONLY_TRANSACTION = Symbol.for("@statewalker/db-sqlite:read-only-transaction");
174
297
  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).";
175
298
  /**
176
299
  * Run `cb` in one SQLite transaction: every statement issued through `tx` commits together, or
@@ -182,16 +305,27 @@ function inTransaction(db, cb) {
182
305
  if (typeof hook !== "function") return Promise.reject(/* @__PURE__ */ new Error(NO_HOOK));
183
306
  return hook(cb);
184
307
  }
308
+ const NO_READ_ONLY_HOOK = "inReadOnlyTransaction: this Db has no SQLite read-only transaction hook. It is not a @statewalker/db-sqlite* Db (or one from a db-sqlite older than 0.1.4), 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).";
309
+ /**
310
+ * Run `cb` in one SQLite transaction that is always rolled back: `tx` sees the committed data and
311
+ * its own writes, and nothing it writes persists, whether `cb` returns (its value is returned) or
312
+ * throws (its error is rethrown). Statements that would end the transaction or reach outside it
313
+ * (BEGIN, COMMIT, END, ROLLBACK, SAVEPOINT, RELEASE, ATTACH, DETACH, PRAGMA, VACUUM) are refused,
314
+ * and once a statement fails, `tx` refuses every later call (SQLite may have ended the transaction
315
+ * itself, as `INSERT OR ROLLBACK` does). Other calls on `db` wait until it ends. `cb` must not do
316
+ * external I/O and must be idempotent: a Durable Object may run it more than once.
317
+ */
318
+ function inReadOnlyTransaction(db, cb) {
319
+ const hook = db[SQLITE_READ_ONLY_TRANSACTION];
320
+ if (typeof hook !== "function") return Promise.reject(/* @__PURE__ */ new Error(NO_READ_ONLY_HOOK));
321
+ return hook(cb);
322
+ }
323
+ /** Whether `db` carries the hook {@link inReadOnlyTransaction} needs. */
324
+ function hasReadOnlyTransaction(db) {
325
+ return typeof db[SQLITE_READ_ONLY_TRANSACTION] === "function";
326
+ }
185
327
  //#endregion
186
328
  //#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
329
  const EMPTY_SQL = "db-sqlite: the SQL is empty (only whitespace, comments or semicolons)";
196
330
  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
331
  function checkSql(sql, one) {
@@ -200,47 +334,76 @@ function checkSql(sql, one) {
200
334
  if (count === "empty") throw new Error(EMPTY_SQL);
201
335
  if (one && count === "many") throw new Error(MANY_STATEMENTS);
202
336
  }
203
- /** boolean → 1/0, undefined → NULL, Date → ISO 8601 UTC text; anything else is left as given. */
337
+ /** The type a rejected parameter is named by: `symbol`, `function`, or the object's class. */
338
+ function typeName(value) {
339
+ if (typeof value !== "object" || value === null) return typeof value;
340
+ const name = value.constructor?.name;
341
+ return typeof name === "string" && name ? name : "Object";
342
+ }
343
+ /**
344
+ * boolean → 1/0, undefined → NULL, Date → ISO 8601 UTC text, ArrayBuffer or any ArrayBuffer view →
345
+ * a Uint8Array over exactly its bytes; null, number, bigint and string are left as given. Anything
346
+ * else (a plain object, Map, array, function, symbol, boxed primitive) rejects: node:sqlite would
347
+ * take a leading object as named parameters and bind the rest one place to the left, and SQLite
348
+ * has no array type (bind a list as JSON text and read it with `json_each`).
349
+ */
204
350
  function toSqliteParam(value, index) {
351
+ if (value === null || typeof value === "string" || typeof value === "number") return value;
352
+ if (typeof value === "bigint") return value;
205
353
  if (typeof value === "boolean") return value ? 1 : 0;
206
354
  if (value === void 0) return null;
207
355
  if (value instanceof Date) {
208
356
  if (Number.isNaN(value.getTime())) throw new RangeError(`db-sqlite: parameter ${index + 1} is an invalid Date`);
209
357
  return value.toISOString();
210
358
  }
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;
359
+ if ((ArrayBuffer.isView(value) || value instanceof ArrayBuffer) && value.byteLength === 0) return (/* @__PURE__ */ new Uint8Array(1)).subarray(0, 0);
360
+ if (value instanceof Uint8Array && value.constructor === Uint8Array) return value;
361
+ if (ArrayBuffer.isView(value)) return new Uint8Array(value.buffer, value.byteOffset, value.byteLength);
362
+ if (value instanceof ArrayBuffer) return new Uint8Array(value);
363
+ const hint = Array.isArray(value) ? "; bind a list as JSON text and read it with json_each" : "";
364
+ 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
365
  }
223
366
  function runAll(engine, sql, params) {
224
367
  checkSql(sql, true);
225
- return fromSqliteRows(engine.all(firstSqlStatement(sql), params.map(toSqliteParam)));
368
+ return toSafeIntegers(engine.all(firstSqlStatement(sql), params.map(toSqliteParam)));
226
369
  }
227
370
  function runExec(engine, sql) {
228
371
  checkSql(sql, false);
229
372
  engine.exec(sql);
230
373
  }
374
+ /** Statements a read-only transaction refuses: they end it, or reach outside it. */
375
+ const READ_ONLY_REFUSED = /* @__PURE__ */ new Set([
376
+ "begin",
377
+ "commit",
378
+ "end",
379
+ "rollback",
380
+ "savepoint",
381
+ "release",
382
+ "attach",
383
+ "detach",
384
+ "pragma",
385
+ "vacuum"
386
+ ]);
387
+ function checkReadOnly(sql) {
388
+ if (typeof sql !== "string") return;
389
+ for (const head of sqlStatementHeads(sql)) {
390
+ if (head === "") throw new Error("db-sqlite: a read-only transaction refuses a statement that does not start with a keyword");
391
+ if (READ_ONLY_REFUSED.has(head)) throw new Error(`db-sqlite: a read-only transaction refuses ${head.toUpperCase()} (it would end the transaction or reach outside it)`);
392
+ }
393
+ }
394
+ const READ_ONLY_FAILED = "db-sqlite: a statement of this read-only transaction failed, so it refuses later calls (SQLite may have ended the transaction)";
395
+ const ROLLBACK_ON_PURPOSE = "db-sqlite: the read-only transaction is rolled back";
231
396
  /**
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.
397
+ * Wrap an engine as a `Db` with the lifecycle of `newSerialisedDb` (calls run one at a time, in
398
+ * call order; `close()` waits for earlier calls; later calls reject with
399
+ * `db-sqlite: the database is closed`; closing twice is a no-op) and the `inTransaction` hook.
400
+ * Every SQLite driver gets the same input handling here: empty SQL rejects, `query` rejects a
401
+ * second statement, parameters are normalised (one SQLite cannot bind rejects) and safe integers come back as numbers. The `tx`
402
+ * handed to a transaction callback bypasses the queue, has no hook (so nesting is rejected) and
403
+ * rejects once its transaction has finished.
237
404
  */
238
405
  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
- };
406
+ const queue = newDbCallQueue("db-sqlite", () => engine.close());
244
407
  const runTransaction = engine.transaction?.bind(engine) ?? (async (fn) => {
245
408
  engine.exec("BEGIN IMMEDIATE");
246
409
  try {
@@ -254,49 +417,89 @@ function newSerialisedSqliteDb(engine) {
254
417
  throw error;
255
418
  }
256
419
  });
257
- const transaction = (cb) => lock(async () => {
258
- live();
420
+ const platformTransaction = engine.transaction?.bind(engine);
421
+ const runReadOnlyTransaction = platformTransaction ? async (fn) => {
422
+ let result;
423
+ let returned = false;
424
+ try {
425
+ await platformTransaction(async () => {
426
+ returned = false;
427
+ result = await fn();
428
+ returned = true;
429
+ throw new Error(ROLLBACK_ON_PURPOSE);
430
+ });
431
+ } catch (error) {
432
+ if (returned && error instanceof Error && error.message === ROLLBACK_ON_PURPOSE) return result;
433
+ throw error;
434
+ }
435
+ throw new Error("db-sqlite: the platform did not roll back the read-only transaction");
436
+ } : async (fn) => {
437
+ const rollback = () => {
438
+ try {
439
+ engine.exec("ROLLBACK");
440
+ } catch (error) {
441
+ if (!/no transaction is active/i.test(String(error?.message))) throw error;
442
+ }
443
+ };
444
+ engine.exec("BEGIN");
445
+ let result;
446
+ try {
447
+ result = await fn();
448
+ } catch (error) {
449
+ rollback();
450
+ throw error;
451
+ }
452
+ rollback();
453
+ return result;
454
+ };
455
+ const newTransactionHook = (readOnly) => (cb) => queue.run(async () => {
259
456
  let finished = false;
260
- const open = () => {
457
+ let failed = false;
458
+ const run = (fn) => {
261
459
  if (finished) throw new Error("db-sqlite: the transaction is finished; use the outer Db");
460
+ if (!readOnly) return fn();
461
+ if (failed) throw new Error(READ_ONLY_FAILED);
462
+ try {
463
+ return fn();
464
+ } catch (error) {
465
+ failed = true;
466
+ throw error;
467
+ }
262
468
  };
263
469
  const tx = {
264
470
  async query(sql, params = []) {
265
- open();
266
- return runAll(engine, sql, params);
471
+ return run(() => {
472
+ if (readOnly) checkReadOnly(sql);
473
+ return runAll(engine, sql, params);
474
+ });
267
475
  },
268
476
  async exec(sql) {
269
- open();
270
- runExec(engine, sql);
477
+ run(() => {
478
+ if (!readOnly) return runExec(engine, sql);
479
+ checkReadOnly(sql);
480
+ checkSql(sql, false);
481
+ for (const statement of splitSqlStatements(sql)) runAll(engine, statement, []);
482
+ });
271
483
  },
272
484
  async close() {
273
485
  throw new Error("db-sqlite: close the outer Db, not the transaction handle");
274
486
  }
275
487
  };
276
488
  try {
277
- return await runTransaction(() => cb(tx));
489
+ return await (readOnly ? runReadOnlyTransaction : runTransaction)(() => cb(tx));
278
490
  } finally {
279
491
  finished = true;
280
492
  }
281
493
  });
282
494
  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
- }),
296
- [SQLITE_TRANSACTION]: transaction
495
+ query: (sql, params = []) => queue.run(() => runAll(engine, sql, params)),
496
+ exec: (sql) => queue.run(() => runExec(engine, sql)),
497
+ close: () => queue.close(),
498
+ [SQLITE_TRANSACTION]: newTransactionHook(false),
499
+ [SQLITE_READ_ONLY_TRANSACTION]: newTransactionHook(true)
297
500
  };
298
501
  }
299
502
  //#endregion
300
- export { SQLITE_TRANSACTION, inTransaction, newSerialisedSqliteDb };
503
+ export { SQLITE_READ_ONLY_TRANSACTION, SQLITE_TRANSACTION, hasReadOnlyTransaction, inReadOnlyTransaction, inTransaction, newSerialisedDb, newSerialisedSqliteDb };
301
504
 
302
505
  //# 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;CACZ;EAAC;EAAG;EAAG;EAAG;EAAG;EAAG;EAAG;EAAG;CAAC;CACvB;EAAC;EAAG;EAAG;EAAG;EAAG;EAAG;EAAG;EAAG;CAAC;CACvB;EAAC;EAAG;EAAG;EAAG;EAAG;EAAG;EAAG;EAAG;CAAC;CACvB;EAAC;EAAG;EAAG;EAAG;EAAG;EAAG;EAAG;EAAG;CAAC;CACvB;EAAC;EAAG;EAAG;EAAG;EAAG;EAAG;EAAG;EAAG;CAAC;CACvB;EAAC;EAAG;EAAG;EAAG;EAAG;EAAG;EAAG;EAAG;CAAC;CACvB;EAAC;EAAG;EAAG;EAAG;EAAG;EAAG;EAAG;EAAG;CAAC;CACvB;EAAC;EAAG;EAAG;EAAG;EAAG;EAAG;EAAG;EAAG;CAAC;AACzB;AAEA,MAAM,WAAmC;CACvC,QAAQ;CACR,MAAM;CACN,WAAW;CACX,SAAS;CACT,KAAK;CACL,SAAS;AACX;AAEA,MAAM,YAAY,MAAc,gBAAgB,KAAK,CAAC,KAAK,EAAE,WAAW,CAAC,KAAK;AAE9E,SAAgB,mBAAmB,KAAgC;CACjE,OAAO,kBAAkB,GAAG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Q,QAAQ,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,KAAK,YAAY;GACf,KAAK;GACL,OAAO,OAAO,QAAQ,KAAK,MAAM;EACnC,CAAC;EACH,OAAO,QACL,KAAK,YAAY;GACf,KAAK;GACL,QAAQ,QAAQ,GAAG;EACrB,CAAC;EACH,aACE,KAAK,YAAY;GACf,IAAI,QAAQ;GACZ,SAAS;GACT,OAAO,MAAM;EACf,CAAC;GACF,qBAAqB;CACxB;AACF"}
1
+ {"version":3,"file":"index.mjs","names":[],"sources":["../src/serialised-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\n/** SQLite's whitespace (sqlite3Isspace): space, \\t, \\n, \\v, \\f, \\r. */\nconst isSpace = (c: string | undefined) =>\n c === \" \" || c === \"\\t\" || c === \"\\n\" || c === \"\\v\" || c === \"\\f\" || c === \"\\r\";\n\n/**\n * The end (exclusive) of a variable token starting at `i` (`$`, `:`, `@` or `#`), as SQLite's\n * tokenizer reads it: identifier characters and `::`, and the Tcl form `$name(…)`, which runs to\n * the first `)` (included) or whitespace, quotes and semicolons included.\n */\nfunction variableEnd(sql: string, i: number): number {\n let j = i + 1;\n let n = 0;\n while (j < sql.length) {\n const c = sql[j] as string;\n if (isIdChar(c)) {\n n++;\n j++;\n } else if (c === \"(\" && n > 0) {\n j++;\n while (j < sql.length && !isSpace(sql[j]) && sql[j] !== \")\") j++;\n if (sql[j] === \")\") j++;\n break;\n } else if (c === \":\" && sql[j + 1] === \":\") {\n j += 2;\n } else {\n break;\n }\n }\n return j;\n}\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\n/**\n * The first word of every statement of `sql`, lowercased, in order (\"\" for a statement that does\n * not start with a word, such as `(SELECT 1)`). Statements are split as SQLite splits them, so a\n * keyword inside a literal, a comment or a trigger body is not a head. Empty statements are\n * skipped.\n */\nexport function sqlStatementHeads(sql: string): string[] {\n return scanSqlStatements(sql).heads;\n}\n\n/**\n * The statements of `sql`, split as {@link sqlStatementHeads} splits them: each from its first\n * token to just before the semicolon that ends it (the last to the end of the text).\n */\nexport function splitSqlStatements(sql: string): string[] {\n return scanSqlStatements(sql).statements;\n}\n\nfunction scanSqlStatements(sql: string): {\n count: SqlStatementCount;\n firstEnd: number;\n heads: string[];\n statements: string[];\n} {\n const heads: string[] = [];\n const statements: string[] = [];\n let start = 0; // where the current statement's first token starts\n let firstEnd = -1; // index of the \";\" that ends the first statement\n let state = 0;\n let inStatement = false; // a token other than whitespace or \";\" was seen since the last end\n let i = 0;\n const n = sql.length;\n const result = () => ({\n count: (heads.length === 0\n ? \"empty\"\n : heads.length === 1\n ? \"one\"\n : \"many\") as SqlStatementCount,\n firstEnd,\n heads,\n statements: inStatement ? [...statements, sql.slice(start)] : statements,\n });\n while (i < n) {\n const c = sql[i] as string;\n const tokenStart = i;\n let token: number;\n let word = \"\";\n if (c === \";\") {\n token = SEMI;\n } else if (isSpace(c)) {\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) {\n // An unterminated literal runs to the end: content, which SQLite reports as an error.\n if (!inStatement) {\n heads.push(\"\");\n start = tokenStart;\n inStatement = true;\n }\n return result();\n }\n i = close;\n token = OTHER;\n } else if (c === \"$\" || c === \":\" || c === \"@\" || c === \"#\") {\n // A variable, not a word: SQLite reads `$a(';x')` as one token, quotes and all.\n i = variableEnd(sql, i) - 1;\n token = OTHER;\n } else if (isIdChar(c)) {\n let j = i + 1;\n while (j < n && isIdChar(sql[j] as string)) j++;\n word = sql.slice(i, j).toLowerCase();\n token = KEYWORDS[word] ?? OTHER;\n i = j - 1;\n } else {\n token = OTHER;\n }\n if (token !== SEMI && token !== WS && !inStatement) {\n inStatement = true;\n heads.push(word);\n start = tokenStart;\n }\n state = TRANS[state]?.[token] ?? 2;\n if (token === SEMI && state === 1 && inStatement) {\n inStatement = false;\n statements.push(sql.slice(start, i));\n if (firstEnd < 0) firstEnd = i;\n }\n i++;\n }\n return result();\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/**\n * Key under which a SQLite Db carries its read-only transaction hook (a separate key, so that a Db\n * from an older db-sqlite, which has only the committing hook, is refused rather than committed).\n */\nexport const SQLITE_READ_ONLY_TRANSACTION: unique symbol = Symbol.for(\n \"@statewalker/db-sqlite:read-only-transaction\",\n);\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\nconst NO_READ_ONLY_HOOK =\n \"inReadOnlyTransaction: this Db has no SQLite read-only transaction hook. It is not a \" +\n \"@statewalker/db-sqlite* Db (or one from a db-sqlite older than 0.1.4), \" +\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 that is always rolled back: `tx` sees the committed data and\n * its own writes, and nothing it writes persists, whether `cb` returns (its value is returned) or\n * throws (its error is rethrown). Statements that would end the transaction or reach outside it\n * (BEGIN, COMMIT, END, ROLLBACK, SAVEPOINT, RELEASE, ATTACH, DETACH, PRAGMA, VACUUM) are refused,\n * and once a statement fails, `tx` refuses every later call (SQLite may have ended the transaction\n * itself, as `INSERT OR ROLLBACK` does). Other calls on `db` wait until it 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 inReadOnlyTransaction<T>(db: Db, cb: (tx: Db) => Promise<T>): Promise<T> {\n const hook = (db as { [SQLITE_READ_ONLY_TRANSACTION]?: SqliteTransactionHook })[\n SQLITE_READ_ONLY_TRANSACTION\n ];\n if (typeof hook !== \"function\") return Promise.reject(new Error(NO_READ_ONLY_HOOK));\n return hook(cb);\n}\n\n/** Whether `db` carries the hook {@link inReadOnlyTransaction} needs. */\nexport function hasReadOnlyTransaction(db: Db): boolean {\n return (\n typeof (db as { [SQLITE_READ_ONLY_TRANSACTION]?: unknown })[SQLITE_READ_ONLY_TRANSACTION] ===\n \"function\"\n );\n}\n","import type { Db, DbEntry } from \"@statewalker/db-api\";\nimport { newDbCallQueue, toSafeIntegers } from \"./serialised-db.js\";\nimport {\n countSqlStatements,\n firstSqlStatement,\n splitSqlStatements,\n sqlStatementHeads,\n} from \"./sql-statements.js\";\nimport {\n SQLITE_READ_ONLY_TRANSACTION,\n SQLITE_TRANSACTION,\n type SqliteTransactionHook,\n} 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/** Statements a read-only transaction refuses: they end it, or reach outside it. */\nconst READ_ONLY_REFUSED = new Set([\n \"begin\",\n \"commit\",\n \"end\",\n \"rollback\",\n \"savepoint\",\n \"release\",\n \"attach\",\n \"detach\",\n \"pragma\",\n \"vacuum\",\n]);\n\nfunction checkReadOnly(sql: string): void {\n if (typeof sql !== \"string\") return; // checkSql reports it\n for (const head of sqlStatementHeads(sql)) {\n // A statement that does not start with a word is refused too: where this scanner and SQLite\n // could disagree on where a statement starts, the word SQLite sees is never checked.\n if (head === \"\") {\n throw new Error(\n \"db-sqlite: a read-only transaction refuses a statement that does not start with a keyword\",\n );\n }\n if (READ_ONLY_REFUSED.has(head)) {\n throw new Error(\n `db-sqlite: a read-only transaction refuses ${head.toUpperCase()} ` +\n \"(it would end the transaction or reach outside it)\",\n );\n }\n }\n}\n\nconst READ_ONLY_FAILED =\n \"db-sqlite: a statement of this read-only transaction failed, so it refuses later calls \" +\n \"(SQLite may have ended the transaction)\";\nconst ROLLBACK_ON_PURPOSE = \"db-sqlite: the read-only transaction is rolled back\";\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 platformTransaction = engine.transaction?.bind(engine);\n const runReadOnlyTransaction = platformTransaction\n ? async <T>(fn: () => Promise<T>): Promise<T> => {\n // The platform commits when the closure returns: throw to make it roll back.\n let result: T | undefined;\n let returned = false;\n try {\n await platformTransaction(async () => {\n returned = false;\n result = await fn();\n returned = true;\n throw new Error(ROLLBACK_ON_PURPOSE);\n });\n } catch (error) {\n if (returned && error instanceof Error && error.message === ROLLBACK_ON_PURPOSE) {\n return result as T;\n }\n throw error;\n }\n throw new Error(\"db-sqlite: the platform did not roll back the read-only transaction\");\n }\n : async <T>(fn: () => Promise<T>): Promise<T> => {\n // A ROLLBACK that fails for any reason but \"no transaction\" (SQLite ended it itself, as\n // INSERT OR ROLLBACK does: nothing to undo) leaves the transaction open: report it.\n const rollback = () => {\n try {\n engine.exec(\"ROLLBACK\");\n } catch (error) {\n if (!/no transaction is active/i.test(String((error as Error)?.message))) throw error;\n }\n };\n engine.exec(\"BEGIN\");\n let result: T;\n try {\n result = await fn();\n } catch (error) {\n rollback();\n throw error;\n }\n rollback();\n return result;\n };\n\n const newTransactionHook =\n (readOnly: boolean): SqliteTransactionHook =>\n (cb) =>\n queue.run(async () => {\n let finished = false;\n let failed = false;\n const run = <R>(fn: () => R): R => {\n if (finished) throw new Error(\"db-sqlite: the transaction is finished; use the outer Db\");\n if (!readOnly) return fn();\n if (failed) throw new Error(READ_ONLY_FAILED);\n try {\n return fn();\n } catch (error) {\n failed = true;\n throw error;\n }\n };\n const tx: Db = {\n async query<T = DbEntry>(sql: string, params: unknown[] = []): Promise<T[]> {\n return run(() => {\n if (readOnly) checkReadOnly(sql);\n return runAll(engine, sql, params) as T[];\n });\n },\n async exec(sql: string): Promise<void> {\n run(() => {\n if (!readOnly) return runExec(engine, sql);\n checkReadOnly(sql);\n checkSql(sql, false);\n // One statement per engine call, through `all`, which runs exactly one (node:sqlite\n // compiles only the first): text the splitter might misread as part of a statement\n // never runs as a statement of its own, whatever it says.\n for (const statement of splitSqlStatements(sql)) runAll(engine, statement, []);\n });\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 (readOnly ? runReadOnlyTransaction : 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]: newTransactionHook(false),\n [SQLITE_READ_ONLY_TRANSACTION]: newTransactionHook(true),\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,OAAO,OAAO,YAAY,KAAA,CAAS;EACnC,OAAO;CACT;CACA,OAAO;EACL,MAAM,OACJ,UAAU,QAAQ,uBAAO,IAAI,MAAM,GAAG,KAAK,yBAAyB,CAAC,IAAI,QAAQ,EAAE;EACrF,aAAa;GACX,YAAY,QAAQ,WAAW;GAC/B,OAA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,KAA4B;IACrC,UAAU;KACR,IAAI,CAAC,UAAU,OAAO,QAAQ,QAAQ,GAAG;KACzC,cAAc,GAAG;KACjB,SAAS,KAAK,KAAK;KAInB,KAAK,MAAM,aAAa,mBAAmB,GAAG,GAAG,OAAO,QAAQ,WAAW,CAAC,CAAC;IAC/E,CAAC;GACH;GACA,MAAM,QAAuB;IAC3B,MAAM,IAAI,MAAM,2DAA2D;GAC7E;EACF;EACA,IAAI;GACF,OAAO,OAAO,WAAW,yBAAyB,eAAA,OAAsB,GAAG,EAAE,CAAC;EAChF,UAAU;GACR,WAAW;EACb;CACF,CAAC;CAEL,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,mBAAmB,KAAK;GAC7C,+BAA+B,mBAAmB,IAAI;CACzD;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.4",
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,9 +1,16 @@
1
+ export {
2
+ newSerialisedDb,
3
+ type SerialisedDbEngine,
4
+ } from "./serialised-db.js";
1
5
  export {
2
6
  newSerialisedSqliteDb,
3
7
  type SqliteEngine,
4
8
  } from "./serialised-sqlite-db.js";
5
9
  export {
10
+ hasReadOnlyTransaction,
11
+ inReadOnlyTransaction,
6
12
  inTransaction,
13
+ SQLITE_READ_ONLY_TRANSACTION,
7
14
  SQLITE_TRANSACTION,
8
15
  type SqliteTransactionHook,
9
16
  } from "./sqlite-transaction.js";