From 685a0ae18b545dff29e5ef29fac341cbbc0c0e16 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 v2] Use an index scan in RemoveSubscriptionRel() when
 possible.

Previously this function scanned all of pg_subscription_rel with a
heap scan, even when given a relation OID that the (srrelid, srsubid)
primary key index could serve.  It's called for every dropped
relation, so on a subscriber with a large pg_subscription_rel every
dropped table paid for a full scan.

Use the index when a relation OID is given.  DROP SUBSCRIPTION passes
only a subscription OID, so that path keeps scanning the heap.

Author: Manu <manuelreyesbravo@gmail.com>
Reviewed-by: Masahiko Sawada <sawada.mshk@gmail.com>
Reviewed-by: Chao Li <li.evan.chao@gmail.com>
Discussion: https://postgr.es/m/179489354788.348371.16745415952616502664@gmail.com
---
 src/backend/catalog/pg_subscription.c | 27 ++++++++++++++++-----------
 1 file changed, 16 insertions(+), 11 deletions(-)

diff --git a/src/backend/catalog/pg_subscription.c b/src/backend/catalog/pg_subscription.c
index 60c15b22194..2ae57c056b4 100644
--- a/src/backend/catalog/pg_subscription.c
+++ b/src/backend/catalog/pg_subscription.c
@@ -520,34 +520,39 @@ void
 RemoveSubscriptionRel(Oid subid, Oid relid)
 {
 	Relation	rel;
-	TableScanDesc scan;
+	SysScanDesc scan;
 	ScanKeyData skey[2];
 	HeapTuple	tup;
 	int			nkeys = 0;
 
 	rel = table_open(SubscriptionRelRelationId, RowExclusiveLock);
 
-	if (OidIsValid(subid))
+	if (OidIsValid(relid))
 	{
 		ScanKeyInit(&skey[nkeys++],
-					Anum_pg_subscription_rel_srsubid,
+					Anum_pg_subscription_rel_srrelid,
 					BTEqualStrategyNumber,
 					F_OIDEQ,
-					ObjectIdGetDatum(subid));
+					ObjectIdGetDatum(relid));
 	}
 
-	if (OidIsValid(relid))
+	if (OidIsValid(subid))
 	{
 		ScanKeyInit(&skey[nkeys++],
-					Anum_pg_subscription_rel_srrelid,
+					Anum_pg_subscription_rel_srsubid,
 					BTEqualStrategyNumber,
 					F_OIDEQ,
-					ObjectIdGetDatum(relid));
+					ObjectIdGetDatum(subid));
 	}
 
-	/* Do the search and delete what we found. */
-	scan = table_beginscan_catalog(rel, nkeys, skey);
-	while (HeapTupleIsValid(tup = heap_getnext(scan, ForwardScanDirection)))
+	/*
+	 * Do the search and delete what we found.  Use the (srrelid, srsubid)
+	 * index when relid is given; otherwise (DROP SUBSCRIPTION) there is no
+	 * suitable index, so fall back to a heap scan.
+	 */
+	scan = systable_beginscan(rel, SubscriptionRelSrrelidSrsubidIndexId,
+							  OidIsValid(relid), NULL, nkeys, skey);
+	while (HeapTupleIsValid(tup = systable_getnext(scan)))
 	{
 		Form_pg_subscription_rel subrel;
 
@@ -584,7 +589,7 @@ RemoveSubscriptionRel(Oid subid, Oid relid)
 
 		CatalogTupleDelete(rel, &tup->t_self);
 	}
-	table_endscan(scan);
+	systable_endscan(scan);
 
 	table_close(rel, RowExclusiveLock);
 }
-- 
2.56.0

