pg.ddx.io  pgsql-hackers@postgresql.org mailing list archive  
help / color / mirror / Atom feed
Many of psql's describe functions bloat cache / waste mem
8+ messages / 4 participants
[nested] [flat]

* Many of psql's describe functions bloat cache / waste mem
@ 2026-07-20 21:25 Andres Freund <andres@anarazel.de>
  2026-07-22 11:55 ` Re: Many of psql's describe functions bloat cache / waste mem xiaoyu liu <xliu19163@gmail.com>
  0 siblings, 1 reply; 8+ messages in thread

From: Andres Freund @ 2026-07-20 21:25 UTC (permalink / raw)
  To: pgsql-hackers

Hi,

I was just looking at an memory usage issue and noticed that a single '\df' in
a database without any user-defined functions, increases backend memory usage
by ~7MB.

Turns out the fault of that is psql's query, which populates the catcaches for
every function in the system:

empty[817089][1]=# explain ANALYZE /**** INTERNAL QUERY ****/
/* Get matching functions */
SELECT n.nspname as "Schema",
  p.proname as "Name",
  pg_catalog.pg_get_function_result(p.oid) as "Result data type",
  pg_catalog.pg_get_function_arguments(p.oid) as "Argument data types",
 CASE p.prokind
  WHEN 'a' THEN 'agg'
  WHEN 'w' THEN 'window'
  WHEN 'p' THEN 'proc'
  ELSE 'func'
 END as "Type"
FROM pg_catalog.pg_proc p
     LEFT JOIN pg_catalog.pg_namespace n ON n.oid = p.pronamespace
WHERE pg_catalog.pg_function_is_visible(p.oid)
      AND n.nspname <> 'pg_catalog'
      AND n.nspname <> 'information_schema'
ORDER BY 1, 2, 4;
┌──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
│                                                          QUERY PLAN                                                          │
├──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┤
│ Sort  (cost=269.17..270.89 rows=688 width=224) (actual time=37.135..37.137 rows=0.00 loops=1)                                │
│   Sort Key: n.nspname, p.proname, (pg_get_function_arguments(p.oid))                                                         │
│   Sort Method: quicksort  Memory: 25kB                                                                                       │
│   Buffers: shared hit=19100                                                                                                  │
│   ->  Hash Join  (cost=1.11..236.74 rows=688 width=224) (actual time=37.089..37.090 rows=0.00 loops=1)                       │
│         Hash Cond: (p.pronamespace = n.oid)                                                                                  │
│         Buffers: shared hit=19094                                                                                            │
│         ->  Seq Scan on pg_proc p  (cost=0.00..221.47 rows=1147 width=73) (actual time=0.040..36.613 rows=3431.00 loops=1)   │
│               Filter: pg_function_is_visible(oid)                                                                            │
│               Rows Removed by Filter: 11                                                                                     │
│               Buffers: shared hit=19093                                                                                      │
│         ->  Hash  (cost=1.07..1.07 rows=3 width=68) (actual time=0.009..0.010 rows=3.00 loops=1)                             │
│               Buckets: 1024  Batches: 1  Memory Usage: 9kB                                                                   │
│               Buffers: shared hit=1                                                                                          │
│               ->  Seq Scan on pg_namespace n  (cost=0.00..1.07 rows=3 width=68) (actual time=0.003..0.005 rows=3.00 loops=1) │
│                     Filter: ((nspname <> 'pg_catalog'::name) AND (nspname <> 'information_schema'::name))                    │
│                     Rows Removed by Filter: 2                                                                                │
│                     Buffers: shared hit=1                                                                                    │
│ Planning:                                                                                                                    │
│   Buffers: shared hit=270                                                                                                    │
│ Planning Time: 1.019 ms                                                                                                      │
│ Execution Time: 37.277 ms                                                                                                    │
└──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
(22 rows)


Because the nspname <> 'pg_catalog' condition is not something that can be
evaluated during the sequential scan on pg_proc, pg_function_is_visible() is
executed for every proc. Which in turn ends up trigger the population of the
entire PROCOID *and* PROCNAMEARGSNSP catcaches (because catalog functions are
visible, we end up doing FuncnameGetCandidates for all functions, which in
turn does a list search in PROCNAMEARGSNSP).


(Also, pretty odd this is a left join, given that the filter condition turns
it back into an inner join)


To show the effect:

empty[817815][1]=# SELECT count(*), sum(total_bytes) total_bytes, sum(total_nblocks) total_nblocks FROM pg_backend_memory_contexts WHERE path @> (SELECT path FROM pg_backend_memory_contexts WHERE name = 'CacheMemoryContext');
┌───────┬─────────────┬───────────────┐
│ count │ total_bytes │ total_nblocks │
├───────┼─────────────┼───────────────┤
│    97 │     1251072 │           163 │
└───────┴─────────────┴───────────────┘
(1 row)

empty[817815][1]=# \df
                        List of functions
┌────────┬──────┬──────────────────┬─────────────────────┬──────┐
│ Schema │ Name │ Result data type │ Argument data types │ Type │
├────────┼──────┼──────────────────┼─────────────────────┼──────┤
└────────┴──────┴──────────────────┴─────────────────────┴──────┘
(0 rows)

empty[817815][1]=# SELECT count(*), sum(total_bytes) total_bytes, sum(total_nblocks) total_nblocks FROM pg_backend_memory_contexts WHERE path @> (SELECT path FROM pg_backend_memory_contexts WHERE name = 'CacheMemoryContext');
┌───────┬─────────────┬───────────────┐
│ count │ total_bytes │ total_nblocks │
├───────┼─────────────┼───────────────┤
│   102 │     8705984 │           182 │
└───────┴─────────────┴───────────────┘
(1 row)


I think a lot of psql's queries have this issue, although most of them won't
be as problematic, because pg_proc has a fair number of rows in pg_catalog
(compared to e.g. pg_class, where's an order of magnitude fewer).




If the query instead is rewritten to filter with:

WHERE pg_catalog.pg_function_is_visible(p.oid)
      AND p.pronamespace <> 'pg_catalog'::regnamespace
      AND p.pronamespace <> 'information_schema'::regnamespace

the query is considerably faster (both first and subsequent executions) and
more importantly the memory usage afterwards is:

┌───────┬─────────────┬───────────────┐
│ count │ total_bytes │ total_nblocks │
├───────┼─────────────┼───────────────┤
│   101 │     1264384 │           174 │
└───────┴─────────────┴───────────────┘
(1 row)


I used a regnamespace query here, but because we use patterns etc in some
places, it's probably better done as a subquery.



I don't plan to work on fixing this in the near term, but it seemed like a
significant enough effect to be worth mentioning on the list.


Greetings,

Andres Freund






^ permalink  raw  reply  [nested|flat] 8+ messages in thread

* Re: Many of psql's describe functions bloat cache / waste mem
  2026-07-20 21:25 Many of psql's describe functions bloat cache / waste mem Andres Freund <andres@anarazel.de>
@ 2026-07-22 11:55 ` xiaoyu liu <xliu19163@gmail.com>
  2026-07-24 03:17   ` Re: Many of psql's describe functions bloat cache / waste mem xiaoyu liu <xliu19163@gmail.com>
  0 siblings, 1 reply; 8+ messages in thread

From: xiaoyu liu @ 2026-07-22 11:55 UTC (permalink / raw)
  To: andres@anarazel.de; +Cc: pgsql-hackers

Hi Andres,

Thanks for the report.  Attached is a patch that changes describeFunctions()
so that, when system functions are not requested and no function pattern is
supplied, functions in pg_catalog and information_schema are filtered by
p.pronamespace before pg_function_is_visible() is evaluated.

I used an uncorrelated ARRAY subquery over pg_namespace rather than
regnamespace casts.  In the tested plan it becomes an InitPlan, and it also
avoids an error if information_schema has been dropped.

Using fresh backends built from the same master revision, I measured:

                                  before       after
CacheMemoryContext increase     7,454,912      13,312 bytes
shared buffer hits                 19,105         108
execution time                     10.189       0.304 ms

The default \df result was unchanged (0 rows).  I also tested \dfS, verbose,
schema-qualified and argument-type patterns, search_path changes, same-name
functions in multiple schemas, and a database without information_schema.
The patch adds a TAP test for the generated query, and make check-world
passes.

Review and comments would be appreciated.

Regards,
Xiaoyu



On Mon, 20 Jul 2026 17:25:00 -0400, Andres Freund <andres@anarazel.de> wrote:
> Hi,
>
> I was just looking at an memory usage issue and noticed that a single '\df' in
> a database without any user-defined functions, increases backend memory usage
> by ~7MB.
>
> Turns out the fault of that is psql's query, which populates the catcaches for
> every function in the system:
>
> empty[817089][1]=# explain ANALYZE /**** INTERNAL QUERY ****/
> /* Get matching functions */
> SELECT n.nspname as "Schema",
> p.proname as "Name",
> pg_catalog.pg_get_function_result(p.oid) as "Result data type",
> pg_catalog.pg_get_function_arguments(p.oid) as "Argument data types",
> CASE p.prokind
> WHEN 'a' THEN 'agg'
> WHEN 'w' THEN 'window'
> WHEN 'p' THEN 'proc'
> ELSE 'func'
> END as "Type"
> FROM pg_catalog.pg_proc p
> LEFT JOIN pg_catalog.pg_namespace n ON n.oid = p.pronamespace
> WHERE pg_catalog.pg_function_is_visible(p.oid)
> AND n.nspname <> 'pg_catalog'
> AND n.nspname <> 'information_schema'
> ORDER BY 1, 2, 4;
> ┌──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
> │ QUERY PLAN │
> ├──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┤
> │ Sort (cost=269.17..270.89 rows=688 width=224) (actual time=37.135..37.137 rows=0.00 loops=1) │
> │ Sort Key: n.nspname, p.proname, (pg_get_function_arguments(p.oid)) │
> │ Sort Method: quicksort Memory: 25kB │
> │ Buffers: shared hit=19100 │
> │ -> Hash Join (cost=1.11..236.74 rows=688 width=224) (actual time=37.089..37.090 rows=0.00 loops=1) │
> │ Hash Cond: (p.pronamespace = n.oid) │
> │ Buffers: shared hit=19094 │
> │ -> Seq Scan on pg_proc p (cost=0.00..221.47 rows=1147 width=73) (actual time=0.040..36.613 rows=3431.00 loops=1) │
> │ Filter: pg_function_is_visible(oid) │
> │ Rows Removed by Filter: 11 │
> │ Buffers: shared hit=19093 │
> │ -> Hash (cost=1.07..1.07 rows=3 width=68) (actual time=0.009..0.010 rows=3.00 loops=1) │
> │ Buckets: 1024 Batches: 1 Memory Usage: 9kB │
> │ Buffers: shared hit=1 │
> │ -> Seq Scan on pg_namespace n (cost=0.00..1.07 rows=3 width=68) (actual time=0.003..0.005 rows=3.00 loops=1) │
> │ Filter: ((nspname <> 'pg_catalog'::name) AND (nspname <> 'information_schema'::name)) │
> │ Rows Removed by Filter: 2 │
> │ Buffers: shared hit=1 │
> │ Planning: │
> │ Buffers: shared hit=270 │
> │ Planning Time: 1.019 ms │
> │ Execution Time: 37.277 ms │
> └──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
> (22 rows)
>
> Because the nspname <> 'pg_catalog' condition is not something that can be
> evaluated during the sequential scan on pg_proc, pg_function_is_visible() is
> executed for every proc. Which in turn ends up trigger the population of the
> entire PROCOID *and* PROCNAMEARGSNSP catcaches (because catalog functions are
> visible, we end up doing FuncnameGetCandidates for all functions, which in
> turn does a list search in PROCNAMEARGSNSP).
>
> (Also, pretty odd this is a left join, given that the filter condition turns
> it back into an inner join)
>
> To show the effect:
>
> empty[817815][1]=# SELECT count(*), sum(total_bytes) total_bytes, sum(total_nblocks) total_nblocks FROM pg_backend_memory_contexts WHERE path @> (SELECT path FROM pg_backend_memory_contexts WHERE name = 'CacheMemoryContext');
> ┌───────┬─────────────┬───────────────┐
> │ count │ total_bytes │ total_nblocks │
> ├───────┼─────────────┼───────────────┤
> │ 97 │ 1251072 │ 163 │
> └───────┴─────────────┴───────────────┘
> (1 row)
>
> empty[817815][1]=# \df
> List of functions
> ┌────────┬──────┬──────────────────┬─────────────────────┬──────┐
> │ Schema │ Name │ Result data type │ Argument data types │ Type │
> ├────────┼──────┼──────────────────┼─────────────────────┼──────┤
> └────────┴──────┴──────────────────┴─────────────────────┴──────┘
> (0 rows)
>
> empty[817815][1]=# SELECT count(*), sum(total_bytes) total_bytes, sum(total_nblocks) total_nblocks FROM pg_backend_memory_contexts WHERE path @> (SELECT path FROM pg_backend_memory_contexts WHERE name = 'CacheMemoryContext');
> ┌───────┬─────────────┬───────────────┐
> │ count │ total_bytes │ total_nblocks │
> ├───────┼─────────────┼───────────────┤
> │ 102 │ 8705984 │ 182 │
> └───────┴─────────────┴───────────────┘
> (1 row)
>
> I think a lot of psql's queries have this issue, although most of them won't
> be as problematic, because pg_proc has a fair number of rows in pg_catalog
> (compared to e.g. pg_class, where's an order of magnitude fewer).
>
> If the query instead is rewritten to filter with:
>
> WHERE pg_catalog.pg_function_is_visible(p.oid)
> AND p.pronamespace <> 'pg_catalog'::regnamespace
> AND p.pronamespace <> 'information_schema'::regnamespace
>
> the query is considerably faster (both first and subsequent executions) and
> more importantly the memory usage afterwards is:
>
> ┌───────┬─────────────┬───────────────┐
> │ count │ total_bytes │ total_nblocks │
> ├───────┼─────────────┼───────────────┤
> │ 101 │ 1264384 │ 174 │
> └───────┴─────────────┴───────────────┘
> (1 row)
>
> I used a regnamespace query here, but because we use patterns etc in some
> places, it's probably better done as a subquery.
>
> I don't plan to work on fixing this in the near term, but it seemed like a
> significant enough effect to be worth mentioning on the list.
>
> Greetings,
>
> Andres Freund


Attachments:

v1-0001-psql-filter-system-functions-before-visibility-ch.patch (text/x-diff, 2.8K) download 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
^ permalink raw reply [nested|flat] 8+ messages in thread

* Re: Many of psql's describe functions bloat cache / waste mem
  2026-07-20 21:25 Many of psql's describe functions bloat cache / waste mem Andres Freund <andres@anarazel.de>
  2026-07-22 11:55 ` Re: Many of psql's describe functions bloat cache / waste mem xiaoyu liu <xliu19163@gmail.com>
