lines-db 0.18.1 → 0.19.1

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 CHANGED
@@ -1,22 +1,19 @@
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";
1
+ import { a as JsonlReader, c as ok, i as replaceFile, l as toError, n as createSchemaImports, o as hashJsonlContent, r as hashContent, s as err, t as MISSING_HASH, u as unwrap } from "./schema-module-D4j10w8_.mjs";
2
2
  import { createRequire } from "node:module";
3
3
  import { randomBytes } from "node:crypto";
4
4
  import { access, chmod, mkdir, readFile, readdir, realpath, rename, rm, stat, writeFile } from "node:fs/promises";
5
5
  import { basename, dirname, extname, isAbsolute, join, relative, resolve } from "node:path";
6
- import { pathToFileURL } from "node:url";
7
6
  import { styleText } from "node:util";
8
7
  import { z } from "zod";
9
- //#region \0rolldown/runtime.js
8
+ // \0rolldown/runtime.js
10
9
  var __require = /* #__PURE__ */ (() => createRequire(import.meta.url))();
11
- //#endregion
12
- //#region src/runtime.ts
10
+ // src/runtime.ts
13
11
  function detectRuntime() {
14
12
  if (typeof process !== "undefined" && process.versions && process.versions.node) return "node";
15
13
  return "unknown";
16
14
  }
17
15
  const RUNTIME = detectRuntime();
18
- //#endregion
19
- //#region src/sqlite-adapter.ts
16
+ // src/sqlite-adapter.ts
20
17
  /**
21
18
  * SQLite adapter for Node.js
22
19
  */
@@ -57,8 +54,7 @@ function createNodeDatabase(path) {
57
54
  }
58
55
  };
59
56
  }
60
- //#endregion
61
- //#region src/jsonl-writer.ts
57
+ // src/jsonl-writer.ts
62
58
  var JsonlWriter = class {
63
59
  /**
64
60
  * Write data to JSONL file
@@ -87,8 +83,7 @@ var JsonlWriter = class {
87
83
  }
88
84
  }
89
85
  };
90
- //#endregion
91
- //#region src/schema-extensions.ts
86
+ // src/schema-extensions.ts
92
87
  /**
93
88
  * Supported schema file extensions, in priority order.
94
89
  * The first match wins when discovering schema files.
@@ -151,8 +146,7 @@ function rewriteExtensionForImport(filePath) {
151
146
  for (const [tsExt, jsExt] of Object.entries(SCHEMA_TO_JS_IMPORT_MAP)) if (filePath.endsWith(tsExt)) return filePath.slice(0, -tsExt.length) + jsExt;
152
147
  return filePath;
153
148
  }
154
- //#endregion
155
- //#region src/schema-loader.ts
149
+ // src/schema-loader.ts
156
150
  var SchemaLoader = class {
157
151
  /**
158
152
  * Check if a schema file exists for a table
@@ -164,13 +158,13 @@ var SchemaLoader = class {
164
158
  * Load a validation schema file for a table
165
159
  * Requires ${tableName}.schema.{ts,mts,cts} to exist in schemaDir, or alongside the JSONL file when omitted
166
160
  */
167
- static async loadSchema(jsonlPath, schemaDir) {
161
+ static async loadSchema(jsonlPath, schemaDir, imports) {
168
162
  const dir = schemaDir ?? dirname(jsonlPath);
169
163
  const tableName = basename(jsonlPath, ".jsonl");
170
164
  const schemaPath = await findSchemaFile(dir, tableName);
171
165
  if (!schemaPath) throw new Error(`Schema file not found for table '${tableName}'. Expected one of: ${SCHEMA_EXTENSIONS.map((ext) => `${tableName}${ext}`).join(", ")}`);
172
166
  try {
173
- const module = await import(`${pathToFileURL(schemaPath).href}?t=${Date.now()}`);
167
+ const module = await (imports ?? createSchemaImports()).import(schemaPath);
174
168
  const schema = module.default || module.schema;
175
169
  if (schema && this.isStandardSchema(schema)) return schema;
176
170
  throw new Error(`Schema file ${schemaPath} does not export a valid StandardSchema`);
@@ -189,8 +183,7 @@ var SchemaLoader = class {
189
183
  return standardObj.version === 1 && typeof standardObj.vendor === "string" && typeof standardObj.validate === "function";
190
184
  }
191
185
  };
192
- //#endregion
193
- //#region src/directory-scanner.ts
186
+ // src/directory-scanner.ts
194
187
  var DirectoryScanner = class {
195
188
  /**
196
189
  * Scan directories for JSONL files and create table configurations.
@@ -223,8 +216,7 @@ var DirectoryScanner = class {
223
216
  return tables;
224
217
  }
225
218
  };
226
- //#endregion
227
- //#region src/schema.ts
219
+ // src/schema.ts
228
220
  /**
229
221
  * Define a bidirectional schema with optional backward transformation
230
222
  *
@@ -280,8 +272,7 @@ function defineSchema(schema, ...args) {
280
272
  function hasBackward(schema) {
281
273
  return "backward" in schema && typeof schema.backward === "function";
282
274
  }
283
- //#endregion
284
- //#region src/merge-fields.ts
275
+ // src/merge-fields.ts
285
276
  /**
286
277
  * Lay the named fields of a computed row over the line a JSONL file already holds.
287
278
  *
@@ -334,8 +325,7 @@ function keepUnknownFields(line, row, columns) {
334
325
  for (const key of Object.keys(row)) if (!Object.hasOwn(line, key)) entries.push([key, row[key]]);
335
326
  return Object.fromEntries(entries);
336
327
  }
337
- //#endregion
338
- //#region src/sql-statements.ts
328
+ // src/sql-statements.ts
339
329
  const TRIGGER_DEFINITION = /^\s*CREATE\s+(?:TEMP(?:ORARY)?\s+)?TRIGGER\b/i;
340
330
  const CLOSER = {
341
331
  "'": "'",
@@ -441,8 +431,7 @@ function isReadOnlyStatement(statement) {
441
431
  if (READ_PRAGMAS_WITH_ARGUMENT.has(name)) return true;
442
432
  return READ_PRAGMAS_BARE.has(name) && argument === void 0;
443
433
  }
444
- //#endregion
445
- //#region src/database.ts
434
+ // src/database.ts
446
435
  function cloneFieldChanges(changes) {
447
436
  return new Map(Array.from(changes, ([tableName, byRow]) => [tableName, new Map(Array.from(byRow, ([rowid, row]) => [rowid, {
448
437
  set: new Set(row.set),
@@ -479,6 +468,7 @@ var LinesDB = class LinesDB {
479
468
  * holds the fields a user wrote, so only what changed since it was written needs remembering
480
469
  */
481
470
  fieldChanges = /* @__PURE__ */ new Map();
471
+ settleUndos;
482
472
  /**
483
473
  * The tables raw SQL may have changed since they were last written back: which fields it set is
484
474
  * unknown, so their rows are written back whole
@@ -510,8 +500,14 @@ var LinesDB = class LinesDB {
510
500
  observedHashes = /* @__PURE__ */ new Map();
511
501
  /** The JSONL files the data directories held when the tables were scanned */
512
502
  scannedJsonlFiles = [];
503
+ /** Tables left out because their files have no rows to infer the columns from */
504
+ emptyTables = /* @__PURE__ */ new Set();
505
+ /** Tables created from the columns `schemaOfEmptyTable` gave, which may lack a field the validator adds */
506
+ tablesFromGivenColumns = /* @__PURE__ */ new Set();
513
507
  /** Each table's schema file and a hash of its content as the tables were loaded, or '' for none */
514
508
  schemaFileStates = /* @__PURE__ */ new Map();
509
+ schemaImports;
510
+ schemaDependencyHashes = /* @__PURE__ */ new Map();
515
511
  constructor(config, dbPath) {
516
512
  this.config = config;
517
513
  this.db = createDatabase(dbPath ?? ":memory:");
@@ -551,12 +547,14 @@ var LinesDB = class LinesDB {
551
547
  const tableName = options?.tableName;
552
548
  const detailedValidate = options?.detailedValidate ?? false;
553
549
  const transform = options?.transform;
550
+ this.emptyTables.clear();
554
551
  this.tables = await DirectoryScanner.scanDirectory(this.config.dataDir);
555
552
  this.scannedJsonlFiles = listJsonlFiles(this.tables);
556
553
  this.observedHashes.clear();
557
554
  this.schemaFileStates.clear();
558
555
  for (const [name, config] of this.tables) this.schemaFileStates.set(name, await this.schemaFileState(name, config));
559
556
  const tablesToLoad = tableName ? [tableName] : Array.from(this.tables.keys());
557
+ for (const name of tablesToLoad) this.tablesFromGivenColumns.delete(name);
560
558
  for (const tableNameToLoad of tablesToLoad) if (!this.tables.has(tableNameToLoad)) {
561
559
  const dataDirs = [this.config.dataDir].flat().map((dir) => `'${dir}'`);
562
560
  throw new Error(`Table '${tableNameToLoad}' not found in directory ${dataDirs.join(", ")}`);
@@ -565,13 +563,25 @@ var LinesDB = class LinesDB {
565
563
  const loadingTables = /* @__PURE__ */ new Set();
566
564
  const attemptedTables = /* @__PURE__ */ new Set();
567
565
  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);
566
+ const imports = createSchemaImports();
567
+ this.schemaImports = imports;
568
+ const schemaPaths = /* @__PURE__ */ new Map();
569
+ for (const [name, config] of this.tables) {
570
+ const schemaPath = await this.findTableSchemaFile(name, config);
571
+ if (schemaPath) schemaPaths.set(name, schemaPath);
572
+ }
573
+ try {
574
+ for (const tableNameToLoad of tablesToLoad) if (!attemptedTables.has(tableNameToLoad)) {
575
+ const tableTransform = tableNameToLoad === tableName ? transform : void 0;
576
+ const { errors, warnings, rowCounts: tableRowCounts, deferredForeignKeys } = await this.loadTableWithDependencies(tableNameToLoad, loadedTables, loadingTables, attemptedTables, detailedValidate, tableTransform);
577
+ allErrors.push(...errors);
578
+ allWarnings.push(...warnings);
579
+ allDeferredForeignKeys.push(...deferredForeignKeys);
580
+ for (const [k, v] of tableRowCounts) allRowCounts.set(k, v);
581
+ }
582
+ } finally {
583
+ this.schemaImports = void 0;
584
+ this.recordSchemaDependencies(imports, attemptedTables, schemaPaths, tableName === void 0);
575
585
  }
576
586
  if (detailedValidate && allDeferredForeignKeys.length > 0) for (const { tableName: tName, foreignKey: fk, filePath } of allDeferredForeignKeys) {
577
587
  if (!loadedTables.has(fk.references.table)) continue;
@@ -596,6 +606,9 @@ var LinesDB = class LinesDB {
596
606
  tableResults
597
607
  };
598
608
  }
609
+ importSchemaModule(schemaPath) {
610
+ return (this.schemaImports ?? createSchemaImports()).import(schemaPath);
611
+ }
599
612
  /**
600
613
  * Load a table and its dependencies recursively
601
614
  */
@@ -618,10 +631,9 @@ var LinesDB = class LinesDB {
618
631
  try {
619
632
  let foreignKeys;
620
633
  try {
621
- const { pathToFileURL } = await import("node:url");
622
634
  const schemaPath = await this.findTableSchemaFile(tableName, tableConfig);
623
635
  if (schemaPath) {
624
- const schemaModule = await import(`${pathToFileURL(schemaPath).href}?t=${Date.now()}`);
636
+ const schemaModule = await this.importSchemaModule(schemaPath);
625
637
  foreignKeys = (schemaModule.schema || schemaModule.default)?.foreignKeys || schemaModule.foreignKeys;
626
638
  }
627
639
  } catch {}
@@ -649,7 +661,10 @@ var LinesDB = class LinesDB {
649
661
  else failedDependencies.add(referencedTable);
650
662
  }
651
663
  }
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`);
664
+ if (failedDependencies.size > 0) for (const dep of failedDependencies) {
665
+ const reason = this.emptyTables.has(dep) ? "has no rows to read its columns from" : "has validation errors";
666
+ warnings.push(`Skipping foreign key validation for table '${tableName}': referenced table '${dep}' ${reason}`);
667
+ }
653
668
  }
654
669
  const allSkippedDependencies = /* @__PURE__ */ new Set([...failedDependencies, ...circularDependencies]);
655
670
  const { loaded, rowCount, errors: loadErrors } = await this.loadTable(tableName, tableConfig, detailedValidate, transform, allSkippedDependencies);
@@ -665,6 +680,7 @@ var LinesDB = class LinesDB {
665
680
  });
666
681
  }
667
682
  } else {
683
+ if (rowCount === 0 && loadErrors.length === 0) this.emptyTables.add(tableName);
668
684
  warnings.push(`Table '${tableName}' was not loaded (no data or skipped)`);
669
685
  this.tables.delete(tableName);
670
686
  }
@@ -718,11 +734,10 @@ var LinesDB = class LinesDB {
718
734
  let validationSchema = config.validationSchema;
719
735
  const schemaMetadata = {};
720
736
  const schemaPath = config.validationSchema ? void 0 : await this.findTableSchemaFile(tableName, config);
721
- if (!validationSchema && schemaPath) validationSchema = await SchemaLoader.loadSchema(config.jsonlPath, dirname(schemaPath));
737
+ if (!validationSchema && schemaPath) validationSchema = await SchemaLoader.loadSchema(config.jsonlPath, dirname(schemaPath), this.schemaImports);
722
738
  if (!config.validationSchema) try {
723
- const { pathToFileURL } = await import("node:url");
724
739
  if (!schemaPath) throw new Error("Schema file not found");
725
- const schemaModule = await import(`${pathToFileURL(schemaPath).href}?t=${Date.now()}`);
740
+ const schemaModule = await this.importSchemaModule(schemaPath);
726
741
  const schemaExport = schemaModule.schema || schemaModule.default;
727
742
  if (schemaExport?.primaryKey) schemaMetadata.primaryKey = schemaExport.primaryKey;
728
743
  else if (schemaModule.primaryKey) schemaMetadata.primaryKey = schemaModule.primaryKey;
@@ -779,12 +794,23 @@ var LinesDB = class LinesDB {
779
794
  if (schemaCol && inferredCol.valueType && !schemaCol.valueType) schemaCol.valueType = inferredCol.valueType;
780
795
  }
781
796
  } else if (config.autoInferSchema !== false) {
782
- if (validatedData.length === 0) return {
783
- loaded: false,
784
- rowCount: 0,
785
- errors: []
786
- };
787
- schema = inferredSchema;
797
+ if (validatedData.length === 0) {
798
+ const declared = await this.config.schemaOfEmptyTable?.({
799
+ tableName,
800
+ schemaPath
801
+ });
802
+ if (!declared || declared.columns.length === 0) return {
803
+ loaded: false,
804
+ rowCount: 0,
805
+ errors: []
806
+ };
807
+ schema = {
808
+ ...declared,
809
+ name: tableName,
810
+ columns: declared.columns.map((column) => ({ ...column }))
811
+ };
812
+ this.tablesFromGivenColumns.add(tableName);
813
+ } else schema = inferredSchema;
788
814
  } else throw new Error(`No schema provided for table ${tableName} and autoInferSchema is disabled`);
789
815
  const biSchema = validationSchema;
790
816
  const primaryKey = biSchema?.primaryKey || schemaMetadata.primaryKey;
@@ -808,6 +834,7 @@ var LinesDB = class LinesDB {
808
834
  if (col && !col.unique && !col.primaryKey) col.unique = true;
809
835
  }
810
836
  }
837
+ if (schema === inferredSchema) this.relaxColumnsTheSchemaLeavesOptional(tableName, schema, data[0]);
811
838
  this.schemas.set(tableName, schema);
812
839
  this.createTable(schema);
813
840
  if (detailedValidate || this.config.writeDataSets) {
@@ -844,6 +871,55 @@ var LinesDB = class LinesDB {
844
871
  };
845
872
  }
846
873
  /**
874
+ * A column no row holds a value in has no type to read a boolean or an object back with, and so reads
875
+ * back as 1 or as JSON text. The first value written settles it, and a string settles it as text so an
876
+ * object written later does not turn that text into JSON. Not asked of the schema: it names no type at
877
+ * run time. Returns what puts the columns back, which a write that did not go in, or a transaction that
878
+ * rolled back, must call: the value that settled it is not in the table
879
+ */
880
+ settleColumnsNoRowHolds(schema, written) {
881
+ const before = [];
882
+ for (const column of schema?.columns ?? []) {
883
+ const value = written[column.name];
884
+ if (column.type !== "NULL" || value === null || value === void 0) continue;
885
+ before.push([
886
+ column,
887
+ column.type,
888
+ column.valueType
889
+ ]);
890
+ if (typeof value === "boolean") {
891
+ column.type = "INTEGER";
892
+ column.valueType = "boolean";
893
+ } else if (typeof value === "string") column.type = "TEXT";
894
+ else if (typeof value === "number") column.type = Number.isInteger(value) ? "INTEGER" : "REAL";
895
+ else if (typeof value === "object" && !(value instanceof Uint8Array)) column.type = "JSON";
896
+ else before.pop();
897
+ }
898
+ const undo = () => {
899
+ for (const [column, type, valueType] of before) {
900
+ column.type = type;
901
+ column.valueType = valueType;
902
+ }
903
+ };
904
+ this.settleUndos?.push(undo);
905
+ return undo;
906
+ }
907
+ /**
908
+ * A column every row holds is inferred NOT NULL, which refuses a later row that leaves it out even
909
+ * where the schema takes that row. The sample row without the field says whether the schema does.
910
+ * A column the schema fills in stays NOT NULL: the row is stored as the schema leaves it
911
+ */
912
+ relaxColumnsTheSchemaLeavesOptional(tableName, schema, sample) {
913
+ if (!sample || !this.validationSchemas.get(tableName)) return;
914
+ for (const column of schema.columns) {
915
+ if (!column.notNull || column.primaryKey || !(column.name in sample)) continue;
916
+ const { [column.name]: _left, ...without } = sample;
917
+ try {
918
+ if ((this.validateAndTransform(tableName, without)[column.name] ?? null) === null) column.notNull = false;
919
+ } catch {}
920
+ }
921
+ }
922
+ /**
847
923
  * Create table in SQLite with constraints and indexes
848
924
  */
849
925
  createTable(schema) {
@@ -909,6 +985,7 @@ var LinesDB = class LinesDB {
909
985
  if (data.length === 0) return;
910
986
  const columnNames = schema.columns.map((col) => col.name);
911
987
  const quotedColumns = columnNames.map((name) => this.quoteIdentifier(name));
988
+ const columnsByName = new Map(schema.columns.map((column) => [column.name, column]));
912
989
  const columnCount = columnNames.length;
913
990
  const maxBatchSize = Math.floor(900 / columnCount);
914
991
  const batchSize = Math.max(1, Math.min(maxBatchSize, 100));
@@ -918,7 +995,7 @@ var LinesDB = class LinesDB {
918
995
  const valuesPlaceholders = batch.map(() => `(${rowPlaceholders})`).join(", ");
919
996
  const sql = `INSERT INTO ${this.quoteTableName(tableName)} (${quotedColumns.join(", ")}) VALUES ${valuesPlaceholders}`;
920
997
  const values = [];
921
- for (const row of batch) for (const col of columnNames) values.push(this.normalizeValue(row[col]));
998
+ for (const row of batch) for (const col of columnNames) values.push(this.normalizeValue(row[col], columnsByName.get(col)));
922
999
  this.db.prepare(sql).run(...values);
923
1000
  }
924
1001
  }
@@ -932,13 +1009,14 @@ var LinesDB = class LinesDB {
932
1009
  const quotedColumns = columnNames.map((name) => this.quoteIdentifier(name));
933
1010
  const placeholders = columnNames.map(() => "?").join(", ");
934
1011
  const sql = `INSERT INTO ${this.quoteTableName(tableName)} (${quotedColumns.join(", ")}) VALUES (${placeholders})`;
1012
+ const columnsByName = new Map(schema.columns.map((column) => [column.name, column]));
935
1013
  const stmt = this.db.prepare(sql);
936
1014
  const rowOrigins = /* @__PURE__ */ new Map();
937
1015
  this.rowOriginsByRowid.set(tableName, rowOrigins);
938
1016
  for (let rowIndex = 0; rowIndex < data.length; rowIndex++) {
939
1017
  const row = data[rowIndex];
940
1018
  try {
941
- const values = columnNames.map((col) => this.normalizeValue(row[col]));
1019
+ const values = columnNames.map((col) => this.normalizeValue(row[col], columnsByName.get(col)));
942
1020
  const { lastInsertRowid } = stmt.run(...values);
943
1021
  rowOrigins.set(String(lastInsertRowid), origins[rowIndex]);
944
1022
  } catch (error) {
@@ -957,7 +1035,7 @@ var LinesDB = class LinesDB {
957
1035
  const fkValue = row[fk.column];
958
1036
  if (fkValue === null || fkValue === void 0) continue;
959
1037
  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)]);
1038
+ const result = this.queryInternal(`SELECT COUNT(*) as count FROM ${this.quoteIdentifier(fk.references.table)} WHERE ${this.quoteIdentifier(fk.references.column)} = ?`, [this.normalizeValue(fkValue, this.columnOf(fk.references.table, fk.references.column))]);
961
1039
  if (result.length > 0 && result[0].count === 0) return {
962
1040
  file,
963
1041
  tableName,
@@ -1105,7 +1183,7 @@ var LinesDB = class LinesDB {
1105
1183
  findInternal(tableName, where) {
1106
1184
  if (where === void 0) return this.queryInternal(`SELECT * FROM ${this.quoteTableName(tableName)}`).map((row) => this.deserializeRow(tableName, row));
1107
1185
  if (Array.isArray(where) && where.length === 0) return [];
1108
- const { sql, values, functionFilters, hasOrWithFunctionFilters } = this.buildWhereClause(where);
1186
+ const { sql, values, functionFilters, hasOrWithFunctionFilters } = this.buildWhereClause(where, tableName);
1109
1187
  let rows;
1110
1188
  if (hasOrWithFunctionFilters) {
1111
1189
  rows = this.queryInternal(`SELECT * FROM ${this.quoteTableName(tableName)}`).map((row) => this.deserializeRow(tableName, row));
@@ -1126,7 +1204,7 @@ var LinesDB = class LinesDB {
1126
1204
  }
1127
1205
  }
1128
1206
  findOneInternal(tableName, where) {
1129
- const { sql, values, functionFilters } = this.buildWhereClause(where);
1207
+ const { sql, values, functionFilters } = this.buildWhereClause(where, tableName);
1130
1208
  let rows;
1131
1209
  if (sql) rows = this.queryInternal(`SELECT * FROM ${this.quoteTableName(tableName)} WHERE ${sql}`, values).map((row) => this.deserializeRow(tableName, row));
1132
1210
  else rows = this.queryInternal(`SELECT * FROM ${this.quoteTableName(tableName)}`).map((row) => this.deserializeRow(tableName, row));
@@ -1223,13 +1301,22 @@ var LinesDB = class LinesDB {
1223
1301
  destination = join([this.config.dataDir].flat().find((dir) => resolve(dir) === resolve(dataDir)), `${tableName}.jsonl`);
1224
1302
  }
1225
1303
  const row = this.validateAndTransform(tableName, data);
1226
- if (!this.schemas.get(tableName)) throw new Error(`Table ${tableName} does not exist`);
1304
+ const schema = this.schemas.get(tableName);
1305
+ if (!schema) throw new Error(`Table ${tableName} does not exist`);
1306
+ this.addMissingColumns(tableName, schema, row);
1227
1307
  const columnNames = Object.keys(row);
1228
1308
  const quotedColumns = columnNames.map((col) => this.quoteIdentifier(col));
1229
1309
  const placeholders = columnNames.map(() => "?").join(", ");
1230
1310
  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);
1311
+ const values = columnNames.map((col) => this.normalizeValue(row[col], this.columnOf(tableName, col)));
1312
+ const undoSettle = this.settleColumnsNoRowHolds(schema, row);
1313
+ let result;
1314
+ try {
1315
+ result = this.executeInternal(sql, values);
1316
+ } catch (error) {
1317
+ undoSettle();
1318
+ throw error;
1319
+ }
1233
1320
  if (destination) {
1234
1321
  const origins = this.rowOriginsByRowid.get(tableName) ?? /* @__PURE__ */ new Map();
1235
1322
  origins.set(String(result.lastInsertRowid), {
@@ -1246,6 +1333,27 @@ var LinesDB = class LinesDB {
1246
1333
  return result;
1247
1334
  }
1248
1335
  /**
1336
+ * A table made from the columns given has only those, and the validator may add a field they lack: the
1337
+ * columns of a table made from rows are those of the validated rows, which have it
1338
+ */
1339
+ addMissingColumns(tableName, schema, row) {
1340
+ if (!this.tablesFromGivenColumns.has(tableName)) return;
1341
+ const known = new Set(schema.columns.map((column) => column.name));
1342
+ const missing = Object.keys(row).filter((key) => !known.has(key));
1343
+ if (missing.length === 0) return;
1344
+ for (const column of unwrap(JsonlReader.inferSchema(tableName, [row])).columns) {
1345
+ if (!missing.includes(column.name)) continue;
1346
+ const sqlType = column.type === "JSON" ? "TEXT" : column.type;
1347
+ this.db.exec(`ALTER TABLE ${this.quoteTableName(tableName)} ADD COLUMN ${this.quoteIdentifier(column.name)} ${sqlType}`);
1348
+ schema.columns.push({
1349
+ name: column.name,
1350
+ type: column.type,
1351
+ notNull: false,
1352
+ valueType: column.valueType
1353
+ });
1354
+ }
1355
+ }
1356
+ /**
1249
1357
  * Batch insert rows with validation per record.
1250
1358
  */
1251
1359
  batchInsert(tableName, records) {
@@ -1258,7 +1366,8 @@ var LinesDB = class LinesDB {
1258
1366
  batchInsertInternal(tableName, records) {
1259
1367
  this.assertMutable(tableName);
1260
1368
  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`);
1369
+ const schema = this.schemas.get(tableName);
1370
+ if (!schema) throw new Error(`Table ${tableName} does not exist`);
1262
1371
  if (records.length === 0) return {
1263
1372
  changes: 0,
1264
1373
  lastInsertRowid: 0
@@ -1268,12 +1377,20 @@ var LinesDB = class LinesDB {
1268
1377
  try {
1269
1378
  for (const record of records) {
1270
1379
  const row = this.validateAndTransform(tableName, record);
1380
+ this.addMissingColumns(tableName, schema, row);
1271
1381
  const columnNames = Object.keys(row);
1272
1382
  const quotedColumns = columnNames.map((col) => this.quoteIdentifier(col));
1273
1383
  const placeholders = columnNames.map(() => "?").join(", ");
1274
1384
  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);
1385
+ const values = columnNames.map((col) => this.normalizeValue(row[col], this.columnOf(tableName, col)));
1386
+ const undoSettle = this.settleColumnsNoRowHolds(this.schemas.get(tableName), row);
1387
+ let result;
1388
+ try {
1389
+ result = this.executeInternal(sql, values);
1390
+ } catch (error) {
1391
+ undoSettle();
1392
+ throw error;
1393
+ }
1277
1394
  this.noteFieldChanges(tableName, result.lastInsertRowid, {
1278
1395
  set: givenFields(record),
1279
1396
  inserted: true
@@ -1318,7 +1435,7 @@ var LinesDB = class LinesDB {
1318
1435
  this.validateData(tableName, mergedData);
1319
1436
  }
1320
1437
  }
1321
- const { sql: whereSql, values: whereValues, functionFilters } = this.buildWhereClause(where);
1438
+ const { sql: whereSql, values: whereValues, functionFilters } = this.buildWhereClause(where, tableName);
1322
1439
  if (functionFilters.length > 0) throw new Error("Function filters are not supported in update operations");
1323
1440
  const targets = this.queryInternal(`SELECT rowid AS "${ROWID_ALIAS}", * FROM ${this.quoteTableName(tableName)} WHERE ${whereSql}`, whereValues);
1324
1441
  const resetFields = options?.resetToDefault ?? [];
@@ -1330,12 +1447,19 @@ var LinesDB = class LinesDB {
1330
1447
  if (Object.keys(data).length > 0) {
1331
1448
  const setClauses = Object.keys(data).map((key) => `${this.quoteIdentifier(key)} = ?`).join(", ");
1332
1449
  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);
1450
+ const values = [...Object.entries(data).map(([key, v]) => this.normalizeValue(v, this.columnOf(tableName, key))), ...whereValues];
1451
+ const undoSettle = this.settleColumnsNoRowHolds(this.schemas.get(tableName), data);
1452
+ try {
1453
+ result = this.executeInternal(sql, values);
1454
+ } catch (error) {
1455
+ undoSettle();
1456
+ throw error;
1457
+ }
1458
+ if (Number(result.changes) === 0) undoSettle();
1335
1459
  }
1336
1460
  const pkName = this.schemas.get(tableName)?.columns.find((col) => col.primaryKey)?.name;
1337
1461
  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])]);
1462
+ const moved = this.queryInternal(`SELECT rowid AS "${ROWID_ALIAS}" FROM ${this.quoteTableName(tableName)} WHERE ${this.quoteIdentifier(pkName)} = ?`, [this.normalizeValue(data[pkName], this.columnOf(tableName, pkName))]);
1339
1463
  if (targets.length === 1 && moved.length === 1) {
1340
1464
  const from = String(targets[0][ROWID_ALIAS]);
1341
1465
  const to = moved[0][ROWID_ALIAS];
@@ -1349,7 +1473,7 @@ var LinesDB = class LinesDB {
1349
1473
  }
1350
1474
  }
1351
1475
  for (const target of targets) {
1352
- const set = Object.keys(data).filter((key) => !sameStoredValue(target[key], this.normalizeValue(data[key])));
1476
+ const set = Object.keys(data).filter((key) => !sameStoredValue(target[key], this.normalizeValue(data[key], this.columnOf(tableName, key))));
1353
1477
  this.noteFieldChanges(tableName, target[ROWID_ALIAS], { set });
1354
1478
  }
1355
1479
  if (resets.length > 0) result = this.applyResets(tableName, resets, resetFields);
@@ -1453,7 +1577,7 @@ var LinesDB = class LinesDB {
1453
1577
  deleteInternal(tableName, where) {
1454
1578
  this.assertMutable(tableName);
1455
1579
  if (!this.schemas.get(tableName)) throw new Error(`Table ${tableName} does not exist`);
1456
- const { sql: whereSql, values, functionFilters } = this.buildWhereClause(where);
1580
+ const { sql: whereSql, values, functionFilters } = this.buildWhereClause(where, tableName);
1457
1581
  if (functionFilters.length > 0) throw new Error("Function filters are not supported in delete operations");
1458
1582
  const deleted = this.rowidsWhere(tableName, whereSql, values);
1459
1583
  const sql = `DELETE FROM ${this.quoteTableName(tableName)} WHERE ${whereSql}`;
@@ -1490,7 +1614,7 @@ var LinesDB = class LinesDB {
1490
1614
  });
1491
1615
  const placeholders = pkValues.map(() => "?").join(", ");
1492
1616
  const sql = `DELETE FROM ${this.quoteTableName(tableName)} WHERE ${this.quoteIdentifier(pkName)} IN (${placeholders})`;
1493
- const values = pkValues.map((value) => this.normalizeValue(value));
1617
+ const values = pkValues.map((value) => this.normalizeValue(value, this.columnOf(tableName, pkName)));
1494
1618
  const deleted = this.rowidsWhere(tableName, `${this.quoteIdentifier(pkName)} IN (${placeholders})`, values);
1495
1619
  const result = this.executeInternal(sql, values);
1496
1620
  this.forgetFieldChanges(tableName, deleted);
@@ -1503,17 +1627,24 @@ var LinesDB = class LinesDB {
1503
1627
  /**
1504
1628
  * Normalize value for SQLite
1505
1629
  */
1506
- normalizeValue(value) {
1630
+ normalizeValue(value, column) {
1507
1631
  if (value === null || value === void 0) return null;
1632
+ if (column?.type === "JSON") {
1633
+ if (value instanceof Uint8Array) return value;
1634
+ return typeof value === "bigint" ? value.toString() : JSON.stringify(value);
1635
+ }
1508
1636
  if (typeof value === "boolean") return value ? 1 : 0;
1509
1637
  if (typeof value === "string" || typeof value === "number" || typeof value === "bigint") return value;
1510
1638
  if (value instanceof Uint8Array) return value;
1511
1639
  return JSON.stringify(value);
1512
1640
  }
1641
+ columnOf(tableName, columnName) {
1642
+ return this.schemas.get(tableName)?.columns.find((column) => column.name === columnName);
1643
+ }
1513
1644
  /**
1514
1645
  * Build WHERE clause from condition (supports OR/AND with arrays and functions)
1515
1646
  */
1516
- buildWhereClause(condition) {
1647
+ buildWhereClause(condition, tableName) {
1517
1648
  const values = [];
1518
1649
  const functionFilters = [];
1519
1650
  let hasOrWithFunctionFilters = false;
@@ -1532,7 +1663,7 @@ var LinesDB = class LinesDB {
1532
1663
  hasFunctionFilter = true;
1533
1664
  } else {
1534
1665
  conditions.push(`${this.quoteIdentifier(key)} = ?`);
1535
- values.push(this.normalizeValue(value));
1666
+ values.push(this.normalizeValue(value, this.columnOf(tableName, key)));
1536
1667
  }
1537
1668
  if (isInOr && hasFunctionFilter) hasOrWithFunctionFilters = true;
1538
1669
  return conditions.join(" AND ");
@@ -1797,8 +1928,9 @@ var LinesDB = class LinesDB {
1797
1928
  for (const key of rowChanges?.reset ?? []) keep.delete(key);
1798
1929
  for (const key of namedFields) keep.add(key);
1799
1930
  if (pkName) keep.add(pkName);
1931
+ const untouched = line !== void 0 && !rowChanges?.inserted && !rowChanges?.set.size && !rowChanges?.reset.size;
1800
1932
  return {
1801
- written: Object.fromEntries(Object.entries(lineRow).filter(([key]) => keep.has(key))),
1933
+ written: Object.fromEntries(Object.entries(lineRow).filter(([key]) => keep.has(key)).map(([key, value]) => [key, untouched && Object.hasOwn(line, key) && !actionColumns.includes(key) && !namedFields.includes(key) ? line[key] : value])),
1802
1934
  narrowed: true
1803
1935
  };
1804
1936
  });
@@ -1882,7 +2014,7 @@ var LinesDB = class LinesDB {
1882
2014
  const validated = this.validateAndTransform(tableName, row);
1883
2015
  return {
1884
2016
  rowid,
1885
- values: fields.map((field) => this.normalizeValue(validated[field]))
2017
+ values: fields.map((field) => this.normalizeValue(validated[field], this.columnOf(tableName, field)))
1886
2018
  };
1887
2019
  });
1888
2020
  }
@@ -2145,7 +2277,8 @@ var LinesDB = class LinesDB {
2145
2277
  }
2146
2278
  /**
2147
2279
  * 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
2280
+ * tells: each JSONL file edited, added or removed, each schema file edited, added or removed, and each
2281
+ * project file a schema imports edited, added or removed
2149
2282
  */
2150
2283
  async findExternalChanges() {
2151
2284
  try {
@@ -2164,6 +2297,16 @@ var LinesDB = class LinesDB {
2164
2297
  });
2165
2298
  if (content === void 0 || hashJsonlContent(content) !== knownHash) changed.add(file);
2166
2299
  }
2300
+ const knownHashes = /* @__PURE__ */ new Map();
2301
+ for (const files of this.schemaDependencyHashes.values()) for (const [file, knownHash] of files) knownHashes.set(file, (knownHashes.get(file) ?? /* @__PURE__ */ new Set()).add(knownHash));
2302
+ for (const [file, hashes] of knownHashes) {
2303
+ const content = await readFile(file).catch((error) => {
2304
+ if (error.code === "ENOENT") return void 0;
2305
+ throw error;
2306
+ });
2307
+ const current = content === void 0 ? MISSING_HASH : hashContent(content);
2308
+ if ([...hashes].some((hash) => hash !== current)) changed.add(file);
2309
+ }
2167
2310
  const tables = await DirectoryScanner.scanDirectory(this.config.dataDir);
2168
2311
  const scanned = new Set(listJsonlFiles(tables));
2169
2312
  for (const file of this.scannedJsonlFiles) if (!scanned.has(file)) changed.add(file);
@@ -2186,6 +2329,25 @@ var LinesDB = class LinesDB {
2186
2329
  });
2187
2330
  return content === void 0 ? "" : `${schemaPath}\0${hashJsonlContent(content)}`;
2188
2331
  }
2332
+ recordSchemaDependencies(imports, tableNames, schemaPaths, replace) {
2333
+ if (replace) {
2334
+ for (const name of this.schemaDependencyHashes.keys()) if (!schemaPaths.has(name)) this.schemaDependencyHashes.delete(name);
2335
+ }
2336
+ for (const name of tableNames) {
2337
+ const schemaPath = schemaPaths.get(name);
2338
+ if (schemaPath) this.schemaDependencyHashes.set(name, imports.dependencies(schemaPath));
2339
+ else this.schemaDependencyHashes.delete(name);
2340
+ }
2341
+ }
2342
+ /**
2343
+ * The project files the schemas import, as paths: not the schema files, and not a package from
2344
+ * node_modules. Those of one table when it is given. An edit to one of them is among
2345
+ * {@link findExternalChanges}
2346
+ */
2347
+ listSchemaDependencies(tableName) {
2348
+ const tables = tableName === void 0 ? [...this.schemaDependencyHashes.values()] : [this.schemaDependencyHashes.get(tableName) ?? /* @__PURE__ */ new Map()];
2349
+ return [...new Set(tables.flatMap((files) => [...files.keys()]))];
2350
+ }
2189
2351
  async schemaFileState(tableName, config) {
2190
2352
  if (config.validationSchema) return "";
2191
2353
  const schemaPath = await this.findTableSchemaFile(tableName, config);
@@ -2235,15 +2397,18 @@ var LinesDB = class LinesDB {
2235
2397
  let rawSqlTablesBefore;
2236
2398
  let linesWithUnknownFieldsBefore;
2237
2399
  let originsBefore;
2400
+ let columnsBefore;
2238
2401
  const scannedBefore = [...this.scannedJsonlFiles];
2239
2402
  let written = [];
2240
2403
  try {
2241
2404
  await this.waitForPendingSyncs();
2242
2405
  originsBefore = new Map([...this.rowOriginsByRowid].map(([name, origins]) => [name, new Map(origins)]));
2406
+ columnsBefore = new Map([...this.tablesFromGivenColumns].map((name) => [name, [...this.schemas.get(name)?.columns ?? []]]));
2243
2407
  fieldChangesBefore = cloneFieldChanges(this.fieldChanges);
2244
2408
  rawSqlTablesBefore = new Set(this.rawSqlTables);
2245
2409
  linesWithUnknownFieldsBefore = new Map(Array.from(this.linesWithUnknownFields, ([tableName, lines]) => [tableName, new Map(lines)]));
2246
2410
  this.db.exec("BEGIN TRANSACTION");
2411
+ this.settleUndos = [];
2247
2412
  this.inTransaction = true;
2248
2413
  this.transactionToken = token;
2249
2414
  this.transactionStarting = false;
@@ -2256,6 +2421,7 @@ var LinesDB = class LinesDB {
2256
2421
  }
2257
2422
  if (!this.isReadOnlyDataSet()) written = await this.writeBackTogether(this.tablesChangedInTransaction());
2258
2423
  this.db.exec("COMMIT");
2424
+ this.settleUndos = void 0;
2259
2425
  this.inTransaction = false;
2260
2426
  this.transactionChanges = void 0;
2261
2427
  return ok(result);
@@ -2263,6 +2429,10 @@ var LinesDB = class LinesDB {
2263
2429
  this.transactionStarting = false;
2264
2430
  this.transactionChanges = void 0;
2265
2431
  if (originsBefore) this.rowOriginsByRowid = originsBefore;
2432
+ for (const [name, columns] of columnsBefore ?? []) {
2433
+ const schema = this.schemas.get(name);
2434
+ if (schema) schema.columns = columns;
2435
+ }
2266
2436
  this.scannedJsonlFiles = scannedBefore;
2267
2437
  if (fieldChangesBefore) this.fieldChanges = fieldChangesBefore;
2268
2438
  if (rawSqlTablesBefore) this.rawSqlTables = rawSqlTablesBefore;
@@ -2271,6 +2441,8 @@ var LinesDB = class LinesDB {
2271
2441
  if (this.inTransaction) try {
2272
2442
  this.db.exec("ROLLBACK");
2273
2443
  } catch (_rollbackError) {}
2444
+ for (const undo of [...this.settleUndos ?? []].reverse()) undo();
2445
+ this.settleUndos = void 0;
2274
2446
  this.inTransaction = false;
2275
2447
  return err(toError(failure));
2276
2448
  } finally {
@@ -2357,8 +2529,7 @@ var LinesDB = class LinesDB {
2357
2529
  function listJsonlFiles(tables) {
2358
2530
  return Array.from(tables.values()).flatMap((config) => config.jsonlPaths ?? [config.jsonlPath]).sort();
2359
2531
  }
2360
- //#endregion
2361
- //#region src/fill.ts
2532
+ // src/fill.ts
2362
2533
  /**
2363
2534
  * Fill the named fields into the rows of the JSONL files that have no value for them, with the values
2364
2535
  * each table computes for a row. A value already in the file is never replaced, and a line that gains
@@ -2393,13 +2564,14 @@ async function fillFieldsInternal(options) {
2393
2564
  const loadFiller = options.loadFiller ?? fillerFromValidationSchema;
2394
2565
  const tablesWithoutSchema = [];
2395
2566
  const tables = [];
2567
+ const imports = createSchemaImports();
2396
2568
  for (const { table, file, target, schemaDir } of sources.values()) {
2397
2569
  const schemaPath = await findSchemaFile(schemaDir, table);
2398
2570
  if (!schemaPath) {
2399
2571
  if (!tablesWithoutSchema.includes(table)) tablesWithoutSchema.push(table);
2400
2572
  continue;
2401
2573
  }
2402
- const schemaModule = await import(`${pathToFileURL(schemaPath).href}?t=${Date.now()}`);
2574
+ const schemaModule = await imports.import(schemaPath);
2403
2575
  tables.push({
2404
2576
  table,
2405
2577
  file,
@@ -2571,8 +2743,7 @@ function serializeRow(row, fieldOrder) {
2571
2743
  for (const [key, value] of ordered) setField(out, key, value);
2572
2744
  return JSON.stringify(out);
2573
2745
  }
2574
- //#endregion
2575
- //#region src/type-generator.ts
2746
+ // src/type-generator.ts
2576
2747
  var TypeGenerator = class {
2577
2748
  dataDir;
2578
2749
  projectRoot;
@@ -2678,8 +2849,7 @@ function toCamelCase(value) {
2678
2849
  function sanitizeIdentifier(value) {
2679
2850
  return value.replace(/[^A-Za-z0-9_$]/g, "");
2680
2851
  }
2681
- //#endregion
2682
- //#region src/jsonl-migration.ts
2852
+ // src/jsonl-migration.ts
2683
2853
  /**
2684
2854
  * Validate a table by temporarily supplying in-memory rows while reusing the existing LinesDB validation pipeline.
2685
2855
  * If validation fails, throws an error with validation details.
@@ -2704,8 +2874,7 @@ async function ensureTableRowsValid(options) {
2704
2874
  }
2705
2875
  });
2706
2876
  }
2707
- //#endregion
2708
- //#region src/error-formatter.ts
2877
+ // src/error-formatter.ts
2709
2878
  var ErrorFormatter = class {
2710
2879
  verbose;
2711
2880
  constructor(options = {}) {
@@ -2807,8 +2976,7 @@ var ErrorFormatter = class {
2807
2976
  return styleText("red", "\n✗ Migration failed and was rolled back");
2808
2977
  }
2809
2978
  };
2810
- //#endregion
2811
- //#region src/dataset-config.ts
2979
+ // src/dataset-config.ts
2812
2980
  const directories = z.array(z.string().min(1)).min(1);
2813
2981
  const datasetConfigSchema = z.strictObject({
2814
2982
  schemaDir: z.string().min(1),
@@ -2840,7 +3008,6 @@ async function loadDatasetConfig(path = "lines-db.config.json", options = {}) {
2840
3008
  schemaDir
2841
3009
  };
2842
3010
  }
2843
- //#endregion
2844
3011
  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
3012
 
2846
3013
  //# sourceMappingURL=index.mjs.map