TypeORM中文文档 v1.1
迁移 / 伪造迁移与回滚
GitHub

伪造迁移与回滚

Faking Migrations and Rollbacks 英文原文 Markdown

你也可以用 --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 标志完全不使用事务包裹迁移。

除了这些标志,你还可以通过把 MigrationInterface 上的 transaction 属性设为 true 或 false,按单个迁移覆盖事务行为。这只在 each 或 none 事务模式下有效。

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