TypeORM 如何检查查询执行是否完成?
TypeORM how to check if query execution finished?
我正在构建一个使用 typeorm 与 postgres 通信的 nestjs 应用程序。
我的表是动态创建的,数据也是动态插入的。这就是我使用原始查询而不是实体的原因。
问题是表中的某些数据是相关的,除非之前的插入查询完成,否则我无法插入新数据。
如何检查查询执行是否完成?
这是我使用的工作流程示例。它适用于小数据但无法处理大数据(10 000 000 个条目及更多)
export class Test {
constructor(
private readonly connection: Connection;
) {}
public async insertData(table1, table2, arr1, arr2) {
await insertInto(table1, arr1);
//I want second insertInto() to be executed after I get confirmation from database that insertInto() from above is finished
await insertInto(table2, arr2);
}
private async insertInto(table, data) {
const queryRunner = this.connection.createQueryRunner();
await queryRunner.connect();
await queryRunner.startTransaction();
const preparedData = [];
//prepare data to be inserted as raw query
//...
try {
await queryRunner.query(`INSERT INTO "${table}" VALUES ${preparedData}`);
await queryRunner.commitTransaction();
} catch (e) {
await queryRunner.rollbackTransaction();
throw new InternalServerErrorException(e, Error while executing custom query. Rollback transaction.)
} finally {
await queryRunner.release();
}
}
}
想要的结果是像这样 queryRunner.query
有一些回调 queryRunner.query('raw_sql', (err, res) => {})
typeorm 可以吗?
谢谢
按照您编写代码的方式,事务提交只会在插入完成后发生。这意味着,此时您还可以执行新查询。您不一定需要回调,因为您使用的是 async/await 语法。
但是,对于非常大的插入,似乎出现了错误(某种 query/connection 超时,或服务器资源失败)。尝试 debugging/printing 错误以查看实际情况。
我建议您尝试将插入分成多批(例如 1k 条记录)。
我正在构建一个使用 typeorm 与 postgres 通信的 nestjs 应用程序。
我的表是动态创建的,数据也是动态插入的。这就是我使用原始查询而不是实体的原因。
问题是表中的某些数据是相关的,除非之前的插入查询完成,否则我无法插入新数据。
如何检查查询执行是否完成? 这是我使用的工作流程示例。它适用于小数据但无法处理大数据(10 000 000 个条目及更多)
export class Test {
constructor(
private readonly connection: Connection;
) {}
public async insertData(table1, table2, arr1, arr2) {
await insertInto(table1, arr1);
//I want second insertInto() to be executed after I get confirmation from database that insertInto() from above is finished
await insertInto(table2, arr2);
}
private async insertInto(table, data) {
const queryRunner = this.connection.createQueryRunner();
await queryRunner.connect();
await queryRunner.startTransaction();
const preparedData = [];
//prepare data to be inserted as raw query
//...
try {
await queryRunner.query(`INSERT INTO "${table}" VALUES ${preparedData}`);
await queryRunner.commitTransaction();
} catch (e) {
await queryRunner.rollbackTransaction();
throw new InternalServerErrorException(e, Error while executing custom query. Rollback transaction.)
} finally {
await queryRunner.release();
}
}
}
想要的结果是像这样 queryRunner.query
有一些回调 queryRunner.query('raw_sql', (err, res) => {})
typeorm 可以吗?
谢谢
按照您编写代码的方式,事务提交只会在插入完成后发生。这意味着,此时您还可以执行新查询。您不一定需要回调,因为您使用的是 async/await 语法。
但是,对于非常大的插入,似乎出现了错误(某种 query/connection 超时,或服务器资源失败)。尝试 debugging/printing 错误以查看实际情况。
我建议您尝试将插入分成多批(例如 1k 条记录)。