lines-db 0.19.1 → 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
@@ -874,15 +874,80 @@ function cloneFieldChanges(changes) {
874
874
  return new Map(Array.from(changes, ([tableName, byRow]) => [tableName, new Map(Array.from(byRow, ([rowid, row]) => [rowid, {
875
875
  set: new Set(row.set),
876
876
  reset: new Set(row.reset),
877
- inserted: row.inserted
877
+ inserted: row.inserted,
878
+ ...row.inputs ? { inputs: new Map(row.inputs) } : {}
878
879
  }]))]));
879
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\"";
880
925
  /** Column alias a query reads a row's rowid under, next to its fields */
881
926
  const ROWID_ALIAS = "__lines_db_rowid";
882
927
  /** The fields a row given to an insert names, leaving out those it leaves undefined */
883
928
  function givenFields(row) {
884
929
  return Object.entries(row).filter(([, value]) => value !== void 0).map(([key]) => key);
885
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
+ }
886
951
  /** Whether a value read from SQLite and one about to be stored are the same */
887
952
  function sameStoredValue(stored, next) {
888
953
  if (stored === null || stored === void 0 || next === null) return (stored ?? null) === next;
@@ -919,6 +984,18 @@ var LinesDB = class LinesDB {
919
984
  * back, also once the row's primary key changed and its line can no longer be found by it
920
985
  */
921
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;
922
999
  /** Whether a transaction's callback has returned and its files are being written back */
923
1000
  transactionClosing = false;
924
1001
  /** Whether a transaction() call is past its guard but has not begun yet */
@@ -1285,16 +1362,26 @@ var LinesDB = class LinesDB {
1285
1362
  } else this.insertData(tableName, schema, validatedData);
1286
1363
  this.fieldChanges.delete(tableName);
1287
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
+ }
1288
1374
  const columnNames = new Set(schema.columns.map((column) => column.name));
1289
1375
  const withUnknown = data.map((row) => Object.keys(row).some((key) => !columnNames.has(key)));
1290
1376
  if (transformedFields.some((fields) => fields.length > 0) || withUnknown.includes(true)) {
1291
1377
  const rowids = this.queryInternal(`SELECT rowid AS "${ROWID_ALIAS}" FROM ${this.quoteTableName(tableName)} ORDER BY rowid`);
1292
1378
  const lines = /* @__PURE__ */ new Map();
1293
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]));
1294
1381
  rowids.forEach((row, index) => {
1295
1382
  const rowid = row[ROWID_ALIAS];
1296
1383
  const origin = this.rowOriginsByRowid.get(tableName)?.get(String(rowid));
1297
- const sourceIndex = origin ? sourceIndexes.get(origin) ?? index : index;
1384
+ const sourceIndex = origin ? sourceIndexes.get(origin) ?? index : lineIndexes.get(String(rowid)) ?? index;
1298
1385
  const set = transformedFields[sourceIndex] ?? [];
1299
1386
  if (set.length > 0) this.noteFieldChanges(tableName, rowid, { set });
1300
1387
  if (withUnknown[sourceIndex]) lines.set(String(rowid), data[sourceIndex]);
@@ -1584,9 +1671,11 @@ var LinesDB = class LinesDB {
1584
1671
  try {
1585
1672
  return run();
1586
1673
  } finally {
1674
+ this.applyMovedRows();
1587
1675
  if (this.totalChanges() !== before) {
1588
1676
  for (const tableName of this.schemas.keys()) {
1589
1677
  this.rawSqlTables.add(tableName);
1678
+ this.linePositionsByRowid.delete(tableName);
1590
1679
  this.noteChange(tableName);
1591
1680
  }
1592
1681
  this.forgetLinesOfGoneRows(this.schemas.keys());
@@ -1763,8 +1852,10 @@ var LinesDB = class LinesDB {
1763
1852
  });
1764
1853
  this.rowOriginsByRowid.set(tableName, origins);
1765
1854
  }
1855
+ this.forgetPosition(tableName, String(result.lastInsertRowid));
1766
1856
  this.noteFieldChanges(tableName, result.lastInsertRowid, {
1767
1857
  set: givenFields(data),
1858
+ inputs: transformedInputs(data, row),
1768
1859
  inserted: true
1769
1860
  });
1770
1861
  this.afterWrite(tableName, result.changes);
@@ -1829,8 +1920,10 @@ var LinesDB = class LinesDB {
1829
1920
  undoSettle();
1830
1921
  throw error;
1831
1922
  }
1923
+ this.forgetPosition(tableName, String(result.lastInsertRowid));
1832
1924
  this.noteFieldChanges(tableName, result.lastInsertRowid, {
1833
1925
  set: givenFields(record),
1926
+ inputs: transformedInputs(record, row),
1834
1927
  inserted: true
1835
1928
  });
1836
1929
  totalChanges += BigInt(result.changes);
@@ -1860,44 +1953,58 @@ var LinesDB = class LinesDB {
1860
1953
  updateInternal(tableName, data, where, options) {
1861
1954
  this.assertMutable(tableName);
1862
1955
  if (!this.schemas.get(tableName)) throw new Error(`Table ${tableName} does not exist`);
1863
- const shouldValidate = options?.validate !== false;
1864
- const hasValidationSchema = this.validationSchemas.has(tableName);
1865
- if (shouldValidate && hasValidationSchema) {
1866
- const existingRows = this.findInternal(tableName, where);
1867
- for (const existingRow of existingRows) {
1868
- const mergedData = {
1869
- ...existingRow,
1870
- ...data
1871
- };
1872
- for (const field of options?.resetToDefault ?? []) delete mergedData[field];
1873
- this.validateData(tableName, mergedData);
1874
- }
1875
- }
1876
1956
  const { sql: whereSql, values: whereValues, functionFilters } = this.buildWhereClause(where, tableName);
1877
1957
  if (functionFilters.length > 0) throw new Error("Function filters are not supported in update operations");
1878
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);
1879
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
+ });
1880
1974
  const resets = resetFields.length > 0 ? this.computeResets(tableName, targets, data, resetFields) : [];
1881
1975
  let result = {
1882
1976
  changes: 0,
1883
1977
  lastInsertRowid: 0
1884
1978
  };
1885
- if (Object.keys(data).length > 0) {
1886
- const setClauses = Object.keys(data).map((key) => `${this.quoteIdentifier(key)} = ?`).join(", ");
1887
- const sql = `UPDATE ${this.quoteTableName(tableName)} SET ${setClauses} WHERE ${whereSql}`;
1888
- const values = [...Object.entries(data).map(([key, v]) => this.normalizeValue(v, this.columnOf(tableName, key))), ...whereValues];
1889
- 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");
1890
1986
  try {
1891
- 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");
1892
1993
  } catch (error) {
1994
+ this.db.exec("ROLLBACK TO lines_db_update");
1995
+ this.db.exec("RELEASE lines_db_update");
1893
1996
  undoSettle();
1894
1997
  throw error;
1895
1998
  }
1896
- if (Number(result.changes) === 0) undoSettle();
1999
+ result = {
2000
+ changes: Number(changes),
2001
+ lastInsertRowid
2002
+ };
2003
+ if (changes === 0n) undoSettle();
1897
2004
  }
1898
2005
  const pkName = this.schemas.get(tableName)?.columns.find((col) => col.primaryKey)?.name;
1899
2006
  if (pkName && Object.hasOwn(data, pkName)) {
1900
- 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))]);
1901
2008
  if (targets.length === 1 && moved.length === 1) {
1902
2009
  const from = String(targets[0][ROWID_ALIAS]);
1903
2010
  const to = moved[0][ROWID_ALIAS];
@@ -1910,10 +2017,14 @@ var LinesDB = class LinesDB {
1910
2017
  }
1911
2018
  }
