手动创建
你可以通过 CLI 指定迁移的名称和位置来创建一个新迁移:
npx typeorm migration:create <path/to/migrations>/<migration-name>例如:
npx typeorm migration:create src/db/migrations/post-refactoring运行该命令后,你会在 src/db/migrations 目录下看到一个新生成的文件,名为 {TIMESTAMP}-post-refactoring.ts,其中 {TIMESTAMP} 是生成该迁移时的当前时间戳。
现在你可以打开这个文件,把迁移的 sql 查询加进去。你应该会在迁移文件中看到如下内容:
import { MigrationInterface, QueryRunner } from "typeorm"
export class PostRefactoringTIMESTAMP implements MigrationInterface {
async up(queryRunner: QueryRunner): Promise<void> {}
async down(queryRunner: QueryRunner): Promise<void> {}
}有两个方法必须填入你的迁移代码:up 和 down。up 要包含执行迁移所需的代码。down 要回滚 up 所做的一切。down 方法用于回滚最近一次迁移。
在 up 和 down 中你都有一个 QueryRunner 对象。所有数据库操作都通过这个对象执行。进一步了解 query runner。
我们来看看加上 Post 变更后的迁移长什么样:
import { MigrationInterface, QueryRunner } from "typeorm"
export class PostRefactoringTIMESTAMP implements MigrationInterface {
async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(
`ALTER TABLE "post" RENAME COLUMN "title" TO "name"`,
)
}
async down(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(
`ALTER TABLE "post" RENAME COLUMN "name" TO "title"`,
) // 回滚 "up" 方法中所做的改动
}
}You can create a new migration using CLI by specifying the name and location of the migration:
npx typeorm migration:create <path/to/migrations>/<migration-name>For example:
npx typeorm migration:create src/db/migrations/post-refactoringAfter you run the command you can see a new file generated in the src/db/migrations directory named {TIMESTAMP}-post-refactoring.ts where {TIMESTAMP} is the current timestamp when the migration was generated.
Now you can open the file and add your migration sql queries there. You should see the following content inside your migration:
import { MigrationInterface, QueryRunner } from "typeorm"
export class PostRefactoringTIMESTAMP implements MigrationInterface {
async up(queryRunner: QueryRunner): Promise<void> {}
async down(queryRunner: QueryRunner): Promise<void> {}
}There are two methods you must fill with your migration code: up and down. up has to contain the code you need to perform the migration. down has to revert whatever up changed. down method is used to revert the last migration.
Inside both up and down you have a QueryRunner object. All database operations are executed using this object. Learn more about query runner.
Let's see what the migration looks like with our Post changes:
import { MigrationInterface, QueryRunner } from "typeorm"
export class PostRefactoringTIMESTAMP implements MigrationInterface {
async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(
`ALTER TABLE "post" RENAME COLUMN "title" TO "name"`,
)
}
async down(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(
`ALTER TABLE "post" RENAME COLUMN "name" TO "title"`,
) // reverts things made in "up" method
}
}