lines-db 0.18.0 → 0.19.0
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 +21 -0
- package/README.md +2 -0
- package/bin/cli.mjs +320 -139
- package/dist/index.d.mts +26 -29
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +185 -63
- package/dist/index.mjs.map +1 -1
- package/dist/internal.d.mts +1 -3
- package/dist/internal.d.mts.map +1 -1
- package/dist/internal.mjs +1 -1
- package/dist/{jsonl-reader-CoYEJ9pg.d.mts → jsonl-reader-aQqE1pe5.d.mts} +10 -7
- package/dist/jsonl-reader-aQqE1pe5.d.mts.map +1 -0
- package/dist/{replace-file-AWLIm7aN.mjs → replace-file-fStWc0ej.mjs} +4 -7
- package/dist/{replace-file-AWLIm7aN.mjs.map → replace-file-fStWc0ej.mjs.map} +1 -1
- package/package.json +9 -9
- package/dist/jsonl-reader-CoYEJ9pg.d.mts.map +0 -1
package/dist/index.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { a as ok, i as err, n as JsonlReader, o as toError, r as hashJsonlContent, s as unwrap, t as replaceFile } from "./replace-file-
|
|
1
|
+
import { a as ok, i as err, n as JsonlReader, o as toError, r as hashJsonlContent, s as unwrap, t as replaceFile } from "./replace-file-fStWc0ej.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";
|
|
@@ -6,17 +6,15 @@ import { basename, dirname, extname, isAbsolute, join, relative, resolve } from
|
|
|
6
6
|
import { pathToFileURL } from "node:url";
|
|
7
7
|
import { styleText } from "node:util";
|
|
8
8
|
import { z } from "zod";
|
|
9
|
-
|
|
9
|
+
// \0rolldown/runtime.js
|
|
10
10
|
var __require = /* #__PURE__ */ (() => createRequire(import.meta.url))();
|
|
11
|
-
|
|
12
|
-
//#region src/runtime.ts
|
|
11
|
+
// src/runtime.ts
|
|
13
12
|
function detectRuntime() {
|
|
14
13
|
if (typeof process !== "undefined" && process.versions && process.versions.node) return "node";
|
|
15
14
|
return "unknown";
|
|
16
15
|
}
|
|
17
16
|
const RUNTIME = detectRuntime();
|
|
18
|
-
|
|
19
|
-
//#region src/sqlite-adapter.ts
|
|
17
|
+
// src/sqlite-adapter.ts
|
|
20
18
|
/**
|
|
21
19
|
* SQLite adapter for Node.js
|
|
22
20
|
*/
|
|
@@ -57,8 +55,7 @@ function createNodeDatabase(path) {
|
|
|
57
55
|
}
|
|
58
56
|
};
|
|
59
57
|
}
|
|
60
|
-
|
|
61
|
-
//#region src/jsonl-writer.ts
|
|
58
|
+
// src/jsonl-writer.ts
|
|
62
59
|
var JsonlWriter = class {
|
|
63
60
|
/**
|
|
64
61
|
* Write data to JSONL file
|
|
@@ -87,8 +84,7 @@ var JsonlWriter = class {
|
|
|
87
84
|
}
|
|
88
85
|
}
|
|
89
86
|
};
|
|
90
|
-
|
|
91
|
-
//#region src/schema-extensions.ts
|
|
87
|
+
// src/schema-extensions.ts
|
|
92
88
|
/**
|
|
93
89
|
* Supported schema file extensions, in priority order.
|
|
94
90
|
* The first match wins when discovering schema files.
|
|
@@ -151,8 +147,7 @@ function rewriteExtensionForImport(filePath) {
|
|
|
151
147
|
for (const [tsExt, jsExt] of Object.entries(SCHEMA_TO_JS_IMPORT_MAP)) if (filePath.endsWith(tsExt)) return filePath.slice(0, -tsExt.length) + jsExt;
|
|
152
148
|
return filePath;
|
|
153
149
|
}
|
|
154
|
-
|
|
155
|
-
//#region src/schema-loader.ts
|
|
150
|
+
// src/schema-loader.ts
|
|
156
151
|
var SchemaLoader = class {
|
|
157
152
|
/**
|
|
158
153
|
* Check if a schema file exists for a table
|
|
@@ -189,8 +184,7 @@ var SchemaLoader = class {
|
|
|
189
184
|
return standardObj.version === 1 && typeof standardObj.vendor === "string" && typeof standardObj.validate === "function";
|
|
190
185
|
}
|
|
191
186
|
};
|
|
192
|
-
|
|
193
|
-
//#region src/directory-scanner.ts
|
|
187
|
+
// src/directory-scanner.ts
|
|
194
188
|
var DirectoryScanner = class {
|
|
195
189
|
/**
|
|
196
190
|
* Scan directories for JSONL files and create table configurations.
|
|
@@ -223,8 +217,7 @@ var DirectoryScanner = class {
|
|
|
223
217
|
return tables;
|
|
224
218
|
}
|
|
225
219
|
};
|
|
226
|
-
|
|
227
|
-
//#region src/schema.ts
|
|
220
|
+
// src/schema.ts
|
|
228
221
|
/**
|
|
229
222
|
* Define a bidirectional schema with optional backward transformation
|
|
230
223
|
*
|
|
@@ -280,8 +273,7 @@ function defineSchema(schema, ...args) {
|
|
|
280
273
|
function hasBackward(schema) {
|
|
281
274
|
return "backward" in schema && typeof schema.backward === "function";
|
|
282
275
|
}
|
|
283
|
-
|
|
284
|
-
//#region src/merge-fields.ts
|
|
276
|
+
// src/merge-fields.ts
|
|
285
277
|
/**
|
|
286
278
|
* Lay the named fields of a computed row over the line a JSONL file already holds.
|
|
287
279
|
*
|
|
@@ -334,8 +326,7 @@ function keepUnknownFields(line, row, columns) {
|
|
|
334
326
|
for (const key of Object.keys(row)) if (!Object.hasOwn(line, key)) entries.push([key, row[key]]);
|
|
335
327
|
return Object.fromEntries(entries);
|
|
336
328
|
}
|
|
337
|
-
|
|
338
|
-
//#region src/sql-statements.ts
|
|
329
|
+
// src/sql-statements.ts
|
|
339
330
|
const TRIGGER_DEFINITION = /^\s*CREATE\s+(?:TEMP(?:ORARY)?\s+)?TRIGGER\b/i;
|
|
340
331
|
const CLOSER = {
|
|
341
332
|
"'": "'",
|
|
@@ -441,8 +432,7 @@ function isReadOnlyStatement(statement) {
|
|
|
441
432
|
if (READ_PRAGMAS_WITH_ARGUMENT.has(name)) return true;
|
|
442
433
|
return READ_PRAGMAS_BARE.has(name) && argument === void 0;
|
|
443
434
|
}
|
|
444
|
-
|
|
445
|
-
//#region src/database.ts
|
|
435
|
+
// src/database.ts
|
|
446
436
|
function cloneFieldChanges(changes) {
|
|
447
437
|
return new Map(Array.from(changes, ([tableName, byRow]) => [tableName, new Map(Array.from(byRow, ([rowid, row]) => [rowid, {
|
|
448
438
|
set: new Set(row.set),
|
|
@@ -479,6 +469,7 @@ var LinesDB = class LinesDB {
|
|
|
479
469
|
* holds the fields a user wrote, so only what changed since it was written needs remembering
|
|
480
470
|
*/
|
|
481
471
|
fieldChanges = /* @__PURE__ */ new Map();
|
|
472
|
+
settleUndos;
|
|
482
473
|
/**
|
|
483
474
|
* The tables raw SQL may have changed since they were last written back: which fields it set is
|
|
484
475
|
* unknown, so their rows are written back whole
|
|
@@ -510,6 +501,10 @@ var LinesDB = class LinesDB {
|
|
|
510
501
|
observedHashes = /* @__PURE__ */ new Map();
|
|
511
502
|
/** The JSONL files the data directories held when the tables were scanned */
|
|
512
503
|
scannedJsonlFiles = [];
|
|
504
|
+
/** Tables left out because their files have no rows to infer the columns from */
|
|
505
|
+
emptyTables = /* @__PURE__ */ new Set();
|
|
506
|
+
/** Tables created from the columns `schemaOfEmptyTable` gave, which may lack a field the validator adds */
|
|
507
|
+
tablesFromGivenColumns = /* @__PURE__ */ new Set();
|
|
513
508
|
/** Each table's schema file and a hash of its content as the tables were loaded, or '' for none */
|
|
514
509
|
schemaFileStates = /* @__PURE__ */ new Map();
|
|
515
510
|
constructor(config, dbPath) {
|
|
@@ -551,12 +546,14 @@ var LinesDB = class LinesDB {
|
|
|
551
546
|
const tableName = options?.tableName;
|
|
552
547
|
const detailedValidate = options?.detailedValidate ?? false;
|
|
553
548
|
const transform = options?.transform;
|
|
549
|
+
this.emptyTables.clear();
|
|
554
550
|
this.tables = await DirectoryScanner.scanDirectory(this.config.dataDir);
|
|
555
551
|
this.scannedJsonlFiles = listJsonlFiles(this.tables);
|
|
556
552
|
this.observedHashes.clear();
|
|
557
553
|
this.schemaFileStates.clear();
|
|
558
554
|
for (const [name, config] of this.tables) this.schemaFileStates.set(name, await this.schemaFileState(name, config));
|
|
559
555
|
const tablesToLoad = tableName ? [tableName] : Array.from(this.tables.keys());
|
|
556
|
+
for (const name of tablesToLoad) this.tablesFromGivenColumns.delete(name);
|
|
560
557
|
for (const tableNameToLoad of tablesToLoad) if (!this.tables.has(tableNameToLoad)) {
|
|
561
558
|
const dataDirs = [this.config.dataDir].flat().map((dir) => `'${dir}'`);
|
|
562
559
|
throw new Error(`Table '${tableNameToLoad}' not found in directory ${dataDirs.join(", ")}`);
|
|
@@ -649,7 +646,10 @@ var LinesDB = class LinesDB {
|
|
|
649
646
|
else failedDependencies.add(referencedTable);
|
|
650
647
|
}
|
|
651
648
|
}
|
|
652
|
-
if (failedDependencies.size > 0) for (const dep of failedDependencies)
|
|
649
|
+
if (failedDependencies.size > 0) for (const dep of failedDependencies) {
|
|
650
|
+
const reason = this.emptyTables.has(dep) ? "has no rows to read its columns from" : "has validation errors";
|
|
651
|
+
warnings.push(`Skipping foreign key validation for table '${tableName}': referenced table '${dep}' ${reason}`);
|
|
652
|
+
}
|
|
653
653
|
}
|
|
654
654
|
const allSkippedDependencies = /* @__PURE__ */ new Set([...failedDependencies, ...circularDependencies]);
|
|
655
655
|
const { loaded, rowCount, errors: loadErrors } = await this.loadTable(tableName, tableConfig, detailedValidate, transform, allSkippedDependencies);
|
|
@@ -665,6 +665,7 @@ var LinesDB = class LinesDB {
|
|
|
665
665
|
});
|
|
666
666
|
}
|
|
667
667
|
} else {
|
|
668
|
+
if (rowCount === 0 && loadErrors.length === 0) this.emptyTables.add(tableName);
|
|
668
669
|
warnings.push(`Table '${tableName}' was not loaded (no data or skipped)`);
|
|
669
670
|
this.tables.delete(tableName);
|
|
670
671
|
}
|
|
@@ -779,12 +780,23 @@ var LinesDB = class LinesDB {
|
|
|
779
780
|
if (schemaCol && inferredCol.valueType && !schemaCol.valueType) schemaCol.valueType = inferredCol.valueType;
|
|
780
781
|
}
|
|
781
782
|
} else if (config.autoInferSchema !== false) {
|
|
782
|
-
if (validatedData.length === 0)
|
|
783
|
-
|
|
784
|
-
|
|
785
|
-
|
|
786
|
-
|
|
787
|
-
|
|
783
|
+
if (validatedData.length === 0) {
|
|
784
|
+
const declared = await this.config.schemaOfEmptyTable?.({
|
|
785
|
+
tableName,
|
|
786
|
+
schemaPath
|
|
787
|
+
});
|
|
788
|
+
if (!declared || declared.columns.length === 0) return {
|
|
789
|
+
loaded: false,
|
|
790
|
+
rowCount: 0,
|
|
791
|
+
errors: []
|
|
792
|
+
};
|
|
793
|
+
schema = {
|
|
794
|
+
...declared,
|
|
795
|
+
name: tableName,
|
|
796
|
+
columns: declared.columns.map((column) => ({ ...column }))
|
|
797
|
+
};
|
|
798
|
+
this.tablesFromGivenColumns.add(tableName);
|
|
799
|
+
} else schema = inferredSchema;
|
|
788
800
|
} else throw new Error(`No schema provided for table ${tableName} and autoInferSchema is disabled`);
|
|
789
801
|
const biSchema = validationSchema;
|
|
790
802
|
const primaryKey = biSchema?.primaryKey || schemaMetadata.primaryKey;
|
|
@@ -808,6 +820,7 @@ var LinesDB = class LinesDB {
|
|
|
808
820
|
if (col && !col.unique && !col.primaryKey) col.unique = true;
|
|
809
821
|
}
|
|
810
822
|
}
|
|
823
|
+
if (schema === inferredSchema) this.relaxColumnsTheSchemaLeavesOptional(tableName, schema, data[0]);
|
|
811
824
|
this.schemas.set(tableName, schema);
|
|
812
825
|
this.createTable(schema);
|
|
813
826
|
if (detailedValidate || this.config.writeDataSets) {
|
|
@@ -844,6 +857,55 @@ var LinesDB = class LinesDB {
|
|
|
844
857
|
};
|
|
845
858
|
}
|
|
846
859
|
/**
|
|
860
|
+
* A column no row holds a value in has no type to read a boolean or an object back with, and so reads
|
|
861
|
+
* back as 1 or as JSON text. The first value written settles it, and a string settles it as text so an
|
|
862
|
+
* object written later does not turn that text into JSON. Not asked of the schema: it names no type at
|
|
863
|
+
* run time. Returns what puts the columns back, which a write that did not go in, or a transaction that
|
|
864
|
+
* rolled back, must call: the value that settled it is not in the table
|
|
865
|
+
*/
|
|
866
|
+
settleColumnsNoRowHolds(schema, written) {
|
|
867
|
+
const before = [];
|
|
868
|
+
for (const column of schema?.columns ?? []) {
|
|
869
|
+
const value = written[column.name];
|
|
870
|
+
if (column.type !== "NULL" || value === null || value === void 0) continue;
|
|
871
|
+
before.push([
|
|
872
|
+
column,
|
|
873
|
+
column.type,
|
|
874
|
+
column.valueType
|
|
875
|
+
]);
|
|
876
|
+
if (typeof value === "boolean") {
|
|
877
|
+
column.type = "INTEGER";
|
|
878
|
+
column.valueType = "boolean";
|
|
879
|
+
} else if (typeof value === "string") column.type = "TEXT";
|
|
880
|
+
else if (typeof value === "number") column.type = Number.isInteger(value) ? "INTEGER" : "REAL";
|
|
881
|
+
else if (typeof value === "object" && !(value instanceof Uint8Array)) column.type = "JSON";
|
|
882
|
+
else before.pop();
|
|
883
|
+
}
|
|
884
|
+
const undo = () => {
|
|
885
|
+
for (const [column, type, valueType] of before) {
|
|
886
|
+
column.type = type;
|
|
887
|
+
column.valueType = valueType;
|
|
888
|
+
}
|
|
889
|
+
};
|
|
890
|
+
this.settleUndos?.push(undo);
|
|
891
|
+
return undo;
|
|
892
|
+
}
|
|
893
|
+
/**
|
|
894
|
+
* A column every row holds is inferred NOT NULL, which refuses a later row that leaves it out even
|
|
895
|
+
* where the schema takes that row. The sample row without the field says whether the schema does.
|
|
896
|
+
* A column the schema fills in stays NOT NULL: the row is stored as the schema leaves it
|
|
897
|
+
*/
|
|
898
|
+
relaxColumnsTheSchemaLeavesOptional(tableName, schema, sample) {
|
|
899
|
+
if (!sample || !this.validationSchemas.get(tableName)) return;
|
|
900
|
+
for (const column of schema.columns) {
|
|
901
|
+
if (!column.notNull || column.primaryKey || !(column.name in sample)) continue;
|
|
902
|
+
const { [column.name]: _left, ...without } = sample;
|
|
903
|
+
try {
|
|
904
|
+
if ((this.validateAndTransform(tableName, without)[column.name] ?? null) === null) column.notNull = false;
|
|
905
|
+
} catch {}
|
|
906
|
+
}
|
|
907
|
+
}
|
|
908
|
+
/**
|
|
847
909
|
* Create table in SQLite with constraints and indexes
|
|
848
910
|
*/
|
|
849
911
|
createTable(schema) {
|
|
@@ -909,6 +971,7 @@ var LinesDB = class LinesDB {
|
|
|
909
971
|
if (data.length === 0) return;
|
|
910
972
|
const columnNames = schema.columns.map((col) => col.name);
|
|
911
973
|
const quotedColumns = columnNames.map((name) => this.quoteIdentifier(name));
|
|
974
|
+
const columnsByName = new Map(schema.columns.map((column) => [column.name, column]));
|
|
912
975
|
const columnCount = columnNames.length;
|
|
913
976
|
const maxBatchSize = Math.floor(900 / columnCount);
|
|
914
977
|
const batchSize = Math.max(1, Math.min(maxBatchSize, 100));
|
|
@@ -918,7 +981,7 @@ var LinesDB = class LinesDB {
|
|
|
918
981
|
const valuesPlaceholders = batch.map(() => `(${rowPlaceholders})`).join(", ");
|
|
919
982
|
const sql = `INSERT INTO ${this.quoteTableName(tableName)} (${quotedColumns.join(", ")}) VALUES ${valuesPlaceholders}`;
|
|
920
983
|
const values = [];
|
|
921
|
-
for (const row of batch) for (const col of columnNames) values.push(this.normalizeValue(row[col]));
|
|
984
|
+
for (const row of batch) for (const col of columnNames) values.push(this.normalizeValue(row[col], columnsByName.get(col)));
|
|
922
985
|
this.db.prepare(sql).run(...values);
|
|
923
986
|
}
|
|
924
987
|
}
|
|
@@ -932,13 +995,14 @@ var LinesDB = class LinesDB {
|
|
|
932
995
|
const quotedColumns = columnNames.map((name) => this.quoteIdentifier(name));
|
|
933
996
|
const placeholders = columnNames.map(() => "?").join(", ");
|
|
934
997
|
const sql = `INSERT INTO ${this.quoteTableName(tableName)} (${quotedColumns.join(", ")}) VALUES (${placeholders})`;
|
|
998
|
+
const columnsByName = new Map(schema.columns.map((column) => [column.name, column]));
|
|
935
999
|
const stmt = this.db.prepare(sql);
|
|
936
1000
|
const rowOrigins = /* @__PURE__ */ new Map();
|
|
937
1001
|
this.rowOriginsByRowid.set(tableName, rowOrigins);
|
|
938
1002
|
for (let rowIndex = 0; rowIndex < data.length; rowIndex++) {
|
|
939
1003
|
const row = data[rowIndex];
|
|
940
1004
|
try {
|
|
941
|
-
const values = columnNames.map((col) => this.normalizeValue(row[col]));
|
|
1005
|
+
const values = columnNames.map((col) => this.normalizeValue(row[col], columnsByName.get(col)));
|
|
942
1006
|
const { lastInsertRowid } = stmt.run(...values);
|
|
943
1007
|
rowOrigins.set(String(lastInsertRowid), origins[rowIndex]);
|
|
944
1008
|
} catch (error) {
|
|
@@ -957,7 +1021,7 @@ var LinesDB = class LinesDB {
|
|
|
957
1021
|
const fkValue = row[fk.column];
|
|
958
1022
|
if (fkValue === null || fkValue === void 0) continue;
|
|
959
1023
|
try {
|
|
960
|
-
const result = this.queryInternal(`SELECT COUNT(*) as count FROM ${this.quoteIdentifier(fk.references.table)} WHERE ${this.quoteIdentifier(fk.references.column)} = ?`, [this.normalizeValue(fkValue)]);
|
|
1024
|
+
const result = this.queryInternal(`SELECT COUNT(*) as count FROM ${this.quoteIdentifier(fk.references.table)} WHERE ${this.quoteIdentifier(fk.references.column)} = ?`, [this.normalizeValue(fkValue, this.columnOf(fk.references.table, fk.references.column))]);
|
|
961
1025
|
if (result.length > 0 && result[0].count === 0) return {
|
|
962
1026
|
file,
|
|
963
1027
|
tableName,
|
|
@@ -1105,7 +1169,7 @@ var LinesDB = class LinesDB {
|
|
|
1105
1169
|
findInternal(tableName, where) {
|
|
1106
1170
|
if (where === void 0) return this.queryInternal(`SELECT * FROM ${this.quoteTableName(tableName)}`).map((row) => this.deserializeRow(tableName, row));
|
|
1107
1171
|
if (Array.isArray(where) && where.length === 0) return [];
|
|
1108
|
-
const { sql, values, functionFilters, hasOrWithFunctionFilters } = this.buildWhereClause(where);
|
|
1172
|
+
const { sql, values, functionFilters, hasOrWithFunctionFilters } = this.buildWhereClause(where, tableName);
|
|
1109
1173
|
let rows;
|
|
1110
1174
|
if (hasOrWithFunctionFilters) {
|
|
1111
1175
|
rows = this.queryInternal(`SELECT * FROM ${this.quoteTableName(tableName)}`).map((row) => this.deserializeRow(tableName, row));
|
|
@@ -1126,7 +1190,7 @@ var LinesDB = class LinesDB {
|
|
|
1126
1190
|
}
|
|
1127
1191
|
}
|
|
1128
1192
|
findOneInternal(tableName, where) {
|
|
1129
|
-
const { sql, values, functionFilters } = this.buildWhereClause(where);
|
|
1193
|
+
const { sql, values, functionFilters } = this.buildWhereClause(where, tableName);
|
|
1130
1194
|
let rows;
|
|
1131
1195
|
if (sql) rows = this.queryInternal(`SELECT * FROM ${this.quoteTableName(tableName)} WHERE ${sql}`, values).map((row) => this.deserializeRow(tableName, row));
|
|
1132
1196
|
else rows = this.queryInternal(`SELECT * FROM ${this.quoteTableName(tableName)}`).map((row) => this.deserializeRow(tableName, row));
|
|
@@ -1223,13 +1287,22 @@ var LinesDB = class LinesDB {
|
|
|
1223
1287
|
destination = join([this.config.dataDir].flat().find((dir) => resolve(dir) === resolve(dataDir)), `${tableName}.jsonl`);
|
|
1224
1288
|
}
|
|
1225
1289
|
const row = this.validateAndTransform(tableName, data);
|
|
1226
|
-
|
|
1290
|
+
const schema = this.schemas.get(tableName);
|
|
1291
|
+
if (!schema) throw new Error(`Table ${tableName} does not exist`);
|
|
1292
|
+
this.addMissingColumns(tableName, schema, row);
|
|
1227
1293
|
const columnNames = Object.keys(row);
|
|
1228
1294
|
const quotedColumns = columnNames.map((col) => this.quoteIdentifier(col));
|
|
1229
1295
|
const placeholders = columnNames.map(() => "?").join(", ");
|
|
1230
1296
|
const sql = `INSERT INTO ${this.quoteTableName(tableName)} (${quotedColumns.join(", ")}) VALUES (${placeholders})`;
|
|
1231
|
-
const values =
|
|
1232
|
-
const
|
|
1297
|
+
const values = columnNames.map((col) => this.normalizeValue(row[col], this.columnOf(tableName, col)));
|
|
1298
|
+
const undoSettle = this.settleColumnsNoRowHolds(schema, row);
|
|
1299
|
+
let result;
|
|
1300
|
+
try {
|
|
1301
|
+
result = this.executeInternal(sql, values);
|
|
1302
|
+
} catch (error) {
|
|
1303
|
+
undoSettle();
|
|
1304
|
+
throw error;
|
|
1305
|
+
}
|
|
1233
1306
|
if (destination) {
|
|
1234
1307
|
const origins = this.rowOriginsByRowid.get(tableName) ?? /* @__PURE__ */ new Map();
|
|
1235
1308
|
origins.set(String(result.lastInsertRowid), {
|
|
@@ -1246,6 +1319,27 @@ var LinesDB = class LinesDB {
|
|
|
1246
1319
|
return result;
|
|
1247
1320
|
}
|
|
1248
1321
|
/**
|
|
1322
|
+
* A table made from the columns given has only those, and the validator may add a field they lack: the
|
|
1323
|
+
* columns of a table made from rows are those of the validated rows, which have it
|
|
1324
|
+
*/
|
|
1325
|
+
addMissingColumns(tableName, schema, row) {
|
|
1326
|
+
if (!this.tablesFromGivenColumns.has(tableName)) return;
|
|
1327
|
+
const known = new Set(schema.columns.map((column) => column.name));
|
|
1328
|
+
const missing = Object.keys(row).filter((key) => !known.has(key));
|
|
1329
|
+
if (missing.length === 0) return;
|
|
1330
|
+
for (const column of unwrap(JsonlReader.inferSchema(tableName, [row])).columns) {
|
|
1331
|
+
if (!missing.includes(column.name)) continue;
|
|
1332
|
+
const sqlType = column.type === "JSON" ? "TEXT" : column.type;
|
|
1333
|
+
this.db.exec(`ALTER TABLE ${this.quoteTableName(tableName)} ADD COLUMN ${this.quoteIdentifier(column.name)} ${sqlType}`);
|
|
1334
|
+
schema.columns.push({
|
|
1335
|
+
name: column.name,
|
|
1336
|
+
type: column.type,
|
|
1337
|
+
notNull: false,
|
|
1338
|
+
valueType: column.valueType
|
|
1339
|
+
});
|
|
1340
|
+
}
|
|
1341
|
+
}
|
|
1342
|
+
/**
|
|
1249
1343
|
* Batch insert rows with validation per record.
|
|
1250
1344
|
*/
|
|
1251
1345
|
batchInsert(tableName, records) {
|
|
@@ -1258,7 +1352,8 @@ var LinesDB = class LinesDB {
|
|
|
1258
1352
|
batchInsertInternal(tableName, records) {
|
|
1259
1353
|
this.assertMutable(tableName);
|
|
1260
1354
|
if (this.hasSeveralDataDirs()) throw new Error("Use insert with a dataDir for data sets");
|
|
1261
|
-
|
|
1355
|
+
const schema = this.schemas.get(tableName);
|
|
1356
|
+
if (!schema) throw new Error(`Table ${tableName} does not exist`);
|
|
1262
1357
|
if (records.length === 0) return {
|
|
1263
1358
|
changes: 0,
|
|
1264
1359
|
lastInsertRowid: 0
|
|
@@ -1268,12 +1363,20 @@ var LinesDB = class LinesDB {
|
|
|
1268
1363
|
try {
|
|
1269
1364
|
for (const record of records) {
|
|
1270
1365
|
const row = this.validateAndTransform(tableName, record);
|
|
1366
|
+
this.addMissingColumns(tableName, schema, row);
|
|
1271
1367
|
const columnNames = Object.keys(row);
|
|
1272
1368
|
const quotedColumns = columnNames.map((col) => this.quoteIdentifier(col));
|
|
1273
1369
|
const placeholders = columnNames.map(() => "?").join(", ");
|
|
1274
1370
|
const sql = `INSERT INTO ${this.quoteTableName(tableName)} (${quotedColumns.join(", ")}) VALUES (${placeholders})`;
|
|
1275
|
-
const values = columnNames.map((col) => this.normalizeValue(row[col]));
|
|
1276
|
-
const
|
|
1371
|
+
const values = columnNames.map((col) => this.normalizeValue(row[col], this.columnOf(tableName, col)));
|
|
1372
|
+
const undoSettle = this.settleColumnsNoRowHolds(this.schemas.get(tableName), row);
|
|
1373
|
+
let result;
|
|
1374
|
+
try {
|
|
1375
|
+
result = this.executeInternal(sql, values);
|
|
1376
|
+
} catch (error) {
|
|
1377
|
+
undoSettle();
|
|
1378
|
+
throw error;
|
|
1379
|
+
}
|
|
1277
1380
|
this.noteFieldChanges(tableName, result.lastInsertRowid, {
|
|
1278
1381
|
set: givenFields(record),
|
|
1279
1382
|
inserted: true
|
|
@@ -1318,7 +1421,7 @@ var LinesDB = class LinesDB {
|
|
|
1318
1421
|
this.validateData(tableName, mergedData);
|
|
1319
1422
|
}
|
|
1320
1423
|
}
|
|
1321
|
-
const { sql: whereSql, values: whereValues, functionFilters } = this.buildWhereClause(where);
|
|
1424
|
+
const { sql: whereSql, values: whereValues, functionFilters } = this.buildWhereClause(where, tableName);
|
|
1322
1425
|
if (functionFilters.length > 0) throw new Error("Function filters are not supported in update operations");
|
|
1323
1426
|
const targets = this.queryInternal(`SELECT rowid AS "${ROWID_ALIAS}", * FROM ${this.quoteTableName(tableName)} WHERE ${whereSql}`, whereValues);
|
|
1324
1427
|
const resetFields = options?.resetToDefault ?? [];
|
|
@@ -1330,12 +1433,19 @@ var LinesDB = class LinesDB {
|
|
|
1330
1433
|
if (Object.keys(data).length > 0) {
|
|
1331
1434
|
const setClauses = Object.keys(data).map((key) => `${this.quoteIdentifier(key)} = ?`).join(", ");
|
|
1332
1435
|
const sql = `UPDATE ${this.quoteTableName(tableName)} SET ${setClauses} WHERE ${whereSql}`;
|
|
1333
|
-
const values = [...Object.
|
|
1334
|
-
|
|
1436
|
+
const values = [...Object.entries(data).map(([key, v]) => this.normalizeValue(v, this.columnOf(tableName, key))), ...whereValues];
|
|
1437
|
+
const undoSettle = this.settleColumnsNoRowHolds(this.schemas.get(tableName), data);
|
|
1438
|
+
try {
|
|
1439
|
+
result = this.executeInternal(sql, values);
|
|
1440
|
+
} catch (error) {
|
|
1441
|
+
undoSettle();
|
|
1442
|
+
throw error;
|
|
1443
|
+
}
|
|
1444
|
+
if (Number(result.changes) === 0) undoSettle();
|
|
1335
1445
|
}
|
|
1336
1446
|
const pkName = this.schemas.get(tableName)?.columns.find((col) => col.primaryKey)?.name;
|
|
1337
1447
|
if (pkName && Object.hasOwn(data, pkName)) {
|
|
1338
|
-
const moved = this.queryInternal(`SELECT rowid AS "${ROWID_ALIAS}" FROM ${this.quoteTableName(tableName)} WHERE ${this.quoteIdentifier(pkName)} = ?`, [this.normalizeValue(data[pkName])]);
|
|
1448
|
+
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))]);
|
|
1339
1449
|
if (targets.length === 1 && moved.length === 1) {
|
|
1340
1450
|
const from = String(targets[0][ROWID_ALIAS]);
|
|
1341
1451
|
const to = moved[0][ROWID_ALIAS];
|
|
@@ -1349,7 +1459,7 @@ var LinesDB = class LinesDB {
|
|
|
1349
1459
|
}
|
|
1350
1460
|
}
|
|
1351
1461
|
for (const target of targets) {
|
|
1352
|
-
const set = Object.keys(data).filter((key) => !sameStoredValue(target[key], this.normalizeValue(data[key])));
|
|
1462
|
+
const set = Object.keys(data).filter((key) => !sameStoredValue(target[key], this.normalizeValue(data[key], this.columnOf(tableName, key))));
|
|
1353
1463
|
this.noteFieldChanges(tableName, target[ROWID_ALIAS], { set });
|
|
1354
1464
|
}
|
|
1355
1465
|
if (resets.length > 0) result = this.applyResets(tableName, resets, resetFields);
|
|
@@ -1453,7 +1563,7 @@ var LinesDB = class LinesDB {
|
|
|
1453
1563
|
deleteInternal(tableName, where) {
|
|
1454
1564
|
this.assertMutable(tableName);
|
|
1455
1565
|
if (!this.schemas.get(tableName)) throw new Error(`Table ${tableName} does not exist`);
|
|
1456
|
-
const { sql: whereSql, values, functionFilters } = this.buildWhereClause(where);
|
|
1566
|
+
const { sql: whereSql, values, functionFilters } = this.buildWhereClause(where, tableName);
|
|
1457
1567
|
if (functionFilters.length > 0) throw new Error("Function filters are not supported in delete operations");
|
|
1458
1568
|
const deleted = this.rowidsWhere(tableName, whereSql, values);
|
|
1459
1569
|
const sql = `DELETE FROM ${this.quoteTableName(tableName)} WHERE ${whereSql}`;
|
|
@@ -1490,7 +1600,7 @@ var LinesDB = class LinesDB {
|
|
|
1490
1600
|
});
|
|
1491
1601
|
const placeholders = pkValues.map(() => "?").join(", ");
|
|
1492
1602
|
const sql = `DELETE FROM ${this.quoteTableName(tableName)} WHERE ${this.quoteIdentifier(pkName)} IN (${placeholders})`;
|
|
1493
|
-
const values = pkValues.map((value) => this.normalizeValue(value));
|
|
1603
|
+
const values = pkValues.map((value) => this.normalizeValue(value, this.columnOf(tableName, pkName)));
|
|
1494
1604
|
const deleted = this.rowidsWhere(tableName, `${this.quoteIdentifier(pkName)} IN (${placeholders})`, values);
|
|
1495
1605
|
const result = this.executeInternal(sql, values);
|
|
1496
1606
|
this.forgetFieldChanges(tableName, deleted);
|
|
@@ -1503,17 +1613,24 @@ var LinesDB = class LinesDB {
|
|
|
1503
1613
|
/**
|
|
1504
1614
|
* Normalize value for SQLite
|
|
1505
1615
|
*/
|
|
1506
|
-
normalizeValue(value) {
|
|
1616
|
+
normalizeValue(value, column) {
|
|
1507
1617
|
if (value === null || value === void 0) return null;
|
|
1618
|
+
if (column?.type === "JSON") {
|
|
1619
|
+
if (value instanceof Uint8Array) return value;
|
|
1620
|
+
return typeof value === "bigint" ? value.toString() : JSON.stringify(value);
|
|
1621
|
+
}
|
|
1508
1622
|
if (typeof value === "boolean") return value ? 1 : 0;
|
|
1509
1623
|
if (typeof value === "string" || typeof value === "number" || typeof value === "bigint") return value;
|
|
1510
1624
|
if (value instanceof Uint8Array) return value;
|
|
1511
1625
|
return JSON.stringify(value);
|
|
1512
1626
|
}
|
|
1627
|
+
columnOf(tableName, columnName) {
|
|
1628
|
+
return this.schemas.get(tableName)?.columns.find((column) => column.name === columnName);
|
|
1629
|
+
}
|
|
1513
1630
|
/**
|
|
1514
1631
|
* Build WHERE clause from condition (supports OR/AND with arrays and functions)
|
|
1515
1632
|
*/
|
|
1516
|
-
buildWhereClause(condition) {
|
|
1633
|
+
buildWhereClause(condition, tableName) {
|
|
1517
1634
|
const values = [];
|
|
1518
1635
|
const functionFilters = [];
|
|
1519
1636
|
let hasOrWithFunctionFilters = false;
|
|
@@ -1532,7 +1649,7 @@ var LinesDB = class LinesDB {
|
|
|
1532
1649
|
hasFunctionFilter = true;
|
|
1533
1650
|
} else {
|
|
1534
1651
|
conditions.push(`${this.quoteIdentifier(key)} = ?`);
|
|
1535
|
-
values.push(this.normalizeValue(value));
|
|
1652
|
+
values.push(this.normalizeValue(value, this.columnOf(tableName, key)));
|
|
1536
1653
|
}
|
|
1537
1654
|
if (isInOr && hasFunctionFilter) hasOrWithFunctionFilters = true;
|
|
1538
1655
|
return conditions.join(" AND ");
|
|
@@ -1797,8 +1914,9 @@ var LinesDB = class LinesDB {
|
|
|
1797
1914
|
for (const key of rowChanges?.reset ?? []) keep.delete(key);
|
|
1798
1915
|
for (const key of namedFields) keep.add(key);
|
|
1799
1916
|
if (pkName) keep.add(pkName);
|
|
1917
|
+
const untouched = line !== void 0 && !rowChanges?.inserted && !rowChanges?.set.size && !rowChanges?.reset.size;
|
|
1800
1918
|
return {
|
|
1801
|
-
written: Object.fromEntries(Object.entries(lineRow).filter(([key]) => keep.has(key))),
|
|
1919
|
+
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])),
|
|
1802
1920
|
narrowed: true
|
|
1803
1921
|
};
|
|
1804
1922
|
});
|
|
@@ -1882,7 +2000,7 @@ var LinesDB = class LinesDB {
|
|
|
1882
2000
|
const validated = this.validateAndTransform(tableName, row);
|
|
1883
2001
|
return {
|
|
1884
2002
|
rowid,
|
|
1885
|
-
values: fields.map((field) => this.normalizeValue(validated[field]))
|
|
2003
|
+
values: fields.map((field) => this.normalizeValue(validated[field], this.columnOf(tableName, field)))
|
|
1886
2004
|
};
|
|
1887
2005
|
});
|
|
1888
2006
|
}
|
|
@@ -2235,15 +2353,18 @@ var LinesDB = class LinesDB {
|
|
|
2235
2353
|
let rawSqlTablesBefore;
|
|
2236
2354
|
let linesWithUnknownFieldsBefore;
|
|
2237
2355
|
let originsBefore;
|
|
2356
|
+
let columnsBefore;
|
|
2238
2357
|
const scannedBefore = [...this.scannedJsonlFiles];
|
|
2239
2358
|
let written = [];
|
|
2240
2359
|
try {
|
|
2241
2360
|
await this.waitForPendingSyncs();
|
|
2242
2361
|
originsBefore = new Map([...this.rowOriginsByRowid].map(([name, origins]) => [name, new Map(origins)]));
|
|
2362
|
+
columnsBefore = new Map([...this.tablesFromGivenColumns].map((name) => [name, [...this.schemas.get(name)?.columns ?? []]]));
|
|
2243
2363
|
fieldChangesBefore = cloneFieldChanges(this.fieldChanges);
|
|
2244
2364
|
rawSqlTablesBefore = new Set(this.rawSqlTables);
|
|
2245
2365
|
linesWithUnknownFieldsBefore = new Map(Array.from(this.linesWithUnknownFields, ([tableName, lines]) => [tableName, new Map(lines)]));
|
|
2246
2366
|
this.db.exec("BEGIN TRANSACTION");
|
|
2367
|
+
this.settleUndos = [];
|
|
2247
2368
|
this.inTransaction = true;
|
|
2248
2369
|
this.transactionToken = token;
|
|
2249
2370
|
this.transactionStarting = false;
|
|
@@ -2256,6 +2377,7 @@ var LinesDB = class LinesDB {
|
|
|
2256
2377
|
}
|
|
2257
2378
|
if (!this.isReadOnlyDataSet()) written = await this.writeBackTogether(this.tablesChangedInTransaction());
|
|
2258
2379
|
this.db.exec("COMMIT");
|
|
2380
|
+
this.settleUndos = void 0;
|
|
2259
2381
|
this.inTransaction = false;
|
|
2260
2382
|
this.transactionChanges = void 0;
|
|
2261
2383
|
return ok(result);
|
|
@@ -2263,6 +2385,10 @@ var LinesDB = class LinesDB {
|
|
|
2263
2385
|
this.transactionStarting = false;
|
|
2264
2386
|
this.transactionChanges = void 0;
|
|
2265
2387
|
if (originsBefore) this.rowOriginsByRowid = originsBefore;
|
|
2388
|
+
for (const [name, columns] of columnsBefore ?? []) {
|
|
2389
|
+
const schema = this.schemas.get(name);
|
|
2390
|
+
if (schema) schema.columns = columns;
|
|
2391
|
+
}
|
|
2266
2392
|
this.scannedJsonlFiles = scannedBefore;
|
|
2267
2393
|
if (fieldChangesBefore) this.fieldChanges = fieldChangesBefore;
|
|
2268
2394
|
if (rawSqlTablesBefore) this.rawSqlTables = rawSqlTablesBefore;
|
|
@@ -2271,6 +2397,8 @@ var LinesDB = class LinesDB {
|
|
|
2271
2397
|
if (this.inTransaction) try {
|
|
2272
2398
|
this.db.exec("ROLLBACK");
|
|
2273
2399
|
} catch (_rollbackError) {}
|
|
2400
|
+
for (const undo of [...this.settleUndos ?? []].reverse()) undo();
|
|
2401
|
+
this.settleUndos = void 0;
|
|
2274
2402
|
this.inTransaction = false;
|
|
2275
2403
|
return err(toError(failure));
|
|
2276
2404
|
} finally {
|
|
@@ -2357,8 +2485,7 @@ var LinesDB = class LinesDB {
|
|
|
2357
2485
|
function listJsonlFiles(tables) {
|
|
2358
2486
|
return Array.from(tables.values()).flatMap((config) => config.jsonlPaths ?? [config.jsonlPath]).sort();
|
|
2359
2487
|
}
|
|
2360
|
-
|
|
2361
|
-
//#region src/fill.ts
|
|
2488
|
+
// src/fill.ts
|
|
2362
2489
|
/**
|
|
2363
2490
|
* Fill the named fields into the rows of the JSONL files that have no value for them, with the values
|
|
2364
2491
|
* each table computes for a row. A value already in the file is never replaced, and a line that gains
|
|
@@ -2571,8 +2698,7 @@ function serializeRow(row, fieldOrder) {
|
|
|
2571
2698
|
for (const [key, value] of ordered) setField(out, key, value);
|
|
2572
2699
|
return JSON.stringify(out);
|
|
2573
2700
|
}
|
|
2574
|
-
|
|
2575
|
-
//#region src/type-generator.ts
|
|
2701
|
+
// src/type-generator.ts
|
|
2576
2702
|
var TypeGenerator = class {
|
|
2577
2703
|
dataDir;
|
|
2578
2704
|
projectRoot;
|
|
@@ -2678,8 +2804,7 @@ function toCamelCase(value) {
|
|
|
2678
2804
|
function sanitizeIdentifier(value) {
|
|
2679
2805
|
return value.replace(/[^A-Za-z0-9_$]/g, "");
|
|
2680
2806
|
}
|
|
2681
|
-
|
|
2682
|
-
//#region src/jsonl-migration.ts
|
|
2807
|
+
// src/jsonl-migration.ts
|
|
2683
2808
|
/**
|
|
2684
2809
|
* Validate a table by temporarily supplying in-memory rows while reusing the existing LinesDB validation pipeline.
|
|
2685
2810
|
* If validation fails, throws an error with validation details.
|
|
@@ -2704,8 +2829,7 @@ async function ensureTableRowsValid(options) {
|
|
|
2704
2829
|
}
|
|
2705
2830
|
});
|
|
2706
2831
|
}
|
|
2707
|
-
|
|
2708
|
-
//#region src/error-formatter.ts
|
|
2832
|
+
// src/error-formatter.ts
|
|
2709
2833
|
var ErrorFormatter = class {
|
|
2710
2834
|
verbose;
|
|
2711
2835
|
constructor(options = {}) {
|
|
@@ -2807,8 +2931,7 @@ var ErrorFormatter = class {
|
|
|
2807
2931
|
return styleText("red", "\n✗ Migration failed and was rolled back");
|
|
2808
2932
|
}
|
|
2809
2933
|
};
|
|
2810
|
-
|
|
2811
|
-
//#region src/dataset-config.ts
|
|
2934
|
+
// src/dataset-config.ts
|
|
2812
2935
|
const directories = z.array(z.string().min(1)).min(1);
|
|
2813
2936
|
const datasetConfigSchema = z.strictObject({
|
|
2814
2937
|
schemaDir: z.string().min(1),
|
|
@@ -2840,7 +2963,6 @@ async function loadDatasetConfig(path = "lines-db.config.json", options = {}) {
|
|
|
2840
2963
|
schemaDir
|
|
2841
2964
|
};
|
|
2842
2965
|
}
|
|
2843
|
-
//#endregion
|
|
2844
2966
|
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 };
|
|
2845
2967
|
|
|
2846
2968
|
//# sourceMappingURL=index.mjs.map
|