Add support for NOT ENFORCED in foreign key constraints
authorPeter Eisentraut <peter@eisentraut.org>
Wed, 2 Apr 2025 11:30:13 +0000 (13:30 +0200)
committerPeter Eisentraut <peter@eisentraut.org>
Wed, 2 Apr 2025 11:36:44 +0000 (13:36 +0200)
commiteec0040c4bcd650993bb058ebdf61ab94171fda4
tree5b38744ff96722b149336728c50f0d973dc90bc8
parent327d987df1e72a9b146f312df0a5ed34ef148720
Add support for NOT ENFORCED in foreign key constraints

This expands the NOT ENFORCED constraint flag, previously only
supported for CHECK constraints (commit ca87c415e2f), to foreign key
constraints.

Normally, when a foreign key constraint is created on a table, action
and check triggers are added to maintain data integrity.  With this
patch, if a constraint is marked as NOT ENFORCED, integrity checks are
no longer required, making these triggers unnecessary.  Consequently,
when creating a NOT ENFORCED foreign key constraint, triggers will not
be created, and the constraint will be marked as NOT VALID.
Similarly, if an existing foreign key constraint is changed to NOT
ENFORCED, the associated triggers will be dropped, and the constraint
will also be marked as NOT VALID.  Conversely, if a NOT ENFORCED
foreign key constraint is changed to ENFORCED, the necessary triggers
will be created, and the will be changed to VALID by performing
necessary validation.

Since not-enforced foreign key constraints have no triggers, the
shortcut used for example in psql and pg_dump to skip looking for
foreign keys if the relation is known not to have triggers no longer
applies.  (It already didn't work for partitioned tables.)

Author: Amul Sul <sulamul@gmail.com>
Reviewed-by: Joel Jacobson <joel@compiler.org>
Reviewed-by: Andrew Dunstan <andrew@dunslane.net>
Reviewed-by: Peter Eisentraut <peter@eisentraut.org>
Reviewed-by: jian he <jian.universality@gmail.com>
Reviewed-by: Alvaro Herrera <alvherre@alvh.no-ip.org>
Reviewed-by: Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>
Reviewed-by: Isaac Morland <isaac.morland@gmail.com>
Reviewed-by: Alexandra Wang <alexandra.wang.oss@gmail.com>
Tested-by: Triveni N <triveni.n@enterprisedb.com>
Discussion: https://www.postgresql.org/message-id/flat/CAAJ_b962c5AcYW9KUt_R_ER5qs3fUGbe4az-SP-vuwPS-w-AGA@mail.gmail.com
19 files changed:
doc/src/sgml/catalogs.sgml
doc/src/sgml/ref/alter_table.sgml
doc/src/sgml/ref/create_table.sgml
src/backend/catalog/pg_constraint.c
src/backend/catalog/sql_features.txt
src/backend/commands/tablecmds.c
src/backend/optimizer/util/plancat.c
src/backend/parser/gram.y
src/backend/parser/parse_utilcmd.c
src/backend/utils/cache/relcache.c
src/bin/pg_dump/pg_dump.c
src/bin/psql/describe.c
src/include/nodes/parsenodes.h
src/include/utils/rel.h
src/test/regress/expected/constraints.out
src/test/regress/expected/foreign_key.out
src/test/regress/expected/inherit.out
src/test/regress/sql/foreign_key.sql
src/test/regress/sql/inherit.sql