@guren/orm 2.11.1 → 2.12.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.
Files changed (3) hide show
  1. package/dist/index.d.ts +85 -53
  2. package/dist/index.js +901 -716
  3. 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/drizzle-adapter.ts
187
- let database;
188
- let transactionAwaitsCallback;
189
- let inListSize;
190
- let transactionQueue = Promise.resolve();
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
- let savepointSequence = 0;
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 ensureDatabase() {
244
- if (!database) throw new Error("DrizzleAdapter: database has not been configured. Call DrizzleAdapter.configure(db).");
245
- return database;
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,329 +968,163 @@ 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(db) {
456
- database = db;
457
- transactionAwaitsCallback = void 0;
458
- inListSize = void 0;
459
- transactionQueue = Promise.resolve();
460
- },
972
+ configure: configureConnection,
461
973
  getDatabase() {
462
- return ensureDatabase();
974
+ return connection().database;
463
975
  },
464
976
  maxInListSize() {
465
- if (!database) return 500;
466
- inListSize ??= dialectInListSize(database);
467
- return inListSize;
977
+ return currentConnection()?.maxInListSize() ?? 500;
468
978
  },
469
979
  async findMany(table, options, queryOptions) {
470
- let query = resolveExecutor(queryOptions).select().from(table);
471
- const { where, orderBy, limit, offset } = options ?? {};
472
- if (typeof query.where === "function") {
473
- const clause = resolveWhere(table, where);
474
- if (clause) query = query.where(clause);
475
- }
476
- if (typeof query.orderBy === "function") {
477
- const clauses = resolveOrder(table, orderBy);
478
- if (clauses && clauses.length > 0) query = query.orderBy(...clauses);
479
- }
480
- if (typeof query.limit === "function" && typeof limit === "number") query = query.limit(limit);
481
- if (typeof query.offset === "function" && typeof offset === "number") query = query.offset(offset);
482
- return await resolveList(query);
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
- let query = resolveExecutor(queryOptions).select({ value: count() }).from(table);
486
- if (typeof query.where === "function") {
487
- const clause = resolveWhere(table, where);
488
- if (clause) query = query.where(clause);
489
- }
490
- return toCount((await resolveList(query))[0]?.value);
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
- let query = resolveExecutor(queryOptions).select().from(table);
494
- if (typeof query.where === "function") {
495
- const clause = resolveWhere(table, where);
496
- if (clause) query = query.where(clause);
497
- }
498
- const row = await resolveSingle(query);
499
- if (row == null) return null;
500
- return row;
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
- const query = resolveExecutor(writeOptions).insert(table).values(data);
504
- const { usedReturning, row } = await resolveWithReturning(query);
505
- if (usedReturning) return row;
506
- return await resolveMutation(query);
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
- const db = resolveExecutor(writeOptions);
510
- if (!db.update) throw new Error("DrizzleAdapter: configured database does not support updates.");
511
- const clause = resolveWhere(table, where);
512
- const finalQuery = clause ? db.update(table).set(data).where(clause) : db.update(table).set(data);
513
- const { usedReturning, row } = await resolveWithReturning(finalQuery);
514
- if (usedReturning) return row;
515
- return await resolveMutation(finalQuery);
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
- const db = resolveExecutor(writeOptions);
519
- if (!db.delete) throw new Error("DrizzleAdapter: configured database does not support deletes.");
520
- const clause = resolveWhere(table, where);
521
- const finalQuery = clause ? db.delete(table).where(clause) : db.delete(table);
522
- const { usedReturning, row } = await resolveWithReturning(finalQuery);
523
- if (usedReturning) return row;
524
- return await resolveMutation(finalQuery);
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
- const db = resolveExecutor(queryOptions);
528
- const tableRecord = table;
529
- let query;
530
- if (options.select && options.select.length > 0) {
531
- const selection = {};
532
- for (const field of options.select) {
533
- const column = tableRecord[field];
534
- if (!column) throw new Error(`DrizzleAdapter: unknown column "${field}" on provided table.`);
535
- selection[field] = column;
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 = db.select(selection).from(table);
538
- } else query = db.select().from(table);
539
- query = withConditions(query, table, conditions);
540
- if (typeof query.orderBy === "function") {
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 toCount((await resolveList(withConditions(resolveExecutor(queryOptions).select({ value: count() }).from(table), table, conditions)))[0]?.value);
1070
+ return connection().run(queryOptions, async (db) => {
1071
+ return toCount((await resolveList(withConditions(db.select({ value: count() }).from(table), table, conditions)))[0]?.value);
1072
+ });
550
1073
  },
551
1074
  async aggregateAdvanced(table, fn, field, conditions, queryOptions) {
552
- const db = resolveExecutor(queryOptions);
553
- const column = resolveColumn(table, field);
554
- const expression = fn === "min" ? min(column) : fn === "max" ? max(column) : sql`${sql.raw(fn)}(${column})`;
555
- return decodeAggregate(fn, column, field, (await resolveList(withConditions(db.select({ value: expression }).from(table), table, conditions)))[0]?.value ?? null);
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
+ });
556
1080
  },
557
1081
  executor(queryOptions) {
558
- return resolveExecutor(queryOptions);
1082
+ return connection().executor(queryOptions);
1083
+ },
1084
+ queueExecution(query, queryOptions) {
1085
+ return connection().queueExecution(query, queryOptions);
559
1086
  },
560
1087
  async countByAdvanced(table, field, conditions, queryOptions) {
561
- const db = resolveExecutor(queryOptions);
562
- const column = table[field];
563
- if (!column) throw new Error(`DrizzleAdapter: unknown column "${field}" on provided table.`);
564
- let query = withConditions(db.select({
565
- key: column,
566
- value: count()
567
- }).from(table), table, conditions);
568
- if (typeof query.groupBy !== "function") throw new Error("DrizzleAdapter: configured database does not support groupBy().");
569
- query = query.groupBy(column);
570
- return (await resolveList(query)).map(({ key, value }) => ({
571
- key,
572
- count: toCount(value)
573
- }));
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
+ });
574
1102
  },
