@orieljs/database 0.1.0-alpha.14 → 0.1.0-alpha.16

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.js CHANGED
@@ -239,7 +239,7 @@ function rawWithBindings(query, bindings = []) {
239
239
 
240
240
  // Query/Builder.ts
241
241
  import { sql as sql3 } from "kysely";
242
- import { Collection as Collection3, LazyCollection } from "@orieljs/collections";
242
+ import { Collection as Collection2, LazyCollection } from "@orieljs/collections";
243
243
 
244
244
  // Pagination/AbstractPaginator.ts
245
245
  import { Collection } from "@orieljs/collections";
@@ -257,11 +257,12 @@ function buildQuery(values, prefix) {
257
257
  }
258
258
  return parts.join("&");
259
259
  }
260
+ var isModelLike = (value) => typeof value === "object" && value !== null && typeof value.getKey === "function" && typeof value.getAttributes === "function";
260
261
  var isArrayable = (value) => typeof value === "object" && value !== null && typeof value.toArray === "function";
261
262
  var AbstractPaginator = class _AbstractPaginator {
262
263
  constructor(items, perPageValue, options, currentPage) {
263
264
  this.perPageValue = perPageValue;
264
- this.collection = new Collection(items);
265
+ this.collection = items instanceof Collection ? items : new Collection(items);
265
266
  const path = options.path ?? _AbstractPaginator.resolveCurrentPath();
266
267
  this.pathValue = path !== "/" ? path.replace(/\/+$/, "") : path;
267
268
  this.queryValues = { ...options.query ?? {} };
@@ -360,6 +361,7 @@ var AbstractPaginator = class _AbstractPaginator {
360
361
  items() {
361
362
  return this.collection.all();
362
363
  }
364
+ /** The items on this page: an Eloquent query's in its models' Eloquent collection, as Laravel's. */
363
365
  getCollection() {
364
366
  return this.collection;
365
367
  }
@@ -372,7 +374,9 @@ var AbstractPaginator = class _AbstractPaginator {
372
374
  * `posts.through((post) => ({ id: post.id }))`. Each paginator narrows the return type to its own class.
373
375
  */
374
376
  through(callback) {
375
- this.collection = this.collection.map(callback);
377
+ const mapped = this.collection.all().map(callback);
378
+ const eloquent = typeof this.collection.modelKeys === "function" && mapped.every(isModelLike);
379
+ this.collection = eloquent ? new this.collection.constructor(mapped) : new Collection(mapped);
376
380
  return this;
377
381
  }
378
382
  perPage() {
@@ -402,7 +406,6 @@ var AbstractPaginator = class _AbstractPaginator {
402
406
  };
403
407
 
404
408
  // Pagination/CursorPaginator.ts
405
- import { Collection as Collection2 } from "@orieljs/collections";
406
409
  var Cursor = class _Cursor {
407
410
  constructor(parameters, pointsToNext = true) {
408
411
  this.parameters = parameters;
@@ -457,7 +460,7 @@ var CursorPaginator = class extends AbstractPaginator {
457
460
  this.parameters = options.parameters;
458
461
  this.hasMore = this.collection.count() > perPage;
459
462
  this.collection = this.collection.slice(0, perPage);
460
- if (cursorValue?.pointsToPreviousItems()) this.collection = new Collection2(this.collection.all().reverse());
463
+ if (cursorValue?.pointsToPreviousItems()) this.collection = this.collection.reverse();
461
464
  }
462
465
  cursorValue;
463
466
  hasMore;
@@ -740,10 +743,33 @@ var Grammar = class {
740
743
  columnize(columns) {
741
744
  return join(columns.map((column) => this.wrap(column)));
742
745
  }
743
- compileSelect(query) {
744
- const columns = query.columns.length ? join(query.columns.map((column) => typeof column === "object" && "query" in column ? sql2`${sql2.raw(column.exists ? "exists " : "")}(${this.compileSelect(column.query)}) as ${sql2.id(column.as)}` : this.wrap(column))) : sql2.raw("*");
746
+ compileSelect(query, extraColumn) {
747
+ if (query.groupLimit && extraColumn === void 0) return this.compileGroupLimit(query);
748
+ const list3 = query.columns.length ? query.columns.map((column) => typeof column === "object" && "query" in column ? sql2`${sql2.raw(column.exists ? "exists " : "")}(${this.compileSelect(column.query)}) as ${sql2.id(column.as)}` : this.wrap(column)) : [sql2.raw("*")];
749
+ const columns = join(extraColumn ? [...list3, extraColumn] : list3);
745
750
  return clauses([query.distinctRows ? sql2`select distinct ${columns}` : sql2`select ${columns}`, this.compileComponents(query)]);
746
751
  }
752
+ /**
753
+ * Laravel 11's compileGroupLimit(): the query numbers its rows per `column` in its own order, and an outer query keeps
754
+ * those inside the limit and offset, in row-number order. SQLite 3.25+, MySQL 8 and PostgreSQL have window functions.
755
+ */
756
+ compileGroupLimit(query) {
757
+ const { column, limit, offset } = query.groupLimit;
758
+ const inner = query.clone();
759
+ inner.groupLimit = void 0;
760
+ inner.orders = [];
761
+ const order = this.compileOrders(query);
762
+ const over = order ? sql2`partition by ${this.wrap(column)} ${order}` : sql2`partition by ${this.wrap(column)}`;
763
+ const row = sql2.id(GROUP_ROW);
764
+ const kept = [];
765
+ if (offset !== void 0 && offset > 0) kept.push(sql2`${row} > ${sql2.lit(offset)}`);
766
+ if (limit !== void 0) kept.push(sql2`${row} <= ${sql2.lit((offset ?? 0) + limit)}`);
767
+ return clauses([
768
+ sql2`select * from (${this.compileSelect(inner, sql2`row_number() over (${over}) as ${row}`)}) as ${sql2.id("oriel_table")}`,
769
+ kept.length ? sql2`where ${join(kept, " and ")}` : void 0,
770
+ sql2`order by ${row}`
771
+ ]);
772
+ }
747
773
  /** Everything after the select list: from, joins, where, group by, having, order by, limit/offset, lock. */
748
774
  compileComponents(query) {
749
775
  return clauses([
@@ -770,7 +796,9 @@ var Grammar = class {
770
796
  switch (where.type) {
771
797
  case "basic": {
772
798
  const column = typeof where.column === "object" && !(where.column instanceof Expression) ? sql2`(${this.compileSelect(where.column)})` : this.wrap(where.column);
773
- return sql2`${column} ${sql2.raw(this.operator(where.operator))} ${this.parameter(where.value)}`;
799
+ const operator = this.operator(where.operator);
800
+ if (this.driver === "pgsql" && /like/i.test(operator)) return sql2`${column}::text ${sql2.raw(operator)} ${this.parameter(where.value)}`;
801
+ return sql2`${column} ${sql2.raw(operator)} ${this.parameter(where.value)}`;
774
802
  }
775
803
  case "in": {
776
804
  const keyword = sql2.raw(where.not ? "not in" : "in");
@@ -849,7 +877,10 @@ var Grammar = class {
849
877
  if (mode === "update") return sql2.raw("for update");
850
878
  return sql2.raw(this.driver === "pgsql" ? "for share" : "lock in share mode");
851
879
  }
852
- /** `select count(*) as aggregate …`. Orders, limit and offset are dropped; grouped or distinct queries are wrapped. */
880
+ /**
881
+ * `select count(*) as aggregate …`. Orders, limit and offset are dropped. Grouped or distinct queries, and those with a
882
+ * `having` (which may name a selected alias, withCount()'s `comments_count`), are wrapped, keeping their columns.
883
+ */
853
884
  compileAggregate(query, fn, column) {
854
885
  const inner = query.clone();
855
886
  inner.orders = [];
@@ -857,7 +888,7 @@ var Grammar = class {
857
888
  inner.offsetValue = void 0;
858
889
  inner.lockMode = void 0;
859
890
  const target = column === "*" ? sql2.raw("*") : this.wrap(column);
860
- if (inner.groups.length || inner.distinctRows) {
891
+ if (inner.groups.length || inner.distinctRows || inner.havings.length) {
861
892
  if (fn === "count") return sql2`select count(*) as ${sql2.id("aggregate")} from (${this.compileSelect(inner)}) as ${sql2.id("temp_table")}`;
862
893
  if (column instanceof Expression) {
863
894
  throw new LogicError(`${fn}() can't target a raw expression over a distinct or grouped query: select it as an aliased column instead.`);
@@ -945,6 +976,7 @@ var Grammar = class {
945
976
  };
946
977
 
947
978
  // Query/Builder.ts
979
+ var GROUP_ROW = "oriel_row";
948
980
  async function* chunksOf(query, chunkSize) {
949
981
  for (let page = 1; ; page++) {
950
982
  const results = await query.clone().forPage(page, chunkSize).runSelect();
@@ -1005,6 +1037,8 @@ var Builder = class _Builder {
1005
1037
  orders = [];
1006
1038
  limitValue;
1007
1039
  offsetValue;
1040
+ /** A limit and offset per value of `column` (each parent of an eager load), compiled as a window (limitPerGroup()). */
1041
+ groupLimit;
1008
1042
  lockMode;
1009
1043
  // ---------------------------------------------------------------- building
1010
1044
  from(table) {
@@ -1289,11 +1323,24 @@ var Builder = class _Builder {
1289
1323
  }
1290
1324
  /** The collection get() and chunk() hand out (Eloquent's builder makes the model's collection). */
1291
1325
  newCollection(items) {
1292
- return new Collection3(items);
1326
+ return new Collection2(items);
1293
1327
  }
1294
1328
  /** The raw rows, without a Collection around them. */
1295
1329
  async runSelect() {
1296
- return (await this.connection.execute(this.grammar.compileSelect(this))).rows;
1330
+ const rows = (await this.connection.execute(this.grammar.compileSelect(this))).rows;
1331
+ if (this.groupLimit) for (const row of rows) delete row[GROUP_ROW];
1332
+ return rows;
1333
+ }
1334
+ /**
1335
+ * @internal Eager loading (Laravel 11's groupLimit()): the limit and offset set so far apply to each value of `column`,
1336
+ * the parent's key, instead of to the whole query. Compiled as row_number() over (partition by …).
1337
+ */
1338
+ limitPerGroup(column) {
1339
+ if (this.limitValue === void 0 && this.offsetValue === void 0) return this;
1340
+ this.groupLimit = { column, limit: this.limitValue, offset: this.offsetValue };
1341
+ this.limitValue = void 0;
1342
+ this.offsetValue = void 0;
1343
+ return this;
1297
1344
  }
1298
1345
  async first() {
1299
1346
  const rows = await this.clone().limit(1).runSelect();
@@ -1309,7 +1356,7 @@ var Builder = class _Builder {
1309
1356
  async pluck(column) {
1310
1357
  const rows = await this.clone().select(column).runSelect();
1311
1358
  const key = columnKey(column);
1312
- return new Collection3(rows.map((row) => row[key]));
1359
+ return new Collection2(rows.map((row) => row[key]));
1313
1360
  }
1314
1361
  async count(column = "*") {
1315
1362
  return Number(await this.aggregate("count", column) ?? 0);
@@ -1409,14 +1456,14 @@ var Builder = class _Builder {
1409
1456
  const current = page ?? AbstractPaginator.resolveCurrentPage(pageName);
1410
1457
  const total = await this.clone().count();
1411
1458
  const items = total > 0 ? await this.clone().withColumns(columns).forPage(current, size).runSelect() : [];
1412
- return new LengthAwarePaginator(items, total, size, current, { path: AbstractPaginator.resolveCurrentPath(), pageName });
1459
+ return new LengthAwarePaginator(this.newCollection(items), total, size, current, { path: AbstractPaginator.resolveCurrentPath(), pageName });
1413
1460
  }
1414
1461
  /** Paginates without a count: fetches perPage + 1 rows to know whether there is a next page. */
1415
1462
  async simplePaginate(perPage, columns = ["*"], pageName = "page", page) {
1416
1463
  const size = perPage ?? this.defaultPerPage();
1417
1464
  const current = page ?? AbstractPaginator.resolveCurrentPage(pageName);
1418
1465
  const items = await this.clone().withColumns(columns).offset((current - 1) * size).limit(size + 1).runSelect();
1419
- return new Paginator(items, size, current, { path: AbstractPaginator.resolveCurrentPath(), pageName });
1466
+ return new Paginator(this.newCollection(items), size, current, { path: AbstractPaginator.resolveCurrentPath(), pageName });
1420
1467
  }
1421
1468
  /**
1422
1469
  * Paginates by the ordered columns' values instead of an offset. Needs an orderBy (Eloquent adds the primary key);
@@ -1429,7 +1476,7 @@ var Builder = class _Builder {
1429
1476
  const orders = query.ordersForCursor(current?.pointsToPreviousItems() ?? false);
1430
1477
  if (current) query.whereCursor(current, orders, 0);
1431
1478
  const items = await query.limit(size + 1).runSelect();
1432
- return new CursorPaginator(items, size, current, {
1479
+ return new CursorPaginator(this.newCollection(items), size, current, {
1433
1480
  path: AbstractPaginator.resolveCurrentPath(),
1434
1481
  cursorName,
1435
1482
  parameters: orders.map((order) => String(order.column))
@@ -3022,6 +3069,9 @@ var SchemaBuilder = class _SchemaBuilder {
3022
3069
  };
3023
3070
 
3024
3071
  // Connection.ts
3072
+ function holdsCallbacks(frame) {
3073
+ return frame !== void 0 && frame.ignoresCallbacks !== true;
3074
+ }
3025
3075
  var Connection = class {
3026
3076
  constructor(name, config) {
3027
3077
  this.name = name;
@@ -3034,6 +3084,7 @@ var Connection = class {
3034
3084
  db;
3035
3085
  context = new AsyncLocalStorage();
3036
3086
  pinned = [];
3087
+ savepoints = 0;
3037
3088
  loggingQueries = false;
3038
3089
  queryLog = [];
3039
3090
  getName() {
@@ -3106,24 +3157,108 @@ var Connection = class {
3106
3157
  try {
3107
3158
  result = await this.context.run(frame, () => fn(this));
3108
3159
  } catch (error) {
3109
- await this.close(frame, "rollback");
3160
+ try {
3161
+ await this.close(frame, "rollback");
3162
+ } finally {
3163
+ await this.rolledBack(frame);
3164
+ }
3165
+ throw error;
3166
+ }
3167
+ try {
3168
+ await this.close(frame, "commit");
3169
+ } catch (error) {
3170
+ await this.rolledBack(frame);
3110
3171
  throw error;
3111
3172
  }
3112
- await this.close(frame, "commit");
3173
+ await this.committed(frame);
3113
3174
  return result;
3114
3175
  }
3176
+ /** A committed level hands its callbacks to the transaction(fn) it's nested in, or runs them, outside its context. */
3177
+ async committed(frame) {
3178
+ frame.ended = "commit";
3179
+ if (holdsCallbacks(frame.parent)) {
3180
+ frame.parent.callbacks.push(...frame.callbacks.splice(0));
3181
+ frame.parent.rollbacks.push(...frame.rollbacks.splice(0));
3182
+ return;
3183
+ }
3184
+ frame.rollbacks.length = 0;
3185
+ for (const callback of frame.callbacks.splice(0)) await this.context.exit(() => callback());
3186
+ }
3187
+ /** A level that rolled back drops its callbacks and runs its onRollBack ones, outside its context. */
3188
+ async rolledBack(frame) {
3189
+ frame.ended = "rollback";
3190
+ frame.callbacks.length = 0;
3191
+ for (const callback of frame.rollbacks.splice(0)) await this.runQuietly(callback);
3192
+ }
3193
+ /** An onRollBack callback's failure must not hide the error that rolled the transaction back. */
3194
+ async runQuietly(callback) {
3195
+ try {
3196
+ await this.context.exit(() => callback());
3197
+ } catch {
3198
+ }
3199
+ }
3115
3200
  /** Starts a transaction that stays open, for every async context, until commit()/rollBack(). */
3116
3201
  async beginTransaction() {
3117
- this.pinned.push(await this.open());
3202
+ const frame = await this.open();
3203
+ frame.pinned = true;
3204
+ this.pinned.push(frame);
3205
+ }
3206
+ /**
3207
+ * @internal RefreshDatabase's and DatabaseTransactions': the level beginTransaction() just opened holds no
3208
+ * afterCommit() callbacks, so they run as they would without the test's transaction (Laravel's
3209
+ * callbacksShouldIgnore()), and a test's own transaction(fn) or beginTransaction() runs them at its commit.
3210
+ */
3211
+ ignoreAfterCommitAtCurrentLevel() {
3212
+ const frame = this.pinned.at(-1);
3213
+ if (frame) frame.ignoresCallbacks = true;
3118
3214
  }
3215
+ /**
3216
+ * Laravel's DB::afterCommit(): runs the callback once the transaction open here commits, the outermost one when
3217
+ * they're nested, and drops it if that level rolls back: a transaction(fn) open in this async context, or a level
3218
+ * beginTransaction() opened. Outside one, or in only the testing traits' transaction, it runs at once.
3219
+ * `onRollBack` runs instead when the level that holds the callback rolls back. A callback added once its level has
3220
+ * ended (by work nobody awaited) follows it: held by the level it was committed into, run if the commit is done,
3221
+ * dropped if it rolled back.
3222
+ */
3223
+ async afterCommit(callback, onRollBack) {
3224
+ let frame = this.context.getStore() ?? this.pinned.at(-1);
3225
+ while (frame?.ended === "commit") frame = holdsCallbacks(frame.parent) ? frame.parent : void 0;
3226
+ if (!holdsCallbacks(frame)) {
3227
+ await callback();
3228
+ return;
3229
+ }
3230
+ if (frame.ended === "rollback") {
3231
+ if (onRollBack !== void 0) await this.runQuietly(onRollBack);
3232
+ return;
3233
+ }
3234
+ frame.callbacks.push(callback);
3235
+ if (onRollBack !== void 0) frame.rollbacks.push(onRollBack);
3236
+ }
3237
+ /** @internal Whether a transaction is open here that afterCommit() would wait for. */
3238
+ inTransactionContext() {
3239
+ return holdsCallbacks(this.context.getStore() ?? this.pinned.at(-1));
3240
+ }
3241
+ /** Commits the innermost level opened by beginTransaction(), then runs (or hands up) its afterCommit() callbacks. */
3119
3242
  async commit() {
3120
3243
  const frame = this.pinned.pop();
3121
- if (frame) await this.close(frame, "commit");
3244
+ if (!frame) return;
3245
+ try {
3246
+ await this.close(frame, "commit");
3247
+ } catch (error) {
3248
+ await this.rolledBack(frame);
3249
+ throw error;
3250
+ }
3251
+ await this.committed(frame);
3122
3252
  }
3123
- /** Rolls back the innermost level opened by beginTransaction(). Does nothing when none is open. */
3253
+ /** Rolls back the innermost level opened by beginTransaction(), dropping its afterCommit() callbacks. */
3124
3254
  async rollBack() {
3125
3255
  const frame = this.pinned.pop();
3126
- if (frame) await this.close(frame, "rollback");
3256
+ if (!frame) return;
3257
+ try {
3258
+ await this.close(frame, "rollback");
3259
+ } finally {
3260
+ await this.rolledBack(frame);
3261
+ }
3127
3262
  }
3128
3263
  transactionLevel() {
3129
3264
  return this.current()?.level ?? 0;
@@ -3153,23 +3288,38 @@ var Connection = class {
3153
3288
  }
3154
3289
  async open() {
3155
3290
  const parent = this.current();
3156
- if (!parent) return { trx: await this.db.startTransaction().execute(), level: 1 };
3291
+ if (!parent) return { trx: await this.db.startTransaction().execute(), level: 1, turn: Promise.resolve(), callbacks: [], rollbacks: [] };
3292
+ const previous = parent.turn;
3293
+ let endTurn;
3294
+ parent.turn = new Promise((resolve) => endTurn = resolve);
3295
+ await previous;
3157
3296
  const level = parent.level + 1;
3158
- await sql7.raw(`SAVEPOINT trans${level}`).execute(parent.trx);
3159
- return { trx: parent.trx, level };
3297
+ const savepoint = `trans${level}_${++this.savepoints}`;
3298
+ try {
3299
+ await sql7.raw(`SAVEPOINT ${savepoint}`).execute(parent.trx);
3300
+ } catch (error) {
3301
+ endTurn();
3302
+ throw error;
3303
+ }
3304
+ return { trx: parent.trx, level, savepoint, turn: Promise.resolve(), endTurn, parent, callbacks: [], rollbacks: [] };
3160
3305
  }
3161
3306
  async close(frame, action) {
3162
- if (frame.level === 1) {
3163
- await (action === "commit" ? frame.trx.commit() : frame.trx.rollback()).execute();
3164
- } else if (action === "commit") {
3165
- await sql7.raw(`RELEASE SAVEPOINT trans${frame.level}`).execute(frame.trx);
3166
- } else {
3167
- await sql7.raw(`ROLLBACK TO SAVEPOINT trans${frame.level}`).execute(frame.trx);
3307
+ try {
3308
+ if (frame.level === 1) {
3309
+ await (action === "commit" ? frame.trx.commit() : frame.trx.rollback()).execute();
3310
+ } else if (action === "commit") {
3311
+ await sql7.raw(`RELEASE SAVEPOINT ${frame.savepoint}`).execute(frame.trx);
3312
+ } else {
3313
+ await sql7.raw(`ROLLBACK TO SAVEPOINT ${frame.savepoint}`).execute(frame.trx);
3314
+ }
3315
+ } finally {
3316
+ frame.endTurn?.();
3168
3317
  }
3169
3318
  }
3170
3319
  };
3171
3320
 
3172
3321
  // DatabaseManager.ts
3322
+ import { AsyncLocalStorage as AsyncLocalStorage2 } from "async_hooks";
3173
3323
  var DatabaseManagerImpl = class {
3174
3324
  /** Pass the config, or a function that reads it (the provider reads config('database') lazily). */
3175
3325
  constructor(config) {
@@ -3178,6 +3328,8 @@ var DatabaseManagerImpl = class {
3178
3328
  config;
3179
3329
  connections = /* @__PURE__ */ new Map();
3180
3330
  defaultName;
3331
+ /** usingConnection()'s name, for its own async context only: requests running beside it keep theirs. */
3332
+ using = new AsyncLocalStorage2();
3181
3333
  settings() {
3182
3334
  return typeof this.config === "function" ? this.config() : this.config;
3183
3335
  }
@@ -3194,25 +3346,19 @@ var DatabaseManagerImpl = class {
3194
3346
  return connection;
3195
3347
  }
3196
3348
  getDefaultConnection() {
3197
- return this.defaultName ?? this.settings().default;
3349
+ return this.using.getStore() ?? this.defaultName ?? this.settings().default;
3198
3350
  }
3199
3351
  /** Overrides config('database.default'); undefined clears the override. */
3200
3352
  setDefaultConnection(name) {
3201
3353
  this.defaultName = name;
3202
3354
  }
3203
3355
  /**
3204
- * Runs `callback` with `name` as the default connection (Laravel's usingConnection()), then restores the previous
3205
- * override, or none, so the default follows config('database.default') again. Without a name, just runs it.
3356
+ * Runs `callback` with `name` as the default connection (Laravel's usingConnection()), for the callback's own async
3357
+ * context only: other requests running meanwhile keep their default. Without a name, just runs it.
3206
3358
  */
3207
3359
  async usingConnection(name, callback) {
3208
3360
  if (!name) return callback();
3209
- const previous = this.defaultName;
3210
- this.defaultName = name;
3211
- try {
3212
- return await callback();
3213
- } finally {
3214
- this.defaultName = previous;
3215
- }
3361
+ return this.using.run(name, callback);
3216
3362
  }
3217
3363
  /** The connections opened so far. */
3218
3364
  getConnections() {
@@ -3296,6 +3442,18 @@ var DatabaseManagerImpl = class {
3296
3442
  beginTransaction() {
3297
3443
  return this.connection().beginTransaction();
3298
3444
  }
3445
+ /**
3446
+ * Laravel's DB::afterCommit(): waits for the transaction(fn) open in this async context, on the default connection
3447
+ * first, then on any other opened one; runs at once outside one. It opens no connection: one with a transaction is
3448
+ * open already.
3449
+ */
3450
+ async afterCommit(callback, onRollBack) {
3451
+ const preferred = this.connections.get(this.getDefaultConnection());
3452
+ const opened = [...preferred === void 0 ? [] : [preferred], ...this.connections.values()];
3453
+ const open = opened.find((connection) => connection.inTransactionContext());
3454
+ if (open === void 0) await callback();
3455
+ else await open.afterCommit(callback, onRollBack);
3456
+ }
3299
3457
  commit() {
3300
3458
  return this.connection().commit();
3301
3459
  }
@@ -3327,14 +3485,14 @@ var SchemaBuilderToken = token("Database.SchemaBuilder");
3327
3485
  var Schema = facade(SchemaBuilderToken);
3328
3486
 
3329
3487
  // Eloquent/Model.ts
3330
- import { AsyncLocalStorage as AsyncLocalStorage3 } from "async_hooks";
3488
+ import { AsyncLocalStorage as AsyncLocalStorage4 } from "async_hooks";
3331
3489
  import { DatabaseManager as DatabaseManager2, Hasher } from "@orieljs/contracts";
3332
- import { Collection as Collection10 } from "@orieljs/collections";
3490
+ import { Collection as Collection9 } from "@orieljs/collections";
3333
3491
  import { currentContainer as currentContainer3, inject } from "@orieljs/container";
3334
- import { Str as Str6 } from "@orieljs/support";
3492
+ import { serializeDate, Str as Str6 } from "@orieljs/support";
3335
3493
 
3336
3494
  // Eloquent/Builder.ts
3337
- import { Collection as Collection4 } from "@orieljs/collections";
3495
+ import { Collection as Collection3 } from "@orieljs/collections";
3338
3496
  import { Str as Str2 } from "@orieljs/support";
3339
3497
 
3340
3498
  // Eloquent/Relations/constraints.ts
@@ -3557,14 +3715,9 @@ var Builder2 = class extends Builder {
3557
3715
  if (models.length && this.model.hasModelListeners("retrieved")) {
3558
3716
  for (const model of models) await model.fireModelEvent("retrieved", false);
3559
3717
  }
3560
- if (models.length && this.eagerLoad.size) await this.eagerLoadRelations(models);
3718
+ if (models.length && query.eagerLoad.size) await query.eagerLoadRelations(models);
3561
3719
  return models;
3562
3720
  }
3563
- // ---------------------------------------------------------------- eager loading
3564
- /**
3565
- * Relations to load with the results, one query per relation (and per nesting level):
3566
- * with('author'), with('comments.author'), with({ comments: (q) => q.where('approved', true) }), with('author:id,name').
3567
- */
3568
3721
  with(...relations) {
3569
3722
  for (const spec of relations) {
3570
3723
  if (typeof spec === "string") this.addEagerLoad(spec, void 0);
@@ -3573,7 +3726,6 @@ var Builder2 = class extends Builder {
3573
3726
  }
3574
3727
  return this;
3575
3728
  }
3576
- /** Removes eager loads (including the model's default `with`). */
3577
3729
  without(...relations) {
3578
3730
  for (const name of relations) {
3579
3731
  for (const key of [...this.eagerLoad.keys()]) if (key === name || key.startsWith(`${name}.`)) this.eagerLoad.delete(key);
@@ -3598,6 +3750,7 @@ var Builder2 = class extends Builder {
3598
3750
  const relation = this.getRelation(name);
3599
3751
  relation.addEagerConstraints(models);
3600
3752
  constraint?.(relation);
3753
+ relation.limitEagerPerParent();
3601
3754
  const nested = this.relationsNestedUnder(name);
3602
3755
  if (Object.keys(nested).length) relation.with(nested);
3603
3756
  relation.initRelation(models, name);
@@ -3628,40 +3781,24 @@ var Builder2 = class extends Builder {
3628
3781
  }
3629
3782
  return nested;
3630
3783
  }
3631
- // ---------------------------------------------------------------- relation counts and existence
3632
- /**
3633
- * Adds `<relation>_count` columns: withCount('comments'), withCount({ comments: (q) => q.where('approved', true) }),
3634
- * withCount('comments as approved_count'). Global scopes of the related model (soft deletes) apply.
3635
- */
3636
3784
  withCount(...relations) {
3637
3785
  return this.withAggregate(relations, "*", "count");
3638
3786
  }
3639
- /** Adds `<relation>_sum_<column>`: withSum('orders', 'price'), withSum({ 'orders as paid': (q) => … }, 'price'). */
3640
3787
  withSum(relations, column) {
3641
3788
  return this.withAggregate(relations, column, "sum");
3642
3789
  }
3643
- /** Adds `<relation>_avg_<column>`. */
3644
3790
  withAvg(relations, column) {
3645
3791
  return this.withAggregate(relations, column, "avg");
3646
3792
  }
3647
- /** Adds `<relation>_min_<column>`. */
3648
3793
  withMin(relations, column) {
3649
3794
  return this.withAggregate(relations, column, "min");
3650
3795
  }
3651
- /** Adds `<relation>_max_<column>`. */
3652
3796
  withMax(relations, column) {
3653
3797
  return this.withAggregate(relations, column, "max");
3654
3798
  }
3655
- /** Adds a boolean `<relation>_exists`: withExists('comments'). */
3656
3799
  withExists(...relations) {
3657
3800
  return this.withAggregate(relations, "*", "exists");
3658
3801
  }
3659
- /**
3660
- * Laravel's withAggregate(): a correlated subquery per relation, `select <fn>(<related column>) … as <alias>`, the
3661
- * alias being `<relation>_<fn>_<column>` unless the relation is named `'orders as alias'`. The relation's
3662
- * constraint and the related model's global scopes apply; orderings are dropped. 'exists' selects
3663
- * `exists (…)`, cast to a boolean. Without a function the column's first value is selected.
3664
- */
3665
3802
  withAggregate(relations, column, fn) {
3666
3803
  const specs = this.normalizeRelationSpecs([relations].flat());
3667
3804
  if (!specs.length) return this;
@@ -3670,9 +3807,10 @@ var Builder2 = class extends Builder {
3670
3807
  const [rawName = "", as] = spec.split(/\s+as\s+/i);
3671
3808
  const name = rawName.trim();
3672
3809
  const relation = this.getRelation(name);
3673
- const target = column instanceof Expression ? column : new Expression(column === "*" ? "*" : this.connection.compile(this.grammar.wrap(relation.getRelated().qualifyColumn(column))).sql);
3810
+ const query = relation.getRelationExistenceQuery(relation.getRelated().newQueryWithoutRelationships(), this);
3811
+ const target = column instanceof Expression ? column : new Expression(column === "*" ? "*" : this.connection.compile(this.grammar.wrap(query.getModel().qualifyColumn(column))).sql);
3674
3812
  const expression = fn && fn !== "exists" ? new Expression(`${fn}(${target.value})`, target.bindings) : target;
3675
- const query = relation.getRelationExistenceQuery(relation.getRelated().newQueryWithoutRelationships(), this, [expression]);
3813
+ query.select(expression);
3676
3814
  query.wheres.push(...relation.wheres);
3677
3815
  if (constraint) query.callScope((q) => constraint(q));
3678
3816
  const scoped = query.applyScopes();
@@ -3694,13 +3832,10 @@ var Builder2 = class extends Builder {
3694
3832
  this.selectCasts = { ...this.selectCasts, ...casts };
3695
3833
  return this;
3696
3834
  }
3697
- /**
3698
- * Rows that have related rows: has('comments'), has('comments', '>=', 3), has('comments.author').
3699
- * Uses `exists (…)` for the common "at least one"/"none" cases and a count subquery otherwise.
3700
- */
3701
3835
  has(relation, operator = ">=", count = 1, boolean = "and", callback) {
3702
- if (relation.includes(".")) return this.hasNested(relation, operator, count, boolean, callback);
3703
- const instance = this.getRelation(relation);
3836
+ const name = relation;
3837
+ if (name.includes(".")) return this.hasNested(name, operator, count, boolean, callback);
3838
+ const instance = this.getRelation(name);
3704
3839
  const useExists = (operator === ">=" || operator === "<") && count === 1;
3705
3840
  const query = useExists ? instance.getRelationExistenceQuery(instance.getRelated().newQueryWithoutRelationships(), this) : instance.getRelationExistenceCountQuery(instance.getRelated().newQueryWithoutRelationships(), this);
3706
3841
  query.wheres.push(...instance.wheres);
@@ -3718,7 +3853,6 @@ var Builder2 = class extends Builder {
3718
3853
  orDoesntHave(relation) {
3719
3854
  return this.doesntHave(relation, "or");
3720
3855
  }
3721
- /** Rows with related rows matching the callback: whereHas('comments', (q) => q.where('approved', true)). */
3722
3856
  whereHas(relation, callback, operator = ">=", count = 1) {
3723
3857
  return this.has(relation, operator, count, "and", callback);
3724
3858
  }
@@ -3766,14 +3900,14 @@ var Builder2 = class extends Builder {
3766
3900
  const query = this.applyScopes().clone();
3767
3901
  const rows = await Builder.prototype.runSelect.call(query.select(column));
3768
3902
  const key = column.includes(".") ? column.slice(column.lastIndexOf(".") + 1) : column;
3769
- return new Collection4(rows.map((row) => this.model.newInstance().setRawAttributes({ [key]: row[key] }).getAttribute(key)));
3903
+ return new Collection3(rows.map((row) => this.model.newInstance().setRawAttributes({ [key]: row[key] }).getAttribute(key)));
3770
3904
  }
3771
3905
  /** Whether `id` can't be one of the model's unique ids (not a UUID for HasUuids): it matches no row. */
3772
3906
  isMalformedKey(id) {
3773
3907
  return this.model.uniqueIds().includes(this.model.getKeyName()) && !this.model.isValidUniqueId(id);
3774
3908
  }
3775
- /** A malformed unique id (HasUuids, HasUlids) finds nothing without a query, as route model binding does. */
3776
3909
  async find(id) {
3910
+ if (Array.isArray(id)) return this.findMany(id);
3777
3911
  if (this.isMalformedKey(id)) return void 0;
3778
3912
  return this.clone().whereKey(id).first();
3779
3913
  }
@@ -3812,48 +3946,46 @@ var Builder2 = class extends Builder {
3812
3946
  newModelInstance(attributes = {}) {
3813
3947
  return this.model.newInstance(attributes);
3814
3948
  }
3815
- make(attributes = {}) {
3816
- return this.newModelInstance(attributes);
3949
+ make(attributes) {
3950
+ return this.newModelInstance(attributes ?? {});
3817
3951
  }
3818
- async create(attributes = {}) {
3819
- const model = this.newModelInstance(attributes);
3952
+ async create(attributes) {
3953
+ const model = this.newModelInstance(attributes ?? {});
3820
3954
  await model.save();
3821
3955
  return model;
3822
3956
  }
3823
- /** Creates without mass assignment protection. Never pass it request input. */
3824
3957
  async forceCreate(attributes) {
3825
3958
  const model = this.newModelInstance().forceFill(attributes);
3826
3959
  await model.save();
3827
3960
  return model;
3828
3961
  }
3829
- /** The first match, or a new unsaved model with attributes + values. */
3830
- async firstOrNew(attributes, values = {}) {
3831
- return await this.clone().where(attributes).first() ?? this.newModelInstance({ ...attributes, ...values });
3962
+ async firstOrNew(attributes, values) {
3963
+ const where = attributes;
3964
+ return await this.clone().where(where).first() ?? this.newModelInstance({ ...where, ...values ?? {} });
3832
3965
  }
3833
- /** The first match, or a new saved model. A concurrent insert of the same unique key returns that row instead. */
3834
- async firstOrCreate(attributes, values = {}) {
3835
- return await this.clone().where(attributes).first() ?? this.createOrFirst(attributes, values);
3966
+ async firstOrCreate(attributes, values) {
3967
+ return await this.clone().where(attributes).first() ?? this.createOrFirst(attributes, values ?? {});
3836
3968
  }
3837
- /** Tries to create; on a unique constraint violation, returns the existing row (Laravel's createOrFirst()). */
3838
- async createOrFirst(attributes, values = {}) {
3969
+ async createOrFirst(attributes, values) {
3970
+ const where = attributes;
3971
+ const extra = values ?? {};
3839
3972
  try {
3840
3973
  const connection = this.connection;
3841
- const create = () => this.create({ ...attributes, ...values });
3974
+ const create = () => this.create({ ...where, ...extra });
3842
3975
  return connection.transactionLevel() > 0 ? await connection.transaction(create) : await create();
3843
3976
  } catch (error) {
3844
3977
  if (!isUniqueViolation(error)) throw error;
3845
- const existing = await this.clone().where(attributes).first();
3978
+ const existing = await this.clone().where(where).first();
3846
3979
  if (!existing) throw error;
3847
3980
  return existing;
3848
3981
  }
3849
3982
  }
3850
- /** Updates the first match with values, or creates it. */
3851
- async updateOrCreate(attributes, values = {}) {
3852
- const model = await this.firstOrCreate(attributes, values);
3853
- if (!model.wasRecentlyCreated) await model.fill(values).save();
3983
+ async updateOrCreate(attributes, values) {
3984
+ const extra = values ?? {};
3985
+ const model = await this.firstOrCreate(attributes, extra);
3986
+ if (!model.wasRecentlyCreated) await model.fill(extra).save();
3854
3987
  return model;
3855
3988
  }
3856
- /** Mass update (no model events); sets updated_at when the model uses timestamps. */
3857
3989
  async update(values) {
3858
3990
  return Builder.prototype.update.call(this.applyScopes(), this.addUpdatedAtColumn(values));
3859
3991
  }
@@ -3923,7 +4055,7 @@ var Builder2 = class extends Builder {
3923
4055
 
3924
4056
  // Eloquent/casts.ts
3925
4057
  import { isDeepStrictEqual } from "util";
3926
- import { Collection as Collection5 } from "@orieljs/collections";
4058
+ import { Collection as Collection4 } from "@orieljs/collections";
3927
4059
  var JSON_CASTS = /* @__PURE__ */ new Set(["array", "json", "object", "collection"]);
3928
4060
  var DATE_CASTS = /* @__PURE__ */ new Set(["date", "datetime", "immutable_date", "immutable_datetime"]);
3929
4061
  var PRIMITIVE_CASTS = /* @__PURE__ */ new Set(["int", "integer", "float", "double", "real", "string", "bool", "boolean", "timestamp"]);
@@ -3985,7 +4117,7 @@ function castGet(model, key, cast, value, attributes, className) {
3985
4117
  case "object":
3986
4118
  return typeof value === "string" ? JSON.parse(value) : structuredClone(value);
3987
4119
  case "collection":
3988
- return new Collection5(typeof value === "string" ? JSON.parse(value) : structuredClone(value));
4120
+ return new Collection4(typeof value === "string" ? JSON.parse(value) : structuredClone(value));
3989
4121
  case "date":
3990
4122
  case "immutable_date": {
3991
4123
  const date = parseDateTime(value);
@@ -4006,7 +4138,7 @@ function castSet(model, key, cast, value, attributes, className) {
4006
4138
  if (value === null || value === void 0) return null;
4007
4139
  if (isEnum(cast)) return castGet(model, key, cast, value, attributes, className);
4008
4140
  if (typeof cast !== "string") return value;
4009
- if (JSON_CASTS.has(cast)) return JSON.stringify(value instanceof Collection5 ? value.all() : value);
4141
+ if (JSON_CASTS.has(cast)) return JSON.stringify(value instanceof Collection4 ? value.all() : value);
4010
4142
  if (cast === "date" || cast === "immutable_date") return formatDate(parseDateTime(value));
4011
4143
  if (cast === "datetime" || cast === "immutable_datetime") return formatDateTime(parseDateTime(value));
4012
4144
  if (cast === "timestamp") return formatDateTime(typeof value === "number" ? new Date(value * 1e3) : parseDateTime(value));
@@ -4026,7 +4158,7 @@ function isEquivalent(cast, current, original, model, key, className) {
4026
4158
  if (typeof cast === "string" && (JSON_CASTS.has(cast) || PRIMITIVE_CASTS.has(cast) || cast.startsWith("decimal:"))) {
4027
4159
  const a = read(current);
4028
4160
  const b = read(original);
4029
- return isDeepStrictEqual(a instanceof Collection5 ? a.all() : a, b instanceof Collection5 ? b.all() : b);
4161
+ return isDeepStrictEqual(a instanceof Collection4 ? a.all() : a, b instanceof Collection4 ? b.all() : b);
4030
4162
  }
4031
4163
  if (isEnum(cast)) return String(current) === String(original);
4032
4164
  }
@@ -4035,19 +4167,19 @@ function isEquivalent(cast, current, original, model, key, className) {
4035
4167
  }
4036
4168
 
4037
4169
  // Eloquent/Collection.ts
4038
- import { Collection as Collection6 } from "@orieljs/collections";
4170
+ import { Collection as Collection5 } from "@orieljs/collections";
4039
4171
  var dictionaryKey = (key) => String(key);
4040
4172
  var isModel = (value) => typeof value === "object" && value !== null && typeof value.getKey === "function" && typeof value.relationLoaded === "function";
4041
4173
  function uniqueByKey(models) {
4042
4174
  return [...new Map(models.map((model) => [dictionaryKey(model.getKey()), model])).values()];
4043
4175
  }
4044
4176
  function relatedModels(value) {
4045
- if (value instanceof Collection6) return value.all().filter(isModel);
4177
+ if (value instanceof Collection5) return value.all().filter(isModel);
4046
4178
  return isModel(value) ? [value] : [];
4047
4179
  }
4048
- var EloquentCollection = class extends Collection6 {
4180
+ var EloquentCollection = class extends Collection5 {
4049
4181
  find(key, defaultValue) {
4050
- const value = isModel(key) ? key.getKey() : key instanceof Collection6 ? key.all() : key;
4182
+ const value = isModel(key) ? key.getKey() : key instanceof Collection5 ? key.all() : key;
4051
4183
  if (Array.isArray(value)) {
4052
4184
  const wanted = new Set(value.map(dictionaryKey));
4053
4185
  return this.filter((model) => wanted.has(dictionaryKey(model.getKey())));
@@ -4055,7 +4187,7 @@ var EloquentCollection = class extends Collection6 {
4055
4187
  return this.first((model) => dictionaryKey(model.getKey()) === dictionaryKey(value), defaultValue);
4056
4188
  }
4057
4189
  findOrFail(key) {
4058
- const value = key instanceof Collection6 ? key.all() : key;
4190
+ const value = key instanceof Collection5 ? key.all() : key;
4059
4191
  if (Array.isArray(value)) {
4060
4192
  const found = this.find(value);
4061
4193
  const keys = [...new Map(value.map((id) => [dictionaryKey(id), id])).values()];
@@ -4079,40 +4211,33 @@ var EloquentCollection = class extends Collection6 {
4079
4211
  }
4080
4212
  /** The same models in a plain Collection. */
4081
4213
  toBase() {
4082
- return new Collection6(this.items);
4214
+ return new Collection5(this.items);
4083
4215
  }
4084
4216
  contains(...args) {
4085
- if (args.length > 1 || typeof args[0] === "function") return Reflect.apply(Collection6.prototype.contains, this, args);
4217
+ if (args.length > 1 || typeof args[0] === "function") return Reflect.apply(Collection5.prototype.contains, this, args);
4086
4218
  const [key] = args;
4087
4219
  if (isModel(key)) return this.items.some((model) => model.is(key));
4088
4220
  return this.items.some((model) => dictionaryKey(model.getKey()) === dictionaryKey(key));
4089
4221
  }
4090
4222
  containsStrict(...args) {
4091
- return Reflect.apply(Collection6.prototype.contains, this, args);
4223
+ return Reflect.apply(Collection5.prototype.contains, this, args);
4092
4224
  }
4093
4225
  doesntContainStrict(...args) {
4094
- return !Reflect.apply(Collection6.prototype.contains, this, args);
4226
+ return !Reflect.apply(Collection5.prototype.contains, this, args);
4095
4227
  }
4096
- /** Eager loads relations onto every model, one query per relation: await posts.load('author', 'comments.author'). */
4097
4228
  async load(...relations) {
4098
4229
  const first = this.first();
4099
4230
  if (!first || !relations.length) return this;
4100
4231
  await first.newQueryWithoutRelationships().with(...relations).eagerLoadRelations(this.items);
4101
4232
  return this;
4102
4233
  }
4103
- /** Loads only the relations that aren't loaded yet; nested paths are followed into the loaded relations. */
4104
4234
  async loadMissing(...relations) {
4105
- await loadMissingOn(this.items, relations);
4235
+ await loadMissingOn(this.items, [...relations]);
4106
4236
  return this;
4107
4237
  }
4108
- /** Adds <relation>_count attributes to every model with one query: await posts.loadCount('comments'). */
4109
4238
  loadCount(...relations) {
4110
4239
  return this.loadAggregate(relations, "*", "count");
4111
4240
  }
4112
- /**
4113
- * Laravel's loadAggregate(): withAggregate() for models already loaded, with one query for the whole collection.
4114
- * The values become clean attributes (with their casts: loadExists() gives booleans).
4115
- */
4116
4241
  async loadAggregate(relations, column, fn) {
4117
4242
  const first = this.first();
4118
4243
  if (!first || ![relations].flat().length) return this;
@@ -4128,7 +4253,6 @@ var EloquentCollection = class extends Collection6 {
4128
4253
  }
4129
4254
  return this;
4130
4255
  }
4131
- /** Adds <relation>_sum_<column> to every model: await users.loadSum('orders', 'price'). */
4132
4256
  loadSum(relations, column) {
4133
4257
  return this.loadAggregate(relations, column, "sum");
4134
4258
  }
@@ -4141,7 +4265,6 @@ var EloquentCollection = class extends Collection6 {
4141
4265
  loadMax(relations, column) {
4142
4266
  return this.loadAggregate(relations, column, "max");
4143
4267
  }
4144
- /** Adds a boolean <relation>_exists to every model. */
4145
4268
  loadExists(...relations) {
4146
4269
  return this.loadAggregate(relations, "*", "exists");
4147
4270
  }
@@ -4233,7 +4356,7 @@ async function loadMissingOn(models, paths) {
4233
4356
  import { existsSync, readdirSync } from "fs";
4234
4357
  import { join as join4 } from "path";
4235
4358
  import { pathToFileURL } from "url";
4236
- import { Collection as Collection9 } from "@orieljs/collections";
4359
+ import { Collection as Collection8 } from "@orieljs/collections";
4237
4360
  import { Str as Str5 } from "@orieljs/support";
4238
4361
 
4239
4362
  // Eloquent/Relations/BelongsTo.ts
@@ -4283,7 +4406,8 @@ function resolveMorphClass(type) {
4283
4406
  }
4284
4407
 
4285
4408
  // Eloquent/Relations/Relation.ts
4286
- var Relation = class extends Builder2 {
4409
+ var selfAliases = 0;
4410
+ var Relation = class _Relation extends Builder2 {
4287
4411
  constructor(related, parent) {
4288
4412
  super(related);
4289
4413
  this.parent = parent;
@@ -4306,6 +4430,36 @@ var Relation = class extends Builder2 {
4306
4430
  getRelated() {
4307
4431
  return this.model;
4308
4432
  }
4433
+ /**
4434
+ * When the related table is the parent's own (a category's children, a user's followers), the existence query reads it
4435
+ * under an alias, `oriel_reserved_<n>`, so its columns aren't the outer row's. The related model takes the alias as its
4436
+ * table, so its qualified columns (keys, soft deletes, a constraint's qualifyColumn()) follow. Returns the alias, or
4437
+ * undefined when the tables differ.
4438
+ */
4439
+ aliasSelfTable(query) {
4440
+ const table = query.getModel().getTable();
4441
+ if (table !== this.parent.getTable()) return void 0;
4442
+ const alias = _Relation.reserveAlias();
4443
+ query.from(`${table} as ${alias}`);
4444
+ query.getModel().setTable(alias);
4445
+ return alias;
4446
+ }
4447
+ /** A new `oriel_reserved_<n>` alias, for a table a query reads twice. */
4448
+ static reserveAlias() {
4449
+ return `oriel_reserved_${selfAliases++}`;
4450
+ }
4451
+ /**
4452
+ * @internal After an eager load's constraint: a limit() or offset() set there applies to each parent, as in Laravel 11,
4453
+ * on the relations that know the column holding the parent's key.
4454
+ */
4455
+ limitEagerPerParent() {
4456
+ const column = this.eagerPartitionColumn();
4457
+ if (column !== void 0) this.limitPerGroup(column);
4458
+ }
4459
+ /** The column of the eager query holding each row's parent key; undefined where a per-parent limit makes no sense. */
4460
+ eagerPartitionColumn() {
4461
+ return void 0;
4462
+ }
4309
4463
  /** Subclasses call this last in their constructor: adds the per-parent constraints unless eager loading. */
4310
4464
  init() {
4311
4465
  if (relationConstraintsEnabled()) this.addConstraints();
@@ -4390,6 +4544,7 @@ var BelongsTo = class extends Relation {
4390
4544
  return this.associate(null);
4391
4545
  }
4392
4546
  getRelationExistenceQuery(query, _parentQuery, columns = ["*"]) {
4547
+ this.aliasSelfTable(query);
4393
4548
  return query.select(...columns).whereColumn(this.getQualifiedForeignKeyName(), "=", this.getQualifiedOwnerKeyName());
4394
4549
  }
4395
4550
  /** The loaded-relation name: the resolved name, else the related class in camelCase (author → pass it explicitly). */
@@ -4399,7 +4554,7 @@ var BelongsTo = class extends Relation {
4399
4554
  };
4400
4555
 
4401
4556
  // Eloquent/Relations/BelongsToMany.ts
4402
- import { Collection as Collection7 } from "@orieljs/collections";
4557
+ import { Collection as Collection6 } from "@orieljs/collections";
4403
4558
  var BelongsToMany = class extends Relation {
4404
4559
  constructor(related, parent, table, foreignPivotKey, relatedPivotKey, parentKey, relatedKey) {
4405
4560
  super(related, parent);
@@ -4484,7 +4639,11 @@ var BelongsToMany = class extends Relation {
4484
4639
  for (const model of models) model.setRelation(relation, this.getRelated().newCollection(dictionary.get(String(model.getAttribute(this.parentKey))) ?? []));
4485
4640
  return models;
4486
4641
  }
4642
+ eagerPartitionColumn() {
4643
+ return this.qualifyPivotColumn(this.foreignPivotKey);
4644
+ }
4487
4645
  getRelationExistenceQuery(query, _parentQuery, columns = ["*"]) {
4646
+ this.aliasSelfTable(query);
4488
4647
  return query.select(...columns).join(this.table, this.model.qualifyColumn(this.relatedKey), "=", this.qualifyPivotColumn(this.relatedPivotKey)).whereColumn(this.parent.qualifyColumn(this.parentKey), "=", this.qualifyPivotColumn(this.foreignPivotKey));
4489
4648
  }
4490
4649
  // ---------------------------------------------------------------- the pivot table
@@ -4552,9 +4711,8 @@ var BelongsToMany = class extends Relation {
4552
4711
  if (this.pivotTimestamps) values[this.pivotTimestamps[1]] = formatDateTime(this.parent.freshTimestamp());
4553
4712
  return this.newPivotQuery().where(this.foreignPivotKey, "=", this.getParentKey()).where(this.relatedPivotKey, "=", this.idOf(id)).update(values);
4554
4713
  }
4555
- /** Saves a new related model and attaches it. */
4556
- async create(attributes = {}, pivotAttributes = {}) {
4557
- const model = this.model.newInstance(attributes);
4714
+ async create(attributes, pivotAttributes = {}) {
4715
+ const model = this.model.newInstance(attributes ?? {});
4558
4716
  await model.save();
4559
4717
  await this.attach(model, pivotAttributes);
4560
4718
  return model;
@@ -4603,7 +4761,7 @@ var BelongsToMany = class extends Relation {
4603
4761
  /** ids → Map(id → extra pivot attributes). Models become their related key. */
4604
4762
  parseIds(ids) {
4605
4763
  const parsed = /* @__PURE__ */ new Map();
4606
- if (ids instanceof Collection7) ids = ids.all();
4764
+ if (ids instanceof Collection6) ids = ids.all();
4607
4765
  if (Array.isArray(ids)) {
4608
4766
  for (const id of ids) parsed.set(this.idOf(id), {});
4609
4767
  } else if (ids !== null && typeof ids === "object" && !this.isModel(ids)) {
@@ -4761,20 +4919,29 @@ var HasOneOrMany = class extends Relation {
4761
4919
  for (const model of models) saved.push(await this.save(model));
4762
4920
  return saved;
4763
4921
  }
4922
+ /** One related model per record, in the related model's Eloquent collection. */
4764
4923
  async createMany(records) {
4765
4924
  const created = [];
4766
4925
  for (const record of records) created.push(await this.create(record));
4767
- return created;
4926
+ return this.getRelated().newCollection(created);
4927
+ }
4928
+ eagerPartitionColumn() {
4929
+ return this.foreignKey;
4768
4930
  }
4769
4931
  getRelationExistenceQuery(query, _parentQuery, columns = ["*"]) {
4770
- query.select(...columns).whereColumn(this.getQualifiedParentKeyName(), "=", this.foreignKey);
4771
- if (this.morph) query.where(this.morph.type, "=", this.morph.value);
4932
+ const alias = this.aliasSelfTable(query);
4933
+ const foreignKey = alias === void 0 ? this.foreignKey : `${alias}.${this.getForeignKeyName()}`;
4934
+ query.select(...columns).whereColumn(this.getQualifiedParentKeyName(), "=", foreignKey);
4935
+ if (this.morph) {
4936
+ const type = alias === void 0 ? this.morph.type : `${alias}.${this.morph.type.slice(this.morph.type.lastIndexOf(".") + 1)}`;
4937
+ query.where(type, "=", this.morph.value);
4938
+ }
4772
4939
  return query;
4773
4940
  }
4774
4941
  };
4775
4942
 
4776
4943
  // Eloquent/Relations/MorphTo.ts
4777
- import { Collection as Collection8 } from "@orieljs/collections";
4944
+ import { Collection as Collection7 } from "@orieljs/collections";
4778
4945
  var MorphTo = class extends BelongsTo {
4779
4946
  /**
4780
4947
  * @param related an instance of the current type's class (the child's own class when the type is empty)
@@ -4836,7 +5003,7 @@ var MorphTo = class extends BelongsTo {
4836
5003
  results.push(result);
4837
5004
  }
4838
5005
  }
4839
- return new Collection8(results);
5006
+ return new Collection7(results);
4840
5007
  }
4841
5008
  match(models, results, relation) {
4842
5009
  for (const result of results) {
@@ -4912,7 +5079,11 @@ var Factory = class _Factory {
4912
5079
  const name = relationship ?? Str5.camel(Str5.plural(new factory.model().constructor.name));
4913
5080
  return this.newInstance({ hasRelations: [...this.hasRelations, { factory, relationship: name, pivot }] });
4914
5081
  }
4915
- /** Sets a belongsTo parent: for(User.factory()) or for(user) (relationship default: 'user'). Created once. */
5082
+ /**
5083
+ * Sets a belongsTo parent: for(User.factory()) or for(user) (relationship default: 'user'). A factory parent is made
5084
+ * once per make()/create() call, for all of its models, and again by the next call, so a factory kept in a variable
5085
+ * never points at a parent an earlier test rolled back.
5086
+ */
4916
5087
  for(parent, relationship) {
4917
5088
  const cls = parent instanceof Model ? parent.constructor : new parent.model().constructor;
4918
5089
  return this.newInstance({ forRelations: [...this.forRelations, { parent, relationship: relationship ?? Str5.camel(cls.name) }] });
@@ -4926,7 +5097,8 @@ var Factory = class _Factory {
4926
5097
  /** The attributes only, without a model (a Row, or a Row[] after count()). */
4927
5098
  async raw(attributes = {}) {
4928
5099
  const rows = [];
4929
- for (let index = 0; index < (this.countValue ?? 1); index++) rows.push(await this.attributesFor(attributes, index));
5100
+ const parents = /* @__PURE__ */ new Map();
5101
+ for (let index = 0; index < (this.countValue ?? 1); index++) rows.push(await this.attributesFor(attributes, index, parents));
4930
5102
  return this.countValue === void 0 ? rows[0] : rows;
4931
5103
  }
4932
5104
  /** Unsaved models (afterMaking callbacks run). */
@@ -4950,12 +5122,16 @@ var Factory = class _Factory {
4950
5122
  async createOne(attributes = {}) {
4951
5123
  return await this.newInstance({ countValue: void 0 }).create(attributes);
4952
5124
  }
4953
- /** One model per record (or `count` models). */
5125
+ /** One model per record (or `count` models), in the model's Eloquent collection. */
4954
5126
  async createMany(records) {
4955
5127
  const list3 = typeof records === "number" ? Array.from({ length: records }, () => ({})) : records;
4956
5128
  const created = [];
4957
5129
  for (const record of list3) created.push(await this.createOne(record));
4958
- return new Collection9(created);
5130
+ return this.collect(created);
5131
+ }
5132
+ /** The models in their own Eloquent collection (the model's newCollection()). */
5133
+ collect(models) {
5134
+ return new this.model().newCollection(models);
4959
5135
  }
4960
5136
  newInstance(changes) {
4961
5137
  const copy = Object.create(Object.getPrototypeOf(this));
@@ -4964,20 +5140,21 @@ var Factory = class _Factory {
4964
5140
  }
4965
5141
  async makeModels(attributes) {
4966
5142
  const models = [];
5143
+ const parents = /* @__PURE__ */ new Map();
4967
5144
  for (let index = 0; index < (this.countValue ?? 1); index++) {
4968
- const model = new this.model().forceFill(await this.attributesFor(attributes, index));
5145
+ const model = new this.model().forceFill(await this.attributesFor(attributes, index, parents));
4969
5146
  for (const callback of this.afterMakingCallbacks) await callback(model);
4970
5147
  models.push(model);
4971
5148
  }
4972
5149
  return models;
4973
5150
  }
4974
5151
  /** definition() + states + overrides + for() parents, with factory and function values expanded. */
4975
- async attributesFor(overrides, index) {
5152
+ async attributesFor(overrides, index, parents = /* @__PURE__ */ new Map()) {
4976
5153
  const context = { index, count: this.countValue ?? 1 };
4977
5154
  let attributes = this.definition();
4978
5155
  for (const state of this.states) attributes = { ...attributes, ...typeof state === "function" ? state(attributes, context) : state };
4979
5156
  attributes = { ...attributes, ...overrides };
4980
- for (const parent of this.forRelations) Object.assign(attributes, await this.parentAttributes(parent));
5157
+ for (const parent of this.forRelations) Object.assign(attributes, await this.parentAttributes(parent, parents));
4981
5158
  const expanded = {};
4982
5159
  for (const [key, value] of Object.entries(attributes)) {
4983
5160
  if (value instanceof _Factory) expanded[key] = (await value.createOne()).getKey();
@@ -4987,8 +5164,12 @@ var Factory = class _Factory {
4987
5164
  }
4988
5165
  return expanded;
4989
5166
  }
4990
- async parentAttributes(parent) {
4991
- const resolved = parent.resolved ??= parent.parent instanceof Model ? parent.parent : await parent.parent.createOne();
5167
+ async parentAttributes(parent, parents) {
5168
+ let resolved = parents.get(parent);
5169
+ if (resolved === void 0) {
5170
+ resolved = parent.parent instanceof Model ? parent.parent : await parent.parent.createOne();
5171
+ parents.set(parent, resolved);
5172
+ }
4992
5173
  const relation = this.relationOn(new this.model(), parent.relationship);
4993
5174
  if (relation instanceof MorphTo) {
4994
5175
  return { [relation.getForeignKeyName()]: resolved.getKey(), [relation.getMorphType()]: resolved.getMorphClass() };
@@ -5001,7 +5182,7 @@ var Factory = class _Factory {
5001
5182
  const relation = this.relationOn(model, relationship);
5002
5183
  if (relation instanceof BelongsToMany) {
5003
5184
  const related = await factory.create();
5004
- await relation.attach(related instanceof Collection9 ? related.all() : related, pivot);
5185
+ await relation.attach(related instanceof Collection8 ? related.all() : related, pivot);
5005
5186
  } else if (relation instanceof HasOneOrMany) {
5006
5187
  const foreign = { [relation.getForeignKeyName()]: relation.getParentKey() };
5007
5188
  if (relation.morph) foreign[relation.getMorphType()] = relation.getMorphClass();
@@ -5015,7 +5196,7 @@ var Factory = class _Factory {
5015
5196
  return model.getRelationInstance(relationship);
5016
5197
  }
5017
5198
  result(models) {
5018
- return this.countValue === void 0 ? models[0] : new Collection9(models);
5199
+ return this.countValue === void 0 ? models[0] : this.collect(models);
5019
5200
  }
5020
5201
  };
5021
5202
  async function discoverFactories(path) {
@@ -5032,7 +5213,7 @@ async function discoverFactories(path) {
5032
5213
  }
5033
5214
 
5034
5215
  // Eloquent/events.ts
5035
- import { AsyncLocalStorage as AsyncLocalStorage2 } from "async_hooks";
5216
+ import { AsyncLocalStorage as AsyncLocalStorage3 } from "async_hooks";
5036
5217
  import { EventDispatcher } from "@orieljs/contracts";
5037
5218
  import { currentContainer as currentContainer2 } from "@orieljs/container";
5038
5219
  var MODEL_EVENTS = [
@@ -5050,7 +5231,7 @@ var MODEL_EVENTS = [
5050
5231
  "forceDeleting",
5051
5232
  "forceDeleted"
5052
5233
  ];
5053
- var muted = new AsyncLocalStorage2();
5234
+ var muted = new AsyncLocalStorage3();
5054
5235
  function modelEventName(event, className) {
5055
5236
  return `eloquent.${event}: ${className}`;
5056
5237
  }
@@ -5094,7 +5275,7 @@ var HasMany = class extends HasOneOrMany {
5094
5275
 
5095
5276
  // Eloquent/Relations/HasManyThrough.ts
5096
5277
  var THROUGH_KEY = "laravel_through_key";
5097
- var HasManyThrough = class extends Relation {
5278
+ var HasManyThrough = class _HasManyThrough extends Relation {
5098
5279
  /**
5099
5280
  * @param firstKey on the through table, pointing at the far parent ('users.country_id')
5100
5281
  * @param secondKey on the related table, pointing at the through model ('posts.user_id')
@@ -5108,9 +5289,10 @@ var HasManyThrough = class extends Relation {
5108
5289
  this.secondKey = secondKey;
5109
5290
  this.localKey = localKey;
5110
5291
  this.secondLocalKey = secondLocalKey;
5111
- this.join(this.throughParent.getTable(), this.getQualifiedParentKeyName(), "=", this.getQualifiedForeignKeyName());
5292
+ this.throughAlias = throughParent.getTable() === related.getTable() ? _HasManyThrough.reserveAlias() : void 0;
5293
+ this.join(this.throughTable(this.throughAlias), this.getQualifiedParentKeyName(), "=", this.getQualifiedForeignKeyName());
5112
5294
  if (this.throughParent.usesSoftDeletes()) {
5113
- this.withGlobalScope("SoftDeletableHasManyThrough", (query) => query.whereNull(this.throughParent.getQualifiedDeletedAtColumn()));
5295
+ this.withGlobalScope("SoftDeletableHasManyThrough", (query) => query.whereNull(this.throughColumn(this.throughParent.getDeletedAtColumn())));
5114
5296
  }
5115
5297
  this.init();
5116
5298
  }
@@ -5121,9 +5303,22 @@ var HasManyThrough = class extends Relation {
5121
5303
  secondLocalKey;
5122
5304
  /** The through key of each loaded model (kept off its attributes, so it never reaches toJSON()). */
5123
5305
  throughKeys = /* @__PURE__ */ new WeakMap();
5306
+ /**
5307
+ * The through table's alias when it is the related table too (a person's grandchildren, through their children):
5308
+ * every query of the relation reads it under this name, its keys and soft deletes included.
5309
+ */
5310
+ throughAlias;
5311
+ /** The through table to join: `users`, or `users as <alias>`. */
5312
+ throughTable(alias) {
5313
+ return alias === void 0 ? this.throughParent.getTable() : `${this.throughParent.getTable()} as ${alias}`;
5314
+ }
5315
+ /** A through column, qualified by the through table or by its alias. */
5316
+ throughColumn(column, alias = this.throughAlias) {
5317
+ return alias === void 0 ? this.throughParent.qualifyColumn(column) : `${alias}.${column}`;
5318
+ }
5124
5319
  /** users.country_id */
5125
5320
  getQualifiedFirstKeyName() {
5126
- return this.throughParent.qualifyColumn(this.firstKey);
5321
+ return this.throughColumn(this.firstKey);
5127
5322
  }
5128
5323
  /** posts.user_id */
5129
5324
  getQualifiedForeignKeyName() {
@@ -5131,7 +5326,7 @@ var HasManyThrough = class extends Relation {
5131
5326
  }
5132
5327
  /** users.id */
5133
5328
  getQualifiedParentKeyName() {
5134
- return this.throughParent.qualifyColumn(this.secondLocalKey);
5329
+ return this.throughColumn(this.secondLocalKey);
5135
5330
  }
5136
5331
  /** countries.id */
5137
5332
  getQualifiedLocalKeyName() {
@@ -5156,6 +5351,10 @@ var HasManyThrough = class extends Relation {
5156
5351
  }
5157
5352
  return models;
5158
5353
  }
5354
+ /** An eager limit() or offset() applies to each far parent, by the through table's key to it (Laravel 11). */
5355
+ eagerPartitionColumn() {
5356
+ return this.getQualifiedFirstKeyName();
5357
+ }
5159
5358
  async getResults() {
5160
5359
  const key = this.parent.getAttribute(this.localKey);
5161
5360
  return key === null || key === void 0 ? this.getRelated().newCollection() : this.get();
@@ -5178,9 +5377,15 @@ var HasManyThrough = class extends Relation {
5178
5377
  for (const model of models) model.setRelation(relation, this.getRelated().newCollection(dictionary.get(String(model.getAttribute(this.localKey))) ?? []));
5179
5378
  return models;
5180
5379
  }
5380
+ /**
5381
+ * The query of has()/withCount(), as Laravel's ...ForSelfRelation and ...ForThroughSelfRelation: a related table that
5382
+ * is the parent's is read under an alias, and so is a through table that is the parent's (or the related one).
5383
+ */
5181
5384
  getRelationExistenceQuery(query, _parentQuery, columns = ["*"]) {
5182
- query.select(...columns).join(this.throughParent.getTable(), this.getQualifiedParentKeyName(), "=", this.getQualifiedForeignKeyName()).whereColumn(this.getQualifiedLocalKeyName(), "=", this.getQualifiedFirstKeyName());
5183
- if (this.throughParent.usesSoftDeletes()) query.whereNull(this.throughParent.getQualifiedDeletedAtColumn());
5385
+ const related = this.aliasSelfTable(query) ?? query.getModel().getTable();
5386
+ const alias = this.throughAlias ?? (this.throughParent.getTable() === this.parent.getTable() ? _HasManyThrough.reserveAlias() : void 0);
5387
+ query.select(...columns).join(this.throughTable(alias), this.throughColumn(this.secondLocalKey, alias), "=", `${related}.${this.secondKey}`).whereColumn(this.getQualifiedLocalKeyName(), "=", this.throughColumn(this.firstKey, alias));
5388
+ if (this.throughParent.usesSoftDeletes()) query.whereNull(this.throughColumn(this.throughParent.getDeletedAtColumn(), alias));
5184
5389
  return query;
5185
5390
  }
5186
5391
  };
@@ -5275,7 +5480,7 @@ var prototypes = /* @__PURE__ */ new Map();
5275
5480
  var unguardedGlobally = { value: false };
5276
5481
  var addingDefaultCounts = /* @__PURE__ */ new Set();
5277
5482
  var PLAIN_COLUMN = /^[A-Za-z_][A-Za-z0-9_]*$/;
5278
- var unguardedScope = new AsyncLocalStorage3();
5483
+ var unguardedScope = new AsyncLocalStorage4();
5279
5484
  var globalScopes = /* @__PURE__ */ new Map();
5280
5485
  var anonymousScopes = 0;
5281
5486
  function installScopeProxies(cls) {
@@ -5306,9 +5511,6 @@ function hasher() {
5306
5511
  return container.make(Hasher);
5307
5512
  }
5308
5513
  var serializing = /* @__PURE__ */ new WeakSet();
5309
- function serializeDate(date) {
5310
- return date.toISOString().replace(/\.(\d{3})Z$/, ".$1000Z");
5311
- }
5312
5514
  var Model = class _Model {
5313
5515
  static CREATED_AT = "created_at";
5314
5516
  static UPDATED_AT = "updated_at";
@@ -5402,8 +5604,8 @@ var Model = class _Model {
5402
5604
  return instance;
5403
5605
  }
5404
5606
  /** A new, unsaved model filled with attributes (mass assignment rules apply). */
5405
- static make(attributes = {}) {
5406
- return new this().fill(attributes);
5607
+ static make(attributes) {
5608
+ return new this().fill(attributes ?? {});
5407
5609
  }
5408
5610
  static addGlobalScope(nameOrScope, implementation) {
5409
5611
  let name;
@@ -5696,20 +5898,20 @@ var Model = class _Model {
5696
5898
  return this.query().lazyById(chunkSize);
5697
5899
  }
5698
5900
  /** Creates and saves a model (mass assignment rules apply). */
5699
- static create(attributes = {}) {
5700
- return this.query().create(attributes);
5901
+ static create(attributes) {
5902
+ return this.query().create(attributes ?? {});
5701
5903
  }
5702
5904
  static forceCreate(attributes) {
5703
5905
  return this.query().forceCreate(attributes);
5704
5906
  }
5705
- static firstOrNew(attributes, values = {}) {
5706
- return this.query().firstOrNew(attributes, values);
5907
+ static firstOrNew(attributes, values) {
5908
+ return this.query().firstOrNew(attributes, values ?? {});
5707
5909
  }
5708
- static firstOrCreate(attributes, values = {}) {
5709
- return this.query().firstOrCreate(attributes, values);
5910
+ static firstOrCreate(attributes, values) {
5911
+ return this.query().firstOrCreate(attributes, values ?? {});
5710
5912
  }
5711
- static updateOrCreate(attributes, values = {}) {
5712
- return this.query().updateOrCreate(attributes, values);
5913
+ static updateOrCreate(attributes, values) {
5914
+ return this.query().updateOrCreate(attributes, values ?? {});
5713
5915
  }
5714
5916
  static factory(count, state) {
5715
5917
  let factory = Factory.forModel(this);
@@ -5966,6 +6168,7 @@ var Model = class _Model {
5966
6168
  if (value === void 0 || value === null || value === "") this.setAttribute(column, this.newUniqueId());
5967
6169
  }
5968
6170
  }
6171
+ /** The primary key's value: a string, a number or a bigint, or nothing on a model not yet saved. */
5969
6172
  getKey() {
5970
6173
  return this.getAttribute(this.getKeyName());
5971
6174
  }
@@ -6132,9 +6335,9 @@ var Model = class _Model {
6132
6335
  this.pendingHashes.clear();
6133
6336
  }
6134
6337
  /** Fills and saves an existing model. */
6135
- async update(attributes = {}) {
6338
+ async update(attributes) {
6136
6339
  if (!this.exists) return false;
6137
- return this.fill(attributes).save();
6340
+ return this.fill(attributes ?? {}).save();
6138
6341
  }
6139
6342
  /**
6140
6343
  * Deletes the model's row, or sets deleted_at with soft deletes. Returns false for a model that isn't saved, or
@@ -6304,8 +6507,11 @@ var Model = class _Model {
6304
6507
  }
6305
6508
  async incrementOrDecrement(column, amount, extra) {
6306
6509
  if (!this.exists) return this.newQueryWithoutRelationships().increment(column, amount, extra);
6307
- const affected = await this.setKeysForSaveQuery(this.newModelQuery()).increment(column, amount, extra);
6308
6510
  this.forceFill({ ...extra, [column]: Number(this.getAttribute(column) ?? 0) + amount });
6511
+ if (await this.fireModelEvent("updating") === false) return 0;
6512
+ const affected = await this.setKeysForSaveQuery(this.newModelQuery()).increment(column, amount, extra);
6513
+ this.syncChanges();
6514
+ await this.fireModelEvent("updated", false);
6309
6515
  this.syncOriginalAttributes(column, ...Object.keys(extra));
6310
6516
  return affected;
6311
6517
  }
@@ -6590,7 +6796,7 @@ var Model = class _Model {
6590
6796
  const key = Str6.snake(name);
6591
6797
  if (!this.isArrayableKey(key)) continue;
6592
6798
  if (value === null || value === void 0) result[key] = null;
6593
- else if (value instanceof Collection10) result[key] = value.toArray();
6799
+ else if (value instanceof Collection9) result[key] = value.toArray();
6594
6800
  else if (typeof value.toArray === "function") result[key] = value.toArray();
6595
6801
  else result[key] = value;
6596
6802
  }
@@ -6598,7 +6804,7 @@ var Model = class _Model {
6598
6804
  }
6599
6805
  serializeValue(value) {
6600
6806
  if (value instanceof Date) return serializeDate(value);
6601
- if (value instanceof Collection10) return value.toArray();
6807
+ if (value instanceof Collection9) return value.toArray();
6602
6808
  return value;
6603
6809
  }
6604
6810
  isArrayableKey(key) {
@@ -7176,12 +7382,22 @@ var TypeGenerator = class {
7176
7382
  const members = attributes.filter(([column]) => !(column in instance));
7177
7383
  const extra = accessors(model).filter(([attribute]) => !columns.some((column) => column.name === attribute) && !(attribute in instance));
7178
7384
  const statics = scopes(model).filter(([method]) => !(method in Model));
7385
+ const names = (list3) => list3.map((item) => `'${item}'`).join(" | ");
7386
+ const hidden = instance.getHidden();
7387
+ const visible = instance.getVisible();
7388
+ const appends = instance.getAppends();
7179
7389
  const lines = [
7180
7390
  `declare module '${this.modulePath(file)}' {`,
7181
7391
  ` interface ${name} {`,
7182
7392
  " $attributes?: {",
7183
7393
  ...attributes.map(([column, type]) => ` ${this.key(column)}: ${type}`),
7184
7394
  " }",
7395
+ // The model itself, for its own methods: inside them `this` is a type parameter, and their writes and loads read
7396
+ // the attributes and relations they check from here.
7397
+ ` $self?: ${name}`,
7398
+ ...hidden.length ? [` $hidden?: ${names(hidden)}`] : [],
7399
+ ...visible.length ? [` $visible?: ${names(visible)}`] : [],
7400
+ ...appends.length ? [` $appends?: ${names(appends)}`] : [],
7185
7401
  ...members.map(([column, type]) => ` ${this.key(column)}: ${type}`),
7186
7402
  ...extra.map(([attribute, method]) => ` ${this.key(attribute)}: ReturnType<${name}['${method}']>`),
7187
7403
  " }"