Skip to main content
Version: 7.0

@mikro-orm/core

Index

References

Namespaces

Enumerations

Classes

Interfaces

Type Aliases

Variables

Functions

References

Raw

Renames and re-exports RawQueryFragment

Type Aliases

AnyEntity

AnyEntity<T>: Partial<T>

Loose entity type used in generic contexts. Equivalent to Partial<T>.


Type parameters

  • T = any

AnyString

AnyString: string & {}

Branded string that accepts any string value while preserving autocompletion for known literals.

AutoPath

AutoPath<O, P, E, D>: P extends boolean ? P : [D] extends [never] ? never : P extends any ? P extends string ? P extends `${infer A}.${infer B}` ? A extends StringKeys<O, E> ? `${A}.${AutoPath<NonNullable<GetStringKey<O, A, E>>, B, E, Prev[D]>}` : never : P extends StringKeys<O, E> ? (NonNullable<GetStringKey<..., ..., ...>> extends unknown ? Exclude<P, `${...}.`> : never) | (StringKeys<NonNullable<...>, E> extends never ? never : `${... & ...}.`) : StringKeys<O, E> | `${RelationKeys<O>}:ref` : never : never

Autocomplete-friendly type for dot-separated relation paths (e.g., 'author.books'). Validates each segment against entity keys and provides IDE suggestions. Depth-limited to prevent infinite recursion.


Type parameters

  • O
  • P: string | boolean
  • E: string = never
  • D: Prev[number] = 9

Cast

Cast<T, R>: T extends R ? T : R

Conditional cast: returns T if it extends R, otherwise returns R.


Type parameters

  • T
  • R

CheckCallback

CheckCallback<T>: (columns, table) => string | Raw

Callback for CHECK constraint expressions. Receives column mappings and table info.


Type parameters

  • T

Type declaration

    • (columns, table): string | Raw
    • Parameters

      • columns: Record<PropertyName<T>, string>
      • table: SchemaTable

      Returns string | Raw

CompiledFunctions

CompiledFunctions: Record<string, (...args) => any>

Record of compiled functions, used internally for hydration and comparison.

ConnectionType

ConnectionType: read | write

Discriminator for read vs write database connections in read-replica setups.

Constructor

Constructor<T>: new (...args) => T

Generic constructor type. Matches any class that can be instantiated with new.


Type parameters

  • T = unknown

Type declaration

    • new (...args): T
    • Parameters

      • rest...args: any[]

      Returns T

DeepPartial

DeepPartial<T>: T & { [ P in keyof T ]?: T[P] extends infer U[] ? DeepPartial<U>[] : T[P] extends Readonly<infer U>[] ? Readonly<DeepPartial<U>>[] : DeepPartial<T[P]> }

Recursively makes all properties of T optional, including nested objects and arrays.


Type parameters

  • T

DefineConfig

DefineConfig<T>: T & DefineConfig.Brand

Branded type for entity-level configuration (e.g., [Config]?: DefineConfig<{ forceObject: true }>). Controls type-level behavior such as forcing object representation for primary keys in DTOs.


Type parameters

Dictionary

Dictionary<T>: {}

Simple string-keyed object type. Use instead of Record<string, T> for convenience.


Type parameters

  • T = any

