node.js - TypeORM 和 PostgreSQL 死鎖
我有這段程式碼,它會輸出一個錯誤:
UnhandledPromiseRejectionWarning: QueryRunnerAlreadyReleasedError: 查詢執行器已經釋放。無法再執行查詢。
來電者
const res = await getManager().transaction(async entityManager => {
return ServiceA.method1(entityManager);
});
服務 A
static async method1(entityManager: EntityManager) {
const deleteResult = await entityManager //changing this line to getManager() fixes the issue, but in other situations it still comes back
.createQueryBuilder()
.setLock('pessimistic_write')
.delete()
.from(MyEntity)
.where('relate = :id', { id: some id })
.execute();
await ServiceB.method1({
...
entityManager: entityManager
});
await ServiceB.method2({
...
entityManager: entityManager
});
return true;
}
服務 B
static async method1(params: {
...
entityManager: EntityManager;
}) {
let lockedEntityOne = await EntityOneDao.getAndLock(..., params.entityManager);
if (!lockedEntityOne) throw new Error('not found');
//modify lockedEntityOne
const aNewRelatedEntityOne = await this._createANewRelatedEntityOne()
await params.entityManager.save([lockedEntityOne, aNewRelatedEntityOne]);
return lockedEntityOne;
}
static async method2(params: {
...
entityManager: EntityManager;
}) {
let lockedEntityTwo = await EntityTwoDao.getAndLock(..., params.entityManager);
if (!lockedEntityTwo) throw new Error('not found');
//modify lockedEntityTwo
const aNewRelatedEntityTwo = await this._createANewRelatedEntityTwo()
await params.entityManager.save([lockedEntityTwo, aNewRelatedEntityTwo]); //where the above error is thrown
return lockedEntityTwo;
}
在 Service A 中,如果我將使用傳入的 entityManager 的那一行改成從 'typeorm' 套件匯入的 getManager(),那麼該特定情況就解決了。然而在其他情況下問題又會再出現。我知道這有點多,但我在想四處傳遞 entityManager 來重複使用它是否是一個壞主意。任何幫助都非常感謝。
編輯 1
我已經從實體中移除了所有「pessimistic_write」鎖,但問題仍然存在。我仍然不明白為什麼使用新的管理器可以解決這個特定情況,而在其他情況下卻會出現相同的錯誤。