From 4f986b7d3c2c2057a34f77e758f55b5ff4402352 Mon Sep 17 00:00:00 2001
From: Manu <manuelreyesbravo@gmail.com>
Date: Tue, 1 Dec 2026 02:10:29 -0300
Subject: [PATCH v1] Avoid quadratic behavior in MergeConstraintsIntoExisting()

ALTER TABLE ... INHERIT and ALTER TABLE ... ATTACH PARTITION call
MergeConstraintsIntoExisting(), which, for each CHECK and not-null
constraint of the parent, started a new scan over all pg_constraint
rows of the child.  That is O(N^2) in the number of constraints, as the
function's header comment has said since f58eac82eeb, and commit
b3f0e0503f3 described the function as "horribly inefficient" when
restoring tables with many inherited constraints.

Since 14e87ffa5c5 every not-null column has a pg_constraint row, so
this is no longer limited to tables with unusual numbers of CHECK
constraints: any wide table with NOT NULL columns hits it, and
pg_upgrade and pg_restore run one ATTACH PARTITION per partition.

Instead, look up each CHECK constraint of the parent in the child by
name, using the index on (conrelid, contypid, conname), and read the
child's not-null constraints only once, into an array indexed by the
parent's attribute number (through the existing attribute map).  The
checks applied to a matching pair, the error messages and the order in
which errors are raised are unchanged.

Attaching one partition to a table with 1600 NOT NULL columns goes
from about 280 ms to 36 ms, and pg_upgrade of a table with 1000
partitions and 200 NOT NULL columns executes 15% fewer instructions.

Author: Manu <manuelreyesbravo@gmail.com>
---
 src/backend/commands/tablecmds.c | 252 ++++++++++++++++++-------------
 1 file changed, 144 insertions(+), 108 deletions(-)

diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c
index 9e363a44c20..a2f83ef8252 100644
--- a/src/backend/commands/tablecmds.c
+++ b/src/backend/commands/tablecmds.c
@@ -18953,9 +18953,9 @@ MergeAttributesIntoExisting(Relation child_rel, Relation parent_rel, bool ispart
  * Currently all constraints in parent must be present in the child. One day we
  * may consider adding new constraints like CREATE TABLE does.
  *
- * XXX This is O(N^2) which may be an issue with tables with hundreds of
- * constraints. As long as tables have more like 10 constraints it shouldn't be
- * a problem though. Even 100 constraints ought not be the end of the world.
+ * To keep the cost from growing with the product of the number of
+ * constraints of both tables, each CHECK constraint is looked up by name in
+ * the child, and the child's not-null constraints are read only once.
  *
  * XXX See MergeWithExistingConstraint too if you change this code.
  */
@@ -18968,6 +18968,7 @@ MergeConstraintsIntoExisting(Relation child_rel, Relation parent_rel)
 	HeapTuple	parent_tuple;
 	Oid			parent_relid = RelationGetRelid(parent_rel);
 	AttrMap    *attmap;
+	HeapTuple  *child_notnulls = NULL;	/* indexed by parent attnum */
 
 	constraintrel = table_open(ConstraintRelationId, RowExclusiveLock);
 
@@ -18986,11 +18987,8 @@ MergeConstraintsIntoExisting(Relation child_rel, Relation parent_rel)
 	while (HeapTupleIsValid(parent_tuple = systable_getnext(parent_scan)))
 	{
 		Form_pg_constraint parent_con = (Form_pg_constraint) GETSTRUCT(parent_tuple);
-		SysScanDesc child_scan;
-		ScanKeyData child_key;
+		Form_pg_constraint child_con;
 		HeapTuple	child_tuple;
-		AttrNumber	parent_attno;
-		bool		found = false;
 
 		if (parent_con->contype != CONSTRAINT_CHECK &&
 			parent_con->contype != CONSTRAINT_NOTNULL)
@@ -19000,126 +18998,100 @@ MergeConstraintsIntoExisting(Relation child_rel, Relation parent_rel)
 		if (parent_con->connoinherit)
 			continue;
 
-		if (parent_con->contype == CONSTRAINT_NOTNULL)
-			parent_attno = extractNotNullColumn(parent_tuple);
-		else
-			parent_attno = InvalidAttrNumber;
+		/*
+		 * Search for a child constraint matching this one.  CHECK constraints
+		 * are matched by constraint name, NOT NULL ones by attribute number.
+		 */
+		if (parent_con->contype == CONSTRAINT_CHECK)
+		{
+			SysScanDesc child_scan;
+			ScanKeyData child_key[3];
 
-		/* Search for a child constraint matching this one */
-		ScanKeyInit(&child_key,
-					Anum_pg_constraint_conrelid,
-					BTEqualStrategyNumber, F_OIDEQ,
-					ObjectIdGetDatum(RelationGetRelid(child_rel)));
-		child_scan = systable_beginscan(constraintrel, ConstraintRelidTypidNameIndexId,
-										true, NULL, 1, &child_key);
+			ScanKeyInit(&child_key[0],
+						Anum_pg_constraint_conrelid,
+						BTEqualStrategyNumber, F_OIDEQ,
+						ObjectIdGetDatum(RelationGetRelid(child_rel)));
+			ScanKeyInit(&child_key[1],
+						Anum_pg_constraint_contypid,
+						BTEqualStrategyNumber, F_OIDEQ,
+						ObjectIdGetDatum(InvalidOid));
+			ScanKeyInit(&child_key[2],
+						Anum_pg_constraint_conname,
+						BTEqualStrategyNumber, F_NAMEEQ,
+						NameGetDatum(&parent_con->conname));
+			child_scan = systable_beginscan(constraintrel, ConstraintRelidTypidNameIndexId,
+											true, NULL, 3, child_key);
+
+			/* There can be at most one matching row */
+			child_tuple = systable_getnext(child_scan);
+			if (HeapTupleIsValid(child_tuple) &&
+				((Form_pg_constraint) GETSTRUCT(child_tuple))->contype == CONSTRAINT_CHECK)
+				child_tuple = heap_copytuple(child_tuple);
+			else
+				child_tuple = NULL;
 
-		while (HeapTupleIsValid(child_tuple = systable_getnext(child_scan)))
+			systable_endscan(child_scan);
+		}
+		else
 		{
-			Form_pg_constraint child_con = (Form_pg_constraint) GETSTRUCT(child_tuple);
-			HeapTuple	child_copy;
-
-			if (child_con->contype != parent_con->contype)
-				continue;
+			AttrNumber	parent_attno = extractNotNullColumn(parent_tuple);
 
 			/*
-			 * CHECK constraint are matched by constraint name, NOT NULL ones
-			 * by attribute number.
+			 * The first time, collect the child's not-null constraints on
+			 * columns that are NOT NULL in the parent, by parent column.  We
+			 * keep copies of the tuples as they are now: the updates made
+			 * below are not visible to scans within this command anyway.
 			 */
-			if (child_con->contype == CONSTRAINT_CHECK)
+			if (child_notnulls == NULL)
 			{
-				if (strcmp(NameStr(parent_con->conname),
-						   NameStr(child_con->conname)) != 0)
-					continue;
-			}
-			else if (child_con->contype == CONSTRAINT_NOTNULL)
-			{
-				Form_pg_attribute parent_attr;
-				Form_pg_attribute child_attr;
-				AttrNumber	child_attno;
+				SysScanDesc child_scan;
+				ScanKeyData child_key;
 
-				parent_attr = TupleDescAttr(parent_rel->rd_att, parent_attno - 1);
-				child_attno = extractNotNullColumn(child_tuple);
-				if (parent_attno != attmap->attnums[child_attno - 1])
-					continue;
+				child_notnulls = palloc0_array(HeapTuple,
+											   RelationGetNumberOfAttributes(parent_rel) + 1);
 
-				child_attr = TupleDescAttr(child_rel->rd_att, child_attno - 1);
-				/* there shouldn't be constraints on dropped columns */
-				if (parent_attr->attisdropped || child_attr->attisdropped)
-					elog(ERROR, "found not-null constraint on dropped columns");
-			}
-
-			if (child_con->contype == CONSTRAINT_CHECK &&
-				!constraints_equivalent(parent_tuple, child_tuple, RelationGetDescr(constraintrel)))
-				ereport(ERROR,
-						(errcode(ERRCODE_DATATYPE_MISMATCH),
-						 errmsg("child table \"%s\" has different definition for check constraint \"%s\"",
-								RelationGetRelationName(child_rel), NameStr(parent_con->conname))));
+				ScanKeyInit(&child_key,
+							Anum_pg_constraint_conrelid,
+							BTEqualStrategyNumber, F_OIDEQ,
+							ObjectIdGetDatum(RelationGetRelid(child_rel)));
+				child_scan = systable_beginscan(constraintrel, ConstraintRelidTypidNameIndexId,
+												true, NULL, 1, &child_key);
 
-			/*
-			 * If the child constraint is "no inherit" then cannot merge
-			 */
-			if (child_con->connoinherit)
-				ereport(ERROR,
-						(errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
-						 errmsg("constraint \"%s\" conflicts with non-inherited constraint on child table \"%s\"",
-								NameStr(child_con->conname), RelationGetRelationName(child_rel))));
+				while (HeapTupleIsValid(child_tuple = systable_getnext(child_scan)))
+				{
+					AttrNumber	child_parent_attno;
 
-			/*
-			 * If the child constraint is "not valid" then cannot merge with a
-			 * valid parent constraint
-			 */
-			if (parent_con->convalidated && child_con->conenforced &&
-				!child_con->convalidated)
-				ereport(ERROR,
-						(errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
-						 errmsg("constraint \"%s\" conflicts with NOT VALID constraint on child table \"%s\"",
-								NameStr(child_con->conname), RelationGetRelationName(child_rel))));
+					child_con = (Form_pg_constraint) GETSTRUCT(child_tuple);
+					if (child_con->contype != CONSTRAINT_NOTNULL)
+						continue;
 
-			/*
-			 * A NOT ENFORCED child constraint cannot be merged with an
-			 * ENFORCED parent constraint. However, the reverse is allowed,
-			 * where the child constraint is ENFORCED.
-			 */
-			if (parent_con->conenforced && !child_con->conenforced)
-				ereport(ERROR,
-						(errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
-						 errmsg("constraint \"%s\" conflicts with NOT ENFORCED constraint on child table \"%s\"",
-								NameStr(child_con->conname), RelationGetRelationName(child_rel))));
+					child_parent_attno = attmap->attnums[extractNotNullColumn(child_tuple) - 1];
+					if (child_parent_attno > 0 &&
+						TupleDescAttr(parent_rel->rd_att, child_parent_attno - 1)->attnotnull &&
+						child_notnulls[child_parent_attno] == NULL)
+						child_notnulls[child_parent_attno] = heap_copytuple(child_tuple);
+				}
 
-			/*
-			 * OK, bump the child constraint's inheritance count.  (If we fail
-			 * later on, this change will just roll back.)
-			 */
-			child_copy = heap_copytuple(child_tuple);
-			child_con = (Form_pg_constraint) GETSTRUCT(child_copy);
+				systable_endscan(child_scan);
+			}
 
-			if (pg_add_s16_overflow(child_con->coninhcount, 1,
-									&child_con->coninhcount))
-				ereport(ERROR,
-						errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
-						errmsg("too many inheritance parents"));
+			child_tuple = child_notnulls[parent_attno];
 
-			/*
-			 * In case of partitions, an inherited constraint must be
-			 * inherited only once since it cannot have multiple parents and
-			 * it is never considered local.
-			 */
-			if (parent_rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
+			if (HeapTupleIsValid(child_tuple))
 			{
-				Assert(child_con->coninhcount == 1);
-				child_con->conislocal = false;
-			}
-
-			CatalogTupleUpdate(constraintrel, &child_copy->t_self, child_copy);
-			heap_freetuple(child_copy);
+				Form_pg_attribute parent_attr;
+				Form_pg_attribute child_attr;
 
-			found = true;
-			break;
+				parent_attr = TupleDescAttr(parent_rel->rd_att, parent_attno - 1);
+				child_attr = TupleDescAttr(child_rel->rd_att,
+										   extractNotNullColumn(child_tuple) - 1);
+				/* there shouldn't be constraints on dropped columns */
+				if (parent_attr->attisdropped || child_attr->attisdropped)
+					elog(ERROR, "found not-null constraint on dropped columns");
+			}
 		}
 
-		systable_endscan(child_scan);
-
-		if (!found)
+		if (!HeapTupleIsValid(child_tuple))
 		{
 			if (parent_con->contype == CONSTRAINT_NOTNULL)
 				ereport(ERROR,
@@ -19135,6 +19107,70 @@ MergeConstraintsIntoExisting(Relation child_rel, Relation parent_rel)
 					 errmsg("child table is missing constraint \"%s\"",
 							NameStr(parent_con->conname))));
 		}
