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/dist/index.mjs CHANGED
@@ -436,15 +436,80 @@ function cloneFieldChanges(changes) {
436
436
  return new Map(Array.from(changes, ([tableName, byRow]) => [tableName, new Map(Array.from(byRow, ([rowid, row]) => [rowid, {
437
437
  set: new Set(row.set),
438
438
  reset: new Set(row.reset),
439
- inserted: row.inserted
439
+ inserted: row.inserted,
440
+ ...row.inputs ? { inputs: new Map(row.inputs) } : {}
440
441
  }]))]));
441
442
  }
443
+ /** The line of each row by the position recorded for it, undefined for a row that has none */
444
+ function linesByPosition(positions, rowids, existingRows) {
445
+ if (!positions) return void 0;
446
+ return rowids.map((rowid) => {
447
+ const position = positions.get(rowid);
448
+ return position === void 0 ? void 0 : existingRows[position];
449
+ });
450
+ }
451
+ /**
452
+ * Where each row's line stands in a file once it is written: the lines of rows that kept one stay in order,
453
+ * and a row without one goes after them, in the order the rows are given
454
+ */
455
+ function positionsAfterWrite(rowids, matches, existingRows) {
456
+ const kept = new Set(matches.filter((line) => line !== void 0));
457
+ const positionOfLine = /* @__PURE__ */ new Map();
458
+ existingRows.filter((line) => kept.has(line)).forEach((line, position) => positionOfLine.set(line, position));
459
+ let next = positionOfLine.size;
460
+ return new Map(rowids.map((rowid, index) => {
461
+ const line = matches[index];
462
+ return [rowid, line === void 0 ? next++ : positionOfLine.get(line)];
463
+ }));
464
+ }
465
+ /**
466
+ * What was kept by rowid when a write-back read its rows, brought up to date with the changes made since, in order:
467
+ * a deleted or reused rowid loses what it had, and a row that moved carries it to its new rowid
468
+ */
469
+ function replayEdits(byRowid, edits) {
470
+ for (const edit of edits) {
471
+ if ("forget" in edit) {
472
+ byRowid.delete(edit.forget);
473
+ continue;
474
+ }
475
+ const kept = byRowid.get(edit.from);
476
+ if (kept === void 0) continue;
477
+ byRowid.delete(edit.from);
478
+ byRowid.set(edit.to, kept);
479
+ }
480
+ return byRowid;
481
+ }
482
+ /**
483
+ * The temporary table the rowid changes of rows are logged to. Not qualified with `temp.`: SQLite before 3.53, as Bun
484
+ * ships, refuses a qualified table name in a trigger body, and an unqualified one is looked up in `temp` first
485
+ */
486
+ const MOVED_ROWS_LOG = "\"__lines_db_moved_rows\"";
442
487
  /** Column alias a query reads a row's rowid under, next to its fields */
443
488
  const ROWID_ALIAS = "__lines_db_rowid";
444
489
  /** The fields a row given to an insert names, leaving out those it leaves undefined */
445
490
  function givenFields(row) {
446
491
  return Object.entries(row).filter(([, value]) => value !== void 0).map(([key]) => key);
447
492
  }
493
+ /** Whether two values read the same once written as JSON; a bigint reads as its digits, which JSON.stringify refuses */
494
+ function sameValue(a, b) {
495
+ const text = (value) => JSON.stringify(value, (_key, item) => typeof item === "bigint" ? String(item) : item);
496
+ return text(a) === text(b);
497
+ }
498
+ /** Whether a value is a bigint or holds one at any depth, which a JSONL line cannot hold */
499
+ function holdsBigint(value) {
500
+ if (typeof value === "bigint") return true;
501
+ if (Array.isArray(value)) return value.some(holdsBigint);
502
+ return value !== null && typeof value === "object" && Object.values(value).some(holdsBigint);
503
+ }
504
+ /**
505
+ * The values of a row given to an insert that the stored row holds differently, after the schema transformed
506
+ * them. A value holding a bigint is left out: a line cannot hold one, so the row keeps the value the schema
507
+ * made of it
508
+ */
509
+ function transformedInputs(given, stored) {
510
+ const inputs = new Map(Object.entries(given).filter(([key, value]) => value !== void 0 && !holdsBigint(value) && !sameValue(value, stored[key])).map(([key, value]) => [key, structuredClone(value)]));
511
+ return inputs.size > 0 ? inputs : void 0;
512
+ }
448
513
  /** Whether a value read from SQLite and one about to be stored are the same */