@ 2026-07-24 03:17   ` xiaoyu liu <xliu19163@gmail.com>
  2026-08-21 14:24     ` Re: Many of psql's describe functions bloat cache / waste mem Jan Nidzwetzki <jan@planetscale.com>
  0 siblings, 1 reply; 8+ messages in thread

From: xiaoyu liu @ 2026-07-24 03:17 UTC (permalink / raw)
  To: andres@anarazel.de; +Cc: pgsql-hackers

Hi,

I plan to register this patch in the next open CommitFest so that it can
enter the regular review queue and be picked up by CFBot.

If anyone has already started reviewing it, or sees an issue with the
current approach, please let me know.

Regards,
Xiaoyu

On Wed, 22 Jul 2026 19:55:50 +0800, xiaoyu liu xliu19163@gmail.com wrote:

Hi Andres,

Thanks for the report. Attached is a patch that changes describeFunctions()
so that, when system functions are not requested and no function pattern is
supplied, functions in pg_catalog and information_schema are filtered by
p.pronamespace before pg_function_is_visible() is evaluated.

I used an uncorrelated ARRAY subquery over pg_namespace rather than
regnamespace casts. In the tested plan it becomes an InitPlan, and it also
avoids an error if information_schema has been dropped.

Using fresh backends built from the same master revision, I measured:

before after
CacheMemoryContext increase 7,454,912 13,312 bytes
shared buffer hits 19,105 108
execution time 10.189 0.304 ms

The default \df result was unchanged (0 rows). I also tested \dfS, verbose,
schema-qualified and argument-type patterns, search_path changes, same-name
functions in multiple schemas, and a database without information_schema.
The patch adds a TAP test for the generated query, and make check-world
passes.

Review and comments would be appreciated.

Regards,
Xiaoyu

On Mon, 20 Jul 2026 17:25:00 -0400, Andres Freund andres@anarazel.de wrote:

Hi,

I was just looking at an memory usage issue and noticed that a single ‘\df’
in
a database without any user-defined functions, increases backend memory
usage
by ~7MB.

Turns out the fault of that is psql’s query, which populates the catcaches
for
every function in the system:

empty[817089][1]=# explain ANALYZE /**** INTERNAL QUERY ***
*/ /* Get matching functions */
SELECT n.nspname as “Schema”,
p.proname as “Name”,
pg_catalog.pg_get_function_result(p.oid) as “Result data type”,
pg_catalog.pg_get_function_arguments(p.oid) as “Argument data types”,
CASE p.prokind
WHEN ‘a’ THEN ‘agg’
WHEN ‘w’ THEN ‘window’
WHEN ‘p’ THEN ‘proc’
ELSE ‘func’
END as “Type”
FROM pg_catalog.pg_proc p
LEFT JOIN pg_catalog.pg_namespace n ON n.oid = p.pronamespace
WHERE pg_catalog.pg_function_is_visible(p.oid)
AND n.nspname <> ‘pg_catalog’
AND n.nspname <> ‘information_schema’
ORDER BY 1, 2, 4;
┌──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
│ QUERY PLAN │
├──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┤
│ Sort (cost=269.17…270.89 rows=688 width=224) (actual time=37.135…37.137
rows=0.00 loops=1) │
│ Sort Key: n.nspname, p.proname, (pg_get_function_arguments(p.oid)) │
│ Sort Method: quicksort Memory: 25kB │
│ Buffers: shared hit=19100 │
│ -> Hash Join (cost=1.11…236.74 rows=688 width=224) (actual
time=37.089…37.090 rows=0.00 loops=1) │
│ Hash Cond: (p.pronamespace = n.oid) │
│ Buffers: shared hit=19094 │
│ -> Seq Scan on pg_proc p (cost=0.00…221.47 rows=1147 width=73) (actual
time=0.040…36.613 rows=3431.00 loops=1) │
│ Filter: pg_function_is_visible(oid) │
│ Rows Removed by Filter: 11 │
│ Buffers: shared hit=19093 │
│ -> Hash (cost=1.07…1.07 rows=3 width=68) (actual time=0.009…0.010
rows=3.00 loops=1) │
│ Buckets: 1024 Batches: 1 Memory Usage: 9kB │
│ Buffers: shared hit=1 │
│ -> Seq Scan on pg_namespace n (cost=0.00…1.07 rows=3 width=68) (actual
time=0.003…0.005 rows=3.00 loops=1) │
│ Filter: ((nspname <> ‘pg_catalog’::name) AND (nspname <>
‘information_schema’::name)) │
│ Rows Removed by Filter: 2 │
│ Buffers: shared hit=1 │
│ Planning: │
│ Buffers: shared hit=270 │
│ Planning Time: 1.019 ms │
│ Execution Time: 37.277 ms │
└──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
(22 rows)

