@orkestrel/relation 0.0.18 → 0.0.20

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.
@@ -82,6 +82,33 @@ function isRelationDescriptor(value) {
82
82
  }
83
83
  // src/core/helpers.ts
84
84
  /**
85
+ * Validates a relation table through its bound storage, translating only an undeclared table.
86
+ *
87
+ * @param storage - The storage that resolves the table
88
+ * @param model - The owning model's name
89
+ * @param relation - The relation's name
90
+ * @param table - The target or junction table's name
91
+ * @param junction - If `true`, reports an undeclared junction; if `false`, reports an undeclared target. Default: `false`.
92
+ * @throws An `INVALID` {@link RelationError} for an undeclared table; every other storage error propagates unchanged.
93
+ *
94
+ * @example
95
+ * ```ts
96
+ * validateRelationTable(storage, 'accounts', 'contacts', 'contacts')
97
+ * ```
98
+ */
99
+ function validateRelationTable(storage, model, relation, table, junction = false) {
100
+ try {
101
+ storage.table(table);
102
+ } catch (error) {
103
+ if (!(0, _orkestrel_database.isDatabaseError)(error) || error.code !== "NOT_FOUND") throw error;
104
+ throw new RelationError("INVALID", `Model '${model}' relation '${relation}' ${junction ? "uses undeclared junction" : "targets undeclared table"} '${table}'`, {
105
+ model,
106
+ relation,
107
+ table
108
+ });
109
+ }
110
+ }
111
+ /**
85
112
  * Resolves one raw {@link Relation} value into a flat {@link ResolvedRelation}.
86
113
  *
87
114
  * @remarks
@@ -232,9 +259,11 @@ function countAttached(values) {
232
259
  * row already holds replaces it, and a row missing the column indexes under the string
233
260
  * `'undefined'`. This is the projection a `belongs` load and a `through` load use to
234
261
  * attach one related row per key.
262
+ * Optional `values` supply the attached rows by position; keys always come from `rows`.
235
263
  *
236
264
  * @param rows - The rows to index
237
265
  * @param column - The column to key on
266
+ * @param values - The rows to attach by position. Default: `rows`. Missing positions are omitted.
238
267
  * @returns A read-only map from each key's string form to its row
239
268
  *
240
269
  * @example
@@ -242,8 +271,11 @@ function countAttached(values) {
242
271
  * indexRows([{ id: 'r1' }, { id: 'r2' }], 'id').get('r1') // { id: 'r1' }
243
272
  * ```
244
273
  */
