@orkestrel/relation 0.0.10 → 0.0.11

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.
@@ -11,7 +11,7 @@ import { TableInterface } from '@orkestrel/database';
11
11
  import { TableMap } from '@orkestrel/database';
12
12
 
13
13
  /**
14
- * Build a `belongs` relation — a foreign key on THIS table points at the related row.
14
+ * Builds a `belongs` relation — a foreign key on THIS table points at the related row.
15
15
  *
16
16
  * @param column - The FK column on this table
17
17
  * @param model - Target table name (defaults to the relation name)
@@ -25,7 +25,25 @@ import { TableMap } from '@orkestrel/database';
25
25
  export declare function belongsTo(column: string, model?: string): RelationDescriptor;
26
26
 
27
27
  /**
28
- * Create a relation manager over a database and its relation definitions.
28
+ * Counts the related rows one relation attached across a record set.
29
+ *
30
+ * @remarks
31
+ * An array-valued relation (`many` / `through` / `morph`) sums its lengths; a
32
+ * single-valued one (`belongs` / `one`) counts each present row. This is the count a
33
+ * `Model` carries on its `load` event.
34
+ *
35
+ * @param values - One relation's loaded value per record
36
+ * @returns The total related rows attached across the set
37
+ *
38
+ * @example
39
+ * ```ts
40
+ * countAttached([[{ id: 'p1' }, { id: 'p2' }], undefined, { id: 'p3' }]) // 3
41
+ * ```
42
+ */
43
+ export declare function countAttached(values: ReadonlyArray<Row | readonly Row[] | undefined>): number;
44
+
45
+ /**
46
+ * Creates a relation manager over a database and its relation definitions.
29
47
  *
30
48
  * @remarks
31
49
  * `relations` maps table names (constrained to the database's tables) to their
@@ -52,17 +70,38 @@ export declare function belongsTo(column: string, model?: string): RelationDescr
52
70
  */
53
71
  export declare function createRelationManager<T extends TableMap>(options: RelationManagerOptions<T>): RelationManagerInterface<T>;
54
72
 
55
- /** Pagination, ordering, and cancellation for `find`. */
73
+ /** Configures pagination, ordering, and cancellation for `find`. */
56
74
  export declare interface FindOptions extends OperationOptions {
57
75
  readonly limit?: number;
58
76
  readonly offset?: number;
59
77
  readonly sort?: string;
60
- /** The sort direction; defaults to `ascending` when {@link sort} is present. */
78
+ /** Holds the sort direction; defaults to `ascending` when {@link sort} is present. */
61
79
  readonly direction?: OrderDirection;
62
80
  }
63
81
 
