From aa70a92408ba967e4e97c53f92e5430e7f8524ee Mon Sep 17 00:00:00 2001
From: MisterRaindrop <278811821@qq.com>
Date: Wed, 22 Jul 2026 18:49:53 +0800
Subject: [PATCH v1] psql: filter system functions before visibility checks in
 \df

---
 src/bin/psql/describe.c     | 26 ++++++++++++++++++++++----
 src/bin/psql/t/001_basic.pl | 12 ++++++++++++
 2 files changed, 34 insertions(+), 4 deletions(-)

diff --git a/src/bin/psql/describe.c b/src/bin/psql/describe.c
index a2f09c26369..9233a9ff1e0 100644
--- a/src/bin/psql/describe.c
+++ b/src/bin/psql/describe.c
@@ -546,6 +546,28 @@ describeFunctions(const char *functypes, const char *func_pattern,
 		appendPQExpBufferStr(&buf, "      )\n");
 	}
 
+	/*
+	 * Use p.pronamespace here, rather than n.nspname, so that the
+	 * system schemas can be filtered during the pg_proc scan, before calling
+	 * pg_function_is_visible().  The latter can populate catalog caches for
+	 * every function it examines.  The ARRAY subquery becomes an InitPlan and
+	 * quietly ignores either schema if it does not exist.
+	 */
+	if (!showSystem && !func_pattern)
+	{
+		if (have_where)
+			appendPQExpBufferStr(&buf, "      AND ");
+		else
+		{
+			appendPQExpBufferStr(&buf, "WHERE ");
+			have_where = true;
+		}
+		appendPQExpBufferStr(&buf,
+							 "p.pronamespace <> ALL (ARRAY(\n"
+							 "        SELECT oid FROM pg_catalog.pg_namespace\n"
+							 "        WHERE nspname IN ('pg_catalog', 'information_schema')))\n");
+	}
+
 	if (!validateSQLNamePattern(&buf, func_pattern, have_where, false,
 								"n.nspname", "p.proname", NULL,
 								"pg_catalog.pg_function_is_visible(p.oid)",
@@ -586,10 +608,6 @@ describeFunctions(const char *functypes, const char *func_pattern,
 		}
 	}
 
-	if (!showSystem && !func_pattern)
-		appendPQExpBufferStr(&buf, "      AND n.nspname <> 'pg_catalog'\n"
-							 "      AND n.nspname <> 'information_schema'\n");
-
 	appendPQExpBufferStr(&buf, "ORDER BY 1, 2, 4;");
 
 	res = PSQLexec(buf.data);
diff --git a/src/bin/psql/t/001_basic.pl b/src/bin/psql/t/001_basic.pl
index bbd330216ae..d972e82a9dd 100644
--- a/src/bin/psql/t/001_basic.pl
+++ b/src/bin/psql/t/001_basic.pl
@@ -75,6 +75,18 @@ $node->start;
 psql_like($node, '\copyright', qr/Copyright/, '\copyright');
 psql_like($node, '\help', qr/ALTER/, '\help without arguments');
 psql_like($node, '\help SELECT', qr/SELECT/, '\help with argument');
+psql_like(
+	$node,
+	'\set ECHO_HIDDEN on
+\df',
+	qr{
+		WHERE \s+ p\.pronamespace \s+ <> \s+ ALL \s+ \(ARRAY\(
+		.*? SELECT \s+ oid \s+ FROM \s+ pg_catalog\.pg_namespace
+		.*? WHERE \s+ nspname \s+ IN \s+
+		\('pg_catalog', \s+ 'information_schema'\)\)\)
+		.*? AND \s+ pg_catalog\.pg_function_is_visible\(p\.oid\)
+	}xs,
+	'\df filters system functions before testing visibility');
 
 # Test clean handling of unsupported replication command responses
 psql_fails_like(
-- 
2.44.0

