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/bin/cli.mjs CHANGED
@@ -1,19 +1,19 @@
1
1
  #!/usr/bin/env node
2
2
  import { createRequire, register } from "node:module";
3
+ import * as l from "loculus";
4
+ import { _rawValidate, _resolveIssue, _typeIssue, config } from "loculus";
3
5
  import { access, chmod, link, mkdir, readFile, readdir, realpath, rename, rm, stat, writeFile } from "node:fs/promises";
4
6
  import { basename, dirname, extname, isAbsolute, join, normalize, relative, resolve } from "node:path";
5
7
  import { createHash, randomBytes } from "node:crypto";
6
8
  import { pathToFileURL } from "node:url";
7
9
  import { styleText } from "node:util";
8
- import * as l from "loculus";
9
10
  import { arg, defineCommand, runMain } from "@politty/loculus";
10
11
  import { runInNewContext } from "node:vm";
11
12
  import { spawn } from "node:child_process";
12
13
  import { z } from "zod";
13
- //#region \0rolldown/runtime.js
14
+ // \0rolldown/runtime.js
14
15
  var __require = /* #__PURE__ */ (() => createRequire(import.meta.url))();
15
- //#endregion
16
- //#region src/schema-extensions.ts
16
+ // src/schema-extensions.ts
17
17
  /**
18
18
  * Supported schema file extensions, in priority order.
19
19
  * The first match wins when discovering schema files.
@@ -62,8 +62,7 @@ function rewriteExtensionForImport(filePath) {
62
62
  for (const [tsExt, jsExt] of Object.entries(SCHEMA_TO_JS_IMPORT_MAP)) if (filePath.endsWith(tsExt)) return filePath.slice(0, -tsExt.length) + jsExt;
63
63
  return filePath;
64
64
  }
65
- //#endregion
66
- //#region src/type-generator.ts
65
+ // src/type-generator.ts
67
66
  var TypeGenerator = class {
68
67
  dataDir;
69
68
  projectRoot;
@@ -169,15 +168,13 @@ function toCamelCase(value) {
169
168
  function sanitizeIdentifier(value) {
170
169
  return value.replace(/[^A-Za-z0-9_$]/g, "");
171
170
  }
172
- //#endregion
173
- //#region src/runtime.ts
171
+ // src/runtime.ts
174
172
  function detectRuntime() {
175
173
  if (typeof process !== "undefined" && process.versions && process.versions.node) return "node";
176
174
  return "unknown";
177
175
  }
178
176
  const RUNTIME = detectRuntime();
179
- //#endregion
180
- //#region src/sqlite-adapter.ts
177
+ // src/sqlite-adapter.ts
181
178
  /**
182
179
  * SQLite adapter for Node.js
183
180
  */
@@ -218,8 +215,7 @@ function createNodeDatabase(path) {
218
215
  }
219
216
  };
220
217
  }
