@guren/orm 2.8.0 → 2.10.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/dist/index.d.ts +79 -16
- package/dist/index.js +569 -300
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -27,6 +27,23 @@ else {
|
|
|
27
27
|
}
|
|
28
28
|
}
|
|
29
29
|
//#endregion
|
|
30
|
+
//#region src/internal-keys.ts
|
|
31
|
+
/**
|
|
32
|
+
* What `Model`, `QueryBuilder` and the adapters share without importing each
|
|
33
|
+
* other, kept out of the package entry point. The keys live here rather than on
|
|
34
|
+
* either class because `Model` names one as a computed static key: evaluated
|
|
35
|
+
* while the two modules' import cycle is still unwinding, a key declared in the
|
|
36
|
+
* other one is in its temporal dead zone.
|
|
37
|
+
*/
|
|
38
|
+
/** Bulk update with an already-filtered, already-prepared payload. */
|
|
39
|
+
const PREPARED_UPDATE = Symbol("guren.orm.preparedUpdate");
|
|
40
|
+
/** Freezes the conditions applied so far as the model's global scopes. */
|
|
41
|
+
const SEAL_SCOPES = Symbol("guren.orm.sealScopes");
|
|
42
|
+
/** The model's one read-transform pass over a result set. */
|
|
43
|
+
const READ_TRANSFORMS = Symbol("guren.orm.readTransforms");
|
|
44
|
+
/** Rows as the adapter read them, for the joins a relation loader makes. */
|
|
45
|
+
const RAW_RESULTS = Symbol("guren.orm.rawResults");
|
|
46
|
+
//#endregion
|
|
30
47
|
//#region src/where-conditions.ts
|
|
31
48
|
/**
|
|
32
49
|
* True when the caller wrote filters and every one of them was `undefined`.
|
|
@@ -139,14 +156,50 @@ function buildDrizzleConditions(table, conditions) {
|
|
|
139
156
|
//#region src/adapters/drizzle-adapter.ts
|
|
140
157
|
let database;
|
|
141
158
|
let transactionAwaitsCallback;
|
|
159
|
+
let inListSize;
|
|
142
160
|
let transactionQueue = Promise.resolve();
|
|
143
|
-
let
|
|
161
|
+
let transactionStore;
|
|
162
|
+
let loadedStore;
|
|
163
|
+
let savepointSequence = 0;
|
|
164
|
+
const POOLED_IN_LIST_SIZE = 5e3;
|
|
165
|
+
/**
|
|
166
|
+
* Read from how the dialect escapes a parameter and a name, since this adapter
|
|
167
|
+
* takes any drizzle-shaped handle and a driver list would name one it has never
|
|
168
|
+
* heard of. A shape it cannot place keeps the conservative figure.
|
|
169
|
+
*/
|
|
170
|
+
function dialectInListSize(db) {
|
|
171
|
+
const dialect = db.dialect;
|
|
172
|
+
try {
|
|
173
|
+
if (dialect?.escapeParam?.(0) === "$1") return POOLED_IN_LIST_SIZE;
|
|
174
|
+
if (dialect?.escapeName?.("x") === "`x`") return POOLED_IN_LIST_SIZE;
|
|
175
|
+
} catch {}
|
|
176
|
+
return 500;
|
|
177
|
+
}
|
|
178
|
+
function withConditions(query, table, conditions) {
|
|
179
|
+
if (typeof query.where !== "function") return query;
|
|
180
|
+
const clause = buildDrizzleConditions(table, conditions);
|
|
181
|
+
return clause ? query.where(clause) : query;
|
|
182
|
+
}
|
|
183
|
+
/** Drivers report a count as a number, a bigint or a decimal string. */
|
|
184
|
+
function toCount(value) {
|
|
185
|
+
const total = Number(value ?? 0);
|
|
186
|
+
return Number.isNaN(total) ? 0 : total;
|
|
187
|
+
}
|
|
144
188
|
function ensureDatabase() {
|
|
145
189
|
if (!database) throw new Error("DrizzleAdapter: database has not been configured. Call DrizzleAdapter.configure(db).");
|
|
146
190
|
return database;
|
|
147
191
|
}
|
|
192
|
+
/**
|
|
193
|
+
* An explicit `trx` wins; without one, a call made inside a `transaction()`
|
|
194
|
+
* callback runs on that transaction. Off the pool, on a driver whose pool is
|
|
195
|
+
* `max: 1`, it would wait on the connection the open transaction holds. A
|
|
196
|
+
* settled ambient is ignored: a continuation nobody awaited outlives the
|
|
197
|
+
* transaction it was started in, and its handle is finalised by then.
|
|
198
|
+
*/
|
|
148
199
|
function resolveExecutor(options) {
|
|
149
200
|
if (options?.trx && typeof options.trx === "object") return options.trx;
|
|
201
|
+
const ambient = loadedStore?.getStore();
|
|
202
|
+
if (ambient && !ambient.settled && typeof ambient.handle === "object" && ambient.handle !== null) return ambient.handle;
|
|
150
203
|
return ensureDatabase();
|
|
151
204
|
}
|
|
152
205
|
async function resolveList(result) {
|
|
@@ -237,34 +290,96 @@ async function awaitsItsCallback(db) {
|
|
|
237
290
|
return transactionAwaitsCallback;
|
|
238
291
|
}
|
|
239
292
|
/**
|
|
240
|
-
* Imported on demand so `node:async_hooks` stays off the module graph
|
|
241
|
-
*
|
|
242
|
-
*
|
|
293
|
+
* Imported on demand so `node:async_hooks` stays off the module graph until a
|
|
294
|
+
* transaction is opened (Workers needs `nodejs_compat` for it, as for
|
|
295
|
+
* `node:crypto`). The promise is what is memoized, not the storage: two
|
|
243
296
|
* concurrent first callers must not end up asking different instances.
|
|
244
297
|
*/
|
|
245
|
-
function
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
return
|
|
249
|
-
run: (fn) => store.run(true, fn),
|
|
250
|
-
isInside: () => store.getStore() === true
|
|
251
|
-
};
|
|
298
|
+
function loadTransactionStore() {
|
|
299
|
+
transactionStore ??= import("node:async_hooks").then(({ AsyncLocalStorage }) => {
|
|
300
|
+
loadedStore = new AsyncLocalStorage();
|
|
301
|
+
return loadedStore;
|
|
252
302
|
});
|
|
253
|
-
return
|
|
303
|
+
return transactionStore;
|
|
304
|
+
}
|
|
305
|
+
/**
|
|
306
|
+
* Opened on the root database for a top-level call and on the open
|
|
307
|
+
* transaction's own handle for a nested one, which is what makes drizzle emit
|
|
308
|
+
* SAVEPOINT for the second. `settled` is set once the transaction itself has
|
|
309
|
+
* finished, not once its callback has.
|
|
310
|
+
*/
|
|
311
|
+
async function runDriverTransaction(open, store, callback) {
|
|
312
|
+
let entry;
|
|
313
|
+
try {
|
|
314
|
+
return await open((trx) => {
|
|
315
|
+
entry = driverEntry(trx, store);
|
|
316
|
+
return store.run(entry, () => callback(trx));
|
|
317
|
+
});
|
|
318
|
+
} finally {
|
|
319
|
+
if (entry) entry.settled = true;
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
function driverEntry(handle, store) {
|
|
323
|
+
const open = handle.transaction;
|
|
324
|
+
return {
|
|
325
|
+
handle,
|
|
326
|
+
settled: false,
|
|
327
|
+
nest: (callback) => typeof open === "function" ? runDriverTransaction(open.bind(handle), store, callback) : callback(handle)
|
|
328
|
+
};
|
|
329
|
+
}
|
|
330
|
+
function manualEntry(db, run, store) {
|
|
331
|
+
return {
|
|
332
|
+
handle: db,
|
|
333
|
+
settled: false,
|
|
334
|
+
nest: (callback) => runSavepoint(db, run, store, callback)
|
|
335
|
+
};
|
|
336
|
+
}
|
|
337
|
+
/**
|
|
338
|
+
* The savepoint the manual BEGIN/COMMIT path drives itself: this driver's own
|
|
339
|
+
* `transaction()` commits before awaiting, so a nested call cannot go through
|
|
340
|
+
* it. Savepoints do not pass through `transactionQueue`, so nested
|
|
341
|
+
* transactions have to be awaited one at a time — two released out of order
|
|
342
|
+
* discard each other's frames.
|
|
343
|
+
*/
|
|
344
|
+
async function runSavepoint(db, run, store, callback) {
|
|
345
|
+
const name = `guren_sp_${savepointSequence += 1}`;
|
|
346
|
+
await run(sql.raw(`savepoint ${name}`));
|
|
347
|
+
return enterTransaction(db, run, store, callback, {
|
|
348
|
+
commit: [`release savepoint ${name}`],
|
|
349
|
+
rollback: [`rollback to savepoint ${name}`, `release savepoint ${name}`]
|
|
350
|
+
});
|
|
351
|
+
}
|
|
352
|
+
/**
|
|
353
|
+
* The lifecycle both hand-driven paths share, from the statement that opened the
|
|
354
|
+
* transaction to the one that settles it. The entry is entered synchronously,
|
|
355
|
+
* which is what puts every await inside the callback — and so any transaction it
|
|
356
|
+
* starts — in this transaction's async context.
|
|
357
|
+
*/
|
|
358
|
+
async function enterTransaction(db, run, store, callback, settle) {
|
|
359
|
+
const entry = manualEntry(db, run, store);
|
|
360
|
+
try {
|
|
361
|
+
const result = await store.run(entry, () => callback(db));
|
|
362
|
+
for (const statement of settle.commit) await run(sql.raw(statement));
|
|
363
|
+
return result;
|
|
364
|
+
} catch (error) {
|
|
365
|
+
try {
|
|
366
|
+
for (const statement of settle.rollback) await run(sql.raw(statement));
|
|
367
|
+
} catch {}
|
|
368
|
+
throw error;
|
|
369
|
+
} finally {
|
|
370
|
+
entry.settled = true;
|
|
371
|
+
}
|
|
254
372
|
}
|
|
255
373
|
/**
|
|
256
374
|
* Serializes what `runExclusively` drives, since one connection takes one
|
|
257
|
-
* transaction.
|
|
258
|
-
*
|
|
259
|
-
*
|
|
260
|
-
* call from an unrelated concurrent one, and refusing both punishes the second.
|
|
375
|
+
* transaction. Only a caller outside every transaction may wait here: a nested
|
|
376
|
+
* one would queue behind itself, which is why `transaction()` settles nesting
|
|
377
|
+
* from the async context before reaching this queue.
|
|
261
378
|
*/
|
|
262
|
-
async function runOwnTransaction(db, callback) {
|
|
379
|
+
async function runOwnTransaction(db, store, callback) {
|
|
263
380
|
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.");
|
|
264
|
-
const scope = await loadTransactionScope();
|
|
265
|
-
if (scope.isInside()) throw new Error("DrizzleAdapter: cannot begin a transaction inside another one. This driver holds a single connection, which takes one transaction at a time, so the inner transaction would wait on the outer one to finish and the outer on the inner.");
|
|
266
381
|
const run = db.run.bind(db);
|
|
267
|
-
const slot = transactionQueue.then(() => runExclusively(db, run,
|
|
382
|
+
const slot = transactionQueue.then(() => runExclusively(db, run, store, callback));
|
|
268
383
|
transactionQueue = slot.then(NOOP, NOOP);
|
|
269
384
|
return slot;
|
|
270
385
|
}
|
|
@@ -274,28 +389,28 @@ async function runOwnTransaction(db, callback) {
|
|
|
274
389
|
* transaction scope: these drivers hold one connection, so every statement
|
|
275
390
|
* between BEGIN and COMMIT is inside it. Callers reach this one at a time.
|
|
276
391
|
*/
|
|
277
|
-
async function runExclusively(db, run,
|
|
392
|
+
async function runExclusively(db, run, store, callback) {
|
|
278
393
|
await run(sql.raw("begin"));
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
} catch (error) {
|
|
284
|
-
try {
|
|
285
|
-
await run(sql.raw("rollback"));
|
|
286
|
-
} catch {}
|
|
287
|
-
throw error;
|
|
288
|
-
}
|
|
394
|
+
return enterTransaction(db, run, store, callback, {
|
|
395
|
+
commit: ["commit"],
|
|
396
|
+
rollback: ["rollback"]
|
|
397
|
+
});
|
|
289
398
|
}
|
|
290
399
|
const DrizzleAdapter = {
|
|
291
400
|
configure(db) {
|
|
292
401
|
database = db;
|
|
293
402
|
transactionAwaitsCallback = void 0;
|
|
403
|
+
inListSize = void 0;
|
|
294
404
|
transactionQueue = Promise.resolve();
|
|
295
405
|
},
|
|
296
406
|
getDatabase() {
|
|
297
407
|
return ensureDatabase();
|
|
298
408
|
},
|
|
409
|
+
maxInListSize() {
|
|
410
|
+
if (!database) return 500;
|
|
411
|
+
inListSize ??= dialectInListSize(database);
|
|
412
|
+
return inListSize;
|
|
413
|
+
},
|
|
299
414
|
async findMany(table, options, queryOptions) {
|
|
300
415
|
let query = resolveExecutor(queryOptions).select().from(table);
|
|
301
416
|
const { where, orderBy, limit, offset } = options ?? {};
|
|
@@ -317,9 +432,7 @@ const DrizzleAdapter = {
|
|
|
317
432
|
const clause = resolveWhere(table, where);
|
|
318
433
|
if (clause) query = query.where(clause);
|
|
319
434
|
}
|
|
320
|
-
|
|
321
|
-
const total = typeof raw === "bigint" ? Number(raw) : Number(raw);
|
|
322
|
-
return Number.isNaN(total) ? 0 : total;
|
|
435
|
+
return toCount((await resolveList(query))[0]?.value);
|
|
323
436
|
},
|
|
324
437
|
async findUnique(table, where, queryOptions) {
|
|
325
438
|
let query = resolveExecutor(queryOptions).select().from(table);
|
|
@@ -368,10 +481,7 @@ const DrizzleAdapter = {
|
|
|
368
481
|
}
|
|
369
482
|
query = db.select(selection).from(table);
|
|
370
483
|
} else query = db.select().from(table);
|
|
371
|
-
|
|
372
|
-
const clause = buildDrizzleConditions(table, conditions);
|
|
373
|
-
if (clause) query = query.where(clause);
|
|
374
|
-
}
|
|
484
|
+
query = withConditions(query, table, conditions);
|
|
375
485
|
if (typeof query.orderBy === "function") {
|
|
376
486
|
const clauses = resolveOrder(table, options.orderBy);
|
|
377
487
|
if (clauses && clauses.length > 0) query = query.orderBy(...clauses);
|
|
@@ -381,14 +491,22 @@ const DrizzleAdapter = {
|
|
|
381
491
|
return await resolveList(query);
|
|
382
492
|
},
|
|
383
493
|
async countAdvanced(table, conditions, queryOptions) {
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
494
|
+
return toCount((await resolveList(withConditions(resolveExecutor(queryOptions).select({ value: count() }).from(table), table, conditions)))[0]?.value);
|
|
495
|
+
},
|
|
496
|
+
async countByAdvanced(table, field, conditions, queryOptions) {
|
|
497
|
+
const db = resolveExecutor(queryOptions);
|
|
498
|
+
const column = table[field];
|
|
499
|
+
if (!column) throw new Error(`DrizzleAdapter: unknown column "${field}" on provided table.`);
|
|
500
|
+
let query = withConditions(db.select({
|
|
501
|
+
key: column,
|
|
502
|
+
value: count()
|
|
503
|
+
}).from(table), table, conditions);
|
|
504
|
+
if (typeof query.groupBy !== "function") throw new Error("DrizzleAdapter: configured database does not support groupBy().");
|
|
505
|
+
query = query.groupBy(column);
|
|
506
|
+
return (await resolveList(query)).map(({ key, value }) => ({
|
|
507
|
+
key,
|
|
508
|
+
count: toCount(value)
|
|
509
|
+
}));
|
|
392
510
|
},
|
|
393
511
|
async updateAdvanced(table, conditions, data, writeOptions) {
|
|
394
512
|
const db = resolveExecutor(writeOptions);
|
|
@@ -408,22 +526,52 @@ const DrizzleAdapter = {
|
|
|
408
526
|
if (usedReturning) return row;
|
|
409
527
|
return await resolveMutation(finalQuery);
|
|
410
528
|
},
|
|
529
|
+
/**
|
|
530
|
+
* A nested call opens a savepoint inside the transaction already running
|
|
531
|
+
* rather than a second top-level one: on a `max: 1` pool that second one
|
|
532
|
+
* would wait on the connection the first holds, and on the single-connection
|
|
533
|
+
* drivers it would queue behind itself. An inner throw the outer callback
|
|
534
|
+
* catches therefore discards only the inner writes.
|
|
535
|
+
*/
|
|
411
536
|
async transaction(callback) {
|
|
412
537
|
const db = ensureDatabase();
|
|
413
538
|
if (typeof db.transaction !== "function") throw new Error("DrizzleAdapter: configured database does not support transactions.");
|
|
414
|
-
|
|
415
|
-
|
|
539
|
+
const store = await loadTransactionStore();
|
|
540
|
+
const ambient = store.getStore();
|
|
541
|
+
if (ambient && !ambient.settled) return ambient.nest(callback);
|
|
542
|
+
if (await awaitsItsCallback(db)) return runDriverTransaction(db.transaction.bind(db), store, callback);
|
|
543
|
+
return runOwnTransaction(db, store, callback);
|
|
416
544
|
}
|
|
417
545
|
};
|
|
418
546
|
//#endregion
|
|
419
547
|
//#region src/attributes.ts
|
|
548
|
+
const PROTOTYPE_KEYS = /* @__PURE__ */ new Set([
|
|
549
|
+
"__proto__",
|
|
550
|
+
"constructor",
|
|
551
|
+
"prototype"
|
|
552
|
+
]);
|
|
553
|
+
/**
|
|
554
|
+
* A computed field is written with `record[key] = …`, and `__proto__` as a key
|
|
555
|
+
* would rewrite the record's prototype rather than a column. The names come
|
|
556
|
+
* from a model's static definitions, so refusing them is a boot-time mistake
|
|
557
|
+
* surfacing at first use, not a runtime input check.
|
|
558
|
+
*/
|
|
559
|
+
function assertWritableKey(key, kind) {
|
|
560
|
+
if (PROTOTYPE_KEYS.has(key)) throw new Error(`An ${kind} cannot be named "${key}": that key would alter the record's prototype.`);
|
|
561
|
+
}
|
|
562
|
+
/** Writes the computed values onto `record`; each accessor sees the ones before it. */
|
|
563
|
+
function applyAccessorsInPlace(record, accessors) {
|
|
564
|
+
for (const key of Object.keys(accessors)) {
|
|
565
|
+
assertWritableKey(key, "accessor");
|
|
566
|
+
record[key] = accessors[key](record);
|
|
567
|
+
}
|
|
568
|
+
}
|
|
420
569
|
/** Apply accessors to a record, returning a new record with computed values. */
|
|
421
570
|
function applyAccessors(record, accessors) {
|
|
422
571
|
if (!accessors) return record;
|
|
423
|
-
|
|
424
|
-
if (keys.length === 0) return record;
|
|
572
|
+
if (Object.keys(accessors).length === 0) return record;
|
|
425
573
|
const result = { ...record };
|
|
426
|
-
|
|
574
|
+
applyAccessorsInPlace(result, accessors);
|
|
427
575
|
return result;
|
|
428
576
|
}
|
|
429
577
|
/** Apply mutators to data before persistence, returning a new object. */
|
|
@@ -432,7 +580,10 @@ function applyMutators(data, mutators) {
|
|
|
432
580
|
const keys = Object.keys(mutators);
|
|
433
581
|
if (keys.length === 0) return data;
|
|
434
582
|
const result = { ...data };
|
|
435
|
-
for (const key of keys)
|
|
583
|
+
for (const key of keys) {
|
|
584
|
+
assertWritableKey(key, "mutator");
|
|
585
|
+
if (Object.hasOwn(result, key)) result[key] = mutators[key](result[key], result);
|
|
586
|
+
}
|
|
436
587
|
return result;
|
|
437
588
|
}
|
|
438
589
|
//#endregion
|
|
@@ -517,16 +668,6 @@ var ModelNotFoundException = class extends Error {
|
|
|
517
668
|
//#endregion
|
|
518
669
|
//#region src/QueryBuilder.ts
|
|
519
670
|
/**
|
|
520
|
-
* Key for the prepared-payload update terminal. Exported for `Model` across
|
|
521
|
-
* the module boundary, but kept out of the package entry point.
|
|
522
|
-
*/
|
|
523
|
-
const PREPARED_UPDATE = Symbol("guren.orm.preparedUpdate");
|
|
524
|
-
/**
|
|
525
|
-
* Key for the global-scope seal. Exported for `Model` across the module
|
|
526
|
-
* boundary, but kept out of the package entry point.
|
|
527
|
-
*/
|
|
528
|
-
const SEAL_SCOPES = Symbol("guren.orm.sealScopes");
|
|
529
|
-
/**
|
|
530
671
|
* Fluent query builder for the Guren ORM. Thenable, so awaiting a builder
|
|
531
672
|
* resolves to the result of `get()`.
|
|
532
673
|
*
|
|
@@ -625,6 +766,11 @@ var QueryBuilder = class QueryBuilder {
|
|
|
625
766
|
this.options.offsetValue = n;
|
|
626
767
|
return this;
|
|
627
768
|
}
|
|
769
|
+
/**
|
|
770
|
+
* Narrows the row to these columns. The model's accessors are then skipped:
|
|
771
|
+
* one reading a column `fields` left out would fabricate a value from
|
|
772
|
+
* `undefined`. Casts still apply to the columns that are there.
|
|
773
|
+
*/
|
|
628
774
|
select(...fields) {
|
|
629
775
|
this.options.selectFields = [...fields];
|
|
630
776
|
return this;
|
|
@@ -641,7 +787,7 @@ var QueryBuilder = class QueryBuilder {
|
|
|
641
787
|
* callbacks, each run after the foreign-key filter on exactly the level its key
|
|
642
788
|
* names. Pitfalls: a top-level `orWhere()` ORs against the foreign-key filter
|
|
643
789
|
* (group it); `select()` must keep the relation's key column or the relation is
|
|
644
|
-
* empty; `limit()`
|
|
790
|
+
* empty; `limit()` caps the whole result set, not each parent's share.
|
|
645
791
|
*/
|
|
646
792
|
with(...relations) {
|
|
647
793
|
for (const rel of relations) if (typeof rel === "string") {
|
|
@@ -653,18 +799,28 @@ var QueryBuilder = class QueryBuilder {
|
|
|
653
799
|
return this;
|
|
654
800
|
}
|
|
655
801
|
async get() {
|
|
656
|
-
|
|
657
|
-
|
|
802
|
+
return this.fetch();
|
|
803
|
+
}
|
|
804
|
+
/**
|
|
805
|
+
* Runs the query and hands back the rows as the adapter read them. Symbol-keyed
|
|
806
|
+
* and never re-exported: a named public method here would be a supported way to
|
|
807
|
+
* read past a model's casts.
|
|
808
|
+
*/
|
|
809
|
+
async [RAW_RESULTS]() {
|
|
810
|
+
return this.fetchRaw();
|
|
811
|
+
}
|
|
812
|
+
/** The one read pipeline: rows, then eager loads, then the model's transforms. */
|
|
813
|
+
async fetch(overrides) {
|
|
814
|
+
const results = await this.fetchRaw(overrides);
|
|
815
|
+
const projected = (this.options.selectFields?.length ?? 0) > 0;
|
|
816
|
+
return this.modelClass[READ_TRANSFORMS](results, projected);
|
|
817
|
+
}
|
|
818
|
+
async fetchRaw(overrides) {
|
|
819
|
+
return this.loadEagerRelations(await this.executeQuery(overrides));
|
|
658
820
|
}
|
|
659
821
|
async first() {
|
|
660
822
|
if (this.filtersEvaporated()) return null;
|
|
661
|
-
|
|
662
|
-
this.options.limitValue = 1;
|
|
663
|
-
try {
|
|
664
|
-
return (await this.get())[0] ?? null;
|
|
665
|
-
} finally {
|
|
666
|
-
this.options.limitValue = prev;
|
|
667
|
-
}
|
|
823
|
+
return (await this.fetch({ limit: 1 }))[0] ?? null;
|
|
668
824
|
}
|
|
669
825
|
/** @throws ModelNotFoundException (404) if no record matches. */
|
|
670
826
|
async firstOrFail() {
|
|
@@ -678,6 +834,26 @@ var QueryBuilder = class QueryBuilder {
|
|
|
678
834
|
if (typeof advancedAdapter.countAdvanced === "function") return advancedAdapter.countAdvanced(this.table, this.effectiveConditions(), { trx: this.options.trx });
|
|
679
835
|
return (await this.executeQuery()).length;
|
|
680
836
|
}
|
|
837
|
+
/**
|
|
838
|
+
* @internal Row count per distinct value of `field`, as one grouped COUNT
|
|
839
|
+
* where the adapter issues it. Without `countByAdvanced` the rows are loaded
|
|
840
|
+
* and counted here, narrowed to that one column where the adapter can project
|
|
841
|
+
* and whole where it cannot.
|
|
842
|
+
*/
|
|
843
|
+
async countBy(field) {
|
|
844
|
+
const advancedAdapter = this.adapter;
|
|
845
|
+
const counts = /* @__PURE__ */ new Map();
|
|
846
|
+
if (typeof advancedAdapter.countByAdvanced === "function") {
|
|
847
|
+
const rows = await advancedAdapter.countByAdvanced(this.table, field, this.effectiveConditions(), { trx: this.options.trx });
|
|
848
|
+
for (const { key, count } of rows) counts.set(key, count);
|
|
849
|
+
return counts;
|
|
850
|
+
}
|
|
851
|
+
for (const row of await this.executeQuery({ select: [field] })) {
|
|
852
|
+
const key = row[field];
|
|
853
|
+
counts.set(key, (counts.get(key) ?? 0) + 1);
|
|
854
|
+
}
|
|
855
|
+
return counts;
|
|
856
|
+
}
|
|
681
857
|
async paginate(pageOrOptions = 1, perPageArg = 15) {
|
|
682
858
|
const page = typeof pageOrOptions === "object" ? pageOrOptions.page ?? 1 : pageOrOptions;
|
|
683
859
|
const perPage = typeof pageOrOptions === "object" ? pageOrOptions.perPage ?? 15 : perPageArg;
|
|
@@ -687,17 +863,10 @@ var QueryBuilder = class QueryBuilder {
|
|
|
687
863
|
const totalPages = total === 0 ? 1 : Math.max(1, Math.ceil(total / sanitizedPerPage));
|
|
688
864
|
const currentPage = Math.min(sanitizedPage, totalPages);
|
|
689
865
|
const offset = (currentPage - 1) * sanitizedPerPage;
|
|
690
|
-
const
|
|
691
|
-
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
let data;
|
|
695
|
-
try {
|
|
696
|
-
data = await this.get();
|
|
697
|
-
} finally {
|
|
698
|
-
this.options.limitValue = prevLimit;
|
|
699
|
-
this.options.offsetValue = prevOffset;
|
|
700
|
-
}
|
|
866
|
+
const data = await this.fetch({
|
|
867
|
+
limit: sanitizedPerPage,
|
|
868
|
+
offset
|
|
869
|
+
});
|
|
701
870
|
const from = total === 0 ? 0 : offset + 1;
|
|
702
871
|
const to = total === 0 ? 0 : offset + data.length;
|
|
703
872
|
return {
|
|
@@ -844,21 +1013,23 @@ var QueryBuilder = class QueryBuilder {
|
|
|
844
1013
|
value
|
|
845
1014
|
});
|
|
846
1015
|
}
|
|
847
|
-
async executeQuery() {
|
|
1016
|
+
async executeQuery(overrides = {}) {
|
|
848
1017
|
const advancedAdapter = this.adapter;
|
|
1018
|
+
const limit = overrides.limit ?? this.options.limitValue;
|
|
1019
|
+
const offset = overrides.offset ?? this.options.offsetValue;
|
|
849
1020
|
if (typeof advancedAdapter.findManyAdvanced === "function") return advancedAdapter.findManyAdvanced(this.table, this.effectiveConditions(), {
|
|
850
1021
|
orderBy: this.options.orderBy.length > 0 ? this.options.orderBy : void 0,
|
|
851
|
-
limit
|
|
852
|
-
offset
|
|
853
|
-
select: this.options.selectFields
|
|
1022
|
+
limit,
|
|
1023
|
+
offset,
|
|
1024
|
+
select: overrides.select ?? this.options.selectFields
|
|
854
1025
|
}, { trx: this.options.trx });
|
|
855
1026
|
const simpleWhere = this.toSimpleWhereClause();
|
|
856
1027
|
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.`);
|
|
857
1028
|
return this.adapter.findMany(this.table, {
|
|
858
1029
|
where: simpleWhere ?? void 0,
|
|
859
1030
|
orderBy: this.options.orderBy.length > 0 ? this.options.orderBy : void 0,
|
|
860
|
-
limit
|
|
861
|
-
offset
|
|
1031
|
+
limit,
|
|
1032
|
+
offset
|
|
862
1033
|
}, { trx: this.options.trx });
|
|
863
1034
|
}
|
|
864
1035
|
/** Null when the conditions are too complex for a basic adapter's WhereClause. */
|
|
@@ -895,8 +1066,10 @@ var QueryBuilder = class QueryBuilder {
|
|
|
895
1066
|
/** Serializes a record for JSON output: appends, then visible/hidden filtering. */
|
|
896
1067
|
function serializeRecord(record, options) {
|
|
897
1068
|
let result = { ...record };
|
|
898
|
-
if (options.appends && options.accessors) {
|
|
899
|
-
|
|
1069
|
+
if (options.appends && options.accessors) for (const key of options.appends) {
|
|
1070
|
+
if (key in result) continue;
|
|
1071
|
+
const accessor = options.accessors[key];
|
|
1072
|
+
if (accessor) result[key] = accessor(result);
|
|
900
1073
|
}
|
|
901
1074
|
if (options.visible && options.visible.length > 0) {
|
|
902
1075
|
const filtered = {};
|
|
@@ -932,6 +1105,8 @@ var MassAssignmentException = class extends Error {
|
|
|
932
1105
|
this.reason = reason;
|
|
933
1106
|
}
|
|
934
1107
|
};
|
|
1108
|
+
//#endregion
|
|
1109
|
+
//#region src/Model.ts
|
|
935
1110
|
/**
|
|
936
1111
|
* ActiveRecord-style base class for database models. Prefer `defineModel(table)`,
|
|
937
1112
|
* which infers the type markers; extending `Model` directly means setting
|
|
@@ -1092,38 +1267,29 @@ var Model = class Model {
|
|
|
1092
1267
|
if (!castDefs) return record;
|
|
1093
1268
|
if (!Object.keys(castDefs).some((key) => key in record && record[key] != null)) return record;
|
|
1094
1269
|
const result = { ...record };
|
|
1095
|
-
|
|
1096
|
-
if (!(field in result)) continue;
|
|
1097
|
-
const value = result[field];
|
|
1098
|
-
if (value == null) continue;
|
|
1099
|
-
switch (castType) {
|
|
1100
|
-
case "json":
|
|
1101
|
-
if (typeof value === "string") try {
|
|
1102
|
-
result[field] = JSON.parse(value);
|
|
1103
|
-
} catch {}
|
|
1104
|
-
break;
|
|
1105
|
-
case "date":
|
|
1106
|
-
if (!(value instanceof Date)) result[field] = new Date(value);
|
|
1107
|
-
break;
|
|
1108
|
-
case "boolean":
|
|
1109
|
-
result[field] = Boolean(value);
|
|
1110
|
-
break;
|
|
1111
|
-
case "number":
|
|
1112
|
-
result[field] = Number(value);
|
|
1113
|
-
break;
|
|
1114
|
-
case "string": result[field] = String(value);
|
|
1115
|
-
}
|
|
1116
|
-
}
|
|
1270
|
+
castInPlace(result, castDefs);
|
|
1117
1271
|
return result;
|
|
1118
1272
|
}
|
|
1119
|
-
/**
|
|
1273
|
+
/** The one read-transform pass for a record, in order: casts then accessors. */
|
|
1120
1274
|
static applyReadTransforms(record) {
|
|
1275
|
+
if (!this.casts && !this.accessors) return record;
|
|
1121
1276
|
let result = record;
|
|
1122
1277
|
if (this.casts) result = this.applyCasts(result);
|
|
1123
1278
|
if (this.accessors) result = applyAccessors(result, this.accessors);
|
|
1124
1279
|
return result;
|
|
1125
1280
|
}
|
|
1126
1281
|
/**
|
|
1282
|
+
* The same pass over a result set. Symbol-keyed for `QueryBuilder` across the
|
|
1283
|
+
* module boundary, and kept out of the package entry point. `projected` marks
|
|
1284
|
+
* a row `select()` narrowed: an accessor there would read columns that are not
|
|
1285
|
+
* on it, while `applyCasts` already skips an absent one.
|
|
1286
|
+
*/
|
|
1287
|
+
static [READ_TRANSFORMS](records, projected = false) {
|
|
1288
|
+
if (projected) return this.casts ? records.map((record) => this.applyCasts(record)) : records;
|
|
1289
|
+
if (!this.casts && !this.accessors) return records;
|
|
1290
|
+
return records.map((record) => this.applyReadTransforms(record));
|
|
1291
|
+
}
|
|
1292
|
+
/**
|
|
1127
1293
|
* In order: `deniedFields()` throws, checked on the raw input so no later
|
|
1128
1294
|
* rule can swallow them; `id` is stripped silently; then, with `fillable`
|
|
1129
1295
|
* set, anything outside it throws.
|
|
@@ -1187,11 +1353,14 @@ var Model = class Model {
|
|
|
1187
1353
|
return this.table;
|
|
1188
1354
|
}
|
|
1189
1355
|
static async all(queryOptions) {
|
|
1190
|
-
|
|
1191
|
-
|
|
1192
|
-
|
|
1193
|
-
|
|
1194
|
-
|
|
1356
|
+
return this.newQuery(queryOptions).get();
|
|
1357
|
+
}
|
|
1358
|
+
/**
|
|
1359
|
+
* The rows a relation load joins against, as the adapter read them: a cast on
|
|
1360
|
+
* the parent's key column would stop the child rows from matching it.
|
|
1361
|
+
*/
|
|
1362
|
+
static async rawRecords(where, queryOptions) {
|
|
1363
|
+
return this.newQuery(queryOptions).where(where ?? {})[RAW_RESULTS]();
|
|
1195
1364
|
}
|
|
1196
1365
|
static async find(id, key = "id", queryOptions) {
|
|
1197
1366
|
if (id === void 0) return null;
|
|
@@ -1199,8 +1368,7 @@ var Model = class Model {
|
|
|
1199
1368
|
const table = this.resolveTable();
|
|
1200
1369
|
const where = { [key]: id };
|
|
1201
1370
|
const record = await this.getAdapter().findUnique(table, where, queryOptions);
|
|
1202
|
-
|
|
1203
|
-
return record;
|
|
1371
|
+
return record && this.applyReadTransforms(record);
|
|
1204
1372
|
}
|
|
1205
1373
|
/** @throws ModelNotFoundException (404) when no record matches. */
|
|
1206
1374
|
static async findOrFail(id, key = "id", queryOptions) {
|
|
@@ -1237,8 +1405,7 @@ var Model = class Model {
|
|
|
1237
1405
|
where,
|
|
1238
1406
|
limit: 1
|
|
1239
1407
|
}, queryOptions))[0] ?? null;
|
|
1240
|
-
|
|
1241
|
-
return record;
|
|
1408
|
+
return record && this.applyReadTransforms(record);
|
|
1242
1409
|
}
|
|
1243
1410
|
static where(fieldOrConditions, operatorOrValue, value) {
|
|
1244
1411
|
const builder = this.newQuery();
|
|
@@ -1412,67 +1579,38 @@ var Model = class Model {
|
|
|
1412
1579
|
const table = this.resolveTable();
|
|
1413
1580
|
const options = { orderBy };
|
|
1414
1581
|
if (where && Object.keys(where).length > 0) options.where = where;
|
|
1415
|
-
|
|
1582
|
+
const records = await this.getAdapter().findMany(table, options, queryOptions);
|
|
1583
|
+
return this[READ_TRANSFORMS](records);
|
|
1416
1584
|
}
|
|
1417
1585
|
/**
|
|
1418
1586
|
* @example
|
|
1419
1587
|
* await User.paginate({ page: 2, perPage: 20, where: { status: 'active' } })
|
|
1420
1588
|
*/
|
|
1421
1589
|
static async paginate(options = {}, queryOptions) {
|
|
1422
|
-
|
|
1423
|
-
|
|
1424
|
-
|
|
1425
|
-
|
|
1426
|
-
|
|
1427
|
-
|
|
1428
|
-
|
|
1429
|
-
|
|
1430
|
-
|
|
1431
|
-
|
|
1432
|
-
|
|
1433
|
-
const
|
|
1434
|
-
|
|
1435
|
-
|
|
1436
|
-
|
|
1437
|
-
let total = 0;
|
|
1438
|
-
if (typeof adapter.count === "function") total = await adapter.count(table, options.where, queryOptions);
|
|
1439
|
-
else total = (options.where ? await this.newQuery(queryOptions).where(options.where).get() : await this.all(queryOptions)).length;
|
|
1440
|
-
const totalPages = total === 0 ? 1 : Math.max(1, Math.ceil(total / perPage));
|
|
1441
|
-
const currentPage = Math.min(sanitizedPage, totalPages);
|
|
1442
|
-
const offset = (currentPage - 1) * perPage;
|
|
1443
|
-
const orderByClause = options.orderBy ? normalizeOrderBy(options.orderBy) : void 0;
|
|
1444
|
-
const findOptions = {
|
|
1445
|
-
where: options.where,
|
|
1446
|
-
orderBy: orderByClause,
|
|
1447
|
-
limit: perPage,
|
|
1448
|
-
offset
|
|
1449
|
-
};
|
|
1450
|
-
const data = await adapter.findMany(table, findOptions, queryOptions);
|
|
1451
|
-
const from = total === 0 ? 0 : offset + 1;
|
|
1452
|
-
const to = total === 0 ? 0 : offset + data.length;
|
|
1453
|
-
return {
|
|
1454
|
-
data,
|
|
1455
|
-
meta: {
|
|
1456
|
-
total,
|
|
1457
|
-
perPage,
|
|
1458
|
-
currentPage,
|
|
1459
|
-
totalPages,
|
|
1460
|
-
hasMore: currentPage < totalPages,
|
|
1461
|
-
from,
|
|
1462
|
-
to: Math.min(to, total)
|
|
1463
|
-
}
|
|
1464
|
-
};
|
|
1590
|
+
return this.paginationQuery(options, queryOptions).paginate({
|
|
1591
|
+
page: options.page,
|
|
1592
|
+
perPage: options.perPage
|
|
1593
|
+
});
|
|
1594
|
+
}
|
|
1595
|
+
/**
|
|
1596
|
+
* The builder owns pagination: the count matters as much as the rows, and a
|
|
1597
|
+
* second sanitise-count-slice here would agree with the builder's by
|
|
1598
|
+
* inspection rather than by construction.
|
|
1599
|
+
*/
|
|
1600
|
+
static paginationQuery(options, queryOptions) {
|
|
1601
|
+
const builder = this.newQuery(queryOptions);
|
|
1602
|
+
if (options.where && Object.keys(options.where).length > 0) builder.where(options.where);
|
|
1603
|
+
if (options.orderBy) for (const clause of normalizeOrderBy(options.orderBy)) builder.orderBy(clause.column, clause.direction);
|
|
1604
|
+
return builder;
|
|
1465
1605
|
}
|
|
1466
1606
|
static async withPaginate(relations, options = {}, queryOptions) {
|
|
1467
|
-
const
|
|
1607
|
+
const builder = this.paginationQuery(options, queryOptions);
|
|
1468
1608
|
const relationList = normalizeRelations(relations);
|
|
1469
|
-
if (relationList.length
|
|
1470
|
-
|
|
1471
|
-
|
|
1472
|
-
|
|
1473
|
-
|
|
1474
|
-
meta: result.meta
|
|
1475
|
-
};
|
|
1609
|
+
if (relationList.length > 0) builder.with(...relationList);
|
|
1610
|
+
return builder.paginate({
|
|
1611
|
+
page: options.page,
|
|
1612
|
+
perPage: options.perPage
|
|
1613
|
+
});
|
|
1476
1614
|
}
|
|
1477
1615
|
static async create(data, writeOptions) {
|
|
1478
1616
|
return this.runCreate(data, writeOptions, true);
|
|
@@ -1509,8 +1647,7 @@ var Model = class Model {
|
|
|
1509
1647
|
await executeObservers(observers, "created", resultData);
|
|
1510
1648
|
await executeObservers(observers, "saved", resultData);
|
|
1511
1649
|
}
|
|
1512
|
-
|
|
1513
|
-
return result;
|
|
1650
|
+
return this.applyReadTransforms(result);
|
|
1514
1651
|
}
|
|
1515
1652
|
static async update(where, data, writeOptions) {
|
|
1516
1653
|
return this.runUpdate(where, data, writeOptions, true);
|
|
@@ -1550,8 +1687,7 @@ var Model = class Model {
|
|
|
1550
1687
|
await executeObservers(observers, "updated", resultData);
|
|
1551
1688
|
await executeObservers(observers, "saved", resultData);
|
|
1552
1689
|
}
|
|
1553
|
-
|
|
1554
|
-
return result;
|
|
1690
|
+
return this.applyReadTransforms(result);
|
|
1555
1691
|
}
|
|
1556
1692
|
static async delete(where, writeOptions) {
|
|
1557
1693
|
const table = this.resolveTable();
|
|
@@ -1588,71 +1724,35 @@ var Model = class Model {
|
|
|
1588
1724
|
return fallbackBuilder.from(table);
|
|
1589
1725
|
}
|
|
1590
1726
|
static async with(relations, where, queryOptions) {
|
|
1591
|
-
const records =
|
|
1592
|
-
if (!records.length) return records;
|
|
1727
|
+
const records = await this.rawRecords(where, queryOptions);
|
|
1593
1728
|
const relationList = normalizeRelations(relations);
|
|
1594
|
-
if (relationList.length === 0) return records;
|
|
1595
|
-
|
|
1596
|
-
|
|
1597
|
-
return copies;
|
|
1729
|
+
if (records.length === 0 || relationList.length === 0) return this[READ_TRANSFORMS](records);
|
|
1730
|
+
await this.loadRelationsInto(records, relationList, queryOptions);
|
|
1731
|
+
return this[READ_TRANSFORMS](records);
|
|
1598
1732
|
}
|
|
1599
1733
|
static async withCount(relations, where, queryOptions) {
|
|
1600
|
-
const records =
|
|
1601
|
-
if (
|
|
1734
|
+
const records = await this.rawRecords(where, queryOptions);
|
|
1735
|
+
if (records.length === 0) return this[READ_TRANSFORMS](records);
|
|
1602
1736
|
const relationList = normalizeRelations(relations);
|
|
1603
|
-
const
|
|
1604
|
-
|
|
1605
|
-
return copies;
|
|
1737
|
+
for (const relationName of relationList) await this.loadRelationCountInto(records, relationName, queryOptions);
|
|
1738
|
+
return this[READ_TRANSFORMS](records);
|
|
1606
1739
|
}
|
|
1607
1740
|
/** @internal Attaches a `${name}Count` field for one relation. */
|
|
1608
1741
|
static async loadRelationCountInto(records, relationName, queryOptions) {
|
|
1609
1742
|
if (relationName.includes(".")) throw new Error(`${this.name}: withCount does not support nested relation "${relationName}".`);
|
|
1610
1743
|
const definition = this.getRelationDefinition(relationName);
|
|
1611
1744
|
if (!definition) throw new Error(`${this.name}: unknown relation "${relationName}".`);
|
|
1745
|
+
const plan = relationCountPlan(definition, this.name);
|
|
1746
|
+
if (!plan) throw new Error(`${this.name}: withCount does not support ${definition.type} relation "${relationName}".`);
|
|
1747
|
+
const related = await resolveModelReference(plan.related);
|
|
1748
|
+
const keys = distinctKeys(records, plan.parentKey);
|
|
1749
|
+
const size = maxInListSize(related.getAdapter());
|
|
1750
|
+
const counts = plan.presenceOnly ? await countOwnersPresent(related, plan.childKey, keys, size, queryOptions) : await countByChunks(keys, size, (chunk) => related.newQuery(queryOptions).where({
|
|
1751
|
+
...plan.where,
|
|
1752
|
+
[plan.childKey]: chunk
|
|
1753
|
+
}).countBy(plan.childKey));
|
|
1612
1754
|
const countField = `${relationName}Count`;
|
|
1613
|
-
|
|
1614
|
-
case "hasMany":
|
|
1615
|
-
case "hasOne": {
|
|
1616
|
-
const related = await resolveModelReference(definition.related);
|
|
1617
|
-
const { foreignKey, localKey } = definition;
|
|
1618
|
-
const values = Array.from(new Set(records.map((record) => record[localKey]).filter((value) => value != null)));
|
|
1619
|
-
const counts = /* @__PURE__ */ new Map();
|
|
1620
|
-
if (values.length > 0) {
|
|
1621
|
-
const relatedRecords = await related.newQuery(queryOptions).where({ [foreignKey]: values });
|
|
1622
|
-
for (const item of relatedRecords) {
|
|
1623
|
-
const key = item[foreignKey];
|
|
1624
|
-
counts.set(key, (counts.get(key) ?? 0) + 1);
|
|
1625
|
-
}
|
|
1626
|
-
}
|
|
1627
|
-
for (const record of records) record[countField] = counts.get(record[localKey]) ?? 0;
|
|
1628
|
-
return;
|
|
1629
|
-
}
|
|
1630
|
-
case "morphMany": {
|
|
1631
|
-
const withRelation = records.map((record) => ({ ...record }));
|
|
1632
|
-
await this.loadRelationInto(withRelation, relationName, queryOptions);
|
|
1633
|
-
for (const [index, record] of records.entries()) {
|
|
1634
|
-
const value = withRelation[index]?.[relationName];
|
|
1635
|
-
record[countField] = Array.isArray(value) ? value.length : 0;
|
|
1636
|
-
}
|
|
1637
|
-
return;
|
|
1638
|
-
}
|
|
1639
|
-
case "belongsTo": {
|
|
1640
|
-
const related = await resolveModelReference(definition.related);
|
|
1641
|
-
const { foreignKey, ownerKey } = definition;
|
|
1642
|
-
const values = Array.from(new Set(records.map((record) => record[foreignKey]).filter((value) => value != null)));
|
|
1643
|
-
const ownerKeys = /* @__PURE__ */ new Set();
|
|
1644
|
-
if (values.length > 0) {
|
|
1645
|
-
const owners = await related.newQuery(queryOptions).where({ [ownerKey]: values });
|
|
1646
|
-
for (const owner of owners) ownerKeys.add(owner[ownerKey]);
|
|
1647
|
-
}
|
|
1648
|
-
for (const record of records) {
|
|
1649
|
-
const key = record[foreignKey];
|
|
1650
|
-
record[countField] = key != null && ownerKeys.has(key) ? 1 : 0;
|
|
1651
|
-
}
|
|
1652
|
-
return;
|
|
1653
|
-
}
|
|
1654
|
-
default: throw new Error(`${this.name}: withCount does not support ${definition.type} relation "${relationName}".`);
|
|
1655
|
-
}
|
|
1755
|
+
for (const record of records) record[countField] = counts.get(record[plan.parentKey]) ?? 0;
|
|
1656
1756
|
}
|
|
1657
1757
|
/**
|
|
1658
1758
|
* @internal Used by QueryBuilder for eager loading. Paths are grouped by head
|
|
@@ -1691,29 +1791,30 @@ var Model = class Model {
|
|
|
1691
1791
|
if (!definition) throw new Error(`${this.name}: unknown relation "${head}".`);
|
|
1692
1792
|
const currentPath = pathPrefix ? `${pathPrefix}.${head}` : head;
|
|
1693
1793
|
const constraint = constraints?.get(currentPath);
|
|
1794
|
+
let projected = false;
|
|
1694
1795
|
switch (definition.type) {
|
|
1695
1796
|
case "hasMany":
|
|
1696
|
-
await this.loadHasMany(records, definition, queryOptions, constraint);
|
|
1797
|
+
projected = await this.loadHasMany(records, definition, queryOptions, constraint);
|
|
1697
1798
|
break;
|
|
1698
1799
|
case "hasOne":
|
|
1699
|
-
await this.loadHasOne(records, definition, queryOptions, constraint);
|
|
1800
|
+
projected = await this.loadHasOne(records, definition, queryOptions, constraint);
|
|
1700
1801
|
break;
|
|
1701
1802
|
case "belongsTo":
|
|
1702
|
-
await this.loadBelongsTo(records, definition, queryOptions, constraint);
|
|
1803
|
+
projected = await this.loadBelongsTo(records, definition, queryOptions, constraint);
|
|
1703
1804
|
break;
|
|
1704
1805
|
case "belongsToMany":
|
|
1705
|
-
await this.loadBelongsToMany(records, definition, queryOptions, constraint);
|
|
1806
|
+
projected = await this.loadBelongsToMany(records, definition, queryOptions, constraint);
|
|
1706
1807
|
break;
|
|
1707
1808
|
case "hasManyThrough":
|
|
1708
|
-
await this.loadHasManyThrough(records, definition, queryOptions, constraint);
|
|
1809
|
+
projected = await this.loadHasManyThrough(records, definition, queryOptions, constraint);
|
|
1709
1810
|
break;
|
|
1710
1811
|
case "morphMany":
|
|
1711
|
-
await this.loadMorphMany(records, definition, queryOptions, constraint);
|
|
1812
|
+
projected = await this.loadMorphMany(records, definition, queryOptions, constraint);
|
|
1712
1813
|
break;
|
|
1713
1814
|
case "morphTo": await this.loadMorphTo(records, definition, queryOptions, constraint);
|
|
1714
1815
|
}
|
|
1715
|
-
if (tails.length ===
|
|
1716
|
-
if (definition.type === "morphTo")
|
|
1816
|
+
if (tails.length > 0 && definition.type === "morphTo") throw new Error(`${this.name}: nested eager loading through morphTo relation "${head}" is not supported.`);
|
|
1817
|
+
if (definition.type === "morphTo") return;
|
|
1717
1818
|
const children = [];
|
|
1718
1819
|
const seen = /* @__PURE__ */ new Set();
|
|
1719
1820
|
for (const record of records) {
|
|
@@ -1725,29 +1826,32 @@ var Model = class Model {
|
|
|
1725
1826
|
}
|
|
1726
1827
|
}
|
|
1727
1828
|
if (children.length === 0) return;
|
|
1728
|
-
|
|
1829
|
+
const related = await resolveModelReference(definition.related);
|
|
1830
|
+
if (tails.length > 0) await related.loadRelationsInto(children, tails, queryOptions, constraints, currentPath);
|
|
1831
|
+
applyRelatedReadTransforms(related, children, projected);
|
|
1729
1832
|
}
|
|
1730
1833
|
static async loadHasMany(records, definition, queryOptions, constraint) {
|
|
1731
1834
|
const { foreignKey, localKey, name } = definition;
|
|
1732
|
-
|
|
1835
|
+
return loadRelationData(records, name, await resolveModelReference(definition.related), localKey, foreignKey, true, queryOptions, constraint);
|
|
1733
1836
|
}
|
|
1734
1837
|
static async loadHasOne(records, definition, queryOptions, constraint) {
|
|
1735
1838
|
const { foreignKey, localKey, name } = definition;
|
|
1736
|
-
|
|
1839
|
+
return loadRelationData(records, name, await resolveModelReference(definition.related), localKey, foreignKey, false, queryOptions, constraint);
|
|
1737
1840
|
}
|
|
1738
1841
|
static async loadBelongsTo(records, definition, queryOptions, constraint) {
|
|
1739
1842
|
const { foreignKey, ownerKey, name } = definition;
|
|
1740
|
-
|
|
1843
|
+
return loadRelationData(records, name, await resolveModelReference(definition.related), foreignKey, ownerKey, false, queryOptions, constraint);
|
|
1741
1844
|
}
|
|
1742
1845
|
static async loadBelongsToMany(records, definition, queryOptions, constraint) {
|
|
1743
1846
|
const { pivotTable, foreignPivotKey, relatedPivotKey, parentKey, relatedKey, name } = definition;
|
|
1744
1847
|
const related = await resolveModelReference(definition.related);
|
|
1745
|
-
const parentValues =
|
|
1848
|
+
const parentValues = distinctKeys(records, parentKey);
|
|
1746
1849
|
if (parentValues.length === 0) {
|
|
1747
1850
|
for (const record of records) record[name] = [];
|
|
1748
|
-
return;
|
|
1851
|
+
return false;
|
|
1749
1852
|
}
|
|
1750
|
-
const
|
|
1853
|
+
const adapter = this.getAdapter();
|
|
1854
|
+
const pivotRows = await loadByChunks(parentValues, maxInListSize(adapter), (chunk) => adapter.findMany(pivotTable, { where: { [foreignPivotKey]: chunk } }, queryOptions));
|
|
1751
1855
|
const pivotMap = /* @__PURE__ */ new Map();
|
|
1752
1856
|
const allRelatedIds = /* @__PURE__ */ new Set();
|
|
1753
1857
|
for (const row of pivotRows) {
|
|
@@ -1759,9 +1863,9 @@ var Model = class Model {
|
|
|
1759
1863
|
}
|
|
1760
1864
|
if (allRelatedIds.size === 0) {
|
|
1761
1865
|
for (const record of records) record[name] = [];
|
|
1762
|
-
return;
|
|
1866
|
+
return false;
|
|
1763
1867
|
}
|
|
1764
|
-
const relatedRecords = await
|
|
1868
|
+
const { records: relatedRecords, projected } = await loadRelatedRecords(related, Array.from(allRelatedIds), (chunk) => ({ [relatedKey]: chunk }), queryOptions, constraint);
|
|
1765
1869
|
const relatedMap = /* @__PURE__ */ new Map();
|
|
1766
1870
|
for (const item of relatedRecords) relatedMap.set(item[relatedKey], { ...item });
|
|
1767
1871
|
for (const record of records) {
|
|
@@ -1772,17 +1876,18 @@ var Model = class Model {
|
|
|
1772
1876
|
}
|
|
1773
1877
|
record[name] = (pivotMap.get(pk) ?? []).map((id) => relatedMap.get(id)).filter((item) => item != null);
|
|
1774
1878
|
}
|
|
1879
|
+
return projected;
|
|
1775
1880
|
}
|
|
1776
1881
|
static async loadHasManyThrough(records, definition, queryOptions, constraint) {
|
|
1777
1882
|
const { firstKey, secondKey, localKey, secondLocalKey, name } = definition;
|
|
1778
1883
|
const related = await resolveModelReference(definition.related);
|
|
1779
1884
|
const through = await resolveModelReference(definition.through);
|
|
1780
|
-
const localValues =
|
|
1885
|
+
const localValues = distinctKeys(records, localKey);
|
|
1781
1886
|
if (localValues.length === 0) {
|
|
1782
1887
|
for (const record of records) record[name] = [];
|
|
1783
|
-
return;
|
|
1888
|
+
return false;
|
|
1784
1889
|
}
|
|
1785
|
-
const throughRecords = await through.newQuery(queryOptions).where({ [firstKey]:
|
|
1890
|
+
const throughRecords = await loadByChunks(localValues, maxInListSize(through.getAdapter()), (chunk) => through.newQuery(queryOptions).where({ [firstKey]: chunk })[RAW_RESULTS]());
|
|
1786
1891
|
const throughMap = /* @__PURE__ */ new Map();
|
|
1787
1892
|
const allThroughIds = /* @__PURE__ */ new Set();
|
|
1788
1893
|
for (const row of throughRecords) {
|
|
@@ -1794,9 +1899,9 @@ var Model = class Model {
|
|
|
1794
1899
|
}
|
|
1795
1900
|
if (allThroughIds.size === 0) {
|
|
1796
1901
|
for (const record of records) record[name] = [];
|
|
1797
|
-
return;
|
|
1902
|
+
return false;
|
|
1798
1903
|
}
|
|
1799
|
-
const relatedRecords = await
|
|
1904
|
+
const { records: relatedRecords, projected } = await loadRelatedRecords(related, Array.from(allThroughIds), (chunk) => ({ [secondKey]: chunk }), queryOptions, constraint);
|
|
1800
1905
|
const relatedByKey = /* @__PURE__ */ new Map();
|
|
1801
1906
|
for (const item of relatedRecords) {
|
|
1802
1907
|
const key = item[secondKey];
|
|
@@ -1817,6 +1922,7 @@ var Model = class Model {
|
|
|
1817
1922
|
}
|
|
1818
1923
|
record[name] = items;
|
|
1819
1924
|
}
|
|
1925
|
+
return projected;
|
|
1820
1926
|
}
|
|
1821
1927
|
static async loadMorphMany(records, definition, queryOptions, constraint) {
|
|
1822
1928
|
const { morphName, localKey, name } = definition;
|
|
@@ -1824,15 +1930,15 @@ var Model = class Model {
|
|
|
1824
1930
|
const typeColumn = `${morphName}Type`;
|
|
1825
1931
|
const idColumn = `${morphName}Id`;
|
|
1826
1932
|
const parentType = this.name;
|
|
1827
|
-
const localValues =
|
|
1933
|
+
const localValues = distinctKeys(records, localKey);
|
|
1828
1934
|
if (localValues.length === 0) {
|
|
1829
1935
|
for (const record of records) record[name] = [];
|
|
1830
|
-
return;
|
|
1936
|
+
return false;
|
|
1831
1937
|
}
|
|
1832
|
-
const allRelated = await
|
|
1938
|
+
const { records: allRelated, projected } = await loadRelatedRecords(related, localValues, (chunk) => ({
|
|
1833
1939
|
[typeColumn]: parentType,
|
|
1834
|
-
[idColumn]:
|
|
1835
|
-
}), constraint);
|
|
1940
|
+
[idColumn]: chunk
|
|
1941
|
+
}), queryOptions, constraint);
|
|
1836
1942
|
const map = /* @__PURE__ */ new Map();
|
|
1837
1943
|
for (const item of allRelated) {
|
|
1838
1944
|
if (item[typeColumn] !== parentType) continue;
|
|
@@ -1844,6 +1950,7 @@ var Model = class Model {
|
|
|
1844
1950
|
const key = record[localKey];
|
|
1845
1951
|
record[name] = key != null ? map.get(key) ?? [] : [];
|
|
1846
1952
|
}
|
|
1953
|
+
return projected;
|
|
1847
1954
|
}
|
|
1848
1955
|
static async loadMorphTo(records, definition, queryOptions, constraint) {
|
|
1849
1956
|
const { morphName, name } = definition;
|
|
@@ -1862,10 +1969,10 @@ var Model = class Model {
|
|
|
1862
1969
|
for (const [type, ids] of byType) {
|
|
1863
1970
|
const modelClass = morphMap[type];
|
|
1864
1971
|
if (!modelClass) continue;
|
|
1865
|
-
const
|
|
1866
|
-
const results = await applyEagerConstraint(modelClass.newQuery(queryOptions).where({ id: uniqueIds }), constraint);
|
|
1972
|
+
const { records: results, projected } = await loadRelatedRecords(modelClass, Array.from(new Set(ids)), (chunk) => ({ id: chunk }), queryOptions, constraint);
|
|
1867
1973
|
const idMap = /* @__PURE__ */ new Map();
|
|
1868
1974
|
for (const r of results) idMap.set(r.id, { ...r });
|
|
1975
|
+
applyRelatedReadTransforms(modelClass, Array.from(idMap.values()), projected);
|
|
1869
1976
|
resolved.set(type, idMap);
|
|
1870
1977
|
}
|
|
1871
1978
|
for (const record of records) {
|
|
@@ -1879,23 +1986,54 @@ var Model = class Model {
|
|
|
1879
1986
|
}
|
|
1880
1987
|
}
|
|
1881
1988
|
};
|
|
1989
|
+
/** The cast switch, written onto `target`. */
|
|
1990
|
+
function castInPlace(target, castDefs) {
|
|
1991
|
+
for (const [field, castType] of Object.entries(castDefs)) {
|
|
1992
|
+
if (!(field in target)) continue;
|
|
1993
|
+
const value = target[field];
|
|
1994
|
+
if (value == null) continue;
|
|
1995
|
+
switch (castType) {
|
|
1996
|
+
case "json":
|
|
1997
|
+
if (typeof value === "string") try {
|
|
1998
|
+
target[field] = JSON.parse(value);
|
|
1999
|
+
} catch {}
|
|
2000
|
+
break;
|
|
2001
|
+
case "date":
|
|
2002
|
+
if (!(value instanceof Date)) target[field] = new Date(value);
|
|
2003
|
+
break;
|
|
2004
|
+
case "boolean":
|
|
2005
|
+
target[field] = Boolean(value);
|
|
2006
|
+
break;
|
|
2007
|
+
case "number":
|
|
2008
|
+
target[field] = Number(value);
|
|
2009
|
+
break;
|
|
2010
|
+
case "string": target[field] = String(value);
|
|
2011
|
+
}
|
|
2012
|
+
}
|
|
2013
|
+
}
|
|
1882
2014
|
/**
|
|
1883
|
-
*
|
|
1884
|
-
*
|
|
1885
|
-
*
|
|
1886
|
-
*
|
|
2015
|
+
* Written onto the records rather than onto copies: the parent rows hold them
|
|
2016
|
+
* by reference, and a nested loader has already keyed its own rows on them.
|
|
2017
|
+
* Keep in step with `[READ_TRANSFORMS]`: same casts-then-accessors order, and
|
|
2018
|
+
* the same rule that `projected` rows (a constraint's `select()` narrowed them)
|
|
2019
|
+
* skip the accessors, which would read a column that is not on them.
|
|
1887
2020
|
*/
|
|
1888
|
-
|
|
1889
|
-
|
|
1890
|
-
|
|
2021
|
+
function applyRelatedReadTransforms(related, records, projected) {
|
|
2022
|
+
const casts = related.casts;
|
|
2023
|
+
const accessors = projected ? void 0 : related.accessors;
|
|
2024
|
+
if (!casts && !accessors) return;
|
|
2025
|
+
for (const record of records) {
|
|
2026
|
+
if (casts) castInPlace(record, casts);
|
|
2027
|
+
if (accessors) applyAccessorsInPlace(record, accessors);
|
|
2028
|
+
}
|
|
1891
2029
|
}
|
|
1892
2030
|
async function loadRelationData(records, name, related, parentKey, relatedKey, isArray, queryOptions, constraint) {
|
|
1893
|
-
const values =
|
|
2031
|
+
const values = distinctKeys(records, parentKey);
|
|
1894
2032
|
if (values.length === 0) {
|
|
1895
2033
|
for (const record of records) record[name] = isArray ? [] : null;
|
|
1896
|
-
return;
|
|
2034
|
+
return false;
|
|
1897
2035
|
}
|
|
1898
|
-
const relatedRecords = await
|
|
2036
|
+
const { records: relatedRecords, projected } = await loadRelatedRecords(related, values, (chunk) => ({ [relatedKey]: chunk }), queryOptions, constraint);
|
|
1899
2037
|
const map = /* @__PURE__ */ new Map();
|
|
1900
2038
|
for (const item of relatedRecords) {
|
|
1901
2039
|
const key = item[relatedKey];
|
|
@@ -1912,6 +2050,91 @@ async function loadRelationData(records, name, related, parentKey, relatedKey, i
|
|
|
1912
2050
|
}
|
|
1913
2051
|
record[name] = map.get(key) ?? (isArray ? [] : null);
|
|
1914
2052
|
}
|
|
2053
|
+
return projected;
|
|
2054
|
+
}
|
|
2055
|
+
function maxInListSize(adapter) {
|
|
2056
|
+
const size = adapter.maxInListSize?.();
|
|
2057
|
+
return typeof size === "number" && size >= 1 ? Math.floor(size) : 500;
|
|
2058
|
+
}
|
|
2059
|
+
function relationCountPlan(definition, parentType) {
|
|
2060
|
+
switch (definition.type) {
|
|
2061
|
+
case "hasMany":
|
|
2062
|
+
case "hasOne": return {
|
|
2063
|
+
related: definition.related,
|
|
2064
|
+
parentKey: definition.localKey,
|
|
2065
|
+
childKey: definition.foreignKey,
|
|
2066
|
+
where: {},
|
|
2067
|
+
presenceOnly: false
|
|
2068
|
+
};
|
|
2069
|
+
case "morphMany": return {
|
|
2070
|
+
related: definition.related,
|
|
2071
|
+
parentKey: definition.localKey,
|
|
2072
|
+
childKey: `${definition.morphName}Id`,
|
|
2073
|
+
where: { [`${definition.morphName}Type`]: parentType },
|
|
2074
|
+
presenceOnly: false
|
|
2075
|
+
};
|
|
2076
|
+
case "belongsTo": return {
|
|
2077
|
+
related: definition.related,
|
|
2078
|
+
parentKey: definition.foreignKey,
|
|
2079
|
+
childKey: definition.ownerKey,
|
|
2080
|
+
where: {},
|
|
2081
|
+
presenceOnly: true
|
|
2082
|
+
};
|
|
2083
|
+
default: return;
|
|
2084
|
+
}
|
|
2085
|
+
}
|
|
2086
|
+
/**
|
|
2087
|
+
* One row per owner key that exists, never a grouped COUNT: the answer is 0 or
|
|
2088
|
+
* 1, and the key column alone is all of the owner row anything here reads.
|
|
2089
|
+
*/
|
|
2090
|
+
async function countOwnersPresent(related, ownerKey, keys, size, queryOptions) {
|
|
2091
|
+
const rows = await loadByChunks(keys, size, (chunk) => related.newQuery(queryOptions).where({ [ownerKey]: chunk }).select(ownerKey)[RAW_RESULTS]());
|
|
2092
|
+
return new Map(rows.map((row) => [row[ownerKey], 1]));
|
|
2093
|
+
}
|
|
2094
|
+
function distinctKeys(records, key) {
|
|
2095
|
+
return Array.from(new Set(records.map((r) => r[key]).filter((v) => v != null)));
|
|
2096
|
+
}
|
|
2097
|
+
function chunkKeys(values, size) {
|
|
2098
|
+
if (values.length <= size) return [values];
|
|
2099
|
+
const chunks = [];
|
|
2100
|
+
for (let i = 0; i < values.length; i += size) chunks.push(values.slice(i, i + size));
|
|
2101
|
+
return chunks;
|
|
2102
|
+
}
|
|
2103
|
+
async function loadByChunks(values, size, load) {
|
|
2104
|
+
const results = [];
|
|
2105
|
+
for (const chunk of chunkKeys(values, size)) for (const record of await load(chunk)) results.push(record);
|
|
2106
|
+
return results;
|
|
2107
|
+
}
|
|
2108
|
+
/**
|
|
2109
|
+
* The related rows behind one eager load, and whether the constraint narrowed
|
|
2110
|
+
* them with `select()`. The callback runs on the builder that is executed: it
|
|
2111
|
+
* is the caller's, and a probe would run it an extra time per load. A top-level
|
|
2112
|
+
* `orWhere()` in it widens the foreign-key filter, so a loader that groups on
|
|
2113
|
+
* something weaker (morphMany, on the morph id) filters the rows itself.
|
|
2114
|
+
*/
|
|
2115
|
+
async function loadRelatedRecords(related, keys, clause, queryOptions, constraint) {
|
|
2116
|
+
const rows = (chunk) => {
|
|
2117
|
+
const query = related.newQuery(queryOptions).where(clause(chunk));
|
|
2118
|
+
constraint?.(query);
|
|
2119
|
+
return query[RAW_RESULTS]();
|
|
2120
|
+
};
|
|
2121
|
+
const size = maxInListSize(related.getAdapter());
|
|
2122
|
+
const whole = related.newQuery(queryOptions).where(clause(keys));
|
|
2123
|
+
constraint?.(whole);
|
|
2124
|
+
const options = whole.getOptions();
|
|
2125
|
+
const projected = (options.selectFields?.length ?? 0) > 0;
|
|
2126
|
+
const describesWholeSet = options.limitValue !== void 0 || options.offsetValue !== void 0 || options.orderBy.length > 0;
|
|
2127
|
+
if (keys.length <= size || describesWholeSet) return {
|
|
2128
|
+
records: await whole[RAW_RESULTS](),
|
|
2129
|
+
projected
|
|
2130
|
+
};
|
|
2131
|
+
return {
|
|
2132
|
+
records: await loadByChunks(keys, size, rows),
|
|
2133
|
+
projected
|
|
2134
|
+
};
|
|
2135
|
+
}
|
|
2136
|
+
async function countByChunks(values, size, count) {
|
|
2137
|
+
return new Map(await loadByChunks(values, size, async (chunk) => Array.from(await count(chunk))));
|
|
1915
2138
|
}
|
|
1916
2139
|
async function resolveModelReference(reference) {
|
|
1917
2140
|
if (typeof reference === "function" && "prototype" in reference && reference.prototype instanceof Model) return reference;
|
|
@@ -2327,40 +2550,82 @@ function listLocalMigrations(migrationsFolder) {
|
|
|
2327
2550
|
if (!existsSync(migrationsFolder)) return [];
|
|
2328
2551
|
return readdirSync(migrationsFolder, { withFileTypes: true }).filter((entry) => entry.isDirectory() && existsSync(resolve(migrationsFolder, entry.name, "migration.sql"))).map((entry) => ({ name: entry.name })).sort((a, b) => a.name.localeCompare(b.name));
|
|
2329
2552
|
}
|
|
2553
|
+
function parseAppliedAt(row) {
|
|
2554
|
+
if (!row?.appliedAt) return null;
|
|
2555
|
+
const parsed = row.appliedAt instanceof Date ? row.appliedAt : new Date(row.appliedAt);
|
|
2556
|
+
return Number.isNaN(parsed.getTime()) ? null : parsed;
|
|
2557
|
+
}
|
|
2330
2558
|
/**
|
|
2331
2559
|
* Joins local migration folders with the migrator's tracker rows. Drizzle
|
|
2332
2560
|
* decides pending migrations by name membership, so status uses that rule.
|
|
2561
|
+
* The same rule makes the migrator skip a row with no folder, whatever that
|
|
2562
|
+
* row's migration created, so those rows come back too, marked `orphaned`.
|
|
2333
2563
|
*/
|
|
2334
2564
|
function buildMigrationStatus(localMigrations, appliedRows) {
|
|
2335
|
-
const
|
|
2336
|
-
for (const row of appliedRows) if (row.name)
|
|
2337
|
-
|
|
2338
|
-
const row =
|
|
2339
|
-
|
|
2340
|
-
if (row?.appliedAt) {
|
|
2341
|
-
const parsed = row.appliedAt instanceof Date ? row.appliedAt : new Date(row.appliedAt);
|
|
2342
|
-
appliedAt = Number.isNaN(parsed.getTime()) ? null : parsed;
|
|
2343
|
-
}
|
|
2565
|
+
const unmatchedRows = /* @__PURE__ */ new Map();
|
|
2566
|
+
for (const row of appliedRows) if (row.name) unmatchedRows.set(row.name, row);
|
|
2567
|
+
const entries = localMigrations.map((migration) => {
|
|
2568
|
+
const row = unmatchedRows.get(migration.name);
|
|
2569
|
+
unmatchedRows.delete(migration.name);
|
|
2344
2570
|
return {
|
|
2345
2571
|
name: migration.name,
|
|
2346
2572
|
applied: row !== void 0,
|
|
2347
|
-
appliedAt
|
|
2573
|
+
appliedAt: parseAppliedAt(row)
|
|
2348
2574
|
};
|
|
2349
2575
|
});
|
|
2576
|
+
if (unmatchedRows.size === 0) return entries;
|
|
2577
|
+
const orphaned = [...unmatchedRows].map(([name, row]) => ({
|
|
2578
|
+
name,
|
|
2579
|
+
applied: true,
|
|
2580
|
+
appliedAt: parseAppliedAt(row),
|
|
2581
|
+
orphaned: true
|
|
2582
|
+
}));
|
|
2583
|
+
return [...entries, ...orphaned].sort((a, b) => a.name.localeCompare(b.name));
|
|
2350
2584
|
}
|
|
2351
2585
|
/**
|
|
2352
|
-
*
|
|
2353
|
-
*
|
|
2354
|
-
*
|
|
2586
|
+
* Where the migrations folder and the tracker disagree, in both directions.
|
|
2587
|
+
* Best-effort by contract: the names exist to be logged, and a tracker this
|
|
2588
|
+
* driver cannot read costs the names, not the boot.
|
|
2355
2589
|
*/
|
|
2356
|
-
async function
|
|
2590
|
+
async function readMigrationDrift(migrationsFolder, readApplied) {
|
|
2357
2591
|
try {
|
|
2358
|
-
|
|
2592
|
+
const status = buildMigrationStatus(listLocalMigrations(migrationsFolder), await readApplied());
|
|
2593
|
+
return {
|
|
2594
|
+
pending: status.filter((entry) => !entry.applied).map((entry) => entry.name),
|
|
2595
|
+
orphaned: status.filter((entry) => entry.orphaned).map((entry) => entry.name)
|
|
2596
|
+
};
|
|
2359
2597
|
} catch {
|
|
2360
|
-
return
|
|
2598
|
+
return {
|
|
2599
|
+
pending: [],
|
|
2600
|
+
orphaned: []
|
|
2601
|
+
};
|
|
2361
2602
|
}
|
|
2362
2603
|
}
|
|
2363
2604
|
/**
|
|
2605
|
+
* One migrator run, reported on both sides. The tracker is read before the
|
|
2606
|
+
* migrator writes (afterwards every row is applied), and orphans are named
|
|
2607
|
+
* before it runs, since they are the likeliest reason it is about to fail.
|
|
2608
|
+
* Without `readApplied` nothing is read or reported: a reset's re-apply.
|
|
2609
|
+
*/
|
|
2610
|
+
async function migrateAndReport(migrationsFolder, { readApplied, migrate }) {
|
|
2611
|
+
const drift = readApplied ? await readMigrationDrift(migrationsFolder, readApplied) : {
|
|
2612
|
+
pending: [],
|
|
2613
|
+
orphaned: []
|
|
2614
|
+
};
|
|
2615
|
+
reportOrphanedMigrations(drift.orphaned, migrationsFolder);
|
|
2616
|
+
await migrate();
|
|
2617
|
+
reportAppliedMigrations(drift.pending, migrationsFolder);
|
|
2618
|
+
}
|
|
2619
|
+
/**
|
|
2620
|
+
* Warns on every boot while the tracker holds rows no folder carries, such as a
|
|
2621
|
+
* generator's migration a dev server applied before `git clean` removed it. Its
|
|
2622
|
+
* tables stay behind, and a later migration creating them again fails.
|
|
2623
|
+
*/
|
|
2624
|
+
function reportOrphanedMigrations(orphaned, migrationsFolder) {
|
|
2625
|
+
if (orphaned.length === 0) return;
|
|
2626
|
+
console.warn(`[guren/orm] ${orphaned.length} migration(s) applied to this database have no folder in ${migrationsFolder}: ${orphaned.join(", ")}.\n[guren/orm] Whatever they created is still in the database. \`bun run db:status\` lists them as orphaned.`);
|
|
2627
|
+
}
|
|
2628
|
+
/**
|
|
2364
2629
|
* Names what a run applied, so a migration nobody added on purpose — an orphan
|
|
2365
2630
|
* folder a generator left behind on a branch that was deleted, say — does not
|
|
2366
2631
|
* reach the database in silence. Silent when the run applied nothing: an
|
|
@@ -2550,9 +2815,10 @@ function createPostgresDatabase(options) {
|
|
|
2550
2815
|
client: migrationClient,
|
|
2551
2816
|
...relations ? { relations } : {}
|
|
2552
2817
|
});
|
|
2553
|
-
|
|
2554
|
-
|
|
2555
|
-
|
|
2818
|
+
await migrateAndReport(resolvedMigrationsFolder, {
|
|
2819
|
+
readApplied: report ? () => readAppliedMigrations(migrationClient) : void 0,
|
|
2820
|
+
migrate: () => migrate(db, { migrationsFolder: resolvedMigrationsFolder })
|
|
2821
|
+
});
|
|
2556
2822
|
} finally {
|
|
2557
2823
|
await migrationClient.end({ timeout: 0 });
|
|
2558
2824
|
}
|
|
@@ -2711,9 +2977,10 @@ function createMySqlDatabase(options) {
|
|
|
2711
2977
|
client: migrationClient,
|
|
2712
2978
|
...relations ? { relations } : {}
|
|
2713
2979
|
});
|
|
2714
|
-
|
|
2715
|
-
|
|
2716
|
-
|
|
2980
|
+
await migrateAndReport(resolvedMigrationsFolder, {
|
|
2981
|
+
readApplied: report ? () => readAppliedMigrations(migrationDb) : void 0,
|
|
2982
|
+
migrate: () => migrate(migrationDb, { migrationsFolder: resolvedMigrationsFolder })
|
|
2983
|
+
});
|
|
2717
2984
|
} finally {
|
|
2718
2985
|
await closePool(migrationClient);
|
|
2719
2986
|
}
|
|
@@ -2943,10 +3210,11 @@ function createSqliteDatabase(options) {
|
|
|
2943
3210
|
const summary = inspectMigrationsFolder(resolvedMigrationsFolder);
|
|
2944
3211
|
if (summary.migrationsFound === 0) return noMigrationsToRun(summary);
|
|
2945
3212
|
const db = await database.get();
|
|
2946
|
-
const pending = report ? await pendingMigrationNames(resolvedMigrationsFolder, readAppliedMigrations) : [];
|
|
2947
3213
|
const { migrate } = await import("drizzle-orm/bun-sqlite/migrator");
|
|
2948
|
-
await
|
|
2949
|
-
|
|
3214
|
+
await migrateAndReport(resolvedMigrationsFolder, {
|
|
3215
|
+
readApplied: report ? readAppliedMigrations : void 0,
|
|
3216
|
+
migrate: () => migrate(db, { migrationsFolder: resolvedMigrationsFolder })
|
|
3217
|
+
});
|
|
2950
3218
|
return summary;
|
|
2951
3219
|
} catch (error) {
|
|
2952
3220
|
throw migrationFailure(error);
|
|
@@ -3095,9 +3363,10 @@ function createAwsDataApiDatabase(options) {
|
|
|
3095
3363
|
if (summary.migrationsFound === 0) return noMigrationsToRun(summary);
|
|
3096
3364
|
const { migrate } = await loadAwsDataApiModules();
|
|
3097
3365
|
await withAdminDb(async (db) => {
|
|
3098
|
-
|
|
3099
|
-
|
|
3100
|
-
|
|
3366
|
+
await migrateAndReport(resolvedMigrationsFolder, {
|
|
3367
|
+
readApplied: report ? () => readAppliedMigrations(db) : void 0,
|
|
3368
|
+
migrate: () => migrate(db, { migrationsFolder: resolvedMigrationsFolder })
|
|
3369
|
+
});
|
|
3101
3370
|
});
|
|
3102
3371
|
return summary;
|
|
3103
3372
|
} catch (error) {
|