@procedures/sqlite 0.60.0 → 0.61.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. package/CHANGELOG.md +57 -0
  2. package/README.md +84 -183
  3. package/dist/engines.d.ts +31 -31
  4. package/dist/engines.d.ts.map +1 -1
  5. package/dist/engines.js +35 -78
  6. package/dist/engines.js.map +1 -1
  7. package/dist/index.d.ts +3 -5
  8. package/dist/index.d.ts.map +1 -1
  9. package/dist/index.js +3 -7
  10. package/dist/index.js.map +1 -1
  11. package/dist/load.d.ts +9 -0
  12. package/dist/load.d.ts.map +1 -0
  13. package/dist/load.js +11 -0
  14. package/dist/load.js.map +1 -0
  15. package/dist/module.d.ts.map +1 -1
  16. package/dist/module.js +104 -62
  17. package/dist/module.js.map +1 -1
  18. package/dist/procedures/db/backup.d.ts +5 -7
  19. package/dist/procedures/db/backup.d.ts.map +1 -1
  20. package/dist/procedures/db/backup.js +22 -27
  21. package/dist/procedures/db/backup.js.map +1 -1
  22. package/dist/procedures/db/migrate.d.ts +1 -1
  23. package/dist/procedures/db/migrate.d.ts.map +1 -1
  24. package/dist/procedures/db/migrate.js +32 -38
  25. package/dist/procedures/db/migrate.js.map +1 -1
  26. package/dist/procedures/db/schema.d.ts.map +1 -1
  27. package/dist/procedures/db/schema.js +8 -10
  28. package/dist/procedures/db/schema.js.map +1 -1
  29. package/dist/procedures/db/shared.d.ts +75 -10
  30. package/dist/procedures/db/shared.d.ts.map +1 -1
  31. package/dist/procedures/db/shared.js +148 -53
  32. package/dist/procedures/db/shared.js.map +1 -1
  33. package/dist/procedures/db/tables.d.ts.map +1 -1
  34. package/dist/procedures/db/tables.js +5 -7
  35. package/dist/procedures/db/tables.js.map +1 -1
  36. package/dist/procedures/db/transaction.d.ts +3 -4
  37. package/dist/procedures/db/transaction.d.ts.map +1 -1
  38. package/dist/procedures/db/transaction.js +18 -26
  39. package/dist/procedures/db/transaction.js.map +1 -1
  40. package/dist/storage.d.ts +18 -29
  41. package/dist/storage.d.ts.map +1 -1
  42. package/dist/storage.js +32 -118
  43. package/dist/storage.js.map +1 -1
  44. package/dist/types.d.ts +1 -1
  45. package/dist/types.d.ts.map +1 -1
  46. package/dist/types.js +1 -1
  47. package/dist/types.js.map +1 -1
  48. package/package.json +8 -10
  49. package/src/engines.ts +50 -132
  50. package/src/index.ts +3 -31
  51. package/src/load.ts +15 -0
  52. package/src/module.ts +128 -84
  53. package/src/procedures/db/backup.ts +21 -27
  54. package/src/procedures/db/migrate.ts +35 -40
  55. package/src/procedures/db/schema.ts +10 -12
  56. package/src/procedures/db/shared.ts +178 -50
  57. package/src/procedures/db/tables.ts +5 -7
  58. package/src/procedures/db/transaction.ts +17 -24
  59. package/src/storage.ts +39 -136
  60. package/src/types.ts +2 -2
@@ -1,23 +1,20 @@
1
1
  /**
2
2
  * sqlite.backup procedure (roadmap R44)
3
3
  *
4
- * A copy of a database in a new file. The package runs SQLite in WebAssembly (sql.js): the
5
- * database is in the memory of the module, and `VACUUM INTO` and the backup API write into the
6
- * file system of the module, not to the disk. So the procedure takes the image of the database
7
- * (`export()`, the serialized database) in the file queue of the database, where no other call
8
- * of this process changes it. It writes the image to a file next to the target, checks it with
9
- * `PRAGMA integrity_check`, and renames it.
4
+ * A copy of a database in a new file. The procedure writes the copy with `snapshot` of `@mark1russell7/sqlite` (`VACUUM
5
+ * INTO`) to a temporary file next to the target. It checks the copy with `PRAGMA integrity_check`, and renames it.
10
6
  *
7
+ * - The copy is one consistent state of the database, with the changes in its WAL file. Writers can continue during the
8
+ * copy.
9
+ * - The copy is compact: it has no free pages.
11
10
  * - The procedure does not replace a file, and it does not write the source.
12
- * - With `vacuum: true`, it compacts the copy (VACUUM on the copy): the result of `VACUUM INTO`.
13
11
  */
14
12
 