64
82
  /**
65
- * Build a `many` relation — a foreign key on the RELATED table points back here.
83
+ * Groups rows by the string form of one column, for one-to-many lookups.
84
+ *
85
+ * @remarks
86
+ * The column is read with {@link readColumn} and its value stringified, so a numeric
87
+ * and a string foreign key meet at the same group. Rows keep their input order inside
88
+ * a group, a key no row carries is absent rather than empty, and a row missing the
89
+ * column groups under the string `'undefined'`. This is the projection a `many` load
90
+ * and a `morph` load use to attach every related row per key.
91
+ *
92
+ * @param rows - The rows to group
93
+ * @param column - The column to key on
94
+ * @returns A read-only map from each key's string form to its rows, in input order
95
+ *
96
+ * @example
97
+ * ```ts
98
+ * groupRows([{ author: 'u1' }, { author: 'u1' }], 'author').get('u1')?.length // 2
99
+ * ```
100
+ */
101
+ export declare function groupRows(rows: readonly Row[], column: string): ReadonlyMap<string, readonly Row[]>;
102
+
103
+ /**
104
+ * Builds a `many` relation — a foreign key on the RELATED table points back here.
66
105
  *
67
106
  * @param key - The FK column on the related table
68
107
  * @param model - Target table name (defaults to the relation name)
@@ -71,7 +110,7 @@ export declare interface FindOptions extends OperationOptions {
71
110
  export declare function hasMany(key: string, model?: string): RelationDescriptor;
72
111
 
73
112
  /**
74
- * Build a `morph` relation — a polymorphic FK plus a discriminator on the RELATED table.
113
+ * Builds a `morph` relation — a polymorphic FK plus a discriminator on the RELATED table.
75
114
  *
76
115
  * @param key - The FK column on the related table
77
116
  * @param tag - The discriminator column on the related table
@@ -87,7 +126,7 @@ export declare function hasMany(key: string, model?: string): RelationDescriptor
87
126
  export declare function hasMorph(key: string, tag: string, label: string, model?: string): RelationDescriptor;
88
127
 
89
128
  /**
90
- * Build a `one` relation — like {@link hasMany}, but a single related row.
129
+ * Builds a `one` relation — like {@link hasMany}, but a single related row.
91
130
  *
92
131
  * @param key - The FK column on the related table
93
132
  * @param model - Target table name (defaults to the relation name)
@@ -96,7 +135,7 @@ export declare function hasMorph(key: string, tag: string, label: string, model?
96
135
  export declare function hasOne(key: string, model?: string): RelationDescriptor;
97
136
 
98
137
  /**
99
- * Build a `through` relation — a junction table links the two sides (many-to-many).
138
+ * Builds a `through` relation — a junction table links the two sides (many-to-many).
100
139
  *
101
140
  * @param through - The junction table name
102
141
  * @param source - The junction FK column pointing at THIS model
@@ -112,7 +151,7 @@ export declare function hasOne(key: string, model?: string): RelationDescriptor;
112
151
  export declare function hasThrough(through: string, source: string, target: string, model?: string): RelationDescriptor;
113
152
 
114
153
  /**
115
- * Which relations to populate when loading — and, recursively, their own.
154
+ * Selects which relations to populate when loading — and, recursively, their own.
116
155
  *
117
156
  * @remarks
118
157
  * `true` loads the relation flat; a nested {@link Include} loads it and its
@@ -128,34 +167,84 @@ export declare interface Include {
128
167
  }
129
168
 
130
169
  /**
131
- * Narrow a value to a {@link RelationDescriptor} (the object form of a relation).
170
+ * Indexes rows by the string form of one column, for keyed lookups.
171
+ *
172
+ * @remarks
173
+ * The column is read with {@link readColumn} and its value stringified, so a numeric
174
+ * and a string foreign key meet at the same entry. A later row with a key an earlier
175
+ * row already holds replaces it, and a row missing the column indexes under the string
176
+ * `'undefined'`. This is the projection a `belongs` load and a `through` load use to
177
+ * attach one related row per key.
178
+ *
179
+ * @param rows - The rows to index
180
+ * @param column - The column to key on
181
+ * @returns A read-only map from each key's string form to its row
182
+ *
183
+ * @example
184
+ * ```ts
185
+ * indexRows([{ id: 'r1' }, { id: 'r2' }], 'id').get('r1') // { id: 'r1' }
186
+ * ```
187
+ */
188
+ export declare function indexRows(rows: readonly Row[], column: string): ReadonlyMap<string, Row>;
189
+
190
+ /**
191
+ * Narrows a value to a {@link RelationDescriptor} (the object form of a relation).
192
+ *
193
+ * @remarks
194
+ * A record satisfies the descriptor when every member it declares carries its declared
195
+ * type: `relationship` is one of the `Relationship` values, and `column`, `key`,
196
+ * `through`, `source`, `target`, `tag`, `label`, and `model` are strings. A member the
197
+ * record omits is unconstrained, a member present with an `undefined` value is refused,
198
+ * and a member the descriptor does not declare is carried without being checked. This
199
+ * is what lets `resolveRelation` read each member after one narrow and report a
200
+ * malformed definition as an `INVALID` `RelationError` instead of resolving a
201
+ * wrong-typed column into an arm that declares it a string.
132
202
  *
133
203
  * @param value - The value to test
134
- * @returns `true` when `value` is a plain record
204
+ * @returns True if `value` is a record whose every declared member holds its declared
205
+ * type; false otherwise
206
+ *
207
+ * @example
208
+ * ```ts
209
+ * isRelationDescriptor(belongsTo('accountId')) // true
210
+ * isRelationDescriptor({ column: 42 }) // false — `column` is declared a string
211
+ * ```
135
212
  */
