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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -600,6 +600,7 @@ declare class Connection implements DatabaseConnection {
600
600
  protected readonly db: Kysely<any>;
601
601
  private readonly context;
602
602
  private readonly pinned;
603
+ private savepoints;
603
604
  private loggingQueries;
604
605
  private queryLog;
605
606
  constructor(name: string, config: ConnectionConfig);
@@ -834,7 +835,12 @@ declare class Grammar {
834
835
  parameter(value: unknown): Sql;
835
836
  operator(operator: string): string;
836
837
  columnize(columns: ReadonlyArray<string | Expression>): Sql;
837
- compileSelect(query: Builder$1<unknown>): Sql;
838
+ compileSelect(query: Builder$1<unknown>, extraColumn?: Sql): Sql;
839
+ /**
840
+ * Laravel 11's compileGroupLimit(): the query numbers its rows per `column` in its own order, and an outer query keeps
841
+ * those inside the limit and offset, in row-number order. SQLite 3.25+, MySQL 8 and PostgreSQL have window functions.
842
+ */
843
+ compileGroupLimit(query: Builder$1<unknown>): Sql;
838
844
  /** Everything after the select list: from, joins, where, group by, having, order by, limit/offset, lock. */
839
845
  compileComponents(query: Builder$1<unknown>): Sql;
840
846
  compileOrders(query: Builder$1<unknown>): Sql | undefined;
@@ -858,7 +864,10 @@ declare class Grammar {
858
864
  compileHavings(havings: readonly Having[]): Sql | undefined;
859
865
  compileLimitOffset(limit: number | undefined, offset: number | undefined): Sql | undefined;
860
866
  compileLock(mode: 'update' | 'share' | undefined): Sql | undefined;
861
- /** `select count(*) as aggregate …`. Orders, limit and offset are dropped; grouped or distinct queries are wrapped. */
867
+ /**
868
+ * `select count(*) as aggregate …`. Orders, limit and offset are dropped. Grouped or distinct queries, and those with a
869
+ * `having` (which may name a selected alias, withCount()'s `comments_count`), are wrapped, keeping their columns.
870
+ */
862
871
  compileAggregate(query: Builder$1<unknown>, fn: string, column: string | Expression): Sql;
863
872
  compileExists(query: Builder$1<unknown>): Sql;
864
873
  compileInsert(query: Builder$1<unknown>, rows: readonly Row[]): Sql;
@@ -986,6 +995,12 @@ declare class Builder$1<T = Row> implements QueryBuilder<T> {
986
995
  orders: Order[];
987
996
  limitValue: number | undefined;
988
997
  offsetValue: number | undefined;
998
+ /** A limit and offset per value of `column` (each parent of an eager load), compiled as a window (limitPerGroup()). */
999
+ groupLimit: {
1000
+ column: string;
1001
+ limit: number | undefined;
1002
+ offset: number | undefined;
1003
+ } | undefined;
989
1004
  lockMode: 'update' | 'share' | undefined;
990
1005
  constructor(connection: Connection, table?: string | Expression);
991
1006
  from(table: string | Expression): this;
@@ -1096,6 +1111,11 @@ declare class Builder$1<T = Row> implements QueryBuilder<T> {
1096
1111
  protected newCollection(items: T[]): Collection<T>;
1097
1112
  /** The raw rows, without a Collection around them. */
1098
1113
  runSelect(): Promise<T[]>;
1114
+ /**
1115
+ * @internal Eager loading (Laravel 11's groupLimit()): the limit and offset set so far apply to each value of `column`,
1116
+ * the parent's key, instead of to the whole query. Compiled as row_number() over (partition by …).
1117
+ */
1118
+ limitPerGroup(column: string): this;
1099
1119
  first(): Promise<T | undefined>;
1100
1120
  find(id: unknown, keyName?: string): Promise<T | undefined>;
1101
1121
  value<V = unknown>(column: string): Promise<V | undefined>;
@@ -1217,6 +1237,8 @@ declare class DatabaseManagerImpl implements DatabaseManager {
1217
1237
  private readonly config;
1218
1238
  private readonly connections;
1219
1239
  private defaultName;
1240
+ /** usingConnection()'s name, for its own async context only: requests running beside it keep theirs. */
1241
+ private readonly using;
1220
1242
  /** Pass the config, or a function that reads it (the provider reads config('database') lazily). */
1221
1243
  constructor(config: DatabaseConfig | (() => DatabaseConfig));
1222
1244
  private settings;
@@ -1226,8 +1248,8 @@ declare class DatabaseManagerImpl implements DatabaseManager {
1226
1248
  /** Overrides config('database.default'); undefined clears the override. */
1227
1249
  setDefaultConnection(name: string | undefined): void;
1228
1250
  /**
1229
- * Runs `callback` with `name` as the default connection (Laravel's usingConnection()), then restores the previous
1230
- * override, or none, so the default follows config('database.default') again. Without a name, just runs it.
1251
+ * Runs `callback` with `name` as the default connection (Laravel's usingConnection()), for the callback's own async
1252
+ * context only: other requests running meanwhile keep their default. Without a name, just runs it.
1231
1253
  */
1232
1254
  usingConnection<T>(name: string | undefined, callback: () => Promise<T>): Promise<T>;
1233
1255
  /** The connections opened so far. */
@@ -1383,12 +1405,6 @@ declare class EloquentCollection<M extends Model = Model> extends Collection<M>
1383
1405
  toQuery(): Builder<M>;
1384
1406
  }
1385
1407
 
1386
- /**
1387
- * A relation is the related model's query builder, constrained to the parent: post.comments() is a
1388
- * Builder<Comment> with `where comments.post_id = ?`, so every builder method (where, orderBy, paginate, a local
1389
- * scope, …) works on it. Subclasses add eager loading (addEagerConstraints/initRelation/match) and the existence
1390
- * queries behind has()/whereHas()/withCount().
1391
- */
1392
1408
  declare abstract class Relation<R extends Model = Model, P extends Model = Model, Result = unknown> extends Builder<R> {
1393
1409
  readonly parent: P;
1394
1410
  /** The name the relation is loaded under (set when resolved by name, for eager loading and associate()). */
@@ -1399,6 +1415,20 @@ declare abstract class Relation<R extends Model = Model, P extends Model = Model
1399
1415
  protected constructor(related: R, parent: P);
1400
1416
  getParent(): P;
1401
1417
  getRelated(): R;
1418
+ /**
1419
+ * When the related table is the parent's own (a category's children, a user's followers), the existence query reads it
1420
+ * under an alias, `oriel_reserved_<n>`, so its columns aren't the outer row's. The related model takes the alias as its
1421
+ * table, so its qualified columns (keys, soft deletes, a constraint's qualifyColumn()) follow. Returns the alias, or
1422
+ * undefined when the tables differ.
1423
+ */
1424
+ protected aliasSelfTable(query: Builder<R>): string | undefined;
1425
+ /**
1426
+ * @internal After an eager load's constraint: a limit() or offset() set there applies to each parent, as in Laravel 11,
1427
+ * on the relations that know the column holding the parent's key.
1428
+ */
1429
+ limitEagerPerParent(): void;
1430
+ /** The column of the eager query holding each row's parent key; undefined where a per-parent limit makes no sense. */
1431
+ protected eagerPartitionColumn(): string | undefined;
1402
1432
  /** Subclasses call this last in their constructor: adds the per-parent constraints unless eager loading. */
1403
1433
  protected init(): void;
1404
1434
  /** The constraints for one parent: where comments.post_id = post.id. */
@@ -1609,7 +1639,11 @@ declare class Builder<M extends Model = Model> extends Builder$1<M> {
1609
1639
  pluck<V = unknown>(column: Column<M>): Promise<Collection<V>>;
1610
1640
  /** Whether `id` can't be one of the model's unique ids (not a UUID for HasUuids): it matches no row. */
1611
1641
  protected isMalformedKey(id: unknown): boolean;
1612
- /** A malformed unique id (HasUuids, HasUlids) finds nothing without a query, as route model binding does. */
1642
+ /**
1643
+ * A model by its key, or undefined; with an array of keys, the models found, as a collection (Laravel's find()). A
1644
+ * malformed unique id (HasUuids, HasUlids) finds nothing without a query, as route model binding does.
1645
+ */
1646
+ find(ids: readonly unknown[]): Promise<EloquentCollection<M>>;
1613
1647
  find(id: unknown): Promise<M | undefined>;
1614
1648
  findMany(ids: readonly unknown[]): Promise<EloquentCollection<M>>;
1615
1649
  /** find(), or ModelNotFoundError (a 404). With an array, every id must exist. */
@@ -1703,8 +1737,9 @@ interface HasRelationship {
1703
1737
  interface ForRelationship {
1704
1738
  parent: RelatedFactory | Model;
1705
1739
  relationship: string;
1706
- resolved?: Model;
1707
1740
  }
1741
+ /** The for() parents one make()/create()/raw() call has resolved: shared by that call's models, made again by the next. */
1742
+ type ResolvedParents = Map<ForRelationship, Model>;
1708
1743
  /** The builder state newInstance() copies and changes. */
1709
1744
  interface FactoryState<M extends Model> {
1710
1745
  countValue: number | undefined;
@@ -1748,7 +1783,11 @@ declare abstract class Factory<M extends Model = Model> {
1748
1783
  trashed(): this;
1749
1784
  /** Creates related models for each created model: has(Post.factory().count(3)) (relationship default: 'posts'). */
1750
1785
  has(factory: RelatedFactory, relationship?: string, pivot?: Row): this;
1751
- /** Sets a belongsTo parent: for(User.factory()) or for(user) (relationship default: 'user'). Created once. */
1786
+ /**
1787
+ * Sets a belongsTo parent: for(User.factory()) or for(user) (relationship default: 'user'). A factory parent is made
1788
+ * once per make()/create() call, for all of its models, and again by the next call, so a factory kept in a variable
1789
+ * never points at a parent an earlier test rolled back.
1790
+ */
1752
1791
  for(parent: RelatedFactory | Model, relationship?: string): this;
1753
1792
  afterMaking(callback: (model: M) => unknown): this;
1754
1793
  afterCreating(callback: (model: M) => unknown): this;
@@ -1765,7 +1804,7 @@ declare abstract class Factory<M extends Model = Model> {
1765
1804
  protected newInstance(changes: Partial<FactoryState<M>>): this;
1766
1805
  protected makeModels(attributes: Row): Promise<M[]>;
1767
1806
  /** definition() + states + overrides + for() parents, with factory and function values expanded. */
1768
- protected attributesFor(overrides: Row, index: number): Promise<Row>;
1807
+ protected attributesFor(overrides: Row, index: number, parents?: ResolvedParents): Promise<Row>;
1769
1808
  private parentAttributes;
1770
1809
  private createChildren;
1771
1810
  private relationOn;
@@ -1848,6 +1887,7 @@ declare class BelongsToMany<R extends Model, P extends Model = Model> extends Re
1848
1887
  getResults(): Promise<EloquentCollection<R>>;
1849
1888
  initRelation(models: P[], relation: string): P[];
1850
1889
  match(models: P[], results: R[], relation: string): P[];
1890
+ protected eagerPartitionColumn(): string;
1851
1891
  getRelationExistenceQuery(query: Builder<R>, _parentQuery: Builder<P>, columns?: ColumnRef[]): Builder<R>;
1852
1892
  /** Inserts pivot rows for ids (or models, or { id: attributes }), with shared extra attributes. */
1853
1893
  attach(ids: PivotIds, attributes?: Row): Promise<void>;
@@ -1942,6 +1982,7 @@ declare abstract class HasOneOrMany<R extends Model, P extends Model, Result> ex
1942
1982
  protected setForeignAttributes(model: R): R;
1943
1983
  saveMany(models: Iterable<R>): Promise<R[]>;
1944
1984
  createMany(records: Row[]): Promise<R[]>;
1985
+ protected eagerPartitionColumn(): string;
1945
1986
  getRelationExistenceQuery(query: Builder<R>, _parentQuery: Builder<P>, columns?: ColumnRef[]): Builder<R>;
1946
1987
  }
1947
1988
 
@@ -2211,6 +2252,7 @@ declare class Model implements ModelInstance {
2211
2252
  static onlyTrashed<C extends typeof Model>(this: C): ModelBuilder<C>;
2212
2253
  static withoutTrashed<C extends typeof Model>(this: C): ModelBuilder<C>;
2213
2254
  static all<C extends typeof Model>(this: C): Promise<EloquentCollection<Instance<C>>>;
2255
+ static find<C extends typeof Model>(this: C, ids: readonly unknown[]): Promise<EloquentCollection<Instance<C>>>;
2214
2256
  static find<C extends typeof Model>(this: C, id: unknown): Promise<Instance<C> | undefined>;
2215
2257
  static findOrFail<C extends typeof Model>(this: C, ids: readonly unknown[]): Promise<EloquentCollection<Instance<C>>>;
2216
2258
  static findOrFail<C extends typeof Model>(this: C, id: unknown): Promise<Instance<C>>;
package/dist/index.js CHANGED
@@ -740,10 +740,33 @@ var Grammar = class {
740
740
  columnize(columns) {
741
741
  return join(columns.map((column) => this.wrap(column)));
742
742
  }
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("*");
743
+ compileSelect(query, extraColumn) {
744
+ if (query.groupLimit && extraColumn === void 0) return this.compileGroupLimit(query);
745
+ 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("*")];
746
+ const columns = join(extraColumn ? [...list3, extraColumn] : list3);
745
747
  return clauses([query.distinctRows ? sql2`select distinct ${columns}` : sql2`select ${columns}`, this.compileComponents(query)]);
746
748
  }
749
+ /**
750
+ * Laravel 11's compileGroupLimit(): the query numbers its rows per `column` in its own order, and an outer query keeps
751
+ * those inside the limit and offset, in row-number order. SQLite 3.25+, MySQL 8 and PostgreSQL have window functions.
752
+ */
753
+ compileGroupLimit(query) {
754
+ const { column, limit, offset } = query.groupLimit;
755
+ const inner = query.clone();
756
+ inner.groupLimit = void 0;
757
+ inner.orders = [];
758
+ const order = this.compileOrders(query);
759
+ const over = order ? sql2`partition by ${this.wrap(column)} ${order}` : sql2`partition by ${this.wrap(column)}`;
760
+ const row = sql2.id(GROUP_ROW);
761
+ const kept = [];
762
+ if (offset !== void 0 && offset > 0) kept.push(sql2`${row} > ${sql2.lit(offset)}`);
763
+ if (limit !== void 0) kept.push(sql2`${row} <= ${sql2.lit((offset ?? 0) + limit)}`);
764
+ return clauses([
765
+ sql2`select * from (${this.compileSelect(inner, sql2`row_number() over (${over}) as ${row}`)}) as ${sql2.id("oriel_table")}`,
766
+ kept.length ? sql2`where ${join(kept, " and ")}` : void 0,
767
+ sql2`order by ${row}`
768
+ ]);
769
+ }
747
770
  /** Everything after the select list: from, joins, where, group by, having, order by, limit/offset, lock. */
748
771
  compileComponents(query) {
749
772
  return clauses([
@@ -770,7 +793,9 @@ var Grammar = class {
770
793
  switch (where.type) {
771
794
  case "basic": {
772
795
  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)}`;
796
+ const operator = this.operator(where.operator);
797
+ if (this.driver === "pgsql" && /like/i.test(operator)) return sql2`${column}::text ${sql2.raw(operator)} ${this.parameter(where.value)}`;
798
+ return sql2`${column} ${sql2.raw(operator)} ${this.parameter(where.value)}`;
774
799
  }
775
800
  case "in": {
776
801
  const keyword = sql2.raw(where.not ? "not in" : "in");
@@ -849,7 +874,10 @@ var Grammar = class {
849
874
  if (mode === "update") return sql2.raw("for update");
850
875
  return sql2.raw(this.driver === "pgsql" ? "for share" : "lock in share mode");
851
876
  }
852
- /** `select count(*) as aggregate …`. Orders, limit and offset are dropped; grouped or distinct queries are wrapped. */
877
+ /**
878
+ * `select count(*) as aggregate …`. Orders, limit and offset are dropped. Grouped or distinct queries, and those with a
879
+ * `having` (which may name a selected alias, withCount()'s `comments_count`), are wrapped, keeping their columns.
880
+ */
853
881
  compileAggregate(query, fn, column) {
854
882
  const inner = query.clone();
855
883
  inner.orders = [];
@@ -857,7 +885,7 @@ var Grammar = class {
857
885
  inner.offsetValue = void 0;
858
886
  inner.lockMode = void 0;
859
887
  const target = column === "*" ? sql2.raw("*") : this.wrap(column);
860
- if (inner.groups.length || inner.distinctRows) {
888
+ if (inner.groups.length || inner.distinctRows || inner.havings.length) {
861
889
  if (fn === "count") return sql2`select count(*) as ${sql2.id("aggregate")} from (${this.compileSelect(inner)}) as ${sql2.id("temp_table")}`;
862
890
  if (column instanceof Expression) {
863
891
  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 +973,7 @@ var Grammar = class {
945
973
  };
946
974
 
947
975
  // Query/Builder.ts
976
+ var GROUP_ROW = "oriel_row";
948
977
  async function* chunksOf(query, chunkSize) {
949
978
  for (let page = 1; ; page++) {
950
979
  const results = await query.clone().forPage(page, chunkSize).runSelect();
@@ -1005,6 +1034,8 @@ var Builder = class _Builder {
1005
1034
  orders = [];
1006
1035
  limitValue;
1007
1036
  offsetValue;
1037
+ /** A limit and offset per value of `column` (each parent of an eager load), compiled as a window (limitPerGroup()). */
1038
+ groupLimit;
1008
1039
  lockMode;
1009
1040
  // ---------------------------------------------------------------- building
1010
1041
  from(table) {
@@ -1293,7 +1324,20 @@ var Builder = class _Builder {
1293
1324
  }
1294
1325
  /** The raw rows, without a Collection around them. */
1295
1326
  async runSelect() {
1296
- return (await this.connection.execute(this.grammar.compileSelect(this))).rows;
1327
+ const rows = (await this.connection.execute(this.grammar.compileSelect(this))).rows;
1328
+ if (this.groupLimit) for (const row of rows) delete row[GROUP_ROW];
1329
+ return rows;
1330
+ }
1331
+ /**
1332
+ * @internal Eager loading (Laravel 11's groupLimit()): the limit and offset set so far apply to each value of `column`,
1333
+ * the parent's key, instead of to the whole query. Compiled as row_number() over (partition by …).
1334
+ */
1335
+ limitPerGroup(column) {
1336
+ if (this.limitValue === void 0 && this.offsetValue === void 0) return this;
1337
+ this.groupLimit = { column, limit: this.limitValue, offset: this.offsetValue };
1338
+ this.limitValue = void 0;
1339
+ this.offsetValue = void 0;
1340
+ return this;
1297
1341
  }
1298
1342
  async first() {
1299
1343
  const rows = await this.clone().limit(1).runSelect();
@@ -3034,6 +3078,7 @@ var Connection = class {
3034
3078
  db;
3035
3079
  context = new AsyncLocalStorage();
3036
3080
  pinned = [];
3081
+ savepoints = 0;
3037
3082
  loggingQueries = false;
3038
3083
  queryLog = [];
3039
3084
  getName() {
@@ -3153,23 +3198,38 @@ var Connection = class {
3153
3198
  }
3154
3199
  async open() {
3155
3200
  const parent = this.current();
3156
- if (!parent) return { trx: await this.db.startTransaction().execute(), level: 1 };
3201
+ if (!parent) return { trx: await this.db.startTransaction().execute(), level: 1, turn: Promise.resolve() };
3202
+ const previous = parent.turn;
3203
+ let endTurn;
3204
+ parent.turn = new Promise((resolve) => endTurn = resolve);
3205
+ await previous;
3157
3206
  const level = parent.level + 1;
3158
- await sql7.raw(`SAVEPOINT trans${level}`).execute(parent.trx);
3159
- return { trx: parent.trx, level };
3207
+ const savepoint = `trans${level}_${++this.savepoints}`;
3208
+ try {
3209
+ await sql7.raw(`SAVEPOINT ${savepoint}`).execute(parent.trx);
3210
+ } catch (error) {
3211
+ endTurn();
3212
+ throw error;
3213
+ }
3214
+ return { trx: parent.trx, level, savepoint, turn: Promise.resolve(), endTurn };
3160
3215
  }
3161
3216
  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);
3217
+ try {
3218
+ if (frame.level === 1) {
3219
+ await (action === "commit" ? frame.trx.commit() : frame.trx.rollback()).execute();
3220
+ } else if (action === "commit") {
3221
+ await sql7.raw(`RELEASE SAVEPOINT ${frame.savepoint}`).execute(frame.trx);
3222
+ } else {
3223
+ await sql7.raw(`ROLLBACK TO SAVEPOINT ${frame.savepoint}`).execute(frame.trx);
3224
+ }
3225
+ } finally {
3226
+ frame.endTurn?.();
3168
3227
  }
3169
3228
  }
3170
3229
  };
3171
3230
 
3172
3231
  // DatabaseManager.ts
3232
+ import { AsyncLocalStorage as AsyncLocalStorage2 } from "async_hooks";
3173
3233
  var DatabaseManagerImpl = class {
3174
3234
  /** Pass the config, or a function that reads it (the provider reads config('database') lazily). */
3175
3235
  constructor(config) {
@@ -3178,6 +3238,8 @@ var DatabaseManagerImpl = class {
3178
3238
  config;
3179
3239
  connections = /* @__PURE__ */ new Map();
3180
3240
  defaultName;
3241
+ /** usingConnection()'s name, for its own async context only: requests running beside it keep theirs. */
3242
+ using = new AsyncLocalStorage2();
3181
3243
  settings() {
3182
3244
  return typeof this.config === "function" ? this.config() : this.config;
3183
3245
  }
@@ -3194,25 +3256,19 @@ var DatabaseManagerImpl = class {
3194
3256
  return connection;
3195
3257
  }
3196
3258
  getDefaultConnection() {
3197
- return this.defaultName ?? this.settings().default;
3259
+ return this.using.getStore() ?? this.defaultName ?? this.settings().default;
3198
3260
  }
3199
3261
  /** Overrides config('database.default'); undefined clears the override. */
3200
3262
  setDefaultConnection(name) {
3201
3263
  this.defaultName = name;
3202
3264
  }
3203
3265
  /**
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.
3266
+ * Runs `callback` with `name` as the default connection (Laravel's usingConnection()), for the callback's own async
3267
+ * context only: other requests running meanwhile keep their default. Without a name, just runs it.
3206
3268
  */
3207
3269
  async usingConnection(name, callback) {
3208
3270
  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
- }
3271
+ return this.using.run(name, callback);
3216
3272
  }
3217
3273
  /** The connections opened so far. */
3218
3274
  getConnections() {
@@ -3327,7 +3383,7 @@ var SchemaBuilderToken = token("Database.SchemaBuilder");
3327
3383
  var Schema = facade(SchemaBuilderToken);
3328
3384
 
3329
3385
  // Eloquent/Model.ts
3330
- import { AsyncLocalStorage as AsyncLocalStorage3 } from "async_hooks";
3386
+ import { AsyncLocalStorage as AsyncLocalStorage4 } from "async_hooks";
3331
3387
  import { DatabaseManager as DatabaseManager2, Hasher } from "@orieljs/contracts";
3332
3388
  import { Collection as Collection10 } from "@orieljs/collections";
3333
3389
  import { currentContainer as currentContainer3, inject } from "@orieljs/container";
@@ -3557,7 +3613,7 @@ var Builder2 = class extends Builder {
3557
3613
  if (models.length && this.model.hasModelListeners("retrieved")) {
3558
3614
  for (const model of models) await model.fireModelEvent("retrieved", false);
3559
3615
  }
3560
- if (models.length && this.eagerLoad.size) await this.eagerLoadRelations(models);
3616
+ if (models.length && query.eagerLoad.size) await query.eagerLoadRelations(models);
3561
3617
  return models;
3562
3618
  }
3563
3619
  // ---------------------------------------------------------------- eager loading
@@ -3598,6 +3654,7 @@ var Builder2 = class extends Builder {
3598
3654
  const relation = this.getRelation(name);
3599
3655
  relation.addEagerConstraints(models);
3600
3656
  constraint?.(relation);
3657
+ relation.limitEagerPerParent();
3601
3658
  const nested = this.relationsNestedUnder(name);
3602
3659
  if (Object.keys(nested).length) relation.with(nested);
3603
3660
  relation.initRelation(models, name);
@@ -3670,9 +3727,10 @@ var Builder2 = class extends Builder {
3670
3727
  const [rawName = "", as] = spec.split(/\s+as\s+/i);
3671
3728
  const name = rawName.trim();
3672
3729
  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);
3730
+ const query = relation.getRelationExistenceQuery(relation.getRelated().newQueryWithoutRelationships(), this);
3731
+ const target = column instanceof Expression ? column : new Expression(column === "*" ? "*" : this.connection.compile(this.grammar.wrap(query.getModel().qualifyColumn(column))).sql);
3674
3732
  const expression = fn && fn !== "exists" ? new Expression(`${fn}(${target.value})`, target.bindings) : target;
3675
- const query = relation.getRelationExistenceQuery(relation.getRelated().newQueryWithoutRelationships(), this, [expression]);
3733
+ query.select(expression);
3676
3734
  query.wheres.push(...relation.wheres);
3677
3735
  if (constraint) query.callScope((q) => constraint(q));
3678
3736
  const scoped = query.applyScopes();
@@ -3772,8 +3830,8 @@ var Builder2 = class extends Builder {
3772
3830
  isMalformedKey(id) {
3773
3831
  return this.model.uniqueIds().includes(this.model.getKeyName()) && !this.model.isValidUniqueId(id);
3774
3832
  }
3775
- /** A malformed unique id (HasUuids, HasUlids) finds nothing without a query, as route model binding does. */
3776
3833
  async find(id) {
3834
+ if (Array.isArray(id)) return this.findMany(id);
3777
3835
  if (this.isMalformedKey(id)) return void 0;
3778
3836
  return this.clone().whereKey(id).first();
3779
3837
  }
@@ -4283,6 +4341,7 @@ function resolveMorphClass(type) {
4283
4341
  }
4284
4342
 
4285
4343
  // Eloquent/Relations/Relation.ts
4344
+ var selfAliases = 0;
4286
4345
  var Relation = class extends Builder2 {
4287
4346
  constructor(related, parent) {
4288
4347
  super(related);
@@ -4306,6 +4365,32 @@ var Relation = class extends Builder2 {
4306
4365
  getRelated() {
4307
4366
  return this.model;
4308
4367
  }
4368
+ /**
4369
+ * When the related table is the parent's own (a category's children, a user's followers), the existence query reads it
4370
+ * under an alias, `oriel_reserved_<n>`, so its columns aren't the outer row's. The related model takes the alias as its
4371
+ * table, so its qualified columns (keys, soft deletes, a constraint's qualifyColumn()) follow. Returns the alias, or
4372
+ * undefined when the tables differ.
4373
+ */
4374
+ aliasSelfTable(query) {
4375
+ const table = query.getModel().getTable();
4376
+ if (table !== this.parent.getTable()) return void 0;
4377
+ const alias = `oriel_reserved_${selfAliases++}`;
4378
+ query.from(`${table} as ${alias}`);
4379
+ query.getModel().setTable(alias);
4380
+ return alias;
4381
+ }
4382
+ /**
4383
+ * @internal After an eager load's constraint: a limit() or offset() set there applies to each parent, as in Laravel 11,
4384
+ * on the relations that know the column holding the parent's key.
4385
+ */
4386
+ limitEagerPerParent() {
4387
+ const column = this.eagerPartitionColumn();
4388
+ if (column !== void 0) this.limitPerGroup(column);
4389
+ }
4390
+ /** The column of the eager query holding each row's parent key; undefined where a per-parent limit makes no sense. */
4391
+ eagerPartitionColumn() {
4392
+ return void 0;
4393
+ }
4309
4394
  /** Subclasses call this last in their constructor: adds the per-parent constraints unless eager loading. */
4310
4395
  init() {
4311
4396
  if (relationConstraintsEnabled()) this.addConstraints();
@@ -4390,6 +4475,7 @@ var BelongsTo = class extends Relation {
4390
4475
  return this.associate(null);
4391
4476
  }
4392
4477
  getRelationExistenceQuery(query, _parentQuery, columns = ["*"]) {
4478
+ this.aliasSelfTable(query);
4393
4479
  return query.select(...columns).whereColumn(this.getQualifiedForeignKeyName(), "=", this.getQualifiedOwnerKeyName());
4394
4480
  }
4395
4481
  /** The loaded-relation name: the resolved name, else the related class in camelCase (author → pass it explicitly). */
@@ -4484,7 +4570,11 @@ var BelongsToMany = class extends Relation {
4484
4570
  for (const model of models) model.setRelation(relation, this.getRelated().newCollection(dictionary.get(String(model.getAttribute(this.parentKey))) ?? []));
4485
4571
  return models;
4486
4572
  }
4573
+ eagerPartitionColumn() {
4574
+ return this.qualifyPivotColumn(this.foreignPivotKey);
4575
+ }
4487
4576
  getRelationExistenceQuery(query, _parentQuery, columns = ["*"]) {
4577
+ this.aliasSelfTable(query);
4488
4578
  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
4579
  }
4490
4580
  // ---------------------------------------------------------------- the pivot table
@@ -4766,9 +4856,17 @@ var HasOneOrMany = class extends Relation {
4766
4856
  for (const record of records) created.push(await this.create(record));
4767
4857
  return created;
4768
4858
  }
4859
+ eagerPartitionColumn() {
4860
+ return this.foreignKey;
4861
+ }
4769
4862
  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);
4863
+ const alias = this.aliasSelfTable(query);
4864
+ const foreignKey = alias === void 0 ? this.foreignKey : `${alias}.${this.getForeignKeyName()}`;
4865
+ query.select(...columns).whereColumn(this.getQualifiedParentKeyName(), "=", foreignKey);
4866
+ if (this.morph) {
4867
+ const type = alias === void 0 ? this.morph.type : `${alias}.${this.morph.type.slice(this.morph.type.lastIndexOf(".") + 1)}`;
4868
+ query.where(type, "=", this.morph.value);
4869
+ }
4772
4870
  return query;
4773
4871
  }
4774
4872
  };
@@ -4912,7 +5010,11 @@ var Factory = class _Factory {
4912
5010
  const name = relationship ?? Str5.camel(Str5.plural(new factory.model().constructor.name));
4913
5011
  return this.newInstance({ hasRelations: [...this.hasRelations, { factory, relationship: name, pivot }] });
4914
5012
  }
4915
- /** Sets a belongsTo parent: for(User.factory()) or for(user) (relationship default: 'user'). Created once. */
5013
+ /**
5014
+ * Sets a belongsTo parent: for(User.factory()) or for(user) (relationship default: 'user'). A factory parent is made
5015
+ * once per make()/create() call, for all of its models, and again by the next call, so a factory kept in a variable
5016
+ * never points at a parent an earlier test rolled back.
5017
+ */
4916
5018
  for(parent, relationship) {
4917
5019
  const cls = parent instanceof Model ? parent.constructor : new parent.model().constructor;
4918
5020
  return this.newInstance({ forRelations: [...this.forRelations, { parent, relationship: relationship ?? Str5.camel(cls.name) }] });
@@ -4926,7 +5028,8 @@ var Factory = class _Factory {
4926
5028
  /** The attributes only, without a model (a Row, or a Row[] after count()). */
4927
5029
  async raw(attributes = {}) {
4928
5030
  const rows = [];
4929
- for (let index = 0; index < (this.countValue ?? 1); index++) rows.push(await this.attributesFor(attributes, index));
5031
+ const parents = /* @__PURE__ */ new Map();
5032
+ for (let index = 0; index < (this.countValue ?? 1); index++) rows.push(await this.attributesFor(attributes, index, parents));
4930
5033
  return this.countValue === void 0 ? rows[0] : rows;
4931
5034
  }
4932
5035
  /** Unsaved models (afterMaking callbacks run). */
@@ -4964,20 +5067,21 @@ var Factory = class _Factory {
4964
5067
  }
4965
5068
  async makeModels(attributes) {
4966
5069
  const models = [];
5070
+ const parents = /* @__PURE__ */ new Map();
4967
5071
  for (let index = 0; index < (this.countValue ?? 1); index++) {
4968
- const model = new this.model().forceFill(await this.attributesFor(attributes, index));
5072
+ const model = new this.model().forceFill(await this.attributesFor(attributes, index, parents));
4969
5073
  for (const callback of this.afterMakingCallbacks) await callback(model);
4970
5074
  models.push(model);
4971
5075
  }
4972
5076
  return models;
4973
5077
  }
4974
5078
  /** definition() + states + overrides + for() parents, with factory and function values expanded. */
4975
- async attributesFor(overrides, index) {
5079
+ async attributesFor(overrides, index, parents = /* @__PURE__ */ new Map()) {
4976
5080
  const context = { index, count: this.countValue ?? 1 };
4977
5081
  let attributes = this.definition();
4978
5082
  for (const state of this.states) attributes = { ...attributes, ...typeof state === "function" ? state(attributes, context) : state };
4979
5083
  attributes = { ...attributes, ...overrides };
4980
- for (const parent of this.forRelations) Object.assign(attributes, await this.parentAttributes(parent));
5084
+ for (const parent of this.forRelations) Object.assign(attributes, await this.parentAttributes(parent, parents));
4981
5085
  const expanded = {};
4982
5086
  for (const [key, value] of Object.entries(attributes)) {
4983
5087
  if (value instanceof _Factory) expanded[key] = (await value.createOne()).getKey();
@@ -4987,8 +5091,12 @@ var Factory = class _Factory {
4987
5091
  }
4988
5092
  return expanded;
4989
5093
  }
4990
- async parentAttributes(parent) {
4991
- const resolved = parent.resolved ??= parent.parent instanceof Model ? parent.parent : await parent.parent.createOne();
5094
+ async parentAttributes(parent, parents) {
5095
+ let resolved = parents.get(parent);
5096
+ if (resolved === void 0) {
5097
+ resolved = parent.parent instanceof Model ? parent.parent : await parent.parent.createOne();
5098
+ parents.set(parent, resolved);
5099
+ }
4992
5100
  const relation = this.relationOn(new this.model(), parent.relationship);
4993
5101
  if (relation instanceof MorphTo) {
4994
5102
  return { [relation.getForeignKeyName()]: resolved.getKey(), [relation.getMorphType()]: resolved.getMorphClass() };
@@ -5032,7 +5140,7 @@ async function discoverFactories(path) {
5032
5140
  }
5033
5141
 
5034
5142
  // Eloquent/events.ts
5035
- import { AsyncLocalStorage as AsyncLocalStorage2 } from "async_hooks";
5143
+ import { AsyncLocalStorage as AsyncLocalStorage3 } from "async_hooks";
5036
5144
  import { EventDispatcher } from "@orieljs/contracts";
5037
5145
  import { currentContainer as currentContainer2 } from "@orieljs/container";
5038
5146
  var MODEL_EVENTS = [
@@ -5050,7 +5158,7 @@ var MODEL_EVENTS = [
5050
5158
  "forceDeleting",
5051
5159
  "forceDeleted"
5052
5160
  ];
5053
- var muted = new AsyncLocalStorage2();
5161
+ var muted = new AsyncLocalStorage3();
5054
5162
  function modelEventName(event, className) {
5055
5163
  return `eloquent.${event}: ${className}`;
5056
5164
  }
@@ -5275,7 +5383,7 @@ var prototypes = /* @__PURE__ */ new Map();
5275
5383
  var unguardedGlobally = { value: false };
5276
5384
  var addingDefaultCounts = /* @__PURE__ */ new Set();
5277
5385
  var PLAIN_COLUMN = /^[A-Za-z_][A-Za-z0-9_]*$/;
5278
- var unguardedScope = new AsyncLocalStorage3();
5386
+ var unguardedScope = new AsyncLocalStorage4();
5279
5387
  var globalScopes = /* @__PURE__ */ new Map();
5280
5388
  var anonymousScopes = 0;
5281
5389
  function installScopeProxies(cls) {
@@ -6304,8 +6412,11 @@ var Model = class _Model {
6304
6412
  }
6305
6413
  async incrementOrDecrement(column, amount, extra) {
6306
6414
  if (!this.exists) return this.newQueryWithoutRelationships().increment(column, amount, extra);
6307
- const affected = await this.setKeysForSaveQuery(this.newModelQuery()).increment(column, amount, extra);
6308
6415
  this.forceFill({ ...extra, [column]: Number(this.getAttribute(column) ?? 0) + amount });
6416
+ if (await this.fireModelEvent("updating") === false) return 0;
6417
+ const affected = await this.setKeysForSaveQuery(this.newModelQuery()).increment(column, amount, extra);
6418
+ this.syncChanges();
6419
+ await this.fireModelEvent("updated", false);
6309
6420
  this.syncOriginalAttributes(column, ...Object.keys(extra));
6310
6421
  return affected;
6311
6422
  }
@@ -7176,12 +7287,14 @@ var TypeGenerator = class {
7176
7287
  const members = attributes.filter(([column]) => !(column in instance));
7177
7288
  const extra = accessors(model).filter(([attribute]) => !columns.some((column) => column.name === attribute) && !(attribute in instance));
7178
7289
  const statics = scopes(model).filter(([method]) => !(method in Model));
7290
+ const hidden = instance.getHidden().filter((column) => columns.some(({ name: columnName }) => columnName === column));
7179
7291
  const lines = [
7180
7292
  `declare module '${this.modulePath(file)}' {`,
7181
7293
  ` interface ${name} {`,
7182
7294
  " $attributes?: {",
7183
7295
  ...attributes.map(([column, type]) => ` ${this.key(column)}: ${type}`),
7184
7296
  " }",
7297
+ ...hidden.length ? [` $hidden?: ${hidden.map((column) => `'${column}'`).join(" | ")}`] : [],
7185
7298
  ...members.map(([column, type]) => ` ${this.key(column)}: ${type}`),
7186
7299
  ...extra.map(([attribute, method]) => ` ${this.key(attribute)}: ReturnType<${name}['${method}']>`),
7187
7300
  " }"