449
514
  function sameStoredValue(stored, next) {
450
515
  if (stored === null || stored === void 0 || next === null) return (stored ?? null) === next;
@@ -481,6 +546,18 @@ var LinesDB = class LinesDB {
481
546
  * back, also once the row's primary key changed and its line can no longer be found by it
482
547
  */
483
548
  linesWithUnknownFields = /* @__PURE__ */ new Map();
549
+ /**
550
+ * For a table without a primary key, where each row's line stands in its file: the rows cannot be
551
+ * matched to their lines by key, and by order only while none is added or removed
552
+ */
553
+ linePositionsByRowid = /* @__PURE__ */ new Map();
554
+ /**
555
+ * What happened to the positions of a table's rows since its rows were read for its write-back, in order: the
556
+ * positions that write-back computes describe the rows as they were, and are brought up to date with these
557
+ */
558
+ positionEdits = /* @__PURE__ */ new Map();
559
+ /** Whether the temporary table that triggers log the rowid changes of rows to exists */
560
+ movedRowsLogReady = false;
484
561
  /** Whether a transaction's callback has returned and its files are being written back */
485
562
  transactionClosing = false;
486
563
  /** Whether a transaction() call is past its guard but has not begun yet */
@@ -847,16 +924,26 @@ var LinesDB = class LinesDB {
847
924
  } else this.insertData(tableName, schema, validatedData);
848
925
  this.fieldChanges.delete(tableName);
849
926
  this.linesWithUnknownFields.delete(tableName);
927
+ this.linePositionsByRowid.delete(tableName);
928
+ if (this.tracksLinePositions(tableName)) {
929
+ this.logMovedRows(tableName);
930
+ const positions = /* @__PURE__ */ new Map();
931
+ this.rowidsInLineOrder(tableName, validatedData).forEach((rowid, index) => {
932
+ if (rowid !== void 0) positions.set(rowid, index);
933
+ });
934
+ this.linePositionsByRowid.set(tableName, positions);
935
+ }
850
936
  const columnNames = new Set(schema.columns.map((column) => column.name));
851
937
  const withUnknown = data.map((row) => Object.keys(row).some((key) => !columnNames.has(key)));
852
938
  if (transformedFields.some((fields) => fields.length > 0) || withUnknown.includes(true)) {
853
939
  const rowids = this.queryInternal(`SELECT rowid AS "${ROWID_ALIAS}" FROM ${this.quoteTableName(tableName)} ORDER BY rowid`);
854
940
  const lines = /* @__PURE__ */ new Map();
855
941
  const sourceIndexes = new Map(origins.map((origin, index) => [origin, index]));
942
+ const lineIndexes = new Map(this.rowidsInLineOrder(tableName, validatedData).map((rowid, index) => [rowid, index]));
856
943
  rowids.forEach((row, index) => {
857
944
  const rowid = row[ROWID_ALIAS];
858
945
  const origin = this.rowOriginsByRowid.get(tableName)?.get(String(rowid));
859
- const sourceIndex = origin ? sourceIndexes.get(origin) ?? index : index;
946
+ const sourceIndex = origin ? sourceIndexes.get(origin) ?? index : lineIndexes.get(String(rowid)) ?? index;
860
947
  const set = transformedFields[sourceIndex] ?? [];
861
948
  if (set.length > 0) this.noteFieldChanges(tableName, rowid, { set });
862
949
  if (withUnknown[sourceIndex]) lines.set(String(rowid), data[sourceIndex]);
@@ -1146,9 +1233,11 @@ var LinesDB = class LinesDB {
1146
1233
  try {
1147
1234
  return run();
1148
1235
  } finally {
1236
+ this.applyMovedRows();
1149
1237
  if (this.totalChanges() !== before) {
1150
1238
  for (const tableName of this.schemas.keys()) {
1151
1239
  this.rawSqlTables.add(tableName);
1240
+ this.linePositionsByRowid.delete(tableName);
1152
1241
  this.noteChange(tableName);
1153
1242
  }
1154
1243
  this.forgetLinesOfGoneRows(this.schemas.keys());
@@ -1325,8 +1414,10 @@ var LinesDB = class LinesDB {
1325
1414
  });
1326
1415
  this.rowOriginsByRowid.set(tableName, origins);
1327
1416
  }
1417
+ this.forgetPosition(tableName, String(result.lastInsertRowid));
1328
1418
  this.noteFieldChanges(tableName, result.lastInsertRowid, {
1329
1419
  set: givenFields(data),
1420
+ inputs: transformedInputs(data, row),
1330
1421
  inserted: true
1331
1422
  });
1332
1423
  this.afterWrite(tableName, result.changes);
@@ -1391,8 +1482,10 @@ var LinesDB = class LinesDB {
1391
1482
  undoSettle();
1392
1483
  throw error;
1393
1484
  }
1485
+ this.forgetPosition(tableName, String(result.lastInsertRowid));
1394
1486
  this.noteFieldChanges(tableName, result.lastInsertRowid, {
1395
1487
  set: givenFields(record),
1488
+ inputs: transformedInputs(record, row),
1396
1489
  inserted: true
1397
1490
  });
1398
1491
  totalChanges += BigInt(result.changes);
@@ -1422,44 +1515,58 @@ var LinesDB = class LinesDB {
1422
1515
  updateInternal(tableName, data, where, options) {
1423
1516
  this.assertMutable(tableName);
1424
1517
  if (!this.schemas.get(tableName)) throw new Error(`Table ${tableName} does not exist`);
1425
- const shouldValidate = options?.validate !== false;
1426
- const hasValidationSchema = this.validationSchemas.has(tableName);
1427
- if (shouldValidate && hasValidationSchema) {
1428
- const existingRows = this.findInternal(tableName, where);
1429
- for (const existingRow of existingRows) {
1430
- const mergedData = {
1431
- ...existingRow,
1432
- ...data
1433
- };
1434
- for (const field of options?.resetToDefault ?? []) delete mergedData[field];
1435
- this.validateData(tableName, mergedData);
1436
- }
1437
- }
1438
1518
  const { sql: whereSql, values: whereValues, functionFilters } = this.buildWhereClause(where, tableName);
1439
1519
  if (functionFilters.length > 0) throw new Error("Function filters are not supported in update operations");
1440
1520
  const targets = this.queryInternal(`SELECT rowid AS "${ROWID_ALIAS}", * FROM ${this.quoteTableName(tableName)} WHERE ${whereSql}`, whereValues);
1521
+ const shouldValidate = options?.validate !== false;
1522
+ const hasValidationSchema = this.validationSchemas.has(tableName);
1523
+ const givenKeys = Object.keys(data);
1441
1524
  const resetFields = options?.resetToDefault ?? [];
1525
+ const storedValues = targets.map((target) => {
1526
+ if (!shouldValidate || !hasValidationSchema) return data;
1527
+ const { [ROWID_ALIAS]: _rowid, ...stored } = target;
1528
+ const merged = {
1529
+ ...this.deserializeRow(tableName, stored),
1530
+ ...data
1531
+ };
1532
+ for (const field of resetFields) delete merged[field];
1533
+ const validated = this.validateAndTransform(tableName, merged);
1534
+ return Object.fromEntries(givenKeys.map((key) => [key, Object.hasOwn(validated, key) ? validated[key] : data[key]]));
1535
+ });
1442
1536
  const resets = resetFields.length > 0 ? this.computeResets(tableName, targets, data, resetFields) : [];
1443
1537
  let result = {
1444
1538
  changes: 0,
1445
1539
  lastInsertRowid: 0
1446
1540
  };
1447
- if (Object.keys(data).length > 0) {
1448
- const setClauses = Object.keys(data).map((key) => `${this.quoteIdentifier(key)} = ?`).join(", ");
1449
- const sql = `UPDATE ${this.quoteTableName(tableName)} SET ${setClauses} WHERE ${whereSql}`;
1450
- const values = [...Object.entries(data).map(([key, v]) => this.normalizeValue(v, this.columnOf(tableName, key))), ...whereValues];
1451
- const undoSettle = this.settleColumnsNoRowHolds(this.schemas.get(tableName), data);
1541
+ if (givenKeys.length > 0 && targets.length > 0) {
1542
+ const setClauses = givenKeys.map((key) => `${this.quoteIdentifier(key)} = ?`).join(", ");
1543
+ const sql = `UPDATE ${this.quoteTableName(tableName)} SET ${setClauses} WHERE rowid = ?`;
1544
+ const undoSettle = this.settleColumnsNoRowHolds(this.schemas.get(tableName), storedValues[0]);
1545
+ let changes = 0n;
1546
+ let lastInsertRowid = 0;
1547
+ this.db.exec("SAVEPOINT lines_db_update");
1452
1548
  try {
1453
- result = this.executeInternal(sql, values);
1549
+ targets.forEach((target, index) => {
1550
+ const written = this.executeInternal(sql, [...givenKeys.map((key) => this.normalizeValue(storedValues[index][key], this.columnOf(tableName, key))), target[ROWID_ALIAS]]);
1551
+ changes += BigInt(written.changes);
1552
+ lastInsertRowid = written.lastInsertRowid;
1553
+ });
1554
+ this.db.exec("RELEASE lines_db_update");
1454
1555
  } catch (error) {
1556
+ this.db.exec("ROLLBACK TO lines_db_update");
1557
+ this.db.exec("RELEASE lines_db_update");
1455
1558
  undoSettle();
1456
1559
  throw error;
1457
1560
  }
1458
- if (Number(result.changes) === 0) undoSettle();
1561
+ result = {
1562
+ changes: Number(changes),
1563
+ lastInsertRowid
1564
+ };
1565
+ if (changes === 0n) undoSettle();
1459
1566
  }
1460
1567
  const pkName = this.schemas.get(tableName)?.columns.find((col) => col.primaryKey)?.name;
1461
1568
  if (pkName && Object.hasOwn(data, pkName)) {
1462
- const moved = this.queryInternal(`SELECT rowid AS "${ROWID_ALIAS}" FROM ${this.quoteTableName(tableName)} WHERE ${this.quoteIdentifier(pkName)} = ?`, [this.normalizeValue(data[pkName], this.columnOf(tableName, pkName))]);
1569
+ const moved = this.queryInternal(`SELECT rowid AS "${ROWID_ALIAS}" FROM ${this.quoteTableName(tableName)} WHERE ${this.quoteIdentifier(pkName)} = ?`, [this.normalizeValue((storedValues[0] ?? data)[pkName], this.columnOf(tableName, pkName))]);
1463
1570
  if (targets.length === 1 && moved.length === 1) {
1464
1571
  const from = String(targets[0][ROWID_ALIAS]);
1465
1572
  const to = moved[0][ROWID_ALIAS];
@@ -1472,10 +1579,14 @@ var LinesDB = class LinesDB {
1472
1579
  }
1473
1580
  }
1474
1581
  }
1475
- for (const target of targets) {
1476
- const set = Object.keys(data).filter((key) => !sameStoredValue(target[key], this.normalizeValue(data[key], this.columnOf(tableName, key))));
1477
- this.noteFieldChanges(tableName, target[ROWID_ALIAS], { set });
1478
- }
1582
+ targets.forEach((target, index) => {
1583
+ const set = givenKeys.filter((key) => !sameStoredValue(target[key], this.normalizeValue(storedValues[index][key], this.columnOf(tableName, key))));
1584
+ const given = Object.fromEntries(set.map((key) => [key, data[key]]));
1585
+ this.noteFieldChanges(tableName, target[ROWID_ALIAS], {
1586
+ set,
1587
+ inputs: transformedInputs(given, storedValues[index])
1588
+ });
1589
+ });
1479
1590
  if (resets.length > 0) result = this.applyResets(tableName, resets, resetFields);
1480
1591
  this.afterWrite(tableName, result.changes);
1481
1592
  return result;
@@ -1829,9 +1940,18 @@ var LinesDB = class LinesDB {
1829
1940
  this.assertWritable(tableName);
1830
1941
  const config = this.tables.get(tableName);
1831
1942
  if (!config) throw new Error(`Table ${tableName} not found`);
1943
+ this.positionEdits.set(tableName, []);
1832
1944
  const stored = this.readStoredRows(tableName);
1833
- if (!this.hasSeveralDataDirs()) return [await this.prepareFileWriteBack(tableName, config.jsonlPath, stored, options)];
1834
- const origins = this.rowOriginsByRowid.get(tableName);
1945
+ const recorded = this.linePositionsByRowid.get(tableName);
1946
+ const atRead = {
1947
+ generation: this.changeGenerations.get(tableName) ?? 0,
1948
+ positions: recorded && new Map(recorded),
1949
+ origins: new Map(this.rowOriginsByRowid.get(tableName) ?? []),
1950
+ changes: cloneFieldChanges(/* @__PURE__ */ new Map([[tableName, this.fieldChanges.get(tableName) ?? /* @__PURE__ */ new Map()]])).get(tableName),
1951
+ unknownFieldLines: new Map(this.linesWithUnknownFields.get(tableName) ?? [])
1952
+ };
1953
+ if (!this.hasSeveralDataDirs()) return [await this.prepareFileWriteBack(tableName, config.jsonlPath, stored, options, atRead)];
1954
+ const origins = atRead.origins;
1835
1955
  const byFile = new Map([this.config.dataDir].flat().map((dir) => [join(dir, `${tableName}.jsonl`), []]));
1836
1956
  stored.rowids.forEach((rowid, index) => {
1837
1957
  const origin = origins?.get(rowid);
@@ -1848,33 +1968,98 @@ var LinesDB = class LinesDB {
1848
1968
  rows: indexes.map((i) => stored.rows[i]),
1849
1969
  lineRows: indexes.map((i) => stored.lineRows[i])
1850
1970
  };
1851
- const fileWrite = await this.prepareFileWriteBack(tableName, file, rows, options);
1971
+ const fileWrite = await this.prepareFileWriteBack(tableName, file, rows, options, atRead);
1852
1972
  if (!fileWrite.unchanged) prepared.push(fileWrite);
1853
1973
  }
1854
1974
  return prepared;
1855
1975
  }
1856
- async prepareFileWriteBack(tableName, jsonlPath, stored, options) {
1976
+ forgetPosition(tableName, rowid) {
1977
+ this.linePositionsByRowid.get(tableName)?.delete(rowid);
1978
+ this.positionEdits.get(tableName)?.push({ forget: rowid });
1979
+ }
1980
+ /**
1981
+ * The rowid of the row each line was loaded into, in the order of the lines. Not the rowid order: an INTEGER
1982
+ * PRIMARY KEY is the rowid, so the line `{"id":3}` first in its file is the row with rowid 3
1983
+ */
1984
+ rowidsInLineOrder(tableName, rows) {
1985
+ const pk = this.schemas.get(tableName)?.columns.find((column) => column.primaryKey);
1986
+ const stored = this.queryInternal(`SELECT rowid AS "${ROWID_ALIAS}" FROM ${this.quoteTableName(tableName)} ORDER BY rowid`).map((row) => String(row[ROWID_ALIAS]));
1987
+ if (pk?.type !== "INTEGER") return stored;
1988
+ const present = new Set(stored);
1989
+ let largest;
1990
+ return rows.map((row) => {
1991
+ const key = row[pk.name];
1992
+ const rowid = key === void 0 || key === null ? (largest ?? 0) + 1 : Number(key);
1993
+ largest = largest === void 0 ? rowid : Math.max(largest, rowid);
1994
+ return present.has(String(rowid)) ? String(rowid) : void 0;
1995
+ });
1996
+ }
1997
+ /**
1998
+ * Log each change of a row's rowid in the table: a foreign-key action or raw SQL can change an INTEGER PRIMARY
1999
+ * KEY, which is the rowid, without a write through this database telling it which row moved
2000
+ */
2001
+ logMovedRows(tableName) {
2002
+ if (!this.movedRowsLogReady) {
2003
+ this.db.exec(`CREATE TEMP TABLE IF NOT EXISTS ${MOVED_ROWS_LOG} (tbl TEXT, old INTEGER, new INTEGER)`);
2004
+ this.movedRowsLogReady = true;
2005
+ }
2006
+ const trigger = this.quoteIdentifier(`__lines_db_moved_${tableName}`);
2007
+ const name = `'${tableName.replace(/'/g, "''")}'`;
2008
+ this.db.exec(`CREATE TEMP TRIGGER IF NOT EXISTS ${trigger} AFTER UPDATE ON main.${this.quoteTableName(tableName)} WHEN old.rowid IS NOT new.rowid BEGIN INSERT INTO ${MOVED_ROWS_LOG} VALUES (${name}, old.rowid, new.rowid); END`);
2009
+ }
2010
+ /** Move what is kept by rowid to the rowid each logged row moved to, in the order the rows moved */
2011
+ applyMovedRows() {
2012
+ if (!this.movedRowsLogReady) return;
2013
+ const moved = this.queryInternal(`SELECT tbl, old, new FROM ${MOVED_ROWS_LOG} ORDER BY rowid`);
2014
+ if (moved.length === 0) return;
2015
+ this.db.exec(`DELETE FROM ${MOVED_ROWS_LOG}`);
2016
+ for (const { tbl, old, new: to } of moved) this.moveRowMetadata(String(tbl), String(old), String(to));
2017
+ }
2018
+ /**
2019
+ * Whether the lines of a table are remembered by position, so a row whose key changed, or that has none, is
2020
+ * found again by where its line stood. Several data directories have the origin of each row instead
2021
+ */
2022
+ tracksLinePositions(_tableName) {
2023
+ return !this.hasSeveralDataDirs();
2024
+ }
2025
+ hasNoPrimaryKey(tableName) {
2026
+ return this.schemas.get(tableName)?.columns.some((column) => column.primaryKey) === false;
2027
+ }
2028
+ async prepareFileWriteBack(tableName, jsonlPath, stored, options, atRead) {
1857
2029
  const { rowids, rows: deserializedRows, lineRows } = stored;
1858
- const generation = this.changeGenerations.get(tableName) ?? 0;
2030
+ const generation = atRead?.generation ?? this.changeGenerations.get(tableName) ?? 0;
1859
2031
  let finalRows = lineRows;
1860
2032
  const previousContent = await readFile(jsonlPath, "utf-8").catch((error) => {
1861
2033
  if (error.code === "ENOENT") return void 0;
1862
2034
  throw error;
1863
2035
  });
1864
2036
  const existingRows = await this.readUnchangedRows(jsonlPath);
1865
- const matches = this.hasSeveralDataDirs() ? rowids.map((rowid) => existingRows[this.rowOriginsByRowid.get(tableName).get(rowid).rowIndex]) : void 0;
2037
+ const origins = atRead?.origins ?? this.rowOriginsByRowid.get(tableName);
2038
+ const matchedByOrigin = this.hasSeveralDataDirs() ? rowids.map((rowid) => {
2039
+ const origin = origins?.get(rowid);
2040
+ return origin && existingRows[origin.rowIndex];
2041
+ }) : void 0;
2042
+ const byPosition = matchedByOrigin ? void 0 : linesByPosition(atRead?.positions, rowids, existingRows);
2043
+ const matches = matchedByOrigin ?? (this.hasNoPrimaryKey(tableName) ? byPosition : void 0);
2044
+ const positionedLines = matches ? void 0 : byPosition;
1866
2045
  const fields = options?.fields ?? this.config.writeBackFields;
1867
- if ((options?.writeFilledValues ?? this.config.writeFilledValues ?? "all") === "primaryKey") finalRows = this.keepWrittenFields(tableName, rowids, deserializedRows, finalRows, existingRows, fields, matches).map(({ written }) => written);
2046
+ if ((options?.writeFilledValues ?? this.config.writeFilledValues ?? "all") === "primaryKey") finalRows = this.keepWrittenFields(tableName, rowids, deserializedRows, finalRows, existingRows, fields, matches, {
2047
+ positionedLines,
2048
+ changes: atRead?.changes
2049
+ }).map(({ written }) => written);
1868
2050
  const columns = new Set(this.schemas.get(tableName)?.columns.map((column) => column.name));
1869
- const readLines = this.linesWithUnknownFields.get(tableName);
2051
+ const readLines = atRead?.unknownFieldLines ?? this.linesWithUnknownFields.get(tableName);
1870
2052
  finalRows = finalRows.map((row, index) => {
1871
2053
  const line = readLines?.get(rowids[index]);
1872
2054
  return line ? keepUnknownFields(line, row, columns) : row;
1873
2055
  });
2056
+ let linesOfRows;
1874
2057
  finalRows = this.mergeWithExistingLines(tableName, existingRows, finalRows, {
1875
2058
  fields,
1876
2059
  strictFields: options?.strictFields ?? false,
1877
- matches
2060
+ matches,
2061
+ positionedLines,
2062
+ onMatched: (lines) => linesOfRows = lines
1878
2063
  });
1879
2064
  return {
1880
2065
  tableName,
@@ -1882,10 +2067,11 @@ var LinesDB = class LinesDB {
1882
2067
  rows: finalRows,
1883
2068
  previousContent,
1884
2069
  generation,
1885
- ...matches ? {
2070
+ ...matchedByOrigin ? {
1886
2071
  rowids,
1887
2072
  unchanged: JsonlWriter.serialize(existingRows) === JsonlWriter.serialize(finalRows)
1888
- } : {}
2073
+ } : {},
2074
+ ...this.tracksLinePositions(tableName) && !matchedByOrigin ? { positions: linesOfRows ? positionsAfterWrite(rowids, linesOfRows, existingRows) : new Map(rowids.map((rowid, position) => [rowid, position])) } : {}
1889
2075
  };
1890
2076
  }
1891
2077
  /**
@@ -1908,17 +2094,22 @@ var LinesDB = class LinesDB {
1908
2094
  * minus those reset to their default - its primary key and the fields named to be written back, so
1909
2095
  * a value the schema fills in stays out of the file
1910
2096
  */
1911
- keepWrittenFields(tableName, rowids, rows, lineRows, existingRows, namedFields = [], matchedLines) {
2097
+ keepWrittenFields(tableName, rowids, rows, lineRows, existingRows, namedFields = [], matchedLines, options) {
1912
2098
  const pkName = this.schemas.get(tableName)?.columns.find((col) => col.primaryKey)?.name;
1913
- const actionColumns = (this.schemas.get(tableName)?.foreignKeys ?? []).filter((fk) => [fk.onDelete, fk.onUpdate].some((action) => action === "CASCADE" || action === "SET NULL")).map((fk) => fk.column);
1914
- const lines = matchedLines ?? this.matchExistingRows(tableName, lineRows, existingRows, { required: false });
1915
- const changes = this.fieldChanges.get(tableName);
2099
+ const actionColumns = options?.ignoreActions ? [] : (this.schemas.get(tableName)?.foreignKeys ?? []).filter((fk) => [fk.onDelete, fk.onUpdate].some((action) => action === "CASCADE" || action === "SET NULL")).map((fk) => fk.column);
2100
+ const lines = matchedLines ?? this.matchExistingRows(tableName, lineRows, existingRows, {
2101
+ required: false,
2102
+ byOutputKey: true,
2103
+ positionedLines: options?.positionedLines
2104
+ });
2105
+ const changes = options?.changes ?? this.fieldChanges.get(tableName);
1916
2106
  return lineRows.map((lineRow, index) => {
1917
2107
  const line = lines?.[index];
1918
2108
  const rowChanges = changes?.get(rowids[index]);
1919
2109
  if (Object.keys(lineRow).some((key) => !Object.hasOwn(rows[index], key)) || this.rawSqlTables.has(tableName) || !line && !rowChanges?.inserted) return {
1920
2110
  written: lineRow,
1921
- narrowed: false
2111
+ narrowed: false,
2112
+ line
1922
2113
  };
1923
2114
  const keep = /* @__PURE__ */ new Set([
1924
2115
  ...Object.keys(line ?? {}),
@@ -1928,10 +2119,11 @@ var LinesDB = class LinesDB {
1928
2119
  for (const key of rowChanges?.reset ?? []) keep.delete(key);
1929
2120
  for (const key of namedFields) keep.add(key);
1930
2121
  if (pkName) keep.add(pkName);
1931
- const untouched = line !== void 0 && !rowChanges?.inserted && !rowChanges?.set.size && !rowChanges?.reset.size;
2122
+ const untouched = (key) => line !== void 0 && !rowChanges?.inserted && Object.hasOwn(line, key) && !rowChanges?.set.has(key) && !rowChanges?.reset.has(key);
1932
2123
  return {
1933
- written: Object.fromEntries(Object.entries(lineRow).filter(([key]) => keep.has(key)).map(([key, value]) => [key, untouched && Object.hasOwn(line, key) && !actionColumns.includes(key) && !namedFields.includes(key) ? line[key] : value])),
1934
- narrowed: true
2124
+ written: Object.fromEntries(Object.entries(lineRow).filter(([key]) => keep.has(key)).map(([key, value]) => [key, untouched(key) && !actionColumns.includes(key) && !namedFields.includes(key) ? line[key] : rowChanges?.inputs?.has(key) && !actionColumns.includes(key) && !namedFields.includes(key) ? rowChanges.inputs.get(key) : value])),
2125
+ narrowed: true,
2126
+ line
1935
2127
  };
1936
2128
  });
1937
2129
  }
@@ -1943,10 +2135,15 @@ var LinesDB = class LinesDB {
1943
2135
  * later, which must not inherit them
1944
2136
  */
1945
2137
  moveRowMetadata(tableName, from, to) {
2138
+ this.positionEdits.get(tableName)?.push({
2139
+ from,
2140
+ to
2141
+ });
1946
2142
  for (const byRow of [
1947
2143
  this.fieldChanges.get(tableName),
1948
2144
  this.linesWithUnknownFields.get(tableName),
1949
- this.rowOriginsByRowid.get(tableName)
2145
+ this.rowOriginsByRowid.get(tableName),
2146
+ this.linePositionsByRowid.get(tableName)
1950
2147
  ]) {
1951
2148
  const kept = byRow?.get(from);
1952
2149
  if (!byRow || kept === void 0) continue;
@@ -1971,6 +2168,7 @@ var LinesDB = class LinesDB {
1971
2168
  }
1972
2169
  forgetFieldChanges(tableName, rowids) {
1973
2170
  for (const rowid of rowids) {
2171
+ this.forgetPosition(tableName, rowid);
1974
2172
  this.fieldChanges.get(tableName)?.delete(rowid);
1975
2173
  this.linesWithUnknownFields.get(tableName)?.delete(rowid);
1976
2174
  }
@@ -1990,10 +2188,16 @@ var LinesDB = class LinesDB {
1990
2188
  for (const key of changes.set ?? []) {
1991
2189
  rowChanges.set.add(key);
1992
2190
  rowChanges.reset.delete(key);
2191
+ rowChanges.inputs?.delete(key);
1993
2192
  }
1994
2193
  for (const key of changes.reset ?? []) {
1995
2194
  rowChanges.reset.add(key);
1996
2195
  rowChanges.set.delete(key);
2196
+ rowChanges.inputs?.delete(key);
2197
+ }
2198
+ for (const [key, value] of changes.inputs ?? []) {
2199
+ rowChanges.inputs ??= /* @__PURE__ */ new Map();
2200
+ rowChanges.inputs.set(key, value);
1997
2201
  }
1998
2202
  byRow.set(String(rowid), rowChanges);
1999
2203
  this.fieldChanges.set(tableName, byRow);
@@ -2034,25 +2238,49 @@ var LinesDB = class LinesDB {
2034
2238
  }
2035
2239
  /**
2036
2240
  * Every row of a table with the fields the schema filled in rather than the file: the ones its line
2037
- * does not hold and no write set, which a write-back leaves out of the file
2241
+ * does not hold and no write set, which a write-back leaves out of the file. `input` is the row as
2242
+ * its line holds it - the values before the schema transformed them, without the defaulted fields.
2038
2243
  */
2039
2244
  async findWithDefaults(tableName) {
2040
2245
  try {
2041
2246
  const tableConfig = this.tables.get(tableName);
2042
2247
  if (!tableConfig || !this.schemas.has(tableName)) throw new Error(`Table '${tableName}' is not loaded`);
2043
- await this.waitForPendingSyncs();
2044
- const { rowids, rows, lineRows } = this.readStoredRows(tableName);
2045
- const fileRows = /* @__PURE__ */ new Map();
2046
- for (const file of this.hasSeveralDataDirs() ? /* @__PURE__ */ new Set([...tableConfig.jsonlPaths ?? [tableConfig.jsonlPath], ...[...this.rowOriginsByRowid.get(tableName)?.values() ?? []].map((origin) => origin.file)]) : [tableConfig.jsonlPath]) fileRows.set(file, await this.readUnchangedRows(file));
2248
+ let stored;
2249
+ let positionsAtRead;
2250
+ let fileRows;
2251
+ for (let attempt = 1;; attempt++) {
2252
+ await this.waitForPendingSyncs();
2253
+ const files = this.hasSeveralDataDirs() ? [.../* @__PURE__ */ new Set([...tableConfig.jsonlPaths ?? [tableConfig.jsonlPath], ...[...this.rowOriginsByRowid.get(tableName)?.values() ?? []].map((origin) => origin.file)])] : [tableConfig.jsonlPath];
2254
+ const generation = this.changeGenerations.get(tableName) ?? 0;
2255
+ const hashes = files.map((file) => this.fileHashes.get(file));
2256
+ stored = this.readStoredRows(tableName);
2257
+ const recorded = this.linePositionsByRowid.get(tableName);
2258
+ positionsAtRead = recorded && new Map(recorded);
2259
+ fileRows = /* @__PURE__ */ new Map();
2260
+ const unchanged = () => (this.changeGenerations.get(tableName) ?? 0) === generation && files.every((file, index) => this.fileHashes.get(file) === hashes[index]);
2261
+ try {
2262
+ for (const file of files) fileRows.set(file, await this.readUnchangedRows(file));
2263
+ } catch (error) {
2264
+ if (!(error instanceof Error && error.name === "JsonlConflictError") || unchanged()) throw error;
2265
+ }
2266
+ if (unchanged()) break;
2267
+ if (attempt >= 5) throw new Error(`The rows of '${tableName}' kept changing while they were read; read them again`);
2268
+ }
2269
+ const { rowids, rows, lineRows } = stored;
2047
2270
  const existingRows = [...fileRows.values()].flat();
2048
2271
  const matches = this.hasSeveralDataDirs() && this.config.writeDataSets ? rowids.map((rowid) => {
2049
2272
  const origin = this.rowOriginsByRowid.get(tableName)?.get(rowid);
2050
2273
  return origin && fileRows.get(origin.file)?.[origin.rowIndex];
2051
- }) : void 0;
2274
+ }) : linesByPosition(positionsAtRead, rowids, existingRows);
2052
2275
  const kept = this.keepWrittenFields(tableName, rowids, rows, lineRows, existingRows, this.config.writeBackFields, matches);
2276
+ const lines = this.keepWrittenFields(tableName, rowids, rows, lineRows, existingRows, [], matches, { ignoreActions: true });
2053
2277
  return ok(rows.map((row, index) => ({
2054
2278
  row,
2055
- defaulted: kept[index].narrowed ? Object.keys(row).filter((key) => !Object.hasOwn(kept[index].written, key)) : []
2279
+ defaulted: kept[index].narrowed ? Object.keys(row).filter((key) => !Object.hasOwn(kept[index].written, key)) : [],
2280
+ input: {
2281
+ ...lines[index].written,
2282
+ ...Object.fromEntries(Object.entries(lines[index].line ?? {}).filter(([key]) => !Object.hasOwn(lines[index].written, key) && !Object.hasOwn(row, key)))
2283
+ }
2056
2284
  })));
2057
2285
  } catch (error) {
2058
2286
  return err(toError(error));
@@ -2072,6 +2300,7 @@ var LinesDB = class LinesDB {
2072
2300
  * tables it changed once its callback is done
2073
2301
  */
2074
2302
  afterWrite(tableName, changes) {
2303
+ this.applyMovedRows();
2075
2304
  if (BigInt(changes) === 0n && this.transactionChanges) return;
2076
2305
  const tableNames = [tableName, ...this.tablesChangedByForeignKeyActions(tableName)];
2077
2306
  this.forgetLinesOfGoneRows(tableNames);
@@ -2125,17 +2354,20 @@ var LinesDB = class LinesDB {
2125
2354
  } catch (error) {
2126
2355
  throw await this.restoreAll(written, error);
2127
2356
  }
2128
- for (const { tableName, jsonlPath, generation, rowids } of written) {
2357
+ for (const { tableName, jsonlPath, generation, rowids, positions } of written) {
2358
+ const edits = this.positionEdits.get(tableName) ?? [];
2359
+ if (positions) this.linePositionsByRowid.set(tableName, replayEdits(positions, edits));
2129
2360
  if ((this.changeGenerations.get(tableName) ?? 0) === generation) {
2130
2361
  this.fieldChanges.delete(tableName);
2131
2362
  this.rawSqlTables.delete(tableName);
2132
2363
  }
2133
2364
  if (rowids) {
2134
2365
  const origins = this.rowOriginsByRowid.get(tableName);
2135
- rowids.forEach((rowid, rowIndex) => origins.set(rowid, {
2366
+ const writtenOrigins = new Map(rowids.map((rowid, rowIndex) => [rowid, {
2136
2367
  file: jsonlPath,
2137
2368
  rowIndex
2138
- }));
2369
+ }]));
2370
+ for (const [rowid, origin] of replayEdits(writtenOrigins, edits)) origins.set(rowid, origin);
2139
2371
  if (!this.scannedJsonlFiles.includes(jsonlPath)) this.scannedJsonlFiles.push(jsonlPath);
2140
2372
  }
2141
2373
  }
@@ -2203,7 +2435,11 @@ var LinesDB = class LinesDB {
2203
2435
  const unknownFields = fields.filter((field) => !tableFields.includes(field));
2204
2436
  throw new Error(`Cannot write back field(s) [${unknownFields.join(", ")}] for table '${tableName}': no such field in the rows written back to the file.`);
2205
2437
  }
2206
- const existing = options.matches ?? this.matchExistingRows(tableName, rows, existingRows, { required: fields !== void 0 });
2438
+ const existing = options.matches ?? this.matchExistingRows(tableName, rows, existingRows, {
2439
+ required: fields !== void 0,
2440
+ positionedLines: options.positionedLines
2441
+ });
2442
+ options.onMatched?.(existing);
2207
2443
  if (!existing) return rows;
2208
2444
  const rowByLine = /* @__PURE__ */ new Map();
2209
2445
  const newRows = [];
@@ -2221,20 +2457,41 @@ var LinesDB = class LinesDB {
2221
2457
  }), ...newRows];
2222
2458
  }
2223
2459
  /**
2460
+ * The primary key the schema makes of a line, which is how the stored rows hold it. The line's own key
2461
+ * when the rows are in the line's terms (a `backward` transformation maps them back), when there is no
2462
+ * schema, or when the schema refuses the line
2463
+ */
2464
+ outputKeyOfLine(tableName, line, pkName) {
2465
+ const schema = this.validationSchemas.get(tableName);
2466
+ if (!schema || hasBackward(schema) || line[pkName] === void 0 || line[pkName] === null) return line[pkName];
2467
+ try {
2468
+ return this.validateAndTransform(tableName, line)[pkName] ?? line[pkName];
2469
+ } catch {
2470
+ return line[pkName];
2471
+ }
2472
+ }
2473
+ /**
2224
2474
  * Pair each row with the JSONL line it came from, indexed the same way as `rows`.
2225
2475
  * Returns undefined when the rows cannot be matched and the caller can do without it.
2226
2476
  */
2227
2477
  matchExistingRows(tableName, rows, existingRows, options) {
2228
2478
  if (existingRows.length === 0) return rows.map(() => void 0);
2229
2479
  const pkName = this.schemas.get(tableName)?.columns.find((col) => col.primaryKey)?.name;
2230
- const pkValues = pkName ? existingRows.map((row) => row[pkName]) : [];
2480
+ if (pkName && options.positionedLines?.every((line) => line !== void 0)) return options.positionedLines;
2481
+ const pkValues = pkName ? existingRows.map((row) => options.byOutputKey ? this.outputKeyOfLine(tableName, row, pkName) : row[pkName]) : [];
2231
2482
  if (pkName !== void 0 && pkValues.every((value) => value !== void 0 && value !== null) && new Set(pkValues.map((value) => String(value))).size === pkValues.length) {
2232
2483
  const byPk = new Map(existingRows.map((row, index) => [String(pkValues[index]), row]));
2233
- return rows.map((row) => {
2484
+ const positioned = options.positionedLines;
2485
+ const claimed = new Set(positioned?.filter((line) => line !== void 0));
2486
+ return rows.map((row, index) => {
2487
+ const byPosition = positioned?.[index];
2488
+ if (byPosition) return byPosition;
2234
2489
  const pkValue = row[pkName];
2235
- return pkValue === void 0 || pkValue === null ? void 0 : byPk.get(String(pkValue));
2490
+ const byKey = pkValue === void 0 || pkValue === null ? void 0 : byPk.get(String(pkValue));
2491
+ return byKey && !claimed.has(byKey) ? byKey : void 0;
2236
2492
  });
2237
2493
  }
2494
+ if (options.positionedLines) return options.positionedLines;
2238
2495
  if (rows.length !== existingRows.length) {
2239
2496
  if (!options.required) return;
2240
2497
  throw new Error(`Cannot write back selected fields for table '${tableName}': the file has ${existingRows.length} row(s) but the table has ${rows.length}, and ${pkName ? `column '${pkName}' is not usable as a primary key in the file` : "the table has no primary key"}, so rows cannot be matched to their existing lines.`);
@@ -2396,6 +2653,7 @@ var LinesDB = class LinesDB {
2396
2653
  let fieldChangesBefore;
2397
2654
  let rawSqlTablesBefore;
2398
2655
  let linesWithUnknownFieldsBefore;
2656
+ let linePositionsBefore;
2399
2657
  let originsBefore;
2400
2658
  let columnsBefore;
2401
2659
  const scannedBefore = [...this.scannedJsonlFiles];
@@ -2407,6 +2665,7 @@ var LinesDB = class LinesDB {
2407
2665
  fieldChangesBefore = cloneFieldChanges(this.fieldChanges);
2408
2666
  rawSqlTablesBefore = new Set(this.rawSqlTables);
2409
2667
  linesWithUnknownFieldsBefore = new Map(Array.from(this.linesWithUnknownFields, ([tableName, lines]) => [tableName, new Map(lines)]));
2668
+ linePositionsBefore = new Map(Array.from(this.linePositionsByRowid, ([tableName, positions]) => [tableName, new Map(positions)]));
2410
2669
  this.db.exec("BEGIN TRANSACTION");
2411
2670
  this.settleUndos = [];
2412
2671
  this.inTransaction = true;
@@ -2437,6 +2696,7 @@ var LinesDB = class LinesDB {
2437
2696
  if (fieldChangesBefore) this.fieldChanges = fieldChangesBefore;
2438
2697
  if (rawSqlTablesBefore) this.rawSqlTables = rawSqlTablesBefore;
2439
2698
  if (linesWithUnknownFieldsBefore) this.linesWithUnknownFields = linesWithUnknownFieldsBefore;
2699
+ if (linePositionsBefore) this.linePositionsByRowid = linePositionsBefore;
2440
2700
  const failure = await this.restoreAll(written, error);
2441
2701
  if (this.inTransaction) try {
2442
2702
  this.db.exec("ROLLBACK");