考虑以下内容,在两个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
命令阻止了随后的查询。
我的直觉是,这两个语句都包装在迁移框架提供的事务中
解决此问题的最佳方法是什么。
谢谢!
答案 0 :(得分:0)
弄清楚:
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")`
);
}
请注意,await queryRunner.query(
START TRANSACTION );
包装了ALTER TABLE命令
为我们创建了子交易。注意-这可能仅适用于postgreSQL