【问题标题】:With TypeORM migrations how to seed a column during a migration使用 TypeORM 迁移如何在迁移期间为列播种
【发布时间】:2018-10-19 15:26:10
【问题描述】:

考虑以下情况,在两个 queryRunner.query 命令之间,我想做一些逻辑来播种新列。

  public async up(queryRunner: QueryRunner): Promise<any> {
    await queryRunner.query(`ALTER TABLE "users" ADD "selectedNotebookId" uuid`);

    const userRepo = await queryRunner.connection.getRepository(User);

    const allUsers = await userRepo.find({
      where: {},
      relations: ['notebooks']
    });

    const bar = new ProgressBar(':bar', { total: allUsers.length });

    const promises: Promise<void>[] = allUsers.map((user: User) => {
      user.selectedNotebook = user.notebooks[0];
      return userRepo.save(user).then(() => {
        bar.tick();
      });
    });

    await Promise.all(promises);

    await queryRunner.query(
      `ALTER TABLE "users" ADD CONSTRAINT "UQ_df4319c3d54b91856514f0dbcb3" UNIQUE ("selectedNotebookId")`
    );
    await queryRunner.query(
      `ALTER TABLE "users" ADD CONSTRAINT "FK_df4319c3d54b91856514f0dbcb3" FOREIGN KEY ("selectedNotebookId") REFERENCES "notebook"("id")`
    );
  }

我遇到的问题是第一个 ALTER TABLE 命令阻止了后续查询。

我的直觉是,这两个语句都包含在迁移框架提供的事务中

解决此问题的最佳方法是什么。

谢谢!!

【问题讨论】:

    标签: javascript postgresql typeorm


    【解决方案1】:

    想办法:

      public async up(queryRunner: QueryRunner): Promise<any> {
        await queryRunner.query(`START TRANSACTION`);
        await queryRunner.query(`ALTER TABLE "users" ADD "selectedNotebookId" uuid`);
        await queryRunner.query(`COMMIT TRANSACTION`);
    
        const userRepo = await queryRunner.connection.getRepository(User);
    
        const allUsers = await userRepo.find({
          where: {},
          relations: ['notebooks']
        });
    
        const bar = new ProgressBar(':bar', { total: allUsers.length });
    
        const promises: Promise<void>[] = allUsers.map((user: User) => {
          user.selectedNotebook = user.notebooks[0];
          return userRepo.save(user).then(() => {
            bar.tick();
          });
        });
    
        await Promise.all(promises);
    
        await queryRunner.query(
          `ALTER TABLE "users" ADD CONSTRAINT "UQ_df4319c3d54b91856514f0dbcb3" UNIQUE ("selectedNotebookId")`
        );
        await queryRunner.query(
          `ALTER TABLE "users" ADD CONSTRAINT "FK_df4319c3d54b91856514f0dbcb3" FOREIGN KEY ("selectedNotebookId") REFERENCES "notebook"("id")`
        );
      }
    

    注意包装了 ALTER TABLE 命令的 await queryRunner.query(START TRANSACTION);

    为我们创建一个子事务。注意——这可能只适用于 postgreSQL

    【讨论】:

    • 对此的更新——在使用 typeorm 几年后——我发现这是一种反模式——所有像这样的迁移逻辑都应该用原始 sql 编写。主要原因是您的域主要更改并且您不想在旧迁移文件中维护类型
    猜你喜欢
    • 1970-01-01
    • 2020-06-16
    • 2021-05-23
    • 1970-01-01
    • 2017-04-11
    • 2021-10-08
    • 2019-11-17
    • 2022-12-11
    • 2022-07-25
    相关资源
    最近更新 更多