简体   繁体   中英

Can I get all foreign key violations in postgres?

I have a table with two columns with foreign key constraints, for example:

CREATE TABLE example
(
  id integer PRIMARY KEY,
  f1 integer REFERENCES example(id),
  f2 integer REFERENCES example(id)
);

If I then perform the insert:

insert into example (id, f1, f2) values (1, 2, 2);

I will obviously get an error, but only for the first failed constraint:

ERROR:  insert or update on table "example" violates foreign key constraint "example_f1_fkey"
DETAIL:  Key (f1)=(2) is not present in table "example".

My question is: Is it possible to configure postgres so it returns an error with both of the failed key constraints?

Thanks very much, Ben

Is it possible to configure postgres so it returns an error with both of the failed key constraints?

No, it isn't. The first FK failure aborts the transaction so no further checks are run.

It would be interesting to be able to capture all violations but there's no way to do that in current versions (true in 9.3, at least).

To do it you'd need to be able to selectively change ERROR level reports for CHECK constraints, foreign key constraint checks, etc into WARNING s that also set a flag that'd force the transaction to abort at the end of the current statement. That might not be too hard to do technically, but it's certainly going to involve a chunk of work on the PostgreSQL source code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM