Fix ALTER TABLE DETACH for inconsistent indexes
authorAlvaro Herrera
Fri, 12 Jul 2024 10:54:01 +0000 (12:54 +0200)
committerAlvaro Herrera
Fri, 12 Jul 2024 10:54:01 +0000 (12:54 +0200)
commit30ca4e1ab1ffc1d7c4d5fe4afc800d946a585d96
tree8a50237baa70ff7104489bb6886aff15f4933bb3
parentae4e072bad5ff254a4fcfe876aae849acdaf8c3d
Fix ALTER TABLE DETACH for inconsistent indexes

When a partitioned table has an index that doesn't support a constraint,
but a partition has an equivalent index that does, then a DETACH
operation would misbehave: a crash in assertion-enabled systems (because
we fail to find the constraint in the parent that we expect to), or a
broken coninhcount value (-1) in production systems (because we blindly
believe that we've successfully detached the parent).

While we should reject an ATTACH of a partition with such an index, we
have failed to do so in existing releases, so adding an error in stable
releases might break the (unlikely) existing applications that rely on
this behavior.  At this point I don't even want to reject them in
master, because it'd break pg_upgrade if such databases exist, and there
would be no easy way to fix existing databases without expensive index
rebuilds.

(Later on we could add ALTER TABLE ... ADD CONSTRAINT USING INDEX to
partitioned tables, which would allow the user to fix such patterns.  At
that point we could add more restrictions to prevent the problem from
its root.)

Also, add a test case that leaves one table in this condition, so that
we can verify that pg_upgrade continues to work if we later decide to
change the policy on the master branch.

Backpatch to all supported branches.

Co-authored-by: Tender Wang
Reported-by: Alexander Lakhin
Reviewed-by: Tender Wang
Reviewed-by: Michael Paquier
Discussion: https://postgr.es/m/18500-62948b6fe5522f56@postgresql.org
src/backend/commands/tablecmds.c
src/test/regress/expected/constraints.out
src/test/regress/sql/constraints.sql