@mikro-orm/core 7.1.0-dev.3 → 7.1.0-dev.31

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 (55) hide show
  1. package/EntityManager.d.ts +44 -11
  2. package/EntityManager.js +139 -31
  3. package/README.md +2 -1
  4. package/drivers/IDatabaseDriver.d.ts +39 -1
  5. package/entity/BaseEntity.d.ts +68 -1
  6. package/entity/BaseEntity.js +18 -0
  7. package/entity/Collection.d.ts +6 -3
  8. package/entity/Collection.js +15 -4
  9. package/entity/EntityFactory.js +20 -1
  10. package/entity/EntityLoader.d.ts +3 -1
  11. package/entity/EntityLoader.js +39 -16
  12. package/entity/EntityRepository.d.ts +27 -9
  13. package/entity/EntityRepository.js +12 -0
  14. package/entity/Reference.d.ts +42 -1
  15. package/entity/Reference.js +9 -0
  16. package/entity/defineEntity.d.ts +105 -23
  17. package/entity/defineEntity.js +17 -6
  18. package/entity/utils.js +4 -5
  19. package/errors.d.ts +2 -0
  20. package/errors.js +4 -0
  21. package/index.d.ts +2 -2
  22. package/index.js +1 -1
  23. package/metadata/EntitySchema.js +3 -0
  24. package/metadata/MetadataDiscovery.d.ts +12 -0
  25. package/metadata/MetadataDiscovery.js +185 -16
  26. package/metadata/MetadataValidator.d.ts +24 -0
  27. package/metadata/MetadataValidator.js +202 -1
  28. package/metadata/types.d.ts +77 -4
  29. package/naming-strategy/AbstractNamingStrategy.d.ts +1 -1
  30. package/naming-strategy/NamingStrategy.d.ts +1 -1
  31. package/package.json +1 -1
  32. package/platforms/Platform.d.ts +8 -1
  33. package/platforms/Platform.js +40 -4
  34. package/serialization/EntitySerializer.js +2 -1
  35. package/typings.d.ts +176 -18
  36. package/typings.js +22 -5
  37. package/unit-of-work/UnitOfWork.js +3 -0
  38. package/utils/AbstractMigrator.d.ts +20 -5
  39. package/utils/AbstractMigrator.js +263 -28
  40. package/utils/AbstractSchemaGenerator.d.ts +1 -1
  41. package/utils/AbstractSchemaGenerator.js +4 -1
  42. package/utils/Configuration.d.ts +25 -0
  43. package/utils/Configuration.js +1 -0
  44. package/utils/DataloaderUtils.d.ts +10 -1
  45. package/utils/DataloaderUtils.js +78 -0
  46. package/utils/EntityComparator.js +1 -1
  47. package/utils/QueryHelper.d.ts +16 -0
  48. package/utils/QueryHelper.js +15 -0
  49. package/utils/Utils.js +1 -1
  50. package/utils/fs-utils.d.ts +2 -0
  51. package/utils/fs-utils.js +7 -1
  52. package/utils/index.d.ts +1 -0
  53. package/utils/index.js +1 -0
  54. package/utils/partition-utils.d.ts +17 -0
  55. package/utils/partition-utils.js +79 -0
package/typings.d.ts CHANGED
@@ -11,7 +11,7 @@ import type { SerializationContext } from './serialization/SerializationContext.
11
11
  import type { SerializeOptions } from './serialization/EntitySerializer.js';
12
12
  import type { MetadataStorage } from './metadata/MetadataStorage.js';
13
13
  import type { EntitySchema } from './metadata/EntitySchema.js';
14
- import type { IndexColumnOptions } from './metadata/types.js';
14
+ import type { EntityPartitionBy, IndexColumnOptions } from './metadata/types.js';
15
15
  import type { Type, types } from './types/index.js';
16
16
  import type { Platform } from './platforms/Platform.js';
17
17
  import type { Configuration } from './utils/Configuration.js';
@@ -47,7 +47,7 @@ export type AsyncFunction<R = any, T = Dictionary> = (args: T) => Promise<T>;
47
47
  export type Compute<T> = {
48
48
  [K in keyof T]: T[K];
49
49
  } & {};
50
- type InternalKeys = 'EntityRepositoryType' | 'PrimaryKeyProp' | 'OptionalProps' | 'EagerProps' | 'HiddenProps' | '__selectedType' | '__loadedType';
50
+ type InternalKeys = 'EntityRepositoryType' | 'PrimaryKeyProp' | 'OptionalProps' | 'EagerProps' | 'HiddenProps' | 'IndexHints' | '__selectedType' | '__loadedType';
51
51
  /** Filters out function, symbol, and internal keys from an entity type. When `B = true`, also excludes scalar keys. */
52
52
  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
53
  /** Extracts keys of `T` whose values are functions. */
