@orkestrel/relation 0.0.19 → 0.0.21

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.
@@ -1,4 +1,4 @@
1
- import type { DatabaseInterface } from '@orkestrel/database';
1
+ import type { DatabaseStorageInterface } from '@orkestrel/database';
2
2
  import type { EmitterErrorHandler } from '@orkestrel/emitter';
3
3
  import type { EmitterHooks } from '@orkestrel/emitter';
4
4
  import type { EmitterInterface } from '@orkestrel/emitter';
@@ -44,7 +44,7 @@ export declare function belongsTo(column: string, model?: string): RelationDescr
44
44
  export declare function countAttached(values: ReadonlyArray<Row | readonly Row[] | undefined>): number;
45
45
 
46
46
  /**
47
- * Creates a {@link RelationManagerInterface} over a database and its relation map.
47
+ * Creates a {@link RelationManagerInterface} over storage and its relation map.
48
48
  *
49
49
  * @remarks
50
50
  * `relations` maps table names (constrained to the database's tables) to their
@@ -52,7 +52,9 @@ export declare function countAttached(values: ReadonlyArray<Row | readonly Row[]
52
52
  * `hasThrough` / `hasMorph`. `manager.model(name)` returns the typed model for a
53
53
  * table — its own table is fully typed, related rows load at the `Row` type.
54
54
  *
55
- * @param options - The `database` and an optional `relations` map
55
+ * At a typed root, pass the table map as the type argument. Transaction storage infers it.
56
+ *
57
+ * @param options - The `storage` and an optional `relations` map
56
58
  * @returns A typed {@link RelationManagerInterface}
57
59
  *
58
60
  * @example Defining relations
@@ -66,8 +68,8 @@ export declare function countAttached(values: ReadonlyArray<Row | readonly Row[]
66
68
  * hasMorph,
67
69
  * } from '@orkestrel/relation'
68
70
  *
69
- * const manager = createRelationManager({
70
- * database: db,
71
+ * const manager = createRelationManager<typeof TABLES>({
72
+ * storage: db,
71
73
  * relations: {
72
74
  * accounts: {
73
75
  * classification: belongsTo('classificationId', 'classifications'), // foreign key on accounts
@@ -103,9 +105,11 @@ export declare interface FindOptions extends OperationOptions {
103
105
  * a group, a key no row carries is absent rather than empty, and a row missing the
104
106
  * column groups under the string `'undefined'`. This is the projection a `many` load
105
107
  * and a `morph` load use to attach every related row per key.
108
+ * Optional `values` supply the attached rows by position; keys always come from `rows`.
106
109
  *
107
110
  * @param rows - The rows to group
108
111
  * @param column - The column to key on
112
+ * @param values - The rows to attach by position. Default: `rows`. Missing positions are omitted.
109
113
  * @returns A read-only map from each key's string form to its rows, in input order
110
114
  *
111
115
  * @example
@@ -113,7 +117,7 @@ export declare interface FindOptions extends OperationOptions {
113
117
  * groupRows([{ author: 'u1' }, { author: 'u1' }], 'author').get('u1')?.length // 2
114
118
  * ```
115
119
  */
116
- export declare function groupRows(rows: readonly Row[], column: string): ReadonlyMap<string, readonly Row[]>;
120
+ export declare function groupRows(rows: readonly Row[], column: string, values?: readonly Row[]): ReadonlyMap<string, readonly Row[]>;
117
121
 
118
122
  /**
119
123
  * Builds a `many` relation — a foreign key on the related table points back at the owning row
@@ -192,9 +196,11 @@ export declare interface Include {
192
196
  * row already holds replaces it, and a row missing the column indexes under the string
193
197
  * `'undefined'`. This is the projection a `belongs` load and a `through` load use to
194
198
  * attach one related row per key.
199
+ * Optional `values` supply the attached rows by position; keys always come from `rows`.
195
200
  *
196
201
  * @param rows - The rows to index
197
202
  * @param column - The column to key on
203
+ * @param values - The rows to attach by position. Default: `rows`. Missing positions are omitted.
198
204
  * @returns A read-only map from each key's string form to its row
199
205
  *
200
206
  * @example
@@ -202,7 +208,7 @@ export declare interface Include {
202
208
  * indexRows([{ id: 'r1' }, { id: 'r2' }], 'id').get('r1') // { id: 'r1' }
203
209
  * ```
204
210
  */