Type declaration

    EmbeddedPrefixMode

    EmbeddedPrefixMode: absolute | relative

    With absolute the prefix is set at the root of the entity (regardless of the nesting level)

    EntityClass

    EntityClass<T>: Function & { prototype: T }

    A class (function with prototype) whose instances are of type T.


    Type parameters

    • T = any

    EntityCtor

    EntityCtor<T>: abstract new (...args) => T

    Abstract constructor type that matches both abstract and concrete entity classes.


    Type parameters

    • T = any

    Type declaration

      • abstract new (...args): T
      • Parameters

        • rest...args: any[]

        Returns T

    EntityData

    EntityData<T, C>: { [ K in EntityKey<T> ]?: EntityDataItem<T[K] & {}, C> }

    Data shape for creating or updating entities. All properties are optional. Used in em.create() and em.assign().


    Type parameters

    • T
    • C: boolean = false

    EntityDataValue

    EntityDataValue<T>: EntityData<T>[EntityKey<T>]

    Resolves to the value type within EntityData<T> (the data shape used for create/update).


    Type parameters

    • T

    EntityDictionary

    EntityDictionary<T>: EntityData<T> & Record<any, any>

    EntityData<T> extended with an index signature, allowing arbitrary additional properties.


    Type parameters

    • T

    EntityDTO

    EntityDTO<T, C>: { [ K in keyof T as DTORequiredKeys<T, K> ]: EntityDTOProp<T, T[K], C> | AddOptional<T[K]> } & { [ K in keyof T as DTOOptionalKeys<T, K> ]?: EntityDTOProp<T, T[K], C> | AddOptional<T[K]> }

    Plain object (DTO) representation of an entity as returned by toObject() / toPOJO(). Unwraps references to PKs, collections to arrays, and respects hidden properties.


    Type parameters

    EntityDTOProp

    EntityDTOProp<E, T, C, Flat>: T extends Scalar ? T : T extends ScalarReference<infer U> ? U : T extends { __serialized?: infer U } ? IsUnknown<U> extends false ? U : T : T extends LoadedReferenceShape<infer U> ? DTOWrapper<U, C, Flat> : T extends ReferenceShape<infer U> ? PrimaryOrObject<E, U, C> : T extends LoadedCollectionShape<infer U> ? DTOWrapper<U & object, C, Flat>[] : T extends CollectionShape<infer U> ? PrimaryOrObject<E, U & object, C>[] : T extends readonly ...[] ? U extends Scalar ? T : EntityDTOProp<..., ..., ..., ...>[] : T extends Relation<T> ? DTOWrapper<T, C, Flat> : T

    Resolves the serialized (DTO) type for a single entity property. Unwraps references, collections, and custom serialized types.


    Type parameters

    EntityField

    EntityField<T, P>: keyof T | PopulatePath.ALL | AutoPath<T, P, `${PopulatePath.ALL}`>

    Represents a field selector for entity queries (property name or wildcard).


    Type parameters

    • T
    • P: string = PopulatePath.ALL

    EntityKey

    EntityKey<T, B>: string & { [ K in keyof T ]-?: CleanKeys<T, K, B> extends never ? never : K }[keyof T]

    Extracts string property keys from an entity, excluding symbols, functions, and internal keys. Pass B = true to also exclude scalar properties (useful for getting only relation keys).


    Type parameters

    • T = unknown
    • B: boolean = false

    EntityName

    EntityName<T>: EntityClass<T> | EntityCtor<T> | EntitySchema<T, any>

    Any valid entity name reference: a class, abstract constructor, or EntitySchema.


    Type parameters

    • T = any

    EntityOptions

    EntityOptions<T, E>: { abstract?: boolean; collection?: string; comment?: string; constructorParams?: (T extends EntityClass<infer P> ? keyof P : string)[]; discriminatorColumn?: (T extends EntityClass<infer P> ? keyof P : string) | AnyString; discriminatorMap?: Dictionary<string>; discriminatorValue?: number | string; expression?: string | (em, where, options, stream) => object; forceConstructor?: boolean; hasTriggers?: boolean; inheritance?: tpt; orderBy?: QueryOrderMap<E> | QueryOrderMap<E>[]; readonly?: boolean; repository?: () => Constructor; schema?: string; tableName?: string; view?: boolean | { materialized?: boolean; withData?: boolean }; virtual?: boolean }

    Type parameters

    Type declaration

    • optionalabstract?: boolean

      Marks entity as abstract, such entities are inlined during discovery.

    • optionalcollection?: string

      Override default collection/table name. Alias for tableName.

    • optionalcomment?: string

      Specify comment to table. (SQL only)

    • optionalconstructorParams?: (T extends EntityClass<infer P> ? keyof P : string)[]

      Specify constructor parameters to be used in em.create or when forceConstructor is enabled. Those should be names of declared entity properties in the same order as your constructor uses them. The ORM tries to infer those automatically, use this option in case the inference fails.

    • optionaldiscriminatorColumn?: (T extends EntityClass<infer P> ? keyof P : string) | AnyString
    • optionaldiscriminatorMap?: Dictionary<string>
    • optionaldiscriminatorValue?: number | string
    • optionalexpression?: string | (em, where, options, stream) => object

      SQL query that maps to a virtual entity, or for view entities, the view definition.

    • optionalforceConstructor?: boolean

      Enforce use of constructor when creating managed entity instances.

    • optionalhasTriggers?: boolean

      Used to make ORM aware of externally defined triggers. This is needed for MS SQL Server multi inserts, ignored in other dialects.

    • optionalinheritance?: tpt

      Set inheritance strategy: 'tpt' for Table-Per-Type inheritance. When set on the root entity, each entity in the hierarchy gets its own table with a FK from child PK to parent PK.

    • optionalorderBy?: QueryOrderMap<E> | QueryOrderMap<E>[]

      Set default ordering for this entity. This ordering is applied when:

      • Querying the entity directly via em.find(), em.findAll(), etc.
      • Populating the entity as a relation

      All orderings are combined together. Precedence (highest to lowest):

      1. Runtime FindOptions.orderBy
      2. Relation-level @OneToMany({ orderBy }) / @ManyToMany({ orderBy })
      3. Entity-level @Entity({ orderBy })
    • optionalreadonly?: boolean

      Disables change tracking - such entities are ignored during flush.

    • optionalrepository?: () => Constructor
    • optionalschema?: string

      Sets the schema name.

    • optionaltableName?: string

      Override default collection/table name. Alias for collection.

    • optionalview?: boolean | { materialized?: boolean; withData?: boolean }

      Marks entity as a database view. Unlike virtual entities which evaluate expressions at query time, view entities create actual database views. The expression option must be provided when view is true. View entities are read-only by default.

      Use view: true for regular views, or view: { materialized: true } for materialized views (PostgreSQL only). Materialized views store the query results and must be refreshed to update data. Use view: { materialized: true, withData: false } to create an unpopulated materialized view.

    • optionalvirtual?: boolean

      Marks entity as virtual. This is set automatically when you use expression option (unless view is set).

    EntityProps

    EntityProps<T>: { -readonly [ K in EntityKey<T> ]?: T[K] }

    Partial entity shape with all entity properties optional.


    Type parameters

    • T

    EntityRef

    EntityRef<T>: true extends IsUnknown<PrimaryProperty<T>> ? Reference<T> : IsAny<T> extends true ? Reference<T> : { [ K in PrimaryProperty<T> & keyof T ]: T[K] } & Reference<T>

    Alias for Reference<T> & { id: number } (see Ref).


    Type parameters

    • T: object

    EntitySchemaMetadata

    EntitySchemaMetadata<Entity, Base, Class>: Omit<Partial<EntityMetadata<Entity>>, name | properties | extends> & ({ name: string } | { class: Class; name?: string }) & { extends?: EntityName<Base> } & { properties?: { [ Key in keyof OmitBaseProps<Entity, Base> as CleanKeys<OmitBaseProps<Entity, Base>, Key> ]-?: EntitySchemaProperty<ExpandProperty<NonNullable<Entity[Key]>>, Entity> } } & { inheritance?: tpt }

    Configuration object for defining an entity via EntitySchema.


    Type parameters

    EntitySchemaProperty

    EntitySchemaProperty<Target, Owner>: ({ kind: ReferenceKind.MANY_TO_ONE | m:1 } & TypeDef<Target> & ManyToOneOptions<Owner, Target>) | ({ kind: ReferenceKind.ONE_TO_ONE | 1:1 } & TypeDef<Target> & OneToOneOptions<Owner, Target>) | ({ kind: ReferenceKind.ONE_TO_MANY | 1:m } & TypeDef<Target> & OneToManyOptions<Owner, Target>) | ({ kind: ReferenceKind.MANY_TO_MANY | m:n } & TypeDef<Target> & ManyToManyOptions<Owner, Target>) | ({ kind: ReferenceKind.EMBEDDED | embedded } & EmbeddedTypeDef<Target> & EmbeddedOptions<Owner, Target> & PropertyOptions<Owner>) | ({ enum: true } & EnumOptions<Owner>) | (TypeDef<Target> & PropertyOptions<Owner>)

    Union type representing all possible property definition shapes in an EntitySchema.


    Type parameters

    • Target
    • Owner

    EntityType

    EntityType<T>: T | LoadedEntityType<T>

    Accepts either a plain entity type or a Loaded/Selected wrapped version.


    Type parameters

    • T

    EntityValue

    EntityValue<T>: T[EntityKey<T>]

    Resolves to the value type of entity properties (keyed by EntityKey<T>).


    Type parameters

    • T

    ExpandHint

    ExpandHint<T, L>: L | AddEager<T>

    Combines an explicit populate hint L with the entity's eagerly loaded properties.


    Type parameters

    • T
    • L: string

    ExpandProperty

    ExpandProperty<T>: T extends ReferenceShape<infer U> ? NonNullable<U> : T extends CollectionShape<infer U> ? NonNullable<U> : T extends infer U[] ? NonNullable<U> : NonNullable<T>

    Unwraps a property type from its wrapper (Reference, Collection, or array) to the inner entity type.


    Type parameters

    • T

    ExpandQuery

    ExpandQuery<T>: T extends object ? T extends Scalar ? never : FilterQuery<T> : FilterValue<T>

    Recursively expands a type into its FilterQuery form for nested object filtering.


    Type parameters

    • T

    ExpandScalar

    ExpandScalar<T>: null | (T extends string ? T | RegExp : T extends Date ? Date | string : T extends bigint ? bigint | string | number : T)

    Expands a scalar type to include alternative representations accepted in queries (e.g., Date | string).


    Type parameters

    • T

    FilterDef

    FilterDef<T>: FilterDefResolved<EntityFromInput<T>> & { entity?: T }

    Definition of a query filter that can be registered globally or per-entity via @Filter().


    Type parameters

    FilterItemValue

    FilterItemValue<T>: T | ExpandScalar<T> | Primary<T> | Raw

    A single filter value: the raw value, its expanded scalar form, its primary key, or a raw SQL expression.


    Type parameters

    • T

    FilterKey

    FilterKey<T>: keyof FilterQuery<T>

    Extracts valid keys for FilterQuery<T>.


    Type parameters

    • T

    FilterObject

    FilterObject<T>: { -readonly [ K in EntityKey<T> ]?: ExpandQuery<ExpandProperty<FilterObjectProp<T, K>>> | ExpandQueryMerged<ExpandProperty<FilterObjectProp<T, K>>> | FilterValue<ExpandProperty<FilterObjectProp<T, K>>> | ElemMatchFilter<FilterObjectProp<T, K>> | null }

    Object form of a filter query, mapping entity keys to their filter conditions.


    Type parameters

    • T

    FilterOptions

    FilterOptions: Dictionary<boolean | Dictionary> | string[] | boolean

    Configuration for enabling/disabling named filters on a query.

    FilterQuery

    FilterQuery<T>: ObjectQuery<T> | NonNullable<ExpandScalar<Primary<T>>> | NonNullable<EntityProps<T> & OperatorMap<T>> | FilterQuery<T>[]

    The main query filter type used in em.find(), em.findOne(), etc. Accepts an object query, a primary key value, entity props with operators, or an array of filters.


    Type parameters

    • T

    FilterValue

    FilterValue<T>: OperatorMap<FilterItemValue<T>> | FilterItemValue<T> | FilterItemValue<T>[] | null

    A complete filter value: an operator map, a single value, an array of values, or null.


    Type parameters

    • T

    FormulaCallback

    FormulaCallback<T>: (columns, table) => string | Raw

    Callback for computed (formula) properties. Receives column mappings and table info, returns a SQL expression.


    Type parameters

    • T

    Type declaration

      • (columns, table): string | Raw
      • Parameters

        Returns string | Raw

    FormulaTable

    FormulaTable: { alias: string; name: string; qualifiedName: string; schema?: string; toString: () => string }

    Table reference object passed to formula callbacks, including alias and schema information.


    Type declaration

    • alias: string
    • name: string
    • qualifiedName: string
    • optionalschema?: string
    • toString: () => string
        • (): string
        • Returns string

    FromEntityType

    FromEntityType<T>: T extends LoadedEntityType<infer U> ? U : T

    Extracts the base entity type from a Loaded/Selected wrapper, or returns T as-is.


    Type parameters

    • T

    GeneratedColumnCallback

    GeneratedColumnCallback<T>: (columns, table) => string | Raw

    Callback for generated (computed) column expressions. Receives column mappings and table info.


    Type parameters

    • T

    Type declaration

      • (columns, table): string | Raw
      • Parameters

        • columns: Record<PropertyName<T>, string>
        • table: SchemaTable

        Returns string | Raw

    GetRepository

    GetRepository<Entity, Fallback>: Entity[typeof EntityRepositoryType] extends EntityRepository<any> | undefined ? NonNullable<Entity[typeof EntityRepositoryType]> : Fallback

    Resolves the custom repository type for an entity (from [EntityRepositoryType]), or falls back to Fallback.


    Type parameters

    • Entity: {}
    • Fallback

    Hidden

    Hidden<T>: T & Hidden.Brand

    Branded type that marks a property as hidden from serialization. Use as a property type wrapper: password: Hidden<string> instead of listing in [HiddenProps].


    Type parameters

    • T = unknown

    ImportsResolver

    ImportsResolver: (alias, basePath, extension, originFileName) => { name: string; path: string } | undefined

    Custom resolver for import paths in the entity generator. Returns a path/name pair or undefined to use the default.


    Type declaration

      • (alias, basePath, extension, originFileName): { name: string; path: string } | undefined
      • Parameters

        • alias: string
        • basePath: string
        • extension: .js |
        • originFileName: string

        Returns { name: string; path: string } | undefined

    IndexCallback

    IndexCallback<T>: (columns, table, indexName) => string | Raw

    Callback for custom index expressions. Receives column mappings, table info, and the index name.


    Type parameters

    • T

    Type declaration

      • (columns, table, indexName): string | Raw
      • Parameters

        • columns: Record<PropertyName<T>, string>
        • table: SchemaTable
        • indexName: string

        Returns string | Raw

    InferEntity

    InferEntity<Schema>: Schema extends { ~entity: infer E } ? E : Schema extends EntitySchema<infer Entity> ? Entity : Schema extends EntityClass<infer Entity> ? Entity : Schema

    Extracts the entity type from an EntitySchema, EntitySchemaWithMeta, or entity class. Uses a fast-path direct property access when available, falling back to generic inference.


    Type parameters

    • Schema

    InferEntityFromProperties

    InferEntityFromProperties<Properties, PK, Base, Repository, ForceObject>: (IsNever<Base> extends true ? {} : Base extends { toObject: any } ? Pick<IWrappedEntity<{ -readonly [ K in keyof Properties ]: InferBuilderValue<MaybeReturnType<...[...]>> } & { [PrimaryKeyProp]?: InferCombinedPrimaryKey<Properties, PK, Base> } & (IsNever<Repository> extends true ? {} : { [EntityRepositoryType]?: ... extends ... ? ... : ... }) & Omit<Base, typeof PrimaryKeyProp>>, BaseEntityMethodKeys> : {}) & { -readonly [ K in keyof Properties ]: InferBuilderValue<MaybeReturnType<Properties[K]>> } & { [PrimaryKeyProp]?: InferCombinedPrimaryKey<Properties, PK, Base> } & (IsNever<Repository> extends true ? {} : { [EntityRepositoryType]?: Repository extends Constructor<infer R> ? R : Repository }) & (IsNever<Base> extends true ? {} : Omit<Base, typeof PrimaryKeyProp>) & (ForceObject extends true ? { [Config]?: DefineConfig<{ forceObject: true }> } : {})

    Infers the entity type from a defineEntity() properties map, resolving builders, base classes, and primary keys.


    Type parameters

    • Properties: Record<string, any>
    • PK: keyof Properties[] | undefined = undefined
    • Base = never
    • Repository = never
    • ForceObject: boolean = false

    InferEntityName

    InferEntityName<T>: T extends { [EntityName]?: infer Name } ? Name extends string ? Name : never : never

    Extracts the entity name string literal from an entity type that declares [EntityName].


    Type parameters

    • T

    InferPrimaryKey

    InferPrimaryKey<Properties>: { [ K in keyof Properties ]: MaybeReturnType<Properties[K]> extends { ~options: { primary: true } } ? K : never }[keyof Properties]

    Extracts the primary key property names from a properties map by finding builders with primary: true.


    Type parameters

    • Properties: Record<string, any>

    IPrimaryKey

    IPrimaryKey<T>: T

    Alias for a primary key value, constrained to IPrimaryKeyValue.


    Type parameters

    • T: IPrimaryKeyValue = IPrimaryKeyValue

    IsSubset

    IsSubset<T, U>: keyof U extends keyof T ? {} : string extends keyof U ? {} : { [ K in keyof U as K extends keyof T ? never : CleanKeys<U, K> ]: never }

    Validates that U is a subset of T. Returns {} if valid, or a mapped type with never values to cause a type error.


    Type parameters

    • T
    • U

    IsUnknown

    IsUnknown<T>: T extends unknown ? unknown extends T ? true : never : never

    Evaluates to true if T is the unknown type.


    Type parameters

    • T

    IType

    IType<Runtime, Raw, Serialized>: Runtime & { __raw?: Raw; __runtime?: Runtime; __serialized?: Serialized }

    Branded type helper for mapping between JS runtime, database raw, and JSON serialized representations.


    Type parameters

    • Runtime
    • Raw
    • Serialized = Raw

    Loaded

    Loaded<T, L, F, E>: LoadedInternal<T, L, F, E> & { [___loadedType]?: T; [___loadHint]?: (hint) => void }

    Represents entity with its loaded relations (populate hint) and selected properties (fields hint). The __loadHint marker uses contravariance to ensure Loaded<A, 'b'> is NOT assignable to Loaded<A, 'b.c'>.


    Type parameters

    • T
    • L: string = never
    • F: string = *
    • E: string = never

    LoggerNamespace

    LoggerNamespace: query | query-params | schema | discovery | info | deprecated | slow-query

    Available logging namespaces that can be individually enabled or disabled.

    LoggingOptions

    LoggingOptions: Pick<LogContext, label | enabled | debugMode>

    Logger options to modify format output and overrides, including a label and additional properties that can be accessed by custom loggers.

    Differs from LoggerOptions in terms of how they are used; this type is primarily a public type meant to be used within methods like em.find().

    @example
    await em.findOne(User, 1, { logger: { label: 'user middleware' } };
    // [query] (user middleware) select * from user where id = 1;

    MaybePromise

    MaybePromise<T>: T | Promise<T>

    Represents a value that may be synchronous or wrapped in a Promise.


    Type parameters

    • T

    MergeLoaded

    MergeLoaded<T, U, P, F, E, R>: IsLoadedType<T> extends true ? T & Loaded<U, P, F, E> : Loaded<T, P, F, E>

    Optimized MergeLoaded using intersection instead of extraction. When T is already Loaded, we intersect with a new Loaded type for the additional hints. This avoids the expensive pattern matching needed to extract hints from Loaded types. Used for em.populate and em.refresh.


    Type parameters

    • T
    • U
    • P: string
    • F: string
    • E: string
    • R: boolean = false

    MergeSelected

    MergeSelected<T, U, F>: IsLoadedType<T> extends true ? T & Loaded<U, never, F, never> : T

    Optimized MergeSelected using intersection instead of extraction. When T is already Loaded, we intersect with a new Loaded type for the selected fields. This avoids the expensive pattern matching needed to extract hints from Loaded types.


    Type parameters

    • T
    • U
    • F: string

    MetadataProcessor

    MetadataProcessor: (metadata, platform) => MaybePromise<void>

    Callback for processing entity metadata during discovery or entity generation.


    Type declaration

    MigrateOptions

    MigrateOptions: { from?: string | number; migrations?: string[]; to?: string | number; transaction?: Transaction }

    Options for controlling which migrations to run (range, specific list, or transaction).


    Type declaration

    • optionalfrom?: string | number
    • optionalmigrations?: string[]
    • optionalto?: string | number
    • optionaltransaction?: Transaction

    MigrationInfo

    MigrationInfo: { name: string; path?: string }

    Basic migration descriptor with a name and optional file path.


    Type declaration

    • name: string
    • optionalpath?: string

    MigrationResult

    MigrationResult: { code: string; diff: MigrationDiff; fileName: string }

    Result of creating a new migration file, including the generated code and schema diff.


    Type declaration

    MigrationRow

    MigrationRow: { executed_at: Date; id: number; name: string }

    A row from the migrations tracking table, representing an executed migration.


    Type declaration

    • executed_at: Date
    • id: number
    • name: string

    MigrationsOptions

    MigrationsOptions: { allOrNothing?: boolean; disableForeignKeys?: boolean; dropTables?: boolean; emit?: js | ts | cjs; fileName?: (timestamp, name) => string; generator?: Constructor<IMigrationGenerator>; glob?: string; migrationsList?: (MigrationObject | Constructor<Migration>)[]; path?: string; pathTs?: string; safe?: boolean; silent?: boolean; snapshot?: boolean; snapshotName?: string; tableName?: string; transactional?: boolean }

    Configuration options for database migrations.

    @see

    Type declaration

    • optionalallOrNothing?: boolean

      Run all migrations in the current batch in a master transaction.

    • optionaldisableForeignKeys?: boolean

      Try to disable foreign key checks during migrations.

    • optionaldropTables?: boolean

      Allow dropping tables during schema diff.

    • optionalemit?: js | ts | cjs

      File extension for generated migration files.

    • optionalfileName?: (timestamp, name) => string

      Custom function to generate migration file names.

        • (timestamp, name): string
        • Parameters

          • timestamp: string
          • optionalname: string

          Returns string

    • optionalgenerator?: Constructor<IMigrationGenerator>

      Custom migration generator class.

    • optionalglob?: string

      Glob pattern to match migration files.

    • optionalmigrationsList?: (MigrationObject | Constructor<Migration>)[]

      List of migration classes or objects to use instead of file-based discovery.

    • optionalpath?: string

      Path to the folder with migration files (for compiled JavaScript files).

    • optionalpathTs?: string

      Path to the folder with migration files (for TypeScript source files). Used when running in TypeScript mode.

    • optionalsafe?: boolean

      Safe mode - only allow adding new tables and columns, never dropping existing ones.

    • optionalsilent?: boolean

      Disable logging for migration operations.

    • optionalsnapshot?: boolean

      Create a snapshot of the current schema after migration generation.

    • optionalsnapshotName?: string

      Custom name for the snapshot file.

    • optionaltableName?: string

      Name of the migrations table.

    • optionaltransactional?: boolean

      Run each migration inside a transaction.

    MigratorEvent

    MigratorEvent: migrating | migrated | reverting | reverted

    Events emitted by the migrator during migration execution.

    New

    New<T, P>: Loaded<T, P>

    Alias for Loaded<T, P>. Represents a newly created entity with all specified relations populated.


    Type parameters

    • T
    • P: string = string

    ObjectQuery

    ObjectQuery<T>: OperatorMap<T> & FilterObject<T>

    Object-based query filter combining operator maps with property-level filters.


    Type parameters

    • T

    Opt

    Opt<T>: T & Opt.Brand

    Branded type that marks a property as optional in em.create(). Use as a property type wrapper: createdAt: Opt<Date> instead of listing in [OptionalProps].


    Type parameters

    • T = unknown

    OrderDefinition

    OrderDefinition<T>: (QueryOrderMap<T> & { 0?: never }) | QueryOrderMap<T>[]

    Defines the ordering for query results, either a single order map or an array of them.


    Type parameters

    • T

    Populate

    Populate<T, P>: readonly AutoPath<T, P, `${PopulatePath}`>[] | false

    Type for the populate option in find methods. An array of relation paths to eagerly load, or false to disable.


    Type parameters

    • T
    • P: string = never

    PopulateHintOptions

    PopulateHintOptions: { joinType?: inner join | left join; strategy?: LoadStrategy.JOINED | LoadStrategy.SELECT_IN | joined | select-in }

    Inline options that can be appended to populate hint strings (e.g., strategy, join type).


    Type declaration

    • optionaljoinType?: inner join | left join
    • optionalstrategy?: LoadStrategy.JOINED | LoadStrategy.SELECT_IN | joined | select-in

    PopulateOptions

    PopulateOptions<T>: { all?: boolean; children?: PopulateOptions<T[keyof T]>[]; dataOnly?: boolean; field: EntityKey<T>; filter?: boolean; joinType?: inner join | left join; strategy?: LoadStrategy }

    Parsed populate hint for a single relation, including strategy and nested children.


    Type parameters

    • T

    Type declaration

    • optionalall?: boolean
    • optionalchildren?: PopulateOptions<T[keyof T]>[]
    • optionaldataOnly?: boolean

      When true, ignores mapToPk on the property and returns full entity data instead of just PKs.

    • field: EntityKey<T>
    • optionalfilter?: boolean
    • optionaljoinType?: inner join | left join
    • optionalstrategy?: LoadStrategy

    Prefixes

    Prefixes<S>: S extends * ? string : S extends `${infer H}.${infer T}` ? H | `${H}.${Prefixes<T>}` : S

    Expands a populate hint into all its prefixes. e.g., Prefixes<'a.b.c'> = 'a' | 'a.b' | 'a.b.c' This reflects that loading 'a.b.c' means 'a' and 'a.b' are also loaded. Special case: '*' returns string to ensure Loaded<T, '*'> is assignable to any Loaded<T, Hint>.


    Type parameters

    • S: string

    Primary

    Primary<T>: IsAny<T> extends true ? any : T extends { [PrimaryKeyProp]?: infer PK } ? PK extends undefined ? Omit<T, typeof PrimaryKeyProp> : PK extends keyof T ? ReadonlyPrimary<UnwrapPrimary<T[PK]>> : PK extends keyof T[] ? ReadonlyPrimary<PrimaryPropToType<T, PK>> : PK : T extends { _id?: infer PK } ? ReadonlyPrimary<PK> | string : T extends { id?: infer PK } ? ReadonlyPrimary<PK> : T extends { uuid?: infer PK } ? ReadonlyPrimary<PK> : T

    Resolves the primary key type for an entity. Uses [PrimaryKeyProp] if declared, otherwise falls back to _id, id, or uuid properties. For composite keys, returns a tuple.


    Type parameters

    • T

    PropertyBuilders

    PropertyBuilders: { [ K in Exclude<keyof typeof types, PropertyBuildersOverrideKeys> ]: () => UniversalPropertyOptionsBuilder<InferPropertyValueType<typeof types[K]>, EmptyOptions, IncludeKeysForProperty> } & { array: <T>(toJsValue, toDbValue) => UniversalPropertyOptionsBuilder<InferPropertyValueType<typeof types.array>, EmptyOptions, IncludeKeysForProperty>; bigint: <Mode>(mode) => UniversalPropertyOptionsBuilder<InferPropertyValueType<typeof types.bigint>, EmptyOptions, IncludeKeysForProperty>; datetime: (length) => UniversalPropertyOptionsBuilder<InferPropertyValueType<typeof types.datetime>, EmptyOptions, IncludeKeysForProperty>; decimal: <Mode>(mode) => UniversalPropertyOptionsBuilder<InferPropertyValueType<typeof types.decimal>, EmptyOptions, IncludeKeysForProperty>; embedded: <Target>(target) => PropertyChain<InferEntity<Target extends infer T[] ? T : Target>, EmptyOptions & { kind: embedded }>; enum: <T>(items) => UniversalPropertyOptionsBuilder<T extends () => Dictionary ? ValueOf<ReturnType<T>> : T extends infer Value[] ? Value : T, EmptyOptions, IncludeKeysForEnumOptions>; formula: <T>(formula) => UniversalPropertyOptionsBuilder<T, EmptyOptions, IncludeKeysForProperty>; json: <T>() => UniversalPropertyOptionsBuilder<T, EmptyOptions, IncludeKeysForProperty>; manyToMany: <Target>(target) => PropertyChain<InferEntity<Target>, EmptyOptions & { kind: m:n }>; manyToOne: <Target>(target) => PropertyChain<InferEntity<Target extends infer T[] ? T : Target>, EmptyOptions & { kind: m:1 }>; oneToMany: <Target>(target) => PropertyChain<InferEntity<Target>, EmptyOptions & { kind: 1:m }>; oneToOne: <Target>(target) => PropertyChain<InferEntity<Target extends infer T[] ? T : Target>, EmptyOptions & { kind: 1:1 }>; time: (length) => UniversalPropertyOptionsBuilder<InferPropertyValueType<typeof types.time>, EmptyOptions, IncludeKeysForProperty>; type: <T>(type) => UniversalPropertyOptionsBuilder<InferPropertyValueType<T>, EmptyOptions, IncludeKeysForProperty> }

    Map of factory functions for creating type-safe property builders (scalars, enums, embeddables, and relations).

    QueryOrderKeys

    QueryOrderKeys<T>: QueryOrderKeysFlat | QueryOrderMap<T>

    Type parameters

    • T

    QueryOrderKeysFlat

    QueryOrderKeysFlat: QueryOrder | QueryOrderNumeric | `${QueryOrder}`

    QueryOrderMap

    QueryOrderMap<T>: { [ K in EntityKey<T> ]?: QueryOrderKeys<ExpandProperty<T[K]>> }

    Type parameters

    • T

    RawQueryFragmentSymbol

    RawQueryFragmentSymbol: symbol & { [rawFragmentSymbolBrand]: true }

    Branded symbol type used as a unique key for tracking raw SQL fragments in object properties.

    Ref

    Ref<T>: T extends any ? IsAny<T> extends true ? Reference<T & object> : T extends Scalar ? ScalarReference<T> : EntityRef<T & object> : never

    Ref type represents a Reference instance, and adds the primary keys to its prototype automatically, so you can do ref.id instead of ref.unwrap().id. It resolves to either ScalarRef or EntityRef, based on the type argument.


    Type parameters

    • T

    Rel

    Rel<T>: T

    Identity type that can be used to get around issues with cycles in bidirectional relations. It will disable reflect-metadata inference.


    Type parameters

    • T

    RequiredEntityData

    RequiredEntityData<T, I, C>: { [ K in keyof T as RequiredKeys<T, K, I> ]: T[K] | RequiredEntityDataProp<T[K], T, C> | Primary<T[K]> | PolymorphicPrimary<T[K]> | Raw } & { [ K in keyof T as OptionalKeys<T, K, I> ]?: T[K] | RequiredEntityDataProp<T[K], T, C> | Primary<T[K]> | PolymorphicPrimary<T[K]> | Raw | null }

    Data shape for em.create() with required/optional distinction based on entity metadata. Properties with defaults, nullable types, Opt brand, or [OptionalProps] declaration are optional. I excludes additional types from being required (used for inverse side of relations).


    Type parameters

    • T
    • I = never
    • C: boolean = false

    RequiredNullable

    RequiredNullable<T>: (T & RequiredNullable.Brand) | null

    Branded type that marks a nullable property as required in em.create(). By default, nullable properties are treated as optional; this forces them to be explicitly provided.


    Type parameters

    • T = never

    Scalar

    Scalar: boolean | number | string | bigint | symbol | Date | RegExp | Uint8Array | { toHexString: any }

    Union of types considered "scalar" (non-entity) values. Used to distinguish entity relations from plain values.

    ScalarRef

    ScalarRef<T>: ScalarReference<T>

    Alias for ScalarReference (see Ref).


    Type parameters

    • T

    SchemaColumns

    SchemaColumns<T>: Record<PropertyName<T>, string>

    Column mapping for schema callbacks (indexes, checks, generated columns). Maps property names to field names. For TPT entities, only includes properties that belong to the current table (not inherited properties from parent tables).


    Type parameters

    • T

    SchemaTable

    SchemaTable: { name: string; qualifiedName: string; schema?: string; toString: () => string }

    Table reference for schema callbacks (indexes, checks, generated columns). Unlike FormulaTable, this has no alias since schema generation doesn't use query aliases.


    Type declaration

    • name: string
    • qualifiedName: string
    • optionalschema?: string
    • toString: () => string
        • (): string
        • Returns string

    Selected

    Selected<T, L, F>: { [ K in keyof T as IsPrefixed<T, K, L | F | AddEager<T>> | FunctionKeys<T, K> ]: T[K] extends Function ? T[K] : NonNullable<T[K]> extends Scalar ? T[K] : LoadedProp<NonNullable<T[K]>, Suffix<K, L, true>, Suffix<K, F, true>> | AddOptional<T[K]> } & { [___selectedType]?: T }

    Entity type narrowed to only the selected fields (F) and populated relations (L). Used as the return type when fields option is specified in find methods.


    Type parameters

    • T
    • L: string = never
    • F: string = *

    SerializeDTO

    SerializeDTO<T, H, E, C>: string extends H ? EntityDTOFlat<T, C> : { [ 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> }

    Return type of serialize(). Combines Loaded + EntityDTO in a single pass for better performance. Respects populate hints (H) and exclude hints (E).


    Type parameters

    • T
    • H: string = never
    • E: string = never
    • C: TypeConfig = never

    Transaction

    Transaction<T>: T & {}

    Opaque transaction context type, wrapping the driver-specific transaction object.


    Type parameters

    • T = any

    TransactionEventType

    TransactionEventType: EventType.beforeTransactionStart | EventType.afterTransactionStart | EventType.beforeTransactionCommit | EventType.afterTransactionCommit | EventType.beforeTransactionRollback | EventType.afterTransactionRollback

    UnboxArray

    UnboxArray<T>: T extends any[] ? ArrayElement<T> : T

    Unwraps an array type to its element type; non-arrays pass through unchanged.


    Type parameters

    • T

    UniversalPropertyKeys

    UniversalPropertyKeys: keyof PropertyOptions<any> | keyof EnumOptions<any> | keyof EmbeddedOptions<any, any> | keyof ReferenceOptions<any, any> | keyof ManyToOneOptions<any, any> | keyof OneToManyOptions<any, any> | keyof OneToOneOptions<any, any> | keyof ManyToManyOptions<any, any>

    Union of all option keys supported across all property definition types (scalar, enum, embedded, relations).

    Variables

    constARRAY_OPERATORS

    ARRAY_OPERATORS: string[] = ...

    constConfig

    Config: typeof Config = ...

    Symbol used to declare type-level configuration on an entity (e.g., [Config]?: DefineConfig<{ forceObject: true }>).

    constEagerProps

    EagerProps: typeof EagerProps = ...

    Symbol used to declare which relation properties should be eagerly loaded (e.g., [EagerProps]?: 'author').

    constEntityManagerType

    EntityManagerType: typeof EntityManagerType = ...

    Symbol used to extract the EntityManager type from a driver instance.

    constEntityName

    EntityName: typeof EntityName = ...

    Symbol used to declare the entity name as a string literal type (used by defineEntity).

    constEntityRepositoryType

    EntityRepositoryType: typeof EntityRepositoryType = ...

    Symbol used to declare a custom repository type on an entity class (e.g., [EntityRepositoryType]?: BookRepository).

    constEventTypeMap

    EventTypeMap: Record<EventType, number> = ...

    constHiddenProps

    HiddenProps: typeof HiddenProps = ...

    Symbol used to declare which properties are hidden from serialization (e.g., [HiddenProps]?: 'password').

    constJSON_KEY_OPERATORS

    JSON_KEY_OPERATORS: string[] = ...

    constJsonProperty

    JsonProperty: typeof JsonProperty = ...

    Symbol used to tag cloned embeddable data for JSON serialization handling.

    constOptionalProps

    OptionalProps: typeof OptionalProps = ...

    Symbol used to declare which properties are optional in em.create() (e.g., [OptionalProps]?: 'createdAt').

    constp

    constPrimaryKeyProp

    PrimaryKeyProp: typeof PrimaryKeyProp = ...

    Symbol used to declare the primary key property name(s) on an entity (e.g., [PrimaryKeyProp]?: 'id').

    constSCALAR_TYPES

    SCALAR_TYPES: Set<string> = ...

    constt

    t: { array: typeof ArrayType; bigint: typeof BigIntType; blob: typeof BlobType; boolean: typeof BooleanType; character: typeof CharacterType; date: typeof DateType; datetime: typeof DateTimeType; decimal: typeof DecimalType; double: typeof DoubleType; enum: typeof EnumType; enumArray: typeof EnumArrayType; float: typeof FloatType; integer: typeof IntegerType; interval: typeof IntervalType; json: typeof JsonType; mediumint: typeof MediumIntType; smallint: typeof SmallIntType; string: typeof StringType; text: typeof TextType; time: typeof TimeType; tinyint: typeof TinyIntType; uint8array: typeof Uint8ArrayType; unknown: typeof UnknownType; uuid: typeof UuidType } = types

    Shorthand alias for the types registry.


    Type declaration

    consttypes

    types: { array: typeof ArrayType; bigint: typeof BigIntType; blob: typeof BlobType; boolean: typeof BooleanType; character: typeof CharacterType; date: typeof DateType; datetime: typeof DateTimeType; decimal: typeof DecimalType; double: typeof DoubleType; enum: typeof EnumType; enumArray: typeof EnumArrayType; float: typeof FloatType; integer: typeof IntegerType; interval: typeof IntervalType; json: typeof JsonType; mediumint: typeof MediumIntType; smallint: typeof SmallIntType; string: typeof StringType; text: typeof TextType; time: typeof TimeType; tinyint: typeof TinyIntType; uint8array: typeof Uint8ArrayType; unknown: typeof UnknownType; uuid: typeof UuidType } = ...

    Registry of all built-in type constructors, keyed by their short name (e.g., types.integer, types.uuid).


    Type declaration