跳至主内容区

模拟迁移与回滚

非官方测试版翻译

本页面由 PageTurner AI 翻译(测试版)。未经项目官方认可。 发现错误? 报告问题 →

可通过 --fake 标志(简写 -f)模拟运行迁移。该操作会将迁移记录添加到迁移表中但不实际执行,适用于以下场景:

  • 数据库已手动完成变更后补充迁移记录
  • 迁移由外部工具执行后仍需保持迁移历史完整性
typeorm migration:run -d path-to-datasource-config --fake

此机制同样适用于回滚操作。

typeorm migration:revert -d path-to-datasource-config --fake

事务模式配置

默认情况下,TypeORM 会在单个包裹事务中执行所有迁移(对应 --transaction all 模式)。如需精细控制事务:

  • 使用 --transaction each 为每个迁移单独创建事务
  • 使用 --transaction none 完全禁用事务包裹

eachnone 模式下,还可通过设置 MigrationInterface 上的 transaction 属性(true/false)单独覆盖事务行为。

import { MigrationInterface, QueryRunner } from "typeorm"

export class AddIndexTIMESTAMP implements MigrationInterface {
transaction = false

async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(
`CREATE INDEX CONCURRENTLY post_names_idx ON post(name)`,
)
}

async down(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(`DROP INDEX CONCURRENTLY post_names_idx`)
}
}