@orkestrel/relation 0.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +77 -0
- package/dist/src/core/index.cjs +569 -0
- package/dist/src/core/index.cjs.map +1 -0
- package/dist/src/core/index.d.cts +438 -0
- package/dist/src/core/index.d.ts +438 -0
- package/dist/src/core/index.js +556 -0
- package/dist/src/core/index.js.map +1 -0
- package/package.json +84 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Orkestrel
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
# @orkestrel/relation
|
|
2
|
+
|
|
3
|
+
A typed **relation manager** over [`@orkestrel/database`](https://github.com/orkestrel/database)
|
|
4
|
+
tables — name a table's relations once, then `load` / `find` records with their
|
|
5
|
+
related rows already attached. Loading is **batched** — one query per relation
|
|
6
|
+
across the whole record set, grouped in memory and merged on — so a hundred
|
|
7
|
+
parents cost the same number of round-trips as one. Five relation kinds
|
|
8
|
+
(`belongs` / `many` / `one` / `through` / `morph`) cover the FK shapes; nested
|
|
9
|
+
includes recurse through the registry; `link` / `unlink` / `links` manage a
|
|
10
|
+
many-to-many junction without hand-writing join rows. Environment-agnostic —
|
|
11
|
+
no I/O, no browser or server assumptions. Part of the `@orkestrel` line.
|
|
12
|
+
|
|
13
|
+
## Install
|
|
14
|
+
|
|
15
|
+
```sh
|
|
16
|
+
npm install @orkestrel/relation
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
## Requirements
|
|
20
|
+
|
|
21
|
+
- Node.js >= 24
|
|
22
|
+
- ESM-only (no CommonJS build)
|
|
23
|
+
|
|
24
|
+
## Usage
|
|
25
|
+
|
|
26
|
+
```ts
|
|
27
|
+
import { createRelationManager, belongsTo, hasMany, hasThrough } from '@orkestrel/relation'
|
|
28
|
+
import { createDatabase, createMemoryDriver } from '@orkestrel/database'
|
|
29
|
+
import { stringShape } from '@orkestrel/contract'
|
|
30
|
+
|
|
31
|
+
const db = createDatabase({
|
|
32
|
+
driver: createMemoryDriver(),
|
|
33
|
+
tables: {
|
|
34
|
+
accounts: { id: stringShape(), name: stringShape(), classificationId: stringShape() },
|
|
35
|
+
contacts: { id: stringShape(), accountId: stringShape(), email: stringShape() },
|
|
36
|
+
classifications: { id: stringShape(), label: stringShape() },
|
|
37
|
+
},
|
|
38
|
+
})
|
|
39
|
+
|
|
40
|
+
const manager = createRelationManager({
|
|
41
|
+
database: db,
|
|
42
|
+
relations: {
|
|
43
|
+
accounts: {
|
|
44
|
+
classification: belongsTo('classificationId', 'classifications'), // FK on accounts
|
|
45
|
+
contacts: hasMany('accountId'), // FK on contacts → back here
|
|
46
|
+
},
|
|
47
|
+
contacts: { account: belongsTo('accountId', 'accounts') },
|
|
48
|
+
},
|
|
49
|
+
})
|
|
50
|
+
|
|
51
|
+
const accounts = manager.model('accounts') // a typed Model; only the relations you ask for load
|
|
52
|
+
const acme = await accounts.load('acc1', { contacts: true, classification: true })
|
|
53
|
+
|
|
54
|
+
acme?.name // ✅ the base row is the table's row type
|
|
55
|
+
acme?.contacts // the relation property — broad (Row | readonly Row[] | undefined)
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
`model(name)` is checked against the database's declared tables, so a typo is a
|
|
59
|
+
compile error. The model's own table (`model.table`) carries that table's row
|
|
60
|
+
type; the attached related rows are the broad `Row` — narrow them where you
|
|
61
|
+
read them.
|
|
62
|
+
|
|
63
|
+
## Guide
|
|
64
|
+
|
|
65
|
+
For the full surface — the manager, the `Model`, the relation builders
|
|
66
|
+
(`belongsTo` / `hasMany` / `hasOne` / `hasThrough` / `hasMorph`), resolution,
|
|
67
|
+
errors, and the observation surface — see
|
|
68
|
+
[`guides/src/relation.md`](guides/src/relation.md).
|
|
69
|
+
|
|
70
|
+
## Package
|
|
71
|
+
|
|
72
|
+
Published as a single typed entry point per the `exports` field in
|
|
73
|
+
`package.json`.
|
|
74
|
+
|
|
75
|
+
## License
|
|
76
|
+
|
|
77
|
+
MIT © [Orkestrel](https://github.com/orkestrel) — see [LICENSE](./LICENSE).
|
|
@@ -0,0 +1,569 @@
|
|
|
1
|
+
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
+
let _orkestrel_contract = require("@orkestrel/contract");
|
|
3
|
+
let _orkestrel_database = require("@orkestrel/database");
|
|
4
|
+
let _orkestrel_emitter = require("@orkestrel/emitter");
|
|
5
|
+
//#region src/core/errors.ts
|
|
6
|
+
/**
|
|
7
|
+
* An error thrown by the relations layer.
|
|
8
|
+
*
|
|
9
|
+
* @remarks
|
|
10
|
+
* Thrown for: a relation value whose relationship cannot be inferred (`INVALID`), a
|
|
11
|
+
* reference to a relation a model does not define (`UNKNOWN_RELATION`), and
|
|
12
|
+
* `link` / `unlink` / `links` on a relation that is not a `through` (`NOT_THROUGH`).
|
|
13
|
+
*/
|
|
14
|
+
var RelationError = class extends Error {
|
|
15
|
+
code;
|
|
16
|
+
context;
|
|
17
|
+
constructor(code, message, context) {
|
|
18
|
+
super(message);
|
|
19
|
+
this.name = "RelationError";
|
|
20
|
+
this.code = code;
|
|
21
|
+
this.context = context;
|
|
22
|
+
}
|
|
23
|
+
};
|
|
24
|
+
/**
|
|
25
|
+
* Narrow an unknown caught value to a {@link RelationError}.
|
|
26
|
+
*
|
|
27
|
+
* @param value - The value to test (typically a `catch` binding)
|
|
28
|
+
* @returns `true` when `value` is a {@link RelationError}
|
|
29
|
+
*/
|
|
30
|
+
function isRelationError(value) {
|
|
31
|
+
return value instanceof RelationError;
|
|
32
|
+
}
|
|
33
|
+
//#endregion
|
|
34
|
+
//#region src/core/helpers.ts
|
|
35
|
+
/**
|
|
36
|
+
* Narrow a value to a {@link RelationDescriptor} (the object form of a relation).
|
|
37
|
+
*
|
|
38
|
+
* @param value - The value to test
|
|
39
|
+
* @returns `true` when `value` is a plain record
|
|
40
|
+
*/
|
|
41
|
+
function isRelationDescriptor(value) {
|
|
42
|
+
return (0, _orkestrel_contract.isRecord)(value);
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* Resolve one raw {@link Relation} value into a flat {@link ResolvedRelation}.
|
|
46
|
+
*
|
|
47
|
+
* @remarks
|
|
48
|
+
* A `string` is a `belongs` (FK column on this table); a `readonly string[]` is a
|
|
49
|
+
* `many` (FK column on the related table); a {@link RelationDescriptor} uses its
|
|
50
|
+
* explicit `relationship`, or infers it from the fields present. The target model
|
|
51
|
+
* defaults to the relation name. Throws `INVALID` when the relationship cannot be
|
|
52
|
+
* resolved or a required field is missing.
|
|
53
|
+
*
|
|
54
|
+
* @param name - The relation name (its key in the {@link RelationMap})
|
|
55
|
+
* @param value - The raw relation value
|
|
56
|
+
* @returns The resolved relation
|
|
57
|
+
*/
|
|
58
|
+
function resolveRelation(name, value) {
|
|
59
|
+
if ((0, _orkestrel_contract.isString)(value)) return {
|
|
60
|
+
relationship: "belongs",
|
|
61
|
+
name,
|
|
62
|
+
model: name,
|
|
63
|
+
column: value
|
|
64
|
+
};
|
|
65
|
+
if ((0, _orkestrel_contract.isArray)(value)) {
|
|
66
|
+
const key = value[0];
|
|
67
|
+
if (!(0, _orkestrel_contract.isString)(key)) throw new RelationError("INVALID", `Relation '${name}': array form needs a string FK column`, { relation: name });
|
|
68
|
+
return {
|
|
69
|
+
relationship: "many",
|
|
70
|
+
name,
|
|
71
|
+
model: name,
|
|
72
|
+
key
|
|
73
|
+
};
|
|
74
|
+
}
|
|
75
|
+
if (!isRelationDescriptor(value)) throw new RelationError("INVALID", `Relation '${name}': not a string, array, or descriptor`, { relation: name });
|
|
76
|
+
const model = value.model ?? name;
|
|
77
|
+
const infer = () => {
|
|
78
|
+
if ((0, _orkestrel_contract.isDefined)(value.through)) return "through";
|
|
79
|
+
if ((0, _orkestrel_contract.isDefined)(value.tag)) return "morph";
|
|
80
|
+
if ((0, _orkestrel_contract.isDefined)(value.column)) return "belongs";
|
|
81
|
+
if ((0, _orkestrel_contract.isDefined)(value.key)) return "one";
|
|
82
|
+
throw new RelationError("INVALID", `Relation '${name}': cannot infer relationship from descriptor`, { relation: name });
|
|
83
|
+
};
|
|
84
|
+
const relationship = value.relationship ?? infer();
|
|
85
|
+
const require = (present, fields) => {
|
|
86
|
+
if (!present) throw new RelationError("INVALID", `Relation '${name}': ${relationship} needs ${fields}`, { relation: name });
|
|
87
|
+
};
|
|
88
|
+
switch (relationship) {
|
|
89
|
+
case "belongs":
|
|
90
|
+
require((0, _orkestrel_contract.isDefined)(value.column), `'column'`);
|
|
91
|
+
return {
|
|
92
|
+
relationship,
|
|
93
|
+
name,
|
|
94
|
+
model,
|
|
95
|
+
column: value.column
|
|
96
|
+
};
|
|
97
|
+
case "many":
|
|
98
|
+
require((0, _orkestrel_contract.isDefined)(value.key), `'key'`);
|
|
99
|
+
return {
|
|
100
|
+
relationship,
|
|
101
|
+
name,
|
|
102
|
+
model,
|
|
103
|
+
key: value.key
|
|
104
|
+
};
|
|
105
|
+
case "one":
|
|
106
|
+
require((0, _orkestrel_contract.isDefined)(value.key), `'key'`);
|
|
107
|
+
return {
|
|
108
|
+
relationship,
|
|
109
|
+
name,
|
|
110
|
+
model,
|
|
111
|
+
key: value.key
|
|
112
|
+
};
|
|
113
|
+
case "through":
|
|
114
|
+
require((0, _orkestrel_contract.isDefined)(value.through) && (0, _orkestrel_contract.isDefined)(value.source) && (0, _orkestrel_contract.isDefined)(value.target), `'through', 'source', and 'target'`);
|
|
115
|
+
return {
|
|
116
|
+
relationship,
|
|
117
|
+
name,
|
|
118
|
+
model,
|
|
119
|
+
through: value.through,
|
|
120
|
+
source: value.source,
|
|
121
|
+
target: value.target
|
|
122
|
+
};
|
|
123
|
+
case "morph":
|
|
124
|
+
require((0, _orkestrel_contract.isDefined)(value.key) && (0, _orkestrel_contract.isDefined)(value.tag) && (0, _orkestrel_contract.isDefined)(value.label), `'key', 'tag', and 'label'`);
|
|
125
|
+
return {
|
|
126
|
+
relationship,
|
|
127
|
+
name,
|
|
128
|
+
model,
|
|
129
|
+
key: value.key,
|
|
130
|
+
tag: value.tag,
|
|
131
|
+
label: value.label
|
|
132
|
+
};
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
/**
|
|
136
|
+
* Resolve every entry of a {@link RelationMap} into a name → {@link ResolvedRelation} map.
|
|
137
|
+
*
|
|
138
|
+
* @param relations - The raw relation map
|
|
139
|
+
* @returns A map keyed by relation name
|
|
140
|
+
*/
|
|
141
|
+
function resolveRelationMap(relations) {
|
|
142
|
+
const resolved = /* @__PURE__ */ new Map();
|
|
143
|
+
for (const [name, value] of Object.entries(relations)) resolved.set(name, resolveRelation(name, value));
|
|
144
|
+
return resolved;
|
|
145
|
+
}
|
|
146
|
+
/**
|
|
147
|
+
* Build a `belongs` relation — a foreign key on THIS table points at the related row.
|
|
148
|
+
*
|
|
149
|
+
* @param column - The FK column on this table
|
|
150
|
+
* @param model - Target table name (defaults to the relation name)
|
|
151
|
+
* @returns A {@link RelationDescriptor}
|
|
152
|
+
*
|
|
153
|
+
* @example
|
|
154
|
+
* ```ts
|
|
155
|
+
* { classification: belongsTo('classificationId', 'classifications') }
|
|
156
|
+
* ```
|
|
157
|
+
*/
|
|
158
|
+
function belongsTo(column, model) {
|
|
159
|
+
return {
|
|
160
|
+
relationship: "belongs",
|
|
161
|
+
column,
|
|
162
|
+
...model !== void 0 ? { model } : {}
|
|
163
|
+
};
|
|
164
|
+
}
|
|
165
|
+
/**
|
|
166
|
+
* Build a `many` relation — a foreign key on the RELATED table points back here.
|
|
167
|
+
*
|
|
168
|
+
* @param key - The FK column on the related table
|
|
169
|
+
* @param model - Target table name (defaults to the relation name)
|
|
170
|
+
* @returns A {@link RelationDescriptor}
|
|
171
|
+
*/
|
|
172
|
+
function hasMany(key, model) {
|
|
173
|
+
return {
|
|
174
|
+
relationship: "many",
|
|
175
|
+
key,
|
|
176
|
+
...model !== void 0 ? { model } : {}
|
|
177
|
+
};
|
|
178
|
+
}
|
|
179
|
+
/**
|
|
180
|
+
* Build a `one` relation — like {@link hasMany}, but a single related row.
|
|
181
|
+
*
|
|
182
|
+
* @param key - The FK column on the related table
|
|
183
|
+
* @param model - Target table name (defaults to the relation name)
|
|
184
|
+
* @returns A {@link RelationDescriptor}
|
|
185
|
+
*/
|
|
186
|
+
function hasOne(key, model) {
|
|
187
|
+
return {
|
|
188
|
+
relationship: "one",
|
|
189
|
+
key,
|
|
190
|
+
...model !== void 0 ? { model } : {}
|
|
191
|
+
};
|
|
192
|
+
}
|
|
193
|
+
/**
|
|
194
|
+
* Build a `through` relation — a junction table links the two sides (many-to-many).
|
|
195
|
+
*
|
|
196
|
+
* @param through - The junction table name
|
|
197
|
+
* @param source - The junction FK column pointing at THIS model
|
|
198
|
+
* @param target - The junction FK column pointing at the related model
|
|
199
|
+
* @param model - Target table name (defaults to the relation name)
|
|
200
|
+
* @returns A {@link RelationDescriptor}
|
|
201
|
+
*
|
|
202
|
+
* @example
|
|
203
|
+
* ```ts
|
|
204
|
+
* { reps: hasThrough('accountReps', 'accountId', 'repId', 'reps') }
|
|
205
|
+
* ```
|
|
206
|
+
*/
|
|
207
|
+
function hasThrough(through, source, target, model) {
|
|
208
|
+
return {
|
|
209
|
+
relationship: "through",
|
|
210
|
+
through,
|
|
211
|
+
source,
|
|
212
|
+
target,
|
|
213
|
+
...model !== void 0 ? { model } : {}
|
|
214
|
+
};
|
|
215
|
+
}
|
|
216
|
+
/**
|
|
217
|
+
* Build a `morph` relation — a polymorphic FK plus a discriminator on the RELATED table.
|
|
218
|
+
*
|
|
219
|
+
* @param key - The FK column on the related table
|
|
220
|
+
* @param tag - The discriminator column on the related table
|
|
221
|
+
* @param label - The discriminator value identifying THIS model
|
|
222
|
+
* @param model - Target table name (defaults to the relation name)
|
|
223
|
+
* @returns A {@link RelationDescriptor}
|
|
224
|
+
*
|
|
225
|
+
* @example
|
|
226
|
+
* ```ts
|
|
227
|
+
* { notes: hasMorph('entityId', 'entityType', 'account', 'notes') }
|
|
228
|
+
* ```
|
|
229
|
+
*/
|
|
230
|
+
function hasMorph(key, tag, label, model) {
|
|
231
|
+
return {
|
|
232
|
+
relationship: "morph",
|
|
233
|
+
key,
|
|
234
|
+
tag,
|
|
235
|
+
label,
|
|
236
|
+
...model !== void 0 ? { model } : {}
|
|
237
|
+
};
|
|
238
|
+
}
|
|
239
|
+
//#endregion
|
|
240
|
+
//#region src/core/Model.ts
|
|
241
|
+
/**
|
|
242
|
+
* A model — a typed table paired with relation-aware loading.
|
|
243
|
+
*
|
|
244
|
+
* @remarks
|
|
245
|
+
* The model's own table is fully typed (`table`); related tables are reached by
|
|
246
|
+
* runtime name through the database at the broad `Row` type. Loading is batched:
|
|
247
|
+
* for each relation, one query fetches the related rows for the whole record set
|
|
248
|
+
* (`where(col).any(keys)`), grouped in memory and attached — no N+1. Nested
|
|
249
|
+
* includes recurse through the registry `lookup`, so loaded relations carry their
|
|
250
|
+
* own loaded relations. Columns are read with `Reflect.get` (the base row's type
|
|
251
|
+
* is closed) and relation properties merged with `Object.assign` — no `as`.
|
|
252
|
+
*
|
|
253
|
+
* @remarks
|
|
254
|
+
* - **Observable (§13).** The owned {@link emitter} ({@link ModelEventMap}) carries the
|
|
255
|
+
* eager-load + junction moments — `load` (a relation resolved: its name + the count of
|
|
256
|
+
* related rows attached across the whole record set), `link` / `unlink` (a junction row
|
|
257
|
+
* written) — for fire-and-forget observers. Every event is emitted directly, strictly
|
|
258
|
+
* AFTER the load resolves / the junction op completes; the emitter isolates a listener
|
|
259
|
+
* throw and routes it to its `error` handler (the `error` option), so a buggy observer can
|
|
260
|
+
* never corrupt the batched eager-load (no N+1 in the events either — one `load` per
|
|
261
|
+
* relation, not per record).
|
|
262
|
+
*/
|
|
263
|
+
var Model = class {
|
|
264
|
+
#name;
|
|
265
|
+
#table;
|
|
266
|
+
#resolved;
|
|
267
|
+
#relations;
|
|
268
|
+
#lookup;
|
|
269
|
+
#database;
|
|
270
|
+
#emitter;
|
|
271
|
+
constructor(name, table, resolved, relations, lookup, database, on, error) {
|
|
272
|
+
this.#name = name;
|
|
273
|
+
this.#table = table;
|
|
274
|
+
this.#resolved = resolved;
|
|
275
|
+
this.#relations = relations;
|
|
276
|
+
this.#lookup = lookup;
|
|
277
|
+
this.#database = database;
|
|
278
|
+
this.#emitter = new _orkestrel_emitter.Emitter({
|
|
279
|
+
on,
|
|
280
|
+
error
|
|
281
|
+
});
|
|
282
|
+
}
|
|
283
|
+
get emitter() {
|
|
284
|
+
return this.#emitter;
|
|
285
|
+
}
|
|
286
|
+
get name() {
|
|
287
|
+
return this.#name;
|
|
288
|
+
}
|
|
289
|
+
get table() {
|
|
290
|
+
return this.#table;
|
|
291
|
+
}
|
|
292
|
+
get relations() {
|
|
293
|
+
return this.#relations;
|
|
294
|
+
}
|
|
295
|
+
async load(keys, include) {
|
|
296
|
+
if ((0, _orkestrel_contract.isArray)(keys)) {
|
|
297
|
+
const bases = await this.#table.get(keys);
|
|
298
|
+
const present = bases.filter(_orkestrel_contract.isDefined);
|
|
299
|
+
const props = await this.#populate(present, include, this.#resolved, this.#table.primary);
|
|
300
|
+
let next = 0;
|
|
301
|
+
return bases.map((base) => base === void 0 ? void 0 : Object.assign({}, base, props[next++]));
|
|
302
|
+
}
|
|
303
|
+
const base = await this.#table.get(keys);
|
|
304
|
+
if (base === void 0) return void 0;
|
|
305
|
+
const [props] = await this.#populate([base], include, this.#resolved, this.#table.primary);
|
|
306
|
+
return Object.assign({}, base, props);
|
|
307
|
+
}
|
|
308
|
+
async find(include, options) {
|
|
309
|
+
const query = this.#table.query();
|
|
310
|
+
if (options?.sort !== void 0) if (options.direction === "descending") query.descending(options.sort);
|
|
311
|
+
else query.ascending(options.sort);
|
|
312
|
+
if (options?.offset !== void 0) query.offset(options.offset);
|
|
313
|
+
if (options?.limit !== void 0) query.limit(options.limit);
|
|
314
|
+
const records = await query.all();
|
|
315
|
+
const props = await this.#populate(records, include, this.#resolved, this.#table.primary);
|
|
316
|
+
return records.map((record, index) => Object.assign({}, record, props[index]));
|
|
317
|
+
}
|
|
318
|
+
async link(key, relation, target) {
|
|
319
|
+
const resolved = this.#through(relation);
|
|
320
|
+
await this.#database.table(resolved.through ?? "").set({
|
|
321
|
+
[resolved.source ?? ""]: key,
|
|
322
|
+
[resolved.target ?? ""]: target
|
|
323
|
+
});
|
|
324
|
+
this.#emitter.emit("link", key, relation);
|
|
325
|
+
}
|
|
326
|
+
async unlink(key, relation, target) {
|
|
327
|
+
const resolved = this.#through(relation);
|
|
328
|
+
const junction = this.#database.table(resolved.through ?? "");
|
|
329
|
+
const rows = await junction.query().where(resolved.source ?? "").equals(key).and(resolved.target ?? "").equals(target).all();
|
|
330
|
+
for (const row of rows) {
|
|
331
|
+
const id = (0, _orkestrel_database.extractKey)(row, junction.primary);
|
|
332
|
+
if (id !== void 0) await junction.remove(id);
|
|
333
|
+
}
|
|
334
|
+
this.#emitter.emit("unlink", key, relation);
|
|
335
|
+
}
|
|
336
|
+
async links(key, relation) {
|
|
337
|
+
const resolved = this.#through(relation);
|
|
338
|
+
const rows = await this.#database.table(resolved.through ?? "").query().where(resolved.source ?? "").equals(key).all();
|
|
339
|
+
const target = resolved.target ?? "";
|
|
340
|
+
const keys = [];
|
|
341
|
+
for (const row of rows) {
|
|
342
|
+
const value = (0, _orkestrel_database.extractKey)(row, target);
|
|
343
|
+
if (value !== void 0) keys.push(value);
|
|
344
|
+
}
|
|
345
|
+
return keys;
|
|
346
|
+
}
|
|
347
|
+
#field(record, column) {
|
|
348
|
+
return Reflect.get(record, column);
|
|
349
|
+
}
|
|
350
|
+
#through(relation) {
|
|
351
|
+
const resolved = this.#resolved.get(relation);
|
|
352
|
+
if (resolved === void 0) throw new RelationError("UNKNOWN_RELATION", `Model '${this.#name}' has no relation '${relation}'`, {
|
|
353
|
+
model: this.#name,
|
|
354
|
+
relation
|
|
355
|
+
});
|
|
356
|
+
if (resolved.relationship !== "through") throw new RelationError("NOT_THROUGH", `Relation '${relation}' on '${this.#name}' is not a through`, {
|
|
357
|
+
model: this.#name,
|
|
358
|
+
relation
|
|
359
|
+
});
|
|
360
|
+
return resolved;
|
|
361
|
+
}
|
|
362
|
+
async #populate(records, include, resolvedMap, primary) {
|
|
363
|
+
const props = records.map(() => ({}));
|
|
364
|
+
for (const [name, sub] of Object.entries(include)) {
|
|
365
|
+
if (sub === false) continue;
|
|
366
|
+
const resolved = resolvedMap.get(name);
|
|
367
|
+
if (resolved === void 0) continue;
|
|
368
|
+
const values = await this.#load(records, resolved, sub, primary);
|
|
369
|
+
values.forEach((value, index) => {
|
|
370
|
+
props[index][resolved.name] = value;
|
|
371
|
+
});
|
|
372
|
+
this.#emitter.emit("load", resolved.name, this.#attached(values));
|
|
373
|
+
}
|
|
374
|
+
return props;
|
|
375
|
+
}
|
|
376
|
+
#attached(values) {
|
|
377
|
+
let total = 0;
|
|
378
|
+
for (const value of values) if ((0, _orkestrel_contract.isArray)(value)) total += value.length;
|
|
379
|
+
else if (value !== void 0) total += 1;
|
|
380
|
+
return total;
|
|
381
|
+
}
|
|
382
|
+
async #load(records, resolved, sub, primary) {
|
|
383
|
+
switch (resolved.relationship) {
|
|
384
|
+
case "belongs": return this.#loadBelongs(records, resolved, sub);
|
|
385
|
+
case "many": return this.#loadMany(records, resolved, sub, primary);
|
|
386
|
+
case "one": return this.#loadOne(records, resolved, sub, primary);
|
|
387
|
+
case "through": return this.#loadThrough(records, resolved, sub, primary);
|
|
388
|
+
case "morph": return this.#loadMorph(records, resolved, sub, primary);
|
|
389
|
+
}
|
|
390
|
+
}
|
|
391
|
+
async #loadBelongs(records, resolved, sub) {
|
|
392
|
+
const column = resolved.column ?? "";
|
|
393
|
+
const keys = [...new Set(records.map((record) => this.#field(record, column)).filter(_orkestrel_contract.isDefined))];
|
|
394
|
+
if (keys.length === 0) return records.map(() => void 0);
|
|
395
|
+
const related = this.#database.table(resolved.model);
|
|
396
|
+
const rows = await related.query().where(related.primary).any(keys).all();
|
|
397
|
+
const index = this.#index(await this.#nest(resolved.model, rows, sub), related.primary);
|
|
398
|
+
return records.map((record) => {
|
|
399
|
+
const fk = this.#field(record, column);
|
|
400
|
+
return (0, _orkestrel_contract.isDefined)(fk) ? index.get(String(fk)) : void 0;
|
|
401
|
+
});
|
|
402
|
+
}
|
|
403
|
+
async #loadMany(records, resolved, sub, primary) {
|
|
404
|
+
const foreign = resolved.key ?? "";
|
|
405
|
+
const keys = [...new Set(records.map((record) => this.#field(record, primary)).filter(_orkestrel_contract.isDefined))];
|
|
406
|
+
if (keys.length === 0) return records.map(() => []);
|
|
407
|
+
const rows = await this.#database.table(resolved.model).query().where(foreign).any(keys).all();
|
|
408
|
+
const groups = this.#group(await this.#nest(resolved.model, rows, sub), foreign);
|
|
409
|
+
return records.map((record) => groups.get(String(this.#field(record, primary))) ?? []);
|
|
410
|
+
}
|
|
411
|
+
async #loadOne(records, resolved, sub, primary) {
|
|
412
|
+
return (await this.#loadMany(records, resolved, sub, primary)).map((group) => group.length > 0 ? group[0] : void 0);
|
|
413
|
+
}
|
|
414
|
+
async #loadThrough(records, resolved, sub, primary) {
|
|
415
|
+
const source = resolved.source ?? "";
|
|
416
|
+
const target = resolved.target ?? "";
|
|
417
|
+
const parents = [...new Set(records.map((record) => this.#field(record, primary)).filter(_orkestrel_contract.isDefined))];
|
|
418
|
+
if (parents.length === 0) return records.map(() => []);
|
|
419
|
+
const junctions = await this.#database.table(resolved.through ?? "").query().where(source).any(parents).all();
|
|
420
|
+
const targetsBySource = /* @__PURE__ */ new Map();
|
|
421
|
+
for (const junction of junctions) {
|
|
422
|
+
const value = this.#field(junction, target);
|
|
423
|
+
if (!(0, _orkestrel_contract.isDefined)(value)) continue;
|
|
424
|
+
const owner = String(this.#field(junction, source));
|
|
425
|
+
const list = targetsBySource.get(owner);
|
|
426
|
+
if (list !== void 0) list.push(value);
|
|
427
|
+
else targetsBySource.set(owner, [value]);
|
|
428
|
+
}
|
|
429
|
+
const targets = [...new Set([...targetsBySource.values()].flat())];
|
|
430
|
+
if (targets.length === 0) return records.map(() => []);
|
|
431
|
+
const related = this.#database.table(resolved.model);
|
|
432
|
+
const rows = await related.query().where(related.primary).any(targets).all();
|
|
433
|
+
const index = this.#index(await this.#nest(resolved.model, rows, sub), related.primary);
|
|
434
|
+
return records.map((record) => {
|
|
435
|
+
const out = [];
|
|
436
|
+
for (const value of targetsBySource.get(String(this.#field(record, primary))) ?? []) {
|
|
437
|
+
const row = index.get(String(value));
|
|
438
|
+
if (row !== void 0) out.push(row);
|
|
439
|
+
}
|
|
440
|
+
return out;
|
|
441
|
+
});
|
|
442
|
+
}
|
|
443
|
+
async #loadMorph(records, resolved, sub, primary) {
|
|
444
|
+
const foreign = resolved.key ?? "";
|
|
445
|
+
const keys = [...new Set(records.map((record) => this.#field(record, primary)).filter(_orkestrel_contract.isDefined))];
|
|
446
|
+
if (keys.length === 0) return records.map(() => []);
|
|
447
|
+
const rows = await this.#database.table(resolved.model).query().where(foreign).any(keys).and(resolved.tag ?? "").equals(resolved.label ?? "").all();
|
|
448
|
+
const groups = this.#group(await this.#nest(resolved.model, rows, sub), foreign);
|
|
449
|
+
return records.map((record) => groups.get(String(this.#field(record, primary))) ?? []);
|
|
450
|
+
}
|
|
451
|
+
async #nest(model, rows, sub) {
|
|
452
|
+
if (typeof sub === "boolean" || rows.length === 0) return rows;
|
|
453
|
+
const context = this.#lookup(model);
|
|
454
|
+
if (context === void 0) return rows;
|
|
455
|
+
const props = await this.#populate(rows, sub, context.resolved, context.primary);
|
|
456
|
+
return rows.map((row, index) => Object.assign({}, row, props[index]));
|
|
457
|
+
}
|
|
458
|
+
#index(rows, column) {
|
|
459
|
+
const map = /* @__PURE__ */ new Map();
|
|
460
|
+
for (const row of rows) map.set(String(this.#field(row, column)), row);
|
|
461
|
+
return map;
|
|
462
|
+
}
|
|
463
|
+
#group(rows, column) {
|
|
464
|
+
const map = /* @__PURE__ */ new Map();
|
|
465
|
+
for (const row of rows) {
|
|
466
|
+
const key = String(this.#field(row, column));
|
|
467
|
+
const group = map.get(key);
|
|
468
|
+
if (group !== void 0) group.push(row);
|
|
469
|
+
else map.set(key, [row]);
|
|
470
|
+
}
|
|
471
|
+
return map;
|
|
472
|
+
}
|
|
473
|
+
};
|
|
474
|
+
//#endregion
|
|
475
|
+
//#region src/core/RelationManager.ts
|
|
476
|
+
/**
|
|
477
|
+
* The relation registry — resolves a {@link RelationsShape} once at construction
|
|
478
|
+
* and vends a typed {@link ModelInterface} per declared table.
|
|
479
|
+
*
|
|
480
|
+
* @remarks
|
|
481
|
+
* Holds the database both at its precise type (to type each model's own table)
|
|
482
|
+
* and at the broad `DatabaseInterface` (to fetch related tables by runtime name
|
|
483
|
+
* while loading). Relation targets are validated lazily — a relation to a missing
|
|
484
|
+
* table fails when that relation is first loaded.
|
|
485
|
+
*/
|
|
486
|
+
var RelationManager = class {
|
|
487
|
+
#database;
|
|
488
|
+
#broad;
|
|
489
|
+
#relations;
|
|
490
|
+
#resolved = /* @__PURE__ */ new Map();
|
|
491
|
+
constructor(options) {
|
|
492
|
+
this.#database = options.database;
|
|
493
|
+
this.#broad = options.database;
|
|
494
|
+
this.#relations = options.relations ?? {};
|
|
495
|
+
for (const [name, map] of Object.entries(this.#relations)) if (map !== void 0) this.#resolved.set(name, resolveRelationMap(map));
|
|
496
|
+
}
|
|
497
|
+
get count() {
|
|
498
|
+
return this.#resolved.size;
|
|
499
|
+
}
|
|
500
|
+
model(name) {
|
|
501
|
+
const resolved = this.#resolved.get(name) ?? /* @__PURE__ */ new Map();
|
|
502
|
+
const relations = this.#relations[name] ?? {};
|
|
503
|
+
return this.#vend(name, this.#database.table(name), resolved, relations);
|
|
504
|
+
}
|
|
505
|
+
models() {
|
|
506
|
+
return [...this.#resolved.keys()];
|
|
507
|
+
}
|
|
508
|
+
has(name) {
|
|
509
|
+
return this.#resolved.has(name);
|
|
510
|
+
}
|
|
511
|
+
#vend(name, table, resolved, relations) {
|
|
512
|
+
return new Model(name, table, resolved, relations, (model) => this.#context(model), this.#broad);
|
|
513
|
+
}
|
|
514
|
+
#context(model) {
|
|
515
|
+
const resolved = this.#resolved.get(model);
|
|
516
|
+
if (resolved === void 0) return void 0;
|
|
517
|
+
return {
|
|
518
|
+
resolved,
|
|
519
|
+
primary: this.#broad.table(model).primary
|
|
520
|
+
};
|
|
521
|
+
}
|
|
522
|
+
};
|
|
523
|
+
//#endregion
|
|
524
|
+
//#region src/core/factories.ts
|
|
525
|
+
/**
|
|
526
|
+
* Create a relation manager over a database and its relation definitions.
|
|
527
|
+
*
|
|
528
|
+
* @remarks
|
|
529
|
+
* `relations` maps table names (constrained to the database's tables) to their
|
|
530
|
+
* relation maps; build entries with `belongsTo` / `hasMany` / `hasOne` /
|
|
531
|
+
* `hasThrough` / `hasMorph`. `manager.model(name)` returns the typed model for a
|
|
532
|
+
* table — its own table is fully typed, related rows load at the `Row` type.
|
|
533
|
+
*
|
|
534
|
+
* @param options - The `database` and an optional `relations` map
|
|
535
|
+
* @returns A typed {@link RelationManagerInterface}
|
|
536
|
+
*
|
|
537
|
+
* @example
|
|
538
|
+
* ```ts
|
|
539
|
+
* import { createRelationManager, belongsTo, hasMany } from '@src/core'
|
|
540
|
+
*
|
|
541
|
+
* const manager = createRelationManager({
|
|
542
|
+
* database: db,
|
|
543
|
+
* relations: {
|
|
544
|
+
* accounts: { classification: belongsTo('classificationId', 'classifications'), contacts: hasMany('accountId') },
|
|
545
|
+
* contacts: { account: belongsTo('accountId', 'accounts') },
|
|
546
|
+
* },
|
|
547
|
+
* })
|
|
548
|
+
* const acme = await manager.model('accounts').load('acc1', { contacts: true, classification: true })
|
|
549
|
+
* ```
|
|
550
|
+
*/
|
|
551
|
+
function createRelationManager(options) {
|
|
552
|
+
return new RelationManager(options);
|
|
553
|
+
}
|
|
554
|
+
//#endregion
|
|
555
|
+
exports.Model = Model;
|
|
556
|
+
exports.RelationError = RelationError;
|
|
557
|
+
exports.RelationManager = RelationManager;
|
|
558
|
+
exports.belongsTo = belongsTo;
|
|
559
|
+
exports.createRelationManager = createRelationManager;
|
|
560
|
+
exports.hasMany = hasMany;
|
|
561
|
+
exports.hasMorph = hasMorph;
|
|
562
|
+
exports.hasOne = hasOne;
|
|
563
|
+
exports.hasThrough = hasThrough;
|
|
564
|
+
exports.isRelationDescriptor = isRelationDescriptor;
|
|
565
|
+
exports.isRelationError = isRelationError;
|
|
566
|
+
exports.resolveRelation = resolveRelation;
|
|
567
|
+
exports.resolveRelationMap = resolveRelationMap;
|
|
568
|
+
|
|
569
|
+
//# sourceMappingURL=index.cjs.map
|