我正在構建一個使用 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) => {})
打字機可以嗎?
謝謝
uj5u.com熱心網友回復:
按照您的代碼撰寫方式,事務提交只會在插入完成后發生。這意味著,此時您還可以執行新查詢。您不一定需要回呼,因為您使用的是 async/await 語法。
但是,對于非常大的插入,似乎發生了一些錯誤(某種查詢/連接超時,或服務器資源失敗)。嘗試除錯/列印錯誤以查看實際發生的情況。
我建議您嘗試將插入拆分為多個批次(例如 1k 條記錄)。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/364926.html
標籤:sql PostgreSQL的 嵌套 打字机 node.js-typeorm
