import { EntityMetadata, type AnyEntity, type EntityKey, type Constructor, type DeepPartial, type Dictionary, type EntityName, type EntityProperty, type CleanKeys, type ExpandProperty, type IsNever, type EntityCtor, } from '../typings.js'; import type { EntityRepository } from '../entity/EntityRepository.js'; import { BaseEntity } from '../entity/BaseEntity.js'; import { type EventType, Cascade, ReferenceKind } from '../enums.js'; import type { EventArgs } from '../events/EventSubscriber.js'; import { Type } from '../types/Type.js'; import { Utils } from '../utils/Utils.js'; import { EnumArrayType } from '../types/EnumArrayType.js'; import type { PropertyOptions, ManyToOneOptions, OneToOneOptions, OneToManyOptions, ManyToManyOptions, EmbeddedOptions, EnumOptions, PrimaryKeyOptions, SerializedPrimaryKeyOptions, IndexOptions, UniqueOptions, } from './types.js'; // mirrors `MetadataStorage.META_SYMBOL`, we can't import it here due to a module cycle const META_SYMBOL = Symbol.for('@mikro-orm/core/MetadataStorage.META_SYMBOL'); type TypeType = | string | NumberConstructor | StringConstructor | BooleanConstructor | DateConstructor | ArrayConstructor | Constructor> | Type; type TypeDef = { type: TypeType } | { entity: () => EntityName | EntityName[] }; type EmbeddedTypeDef = { type: TypeType } | { entity: () => EntityName | EntityName[] }; /** Union type representing all possible property definition shapes in an EntitySchema. */ export type EntitySchemaProperty = | ({ kind: ReferenceKind.MANY_TO_ONE | 'm:1' } & TypeDef & ManyToOneOptions) | ({ kind: ReferenceKind.ONE_TO_ONE | '1:1' } & TypeDef & OneToOneOptions) | ({ kind: ReferenceKind.ONE_TO_MANY | '1:m' } & TypeDef & OneToManyOptions) | ({ kind: ReferenceKind.MANY_TO_MANY | 'm:n' } & TypeDef & ManyToManyOptions) | ({ kind: ReferenceKind.EMBEDDED | 'embedded' } & EmbeddedTypeDef & EmbeddedOptions & PropertyOptions) | ({ enum: true } & EnumOptions) | (TypeDef & PropertyOptions); type OmitBaseProps = IsNever extends true ? Entity : Omit; /** Configuration object for defining an entity via EntitySchema. */ export type EntitySchemaMetadata> = Omit< Partial>, 'name' | 'properties' | 'extends' > & ({ name: string } | { class: Class; name?: string }) & { extends?: EntityName } & { properties?: { [Key in keyof OmitBaseProps as CleanKeys, Key>]-?: EntitySchemaProperty< ExpandProperty>, Entity >; }; } & { inheritance?: 'tpt' }; /** Class-less entity definition that provides a programmatic API for defining entities without decorators. */ export class EntitySchema> { /** * When schema links the entity class via `class` option, this registry allows the lookup from opposite side, * so we can use the class in `entities` option just like the EntitySchema instance. * * Stored on `globalThis` via `Symbol.for` to survive the CJS/ESM dual-package hazard * (e.g. when `tsx` loads the same package in both module systems). */ static get REGISTRY(): Map { const key = Symbol.for('@mikro-orm/core/EntitySchema.REGISTRY'); return ((globalThis as any)[key] ??= new Map()); } /** @internal Type-level marker for fast entity type inference */ declare readonly '~entity': Entity; private readonly _meta: EntityMetadata; private internal = false; private initialized = false; constructor(meta: EntitySchemaMetadata) { // Skip for internal schemas (fromMetadata) — the name was already resolved, // re-deriving it from class.name would break defineEntity + setClass with a different name (GH #7391). if (!(meta as Dictionary).internal) { meta.name = meta.class ? meta.class.name : meta.name; } if (meta.name) { meta.abstract ??= false; } this._meta = new EntityMetadata({ className: meta.name, ...(meta as Partial>), }); this._meta.root ??= this._meta; if (meta.class && !(meta as Dictionary).internal) { EntitySchema.REGISTRY.set(meta.class, this); } } /** * Checks if the given value is an EntitySchema instance, using duck-typing * as a fallback when `instanceof` fails due to CJS/ESM dual-package hazard * (e.g. when using `tsx` or `@swc-node/register` with `"type": "commonjs"` projects). */ static is(item: unknown): item is EntitySchema { if (item instanceof EntitySchema) { return true; } return item != null && typeof item === 'object' && item.constructor?.name === 'EntitySchema' && 'meta' in item; } /** Creates an EntitySchema from existing EntityMetadata (used internally). */ static fromMetadata( meta: EntityMetadata | DeepPartial>, ): EntitySchema { const schema = new EntitySchema({ ...meta, internal: true } as unknown as EntitySchemaMetadata); schema.internal = true; return schema; } /** Adds a scalar property to the entity schema. */ addProperty( name: EntityKey, type?: TypeType, options: PropertyOptions | EntityProperty = {}, ): void { this.renameCompositeOptions(name, options); const prop = { name, kind: ReferenceKind.SCALAR, ...options, ...this.normalizeType(options, type), } as EntityProperty; if (type && Type.isMappedType((type as Constructor).prototype)) { prop.type = type as string; } if (typeof prop.formula === 'string') { const formula = prop.formula; prop.formula = () => formula; } if (prop.formula) { prop.persist ??= false; } if ((prop as any).check) { this._meta.checks.push({ property: prop.name, expression: (prop as any).check }); delete (prop as any).check; } this._meta.properties[name] = prop; } /** Adds an enum property to the entity schema. */ addEnum(name: EntityKey, type?: TypeType, options: EnumOptions = {}): void { if (options.items instanceof Function) { options.items = Utils.extractEnumValues(options.items()); } else if (options.items && !Array.isArray(options.items) && typeof options.items === 'object') { options.items = Utils.extractEnumValues(options.items as Dictionary); } // enum arrays are simple numeric/string arrays, the constraint is enforced in the custom type only if (options.array && !options.type) { options.type = new EnumArrayType( `${this._meta.className}.${name}`, options.items as readonly (number | string)[], ); (options as EntityProperty).enum = false; } const prop = { enum: true, ...options }; if (prop.array) { prop.enum = false; } // force string labels on native enums if (prop.nativeEnumName && Array.isArray(prop.items)) { prop.items = prop.items.map(val => '' + val); } this.addProperty(name, this.internal ? type : type || 'enum', prop); } /** Adds a version property for optimistic locking. */ addVersion(name: EntityKey, type: TypeType, options: PropertyOptions = {}): void { this.addProperty(name, type, { version: true, ...options }); } /** Adds a primary key property to the entity schema. */ addPrimaryKey(name: EntityKey, type: TypeType, options: PrimaryKeyOptions = {}): void { this.addProperty(name, type, { primary: true, ...options }); } /** Adds a serialized primary key property (e.g. for MongoDB ObjectId). */ addSerializedPrimaryKey( name: EntityKey, type: TypeType, options: SerializedPrimaryKeyOptions = {}, ): void { this._meta.serializedPrimaryKey = name; this.addProperty(name, type, { serializedPrimaryKey: true, ...options }); } /** Adds an embedded property to the entity schema. */ addEmbedded(name: EntityKey, options: EmbeddedOptions): void { this.renameCompositeOptions(name, options); Utils.defaultValue(options, 'prefix', true); if (options.array) { options.object = true; // force object mode for arrays } this._meta.properties[name] = { name, kind: ReferenceKind.EMBEDDED, ...this.normalizeType(options), ...options, } as EntityProperty; } /** Adds a many-to-one relation to the entity schema. */ addManyToOne( name: EntityKey, type: TypeType, options: ManyToOneOptions, ): void { const prop = this.createProperty(ReferenceKind.MANY_TO_ONE, options); prop.owner = true; if (prop.joinColumns && !prop.fieldNames) { prop.fieldNames = prop.joinColumns; } if (prop.fieldNames && !prop.joinColumns) { prop.joinColumns = prop.fieldNames; } // By default, the foreign key constraint is created on the relation Utils.defaultValue(prop, 'createForeignKeyConstraint', true); this.addProperty(name, type, prop); } /** Adds a many-to-many relation to the entity schema. */ addManyToMany( name: EntityKey, type: TypeType, options: ManyToManyOptions, ): void { options.fixedOrder = options.fixedOrder || !!options.fixedOrderColumn; if (!options.owner && !options.mappedBy) { options.owner = true; } if (options.owner) { Utils.renameKey(options, 'mappedBy', 'inversedBy'); // By default, the foreign key constraint is created on the relation Utils.defaultValue(options, 'createForeignKeyConstraint', true); } const prop = this.createProperty(ReferenceKind.MANY_TO_MANY, options); this.addProperty(name, type, prop); } /** Adds a one-to-many relation to the entity schema. */ addOneToMany( name: EntityKey, type: TypeType, options: OneToManyOptions, ): void { const prop = this.createProperty(ReferenceKind.ONE_TO_MANY, options); this.addProperty(name, type, prop); } /** Adds a one-to-one relation to the entity schema. */ addOneToOne( name: EntityKey, type: TypeType, options: OneToOneOptions, ): void { const prop = this.createProperty(ReferenceKind.ONE_TO_ONE, options) as EntityProperty; Utils.defaultValue(prop, 'owner', !!prop.inversedBy || !prop.mappedBy); Utils.defaultValue(prop, 'unique', prop.owner); if (prop.owner) { if (options.mappedBy) { Utils.renameKey(prop, 'mappedBy', 'inversedBy'); } // By default, the foreign key constraint is created on the relation Utils.defaultValue(prop, 'createForeignKeyConstraint', true); } if (prop.joinColumns && !prop.fieldNames) { prop.fieldNames = prop.joinColumns; } if (prop.fieldNames && !prop.joinColumns) { prop.joinColumns = prop.fieldNames; } this.addProperty(name, type, prop); } /** Adds an index definition to the entity schema. */ addIndex(options: IndexOptions): void { this._meta.indexes.push(options as any); } /** Adds a unique constraint definition to the entity schema. */ addUnique(options: UniqueOptions): void { this._meta.uniques.push(options as any); } /** Sets a custom repository class for this entity. */ setCustomRepository(repository: () => Constructor): void { this._meta.repository = repository as () => Constructor>; } /** Sets the base entity that this schema extends. */ setExtends(base: EntityName): void { this._meta.extends = base; } /** Sets or replaces the entity class associated with this schema. */ setClass(cls: Class) { const oldClass = this._meta.class; const sameClass = this._meta.class === cls; this._meta.class = cls; this._meta.prototype = cls.prototype; this._meta.className = this._meta.name ?? cls.name; if (!sameClass || !this._meta.constructorParams) { this._meta.constructorParams = Utils.getConstructorParams(cls) as EntityKey[]; } if (!this.internal) { // Remove old class from registry if it's being replaced with a different class if (oldClass && oldClass !== cls && EntitySchema.REGISTRY.get(oldClass) === this) { EntitySchema.REGISTRY.delete(oldClass); } EntitySchema.REGISTRY.set(cls, this); } const base = Object.getPrototypeOf(cls); // Only set extends if the parent is NOT the auto-generated class for this same entity. // When the user extends the auto-generated class (from defineEntity without a class option) // and registers their custom class via setClass, we don't want to discover the // auto-generated class as a separate parent entity. A parent carrying its own decorator // metadata is a real base class even when a minifier mangles it to the same name as the child. if (base !== BaseEntity && (base.name !== this._meta.className || Object.hasOwn(base, META_SYMBOL))) { this._meta.extends ??= base.name ? base : undefined; } } /** Returns the underlying EntityMetadata. */ get meta(): EntityMetadata { return this._meta; } /** Returns the entity class name. */ get name(): string | EntityName { return this._meta.className; } /** Returns the database table name. */ get tableName(): string { return this._meta.tableName; } get class(): Class { return this._meta.class; } get properties(): Record { return this._meta.properties; } new(...params: ConstructorParameters): Entity { return new (this._meta.class as any)(...params); } /** * @internal */ init(): this { if (this.initialized) { return this; } this.setClass(this._meta.class); // `discriminator` is the property name on the entity / embeddable; `discriminatorColumn` is an // optional column-name override on that property. For backward compat, when only // `discriminatorColumn` is given (legacy), it is treated as the property name. Once normalized, // `meta.discriminatorColumn` always holds the property name (so existing readers keep working), // and `meta.discriminatorFieldName` carries the explicit column override (if any). if ( this._meta.discriminator && this._meta.discriminatorColumn && this._meta.discriminator !== this._meta.discriminatorColumn ) { this._meta.discriminatorFieldName = this._meta.discriminatorColumn; this._meta.discriminatorColumn = this._meta.discriminator; } else { this._meta.discriminatorColumn ??= this._meta.discriminator; this._meta.discriminator ??= this._meta.discriminatorColumn; } // Abstract TPT entities keep their name because they have their own table const isTPT = (this._meta as any).inheritance === 'tpt' || this.isPartOfTPTHierarchy(); if (this._meta.abstract && !this._meta.discriminatorColumn && !isTPT) { delete this._meta.name; } const tableName = this._meta.collection ?? this._meta.tableName; if (tableName?.includes('.') && !this._meta.schema) { this._meta.schema = tableName.substring(0, tableName.indexOf('.')); this._meta.tableName = tableName.substring(tableName.indexOf('.') + 1); } this.initProperties(); this.initPrimaryKeys(); this._meta.props = Object.values(this._meta.properties); this._meta.relations = this._meta.props.filter( prop => typeof prop.kind !== 'undefined' && prop.kind !== ReferenceKind.SCALAR && prop.kind !== ReferenceKind.EMBEDDED, ); this.initialized = true; return this; } /** * Check if this entity is part of a TPT hierarchy by walking up the extends chain. * This handles mid-level abstract entities (e.g., Animal -> Mammal -> Dog where Mammal is abstract). */ private isPartOfTPTHierarchy(): boolean { let parent = this._meta.extends; while (parent) { const parentSchema = EntitySchema.is(parent) ? parent : EntitySchema.REGISTRY.get(parent as any); if (!parentSchema) { break; } if ((parentSchema._meta as any).inheritance === 'tpt') { return true; } parent = parentSchema._meta.extends; } return false; } private initProperties(): void { Utils.entries(this._meta.properties).forEach(([name, options]) => { if (Type.isMappedType(options.type)) { options.type ??= (options.type as Dictionary).constructor.name; } switch (options.kind) { case ReferenceKind.ONE_TO_ONE: this.addOneToOne(name, options.type, options as unknown as OneToOneOptions); break; case ReferenceKind.ONE_TO_MANY: this.addOneToMany(name, options.type, options); break; case ReferenceKind.MANY_TO_ONE: this.addManyToOne(name, options.type, options as unknown as ManyToOneOptions); break; case ReferenceKind.MANY_TO_MANY: this.addManyToMany(name, options.type, options as unknown as ManyToManyOptions); break; case ReferenceKind.EMBEDDED: this.addEmbedded(name, options as EmbeddedOptions); break; default: if (options.enum) { this.addEnum(name, options.type, options); } else if (options.primary) { this.addPrimaryKey(name, options.type, options); } else if (options.serializedPrimaryKey) { this.addSerializedPrimaryKey(name, options.type, options); } else if (options.version) { this.addVersion(name, options.type, options); } else { this.addProperty(name, options.type, options); } } }); } private initPrimaryKeys(): void { const pks = Object.values>(this._meta.properties).filter(prop => prop.primary); if (pks.length > 0) { this._meta.primaryKeys = pks.map(prop => prop.name); this._meta.compositePK = pks.length > 1; this._meta.simplePK = !this._meta.compositePK && pks[0].kind === ReferenceKind.SCALAR && !pks[0].customType; } if (pks.length === 1 && ['number', 'bigint'].includes(pks[0].type)) { pks[0].autoincrement ??= true; } const serializedPrimaryKey = Object.values>(this._meta.properties).find( prop => prop.serializedPrimaryKey, ); if (serializedPrimaryKey) { this._meta.serializedPrimaryKey = serializedPrimaryKey.name; } } private normalizeType( options: PropertyOptions | EntityProperty | EmbeddedOptions, type?: string | any | Constructor, ): { type: string; target?: unknown } { if ('entity' in options) { /* v8 ignore next */ if (typeof options.entity === 'string') { throw new Error( `Relation target needs to be an entity class or EntitySchema instance, string '${options.entity}' given instead for ${this._meta.className}.${options.name}.`, ); } else if (options.entity) { const tmp = options.entity(); type = options.type = Array.isArray(tmp) ? tmp .map(t => Utils.className(t)) .sort() .join(' | ') : Utils.className(tmp); const target: EntityName | EntityName[] = EntitySchema.is(tmp) ? tmp.meta.class : tmp; return { type, target }; } } if (type instanceof Function) { type = type.name; } if (['String', 'Number', 'Boolean', 'Array'].includes(type)) { type = type.toLowerCase(); } return { type }; } private createProperty(kind: ReferenceKind, options: PropertyOptions | EntityProperty): EntityProperty { return { kind, cascade: [Cascade.PERSIST], ...options, } as EntityProperty; } private rename(data: U, from: string, to: string): void { if (from in data && !(to in data)) { // @ts-ignore data[to] = [data[from]]; // @ts-ignore delete data[from]; } } private renameCompositeOptions( name: EntityKey, options: PropertyOptions | EntityProperty | EmbeddedOptions = {}, ): void { if (name !== options.name && !options.fieldNames) { Utils.renameKey(options, 'name', 'fieldName'); } else if (options.name && (options.fieldNames?.length ?? 0) > 1) { delete options.name; } this.rename(options, 'fieldName', 'fieldNames'); this.rename(options, 'joinColumn', 'joinColumns'); this.rename(options, 'inverseJoinColumn', 'inverseJoinColumns'); this.rename(options, 'referenceColumnName', 'referencedColumnNames'); this.rename(options, 'columnType', 'columnTypes'); } /** * Adds a lifecycle hook handler to the entity schema. * This method allows registering hooks after the entity is defined, * which can be useful for avoiding circular type references. * * @example * ```ts * export const Article = defineEntity({ * name: 'Article', * properties: { ... }, * }); * * Article.addHook('beforeCreate', async args => { * args.entity.slug = args.entity.title.toLowerCase(); * }); * ``` */ addHook( event: EventType | `${EventType}`, handler: (args: EventArgs) => void | Promise, ): this { this._meta.hooks[event as EventType] ??= []; this._meta.hooks[event as EventType]!.push(handler as any); return this; } }