Because the nspname <> ‘pg_catalog’ condition is not something that can be
evaluated during the sequential scan on pg_proc, pg_function_is_visible() is
executed for every proc. Which in turn ends up trigger the population of the
entire PROCOID *and* PROCNAMEARGSNSP catcaches (because catalog functions
are
visible, we end up doing FuncnameGetCandidates for all functions, which in
turn does a list search in PROCNAMEARGSNSP).

(Also, pretty odd this is a left join, given that the filter condition turns
it back into an inner join)

To show the effect:

empty[817815][1]=# SELECT count(*), sum(total_bytes) total_bytes,
sum(total_nblocks) total_nblocks FROM pg_backend_memory_contexts WHERE path
@> (SELECT path FROM pg_backend_memory_contexts WHERE name =
‘CacheMemoryContext’);
┌───────┬─────────────┬───────────────┐
│ count │ total_bytes │ total_nblocks │
├───────┼─────────────┼───────────────┤
│ 97 │ 1251072 │ 163 │
└───────┴─────────────┴───────────────┘
(1 row)

empty[817815][1]=# \df
List of functions
┌────────┬──────┬──────────────────┬─────────────────────┬──────┐
│ Schema │ Name │ Result data type │ Argument data types │ Type │
├────────┼──────┼──────────────────┼─────────────────────┼──────┤
└────────┴──────┴──────────────────┴─────────────────────┴──────┘
(0 rows)

empty[817815][1]=# SELECT count(*), sum(total_bytes) total_bytes,
sum(total_nblocks) total_nblocks FROM pg_backend_memory_contexts WHERE path
@> (SELECT path FROM pg_backend_memory_contexts WHERE name =
‘CacheMemoryContext’);
┌───────┬─────────────┬───────────────┐
│ count │ total_bytes │ total_nblocks │
├───────┼─────────────┼───────────────┤
│ 102 │ 8705984 │ 182 │
└───────┴─────────────┴───────────────┘
(1 row)

I think a lot of psql’s queries have this issue, although most of them won’t
be as problematic, because pg_proc has a fair number of rows in pg_catalog
(compared to e.g. pg_class, where’s an order of magnitude fewer).

If the query instead is rewritten to filter with:

WHERE pg_catalog.pg_function_is_visible(p.oid)
AND p.pronamespace <> ‘pg_catalog’::regnamespace
AND p.pronamespace <> ‘information_schema’::regnamespace

the query is considerably faster (both first and subsequent executions) and
more importantly the memory usage afterwards is:

┌───────┬─────────────┬───────────────┐
│ count │ total_bytes │ total_nblocks │
├───────┼─────────────┼───────────────┤
│ 101 │ 1264384 │ 174 │
└───────┴─────────────┴───────────────┘
(1 row)

I used a regnamespace query here, but because we use patterns etc in some
places, it’s probably better done as a subquery.

I don’t plan to work on fixing this in the near term, but it seemed like a
significant enough effect to be worth mentioning on the list.

Greetings,

Andres Freund


^ permalink  raw  reply  [nested|flat] 8+ messages in thread

* Re: Many of psql's describe functions bloat cache / waste mem
  2026-07-20 21:25 Many of psql's describe functions bloat cache / waste mem Andres Freund <andres@anarazel.de>
  2026-07-22 11:55 ` Re: Many of psql's describe functions bloat cache / waste mem xiaoyu liu <xliu19163@gmail.com>
  2026-07-24 03:17   ` Re: Many of psql's describe functions bloat cache / waste mem xiaoyu liu <xliu19163@gmail.com>
@ 2026-08-21 14:24     ` Jan Nidzwetzki <jan@planetscale.com>
  2026-09-01 03:00       ` Re: Many of psql's describe functions bloat cache / waste mem xliu19163@gmail.com
  0 siblings, 1 reply; 8+ messages in thread

From: Jan Nidzwetzki @ 2026-08-21 14:24 UTC (permalink / raw)
  To: xiaoyu liu <xliu19163@gmail.com>; andres@anarazel.de; +Cc: pgsql-hackers

Hi Hackers,

On 24.07.26 05:17, xiaoyu liu wrote:
[...]

> If anyone has already started reviewing it, or sees an issue with the
> current approach, please let me know.


Thanks for the patch. I tested it and it applied to the current master
branch (a1bb92fb), and check-world passes. I checked the size of the
CacheMemoryContext before and after running \df:

master@a1bb92fb: 8,705,984 B
patch applied:   1,264,384 B

So the patch clearly reduces the size of the CacheMemoryContext
populated by this query. I also tested the query plan shape. As
mentioned in the comment of the patch, the OID lookup subquery becomes
an InitPlan:

                                               QUERY PLAN

---------------------------------------------------------------------------------------------------------
 Sort  (cost=268.31..268.32 rows=1 width=224)
   Sort Key: n.nspname, p.proname, (pg_get_function_arguments(p.oid))
   InitPlan array_1
     ->  Seq Scan on pg_namespace  (cost=0.00..1.06 rows=2 width=4)
           Filter: (nspname = ANY
('{pg_catalog,information_schema}'::name[]))
   ->  Nested Loop Left Join  (cost=0.00..267.24 rows=1 width=224)
         Join Filter: (n.oid = p.pronamespace)
         ->  Seq Scan on pg_proc p  (cost=0.00..266.11 rows=1 width=73)
               Filter: ((pronamespace <> ALL ((InitPlan array_1).col1))
AND pg_function_is_visible(oid))
         ->  Seq Scan on pg_namespace n  (cost=0.00..1.05 rows=5 width=68)
(10 rows)

Now a 'Nested Loop Left Join' is used. As Andres pointed out, this LEFT
JOIN could be changed to a JOIN.


Tests
=====

I think I found an issue in the test. According to the test description,
it ensures "filters system functions before testing visibility". To do
so, the filter must run first, then pg_function_is_visible(). This
happens currently as desired in the query plan.

Filter: ((pronamespace <> ALL ((InitPlan array_1).col1)) AND
pg_function_is_visible(oid))

However, PostgreSQL could reorder both conditions (they are ordered that
way because of their costs). But the costs could change for whatever
reason. For example, if you run "ALTER FUNCTION
pg_catalog.pg_function_is_visible(oid) COST 1;", the conditions in the
query filter flip to:

Filter: (pg_function_is_visible(oid) AND (pronamespace <> ALL ((InitPlan
array_1).col1)))

In this case, pg_function_is_visible() runs for every row found in the
catalog. I verified this using 'funccount' and running \df in parallel
(in my database I have 6 user functions and 3455 catalog functions defined):

# Filter first and then pg_function_is_visible(oid)

$ sudo funccount-bpfcc "$(pg_config
--bindir)/postgres:pg_function_is_visible"
[...]
FUNC                                    COUNT
pg_function_is_visible                      6
Detaching...


# pg_function_is_visible(oid) first and then the filter

$ sudo funccount-bpfcc "$(pg_config
--bindir)/postgres:pg_function_is_visible"
[...]
FUNC                                    COUNT
pg_function_is_visible                   3461
Detaching...


The regex only checks the SQL text that psql generates, not the
resulting query plan. That text is identical in both cases, so the test
cannot detect this regression at all: with the procost changed as above,
pg_function_is_visible() is called for every row in pg_proc and
001_basic.pl still passes.

That said, I am not sure if we need such kind of test in the end. For
example, 112e40b867b reordered clauses for plan reasons in describe.c
and went in without tests.


Other \d commands
=================

As Andres outlined, there are more \d commands affected by this problem
and only \df is changed by the current version of this patch. For
example, \do uses the old shape of the query plan where
'pg_operator_is_visible' is called for every operator.

The query plan for \do:

                                         QUERY PLAN



-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
 Sort  (cost=133.01..133.41 rows=161 width=256)
   Sort Key: n.nspname, o.oprname, (CASE WHEN (o.oprkind = 'l'::"char")
THEN NULL::text ELSE format_type(o.oprleft, NULL::integer) END), (CASE
WHEN (o.oprkind = 'r'::"char") THEN NULL::text ELSE
format_type(o.oprright, NULL::integer) END)
   ->  Hash Join  (cost=1.11..127.10 rows=161 width=256)
         Hash Cond: (o.oprnamespace = n.oid)
         ->  Seq Scan on pg_operator o  (cost=0.00..42.18 rows=268 width=89)
               Filter: pg_operator_is_visible(oid)
         ->  Hash  (cost=1.07..1.07 rows=3 width=68)
               ->  Seq Scan on pg_namespace n  (cost=0.00..1.07 rows=3
width=68)
                     Filter: ((nspname <> 'pg_catalog'::name) AND
(nspname <> 'information_schema'::name))
(9 rows)


