Skip to main content
Version: 7.1

@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

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> ]?: RestoreOptUnknown<T[K]> | 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

    EntityDataPropValue

    EntityDataPropValue<T>: T | Primary<T> | PolymorphicPrimary<T>

    Allowed value types when assigning to an entity data property: the entity itself, its PK, or a polymorphic PK tuple.


    Type parameters

    • T

    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 extends { __serialized?: infer U } ? IsUnknown<U> extends false ? U : T : 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)[]; discriminator?: (T extends EntityClass<infer P> ? keyof P : string) | AnyString; discriminatorColumn?: string; discriminatorMap?: Dictionary<string>; discriminatorValue?: number | string; expression?: string | (em, where, options, stream) => object; forceConstructor?: boolean; hasTriggers?: boolean; inheritance?: tpt; orderBy?: QueryOrderMap<E> | QueryOrderMap<E>[]; partitionBy?: EntityPartitionBy<E>; readonly?: boolean; repository?: () => Constructor; schema?: string; tableName?: string; triggers?: TriggerDef<E>[]; 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.

    • optionaldiscriminator?: (T extends EntityClass<infer P> ? keyof P : string) | AnyString

      For Single Table Inheritance. Property name on the entity that stores the discriminator value.

    • optionaldiscriminatorColumn?: string

      For Single Table Inheritance. Override the discriminator column name (the property is named via discriminator; defaults to the naming-strategy-derived column).

    • 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 })
    • optionalpartitionBy?: EntityPartitionBy<E>

      PostgreSQL partitioning definition for this table.

      Partitioned tables are tracked by the schema generator and introspected back from PostgreSQL. Changing an existing partition layout still requires a manual migration.

    • 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.

    • optionaltriggers?: TriggerDef<E>[]

      Database triggers to create for this entity's table. (SQL drivers only)

    • 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).

    EntityPartitionBy

    EntityPartitionBy<E>: { expression: EntityPartitionExpression<E>; partitions: number | readonly string[]; type: Extract<EntityPartitionType, hash> } | { expression: EntityPartitionExpression<E>; partitions: EntityPartition<E>[]; type: Exclude<EntityPartitionType, hash> }

    PostgreSQL table partitioning definition.

    • hash partitions generate child tables automatically from the partition count
    • list and range partitions require explicit child partition definitions

    Type parameters

    EntityPartitionExpression

    EntityPartitionExpression<E>: (keyof E & string) | readonly (keyof E & string)[] | AnyString | (columns) => string

    Partition key expression for PostgreSQL partitioned tables.

    You can use:

    • a property name, e.g. 'type'
    • a list of property names for composite expressions, e.g. ['tenant', 'createdAt']
    • a raw SQL expression string, e.g. "date_trunc('month', created_at)"
    • a callback that receives schema column mappings and returns SQL

    Type parameters

    EntityPartitionType

    EntityPartitionType: hash | list | range

    Supported PostgreSQL partitioning strategies.

    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 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>

    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

    ExtractIndexHints

    ExtractIndexHints<T>: T extends { [IndexHints]?: infer H } ? H extends [infer P] ? InferPropertyIndexMap<P> : H : never

    Extracts the index hints map from an entity type. Returns never when no hints are declared. For decorator entities, [IndexHints] contains a pre-computed { idxName: 'prop' } map. For defineEntity entities, [IndexHints] contains [Properties] (a tuple wrapping the raw property builders), which is lazily converted to the index map when first accessed.


    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

    FormulaColumns

    FormulaColumns<T>: Record<PropertyName<T>, string> & { toString: any }

    Column mapping for formula callbacks. Maps property names to fully-qualified alias.fieldName. Has toString() returning the main alias for backwards compatibility with old formula syntax.

    @example
    // New recommended syntax - use cols.propName for fully-qualified references
    formula: cols => `${cols.firstName} || ' ' || ${cols.lastName}`

    // Old syntax still works - cols.toString() returns the alias
    formula: cols => `${cols}.first_name || ' ' || ${cols}.last_name`

    Type parameters

    • T

    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. The runtime columns object includes nested entries for embedded properties (see SchemaColumnRef); cast to SchemaColumns<T> if you need typed nested access.


    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. The runtime columns object includes nested entries for embedded properties (see SchemaColumnRef); cast to SchemaColumns<T> if you need typed nested access.


    Type parameters

    • T

    Type declaration

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

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

        Returns string | Raw

    IndexColumns

    IndexColumns<T, Name>: ExtractIndexHints<T> extends Record<Name, infer Cols> ? Cols & string : EntityKey<T>

    Properties covered by the named index on entity T. Falls back to all entity keys when the index is unknown.


    Type parameters

    • T
    • Name: string

    IndexFilterQuery

    IndexFilterQuery<T, Using>: [Using] extends [never] ? FilterQuery<T> : (OperatorMap<T> & { -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 }) | NonNullable<ExpandScalar<Primary<T>>> | IndexFilterQuery<T, Using>[]

    FilterQuery restricted to only properties covered by the specified index(es). Used when using option is set in FindOptions to enforce type-safe index usage.


    Type parameters

    • T
    • Using: string

    IndexName

    IndexName<T>: [ExtractIndexHints<T>] extends [never] ? string : (keyof ExtractIndexHints<T> & string) | (string & {})

    Union of declared index names on an entity. Falls back to string when no [IndexHints] are declared.


    Type parameters

    • T

    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, BaseDiscriminatorColumn, DiscriminatorValue>: (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 ... ? ... : ... }) & NarrowDiscriminator<Omit<Base, typeof PrimaryKeyProp>, BaseDiscriminatorColumn, DiscriminatorValue>>, 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 ? {} : NarrowDiscriminator<Omit<Base, typeof PrimaryKeyProp>, BaseDiscriminatorColumn, DiscriminatorValue>) & (ForceObject extends true ? { [Config]?: DefineConfig<{ forceObject: true }> } : {}) & { [IndexHints]?: [Properties] }

    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
    • BaseDiscriminatorColumn: string | undefined = undefined
    • DiscriminatorValue: string | number | undefined = undefined

    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>

    InferPrimaryKeyConstraint

    InferPrimaryKeyConstraint<Properties>: { [ K in keyof Properties ]: Properties[K] extends (...args) => any ? K : Properties[K] extends { ~options: { primary: true } } ? K : never }[keyof Properties]

    Like InferPrimaryKey, but skips evaluating function return types to prevent circular inference (GH #7445).


    Type parameters

    • Properties: Record<string, any>

    InflightQueryAbortStrategy

    InflightQueryAbortStrategy: ignore query | cancel query | kill session

    Strategy applied when an AbortSignal fires while a query is in flight.

    • 'ignore query' — stop awaiting; the query keeps running on the server until it settles (the connection returns to the pool only when the database replies).
    • 'cancel query' — ask the database to cancel the running query (e.g. pg_cancel_backend, KILL QUERY). Falls back to 'ignore query' if the dialect cannot cancel. Most engines do not cancel writes; partial commits are possible.
    • 'kill session' — terminate the database session/process the query runs in (pg_terminate_backend etc.). Falls back to 'cancel query' if not supported.

    Default: 'ignore query'.

    Streaming queries (em.stream() / qb.stream()): the strategy is silently treated as 'ignore query' because the underlying driver only accepts a plain AbortSignal for streamed reads — there is no server-side cancel for an open cursor. The MongoDB driver also has no notion of strategies; only the signal is honored there.

    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

    LazyRef

    LazyRef<T>: IsAny<T> extends true ? LazyRef.Brand<T> : { [ K in PrimaryProperty<T> & keyof T ]: T[K] } & LazyRef.Brand<T>

    Type-level marker for a to-one relation that is direct at runtime (no Reference wrapper) but restricted at compile time until narrowed via Loaded<>.

    Use as the property type on a @ManyToOne/@OneToOne relation that does not have ref: true:

    @ManyToOne(() => User)
    author!: LazyRef<User>;

    Semantics:

    • Runtime: identical to a plain direct relation — article.author is a User instance (stub or hydrated), article.author instanceof User is true, no Reference object is created.
    • Type (unloaded view): only the primary key is accessible. Accessing other properties is a compile error.
    • Type (loaded view): once the relation is in the populate hint of a Loaded<Entity, 'author'>, it narrows back to the full entity — no .$ or .get() indirection needed.

    Note: the safety is purely compile-time. JS code or as any casts bypass it.


    Type parameters

    • T: object

    LoadableConstructor

    LoadableConstructor<TBase>: abstract new (...args) => InstanceType<TBase> & LoadableEntity

    Return-type shape of Loadable — a constructor that produces instances of TBase enriched with LoadableEntity.


    Type parameters

    • TBase: EntityConstructor

    Type declaration

    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[]; schema?: 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[]
    • optionalschema?: string

      Target schema to run migrations against. Issues a driver-specific "set current schema" statement (e.g. SET search_path on PostgreSQL) before each migration, and places the tracking table in this schema. Overrides migrations.schema from config. Not supported on MSSQL.

    • 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; includeWildcardSchema?: boolean; migrationsList?: (MigrationObject | Constructor<Migration>)[]; path?: string; pathTs?: string; safe?: boolean; schema?: string; 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.

    • optionalincludeWildcardSchema?: boolean

      When set, entities with a wildcard schema (schema: '*') are included in generated migrations. The emitted SQL is unqualified — and therefore safe to apply against any schema at runtime via migrator.up({ schema }) — only when neither options.schema nor the ORM's config.schema is set. If config.schema is set, wildcard tables are qualified with it (useful for local dev runs); in that case, generate migrations from an environment where config.schema is unset.

    • 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.

    • optionalschema?: string

      Target schema used when running migrations. When set, the driver's "set current schema" statement (e.g. SET search_path on PostgreSQL) is issued before each migration, and the migration tracking table lives in this schema. Can be overridden per call via migrator.up({ schema }).

      Intended for per-deployment-one-schema setups (e.g. PR previews) and for applying a single unqualified migration to multiple schemas (see includeWildcardSchema). Not supported on MSSQL.

    • 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; limit?: number; offset?: number; orderBy?: QueryOrderMap<any>; 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
    • optionallimit?: number

      Limit the number of items loaded per parent entity. Collections will be marked as partial and readonly.

    • optionaloffset?: number

      Offset for per-parent limiting (used with limit).

    • optionalorderBy?: QueryOrderMap<any>

      Order by clause for per-parent limiting. Takes precedence over nested FindOptions.orderBy.

    • 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; limit?: number; offset?: number; orderBy?: QueryOrderMap<T[keyof T]>; 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
    • optionallimit?: number

      Limit the number of items loaded per parent entity. Collections will be marked as partial and readonly.

    • optionaloffset?: number

      Offset for per-parent limiting (used with limit).

    • optionalorderBy?: QueryOrderMap<T[keyof T]>

      Order by clause for per-parent limiting. Takes precedence over nested FindOptions.orderBy.

    • 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 readonly infer Value[] ? Value : T extends Dictionary ? ValueOf<T> : 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> ]: RestoreOptUnknown<T[K]> | RequiredEntityDataProp<T[K], T, C> | Primary<T[K]> | PolymorphicPrimary<T[K]> | Raw } & { [ K in keyof T as OptionalKeys<T, K, I> ]?: RestoreOptUnknown<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

    RoutineArgs

    RoutineArgs<R>: R extends Routine<any, infer A, any> ? A : Record<string, unknown>

    Type parameters

    • R

    RoutineBodyCallback

    RoutineBodyCallback<T>: (params, em) => string | Raw

    Type parameters

    • T

    Type declaration

      • (params, em): string | Raw
      • Parameters

        • params: RoutineParamMap<T>
        • em: any

        Returns string | Raw

    RoutineIgnoreField

    RoutineIgnoreField: body | comment | security | deterministic | definer

    RoutineJsBody

    RoutineJsBody<T>: (params) => unknown

    JS fallback registered as a UDF on SQLite (better-sqlite3). Functions only.


    Type parameters

    • T

    Type declaration

      • (params): unknown
      • Parameters

        • params: T

        Returns unknown

    RoutineReturn

    RoutineReturn<R>: R extends Routine<any, any, infer Re> ? Re : unknown

    Type parameters

    • R

    RoutineReturns

    RoutineReturns<T>: () => EntityName<any> | () => EntityName<any>[] | { nullable?: boolean; type: Type<unknown> | Constructor<Type<unknown>> } | { columnType?: string; customType?: Type<unknown> | Constructor<Type<unknown>>; nullable?: boolean; runtimeType: RoutineRuntimeType } | { hydrate: (rows, args, em) => unknown }

    Routine return shape:

    • omitted/void: procedures with no result set
    • () => Entity (single or tuple): hydrated row arrays, one per result set
    • { type: Type<...> }: scalar function return — runtime/column types both inferred from the Type generics
    • { runtimeType, columnType }: scalar function return with explicit SQL+TS types
    • { hydrate }: fully custom row mapping

    Type parameters

    • T = unknown

    RoutineRuntimeType

    RoutineRuntimeType: keyof RoutineRuntimeTypeMap

    Narrow union (vs EntityProperty['runtimeType']) so literals survive const inference and feed args/return inference.

    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

    SchemaColumnRef

    SchemaColumnRef: string & {}

    Column reference for schema callbacks. Behaves like a string (coercible via toString()), with arbitrary nested property access for embedded sub-columns (e.g. cols.address.city).

    SchemaColumns

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

    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). Embedded properties expose their sub-columns via nested access (e.g. cols.address.city), while coercing to the embedded property's own column name via toString() (matches the pre-7712 behaviour, regardless of any custom prefix).


    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]> } & { [___fieldsHint]?: (hint) => void; [___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, F, KeepPK>: string extends H ? EntityDTOFlat<T, C> : [F] extends [*] ? { [ 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> } : { [ 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> }

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

    KeepPK controls whether primary keys are auto-included when narrowing by F. The toObject() path keeps the default true (PKs always present); the explicit serialize() path passes false so the user-provided fields option is a strict whitelist that can drop PKs from the output.


    Type parameters

    • T
    • H: string = never
    • E: string = never
    • C: TypeConfig = never
    • F: string = *
    • KeepPK: boolean = true

    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

    TriggerCallback

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

    Callback for trigger body 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

    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).

    WithUsingOptions

    WithUsingOptions<Opts, Entity, Using>: Omit<Opts, where | using> & { using?: Using | Using[]; where?: [Using] extends [never] ? FilterQuery<Entity> : IndexFilterQuery<Entity, Using> }

    Replaces where and using on an options type with index-aware variants when Using is specified.


    Type parameters

    • Opts
    • Entity
    • Using: string

    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').

    constIndexHints

    IndexHints: typeof IndexHints = ...

    Symbol used to declare index-to-column mappings on an entity type. For decorator entities, declare as a phantom property:

    [IndexHints]?: { idx_email: 'email'; idx_name_age: 'name' | 'age' };

    For defineEntity entities, index hints are inferred automatically from named indexes (property-level .index('name') and entity-level indexes/uniques).

    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

    Page Options