lines-db 0.19.1 → 0.19.3

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
@@ -239,6 +239,32 @@ function unwrap(result) {
239
239
  if (result.ok) return result.value;
240
240
  throw result.error;
241
241
  }
242
+ // src/jsonl-record-lines.ts
243
+ function strayWhitespace(raw, trimmed) {
244
+ const start = raw.indexOf(trimmed);
245
+ const around = raw.slice(0, start) + raw.slice(start + trimmed.length);
246
+ return [...new Set(around)].filter((char) => char !== " " && char !== " " && char !== "\r");
247
+ }
248
+ /**
249
+ * Split JSONL content into the lines that hold a row: one leading byte order mark and each line's
250
+ * trailing carriage return are dropped, and lines that are blank after trimming are skipped.
251
+ * `line` is the 1-based physical line, so skipped lines still count. Whitespace around a row is
252
+ * trimmed; a character JSON does not allow as whitespace, such as a non-breaking space, is
253
+ * trimmed with a `warning`.
254
+ */
255
+ function jsonlRecordLines(content) {
256
+ return (content.startsWith("") ? content.slice(1) : content).split("\n").flatMap((raw, index) => {
257
+ const text = raw.trim();
258
+ if (text.length === 0) return [];
259
+ const stray = strayWhitespace(raw, text);
260
+ const record = {
261
+ text,
262
+ line: index + 1
263
+ };
264
+ if (stray.length > 0) record.warning = `has ${stray.map((char) => `U+${char.codePointAt(0).toString(16).toUpperCase().padStart(4, "0")}`).join(", ")} around its row, which JSON does not allow`;
265
+ return [record];
266
+ });
267
+ }
242
268
  // src/jsonl-reader.ts
243
269
  /** Fingerprint of a JSONL file's content, to tell whether the file changed since it was read */
