From 63bb93fb784d841ed77e9dc7f28d22e1656e9371 Mon Sep 17 00:00:00 2001
From: Manuel Reyes Bravo <manuelreyesbravo@gmail.com>
Date: Mon, 16 Nov 2026 19:41:27 -0300
Subject: [PATCH v1] Avoid quadratic name search for FKs to partitioned tables

When a foreign key references a partitioned table,
addFkRecurseReferenced() creates one pg_constraint row per partition,
all on the referencing relation and named after the constraint, and
ChooseConstraintName() looked for a free name starting from suffix 1
each time: N partitions took N(N+1)/2 index probes.  pg_restore and
pg_upgrade pay this once per such foreign key.  With 10,000
partitions, ALTER TABLE ... ADD FOREIGN KEY took 43 s instead of 2 s.

Keep the last suffix chosen in the recursion and start the next search
after it.  Every lower suffix is known to be taken, so the names are the
same as before; they could only differ if another session dropped a
constraint with one of those names in the same schema meanwhile, the
race ChooseConstraintName() already accepts.  This covers ADD FOREIGN
KEY, CREATE TABLE ... REFERENCES and DETACH PARTITION of a referencing
partition.  Attaching or creating a single referenced partition still
searches from 1, which is linear per command.

Add ChooseConstraintNameExtended() to carry the suffix, and a test that
pins the names when one in the middle of the sequence is taken.

Discussion:
---
 src/backend/catalog/pg_constraint.c       | 32 ++++++++++--
 src/backend/commands/tablecmds.c          | 60 ++++++++++++++++-------
 src/include/catalog/pg_constraint.h       |  3 ++
 src/test/regress/expected/foreign_key.out | 37 ++++++++++++++
 src/test/regress/sql/foreign_key.sql      | 22 +++++++++
 5 files changed, 132 insertions(+), 22 deletions(-)

