gpt4 book ai didi

PG-Promise - 两个数据库的事务逻辑

转载 作者:行者123 更新时间:2023-12-04 07:54:34 25 4
gpt4 key购买 nike

如何使用 PG-Promise 在两个不同的数据库之间分配事务?提交或回滚应该应用于两个数据库,如果一个失败,另一个应该恢复更改
我一直在使用这样的东西,但我不确定它是否有效:

try {
await firstDb.tx(async (firstDbTask) => {
await secondDb.tx(async (secondDbTask) => {
// second db stuff
})
// first db stuff
});

return true;
} catch (err) {
return err;
}

最佳答案

为多个数据库同步事务逻辑并非易事,但可行。解决方案基本上都是关于正确使用 promise 的,没有太多其他的......
我们使我们的多数据库事务通过外部 promise 公开其最终的内部状态,因此我们可以将事务结果与该状态交叉对齐:

let firstTx, secondTx;

firstTx = new Promise((resolve, reject) => {
firstDb.tx(async t => {
// do your queries here first...

// success, signal after all the queries:
resolve(/*null or whatever data*/);

// Align COMMIT-ROLLBACK logic with the other transaction:
await secondTx;
}).catch(reject);
});

secondTx = new Promise((resolve, reject) => {
secondDb.tx(async t => {
// do your queries here first...

// success, signal at the end:
resolve(/*null or whatever data*/);

// Align COMMIT-ROLLBACK logic with the other transaction:
await firstTx;
}).catch(reject);
});

await Promise.all([firstTx, secondTx]); // finish transactions logic
这种方法确保如果其中一个事务失败,两个事务都将回滚。和 COMMIT只能同时发生或不发生。

但是请注意,上面的解决方案与交易状态有关,即在我们调用 Promise.all 之后有点松散。在那里,两个事务都已完成其逻辑的执行,但结果 COMMIT/ ROLLBACK还没执行完。
如果您需要完全关闭两笔交易,您必须跟进单独的 await以结束实际交易,如下图:
let firstTx, secondTx, tx1, tx2;

firstTx = new Promise((resolve, reject) => {
tx1 = firstDb.tx(async t => {
// do your queries here first...

// success, signal after all the queries:
resolve(/*null or whatever data*/);

// Align COMMIT-ROLLBACK logic with the other transaction:
await secondTx;
}).catch(reject);
});

secondTx = new Promise((resolve, reject) => {
tx2 = secondDb.tx(async t => {
// do your queries here first...

// success, signal at the end:
resolve(/*null or whatever data*/);

// Align COMMIT-ROLLBACK logic with the other transaction:
await firstTx;
}).catch(reject);
});

await Promise.all([firstTx, secondTx]); // finish transactions logic

await Promise.all([tx1, tx2]); // finish transactions execution

// All COMMIT-s or ROLLBACK-s have been executed.
请注意,上述规定仅在两个事务都成功且 COMMIT 时才有意义。 .当任何一个失败时,第一个 await会抛出,所以第二个不会执行,这很重要,因为万一失败, tx1tx2可能仍然是 undefined .这就是为什么我们有两个独立的 await -s 到底在那里。

关于PG-Promise - 两个数据库的事务逻辑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66770440/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com