lines-db 0.18.1 → 0.19.1
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 +23 -0
- package/README.ja.md +1 -1
- package/README.md +3 -1
- package/bin/cli.mjs +688 -112
- package/dist/index.d.mts +39 -31
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +247 -80
- package/dist/index.mjs.map +1 -1
- package/dist/internal.d.mts +2 -4
- package/dist/internal.d.mts.map +1 -1
- package/dist/internal.mjs +1 -1
- package/dist/schema-module-D4j10w8_.mjs +396 -0
- package/dist/schema-module-D4j10w8_.mjs.map +1 -0
- package/dist/{jsonl-reader-CoYEJ9pg.d.mts → schema-module-Tb40gPyF.d.mts} +25 -8
- package/dist/schema-module-Tb40gPyF.d.mts.map +1 -0
- package/package.json +6 -6
- package/dist/jsonl-reader-CoYEJ9pg.d.mts.map +0 -1
- package/dist/replace-file-AWLIm7aN.mjs +0 -203
- package/dist/replace-file-AWLIm7aN.mjs.map +0 -1
package/bin/cli.mjs
CHANGED
|
@@ -1,19 +1,21 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
+
import * as nodeModule from "node:module";
|
|
2
3
|
import { createRequire, register } from "node:module";
|
|
4
|
+
import * as l from "loculus";
|
|
5
|
+
import { _rawValidate, _resolveIssue, _typeIssue, config } from "loculus";
|
|
3
6
|
import { access, chmod, link, mkdir, readFile, readdir, realpath, rename, rm, stat, writeFile } from "node:fs/promises";
|
|
4
7
|
import { basename, dirname, extname, isAbsolute, join, normalize, relative, resolve } from "node:path";
|
|
5
8
|
import { createHash, randomBytes } from "node:crypto";
|
|
6
|
-
import {
|
|
9
|
+
import { existsSync, readFileSync, realpathSync } from "node:fs";
|
|
10
|
+
import { fileURLToPath, pathToFileURL } from "node:url";
|
|
7
11
|
import { styleText } from "node:util";
|
|
8
|
-
import * as l from "loculus";
|
|
9
12
|
import { arg, defineCommand, runMain } from "@politty/loculus";
|
|
10
13
|
import { runInNewContext } from "node:vm";
|
|
11
14
|
import { spawn } from "node:child_process";
|
|
12
15
|
import { z } from "zod";
|
|
13
|
-
|
|
16
|
+
// \0rolldown/runtime.js
|
|
14
17
|
var __require = /* #__PURE__ */ (() => createRequire(import.meta.url))();
|
|
15
|
-
|
|
16
|
-
//#region src/schema-extensions.ts
|
|
18
|
+
// src/schema-extensions.ts
|
|
17
19
|
/**
|
|
18
20
|
* Supported schema file extensions, in priority order.
|
|
19
21
|
* The first match wins when discovering schema files.
|
|
@@ -62,8 +64,7 @@ function rewriteExtensionForImport(filePath) {
|
|
|
62
64
|
for (const [tsExt, jsExt] of Object.entries(SCHEMA_TO_JS_IMPORT_MAP)) if (filePath.endsWith(tsExt)) return filePath.slice(0, -tsExt.length) + jsExt;
|
|
63
65
|
return filePath;
|
|
64
66
|
}
|
|
65
|
-
|
|
66
|
-
//#region src/type-generator.ts
|
|
67
|
+
// src/type-generator.ts
|
|
67
68
|
var TypeGenerator = class {
|
|
68
69
|
dataDir;
|
|
69
70
|
projectRoot;
|
|
@@ -169,15 +170,13 @@ function toCamelCase(value) {
|
|
|
169
170
|
function sanitizeIdentifier(value) {
|
|
170
171
|
return value.replace(/[^A-Za-z0-9_$]/g, "");
|
|
171
172
|
}
|
|
172
|
-
|
|
173
|
-
//#region src/runtime.ts
|
|
173
|
+
// src/runtime.ts
|
|
174
174
|
function detectRuntime() {
|
|
175
175
|
if (typeof process !== "undefined" && process.versions && process.versions.node) return "node";
|
|
176
176
|
return "unknown";
|
|
177
177
|
}
|
|
178
178
|
const RUNTIME = detectRuntime();
|
|
179
|
-
|
|
180
|
-
//#region src/sqlite-adapter.ts
|
|
179
|
+
// src/sqlite-adapter.ts
|
|
181
180
|
/**
|
|
182
181
|
* SQLite adapter for Node.js
|
|
183
182
|
*/
|
|
@@ -218,8 +217,7 @@ function createNodeDatabase(path) {
|
|
|
218
217
|
}
|
|
219
218
|
};
|
|
220
219
|
}
|
|
221
|
-
|
|
222
|
-
//#region src/result.ts
|
|
220
|
+
// src/result.ts
|
|
223
221
|
function ok(value) {
|
|
224
222
|
return {
|
|
225
223
|
ok: true,
|
|
@@ -241,8 +239,7 @@ function unwrap(result) {
|
|
|
241
239
|
if (result.ok) return result.value;
|
|
242
240
|
throw result.error;
|
|
243
241
|
}
|
|
244
|
-
|
|
245
|
-
//#region src/jsonl-reader.ts
|
|
242
|
+
// src/jsonl-reader.ts
|
|
246
243
|
/** Fingerprint of a JSONL file's content, to tell whether the file changed since it was read */
|
|
247
244
|
function hashJsonlContent(content) {
|
|
248
245
|
return createHash("sha256").update(content).digest("hex");
|
|
@@ -364,8 +361,7 @@ var JsonlReader = class {
|
|
|
364
361
|
return "TEXT";
|
|
365
362
|
}
|
|
366
363
|
};
|
|
367
|
-
|
|
368
|
-
//#region src/jsonl-writer.ts
|
|
364
|
+
// src/jsonl-writer.ts
|
|
369
365
|
var JsonlWriter = class {
|
|
370
366
|
/**
|
|
371
367
|
* Write data to JSONL file
|
|
@@ -394,8 +390,7 @@ var JsonlWriter = class {
|
|
|
394
390
|
}
|
|
395
391
|
}
|
|
396
392
|
};
|
|
397
|
-
|
|
398
|
-
//#region src/replace-file.ts
|
|
393
|
+
// src/replace-file.ts
|
|
399
394
|
async function replaceFile(file, write, expected) {
|
|
400
395
|
const suffix = randomBytes(12).toString("hex");
|
|
401
396
|
const temporary = `${file}.${suffix}.tmp`;
|
|
@@ -445,8 +440,200 @@ async function replaceFile(file, write, expected) {
|
|
|
445
440
|
if (!moved) await rm(temporary, { force: true }).catch(() => {});
|
|
446
441
|
}
|
|
447
442
|
}
|
|
448
|
-
|
|
449
|
-
|
|
443
|
+
// src/schema-module.ts
|
|
444
|
+
const VERSION_PARAM = "linesDbV";
|
|
445
|
+
const SHARED = Symbol.for("lines-db:schema-imports:1");
|
|
446
|
+
let counter = 0;
|
|
447
|
+
const shared = globalThis[SHARED] ??= {
|
|
448
|
+
graph: /* @__PURE__ */ new Map(),
|
|
449
|
+
evaluated: /* @__PURE__ */ new Map(),
|
|
450
|
+
evaluatedUrls: /* @__PURE__ */ new Set(),
|
|
451
|
+
versions: /* @__PURE__ */ new Map(),
|
|
452
|
+
hashes: /* @__PURE__ */ new Map(),
|
|
453
|
+
salt: "",
|
|
454
|
+
hooked: false
|
|
455
|
+
};
|
|
456
|
+
shared.evaluated ??= /* @__PURE__ */ new Map();
|
|
457
|
+
shared.evaluatedUrls ??= /* @__PURE__ */ new Set();
|
|
458
|
+
const packageRoots = /* @__PURE__ */ new Map();
|
|
459
|
+
function hashOf(parts) {
|
|
460
|
+
const hash = createHash("sha1");
|
|
461
|
+
for (const part of parts) hash.update(part).update("\0");
|
|
462
|
+
return hash.digest("hex");
|
|
463
|
+
}
|
|
464
|
+
function contentOf(file) {
|
|
465
|
+
try {
|
|
466
|
+
return readFileSync(file);
|
|
467
|
+
} catch {
|
|
468
|
+
return;
|
|
469
|
+
}
|
|
470
|
+
}
|
|
471
|
+
function hashContent(content) {
|
|
472
|
+
return createHash("sha1").update(content).digest("hex");
|
|
473
|
+
}
|
|
474
|
+
/** What a file that is not there holds: not a hash, so that no file can have it */
|
|
475
|
+
const MISSING_HASH = "missing";
|
|
476
|
+
function hashOfFile(file) {
|
|
477
|
+
const content = contentOf(file);
|
|
478
|
+
return content === void 0 ? MISSING_HASH : hashContent(content);
|
|
479
|
+
}
|
|
480
|
+
/**
|
|
481
|
+
* What the file is, with what it imports: a file evaluated again only when it or a file it imports changed,
|
|
482
|
+
* as a URL that names the version is one module for as long as the version stays. An import not recorded
|
|
483
|
+
* yet is not in the version. A file importing itself through others is taken by its own content there, so
|
|
484
|
+
* a version that was cut by a cycle is kept only for the file the count started from, which holds all of it
|
|
485
|
+
*/
|
|
486
|
+
function versionOf(file, visiting = /* @__PURE__ */ new Set()) {
|
|
487
|
+
const known = shared.versions.get(file);
|
|
488
|
+
if (known) return {
|
|
489
|
+
version: known,
|
|
490
|
+
whole: true
|
|
491
|
+
};
|
|
492
|
+
const content = hashOfFile(file);
|
|
493
|
+
if (!shared.hashes.has(file)) shared.hashes.set(file, content);
|
|
494
|
+
if (visiting.has(file)) return {
|
|
495
|
+
version: hashOf([shared.salt, content]),
|
|
496
|
+
whole: false
|
|
497
|
+
};
|
|
498
|
+
visiting.add(file);
|
|
499
|
+
let whole = true;
|
|
500
|
+
const versions = [];
|
|
501
|
+
for (const imported of [...shared.graph.get(file) ?? []].sort()) {
|
|
502
|
+
const importedVersion = versionOf(imported, visiting);
|
|
503
|
+
versions.push(importedVersion.version);
|
|
504
|
+
whole &&= importedVersion.whole;
|
|
505
|
+
}
|
|
506
|
+
visiting.delete(file);
|
|
507
|
+
const version = hashOf([
|
|
508
|
+
shared.salt,
|
|
509
|
+
content,
|
|
510
|
+
...versions
|
|
511
|
+
]);
|
|
512
|
+
if (whole || visiting.size === 0) shared.versions.set(file, version);
|
|
513
|
+
return {
|
|
514
|
+
version,
|
|
515
|
+
whole
|
|
516
|
+
};
|
|
517
|
+
}
|
|
518
|
+
function packageRootOf(file) {
|
|
519
|
+
const start = dirname(file);
|
|
520
|
+
const cached = packageRoots.get(start);
|
|
521
|
+
if (cached !== void 0) return cached;
|
|
522
|
+
let dir = start;
|
|
523
|
+
let root = "";
|
|
524
|
+
for (;;) {
|
|
525
|
+
if (existsSync(join(dir, "package.json"))) {
|
|
526
|
+
root = dir;
|
|
527
|
+
break;
|
|
528
|
+
}
|
|
529
|
+
const parent = dirname(dir);
|
|
530
|
+
if (parent === dir) break;
|
|
531
|
+
dir = parent;
|
|
532
|
+
}
|
|
533
|
+
packageRoots.set(start, root);
|
|
534
|
+
return root;
|
|
535
|
+
}
|
|
536
|
+
/**
|
|
537
|
+
* A file imported under a URL not seen before is evaluated, and imports again what it imports: what an earlier
|
|
538
|
+
* evaluation of it imported is dropped here, as a file that no longer imports anything resolves nothing to
|
|
539
|
+
* replace it. A URL seen before is a module already evaluated, whose imports stay
|
|
540
|
+
*/
|
|
541
|
+
function startEvaluation(file, url) {
|
|
542
|
+
if (shared.evaluatedUrls.has(url)) return;
|
|
543
|
+
shared.evaluatedUrls.add(url);
|
|
544
|
+
shared.graph.set(file, /* @__PURE__ */ new Set());
|
|
545
|
+
shared.evaluated.set(file, url);
|
|
546
|
+
}
|
|
547
|
+
/** Records the import of a file by a file that is read with versions; false for a file that is not one of the project */
|
|
548
|
+
function recordImport(parentURL, imported) {
|
|
549
|
+
if (!new URL(parentURL).searchParams.has(VERSION_PARAM)) return false;
|
|
550
|
+
const parent = fileURLToPath(parentURL);
|
|
551
|
+
if (packageRootOf(imported) !== packageRootOf(parent)) return false;
|
|
552
|
+
let imports = shared.graph.get(parent);
|
|
553
|
+
if (!imports || shared.evaluated.get(parent) !== parentURL) {
|
|
554
|
+
imports = /* @__PURE__ */ new Set();
|
|
555
|
+
shared.graph.set(parent, imports);
|
|
556
|
+
shared.evaluated.set(parent, parentURL);
|
|
557
|
+
}
|
|
558
|
+
imports.add(imported);
|
|
559
|
+
versionOf(imported);
|
|
560
|
+
return true;
|
|
561
|
+
}
|
|
562
|
+
function hookImports() {
|
|
563
|
+
if (shared.hooked) return true;
|
|
564
|
+
if (typeof nodeModule.registerHooks !== "function") return false;
|
|
565
|
+
nodeModule.registerHooks({ resolve(specifier, context, nextResolve) {
|
|
566
|
+
let resolved;
|
|
567
|
+
try {
|
|
568
|
+
resolved = nextResolve(specifier, context);
|
|
569
|
+
} catch (error) {
|
|
570
|
+
if (error.code === "ERR_MODULE_NOT_FOUND" && /^\.\.?\//.test(specifier)) {
|
|
571
|
+
const missing = context.parentURL?.startsWith("file:") ? new URL(specifier, context.parentURL) : void 0;
|
|
572
|
+
if (missing && !missing.href.includes("/node_modules/")) recordImport(context.parentURL, fileURLToPath(missing));
|
|
573
|
+
}
|
|
574
|
+
throw error;
|
|
575
|
+
}
|
|
576
|
+
if (!context.parentURL?.includes(VERSION_PARAM) || !resolved.url.startsWith("file:")) return resolved;
|
|
577
|
+
if (resolved.url.includes("/node_modules/")) return resolved;
|
|
578
|
+
const url = new URL(resolved.url);
|
|
579
|
+
if (url.searchParams.has(VERSION_PARAM)) return resolved;
|
|
580
|
+
const imported = fileURLToPath(url);
|
|
581
|
+
if (!recordImport(context.parentURL, imported)) return resolved;
|
|
582
|
+
url.searchParams.set(VERSION_PARAM, versionOf(imported).version);
|
|
583
|
+
startEvaluation(imported, url.href);
|
|
584
|
+
return {
|
|
585
|
+
...resolved,
|
|
586
|
+
url: url.href
|
|
587
|
+
};
|
|
588
|
+
} });
|
|
589
|
+
shared.hooked = true;
|
|
590
|
+
return true;
|
|
591
|
+
}
|
|
592
|
+
function realFile(file) {
|
|
593
|
+
try {
|
|
594
|
+
return realpathSync(file);
|
|
595
|
+
} catch {
|
|
596
|
+
return file;
|
|
597
|
+
}
|
|
598
|
+
}
|
|
599
|
+
function importedBy(entries) {
|
|
600
|
+
const files = /* @__PURE__ */ new Set();
|
|
601
|
+
const pending = [...entries].flatMap((entry) => [...shared.graph.get(entry) ?? []]);
|
|
602
|
+
for (let file = pending.pop(); file !== void 0; file = pending.pop()) {
|
|
603
|
+
if (files.has(file)) continue;
|
|
604
|
+
files.add(file);
|
|
605
|
+
pending.push(...shared.graph.get(file) ?? []);
|
|
606
|
+
}
|
|
607
|
+
return [...files].filter((file) => !entries.has(file));
|
|
608
|
+
}
|
|
609
|
+
/**
|
|
610
|
+
* Imports of schema files in which a file imported by several of them, and by the same one again, is
|
|
611
|
+
* evaluated once: the versions are taken at the first import of a file and kept for the ones after it
|
|
612
|
+
*/
|
|
613
|
+
function createSchemaImports() {
|
|
614
|
+
const hooks = hookImports();
|
|
615
|
+
shared.versions.clear();
|
|
616
|
+
shared.hashes.clear();
|
|
617
|
+
const modules = /* @__PURE__ */ new Map();
|
|
618
|
+
return {
|
|
619
|
+
import(schemaPath) {
|
|
620
|
+
const file = realFile(schemaPath);
|
|
621
|
+
const known = modules.get(file);
|
|
622
|
+
if (known) return known;
|
|
623
|
+
const url = new URL(pathToFileURL(file).href);
|
|
624
|
+
url.searchParams.set(VERSION_PARAM, hooks ? versionOf(file).version : `${Date.now()}`);
|
|
625
|
+
if (hooks) startEvaluation(file, url.href);
|
|
626
|
+
const loaded = import(url.href);
|
|
627
|
+
loaded.catch(() => {
|
|
628
|
+
shared.salt = `${Date.now()}-${++counter}`;
|
|
629
|
+
});
|
|
630
|
+
modules.set(file, loaded);
|
|
631
|
+
return loaded;
|
|
632
|
+
},
|
|
633
|
+
dependencies: (schemaPath) => new Map(importedBy(new Set(schemaPath ? [realFile(schemaPath)] : modules.keys())).map((file) => [file, shared.hashes.get(file) ?? hashOfFile(file)]))
|
|
634
|
+
};
|
|
635
|
+
}
|
|
636
|
+
// src/schema-loader.ts
|
|
450
637
|
var SchemaLoader = class {
|
|
451
638
|
/**
|
|
452
639
|
* Check if a schema file exists for a table
|
|
@@ -458,13 +645,13 @@ var SchemaLoader = class {
|
|
|
458
645
|
* Load a validation schema file for a table
|
|
459
646
|
* Requires ${tableName}.schema.{ts,mts,cts} to exist in schemaDir, or alongside the JSONL file when omitted
|
|
460
647
|
*/
|
|
461
|
-
static async loadSchema(jsonlPath, schemaDir) {
|
|
648
|
+
static async loadSchema(jsonlPath, schemaDir, imports) {
|
|
462
649
|
const dir = schemaDir ?? dirname(jsonlPath);
|
|
463
650
|
const tableName = basename(jsonlPath, ".jsonl");
|
|
464
651
|
const schemaPath = await findSchemaFile(dir, tableName);
|
|
465
652
|
if (!schemaPath) throw new Error(`Schema file not found for table '${tableName}'. Expected one of: ${SCHEMA_EXTENSIONS.map((ext) => `${tableName}${ext}`).join(", ")}`);
|
|
466
653
|
try {
|
|
467
|
-
const module = await
|
|
654
|
+
const module = await (imports ?? createSchemaImports()).import(schemaPath);
|
|
468
655
|
const schema = module.default || module.schema;
|
|
469
656
|
if (schema && this.isStandardSchema(schema)) return schema;
|
|
470
657
|
throw new Error(`Schema file ${schemaPath} does not export a valid StandardSchema`);
|
|
@@ -483,8 +670,7 @@ var SchemaLoader = class {
|
|
|
483
670
|
return standardObj.version === 1 && typeof standardObj.vendor === "string" && typeof standardObj.validate === "function";
|
|
484
671
|
}
|
|
485
672
|
};
|
|
486
|
-
|
|
487
|
-
//#region src/directory-scanner.ts
|
|
673
|
+
// src/directory-scanner.ts
|
|
488
674
|
var DirectoryScanner = class {
|
|
489
675
|
/**
|
|
490
676
|
* Scan directories for JSONL files and create table configurations.
|
|
@@ -517,16 +703,14 @@ var DirectoryScanner = class {
|
|
|
517
703
|
return tables;
|
|
518
704
|
}
|
|
519
705
|
};
|
|
520
|
-
|
|
521
|
-
//#region src/schema.ts
|
|
706
|
+
// src/schema.ts
|
|
522
707
|
/**
|
|
523
708
|
* Check if a schema has backward transformation
|
|
524
709
|
*/
|
|
525
710
|
function hasBackward(schema) {
|
|
526
711
|
return "backward" in schema && typeof schema.backward === "function";
|
|
527
712
|
}
|
|
528
|
-
|
|
529
|
-
//#region src/merge-fields.ts
|
|
713
|
+
// src/merge-fields.ts
|
|
530
714
|
/**
|
|
531
715
|
* Lay the named fields of a computed row over the line a JSONL file already holds.
|
|
532
716
|
*
|
|
@@ -579,8 +763,7 @@ function keepUnknownFields(line, row, columns) {
|
|
|
579
763
|
for (const key of Object.keys(row)) if (!Object.hasOwn(line, key)) entries.push([key, row[key]]);
|
|
580
764
|
return Object.fromEntries(entries);
|
|
581
765
|
}
|
|
582
|
-
|
|
583
|
-
//#region src/sql-statements.ts
|
|
766
|
+
// src/sql-statements.ts
|
|
584
767
|
const TRIGGER_DEFINITION = /^\s*CREATE\s+(?:TEMP(?:ORARY)?\s+)?TRIGGER\b/i;
|
|
585
768
|
const CLOSER = {
|
|
586
769
|
"'": "'",
|
|
@@ -686,8 +869,7 @@ function isReadOnlyStatement(statement) {
|
|
|
686
869
|
if (READ_PRAGMAS_WITH_ARGUMENT.has(name)) return true;
|
|
687
870
|
return READ_PRAGMAS_BARE.has(name) && argument === void 0;
|
|
688
871
|
}
|
|
689
|
-
|
|
690
|
-
//#region src/database.ts
|
|
872
|
+
// src/database.ts
|
|
691
873
|
function cloneFieldChanges(changes) {
|
|
692
874
|
return new Map(Array.from(changes, ([tableName, byRow]) => [tableName, new Map(Array.from(byRow, ([rowid, row]) => [rowid, {
|
|
693
875
|
set: new Set(row.set),
|
|
@@ -724,6 +906,7 @@ var LinesDB = class LinesDB {
|
|
|
724
906
|
* holds the fields a user wrote, so only what changed since it was written needs remembering
|
|
725
907
|
*/
|
|
726
908
|
fieldChanges = /* @__PURE__ */ new Map();
|
|
909
|
+
settleUndos;
|
|
727
910
|
/**
|
|
728
911
|
* The tables raw SQL may have changed since they were last written back: which fields it set is
|
|
729
912
|
* unknown, so their rows are written back whole
|
|
@@ -755,8 +938,14 @@ var LinesDB = class LinesDB {
|
|
|
755
938
|
observedHashes = /* @__PURE__ */ new Map();
|
|
756
939
|
/** The JSONL files the data directories held when the tables were scanned */
|
|
757
940
|
scannedJsonlFiles = [];
|
|
941
|
+
/** Tables left out because their files have no rows to infer the columns from */
|
|
942
|
+
emptyTables = /* @__PURE__ */ new Set();
|
|
943
|
+
/** Tables created from the columns `schemaOfEmptyTable` gave, which may lack a field the validator adds */
|
|
944
|
+
tablesFromGivenColumns = /* @__PURE__ */ new Set();
|
|
758
945
|
/** Each table's schema file and a hash of its content as the tables were loaded, or '' for none */
|
|
759
946
|
schemaFileStates = /* @__PURE__ */ new Map();
|
|
947
|
+
schemaImports;
|
|
948
|
+
schemaDependencyHashes = /* @__PURE__ */ new Map();
|
|
760
949
|
constructor(config, dbPath) {
|
|
761
950
|
this.config = config;
|
|
762
951
|
this.db = createDatabase(dbPath ?? ":memory:");
|
|
@@ -796,12 +985,14 @@ var LinesDB = class LinesDB {
|
|
|
796
985
|
const tableName = options?.tableName;
|
|
797
986
|
const detailedValidate = options?.detailedValidate ?? false;
|
|
798
987
|
const transform = options?.transform;
|
|
988
|
+
this.emptyTables.clear();
|
|
799
989
|
this.tables = await DirectoryScanner.scanDirectory(this.config.dataDir);
|
|
800
990
|
this.scannedJsonlFiles = listJsonlFiles(this.tables);
|
|
801
991
|
this.observedHashes.clear();
|
|
802
992
|
this.schemaFileStates.clear();
|
|
803
993
|
for (const [name, config] of this.tables) this.schemaFileStates.set(name, await this.schemaFileState(name, config));
|
|
804
994
|
const tablesToLoad = tableName ? [tableName] : Array.from(this.tables.keys());
|
|
995
|
+
for (const name of tablesToLoad) this.tablesFromGivenColumns.delete(name);
|
|
805
996
|
for (const tableNameToLoad of tablesToLoad) if (!this.tables.has(tableNameToLoad)) {
|
|
806
997
|
const dataDirs = [this.config.dataDir].flat().map((dir) => `'${dir}'`);
|
|
807
998
|
throw new Error(`Table '${tableNameToLoad}' not found in directory ${dataDirs.join(", ")}`);
|
|
@@ -810,13 +1001,25 @@ var LinesDB = class LinesDB {
|
|
|
810
1001
|
const loadingTables = /* @__PURE__ */ new Set();
|
|
811
1002
|
const attemptedTables = /* @__PURE__ */ new Set();
|
|
812
1003
|
const allDeferredForeignKeys = [];
|
|
813
|
-
|
|
814
|
-
|
|
815
|
-
|
|
816
|
-
|
|
817
|
-
|
|
818
|
-
|
|
819
|
-
|
|
1004
|
+
const imports = createSchemaImports();
|
|
1005
|
+
this.schemaImports = imports;
|
|
1006
|
+
const schemaPaths = /* @__PURE__ */ new Map();
|
|
1007
|
+
for (const [name, config] of this.tables) {
|
|
1008
|
+
const schemaPath = await this.findTableSchemaFile(name, config);
|
|
1009
|
+
if (schemaPath) schemaPaths.set(name, schemaPath);
|
|
1010
|
+
}
|
|
1011
|
+
try {
|
|
1012
|
+
for (const tableNameToLoad of tablesToLoad) if (!attemptedTables.has(tableNameToLoad)) {
|
|
1013
|
+
const tableTransform = tableNameToLoad === tableName ? transform : void 0;
|
|
1014
|
+
const { errors, warnings, rowCounts: tableRowCounts, deferredForeignKeys } = await this.loadTableWithDependencies(tableNameToLoad, loadedTables, loadingTables, attemptedTables, detailedValidate, tableTransform);
|
|
1015
|
+
allErrors.push(...errors);
|
|
1016
|
+
allWarnings.push(...warnings);
|
|
1017
|
+
allDeferredForeignKeys.push(...deferredForeignKeys);
|
|
1018
|
+
for (const [k, v] of tableRowCounts) allRowCounts.set(k, v);
|
|
1019
|
+
}
|
|
1020
|
+
} finally {
|
|
1021
|
+
this.schemaImports = void 0;
|
|
1022
|
+
this.recordSchemaDependencies(imports, attemptedTables, schemaPaths, tableName === void 0);
|
|
820
1023
|
}
|
|
821
1024
|
if (detailedValidate && allDeferredForeignKeys.length > 0) for (const { tableName: tName, foreignKey: fk, filePath } of allDeferredForeignKeys) {
|
|
822
1025
|
if (!loadedTables.has(fk.references.table)) continue;
|
|
@@ -841,6 +1044,9 @@ var LinesDB = class LinesDB {
|
|
|
841
1044
|
tableResults
|
|
842
1045
|
};
|
|
843
1046
|
}
|
|
1047
|
+
importSchemaModule(schemaPath) {
|
|
1048
|
+
return (this.schemaImports ?? createSchemaImports()).import(schemaPath);
|
|
1049
|
+
}
|
|
844
1050
|
/**
|
|
845
1051
|
* Load a table and its dependencies recursively
|
|
846
1052
|
*/
|
|
@@ -863,10 +1069,9 @@ var LinesDB = class LinesDB {
|
|
|
863
1069
|
try {
|
|
864
1070
|
let foreignKeys;
|
|
865
1071
|
try {
|
|
866
|
-
const { pathToFileURL } = await import("node:url");
|
|
867
1072
|
const schemaPath = await this.findTableSchemaFile(tableName, tableConfig);
|
|
868
1073
|
if (schemaPath) {
|
|
869
|
-
const schemaModule = await
|
|
1074
|
+
const schemaModule = await this.importSchemaModule(schemaPath);
|
|
870
1075
|
foreignKeys = (schemaModule.schema || schemaModule.default)?.foreignKeys || schemaModule.foreignKeys;
|
|
871
1076
|
}
|
|
872
1077
|
} catch {}
|
|
@@ -894,7 +1099,10 @@ var LinesDB = class LinesDB {
|
|
|
894
1099
|
else failedDependencies.add(referencedTable);
|
|
895
1100
|
}
|
|
896
1101
|
}
|
|
897
|
-
if (failedDependencies.size > 0) for (const dep of failedDependencies)
|
|
1102
|
+
if (failedDependencies.size > 0) for (const dep of failedDependencies) {
|
|
1103
|
+
const reason = this.emptyTables.has(dep) ? "has no rows to read its columns from" : "has validation errors";
|
|
1104
|
+
warnings.push(`Skipping foreign key validation for table '${tableName}': referenced table '${dep}' ${reason}`);
|
|
1105
|
+
}
|
|
898
1106
|
}
|
|
899
1107
|
const allSkippedDependencies = /* @__PURE__ */ new Set([...failedDependencies, ...circularDependencies]);
|
|
900
1108
|
const { loaded, rowCount, errors: loadErrors } = await this.loadTable(tableName, tableConfig, detailedValidate, transform, allSkippedDependencies);
|
|
@@ -910,6 +1118,7 @@ var LinesDB = class LinesDB {
|
|
|
910
1118
|
});
|
|
911
1119
|
}
|
|
912
1120
|
} else {
|
|
1121
|
+
if (rowCount === 0 && loadErrors.length === 0) this.emptyTables.add(tableName);
|
|
913
1122
|
warnings.push(`Table '${tableName}' was not loaded (no data or skipped)`);
|
|
914
1123
|
this.tables.delete(tableName);
|
|
915
1124
|
}
|
|
@@ -963,11 +1172,10 @@ var LinesDB = class LinesDB {
|
|
|
963
1172
|
let validationSchema = config.validationSchema;
|
|
964
1173
|
const schemaMetadata = {};
|
|
965
1174
|
const schemaPath = config.validationSchema ? void 0 : await this.findTableSchemaFile(tableName, config);
|
|
966
|
-
if (!validationSchema && schemaPath) validationSchema = await SchemaLoader.loadSchema(config.jsonlPath, dirname(schemaPath));
|
|
1175
|
+
if (!validationSchema && schemaPath) validationSchema = await SchemaLoader.loadSchema(config.jsonlPath, dirname(schemaPath), this.schemaImports);
|
|
967
1176
|
if (!config.validationSchema) try {
|
|
968
|
-
const { pathToFileURL } = await import("node:url");
|
|
969
1177
|
if (!schemaPath) throw new Error("Schema file not found");
|
|
970
|
-
const schemaModule = await
|
|
1178
|
+
const schemaModule = await this.importSchemaModule(schemaPath);
|
|
971
1179
|
const schemaExport = schemaModule.schema || schemaModule.default;
|
|
972
1180
|
if (schemaExport?.primaryKey) schemaMetadata.primaryKey = schemaExport.primaryKey;
|
|
973
1181
|
else if (schemaModule.primaryKey) schemaMetadata.primaryKey = schemaModule.primaryKey;
|
|
@@ -1024,12 +1232,23 @@ var LinesDB = class LinesDB {
|
|
|
1024
1232
|
if (schemaCol && inferredCol.valueType && !schemaCol.valueType) schemaCol.valueType = inferredCol.valueType;
|
|
1025
1233
|
}
|
|
1026
1234
|
} else if (config.autoInferSchema !== false) {
|
|
1027
|
-
if (validatedData.length === 0)
|
|
1028
|
-
|
|
1029
|
-
|
|
1030
|
-
|
|
1031
|
-
|
|
1032
|
-
|
|
1235
|
+
if (validatedData.length === 0) {
|
|
1236
|
+
const declared = await this.config.schemaOfEmptyTable?.({
|
|
1237
|
+
tableName,
|
|
1238
|
+
schemaPath
|
|
1239
|
+
});
|
|
1240
|
+
if (!declared || declared.columns.length === 0) return {
|
|
1241
|
+
loaded: false,
|
|
1242
|
+
rowCount: 0,
|
|
1243
|
+
errors: []
|
|
1244
|
+
};
|
|
1245
|
+
schema = {
|
|
1246
|
+
...declared,
|
|
1247
|
+
name: tableName,
|
|
1248
|
+
columns: declared.columns.map((column) => ({ ...column }))
|
|
1249
|
+
};
|
|
1250
|
+
this.tablesFromGivenColumns.add(tableName);
|
|
1251
|
+
} else schema = inferredSchema;
|
|
1033
1252
|
} else throw new Error(`No schema provided for table ${tableName} and autoInferSchema is disabled`);
|
|
1034
1253
|
const biSchema = validationSchema;
|
|
1035
1254
|
const primaryKey = biSchema?.primaryKey || schemaMetadata.primaryKey;
|
|
@@ -1053,6 +1272,7 @@ var LinesDB = class LinesDB {
|
|
|
1053
1272
|
if (col && !col.unique && !col.primaryKey) col.unique = true;
|
|
1054
1273
|
}
|
|
1055
1274
|
}
|
|
1275
|
+
if (schema === inferredSchema) this.relaxColumnsTheSchemaLeavesOptional(tableName, schema, data[0]);
|
|
1056
1276
|
this.schemas.set(tableName, schema);
|
|
1057
1277
|
this.createTable(schema);
|
|
1058
1278
|
if (detailedValidate || this.config.writeDataSets) {
|
|
@@ -1089,6 +1309,55 @@ var LinesDB = class LinesDB {
|
|
|
1089
1309
|
};
|
|
1090
1310
|
}
|
|
1091
1311
|
/**
|
|
1312
|
+
* A column no row holds a value in has no type to read a boolean or an object back with, and so reads
|
|
1313
|
+
* back as 1 or as JSON text. The first value written settles it, and a string settles it as text so an
|
|
1314
|
+
* object written later does not turn that text into JSON. Not asked of the schema: it names no type at
|
|
1315
|
+
* run time. Returns what puts the columns back, which a write that did not go in, or a transaction that
|
|
1316
|
+
* rolled back, must call: the value that settled it is not in the table
|
|
1317
|
+
*/
|
|
1318
|
+
settleColumnsNoRowHolds(schema, written) {
|
|
1319
|
+
const before = [];
|
|
1320
|
+
for (const column of schema?.columns ?? []) {
|
|
1321
|
+
const value = written[column.name];
|
|
1322
|
+
if (column.type !== "NULL" || value === null || value === void 0) continue;
|
|
1323
|
+
before.push([
|
|
1324
|
+
column,
|
|
1325
|
+
column.type,
|
|
1326
|
+
column.valueType
|
|
1327
|
+
]);
|
|
1328
|
+
if (typeof value === "boolean") {
|
|
1329
|
+
column.type = "INTEGER";
|
|
1330
|
+
column.valueType = "boolean";
|
|
1331
|
+
} else if (typeof value === "string") column.type = "TEXT";
|
|
1332
|
+
else if (typeof value === "number") column.type = Number.isInteger(value) ? "INTEGER" : "REAL";
|
|
1333
|
+
else if (typeof value === "object" && !(value instanceof Uint8Array)) column.type = "JSON";
|
|
1334
|
+
else before.pop();
|
|
1335
|
+
}
|
|
1336
|
+
const undo = () => {
|
|
1337
|
+
for (const [column, type, valueType] of before) {
|
|
1338
|
+
column.type = type;
|
|
1339
|
+
column.valueType = valueType;
|
|
1340
|
+
}
|
|
1341
|
+
};
|
|
1342
|
+
this.settleUndos?.push(undo);
|
|
1343
|
+
return undo;
|
|
1344
|
+
}
|
|
1345
|
+
/**
|
|
1346
|
+
* A column every row holds is inferred NOT NULL, which refuses a later row that leaves it out even
|
|
1347
|
+
* where the schema takes that row. The sample row without the field says whether the schema does.
|
|
1348
|
+
* A column the schema fills in stays NOT NULL: the row is stored as the schema leaves it
|
|
1349
|
+
*/
|
|
1350
|
+
relaxColumnsTheSchemaLeavesOptional(tableName, schema, sample) {
|
|
1351
|
+
if (!sample || !this.validationSchemas.get(tableName)) return;
|
|
1352
|
+
for (const column of schema.columns) {
|
|
1353
|
+
if (!column.notNull || column.primaryKey || !(column.name in sample)) continue;
|
|
1354
|
+
const { [column.name]: _left, ...without } = sample;
|
|
1355
|
+
try {
|
|
1356
|
+
if ((this.validateAndTransform(tableName, without)[column.name] ?? null) === null) column.notNull = false;
|
|
1357
|
+
} catch {}
|
|
1358
|
+
}
|
|
1359
|
+
}
|
|
1360
|
+
/**
|
|
1092
1361
|
* Create table in SQLite with constraints and indexes
|
|
1093
1362
|
*/
|
|
1094
1363
|
createTable(schema) {
|
|
@@ -1154,6 +1423,7 @@ var LinesDB = class LinesDB {
|
|
|
1154
1423
|
if (data.length === 0) return;
|
|
1155
1424
|
const columnNames = schema.columns.map((col) => col.name);
|
|
1156
1425
|
const quotedColumns = columnNames.map((name) => this.quoteIdentifier(name));
|
|
1426
|
+
const columnsByName = new Map(schema.columns.map((column) => [column.name, column]));
|
|
1157
1427
|
const columnCount = columnNames.length;
|
|
1158
1428
|
const maxBatchSize = Math.floor(900 / columnCount);
|
|
1159
1429
|
const batchSize = Math.max(1, Math.min(maxBatchSize, 100));
|
|
@@ -1163,7 +1433,7 @@ var LinesDB = class LinesDB {
|
|
|
1163
1433
|
const valuesPlaceholders = batch.map(() => `(${rowPlaceholders})`).join(", ");
|
|
1164
1434
|
const sql = `INSERT INTO ${this.quoteTableName(tableName)} (${quotedColumns.join(", ")}) VALUES ${valuesPlaceholders}`;
|
|
1165
1435
|
const values = [];
|
|
1166
|
-
for (const row of batch) for (const col of columnNames) values.push(this.normalizeValue(row[col]));
|
|
1436
|
+
for (const row of batch) for (const col of columnNames) values.push(this.normalizeValue(row[col], columnsByName.get(col)));
|
|
1167
1437
|
this.db.prepare(sql).run(...values);
|
|
1168
1438
|
}
|
|
1169
1439
|
}
|
|
@@ -1177,13 +1447,14 @@ var LinesDB = class LinesDB {
|
|
|
1177
1447
|
const quotedColumns = columnNames.map((name) => this.quoteIdentifier(name));
|
|
1178
1448
|
const placeholders = columnNames.map(() => "?").join(", ");
|
|
1179
1449
|
const sql = `INSERT INTO ${this.quoteTableName(tableName)} (${quotedColumns.join(", ")}) VALUES (${placeholders})`;
|
|
1450
|
+
const columnsByName = new Map(schema.columns.map((column) => [column.name, column]));
|
|
1180
1451
|
const stmt = this.db.prepare(sql);
|
|
1181
1452
|
const rowOrigins = /* @__PURE__ */ new Map();
|
|
1182
1453
|
this.rowOriginsByRowid.set(tableName, rowOrigins);
|
|
1183
1454
|
for (let rowIndex = 0; rowIndex < data.length; rowIndex++) {
|
|
1184
1455
|
const row = data[rowIndex];
|
|
1185
1456
|
try {
|
|
1186
|
-
const values = columnNames.map((col) => this.normalizeValue(row[col]));
|
|
1457
|
+
const values = columnNames.map((col) => this.normalizeValue(row[col], columnsByName.get(col)));
|
|
1187
1458
|
const { lastInsertRowid } = stmt.run(...values);
|
|
1188
1459
|
rowOrigins.set(String(lastInsertRowid), origins[rowIndex]);
|
|
1189
1460
|
} catch (error) {
|
|
@@ -1202,7 +1473,7 @@ var LinesDB = class LinesDB {
|
|
|
1202
1473
|
const fkValue = row[fk.column];
|
|
1203
1474
|
if (fkValue === null || fkValue === void 0) continue;
|
|
1204
1475
|
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)]);
|
|
1476
|
+
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
1477
|
if (result.length > 0 && result[0].count === 0) return {
|
|
1207
1478
|
file,
|
|
1208
1479
|
tableName,
|
|
@@ -1350,7 +1621,7 @@ var LinesDB = class LinesDB {
|
|
|
1350
1621
|
findInternal(tableName, where) {
|
|
1351
1622
|
if (where === void 0) return this.queryInternal(`SELECT * FROM ${this.quoteTableName(tableName)}`).map((row) => this.deserializeRow(tableName, row));
|
|
1352
1623
|
if (Array.isArray(where) && where.length === 0) return [];
|
|
1353
|
-
const { sql, values, functionFilters, hasOrWithFunctionFilters } = this.buildWhereClause(where);
|
|
1624
|
+
const { sql, values, functionFilters, hasOrWithFunctionFilters } = this.buildWhereClause(where, tableName);
|
|
1354
1625
|
let rows;
|
|
1355
1626
|
if (hasOrWithFunctionFilters) {
|
|
1356
1627
|
rows = this.queryInternal(`SELECT * FROM ${this.quoteTableName(tableName)}`).map((row) => this.deserializeRow(tableName, row));
|
|
@@ -1371,7 +1642,7 @@ var LinesDB = class LinesDB {
|
|
|
1371
1642
|
}
|
|
1372
1643
|
}
|
|
1373
1644
|
findOneInternal(tableName, where) {
|
|
1374
|
-
const { sql, values, functionFilters } = this.buildWhereClause(where);
|
|
1645
|
+
const { sql, values, functionFilters } = this.buildWhereClause(where, tableName);
|
|
1375
1646
|
let rows;
|
|
1376
1647
|
if (sql) rows = this.queryInternal(`SELECT * FROM ${this.quoteTableName(tableName)} WHERE ${sql}`, values).map((row) => this.deserializeRow(tableName, row));
|
|
1377
1648
|
else rows = this.queryInternal(`SELECT * FROM ${this.quoteTableName(tableName)}`).map((row) => this.deserializeRow(tableName, row));
|
|
@@ -1468,13 +1739,22 @@ var LinesDB = class LinesDB {
|
|
|
1468
1739
|
destination = join([this.config.dataDir].flat().find((dir) => resolve(dir) === resolve(dataDir)), `${tableName}.jsonl`);
|
|
1469
1740
|
}
|
|
1470
1741
|
const row = this.validateAndTransform(tableName, data);
|
|
1471
|
-
|
|
1742
|
+
const schema = this.schemas.get(tableName);
|
|
1743
|
+
if (!schema) throw new Error(`Table ${tableName} does not exist`);
|
|
1744
|
+
this.addMissingColumns(tableName, schema, row);
|
|
1472
1745
|
const columnNames = Object.keys(row);
|
|
1473
1746
|
const quotedColumns = columnNames.map((col) => this.quoteIdentifier(col));
|
|
1474
1747
|
const placeholders = columnNames.map(() => "?").join(", ");
|
|
1475
1748
|
const sql = `INSERT INTO ${this.quoteTableName(tableName)} (${quotedColumns.join(", ")}) VALUES (${placeholders})`;
|
|
1476
|
-
const values =
|
|
1477
|
-
const
|
|
1749
|
+
const values = columnNames.map((col) => this.normalizeValue(row[col], this.columnOf(tableName, col)));
|
|
1750
|
+
const undoSettle = this.settleColumnsNoRowHolds(schema, row);
|
|
1751
|
+
let result;
|
|
1752
|
+
try {
|
|
1753
|
+
result = this.executeInternal(sql, values);
|
|
1754
|
+
} catch (error) {
|
|
1755
|
+
undoSettle();
|
|
1756
|
+
throw error;
|
|
1757
|
+
}
|
|
1478
1758
|
if (destination) {
|
|
1479
1759
|
const origins = this.rowOriginsByRowid.get(tableName) ?? /* @__PURE__ */ new Map();
|
|
1480
1760
|
origins.set(String(result.lastInsertRowid), {
|
|
@@ -1491,6 +1771,27 @@ var LinesDB = class LinesDB {
|
|
|
1491
1771
|
return result;
|
|
1492
1772
|
}
|
|
1493
1773
|
/**
|
|
1774
|
+
* A table made from the columns given has only those, and the validator may add a field they lack: the
|
|
1775
|
+
* columns of a table made from rows are those of the validated rows, which have it
|
|
1776
|
+
*/
|
|
1777
|
+
addMissingColumns(tableName, schema, row) {
|
|
1778
|
+
if (!this.tablesFromGivenColumns.has(tableName)) return;
|
|
1779
|
+
const known = new Set(schema.columns.map((column) => column.name));
|
|
1780
|
+
const missing = Object.keys(row).filter((key) => !known.has(key));
|
|
1781
|
+
if (missing.length === 0) return;
|
|
1782
|
+
for (const column of unwrap(JsonlReader.inferSchema(tableName, [row])).columns) {
|
|
1783
|
+
if (!missing.includes(column.name)) continue;
|
|
1784
|
+
const sqlType = column.type === "JSON" ? "TEXT" : column.type;
|
|
1785
|
+
this.db.exec(`ALTER TABLE ${this.quoteTableName(tableName)} ADD COLUMN ${this.quoteIdentifier(column.name)} ${sqlType}`);
|
|
1786
|
+
schema.columns.push({
|
|
1787
|
+
name: column.name,
|
|
1788
|
+
type: column.type,
|
|
1789
|
+
notNull: false,
|
|
1790
|
+
valueType: column.valueType
|
|
1791
|
+
});
|
|
1792
|
+
}
|
|
1793
|
+
}
|
|
1794
|
+
/**
|
|
1494
1795
|
* Batch insert rows with validation per record.
|
|
1495
1796
|
*/
|
|
1496
1797
|
batchInsert(tableName, records) {
|
|
@@ -1503,7 +1804,8 @@ var LinesDB = class LinesDB {
|
|
|
1503
1804
|
batchInsertInternal(tableName, records) {
|
|
1504
1805
|
this.assertMutable(tableName);
|
|
1505
1806
|
if (this.hasSeveralDataDirs()) throw new Error("Use insert with a dataDir for data sets");
|
|
1506
|
-
|
|
1807
|
+
const schema = this.schemas.get(tableName);
|
|
1808
|
+
if (!schema) throw new Error(`Table ${tableName} does not exist`);
|
|
1507
1809
|
if (records.length === 0) return {
|
|
1508
1810
|
changes: 0,
|
|
1509
1811
|
lastInsertRowid: 0
|
|
@@ -1513,12 +1815,20 @@ var LinesDB = class LinesDB {
|
|
|
1513
1815
|
try {
|
|
1514
1816
|
for (const record of records) {
|
|
1515
1817
|
const row = this.validateAndTransform(tableName, record);
|
|
1818
|
+
this.addMissingColumns(tableName, schema, row);
|
|
1516
1819
|
const columnNames = Object.keys(row);
|
|
1517
1820
|
const quotedColumns = columnNames.map((col) => this.quoteIdentifier(col));
|
|
1518
1821
|
const placeholders = columnNames.map(() => "?").join(", ");
|
|
1519
1822
|
const sql = `INSERT INTO ${this.quoteTableName(tableName)} (${quotedColumns.join(", ")}) VALUES (${placeholders})`;
|
|
1520
|
-
const values = columnNames.map((col) => this.normalizeValue(row[col]));
|
|
1521
|
-
const
|
|
1823
|
+
const values = columnNames.map((col) => this.normalizeValue(row[col], this.columnOf(tableName, col)));
|
|
1824
|
+
const undoSettle = this.settleColumnsNoRowHolds(this.schemas.get(tableName), row);
|
|
1825
|
+
let result;
|
|
1826
|
+
try {
|
|
1827
|
+
result = this.executeInternal(sql, values);
|
|
1828
|
+
} catch (error) {
|
|
1829
|
+
undoSettle();
|
|
1830
|
+
throw error;
|
|
1831
|
+
}
|
|
1522
1832
|
this.noteFieldChanges(tableName, result.lastInsertRowid, {
|
|
1523
1833
|
set: givenFields(record),
|
|
1524
1834
|
inserted: true
|
|
@@ -1563,7 +1873,7 @@ var LinesDB = class LinesDB {
|
|
|
1563
1873
|
this.validateData(tableName, mergedData);
|
|
1564
1874
|
}
|
|
1565
1875
|
}
|
|
1566
|
-
const { sql: whereSql, values: whereValues, functionFilters } = this.buildWhereClause(where);
|
|
1876
|
+
const { sql: whereSql, values: whereValues, functionFilters } = this.buildWhereClause(where, tableName);
|
|
1567
1877
|
if (functionFilters.length > 0) throw new Error("Function filters are not supported in update operations");
|
|
1568
1878
|
const targets = this.queryInternal(`SELECT rowid AS "${ROWID_ALIAS}", * FROM ${this.quoteTableName(tableName)} WHERE ${whereSql}`, whereValues);
|
|
1569
1879
|
const resetFields = options?.resetToDefault ?? [];
|
|
@@ -1575,12 +1885,19 @@ var LinesDB = class LinesDB {
|
|
|
1575
1885
|
if (Object.keys(data).length > 0) {
|
|
1576
1886
|
const setClauses = Object.keys(data).map((key) => `${this.quoteIdentifier(key)} = ?`).join(", ");
|
|
1577
1887
|
const sql = `UPDATE ${this.quoteTableName(tableName)} SET ${setClauses} WHERE ${whereSql}`;
|
|
1578
|
-
const values = [...Object.
|
|
1579
|
-
|
|
1888
|
+
const values = [...Object.entries(data).map(([key, v]) => this.normalizeValue(v, this.columnOf(tableName, key))), ...whereValues];
|
|
1889
|
+
const undoSettle = this.settleColumnsNoRowHolds(this.schemas.get(tableName), data);
|
|
1890
|
+
try {
|
|
1891
|
+
result = this.executeInternal(sql, values);
|
|
1892
|
+
} catch (error) {
|
|
1893
|
+
undoSettle();
|
|
1894
|
+
throw error;
|
|
1895
|
+
}
|
|
1896
|
+
if (Number(result.changes) === 0) undoSettle();
|
|
1580
1897
|
}
|
|
1581
1898
|
const pkName = this.schemas.get(tableName)?.columns.find((col) => col.primaryKey)?.name;
|
|
1582
1899
|
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])]);
|
|
1900
|
+
const moved = this.queryInternal(`SELECT rowid AS "${ROWID_ALIAS}" FROM ${this.quoteTableName(tableName)} WHERE ${this.quoteIdentifier(pkName)} = ?`, [this.normalizeValue(data[pkName], this.columnOf(tableName, pkName))]);
|
|
1584
1901
|
if (targets.length === 1 && moved.length === 1) {
|
|
1585
1902
|
const from = String(targets[0][ROWID_ALIAS]);
|
|
1586
1903
|
const to = moved[0][ROWID_ALIAS];
|
|
@@ -1594,7 +1911,7 @@ var LinesDB = class LinesDB {
|
|
|
1594
1911
|
}
|
|
1595
1912
|
}
|
|
1596
1913
|
for (const target of targets) {
|
|
1597
|
-
const set = Object.keys(data).filter((key) => !sameStoredValue(target[key], this.normalizeValue(data[key])));
|
|
1914
|
+
const set = Object.keys(data).filter((key) => !sameStoredValue(target[key], this.normalizeValue(data[key], this.columnOf(tableName, key))));
|
|
1598
1915
|
this.noteFieldChanges(tableName, target[ROWID_ALIAS], { set });
|
|
1599
1916
|
}
|
|
1600
1917
|
if (resets.length > 0) result = this.applyResets(tableName, resets, resetFields);
|
|
@@ -1698,7 +2015,7 @@ var LinesDB = class LinesDB {
|
|
|
1698
2015
|
deleteInternal(tableName, where) {
|
|
1699
2016
|
this.assertMutable(tableName);
|
|
1700
2017
|
if (!this.schemas.get(tableName)) throw new Error(`Table ${tableName} does not exist`);
|
|
1701
|
-
const { sql: whereSql, values, functionFilters } = this.buildWhereClause(where);
|
|
2018
|
+
const { sql: whereSql, values, functionFilters } = this.buildWhereClause(where, tableName);
|
|
1702
2019
|
if (functionFilters.length > 0) throw new Error("Function filters are not supported in delete operations");
|
|
1703
2020
|
const deleted = this.rowidsWhere(tableName, whereSql, values);
|
|
1704
2021
|
const sql = `DELETE FROM ${this.quoteTableName(tableName)} WHERE ${whereSql}`;
|
|
@@ -1735,7 +2052,7 @@ var LinesDB = class LinesDB {
|
|
|
1735
2052
|
});
|
|
1736
2053
|
const placeholders = pkValues.map(() => "?").join(", ");
|
|
1737
2054
|
const sql = `DELETE FROM ${this.quoteTableName(tableName)} WHERE ${this.quoteIdentifier(pkName)} IN (${placeholders})`;
|
|
1738
|
-
const values = pkValues.map((value) => this.normalizeValue(value));
|
|
2055
|
+
const values = pkValues.map((value) => this.normalizeValue(value, this.columnOf(tableName, pkName)));
|
|
1739
2056
|
const deleted = this.rowidsWhere(tableName, `${this.quoteIdentifier(pkName)} IN (${placeholders})`, values);
|
|
1740
2057
|
const result = this.executeInternal(sql, values);
|
|
1741
2058
|
this.forgetFieldChanges(tableName, deleted);
|
|
@@ -1748,17 +2065,24 @@ var LinesDB = class LinesDB {
|
|
|
1748
2065
|
/**
|
|
1749
2066
|
* Normalize value for SQLite
|
|
1750
2067
|
*/
|
|
1751
|
-
normalizeValue(value) {
|
|
2068
|
+
normalizeValue(value, column) {
|
|
1752
2069
|
if (value === null || value === void 0) return null;
|
|
2070
|
+
if (column?.type === "JSON") {
|
|
2071
|
+
if (value instanceof Uint8Array) return value;
|
|
2072
|
+
return typeof value === "bigint" ? value.toString() : JSON.stringify(value);
|
|
2073
|
+
}
|
|
1753
2074
|
if (typeof value === "boolean") return value ? 1 : 0;
|
|
1754
2075
|
if (typeof value === "string" || typeof value === "number" || typeof value === "bigint") return value;
|
|
1755
2076
|
if (value instanceof Uint8Array) return value;
|
|
1756
2077
|
return JSON.stringify(value);
|
|
1757
2078
|
}
|
|
2079
|
+
columnOf(tableName, columnName) {
|
|
2080
|
+
return this.schemas.get(tableName)?.columns.find((column) => column.name === columnName);
|
|
2081
|
+
}
|
|
1758
2082
|
/**
|
|
1759
2083
|
* Build WHERE clause from condition (supports OR/AND with arrays and functions)
|
|
1760
2084
|
*/
|
|
1761
|
-
buildWhereClause(condition) {
|
|
2085
|
+
buildWhereClause(condition, tableName) {
|
|
1762
2086
|
const values = [];
|
|
1763
2087
|
const functionFilters = [];
|
|
1764
2088
|
let hasOrWithFunctionFilters = false;
|
|
@@ -1777,7 +2101,7 @@ var LinesDB = class LinesDB {
|
|
|
1777
2101
|
hasFunctionFilter = true;
|
|
1778
2102
|
} else {
|
|
1779
2103
|
conditions.push(`${this.quoteIdentifier(key)} = ?`);
|
|
1780
|
-
values.push(this.normalizeValue(value));
|
|
2104
|
+
values.push(this.normalizeValue(value, this.columnOf(tableName, key)));
|
|
1781
2105
|
}
|
|
1782
2106
|
if (isInOr && hasFunctionFilter) hasOrWithFunctionFilters = true;
|
|
1783
2107
|
return conditions.join(" AND ");
|
|
@@ -2042,8 +2366,9 @@ var LinesDB = class LinesDB {
|
|
|
2042
2366
|
for (const key of rowChanges?.reset ?? []) keep.delete(key);
|
|
2043
2367
|
for (const key of namedFields) keep.add(key);
|
|
2044
2368
|
if (pkName) keep.add(pkName);
|
|
2369
|
+
const untouched = line !== void 0 && !rowChanges?.inserted && !rowChanges?.set.size && !rowChanges?.reset.size;
|
|
2045
2370
|
return {
|
|
2046
|
-
written: Object.fromEntries(Object.entries(lineRow).filter(([key]) => keep.has(key))),
|
|
2371
|
+
written: Object.fromEntries(Object.entries(lineRow).filter(([key]) => keep.has(key)).map(([key, value]) => [key, untouched && Object.hasOwn(line, key) && !actionColumns.includes(key) && !namedFields.includes(key) ? line[key] : value])),
|
|
2047
2372
|
narrowed: true
|
|
2048
2373
|
};
|
|
2049
2374
|
});
|
|
@@ -2127,7 +2452,7 @@ var LinesDB = class LinesDB {
|
|
|
2127
2452
|
const validated = this.validateAndTransform(tableName, row);
|
|
2128
2453
|
return {
|
|
2129
2454
|
rowid,
|
|
2130
|
-
values: fields.map((field) => this.normalizeValue(validated[field]))
|
|
2455
|
+
values: fields.map((field) => this.normalizeValue(validated[field], this.columnOf(tableName, field)))
|
|
2131
2456
|
};
|
|
2132
2457
|
});
|
|
2133
2458
|
}
|
|
@@ -2390,7 +2715,8 @@ var LinesDB = class LinesDB {
|
|
|
2390
2715
|
}
|
|
2391
2716
|
/**
|
|
2392
2717
|
* The files that changed since this database last read or wrote them, as {@link hasExternalChanges}
|
|
2393
|
-
* tells: each JSONL file edited, added or removed,
|
|
2718
|
+
* tells: each JSONL file edited, added or removed, each schema file edited, added or removed, and each
|
|
2719
|
+
* project file a schema imports edited, added or removed
|
|
2394
2720
|
*/
|
|
2395
2721
|
async findExternalChanges() {
|
|
2396
2722
|
try {
|
|
@@ -2409,6 +2735,16 @@ var LinesDB = class LinesDB {
|
|
|
2409
2735
|
});
|
|
2410
2736
|
if (content === void 0 || hashJsonlContent(content) !== knownHash) changed.add(file);
|
|
2411
2737
|
}
|
|
2738
|
+
const knownHashes = /* @__PURE__ */ new Map();
|
|
2739
|
+
for (const files of this.schemaDependencyHashes.values()) for (const [file, knownHash] of files) knownHashes.set(file, (knownHashes.get(file) ?? /* @__PURE__ */ new Set()).add(knownHash));
|
|
2740
|
+
for (const [file, hashes] of knownHashes) {
|
|
2741
|
+
const content = await readFile(file).catch((error) => {
|
|
2742
|
+
if (error.code === "ENOENT") return void 0;
|
|
2743
|
+
throw error;
|
|
2744
|
+
});
|
|
2745
|
+
const current = content === void 0 ? MISSING_HASH : hashContent(content);
|
|
2746
|
+
if ([...hashes].some((hash) => hash !== current)) changed.add(file);
|
|
2747
|
+
}
|
|
2412
2748
|
const tables = await DirectoryScanner.scanDirectory(this.config.dataDir);
|
|
2413
2749
|
const scanned = new Set(listJsonlFiles(tables));
|
|
2414
2750
|
for (const file of this.scannedJsonlFiles) if (!scanned.has(file)) changed.add(file);
|
|
@@ -2431,6 +2767,25 @@ var LinesDB = class LinesDB {
|
|
|
2431
2767
|
});
|
|
2432
2768
|
return content === void 0 ? "" : `${schemaPath}\0${hashJsonlContent(content)}`;
|
|
2433
2769
|
}
|
|
2770
|
+
recordSchemaDependencies(imports, tableNames, schemaPaths, replace) {
|
|
2771
|
+
if (replace) {
|
|
2772
|
+
for (const name of this.schemaDependencyHashes.keys()) if (!schemaPaths.has(name)) this.schemaDependencyHashes.delete(name);
|
|
2773
|
+
}
|
|
2774
|
+
for (const name of tableNames) {
|
|
2775
|
+
const schemaPath = schemaPaths.get(name);
|
|
2776
|
+
if (schemaPath) this.schemaDependencyHashes.set(name, imports.dependencies(schemaPath));
|
|
2777
|
+
else this.schemaDependencyHashes.delete(name);
|
|
2778
|
+
}
|
|
2779
|
+
}
|
|
2780
|
+
/**
|
|
2781
|
+
* The project files the schemas import, as paths: not the schema files, and not a package from
|
|
2782
|
+
* node_modules. Those of one table when it is given. An edit to one of them is among
|
|
2783
|
+
* {@link findExternalChanges}
|
|
2784
|
+
*/
|
|
2785
|
+
listSchemaDependencies(tableName) {
|
|
2786
|
+
const tables = tableName === void 0 ? [...this.schemaDependencyHashes.values()] : [this.schemaDependencyHashes.get(tableName) ?? /* @__PURE__ */ new Map()];
|
|
2787
|
+
return [...new Set(tables.flatMap((files) => [...files.keys()]))];
|
|
2788
|
+
}
|
|
2434
2789
|
async schemaFileState(tableName, config) {
|
|
2435
2790
|
if (config.validationSchema) return "";
|
|
2436
2791
|
const schemaPath = await this.findTableSchemaFile(tableName, config);
|
|
@@ -2480,15 +2835,18 @@ var LinesDB = class LinesDB {
|
|
|
2480
2835
|
let rawSqlTablesBefore;
|
|
2481
2836
|
let linesWithUnknownFieldsBefore;
|
|
2482
2837
|
let originsBefore;
|
|
2838
|
+
let columnsBefore;
|
|
2483
2839
|
const scannedBefore = [...this.scannedJsonlFiles];
|
|
2484
2840
|
let written = [];
|
|
2485
2841
|
try {
|
|
2486
2842
|
await this.waitForPendingSyncs();
|
|
2487
2843
|
originsBefore = new Map([...this.rowOriginsByRowid].map(([name, origins]) => [name, new Map(origins)]));
|
|
2844
|
+
columnsBefore = new Map([...this.tablesFromGivenColumns].map((name) => [name, [...this.schemas.get(name)?.columns ?? []]]));
|
|
2488
2845
|
fieldChangesBefore = cloneFieldChanges(this.fieldChanges);
|
|
2489
2846
|
rawSqlTablesBefore = new Set(this.rawSqlTables);
|
|
2490
2847
|
linesWithUnknownFieldsBefore = new Map(Array.from(this.linesWithUnknownFields, ([tableName, lines]) => [tableName, new Map(lines)]));
|
|
2491
2848
|
this.db.exec("BEGIN TRANSACTION");
|
|
2849
|
+
this.settleUndos = [];
|
|
2492
2850
|
this.inTransaction = true;
|
|
2493
2851
|
this.transactionToken = token;
|
|
2494
2852
|
this.transactionStarting = false;
|
|
@@ -2501,6 +2859,7 @@ var LinesDB = class LinesDB {
|
|
|
2501
2859
|
}
|
|
2502
2860
|
if (!this.isReadOnlyDataSet()) written = await this.writeBackTogether(this.tablesChangedInTransaction());
|
|
2503
2861
|
this.db.exec("COMMIT");
|
|
2862
|
+
this.settleUndos = void 0;
|
|
2504
2863
|
this.inTransaction = false;
|
|
2505
2864
|
this.transactionChanges = void 0;
|
|
2506
2865
|
return ok(result);
|
|
@@ -2508,6 +2867,10 @@ var LinesDB = class LinesDB {
|
|
|
2508
2867
|
this.transactionStarting = false;
|
|
2509
2868
|
this.transactionChanges = void 0;
|
|
2510
2869
|
if (originsBefore) this.rowOriginsByRowid = originsBefore;
|
|
2870
|
+
for (const [name, columns] of columnsBefore ?? []) {
|
|
2871
|
+
const schema = this.schemas.get(name);
|
|
2872
|
+
if (schema) schema.columns = columns;
|
|
2873
|
+
}
|
|
2511
2874
|
this.scannedJsonlFiles = scannedBefore;
|
|
2512
2875
|
if (fieldChangesBefore) this.fieldChanges = fieldChangesBefore;
|
|
2513
2876
|
if (rawSqlTablesBefore) this.rawSqlTables = rawSqlTablesBefore;
|
|
@@ -2516,6 +2879,8 @@ var LinesDB = class LinesDB {
|
|
|
2516
2879
|
if (this.inTransaction) try {
|
|
2517
2880
|
this.db.exec("ROLLBACK");
|
|
2518
2881
|
} catch (_rollbackError) {}
|
|
2882
|
+
for (const undo of [...this.settleUndos ?? []].reverse()) undo();
|
|
2883
|
+
this.settleUndos = void 0;
|
|
2519
2884
|
this.inTransaction = false;
|
|
2520
2885
|
return err(toError(failure));
|
|
2521
2886
|
} finally {
|
|
@@ -2602,8 +2967,7 @@ var LinesDB = class LinesDB {
|
|
|
2602
2967
|
function listJsonlFiles(tables) {
|
|
2603
2968
|
return Array.from(tables.values()).flatMap((config) => config.jsonlPaths ?? [config.jsonlPath]).sort();
|
|
2604
2969
|
}
|
|
2605
|
-
|
|
2606
|
-
//#region src/error-formatter.ts
|
|
2970
|
+
// src/error-formatter.ts
|
|
2607
2971
|
var ErrorFormatter = class {
|
|
2608
2972
|
verbose;
|
|
2609
2973
|
constructor(options = {}) {
|
|
@@ -2705,8 +3069,7 @@ var ErrorFormatter = class {
|
|
|
2705
3069
|
return styleText("red", "\n✗ Migration failed and was rolled back");
|
|
2706
3070
|
}
|
|
2707
3071
|
};
|
|
2708
|
-
|
|
2709
|
-
//#region src/fill.ts
|
|
3072
|
+
// src/fill.ts
|
|
2710
3073
|
/**
|
|
2711
3074
|
* Fill the named fields into the rows of the JSONL files that have no value for them, with the values
|
|
2712
3075
|
* each table computes for a row. A value already in the file is never replaced, and a line that gains
|
|
@@ -2741,13 +3104,14 @@ async function fillFieldsInternal(options) {
|
|
|
2741
3104
|
const loadFiller = options.loadFiller ?? fillerFromValidationSchema;
|
|
2742
3105
|
const tablesWithoutSchema = [];
|
|
2743
3106
|
const tables = [];
|
|
3107
|
+
const imports = createSchemaImports();
|
|
2744
3108
|
for (const { table, file, target, schemaDir } of sources.values()) {
|
|
2745
3109
|
const schemaPath = await findSchemaFile(schemaDir, table);
|
|
2746
3110
|
if (!schemaPath) {
|
|
2747
3111
|
if (!tablesWithoutSchema.includes(table)) tablesWithoutSchema.push(table);
|
|
2748
3112
|
continue;
|
|
2749
3113
|
}
|
|
2750
|
-
const schemaModule = await import(
|
|
3114
|
+
const schemaModule = await imports.import(schemaPath);
|
|
2751
3115
|
tables.push({
|
|
2752
3116
|
table,
|
|
2753
3117
|
file,
|
|
@@ -2919,8 +3283,7 @@ function serializeRow(row, fieldOrder) {
|
|
|
2919
3283
|
for (const [key, value] of ordered) setField(out, key, value);
|
|
2920
3284
|
return JSON.stringify(out);
|
|
2921
3285
|
}
|
|
2922
|
-
|
|
2923
|
-
//#region src/dataset-config.ts
|
|
3286
|
+
// src/dataset-config.ts
|
|
2924
3287
|
const directories = z.array(z.string().min(1)).min(1);
|
|
2925
3288
|
const datasetConfigSchema = z.strictObject({
|
|
2926
3289
|
schemaDir: z.string().min(1),
|
|
@@ -2966,8 +3329,227 @@ async function loadDatasetConfig(path = "lines-db.config.json", options = {}) {
|
|
|
2966
3329
|
schemaDir
|
|
2967
3330
|
};
|
|
2968
3331
|
}
|
|
2969
|
-
|
|
2970
|
-
|
|
3332
|
+
// src/cli.ts
|
|
3333
|
+
function __loculus_9(result, input) {
|
|
3334
|
+
if (config().customError === void 0) return result;
|
|
3335
|
+
return result.issues ? { issues: result.issues.map((issue) => issue.path?.length ? issue : _resolveIssue(issue, input)) } : result;
|
|
3336
|
+
}
|
|
3337
|
+
const __loculus_1 = /^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?$/;
|
|
3338
|
+
function __loculus_25(message, code, raw) {
|
|
3339
|
+
return { issues: [_typeIssue("string", raw, message)] };
|
|
3340
|
+
}
|
|
3341
|
+
function __loculus_12(value) {
|
|
3342
|
+
const raw = value;
|
|
3343
|
+
if (typeof value !== "string") return __loculus_25("Expected a string", "invalid_type", raw);
|
|
3344
|
+
return { value };
|
|
3345
|
+
}
|
|
3346
|
+
function __loculus_11(value) {
|
|
3347
|
+
const raw = value;
|
|
3348
|
+
if (typeof value !== "string") return __loculus_9(__loculus_25("Expected a string", "invalid_type", raw), raw);
|
|
3349
|
+
return "issues" in {} ? __loculus_9({ value }, raw) : { value };
|
|
3350
|
+
}
|
|
3351
|
+
function __loculus_15(value) {
|
|
3352
|
+
const raw = value;
|
|
3353
|
+
if (value === void 0) return { value: void 0 };
|
|
3354
|
+
if (typeof value !== "string") return { issues: [_typeIssue("string", raw, "Expected a string")] };
|
|
3355
|
+
return { value };
|
|
3356
|
+
}
|
|
3357
|
+
function __loculus_14(value) {
|
|
3358
|
+
const raw = value;
|
|
3359
|
+
if (value === void 0) return "issues" in {} ? __loculus_9({ value: void 0 }, raw) : { value: void 0 };
|
|
3360
|
+
if (typeof value !== "string") return __loculus_9({ issues: [_typeIssue("string", raw, "Expected a string")] }, raw);
|
|
3361
|
+
return "issues" in {} ? __loculus_9({ value }, raw) : { value };
|
|
3362
|
+
}
|
|
3363
|
+
function __loculus_18(value) {
|
|
3364
|
+
const raw = value;
|
|
3365
|
+
if (value === void 0) return { value: false };
|
|
3366
|
+
if (value === true || value === "true" || value === "1") return { value: true };
|
|
3367
|
+
if (value === false || value === "false" || value === "0") return { value: false };
|
|
3368
|
+
return { issues: [_typeIssue("boolean", raw, "Expected true, false, 1 or 0")] };
|
|
3369
|
+
}
|
|
3370
|
+
function __loculus_17(value) {
|
|
3371
|
+
const raw = value;
|
|
3372
|
+
if (value === void 0) return "issues" in {} ? __loculus_9({ value: false }, raw) : { value: false };
|
|
3373
|
+
if (value === true || value === "true" || value === "1") return "issues" in {} ? __loculus_9({ value: true }, raw) : { value: true };
|
|
3374
|
+
if (value === false || value === "false" || value === "0") return "issues" in {} ? __loculus_9({ value: false }, raw) : { value: false };
|
|
3375
|
+
return __loculus_9({ issues: [_typeIssue("boolean", raw, "Expected true, false, 1 or 0")] }, raw);
|
|
3376
|
+
}
|
|
3377
|
+
function __loculus_23(value) {
|
|
3378
|
+
const raw = value;
|
|
3379
|
+
if (value === void 0) return { value: 4848 };
|
|
3380
|
+
if (typeof value !== "number") {
|
|
3381
|
+
if (typeof value !== "string" || !__loculus_1.test(value)) return { issues: [_typeIssue("number", raw, "Expected a decimal number")] };
|
|
3382
|
+
value = Number(value);
|
|
3383
|
+
}
|
|
3384
|
+
if (!Number.isFinite(value)) return { issues: [{
|
|
3385
|
+
message: "Expected a finite number",
|
|
3386
|
+
code: "invalid_value"
|
|
3387
|
+
}] };
|
|
3388
|
+
if (!Number.isSafeInteger(value)) return { issues: [{
|
|
3389
|
+
message: "Expected a safe integer",
|
|
3390
|
+
code: "invalid_value"
|
|
3391
|
+
}] };
|
|
3392
|
+
if (!(value >= 0)) return { issues: [{
|
|
3393
|
+
message: "Expected at least 0",
|
|
3394
|
+
code: "too_small",
|
|
3395
|
+
origin: "number",
|
|
3396
|
+
min: 0,
|
|
3397
|
+
inclusive: true
|
|
3398
|
+
}] };
|
|
3399
|
+
if (!(value <= 65535)) return { issues: [{
|
|
3400
|
+
message: "Expected at most 65535",
|
|
3401
|
+
code: "too_big",
|
|
3402
|
+
origin: "number",
|
|
3403
|
+
max: 65535,
|
|
3404
|
+
inclusive: true
|
|
3405
|
+
}] };
|
|
3406
|
+
return { value };
|
|
3407
|
+
}
|
|
3408
|
+
function __loculus_22(value) {
|
|
3409
|
+
const raw = value;
|
|
3410
|
+
if (value === void 0) return "issues" in {} ? __loculus_9({ value: 4848 }, raw) : { value: 4848 };
|
|
3411
|
+
if (typeof value !== "number") {
|
|
3412
|
+
if (typeof value !== "string" || !__loculus_1.test(value)) return __loculus_9({ issues: [_typeIssue("number", raw, "Expected a decimal number")] }, raw);
|
|
3413
|
+
value = Number(value);
|
|
3414
|
+
}
|
|
3415
|
+
if (!Number.isFinite(value)) return __loculus_9({ issues: [{
|
|
3416
|
+
message: "Expected a finite number",
|
|
3417
|
+
code: "invalid_value"
|
|
3418
|
+
}] }, raw);
|
|
3419
|
+
if (!Number.isSafeInteger(value)) return __loculus_9({ issues: [{
|
|
3420
|
+
message: "Expected a safe integer",
|
|
3421
|
+
code: "invalid_value"
|
|
3422
|
+
}] }, raw);
|
|
3423
|
+
if (!(value >= 0)) return __loculus_9({ issues: [{
|
|
3424
|
+
message: "Expected at least 0",
|
|
3425
|
+
code: "too_small",
|
|
3426
|
+
origin: "number",
|
|
3427
|
+
min: 0,
|
|
3428
|
+
inclusive: true
|
|
3429
|
+
}] }, raw);
|
|
3430
|
+
if (!(value <= 65535)) return __loculus_9({ issues: [{
|
|
3431
|
+
message: "Expected at most 65535",
|
|
3432
|
+
code: "too_big",
|
|
3433
|
+
origin: "number",
|
|
3434
|
+
max: 65535,
|
|
3435
|
+
inclusive: true
|
|
3436
|
+
}] }, raw);
|
|
3437
|
+
return "issues" in {} ? __loculus_9({ value }, raw) : { value };
|
|
3438
|
+
}
|
|
3439
|
+
/* @__NO_SIDE_EFFECTS__ */
|
|
3440
|
+
function __loculus_13() {
|
|
3441
|
+
return {
|
|
3442
|
+
meta: {
|
|
3443
|
+
kind: "string",
|
|
3444
|
+
description: void 0
|
|
3445
|
+
},
|
|
3446
|
+
"~standard": {
|
|
3447
|
+
version: 1,
|
|
3448
|
+
vendor: "loculus",
|
|
3449
|
+
validate: __loculus_11
|
|
3450
|
+
},
|
|
3451
|
+
field: true,
|
|
3452
|
+
[_rawValidate]: __loculus_12
|
|
3453
|
+
};
|
|
3454
|
+
}
|
|
3455
|
+
/* @__NO_SIDE_EFFECTS__ */
|
|
3456
|
+
function __loculus_16() {
|
|
3457
|
+
return {
|
|
3458
|
+
meta: {
|
|
3459
|
+
kind: "string",
|
|
3460
|
+
description: void 0,
|
|
3461
|
+
optional: true,
|
|
3462
|
+
nullable: false
|
|
3463
|
+
},
|
|
3464
|
+
"~standard": {
|
|
3465
|
+
version: 1,
|
|
3466
|
+
vendor: "loculus",
|
|
3467
|
+
validate: __loculus_14
|
|
3468
|
+
},
|
|
3469
|
+
field: true,
|
|
3470
|
+
[_rawValidate]: __loculus_15
|
|
3471
|
+
};
|
|
3472
|
+
}
|
|
3473
|
+
/* @__NO_SIDE_EFFECTS__ */
|
|
3474
|
+
function __loculus_19() {
|
|
3475
|
+
return {
|
|
3476
|
+
meta: {
|
|
3477
|
+
kind: "boolean",
|
|
3478
|
+
description: void 0,
|
|
3479
|
+
optional: true,
|
|
3480
|
+
nullable: false,
|
|
3481
|
+
defaultValue: false
|
|
3482
|
+
},
|
|
3483
|
+
"~standard": {
|
|
3484
|
+
version: 1,
|
|
3485
|
+
vendor: "loculus",
|
|
3486
|
+
validate: __loculus_17
|
|
3487
|
+
},
|
|
3488
|
+
field: true,
|
|
3489
|
+
[_rawValidate]: __loculus_18
|
|
3490
|
+
};
|
|
3491
|
+
}
|
|
3492
|
+
/* @__NO_SIDE_EFFECTS__ */
|
|
3493
|
+
function __loculus_24() {
|
|
3494
|
+
return {
|
|
3495
|
+
meta: {
|
|
3496
|
+
kind: "number",
|
|
3497
|
+
description: void 0,
|
|
3498
|
+
optional: true,
|
|
3499
|
+
nullable: false,
|
|
3500
|
+
defaultValue: 4848
|
|
3501
|
+
},
|
|
3502
|
+
"~standard": {
|
|
3503
|
+
version: 1,
|
|
3504
|
+
vendor: "loculus",
|
|
3505
|
+
validate: __loculus_22
|
|
3506
|
+
},
|
|
3507
|
+
field: true,
|
|
3508
|
+
[_rawValidate]: __loculus_23
|
|
3509
|
+
};
|
|
3510
|
+
}
|
|
3511
|
+
function __loculus_21(value) {
|
|
3512
|
+
const raw = value;
|
|
3513
|
+
if (!Array.isArray(value)) return __loculus_9({ issues: [_typeIssue("array", raw, "Expected an array")] }, raw);
|
|
3514
|
+
const inputs = Array.isArray(value) ? value : [value];
|
|
3515
|
+
const output = [];
|
|
3516
|
+
let issues;
|
|
3517
|
+
for (let i = 0; i < inputs.length; i++) {
|
|
3518
|
+
const result = __loculus_11(inputs[i]);
|
|
3519
|
+
if (result.issues) for (const issue of result.issues) (issues ??= []).push({
|
|
3520
|
+
...issue,
|
|
3521
|
+
path: issue.path ? [i, ...issue.path] : [i]
|
|
3522
|
+
});
|
|
3523
|
+
else output.push(result.value);
|
|
3524
|
+
}
|
|
3525
|
+
if (issues) return { issues };
|
|
3526
|
+
if (inputs.length < 1) return __loculus_9({ issues: [{
|
|
3527
|
+
message: "Expected at least 1 items",
|
|
3528
|
+
code: "too_small",
|
|
3529
|
+
origin: "array",
|
|
3530
|
+
min: 1,
|
|
3531
|
+
inclusive: true
|
|
3532
|
+
}] }, raw);
|
|
3533
|
+
return "issues" in {} ? __loculus_9({ value: output }, raw) : { value: output };
|
|
3534
|
+
}
|
|
3535
|
+
/* @__NO_SIDE_EFFECTS__ */
|
|
3536
|
+
function __loculus_20(inner) {
|
|
3537
|
+
return {
|
|
3538
|
+
meta: {
|
|
3539
|
+
kind: "array",
|
|
3540
|
+
inner,
|
|
3541
|
+
enumValues: inner.meta.enumValues,
|
|
3542
|
+
...inner.meta.literalValues ? { literalValues: inner.meta.literalValues } : {},
|
|
3543
|
+
description: void 0
|
|
3544
|
+
},
|
|
3545
|
+
"~standard": {
|
|
3546
|
+
version: 1,
|
|
3547
|
+
vendor: "loculus",
|
|
3548
|
+
validate: __loculus_21
|
|
3549
|
+
},
|
|
3550
|
+
field: true
|
|
3551
|
+
};
|
|
3552
|
+
}
|
|
2971
3553
|
register("amaro/transform", import.meta.url);
|
|
2972
3554
|
const originalEmitWarning = process.emitWarning;
|
|
2973
3555
|
process.emitWarning = (warning, ...args) => {
|
|
@@ -3001,11 +3583,11 @@ const generateCommand = defineCommand({
|
|
|
3001
3583
|
name: "generate",
|
|
3002
3584
|
description: "Generate TypeScript type definitions from schema files",
|
|
3003
3585
|
args: l.object({
|
|
3004
|
-
dataDir: arg(
|
|
3586
|
+
dataDir: arg(/* @__PURE__ */ __loculus_13(), {
|
|
3005
3587
|
positional: true,
|
|
3006
3588
|
description: "Directory containing JSONL and schema files"
|
|
3007
3589
|
}),
|
|
3008
|
-
output: arg(
|
|
3590
|
+
output: arg(/* @__PURE__ */ __loculus_16(), {
|
|
3009
3591
|
alias: "o",
|
|
3010
3592
|
description: "Output file path (default: db.ts in dataDir)"
|
|
3011
3593
|
})
|
|
@@ -3027,14 +3609,14 @@ const validateCommand = defineCommand({
|
|
|
3027
3609
|
name: "validate",
|
|
3028
3610
|
description: "Validate JSONL file(s) against schema",
|
|
3029
3611
|
args: l.object({
|
|
3030
|
-
path: arg(
|
|
3612
|
+
path: arg(/* @__PURE__ */ __loculus_16(), {
|
|
3031
3613
|
positional: true,
|
|
3032
3614
|
description: "File or directory path to validate (omit to use lines-db.config.json)"
|
|
3033
3615
|
}),
|
|
3034
|
-
config: arg(
|
|
3035
|
-
dataset: arg(l.array(
|
|
3036
|
-
allDatasets: arg(
|
|
3037
|
-
verbose: arg(
|
|
3616
|
+
config: arg(/* @__PURE__ */ __loculus_16(), { description: "Dataset configuration file (default: ./lines-db.config.json)" }),
|
|
3617
|
+
dataset: arg(l.array(/* @__PURE__ */ __loculus_13(), { optional: true }), { description: "Named datasets to validate together with base (repeat to select several)" }),
|
|
3618
|
+
allDatasets: arg(/* @__PURE__ */ __loculus_19(), { description: "Validate base and all datasets together" }),
|
|
3619
|
+
verbose: arg(/* @__PURE__ */ __loculus_19(), {
|
|
3038
3620
|
alias: "v",
|
|
3039
3621
|
description: "Show verbose error output"
|
|
3040
3622
|
})
|
|
@@ -3135,24 +3717,24 @@ const migrateCommand = defineCommand({
|
|
|
3135
3717
|
name: "migrate",
|
|
3136
3718
|
description: "Migrate data with transformation function",
|
|
3137
3719
|
args: l.object({
|
|
3138
|
-
path: arg(
|
|
3720
|
+
path: arg(/* @__PURE__ */ __loculus_13(), {
|
|
3139
3721
|
positional: true,
|
|
3140
3722
|
description: "File or directory path to migrate"
|
|
3141
3723
|
}),
|
|
3142
|
-
transform: arg(
|
|
3724
|
+
transform: arg(/* @__PURE__ */ __loculus_13(), {
|
|
3143
3725
|
positional: true,
|
|
3144
3726
|
description: "Transform function (e.g., \"(row) => ({ ...row, age: row.age + 1 })\")"
|
|
3145
3727
|
}),
|
|
3146
|
-
filter: arg(
|
|
3728
|
+
filter: arg(/* @__PURE__ */ __loculus_16(), {
|
|
3147
3729
|
alias: "f",
|
|
3148
3730
|
description: "Filter expression"
|
|
3149
3731
|
}),
|
|
3150
|
-
fields: arg(
|
|
3151
|
-
errorOutput: arg(
|
|
3732
|
+
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" }),
|
|
3733
|
+
errorOutput: arg(/* @__PURE__ */ __loculus_16(), {
|
|
3152
3734
|
alias: "e",
|
|
3153
3735
|
description: "Output file path for transformed data when migration fails"
|
|
3154
3736
|
}),
|
|
3155
|
-
verbose: arg(
|
|
3737
|
+
verbose: arg(/* @__PURE__ */ __loculus_19(), {
|
|
3156
3738
|
alias: "v",
|
|
3157
3739
|
description: "Show verbose error output"
|
|
3158
3740
|
})
|
|
@@ -3188,12 +3770,12 @@ const fillCommand = defineCommand({
|
|
|
3188
3770
|
name: "fill",
|
|
3189
3771
|
description: "Fill the values each table computes into the JSONL rows that have none for the named fields",
|
|
3190
3772
|
args: l.object({
|
|
3191
|
-
path: arg(
|
|
3773
|
+
path: arg(/* @__PURE__ */ __loculus_20(/* @__PURE__ */ __loculus_13()), {
|
|
3192
3774
|
positional: true,
|
|
3193
3775
|
description: "One or more data directories or .jsonl files"
|
|
3194
3776
|
}),
|
|
3195
|
-
schemaDir: arg(
|
|
3196
|
-
fields: arg(
|
|
3777
|
+
schemaDir: arg(/* @__PURE__ */ __loculus_16(), { description: "Directory holding shared schemas (default: next to each JSONL file)" }),
|
|
3778
|
+
fields: arg(/* @__PURE__ */ __loculus_16(), {
|
|
3197
3779
|
alias: "f",
|
|
3198
3780
|
description: "Comma-separated fields to fill (default: each table's primary key)"
|
|
3199
3781
|
})
|
|
@@ -3230,22 +3812,17 @@ const studioCommand = defineCommand({
|
|
|
3230
3812
|
name: "studio",
|
|
3231
3813
|
description: "Browse and edit the tables of a data directory in the browser",
|
|
3232
3814
|
args: l.object({
|
|
3233
|
-
path: arg(
|
|
3815
|
+
path: arg(/* @__PURE__ */ __loculus_16(), {
|
|
3234
3816
|
positional: true,
|
|
3235
3817
|
description: "Directory containing JSONL files"
|
|
3236
3818
|
}),
|
|
3237
|
-
dataDir: arg(l.array(
|
|
3238
|
-
schemaDir: arg(
|
|
3239
|
-
port: arg(
|
|
3240
|
-
integer: true,
|
|
3241
|
-
gte: 0,
|
|
3242
|
-
lte: 65535,
|
|
3243
|
-
default: 4848
|
|
3244
|
-
}), {
|
|
3819
|
+
dataDir: arg(l.array(/* @__PURE__ */ __loculus_13(), { default: [] }), { description: "Directory containing JSONL files (repeatable)" }),
|
|
3820
|
+
schemaDir: arg(/* @__PURE__ */ __loculus_16(), { description: "Directory containing shared schema files (required for several data directories)" }),
|
|
3821
|
+
port: arg(/* @__PURE__ */ __loculus_24(), {
|
|
3245
3822
|
alias: "p",
|
|
3246
3823
|
description: "Port to listen on (0 picks a free one)"
|
|
3247
3824
|
}),
|
|
3248
|
-
open: arg(
|
|
3825
|
+
open: arg(/* @__PURE__ */ __loculus_19(), { description: "Open the studio in the default browser" }),
|
|
3249
3826
|
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" })
|
|
3250
3827
|
}),
|
|
3251
3828
|
run: async (args) => {
|
|
@@ -3567,5 +4144,4 @@ async function migrateFile(filePath, transformStr, options) {
|
|
|
3567
4144
|
throw error;
|
|
3568
4145
|
}
|
|
3569
4146
|
}
|
|
3570
|
-
//#endregion
|
|
3571
4147
|
export {};
|