575
1103
  async updateAdvanced(table, conditions, data, writeOptions) {
576
- const db = resolveExecutor(writeOptions);
577
- if (!db.update) throw new Error("DrizzleAdapter: configured database does not support updates.");
578
- const clause = buildDrizzleConditions(table, conditions);
579
- const finalQuery = clause ? db.update(table).set(data).where(clause) : db.update(table).set(data);
580
- const { usedReturning, row } = await resolveWithReturning(finalQuery);
581
- if (usedReturning) return row;
582
- return await resolveMutation(finalQuery);
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
+ });
583
1112
  },
584
1113
  async deleteAdvanced(table, conditions, writeOptions) {
585
- const db = resolveExecutor(writeOptions);
586
- if (!db.delete) throw new Error("DrizzleAdapter: configured database does not support deletes.");
587
- const clause = buildDrizzleConditions(table, conditions);
588
- const finalQuery = clause ? db.delete(table).where(clause) : db.delete(table);
589
- const { usedReturning, row } = await resolveWithReturning(finalQuery);
590
- if (usedReturning) return row;
591
- return await resolveMutation(finalQuery);
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
+ });
592
1122
  },
593
- /**
594
- * A nested call opens a savepoint inside the transaction already running
595
- * rather than a second top-level one: on a `max: 1` pool that second one
596
- * would wait on the connection the first holds, and on the single-connection
597
- * drivers it would queue behind itself. An inner throw the outer callback
598
- * catches therefore discards only the inner writes.
599
- */
600
1123
  async transaction(callback) {
601
- const db = ensureDatabase();
602
- if (typeof db.transaction !== "function") throw new Error("DrizzleAdapter: configured database does not support transactions.");
603
- const store = await loadTransactionStore();
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);
1124
+ return connection().transaction(callback);
608
1125
  }
609
1126
  };
610
1127
  //#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);
650
- }
651
- return result;
652
- }
653
- //#endregion
654
1128
  //#region src/deprecate.ts
