From 871e05438526c4d75313c93db9a1639adb2cfa1d 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 3/3] Use the confrelid index in heap_truncate_find_FKs()
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

heap_truncate_find_FKs(), which heap_truncate_check_FKs() uses for
TRUNCATE and for ON COMMIT DELETE ROWS at commit, still scanned all of
pg_constraint.  Look up all the relations of its list in one scan of
the confrelid index, with confrelid = ANY (array), so that only the
foreign keys referencing the list are visited.  One scan rather than a
probe per relation, because each probe pays for setting up an index
scan.  When the function climbs to a partitioned parent constraint, the
extra pass looks up only the relations that adds.

Add a test to unsafe_tests that runs these lookups with
ignore_system_indexes, through the heap scan path of
systable_beginscan().

In a nearly empty database a long list still costs a little more than
the old seqscan: with 1,000 ON COMMIT DELETE ROWS temporary tables that
have triggers, a commit costs about 3% more (under 1M instructions).

Suggested-by: Álvaro Herrera <alvherre@kurilemu.de>
Discussion: https://postgr.es/m/avXKHF359xUI1AVE@alvherre.pgsql
---
 src/backend/catalog/heap.c                    | 39 +++++++++++----
 src/test/modules/unsafe_tests/Makefile        |  2 +-
 .../expected/truncate_heapscan.out            | 47 +++++++++++++++++++
 src/test/modules/unsafe_tests/meson.build     |  1 +
 .../unsafe_tests/sql/truncate_heapscan.sql    | 26 ++++++++++
 5 files changed, 104 insertions(+), 11 deletions(-)
 create mode 100644 src/test/modules/unsafe_tests/expected/truncate_heapscan.out
 create mode 100644 src/test/modules/unsafe_tests/sql/truncate_heapscan.sql

diff --git a/src/backend/catalog/heap.c b/src/backend/catalog/heap.c
index c8ec7b4..03bfdaa 100644
--- a/src/backend/catalog/heap.c
+++ b/src/backend/catalog/heap.c
@@ -4107,13 +4107,21 @@ heap_truncate_find_FKs(List *relationIds)
 	SysScanDesc fkeyScan;
 	HeapTuple	tuple;
 	bool		restart;
+	Datum	   *elems;
+	int			nelems;
+	int			nsearched = 0;
+	ArrayType  *arr;
 
 	oids = list_copy(relationIds);
 
 	/*
-	 * Must scan pg_constraint.  It is a seqscan although confrelid is
-	 * indexed, because probing the index once for each relation in the list
-	 * costs more than one pass over a small catalog.
+	 * Must scan pg_constraint.  Look up all the relations in our list in one
+	 * scan of the index on confrelid, which is only set nonzero by FK
+	 * constraints, so we visit just the foreign keys that reference our list.
+	 * One scan with confrelid = ANY rather than a probe per relation, because
+	 * each probe pays for setting up an index scan, which adds up for long
+	 * lists such as those of ON COMMIT DELETE ROWS.  A restart only needs to
+	 * look up the relations added since the previous pass.
 	 */
 	fkeyRel = table_open(ConstraintRelationId, AccessShareLock);
 
@@ -4121,21 +4129,30 @@ restart:
 	restart = false;
 	parent_cons = NIL;
 
