@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
package/src/module.ts CHANGED
@@ -11,17 +11,8 @@
11
11
 
12
12
  import { definePackage, createProcedure, type AnyProcedure, type FsRootRules, type ProcedureModule, type PackageDefinition } from "@procedures/client";
13
13
  import * as z from "zod";
14
+ import type { DatabaseSync } from "node:sqlite";
14
15
  import {
15
- withConnection,
16
- query,
17
- execute,
18
- lastInsertRowId,
19
- runMigrations,
20
- tableExists,
21
- type Migration,
22
- } from "@mark1russell7/docker-sqlite";
23
- import {
24
- DEFAULT_DB_PATH,
25
16
  LOG_LEVELS,
26
17
  type DbQueryInput,
27
18
  type DbQueryOutput,
@@ -35,6 +26,19 @@ import {
35
26
  type LogLevel,
36
27
  } from "./types.js";
37
28
  import { dbTables, dbSchema, dbTransaction, dbMigrate, dbBackup } from "./procedures/db/index.js";
29
+ import {
30
+ countStatements,
31
+ databasePath,
32
+ rowsOf,
33
+ runStatement,
34
+ runStatements,
35
+ toSqlParams,
36
+ totalChanges,
37
+ withDatabase,
38
+ type OpenMode,
39
+ type SqlParam,
40
+ } from "./procedures/db/shared.js";
41
+ import type { Sqlite } from "./load.js";
38
42
  import {
39
43
  DbTablesInputSchema,
40
44
  DbTablesOutputSchema,
@@ -62,10 +66,11 @@ import {
62
66
  // The rules under a root of the files (roadmap R33)
63
67
  // =============================================================================
64
68
 
65
- // The procedures open the file in the process with sql.js, which keeps the database in memory. An
66
- // ATTACH or a VACUUM INTO of the SQL goes to the memory file system of sql.js, not to the disk.
67
- // So the paths of the input are all the paths that a call reaches. The default database (the CLI
68
- // log database in the home folder) is outside a root, so under a root a call must give dbPath.
69
+ // Each procedure opens the file through the engine of @mark1russell7/sqlite. The procedures that run
70
+ // the SQL of a caller (sqlite.query, sqlite.execute, sqlite.transaction and sqlite.migrate) keep that
71
+ // SQL on its file with confineToFile. So the paths of the input are all the paths that a call reaches.
72
+ // The default database (the CLI log database in the home folder) is outside a root, so under a root
73
+ // a call must give dbPath.
69
74
 
70
75
  /** A procedure of one database file. `:memory:` is a database in memory, not a path. */
71
76
  const DATABASE_IN_A_ROOT: FsRootRules = { paths: ["dbPath"], required: ["dbPath"], values: [":memory:"] };
@@ -87,7 +92,7 @@ const BACKUP_IN_A_ROOT: FsRootRules = { paths: ["dbPath", "to"], required: ["dbP
87
92
  const dbPathField = z
88
93
  .string()
89
94
  .optional()
90
- .describe("The SQLite database file (default: the CLI log database, ~/logs/cli/cli.db). A query does not make a missing file.");
95
+ .describe("The SQLite database file (default: the CLI log database, ~/logs/cli/cli.db). A query does not make a missing file, and a write makes it.");
91
96
  const paramsField = z
92
97
  .array(z.unknown())
93
98
  .optional()
@@ -158,11 +163,8 @@ const logsQueryOutputSchema: z.ZodType<LogsQueryOutput> = z.looseObject({
158
163
  // Log Table Migrations
159
164
  // =============================================================================
160
165
 
161
- const LOG_MIGRATIONS: Migration[] = [
162
- {
163
- version: 1,
164
- description: "Create logs table",
165
- up: `
166
+ /** The SQL of the logs table: the version 1 of the log migrations. The file format is the format of earlier versions. */
167
+ const LOG_TABLE_SQL = `
166
168
  CREATE TABLE IF NOT EXISTS logs (
167
169
  id INTEGER PRIMARY KEY AUTOINCREMENT,
168
170
  timestamp TEXT NOT NULL DEFAULT (datetime('now')),
@@ -179,18 +181,80 @@ const LOG_MIGRATIONS: Migration[] = [
179
181
  CREATE INDEX IF NOT EXISTS idx_logs_level ON logs(level);
180
182
  CREATE INDEX IF NOT EXISTS idx_logs_timestamp ON logs(timestamp);
181
183
  CREATE INDEX IF NOT EXISTS idx_logs_command ON logs(command);
182
- `,
183
- down: "DROP TABLE IF EXISTS logs;",
184
- },
185
- ];
184
+ `;
186
185
 
187
186
  /**
188
- * Ensure the logs table exists
187
+ * This function makes the logs table when the file does not have it, in the transaction of the caller. The table
188
+ * `_migrations` records the version 1, as in earlier versions of this package, so a file of an earlier version
189
+ * opens with its logs.
189
190
  */
190
- async function ensureLogsTable(dbPath: string): Promise<void> {
191
- await withConnection({ dbPath }, (db) => {
192
- runMigrations(db, LOG_MIGRATIONS);
193
- });
191
+ function ensureLogsTable(db: DatabaseSync): void {
192
+ db.exec(
193
+ "CREATE TABLE IF NOT EXISTS _migrations (version INTEGER PRIMARY KEY, description TEXT NOT NULL, applied_at TEXT NOT NULL DEFAULT (datetime('now')))",
194
+ );
195
+ if (rowsOf(db, "SELECT 1 FROM _migrations WHERE version = 1").length > 0) return;
196
+ db.exec(LOG_TABLE_SQL);
197
+ db.prepare("INSERT INTO _migrations (version, description) VALUES (?, ?)").run(1, "Create logs table");
198
+ }
199
+
200
+ /** True when the database has a table of the name. */
201
+ function tableExists(db: DatabaseSync, name: string): boolean {
202
+ return rowsOf(db, "SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?", [name]).length > 0;
203
+ }
204
+
205
+ /** `sqlite.query`: a missing file reads as an empty database, the connection only reads, and the guard is on. */
206
+ const QUERY_MODE: OpenMode = { procedure: "sqlite.query", missing: "empty", queryOnly: true, callerSql: true };
207
+ /** `sqlite.execute`: a missing file is made, and the guard is on. */
208
+ const EXECUTE_MODE: OpenMode = { procedure: "sqlite.execute", missing: "make", queryOnly: false, callerSql: true };
209
+ /** `logs.store`: a missing file is made. The procedure runs only its own SQL. */
210
+ const LOGS_STORE_MODE: OpenMode = { procedure: "logs.store", missing: "make", queryOnly: false, callerSql: false };
211
+ /** `logs.query`: the connection only reads. The procedure runs only its own SQL. */
212
+ const LOGS_QUERY_MODE: OpenMode = { procedure: "logs.query", missing: "empty", queryOnly: true, callerSql: false };
213
+
214
+ /**
215
+ * This function runs the SQL text of `sqlite.execute`, and gives the number of rows that it changed.
216
+ *
217
+ * - One statement runs alone with its params. Thus a `VACUUM` or a pragma works.
218
+ * - A script of several statements takes no params. It runs in one transaction: all its statements take effect, or none
219
+ * does.
220
+ * - A script that starts with `BEGIN` (or another statement that controls a transaction) runs as written. It controls
221
+ * its own transactions. After an error, the procedure rolls back the open transaction.
222
+ * - A text that leaves a transaction open fails, also one `BEGIN` alone. The procedure rolls the transaction back, so
223
+ * the file keeps none of its changes. Without this check, the close of the connection rolls it back with no error.
224
+ */
225
+ function executeSql(sqlite: Sqlite, db: DatabaseSync, sql: string, params: readonly SqlParam[]): number {
226
+ const label = "sqlite.execute";
227
+ const changes = runExecuteSql(sqlite, db, sql, params, label);
228
+ if (db.isTransaction) {
229
+ db.exec("ROLLBACK");
230
+ throw new Error(`${label}: the SQL left a transaction open, so the procedure rolled it back. End each transaction with COMMIT or ROLLBACK.`);
231
+ }
232
+ return changes;
233
+ }
234
+
235
+ /** This function runs the SQL text of `sqlite.execute` in the ways that `executeSql` tells. */
236
+ function runExecuteSql(sqlite: Sqlite, db: DatabaseSync, sql: string, params: readonly SqlParam[], label: string): number {
237
+ const { count, firstControls } = countStatements(sqlite, db, sql);
238
+ if (count === 0) throw new Error(`${label}: the SQL has no statement`);
239
+ if (count === 1) {
240
+ const before = totalChanges(db);
241
+ runStatement(db.prepare(sql), params);
242
+ return totalChanges(db) - before;
243
+ }
244
+ if (params.length > 0) {
245
+ throw new Error(`${label}: the params bind to one statement, and the SQL has several. Send one statement for each call.`);
246
+ }
247
+ if (!firstControls) return sqlite.transaction(db, () => runStatements(sqlite, db, sql, [], label).changes);
248
+ try {
249
+ return runStatements(sqlite, db, sql, [], label, "allow").changes;
250
+ } catch (error) {
251
+ try {
252
+ if (db.isTransaction) db.exec("ROLLBACK");
253
+ } catch {
254
+ // SQLite ended the transaction already
255
+ }
256
+ throw error;
257
+ }
194
258
  }
195
259
 
196
260
  // =============================================================================
@@ -209,16 +273,12 @@ const sqliteQueryProcedure = createProcedure()
209
273
  fsRoot: DATABASE_IN_A_ROOT,
210
274
  })
211
275
  .handler(async (input: DbQueryInput): Promise<DbQueryOutput> => {
212
- const dbPath = input.dbPath ?? DEFAULT_DB_PATH;
213
- const params = input.params ?? [];
214
-
215
- return withConnection({ dbPath }, (db) => {
216
- db.run("PRAGMA query_only = 1");
217
- const result = query(db, input.sql, params);
218
- return {
219
- columns: result.columns,
220
- rows: result.rows,
221
- };
276
+ const params = toSqlParams(input.params, "sqlite.query");
277
+ return withDatabase(databasePath(input.dbPath), QUERY_MODE, (db) => {
278
+ // Only the first statement of the text runs
279
+ const statement = db.prepare(input.sql);
280
+ const columns = statement.columns().map((column) => column.name);
281
+ return { columns, rows: statement.all(...params) as Record<string, unknown>[] };
222
282
  });
223
283
  })
224
284
  .build();
@@ -237,13 +297,8 @@ const sqliteExecuteProcedure = createProcedure()
237
297
  fsRoot: DATABASE_IN_A_ROOT,
238
298
  })
239
299
  .handler(async (input: DbExecuteInput): Promise<DbExecuteOutput> => {
240
- const dbPath = input.dbPath ?? DEFAULT_DB_PATH;
241
- const params = input.params ?? [];
242
-
243
- return withConnection({ dbPath }, (db) => {
244
- const result = execute(db, input.sql, params);
245
- return { changes: result.changes };
246
- });
300
+ const params = toSqlParams(input.params, "sqlite.execute");
301
+ return withDatabase(databasePath(input.dbPath), EXECUTE_MODE, (db, sqlite) => ({ changes: executeSql(sqlite, db, input.sql, params) }));
247
302
  })
248
303
  .build();
249
304
 
@@ -262,37 +317,33 @@ const logsStoreProcedure = createProcedure()
262
317
  fsRoot: DATABASE_IN_A_ROOT,
263
318
  })
264
319
  .handler(async (input: LogsStoreInput): Promise<LogsStoreOutput> => {
265
- const dbPath = input.dbPath ?? DEFAULT_DB_PATH;
320
+ const dbPath = databasePath(input.dbPath);
266
321
 
267
322
  // Validate log level
268
323
  if (!LOG_LEVELS.includes(input.level)) {
269
324
  throw new Error(`Invalid log level: ${input.level}`);
270
325
  }
271
326
 
272
- // Ensure table exists
273
- await ensureLogsTable(dbPath);
274
-
275
- return withConnection({ dbPath }, (db) => {
276
- const dataJson = input.data ? JSON.stringify(input.data) : null;
277
-
278
- execute(
279
- db,
280
- `INSERT INTO logs (level, message, data, session_id, command, context, error_stack)
327
+ return withDatabase(dbPath, LOGS_STORE_MODE, (db, sqlite) =>
328
+ sqlite.transaction(db, () => {
329
+ ensureLogsTable(db);
330
+ const result = db
331
+ .prepare(
332
+ `INSERT INTO logs (level, message, data, session_id, command, context, error_stack)
281
333
  VALUES (?, ?, ?, ?, ?, ?, ?)`,
282
- [
283
- input.level,
284
- input.message,
285
- dataJson,
286
- input.sessionId ?? null,
287
- input.command ?? null,
288
- input.context ?? null,
289
- input.errorStack ?? null,
290
- ]
291
- );
292
-
293
- const id = lastInsertRowId(db);
294
- return { id };
295
- });
334
+ )
335
+ .run(
336
+ input.level,
337
+ input.message,
338
+ input.data ? JSON.stringify(input.data) : null,
339
+ input.sessionId ?? null,
340
+ input.command ?? null,
341
+ input.context ?? null,
342
+ input.errorStack ?? null,
343
+ );
344
+ return { id: Number(result.lastInsertRowid) };
345
+ }),
346
+ );
296
347
  })
297
348
  .build();
298
349
 
@@ -327,15 +378,12 @@ const logsQueryProcedure = createProcedure()
327
378
  fsRoot: DATABASE_IN_A_ROOT,
328
379
  })
329
380
  .handler(async (input: LogsQueryInput): Promise<LogsQueryOutput> => {
330
- const dbPath = input.dbPath ?? DEFAULT_DB_PATH;
331
-
332
- return withConnection({ dbPath }, (db) => {
381
+ return withDatabase(databasePath(input.dbPath), LOGS_QUERY_MODE, (db) => {
333
382
  if (!tableExists(db, "logs")) {
334
383
  return { logs: [] };
335
384
  }
336
- db.run("PRAGMA query_only = 1");
337
385
  const conditions: string[] = [];
338
- const params: unknown[] = [];
386
+ const params: SqlParam[] = [];
339
387
 
340
388
  if (input.sessionId !== undefined) {
341
389
  conditions.push("session_id = ?");
@@ -381,7 +429,7 @@ const logsQueryProcedure = createProcedure()
381
429
  ${offsetClause}
382
430
  `;
383
431
 
384
- const result = query<{
432
+ const rows = rowsOf<{
385
433
  id: number;
386
434
  timestamp: string;
387
435
  level: string;
@@ -393,8 +441,8 @@ const logsQueryProcedure = createProcedure()
393
441
  error_stack: string | null;
394
442
  }>(db, sql, params);
395
443
 
396
- const logs: LogEntry[] = result.rows.map((row) => ({
397
- id: row.id,
444
+ const logs: LogEntry[] = rows.map((row) => ({
445
+ id: Number(row.id),
398
446
  timestamp: row.timestamp,
399
447
  level: row.level as LogLevel,
400
448
  message: row.message,
@@ -407,12 +455,8 @@ const logsQueryProcedure = createProcedure()
407
455
 
408
456
  // Total number of rows matching the filters, ignoring LIMIT/OFFSET, so
409
457
  // callers can paginate. `params` holds only the WHERE-clause bindings.
410
- const countResult = query<{ total: number }>(
411
- db,
412
- `SELECT COUNT(*) AS total FROM logs ${whereClause}`,
413
- params
414
- );
415
- const total = countResult.rows[0]?.total ?? 0;
458
+ const counted = rowsOf<{ total: number }>(db, `SELECT COUNT(*) AS total FROM logs ${whereClause}`, params);
459
+ const total = Number(counted[0]?.total ?? 0);
416
460
 
417
461
  return { logs, total };
418
462
  });
@@ -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
  });