Typeorm 迁移无法正确检测更改

nim*_*loo 5 postgresql typescript typeorm nestjs

我在使用 postgresql 数据库的 Nestjs 应用程序中使用 typeorm。当我尝试创建迁移以同步数据库以应用应用程序更改时,生成的迁移文件中始终存在以下查询(我删除了一些不必要的查询以提高可读性):

export class portal1631976435381 implements MigrationInterface {
    name = 'portal1631976435381'

    public async up(queryRunner: QueryRunner): Promise<void> {
        await queryRunner.query(`ALTER TABLE "organization" DROP COLUMN "isTransporter"`);
        await queryRunner.query(`ALTER TABLE "organization" DROP COLUMN "crmId"`);
        await queryRunner.query(`ALTER TABLE "organization" DROP COLUMN "telephoneNumber"`);
        await queryRunner.query(`ALTER TABLE "organization" ADD "crmId" character varying`);
        await queryRunner.query(`ALTER TABLE "organization" ADD "telephoneNumber" character varying`);
        await queryRunner.query(`ALTER TABLE "organization" ADD "isTransporter" boolean NOT NULL DEFAULT false`);
        await queryRunner.query(`CREATE VIEW "inventory_based_on_receipt_item_view" AS SELECT "ri"."id" AS "receiptItemId" from someTableC`);
        await queryRunner.query(`INSERT INTO "typeorm_metadata"("type", "schema", "name", "value") VALUES ($1, $2, $3, $4)`, ["VIEW","public","inventory_based_on_receipt_item_view",]);
        await queryRunner.query(`CREATE VIEW "inventory_based_on_receipt_item_view" AS SELECT "ri"."id" AS "receiptItemId" from someTableB`);
        await queryRunner.query(`INSERT INTO "typeorm_metadata"("type", "schema", "name", "value") VALUES ($1, $2, $3, $4)`, ["VIEW","public","inventory_based_on_receipt_item_view",]);
        await queryRunner.query(`CREATE VIEW "receipt_item_transaction_view" AS SELECT "ri"."id" AS "receiptItemId" from someTableA`)
        await queryRunner.query(`INSERT INTO "typeorm_metadata"("type", "schema", "name", "value") VALUES ($1, $2, $3, $4)`, ["VIEW","public",...]);
    }
    public async down(queryRunner: QueryRunner): Promise<void> { ... }
}
Run Code Online (Sandbox Code Playgroud)

无论应用程序发生什么更改,所有 viewEntities 都会被删除并重新创建。

另一个问题是,inventory_based_on_receipt_item_view尽管我只有一个具有该名称的 viewEntity (我真的不知道它来自哪里),但在查询中使用 2 个略有不同的查询创建了两次。另一个问题是组织表的 3 列(crmIdtelephoneNumberisTransporter)被删除并以相同的详细信息重新创建。

我想知道是否有更好的方法来迁移数据库表,也许使用另一个包(我自己找不到任何有用的东西)或任何可以优化我的工作流程的解决方法?因为每当实体发生任何更改时,我都需要重新生成迁移文件,并确保删除生成的每个错误查询。

nim*_*loo 6

我发现了问题。执行迁移脚本时,它会在迁移文件夹中创建迁移 ts 文件,但 dist 文件夹中先前的迁移文件存在。因此,新的迁移文件将附加到 dist 文件夹中现有的迁移文件中。

在运行之前删除 dist 文件夹migration:generate可以解决问题。