import type { ConnectionType, Constructor, EntityData, EntityMetadata, EntityProperty, FilterQuery, Primary, Dictionary, IPrimaryKey, PopulateOptions, EntityDictionary, AutoPath, ObjectQuery, FilterObject, Populate, EntityName, PopulateHintOptions, Prefixes } from '../typings.js'; import type { Connection, QueryResult, Transaction } from '../connections/Connection.js'; import type { FlushMode, LockMode, QueryOrderMap, QueryFlag, LoadStrategy, PopulateHint, PopulatePath } from '../enums.js'; import type { Platform } from '../platforms/Platform.js'; import type { MetadataStorage } from '../metadata/MetadataStorage.js'; import type { Collection } from '../entity/Collection.js'; import type { EntityManager } from '../EntityManager.js'; import type { DriverException } from '../exceptions.js'; import type { Configuration } from '../utils/Configuration.js'; import type { MikroORM } from '../MikroORM.js'; import type { LoggingOptions, LogContext } from '../logging/Logger.js'; import type { Raw } from '../utils/RawQueryFragment.js'; /** Symbol used to extract the EntityManager type from a driver instance. */ export declare const EntityManagerType: unique symbol; /** Interface defining the contract for all database drivers. */ export interface IDatabaseDriver { [EntityManagerType]: EntityManager; readonly config: Configuration; /** Creates a new EntityManager instance for this driver. */ createEntityManager(useContext?: boolean): this[typeof EntityManagerType]; /** Opens a connection to the database. */ connect(options?: { skipOnConnect?: boolean; }): Promise; /** Closes the database connection. */ close(force?: boolean): Promise; /** Closes and re-establishes the database connection. */ reconnect(options?: { skipOnConnect?: boolean; }): Promise; /** Returns the underlying database connection (write or read replica). */ getConnection(type?: ConnectionType): C; /** * Finds selection of entities */ find(entityName: EntityName, where: FilterQuery, options?: FindOptions): Promise[]>; /** * Finds single entity (table row, document) */ findOne(entityName: EntityName, where: FilterQuery, options?: FindOneOptions): Promise | null>; /** Finds entities backed by a virtual (expression-based) definition. */ findVirtual(entityName: EntityName, where: FilterQuery, options: FindOptions): Promise[]>; /** Returns an async iterator that streams query results one entity at a time. */ stream(entityName: EntityName, where: FilterQuery, options: StreamOptions): AsyncIterableIterator; /** Inserts a single row into the database. */ nativeInsert(entityName: EntityName, data: EntityDictionary, options?: NativeInsertUpdateOptions): Promise>; /** Inserts multiple rows into the database in a single batch operation. */ nativeInsertMany(entityName: EntityName, data: EntityDictionary[], options?: NativeInsertUpdateManyOptions, transform?: (sql: string) => string): Promise>; /** Updates rows matching the given condition. */ nativeUpdate(entityName: EntityName, where: FilterQuery, data: EntityDictionary, options?: NativeInsertUpdateOptions): Promise>; /** Updates multiple rows with different payloads in a single batch operation. */ nativeUpdateMany(entityName: EntityName, where: FilterQuery[], data: EntityDictionary[], options?: NativeInsertUpdateManyOptions): Promise>; /** Deletes rows matching the given condition. */ nativeDelete(entityName: EntityName, where: FilterQuery, options?: NativeDeleteOptions): Promise>; /** Persists changes to M:N collections (inserts/deletes pivot table rows). */ syncCollections(collections: Iterable>, options?: DriverMethodOptions): Promise; /** Counts entities matching the given condition. */ count(entityName: EntityName, where: FilterQuery, options?: CountOptions): Promise; /** Executes a MongoDB aggregation pipeline (MongoDB driver only). */ aggregate(entityName: EntityName, pipeline: any[]): Promise; /** Maps raw database result to entity data, converting column names to property names. */ mapResult(result: EntityDictionary, meta: EntityMetadata, populate?: PopulateOptions[]): EntityData | null; /** * When driver uses pivot tables for M:N, this method will load identifiers for given collections from them */ loadFromPivotTable(prop: EntityProperty, owners: Primary[][], where?: FilterQuery, orderBy?: OrderDefinition, ctx?: Transaction, options?: FindOptions, pivotJoin?: boolean): Promise>; /** Returns the database platform abstraction for this driver. */ getPlatform(): Platform; /** Sets the metadata storage used by this driver. */ setMetadata(metadata: MetadataStorage): void; /** Returns the metadata storage used by this driver. */ getMetadata(): MetadataStorage; /** * Returns name of the underlying database dependencies (e.g. `mongodb` or `mysql2`) * for SQL drivers it also returns `knex` in the array as connectors are not used directly there */ getDependencies(): string[]; /** Acquires a pessimistic lock on the given entity. */ lockPessimistic(entity: T, options: LockOptions): Promise; /** * Converts native db errors to standardized driver exceptions */ convertException(exception: Error): DriverException; /** * @internal */ getSchemaName(meta?: EntityMetadata, options?: { schema?: string; parentSchema?: string; }): string | undefined; /** * @internal */ getORMClass(): Constructor; } /** Represents a field selector for entity queries (property name or wildcard). */ export type EntityField = keyof T | PopulatePath.ALL | AutoPath; /** Defines the ordering for query results, either a single order map or an array of them. */ export type OrderDefinition = (QueryOrderMap & { 0?: never; }) | QueryOrderMap[]; /** Options for `em.findAll()`, extends FindOptions with an optional `where` clause. */ export interface FindAllOptions extends FindOptions { where?: FilterQuery; } /** Options for streaming query results via `em.stream()`. */ export interface StreamOptions extends Omit, 'cache' | 'before' | 'after' | 'first' | 'last' | 'overfetch' | 'strategy'> { /** * When populating to-many relations, the ORM streams fully merged entities instead of yielding every row. * You can opt out of this behavior by specifying `mergeResults: false`. This will yield every row from * the SQL result, but still mapped to entities, meaning that to-many collections will contain at most * a single item, and you will get duplicate root entities when they have multiple items in the populated * collection. * * @default true */ mergeResults?: boolean; } /** Configuration for enabling/disabling named filters on a query. */ export type FilterOptions = Dictionary | string[] | boolean; /** Specifies which relations to populate and which fields to select or exclude. */ export interface LoadHint { populate?: Populate; fields?: readonly AutoPath[]; exclude?: readonly AutoPath[]; } /** Options for `em.find()` queries, including population, ordering, pagination, and locking. */ export interface FindOptions extends LoadHint { /** * Where condition for populated relations. This will have no effect on the root entity. * With `select-in` strategy, this is applied only to the populate queries. * With `joined` strategy, those are applied as `join on` conditions. * When you use a nested condition on a to-many relation, it will produce a nested inner join, * discarding the collection items based on the child condition. */ populateWhere?: ObjectQuery | PopulateHint | `${PopulateHint}`; /** * Filter condition for populated relations. This is similar to `populateWhere`, but will produce a `left join` * when nesting the condition. This is used for implementation of joined filters. */ populateFilter?: ObjectQuery; /** * Index-friendly alternative to `$or` for conditions that span joined relations. * Each array element becomes an independent branch combined via `UNION ALL` subquery: * `WHERE pk IN (branch_1 UNION ALL branch_2 ... branch_N)`. * The database plans each branch independently, enabling per-table index usage * (e.g. GIN trigram indexes for fuzzy search across related entities). * sql only */ unionWhere?: ObjectQuery[]; /** * Strategy for combining `unionWhere` branches. * - `'union-all'` (default) — skips deduplication, faster for most use cases. * - `'union'` — deduplicates rows between branches; useful when branch overlap is very high. * sql only */ unionWhereStrategy?: 'union-all' | 'union'; /** Used for ordering of the populate queries. If not specified, the value of `options.orderBy` is used. */ populateOrderBy?: OrderDefinition; /** Per-relation overrides for populate loading behavior. Keys are populate paths (same as used in `populate`). */ populateHints?: [Hint] extends [never] ? never : { [K in Prefixes]?: PopulateHintOptions; }; /** Ordering of the results.Can be an object or array of objects, keys are property names, values are ordering (asc/desc) */ orderBy?: OrderDefinition; /** Control result caching for this query. Result cache is by default disabled, not to be confused with the identity map. */ cache?: boolean | number | [string, number]; /** * Limit the number of returned results. If you try to use limit/offset on a query that joins a to-many relation, pagination mechanism * will be triggered, resulting in a subquery condition, to apply this limit only to the root entities * instead of the cartesian product you get from a database in this case. */ limit?: number; /** * Sets the offset. If you try to use limit/offset on a query that joins a to-many relation, pagination mechanism * will be triggered, resulting in a subquery condition, to apply this limit only to the root entities * instead of the cartesian product you get from a database in this case. */ offset?: number; /** Fetch items `before` this cursor. */ before?: string | { startCursor: string | null; } | FilterObject; /** Fetch items `after` this cursor. */ after?: string | { endCursor: string | null; } | FilterObject; /** Fetch `first` N items. */ first?: number; /** Fetch `last` N items. */ last?: number; /** Fetch one more item than `first`/`last`, enabled automatically in `em.findByCursor` to check if there is a next page. */ overfetch?: boolean; refresh?: boolean; convertCustomTypes?: boolean; disableIdentityMap?: boolean; schema?: string; flags?: QueryFlag[]; /** sql only */ groupBy?: string | string[]; having?: FilterQuery; /** sql only */ strategy?: LoadStrategy | `${LoadStrategy}`; flushMode?: FlushMode | `${FlushMode}`; filters?: FilterOptions; /** sql only */ lockMode?: Exclude; /** sql only */ lockTableAliases?: string[]; ctx?: Transaction; connectionType?: ConnectionType; /** SQL: appended to FROM clause (e.g. `'force index(my_index)'`); MongoDB: index name or spec passed as `hint`. */ indexHint?: string | Dictionary; /** sql only */ comments?: string | string[]; /** sql only */ hintComments?: string | string[]; /** SQL: collation name string applied as COLLATE to ORDER BY; MongoDB: CollationOptions object. */ collation?: CollationOptions | string; /** mongodb only */ maxTimeMS?: number; /** mongodb only */ allowDiskUse?: boolean; loggerContext?: LogContext; logging?: LoggingOptions; /** @internal used to apply filters to the auto-joined relations */ em?: EntityManager; } /** Options for cursor-based pagination via `em.findByCursor()`. */ export interface FindByCursorOptions extends Omit, 'limit' | 'offset'> { includeCount?: I; } /** Options for `em.findOne()`, extends FindOptions with optimistic lock version support. */ export interface FindOneOptions extends Omit, 'limit' | 'lockMode'> { lockMode?: LockMode; lockVersion?: number | Date; } /** Options for `em.findOneOrFail()`, adds a custom error handler for missing entities. */ export interface FindOneOrFailOptions extends FindOneOptions { failHandler?: (entityName: string, where: Dictionary | IPrimaryKey | any) => Error; strict?: boolean; } /** Options for native insert and update operations. */ export interface NativeInsertUpdateOptions { convertCustomTypes?: boolean; ctx?: Transaction; schema?: string; /** `nativeUpdate()` only option */ upsert?: boolean; loggerContext?: LogContext; /** sql only */ unionWhere?: ObjectQuery[]; /** sql only */ unionWhereStrategy?: 'union-all' | 'union'; filters?: FilterOptions; /** @internal */ em?: EntityManager; } /** Options for batch native insert and update operations. */ export interface NativeInsertUpdateManyOptions extends NativeInsertUpdateOptions { processCollections?: boolean; } /** Options for `em.upsert()`, controlling conflict resolution behavior. */ export interface UpsertOptions extends Omit, 'upsert'> { onConflictFields?: (keyof Entity)[] | Raw; onConflictAction?: 'ignore' | 'merge'; onConflictMergeFields?: AutoPath[]; onConflictExcludeFields?: AutoPath[]; onConflictWhere?: FilterQuery; disableIdentityMap?: boolean; } /** Options for `em.upsertMany()`, adds batch size control. */ export interface UpsertManyOptions extends UpsertOptions { batchSize?: number; } /** Options for `em.count()` queries. */ export interface CountOptions { filters?: FilterOptions; schema?: string; groupBy?: string | readonly string[]; having?: FilterQuery; cache?: boolean | number | [string, number]; populate?: Populate; populateWhere?: ObjectQuery | PopulateHint | `${PopulateHint}`; populateFilter?: ObjectQuery; /** @see FindOptions.unionWhere */ unionWhere?: ObjectQuery[]; /** @see FindOptions.unionWhereStrategy */ unionWhereStrategy?: 'union-all' | 'union'; ctx?: Transaction; connectionType?: ConnectionType; flushMode?: FlushMode | `${FlushMode}`; /** SQL: appended to FROM clause (e.g. `'force index(my_index)'`); MongoDB: index name or spec passed as `hint`. */ indexHint?: string | Dictionary; /** sql only */ comments?: string | string[]; /** sql only */ hintComments?: string | string[]; /** SQL: collation name string applied as COLLATE; MongoDB: CollationOptions object. */ collation?: CollationOptions | string; /** mongodb only */ maxTimeMS?: number; loggerContext?: LogContext; logging?: LoggingOptions; /** @internal used to apply filters to the auto-joined relations */ em?: EntityManager; } /** Options for `em.qb().update()` operations. */ export interface UpdateOptions { filters?: FilterOptions; schema?: string; ctx?: Transaction; /** sql only */ unionWhere?: ObjectQuery[]; /** sql only */ unionWhereStrategy?: 'union-all' | 'union'; } /** Options for `em.qb().delete()` operations. */ export interface DeleteOptions extends DriverMethodOptions { filters?: FilterOptions; /** sql only */ unionWhere?: ObjectQuery[]; /** sql only */ unionWhereStrategy?: 'union-all' | 'union'; /** @internal */ em?: EntityManager; } /** Options for `em.nativeDelete()` operations. */ export interface NativeDeleteOptions extends DriverMethodOptions { filters?: FilterOptions; /** sql only */ unionWhere?: ObjectQuery[]; /** sql only */ unionWhereStrategy?: 'union-all' | 'union'; /** @internal */ em?: EntityManager; } /** Options for pessimistic and optimistic lock operations. */ export interface LockOptions extends DriverMethodOptions { lockMode?: LockMode; lockVersion?: number | Date; lockTableAliases?: string[]; logging?: LoggingOptions; } /** Base options shared by all driver methods (transaction context, schema, logging). */ export interface DriverMethodOptions { ctx?: Transaction; schema?: string; loggerContext?: LogContext; } /** MongoDB-style collation options for locale-aware string comparison. */ export interface CollationOptions { locale: string; caseLevel?: boolean; caseFirst?: string; strength?: number; numericOrdering?: boolean; alternate?: string; maxVariable?: string; backwards?: boolean; } /** Options for `em.getReference()`, controlling wrapping and type conversion. */ export interface GetReferenceOptions { wrapped?: boolean; convertCustomTypes?: boolean; schema?: string; /** * Property name to use for identity map lookup instead of the primary key. * This is useful for creating references by unique non-PK properties. */ key?: string; }