Allow NOT VALID foreign key constraints on partitioned tables.
Amul Sul <sulamul@gmail.com>
From: Amul Sul <sulamul@gmail.com>
To: PostgreSQL Hackers <pgsql-hackers@lists.postgresql.org>
Date: 2025-01-02T16:49:13Z
Lists: pgsql-hackers
Attachments
- v1-0001-Refactor-Split-ATExecValidateConstraint.patch (application/x-patch) patch v1-0001
- v1-0002-Allow-NOT-VALID-foreign-key-constraints-on-partit.patch (application/x-patch) patch v1-0002
Hi, While working on NOT ENFORCED constraints[1], which are by default marked as NOT VALID, I encountered an error when adding a NOT ENFORCED foreign key (FK) constraint to a partitioned table [2]. Alvaro also confirmed off-list that NOT VALID FK constraints have not yet been implemented. This patch addresses that gap. When adding a new FK constraint or attaching a partitioned table, where matching FK constraints are merged, we allow the parent constraint to be NOT VALID while the child constraint remains VALID, which is harmless. However, the reverse scenario -- where the parent constraint is VALID and the child is NOT VALID -- is incorrect. To address this, when merging a NOT VALID FK constraint from the child with a VALID parent constraint, it implicitly validates the child constraint against its existing data and marks it as VALID. This behavior aligns with adding a new FK constraint directly to the child table, which would also validate the existing data. The 0001 patch focuses on code refactoring and does not modify or introduce new behaviors. It splits ATExecValidateConstraint() into two separate functions for handling FK and CHECK constraints. For this feature, I wanted to reuse the FK validation logic and make it recursive for partitioned tables, necessitating its separation. Although CHECK constraint validation isn't required for this work, separating it simplifies ATExecValidateConstraint() and prepares the codebase for adding support for other constraint types (e.g., NOT NULL) in the future. Additional changes in the refactoring include renaming the variable tuple to contuple within these functions, duplicating a few lines of code that update pg_constraint.convalidated, and running pgindent, which rearranged the code and comments. I hope the duplication is not a significant concern. Please review the attached patches. Any comments or suggestions would be greatly appreciated. Thank you! 1] https://postgr.es/m/CAAJ_b962c5AcYW9KUt_R_ER5qs3fUGbe4az-SP-vuwPS-w-AGA@mail.gmail.com 2] https://postgr.es/m/CAAJ_b94+0-YFj4LopVqz_+c7ckkUYa77G_5rgTJVnUyepuhmrA@mail.gmail.com -- Regards, Amul Sul EDB: http://www.enterprisedb.com
Commits
-
Add missing CommandCounterIncrement
- 0a16c8326c5a 18.0 landed
-
Fix instability in recently added regression tests
- c44c2d275987 18.0 landed
-
Allow NOT VALID foreign key constraints on partitioned tables
- b663b9436e75 18.0 landed
-
Split ATExecValidateConstraint into reusable pieces
- 86374c9a0e30 18.0 landed