Postgresql – Is disabling triggers to disable foreign key constraints a good idea

foreign keypostgresqltrigger

Background

We're moving a legacy application from a non-relational database to PostgreSQL.

Problem

We'd like to enable foreign keys on a lot of fields for future data integrity and so that reporting tools can easily determine which tables are linked. Some of the current data won't pass the FK check and because of the legacy app connecting to the database we can't turn on the FKs yet.

Temporary Solution

Some of the programmers are suggesting that we disable triggers on the database as shown here so that the FKs aren't enforced but will still be there for reporting tools.

Question

I'm afraid that this will cause a bunch of other un-intended consequences but I'm not sure what they are. Can anyone put my fears to rest or explain why this is a really bad idea? I'm assuming that one reason it is bad is that it would disable all triggers not just triggers that fire the FK constraints.

Best Answer

You can create the foreign key constraints with the option NOT VALID. Then they are declared, but are not enforced:

create table parent (id integer primary key);
create table child (id integer primary key, pid integer);

insert into parent values (1),(2),(3);
insert into child values (1,100),(2,200),(3,300); --<< invalid pid values!

alter table child 
     add constraint fk_child_parent 
     foreign key (pid) references p (id) NOT VALID; --<< succeeds