lines-db 0.19.0 → 0.19.2

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,9 +1,8 @@
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-fStWc0ej.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
8
  // \0rolldown/runtime.js
@@ -159,13 +158,13 @@ var SchemaLoader = class {
159
158
  * Load a validation schema file for a table
160
159
  * Requires ${tableName}.schema.{ts,mts,cts} to exist in schemaDir, or alongside the JSONL file when omitted
161
160
  */
162
- static async loadSchema(jsonlPath, schemaDir) {
161
+ static async loadSchema(jsonlPath, schemaDir, imports) {
163
162
  const dir = schemaDir ?? dirname(jsonlPath);
164
163
  const tableName = basename(jsonlPath, ".jsonl");
165
164
  const schemaPath = await findSchemaFile(dir, tableName);
166
165
  if (!schemaPath) throw new Error(`Schema file not found for table '${tableName}'. Expected one of: ${SCHEMA_EXTENSIONS.map((ext) => `${tableName}${ext}`).join(", ")}`);
167
166
  try {
168
- const module = await import(`${pathToFileURL(schemaPath).href}?t=${Date.now()}`);
167
+ const module = await (imports ?? createSchemaImports()).import(schemaPath);
169
168
  const schema = module.default || module.schema;
170
169
  if (schema && this.isStandardSchema(schema)) return schema;
171
170
  throw new Error(`Schema file ${schemaPath} does not export a valid StandardSchema`);
@@ -437,15 +436,80 @@ function cloneFieldChanges(changes) {
437
436
  return new Map(Array.from(changes, ([tableName, byRow]) => [tableName, new Map(Array.from(byRow, ([rowid, row]) => [rowid, {
438
437
  set: new Set(row.set),
439
438
  reset: new Set(row.reset),
440
- inserted: row.inserted
439
+ inserted: row.inserted,
440
+ ...row.inputs ? { inputs: new Map(row.inputs) } : {}
441
441
  }]))]));
442
442
  }
443
+ /** The line of each row by the position recorded for it, undefined for a row that has none */
444
+ function linesByPosition(positions, rowids, existingRows) {
445
+ if (!positions) return void 0;
446
+ return rowids.map((rowid) => {
447
+ const position = positions.get(rowid);
448
+ return position === void 0 ? void 0 : existingRows[position];
449
+ });
450
+ }
451
+ /**
452
+ * Where each row's line stands in a file once it is written: the lines of rows that kept one stay in order,
453
+ * and a row without one goes after them, in the order the rows are given
454
+ */
455
+ function positionsAfterWrite(rowids, matches, existingRows) {
456
+ const kept = new Set(matches.filter((line) => line !== void 0));
457
+ const positionOfLine = /* @__PURE__ */ new Map();
458
+ existingRows.filter((line) => kept.has(line)).forEach((line, position) => positionOfLine.set(line, position));
459
+ let next = positionOfLine.size;
460
+ return new Map(rowids.map((rowid, index) => {
461
+ const line = matches[index];
462
+ return [rowid, line === void 0 ? next++ : positionOfLine.get(line)];
463
+ }));
464
+ }
465
+ /**
466
+ * What was kept by rowid when a write-back read its rows, brought up to date with the changes made since, in order:
467
+ * a deleted or reused rowid loses what it had, and a row that moved carries it to its new rowid
468
+ */
469
+ function replayEdits(byRowid, edits) {
470
+ for (const edit of edits) {
471
+ if ("forget" in edit) {
472
+ byRowid.delete(edit.forget);
473
+ continue;
474
+ }
475
+ const kept = byRowid.get(edit.from);
476
+ if (kept === void 0) continue;
477
+ byRowid.delete(edit.from);
478
+ byRowid.set(edit.to, kept);
479
+ }
480
+ return byRowid;
481
+ }
482
+ /**
483
+ * The temporary table the rowid changes of rows are logged to. Not qualified with `temp.`: SQLite before 3.53, as Bun
484
+ * ships, refuses a qualified table name in a trigger body, and an unqualified one is looked up in `temp` first
485
+ */
486
+ const MOVED_ROWS_LOG = "\"__lines_db_moved_rows\"";
443
487
  /** Column alias a query reads a row's rowid under, next to its fields */
444
488
  const ROWID_ALIAS = "__lines_db_rowid";
445
489
  /** The fields a row given to an insert names, leaving out those it leaves undefined */
446
490
  function givenFields(row) {
447
491
  return Object.entries(row).filter(([, value]) => value !== void 0).map(([key]) => key);
448
492
  }
493
+ /** Whether two values read the same once written as JSON; a bigint reads as its digits, which JSON.stringify refuses */
494
+ function sameValue(a, b) {
495
+ const text = (value) => JSON.stringify(value, (_key, item) => typeof item === "bigint" ? String(item) : item);
496
+ return text(a) === text(b);
497
+ }
498
+ /** Whether a value is a bigint or holds one at any depth, which a JSONL line cannot hold */
499
+ function holdsBigint(value) {
500
+ if (typeof value === "bigint") return true;
501
+ if (Array.isArray(value)) return value.some(holdsBigint);
502
+ return value !== null && typeof value === "object" && Object.values(value).some(holdsBigint);
503
+ }
504
+ /**
505
+ * The values of a row given to an insert that the stored row holds differently, after the schema transformed
506
+ * them. A value holding a bigint is left out: a line cannot hold one, so the row keeps the value the schema
507
+ * made of it
508
+ */
509
+ function transformedInputs(given, stored) {
510
+ const inputs = new Map(Object.entries(given).filter(([key, value]) => value !== void 0 && !holdsBigint(value) && !sameValue(value, stored[key])).map(([key, value]) => [key, structuredClone(value)]));
511
+ return inputs.size > 0 ? inputs : void 0;
512
+ }
449
513
  /** Whether a value read from SQLite and one about to be stored are the same */
450
514
  function sameStoredValue(stored, next) {
451
515
  if (stored === null || stored === void 0 || next === null) return (stored ?? null) === next;
@@ -482,6 +546,18 @@ var LinesDB = class LinesDB {
482
546
  * back, also once the row's primary key changed and its line can no longer be found by it
483
547
  */
484
548
  linesWithUnknownFields = /* @__PURE__ */ new Map();
549
+ /**
550
+ * For a table without a primary key, where each row's line stands in its file: the rows cannot be
551
+ * matched to their lines by key, and by order only while none is added or removed
552
+ */
553
+ linePositionsByRowid = /* @__PURE__ */ new Map();
554
+ /**
555
+ * What happened to the positions of a table's rows since its rows were read for its write-back, in order: the
556
+ * positions that write-back computes describe the rows as they were, and are brought up to date with these
557
+ */
558
+ positionEdits = /* @__PURE__ */ new Map();
559
+ /** Whether the temporary table that triggers log the rowid changes of rows to exists */
560
+ movedRowsLogReady = false;
485
561
  /** Whether a transaction's callback has returned and its files are being written back */
486
562
  transactionClosing = false;
487
563
  /** Whether a transaction() call is past its guard but has not begun yet */
@@ -507,6 +583,8 @@ var LinesDB = class LinesDB {
507
583
  tablesFromGivenColumns = /* @__PURE__ */ new Set();
508
584
  /** Each table's schema file and a hash of its content as the tables were loaded, or '' for none */
509
585
  schemaFileStates = /* @__PURE__ */ new Map();
586
+ schemaImports;
587
+ schemaDependencyHashes = /* @__PURE__ */ new Map();
510
588
  constructor(config, dbPath) {
511
589
  this.config = config;
512
590
  this.db = createDatabase(dbPath ?? ":memory:");
@@ -562,13 +640,25 @@ var LinesDB = class LinesDB {
562
640
  const loadingTables = /* @__PURE__ */ new Set();
563
641
  const attemptedTables = /* @__PURE__ */ new Set();
564
642
  const allDeferredForeignKeys = [];
565
- for (const tableNameToLoad of tablesToLoad) if (!attemptedTables.has(tableNameToLoad)) {
566
- const tableTransform = tableNameToLoad === tableName ? transform : void 0;
567
- const { errors, warnings, rowCounts: tableRowCounts, deferredForeignKeys } = await this.loadTableWithDependencies(tableNameToLoad, loadedTables, loadingTables, attemptedTables, detailedValidate, tableTransform);
568
- allErrors.push(...errors);
569
- allWarnings.push(...warnings);
570
- allDeferredForeignKeys.push(...deferredForeignKeys);
571
- for (const [k, v] of tableRowCounts) allRowCounts.set(k, v);
643
+ const imports = createSchemaImports();
644
+ this.schemaImports = imports;
645
+ const schemaPaths = /* @__PURE__ */ new Map();
646
+ for (const [name, config] of this.tables) {
647
+ const schemaPath = await this.findTableSchemaFile(name, config);
648
+ if (schemaPath) schemaPaths.set(name, schemaPath);
649
+ }
650
+ try {
651
+ for (const tableNameToLoad of tablesToLoad) if (!attemptedTables.has(tableNameToLoad)) {
652
+ const tableTransform = tableNameToLoad === tableName ? transform : void 0;
653
+ const { errors, warnings, rowCounts: tableRowCounts, deferredForeignKeys } = await this.loadTableWithDependencies(tableNameToLoad, loadedTables, loadingTables, attemptedTables, detailedValidate, tableTransform);
654
+ allErrors.push(...errors);
655
+ allWarnings.push(...warnings);
656
+ allDeferredForeignKeys.push(...deferredForeignKeys);
657
+ for (const [k, v] of tableRowCounts) allRowCounts.set(k, v);
658
+ }
659
+ } finally {
660
+ this.schemaImports = void 0;
661
+ this.recordSchemaDependencies(imports, attemptedTables, schemaPaths, tableName === void 0);
572
662
  }
573
663
  if (detailedValidate && allDeferredForeignKeys.length > 0) for (const { tableName: tName, foreignKey: fk, filePath } of allDeferredForeignKeys) {
574
664
  if (!loadedTables.has(fk.references.table)) continue;
@@ -593,6 +683,9 @@ var LinesDB = class LinesDB {
593
683
  tableResults
594
684
  };
595
685
  }
686
+ importSchemaModule(schemaPath) {
687
+ return (this.schemaImports ?? createSchemaImports()).import(schemaPath);
688
+ }
596
689
  /**
597
690
  * Load a table and its dependencies recursively
598
691
  */
@@ -615,10 +708,9 @@ var LinesDB = class LinesDB {
615
708
  try {
616
709
  let foreignKeys;
617
710
  try {
618
- const { pathToFileURL } = await import("node:url");
619
711
  const schemaPath = await this.findTableSchemaFile(tableName, tableConfig);
620
712
  if (schemaPath) {
621
- const schemaModule = await import(`${pathToFileURL(schemaPath).href}?t=${Date.now()}`);
713
+ const schemaModule = await this.importSchemaModule(schemaPath);
622
714
  foreignKeys = (schemaModule.schema || schemaModule.default)?.foreignKeys || schemaModule.foreignKeys;
623
715
  }
624
716
  } catch {}
@@ -719,11 +811,10 @@ var LinesDB = class LinesDB {
719
811
  let validationSchema = config.validationSchema;
720
812
  const schemaMetadata = {};
721
813
  const schemaPath = config.validationSchema ? void 0 : await this.findTableSchemaFile(tableName, config);
722
- if (!validationSchema && schemaPath) validationSchema = await SchemaLoader.loadSchema(config.jsonlPath, dirname(schemaPath));
814
+ if (!validationSchema && schemaPath) validationSchema = await SchemaLoader.loadSchema(config.jsonlPath, dirname(schemaPath), this.schemaImports);
723
815
  if (!config.validationSchema) try {
724
- const { pathToFileURL } = await import("node:url");
725
816
  if (!schemaPath) throw new Error("Schema file not found");
726
- const schemaModule = await import(`${pathToFileURL(schemaPath).href}?t=${Date.now()}`);
817
+ const schemaModule = await this.importSchemaModule(schemaPath);
727
818
  const schemaExport = schemaModule.schema || schemaModule.default;
728
819
  if (schemaExport?.primaryKey) schemaMetadata.primaryKey = schemaExport.primaryKey;
729
820
  else if (schemaModule.primaryKey) schemaMetadata.primaryKey = schemaModule.primaryKey;
@@ -833,16 +924,26 @@ var LinesDB = class LinesDB {
833
924
  } else this.insertData(tableName, schema, validatedData);
834
925
  this.fieldChanges.delete(tableName);
835
926
  this.linesWithUnknownFields.delete(tableName);
927
+ this.linePositionsByRowid.delete(tableName);
928
+ if (this.tracksLinePositions(tableName)) {
929
+ this.logMovedRows(tableName);
930
+ const positions = /* @__PURE__ */ new Map();
931
+ this.rowidsInLineOrder(tableName, validatedData).forEach((rowid, index) => {
932
+ if (rowid !== void 0) positions.set(rowid, index);
933
+ });
934
+ this.linePositionsByRowid.set(tableName, positions);
935
+ }
836
936
  const columnNames = new Set(schema.columns.map((column) => column.name));
837
937
  const withUnknown = data.map((row) => Object.keys(row).some((key) => !columnNames.has(key)));
838
938
  if (transformedFields.some((fields) => fields.length > 0) || withUnknown.includes(true)) {
839
939
  const rowids = this.queryInternal(`SELECT rowid AS "${ROWID_ALIAS}" FROM ${this.quoteTableName(tableName)} ORDER BY rowid`);
840
940
  const lines = /* @__PURE__ */ new Map();
841
941
  const sourceIndexes = new Map(origins.map((origin, index) => [origin, index]));
942
+ const lineIndexes = new Map(this.rowidsInLineOrder(tableName, validatedData).map((rowid, index) => [rowid, index]));
842
943
  rowids.forEach((row, index) => {
843
944
  const rowid = row[ROWID_ALIAS];
844
945
  const origin = this.rowOriginsByRowid.get(tableName)?.get(String(rowid));
845
- const sourceIndex = origin ? sourceIndexes.get(origin) ?? index : index;
946
+ const sourceIndex = origin ? sourceIndexes.get(origin) ?? index : lineIndexes.get(String(rowid)) ?? index;
846
947
  const set = transformedFields[sourceIndex] ?? [];
847
948
  if (set.length > 0) this.noteFieldChanges(tableName, rowid, { set });
848
949
  if (withUnknown[sourceIndex]) lines.set(String(rowid), data[sourceIndex]);
@@ -1132,9 +1233,11 @@ var LinesDB = class LinesDB {
1132
1233
  try {
1133
1234
  return run();
1134
1235
  } finally {
1236
+ this.applyMovedRows();
1135
1237
  if (this.totalChanges() !== before) {
1136
1238
  for (const tableName of this.schemas.keys()) {
1137
1239
  this.rawSqlTables.add(tableName);
1240
+ this.linePositionsByRowid.delete(tableName);
1138
1241
  this.noteChange(tableName);
1139
1242
  }
1140
1243
  this.forgetLinesOfGoneRows(this.schemas.keys());
@@ -1311,8 +1414,10 @@ var LinesDB = class LinesDB {
1311
1414
  });
1312
1415
  this.rowOriginsByRowid.set(tableName, origins);
1313
1416
  }
1417
+ this.forgetPosition(tableName, String(result.lastInsertRowid));
1314
1418
  this.noteFieldChanges(tableName, result.lastInsertRowid, {
1315
1419
  set: givenFields(data),
1420
+ inputs: transformedInputs(data, row),
1316
1421
  inserted: true
1317
1422
  });
1318
1423
  this.afterWrite(tableName, result.changes);
@@ -1377,8 +1482,10 @@ var LinesDB = class LinesDB {
1377
1482
  undoSettle();
1378
1483
  throw error;
1379
1484
  }
1485
+ this.forgetPosition(tableName, String(result.lastInsertRowid));
1380
1486
  this.noteFieldChanges(tableName, result.lastInsertRowid, {
1381
1487
  set: givenFields(record),
1488
+ inputs: transformedInputs(record, row),
1382
1489
  inserted: true
1383
1490
  });
1384
1491
  totalChanges += BigInt(result.changes);
@@ -1408,44 +1515,58 @@ var LinesDB = class LinesDB {
1408
1515
  updateInternal(tableName, data, where, options) {
1409
1516
  this.assertMutable(tableName);
1410
1517
  if (!this.schemas.get(tableName)) throw new Error(`Table ${tableName} does not exist`);
1411
- const shouldValidate = options?.validate !== false;
1412
- const hasValidationSchema = this.validationSchemas.has(tableName);
1413
- if (shouldValidate && hasValidationSchema) {
1414
- const existingRows = this.findInternal(tableName, where);
1415
- for (const existingRow of existingRows) {
1416
- const mergedData = {
1417
- ...existingRow,
1418
- ...data
1419
- };
1420
- for (const field of options?.resetToDefault ?? []) delete mergedData[field];
1421
- this.validateData(tableName, mergedData);
1422
- }
1423
- }
1424
1518
  const { sql: whereSql, values: whereValues, functionFilters } = this.buildWhereClause(where, tableName);
1425
1519
  if (functionFilters.length > 0) throw new Error("Function filters are not supported in update operations");
1426
1520
  const targets = this.queryInternal(`SELECT rowid AS "${ROWID_ALIAS}", * FROM ${this.quoteTableName(tableName)} WHERE ${whereSql}`, whereValues);
1521
+ const shouldValidate = options?.validate !== false;
1522
+ const hasValidationSchema = this.validationSchemas.has(tableName);
1523
+ const givenKeys = Object.keys(data);
1427
1524
  const resetFields = options?.resetToDefault ?? [];
1525
+ const storedValues = targets.map((target) => {
1526
+ if (!shouldValidate || !hasValidationSchema) return data;
1527
+ const { [ROWID_ALIAS]: _rowid, ...stored } = target;
1528
+ const merged = {
1529
+ ...this.deserializeRow(tableName, stored),
1530
+ ...data
1531
+ };
1532
+ for (const field of resetFields) delete merged[field];
1533
+ const validated = this.validateAndTransform(tableName, merged);
1534
+ return Object.fromEntries(givenKeys.map((key) => [key, Object.hasOwn(validated, key) ? validated[key] : data[key]]));
1535
+ });
1428
1536
  const resets = resetFields.length > 0 ? this.computeResets(tableName, targets, data, resetFields) : [];
1429
1537
  let result = {
1430
1538
  changes: 0,
1431
1539
  lastInsertRowid: 0
1432
1540
  };
1433
- if (Object.keys(data).length > 0) {
1434
- const setClauses = Object.keys(data).map((key) => `${this.quoteIdentifier(key)} = ?`).join(", ");
1435
- const sql = `UPDATE ${this.quoteTableName(tableName)} SET ${setClauses} WHERE ${whereSql}`;
1436
- const values = [...Object.entries(data).map(([key, v]) => this.normalizeValue(v, this.columnOf(tableName, key))), ...whereValues];
1437
- const undoSettle = this.settleColumnsNoRowHolds(this.schemas.get(tableName), data);
1541
+ if (givenKeys.length > 0 && targets.length > 0) {
1542
+ const setClauses = givenKeys.map((key) => `${this.quoteIdentifier(key)} = ?`).join(", ");
1543
+ const sql = `UPDATE ${this.quoteTableName(tableName)} SET ${setClauses} WHERE rowid = ?`;
1544
+ const undoSettle = this.settleColumnsNoRowHolds(this.schemas.get(tableName), storedValues[0]);
1545
+ let changes = 0n;
1546
+ let lastInsertRowid = 0;
1547
+ this.db.exec("SAVEPOINT lines_db_update");
1438
1548
  try {
1439
- result = this.executeInternal(sql, values);
1549
+ targets.forEach((target, index) => {
1550
+ const written = this.executeInternal(sql, [...givenKeys.map((key) => this.normalizeValue(storedValues[index][key], this.columnOf(tableName, key))), target[ROWID_ALIAS]]);
1551
+ changes += BigInt(written.changes);
1552
+ lastInsertRowid = written.lastInsertRowid;
1553
+ });
1554
+ this.db.exec("RELEASE lines_db_update");
1440
1555
  } catch (error) {
1556
+ this.db.exec("ROLLBACK TO lines_db_update");
1557
+ this.db.exec("RELEASE lines_db_update");
1441
1558
  undoSettle();
1442
1559
  throw error;
1443
1560
  }
1444
- if (Number(result.changes) === 0) undoSettle();
1561
+ result = {
1562
+ changes: Number(changes),
1563
+ lastInsertRowid
1564
+ };
1565
+ if (changes === 0n) undoSettle();
1445
1566
  }
1446
1567
  const pkName = this.schemas.get(tableName)?.columns.find((col) => col.primaryKey)?.name;
1447
1568
  if (pkName && Object.hasOwn(data, pkName)) {
1448
- 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))]);
1569
+ const moved = this.queryInternal(`SELECT rowid AS "${ROWID_ALIAS}" FROM ${this.quoteTableName(tableName)} WHERE ${this.quoteIdentifier(pkName)} = ?`, [this.normalizeValue((storedValues[0] ?? data)[pkName], this.columnOf(tableName, pkName))]);
1449
1570
  if (targets.length === 1 && moved.length === 1) {
1450
1571
  const from = String(targets[0][ROWID_ALIAS]);
1451
1572
  const to = moved[0][ROWID_ALIAS];
@@ -1458,10 +1579,14 @@ var LinesDB = class LinesDB {
1458
1579
  }
1459
1580
  }
1460
1581
  }
1461
- for (const target of targets) {
1462
- const set = Object.keys(data).filter((key) => !sameStoredValue(target[key], this.normalizeValue(data[key], this.columnOf(tableName, key))));
1463
- this.noteFieldChanges(tableName, target[ROWID_ALIAS], { set });
1464
- }
1582
+ targets.forEach((target, index) => {
1583
+ const set = givenKeys.filter((key) => !sameStoredValue(target[key], this.normalizeValue(storedValues[index][key], this.columnOf(tableName, key))));
1584
+ const given = Object.fromEntries(set.map((key) => [key, data[key]]));
1585
+ this.noteFieldChanges(tableName, target[ROWID_ALIAS], {
1586
+ set,
1587
+ inputs: transformedInputs(given, storedValues[index])
1588
+ });
1589
+ });
1465
1590
  if (resets.length > 0) result = this.applyResets(tableName, resets, resetFields);
1466
1591
  this.afterWrite(tableName, result.changes);
1467
1592
  return result;
@@ -1815,9 +1940,18 @@ var LinesDB = class LinesDB {
1815
1940
  this.assertWritable(tableName);
1816
1941
  const config = this.tables.get(tableName);
1817
1942
  if (!config) throw new Error(`Table ${tableName} not found`);
1943
+ this.positionEdits.set(tableName, []);
1818
1944
  const stored = this.readStoredRows(tableName);
1819
- if (!this.hasSeveralDataDirs()) return [await this.prepareFileWriteBack(tableName, config.jsonlPath, stored, options)];
1820
- const origins = this.rowOriginsByRowid.get(tableName);
1945
+ const recorded = this.linePositionsByRowid.get(tableName);
1946
+ const atRead = {
1947
+ generation: this.changeGenerations.get(tableName) ?? 0,
1948
+ positions: recorded && new Map(recorded),
1949
+ origins: new Map(this.rowOriginsByRowid.get(tableName) ?? []),
1950
+ changes: cloneFieldChanges(/* @__PURE__ */ new Map([[tableName, this.fieldChanges.get(tableName) ?? /* @__PURE__ */ new Map()]])).get(tableName),
1951
+ unknownFieldLines: new Map(this.linesWithUnknownFields.get(tableName) ?? [])
1952
+ };
1953
+ if (!this.hasSeveralDataDirs()) return [await this.prepareFileWriteBack(tableName, config.jsonlPath, stored, options, atRead)];
1954
+ const origins = atRead.origins;
1821
1955
  const byFile = new Map([this.config.dataDir].flat().map((dir) => [join(dir, `${tableName}.jsonl`), []]));
1822
1956
  stored.rowids.forEach((rowid, index) => {
1823
1957
  const origin = origins?.get(rowid);
@@ -1834,33 +1968,98 @@ var LinesDB = class LinesDB {
1834
1968
  rows: indexes.map((i) => stored.rows[i]),
1835
1969
  lineRows: indexes.map((i) => stored.lineRows[i])
1836
1970
  };
1837
- const fileWrite = await this.prepareFileWriteBack(tableName, file, rows, options);
1971
+ const fileWrite = await this.prepareFileWriteBack(tableName, file, rows, options, atRead);
1838
1972
  if (!fileWrite.unchanged) prepared.push(fileWrite);
1839
1973
  }
1840
1974
  return prepared;
1841
1975
  }
1842
- async prepareFileWriteBack(tableName, jsonlPath, stored, options) {
1976
+ forgetPosition(tableName, rowid) {
1977
+ this.linePositionsByRowid.get(tableName)?.delete(rowid);
1978
+ this.positionEdits.get(tableName)?.push({ forget: rowid });
1979
+ }
1980
+ /**
1981
+ * The rowid of the row each line was loaded into, in the order of the lines. Not the rowid order: an INTEGER
1982
+ * PRIMARY KEY is the rowid, so the line `{"id":3}` first in its file is the row with rowid 3
1983
+ */
1984
+ rowidsInLineOrder(tableName, rows) {
1985
+ const pk = this.schemas.get(tableName)?.columns.find((column) => column.primaryKey);
1986
+ const stored = this.queryInternal(`SELECT rowid AS "${ROWID_ALIAS}" FROM ${this.quoteTableName(tableName)} ORDER BY rowid`).map((row) => String(row[ROWID_ALIAS]));
1987
+ if (pk?.type !== "INTEGER") return stored;
1988
+ const present = new Set(stored);
1989
+ let largest;
1990
+ return rows.map((row) => {
1991
+ const key = row[pk.name];
1992
+ const rowid = key === void 0 || key === null ? (largest ?? 0) + 1 : Number(key);
1993
+ largest = largest === void 0 ? rowid : Math.max(largest, rowid);
1994
+ return present.has(String(rowid)) ? String(rowid) : void 0;
1995
+ });
1996
+ }
1997
+ /**
1998
+ * Log each change of a row's rowid in the table: a foreign-key action or raw SQL can change an INTEGER PRIMARY
1999
+ * KEY, which is the rowid, without a write through this database telling it which row moved
2000
+ */
2001
+ logMovedRows(tableName) {
2002
+ if (!this.movedRowsLogReady) {
2003
+ this.db.exec(`CREATE TEMP TABLE IF NOT EXISTS ${MOVED_ROWS_LOG} (tbl TEXT, old INTEGER, new INTEGER)`);
2004
+ this.movedRowsLogReady = true;
2005
+ }
2006
+ const trigger = this.quoteIdentifier(`__lines_db_moved_${tableName}`);
2007
+ const name = `'${tableName.replace(/'/g, "''")}'`;
2008
+ this.db.exec(`CREATE TEMP TRIGGER IF NOT EXISTS ${trigger} AFTER UPDATE ON main.${this.quoteTableName(tableName)} WHEN old.rowid IS NOT new.rowid BEGIN INSERT INTO ${MOVED_ROWS_LOG} VALUES (${name}, old.rowid, new.rowid); END`);
2009
+ }
2010
+ /** Move what is kept by rowid to the rowid each logged row moved to, in the order the rows moved */
2011
+ applyMovedRows() {
2012
+ if (!this.movedRowsLogReady) return;
2013
+ const moved = this.queryInternal(`SELECT tbl, old, new FROM ${MOVED_ROWS_LOG} ORDER BY rowid`);
2014
+ if (moved.length === 0) return;
2015
+ this.db.exec(`DELETE FROM ${MOVED_ROWS_LOG}`);
2016
+ for (const { tbl, old, new: to } of moved) this.moveRowMetadata(String(tbl), String(old), String(to));
2017
+ }
2018
+ /**
2019
+ * Whether the lines of a table are remembered by position, so a row whose key changed, or that has none, is
2020
+ * found again by where its line stood. Several data directories have the origin of each row instead
2021
+ */
2022
+ tracksLinePositions(_tableName) {
2023
+ return !this.hasSeveralDataDirs();
2024
+ }
2025
+ hasNoPrimaryKey(tableName) {
2026
+ return this.schemas.get(tableName)?.columns.some((column) => column.primaryKey) === false;
2027
+ }
2028
+ async prepareFileWriteBack(tableName, jsonlPath, stored, options, atRead) {
1843
2029
  const { rowids, rows: deserializedRows, lineRows } = stored;
1844
- const generation = this.changeGenerations.get(tableName) ?? 0;
2030
+ const generation = atRead?.generation ?? this.changeGenerations.get(tableName) ?? 0;
1845
2031
  let finalRows = lineRows;
1846
2032
  const previousContent = await readFile(jsonlPath, "utf-8").catch((error) => {
1847
2033
  if (error.code === "ENOENT") return void 0;
1848
2034
  throw error;
1849
2035
  });
1850
2036
  const existingRows = await this.readUnchangedRows(jsonlPath);
1851
- const matches = this.hasSeveralDataDirs() ? rowids.map((rowid) => existingRows[this.rowOriginsByRowid.get(tableName).get(rowid).rowIndex]) : void 0;
2037
+ const origins = atRead?.origins ?? this.rowOriginsByRowid.get(tableName);
2038
+ const matchedByOrigin = this.hasSeveralDataDirs() ? rowids.map((rowid) => {
2039
+ const origin = origins?.get(rowid);
2040
+ return origin && existingRows[origin.rowIndex];
2041
+ }) : void 0;
2042
+ const byPosition = matchedByOrigin ? void 0 : linesByPosition(atRead?.positions, rowids, existingRows);
2043
+ const matches = matchedByOrigin ?? (this.hasNoPrimaryKey(tableName) ? byPosition : void 0);
2044
+ const positionedLines = matches ? void 0 : byPosition;
1852
2045
  const fields = options?.fields ?? this.config.writeBackFields;
1853
- if ((options?.writeFilledValues ?? this.config.writeFilledValues ?? "all") === "primaryKey") finalRows = this.keepWrittenFields(tableName, rowids, deserializedRows, finalRows, existingRows, fields, matches).map(({ written }) => written);
2046
+ if ((options?.writeFilledValues ?? this.config.writeFilledValues ?? "all") === "primaryKey") finalRows = this.keepWrittenFields(tableName, rowids, deserializedRows, finalRows, existingRows, fields, matches, {
2047
+ positionedLines,
2048
+ changes: atRead?.changes
2049
+ }).map(({ written }) => written);
1854
2050
  const columns = new Set(this.schemas.get(tableName)?.columns.map((column) => column.name));
1855
- const readLines = this.linesWithUnknownFields.get(tableName);
2051
+ const readLines = atRead?.unknownFieldLines ?? this.linesWithUnknownFields.get(tableName);
1856
2052
  finalRows = finalRows.map((row, index) => {
1857
2053
  const line = readLines?.get(rowids[index]);
1858
2054
  return line ? keepUnknownFields(line, row, columns) : row;
1859
2055
  });
2056
+ let linesOfRows;
1860
2057
  finalRows = this.mergeWithExistingLines(tableName, existingRows, finalRows, {
1861
2058
  fields,
1862
2059
  strictFields: options?.strictFields ?? false,
1863
- matches
2060
+ matches,
2061
+ positionedLines,
2062
+ onMatched: (lines) => linesOfRows = lines
1864
2063
  });
1865
2064
  return {
1866
2065
  tableName,
@@ -1868,10 +2067,11 @@ var LinesDB = class LinesDB {
1868
2067
  rows: finalRows,
1869
2068
  previousContent,
1870
2069
  generation,
1871
- ...matches ? {
2070
+ ...matchedByOrigin ? {
1872
2071
  rowids,
1873
2072
  unchanged: JsonlWriter.serialize(existingRows) === JsonlWriter.serialize(finalRows)
1874
- } : {}
2073
+ } : {},
2074
+ ...this.tracksLinePositions(tableName) && !matchedByOrigin ? { positions: linesOfRows ? positionsAfterWrite(rowids, linesOfRows, existingRows) : new Map(rowids.map((rowid, position) => [rowid, position])) } : {}
1875
2075
  };
1876
2076
  }
1877
2077
  /**
@@ -1894,17 +2094,22 @@ var LinesDB = class LinesDB {
1894
2094
  * minus those reset to their default - its primary key and the fields named to be written back, so
1895
2095
  * a value the schema fills in stays out of the file
1896
2096
  */
1897
- keepWrittenFields(tableName, rowids, rows, lineRows, existingRows, namedFields = [], matchedLines) {
2097
+ keepWrittenFields(tableName, rowids, rows, lineRows, existingRows, namedFields = [], matchedLines, options) {
1898
2098
  const pkName = this.schemas.get(tableName)?.columns.find((col) => col.primaryKey)?.name;
1899
- const actionColumns = (this.schemas.get(tableName)?.foreignKeys ?? []).filter((fk) => [fk.onDelete, fk.onUpdate].some((action) => action === "CASCADE" || action === "SET NULL")).map((fk) => fk.column);
1900
- const lines = matchedLines ?? this.matchExistingRows(tableName, lineRows, existingRows, { required: false });
1901
- const changes = this.fieldChanges.get(tableName);
2099
+ const actionColumns = options?.ignoreActions ? [] : (this.schemas.get(tableName)?.foreignKeys ?? []).filter((fk) => [fk.onDelete, fk.onUpdate].some((action) => action === "CASCADE" || action === "SET NULL")).map((fk) => fk.column);
2100
+ const lines = matchedLines ?? this.matchExistingRows(tableName, lineRows, existingRows, {
2101
+ required: false,
2102
+ byOutputKey: true,
2103
+ positionedLines: options?.positionedLines
2104
+ });
2105
+ const changes = options?.changes ?? this.fieldChanges.get(tableName);
1902
2106
  return lineRows.map((lineRow, index) => {
1903
2107
  const line = lines?.[index];
1904
2108
  const rowChanges = changes?.get(rowids[index]);
1905
2109
  if (Object.keys(lineRow).some((key) => !Object.hasOwn(rows[index], key)) || this.rawSqlTables.has(tableName) || !line && !rowChanges?.inserted) return {
1906
2110
  written: lineRow,
1907
- narrowed: false
2111
+ narrowed: false,
2112
+ line
1908
2113
  };
1909
2114
  const keep = /* @__PURE__ */ new Set([
1910
2115
  ...Object.keys(line ?? {}),
@@ -1914,10 +2119,11 @@ var LinesDB = class LinesDB {
1914
2119
  for (const key of rowChanges?.reset ?? []) keep.delete(key);
1915
2120
  for (const key of namedFields) keep.add(key);
1916
2121
  if (pkName) keep.add(pkName);
1917
- const untouched = line !== void 0 && !rowChanges?.inserted && !rowChanges?.set.size && !rowChanges?.reset.size;
2122
+ const untouched = (key) => line !== void 0 && !rowChanges?.inserted && Object.hasOwn(line, key) && !rowChanges?.set.has(key) && !rowChanges?.reset.has(key);
1918
2123
  return {
1919
- 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])),
1920
- narrowed: true
2124
+ written: Object.fromEntries(Object.entries(lineRow).filter(([key]) => keep.has(key)).map(([key, value]) => [key, untouched(key) && !actionColumns.includes(key) && !namedFields.includes(key) ? line[key] : rowChanges?.inputs?.has(key) && !actionColumns.includes(key) && !namedFields.includes(key) ? rowChanges.inputs.get(key) : value])),
2125
+ narrowed: true,
2126
+ line
1921
2127
  };
1922
2128
  });
1923
2129
  }
@@ -1929,10 +2135,15 @@ var LinesDB = class LinesDB {
1929
2135
  * later, which must not inherit them
1930
2136
  */
1931
2137
  moveRowMetadata(tableName, from, to) {
2138
+ this.positionEdits.get(tableName)?.push({
2139
+ from,
2140
+ to
2141
+ });
1932
2142
  for (const byRow of [
1933
2143
  this.fieldChanges.get(tableName),
1934
2144
  this.linesWithUnknownFields.get(tableName),
1935
- this.rowOriginsByRowid.get(tableName)
2145
+ this.rowOriginsByRowid.get(tableName),
2146
+ this.linePositionsByRowid.get(tableName)
1936
2147
  ]) {
1937
2148
  const kept = byRow?.get(from);
1938
2149
  if (!byRow || kept === void 0) continue;
@@ -1957,6 +2168,7 @@ var LinesDB = class LinesDB {
1957
2168
  }
1958
2169
  forgetFieldChanges(tableName, rowids) {
1959
2170
  for (const rowid of rowids) {
2171
+ this.forgetPosition(tableName, rowid);
1960
2172
  this.fieldChanges.get(tableName)?.delete(rowid);
1961
2173
  this.linesWithUnknownFields.get(tableName)?.delete(rowid);
1962
2174
  }
@@ -1976,10 +2188,16 @@ var LinesDB = class LinesDB {
1976
2188
  for (const key of changes.set ?? []) {
1977
2189
  rowChanges.set.add(key);
1978
2190
  rowChanges.reset.delete(key);
2191
+ rowChanges.inputs?.delete(key);
1979
2192
  }
1980
2193
  for (const key of changes.reset ?? []) {
1981
2194
  rowChanges.reset.add(key);
1982
2195
  rowChanges.set.delete(key);
2196
+ rowChanges.inputs?.delete(key);
2197
+ }
2198
+ for (const [key, value] of changes.inputs ?? []) {
2199
+ rowChanges.inputs ??= /* @__PURE__ */ new Map();
2200
+ rowChanges.inputs.set(key, value);
1983
2201
  }
1984
2202
  byRow.set(String(rowid), rowChanges);
1985
2203
  this.fieldChanges.set(tableName, byRow);
@@ -2020,25 +2238,49 @@ var LinesDB = class LinesDB {
2020
2238
  }
2021
2239
  /**
2022
2240
  * Every row of a table with the fields the schema filled in rather than the file: the ones its line
2023
- * does not hold and no write set, which a write-back leaves out of the file
2241
+ * does not hold and no write set, which a write-back leaves out of the file. `input` is the row as
2242
+ * its line holds it - the values before the schema transformed them, without the defaulted fields.
2024
2243
  */
2025
2244
  async findWithDefaults(tableName) {
2026
2245
  try {
2027
2246
  const tableConfig = this.tables.get(tableName);
2028
2247
  if (!tableConfig || !this.schemas.has(tableName)) throw new Error(`Table '${tableName}' is not loaded`);
2029
- await this.waitForPendingSyncs();
2030
- const { rowids, rows, lineRows } = this.readStoredRows(tableName);
2031
- const fileRows = /* @__PURE__ */ new Map();
2032
- 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));
2248
+ let stored;
2249
+ let positionsAtRead;
2250
+ let fileRows;
2251
+ for (let attempt = 1;; attempt++) {
2252
+ await this.waitForPendingSyncs();
2253
+ const files = this.hasSeveralDataDirs() ? [.../* @__PURE__ */ new Set([...tableConfig.jsonlPaths ?? [tableConfig.jsonlPath], ...[...this.rowOriginsByRowid.get(tableName)?.values() ?? []].map((origin) => origin.file)])] : [tableConfig.jsonlPath];
2254
+ const generation = this.changeGenerations.get(tableName) ?? 0;
2255
+ const hashes = files.map((file) => this.fileHashes.get(file));
2256
+ stored = this.readStoredRows(tableName);
2257
+ const recorded = this.linePositionsByRowid.get(tableName);
2258
+ positionsAtRead = recorded && new Map(recorded);
2259
+ fileRows = /* @__PURE__ */ new Map();
2260
+ const unchanged = () => (this.changeGenerations.get(tableName) ?? 0) === generation && files.every((file, index) => this.fileHashes.get(file) === hashes[index]);
2261
+ try {
2262
+ for (const file of files) fileRows.set(file, await this.readUnchangedRows(file));
2263
+ } catch (error) {
2264
+ if (!(error instanceof Error && error.name === "JsonlConflictError") || unchanged()) throw error;
2265
+ }
2266
+ if (unchanged()) break;
2267
+ if (attempt >= 5) throw new Error(`The rows of '${tableName}' kept changing while they were read; read them again`);
2268
+ }
2269
+ const { rowids, rows, lineRows } = stored;
2033
2270
  const existingRows = [...fileRows.values()].flat();
2034
2271
  const matches = this.hasSeveralDataDirs() && this.config.writeDataSets ? rowids.map((rowid) => {
2035
2272
  const origin = this.rowOriginsByRowid.get(tableName)?.get(rowid);
2036
2273
  return origin && fileRows.get(origin.file)?.[origin.rowIndex];
2037
- }) : void 0;
2274
+ }) : linesByPosition(positionsAtRead, rowids, existingRows);
2038
2275
  const kept = this.keepWrittenFields(tableName, rowids, rows, lineRows, existingRows, this.config.writeBackFields, matches);
2276
+ const lines = this.keepWrittenFields(tableName, rowids, rows, lineRows, existingRows, [], matches, { ignoreActions: true });
2039
2277
  return ok(rows.map((row, index) => ({
2040
2278
  row,
2041
- defaulted: kept[index].narrowed ? Object.keys(row).filter((key) => !Object.hasOwn(kept[index].written, key)) : []
2279
+ defaulted: kept[index].narrowed ? Object.keys(row).filter((key) => !Object.hasOwn(kept[index].written, key)) : [],
2280
+ input: {
2281
+ ...lines[index].written,
2282
+ ...Object.fromEntries(Object.entries(lines[index].line ?? {}).filter(([key]) => !Object.hasOwn(lines[index].written, key) && !Object.hasOwn(row, key)))
2283
+ }
2042
2284
  })));
2043
2285
  } catch (error) {
2044
2286
  return err(toError(error));
@@ -2058,6 +2300,7 @@ var LinesDB = class LinesDB {
2058
2300
  * tables it changed once its callback is done
2059
2301
  */
2060
2302
  afterWrite(tableName, changes) {
2303
+ this.applyMovedRows();
2061
2304
  if (BigInt(changes) === 0n && this.transactionChanges) return;
2062
2305
  const tableNames = [tableName, ...this.tablesChangedByForeignKeyActions(tableName)];
2063
2306
  this.forgetLinesOfGoneRows(tableNames);
@@ -2111,17 +2354,20 @@ var LinesDB = class LinesDB {
2111
2354
  } catch (error) {
2112
2355
  throw await this.restoreAll(written, error);
2113
2356
  }
2114
- for (const { tableName, jsonlPath, generation, rowids } of written) {
2357
+ for (const { tableName, jsonlPath, generation, rowids, positions } of written) {
2358
+ const edits = this.positionEdits.get(tableName) ?? [];
2359
+ if (positions) this.linePositionsByRowid.set(tableName, replayEdits(positions, edits));
2115
2360
  if ((this.changeGenerations.get(tableName) ?? 0) === generation) {
2116
2361
  this.fieldChanges.delete(tableName);
2117
2362
  this.rawSqlTables.delete(tableName);
2118
2363
  }
2119
2364
  if (rowids) {
2120
2365
  const origins = this.rowOriginsByRowid.get(tableName);
2121
- rowids.forEach((rowid, rowIndex) => origins.set(rowid, {
2366
+ const writtenOrigins = new Map(rowids.map((rowid, rowIndex) => [rowid, {
2122
2367
  file: jsonlPath,
2123
2368
  rowIndex
2124
- }));
2369
+ }]));
2370
+ for (const [rowid, origin] of replayEdits(writtenOrigins, edits)) origins.set(rowid, origin);
2125
2371
  if (!this.scannedJsonlFiles.includes(jsonlPath)) this.scannedJsonlFiles.push(jsonlPath);
2126
2372
  }
2127
2373
  }
@@ -2189,7 +2435,11 @@ var LinesDB = class LinesDB {
2189
2435
  const unknownFields = fields.filter((field) => !tableFields.includes(field));
2190
2436
  throw new Error(`Cannot write back field(s) [${unknownFields.join(", ")}] for table '${tableName}': no such field in the rows written back to the file.`);
2191
2437
  }
2192
- const existing = options.matches ?? this.matchExistingRows(tableName, rows, existingRows, { required: fields !== void 0 });
2438
+ const existing = options.matches ?? this.matchExistingRows(tableName, rows, existingRows, {
2439
+ required: fields !== void 0,
2440
+ positionedLines: options.positionedLines
2441
+ });
2442
+ options.onMatched?.(existing);
2193
2443
  if (!existing) return rows;
2194
2444
  const rowByLine = /* @__PURE__ */ new Map();
2195
2445
  const newRows = [];
@@ -2207,20 +2457,41 @@ var LinesDB = class LinesDB {
2207
2457
  }), ...newRows];
2208
2458
  }
2209
2459
  /**
2460
+ * The primary key the schema makes of a line, which is how the stored rows hold it. The line's own key
2461
+ * when the rows are in the line's terms (a `backward` transformation maps them back), when there is no
2462
+ * schema, or when the schema refuses the line
2463
+ */
2464
+ outputKeyOfLine(tableName, line, pkName) {
2465
+ const schema = this.validationSchemas.get(tableName);
2466
+ if (!schema || hasBackward(schema) || line[pkName] === void 0 || line[pkName] === null) return line[pkName];
2467
+ try {
2468
+ return this.validateAndTransform(tableName, line)[pkName] ?? line[pkName];
2469
+ } catch {
2470
+ return line[pkName];
2471
+ }
2472
+ }
2473
+ /**
2210
2474
  * Pair each row with the JSONL line it came from, indexed the same way as `rows`.
2211
2475
  * Returns undefined when the rows cannot be matched and the caller can do without it.
2212
2476
  */
2213
2477
  matchExistingRows(tableName, rows, existingRows, options) {
2214
2478
  if (existingRows.length === 0) return rows.map(() => void 0);
2215
2479
  const pkName = this.schemas.get(tableName)?.columns.find((col) => col.primaryKey)?.name;
2216
- const pkValues = pkName ? existingRows.map((row) => row[pkName]) : [];
2480
+ if (pkName && options.positionedLines?.every((line) => line !== void 0)) return options.positionedLines;
2481
+ const pkValues = pkName ? existingRows.map((row) => options.byOutputKey ? this.outputKeyOfLine(tableName, row, pkName) : row[pkName]) : [];
2217
2482
  if (pkName !== void 0 && pkValues.every((value) => value !== void 0 && value !== null) && new Set(pkValues.map((value) => String(value))).size === pkValues.length) {
2218
2483
  const byPk = new Map(existingRows.map((row, index) => [String(pkValues[index]), row]));
2219
- return rows.map((row) => {
2484
+ const positioned = options.positionedLines;
2485
+ const claimed = new Set(positioned?.filter((line) => line !== void 0));
2486
+ return rows.map((row, index) => {
2487
+ const byPosition = positioned?.[index];
2488
+ if (byPosition) return byPosition;
2220
2489
  const pkValue = row[pkName];
2221
- return pkValue === void 0 || pkValue === null ? void 0 : byPk.get(String(pkValue));
2490
+ const byKey = pkValue === void 0 || pkValue === null ? void 0 : byPk.get(String(pkValue));
2491
+ return byKey && !claimed.has(byKey) ? byKey : void 0;
2222
2492
  });
2223
2493
  }
2494
+ if (options.positionedLines) return options.positionedLines;
2224
2495
  if (rows.length !== existingRows.length) {
2225
2496
  if (!options.required) return;
2226
2497
  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.`);
@@ -2263,7 +2534,8 @@ var LinesDB = class LinesDB {
2263
2534
  }
2264
2535
  /**
2265
2536
  * The files that changed since this database last read or wrote them, as {@link hasExternalChanges}
2266
- * tells: each JSONL file edited, added or removed, and each schema file edited, added or removed
2537
+ * tells: each JSONL file edited, added or removed, each schema file edited, added or removed, and each
2538
+ * project file a schema imports edited, added or removed
2267
2539
  */
2268
2540
  async findExternalChanges() {
2269
2541
  try {
@@ -2282,6 +2554,16 @@ var LinesDB = class LinesDB {
2282
2554
  });
2283
2555
  if (content === void 0 || hashJsonlContent(content) !== knownHash) changed.add(file);
2284
2556
  }
2557
+ const knownHashes = /* @__PURE__ */ new Map();
2558
+ for (const files of this.schemaDependencyHashes.values()) for (const [file, knownHash] of files) knownHashes.set(file, (knownHashes.get(file) ?? /* @__PURE__ */ new Set()).add(knownHash));
2559
+ for (const [file, hashes] of knownHashes) {
2560
+ const content = await readFile(file).catch((error) => {
2561
+ if (error.code === "ENOENT") return void 0;
2562
+ throw error;
2563
+ });
2564
+ const current = content === void 0 ? MISSING_HASH : hashContent(content);
2565
+ if ([...hashes].some((hash) => hash !== current)) changed.add(file);
2566
+ }
2285
2567
  const tables = await DirectoryScanner.scanDirectory(this.config.dataDir);
2286
2568
  const scanned = new Set(listJsonlFiles(tables));
2287
2569
  for (const file of this.scannedJsonlFiles) if (!scanned.has(file)) changed.add(file);
@@ -2304,6 +2586,25 @@ var LinesDB = class LinesDB {
2304
2586
  });
2305
2587
  return content === void 0 ? "" : `${schemaPath}\0${hashJsonlContent(content)}`;
2306
2588
  }
2589
+ recordSchemaDependencies(imports, tableNames, schemaPaths, replace) {
2590
+ if (replace) {
2591
+ for (const name of this.schemaDependencyHashes.keys()) if (!schemaPaths.has(name)) this.schemaDependencyHashes.delete(name);
2592
+ }
2593
+ for (const name of tableNames) {
2594
+ const schemaPath = schemaPaths.get(name);
2595
+ if (schemaPath) this.schemaDependencyHashes.set(name, imports.dependencies(schemaPath));
2596
+ else this.schemaDependencyHashes.delete(name);
2597
+ }
2598
+ }
2599
+ /**
2600
+ * The project files the schemas import, as paths: not the schema files, and not a package from
2601
+ * node_modules. Those of one table when it is given. An edit to one of them is among
2602
+ * {@link findExternalChanges}
2603
+ */
2604
+ listSchemaDependencies(tableName) {
2605
+ const tables = tableName === void 0 ? [...this.schemaDependencyHashes.values()] : [this.schemaDependencyHashes.get(tableName) ?? /* @__PURE__ */ new Map()];
2606
+ return [...new Set(tables.flatMap((files) => [...files.keys()]))];
2607
+ }
2307
2608
  async schemaFileState(tableName, config) {
2308
2609
  if (config.validationSchema) return "";
2309
2610
  const schemaPath = await this.findTableSchemaFile(tableName, config);
@@ -2352,6 +2653,7 @@ var LinesDB = class LinesDB {
2352
2653
  let fieldChangesBefore;
2353
2654
  let rawSqlTablesBefore;
2354
2655
  let linesWithUnknownFieldsBefore;
2656
+ let linePositionsBefore;
2355
2657
  let originsBefore;
2356
2658
  let columnsBefore;
2357
2659
  const scannedBefore = [...this.scannedJsonlFiles];
@@ -2363,6 +2665,7 @@ var LinesDB = class LinesDB {
2363
2665
  fieldChangesBefore = cloneFieldChanges(this.fieldChanges);
2364
2666
  rawSqlTablesBefore = new Set(this.rawSqlTables);
2365
2667
  linesWithUnknownFieldsBefore = new Map(Array.from(this.linesWithUnknownFields, ([tableName, lines]) => [tableName, new Map(lines)]));
2668
+ linePositionsBefore = new Map(Array.from(this.linePositionsByRowid, ([tableName, positions]) => [tableName, new Map(positions)]));
2366
2669
  this.db.exec("BEGIN TRANSACTION");
2367
2670
  this.settleUndos = [];
2368
2671
  this.inTransaction = true;
@@ -2393,6 +2696,7 @@ var LinesDB = class LinesDB {
2393
2696
  if (fieldChangesBefore) this.fieldChanges = fieldChangesBefore;
2394
2697
  if (rawSqlTablesBefore) this.rawSqlTables = rawSqlTablesBefore;
2395
2698
  if (linesWithUnknownFieldsBefore) this.linesWithUnknownFields = linesWithUnknownFieldsBefore;
2699
+ if (linePositionsBefore) this.linePositionsByRowid = linePositionsBefore;
2396
2700
  const failure = await this.restoreAll(written, error);
2397
2701
  if (this.inTransaction) try {
2398
2702
  this.db.exec("ROLLBACK");
@@ -2520,13 +2824,14 @@ async function fillFieldsInternal(options) {
2520
2824
  const loadFiller = options.loadFiller ?? fillerFromValidationSchema;
2521
2825
  const tablesWithoutSchema = [];
2522
2826
  const tables = [];
2827
+ const imports = createSchemaImports();
2523
2828
  for (const { table, file, target, schemaDir } of sources.values()) {
2524
2829
  const schemaPath = await findSchemaFile(schemaDir, table);
2525
2830
  if (!schemaPath) {
2526
2831
  if (!tablesWithoutSchema.includes(table)) tablesWithoutSchema.push(table);
2527
2832
  continue;
2528
2833
  }
2529
- const schemaModule = await import(`${pathToFileURL(schemaPath).href}?t=${Date.now()}`);
2834
+ const schemaModule = await imports.import(schemaPath);
2530
2835
  tables.push({
2531
2836
  table,
2532
2837
  file,