1912
2019
  }
1913
- for (const target of targets) {
1914
- const set = Object.keys(data).filter((key) => !sameStoredValue(target[key], this.normalizeValue(data[key], this.columnOf(tableName, key))));
1915
- this.noteFieldChanges(tableName, target[ROWID_ALIAS], { set });
1916
- }
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
+ });
1917
2028
  if (resets.length > 0) result = this.applyResets(tableName, resets, resetFields);
1918
2029
  this.afterWrite(tableName, result.changes);
1919
2030
  return result;
@@ -2267,9 +2378,18 @@ var LinesDB = class LinesDB {
2267
2378
  this.assertWritable(tableName);
2268
2379
  const config = this.tables.get(tableName);
2269
2380
  if (!config) throw new Error(`Table ${tableName} not found`);
2381
+ this.positionEdits.set(tableName, []);
2270
2382
  const stored = this.readStoredRows(tableName);
2271
- if (!this.hasSeveralDataDirs()) return [await this.prepareFileWriteBack(tableName, config.jsonlPath, stored, options)];
2272
- 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;
2273
2393
  const byFile = new Map([this.config.dataDir].flat().map((dir) => [join(dir, `${tableName}.jsonl`), []]));
2274
2394
  stored.rowids.forEach((rowid, index) => {
2275
2395
  const origin = origins?.get(rowid);
@@ -2286,33 +2406,98 @@ var LinesDB = class LinesDB {
2286
2406
  rows: indexes.map((i) => stored.rows[i]),
2287
2407
  lineRows: indexes.map((i) => stored.lineRows[i])
2288
2408
  };
2289
- const fileWrite = await this.prepareFileWriteBack(tableName, file, rows, options);
2409
+ const fileWrite = await this.prepareFileWriteBack(tableName, file, rows, options, atRead);
2290
2410
  if (!fileWrite.unchanged) prepared.push(fileWrite);
2291
2411
  }
2292
2412
  return prepared;
2293
2413
  }
2294
- 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) {
2295
2467
  const { rowids, rows: deserializedRows, lineRows } = stored;
2296
- const generation = this.changeGenerations.get(tableName) ?? 0;
2468
+ const generation = atRead?.generation ?? this.changeGenerations.get(tableName) ?? 0;
2297
2469
  let finalRows = lineRows;
2298
2470
  const previousContent = await readFile(jsonlPath, "utf-8").catch((error) => {
2299
2471
  if (error.code === "ENOENT") return void 0;
2300
2472
  throw error;
2301
2473
  });
2302
2474
  const existingRows = await this.readUnchangedRows(jsonlPath);
2303
- 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;
2304
2483
  const fields = options?.fields ?? this.config.writeBackFields;
2305
- 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);
2306
2488
  const columns = new Set(this.schemas.get(tableName)?.columns.map((column) => column.name));