What do you think about introducing a helper function like
'appendSystemSchemaFilter()' that adds the filter condition as proposed
in the patch, and calling it from the other places in describe.c that
exclude the system schemas?


Best regards
 Jan

-- 
Jan Nidzwetzki
PlanetScale Postgres Core Team







^ permalink  raw  reply  [nested|flat] 8+ messages in thread

* Re: Many of psql's describe functions bloat cache / waste mem
  2026-07-20 21:25 Many of psql's describe functions bloat cache / waste mem Andres Freund <andres@anarazel.de>
  2026-07-22 11:55 ` Re: Many of psql's describe functions bloat cache / waste mem xiaoyu liu <xliu19163@gmail.com>
  2026-07-24 03:17   ` Re: Many of psql's describe functions bloat cache / waste mem xiaoyu liu <xliu19163@gmail.com>
  2026-08-21 14:24     ` Re: Many of psql's describe functions bloat cache / waste mem Jan Nidzwetzki <jan@planetscale.com>
@ 2026-09-01 03:00       ` xliu19163@gmail.com
  2026-09-02 10:56         ` Re: Many of psql's describe functions bloat cache / waste mem Jan Nidzwetzki <jan@planetscale.com>
  0 siblings, 1 reply; 8+ messages in thread

From: xliu19163@gmail.com @ 2026-09-01 03:00 UTC (permalink / raw)
  To: Jan Nidzwetzki <jan@planetscale.com>; Andres Freund <andres@anarazel.de>; +Cc: pgsql-hackers

Hi Jan,

Thanks for the detailed review and for confirming the memory reduction.

Attached is v2. I followed your suggestions:

- introduced appendSystemSchemaFilter() and reused it in the
describe.c queries that exclude pg_catalog and information_schema,
including \df and \do;
- changed the corresponding object-to-pg_namespace LEFT JOINs to JOIN
where the namespace is mandatory;
- removed the TAP test from v1, since checking the generated SQL text
cannot guarantee planner clause evaluation order.

The filter still uses an uncorrelated pg_namespace subquery, so it
becomes an InitPlan. The ARRAY(...) / <> ALL form also continues to
work when information_schema is absent.

I rebased v2 onto current master (3b120b1e94d). make check-world
passes for all suites enabled in my local build. TAP tests were not
enabled because IPC::Run is not available locally. I also manually
checked the affected psql commands, including \df and \do, and
confirmed the expected plan shape and CacheMemoryContext behavior.

Please let me know what you think.

Best regards,
Xiaoyu

Attachments:

v2-0001-psql-filter-system-objects-before-visibility-chec.patch (text/x-patch, 15.4K) download From 4d8374500d54c7e10d702e94f42c00f13af3773a Mon Sep 17 00:00:00 2001 From: xiaoyu liu <xliu19163@gmail.com> Date: Wed, 22 Jul 2026 18:49:53 +0800 Subject: [PATCH v2] psql: filter system objects before visibility checks When describe commands hide system objects, filter pg_catalog and information_schema using namespace OIDs from the object catalogs. This lets the namespace restriction be applied during the catalog scan and avoids unnecessary visibility checks and cache population. Centralize the filter construction in a helper and use inner joins for the corresponding object-to-namespace joins. --- src/bin/psql/describe.c | 116 ++++++++++++++++++++++------------------ 1 file changed, 64 insertions(+), 52 deletions(-) diff --git a/src/bin/psql/describe.c b/src/bin/psql/describe.c index 063e2555814..22509bc9f71 100644 --- a/src/bin/psql/describe.c +++ b/src/bin/psql/describe.c @@ -54,6 +54,9 @@ static bool describeOneTSConfig(const char *oid, const char *nspname, const char *pnspname, const char *prsname); static void printACLColumn(PQExpBuffer buf, const char *colname); static bool listOneExtensionContents(const char *extname, const char *oid); +static void appendSystemSchemaFilter(PQExpBuffer buf, + const char *namespacevar, + bool have_where); static bool validateSQLNamePattern(PQExpBuffer buf, const char *pattern, bool have_where, bool force_escape, const char *schemavar, const char *namevar, @@ -102,20 +105,19 @@ describeAggregates(const char *pattern, bool verbose, bool showSystem) appendPQExpBuffer(&buf, " pg_catalog.obj_description(p.oid, 'pg_proc') as \"%s\"\n" "FROM pg_catalog.pg_proc p\n" - " LEFT JOIN pg_catalog.pg_namespace n ON n.oid = p.pronamespace\n" + " JOIN pg_catalog.pg_namespace n ON n.oid = p.pronamespace\n" "WHERE p.prokind = " CppAsString2(PROKIND_AGGREGATE) "\n", gettext_noop("Description")); else appendPQExpBuffer(&buf, " pg_catalog.obj_description(p.oid, 'pg_proc') as \"%s\"\n" "FROM pg_catalog.pg_proc p\n" - " LEFT JOIN pg_catalog.pg_namespace n ON n.oid = p.pronamespace\n" + " JOIN pg_catalog.pg_namespace n ON n.oid = p.pronamespace\n" "WHERE p.proisagg\n", gettext_noop("Description")); if (!showSystem && !pattern) - appendPQExpBufferStr(&buf, " AND n.nspname <> 'pg_catalog'\n" - " AND n.nspname <> 'information_schema'\n"); + appendSystemSchemaFilter(&buf, "p.pronamespace", true); if (!validateSQLNamePattern(&buf, pattern, true, false, "n.nspname", "p.proname", NULL, @@ -426,7 +428,7 @@ describeFunctions(const char *functypes, const char *func_pattern, appendPQExpBufferStr(&buf, "\nFROM pg_catalog.pg_proc p" - "\n LEFT JOIN pg_catalog.pg_namespace n ON n.oid = p.pronamespace\n"); + "\n JOIN pg_catalog.pg_namespace n ON n.oid = p.pronamespace\n"); for (int i = 0; i < num_arg_patterns; i++) { @@ -546,6 +548,12 @@ describeFunctions(const char *functypes, const char *func_pattern, appendPQExpBufferStr(&buf, " )\n"); } + if (!showSystem && !func_pattern) + { + appendSystemSchemaFilter(&buf, "p.pronamespace", have_where); + have_where = true; + } + if (!validateSQLNamePattern(&buf, func_pattern, have_where, false, "n.nspname", "p.proname", NULL, "pg_catalog.pg_function_is_visible(p.oid)", @@ -586,10 +594,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); @@ -666,7 +670,7 @@ describeTypes(const char *pattern, bool verbose, bool showSystem) gettext_noop("Description")); appendPQExpBufferStr(&buf, "FROM pg_catalog.pg_type t\n" - " LEFT JOIN pg_catalog.pg_namespace n ON n.oid = t.typnamespace\n"); + " JOIN pg_catalog.pg_namespace n ON n.oid = t.typnamespace\n"); /* * do not include complex types (typrelid!=0) unless they are standalone @@ -684,8 +688,7 @@ describeTypes(const char *pattern, bool verbose, bool showSystem) appendPQExpBufferStr(&buf, " AND NOT EXISTS(SELECT 1 FROM pg_catalog.pg_type el WHERE el.oid = t.typelem AND el.typarray = t.oid)\n"); if (!showSystem && !pattern) - appendPQExpBufferStr(&buf, " AND n.nspname <> 'pg_catalog'\n" - " AND n.nspname <> 'information_schema'\n"); + appendSystemSchemaFilter(&buf, "t.typnamespace", true); /* Match name pattern against either internal or external name */ if (!validateSQLNamePattern(&buf, map_typename_pattern(pattern), @@ -828,7 +831,7 @@ describeOperators(const char *oper_pattern, " coalesce(pg_catalog.obj_description(o.oid, 'pg_operator'),\n" " pg_catalog.obj_description(o.oprcode, 'pg_proc')) AS \"%s\"\n" "FROM pg_catalog.pg_operator o\n" - " LEFT JOIN pg_catalog.pg_namespace n ON n.oid = o.oprnamespace\n", + " JOIN pg_catalog.pg_namespace n ON n.oid = o.oprnamespace\n", gettext_noop("Description")); if (num_arg_patterns >= 2) @@ -852,8 +855,7 @@ describeOperators(const char *oper_pattern, " LEFT JOIN pg_catalog.pg_proc p ON p.oid = o.oprcode\n"); if (!showSystem && !oper_pattern) - appendPQExpBufferStr(&buf, "WHERE n.nspname <> 'pg_catalog'\n" - " AND n.nspname <> 'information_schema'\n"); + appendSystemSchemaFilter(&buf, "o.oprnamespace", false); if (!validateSQLNamePattern(&buf, oper_pattern, !showSystem && !oper_pattern, true, @@ -1121,7 +1123,7 @@ permissionsList(const char *pattern, bool showSystem) gettext_noop("Policies")); appendPQExpBufferStr(&buf, "\nFROM pg_catalog.pg_class c\n" - " LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace\n" + " JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace\n" "WHERE c.relkind IN (" CppAsString2(RELKIND_RELATION) "," CppAsString2(RELKIND_VIEW) "," @@ -1132,8 +1134,7 @@ permissionsList(const char *pattern, bool showSystem) CppAsString2(RELKIND_PARTITIONED_TABLE) ")\n"); if (!showSystem && !pattern) - appendPQExpBufferStr(&buf, " AND n.nspname <> 'pg_catalog'\n" - " AND n.nspname <> 'information_schema'\n"); + appendSystemSchemaFilter(&buf, "c.relnamespace", true); if (!validateSQLNamePattern(&buf, pattern, true, false, "n.nspname", "c.relname", NULL, @@ -1280,13 +1281,12 @@ objectDescription(const char *pattern, bool showSystem) " FROM pg_catalog.pg_constraint pgc\n" " JOIN pg_catalog.pg_class c " "ON c.oid = pgc.conrelid\n" - " LEFT JOIN pg_catalog.pg_namespace n " + " JOIN pg_catalog.pg_namespace n " " ON n.oid = c.relnamespace\n", gettext_noop("table constraint")); if (!showSystem && !pattern) - appendPQExpBufferStr(&buf, "WHERE n.nspname <> 'pg_catalog'\n" - " AND n.nspname <> 'information_schema'\n"); + appendSystemSchemaFilter(&buf, "c.relnamespace", false); if (!validateSQLNamePattern(&buf, pattern, !showSystem && !pattern, false, "n.nspname", "pgc.conname", NULL, @@ -1304,13 +1304,12 @@ objectDescription(const char *pattern, bool showSystem) " FROM pg_catalog.pg_constraint pgc\n" " JOIN pg_catalog.pg_type t " "ON t.oid = pgc.contypid\n" - " LEFT JOIN pg_catalog.pg_namespace n " + " JOIN pg_catalog.pg_namespace n " " ON n.oid = t.typnamespace\n", gettext_noop("domain constraint")); if (!showSystem && !pattern) - appendPQExpBufferStr(&buf, "WHERE n.nspname <> 'pg_catalog'\n" - " AND n.nspname <> 'information_schema'\n"); + appendSystemSchemaFilter(&buf, "t.typnamespace", false); if (!validateSQLNamePattern(&buf, pattern, !showSystem && !pattern, false, "n.nspname", "pgc.conname", NULL, @@ -1333,8 +1332,7 @@ objectDescription(const char *pattern, bool showSystem) gettext_noop("operator class")); if (!showSystem && !pattern) - appendPQExpBufferStr(&buf, " AND n.nspname <> 'pg_catalog'\n" - " AND n.nspname <> 'information_schema'\n"); + appendSystemSchemaFilter(&buf, "o.opcnamespace", true); if (!validateSQLNamePattern(&buf, pattern, true, false, "n.nspname", "o.opcname", NULL, @@ -1357,8 +1355,7 @@ objectDescription(const char *pattern, bool showSystem) gettext_noop("operator family")); if (!showSystem && !pattern) - appendPQExpBufferStr(&buf, " AND n.nspname <> 'pg_catalog'\n" - " AND n.nspname <> 'information_schema'\n"); + appendSystemSchemaFilter(&buf, "opf.opfnamespace", true); if (!validateSQLNamePattern(&buf, pattern, true, false, "n.nspname", "opf.opfname", NULL, @@ -1375,13 +1372,12 @@ objectDescription(const char *pattern, bool showSystem) " CAST('%s' AS pg_catalog.text) as object\n" " FROM pg_catalog.pg_rewrite r\n" " JOIN pg_catalog.pg_class c ON c.oid = r.ev_class\n" - " LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace\n" + " JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace\n" " WHERE r.rulename != '_RETURN'\n", gettext_noop("rule")); if (!showSystem && !pattern) - appendPQExpBufferStr(&buf, " AND n.nspname <> 'pg_catalog'\n" - " AND n.nspname <> 'information_schema'\n"); + appendSystemSchemaFilter(&buf, "c.relnamespace", true); if (!validateSQLNamePattern(&buf, pattern, true, false, "n.nspname", "r.rulename", NULL, @@ -1398,12 +1394,11 @@ objectDescription(const char *pattern, bool showSystem) " CAST('%s' AS pg_catalog.text) as object\n" " FROM pg_catalog.pg_trigger t\n" " JOIN pg_catalog.pg_class c ON c.oid = t.tgrelid\n" - " LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace\n", + " JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace\n", gettext_noop("trigger")); if (!showSystem && !pattern) - appendPQExpBufferStr(&buf, "WHERE n.nspname <> 'pg_catalog'\n" - " AND n.nspname <> 'information_schema'\n"); + appendSystemSchemaFilter(&buf, "c.relnamespace", false); if (!validateSQLNamePattern(&buf, pattern, !showSystem && !pattern, false, "n.nspname", "t.tgname", NULL, @@ -1462,11 +1457,10 @@ describeTableDetails(const char *pattern, bool verbose, bool showSystem) " n.nspname,\n" " c.relname\n" "FROM pg_catalog.pg_class c\n" - " LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace\n"); + " JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace\n"); if (!showSystem && !pattern) - appendPQExpBufferStr(&buf, "WHERE n.nspname <> 'pg_catalog'\n" - " AND n.nspname <> 'information_schema'\n"); + appendSystemSchemaFilter(&buf, "c.relnamespace", false); if (!validateSQLNamePattern(&buf, pattern, !showSystem && !pattern, false, "n.nspname", "c.relname", NULL, @@ -4188,7 +4182,7 @@ listTables(const char *tabtypes, const char *pattern, bool verbose, bool showSys appendPQExpBufferStr(&buf, "\nFROM pg_catalog.pg_class c" - "\n LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace"); + "\n JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace"); if (pset.sversion >= 120000 && !pset.hide_tableam && (showTables || showMatViews || showIndexes)) @@ -4229,9 +4223,10 @@ listTables(const char *tabtypes, const char *pattern, bool verbose, bool showSys appendPQExpBufferStr(&buf, ")\n"); if (!showSystem && !pattern) - appendPQExpBufferStr(&buf, " AND n.nspname <> 'pg_catalog'\n" - " AND n.nspname !~ '^pg_toast'\n" - " AND n.nspname <> 'information_schema'\n"); + { + appendSystemSchemaFilter(&buf, "c.relnamespace", true); + appendPQExpBufferStr(&buf, " AND n.nspname !~ '^pg_toast'\n"); + } if (!validateSQLNamePattern(&buf, pattern, true, false, "n.nspname", "c.relname", NULL, @@ -4442,7 +4437,7 @@ listPartitionedTables(const char *reltypes, const char *pattern, bool verbose) appendPQExpBufferStr(&buf, "\nFROM pg_catalog.pg_class c" - "\n LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace"); + "\n JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace"); if (showIndexes) appendPQExpBufferStr(&buf, @@ -4502,9 +4497,10 @@ listPartitionedTables(const char *reltypes, const char *pattern, bool verbose) " AND NOT c.relispartition\n" : ""); if (!pattern) - appendPQExpBufferStr(&buf, " AND n.nspname <> 'pg_catalog'\n" - " AND n.nspname !~ '^pg_toast'\n" - " AND n.nspname <> 'information_schema'\n"); + { + appendSystemSchemaFilter(&buf, "c.relnamespace", true); + appendPQExpBufferStr(&buf, " AND n.nspname !~ '^pg_toast'\n"); + } if (!validateSQLNamePattern(&buf, pattern, true, false, "n.nspname", "c.relname", NULL, @@ -4662,7 +4658,7 @@ listDomains(const char *pattern, bool verbose, bool showSystem) appendPQExpBufferStr(&buf, "\nFROM pg_catalog.pg_type t\n" - " LEFT JOIN pg_catalog.pg_namespace n ON n.oid = t.typnamespace\n"); + " JOIN pg_catalog.pg_namespace n ON n.oid = t.typnamespace\n"); if (verbose) appendPQExpBufferStr(&buf, @@ -4673,8 +4669,7 @@ listDomains(const char *pattern, bool verbose, bool showSystem) appendPQExpBufferStr(&buf, "WHERE t.typtype = 'd'\n"); if (!showSystem && !pattern) - appendPQExpBufferStr(&buf, " AND n.nspname <> 'pg_catalog'\n" - " AND n.nspname <> 'information_schema'\n"); + appendSystemSchemaFilter(&buf, "t.typnamespace", true); if (!validateSQLNamePattern(&buf, pattern, true, false, "n.nspname", "t.typname", NULL, @@ -4752,8 +4747,7 @@ listConversions(const char *pattern, bool verbose, bool showSystem) appendPQExpBufferStr(&buf, "WHERE true\n"); if (!showSystem && !pattern) - appendPQExpBufferStr(&buf, " AND n.nspname <> 'pg_catalog'\n" - " AND n.nspname <> 'information_schema'\n"); + appendSystemSchemaFilter(&buf, "c.connamespace", true); if (!validateSQLNamePattern(&buf, pattern, true, false, "n.nspname", "c.conname", NULL, @@ -5223,8 +5217,7 @@ listCollations(const char *pattern, bool verbose, bool showSystem) "WHERE n.oid = c.collnamespace\n"); if (!showSystem && !pattern) - appendPQExpBufferStr(&buf, " AND n.nspname <> 'pg_catalog'\n" - " AND n.nspname <> 'information_schema'\n"); + appendSystemSchemaFilter(&buf, "c.collnamespace", true); /* * Hide collations that aren't usable in the current database's encoding. @@ -6425,6 +6418,25 @@ listOneExtensionContents(const char *extname, const char *oid) return true; } +/* + * Append a filter that excludes objects in pg_catalog and + * information_schema. Use the namespace OID stored in the object's catalog, + * rather than the name obtained through pg_namespace, so the restriction can + * be applied during the object catalog scan. The subquery also tolerates a + * missing information_schema. + */ +static void +appendSystemSchemaFilter(PQExpBuffer buf, const char *namespacevar, + bool have_where) +{ + appendPQExpBuffer(buf, + "%s%s <> ALL (ARRAY(\n" + " SELECT oid FROM pg_catalog.pg_namespace\n" + " WHERE nspname IN ('pg_catalog', 'information_schema')))\n", + have_where ? " AND " : "WHERE ", + namespacevar); +} + /* * validateSQLNamePattern * -- 2.44.0
^ permalink raw reply [nested|flat] 8+ messages in thread

* Re: Many of psql's describe functions bloat cache / waste mem
  2026-07-20 21:25 Many of psql's describe functions bloat cache / waste mem Andres Freund <andres@anarazel.de>
  2026-07-22 11:55 ` Re: Many of psql's describe functions bloat cache / waste mem xiaoyu liu <xliu19163@gmail.com>
  2026-07-24 03:17   ` Re: Many of psql's describe functions bloat cache / waste mem xiaoyu liu <xliu19163@gmail.com>
  2026-08-21 14:24     ` Re: Many of psql's describe functions bloat cache / waste mem Jan Nidzwetzki <jan@planetscale.com>
  2026-09-01 03:00       ` Re: Many of psql's describe functions bloat cache / waste mem xliu19163@gmail.com
@ 2026-09-02 10:56         ` Jan Nidzwetzki <jan@planetscale.com>
  2026-09-03 02:30           ` Re: Many of psql's describe functions bloat cache / waste mem xliu19163@gmail.com
  0 siblings, 1 reply; 8+ messages in thread

From: Jan Nidzwetzki @ 2026-09-02 10:56 UTC (permalink / raw)
  To: xliu19163@gmail.com, Andres Freund <andres@anarazel.de>; +Cc: pgsql-hackers

Hi Xiaoyu,

On 01.09.26 05:00, xliu19163@gmail.com wrote:
> Hi Jan,
> 
> Thanks for the detailed review and for confirming the memory reduction.
> 
> Attached is v2. I followed your suggestions:


Thanks for v2 of the patch. It applied cleanly to the current master
branch and check-world passes.


Testing
=======

I ran a few tests locally, and it decreases memory usage for several
commands. I used the following script for verification:

sql="FROM pg_backend_memory_contexts
     WHERE path @> (SELECT path FROM pg_backend_memory_contexts
                    WHERE name = 'CacheMemoryContext')"

for c in '\d' '\da' '\dc' '\dd' '\dD' '\df' '\di' '\dm' '\do' \
 '\dO' '\dp' '\dP' '\ds' '\dt' '\dT' '\dv' '\z'; do
  printf '%-5s ' "$c"
  psql -X -qtA <<EOF
SELECT sum(total_bytes) AS before $sql \gset
\o /dev/null
$c
\o
SELECT sum(total_bytes) - :before $sql;
EOF
done

Compared to the master branch, I see the following changes:

cmd         master           v2        saved
\d          541696       541696            0
\da         537600       537600            0
\dc         535552       535552            0
\dd        1608704       560128      1048576
\dD         543744       543744            0
\df        7979200       537600      7441600
\di         541696       541696            0
\dm         541696       541696            0
\do        1583104       534528      1048576
\dO        1600576       535552      1065024
\dp         564224       564224            0
\dP         537600       537600            0
\ds         537600       537600            0
\dt         541696       541696            0
\dT         537600       537600            0
\dv         537600       537600            0
\z          564224       564224            0
total                               10603776

The commands that show no change either have a cheap qual that
short-circuits before the visibility check (\da filters on prokind
first) or save less than one allocation block, which total_bytes cannot
show. We could also compare used_bytes, but since this thread started
with total_bytes, I don't want to change the memory-usage measurement
method to keep the results comparable (but I'm happy to do these
measurements if required).


Review
======

- One thing I noticed: in listTables() and listPartitionedTables(), the
TOAST schemas are still excluded via n.nspname. That part of the filter
cannot be applied during the pg_class scan, so \di still calls
pg_table_is_visible() for every TOAST index. Folding "n.nspname !~
'^pg_toast'" into the subquery in appendSystemSchemaFilter() would avoid
that. However, it has to stay optional for the other callers, since
objects can be created in pg_toast. That could be a follow-up patch to
keep this one focused on memory usage.

- The commit message is missing line breaks. I suggest wrapping it at
around 75 characters.

- The patch addresses two things: (1) it changes LEFT JOIN to JOIN and
(2) adds the filter. It could be beneficial to split this into two
different commits.


Apart from this, the patch looks good to me.


Best regards
   Jan

-- 
Jan Nidzwetzki
PlanetScale Postgres Core Team







^ permalink  raw  reply  [nested|flat] 8+ messages in thread

* Re: Many of psql's describe functions bloat cache / waste mem
  2026-07-20 21:25 Many of psql's describe functions bloat cache / waste mem Andres Freund <andres@anarazel.de>
  2026-07-22 11:55 ` Re: Many of psql's describe functions bloat cache / waste mem xiaoyu liu <xliu19163@gmail.com>
  2026-07-24 03:17   ` Re: Many of psql's describe functions bloat cache / waste mem xiaoyu liu <xliu19163@gmail.com>
  2026-08-21 14:24     ` Re: Many of psql's describe functions bloat cache / waste mem Jan Nidzwetzki <jan@planetscale.com>
  2026-09-01 03:00       ` Re: Many of psql's describe functions bloat cache / waste mem xliu19163@gmail.com
  2026-09-02 10:56         ` Re: Many of psql's describe functions bloat cache / waste mem Jan Nidzwetzki <jan@planetscale.com>