245
- function indexRows(rows, column) {
246
- return new Map(Iterator.from(rows).map((row) => [String(readColumn(row, column)), row]));
274
+ function indexRows(rows, column, values = rows) {
275
+ return new Map(Iterator.from(rows).flatMap((row, index) => {
276
+ const value = values[index];
277
+ return value === void 0 ? [] : [[String(readColumn(row, column)), value]];
278
+ }));
247
279
  }
248
280
  /**
249
281
  * Groups rows by the string form of one column, for one-to-many lookups.
@@ -254,9 +286,11 @@ function indexRows(rows, column) {
254
286
  * a group, a key no row carries is absent rather than empty, and a row missing the
255
287
  * column groups under the string `'undefined'`. This is the projection a `many` load
256
288
  * and a `morph` load use to attach every related row per key.
289
+ * Optional `values` supply the attached rows by position; keys always come from `rows`.
257
290
  *
258
291
  * @param rows - The rows to group
259
292
  * @param column - The column to key on
293
+ * @param values - The rows to attach by position. Default: `rows`. Missing positions are omitted.
260
294
  * @returns A read-only map from each key's string form to its rows, in input order
261
295
  *
262
296
  * @example
@@ -264,13 +298,15 @@ function indexRows(rows, column) {
264
298
  * groupRows([{ author: 'u1' }, { author: 'u1' }], 'author').get('u1')?.length // 2
265
299
  * ```
266
300
  */
267
- function groupRows(rows, column) {
301
+ function groupRows(rows, column, values = rows) {
268
302
  const groups = /* @__PURE__ */ new Map();
269
- for (const row of rows) {
303
+ for (const [index, row] of rows.entries()) {
304
+ const value = values[index];
305
+ if (value === void 0) continue;
270
306
  const key = String(readColumn(row, column));
271
307
  const group = groups.get(key);
272
- if (group !== void 0) group.push(row);
273
- else groups.set(key, [row]);
308
+ if (group !== void 0) group.push(value);
309
+ else groups.set(key, [value]);
274
310
  }
275
311
  return groups;
276
312
  }
@@ -376,7 +412,7 @@ function hasMorph(key, tag, label, model) {
376
412
  *
377
413
  * @remarks
378
414
  * The model's own table is fully typed (`table`); related tables are reached by
379
- * runtime name through the database at the broad `Row` type. Loading is batched:
415
+ * runtime name through the bound storage at the broad `Row` type. Loading is batched:
380
416
  * a direct relation uses one query for the whole record set, while a `through`
381
417
  * relation uses two (junction then target); both counts remain constant regardless
382
418
  * of parent count. Nested includes recurse through the registry `lookup`, so each
@@ -400,11 +436,11 @@ function hasMorph(key, tag, label, model) {
400
436
  * const relations = { posts: hasMany('author') }
401
437
  * const users = new Model(
402
438
  * 'users',
403
- * database.table('users'),
439
+ * storage.table('users'),
404
440
  * resolveRelationMap(relations),
405
441
  * relations,
406
442
  * () => undefined,
407
- * database,
443
+ * storage,
408
444
  * )
409
445
  * users.emitter.on('load', (name, count) => metrics.record(`relation.${name}`, count))
410
446
  * const ada = await users.load('u1', { posts: true })
@@ -416,29 +452,32 @@ var Model = class {
416
452
  #resolved;
417
453
  #relations;
418
454
  #lookup;
419
- #database;
455
+ #storage;
420
456
  #emitter;
421
457
  /**
422
458
  * Constructs a model over one table and its resolved relations.
423
459
  *
424
460
  * @param name - The model's table name
425
- * @param table - The typed table this model's own reads and writes go through
461
+ * @param table - The typed table this model's own reads and writes go through; take it
462
+ * from `storage` so both belong to one scope, as `RelationManager` does
463
+ * (a root table read inside a transaction refuses with `CONFLICT`)
426
464
  * @param resolved - The model's relations, resolved by `resolveRelationMap`
427
465
  * @param relations - The raw relation map the resolved relations came from
428
466
  * @param lookup - Reads a related model's {@link RelationContext} for a nested include,
429
- * and returns `undefined` for a model the registry does not hold
430
- * @param database - The broad database used to read related and junction tables by name
467
+ * and returns `undefined` for a model the registry does not hold; its contexts must
468
+ * resolve through the same `storage`
469
+ * @param storage - The broad storage used to read related and junction tables by name
431
470
  * @param on - Initial {@link ModelEventMap} listeners
432
471
  * @param error - Receives a listener throw as `(error, event)`. Default: the throw is
433
472
  * swallowed.
434
473
  */
435
- constructor(name, table, resolved, relations, lookup, database, on, error) {
474
+ constructor(name, table, resolved, relations, lookup, storage, on, error) {
436
475
  this.#name = name;
437
476
  this.#table = table;
438
477
  this.#resolved = resolved;
439
478
  this.#relations = relations;
440
479
  this.#lookup = lookup;
441
- this.#database = database;
480
+ this.#storage = storage;
442
481
  this.#emitter = new _orkestrel_emitter.Emitter({
443
482
  ...on !== void 0 ? { on } : {},
444
483
  ...error !== void 0 ? { error } : {}
@@ -485,7 +524,7 @@ var Model = class {
485
524
  async link(key, relation, target, options) {
486
525
  (0, _orkestrel_database.checkAbort)(options?.signal);
487
526
  const resolved = this.#through(relation);
488
- const junction = this.#database.table(resolved.through);
527
+ const junction = this.#storage.table(resolved.through);
489
528
  if (await junction.count({ conditions: [{
490
529
  column: resolved.source,
491
530
  operator: "equals",
@@ -506,7 +545,7 @@ var Model = class {
506
545
  async unlink(key, relation, target, options) {
507
546
  (0, _orkestrel_database.checkAbort)(options?.signal);
508
547
  const resolved = this.#through(relation);
509
- const junction = this.#database.table(resolved.through);
548
+ const junction = this.#storage.table(resolved.through);
510
549
  const rows = await junction.records({ conditions: [{
511
550
  column: resolved.source,
512
551
  operator: "equals",
@@ -518,19 +557,16 @@ var Model = class {
518
557
  values: [target],
519
558
  connector: "and"
520
559
  }] }, options);
521
- await this.#database.transaction(async (transaction) => {
522
- const scoped = transaction.table(resolved.through);
523
- for (const row of rows) {
524
- const id = (0, _orkestrel_database.extractKey)(row, junction.primary);
525
- if (id !== void 0) await scoped.remove(id, options);
526
- }
527
- }, options);
560
+ for (const row of rows) {
561
+ const id = (0, _orkestrel_database.extractKey)(row, junction.primary);
562
+ if (id !== void 0) await junction.remove(id, options);
563
+ }
528
564
  this.#emitter.emit("unlink", key, relation);
529
565
  }
530
566
  async links(key, relation, options) {
531
567
  (0, _orkestrel_database.checkAbort)(options?.signal);
532
568
  const resolved = this.#through(relation);
533
- const rows = await this.#database.table(resolved.through).records({ conditions: [{
569
+ const rows = await this.#storage.table(resolved.through).records({ conditions: [{
534
570
  column: resolved.source,
535
571
  operator: "equals",
536
572
  values: [key],
@@ -586,14 +622,14 @@ var Model = class {
586
622
  const column = resolved.column;
587
623
  const keys = [...new Set(records.map((record) => readColumn(record, column)).filter(_orkestrel_contract.isDefined))];
588
624
  if (keys.length === 0) return records.map(() => void 0);
589
- const related = this.#database.table(resolved.model);
625
+ const related = this.#storage.table(resolved.model);
590
626
  const rows = await related.records({ conditions: [{
591
627
  column: related.primary,
592
628
  operator: "any",
593
629
  values: keys,
594
630
  connector: "and"
595
631
  }] }, options);
596
- const index = indexRows(await this.#nest(resolved.model, rows, sub, options), related.primary);
632
+ const index = indexRows(rows, related.primary, await this.#nest(resolved.model, rows, sub, options));
597
633
  return records.map((record) => {
598
634
  const fk = readColumn(record, column);
599
635
  return (0, _orkestrel_contract.isDefined)(fk) ? index.get(String(fk)) : void 0;
@@ -603,13 +639,13 @@ var Model = class {
603
639
  const foreign = resolved.key;
604
640
  const keys = [...new Set(records.map((record) => readColumn(record, primary)).filter(_orkestrel_contract.isDefined))];
605
641
  if (keys.length === 0) return records.map(() => []);
606
- const rows = await this.#database.table(resolved.model).records({ conditions: [{
642
+ const rows = await this.#storage.table(resolved.model).records({ conditions: [{
607
643
  column: foreign,
608
644
  operator: "any",
609
645
  values: keys,
610
646
  connector: "and"
611
647
  }] }, options);
612
- const groups = groupRows(await this.#nest(resolved.model, rows, sub, options), foreign);
648
+ const groups = groupRows(rows, foreign, await this.#nest(resolved.model, rows, sub, options));
613
649
  return records.map((record) => groups.get(String(readColumn(record, primary))) ?? []);
614
650
  }
615
651
  async #loadOne(records, resolved, sub, primary, options) {
@@ -620,7 +656,7 @@ var Model = class {
620
656
  const target = resolved.target;
621
657
  const parents = [...new Set(records.map((record) => readColumn(record, primary)).filter(_orkestrel_contract.isDefined))];
622
658
  if (parents.length === 0) return records.map(() => []);
623
- const junctions = await this.#database.table(resolved.through).records({ conditions: [{
659
+ const junctions = await this.#storage.table(resolved.through).records({ conditions: [{
624
660
  column: source,
625
661
  operator: "any",
626
662
  values: parents,
@@ -637,14 +673,14 @@ var Model = class {
637
673
  }
638
674
  const targets = [...new Set([...targetsBySource.values()].flat())];
639
675
  if (targets.length === 0) return records.map(() => []);
640
- const related = this.#database.table(resolved.model);
676
+ const related = this.#storage.table(resolved.model);
641
677
  const rows = await related.records({ conditions: [{
642
678
  column: related.primary,
643
679
  operator: "any",
644
680
  values: targets,
645
681
  connector: "and"
646
682
  }] }, options);
647
- const index = indexRows(await this.#nest(resolved.model, rows, sub, options), related.primary);
683
+ const index = indexRows(rows, related.primary, await this.#nest(resolved.model, rows, sub, options));
648
684
  return records.map((record) => {
649
685
  const out = [];
650
686
  for (const value of targetsBySource.get(String(readColumn(record, primary))) ?? []) {
@@ -658,7 +694,7 @@ var Model = class {
658
694
  const foreign = resolved.key;
659
695
  const keys = [...new Set(records.map((record) => readColumn(record, primary)).filter(_orkestrel_contract.isDefined))];
660
696
  if (keys.length === 0) return records.map(() => []);
661
- const rows = await this.#database.table(resolved.model).records({ conditions: [{
697
+ const rows = await this.#storage.table(resolved.model).records({ conditions: [{
662
698
  column: foreign,
663
699
  operator: "any",
664
700
  values: keys,
@@ -669,7 +705,7 @@ var Model = class {
669
705
  values: [resolved.label],
670
706
  connector: "and"
671
707
  }] }, options);
672
- const groups = groupRows(await this.#nest(resolved.model, rows, sub, options), foreign);
708
+ const groups = groupRows(rows, foreign, await this.#nest(resolved.model, rows, sub, options));
673
709
  return records.map((record) => groups.get(String(readColumn(record, primary))) ?? []);
674
710
  }
675
711
  async #nest(model, rows, sub, options) {
@@ -686,8 +722,8 @@ var Model = class {
686
722
  * {@link ModelInterface} per declared table.
687
723
  *
688
724
  * @remarks
689
- * Holds the database both at its precise type (to type each model's own table)
690
- * and at the broad `DatabaseInterface` (to fetch related tables by runtime name
725
+ * Holds storage both at its precise type (to type each model's own table)
726
+ * and at the broad `DatabaseStorageInterface` (to fetch related tables by runtime name
691
727
  * while loading). Construction validates every target and junction against the
692
728
  * database's declared tables, so invalid definitions fail before an operation runs.
693
729
  * The `model` option's `on` and `error` are threaded into every model vended, and
@@ -698,8 +734,8 @@ var Model = class {
698
734
  * ```ts
699
735
  * import { RelationManager, hasMany } from '@orkestrel/relation'
700
736
  *
701
- * const manager = new RelationManager({
702
- * database,
737
+ * const manager = new RelationManager<typeof TABLES>({
738
+ * storage: database,
703
739
  * relations: { users: { posts: hasMany('author') } },
704
740
  * model: { on: { load: (name, count) => metrics.record(`relation.${name}`, count) } },
705
741
  * })
@@ -708,39 +744,30 @@ var Model = class {
708
744
  * ```
709
745
  */
710
746
  var RelationManager = class {
711
- #database;
747
+ #storage;
712
748
  #broad;
713
749
  #relations;
714
750
  #model;
715
751
  #resolved = /* @__PURE__ */ new Map();
716
752
  /**
717
- * Constructs a registry over a database and its relation definitions.
753
+ * Constructs a registry over storage and its relation definitions.
718
754
  *
719
- * @param options - The `database`, an optional `relations` map, and the optional
755
+ * @param options - The `storage`, an optional `relations` map, and the optional
720
756
  * `model` emitter settings threaded into every model vended
721
757
  * @throws An `INVALID` {@link RelationError} when a relation targets a table or a
722
758
  * junction the database does not declare
723
759
  */
724
760
  constructor(options) {
725
- this.#database = options.database;
726
- this.#broad = options.database;
761
+ this.#storage = options.storage;
762
+ this.#broad = options.storage;
727
763
  this.#relations = options.relations ?? {};
728
764
  this.#model = options.model;
729
- const declared = new Set(Object.keys(this.#broad.export()));
730
765
  for (const [name, map] of Object.entries(this.#relations)) {
731
766
  if (map === void 0) continue;
732
767
  const resolved = resolveRelationMap(map);
733
768
  for (const [relation, entry] of resolved) {
734
- if (!declared.has(entry.model)) throw new RelationError("INVALID", `Model '${name}' relation '${relation}' targets undeclared table '${entry.model}'`, {
735
- model: name,
736
- relation,
737
- table: entry.model
738
- });
739
- if (entry.relationship === "through" && !declared.has(entry.through)) throw new RelationError("INVALID", `Model '${name}' relation '${relation}' uses undeclared junction '${entry.through}'`, {
740
- model: name,
741
- relation,
742
- table: entry.through
743
- });
769
+ validateRelationTable(this.#broad, name, relation, entry.model);
770
+ if (entry.relationship === "through") validateRelationTable(this.#broad, name, relation, entry.through, true);
744
771
  }
745
772
  this.#resolved.set(name, resolved);
746
773
  }
@@ -751,7 +778,7 @@ var RelationManager = class {
751
778
  model(name) {
752
779
  const resolved = this.#resolved.get(name) ?? /* @__PURE__ */ new Map();
753
780
  const relations = this.#relations[name] ?? {};
754
- return this.#vend(name, this.#database.table(name), resolved, relations);
781
+ return this.#vend(name, this.#storage.table(name), resolved, relations);
755
782
  }
756
783
  names() {
757
784
  return [...this.#resolved.keys()];
@@ -773,7 +800,7 @@ var RelationManager = class {
773
800
  };
774
801
  // src/core/factories.ts
775
802
  /**
776
- * Creates a {@link RelationManagerInterface} over a database and its relation map.
803
+ * Creates a {@link RelationManagerInterface} over storage and its relation map.
777
804
  *
778
805
  * @remarks
779
806
  * `relations` maps table names (constrained to the database's tables) to their
@@ -781,7 +808,9 @@ var RelationManager = class {
781
808
  * `hasThrough` / `hasMorph`. `manager.model(name)` returns the typed model for a
782
809
  * table — its own table is fully typed, related rows load at the `Row` type.
783
810
  *
784
- * @param options - The `database` and an optional `relations` map
811
+ * At a typed root, pass the table map as the type argument. Transaction storage infers it.
812
+ *
813
+ * @param options - The `storage` and an optional `relations` map
785
814
  * @returns A typed {@link RelationManagerInterface}
786
815
  *
787
816
  * @example Defining relations
@@ -795,8 +824,8 @@ var RelationManager = class {
795
824
  * hasMorph,
796
825
  * } from '@orkestrel/relation'
797
826
  *
798
- * const manager = createRelationManager({
799
- * database: db,
827
+ * const manager = createRelationManager<typeof TABLES>({
828
+ * storage: db,
800
829
  * relations: {
801
830
  * accounts: {
802
831
  * classification: belongsTo('classificationId', 'classifications'), // foreign key on accounts
@@ -832,5 +861,6 @@ exports.isRelationError = isRelationError;
832
861
  exports.readColumn = readColumn;
833
862
  exports.resolveRelation = resolveRelation;
834
863
  exports.resolveRelationMap = resolveRelationMap;
864
+ exports.validateRelationTable = validateRelationTable;
835
865
 
836
866
  //# sourceMappingURL=index.cjs.map