@orkestrel/relation 0.0.22 → 0.0.24
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/dist/src/core/index.cjs +243 -173
- package/dist/src/core/index.cjs.map +1 -1
- package/dist/src/core/index.d.cts +176 -61
- package/dist/src/core/index.d.ts +176 -61
- package/dist/src/core/index.js +241 -175
- package/dist/src/core/index.js.map +1 -1
- package/package.json +5 -5
package/dist/src/core/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { INTRINSICS, holds, isArray, isBoolean, isDefined, isFunction, isObject, isRecord, isString, literalOf } from "@orkestrel/contract";
|
|
2
|
-
import { checkAbort, extractKey, isDatabaseError } from "@orkestrel/database";
|
|
1
|
+
import { INTRINSICS, admitValue, createContract, describeFaults, holds, isArray, isBoolean, isDefined, isFailure, isFunction, isInstance, isObject, isRecord, isString, literalOf, literalShape, objectShape, optionalShape, renderPath, resolveField, stringShape } from "@orkestrel/contract";
|
|
2
|
+
import { checkAbort, extractKey, isDatabaseError, isKey } from "@orkestrel/database";
|
|
3
3
|
import { Emitter } from "@orkestrel/emitter";
|
|
4
4
|
// src/core/errors.ts
|
|
5
5
|
/**
|
|
@@ -9,7 +9,9 @@ import { Emitter } from "@orkestrel/emitter";
|
|
|
9
9
|
* @remarks
|
|
10
10
|
* Thrown for: a relation value whose relationship cannot be inferred (`INVALID`), a
|
|
11
11
|
* relation targeting a table or junction the database does not declare, raised when
|
|
12
|
-
* the manager is created (`INVALID`), a
|
|
12
|
+
* the manager is created (`INVALID`), a junction keyed by its relation's `source` or
|
|
13
|
+
* `target` column (`INVALID`), a row a storage returns that is not a plain record
|
|
14
|
+
* (`INVALID`), a reference to a relation a model does not
|
|
13
15
|
* define (`UNKNOWN_RELATION`), and `link` / `unlink` / `links` on a relation that is
|
|
14
16
|
* not a `through` (`NOT_THROUGH`).
|
|
15
17
|
*/
|
|
@@ -27,58 +29,104 @@ var RelationError = class extends Error {
|
|
|
27
29
|
/**
|
|
28
30
|
* Narrows an unknown caught value to a {@link RelationError}.
|
|
29
31
|
*
|
|
32
|
+
* @remarks
|
|
33
|
+
* Accepts branded instances and subclasses across package copies and module formats.
|
|
34
|
+
* Requires a declared {@link RelationErrorCode} and a `context` that is absent, an object,
|
|
35
|
+
* or a callable object. Refuses look-alikes, transparent proxies, and plain branded objects
|
|
36
|
+
* without requiring an exact `name`.
|
|
37
|
+
*
|
|
30
38
|
* @param value - The value to test (typically a `catch` binding)
|
|
31
|
-
* @returns True if
|
|
39
|
+
* @returns True if `value` is a {@link RelationError}; false otherwise
|
|
40
|
+
*
|
|
41
|
+
* @example
|
|
42
|
+
* ```ts
|
|
43
|
+
* try {
|
|
44
|
+
* resolveRelation('ghost', {})
|
|
45
|
+
* } catch (error) {
|
|
46
|
+
* if (isRelationError(error) && error.code === 'INVALID') report(error.message)
|
|
47
|
+
* }
|
|
48
|
+
* ```
|
|
32
49
|
*/
|
|
33
50
|
function isRelationError(value) {
|
|
34
51
|
return holds(() => {
|
|
35
|
-
|
|
36
|
-
if (
|
|
52
|
+
const intrinsic = INTRINSICS.error;
|
|
53
|
+
if (!isInstance(value, intrinsic) || INTRINSICS.prototype(value) === intrinsic.prototype) return false;
|
|
54
|
+
const brand = INTRINSICS.describe(value, Symbol.for("@orkestrel/relation.RelationError"));
|
|
55
|
+
if (brand === void 0 || brand.value !== value) return false;
|
|
37
56
|
const code = INTRINSICS.reflect.read(value, "code");
|
|
38
|
-
if (
|
|
57
|
+
if (!literalOf("INVALID", "UNKNOWN_RELATION", "NOT_THROUGH")(code)) return false;
|
|
39
58
|
const context = INTRINSICS.reflect.read(value, "context");
|
|
40
59
|
return context === void 0 || isObject(context) || isFunction(context);
|
|
41
60
|
});
|
|
42
61
|
}
|
|
62
|
+
// src/core/shapers.ts
|
|
63
|
+
/**
|
|
64
|
+
* Declares the object form of a relation as a closed contract shape.
|
|
65
|
+
*
|
|
66
|
+
* @remarks
|
|
67
|
+
* Every member is optional: `relationship` is one of the `Relationship` values, and
|
|
68
|
+
* `column`, `key`, `through`, `source`, `target`, `tag`, `label`, and `model` are strings.
|
|
69
|
+
* The object is closed, so an enumerable, string-keyed member the descriptor does not declare
|
|
70
|
+
* refuses it.
|
|
71
|
+
*
|
|
72
|
+
* @example
|
|
73
|
+
* ```ts
|
|
74
|
+
* import { createContract } from '@orkestrel/contract'
|
|
75
|
+
* import { relationDescriptorShape } from '@orkestrel/relation'
|
|
76
|
+
*
|
|
77
|
+
* createContract(relationDescriptorShape).is({ column: 'accountId', comment: 'x' }) // false
|
|
78
|
+
* ```
|
|
79
|
+
*/
|
|
80
|
+
var relationDescriptorShape = objectShape({
|
|
81
|
+
relationship: optionalShape(literalShape([
|
|
82
|
+
"belongs",
|
|
83
|
+
"many",
|
|
84
|
+
"one",
|
|
85
|
+
"through",
|
|
86
|
+
"morph"
|
|
87
|
+
])),
|
|
88
|
+
column: optionalShape(stringShape()),
|
|
89
|
+
key: optionalShape(stringShape()),
|
|
90
|
+
through: optionalShape(stringShape()),
|
|
91
|
+
source: optionalShape(stringShape()),
|
|
92
|
+
target: optionalShape(stringShape()),
|
|
93
|
+
tag: optionalShape(stringShape()),
|
|
94
|
+
label: optionalShape(stringShape()),
|
|
95
|
+
model: optionalShape(stringShape())
|
|
96
|
+
});
|
|
97
|
+
// src/core/contracts.ts
|
|
98
|
+
/**
|
|
99
|
+
* Holds the compiled contract of a relation descriptor, which `resolveRelation` admits through.
|
|
100
|
+
*
|
|
101
|
+
* @example
|
|
102
|
+
* ```ts
|
|
103
|
+
* import { relationDescriptorContract } from '@orkestrel/relation'
|
|
104
|
+
*
|
|
105
|
+
* relationDescriptorContract.audit({ column: 'accountId', comment: 'x' }) // [{ reason: 'extra', path: ['comment'] }]
|
|
106
|
+
* ```
|
|
107
|
+
*/
|
|
108
|
+
var relationDescriptorContract = createContract(relationDescriptorShape);
|
|
43
109
|
// src/core/validators.ts
|
|
44
110
|
/**
|
|
45
111
|
* Narrows a value to a {@link RelationDescriptor} (the object form of a relation).
|
|
46
112
|
*
|
|
47
113
|
* @remarks
|
|
48
|
-
*
|
|
49
|
-
*
|
|
50
|
-
* `through`, `source`, `target`, `tag`, `label`, and `model`
|
|
51
|
-
*
|
|
52
|
-
*
|
|
53
|
-
*
|
|
54
|
-
*
|
|
55
|
-
* wrong-typed column into an arm that declares it a string.
|
|
56
|
-
*
|
|
57
|
-
* @param value - The value to test
|
|
58
|
-
* @returns True if `value` is a record whose every declared member holds its declared
|
|
59
|
-
* type; false otherwise
|
|
114
|
+
* The guard of the compiled `relationDescriptorContract`: a plain record whose every
|
|
115
|
+
* member is optional, with `relationship` one of the `Relationship` values and `column`,
|
|
116
|
+
* `key`, `through`, `source`, `target`, `tag`, `label`, and `model` strings. A member
|
|
117
|
+
* present with an `undefined` value, a member holding another type, and an enumerable,
|
|
118
|
+
* string-keyed member the descriptor does not declare each refuse it. That is what lets
|
|
119
|
+
* `resolveRelation` read each member after one narrow and report a malformed definition
|
|
120
|
+
* as an `INVALID` `RelationError`.
|
|
60
121
|
*
|
|
61
122
|
* @example
|
|
62
123
|
* ```ts
|
|
63
124
|
* isRelationDescriptor(belongsTo('accountId')) // true
|
|
64
125
|
* isRelationDescriptor({ column: 42 }) // false — `column` is declared a string
|
|
126
|
+
* isRelationDescriptor({ column: 'accountId', comment: 'x' }) // false — `comment` is undeclared
|
|
65
127
|
* ```
|
|
66
128
|
*/
|
|
67
|
-
|
|
68
|
-
if (!isRecord(value)) return false;
|
|
69
|
-
if ("relationship" in value && !literalOf("belongs", "many", "one", "through", "morph")(value.relationship)) return false;
|
|
70
|
-
for (const member of [
|
|
71
|
-
"column",
|
|
72
|
-
"key",
|
|
73
|
-
"through",
|
|
74
|
-
"source",
|
|
75
|
-
"target",
|
|
76
|
-
"tag",
|
|
77
|
-
"label",
|
|
78
|
-
"model"
|
|
79
|
-
]) if (member in value && !isString(value[member])) return false;
|
|
80
|
-
return true;
|
|
81
|
-
}
|
|
129
|
+
var isRelationDescriptor = relationDescriptorContract.is;
|
|
82
130
|
// src/core/helpers.ts
|
|
83
131
|
/**
|
|
84
132
|
* Validates a relation table through its bound storage, translating only an undeclared table.
|
|
@@ -100,7 +148,7 @@ function validateRelationTable(storage, model, relation, table, junction = false
|
|
|
100
148
|
storage.table(table);
|
|
101
149
|
} catch (error) {
|
|
102
150
|
if (!isDatabaseError(error) || error.code !== "NOT_FOUND") throw error;
|
|
103
|
-
throw new RelationError("INVALID", `
|
|
151
|
+
throw new RelationError("INVALID", junction ? `Relation ${renderPath([model, relation])} uses undeclared junction ${renderPath([table])}; declare it in the database's tables or correct the relation's through` : `Relation ${renderPath([model, relation])} targets undeclared table ${renderPath([table])}; declare it in the database's tables or correct the relation's model`, {
|
|
104
152
|
model,
|
|
105
153
|
relation,
|
|
106
154
|
table
|
|
@@ -108,20 +156,78 @@ function validateRelationTable(storage, model, relation, table, junction = false
|
|
|
108
156
|
}
|
|
109
157
|
}
|
|
110
158
|
/**
|
|
159
|
+
* Validates that a `through` relation's junction keys its rows by a column of its own.
|
|
160
|
+
*
|
|
161
|
+
* @remarks
|
|
162
|
+
* `link` writes the pair's `computeLinkKey` into the junction's primary column, so a junction
|
|
163
|
+
* whose primary column is the relation's `source` or `target` column cannot hold that key.
|
|
164
|
+
*
|
|
165
|
+
* @param model - The owning model's name
|
|
166
|
+
* @param resolved - The resolved `through` relation
|
|
167
|
+
* @param primary - The junction table's primary-key column
|
|
168
|
+
* @throws An `INVALID` {@link RelationError} when `primary` is the relation's `source` or
|
|
169
|
+
* `target` column
|
|
170
|
+
*
|
|
171
|
+
* @example
|
|
172
|
+
* ```ts
|
|
173
|
+
* validateRelationJunction('accounts', resolved, 'id') // a junction keyed by `id` passes
|
|
174
|
+
* ```
|
|
175
|
+
*/
|
|
176
|
+
function validateRelationJunction(model, resolved, primary) {
|
|
177
|
+
const role = primary === resolved.source ? "source" : primary === resolved.target ? "target" : void 0;
|
|
178
|
+
if (role === void 0) return;
|
|
179
|
+
throw new RelationError("INVALID", `Relation ${renderPath([model, resolved.name])} keys its junction ${renderPath([resolved.through])} by its ${role} column ${renderPath([primary])}; give the junction a separate text primary column, which link fills with computeLinkKey`, {
|
|
180
|
+
model,
|
|
181
|
+
relation: resolved.name,
|
|
182
|
+
table: resolved.through,
|
|
183
|
+
column: primary
|
|
184
|
+
});
|
|
185
|
+
}
|
|
186
|
+
/**
|
|
187
|
+
* Reads one row a storage returned, refusing a value that is not a plain record.
|
|
188
|
+
*
|
|
189
|
+
* @remarks
|
|
190
|
+
* Contract's `isRecord` decides, so a class instance, an array, or a primitive that a custom
|
|
191
|
+
* `DatabaseStorageInterface` returns raises rather than reading as a miss or dropping.
|
|
192
|
+
*
|
|
193
|
+
* @param table - The table the row came from
|
|
194
|
+
* @param row - The row as the storage returned it
|
|
195
|
+
* @returns The row, narrowed to a record
|
|
196
|
+
* @throws An `INVALID` {@link RelationError} naming `table` when `row` is not a plain record
|
|
197
|
+
*
|
|
198
|
+
* @example
|
|
199
|
+
* ```ts
|
|
200
|
+
* readRow('accounts', { id: 'acc1' }) // { id: 'acc1' }
|
|
201
|
+
* ```
|
|
202
|
+
*/
|
|
203
|
+
function readRow(table, row) {
|
|
204
|
+
if (isRecord(row)) return row;
|
|
205
|
+
throw new RelationError("INVALID", `Table ${renderPath([table])} returned a row that is not a plain record; a storage must return plain record rows`, { table });
|
|
206
|
+
}
|
|
207
|
+
/**
|
|
111
208
|
* Resolves one raw {@link Relation} value into a flat {@link ResolvedRelation}.
|
|
112
209
|
*
|
|
113
210
|
* @remarks
|
|
114
211
|
* A `string` is a `belongs` (foreign-key column on this table); a `readonly string[]`
|
|
115
212
|
* is a `many` (foreign-key column on the related table); a {@link RelationDescriptor}
|
|
116
213
|
* uses its explicit `relationship`, or infers it from the fields present. The target
|
|
117
|
-
* model defaults to the relation name.
|
|
118
|
-
*
|
|
214
|
+
* model defaults to the relation name. A descriptor must pass `relationDescriptorContract`'s
|
|
215
|
+
* strict guard: an undeclared member, enumerable or not, a member holding another type, and
|
|
216
|
+
* a member present as `undefined` each refuse it, and no lossless repair admits it. The
|
|
217
|
+
* refusal carries the contract's audit faults, described against its schema. Every column the resolved arm declares is validated here, which is
|
|
218
|
+
* what lets each arm declare its columns required.
|
|
119
219
|
*
|
|
120
220
|
* @param name - The relation name (its key in the {@link RelationMap})
|
|
121
221
|
* @param value - The raw relation value
|
|
122
222
|
* @returns The resolved relation, on the arm its `relationship` names
|
|
123
|
-
* @throws An `INVALID` {@link RelationError} when the relationship cannot be resolved,
|
|
124
|
-
*
|
|
223
|
+
* @throws An `INVALID` {@link RelationError} when the relationship cannot be resolved, when the
|
|
224
|
+
* descriptor fails its contract (the faults ride on `context.faults`), or when a column the
|
|
225
|
+
* resolved arm declares is missing
|
|
226
|
+
*
|
|
227
|
+
* @example
|
|
228
|
+
* ```ts
|
|
229
|
+
* resolveRelation('classification', belongsTo('classificationId', 'classifications')).relationship // 'belongs'
|
|
230
|
+
* ```
|
|
125
231
|
*/
|
|
126
232
|
function resolveRelation(name, value) {
|
|
127
233
|
if (isString(value)) return {
|
|
@@ -130,9 +236,10 @@ function resolveRelation(name, value) {
|
|
|
130
236
|
model: name,
|
|
131
237
|
column: value
|
|
132
238
|
};
|
|
239
|
+
const path = renderPath([name]);
|
|
133
240
|
if (isArray(value)) {
|
|
134
241
|
const key = value[0];
|
|
135
|
-
if (!isString(key)) throw new RelationError("INVALID", `Relation
|
|
242
|
+
if (!isString(key)) throw new RelationError("INVALID", `Relation ${path}: the array form needs a foreign-key column string first, such as ['accountId']`, { relation: name });
|
|
136
243
|
return {
|
|
137
244
|
relationship: "many",
|
|
138
245
|
name,
|
|
@@ -140,14 +247,22 @@ function resolveRelation(name, value) {
|
|
|
140
247
|
key
|
|
141
248
|
};
|
|
142
249
|
}
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
250
|
+
const admitted = admitValue(relationDescriptorContract, value);
|
|
251
|
+
if (isFailure(admitted)) {
|
|
252
|
+
const faults = admitted.error.faults;
|
|
253
|
+
throw new RelationError("INVALID", `Relation ${path}: expected a column string, a [key] array, or a relation descriptor\n${describeFaults(faults, relationDescriptorContract.schema)}`, {
|
|
254
|
+
relation: name,
|
|
255
|
+
faults
|
|
256
|
+
});
|
|
257
|
+
}
|
|
258
|
+
const descriptor = admitted.value;
|
|
259
|
+
const model = descriptor.model ?? name;
|
|
260
|
+
const relationship = descriptor.relationship !== void 0 ? descriptor.relationship : isDefined(descriptor.through) ? "through" : isDefined(descriptor.tag) ? "morph" : isDefined(descriptor.column) ? "belongs" : isDefined(descriptor.key) ? "one" : void 0;
|
|
261
|
+
if (relationship === void 0) throw new RelationError("INVALID", `Relation ${path}: cannot infer the relationship; set relationship, or give column (belongs), key (one), through (through), or tag (morph)`, { relation: name });
|
|
147
262
|
switch (relationship) {
|
|
148
263
|
case "belongs": {
|
|
149
|
-
const column =
|
|
150
|
-
if (column === void 0) throw new RelationError("INVALID", `Relation
|
|
264
|
+
const column = descriptor.column;
|
|
265
|
+
if (column === void 0) throw new RelationError("INVALID", `Relation ${path}: a belongs relation needs column; build it with belongsTo(column)`, { relation: name });
|
|
151
266
|
return {
|
|
152
267
|
relationship,
|
|
153
268
|
name,
|
|
@@ -156,8 +271,8 @@ function resolveRelation(name, value) {
|
|
|
156
271
|
};
|
|
157
272
|
}
|
|
158
273
|
case "many": {
|
|
159
|
-
const key =
|
|
160
|
-
if (key === void 0) throw new RelationError("INVALID", `Relation
|
|
274
|
+
const key = descriptor.key;
|
|
275
|
+
if (key === void 0) throw new RelationError("INVALID", `Relation ${path}: a many relation needs key; build it with hasMany(key)`, { relation: name });
|
|
161
276
|
return {
|
|
162
277
|
relationship,
|
|
163
278
|
name,
|
|
@@ -166,8 +281,8 @@ function resolveRelation(name, value) {
|
|
|
166
281
|
};
|
|
167
282
|
}
|
|
168
283
|
case "one": {
|
|
169
|
-
const key =
|
|
170
|
-
if (key === void 0) throw new RelationError("INVALID", `Relation
|
|
284
|
+
const key = descriptor.key;
|
|
285
|
+
if (key === void 0) throw new RelationError("INVALID", `Relation ${path}: a one relation needs key; build it with hasOne(key)`, { relation: name });
|
|
171
286
|
return {
|
|
172
287
|
relationship,
|
|
173
288
|
name,
|
|
@@ -176,8 +291,8 @@ function resolveRelation(name, value) {
|
|
|
176
291
|
};
|
|
177
292
|
}
|
|
178
293
|
case "through": {
|
|
179
|
-
const { through, source, target } =
|
|
180
|
-
if (through === void 0 || source === void 0 || target === void 0) throw new RelationError("INVALID", `Relation
|
|
294
|
+
const { through, source, target } = descriptor;
|
|
295
|
+
if (through === void 0 || source === void 0 || target === void 0) throw new RelationError("INVALID", `Relation ${path}: a through relation needs through, source, and target; build it with hasThrough(through, source, target)`, { relation: name });
|
|
181
296
|
return {
|
|
182
297
|
relationship,
|
|
183
298
|
name,
|
|
@@ -188,8 +303,8 @@ function resolveRelation(name, value) {
|
|
|
188
303
|
};
|
|
189
304
|
}
|
|
190
305
|
case "morph": {
|
|
191
|
-
const { key, tag, label } =
|
|
192
|
-
if (key === void 0 || tag === void 0 || label === void 0) throw new RelationError("INVALID", `Relation
|
|
306
|
+
const { key, tag, label } = descriptor;
|
|
307
|
+
if (key === void 0 || tag === void 0 || label === void 0) throw new RelationError("INVALID", `Relation ${path}: a morph relation needs key, tag, and label; build it with hasMorph(key, tag, label)`, { relation: name });
|
|
193
308
|
return {
|
|
194
309
|
relationship,
|
|
195
310
|
name,
|
|
@@ -211,24 +326,24 @@ function resolveRelationMap(relations) {
|
|
|
211
326
|
return new Map(Object.entries(relations).map(([name, value]) => [name, resolveRelation(name, value)]));
|
|
212
327
|
}
|
|
213
328
|
/**
|
|
214
|
-
*
|
|
329
|
+
* Computes the junction row's primary key for one pair of a `through` relation.
|
|
215
330
|
*
|
|
216
331
|
* @remarks
|
|
217
|
-
*
|
|
218
|
-
*
|
|
332
|
+
* The key is the JSON text of `[key, target]`, so each pair has one key and a string key
|
|
333
|
+
* stays apart from the number it spells. `link` inserts under this key and `unlink` removes
|
|
334
|
+
* it, which is why a junction's primary column must store text.
|
|
219
335
|
*
|
|
220
|
-
* @param
|
|
221
|
-
* @param
|
|
222
|
-
* @returns The
|
|
336
|
+
* @param key - The owning record's primary key
|
|
337
|
+
* @param target - The related record's primary key
|
|
338
|
+
* @returns The pair's junction key
|
|
223
339
|
*
|
|
224
340
|
* @example
|
|
225
341
|
* ```ts
|
|
226
|
-
*
|
|
342
|
+
* computeLinkKey('acc1', 'rep1') // '["acc1","rep1"]'
|
|
227
343
|
* ```
|
|
228
344
|
*/
|
|
229
|
-
function
|
|
230
|
-
|
|
231
|
-
return Reflect.get(record, column);
|
|
345
|
+
function computeLinkKey(key, target) {
|
|
346
|
+
return JSON.stringify([key, target]);
|
|
232
347
|
}
|
|
233
348
|
/**
|
|
234
349
|
* Counts the related rows one relation attached across a record set.
|
|
@@ -253,7 +368,7 @@ function countAttached(values) {
|
|
|
253
368
|
* Indexes rows by the string form of one column, for keyed lookups.
|
|
254
369
|
*
|
|
255
370
|
* @remarks
|
|
256
|
-
* The column is read with
|
|
371
|
+
* The column is read with `resolveField` and its value stringified, so a numeric
|
|
257
372
|
* and a string foreign key meet at the same entry. A later row with a key an earlier
|
|
258
373
|
* row already holds replaces it, and a row missing the column indexes under the string
|
|
259
374
|
* `'undefined'`. This is the projection a `belongs` load and a `through` load use to
|
|
@@ -273,14 +388,14 @@ function countAttached(values) {
|
|
|
273
388
|
function indexRows(rows, column, values = rows) {
|
|
274
389
|
return new Map(Iterator.from(rows).flatMap((row, index) => {
|
|
275
390
|
const value = values[index];
|
|
276
|
-
return value === void 0 ? [] : [[String(
|
|
391
|
+
return value === void 0 ? [] : [[String(resolveField(row, column)), value]];
|
|
277
392
|
}));
|
|
278
393
|
}
|
|
279
394
|
/**
|
|
280
395
|
* Groups rows by the string form of one column, for one-to-many lookups.
|
|
281
396
|
*
|
|
282
397
|
* @remarks
|
|
283
|
-
* The column is read with
|
|
398
|
+
* The column is read with `resolveField` and its value stringified, so a numeric
|
|
284
399
|
* and a string foreign key meet at the same group. Rows keep their input order inside
|
|
285
400
|
* a group, a key no row carries is absent rather than empty, and a row missing the
|
|
286
401
|
* column groups under the string `'undefined'`. This is the projection a `many` load
|
|
@@ -298,16 +413,11 @@ function indexRows(rows, column, values = rows) {
|
|
|
298
413
|
* ```
|
|
299
414
|
*/
|
|
300
415
|
function groupRows(rows, column, values = rows) {
|
|
301
|
-
const
|
|
302
|
-
for (const [index, row] of rows.entries()) {
|
|
416
|
+
const pairs = Iterator.from(rows.entries()).flatMap(([index, row]) => {
|
|
303
417
|
const value = values[index];
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
if (group !== void 0) group.push(value);
|
|
308
|
-
else groups.set(key, [value]);
|
|
309
|
-
}
|
|
310
|
-
return groups;
|
|
418
|
+
return value === void 0 ? [] : [[String(resolveField(row, column)), value]];
|
|
419
|
+
});
|
|
420
|
+
return new Map(Iterator.from(Map.groupBy(pairs, ([key]) => key)).map(([key, group]) => [key, group.map(([, value]) => value)]));
|
|
311
421
|
}
|
|
312
422
|
/**
|
|
313
423
|
* Builds a `belongs` relation — a foreign key on the owning table points at the related row
|
|
@@ -415,8 +525,10 @@ function hasMorph(key, tag, label, model) {
|
|
|
415
525
|
* a direct relation uses one query for the whole record set, while a `through`
|
|
416
526
|
* relation uses two (junction then target); both counts remain constant regardless
|
|
417
527
|
* of parent count. Nested includes recurse through the registry `lookup`, so each
|
|
418
|
-
* nested level is batched again.
|
|
419
|
-
*
|
|
528
|
+
* nested level is batched again. A load by primary key (`belongs`, a `through` target)
|
|
529
|
+
* reads through the table's keyed `get`; a load by foreign key reads through `records`
|
|
530
|
+
* with `any`. Columns are read with `resolveField` and relation properties merged with
|
|
531
|
+
* `Object.assign` — no `as`.
|
|
420
532
|
*
|
|
421
533
|
* @remarks
|
|
422
534
|
* - **Observable.** The owned {@link emitter} ({@link ModelEventMap}) carries the
|
|
@@ -497,95 +609,70 @@ var Model = class {
|
|
|
497
609
|
async load(keys, include, options) {
|
|
498
610
|
checkAbort(options?.signal);
|
|
499
611
|
if (isArray(keys)) {
|
|
500
|
-
const bases = await this.#table.get(keys);
|
|
612
|
+
const bases = (await this.#table.get(keys)).map((base) => base === void 0 ? void 0 : readRow(this.#table.name, base));
|
|
501
613
|
const present = bases.filter(isDefined);
|
|
502
614
|
const attachments = (await this.#populate(present, include, this.#resolved, this.#table.primary, options)).values();
|
|
503
615
|
return bases.map((base) => base === void 0 ? void 0 : Object.assign({}, base, attachments.next().value));
|
|
504
616
|
}
|
|
505
|
-
const
|
|
506
|
-
if (
|
|
617
|
+
const found = await this.#table.get(keys);
|
|
618
|
+
if (found === void 0) return void 0;
|
|
619
|
+
const base = readRow(this.#table.name, found);
|
|
507
620
|
const [props] = await this.#populate([base], include, this.#resolved, this.#table.primary, options);
|
|
508
621
|
return Object.assign({}, base, props);
|
|
509
622
|
}
|
|
510
623
|
async find(include, options) {
|
|
511
624
|
checkAbort(options?.signal);
|
|
512
|
-
const
|
|
625
|
+
const rows = (await this.#table.records({
|
|
513
626
|
...options?.sort !== void 0 ? { order: [{
|
|
514
627
|
column: options.sort,
|
|
515
628
|
direction: options.direction ?? "ascending"
|
|
516
629
|
}] } : {},
|
|
517
630
|
...options?.offset !== void 0 ? { offset: options.offset } : {},
|
|
518
631
|
...options?.limit !== void 0 ? { limit: options.limit } : {}
|
|
519
|
-
}, options);
|
|
520
|
-
const props = await this.#populate(
|
|
521
|
-
return
|
|
632
|
+
}, options)).map((record) => readRow(this.#table.name, record));
|
|
633
|
+
const props = await this.#populate(rows, include, this.#resolved, this.#table.primary, options);
|
|
634
|
+
return rows.map((row, index) => Object.assign({}, row, props[index]));
|
|
522
635
|
}
|
|
523
636
|
async link(key, relation, target, options) {
|
|
524
637
|
checkAbort(options?.signal);
|
|
525
638
|
const resolved = this.#through(relation);
|
|
526
639
|
const junction = this.#storage.table(resolved.through);
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
}
|
|
538
|
-
await junction.set({
|
|
539
|
-
[resolved.source]: key,
|
|
540
|
-
[resolved.target]: target
|
|
541
|
-
}, options);
|
|
640
|
+
const id = computeLinkKey(key, target);
|
|
641
|
+
try {
|
|
642
|
+
await junction.add({
|
|
643
|
+
[junction.primary]: id,
|
|
644
|
+
[resolved.source]: key,
|
|
645
|
+
[resolved.target]: target
|
|
646
|
+
}, options);
|
|
647
|
+
} catch (error) {
|
|
648
|
+
if (isDatabaseError(error) && error.code === "CONFLICT" && await junction.has(id)) return;
|
|
649
|
+
throw error;
|
|
650
|
+
}
|
|
542
651
|
this.#emitter.emit("link", key, relation);
|
|
543
652
|
}
|
|
544
653
|
async unlink(key, relation, target, options) {
|
|
545
654
|
checkAbort(options?.signal);
|
|
546
655
|
const resolved = this.#through(relation);
|
|
547
|
-
|
|
548
|
-
const rows = await junction.records({ conditions: [{
|
|
549
|
-
column: resolved.source,
|
|
550
|
-
operator: "equals",
|
|
551
|
-
values: [key],
|
|
552
|
-
connector: "and"
|
|
553
|
-
}, {
|
|
554
|
-
column: resolved.target,
|
|
555
|
-
operator: "equals",
|
|
556
|
-
values: [target],
|
|
557
|
-
connector: "and"
|
|
558
|
-
}] }, 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
|
-
}
|
|
563
|
-
this.#emitter.emit("unlink", key, relation);
|
|
656
|
+
if (await this.#storage.table(resolved.through).remove(computeLinkKey(key, target), options)) this.#emitter.emit("unlink", key, relation);
|
|
564
657
|
}
|
|
565
658
|
async links(key, relation, options) {
|
|
566
659
|
checkAbort(options?.signal);
|
|
567
660
|
const resolved = this.#through(relation);
|
|
568
|
-
const
|
|
661
|
+
const junction = this.#storage.table(resolved.through);
|
|
662
|
+
return (await junction.records({ conditions: [{
|
|
569
663
|
column: resolved.source,
|
|
570
664
|
operator: "equals",
|
|
571
665
|
values: [key],
|
|
572
666
|
connector: "and"
|
|
573
|
-
}] }, options);
|
|
574
|
-
const target = resolved.target;
|
|
575
|
-
const keys = [];
|
|
576
|
-
for (const row of rows) {
|
|
577
|
-
const value = extractKey(row, target);
|
|
578
|
-
if (value !== void 0) keys.push(value);
|
|
579
|
-
}
|
|
580
|
-
return keys;
|
|
667
|
+
}] }, options)).map((row) => extractKey(readRow(junction.name, row), resolved.target)).filter(isDefined);
|
|
581
668
|
}
|
|
582
669
|
#through(relation) {
|
|
583
670
|
const resolved = this.#resolved.get(relation);
|
|
584
|
-
if (resolved === void 0) throw new RelationError("UNKNOWN_RELATION", `Model
|
|
671
|
+
if (resolved === void 0) throw new RelationError("UNKNOWN_RELATION", `Model ${renderPath([this.#name])} has no relation ${renderPath([relation])}; declare it in the model's relation map`, {
|
|
585
672
|
model: this.#name,
|
|
586
673
|
relation
|
|
587
674
|
});
|
|
588
|
-
if (resolved.relationship !== "through") throw new RelationError("NOT_THROUGH", `Relation
|
|
675
|
+
if (resolved.relationship !== "through") throw new RelationError("NOT_THROUGH", `Relation ${renderPath([this.#name, relation])} is a ${resolved.relationship} relation; link, unlink, and links need a through relation built with hasThrough`, {
|
|
589
676
|
model: this.#name,
|
|
590
677
|
relation
|
|
591
678
|
});
|
|
@@ -619,33 +706,28 @@ var Model = class {
|
|
|
619
706
|
}
|
|
620
707
|
async #loadBelongs(records, resolved, sub, options) {
|
|
621
708
|
const column = resolved.column;
|
|
622
|
-
const keys = [...new Set(records.map((record) =>
|
|
709
|
+
const keys = [...new Set(records.map((record) => resolveField(record, column)).filter(isKey))];
|
|
623
710
|
if (keys.length === 0) return records.map(() => void 0);
|
|
624
711
|
const related = this.#storage.table(resolved.model);
|
|
625
|
-
const rows = await related.
|
|
626
|
-
column: related.primary,
|
|
627
|
-
operator: "any",
|
|
628
|
-
values: keys,
|
|
629
|
-
connector: "and"
|
|
630
|
-
}] }, options);
|
|
712
|
+
const rows = (await related.get(keys)).filter((row) => row !== void 0).map((row) => readRow(related.name, row));
|
|
631
713
|
const index = indexRows(rows, related.primary, await this.#nest(resolved.model, rows, sub, options));
|
|
632
714
|
return records.map((record) => {
|
|
633
|
-
const fk =
|
|
634
|
-
return
|
|
715
|
+
const fk = resolveField(record, column);
|
|
716
|
+
return isKey(fk) ? index.get(String(fk)) : void 0;
|
|
635
717
|
});
|
|
636
718
|
}
|
|
637
719
|
async #loadMany(records, resolved, sub, primary, options) {
|
|
638
720
|
const foreign = resolved.key;
|
|
639
|
-
const keys = [...new Set(records.map((record) =>
|
|
721
|
+
const keys = [...new Set(records.map((record) => resolveField(record, primary)).filter(isDefined))];
|
|
640
722
|
if (keys.length === 0) return records.map(() => []);
|
|
641
|
-
const rows = await this.#storage.table(resolved.model).records({ conditions: [{
|
|
723
|
+
const rows = (await this.#storage.table(resolved.model).records({ conditions: [{
|
|
642
724
|
column: foreign,
|
|
643
725
|
operator: "any",
|
|
644
726
|
values: keys,
|
|
645
727
|
connector: "and"
|
|
646
|
-
}] }, options);
|
|
728
|
+
}] }, options)).map((row) => readRow(resolved.model, row));
|
|
647
729
|
const groups = groupRows(rows, foreign, await this.#nest(resolved.model, rows, sub, options));
|
|
648
|
-
return records.map((record) => groups.get(String(
|
|
730
|
+
return records.map((record) => groups.get(String(resolveField(record, primary))) ?? []);
|
|
649
731
|
}
|
|
650
732
|
async #loadOne(records, resolved, sub, primary, options) {
|
|
651
733
|
return (await this.#loadMany(records, resolved, sub, primary, options)).map((group) => group.length > 0 ? group[0] : void 0);
|
|
@@ -653,47 +735,28 @@ var Model = class {
|
|
|
653
735
|
async #loadThrough(records, resolved, sub, primary, options) {
|
|
654
736
|
const source = resolved.source;
|
|
655
737
|
const target = resolved.target;
|
|
656
|
-
const parents = [...new Set(records.map((record) =>
|
|
738
|
+
const parents = [...new Set(records.map((record) => resolveField(record, primary)).filter(isDefined))];
|
|
657
739
|
if (parents.length === 0) return records.map(() => []);
|
|
658
|
-
const junctions = await this.#storage.table(resolved.through).records({ conditions: [{
|
|
740
|
+
const junctions = (await this.#storage.table(resolved.through).records({ conditions: [{
|
|
659
741
|
column: source,
|
|
660
742
|
operator: "any",
|
|
661
743
|
values: parents,
|
|
662
744
|
connector: "and"
|
|
663
|
-
}] }, options);
|
|
664
|
-
const
|
|
665
|
-
for (const junction of junctions) {
|
|
666
|
-
const value = readColumn(junction, target);
|
|
667
|
-
if (!isDefined(value)) continue;
|
|
668
|
-
const owner = String(readColumn(junction, source));
|
|
669
|
-
const list = targetsBySource.get(owner);
|
|
670
|
-
if (list !== void 0) list.push(value);
|
|
671
|
-
else targetsBySource.set(owner, [value]);
|
|
672
|
-
}
|
|
673
|
-
const targets = [...new Set([...targetsBySource.values()].flat())];
|
|
745
|
+
}] }, options)).map((junction) => readRow(resolved.through, junction));
|
|
746
|
+
const targets = [...new Set(junctions.map((junction) => resolveField(junction, target)).filter(isKey))];
|
|
674
747
|
if (targets.length === 0) return records.map(() => []);
|
|
748
|
+
checkAbort(options?.signal);
|
|
675
749
|
const related = this.#storage.table(resolved.model);
|
|
676
|
-
const rows = await related.
|
|
677
|
-
column: related.primary,
|
|
678
|
-
operator: "any",
|
|
679
|
-
values: targets,
|
|
680
|
-
connector: "and"
|
|
681
|
-
}] }, options);
|
|
750
|
+
const rows = (await related.get(targets)).filter((row) => row !== void 0).map((row) => readRow(related.name, row));
|
|
682
751
|
const index = indexRows(rows, related.primary, await this.#nest(resolved.model, rows, sub, options));
|
|
683
|
-
|
|
684
|
-
|
|
685
|
-
for (const value of targetsBySource.get(String(readColumn(record, primary))) ?? []) {
|
|
686
|
-
const row = index.get(String(value));
|
|
687
|
-
if (row !== void 0) out.push(row);
|
|
688
|
-
}
|
|
689
|
-
return out;
|
|
690
|
-
});
|
|
752
|
+
const groups = groupRows(junctions, source);
|
|
753
|
+
return records.map((record) => (groups.get(String(resolveField(record, primary))) ?? []).map((junction) => resolveField(junction, target)).filter(isKey).map((value) => index.get(String(value))).filter(isDefined));
|
|
691
754
|
}
|
|
692
755
|
async #loadMorph(records, resolved, sub, primary, options) {
|
|
693
756
|
const foreign = resolved.key;
|
|
694
|
-
const keys = [...new Set(records.map((record) =>
|
|
757
|
+
const keys = [...new Set(records.map((record) => resolveField(record, primary)).filter(isDefined))];
|
|
695
758
|
if (keys.length === 0) return records.map(() => []);
|
|
696
|
-
const rows = await this.#storage.table(resolved.model).records({ conditions: [{
|
|
759
|
+
const rows = (await this.#storage.table(resolved.model).records({ conditions: [{
|
|
697
760
|
column: foreign,
|
|
698
761
|
operator: "any",
|
|
699
762
|
values: keys,
|
|
@@ -703,9 +766,9 @@ var Model = class {
|
|
|
703
766
|
operator: "equals",
|
|
704
767
|
values: [resolved.label],
|
|
705
768
|
connector: "and"
|
|
706
|
-
}] }, options);
|
|
769
|
+
}] }, options)).map((row) => readRow(resolved.model, row));
|
|
707
770
|
const groups = groupRows(rows, foreign, await this.#nest(resolved.model, rows, sub, options));
|
|
708
|
-
return records.map((record) => groups.get(String(
|
|
771
|
+
return records.map((record) => groups.get(String(resolveField(record, primary))) ?? []);
|
|
709
772
|
}
|
|
710
773
|
async #nest(model, rows, sub, options) {
|
|
711
774
|
if (isBoolean(sub) || rows.length === 0) return rows;
|
|
@@ -717,7 +780,7 @@ var Model = class {
|
|
|
717
780
|
};
|
|
718
781
|
// src/core/RelationManager.ts
|
|
719
782
|
/**
|
|
720
|
-
* Resolves a {@link
|
|
783
|
+
* Resolves a {@link RelationSchema} once at construction and vends a typed
|
|
721
784
|
* {@link ModelInterface} per declared table.
|
|
722
785
|
*
|
|
723
786
|
* @remarks
|
|
@@ -766,7 +829,10 @@ var RelationManager = class {
|
|
|
766
829
|
const resolved = resolveRelationMap(map);
|
|
767
830
|
for (const [relation, entry] of resolved) {
|
|
768
831
|
validateRelationTable(this.#broad, name, relation, entry.model);
|
|
769
|
-
if (entry.relationship === "through")
|
|
832
|
+
if (entry.relationship === "through") {
|
|
833
|
+
validateRelationTable(this.#broad, name, relation, entry.through, true);
|
|
834
|
+
validateRelationJunction(name, entry, this.#broad.table(entry.through).primary);
|
|
835
|
+
}
|
|
770
836
|
}
|
|
771
837
|
this.#resolved.set(name, resolved);
|
|
772
838
|
}
|
|
@@ -843,6 +909,6 @@ var RelationManager = class {
|
|
|
843
909
|
function createRelationManager(options) {
|
|
844
910
|
return new RelationManager(options);
|
|
845
911
|
}
|
|
846
|
-
export { Model, RelationError, RelationManager, belongsTo, countAttached, createRelationManager, groupRows, hasMany, hasMorph, hasOne, hasThrough, indexRows, isRelationDescriptor, isRelationError,
|
|
912
|
+
export { Model, RelationError, RelationManager, belongsTo, computeLinkKey, countAttached, createRelationManager, groupRows, hasMany, hasMorph, hasOne, hasThrough, indexRows, isRelationDescriptor, isRelationError, readRow, relationDescriptorContract, relationDescriptorShape, resolveRelation, resolveRelationMap, validateRelationJunction, validateRelationTable };
|
|
847
913
|
|
|
848
914
|
//# sourceMappingURL=index.js.map
|