Move RemoveInheritedConstraint() call slightly earlier
authorPeter Eisentraut <peter@eisentraut.org>
Tue, 11 Mar 2025 09:43:48 +0000 (10:43 +0100)
committerPeter Eisentraut <peter@eisentraut.org>
Tue, 11 Mar 2025 09:43:48 +0000 (10:43 +0100)
This change is harmless and does not affect the existing intended
operation.  It is necessary for a subsequent patch operation (NOT
ENFORCED foreign keys), where we may need to change the child
constraint to enforced.  In this case, we would create the necessary
triggers and queue the constraint for validation, so it is important
to remove any unnecessary constraints before proceeding.

This is a small change that could have been included in the previous
"split tryAttachPartitionForeignKey" refactoring patch (commit
1d26c2d2c4b), but was kept separate to highlight the changes.

Author: Amul Sul <amul.sul@enterprisedb.com>
Reviewed-by: Alexandra Wang <alexandra.wang.oss@gmail.com>
Discussion: https://www.postgresql.org/message-id/flat/CAAJ_b962c5AcYW9KUt_R_ER5qs3fUGbe4az-SP-vuwPS-w-AGA%40mail.gmail.com

src/backend/commands/tablecmds.c

index 1ada38908c19746278c9661b12a09515d71d0c71..18ff89565775656e0f1a6edf5deedd432be5b313 100644 (file)
@@ -11572,6 +11572,21 @@ AttachPartitionForeignKey(List **wqueue,
    partConstrFrelid = partConstr->confrelid;
    partConstrRelid = partConstr->conrelid;
 
+   /*
+    * If the referenced table is partitioned, then the partition we're
+    * attaching now has extra pg_constraint rows and action triggers that are
+    * no longer needed.  Remove those.
+    */
+   if (get_rel_relkind(partConstrFrelid) == RELKIND_PARTITIONED_TABLE)
+   {
+       Relation    pg_constraint = table_open(ConstraintRelationId, RowShareLock);
+
+       RemoveInheritedConstraint(pg_constraint, trigrel, partConstrOid,
+                                 partConstrRelid);
+
+       table_close(pg_constraint, RowShareLock);
+   }
+
    /*
     * Will we need to validate this constraint?   A valid parent constraint
     * implies that all child constraints have been validated, so if this one
@@ -11608,21 +11623,6 @@ AttachPartitionForeignKey(List **wqueue,
    TriggerSetParentTrigger(trigrel, updateTriggerOid, parentUpdTrigger,
                            RelationGetRelid(partition));
 
-   /*
-    * If the referenced table is partitioned, then the partition we're
-    * attaching now has extra pg_constraint rows and action triggers that are
-    * no longer needed.  Remove those.
-    */
-   if (get_rel_relkind(partConstrFrelid) == RELKIND_PARTITIONED_TABLE)
-   {
-       Relation    pg_constraint = table_open(ConstraintRelationId, RowShareLock);
-
-       RemoveInheritedConstraint(pg_constraint, trigrel, partConstrOid,
-                                 partConstrRelid);
-
-       table_close(pg_constraint, RowShareLock);
-   }
-
    /*
     * We updated this pg_constraint row above to set its parent; validating
     * it will cause its convalidated flag to change, so we need CCI here.  In