durable-db 0.9.0 → 0.11.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.
@@ -2,7 +2,7 @@ import { r as type } from "./type-CUgZsZp3.js";
2
2
  import { t as actionArgsType } from "./actionArgs-DP2tQrlf.js";
3
3
  import { Table, getTableColumns, getTableName, is, isSQLWrapper } from "drizzle-orm";
4
4
  import { SQLiteSyncDialect, getTableConfig } from "drizzle-orm/sqlite-core";
5
- import { AliasNode, CamelCasePlugin, ColumnNode, ColumnUpdateNode, IdentifierNode, InsertQueryNode, PrimitiveValueListNode, TableNode, ValueListNode, ValueNode, ValuesNode, sql } from "kysely";
5
+ import { AliasNode, CamelCasePlugin, ColumnNode, ColumnUpdateNode, DeleteQueryNode, IdentifierNode, InsertQueryNode, OperationNodeTransformer, PrimitiveValueListNode, ReferenceNode, SelectAllNode, SelectQueryNode, TableNode, UpdateQueryNode, ValueListNode, ValueNode, ValuesNode, expressionBuilder, sql } from "kysely";
6
6
  import { toCamelCase, toSnakeCase } from "drizzle-orm/casing";
7
7
  //#region src/db/relations.ts
8
8
  const registries = /* @__PURE__ */ new WeakMap();
@@ -142,11 +142,22 @@ var SchemaPlugin = class extends CamelCasePlugin {
142
142
  camelCase(str) {
143
143
  return this.sqlToJs.get(str) ?? super.camelCase(str);
144
144
  }
145
+ /**
146
+ * The key a result row has for an identifier a query writes as `name`: it
147
+ * is snake_cased on the way in and camelCased on the way out.
148
+ */
149
+ resultKey(name) {
150
+ return this.camelCase(this.snakeCase(name));
151
+ }
145
152
  };
146
153
  function getKyselyTableName(node) {
147
154
  if (node && TableNode.is(node)) return node.table.identifier.name;
148
155
  return null;
149
156
  }
