From 06b312ad3d7fbb0d28754a7d066b0f6ec1694493 Mon Sep 17 00:00:00 2001
From: Rushabh Lathia <rushabh.lathia@enterprisedb.com>
Date: Fri, 4 Apr 2025 17:10:44 +0530
Subject: [PATCH 1/2] Fix MergeWithExistingConstraint()

If the child already has a valid constraint and we are creating an invalid
one with same definition on it.  The child's constraint will remain valid,
but can no longer be marked as local.
---
 src/backend/catalog/heap.c            | 21 +++++++++++++++++----
 src/test/regress/expected/inherit.out |  2 +-
 2 files changed, 18 insertions(+), 5 deletions(-)

diff --git a/src/backend/catalog/heap.c b/src/backend/catalog/heap.c
index b807ab66668..8a75e2dafab 100644
--- a/src/backend/catalog/heap.c
+++ b/src/backend/catalog/heap.c
@@ -2826,11 +2826,24 @@ MergeWithExistingConstraint(Relation rel, const char *ccname, Node *expr,
 		{
 			if (is_local)
 				con->conislocal = true;
-			else if (pg_add_s16_overflow(con->coninhcount, 1,
+			else
+			{
+				if(pg_add_s16_overflow(con->coninhcount, 1,
 										 &con->coninhcount))
-				ereport(ERROR,
-						errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
-						errmsg("too many inheritance parents"));
+					ereport(ERROR,
+							errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
+							errmsg("too many inheritance parents"));
+
+				/*
+				 * If the child already has a valid constraint and we are
+				 * creating an invalid one with same definition on it.  The
+				 * child's constraint will remain valid, but can no longer be
+				 * marked as local.
+				*/
+				if (!is_initially_valid && con->convalidated &&
+					is_enforced && con->conenforced)
+					con->conislocal = false;
+			}
 		}
 
 		if (is_no_inherit)
diff --git a/src/test/regress/expected/inherit.out b/src/test/regress/expected/inherit.out
index 2a8bfba768e..e063f48d343 100644
--- a/src/test/regress/expected/inherit.out
+++ b/src/test/regress/expected/inherit.out
@@ -1571,7 +1571,7 @@ order by 1, 2;
          relname         |       conname        | convalidated | conislocal | coninhcount | connoinherit 
 -------------------------+----------------------+--------------+------------+-------------+--------------
  invalid_check_con       | inh_check_constraint | f            | t          |           0 | f
- invalid_check_con_child | inh_check_constraint | t            | t          |           1 | f
+ invalid_check_con_child | inh_check_constraint | t            | f          |           1 | f
 (2 rows)
 
 -- We don't drop the invalid_check_con* tables, to test dump/reload with
-- 
2.43.0

