@guren/orm 2.11.1 → 2.13.0
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/README.md +7 -1
- package/dist/index.d.ts +150 -72
- package/dist/index.js +1023 -770
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -57,6 +57,32 @@ function registerOrmInstance(identity) {
|
|
|
57
57
|
}
|
|
58
58
|
registerOrmInstance(moduleIdentity());
|
|
59
59
|
//#endregion
|
|
60
|
+
//#region src/casts.ts
|
|
61
|
+
function castInPlace(target, castDefs) {
|
|
62
|
+
for (const [field, castType] of Object.entries(castDefs)) {
|
|
63
|
+
if (!(field in target)) continue;
|
|
64
|
+
const value = target[field];
|
|
65
|
+
if (value == null) continue;
|
|
66
|
+
switch (castType) {
|
|
67
|
+
case "json":
|
|
68
|
+
if (typeof value === "string") try {
|
|
69
|
+
target[field] = JSON.parse(value);
|
|
70
|
+
} catch {}
|
|
71
|
+
break;
|
|
72
|
+
case "date":
|
|
73
|
+
if (!(value instanceof Date)) target[field] = new Date(value);
|
|
74
|
+
break;
|
|
75
|
+
case "boolean":
|
|
76
|
+
target[field] = Boolean(value);
|
|
77
|
+
break;
|
|
78
|
+
case "number":
|
|
79
|
+
target[field] = Number(value);
|
|
80
|
+
break;
|
|
81
|
+
case "string": target[field] = String(value);
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
//#endregion
|
|
60
86
|
//#region src/internal-keys.ts
|
|
61
87
|
/**
|
|
62
88
|
* What `Model`, `QueryBuilder` and the adapters share without importing each
|
|
@@ -73,6 +99,371 @@ const SEAL_SCOPES = Symbol("guren.orm.sealScopes");
|
|
|
73
99
|
const READ_TRANSFORMS = Symbol("guren.orm.readTransforms");
|
|
74
100
|
/** Rows as the adapter read them, for the joins a relation loader makes. */
|
|
75
101
|
const RAW_RESULTS = Symbol("guren.orm.rawResults");
|
|
102
|
+
/** Model-specific bulk deletion, preserving the builder's scopes. */
|
|
103
|
+
const BULK_DELETE = Symbol("guren.orm.bulkDelete");
|
|
104
|
+
/** Explicit physical deletion, used by SoftDeletes.forceDelete. */
|
|
105
|
+
const PHYSICAL_DELETE = Symbol("guren.orm.physicalDelete");
|
|
106
|
+
/** A static delete run inside the model's lifecycle, shared with SoftDeletes. */
|
|
107
|
+
const LIFECYCLE_DELETE = Symbol("guren.orm.lifecycleDelete");
|
|
108
|
+
//#endregion
|
|
109
|
+
//#region src/attributes.ts
|
|
110
|
+
/**
|
|
111
|
+
* A computed field is written with `record[key] = …`, and `__proto__` as a key
|
|
112
|
+
* would rewrite the record's prototype rather than a column. The names come
|
|
113
|
+
* from a model's static definitions, so refusing them is a boot-time mistake
|
|
114
|
+
* surfacing at first use, not a runtime input check. The comparison is spelled
|
|
115
|
+
* at each write because CodeQL does not follow a guard that throws elsewhere.
|
|
116
|
+
*/
|
|
117
|
+
function prototypeKeyError(key, kind) {
|
|
118
|
+
return /* @__PURE__ */ new Error(`An ${kind} cannot be named "${key}": that key would alter the record's prototype.`);
|
|
119
|
+
}
|
|
120
|
+
/** Writes the computed values onto `record`; each accessor sees the ones before it. */
|
|
121
|
+
function applyAccessorsInPlace(record, accessors) {
|
|
122
|
+
for (const key of Object.keys(accessors)) {
|
|
123
|
+
if (key === "__proto__" || key === "constructor" || key === "prototype") throw prototypeKeyError(key, "accessor");
|
|
124
|
+
record[key] = accessors[key](record);
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
/** Apply accessors to a record, returning a new record with computed values. */
|
|
128
|
+
function applyAccessors(record, accessors) {
|
|
129
|
+
if (!accessors) return record;
|
|
130
|
+
if (Object.keys(accessors).length === 0) return record;
|
|
131
|
+
const result = { ...record };
|
|
132
|
+
applyAccessorsInPlace(result, accessors);
|
|
133
|
+
return result;
|
|
134
|
+
}
|
|
135
|
+
/** Apply mutators to data before persistence, returning a new object. */
|
|
136
|
+
function applyMutators(data, mutators) {
|
|
137
|
+
if (!mutators) return data;
|
|
138
|
+
const keys = Object.keys(mutators);
|
|
139
|
+
if (keys.length === 0) return data;
|
|
140
|
+
const result = { ...data };
|
|
141
|
+
for (const key of keys) {
|
|
142
|
+
if (key === "__proto__" || key === "constructor" || key === "prototype") throw prototypeKeyError(key, "mutator");
|
|
143
|
+
if (Object.hasOwn(result, key)) result[key] = mutators[key](result[key], result);
|
|
144
|
+
}
|
|
145
|
+
return result;
|
|
146
|
+
}
|
|
147
|
+
//#endregion
|
|
148
|
+
//#region src/relation-records.ts
|
|
149
|
+
/**
|
|
150
|
+
* Written onto the records rather than onto copies: the parent rows hold them
|
|
151
|
+
* by reference, and a nested loader has already keyed its own rows on them.
|
|
152
|
+
* Keep in step with `[READ_TRANSFORMS]`: same casts-then-accessors order, and
|
|
153
|
+
* the same rule that `projected` rows (a constraint's `select()` narrowed them)
|
|
154
|
+
* skip the accessors, which would read a column that is not on them.
|
|
155
|
+
*/
|
|
156
|
+
function applyRelatedReadTransforms(related, records, projected) {
|
|
157
|
+
const casts = related.casts;
|
|
158
|
+
const accessors = projected ? void 0 : related.accessors;
|
|
159
|
+
if (!casts && !accessors) return;
|
|
160
|
+
for (const record of records) {
|
|
161
|
+
if (casts) castInPlace(record, casts);
|
|
162
|
+
if (accessors) applyAccessorsInPlace(record, accessors);
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
function maxInListSize(adapter) {
|
|
166
|
+
const size = adapter.maxInListSize?.();
|
|
167
|
+
return typeof size === "number" && size >= 1 ? Math.floor(size) : 500;
|
|
168
|
+
}
|
|
169
|
+
function relationCountPlan(definition, parentType) {
|
|
170
|
+
switch (definition.type) {
|
|
171
|
+
case "hasMany":
|
|
172
|
+
case "hasOne": return {
|
|
173
|
+
related: definition.related,
|
|
174
|
+
parentKey: definition.localKey,
|
|
175
|
+
childKey: definition.foreignKey,
|
|
176
|
+
where: {},
|
|
177
|
+
presenceOnly: false
|
|
178
|
+
};
|
|
179
|
+
case "morphMany": return {
|
|
180
|
+
related: definition.related,
|
|
181
|
+
parentKey: definition.localKey,
|
|
182
|
+
childKey: `${definition.morphName}Id`,
|
|
183
|
+
where: { [`${definition.morphName}Type`]: parentType },
|
|
184
|
+
presenceOnly: false
|
|
185
|
+
};
|
|
186
|
+
case "belongsTo": return {
|
|
187
|
+
related: definition.related,
|
|
188
|
+
parentKey: definition.foreignKey,
|
|
189
|
+
childKey: definition.ownerKey,
|
|
190
|
+
where: {},
|
|
191
|
+
presenceOnly: true
|
|
192
|
+
};
|
|
193
|
+
default: return;
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
/**
|
|
197
|
+
* One row per owner key that exists, never a grouped COUNT: the answer is 0 or
|
|
198
|
+
* 1, and the key column alone is all of the owner row anything here reads.
|
|
199
|
+
*/
|
|
200
|
+
async function countOwnersPresent(related, ownerKey, keys, size, queryOptions) {
|
|
201
|
+
const rows = await loadByChunks(keys, size, (chunk) => related.newQuery(queryOptions).where({ [ownerKey]: chunk }).select(ownerKey)[RAW_RESULTS]());
|
|
202
|
+
return new Map(rows.map((row) => [row[ownerKey], 1]));
|
|
203
|
+
}
|
|
204
|
+
function distinctKeys(records, key) {
|
|
205
|
+
return Array.from(new Set(records.map((r) => r[key]).filter((v) => v != null)));
|
|
206
|
+
}
|
|
207
|
+
function chunkKeys(values, size) {
|
|
208
|
+
if (values.length <= size) return [values];
|
|
209
|
+
const chunks = [];
|
|
210
|
+
for (let i = 0; i < values.length; i += size) chunks.push(values.slice(i, i + size));
|
|
211
|
+
return chunks;
|
|
212
|
+
}
|
|
213
|
+
async function loadByChunks(values, size, load) {
|
|
214
|
+
const results = [];
|
|
215
|
+
for (const chunk of chunkKeys(values, size)) for (const record of await load(chunk)) results.push(record);
|
|
216
|
+
return results;
|
|
217
|
+
}
|
|
218
|
+
/**
|
|
219
|
+
* The related rows behind one eager load, and whether the constraint narrowed
|
|
220
|
+
* them with `select()`. The callback runs on `whole`, which decides whether the
|
|
221
|
+
* keys may be split; chunked, it runs once more per executed chunk. A top-level
|
|
222
|
+
* `orWhere()` in it widens the foreign-key filter, so a loader that groups on
|
|
223
|
+
* something weaker (morphMany, on the morph id) filters the rows itself.
|
|
224
|
+
*/
|
|
225
|
+
async function loadRelatedRecords(related, keys, clause, queryOptions, constraint) {
|
|
226
|
+
const rows = (chunk) => {
|
|
227
|
+
const query = related.newQuery(queryOptions).where(clause(chunk));
|
|
228
|
+
constraint?.(query);
|
|
229
|
+
return query[RAW_RESULTS]();
|
|
230
|
+
};
|
|
231
|
+
const size = maxInListSize(related.getAdapter());
|
|
232
|
+
const whole = related.newQuery(queryOptions).where(clause(keys));
|
|
233
|
+
constraint?.(whole);
|
|
234
|
+
const options = whole.getOptions();
|
|
235
|
+
const projected = (options.selectFields?.length ?? 0) > 0;
|
|
236
|
+
const describesWholeSet = options.limitValue !== void 0 || options.offsetValue !== void 0 || options.orderBy.length > 0;
|
|
237
|
+
if (keys.length <= size || describesWholeSet) return {
|
|
238
|
+
records: await whole[RAW_RESULTS](),
|
|
239
|
+
projected
|
|
240
|
+
};
|
|
241
|
+
return {
|
|
242
|
+
records: await loadByChunks(keys, size, rows),
|
|
243
|
+
projected
|
|
244
|
+
};
|
|
245
|
+
}
|
|
246
|
+
async function countByChunks(values, size, count) {
|
|
247
|
+
return new Map(await loadByChunks(values, size, async (chunk) => Array.from(await count(chunk))));
|
|
248
|
+
}
|
|
249
|
+
async function resolveModelReference(reference) {
|
|
250
|
+
if (typeof reference.newQuery === "function") return reference;
|
|
251
|
+
return await reference();
|
|
252
|
+
}
|
|
253
|
+
//#endregion
|
|
254
|
+
//#region src/relation-loading.ts
|
|
255
|
+
async function loadRelationData(records, name, related, parentKey, relatedKey, isArray, queryOptions, constraint) {
|
|
256
|
+
const values = distinctKeys(records, parentKey);
|
|
257
|
+
if (values.length === 0) {
|
|
258
|
+
for (const record of records) record[name] = isArray ? [] : null;
|
|
259
|
+
return false;
|
|
260
|
+
}
|
|
261
|
+
const { records: relatedRecords, projected } = await loadRelatedRecords(related, values, (chunk) => ({ [relatedKey]: chunk }), queryOptions, constraint);
|
|
262
|
+
const map = /* @__PURE__ */ new Map();
|
|
263
|
+
for (const item of relatedRecords) {
|
|
264
|
+
const key = item[relatedKey];
|
|
265
|
+
if (isArray) {
|
|
266
|
+
if (!map.has(key)) map.set(key, []);
|
|
267
|
+
map.get(key).push({ ...item });
|
|
268
|
+
} else map.set(key, { ...item });
|
|
269
|
+
}
|
|
270
|
+
for (const record of records) {
|
|
271
|
+
const key = record[parentKey];
|
|
272
|
+
if (key == null) {
|
|
273
|
+
record[name] = isArray ? [] : null;
|
|
274
|
+
continue;
|
|
275
|
+
}
|
|
276
|
+
record[name] = map.get(key) ?? (isArray ? [] : null);
|
|
277
|
+
}
|
|
278
|
+
return projected;
|
|
279
|
+
}
|
|
280
|
+
async function loadHasMany(records, definition, queryOptions, constraint) {
|
|
281
|
+
const { foreignKey, localKey, name } = definition;
|
|
282
|
+
return loadRelationData(records, name, await resolveModelReference(definition.related), localKey, foreignKey, true, queryOptions, constraint);
|
|
283
|
+
}
|
|
284
|
+
async function loadHasOne(records, definition, queryOptions, constraint) {
|
|
285
|
+
const { foreignKey, localKey, name } = definition;
|
|
286
|
+
return loadRelationData(records, name, await resolveModelReference(definition.related), localKey, foreignKey, false, queryOptions, constraint);
|
|
287
|
+
}
|
|
288
|
+
async function loadBelongsTo(records, definition, queryOptions, constraint) {
|
|
289
|
+
const { foreignKey, ownerKey, name } = definition;
|
|
290
|
+
return loadRelationData(records, name, await resolveModelReference(definition.related), foreignKey, ownerKey, false, queryOptions, constraint);
|
|
291
|
+
}
|
|
292
|
+
async function loadBelongsToMany(owner, records, definition, queryOptions, constraint) {
|
|
293
|
+
const { pivotTable, foreignPivotKey, relatedPivotKey, parentKey, relatedKey, name } = definition;
|
|
294
|
+
const related = await resolveModelReference(definition.related);
|
|
295
|
+
const parentValues = distinctKeys(records, parentKey);
|
|
296
|
+
if (parentValues.length === 0) {
|
|
297
|
+
for (const record of records) record[name] = [];
|
|
298
|
+
return false;
|
|
299
|
+
}
|
|
300
|
+
const adapter = owner.getAdapter();
|
|
301
|
+
const pivotRows = await loadByChunks(parentValues, maxInListSize(adapter), (chunk) => adapter.findMany(pivotTable, { where: { [foreignPivotKey]: chunk } }, queryOptions));
|
|
302
|
+
const pivotMap = /* @__PURE__ */ new Map();
|
|
303
|
+
const allRelatedIds = /* @__PURE__ */ new Set();
|
|
304
|
+
for (const row of pivotRows) {
|
|
305
|
+
const fk = row[foreignPivotKey];
|
|
306
|
+
const rk = row[relatedPivotKey];
|
|
307
|
+
if (!pivotMap.has(fk)) pivotMap.set(fk, []);
|
|
308
|
+
pivotMap.get(fk).push(rk);
|
|
309
|
+
allRelatedIds.add(rk);
|
|
310
|
+
}
|
|
311
|
+
if (allRelatedIds.size === 0) {
|
|
312
|
+
for (const record of records) record[name] = [];
|
|
313
|
+
return false;
|
|
314
|
+
}
|
|
315
|
+
const { records: relatedRecords, projected } = await loadRelatedRecords(related, Array.from(allRelatedIds), (chunk) => ({ [relatedKey]: chunk }), queryOptions, constraint);
|
|
316
|
+
const relatedMap = /* @__PURE__ */ new Map();
|
|
317
|
+
for (const item of relatedRecords) relatedMap.set(item[relatedKey], { ...item });
|
|
318
|
+
for (const record of records) {
|
|
319
|
+
const pk = record[parentKey];
|
|
320
|
+
if (pk == null) {
|
|
321
|
+
record[name] = [];
|
|
322
|
+
continue;
|
|
323
|
+
}
|
|
324
|
+
record[name] = (pivotMap.get(pk) ?? []).map((id) => relatedMap.get(id)).filter((item) => item != null);
|
|
325
|
+
}
|
|
326
|
+
return projected;
|
|
327
|
+
}
|
|
328
|
+
async function loadHasManyThrough(records, definition, queryOptions, constraint) {
|
|
329
|
+
const { firstKey, secondKey, localKey, secondLocalKey, name } = definition;
|
|
330
|
+
const related = await resolveModelReference(definition.related);
|
|
331
|
+
const through = await resolveModelReference(definition.through);
|
|
332
|
+
const localValues = distinctKeys(records, localKey);
|
|
333
|
+
if (localValues.length === 0) {
|
|
334
|
+
for (const record of records) record[name] = [];
|
|
335
|
+
return false;
|
|
336
|
+
}
|
|
337
|
+
const throughRecords = await loadByChunks(localValues, maxInListSize(through.getAdapter()), (chunk) => through.newQuery(queryOptions).where({ [firstKey]: chunk })[RAW_RESULTS]());
|
|
338
|
+
const throughMap = /* @__PURE__ */ new Map();
|
|
339
|
+
const allThroughIds = /* @__PURE__ */ new Set();
|
|
340
|
+
for (const row of throughRecords) {
|
|
341
|
+
const fk = row[firstKey];
|
|
342
|
+
const tk = row[secondLocalKey];
|
|
343
|
+
if (!throughMap.has(fk)) throughMap.set(fk, []);
|
|
344
|
+
throughMap.get(fk).push(tk);
|
|
345
|
+
allThroughIds.add(tk);
|
|
346
|
+
}
|
|
347
|
+
if (allThroughIds.size === 0) {
|
|
348
|
+
for (const record of records) record[name] = [];
|
|
349
|
+
return false;
|
|
350
|
+
}
|
|
351
|
+
const { records: relatedRecords, projected } = await loadRelatedRecords(related, Array.from(allThroughIds), (chunk) => ({ [secondKey]: chunk }), queryOptions, constraint);
|
|
352
|
+
const relatedByKey = /* @__PURE__ */ new Map();
|
|
353
|
+
for (const item of relatedRecords) {
|
|
354
|
+
const key = item[secondKey];
|
|
355
|
+
if (!relatedByKey.has(key)) relatedByKey.set(key, []);
|
|
356
|
+
relatedByKey.get(key).push({ ...item });
|
|
357
|
+
}
|
|
358
|
+
for (const record of records) {
|
|
359
|
+
const lk = record[localKey];
|
|
360
|
+
if (lk == null) {
|
|
361
|
+
record[name] = [];
|
|
362
|
+
continue;
|
|
363
|
+
}
|
|
364
|
+
const throughIds = throughMap.get(lk) ?? [];
|
|
365
|
+
const items = [];
|
|
366
|
+
for (const tid of throughIds) {
|
|
367
|
+
const matched = relatedByKey.get(tid) ?? [];
|
|
368
|
+
items.push(...matched);
|
|
369
|
+
}
|
|
370
|
+
record[name] = items;
|
|
371
|
+
}
|
|
372
|
+
return projected;
|
|
373
|
+
}
|
|
374
|
+
async function loadMorphMany(owner, records, definition, queryOptions, constraint) {
|
|
375
|
+
const { morphName, localKey, name } = definition;
|
|
376
|
+
const related = await resolveModelReference(definition.related);
|
|
377
|
+
const typeColumn = `${morphName}Type`;
|
|
378
|
+
const idColumn = `${morphName}Id`;
|
|
379
|
+
const parentType = owner.name;
|
|
380
|
+
const localValues = distinctKeys(records, localKey);
|
|
381
|
+
if (localValues.length === 0) {
|
|
382
|
+
for (const record of records) record[name] = [];
|
|
383
|
+
return false;
|
|
384
|
+
}
|
|
385
|
+
const { records: allRelated, projected } = await loadRelatedRecords(related, localValues, (chunk) => ({
|
|
386
|
+
[typeColumn]: parentType,
|
|
387
|
+
[idColumn]: chunk
|
|
388
|
+
}), queryOptions, constraint);
|
|
389
|
+
const map = /* @__PURE__ */ new Map();
|
|
390
|
+
for (const item of allRelated) {
|
|
391
|
+
if (item[typeColumn] !== parentType) continue;
|
|
392
|
+
const key = item[idColumn];
|
|
393
|
+
if (!map.has(key)) map.set(key, []);
|
|
394
|
+
map.get(key).push({ ...item });
|
|
395
|
+
}
|
|
396
|
+
for (const record of records) {
|
|
397
|
+
const key = record[localKey];
|
|
398
|
+
record[name] = key != null ? map.get(key) ?? [] : [];
|
|
399
|
+
}
|
|
400
|
+
return projected;
|
|
401
|
+
}
|
|
402
|
+
async function loadMorphTo(morphMap, records, definition, queryOptions, constraint) {
|
|
403
|
+
const { morphName, name } = definition;
|
|
404
|
+
const typeColumn = `${morphName}Type`;
|
|
405
|
+
const idColumn = `${morphName}Id`;
|
|
406
|
+
const byType = /* @__PURE__ */ new Map();
|
|
407
|
+
for (const record of records) {
|
|
408
|
+
const type = record[typeColumn];
|
|
409
|
+
const id = record[idColumn];
|
|
410
|
+
if (!type || id == null) continue;
|
|
411
|
+
if (!byType.has(type)) byType.set(type, []);
|
|
412
|
+
byType.get(type).push(id);
|
|
413
|
+
}
|
|
414
|
+
const resolved = /* @__PURE__ */ new Map();
|
|
415
|
+
for (const [type, ids] of byType) {
|
|
416
|
+
const modelClass = morphMap[type];
|
|
417
|
+
if (!modelClass) continue;
|
|
418
|
+
const { records: results, projected } = await loadRelatedRecords(modelClass, Array.from(new Set(ids)), (chunk) => ({ id: chunk }), queryOptions, constraint);
|
|
419
|
+
const idMap = /* @__PURE__ */ new Map();
|
|
420
|
+
for (const r of results) idMap.set(r.id, { ...r });
|
|
421
|
+
applyRelatedReadTransforms(modelClass, Array.from(idMap.values()), projected);
|
|
422
|
+
resolved.set(type, idMap);
|
|
423
|
+
}
|
|
424
|
+
for (const record of records) {
|
|
425
|
+
const type = record[typeColumn];
|
|
426
|
+
const id = record[idColumn];
|
|
427
|
+
if (!type || id == null) {
|
|
428
|
+
record[name] = null;
|
|
429
|
+
continue;
|
|
430
|
+
}
|
|
431
|
+
record[name] = resolved.get(type)?.get(id) ?? null;
|
|
432
|
+
}
|
|
433
|
+
}
|
|
434
|
+
//#endregion
|
|
435
|
+
//#region src/relation-tree.ts
|
|
436
|
+
function groupRelationPaths(relationNames) {
|
|
437
|
+
const groups = /* @__PURE__ */ new Map();
|
|
438
|
+
for (const path of relationNames) {
|
|
439
|
+
const [head, ...rest] = path.split(".");
|
|
440
|
+
const tails = groups.get(head) ?? [];
|
|
441
|
+
groups.set(head, tails);
|
|
442
|
+
if (rest.length > 0) {
|
|
443
|
+
const tail = rest.join(".");
|
|
444
|
+
if (!tails.includes(tail)) tails.push(tail);
|
|
445
|
+
}
|
|
446
|
+
}
|
|
447
|
+
return groups;
|
|
448
|
+
}
|
|
449
|
+
async function loadRelationChildren({ modelName, records, definition, head, tails, projected, currentPath, queryOptions, constraints }) {
|
|
450
|
+
if (tails.length > 0 && definition.type === "morphTo") throw new Error(`${modelName}: nested eager loading through morphTo relation "${head}" is not supported.`);
|
|
451
|
+
if (definition.type === "morphTo") return;
|
|
452
|
+
const children = [];
|
|
453
|
+
const seen = /* @__PURE__ */ new Set();
|
|
454
|
+
for (const record of records) {
|
|
455
|
+
const value = record[head];
|
|
456
|
+
const items = Array.isArray(value) ? value : value != null ? [value] : [];
|
|
457
|
+
for (const item of items) if (item && typeof item === "object" && !seen.has(item)) {
|
|
458
|
+
seen.add(item);
|
|
459
|
+
children.push(item);
|
|
460
|
+
}
|
|
461
|
+
}
|
|
462
|
+
if (children.length === 0) return;
|
|
463
|
+
const related = await resolveModelReference(definition.related);
|
|
464
|
+
if (tails.length > 0) await related.loadRelationsInto(children, tails, queryOptions, constraints, currentPath);
|
|
465
|
+
applyRelatedReadTransforms(related, children, projected);
|
|
466
|
+
}
|
|
76
467
|
//#endregion
|
|
77
468
|
//#region src/where-conditions.ts
|
|
78
469
|
/**
|
|
@@ -183,15 +574,74 @@ function buildDrizzleConditions(table, conditions) {
|
|
|
183
574
|
return normalized ? buildSingleCondition(table, normalized) : void 0;
|
|
184
575
|
}
|
|
185
576
|
//#endregion
|
|
186
|
-
//#region src/adapters/
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
577
|
+
//#region src/adapters/is-promise-like.ts
|
|
578
|
+
function isPromiseLike(value) {
|
|
579
|
+
return typeof value === "object" && value !== null && "then" in value && typeof value.then === "function";
|
|
580
|
+
}
|
|
581
|
+
//#endregion
|
|
582
|
+
//#region src/adapters/drizzle-connection.ts
|
|
583
|
+
const connections = /* @__PURE__ */ new WeakMap();
|
|
584
|
+
let defaultConnection;
|
|
191
585
|
let transactionStore;
|
|
192
586
|
let loadedStore;
|
|
193
|
-
|
|
587
|
+
function configureConnection(db) {
|
|
588
|
+
if (!db) {
|
|
589
|
+
defaultConnection = void 0;
|
|
590
|
+
return;
|
|
591
|
+
}
|
|
592
|
+
let connection = connections.get(db);
|
|
593
|
+
if (!connection) {
|
|
594
|
+
connection = createConnectionRuntime(db);
|
|
595
|
+
connections.set(db, connection);
|
|
596
|
+
}
|
|
597
|
+
defaultConnection = connection;
|
|
598
|
+
}
|
|
599
|
+
/** Reconfiguration changes the default, never the owner of an in-flight transaction. */
|
|
600
|
+
function currentConnection() {
|
|
601
|
+
return liveAmbient()?.owner ?? defaultConnection;
|
|
602
|
+
}
|
|
603
|
+
/**
|
|
604
|
+
* The transaction the async context carries, while it is still open; `owner`
|
|
605
|
+
* narrows it to that runtime's own. A settled ambient is ignored: a
|
|
606
|
+
* continuation nobody awaited outlives the transaction it was started in, and
|
|
607
|
+
* its handle is finalised by then.
|
|
608
|
+
*/
|
|
609
|
+
function liveAmbient(owner) {
|
|
610
|
+
const ambient = loadedStore?.getStore();
|
|
611
|
+
if (!ambient || ambient.settled) return void 0;
|
|
612
|
+
return owner && ambient.owner !== owner ? void 0 : ambient;
|
|
613
|
+
}
|
|
614
|
+
/**
|
|
615
|
+
* Imported on demand so `node:async_hooks` stays off the module graph until a
|
|
616
|
+
* transaction is opened (Workers needs `nodejs_compat` for it, as for
|
|
617
|
+
* `node:crypto`). The promise is what is memoized, not the storage: two
|
|
618
|
+
* concurrent first callers must not end up asking different instances.
|
|
619
|
+
*/
|
|
620
|
+
function loadTransactionStore() {
|
|
621
|
+
transactionStore ??= import("node:async_hooks").then(({ AsyncLocalStorage }) => {
|
|
622
|
+
loadedStore = new AsyncLocalStorage();
|
|
623
|
+
return loadedStore;
|
|
624
|
+
});
|
|
625
|
+
return transactionStore;
|
|
626
|
+
}
|
|
194
627
|
const POOLED_IN_LIST_SIZE = 5e3;
|
|
628
|
+
const SYNC_EXECUTIONS = [
|
|
629
|
+
"all",
|
|
630
|
+
"get",
|
|
631
|
+
"run",
|
|
632
|
+
"values"
|
|
633
|
+
];
|
|
634
|
+
const NOOP = () => void 0;
|
|
635
|
+
function isCallable(value) {
|
|
636
|
+
return typeof value === "function";
|
|
637
|
+
}
|
|
638
|
+
function define(target, key, value) {
|
|
639
|
+
Object.defineProperty(target, key, {
|
|
640
|
+
configurable: true,
|
|
641
|
+
writable: true,
|
|
642
|
+
value
|
|
643
|
+
});
|
|
644
|
+
}
|
|
195
645
|
/**
|
|
196
646
|
* Read from how the dialect escapes a parameter and a name, since this adapter
|
|
197
647
|
* takes any drizzle-shaped handle and a driver list would name one it has never
|
|
@@ -205,6 +655,211 @@ function dialectInListSize(db) {
|
|
|
205
655
|
} catch {}
|
|
206
656
|
return 500;
|
|
207
657
|
}
|
|
658
|
+
function createConnectionRuntime(db) {
|
|
659
|
+
let transactionAwaitsCallback;
|
|
660
|
+
let inListSize;
|
|
661
|
+
let transactionQueue = Promise.resolve();
|
|
662
|
+
const pendingOperations = /* @__PURE__ */ new Set();
|
|
663
|
+
let manualTransactionOpen = false;
|
|
664
|
+
let savepointSequence = 0;
|
|
665
|
+
/**
|
|
666
|
+
* An explicit `trx` wins; without one, a call made inside a `transaction()`
|
|
667
|
+
* callback runs on that transaction. Off the pool, on a driver whose pool is
|
|
668
|
+
* `max: 1`, it would wait on the connection the open transaction holds.
|
|
669
|
+
*/
|
|
670
|
+
function resolveExecutor(options) {
|
|
671
|
+
if (options?.trx && typeof options.trx === "object") return options.trx;
|
|
672
|
+
const handle = liveAmbient(runtime)?.handle;
|
|
673
|
+
if (typeof handle === "object" && handle !== null) return handle;
|
|
674
|
+
return db;
|
|
675
|
+
}
|
|
676
|
+
function withExecutor(options, callback) {
|
|
677
|
+
if (options?.trx || liveAmbient(runtime)) return callback(resolveExecutor(options));
|
|
678
|
+
if (transactionAwaitsCallback === false) {
|
|
679
|
+
const operation = transactionQueue.then(() => callback(db));
|
|
680
|
+
transactionQueue = operation.then(NOOP, NOOP);
|
|
681
|
+
return operation;
|
|
682
|
+
}
|
|
683
|
+
const operation = callback(db);
|
|
684
|
+
if (transactionAwaitsCallback === void 0) {
|
|
685
|
+
pendingOperations.add(operation);
|
|
686
|
+
const forget = () => pendingOperations.delete(operation);
|
|
687
|
+
operation.then(forget, forget);
|
|
688
|
+
}
|
|
689
|
+
return operation;
|
|
690
|
+
}
|
|
691
|
+
/** A BEGIN this adapter issued is on the connection, and the caller is not inside it. */
|
|
692
|
+
function foreignTransactionOpen() {
|
|
693
|
+
return manualTransactionOpen && !liveAmbient(runtime);
|
|
694
|
+
}
|
|
695
|
+
/**
|
|
696
|
+
* `then` reaches drizzle's `execute()`, so replacing it on the instance routes
|
|
697
|
+
* every await through `withExecutor`. `all()`/`get()`/`run()`/`values()` return
|
|
698
|
+
* synchronously on bun:sqlite and cannot wait: during a transaction another
|
|
699
|
+
* context holds they would run inside it, so they throw instead. A prepared
|
|
700
|
+
* statement executes later, so it gets the same treatment.
|
|
701
|
+
*/
|
|
702
|
+
function queueQuery(query, queryOptions) {
|
|
703
|
+
if (!query || typeof query !== "object") return query;
|
|
704
|
+
const target = query;
|
|
705
|
+
const { execute, prepare } = target;
|
|
706
|
+
if (isCallable(execute)) define(target, "execute", (...args) => withExecutor(queryOptions, async () => execute.apply(target, args)));
|
|
707
|
+
if (isCallable(prepare)) define(target, "prepare", (...args) => queueQuery(prepare.apply(target, args), queryOptions));
|
|
708
|
+
for (const method of SYNC_EXECUTIONS) {
|
|
709
|
+
const run = target[method];
|
|
710
|
+
if (!isCallable(run)) continue;
|
|
711
|
+
define(target, method, (...args) => {
|
|
712
|
+
if (foreignTransactionOpen()) throw new Error(`DrizzleAdapter: ${method}() cannot wait for the transaction another context has open on this connection, and would run inside it. Await the query instead.`);
|
|
713
|
+
return run.apply(target, args);
|
|
714
|
+
});
|
|
715
|
+
}
|
|
716
|
+
return query;
|
|
717
|
+
}
|
|
718
|
+
/**
|
|
719
|
+
* Whether `db.transaction()` awaits its callback before committing: drizzle's
|
|
720
|
+
* bun-sqlite COMMITs on whatever the callback returns, d1 and every pg/mysql
|
|
721
|
+
* driver await it. Probed rather than matched against a driver list, because
|
|
722
|
+
* this adapter takes any drizzle-shaped handle and one a list never named gets
|
|
723
|
+
* the wrong path silently. Costs one empty transaction per configured database.
|
|
724
|
+
*/
|
|
725
|
+
async function awaitsItsCallback(db) {
|
|
726
|
+
if (transactionAwaitsCallback === void 0) {
|
|
727
|
+
const probe = db.transaction?.(NOOP);
|
|
728
|
+
transactionAwaitsCallback = isPromiseLike(probe);
|
|
729
|
+
if (isPromiseLike(probe)) await probe.catch(NOOP);
|
|
730
|
+
}
|
|
731
|
+
return transactionAwaitsCallback;
|
|
732
|
+
}
|
|
733
|
+
/**
|
|
734
|
+
* Opened on the root database for a top-level call and on the open
|
|
735
|
+
* transaction's own handle for a nested one, which is what makes drizzle emit
|
|
736
|
+
* SAVEPOINT for the second. `settled` is set once the transaction itself has
|
|
737
|
+
* finished, not once its callback has.
|
|
738
|
+
*/
|
|
739
|
+
async function runDriverTransaction(open, store, callback) {
|
|
740
|
+
let entry;
|
|
741
|
+
try {
|
|
742
|
+
return await open((trx) => {
|
|
743
|
+
entry = driverEntry(trx, store);
|
|
744
|
+
return store.run(entry, () => callback(trx));
|
|
745
|
+
});
|
|
746
|
+
} finally {
|
|
747
|
+
if (entry) entry.settled = true;
|
|
748
|
+
}
|
|
749
|
+
}
|
|
750
|
+
function driverEntry(handle, store) {
|
|
751
|
+
const open = handle.transaction;
|
|
752
|
+
return {
|
|
753
|
+
owner: runtime,
|
|
754
|
+
handle,
|
|
755
|
+
settled: false,
|
|
756
|
+
nest: (callback) => typeof open === "function" ? runDriverTransaction(open.bind(handle), store, callback) : callback(handle)
|
|
757
|
+
};
|
|
758
|
+
}
|
|
759
|
+
function manualEntry(run, store) {
|
|
760
|
+
return {
|
|
761
|
+
owner: runtime,
|
|
762
|
+
handle: db,
|
|
763
|
+
settled: false,
|
|
764
|
+
nest: (callback) => runSavepoint(run, store, callback)
|
|
765
|
+
};
|
|
766
|
+
}
|
|
767
|
+
/**
|
|
768
|
+
* The savepoint the manual BEGIN/COMMIT path drives itself: this driver's own
|
|
769
|
+
* `transaction()` commits before awaiting, so a nested call cannot go through
|
|
770
|
+
* it. Savepoints do not pass through `transactionQueue`, so nested
|
|
771
|
+
* transactions have to be awaited one at a time — two released out of order
|
|
772
|
+
* discard each other's frames.
|
|
773
|
+
*/
|
|
774
|
+
async function runSavepoint(run, store, callback) {
|
|
775
|
+
const name = `guren_sp_${savepointSequence += 1}`;
|
|
776
|
+
await run(sql.raw(`savepoint ${name}`));
|
|
777
|
+
return enterTransaction(run, store, callback, {
|
|
778
|
+
commit: [`release savepoint ${name}`],
|
|
779
|
+
rollback: [`rollback to savepoint ${name}`, `release savepoint ${name}`]
|
|
780
|
+
});
|
|
781
|
+
}
|
|
782
|
+
/**
|
|
783
|
+
* The lifecycle both hand-driven paths share, from the statement that opened the
|
|
784
|
+
* transaction to the one that settles it. The entry is entered synchronously,
|
|
785
|
+
* which is what puts every await inside the callback — and so any transaction it
|
|
786
|
+
* starts — in this transaction's async context.
|
|
787
|
+
*/
|
|
788
|
+
async function enterTransaction(run, store, callback, settle) {
|
|
789
|
+
const entry = manualEntry(run, store);
|
|
790
|
+
try {
|
|
791
|
+
const result = await store.run(entry, () => callback(db));
|
|
792
|
+
for (const statement of settle.commit) await run(sql.raw(statement));
|
|
793
|
+
return result;
|
|
794
|
+
} catch (error) {
|
|
795
|
+
try {
|
|
796
|
+
for (const statement of settle.rollback) await run(sql.raw(statement));
|
|
797
|
+
} catch {}
|
|
798
|
+
throw error;
|
|
799
|
+
} finally {
|
|
800
|
+
entry.settled = true;
|
|
801
|
+
}
|
|
802
|
+
}
|
|
803
|
+
/**
|
|
804
|
+
* Serializes what `runExclusively` drives, since one connection takes one
|
|
805
|
+
* transaction. Only a caller outside every transaction may wait here: a nested
|
|
806
|
+
* one would queue behind itself, which is why `transaction()` settles nesting
|
|
807
|
+
* from the async context before reaching this queue.
|
|
808
|
+
*/
|
|
809
|
+
async function runOwnTransaction(store, callback) {
|
|
810
|
+
if (typeof db.run !== "function") throw new Error("DrizzleAdapter: the configured database commits before its transaction callback has awaited anything, and exposes no run() to drive BEGIN/COMMIT with, so transactions on it cannot be made atomic.");
|
|
811
|
+
const run = db.run.bind(db);
|
|
812
|
+
const pending = [...pendingOperations];
|
|
813
|
+
const slot = transactionQueue.then(async () => {
|
|
814
|
+
await Promise.allSettled(pending);
|
|
815
|
+
return runExclusively(run, store, callback);
|
|
816
|
+
});
|
|
817
|
+
transactionQueue = slot.then(NOOP, NOOP);
|
|
818
|
+
return slot;
|
|
819
|
+
}
|
|
820
|
+
/**
|
|
821
|
+
* BEGIN/COMMIT/ROLLBACK driven here so an async callback is honoured on a driver
|
|
822
|
+
* that would otherwise commit before awaiting it. The handle itself is the
|
|
823
|
+
* transaction scope: these drivers hold one connection, so every statement
|
|
824
|
+
* between BEGIN and COMMIT is inside it. Callers reach this one at a time.
|
|
825
|
+
*/
|
|
826
|
+
async function runExclusively(run, store, callback) {
|
|
827
|
+
manualTransactionOpen = true;
|
|
828
|
+
try {
|
|
829
|
+
await run(sql.raw("begin"));
|
|
830
|
+
return await enterTransaction(run, store, callback, {
|
|
831
|
+
commit: ["commit"],
|
|
832
|
+
rollback: ["rollback"]
|
|
833
|
+
});
|
|
834
|
+
} finally {
|
|
835
|
+
manualTransactionOpen = false;
|
|
836
|
+
}
|
|
837
|
+
}
|
|
838
|
+
const runtime = {
|
|
839
|
+
database: db,
|
|
840
|
+
executor: resolveExecutor,
|
|
841
|
+
run: withExecutor,
|
|
842
|
+
queueExecution(query, options) {
|
|
843
|
+
if (options?.trx || transactionAwaitsCallback === true) return query;
|
|
844
|
+
return queueQuery(query, options);
|
|
845
|
+
},
|
|
846
|
+
maxInListSize() {
|
|
847
|
+
inListSize ??= dialectInListSize(db);
|
|
848
|
+
return inListSize;
|
|
849
|
+
},
|
|
850
|
+
async transaction(callback) {
|
|
851
|
+
if (typeof db.transaction !== "function") throw new Error("DrizzleAdapter: configured database does not support transactions.");
|
|
852
|
+
const store = await loadTransactionStore();
|
|
853
|
+
const ambient = liveAmbient(runtime);
|
|
854
|
+
if (ambient) return ambient.nest(callback);
|
|
855
|
+
if (await awaitsItsCallback(db)) return runDriverTransaction(db.transaction.bind(db), store, callback);
|
|
856
|
+
return runOwnTransaction(store, callback);
|
|
857
|
+
}
|
|
858
|
+
};
|
|
859
|
+
return runtime;
|
|
860
|
+
}
|
|
861
|
+
//#endregion
|
|
862
|
+
//#region src/adapters/drizzle-adapter.ts
|
|
208
863
|
function withConditions(query, table, conditions) {
|
|
209
864
|
if (typeof query.where !== "function") return query;
|
|
210
865
|
const clause = buildDrizzleConditions(table, conditions);
|
|
@@ -240,22 +895,10 @@ function decodeAggregate(fn, column, field, raw) {
|
|
|
240
895
|
if (kind === "string") return String(raw);
|
|
241
896
|
return raw;
|
|
242
897
|
}
|
|
243
|
-
function
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
/**
|
|
248
|
-
* An explicit `trx` wins; without one, a call made inside a `transaction()`
|
|
249
|
-
* callback runs on that transaction. Off the pool, on a driver whose pool is
|
|
250
|
-
* `max: 1`, it would wait on the connection the open transaction holds. A
|
|
251
|
-
* settled ambient is ignored: a continuation nobody awaited outlives the
|
|
252
|
-
* transaction it was started in, and its handle is finalised by then.
|
|
253
|
-
*/
|
|
254
|
-
function resolveExecutor(options) {
|
|
255
|
-
if (options?.trx && typeof options.trx === "object") return options.trx;
|
|
256
|
-
const ambient = loadedStore?.getStore();
|
|
257
|
-
if (ambient && !ambient.settled && typeof ambient.handle === "object" && ambient.handle !== null) return ambient.handle;
|
|
258
|
-
return ensureDatabase();
|
|
898
|
+
function connection() {
|
|
899
|
+
const runtime = currentConnection();
|
|
900
|
+
if (!runtime) throw new Error("DrizzleAdapter: database has not been configured. Call DrizzleAdapter.configure(db).");
|
|
901
|
+
return runtime;
|
|
259
902
|
}
|
|
260
903
|
async function resolveList(result) {
|
|
261
904
|
if (isPromiseLike(result)) return result;
|
|
@@ -307,9 +950,6 @@ async function resolveMutation(result) {
|
|
|
307
950
|
if ("run" in result && typeof result.run === "function") return result.run();
|
|
308
951
|
return result;
|
|
309
952
|
}
|
|
310
|
-
function isPromiseLike(value) {
|
|
311
|
-
return typeof value === "object" && value !== null && "then" in value && typeof value.then === "function";
|
|
312
|
-
}
|
|
313
953
|
/**
|
|
314
954
|
* Eagerly call `.returning()` if available: bun-sqlite's query builders are
|
|
315
955
|
* thenable, so `resolveMutation`'s `isPromiseLike` check would otherwise win
|
|
@@ -328,328 +968,162 @@ async function resolveWithReturning(query) {
|
|
|
328
968
|
row: void 0
|
|
329
969
|
};
|
|
330
970
|
}
|
|
331
|
-
const NOOP = () => void 0;
|
|
332
|
-
/**
|
|
333
|
-
* Whether `db.transaction()` awaits its callback before committing: drizzle's
|
|
334
|
-
* bun-sqlite COMMITs on whatever the callback returns, d1 and every pg/mysql
|
|
335
|
-
* driver await it. Probed rather than matched against a driver list, because
|
|
336
|
-
* this adapter takes any drizzle-shaped handle and one a list never named gets
|
|
337
|
-
* the wrong path silently. Costs one empty transaction per configured database.
|
|
338
|
-
*/
|
|
339
|
-
async function awaitsItsCallback(db) {
|
|
340
|
-
if (transactionAwaitsCallback === void 0) {
|
|
341
|
-
const probe = db.transaction?.(NOOP);
|
|
342
|
-
transactionAwaitsCallback = isPromiseLike(probe);
|
|
343
|
-
if (isPromiseLike(probe)) await probe.catch(NOOP);
|
|
344
|
-
}
|
|
345
|
-
return transactionAwaitsCallback;
|
|
346
|
-
}
|
|
347
|
-
/**
|
|
348
|
-
* Imported on demand so `node:async_hooks` stays off the module graph until a
|
|
349
|
-
* transaction is opened (Workers needs `nodejs_compat` for it, as for
|
|
350
|
-
* `node:crypto`). The promise is what is memoized, not the storage: two
|
|
351
|
-
* concurrent first callers must not end up asking different instances.
|
|
352
|
-
*/
|
|
353
|
-
function loadTransactionStore() {
|
|
354
|
-
transactionStore ??= import("node:async_hooks").then(({ AsyncLocalStorage }) => {
|
|
355
|
-
loadedStore = new AsyncLocalStorage();
|
|
356
|
-
return loadedStore;
|
|
357
|
-
});
|
|
358
|
-
return transactionStore;
|
|
359
|
-
}
|
|
360
|
-
/**
|
|
361
|
-
* Opened on the root database for a top-level call and on the open
|
|
362
|
-
* transaction's own handle for a nested one, which is what makes drizzle emit
|
|
363
|
-
* SAVEPOINT for the second. `settled` is set once the transaction itself has
|
|
364
|
-
* finished, not once its callback has.
|
|
365
|
-
*/
|
|
366
|
-
async function runDriverTransaction(open, store, callback) {
|
|
367
|
-
let entry;
|
|
368
|
-
try {
|
|
369
|
-
return await open((trx) => {
|
|
370
|
-
entry = driverEntry(trx, store);
|
|
371
|
-
return store.run(entry, () => callback(trx));
|
|
372
|
-
});
|
|
373
|
-
} finally {
|
|
374
|
-
if (entry) entry.settled = true;
|
|
375
|
-
}
|
|
376
|
-
}
|
|
377
|
-
function driverEntry(handle, store) {
|
|
378
|
-
const open = handle.transaction;
|
|
379
|
-
return {
|
|
380
|
-
handle,
|
|
381
|
-
settled: false,
|
|
382
|
-
nest: (callback) => typeof open === "function" ? runDriverTransaction(open.bind(handle), store, callback) : callback(handle)
|
|
383
|
-
};
|
|
384
|
-
}
|
|
385
|
-
function manualEntry(db, run, store) {
|
|
386
|
-
return {
|
|
387
|
-
handle: db,
|
|
388
|
-
settled: false,
|
|
389
|
-
nest: (callback) => runSavepoint(db, run, store, callback)
|
|
390
|
-
};
|
|
391
|
-
}
|
|
392
|
-
/**
|
|
393
|
-
* The savepoint the manual BEGIN/COMMIT path drives itself: this driver's own
|
|
394
|
-
* `transaction()` commits before awaiting, so a nested call cannot go through
|
|
395
|
-
* it. Savepoints do not pass through `transactionQueue`, so nested
|
|
396
|
-
* transactions have to be awaited one at a time — two released out of order
|
|
397
|
-
* discard each other's frames.
|
|
398
|
-
*/
|
|
399
|
-
async function runSavepoint(db, run, store, callback) {
|
|
400
|
-
const name = `guren_sp_${savepointSequence += 1}`;
|
|
401
|
-
await run(sql.raw(`savepoint ${name}`));
|
|
402
|
-
return enterTransaction(db, run, store, callback, {
|
|
403
|
-
commit: [`release savepoint ${name}`],
|
|
404
|
-
rollback: [`rollback to savepoint ${name}`, `release savepoint ${name}`]
|
|
405
|
-
});
|
|
406
|
-
}
|
|
407
|
-
/**
|
|
408
|
-
* The lifecycle both hand-driven paths share, from the statement that opened the
|
|
409
|
-
* transaction to the one that settles it. The entry is entered synchronously,
|
|
410
|
-
* which is what puts every await inside the callback — and so any transaction it
|
|
411
|
-
* starts — in this transaction's async context.
|
|
412
|
-
*/
|
|
413
|
-
async function enterTransaction(db, run, store, callback, settle) {
|
|
414
|
-
const entry = manualEntry(db, run, store);
|
|
415
|
-
try {
|
|
416
|
-
const result = await store.run(entry, () => callback(db));
|
|
417
|
-
for (const statement of settle.commit) await run(sql.raw(statement));
|
|
418
|
-
return result;
|
|
419
|
-
} catch (error) {
|
|
420
|
-
try {
|
|
421
|
-
for (const statement of settle.rollback) await run(sql.raw(statement));
|
|
422
|
-
} catch {}
|
|
423
|
-
throw error;
|
|
424
|
-
} finally {
|
|
425
|
-
entry.settled = true;
|
|
426
|
-
}
|
|
427
|
-
}
|
|
428
|
-
/**
|
|
429
|
-
* Serializes what `runExclusively` drives, since one connection takes one
|
|
430
|
-
* transaction. Only a caller outside every transaction may wait here: a nested
|
|
431
|
-
* one would queue behind itself, which is why `transaction()` settles nesting
|
|
432
|
-
* from the async context before reaching this queue.
|
|
433
|
-
*/
|
|
434
|
-
async function runOwnTransaction(db, store, callback) {
|
|
435
|
-
if (typeof db.run !== "function") throw new Error("DrizzleAdapter: the configured database commits before its transaction callback has awaited anything, and exposes no run() to drive BEGIN/COMMIT with, so transactions on it cannot be made atomic.");
|
|
436
|
-
const run = db.run.bind(db);
|
|
437
|
-
const slot = transactionQueue.then(() => runExclusively(db, run, store, callback));
|
|
438
|
-
transactionQueue = slot.then(NOOP, NOOP);
|
|
439
|
-
return slot;
|
|
440
|
-
}
|
|
441
|
-
/**
|
|
442
|
-
* BEGIN/COMMIT/ROLLBACK driven here so an async callback is honoured on a driver
|
|
443
|
-
* that would otherwise commit before awaiting it. The handle itself is the
|
|
444
|
-
* transaction scope: these drivers hold one connection, so every statement
|
|
445
|
-
* between BEGIN and COMMIT is inside it. Callers reach this one at a time.
|
|
446
|
-
*/
|
|
447
|
-
async function runExclusively(db, run, store, callback) {
|
|
448
|
-
await run(sql.raw("begin"));
|
|
449
|
-
return enterTransaction(db, run, store, callback, {
|
|
450
|
-
commit: ["commit"],
|
|
451
|
-
rollback: ["rollback"]
|
|
452
|
-
});
|
|
453
|
-
}
|
|
454
971
|
const DrizzleAdapter = {
|
|
455
|
-
configure
|
|
456
|
-
database = db;
|
|
457
|
-
transactionAwaitsCallback = void 0;
|
|
458
|
-
inListSize = void 0;
|
|
459
|
-
transactionQueue = Promise.resolve();
|
|
460
|
-
},
|
|
972
|
+
configure: configureConnection,
|
|
461
973
|
getDatabase() {
|
|
462
|
-
return
|
|
974
|
+
return connection().database;
|
|
463
975
|
},
|
|
464
976
|
maxInListSize() {
|
|
465
|
-
|
|
466
|
-
inListSize ??= dialectInListSize(database);
|
|
467
|
-
return inListSize;
|
|
977
|
+
return currentConnection()?.maxInListSize() ?? 500;
|
|
468
978
|
},
|
|
469
979
|
async findMany(table, options, queryOptions) {
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
980
|
+
return connection().run(queryOptions, async (db) => {
|
|
981
|
+
let query = db.select().from(table);
|
|
982
|
+
const { where, orderBy, limit, offset } = options ?? {};
|
|
983
|
+
if (typeof query.where === "function") {
|
|
984
|
+
const clause = resolveWhere(table, where);
|
|
985
|
+
if (clause) query = query.where(clause);
|
|
986
|
+
}
|
|
987
|
+
if (typeof query.orderBy === "function") {
|
|
988
|
+
const clauses = resolveOrder(table, orderBy);
|
|
989
|
+
if (clauses && clauses.length > 0) query = query.orderBy(...clauses);
|
|
990
|
+
}
|
|
991
|
+
if (typeof query.limit === "function" && typeof limit === "number") query = query.limit(limit);
|
|
992
|
+
if (typeof query.offset === "function" && typeof offset === "number") query = query.offset(offset);
|
|
993
|
+
return await resolveList(query);
|
|
994
|
+
});
|
|
483
995
|
},
|
|
484
996
|
async count(table, where, queryOptions) {
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
997
|
+
return connection().run(queryOptions, async (db) => {
|
|
998
|
+
let query = db.select({ value: count() }).from(table);
|
|
999
|
+
if (typeof query.where === "function") {
|
|
1000
|
+
const clause = resolveWhere(table, where);
|
|
1001
|
+
if (clause) query = query.where(clause);
|
|
1002
|
+
}
|
|
1003
|
+
return toCount((await resolveList(query))[0]?.value);
|
|
1004
|
+
});
|
|
491
1005
|
},
|
|
492
1006
|
async findUnique(table, where, queryOptions) {
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
1007
|
+
return connection().run(queryOptions, async (db) => {
|
|
1008
|
+
let query = db.select().from(table);
|
|
1009
|
+
if (typeof query.where === "function") {
|
|
1010
|
+
const clause = resolveWhere(table, where);
|
|
1011
|
+
if (clause) query = query.where(clause);
|
|
1012
|
+
}
|
|
1013
|
+
const row = await resolveSingle(query);
|
|
1014
|
+
if (row == null) return null;
|
|
1015
|
+
return row;
|
|
1016
|
+
});
|
|
501
1017
|
},
|
|
502
1018
|
async create(table, data, writeOptions) {
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
1019
|
+
return connection().run(writeOptions, async (db) => {
|
|
1020
|
+
const query = db.insert(table).values(data);
|
|
1021
|
+
const { usedReturning, row } = await resolveWithReturning(query);
|
|
1022
|
+
if (usedReturning) return row;
|
|
1023
|
+
return await resolveMutation(query);
|
|
1024
|
+
});
|
|
507
1025
|
},
|
|
508
1026
|
async update(table, where, data, writeOptions) {
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
1027
|
+
return connection().run(writeOptions, async (db) => {
|
|
1028
|
+
if (!db.update) throw new Error("DrizzleAdapter: configured database does not support updates.");
|
|
1029
|
+
const clause = resolveWhere(table, where);
|
|
1030
|
+
const finalQuery = clause ? db.update(table).set(data).where(clause) : db.update(table).set(data);
|
|
1031
|
+
const { usedReturning, row } = await resolveWithReturning(finalQuery);
|
|
1032
|
+
if (usedReturning) return row;
|
|
1033
|
+
return await resolveMutation(finalQuery);
|
|
1034
|
+
});
|
|
516
1035
|
},
|
|
517
1036
|
async delete(table, where, writeOptions) {
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
1037
|
+
return connection().run(writeOptions, async (db) => {
|
|
1038
|
+
if (!db.delete) throw new Error("DrizzleAdapter: configured database does not support deletes.");
|
|
1039
|
+
const clause = resolveWhere(table, where);
|
|
1040
|
+
const finalQuery = clause ? db.delete(table).where(clause) : db.delete(table);
|
|
1041
|
+
const { usedReturning, row } = await resolveWithReturning(finalQuery);
|
|
1042
|
+
if (usedReturning) return row;
|
|
1043
|
+
return await resolveMutation(finalQuery);
|
|
1044
|
+
});
|
|
525
1045
|
},
|
|
526
1046
|
async findManyAdvanced(table, conditions, options, queryOptions) {
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
1047
|
+
return connection().run(queryOptions, async (db) => {
|
|
1048
|
+
const tableRecord = table;
|
|
1049
|
+
let query;
|
|
1050
|
+
if (options.select && options.select.length > 0) {
|
|
1051
|
+
const selection = {};
|
|
1052
|
+
for (const field of options.select) {
|
|
1053
|
+
const column = tableRecord[field];
|
|
1054
|
+
if (!column) throw new Error(`DrizzleAdapter: unknown column "${field}" on provided table.`);
|
|
1055
|
+
selection[field] = column;
|
|
1056
|
+
}
|
|
1057
|
+
query = db.select(selection).from(table);
|
|
1058
|
+
} else query = db.select().from(table);
|
|
1059
|
+
query = withConditions(query, table, conditions);
|
|
1060
|
+
if (typeof query.orderBy === "function") {
|
|
1061
|
+
const clauses = resolveOrder(table, options.orderBy);
|
|
1062
|
+
if (clauses && clauses.length > 0) query = query.orderBy(...clauses);
|
|
536
1063
|
}
|
|
537
|
-
query =
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
const clauses = resolveOrder(table, options.orderBy);
|
|
542
|
-
if (clauses && clauses.length > 0) query = query.orderBy(...clauses);
|
|
543
|
-
}
|
|
544
|
-
if (typeof query.limit === "function" && typeof options.limit === "number") query = query.limit(options.limit);
|
|
545
|
-
if (typeof query.offset === "function" && typeof options.offset === "number") query = query.offset(options.offset);
|
|
546
|
-
return await resolveList(query);
|
|
1064
|
+
if (typeof query.limit === "function" && typeof options.limit === "number") query = query.limit(options.limit);
|
|
1065
|
+
if (typeof query.offset === "function" && typeof options.offset === "number") query = query.offset(options.offset);
|
|
1066
|
+
return await resolveList(query);
|
|
1067
|
+
});
|
|
547
1068
|
},
|
|
548
1069
|
async countAdvanced(table, conditions, queryOptions) {
|
|
549
|
-
return
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
},
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
const ambient = store.getStore();
|
|
605
|
-
if (ambient && !ambient.settled) return ambient.nest(callback);
|
|
606
|
-
if (await awaitsItsCallback(db)) return runDriverTransaction(db.transaction.bind(db), store, callback);
|
|
607
|
-
return runOwnTransaction(db, store, callback);
|
|
608
|
-
}
|
|
609
|
-
};
|
|
610
|
-
//#endregion
|
|
611
|
-
//#region src/attributes.ts
|
|
612
|
-
const PROTOTYPE_KEYS = /* @__PURE__ */ new Set([
|
|
613
|
-
"__proto__",
|
|
614
|
-
"constructor",
|
|
615
|
-
"prototype"
|
|
616
|
-
]);
|
|
617
|
-
/**
|
|
618
|
-
* A computed field is written with `record[key] = …`, and `__proto__` as a key
|
|
619
|
-
* would rewrite the record's prototype rather than a column. The names come
|
|
620
|
-
* from a model's static definitions, so refusing them is a boot-time mistake
|
|
621
|
-
* surfacing at first use, not a runtime input check.
|
|
622
|
-
*/
|
|
623
|
-
function assertWritableKey(key, kind) {
|
|
624
|
-
if (PROTOTYPE_KEYS.has(key)) throw new Error(`An ${kind} cannot be named "${key}": that key would alter the record's prototype.`);
|
|
625
|
-
}
|
|
626
|
-
/** Writes the computed values onto `record`; each accessor sees the ones before it. */
|
|
627
|
-
function applyAccessorsInPlace(record, accessors) {
|
|
628
|
-
for (const key of Object.keys(accessors)) {
|
|
629
|
-
assertWritableKey(key, "accessor");
|
|
630
|
-
record[key] = accessors[key](record);
|
|
631
|
-
}
|
|
632
|
-
}
|
|
633
|
-
/** Apply accessors to a record, returning a new record with computed values. */
|
|
634
|
-
function applyAccessors(record, accessors) {
|
|
635
|
-
if (!accessors) return record;
|
|
636
|
-
if (Object.keys(accessors).length === 0) return record;
|
|
637
|
-
const result = { ...record };
|
|
638
|
-
applyAccessorsInPlace(result, accessors);
|
|
639
|
-
return result;
|
|
640
|
-
}
|
|
641
|
-
/** Apply mutators to data before persistence, returning a new object. */
|
|
642
|
-
function applyMutators(data, mutators) {
|
|
643
|
-
if (!mutators) return data;
|
|
644
|
-
const keys = Object.keys(mutators);
|
|
645
|
-
if (keys.length === 0) return data;
|
|
646
|
-
const result = { ...data };
|
|
647
|
-
for (const key of keys) {
|
|
648
|
-
assertWritableKey(key, "mutator");
|
|
649
|
-
if (Object.hasOwn(result, key)) result[key] = mutators[key](result[key], result);
|
|
1070
|
+
return connection().run(queryOptions, async (db) => {
|
|
1071
|
+
return toCount((await resolveList(withConditions(db.select({ value: count() }).from(table), table, conditions)))[0]?.value);
|
|
1072
|
+
});
|
|
1073
|
+
},
|
|
1074
|
+
async aggregateAdvanced(table, fn, field, conditions, queryOptions) {
|
|
1075
|
+
return connection().run(queryOptions, async (db) => {
|
|
1076
|
+
const column = resolveColumn(table, field);
|
|
1077
|
+
const expression = fn === "min" ? min(column) : fn === "max" ? max(column) : sql`${sql.raw(fn)}(${column})`;
|
|
1078
|
+
return decodeAggregate(fn, column, field, (await resolveList(withConditions(db.select({ value: expression }).from(table), table, conditions)))[0]?.value ?? null);
|
|
1079
|
+
});
|
|
1080
|
+
},
|
|
1081
|
+
executor(queryOptions) {
|
|
1082
|
+
return connection().executor(queryOptions);
|
|
1083
|
+
},
|
|
1084
|
+
queueExecution(query, queryOptions) {
|
|
1085
|
+
return connection().queueExecution(query, queryOptions);
|
|
1086
|
+
},
|
|
1087
|
+
async countByAdvanced(table, field, conditions, queryOptions) {
|
|
1088
|
+
return connection().run(queryOptions, async (db) => {
|
|
1089
|
+
const column = table[field];
|
|
1090
|
+
if (!column) throw new Error(`DrizzleAdapter: unknown column "${field}" on provided table.`);
|
|
1091
|
+
let query = withConditions(db.select({
|
|
1092
|
+
key: column,
|
|
1093
|
+
value: count()
|
|
1094
|
+
}).from(table), table, conditions);
|
|
1095
|
+
if (typeof query.groupBy !== "function") throw new Error("DrizzleAdapter: configured database does not support groupBy().");
|
|
1096
|
+
query = query.groupBy(column);
|
|
1097
|
+
return (await resolveList(query)).map(({ key, value }) => ({
|
|
1098
|
+
key,
|
|
1099
|
+
count: toCount(value)
|
|
1100
|
+
}));
|
|
1101
|
+
});
|
|
1102
|
+
},
|
|
1103
|
+
async updateAdvanced(table, conditions, data, writeOptions) {
|
|
1104
|
+
return connection().run(writeOptions, async (db) => {
|
|
1105
|
+
if (!db.update) throw new Error("DrizzleAdapter: configured database does not support updates.");
|
|
1106
|
+
const clause = buildDrizzleConditions(table, conditions);
|
|
1107
|
+
const finalQuery = clause ? db.update(table).set(data).where(clause) : db.update(table).set(data);
|
|
1108
|
+
const { usedReturning, row } = await resolveWithReturning(finalQuery);
|
|
1109
|
+
if (usedReturning) return row;
|
|
1110
|
+
return await resolveMutation(finalQuery);
|
|
1111
|
+
});
|
|
1112
|
+
},
|
|
1113
|
+
async deleteAdvanced(table, conditions, writeOptions) {
|
|
1114
|
+
return connection().run(writeOptions, async (db) => {
|
|
1115
|
+
if (!db.delete) throw new Error("DrizzleAdapter: configured database does not support deletes.");
|
|
1116
|
+
const clause = buildDrizzleConditions(table, conditions);
|
|
1117
|
+
const finalQuery = clause ? db.delete(table).where(clause) : db.delete(table);
|
|
1118
|
+
const { usedReturning, row } = await resolveWithReturning(finalQuery);
|
|
1119
|
+
if (usedReturning) return row;
|
|
1120
|
+
return await resolveMutation(finalQuery);
|
|
1121
|
+
});
|
|
1122
|
+
},
|
|
1123
|
+
async transaction(callback) {
|
|
1124
|
+
return connection().transaction(callback);
|
|
650
1125
|
}
|
|
651
|
-
|
|
652
|
-
}
|
|
1126
|
+
};
|
|
653
1127
|
//#endregion
|
|
654
1128
|
//#region src/deprecate.ts
|
|
655
1129
|
const warned = /* @__PURE__ */ new Set();
|
|
@@ -726,6 +1200,36 @@ async function executeObservers(observers, name, data) {
|
|
|
726
1200
|
return true;
|
|
727
1201
|
}
|
|
728
1202
|
//#endregion
|
|
1203
|
+
//#region src/model-lifecycle.ts
|
|
1204
|
+
const events = {
|
|
1205
|
+
create: {
|
|
1206
|
+
before: ["creating", "saving"],
|
|
1207
|
+
after: ["created", "saved"]
|
|
1208
|
+
},
|
|
1209
|
+
update: {
|
|
1210
|
+
before: ["updating", "saving"],
|
|
1211
|
+
after: ["updated", "saved"]
|
|
1212
|
+
},
|
|
1213
|
+
delete: {
|
|
1214
|
+
before: ["deleting"],
|
|
1215
|
+
after: ["deleted"]
|
|
1216
|
+
}
|
|
1217
|
+
};
|
|
1218
|
+
function modelLifecycle(modelName, operation, hooks, observers, method = operation) {
|
|
1219
|
+
const observerList = observers?.slice();
|
|
1220
|
+
const { before: beforeEvents, after: afterEvents } = events[operation];
|
|
1221
|
+
return {
|
|
1222
|
+
async before(data) {
|
|
1223
|
+
for (const name of beforeEvents) if (!await executeHook(hooks, name, data)) throw new Error(`${modelName}.${method}() aborted by '${name}' hook.`);
|
|
1224
|
+
for (const name of beforeEvents) if (!await executeObservers(observerList, name, data)) throw new Error(`${modelName}.${method}() aborted by observer '${name}'.`);
|
|
1225
|
+
},
|
|
1226
|
+
async after(data) {
|
|
1227
|
+
for (const name of afterEvents) await executeHook(hooks, name, data);
|
|
1228
|
+
for (const name of afterEvents) await executeObservers(observerList, name, data);
|
|
1229
|
+
}
|
|
1230
|
+
};
|
|
1231
|
+
}
|
|
1232
|
+
//#endregion
|
|
729
1233
|
//#region src/ModelNotFoundException.ts
|
|
730
1234
|
/**
|
|
731
1235
|
* Thrown by findOrFail/firstOrFail. Carries `statusCode` 404 so exception
|
|
@@ -744,6 +1248,10 @@ var ModelNotFoundException = class extends Error {
|
|
|
744
1248
|
};
|
|
745
1249
|
//#endregion
|
|
746
1250
|
//#region src/QueryBuilder.ts
|
|
1251
|
+
const VALUELESS_OPERATOR_HELPERS = {
|
|
1252
|
+
"is null": "whereNull",
|
|
1253
|
+
"is not null": "whereNotNull"
|
|
1254
|
+
};
|
|
747
1255
|
/**
|
|
748
1256
|
* Fluent query builder for the Guren ORM. Thenable, so awaiting a builder
|
|
749
1257
|
* resolves to the result of `get()`.
|
|
@@ -778,8 +1286,10 @@ var QueryBuilder = class QueryBuilder {
|
|
|
778
1286
|
return this;
|
|
779
1287
|
}
|
|
780
1288
|
const field = fieldOrConditions;
|
|
781
|
-
if (arguments.length === 2)
|
|
782
|
-
|
|
1289
|
+
if (arguments.length === 2) {
|
|
1290
|
+
this.refuseOperatorAsValue("where", field, operatorOrValue);
|
|
1291
|
+
this.addSimpleCondition(field, Array.isArray(operatorOrValue) ? "in" : "=", operatorOrValue);
|
|
1292
|
+
} else this.addSimpleCondition(field, operatorOrValue, value);
|
|
783
1293
|
return this;
|
|
784
1294
|
}
|
|
785
1295
|
orWhere(fieldOrConditions, operatorOrValue, value) {
|
|
@@ -791,13 +1301,15 @@ var QueryBuilder = class QueryBuilder {
|
|
|
791
1301
|
if (typeof fieldOrConditions === "object" && fieldOrConditions !== null) orConditions.push(...this.simpleConditionsFrom(fieldOrConditions));
|
|
792
1302
|
else {
|
|
793
1303
|
const field = fieldOrConditions;
|
|
794
|
-
if (arguments.length === 2)
|
|
795
|
-
|
|
796
|
-
|
|
797
|
-
|
|
798
|
-
|
|
799
|
-
|
|
800
|
-
|
|
1304
|
+
if (arguments.length === 2) {
|
|
1305
|
+
this.refuseOperatorAsValue("orWhere", field, operatorOrValue);
|
|
1306
|
+
orConditions.push({
|
|
1307
|
+
type: "simple",
|
|
1308
|
+
field,
|
|
1309
|
+
operator: Array.isArray(operatorOrValue) ? "in" : "=",
|
|
1310
|
+
value: operatorOrValue
|
|
1311
|
+
});
|
|
1312
|
+
} else orConditions.push({
|
|
801
1313
|
type: "simple",
|
|
802
1314
|
field,
|
|
803
1315
|
operator: operatorOrValue,
|
|
@@ -991,7 +1503,8 @@ var QueryBuilder = class QueryBuilder {
|
|
|
991
1503
|
selectFromTable() {
|
|
992
1504
|
const fields = this.options.selectFields;
|
|
993
1505
|
const selection = fields && fields.length > 0 ? Object.fromEntries(fields.map((field) => [field, resolveColumn(this.table, field)])) : void 0;
|
|
994
|
-
|
|
1506
|
+
const query = this.resolveDrizzleDatabase().select(selection)?.from?.(this.table);
|
|
1507
|
+
return this.adapter.queueExecution?.(query, { trx: this.options.trx }) ?? query;
|
|
995
1508
|
}
|
|
996
1509
|
resolveDrizzleDatabase() {
|
|
997
1510
|
const advancedAdapter = this.adapter;
|
|
@@ -1069,22 +1582,39 @@ var QueryBuilder = class QueryBuilder {
|
|
|
1069
1582
|
* would be a supported way to bypass mass-assignment protection entirely.
|
|
1070
1583
|
*/
|
|
1071
1584
|
async [PREPARED_UPDATE](payload) {
|
|
1072
|
-
|
|
1073
|
-
|
|
1074
|
-
|
|
1075
|
-
|
|
1585
|
+
const adapter = this.assertWritable("update");
|
|
1586
|
+
if (typeof adapter.updateAdvanced === "function") return adapter.updateAdvanced(this.table, this.effectiveConditions(), payload, { trx: this.options.trx });
|
|
1587
|
+
return adapter.update(this.table, this.simpleWhereFor("update"), payload, { trx: this.options.trx });
|
|
1588
|
+
}
|
|
1589
|
+
/**
|
|
1590
|
+
* The object-where a basic adapter takes; a condition the flat object cannot
|
|
1591
|
+
* carry (an OR group, an operator, two values on one field) refuses rather
|
|
1592
|
+
* than writing with it dropped.
|
|
1593
|
+
*/
|
|
1594
|
+
simpleWhereFor(operation) {
|
|
1076
1595
|
const simpleWhere = this.toSimpleWhereClause();
|
|
1077
|
-
if (simpleWhere)
|
|
1078
|
-
|
|
1596
|
+
if (!simpleWhere) throw new Error(`Advanced conditions require an adapter that supports ${operation}Advanced.`);
|
|
1597
|
+
return simpleWhere;
|
|
1598
|
+
}
|
|
1599
|
+
/** Returns the adapter narrowed to the operation, so no call site needs a non-null assertion. */
|
|
1600
|
+
assertWritable(operation) {
|
|
1601
|
+
if (!this.adapter[operation]) throw new Error(`Configured adapter does not support ${operation} operations.`);
|
|
1602
|
+
this.assertWriteOptions();
|
|
1603
|
+
this.assertFiltersSurvived(operation);
|
|
1604
|
+
return this.adapter;
|
|
1605
|
+
}
|
|
1606
|
+
assertWriteOptions() {
|
|
1607
|
+
if (this.options.limitValue !== void 0 || this.options.offsetValue !== void 0 || this.options.orderBy.length > 0) throw new Error("Bulk writes do not support limit(), offset(), or orderBy(). Select the intended IDs first and write with whereIn().");
|
|
1079
1608
|
}
|
|
1080
1609
|
async delete() {
|
|
1081
|
-
|
|
1082
|
-
|
|
1083
|
-
|
|
1084
|
-
|
|
1085
|
-
|
|
1086
|
-
|
|
1087
|
-
|
|
1610
|
+
const model = this.modelClass;
|
|
1611
|
+
if (model[BULK_DELETE]) return model[BULK_DELETE](this);
|
|
1612
|
+
return this[PHYSICAL_DELETE]();
|
|
1613
|
+
}
|
|
1614
|
+
async [PHYSICAL_DELETE]() {
|
|
1615
|
+
const adapter = this.assertWritable("delete");
|
|
1616
|
+
if (typeof adapter.deleteAdvanced === "function") return adapter.deleteAdvanced(this.table, this.effectiveConditions(), { trx: this.options.trx });
|
|
1617
|
+
return adapter.delete(this.table, this.simpleWhereFor("delete"), { trx: this.options.trx });
|
|
1088
1618
|
}
|
|
1089
1619
|
/** Makes the builder awaitable, resolving to `get()`. */
|
|
1090
1620
|
then(onfulfilled, onrejected) {
|
|
@@ -1163,6 +1693,18 @@ var QueryBuilder = class QueryBuilder {
|
|
|
1163
1693
|
if (!this.filtersEvaporated()) return;
|
|
1164
1694
|
throw new Error(`${this.modelClass.name}: refusing to ${operation} unfiltered — every value in the where clause was undefined.`);
|
|
1165
1695
|
}
|
|
1696
|
+
/**
|
|
1697
|
+
* `where(field, 'is null')` type-checks through the `(field, value)` overload on
|
|
1698
|
+
* any string column and compiles to `field = 'is null'`, silently dropping the
|
|
1699
|
+
* NULL rows. A value-taking token (`'like'`) is left alone: it can be real data.
|
|
1700
|
+
*/
|
|
1701
|
+
refuseOperatorAsValue(method, field, value) {
|
|
1702
|
+
if (typeof value !== "string" || !Object.hasOwn(VALUELESS_OPERATOR_HELPERS, value)) return;
|
|
1703
|
+
const helper = `${VALUELESS_OPERATOR_HELPERS[value]}('${field}')`;
|
|
1704
|
+
const threeArgument = `${method}('${field}', '${value}', null)`;
|
|
1705
|
+
const fix = method === "where" ? `Use ${helper} or ${threeArgument}` : `Use ${threeArgument}, the OR form of ${helper}`;
|
|
1706
|
+
throw new Error(`${this.modelClass.name}: ${method}('${field}', '${value}') would compare ${field} to the string '${value}'. ${fix}; to match that string, write ${method}('${field}', '=', '${value}').`);
|
|
1707
|
+
}
|
|
1166
1708
|
addSimpleCondition(field, operator, value) {
|
|
1167
1709
|
this.conditions.push({
|
|
1168
1710
|
type: "simple",
|
|
@@ -1183,18 +1725,20 @@ var QueryBuilder = class QueryBuilder {
|
|
|
1183
1725
|
select: overrides.select ?? this.options.selectFields
|
|
1184
1726
|
}, { trx: this.options.trx });
|
|
1185
1727
|
const simpleWhere = this.toSimpleWhereClause();
|
|
1186
|
-
if (simpleWhere === null
|
|
1728
|
+
if (simpleWhere === null) throw new Error(`${this.modelClass.name}: this query uses conditions the configured adapter cannot express (it implements neither findManyAdvanced nor countAdvanced). Running it would drop every condition, including any global scope, and return unfiltered rows.`);
|
|
1187
1729
|
return this.adapter.findMany(this.table, {
|
|
1188
|
-
where: simpleWhere
|
|
1730
|
+
where: simpleWhere,
|
|
1189
1731
|
orderBy: orderBy.length > 0 ? orderBy : void 0,
|
|
1190
1732
|
limit,
|
|
1191
1733
|
offset
|
|
1192
1734
|
}, { trx: this.options.trx });
|
|
1193
1735
|
}
|
|
1194
|
-
/**
|
|
1736
|
+
/**
|
|
1737
|
+
* The flat object a basic adapter's WhereClause takes: `{}` for no conditions
|
|
1738
|
+
* at all, null when the conditions are too complex for it.
|
|
1739
|
+
*/
|
|
1195
1740
|
toSimpleWhereClause() {
|
|
1196
1741
|
const conditions = this.allConditions();
|
|
1197
|
-
if (conditions.length === 0) return null;
|
|
1198
1742
|
const result = {};
|
|
1199
1743
|
for (const condition of conditions) {
|
|
1200
1744
|
if (condition.type !== "simple") return null;
|
|
@@ -1246,24 +1790,41 @@ function serializeRecords(records, options) {
|
|
|
1246
1790
|
/**
|
|
1247
1791
|
* Thrown when mass assignment receives fields it must not write. Discarding
|
|
1248
1792
|
* them silently hides bugs and can mask injection attempts, so models throw.
|
|
1249
|
-
* `reason` is `'
|
|
1250
|
-
* `'
|
|
1793
|
+
* `reason` is `'denied'` for a field in `deniedFields()`, unassignable whatever
|
|
1794
|
+
* `fillable` says, and `'not-fillable'` for every other refusal: a field outside
|
|
1795
|
+
* `fillable`, or a `set` the allowlist does not admit (RFC 0031).
|
|
1251
1796
|
*/
|
|
1252
1797
|
var MassAssignmentException = class extends Error {
|
|
1253
1798
|
model;
|
|
1254
1799
|
fields;
|
|
1255
1800
|
reason;
|
|
1801
|
+
/**
|
|
1802
|
+
* `set` names the `create(data, { set })` rule that refused the fields and
|
|
1803
|
+
* only changes the message: `'no-fillable'` (the model declares no `fillable`),
|
|
1804
|
+
* `'id'`, `'fillable'` (a `set` key a request may already write) or
|
|
1805
|
+
* `'conflict'` (a key in both `data` and `set`).
|
|
1806
|
+
*/
|
|
1256
1807
|
constructor(model, fields, options) {
|
|
1257
1808
|
const reason = options?.reason ?? "not-fillable";
|
|
1809
|
+
const set = options && "set" in options ? options.set : void 0;
|
|
1258
1810
|
const list = fields.map((field) => `"${field}"`).join(", ");
|
|
1259
|
-
|
|
1260
|
-
super(`${model}: mass assignment blocked for field(s) ${list}. ${remediation} Never call forceCreate/forceUpdate with request input.`);
|
|
1811
|
+
super(`${model}: mass assignment blocked for field(s) ${list}. ${remediation(model, fields, reason, set)} Never pass request input to forceCreate/forceUpdate or spread it into set.`);
|
|
1261
1812
|
this.name = "MassAssignmentException";
|
|
1262
1813
|
this.model = model;
|
|
1263
1814
|
this.fields = fields;
|
|
1264
1815
|
this.reason = reason;
|
|
1265
1816
|
}
|
|
1266
1817
|
};
|
|
1818
|
+
function remediation(model, fields, reason, set) {
|
|
1819
|
+
if (reason === "denied") return `These are protected columns (e.g. credential fields) and can never be mass-assigned, not even through ${model}.fillable or set. Pass the plain input field (e.g. \`password\`) and let the model derive them, or use ${model}.forceCreate()/forceUpdate() for trusted server-side values such as \`passwordHash: 'oauth:...'\`.`;
|
|
1820
|
+
switch (set) {
|
|
1821
|
+
case "no-fillable": return `${model} declares no fillable, so every column is already writable through the data and set would keep nothing apart. Declare fillable with the columns a request may set.`;
|
|
1822
|
+
case "id": return `set cannot carry the primary key: a server-chosen id is a system write, which belongs in ${model}.forceCreate().`;
|
|
1823
|
+
case "fillable": return `They are in ${model}.fillable, so a request may already set them: pass them in the data. A column the server sets must not be fillable, or every other write would accept it from a request.`;
|
|
1824
|
+
case "conflict": return `They are set by the server in this call, so they must not also arrive in the data.`;
|
|
1825
|
+
default: return `Add them to fillable if a request may set them; if the server chooses the value, name it in the set option of ${model}.create() or ${model}.update(): { set: { ${fields.join(", ")} } }.`;
|
|
1826
|
+
}
|
|
1827
|
+
}
|
|
1267
1828
|
//#endregion
|
|
1268
1829
|
//#region src/Model.ts
|
|
1269
1830
|
/**
|
|
@@ -1297,9 +1858,9 @@ var Model = class Model {
|
|
|
1297
1858
|
/**
|
|
1298
1859
|
* Mass-assignment allowlist. When set, any other key in `create()`/`update()`
|
|
1299
1860
|
* input throws a MassAssignmentException rather than being discarded, so
|
|
1300
|
-
* bugs and injection attempts surface
|
|
1301
|
-
*
|
|
1302
|
-
* `deniedFields()` always throws.
|
|
1861
|
+
* bugs and injection attempts surface. A column the server chooses goes in
|
|
1862
|
+
* `set`, and must stay out of this list. Independent of it, `id` is always
|
|
1863
|
+
* stripped and `deniedFields()` always throws.
|
|
1303
1864
|
*/
|
|
1304
1865
|
static fillable;
|
|
1305
1866
|
/**
|
|
@@ -1339,10 +1900,11 @@ var Model = class Model {
|
|
|
1339
1900
|
}
|
|
1340
1901
|
/** A model scope that forwards `trx` to every query and write on it. */
|
|
1341
1902
|
static inTransaction(trx) {
|
|
1342
|
-
const where = (
|
|
1903
|
+
const where = (...args) => {
|
|
1904
|
+
const [fieldOrConditions, operatorOrValue, value] = args;
|
|
1343
1905
|
if (typeof fieldOrConditions === "function") return this.newQuery({ trx }).where(fieldOrConditions);
|
|
1344
1906
|
if (typeof fieldOrConditions === "object" && fieldOrConditions !== null) return this.newQuery({ trx }).where(fieldOrConditions);
|
|
1345
|
-
if (
|
|
1907
|
+
if (args.length === 3) return this.newQuery({ trx }).where(fieldOrConditions, operatorOrValue, value);
|
|
1346
1908
|
return this.newQuery({ trx }).where(fieldOrConditions, operatorOrValue);
|
|
1347
1909
|
};
|
|
1348
1910
|
return {
|
|
@@ -1353,8 +1915,14 @@ var Model = class Model {
|
|
|
1353
1915
|
first: (where) => this.first(where, { trx }),
|
|
1354
1916
|
where,
|
|
1355
1917
|
newQuery: () => this.newQuery({ trx }),
|
|
1356
|
-
create: (data) => this.create(data, {
|
|
1357
|
-
|
|
1918
|
+
create: ((data, options) => this.create(data, {
|
|
1919
|
+
...options,
|
|
1920
|
+
trx
|
|
1921
|
+
})),
|
|
1922
|
+
update: ((where, data, options) => this.update(where, data, {
|
|
1923
|
+
...options,
|
|
1924
|
+
trx
|
|
1925
|
+
})),
|
|
1358
1926
|
delete: (where) => this.delete(where, { trx }),
|
|
1359
1927
|
paginate: (options) => this.paginate(options, { trx })
|
|
1360
1928
|
};
|
|
@@ -1396,9 +1964,8 @@ var Model = class Model {
|
|
|
1396
1964
|
return new QueryBuilder(this, queryOptions);
|
|
1397
1965
|
}
|
|
1398
1966
|
/**
|
|
1399
|
-
*
|
|
1400
|
-
*
|
|
1401
|
-
* still in scope.
|
|
1967
|
+
* Ahead of the `updating`/`deleting` hooks, which must not fire for a write
|
|
1968
|
+
* that is refused; the builder repeats the check for its own callers.
|
|
1402
1969
|
*/
|
|
1403
1970
|
static assertFiltersSurvived(where, operation) {
|
|
1404
1971
|
if (!everyFilterDropped(where)) return;
|
|
@@ -1449,25 +2016,43 @@ var Model = class Model {
|
|
|
1449
2016
|
return records.map((record) => this.applyReadTransforms(record));
|
|
1450
2017
|
}
|
|
1451
2018
|
/**
|
|
1452
|
-
* In order: `
|
|
1453
|
-
*
|
|
1454
|
-
*
|
|
2019
|
+
* In order: a non-empty `set` is refused without `fillable`, or holding `id`,
|
|
2020
|
+
* a denied or a fillable key (RFC 0031); `deniedFields()` throws, checked on
|
|
2021
|
+
* the raw input so no later rule can swallow them; `id` is stripped silently;
|
|
2022
|
+
* then, with `fillable` set, anything outside it throws. `set` is merged last.
|
|
1455
2023
|
*/
|
|
1456
|
-
static filterFillable(data) {
|
|
1457
|
-
const
|
|
2024
|
+
static filterFillable(data, set) {
|
|
2025
|
+
const fillableFields = this.fillable;
|
|
2026
|
+
const deniedFields = this.deniedFields();
|
|
2027
|
+
const setKeys = set ? Object.keys(set) : [];
|
|
2028
|
+
if (setKeys.length > 0) this.assertSettable(setKeys, fillableFields, deniedFields);
|
|
2029
|
+
const denied = deniedFields.filter((field) => field in data);
|
|
1458
2030
|
if (denied.length > 0) throw new MassAssignmentException(this.name, denied, { reason: "denied" });
|
|
1459
2031
|
let candidate = data;
|
|
1460
2032
|
if ("id" in candidate) {
|
|
1461
2033
|
const { id: _id, ...rest } = candidate;
|
|
1462
2034
|
candidate = rest;
|
|
1463
2035
|
}
|
|
1464
|
-
const fillableFields = this.fillable;
|
|
1465
2036
|
if (!fillableFields) return candidate;
|
|
1466
2037
|
const blocked = Object.keys(candidate).filter((key) => !fillableFields.includes(key));
|
|
1467
|
-
if (blocked.length > 0)
|
|
2038
|
+
if (blocked.length > 0) {
|
|
2039
|
+
const alsoSet = blocked.filter((key) => setKeys.includes(key));
|
|
2040
|
+
throw alsoSet.length > 0 ? new MassAssignmentException(this.name, alsoSet, { set: "conflict" }) : new MassAssignmentException(this.name, blocked);
|
|
2041
|
+
}
|
|
1468
2042
|
const filtered = {};
|
|
1469
2043
|
for (const key of fillableFields) if (key in candidate) filtered[key] = candidate[key];
|
|
1470
|
-
return
|
|
2044
|
+
return setKeys.length > 0 ? {
|
|
2045
|
+
...filtered,
|
|
2046
|
+
...set
|
|
2047
|
+
} : filtered;
|
|
2048
|
+
}
|
|
2049
|
+
static assertSettable(keys, fillableFields, deniedFields) {
|
|
2050
|
+
if (!fillableFields) throw new MassAssignmentException(this.name, keys, { set: "no-fillable" });
|
|
2051
|
+
if (keys.includes("id")) throw new MassAssignmentException(this.name, ["id"], { set: "id" });
|
|
2052
|
+
const denied = keys.filter((key) => deniedFields.includes(key));
|
|
2053
|
+
if (denied.length > 0) throw new MassAssignmentException(this.name, denied, { reason: "denied" });
|
|
2054
|
+
const fillable = keys.filter((key) => fillableFields.includes(key));
|
|
2055
|
+
if (fillable.length > 0) throw new MassAssignmentException(this.name, fillable, { set: "fillable" });
|
|
1471
2056
|
}
|
|
1472
2057
|
static async preparePersistencePayload(data) {
|
|
1473
2058
|
let result = { ...data };
|
|
@@ -1523,7 +2108,7 @@ var Model = class Model {
|
|
|
1523
2108
|
}
|
|
1524
2109
|
static async find(id, key = "id", queryOptions) {
|
|
1525
2110
|
if (id === void 0) return null;
|
|
1526
|
-
if (this.hasScopes()) return this.newQuery(queryOptions).where(key
|
|
2111
|
+
if (this.hasScopes()) return this.newQuery(queryOptions).where({ [key]: id }).first();
|
|
1527
2112
|
const table = this.resolveTable();
|
|
1528
2113
|
const where = { [key]: id };
|
|
1529
2114
|
const record = await this.getAdapter().findUnique(table, where, queryOptions);
|
|
@@ -1771,100 +2356,69 @@ var Model = class Model {
|
|
|
1771
2356
|
perPage: options.perPage
|
|
1772
2357
|
});
|
|
1773
2358
|
}
|
|
1774
|
-
static async create(data,
|
|
1775
|
-
return this.runCreate(data,
|
|
2359
|
+
static async create(data, options) {
|
|
2360
|
+
if (options?.set === void 0) return this.runCreate(data, options, true);
|
|
2361
|
+
const { set, ...writeOptions } = options;
|
|
2362
|
+
return this.runCreate(data, writeOptions, true, set);
|
|
1776
2363
|
}
|
|
1777
2364
|
/**
|
|
1778
|
-
* Create bypassing mass-assignment protection.
|
|
1779
|
-
* (OAuth linking, seeders, system records)
|
|
2365
|
+
* Create bypassing mass-assignment protection. Data that carries nothing from
|
|
2366
|
+
* the request only (OAuth linking, seeders, system records); a server-chosen
|
|
2367
|
+
* column next to request data goes in `create(data, { set })`.
|
|
1780
2368
|
*/
|
|
1781
2369
|
static async forceCreate(data, writeOptions) {
|
|
1782
2370
|
return this.runCreate(data, writeOptions, false);
|
|
1783
2371
|
}
|
|
1784
|
-
static async runCreate(data, writeOptions, applyFillable) {
|
|
2372
|
+
static async runCreate(data, writeOptions, applyFillable, set) {
|
|
1785
2373
|
const table = this.resolveTable();
|
|
1786
|
-
const filtered = applyFillable ? this.filterFillable(data) : { ...data };
|
|
2374
|
+
const filtered = applyFillable ? this.filterFillable(data, set) : { ...data };
|
|
1787
2375
|
const payload = await this.preparePersistencePayload(filtered);
|
|
1788
|
-
const
|
|
1789
|
-
|
|
1790
|
-
if (hooks) {
|
|
1791
|
-
if (!await executeHook(hooks, "creating", payload)) throw new Error(`${this.name}.create() aborted by 'creating' hook.`);
|
|
1792
|
-
if (!await executeHook(hooks, "saving", payload)) throw new Error(`${this.name}.create() aborted by 'saving' hook.`);
|
|
1793
|
-
}
|
|
1794
|
-
if (observers) {
|
|
1795
|
-
if (!await executeObservers(observers, "creating", payload)) throw new Error(`${this.name}.create() aborted by observer 'creating'.`);
|
|
1796
|
-
if (!await executeObservers(observers, "saving", payload)) throw new Error(`${this.name}.create() aborted by observer 'saving'.`);
|
|
1797
|
-
}
|
|
2376
|
+
const lifecycle = modelLifecycle(this.name, "create", this.hooks, this.observers);
|
|
2377
|
+
await lifecycle.before(payload);
|
|
1798
2378
|
const result = await this.getAdapter().create(table, payload, writeOptions);
|
|
1799
|
-
|
|
1800
|
-
const resultData = result;
|
|
1801
|
-
await executeHook(hooks, "created", resultData);
|
|
1802
|
-
await executeHook(hooks, "saved", resultData);
|
|
1803
|
-
}
|
|
1804
|
-
if (observers) {
|
|
1805
|
-
const resultData = result;
|
|
1806
|
-
await executeObservers(observers, "created", resultData);
|
|
1807
|
-
await executeObservers(observers, "saved", resultData);
|
|
1808
|
-
}
|
|
2379
|
+
await lifecycle.after(result);
|
|
1809
2380
|
return this.applyReadTransforms(result);
|
|
1810
2381
|
}
|
|
1811
|
-
static async update(where, data,
|
|
1812
|
-
return this.runUpdate(where, data,
|
|
2382
|
+
static async update(where, data, options) {
|
|
2383
|
+
if (options?.set === void 0) return this.runUpdate(where, data, options, true);
|
|
2384
|
+
const { set, ...writeOptions } = options;
|
|
2385
|
+
return this.runUpdate(where, data, writeOptions, true, set);
|
|
1813
2386
|
}
|
|
1814
2387
|
/**
|
|
1815
|
-
* Update bypassing mass-assignment protection.
|
|
1816
|
-
*
|
|
2388
|
+
* Update bypassing mass-assignment protection. Data that carries nothing from
|
|
2389
|
+
* the request only; a server-chosen column next to request data goes in
|
|
2390
|
+
* `update(where, data, { set })`.
|
|
1817
2391
|
*/
|
|
1818
2392
|
static async forceUpdate(where, data, writeOptions) {
|
|
1819
2393
|
return this.runUpdate(where, data, writeOptions, false);
|
|
1820
2394
|
}
|
|
1821
|
-
static async runUpdate(where, data, writeOptions, applyFillable) {
|
|
1822
|
-
|
|
1823
|
-
const adapter = this.getAdapter();
|
|
1824
|
-
if (!adapter.update) throw new Error("Configured adapter does not support update operations.");
|
|
2395
|
+
static async runUpdate(where, data, writeOptions, applyFillable, set) {
|
|
2396
|
+
if (!this.getAdapter().update) throw new Error("Configured adapter does not support update operations.");
|
|
1825
2397
|
this.assertFiltersSurvived(where, "update");
|
|
1826
|
-
const filtered = applyFillable ? this.filterFillable(data) : { ...data };
|
|
2398
|
+
const filtered = applyFillable ? this.filterFillable(data, set) : { ...data };
|
|
1827
2399
|
const payload = await this.preparePersistencePayload(filtered);
|
|
1828
|
-
const
|
|
1829
|
-
|
|
1830
|
-
|
|
1831
|
-
|
|
1832
|
-
if (!await executeHook(hooks, "saving", payload)) throw new Error(`${this.name}.update() aborted by 'saving' hook.`);
|
|
1833
|
-
}
|
|
1834
|
-
if (observers) {
|
|
1835
|
-
if (!await executeObservers(observers, "updating", payload)) throw new Error(`${this.name}.update() aborted by observer 'updating'.`);
|
|
1836
|
-
if (!await executeObservers(observers, "saving", payload)) throw new Error(`${this.name}.update() aborted by observer 'saving'.`);
|
|
1837
|
-
}
|
|
1838
|
-
const result = this.hasScopes() ? await this.newQuery(writeOptions).where(where)[PREPARED_UPDATE](payload) : await adapter.update(table, where, payload, writeOptions);
|
|
1839
|
-
if (hooks) {
|
|
1840
|
-
const resultData = result;
|
|
1841
|
-
await executeHook(hooks, "updated", resultData);
|
|
1842
|
-
await executeHook(hooks, "saved", resultData);
|
|
1843
|
-
}
|
|
1844
|
-
if (observers) {
|
|
1845
|
-
const resultData = result;
|
|
1846
|
-
await executeObservers(observers, "updated", resultData);
|
|
1847
|
-
await executeObservers(observers, "saved", resultData);
|
|
1848
|
-
}
|
|
2400
|
+
const lifecycle = modelLifecycle(this.name, "update", this.hooks, this.observers);
|
|
2401
|
+
await lifecycle.before(payload);
|
|
2402
|
+
const result = await this.newQuery(writeOptions).where(where)[PREPARED_UPDATE](payload);
|
|
2403
|
+
await lifecycle.after(result);
|
|
1849
2404
|
return this.applyReadTransforms(result);
|
|
1850
2405
|
}
|
|
1851
2406
|
static async delete(where, writeOptions) {
|
|
1852
|
-
|
|
1853
|
-
|
|
1854
|
-
|
|
2407
|
+
if (!this.getAdapter().delete) throw new Error("Configured adapter does not support delete operations.");
|
|
2408
|
+
return this[LIFECYCLE_DELETE](where, "delete", () => this.newQuery(writeOptions).where(where).delete());
|
|
2409
|
+
}
|
|
2410
|
+
/**
|
|
2411
|
+
* Runs `write` between the `deleting` and `deleted` events, for `delete()`
|
|
2412
|
+
* and the SoftDeletes overrides. Symbol-keyed and kept out of the package
|
|
2413
|
+
* entry point; each caller checks its own adapter capability first.
|
|
2414
|
+
*/
|
|
2415
|
+
static async [LIFECYCLE_DELETE](where, method, write) {
|
|
1855
2416
|
this.assertFiltersSurvived(where, "delete");
|
|
1856
|
-
const
|
|
1857
|
-
const observers = this.observers;
|
|
2417
|
+
const lifecycle = modelLifecycle(this.name, "delete", this.hooks, this.observers, method);
|
|
1858
2418
|
const whereData = where;
|
|
1859
|
-
|
|
1860
|
-
|
|
1861
|
-
|
|
1862
|
-
if (observers) {
|
|
1863
|
-
if (!await executeObservers(observers, "deleting", whereData)) throw new Error(`${this.name}.delete() aborted by observer 'deleting'.`);
|
|
1864
|
-
}
|
|
1865
|
-
const result = this.hasScopes() ? await this.newQuery(writeOptions).where(where).delete() : await adapter.delete(table, where, writeOptions);
|
|
1866
|
-
if (hooks) await executeHook(hooks, "deleted", whereData);
|
|
1867
|
-
if (observers) await executeObservers(observers, "deleted", whereData);
|
|
2419
|
+
await lifecycle.before(whereData);
|
|
2420
|
+
const result = await write();
|
|
2421
|
+
await lifecycle.after(whereData);
|
|
1868
2422
|
return result;
|
|
1869
2423
|
}
|
|
1870
2424
|
/**
|
|
@@ -1928,17 +2482,7 @@ var Model = class Model {
|
|
|
1928
2482
|
*/
|
|
1929
2483
|
static async loadRelationsInto(records, relationNames, queryOptions, constraints, pathPrefix = "") {
|
|
1930
2484
|
if (relationNames.length === 0) return;
|
|
1931
|
-
const
|
|
1932
|
-
for (const path of relationNames) {
|
|
1933
|
-
const [head, ...rest] = path.split(".");
|
|
1934
|
-
const tails = groups.get(head) ?? [];
|
|
1935
|
-
groups.set(head, tails);
|
|
1936
|
-
if (rest.length > 0) {
|
|
1937
|
-
const tail = rest.join(".");
|
|
1938
|
-
if (!tails.includes(tail)) tails.push(tail);
|
|
1939
|
-
}
|
|
1940
|
-
}
|
|
1941
|
-
for (const [head, tails] of groups) await this.loadRelationLevel(records, head, tails, queryOptions, constraints, pathPrefix);
|
|
2485
|
+
for (const [head, tails] of groupRelationPaths(relationNames)) await this.loadRelationLevel(records, head, tails, queryOptions, constraints, pathPrefix);
|
|
1942
2486
|
}
|
|
1943
2487
|
/**
|
|
1944
2488
|
* @internal Public because generated code reaches it; internal callers should
|
|
@@ -1979,333 +2523,40 @@ var Model = class Model {
|
|
|
1979
2523
|
break;
|
|
1980
2524
|
case "morphTo": await this.loadMorphTo(records, definition, queryOptions, constraint);
|
|
1981
2525
|
}
|
|
1982
|
-
|
|
1983
|
-
|
|
1984
|
-
|
|
1985
|
-
|
|
1986
|
-
|
|
1987
|
-
|
|
1988
|
-
|
|
1989
|
-
|
|
1990
|
-
|
|
1991
|
-
|
|
1992
|
-
|
|
1993
|
-
}
|
|
1994
|
-
if (children.length === 0) return;
|
|
1995
|
-
const related = await resolveModelReference(definition.related);
|
|
1996
|
-
if (tails.length > 0) await related.loadRelationsInto(children, tails, queryOptions, constraints, currentPath);
|
|
1997
|
-
applyRelatedReadTransforms(related, children, projected);
|
|
2526
|
+
await loadRelationChildren({
|
|
2527
|
+
modelName: this.name,
|
|
2528
|
+
records,
|
|
2529
|
+
definition,
|
|
2530
|
+
head,
|
|
2531
|
+
tails,
|
|
2532
|
+
projected,
|
|
2533
|
+
currentPath,
|
|
2534
|
+
queryOptions,
|
|
2535
|
+
constraints
|
|
2536
|
+
});
|
|
1998
2537
|
}
|
|
1999
2538
|
static async loadHasMany(records, definition, queryOptions, constraint) {
|
|
2000
|
-
|
|
2001
|
-
return loadRelationData(records, name, await resolveModelReference(definition.related), localKey, foreignKey, true, queryOptions, constraint);
|
|
2539
|
+
return loadHasMany(records, definition, queryOptions, constraint);
|
|
2002
2540
|
}
|
|
2003
2541
|
static async loadHasOne(records, definition, queryOptions, constraint) {
|
|
2004
|
-
|
|
2005
|
-
return loadRelationData(records, name, await resolveModelReference(definition.related), localKey, foreignKey, false, queryOptions, constraint);
|
|
2542
|
+
return loadHasOne(records, definition, queryOptions, constraint);
|
|
2006
2543
|
}
|
|
2007
2544
|
static async loadBelongsTo(records, definition, queryOptions, constraint) {
|
|
2008
|
-
|
|
2009
|
-
return loadRelationData(records, name, await resolveModelReference(definition.related), foreignKey, ownerKey, false, queryOptions, constraint);
|
|
2545
|
+
return loadBelongsTo(records, definition, queryOptions, constraint);
|
|
2010
2546
|
}
|
|
2011
2547
|
static async loadBelongsToMany(records, definition, queryOptions, constraint) {
|
|
2012
|
-
|
|
2013
|
-
const related = await resolveModelReference(definition.related);
|
|
2014
|
-
const parentValues = distinctKeys(records, parentKey);
|
|
2015
|
-
if (parentValues.length === 0) {
|
|
2016
|
-
for (const record of records) record[name] = [];
|
|
2017
|
-
return false;
|
|
2018
|
-
}
|
|
2019
|
-
const adapter = this.getAdapter();
|
|
2020
|
-
const pivotRows = await loadByChunks(parentValues, maxInListSize(adapter), (chunk) => adapter.findMany(pivotTable, { where: { [foreignPivotKey]: chunk } }, queryOptions));
|
|
2021
|
-
const pivotMap = /* @__PURE__ */ new Map();
|
|
2022
|
-
const allRelatedIds = /* @__PURE__ */ new Set();
|
|
2023
|
-
for (const row of pivotRows) {
|
|
2024
|
-
const fk = row[foreignPivotKey];
|
|
2025
|
-
const rk = row[relatedPivotKey];
|
|
2026
|
-
if (!pivotMap.has(fk)) pivotMap.set(fk, []);
|
|
2027
|
-
pivotMap.get(fk).push(rk);
|
|
2028
|
-
allRelatedIds.add(rk);
|
|
2029
|
-
}
|
|
2030
|
-
if (allRelatedIds.size === 0) {
|
|
2031
|
-
for (const record of records) record[name] = [];
|
|
2032
|
-
return false;
|
|
2033
|
-
}
|
|
2034
|
-
const { records: relatedRecords, projected } = await loadRelatedRecords(related, Array.from(allRelatedIds), (chunk) => ({ [relatedKey]: chunk }), queryOptions, constraint);
|
|
2035
|
-
const relatedMap = /* @__PURE__ */ new Map();
|
|
2036
|
-
for (const item of relatedRecords) relatedMap.set(item[relatedKey], { ...item });
|
|
2037
|
-
for (const record of records) {
|
|
2038
|
-
const pk = record[parentKey];
|
|
2039
|
-
if (pk == null) {
|
|
2040
|
-
record[name] = [];
|
|
2041
|
-
continue;
|
|
2042
|
-
}
|
|
2043
|
-
record[name] = (pivotMap.get(pk) ?? []).map((id) => relatedMap.get(id)).filter((item) => item != null);
|
|
2044
|
-
}
|
|
2045
|
-
return projected;
|
|
2548
|
+
return loadBelongsToMany(this, records, definition, queryOptions, constraint);
|
|
2046
2549
|
}
|
|
2047
2550
|
static async loadHasManyThrough(records, definition, queryOptions, constraint) {
|
|
2048
|
-
|
|
2049
|
-
const related = await resolveModelReference(definition.related);
|
|
2050
|
-
const through = await resolveModelReference(definition.through);
|
|
2051
|
-
const localValues = distinctKeys(records, localKey);
|
|
2052
|
-
if (localValues.length === 0) {
|
|
2053
|
-
for (const record of records) record[name] = [];
|
|
2054
|
-
return false;
|
|
2055
|
-
}
|
|
2056
|
-
const throughRecords = await loadByChunks(localValues, maxInListSize(through.getAdapter()), (chunk) => through.newQuery(queryOptions).where({ [firstKey]: chunk })[RAW_RESULTS]());
|
|
2057
|
-
const throughMap = /* @__PURE__ */ new Map();
|
|
2058
|
-
const allThroughIds = /* @__PURE__ */ new Set();
|
|
2059
|
-
for (const row of throughRecords) {
|
|
2060
|
-
const fk = row[firstKey];
|
|
2061
|
-
const tk = row[secondLocalKey];
|
|
2062
|
-
if (!throughMap.has(fk)) throughMap.set(fk, []);
|
|
2063
|
-
throughMap.get(fk).push(tk);
|
|
2064
|
-
allThroughIds.add(tk);
|
|
2065
|
-
}
|
|
2066
|
-
if (allThroughIds.size === 0) {
|
|
2067
|
-
for (const record of records) record[name] = [];
|
|
2068
|
-
return false;
|
|
2069
|
-
}
|
|
2070
|
-
const { records: relatedRecords, projected } = await loadRelatedRecords(related, Array.from(allThroughIds), (chunk) => ({ [secondKey]: chunk }), queryOptions, constraint);
|
|
2071
|
-
const relatedByKey = /* @__PURE__ */ new Map();
|
|
2072
|
-
for (const item of relatedRecords) {
|
|
2073
|
-
const key = item[secondKey];
|
|
2074
|
-
if (!relatedByKey.has(key)) relatedByKey.set(key, []);
|
|
2075
|
-
relatedByKey.get(key).push({ ...item });
|
|
2076
|
-
}
|
|
2077
|
-
for (const record of records) {
|
|
2078
|
-
const lk = record[localKey];
|
|
2079
|
-
if (lk == null) {
|
|
2080
|
-
record[name] = [];
|
|
2081
|
-
continue;
|
|
2082
|
-
}
|
|
2083
|
-
const throughIds = throughMap.get(lk) ?? [];
|
|
2084
|
-
const items = [];
|
|
2085
|
-
for (const tid of throughIds) {
|
|
2086
|
-
const matched = relatedByKey.get(tid) ?? [];
|
|
2087
|
-
items.push(...matched);
|
|
2088
|
-
}
|
|
2089
|
-
record[name] = items;
|
|
2090
|
-
}
|
|
2091
|
-
return projected;
|
|
2551
|
+
return loadHasManyThrough(records, definition, queryOptions, constraint);
|
|
2092
2552
|
}
|
|
2093
2553
|
static async loadMorphMany(records, definition, queryOptions, constraint) {
|
|
2094
|
-
|
|
2095
|
-
const related = await resolveModelReference(definition.related);
|
|
2096
|
-
const typeColumn = `${morphName}Type`;
|
|
2097
|
-
const idColumn = `${morphName}Id`;
|
|
2098
|
-
const parentType = this.name;
|
|
2099
|
-
const localValues = distinctKeys(records, localKey);
|
|
2100
|
-
if (localValues.length === 0) {
|
|
2101
|
-
for (const record of records) record[name] = [];
|
|
2102
|
-
return false;
|
|
2103
|
-
}
|
|
2104
|
-
const { records: allRelated, projected } = await loadRelatedRecords(related, localValues, (chunk) => ({
|
|
2105
|
-
[typeColumn]: parentType,
|
|
2106
|
-
[idColumn]: chunk
|
|
2107
|
-
}), queryOptions, constraint);
|
|
2108
|
-
const map = /* @__PURE__ */ new Map();
|
|
2109
|
-
for (const item of allRelated) {
|
|
2110
|
-
if (item[typeColumn] !== parentType) continue;
|
|
2111
|
-
const key = item[idColumn];
|
|
2112
|
-
if (!map.has(key)) map.set(key, []);
|
|
2113
|
-
map.get(key).push({ ...item });
|
|
2114
|
-
}
|
|
2115
|
-
for (const record of records) {
|
|
2116
|
-
const key = record[localKey];
|
|
2117
|
-
record[name] = key != null ? map.get(key) ?? [] : [];
|
|
2118
|
-
}
|
|
2119
|
-
return projected;
|
|
2554
|
+
return loadMorphMany(this, records, definition, queryOptions, constraint);
|
|
2120
2555
|
}
|
|
2121
2556
|
static async loadMorphTo(records, definition, queryOptions, constraint) {
|
|
2122
|
-
|
|
2123
|
-
const typeColumn = `${morphName}Type`;
|
|
2124
|
-
const idColumn = `${morphName}Id`;
|
|
2125
|
-
const morphMap = Model.morphMap ?? {};
|
|
2126
|
-
const byType = /* @__PURE__ */ new Map();
|
|
2127
|
-
for (const record of records) {
|
|
2128
|
-
const type = record[typeColumn];
|
|
2129
|
-
const id = record[idColumn];
|
|
2130
|
-
if (!type || id == null) continue;
|
|
2131
|
-
if (!byType.has(type)) byType.set(type, []);
|
|
2132
|
-
byType.get(type).push(id);
|
|
2133
|
-
}
|
|
2134
|
-
const resolved = /* @__PURE__ */ new Map();
|
|
2135
|
-
for (const [type, ids] of byType) {
|
|
2136
|
-
const modelClass = morphMap[type];
|
|
2137
|
-
if (!modelClass) continue;
|
|
2138
|
-
const { records: results, projected } = await loadRelatedRecords(modelClass, Array.from(new Set(ids)), (chunk) => ({ id: chunk }), queryOptions, constraint);
|
|
2139
|
-
const idMap = /* @__PURE__ */ new Map();
|
|
2140
|
-
for (const r of results) idMap.set(r.id, { ...r });
|
|
2141
|
-
applyRelatedReadTransforms(modelClass, Array.from(idMap.values()), projected);
|
|
2142
|
-
resolved.set(type, idMap);
|
|
2143
|
-
}
|
|
2144
|
-
for (const record of records) {
|
|
2145
|
-
const type = record[typeColumn];
|
|
2146
|
-
const id = record[idColumn];
|
|
2147
|
-
if (!type || id == null) {
|
|
2148
|
-
record[name] = null;
|
|
2149
|
-
continue;
|
|
2150
|
-
}
|
|
2151
|
-
record[name] = resolved.get(type)?.get(id) ?? null;
|
|
2152
|
-
}
|
|
2557
|
+
return loadMorphTo(Model.morphMap ?? {}, records, definition, queryOptions, constraint);
|
|
2153
2558
|
}
|
|
2154
2559
|
};
|
|
2155
|
-
/** The cast switch, written onto `target`. */
|
|
2156
|
-
function castInPlace(target, castDefs) {
|
|
2157
|
-
for (const [field, castType] of Object.entries(castDefs)) {
|
|
2158
|
-
if (!(field in target)) continue;
|
|
2159
|
-
const value = target[field];
|
|
2160
|
-
if (value == null) continue;
|
|
2161
|
-
switch (castType) {
|
|
2162
|
-
case "json":
|
|
2163
|
-
if (typeof value === "string") try {
|
|
2164
|
-
target[field] = JSON.parse(value);
|
|
2165
|
-
} catch {}
|
|
2166
|
-
break;
|
|
2167
|
-
case "date":
|
|
2168
|
-
if (!(value instanceof Date)) target[field] = new Date(value);
|
|
2169
|
-
break;
|
|
2170
|
-
case "boolean":
|
|
2171
|
-
target[field] = Boolean(value);
|
|
2172
|
-
break;
|
|
2173
|
-
case "number":
|
|
2174
|
-
target[field] = Number(value);
|
|
2175
|
-
break;
|
|
2176
|
-
case "string": target[field] = String(value);
|
|
2177
|
-
}
|
|
2178
|
-
}
|
|
2179
|
-
}
|
|
2180
|
-
/**
|
|
2181
|
-
* Written onto the records rather than onto copies: the parent rows hold them
|
|
2182
|
-
* by reference, and a nested loader has already keyed its own rows on them.
|
|
2183
|
-
* Keep in step with `[READ_TRANSFORMS]`: same casts-then-accessors order, and
|
|
2184
|
-
* the same rule that `projected` rows (a constraint's `select()` narrowed them)
|
|
2185
|
-
* skip the accessors, which would read a column that is not on them.
|
|
2186
|
-
*/
|
|
2187
|
-
function applyRelatedReadTransforms(related, records, projected) {
|
|
2188
|
-
const casts = related.casts;
|
|
2189
|
-
const accessors = projected ? void 0 : related.accessors;
|
|
2190
|
-
if (!casts && !accessors) return;
|
|
2191
|
-
for (const record of records) {
|
|
2192
|
-
if (casts) castInPlace(record, casts);
|
|
2193
|
-
if (accessors) applyAccessorsInPlace(record, accessors);
|
|
2194
|
-
}
|
|
2195
|
-
}
|
|
2196
|
-
async function loadRelationData(records, name, related, parentKey, relatedKey, isArray, queryOptions, constraint) {
|
|
2197
|
-
const values = distinctKeys(records, parentKey);
|
|
2198
|
-
if (values.length === 0) {
|
|
2199
|
-
for (const record of records) record[name] = isArray ? [] : null;
|
|
2200
|
-
return false;
|
|
2201
|
-
}
|
|
2202
|
-
const { records: relatedRecords, projected } = await loadRelatedRecords(related, values, (chunk) => ({ [relatedKey]: chunk }), queryOptions, constraint);
|
|
2203
|
-
const map = /* @__PURE__ */ new Map();
|
|
2204
|
-
for (const item of relatedRecords) {
|
|
2205
|
-
const key = item[relatedKey];
|
|
2206
|
-
if (isArray) {
|
|
2207
|
-
if (!map.has(key)) map.set(key, []);
|
|
2208
|
-
map.get(key).push({ ...item });
|
|
2209
|
-
} else map.set(key, { ...item });
|
|
2210
|
-
}
|
|
2211
|
-
for (const record of records) {
|
|
2212
|
-
const key = record[parentKey];
|
|
2213
|
-
if (key == null) {
|
|
2214
|
-
record[name] = isArray ? [] : null;
|
|
2215
|
-
continue;
|
|
2216
|
-
}
|
|
2217
|
-
record[name] = map.get(key) ?? (isArray ? [] : null);
|
|
2218
|
-
}
|
|
2219
|
-
return projected;
|
|
2220
|
-
}
|
|
2221
|
-
function maxInListSize(adapter) {
|
|
2222
|
-
const size = adapter.maxInListSize?.();
|
|
2223
|
-
return typeof size === "number" && size >= 1 ? Math.floor(size) : 500;
|
|
2224
|
-
}
|
|
2225
|
-
function relationCountPlan(definition, parentType) {
|
|
2226
|
-
switch (definition.type) {
|
|
2227
|
-
case "hasMany":
|
|
2228
|
-
case "hasOne": return {
|
|
2229
|
-
related: definition.related,
|
|
2230
|
-
parentKey: definition.localKey,
|
|
2231
|
-
childKey: definition.foreignKey,
|
|
2232
|
-
where: {},
|
|
2233
|
-
presenceOnly: false
|
|
2234
|
-
};
|
|
2235
|
-
case "morphMany": return {
|
|
2236
|
-
related: definition.related,
|
|
2237
|
-
parentKey: definition.localKey,
|
|
2238
|
-
childKey: `${definition.morphName}Id`,
|
|
2239
|
-
where: { [`${definition.morphName}Type`]: parentType },
|
|
2240
|
-
presenceOnly: false
|
|
2241
|
-
};
|
|
2242
|
-
case "belongsTo": return {
|
|
2243
|
-
related: definition.related,
|
|
2244
|
-
parentKey: definition.foreignKey,
|
|
2245
|
-
childKey: definition.ownerKey,
|
|
2246
|
-
where: {},
|
|
2247
|
-
presenceOnly: true
|
|
2248
|
-
};
|
|
2249
|
-
default: return;
|
|
2250
|
-
}
|
|
2251
|
-
}
|
|
2252
|
-
/**
|
|
2253
|
-
* One row per owner key that exists, never a grouped COUNT: the answer is 0 or
|
|
2254
|
-
* 1, and the key column alone is all of the owner row anything here reads.
|
|
2255
|
-
*/
|
|
2256
|
-
async function countOwnersPresent(related, ownerKey, keys, size, queryOptions) {
|
|
2257
|
-
const rows = await loadByChunks(keys, size, (chunk) => related.newQuery(queryOptions).where({ [ownerKey]: chunk }).select(ownerKey)[RAW_RESULTS]());
|
|
2258
|
-
return new Map(rows.map((row) => [row[ownerKey], 1]));
|
|
2259
|
-
}
|
|
2260
|
-
function distinctKeys(records, key) {
|
|
2261
|
-
return Array.from(new Set(records.map((r) => r[key]).filter((v) => v != null)));
|
|
2262
|
-
}
|
|
2263
|
-
function chunkKeys(values, size) {
|
|
2264
|
-
if (values.length <= size) return [values];
|
|
2265
|
-
const chunks = [];
|
|
2266
|
-
for (let i = 0; i < values.length; i += size) chunks.push(values.slice(i, i + size));
|
|
2267
|
-
return chunks;
|
|
2268
|
-
}
|
|
2269
|
-
async function loadByChunks(values, size, load) {
|
|
2270
|
-
const results = [];
|
|
2271
|
-
for (const chunk of chunkKeys(values, size)) for (const record of await load(chunk)) results.push(record);
|
|
2272
|
-
return results;
|
|
2273
|
-
}
|
|
2274
|
-
/**
|
|
2275
|
-
* The related rows behind one eager load, and whether the constraint narrowed
|
|
2276
|
-
* them with `select()`. The callback runs on the builder that is executed: it
|
|
2277
|
-
* is the caller's, and a probe would run it an extra time per load. A top-level
|
|
2278
|
-
* `orWhere()` in it widens the foreign-key filter, so a loader that groups on
|
|
2279
|
-
* something weaker (morphMany, on the morph id) filters the rows itself.
|
|
2280
|
-
*/
|
|
2281
|
-
async function loadRelatedRecords(related, keys, clause, queryOptions, constraint) {
|
|
2282
|
-
const rows = (chunk) => {
|
|
2283
|
-
const query = related.newQuery(queryOptions).where(clause(chunk));
|
|
2284
|
-
constraint?.(query);
|
|
2285
|
-
return query[RAW_RESULTS]();
|
|
2286
|
-
};
|
|
2287
|
-
const size = maxInListSize(related.getAdapter());
|
|
2288
|
-
const whole = related.newQuery(queryOptions).where(clause(keys));
|
|
2289
|
-
constraint?.(whole);
|
|
2290
|
-
const options = whole.getOptions();
|
|
2291
|
-
const projected = (options.selectFields?.length ?? 0) > 0;
|
|
2292
|
-
const describesWholeSet = options.limitValue !== void 0 || options.offsetValue !== void 0 || options.orderBy.length > 0;
|
|
2293
|
-
if (keys.length <= size || describesWholeSet) return {
|
|
2294
|
-
records: await whole[RAW_RESULTS](),
|
|
2295
|
-
projected
|
|
2296
|
-
};
|
|
2297
|
-
return {
|
|
2298
|
-
records: await loadByChunks(keys, size, rows),
|
|
2299
|
-
projected
|
|
2300
|
-
};
|
|
2301
|
-
}
|
|
2302
|
-
async function countByChunks(values, size, count) {
|
|
2303
|
-
return new Map(await loadByChunks(values, size, async (chunk) => Array.from(await count(chunk))));
|
|
2304
|
-
}
|
|
2305
|
-
async function resolveModelReference(reference) {
|
|
2306
|
-
if (typeof reference === "function" && "prototype" in reference && reference.prototype instanceof Model) return reference;
|
|
2307
|
-
return await reference();
|
|
2308
|
-
}
|
|
2309
2560
|
/**
|
|
2310
2561
|
* A table-backed model base class: `recordType`/`createType` inferred from the
|
|
2311
2562
|
* table, `optionalOnCreate`/`requireOnCreate` reshaping the create payload without
|
|
@@ -2393,9 +2644,11 @@ function SoftDeletes(Base) {
|
|
|
2393
2644
|
SoftDeleteModel.addGlobalScope("softDelete", scopeFn);
|
|
2394
2645
|
SoftDeleteModel.delete = async function(where, writeOptions) {
|
|
2395
2646
|
if (!this.getAdapter().update) throw new Error("Configured adapter does not support update operations (needed for soft delete).");
|
|
2396
|
-
|
|
2397
|
-
return scopedQuery(this, where, writeOptions)[PREPARED_UPDATE]({ [column]: /* @__PURE__ */ new Date() });
|
|
2647
|
+
return this[LIFECYCLE_DELETE](where, "delete", () => scopedQuery(this, where, writeOptions).delete());
|
|
2398
2648
|
};
|
|
2649
|
+
Object.defineProperty(SoftDeleteModel, BULK_DELETE, { value: function(query) {
|
|
2650
|
+
return query[PREPARED_UPDATE]({ [this.deletedAtColumn]: /* @__PURE__ */ new Date() });
|
|
2651
|
+
} });
|
|
2399
2652
|
SoftDeleteModel.withTrashed = function(queryOptions) {
|
|
2400
2653
|
return withoutSoftDeleteScope(this, queryOptions);
|
|
2401
2654
|
};
|
|
@@ -2410,7 +2663,7 @@ function SoftDeletes(Base) {
|
|
|
2410
2663
|
};
|
|
2411
2664
|
SoftDeleteModel.forceDelete = async function(where, writeOptions) {
|
|
2412
2665
|
if (!this.getAdapter().delete) throw new Error("Configured adapter does not support delete operations.");
|
|
2413
|
-
return trashedScopedQuery(this, where, writeOptions)
|
|
2666
|
+
return this[LIFECYCLE_DELETE](where, "forceDelete", () => trashedScopedQuery(this, where, writeOptions)[PHYSICAL_DELETE]());
|
|
2414
2667
|
};
|
|
2415
2668
|
return SoftDeleteModel;
|
|
2416
2669
|
}
|