-	fkeyScan = systable_beginscan(fkeyRel, InvalidOid, false,
-								  NULL, 0, NULL);
+	/* confrelid = ANY (the relations not looked up yet) */
+	elems = palloc_array(Datum, list_length(oids) - nsearched);
+	nelems = 0;
+	for_each_from(cell, oids, nsearched)
+		elems[nelems++] = ObjectIdGetDatum(lfirst_oid(cell));
+	nsearched = list_length(oids);
+	arr = construct_array_builtin(elems, nelems, OIDOID);
+	ScanKeyInit(&key,
+				Anum_pg_constraint_confrelid,
+				BTEqualStrategyNumber, F_OIDEQ,
+				PointerGetDatum(arr));
+	key.sk_flags |= SK_SEARCHARRAY;
+
+	fkeyScan = systable_beginscan(fkeyRel, ConstraintForeignRelIndexId,
+								  true, NULL, 1, &key);
 
 	while (HeapTupleIsValid(tuple = systable_getnext(fkeyScan)))
 	{
 		Form_pg_constraint con = (Form_pg_constraint) GETSTRUCT(tuple);
 
-		/* Not a foreign key */
+		/* Only foreign keys set confrelid, but check anyway */
 		if (con->contype != CONSTRAINT_FOREIGN)
 			continue;
 
-		/* Not referencing one of our list of tables */
-		if (!list_member_oid(oids, con->confrelid))
-			continue;
-
 		/*
 		 * If this constraint has a parent constraint which we have not seen
 		 * yet, keep track of it for the second loop, below.  Tracking parent
@@ -4155,6 +4172,8 @@ restart:
 	}
 
 	systable_endscan(fkeyScan);
+	pfree(arr);
+	pfree(elems);
 
 	/*
 	 * Process each parent constraint we found to add the list of referenced
diff --git a/src/test/modules/unsafe_tests/Makefile b/src/test/modules/unsafe_tests/Makefile
index a85c854..003cd22 100644
--- a/src/test/modules/unsafe_tests/Makefile
+++ b/src/test/modules/unsafe_tests/Makefile
@@ -1,6 +1,6 @@
 # src/test/modules/unsafe_tests/Makefile
 
-REGRESS = rolenames setconfig alter_system_table guc_privs
+REGRESS = rolenames setconfig alter_system_table guc_privs truncate_heapscan
 REGRESS_OPTS = \
 	--create-role=regress_authenticated_user_db_sr \
 	--create-role=regress_authenticated_user_db_ssa \
diff --git a/src/test/modules/unsafe_tests/expected/truncate_heapscan.out b/src/test/modules/unsafe_tests/expected/truncate_heapscan.out
new file mode 100644
index 0000000..5fda65d
--- /dev/null
+++ b/src/test/modules/unsafe_tests/expected/truncate_heapscan.out
@@ -0,0 +1,47 @@
+--
+-- TRUNCATE foreign key lookups through the heap scan of pg_constraint
+-- (ignore_system_indexes), where systable_beginscan() has to check the
+-- confrelid = ANY key itself.
+--
+CREATE TABLE trunc_isi_a (id int PRIMARY KEY) PARTITION BY RANGE (id);
+CREATE TABLE trunc_isi_a1 PARTITION OF trunc_isi_a FOR VALUES FROM (0) TO (10);
+CREATE TABLE trunc_isi_b (id int PRIMARY KEY, a int REFERENCES trunc_isi_a)
+  PARTITION BY RANGE (id);
+CREATE TABLE trunc_isi_b1 PARTITION OF trunc_isi_b FOR VALUES FROM (0) TO (10);
+CREATE TABLE trunc_isi_c (b int REFERENCES trunc_isi_b);
+INSERT INTO trunc_isi_a VALUES (1);
+INSERT INTO trunc_isi_b VALUES (1, 1);
+INSERT INTO trunc_isi_c VALUES (1);
+-- ignore_system_indexes only takes effect at connection start.  Only SHOW,
+-- the TRUNCATEs and a count run with it: DDL may use an index anyway and
+-- warn.
+\c -reuse-previous=on "options=-cignore_system_indexes=on"
+SHOW ignore_system_indexes;
+ ignore_system_indexes 
+-----------------------
+ on
+(1 row)
+
+TRUNCATE trunc_isi_a1, trunc_isi_b1;  -- fail
+ERROR:  cannot truncate a table referenced in a foreign key constraint
+DETAIL:  Table "trunc_isi_b" references "trunc_isi_a1".
+HINT:  Truncate table "trunc_isi_b" at the same time, or use TRUNCATE ... CASCADE.
+TRUNCATE trunc_isi_a1 CASCADE;
+NOTICE:  truncate cascades to table "trunc_isi_b"
+NOTICE:  truncate cascades to table "trunc_isi_b1"
+NOTICE:  truncate cascades to table "trunc_isi_c"
+SELECT (SELECT count(*) FROM trunc_isi_a) + (SELECT count(*) FROM trunc_isi_b) +
+       (SELECT count(*) FROM trunc_isi_c) AS rows_left;
+ rows_left 
+-----------
+         0
+(1 row)
+
+\c -reuse-previous=on "options="
+SHOW ignore_system_indexes;
+ ignore_system_indexes 
+-----------------------
+ off
+(1 row)
+
+DROP TABLE trunc_isi_a, trunc_isi_b, trunc_isi_c;
diff --git a/src/test/modules/unsafe_tests/meson.build b/src/test/modules/unsafe_tests/meson.build
index 8217bbe..0209399 100644
--- a/src/test/modules/unsafe_tests/meson.build
+++ b/src/test/modules/unsafe_tests/meson.build
@@ -10,6 +10,7 @@ tests += {
       'setconfig',
       'alter_system_table',
       'guc_privs',
+      'truncate_heapscan',
     ],
     'regress_args': ['--create-role=regress_authenticated_user_db_sr',
                      '--create-role=regress_authenticated_user_db_ssa',
diff --git a/src/test/modules/unsafe_tests/sql/truncate_heapscan.sql b/src/test/modules/unsafe_tests/sql/truncate_heapscan.sql
new file mode 100644
index 0000000..618e5a2
--- /dev/null
+++ b/src/test/modules/unsafe_tests/sql/truncate_heapscan.sql
@@ -0,0 +1,26 @@
+--
+-- TRUNCATE foreign key lookups through the heap scan of pg_constraint
+-- (ignore_system_indexes), where systable_beginscan() has to check the
+-- confrelid = ANY key itself.
+--
+CREATE TABLE trunc_isi_a (id int PRIMARY KEY) PARTITION BY RANGE (id);
+CREATE TABLE trunc_isi_a1 PARTITION OF trunc_isi_a FOR VALUES FROM (0) TO (10);
+CREATE TABLE trunc_isi_b (id int PRIMARY KEY, a int REFERENCES trunc_isi_a)
+  PARTITION BY RANGE (id);
+CREATE TABLE trunc_isi_b1 PARTITION OF trunc_isi_b FOR VALUES FROM (0) TO (10);
+CREATE TABLE trunc_isi_c (b int REFERENCES trunc_isi_b);
+INSERT INTO trunc_isi_a VALUES (1);
+INSERT INTO trunc_isi_b VALUES (1, 1);
+INSERT INTO trunc_isi_c VALUES (1);
+-- ignore_system_indexes only takes effect at connection start.  Only SHOW,
+-- the TRUNCATEs and a count run with it: DDL may use an index anyway and
+-- warn.
+\c -reuse-previous=on "options=-cignore_system_indexes=on"
+SHOW ignore_system_indexes;
+TRUNCATE trunc_isi_a1, trunc_isi_b1;  -- fail
+TRUNCATE trunc_isi_a1 CASCADE;
+SELECT (SELECT count(*) FROM trunc_isi_a) + (SELECT count(*) FROM trunc_isi_b) +
+       (SELECT count(*) FROM trunc_isi_c) AS rows_left;
+\c -reuse-previous=on "options="
+SHOW ignore_system_indexes;
+DROP TABLE trunc_isi_a, trunc_isi_b, trunc_isi_c;
-- 
2.56.1

