@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
package/src/engines.ts CHANGED
@@ -1,41 +1,40 @@
1
1
  /**
2
- * The two SQLite engines of `SqliteStorage`: `node:sqlite` and sql.js. Each engine gives a
3
- * `SqlConnection` of `@mark1russell7/sqlite`, so the storage has one set of queries and uses the
4
- * transactions of that package.
2
+ * The SQLite engine of `SqliteStorage`: `openDatabase` of `@mark1russell7/sqlite`, on the module
3
+ * `node:sqlite` of Node.js. It gives a `SqlConnection` of that package, so the storage uses its
4
+ * transactions. It writes only the changed pages of the file, and SQLite locks the file for each
5
+ * write.
5
6
  *
6
- * - The engine `node` is `openDatabase` of `@mark1russell7/sqlite`, on the module `node:sqlite` of
7
- * Node.js. It writes only the changed pages of the file, and SQLite locks the file for each write.
8
- * - The engine `sqljs` is sql.js (SQLite in WebAssembly), through `@mark1russell7/docker-sqlite`
9
- * and the adapter `sqlJsConnection`. It keeps the database in memory and writes the whole file
10
- * after a write.
11
- * - The two engines read and write the same file format.
7
+ * Version 0.61.0 removed the engine `sqljs` (sql.js, SQLite in WebAssembly). A file that it wrote
8
+ * opens with this engine, with its items and its versions.
12
9
  *
13
10
  * This module loads the main entry of `@mark1russell7/sqlite`, and with it `node:sqlite`, only
14
11
  * when a storage opens. An import of this package does not load them.
15
12
  */
16
13
 
17
- import { existsSync, statSync } from "node:fs";
18
- import { createConnection } from "@mark1russell7/docker-sqlite";
19
- import { sqlJsConnection, type SqlConnection, type SqlStatement } from "@mark1russell7/sqlite/portable";
14
+ import { existsSync } from "node:fs";
15
+ import type { SqlConnection, SqlStatement } from "@mark1russell7/sqlite/portable";
16
+ import { loadSqlite, type Sqlite } from "./load.js";
20
17
 
21
18
  /** The path of a database that is only in memory. */
22
19
  export const MEMORY_PATH = ":memory:";
23
20
 
24
- /** The engine of a database: `node:sqlite` (`node`) or sql.js (`sqljs`). */
25
- export type SqliteEngineName = "node" | "sqljs";
21
+ /** The engine of a database: `node:sqlite` (`node`). Version 0.61.0 removed the engine `sqljs`. */
22
+ export type SqliteEngineName = "node";
26
23
 
27
- /**
28
- * The engine choice of a `SqliteStorage`. With `auto`, the storage uses `node` when Node.js has
29
- * `node:sqlite`, and `sqljs` when it does not.
30
- */
24
+ /** The engine choice of a `SqliteStorage`. `auto` and `node` both use `node:sqlite`. */
31
25
  export type SqliteEngine = "auto" | SqliteEngineName;
32
26
 
33
- const ENGINES: ReadonlySet<string> = new Set<SqliteEngine>(["auto", "node", "sqljs"]);
27
+ const ENGINES: ReadonlySet<string> = new Set<SqliteEngine>(["auto", "node"]);
34
28
 
35
29
  /** This function gives the engine choice when it is known. Else it throws a `TypeError`. */
36
30
  export function checkEngine(engine: unknown): SqliteEngine {
31
+ if (engine === "sqljs") {
32
+ throw new TypeError(
33
+ "The SQLite engine sqljs was removed in version 0.61.0: use auto or node. A file of the engine sqljs opens with the engine node.",
34
+ );
35
+ }
37
36
  if (typeof engine !== "string" || !ENGINES.has(engine)) {
38
- throw new TypeError(`Unknown SQLite engine ${JSON.stringify(engine)}: use auto, node or sqljs`);
37
+ throw new TypeError(`Unknown SQLite engine ${JSON.stringify(engine)}: use auto or node`);
39
38
  }
40
39
  return engine as SqliteEngine;
41
40
  }