655
1129
  const warned = /* @__PURE__ */ new Set();
656
1130
  /**
@@ -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
@@ -991,7 +1495,8 @@ var QueryBuilder = class QueryBuilder {
991
1495
  selectFromTable() {
992
1496
  const fields = this.options.selectFields;
993
1497
  const selection = fields && fields.length > 0 ? Object.fromEntries(fields.map((field) => [field, resolveColumn(this.table, field)])) : void 0;
994
- return this.resolveDrizzleDatabase().select(selection)?.from?.(this.table);
1498
+ const query = this.resolveDrizzleDatabase().select(selection)?.from?.(this.table);
1499
+ return this.adapter.queueExecution?.(query, { trx: this.options.trx }) ?? query;
995
1500
  }
996
1501
  resolveDrizzleDatabase() {
997
1502
  const advancedAdapter = this.adapter;
@@ -1069,22 +1574,39 @@ var QueryBuilder = class QueryBuilder {
1069
1574
  * would be a supported way to bypass mass-assignment protection entirely.
1070
1575
  */
1071
1576
  async [PREPARED_UPDATE](payload) {
1072
- if (!this.adapter.update) throw new Error("Configured adapter does not support update operations.");
1073
- this.assertFiltersSurvived("update");
1074
- const advancedAdapter = this.adapter;
1075
- if (typeof advancedAdapter.updateAdvanced === "function") return advancedAdapter.updateAdvanced(this.table, this.effectiveConditions(), payload, { trx: this.options.trx });
1577
+ const adapter = this.assertWritable("update");
1578
+ if (typeof adapter.updateAdvanced === "function") return adapter.updateAdvanced(this.table, this.effectiveConditions(), payload, { trx: this.options.trx });
1579
+ return adapter.update(this.table, this.simpleWhereFor("update"), payload, { trx: this.options.trx });
1580
+ }
1581
+ /**
1582
+ * The object-where a basic adapter takes; a condition the flat object cannot
1583
+ * carry (an OR group, an operator, two values on one field) refuses rather
1584
+ * than writing with it dropped.
1585
+ */
1586
+ simpleWhereFor(operation) {
1076
1587
  const simpleWhere = this.toSimpleWhereClause();
1077
- if (simpleWhere) return this.adapter.update(this.table, simpleWhere, payload, { trx: this.options.trx });
1078
- throw new Error("Advanced conditions require an adapter that supports updateAdvanced.");
1588
+ if (!simpleWhere) throw new Error(`Advanced conditions require an adapter that supports ${operation}Advanced.`);
1589
+ return simpleWhere;
1590
+ }
1591
+ /** Returns the adapter narrowed to the operation, so no call site needs a non-null assertion. */
1592
+ assertWritable(operation) {
1593
+ if (!this.adapter[operation]) throw new Error(`Configured adapter does not support ${operation} operations.`);
1594
+ this.assertWriteOptions();
1595
+ this.assertFiltersSurvived(operation);
1596
+ return this.adapter;
1597
+ }
1598
+ assertWriteOptions() {
1599
+ 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
1600
  }
1080
1601
  async delete() {
1081
- if (!this.adapter.delete) throw new Error("Configured adapter does not support delete operations.");
1082
- this.assertFiltersSurvived("delete");
1083
- const advancedAdapter = this.adapter;
1084
- if (typeof advancedAdapter.deleteAdvanced === "function") return advancedAdapter.deleteAdvanced(this.table, this.effectiveConditions(), { trx: this.options.trx });
1085
- const simpleWhere = this.toSimpleWhereClause();
1086
- if (simpleWhere) return this.adapter.delete(this.table, simpleWhere, { trx: this.options.trx });
1087
- throw new Error("Advanced conditions require an adapter that supports deleteAdvanced.");
1602
+ const model = this.modelClass;
1603
+ if (model[BULK_DELETE]) return model[BULK_DELETE](this);
1604
+ return this[PHYSICAL_DELETE]();
1605
+ }
1606
+ async [PHYSICAL_DELETE]() {
1607
+ const adapter = this.assertWritable("delete");
1608
+ if (typeof adapter.deleteAdvanced === "function") return adapter.deleteAdvanced(this.table, this.effectiveConditions(), { trx: this.options.trx });
1609
+ return adapter.delete(this.table, this.simpleWhereFor("delete"), { trx: this.options.trx });
1088
1610
  }
