@mikro-orm/core 7.0.17 → 7.0.18-dev.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (69) hide show
  1. package/EntityManager.d.ts +106 -12
  2. package/EntityManager.js +228 -19
  3. package/MikroORM.d.ts +3 -3
  4. package/README.md +2 -1
  5. package/connections/Connection.d.ts +67 -1
  6. package/connections/Connection.js +64 -0
  7. package/drivers/DatabaseDriver.d.ts +1 -0
  8. package/drivers/DatabaseDriver.js +3 -0
  9. package/drivers/IDatabaseDriver.d.ts +50 -7
  10. package/entity/BaseEntity.d.ts +70 -3
  11. package/entity/BaseEntity.js +18 -0
  12. package/entity/Collection.d.ts +6 -3
  13. package/entity/Collection.js +15 -4
  14. package/entity/EntityAssigner.js +8 -0
  15. package/entity/EntityFactory.js +20 -1
  16. package/entity/EntityLoader.d.ts +8 -1
  17. package/entity/EntityLoader.js +41 -16
  18. package/entity/EntityRepository.d.ts +27 -9
  19. package/entity/EntityRepository.js +12 -0
  20. package/entity/Reference.d.ts +42 -1
  21. package/entity/Reference.js +9 -0
  22. package/entity/WrappedEntity.d.ts +2 -2
  23. package/entity/defineEntity.d.ts +92 -17
  24. package/entity/defineEntity.js +17 -6
  25. package/entity/utils.js +4 -5
  26. package/enums.d.ts +8 -1
  27. package/errors.d.ts +2 -0
  28. package/errors.js +4 -0
  29. package/index.d.ts +2 -2
  30. package/index.js +1 -1
  31. package/metadata/EntitySchema.js +3 -0
  32. package/metadata/MetadataDiscovery.d.ts +11 -0
  33. package/metadata/MetadataDiscovery.js +135 -10
  34. package/metadata/MetadataValidator.d.ts +26 -0
  35. package/metadata/MetadataValidator.js +236 -0
  36. package/metadata/Routine.d.ts +74 -0
  37. package/metadata/Routine.js +140 -0
  38. package/metadata/index.d.ts +1 -0
  39. package/metadata/index.js +1 -0
  40. package/metadata/types.d.ts +77 -4
  41. package/naming-strategy/AbstractNamingStrategy.d.ts +1 -1
  42. package/naming-strategy/NamingStrategy.d.ts +1 -1
  43. package/package.json +1 -1
  44. package/platforms/Platform.d.ts +7 -0
  45. package/platforms/Platform.js +15 -1
  46. package/serialization/EntitySerializer.d.ts +18 -6
  47. package/serialization/EntitySerializer.js +31 -4
  48. package/typings.d.ts +389 -18
  49. package/typings.js +21 -4
  50. package/unit-of-work/UnitOfWork.js +11 -3
  51. package/utils/AbstractMigrator.d.ts +26 -3
  52. package/utils/AbstractMigrator.js +264 -15
  53. package/utils/AbstractSchemaGenerator.d.ts +1 -1
  54. package/utils/AbstractSchemaGenerator.js +4 -1
  55. package/utils/Configuration.d.ts +40 -3
  56. package/utils/Configuration.js +46 -0
  57. package/utils/DataloaderUtils.d.ts +10 -1
  58. package/utils/DataloaderUtils.js +78 -0
  59. package/utils/QueryHelper.d.ts +16 -0
  60. package/utils/QueryHelper.js +15 -0
  61. package/utils/TransactionManager.js +2 -0
  62. package/utils/Utils.d.ts +1 -1
  63. package/utils/Utils.js +1 -1
  64. package/utils/fs-utils.d.ts +2 -0
  65. package/utils/fs-utils.js +7 -1
  66. package/utils/index.d.ts +1 -0
  67. package/utils/index.js +1 -0
  68. package/utils/partition-utils.d.ts +17 -0
  69. package/utils/partition-utils.js +79 -0
package/typings.d.ts CHANGED
@@ -10,8 +10,9 @@ import { Reference, type ScalarReference } from './entity/Reference.js';
10
10
  import type { SerializationContext } from './serialization/SerializationContext.js';
11
11
  import type { SerializeOptions } from './serialization/EntitySerializer.js';
12
12
  import type { MetadataStorage } from './metadata/MetadataStorage.js';
13
+ import type { Routine } from './metadata/Routine.js';
13
14
  import type { EntitySchema } from './metadata/EntitySchema.js';
14
- import type { IndexColumnOptions } from './metadata/types.js';
15
+ import type { EntityPartitionBy, IndexColumnOptions } from './metadata/types.js';
15
16
  import type { Type, types } from './types/index.js';
16
17
  import type { Platform } from './platforms/Platform.js';
17
18
  import type { Configuration } from './utils/Configuration.js';
@@ -47,7 +48,7 @@ export type AsyncFunction<R = any, T = Dictionary> = (args: T) => Promise<T>;
47
48
  export type Compute<T> = {
48
49
  [K in keyof T]: T[K];
49
50
  } & {};
50
- type InternalKeys = 'EntityRepositoryType' | 'PrimaryKeyProp' | 'OptionalProps' | 'EagerProps' | 'HiddenProps' | '__selectedType' | '__loadedType';
51
+ type InternalKeys = 'EntityRepositoryType' | 'PrimaryKeyProp' | 'OptionalProps' | 'EagerProps' | 'HiddenProps' | 'IndexHints' | '__selectedType' | '__loadedType';
51
52
  /** Filters out function, symbol, and internal keys from an entity type. When `B = true`, also excludes scalar keys. */
52
53
  export type CleanKeys<T, K extends keyof T, B extends boolean = false> = T[K] & {} extends Function ? never : K extends symbol | InternalKeys ? never : B extends true ? T[K] & {} extends Scalar ? never : K : K;
53
54
  /** Extracts keys of `T` whose values are functions. */
