Fix self-referencing foreign keys with partitioned tables
authorAlvaro Herrera <alvherre@alvh.no-ip.org>
Fri, 7 Oct 2022 17:37:48 +0000 (19:37 +0200)
committerAlvaro Herrera <alvherre@alvh.no-ip.org>
Fri, 7 Oct 2022 17:37:48 +0000 (19:37 +0200)
commit614a406b4ff1b6f0f84b89fb56dca5175978177d
tree35393c6c149fd532b133c6a7597a642b56cb40ec
parent3edc71ec043865c735cc7cd67df1c0e211fa97dd
Fix self-referencing foreign keys with partitioned tables

There are a number of bugs in this area.  Two of them are fixed here,
namely:
1. get_relation_idx_constraint_oid does not restrict the type of
   constraint that's returned, so with sufficient bad luck it can
   return the OID of a foreign key constraint.  This has the effect that
   a primary key in a partition can end up as a child of a foreign key,
   which makes no sense (it needs to be the child of the equivalent
   primary key.)
   Change the API contract so that only index-backed constraints are
   returned, mimicking get_constraint_index().

2. Both CloneFkReferenced and CloneFkReferencing clone a
   self-referencing foreign key, so the partition ends up with
   a duplicate foreign key.  Change the former function to ignore such
   constraints.

Add some tests to verify that things are better now.  (However, these
new tests show some additional misbehavior that will be fixed later --
namely that there's a constraint marked NOT VALID.)

Backpatch to 12, where these constraints are possible at all.

Author: Jehan-Guillaume de Rorthais <jgdr@dalibo.com>
Discussion: https://postgr.es/m/20220603154232.1715b14c@karst
src/backend/catalog/pg_constraint.c
src/backend/commands/tablecmds.c
src/test/regress/expected/foreign_key.out
src/test/regress/sql/foreign_key.sql