如何在 Postgres 转储文件中禁用外键约束?

Dav*_*ave 1 postgresql foreign-key insert dump

我正在使用 Postgres 9.5。我为我的三个表创建了一个 INSERT 转储文件。为了避免出现外键错误,我将以下内容添加到文件的顶部和底部(“...”是所有插入的位置)...

SET statement_timeout = 0;
SET lock_timeout = 0;
SET client_encoding = 'UTF8';
SET standard_conforming_strings = on;
SET check_function_bodies = false;
SET client_min_messages = warning;
SET row_security = off;

SET search_path = public, pg_catalog;
ALTER TABLE addresses DISABLE TRIGGER ALL;
ALTER TABLE table1 DISABLE TRIGGER ALL;
ALTER TABLE table2 DISABLE TRIGGER ALL;

…

ALTER TABLE addresses ENABLE TRIGGER ALL;
ALTER TABLE table1 ENABLE TRIGGER ALL;
ALTER TABLE table2 ENABLE TRIGGER ALL;
Run Code Online (Sandbox Code Playgroud)

但是,即使我运行这个文件,我也会收到类似的错误

ERROR:  insert or update on table "table2" violates foreign key constraint "fk_rails_ba656ceafa"
DETAIL:  Key (table1_id)=(f62c5fee-1031-4d5e-a084-9210f052a2d1) is not present in table "table1".
Run Code Online (Sandbox Code Playgroud)

尽管禁用了外键,但为什么我会收到这些错误,更重要的是,我该如何防止它们?我想插入所有数据,然后重新启用外键。

Eva*_*oll 8

我不确定发生了什么,但你肯定没有给我们足够的信息。ALTER TABLE DISABLE TRIGGER ALL禁用FOREIGN KEYS.

test=# CREATE TABLE table1 ( id serial PRIMARY KEY );
CREATE TABLE

test=# CREATE TABLE table2 ( fkey int REFERENCES table1(id) );
CREATE TABLE

test=# INSERT INTO table2 VALUES (1);
ERROR:  insert or update on table "table2" violates foreign key constraint "table2_fkey_fkey"
DETAIL:  Key (fkey)=(1) is not present in table "table1".

test=# ALTER TABLE table2 DISABLE TRIGGER ALL;
ALTER TABLE

test=# INSERT INTO table2 VALUES (1);
INSERT 0 1
Run Code Online (Sandbox Code Playgroud)

永远不会建议任何人DISABLE TRIGGERS,或者让他们NOT VALID。他们在那里确保数据完整性,即使在很短的时间内禁用它们也是灾难的秘诀,在我看来也是一种反模式。

只是pg_dumpall修剪掉你不需要的东西。