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/bin/cli.mjs CHANGED
@@ -1,11 +1,13 @@
1
1
  #!/usr/bin/env node
2
+ import * as nodeModule from "node:module";
2
3
  import { createRequire, register } from "node:module";
3
4
  import * as l from "loculus";
4
5
  import { _rawValidate, _resolveIssue, _typeIssue, config } from "loculus";
5
6
  import { access, chmod, link, mkdir, readFile, readdir, realpath, rename, rm, stat, writeFile } from "node:fs/promises";
6
7
  import { basename, dirname, extname, isAbsolute, join, normalize, relative, resolve } from "node:path";
7
8
  import { createHash, randomBytes } from "node:crypto";
8
- import { pathToFileURL } from "node:url";
9
+ import { existsSync, readFileSync, realpathSync } from "node:fs";
10
+ import { fileURLToPath, pathToFileURL } from "node:url";
9
11
  import { styleText } from "node:util";
10
12
  import { arg, defineCommand, runMain } from "@politty/loculus";
11
13
  import { runInNewContext } from "node:vm";
@@ -438,6 +440,199 @@ async function replaceFile(file, write, expected) {
438
440
  if (!moved) await rm(temporary, { force: true }).catch(() => {});
439
441
  }
440
442
  }
443
+ // src/schema-module.ts
444
+ const VERSION_PARAM = "linesDbV";
445
+ const SHARED = Symbol.for("lines-db:schema-imports:1");
446
+ let counter = 0;
447
+ const shared = globalThis[SHARED] ??= {
448
+ graph: /* @__PURE__ */ new Map(),
449
+ evaluated: /* @__PURE__ */ new Map(),
450
+ evaluatedUrls: /* @__PURE__ */ new Set(),
451
+ versions: /* @__PURE__ */ new Map(),
452
+ hashes: /* @__PURE__ */ new Map(),
453
+ salt: "",
454
+ hooked: false
455
+ };
456
+ shared.evaluated ??= /* @__PURE__ */ new Map();
457
+ shared.evaluatedUrls ??= /* @__PURE__ */ new Set();
458
+ const packageRoots = /* @__PURE__ */ new Map();
459
+ function hashOf(parts) {
460
+ const hash = createHash("sha1");
461
+ for (const part of parts) hash.update(part).update("\0");
462
+ return hash.digest("hex");
463
+ }
464
+ function contentOf(file) {
465
+ try {
466
+ return readFileSync(file);
467
+ } catch {
468
+ return;
469
+ }
470
+ }
471
+ function hashContent(content) {
472
+ return createHash("sha1").update(content).digest("hex");
473
+ }
474
+ /** What a file that is not there holds: not a hash, so that no file can have it */
475
+ const MISSING_HASH = "missing";
476
+ function hashOfFile(file) {
477
+ const content = contentOf(file);
478
+ return content === void 0 ? MISSING_HASH : hashContent(content);
479
+ }
480
+ /**
481
+ * What the file is, with what it imports: a file evaluated again only when it or a file it imports changed,
482
+ * as a URL that names the version is one module for as long as the version stays. An import not recorded
483
+ * yet is not in the version. A file importing itself through others is taken by its own content there, so
484
+ * a version that was cut by a cycle is kept only for the file the count started from, which holds all of it
485
+ */
486
+ function versionOf(file, visiting = /* @__PURE__ */ new Set()) {
487
+ const known = shared.versions.get(file);
488
+ if (known) return {
489
+ version: known,
490
+ whole: true
491
+ };
492
+ const content = hashOfFile(file);
493
+ if (!shared.hashes.has(file)) shared.hashes.set(file, content);
494
+ if (visiting.has(file)) return {
495
+ version: hashOf([shared.salt, content]),
496
+ whole: false
497
+ };
498
+ visiting.add(file);
499
+ let whole = true;
500
+ const versions = [];
501
+ for (const imported of [...shared.graph.get(file) ?? []].sort()) {
502
+ const importedVersion = versionOf(imported, visiting);
503
+ versions.push(importedVersion.version);
504
+ whole &&= importedVersion.whole;
505
+ }
506
+ visiting.delete(file);
507
+ const version = hashOf([
508
+ shared.salt,
509
+ content,
510
+ ...versions
511
+ ]);
512
+ if (whole || visiting.size === 0) shared.versions.set(file, version);
513
+ return {
514
+ version,
515
+ whole
516
+ };
517
+ }
518
+ function packageRootOf(file) {
519
+ const start = dirname(file);
520
+ const cached = packageRoots.get(start);
521
+ if (cached !== void 0) return cached;
522
+ let dir = start;
523
+ let root = "";
524
+ for (;;) {
525
+ if (existsSync(join(dir, "package.json"))) {
526
+ root = dir;
527
+ break;
528
+ }
529
+ const parent = dirname(dir);
530
+ if (parent === dir) break;
531
+ dir = parent;
532
+ }
533
+ packageRoots.set(start, root);
534
+ return root;
535
+ }
536
+ /**
537
+ * A file imported under a URL not seen before is evaluated, and imports again what it imports: what an earlier
538
+ * evaluation of it imported is dropped here, as a file that no longer imports anything resolves nothing to
539
+ * replace it. A URL seen before is a module already evaluated, whose imports stay
540
+ */
541
+ function startEvaluation(file, url) {
542
+ if (shared.evaluatedUrls.has(url)) return;
543
+ shared.evaluatedUrls.add(url);
544
+ shared.graph.set(file, /* @__PURE__ */ new Set());
545
+ shared.evaluated.set(file, url);
546
+ }
547
+ /** Records the import of a file by a file that is read with versions; false for a file that is not one of the project */
548
+ function recordImport(parentURL, imported) {
549
+ if (!new URL(parentURL).searchParams.has(VERSION_PARAM)) return false;
550
+ const parent = fileURLToPath(parentURL);
551
+ if (packageRootOf(imported) !== packageRootOf(parent)) return false;
552
+ let imports = shared.graph.get(parent);
553
+ if (!imports || shared.evaluated.get(parent) !== parentURL) {
554
+ imports = /* @__PURE__ */ new Set();
555
+ shared.graph.set(parent, imports);
556
+ shared.evaluated.set(parent, parentURL);
557
+ }
558
+ imports.add(imported);
559
+ versionOf(imported);
560
+ return true;
561
+ }
562
+ function hookImports() {
563
+ if (shared.hooked) return true;
564
+ if (typeof nodeModule.registerHooks !== "function") return false;
565
+ nodeModule.registerHooks({ resolve(specifier, context, nextResolve) {
566
+ let resolved;
567
+ try {
568
+ resolved = nextResolve(specifier, context);
569
+ } catch (error) {
570
+ if (error.code === "ERR_MODULE_NOT_FOUND" && /^\.\.?\//.test(specifier)) {
571
+ const missing = context.parentURL?.startsWith("file:") ? new URL(specifier, context.parentURL) : void 0;
572
+ if (missing && !missing.href.includes("/node_modules/")) recordImport(context.parentURL, fileURLToPath(missing));
573
+ }
574
+ throw error;
575
+ }
576
+ if (!context.parentURL?.includes(VERSION_PARAM) || !resolved.url.startsWith("file:")) return resolved;
577
+ if (resolved.url.includes("/node_modules/")) return resolved;
578
+ const url = new URL(resolved.url);
579
+ if (url.searchParams.has(VERSION_PARAM)) return resolved;
580
+ const imported = fileURLToPath(url);
581
+ if (!recordImport(context.parentURL, imported)) return resolved;
582
+ url.searchParams.set(VERSION_PARAM, versionOf(imported).version);
583
+ startEvaluation(imported, url.href);
584
+ return {
585
+ ...resolved,
586
+ url: url.href
587
+ };
588
+ } });
589
+ shared.hooked = true;
590
+ return true;
591
+ }
592
+ function realFile(file) {
593
+ try {
594
+ return realpathSync(file);
595
+ } catch {
596
+ return file;
597
+ }
598
+ }
599
+ function importedBy(entries) {
600
+ const files = /* @__PURE__ */ new Set();
601
+ const pending = [...entries].flatMap((entry) => [...shared.graph.get(entry) ?? []]);
602
+ for (let file = pending.pop(); file !== void 0; file = pending.pop()) {
603
+ if (files.has(file)) continue;
604
+ files.add(file);
605
+ pending.push(...shared.graph.get(file) ?? []);
606
+ }
607
+ return [...files].filter((file) => !entries.has(file));
608
+ }
609
+ /**
610
+ * Imports of schema files in which a file imported by several of them, and by the same one again, is
611
+ * evaluated once: the versions are taken at the first import of a file and kept for the ones after it
612
+ */
613
+ function createSchemaImports() {
614
+ const hooks = hookImports();
615
+ shared.versions.clear();
616
+ shared.hashes.clear();
617
+ const modules = /* @__PURE__ */ new Map();
618
+ return {
619
+ import(schemaPath) {
620
+ const file = realFile(schemaPath);
621
+ const known = modules.get(file);
622
+ if (known) return known;
623
+ const url = new URL(pathToFileURL(file).href);
624
+ url.searchParams.set(VERSION_PARAM, hooks ? versionOf(file).version : `${Date.now()}`);
625
+ if (hooks) startEvaluation(file, url.href);
626
+ const loaded = import(url.href);
627
+ loaded.catch(() => {
628
+ shared.salt = `${Date.now()}-${++counter}`;
629
+ });
630
+ modules.set(file, loaded);
631
+ return loaded;
632
+ },
633
+ dependencies: (schemaPath) => new Map(importedBy(new Set(schemaPath ? [realFile(schemaPath)] : modules.keys())).map((file) => [file, shared.hashes.get(file) ?? hashOfFile(file)]))
634
+ };
635
+ }
441
636
  // src/schema-loader.ts
