On 25/11/2026 00:10, David Rowley wrote:
I've been investigating some internally reported pg_upgrade slowness.
The schema I was given (attached) creates a few highly partitioned
tables and foreign keys that reference some partitioned tables.

A big part of pg_upgrade slowness is the schema restore on the target
instance. The problem from the SPI call for the foreign key check
planning and executing the query to the referenced partitioned table.
There's quite a bit of planner and executor startup/shutdown work when
there's lots of partitions.

What I'm wondering now is if we should just skip the foreign key
checks when IsBinaryUpgrade == true. We expect all tables to be empty
in that case, so I'm not sure there's any point in doing the checks.
One problem might be that, in theory, someone could run postgres
directly without using pg_ctl and pass the -b flag to run in binary
upgrade mode and create a valid foreign key with violations.

Another thing I considered was if we were to modify pg_dump to put the
foreign key constraints inside the CREATE TABLE statements. In that
case, we don't do the validation because the table is empty.  The
problem there is dependencies. The referenced table must exist, and
the unique/PK index must exist too. There's also a problem with
circular FKs where tables reference each other. i.e. probably a
nightmare and a constant source of bug reports.

The test case I'm working with is attached. Running pg_upgrade on master with:

pg_upgrade -d pgdata -D pgdata_new -b ~/pg/bin -B ~/pg/bin | ts
'%Y-%m-%dT%H:%M:%S%z'

master:

2026-11-24T18:20:21+1300 Restoring global objects in the new cluster
                 ok
2026-11-24T18:35:26+1300 Restoring database schemas in the new cluster
                 ok (15:05)

Skip FK validation patch:

2026-11-24T18:42:24+1300 Restoring global objects in the new cluster
                 ok
2026-11-24T18:52:15+1300 Restoring database schemas in the new cluster
                 ok (9:51)

So the patch knocks about 35% off the runtime of restoring the schema.

35% sounds nice..

I'm hesitant to add special cases like this for pg_upgrade, though. Could you could optimize validateForeignKeyConstraint() for the case of an empty table, whether it's part of pg_upgrade or not? That would also help plain pg_dump/restore.

For example, you could first do a quick check to see if the table is completely empty, before starting up the SPI query. Something like the attached quick prototype. (I first tried calling table_relation_estimate_size(), but that returns a dummy, constant estimate rather than 0 for an empty table that hasn't been vacuumed yet.)

Playing with that schema, I noticed a lot of time is also spent in ChooseConstraintName(). I recall seeing a separate thread about that, though.

- Heikki
diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c
index 9786a5af58a..805963f8bda 100644
--- a/src/backend/commands/tablecmds.c
+++ b/src/backend/commands/tablecmds.c
@@ -14823,6 +14823,7 @@ validateForeignKeyConstraint(char *conname,
 	Snapshot	snapshot;
 	MemoryContext oldcxt;
 	MemoryContext perTupCxt;
+	bool		first;
 
 	ereport(DEBUG1,
 			(errmsg_internal("validating foreign key constraint \"%s\"", conname)));
@@ -14841,15 +14842,6 @@ validateForeignKeyConstraint(char *conname,
 	trig.tginitdeferred = false;
 	/* we needn't fill in remaining fields */
 
-	/*
-	 * See if we can do it with a single LEFT JOIN query.  A false result
-	 * indicates we must proceed with the fire-the-trigger method. We can't do
-	 * a LEFT JOIN for temporal FKs yet, but we can once we support temporal
-	 * left joins.
-	 */
-	if (!hasperiod && RI_Initial_Check(&trig, rel, pkrel))
-		return;
-
 	/*
 	 * Scan through each tuple, calling RI_FKey_check_ins (insert trigger) as
 	 * if that tuple had just been inserted.  If any of those fail, it should
@@ -14864,6 +14856,7 @@ validateForeignKeyConstraint(char *conname,
 									  ALLOCSET_SMALL_SIZES);
 	oldcxt = MemoryContextSwitchTo(perTupCxt);
 
+	first = true;
 	while (table_scan_getnextslot(scan, ForwardScanDirection, slot))
 	{
 		LOCAL_FCINFO(fcinfo, 0);
@@ -14871,6 +14864,24 @@ validateForeignKeyConstraint(char *conname,
 
 		CHECK_FOR_INTERRUPTS();
 
+		/*
+		 * On the first iteration, see if we can do the whole check with a
+		 * single LEFT JOIN query.  A false result indicates we must proceed
+		 * with the fire-the-trigger method. We can't do a LEFT JOIN for
+		 * temporal FKs yet, but we can once we support temporal left joins.
+		 *
+		 * We try this only after opening the table and confirming that it has
+		 * at least one row, to avoid the overhead of firing up the
+		 * planner/executor for the common special case that the table is
+		 * completely empty.
+		 */
+		if (first)
+		{
+			if (!hasperiod && RI_Initial_Check(&trig, rel, pkrel))
+				break;
+			first = false;
+		}
+
 		/*
 		 * Make a call to the trigger function
 		 *

Reply via email to