import type { MigrationsOptions, Transaction } from '@mikro-orm/core'; import type { MongoDriver, MongoConnection } from '@mikro-orm/mongodb'; import type { Migration } from './Migration.js'; import { rejectRuntimeSchema } from './typings.js'; /** Executes individual MongoDB migration files within optional transaction contexts. */ export class MigrationRunner { private readonly connection: MongoConnection; private masterTransaction?: Transaction; constructor( protected readonly driver: MongoDriver, protected readonly options: MigrationsOptions, ) { this.connection = this.driver.getConnection(); } async run( migration: Migration, method: 'up' | 'down', afterRun?: (tx?: Transaction) => Promise, ): Promise { migration.reset(); if (!this.options.transactional || !migration.isTransactional()) { await migration[method](); await afterRun?.(); } else if (this.masterTransaction) { migration.setTransactionContext(this.masterTransaction); await migration[method](); await afterRun?.(this.masterTransaction); } else { await this.connection.transactional( async tx => { migration.setTransactionContext(tx); await migration[method](); await afterRun?.(tx); }, { ctx: this.masterTransaction }, ); } } setMasterMigration(trx: Transaction) { this.masterTransaction = trx; } unsetMasterMigration() { delete this.masterTransaction; } setRunSchema(schema?: string) { rejectRuntimeSchema(schema); } unsetRunSchema() { /* nothing to do */ } }