+
+		child_con = (Form_pg_constraint) GETSTRUCT(child_tuple);
+
+		if (child_con->contype == CONSTRAINT_CHECK &&
+			!constraints_equivalent(parent_tuple, child_tuple, RelationGetDescr(constraintrel)))
+			ereport(ERROR,
+					(errcode(ERRCODE_DATATYPE_MISMATCH),
+					 errmsg("child table \"%s\" has different definition for check constraint \"%s\"",
+							RelationGetRelationName(child_rel), NameStr(parent_con->conname))));
+
+		/*
+		 * If the child constraint is "no inherit" then cannot merge
+		 */
+		if (child_con->connoinherit)
+			ereport(ERROR,
+					(errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
+					 errmsg("constraint \"%s\" conflicts with non-inherited constraint on child table \"%s\"",
+							NameStr(child_con->conname), RelationGetRelationName(child_rel))));
+
+		/*
+		 * If the child constraint is "not valid" then cannot merge with a
+		 * valid parent constraint
+		 */
+		if (parent_con->convalidated && child_con->conenforced &&
+			!child_con->convalidated)
+			ereport(ERROR,
+					(errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
+					 errmsg("constraint \"%s\" conflicts with NOT VALID constraint on child table \"%s\"",
+							NameStr(child_con->conname), RelationGetRelationName(child_rel))));
+
+		/*
+		 * A NOT ENFORCED child constraint cannot be merged with an ENFORCED
+		 * parent constraint. However, the reverse is allowed, where the child
+		 * constraint is ENFORCED.
+		 */
+		if (parent_con->conenforced && !child_con->conenforced)
+			ereport(ERROR,
+					(errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
+					 errmsg("constraint \"%s\" conflicts with NOT ENFORCED constraint on child table \"%s\"",
+							NameStr(child_con->conname), RelationGetRelationName(child_rel))));
+
+		/*
+		 * OK, bump the child constraint's inheritance count.  (If we fail
+		 * later on, this change will just roll back.)  The tuple is our own
+		 * copy, so we can scribble on it.
+		 */
+		if (pg_add_s16_overflow(child_con->coninhcount, 1,
+								&child_con->coninhcount))
+			ereport(ERROR,
+					errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
+					errmsg("too many inheritance parents"));
+
+		/*
+		 * In case of partitions, an inherited constraint must be inherited
+		 * only once since it cannot have multiple parents and it is never
+		 * considered local.
+		 */
+		if (parent_rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
+		{
+			Assert(child_con->coninhcount == 1);
+			child_con->conislocal = false;
+		}
+
+		CatalogTupleUpdate(constraintrel, &child_tuple->t_self, child_tuple);
 	}
 
 	systable_endscan(parent_scan);

base-commit: c1dd701fb5f866fbab78dcd33b184e2fb7a4782d
-- 
2.56.1

