174

I'm creating a lot of migrations that have foreign keys in PostgreSQL 9.4.

This is creating a headache because the tables must all be in the exact order expected by the foreign keys when they are migrated. It gets even stickier if I have to run migrations from other packages that my new migrations depend on for a foreign key.

In MySQL, I can simplify this by simply adding SET FOREIGN_KEY_CHECKS = 0; to the top of my migration file. How can I do this temporarily in PostgresSQL only for the length of the migration code?

BTW, using the Laravel Schema Builder for this.

2 Answers 2

304

For migration, it is easier to disable all triggers with:

SET session_replication_role = 'replica';

And after migration reenable all with

SET session_replication_role = 'origin';
13
  • 6
    Holy cow, is this both more simple and more appropriate for the specific task at hand. (Yes.)
    – ijoseph
    Jul 10, 2018 at 18:20
  • 20
    Word of caution: this requires superuser privileges. Try "SET CONSTRAINTS ALL DEFERRED".
    – JJC
    Jul 19, 2018 at 22:49
  • 21
    I'm on 10.4 and this above statement doesn't seem to work.
    – Stephane
    Oct 25, 2018 at 13:12
  • 4
    Would somebody be able to outline the dangers/risks of this method and in what scenarios it should be used and how to mitigate risks? What is best practice if this is considered a poor practice?
    – karns
    Jan 21, 2020 at 20:24
  • 14
    Btw, this parameter can be set in AWS RDS in the database parameter group and applied without restarting the db! Very useful if you're using DMS into an empty db with existing schema and constraints created.
    – Mike Atlas
    Mar 24, 2020 at 21:42
127

PostgreSQL doesn't support any configuration option, but there is another possibility.

postgres=# \d b
        Table "public.b"
┌────────┬─────────┬───────────┐
│ Column │  Type   │ Modifiers │
╞════════╪═════════╪═══════════╡
│ id     │ integer │           │
└────────┴─────────┴───────────┘
Foreign-key constraints:
    "b_id_fkey" FOREIGN KEY (id) REFERENCES a(id) DEFERRABLE

The referential integrity in Postgres is implemented by triggers, and you can disable triggers on table. With this method you can upload any data (risk), but it is significantly faster - because the check over large data is expensive. And if your upload is safe, then you can do it.

BEGIN;
ALTER TABLE b DISABLE TRIGGER ALL;
-- now the RI over table b is disabled
ALTER TABLE b ENABLE TRIGGER ALL;
COMMIT;

Next possibility is using deferred constraints. This move constraint check to commit time. So you should not to respect order with INSERT commands:

ALTER TABLE b ALTER CONSTRAINT b_id_fkey DEFERRABLE;

BEGIN
postgres=# SET CONSTRAINTS b_id_fkey DEFERRED;
SET CONSTRAINTS
postgres=# INSERT INTO b VALUES(100); -- this is not in a table
INSERT 0 1
postgres=# INSERT INTO b VALUES(10);
INSERT 0 1 
postgres=# COMMIT;
ERROR:  insert or update on table "b" violates foreign key constraint "b_id_fkey"
DETAIL:  Key (id)=(100) is not present in table "a".

This method should be preferred for you, because the inserted data will be checked.

6
  • 5
    For some reason, this worked once for me and then not at all. I'm in aws aurora postgres, where they lock down the super user role so customers can't mess up the replication settings. It looks like I have to be a super user to disable some system triggers. (I'm currently using my admin account that is also the owner-- I'm not sure why it worked once.) Setting the replication option is also not a viable option, as that also requires the super user role. My only option seems to be dropping and recreating the foreign keys...
    – ps2goat
    Dec 18, 2018 at 18:35
  • 4
    Same here. Doing DISABLE TRIGGER ALL thing, but it has no effect. I don't even get any warning. It's just ignored.
    – jayarjo
    May 26, 2020 at 13:00
  • 4
    On Amazon RDS, this gives the following error: > permission denied: "RI_ConstraintTrigger_a_23031" is a system trigger so this recipe is not for every case, unfortunately :)
    – kolypto
    Jun 18, 2020 at 8:59
  • 2
    Error on local db too. With user having all privileges to database, got **permission denied: "RI_ConstraintTrigger_a_16564" is a system trigger ** Nov 26, 2020 at 11:33
  • 1
    @otocan - no, not yet. The performance is same. Theoretically it can be implemented differently, but nobody did this work. Apr 26, 2021 at 19:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.