@ 2026-09-03 02:30           ` xliu19163@gmail.com
  2026-09-03 10:03             ` Re: Many of psql's describe functions bloat cache / waste mem Jan Nidzwetzki <jan@planetscale.com>
  0 siblings, 1 reply; 8+ messages in thread

From: xliu19163@gmail.com @ 2026-09-03 02:30 UTC (permalink / raw)
  To: Jan Nidzwetzki <jan@planetscale.com>; Andres Freund <andres@anarazel.de>; +Cc: pgsql-hackers

Hi Jan,

Thanks for testing v2 and for the additional review.

Attached is v3. I split the changes into two patches:

1. Change the applicable object-to-pg_namespace joins from LEFT JOIN to JOIN.
2. Add appendSystemSchemaFilter() and use it in the affected describe queries.

I also wrapped both commit messages at around 75 characters.

I left the pg_toast optimization out of this series, as suggested, so it can
be handled separately without expanding the scope of this patch.

The series is rebased onto current master (792094a5ce8). make check-world
passes for all suites enabled in my local build. TAP tests were not enabled
because IPC::Run is unavailable locally.

Best regards,
Xiaoyu

Attachments: download all (2 files, .tar.gz)

v3-0001-psql-use-inner-joins-for-object-namespaces.patch (text/x-patch, 6.4K) download From aed41d02504afdec22ea9a16e91848f3c50d3e8c Mon Sep 17 00:00:00 2001 From: xiaoyu liu <xliu19163@gmail.com> Date: Thu, 3 Sep 2026 09:58:17 +0800 Subject: [PATCH v3 1/2] psql: use inner joins for object namespaces The namespace columns referenced by these describe queries always identify a pg_namespace row. Use inner joins instead of left joins when fetching those namespaces. --- src/bin/psql/describe.c | 28 ++++++++++++++-------------- 1 file changed, 14 insertions(+), 14 deletions(-) diff --git a/src/bin/psql/describe.c b/src/bin/psql/describe.c index 063e2555814..0bc9f39a124 100644 --- a/src/bin/psql/describe.c +++ b/src/bin/psql/describe.c @@ -102,14 +102,14 @@ describeAggregates(const char *pattern, bool verbose, bool showSystem) appendPQExpBuffer(&buf, " pg_catalog.obj_description(p.oid, 'pg_proc') as \"%s\"\n" "FROM pg_catalog.pg_proc p\n" - " LEFT JOIN pg_catalog.pg_namespace n ON n.oid = p.pronamespace\n" + " JOIN pg_catalog.pg_namespace n ON n.oid = p.pronamespace\n" "WHERE p.prokind = " CppAsString2(PROKIND_AGGREGATE) "\n", gettext_noop("Description")); else appendPQExpBuffer(&buf, " pg_catalog.obj_description(p.oid, 'pg_proc') as \"%s\"\n" "FROM pg_catalog.pg_proc p\n" - " LEFT JOIN pg_catalog.pg_namespace n ON n.oid = p.pronamespace\n" + " JOIN pg_catalog.pg_namespace n ON n.oid = p.pronamespace\n" "WHERE p.proisagg\n", gettext_noop("Description")); @@ -426,7 +426,7 @@ describeFunctions(const char *functypes, const char *func_pattern, appendPQExpBufferStr(&buf, "\nFROM pg_catalog.pg_proc p" - "\n LEFT JOIN pg_catalog.pg_namespace n ON n.oid = p.pronamespace\n"); + "\n JOIN pg_catalog.pg_namespace n ON n.oid = p.pronamespace\n"); for (int i = 0; i < num_arg_patterns; i++) { @@ -666,7 +666,7 @@ describeTypes(const char *pattern, bool verbose, bool showSystem) gettext_noop("Description")); appendPQExpBufferStr(&buf, "FROM pg_catalog.pg_type t\n" - " LEFT JOIN pg_catalog.pg_namespace n ON n.oid = t.typnamespace\n"); + " JOIN pg_catalog.pg_namespace n ON n.oid = t.typnamespace\n"); /* * do not include complex types (typrelid!=0) unless they are standalone @@ -828,7 +828,7 @@ describeOperators(const char *oper_pattern, " coalesce(pg_catalog.obj_description(o.oid, 'pg_operator'),\n" " pg_catalog.obj_description(o.oprcode, 'pg_proc')) AS \"%s\"\n" "FROM pg_catalog.pg_operator o\n" - " LEFT JOIN pg_catalog.pg_namespace n ON n.oid = o.oprnamespace\n", + " JOIN pg_catalog.pg_namespace n ON n.oid = o.oprnamespace\n", gettext_noop("Description")); if (num_arg_patterns >= 2) @@ -1121,7 +1121,7 @@ permissionsList(const char *pattern, bool showSystem) gettext_noop("Policies")); appendPQExpBufferStr(&buf, "\nFROM pg_catalog.pg_class c\n" - " LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace\n" + " JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace\n" "WHERE c.relkind IN (" CppAsString2(RELKIND_RELATION) "," CppAsString2(RELKIND_VIEW) "," @@ -1280,7 +1280,7 @@ objectDescription(const char *pattern, bool showSystem) " FROM pg_catalog.pg_constraint pgc\n" " JOIN pg_catalog.pg_class c " "ON c.oid = pgc.conrelid\n" - " LEFT JOIN pg_catalog.pg_namespace n " + " JOIN pg_catalog.pg_namespace n " " ON n.oid = c.relnamespace\n", gettext_noop("table constraint")); @@ -1304,7 +1304,7 @@ objectDescription(const char *pattern, bool showSystem) " FROM pg_catalog.pg_constraint pgc\n" " JOIN pg_catalog.pg_type t " "ON t.oid = pgc.contypid\n" - " LEFT JOIN pg_catalog.pg_namespace n " + " JOIN pg_catalog.pg_namespace n " " ON n.oid = t.typnamespace\n", gettext_noop("domain constraint")); @@ -1375,7 +1375,7 @@ objectDescription(const char *pattern, bool showSystem) " CAST('%s' AS pg_catalog.text) as object\n" " FROM pg_catalog.pg_rewrite r\n" " JOIN pg_catalog.pg_class c ON c.oid = r.ev_class\n" - " LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace\n" + " JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace\n" " WHERE r.rulename != '_RETURN'\n", gettext_noop("rule")); @@ -1398,7 +1398,7 @@ objectDescription(const char *pattern, bool showSystem) " CAST('%s' AS pg_catalog.text) as object\n" " FROM pg_catalog.pg_trigger t\n" " JOIN pg_catalog.pg_class c ON c.oid = t.tgrelid\n" - " LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace\n", + " JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace\n", gettext_noop("trigger")); if (!showSystem && !pattern) @@ -1462,7 +1462,7 @@ describeTableDetails(const char *pattern, bool verbose, bool showSystem) " n.nspname,\n" " c.relname\n" "FROM pg_catalog.pg_class c\n" - " LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace\n"); + " JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace\n"); if (!showSystem && !pattern) appendPQExpBufferStr(&buf, "WHERE n.nspname <> 'pg_catalog'\n" @@ -4188,7 +4188,7 @@ listTables(const char *tabtypes, const char *pattern, bool verbose, bool showSys appendPQExpBufferStr(&buf, "\nFROM pg_catalog.pg_class c" - "\n LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace"); + "\n JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace"); if (pset.sversion >= 120000 && !pset.hide_tableam && (showTables || showMatViews || showIndexes)) @@ -4442,7 +4442,7 @@ listPartitionedTables(const char *reltypes, const char *pattern, bool verbose) appendPQExpBufferStr(&buf, "\nFROM pg_catalog.pg_class c" - "\n LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace"); + "\n JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace"); if (showIndexes) appendPQExpBufferStr(&buf, @@ -4662,7 +4662,7 @@ listDomains(const char *pattern, bool verbose, bool showSystem) appendPQExpBufferStr(&buf, "\nFROM pg_catalog.pg_type t\n" - " LEFT JOIN pg_catalog.pg_namespace n ON n.oid = t.typnamespace\n"); + " JOIN pg_catalog.pg_namespace n ON n.oid = t.typnamespace\n"); if (verbose) appendPQExpBufferStr(&buf, -- 2.44.0
v3-0002-psql-filter-system-objects-before-visibility-chec.patch (text/x-patch, 10.5K) download From 07233335f92cf7eaffedfcc56d9849b962617ee2 Mon Sep 17 00:00:00 2001 From: xiaoyu liu <xliu19163@gmail.com> Date: Thu, 3 Sep 2026 09:59:27 +0800 Subject: [PATCH v3 2/2] psql: filter system objects before visibility checks When describe commands hide system objects, filter pg_catalog and information_schema using namespace OIDs from the object catalogs. This lets the namespace restriction be applied during the catalog scan and avoids unnecessary visibility checks and cache population. Centralize construction of the filter in appendSystemSchemaFilter() and reuse it in the affected describe queries. --- src/bin/psql/describe.c | 88 +++++++++++++++++++++++------------------ 1 file changed, 50 insertions(+), 38 deletions(-) diff --git a/src/bin/psql/describe.c b/src/bin/psql/describe.c index 0bc9f39a124..22509bc9f71 100644 --- a/src/bin/psql/describe.c +++ b/src/bin/psql/describe.c @@ -54,6 +54,9 @@ static bool describeOneTSConfig(const char *oid, const char *nspname, const char *pnspname, const char *prsname); static void printACLColumn(PQExpBuffer buf, const char *colname); static bool listOneExtensionContents(const char *extname, const char *oid); +static void appendSystemSchemaFilter(PQExpBuffer buf, + const char *namespacevar, + bool have_where); static bool validateSQLNamePattern(PQExpBuffer buf, const char *pattern, bool have_where, bool force_escape, const char *schemavar, const char *namevar, @@ -114,8 +117,7 @@ describeAggregates(const char *pattern, bool verbose, bool showSystem) gettext_noop("Description")); if (!showSystem && !pattern) - appendPQExpBufferStr(&buf, " AND n.nspname <> 'pg_catalog'\n" - " AND n.nspname <> 'information_schema'\n"); + appendSystemSchemaFilter(&buf, "p.pronamespace", true); if (!validateSQLNamePattern(&buf, pattern, true, false, "n.nspname", "p.proname", NULL, @@ -546,6 +548,12 @@ describeFunctions(const char *functypes, const char *func_pattern, appendPQExpBufferStr(&buf, " )\n"); } + if (!showSystem && !func_pattern) + { + appendSystemSchemaFilter(&buf, "p.pronamespace", have_where); + have_where = true; + } + if (!validateSQLNamePattern(&buf, func_pattern, have_where, false, "n.nspname", "p.proname", NULL, "pg_catalog.pg_function_is_visible(p.oid)", @@ -586,10 +594,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); @@ -684,8 +688,7 @@ describeTypes(const char *pattern, bool verbose, bool showSystem) appendPQExpBufferStr(&buf, " AND NOT EXISTS(SELECT 1 FROM pg_catalog.pg_type el WHERE el.oid = t.typelem AND el.typarray = t.oid)\n"); if (!showSystem && !pattern) - appendPQExpBufferStr(&buf, " AND n.nspname <> 'pg_catalog'\n" - " AND n.nspname <> 'information_schema'\n"); + appendSystemSchemaFilter(&buf, "t.typnamespace", true); /* Match name pattern against either internal or external name */ if (!validateSQLNamePattern(&buf, map_typename_pattern(pattern), @@ -852,8 +855,7 @@ describeOperators(const char *oper_pattern, " LEFT JOIN pg_catalog.pg_proc p ON p.oid = o.oprcode\n"); if (!showSystem && !oper_pattern) - appendPQExpBufferStr(&buf, "WHERE n.nspname <> 'pg_catalog'\n" - " AND n.nspname <> 'information_schema'\n"); + appendSystemSchemaFilter(&buf, "o.oprnamespace", false); if (!validateSQLNamePattern(&buf, oper_pattern, !showSystem && !oper_pattern, true, @@ -1132,8 +1134,7 @@ permissionsList(const char *pattern, bool showSystem) CppAsString2(RELKIND_PARTITIONED_TABLE) ")\n"); if (!showSystem && !pattern) - appendPQExpBufferStr(&buf, " AND n.nspname <> 'pg_catalog'\n" - " AND n.nspname <> 'information_schema'\n"); + appendSystemSchemaFilter(&buf, "c.relnamespace", true); if (!validateSQLNamePattern(&buf, pattern, true, false, "n.nspname", "c.relname", NULL, @@ -1285,8 +1286,7 @@ objectDescription(const char *pattern, bool showSystem) gettext_noop("table constraint")); if (!showSystem && !pattern) - appendPQExpBufferStr(&buf, "WHERE n.nspname <> 'pg_catalog'\n" - " AND n.nspname <> 'information_schema'\n"); + appendSystemSchemaFilter(&buf, "c.relnamespace", false); if (!validateSQLNamePattern(&buf, pattern, !showSystem && !pattern, false, "n.nspname", "pgc.conname", NULL, @@ -1309,8 +1309,7 @@ objectDescription(const char *pattern, bool showSystem) gettext_noop("domain constraint")); if (!showSystem && !pattern) - appendPQExpBufferStr(&buf, "WHERE n.nspname <> 'pg_catalog'\n" - " AND n.nspname <> 'information_schema'\n"); + appendSystemSchemaFilter(&buf, "t.typnamespace", false); if (!validateSQLNamePattern(&buf, pattern, !showSystem && !pattern, false, "n.nspname", "pgc.conname", NULL, @@ -1333,8 +1332,7 @@ objectDescription(const char *pattern, bool showSystem) gettext_noop("operator class")); if (!showSystem && !pattern) - appendPQExpBufferStr(&buf, " AND n.nspname <> 'pg_catalog'\n" - " AND n.nspname <> 'information_schema'\n"); + appendSystemSchemaFilter(&buf, "o.opcnamespace", true); if (!validateSQLNamePattern(&buf, pattern, true, false, "n.nspname", "o.opcname", NULL, @@ -1357,8 +1355,7 @@ objectDescription(const char *pattern, bool showSystem) gettext_noop("operator family")); if (!showSystem && !pattern) - appendPQExpBufferStr(&buf, " AND n.nspname <> 'pg_catalog'\n" - " AND n.nspname <> 'information_schema'\n"); + appendSystemSchemaFilter(&buf, "opf.opfnamespace", true); if (!validateSQLNamePattern(&buf, pattern, true, false, "n.nspname", "opf.opfname", NULL, @@ -1380,8 +1377,7 @@ objectDescription(const char *pattern, bool showSystem) gettext_noop("rule")); if (!showSystem && !pattern) - appendPQExpBufferStr(&buf, " AND n.nspname <> 'pg_catalog'\n" - " AND n.nspname <> 'information_schema'\n"); + appendSystemSchemaFilter(&buf, "c.relnamespace", true); if (!validateSQLNamePattern(&buf, pattern, true, false, "n.nspname", "r.rulename", NULL, @@ -1402,8 +1398,7 @@ objectDescription(const char *pattern, bool showSystem) gettext_noop("trigger")); if (!showSystem && !pattern) - appendPQExpBufferStr(&buf, "WHERE n.nspname <> 'pg_catalog'\n" - " AND n.nspname <> 'information_schema'\n"); + appendSystemSchemaFilter(&buf, "c.relnamespace", false); if (!validateSQLNamePattern(&buf, pattern, !showSystem && !pattern, false, "n.nspname", "t.tgname", NULL, @@ -1465,8 +1460,7 @@ describeTableDetails(const char *pattern, bool verbose, bool showSystem) " JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace\n"); if (!showSystem && !pattern) - appendPQExpBufferStr(&buf, "WHERE n.nspname <> 'pg_catalog'\n" - " AND n.nspname <> 'information_schema'\n"); + appendSystemSchemaFilter(&buf, "c.relnamespace", false); if (!validateSQLNamePattern(&buf, pattern, !showSystem && !pattern, false, "n.nspname", "c.relname", NULL, @@ -4229,9 +4223,10 @@ listTables(const char *tabtypes, const char *pattern, bool verbose, bool showSys appendPQExpBufferStr(&buf, ")\n"); if (!showSystem && !pattern) - appendPQExpBufferStr(&buf, " AND n.nspname <> 'pg_catalog'\n" - " AND n.nspname !~ '^pg_toast'\n" - " AND n.nspname <> 'information_schema'\n"); + { + appendSystemSchemaFilter(&buf, "c.relnamespace", true); + appendPQExpBufferStr(&buf, " AND n.nspname !~ '^pg_toast'\n"); + } if (!validateSQLNamePattern(&buf, pattern, true, false, "n.nspname", "c.relname", NULL, @@ -4502,9 +4497,10 @@ listPartitionedTables(const char *reltypes, const char *pattern, bool verbose) " AND NOT c.relispartition\n" : ""); if (!pattern) - appendPQExpBufferStr(&buf, " AND n.nspname <> 'pg_catalog'\n" - " AND n.nspname !~ '^pg_toast'\n" - " AND n.nspname <> 'information_schema'\n"); + { + appendSystemSchemaFilter(&buf, "c.relnamespace", true); + appendPQExpBufferStr(&buf, " AND n.nspname !~ '^pg_toast'\n"); + } if (!validateSQLNamePattern(&buf, pattern, true, false, "n.nspname", "c.relname", NULL, @@ -4673,8 +4669,7 @@ listDomains(const char *pattern, bool verbose, bool showSystem) appendPQExpBufferStr(&buf, "WHERE t.typtype = 'd'\n"); if (!showSystem && !pattern) - appendPQExpBufferStr(&buf, " AND n.nspname <> 'pg_catalog'\n" - " AND n.nspname <> 'information_schema'\n"); + appendSystemSchemaFilter(&buf, "t.typnamespace", true); if (!validateSQLNamePattern(&buf, pattern, true, false, "n.nspname", "t.typname", NULL, @@ -4752,8 +4747,7 @@ listConversions(const char *pattern, bool verbose, bool showSystem) appendPQExpBufferStr(&buf, "WHERE true\n"); if (!showSystem && !pattern) - appendPQExpBufferStr(&buf, " AND n.nspname <> 'pg_catalog'\n" - " AND n.nspname <> 'information_schema'\n"); + appendSystemSchemaFilter(&buf, "c.connamespace", true); if (!validateSQLNamePattern(&buf, pattern, true, false, "n.nspname", "c.conname", NULL, @@ -5223,8 +5217,7 @@ listCollations(const char *pattern, bool verbose, bool showSystem) "WHERE n.oid = c.collnamespace\n"); if (!showSystem && !pattern) - appendPQExpBufferStr(&buf, " AND n.nspname <> 'pg_catalog'\n" - " AND n.nspname <> 'information_schema'\n"); + appendSystemSchemaFilter(&buf, "c.collnamespace", true); /* * Hide collations that aren't usable in the current database's encoding. @@ -6425,6 +6418,25 @@ listOneExtensionContents(const char *extname, const char *oid) return true; } +/* + * Append a filter that excludes objects in pg_catalog and + * information_schema. Use the namespace OID stored in the object's catalog, + * rather than the name obtained through pg_namespace, so the restriction can + * be applied during the object catalog scan. The subquery also tolerates a + * missing information_schema. + */ +static void +appendSystemSchemaFilter(PQExpBuffer buf, const char *namespacevar, + bool have_where) +{ + appendPQExpBuffer(buf, + "%s%s <> ALL (ARRAY(\n" + " SELECT oid FROM pg_catalog.pg_namespace\n" + " WHERE nspname IN ('pg_catalog', 'information_schema')))\n", + have_where ? " AND " : "WHERE ", + namespacevar); +} + /* * validateSQLNamePattern * -- 2.44.0
^ permalink raw reply [nested|flat] 8+ messages in thread

* Re: Many of psql's describe functions bloat cache / waste mem
  2026-07-20 21:25 Many of psql's describe functions bloat cache / waste mem Andres Freund <andres@anarazel.de>
  2026-07-22 11:55 ` Re: Many of psql's describe functions bloat cache / waste mem xiaoyu liu <xliu19163@gmail.com>
  2026-07-24 03:17   ` Re: Many of psql's describe functions bloat cache / waste mem xiaoyu liu <xliu19163@gmail.com>
  2026-08-21 14:24     ` Re: Many of psql's describe functions bloat cache / waste mem Jan Nidzwetzki <jan@planetscale.com>
  2026-09-01 03:00       ` Re: Many of psql's describe functions bloat cache / waste mem xliu19163@gmail.com
  2026-09-02 10:56         ` Re: Many of psql's describe functions bloat cache / waste mem Jan Nidzwetzki <jan@planetscale.com>
  2026-09-03 02:30           ` Re: Many of psql's describe functions bloat cache / waste mem xliu19163@gmail.com
@ 2026-09-03 10:03             ` Jan Nidzwetzki <jan@planetscale.com>
  0 siblings, 0 replies; 8+ messages in thread

From: Jan Nidzwetzki @ 2026-09-03 10:03 UTC (permalink / raw)
  To: xliu19163@gmail.com, Andres Freund <andres@anarazel.de>; +Cc: pgsql-hackers

Hi Xiaoyu,

On 03.09.26 04:30, xliu19163@gmail.com wrote:
> Hi Jan,
> 
> Thanks for testing v2 and for the additional review.
> 
> Attached is v3. I split the changes into two patches:


Thank you for the v3 patch series. I have applied the patches in order
and performed a "make check-world" after each patch. They applied
cleanly to the master branch, and all tests passed successfully.

I ran a couple of tests and compared the command output to master. The
output looks good and unchanged. I can also confirm that the memory
reduction I measured with v2 is still there.

So, the series looks good to me.

Best regards
 Jan

-- 
Jan Nidzwetzki
PlanetScale Postgres Core Team







^ permalink  raw  reply  [nested|flat] 8+ messages in thread


end of thread, other threads:[~2026-09-03 10:03 UTC | newest]

Thread overview: 8+ messages (download: mbox mbox.gz follow: Atom feed)
-- links below jump to the message on this page --
2026-07-20 21:25 Many of psql's describe functions bloat cache / waste mem Andres Freund <andres@anarazel.de>
2026-07-22 11:55 ` xiaoyu liu <xliu19163@gmail.com>
2026-07-24 03:17   ` xiaoyu liu <xliu19163@gmail.com>
2026-08-21 14:24     ` Jan Nidzwetzki <jan@planetscale.com>
2026-09-01 03:00       ` xliu19163@gmail.com
2026-09-02 10:56         ` Jan Nidzwetzki <jan@planetscale.com>
2026-09-03 02:30           ` xliu19163@gmail.com
2026-09-03 10:03             ` Jan Nidzwetzki <jan@planetscale.com>

This inbox is served by DDX for PostgreSQL; see mirroring instructions
for how to clone and mirror all data and code used for this inbox