2307
- const readLines = this.linesWithUnknownFields.get(tableName);
2489
+ const readLines = atRead?.unknownFieldLines ?? this.linesWithUnknownFields.get(tableName);
2308
2490
  finalRows = finalRows.map((row, index) => {
2309
2491
  const line = readLines?.get(rowids[index]);
2310
2492
  return line ? keepUnknownFields(line, row, columns) : row;
2311
2493
  });
2494
+ let linesOfRows;
2312
2495
  finalRows = this.mergeWithExistingLines(tableName, existingRows, finalRows, {
2313
2496
  fields,
2314
2497
  strictFields: options?.strictFields ?? false,
2315
- matches
2498
+ matches,
2499
+ positionedLines,
2500
+ onMatched: (lines) => linesOfRows = lines
2316
2501
  });
2317
2502
  return {
2318
2503
  tableName,
@@ -2320,10 +2505,11 @@ var LinesDB = class LinesDB {
2320
2505
  rows: finalRows,
2321
2506
  previousContent,
2322
2507
  generation,
2323
- ...matches ? {
2508
+ ...matchedByOrigin ? {
2324
2509
  rowids,
2325
2510
  unchanged: JsonlWriter.serialize(existingRows) === JsonlWriter.serialize(finalRows)
2326
- } : {}
2511
+ } : {},
2512
+ ...this.tracksLinePositions(tableName) && !matchedByOrigin ? { positions: linesOfRows ? positionsAfterWrite(rowids, linesOfRows, existingRows) : new Map(rowids.map((rowid, position) => [rowid, position])) } : {}
2327
2513
  };
2328
2514
  }
2329
2515
  /**
@@ -2346,17 +2532,22 @@ var LinesDB = class LinesDB {
2346
2532
  * minus those reset to their default - its primary key and the fields named to be written back, so
2347
2533
  * a value the schema fills in stays out of the file
2348
2534
  */
2349
- keepWrittenFields(tableName, rowids, rows, lineRows, existingRows, namedFields = [], matchedLines) {
2535
+ keepWrittenFields(tableName, rowids, rows, lineRows, existingRows, namedFields = [], matchedLines, options) {
2350
2536
  const pkName = this.schemas.get(tableName)?.columns.find((col) => col.primaryKey)?.name;
2351
- const actionColumns = (this.schemas.get(tableName)?.foreignKeys ?? []).filter((fk) => [fk.onDelete, fk.onUpdate].some((action) => action === "CASCADE" || action === "SET NULL")).map((fk) => fk.column);
2352
- const lines = matchedLines ?? this.matchExistingRows(tableName, lineRows, existingRows, { required: false });
2353
- 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);
2354
2544
  return lineRows.map((lineRow, index) => {
2355
2545
  const line = lines?.[index];
2356
2546
  const rowChanges = changes?.get(rowids[index]);
2357
2547
  if (Object.keys(lineRow).some((key) => !Object.hasOwn(rows[index], key)) || this.rawSqlTables.has(tableName) || !line && !rowChanges?.inserted) return {
2358
2548
  written: lineRow,
2359
- narrowed: false
2549
+ narrowed: false,
2550
+ line
2360
2551
  };
2361
2552
  const keep = /* @__PURE__ */ new Set([
2362
2553
  ...Object.keys(line ?? {}),
@@ -2366,10 +2557,11 @@ var LinesDB = class LinesDB {
2366
2557
  for (const key of rowChanges?.reset ?? []) keep.delete(key);
2367
2558
  for (const key of namedFields) keep.add(key);
2368
2559
  if (pkName) keep.add(pkName);
2369
- 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);
2370
2561
  return {
2371
- 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])),
2372
- 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
2373
2565
  };
2374
2566
  });
