From cd801605381a33c31730bdad4ae0d0fc31fdf32d Mon Sep 17 00:00:00 2001
From: Manuel Reyes Bravo <manuelreyesbravo@gmail.com>
Date: Fri, 13 Nov 2026 17:11:29 -0300
Subject: [PATCH v1 1/3] Avoid repeated foreign key lookups in TRUNCATE CASCADE

ExecuteTruncateGuts() calls heap_truncate_find_FKs() once per level of
references, and passed it the whole, growing list of relations, so each
level looked up again the referencers of every relation found so far:
for a chain of N tables, N lookups of up to N relations.  Pass it only
the relations added at the previous level instead.  The referencers of
the others are already in the list, so each level adds the same
relations as before, in the same order.  A relation can be found again,
for example through a cycle of foreign keys; skip it.  Add a test where
the cascade reaches such a cycle.

Discussion: https://postgr.es/m/avXKHF359xUI1AVE@alvherre.pgsql
---
 src/backend/commands/tablecmds.c       | 18 ++++++++++++++----
 src/test/regress/expected/truncate.out | 26 ++++++++++++++++++++++++++
 src/test/regress/sql/truncate.sql      | 18 ++++++++++++++++++
 3 files changed, 58 insertions(+), 4 deletions(-)

diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c
index b670092..7bbc26b 100644
--- a/src/backend/commands/tablecmds.c
+++ b/src/backend/commands/tablecmds.c
@@ -2055,19 +2055,28 @@ ExecuteTruncateGuts(List *explicit_rels,
 	rels = list_copy(explicit_rels);
 	if (behavior == DROP_CASCADE)
 	{
-		for (;;)
+		List	   *pending = list_copy(relids);
+
+		/*
+		 * Each iteration only needs the referencers of the rels added by the
+		 * previous one; those of older rels were already added.
+		 */
+		while (pending != NIL)
 		{
 			List	   *newrelids;
 
-			newrelids = heap_truncate_find_FKs(relids);
-			if (newrelids == NIL)
-				break;			/* nothing else to add */
+			newrelids = heap_truncate_find_FKs(pending);
+			list_free(pending);
+			pending = NIL;
 
 			foreach(cell, newrelids)
 			{
 				Oid			relid = lfirst_oid(cell);
 				Relation	rel;
 
+				if (list_member_oid(relids, relid))
+					continue;
+
 				rel = table_open(relid, AccessExclusiveLock);
 				ereport(NOTICE,
 						(errmsg("truncate cascades to table \"%s\"",
@@ -2077,6 +2086,7 @@ ExecuteTruncateGuts(List *explicit_rels,
 				truncate_check_activity(rel);
 				rels = lappend(rels, rel);
 				relids = lappend_oid(relids, relid);
+				pending = lappend_oid(pending, relid);
 
 				/* Log this relation only if needed for logical decoding */
 				if (RelationIsLogicallyLogged(rel))
diff --git a/src/test/regress/expected/truncate.out b/src/test/regress/expected/truncate.out
index 1e88e86..5d83da6 100644
--- a/src/test/regress/expected/truncate.out
+++ b/src/test/regress/expected/truncate.out
@@ -138,6 +138,32 @@ SELECT * FROM trunc_e;
 (0 rows)
 
 DROP TABLE truncate_a,trunc_c,trunc_b,trunc_d,trunc_e CASCADE;
+-- TRUNCATE ... CASCADE reaching a cycle of foreign keys: trunc_cyc_b is
+-- found through trunc_cyc_a, and trunc_cyc_a references it back
+CREATE TABLE trunc_cyc_r (id int PRIMARY KEY);
+CREATE TABLE trunc_cyc_a (id int PRIMARY KEY, r int REFERENCES trunc_cyc_r, b int);
+CREATE TABLE trunc_cyc_b (id int PRIMARY KEY, a int REFERENCES trunc_cyc_a);
+ALTER TABLE trunc_cyc_a ADD FOREIGN KEY (b) REFERENCES trunc_cyc_b;
+INSERT INTO trunc_cyc_r VALUES (1);
+INSERT INTO trunc_cyc_a VALUES (1, 1, NULL);
+INSERT INTO trunc_cyc_b VALUES (1, 1);
+UPDATE trunc_cyc_a SET b = 1;
+TRUNCATE TABLE trunc_cyc_r CASCADE;
+NOTICE:  truncate cascades to table "trunc_cyc_a"
+NOTICE:  truncate cascades to table "trunc_cyc_b"
+SELECT count(*) FROM trunc_cyc_r
+   UNION ALL
+ SELECT count(*) FROM trunc_cyc_a
+   UNION ALL
+ SELECT count(*) FROM trunc_cyc_b;
+ count 
+-------
+     0
+     0
+     0
+(3 rows)
+
+DROP TABLE trunc_cyc_r, trunc_cyc_a, trunc_cyc_b;
 -- Test TRUNCATE with inheritance
 CREATE TABLE trunc_f (col1 integer primary key);
 INSERT INTO trunc_f VALUES (1);
diff --git a/src/test/regress/sql/truncate.sql b/src/test/regress/sql/truncate.sql
index 54f26e3..0a902bd 100644
--- a/src/test/regress/sql/truncate.sql
+++ b/src/test/regress/sql/truncate.sql
@@ -78,6 +78,24 @@ SELECT * FROM trunc_e;
 
 DROP TABLE truncate_a,trunc_c,trunc_b,trunc_d,trunc_e CASCADE;
 
+-- TRUNCATE ... CASCADE reaching a cycle of foreign keys: trunc_cyc_b is
+-- found through trunc_cyc_a, and trunc_cyc_a references it back
+CREATE TABLE trunc_cyc_r (id int PRIMARY KEY);
+CREATE TABLE trunc_cyc_a (id int PRIMARY KEY, r int REFERENCES trunc_cyc_r, b int);
+CREATE TABLE trunc_cyc_b (id int PRIMARY KEY, a int REFERENCES trunc_cyc_a);
+ALTER TABLE trunc_cyc_a ADD FOREIGN KEY (b) REFERENCES trunc_cyc_b;
+INSERT INTO trunc_cyc_r VALUES (1);
+INSERT INTO trunc_cyc_a VALUES (1, 1, NULL);
+INSERT INTO trunc_cyc_b VALUES (1, 1);
+UPDATE trunc_cyc_a SET b = 1;
+TRUNCATE TABLE trunc_cyc_r CASCADE;
+SELECT count(*) FROM trunc_cyc_r
+   UNION ALL
+ SELECT count(*) FROM trunc_cyc_a
+   UNION ALL
+ SELECT count(*) FROM trunc_cyc_b;
+DROP TABLE trunc_cyc_r, trunc_cyc_a, trunc_cyc_b;
+
 -- Test TRUNCATE with inheritance
 
 CREATE TABLE trunc_f (col1 integer primary key);
-- 
2.56.1

