pgsql: Handle self-referencing FKs correctly in partitioned tables

From: Álvaro Herrera <alvherre(at)kurilemu(dot)de>
To: pgsql-committers(at)lists(dot)postgresql(dot)org
Subject: pgsql: Handle self-referencing FKs correctly in partitioned tables
Date: 2025-05-02 19:30:07
Message-ID: E1uAw5H-000fTI-0e@gemulon.postgresql.org
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-committers

Handle self-referencing FKs correctly in partitioned tables

For self-referencing foreign keys in partitioned tables, we weren't
handling creation of pg_constraint rows during CREATE TABLE PARTITION AS
as well as ALTER TABLE ATTACH PARTITION. This is an old bug -- mostly,
we broke this in 614a406b4ff1 while trying to fix it (so 12.13, 13.9,
14.6 and 15.0 and up all behave incorrectly). This commit reverts part
of that with additional fixes for full correctness, and installs more
tests to verify the parts we broke, not just the catalog contents but
also the user-visible behavior.

Backpatch to all live branches. In branches 13 and 14, commit
46a8c27a7226 changed the behavior during DETACH to drop a FK
constraint rather than trying to repair it, because the complete fix of
repairing catalog constraints was problematic due to lack of previous
fixes. For this reason, the test behavior in those branches is a bit
different. However, as best as I can tell, the fix works correctly
there.

In release notes we have to recommend that all self-referencing foreign
keys on partitioned tables be recreated if partitions have been created
or attached after the FK was created, keeping in mind that violating
rows might already be present on the referencing side.

Reported-by: Guillaume Lelarge <guillaume(at)lelarge(dot)info>
Reported-by: Matthew Gabeler-Lee <fastcat(at)gmail(dot)com>
Reported-by: Luca Vallisa <luca(dot)vallisa(at)gmail(dot)com>
Discussion: https://postgr.es/m/CAECtzeWHCA+6tTcm2Oh2+g7fURUJpLZb-=pRXgeWJ-Pi+VU=_w@mail.gmail.com
Discussion: https://postgr.es/m/18156-a44bc7096f0683e6@postgresql.org
Discussion: https://postgr.es/m/CAAT=myvsiF-Attja5DcWoUWh21R12R-sfXECY2-3ynt8kaOqjw@mail.gmail.com

Branch
------
REL_16_STABLE

Details
-------
https://git.postgresql.org/pg/commitdiff/1817d62ecbf55f27101b8ad30e24630c33b38325

Modified Files
--------------
src/backend/commands/tablecmds.c | 21 ++----
src/test/regress/expected/foreign_key.out | 104 +++++++++++++++++++-----------
src/test/regress/expected/triggers.out | 8 ++-
src/test/regress/sql/foreign_key.sql | 35 ++++++++--
4 files changed, 107 insertions(+), 61 deletions(-)

Browse pgsql-committers by date

  From Date Subject
Next Message Tom Lane 2025-05-02 20:16:32 pgsql: Don't use a tuplestore if we don't have to for SQL-language func
Previous Message Tom Lane 2025-05-02 19:13:12 pgsql: Doc: correct spelling of meson switch.