205
- export declare function indexRows(rows: readonly Row[], column: string): ReadonlyMap<string, Row>;
211
+ export declare function indexRows(rows: readonly Row[], column: string, values?: readonly Row[]): ReadonlyMap<string, Row>;
206
212
 
207
213
  /**
208
214
  * Narrows a value to a {@link RelationDescriptor} (the object form of a relation).
@@ -265,7 +271,7 @@ export declare type LoadedMap = Record<string, Row | readonly Row[] | undefined>
265
271
  *
266
272
  * @remarks
267
273
  * The model's own table is fully typed (`table`); related tables are reached by
268
- * runtime name through the database at the broad `Row` type. Loading is batched:
274
+ * runtime name through the bound storage at the broad `Row` type. Loading is batched:
269
275
  * a direct relation uses one query for the whole record set, while a `through`
270
276
  * relation uses two (junction then target); both counts remain constant regardless
271
277
  * of parent count. Nested includes recurse through the registry `lookup`, so each
@@ -289,11 +295,11 @@ export declare type LoadedMap = Record<string, Row | readonly Row[] | undefined>
289
295
  * const relations = { posts: hasMany('author') }
290
296
  * const users = new Model(
291
297
  * 'users',
292
- * database.table('users'),
298
+ * storage.table('users'),
293
299
  * resolveRelationMap(relations),
294
300
  * relations,
295
301
  * () => undefined,
296
- * database,
302
+ * storage,
297
303
  * )
298
304
  * users.emitter.on('load', (name, count) => metrics.record(`relation.${name}`, count))
299
305
  * const ada = await users.load('u1', { posts: true })
@@ -305,17 +311,20 @@ export declare class Model<T = Row> implements ModelInterface<T> {
305
311
  * Constructs a model over one table and its resolved relations.
306
312
  *
307
313
  * @param name - The model's table name
308
- * @param table - The typed table this model's own reads and writes go through
314
+ * @param table - The typed table this model's own reads and writes go through; take it
315
+ * from `storage` so both belong to one scope, as `RelationManager` does
316
+ * (a root table read inside a transaction refuses with `CONFLICT`)
309
317
  * @param resolved - The model's relations, resolved by `resolveRelationMap`
310
318
  * @param relations - The raw relation map the resolved relations came from
311
319
  * @param lookup - Reads a related model's {@link RelationContext} for a nested include,
312
- * and returns `undefined` for a model the registry does not hold
313
- * @param database - The broad database used to read related and junction tables by name
320
+ * and returns `undefined` for a model the registry does not hold; its contexts must
321
+ * resolve through the same `storage`
322
+ * @param storage - The broad storage used to read related and junction tables by name
314
323
  * @param on - Initial {@link ModelEventMap} listeners
315
324
  * @param error - Receives a listener throw as `(error, event)`. Default: the throw is
316
325
  * swallowed.
317
326
  */
318
- constructor(name: string, table: TableInterface<T>, resolved: ReadonlyMap<string, ResolvedRelation>, relations: RelationMap, lookup: (model: string) => RelationContext | undefined, database: DatabaseInterface, on?: EmitterHooks<ModelEventMap>, error?: EmitterErrorHandler);
327
+ constructor(name: string, table: TableInterface<T>, resolved: ReadonlyMap<string, ResolvedRelation>, relations: RelationMap, lookup: (model: string) => RelationContext | undefined, storage: DatabaseStorageInterface, on?: EmitterHooks<ModelEventMap>, error?: EmitterErrorHandler);
319
328
  get emitter(): EmitterInterface<ModelEventMap>;
320
329
  get name(): string;
321
330
  get table(): TableInterface<T>;
@@ -337,8 +346,8 @@ export declare class Model<T = Row> implements ModelInterface<T> {
337
346
  * `load` fires once per relation that an eager-load resolves, carrying the relation name +
338
347
  * the count of related rows attached for the whole record set (it is the batched load
339
348
  * moment, not one event per record — there is no N+1 in the events either). `link` /
340
- * `unlink` fire after a junction row is inserted / removed, carrying the owning key + the
341
- * relation name. Listener isolation is the emitter's: every event is emitted
349
+ * `unlink` fire after the junction operation completes within the bound scope and before
350
+ * any outer commit, carrying the owning key + the relation name. Listener isolation is the emitter's: every event is emitted
342
351
  * directly and a listener throw is routed to the emitter's `error` handler (the `error`
343
352
  * option), never onto this map, and sits strictly after the load resolves / the junction op