244
270
  function hashJsonlContent(content) {
@@ -276,7 +302,8 @@ var JsonlReader = class {
276
302
  const overrideRows = this.overrides?.get(normalize(filePath));
277
303
  if (overrideRows) return ok({
278
304
  rows: ok(overrideRows.map((row) => JSON.parse(JSON.stringify(row)))),
279
- contentHash: void 0
305
+ contentHash: void 0,
306
+ warnings: []
280
307
  });
281
308
  let content;
282
309
  try {
@@ -284,31 +311,31 @@ var JsonlReader = class {
284
311
  } catch (error) {
285
312
  return err(toError(error));
286
313
  }
314
+ const records = jsonlRecordLines(content);
315
+ const warnings = records.flatMap(({ line, warning }) => warning ? [`${filePath}:${line} ${warning}`] : []);
287
316
  return ok({
288
- rows: this.parse(filePath, content),
289
- contentHash: hashJsonlContent(content)
317
+ rows: this.parse(filePath, records),
318
+ contentHash: hashJsonlContent(content),
319
+ warnings
290
320
  });
291
321
  }
292
- static parse(filePath, content) {
293
- const rawLines = (content.startsWith("") ? content.slice(1) : content).split("\n");
322
+ static parse(filePath, records) {
294
323
  const rows = [];
295
- for (let i = 0; i < rawLines.length; i++) {
296
- const line = rawLines[i].endsWith("\r") ? rawLines[i].slice(0, -1) : rawLines[i];
297
- if (line.trim().length === 0) continue;
324
+ for (const { text, line } of records) {
298
325
  const fail = (message, cause) => {
299
326
  const parseError = new Error(message, { cause });
300
327
  parseError.name = "JsonlParseError";
301
328
  parseError.file = filePath;
302
- parseError.line = i + 1;
329
+ parseError.line = line;
303
330
  return err(parseError);
304
331
  };
305
332
  let value;
306
333
  try {
307
- value = JSON.parse(line);
334
+ value = JSON.parse(text);
308
335
  } catch (error) {
309
- return fail(`Failed to parse JSON line: ${line}`, error);
336
+ return fail(`Failed to parse JSON line: ${text}`, error);
310
337
  }
311
- if (typeof value !== "object" || value === null || Array.isArray(value)) return fail(`A JSONL line holds a row, which is a JSON object: ${line}`);
338
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return fail(`A JSONL line holds a row, which is a JSON object: ${text}`);
312
339
  rows.push(value);
313
340
  }
314
341
  return ok(rows);
@@ -874,15 +901,80 @@ function cloneFieldChanges(changes) {
874
901
  return new Map(Array.from(changes, ([tableName, byRow]) => [tableName, new Map(Array.from(byRow, ([rowid, row]) => [rowid, {
875
902
  set: new Set(row.set),
876
903
  reset: new Set(row.reset),
877
- inserted: row.inserted
904
+ inserted: row.inserted,
905
+ ...row.inputs ? { inputs: new Map(row.inputs) } : {}
878
906
  }]))]));
879
907
  }
908
+ /** The line of each row by the position recorded for it, undefined for a row that has none */
909
+ function linesByPosition(positions, rowids, existingRows) {
910
+ if (!positions) return void 0;
911
+ return rowids.map((rowid) => {
912
+ const position = positions.get(rowid);
913
+ return position === void 0 ? void 0 : existingRows[position];
914
+ });
915
+ }
916
+ /**
917
+ * Where each row's line stands in a file once it is written: the lines of rows that kept one stay in order,
918
+ * and a row without one goes after them, in the order the rows are given
919
+ */
920
+ function positionsAfterWrite(rowids, matches, existingRows) {
921
+ const kept = new Set(matches.filter((line) => line !== void 0));
922
+ const positionOfLine = /* @__PURE__ */ new Map();
923
+ existingRows.filter((line) => kept.has(line)).forEach((line, position) => positionOfLine.set(line, position));
924
+ let next = positionOfLine.size;
925
+ return new Map(rowids.map((rowid, index) => {
926
+ const line = matches[index];
927
+ return [rowid, line === void 0 ? next++ : positionOfLine.get(line)];
928
+ }));
929
+ }
930
+ /**
931
+ * What was kept by rowid when a write-back read its rows, brought up to date with the changes made since, in order:
932
+ * a deleted or reused rowid loses what it had, and a row that moved carries it to its new rowid
933
+ */
934
+ function replayEdits(byRowid, edits) {
935
+ for (const edit of edits) {
936
+ if ("forget" in edit) {
937
+ byRowid.delete(edit.forget);
938
+ continue;
939
+ }
940
+ const kept = byRowid.get(edit.from);
941
+ if (kept === void 0) continue;
942
+ byRowid.delete(edit.from);
943
+ byRowid.set(edit.to, kept);
944
+ }
945
+ return byRowid;
946
+ }
947
+ /**
948
+ * The temporary table the rowid changes of rows are logged to. Not qualified with `temp.`: SQLite before 3.53, as Bun
949
+ * ships, refuses a qualified table name in a trigger body, and an unqualified one is looked up in `temp` first
950
+ */
951
+ const MOVED_ROWS_LOG = "\"__lines_db_moved_rows\"";
880
952
  /** Column alias a query reads a row's rowid under, next to its fields */
881
953
  const ROWID_ALIAS = "__lines_db_rowid";
882
954
  /** The fields a row given to an insert names, leaving out those it leaves undefined */
883
955
  function givenFields(row) {
884
956
  return Object.entries(row).filter(([, value]) => value !== void 0).map(([key]) => key);
885
957
  }
958
+ /** Whether two values read the same once written as JSON; a bigint reads as its digits, which JSON.stringify refuses */
959
+ function sameValue(a, b) {
960
+ const text = (value) => JSON.stringify(value, (_key, item) => typeof item === "bigint" ? String(item) : item);
961
+ return text(a) === text(b);
962
+ }
963
+ /** Whether a value is a bigint or holds one at any depth, which a JSONL line cannot hold */
964
+ function holdsBigint(value) {
965
+ if (typeof value === "bigint") return true;
966
+ if (Array.isArray(value)) return value.some(holdsBigint);
967
+ return value !== null && typeof value === "object" && Object.values(value).some(holdsBigint);
968
+ }
969
+ /**
970
+ * The values of a row given to an insert that the stored row holds differently, after the schema transformed
971
+ * them. A value holding a bigint is left out: a line cannot hold one, so the row keeps the value the schema
972
+ * made of it
973
+ */
974
+ function transformedInputs(given, stored) {
975
+ 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)]));
976
+ return inputs.size > 0 ? inputs : void 0;
977
+ }
886
978
  /** Whether a value read from SQLite and one about to be stored are the same */
887
979
  function sameStoredValue(stored, next) {
888
980
  if (stored === null || stored === void 0 || next === null) return (stored ?? null) === next;
@@ -919,6 +1011,18 @@ var LinesDB = class LinesDB {
919
1011
  * back, also once the row's primary key changed and its line can no longer be found by it
920
1012
  */
921
1013
  linesWithUnknownFields = /* @__PURE__ */ new Map();
1014
+ /**
1015
+ * For a table without a primary key, where each row's line stands in its file: the rows cannot be
1016
+ * matched to their lines by key, and by order only while none is added or removed
1017
+ */
1018
+ linePositionsByRowid = /* @__PURE__ */ new Map();
1019
+ /**
1020
+ * What happened to the positions of a table's rows since its rows were read for its write-back, in order: the
1021
+ * positions that write-back computes describe the rows as they were, and are brought up to date with these
1022
+ */
1023
+ positionEdits = /* @__PURE__ */ new Map();
1024
+ /** Whether the temporary table that triggers log the rowid changes of rows to exists */
1025
+ movedRowsLogReady = false;
922
1026
  /** Whether a transaction's callback has returned and its files are being written back */
923
1027
  transactionClosing = false;
924
1028
  /** Whether a transaction() call is past its guard but has not begun yet */
@@ -1013,7 +1117,7 @@ var LinesDB = class LinesDB {
1013
1117
  const tableTransform = tableNameToLoad === tableName ? transform : void 0;
1014
1118
  const { errors, warnings, rowCounts: tableRowCounts, deferredForeignKeys } = await this.loadTableWithDependencies(tableNameToLoad, loadedTables, loadingTables, attemptedTables, detailedValidate, tableTransform);
1015
1119
  allErrors.push(...errors);
1016
- allWarnings.push(...warnings);
1120
+ for (const warning of warnings) allWarnings.push(warning);
1017
1121
  allDeferredForeignKeys.push(...deferredForeignKeys);
1018
1122
  for (const [k, v] of tableRowCounts) allRowCounts.set(k, v);
1019
1123
  }
@@ -1082,7 +1186,7 @@ var LinesDB = class LinesDB {
1082
1186
  if (this.tables.has(referencedTable)) {
1083
1187
  const depResult = await this.loadTableWithDependencies(referencedTable, loadedTables, loadingTables, attemptedTables, detailedValidate, void 0);
1084
1188
  errors.push(...depResult.errors);
1085
- warnings.push(...depResult.warnings);
1189
+ for (const warning of depResult.warnings) warnings.push(warning);
1086
1190
  deferredForeignKeys.push(...depResult.deferredForeignKeys);
1087
1191
  for (const [k, v] of depResult.rowCounts) rowCounts.set(k, v);
1088
1192
  } else throw new Error(`Foreign key reference to non-existent table '${referencedTable}' in table '${tableName}'`);
@@ -1105,7 +1209,7 @@ var LinesDB = class LinesDB {
1105
1209
  }
1106
1210
  }
1107
1211
  const allSkippedDependencies = /* @__PURE__ */ new Set([...failedDependencies, ...circularDependencies]);
1108
- const { loaded, rowCount, errors: loadErrors } = await this.loadTable(tableName, tableConfig, detailedValidate, transform, allSkippedDependencies);
1212
+ const { loaded, rowCount, errors: loadErrors } = await this.loadTable(tableName, tableConfig, detailedValidate, transform, allSkippedDependencies, warnings);
1109
1213
  errors.push(...loadErrors);
1110
1214
  rowCounts.set(tableName, rowCount);
1111
1215
  if (loaded) {
@@ -1142,15 +1246,16 @@ var LinesDB = class LinesDB {
1142
1246
  * Load a single table from JSONL file
1143
1247
  * @returns Object with loaded status and validation errors
1144
1248
  */
1145
- async loadTable(tableName, config, detailedValidate, transform, failedDependencies) {
1249
+ async loadTable(tableName, config, detailedValidate, transform, failedDependencies, warnings = []) {
1146
1250
  let data = [];
1147
1251
  const origins = [];
1148
1252
  const contentHashes = /* @__PURE__ */ new Map();
1149
1253
  for (const jsonlPath of config.jsonlPaths ?? [config.jsonlPath]) {
1150
1254
  const readResult = await JsonlReader.readSnapshot(jsonlPath);
1151
1255
  if (!readResult.ok) throw readResult.error;
1152
- const { rows, contentHash } = readResult.value;
1256
+ const { rows, contentHash, warnings: readWarnings } = readResult.value;
1153
1257
  if (!rows.ok) throw rows.error;
1258
+ for (const warning of readWarnings) warnings.push(`Table '${tableName}': ${warning}`);
1154
1259
  if (contentHash !== void 0) {
1155
1260
  contentHashes.set(jsonlPath, contentHash);
1156
1261
  this.observedHashes.set(jsonlPath, contentHash);
@@ -1285,16 +1390,26 @@ var LinesDB = class LinesDB {
1285
1390
  } else this.insertData(tableName, schema, validatedData);
1286
1391
  this.fieldChanges.delete(tableName);
1287
1392
  this.linesWithUnknownFields.delete(tableName);
1393
+ this.linePositionsByRowid.delete(tableName);
1394
+ if (this.tracksLinePositions(tableName)) {
1395
+ this.logMovedRows(tableName);
1396
+ const positions = /* @__PURE__ */ new Map();
1397
+ this.rowidsInLineOrder(tableName, validatedData).forEach((rowid, index) => {
1398
+ if (rowid !== void 0) positions.set(rowid, index);
1399
+ });
1400
+ this.linePositionsByRowid.set(tableName, positions);
1401
+ }
1288
1402
  const columnNames = new Set(schema.columns.map((column) => column.name));
1289
1403
  const withUnknown = data.map((row) => Object.keys(row).some((key) => !columnNames.has(key)));
1290
1404
  if (transformedFields.some((fields) => fields.length > 0) || withUnknown.includes(true)) {
1291
1405
  const rowids = this.queryInternal(`SELECT rowid AS "${ROWID_ALIAS}" FROM ${this.quoteTableName(tableName)} ORDER BY rowid`);
1292
1406
  const lines = /* @__PURE__ */ new Map();
1293
1407
  const sourceIndexes = new Map(origins.map((origin, index) => [origin, index]));
1408
+ const lineIndexes = new Map(this.rowidsInLineOrder(tableName, validatedData).map((rowid, index) => [rowid, index]));
1294
1409
  rowids.forEach((row, index) => {
1295
1410
  const rowid = row[ROWID_ALIAS];
1296
1411
  const origin = this.rowOriginsByRowid.get(tableName)?.get(String(rowid));
1297
- const sourceIndex = origin ? sourceIndexes.get(origin) ?? index : index;
1412
+ const sourceIndex = origin ? sourceIndexes.get(origin) ?? index : lineIndexes.get(String(rowid)) ?? index;
1298
1413
  const set = transformedFields[sourceIndex] ?? [];
1299
1414
  if (set.length > 0) this.noteFieldChanges(tableName, rowid, { set });
1300
1415
  if (withUnknown[sourceIndex]) lines.set(String(rowid), data[sourceIndex]);
@@ -1584,9 +1699,11 @@ var LinesDB = class LinesDB {
1584
1699
  try {
1585
1700
  return run();
1586
1701
  } finally {
1702
+ this.applyMovedRows();
1587
1703
  if (this.totalChanges() !== before) {
1588
1704
  for (const tableName of this.schemas.keys()) {
1589
1705
  this.rawSqlTables.add(tableName);
1706
+ this.linePositionsByRowid.delete(tableName);
1590
1707
  this.noteChange(tableName);
1591
1708
  }
1592
1709
  this.forgetLinesOfGoneRows(this.schemas.keys());
@@ -1763,8 +1880,10 @@ var LinesDB = class LinesDB {
1763
1880
  });
1764
1881
  this.rowOriginsByRowid.set(tableName, origins);
1765
1882
  }
1883
+ this.forgetPosition(tableName, String(result.lastInsertRowid));
1766
1884
  this.noteFieldChanges(tableName, result.lastInsertRowid, {
1767
1885
  set: givenFields(data),
1886
+ inputs: transformedInputs(data, row),
1768
1887
  inserted: true
1769
1888
  });
1770
1889
  this.afterWrite(tableName, result.changes);
@@ -1829,8 +1948,10 @@ var LinesDB = class LinesDB {
1829
1948
  undoSettle();
1830
1949
  throw error;
1831
1950
  }
1951
+ this.forgetPosition(tableName, String(result.lastInsertRowid));
1832
1952
  this.noteFieldChanges(tableName, result.lastInsertRowid, {
1833
1953
  set: givenFields(record),
1954
+ inputs: transformedInputs(record, row),
1834
1955
  inserted: true
1835
1956
  });
1836
1957
  totalChanges += BigInt(result.changes);
@@ -1860,44 +1981,58 @@ var LinesDB = class LinesDB {
1860
1981
  updateInternal(tableName, data, where, options) {
1861
1982
  this.assertMutable(tableName);
1862
1983
  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
1984
  const { sql: whereSql, values: whereValues, functionFilters } = this.buildWhereClause(where, tableName);
1877
1985
  if (functionFilters.length > 0) throw new Error("Function filters are not supported in update operations");
1878
1986
  const targets = this.queryInternal(`SELECT rowid AS "${ROWID_ALIAS}", * FROM ${this.quoteTableName(tableName)} WHERE ${whereSql}`, whereValues);
1987
+ const shouldValidate = options?.validate !== false;
1988
+ const hasValidationSchema = this.validationSchemas.has(tableName);
1989
+ const givenKeys = Object.keys(data);
1879
1990
  const resetFields = options?.resetToDefault ?? [];
1991
+ const storedValues = targets.map((target) => {
1992
+ if (!shouldValidate || !hasValidationSchema) return data;
1993
+ const { [ROWID_ALIAS]: _rowid, ...stored } = target;
1994
+ const merged = {
1995
+ ...this.deserializeRow(tableName, stored),
1996
+ ...data
1997
+ };
1998
+ for (const field of resetFields) delete merged[field];
1999
+ const validated = this.validateAndTransform(tableName, merged);
2000
+ return Object.fromEntries(givenKeys.map((key) => [key, Object.hasOwn(validated, key) ? validated[key] : data[key]]));
2001
+ });
1880
2002
  const resets = resetFields.length > 0 ? this.computeResets(tableName, targets, data, resetFields) : [];
1881
2003
  let result = {
1882
2004
  changes: 0,
1883
2005
  lastInsertRowid: 0
1884
2006
  };
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);
2007
+ if (givenKeys.length > 0 && targets.length > 0) {
2008
+ const setClauses = givenKeys.map((key) => `${this.quoteIdentifier(key)} = ?`).join(", ");
2009
+ const sql = `UPDATE ${this.quoteTableName(tableName)} SET ${setClauses} WHERE rowid = ?`;
2010
+ const undoSettle = this.settleColumnsNoRowHolds(this.schemas.get(tableName), storedValues[0]);
2011
+ let changes = 0n;
2012
+ let lastInsertRowid = 0;
2013
+ this.db.exec("SAVEPOINT lines_db_update");
1890
2014
  try {
1891
- result = this.executeInternal(sql, values);
2015
+ targets.forEach((target, index) => {
2016
+ const written = this.executeInternal(sql, [...givenKeys.map((key) => this.normalizeValue(storedValues[index][key], this.columnOf(tableName, key))), target[ROWID_ALIAS]]);
2017
+ changes += BigInt(written.changes);
2018
+ lastInsertRowid = written.lastInsertRowid;
2019
+ });
2020
+ this.db.exec("RELEASE lines_db_update");
1892
2021
  } catch (error) {
2022
+ this.db.exec("ROLLBACK TO lines_db_update");
2023
+ this.db.exec("RELEASE lines_db_update");
1893
2024
  undoSettle();
1894
2025
  throw error;
1895
2026
  }
1896
- if (Number(result.changes) === 0) undoSettle();
2027
+ result = {
2028
+ changes: Number(changes),
2029
+ lastInsertRowid
2030
+ };
2031
+ if (changes === 0n) undoSettle();
1897
2032
  }
1898
2033
  const pkName = this.schemas.get(tableName)?.columns.find((col) => col.primaryKey)?.name;
1899
2034
  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))]);
2035
+ 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
2036
  if (targets.length === 1 && moved.length === 1) {
1902
2037
  const from = String(targets[0][ROWID_ALIAS]);
1903
2038
  const to = moved[0][ROWID_ALIAS];
@@ -1910,10 +2045,14 @@ var LinesDB = class LinesDB {
1910
2045
  }
1911
2046
  }
1912
2047
  }
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
- }
2048
+ targets.forEach((target, index) => {
2049
+ const set = givenKeys.filter((key) => !sameStoredValue(target[key], this.normalizeValue(storedValues[index][key], this.columnOf(tableName, key))));
2050
+ const given = Object.fromEntries(set.map((key) => [key, data[key]]));
2051
+ this.noteFieldChanges(tableName, target[ROWID_ALIAS], {
2052
+ set,
2053
+ inputs: transformedInputs(given, storedValues[index])
2054
+ });
2055
+ });
1917
2056
  if (resets.length > 0) result = this.applyResets(tableName, resets, resetFields);
1918
2057
  this.afterWrite(tableName, result.changes);
1919
2058
  return result;
@@ -2267,9 +2406,18 @@ var LinesDB = class LinesDB {
2267
2406
  this.assertWritable(tableName);
2268
2407
  const config = this.tables.get(tableName);
2269
2408
  if (!config) throw new Error(`Table ${tableName} not found`);
2409
+ this.positionEdits.set(tableName, []);
2270
2410
  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);
2411
+ const recorded = this.linePositionsByRowid.get(tableName);
2412
+ const atRead = {
2413
+ generation: this.changeGenerations.get(tableName) ?? 0,
2414
+ positions: recorded && new Map(recorded),
2415
+ origins: new Map(this.rowOriginsByRowid.get(tableName) ?? []),
2416
+ changes: cloneFieldChanges(/* @__PURE__ */ new Map([[tableName, this.fieldChanges.get(tableName) ?? /* @__PURE__ */ new Map()]])).get(tableName),
2417
+ unknownFieldLines: new Map(this.linesWithUnknownFields.get(tableName) ?? [])
2418
+ };
2419
+ if (!this.hasSeveralDataDirs()) return [await this.prepareFileWriteBack(tableName, config.jsonlPath, stored, options, atRead)];
2420
+ const origins = atRead.origins;
2273
2421
  const byFile = new Map([this.config.dataDir].flat().map((dir) => [join(dir, `${tableName}.jsonl`), []]));
2274
2422
  stored.rowids.forEach((rowid, index) => {
2275
2423
  const origin = origins?.get(rowid);
@@ -2286,33 +2434,98 @@ var LinesDB = class LinesDB {
2286
2434
  rows: indexes.map((i) => stored.rows[i]),
2287
2435
  lineRows: indexes.map((i) => stored.lineRows[i])
2288
2436
  };
2289
- const fileWrite = await this.prepareFileWriteBack(tableName, file, rows, options);
2437
+ const fileWrite = await this.prepareFileWriteBack(tableName, file, rows, options, atRead);
2290
2438
  if (!fileWrite.unchanged) prepared.push(fileWrite);
2291
2439
  }
2292
2440
  return prepared;
2293
2441
  }
2294
- async prepareFileWriteBack(tableName, jsonlPath, stored, options) {
2442
+ forgetPosition(tableName, rowid) {
2443
+ this.linePositionsByRowid.get(tableName)?.delete(rowid);
2444
+ this.positionEdits.get(tableName)?.push({ forget: rowid });
2445
+ }
2446
+ /**
2447
+ * The rowid of the row each line was loaded into, in the order of the lines. Not the rowid order: an INTEGER
2448
+ * PRIMARY KEY is the rowid, so the line `{"id":3}` first in its file is the row with rowid 3
2449
+ */
2450
+ rowidsInLineOrder(tableName, rows) {
2451
+ const pk = this.schemas.get(tableName)?.columns.find((column) => column.primaryKey);
2452
+ const stored = this.queryInternal(`SELECT rowid AS "${ROWID_ALIAS}" FROM ${this.quoteTableName(tableName)} ORDER BY rowid`).map((row) => String(row[ROWID_ALIAS]));
2453
+ if (pk?.type !== "INTEGER") return stored;
2454
+ const present = new Set(stored);
2455
+ let largest;
2456
+ return rows.map((row) => {
2457
+ const key = row[pk.name];
2458
+ const rowid = key === void 0 || key === null ? (largest ?? 0) + 1 : Number(key);
2459
+ largest = largest === void 0 ? rowid : Math.max(largest, rowid);
2460
+ return present.has(String(rowid)) ? String(rowid) : void 0;
2461
+ });
2462
+ }
2463
+ /**
2464
+ * Log each change of a row's rowid in the table: a foreign-key action or raw SQL can change an INTEGER PRIMARY
2465
+ * KEY, which is the rowid, without a write through this database telling it which row moved
2466
+ */
2467
+ logMovedRows(tableName) {
2468
+ if (!this.movedRowsLogReady) {
2469
+ this.db.exec(`CREATE TEMP TABLE IF NOT EXISTS ${MOVED_ROWS_LOG} (tbl TEXT, old INTEGER, new INTEGER)`);
2470
+ this.movedRowsLogReady = true;
2471
+ }
2472
+ const trigger = this.quoteIdentifier(`__lines_db_moved_${tableName}`);
2473
+ const name = `'${tableName.replace(/'/g, "''")}'`;
2474
+ 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`);
2475
+ }
2476
+ /** Move what is kept by rowid to the rowid each logged row moved to, in the order the rows moved */
2477
+ applyMovedRows() {
2478
+ if (!this.movedRowsLogReady) return;
2479
+ const moved = this.queryInternal(`SELECT tbl, old, new FROM ${MOVED_ROWS_LOG} ORDER BY rowid`);
2480
+ if (moved.length === 0) return;
2481
+ this.db.exec(`DELETE FROM ${MOVED_ROWS_LOG}`);
2482
+ for (const { tbl, old, new: to } of moved) this.moveRowMetadata(String(tbl), String(old), String(to));
2483
+ }
2484
+ /**
2485
+ * Whether the lines of a table are remembered by position, so a row whose key changed, or that has none, is
2486
+ * found again by where its line stood. Several data directories have the origin of each row instead
2487
+ */
2488
+ tracksLinePositions(_tableName) {
2489
+ return !this.hasSeveralDataDirs();
2490
+ }
2491
+ hasNoPrimaryKey(tableName) {
2492
+ return this.schemas.get(tableName)?.columns.some((column) => column.primaryKey) === false;
2493
+ }
2494
+ async prepareFileWriteBack(tableName, jsonlPath, stored, options, atRead) {
2295
2495
  const { rowids, rows: deserializedRows, lineRows } = stored;
2296
- const generation = this.changeGenerations.get(tableName) ?? 0;
2496
+ const generation = atRead?.generation ?? this.changeGenerations.get(tableName) ?? 0;
2297
2497
  let finalRows = lineRows;
2298
2498
  const previousContent = await readFile(jsonlPath, "utf-8").catch((error) => {
2299
2499
  if (error.code === "ENOENT") return void 0;
2300
2500
  throw error;
2301
2501
  });
2302
2502
  const existingRows = await this.readUnchangedRows(jsonlPath);
2303
- const matches = this.hasSeveralDataDirs() ? rowids.map((rowid) => existingRows[this.rowOriginsByRowid.get(tableName).get(rowid).rowIndex]) : void 0;
2503
+ const origins = atRead?.origins ?? this.rowOriginsByRowid.get(tableName);
2504
+ const matchedByOrigin = this.hasSeveralDataDirs() ? rowids.map((rowid) => {
2505
+ const origin = origins?.get(rowid);
2506
+ return origin && existingRows[origin.rowIndex];
2507
+ }) : void 0;
2508
+ const byPosition = matchedByOrigin ? void 0 : linesByPosition(atRead?.positions, rowids, existingRows);
2509
+ const matches = matchedByOrigin ?? (this.hasNoPrimaryKey(tableName) ? byPosition : void 0);
2510
+ const positionedLines = matches ? void 0 : byPosition;
2304
2511
  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);
2512
+ if ((options?.writeFilledValues ?? this.config.writeFilledValues ?? "all") === "primaryKey") finalRows = this.keepWrittenFields(tableName, rowids, deserializedRows, finalRows, existingRows, fields, matches, {
2513
+ positionedLines,
2514
+ changes: atRead?.changes
2515
+ }).map(({ written }) => written);
2306
2516
  const columns = new Set(this.schemas.get(tableName)?.columns.map((column) => column.name));
2307
- const readLines = this.linesWithUnknownFields.get(tableName);
2517
+ const readLines = atRead?.unknownFieldLines ?? this.linesWithUnknownFields.get(tableName);
2308
2518
  finalRows = finalRows.map((row, index) => {
2309
2519
  const line = readLines?.get(rowids[index]);
2310
2520
  return line ? keepUnknownFields(line, row, columns) : row;
2311
2521
  });
2522
+ let linesOfRows;
2312
2523
  finalRows = this.mergeWithExistingLines(tableName, existingRows, finalRows, {
2313
2524
  fields,
2314
2525
  strictFields: options?.strictFields ?? false,
2315
- matches
2526
+ matches,
2527
+ positionedLines,
2528
+ onMatched: (lines) => linesOfRows = lines
2316
2529
  });
2317
2530
  return {
2318
2531
  tableName,
@@ -2320,10 +2533,11 @@ var LinesDB = class LinesDB {
2320
2533
  rows: finalRows,
2321
2534
  previousContent,
2322
2535
  generation,
2323
- ...matches ? {
2536
+ ...matchedByOrigin ? {
2324
2537
  rowids,
2325
2538
  unchanged: JsonlWriter.serialize(existingRows) === JsonlWriter.serialize(finalRows)
2326
- } : {}
2539
+ } : {},
2540
+ ...this.tracksLinePositions(tableName) && !matchedByOrigin ? { positions: linesOfRows ? positionsAfterWrite(rowids, linesOfRows, existingRows) : new Map(rowids.map((rowid, position) => [rowid, position])) } : {}
2327
2541
  };
2328
2542
  }
2329
2543
  /**
@@ -2346,17 +2560,22 @@ var LinesDB = class LinesDB {
2346
2560
  * minus those reset to their default - its primary key and the fields named to be written back, so
2347
2561
  * a value the schema fills in stays out of the file
2348
2562
  */
2349
- keepWrittenFields(tableName, rowids, rows, lineRows, existingRows, namedFields = [], matchedLines) {
2563
+ keepWrittenFields(tableName, rowids, rows, lineRows, existingRows, namedFields = [], matchedLines, options) {
2350
2564
  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);
2565
+ 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);
2566
+ const lines = matchedLines ?? this.matchExistingRows(tableName, lineRows, existingRows, {
2567
+ required: false,
2568
+ byOutputKey: true,
2569
+ positionedLines: options?.positionedLines
2570
+ });
2571
+ const changes = options?.changes ?? this.fieldChanges.get(tableName);
2354
2572
  return lineRows.map((lineRow, index) => {
2355
2573
  const line = lines?.[index];
2356
2574
  const rowChanges = changes?.get(rowids[index]);
2357
2575
  if (Object.keys(lineRow).some((key) => !Object.hasOwn(rows[index], key)) || this.rawSqlTables.has(tableName) || !line && !rowChanges?.inserted) return {
2358
2576
  written: lineRow,
2359
- narrowed: false
2577
+ narrowed: false,
2578
+ line
2360
2579
  };
2361
2580
  const keep = /* @__PURE__ */ new Set([
2362
2581
  ...Object.keys(line ?? {}),
@@ -2366,10 +2585,11 @@ var LinesDB = class LinesDB {
2366
2585
  for (const key of rowChanges?.reset ?? []) keep.delete(key);
2367
2586
  for (const key of namedFields) keep.add(key);
2368
2587
  if (pkName) keep.add(pkName);
2369
- const untouched = line !== void 0 && !rowChanges?.inserted && !rowChanges?.set.size && !rowChanges?.reset.size;
2588
+ const untouched = (key) => line !== void 0 && !rowChanges?.inserted && Object.hasOwn(line, key) && !rowChanges?.set.has(key) && !rowChanges?.reset.has(key);
2370
2589
  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
2590
+ 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])),
2591
+ narrowed: true,
2592
+ line
2373
2593
  };
2374
2594
  });
2375
2595
  }
@@ -2381,10 +2601,15 @@ var LinesDB = class LinesDB {
2381
2601
  * later, which must not inherit them
2382
2602
  */
2383
2603
  moveRowMetadata(tableName, from, to) {
2604
+ this.positionEdits.get(tableName)?.push({
2605
+ from,
2606
+ to
2607
+ });
2384
2608
  for (const byRow of [
2385
2609
  this.fieldChanges.get(tableName),
2386
2610
  this.linesWithUnknownFields.get(tableName),
2387
- this.rowOriginsByRowid.get(tableName)
2611
+ this.rowOriginsByRowid.get(tableName),
2612
+ this.linePositionsByRowid.get(tableName)
2388
2613
  ]) {
2389
2614
  const kept = byRow?.get(from);
2390
2615
  if (!byRow || kept === void 0) continue;
@@ -2409,6 +2634,7 @@ var LinesDB = class LinesDB {
2409
2634
  }
2410
2635
  forgetFieldChanges(tableName, rowids) {
2411
2636
  for (const rowid of rowids) {
2637
+ this.forgetPosition(tableName, rowid);
2412
2638
  this.fieldChanges.get(tableName)?.delete(rowid);
2413
2639
  this.linesWithUnknownFields.get(tableName)?.delete(rowid);
2414
2640
  }
@@ -2428,10 +2654,16 @@ var LinesDB = class LinesDB {
2428
2654
  for (const key of changes.set ?? []) {
2429
2655
  rowChanges.set.add(key);
2430
2656
  rowChanges.reset.delete(key);
2657
+ rowChanges.inputs?.delete(key);
2431
2658
  }
2432
2659
  for (const key of changes.reset ?? []) {
2433
2660
  rowChanges.reset.add(key);
2434
2661
  rowChanges.set.delete(key);
2662
+ rowChanges.inputs?.delete(key);
2663
+ }
2664
+ for (const [key, value] of changes.inputs ?? []) {
2665
+ rowChanges.inputs ??= /* @__PURE__ */ new Map();
2666
+ rowChanges.inputs.set(key, value);
2435
2667
  }
2436
2668
  byRow.set(String(rowid), rowChanges);
2437
2669
  this.fieldChanges.set(tableName, byRow);
@@ -2472,25 +2704,49 @@ var LinesDB = class LinesDB {
2472
2704
  }
2473
2705
  /**
2474
2706
  * 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
2707
+ * does not hold and no write set, which a write-back leaves out of the file. `input` is the row as
2708
+ * its line holds it - the values before the schema transformed them, without the defaulted fields.
2476
2709
  */
2477
2710
  async findWithDefaults(tableName) {
2478
2711
  try {
2479
2712
  const tableConfig = this.tables.get(tableName);
2480
2713
  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));
2714
+ let stored;
2715
+ let positionsAtRead;
2716
+ let fileRows;
2717
+ for (let attempt = 1;; attempt++) {
2718
+ await this.waitForPendingSyncs();
2719
+ const files = this.hasSeveralDataDirs() ? [.../* @__PURE__ */ new Set([...tableConfig.jsonlPaths ?? [tableConfig.jsonlPath], ...[...this.rowOriginsByRowid.get(tableName)?.values() ?? []].map((origin) => origin.file)])] : [tableConfig.jsonlPath];
2720
+ const generation = this.changeGenerations.get(tableName) ?? 0;
2721
+ const hashes = files.map((file) => this.fileHashes.get(file));
2722
+ stored = this.readStoredRows(tableName);
2723
+ const recorded = this.linePositionsByRowid.get(tableName);
2724
+ positionsAtRead = recorded && new Map(recorded);
2725
+ fileRows = /* @__PURE__ */ new Map();
2726
+ const unchanged = () => (this.changeGenerations.get(tableName) ?? 0) === generation && files.every((file, index) => this.fileHashes.get(file) === hashes[index]);
2727
+ try {
2728
+ for (const file of files) fileRows.set(file, await this.readUnchangedRows(file));
2729
+ } catch (error) {
2730
+ if (!(error instanceof Error && error.name === "JsonlConflictError") || unchanged()) throw error;
2731
+ }
2732
+ if (unchanged()) break;
2733
+ if (attempt >= 5) throw new Error(`The rows of '${tableName}' kept changing while they were read; read them again`);
2734
+ }
2735
+ const { rowids, rows, lineRows } = stored;
2485
2736
  const existingRows = [...fileRows.values()].flat();
2486
2737
  const matches = this.hasSeveralDataDirs() && this.config.writeDataSets ? rowids.map((rowid) => {
2487
2738
  const origin = this.rowOriginsByRowid.get(tableName)?.get(rowid);
2488
2739
  return origin && fileRows.get(origin.file)?.[origin.rowIndex];
2489
- }) : void 0;
2740
+ }) : linesByPosition(positionsAtRead, rowids, existingRows);
2490
2741
  const kept = this.keepWrittenFields(tableName, rowids, rows, lineRows, existingRows, this.config.writeBackFields, matches);
2742
+ const lines = this.keepWrittenFields(tableName, rowids, rows, lineRows, existingRows, [], matches, { ignoreActions: true });
2491
2743
  return ok(rows.map((row, index) => ({
2492
2744
  row,
2493
- defaulted: kept[index].narrowed ? Object.keys(row).filter((key) => !Object.hasOwn(kept[index].written, key)) : []
2745
+ defaulted: kept[index].narrowed ? Object.keys(row).filter((key) => !Object.hasOwn(kept[index].written, key)) : [],
2746
+ input: {
2747
+ ...lines[index].written,
2748
+ ...Object.fromEntries(Object.entries(lines[index].line ?? {}).filter(([key]) => !Object.hasOwn(lines[index].written, key) && !Object.hasOwn(row, key)))
2749
+ }
2494
2750
  })));
2495
2751
  } catch (error) {
2496
2752
  return err(toError(error));
@@ -2510,6 +2766,7 @@ var LinesDB = class LinesDB {
2510
2766
  * tables it changed once its callback is done
2511
2767
  */
2512
2768
  afterWrite(tableName, changes) {
2769
+ this.applyMovedRows();
2513
2770
  if (BigInt(changes) === 0n && this.transactionChanges) return;
2514
2771
  const tableNames = [tableName, ...this.tablesChangedByForeignKeyActions(tableName)];
2515
2772
  this.forgetLinesOfGoneRows(tableNames);
@@ -2563,17 +2820,20 @@ var LinesDB = class LinesDB {
2563
2820
  } catch (error) {
2564
2821
  throw await this.restoreAll(written, error);
2565
2822
  }
2566
- for (const { tableName, jsonlPath, generation, rowids } of written) {
2823
+ for (const { tableName, jsonlPath, generation, rowids, positions } of written) {
2824
+ const edits = this.positionEdits.get(tableName) ?? [];
2825
+ if (positions) this.linePositionsByRowid.set(tableName, replayEdits(positions, edits));
2567
2826
  if ((this.changeGenerations.get(tableName) ?? 0) === generation) {
2568
2827
  this.fieldChanges.delete(tableName);
2569
2828
  this.rawSqlTables.delete(tableName);
2570
2829
  }
2571
2830
  if (rowids) {
2572
2831
  const origins = this.rowOriginsByRowid.get(tableName);
2573
- rowids.forEach((rowid, rowIndex) => origins.set(rowid, {
2832
+ const writtenOrigins = new Map(rowids.map((rowid, rowIndex) => [rowid, {
2574
2833
  file: jsonlPath,
2575
2834
  rowIndex
2576
- }));
2835
+ }]));
2836
+ for (const [rowid, origin] of replayEdits(writtenOrigins, edits)) origins.set(rowid, origin);
2577
2837
  if (!this.scannedJsonlFiles.includes(jsonlPath)) this.scannedJsonlFiles.push(jsonlPath);
2578
2838
  }
2579
2839
  }
@@ -2641,7 +2901,11 @@ var LinesDB = class LinesDB {
2641
2901
  const unknownFields = fields.filter((field) => !tableFields.includes(field));
2642
2902
  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
2903
  }
2644
- const existing = options.matches ?? this.matchExistingRows(tableName, rows, existingRows, { required: fields !== void 0 });
2904
+ const existing = options.matches ?? this.matchExistingRows(tableName, rows, existingRows, {
2905
+ required: fields !== void 0,
2906
+ positionedLines: options.positionedLines
2907
+ });
2908
+ options.onMatched?.(existing);
2645
2909
  if (!existing) return rows;
2646
2910
  const rowByLine = /* @__PURE__ */ new Map();
2647
2911
  const newRows = [];
@@ -2659,20 +2923,41 @@ var LinesDB = class LinesDB {
2659
2923
  }), ...newRows];
2660
2924
  }
2661
2925
  /**
2926
+ * The primary key the schema makes of a line, which is how the stored rows hold it. The line's own key
2927
+ * when the rows are in the line's terms (a `backward` transformation maps them back), when there is no
2928
+ * schema, or when the schema refuses the line
2929
+ */
2930
+ outputKeyOfLine(tableName, line, pkName) {
2931
+ const schema = this.validationSchemas.get(tableName);
2932
+ if (!schema || hasBackward(schema) || line[pkName] === void 0 || line[pkName] === null) return line[pkName];
2933
+ try {
2934
+ return this.validateAndTransform(tableName, line)[pkName] ?? line[pkName];
2935
+ } catch {
2936
+ return line[pkName];
2937
+ }
2938
+ }
2939
+ /**
2662
2940
  * Pair each row with the JSONL line it came from, indexed the same way as `rows`.
2663
2941
  * Returns undefined when the rows cannot be matched and the caller can do without it.
2664
2942
  */
2665
2943
  matchExistingRows(tableName, rows, existingRows, options) {
2666
2944
  if (existingRows.length === 0) return rows.map(() => void 0);
2667
2945
  const pkName = this.schemas.get(tableName)?.columns.find((col) => col.primaryKey)?.name;
2668
- const pkValues = pkName ? existingRows.map((row) => row[pkName]) : [];
2946
+ if (pkName && options.positionedLines?.every((line) => line !== void 0)) return options.positionedLines;
2947
+ const pkValues = pkName ? existingRows.map((row) => options.byOutputKey ? this.outputKeyOfLine(tableName, row, pkName) : row[pkName]) : [];
2669
2948
  if (pkName !== void 0 && pkValues.every((value) => value !== void 0 && value !== null) && new Set(pkValues.map((value) => String(value))).size === pkValues.length) {
2670
2949
  const byPk = new Map(existingRows.map((row, index) => [String(pkValues[index]), row]));
2671
- return rows.map((row) => {
2950
+ const positioned = options.positionedLines;
2951
+ const claimed = new Set(positioned?.filter((line) => line !== void 0));
2952
+ return rows.map((row, index) => {
2953
+ const byPosition = positioned?.[index];
2954
+ if (byPosition) return byPosition;
2672
2955
  const pkValue = row[pkName];
2673
- return pkValue === void 0 || pkValue === null ? void 0 : byPk.get(String(pkValue));
2956
+ const byKey = pkValue === void 0 || pkValue === null ? void 0 : byPk.get(String(pkValue));
2957
+ return byKey && !claimed.has(byKey) ? byKey : void 0;
2674
2958
  });
2675
2959
  }
2960
+ if (options.positionedLines) return options.positionedLines;
2676
2961
  if (rows.length !== existingRows.length) {
2677
2962
  if (!options.required) return;
2678
2963
  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 +3119,7 @@ var LinesDB = class LinesDB {
2834
3119
  let fieldChangesBefore;
2835
3120
  let rawSqlTablesBefore;
2836
3121
  let linesWithUnknownFieldsBefore;
3122
+ let linePositionsBefore;
2837
3123
  let originsBefore;
2838
3124
  let columnsBefore;
2839
3125
  const scannedBefore = [...this.scannedJsonlFiles];
@@ -2845,6 +3131,7 @@ var LinesDB = class LinesDB {
2845
3131
  fieldChangesBefore = cloneFieldChanges(this.fieldChanges);
2846
3132
  rawSqlTablesBefore = new Set(this.rawSqlTables);
2847
3133
  linesWithUnknownFieldsBefore = new Map(Array.from(this.linesWithUnknownFields, ([tableName, lines]) => [tableName, new Map(lines)]));
3134
+ linePositionsBefore = new Map(Array.from(this.linePositionsByRowid, ([tableName, positions]) => [tableName, new Map(positions)]));
2848
3135
  this.db.exec("BEGIN TRANSACTION");
2849
3136
  this.settleUndos = [];
2850
3137
  this.inTransaction = true;
@@ -2875,6 +3162,7 @@ var LinesDB = class LinesDB {
2875
3162
  if (fieldChangesBefore) this.fieldChanges = fieldChangesBefore;
2876
3163
  if (rawSqlTablesBefore) this.rawSqlTables = rawSqlTablesBefore;
2877
3164
  if (linesWithUnknownFieldsBefore) this.linesWithUnknownFields = linesWithUnknownFieldsBefore;
3165
+ if (linePositionsBefore) this.linePositionsByRowid = linePositionsBefore;
2878
3166
  const failure = await this.restoreAll(written, error);
2879
3167
  if (this.inTransaction) try {
2880
3168
  this.db.exec("ROLLBACK");
@@ -3261,8 +3549,9 @@ function splitLines(content) {
3261
3549
  const carriage = raw.endsWith("\r") ? "\r" : "";
3262
3550
  const text = carriage ? raw.slice(0, -1) : raw;
3263
3551
  let row;
3264
- if (text.trim() !== "") try {
3265
- const parsed = JSON.parse(text);
3552
+ const trimmed = text.trim();
3553
+ if (trimmed !== "") try {
3554
+ const parsed = JSON.parse(trimmed);
3266
3555
  row = parsed !== null && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : void 0;
3267
3556
  } catch {
3268
3557
  row = void 0;
@@ -3641,28 +3930,31 @@ const validateCommand = defineCommand({
3641
3930
  }
3642
3931
  if (!tableName) {
3643
3932
  const formatter = new ErrorFormatter({ verbose: args.verbose });
3644
- for (const tableResult of result.tableResults) if (tableResult.valid && tableResult.warnings.length === 0) console.log(styleText("green", `✓ ${tableResult.tableName} (${tableResult.rowCount} records)`));
3645
- else if (tableResult.valid && tableResult.warnings.length > 0) for (const warning of tableResult.warnings) console.warn(styleText("yellow", `⚠ ${warning}`));
3646
- else {
3647
- const fileErrors = tableResult.errors;
3648
- console.error(formatter.formatErrorHeader(fileErrors.length, fileErrors[0]?.file));
3649
- console.error("");
3650
- const validationErrors = fileErrors.filter((e) => e.type !== "foreignKey" || !e.foreignKeyError);
3651
- const foreignKeyErrors = fileErrors.filter((e) => e.type === "foreignKey" && e.foreignKeyError);
3652
- if (validationErrors.length > 0) console.error(formatter.formatValidationErrors(validationErrors.map((e) => ({
3653
- file: e.file,
3654
- rowIndex: e.rowIndex,
3655
- issues: e.issues
3656
- }))));
3657
- for (const error of foreignKeyErrors) if (error.foreignKeyError) console.error(formatter.formatForeignKeyError({
3658
- file: error.file,
3659
- rowIndex: error.rowIndex,
3660
- column: error.foreignKeyError.column,
3661
- value: error.foreignKeyError.value,
3662
- referencedTable: error.foreignKeyError.referencedTable,
3663
- referencedColumn: error.foreignKeyError.referencedColumn
3664
- }));
3665
- console.error("");
3933
+ for (const tableResult of result.tableResults) {
3934
+ for (const warning of tableResult.warnings) console.warn(styleText("yellow", `⚠ ${warning}`));
3935
+ if (tableResult.valid) {
3936
+ if (tableResult.warnings.length === 0) console.log(styleText("green", `✓ ${tableResult.tableName} (${tableResult.rowCount} records)`));
3937
+ } else {
3938
+ const fileErrors = tableResult.errors;
3939
+ console.error(formatter.formatErrorHeader(fileErrors.length, fileErrors[0]?.file));
3940
+ console.error("");
3941
+ const validationErrors = fileErrors.filter((e) => e.type !== "foreignKey" || !e.foreignKeyError);
3942
+ const foreignKeyErrors = fileErrors.filter((e) => e.type === "foreignKey" && e.foreignKeyError);
3943
+ if (validationErrors.length > 0) console.error(formatter.formatValidationErrors(validationErrors.map((e) => ({
3944
+ file: e.file,
3945
+ rowIndex: e.rowIndex,
3946
+ issues: e.issues
3947
+ }))));
3948
+ for (const error of foreignKeyErrors) if (error.foreignKeyError) console.error(formatter.formatForeignKeyError({
3949
+ file: error.file,
3950
+ rowIndex: error.rowIndex,
3951
+ column: error.foreignKeyError.column,
3952
+ value: error.foreignKeyError.value,
3953
+ referencedTable: error.foreignKeyError.referencedTable,
3954
+ referencedColumn: error.foreignKeyError.referencedColumn
3955
+ }));
3956
+ console.error("");
3957
+ }
3666
3958
  }
3667
3959
  if (result.valid) {
3668
3960
  console.log("");