2375
2567
  }
@@ -2381,10 +2573,15 @@ var LinesDB = class LinesDB {
2381
2573
  * later, which must not inherit them
2382
2574
  */
2383
2575
  moveRowMetadata(tableName, from, to) {
2576
+ this.positionEdits.get(tableName)?.push({
2577
+ from,
2578
+ to
2579
+ });
2384
2580
  for (const byRow of [
2385
2581
  this.fieldChanges.get(tableName),
2386
2582
  this.linesWithUnknownFields.get(tableName),
2387
- this.rowOriginsByRowid.get(tableName)
2583
+ this.rowOriginsByRowid.get(tableName),
2584
+ this.linePositionsByRowid.get(tableName)
2388
2585
  ]) {
2389
2586
  const kept = byRow?.get(from);
2390
2587
  if (!byRow || kept === void 0) continue;
@@ -2409,6 +2606,7 @@ var LinesDB = class LinesDB {
2409
2606
  }
2410
2607
  forgetFieldChanges(tableName, rowids) {
2411
2608
  for (const rowid of rowids) {
2609
+ this.forgetPosition(tableName, rowid);
2412
2610
  this.fieldChanges.get(tableName)?.delete(rowid);
2413
2611
  this.linesWithUnknownFields.get(tableName)?.delete(rowid);
2414
2612
  }
@@ -2428,10 +2626,16 @@ var LinesDB = class LinesDB {
2428
2626
  for (const key of changes.set ?? []) {
2429
2627
  rowChanges.set.add(key);
2430
2628
  rowChanges.reset.delete(key);
2629
+ rowChanges.inputs?.delete(key);
2431
2630
  }
2432
2631
  for (const key of changes.reset ?? []) {
2433
2632
  rowChanges.reset.add(key);
2434
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);
2435
2639
  }
2436
2640
  byRow.set(String(rowid), rowChanges);
2437
2641
  this.fieldChanges.set(tableName, byRow);
@@ -2472,25 +2676,49 @@ var LinesDB = class LinesDB {
2472
2676
  }
2473
2677
  /**
2474
2678
  * Every row of a table with the fields the schema filled in rather than the file: the ones its line
2475
- * 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.
2476
2681
  */
2477
2682
  async findWithDefaults(tableName) {
2478
2683
  try {
2479
2684
  const tableConfig = this.tables.get(tableName);
2480
2685
  if (!tableConfig || !this.schemas.has(tableName)) throw new Error(`Table '${tableName}' is not loaded`);
2481
- await this.waitForPendingSyncs();
2482
- const { rowids, rows, lineRows } = this.readStoredRows(tableName);
2483
- const fileRows = /* @__PURE__ */ new Map();
2484
- 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;
2485
2708
  const existingRows = [...fileRows.values()].flat();
2486
2709
  const matches = this.hasSeveralDataDirs() && this.config.writeDataSets ? rowids.map((rowid) => {
2487
2710
  const origin = this.rowOriginsByRowid.get(tableName)?.get(rowid);
2488
2711
  return origin && fileRows.get(origin.file)?.[origin.rowIndex];
2489
- }) : void 0;
2712
+ }) : linesByPosition(positionsAtRead, rowids, existingRows);
2490
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 });
2491
2715
  return ok(rows.map((row, index) => ({
2492
2716
  row,
2493
- 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
+ }
2494
2722
  })));
2495
2723
  } catch (error) {
2496
2724
  return err(toError(error));
@@ -2510,6 +2738,7 @@ var LinesDB = class LinesDB {
2510
2738
  * tables it changed once its callback is done
2511
2739
  */
2512
2740
  afterWrite(tableName, changes) {
2741
+ this.applyMovedRows();
2513
2742
  if (BigInt(changes) === 0n && this.transactionChanges) return;
2514
2743
  const tableNames = [tableName, ...this.tablesChangedByForeignKeyActions(tableName)];
2515
2744
  this.forgetLinesOfGoneRows(tableNames);
@@ -2563,17 +2792,20 @@ var LinesDB = class LinesDB {
2563
2792
  } catch (error) {
2564
2793
  throw await this.restoreAll(written, error);
2565
2794
  }
2566
- 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));
2567
2798
  if ((this.changeGenerations.get(tableName) ?? 0) === generation) {
2568
2799
  this.fieldChanges.delete(tableName);
2569
2800
  this.rawSqlTables.delete(tableName);
2570
2801
  }
2571
2802
  if (rowids) {
2572
2803
  const origins = this.rowOriginsByRowid.get(tableName);
2573
- rowids.forEach((rowid, rowIndex) => origins.set(rowid, {
2804
+ const writtenOrigins = new Map(rowids.map((rowid, rowIndex) => [rowid, {
2574
2805
  file: jsonlPath,
2575
2806
  rowIndex
2576
- }));
2807
+ }]));
2808
+ for (const [rowid, origin] of replayEdits(writtenOrigins, edits)) origins.set(rowid, origin);
2577
2809
  if (!this.scannedJsonlFiles.includes(jsonlPath)) this.scannedJsonlFiles.push(jsonlPath);
2578
2810
  }
2579
2811
  }