diff --git a/src/backend/catalog/pg_constraint.c b/src/backend/catalog/pg_constraint.c
index 3a8dbbe..edd8742 100644
--- a/src/backend/catalog/pg_constraint.c
+++ b/src/backend/catalog/pg_constraint.c
@@ -517,7 +517,30 @@ ChooseConstraintName(const char *name1, const char *name2,
 					 const char *label, Oid namespaceid,
 					 List *others)
 {
-	int			pass = 0;
+	return ChooseConstraintNameExtended(name1, name2, label, namespaceid,
+										others, NULL);
+}
+
+/*
+ * ChooseConstraintNameExtended
+ *		As ChooseConstraintName, for callers that choose several names with
+ *		the same name1, name2, label and namespace in a row.
+ *
+ * If passp is not NULL, the caller promises that the names numbered up to
+ * *passp (and the unmodified label, if *passp > 0) are taken, so the search
+ * starts at *passp + 1.  On return, *passp is set to the number used in the
+ * chosen name (0 for the unmodified label), so that passing it back for the
+ * next name of the series continues where this one stopped.  If the promise
+ * is wrong, the result is still a free name, just not the lowest one; that
+ * includes the case of a name being dropped concurrently, which is the same
+ * race described for ChooseConstraintName.
+ */
+char *
+ChooseConstraintNameExtended(const char *name1, const char *name2,
+							 const char *label, Oid namespaceid,
+							 List *others, int *passp)
+{
+	int			pass = passp ? *passp : 0;
 	char	   *conname = NULL;
 	char		modlabel[NAMEDATALEN];
 	Relation	conDesc;
@@ -528,8 +551,8 @@ ChooseConstraintName(const char *name1, const char *name2,
 
 	conDesc = table_open(ConstraintRelationId, AccessShareLock);
 
-	/* try the unmodified label first, unless it's empty */
-	if (label[0] != '\0')
+	/* try the unmodified label first, unless it's empty or known taken */
+	if (label[0] != '\0' && pass == 0)
 		strlcpy(modlabel, label, sizeof(modlabel));
 	else
 		snprintf(modlabel, sizeof(modlabel), "%s%d", label, ++pass);
@@ -579,6 +602,9 @@ ChooseConstraintName(const char *name1, const char *name2,
 
 	table_close(conDesc, AccessShareLock);
 
+	if (passp)
+		*passp = pass;
+
 	return conname;
 }
 
diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c
index b670092..a2cfa3b 100644
--- a/src/backend/commands/tablecmds.c
+++ b/src/backend/commands/tablecmds.c
@@ -604,7 +604,7 @@ static ObjectAddress addFkConstraint(addFkConstraintSides fkside,
 									 Oid *pfeqoperators, Oid *ppeqoperators,
 									 Oid *ffeqoperators, int numfkdelsetcols,
 									 int16 *fkdelsetcols, bool is_internal,
-									 bool with_period);
+									 bool with_period, int *conname_pass);
 static void addFkRecurseReferenced(Constraint *fkconstraint,
 								   Relation rel, Relation pkrel, Oid indexOid, Oid parentConstr,
 								   int numfks, int16 *pkattnum, int16 *fkattnum,
@@ -612,7 +612,7 @@ static void addFkRecurseReferenced(Constraint *fkconstraint,
 								   int numfkdelsetcols, int16 *fkdelsetcols,
 								   bool old_check_ok,
 								   Oid parentDelTrigger, Oid parentUpdTrigger,
-								   bool with_period);
+								   bool with_period, int *conname_pass);
 static void addFkRecurseReferencing(List **wqueue, Constraint *fkconstraint,
 									Relation rel, Relation pkrel, Oid indexOid, Oid parentConstr,
 									int numfks, int16 *pkattnum, int16 *fkattnum,
@@ -10788,6 +10788,7 @@ ATAddForeignKeyConstraint(List **wqueue, AlteredTableInfo *tab, Relation rel,
 	Oid			indexOid;
 	bool		old_check_ok;
 	ObjectAddress address;
+	int			conname_pass = 0;
 	ListCell   *old_pfeqop_item = list_head(fkconstraint->old_conpfeqop);
 
 	/*
@@ -11288,7 +11289,10 @@ ATAddForeignKeyConstraint(List **wqueue, AlteredTableInfo *tab, Relation rel,
 						  &intersectoperoid);
 	}
 
-	/* First, create the constraint catalog entry itself. */
+	/*
+	 * First, create the constraint catalog entry itself.  Its name is not
+	 * part of the series of names for the partitions, hence no conname_pass.
+	 */
 	address = addFkConstraint(addFkBothSides,
 							  fkconstraint->conname, fkconstraint, rel, pkrel,
 							  indexOid,
@@ -11302,7 +11306,8 @@ ATAddForeignKeyConstraint(List **wqueue, AlteredTableInfo *tab, Relation rel,
 							  numfkdelsetcols,
 							  fkdelsetcols,
 							  false,
-							  with_period);
+							  with_period,
+							  NULL);
 
 	/* Next process the action triggers at the referenced side and recurse */
 	addFkRecurseReferenced(fkconstraint, rel, pkrel,
@@ -11318,7 +11323,8 @@ ATAddForeignKeyConstraint(List **wqueue, AlteredTableInfo *tab, Relation rel,
 						   fkdelsetcols,
 						   old_check_ok,
 						   InvalidOid, InvalidOid,
-						   with_period);
+						   with_period,
+						   &conname_pass);
 
 	/* Lastly create the check triggers at the referencing side and recurse */
 	addFkRecurseReferencing(wqueue, fkconstraint, rel, pkrel,
@@ -11428,6 +11434,9 @@ validateFkOnDeleteSetColumns(int numfks, const int16 *fkattnums,
  * fkdelsetcols: the attnum array of the columns in the ON DELETE SET
  *      NULL/DEFAULT clause
  * with_period: true if this is a temporal FK
+ * conname_pass: if not NULL, the suffix number of the last name chosen for
+ *      the constraint rows created so far for this same rel and
+ *      constraintname (see addFkRecurseReferenced); updated on return
  */
 static ObjectAddress
 addFkConstraint(addFkConstraintSides fkside,
@@ -11436,7 +11445,7 @@ addFkConstraint(addFkConstraintSides fkside,
 				int numfks, int16 *pkattnum,
 				int16 *fkattnum, Oid *pfeqoperators, Oid *ppeqoperators,
 				Oid *ffeqoperators, int numfkdelsetcols, int16 *fkdelsetcols,
-				bool is_internal, bool with_period)
+				bool is_internal, bool with_period, int *conname_pass)
 {
 	ObjectAddress address;
 	Oid			constrOid;
@@ -11460,15 +11469,17 @@ addFkConstraint(addFkConstraintSides fkside,
 	 * Caller supplies us with a constraint name; however, it may be used in
 	 * this partition, so come up with a different one in that case.  Unless
 	 * truncation to NAMEDATALEN dictates otherwise, the new name will be the
-	 * supplied name with an underscore and digit(s) appended.
+	 * supplied name with an underscore and digit(s) appended.  conname_pass,
+	 * if given, lets a series of such names skip the suffixes already used.
 	 */
 	if (ConstraintNameIsUsed(CONSTRAINT_RELATION,
 							 RelationGetRelid(rel),
 							 constraintname))
-		conname = ChooseConstraintName(constraintname,
-									   NULL,
-									   "",
-									   RelationGetNamespace(rel), NIL);
+		conname = ChooseConstraintNameExtended(constraintname,
+											   NULL,
+											   "",
+											   RelationGetNamespace(rel), NIL,
+											   conname_pass);
 	else
 		conname = constraintname;
 
@@ -11606,6 +11617,12 @@ addFkConstraint(addFkConstraintSides fkside,
  *      partition, the OIDs of the parent action triggers for DELETE and
  *      UPDATE respectively.
  * with_period: true if this is a temporal FK
+ * conname_pass: points to the suffix number of the last name chosen in this
+ *      recursion (0 at the top), and is updated as names are chosen.  Every
+ *      row created here is on rel and named after fkconstraint->conname, and
+ *      each gets the lowest free suffix, so the lower ones are all taken and
+ *      the search for the next name can start after the last one.  See
+ *      ChooseConstraintNameExtended.
  */
 static void
 addFkRecurseReferenced(Constraint *fkconstraint, Relation rel,
@@ -11616,7 +11633,7 @@ addFkRecurseReferenced(Constraint *fkconstraint, Relation rel,
 					   int numfkdelsetcols, int16 *fkdelsetcols,
 					   bool old_check_ok,
 					   Oid parentDelTrigger, Oid parentUpdTrigger,
-					   bool with_period)
+					   bool with_period, int *conname_pass)
 {
 	Oid			deleteTriggerOid = InvalidOid,
 				updateTriggerOid = InvalidOid;
@@ -11685,7 +11702,8 @@ addFkRecurseReferenced(Constraint *fkconstraint, Relation rel,
 									  numfks, mapped_pkattnum,
 									  fkattnum, pfeqoperators, ppeqoperators,
 									  ffeqoperators, numfkdelsetcols,
-									  fkdelsetcols, true, with_period);
+									  fkdelsetcols, true, with_period,
+									  conname_pass);
 			/* ... and recurse to our children */
 			addFkRecurseReferenced(fkconstraint, rel, partRel,
 								   partIndexId, address.objectId, numfks,
@@ -11694,7 +11712,7 @@ addFkRecurseReferenced(Constraint *fkconstraint, Relation rel,
 								   numfkdelsetcols, fkdelsetcols,
 								   old_check_ok,
 								   deleteTriggerOid, updateTriggerOid,
-								   with_period);
+								   with_period, conname_pass);
 
 			/* Done -- clean up (but keep the lock) */
 			table_close(partRel, NoLock);
@@ -11884,7 +11902,7 @@ addFkRecurseReferencing(List **wqueue, Constraint *fkconstraint, Relation rel,
 									  mapped_fkattnum, pfeqoperators,
 									  ppeqoperators, ffeqoperators,
 									  numfkdelsetcols, fkdelsetcols, true,
-									  with_period);
+									  with_period, NULL);
 
 			/* call ourselves to finalize the creation and we're done */
 			addFkRecurseReferencing(wqueue, fkconstraint, partition, pkrel,
@@ -12028,6 +12046,7 @@ CloneFkReferenced(Relation parentRel, Relation partitionRel)
 		ObjectAddress address;
 		Oid			deleteTriggerOid = InvalidOid,
 					updateTriggerOid = InvalidOid;
+		int			conname_pass = 0;
 
 		tuple = SearchSysCache1(CONSTROID, ObjectIdGetDatum(constrOid));
 		if (!HeapTupleIsValid(tuple))
@@ -12118,7 +12137,7 @@ CloneFkReferenced(Relation parentRel, Relation partitionRel)
 								  numfks, mapped_confkey,
 								  conkey, conpfeqop, conppeqop, conffeqop,
 								  numfkdelsetcols, confdelsetcols, false,
-								  constrForm->conperiod);
+								  constrForm->conperiod, &conname_pass);
 		/* ... and recurse */
 		addFkRecurseReferenced(fkconstraint,
 							   fkRel,
@@ -12136,7 +12155,8 @@ CloneFkReferenced(Relation parentRel, Relation partitionRel)
 							   true,
 							   deleteTriggerOid,
 							   updateTriggerOid,
-							   constrForm->conperiod);
+							   constrForm->conperiod,
+							   &conname_pass);
 
 		table_close(fkRel, NoLock);
 		ReleaseSysCache(tuple);
@@ -12363,7 +12383,7 @@ CloneFkReferencing(List **wqueue, Relation parentRel, Relation partRel)
 								  mapped_conkey, conpfeqop,
 								  conppeqop, conffeqop,
 								  numfkdelsetcols, confdelsetcols,
-								  false, with_period);
+								  false, with_period, NULL);
 
 		/* Done with the cloned constraint's tuple */
 		ReleaseSysCache(tuple);
@@ -22650,6 +22670,7 @@ DetachPartitionFinalize(Relation rel, Relation partRel, bool concurrent,
 			int			numfkdelsetcols;
 			AttrNumber	confdelsetcols[INDEX_MAX_KEYS];
 			Relation	refdRel;
+			int			conname_pass = 0;
 
 			DeconstructFkConstraintRow(contup,
 									   &numfks,
@@ -22710,7 +22731,8 @@ DetachPartitionFinalize(Relation rel, Relation partRel, bool concurrent,
 								   confdelsetcols,
 								   true,
 								   InvalidOid, InvalidOid,
-								   conform->conperiod);
+								   conform->conperiod,
+								   &conname_pass);
 			table_close(refdRel, NoLock);	/* keep lock till end of xact */
 		}
 
diff --git a/src/include/catalog/pg_constraint.h b/src/include/catalog/pg_constraint.h
index e0e55b0..58894be 100644
--- a/src/include/catalog/pg_constraint.h
+++ b/src/include/catalog/pg_constraint.h
@@ -263,6 +263,9 @@ extern bool ConstraintNameExists(const char *conname, Oid namespaceid);
 extern char *ChooseConstraintName(const char *name1, const char *name2,
 								  const char *label, Oid namespaceid,
 								  List *others);
+extern char *ChooseConstraintNameExtended(const char *name1, const char *name2,
+										  const char *label, Oid namespaceid,
+										  List *others, int *passp);
 
 extern HeapTuple findNotNullConstraintAttnum(Oid relid, AttrNumber attnum);
 extern HeapTuple findNotNullConstraint(Oid relid, const char *colname);
diff --git a/src/test/regress/expected/foreign_key.out b/src/test/regress/expected/foreign_key.out
index 95a0531..701d097 100644
--- a/src/test/regress/expected/foreign_key.out
+++ b/src/test/regress/expected/foreign_key.out
@@ -3699,6 +3699,43 @@ DETAIL:  drop cascades to table fkpart13_t1
 drop cascades to table fkpart13_t2
 drop cascades to table fkpart13_t3
 RESET search_path;
+-- The constraint rows created for each partition of a referenced partitioned
+-- table get the lowest suffix not taken in the schema, even when a name in the
+-- middle of the sequence is already taken, across levels of partitioning, and
+-- for a partition attached later.
+CREATE SCHEMA fkpart14;
+SET search_path TO fkpart14;
+CREATE TABLE pk (a int PRIMARY KEY) PARTITION BY RANGE (a);
+CREATE TABLE pk1 PARTITION OF pk FOR VALUES FROM (1) TO (2);
+CREATE TABLE pk2 PARTITION OF pk FOR VALUES FROM (2) TO (3);
+CREATE TABLE pk3 PARTITION OF pk FOR VALUES FROM (3) TO (5) PARTITION BY RANGE (a);
+CREATE TABLE pk31 PARTITION OF pk3 FOR VALUES FROM (3) TO (4);
+CREATE TABLE pk32 PARTITION OF pk3 FOR VALUES FROM (4) TO (5);
+CREATE TABLE pk4 PARTITION OF pk FOR VALUES FROM (5) TO (6);
+CREATE TABLE other (a int CONSTRAINT fk_a_fkey_3 CHECK (a > 0));
+CREATE TABLE fk (a int REFERENCES pk);
+CREATE TABLE pk5 (a int PRIMARY KEY);
+ALTER TABLE pk ATTACH PARTITION pk5 FOR VALUES FROM (6) TO (7);
+SELECT conname, confrelid::regclass FROM pg_constraint
+WHERE conrelid = 'fk'::regclass ORDER BY conname COLLATE "C";
+   conname   | confrelid 
+-------------+-----------
+ fk_a_fkey   | pk
+ fk_a_fkey_1 | pk1
+ fk_a_fkey_2 | pk2
+ fk_a_fkey_4 | pk3
+ fk_a_fkey_5 | pk31
+ fk_a_fkey_6 | pk32
+ fk_a_fkey_7 | pk4
+ fk_a_fkey_8 | pk5
+(8 rows)
+
+DROP SCHEMA fkpart14 CASCADE;
+NOTICE:  drop cascades to 3 other objects
+DETAIL:  drop cascades to table pk
+drop cascades to table other
+drop cascades to table fk
+RESET search_path;
 -- Test the fast-path ALTER TABLE validation path.  RLS on the referenced
 -- table makes RI_Initial_Check() decline the set-based check, so validation
 -- invokes the RI trigger once per referencing row.
diff --git a/src/test/regress/sql/foreign_key.sql b/src/test/regress/sql/foreign_key.sql
index 65b68f4..1b7e35a 100644
--- a/src/test/regress/sql/foreign_key.sql
+++ b/src/test/regress/sql/foreign_key.sql
@@ -2672,6 +2672,28 @@ WITH cte AS (
 DROP SCHEMA fkpart13 CASCADE;
 RESET search_path;
 
+-- The constraint rows created for each partition of a referenced partitioned
+-- table get the lowest suffix not taken in the schema, even when a name in the
+-- middle of the sequence is already taken, across levels of partitioning, and
+-- for a partition attached later.
+CREATE SCHEMA fkpart14;
+SET search_path TO fkpart14;
+CREATE TABLE pk (a int PRIMARY KEY) PARTITION BY RANGE (a);
+CREATE TABLE pk1 PARTITION OF pk FOR VALUES FROM (1) TO (2);
+CREATE TABLE pk2 PARTITION OF pk FOR VALUES FROM (2) TO (3);
+CREATE TABLE pk3 PARTITION OF pk FOR VALUES FROM (3) TO (5) PARTITION BY RANGE (a);
+CREATE TABLE pk31 PARTITION OF pk3 FOR VALUES FROM (3) TO (4);
+CREATE TABLE pk32 PARTITION OF pk3 FOR VALUES FROM (4) TO (5);
+CREATE TABLE pk4 PARTITION OF pk FOR VALUES FROM (5) TO (6);
+CREATE TABLE other (a int CONSTRAINT fk_a_fkey_3 CHECK (a > 0));
+CREATE TABLE fk (a int REFERENCES pk);
+CREATE TABLE pk5 (a int PRIMARY KEY);
+ALTER TABLE pk ATTACH PARTITION pk5 FOR VALUES FROM (6) TO (7);
+SELECT conname, confrelid::regclass FROM pg_constraint
+WHERE conrelid = 'fk'::regclass ORDER BY conname COLLATE "C";
+DROP SCHEMA fkpart14 CASCADE;
+RESET search_path;
+
 -- Test the fast-path ALTER TABLE validation path.  RLS on the referenced
 -- table makes RI_Initial_Check() decline the set-based check, so validation
 -- invokes the RI trigger once per referencing row.
-- 
2.56.1

