TypeORM 如何檢查查詢執行是否完成?

月見3

我正在構建一個使用 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) => {})

打字機可以嗎?

謝謝

迪奧戈·西蒙斯

按照您的代碼編寫方式,事務提交只會在插入完成後發生。這意味著,此時您還可以執行新查詢。您不一定需要回調,因為您使用的是 async/await 語法。

但是,對於非常大的插入,似乎發生了一些錯誤(某種查詢/連接超時,或服務器資源失敗)。嘗試調試/打印錯誤以查看實際發生的情況。

我建議您嘗試將插入拆分為多個批次(例如 1k 條記錄)。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章