@@ -113,7 +113,7 @@ type LoadedReferenceShape<T = any> = ReferenceShape & {
113
113
  * Using this instead of `Loadable<any>` in conditional type checks prevents
114
114
  * TypeScript from evaluating the full Collection/Reference interfaces.
115
115
  */
116
- type LoadableShape = CollectionShape | ReferenceShape | readonly any[];
116
+ type LoadableShape = CollectionShape | ReferenceShape | LazyRef.Brand<any> | readonly any[];
117
117
  /** Gets all keys from all members of a union type (distributes over the union). */
118
118
  export type UnionKeys<T> = T extends any ? keyof T : never;
119
119
  /** Gets the type of a property from all union members that have it (distributes over the union). */
@@ -150,6 +150,44 @@ export declare const EntityName: unique symbol;
150
150
  export type InferEntityName<T> = T extends {
151
151
  [EntityName]?: infer Name;
152
152
  } ? (Name extends string ? Name : never) : never;
153
+ /**
154
+ * Symbol used to declare index-to-column mappings on an entity type.
155
+ * For decorator entities, declare as a phantom property:
156
+ * ```typescript
157
+ * [IndexHints]?: { idx_email: 'email'; idx_name_age: 'name' | 'age' };
158
+ * ```
159
+ * For `defineEntity` entities, index hints are inferred automatically from
160
+ * named indexes (property-level `.index('name')` and entity-level `indexes`/`uniques`).
161
+ */
162
+ export declare const IndexHints: unique symbol;
163
+ /**
164
+ * Extracts the index hints map from an entity type. Returns `never` when no hints are declared.
165
+ * For decorator entities, `[IndexHints]` contains a pre-computed `{ idxName: 'prop' }` map.
166
+ * For `defineEntity` entities, `[IndexHints]` contains `[Properties]` (a tuple wrapping the
167
+ * raw property builders), which is lazily converted to the index map when first accessed.
168
+ */
169
+ export type ExtractIndexHints<T> = T extends {
170
+ [IndexHints]?: infer H;
171
+ } ? H extends [infer P extends Record<string, any>] ? InferPropertyIndexMap<P> : H : never;
172
+ /**
173
+ * Extracts `{ indexName: propertyKey }` from property builder options.
174
+ * Checks `.index('name')` and `.unique('name')` on each property in a single pass.
175
+ */
176
+ export type InferPropertyIndexMap<Properties extends Record<string, any>> = {
177
+ [K in keyof Properties as MaybeReturnType<Properties[K]> extends {
178
+ '~options': {
179
+ index: infer N extends string;
180
+ };
181
+ } ? N : MaybeReturnType<Properties[K]> extends {
182
+ '~options': {
183
+ unique: infer N extends string;
184
+ };
185
+ } ? N : never]: K & string;
186
+ };
187
+ /** Union of declared index names on an entity. Falls back to `string` when no `[IndexHints]` are declared. */
188
+ export type IndexName<T> = [ExtractIndexHints<T>] extends [never] ? string : (keyof ExtractIndexHints<T> & string) | (string & {});
189
+ /** Properties covered by the named index on entity T. Falls back to all entity keys when the index is unknown. */
190
+ export type IndexColumns<T, Name extends string> = ExtractIndexHints<T> extends Record<Name, infer Cols> ? Cols & string : EntityKey<T>;
153
191
  /**
154
192
  * Branded type that marks a property as optional in `em.create()`.
155
193
  * Use as a property type wrapper: `createdAt: Opt<Date>` instead of listing in `[OptionalProps]`.
@@ -328,6 +366,18 @@ export type ObjectQuery<T> = OperatorMap<T> & FilterObject<T>;
328
366
  * Accepts an object query, a primary key value, entity props with operators, or an array of filters.
329
367
  */
330
368
  export type FilterQuery<T> = ObjectQuery<T> | NonNullable<ExpandScalar<Primary<T>>> | NonNullable<EntityProps<T> & OperatorMap<T>> | FilterQuery<T>[];
369
+ /**
370
+ * `FilterQuery` restricted to only properties covered by the specified index(es).
371
+ * Used when `using` option is set in `FindOptions` to enforce type-safe index usage.
372
+ */
373
+ export type IndexFilterQuery<T, Using extends string> = [Using] extends [never] ? FilterQuery<T> : (OperatorMap<T> & {
374
+ -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;
375
+ }) | NonNullable<ExpandScalar<Primary<T>>> | IndexFilterQuery<T, Using>[];
376
+ /** Replaces `where` and `using` on an options type with index-aware variants when `Using` is specified. */
377
+ export type WithUsingOptions<Opts, Entity, Using extends string> = Omit<Opts, 'where' | 'using'> & {
378
+ using?: Using | Using[];
379
+ where?: [Using] extends [never] ? FilterQuery<Entity> : IndexFilterQuery<Entity, Using>;
380
+ };
331
381
  /** Public interface for the entity wrapper, accessible via `wrap(entity)`. Provides helper methods for entity state management. */
332
382
  export interface IWrappedEntity<Entity extends object> {
333
383
  isInitialized(): boolean;
@@ -417,12 +467,12 @@ type NonArrayObject = object & {
417
467
  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
468
  __runtime?: infer Runtime;
419
469
  __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>;
470
+ } ? 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
471
  /** Like `EntityDataProp` but used in `RequiredEntityData` context with required/optional key distinction. */
422
472
  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
473
  __runtime?: infer Runtime;
424
474
  __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>;
475
+ } ? 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
476
  /** Nested entity data shape for embedded or related entities within `EntityData`. */
427
477
  export type EntityDataNested<T, C extends boolean = false> = T extends undefined ? never : T extends any[] ? Readonly<T> : EntityData<T, C> | ExpandEntityProp<T, C>;
428
478
  type UnwrapScalarRef<T> = T extends ScalarReference<infer U> ? U : T;
@@ -471,6 +521,35 @@ type Relation<T> = {
471
521
  export type Rel<T> = T;
472
522
  /** Alias for `ScalarReference` (see {@apilink Ref}). */
473
523
  export type ScalarRef<T> = ScalarReference<T>;
524
+ /**
525
+ * Type-level marker for a to-one relation that is **direct at runtime** (no `Reference` wrapper) but
526
+ * **restricted at compile time** until narrowed via `Loaded<>`.
527
+ *
528
+ * Use as the property type on a `@ManyToOne`/`@OneToOne` relation that does **not** have `ref: true`:
529
+ *
530
+ * ```ts
531
+ * @ManyToOne(() => User)
532
+ * author!: LazyRef<User>;
533
+ * ```
534
+ *
535
+ * Semantics:
536
+ * - **Runtime**: identical to a plain direct relation — `article.author` is a `User` instance (stub or hydrated),
537
+ * `article.author instanceof User` is `true`, no `Reference` object is created.
538
+ * - **Type (unloaded view)**: only the primary key is accessible. Accessing other properties is a compile error.
539
+ * - **Type (loaded view)**: once the relation is in the populate hint of a `Loaded<Entity, 'author'>`, it narrows
540
+ * back to the full entity — no `.$` or `.get()` indirection needed.
541
+ *
542
+ * Note: the safety is purely compile-time. JS code or `as any` casts bypass it.
543
+ */
544
+ export type LazyRef<T extends object> = IsAny<T> extends true ? LazyRef.Brand<T> : {
545
+ [K in PrimaryProperty<T> & keyof T]: T[K];
546
+ } & LazyRef.Brand<T>;
547
+ export declare namespace LazyRef {
548
+ const __lazyRef: unique symbol;
549
+ interface Brand<T> {
550
+ [__lazyRef]?: (arg: T) => T;
551
+ }
552
+ }
474
553
  /** Alias for `Reference<T> & { id: number }` (see {@apilink Ref}). */
475
554
  export type EntityRef<T extends object> = true extends IsUnknown<PrimaryProperty<T>> ? Reference<T> : IsAny<T> extends true ? Reference<T> : {
476
555
  [K in PrimaryProperty<T> & keyof T]: T[K];
@@ -606,6 +685,8 @@ export type IndexCallback<T> = (columns: Record<PropertyName<T>, string>, table:
606
685
  export type FormulaCallback<T> = (columns: FormulaColumns<T>, table: FormulaTable) => string | Raw;
607
686
  /** Callback for CHECK constraint expressions. Receives column mappings and table info. */
608
687
  export type CheckCallback<T> = (columns: Record<PropertyName<T>, string>, table: SchemaTable) => string | Raw;
688
+ /** Callback for trigger body expressions. Receives column mappings and table info. */
689
+ export type TriggerCallback<T> = (columns: Record<PropertyName<T>, string>, table: SchemaTable) => string | Raw;
609
690
  /** Callback for generated (computed) column expressions. Receives column mappings and table info. */
610
691
  export type GeneratedColumnCallback<T> = (columns: Record<PropertyName<T>, string>, table: SchemaTable) => string | Raw;
611
692
  /** Definition of a CHECK constraint on a table or property. */
@@ -614,6 +695,23 @@ export interface CheckConstraint<T = any> {
614
695
  property?: string;
615
696
  expression: string | Raw | CheckCallback<T>;
616
697
  }
698
+ /** Definition of a database trigger on a table. */
699
+ export interface TriggerDef<T = any> {
700
+ /** Trigger name. Auto-generated if omitted. */
701
+ name?: string;
702
+ /** When the trigger fires relative to the event. */
703
+ timing: 'before' | 'after' | 'instead of';
704
+ /** Which DML events activate the trigger. */
705
+ events: ('insert' | 'update' | 'delete' | 'truncate')[];
706
+ /** Whether the trigger fires once per row or per statement. Defaults to `'row'`. */
707
+ forEach?: 'row' | 'statement';
708
+ /** SQL body of the trigger. Can be a string, Raw query, or callback receiving column name mappings. */
709
+ body?: string | Raw | TriggerCallback<T>;
710
+ /** Optional SQL WHEN condition for the trigger. */
711
+ when?: string;
712
+ /** Raw DDL escape hatch — full CREATE TRIGGER statement. Mutually exclusive with `body`. */
713
+ expression?: string;
714
+ }
617
715
  /** Branded string that accepts any string value while preserving autocompletion for known literals. */
618
716
  export type AnyString = string & {};
619
717
  /** Describes a single property (column, relation, or embedded) within an entity's metadata. */
@@ -711,11 +809,12 @@ export interface EntityProperty<Owner = any, Target = any> {
711
809
  serializer?: (value: any, options?: SerializeOptions<any>) => any;
712
810
  serializedName?: string;
713
811
  comment?: string;
812
+ collation?: string;
714
813
  /** mysql only */
715
814
  extra?: string;
716
815
  userDefined?: boolean;
717
816
  optional?: boolean;
718
- ignoreSchemaChanges?: ('type' | 'extra' | 'default')[];
817
+ ignoreSchemaChanges?: ('type' | 'extra' | 'default' | 'collation')[];
719
818
  deferMode?: DeferMode;
720
819
  createForeignKeyConstraint: boolean;
721
820
  foreignKeyName?: string;
@@ -763,7 +862,6 @@ export type EntityCtor<T = any> = abstract new (...args: any[]) => T;
763
862
  export interface EntityMetadata<Entity = any, Class extends EntityCtor<Entity> = EntityCtor<Entity>> {
764
863
  name?: string;
765
864
  className: string;
766
- tableName: string;
767
865
  schema?: string;
768
866
  pivotTable?: boolean;
769
867
  virtual?: boolean;
@@ -776,6 +874,8 @@ export interface EntityMetadata<Entity = any, Class extends EntityCtor<Entity> =
776
874
  materialized?: boolean;
777
875
  /** For materialized views, whether data is populated on creation. Defaults to true. */
778
876
  withData?: boolean;
877
+ /** PostgreSQL partitioning definition for this table. */
878
+ partitionBy?: EntityPartitionBy<Entity>;
779
879
  expression?: string | ((em: any, where: ObjectQuery<Entity>, options: FindOptions<Entity, any, any, any>, stream?: boolean) => MaybePromise<Raw | object | string>);
780
880
  discriminatorColumn?: EntityKey<Entity> | AnyString;
781
881
  discriminatorValue?: number | string;
@@ -814,6 +914,7 @@ export interface EntityMetadata<Entity = any, Class extends EntityCtor<Entity> =
814
914
  type?: string;
815
915
  options?: Dictionary;
816
916
  expression?: string | IndexCallback<Entity>;
917
+ where?: string | FilterQuery<Entity>;
817
918
  columns?: IndexColumnOptions[];
818
919
  include?: EntityKey<Entity> | EntityKey<Entity>[];
819
920
  fillFactor?: number;
@@ -826,6 +927,7 @@ export interface EntityMetadata<Entity = any, Class extends EntityCtor<Entity> =
826
927
  name?: string;
827
928
  options?: Dictionary;
828
929
  expression?: string | IndexCallback<Entity>;
930
+ where?: string | FilterQuery<Entity>;
829
931
  deferMode?: DeferMode | `${DeferMode}`;
830
932
  columns?: IndexColumnOptions[];
831
933
  include?: EntityKey<Entity> | EntityKey<Entity>[];
@@ -833,6 +935,7 @@ export interface EntityMetadata<Entity = any, Class extends EntityCtor<Entity> =
833
935
  disabled?: boolean;
834
936
  }[];
835
937
  checks: CheckConstraint<Entity>[];
938
+ triggers: TriggerDef<Entity>[];
836
939
  repositoryClass?: string;
837
940
  repository: () => EntityClass<EntityRepository<any>>;
838
941
  hooks: {
@@ -853,6 +956,8 @@ export interface EntityMetadata<Entity = any, Class extends EntityCtor<Entity> =
853
956
  polymorphicDiscriminatorMap?: Dictionary<EntityClass>;
854
957
  /** Inheritance type: 'sti' (Single Table Inheritance) or 'tpt' (Table-Per-Type). Only set on root entities. */
855
958
  inheritanceType?: 'sti' | 'tpt';
959
+ /** Legacy alias populated from `EntityOptions.inheritance`; mirrored to `inheritanceType` during discovery. */
960
+ inheritance?: 'tpt';
856
961
  /** For TPT: direct parent entity metadata (the entity this one extends). */
857
962
  tptParent?: EntityMetadata;
858
963
  /** For TPT: direct child entities (entities that extend this one). */
@@ -880,6 +985,11 @@ export interface EntityMetadata<Entity = any, Class extends EntityCtor<Entity> =
880
985
  export interface CreateSchemaOptions {
881
986
  wrap?: boolean;
882
987
  schema?: string;
988
+ /**
989
+ * When true, entities with a wildcard schema (`schema: '*'`) are included in the generated DDL.
990
+ * Without this, wildcard tables are skipped.
991
+ */
992
+ includeWildcardSchema?: boolean;
883
993
  }
884
994
  /** Options for `ISchemaGenerator.clear()` to truncate/clear database tables. */
885
995
  export interface ClearDatabaseOptions {
@@ -909,6 +1019,13 @@ export interface UpdateSchemaOptions<DatabaseSchema = unknown> {
909
1019
  dropTables?: boolean;
910
1020
  schema?: string;
911
1021
  fromSchema?: DatabaseSchema;
1022
+ /**
1023
+ * When true, entities with a wildcard schema (`schema: '*'`) are included in the diff so migrations
1024
+ * can be generated for them. The emitted SQL is unqualified — and therefore safe to apply against
1025
+ * any schema at runtime — only when neither `options.schema` nor `config.schema` is set; otherwise
1026
+ * wildcard tables inherit that schema qualifier.
1027
+ */
1028
+ includeWildcardSchema?: boolean;
912
1029
  }
913
1030
  /** Options for `ISchemaGenerator.refresh()` which drops and recreates the schema. */
914
1031
  export interface RefreshDatabaseOptions extends CreateSchemaOptions {
@@ -989,6 +1106,12 @@ export type MigrateOptions = {
989
1106
  to?: string | number;
990
1107
  migrations?: string[];
991
1108
  transaction?: Transaction;
1109
+ /**
1110
+ * Target schema to run migrations against. Issues a driver-specific "set current schema"
1111
+ * statement (e.g. `SET search_path` on PostgreSQL) before each migration, and places the
1112
+ * tracking table in this schema. Overrides `migrations.schema` from config. Not supported on MSSQL.
1113
+ */
1114
+ schema?: string;
992
1115
  };
993
1116
  /** Result of creating a new migration file, including the generated code and schema diff. */
994
1117
  export type MigrationResult = {
@@ -1006,21 +1129,25 @@ export type MigrationRow = {
1006
1129
  * @internal
1007
1130
  */
1008
1131
  export interface IMigrationRunner {
1009
- run(migration: Migration, method: 'up' | 'down'): Promise<void>;
1132
+ run(migration: Migration, method: 'up' | 'down', afterRun?: (tx?: Transaction) => Promise<void>): Promise<void>;
1010
1133
  setMasterMigration(trx: Transaction): void;
1011
1134
  unsetMasterMigration(): void;
1135
+ setRunSchema?(schema?: string): void;
1136
+ unsetRunSchema?(): void;
1012
1137
  }
1013
1138
  /**
1014
1139
  * @internal
1015
1140
  */
1016
1141
  export interface IMigratorStorage {
1017
1142
  executed(): Promise<string[]>;
1018
- logMigration(params: Dictionary): Promise<void>;
1019
- unlogMigration(params: Dictionary): Promise<void>;
1143
+ logMigration(params: Dictionary, tx?: Transaction): Promise<void>;
1144
+ unlogMigration(params: Dictionary, tx?: Transaction): Promise<void>;
1020
1145
  getExecutedMigrations(): Promise<MigrationRow[]>;
1021
1146
  ensureTable?(): Promise<void>;
1022
1147
  setMasterMigration(trx: Transaction): void;
1023
1148
  unsetMasterMigration(): void;
1149
+ setRunSchema?(schema?: string): void;
1150
+ unsetRunSchema?(): void;
1024
1151
  getMigrationName(name: string): string;
1025
1152
  getTableName?(): {
1026
1153
  schemaName?: string;
@@ -1047,11 +1174,15 @@ export interface IMigrator {
1047
1174
  /**
1048
1175
  * Returns list of already executed migrations.
1049
1176
  */
1050
- getExecuted(): Promise<MigrationRow[]>;
1177
+ getExecuted(options?: {
1178
+ schema?: string;
1179
+ }): Promise<MigrationRow[]>;
1051
1180
  /**
1052
1181
  * Returns list of pending (not yet executed) migrations found in the migration directory.
1053
1182
  */
1054
- getPending(): Promise<MigrationInfo[]>;
1183
+ getPending(options?: {
1184
+ schema?: string;
1185
+ }): Promise<MigrationInfo[]>;
1055
1186
  /**
1056
1187
  * Executes specified migrations. Without parameter it will migrate up to the latest version.
1057
1188
  */
@@ -1060,6 +1191,11 @@ export interface IMigrator {
1060
1191
  * Executes down migrations to the given point. Without parameter it will migrate one version down.
1061
1192
  */
1062
1193
  down(options?: string | string[] | Omit<MigrateOptions, 'from'>): Promise<MigrationInfo[]>;
1194
+ /**
1195
+ * Combines multiple executed migrations into a single migration file.
1196
+ * Concatenates source code without touching the database schema.
1197
+ */
1198
+ rollup(migrations?: string[]): Promise<MigrationResult>;
1063
1199
  /**
1064
1200
  * Registers event handler.
1065
1201
  */
@@ -1142,13 +1278,32 @@ export type PopulateOptions<T> = {
1142
1278
  children?: PopulateOptions<T[keyof T]>[];
1143
1279
  /** When true, ignores `mapToPk` on the property and returns full entity data instead of just PKs. */
1144
1280
  dataOnly?: boolean;
1281
+ /** Limit the number of items loaded per parent entity. Collections will be marked as partial and readonly. */
1282
+ limit?: number;
1283
+ /** Offset for per-parent limiting (used with `limit`). */
1284
+ offset?: number;
1285
+ /** Order by clause for per-parent limiting. Takes precedence over nested `FindOptions.orderBy`. */
1286
+ orderBy?: QueryOrderMap<T[keyof T]>;
1145
1287
  };
1146
1288
  /** Inline options that can be appended to populate hint strings (e.g., strategy, join type). */
1147
1289
  export type PopulateHintOptions = {
1148
1290
  strategy?: LoadStrategy.JOINED | LoadStrategy.SELECT_IN | 'joined' | 'select-in';
1149
1291
  joinType?: 'inner join' | 'left join';
1292
+ /** Limit the number of items loaded per parent entity. Collections will be marked as partial and readonly. */
1293
+ limit?: number;
1294
+ /** Offset for per-parent limiting (used with `limit`). */
1295
+ offset?: number;
1296
+ /** Order by clause for per-parent limiting. Takes precedence over nested `FindOptions.orderBy`. */
1297
+ orderBy?: QueryOrderMap<any>;
1150
1298
  };
1151
1299
  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;
1300
+ /**
1301
+ * Like {@link ExtractType} but also unwraps {@link LazyRef}. Kept separate so {@link ExtractType}'s
1302
+ * hot path (used by `IsOptional`, `EntityData`, `RequiredEntityData`) doesn't pay the cost of the
1303
+ * extra branch — those contexts handle `LazyRef` in their own earlier branches (see
1304
+ * `EntityDataProp` / `RequiredEntityDataProp`) before delegating to `ExtractType`.
1305
+ */
1306
+ type ExtractTypeWithLazyRef<T> = T extends LazyRef.Brand<infer U> ? U : ExtractType<T>;
1152
1307
  type ExtractStringKeys<T> = {
1153
1308
  [K in keyof T]-?: CleanKeys<T, K>;
1154
1309
  }[keyof T] & {};
@@ -1156,8 +1311,8 @@ type ExtractStringKeys<T> = {
1156
1311
  * Extracts string keys from an entity type, handling Collection/Reference wrappers.
1157
1312
  * Simplified to just check `T extends object` since ExtractType handles the unwrapping.
1158
1313
  */
1159
- type StringKeys<T, E extends string = never> = T extends object ? ExtractStringKeys<ExtractType<T>> | E : never;
1160
- type GetStringKey<T, K extends StringKeys<T, string>, E extends string> = K extends keyof T ? ExtractType<T[K]> : K extends E ? keyof T : never;
1314
+ type StringKeys<T, E extends string = never> = T extends object ? ExtractStringKeys<ExtractTypeWithLazyRef<T>> | E : never;
1315
+ type GetStringKey<T, K extends StringKeys<T, string>, E extends string> = K extends keyof T ? ExtractTypeWithLazyRef<T[K]> : K extends E ? keyof T : never;
1161
1316
  type Prev = [never, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
1162
1317
  type RelationKeys<T> = T extends object ? {
1163
1318
  [K in keyof T]-?: CleanKeys<T, K, true>;
@@ -1172,8 +1327,8 @@ export type UnboxArray<T> = T extends any[] ? ArrayElement<T> : T;
1172
1327
  /** Extracts the element type from an array type. */
1173
1328
  export type ArrayElement<ArrayType extends unknown[]> = ArrayType extends (infer ElementType)[] ? ElementType : never;
1174
1329
  /** Unwraps a property type from its wrapper (Reference, Collection, or array) to the inner entity type. */
1175
- 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>;
1176
- 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;
1330
+ 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>;
1331
+ 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;
1177
1332
  type IsTrue<T> = IsNever<T> extends true ? false : T extends boolean ? (T extends true ? true : false) : false;
1178
1333
  type StringLiteral<T> = T extends string ? (string extends T ? never : T) : never;
1179
1334
  type Prefix<T, K> = K extends `${infer S}.${string}` ? S : K extends '*' ? keyof T : K;
@@ -1207,7 +1362,7 @@ export type MergeSelected<T, U, F extends string> = IsLoadedType<T> extends true
1207
1362
  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>;
1208
1363
  /** Extracts the nullability modifiers (`null`, `undefined`, or both) from a type `T`. */
1209
1364
  export type AddOptional<T> = undefined | null extends T ? null | undefined : null extends T ? null : undefined extends T ? undefined : never;
1210
- type LoadedProp<T, L extends string = never, F extends string = '*', E extends string = never> = LoadedLoadable<T, Loaded<ExtractType<T>, L, F, E>>;
1365
+ type LoadedProp<T, L extends string = never, F extends string = '*', E extends string = never> = LoadedLoadable<T, Loaded<ExtractTypeWithLazyRef<T>, L, F, E>>;
1211
1366
  /** Extracts the eager-loaded property names declared via `[EagerProps]` as a string union. */
1212
1367
  export type AddEager<T> = ExtractEagerProps<T> & string;
1213
1368
  /** Combines an explicit populate hint `L` with the entity's eagerly loaded properties. */
@@ -1322,15 +1477,18 @@ export type MaybeReturnType<T> = T extends (...args: any[]) => infer R ? R : T;
1322
1477
  * Extended `EntitySchema` interface that carries additional type-level metadata (entity name, properties, table name).
1323
1478
  * Returned by `defineEntity()` to provide strong type inference without explicit generics.
1324
1479
  */
1325
- export interface EntitySchemaWithMeta<TName extends string = string, TTableName extends string = string, TEntity = any, TBase = never, TProperties extends Record<string, any> = Record<string, any>, TClass extends EntityCtor = EntityCtor<TEntity>> extends EntitySchema<TEntity, TBase, TClass> {
1480
+ export interface EntitySchemaWithMeta<TName extends string = string, TTableName extends string = string, TEntity = any, TBase = never, TProperties extends Record<string, any> = Record<string, any>, TClass extends EntityCtor = EntityCtor<TEntity>, TDiscriminatorColumn extends string | undefined = undefined> extends EntitySchema<TEntity, TBase, TClass> {
1326
1481
  readonly name: TName;
1327
1482
  readonly properties: TProperties;
1328
1483
  readonly tableName: TTableName;
1329
1484
  /** @internal Direct entity type access - avoids expensive pattern matching */
1330
1485
  readonly '~entity': TEntity;
1486
+ /** @internal Type-level marker carrying the discriminator column name, used by `defineEntity()` to narrow inherited discriminator properties to the literal `discriminatorValue` of each child schema. */
1487
+ readonly '~discriminatorColumn'?: TDiscriminatorColumn;
1331
1488
  /** @internal */
1332
1489
  readonly class: TClass & {
1333
1490
  '~entityName'?: TName;
1491
+ '~discriminatorColumn'?: TDiscriminatorColumn;
1334
1492
  };
1335
1493
  }
1336
1494
  /**
package/typings.js CHANGED
@@ -4,7 +4,6 @@ import { EntityHelper } from './entity/EntityHelper.js';
4
4
  import { helper } from './entity/wrap.js';
5
5
  import { Utils } from './utils/Utils.js';
6
6
  import { EntityComparator } from './utils/EntityComparator.js';
7
- import { BaseEntity } from './entity/BaseEntity.js';
8
7
  /** Symbol used to declare a custom repository type on an entity class (e.g., `[EntityRepositoryType]?: BookRepository`). */
9
8
  export const EntityRepositoryType = Symbol('EntityRepositoryType');
10
9
  /** Symbol used to declare the primary key property name(s) on an entity (e.g., `[PrimaryKeyProp]?: 'id'`). */
@@ -22,6 +21,16 @@ export const Config = Symbol('Config');
22
21
  /** Symbol used to declare the entity name as a string literal type (used by `defineEntity`). */
23
22
  // eslint-disable-next-line @typescript-eslint/no-redeclare
24
23
  export const EntityName = Symbol('EntityName');
24
+ /**
25
+ * Symbol used to declare index-to-column mappings on an entity type.
26
+ * For decorator entities, declare as a phantom property:
27
+ * ```typescript
28
+ * [IndexHints]?: { idx_email: 'email'; idx_name_age: 'name' | 'age' };
29
+ * ```
30
+ * For `defineEntity` entities, index hints are inferred automatically from
31
+ * named indexes (property-level `.index('name')` and entity-level `indexes`/`uniques`).
32
+ */
33
+ export const IndexHints = Symbol('IndexHints');
25
34
  /**
26
35
  * Runtime metadata for an entity, holding its properties, relations, indexes, hooks, and more.
27
36
  * Created during metadata discovery and used throughout the ORM lifecycle.
@@ -39,12 +48,20 @@ export class EntityMetadata {
39
48
  this.indexes = [];
40
49
  this.uniques = [];
41
50
  this.checks = [];
51
+ this.triggers = [];
42
52
  this.referencingProperties = [];
43
53
  this.concurrencyCheckKeys = new Set();
44
54
  Object.assign(this, meta);
45
55
  const name = meta.className ?? meta.name;
46
56
  if (!this.class && name) {
47
- const Class = this.extends === BaseEntity ? { [name]: class extends BaseEntity {
57
+ let Parent;
58
+ if (typeof this.extends === 'function') {
59
+ Parent = this.extends;
60
+ }
61
+ else if (this.extends != null && typeof this.extends.class === 'function') {
62
+ Parent = this.extends.class;
63
+ }
64
+ const Class = Parent ? { [name]: class extends Parent {
48
65
  } }[name] : { [name]: class {
49
66
  } }[name];
50
67
  this.class = Class;
@@ -149,7 +166,7 @@ export class EntityMetadata {
149
166
  if (prop.inherited || (prop.persist === false && prop.userDefined !== false)) {
150
167
  return false;
151
168
  }
152
- return prop.kind === ReferenceKind.SCALAR && ['string', 'number', 'boolean', 'Date'].includes(prop.type);
169
+ return (prop.kind === ReferenceKind.SCALAR && !prop.array && ['string', 'number', 'boolean', 'Date'].includes(prop.type));
153
170
  });
154
171
  this.hydrateProps = this.props.filter(prop => {
155
172
  // `prop.userDefined` is either `undefined` or `false`
@@ -244,8 +261,8 @@ export class EntityMetadata {
244
261
  }, { __gettersDefined: { value: true, enumerable: false } });
245
262
  }
246
263
  initIndexes(prop) {
247
- const simpleIndex = this.indexes.find(index => index.properties === prop.name && !index.options && !index.type && !index.expression);
248
- const simpleUnique = this.uniques.find(index => index.properties === prop.name && !index.options);
264
+ const simpleIndex = this.indexes.find(index => index.properties === prop.name && !index.options && !index.type && !index.expression && index.where == null);
265
+ const simpleUnique = this.uniques.find(index => index.properties === prop.name && !index.options && !index.expression && index.where == null);
249
266
  const owner = prop.kind === ReferenceKind.MANY_TO_ONE;
250
267
  if (!prop.index && simpleIndex) {
251
268
  Utils.defaultValue(simpleIndex, 'name', true);
@@ -474,6 +474,9 @@ export class UnitOfWork {
474
474
  }
475
475
  unsetIdentity(entity) {
476
476
  this.#identityMap.delete(entity);
477
+ this.#persistStack.delete(entity);
478
+ this.#removeStack.delete(entity);
479
+ this.#orphanRemoveStack.delete(entity);
477
480
  const wrapped = helper(entity);
478
481
  const serializedPK = wrapped.getSerializedPrimaryKey();
479
482
  // remove references of this entity in all managed entities, otherwise flushing could reinsert the entity
@@ -1,18 +1,19 @@
1
- import type { Constructor, IMigrationGenerator, IMigrationRunner, IMigrator, IMigratorStorage, MaybePromise, Migration, MigrationInfo, MigrationRow, MigratorEvent } from '../typings.js';
1
+ import type { Constructor, IMigrationGenerator, IMigrationRunner, IMigrator, IMigratorStorage, MaybePromise, Migration, MigrationInfo, MigrationResult, MigrationRow, MigratorEvent } from '../typings.js';
2
2
  import type { Transaction } from '../connections/Connection.js';
3
3
  import type { Configuration, MigrationsOptions } from './Configuration.js';
4
4
  import type { EntityManagerType, IDatabaseDriver } from '../drivers/IDatabaseDriver.js';
5
5
  interface RunnableMigration {
6
6
  name: string;
7
7
  path?: string;
8
- up: () => MaybePromise<void>;
9
- down: () => MaybePromise<void>;
8
+ up: (afterRun?: (tx?: Transaction) => Promise<void>) => MaybePromise<void>;
9
+ down: (afterRun?: (tx?: Transaction) => Promise<void>) => MaybePromise<void>;
10
10
  }
11
11
  type MigrateOptions = {
12
12
  from?: string | number;
13
13
  to?: string | number;
14
14
  migrations?: string[];
15
15
  transaction?: Transaction;
16
+ schema?: string;
16
17
  };
17
18
  export declare abstract class AbstractMigrator<D extends IDatabaseDriver> implements IMigrator {
18
19
  #private;
@@ -57,11 +58,15 @@ export declare abstract class AbstractMigrator<D extends IDatabaseDriver> implem
57
58
  /**
58
59
  * @inheritDoc
59
60
  */
60
- getExecuted(): Promise<MigrationRow[]>;
61
+ getExecuted(options?: {
62
+ schema?: string;
63
+ }): Promise<MigrationRow[]>;
61
64
  /**
62
65
  * @inheritDoc
63
66
  */
64
- getPending(): Promise<MigrationInfo[]>;
67
+ getPending(options?: {
68
+ schema?: string;
69
+ }): Promise<MigrationInfo[]>;
65
70
  /**
66
71
  * @inheritDoc
67
72
  */
@@ -70,6 +75,16 @@ export declare abstract class AbstractMigrator<D extends IDatabaseDriver> implem
70
75
  * @inheritDoc
71
76
  */
72
77
  down(options?: string | string[] | Omit<MigrateOptions, 'from'>): Promise<MigrationInfo[]>;
78
+ /**
79
+ * @inheritDoc
80
+ */
81
+ rollup(migrations?: string[]): Promise<MigrationResult>;
82
+ /**
83
+ * Extracts the body of a method from migration source code using brace counting.
84
+ * Returns the raw lines between the opening and closing braces, or empty string if not found.
85
+ * @internal
86
+ */
87
+ private extractMethodBody;
73
88
  abstract getStorage(): IMigratorStorage;
74
89
  /**
75
90
  * @inheritDoc