221
- //#endregion
222
- //#region src/result.ts
218
+ // src/result.ts
223
219
  function ok(value) {
224
220
  return {
225
221
  ok: true,
@@ -241,8 +237,7 @@ function unwrap(result) {
241
237
  if (result.ok) return result.value;
242
238
  throw result.error;
243
239
  }
244
- //#endregion
245
- //#region src/jsonl-reader.ts
240
+ // src/jsonl-reader.ts
246
241
  /** Fingerprint of a JSONL file's content, to tell whether the file changed since it was read */
247
242
  function hashJsonlContent(content) {
248
243
  return createHash("sha256").update(content).digest("hex");
@@ -364,8 +359,7 @@ var JsonlReader = class {
364
359
  return "TEXT";
365
360
  }
366
361
  };
367
- //#endregion
368
- //#region src/jsonl-writer.ts
362
+ // src/jsonl-writer.ts
369
363
  var JsonlWriter = class {
370
364
  /**
371
365
  * Write data to JSONL file
@@ -394,8 +388,7 @@ var JsonlWriter = class {
394
388
  }
395
389
  }
396
390
  };
397
- //#endregion
398
- //#region src/replace-file.ts
391
+ // src/replace-file.ts
399
392
  async function replaceFile(file, write, expected) {
400
393
  const suffix = randomBytes(12).toString("hex");
401
394
  const temporary = `${file}.${suffix}.tmp`;
@@ -445,8 +438,7 @@ async function replaceFile(file, write, expected) {
445
438
  if (!moved) await rm(temporary, { force: true }).catch(() => {});
446
439
  }
447
440
  }
448
- //#endregion
449
- //#region src/schema-loader.ts
441
+ // src/schema-loader.ts
450
442
  var SchemaLoader = class {
451
443
  /**
452
444
  * Check if a schema file exists for a table
@@ -483,8 +475,7 @@ var SchemaLoader = class {
483
475
  return standardObj.version === 1 && typeof standardObj.vendor === "string" && typeof standardObj.validate === "function";
484
476
  }
485
477
  };
486
- //#endregion
487
- //#region src/directory-scanner.ts
478
+ // src/directory-scanner.ts
488
479
  var DirectoryScanner = class {
489
480
  /**
490
481
  * Scan directories for JSONL files and create table configurations.
@@ -517,16 +508,14 @@ var DirectoryScanner = class {
517
508
  return tables;
518
509
  }
519
510
  };
520
- //#endregion
521
- //#region src/schema.ts
511
+ // src/schema.ts
522
512
  /**
523
513
  * Check if a schema has backward transformation
524
514
  */
525
515
  function hasBackward(schema) {
526
516
  return "backward" in schema && typeof schema.backward === "function";
527
517
  }
528
- //#endregion
529
- //#region src/merge-fields.ts
518
+ // src/merge-fields.ts
530
519
  /**
531
520
  * Lay the named fields of a computed row over the line a JSONL file already holds.
532
521
  *
@@ -579,8 +568,7 @@ function keepUnknownFields(line, row, columns) {
579
568
  for (const key of Object.keys(row)) if (!Object.hasOwn(line, key)) entries.push([key, row[key]]);
580
569
  return Object.fromEntries(entries);
581
570
  }
582
- //#endregion
583
- //#region src/sql-statements.ts
571
+ // src/sql-statements.ts
584
572
  const TRIGGER_DEFINITION = /^\s*CREATE\s+(?:TEMP(?:ORARY)?\s+)?TRIGGER\b/i;
585
573
  const CLOSER = {
586
574
  "'": "'",
@@ -686,8 +674,7 @@ function isReadOnlyStatement(statement) {
686
674
  if (READ_PRAGMAS_WITH_ARGUMENT.has(name)) return true;
687
675
  return READ_PRAGMAS_BARE.has(name) && argument === void 0;
688
676
  }
689
- //#endregion
690
- //#region src/database.ts
677
+ // src/database.ts
691
678
  function cloneFieldChanges(changes) {
692
679
  return new Map(Array.from(changes, ([tableName, byRow]) => [tableName, new Map(Array.from(byRow, ([rowid, row]) => [rowid, {
693
680
  set: new Set(row.set),
@@ -724,6 +711,7 @@ var LinesDB = class LinesDB {
724
711
  * holds the fields a user wrote, so only what changed since it was written needs remembering
725
712
  */
726
713
  fieldChanges = /* @__PURE__ */ new Map();
714
+ settleUndos;
727
715
  /**
728
716
  * The tables raw SQL may have changed since they were last written back: which fields it set is
729
717
  * unknown, so their rows are written back whole
@@ -755,6 +743,10 @@ var LinesDB = class LinesDB {
755
743
  observedHashes = /* @__PURE__ */ new Map();
756
744
  /** The JSONL files the data directories held when the tables were scanned */
757
745
  scannedJsonlFiles = [];
746
+ /** Tables left out because their files have no rows to infer the columns from */
747
+ emptyTables = /* @__PURE__ */ new Set();
748
+ /** Tables created from the columns `schemaOfEmptyTable` gave, which may lack a field the validator adds */
749
+ tablesFromGivenColumns = /* @__PURE__ */ new Set();
758
750
  /** Each table's schema file and a hash of its content as the tables were loaded, or '' for none */
759
751
  schemaFileStates = /* @__PURE__ */ new Map();
760
752
  constructor(config, dbPath) {
@@ -796,12 +788,14 @@ var LinesDB = class LinesDB {
796
788
  const tableName = options?.tableName;
797
789
  const detailedValidate = options?.detailedValidate ?? false;
798
790
  const transform = options?.transform;
791
+ this.emptyTables.clear();
799
792
  this.tables = await DirectoryScanner.scanDirectory(this.config.dataDir);
800
793
  this.scannedJsonlFiles = listJsonlFiles(this.tables);
801
794
  this.observedHashes.clear();
802
795
  this.schemaFileStates.clear();
803
796
  for (const [name, config] of this.tables) this.schemaFileStates.set(name, await this.schemaFileState(name, config));
804
797
  const tablesToLoad = tableName ? [tableName] : Array.from(this.tables.keys());
798
+ for (const name of tablesToLoad) this.tablesFromGivenColumns.delete(name);
805
799
  for (const tableNameToLoad of tablesToLoad) if (!this.tables.has(tableNameToLoad)) {
806
800
  const dataDirs = [this.config.dataDir].flat().map((dir) => `'${dir}'`);
807
801
  throw new Error(`Table '${tableNameToLoad}' not found in directory ${dataDirs.join(", ")}`);
@@ -894,7 +888,10 @@ var LinesDB = class LinesDB {
894
888
  else failedDependencies.add(referencedTable);
895
889
  }
896
890
  }
897
- if (failedDependencies.size > 0) for (const dep of failedDependencies) warnings.push(`Skipping foreign key validation for table '${tableName}': referenced table '${dep}' has validation errors`);
891
+ if (failedDependencies.size > 0) for (const dep of failedDependencies) {
892
+ const reason = this.emptyTables.has(dep) ? "has no rows to read its columns from" : "has validation errors";
893
+ warnings.push(`Skipping foreign key validation for table '${tableName}': referenced table '${dep}' ${reason}`);
894
+ }
898
895
  }
899
896
  const allSkippedDependencies = /* @__PURE__ */ new Set([...failedDependencies, ...circularDependencies]);
900
897
  const { loaded, rowCount, errors: loadErrors } = await this.loadTable(tableName, tableConfig, detailedValidate, transform, allSkippedDependencies);
@@ -910,6 +907,7 @@ var LinesDB = class LinesDB {
910
907
  });
911
908
  }
912
909
  } else {
910
+ if (rowCount === 0 && loadErrors.length === 0) this.emptyTables.add(tableName);
913
911
  warnings.push(`Table '${tableName}' was not loaded (no data or skipped)`);
914
912
  this.tables.delete(tableName);
915
913
  }
@@ -1024,12 +1022,23 @@ var LinesDB = class LinesDB {
1024
1022
  if (schemaCol && inferredCol.valueType && !schemaCol.valueType) schemaCol.valueType = inferredCol.valueType;
1025
1023
  }
1026
1024
  } else if (config.autoInferSchema !== false) {
1027
- if (validatedData.length === 0) return {
1028
- loaded: false,
1029
- rowCount: 0,
1030
- errors: []
1031
- };
1032
- schema = inferredSchema;
1025
+ if (validatedData.length === 0) {
1026
+ const declared = await this.config.schemaOfEmptyTable?.({
1027
+ tableName,
1028
+ schemaPath
1029
+ });
1030
+ if (!declared || declared.columns.length === 0) return {
1031
+ loaded: false,
1032
+ rowCount: 0,
1033
+ errors: []
1034
+ };
1035
+ schema = {
1036
+ ...declared,
1037
+ name: tableName,
1038
+ columns: declared.columns.map((column) => ({ ...column }))
1039
+ };
1040
+ this.tablesFromGivenColumns.add(tableName);
1041
+ } else schema = inferredSchema;
1033
1042
  } else throw new Error(`No schema provided for table ${tableName} and autoInferSchema is disabled`);
1034
1043
  const biSchema = validationSchema;
1035
1044
  const primaryKey = biSchema?.primaryKey || schemaMetadata.primaryKey;
@@ -1053,6 +1062,7 @@ var LinesDB = class LinesDB {
1053
1062
  if (col && !col.unique && !col.primaryKey) col.unique = true;
1054
1063
  }
1055
1064
  }
1065
+ if (schema === inferredSchema) this.relaxColumnsTheSchemaLeavesOptional(tableName, schema, data[0]);
1056
1066
  this.schemas.set(tableName, schema);
1057
1067
  this.createTable(schema);
1058
1068
  if (detailedValidate || this.config.writeDataSets) {
@@ -1089,6 +1099,55 @@ var LinesDB = class LinesDB {
1089
1099
  };
1090
1100
  }
1091
1101
  /**
1102
+ * A column no row holds a value in has no type to read a boolean or an object back with, and so reads
1103
+ * back as 1 or as JSON text. The first value written settles it, and a string settles it as text so an
1104
+ * object written later does not turn that text into JSON. Not asked of the schema: it names no type at
1105
+ * run time. Returns what puts the columns back, which a write that did not go in, or a transaction that
1106
+ * rolled back, must call: the value that settled it is not in the table
1107
+ */
1108
+ settleColumnsNoRowHolds(schema, written) {
1109
+ const before = [];
1110
+ for (const column of schema?.columns ?? []) {
1111
+ const value = written[column.name];
1112
+ if (column.type !== "NULL" || value === null || value === void 0) continue;
1113
+ before.push([
1114
+ column,
1115
+ column.type,
1116
+ column.valueType
1117
+ ]);
1118
+ if (typeof value === "boolean") {
1119
+ column.type = "INTEGER";
1120
+ column.valueType = "boolean";
1121
+ } else if (typeof value === "string") column.type = "TEXT";
1122
+ else if (typeof value === "number") column.type = Number.isInteger(value) ? "INTEGER" : "REAL";
1123
+ else if (typeof value === "object" && !(value instanceof Uint8Array)) column.type = "JSON";
1124
+ else before.pop();
1125
+ }
1126
+ const undo = () => {
1127
+ for (const [column, type, valueType] of before) {
1128
+ column.type = type;
1129
+ column.valueType = valueType;
1130
+ }
1131
+ };
1132
+ this.settleUndos?.push(undo);
1133
+ return undo;
1134
+ }
1135
+ /**
1136
+ * A column every row holds is inferred NOT NULL, which refuses a later row that leaves it out even
1137
+ * where the schema takes that row. The sample row without the field says whether the schema does.
1138
+ * A column the schema fills in stays NOT NULL: the row is stored as the schema leaves it
1139
+ */
1140
+ relaxColumnsTheSchemaLeavesOptional(tableName, schema, sample) {
1141
+ if (!sample || !this.validationSchemas.get(tableName)) return;
1142
+ for (const column of schema.columns) {
1143
+ if (!column.notNull || column.primaryKey || !(column.name in sample)) continue;
1144
+ const { [column.name]: _left, ...without } = sample;
1145
+ try {
1146
+ if ((this.validateAndTransform(tableName, without)[column.name] ?? null) === null) column.notNull = false;
1147
+ } catch {}
1148
+ }
1149
+ }
1150
+ /**
1092
1151
  * Create table in SQLite with constraints and indexes
1093
1152
  */
