On Fri, 27 Nov 2026 at 22:02, Heikki Linnakangas <[email protected]> wrote:
> The table_rescan() seems a bit ugly to me, I'd rather restructure the
> loop slightly to avoid that. Maybe turn it from "while
> (table_scan_getnextslot())" into "do {} while(table_scan_getnextslot())"
>
> The comments could use some copy-editing. It mentions "pg_dump
> --schema-only" explicitly, but I think it's even more generally true
> that the table is likely to be empty. And the comment about temporal FKs
> seems misplaced now, that should still be above the "if (!hasperiod)" check.

Thanks for looking. Updated patch attached.

David
From d40dca4d15bf81b3fb66b01360b168ecef427768 Mon Sep 17 00:00:00 2001
From: David Rowley <[email protected]>
Date: Thu, 26 Nov 2026 15:34:17 +1300
Subject: [PATCH v2] Add precheck any referencing rows when adding a FOREIGN
 KEY

We check for violations when adding new FOREIGN KEY constraints by
running an SPI query.  During pg_upgrade's schema restore, adding all the
foreign keys could be costly, especially so when the referenced table is
partitioned, as even with empty tables, there's a large overhead in terms
of planning and executor startup/shutdown.

Here we add a cheap precheck to first check if the referencing table has
any rows before running the SPI query.  This adds a tiny extra cost when
the table is non-empty, but can save a huge amount of effort for empty
tables.

Discussion: 
https://postgr.es/m/caaphdvqwnjmaqowh31d8qow9pozivzowd17vsgfpezdmcht...@mail.gmail.com
---
 src/backend/commands/tablecmds.c | 45 ++++++++++++++++++++------------
 1 file changed, 29 insertions(+), 16 deletions(-)

diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c
index 9e363a44c20..9755943f110 100644
--- a/src/backend/commands/tablecmds.c
+++ b/src/backend/commands/tablecmds.c
@@ -14801,20 +14801,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
-        * ereport(ERROR) and that's that.
-        */
        snapshot = RegisterSnapshot(GetLatestSnapshot());
        slot = table_slot_create(rel, NULL);
        scan = table_beginscan(rel, snapshot, 0, NULL,
@@ -14824,7 +14810,33 @@ validateForeignKeyConstraint(char *conname,
                                                                          
ALLOCSET_SMALL_SIZES);
        oldcxt = MemoryContextSwitchTo(perTupCxt);
 
-       while (table_scan_getnextslot(scan, ForwardScanDirection, slot))
+       /*
+        * For non-temporal FKs, we use a LEFT JOIN SPI query to check for 
foreign
+        * key violations, checking if the referencing table contains rows not 
in
+        * the referenced table.  Because creating foreign keys on empty tables 
is
+        * common, it's worth checking to see if the referencing table has any
+        * rows before we go to the trouble of running the SPI query.  If the
+        * referenced table is partitioned, then the SPI query can be expensive 
to
+        * plan and go through executor startup/shutdown, so checking for 0 rows
+        * can be a significant shortcut.
+        */
+       if (!table_scan_getnextslot(scan, ForwardScanDirection, slot))
+               goto cleanup;
+
+       /*
+        * A false result from RI_Initial_Check() 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))
+               goto cleanup;
+
+       /*
+        * 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
+        * ereport(ERROR) and that's that.
+        */
+       do
        {
                LOCAL_FCINFO(fcinfo, 0);
                TriggerData trigdata = {0};
@@ -14853,8 +14865,9 @@ validateForeignKeyConstraint(char *conname,
                RI_FKey_check_ins(fcinfo);
 
                MemoryContextReset(perTupCxt);
-       }
+       } while (table_scan_getnextslot(scan, ForwardScanDirection, slot));
 
+cleanup:
        MemoryContextSwitchTo(oldcxt);
        MemoryContextDelete(perTupCxt);
        table_endscan(scan);
-- 
2.53.0

Reply via email to