344
353
  * completes — so a throwing observer can never corrupt the eager-load batching or a
@@ -381,8 +390,7 @@ export declare type ModelEventMap = {
381
390
  * moments ({@link ModelEventMap}) for fire-and-forget observers — emitting is
382
391
  * observation-only (a swallowed listener throw can never corrupt the batched load).
383
392
  * `link` is idempotent for sequential calls: an existing pair writes nothing and
384
- * emits nothing. `unlink` removes matching junction rows inside one database
385
- * transaction, so a fault rolls the removal back.
393
+ * emits nothing. `unlink` shares the atomicity of the bound storage's scope.
386
394
  */
387
395
  export declare interface ModelInterface<T = Row> {
388
396
  readonly emitter: EmitterInterface<ModelEventMap>;
@@ -430,7 +438,11 @@ export declare interface ModelInterface<T = Row> {
430
438
  */
431
439
  link(key: Key, relation: string, target: Key, options?: OperationOptions): Promise<void>;
432
440
  /**
433
- * Removes every matching junction row for a `through` relation inside one transaction.
441
+ * Removes every matching junction row for a `through` relation through the bound storage.
442
+ *
443
+ * @remarks
444
+ * Atomicity is the enclosing scope's: enclose the call in `database.transaction()` for
445
+ * all-or-nothing removal; outside one, a fault leaves the removals made before it.
434
446
  *
435
447
  * @param key - The owning record's primary key
436
448
  * @param relation - The `through` relation's name
@@ -544,8 +556,8 @@ export declare type RelationErrorCode = 'INVALID' | 'UNKNOWN_RELATION' | 'NOT_TH
544
556
  * {@link ModelInterface} per declared table.
545
557
  *
546
558
  * @remarks
547
- * Holds the database both at its precise type (to type each model's own table)
548
- * and at the broad `DatabaseInterface` (to fetch related tables by runtime name
559
+ * Holds storage both at its precise type (to type each model's own table)
560
+ * and at the broad `DatabaseStorageInterface` (to fetch related tables by runtime name
549
561
  * while loading). Construction validates every target and junction against the
550
562
  * database's declared tables, so invalid definitions fail before an operation runs.
551
563
  * The `model` option's `on` and `error` are threaded into every model vended, and
@@ -556,8 +568,8 @@ export declare type RelationErrorCode = 'INVALID' | 'UNKNOWN_RELATION' | 'NOT_TH
556
568
  * ```ts
557
569
  * import { RelationManager, hasMany } from '@orkestrel/relation'
558
570
  *
559
- * const manager = new RelationManager({
560
- * database,
571
+ * const manager = new RelationManager<typeof TABLES>({
572
+ * storage: database,
561
573
  * relations: { users: { posts: hasMany('author') } },
562
574
  * model: { on: { load: (name, count) => metrics.record(`relation.${name}`, count) } },
563
575
  * })
@@ -568,9 +580,9 @@ export declare type RelationErrorCode = 'INVALID' | 'UNKNOWN_RELATION' | 'NOT_TH
568
580
  export declare class RelationManager<T extends TableMap = TableMap> implements RelationManagerInterface<T> {
569
581
  #private;
570
582
  /**
571
- * Constructs a registry over a database and its relation definitions.
583
+ * Constructs a registry over storage and its relation definitions.
572
584
  *
573
- * @param options - The `database`, an optional `relations` map, and the optional
585
+ * @param options - The `storage`, an optional `relations` map, and the optional
574
586
  * `model` emitter settings threaded into every model vended
575
587
  * @throws An `INVALID` {@link RelationError} when a relation targets a table or a
576
588
  * junction the database does not declare
@@ -632,14 +644,16 @@ export declare interface RelationManagerInterface<T extends TableMap = TableMap>
632
644
  */
633
645
  export declare interface RelationManagerOptions<T extends TableMap = TableMap> {
634
646
  /**
635
- * Holds the database to build the registry over.
647
+ * Holds the storage the registry resolves tables through: a database, or the storage a transaction scope supplies.
636
648
  *
637
649
  * @remarks
638
- * Intersected with the broad `DatabaseInterface` so the manager gets both the
639
- * precise view (typing each declared table for `model()`) and the broad view
640
- * (runtime table lookup by name while resolving relations).
650
+ * Intersected with the broad `DatabaseStorageInterface` so `model()` types each
651
+ * declared table and loaders look related tables up by runtime name. A manager over
652
+ * transaction storage belongs to that callback; its models and tables throw `CONFLICT`
653
+ * after settlement. Construction resolves every relation target and junction through
654
+ * `table()`; an undeclared one throws `INVALID`, and every other storage error propagates unchanged.
641
655
  */
642
- readonly database: DatabaseInterface<T> & DatabaseInterface;
656
+ readonly storage: DatabaseStorageInterface<T> & DatabaseStorageInterface;
643
657
  readonly relations?: RelationsShape<T>;
644
658
  readonly model?: {
645
659
  readonly on?: EmitterHooks<ModelEventMap>;
@@ -791,4 +805,21 @@ export declare function resolveRelation(name: string, value: Relation): Resolved
791
805
  */
792
806
  export declare function resolveRelationMap(relations: RelationMap): ReadonlyMap<string, ResolvedRelation>;
793
807
 
808
+ /**
809
+ * Validates a relation table through its bound storage, translating only an undeclared table.
810
+ *
811
+ * @param storage - The storage that resolves the table
812
+ * @param model - The owning model's name
813
+ * @param relation - The relation's name
814
+ * @param table - The target or junction table's name
815
+ * @param junction - If `true`, reports an undeclared junction; if `false`, reports an undeclared target. Default: `false`.
816
+ * @throws An `INVALID` {@link RelationError} for an undeclared table; every other storage error propagates unchanged.
817
+ *
818
+ * @example
819
+ * ```ts
820
+ * validateRelationTable(storage, 'accounts', 'contacts', 'contacts')
821
+ * ```
822
+ */
823
+ export declare function validateRelationTable(storage: DatabaseStorageInterface, model: string, relation: string, table: string, junction?: boolean): void;
824
+
794
825
  export { }
@@ -1,5 +1,5 @@
1
1
  import { INTRINSICS, holds, isArray, isBoolean, isDefined, isFunction, isObject, isRecord, isString, literalOf } from "@orkestrel/contract";
2
- import { checkAbort, extractKey } from "@orkestrel/database";
2
+ import { checkAbort, extractKey, isDatabaseError } from "@orkestrel/database";
3
3
  import { Emitter } from "@orkestrel/emitter";
4
4
  // src/core/errors.ts
5
5
  /**
@@ -81,6 +81,33 @@ function isRelationDescriptor(value) {
81
81
  }
82
82
  // src/core/helpers.ts
83
83
  /**
84
+ * Validates a relation table through its bound storage, translating only an undeclared table.
85
+ *
86
+ * @param storage - The storage that resolves the table
87
+ * @param model - The owning model's name
88
+ * @param relation - The relation's name
89
+ * @param table - The target or junction table's name
90
+ * @param junction - If `true`, reports an undeclared junction; if `false`, reports an undeclared target. Default: `false`.
91
+ * @throws An `INVALID` {@link RelationError} for an undeclared table; every other storage error propagates unchanged.
92
+ *
93
+ * @example
94
+ * ```ts
95
+ * validateRelationTable(storage, 'accounts', 'contacts', 'contacts')
96
+ * ```
97
+ */
98
+ function validateRelationTable(storage, model, relation, table, junction = false) {
99
+ try {
100
+ storage.table(table);
101
+ } catch (error) {
102
+ if (!isDatabaseError(error) || error.code !== "NOT_FOUND") throw error;
103
+ throw new RelationError("INVALID", `Model '${model}' relation '${relation}' ${junction ? "uses undeclared junction" : "targets undeclared table"} '${table}'`, {
104
+ model,
105
+ relation,
106
+ table
107
+ });
108
+ }
109
+ }
110
+ /**
84
111
  * Resolves one raw {@link Relation} value into a flat {@link ResolvedRelation}.
85
112
  *
86
113
  * @remarks
@@ -231,9 +258,11 @@ function countAttached(values) {
231
258
  * row already holds replaces it, and a row missing the column indexes under the string
232
259
  * `'undefined'`. This is the projection a `belongs` load and a `through` load use to
233
260
  * attach one related row per key.
261
+ * Optional `values` supply the attached rows by position; keys always come from `rows`.
234
262
  *
235
263
  * @param rows - The rows to index
236
264
  * @param column - The column to key on
265
+ * @param values - The rows to attach by position. Default: `rows`. Missing positions are omitted.
237
266
  * @returns A read-only map from each key's string form to its row
238
267
  *
239
268
  * @example
@@ -241,8 +270,11 @@ function countAttached(values) {
241
270
  * indexRows([{ id: 'r1' }, { id: 'r2' }], 'id').get('r1') // { id: 'r1' }
242
271
  * ```
243
272
  */
244
- function indexRows(rows, column) {
245
- return new Map(Iterator.from(rows).map((row) => [String(readColumn(row, column)), row]));
273
+ function indexRows(rows, column, values = rows) {
274
+ return new Map(Iterator.from(rows).flatMap((row, index) => {
275
+ const value = values[index];
276
+ return value === void 0 ? [] : [[String(readColumn(row, column)), value]];
277
+ }));
246
278
  }
247
279
  /**
248
280
  * Groups rows by the string form of one column, for one-to-many lookups.
@@ -253,9 +285,11 @@ function indexRows(rows, column) {
253
285
  * a group, a key no row carries is absent rather than empty, and a row missing the
254
286
  * column groups under the string `'undefined'`. This is the projection a `many` load
255
287
  * and a `morph` load use to attach every related row per key.
288
+ * Optional `values` supply the attached rows by position; keys always come from `rows`.
256
289
  *
257
290
  * @param rows - The rows to group
258
291
  * @param column - The column to key on
292
+ * @param values - The rows to attach by position. Default: `rows`. Missing positions are omitted.
259
293
  * @returns A read-only map from each key's string form to its rows, in input order
260
294
  *
261
295
  * @example
@@ -263,13 +297,15 @@ function indexRows(rows, column) {
263
297
  * groupRows([{ author: 'u1' }, { author: 'u1' }], 'author').get('u1')?.length // 2
264
298
  * ```
265
299
  */
266
- function groupRows(rows, column) {
300
+ function groupRows(rows, column, values = rows) {
267
301
  const groups = /* @__PURE__ */ new Map();
268
- for (const row of rows) {
302
+ for (const [index, row] of rows.entries()) {
303
+ const value = values[index];
304
+ if (value === void 0) continue;
269
305
  const key = String(readColumn(row, column));
270
306
  const group = groups.get(key);
271
- if (group !== void 0) group.push(row);
272
- else groups.set(key, [row]);
307
+ if (group !== void 0) group.push(value);
308
+ else groups.set(key, [value]);
273
309
  }
274
310
  return groups;
275
311
  }
@@ -375,7 +411,7 @@ function hasMorph(key, tag, label, model) {
375
411
  *
376
412
  * @remarks
377
413
  * The model's own table is fully typed (`table`); related tables are reached by
378
- * runtime name through the database at the broad `Row` type. Loading is batched:
414
+ * runtime name through the bound storage at the broad `Row` type. Loading is batched:
379
415
  * a direct relation uses one query for the whole record set, while a `through`
380
416
  * relation uses two (junction then target); both counts remain constant regardless
381
417
  * of parent count. Nested includes recurse through the registry `lookup`, so each
@@ -399,11 +435,11 @@ function hasMorph(key, tag, label, model) {
399
435
  * const relations = { posts: hasMany('author') }
400
436
  * const users = new Model(
401
437
  * 'users',
402
- * database.table('users'),
438
+ * storage.table('users'),
403
439
  * resolveRelationMap(relations),
404
440
  * relations,
405
441
  * () => undefined,
406
- * database,
442
+ * storage,
407
443
  * )
408
444
  * users.emitter.on('load', (name, count) => metrics.record(`relation.${name}`, count))
409
445
  * const ada = await users.load('u1', { posts: true })
@@ -415,29 +451,32 @@ var Model = class {
415
451
  #resolved;
416
452
  #relations;
417
453
  #lookup;
418
- #database;
454
+ #storage;
419
455
  #emitter;
420
456
  /**
421
457
  * Constructs a model over one table and its resolved relations.
422
458
  *
423
459
  * @param name - The model's table name
424
- * @param table - The typed table this model's own reads and writes go through
460
+ * @param table - The typed table this model's own reads and writes go through; take it
461
+ * from `storage` so both belong to one scope, as `RelationManager` does
462
+ * (a root table read inside a transaction refuses with `CONFLICT`)
425
463
  * @param resolved - The model's relations, resolved by `resolveRelationMap`
426
464
  * @param relations - The raw relation map the resolved relations came from
427
465
  * @param lookup - Reads a related model's {@link RelationContext} for a nested include,
428
- * and returns `undefined` for a model the registry does not hold
429
- * @param database - The broad database used to read related and junction tables by name
466
+ * and returns `undefined` for a model the registry does not hold; its contexts must
467
+ * resolve through the same `storage`
468
+ * @param storage - The broad storage used to read related and junction tables by name
430
469
  * @param on - Initial {@link ModelEventMap} listeners
431
470
  * @param error - Receives a listener throw as `(error, event)`. Default: the throw is
432
471
  * swallowed.
433
472
  */
434
- constructor(name, table, resolved, relations, lookup, database, on, error) {
473
+ constructor(name, table, resolved, relations, lookup, storage, on, error) {
435
474
  this.#name = name;
436
475
  this.#table = table;
437
476
  this.#resolved = resolved;
438
477
  this.#relations = relations;
439
478
  this.#lookup = lookup;
440
- this.#database = database;
479
+ this.#storage = storage;
441
480
  this.#emitter = new Emitter({
442
481
  ...on !== void 0 ? { on } : {},
443
482
  ...error !== void 0 ? { error } : {}
@@ -484,7 +523,7 @@ var Model = class {
484
523
  async link(key, relation, target, options) {
485
524
  checkAbort(options?.signal);
486
525
  const resolved = this.#through(relation);
487
- const junction = this.#database.table(resolved.through);
526
+ const junction = this.#storage.table(resolved.through);
488
527
  if (await junction.count({ conditions: [{
489
528
  column: resolved.source,
490
529
  operator: "equals",
@@ -505,7 +544,7 @@ var Model = class {
505
544
  async unlink(key, relation, target, options) {
506
545
  checkAbort(options?.signal);
507
546
  const resolved = this.#through(relation);
508
- const junction = this.#database.table(resolved.through);
547
+ const junction = this.#storage.table(resolved.through);
509
548
  const rows = await junction.records({ conditions: [{
510
549
  column: resolved.source,
511
550
  operator: "equals",
@@ -517,19 +556,16 @@ var Model = class {
517
556
  values: [target],
518
557
  connector: "and"
519
558
  }] }, options);
520
- await this.#database.transaction(async (transaction) => {
521
- const scoped = transaction.table(resolved.through);
522
- for (const row of rows) {
523
- const id = extractKey(row, junction.primary);
524
- if (id !== void 0) await scoped.remove(id, options);
525
- }
526
- }, options);
559
+ for (const row of rows) {
560
+ const id = extractKey(row, junction.primary);
561
+ if (id !== void 0) await junction.remove(id, options);
562
+ }
527
563
  this.#emitter.emit("unlink", key, relation);
528
564
  }
529
565
  async links(key, relation, options) {
530
566
  checkAbort(options?.signal);
531
567
  const resolved = this.#through(relation);
532
- const rows = await this.#database.table(resolved.through).records({ conditions: [{
568
+ const rows = await this.#storage.table(resolved.through).records({ conditions: [{
533
569
  column: resolved.source,
534
570
  operator: "equals",
535
571
  values: [key],
@@ -585,14 +621,14 @@ var Model = class {
585
621
  const column = resolved.column;
586
622
  const keys = [...new Set(records.map((record) => readColumn(record, column)).filter(isDefined))];
587
623
  if (keys.length === 0) return records.map(() => void 0);
588
- const related = this.#database.table(resolved.model);
624
+ const related = this.#storage.table(resolved.model);
589
625
  const rows = await related.records({ conditions: [{
590
626
  column: related.primary,
591
627
  operator: "any",
592
628
  values: keys,
593
629
  connector: "and"
594
630
  }] }, options);
595
- const index = indexRows(await this.#nest(resolved.model, rows, sub, options), related.primary);
631
+ const index = indexRows(rows, related.primary, await this.#nest(resolved.model, rows, sub, options));
596
632
  return records.map((record) => {
597
633
  const fk = readColumn(record, column);
598
634
  return isDefined(fk) ? index.get(String(fk)) : void 0;
@@ -602,13 +638,13 @@ var Model = class {
602
638
  const foreign = resolved.key;
603
639
  const keys = [...new Set(records.map((record) => readColumn(record, primary)).filter(isDefined))];
604
640
  if (keys.length === 0) return records.map(() => []);
605
- const rows = await this.#database.table(resolved.model).records({ conditions: [{
641
+ const rows = await this.#storage.table(resolved.model).records({ conditions: [{
606
642
  column: foreign,
607
643
  operator: "any",
608
644
  values: keys,
609
645
  connector: "and"
610
646
  }] }, options);
611
- const groups = groupRows(await this.#nest(resolved.model, rows, sub, options), foreign);
647
+ const groups = groupRows(rows, foreign, await this.#nest(resolved.model, rows, sub, options));
612
648
  return records.map((record) => groups.get(String(readColumn(record, primary))) ?? []);
613
649
  }
614
650
  async #loadOne(records, resolved, sub, primary, options) {
@@ -619,7 +655,7 @@ var Model = class {
619
655
  const target = resolved.target;
620
656
  const parents = [...new Set(records.map((record) => readColumn(record, primary)).filter(isDefined))];
621
657
  if (parents.length === 0) return records.map(() => []);
622
- const junctions = await this.#database.table(resolved.through).records({ conditions: [{
658
+ const junctions = await this.#storage.table(resolved.through).records({ conditions: [{
623
659
  column: source,
624
660
  operator: "any",
625
661
  values: parents,
@@ -636,14 +672,14 @@ var Model = class {
636
672
  }
637
673
  const targets = [...new Set([...targetsBySource.values()].flat())];
638
674
  if (targets.length === 0) return records.map(() => []);
639
- const related = this.#database.table(resolved.model);
675
+ const related = this.#storage.table(resolved.model);
640
676
  const rows = await related.records({ conditions: [{
641
677
  column: related.primary,
642
678
  operator: "any",
643
679
  values: targets,
644
680
  connector: "and"
645
681
  }] }, options);
646
- const index = indexRows(await this.#nest(resolved.model, rows, sub, options), related.primary);
682
+ const index = indexRows(rows, related.primary, await this.#nest(resolved.model, rows, sub, options));
647
683
  return records.map((record) => {
648
684
  const out = [];
649
685
  for (const value of targetsBySource.get(String(readColumn(record, primary))) ?? []) {
@@ -657,7 +693,7 @@ var Model = class {
657
693
  const foreign = resolved.key;
658
694
  const keys = [...new Set(records.map((record) => readColumn(record, primary)).filter(isDefined))];
659
695
  if (keys.length === 0) return records.map(() => []);
660
- const rows = await this.#database.table(resolved.model).records({ conditions: [{
696
+ const rows = await this.#storage.table(resolved.model).records({ conditions: [{
661
697
  column: foreign,
662
698
  operator: "any",
663
699
  values: keys,
@@ -668,7 +704,7 @@ var Model = class {
668
704
  values: [resolved.label],
669
705
  connector: "and"
670
706
  }] }, options);
671
- const groups = groupRows(await this.#nest(resolved.model, rows, sub, options), foreign);
707
+ const groups = groupRows(rows, foreign, await this.#nest(resolved.model, rows, sub, options));
672
708
  return records.map((record) => groups.get(String(readColumn(record, primary))) ?? []);
673
709
  }
674
710
  async #nest(model, rows, sub, options) {
@@ -685,8 +721,8 @@ var Model = class {
685
721
  * {@link ModelInterface} per declared table.
686
722
  *
687
723
  * @remarks
688
- * Holds the database both at its precise type (to type each model's own table)
689
- * and at the broad `DatabaseInterface` (to fetch related tables by runtime name
724
+ * Holds storage both at its precise type (to type each model's own table)
725
+ * and at the broad `DatabaseStorageInterface` (to fetch related tables by runtime name
690
726
  * while loading). Construction validates every target and junction against the
691
727
  * database's declared tables, so invalid definitions fail before an operation runs.
692
728
  * The `model` option's `on` and `error` are threaded into every model vended, and
@@ -697,8 +733,8 @@ var Model = class {
697
733
  * ```ts
698
734
  * import { RelationManager, hasMany } from '@orkestrel/relation'
699
735
  *
700
- * const manager = new RelationManager({
701
- * database,
736
+ * const manager = new RelationManager<typeof TABLES>({
737
+ * storage: database,
702
738
  * relations: { users: { posts: hasMany('author') } },
703
739
  * model: { on: { load: (name, count) => metrics.record(`relation.${name}`, count) } },
704
740
  * })
@@ -707,39 +743,30 @@ var Model = class {
707
743
  * ```
708
744
  */
709
745
  var RelationManager = class {
710
- #database;
746
+ #storage;
711
747
  #broad;
712
748
  #relations;
713
749
  #model;
714
750
  #resolved = /* @__PURE__ */ new Map();
715
751
  /**
716
- * Constructs a registry over a database and its relation definitions.
752
+ * Constructs a registry over storage and its relation definitions.
717
753
  *
718
- * @param options - The `database`, an optional `relations` map, and the optional
754
+ * @param options - The `storage`, an optional `relations` map, and the optional
719
755
  * `model` emitter settings threaded into every model vended
720
756
  * @throws An `INVALID` {@link RelationError} when a relation targets a table or a
721
757
  * junction the database does not declare
722
758
  */
723
759
  constructor(options) {
724
- this.#database = options.database;
725
- this.#broad = options.database;
760
+ this.#storage = options.storage;
761
+ this.#broad = options.storage;
726
762
  this.#relations = options.relations ?? {};
727
763
  this.#model = options.model;
728
- const declared = new Set(Object.keys(this.#broad.export()));
729
764
  for (const [name, map] of Object.entries(this.#relations)) {
730
765
  if (map === void 0) continue;
731
766
  const resolved = resolveRelationMap(map);
732
767
  for (const [relation, entry] of resolved) {
733
- if (!declared.has(entry.model)) throw new RelationError("INVALID", `Model '${name}' relation '${relation}' targets undeclared table '${entry.model}'`, {
734
- model: name,
735
- relation,
736
- table: entry.model
737
- });
738
- if (entry.relationship === "through" && !declared.has(entry.through)) throw new RelationError("INVALID", `Model '${name}' relation '${relation}' uses undeclared junction '${entry.through}'`, {
739
- model: name,
740
- relation,
741
- table: entry.through
742
- });
768
+ validateRelationTable(this.#broad, name, relation, entry.model);
769
+ if (entry.relationship === "through") validateRelationTable(this.#broad, name, relation, entry.through, true);
743
770
  }
744
771
  this.#resolved.set(name, resolved);
745
772
  }
@@ -750,7 +777,7 @@ var RelationManager = class {
750
777
  model(name) {
751
778
  const resolved = this.#resolved.get(name) ?? /* @__PURE__ */ new Map();
752
779
  const relations = this.#relations[name] ?? {};
753
- return this.#vend(name, this.#database.table(name), resolved, relations);
780
+ return this.#vend(name, this.#storage.table(name), resolved, relations);
754
781
  }
755
782
  names() {
756
783
  return [...this.#resolved.keys()];
@@ -772,7 +799,7 @@ var RelationManager = class {
772
799
  };
773
800
  // src/core/factories.ts
774
801
  /**
775
- * Creates a {@link RelationManagerInterface} over a database and its relation map.
802
+ * Creates a {@link RelationManagerInterface} over storage and its relation map.
776
803
  *
777
804
  * @remarks
778
805
  * `relations` maps table names (constrained to the database's tables) to their
@@ -780,7 +807,9 @@ var RelationManager = class {
780
807
  * `hasThrough` / `hasMorph`. `manager.model(name)` returns the typed model for a
781
808
  * table — its own table is fully typed, related rows load at the `Row` type.
782
809
  *
783
- * @param options - The `database` and an optional `relations` map
810
+ * At a typed root, pass the table map as the type argument. Transaction storage infers it.
811
+ *
812
+ * @param options - The `storage` and an optional `relations` map
784
813
  * @returns A typed {@link RelationManagerInterface}
785
814
  *
786
815
  * @example Defining relations
@@ -794,8 +823,8 @@ var RelationManager = class {
794
823
  * hasMorph,
795
824
  * } from '@orkestrel/relation'
796
825
  *
797
- * const manager = createRelationManager({
798
- * database: db,
826
+ * const manager = createRelationManager<typeof TABLES>({
827
+ * storage: db,
799
828
  * relations: {
800
829
  * accounts: {
801
830
  * classification: belongsTo('classificationId', 'classifications'), // foreign key on accounts
@@ -814,6 +843,6 @@ var RelationManager = class {
814
843
  function createRelationManager(options) {
815
844
  return new RelationManager(options);
816
845
  }
817
- export { Model, RelationError, RelationManager, belongsTo, countAttached, createRelationManager, groupRows, hasMany, hasMorph, hasOne, hasThrough, indexRows, isRelationDescriptor, isRelationError, readColumn, resolveRelation, resolveRelationMap };
846
+ export { Model, RelationError, RelationManager, belongsTo, countAttached, createRelationManager, groupRows, hasMany, hasMorph, hasOne, hasThrough, indexRows, isRelationDescriptor, isRelationError, readColumn, resolveRelation, resolveRelationMap, validateRelationTable };
818
847
 
819
848
  //# sourceMappingURL=index.js.map