157
+ /** A binary value: an ArrayBuffer or a view of one (a Uint8Array, a Buffer). */
158
+ function isBinary(value) {
159
+ return value instanceof ArrayBuffer || ArrayBuffer.isView(value);
160
+ }
150
161
  function getKyselyColumnName(node) {
151
162
  if (!node) return null;
152
163
  if (ColumnNode.is(node)) return node.column.name;
@@ -343,6 +354,7 @@ var DateSerializePlugin = class {
343
354
  transformNode(node) {
344
355
  if (node === null || node === void 0) return node;
345
356
  if (node instanceof Date) return dateSerializers.serialize(node);
357
+ if (isBinary(node)) return node;
346
358
  if (Array.isArray(node)) return node.map((item) => this.transformNode(item));
347
359
  if (typeof node === "object") {
348
360
  const result = {};
@@ -426,6 +438,326 @@ var BooleanDeserializePlugin = class {
426
438
  }
427
439
  };
428
440
  /**
441
+ * The JSON-mode columns of a schema, table by table. A table is found under
442
+ * its schema key and its SQL name; a column under its property name, its name
443
+ * and its snake_cased property name, like collectDateColumnNames — so a
444
+ * lookup works on either side of the CamelCasePlugin.
445
+ */
446
+ function collectJsonTables(schema) {
447
+ const tables = /* @__PURE__ */ new Map();
448
+ for (const [schemaKey, table] of Object.entries(schema)) {
449
+ const facts = {
450
+ json: /* @__PURE__ */ new Map(),
451
+ plain: /* @__PURE__ */ new Set()
452
+ };
453
+ for (const [propertyName, column] of Object.entries(getTableColumns(table))) {
454
+ const names = [
455
+ propertyName,
456
+ column.name,
457
+ toSnakeCase(propertyName)
458
+ ];
459
+ if (column.dataType === "json") {
460
+ const storage = column.getSQLType() === "blob" ? "blob" : "text";
461
+ for (const name of names) facts.json.set(name, storage);
462
+ } else for (const name of names) facts.plain.add(name);
463
+ }
464
+ const tableName = getTableName(table);
465
+ for (const name of [
466
+ schemaKey,
467
+ tableName,
468
+ toCamelCase(tableName)
469
+ ]) if (!tables.has(name)) tables.set(name, facts);
470
+ }
471
+ return tables;
472
+ }
473
+ function hasJsonColumn(schema) {
474
+ return Object.values(schema).some((table) => Object.values(getTableColumns(table)).some((column) => column.dataType === "json"));
475
+ }
476
+ /**
477
+ * What a JSON-mode column stores for a value: its JSON text, as UTF-8 bytes
478
+ * in a blob column. A string is JSON too (`"text"`), so it reads back as the
479
+ * string it was.
480
+ */
481
+ function serializeJsonValue(value, storage) {
482
+ if (value === null || value === void 0) return value;
483
+ const json = JSON.stringify(value);
484
+ if (json === void 0) return value;
485
+ return storage === "blob" ? new TextEncoder().encode(json) : json;
486
+ }
487
+ /**
488
+ * What a JSON-mode column holds, from what SQLite answered: text is parsed,
489
+ * bytes (a blob column) are read as UTF-8 first. What is no JSON — a row
490
+ * written before these columns were serialized — is answered as it is.
491
+ */
492
+ function parseJsonValue(value) {
493
+ let text = value;
494
+ if (isBinary(value)) try {
495
+ text = new TextDecoder("utf-8", { fatal: true }).decode(value);
496
+ } catch {
497
+ return value;
498
+ }
499
+ if (typeof text !== "string") return value;
500
+ try {
501
+ return JSON.parse(text);
502
+ } catch {
503
+ return value;
504
+ }
505
+ }
506
+ /** The table a node names: `invoices`, or the one behind `invoices as i`. */
507
+ function tableNameOf(node) {
508
+ if (!node) return null;
509
+ if (TableNode.is(node)) return node.table.identifier.name;
510
+ if (AliasNode.is(node) && TableNode.is(node.node)) return node.node.table.identifier.name;
511
+ return null;
512
+ }
513
+ /** The column a node names: `meta`, or the one in `i.meta`. */
514
+ function columnNameOf(node) {
515
+ if (!node) return null;
516
+ if (ColumnNode.is(node)) return node.column.name;
517
+ if (ReferenceNode.is(node) && ColumnNode.is(node.column)) return node.column.column.name;
518
+ return null;
519
+ }
520
+ /** Every table a query names, however deep — never walking the values it carries. */
521
+ function walkTables(node, visit) {
522
+ if (Array.isArray(node)) {
523
+ for (const item of node) walkTables(item, visit);
524
+ return;
525
+ }
526
+ if (typeof node !== "object" || node === null) return;
527
+ const kind = node.kind;
528
+ if (typeof kind !== "string" || kind === "ValueNode" || kind === "PrimitiveValueListNode") return;
529
+ if (TableNode.is(node)) {
530
+ visit(node.table.identifier.name);
531
+ return;
532
+ }
533
+ for (const value of Object.values(node)) walkTables(value, visit);
534
+ }
535
+ /** The names that are a JSON-mode column in one of `tables` and another kind of column in none. */
536
+ function jsonNamesAmong(tables) {
537
+ const json = /* @__PURE__ */ new Set();
538
+ const plain = /* @__PURE__ */ new Set();
539
+ for (const facts of new Set(tables)) {
540
+ for (const name of facts.json.keys()) json.add(name);
541
+ for (const name of facts.plain) plain.add(name);
542
+ }
543
+ for (const name of plain) json.delete(name);
544
+ return json;
545
+ }
546
+ /**
547
+ * The two plugins behind JSON-mode columns (`text({ mode: 'json' })`,
548
+ * `blob({ mode: 'json' })`): a value written to one is stored as its JSON, and
549
+ * one that is read comes back as the value.
550
+ *
551
+ * `write` goes before the plugin that renames identifiers and before
552
+ * DateSerializePlugin; `read` after them. In between they share which keys of
553
+ * a query's rows are JSON columns, worked out from what the query selects:
554
+ *
555
+ * - a column (`meta`, `i.meta`, `i.meta as m`) is resolved against the tables
556
+ * the query reads from — the same name in a table where it is another kind
557
+ * of column is left alone;
558
+ * - `selectAll()` / `returningAll()` are every JSON column of those tables;
559
+ * - where the source is no table of the schema (a subquery, a CTE, a raw
560
+ * query), a name goes for a JSON column when it is one in a table the query
561
+ * names (in any table, for a query that names none) and another kind of
562
+ * column in none of them.
563
+ *
564
+ * An expression (a JSON path, a function call, `related()`) is the caller's:
565
+ * it is neither serialized nor parsed. So is a value compared with a JSON
566
+ * column in a `where`.
567
+ */
568
+ function createJsonPlugins(schema, options = {}) {
569
+ const tables = collectJsonTables(schema);
570
+ const resultKey = options.resultKey ?? ((name) => name);
571
+ const selected = /* @__PURE__ */ new WeakMap();
572
+ let everywhere;
573
+ const writeValue = (facts, column, node) => {
574
+ const storage = column === null ? void 0 : facts.json.get(column);
575
+ if (!storage || !ValueNode.is(node)) return node;
576
+ return Object.freeze({
577
+ ...node,
578
+ value: serializeJsonValue(node.value, storage)
579
+ });
580
+ };
581
+ const writeUpdates = (facts, updates) => updates.map((update) => {
582
+ const value = writeValue(facts, columnNameOf(update.column), update.value);
583
+ return value === update.value ? update : Object.freeze({
584
+ ...update,
585
+ value
586
+ });
587
+ });
588
+ const writeInsert = (node) => {
589
+ const facts = tables.get(tableNameOf(node.into) ?? "");
590
+ if (!facts || facts.json.size === 0) return node;
591
+ let out = node;
592
+ if (node.columns && node.values && ValuesNode.is(node.values)) {
593
+ const storages = node.columns.map((column) => facts.json.get(column.column.name));
594
+ if (storages.some((storage) => storage !== void 0)) {
595
+ const rows = node.values.values.map((row) => {
596
+ if (PrimitiveValueListNode.is(row)) return PrimitiveValueListNode.create(row.values.map((value, i) => storages[i] ? serializeJsonValue(value, storages[i]) : value));
597
+ if (ValueListNode.is(row)) return ValueListNode.create(row.values.map((value, i) => {
598
+ const storage = storages[i];
599
+ if (!storage || !ValueNode.is(value)) return value;
600
+ return Object.freeze({
601
+ ...value,
602
+ value: serializeJsonValue(value.value, storage)
603
+ });
604
+ }));
605
+ return row;
606
+ });
607
+ out = InsertQueryNode.cloneWith(out, { values: ValuesNode.create(rows) });
608
+ }
609
+ }
610
+ if (node.onConflict?.updates) out = InsertQueryNode.cloneWith(out, { onConflict: Object.freeze({
611
+ ...node.onConflict,
612
+ updates: writeUpdates(facts, node.onConflict.updates)
613
+ }) });
614
+ return out;
615
+ };
616
+ const writeUpdate = (node) => {
617
+ const facts = tables.get(tableNameOf(node.table) ?? "");
618
+ if (!facts || facts.json.size === 0 || !node.updates) return node;
619
+ return Object.freeze({
620
+ ...node,
621
+ updates: writeUpdates(facts, node.updates)
622
+ });
623
+ };
624
+ const fallbackFor = (root) => {
625
+ const named = /* @__PURE__ */ new Set();
626
+ let any = false;
627
+ walkTables(root, (name) => {
628
+ any = true;
629
+ const facts = tables.get(name);
630
+ if (facts) named.add(facts);
631
+ });
632
+ if (any) return jsonNamesAmong(named);
633
+ return everywhere ??= jsonNamesAmong(tables.values());
634
+ };
635
+ const scopeOf = (root, sources) => {
636
+ let fallback;
637
+ const scope = {
638
+ sources: /* @__PURE__ */ new Map(),
639
+ opaque: false,
640
+ fallback: () => fallback ??= fallbackFor(root)
641
+ };
642
+ for (const node of sources) {
643
+ if (!node) continue;
644
+ if (TableNode.is(node)) {
645
+ const name = node.table.identifier.name;
646
+ scope.sources.set(name, tables.get(name) ?? null);
647
+ } else if (AliasNode.is(node) && IdentifierNode.is(node.alias)) {
648
+ const table = TableNode.is(node.node) ? tables.get(node.node.table.identifier.name) : void 0;
649
+ scope.sources.set(node.alias.name, table ?? null);
650
+ } else scope.opaque = true;
651
+ }
652
+ return scope;
653
+ };
654
+ const isJson = (scope, qualifier, column) => {
655
+ if (qualifier !== null) {
656
+ const facts = scope.sources.get(qualifier);
657
+ return facts ? facts.json.has(column) : scope.fallback().has(column);
658
+ }
659
+ let json = false;
660
+ for (const facts of scope.sources.values()) {
661
+ if (!facts) continue;
662
+ if (facts.plain.has(column)) return false;
663
+ if (facts.json.has(column)) json = true;
664
+ }
665
+ return json || scope.fallback().has(column);
666
+ };
667
+ const keysOf = (root) => {
668
+ const keys = /* @__PURE__ */ new Set();
669
+ const addAll = (names) => {
670
+ for (const name of names) {
671
+ keys.add(name);
672
+ keys.add(resultKey(name));
673
+ }
674
+ };
675
+ let scope;
676
+ let selections;
677
+ if (SelectQueryNode.is(root)) {
678
+ scope = scopeOf(root, [...root.from?.froms ?? [], ...(root.joins ?? []).map((join) => join.table)]);
679
+ selections = root.selections;
680
+ } else if (InsertQueryNode.is(root)) {
681
+ scope = scopeOf(root, [root.into]);
682
+ selections = root.returning?.selections;
683
+ } else if (UpdateQueryNode.is(root)) {
684
+ scope = scopeOf(root, [
685
+ root.table,
686
+ ...root.from?.froms ?? [],
687
+ ...(root.joins ?? []).map((join) => join.table)
688
+ ]);
689
+ selections = root.returning?.selections;
690
+ } else if (DeleteQueryNode.is(root)) {
691
+ scope = scopeOf(root, [
692
+ ...root.from.froms,
693
+ ...(root.joins ?? []).map((join) => join.table),
694
+ ...root.using?.tables ?? []
695
+ ]);
696
+ selections = root.returning?.selections;
697
+ } else if (root.kind === "RawNode") {
698
+ addAll(fallbackFor(root));
699
+ return keys.size > 0 ? keys : void 0;
700
+ } else return;
701
+ if (!selections) return void 0;
702
+ const unknown = scope.opaque || [...scope.sources.values()].some((facts) => facts === null);
703
+ for (const { selection } of selections) if (SelectAllNode.is(selection)) {
704
+ addAll(jsonNamesAmong([...scope.sources.values()].filter((facts) => facts !== null)));
705
+ if (unknown) addAll(scope.fallback());
706
+ } else if (ReferenceNode.is(selection)) {
707
+ const qualifier = tableNameOf(selection.table);
708
+ if (SelectAllNode.is(selection.column)) {
709
+ const facts = qualifier === null ? void 0 : scope.sources.get(qualifier);
710
+ addAll(facts ? facts.json.keys() : scope.fallback());
711
+ } else if (isJson(scope, qualifier, selection.column.column.name)) keys.add(resultKey(selection.column.column.name));
712
+ } else if (ColumnNode.is(selection)) {
713
+ if (isJson(scope, null, selection.column.name)) keys.add(resultKey(selection.column.name));
714
+ } else if (AliasNode.is(selection) && IdentifierNode.is(selection.alias)) {
715
+ const aliased = selection.node;
716
+ const column = ReferenceNode.is(aliased) || ColumnNode.is(aliased) ? columnNameOf(aliased) : null;
717
+ const qualifier = ReferenceNode.is(aliased) ? tableNameOf(aliased.table) : null;
718
+ if (column !== null && isJson(scope, qualifier, column)) keys.add(resultKey(selection.alias.name));
719
+ }
720
+ return keys.size > 0 ? keys : void 0;
721
+ };
722
+ return {
723
+ write: {
724
+ transformQuery({ node, queryId }) {
725
+ const keys = keysOf(node);
726
+ if (keys) selected.set(queryId, keys);
727
+ if (InsertQueryNode.is(node)) return writeInsert(node);
728
+ if (UpdateQueryNode.is(node)) return writeUpdate(node);
729
+ return node;
730
+ },
731
+ async transformResult({ result }) {
732
+ return result;
733
+ }
734
+ },
735
+ read: {
736
+ transformQuery({ node }) {
737
+ return node;
738
+ },
739
+ async transformResult({ result, queryId }) {
740
+ const keys = selected.get(queryId);
741
+ if (!keys || result.rows.length === 0) return result;
742
+ const rows = result.rows.map((row) => {
743
+ let out;
744
+ for (const key of keys) {
745
+ const value = row[key];
746
+ if (value === void 0 || value === null) continue;
747
+ const parsed = parseJsonValue(value);
748
+ if (parsed !== value) (out ??= { ...row })[key] = parsed;
749
+ }
750
+ return out ?? row;
751
+ });
752
+ return {
753
+ ...result,
754
+ rows
755
+ };
756
+ }
757
+ }
758
+ };
759
+ }
760
+ /**
429
761
  * Validate that a schema object is shaped like a record of Drizzle tables.
430
762
  *
431
763
  * Throws a descriptive error pointing at the offending key when the schema
@@ -446,16 +778,23 @@ function assertValidSchema(schema) {
446
778
  * - SchemaPlugin (extends CamelCasePlugin): schema-aware camelCase ↔ snake_case
447
779
  * - DateSerializePlugin: Date ↔ SQLite text serialization
448
780
  * - BooleanDeserializePlugin: boolean-mode columns read back as booleans
781
+ * - createJsonPlugins' two: JSON-mode columns written as JSON and read back
782
+ * as their value — only for a schema that has such a column
449
783
  *
450
784
  * When camelCase is false, SchemaPlugin is omitted.
451
785
  */
452
786
  function createDrizzlePlugins(schema, camelCase = true) {
453
787
  assertValidSchema(schema);
788
+ const tables = schema;
789
+ const schemaPlugin = camelCase ? new SchemaPlugin(schema) : void 0;
790
+ const json = hasJsonColumn(tables) ? createJsonPlugins(tables, schemaPlugin ? { resultKey: (name) => schemaPlugin.resultKey(name) } : {}) : void 0;
454
791
  const plugins = [];
455
- plugins.push(new DrizzleDefaultsPlugin(schema));
456
- if (camelCase) plugins.push(new SchemaPlugin(schema));
457
- plugins.push(new DateSerializePlugin(schema));
458
- plugins.push(new BooleanDeserializePlugin(schema));
792
+ plugins.push(new DrizzleDefaultsPlugin(tables));
793
+ if (json) plugins.push(json.write);
794
+ if (schemaPlugin) plugins.push(schemaPlugin);
795
+ plugins.push(new DateSerializePlugin(tables));
796
+ plugins.push(new BooleanDeserializePlugin(tables));
797
+ if (json) plugins.push(json.read);
459
798
  return plugins;
460
799
  }
461
800
  //#endregion
@@ -465,37 +804,107 @@ const specs = /* @__PURE__ */ new WeakMap();
465
804
  function metaOf(spec) {
466
805
  return {
467
806
  target: spec.relation.target,
468
- with: new Map(spec.with.map((nested) => [nested.relation.name, metaOf(nested)]))
807
+ with: new Map(spec.with.map((nested) => [nested.alias, metaOf(nested)]))
469
808
  };
470
809
  }
810
+ /** The names a select reads its tables under: a table's own, or its alias. */
811
+ function namesIn(node) {
812
+ const names = /* @__PURE__ */ new Set();
813
+ const add = (source) => {
814
+ if (TableNode.is(source)) names.add(source.table.identifier.name);
815
+ else if (AliasNode.is(source) && IdentifierNode.is(source.alias)) names.add(source.alias.name);
816
+ };
817
+ for (const source of node.from?.froms ?? []) add(source);
818
+ for (const join of node.joins ?? []) add(join.table);
819
+ return names;
820
+ }
821
+ var Qualify = class extends OperationNodeTransformer {
822
+ #target;
823
+ #alias;
824
+ #where;
825
+ /** How many selects of the condition's own this is inside. */
826
+ #depth = 0;
827
+ /** How many of those read the related table under its name. */
828
+ #shadowed = 0;
829
+ constructor(target, alias, where) {
830
+ super();
831
+ this.#target = target;
832
+ this.#alias = alias;
833
+ this.#where = where;
834
+ }
835
+ transformSelectQuery(node, queryId) {
836
+ const shadows = namesIn(node).has(this.#target);
837
+ this.#depth++;
838
+ if (shadows) this.#shadowed++;
839
+ try {
840
+ return super.transformSelectQuery(node, queryId);
841
+ } finally {
842
+ this.#depth--;
843
+ if (shadows) this.#shadowed--;
844
+ }
845
+ }
846
+ transformReference(node, queryId) {
847
+ const table = node.table?.table.identifier.name;
848
+ if (table === void 0 ? this.#depth === 0 : table === this.#target && this.#shadowed === 0) return super.transformReference({
849
+ ...node,
850
+ table: TableNode.create(this.#alias)
851
+ }, queryId);
852
+ if (table !== void 0 && table !== this.#target && this.#depth === 0) {
853
+ const column = "column" in node.column ? node.column.column.name : "*";
854
+ throw new TypeError(`${this.#where}: where is a condition on "${this.#target}", and "${table}.${column}" is of another table — read that one in a subquery: eb.exists(eb.selectFrom('${table}')…).`);
855
+ }
856
+ return super.transformReference(node, queryId);
857
+ }
858
+ };
859
+ const messageOf = (spec) => `[durable-db] related('${spec.relation.table}', '${spec.relation.name}')`;
860
+ /** ` and (<the condition>)` about the rows that go by `alias` — or nothing. */
861
+ function filter(spec, alias) {
862
+ if (!spec.where) return sql``;
863
+ const node = new Qualify(spec.relation.target, alias, messageOf(spec)).transformNode(spec.where);
864
+ return sql` and (${{ toOperationNode: () => node }})`;
865
+ }
471
866
  function render(spec, outer, depth) {
472
867
  const { relation } = spec;
473
868
  const row = `_r${depth}`;
474
869
  const pairs = spec.columns.map((column) => sql`${sql.lit(column)}, ${sql.ref(`${row}.${column}`)}`);
475
- for (const nested of spec.with) pairs.push(sql`${sql.lit(nested.relation.name)}, json(${render(nested, row, depth + 1)})`);
870
+ for (const nested of spec.with) pairs.push(sql`${sql.lit(nested.alias)}, json(${render(nested, row, depth + 1)})`);
476
871
  const object = sql`json_object(${sql.join(pairs)})`;
477
872
  const target = sql.table(relation.target);
478
873
  const matches = (alias) => sql`${sql.ref(`${alias}.${relation.foreign}`)} = ${sql.ref(`${outer}.${relation.local}`)}`;
479
874
  if (relation.kind === "one") return sql`(select ${object} from ${target} as ${sql.ref(row)} where ${matches(row)} limit 1)`;
480
- if (spec.orderBy.length === 0 && spec.limit === void 0) return sql`(select json_group_array(${object}) from ${target} as ${sql.ref(row)} where ${matches(row)})`;
875
+ if (spec.orderBy.length === 0 && spec.limit === void 0) return sql`(select json_group_array(${object}) from ${target} as ${sql.ref(row)} where ${matches(row)}${filter(spec, row)})`;
481
876
  const inner = `_s${depth}`;
482
877
  const order = spec.orderBy.length === 0 ? sql`` : sql` order by ${sql.join(spec.orderBy.map(([column, direction]) => sql`${sql.ref(`${inner}.${column}`)} ${sql.raw(direction)}`))}`;
483
878
  const limit = spec.limit === void 0 ? sql`` : sql` limit ${sql.lit(spec.limit)}`;
484
- return sql`(select json_group_array(${object}) from (select * from ${target} as ${sql.ref(inner)} where ${matches(inner)}${order}${limit}) as ${sql.ref(row)})`;
879
+ return sql`(select json_group_array(${object}) from (select * from ${target} as ${sql.ref(inner)} where ${matches(inner)}${filter(spec, inner)}${order}${limit}) as ${sql.ref(row)})`;
485
880
  }
486
881
  /**
487
882
  * A relation as a selection: what `related()` returns. `table` is the table
488
883
  * it is a relation of (so `with` takes only the related table's own), `alias`
489
- * the relation's name — the key it is answered under.
884
+ * the key it is answered under — the relation's name, until `.as()` says
885
+ * another.
490
886
  */
491
- var RelatedExpression = class {
887
+ var RelatedExpression = class RelatedExpression {
492
888
  table;
493
889
  alias;
494
890
  constructor(spec) {
495
891
  this.table = spec.relation.table;
496
- this.alias = spec.relation.name;
892
+ this.alias = spec.alias;
497
893
  specs.set(this, spec);
498
894
  }
895
+ /**
896
+ * The same relation, answered under `name` instead of its own:
897
+ * `related('customers', 'invoices', { columns: ['id'], limit: 1 }).as('latest')`.
898
+ * A new expression — this one keeps its name.
899
+ */
900
+ as(name) {
901
+ const spec = specs.get(this);
902
+ if (typeof name !== "string" || name === "") throw new TypeError(`[durable-db] related('${spec.relation.table}', '${spec.relation.name}').as() takes the name to answer it under.`);
903
+ return new RelatedExpression({
904
+ ...spec,
905
+ alias: name
906
+ });
907
+ }
499
908
  get expression() {
500
909
  return render(specs.get(this), this.table, 1);
501
910
  }
@@ -510,9 +919,9 @@ var RelatedExpression = class {
510
919
  };
511
920
  function specOf(schema, table, name, arg) {
512
921
  const relation = relationOf(schema, table, name);
513
- const where = `[durable-db] related('${table}', '${name}')`;
922
+ const where = messageOf({ relation });
514
923
  const options = Array.isArray(arg) ? { columns: arg } : arg;
515
- if (typeof options !== "object" || options === null) throw new TypeError(`${where} takes the columns to read: ['id', …], or { columns, with, orderBy, limit }.`);
924
+ if (typeof options !== "object" || options === null) throw new TypeError(`${where} takes the columns to read: ['id', …], or { columns, with, orderBy, limit, where }.`);
516
925
  const known = getTableColumns(schema[relation.target]);
517
926
  const column = (key, what) => {
518
927
  if (typeof key !== "string" || !Object.hasOwn(known, key)) throw new TypeError(`${where}: ${what} "${String(key)}" is not a column of "${relation.target}". Its columns: ${Object.keys(known).join(", ")}.`);
@@ -532,8 +941,8 @@ function specOf(schema, table, name, arg) {
532
941
  const other = spec.schema === schema ? "" : " of another database";
533
942
  throw new TypeError(`${where}: with takes relations of "${relation.target}", and "${spec.relation.name}" is one of "${spec.relation.table}"${other}.`);
534
943
  }
535
- if (names.has(spec.relation.name)) throw new TypeError(`${where}: "${spec.relation.name}" is there twice — as a column and a relation, or the relation twice.`);
536
- names.add(spec.relation.name);
944
+ if (names.has(spec.alias)) throw new TypeError(`${where}: "${spec.alias}" is there twice — as a column and a relation, or two relations under one name.`);
945
+ names.add(spec.alias);
537
946
  inner.push(spec);
538
947
  }
539
948
  if (names.size === 0) throw new TypeError(`${where} reads nothing: name the columns to read.`);
@@ -545,17 +954,32 @@ function specOf(schema, table, name, arg) {
545
954
  }
546
955
  const { limit } = options;
547
956
  if (limit !== void 0 && (!Number.isSafeInteger(limit) || limit < 0)) throw new TypeError(`${where}: limit is a whole number, 0 or more.`);
548
- if (relation.kind === "one" && (orderBy.length > 0 || limit !== void 0)) throw new TypeError(`${where} leads to one row: orderBy and limit are for a relation that leads to many.`);
957
+ if (relation.kind === "one" && (orderBy.length > 0 || limit !== void 0 || options.where !== void 0)) throw new TypeError(`${where} leads to one row: orderBy, limit and where are for a relation that leads to many.`);
958
+ let condition;
959
+ if (options.where !== void 0) {
960
+ const example = `where: (eb) => eb('<column>', '=', value)`;
961
+ if (typeof options.where !== "function") throw new TypeError(`${where}: where is a function that answers a condition — ${example}`);
962
+ const answered = options.where(expressionBuilder());
963
+ if (typeof answered !== "object" || answered === null || typeof answered.toOperationNode !== "function") throw new TypeError(`${where}: where answers a condition — ${example}`);
964
+ condition = answered.toOperationNode();
965
+ new Qualify(relation.target, relation.target, where).transformNode(condition);
966
+ }
549
967
  return {
550
968
  schema,
551
969
  relation,
970
+ alias: relation.name,
552
971
  columns,
553
972
  with: inner,
554
973
  orderBy,
555
- limit
974
+ limit,
975
+ where: condition
556
976
  };
557
977
  }
558
- /** `related` for a schema: what `defineDatabase()` hands out. */
978
+ /**
979
+ * `related` for a schema: what `defineDatabase()` hands out, and the way to
980
+ * it for code that is handed a schema — typed by the schema's tables, or by
981
+ * strings (`AnyRelated`) when its type names none.
982
+ */
559
983
  function createRelated(schema) {
560
984
  const related = (table, relation, arg) => new RelatedExpression(specOf(schema, table, relation, arg));
561
985
  return related;
@@ -586,7 +1010,8 @@ function toBoolean(value) {
586
1010
  * query as the builder made it, marks and all — and `results` last, when the
587
1011
  * row's keys are the schema's again.
588
1012
  */
589
- function createRelatedPlugins(schema) {
1013
+ function createRelatedPlugins(schema, options = {}) {
1014
+ const resultKey = options.resultKey ?? ((name) => name);
590
1015
  const selected = /* @__PURE__ */ new WeakMap();
591
1016
  const kinds = /* @__PURE__ */ new Map();
592
1017
  const kindsOf = (table) => {
@@ -594,12 +1019,14 @@ function createRelatedPlugins(schema) {
594
1019
  if (!kind) {
595
1020
  kind = {
596
1021
  dates: /* @__PURE__ */ new Set(),
597
- booleans: /* @__PURE__ */ new Set()
1022
+ booleans: /* @__PURE__ */ new Set(),
1023
+ jsons: /* @__PURE__ */ new Set()
598
1024
  };
599
1025
  const target = schema[table];
600
1026
  const columns = target ? getTableColumns(target) : {};
601
1027
  for (const [key, column] of Object.entries(columns)) if (column.dataType === "date") kind.dates.add(key);
602
1028
  else if (column.dataType === "boolean") kind.booleans.add(key);
1029
+ else if (column.dataType === "json") kind.jsons.add(key);
603
1030
  kinds.set(table, kind);
604
1031
  }
605
1032
  return kind;
@@ -607,7 +1034,7 @@ function createRelatedPlugins(schema) {
607
1034
  const revive = (value, meta) => {
608
1035
  if (Array.isArray(value)) return value.map((item) => revive(item, meta));
609
1036
  if (typeof value !== "object" || value === null) return value;
610
- const { dates, booleans } = kindsOf(meta.target);
1037
+ const { dates, booleans, jsons } = kindsOf(meta.target);
611
1038
  const row = value;
612
1039
  for (const [key, item] of Object.entries(row)) {
613
1040
  const nested = meta.with.get(key);
@@ -615,6 +1042,7 @@ function createRelatedPlugins(schema) {
615
1042
  else if (dates.has(key)) {
616
1043
  if (typeof item === "string" && dateSerializers.isSerializedDateString(item)) row[key] = dateSerializers.deserialize(item);
617
1044
  } else if (booleans.has(key)) row[key] = toBoolean(item);
1045
+ else if (jsons.has(key)) row[key] = parseJsonValue(item);
618
1046
  }
619
1047
  return row;
620
1048
  };
@@ -638,9 +1066,14 @@ function createRelatedPlugins(schema) {
638
1066
  if (!relations) return result;
639
1067
  const rows = result.rows.map((row) => {
640
1068
  const out = { ...row };
641
- for (const [key, meta] of relations) {
642
- const raw = out[key];
643
- if (typeof raw === "string") out[key] = revive(JSON.parse(raw), meta);
1069
+ for (const [alias, meta] of relations) {
1070
+ const key = resultKey(alias);
1071
+ if (key !== alias && Object.hasOwn(out, key)) {
1072
+ out[alias] = out[key];
1073
+ delete out[key];
1074
+ }
1075
+ const raw = out[alias];
1076
+ if (typeof raw === "string") out[alias] = revive(JSON.parse(raw), meta);
644
1077
  }
645
1078
  return out;
646
1079
  });
@@ -764,4 +1197,4 @@ function defineDatabase(config) {
764
1197
  };
765
1198
  }
766
1199
  //#endregion
767
- export { createRelatedPlugins as a, SchemaPlugin as c, relationOf as d, relationsOf as f, RelatedExpression as i, createDrizzlePlugins as l, defineDatabase as n, DateSerializePlugin as o, liveTestDatabases as r, DrizzleDefaultsPlugin as s, ACTION_TEST_META as t, dateSerializers as u };
1200
+ export { createRelated as a, DrizzleDefaultsPlugin as c, createJsonPlugins as d, dateSerializers as f, relationsOf as h, RelatedExpression as i, SchemaPlugin as l, relationOf as m, defineDatabase as n, createRelatedPlugins as o, parseJsonValue as p, liveTestDatabases as r, DateSerializePlugin as s, ACTION_TEST_META as t, createDrizzlePlugins as u };