@@ -2641,7 +2873,11 @@ var LinesDB = class LinesDB {
2641
2873
  const unknownFields = fields.filter((field) => !tableFields.includes(field));
2642
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.`);
2643
2875
  }
2644
- 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);
2645
2881
  if (!existing) return rows;
2646
2882
  const rowByLine = /* @__PURE__ */ new Map();
2647
2883
  const newRows = [];
@@ -2659,20 +2895,41 @@ var LinesDB = class LinesDB {
2659
2895
  }), ...newRows];
2660
2896
  }
2661
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
+ /**
2662
2912
  * Pair each row with the JSONL line it came from, indexed the same way as `rows`.
2663
2913
  * Returns undefined when the rows cannot be matched and the caller can do without it.
2664
2914
  */
2665
2915
  matchExistingRows(tableName, rows, existingRows, options) {
2666
2916
  if (existingRows.length === 0) return rows.map(() => void 0);
2667
2917
  const pkName = this.schemas.get(tableName)?.columns.find((col) => col.primaryKey)?.name;
2668
- 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]) : [];
2669
2920
  if (pkName !== void 0 && pkValues.every((value) => value !== void 0 && value !== null) && new Set(pkValues.map((value) => String(value))).size === pkValues.length) {
2670
2921
  const byPk = new Map(existingRows.map((row, index) => [String(pkValues[index]), row]));
2671
- 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;
2672
2927
  const pkValue = row[pkName];
2673
- 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;
2674
2930
  });
2675
2931
  }
2932
+ if (options.positionedLines) return options.positionedLines;
2676
2933
  if (rows.length !== existingRows.length) {
2677
2934
  if (!options.required) return;
2678
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.`);
@@ -2834,6 +3091,7 @@ var LinesDB = class LinesDB {
2834
3091
  let fieldChangesBefore;
2835
3092
  let rawSqlTablesBefore;
2836
3093
  let linesWithUnknownFieldsBefore;
3094
+ let linePositionsBefore;
2837
3095
  let originsBefore;
2838
3096
  let columnsBefore;
2839
3097
  const scannedBefore = [...this.scannedJsonlFiles];
@@ -2845,6 +3103,7 @@ var LinesDB = class LinesDB {
2845
3103
  fieldChangesBefore = cloneFieldChanges(this.fieldChanges);
2846
3104
  rawSqlTablesBefore = new Set(this.rawSqlTables);
2847
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)]));
2848
3107
  this.db.exec("BEGIN TRANSACTION");
2849
3108
  this.settleUndos = [];
2850
3109
  this.inTransaction = true;
@@ -2875,6 +3134,7 @@ var LinesDB = class LinesDB {
2875
3134
  if (fieldChangesBefore) this.fieldChanges = fieldChangesBefore;
2876
3135
  if (rawSqlTablesBefore) this.rawSqlTables = rawSqlTablesBefore;
2877
3136
  if (linesWithUnknownFieldsBefore) this.linesWithUnknownFields = linesWithUnknownFieldsBefore;
3137
+ if (linePositionsBefore) this.linePositionsByRowid = linePositionsBefore;
2878
3138
  const failure = await this.restoreAll(written, error);
2879
3139
  if (this.inTransaction) try {
2880
3140
  this.db.exec("ROLLBACK");