136
213
  export declare function isRelationDescriptor(value: unknown): value is RelationDescriptor;
137
214
 
138
215
  /**
139
- * Narrow an unknown caught value to a {@link RelationError}.
216
+ * Narrows an unknown caught value to a {@link RelationError}.
140
217
  *
141
218
  * @param value - The value to test (typically a `catch` binding)
142
- * @returns `true` when `value` is a {@link RelationError}
219
+ * @returns True if `value` is a {@link RelationError}; false otherwise
143
220
  */
144
221
  export declare function isRelationError(value: unknown): value is RelationError;
145
222
 
146
223
  /**
147
- * A row with its loaded relation properties attached.
224
+ * Represents a row with its loaded relation properties attached.
148
225
  *
149
226
  * @remarks
150
227
  * The base row is fully typed (the table's row type); the relation properties
151
- * ({@link RelationProps}) are broad — narrow them at the use site. Typing each
228
+ * ({@link LoadedMap}) are broad — narrow them at the use site. Typing each
152
229
  * relation property to its target row is a deliberate (documented) deferral, like
153
230
  * the database guide's deferred pieces.
154
231
  */
155
- export declare type Loaded<T> = T & Readonly<RelationProps>;
232
+ export declare type Loaded<T> = T & Readonly<LoadedMap>;
156
233
 
157
234
  /**
158
- * A model — a typed table paired with relation-aware loading.
235
+ * Holds the relation properties attached to a {@link Loaded} row — each relation
236
+ * name mapped to its loaded related row(s), or `undefined` when a `belongs` /
237
+ * `one` relation misses.
238
+ *
239
+ * @remarks
240
+ * The broad value type (`Row | readonly Row[] | undefined`) is narrowed at the use
241
+ * site. This is the mutable bag a `Model` fills while populating a record set;
242
+ * `Loaded<T>` is a base row intersected with its `Readonly` form.
243
+ */
244
+ export declare type LoadedMap = Record<string, Row | readonly Row[] | undefined>;
245
+
246
+ /**
247
+ * Pairs a typed table with relation-aware loading.
159
248
  *
160
249
  * @remarks
161
250
  * The model's own table is fully typed (`table`); related tables are reached by
@@ -167,7 +256,7 @@ export declare type Loaded<T> = T & Readonly<RelationProps>;
167
256
  * type is closed) and relation properties merged with `Object.assign` — no `as`.
168
257
  *
169
258
  * @remarks
170
- * - **Observable (§13).** The owned {@link emitter} ({@link ModelEventMap}) carries the
259
+ * - **Observable.** The owned {@link emitter} ({@link ModelEventMap}) carries the
171
260
  * eager-load + junction moments — `load` (a relation resolved: its name + the count of
172
261
  * related rows attached across the whole record set), `link` / `unlink` (a junction row
173
262
  * written) — for fire-and-forget observers. Every event is emitted directly, strictly
@@ -175,9 +264,40 @@ export declare type Loaded<T> = T & Readonly<RelationProps>;
175
264
  * throw and routes it to its `error` handler (the `error` option), so a buggy observer can
176
265
  * never corrupt the batched eager-load (no N+1 in the events either — one `load` per
177
266
  * relation, not per record).
267
+ *
268
+ * @example
269
+ * ```ts
270
+ * import { Model, resolveRelationMap, hasMany } from '@orkestrel/relation'
271
+ *
272
+ * const relations = { posts: hasMany('author') }
273
+ * const users = new Model(
274
+ * 'users',
275
+ * database.table('users'),
276
+ * resolveRelationMap(relations),
277
+ * relations,
278
+ * () => undefined,
279
+ * database,
280
+ * )
281
+ * users.emitter.on('load', (name, count) => metrics.record(`relation.${name}`, count))
282
+ * const ada = await users.load('u1', { posts: true })
283
+ * ```
178
284
  */
