gpt4 book ai didi

node.js - 具有延迟约束的 Postgres Sequelize 事务不起作用

转载 作者:行者123 更新时间:2023-12-03 22:23:21 25 4
gpt4 key购买 nike

目的:
我正在尝试在事务内的相关表中进行更改。

操作:
我已经更改了表中的约束以将它们设置为 DEFERRABLE INITIALLY DEFERRED 以便能够在事务内的引用表中提交。 Just like in this article.

所以在我的表中有两个 FK 约束:

Foreign-key constraints:
"updaters_features_updater_id_fkey" FOREIGN KEY (updater_id) REFERENCES updaters(id) ON UPDATE CASCADE ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED
"updaters_features_feature_id_fkey" FOREIGN KEY (feature_id) REFERENCES features(id) ON UPDATE CASCADE ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED

我开始交易:
sequelize.transaction({
deferrable: this.db.sequelize.Deferrable.SET_DEFERRED,
}, t => {
//insert into updates table
//insert into updates_features table
})

它生成下一个 SQL 查询:
START TRANSACTION;
SET CONSTRAINTS ALL DEFERRED
SET SESSION TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;
INSERT INTO "public"."updaters" ("id","description","is_full","created_at","updated_at","android_model_id","version_from_id","version_to_id") VALUES (DEFAULT,'Description',true,'2019-12-18 09:46:21.272 +00:00','2019-12-18 09:46:21.272 +00:00',1,31,32) RETURNING *;
INSERT INTO "public"."updaters_features" ("created_at","updated_at","feature_id","updater_id") VALUES ('2019-12-18 09:46:21.267 +00:00','2019-12-18 09:46:21.267 +00:00',3,280),('2019-12-18 09:46:21.267 +00:00','2019-12-18 09:46:21.267 +00:00',5,280);


它因违反外键约束而失败 Key (updater_id)=(280) is not present in table "updaters".
我找不到问题,最奇怪的是,如果我从控制台复制 SQL 查询并在 psql 中手动运行它 - 一切都很好,我可以提交事务。

我在 this question 中寻找,但我有不同的问题。

UPD(应用事务代码的JS):
await this.withTransation({
deferrable: this.db.sequelize.Deferrable.SET_DEFERRED,
}, async(transaction) => {
update = await this.dbModel.create({
version_from_id: body.buildFrom,
version_to_id: body.buildTo,
android_model_id: body.modelId,
description: body.description,
isFull: body.isFull,
}, {transaction});
await this.db.UpdatersGroups.bulkCreate(body.groupIds.map((groupId) => ({
feature_id: groupId,
updater_id: update.id,
})));
});
withTransaction 是我的抽象,我确信它可以正常工作(只需在 sequelize 中创建非托管事务)

最佳答案

第二个查询不在事务上下文中执行,因此添加 transaction 应该会有所帮助:

...
await this.db.UpdatersGroups.bulkCreate(body.groupIds.map((groupId) => ({
feature_id: groupId,
updater_id: update.id,
}), { transaction })); // transaction here is applied.

关于node.js - 具有延迟约束的 Postgres Sequelize 事务不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59390570/

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