【发布时间】:2020-04-10 22:05:15
【问题描述】:
目的: 我正在尝试对事务内的相关表进行更改。
操作:
我已经更改了表中的约束以将它们设置为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 中创建非托管事务)
【问题讨论】:
-
第二个 INSERTION 使用硬编码的 FK
280。这有点奇怪。你能分享一个插入的JS代码吗? -
@AndreiPiatrou 当然。我已经更新了帖子。
标签: node.js postgresql transactions sequelize.js deferred