442
637
  var SchemaLoader = class {
443
638
  /**
@@ -450,13 +645,13 @@ var SchemaLoader = class {
450
645
  * Load a validation schema file for a table
451
646
  * Requires ${tableName}.schema.{ts,mts,cts} to exist in schemaDir, or alongside the JSONL file when omitted
452
647
  */
453
- static async loadSchema(jsonlPath, schemaDir) {
648
+ static async loadSchema(jsonlPath, schemaDir, imports) {
454
649
  const dir = schemaDir ?? dirname(jsonlPath);
455
650
  const tableName = basename(jsonlPath, ".jsonl");
456
651
  const schemaPath = await findSchemaFile(dir, tableName);
457
652
  if (!schemaPath) throw new Error(`Schema file not found for table '${tableName}'. Expected one of: ${SCHEMA_EXTENSIONS.map((ext) => `${tableName}${ext}`).join(", ")}`);
458
653
  try {
459
- const module = await import(`${pathToFileURL(schemaPath).href}?t=${Date.now()}`);
654
+ const module = await (imports ?? createSchemaImports()).import(schemaPath);
460
655
  const schema = module.default || module.schema;
461
656
  if (schema && this.isStandardSchema(schema)) return schema;
462
657
  throw new Error(`Schema file ${schemaPath} does not export a valid StandardSchema`);
@@ -679,15 +874,80 @@ function cloneFieldChanges(changes) {
679
874
  return new Map(Array.from(changes, ([tableName, byRow]) => [tableName, new Map(Array.from(byRow, ([rowid, row]) => [rowid, {
680
875
  set: new Set(row.set),
681
876
  reset: new Set(row.reset),
682
- inserted: row.inserted
877
+ inserted: row.inserted,
878
+ ...row.inputs ? { inputs: new Map(row.inputs) } : {}
683
879
  }]))]));
684
880
  }
881
+ /** The line of each row by the position recorded for it, undefined for a row that has none */
882
+ function linesByPosition(positions, rowids, existingRows) {
883
+ if (!positions) return void 0;
884
+ return rowids.map((rowid) => {
885
+ const position = positions.get(rowid);
886
+ return position === void 0 ? void 0 : existingRows[position];
887
+ });
888
+ }
889
+ /**
890
+ * Where each row's line stands in a file once it is written: the lines of rows that kept one stay in order,
891
+ * and a row without one goes after them, in the order the rows are given
892
+ */
893
+ function positionsAfterWrite(rowids, matches, existingRows) {
894
+ const kept = new Set(matches.filter((line) => line !== void 0));
895
+ const positionOfLine = /* @__PURE__ */ new Map();
896
+ existingRows.filter((line) => kept.has(line)).forEach((line, position) => positionOfLine.set(line, position));
897
+ let next = positionOfLine.size;
898
+ return new Map(rowids.map((rowid, index) => {
899
+ const line = matches[index];
900
+ return [rowid, line === void 0 ? next++ : positionOfLine.get(line)];
901
+ }));
902
+ }
903
+ /**
904
+ * What was kept by rowid when a write-back read its rows, brought up to date with the changes made since, in order:
905
+ * a deleted or reused rowid loses what it had, and a row that moved carries it to its new rowid
906
+ */
907
+ function replayEdits(byRowid, edits) {
908
+ for (const edit of edits) {
909
+ if ("forget" in edit) {
910
+ byRowid.delete(edit.forget);
911
+ continue;
912
+ }
913
+ const kept = byRowid.get(edit.from);
914
+ if (kept === void 0) continue;
915
+ byRowid.delete(edit.from);
916
+ byRowid.set(edit.to, kept);
917
+ }
918
+ return byRowid;
919
+ }
920
+ /**
921
+ * The temporary table the rowid changes of rows are logged to. Not qualified with `temp.`: SQLite before 3.53, as Bun
922
+ * ships, refuses a qualified table name in a trigger body, and an unqualified one is looked up in `temp` first
923
+ */
924
+ const MOVED_ROWS_LOG = "\"__lines_db_moved_rows\"";
685
925
  /** Column alias a query reads a row's rowid under, next to its fields */
686
926
  const ROWID_ALIAS = "__lines_db_rowid";
687
927
  /** The fields a row given to an insert names, leaving out those it leaves undefined */
688
928
  function givenFields(row) {
689
929
  return Object.entries(row).filter(([, value]) => value !== void 0).map(([key]) => key);
690
930
  }
931
+ /** Whether two values read the same once written as JSON; a bigint reads as its digits, which JSON.stringify refuses */
932
+ function sameValue(a, b) {
933
+ const text = (value) => JSON.stringify(value, (_key, item) => typeof item === "bigint" ? String(item) : item);
934
+ return text(a) === text(b);
935
+ }
936
+ /** Whether a value is a bigint or holds one at any depth, which a JSONL line cannot hold */
937
+ function holdsBigint(value) {
938
+ if (typeof value === "bigint") return true;
939
+ if (Array.isArray(value)) return value.some(holdsBigint);
940
+ return value !== null && typeof value === "object" && Object.values(value).some(holdsBigint);
941
+ }
942
+ /**
943
+ * The values of a row given to an insert that the stored row holds differently, after the schema transformed
944
+ * them. A value holding a bigint is left out: a line cannot hold one, so the row keeps the value the schema
945
+ * made of it
946
+ */
947
+ function transformedInputs(given, stored) {
948
+ 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)]));
949
+ return inputs.size > 0 ? inputs : void 0;
950
+ }
691
951
  /** Whether a value read from SQLite and one about to be stored are the same */
