在禁用表上的触发器后,为什么外键处于活动状态?

时间:2017-10-31 21:39:12

标签: postgresql triggers foreign-keys truncate

我试图刷新其他数据引用的一些数据 - 我想截断并重新加载ms_automobile表,但是rm_automobile表有一个外键。

看起来像是'禁用触发器'语句正在运行(以postgres,超级用户身份运行):

mobilesurvey=# ALTER TABLE ms_automobile DISABLE TRIGGER ALL;
ALTER TABLE
mobilesurvey=# ALTER TABLE rm_automobile DISABLE TRIGGER ALL;
ALTER TABLE

但我无法截断ms_automobile表:

mobilesurvey=# TRUNCATE TABLE ms_automobile;
ERROR:  cannot truncate a table referenced in a foreign key constraint
DETAIL:  Table "rm_automobile" references "ms_automobile".
HINT:  Truncate table "rm_automobile" at the same time, or use TRUNCATE ... CASCADE.

同样,我不想丢失rm_automobile数据;在TRUNCATE之后我计划做一个包含丢失的ms_automobile数据的pg_restore。

如果可能的话,我想禁用而不是删除约束 - 它们中有更多,并且维护禁用/启用似乎比维护丢弃/添加更不容易出错。

那么,我怎么能在这里实际禁用外键呢?

1 个答案:

答案 0 :(得分:0)

禁用触发器可以按预期在DELETE上运行(而不是在TRUNCATE上)。

DELETE FROM ms_automobile;

TRUNCATE以与INSERT / UPDATE / DELETE不同的特定方式实现。它没有使用触发器,但在执行之前检查一次参照完整性。