@guren/orm 2.8.0 → 2.9.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 +74 -16
  2. package/dist/index.js +495 -272
  3. package/package.json +1 -1
package/dist/index.d.ts CHANGED
@@ -17,18 +17,25 @@ declare function applyAccessors<T extends PlainObject>(record: T, accessors?: Ac
17
17
  /** Apply mutators to data before persistence, returning a new object. */
18
18
  declare function applyMutators(data: PlainObject, mutators?: MutatorDefinitions): PlainObject;
19
19
  //#endregion
20
- //#region src/QueryBuilder.d.ts
21
- type FieldKey<TRecord extends PlainObject> = keyof TRecord & string;
20
+ //#region src/internal-keys.d.ts
22
21
  /**
23
- * Key for the prepared-payload update terminal. Exported for `Model` across
24
- * the module boundary, but kept out of the package entry point.
22
+ * What `Model`, `QueryBuilder` and the adapters share without importing each
23
+ * other, kept out of the package entry point. The keys live here rather than on
24
+ * either class because `Model` names one as a computed static key: evaluated
25
+ * while the two modules' import cycle is still unwinding, a key declared in the
26
+ * other one is in its temporal dead zone.
25
27
  */
28
+ /** Bulk update with an already-filtered, already-prepared payload. */
26
29
  declare const PREPARED_UPDATE: unique symbol;
27
- /**
28
- * Key for the global-scope seal. Exported for `Model` across the module
29
- * boundary, but kept out of the package entry point.
30
- */
30
+ /** Freezes the conditions applied so far as the model's global scopes. */
31
31
  declare const SEAL_SCOPES: unique symbol;
32
+ /** The model's one read-transform pass over a result set. */
33
+ declare const READ_TRANSFORMS: unique symbol;
34
+ /** Rows as the adapter read them, for the joins a relation loader makes. */
35
+ declare const RAW_RESULTS: unique symbol;
36
+ //#endregion
37
+ //#region src/QueryBuilder.d.ts
38
+ type FieldKey<TRecord extends PlainObject> = keyof TRecord & string;
32
39
  type WhereOperator = '=' | '!=' | '>' | '<' | '>=' | '<=' | 'like' | 'in' | 'not in' | 'is null' | 'is not null';
33
40
  interface SimpleCondition {
34
41
  type: 'simple';
@@ -114,6 +121,11 @@ declare class QueryBuilder<TRecord extends PlainObject = PlainObject, TResult ex
114
121
  orderBy(field: FieldKey<TRecord>, direction?: OrderDirection): this;
115
122
  limit(n: number): this;
116
123
  offset(n: number): this;
124
+ /**
125
+ * Narrows the row to these columns. The model's accessors are then skipped:
126
+ * one reading a column `fields` left out would fabricate a value from
127
+ * `undefined`. Casts still apply to the columns that are there.
128
+ */
117
129
  select<TKey extends FieldKey<TRecord>>(...fields: readonly TKey[]): QueryBuilder<TRecord, Pick<TRecord, TKey>>;
118
130
  /** Apply a named query scope defined on the model. */
119
131
  scope(name: string): this;
@@ -122,14 +134,30 @@ declare class QueryBuilder<TRecord extends PlainObject = PlainObject, TResult ex
122
134
  * callbacks, each run after the foreign-key filter on exactly the level its key
123
135
  * names. Pitfalls: a top-level `orWhere()` ORs against the foreign-key filter
124
136
  * (group it); `select()` must keep the relation's key column or the relation is
125
- * empty; `limit()` applies to the one batched query, not per parent record.
137
+ * empty; `limit()` caps the whole result set, not each parent's share.
126
138
  */
127
139
  with(...relations: (string | Record<string, EagerLoadConstraint>)[]): this;
128
140
  get(): Promise<TResult[]>;
141
+ /**
142
+ * Runs the query and hands back the rows as the adapter read them. Symbol-keyed
143
+ * and never re-exported: a named public method here would be a supported way to
144
+ * read past a model's casts.
145
+ */
146
+ [RAW_RESULTS](): Promise<TResult[]>;
147
+ /** The one read pipeline: rows, then eager loads, then the model's transforms. */
148
+ private fetch;
149
+ private fetchRaw;
129
150
  first(): Promise<TResult | null>;
130
151
  /** @throws ModelNotFoundException (404) if no record matches. */
131
152
  firstOrFail(): Promise<TResult>;
132
153
  count(): Promise<number>;
154
+ /**
155
+ * @internal Row count per distinct value of `field`, as one grouped COUNT
156
+ * where the adapter issues it. Without `countByAdvanced` the rows are loaded
157
+ * and counted here, narrowed to that one column where the adapter can project
158
+ * and whole where it cannot.
159
+ */
160
+ countBy(field: FieldKey<TRecord>): Promise<Map<unknown, number>>;
133
161
  /**
134
162
  * Takes positional arguments or the same options object as
135
163
  * `Model.paginate()`, so the two APIs stay interchangeable.
@@ -212,6 +240,17 @@ interface ORMAdapterAdvanced extends ORMAdapter {
212
240
  select?: readonly string[];
213
241
  }, queryOptions?: AdapterQueryOptions): Promise<TRecord[]>;
214
242
  countAdvanced?<TRecord extends PlainObject = PlainObject>(table: unknown, conditions: WhereCondition[], queryOptions?: AdapterQueryOptions): Promise<number>;
243
+ /**
244
+ * Keys the adapter admits in one IN list, from the bound-variable limit the
245
+ * driver it holds sets. Without it, the ORM uses the figure every dialect it
246
+ * supports admits.
247
+ */
248
+ maxInListSize?(): number;
249
+ /** `SELECT field, COUNT(*) ... GROUP BY field` under `conditions`. */
250
+ countByAdvanced?(table: unknown, field: string, conditions: WhereCondition[], queryOptions?: AdapterQueryOptions): Promise<Array<{
251
+ key: unknown;
252
+ count: number;
253
+ }>>;
215
254
  updateAdvanced?<TRecord extends PlainObject = PlainObject>(table: unknown, conditions: WhereCondition[], data: PlainObject, writeOptions?: AdapterQueryOptions): Promise<TRecord>;
216
255
  deleteAdvanced?<TRecord extends PlainObject = PlainObject>(table: unknown, conditions: WhereCondition[], writeOptions?: AdapterQueryOptions): Promise<number | PlainObject | void>;
217
256
  }
@@ -442,8 +481,15 @@ declare abstract class Model<TRecord extends PlainObject = PlainObject> {
442
481
  static serialize<T extends typeof Model>(this: T, record: TRecordFor<T>): PlainObject;
443
482
  static serializeMany<T extends typeof Model>(this: T, records: TRecordFor<T>[]): PlainObject[];
444
483
  static applyCasts<T extends PlainObject>(record: T): T;
445
- /** Read-time transforms, in order: casts then accessors. */
484
+ /** The one read-transform pass for a record, in order: casts then accessors. */
446
485
  protected static applyReadTransforms<T extends PlainObject>(record: T): T;
486
+ /**
487
+ * The same pass over a result set. Symbol-keyed for `QueryBuilder` across the
488
+ * module boundary, and kept out of the package entry point. `projected` marks
489
+ * a row `select()` narrowed: an accessor there would read columns that are not
490
+ * on it, while `applyCasts` already skips an absent one.
491
+ */
492
+ static [READ_TRANSFORMS]<T extends PlainObject>(records: T[], projected?: boolean): T[];
447
493
  /**
448
494
  * In order: `deniedFields()` throws, checked on the raw input so no later
449
495
  * rule can swallow them; `id` is stripped silently; then, with `fillable`
@@ -458,6 +504,11 @@ declare abstract class Model<TRecord extends PlainObject = PlainObject> {
458
504
  static getRelationDefinition(name: string): RelationDefinition | undefined;
459
505
  static resolveTable(): unknown;
460
506
  static all<T extends typeof Model>(this: T, queryOptions?: ModelQueryOptions): Promise<Array<TRecordFor<T>>>;
507
+ /**
508
+ * The rows a relation load joins against, as the adapter read them: a cast on
509
+ * the parent's key column would stop the child rows from matching it.
510
+ */
511
+ protected static rawRecords<T extends typeof Model>(this: T, where: WhereClauseFor<T> | undefined, queryOptions?: ModelQueryOptions): Promise<Array<TRecordFor<T>>>;
461
512
  static find<T extends typeof Model>(this: T, id: TRecordFor<T>[keyof TRecordFor<T> & string], key?: keyof TRecordFor<T> & string, queryOptions?: ModelQueryOptions): Promise<TRecordFor<T> | null>;
462
513
  /** @throws ModelNotFoundException (404) when no record matches. */
463
514
  static findOrFail<T extends typeof Model>(this: T, id: TRecordFor<T>[keyof TRecordFor<T> & string], key?: keyof TRecordFor<T> & string, queryOptions?: ModelQueryOptions): Promise<TRecordFor<T>>;
@@ -551,6 +602,12 @@ declare abstract class Model<TRecord extends PlainObject = PlainObject> {
551
602
  * await User.paginate({ page: 2, perPage: 20, where: { status: 'active' } })
552
603
  */
553
604
  static paginate<T extends typeof Model>(this: T, options?: PaginateOptions<TRecordFor<T>>, queryOptions?: ModelQueryOptions): Promise<PaginatedResult<TRecordFor<T>>>;
605
+ /**
606
+ * The builder owns pagination: the count matters as much as the rows, and a
607
+ * second sanitise-count-slice here would agree with the builder's by
608
+ * inspection rather than by construction.
609
+ */
610
+ private static paginationQuery;
554
611
  static withPaginate<T extends typeof Model, K extends RelationPath<T>>(this: T, relations: K | readonly K[], options?: PaginateOptions<TRecordFor<T>>, queryOptions?: ModelQueryOptions): Promise<PaginatedResult<TRecordFor<T> & RelationTypePick<T, K | readonly K[]>>>;
555
612
  static create<T extends typeof Model>(this: T, data: TCreateFor<T>, writeOptions?: ModelWriteOptions): Promise<TRecordFor<T>>;
556
613
  /**
@@ -610,12 +667,12 @@ declare abstract class Model<TRecord extends PlainObject = PlainObject> {
610
667
  * leaf looks itself up under that whole key, not under `comments`.
611
668
  */
612
669
  protected static loadRelationLevel<T extends typeof Model>(this: T, records: Array<PlainObject>, head: string, tails: readonly string[], queryOptions?: ModelQueryOptions, constraints?: EagerLoadConstraints, pathPrefix?: string): Promise<void>;
613
- protected static loadHasMany(records: Array<PlainObject>, definition: HasManyRelationDefinition, queryOptions?: ModelQueryOptions, constraint?: EagerLoadConstraint): Promise<void>;
614
- protected static loadHasOne(records: Array<PlainObject>, definition: HasOneRelationDefinition, queryOptions?: ModelQueryOptions, constraint?: EagerLoadConstraint): Promise<void>;
615
- protected static loadBelongsTo(records: Array<PlainObject>, definition: BelongsToRelationDefinition, queryOptions?: ModelQueryOptions, constraint?: EagerLoadConstraint): Promise<void>;
616
- protected static loadBelongsToMany(records: Array<PlainObject>, definition: BelongsToManyRelationDefinition, queryOptions?: ModelQueryOptions, constraint?: EagerLoadConstraint): Promise<void>;
617
- protected static loadHasManyThrough(records: Array<PlainObject>, definition: HasManyThroughRelationDefinition, queryOptions?: ModelQueryOptions, constraint?: EagerLoadConstraint): Promise<void>;
618
- protected static loadMorphMany(records: Array<PlainObject>, definition: MorphManyRelationDefinition, queryOptions?: ModelQueryOptions, constraint?: EagerLoadConstraint): Promise<void>;
670
+ protected static loadHasMany(records: Array<PlainObject>, definition: HasManyRelationDefinition, queryOptions?: ModelQueryOptions, constraint?: EagerLoadConstraint): Promise<boolean>;
671
+ protected static loadHasOne(records: Array<PlainObject>, definition: HasOneRelationDefinition, queryOptions?: ModelQueryOptions, constraint?: EagerLoadConstraint): Promise<boolean>;
672
+ protected static loadBelongsTo(records: Array<PlainObject>, definition: BelongsToRelationDefinition, queryOptions?: ModelQueryOptions, constraint?: EagerLoadConstraint): Promise<boolean>;
673
+ protected static loadBelongsToMany(records: Array<PlainObject>, definition: BelongsToManyRelationDefinition, queryOptions?: ModelQueryOptions, constraint?: EagerLoadConstraint): Promise<boolean>;
674
+ protected static loadHasManyThrough(records: Array<PlainObject>, definition: HasManyThroughRelationDefinition, queryOptions?: ModelQueryOptions, constraint?: EagerLoadConstraint): Promise<boolean>;
675
+ protected static loadMorphMany(records: Array<PlainObject>, definition: MorphManyRelationDefinition, queryOptions?: ModelQueryOptions, constraint?: EagerLoadConstraint): Promise<boolean>;
619
676
  protected static loadMorphTo(records: Array<PlainObject>, definition: MorphToRelationDefinition, queryOptions?: ModelQueryOptions, constraint?: EagerLoadConstraint): Promise<void>;
620
677
  }
621
678
  type TRecordFor<T extends typeof Model> = T extends {
@@ -833,6 +890,7 @@ type DrizzleLikeSelect = {
833
890
  orderBy?: (...clauses: unknown[]) => DrizzleLikeSelect;
834
891
  limit?: (value: number) => DrizzleLikeSelect;
835
892
  offset?: (value: number) => DrizzleLikeSelect;
893
+ groupBy?: (...columns: unknown[]) => DrizzleLikeSelect;
836
894
  all?: () => Promise<unknown[]>;
837
895
  get?: () => Promise<unknown>;
838
896
  };
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 transactionScope;
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 of a
241
- * Workers or Lambda bundle, whose drivers all await their callback and never
242
- * reach this branch. The promise is what is memoized, not the storage: two
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 loadTransactionScope() {
246
- transactionScope ??= import("node:async_hooks").then(({ AsyncLocalStorage }) => {
247
- const store = new AsyncLocalStorage();
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 transactionScope;
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. Waiting is only safe for a caller that is not already inside one:
258
- * that caller would be queued behind itself. Async context is what separates the
259
- * two, and it is the only thing that can — arrival order cannot tell a nested
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, scope, callback));
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, scope, callback) {
392
+ async function runExclusively(db, run, store, callback) {
278
393
  await run(sql.raw("begin"));
279
- try {
280
- const result = await scope.run(() => callback(db));
281
- await run(sql.raw("commit"));
282
- return result;
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
- const raw = (await resolveList(query))[0]?.value ?? 0;
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
- if (typeof query.where === "function") {
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
- let query = resolveExecutor(queryOptions).select({ value: count() }).from(table);
385
- if (typeof query.where === "function") {
386
- const clause = buildDrizzleConditions(table, conditions);
387
- if (clause) query = query.where(clause);
388
- }
389
- const raw = (await resolveList(query))[0]?.value ?? 0;
390
- const total = typeof raw === "bigint" ? Number(raw) : Number(raw);
391
- return Number.isNaN(total) ? 0 : total;
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
- if (await awaitsItsCallback(db)) return db.transaction(callback);
415
- return runOwnTransaction(db, callback);
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
- const keys = Object.keys(accessors);
424
- if (keys.length === 0) return record;
572
+ if (Object.keys(accessors).length === 0) return record;
425
573
  const result = { ...record };
426
- for (const key of keys) result[key] = accessors[key](result);
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) if (key in result) result[key] = mutators[key](result[key], result);
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()` applies to the one batched query, not per parent record.
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
- const results = await this.executeQuery();
657
- return this.loadEagerRelations(results);
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
- const prev = this.options.limitValue;
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 prevLimit = this.options.limitValue;
691
- const prevOffset = this.options.offsetValue;
692
- this.options.limitValue = sanitizedPerPage;
693
- this.options.offsetValue = offset;
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: this.options.limitValue,
852
- offset: this.options.offsetValue,
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: this.options.limitValue,
861
- offset: this.options.offsetValue
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
- for (const key of options.appends) if (options.accessors[key]) result[key] = options.accessors[key](result);
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
- for (const [field, castType] of Object.entries(castDefs)) {
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
- /** Read-time transforms, in order: casts then accessors. */
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
- if (this.hasScopes()) return this.newQuery(queryOptions).get();
1191
- const table = this.resolveTable();
1192
- const records = await this.getAdapter().findMany(table, void 0, queryOptions);
1193
- if (this.casts || this.accessors) return records.map((r) => this.applyReadTransforms(r));
1194
- return records;
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
- if (record && (this.casts || this.accessors)) return this.applyReadTransforms(record);
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
- if (record && (this.casts || this.accessors)) return this.applyReadTransforms(record);
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
- return this.getAdapter().findMany(table, options, queryOptions);
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
- if (this.hasScopes()) {
1423
- const builder = this.newQuery(queryOptions);
1424
- if (options.where && Object.keys(options.where).length > 0) builder.where(options.where);
1425
- if (options.orderBy) for (const clause of normalizeOrderBy(options.orderBy)) builder.orderBy(clause.column, clause.direction);
1426
- return builder.paginate({
1427
- page: options.page,
1428
- perPage: options.perPage
1429
- });
1430
- }
1431
- const table = this.resolveTable();
1432
- const adapter = this.getAdapter();
1433
- const requestedPage = typeof options.page === "number" ? options.page : 1;
1434
- const sanitizedPage = Number.isFinite(requestedPage) && requestedPage >= 1 ? Math.floor(requestedPage) : 1;
1435
- const requestedPerPage = typeof options.perPage === "number" ? options.perPage : 15;
1436
- const perPage = Number.isFinite(requestedPerPage) && requestedPerPage >= 1 ? Math.floor(requestedPerPage) : 15;
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 result = await this.paginate(options, queryOptions);
1607
+ const builder = this.paginationQuery(options, queryOptions);
1468
1608
  const relationList = normalizeRelations(relations);
1469
- if (relationList.length === 0 || result.data.length === 0) return result;
1470
- const records = result.data.map((record) => ({ ...record }));
1471
- await this.loadRelationsInto(records, relationList, queryOptions);
1472
- return {
1473
- data: records,
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
- if (this.casts || this.accessors) return this.applyReadTransforms(result);
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
- if (this.casts || this.accessors) return this.applyReadTransforms(result);
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 = where ? await this.newQuery(queryOptions).where(where).get() : await this.all(queryOptions);
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
- const copies = records.map((record) => ({ ...record }));
1596
- await this.loadRelationsInto(copies, relationList, queryOptions);
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 = where ? await this.newQuery(queryOptions).where(where).get() : await this.all(queryOptions);
1601
- if (!records.length) return records;
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 copies = records.map((record) => ({ ...record }));
1604
- for (const relationName of relationList) await this.loadRelationCountInto(copies, relationName, queryOptions);
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
- switch (definition.type) {
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 === 0) return;
1716
- if (definition.type === "morphTo") throw new Error(`${this.name}: nested eager loading through morphTo relation "${head}" is not supported.`);
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
- await (await resolveModelReference(definition.related)).loadRelationsInto(children, tails, queryOptions, constraints, currentPath);
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
- await loadRelationData(records, name, await resolveModelReference(definition.related), localKey, foreignKey, true, queryOptions, constraint);
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
- await loadRelationData(records, name, await resolveModelReference(definition.related), localKey, foreignKey, false, queryOptions, constraint);
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
- await loadRelationData(records, name, await resolveModelReference(definition.related), foreignKey, ownerKey, false, queryOptions, constraint);
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 = Array.from(new Set(records.map((r) => r[parentKey]).filter((v) => v != null)));
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 pivotRows = await this.getAdapter().findMany(pivotTable, { where: { [foreignPivotKey]: parentValues } }, queryOptions);
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 applyEagerConstraint(related.newQuery(queryOptions).where({ [relatedKey]: Array.from(allRelatedIds) }), constraint);
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 = Array.from(new Set(records.map((r) => r[localKey]).filter((v) => v != null)));
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]: localValues });
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 applyEagerConstraint(related.newQuery(queryOptions).where({ [secondKey]: Array.from(allThroughIds) }), constraint);
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 = Array.from(new Set(records.map((r) => r[localKey]).filter((v) => v != null)));
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 applyEagerConstraint(related.newQuery(queryOptions).where({
1938
+ const { records: allRelated, projected } = await loadRelatedRecords(related, localValues, (chunk) => ({
1833
1939
  [typeColumn]: parentType,
1834
- [idColumn]: localValues
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 uniqueIds = Array.from(new Set(ids));
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
- * The callback runs with the foreign-key filter already on the builder, so a
1884
- * `where()` narrows it and a top-level `orWhere()` widens it — a loader that
1885
- * groups on something weaker than the full filter (morphMany, on the morph id)
1886
- * must not rely on the query alone to keep other rows out.
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
- async function applyEagerConstraint(query, constraint) {
1889
- constraint?.(query);
1890
- return await query;
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 = Array.from(new Set(records.map((r) => r[parentKey]).filter((v) => v != null)));
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 applyEagerConstraint(related.newQuery(queryOptions).where({ [relatedKey]: values }), constraint);
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;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@guren/orm",
3
- "version": "2.8.0",
3
+ "version": "2.9.0",
4
4
  "type": "module",
5
5
  "sideEffects": [
6
6
  "./src/instance-guard.ts",