692
952
  function sameStoredValue(stored, next) {
693
953
  if (stored === null || stored === void 0 || next === null) return (stored ?? null) === next;
@@ -724,6 +984,18 @@ var LinesDB = class LinesDB {
724
984
  * back, also once the row's primary key changed and its line can no longer be found by it
725
985
  */
726
986
  linesWithUnknownFields = /* @__PURE__ */ new Map();
987
+ /**
988
+ * For a table without a primary key, where each row's line stands in its file: the rows cannot be
989
+ * matched to their lines by key, and by order only while none is added or removed
990
+ */
991
+ linePositionsByRowid = /* @__PURE__ */ new Map();
992
+ /**
993
+ * What happened to the positions of a table's rows since its rows were read for its write-back, in order: the
994
+ * positions that write-back computes describe the rows as they were, and are brought up to date with these
995
+ */
996
+ positionEdits = /* @__PURE__ */ new Map();
997
+ /** Whether the temporary table that triggers log the rowid changes of rows to exists */
998
+ movedRowsLogReady = false;
727
999
  /** Whether a transaction's callback has returned and its files are being written back */
728
1000
  transactionClosing = false;
729
1001
  /** Whether a transaction() call is past its guard but has not begun yet */
@@ -749,6 +1021,8 @@ var LinesDB = class LinesDB {
749
1021
  tablesFromGivenColumns = /* @__PURE__ */ new Set();
750
1022
  /** Each table's schema file and a hash of its content as the tables were loaded, or '' for none */
751
1023
  schemaFileStates = /* @__PURE__ */ new Map();
1024
+ schemaImports;
1025
+ schemaDependencyHashes = /* @__PURE__ */ new Map();
752
1026
  constructor(config, dbPath) {
753
1027
  this.config = config;
754
1028
  this.db = createDatabase(dbPath ?? ":memory:");
@@ -804,13 +1078,25 @@ var LinesDB = class LinesDB {
804
1078
  const loadingTables = /* @__PURE__ */ new Set();
805
1079
  const attemptedTables = /* @__PURE__ */ new Set();
806
1080
  const allDeferredForeignKeys = [];
807
- for (const tableNameToLoad of tablesToLoad) if (!attemptedTables.has(tableNameToLoad)) {
808
- const tableTransform = tableNameToLoad === tableName ? transform : void 0;
809
- const { errors, warnings, rowCounts: tableRowCounts, deferredForeignKeys } = await this.loadTableWithDependencies(tableNameToLoad, loadedTables, loadingTables, attemptedTables, detailedValidate, tableTransform);
810
- allErrors.push(...errors);
811
- allWarnings.push(...warnings);
812
- allDeferredForeignKeys.push(...deferredForeignKeys);
813
- for (const [k, v] of tableRowCounts) allRowCounts.set(k, v);
1081
+ const imports = createSchemaImports();
1082
+ this.schemaImports = imports;
1083
+ const schemaPaths = /* @__PURE__ */ new Map();
1084
+ for (const [name, config] of this.tables) {
1085
+ const schemaPath = await this.findTableSchemaFile(name, config);
1086
+ if (schemaPath) schemaPaths.set(name, schemaPath);
1087
+ }
1088
+ try {
1089
+ for (const tableNameToLoad of tablesToLoad) if (!attemptedTables.has(tableNameToLoad)) {
1090
+ const tableTransform = tableNameToLoad === tableName ? transform : void 0;
1091
+ const { errors, warnings, rowCounts: tableRowCounts, deferredForeignKeys } = await this.loadTableWithDependencies(tableNameToLoad, loadedTables, loadingTables, attemptedTables, detailedValidate, tableTransform);
1092
+ allErrors.push(...errors);
1093
+ allWarnings.push(...warnings);
1094
+ allDeferredForeignKeys.push(...deferredForeignKeys);
1095
+ for (const [k, v] of tableRowCounts) allRowCounts.set(k, v);
1096
+ }
1097
+ } finally {
1098
+ this.schemaImports = void 0;
1099
+ this.recordSchemaDependencies(imports, attemptedTables, schemaPaths, tableName === void 0);
814
1100
  }
815
1101
  if (detailedValidate && allDeferredForeignKeys.length > 0) for (const { tableName: tName, foreignKey: fk, filePath } of allDeferredForeignKeys) {
816
1102
  if (!loadedTables.has(fk.references.table)) continue;
@@ -835,6 +1121,9 @@ var LinesDB = class LinesDB {
835
1121
  tableResults
836
1122
  };
837
1123
  }
1124
+ importSchemaModule(schemaPath) {
1125
+ return (this.schemaImports ?? createSchemaImports()).import(schemaPath);
1126
+ }
838
1127
  /**
839
1128
  * Load a table and its dependencies recursively
840
1129
  */
@@ -857,10 +1146,9 @@ var LinesDB = class LinesDB {
857
1146
  try {
858
1147
  let foreignKeys;
859
1148
  try {
860
- const { pathToFileURL } = await import("node:url");
861
1149
  const schemaPath = await this.findTableSchemaFile(tableName, tableConfig);
862
1150
  if (schemaPath) {
863
- const schemaModule = await import(`${pathToFileURL(schemaPath).href}?t=${Date.now()}`);
1151
+ const schemaModule = await this.importSchemaModule(schemaPath);
864
1152
  foreignKeys = (schemaModule.schema || schemaModule.default)?.foreignKeys || schemaModule.foreignKeys;
865
1153
  }
866
1154
  } catch {}
@@ -961,11 +1249,10 @@ var LinesDB = class LinesDB {
961
1249
  let validationSchema = config.validationSchema;
962
1250
  const schemaMetadata = {};
963
1251
  const schemaPath = config.validationSchema ? void 0 : await this.findTableSchemaFile(tableName, config);
964
- if (!validationSchema && schemaPath) validationSchema = await SchemaLoader.loadSchema(config.jsonlPath, dirname(schemaPath));
1252
+ if (!validationSchema && schemaPath) validationSchema = await SchemaLoader.loadSchema(config.jsonlPath, dirname(schemaPath), this.schemaImports);
965
1253
  if (!config.validationSchema) try {
966
- const { pathToFileURL } = await import("node:url");
967
1254
  if (!schemaPath) throw new Error("Schema file not found");
968
- const schemaModule = await import(`${pathToFileURL(schemaPath).href}?t=${Date.now()}`);
1255
+ const schemaModule = await this.importSchemaModule(schemaPath);
969
1256
  const schemaExport = schemaModule.schema || schemaModule.default;
970
1257
  if (schemaExport?.primaryKey) schemaMetadata.primaryKey = schemaExport.primaryKey;
971
1258
  else if (schemaModule.primaryKey) schemaMetadata.primaryKey = schemaModule.primaryKey;
@@ -1075,16 +1362,26 @@ var LinesDB = class LinesDB {
1075
1362
  } else this.insertData(tableName, schema, validatedData);
1076
1363
  this.fieldChanges.delete(tableName);
1077
1364
  this.linesWithUnknownFields.delete(tableName);
1365
+ this.linePositionsByRowid.delete(tableName);
1366
+ if (this.tracksLinePositions(tableName)) {
1367
+ this.logMovedRows(tableName);
1368
+ const positions = /* @__PURE__ */ new Map();
1369
+ this.rowidsInLineOrder(tableName, validatedData).forEach((rowid, index) => {
1370
+ if (rowid !== void 0) positions.set(rowid, index);
1371
+ });
1372
+ this.linePositionsByRowid.set(tableName, positions);
1373
+ }
1078
1374
  const columnNames = new Set(schema.columns.map((column) => column.name));
1079
1375
  const withUnknown = data.map((row) => Object.keys(row).some((key) => !columnNames.has(key)));
1080
1376
  if (transformedFields.some((fields) => fields.length > 0) || withUnknown.includes(true)) {
1081
1377
  const rowids = this.queryInternal(`SELECT rowid AS "${ROWID_ALIAS}" FROM ${this.quoteTableName(tableName)} ORDER BY rowid`);
1082
1378
  const lines = /* @__PURE__ */ new Map();
1083
1379
  const sourceIndexes = new Map(origins.map((origin, index) => [origin, index]));
1380
+ const lineIndexes = new Map(this.rowidsInLineOrder(tableName, validatedData).map((rowid, index) => [rowid, index]));
1084
1381
  rowids.forEach((row, index) => {
1085
1382
  const rowid = row[ROWID_ALIAS];
1086
1383
  const origin = this.rowOriginsByRowid.get(tableName)?.get(String(rowid));
1087
- const sourceIndex = origin ? sourceIndexes.get(origin) ?? index : index;
1384
+ const sourceIndex = origin ? sourceIndexes.get(origin) ?? index : lineIndexes.get(String(rowid)) ?? index;
1088
1385
  const set = transformedFields[sourceIndex] ?? [];
1089
1386
  if (set.length > 0) this.noteFieldChanges(tableName, rowid, { set });
1090
1387
  if (withUnknown[sourceIndex]) lines.set(String(rowid), data[sourceIndex]);
@@ -1374,9 +1671,11 @@ var LinesDB = class LinesDB {
1374
1671
  try {
1375
1672
  return run();
1376
1673
  } finally {
1674
+ this.applyMovedRows();
1377
1675
  if (this.totalChanges() !== before) {
1378
1676
  for (const tableName of this.schemas.keys()) {
1379
1677
  this.rawSqlTables.add(tableName);
1678
+ this.linePositionsByRowid.delete(tableName);
1380
1679
  this.noteChange(tableName);
1381
1680
  }
1382
1681
  this.forgetLinesOfGoneRows(this.schemas.keys());
@@ -1553,8 +1852,10 @@ var LinesDB = class LinesDB {
1553
1852
  });
1554
1853
  this.rowOriginsByRowid.set(tableName, origins);
1555
1854
  }
1855
+ this.forgetPosition(tableName, String(result.lastInsertRowid));
1556
1856
  this.noteFieldChanges(tableName, result.lastInsertRowid, {
1557
1857
  set: givenFields(data),
1858
+ inputs: transformedInputs(data, row),
1558
1859
  inserted: true
1559
1860
  });
1560
1861
  this.afterWrite(tableName, result.changes);
@@ -1619,8 +1920,10 @@ var LinesDB = class LinesDB {
1619
1920
  undoSettle();
1620
1921
  throw error;
1621
1922
  }
1923
+ this.forgetPosition(tableName, String(result.lastInsertRowid));
1622
1924
  this.noteFieldChanges(tableName, result.lastInsertRowid, {
1623
1925
  set: givenFields(record),
1926
+ inputs: transformedInputs(record, row),
1624
1927
  inserted: true
1625
1928
  });
1626
1929
  totalChanges += BigInt(result.changes);
@@ -1650,44 +1953,58 @@ var LinesDB = class LinesDB {
1650
1953
  updateInternal(tableName, data, where, options) {
1651
1954
  this.assertMutable(tableName);
1652
1955
  if (!this.schemas.get(tableName)) throw new Error(`Table ${tableName} does not exist`);
1653
- const shouldValidate = options?.validate !== false;
1654
- const hasValidationSchema = this.validationSchemas.has(tableName);
1655
- if (shouldValidate && hasValidationSchema) {
1656
- const existingRows = this.findInternal(tableName, where);
1657
- for (const existingRow of existingRows) {
1658
- const mergedData = {
1659
- ...existingRow,
1660
- ...data
1661
- };
1662
- for (const field of options?.resetToDefault ?? []) delete mergedData[field];
1663
- this.validateData(tableName, mergedData);
1664
- }
1665
- }
1666
1956
  const { sql: whereSql, values: whereValues, functionFilters } = this.buildWhereClause(where, tableName);
1667
1957
  if (functionFilters.length > 0) throw new Error("Function filters are not supported in update operations");
1668
1958
  const targets = this.queryInternal(`SELECT rowid AS "${ROWID_ALIAS}", * FROM ${this.quoteTableName(tableName)} WHERE ${whereSql}`, whereValues);
1959
+ const shouldValidate = options?.validate !== false;
1960
+ const hasValidationSchema = this.validationSchemas.has(tableName);
1961
+ const givenKeys = Object.keys(data);
1669
1962
  const resetFields = options?.resetToDefault ?? [];
1963
+ const storedValues = targets.map((target) => {
1964
+ if (!shouldValidate || !hasValidationSchema) return data;
1965
+ const { [ROWID_ALIAS]: _rowid, ...stored } = target;
1966
+ const merged = {
1967
+ ...this.deserializeRow(tableName, stored),
1968
+ ...data
1969
+ };
1970
+ for (const field of resetFields) delete merged[field];
1971
+ const validated = this.validateAndTransform(tableName, merged);
1972
+ return Object.fromEntries(givenKeys.map((key) => [key, Object.hasOwn(validated, key) ? validated[key] : data[key]]));
1973
+ });
1670
1974
  const resets = resetFields.length > 0 ? this.computeResets(tableName, targets, data, resetFields) : [];
1671
1975
  let result = {
1672
1976
  changes: 0,
1673
1977
  lastInsertRowid: 0
1674
1978
  };
1675
- if (Object.keys(data).length > 0) {
1676
- const setClauses = Object.keys(data).map((key) => `${this.quoteIdentifier(key)} = ?`).join(", ");
1677
- const sql = `UPDATE ${this.quoteTableName(tableName)} SET ${setClauses} WHERE ${whereSql}`;
1678
- const values = [...Object.entries(data).map(([key, v]) => this.normalizeValue(v, this.columnOf(tableName, key))), ...whereValues];
1679
- const undoSettle = this.settleColumnsNoRowHolds(this.schemas.get(tableName), data);
1979
+ if (givenKeys.length > 0 && targets.length > 0) {
1980
+ const setClauses = givenKeys.map((key) => `${this.quoteIdentifier(key)} = ?`).join(", ");
1981
+ const sql = `UPDATE ${this.quoteTableName(tableName)} SET ${setClauses} WHERE rowid = ?`;
1982
+ const undoSettle = this.settleColumnsNoRowHolds(this.schemas.get(tableName), storedValues[0]);
1983
+ let changes = 0n;
1984
+ let lastInsertRowid = 0;
1985
+ this.db.exec("SAVEPOINT lines_db_update");
1680
1986
  try {
1681
- result = this.executeInternal(sql, values);
1987
+ targets.forEach((target, index) => {
1988
+ const written = this.executeInternal(sql, [...givenKeys.map((key) => this.normalizeValue(storedValues[index][key], this.columnOf(tableName, key))), target[ROWID_ALIAS]]);
1989
+ changes += BigInt(written.changes);
1990
+ lastInsertRowid = written.lastInsertRowid;
1991
+ });
1992
+ this.db.exec("RELEASE lines_db_update");
1682
1993
  } catch (error) {
1994
+ this.db.exec("ROLLBACK TO lines_db_update");
1995
+ this.db.exec("RELEASE lines_db_update");
1683
1996
  undoSettle();
1684
1997
  throw error;
1685
1998
  }
1686
- if (Number(result.changes) === 0) undoSettle();
1999
+ result = {
2000
+ changes: Number(changes),
2001
+ lastInsertRowid
2002
+ };
2003
+ if (changes === 0n) undoSettle();
1687
2004
  }
1688
2005
  const pkName = this.schemas.get(tableName)?.columns.find((col) => col.primaryKey)?.name;
1689
2006
  if (pkName && Object.hasOwn(data, pkName)) {
1690
- 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))]);
2007
+ 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))]);
1691
2008
  if (targets.length === 1 && moved.length === 1) {
1692
2009
  const from = String(targets[0][ROWID_ALIAS]);
1693
2010
  const to = moved[0][ROWID_ALIAS];
@@ -1700,10 +2017,14 @@ var LinesDB = class LinesDB {
1700
2017
  }
1701
2018
  }
1702
2019
  }
1703
- for (const target of targets) {
1704
- const set = Object.keys(data).filter((key) => !sameStoredValue(target[key], this.normalizeValue(data[key], this.columnOf(tableName, key))));
1705
- this.noteFieldChanges(tableName, target[ROWID_ALIAS], { set });
1706
- }
2020
+ targets.forEach((target, index) => {
2021
+ const set = givenKeys.filter((key) => !sameStoredValue(target[key], this.normalizeValue(storedValues[index][key], this.columnOf(tableName, key))));
2022
+ const given = Object.fromEntries(set.map((key) => [key, data[key]]));
2023
+ this.noteFieldChanges(tableName, target[ROWID_ALIAS], {
2024
+ set,
2025
+ inputs: transformedInputs(given, storedValues[index])
2026
+ });
2027
+ });
1707
2028
  if (resets.length > 0) result = this.applyResets(tableName, resets, resetFields);
1708
2029
  this.afterWrite(tableName, result.changes);
1709
2030
  return result;
@@ -2057,9 +2378,18 @@ var LinesDB = class LinesDB {
2057
2378
  this.assertWritable(tableName);
2058
2379
  const config = this.tables.get(tableName);
2059
2380
  if (!config) throw new Error(`Table ${tableName} not found`);
2381
+ this.positionEdits.set(tableName, []);
2060
2382
  const stored = this.readStoredRows(tableName);
2061
- if (!this.hasSeveralDataDirs()) return [await this.prepareFileWriteBack(tableName, config.jsonlPath, stored, options)];
2062
- const origins = this.rowOriginsByRowid.get(tableName);
2383
+ const recorded = this.linePositionsByRowid.get(tableName);
2384
+ const atRead = {
2385
+ generation: this.changeGenerations.get(tableName) ?? 0,
2386
+ positions: recorded && new Map(recorded),
2387
+ origins: new Map(this.rowOriginsByRowid.get(tableName) ?? []),
2388
+ changes: cloneFieldChanges(/* @__PURE__ */ new Map([[tableName, this.fieldChanges.get(tableName) ?? /* @__PURE__ */ new Map()]])).get(tableName),
2389
+ unknownFieldLines: new Map(this.linesWithUnknownFields.get(tableName) ?? [])
2390
+ };
2391
+ if (!this.hasSeveralDataDirs()) return [await this.prepareFileWriteBack(tableName, config.jsonlPath, stored, options, atRead)];
2392
+ const origins = atRead.origins;
2063
2393
  const byFile = new Map([this.config.dataDir].flat().map((dir) => [join(dir, `${tableName}.jsonl`), []]));
2064
2394
  stored.rowids.forEach((rowid, index) => {
2065
2395
  const origin = origins?.get(rowid);
@@ -2076,33 +2406,98 @@ var LinesDB = class LinesDB {
2076
2406
  rows: indexes.map((i) => stored.rows[i]),
2077
2407
  lineRows: indexes.map((i) => stored.lineRows[i])
2078
2408
  };
2079
- const fileWrite = await this.prepareFileWriteBack(tableName, file, rows, options);
2409
+ const fileWrite = await this.prepareFileWriteBack(tableName, file, rows, options, atRead);
2080
2410
  if (!fileWrite.unchanged) prepared.push(fileWrite);
2081
2411
  }
2082
2412
  return prepared;
2083
2413
  }
2084
- async prepareFileWriteBack(tableName, jsonlPath, stored, options) {
2414
+ forgetPosition(tableName, rowid) {
2415
+ this.linePositionsByRowid.get(tableName)?.delete(rowid);
2416
+ this.positionEdits.get(tableName)?.push({ forget: rowid });
2417
+ }
2418
+ /**
2419
+ * The rowid of the row each line was loaded into, in the order of the lines. Not the rowid order: an INTEGER
2420
+ * PRIMARY KEY is the rowid, so the line `{"id":3}` first in its file is the row with rowid 3
2421
+ */
2422
+ rowidsInLineOrder(tableName, rows) {
2423
+ const pk = this.schemas.get(tableName)?.columns.find((column) => column.primaryKey);
2424
+ const stored = this.queryInternal(`SELECT rowid AS "${ROWID_ALIAS}" FROM ${this.quoteTableName(tableName)} ORDER BY rowid`).map((row) => String(row[ROWID_ALIAS]));
2425
+ if (pk?.type !== "INTEGER") return stored;
2426
+ const present = new Set(stored);
2427
+ let largest;
2428
+ return rows.map((row) => {
2429
+ const key = row[pk.name];
2430
+ const rowid = key === void 0 || key === null ? (largest ?? 0) + 1 : Number(key);
2431
+ largest = largest === void 0 ? rowid : Math.max(largest, rowid);
2432
+ return present.has(String(rowid)) ? String(rowid) : void 0;
2433
+ });
2434
+ }
2435
+ /**
2436
+ * Log each change of a row's rowid in the table: a foreign-key action or raw SQL can change an INTEGER PRIMARY
2437
+ * KEY, which is the rowid, without a write through this database telling it which row moved
2438
+ */
2439
+ logMovedRows(tableName) {
2440
+ if (!this.movedRowsLogReady) {
2441
+ this.db.exec(`CREATE TEMP TABLE IF NOT EXISTS ${MOVED_ROWS_LOG} (tbl TEXT, old INTEGER, new INTEGER)`);
2442
+ this.movedRowsLogReady = true;
2443
+ }
2444
+ const trigger = this.quoteIdentifier(`__lines_db_moved_${tableName}`);
2445
+ const name = `'${tableName.replace(/'/g, "''")}'`;
2446
+ 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`);
2447
+ }
2448
+ /** Move what is kept by rowid to the rowid each logged row moved to, in the order the rows moved */
2449
+ applyMovedRows() {
2450
+ if (!this.movedRowsLogReady) return;
2451
+ const moved = this.queryInternal(`SELECT tbl, old, new FROM ${MOVED_ROWS_LOG} ORDER BY rowid`);
2452
+ if (moved.length === 0) return;
2453
+ this.db.exec(`DELETE FROM ${MOVED_ROWS_LOG}`);
2454
+ for (const { tbl, old, new: to } of moved) this.moveRowMetadata(String(tbl), String(old), String(to));
2455
+ }
2456
+ /**
2457
+ * Whether the lines of a table are remembered by position, so a row whose key changed, or that has none, is
2458
+ * found again by where its line stood. Several data directories have the origin of each row instead
2459
+ */
2460
+ tracksLinePositions(_tableName) {
2461
+ return !this.hasSeveralDataDirs();
2462
+ }
2463
+ hasNoPrimaryKey(tableName) {
2464
+ return this.schemas.get(tableName)?.columns.some((column) => column.primaryKey) === false;
2465
+ }
2466
+ async prepareFileWriteBack(tableName, jsonlPath, stored, options, atRead) {
2085
2467
  const { rowids, rows: deserializedRows, lineRows } = stored;
2086
- const generation = this.changeGenerations.get(tableName) ?? 0;
2468
+ const generation = atRead?.generation ?? this.changeGenerations.get(tableName) ?? 0;
2087
2469
  let finalRows = lineRows;
2088
2470
  const previousContent = await readFile(jsonlPath, "utf-8").catch((error) => {
2089
2471
  if (error.code === "ENOENT") return void 0;
2090
2472
  throw error;
2091
2473
  });
2092
2474
  const existingRows = await this.readUnchangedRows(jsonlPath);
2093
- const matches = this.hasSeveralDataDirs() ? rowids.map((rowid) => existingRows[this.rowOriginsByRowid.get(tableName).get(rowid).rowIndex]) : void 0;
2475
+ const origins = atRead?.origins ?? this.rowOriginsByRowid.get(tableName);
2476
+ const matchedByOrigin = this.hasSeveralDataDirs() ? rowids.map((rowid) => {
2477
+ const origin = origins?.get(rowid);
2478
+ return origin && existingRows[origin.rowIndex];
2479
+ }) : void 0;
2480
+ const byPosition = matchedByOrigin ? void 0 : linesByPosition(atRead?.positions, rowids, existingRows);
2481
+ const matches = matchedByOrigin ?? (this.hasNoPrimaryKey(tableName) ? byPosition : void 0);
2482
+ const positionedLines = matches ? void 0 : byPosition;
2094
2483
  const fields = options?.fields ?? this.config.writeBackFields;
2095
- if ((options?.writeFilledValues ?? this.config.writeFilledValues ?? "all") === "primaryKey") finalRows = this.keepWrittenFields(tableName, rowids, deserializedRows, finalRows, existingRows, fields, matches).map(({ written }) => written);
2484
+ if ((options?.writeFilledValues ?? this.config.writeFilledValues ?? "all") === "primaryKey") finalRows = this.keepWrittenFields(tableName, rowids, deserializedRows, finalRows, existingRows, fields, matches, {
2485
+ positionedLines,
2486
+ changes: atRead?.changes
2487
+ }).map(({ written }) => written);
2096
2488
  const columns = new Set(this.schemas.get(tableName)?.columns.map((column) => column.name));
2097
- const readLines = this.linesWithUnknownFields.get(tableName);
2489
+ const readLines = atRead?.unknownFieldLines ?? this.linesWithUnknownFields.get(tableName);
2098
2490
  finalRows = finalRows.map((row, index) => {
2099
2491
  const line = readLines?.get(rowids[index]);
2100
2492
  return line ? keepUnknownFields(line, row, columns) : row;
2101
2493
  });
2494
+ let linesOfRows;
2102
2495
  finalRows = this.mergeWithExistingLines(tableName, existingRows, finalRows, {
2103
2496
  fields,
2104
2497
  strictFields: options?.strictFields ?? false,
2105
- matches
2498
+ matches,
2499
+ positionedLines,
2500
+ onMatched: (lines) => linesOfRows = lines
2106
2501
  });
2107
2502
  return {
2108
2503
  tableName,
@@ -2110,10 +2505,11 @@ var LinesDB = class LinesDB {
2110
2505
  rows: finalRows,
2111
2506
  previousContent,
2112
2507
  generation,
2113
- ...matches ? {
2508
+ ...matchedByOrigin ? {
2114
2509
  rowids,
2115
2510
  unchanged: JsonlWriter.serialize(existingRows) === JsonlWriter.serialize(finalRows)
2116
- } : {}
2511
+ } : {},
2512
+ ...this.tracksLinePositions(tableName) && !matchedByOrigin ? { positions: linesOfRows ? positionsAfterWrite(rowids, linesOfRows, existingRows) : new Map(rowids.map((rowid, position) => [rowid, position])) } : {}
2117
2513
  };
2118
2514
  }
2119
2515
  /**
@@ -2136,17 +2532,22 @@ var LinesDB = class LinesDB {
2136
2532
  * minus those reset to their default - its primary key and the fields named to be written back, so
2137
2533
  * a value the schema fills in stays out of the file
2138
2534
  */
2139
- keepWrittenFields(tableName, rowids, rows, lineRows, existingRows, namedFields = [], matchedLines) {
2535
+ keepWrittenFields(tableName, rowids, rows, lineRows, existingRows, namedFields = [], matchedLines, options) {
2140
2536
  const pkName = this.schemas.get(tableName)?.columns.find((col) => col.primaryKey)?.name;
2141
- const actionColumns = (this.schemas.get(tableName)?.foreignKeys ?? []).filter((fk) => [fk.onDelete, fk.onUpdate].some((action) => action === "CASCADE" || action === "SET NULL")).map((fk) => fk.column);
2142
- const lines = matchedLines ?? this.matchExistingRows(tableName, lineRows, existingRows, { required: false });
2143
- const changes = this.fieldChanges.get(tableName);
2537
+ 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);
2538
+ const lines = matchedLines ?? this.matchExistingRows(tableName, lineRows, existingRows, {
2539
+ required: false,
2540
+ byOutputKey: true,
2541
+ positionedLines: options?.positionedLines
2542
+ });
2543
+ const changes = options?.changes ?? this.fieldChanges.get(tableName);
2144
2544
  return lineRows.map((lineRow, index) => {
2145
2545
  const line = lines?.[index];
2146
2546
  const rowChanges = changes?.get(rowids[index]);
2147
2547
  if (Object.keys(lineRow).some((key) => !Object.hasOwn(rows[index], key)) || this.rawSqlTables.has(tableName) || !line && !rowChanges?.inserted) return {
2148
2548
  written: lineRow,
2149
- narrowed: false
2549
+ narrowed: false,
2550
+ line
2150
2551
  };
2151
2552
  const keep = /* @__PURE__ */ new Set([
2152
2553
  ...Object.keys(line ?? {}),
@@ -2156,10 +2557,11 @@ var LinesDB = class LinesDB {
2156
2557
  for (const key of rowChanges?.reset ?? []) keep.delete(key);
2157
2558
  for (const key of namedFields) keep.add(key);
2158
2559
  if (pkName) keep.add(pkName);
2159
- const untouched = line !== void 0 && !rowChanges?.inserted && !rowChanges?.set.size && !rowChanges?.reset.size;
2560
+ const untouched = (key) => line !== void 0 && !rowChanges?.inserted && Object.hasOwn(line, key) && !rowChanges?.set.has(key) && !rowChanges?.reset.has(key);
2160
2561
  return {
2161
- 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])),
2162
- narrowed: true
2562
+ 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])),
2563
+ narrowed: true,
2564
+ line
2163
2565
  };
2164
2566
  });
2165
2567
  }
@@ -2171,10 +2573,15 @@ var LinesDB = class LinesDB {
2171
2573
  * later, which must not inherit them
2172
2574
  */
2173
2575
  moveRowMetadata(tableName, from, to) {
2576
+ this.positionEdits.get(tableName)?.push({
2577
+ from,
2578
+ to
2579
+ });
2174
2580
  for (const byRow of [
2175
2581
  this.fieldChanges.get(tableName),
2176
2582
  this.linesWithUnknownFields.get(tableName),
2177
- this.rowOriginsByRowid.get(tableName)
2583
+ this.rowOriginsByRowid.get(tableName),
2584
+ this.linePositionsByRowid.get(tableName)
2178
2585
  ]) {
2179
2586
  const kept = byRow?.get(from);
2180
2587
  if (!byRow || kept === void 0) continue;
@@ -2199,6 +2606,7 @@ var LinesDB = class LinesDB {
2199
2606
  }
2200
2607
  forgetFieldChanges(tableName, rowids) {
2201
2608
  for (const rowid of rowids) {
2609
+ this.forgetPosition(tableName, rowid);
2202
2610
  this.fieldChanges.get(tableName)?.delete(rowid);
2203
2611
  this.linesWithUnknownFields.get(tableName)?.delete(rowid);
2204
2612
  }
@@ -2218,10 +2626,16 @@ var LinesDB = class LinesDB {
2218
2626
  for (const key of changes.set ?? []) {
2219
2627
  rowChanges.set.add(key);
2220
2628
  rowChanges.reset.delete(key);
2629
+ rowChanges.inputs?.delete(key);
2221
2630
  }
2222
2631
  for (const key of changes.reset ?? []) {
2223
2632
  rowChanges.reset.add(key);
2224
2633
  rowChanges.set.delete(key);
2634
+ rowChanges.inputs?.delete(key);
2635
+ }
2636
+ for (const [key, value] of changes.inputs ?? []) {
2637
+ rowChanges.inputs ??= /* @__PURE__ */ new Map();
2638
+ rowChanges.inputs.set(key, value);
2225
2639
  }
2226
2640
  byRow.set(String(rowid), rowChanges);
2227
2641
  this.fieldChanges.set(tableName, byRow);
@@ -2262,25 +2676,49 @@ var LinesDB = class LinesDB {
2262
2676
  }
2263
2677
  /**
2264
2678
  * Every row of a table with the fields the schema filled in rather than the file: the ones its line
2265
- * does not hold and no write set, which a write-back leaves out of the file
2679
+ * does not hold and no write set, which a write-back leaves out of the file. `input` is the row as
2680
+ * its line holds it - the values before the schema transformed them, without the defaulted fields.
2266
2681
  */
2267
2682
  async findWithDefaults(tableName) {
2268
2683
  try {
2269
2684
  const tableConfig = this.tables.get(tableName);
2270
2685
  if (!tableConfig || !this.schemas.has(tableName)) throw new Error(`Table '${tableName}' is not loaded`);
2271
- await this.waitForPendingSyncs();
2272
- const { rowids, rows, lineRows } = this.readStoredRows(tableName);
2273
- const fileRows = /* @__PURE__ */ new Map();
2274
- 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));
2686
+ let stored;
2687
+ let positionsAtRead;
2688
+ let fileRows;
2689
+ for (let attempt = 1;; attempt++) {
2690
+ await this.waitForPendingSyncs();
2691
+ const files = this.hasSeveralDataDirs() ? [.../* @__PURE__ */ new Set([...tableConfig.jsonlPaths ?? [tableConfig.jsonlPath], ...[...this.rowOriginsByRowid.get(tableName)?.values() ?? []].map((origin) => origin.file)])] : [tableConfig.jsonlPath];
2692
+ const generation = this.changeGenerations.get(tableName) ?? 0;
2693
+ const hashes = files.map((file) => this.fileHashes.get(file));
2694
+ stored = this.readStoredRows(tableName);
2695
+ const recorded = this.linePositionsByRowid.get(tableName);
2696
+ positionsAtRead = recorded && new Map(recorded);
2697
+ fileRows = /* @__PURE__ */ new Map();
2698
+ const unchanged = () => (this.changeGenerations.get(tableName) ?? 0) === generation && files.every((file, index) => this.fileHashes.get(file) === hashes[index]);
2699
+ try {
2700
+ for (const file of files) fileRows.set(file, await this.readUnchangedRows(file));
2701
+ } catch (error) {
2702
+ if (!(error instanceof Error && error.name === "JsonlConflictError") || unchanged()) throw error;
2703
+ }
2704
+ if (unchanged()) break;
2705
+ if (attempt >= 5) throw new Error(`The rows of '${tableName}' kept changing while they were read; read them again`);
2706
+ }
2707
+ const { rowids, rows, lineRows } = stored;
2275
2708
  const existingRows = [...fileRows.values()].flat();
2276
2709
  const matches = this.hasSeveralDataDirs() && this.config.writeDataSets ? rowids.map((rowid) => {
2277
2710
  const origin = this.rowOriginsByRowid.get(tableName)?.get(rowid);
2278
2711
  return origin && fileRows.get(origin.file)?.[origin.rowIndex];
2279
- }) : void 0;
2712
+ }) : linesByPosition(positionsAtRead, rowids, existingRows);
2280
2713
  const kept = this.keepWrittenFields(tableName, rowids, rows, lineRows, existingRows, this.config.writeBackFields, matches);
2714
+ const lines = this.keepWrittenFields(tableName, rowids, rows, lineRows, existingRows, [], matches, { ignoreActions: true });
2281
2715
  return ok(rows.map((row, index) => ({
2282
2716
  row,
2283
- defaulted: kept[index].narrowed ? Object.keys(row).filter((key) => !Object.hasOwn(kept[index].written, key)) : []
2717
+ defaulted: kept[index].narrowed ? Object.keys(row).filter((key) => !Object.hasOwn(kept[index].written, key)) : [],
2718
+ input: {
2719
+ ...lines[index].written,
2720
+ ...Object.fromEntries(Object.entries(lines[index].line ?? {}).filter(([key]) => !Object.hasOwn(lines[index].written, key) && !Object.hasOwn(row, key)))
2721
+ }
2284
2722
  })));
2285
2723
  } catch (error) {
2286
2724
  return err(toError(error));
@@ -2300,6 +2738,7 @@ var LinesDB = class LinesDB {
2300
2738
  * tables it changed once its callback is done
2301
2739
  */
2302
2740
  afterWrite(tableName, changes) {
2741
+ this.applyMovedRows();
2303
2742
  if (BigInt(changes) === 0n && this.transactionChanges) return;
2304
2743
  const tableNames = [tableName, ...this.tablesChangedByForeignKeyActions(tableName)];
2305
2744
  this.forgetLinesOfGoneRows(tableNames);
@@ -2353,17 +2792,20 @@ var LinesDB = class LinesDB {
2353
2792
  } catch (error) {
2354
2793
  throw await this.restoreAll(written, error);
2355
2794
  }
2356
- for (const { tableName, jsonlPath, generation, rowids } of written) {
2795
+ for (const { tableName, jsonlPath, generation, rowids, positions } of written) {
2796
+ const edits = this.positionEdits.get(tableName) ?? [];
2797
+ if (positions) this.linePositionsByRowid.set(tableName, replayEdits(positions, edits));
2357
2798
  if ((this.changeGenerations.get(tableName) ?? 0) === generation) {
2358
2799
  this.fieldChanges.delete(tableName);
2359
2800
  this.rawSqlTables.delete(tableName);
2360
2801
  }
2361
2802
  if (rowids) {
2362
2803
  const origins = this.rowOriginsByRowid.get(tableName);
2363
- rowids.forEach((rowid, rowIndex) => origins.set(rowid, {
2804
+ const writtenOrigins = new Map(rowids.map((rowid, rowIndex) => [rowid, {
2364
2805
  file: jsonlPath,
2365
2806
  rowIndex
2366
- }));
2807
+ }]));
2808
+ for (const [rowid, origin] of replayEdits(writtenOrigins, edits)) origins.set(rowid, origin);
2367
2809
  if (!this.scannedJsonlFiles.includes(jsonlPath)) this.scannedJsonlFiles.push(jsonlPath);
2368
2810
  }
2369
2811
  }
@@ -2431,7 +2873,11 @@ var LinesDB = class LinesDB {
2431
2873
  const unknownFields = fields.filter((field) => !tableFields.includes(field));
2432
2874
  throw new Error(`Cannot write back field(s) [${unknownFields.join(", ")}] for table '${tableName}': no such field in the rows written back to the file.`);
2433
2875
  }
2434
- const existing = options.matches ?? this.matchExistingRows(tableName, rows, existingRows, { required: fields !== void 0 });
2876
+ const existing = options.matches ?? this.matchExistingRows(tableName, rows, existingRows, {
2877
+ required: fields !== void 0,
2878
+ positionedLines: options.positionedLines
2879
+ });
2880
+ options.onMatched?.(existing);
2435
2881
  if (!existing) return rows;
2436
2882
  const rowByLine = /* @__PURE__ */ new Map();
2437
2883
  const newRows = [];
@@ -2449,20 +2895,41 @@ var LinesDB = class LinesDB {
2449
2895
  }), ...newRows];
2450
2896
  }
2451
2897
  /**
2898
+ * The primary key the schema makes of a line, which is how the stored rows hold it. The line's own key
2899
+ * when the rows are in the line's terms (a `backward` transformation maps them back), when there is no
2900
+ * schema, or when the schema refuses the line
2901
+ */
2902
+ outputKeyOfLine(tableName, line, pkName) {
2903
+ const schema = this.validationSchemas.get(tableName);
2904
+ if (!schema || hasBackward(schema) || line[pkName] === void 0 || line[pkName] === null) return line[pkName];
2905
+ try {
2906
+ return this.validateAndTransform(tableName, line)[pkName] ?? line[pkName];
2907
+ } catch {
2908
+ return line[pkName];
2909
+ }
2910
+ }
2911
+ /**
2452
2912
  * Pair each row with the JSONL line it came from, indexed the same way as `rows`.
2453
2913
  * Returns undefined when the rows cannot be matched and the caller can do without it.
2454
2914
  */
2455
2915
  matchExistingRows(tableName, rows, existingRows, options) {
2456
2916
  if (existingRows.length === 0) return rows.map(() => void 0);
2457
2917
  const pkName = this.schemas.get(tableName)?.columns.find((col) => col.primaryKey)?.name;
2458
- const pkValues = pkName ? existingRows.map((row) => row[pkName]) : [];
2918
+ if (pkName && options.positionedLines?.every((line) => line !== void 0)) return options.positionedLines;
2919
+ const pkValues = pkName ? existingRows.map((row) => options.byOutputKey ? this.outputKeyOfLine(tableName, row, pkName) : row[pkName]) : [];
2459
2920
  if (pkName !== void 0 && pkValues.every((value) => value !== void 0 && value !== null) && new Set(pkValues.map((value) => String(value))).size === pkValues.length) {
2460
2921
  const byPk = new Map(existingRows.map((row, index) => [String(pkValues[index]), row]));
2461
- return rows.map((row) => {
2922
+ const positioned = options.positionedLines;
2923
+ const claimed = new Set(positioned?.filter((line) => line !== void 0));
2924
+ return rows.map((row, index) => {
2925
+ const byPosition = positioned?.[index];
2926
+ if (byPosition) return byPosition;
2462
2927
  const pkValue = row[pkName];
2463
- return pkValue === void 0 || pkValue === null ? void 0 : byPk.get(String(pkValue));
2928
+ const byKey = pkValue === void 0 || pkValue === null ? void 0 : byPk.get(String(pkValue));
2929
+ return byKey && !claimed.has(byKey) ? byKey : void 0;
2464
2930
  });
2465
2931
  }
2932
+ if (options.positionedLines) return options.positionedLines;
2466
2933
  if (rows.length !== existingRows.length) {
2467
2934
  if (!options.required) return;
2468
2935
  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.`);
@@ -2505,7 +2972,8 @@ var LinesDB = class LinesDB {
2505
2972
  }
2506
2973
  /**
2507
2974
  * The files that changed since this database last read or wrote them, as {@link hasExternalChanges}
2508
- * tells: each JSONL file edited, added or removed, and each schema file edited, added or removed
2975
+ * tells: each JSONL file edited, added or removed, each schema file edited, added or removed, and each
2976
+ * project file a schema imports edited, added or removed
2509
2977
  */
2510
2978
  async findExternalChanges() {
2511
2979
  try {
@@ -2524,6 +2992,16 @@ var LinesDB = class LinesDB {
2524
2992
  });
2525
2993
  if (content === void 0 || hashJsonlContent(content) !== knownHash) changed.add(file);
2526
2994
  }
2995
+ const knownHashes = /* @__PURE__ */ new Map();
2996
+ for (const files of this.schemaDependencyHashes.values()) for (const [file, knownHash] of files) knownHashes.set(file, (knownHashes.get(file) ?? /* @__PURE__ */ new Set()).add(knownHash));
2997
+ for (const [file, hashes] of knownHashes) {
2998
+ const content = await readFile(file).catch((error) => {
2999
+ if (error.code === "ENOENT") return void 0;
3000
+ throw error;
3001
+ });
3002
+ const current = content === void 0 ? MISSING_HASH : hashContent(content);
3003
+ if ([...hashes].some((hash) => hash !== current)) changed.add(file);
3004
+ }
2527
3005
  const tables = await DirectoryScanner.scanDirectory(this.config.dataDir);
2528
3006
  const scanned = new Set(listJsonlFiles(tables));
2529
3007
  for (const file of this.scannedJsonlFiles) if (!scanned.has(file)) changed.add(file);
@@ -2546,6 +3024,25 @@ var LinesDB = class LinesDB {
2546
3024
  });
2547
3025
  return content === void 0 ? "" : `${schemaPath}\0${hashJsonlContent(content)}`;
2548
3026
  }
3027
+ recordSchemaDependencies(imports, tableNames, schemaPaths, replace) {
3028
+ if (replace) {
3029
+ for (const name of this.schemaDependencyHashes.keys()) if (!schemaPaths.has(name)) this.schemaDependencyHashes.delete(name);
3030
+ }
3031
+ for (const name of tableNames) {
3032
+ const schemaPath = schemaPaths.get(name);
3033
+ if (schemaPath) this.schemaDependencyHashes.set(name, imports.dependencies(schemaPath));
3034
+ else this.schemaDependencyHashes.delete(name);
3035
+ }
3036
+ }
3037
+ /**
3038
+ * The project files the schemas import, as paths: not the schema files, and not a package from
3039
+ * node_modules. Those of one table when it is given. An edit to one of them is among
3040
+ * {@link findExternalChanges}
3041
+ */
3042
+ listSchemaDependencies(tableName) {
3043
+ const tables = tableName === void 0 ? [...this.schemaDependencyHashes.values()] : [this.schemaDependencyHashes.get(tableName) ?? /* @__PURE__ */ new Map()];
3044
+ return [...new Set(tables.flatMap((files) => [...files.keys()]))];
3045
+ }
2549
3046
  async schemaFileState(tableName, config) {
2550
3047
  if (config.validationSchema) return "";
2551
3048
  const schemaPath = await this.findTableSchemaFile(tableName, config);
@@ -2594,6 +3091,7 @@ var LinesDB = class LinesDB {
2594
3091
  let fieldChangesBefore;
2595
3092
  let rawSqlTablesBefore;
2596
3093
  let linesWithUnknownFieldsBefore;
3094
+ let linePositionsBefore;
2597
3095
  let originsBefore;
2598
3096
  let columnsBefore;
2599
3097
  const scannedBefore = [...this.scannedJsonlFiles];
@@ -2605,6 +3103,7 @@ var LinesDB = class LinesDB {
2605
3103
  fieldChangesBefore = cloneFieldChanges(this.fieldChanges);
2606
3104
  rawSqlTablesBefore = new Set(this.rawSqlTables);
2607
3105
  linesWithUnknownFieldsBefore = new Map(Array.from(this.linesWithUnknownFields, ([tableName, lines]) => [tableName, new Map(lines)]));
3106
+ linePositionsBefore = new Map(Array.from(this.linePositionsByRowid, ([tableName, positions]) => [tableName, new Map(positions)]));
2608
3107
  this.db.exec("BEGIN TRANSACTION");
2609
3108
  this.settleUndos = [];
2610
3109
  this.inTransaction = true;
@@ -2635,6 +3134,7 @@ var LinesDB = class LinesDB {
2635
3134
  if (fieldChangesBefore) this.fieldChanges = fieldChangesBefore;
2636
3135
  if (rawSqlTablesBefore) this.rawSqlTables = rawSqlTablesBefore;
2637
3136
  if (linesWithUnknownFieldsBefore) this.linesWithUnknownFields = linesWithUnknownFieldsBefore;
3137
+ if (linePositionsBefore) this.linePositionsByRowid = linePositionsBefore;
2638
3138
  const failure = await this.restoreAll(written, error);
2639
3139
  if (this.inTransaction) try {
2640
3140
  this.db.exec("ROLLBACK");
@@ -2864,13 +3364,14 @@ async function fillFieldsInternal(options) {
2864
3364
  const loadFiller = options.loadFiller ?? fillerFromValidationSchema;
2865
3365
  const tablesWithoutSchema = [];
2866
3366
  const tables = [];
3367
+ const imports = createSchemaImports();
2867
3368
  for (const { table, file, target, schemaDir } of sources.values()) {
2868
3369
  const schemaPath = await findSchemaFile(schemaDir, table);
2869
3370
  if (!schemaPath) {
2870
3371
  if (!tablesWithoutSchema.includes(table)) tablesWithoutSchema.push(table);
2871
3372
  continue;
2872
3373
  }
2873
- const schemaModule = await import(`${pathToFileURL(schemaPath).href}?t=${Date.now()}`);
3374
+ const schemaModule = await imports.import(schemaPath);
2874
3375
  tables.push({
2875
3376
  table,
2876
3377
  file,