【问题标题】:TypeORM how to check if query execution finished?TypeORM如何检查查询执行是否完成?
【发布时间】:2022-01-02 03:05:21
【问题描述】:

我正在构建一个使用 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('raw_sql', (err, res) => {})queryRunner.query 进行一些回调

typeorm 可以吗?

谢谢

【问题讨论】:

    标签: sql postgresql nestjs typeorm node.js-typeorm


    【解决方案1】:

    按照您的代码编写方式,事务提交只会在插入完成后发生。这意味着,此时您还可以执行新查询。您不一定需要回调,因为您使用的是 async/await 语法。

    但是,对于非常大的插入,似乎发生了一些错误(某种查询/连接超时,或服务器资源失败)。尝试调试/打印错误,看看到底发生了什么。

    我建议您尝试将插入分成多个批次(例如 1k 条记录)。

    【讨论】:

    • 嗨。感谢您指出事务提交。这实际上听起来像是一个我可以执行新查询的好地方。是的。我将数据分成块。经过一些测试,我最终每个块有 50k 个条目是最佳的。 (通常传入的数据超过一百万)
    猜你喜欢
    • 1970-01-01
    • 2011-02-15
    • 1970-01-01
    • 2014-07-22
    • 1970-01-01
    • 1970-01-01
    • 2016-11-24
    • 1970-01-01
    • 2018-05-28
    相关资源
    最近更新 更多