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