@procedures/sqlite 0.60.1 → 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 +33 -0
  2. package/README.md +84 -189
  3. package/dist/engines.d.ts +31 -34
  4. package/dist/engines.d.ts.map +1 -1
  5. package/dist/engines.js +35 -95
  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 -30
  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 -158
  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 -137
  60. package/src/types.ts +2 -2
@@ -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
  });