Search code examples
nestjstypeormnestjs-typeorm

How to rollback(execute down) in TypeORM migration automatically in case of error?


We are using TypeORM migrations in one of our NestJS projects. Following is the example format of migration script that we are using.

import {MigrationInterface, QueryRunner} from "typeorm";

export class VMTestTableTwo1713851442445 implements MigrationInterface {

    public async up(queryRunner: QueryRunner): Promise<void> {

      await queryRunner.query(`
        CREATE TABLE "vm_test"(
          "aggregate_id" uuid NOT NULL
        );
      `);
    }

    public async down(queryRunner: QueryRunner): Promise<void> {
      await queryRunner.query(`
        DROP TABLE IF EXISTS "vm_test";
      `);
    }
}

If a up script fails, ideally the down should get executed automatically. But, this is not the case with TypeORM migration. If I am not wrong, Sequelize migration works that way. How to achieve this in TypeORM migration?

UPDATE:

export default TypeOrmModule.forRootAsync({
  useFactory: (config: ConfigService) => {
    return {
      type: 'postgres',
      host: <host>,
      port: <port>,
      username: <username>,
      password: <pwd>,
      database: <db>,
      synchronize: false,
      logging: EnvChecker.queryLogger() ? ['query', 'error'] : false,
      migrationsRun: true,
      migrations: [
        `${__dirname}/../migrations/*{.ts,.js}`
      ],
      autoLoadEntities: true,
      entities: [
        `${__dirname}/../**/domain/entities/*.entity{.ts,.js}`
      ],
      extra: {
        max: <maxPool>,
        connectionTimeoutMillis: <connectionTimeoutMillis>,
        idleTimeoutMillis: <config.get('idleTimeoutMillis')>
      },
      migrationsTransactionMode: 'each'
    };
  },
  inject: [ConfigService]
});

Solution

  • Your migrations will be executed in a transaction, so if something fail the transaction will not be committed and it will be rollback automatically without using your down.

    Your down is not here to rollback in case of error but to allow you to revert your modifications later on. For example, if you change your mind or if you switch to another branch where the migration should not apply.

    More on how transactions are used by TypeORM: https://orkhan.gitbook.io/typeorm/docs/migrations#transaction-modes