@@ -113,7 +114,7 @@ type LoadedReferenceShape<T = any> = ReferenceShape & {
113
114
  * Using this instead of `Loadable<any>` in conditional type checks prevents
114
115
  * TypeScript from evaluating the full Collection/Reference interfaces.
115
116
  */
116
- type LoadableShape = CollectionShape | ReferenceShape | readonly any[];
117
+ type LoadableShape = CollectionShape | ReferenceShape | LazyRef.Brand<any> | readonly any[];
117
118
  /** Gets all keys from all members of a union type (distributes over the union). */
118
119
  export type UnionKeys<T> = T extends any ? keyof T : never;
119
120
  /** Gets the type of a property from all union members that have it (distributes over the union). */
@@ -150,6 +151,44 @@ export declare const EntityName: unique symbol;
150
151
  export type InferEntityName<T> = T extends {
151
152
  [EntityName]?: infer Name;
152
153
  } ? (Name extends string ? Name : never) : never;
154
+ /**
155
+ * Symbol used to declare index-to-column mappings on an entity type.
156
+ * For decorator entities, declare as a phantom property:
157
+ * ```typescript
158
+ * [IndexHints]?: { idx_email: 'email'; idx_name_age: 'name' | 'age' };
159
+ * ```
160
+ * For `defineEntity` entities, index hints are inferred automatically from
161
+ * named indexes (property-level `.index('name')` and entity-level `indexes`/`uniques`).
162
+ */
163
+ export declare const IndexHints: unique symbol;
164
+ /**
165
+ * Extracts the index hints map from an entity type. Returns `never` when no hints are declared.
166
+ * For decorator entities, `[IndexHints]` contains a pre-computed `{ idxName: 'prop' }` map.
167
+ * For `defineEntity` entities, `[IndexHints]` contains `[Properties]` (a tuple wrapping the
168
+ * raw property builders), which is lazily converted to the index map when first accessed.
169
+ */
170
+ export type ExtractIndexHints<T> = T extends {
171
+ [IndexHints]?: infer H;
172
+ } ? H extends [infer P extends Record<string, any>] ? InferPropertyIndexMap<P> : H : never;
173
+ /**
174
+ * Extracts `{ indexName: propertyKey }` from property builder options.
175
+ * Checks `.index('name')` and `.unique('name')` on each property in a single pass.
176
+ */
177
+ export type InferPropertyIndexMap<Properties extends Record<string, any>> = {
178
+ [K in keyof Properties as MaybeReturnType<Properties[K]> extends {
179
+ '~options': {
180
+ index: infer N extends string;
181
+ };
182
+ } ? N : MaybeReturnType<Properties[K]> extends {
183
+ '~options': {
184
+ unique: infer N extends string;
185
+ };
186
+ } ? N : never]: K & string;
187
+ };
188
+ /** Union of declared index names on an entity. Falls back to `string` when no `[IndexHints]` are declared. */
189
+ export type IndexName<T> = [ExtractIndexHints<T>] extends [never] ? string : (keyof ExtractIndexHints<T> & string) | (string & {});
190
+ /** Properties covered by the named index on entity T. Falls back to all entity keys when the index is unknown. */
191
+ export type IndexColumns<T, Name extends string> = ExtractIndexHints<T> extends Record<Name, infer Cols> ? Cols & string : EntityKey<T>;
153
192
  /**
154
193
  * Branded type that marks a property as optional in `em.create()`.
155
194
  * Use as a property type wrapper: `createdAt: Opt<Date>` instead of listing in `[OptionalProps]`.
@@ -328,6 +367,18 @@ export type ObjectQuery<T> = OperatorMap<T> & FilterObject<T>;
328
367
  * Accepts an object query, a primary key value, entity props with operators, or an array of filters.
329
368
  */
330
369
  export type FilterQuery<T> = ObjectQuery<T> | NonNullable<ExpandScalar<Primary<T>>> | NonNullable<EntityProps<T> & OperatorMap<T>> | FilterQuery<T>[];
370
+ /**
371
+ * `FilterQuery` restricted to only properties covered by the specified index(es).
372
+ * Used when `using` option is set in `FindOptions` to enforce type-safe index usage.
373
+ */
374
+ export type IndexFilterQuery<T, Using extends string> = [Using] extends [never] ? FilterQuery<T> : (OperatorMap<T> & {
375
+ -readonly [K in Extract<EntityKey<T>, IndexColumns<T, Using>>]?: ExpandQuery<ExpandProperty<FilterObjectProp<T, K>>> | ExpandQueryMerged<ExpandProperty<FilterObjectProp<T, K>>> | FilterValue<ExpandProperty<FilterObjectProp<T, K>>> | ElemMatchFilter<FilterObjectProp<T, K>> | null;
376
+ }) | NonNullable<ExpandScalar<Primary<T>>> | IndexFilterQuery<T, Using>[];
377
+ /** Replaces `where` and `using` on an options type with index-aware variants when `Using` is specified. */
378
+ export type WithUsingOptions<Opts, Entity, Using extends string> = Omit<Opts, 'where' | 'using'> & {
379
+ using?: Using | Using[];
380
+ where?: [Using] extends [never] ? FilterQuery<Entity> : IndexFilterQuery<Entity, Using>;
381
+ };
331
382
  /** Public interface for the entity wrapper, accessible via `wrap(entity)`. Provides helper methods for entity state management. */
332
383
  export interface IWrappedEntity<Entity extends object> {
333
384
  isInitialized(): boolean;
@@ -341,7 +392,7 @@ export interface IWrappedEntity<Entity extends object> {
341
392
  toObject<Ignored extends EntityKey<Entity>>(ignoreFields: Ignored[]): Omit<EntityDTO<Entity>, Ignored>;
342
393
  toJSON(...args: any[]): EntityDTO<Entity>;
343
394
  toPOJO(): EntityDTO<Entity>;
344
- serialize<Naked extends FromEntityType<Entity> = FromEntityType<Entity>, Hint extends string = never, Exclude extends string = never>(options?: SerializeOptions<Naked, Hint, Exclude>): SerializeDTO<Naked, Hint, Exclude>;
395
+ serialize<Naked extends FromEntityType<Entity> = FromEntityType<Entity>, Hint extends string = never, Exclude extends string = never, Fields extends string = never>(options?: SerializeOptions<Naked, Hint, Exclude, Fields>): SerializeDTO<Naked, Hint, Exclude, never, ResolveSerializeFields<Fields, ExtractFieldsHint<Entity>>, SerializeFieldsKeepPK<Fields>>;
345
396
  setSerializationContext<Hint extends string = never, Fields extends string = never, Exclude extends string = never>(options: LoadHint<Entity, Hint, Fields, Exclude>): void;
346
397
  assign<Naked extends FromEntityType<Entity> = FromEntityType<Entity>, Convert extends boolean = false, Data extends EntityData<Naked, Convert> | Partial<EntityDTO<Naked>> = EntityData<Naked, Convert> | Partial<EntityDTO<Naked>>>(data: Data & IsSubset<EntityData<Naked, Convert>, Data>, options?: AssignOptions<Convert>): MergeSelected<Entity, Naked, keyof Data & string>;
347
398
  getSchema(): string | undefined;
@@ -417,12 +468,12 @@ type NonArrayObject = object & {
417
468
  export type EntityDataProp<T, C extends boolean> = T extends Date ? string | Date : T extends Scalar ? T : T extends ScalarReference<infer U> ? EntityDataProp<U, C> : T extends {
418
469
  __runtime?: infer Runtime;
419
470
  __raw?: infer Raw;
420
- } ? C extends true ? Raw : Runtime : T extends ReferenceShape<infer U> ? EntityDataNested<U, C> : T extends CollectionShape<infer U> ? U | U[] | EntityDataNested<U & object, C> | EntityDataNested<U & object, C>[] : T extends readonly (infer U)[] ? U extends NonArrayObject ? U | U[] | EntityDataNested<U, C> | EntityDataNested<U, C>[] : U[] | EntityDataNested<U, C>[] : EntityDataNested<T, C>;
471
+ } ? C extends true ? Raw : Runtime : T extends LazyRef.Brand<infer U> ? EntityDataNested<U, C> : T extends ReferenceShape<infer U> ? EntityDataNested<U, C> : T extends CollectionShape<infer U> ? U | U[] | EntityDataNested<U & object, C> | EntityDataNested<U & object, C>[] : T extends readonly (infer U)[] ? U extends NonArrayObject ? U | U[] | EntityDataNested<U, C> | EntityDataNested<U, C>[] : U[] | EntityDataNested<U, C>[] : EntityDataNested<T, C>;
421
472
  /** Like `EntityDataProp` but used in `RequiredEntityData` context with required/optional key distinction. */
422
473
  export type RequiredEntityDataProp<T, O, C extends boolean> = T extends Date ? string | Date : Exclude<T, null> extends RequiredNullable.Brand ? T | null : T extends Scalar ? T : T extends ScalarReference<infer U> ? RequiredEntityDataProp<U, O, C> : T extends {
423
474
  __runtime?: infer Runtime;
424
475
  __raw?: infer Raw;
425
- } ? C extends true ? Raw : Runtime : T extends ReferenceShape<infer U> ? RequiredEntityDataNested<U, O, C> : T extends CollectionShape<infer U> ? U | U[] | RequiredEntityDataNested<U & object, O, C> | RequiredEntityDataNested<U & object, O, C>[] : T extends readonly (infer U)[] ? U extends NonArrayObject ? U | U[] | RequiredEntityDataNested<U, O, C> | RequiredEntityDataNested<U, O, C>[] : U[] | RequiredEntityDataNested<U, O, C>[] : RequiredEntityDataNested<T, O, C>;
476
+ } ? C extends true ? Raw : Runtime : T extends LazyRef.Brand<infer U> ? RequiredEntityDataNested<U, O, C> : T extends ReferenceShape<infer U> ? RequiredEntityDataNested<U, O, C> : T extends CollectionShape<infer U> ? U | U[] | RequiredEntityDataNested<U & object, O, C> | RequiredEntityDataNested<U & object, O, C>[] : T extends readonly (infer U)[] ? U extends NonArrayObject ? U | U[] | RequiredEntityDataNested<U, O, C> | RequiredEntityDataNested<U, O, C>[] : U[] | RequiredEntityDataNested<U, O, C>[] : RequiredEntityDataNested<T, O, C>;
426
477
  /** Nested entity data shape for embedded or related entities within `EntityData`. */
427
478
  export type EntityDataNested<T, C extends boolean = false> = T extends undefined ? never : T extends any[] ? Readonly<T> : EntityData<T, C> | ExpandEntityProp<T, C>;
428
479
  type UnwrapScalarRef<T> = T extends ScalarReference<infer U> ? U : T;
@@ -471,6 +522,35 @@ type Relation<T> = {
471
522
  export type Rel<T> = T;
472
523
  /** Alias for `ScalarReference` (see {@apilink Ref}). */
473
524
  export type ScalarRef<T> = ScalarReference<T>;
525
+ /**
526
+ * Type-level marker for a to-one relation that is **direct at runtime** (no `Reference` wrapper) but
527
+ * **restricted at compile time** until narrowed via `Loaded<>`.
528
+ *
529
+ * Use as the property type on a `@ManyToOne`/`@OneToOne` relation that does **not** have `ref: true`:
530
+ *
531
+ * ```ts
532
+ * @ManyToOne(() => User)
533
+ * author!: LazyRef<User>;
534
+ * ```
535
+ *
536
+ * Semantics:
537
+ * - **Runtime**: identical to a plain direct relation — `article.author` is a `User` instance (stub or hydrated),
538
+ * `article.author instanceof User` is `true`, no `Reference` object is created.
539
+ * - **Type (unloaded view)**: only the primary key is accessible. Accessing other properties is a compile error.
540
+ * - **Type (loaded view)**: once the relation is in the populate hint of a `Loaded<Entity, 'author'>`, it narrows
541
+ * back to the full entity — no `.$` or `.get()` indirection needed.
542
+ *
543
+ * Note: the safety is purely compile-time. JS code or `as any` casts bypass it.
544
+ */
545
+ export type LazyRef<T extends object> = IsAny<T> extends true ? LazyRef.Brand<T> : {
546
+ [K in PrimaryProperty<T> & keyof T]: T[K];
547
+ } & LazyRef.Brand<T>;
548
+ export declare namespace LazyRef {
549
+ const __lazyRef: unique symbol;
550
+ interface Brand<T> {
551
+ [__lazyRef]?: (arg: T) => T;
552
+ }
553
+ }
474
554
  /** Alias for `Reference<T> & { id: number }` (see {@apilink Ref}). */
475
555
  export type EntityRef<T extends object> = true extends IsUnknown<PrimaryProperty<T>> ? Reference<T> : IsAny<T> extends true ? Reference<T> : {
476
556
  [K in PrimaryProperty<T> & keyof T]: T[K];
@@ -534,17 +614,32 @@ export type EntityDTOFlat<T, C extends TypeConfig = never> = {
534
614
  type SerializeTopHints<H extends string> = H extends `${infer Top}.${string}` ? Top : H;
535
615
  type SerializeSubHints<K extends string, H extends string> = H extends `${K}.${infer Rest}` ? Rest : never;
536
616
  type SerializeSubFields<K extends string, F extends string> = K extends F ? '*' : [F extends `${K & string}.${infer Rest}` ? Rest : never] extends [never] ? '*' : F extends `${K & string}.${infer Rest}` ? Rest : never;
537
- type SerializeFieldsFilter<T, K extends keyof T, F extends string> = K extends Prefix<T, F> | PrimaryProperty<T> ? K : never;
617
+ type SerializeFieldsFilter<T, K extends keyof T, F extends string, KeepPK extends boolean = true> = K extends Prefix<T, F> | (KeepPK extends true ? PrimaryProperty<T> : never) ? K : never;
538
618
  type SerializePropValue<T, K extends keyof T, H extends string, C extends TypeConfig = never> = K & string extends SerializeTopHints<H> ? NonNullable<T[K]> extends CollectionShape<infer U> ? SerializeDTO<U & object, SerializeSubHints<K & string, H>, never, C>[] : SerializeDTO<ExpandProperty<T[K]>, SerializeSubHints<K & string, H>, never, C> | Extract<T[K], null | undefined> : EntityDTOProp<T, T[K], C>;
539
- type SerializePropValueWithFields<T, K extends keyof T, H extends string, C extends TypeConfig, F extends string> = K & string extends SerializeTopHints<H> ? NonNullable<T[K]> extends CollectionShape<infer U> ? SerializeDTO<U & object, SerializeSubHints<K & string, H>, never, C, SerializeSubFields<K & string, F>>[] : SerializeDTO<ExpandProperty<T[K]>, SerializeSubHints<K & string, H>, never, C, SerializeSubFields<K & string, F>> | Extract<T[K], null | undefined> : EntityDTOProp<T, T[K], C>;
619
+ type SerializePropValueWithFields<T, K extends keyof T, H extends string, C extends TypeConfig, F extends string, KeepPK extends boolean = true> = K & string extends SerializeTopHints<H> ? NonNullable<T[K]> extends CollectionShape<infer U> ? SerializeDTO<U & object, SerializeSubHints<K & string, H>, never, C, SerializeSubFields<K & string, F>, KeepPK>[] : SerializeDTO<ExpandProperty<T[K]>, SerializeSubHints<K & string, H>, never, C, SerializeSubFields<K & string, F>, KeepPK> | Extract<T[K], null | undefined> : EntityDTOProp<T, T[K], C>;
620
+ /**
621
+ * Resolves a user-provided `Fields` generic to the value passed to `SerializeDTO`'s `F` parameter:
622
+ * `never` (no `fields` option) falls back to `Default` (typically `'*'` or the entity's `ExtractFieldsHint`).
623
+ */
624
+ export type ResolveSerializeFields<Fields extends string, Default extends string = '*'> = [Fields] extends [never] ? Default : Fields;
625
+ /**
626
+ * Whether the explicit `serialize()` path should keep primary keys in the output. When the user does not provide
627
+ * a `fields` option (`Fields = never`), behave like `toObject()` and keep PKs; when they do, treat it as a strict
628
+ * whitelist so PKs are dropped unless listed.
629
+ */
630
+ export type SerializeFieldsKeepPK<Fields extends string> = [Fields] extends [never] ? true : false;
540
631
  /**
541
632
  * Return type of `serialize()`. Combines Loaded + EntityDTO in a single pass for better performance.
542
633
  * Respects populate hints (`H`), exclude hints (`E`), and fields hints (`F`).
634
+ *
635
+ * `KeepPK` controls whether primary keys are auto-included when narrowing by `F`. The `toObject()` path keeps the
636
+ * default `true` (PKs always present); the explicit `serialize()` path passes `false` so the user-provided `fields`
637
+ * option is a strict whitelist that can drop PKs from the output.
543
638
  */
544
- export type SerializeDTO<T, H extends string = never, E extends string = never, C extends TypeConfig = never, F extends string = '*'> = string extends H ? EntityDTOFlat<T, C> : [F] extends ['*'] ? {
639
+ export type SerializeDTO<T, H extends string = never, E extends string = never, C extends TypeConfig = never, F extends string = '*', KeepPK extends boolean = true> = string extends H ? EntityDTOFlat<T, C> : [F] extends ['*'] ? {
545
640
  [K in keyof T as ExcludeHidden<T, K> & CleanKeys<T, K> & (IsNever<E> extends true ? K : Exclude<K, E>)]: SerializePropValue<T, K, H, C> | Extract<T[K], null | undefined>;
546
641
  } : {
547
- [K in keyof T as ExcludeHidden<T, K> & CleanKeys<T, K> & (IsNever<E> extends true ? K : Exclude<K, E>) & SerializeFieldsFilter<T, K, F>]: SerializePropValueWithFields<T, K, H, C, F> | Extract<T[K], null | undefined>;
642
+ [K in keyof T as ExcludeHidden<T, K> & CleanKeys<T, K> & (IsNever<E> extends true ? K : Exclude<K, E>) & SerializeFieldsFilter<T, K, F, KeepPK>]: SerializePropValueWithFields<T, K, H, C, F, KeepPK> | Extract<T[K], null | undefined>;
548
643
  };
549
644
  type TargetKeys<T> = T extends EntityClass<infer P> ? keyof P : keyof T;
550
645
  type PropertyName<T> = IsUnknown<T> extends false ? TargetKeys<T> : string;
@@ -605,6 +700,8 @@ export type IndexCallback<T> = (columns: Record<PropertyName<T>, string>, table:
605
700
  export type FormulaCallback<T> = (columns: FormulaColumns<T>, table: FormulaTable) => string | Raw;
606
701
  /** Callback for CHECK constraint expressions. Receives column mappings and table info. */
607
702
  export type CheckCallback<T> = (columns: SchemaColumns<T>, table: SchemaTable) => string | Raw;
703
+ /** Callback for trigger body expressions. Receives column mappings and table info. */
704
+ export type TriggerCallback<T> = (columns: Record<PropertyName<T>, string>, table: SchemaTable) => string | Raw;
608
705
  /**
609
706
  * Callback for generated (computed) column expressions. Receives column mappings and table info.
610
707
  * The runtime `columns` object includes nested entries for embedded properties (see `SchemaColumnRef`);
@@ -617,6 +714,214 @@ export interface CheckConstraint<T = any> {
617
714
  property?: string;
618
715
  expression: string | Raw | CheckCallback<T>;
619
716
  }
717
+ /** Definition of a database trigger on a table. */
718
+ export interface TriggerDef<T = any> {
719
+ /** Trigger name. Auto-generated if omitted. */
720
+ name?: string;
721
+ /** When the trigger fires relative to the event. */
722
+ timing: 'before' | 'after' | 'instead of';
723
+ /** Which DML events activate the trigger. */
724
+ events: ('insert' | 'update' | 'delete' | 'truncate')[];
725
+ /** Whether the trigger fires once per row or per statement. Defaults to `'row'`. */
726
+ forEach?: 'row' | 'statement';
727
+ /** SQL body of the trigger. Can be a string, Raw query, or callback receiving column name mappings. */
728
+ body?: string | Raw | TriggerCallback<T>;
729
+ /** Optional SQL WHEN condition for the trigger. */
730
+ when?: string;
731
+ /** Raw DDL escape hatch — full CREATE TRIGGER statement. Mutually exclusive with `body`. */
732
+ expression?: string;
733
+ }
734
+ export type RoutineParamDirection = 'in' | 'out' | 'inout';
735
+ /** Mirrors MySQL/MariaDB's `SQL DATA ACCESS` clause; ignored by other dialects. */
736
+ export type RoutineDataAccess = 'contains-sql' | 'no-sql' | 'reads-sql-data' | 'modifies-sql-data';
737
+ export type RoutineSecurity = 'invoker' | 'definer';
738
+ export type RoutineKind = 'procedure' | 'function';
739
+ export type RoutineIgnoreField = 'body' | 'comment' | 'security' | 'deterministic' | 'definer';
740
+ export type RoutineParamMap<T> = Record<PropertyName<T>, string>;
741
+ export type RoutineBodyCallback<T> = (params: RoutineParamMap<T>, em: any) => string | Raw;
742
+ /**
743
+ * Routine return shape:
744
+ * - omitted/`void`: procedures with no result set
745
+ * - `() => Entity` (single or tuple): hydrated row arrays, one per result set
746
+ * - `{ type: Type<...> }`: scalar function return — runtime/column types both inferred
747
+ * from the {@link Type} generics
748
+ * - `{ runtimeType, columnType }`: scalar function return with explicit SQL+TS types
749
+ * - `{ hydrate }`: fully custom row mapping
750
+ */
751
+ export type RoutineReturns<T = unknown> = (() => EntityName<any>) | (() => EntityName<any>)[] | {
752
+ type: Type<unknown> | Constructor<Type<unknown>>;
753
+ nullable?: boolean;
754
+ } | {
755
+ runtimeType: RoutineRuntimeType;
756
+ columnType?: string;
757
+ nullable?: boolean;
758
+ customType?: Type<unknown> | Constructor<Type<unknown>>;
759
+ } | {
760
+ hydrate: (rows: Dictionary[][], args: T, em: any) => unknown;
761
+ };
762
+ /** JS fallback registered as a UDF on SQLite (better-sqlite3). Functions only. */
763
+ export type RoutineJsBody<T> = (params: T) => unknown;
764
+ export interface RoutineDef<T = any> {
765
+ type: RoutineKind;
766
+ name?: string;
767
+ schema?: string;
768
+ comment?: string;
769
+ security?: RoutineSecurity;
770
+ /** User the routine runs as when `security: 'definer'`. */
771
+ definer?: string;
772
+ deterministic?: boolean;
773
+ /** MySQL/MariaDB only. */
774
+ dataAccess?: RoutineDataAccess;
775
+ language?: 'sql' | 'plpgsql' | 'tsql' | 'plsql' | AnyString;
776
+ /** Mutually exclusive with `expression`. */
777
+ body?: string | Raw | RoutineBodyCallback<T>;
778
+ /** Raw `CREATE PROCEDURE`/`FUNCTION` escape hatch — schema diff can't detect changes. Prefer `body`. */
779
+ expression?: string;
780
+ /** JS fallback registered as a UDF on SQLite (better-sqlite3). Functions only. */
781
+ bodyJs?: RoutineJsBody<T>;
782
+ returns?: RoutineReturns<T>;
783
+ /** Skip selected fields in schema diff; useful when the engine normalises the body differently. */
784
+ ignoreSchemaChanges?: RoutineIgnoreField[];
785
+ }
786
+ export interface RoutineProperty<Owner = any> {
787
+ name: EntityKey<Owner>;
788
+ /** SQL string, or a `Type` instance (resolved to the dialect column type at schema-gen time via `getColumnType`). */
789
+ type: keyof typeof types | AnyString | Type<unknown>;
790
+ runtimeType: EntityProperty['runtimeType'];
791
+ /** Singleton array to align with EntityProperty's `columnTypes`/Type API surface. */
792
+ columnTypes: string[];
793
+ customType?: Type<unknown>;
794
+ direction: RoutineParamDirection;
795
+ /** Required for OUT/INOUT params — wraps the JS-side value in `ScalarReference`. */
796
+ ref?: boolean;
797
+ length?: number;
798
+ precision?: number;
799
+ scale?: number;
800
+ nullable?: boolean;
801
+ /** Default expression used when the caller omits the parameter, where the dialect supports it. */
802
+ defaultRaw?: string;
803
+ /** Original declaration order, used to rebuild positional argument lists. */
804
+ index: number;
805
+ }
806
+ export interface RoutineParamConfig {
807
+ runtimeType?: RoutineRuntimeType;
808
+ type?: keyof typeof types | AnyString | Type<any> | Constructor<Type<any>>;
809
+ direction?: RoutineParamDirection;
810
+ ref?: boolean;
811
+ length?: number;
812
+ precision?: number;
813
+ scale?: number;
814
+ nullable?: boolean;
815
+ defaultRaw?: string;
816
+ /** Marshals the param via `Type.convertToDatabaseValue` inbound and `convertToJSValue` outbound. */
817
+ customType?: Type<unknown> | Constructor<Type<unknown>>;
818
+ }
819
+ /** Routine declaration shape accepted by the {@link Routine} class. */
820
+ export interface RoutineConfig<T = any> extends Omit<RoutineDef<T>, 'name'> {
821
+ name: string;
822
+ /** Order is preserved from `Object.keys`. */
823
+ params?: Record<string, RoutineParamConfig>;
824
+ }
825
+ export type RoutineRuntimeTypeMap = {
826
+ string: string;
827
+ number: number;
828
+ boolean: boolean;
829
+ bigint: bigint;
830
+ Buffer: Buffer;
831
+ Date: Date;
832
+ object: Dictionary;
833
+ any: any;
834
+ };
835
+ /** Narrow union (vs `EntityProperty['runtimeType']`) so literals survive `const` inference and feed args/return inference. */
836
+ export type RoutineRuntimeType = keyof RoutineRuntimeTypeMap;
837
+ type RoutineRuntimeOf<R> = R extends keyof RoutineRuntimeTypeMap ? RoutineRuntimeTypeMap[R] : unknown;
838
+ type Nullify<P, V> = P extends {
839
+ nullable: true;
840
+ } ? V | null : V;
841
+ type StripSqlTypeArgs<S extends string> = S extends `${infer Base}(${string}` ? Base : S;
842
+ type SqlStringTypes = 'varchar' | 'char' | 'character' | 'nvarchar' | 'nchar' | 'text' | 'mediumtext' | 'longtext' | 'tinytext' | 'ntext' | 'clob' | 'nclob' | 'citext' | 'xml' | 'uuid' | 'string' | 'decimal' | 'numeric' | 'money' | 'bigint' | 'int8' | 'bigserial';
843
+ type SqlNumberTypes = 'int' | 'integer' | 'smallint' | 'tinyint' | 'mediumint' | 'int2' | 'int4' | 'serial' | 'smallserial' | 'real' | 'float' | 'float4' | 'float8' | 'double';
844
+ type SqlBooleanTypes = 'boolean' | 'bool' | 'bit';
845
+ type SqlDateTypes = 'date' | 'datetime' | 'datetime2' | 'smalldatetime' | 'timestamp' | 'timestamptz' | 'time' | 'timetz';
846
+ type SqlJsonTypes = 'json' | 'jsonb';
847
+ type SqlBufferTypes = 'blob' | 'tinyblob' | 'mediumblob' | 'longblob' | 'binary' | 'varbinary' | 'bytea' | 'bytes' | 'image' | 'raw';
848
+ type SqlTypeMap = {
849
+ [K in SqlStringTypes]: string;
850
+ } & {
851
+ [K in SqlNumberTypes]: number;
852
+ } & {
853
+ [K in SqlBooleanTypes]: boolean;
854
+ } & {
855
+ [K in SqlDateTypes]: Date;
856
+ } & {
857
+ [K in SqlJsonTypes]: Dictionary;
858
+ } & {
859
+ [K in SqlBufferTypes]: Buffer;
860
+ } & {
861
+ 'character varying': string;
862
+ 'double precision': number;
863
+ 'time with time zone': Date;
864
+ 'timestamp with time zone': Date;
865
+ 'long raw': Buffer;
866
+ };
867
+ type LookupSqlType<K> = K extends keyof SqlTypeMap ? SqlTypeMap[K] : any;
868
+ /**
869
+ * Maps a SQL-flavoured `type` string (e.g. `'varchar(255)'`, `'int'`, `'timestamp'`) to a TS
870
+ * runtime type, used as a fallback when {@link RoutineParamConfig} does not declare an explicit
871
+ * `runtimeType`. Length/precision arguments are stripped, the lowercase token is matched
872
+ * against {@link SqlTypeMap}. `decimal`/`numeric`/`money`/`bigint` default to `string` since
873
+ * drivers typically return them as strings to preserve precision; opt in to `number` or
874
+ * `bigint` via `runtimeType` when the value range is safe. Unrecognised or genuinely
875
+ * ambiguous types (`refcursor`, `sys_refcursor`, …) fall through to `any`.
876
+ */
877
+ export type SqlTypeToTs<S> = S extends string ? Lowercase<S> extends `tinyint(1)${string}` ? boolean : LookupSqlType<StripSqlTypeArgs<Lowercase<S>>> : any;
878
+ /** Strips `null | undefined` from a `Type<JSType, _>` JSType, so e.g. `StringType extends Type<string | null | undefined>` resolves to `string`. */
879
+ type TypeJsType<T> = T extends Type<infer J, any> ? Exclude<J, null | undefined> : T extends new (...args: any[]) => Type<infer J, any> ? Exclude<J, null | undefined> : never;
880
+ /**
881
+ * TS value type for a single routine parameter. Resolution order:
882
+ *
883
+ * 1. explicit `runtimeType`
884
+ * 2. `type` set to a {@link Type} class or instance — JSType is extracted from the Type generic
885
+ * 3. `type` set to a SQL string — mapped via {@link SqlTypeToTs}
886
+ * 4. fallback `any`
887
+ *
888
+ * `ref: true` wraps the result in `ScalarReference`; `nullable: true` adds `| null`.
889
+ */
890
+ export type RoutineParamValue<P> = P extends {
891
+ runtimeType: infer R;
892
+ } ? P extends {
893
+ ref: true;
894
+ } ? ScalarReference<Nullify<P, RoutineRuntimeOf<R>>> : Nullify<P, RoutineRuntimeOf<R>> : P extends {
895
+ type: infer T;
896
+ } ? [TypeJsType<T>] extends [never] ? T extends string ? P extends {
897
+ ref: true;
898
+ } ? ScalarReference<Nullify<P, SqlTypeToTs<T>>> : Nullify<P, SqlTypeToTs<T>> : P extends {
899
+ ref: true;
900
+ } ? ScalarReference<any> : any : P extends {
901
+ ref: true;
902
+ } ? ScalarReference<Nullify<P, TypeJsType<T>>> : Nullify<P, TypeJsType<T>> : P extends {
903
+ ref: true;
904
+ } ? ScalarReference<any> : any;
905
+ /** Default `TArgs` for {@link Routine}; consumers use {@link RoutineArgs}, which honours overrides from {@link Routine.create}. */
906
+ export type RoutineArgsOf<Config> = Config extends {
907
+ params: infer P;
908
+ } ? P extends Record<string, RoutineParamConfig> ? {
909
+ [K in keyof P]: RoutineParamValue<P[K]>;
910
+ } : Record<string, unknown> : Record<string, unknown>;
911
+ /** Default `TReturn` for {@link Routine}; consumers use {@link RoutineReturn}, which honours overrides from {@link Routine.create}. */
912
+ export type RoutineReturnOf<Config> = Config extends {
913
+ returns: infer R;
914
+ } ? R extends {
915
+ runtimeType: infer RT;
916
+ } ? Nullify<R, RoutineRuntimeOf<RT>> : R extends {
917
+ type: infer T;
918
+ } ? [TypeJsType<T>] extends [never] ? unknown : Nullify<R, TypeJsType<T>> : R extends readonly (() => EntityName<any>)[] ? {
919
+ [K in keyof R]: R[K] extends () => EntityName<infer E> ? E[] : never;
920
+ } : R extends () => EntityName<infer E> ? E[] : R extends {
921
+ hydrate: (...args: any[]) => infer H;
922
+ } ? Awaited<H> : void : void;
923
+ export type RoutineArgs<R> = R extends Routine<any, infer A, any> ? A : Record<string, unknown>;
924
+ export type RoutineReturn<R> = R extends Routine<any, any, infer Re> ? Re : unknown;
620
925
  /** Branded string that accepts any string value while preserving autocompletion for known literals. */
621
926
  export type AnyString = string & {};
622
927
  /** Describes a single property (column, relation, or embedded) within an entity's metadata. */
@@ -714,11 +1019,12 @@ export interface EntityProperty<Owner = any, Target = any> {
714
1019
  serializer?: (value: any, options?: SerializeOptions<any>) => any;
715
1020
  serializedName?: string;
716
1021
  comment?: string;
1022
+ collation?: string;
717
1023
  /** mysql only */
718
1024
  extra?: string;
719
1025
  userDefined?: boolean;
720
1026
  optional?: boolean;
721
- ignoreSchemaChanges?: ('type' | 'extra' | 'default')[];
1027
+ ignoreSchemaChanges?: ('type' | 'extra' | 'default' | 'collation')[];
722
1028
  deferMode?: DeferMode;
723
1029
  createForeignKeyConstraint: boolean;
724
1030
  foreignKeyName?: string;
@@ -782,6 +1088,8 @@ export interface EntityMetadata<Entity = any, Class extends EntityCtor<Entity> =
782
1088
  materialized?: boolean;
783
1089
  /** For materialized views, whether data is populated on creation. Defaults to true. */
784
1090
  withData?: boolean;
1091
+ /** PostgreSQL partitioning definition for this table. */
1092
+ partitionBy?: EntityPartitionBy<Entity>;
785
1093
  expression?: string | ((em: any, where: ObjectQuery<Entity>, options: FindOptions<Entity, any, any, any>, stream?: boolean) => MaybePromise<Raw | object | string>);
786
1094
  discriminatorColumn?: EntityKey<Entity> | AnyString;
787
1095
  discriminatorValue?: number | string;
@@ -820,6 +1128,7 @@ export interface EntityMetadata<Entity = any, Class extends EntityCtor<Entity> =
820
1128
  type?: string;
821
1129
  options?: Dictionary;
822
1130
  expression?: string | IndexCallback<Entity>;
1131
+ where?: string | FilterQuery<Entity>;
823
1132
  columns?: IndexColumnOptions[];
824
1133
  include?: EntityKey<Entity> | EntityKey<Entity>[];
825
1134
  fillFactor?: number;
@@ -832,6 +1141,7 @@ export interface EntityMetadata<Entity = any, Class extends EntityCtor<Entity> =
832
1141
  name?: string;
833
1142
  options?: Dictionary;
834
1143
  expression?: string | IndexCallback<Entity>;
1144
+ where?: string | FilterQuery<Entity>;
835
1145
  deferMode?: DeferMode | `${DeferMode}`;
836
1146
  columns?: IndexColumnOptions[];
837
1147
  include?: EntityKey<Entity> | EntityKey<Entity>[];
@@ -839,6 +1149,7 @@ export interface EntityMetadata<Entity = any, Class extends EntityCtor<Entity> =
839
1149
  disabled?: boolean;
840
1150
  }[];
841
1151
  checks: CheckConstraint<Entity>[];
1152
+ triggers: TriggerDef<Entity>[];
842
1153
  repositoryClass?: string;
843
1154
  repository: () => EntityClass<EntityRepository<any>>;
844
1155
  hooks: {
@@ -859,6 +1170,8 @@ export interface EntityMetadata<Entity = any, Class extends EntityCtor<Entity> =
859
1170
  polymorphicDiscriminatorMap?: Dictionary<EntityClass>;
860
1171
  /** Inheritance type: 'sti' (Single Table Inheritance) or 'tpt' (Table-Per-Type). Only set on root entities. */
861
1172
  inheritanceType?: 'sti' | 'tpt';
1173
+ /** Legacy alias populated from `EntityOptions.inheritance`; mirrored to `inheritanceType` during discovery. */
1174
+ inheritance?: 'tpt';
862
1175
  /** For TPT: direct parent entity metadata (the entity this one extends). */
863
1176
  tptParent?: EntityMetadata;
864
1177
  /** For TPT: direct child entities (entities that extend this one). */
@@ -886,6 +1199,11 @@ export interface EntityMetadata<Entity = any, Class extends EntityCtor<Entity> =
886
1199
  export interface CreateSchemaOptions {
887
1200
  wrap?: boolean;
888
1201
  schema?: string;
1202
+ /**
1203
+ * When true, entities with a wildcard schema (`schema: '*'`) are included in the generated DDL.
1204
+ * Without this, wildcard tables are skipped.
1205
+ */
1206
+ includeWildcardSchema?: boolean;
889
1207
  }
890
1208
  /** Options for `ISchemaGenerator.clear()` to truncate/clear database tables. */
891
1209
  export interface ClearDatabaseOptions {
@@ -915,6 +1233,13 @@ export interface UpdateSchemaOptions<DatabaseSchema = unknown> {
915
1233
  dropTables?: boolean;
916
1234
  schema?: string;
917
1235
  fromSchema?: DatabaseSchema;
1236
+ /**
1237
+ * When true, entities with a wildcard schema (`schema: '*'`) are included in the diff so migrations
1238
+ * can be generated for them. The emitted SQL is unqualified — and therefore safe to apply against
1239
+ * any schema at runtime — only when neither `options.schema` nor `config.schema` is set; otherwise
1240
+ * wildcard tables inherit that schema qualifier.
1241
+ */
1242
+ includeWildcardSchema?: boolean;
918
1243
  }
919
1244
  /** Options for `ISchemaGenerator.refresh()` which drops and recreates the schema. */
920
1245
  export interface RefreshDatabaseOptions extends CreateSchemaOptions {
@@ -995,6 +1320,12 @@ export type MigrateOptions = {
995
1320
  to?: string | number;
996
1321
  migrations?: string[];
997
1322
  transaction?: Transaction;
1323
+ /**
1324
+ * Target schema to run migrations against. Issues a driver-specific "set current schema"
1325
+ * statement (e.g. `SET search_path` on PostgreSQL) before each migration, and places the
1326
+ * tracking table in this schema. Overrides `migrations.schema` from config. Not supported on MSSQL.
1327
+ */
1328
+ schema?: string;
998
1329
  };
999
1330
  /** Result of creating a new migration file, including the generated code and schema diff. */
1000
1331
  export type MigrationResult = {
@@ -1015,6 +1346,8 @@ export interface IMigrationRunner {
1015
1346
  run(migration: Migration, method: 'up' | 'down', afterRun?: (tx?: Transaction) => Promise<void>): Promise<void>;
1016
1347
  setMasterMigration(trx: Transaction): void;
1017
1348
  unsetMasterMigration(): void;
1349
+ setRunSchema?(schema?: string): void;
1350
+ unsetRunSchema?(): void;
1018
1351
  }
1019
1352
  /**
1020
1353
  * @internal
@@ -1027,6 +1360,8 @@ export interface IMigratorStorage {
1027
1360
  ensureTable?(): Promise<void>;
1028
1361
  setMasterMigration(trx: Transaction): void;
1029
1362
  unsetMasterMigration(): void;
1363
+ setRunSchema?(schema?: string): void;
1364
+ unsetRunSchema?(): void;
1030
1365
  getMigrationName(name: string): string;
1031
1366
  getTableName?(): {
1032
1367
  schemaName?: string;
@@ -1053,11 +1388,15 @@ export interface IMigrator {
1053
1388
  /**
1054
1389
  * Returns list of already executed migrations.
1055
1390
  */
1056
- getExecuted(): Promise<MigrationRow[]>;
1391
+ getExecuted(options?: {
1392
+ schema?: string;
1393
+ }): Promise<MigrationRow[]>;
1057
1394
  /**
1058
1395
  * Returns list of pending (not yet executed) migrations found in the migration directory.
1059
1396
  */
1060
- getPending(): Promise<MigrationInfo[]>;
1397
+ getPending(options?: {
1398
+ schema?: string;
1399
+ }): Promise<MigrationInfo[]>;
1061
1400
  /**
1062
1401
  * Executes specified migrations. Without parameter it will migrate up to the latest version.
1063
1402
  */
@@ -1066,6 +1405,11 @@ export interface IMigrator {
1066
1405
  * Executes down migrations to the given point. Without parameter it will migrate one version down.
1067
1406
  */
1068
1407
  down(options?: string | string[] | Omit<MigrateOptions, 'from'>): Promise<MigrationInfo[]>;
1408
+ /**
1409
+ * Combines multiple executed migrations into a single migration file.
1410
+ * Concatenates source code without touching the database schema.
1411
+ */
1412
+ rollup(migrations?: string[]): Promise<MigrationResult>;
1069
1413
  /**
1070
1414
  * Registers event handler.
1071
1415
  */
@@ -1074,6 +1418,14 @@ export interface IMigrator {
1074
1418
  * Removes event handler.
1075
1419
  */
1076
1420
  off(event: MigratorEvent, listener: (event: MigrationInfo) => MaybePromise<void>): IMigrator;
1421
+ /**
1422
+ * Marks a migration as executed without actually running it.
1423
+ */
1424
+ logMigration(name: string): Promise<void>;
1425
+ /**
1426
+ * Removes a migration from the executed list without reverting it.
1427
+ */
1428
+ unlogMigration(name: string): Promise<void>;
1077
1429
  /**
1078
1430
  * @internal
1079
1431
  */
@@ -1140,13 +1492,32 @@ export type PopulateOptions<T> = {
1140
1492
  children?: PopulateOptions<T[keyof T]>[];
1141
1493
  /** When true, ignores `mapToPk` on the property and returns full entity data instead of just PKs. */
1142
1494
  dataOnly?: boolean;
1495
+ /** Limit the number of items loaded per parent entity. Collections will be marked as partial and readonly. */
1496
+ limit?: number;
1497
+ /** Offset for per-parent limiting (used with `limit`). */
1498
+ offset?: number;
1499
+ /** Order by clause for per-parent limiting. Takes precedence over nested `FindOptions.orderBy`. */
1500
+ orderBy?: QueryOrderMap<T[keyof T]>;
1143
1501
  };
1144
1502
  /** Inline options that can be appended to populate hint strings (e.g., strategy, join type). */
1145
1503
  export type PopulateHintOptions = {
1146
1504
  strategy?: LoadStrategy.JOINED | LoadStrategy.SELECT_IN | 'joined' | 'select-in';
1147
1505
  joinType?: 'inner join' | 'left join';
1506
+ /** Limit the number of items loaded per parent entity. Collections will be marked as partial and readonly. */
1507
+ limit?: number;
1508
+ /** Offset for per-parent limiting (used with `limit`). */
1509
+ offset?: number;
1510
+ /** Order by clause for per-parent limiting. Takes precedence over nested `FindOptions.orderBy`. */
1511
+ orderBy?: QueryOrderMap<any>;
1148
1512
  };
1149
1513
  type ExtractType<T> = T extends CollectionShape<infer U> ? U : T extends ReferenceShape<infer U> ? U : T extends Ref<infer U> ? U : T extends readonly (infer U)[] ? U : T;
1514
+ /**
1515
+ * Like {@link ExtractType} but also unwraps {@link LazyRef}. Kept separate so {@link ExtractType}'s
1516
+ * hot path (used by `IsOptional`, `EntityData`, `RequiredEntityData`) doesn't pay the cost of the
1517
+ * extra branch — those contexts handle `LazyRef` in their own earlier branches (see
1518
+ * `EntityDataProp` / `RequiredEntityDataProp`) before delegating to `ExtractType`.
1519
+ */
1520
+ type ExtractTypeWithLazyRef<T> = T extends LazyRef.Brand<infer U> ? U : ExtractType<T>;
1150
1521
  type ExtractStringKeys<T> = {
1151
1522
  [K in keyof T]-?: CleanKeys<T, K>;
1152
1523
  }[keyof T] & {};
@@ -1154,8 +1525,8 @@ type ExtractStringKeys<T> = {
1154
1525
  * Extracts string keys from an entity type, handling Collection/Reference wrappers.
1155
1526
  * Simplified to just check `T extends object` since ExtractType handles the unwrapping.
1156
1527
  */
1157
- type StringKeys<T, E extends string = never> = T extends object ? ExtractStringKeys<ExtractType<T>> | E : never;
1158
- type GetStringKey<T, K extends StringKeys<T, string>, E extends string> = K extends keyof T ? ExtractType<T[K]> : K extends E ? keyof T : never;
1528
+ type StringKeys<T, E extends string = never> = T extends object ? ExtractStringKeys<ExtractTypeWithLazyRef<T>> | E : never;
1529
+ type GetStringKey<T, K extends StringKeys<T, string>, E extends string> = K extends keyof T ? ExtractTypeWithLazyRef<T[K]> : K extends E ? keyof T : never;
1159
1530
  type Prev = [never, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
1160
1531
  type RelationKeys<T> = T extends object ? {
1161
1532
  [K in keyof T]-?: CleanKeys<T, K, true>;
@@ -1170,8 +1541,8 @@ export type UnboxArray<T> = T extends any[] ? ArrayElement<T> : T;
1170
1541
  /** Extracts the element type from an array type. */
1171
1542
  export type ArrayElement<ArrayType extends unknown[]> = ArrayType extends (infer ElementType)[] ? ElementType : never;
1172
1543
  /** Unwraps a property type from its wrapper (Reference, Collection, or array) to the inner entity type. */
1173
- export type ExpandProperty<T> = T extends ReferenceShape<infer U> ? NonNullable<U> : T extends CollectionShape<infer U> ? NonNullable<U> : T extends (infer U)[] ? NonNullable<U> : NonNullable<T>;
1174
- type LoadedLoadable<T, E extends object> = T extends CollectionShape ? LoadedCollection<E> : T extends ScalarReference<infer U> ? LoadedScalarReference<U> : T extends ReferenceShape ? T & LoadedReference<E> : T extends Scalar ? T : T extends (infer U)[] ? U extends Scalar ? T : E[] : E;
1544
+ export type ExpandProperty<T> = T extends LazyRef.Brand<infer U> ? NonNullable<U> : T extends ReferenceShape<infer U> ? NonNullable<U> : T extends CollectionShape<infer U> ? NonNullable<U> : T extends (infer U)[] ? NonNullable<U> : NonNullable<T>;
1545
+ type LoadedLoadable<T, E extends object> = T extends CollectionShape ? LoadedCollection<E> : T extends ScalarReference<infer U> ? LoadedScalarReference<U> : T extends LazyRef.Brand<any> ? E : T extends ReferenceShape ? T & LoadedReference<E> : T extends Scalar ? T : T extends (infer U)[] ? U extends Scalar ? T : E[] : E;
1175
1546
  type IsTrue<T> = IsNever<T> extends true ? false : T extends boolean ? (T extends true ? true : false) : false;
1176
1547
  type StringLiteral<T> = T extends string ? (string extends T ? never : T) : never;
1177
1548
  type Prefix<T, K> = K extends `${infer S}.${string}` ? S : K extends '*' ? keyof T : K;
@@ -1205,7 +1576,7 @@ export type MergeSelected<T, U, F extends string> = IsLoadedType<T> extends true
1205
1576
  export type MergeLoaded<T, U, P extends string, F extends string, E extends string, R extends boolean = false> = IsLoadedType<T> extends true ? T & Loaded<U, P, F, E> : Loaded<T, P, F, E>;
1206
1577
  /** Extracts the nullability modifiers (`null`, `undefined`, or both) from a type `T`. */
1207
1578
  export type AddOptional<T> = undefined | null extends T ? null | undefined : null extends T ? null : undefined extends T ? undefined : never;
1208
- type LoadedProp<T, L extends string = never, F extends string = '*', E extends string = never> = LoadedLoadable<T, Loaded<ExtractType<T>, L, F, E>>;
1579
+ type LoadedProp<T, L extends string = never, F extends string = '*', E extends string = never> = LoadedLoadable<T, Loaded<ExtractTypeWithLazyRef<T>, L, F, E>>;
1209
1580
  /** Extracts the eager-loaded property names declared via `[EagerProps]` as a string union. */
1210
1581
  export type AddEager<T> = ExtractEagerProps<T> & string;
1211
1582
  /** Combines an explicit populate hint `L` with the entity's eagerly loaded properties. */