15
13
  import { existsSync } from "node:fs";
16
- import { rename, stat, unlink, writeFile } from "node:fs/promises";
14
+ import { rename, stat, unlink } from "node:fs/promises";
17
15
  import { resolve } from "node:path";
18
- import { query, withConnection } from "@mark1russell7/docker-sqlite";
19
16
  import type { DbBackupInput, DbBackupOutput } from "../../types.js";
20
- import { databasePath, requireDatabaseFile } from "./shared.js";
17
+ import { databasePath, withDatabase } from "./shared.js";
21
18
 
22
19
  /** The key of a file path: Windows file names do not depend on case. */
23
20
  function fileKey(path: string): string {
@@ -25,34 +22,31 @@ function fileKey(path: string): string {
25
22
  return process.platform === "win32" ? absolute.toLowerCase() : absolute;
26
23
  }
27
24
 
25
+ /** The error for a target that exists. */
26
+ function targetExists(target: string): NodeJS.ErrnoException {
27
+ const error = new Error(`sqlite.backup: the file exists already: ${target}. The procedure does not replace a file.`) as NodeJS.ErrnoException;
28
+ error.code = "EEXIST";
29
+ return error;
30
+ }
31
+
28
32
  /**
29
33
  * Copy a database to a new file
30
34
  */
31
35
  export async function dbBackup(input: DbBackupInput): Promise<DbBackupOutput> {
32
36
  const source = databasePath(input.dbPath);
33
- requireDatabaseFile("sqlite.backup", source);
34
37
  const target = resolve(input.to);
35
38
  if (source !== ":memory:" && fileKey(source) === fileKey(target)) {
36
39
  throw new Error("sqlite.backup: the copy cannot be the database file itself");
37
40
  }
38
- if (existsSync(target)) {
39
- const error = new Error(`sqlite.backup: the file exists already: ${target}. The procedure does not replace a file.`) as NodeJS.ErrnoException;
40
- error.code = "EEXIST";
41
- throw error;
42
- }
43
-
44
- const image = await withConnection({ dbPath: source }, (db) => db.export());
41
+ if (existsSync(target)) throw targetExists(target);
45
42
  const temporary = `${target}.${process.pid}.${Date.now()}.tmp`;
46
43
  try {
47
- await writeFile(temporary, image);
48
- if (input.vacuum) {
49
- // The VACUUM changes the copy only: withConnection saves it to the temporary file
50
- await withConnection({ dbPath: temporary }, (db) => db.run("VACUUM"));
51
- }
52
- const check = await withConnection({ dbPath: temporary }, (db) => query<{ integrity_check: string }>(db, "PRAGMA integrity_check").rows);
53
- const verdict = check.map((row) => row.integrity_check).join("; ");
54
- if (verdict !== "ok") throw new Error(`sqlite.backup: the copy is not valid: ${verdict}`);
55
- if (existsSync(target)) throw new Error(`sqlite.backup: the file exists already: ${target}. The procedure does not replace a file.`);
44
+ const read = { procedure: "sqlite.backup", missing: "error", queryOnly: false, callerSql: false } as const;
45
+ await withDatabase(source, read, (db, sqlite) => sqlite.snapshot(db, temporary));
46
+ const check = { procedure: "sqlite.backup", missing: "error", queryOnly: true, callerSql: false } as const;
47
+ const integrity = await withDatabase(temporary, check, (db, sqlite) => sqlite.checkIntegrity(db));
48
+ if (!integrity.ok) throw new Error(`sqlite.backup: the copy is not valid: ${integrity.problems.join("; ")}`);
49
+ if (existsSync(target)) throw targetExists(target);
56
50
  await rename(temporary, target);
57
51
  } catch (error) {
58
52
  await unlink(temporary).catch(() => undefined);
@@ -7,7 +7,7 @@
7
7
  * migration with the sha256 of its SQL.
8
8
  *
9
9
  * - The pending migrations run in one transaction: when one fails, none is applied.
10
- * - A second call applies nothing, and does not write the file.
10
+ * - A second call applies nothing, and does not change the file.
11
11
  * - The SQL of an applied migration must not change: a different sha256 is an error, and the
12
12
  * call applies nothing. (The sha256 reads line ends as LF, so a checkout with CRLF is the same.)
13
13
  * - A migration must not hold BEGIN, COMMIT or ROLLBACK: the procedure runs the transaction.
@@ -16,9 +16,8 @@
16
16
  import { createHash } from "node:crypto";
17
17
  import { readdir, readFile } from "node:fs/promises";
18
18
  import { join } from "node:path";
19
- import { query, withConnection } from "@mark1russell7/docker-sqlite";
20
19
  import { MIGRATION_TABLE_PATTERN, type DbMigrateInput, type DbMigrateOutput, type DbMigration } from "../../types.js";
21
- import { databasePath, runStatements } from "./shared.js";
20
+ import { databasePath, errorText, rowsOf, runStatements, withDatabase } from "./shared.js";
22
21
 
23
22
  /** The name of a migration file: a number, then "_" or "-", then a name, then ".sql". */
24
23
  const MIGRATION_FILE = /^(\d+)[_-](.+)\.sql$/i;
@@ -75,47 +74,43 @@ export async function dbMigrate(input: DbMigrateInput): Promise<DbMigrateOutput>
75
74
  if (!MIGRATION_TABLE_PATTERN.test(table)) throw new Error(`sqlite.migrate: the table name ${JSON.stringify(table)} is not valid`);
76
75
  const migrations = ordered(input.folder !== undefined ? await migrationsOfFolder(input.folder) : input.migrations!);
77
76
 
78
- return withConnection({ dbPath: databasePath(input.dbPath) }, (db) => {
79
- db.run("BEGIN");
77
+ const mode = { procedure: "sqlite.migrate", missing: "make", queryOnly: false, callerSql: true } as const;
78
+ return withDatabase(databasePath(input.dbPath), mode, (db, sqlite) => {
80
79
  try {
81
- db.run(
82
- `CREATE TABLE IF NOT EXISTS "${table}" (version INTEGER PRIMARY KEY, name TEXT NOT NULL, checksum TEXT NOT NULL, applied_at TEXT NOT NULL DEFAULT (datetime('now')))`,
83
- );
84
- const applied = new Map(
85
- query<{ version: number; checksum: string }>(db, `SELECT version, checksum FROM "${table}"`).rows.map((row) => [row.version, row.checksum]),
86
- );
87
- for (const migration of migrations) {
88
- const known = applied.get(migration.version);
89
- if (known !== undefined && known !== migration.checksum) {
90
- throw new Error(`sqlite.migrate: the migration ${migration.version} (${migration.name}) changed after it was applied: its sha256 is different`);
80
+ return sqlite.transaction(db, () => {
81
+ db.exec(
82
+ `CREATE TABLE IF NOT EXISTS "${table}" (version INTEGER PRIMARY KEY, name TEXT NOT NULL, checksum TEXT NOT NULL, applied_at TEXT NOT NULL DEFAULT (datetime('now')))`,
83
+ );
84
+ const applied = new Map(
85
+ rowsOf<{ version: number; checksum: string }>(db, `SELECT version, checksum FROM "${table}"`).map((row) => [Number(row.version), row.checksum]),
86
+ );
87
+ for (const migration of migrations) {
88
+ const known = applied.get(migration.version);
89
+ if (known !== undefined && known !== migration.checksum) {
90
+ throw new Error(`sqlite.migrate: the migration ${migration.version} (${migration.name}) changed after it was applied: its sha256 is different`);
91
+ }
91
92
  }
92
- }
93
- const pending = migrations.filter((migration) => !applied.has(migration.version));
94
- for (const migration of pending) {
95
- const label = `the migration ${migration.version} (${migration.name})`;
96
- try {
97
- runStatements(db, migration.sql, [], label);
98
- } catch (error) {
99
- const message = error instanceof Error ? error.message : String(error);
100
- throw new Error(message.startsWith(label) ? `sqlite.migrate: ${message}` : `sqlite.migrate: ${label} failed: ${message}`);
93
+ const pending = migrations.filter((migration) => !applied.has(migration.version));
94
+ const record = db.prepare(`INSERT INTO "${table}" (version, name, checksum) VALUES (?, ?, ?)`);
95
+ for (const migration of pending) {
96
+ const label = `the migration ${migration.version} (${migration.name})`;
97
+ try {
98
+ runStatements(sqlite, db, migration.sql, [], label);
99
+ } catch (error) {
100
+ const message = errorText(error);
101
+ throw new Error(message.startsWith(label) ? `sqlite.migrate: ${message}` : `sqlite.migrate: ${label} failed: ${message}`);
102
+ }
103
+ record.run(migration.version, migration.name, migration.checksum);
101
104
  }
102
- db.run(`INSERT INTO "${table}" (version, name, checksum) VALUES (?, ?, ?)`, [migration.version, migration.name, migration.checksum]);
103
- }
104
- db.run("COMMIT");
105
- const versions = [...applied.keys(), ...pending.map((migration) => migration.version)];
106
- return {
107
- applied: pending.map((migration) => ({ version: migration.version, name: migration.name })),
108
- skipped: migrations.length - pending.length,
109
- version: versions.length > 0 ? Math.max(...versions) : 0,
110
- };
105
+ const versions = [...applied.keys(), ...pending.map((migration) => migration.version)];
106
+ return {
107
+ applied: pending.map((migration) => ({ version: migration.version, name: migration.name })),
108
+ skipped: migrations.length - pending.length,
109
+ version: versions.length > 0 ? Math.max(...versions) : 0,
110
+ };
111
+ });
111
112
  } catch (error) {
112
- try {
113
- db.run("ROLLBACK");
114
- } catch {
115
- // SQLite ended the transaction already
116
- }
117
- const message = error instanceof Error ? error.message : String(error);
118
- throw new Error(`${message}. No migration was applied.`);
113
+ throw new Error(`${errorText(error)}. No migration was applied.`);
119
114
  }
120
115
  });
121
116
  }
@@ -6,9 +6,8 @@
6
6
  * bound value, not a part of the SQL text. The connection is read only.
7
7
  */
8
8
 
9
- import { query, withConnection } from "@mark1russell7/docker-sqlite";
10
9
  import type { DbColumnInfo, DbForeignKeyInfo, DbIndexInfo, DbSchemaInput, DbSchemaOutput } from "../../types.js";
11
- import { databasePath, requireDatabaseFile } from "./shared.js";
10
+ import { databasePath, rowsOf, withDatabase } from "./shared.js";
12
11
 
13
12
  interface ColumnRow {
14
13
  name: string;
@@ -38,33 +37,32 @@ interface ForeignKeyRow {
38
37
  */
39
38
  export async function dbSchema(input: DbSchemaInput): Promise<DbSchemaOutput> {
40
39
  const path = databasePath(input.dbPath);
41
- requireDatabaseFile("sqlite.schema", path);
42
- return withConnection({ dbPath: path }, (db) => {
43
- db.run("PRAGMA query_only = 1");
44
- const found = query<{ type: "table" | "view"; sql: string | null }>(
40
+ const mode = { procedure: "sqlite.schema", missing: "error", queryOnly: true, callerSql: false } as const;
41
+ return withDatabase(path, mode, (db) => {
42
+ const found = rowsOf<{ type: "table" | "view"; sql: string | null }>(
45
43
  db,
46
44
  "SELECT type, sql FROM sqlite_master WHERE name = ? AND type IN ('table', 'view')",
47
45
  [input.table],
48
- ).rows[0];
46
+ )[0];
49
47
  if (!found) throw new Error(`sqlite.schema: no table or view named ${JSON.stringify(input.table)}`);
50
48
 
51
- const columns: DbColumnInfo[] = query<ColumnRow>(db, "SELECT name, type, \"notnull\", dflt_value, pk FROM pragma_table_info(?) ORDER BY cid", [input.table]).rows.map(
49
+ const columns: DbColumnInfo[] = rowsOf<ColumnRow>(db, "SELECT name, type, \"notnull\", dflt_value, pk FROM pragma_table_info(?) ORDER BY cid", [input.table]).map(
52
50
  (row) => ({ name: row.name, type: row.type, notNull: row.notnull === 1, defaultValue: row.dflt_value, primaryKey: row.pk }),
53
51
  );
54
- const indexes: DbIndexInfo[] = query<IndexRow>(db, "SELECT name, \"unique\", origin, partial FROM pragma_index_list(?) ORDER BY name", [input.table]).rows.map(
52
+ const indexes: DbIndexInfo[] = rowsOf<IndexRow>(db, "SELECT name, \"unique\", origin, partial FROM pragma_index_list(?) ORDER BY name", [input.table]).map(
55
53
  (row) => ({
56
54
  name: row.name,
57
55
  unique: row.unique === 1,
58
56
  origin: row.origin,
59
57
  partial: row.partial === 1,
60
- columns: query<{ name: string | null }>(db, "SELECT name FROM pragma_index_info(?) ORDER BY seqno", [row.name]).rows.map((column) => column.name ?? "<expression>"),
58
+ columns: rowsOf<{ name: string | null }>(db, "SELECT name FROM pragma_index_info(?) ORDER BY seqno", [row.name]).map((column) => column.name ?? "<expression>"),
61
59
  }),
62
60
  );
63
- const foreignKeys: DbForeignKeyInfo[] = query<ForeignKeyRow>(
61
+ const foreignKeys: DbForeignKeyInfo[] = rowsOf<ForeignKeyRow>(
64
62
  db,
65
63
  "SELECT \"from\", \"table\", \"to\", on_update, on_delete FROM pragma_foreign_key_list(?) ORDER BY id, seq",
66
64
  [input.table],
67
- ).rows.map((row) => ({ from: row.from, table: row.table, to: row.to, onUpdate: row.on_update, onDelete: row.on_delete }));
65
+ ).map((row) => ({ from: row.from, table: row.table, to: row.to, onUpdate: row.on_update, onDelete: row.on_delete }));
68
66
 
69
67
  return { table: input.table, type: found.type, sql: found.sql, columns, indexes, foreignKeys };
70
68
  });
@@ -1,27 +1,146 @@
1
1
  /**
2
- * The helpers of the sqlite.* procedures of roadmap R44.
2
+ * The helpers of the sqlite.* and logs.* procedures. Each procedure opens the file through the engine of
3
+ * `@mark1russell7/sqlite`: `openDatabase` on `node:sqlite`, one connection for each call.
4
+ *
5
+ * - A connection that runs the SQL of a caller gets `confineToFile`: the SQL works only on its file. The guard needs
6
+ * Node.js 24.10 or later. Before it, the call throws `ConfineUnavailableError` (`code: "CONFINE_UNAVAILABLE"`) before
7
+ * it opens the file.
8
+ * - The open does not change the journal mode of a file: a file in WAL mode stays in WAL mode, and another file stays in
9
+ * its mode.
10
+ * - A write waits for the lock of another connection for `BUSY_TIMEOUT_MS`.
3
11
  */
4
12
 
5
13
  import { existsSync } from "node:fs";
6
- import type { Database } from "@mark1russell7/docker-sqlite";
14
+ import type { DatabaseSync, StatementSync } from "node:sqlite";
15
+ import { MEMORY_PATH } from "../../engines.js";
16
+ import { loadSqlite, type Sqlite } from "../../load.js";
7
17
  import { DEFAULT_DB_PATH } from "../../types.js";
8
18
 
19
+ /** The time that a call waits for the lock of another connection, in milliseconds. */
20
+ export const BUSY_TIMEOUT_MS = 5000;
21
+
9
22
  /** The database file of an input: `dbPath`, or the CLI log database. */
10
23
  export function databasePath(dbPath: string | undefined): string {
11
24
  return dbPath ?? DEFAULT_DB_PATH;
12
25
  }
13
26
 
14
- /**
15
- * This function throws ENOENT for a database file that does not exist. A procedure that only
16
- * reads uses it: sql.js opens a missing file as an empty database, so a wrong path gave no tables.
17
- */
27
+ /** This function throws ENOENT for a database file that does not exist. */
18
28
  export function requireDatabaseFile(procedure: string, path: string): void {
19
- if (path === ":memory:" || existsSync(path)) return;
29
+ if (path === MEMORY_PATH || existsSync(path)) return;
20
30
  const error = new Error(`${procedure}: the database file does not exist: ${path}`) as NodeJS.ErrnoException;
21
31
  error.code = "ENOENT";
22
32
  throw error;
23
33
  }
24
34
 
35
+ /** How a procedure opens its database. */
36
+ export interface OpenMode {
37
+ /** The name of the procedure, for the errors. */
38
+ readonly procedure: string;
39
+ /**
40
+ * What a missing file does:
41
+ * - `error`: the call throws ENOENT.
42
+ * - `empty`: the call reads an empty database in memory, and does not make the file.
43
+ * - `make`: the call makes the file and its folder at the open, also when its work then changes nothing or fails.
44
+ */
45
+ readonly missing: "error" | "empty" | "make";
46
+ /** True when the connection only reads: `PRAGMA query_only` refuses each change. */
47
+ readonly queryOnly: boolean;
48
+ /** True when the call runs the SQL of its caller. Then `confineToFile` keeps that SQL on the file. */
49
+ readonly callerSql: boolean;
50
+ }
51
+
52
+ /** True when this Node.js has the guard, false when it does not, undefined before the first check. */
53
+ let confineAvailable: boolean | undefined;
54
+
55
+ /**
56
+ * This function tells if this Node.js has the guard `confineToFile`. It tries the guard one time on a database in
57
+ * memory. The procedures and their tests use this one check.
58
+ */
59
+ export function isConfineAvailable(sqlite: Sqlite): boolean {
60
+ if (confineAvailable === undefined) {
61
+ const probe = sqlite.openDatabase(MEMORY_PATH, { wal: false });
62
+ try {
63
+ sqlite.confineToFile(probe);
64
+ confineAvailable = true;
65
+ } catch (error) {
66
+ if (!(error instanceof sqlite.ConfineUnavailableError)) throw error;
67
+ confineAvailable = false;
68
+ } finally {
69
+ probe.close();
70
+ }
71
+ }
72
+ return confineAvailable;
73
+ }
74
+
75
+ /** This function throws `ConfineUnavailableError` when this Node.js has no guard, before the call opens its file. */
76
+ function checkConfine(sqlite: Sqlite): void {
77
+ if (!isConfineAvailable(sqlite)) throw new sqlite.ConfineUnavailableError();
78
+ }
79
+
80
+ /**
81
+ * This function opens the database of a call, gives it to the work, and closes it. The work is synchronous, so no
82
+ * other call of this process uses the connection.
83
+ */
84
+ export async function withDatabase<T>(path: string, mode: OpenMode, work: (db: DatabaseSync, sqlite: Sqlite) => T): Promise<T> {
85
+ const sqlite = await loadSqlite();
86
+ if (mode.callerSql) checkConfine(sqlite);
87
+ let memory = path === MEMORY_PATH;
88
+ if (!memory && !existsSync(path)) {
89
+ if (mode.missing === "error") requireDatabaseFile(mode.procedure, path);
90
+ else if (mode.missing === "empty") memory = true;
91
+ }
92
+ const db = sqlite.openDatabase(memory ? MEMORY_PATH : path, {
93
+ wal: false,
94
+ busyTimeoutMs: BUSY_TIMEOUT_MS,
95
+ makeFolder: !memory && mode.missing === "make",
96
+ });
97
+ try {
98
+ if (mode.queryOnly) db.exec("PRAGMA query_only = 1");
99
+ if (mode.callerSql) sqlite.confineToFile(db);
100
+ return work(db, sqlite);
101
+ } finally {
102
+ db.close();
103
+ }
104
+ }
105
+
106
+ /** A value that a statement takes. */
107
+ export type SqlParam = null | number | bigint | string | Uint8Array;
108
+
109
+ /**
110
+ * This function gives the values of the `?` placeholders. A boolean becomes 1 or 0, and an undefined value becomes
111
+ * null. Another value is an error: an object would bind as named parameters.
112
+ */
113
+ export function toSqlParams(params: readonly unknown[] | undefined, label: string): SqlParam[] {
114
+ return (params ?? []).map((value, index) => {
115
+ if (value === null || value === undefined) return null;
116
+ if (typeof value === "boolean") return value ? 1 : 0;
117
+ if (typeof value === "number" || typeof value === "string" || typeof value === "bigint" || value instanceof Uint8Array) return value;
118
+ throw new TypeError(`${label}: params[${index}] is ${Array.isArray(value) ? "an array" : `a value of the type ${typeof value}`}. Give a number, a string, a boolean or null.`);
119
+ });
120
+ }
121
+
122
+ /** The rows of one statement, as objects. */
123
+ export function rowsOf<T>(db: DatabaseSync, sql: string, params: readonly SqlParam[] = []): T[] {
124
+ return db.prepare(sql).all(...params) as T[];
125
+ }
126
+
127
+ /** The number of rows that the connection changed since it opened. */
128
+ export function totalChanges(db: DatabaseSync): number {
129
+ return Number(rowsOf<{ n: number }>(db, "SELECT total_changes() AS n")[0]?.n ?? 0);
130
+ }
131
+
132
+ /** This function runs one statement to its end, and gives its rows when it has columns. */
133
+ export function runStatement(statement: StatementSync, params: readonly SqlParam[]): Record<string, unknown>[] | undefined {
134
+ if (statement.columns().length > 0) return statement.all(...params) as Record<string, unknown>[];
135
+ statement.run(...params);
136
+ return undefined;
137
+ }
138
+
139
+ /** The text of an error. */
140
+ export function errorText(error: unknown): string {
141
+ return error instanceof Error ? error.message : String(error);
142
+ }
143
+
25
144
  /** The statements that control a transaction, which the procedures run themselves. */
26
145
  const TRANSACTION_CONTROL = /^(BEGIN|COMMIT|END|ROLLBACK|SAVEPOINT|RELEASE)\b/i;
27
146
 
@@ -47,63 +166,72 @@ export function controlsTransaction(sql: string): boolean {
47
166
  return TRANSACTION_CONTROL.test(withoutLeadingComments(sql));
48
167
  }
49
168
 
50
- /** The result of one statement: the rows that it changed, and its rows when it gives rows. */
169
+ /** The result of one SQL text: the rows that it changed, and the rows of its last statement that gives rows. */
51
170
  export interface StatementRun {
52
171
  changes: number;
53
172
  rows?: Record<string, unknown>[];
54
173
  }
55
174
 
56
- function totalChanges(db: Database): number {
57
- return Number(db.exec("SELECT total_changes()")[0]?.values[0]?.[0] ?? 0);
58
- }
59
-
60
175
  /**
61
- * This function runs the statements of one SQL text in order, and gives one result for the text.
62
- * The params bind to the first statement, so a text with params must hold one statement. A
63
- * statement that controls a transaction is refused: the caller owns the transaction.
176
+ * This function runs the statements of one SQL text in order, and gives one result for the text. The params bind to the
177
+ * first statement, so a text with params must hold one statement.
178
+ *
179
+ * - With `control: "refuse"` (the default), the text runs in the transaction of the caller, and a statement that
180
+ * controls a transaction is an error.
181
+ * - With `control: "allow"`, the text controls its own transactions.
64
182
  */
65
- export function runStatements(db: Database, sql: string, params: unknown[], label: string): StatementRun {
183
+ export function runStatements(
184
+ sqlite: Sqlite,
185
+ db: DatabaseSync,
186
+ sql: string,
187
+ params: readonly SqlParam[],
188
+ label: string,
189
+ control: "refuse" | "allow" = "refuse",
190
+ ): StatementRun {
66
191
  const before = totalChanges(db);
67
192
  const result: StatementRun = { changes: 0 };
68
193
  let count = 0;
69
- const iterator = db.iterateStatements(sql);
70
- try {
71
- for (let step = iterator.next(); !step.done; step = iterator.next()) {
72
- const statement = step.value;
73
- try {
74
- count++;
75
- if (count > 1 && params.length > 0) {
76
- throw new Error(`${label}: the params bind to one statement, and the SQL has several`);
77
- }
78
- if (controlsTransaction(statement.getSQL())) {
79
- throw new Error(`${label}: the procedure runs the transaction: BEGIN, COMMIT, ROLLBACK, SAVEPOINT and RELEASE are refused`);
80
- }
81
- if (count === 1 && params.length > 0) statement.bind(params as never);
82
- if (statement.getColumnNames().length > 0) {
83
- const rows: Record<string, unknown>[] = [];
84
- while (statement.step()) rows.push(statement.getAsObject() as Record<string, unknown>);
85
- result.rows = rows;
86
- } else {
87
- while (statement.step()) {
88
- // A statement without columns gives no rows: one step runs it
89
- }
90
- }
91
- } finally {
92
- statement.free();
93
- }
194
+ for (const statement of sqlite.eachStatement(db, sql)) {
195
+ count++;
196
+ if (count > 1 && params.length > 0) {
197
+ throw new Error(`${label}: the params bind to one statement, and the SQL has several. Send one statement for each call.`);
94
198
  }
95
- } catch (error) {
96
- // Read the iterator to its end: that frees its copy of the SQL (it only prepares the rest)
97
- try {
98
- while (!iterator.next().done) {
99
- // Prepare only
100
- }
101
- } catch {
102
- // A later statement did not prepare: the iterator ended
199
+ if (control === "refuse" && controlsTransaction(statement.sourceSQL)) {
200
+ throw new Error(`${label}: the procedure runs the transaction: BEGIN, COMMIT, ROLLBACK, SAVEPOINT and RELEASE are refused`);
103
201
  }
104
- throw error;
202
+ const rows = runStatement(statement, count === 1 ? params : []);
203
+ if (rows) result.rows = rows;
105
204
  }
106
205
  if (count === 0) throw new Error(`${label}: the SQL has no statement`);
107
206
  result.changes = totalChanges(db) - before;
108
207
  return result;
109
208
  }
209
+
210
+ /** The first statements of a SQL text, before a statement runs. */
211
+ export interface StatementCount {
212
+ /** The number of statements: 0, 1, or 2 for two or more. */
213
+ readonly count: 0 | 1 | 2;
214
+ /** True when the first statement controls a transaction (BEGIN, COMMIT, SAVEPOINT, ...). */
215
+ readonly firstControls: boolean;
216
+ }
217
+
218
+ /**
219
+ * This function counts the statements of a SQL text up to two, and runs none. It compiles the first statement and asks
220
+ * `eachStatement` for the second. A second statement that does not compile before the first one runs, for example an
221
+ * `INSERT` into a table that the first one makes, also counts.
222
+ */
223
+ export function countStatements(sqlite: Sqlite, db: DatabaseSync, sql: string): StatementCount {
224
+ const statements = sqlite.eachStatement(db, sql);
225
+ try {
226
+ const first = statements.next();
227
+ if (first.done) return { count: 0, firstControls: false };
228
+ const firstControls = controlsTransaction(first.value.sourceSQL);
229
+ try {
230
+ return { count: statements.next().done ? 1 : 2, firstControls };
231
+ } catch {
232
+ return { count: 2, firstControls };
233
+ }
234
+ } finally {
235
+ statements.return(undefined);
236
+ }
237
+ }
@@ -5,23 +5,21 @@
5
5
  * is read only (PRAGMA query_only), and a missing file is an error: it does not make one.
6
6
  */
7
7
 
8
- import { query, withConnection } from "@mark1russell7/docker-sqlite";
9
8
  import type { DbTableInfo, DbTablesInput, DbTablesOutput } from "../../types.js";
10
- import { databasePath, requireDatabaseFile } from "./shared.js";
9
+ import { databasePath, rowsOf, withDatabase } from "./shared.js";
11
10
 
12
11
  /**
13
12
  * The tables and views of a database
14
13
  */
15
14
  export async function dbTables(input: DbTablesInput): Promise<DbTablesOutput> {
16
15
  const path = databasePath(input.dbPath);
17
- requireDatabaseFile("sqlite.tables", path);
18
16
  const types = input.views === false ? "('table')" : "('table', 'view')";
19
- return withConnection({ dbPath: path }, (db) => {
20
- db.run("PRAGMA query_only = 1");
21
- const result = query<DbTableInfo>(
17
+ const mode = { procedure: "sqlite.tables", missing: "error", queryOnly: true, callerSql: false } as const;
18
+ return withDatabase(path, mode, (db) => {
19
+ const rows = rowsOf<DbTableInfo>(
22
20
  db,
23
21
  `SELECT name, type, sql FROM sqlite_master WHERE type IN ${types} AND name NOT LIKE 'sqlite\\_%' ESCAPE '\\' ORDER BY name`,
24
22
  );
25
- return { tables: result.rows.map((row) => ({ name: row.name, type: row.type, sql: row.sql ?? null })) };
23
+ return { tables: rows.map((row) => ({ name: row.name, type: row.type, sql: row.sql ?? null })) };
26
24
  });
27
25
  }
@@ -1,42 +1,35 @@
1
1
  /**
2
2
  * sqlite.transaction procedure (roadmap R44)
3
3
  *
4
- * The statements of the input run in order in one transaction. When one fails, the procedure
5
- * rolls back the transaction and does not save the file: the database stays as it was. A
6
- * statement that gives rows (SELECT, or RETURNING) gives them in its result, so a later
7
- * statement can follow an earlier one in the same transaction.
4
+ * The statements of the input run in order in one `BEGIN IMMEDIATE` transaction. When one fails, the procedure rolls back
5
+ * the transaction: the database stays as it was. A statement that gives rows (SELECT, or RETURNING) gives them in its
6
+ * result, so a later statement can follow an earlier one in the same transaction.
8
7
  */
9
8
 
10
- import { withConnection } from "@mark1russell7/docker-sqlite";
11
9
  import type { DbStatementResult, DbTransactionInput, DbTransactionOutput } from "../../types.js";
12
- import { databasePath, runStatements } from "./shared.js";
10
+ import { databasePath, errorText, runStatements, toSqlParams, withDatabase } from "./shared.js";
13
11
 
14
12
  /**
15
13
  * Run statements in one transaction
16
14
  */
17
15
  export async function dbTransaction(input: DbTransactionInput): Promise<DbTransactionOutput> {
18
- return withConnection({ dbPath: databasePath(input.dbPath) }, (db) => {
19
- db.run("BEGIN");
16
+ const mode = { procedure: "sqlite.transaction", missing: "make", queryOnly: false, callerSql: true } as const;
17
+ return withDatabase(databasePath(input.dbPath), mode, (db, sqlite) => {
20
18
  const results: DbStatementResult[] = [];
21
19
  try {
22
- input.statements.forEach((statement, index) => {
23
- const label = `sqlite.transaction: statements[${index}]`;
24
- try {
25
- results.push(runStatements(db, statement.sql, statement.params ?? [], label));
26
- } catch (error) {
27
- const message = error instanceof Error ? error.message : String(error);
28
- throw new Error(message.startsWith(label) ? message : `${label}: ${message}`);
29
- }
20
+ sqlite.transaction(db, () => {
21
+ input.statements.forEach((statement, index) => {
22
+ const label = `sqlite.transaction: statements[${index}]`;
23
+ try {
24
+ results.push(runStatements(sqlite, db, statement.sql, toSqlParams(statement.params, label), label));
25
+ } catch (error) {
26
+ const message = errorText(error);
27
+ throw new Error(message.startsWith(label) ? message : `${label}: ${message}`);
28
+ }
29
+ });
30
30
  });
31
- db.run("COMMIT");
32
31
  } catch (error) {
33
- try {
34
- db.run("ROLLBACK");
35
- } catch {
36
- // SQLite ended the transaction already (an ON CONFLICT ROLLBACK)
37
- }
38
- const message = error instanceof Error ? error.message : String(error);
39
- throw new Error(`${message}. The transaction was rolled back.`);
32
+ throw new Error(`${errorText(error)}. The transaction was rolled back.`);
40
33
  }
41
34
  return { results, changes: results.reduce((sum, result) => sum + result.changes, 0) };
42
35
  });