我目前正在使用 TypeORM 和 PostgreSQL 开发 Node.js 项目。我有多个迁移文件,但我只想运行一个特定的迁移文件,而不是所有待处理的迁移。以下是我的设置的详细信息:
数据源配置(db.ts):
import "dotenv/config";
import { DataSource } from "typeorm";
import { Dog } from "@modules/dog/entities/dog";
import { Breed } from "@modules/breed/entities/breed";
import { Color } from "@modules/color/entities/color";
export const AppDataSource = new DataSource({
type: "postgres",
host: process.env.HOST,
port: 5432,
username: process.env.DB_USERNAME,
password: process.env.PASSWORD,
database: process.env.DATABASE,
entities: [Dog, Breed, Color],
synchronize: false,
logging: true,
migrationsTableName: "migrations",
migrations: ["./src/migrations/*.ts"],
});
package.json中的脚本:
"scripts": {
"start": "nodemon --watch src --exec ts-node -r tsconfig-paths/register src/server.ts",
"migration:generate": "ts-node -r tsconfig-paths/register ./node_modules/typeorm/cli.js migration:generate -d src/config/db.ts src/migrations/",
"migration:run": "ts-node -r tsconfig-paths/register ./node_modules/typeorm/cli.js migration:run -d=src/config/db.ts",
"migration:revert": "ts-node -r tsconfig-paths/register ./node_modules/typeorm/cli.js migration:revert -d=src/config/db.ts"
}
迁移文件:
import { MigrationInterface, QueryRunner } from "typeorm";
export class Dogrename1721198056227 implements MigrationInterface {
name = 'Dogrename1721198056227'
public async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(`ALTER TABLE "dog" RENAME COLUMN "name" TO "dog_name"`);
}
public async down(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(`ALTER TABLE "dog" RENAME COLUMN "dog_name" TO "name"`);
}
}
import { MigrationInterface, QueryRunner } from "typeorm";
export class BreedRename1721198576725 implements MigrationInterface {
name = 'BreedRename1721198576725'
public async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(`ALTER TABLE "breed" RENAME COLUMN "name" TO "breed_name"`);
}
public async down(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(`ALTER TABLE "breed" RENAME COLUMN "breed_name" TO "name"`);
}
}
如何只运行一个特定的迁移文件,例如 Dogrename1721198056227.ts,而不运行所有待处理的迁移?有没有办法使用 TypeORM 来实现这一点?
我尝试过的:
npm run migration:run
但是,此命令会运行所有挂起的迁移。我只需要执行一项特定的迁移。
其他背景:
迁移机制对此没有规定,需要“打破”: 选项 1:将不应执行的迁移添加到“迁移”表中。但是回滚迁移的时候就会出现问题。 或者 选项 2:重命名不适当的迁移文件,使它们与模式
./src/migrations/*.ts
不匹配。
之后你就可以运行npm run migration:run
。