【问题标题】:Will a constraint be applied between two statements during a transaction?在事务期间是否会在两个语句之间应用约束?
【发布时间】:2017-12-29 18:06:58
【问题描述】:

我有一个配置,thing 可以有多个属性,property 可以属于多个事物:

CREATE TABLE thing (
  id integer NOT NULL,
  PRIMARY KEY (id)
);

CREATE TABLE property (
  id integer NOT NULL,
  PRIMARY KEY (id)
);

CREATE TABLE thingproperty (
    thing integer NOT NULL,
    property integer NOT NULL
);

ALTER TABLE thingproperty
ADD CONSTRAINT tp_thing
FOREIGN KEY (thing) REFERENCES thing(id)
ON UPDATE CASCADE ON DELETE CASCADE;

ALTER TABLE thingproperty
ADD CONSTRAINT tp_property
FOREIGN KEY (property) REFERENCES property(id)
ON UPDATE CASCADE ON DELETE CASCADE;

我想确保 property 仅在它属于至少一个 thing 时才能存在,为此我编写了这个删除事物的事务(必要时还删除属性),但我没有不知道对不对:

START TRANSACTION;
DELETE FROM thing ... ;
DELETE FROM property
WHERE id NOT IN (
  SELECT property
  FROM thingproperty
);
COMMIT TRANSACTION;

所以我基本上相信在DELETE FROM thing ... 查询运行后的引擎,它立即应用tp_thing 约束并删除thingproperty 在@ 之前属于已删除thing(s) 的记录987654331@被执行。

这是一种安全的方法吗?

【问题讨论】:

    标签: sql postgresql many-to-many constraints cascading-deletes


    【解决方案1】:

    默认情况下,约束在事务中的每个命令之后立即应用。您可以(在这种情况下您不想)更改此行为,将约束声明为可延迟。在the documentation.中阅读有关可延迟约束的更多信息

    可延期

    不可延期

    这控制是否可以延迟约束。在每个命令之后将立即检查不可延迟的约束。 (...)

    【讨论】:

      猜你喜欢
      • 2011-02-20
      • 2020-07-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多