lines-db 0.0.0-stage → 0.15.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.
package/dist/index.mjs ADDED
@@ -0,0 +1,2796 @@
1
+ import { a as ok, i as err, n as JsonlReader, o as toError, r as hashJsonlContent, s as unwrap, t as replaceFile } from "./replace-file-AWLIm7aN.mjs";
2
+ import { createRequire } from "node:module";
3
+ import { randomBytes } from "node:crypto";
4
+ import { access, chmod, mkdir, readFile, readdir, rename, rm, stat, writeFile } from "node:fs/promises";
5
+ import { basename, dirname, extname, isAbsolute, join, relative, resolve } from "node:path";
6
+ import { pathToFileURL } from "node:url";
7
+ import { styleText } from "node:util";
8
+ //#region \0rolldown/runtime.js
9
+ var __require = /* #__PURE__ */ (() => createRequire(import.meta.url))();
10
+ //#endregion
11
+ //#region src/runtime.ts
12
+ function detectRuntime() {
13
+ if (typeof process !== "undefined" && process.versions && process.versions.node) return "node";
14
+ return "unknown";
15
+ }
16
+ const RUNTIME = detectRuntime();
17
+ //#endregion
18
+ //#region src/sqlite-adapter.ts
19
+ /**
20
+ * SQLite adapter for Node.js
21
+ */
22
+ /**
23
+ * Create a SQLite database instance for Node.js
24
+ */
25
+ function createDatabase(path = ":memory:") {
26
+ if (RUNTIME === "node") return createNodeDatabase(path);
27
+ else throw new Error(`Unsupported runtime: ${RUNTIME}`);
28
+ }
29
+ /**
30
+ * Create a Node.js SQLite database
31
+ */
32
+ function createNodeDatabase(path) {
33
+ const { DatabaseSync } = __require("node:sqlite");
34
+ const db = new DatabaseSync(path);
35
+ db.exec("PRAGMA foreign_keys = ON");
36
+ return {
37
+ prepare(sql) {
38
+ const stmt = db.prepare(sql);
39
+ return {
40
+ run(...params) {
41
+ return stmt.run(...params);
42
+ },
43
+ get(...params) {
44
+ return stmt.get(...params);
45
+ },
46
+ all(...params) {
47
+ return stmt.all(...params);
48
+ }
49
+ };
50
+ },
51
+ exec(sql) {
52
+ db.exec(sql);
53
+ },
54
+ close() {
55
+ db.close();
56
+ }
57
+ };
58
+ }
59
+ //#endregion
60
+ //#region src/jsonl-writer.ts
61
+ var JsonlWriter = class {
62
+ /**
63
+ * Write data to JSONL file
64
+ */
65
+ static async write(filePath, data) {
66
+ await writeFile(filePath, this.serialize(data), "utf-8");
67
+ }
68
+ /**
69
+ * The content {@link write} writes for the data
70
+ */
71
+ static serialize(data) {
72
+ return data.map((obj) => JSON.stringify(obj)).join("\n") + "\n";
73
+ }
74
+ /**
75
+ * Append data to JSONL file
76
+ */
77
+ static async append(filePath, data) {
78
+ const { readFile, writeFile } = await import("node:fs/promises");
79
+ try {
80
+ const existing = await readFile(filePath, "utf-8");
81
+ const lines = data.map((obj) => JSON.stringify(obj)).join("\n");
82
+ await writeFile(filePath, existing.trim() + "\n" + lines + "\n", "utf-8");
83
+ } catch (error) {
84
+ if (error.code === "ENOENT") await this.write(filePath, data);
85
+ else throw error;
86
+ }
87
+ }
88
+ };
89
+ //#endregion
90
+ //#region src/schema-extensions.ts
91
+ /**
92
+ * Supported schema file extensions, in priority order.
93
+ * The first match wins when discovering schema files.
94
+ */
95
+ const SCHEMA_EXTENSIONS = [
96
+ ".schema.ts",
97
+ ".schema.mts",
98
+ ".schema.cts"
99
+ ];
100
+ /**
101
+ * Map from schema extensions to their JavaScript import counterparts.
102
+ */
103
+ const SCHEMA_TO_JS_IMPORT_MAP = {
104
+ ".schema.ts": ".schema.js",
105
+ ".schema.mts": ".schema.mjs",
106
+ ".schema.cts": ".schema.cjs"
107
+ };
108
+ /**
109
+ * Try each supported schema extension and return the full path of the first
110
+ * one that exists on disk. Returns undefined if none is found.
111
+ */
112
+ async function findSchemaFile(dir, tableName) {
113
+ for (const ext of SCHEMA_EXTENSIONS) {
114
+ const candidate = join(dir, `${tableName}${ext}`);
115
+ try {
116
+ await access(candidate);
117
+ return candidate;
118
+ } catch {}
119
+ }
120
+ }
121
+ /**
122
+ * Synchronously find a schema file among directory entries.
123
+ * Returns the full path of the first match, or undefined.
124
+ */
125
+ function findSchemaFileInEntries(dataDirPath, tableName, entries) {
126
+ for (const ext of SCHEMA_EXTENSIONS) {
127
+ const candidateName = `${tableName}${ext}`;
128
+ if (entries.some((e) => e.isFile() && e.name === candidateName)) return join(dataDirPath, candidateName);
129
+ }
130
+ }
131
+ /**
132
+ * Check if a filename matches any supported schema file pattern.
133
+ */
134
+ function isSchemaFile(fileName) {
135
+ return SCHEMA_EXTENSIONS.some((ext) => fileName.endsWith(ext));
136
+ }
137
+ /**
138
+ * Extract table name from a schema filename.
139
+ * e.g., "users.schema.ts" -> "users", "users.schema.mts" -> "users"
140
+ */
141
+ function extractTableNameFromSchemaFile(fileName) {
142
+ for (const ext of SCHEMA_EXTENSIONS) if (fileName.endsWith(ext)) return fileName.slice(0, -ext.length);
143
+ return null;
144
+ }
145
+ /**
146
+ * Rewrite a TypeScript path to its JavaScript counterpart for ESM imports.
147
+ * ".schema.ts" -> ".schema.js", ".schema.mts" -> ".schema.mjs", ".schema.cts" -> ".schema.cjs"
148
+ */
149
+ function rewriteExtensionForImport(filePath) {
150
+ for (const [tsExt, jsExt] of Object.entries(SCHEMA_TO_JS_IMPORT_MAP)) if (filePath.endsWith(tsExt)) return filePath.slice(0, -tsExt.length) + jsExt;
151
+ return filePath;
152
+ }
153
+ //#endregion
154
+ //#region src/schema-loader.ts
155
+ var SchemaLoader = class {
156
+ /**
157
+ * Check if a schema file exists for a table
158
+ */
159
+ static async hasSchema(jsonlPath, schemaDir) {
160
+ return await findSchemaFile(schemaDir ?? dirname(jsonlPath), basename(jsonlPath, ".jsonl")) !== void 0;
161
+ }
162
+ /**
163
+ * Load a validation schema file for a table
164
+ * Requires ${tableName}.schema.{ts,mts,cts} to exist in schemaDir, or alongside the JSONL file when omitted
165
+ */
166
+ static async loadSchema(jsonlPath, schemaDir) {
167
+ const dir = schemaDir ?? dirname(jsonlPath);
168
+ const tableName = basename(jsonlPath, ".jsonl");
169
+ const schemaPath = await findSchemaFile(dir, tableName);
170
+ if (!schemaPath) throw new Error(`Schema file not found for table '${tableName}'. Expected one of: ${SCHEMA_EXTENSIONS.map((ext) => `${tableName}${ext}`).join(", ")}`);
171
+ try {
172
+ const module = await import(`${pathToFileURL(schemaPath).href}?t=${Date.now()}`);
173
+ const schema = module.default || module.schema;
174
+ if (schema && this.isStandardSchema(schema)) return schema;
175
+ throw new Error(`Schema file ${schemaPath} does not export a valid StandardSchema`);
176
+ } catch (error) {
177
+ throw new Error(`Failed to load schema for table '${tableName}' from ${schemaPath}: ${error instanceof Error ? error.message : String(error)}`, { cause: error instanceof Error ? error : void 0 });
178
+ }
179
+ }
180
+ /**
181
+ * Check if an object implements the StandardSchema interface
182
+ */
183
+ static isStandardSchema(obj) {
184
+ if (!obj || typeof obj !== "object") return false;
185
+ const standard = obj["~standard"];
186
+ if (!standard || typeof standard !== "object") return false;
187
+ const standardObj = standard;
188
+ return standardObj.version === 1 && typeof standardObj.vendor === "string" && typeof standardObj.validate === "function";
189
+ }
190
+ };
191
+ //#endregion
192
+ //#region src/directory-scanner.ts
193
+ var DirectoryScanner = class {
194
+ /**
195
+ * Scan directories for JSONL files and create table configurations.
196
+ * A table found in several directories lists its files in the order the directories are given.
197
+ */
198
+ static async scanDirectory(dataDir) {
199
+ const dataDirs = typeof dataDir === "string" ? [dataDir] : dataDir;
200
+ const jsonlPathsByTable = /* @__PURE__ */ new Map();
201
+ for (const dir of dataDirs) {
202
+ let files;
203
+ try {
204
+ files = await readdir(dir);
205
+ } catch (error) {
206
+ throw new Error(`Failed to scan directory ${dir}: ${error instanceof Error ? error.message : String(error)}`);
207
+ }
208
+ for (const file of files) if (extname(file) === ".jsonl") {
209
+ const tableName = basename(file, ".jsonl");
210
+ const jsonlPaths = jsonlPathsByTable.get(tableName) ?? [];
211
+ jsonlPaths.push(join(dir, file));
212
+ jsonlPathsByTable.set(tableName, jsonlPaths);
213
+ }
214
+ }
215
+ if (jsonlPathsByTable.size === 0) console.warn(`Warning: No JSONL files found in directory: ${dataDirs.join(", ")}`);
216
+ const tables = /* @__PURE__ */ new Map();
217
+ for (const [tableName, jsonlPaths] of jsonlPathsByTable) tables.set(tableName, {
218
+ jsonlPath: jsonlPaths[0],
219
+ jsonlPaths,
220
+ autoInferSchema: true
221
+ });
222
+ return tables;
223
+ }
224
+ };
225
+ //#endregion
226
+ //#region src/schema.ts
227
+ /**
228
+ * Define a bidirectional schema with optional backward transformation
229
+ *
230
+ * @param schema - Standard Schema for validation
231
+ * @param options - SchemaOptions object. When Input and Output types differ, backward transformation is required
232
+ *
233
+ * @example
234
+ * // No transformation - backward not needed
235
+ * const schema = defineSchema(
236
+ * v.object({ id: v.number(), name: v.string() })
237
+ * );
238
+ *
239
+ * @example
240
+ * // With transformation - backward REQUIRED
241
+ * const schema = defineSchema(
242
+ * v.pipe(v.string(), v.transform(Number)),
243
+ * {
244
+ * backward: (num) => String(num) // backward: number → string (REQUIRED)
245
+ * }
246
+ * );
247
+ *
248
+ * @example
249
+ * // With primary key and foreign key
250
+ * const schema = defineSchema(
251
+ * v.object({ id: v.number(), customerId: v.number() }),
252
+ * {
253
+ * primaryKey: 'id',
254
+ * foreignKeys: [
255
+ * { column: 'customerId', references: { table: 'users', column: 'id' } }
256
+ * ]
257
+ * }
258
+ * );
259
+ */
260
+ function defineSchema(schema, ...args) {
261
+ const options = args[0];
262
+ const bidirectionalSchema = Object.create(schema);
263
+ if (options) {
264
+ if (options.backward) bidirectionalSchema.backward = options.backward;
265
+ if (options.primaryKey) bidirectionalSchema.primaryKey = options.primaryKey;
266
+ if (options.foreignKeys) bidirectionalSchema.foreignKeys = options.foreignKeys;
267
+ if (options.indexes) bidirectionalSchema.indexes = options.indexes;
268
+ }
269
+ Object.defineProperty(bidirectionalSchema, "~standard", {
270
+ value: schema["~standard"],
271
+ enumerable: true,
272
+ configurable: true
273
+ });
274
+ return bidirectionalSchema;
275
+ }
276
+ /**
277
+ * Check if a schema has backward transformation
278
+ */
279
+ function hasBackward(schema) {
280
+ return "backward" in schema && typeof schema.backward === "function";
281
+ }
282
+ //#endregion
283
+ //#region src/merge-fields.ts
284
+ /**
285
+ * Lay the named fields of a computed row over the line a JSONL file already holds.
286
+ *
287
+ * A field the line did not have is inserted where the schema declares it rather than appended, so a
288
+ * filled-in `id` lands at the front of the line the way a hand-written row has it. No key the line
289
+ * already had moves, and a key the schema does not declare stays behind the declared ones.
290
+ *
291
+ * @param line - The row as the JSONL file holds it
292
+ * @param computed - The row a schema computed from it, which the named fields are taken from. Only its
293
+ * own fields count: a field the schema does not produce is left to the line even when a name like
294
+ * `toString` would resolve to something on `Object.prototype`. A field it holds as `undefined` is
295
+ * left to the line as well.
296
+ * @param options - The fields to take, and the order they are declared in
297
+ * @returns A new row: the line, with the named fields written into it
298
+ *
299
+ * @example
300
+ * // line: {"name":"Alice","note":"check"}
301
+ * // computed: {"id":"018f…","name":"Alice","createdAt":"2026-…"}
302
+ * mergeFields(line, computed, { fields: ['id', 'createdAt'] });
303
+ * // {"id":"018f…","name":"Alice","createdAt":"2026-…","note":"check"}
304
+ */
305
+ function mergeFields(line, computed, options) {
306
+ const rank = /* @__PURE__ */ new Map();
307
+ for (const key of options.keyOrder ?? Object.keys(computed)) if (!rank.has(key)) rank.set(key, rank.size);
308
+ const rankOf = (key) => rank.get(key) ?? Number.MAX_SAFE_INTEGER;
309
+ const written = /* @__PURE__ */ new Map();
310
+ for (const field of options.fields) if (Object.hasOwn(computed, field) && computed[field] !== void 0) written.set(field, computed[field]);
311
+ const inserted = Array.from(written.keys()).filter((field) => !Object.hasOwn(line, field)).sort((a, b) => rankOf(a) - rankOf(b));
312
+ const entries = [];
313
+ for (const key of Object.keys(line)) {
314
+ while (inserted.length > 0 && rankOf(inserted[0]) < rankOf(key)) {
315
+ const field = inserted.shift();
316
+ entries.push([field, written.get(field)]);
317
+ }
318
+ entries.push([key, written.has(key) ? written.get(key) : line[key]]);
319
+ }
320
+ for (const field of inserted) entries.push([field, written.get(field)]);
321
+ return Object.fromEntries(entries);
322
+ }
323
+ /**
324
+ * The row with the fields its line holds that the table has no column for - a schema that strips
325
+ * unknown keys lets them through - kept where the line holds them, so writing back does not drop them
326
+ */
327
+ function keepUnknownFields(line, row, columns) {
328
+ const unknown = Object.keys(line).filter((key) => !columns.has(key) && !Object.hasOwn(row, key));
329
+ if (unknown.length === 0) return row;
330
+ const entries = [];
331
+ for (const key of Object.keys(line)) if (Object.hasOwn(row, key)) entries.push([key, row[key]]);
332
+ else if (unknown.includes(key)) entries.push([key, line[key]]);
333
+ for (const key of Object.keys(row)) if (!Object.hasOwn(line, key)) entries.push([key, row[key]]);
334
+ return Object.fromEntries(entries);
335
+ }
336
+ //#endregion
337
+ //#region src/sql-statements.ts
338
+ const TRIGGER_DEFINITION = /^\s*CREATE\s+(?:TEMP(?:ORARY)?\s+)?TRIGGER\b/i;
339
+ const CLOSER = {
340
+ "'": "'",
341
+ "\"": "\"",
342
+ "`": "`",
343
+ "[": "]"
344
+ };
345
+ /**
346
+ * Split SQL text into its statements at `;`, the way SQLite reads it: a `;` inside a comment or quoted
347
+ * text does not end a statement, and a comment is left out as the whitespace it is
348
+ */
349
+ function splitStatements(sql) {
350
+ const statements = [];
351
+ let current = "";
352
+ let i = 0;
353
+ while (i < sql.length) {
354
+ const char = sql[i];
355
+ if (char === "-" && sql[i + 1] === "-") {
356
+ const end = sql.indexOf("\n", i);
357
+ i = end === -1 ? sql.length : end;
358
+ current += " ";
359
+ } else if (char === "/" && sql[i + 1] === "*") {
360
+ const end = sql.indexOf("*/", i + 2);
361
+ i = end === -1 ? sql.length : end + 2;
362
+ current += " ";
363
+ } else if (char in CLOSER) {
364
+ const end = sql.indexOf(CLOSER[char], i + 1);
365
+ const stop = end === -1 ? sql.length : end + 1;
366
+ current += sql.slice(i, stop);
367
+ i = stop;
368
+ } else if (char === ";" && !insideTriggerBody(current)) {
369
+ statements.push(current);
370
+ current = "";
371
+ i += 1;
372
+ } else {
373
+ current += char;
374
+ i += 1;
375
+ }
376
+ }
377
+ statements.push(current);
378
+ return statements.map((statement) => statement.trim()).filter((statement) => statement.length > 0);
379
+ }
380
+ /**
381
+ * Whether a `;` after this text is inside the body of a trigger, which only a `;` followed by `END` and
382
+ * another `;` closes. Only an END right after a `;` counts, as the END of a CASE in the body does not
383
+ */
384
+ function insideTriggerBody(statement) {
385
+ return TRIGGER_DEFINITION.test(statement) && !/;\s*END$/i.test(statement.trimEnd());
386
+ }
387
+ const READ_STATEMENTS = /* @__PURE__ */ new Set([
388
+ "SELECT",
389
+ "VALUES",
390
+ "WITH",
391
+ "EXPLAIN"
392
+ ]);
393
+ const READ_PRAGMAS_WITH_ARGUMENT = /* @__PURE__ */ new Set([
394
+ "table_info",
395
+ "table_xinfo",
396
+ "table_list",
397
+ "index_list",
398
+ "index_info",
399
+ "index_xinfo",
400
+ "foreign_key_list",
401
+ "foreign_key_check",
402
+ "integrity_check",
403
+ "quick_check",
404
+ "collation_list",
405
+ "database_list",
406
+ "function_list",
407
+ "module_list",
408
+ "pragma_list",
409
+ "compile_options"
410
+ ]);
411
+ const READ_PRAGMAS_BARE = /* @__PURE__ */ new Set([
412
+ "query_only",
413
+ "user_version",
414
+ "application_id",
415
+ "schema_version",
416
+ "foreign_keys",
417
+ "journal_mode",
418
+ "page_count",
419
+ "page_size",
420
+ "freelist_count",
421
+ "encoding",
422
+ "data_version"
423
+ ]);
424
+ const PRAGMA_NAME = String.raw`(?:\w+|"[^"]*"|'[^']*'|\x60[^\x60]*\x60|\[[^\]]*\])`;
425
+ const PRAGMA_STATEMENT = new RegExp(String.raw`^PRAGMA\s+(?:${PRAGMA_NAME}\s*\.\s*)?(${PRAGMA_NAME})\s*(\(.*\))?$`, "is");
426
+ /**
427
+ * Whether a statement, as {@link splitStatements} returns it, only reads. Closed by default: whatever is
428
+ * not known to read is refused, so a statement or pragma added to SQLite later is refused too. A WITH
429
+ * can wrap a write, which the read-only mode of the connection is left to refuse
430
+ */
431
+ function isReadOnlyStatement(statement) {
432
+ const keyword = /^[A-Za-z]+/.exec(statement)?.[0]?.toUpperCase();
433
+ if (keyword === void 0) return false;
434
+ if (READ_STATEMENTS.has(keyword)) return true;
435
+ if (keyword !== "PRAGMA") return false;
436
+ const match = PRAGMA_STATEMENT.exec(statement);
437
+ if (!match) return false;
438
+ const name = match[1].replace(/^["'`[]|["'`\]]$/g, "").toLowerCase();
439
+ const argument = match[2];
440
+ if (READ_PRAGMAS_WITH_ARGUMENT.has(name)) return true;
441
+ return READ_PRAGMAS_BARE.has(name) && argument === void 0;
442
+ }
443
+ //#endregion
444
+ //#region src/database.ts
445
+ function cloneFieldChanges(changes) {
446
+ return new Map(Array.from(changes, ([tableName, byRow]) => [tableName, new Map(Array.from(byRow, ([rowid, row]) => [rowid, {
447
+ set: new Set(row.set),
448
+ reset: new Set(row.reset),
449
+ inserted: row.inserted
450
+ }]))]));
451
+ }
452
+ /** Column alias a query reads a row's rowid under, next to its fields */
453
+ const ROWID_ALIAS = "__lines_db_rowid";
454
+ /** The fields a row given to an insert names, leaving out those it leaves undefined */
455
+ function givenFields(row) {
456
+ return Object.entries(row).filter(([, value]) => value !== void 0).map(([key]) => key);
457
+ }
458
+ /** Whether a value read from SQLite and one about to be stored are the same */
459
+ function sameStoredValue(stored, next) {
460
+ if (stored === null || stored === void 0 || next === null) return (stored ?? null) === next;
461
+ return String(stored) === String(next);
462
+ }
463
+ var LinesDB = class LinesDB {
464
+ db;
465
+ rowMovesTable = `__lines_db_moves_${randomBytes(12).toString("hex")}`;
466
+ config;
467
+ schemas = /* @__PURE__ */ new Map();
468
+ validationSchemas = /* @__PURE__ */ new Map();
469
+ tables = /* @__PURE__ */ new Map();
470
+ inTransaction = false;
471
+ syncQueue = /* @__PURE__ */ new Map();
472
+ /** The order a table's schema declares its fields in, as the rows it computes list them */
473
+ keyOrders = /* @__PURE__ */ new Map();
474
+ /** The row each rowid was inserted from, per table loaded with detailed validation */
475
+ rowOriginsByRowid = /* @__PURE__ */ new Map();
476
+ /**
477
+ * The fields set and reset on each row (by rowid) since its table was last written back: a line
478
+ * holds the fields a user wrote, so only what changed since it was written needs remembering
479
+ */
480
+ fieldChanges = /* @__PURE__ */ new Map();
481
+ /**
482
+ * The tables raw SQL may have changed since they were last written back: which fields it set is
483
+ * unknown, so their rows are written back whole
484
+ */
485
+ rawSqlTables = /* @__PURE__ */ new Set();
486
+ /** How many changes each table has seen, which tells a write-back whether one came after it read the rows */
487
+ changeGenerations = /* @__PURE__ */ new Map();
488
+ /**
489
+ * The lines read, by rowid, that hold a field the table has no column for: kept to write that field
490
+ * back, also once the row's primary key changed and its line can no longer be found by it
491
+ */
492
+ linesWithUnknownFields = /* @__PURE__ */ new Map();
493
+ /** Whether a transaction's callback has returned and its files are being written back */
494
+ transactionClosing = false;
495
+ /** Whether a transaction() call is past its guard but has not begun yet */
496
+ transactionStarting = false;
497
+ /** Whether the running call came in through the object the running transaction() callback receives */
498
+ viaTransactionObject = false;
499
+ /** Identifies the running transaction, so an object kept from an earlier one is not taken for its own */
500
+ transactionToken;
501
+ /** The tables changed in the running transaction, or 'all' once raw SQL may have changed any */
502
+ transactionChanges;
503
+ /** Hash of each JSONL file's content as this database last read or wrote it */
504
+ fileHashes = /* @__PURE__ */ new Map();
505
+ /**
506
+ * Hash of each JSONL file's content as this database last read or wrote it, kept for a table that
507
+ * failed to load too: unlike fileHashes, it only tells whether a file changed and guards no write
508
+ */
509
+ observedHashes = /* @__PURE__ */ new Map();
510
+ /** The JSONL files the data directories held when the tables were scanned */
511
+ scannedJsonlFiles = [];
512
+ /** Each table's schema file and a hash of its content as the tables were loaded, or '' for none */
513
+ schemaFileStates = /* @__PURE__ */ new Map();
514
+ constructor(config, dbPath) {
515
+ this.config = config;
516
+ this.db = createDatabase(dbPath ?? ":memory:");
517
+ }
518
+ static create(config, dbPath) {
519
+ return new LinesDB(config, dbPath);
520
+ }
521
+ /**
522
+ * Initialize database by loading all JSONL files or a specific table
523
+ * Uses dependency resolution to ensure foreign key references are loaded in correct order
524
+ * @param options Optional configuration for initialization
525
+ * @param options.tableName Optional table name to initialize. If not provided, initializes all tables
526
+ * @param options.detailedValidate If true, performs detailed validation by inserting rows one by one to catch constraint violations
527
+ * @param options.transform Optional transform function to apply to rows before validation (only applied to the specified tableName)
528
+ * @returns Result wrapping a ValidationResult with validation status, errors, and warnings
529
+ */
530
+ async initialize(options) {
531
+ try {
532
+ return ok(await this.initializeInternal(options));
533
+ } catch (error) {
534
+ return err(toError(error));
535
+ }
536
+ }
537
+ async initializeInternal(options) {
538
+ if (this.hasSeveralDataDirs() && !this.config.schemaDir) throw new Error("schemaDir is required when dataDir lists several directories: a data set directory does not hold the schemas of its tables");
539
+ this.db.exec("PRAGMA query_only = OFF");
540
+ try {
541
+ return await this.loadTables(options);
542
+ } finally {
543
+ if (this.isReadOnlyDataSet()) this.db.exec("PRAGMA query_only = ON");
544
+ }
545
+ }
546
+ async loadTables(options) {
547
+ const allErrors = [];
548
+ const allWarnings = [];
549
+ const allRowCounts = /* @__PURE__ */ new Map();
550
+ const tableName = options?.tableName;
551
+ const detailedValidate = options?.detailedValidate ?? false;
552
+ const transform = options?.transform;
553
+ this.tables = await DirectoryScanner.scanDirectory(this.config.dataDir);
554
+ this.scannedJsonlFiles = listJsonlFiles(this.tables);
555
+ this.observedHashes.clear();
556
+ this.schemaFileStates.clear();
557
+ for (const [name, config] of this.tables) this.schemaFileStates.set(name, await this.schemaFileState(name, config));
558
+ const tablesToLoad = tableName ? [tableName] : Array.from(this.tables.keys());
559
+ for (const tableNameToLoad of tablesToLoad) if (!this.tables.has(tableNameToLoad)) {
560
+ const dataDirs = [this.config.dataDir].flat().map((dir) => `'${dir}'`);
561
+ throw new Error(`Table '${tableNameToLoad}' not found in directory ${dataDirs.join(", ")}`);
562
+ }
563
+ const loadedTables = /* @__PURE__ */ new Set();
564
+ const loadingTables = /* @__PURE__ */ new Set();
565
+ const attemptedTables = /* @__PURE__ */ new Set();
566
+ const allDeferredForeignKeys = [];
567
+ for (const tableNameToLoad of tablesToLoad) if (!attemptedTables.has(tableNameToLoad)) {
568
+ const tableTransform = tableNameToLoad === tableName ? transform : void 0;
569
+ const { errors, warnings, rowCounts: tableRowCounts, deferredForeignKeys } = await this.loadTableWithDependencies(tableNameToLoad, loadedTables, loadingTables, attemptedTables, detailedValidate, tableTransform);
570
+ allErrors.push(...errors);
571
+ allWarnings.push(...warnings);
572
+ allDeferredForeignKeys.push(...deferredForeignKeys);
573
+ for (const [k, v] of tableRowCounts) allRowCounts.set(k, v);
574
+ }
575
+ if (detailedValidate && allDeferredForeignKeys.length > 0) for (const { tableName: tName, foreignKey: fk, filePath } of allDeferredForeignKeys) {
576
+ if (!loadedTables.has(fk.references.table)) continue;
577
+ const deferredErrors = this.validateDeferredForeignKey(tName, fk, filePath);
578
+ allErrors.push(...deferredErrors);
579
+ }
580
+ const tableResults = tablesToLoad.map((name) => {
581
+ const tableErrors = allErrors.filter((e) => e.tableName === name);
582
+ const tableWarnings = allWarnings.filter((w) => w.includes(`'${name}'`));
583
+ return {
584
+ tableName: name,
585
+ valid: tableErrors.length === 0,
586
+ rowCount: allRowCounts.get(name) ?? 0,
587
+ errors: tableErrors,
588
+ warnings: tableWarnings
589
+ };
590
+ });
591
+ return {
592
+ valid: allErrors.length === 0,
593
+ errors: allErrors,
594
+ warnings: allWarnings,
595
+ tableResults
596
+ };
597
+ }
598
+ /**
599
+ * Load a table and its dependencies recursively
600
+ */
601
+ async loadTableWithDependencies(tableName, loadedTables, loadingTables, attemptedTables, detailedValidate, transform) {
602
+ const errors = [];
603
+ const warnings = [];
604
+ const rowCounts = /* @__PURE__ */ new Map();
605
+ const deferredForeignKeys = [];
606
+ if (attemptedTables.has(tableName)) return {
607
+ errors,
608
+ warnings,
609
+ rowCounts,
610
+ deferredForeignKeys
611
+ };
612
+ attemptedTables.add(tableName);
613
+ if (loadingTables.has(tableName)) throw new Error(`Circular dependency detected for table '${tableName}'`);
614
+ const tableConfig = this.tables.get(tableName);
615
+ if (!tableConfig) throw new Error(`Table configuration not found for '${tableName}'`);
616
+ loadingTables.add(tableName);
617
+ try {
618
+ let foreignKeys;
619
+ try {
620
+ const { pathToFileURL } = await import("node:url");
621
+ const schemaPath = await this.findTableSchemaFile(tableName, tableConfig);
622
+ if (schemaPath) {
623
+ const schemaModule = await import(`${pathToFileURL(schemaPath).href}?t=${Date.now()}`);
624
+ foreignKeys = (schemaModule.schema || schemaModule.default)?.foreignKeys || schemaModule.foreignKeys;
625
+ }
626
+ } catch {}
627
+ if (foreignKeys && foreignKeys.length > 0) for (const fk of foreignKeys) {
628
+ const referencedTable = fk.references.table;
629
+ if (referencedTable === tableName) continue;
630
+ if (!attemptedTables.has(referencedTable)) {
631
+ if (this.tables.has(referencedTable)) {
632
+ const depResult = await this.loadTableWithDependencies(referencedTable, loadedTables, loadingTables, attemptedTables, detailedValidate, void 0);
633
+ errors.push(...depResult.errors);
634
+ warnings.push(...depResult.warnings);
635
+ deferredForeignKeys.push(...depResult.deferredForeignKeys);
636
+ for (const [k, v] of depResult.rowCounts) rowCounts.set(k, v);
637
+ } else throw new Error(`Foreign key reference to non-existent table '${referencedTable}' in table '${tableName}'`);
638
+ }
639
+ }
640
+ const failedDependencies = /* @__PURE__ */ new Set();
641
+ const circularDependencies = /* @__PURE__ */ new Set();
642
+ if (foreignKeys && foreignKeys.length > 0) {
643
+ for (const fk of foreignKeys) {
644
+ const referencedTable = fk.references.table;
645
+ if (referencedTable === tableName) continue;
646
+ if (attemptedTables.has(referencedTable) && !loadedTables.has(referencedTable)) {
647
+ if (loadingTables.has(referencedTable)) circularDependencies.add(referencedTable);
648
+ else failedDependencies.add(referencedTable);
649
+ }
650
+ }
651
+ if (failedDependencies.size > 0) for (const dep of failedDependencies) warnings.push(`Skipping foreign key validation for table '${tableName}': referenced table '${dep}' has validation errors`);
652
+ }
653
+ const allSkippedDependencies = /* @__PURE__ */ new Set([...failedDependencies, ...circularDependencies]);
654
+ const { loaded, rowCount, errors: loadErrors } = await this.loadTable(tableName, tableConfig, detailedValidate, transform, allSkippedDependencies);
655
+ errors.push(...loadErrors);
656
+ rowCounts.set(tableName, rowCount);
657
+ if (loaded) {
658
+ loadedTables.add(tableName);
659
+ if (foreignKeys && circularDependencies.size > 0) {
660
+ for (const fk of foreignKeys) if (circularDependencies.has(fk.references.table)) deferredForeignKeys.push({
661
+ tableName,
662
+ foreignKey: fk,
663
+ filePath: tableConfig.jsonlPath
664
+ });
665
+ }
666
+ } else {
667
+ warnings.push(`Table '${tableName}' was not loaded (no data or skipped)`);
668
+ this.tables.delete(tableName);
669
+ }
670
+ } finally {
671
+ loadingTables.delete(tableName);
672
+ }
673
+ return {
674
+ errors,
675
+ warnings,
676
+ rowCounts,
677
+ deferredForeignKeys
678
+ };
679
+ }
680
+ /**
681
+ * Find the schema file of a table in schemaDir, or next to the table's JSONL file when unset
682
+ */
683
+ async findTableSchemaFile(tableName, config) {
684
+ return findSchemaFile(this.config.schemaDir ?? dirname(config.jsonlPath), tableName);
685
+ }
686
+ /**
687
+ * Load a single table from JSONL file
688
+ * @returns Object with loaded status and validation errors
689
+ */
690
+ async loadTable(tableName, config, detailedValidate, transform, failedDependencies) {
691
+ let data = [];
692
+ const origins = [];
693
+ const contentHashes = /* @__PURE__ */ new Map();
694
+ for (const jsonlPath of config.jsonlPaths ?? [config.jsonlPath]) {
695
+ const readResult = await JsonlReader.readSnapshot(jsonlPath);
696
+ if (!readResult.ok) throw readResult.error;
697
+ const { rows, contentHash } = readResult.value;
698
+ if (!rows.ok) throw rows.error;
699
+ if (contentHash !== void 0) {
700
+ contentHashes.set(jsonlPath, contentHash);
701
+ this.observedHashes.set(jsonlPath, contentHash);
702
+ }
703
+ rows.value.forEach((row, rowIndex) => {
704
+ data.push(row);
705
+ origins.push({
706
+ file: jsonlPath,
707
+ rowIndex
708
+ });
709
+ });
710
+ }
711
+ const transformedFields = [];
712
+ if (transform) data = data.map((row) => {
713
+ const transformed = transform(row);
714
+ transformedFields.push(Object.keys(transformed).filter((key) => JSON.stringify(transformed[key]) !== JSON.stringify(row[key])));
715
+ return transformed;
716
+ });
717
+ let validationSchema = config.validationSchema;
718
+ const schemaMetadata = {};
719
+ const schemaPath = config.validationSchema ? void 0 : await this.findTableSchemaFile(tableName, config);
720
+ if (!validationSchema && schemaPath) validationSchema = await SchemaLoader.loadSchema(config.jsonlPath, dirname(schemaPath));
721
+ if (!config.validationSchema) try {
722
+ const { pathToFileURL } = await import("node:url");
723
+ if (!schemaPath) throw new Error("Schema file not found");
724
+ const schemaModule = await import(`${pathToFileURL(schemaPath).href}?t=${Date.now()}`);
725
+ const schemaExport = schemaModule.schema || schemaModule.default;
726
+ if (schemaExport?.primaryKey) schemaMetadata.primaryKey = schemaExport.primaryKey;
727
+ else if (schemaModule.primaryKey) schemaMetadata.primaryKey = schemaModule.primaryKey;
728
+ if (schemaExport?.foreignKeys) schemaMetadata.foreignKeys = schemaExport.foreignKeys;
729
+ else if (schemaModule.foreignKeys) schemaMetadata.foreignKeys = schemaModule.foreignKeys;
730
+ if (schemaExport?.indexes) schemaMetadata.indexes = schemaExport.indexes;
731
+ else if (schemaModule.indexes) schemaMetadata.indexes = schemaModule.indexes;
732
+ if (process.env.DEBUG_LINES_DB) {
733
+ console.log(`[lines-db] Schema metadata for ${tableName}:`);
734
+ console.log(` primaryKey: ${schemaMetadata.primaryKey}`);
735
+ console.log(` foreignKeys: ${JSON.stringify(schemaMetadata.foreignKeys)}`);
736
+ console.log(` indexes: ${JSON.stringify(schemaMetadata.indexes)}`);
737
+ }
738
+ } catch (_error) {
739
+ if (process.env.DEBUG_LINES_DB) console.warn(`[lines-db] Failed to load schema metadata for ${tableName}:`, _error instanceof Error ? _error.message : String(_error));
740
+ }
741
+ this.validationSchemas.set(tableName, validationSchema);
742
+ const validationErrors = [];
743
+ const validatedData = [];
744
+ this.keyOrders.delete(tableName);
745
+ for (let rowIndex = 0; rowIndex < data.length; rowIndex++) {
746
+ const row = data[rowIndex];
747
+ try {
748
+ const validatedRow = this.validateAndTransform(tableName, row);
749
+ this.recordKeyOrder(tableName, validatedRow);
750
+ validatedData.push(validatedRow);
751
+ } catch (error) {
752
+ if (error instanceof Error && error.name === "ValidationError") validationErrors.push({
753
+ rowIndex,
754
+ rowData: row,
755
+ error
756
+ });
757
+ else throw error;
758
+ }
759
+ }
760
+ const validationErrorDetails = validationErrors.map((ve) => ({
761
+ ...origins[ve.rowIndex],
762
+ tableName,
763
+ issues: ve.error.issues,
764
+ type: "schema"
765
+ }));
766
+ if (validationErrors.length > 0) return {
767
+ loaded: false,
768
+ rowCount: data.length,
769
+ errors: validationErrorDetails
770
+ };
771
+ let schema;
772
+ let inferredSchema;
773
+ if (validatedData.length > 0) inferredSchema = unwrap(JsonlReader.inferSchema(tableName, validatedData));
774
+ if (config.schema) {
775
+ schema = config.schema;
776
+ if (inferredSchema) for (const inferredCol of inferredSchema.columns) {
777
+ const schemaCol = schema.columns.find((c) => c.name === inferredCol.name);
778
+ if (schemaCol && inferredCol.valueType && !schemaCol.valueType) schemaCol.valueType = inferredCol.valueType;
779
+ }
780
+ } else if (config.autoInferSchema !== false) {
781
+ if (validatedData.length === 0) return {
782
+ loaded: false,
783
+ rowCount: 0,
784
+ errors: []
785
+ };
786
+ schema = inferredSchema;
787
+ } else throw new Error(`No schema provided for table ${tableName} and autoInferSchema is disabled`);
788
+ const biSchema = validationSchema;
789
+ const primaryKey = biSchema?.primaryKey || schemaMetadata.primaryKey;
790
+ const foreignKeys = biSchema?.foreignKeys || schemaMetadata.foreignKeys;
791
+ const indexes = biSchema?.indexes || schemaMetadata.indexes;
792
+ if (primaryKey && !schema.columns.some((col) => col.primaryKey)) {
793
+ const col = schema.columns.find((c) => c.name === primaryKey);
794
+ if (col) col.primaryKey = true;
795
+ } else if (!primaryKey && !schema.columns.some((col) => col.primaryKey)) {
796
+ const idColumn = schema.columns.find((c) => c.name === "id");
797
+ if (idColumn) idColumn.primaryKey = true;
798
+ }
799
+ if (foreignKeys) {
800
+ schema.declaredForeignKeys = foreignKeys;
801
+ schema.foreignKeys = failedDependencies && failedDependencies.size > 0 ? foreignKeys.filter((fk) => !failedDependencies.has(fk.references.table)) : foreignKeys;
802
+ }
803
+ if (indexes) {
804
+ schema.indexes = indexes;
805
+ for (const index of indexes) if (index.unique && index.columns.length === 1) {
806
+ const col = schema.columns.find((c) => c.name === index.columns[0]);
807
+ if (col && !col.unique && !col.primaryKey) col.unique = true;
808
+ }
809
+ }
810
+ this.schemas.set(tableName, schema);
811
+ this.createTable(schema);
812
+ if (detailedValidate || this.config.writeDataSets) {
813
+ const insertErrors = this.insertDataWithDetailedValidation(tableName, schema, validatedData, origins);
814
+ if (insertErrors.length > 0) return {
815
+ loaded: false,
816
+ rowCount: data.length,
817
+ errors: insertErrors
818
+ };
819
+ } else this.insertData(tableName, schema, validatedData);
820
+ this.fieldChanges.delete(tableName);
821
+ this.linesWithUnknownFields.delete(tableName);
822
+ const columnNames = new Set(schema.columns.map((column) => column.name));
823
+ const withUnknown = data.map((row) => Object.keys(row).some((key) => !columnNames.has(key)));
824
+ if (transformedFields.some((fields) => fields.length > 0) || withUnknown.includes(true)) {
825
+ const rowids = this.queryInternal(`SELECT rowid AS "${ROWID_ALIAS}" FROM ${this.quoteTableName(tableName)} ORDER BY rowid`);
826
+ const lines = /* @__PURE__ */ new Map();
827
+ const sourceIndexes = new Map(origins.map((origin, index) => [origin, index]));
828
+ rowids.forEach((row, index) => {
829
+ const rowid = row[ROWID_ALIAS];
830
+ const origin = this.rowOriginsByRowid.get(tableName)?.get(String(rowid));
831
+ const sourceIndex = origin ? sourceIndexes.get(origin) ?? index : index;
832
+ const set = transformedFields[sourceIndex] ?? [];
833
+ if (set.length > 0) this.noteFieldChanges(tableName, rowid, { set });
834
+ if (withUnknown[sourceIndex]) lines.set(String(rowid), data[sourceIndex]);
835
+ });
836
+ this.linesWithUnknownFields.set(tableName, lines);
837
+ }
838
+ for (const [jsonlPath, contentHash] of contentHashes) this.fileHashes.set(jsonlPath, contentHash);
839
+ return {
840
+ loaded: true,
841
+ rowCount: data.length,
842
+ errors: []
843
+ };
844
+ }
845
+ /**
846
+ * Create table in SQLite with constraints and indexes
847
+ */
848
+ createTable(schema) {
849
+ const quotedTableName = this.quoteTableName(schema.name);
850
+ const uniqueColumns = /* @__PURE__ */ new Set();
851
+ for (const col of schema.columns) if (col.unique) uniqueColumns.add(col.name);
852
+ if (schema.indexes) {
853
+ for (const index of schema.indexes) if (index.unique && index.columns.length === 1) uniqueColumns.add(index.columns[0]);
854
+ }
855
+ const columnDefs = schema.columns.map((col) => {
856
+ const sqlType = col.type === "JSON" ? "TEXT" : col.type;
857
+ const parts = [this.quoteIdentifier(col.name), sqlType];
858
+ if (col.primaryKey) parts.push("PRIMARY KEY");
859
+ if (col.notNull) parts.push("NOT NULL");
860
+ if (uniqueColumns.has(col.name) && !col.primaryKey) parts.push("UNIQUE");
861
+ return parts.join(" ");
862
+ });
863
+ const foreignKeyDefs = [];
864
+ if (schema.foreignKeys && schema.foreignKeys.length > 0) for (const fk of schema.foreignKeys) {
865
+ const fkParts = [`FOREIGN KEY (${this.quoteIdentifier(fk.column)})`, `REFERENCES ${this.quoteTableName(fk.references.table)}(${this.quoteIdentifier(fk.references.column)})`];
866
+ if (fk.onDelete) fkParts.push(`ON DELETE ${fk.onDelete}`);
867
+ if (fk.onUpdate) fkParts.push(`ON UPDATE ${fk.onUpdate}`);
868
+ foreignKeyDefs.push(fkParts.join(" "));
869
+ }
870
+ const sql = `CREATE TABLE IF NOT EXISTS ${quotedTableName} (${[...columnDefs, ...foreignKeyDefs].join(", ")})`;
871
+ this.db.exec(sql);
872
+ if (this.hasSeveralDataDirs() && this.config.writeDataSets) {
873
+ const moves = this.quoteIdentifier(this.rowMovesTable);
874
+ const trigger = this.quoteIdentifier(`${this.rowMovesTable}_${schema.name}`);
875
+ const name = `'${schema.name.replace(/'/g, "''")}'`;
876
+ this.db.exec(`CREATE TEMP TABLE IF NOT EXISTS ${moves} (tableName TEXT, oldRowid INTEGER, newRowid INTEGER)`);
877
+ this.db.exec(`CREATE TEMP TRIGGER IF NOT EXISTS ${trigger} AFTER UPDATE ON ${quotedTableName}
878
+ WHEN OLD.rowid != NEW.rowid BEGIN
879
+ INSERT INTO ${moves} VALUES (${name}, OLD.rowid, NEW.rowid);
880
+ END`);
881
+ }
882
+ if (schema.indexes && schema.indexes.length > 0) for (let i = 0; i < schema.indexes.length; i++) {
883
+ const index = schema.indexes[i];
884
+ const safeTableName = schema.name.replace(/[^a-zA-Z0-9]/g, "_");
885
+ const resolvedIndexName = index.name || `idx_${safeTableName}_${index.columns.join("_")}_${i}`;
886
+ const indexSql = `CREATE ${index.unique ? "UNIQUE " : ""}INDEX IF NOT EXISTS ${this.quoteIdentifier(resolvedIndexName)} ON ${quotedTableName} (${index.columns.map((col) => this.quoteIdentifier(col)).join(", ")})`;
887
+ this.db.exec(indexSql);
888
+ }
889
+ }
890
+ /**
891
+ * Quote table name to handle special characters in SQL
892
+ */
893
+ quoteTableName(tableName) {
894
+ return this.quoteIdentifier(tableName);
895
+ }
896
+ /**
897
+ * Quote identifier for SQL statements, escaping embedded quotes
898
+ */
899
+ quoteIdentifier(identifier) {
900
+ return `"${identifier.replace(/"/g, "\"\"")}"`;
901
+ }
902
+ /**
903
+ * Insert data into table using batch insert (multiple rows per SQL)
904
+ * SQLite has a parameter limit (default 999), so we batch rows accordingly
905
+ * Throws exception if any constraint violation occurs
906
+ */
907
+ insertData(tableName, schema, data) {
908
+ if (data.length === 0) return;
909
+ const columnNames = schema.columns.map((col) => col.name);
910
+ const quotedColumns = columnNames.map((name) => this.quoteIdentifier(name));
911
+ const columnCount = columnNames.length;
912
+ const maxBatchSize = Math.floor(900 / columnCount);
913
+ const batchSize = Math.max(1, Math.min(maxBatchSize, 100));
914
+ for (let i = 0; i < data.length; i += batchSize) {
915
+ const batch = data.slice(i, i + batchSize);
916
+ const rowPlaceholders = columnNames.map(() => "?").join(", ");
917
+ const valuesPlaceholders = batch.map(() => `(${rowPlaceholders})`).join(", ");
918
+ const sql = `INSERT INTO ${this.quoteTableName(tableName)} (${quotedColumns.join(", ")}) VALUES ${valuesPlaceholders}`;
919
+ const values = [];
920
+ for (const row of batch) for (const col of columnNames) values.push(this.normalizeValue(row[col]));
921
+ this.db.prepare(sql).run(...values);
922
+ }
923
+ }
924
+ /**
925
+ * Insert data into table one row at a time with detailed error reporting
926
+ * This is used for validation to catch constraint violations
927
+ */
928
+ insertDataWithDetailedValidation(tableName, schema, data, origins) {
929
+ const errors = [];
930
+ const columnNames = schema.columns.map((col) => col.name);
931
+ const quotedColumns = columnNames.map((name) => this.quoteIdentifier(name));
932
+ const placeholders = columnNames.map(() => "?").join(", ");
933
+ const sql = `INSERT INTO ${this.quoteTableName(tableName)} (${quotedColumns.join(", ")}) VALUES (${placeholders})`;
934
+ const stmt = this.db.prepare(sql);
935
+ const rowOrigins = /* @__PURE__ */ new Map();
936
+ this.rowOriginsByRowid.set(tableName, rowOrigins);
937
+ for (let rowIndex = 0; rowIndex < data.length; rowIndex++) {
938
+ const row = data[rowIndex];
939
+ try {
940
+ const values = columnNames.map((col) => this.normalizeValue(row[col]));
941
+ const { lastInsertRowid } = stmt.run(...values);
942
+ rowOrigins.set(String(lastInsertRowid), origins[rowIndex]);
943
+ } catch (error) {
944
+ const constraintError = this.analyzeConstraintError(error, origins[rowIndex].file, tableName, origins[rowIndex].rowIndex, row, schema.foreignKeys || []);
945
+ if (constraintError) errors.push(constraintError);
946
+ }
947
+ }
948
+ return errors;
949
+ }
950
+ /**
951
+ * Analyze constraint error and extract detailed information
952
+ */
953
+ analyzeConstraintError(error, file, tableName, rowIndex, row, foreignKeys) {
954
+ const errorMessage = error instanceof Error ? error.message : String(error);
955
+ if (errorMessage.includes("FOREIGN KEY constraint failed")) for (const fk of foreignKeys) {
956
+ const fkValue = row[fk.column];
957
+ if (fkValue === null || fkValue === void 0) continue;
958
+ try {
959
+ const result = this.queryInternal(`SELECT COUNT(*) as count FROM ${this.quoteIdentifier(fk.references.table)} WHERE ${this.quoteIdentifier(fk.references.column)} = ?`, [this.normalizeValue(fkValue)]);
960
+ if (result.length > 0 && result[0].count === 0) return {
961
+ file,
962
+ tableName,
963
+ rowIndex,
964
+ issues: [],
965
+ type: "foreignKey",
966
+ foreignKeyError: {
967
+ column: fk.column,
968
+ value: fkValue,
969
+ referencedTable: fk.references.table,
970
+ referencedColumn: fk.references.column
971
+ }
972
+ };
973
+ } catch (_) {}
974
+ }
975
+ return {
976
+ file,
977
+ tableName,
978
+ rowIndex,
979
+ issues: [{
980
+ message: errorMessage,
981
+ path: []
982
+ }],
983
+ type: "schema"
984
+ };
985
+ }
986
+ /**
987
+ * Validate a deferred foreign key constraint after all tables have been loaded.
988
+ * Used for circular dependency FK validation.
989
+ */
990
+ validateDeferredForeignKey(tableName, fk, filePath) {
991
+ const errors = [];
992
+ const quotedTable = this.quoteTableName(tableName);
993
+ const quotedColumn = this.quoteIdentifier(fk.column);
994
+ const quotedRefTable = this.quoteTableName(fk.references.table);
995
+ const sql = `SELECT rowid as rid, ${quotedColumn} as val FROM ${quotedTable} WHERE ${quotedColumn} IS NOT NULL AND ${quotedColumn} NOT IN (SELECT ${this.quoteIdentifier(fk.references.column)} FROM ${quotedRefTable})`;
996
+ try {
997
+ const rows = this.queryInternal(sql);
998
+ const rowOrigins = this.rowOriginsByRowid.get(tableName);
999
+ for (const row of rows) errors.push({
1000
+ ...rowOrigins?.get(String(row.rid)) ?? {
1001
+ file: filePath,
1002
+ rowIndex: Number(row.rid) - 1
1003
+ },
1004
+ tableName,
1005
+ issues: [],
1006
+ type: "foreignKey",
1007
+ foreignKeyError: {
1008
+ column: fk.column,
1009
+ value: row.val,
1010
+ referencedTable: fk.references.table,
1011
+ referencedColumn: fk.references.column
1012
+ }
1013
+ });
1014
+ } catch (_) {}
1015
+ return errors;
1016
+ }
1017
+ /**
1018
+ * Execute a raw SQL query
1019
+ */
1020
+ query(sql, params = []) {
1021
+ try {
1022
+ this.enforceReadOnlySql();
1023
+ this.refuseUnsafeSql(sql);
1024
+ return ok(this.trackRawSql(() => this.readOnlyWhileTransactionSettles(() => this.queryInternal(sql, params))));
1025
+ } catch (error) {
1026
+ return err(toError(error));
1027
+ }
1028
+ }
1029
+ queryInternal(sql, params = []) {
1030
+ return this.db.prepare(sql).all(...params);
1031
+ }
1032
+ /**
1033
+ * Execute a SQL query that returns a single row
1034
+ */
1035
+ queryOne(sql, params = []) {
1036
+ try {
1037
+ this.enforceReadOnlySql();
1038
+ this.refuseUnsafeSql(sql);
1039
+ return ok(this.trackRawSql(() => this.readOnlyWhileTransactionSettles(() => this.queryOneInternal(sql, params))));
1040
+ } catch (error) {
1041
+ return err(toError(error));
1042
+ }
1043
+ }
1044
+ queryOneInternal(sql, params = []) {
1045
+ const result = this.db.prepare(sql).get(...params);
1046
+ return result === void 0 ? null : result;
1047
+ }
1048
+ /**
1049
+ * Execute a SQL statement (INSERT, UPDATE, DELETE)
1050
+ */
1051
+ execute(sql, params = []) {
1052
+ try {
1053
+ this.enforceReadOnlySql();
1054
+ this.refuseUnsafeSql(sql);
1055
+ this.refuseWhileTransactionSettles("run SQL");
1056
+ return ok(this.trackRawSql(() => this.readOnlyWhileTransactionSettles(() => this.executeInternal(sql, params))));
1057
+ } catch (error) {
1058
+ return err(toError(error));
1059
+ }
1060
+ }
1061
+ /**
1062
+ * Run a caller's SQL, and when it changed rows, write back every table whole: which tables and
1063
+ * fields raw SQL changed is unknown, and a query() can change rows with RETURNING too
1064
+ */
1065
+ trackRawSql(run) {
1066
+ const before = this.totalChanges();
1067
+ try {
1068
+ return run();
1069
+ } finally {
1070
+ if (this.totalChanges() !== before) {
1071
+ for (const tableName of this.schemas.keys()) {
1072
+ this.rawSqlTables.add(tableName);
1073
+ this.noteChange(tableName);
1074
+ }
1075
+ this.forgetLinesOfGoneRows(this.schemas.keys());
1076
+ if (this.transactionChanges) this.transactionChanges = "all";
1077
+ }
1078
+ }
1079
+ }
1080
+ totalChanges() {
1081
+ return Number(this.db.prepare("SELECT total_changes() AS n").get().n);
1082
+ }
1083
+ executeInternal(sql, params = []) {
1084
+ const result = this.db.prepare(sql).run(...params);
1085
+ if (this.hasSeveralDataDirs() && this.config.writeDataSets) {
1086
+ const moves = this.quoteIdentifier(this.rowMovesTable);
1087
+ const changes = this.queryInternal(`SELECT tableName, oldRowid, newRowid FROM ${moves} ORDER BY rowid`);
1088
+ for (const change of changes) this.moveRowMetadata(change.tableName, String(change.oldRowid), String(change.newRowid));
1089
+ if (changes.length > 0) this.db.exec(`DELETE FROM ${moves}`);
1090
+ }
1091
+ return result;
1092
+ }
1093
+ /**
1094
+ * Find rows by condition (supports OR/AND with arrays and function filters)
1095
+ * If where is not provided, returns all rows
1096
+ */
1097
+ find(tableName, where) {
1098
+ try {
1099
+ return ok(this.findInternal(tableName, where));
1100
+ } catch (error) {
1101
+ return err(toError(error));
1102
+ }
1103
+ }
1104
+ findInternal(tableName, where) {
1105
+ if (where === void 0) return this.queryInternal(`SELECT * FROM ${this.quoteTableName(tableName)}`).map((row) => this.deserializeRow(tableName, row));
1106
+ if (Array.isArray(where) && where.length === 0) return [];
1107
+ const { sql, values, functionFilters, hasOrWithFunctionFilters } = this.buildWhereClause(where);
1108
+ let rows;
1109
+ if (hasOrWithFunctionFilters) {
1110
+ rows = this.queryInternal(`SELECT * FROM ${this.quoteTableName(tableName)}`).map((row) => this.deserializeRow(tableName, row));
1111
+ return this.applyOrConditionWithFilters(rows, where);
1112
+ }
1113
+ if (sql) rows = this.queryInternal(`SELECT * FROM ${this.quoteTableName(tableName)} WHERE ${sql}`, values).map((row) => this.deserializeRow(tableName, row));
1114
+ else rows = this.queryInternal(`SELECT * FROM ${this.quoteTableName(tableName)}`).map((row) => this.deserializeRow(tableName, row));
1115
+ return this.applyFunctionFilters(rows, functionFilters);
1116
+ }
1117
+ /**
1118
+ * Find a single row by condition (supports OR/AND with arrays and function filters)
1119
+ */
1120
+ findOne(tableName, where) {
1121
+ try {
1122
+ return ok(this.findOneInternal(tableName, where));
1123
+ } catch (error) {
1124
+ return err(toError(error));
1125
+ }
1126
+ }
1127
+ findOneInternal(tableName, where) {
1128
+ const { sql, values, functionFilters } = this.buildWhereClause(where);
1129
+ let rows;
1130
+ if (sql) rows = this.queryInternal(`SELECT * FROM ${this.quoteTableName(tableName)} WHERE ${sql}`, values).map((row) => this.deserializeRow(tableName, row));
1131
+ else rows = this.queryInternal(`SELECT * FROM ${this.quoteTableName(tableName)}`).map((row) => this.deserializeRow(tableName, row));
1132
+ const filtered = this.applyFunctionFilters(rows, functionFilters);
1133
+ return filtered.length > 0 ? filtered[0] : null;
1134
+ }
1135
+ /**
1136
+ * Deserialize JSON columns in a row
1137
+ */
1138
+ deserializeRow(tableName, row) {
1139
+ const schema = this.schemas.get(tableName);
1140
+ if (!schema) return row;
1141
+ const deserializedRow = { ...row };
1142
+ for (const column of schema.columns) {
1143
+ const colName = column.name;
1144
+ if (!(colName in deserializedRow)) continue;
1145
+ const value = deserializedRow[colName];
1146
+ if (column.type === "JSON" && typeof value === "string") {
1147
+ try {
1148
+ deserializedRow[colName] = JSON.parse(value);
1149
+ } catch (error) {
1150
+ console.warn(`Failed to parse JSON column ${colName}:`, error);
1151
+ }
1152
+ continue;
1153
+ }
1154
+ if (column.valueType === "boolean") {
1155
+ if (typeof value === "number") deserializedRow[colName] = value === 0 ? false : true;
1156
+ else if (typeof value === "bigint") deserializedRow[colName] = value === 0n ? false : true;
1157
+ }
1158
+ }
1159
+ return deserializedRow;
1160
+ }
1161
+ /**
1162
+ * Validate data using StandardSchema and return the transformed value
1163
+ * Note: Only synchronous validation is supported
1164
+ */
1165
+ validateAndTransform(tableName, data) {
1166
+ const schema = this.validationSchemas.get(tableName);
1167
+ if (!schema) return data;
1168
+ const result = schema["~standard"].validate(data);
1169
+ if (result instanceof Promise) throw new Error("Asynchronous validation is not supported. Please use synchronous validation schemas.");
1170
+ if (result.issues && result.issues.length > 0) {
1171
+ const errorMessage = `Validation failed for table '${tableName}':\n${result.issues.map((issue) => {
1172
+ let pathStr = "root";
1173
+ if (issue.path && issue.path.length > 0) pathStr = issue.path.map((segment) => {
1174
+ if (typeof segment === "object" && segment !== null && "key" in segment) return String(segment.key);
1175
+ return String(segment);
1176
+ }).join(".");
1177
+ return ` - ${pathStr}: ${issue.message}`;
1178
+ }).join("\n")}`;
1179
+ const error = new Error(errorMessage);
1180
+ error.name = "ValidationError";
1181
+ error.issues = result.issues;
1182
+ throw error;
1183
+ }
1184
+ const transformedValue = "value" in result ? result.value : data;
1185
+ const normalizedValue = {};
1186
+ for (const [key, value] of Object.entries(transformedValue)) normalizedValue[key] = value === void 0 ? null : value;
1187
+ return normalizedValue;
1188
+ }
1189
+ /**
1190
+ * Validate data using StandardSchema (without returning transformed value)
1191
+ * Note: Only synchronous validation is supported
1192
+ */
1193
+ validateData(tableName, data) {
1194
+ this.validateAndTransform(tableName, data);
1195
+ }
1196
+ /**
1197
+ * Remember the order a computed row lists its fields in - the order the schema declares them, since
1198
+ * that is the order a hook or a validation fills a row in. A sync inserts a key the line did not
1199
+ * have at the place this order gives it.
1200
+ */
1201
+ recordKeyOrder(tableName, row) {
1202
+ const order = this.keyOrders.get(tableName) ?? /* @__PURE__ */ new Set();
1203
+ for (const key of Object.keys(row)) order.add(key);
1204
+ this.keyOrders.set(tableName, order);
1205
+ }
1206
+ /**
1207
+ * Insert a row into a table with validation
1208
+ */
1209
+ insert(tableName, data, options) {
1210
+ try {
1211
+ return ok(this.insertInternal(tableName, data, options));
1212
+ } catch (error) {
1213
+ return err(toError(error));
1214
+ }
1215
+ }
1216
+ insertInternal(tableName, data, options) {
1217
+ this.assertMutable(tableName);
1218
+ let destination;
1219
+ if (this.hasSeveralDataDirs()) {
1220
+ const dataDir = options?.dataDir;
1221
+ if (!dataDir || ![this.config.dataDir].flat().some((dir) => resolve(dir) === resolve(dataDir))) throw new Error("Choose an insert dataDir from the configured data directories");
1222
+ destination = join([this.config.dataDir].flat().find((dir) => resolve(dir) === resolve(dataDir)), `${tableName}.jsonl`);
1223
+ }
1224
+ const row = this.validateAndTransform(tableName, data);
1225
+ if (!this.schemas.get(tableName)) throw new Error(`Table ${tableName} does not exist`);
1226
+ const columnNames = Object.keys(row);
1227
+ const quotedColumns = columnNames.map((col) => this.quoteIdentifier(col));
1228
+ const placeholders = columnNames.map(() => "?").join(", ");
1229
+ const sql = `INSERT INTO ${this.quoteTableName(tableName)} (${quotedColumns.join(", ")}) VALUES (${placeholders})`;
1230
+ const values = Object.values(row).map((v) => this.normalizeValue(v));
1231
+ const result = this.executeInternal(sql, values);
1232
+ if (destination) {
1233
+ const origins = this.rowOriginsByRowid.get(tableName) ?? /* @__PURE__ */ new Map();
1234
+ origins.set(String(result.lastInsertRowid), {
1235
+ file: destination,
1236
+ rowIndex: -1
1237
+ });
1238
+ this.rowOriginsByRowid.set(tableName, origins);
1239
+ }
1240
+ this.noteFieldChanges(tableName, result.lastInsertRowid, {
1241
+ set: givenFields(data),
1242
+ inserted: true
1243
+ });
1244
+ this.afterWrite(tableName, result.changes);
1245
+ return result;
1246
+ }
1247
+ /**
1248
+ * Batch insert rows with validation per record.
1249
+ */
1250
+ batchInsert(tableName, records) {
1251
+ try {
1252
+ return ok(this.batchInsertInternal(tableName, records));
1253
+ } catch (error) {
1254
+ return err(toError(error));
1255
+ }
1256
+ }
1257
+ batchInsertInternal(tableName, records) {
1258
+ this.assertMutable(tableName);
1259
+ if (this.hasSeveralDataDirs()) throw new Error("Use insert with a dataDir for data sets");
1260
+ if (!this.schemas.get(tableName)) throw new Error(`Table ${tableName} does not exist`);
1261
+ if (records.length === 0) return {
1262
+ changes: 0,
1263
+ lastInsertRowid: 0
1264
+ };
1265
+ let totalChanges = 0n;
1266
+ let lastRowid = 0n;
1267
+ try {
1268
+ for (const record of records) {
1269
+ const row = this.validateAndTransform(tableName, record);
1270
+ const columnNames = Object.keys(row);
1271
+ const quotedColumns = columnNames.map((col) => this.quoteIdentifier(col));
1272
+ const placeholders = columnNames.map(() => "?").join(", ");
1273
+ const sql = `INSERT INTO ${this.quoteTableName(tableName)} (${quotedColumns.join(", ")}) VALUES (${placeholders})`;
1274
+ const values = columnNames.map((col) => this.normalizeValue(row[col]));
1275
+ const result = this.executeInternal(sql, values);
1276
+ this.noteFieldChanges(tableName, result.lastInsertRowid, {
1277
+ set: givenFields(record),
1278
+ inserted: true
1279
+ });
1280
+ totalChanges += BigInt(result.changes);
1281
+ lastRowid = BigInt(result.lastInsertRowid);
1282
+ }
1283
+ } finally {
1284
+ this.afterWrite(tableName, totalChanges);
1285
+ }
1286
+ return {
1287
+ changes: totalChanges,
1288
+ lastInsertRowid: lastRowid
1289
+ };
1290
+ }
1291
+ /**
1292
+ * Update rows in a table with validation (supports OR/AND with arrays)
1293
+ * Note: Function filters are not supported for update operations
1294
+ * Note: By default, validation is enabled. For partial updates, existing data is fetched
1295
+ * and merged before validation. Set options.validate = false to disable validation.
1296
+ */
1297
+ update(tableName, data, where, options) {
1298
+ try {
1299
+ return ok(this.updateInternal(tableName, data, where, options));
1300
+ } catch (error) {
1301
+ return err(toError(error));
1302
+ }
1303
+ }
1304
+ updateInternal(tableName, data, where, options) {
1305
+ this.assertMutable(tableName);
1306
+ if (!this.schemas.get(tableName)) throw new Error(`Table ${tableName} does not exist`);
1307
+ const shouldValidate = options?.validate !== false;
1308
+ const hasValidationSchema = this.validationSchemas.has(tableName);
1309
+ if (shouldValidate && hasValidationSchema) {
1310
+ const existingRows = this.findInternal(tableName, where);
1311
+ for (const existingRow of existingRows) {
1312
+ const mergedData = {
1313
+ ...existingRow,
1314
+ ...data
1315
+ };
1316
+ for (const field of options?.resetToDefault ?? []) delete mergedData[field];
1317
+ this.validateData(tableName, mergedData);
1318
+ }
1319
+ }
1320
+ const { sql: whereSql, values: whereValues, functionFilters } = this.buildWhereClause(where);
1321
+ if (functionFilters.length > 0) throw new Error("Function filters are not supported in update operations");
1322
+ const targets = this.queryInternal(`SELECT rowid AS "${ROWID_ALIAS}", * FROM ${this.quoteTableName(tableName)} WHERE ${whereSql}`, whereValues);
1323
+ const resetFields = options?.resetToDefault ?? [];
1324
+ const resets = resetFields.length > 0 ? this.computeResets(tableName, targets, data, resetFields) : [];
1325
+ let result = {
1326
+ changes: 0,
1327
+ lastInsertRowid: 0
1328
+ };
1329
+ if (Object.keys(data).length > 0) {
1330
+ const setClauses = Object.keys(data).map((key) => `${this.quoteIdentifier(key)} = ?`).join(", ");
1331
+ const sql = `UPDATE ${this.quoteTableName(tableName)} SET ${setClauses} WHERE ${whereSql}`;
1332
+ const values = [...Object.values(data).map((v) => this.normalizeValue(v)), ...whereValues];
1333
+ result = this.executeInternal(sql, values);
1334
+ }
1335
+ const pkName = this.schemas.get(tableName)?.columns.find((col) => col.primaryKey)?.name;
1336
+ if (pkName && Object.hasOwn(data, pkName)) {
1337
+ const moved = this.queryInternal(`SELECT rowid AS "${ROWID_ALIAS}" FROM ${this.quoteTableName(tableName)} WHERE ${this.quoteIdentifier(pkName)} = ?`, [this.normalizeValue(data[pkName])]);
1338
+ if (targets.length === 1 && moved.length === 1) {
1339
+ const from = String(targets[0][ROWID_ALIAS]);
1340
+ const to = moved[0][ROWID_ALIAS];
1341
+ if (from !== String(to)) {
1342
+ this.moveRowMetadata(tableName, from, String(to));
1343
+ targets[0] = {
1344
+ ...targets[0],
1345
+ [ROWID_ALIAS]: to
1346
+ };
1347
+ }
1348
+ }
1349
+ }
1350
+ for (const target of targets) {
1351
+ const set = Object.keys(data).filter((key) => !sameStoredValue(target[key], this.normalizeValue(data[key])));
1352
+ this.noteFieldChanges(tableName, target[ROWID_ALIAS], { set });
1353
+ }
1354
+ if (resets.length > 0) result = this.applyResets(tableName, resets, resetFields);
1355
+ this.afterWrite(tableName, result.changes);
1356
+ return result;
1357
+ }
1358
+ /**
1359
+ * Batch update rows with record-specific values and validation.
1360
+ * Each record must include the primary key to identify the target row.
1361
+ * Validation runs once per merged record unless explicitly disabled.
1362
+ */
1363
+ batchUpdate(tableName, records, options) {
1364
+ try {
1365
+ return ok(this.batchUpdateInternal(tableName, records, options));
1366
+ } catch (error) {
1367
+ return err(toError(error));
1368
+ }
1369
+ }
1370
+ batchUpdateInternal(tableName, records, options) {
1371
+ this.assertMutable(tableName);
1372
+ const schema = this.schemas.get(tableName);
1373
+ if (!schema) throw new Error(`Table ${tableName} does not exist`);
1374
+ if (records.length === 0) return {
1375
+ changes: 0,
1376
+ lastInsertRowid: 0
1377
+ };
1378
+ const pkColumn = schema.columns.find((col) => col.primaryKey);
1379
+ if (!pkColumn) throw new Error(`Table ${tableName} does not have a primary key`);
1380
+ const pkName = pkColumn.name;
1381
+ const pkValues = [];
1382
+ for (const record of records) {
1383
+ const pkValue = record[pkName];
1384
+ if (pkValue === void 0) throw new Error(`Record is missing primary key '${String(pkName)}': ${JSON.stringify(record)}`);
1385
+ pkValues.push(pkValue);
1386
+ }
1387
+ const shouldValidate = options?.validate !== false;
1388
+ const hasValidationSchema = this.validationSchemas.has(tableName);
1389
+ if (shouldValidate && hasValidationSchema) {
1390
+ const orCondition = pkValues.map((pkValue) => ({ [pkName]: pkValue }));
1391
+ const existingRows = this.findInternal(tableName, orCondition);
1392
+ const existingRowsMap = /* @__PURE__ */ new Map();
1393
+ for (const row of existingRows) {
1394
+ const pkValue = row[pkName];
1395
+ existingRowsMap.set(pkValue, row);
1396
+ }
1397
+ const validationErrors = [];
1398
+ for (let i = 0; i < records.length; i++) {
1399
+ const record = records[i];
1400
+ const pkValue = record[pkName];
1401
+ const existingRow = existingRowsMap.get(pkValue);
1402
+ if (!existingRow) throw new Error(`No existing row found with ${String(pkName)}=${JSON.stringify(pkValue)}`);
1403
+ const mergedData = {
1404
+ ...existingRow,
1405
+ ...record
1406
+ };
1407
+ try {
1408
+ this.validateData(tableName, mergedData);
1409
+ } catch (error) {
1410
+ if (error instanceof Error && error.name === "ValidationError") validationErrors.push({
1411
+ rowIndex: i,
1412
+ rowData: mergedData,
1413
+ pkValue,
1414
+ error
1415
+ });
1416
+ else throw error;
1417
+ }
1418
+ }
1419
+ if (validationErrors.length > 0) {
1420
+ const enhancedError = /* @__PURE__ */ new Error(`Validation failed for ${validationErrors.length} row(s)`);
1421
+ enhancedError.name = "ValidationError";
1422
+ enhancedError.validationErrors = validationErrors;
1423
+ enhancedError.issues = validationErrors[0].error.issues;
1424
+ throw enhancedError;
1425
+ }
1426
+ }
1427
+ let totalChanges = 0n;
1428
+ let lastRowid = 0n;
1429
+ for (const record of records) {
1430
+ const pkValue = record[pkName];
1431
+ const where = { [pkName]: pkValue };
1432
+ const result = this.updateInternal(tableName, record, where, { validate: false });
1433
+ totalChanges += BigInt(result.changes);
1434
+ lastRowid = BigInt(result.lastInsertRowid);
1435
+ }
1436
+ return {
1437
+ changes: totalChanges,
1438
+ lastInsertRowid: lastRowid
1439
+ };
1440
+ }
1441
+ /**
1442
+ * Delete rows from a table (supports OR/AND with arrays)
1443
+ * Note: Function filters are not supported for delete operations
1444
+ */
1445
+ delete(tableName, where) {
1446
+ try {
1447
+ return ok(this.deleteInternal(tableName, where));
1448
+ } catch (error) {
1449
+ return err(toError(error));
1450
+ }
1451
+ }
1452
+ deleteInternal(tableName, where) {
1453
+ this.assertMutable(tableName);
1454
+ if (!this.schemas.get(tableName)) throw new Error(`Table ${tableName} does not exist`);
1455
+ const { sql: whereSql, values, functionFilters } = this.buildWhereClause(where);
1456
+ if (functionFilters.length > 0) throw new Error("Function filters are not supported in delete operations");
1457
+ const deleted = this.rowidsWhere(tableName, whereSql, values);
1458
+ const sql = `DELETE FROM ${this.quoteTableName(tableName)} WHERE ${whereSql}`;
1459
+ const result = this.executeInternal(sql, values);
1460
+ this.forgetFieldChanges(tableName, deleted);
1461
+ this.afterWrite(tableName, result.changes);
1462
+ return result;
1463
+ }
1464
+ /**
1465
+ * Batch delete rows by primary key.
1466
+ */
1467
+ batchDelete(tableName, records) {
1468
+ try {
1469
+ return ok(this.batchDeleteInternal(tableName, records));
1470
+ } catch (error) {
1471
+ return err(toError(error));
1472
+ }
1473
+ }
1474
+ batchDeleteInternal(tableName, records) {
1475
+ this.assertMutable(tableName);
1476
+ const schema = this.schemas.get(tableName);
1477
+ if (!schema) throw new Error(`Table ${tableName} does not exist`);
1478
+ if (records.length === 0) return {
1479
+ changes: 0,
1480
+ lastInsertRowid: 0
1481
+ };
1482
+ const pkColumn = schema.columns.find((col) => col.primaryKey);
1483
+ if (!pkColumn) throw new Error(`Table ${tableName} does not have a primary key`);
1484
+ const pkName = pkColumn.name;
1485
+ const pkValues = records.map((record, index) => {
1486
+ const pkValue = record[pkName];
1487
+ if (pkValue === void 0) throw new Error(`Record at index ${index} is missing primary key '${String(pkName)}'`);
1488
+ return pkValue;
1489
+ });
1490
+ const placeholders = pkValues.map(() => "?").join(", ");
1491
+ const sql = `DELETE FROM ${this.quoteTableName(tableName)} WHERE ${this.quoteIdentifier(pkName)} IN (${placeholders})`;
1492
+ const values = pkValues.map((value) => this.normalizeValue(value));
1493
+ const deleted = this.rowidsWhere(tableName, `${this.quoteIdentifier(pkName)} IN (${placeholders})`, values);
1494
+ const result = this.executeInternal(sql, values);
1495
+ this.forgetFieldChanges(tableName, deleted);
1496
+ this.afterWrite(tableName, result.changes);
1497
+ return {
1498
+ changes: BigInt(result.changes),
1499
+ lastInsertRowid: BigInt(result.lastInsertRowid)
1500
+ };
1501
+ }
1502
+ /**
1503
+ * Normalize value for SQLite
1504
+ */
1505
+ normalizeValue(value) {
1506
+ if (value === null || value === void 0) return null;
1507
+ if (typeof value === "boolean") return value ? 1 : 0;
1508
+ if (typeof value === "string" || typeof value === "number" || typeof value === "bigint") return value;
1509
+ if (value instanceof Uint8Array) return value;
1510
+ return JSON.stringify(value);
1511
+ }
1512
+ /**
1513
+ * Build WHERE clause from condition (supports OR/AND with arrays and functions)
1514
+ */
1515
+ buildWhereClause(condition) {
1516
+ const values = [];
1517
+ const functionFilters = [];
1518
+ let hasOrWithFunctionFilters = false;
1519
+ const buildCondition = (cond, isInOr = false) => {
1520
+ if (Array.isArray(cond)) return cond.map((item) => {
1521
+ const clause = Array.isArray(item) ? buildCondition(item, true) : buildCondition(item, true);
1522
+ return clause ? `(${clause})` : "";
1523
+ }).filter((clause) => clause !== "").join(" OR ");
1524
+ const conditions = [];
1525
+ let hasFunctionFilter = false;
1526
+ for (const [key, value] of Object.entries(cond)) if (typeof value === "function") {
1527
+ functionFilters.push({
1528
+ key,
1529
+ fn: value
1530
+ });
1531
+ hasFunctionFilter = true;
1532
+ } else {
1533
+ conditions.push(`${this.quoteIdentifier(key)} = ?`);
1534
+ values.push(this.normalizeValue(value));
1535
+ }
1536
+ if (isInOr && hasFunctionFilter) hasOrWithFunctionFilters = true;
1537
+ return conditions.join(" AND ");
1538
+ };
1539
+ return {
1540
+ sql: buildCondition(condition),
1541
+ values,
1542
+ functionFilters,
1543
+ hasOrWithFunctionFilters
1544
+ };
1545
+ }
1546
+ /**
1547
+ * Apply OR condition with function filters by evaluating each row against the condition
1548
+ */
1549
+ applyOrConditionWithFilters(rows, condition) {
1550
+ return rows.filter((row) => this.matchesOrCondition(row, condition));
1551
+ }
1552
+ /**
1553
+ * Check if a row matches an OR/AND condition (recursively)
1554
+ */
1555
+ matchesOrCondition(row, condition) {
1556
+ if (Array.isArray(condition)) return condition.some((item) => this.matchesOrCondition(row, item));
1557
+ return Object.entries(condition).every(([key, value]) => {
1558
+ const rowValue = row[key];
1559
+ if (typeof value === "function") return value(rowValue);
1560
+ return rowValue === value;
1561
+ });
1562
+ }
1563
+ /**
1564
+ * Apply function filters to rows
1565
+ */
1566
+ applyFunctionFilters(rows, functionFilters) {
1567
+ if (functionFilters.length === 0) return rows;
1568
+ return rows.filter((row) => {
1569
+ return functionFilters.every(({ key, fn }) => {
1570
+ const value = row[key];
1571
+ return fn(value);
1572
+ });
1573
+ });
1574
+ }
1575
+ /**
1576
+ * Get table schema
1577
+ */
1578
+ /**
1579
+ * Validate a row against a table's schema, also for a table left out on load because rows failed
1580
+ * validation, so a fix can be checked before it is written to the file
1581
+ */
1582
+ validateRow(tableName, row) {
1583
+ if (!this.tables.has(tableName) && !this.validationSchemas.has(tableName)) {
1584
+ const error = /* @__PURE__ */ new Error(`Table '${tableName}' does not exist`);
1585
+ error.name = "ValidationError";
1586
+ error.issues = [{ message: `Table '${tableName}' does not exist` }];
1587
+ return err(error);
1588
+ }
1589
+ try {
1590
+ return ok(this.validateAndTransform(tableName, row));
1591
+ } catch (error) {
1592
+ if (error instanceof Error && error.name === "ValidationError") return err(error);
1593
+ throw error;
1594
+ }
1595
+ }
1596
+ getSchema(tableName) {
1597
+ return this.schemas.get(tableName);
1598
+ }
1599
+ /**
1600
+ * Get all table names
1601
+ */
1602
+ getTableNames() {
1603
+ return Array.from(this.schemas.keys());
1604
+ }
1605
+ /**
1606
+ * A database composed from several data directories is read-only: the rows of its tables have no
1607
+ * single file to be written back to
1608
+ */
1609
+ hasSeveralDataDirs() {
1610
+ return typeof this.config.dataDir !== "string" && this.config.dataDir.length > 1;
1611
+ }
1612
+ /**
1613
+ * Turn query_only back on before running a caller's SQL, since an earlier call may have run
1614
+ * `PRAGMA query_only = OFF`
1615
+ */
1616
+ /**
1617
+ * Refuse SQL that would end a transaction() or lift the read-only mode that holds back writes made
1618
+ * through the database while it runs. Looked for in each statement as SQLite reads it, so a `;` or a
1619
+ * comment cannot hide one
1620
+ */
1621
+ refuseUnsafeSql(sql, viaTransaction = this.viaTransactionObject) {
1622
+ if (this.hasSeveralDataDirs() && this.config.writeDataSets && splitStatements(sql).some((statement) => !isReadOnlyStatement(statement))) throw new Error("Raw SQL is read-only for composed data sets; use insert, update, or delete to preserve source routing");
1623
+ if (!this.inTransaction && !this.transactionStarting && !this.transactionClosing) return;
1624
+ for (const statement of splitStatements(sql)) {
1625
+ if (this.inTransaction && !viaTransaction && !isReadOnlyStatement(statement)) throw new Error(`'${sql.trim()}' is not a read: while a transaction runs, SQL that changes anything must go through the callback's tx`);
1626
+ if (/^(BEGIN|COMMIT|END|ROLLBACK(?!\s+(TRANSACTION\s+)?TO\b))\b/i.test(statement)) throw new Error(`'${sql.trim()}' would end the transaction before its files are written back; return from the callback to commit, or throw to roll back`);
1627
+ if (!this.inTransaction && /^SAVEPOINT\b/i.test(statement)) throw new Error(`'${sql.trim()}' would open a transaction of its own while the transaction starts`);
1628
+ if (/^PRAGMA\s+(?:(?:\w+|"[^"]*"|'[^']*'|`[^`]*`|\[[^\]]*\])\s*\.\s*)?(?:query_only|"query_only"|'query_only'|`query_only`|\[query_only\])\s*[=(]/i.test(statement)) throw new Error(`'${sql.trim()}' would lift the read-only mode that refuses writes made while a transaction runs`);
1629
+ }
1630
+ }
1631
+ isReadOnlyDataSet() {
1632
+ return this.hasSeveralDataDirs() && !this.config.writeDataSets;
1633
+ }
1634
+ enforceReadOnlySql() {
1635
+ if (this.isReadOnlyDataSet()) this.db.exec("PRAGMA query_only = ON");
1636
+ }
1637
+ /** Writable, and not while a transaction writes back the rows it has already read */
1638
+ assertMutable(tableName) {
1639
+ this.assertWritable(tableName);
1640
+ this.refuseWhileTransactionSettles(`write to table '${tableName}'`);
1641
+ }
1642
+ /**
1643
+ * Refuse a change while a transaction starts or writes its files back: one made while it starts would
1644
+ * be written back with rows the transaction may roll back, and one made while it closes would be
1645
+ * committed without reaching the files. Also refuse one made through the database itself while the
1646
+ * callback runs, which would be committed or rolled back with the transaction unnoticed by its caller
1647
+ */
1648
+ refuseWhileTransactionSettles(action, viaTransaction = this.viaTransactionObject) {
1649
+ if (this.inTransaction && !viaTransaction) throw new Error(`Cannot ${action} through the database while a transaction is running: a change made now would be committed or rolled back with it; use the object the transaction callback receives, or wait until it has finished`);
1650
+ if (this.transactionStarting) throw new Error(`Cannot ${action} while a transaction is starting; ${action.split(" ")[0]} once it has finished`);
1651
+ if (this.transactionClosing) throw new Error(`Cannot ${action} while a transaction writes its files back; ${action.split(" ")[0]} once it has finished`);
1652
+ }
1653
+ /**
1654
+ * Run a query() with the database read-only while a transaction starts or writes its files back.
1655
+ * Not refused outright as execute() is: a query that only reads changes nothing the files would miss
1656
+ */
1657
+ readOnlyWhileTransactionSettles(run, viaTransaction = this.viaTransactionObject) {
1658
+ if (!this.hasSeveralDataDirs() && !this.transactionStarting && !this.transactionClosing && !(this.inTransaction && !viaTransaction)) return run();
1659
+ this.db.exec("PRAGMA query_only = ON");
1660
+ try {
1661
+ return run();
1662
+ } catch (error) {
1663
+ if (/readonly/i.test(toError(error).message)) this.refuseWhileTransactionSettles("change rows", viaTransaction);
1664
+ throw error;
1665
+ } finally {
1666
+ if (!this.isReadOnlyDataSet()) this.db.exec("PRAGMA query_only = OFF");
1667
+ }
1668
+ }
1669
+ assertWritable(tableName) {
1670
+ if (this.isReadOnlyDataSet()) {
1671
+ const target = tableName ? `table '${tableName}'` : "the database";
1672
+ throw new Error(`Cannot write to ${target}: dataDir lists several directories, so its rows have no single file to be written back to`);
1673
+ }
1674
+ }
1675
+ /**
1676
+ * Sync a specific table back to its JSONL file
1677
+ * Syncs of the same table run one after another: auto-sync is fire-and-forget, and a write-back
1678
+ * that reads the file first must never see a file another sync is halfway through writing.
1679
+ */
1680
+ async syncTable(tableName, options) {
1681
+ const current = (this.syncQueue.get(tableName) ?? Promise.resolve()).then(() => this.writeTable(tableName, options));
1682
+ this.syncQueue.set(tableName, current.catch(() => {}));
1683
+ return current;
1684
+ }
1685
+ /**
1686
+ * Write a table back to its JSONL file
1687
+ * Uses backward transformation when available
1688
+ */
1689
+ async writeTable(tableName, options) {
1690
+ await this.writeFilesTogether(await this.prepareWriteBack(tableName, options));
1691
+ }
1692
+ /**
1693
+ * The rows a table is written back as, laid over the lines of its file; fails when the file changed
1694
+ * since this database last read or wrote it
1695
+ */
1696
+ async prepareWriteBack(tableName, options) {
1697
+ this.assertWritable(tableName);
1698
+ const config = this.tables.get(tableName);
1699
+ if (!config) throw new Error(`Table ${tableName} not found`);
1700
+ const stored = this.readStoredRows(tableName);
1701
+ if (!this.hasSeveralDataDirs()) return [await this.prepareFileWriteBack(tableName, config.jsonlPath, stored, options)];
1702
+ const origins = this.rowOriginsByRowid.get(tableName);
1703
+ const byFile = new Map([this.config.dataDir].flat().map((dir) => [join(dir, `${tableName}.jsonl`), []]));
1704
+ stored.rowids.forEach((rowid, index) => {
1705
+ const origin = origins?.get(rowid);
1706
+ if (!origin) throw new Error(`Row ${rowid} of '${tableName}' has no data directory; insert with a dataDir`);
1707
+ const indexes = byFile.get(origin.file) ?? [];
1708
+ indexes.push(index);
1709
+ byFile.set(origin.file, indexes);
1710
+ });
1711
+ const prepared = [];
1712
+ for (const [file, indexes] of byFile) {
1713
+ indexes.sort((a, b) => (origins.get(stored.rowids[a]).rowIndex < 0 ? Infinity : origins.get(stored.rowids[a]).rowIndex) - (origins.get(stored.rowids[b]).rowIndex < 0 ? Infinity : origins.get(stored.rowids[b]).rowIndex));
1714
+ const rows = {
1715
+ rowids: indexes.map((i) => stored.rowids[i]),
1716
+ rows: indexes.map((i) => stored.rows[i]),
1717
+ lineRows: indexes.map((i) => stored.lineRows[i])
1718
+ };
1719
+ const fileWrite = await this.prepareFileWriteBack(tableName, file, rows, options);
1720
+ if (!fileWrite.unchanged) prepared.push(fileWrite);
1721
+ }
1722
+ return prepared;
1723
+ }
1724
+ async prepareFileWriteBack(tableName, jsonlPath, stored, options) {
1725
+ const { rowids, rows: deserializedRows, lineRows } = stored;
1726
+ const generation = this.changeGenerations.get(tableName) ?? 0;
1727
+ let finalRows = lineRows;
1728
+ const previousContent = await readFile(jsonlPath, "utf-8").catch((error) => {
1729
+ if (error.code === "ENOENT") return void 0;
1730
+ throw error;
1731
+ });
1732
+ const existingRows = await this.readUnchangedRows(jsonlPath);
1733
+ const matches = this.hasSeveralDataDirs() ? rowids.map((rowid) => existingRows[this.rowOriginsByRowid.get(tableName).get(rowid).rowIndex]) : void 0;
1734
+ const fields = options?.fields ?? this.config.writeBackFields;
1735
+ if ((options?.writeFilledValues ?? this.config.writeFilledValues ?? "all") === "primaryKey") finalRows = this.keepWrittenFields(tableName, rowids, deserializedRows, finalRows, existingRows, fields, matches).map(({ written }) => written);
1736
+ const columns = new Set(this.schemas.get(tableName)?.columns.map((column) => column.name));
1737
+ const readLines = this.linesWithUnknownFields.get(tableName);
1738
+ finalRows = finalRows.map((row, index) => {
1739
+ const line = readLines?.get(rowids[index]);
1740
+ return line ? keepUnknownFields(line, row, columns) : row;
1741
+ });
1742
+ finalRows = this.mergeWithExistingLines(tableName, existingRows, finalRows, {
1743
+ fields,
1744
+ strictFields: options?.strictFields ?? false,
1745
+ matches
1746
+ });
1747
+ return {
1748
+ tableName,
1749
+ jsonlPath,
1750
+ rows: finalRows,
1751
+ previousContent,
1752
+ generation,
1753
+ ...matches ? {
1754
+ rowids,
1755
+ unchanged: JsonlWriter.serialize(existingRows) === JsonlWriter.serialize(finalRows)
1756
+ } : {}
1757
+ };
1758
+ }
1759
+ /**
1760
+ * Every row of a table in rowid order - the order the file was read in - as stored and as its line
1761
+ * would hold it, after the backward transformation
1762
+ */
1763
+ readStoredRows(tableName) {
1764
+ const stored = this.queryInternal(`SELECT rowid AS "${ROWID_ALIAS}", * FROM ${this.quoteTableName(tableName)} ORDER BY rowid`);
1765
+ const rowids = stored.map((row) => String(row[ROWID_ALIAS]));
1766
+ const rows = stored.map(({ [ROWID_ALIAS]: _rowid, ...row }) => this.deserializeRow(tableName, row));
1767
+ const validationSchema = this.validationSchemas.get(tableName);
1768
+ return {
1769
+ rowids,
1770
+ rows,
1771
+ lineRows: validationSchema && hasBackward(validationSchema) ? rows.map((row) => validationSchema.backward(row)) : rows
1772
+ };
1773
+ }
1774
+ /**
1775
+ * Narrow each row to the fields a user wrote - the ones its line holds, plus those set since and
1776
+ * minus those reset to their default - its primary key and the fields named to be written back, so
1777
+ * a value the schema fills in stays out of the file
1778
+ */
1779
+ keepWrittenFields(tableName, rowids, rows, lineRows, existingRows, namedFields = [], matchedLines) {
1780
+ const pkName = this.schemas.get(tableName)?.columns.find((col) => col.primaryKey)?.name;
1781
+ const actionColumns = (this.schemas.get(tableName)?.foreignKeys ?? []).filter((fk) => [fk.onDelete, fk.onUpdate].some((action) => action === "CASCADE" || action === "SET NULL")).map((fk) => fk.column);
1782
+ const lines = matchedLines ?? this.matchExistingRows(tableName, lineRows, existingRows, { required: false });
1783
+ const changes = this.fieldChanges.get(tableName);
1784
+ return lineRows.map((lineRow, index) => {
1785
+ const line = lines?.[index];
1786
+ const rowChanges = changes?.get(rowids[index]);
1787
+ if (Object.keys(lineRow).some((key) => !Object.hasOwn(rows[index], key)) || this.rawSqlTables.has(tableName) || !line && !rowChanges?.inserted) return {
1788
+ written: lineRow,
1789
+ narrowed: false
1790
+ };
1791
+ const keep = /* @__PURE__ */ new Set([
1792
+ ...Object.keys(line ?? {}),
1793
+ ...rowChanges?.set ?? [],
1794
+ ...actionColumns
1795
+ ]);
1796
+ for (const key of rowChanges?.reset ?? []) keep.delete(key);
1797
+ for (const key of namedFields) keep.add(key);
1798
+ if (pkName) keep.add(pkName);
1799
+ return {
1800
+ written: Object.fromEntries(Object.entries(lineRow).filter(([key]) => keep.has(key))),
1801
+ narrowed: true
1802
+ };
1803
+ });
1804
+ }
1805
+ rowidsWhere(tableName, whereSql, values) {
1806
+ return this.queryInternal(`SELECT rowid AS "${ROWID_ALIAS}" FROM ${this.quoteTableName(tableName)} WHERE ${whereSql}`, values).map((row) => String(row[ROWID_ALIAS]));
1807
+ }
1808
+ /**
1809
+ * Forget the field changes of deleted rows: a deleted row's rowid can be given to a row inserted
1810
+ * later, which must not inherit them
1811
+ */
1812
+ moveRowMetadata(tableName, from, to) {
1813
+ for (const byRow of [
1814
+ this.fieldChanges.get(tableName),
1815
+ this.linesWithUnknownFields.get(tableName),
1816
+ this.rowOriginsByRowid.get(tableName)
1817
+ ]) {
1818
+ const kept = byRow?.get(from);
1819
+ if (!byRow || kept === void 0) continue;
1820
+ byRow.delete(from);
1821
+ byRow.set(to, kept);
1822
+ }
1823
+ }
1824
+ /** Forget the lines kept for rows that are gone, such as rows raw SQL or a foreign-key action deleted */
1825
+ forgetLinesOfGoneRows(tableNames) {
1826
+ for (const tableName of tableNames) {
1827
+ const lines = this.linesWithUnknownFields.get(tableName);
1828
+ if (!lines || lines.size === 0) continue;
1829
+ let stored;
1830
+ try {
1831
+ stored = this.queryInternal(`SELECT rowid AS "${ROWID_ALIAS}" FROM ${this.quoteTableName(tableName)}`);
1832
+ } catch {
1833
+ continue;
1834
+ }
1835
+ const present = new Set(stored.map((row) => String(row[ROWID_ALIAS])));
1836
+ for (const rowid of lines.keys()) if (!present.has(rowid)) lines.delete(rowid);
1837
+ }
1838
+ }
1839
+ forgetFieldChanges(tableName, rowids) {
1840
+ for (const rowid of rowids) {
1841
+ this.fieldChanges.get(tableName)?.delete(rowid);
1842
+ this.linesWithUnknownFields.get(tableName)?.delete(rowid);
1843
+ }
1844
+ }
1845
+ noteChange(tableName) {
1846
+ this.changeGenerations.set(tableName, (this.changeGenerations.get(tableName) ?? 0) + 1);
1847
+ }
1848
+ noteFieldChanges(tableName, rowid, changes) {
1849
+ this.noteChange(tableName);
1850
+ const byRow = this.fieldChanges.get(tableName) ?? /* @__PURE__ */ new Map();
1851
+ const rowChanges = byRow.get(String(rowid)) ?? {
1852
+ set: /* @__PURE__ */ new Set(),
1853
+ reset: /* @__PURE__ */ new Set(),
1854
+ inserted: false
1855
+ };
1856
+ if (changes.inserted) rowChanges.inserted = true;
1857
+ for (const key of changes.set ?? []) {
1858
+ rowChanges.set.add(key);
1859
+ rowChanges.reset.delete(key);
1860
+ }
1861
+ for (const key of changes.reset ?? []) {
1862
+ rowChanges.reset.add(key);
1863
+ rowChanges.set.delete(key);
1864
+ }
1865
+ byRow.set(String(rowid), rowChanges);
1866
+ this.fieldChanges.set(tableName, byRow);
1867
+ }
1868
+ /**
1869
+ * Store the value the schema fills in for each reset field, as validating the row without the field
1870
+ * gives it, and remember the field as reset so it leaves the line
1871
+ */
1872
+ /** The value the schema fills in for each reset field of each target, validating the row without them */
1873
+ computeResets(tableName, targets, data, fields) {
1874
+ return targets.map((target) => {
1875
+ const { [ROWID_ALIAS]: rowid, ...stored } = target;
1876
+ const row = {
1877
+ ...this.deserializeRow(tableName, stored),
1878
+ ...data
1879
+ };
1880
+ for (const field of fields) delete row[field];
1881
+ const validated = this.validateAndTransform(tableName, row);
1882
+ return {
1883
+ rowid,
1884
+ values: fields.map((field) => this.normalizeValue(validated[field]))
1885
+ };
1886
+ });
1887
+ }
1888
+ /** Store the values computeResets gave, and remember the fields as reset so they leave the line */
1889
+ applyResets(tableName, resets, fields) {
1890
+ let changes = 0n;
1891
+ const setClauses = fields.map((field) => `${this.quoteIdentifier(field)} = ?`).join(", ");
1892
+ for (const { rowid, values } of resets) {
1893
+ const result = this.executeInternal(`UPDATE ${this.quoteTableName(tableName)} SET ${setClauses} WHERE rowid = ?`, [...values, rowid]);
1894
+ changes += BigInt(result.changes);
1895
+ this.noteFieldChanges(tableName, rowid, { reset: fields });
1896
+ }
1897
+ return {
1898
+ changes,
1899
+ lastInsertRowid: 0
1900
+ };
1901
+ }
1902
+ /**
1903
+ * Every row of a table with the fields the schema filled in rather than the file: the ones its line
1904
+ * does not hold and no write set, which a write-back leaves out of the file
1905
+ */
1906
+ async findWithDefaults(tableName) {
1907
+ try {
1908
+ const tableConfig = this.tables.get(tableName);
1909
+ if (!tableConfig || !this.schemas.has(tableName)) throw new Error(`Table '${tableName}' is not loaded`);
1910
+ await this.waitForPendingSyncs();
1911
+ const { rowids, rows, lineRows } = this.readStoredRows(tableName);
1912
+ const fileRows = /* @__PURE__ */ new Map();
1913
+ for (const file of this.hasSeveralDataDirs() ? /* @__PURE__ */ new Set([...tableConfig.jsonlPaths ?? [tableConfig.jsonlPath], ...[...this.rowOriginsByRowid.get(tableName)?.values() ?? []].map((origin) => origin.file)]) : [tableConfig.jsonlPath]) fileRows.set(file, await this.readUnchangedRows(file));
1914
+ const existingRows = [...fileRows.values()].flat();
1915
+ const matches = this.hasSeveralDataDirs() && this.config.writeDataSets ? rowids.map((rowid) => {
1916
+ const origin = this.rowOriginsByRowid.get(tableName)?.get(rowid);
1917
+ return origin && fileRows.get(origin.file)?.[origin.rowIndex];
1918
+ }) : void 0;
1919
+ const kept = this.keepWrittenFields(tableName, rowids, rows, lineRows, existingRows, this.config.writeBackFields, matches);
1920
+ return ok(rows.map((row, index) => ({
1921
+ row,
1922
+ defaulted: kept[index].narrowed ? Object.keys(row).filter((key) => !Object.hasOwn(kept[index].written, key)) : []
1923
+ })));
1924
+ } catch (error) {
1925
+ return err(toError(error));
1926
+ }
1927
+ }
1928
+ async writePrepared(prepared) {
1929
+ const { jsonlPath, rows, previousContent } = prepared;
1930
+ if (this.hasSeveralDataDirs() || this.config.writeDataSets) await replaceFile(jsonlPath, (temporary) => JsonlWriter.write(temporary, rows), previousContent);
1931
+ else await JsonlWriter.write(jsonlPath, rows);
1932
+ prepared.completed = true;
1933
+ const contentHash = hashJsonlContent(JsonlWriter.serialize(rows));
1934
+ this.fileHashes.set(jsonlPath, contentHash);
1935
+ this.observedHashes.set(jsonlPath, contentHash);
1936
+ }
1937
+ /**
1938
+ * Write a table back to its file, or leave it to the running transaction, which writes back the
1939
+ * tables it changed once its callback is done
1940
+ */
1941
+ afterWrite(tableName, changes) {
1942
+ if (BigInt(changes) === 0n && this.transactionChanges) return;
1943
+ const tableNames = [tableName, ...this.tablesChangedByForeignKeyActions(tableName)];
1944
+ this.forgetLinesOfGoneRows(tableNames);
1945
+ if (this.transactionChanges) {
1946
+ if (this.transactionChanges !== "all") for (const name of tableNames) this.transactionChanges.add(name);
1947
+ return;
1948
+ }
1949
+ for (const name of tableNames) this.syncTable(name).catch((err) => {
1950
+ console.error(`Failed to sync table ${name}:`, err);
1951
+ });
1952
+ }
1953
+ /**
1954
+ * The tables whose rows an ON DELETE / ON UPDATE action can change when a table's rows change,
1955
+ * following the actions on to the tables they change in turn
1956
+ */
1957
+ tablesChangedByForeignKeyActions(tableName) {
1958
+ const found = /* @__PURE__ */ new Set();
1959
+ const visit = (referenced) => {
1960
+ for (const [name, schema] of this.schemas) {
1961
+ if (found.has(name) || name === tableName) continue;
1962
+ if ((schema.foreignKeys ?? []).some((fk) => fk.references.table === referenced && [fk.onDelete, fk.onUpdate].some((action) => action === "CASCADE" || action === "SET NULL"))) {
1963
+ found.add(name);
1964
+ visit(name);
1965
+ }
1966
+ }
1967
+ };
1968
+ visit(tableName);
1969
+ return Array.from(found);
1970
+ }
1971
+ tablesChangedInTransaction() {
1972
+ const changes = this.transactionChanges;
1973
+ return changes === "all" ? Array.from(this.schemas.keys()) : Array.from(changes ?? []);
1974
+ }
1975
+ /**
1976
+ * Write several tables back, checking every file before writing any, so a file changed on disk
1977
+ * fails the write-back before it has written part of it
1978
+ */
1979
+ async writeBackTogether(tableNames) {
1980
+ await this.waitForPendingSyncs();
1981
+ const prepared = [];
1982
+ for (const tableName of tableNames) prepared.push(...await this.prepareWriteBack(tableName));
1983
+ return this.writeFilesTogether(prepared);
1984
+ }
1985
+ async writeFilesTogether(prepared) {
1986
+ const written = [];
1987
+ try {
1988
+ for (const table of prepared) {
1989
+ written.push(table);
1990
+ await this.writePrepared(table);
1991
+ }
1992
+ } catch (error) {
1993
+ throw await this.restoreAll(written, error);
1994
+ }
1995
+ for (const { tableName, jsonlPath, generation, rowids } of written) {
1996
+ if ((this.changeGenerations.get(tableName) ?? 0) === generation) {
1997
+ this.fieldChanges.delete(tableName);
1998
+ this.rawSqlTables.delete(tableName);
1999
+ }
2000
+ if (rowids) {
2001
+ const origins = this.rowOriginsByRowid.get(tableName);
2002
+ rowids.forEach((rowid, rowIndex) => origins.set(rowid, {
2003
+ file: jsonlPath,
2004
+ rowIndex
2005
+ }));
2006
+ if (!this.scannedJsonlFiles.includes(jsonlPath)) this.scannedJsonlFiles.push(jsonlPath);
2007
+ }
2008
+ }
2009
+ return written;
2010
+ }
2011
+ /**
2012
+ * Put back every written file, going on past one that cannot be put back, and give the error to
2013
+ * throw: the one that made the write-back fail, naming the files left holding what was written
2014
+ */
2015
+ async restoreAll(written, error) {
2016
+ const notRestored = [];
2017
+ for (const table of written) await this.restorePrepared(table).catch(() => notRestored.push(table.jsonlPath));
2018
+ if (notRestored.length === 0) return error;
2019
+ const failure = toError(error);
2020
+ const recoveryError = new Error(`${failure.message}\nThese files could not be put back and hold rows the database does not: ${notRestored.join(", ")}`, { cause: error });
2021
+ if (failure.name === "JsonlConflictError") {
2022
+ recoveryError.name = failure.name;
2023
+ recoveryError.file = failure.file;
2024
+ }
2025
+ return recoveryError;
2026
+ }
2027
+ /**
2028
+ * Put back the content a file held before {@link writePrepared} wrote over it. The file is expected
2029
+ * to hold that content even when putting it back fails, so a file left holding the written rows
2030
+ * counts as changed on disk instead of matching the database
2031
+ */
2032
+ async restorePrepared({ jsonlPath, previousContent, rows, completed }) {
2033
+ if (this.hasSeveralDataDirs() || this.config.writeDataSets) {
2034
+ if (!completed) return;
2035
+ if (await readFile(jsonlPath, "utf8").catch((error) => {
2036
+ if (error.code === "ENOENT") return void 0;
2037
+ throw error;
2038
+ }) !== JsonlWriter.serialize(rows)) throw new Error(`JSONL file '${jsonlPath}' changed during rollback`);
2039
+ }
2040
+ if (previousContent === void 0) {
2041
+ this.fileHashes.delete(jsonlPath);
2042
+ this.observedHashes.delete(jsonlPath);
2043
+ if (this.hasSeveralDataDirs() || this.config.writeDataSets) await replaceFile(jsonlPath, void 0, JsonlWriter.serialize(rows));
2044
+ else await rm(jsonlPath, { force: true });
2045
+ return;
2046
+ }
2047
+ this.fileHashes.set(jsonlPath, hashJsonlContent(previousContent));
2048
+ this.observedHashes.set(jsonlPath, hashJsonlContent(previousContent));
2049
+ if (this.hasSeveralDataDirs() || this.config.writeDataSets) await replaceFile(jsonlPath, (temporary) => writeFile(temporary, previousContent, "utf8"), JsonlWriter.serialize(rows));
2050
+ else await writeFile(jsonlPath, previousContent, "utf-8");
2051
+ }
2052
+ /**
2053
+ * Lay the rows out over the lines the JSONL file already holds.
2054
+ *
2055
+ * Rows keep the order the file lists them in - the database returns rows in its own order, and
2056
+ * an integer primary key is SQLite's rowid, so writing rows back in query order would reshuffle
2057
+ * the file. Rows the file never had follow, in database order.
2058
+ *
2059
+ * With `fields`, only those fields are taken from the row and every other field keeps the value
2060
+ * its line already had, so values a validation hook computed and fields the file omitted are
2061
+ * never materialized. Fields this table does not have are simply not written, so one list can
2062
+ * cover a directory of tables that do not all share it; a sync asked for a single table by name
2063
+ * rejects them instead, since there the caller named both the table and the fields.
2064
+ */
2065
+ mergeWithExistingLines(tableName, existingRows, rows, options) {
2066
+ if (rows.length === 0) return rows;
2067
+ const { fields } = options;
2068
+ const tableFields = fields?.filter((field) => rows.some((row) => field in row));
2069
+ if (fields && tableFields && options.strictFields && tableFields.length < fields.length) {
2070
+ const unknownFields = fields.filter((field) => !tableFields.includes(field));
2071
+ throw new Error(`Cannot write back field(s) [${unknownFields.join(", ")}] for table '${tableName}': no such field in the rows written back to the file.`);
2072
+ }
2073
+ const existing = options.matches ?? this.matchExistingRows(tableName, rows, existingRows, { required: fields !== void 0 });
2074
+ if (!existing) return rows;
2075
+ const rowByLine = /* @__PURE__ */ new Map();
2076
+ const newRows = [];
2077
+ rows.forEach((row, index) => {
2078
+ const base = existing[index];
2079
+ if (base) rowByLine.set(base, row);
2080
+ else newRows.push(row);
2081
+ });
2082
+ return [...existingRows.filter((base) => rowByLine.has(base)).map((base) => {
2083
+ const row = rowByLine.get(base);
2084
+ return tableFields ? mergeFields(base, row, {
2085
+ fields: tableFields,
2086
+ keyOrder: this.keyOrders.get(tableName)
2087
+ }) : row;
2088
+ }), ...newRows];
2089
+ }
2090
+ /**
2091
+ * Pair each row with the JSONL line it came from, indexed the same way as `rows`.
2092
+ * Returns undefined when the rows cannot be matched and the caller can do without it.
2093
+ */
2094
+ matchExistingRows(tableName, rows, existingRows, options) {
2095
+ if (existingRows.length === 0) return rows.map(() => void 0);
2096
+ const pkName = this.schemas.get(tableName)?.columns.find((col) => col.primaryKey)?.name;
2097
+ const pkValues = pkName ? existingRows.map((row) => row[pkName]) : [];
2098
+ if (pkName !== void 0 && pkValues.every((value) => value !== void 0 && value !== null) && new Set(pkValues.map((value) => String(value))).size === pkValues.length) {
2099
+ const byPk = new Map(existingRows.map((row, index) => [String(pkValues[index]), row]));
2100
+ return rows.map((row) => {
2101
+ const pkValue = row[pkName];
2102
+ return pkValue === void 0 || pkValue === null ? void 0 : byPk.get(String(pkValue));
2103
+ });
2104
+ }
2105
+ if (rows.length !== existingRows.length) {
2106
+ if (!options.required) return;
2107
+ throw new Error(`Cannot write back selected fields for table '${tableName}': the file has ${existingRows.length} row(s) but the table has ${rows.length}, and ${pkName ? `column '${pkName}' is not usable as a primary key in the file` : "the table has no primary key"}, so rows cannot be matched to their existing lines.`);
2108
+ }
2109
+ return existingRows;
2110
+ }
2111
+ /**
2112
+ * Read the rows a JSONL file currently holds, treating a missing file as empty, and refuse to go on
2113
+ * when the file is not the one this database last read or wrote: writing over it would drop the
2114
+ * changes made to it since
2115
+ */
2116
+ async readUnchangedRows(jsonlPath) {
2117
+ const result = await JsonlReader.readSnapshot(jsonlPath);
2118
+ if (!result.ok && result.error.code !== "ENOENT") throw result.error;
2119
+ const snapshot = result.ok ? result.value : {
2120
+ rows: ok([]),
2121
+ contentHash: void 0
2122
+ };
2123
+ const knownHash = this.fileHashes.get(jsonlPath);
2124
+ if (knownHash !== void 0 && snapshot.contentHash !== knownHash || this.config.writeDataSets && !this.scannedJsonlFiles.includes(jsonlPath) && snapshot.contentHash !== void 0) {
2125
+ const conflictError = /* @__PURE__ */ new Error(`JSONL file '${jsonlPath}' was changed after the database read it, so it was not overwritten. Create the database again and call initialize() to load the current file, then retry the write.`);
2126
+ conflictError.name = "JsonlConflictError";
2127
+ conflictError.file = jsonlPath;
2128
+ throw conflictError;
2129
+ }
2130
+ return unwrap(snapshot.rows);
2131
+ }
2132
+ /**
2133
+ * Tell whether the files the tables were loaded from changed since this database last read or
2134
+ * wrote them: a JSONL file was edited, added or removed, or a table's schema file was edited, added
2135
+ * or removed. When they did, the database holds rows or a schema the files no longer have; create it
2136
+ * again and call initialize() to load the current files.
2137
+ */
2138
+ async hasExternalChanges() {
2139
+ try {
2140
+ return ok((await this.findExternalChangesInternal()).length > 0);
2141
+ } catch (error) {
2142
+ return err(toError(error));
2143
+ }
2144
+ }
2145
+ /**
2146
+ * The files that changed since this database last read or wrote them, as {@link hasExternalChanges}
2147
+ * tells: each JSONL file edited, added or removed, and each schema file edited, added or removed
2148
+ */
2149
+ async findExternalChanges() {
2150
+ try {
2151
+ return ok(await this.findExternalChangesInternal());
2152
+ } catch (error) {
2153
+ return err(toError(error));
2154
+ }
2155
+ }
2156
+ async findExternalChangesInternal() {
2157
+ await this.waitForPendingSyncs();
2158
+ const changed = /* @__PURE__ */ new Set();
2159
+ for (const [file, knownHash] of this.observedHashes) {
2160
+ const content = await readFile(file, "utf-8").catch((error) => {
2161
+ if (error.code === "ENOENT") return void 0;
2162
+ throw error;
2163
+ });
2164
+ if (content === void 0 || hashJsonlContent(content) !== knownHash) changed.add(file);
2165
+ }
2166
+ const tables = await DirectoryScanner.scanDirectory(this.config.dataDir);
2167
+ const scanned = new Set(listJsonlFiles(tables));
2168
+ for (const file of this.scannedJsonlFiles) if (!scanned.has(file)) changed.add(file);
2169
+ for (const file of scanned) if (!this.scannedJsonlFiles.includes(file)) changed.add(file);
2170
+ for (const name of /* @__PURE__ */ new Set([...this.schemaFileStates.keys(), ...tables.keys()])) {
2171
+ const knownState = this.schemaFileStates.get(name) ?? "";
2172
+ const config = tables.get(name);
2173
+ const state = config ? await this.schemaFileState(name, config) : await this.stateOfKnownSchemaFile(knownState);
2174
+ if (state !== knownState) changed.add((state || knownState).split("\0")[0]);
2175
+ }
2176
+ return [...changed];
2177
+ }
2178
+ /** The state of the schema file a state names, for a table whose JSONL file is gone */
2179
+ async stateOfKnownSchemaFile(knownState) {
2180
+ if (!knownState) return "";
2181
+ const schemaPath = knownState.split("\0")[0];
2182
+ const content = await readFile(schemaPath, "utf-8").catch((error) => {
2183
+ if (error.code === "ENOENT") return void 0;
2184
+ throw error;
2185
+ });
2186
+ return content === void 0 ? "" : `${schemaPath}\0${hashJsonlContent(content)}`;
2187
+ }
2188
+ async schemaFileState(tableName, config) {
2189
+ if (config.validationSchema) return "";
2190
+ const schemaPath = await this.findTableSchemaFile(tableName, config);
2191
+ if (!schemaPath) return "";
2192
+ return `${schemaPath}\0${hashJsonlContent(await readFile(schemaPath, "utf-8"))}`;
2193
+ }
2194
+ /**
2195
+ * Sync database changes back to JSONL files
2196
+ * Uses backward transformation when available
2197
+ * @param tableName Optional table name to sync. If not provided, syncs all loaded tables
2198
+ * @param options Optional sync options, e.g. the fields to write back
2199
+ */
2200
+ async sync(tableName, options) {
2201
+ try {
2202
+ await this.syncInternal(tableName, options);
2203
+ return ok(void 0);
2204
+ } catch (error) {
2205
+ return err(toError(error));
2206
+ }
2207
+ }
2208
+ async syncInternal(tableName, options) {
2209
+ this.refuseWhileTransactionSettles("sync");
2210
+ this.assertWritable(tableName);
2211
+ if (this.inTransaction) throw new Error("sync() is not supported inside a transaction: the transaction writes back the tables it changed once it commits, and a file written earlier would keep rows it rolls back");
2212
+ if (tableName) {
2213
+ if (!this.schemas.has(tableName)) throw new Error(`Table '${tableName}' is not loaded`);
2214
+ await this.syncTable(tableName, {
2215
+ ...options,
2216
+ strictFields: options?.fields !== void 0
2217
+ });
2218
+ } else for (const [name] of this.schemas) await this.syncTable(name, options);
2219
+ }
2220
+ /**
2221
+ * Execute a function within a transaction
2222
+ * Automatically commits on success or rolls back on error.
2223
+ *
2224
+ * Note: `tx` (the argument `fn` receives) is the same Result-returning API as `this` - a failed
2225
+ * `tx.insert()`/`tx.update()`/etc. inside `fn` does not throw and therefore does not roll back the
2226
+ * transaction on its own. To abort on such a failure, check the Result and `throw result.error`
2227
+ * (or any error) from `fn`; only a thrown error rolls the transaction back.
2228
+ */
2229
+ async transaction(fn) {
2230
+ if (this.inTransaction || this.transactionStarting) return err(/* @__PURE__ */ new Error("Nested transactions are not supported"));
2231
+ this.transactionStarting = true;
2232
+ const token = {};
2233
+ let fieldChangesBefore;
2234
+ let rawSqlTablesBefore;
2235
+ let linesWithUnknownFieldsBefore;
2236
+ let originsBefore;
2237
+ const scannedBefore = [...this.scannedJsonlFiles];
2238
+ let written = [];
2239
+ try {
2240
+ await this.waitForPendingSyncs();
2241
+ originsBefore = new Map([...this.rowOriginsByRowid].map(([name, origins]) => [name, new Map(origins)]));
2242
+ fieldChangesBefore = cloneFieldChanges(this.fieldChanges);
2243
+ rawSqlTablesBefore = new Set(this.rawSqlTables);
2244
+ linesWithUnknownFieldsBefore = new Map(Array.from(this.linesWithUnknownFields, ([tableName, lines]) => [tableName, new Map(lines)]));
2245
+ this.db.exec("BEGIN TRANSACTION");
2246
+ this.inTransaction = true;
2247
+ this.transactionToken = token;
2248
+ this.transactionStarting = false;
2249
+ this.transactionChanges = /* @__PURE__ */ new Set();
2250
+ let result;
2251
+ try {
2252
+ result = await fn(this.scopedToTransaction(token));
2253
+ } finally {
2254
+ this.transactionClosing = true;
2255
+ }
2256
+ if (!this.isReadOnlyDataSet()) written = await this.writeBackTogether(this.tablesChangedInTransaction());
2257
+ this.db.exec("COMMIT");
2258
+ this.inTransaction = false;
2259
+ this.transactionChanges = void 0;
2260
+ return ok(result);
2261
+ } catch (error) {
2262
+ this.transactionStarting = false;
2263
+ this.transactionChanges = void 0;
2264
+ if (originsBefore) this.rowOriginsByRowid = originsBefore;
2265
+ this.scannedJsonlFiles = scannedBefore;
2266
+ if (fieldChangesBefore) this.fieldChanges = fieldChangesBefore;
2267
+ if (rawSqlTablesBefore) this.rawSqlTables = rawSqlTablesBefore;
2268
+ if (linesWithUnknownFieldsBefore) this.linesWithUnknownFields = linesWithUnknownFieldsBefore;
2269
+ const failure = await this.restoreAll(written, error);
2270
+ if (this.inTransaction) try {
2271
+ this.db.exec("ROLLBACK");
2272
+ } catch (_rollbackError) {}
2273
+ this.inTransaction = false;
2274
+ return err(toError(failure));
2275
+ } finally {
2276
+ this.transactionClosing = false;
2277
+ this.transactionToken = void 0;
2278
+ }
2279
+ }
2280
+ /**
2281
+ * The object a transaction() callback receives. Calls on it are marked as the transaction's own for as
2282
+ * long as they run; a write made through the database itself in the meantime is refused, since writes are
2283
+ * synchronous and cannot be queued until the transaction ends
2284
+ */
2285
+ scopedToTransaction(token) {
2286
+ return new Proxy(this, { get: (target, property) => {
2287
+ const value = Reflect.get(target, property, target);
2288
+ if (typeof value !== "function") return value;
2289
+ return (...args) => {
2290
+ const before = target.viaTransactionObject;
2291
+ target.viaTransactionObject = before || target.transactionToken === token;
2292
+ try {
2293
+ return value.apply(target, args);
2294
+ } finally {
2295
+ target.viaTransactionObject = before;
2296
+ }
2297
+ };
2298
+ } });
2299
+ }
2300
+ /**
2301
+ * Wait for every queued sync to finish, so a fire-and-forget auto-sync is not dropped
2302
+ */
2303
+ async waitForPendingSyncs() {
2304
+ const awaited = /* @__PURE__ */ new Set();
2305
+ let pending = Array.from(this.syncQueue.values());
2306
+ while (pending.length > 0) {
2307
+ for (const promise of pending) awaited.add(promise);
2308
+ await Promise.all(pending);
2309
+ pending = Array.from(this.syncQueue.values()).filter((promise) => !awaited.has(promise));
2310
+ }
2311
+ }
2312
+ /**
2313
+ * Close the database connection
2314
+ */
2315
+ async close() {
2316
+ try {
2317
+ await this.waitForPendingSyncs();
2318
+ try {
2319
+ this.db.close();
2320
+ } catch (_error) {}
2321
+ return ok(void 0);
2322
+ } catch (error) {
2323
+ return err(toError(error));
2324
+ }
2325
+ }
2326
+ /**
2327
+ * Get a handle for running SQL on the underlying SQLite database. It wraps the connection rather than
2328
+ * being it, also outside a transaction: while a transaction() callback runs, SQL that changes rows is
2329
+ * refused unless the handle came from the callback's `tx`, and SQL that would end the transaction is
2330
+ * refused for every handle. Outside a transaction it runs SQL unchanged.
2331
+ */
2332
+ getDb() {
2333
+ const token = this.viaTransactionObject ? this.transactionToken : void 0;
2334
+ const viaTransaction = () => token !== void 0 && token === this.transactionToken;
2335
+ const idle = () => !this.inTransaction && !this.transactionStarting && !this.transactionClosing;
2336
+ const guarded = (sql, run) => {
2337
+ if (idle() && !this.hasSeveralDataDirs()) return run();
2338
+ this.refuseUnsafeSql(sql, viaTransaction());
2339
+ return this.readOnlyWhileTransactionSettles(() => this.trackRawSql(run), viaTransaction());
2340
+ };
2341
+ return {
2342
+ prepare: (sql) => {
2343
+ if (!idle() || this.hasSeveralDataDirs()) this.refuseUnsafeSql(sql, viaTransaction());
2344
+ const statement = this.readOnlyWhileTransactionSettles(() => this.db.prepare(sql), viaTransaction());
2345
+ return {
2346
+ run: (...params) => guarded(sql, () => statement.run(...params)),
2347
+ get: (...params) => guarded(sql, () => statement.get(...params)),
2348
+ all: (...params) => guarded(sql, () => statement.all(...params))
2349
+ };
2350
+ },
2351
+ exec: (sql) => guarded(sql, () => this.db.exec(sql)),
2352
+ close: () => this.db.close()
2353
+ };
2354
+ }
2355
+ };
2356
+ function listJsonlFiles(tables) {
2357
+ return Array.from(tables.values()).flatMap((config) => config.jsonlPaths ?? [config.jsonlPath]).sort();
2358
+ }
2359
+ //#endregion
2360
+ //#region src/fill.ts
2361
+ /**
2362
+ * Fill the named fields into the rows of the JSONL files that have no value for them, with the values
2363
+ * each table computes for a row. A value already in the file is never replaced, and a line that gains
2364
+ * nothing is left byte for byte; a line that does gain a value is written with its keys in the order
2365
+ * the computed row lists them. Every value is computed before any file is written.
2366
+ */
2367
+ async function fillFields(options) {
2368
+ try {
2369
+ return ok(await fillFieldsInternal(options));
2370
+ } catch (error) {
2371
+ return err(toError(error));
2372
+ }
2373
+ }
2374
+ async function fillFieldsInternal(options) {
2375
+ if (options.fields && options.fields.length === 0) throw new Error("No fields to fill. Name at least one field.");
2376
+ const { dataDir, tableNames } = await resolveTables(options.path);
2377
+ const schemaDir = options.schemaDir ?? dataDir;
2378
+ const loadFiller = options.loadFiller ?? fillerFromValidationSchema;
2379
+ const tablesWithoutSchema = [];
2380
+ const tables = [];
2381
+ for (const table of tableNames) {
2382
+ const schemaPath = await findSchemaFile(schemaDir, table);
2383
+ if (!schemaPath) {
2384
+ tablesWithoutSchema.push(table);
2385
+ continue;
2386
+ }
2387
+ const schemaModule = await import(`${pathToFileURL(schemaPath).href}?t=${Date.now()}`);
2388
+ tables.push({
2389
+ table,
2390
+ fields: options.fields ?? [primaryKeyOf(schemaModule)],
2391
+ fill: loadFiller(schemaModule, {
2392
+ tableName: table,
2393
+ schemaPath
2394
+ })
2395
+ });
2396
+ }
2397
+ const produced = /* @__PURE__ */ new Set();
2398
+ const unreadableLines = [];
2399
+ const filled = [];
2400
+ const writes = [];
2401
+ for (const { table, fields, fill } of tables) {
2402
+ const file = join(dataDir, `${table}.jsonl`);
2403
+ const read = await readFile(file, "utf-8");
2404
+ const bom = read.startsWith("") ? "" : "";
2405
+ const lines = splitLines(read.slice(bom.length));
2406
+ const written = /* @__PURE__ */ new Set();
2407
+ const unreadable = [];
2408
+ let count = 0;
2409
+ lines.forEach((line, index) => {
2410
+ if (!line.row) {
2411
+ if (line.text.trim() !== "") unreadable.push(index + 1);
2412
+ return;
2413
+ }
2414
+ const computed = fill(structuredClone(line.row));
2415
+ const gained = fields.filter((field) => {
2416
+ if (isBlank(ownValue(computed, field))) return false;
2417
+ produced.add(field);
2418
+ return ownValue(line.row, field) === void 0 || ownValue(line.row, field) === null;
2419
+ });
2420
+ if (gained.length === 0) return;
2421
+ for (const field of gained) {
2422
+ setField(line.row, field, computed[field]);
2423
+ written.add(field);
2424
+ }
2425
+ line.text = serializeRow(line.row, Object.keys(computed));
2426
+ count += 1;
2427
+ });
2428
+ if (unreadable.length > 0) unreadableLines.push({
2429
+ file,
2430
+ lines: unreadable
2431
+ });
2432
+ if (count === 0) continue;
2433
+ writes.push({
2434
+ file,
2435
+ read,
2436
+ content: bom + lines.map((line) => `${line.text}${line.eol}`).join("")
2437
+ });
2438
+ filled.push({
2439
+ table,
2440
+ file,
2441
+ fields: [...written],
2442
+ count
2443
+ });
2444
+ }
2445
+ for (const { file, read } of writes) if (await readFile(file, "utf-8") !== read) {
2446
+ const error = /* @__PURE__ */ new Error(`JSONL file '${file}' was changed after it was read, so no file was filled. Run the fill again.`);
2447
+ error.name = "JsonlConflictError";
2448
+ error.file = file;
2449
+ throw error;
2450
+ }
2451
+ await replaceAll(writes);
2452
+ const named = options.fields ?? [...new Set(tables.flatMap(({ fields }) => fields))];
2453
+ return {
2454
+ filled,
2455
+ tablesWithoutSchema,
2456
+ unreadableLines,
2457
+ unproducedFields: tableNames.length > 0 ? named.filter((field) => !produced.has(field)) : []
2458
+ };
2459
+ }
2460
+ /**
2461
+ * Write every file or none: each content goes to a temporary file first, the temporaries replace the
2462
+ * files once all are written, and the files already replaced are put back when a later one fails
2463
+ */
2464
+ async function replaceAll(writes) {
2465
+ const staged = writes.map((write) => ({
2466
+ ...write,
2467
+ temporary: `${write.file}.${randomBytes(6).toString("hex")}.tmp`
2468
+ }));
2469
+ const replaced = [];
2470
+ try {
2471
+ for (const { file, temporary, content } of staged) {
2472
+ await writeFile(temporary, content, "utf-8");
2473
+ await chmod(temporary, (await stat(file)).mode & 4095);
2474
+ }
2475
+ for (const write of staged) {
2476
+ await rename(write.temporary, write.file);
2477
+ replaced.push(write);
2478
+ }
2479
+ } catch (error) {
2480
+ const notRestored = [];
2481
+ for (const { file, read } of replaced) await writeFile(file, read, "utf-8").catch(() => notRestored.push(file));
2482
+ await Promise.all(staged.map(({ temporary }) => rm(temporary, { force: true })));
2483
+ if (notRestored.length === 0) throw error;
2484
+ throw new Error(`${toError(error).message}\nThese files could not be put back and stay filled: ${notRestored.join(", ")}`, { cause: error });
2485
+ }
2486
+ }
2487
+ async function resolveTables(path) {
2488
+ const stats = await stat(path);
2489
+ if (stats.isDirectory()) return {
2490
+ dataDir: path,
2491
+ tableNames: (await readdir(path)).filter((entry) => entry.endsWith(".jsonl")).map((entry) => basename(entry, ".jsonl")).sort()
2492
+ };
2493
+ if (stats.isFile() && path.endsWith(".jsonl")) return {
2494
+ dataDir: dirname(path),
2495
+ tableNames: [basename(path, ".jsonl")]
2496
+ };
2497
+ throw new Error(`Invalid path: ${path}. Must be a directory or .jsonl file.`);
2498
+ }
2499
+ function primaryKeyOf(schemaModule) {
2500
+ const primaryKey = (schemaModule.schema ?? schemaModule.default)?.primaryKey ?? schemaModule.primaryKey;
2501
+ return typeof primaryKey === "string" ? primaryKey : "id";
2502
+ }
2503
+ function fillerFromValidationSchema(schemaModule, { schemaPath }) {
2504
+ const schema = schemaModule.schema ?? schemaModule.default;
2505
+ if (!schema || typeof schema !== "object" || !("~standard" in schema)) throw new Error(`${schemaPath} does not export a StandardSchema as \`schema\` or as its default export`);
2506
+ return (row) => {
2507
+ const result = schema["~standard"].validate(row);
2508
+ if (result instanceof Promise) throw new Error(`${schemaPath}: asynchronous validation is not supported`);
2509
+ if (result.issues) return {};
2510
+ return hasBackward(schema) ? schema.backward(result.value) : result.value;
2511
+ };
2512
+ }
2513
+ function ownValue(row, field) {
2514
+ return Object.hasOwn(row, field) ? row[field] : void 0;
2515
+ }
2516
+ function setField(row, field, value) {
2517
+ Object.defineProperty(row, field, {
2518
+ value,
2519
+ enumerable: true,
2520
+ writable: true,
2521
+ configurable: true
2522
+ });
2523
+ }
2524
+ function isBlank(value) {
2525
+ if (value === void 0 || value === null) return true;
2526
+ if (typeof value !== "object" || Array.isArray(value)) return false;
2527
+ return Object.values(value).every(isBlank);
2528
+ }
2529
+ function splitLines(content) {
2530
+ if (content === "") return [];
2531
+ return content.split("\n").map((raw, index, all) => {
2532
+ const carriage = raw.endsWith("\r") ? "\r" : "";
2533
+ const text = carriage ? raw.slice(0, -1) : raw;
2534
+ let row;
2535
+ if (text.trim() !== "") try {
2536
+ const parsed = JSON.parse(text);
2537
+ row = parsed !== null && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : void 0;
2538
+ } catch {
2539
+ row = void 0;
2540
+ }
2541
+ return {
2542
+ text,
2543
+ eol: index === all.length - 1 ? carriage : `${carriage}\n`,
2544
+ row
2545
+ };
2546
+ });
2547
+ }
2548
+ /** The row with its keys in the order the computed row lists them, and keys it does not list after those */
2549
+ function serializeRow(row, fieldOrder) {
2550
+ const rank = new Map(fieldOrder.map((field, index) => [field, index]));
2551
+ const rankOf = (key) => rank.get(key) ?? fieldOrder.length;
2552
+ const ordered = Object.entries(row).sort(([a], [b]) => rankOf(a) - rankOf(b));
2553
+ const out = {};
2554
+ for (const [key, value] of ordered) setField(out, key, value);
2555
+ return JSON.stringify(out);
2556
+ }
2557
+ //#endregion
2558
+ //#region src/type-generator.ts
2559
+ var TypeGenerator = class {
2560
+ dataDir;
2561
+ projectRoot;
2562
+ outputFile;
2563
+ dataDirPath;
2564
+ constructor(options) {
2565
+ const envProjectRoot = process.env.LINES_DB_TEST_PROJECT_ROOT;
2566
+ this.projectRoot = envProjectRoot !== void 0 ? envProjectRoot : options.projectRoot || process.cwd();
2567
+ this.dataDir = options.dataDir;
2568
+ this.dataDirPath = isAbsolute(this.dataDir) ? this.dataDir : join(this.projectRoot, this.dataDir);
2569
+ this.outputFile = options.output ? isAbsolute(options.output) ? options.output : join(this.projectRoot, options.output) : join(this.dataDirPath, "db.ts");
2570
+ }
2571
+ /**
2572
+ * Generate types file from JSONL files and their optional schema files.
2573
+ */
2574
+ async generate() {
2575
+ const tables = await this.findTables();
2576
+ if (tables.length === 0) throw new Error(`No JSONL files found in ${this.dataDirPath}. Place one or more *.jsonl files in the directory.`);
2577
+ const content = this.generateTypeDeclarations(tables);
2578
+ const outputDir = dirname(this.outputFile);
2579
+ await mkdir(outputDir, { recursive: true });
2580
+ await writeFile(this.outputFile, content, "utf-8");
2581
+ console.log(`Generated types at ${this.outputFile}`);
2582
+ return this.outputFile;
2583
+ }
2584
+ /**
2585
+ * Find all *.jsonl files and check if they have corresponding *.schema.ts files
2586
+ */
2587
+ async findTables() {
2588
+ try {
2589
+ const entries = await readdir(this.dataDirPath, { withFileTypes: true });
2590
+ const tables = [];
2591
+ for (const entry of entries) if (entry.isFile() && entry.name.endsWith(".jsonl")) {
2592
+ const tableName = basename(entry.name, ".jsonl");
2593
+ const schemaFilePath = findSchemaFileInEntries(this.dataDirPath, tableName, entries);
2594
+ tables.push({
2595
+ tableName,
2596
+ schemaFile: schemaFilePath
2597
+ });
2598
+ }
2599
+ return tables;
2600
+ } catch (error) {
2601
+ if (error.code === "ENOENT") throw new Error(`Data directory not found: ${this.dataDirPath}. Set lines-db.dataDir to the correct location.`);
2602
+ throw error;
2603
+ }
2604
+ }
2605
+ /**
2606
+ * Generate type declaration content
2607
+ */
2608
+ generateTypeDeclarations(tables) {
2609
+ const imports = [];
2610
+ const tableEntries = [];
2611
+ const usedAliases = /* @__PURE__ */ new Set();
2612
+ for (const table of tables) {
2613
+ const tableKey = this.formatTableKey(table.tableName);
2614
+ if (table.schemaFile) {
2615
+ const schemaIdentifier = this.createSchemaIdentifier(table.tableName, usedAliases);
2616
+ usedAliases.add(schemaIdentifier);
2617
+ let relativePath = rewriteExtensionForImport(relative(join(this.outputFile, ".."), table.schemaFile).replace(/\\/g, "/"));
2618
+ if (!relativePath.startsWith(".")) relativePath = "./" + relativePath;
2619
+ imports.push(`import { schema as ${schemaIdentifier} } from '${relativePath}';`);
2620
+ tableEntries.push(` ${tableKey}: InferOutput<typeof ${schemaIdentifier}>;`);
2621
+ } else tableEntries.push(` ${tableKey}: Record<string, unknown>;`);
2622
+ }
2623
+ return `// Auto-generated by lines-db
2624
+ // Do not edit this file manually
2625
+
2626
+ ${imports.length > 0 ? `${imports.join("\n")}\n` : ""}import type { DatabaseConfig${imports.length > 0 ? ", InferOutput" : ""} } from 'lines-db';
2627
+ import { fileURLToPath } from 'node:url';
2628
+ import { dirname } from 'node:path';
2629
+
2630
+ const __filename = fileURLToPath(import.meta.url);
2631
+ const __dirname = dirname(__filename);
2632
+
2633
+ export type Tables = {
2634
+ ${tableEntries.join("\n")}
2635
+ };
2636
+
2637
+ export const config: DatabaseConfig<Tables> = {
2638
+ dataDir: __dirname,
2639
+ };
2640
+ `;
2641
+ }
2642
+ createSchemaIdentifier(tableName, usedAliases) {
2643
+ let base = sanitizeIdentifier(toCamelCase(tableName)) || "table";
2644
+ if (!/^[A-Za-z_$]/.test(base)) base = `_${base}`;
2645
+ let candidate = `${base}Schema`;
2646
+ let suffix = 1;
2647
+ while (usedAliases.has(candidate)) candidate = `${base}${++suffix}Schema`;
2648
+ return candidate;
2649
+ }
2650
+ formatTableKey(tableName) {
2651
+ if (/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(tableName)) return tableName;
2652
+ return `'${tableName.replace(/\\/g, "\\\\").replace(/'/g, "\\'")}'`;
2653
+ }
2654
+ };
2655
+ function toCamelCase(value) {
2656
+ const parts = value.split(/[^A-Za-z0-9]+/).filter(Boolean).map((part) => part.toLowerCase());
2657
+ if (parts.length === 0) return value;
2658
+ const [first, ...rest] = parts;
2659
+ return first + rest.map((part) => part.charAt(0).toUpperCase() + part.slice(1)).join("");
2660
+ }
2661
+ function sanitizeIdentifier(value) {
2662
+ return value.replace(/[^A-Za-z0-9_$]/g, "");
2663
+ }
2664
+ //#endregion
2665
+ //#region src/jsonl-migration.ts
2666
+ /**
2667
+ * Validate a table by temporarily supplying in-memory rows while reusing the existing LinesDB validation pipeline.
2668
+ * If validation fails, throws an error with validation details.
2669
+ */
2670
+ async function ensureTableRowsValid(options) {
2671
+ const tablePath = join(options.dataDir, `${options.tableName}.jsonl`);
2672
+ const overrides = /* @__PURE__ */ new Map([[tablePath, options.rows]]);
2673
+ await JsonlReader.withOverrides(overrides, async () => {
2674
+ const db = LinesDB.create({ dataDir: options.dataDir });
2675
+ try {
2676
+ const result = unwrap(await db.initialize({ tableName: options.tableName }));
2677
+ if (!result.valid) {
2678
+ const errorCount = result.errors.length;
2679
+ const errorDetails = result.errors.map((e) => {
2680
+ const issueMessages = e.issues.map((issue) => issue.message).join(", ");
2681
+ return ` Row ${e.rowIndex}: ${issueMessages}`;
2682
+ }).join("\n");
2683
+ throw new Error(`Validation failed for table '${options.tableName}' (${errorCount} error(s)):\n${errorDetails}`);
2684
+ }
2685
+ } finally {
2686
+ await db.close();
2687
+ }
2688
+ });
2689
+ }
2690
+ //#endregion
2691
+ //#region src/error-formatter.ts
2692
+ var ErrorFormatter = class {
2693
+ verbose;
2694
+ constructor(options = {}) {
2695
+ this.verbose = options.verbose ?? false;
2696
+ }
2697
+ /**
2698
+ * Format validation errors
2699
+ */
2700
+ formatValidationErrors(errors) {
2701
+ if (this.verbose) return this.formatValidationErrorsVerbose(errors);
2702
+ return this.formatValidationErrorsCompact(errors);
2703
+ }
2704
+ /**
2705
+ * Format foreign key error
2706
+ */
2707
+ formatForeignKeyError(error) {
2708
+ if (this.verbose) return this.formatForeignKeyErrorVerbose(error);
2709
+ return this.formatForeignKeyErrorCompact(error);
2710
+ }
2711
+ /**
2712
+ * Format compact (default) validation errors
2713
+ */
2714
+ formatValidationErrorsCompact(errors) {
2715
+ const lines = [];
2716
+ for (const error of errors) for (const issue of error.issues) {
2717
+ const fieldPath = this.getFieldPath(issue);
2718
+ const line = `${error.file}:${error.rowIndex + 1} • ${fieldPath}: ${issue.message}`;
2719
+ lines.push(line);
2720
+ }
2721
+ return lines.join("\n");
2722
+ }
2723
+ /**
2724
+ * Format verbose validation errors
2725
+ */
2726
+ formatValidationErrorsVerbose(errors) {
2727
+ const blocks = [];
2728
+ for (let i = 0; i < errors.length; i++) {
2729
+ const error = errors[i];
2730
+ const isLast = i === errors.length - 1;
2731
+ const prefix = isLast ? "└─" : "├─";
2732
+ const linePrefix = isLast ? " " : "│ ";
2733
+ const lines = [`${prefix} ${error.file}:${error.rowIndex + 1}`];
2734
+ for (const issue of error.issues) {
2735
+ const fieldPath = this.getFieldPath(issue);
2736
+ lines.push(`${linePrefix}Field: ${fieldPath}`);
2737
+ lines.push(`${linePrefix}Error: ${issue.message}`);
2738
+ }
2739
+ if (error.originalData !== void 0) lines.push(`${linePrefix}Original data: ${JSON.stringify(error.originalData)}`);
2740
+ if (error.data !== void 0) {
2741
+ const label = error.originalData !== void 0 ? "Transformed data" : "Data";
2742
+ lines.push(`${linePrefix}${label}: ${JSON.stringify(error.data)}`);
2743
+ }
2744
+ blocks.push(lines.join("\n"));
2745
+ }
2746
+ return blocks.join("\n│\n");
2747
+ }
2748
+ /**
2749
+ * Format compact foreign key error
2750
+ */
2751
+ formatForeignKeyErrorCompact(error) {
2752
+ return `${error.file}:${error.rowIndex + 1} • ${error.column}: Foreign key constraint failed - Referenced value ${JSON.stringify(error.value)} does not exist in ${error.referencedTable}(${error.referencedColumn})`;
2753
+ }
2754
+ /**
2755
+ * Format verbose foreign key error
2756
+ */
2757
+ formatForeignKeyErrorVerbose(error) {
2758
+ const lines = [
2759
+ `└─ ${error.file}:${error.rowIndex + 1}`,
2760
+ ` Type: Foreign Key Violation`,
2761
+ ` Field: ${error.column}`,
2762
+ ` Value: ${JSON.stringify(error.value)}`,
2763
+ ` References: ${error.referencedTable}(${error.referencedColumn})`,
2764
+ ` Error: Referenced value does not exist in target table`
2765
+ ];
2766
+ if (error.data !== void 0) lines.push(` Data: ${JSON.stringify(error.data)}`);
2767
+ return lines.join("\n");
2768
+ }
2769
+ /**
2770
+ * Get field path from issue
2771
+ */
2772
+ getFieldPath(issue) {
2773
+ if (!issue.path || issue.path.length === 0) return "root";
2774
+ return issue.path.map((segment) => {
2775
+ if (typeof segment === "object" && segment !== null && "key" in segment) return String(segment.key);
2776
+ return String(segment);
2777
+ }).join(".");
2778
+ }
2779
+ /**
2780
+ * Format error header with count
2781
+ */
2782
+ formatErrorHeader(count, file) {
2783
+ const fileInfo = file ? ` in ${file}` : "";
2784
+ return styleText("red", `✗ Found ${count} error(s)${fileInfo}`);
2785
+ }
2786
+ /**
2787
+ * Format migration failure header
2788
+ */
2789
+ formatMigrationFailureHeader() {
2790
+ return styleText("red", "\n✗ Migration failed and was rolled back");
2791
+ }
2792
+ };
2793
+ //#endregion
2794
+ export { DirectoryScanner, ErrorFormatter, JsonlReader, JsonlWriter, LinesDB, RUNTIME, SCHEMA_EXTENSIONS, SchemaLoader, TypeGenerator, defineSchema, detectRuntime, ensureTableRowsValid, err, extractTableNameFromSchemaFile, fillFields, findSchemaFile, hasBackward, isSchemaFile, mergeFields, ok, rewriteExtensionForImport, unwrap };
2795
+
2796
+ //# sourceMappingURL=index.mjs.map