@@ -43,7 +42,7 @@ export function checkEngine(engine: unknown): SqliteEngine {
43
42
  /** A value that a statement takes or gives. */
44
43
  export type SqlValue = string | number | null;
45
44
 
46
- /** A connection of an engine: a `SqlConnection` that closes. */
45
+ /** A connection of the engine: a `SqlConnection` that closes. */
47
46
  type EngineConnection = SqlConnection & { close(): void };
48
47
 
49
48
  /** The calls of an open database that a storage uses. Each call is synchronous. */
@@ -61,7 +60,7 @@ export interface EngineDatabase {
61
60
  close(): void;
62
61
  }
63
62
 
64
- /** A database of either engine. It keeps one prepared statement for each SQL text. */
63
+ /** A database of the engine. It keeps one prepared statement for each SQL text. */
65
64
  class ConnectionDatabase implements EngineDatabase {
66
65
  readonly connection: EngineConnection;
67
66
 
@@ -103,23 +102,16 @@ class ConnectionDatabase implements EngineDatabase {
103
102
  }
104
103
  }
105
104
 
106
- // ---------------------------------------------------------------------------
107
- // node:sqlite, through @mark1russell7/sqlite
108
- // ---------------------------------------------------------------------------
109
-
110
- /** The part of `@mark1russell7/sqlite` that the engine `node` uses. */
111
- type NodeSqlite = Pick<typeof import("@mark1russell7/sqlite"), "openDatabase">;
112
-
113
- let nodeModule: Promise<NodeSqlite | undefined> | undefined;
105
+ let nodeModule: Promise<Sqlite | undefined> | undefined;
114
106
 
115
107
  /**
116
108
  * This function loads `@mark1russell7/sqlite` one time, and opens a database in memory as a test.
117
109
  * The promise gives undefined when the import or the test fails. Node.js before 22.13 has
118
110
  * `node:sqlite` only with the flag `--experimental-sqlite`.
119
111
  */
120
- function loadNodeSqlite(): Promise<NodeSqlite | undefined> {
121
- nodeModule ??= import("@mark1russell7/sqlite")
122
- .then((module: NodeSqlite) => {
112
+ function loadNodeSqlite(): Promise<Sqlite | undefined> {
113
+ nodeModule ??= loadSqlite()
114
+ .then((module) => {
123
115
  module.openDatabase(MEMORY_PATH, { wal: false }).close();
124
116
  return module;
125
117
  })
@@ -128,8 +120,8 @@ function loadNodeSqlite(): Promise<NodeSqlite | undefined> {
128
120
  }
129
121
 
130
122
  /**
131
- * This function gives true when this Node.js has `node:sqlite` without a flag (Node.js 22.13 or
132
- * later). Then the engine `auto` uses it.
123
+ * This function gives true when this Node.js has `node:sqlite` without a flag. Node.js 22.13 and
124
+ * later have it, and the package needs Node.js 22.13 or later.
133
125
  */
134
126
  export async function isNodeSqliteAvailable(): Promise<boolean> {
135
127
  return (await loadNodeSqlite()) !== undefined;
@@ -142,7 +134,7 @@ export async function isNodeSqliteAvailable(): Promise<boolean> {
142
134
  * busy timeout makes a write wait for the lock of another process. In WAL mode, `NORMAL` keeps the
143
135
  * file consistent after a crash, with fewer disk syncs.
144
136
  */
145
- function openNodeFile(sqlite: NodeSqlite, path: string, busyTimeoutMs: number): ConnectionDatabase {
137
+ function openNodeFile(sqlite: Sqlite, path: string, busyTimeoutMs: number): ConnectionDatabase {
146
138
  return new ConnectionDatabase(
147
139
  sqlite.openDatabase(path, {
148
140
  wal: "when-writable",
@@ -154,53 +146,35 @@ function openNodeFile(sqlite: NodeSqlite, path: string, busyTimeoutMs: number):
154
146
  }
155
147
 
156
148
  /** This function opens a database in memory with `node:sqlite`. */
157
- function openNodeMemory(sqlite: NodeSqlite): ConnectionDatabase {
149
+ function openNodeMemory(sqlite: Sqlite): ConnectionDatabase {
158
150
  return new ConnectionDatabase(sqlite.openDatabase(MEMORY_PATH, { wal: false }));
159
151
  }
160
152
 
161
- // ---------------------------------------------------------------------------
162
- // An open database of a path, with the file work of its engine
163
- // ---------------------------------------------------------------------------
164
-
165
153
  /**
166
- * This function copies the schema of the storages from one database to another. The node engine
154
+ * This function copies the schema of the storages from one database to another. The engine
167
155
  * calls it when it makes the file at the first write.
168
156
  */
169
157
  export type CopySchema = (from: EngineDatabase, to: EngineDatabase) => void;
170
158
 
171
- /** An open database of a path, with the file work of its engine. */
172
- export interface OpenDatabase {
173
- readonly engine: SqliteEngineName;
174
- /** The current database. The node engine changes it when it opens the file. */
175
- readonly db: EngineDatabase;
176
- /**
177
- * True when the node engine waits for the first write to make the file. Until then, the
178
- * database is in memory, and it has the tables and no item.
179
- */
180
- readonly waiting: boolean;
181
- /** This method opens the file and copies the schema to it. The node engine uses it before the first write. */
182
- makeFile(copy: CopySchema): void;
183
- /** This method opens a file that another process made after the open, before a read. */
184
- refresh(copy: CopySchema): void;
185
- /** This method writes the database to the file. Only sql.js has a write to do. */
186
- saveFile(): Promise<void>;
187
- close(): void;
188
- }
189
-
190
159
  /**
191
- * A database of `node:sqlite`. A missing file stays missing until the first write that changes
192
- * an item: until then, the database is in memory.
160
+ * An open database of a path. A missing file stays missing until the first write that changes an
161
+ * item: until then, the database is in memory.
193
162
  */
194
- class NodeOpenDatabase implements OpenDatabase {
195
- private readonly sqlite: NodeSqlite;
163
+ export class OpenDatabase {
164
+ private readonly sqlite: Sqlite;
196
165
  private readonly path: string;
197
166
  private readonly busyTimeoutMs: number;
198
167
 
199
- readonly engine = "node";
168
+ readonly engine: SqliteEngineName = "node";
169
+ /** The current database. It changes when the storage makes the file. */
200
170
  db: EngineDatabase;
171
+ /**
172
+ * True while the storage waits for the first write to make the file. Until then, the database
173
+ * is in memory, and it has the tables and no item.
174
+ */
201
175
  waiting: boolean;
202
176
 
203
- constructor(sqlite: NodeSqlite, path: string, busyTimeoutMs: number) {
177
+ constructor(sqlite: Sqlite, path: string, busyTimeoutMs: number) {
204
178
  this.sqlite = sqlite;
205
179
  this.path = path;
206
180
  this.busyTimeoutMs = busyTimeoutMs;
@@ -216,6 +190,7 @@ class NodeOpenDatabase implements OpenDatabase {
216
190
  }
217
191
  }
218
192
 
193
+ /** This method opens the file and copies the schema to it, before the first write. */
219
194
  makeFile(copy: CopySchema): void {
220
195
  if (!this.waiting) return;
221
196
  const file = openNodeFile(this.sqlite, this.path, this.busyTimeoutMs);
@@ -230,83 +205,26 @@ class NodeOpenDatabase implements OpenDatabase {
230
205
  this.waiting = false;
231
206
  }
232
207
 
208
+ /** This method opens a file that another process made after the open, before a read. */
233
209
  refresh(copy: CopySchema): void {
234
210
  if (this.waiting && existsSync(this.path)) this.makeFile(copy);
235
211
  }
236
212
 
237
- saveFile(): Promise<void> {
238
- return Promise.resolve();
239
- }
240
-
241
- close(): void {
242
- this.db.close();
243
- }
244
- }
245
-
246
- // ---------------------------------------------------------------------------
247
- // sql.js
248
- // ---------------------------------------------------------------------------
249
-
250
- /** A database of sql.js: the database is in memory, and `saveFile()` writes the whole file. */
251
- class SqlJsOpenDatabase implements OpenDatabase {
252
- readonly db: ConnectionDatabase;
253
- private readonly save: () => Promise<void>;
254
-
255
- readonly engine = "sqljs";
256
- readonly waiting = false;
257
-
258
- constructor(db: ConnectionDatabase, save: () => Promise<void>) {
259
- this.db = db;
260
- this.save = save;
261
- }
262
-
263
- makeFile(): void {}
264
-
265
- refresh(): void {}
266
-
267
- saveFile(): Promise<void> {
268
- return this.save();
269
- }
270
-
271
213
  close(): void {
272
214
  this.db.close();
273
215
  }
274
216
  }
275
217
 
276
- /**
277
- * sql.js reads only the main file. A write-ahead log of the node engine (`<file>-wal`) can hold
278
- * changes that are not in the main file yet. A whole-file write of sql.js does not agree with the
279
- * log. Thus sql.js refuses such a file.
280
- */
281
- function checkNoWriteAheadLog(path: string): void {
282
- let size = 0;
283
- try {
284
- size = statSync(`${path}-wal`).size;
285
- } catch {
286
- return;
287
- }
288
- if (size > 0) {
289
- throw new Error(
290
- `The file ${path} has a write-ahead log (${path}-wal) of the engine node: open it with the engine node, or close the process that uses it`,
291
- );
292
- }
293
- }
294
-
295
- /** The error of the engine `node` when this Node.js has no `node:sqlite`. */
218
+ /** The error when this Node.js has no `node:sqlite` without a flag. */
296
219
  function noNodeSqlite(): Error {
297
220
  return new Error(
298
- `The SQLite engine node needs node:sqlite, and this Node.js (${process.version}) does not have it without a flag: use Node.js 22.13 or later, or the engine sqljs or auto`,
221
+ `SqliteStorage needs node:sqlite, and this Node.js (${process.version}) does not have it without a flag: use Node.js 22.13 or later`,
299
222
  );
300
223
  }
301
224
 
302
- /** This function opens the database of a path with an engine. `auto` uses `node` when it can. */
303
- export async function openEngine(path: string, engine: SqliteEngine, busyTimeoutMs: number): Promise<OpenDatabase> {
304
- if (engine !== "sqljs") {
305
- const sqlite = await loadNodeSqlite();
306
- if (sqlite) return new NodeOpenDatabase(sqlite, path, busyTimeoutMs);
307
- if (engine === "node") throw noNodeSqlite();
308
- }
309
- if (path !== MEMORY_PATH) checkNoWriteAheadLog(path);
310
- const { db, save } = await createConnection({ dbPath: path });
311
- return new SqlJsOpenDatabase(new ConnectionDatabase(sqlJsConnection(db)), save);
225
+ /** This function opens the database of a path. */
226
+ export async function openEngine(path: string, busyTimeoutMs: number): Promise<OpenDatabase> {
227
+ const sqlite = await loadNodeSqlite();
228
+ if (!sqlite) throw noNodeSqlite();
229
+ return new OpenDatabase(sqlite, path, busyTimeoutMs);
312
230
  }
package/src/index.ts CHANGED
@@ -1,8 +1,8 @@
1
1
  /**
2
- * client-sqlite
2
+ * @procedures/sqlite
3
3
  *
4
- * SQLite database operations via client procedures.
5
- * Enables database queries and logging via client.call().
4
+ * The SQLite procedures and the SQLite collection storage. Each procedure opens the file through the engine of
5
+ * `@mark1russell7/sqlite`. That package has the functions of a connection (`openDatabase`, `migrate`, `transaction`).
6
6
  *
7
7
  * @example
8
8
  * ```typescript
@@ -92,31 +92,3 @@ export {
92
92
  type SqliteEngineName,
93
93
  type SqliteStorageOptions,
94
94
  } from "./storage.js";
95
-
96
- // =============================================================================
97
- // Re-export docker-sqlite utilities for direct use
98
- // =============================================================================
99
-
100
- export {
101
- withConnection,
102
- createConnection,
103
- query,
104
- execute,
105
- execMultiple,
106
- lastInsertRowId,
107
- tableExists,
108
- getMigrationStatus,
109
- runMigrations,
110
- rollbackMigration,
111
- createMigration,
112
- } from "@mark1russell7/docker-sqlite";
113
-
114
- export type {
115
- ConnectionConfig,
116
- ConnectionCallback,
117
- QueryResult,
118
- ExecuteResult,
119
- Migration,
120
- MigrationStatus,
121
- Database,
122
- } from "@mark1russell7/docker-sqlite";
package/src/load.ts ADDED
@@ -0,0 +1,15 @@
1
+ /**
2
+ * The main entry of `@mark1russell7/sqlite`, loaded at its first use. The procedures and the storage load it, and with
3
+ * it `node:sqlite`, only when they open a database. An import of this package does not load them.
4
+ */
5
+
6
+ /** The main entry of `@mark1russell7/sqlite`. */
7
+ export type Sqlite = typeof import("@mark1russell7/sqlite");
8
+
9
+ let loading: Promise<Sqlite> | undefined;
10
+
11
+ /** This function loads the main entry of `@mark1russell7/sqlite` one time. */
12
+ export function loadSqlite(): Promise<Sqlite> {
13
+ loading ??= import("@mark1russell7/sqlite");
14
+ return loading;
15
+ }
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
  });