179
285
  export declare class Model<T = Row> implements ModelInterface<T> {
180
286
  #private;
287
+ /**
288
+ * Constructs a model over one table and its resolved relations.
289
+ *
290
+ * @param name - The model's table name
291
+ * @param table - The typed table this model's own reads and writes go through
292
+ * @param resolved - The model's relations, resolved by `resolveRelationMap`
293
+ * @param relations - The raw relation map the resolved relations came from
294
+ * @param lookup - Reads a related model's {@link RelationContext} for a nested include,
295
+ * and returns `undefined` for a model the registry does not hold
296
+ * @param database - The broad database used to read related and junction tables by name
297
+ * @param on - Initial {@link ModelEventMap} listeners
298
+ * @param error - Receives a listener throw as `(error, event)`. Default: the throw is
299
+ * swallowed.
300
+ */
181
301
  constructor(name: string, table: TableInterface<T>, resolved: ReadonlyMap<string, ResolvedRelation>, relations: RelationMap, lookup: (model: string) => RelationContext | undefined, database: DatabaseInterface, on?: EmitterHooks<ModelEventMap>, error?: EmitterErrorHandler);
182
302
  get emitter(): EmitterInterface<ModelEventMap>;
183
303
  get name(): string;
@@ -192,39 +312,44 @@ export declare class Model<T = Row> implements ModelInterface<T> {
192
312
  }
193
313
 
194
314
  /**
195
- * The push observation surface of a {@link ModelInterface} (AGENTS §13) — the eager-load
196
- * + junction-management moments a fire-and-forget observer (logging, metrics, a sync
197
- * layer) subscribes to.
198
- *
199
- * @typeParam TKey - The model's primary-key type (a {@link Key}); `link` / `unlink` carry
200
- * the owning key so the map is `ModelEventMap<TKey>`.
315
+ * Declares the push observation surface of a {@link ModelInterface} — the
316
+ * eager-load + junction-management moments a fire-and-forget observer (logging, metrics,
317
+ * a sync layer) subscribes to.
201
318
  *
202
319
  * @remarks
203
320
  * `load` fires once per relation that an eager-load resolves, carrying the relation NAME +
204
321
  * the COUNT of related rows attached for the whole record set (it is the batched load
205
322
  * moment, not one event per record — there is no N+1 in the events either). `link` /
206
323
  * `unlink` fire after a junction row is inserted / removed, carrying the owning key + the
207
- * relation name. Listener isolation is the emitter's (AGENTS §13): every event is emitted
324
+ * relation name. Listener isolation is the emitter's: every event is emitted
208
325
  * directly and a listener throw is routed to the emitter's `error` handler (the `error`
209
326
  * option), never onto this map, and sits AFTER the load resolves / the junction op completes
210
327
  * — so a throwing observer can never corrupt the eager-load batching or a junction write.
211
328
  * `RelationManager` is event-free by design (a stateless
212
329
  * registry that merely vends models — it has no observable lifecycle of its own); the
213
330
  * per-entity {@link ModelInterface} is where loading and linking happen, so the emitter
214
- * lives there. Subscribe via `model.emitter.on(...)`. Declared as a `type` alias (§4.5 —
215
- * `EventMap` is a `type` kind).
331
+ * lives there. Subscribe through `model.emitter.on(...)`.
216
332
  */
217
- export declare type ModelEventMap<TKey extends Key = Key> = {
218
- /** A relation eager-loaded — the relation name + the count of related rows attached. */
333
+ export declare type ModelEventMap = {
334
+ /**
335
+ * Fires when a relation is eager-loaded — the relation name + the count of related rows
336
+ * attached.
337
+ */
219
338
  readonly load: readonly [name: string, count: number];
220
- /** A junction row was inserted for a `through` relation — the owning key + relation name. */
221
- readonly link: readonly [key: TKey, relation: string];
222
- /** A junction row was removed for a `through` relation — the owning key + relation name. */
223
- readonly unlink: readonly [key: TKey, relation: string];
339
+ /**
340
+ * Fires after a junction row is inserted for a `through` relation — the owning key +
341
+ * relation name.
342
+ */
343
+ readonly link: readonly [key: Key, relation: string];
344
+ /**
345
+ * Fires after a junction row is removed for a `through` relation — the owning key +
346
+ * relation name.
347
+ */
348
+ readonly unlink: readonly [key: Key, relation: string];
224
349
  };
225
350
 
226
351
  /**
227
- * A model — a typed table paired with relation-aware loading and junction
352
+ * Represents a typed table paired with relation-aware loading and junction
228
353
  * management.
229
354
  *
230
355
  * @remarks
@@ -234,7 +359,7 @@ export declare type ModelEventMap<TKey extends Key = Key> = {
234
359
  * fetches many; both batch-load (one query per direct relation or two per
235
360
  * `through`, regardless of result size). `link` / `unlink` / `links` manage a
236
361
  * `through` relation's junction rows.
237
- * Exposes a typed {@link emitter} (AGENTS §13) carrying the eager-load + junction
362
+ * Exposes a typed {@link emitter} carrying the eager-load + junction
238
363
  * moments ({@link ModelEventMap}) for fire-and-forget observers — emitting is
239
364
  * observation-only (a swallowed listener throw can never corrupt the batched load).
240
365
  * `link` is idempotent for sequential calls: an existing pair writes nothing and
@@ -255,7 +380,25 @@ export declare interface ModelInterface<T = Row> {
255
380
  }
256
381
 
257
382
  /**
258
- * A single relation definition.
383
+ * Reads one column off any record.
384
+ *
385
+ * @remarks
386
+ * A base row's type is closed, so the column is read with `Reflect.get` rather than
387
+ * index access. Anything that is not an object reads as `undefined`.
388
+ *
389
+ * @param record - The record to read
390
+ * @param column - The column name
391
+ * @returns The column's value, or `undefined` when `record` is not an object
392
+ *
393
+ * @example
394
+ * ```ts
395
+ * readColumn({ accountId: 'acc1' }, 'accountId') // 'acc1'
396
+ * ```
397
+ */
398
+ export declare function readColumn(record: unknown, column: string): unknown;
399
+
400
+ /**
401
+ * Represents a single relation definition.
259
402
  *
260
403
  * @remarks
261
404
  * A `string` is a `belongs` (the FK column on this table); a `readonly string[]`
@@ -265,7 +408,7 @@ export declare interface ModelInterface<T = Row> {
265
408
  export declare type Relation = string | readonly string[] | RelationDescriptor;
266
409
 
267
410
  /**
268
- * A related model's resolved relations and primary-key column, for nested loading.
411
+ * Holds a related model's resolved relations and primary-key column, for nested loading.
269
412
  *
270
413
  * @remarks
271
414
  * The lookup result the relation registry hands a {@link ModelInterface} so it can
@@ -279,7 +422,7 @@ export declare interface RelationContext {
279
422
  }
280
423
 
281
424
  /**
282
- * The object form of a relation.
425
+ * Represents the object form of a relation.
283
426
  *
284
427
  * @remarks
285
428
  * The builder helpers (`belongsTo` / `hasMany` / `hasOne` / `hasThrough` /
@@ -303,7 +446,7 @@ export declare interface RelationDescriptor {
303
446
  }
304
447
 
305
448
  /**
306
- * An error thrown by the relations layer.
449
+ * Represents an error thrown by the relations layer.
307
450
  *
308
451
  * @remarks
309
452
  * Thrown for: a relation value whose relationship cannot be inferred (`INVALID`), a
@@ -318,47 +461,81 @@ export declare class RelationError extends Error {
318
461
  constructor(code: RelationErrorCode, message: string, context?: Readonly<Record<string, unknown>>);
319
462
  }
320
463
 
321
- /** A machine-readable {@link RelationError} code. */
464
+ /** Names a machine-readable {@link RelationError} code. */
322
465
  export declare type RelationErrorCode = 'INVALID' | 'UNKNOWN_RELATION' | 'NOT_THROUGH';
323
466
 
324
467
  /**
325
- * The relation registry — resolves a {@link RelationsShape} once at construction
326
- * and vends a typed {@link ModelInterface} per declared table.
468
+ * Resolves a {@link RelationsShape} once at construction and vends a typed
469
+ * {@link ModelInterface} per declared table.
327
470
  *
328
471
  * @remarks
329
472
  * Holds the database both at its precise type (to type each model's own table)
330
473
  * and at the broad `DatabaseInterface` (to fetch related tables by runtime name
331
474
  * while loading). Construction validates every target and junction against the
332
475
  * database's declared tables, so invalid definitions fail before an operation runs.
476
+ * The `model` option's `on` and `error` are threaded into every model vended, and
477
+ * each `model(name)` call constructs a handle owning its own emitter, so retain the
478
+ * handle a subscription is taken on.
479
+ *
480
+ * @example
481
+ * ```ts
482
+ * import { RelationManager, hasMany } from '@orkestrel/relation'
483
+ *
484
+ * const manager = new RelationManager({
485
+ * database,
486
+ * relations: { users: { posts: hasMany('author') } },
487
+ * model: { on: { load: (name, count) => metrics.record(`relation.${name}`, count) } },
488
+ * })
489
+ * const users = manager.model('users')
490
+ * const ada = await users.load('u1', { posts: true })
491
+ * ```
333
492
  */
334
493
  export declare class RelationManager<T extends TableMap = TableMap> implements RelationManagerInterface<T> {
335
494
  #private;
495
+ /**
496
+ * Constructs a registry over a database and its relation definitions.
497
+ *
498
+ * @param options - The `database`, an optional `relations` map, and the optional
499
+ * `model` emitter settings threaded into every model vended
500
+ * @throws An `INVALID` {@link RelationError} when a relation targets a table or a
501
+ * junction the database does not declare
502
+ */
336
503
  constructor(options: RelationManagerOptions<T>);
337
504
  get count(): number;
338
505
  model<K extends keyof T & string>(name: K): ModelInterface<RowOf<T[K]>>;
339
- models(): readonly string[];
506
+ names(): readonly string[];
340
507
  has(name: string): boolean;
341
508
  }
342
509
 
343
510
  /**
344
- * The relation registry — vends a typed {@link ModelInterface} per table.
511
+ * Vends a typed {@link ModelInterface} per table.
345
512
  *
346
513
  * @remarks
347
514
  * Built from a database and a {@link RelationsShape}; relations are resolved once
348
515
  * at construction. `model(name)` returns the model for a declared table, typed by
349
- * that table's row. Follows the manager accessor pattern (`model` / `models`).
516
+ * that table's row. Each call constructs a model, and the returned handle owns its
517
+ * own emitter, so retain the handle a subscription is taken on.
350
518
  */
351
519
  export declare interface RelationManagerInterface<T extends TableMap = TableMap> {
352
520
  readonly count: number;
353
521
  model<K extends keyof T & string>(name: K): ModelInterface<RowOf<T[K]>>;
354
- models(): readonly string[];
522
+ names(): readonly string[];
355
523
  has(name: string): boolean;
356
524
  }
357
525
 
358
- /** Options for `createRelationManager`. */
526
+ /**
527
+ * Configures `createRelationManager`.
528
+ *
529
+ * @remarks
530
+ * `model` carries the emitter settings the manager threads into every model it
531
+ * vends: `model.on` seeds each vended handle's initial {@link ModelEventMap}
532
+ * listeners, and `model.error` receives a listener throw as `(error, event)`.
533
+ * Each `model(name)` call constructs a handle with its own emitter, so these
534
+ * settings apply per handle rather than once for the manager.
535
+ */
359
536
  export declare interface RelationManagerOptions<T extends TableMap = TableMap> {
360
537
  /**
361
- * The database to build the registry over.
538
+ * Holds the database to build the registry over.
362
539
  *
363
540
  * @remarks
364
541
  * Intersected with the broad `DatabaseInterface` so the manager gets both the
@@ -367,25 +544,17 @@ export declare interface RelationManagerOptions<T extends TableMap = TableMap> {
367
544
  */
368
545
  readonly database: DatabaseInterface<T> & DatabaseInterface;
369
546
  readonly relations?: RelationsShape<T>;
547
+ readonly model?: {
548
+ readonly on?: EmitterHooks<ModelEventMap>;
549
+ readonly error?: EmitterErrorHandler;
550
+ };
370
551
  }
371
552
 
372
- /** A model's relations, keyed by relation name. */
553
+ /** Holds a model's relations, keyed by relation name. */
373
554
  export declare type RelationMap = Readonly<Record<string, Relation>>;
374
555
 
375
556
  /**
376
- * The relation properties attached to a {@link Loaded} row — each relation name
377
- * mapped to its loaded related row(s), or `undefined` when a `belongs` / `one`
378
- * relation misses.
379
- *
380
- * @remarks
381
- * The broad value type (`Row | readonly Row[] | undefined`) is narrowed at the use
382
- * site. This is the mutable bag a `Model` fills while populating a record set;
383
- * `Loaded<T>` is a base row intersected with its `Readonly` form.
384
- */
385
- export declare type RelationProps = Record<string, Row | readonly Row[] | undefined>;
386
-
387
- /**
388
- * The five relation shapes.
557
+ * Enumerates the relationships a relation can declare.
389
558
  *
390
559
  * @remarks
391
560
  * `belongs` — a foreign key on THIS table points at the related row (single).
@@ -397,7 +566,7 @@ export declare type RelationProps = Record<string, Row | readonly Row[] | undefi
397
566
  export declare type Relationship = 'belongs' | 'many' | 'one' | 'through' | 'morph';
398
567
 
399
568
  /**
400
- * Per-table relation maps — the declarative input to `createRelationManager`.
569
+ * Holds per-table relation maps — the declarative input to `createRelationManager`.
401
570
  *
402
571
  * @remarks
403
572
  * Keys are constrained to the database's declared table names, so relations can
@@ -408,43 +577,116 @@ export declare type RelationsShape<T extends TableMap = TableMap> = {
408
577
  };
409
578
 
410
579
  /**
411
- * A relation resolved at define-time into a flat, ready-to-load form.
580
+ * Represents a `belongs` relation resolved at define-time — the foreign key sits on THIS table.
412
581
  *
413
582
  * @remarks
414
- * The relationship and every column needed to load, link, and unlink are
415
- * precomputed from the raw {@link Relation}, so no inference runs at query time.
583
+ * `column` is that foreign key; the related row is the one whose primary key it holds.
584
+ * `name` is the relation's key in its {@link RelationMap} and `model` the target table.
416
585
  */
417
- export declare interface ResolvedRelation {
418
- readonly relationship: Relationship;
586
+ export declare interface ResolvedBelongs {
587
+ readonly relationship: 'belongs';
419
588
  readonly name: string;
420
589
  readonly model: string;
421
- readonly column?: string;
422
- readonly key?: string;
423
- readonly through?: string;
424
- readonly source?: string;
425
- readonly target?: string;
426
- readonly tag?: string;
427
- readonly label?: string;
590
+ readonly column: string;
591
+ }
592
+
593
+ /**
594
+ * Represents a `many` relation resolved at define-time — the foreign key sits on the RELATED
595
+ * table.
596
+ *
597
+ * @remarks
598
+ * `key` is that foreign key. Every related row holding this record's primary-key value
599
+ * in it is attached, so the loaded property is an array.
600
+ */
601
+ export declare interface ResolvedMany {
602
+ readonly relationship: 'many';
603
+ readonly name: string;
604
+ readonly model: string;
605
+ readonly key: string;
606
+ }
607
+
608
+ /**
609
+ * Represents a `morph` relation resolved at define-time — a polymorphic foreign key and its
610
+ * discriminator.
611
+ *
612
+ * @remarks
613
+ * `key` is the foreign key on the related table, `tag` the discriminator column beside
614
+ * it, and `label` the discriminator value identifying THIS model.
615
+ */
616
+ export declare interface ResolvedMorph {
617
+ readonly relationship: 'morph';
618
+ readonly name: string;
619
+ readonly model: string;
620
+ readonly key: string;
621
+ readonly tag: string;
622
+ readonly label: string;
623
+ }
624
+
625
+ /**
626
+ * Represents a `one` relation resolved at define-time — {@link ResolvedMany}'s foreign key, one
627
+ * row.
628
+ *
629
+ * @remarks
630
+ * `key` is the foreign key on the related table. The first matching row is attached and
631
+ * a miss reads as `undefined`.
632
+ */
633
+ export declare interface ResolvedOne {
634
+ readonly relationship: 'one';
635
+ readonly name: string;
636
+ readonly model: string;
637
+ readonly key: string;
638
+ }
639
+
640
+ /**
641
+ * Represents a relation resolved at define-time into a flat, ready-to-load form.
642
+ *
643
+ * @remarks
644
+ * A union over the arms {@link Relationship} names, discriminated on `relationship`:
645
+ * each arm declares exactly the columns that arm needs to load, link, and unlink, and
646
+ * declares them required. `resolveRelation` precomputes and validates them from the raw
647
+ * {@link Relation}, so no inference and no absence check runs at query time. Narrow on
648
+ * `relationship` before reading an arm's own columns.
649
+ */
650
+ export declare type ResolvedRelation = ResolvedBelongs | ResolvedMany | ResolvedOne | ResolvedThrough | ResolvedMorph;
651
+
652
+ /**
653
+ * Represents a `through` relation resolved at define-time — a junction table links the two
654
+ * sides.
655
+ *
656
+ * @remarks
657
+ * `through` is the junction table, `source` its foreign-key column pointing at THIS
658
+ * model, and `target` its foreign-key column pointing at the related model. These are
659
+ * the columns `link` / `unlink` / `links` write and read.
660
+ */
661
+ export declare interface ResolvedThrough {
662
+ readonly relationship: 'through';
663
+ readonly name: string;
664
+ readonly model: string;
665
+ readonly through: string;
666
+ readonly source: string;
667
+ readonly target: string;
428
668
  }
429
669
 
430
670
  /**
431
- * Resolve one raw {@link Relation} value into a flat {@link ResolvedRelation}.
671
+ * Resolves one raw {@link Relation} value into a flat {@link ResolvedRelation}.
432
672
  *
433
673
  * @remarks
434
674
  * A `string` is a `belongs` (FK column on this table); a `readonly string[]` is a
435
675
  * `many` (FK column on the related table); a {@link RelationDescriptor} uses its
436
676
  * explicit `relationship`, or infers it from the fields present. The target model
437
- * defaults to the relation name. Throws `INVALID` when the relationship cannot be
438
- * resolved or a required field is missing.
677
+ * defaults to the relation name. Every column the resolved arm declares is validated
678
+ * here, which is what lets each arm declare its columns required.
439
679
  *
440
680
  * @param name - The relation name (its key in the {@link RelationMap})
441
681
  * @param value - The raw relation value
442
- * @returns The resolved relation
682
+ * @returns The resolved relation, on the arm its `relationship` names
683
+ * @throws An `INVALID` {@link RelationError} when the relationship cannot be resolved, or when a
684
+ * column the resolved arm declares is missing
443
685
  */
444
686
  export declare function resolveRelation(name: string, value: Relation): ResolvedRelation;
445
687
 
446
688
  /**
447
- * Resolve every entry of a {@link RelationMap} into a name → {@link ResolvedRelation} map.
689
+ * Resolves every entry of a {@link RelationMap} into a name → {@link ResolvedRelation} map.
448
690
  *
449
691
  * @param relations - The raw relation map
450
692
  * @returns A map keyed by relation name