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/CHANGELOG.md +26 -0
- package/README.ja.md +21 -3
- package/README.md +21 -3
- package/bin/cli.mjs +394 -102
- package/dist/index.d.mts +57 -2
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +332 -70
- package/dist/index.mjs.map +1 -1
- package/dist/internal.d.mts +1 -1
- package/dist/internal.mjs +1 -1
- package/dist/{schema-module-Tb40gPyF.d.mts → schema-module-C_GKc1zV.d.mts} +3 -1
- package/dist/{schema-module-Tb40gPyF.d.mts.map → schema-module-C_GKc1zV.d.mts.map} +1 -1
- package/dist/{schema-module-D4j10w8_.mjs → schema-module-CdiS2Jq_.mjs} +41 -14
- package/dist/schema-module-CdiS2Jq_.mjs.map +1 -0
- package/package.json +2 -2
- package/dist/schema-module-D4j10w8_.mjs.map +0 -1
package/dist/index.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { a as JsonlReader, c as
|
|
1
|
+
import { a as JsonlReader, c as err, d as unwrap, i as replaceFile, l as ok, n as createSchemaImports, o as hashJsonlContent, r as hashContent, s as jsonlRecordLines, t as MISSING_HASH, u as toError } from "./schema-module-CdiS2Jq_.mjs";
|
|
2
2
|
import { createRequire } from "node:module";
|
|
3
3
|
import { randomBytes } from "node:crypto";
|
|
4
4
|
import { access, chmod, mkdir, readFile, readdir, realpath, rename, rm, stat, writeFile } from "node:fs/promises";
|
|
@@ -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 */
|
|
@@ -575,7 +652,7 @@ var LinesDB = class LinesDB {
|
|
|
575
652
|
const tableTransform = tableNameToLoad === tableName ? transform : void 0;
|
|
576
653
|
const { errors, warnings, rowCounts: tableRowCounts, deferredForeignKeys } = await this.loadTableWithDependencies(tableNameToLoad, loadedTables, loadingTables, attemptedTables, detailedValidate, tableTransform);
|
|
577
654
|
allErrors.push(...errors);
|
|
578
|
-
allWarnings.push(
|
|
655
|
+
for (const warning of warnings) allWarnings.push(warning);
|
|
579
656
|
allDeferredForeignKeys.push(...deferredForeignKeys);
|
|
580
657
|
for (const [k, v] of tableRowCounts) allRowCounts.set(k, v);
|
|
581
658
|
}
|
|
@@ -644,7 +721,7 @@ var LinesDB = class LinesDB {
|
|
|
644
721
|
if (this.tables.has(referencedTable)) {
|
|
645
722
|
const depResult = await this.loadTableWithDependencies(referencedTable, loadedTables, loadingTables, attemptedTables, detailedValidate, void 0);
|
|
646
723
|
errors.push(...depResult.errors);
|
|
647
|
-
|
|
724
|
+
for (const warning of depResult.warnings) warnings.push(warning);
|
|
648
725
|
deferredForeignKeys.push(...depResult.deferredForeignKeys);
|
|
649
726
|
for (const [k, v] of depResult.rowCounts) rowCounts.set(k, v);
|
|
650
727
|
} else throw new Error(`Foreign key reference to non-existent table '${referencedTable}' in table '${tableName}'`);
|
|
@@ -667,7 +744,7 @@ var LinesDB = class LinesDB {
|
|
|
667
744
|
}
|
|
668
745
|
}
|
|
669
746
|
const allSkippedDependencies = /* @__PURE__ */ new Set([...failedDependencies, ...circularDependencies]);
|
|
670
|
-
const { loaded, rowCount, errors: loadErrors } = await this.loadTable(tableName, tableConfig, detailedValidate, transform, allSkippedDependencies);
|
|
747
|
+
const { loaded, rowCount, errors: loadErrors } = await this.loadTable(tableName, tableConfig, detailedValidate, transform, allSkippedDependencies, warnings);
|
|
671
748
|
errors.push(...loadErrors);
|
|
672
749
|
rowCounts.set(tableName, rowCount);
|
|
673
750
|
if (loaded) {
|
|
@@ -704,15 +781,16 @@ var LinesDB = class LinesDB {
|
|
|
704
781
|
* Load a single table from JSONL file
|
|
705
782
|
* @returns Object with loaded status and validation errors
|
|
706
783
|
*/
|
|
707
|
-
async loadTable(tableName, config, detailedValidate, transform, failedDependencies) {
|
|
784
|
+
async loadTable(tableName, config, detailedValidate, transform, failedDependencies, warnings = []) {
|
|
708
785
|
let data = [];
|
|
709
786
|
const origins = [];
|
|
710
787
|
const contentHashes = /* @__PURE__ */ new Map();
|
|
711
788
|
for (const jsonlPath of config.jsonlPaths ?? [config.jsonlPath]) {
|
|
712
789
|
const readResult = await JsonlReader.readSnapshot(jsonlPath);
|
|
713
790
|
if (!readResult.ok) throw readResult.error;
|
|
714
|
-
const { rows, contentHash } = readResult.value;
|
|
791
|
+
const { rows, contentHash, warnings: readWarnings } = readResult.value;
|
|
715
792
|
if (!rows.ok) throw rows.error;
|
|
793
|
+
for (const warning of readWarnings) warnings.push(`Table '${tableName}': ${warning}`);
|
|
716
794
|
if (contentHash !== void 0) {
|
|
717
795
|
contentHashes.set(jsonlPath, contentHash);
|
|
718
796
|
this.observedHashes.set(jsonlPath, contentHash);
|
|
@@ -847,16 +925,26 @@ var LinesDB = class LinesDB {
|
|
|
847
925
|
} else this.insertData(tableName, schema, validatedData);
|
|
848
926
|
this.fieldChanges.delete(tableName);
|
|
849
927
|
this.linesWithUnknownFields.delete(tableName);
|
|
928
|
+
this.linePositionsByRowid.delete(tableName);
|
|
929
|
+
if (this.tracksLinePositions(tableName)) {
|
|
930
|
+
this.logMovedRows(tableName);
|
|
931
|
+
const positions = /* @__PURE__ */ new Map();
|
|
932
|
+
this.rowidsInLineOrder(tableName, validatedData).forEach((rowid, index) => {
|
|
933
|
+
if (rowid !== void 0) positions.set(rowid, index);
|
|
934
|
+
});
|
|
935
|
+
this.linePositionsByRowid.set(tableName, positions);
|
|
936
|
+
}
|
|
850
937
|
const columnNames = new Set(schema.columns.map((column) => column.name));
|
|
851
938
|
const withUnknown = data.map((row) => Object.keys(row).some((key) => !columnNames.has(key)));
|
|
852
939
|
if (transformedFields.some((fields) => fields.length > 0) || withUnknown.includes(true)) {
|
|
853
940
|
const rowids = this.queryInternal(`SELECT rowid AS "${ROWID_ALIAS}" FROM ${this.quoteTableName(tableName)} ORDER BY rowid`);
|
|
854
941
|
const lines = /* @__PURE__ */ new Map();
|
|
855
942
|
const sourceIndexes = new Map(origins.map((origin, index) => [origin, index]));
|
|
943
|
+
const lineIndexes = new Map(this.rowidsInLineOrder(tableName, validatedData).map((rowid, index) => [rowid, index]));
|
|
856
944
|
rowids.forEach((row, index) => {
|
|
857
945
|
const rowid = row[ROWID_ALIAS];
|
|
858
946
|
const origin = this.rowOriginsByRowid.get(tableName)?.get(String(rowid));
|
|
859
|
-
const sourceIndex = origin ? sourceIndexes.get(origin) ?? index : index;
|
|
947
|
+
const sourceIndex = origin ? sourceIndexes.get(origin) ?? index : lineIndexes.get(String(rowid)) ?? index;
|
|
860
948
|
const set = transformedFields[sourceIndex] ?? [];
|
|
861
949
|
if (set.length > 0) this.noteFieldChanges(tableName, rowid, { set });
|
|
862
950
|
if (withUnknown[sourceIndex]) lines.set(String(rowid), data[sourceIndex]);
|
|
@@ -1146,9 +1234,11 @@ var LinesDB = class LinesDB {
|
|
|
1146
1234
|
try {
|
|
1147
1235
|
return run();
|
|
1148
1236
|
} finally {
|
|
1237
|
+
this.applyMovedRows();
|
|
1149
1238
|
if (this.totalChanges() !== before) {
|
|
1150
1239
|
for (const tableName of this.schemas.keys()) {
|
|
1151
1240
|
this.rawSqlTables.add(tableName);
|
|
1241
|
+
this.linePositionsByRowid.delete(tableName);
|
|
1152
1242
|
this.noteChange(tableName);
|
|
1153
1243
|
}
|
|
1154
1244
|
this.forgetLinesOfGoneRows(this.schemas.keys());
|
|
@@ -1325,8 +1415,10 @@ var LinesDB = class LinesDB {
|
|
|
1325
1415
|
});
|
|
1326
1416
|
this.rowOriginsByRowid.set(tableName, origins);
|
|
1327
1417
|
}
|
|
1418
|
+
this.forgetPosition(tableName, String(result.lastInsertRowid));
|
|
1328
1419
|
this.noteFieldChanges(tableName, result.lastInsertRowid, {
|
|
1329
1420
|
set: givenFields(data),
|
|
1421
|
+
inputs: transformedInputs(data, row),
|
|
1330
1422
|
inserted: true
|
|
1331
1423
|
});
|
|
1332
1424
|
this.afterWrite(tableName, result.changes);
|
|
@@ -1391,8 +1483,10 @@ var LinesDB = class LinesDB {
|
|
|
1391
1483
|
undoSettle();
|
|
1392
1484
|
throw error;
|
|
1393
1485
|
}
|
|
1486
|
+
this.forgetPosition(tableName, String(result.lastInsertRowid));
|
|
1394
1487
|
this.noteFieldChanges(tableName, result.lastInsertRowid, {
|
|
1395
1488
|
set: givenFields(record),
|
|
1489
|
+
inputs: transformedInputs(record, row),
|
|
1396
1490
|
inserted: true
|
|
1397
1491
|
});
|
|
1398
1492
|
totalChanges += BigInt(result.changes);
|
|
@@ -1422,44 +1516,58 @@ var LinesDB = class LinesDB {
|
|
|
1422
1516
|
updateInternal(tableName, data, where, options) {
|
|
1423
1517
|
this.assertMutable(tableName);
|
|
1424
1518
|
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
1519
|
const { sql: whereSql, values: whereValues, functionFilters } = this.buildWhereClause(where, tableName);
|
|
1439
1520
|
if (functionFilters.length > 0) throw new Error("Function filters are not supported in update operations");
|
|
1440
1521
|
const targets = this.queryInternal(`SELECT rowid AS "${ROWID_ALIAS}", * FROM ${this.quoteTableName(tableName)} WHERE ${whereSql}`, whereValues);
|
|
1522
|
+
const shouldValidate = options?.validate !== false;
|
|
1523
|
+
const hasValidationSchema = this.validationSchemas.has(tableName);
|
|
1524
|
+
const givenKeys = Object.keys(data);
|
|
1441
1525
|
const resetFields = options?.resetToDefault ?? [];
|
|
1526
|
+
const storedValues = targets.map((target) => {
|
|
1527
|
+
if (!shouldValidate || !hasValidationSchema) return data;
|
|
1528
|
+
const { [ROWID_ALIAS]: _rowid, ...stored } = target;
|
|
1529
|
+
const merged = {
|
|
1530
|
+
...this.deserializeRow(tableName, stored),
|
|
1531
|
+
...data
|
|
1532
|
+
};
|
|
1533
|
+
for (const field of resetFields) delete merged[field];
|
|
1534
|
+
const validated = this.validateAndTransform(tableName, merged);
|
|
1535
|
+
return Object.fromEntries(givenKeys.map((key) => [key, Object.hasOwn(validated, key) ? validated[key] : data[key]]));
|
|
1536
|
+
});
|
|
1442
1537
|
const resets = resetFields.length > 0 ? this.computeResets(tableName, targets, data, resetFields) : [];
|
|
1443
1538
|
let result = {
|
|
1444
1539
|
changes: 0,
|
|
1445
1540
|
lastInsertRowid: 0
|
|
1446
1541
|
};
|
|
1447
|
-
if (
|
|
1448
|
-
const setClauses =
|
|
1449
|
-
const sql = `UPDATE ${this.quoteTableName(tableName)} SET ${setClauses} WHERE
|
|
1450
|
-
const
|
|
1451
|
-
|
|
1542
|
+
if (givenKeys.length > 0 && targets.length > 0) {
|
|
1543
|
+
const setClauses = givenKeys.map((key) => `${this.quoteIdentifier(key)} = ?`).join(", ");
|
|
1544
|
+
const sql = `UPDATE ${this.quoteTableName(tableName)} SET ${setClauses} WHERE rowid = ?`;
|
|
1545
|
+
const undoSettle = this.settleColumnsNoRowHolds(this.schemas.get(tableName), storedValues[0]);
|
|
1546
|
+
let changes = 0n;
|
|
1547
|
+
let lastInsertRowid = 0;
|
|
1548
|
+
this.db.exec("SAVEPOINT lines_db_update");
|
|
1452
1549
|
try {
|
|
1453
|
-
|
|
1550
|
+
targets.forEach((target, index) => {
|
|
1551
|
+
const written = this.executeInternal(sql, [...givenKeys.map((key) => this.normalizeValue(storedValues[index][key], this.columnOf(tableName, key))), target[ROWID_ALIAS]]);
|
|
1552
|
+
changes += BigInt(written.changes);
|
|
1553
|
+
lastInsertRowid = written.lastInsertRowid;
|
|
1554
|
+
});
|
|
1555
|
+
this.db.exec("RELEASE lines_db_update");
|
|
1454
1556
|
} catch (error) {
|
|
1557
|
+
this.db.exec("ROLLBACK TO lines_db_update");
|
|
1558
|
+
this.db.exec("RELEASE lines_db_update");
|
|
1455
1559
|
undoSettle();
|
|
1456
1560
|
throw error;
|
|
1457
1561
|
}
|
|
1458
|
-
|
|
1562
|
+
result = {
|
|
1563
|
+
changes: Number(changes),
|
|
1564
|
+
lastInsertRowid
|
|
1565
|
+
};
|
|
1566
|
+
if (changes === 0n) undoSettle();
|
|
1459
1567
|
}
|
|
1460
1568
|
const pkName = this.schemas.get(tableName)?.columns.find((col) => col.primaryKey)?.name;
|
|
1461
1569
|
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))]);
|
|
1570
|
+
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
1571
|
if (targets.length === 1 && moved.length === 1) {
|
|
1464
1572
|
const from = String(targets[0][ROWID_ALIAS]);
|
|
1465
1573
|
const to = moved[0][ROWID_ALIAS];
|
|
@@ -1472,10 +1580,14 @@ var LinesDB = class LinesDB {
|
|
|
1472
1580
|
}
|
|
1473
1581
|
}
|
|
1474
1582
|
}
|
|
1475
|
-
|
|
1476
|
-
const set =
|
|
1477
|
-
|
|
1478
|
-
|
|
1583
|
+
targets.forEach((target, index) => {
|
|
1584
|
+
const set = givenKeys.filter((key) => !sameStoredValue(target[key], this.normalizeValue(storedValues[index][key], this.columnOf(tableName, key))));
|
|
1585
|
+
const given = Object.fromEntries(set.map((key) => [key, data[key]]));
|
|
1586
|
+
this.noteFieldChanges(tableName, target[ROWID_ALIAS], {
|
|
1587
|
+
set,
|
|
1588
|
+
inputs: transformedInputs(given, storedValues[index])
|
|
1589
|
+
});
|
|
1590
|
+
});
|
|
1479
1591
|
if (resets.length > 0) result = this.applyResets(tableName, resets, resetFields);
|
|
1480
1592
|
this.afterWrite(tableName, result.changes);
|
|
1481
1593
|
return result;
|
|
@@ -1829,9 +1941,18 @@ var LinesDB = class LinesDB {
|
|
|
1829
1941
|
this.assertWritable(tableName);
|
|
1830
1942
|
const config = this.tables.get(tableName);
|
|
1831
1943
|
if (!config) throw new Error(`Table ${tableName} not found`);
|
|
1944
|
+
this.positionEdits.set(tableName, []);
|
|
1832
1945
|
const stored = this.readStoredRows(tableName);
|
|
1833
|
-
|
|
1834
|
-
const
|
|
1946
|
+
const recorded = this.linePositionsByRowid.get(tableName);
|
|
1947
|
+
const atRead = {
|
|
1948
|
+
generation: this.changeGenerations.get(tableName) ?? 0,
|
|
1949
|
+
positions: recorded && new Map(recorded),
|
|
1950
|
+
origins: new Map(this.rowOriginsByRowid.get(tableName) ?? []),
|
|
1951
|
+
changes: cloneFieldChanges(/* @__PURE__ */ new Map([[tableName, this.fieldChanges.get(tableName) ?? /* @__PURE__ */ new Map()]])).get(tableName),
|
|
1952
|
+
unknownFieldLines: new Map(this.linesWithUnknownFields.get(tableName) ?? [])
|
|
1953
|
+
};
|
|
1954
|
+
if (!this.hasSeveralDataDirs()) return [await this.prepareFileWriteBack(tableName, config.jsonlPath, stored, options, atRead)];
|
|
1955
|
+
const origins = atRead.origins;
|
|
1835
1956
|
const byFile = new Map([this.config.dataDir].flat().map((dir) => [join(dir, `${tableName}.jsonl`), []]));
|
|
1836
1957
|
stored.rowids.forEach((rowid, index) => {
|
|
1837
1958
|
const origin = origins?.get(rowid);
|
|
@@ -1848,33 +1969,98 @@ var LinesDB = class LinesDB {
|
|
|
1848
1969
|
rows: indexes.map((i) => stored.rows[i]),
|
|
1849
1970
|
lineRows: indexes.map((i) => stored.lineRows[i])
|
|
1850
1971
|
};
|
|
1851
|
-
const fileWrite = await this.prepareFileWriteBack(tableName, file, rows, options);
|
|
1972
|
+
const fileWrite = await this.prepareFileWriteBack(tableName, file, rows, options, atRead);
|
|
1852
1973
|
if (!fileWrite.unchanged) prepared.push(fileWrite);
|
|
1853
1974
|
}
|
|
1854
1975
|
return prepared;
|
|
1855
1976
|
}
|
|
1856
|
-
|
|
1977
|
+
forgetPosition(tableName, rowid) {
|
|
1978
|
+
this.linePositionsByRowid.get(tableName)?.delete(rowid);
|
|
1979
|
+
this.positionEdits.get(tableName)?.push({ forget: rowid });
|
|
1980
|
+
}
|
|
1981
|
+
/**
|
|
1982
|
+
* The rowid of the row each line was loaded into, in the order of the lines. Not the rowid order: an INTEGER
|
|
1983
|
+
* PRIMARY KEY is the rowid, so the line `{"id":3}` first in its file is the row with rowid 3
|
|
1984
|
+
*/
|
|
1985
|
+
rowidsInLineOrder(tableName, rows) {
|
|
1986
|
+
const pk = this.schemas.get(tableName)?.columns.find((column) => column.primaryKey);
|
|
1987
|
+
const stored = this.queryInternal(`SELECT rowid AS "${ROWID_ALIAS}" FROM ${this.quoteTableName(tableName)} ORDER BY rowid`).map((row) => String(row[ROWID_ALIAS]));
|
|
1988
|
+
if (pk?.type !== "INTEGER") return stored;
|
|
1989
|
+
const present = new Set(stored);
|
|
1990
|
+
let largest;
|
|
1991
|
+
return rows.map((row) => {
|
|
1992
|
+
const key = row[pk.name];
|
|
1993
|
+
const rowid = key === void 0 || key === null ? (largest ?? 0) + 1 : Number(key);
|
|
1994
|
+
largest = largest === void 0 ? rowid : Math.max(largest, rowid);
|
|
1995
|
+
return present.has(String(rowid)) ? String(rowid) : void 0;
|
|
1996
|
+
});
|
|
1997
|
+
}
|
|
1998
|
+
/**
|
|
1999
|
+
* Log each change of a row's rowid in the table: a foreign-key action or raw SQL can change an INTEGER PRIMARY
|
|
2000
|
+
* KEY, which is the rowid, without a write through this database telling it which row moved
|
|
2001
|
+
*/
|
|
2002
|
+
logMovedRows(tableName) {
|
|
2003
|
+
if (!this.movedRowsLogReady) {
|
|
2004
|
+
this.db.exec(`CREATE TEMP TABLE IF NOT EXISTS ${MOVED_ROWS_LOG} (tbl TEXT, old INTEGER, new INTEGER)`);
|
|
2005
|
+
this.movedRowsLogReady = true;
|
|
2006
|
+
}
|
|
2007
|
+
const trigger = this.quoteIdentifier(`__lines_db_moved_${tableName}`);
|
|
2008
|
+
const name = `'${tableName.replace(/'/g, "''")}'`;
|
|
2009
|
+
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`);
|
|
2010
|
+
}
|
|
2011
|
+
/** Move what is kept by rowid to the rowid each logged row moved to, in the order the rows moved */
|
|
2012
|
+
applyMovedRows() {
|
|
2013
|
+
if (!this.movedRowsLogReady) return;
|
|
2014
|
+
const moved = this.queryInternal(`SELECT tbl, old, new FROM ${MOVED_ROWS_LOG} ORDER BY rowid`);
|
|
2015
|
+
if (moved.length === 0) return;
|
|
2016
|
+
this.db.exec(`DELETE FROM ${MOVED_ROWS_LOG}`);
|
|
2017
|
+
for (const { tbl, old, new: to } of moved) this.moveRowMetadata(String(tbl), String(old), String(to));
|
|
2018
|
+
}
|
|
2019
|
+
/**
|
|
2020
|
+
* Whether the lines of a table are remembered by position, so a row whose key changed, or that has none, is
|
|
2021
|
+
* found again by where its line stood. Several data directories have the origin of each row instead
|
|
2022
|
+
*/
|
|
2023
|
+
tracksLinePositions(_tableName) {
|
|
2024
|
+
return !this.hasSeveralDataDirs();
|
|
2025
|
+
}
|
|
2026
|
+
hasNoPrimaryKey(tableName) {
|
|
2027
|
+
return this.schemas.get(tableName)?.columns.some((column) => column.primaryKey) === false;
|
|
2028
|
+
}
|
|
2029
|
+
async prepareFileWriteBack(tableName, jsonlPath, stored, options, atRead) {
|
|
1857
2030
|
const { rowids, rows: deserializedRows, lineRows } = stored;
|
|
1858
|
-
const generation = this.changeGenerations.get(tableName) ?? 0;
|
|
2031
|
+
const generation = atRead?.generation ?? this.changeGenerations.get(tableName) ?? 0;
|
|
1859
2032
|
let finalRows = lineRows;
|
|
1860
2033
|
const previousContent = await readFile(jsonlPath, "utf-8").catch((error) => {
|
|
1861
2034
|
if (error.code === "ENOENT") return void 0;
|
|
1862
2035
|
throw error;
|
|
1863
2036
|
});
|
|
1864
2037
|
const existingRows = await this.readUnchangedRows(jsonlPath);
|
|
1865
|
-
const
|
|
2038
|
+
const origins = atRead?.origins ?? this.rowOriginsByRowid.get(tableName);
|
|
2039
|
+
const matchedByOrigin = this.hasSeveralDataDirs() ? rowids.map((rowid) => {
|
|
2040
|
+
const origin = origins?.get(rowid);
|
|
2041
|
+
return origin && existingRows[origin.rowIndex];
|
|
2042
|
+
}) : void 0;
|
|
2043
|
+
const byPosition = matchedByOrigin ? void 0 : linesByPosition(atRead?.positions, rowids, existingRows);
|
|
2044
|
+
const matches = matchedByOrigin ?? (this.hasNoPrimaryKey(tableName) ? byPosition : void 0);
|
|
2045
|
+
const positionedLines = matches ? void 0 : byPosition;
|
|
1866
2046
|
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
|
|
2047
|
+
if ((options?.writeFilledValues ?? this.config.writeFilledValues ?? "all") === "primaryKey") finalRows = this.keepWrittenFields(tableName, rowids, deserializedRows, finalRows, existingRows, fields, matches, {
|
|
2048
|
+
positionedLines,
|
|
2049
|
+
changes: atRead?.changes
|
|
2050
|
+
}).map(({ written }) => written);
|
|
1868
2051
|
const columns = new Set(this.schemas.get(tableName)?.columns.map((column) => column.name));
|
|
1869
|
-
const readLines = this.linesWithUnknownFields.get(tableName);
|
|
2052
|
+
const readLines = atRead?.unknownFieldLines ?? this.linesWithUnknownFields.get(tableName);
|
|
1870
2053
|
finalRows = finalRows.map((row, index) => {
|
|
1871
2054
|
const line = readLines?.get(rowids[index]);
|
|
1872
2055
|
return line ? keepUnknownFields(line, row, columns) : row;
|
|
1873
2056
|
});
|
|
2057
|
+
let linesOfRows;
|
|
1874
2058
|
finalRows = this.mergeWithExistingLines(tableName, existingRows, finalRows, {
|
|
1875
2059
|
fields,
|
|
1876
2060
|
strictFields: options?.strictFields ?? false,
|
|
1877
|
-
matches
|
|
2061
|
+
matches,
|
|
2062
|
+
positionedLines,
|
|
2063
|
+
onMatched: (lines) => linesOfRows = lines
|
|
1878
2064
|
});
|
|
1879
2065
|
return {
|
|
1880
2066
|
tableName,
|
|
@@ -1882,10 +2068,11 @@ var LinesDB = class LinesDB {
|
|
|
1882
2068
|
rows: finalRows,
|
|
1883
2069
|
previousContent,
|
|
1884
2070
|
generation,
|
|
1885
|
-
...
|
|
2071
|
+
...matchedByOrigin ? {
|
|
1886
2072
|
rowids,
|
|
1887
2073
|
unchanged: JsonlWriter.serialize(existingRows) === JsonlWriter.serialize(finalRows)
|
|
1888
|
-
} : {}
|
|
2074
|
+
} : {},
|
|
2075
|
+
...this.tracksLinePositions(tableName) && !matchedByOrigin ? { positions: linesOfRows ? positionsAfterWrite(rowids, linesOfRows, existingRows) : new Map(rowids.map((rowid, position) => [rowid, position])) } : {}
|
|
1889
2076
|
};
|
|
1890
2077
|
}
|
|
1891
2078
|
/**
|
|
@@ -1908,17 +2095,22 @@ var LinesDB = class LinesDB {
|
|
|
1908
2095
|
* minus those reset to their default - its primary key and the fields named to be written back, so
|
|
1909
2096
|
* a value the schema fills in stays out of the file
|
|
1910
2097
|
*/
|
|
1911
|
-
keepWrittenFields(tableName, rowids, rows, lineRows, existingRows, namedFields = [], matchedLines) {
|
|
2098
|
+
keepWrittenFields(tableName, rowids, rows, lineRows, existingRows, namedFields = [], matchedLines, options) {
|
|
1912
2099
|
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, {
|
|
1915
|
-
|
|
2100
|
+
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);
|
|
2101
|
+
const lines = matchedLines ?? this.matchExistingRows(tableName, lineRows, existingRows, {
|
|
2102
|
+
required: false,
|
|
2103
|
+
byOutputKey: true,
|
|
2104
|
+
positionedLines: options?.positionedLines
|
|
2105
|
+
});
|
|
2106
|
+
const changes = options?.changes ?? this.fieldChanges.get(tableName);
|
|
1916
2107
|
return lineRows.map((lineRow, index) => {
|
|
1917
2108
|
const line = lines?.[index];
|
|
1918
2109
|
const rowChanges = changes?.get(rowids[index]);
|
|
1919
2110
|
if (Object.keys(lineRow).some((key) => !Object.hasOwn(rows[index], key)) || this.rawSqlTables.has(tableName) || !line && !rowChanges?.inserted) return {
|
|
1920
2111
|
written: lineRow,
|
|
1921
|
-
narrowed: false
|
|
2112
|
+
narrowed: false,
|
|
2113
|
+
line
|
|
1922
2114
|
};
|
|
1923
2115
|
const keep = /* @__PURE__ */ new Set([
|
|
1924
2116
|
...Object.keys(line ?? {}),
|
|
@@ -1928,10 +2120,11 @@ var LinesDB = class LinesDB {
|
|
|
1928
2120
|
for (const key of rowChanges?.reset ?? []) keep.delete(key);
|
|
1929
2121
|
for (const key of namedFields) keep.add(key);
|
|
1930
2122
|
if (pkName) keep.add(pkName);
|
|
1931
|
-
const untouched = line !== void 0 && !rowChanges?.inserted && !rowChanges?.set.
|
|
2123
|
+
const untouched = (key) => line !== void 0 && !rowChanges?.inserted && Object.hasOwn(line, key) && !rowChanges?.set.has(key) && !rowChanges?.reset.has(key);
|
|
1932
2124
|
return {
|
|
1933
|
-
written: Object.fromEntries(Object.entries(lineRow).filter(([key]) => keep.has(key)).map(([key, value]) => [key, untouched &&
|
|
1934
|
-
narrowed: true
|
|
2125
|
+
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])),
|
|
2126
|
+
narrowed: true,
|
|
2127
|
+
line
|
|
1935
2128
|
};
|
|
1936
2129
|
});
|
|
1937
2130
|
}
|
|
@@ -1943,10 +2136,15 @@ var LinesDB = class LinesDB {
|
|
|
1943
2136
|
* later, which must not inherit them
|
|
1944
2137
|
*/
|
|
1945
2138
|
moveRowMetadata(tableName, from, to) {
|
|
2139
|
+
this.positionEdits.get(tableName)?.push({
|
|
2140
|
+
from,
|
|
2141
|
+
to
|
|
2142
|
+
});
|
|
1946
2143
|
for (const byRow of [
|
|
1947
2144
|
this.fieldChanges.get(tableName),
|
|
1948
2145
|
this.linesWithUnknownFields.get(tableName),
|
|
1949
|
-
this.rowOriginsByRowid.get(tableName)
|
|
2146
|
+
this.rowOriginsByRowid.get(tableName),
|
|
2147
|
+
this.linePositionsByRowid.get(tableName)
|
|
1950
2148
|
]) {
|
|
1951
2149
|
const kept = byRow?.get(from);
|
|
1952
2150
|
if (!byRow || kept === void 0) continue;
|
|
@@ -1971,6 +2169,7 @@ var LinesDB = class LinesDB {
|
|
|
1971
2169
|
}
|
|
1972
2170
|
forgetFieldChanges(tableName, rowids) {
|
|
1973
2171
|
for (const rowid of rowids) {
|
|
2172
|
+
this.forgetPosition(tableName, rowid);
|
|
1974
2173
|
this.fieldChanges.get(tableName)?.delete(rowid);
|
|
1975
2174
|
this.linesWithUnknownFields.get(tableName)?.delete(rowid);
|
|
1976
2175
|
}
|
|
@@ -1990,10 +2189,16 @@ var LinesDB = class LinesDB {
|
|
|
1990
2189
|
for (const key of changes.set ?? []) {
|
|
1991
2190
|
rowChanges.set.add(key);
|
|
1992
2191
|
rowChanges.reset.delete(key);
|
|
2192
|
+
rowChanges.inputs?.delete(key);
|
|
1993
2193
|
}
|
|
1994
2194
|
for (const key of changes.reset ?? []) {
|
|
1995
2195
|
rowChanges.reset.add(key);
|
|
1996
2196
|
rowChanges.set.delete(key);
|
|
2197
|
+
rowChanges.inputs?.delete(key);
|
|
2198
|
+
}
|
|
2199
|
+
for (const [key, value] of changes.inputs ?? []) {
|
|
2200
|
+
rowChanges.inputs ??= /* @__PURE__ */ new Map();
|
|
2201
|
+
rowChanges.inputs.set(key, value);
|
|
1997
2202
|
}
|
|
1998
2203
|
byRow.set(String(rowid), rowChanges);
|
|
1999
2204
|
this.fieldChanges.set(tableName, byRow);
|
|
@@ -2034,25 +2239,49 @@ var LinesDB = class LinesDB {
|
|
|
2034
2239
|
}
|
|
2035
2240
|
/**
|
|
2036
2241
|
* 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
|
|
2242
|
+
* does not hold and no write set, which a write-back leaves out of the file. `input` is the row as
|
|
2243
|
+
* its line holds it - the values before the schema transformed them, without the defaulted fields.
|
|
2038
2244
|
*/
|
|
2039
2245
|
async findWithDefaults(tableName) {
|
|
2040
2246
|
try {
|
|
2041
2247
|
const tableConfig = this.tables.get(tableName);
|
|
2042
2248
|
if (!tableConfig || !this.schemas.has(tableName)) throw new Error(`Table '${tableName}' is not loaded`);
|
|
2043
|
-
|
|
2044
|
-
|
|
2045
|
-
|
|
2046
|
-
for (
|
|
2249
|
+
let stored;
|
|
2250
|
+
let positionsAtRead;
|
|
2251
|
+
let fileRows;
|
|
2252
|
+
for (let attempt = 1;; attempt++) {
|
|
2253
|
+
await this.waitForPendingSyncs();
|
|
2254
|
+
const files = this.hasSeveralDataDirs() ? [.../* @__PURE__ */ new Set([...tableConfig.jsonlPaths ?? [tableConfig.jsonlPath], ...[...this.rowOriginsByRowid.get(tableName)?.values() ?? []].map((origin) => origin.file)])] : [tableConfig.jsonlPath];
|
|
2255
|
+
const generation = this.changeGenerations.get(tableName) ?? 0;
|
|
2256
|
+
const hashes = files.map((file) => this.fileHashes.get(file));
|
|
2257
|
+
stored = this.readStoredRows(tableName);
|
|
2258
|
+
const recorded = this.linePositionsByRowid.get(tableName);
|
|
2259
|
+
positionsAtRead = recorded && new Map(recorded);
|
|
2260
|
+
fileRows = /* @__PURE__ */ new Map();
|
|
2261
|
+
const unchanged = () => (this.changeGenerations.get(tableName) ?? 0) === generation && files.every((file, index) => this.fileHashes.get(file) === hashes[index]);
|
|
2262
|
+
try {
|
|
2263
|
+
for (const file of files) fileRows.set(file, await this.readUnchangedRows(file));
|
|
2264
|
+
} catch (error) {
|
|
2265
|
+
if (!(error instanceof Error && error.name === "JsonlConflictError") || unchanged()) throw error;
|
|
2266
|
+
}
|
|
2267
|
+
if (unchanged()) break;
|
|
2268
|
+
if (attempt >= 5) throw new Error(`The rows of '${tableName}' kept changing while they were read; read them again`);
|
|
2269
|
+
}
|
|
2270
|
+
const { rowids, rows, lineRows } = stored;
|
|
2047
2271
|
const existingRows = [...fileRows.values()].flat();
|
|
2048
2272
|
const matches = this.hasSeveralDataDirs() && this.config.writeDataSets ? rowids.map((rowid) => {
|
|
2049
2273
|
const origin = this.rowOriginsByRowid.get(tableName)?.get(rowid);
|
|
2050
2274
|
return origin && fileRows.get(origin.file)?.[origin.rowIndex];
|
|
2051
|
-
}) :
|
|
2275
|
+
}) : linesByPosition(positionsAtRead, rowids, existingRows);
|
|
2052
2276
|
const kept = this.keepWrittenFields(tableName, rowids, rows, lineRows, existingRows, this.config.writeBackFields, matches);
|
|
2277
|
+
const lines = this.keepWrittenFields(tableName, rowids, rows, lineRows, existingRows, [], matches, { ignoreActions: true });
|
|
2053
2278
|
return ok(rows.map((row, index) => ({
|
|
2054
2279
|
row,
|
|
2055
|
-
defaulted: kept[index].narrowed ? Object.keys(row).filter((key) => !Object.hasOwn(kept[index].written, key)) : []
|
|
2280
|
+
defaulted: kept[index].narrowed ? Object.keys(row).filter((key) => !Object.hasOwn(kept[index].written, key)) : [],
|
|
2281
|
+
input: {
|
|
2282
|
+
...lines[index].written,
|
|
2283
|
+
...Object.fromEntries(Object.entries(lines[index].line ?? {}).filter(([key]) => !Object.hasOwn(lines[index].written, key) && !Object.hasOwn(row, key)))
|
|
2284
|
+
}
|
|
2056
2285
|
})));
|
|
2057
2286
|
} catch (error) {
|
|
2058
2287
|
return err(toError(error));
|
|
@@ -2072,6 +2301,7 @@ var LinesDB = class LinesDB {
|
|
|
2072
2301
|
* tables it changed once its callback is done
|
|
2073
2302
|
*/
|
|
2074
2303
|
afterWrite(tableName, changes) {
|
|
2304
|
+
this.applyMovedRows();
|
|
2075
2305
|
if (BigInt(changes) === 0n && this.transactionChanges) return;
|
|
2076
2306
|
const tableNames = [tableName, ...this.tablesChangedByForeignKeyActions(tableName)];
|
|
2077
2307
|
this.forgetLinesOfGoneRows(tableNames);
|
|
@@ -2125,17 +2355,20 @@ var LinesDB = class LinesDB {
|
|
|
2125
2355
|
} catch (error) {
|
|
2126
2356
|
throw await this.restoreAll(written, error);
|
|
2127
2357
|
}
|
|
2128
|
-
for (const { tableName, jsonlPath, generation, rowids } of written) {
|
|
2358
|
+
for (const { tableName, jsonlPath, generation, rowids, positions } of written) {
|
|
2359
|
+
const edits = this.positionEdits.get(tableName) ?? [];
|
|
2360
|
+
if (positions) this.linePositionsByRowid.set(tableName, replayEdits(positions, edits));
|
|
2129
2361
|
if ((this.changeGenerations.get(tableName) ?? 0) === generation) {
|
|
2130
2362
|
this.fieldChanges.delete(tableName);
|
|
2131
2363
|
this.rawSqlTables.delete(tableName);
|
|
2132
2364
|
}
|
|
2133
2365
|
if (rowids) {
|
|
2134
2366
|
const origins = this.rowOriginsByRowid.get(tableName);
|
|
2135
|
-
rowids.
|
|
2367
|
+
const writtenOrigins = new Map(rowids.map((rowid, rowIndex) => [rowid, {
|
|
2136
2368
|
file: jsonlPath,
|
|
2137
2369
|
rowIndex
|
|
2138
|
-
}));
|
|
2370
|
+
}]));
|
|
2371
|
+
for (const [rowid, origin] of replayEdits(writtenOrigins, edits)) origins.set(rowid, origin);
|
|
2139
2372
|
if (!this.scannedJsonlFiles.includes(jsonlPath)) this.scannedJsonlFiles.push(jsonlPath);
|
|
2140
2373
|
}
|
|
2141
2374
|
}
|
|
@@ -2203,7 +2436,11 @@ var LinesDB = class LinesDB {
|
|
|
2203
2436
|
const unknownFields = fields.filter((field) => !tableFields.includes(field));
|
|
2204
2437
|
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
2438
|
}
|
|
2206
|
-
const existing = options.matches ?? this.matchExistingRows(tableName, rows, existingRows, {
|
|
2439
|
+
const existing = options.matches ?? this.matchExistingRows(tableName, rows, existingRows, {
|
|
2440
|
+
required: fields !== void 0,
|
|
2441
|
+
positionedLines: options.positionedLines
|
|
2442
|
+
});
|
|
2443
|
+
options.onMatched?.(existing);
|
|
2207
2444
|
if (!existing) return rows;
|
|
2208
2445
|
const rowByLine = /* @__PURE__ */ new Map();
|
|
2209
2446
|
const newRows = [];
|
|
@@ -2221,20 +2458,41 @@ var LinesDB = class LinesDB {
|
|
|
2221
2458
|
}), ...newRows];
|
|
2222
2459
|
}
|
|
2223
2460
|
/**
|
|
2461
|
+
* The primary key the schema makes of a line, which is how the stored rows hold it. The line's own key
|
|
2462
|
+
* when the rows are in the line's terms (a `backward` transformation maps them back), when there is no
|
|
2463
|
+
* schema, or when the schema refuses the line
|
|
2464
|
+
*/
|
|
2465
|
+
outputKeyOfLine(tableName, line, pkName) {
|
|
2466
|
+
const schema = this.validationSchemas.get(tableName);
|
|
2467
|
+
if (!schema || hasBackward(schema) || line[pkName] === void 0 || line[pkName] === null) return line[pkName];
|
|
2468
|
+
try {
|
|
2469
|
+
return this.validateAndTransform(tableName, line)[pkName] ?? line[pkName];
|
|
2470
|
+
} catch {
|
|
2471
|
+
return line[pkName];
|
|
2472
|
+
}
|
|
2473
|
+
}
|
|
2474
|
+
/**
|
|
2224
2475
|
* Pair each row with the JSONL line it came from, indexed the same way as `rows`.
|
|
2225
2476
|
* Returns undefined when the rows cannot be matched and the caller can do without it.
|
|
2226
2477
|
*/
|
|
2227
2478
|
matchExistingRows(tableName, rows, existingRows, options) {
|
|
2228
2479
|
if (existingRows.length === 0) return rows.map(() => void 0);
|
|
2229
2480
|
const pkName = this.schemas.get(tableName)?.columns.find((col) => col.primaryKey)?.name;
|
|
2230
|
-
|
|
2481
|
+
if (pkName && options.positionedLines?.every((line) => line !== void 0)) return options.positionedLines;
|
|
2482
|
+
const pkValues = pkName ? existingRows.map((row) => options.byOutputKey ? this.outputKeyOfLine(tableName, row, pkName) : row[pkName]) : [];
|
|
2231
2483
|
if (pkName !== void 0 && pkValues.every((value) => value !== void 0 && value !== null) && new Set(pkValues.map((value) => String(value))).size === pkValues.length) {
|
|
2232
2484
|
const byPk = new Map(existingRows.map((row, index) => [String(pkValues[index]), row]));
|
|
2233
|
-
|
|
2485
|
+
const positioned = options.positionedLines;
|
|
2486
|
+
const claimed = new Set(positioned?.filter((line) => line !== void 0));
|
|
2487
|
+
return rows.map((row, index) => {
|
|
2488
|
+
const byPosition = positioned?.[index];
|
|
2489
|
+
if (byPosition) return byPosition;
|
|
2234
2490
|
const pkValue = row[pkName];
|
|
2235
|
-
|
|
2491
|
+
const byKey = pkValue === void 0 || pkValue === null ? void 0 : byPk.get(String(pkValue));
|
|
2492
|
+
return byKey && !claimed.has(byKey) ? byKey : void 0;
|
|
2236
2493
|
});
|
|
2237
2494
|
}
|
|
2495
|
+
if (options.positionedLines) return options.positionedLines;
|
|
2238
2496
|
if (rows.length !== existingRows.length) {
|
|
2239
2497
|
if (!options.required) return;
|
|
2240
2498
|
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 +2654,7 @@ var LinesDB = class LinesDB {
|
|
|
2396
2654
|
let fieldChangesBefore;
|
|
2397
2655
|
let rawSqlTablesBefore;
|
|
2398
2656
|
let linesWithUnknownFieldsBefore;
|
|
2657
|
+
let linePositionsBefore;
|
|
2399
2658
|
let originsBefore;
|
|
2400
2659
|
let columnsBefore;
|
|
2401
2660
|
const scannedBefore = [...this.scannedJsonlFiles];
|
|
@@ -2407,6 +2666,7 @@ var LinesDB = class LinesDB {
|
|
|
2407
2666
|
fieldChangesBefore = cloneFieldChanges(this.fieldChanges);
|
|
2408
2667
|
rawSqlTablesBefore = new Set(this.rawSqlTables);
|
|
2409
2668
|
linesWithUnknownFieldsBefore = new Map(Array.from(this.linesWithUnknownFields, ([tableName, lines]) => [tableName, new Map(lines)]));
|
|
2669
|
+
linePositionsBefore = new Map(Array.from(this.linePositionsByRowid, ([tableName, positions]) => [tableName, new Map(positions)]));
|
|
2410
2670
|
this.db.exec("BEGIN TRANSACTION");
|
|
2411
2671
|
this.settleUndos = [];
|
|
2412
2672
|
this.inTransaction = true;
|
|
@@ -2437,6 +2697,7 @@ var LinesDB = class LinesDB {
|
|
|
2437
2697
|
if (fieldChangesBefore) this.fieldChanges = fieldChangesBefore;
|
|
2438
2698
|
if (rawSqlTablesBefore) this.rawSqlTables = rawSqlTablesBefore;
|
|
2439
2699
|
if (linesWithUnknownFieldsBefore) this.linesWithUnknownFields = linesWithUnknownFieldsBefore;
|
|
2700
|
+
if (linePositionsBefore) this.linePositionsByRowid = linePositionsBefore;
|
|
2440
2701
|
const failure = await this.restoreAll(written, error);
|
|
2441
2702
|
if (this.inTransaction) try {
|
|
2442
2703
|
this.db.exec("ROLLBACK");
|
|
@@ -2721,8 +2982,9 @@ function splitLines(content) {
|
|
|
2721
2982
|
const carriage = raw.endsWith("\r") ? "\r" : "";
|
|
2722
2983
|
const text = carriage ? raw.slice(0, -1) : raw;
|
|
2723
2984
|
let row;
|
|
2724
|
-
|
|
2725
|
-
|
|
2985
|
+
const trimmed = text.trim();
|
|
2986
|
+
if (trimmed !== "") try {
|
|
2987
|
+
const parsed = JSON.parse(trimmed);
|
|
2726
2988
|
row = parsed !== null && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : void 0;
|
|
2727
2989
|
} catch {
|
|
2728
2990
|
row = void 0;
|
|
@@ -3008,6 +3270,6 @@ async function loadDatasetConfig(path = "lines-db.config.json", options = {}) {
|
|
|
3008
3270
|
schemaDir
|
|
3009
3271
|
};
|
|
3010
3272
|
}
|
|
3011
|
-
export { DirectoryScanner, ErrorFormatter, JsonlReader, JsonlWriter, LinesDB, RUNTIME, SCHEMA_EXTENSIONS, SchemaLoader, TypeGenerator, defineSchema, detectRuntime, ensureTableRowsValid, err, extractTableNameFromSchemaFile, fillFields, findSchemaFile, hasBackward, isSchemaFile, loadDatasetConfig, mergeFields, ok, rewriteExtensionForImport, unwrap };
|
|
3273
|
+
export { DirectoryScanner, ErrorFormatter, JsonlReader, JsonlWriter, LinesDB, RUNTIME, SCHEMA_EXTENSIONS, SchemaLoader, TypeGenerator, defineSchema, detectRuntime, ensureTableRowsValid, err, extractTableNameFromSchemaFile, fillFields, findSchemaFile, hasBackward, isSchemaFile, jsonlRecordLines, loadDatasetConfig, mergeFields, ok, rewriteExtensionForImport, unwrap };
|
|
3012
3274
|
|
|
3013
3275
|
//# sourceMappingURL=index.mjs.map
|