伪造迁移与回滚
你也可以用 --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`)
}
}You can also fake run a migration using the --fake flag (-f for short). This will add the migration to the migrations table without running it. This is useful for migrations created after manual changes have already been made to the database or when migrations have been run externally (e.g. by another tool or application), and you still would like to keep a consistent migration history.
typeorm migration:run -d path-to-datasource-config --fakeThis is also possible with rollbacks.
typeorm migration:revert -d path-to-datasource-config --fakeTransaction modes
By default, TypeORM will run all your migrations within a single wrapping transaction. This corresponds to the --transaction all flag. If you require more fine grained transaction control, you can use the --transaction each flag to wrap every migration individually, or the --transaction none flag to opt out of wrapping the migrations in transactions altogether.
In addition to these flags, you can also override the transaction behavior on a per-migration basis by setting the transaction property on the MigrationInterface to true or false. This only works in the each or none transaction mode.
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`)
}
}