1094
1153
  createTable(schema) {
@@ -1154,6 +1213,7 @@ var LinesDB = class LinesDB {
1154
1213
  if (data.length === 0) return;
1155
1214
  const columnNames = schema.columns.map((col) => col.name);
1156
1215
  const quotedColumns = columnNames.map((name) => this.quoteIdentifier(name));
1216
+ const columnsByName = new Map(schema.columns.map((column) => [column.name, column]));
1157
1217
  const columnCount = columnNames.length;
1158
1218
  const maxBatchSize = Math.floor(900 / columnCount);
1159
1219
  const batchSize = Math.max(1, Math.min(maxBatchSize, 100));
@@ -1163,7 +1223,7 @@ var LinesDB = class LinesDB {
1163
1223
  const valuesPlaceholders = batch.map(() => `(${rowPlaceholders})`).join(", ");
1164
1224
  const sql = `INSERT INTO ${this.quoteTableName(tableName)} (${quotedColumns.join(", ")}) VALUES ${valuesPlaceholders}`;
1165
1225
  const values = [];
1166
- for (const row of batch) for (const col of columnNames) values.push(this.normalizeValue(row[col]));
1226
+ for (const row of batch) for (const col of columnNames) values.push(this.normalizeValue(row[col], columnsByName.get(col)));
1167
1227
  this.db.prepare(sql).run(...values);
1168
1228
  }
1169
1229
  }
@@ -1177,13 +1237,14 @@ var LinesDB = class LinesDB {
1177
1237
  const quotedColumns = columnNames.map((name) => this.quoteIdentifier(name));
1178
1238
  const placeholders = columnNames.map(() => "?").join(", ");
1179
1239
  const sql = `INSERT INTO ${this.quoteTableName(tableName)} (${quotedColumns.join(", ")}) VALUES (${placeholders})`;
1240
+ const columnsByName = new Map(schema.columns.map((column) => [column.name, column]));
1180
1241
  const stmt = this.db.prepare(sql);
1181
1242
  const rowOrigins = /* @__PURE__ */ new Map();
1182
1243
  this.rowOriginsByRowid.set(tableName, rowOrigins);
1183
1244
  for (let rowIndex = 0; rowIndex < data.length; rowIndex++) {
1184
1245
  const row = data[rowIndex];
1185
1246
  try {
1186
- const values = columnNames.map((col) => this.normalizeValue(row[col]));
1247
+ const values = columnNames.map((col) => this.normalizeValue(row[col], columnsByName.get(col)));
1187
1248
  const { lastInsertRowid } = stmt.run(...values);
1188
1249
  rowOrigins.set(String(lastInsertRowid), origins[rowIndex]);
1189
1250
  } catch (error) {
@@ -1202,7 +1263,7 @@ var LinesDB = class LinesDB {
1202
1263
  const fkValue = row[fk.column];
1203
1264
  if (fkValue === null || fkValue === void 0) continue;
1204
1265
  try {
1205
- const result = this.queryInternal(`SELECT COUNT(*) as count FROM ${this.quoteIdentifier(fk.references.table)} WHERE ${this.quoteIdentifier(fk.references.column)} = ?`, [this.normalizeValue(fkValue)]);
1266
+ 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))]);
1206
1267
  if (result.length > 0 && result[0].count === 0) return {
1207
1268
  file,
1208
1269
  tableName,
@@ -1350,7 +1411,7 @@ var LinesDB = class LinesDB {
1350
1411
  findInternal(tableName, where) {
1351
1412
  if (where === void 0) return this.queryInternal(`SELECT * FROM ${this.quoteTableName(tableName)}`).map((row) => this.deserializeRow(tableName, row));
1352
1413
  if (Array.isArray(where) && where.length === 0) return [];
1353
- const { sql, values, functionFilters, hasOrWithFunctionFilters } = this.buildWhereClause(where);
1414
+ const { sql, values, functionFilters, hasOrWithFunctionFilters } = this.buildWhereClause(where, tableName);
1354
1415
  let rows;
1355
1416
  if (hasOrWithFunctionFilters) {
1356
1417
  rows = this.queryInternal(`SELECT * FROM ${this.quoteTableName(tableName)}`).map((row) => this.deserializeRow(tableName, row));
@@ -1371,7 +1432,7 @@ var LinesDB = class LinesDB {
1371
1432
  }
1372
1433
  }
1373
1434
  findOneInternal(tableName, where) {
1374
- const { sql, values, functionFilters } = this.buildWhereClause(where);
1435
+ const { sql, values, functionFilters } = this.buildWhereClause(where, tableName);
1375
1436
  let rows;
1376
1437
  if (sql) rows = this.queryInternal(`SELECT * FROM ${this.quoteTableName(tableName)} WHERE ${sql}`, values).map((row) => this.deserializeRow(tableName, row));
1377
1438
  else rows = this.queryInternal(`SELECT * FROM ${this.quoteTableName(tableName)}`).map((row) => this.deserializeRow(tableName, row));
@@ -1468,13 +1529,22 @@ var LinesDB = class LinesDB {
1468
1529
  destination = join([this.config.dataDir].flat().find((dir) => resolve(dir) === resolve(dataDir)), `${tableName}.jsonl`);
1469
1530
  }
1470
1531
  const row = this.validateAndTransform(tableName, data);
1471
- if (!this.schemas.get(tableName)) throw new Error(`Table ${tableName} does not exist`);
1532
+ const schema = this.schemas.get(tableName);
1533
+ if (!schema) throw new Error(`Table ${tableName} does not exist`);
1534
+ this.addMissingColumns(tableName, schema, row);
1472
1535
  const columnNames = Object.keys(row);
1473
1536
  const quotedColumns = columnNames.map((col) => this.quoteIdentifier(col));
1474
1537
  const placeholders = columnNames.map(() => "?").join(", ");
1475
1538
  const sql = `INSERT INTO ${this.quoteTableName(tableName)} (${quotedColumns.join(", ")}) VALUES (${placeholders})`;
1476
- const values = Object.values(row).map((v) => this.normalizeValue(v));
1477
- const result = this.executeInternal(sql, values);
1539
+ const values = columnNames.map((col) => this.normalizeValue(row[col], this.columnOf(tableName, col)));
1540
+ const undoSettle = this.settleColumnsNoRowHolds(schema, row);
1541
+ let result;
1542
+ try {
1543
+ result = this.executeInternal(sql, values);
1544
+ } catch (error) {
1545
+ undoSettle();
1546
+ throw error;
1547
+ }
1478
1548
  if (destination) {
1479
1549
  const origins = this.rowOriginsByRowid.get(tableName) ?? /* @__PURE__ */ new Map();
1480
1550
  origins.set(String(result.lastInsertRowid), {
@@ -1491,6 +1561,27 @@ var LinesDB = class LinesDB {
1491
1561
  return result;
1492
1562
  }
1493
1563
  /**
1564
+ * A table made from the columns given has only those, and the validator may add a field they lack: the
1565
+ * columns of a table made from rows are those of the validated rows, which have it
1566
+ */
1567
+ addMissingColumns(tableName, schema, row) {
1568
+ if (!this.tablesFromGivenColumns.has(tableName)) return;
1569
+ const known = new Set(schema.columns.map((column) => column.name));
1570
+ const missing = Object.keys(row).filter((key) => !known.has(key));
1571
+ if (missing.length === 0) return;
1572
+ for (const column of unwrap(JsonlReader.inferSchema(tableName, [row])).columns) {
1573
+ if (!missing.includes(column.name)) continue;
1574
+ const sqlType = column.type === "JSON" ? "TEXT" : column.type;
1575
+ this.db.exec(`ALTER TABLE ${this.quoteTableName(tableName)} ADD COLUMN ${this.quoteIdentifier(column.name)} ${sqlType}`);
1576
+ schema.columns.push({
1577
+ name: column.name,
1578
+ type: column.type,
1579
+ notNull: false,
1580
+ valueType: column.valueType
1581
+ });
1582
+ }
1583
+ }
1584
+ /**
1494
1585
  * Batch insert rows with validation per record.
1495
1586
  */
1496
1587
  batchInsert(tableName, records) {
@@ -1503,7 +1594,8 @@ var LinesDB = class LinesDB {
1503
1594
  batchInsertInternal(tableName, records) {
1504
1595
  this.assertMutable(tableName);
1505
1596
  if (this.hasSeveralDataDirs()) throw new Error("Use insert with a dataDir for data sets");
1506
- if (!this.schemas.get(tableName)) throw new Error(`Table ${tableName} does not exist`);
1597
+ const schema = this.schemas.get(tableName);
1598
+ if (!schema) throw new Error(`Table ${tableName} does not exist`);
1507
1599
  if (records.length === 0) return {
1508
1600
  changes: 0,
1509
1601
  lastInsertRowid: 0
@@ -1513,12 +1605,20 @@ var LinesDB = class LinesDB {
1513
1605
  try {
1514
1606
  for (const record of records) {
1515
1607
  const row = this.validateAndTransform(tableName, record);
1608
+ this.addMissingColumns(tableName, schema, row);
1516
1609
  const columnNames = Object.keys(row);
1517
1610
  const quotedColumns = columnNames.map((col) => this.quoteIdentifier(col));
1518
1611
  const placeholders = columnNames.map(() => "?").join(", ");
1519
1612
  const sql = `INSERT INTO ${this.quoteTableName(tableName)} (${quotedColumns.join(", ")}) VALUES (${placeholders})`;
1520
- const values = columnNames.map((col) => this.normalizeValue(row[col]));
1521
- const result = this.executeInternal(sql, values);
1613
+ const values = columnNames.map((col) => this.normalizeValue(row[col], this.columnOf(tableName, col)));
1614
+ const undoSettle = this.settleColumnsNoRowHolds(this.schemas.get(tableName), row);
1615
+ let result;
1616
+ try {
1617
+ result = this.executeInternal(sql, values);
1618
+ } catch (error) {
1619
+ undoSettle();
1620
+ throw error;
1621
+ }
1522
1622
  this.noteFieldChanges(tableName, result.lastInsertRowid, {
1523
1623
  set: givenFields(record),
1524
1624
  inserted: true
@@ -1563,7 +1663,7 @@ var LinesDB = class LinesDB {
1563
1663
  this.validateData(tableName, mergedData);
1564
1664
  }
1565
1665
  }
1566
- const { sql: whereSql, values: whereValues, functionFilters } = this.buildWhereClause(where);
1666
+ const { sql: whereSql, values: whereValues, functionFilters } = this.buildWhereClause(where, tableName);
1567
1667
  if (functionFilters.length > 0) throw new Error("Function filters are not supported in update operations");
1568
1668
  const targets = this.queryInternal(`SELECT rowid AS "${ROWID_ALIAS}", * FROM ${this.quoteTableName(tableName)} WHERE ${whereSql}`, whereValues);
1569
1669
  const resetFields = options?.resetToDefault ?? [];
@@ -1575,12 +1675,19 @@ var LinesDB = class LinesDB {
1575
1675
  if (Object.keys(data).length > 0) {
1576
1676
  const setClauses = Object.keys(data).map((key) => `${this.quoteIdentifier(key)} = ?`).join(", ");
1577
1677
  const sql = `UPDATE ${this.quoteTableName(tableName)} SET ${setClauses} WHERE ${whereSql}`;
1578
- const values = [...Object.values(data).map((v) => this.normalizeValue(v)), ...whereValues];
1579
- result = this.executeInternal(sql, values);
1678
+ const values = [...Object.entries(data).map(([key, v]) => this.normalizeValue(v, this.columnOf(tableName, key))), ...whereValues];
1679
+ const undoSettle = this.settleColumnsNoRowHolds(this.schemas.get(tableName), data);
1680
+ try {
1681
+ result = this.executeInternal(sql, values);
1682
+ } catch (error) {
1683
+ undoSettle();
1684
+ throw error;
1685
+ }
1686
+ if (Number(result.changes) === 0) undoSettle();
1580
1687
  }
1581
1688
  const pkName = this.schemas.get(tableName)?.columns.find((col) => col.primaryKey)?.name;
1582
1689
  if (pkName && Object.hasOwn(data, pkName)) {
1583
- const moved = this.queryInternal(`SELECT rowid AS "${ROWID_ALIAS}" FROM ${this.quoteTableName(tableName)} WHERE ${this.quoteIdentifier(pkName)} = ?`, [this.normalizeValue(data[pkName])]);
1690
+ 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))]);
1584
1691
  if (targets.length === 1 && moved.length === 1) {
1585
1692
  const from = String(targets[0][ROWID_ALIAS]);
1586
1693
  const to = moved[0][ROWID_ALIAS];
@@ -1594,7 +1701,7 @@ var LinesDB = class LinesDB {
1594
1701
  }
1595
1702
  }
1596
1703
  for (const target of targets) {
1597
- const set = Object.keys(data).filter((key) => !sameStoredValue(target[key], this.normalizeValue(data[key])));
1704
+ const set = Object.keys(data).filter((key) => !sameStoredValue(target[key], this.normalizeValue(data[key], this.columnOf(tableName, key))));
1598
1705
  this.noteFieldChanges(tableName, target[ROWID_ALIAS], { set });
1599
1706
  }
1600
1707
  if (resets.length > 0) result = this.applyResets(tableName, resets, resetFields);
@@ -1698,7 +1805,7 @@ var LinesDB = class LinesDB {
1698
1805
  deleteInternal(tableName, where) {
1699
1806
  this.assertMutable(tableName);
1700
1807
  if (!this.schemas.get(tableName)) throw new Error(`Table ${tableName} does not exist`);
1701
- const { sql: whereSql, values, functionFilters } = this.buildWhereClause(where);
1808
+ const { sql: whereSql, values, functionFilters } = this.buildWhereClause(where, tableName);
1702
1809
  if (functionFilters.length > 0) throw new Error("Function filters are not supported in delete operations");
1703
1810
  const deleted = this.rowidsWhere(tableName, whereSql, values);
1704
1811
  const sql = `DELETE FROM ${this.quoteTableName(tableName)} WHERE ${whereSql}`;
@@ -1735,7 +1842,7 @@ var LinesDB = class LinesDB {
1735
1842
  });
1736
1843
  const placeholders = pkValues.map(() => "?").join(", ");
1737
1844
  const sql = `DELETE FROM ${this.quoteTableName(tableName)} WHERE ${this.quoteIdentifier(pkName)} IN (${placeholders})`;
1738
- const values = pkValues.map((value) => this.normalizeValue(value));
1845
+ const values = pkValues.map((value) => this.normalizeValue(value, this.columnOf(tableName, pkName)));
1739
1846
  const deleted = this.rowidsWhere(tableName, `${this.quoteIdentifier(pkName)} IN (${placeholders})`, values);
1740
1847
  const result = this.executeInternal(sql, values);
1741
1848
  this.forgetFieldChanges(tableName, deleted);
@@ -1748,17 +1855,24 @@ var LinesDB = class LinesDB {
1748
1855
  /**
1749
1856
  * Normalize value for SQLite
1750
1857
  */
1751
- normalizeValue(value) {
1858
+ normalizeValue(value, column) {
1752
1859
  if (value === null || value === void 0) return null;
1860
+ if (column?.type === "JSON") {
1861
+ if (value instanceof Uint8Array) return value;
1862
+ return typeof value === "bigint" ? value.toString() : JSON.stringify(value);
1863
+ }
1753
1864
  if (typeof value === "boolean") return value ? 1 : 0;
1754
1865
  if (typeof value === "string" || typeof value === "number" || typeof value === "bigint") return value;
1755
1866
  if (value instanceof Uint8Array) return value;
1756
1867
  return JSON.stringify(value);
1757
1868
  }
1869
+ columnOf(tableName, columnName) {
1870
+ return this.schemas.get(tableName)?.columns.find((column) => column.name === columnName);
1871
+ }
1758
1872
  /**
1759
1873
  * Build WHERE clause from condition (supports OR/AND with arrays and functions)
1760
1874
  */
1761
- buildWhereClause(condition) {
1875
+ buildWhereClause(condition, tableName) {
1762
1876
  const values = [];
1763
1877
  const functionFilters = [];
1764
1878
  let hasOrWithFunctionFilters = false;
@@ -1777,7 +1891,7 @@ var LinesDB = class LinesDB {
1777
1891
  hasFunctionFilter = true;
1778
1892
  } else {
1779
1893
  conditions.push(`${this.quoteIdentifier(key)} = ?`);
1780
- values.push(this.normalizeValue(value));
1894
+ values.push(this.normalizeValue(value, this.columnOf(tableName, key)));
1781
1895
  }
1782
1896
  if (isInOr && hasFunctionFilter) hasOrWithFunctionFilters = true;
1783
1897
  return conditions.join(" AND ");
@@ -2042,8 +2156,9 @@ var LinesDB = class LinesDB {
2042
2156
  for (const key of rowChanges?.reset ?? []) keep.delete(key);
2043
2157
  for (const key of namedFields) keep.add(key);
2044
2158
  if (pkName) keep.add(pkName);
2159
+ const untouched = line !== void 0 && !rowChanges?.inserted && !rowChanges?.set.size && !rowChanges?.reset.size;
2045
2160
  return {
2046
- written: Object.fromEntries(Object.entries(lineRow).filter(([key]) => keep.has(key))),
2161
+ 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])),
2047
2162
  narrowed: true
2048
2163
  };
2049
2164
  });
@@ -2127,7 +2242,7 @@ var LinesDB = class LinesDB {
2127
2242
  const validated = this.validateAndTransform(tableName, row);
2128
2243
  return {
2129
2244
  rowid,
2130
- values: fields.map((field) => this.normalizeValue(validated[field]))
2245
+ values: fields.map((field) => this.normalizeValue(validated[field], this.columnOf(tableName, field)))
2131
2246
  };
2132
2247
  });
2133
2248
  }
@@ -2480,15 +2595,18 @@ var LinesDB = class LinesDB {
2480
2595
  let rawSqlTablesBefore;
2481
2596
  let linesWithUnknownFieldsBefore;
2482
2597
  let originsBefore;
2598
+ let columnsBefore;
2483
2599
  const scannedBefore = [...this.scannedJsonlFiles];
2484
2600
  let written = [];
2485
2601
  try {
2486
2602
  await this.waitForPendingSyncs();
2487
2603
  originsBefore = new Map([...this.rowOriginsByRowid].map(([name, origins]) => [name, new Map(origins)]));
2604
+ columnsBefore = new Map([...this.tablesFromGivenColumns].map((name) => [name, [...this.schemas.get(name)?.columns ?? []]]));
2488
2605
  fieldChangesBefore = cloneFieldChanges(this.fieldChanges);
2489
2606
  rawSqlTablesBefore = new Set(this.rawSqlTables);
2490
2607
  linesWithUnknownFieldsBefore = new Map(Array.from(this.linesWithUnknownFields, ([tableName, lines]) => [tableName, new Map(lines)]));
2491
2608
  this.db.exec("BEGIN TRANSACTION");
2609
+ this.settleUndos = [];
2492
2610
  this.inTransaction = true;
2493
2611
  this.transactionToken = token;
2494
2612
  this.transactionStarting = false;
@@ -2501,6 +2619,7 @@ var LinesDB = class LinesDB {
2501
2619
  }
2502
2620
  if (!this.isReadOnlyDataSet()) written = await this.writeBackTogether(this.tablesChangedInTransaction());
2503
2621
  this.db.exec("COMMIT");
2622
+ this.settleUndos = void 0;
2504
2623
  this.inTransaction = false;
2505
2624
  this.transactionChanges = void 0;
2506
2625
  return ok(result);
@@ -2508,6 +2627,10 @@ var LinesDB = class LinesDB {
2508
2627
  this.transactionStarting = false;
2509
2628
  this.transactionChanges = void 0;
2510
2629
  if (originsBefore) this.rowOriginsByRowid = originsBefore;
2630
+ for (const [name, columns] of columnsBefore ?? []) {
2631
+ const schema = this.schemas.get(name);
2632
+ if (schema) schema.columns = columns;
2633
+ }
2511
2634
  this.scannedJsonlFiles = scannedBefore;
2512
2635
  if (fieldChangesBefore) this.fieldChanges = fieldChangesBefore;
2513
2636
  if (rawSqlTablesBefore) this.rawSqlTables = rawSqlTablesBefore;
@@ -2516,6 +2639,8 @@ var LinesDB = class LinesDB {
2516
2639
  if (this.inTransaction) try {
2517
2640
  this.db.exec("ROLLBACK");
2518
2641
  } catch (_rollbackError) {}
2642
+ for (const undo of [...this.settleUndos ?? []].reverse()) undo();
2643
+ this.settleUndos = void 0;
2519
2644
  this.inTransaction = false;
2520
2645
  return err(toError(failure));
2521
2646
  } finally {
@@ -2602,8 +2727,7 @@ var LinesDB = class LinesDB {
2602
2727
  function listJsonlFiles(tables) {
2603
2728
  return Array.from(tables.values()).flatMap((config) => config.jsonlPaths ?? [config.jsonlPath]).sort();
2604
2729
  }
2605
- //#endregion
2606
- //#region src/error-formatter.ts
2730
+ // src/error-formatter.ts
2607
2731
  var ErrorFormatter = class {
2608
2732
  verbose;
2609
2733
  constructor(options = {}) {
@@ -2705,8 +2829,7 @@ var ErrorFormatter = class {
2705
2829
  return styleText("red", "\n✗ Migration failed and was rolled back");
2706
2830
  }
2707
2831
  };
2708
- //#endregion
2709
- //#region src/fill.ts
2832
+ // src/fill.ts
2710
2833
  /**
2711
2834
  * Fill the named fields into the rows of the JSONL files that have no value for them, with the values
2712
2835
  * each table computes for a row. A value already in the file is never replaced, and a line that gains
@@ -2919,8 +3042,7 @@ function serializeRow(row, fieldOrder) {
2919
3042
  for (const [key, value] of ordered) setField(out, key, value);
2920
3043
  return JSON.stringify(out);
2921
3044
  }
2922
- //#endregion
2923
- //#region src/dataset-config.ts
3045
+ // src/dataset-config.ts
2924
3046
  const directories = z.array(z.string().min(1)).min(1);
2925
3047
  const datasetConfigSchema = z.strictObject({
2926
3048
  schemaDir: z.string().min(1),
@@ -2966,43 +3088,56 @@ async function loadDatasetConfig(path = "lines-db.config.json", options = {}) {
2966
3088
  schemaDir
2967
3089
  };
2968
3090
  }
2969
- //#endregion
2970
- //#region src/cli.ts
2971
- const __loculus_0 = /^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?$/;
2972
- function __loculus_15(message, code) {
2973
- return { issues: [{
2974
- message,
2975
- code
2976
- }] };
3091
+ // src/cli.ts
3092
+ function __loculus_9(result, input) {
3093
+ if (config().customError === void 0) return result;
3094
+ return result.issues ? { issues: result.issues.map((issue) => issue.path?.length ? issue : _resolveIssue(issue, input)) } : result;
2977
3095
  }
2978
- function __loculus_5(value) {
2979
- if (typeof value !== "string") return __loculus_15("Expected a string", "invalid_type");
3096
+ const __loculus_1 = /^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?$/;
3097
+ function __loculus_25(message, code, raw) {
3098
+ return { issues: [_typeIssue("string", raw, message)] };
3099
+ }
3100
+ function __loculus_12(value) {
3101
+ const raw = value;
3102
+ if (typeof value !== "string") return __loculus_25("Expected a string", "invalid_type", raw);
2980
3103
  return { value };
2981
3104
  }
2982
- function __loculus_7(value) {
3105
+ function __loculus_11(value) {
3106
+ const raw = value;
3107
+ if (typeof value !== "string") return __loculus_9(__loculus_25("Expected a string", "invalid_type", raw), raw);
3108
+ return "issues" in {} ? __loculus_9({ value }, raw) : { value };
3109
+ }
3110
+ function __loculus_15(value) {
3111
+ const raw = value;
2983
3112
  if (value === void 0) return { value: void 0 };
2984
- if (typeof value !== "string") return { issues: [{
2985
- message: "Expected a string",
2986
- code: "invalid_type"
2987
- }] };
3113
+ if (typeof value !== "string") return { issues: [_typeIssue("string", raw, "Expected a string")] };
2988
3114
  return { value };
2989
3115
  }
2990
- function __loculus_9(value) {
3116
+ function __loculus_14(value) {
3117
+ const raw = value;
3118
+ if (value === void 0) return "issues" in {} ? __loculus_9({ value: void 0 }, raw) : { value: void 0 };
3119
+ if (typeof value !== "string") return __loculus_9({ issues: [_typeIssue("string", raw, "Expected a string")] }, raw);
3120
+ return "issues" in {} ? __loculus_9({ value }, raw) : { value };
3121
+ }
3122
+ function __loculus_18(value) {
3123
+ const raw = value;
2991
3124
  if (value === void 0) return { value: false };
2992
3125
  if (value === true || value === "true" || value === "1") return { value: true };
2993
3126
  if (value === false || value === "false" || value === "0") return { value: false };
2994
- return { issues: [{
2995
- message: "Expected true, false, 1 or 0",
2996
- code: "invalid_type"
2997
- }] };
3127
+ return { issues: [_typeIssue("boolean", raw, "Expected true, false, 1 or 0")] };
3128
+ }
3129
+ function __loculus_17(value) {
3130
+ const raw = value;
3131
+ if (value === void 0) return "issues" in {} ? __loculus_9({ value: false }, raw) : { value: false };
3132
+ if (value === true || value === "true" || value === "1") return "issues" in {} ? __loculus_9({ value: true }, raw) : { value: true };
3133
+ if (value === false || value === "false" || value === "0") return "issues" in {} ? __loculus_9({ value: false }, raw) : { value: false };
3134
+ return __loculus_9({ issues: [_typeIssue("boolean", raw, "Expected true, false, 1 or 0")] }, raw);
2998
3135
  }
2999
- function __loculus_13(value) {
3136
+ function __loculus_23(value) {
3137
+ const raw = value;
3000
3138
  if (value === void 0) return { value: 4848 };
3001
3139
  if (typeof value !== "number") {
3002
- if (typeof value !== "string" || !__loculus_0.test(value)) return { issues: [{
3003
- message: "Expected a decimal number",
3004
- code: "invalid_type"
3005
- }] };
3140
+ if (typeof value !== "string" || !__loculus_1.test(value)) return { issues: [_typeIssue("number", raw, "Expected a decimal number")] };
3006
3141
  value = Number(value);
3007
3142
  }
3008
3143
  if (!Number.isFinite(value)) return { issues: [{
@@ -3015,16 +3150,53 @@ function __loculus_13(value) {
3015
3150
  }] };
3016
3151
  if (!(value >= 0)) return { issues: [{
3017
3152
  message: "Expected at least 0",
3018
- code: "invalid_value"
3153
+ code: "too_small",
3154
+ origin: "number",
3155
+ min: 0,
3156
+ inclusive: true
3019
3157
  }] };
3020
3158
  if (!(value <= 65535)) return { issues: [{
3021
3159
  message: "Expected at most 65535",
3022
- code: "invalid_value"
3160
+ code: "too_big",
3161
+ origin: "number",
3162
+ max: 65535,
3163
+ inclusive: true
3023
3164
  }] };
3024
3165
  return { value };
3025
3166
  }
3167
+ function __loculus_22(value) {
3168
+ const raw = value;
3169
+ if (value === void 0) return "issues" in {} ? __loculus_9({ value: 4848 }, raw) : { value: 4848 };
3170
+ if (typeof value !== "number") {
3171
+ if (typeof value !== "string" || !__loculus_1.test(value)) return __loculus_9({ issues: [_typeIssue("number", raw, "Expected a decimal number")] }, raw);
3172
+ value = Number(value);
3173
+ }
3174
+ if (!Number.isFinite(value)) return __loculus_9({ issues: [{
3175
+ message: "Expected a finite number",
3176
+ code: "invalid_value"
3177
+ }] }, raw);
3178
+ if (!Number.isSafeInteger(value)) return __loculus_9({ issues: [{
3179
+ message: "Expected a safe integer",
3180
+ code: "invalid_value"
3181
+ }] }, raw);
3182
+ if (!(value >= 0)) return __loculus_9({ issues: [{
3183
+ message: "Expected at least 0",
3184
+ code: "too_small",
3185
+ origin: "number",
3186
+ min: 0,
3187
+ inclusive: true
3188
+ }] }, raw);
3189
+ if (!(value <= 65535)) return __loculus_9({ issues: [{
3190
+ message: "Expected at most 65535",
3191
+ code: "too_big",
3192
+ origin: "number",
3193
+ max: 65535,
3194
+ inclusive: true
3195
+ }] }, raw);
3196
+ return "issues" in {} ? __loculus_9({ value }, raw) : { value };
3197
+ }
3026
3198
  /* @__NO_SIDE_EFFECTS__ */
3027
- function __loculus_6() {
3199
+ function __loculus_13() {
3028
3200
  return {
3029
3201
  meta: {
3030
3202
  kind: "string",
@@ -3033,13 +3205,14 @@ function __loculus_6() {
3033
3205
  "~standard": {
3034
3206
  version: 1,
3035
3207
  vendor: "loculus",
3036
- validate: __loculus_5
3208
+ validate: __loculus_11
3037
3209
  },
3038
- field: true
3210
+ field: true,
3211
+ [_rawValidate]: __loculus_12
3039
3212
  };
3040
3213
  }
3041
3214
  /* @__NO_SIDE_EFFECTS__ */
3042
- function __loculus_8() {
3215
+ function __loculus_16() {
3043
3216
  return {
3044
3217
  meta: {
3045
3218
  kind: "string",
@@ -3050,13 +3223,14 @@ function __loculus_8() {
3050
3223
  "~standard": {
3051
3224
  version: 1,
3052
3225
  vendor: "loculus",
3053
- validate: __loculus_7
3226
+ validate: __loculus_14
3054
3227
  },
3055
- field: true
3228
+ field: true,
3229
+ [_rawValidate]: __loculus_15
3056
3230
  };
3057
3231
  }
3058
3232
  /* @__NO_SIDE_EFFECTS__ */
3059
- function __loculus_10() {
3233
+ function __loculus_19() {
3060
3234
  return {
3061
3235
  meta: {
3062
3236
  kind: "boolean",
@@ -3068,13 +3242,14 @@ function __loculus_10() {
3068
3242
  "~standard": {
3069
3243
  version: 1,
3070
3244
  vendor: "loculus",
3071
- validate: __loculus_9
3245
+ validate: __loculus_17
3072
3246
  },
3073
- field: true
3247
+ field: true,
3248
+ [_rawValidate]: __loculus_18
3074
3249
  };
3075
3250
  }
3076
3251
  /* @__NO_SIDE_EFFECTS__ */
3077
- function __loculus_14() {
3252
+ function __loculus_24() {
3078
3253
  return {
3079
3254
  meta: {
3080
3255
  kind: "number",
@@ -3086,21 +3261,20 @@ function __loculus_14() {
3086
3261
  "~standard": {
3087
3262
  version: 1,
3088
3263
  vendor: "loculus",
3089
- validate: __loculus_13
3264
+ validate: __loculus_22
3090
3265
  },
3091
- field: true
3266
+ field: true,
3267
+ [_rawValidate]: __loculus_23
3092
3268
  };
3093
3269
  }
3094
- function __loculus_12(value) {
3095
- if (!Array.isArray(value)) return { issues: [{
3096
- message: "Expected an array",
3097
- code: "invalid_type"
3098
- }] };
3270
+ function __loculus_21(value) {
3271
+ const raw = value;
3272
+ if (!Array.isArray(value)) return __loculus_9({ issues: [_typeIssue("array", raw, "Expected an array")] }, raw);
3099
3273
  const inputs = Array.isArray(value) ? value : [value];
3100
3274
  const output = [];
3101
3275
  let issues;
3102
3276
  for (let i = 0; i < inputs.length; i++) {
3103
- const result = __loculus_5(inputs[i]);
3277
+ const result = __loculus_11(inputs[i]);
3104
3278
  if (result.issues) for (const issue of result.issues) (issues ??= []).push({
3105
3279
  ...issue,
3106
3280
  path: issue.path ? [i, ...issue.path] : [i]
@@ -3108,14 +3282,17 @@ function __loculus_12(value) {
3108
3282
  else output.push(result.value);
3109
3283
  }
3110
3284
  if (issues) return { issues };
3111
- if (inputs.length < 1) return { issues: [{
3285
+ if (inputs.length < 1) return __loculus_9({ issues: [{
3112
3286
  message: "Expected at least 1 items",
3113
- code: "invalid_value"
3114
- }] };
3115
- return { value: output };
3287
+ code: "too_small",
3288
+ origin: "array",
3289
+ min: 1,
3290
+ inclusive: true
3291
+ }] }, raw);
3292
+ return "issues" in {} ? __loculus_9({ value: output }, raw) : { value: output };
3116
3293
  }
3117
3294
  /* @__NO_SIDE_EFFECTS__ */
3118
- function __loculus_11(inner) {
3295
+ function __loculus_20(inner) {
3119
3296
  return {
3120
3297
  meta: {
3121
3298
  kind: "array",
@@ -3127,7 +3304,7 @@ function __loculus_11(inner) {
3127
3304
  "~standard": {
3128
3305
  version: 1,
3129
3306
  vendor: "loculus",
3130
- validate: __loculus_12
3307
+ validate: __loculus_21
3131
3308
  },
3132
3309
  field: true
3133
3310
  };
@@ -3165,11 +3342,11 @@ const generateCommand = defineCommand({
3165
3342
  name: "generate",
3166
3343
  description: "Generate TypeScript type definitions from schema files",
3167
3344
  args: l.object({
3168
- dataDir: arg(/* @__PURE__ */ __loculus_6(), {
3345
+ dataDir: arg(/* @__PURE__ */ __loculus_13(), {
3169
3346
  positional: true,
3170
3347
  description: "Directory containing JSONL and schema files"
3171
3348
  }),
3172
- output: arg(/* @__PURE__ */ __loculus_8(), {
3349
+ output: arg(/* @__PURE__ */ __loculus_16(), {
3173
3350
  alias: "o",
3174
3351
  description: "Output file path (default: db.ts in dataDir)"
3175
3352
  })
@@ -3191,14 +3368,14 @@ const validateCommand = defineCommand({
3191
3368
  name: "validate",
3192
3369
  description: "Validate JSONL file(s) against schema",
3193
3370
  args: l.object({
3194
- path: arg(/* @__PURE__ */ __loculus_8(), {
3371
+ path: arg(/* @__PURE__ */ __loculus_16(), {
3195
3372
  positional: true,
3196
3373
  description: "File or directory path to validate (omit to use lines-db.config.json)"
3197
3374
  }),
3198
- config: arg(/* @__PURE__ */ __loculus_8(), { description: "Dataset configuration file (default: ./lines-db.config.json)" }),
3199
- dataset: arg(l.array(/* @__PURE__ */ __loculus_6(), { optional: true }), { description: "Named datasets to validate together with base (repeat to select several)" }),
3200
- allDatasets: arg(/* @__PURE__ */ __loculus_10(), { description: "Validate base and all datasets together" }),
3201
- verbose: arg(/* @__PURE__ */ __loculus_10(), {
3375
+ config: arg(/* @__PURE__ */ __loculus_16(), { description: "Dataset configuration file (default: ./lines-db.config.json)" }),
3376
+ dataset: arg(l.array(/* @__PURE__ */ __loculus_13(), { optional: true }), { description: "Named datasets to validate together with base (repeat to select several)" }),
3377
+ allDatasets: arg(/* @__PURE__ */ __loculus_19(), { description: "Validate base and all datasets together" }),
3378
+ verbose: arg(/* @__PURE__ */ __loculus_19(), {
3202
3379
  alias: "v",
3203
3380
  description: "Show verbose error output"
3204
3381
  })
@@ -3216,6 +3393,11 @@ const validateCommand = defineCommand({
3216
3393
  } finally {
3217
3394
  await db.close();
3218
3395
  }
3396
+ if (result.tableResults.length > 0 && result.tableResults.every((r) => r.rowCount === 0)) {
3397
+ const dirs = [config.dataDir].flat().join(", ");
3398
+ const message = tableName ? `The selected file ${tableName}.jsonl in ${dirs} is empty (0 records), so none of its records were validated.` : `No records were validated: every JSONL file in ${dirs} is empty (0 records in total).`;
3399
+ console.warn(styleText("yellow", `⚠ ${message}`));
3400
+ }
3219
3401
  if (!tableName) {
3220
3402
  const formatter = new ErrorFormatter({ verbose: args.verbose });
3221
3403
  for (const tableResult of result.tableResults) if (tableResult.valid && tableResult.warnings.length === 0) console.log(styleText("green", `✓ ${tableResult.tableName} (${tableResult.rowCount} records)`));
@@ -3294,24 +3476,24 @@ const migrateCommand = defineCommand({
3294
3476
  name: "migrate",
3295
3477
  description: "Migrate data with transformation function",
3296
3478
  args: l.object({
3297
- path: arg(/* @__PURE__ */ __loculus_6(), {
3479
+ path: arg(/* @__PURE__ */ __loculus_13(), {
3298
3480
  positional: true,
3299
3481
  description: "File or directory path to migrate"
3300
3482
  }),
3301
- transform: arg(/* @__PURE__ */ __loculus_6(), {
3483
+ transform: arg(/* @__PURE__ */ __loculus_13(), {
3302
3484
  positional: true,
3303
3485
  description: "Transform function (e.g., \"(row) => ({ ...row, age: row.age + 1 })\")"
3304
3486
  }),
3305
- filter: arg(/* @__PURE__ */ __loculus_8(), {
3487
+ filter: arg(/* @__PURE__ */ __loculus_16(), {
3306
3488
  alias: "f",
3307
3489
  description: "Filter expression"
3308
3490
  }),
3309
- fields: arg(/* @__PURE__ */ __loculus_8(), { description: "Comma-separated fields to write back (e.g. \"id\"). Every other field keeps the value the JSONL file already had. Default: write every field" }),
3310
- errorOutput: arg(/* @__PURE__ */ __loculus_8(), {
3491
+ fields: arg(/* @__PURE__ */ __loculus_16(), { description: "Comma-separated fields to write back (e.g. \"id\"). Every other field keeps the value the JSONL file already had. Default: write every field" }),
3492
+ errorOutput: arg(/* @__PURE__ */ __loculus_16(), {
3311
3493
  alias: "e",
3312
3494
  description: "Output file path for transformed data when migration fails"
3313
3495
  }),
3314
- verbose: arg(/* @__PURE__ */ __loculus_10(), {
3496
+ verbose: arg(/* @__PURE__ */ __loculus_19(), {
3315
3497
  alias: "v",
3316
3498
  description: "Show verbose error output"
3317
3499
  })
@@ -3347,12 +3529,12 @@ const fillCommand = defineCommand({
3347
3529
  name: "fill",
3348
3530
  description: "Fill the values each table computes into the JSONL rows that have none for the named fields",
3349
3531
  args: l.object({
3350
- path: arg(/* @__PURE__ */ __loculus_11(/* @__PURE__ */ __loculus_6()), {
3532
+ path: arg(/* @__PURE__ */ __loculus_20(/* @__PURE__ */ __loculus_13()), {
3351
3533
  positional: true,
3352
3534
  description: "One or more data directories or .jsonl files"
3353
3535
  }),
3354
- schemaDir: arg(/* @__PURE__ */ __loculus_8(), { description: "Directory holding shared schemas (default: next to each JSONL file)" }),
3355
- fields: arg(/* @__PURE__ */ __loculus_8(), {
3536
+ schemaDir: arg(/* @__PURE__ */ __loculus_16(), { description: "Directory holding shared schemas (default: next to each JSONL file)" }),
3537
+ fields: arg(/* @__PURE__ */ __loculus_16(), {
3356
3538
  alias: "f",
3357
3539
  description: "Comma-separated fields to fill (default: each table's primary key)"
3358
3540
  })
@@ -3389,17 +3571,17 @@ const studioCommand = defineCommand({
3389
3571
  name: "studio",
3390
3572
  description: "Browse and edit the tables of a data directory in the browser",
3391
3573
  args: l.object({
3392
- path: arg(/* @__PURE__ */ __loculus_8(), {
3574
+ path: arg(/* @__PURE__ */ __loculus_16(), {
3393
3575
  positional: true,
3394
3576
  description: "Directory containing JSONL files"
3395
3577
  }),
3396
- dataDir: arg(l.array(/* @__PURE__ */ __loculus_6(), { default: [] }), { description: "Directory containing JSONL files (repeatable)" }),
3397
- schemaDir: arg(/* @__PURE__ */ __loculus_8(), { description: "Directory containing shared schema files (required for several data directories)" }),
3398
- port: arg(/* @__PURE__ */ __loculus_14(), {
3578
+ dataDir: arg(l.array(/* @__PURE__ */ __loculus_13(), { default: [] }), { description: "Directory containing JSONL files (repeatable)" }),
3579
+ schemaDir: arg(/* @__PURE__ */ __loculus_16(), { description: "Directory containing shared schema files (required for several data directories)" }),
3580
+ port: arg(/* @__PURE__ */ __loculus_24(), {
3399
3581
  alias: "p",
3400
3582
  description: "Port to listen on (0 picks a free one)"
3401
3583
  }),
3402
- open: arg(/* @__PURE__ */ __loculus_10(), { description: "Open the studio in the default browser" }),
3584
+ open: arg(/* @__PURE__ */ __loculus_19(), { description: "Open the studio in the default browser" }),
3403
3585
  writeFilledValues: arg(l.enum(["all", "primaryKey"], { default: "primaryKey" }), { description: "Values the schema fills in that a save writes: all of them, or only a generated primary key" })
3404
3586
  }),
3405
3587
  run: async (args) => {
@@ -3721,5 +3903,4 @@ async function migrateFile(filePath, transformStr, options) {
3721
3903
  throw error;
3722
3904
  }
3723
3905
  }
3724
- //#endregion
3725
3906
  export {};