TypeORM迁移出错时如何自动回滚(向下执行)?

问题描述 投票:0回答:1

我们正在我们的一个 NestJS 项目中使用 TypeORM 迁移。 以下是我们正在使用的迁移脚本的示例格式。

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";
      `);
    }
}

如果向上脚本失败,理想情况下应该自动执行向下脚本。但是,TypeORM 迁移的情况并非如此。如果我没记错的话,Sequelize 迁移就是这样工作的。 在 TypeORM 迁移中如何实现这一点?

更新:

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]
});
nestjs typeorm nestjs-typeorm
1个回答
1
投票

您的迁移将在事务中执行,因此如果出现故障,事务将不会被提交,并且会自动回滚而不使用您的

down

您的

down
不是为了在出现错误时回滚,而是为了允许您稍后恢复修改。例如,如果您改变主意或者切换到不应应用迁移的另一个分支。

有关 TypeORM 如何使用事务的更多信息:https://orkhan.gitbook.io/typeorm/docs/migrations#transaction-modes

© www.soinside.com 2019 - 2024. All rights reserved.