1089
1611
  /** Makes the builder awaitable, resolving to `get()`. */
1090
1612
  then(onfulfilled, onrejected) {
@@ -1183,18 +1705,20 @@ var QueryBuilder = class QueryBuilder {
1183
1705
  select: overrides.select ?? this.options.selectFields
1184
1706
  }, { trx: this.options.trx });
1185
1707
  const simpleWhere = this.toSimpleWhereClause();
1186
- if (simpleWhere === null && this.hasConditions()) 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.`);
1708
+ 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
1709
  return this.adapter.findMany(this.table, {
1188
- where: simpleWhere ?? void 0,
1710
+ where: simpleWhere,
1189
1711
  orderBy: orderBy.length > 0 ? orderBy : void 0,
1190
1712
  limit,
1191
1713
  offset
1192
1714
  }, { trx: this.options.trx });
1193
1715
  }
1194
- /** Null when the conditions are too complex for a basic adapter's WhereClause. */
1716
+ /**
1717
+ * The flat object a basic adapter's WhereClause takes: `{}` for no conditions
1718
+ * at all, null when the conditions are too complex for it.
1719
+ */
1195
1720
  toSimpleWhereClause() {
1196
1721
  const conditions = this.allConditions();
1197
- if (conditions.length === 0) return null;
1198
1722
  const result = {};
1199
1723
  for (const condition of conditions) {
1200
1724
  if (condition.type !== "simple") return null;
@@ -1396,9 +1920,8 @@ var Model = class Model {
1396
1920
  return new QueryBuilder(this, queryOptions);
1397
1921
  }
1398
1922
  /**
1399
- * Both write entry points fork on `hasScopes()`, and only one arm reaches a
1400
- * builder — so the refusal belongs above the fork, where every adapter is
1401
- * still in scope.
1923
+ * Ahead of the `updating`/`deleting` hooks, which must not fire for a write
1924
+ * that is refused; the builder repeats the check for its own callers.
1402
1925
  */
1403
1926
  static assertFiltersSurvived(where, operation) {
1404
1927
  if (!everyFilterDropped(where)) return;
@@ -1785,27 +2308,10 @@ var Model = class Model {
1785
2308
  const table = this.resolveTable();
1786
2309
  const filtered = applyFillable ? this.filterFillable(data) : { ...data };
1787
2310
  const payload = await this.preparePersistencePayload(filtered);
1788
- const hooks = this.hooks;
1789
- const observers = this.observers;
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
- }
2311
+ const lifecycle = modelLifecycle(this.name, "create", this.hooks, this.observers);
2312
+ await lifecycle.before(payload);
1798
2313
  const result = await this.getAdapter().create(table, payload, writeOptions);
1799
- if (hooks) {
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
- }
2314
+ await lifecycle.after(result);
1809
2315
  return this.applyReadTransforms(result);
1810
2316
  }
1811
2317
  static async update(where, data, writeOptions) {
@@ -1819,52 +2325,32 @@ var Model = class Model {
1819
2325
  return this.runUpdate(where, data, writeOptions, false);
1820
2326
  }
1821
2327
  static async runUpdate(where, data, writeOptions, applyFillable) {
1822
- const table = this.resolveTable();
1823
- const adapter = this.getAdapter();
1824
- if (!adapter.update) throw new Error("Configured adapter does not support update operations.");
2328
+ if (!this.getAdapter().update) throw new Error("Configured adapter does not support update operations.");
1825
2329
  this.assertFiltersSurvived(where, "update");
1826
2330
  const filtered = applyFillable ? this.filterFillable(data) : { ...data };
1827
2331
  const payload = await this.preparePersistencePayload(filtered);
1828
- const hooks = this.hooks;
1829
- const observers = this.observers;
1830
- if (hooks) {
1831
- if (!await executeHook(hooks, "updating", payload)) throw new Error(`${this.name}.update() aborted by 'updating' hook.`);
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
- }
2332
+ const lifecycle = modelLifecycle(this.name, "update", this.hooks, this.observers);
2333
+ await lifecycle.before(payload);
2334
+ const result = await this.newQuery(writeOptions).where(where)[PREPARED_UPDATE](payload);
2335
+ await lifecycle.after(result);
1849
2336
  return this.applyReadTransforms(result);
1850
2337
  }
1851
2338
  static async delete(where, writeOptions) {
1852
- const table = this.resolveTable();
1853
- const adapter = this.getAdapter();
1854
- if (!adapter.delete) throw new Error("Configured adapter does not support delete operations.");
2339
+ if (!this.getAdapter().delete) throw new Error("Configured adapter does not support delete operations.");
2340
+ return this[LIFECYCLE_DELETE](where, "delete", () => this.newQuery(writeOptions).where(where).delete());
2341
+ }
2342
+ /**
2343
+ * Runs `write` between the `deleting` and `deleted` events, for `delete()`
2344
+ * and the SoftDeletes overrides. Symbol-keyed and kept out of the package
2345
+ * entry point; each caller checks its own adapter capability first.
2346
+ */
2347
+ static async [LIFECYCLE_DELETE](where, method, write) {
1855
2348
  this.assertFiltersSurvived(where, "delete");
1856
- const hooks = this.hooks;
1857
- const observers = this.observers;
2349
+ const lifecycle = modelLifecycle(this.name, "delete", this.hooks, this.observers, method);
1858
2350
  const whereData = where;
1859
- if (hooks) {
1860
- if (!await executeHook(hooks, "deleting", whereData)) throw new Error(`${this.name}.delete() aborted by 'deleting' hook.`);
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);
2351
+ await lifecycle.before(whereData);
2352
+ const result = await write();
2353
+ await lifecycle.after(whereData);
1868
2354
  return result;
1869
2355
  }
1870
2356
  /**
@@ -1928,17 +2414,7 @@ var Model = class Model {
1928
2414
  */
1929
2415
  static async loadRelationsInto(records, relationNames, queryOptions, constraints, pathPrefix = "") {
1930
2416
  if (relationNames.length === 0) return;
1931
- const groups = /* @__PURE__ */ new Map();
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);
2417
+ for (const [head, tails] of groupRelationPaths(relationNames)) await this.loadRelationLevel(records, head, tails, queryOptions, constraints, pathPrefix);
1942
2418
  }
1943
2419
  /**
1944
2420
  * @internal Public because generated code reaches it; internal callers should
@@ -1979,333 +2455,40 @@ var Model = class Model {
1979
2455
  break;
1980
2456
  case "morphTo": await this.loadMorphTo(records, definition, queryOptions, constraint);
1981
2457
  }
1982
- if (tails.length > 0 && definition.type === "morphTo") throw new Error(`${this.name}: nested eager loading through morphTo relation "${head}" is not supported.`);
1983
- if (definition.type === "morphTo") return;
1984
- const children = [];
1985
- const seen = /* @__PURE__ */ new Set();
1986
- for (const record of records) {
1987
- const value = record[head];
1988
- const items = Array.isArray(value) ? value : value != null ? [value] : [];
1989
- for (const item of items) if (item && typeof item === "object" && !seen.has(item)) {
1990
- seen.add(item);
1991
- children.push(item);
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);
2458
+ await loadRelationChildren({
2459
+ modelName: this.name,
2460
+ records,
2461
+ definition,
2462
+ head,
2463
+ tails,
2464
+ projected,
2465
+ currentPath,
2466
+ queryOptions,
2467
+ constraints
2468
+ });
1998
2469
  }
1999
2470
  static async loadHasMany(records, definition, queryOptions, constraint) {
2000
- const { foreignKey, localKey, name } = definition;
2001
- return loadRelationData(records, name, await resolveModelReference(definition.related), localKey, foreignKey, true, queryOptions, constraint);
2471
+ return loadHasMany(records, definition, queryOptions, constraint);
2002
2472
  }
2003
2473
  static async loadHasOne(records, definition, queryOptions, constraint) {
2004
- const { foreignKey, localKey, name } = definition;
2005
- return loadRelationData(records, name, await resolveModelReference(definition.related), localKey, foreignKey, false, queryOptions, constraint);
2474
+ return loadHasOne(records, definition, queryOptions, constraint);
2006
2475
  }
2007
2476
  static async loadBelongsTo(records, definition, queryOptions, constraint) {
2008
- const { foreignKey, ownerKey, name } = definition;
2009
- return loadRelationData(records, name, await resolveModelReference(definition.related), foreignKey, ownerKey, false, queryOptions, constraint);
2477
+ return loadBelongsTo(records, definition, queryOptions, constraint);
2010
2478
  }
2011
2479
  static async loadBelongsToMany(records, definition, queryOptions, constraint) {
2012
- const { pivotTable, foreignPivotKey, relatedPivotKey, parentKey, relatedKey, name } = definition;
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;
2480
+ return loadBelongsToMany(this, records, definition, queryOptions, constraint);
2046
2481
  }
2047
2482
  static async loadHasManyThrough(records, definition, queryOptions, constraint) {
2048
- const { firstKey, secondKey, localKey, secondLocalKey, name } = definition;
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;
2483
+ return loadHasManyThrough(records, definition, queryOptions, constraint);
2092
2484
  }
2093
2485
  static async loadMorphMany(records, definition, queryOptions, constraint) {
2094
- const { morphName, localKey, name } = definition;
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;
2486
+ return loadMorphMany(this, records, definition, queryOptions, constraint);
2120
2487
  }
2121
2488
  static async loadMorphTo(records, definition, queryOptions, constraint) {
2122
- const { morphName, name } = definition;
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
- }
2489
+ return loadMorphTo(Model.morphMap ?? {}, records, definition, queryOptions, constraint);
2153
2490
  }
2154
2491
  };
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
2492
  /**
2310
2493
  * A table-backed model base class: `recordType`/`createType` inferred from the
2311
2494
  * table, `optionalOnCreate`/`requireOnCreate` reshaping the create payload without
@@ -2393,9 +2576,11 @@ function SoftDeletes(Base) {
2393
2576
  SoftDeleteModel.addGlobalScope("softDelete", scopeFn);
2394
2577
  SoftDeleteModel.delete = async function(where, writeOptions) {
2395
2578
  if (!this.getAdapter().update) throw new Error("Configured adapter does not support update operations (needed for soft delete).");
2396
- const column = this.deletedAtColumn;
2397
- return scopedQuery(this, where, writeOptions)[PREPARED_UPDATE]({ [column]: /* @__PURE__ */ new Date() });
2579
+ return this[LIFECYCLE_DELETE](where, "delete", () => scopedQuery(this, where, writeOptions).delete());
2398
2580
  };
2581
+ Object.defineProperty(SoftDeleteModel, BULK_DELETE, { value: function(query) {
2582
+ return query[PREPARED_UPDATE]({ [this.deletedAtColumn]: /* @__PURE__ */ new Date() });
2583
+ } });
2399
2584
  SoftDeleteModel.withTrashed = function(queryOptions) {
2400
2585
  return withoutSoftDeleteScope(this, queryOptions);
2401
2586
  };
@@ -2410,7 +2595,7 @@ function SoftDeletes(Base) {
2410
2595
  };
2411
2596
  SoftDeleteModel.forceDelete = async function(where, writeOptions) {
2412
2597
  if (!this.getAdapter().delete) throw new Error("Configured adapter does not support delete operations.");
2413
- return trashedScopedQuery(this, where, writeOptions).delete();
2598
+ return this[LIFECYCLE_DELETE](where, "forceDelete", () => trashedScopedQuery(this, where, writeOptions)[PHYSICAL_DELETE]());
2414
2599
  };
2415
2600
  return SoftDeleteModel;
2416
2601
  }