@mikro-orm/core
Version:
TypeScript ORM for Node.js based on Data Mapper, Unit of Work and Identity Map patterns. Supports MongoDB, MySQL, PostgreSQL and SQLite databases as well as usage with vanilla JavaScript.
173 lines (172 loc) • 8.28 kB
TypeScript
import { type Configuration, type ConnectionOptions } from '../utils/Configuration.js';
import type { LogContext, Logger } from '../logging/Logger.js';
import type { MetadataStorage } from '../metadata/MetadataStorage.js';
import type { ConnectionType, Dictionary, MaybePromise, Primary, RoutineProperty } from '../typings.js';
import type { Routine } from '../metadata/Routine.js';
import type { Platform } from '../platforms/Platform.js';
import type { Type } from '../types/Type.js';
import type { TransactionEventBroadcaster } from '../events/TransactionEventBroadcaster.js';
import type { IsolationLevel } from '../enums.js';
/** Abstract base class for database connections, providing transaction and query execution support. */
export declare abstract class Connection {
#private;
protected readonly config: Configuration;
protected readonly type: ConnectionType;
protected metadata: MetadataStorage;
protected platform: Platform;
protected readonly options: ConnectionOptions;
protected readonly logger: Logger;
protected connected: boolean;
constructor(config: Configuration, options?: ConnectionOptions, type?: ConnectionType);
/**
* Establishes connection to database
*/
abstract connect(options?: {
skipOnConnect?: boolean;
}): void | Promise<void>;
/**
* Are we connected to the database
*/
abstract isConnected(): Promise<boolean>;
/**
* Are we connected to the database
*/
abstract checkConnection(): Promise<{
ok: true;
} | {
ok: false;
reason: string;
error?: Error;
}>;
/**
* Closes the database connection (aka disconnect)
*/
close(force?: boolean): Promise<void>;
/**
* Ensure the connection exists, this is used to support lazy connect when using `new MikroORM()` instead of the async `init` method.
*/
ensureConnection(): Promise<void>;
/**
* Execute raw SQL queries, handy from running schema dump loaded from a file.
* This method doesn't support transactions, as opposed to `orm.schema.execute()`, which is used internally.
*/
executeDump(dump: string): Promise<void>;
protected onConnect(): Promise<void>;
/** Executes a callback inside a transaction, committing on success and rolling back on failure. */
transactional<T>(cb: (trx: Transaction) => Promise<T>, options?: {
isolationLevel?: IsolationLevel | `${IsolationLevel}`;
readOnly?: boolean;
ctx?: Transaction;
eventBroadcaster?: TransactionEventBroadcaster;
loggerContext?: LogContext;
}): Promise<T>;
/** Begins a new database transaction and returns the transaction context. */
begin(options?: {
isolationLevel?: IsolationLevel | `${IsolationLevel}`;
readOnly?: boolean;
ctx?: Transaction;
eventBroadcaster?: TransactionEventBroadcaster;
loggerContext?: LogContext;
}): Promise<Transaction>;
/** Commits the given transaction. */
commit(ctx: Transaction, eventBroadcaster?: TransactionEventBroadcaster, loggerContext?: LogContext): Promise<void>;
/** Rolls back the given transaction. */
rollback(ctx: Transaction, eventBroadcaster?: TransactionEventBroadcaster, loggerContext?: LogContext): Promise<void>;
/** Executes a raw query and returns the result. */
abstract execute<T>(query: string, params?: any[], method?: 'all' | 'get' | 'run', ctx?: Transaction): Promise<QueryResult<T> | any | any[]>;
/** @internal — public callers go through {@link EntityManager.callRoutine}. */
callRoutine<T>(routine: Routine, args: Record<string, unknown>, ctx?: Transaction): Promise<T>;
/**
* Unwraps a routine argument (resolving any `ScalarReference` wrapper) and, when the param
* declares a `customType`, marshals it through `convertToDatabaseValue`. `undefined` is
* normalised to `null` so every driver sees the same shape.
*
* @internal
*/
protected convertRoutineInbound(value: unknown, param: RoutineProperty | undefined): unknown;
/**
* Converts a raw database value to its JS representation via the supplied `customType`, when
* one is declared. Used to marshal scalar function returns and OUT/INOUT values back to the
* caller before they land in a `ScalarReference` or `em.callRoutine`'s return value.
*
* @internal
*/
protected convertRoutineOutbound<T>(value: unknown, customType: Type<unknown> | undefined): T;
/**
* Executes a scalar function routine as `select <qualified>(?, ?, ...) as value`, marshalling
* IN params on the way in and the return value on the way out. The qualified name is built
* from `routine.schema`, falling back to the platform's default schema (e.g. `dbo` on MSSQL),
* which gives MySQL/SQLite a bare name and MSSQL/Oracle the mandatory `schema.name` form.
*
* @internal
*/
protected callRoutineFunction<T>(routine: Routine, args: Record<string, unknown>, ctx?: Transaction): Promise<T>;
/**
* Walks a result row produced by an OUT/INOUT-param SELECT and writes each value into the
* caller's `ScalarReference` slot. Non-reference args are ignored (the user opted out of
* receiving the OUT value).
*
* @internal
*/
protected applyRoutineOutParams(row: Dictionary, outParams: RoutineProperty[], args: Record<string, unknown>): void;
/** Parses and returns the resolved connection configuration (host, port, user, etc.). */
getConnectionOptions(): ConnectionConfig;
/** Sets the metadata storage on this connection. */
setMetadata(metadata: MetadataStorage): void;
/** Sets the platform abstraction on this connection. */
setPlatform(platform: Platform): void;
/** Returns the platform abstraction for this connection. */
getPlatform(): Platform;
protected executeQuery<T>(query: string, cb: () => Promise<T>, context?: LogContext): Promise<T>;
protected logQuery(query: string, context?: LogContext): void;
}
/** Result of a native database query (insert, update, delete). */
export interface QueryResult<T = {
id: number;
}> {
affectedRows: number;
insertId: Primary<T>;
row?: Dictionary;
rows?: Dictionary[];
insertedIds?: Primary<T>[];
}
/** Resolved database connection parameters. */
export interface ConnectionConfig {
host?: string;
port?: number;
user?: string;
password?: string | (() => MaybePromise<string>);
database?: string;
schema?: string;
}
/** Opaque transaction context type, wrapping the driver-specific transaction object. */
export type Transaction<T = any> = T & {};
/**
* 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.
*/
export type InflightQueryAbortStrategy = 'ignore query' | 'cancel query' | 'kill session';
/** Per-query cancellation controls forwarded to the underlying driver. */
export interface AbortQueryOptions {
/** AbortSignal that cancels the query when fired. */
signal?: AbortSignal;
/**
* Strategy used when the signal fires while the query is in flight. See
* {@apilink InflightQueryAbortStrategy} for caveats around streams and MongoDB.
*/
inflightQueryAbortStrategy?: InflightQueryAbortStrategy;
}