pg.ddx.io  pgsql-hackers@postgresql.org mailing list archive  
help / color / mirror / Atom feed
[PATCH] Planner support function for generate_subscripts()
8+ messages / 4 participants
[nested] [flat]

* [PATCH] Planner support function for generate_subscripts()
@ 2026-08-31 02:04 shihao zhong <zhong950419@gmail.com>
  2026-09-07 12:27 ` Re: [PATCH] Planner support function for generate_subscripts() Priyanka S <developerette@gmail.com>
  0 siblings, 1 reply; 8+ messages in thread

From: shihao zhong @ 2026-08-31 02:04 UTC (permalink / raw)
  To: pgsql-hackers <pgsql-hackers@lists.postgresql.org>

Hi hackers,
generate_subscripts() has no planner support function, so its row
estimate is always the prorows value of 1000, no matter what the
arguments are.  unnest() has been estimating its row count from the
array argument since v12.  The attached 0001 does the same for
generate_subscripts().

One difference from unnest() is that generate_subscripts() returns
one row per subscript of the requested dimension, not one row per
element.  An exact answer is therefore only possible when the array
is a plan-time constant.

The support function handles three cases:

1. If any argument is a constant NULL, it reports zero rows, since the
function is strict.
2. If both the array and the dimension number are
constants, it reports the exact length of that dimension.
3. If only the dimension number is known and it is 1, it uses
estimate_array_length().

That works because for one-dimensional arrays, the element count
equals the length of dimension 1. In all other cases it declines and
prorows applies as before.

This can change plans for the better.  Joining five subscripts
against an indexed table:
 Hash Join  (cost=637.00..649.63 rows=1000 width=45)
   Hash Cond: (s.s = items.id)
   ->  Function Scan on generate_subscripts s  (rows=1000) (actual rows=5)
   ->  Hash
         ->  Seq Scan on items  (rows=20000)
becomes
 Nested Loop  (cost=0.29..41.58 rows=5 width=45)
   ->  Function Scan on generate_subscripts s  (rows=5) (actual rows=5)
   ->  Index Scan using items_pkey on items

A note on the statistics path.  estimate_array_length() uses the
DECHIST average, which counts distinct elements, so arrays with many
duplicate or NULL elements get underestimated.  unnest() behaves the
same way.  Fixing that centrally looks like separate work.  The new
regression tests use arrays of distinct elements to keep the expected
output deterministic.

0002 lowers prorows from 1000 to 100.  After 0001, prorows is only
reached when the dimension number is unknown at plan time, or when a
higher dimension of a non-constant array is requested.  100 matches
what unnest() uses.  I kept it as a separate patch so it can be taken
or dropped on its own.

CatVersion bump is required.

Thanks,
Shihao

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

v1-0002-Lower-generate_subscripts-s-prorows-estimate-to-m.patch (application/octet-stream, 4.2K) download From 63171b354f90db33b726dd1b6789807623da7488 Mon Sep 17 00:00:00 2001 From: Zhong ShiHao <zhong950419@gmail.com> Date: Sun, 30 Aug 2026 21:58:16 -0400 Subject: [PATCH v1 2/2] Lower generate_subscripts()'s prorows estimate to match unnest() Now that generate_subscripts() has a support function, prorows is consulted only when that function declines: when the dimension number isn't known at plan time, or when a dimension above the first is requested for a non-constant array. The old value of 1000 has no particular justification and is ten times what unnest() assumes for an array of unknown size. Use 100, so the two functions estimate alike when nothing better is available. --- src/include/catalog/pg_proc.dat | 4 ++-- src/test/regress/expected/planner_est.out | 20 ++++++++++---------- 2 files changed, 12 insertions(+), 12 deletions(-) diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat index e35379afd33..05dfc9f5c3e 100644 --- a/src/include/catalog/pg_proc.dat +++ b/src/include/catalog/pg_proc.dat @@ -1711,12 +1711,12 @@ proargtypes => 'anycompatiblearray anycompatible', prosrc => 'array_positions' }, { oid => '1191', descr => 'array subscripts generator', - proname => 'generate_subscripts', prorows => '1000', + proname => 'generate_subscripts', prorows => '100', prosupport => 'generate_subscripts_support', proretset => 't', prorettype => 'int4', proargtypes => 'anyarray int4 bool', prosrc => 'generate_subscripts' }, { oid => '1192', descr => 'array subscripts generator', - proname => 'generate_subscripts', prorows => '1000', + proname => 'generate_subscripts', prorows => '100', prosupport => 'generate_subscripts_support', proretset => 't', prorettype => 'int4', proargtypes => 'anyarray int4', prosrc => 'generate_subscripts_nodir' }, diff --git a/src/test/regress/expected/planner_est.out b/src/test/regress/expected/planner_est.out index 91305e360f8..5e892ef6728 100644 --- a/src/test/regress/expected/planner_est.out +++ b/src/test/regress/expected/planner_est.out @@ -299,9 +299,9 @@ true, true, false, true); SELECT explain_mask_costs($$ SELECT * FROM generate_subscripts(ARRAY[1, 2, (SELECT 3)], (SELECT 1)) g(s);$$, false, true, false, true); - explain_mask_costs ------------------------------------------------------------------------ - Function Scan on generate_subscripts g (cost=N..N rows=1000 width=N) + explain_mask_costs +---------------------------------------------------------------------- + Function Scan on generate_subscripts g (cost=N..N rows=100 width=N) InitPlan expr_1 -> Result (cost=N..N rows=1 width=N) InitPlan expr_2 @@ -311,9 +311,9 @@ false, true, false, true); SELECT explain_mask_costs($$ SELECT * FROM generate_subscripts(ARRAY[1, 2, (SELECT 3)], 2) g(s);$$, false, true, false, true); - explain_mask_costs ------------------------------------------------------------------------ - Function Scan on generate_subscripts g (cost=N..N rows=1000 width=N) + explain_mask_costs +---------------------------------------------------------------------- + Function Scan on generate_subscripts g (cost=N..N rows=100 width=N) InitPlan expr_1 -> Result (cost=N..N rows=1 width=N) (3 rows) @@ -342,11 +342,11 @@ true, true, false, true); SELECT explain_mask_costs($$ SELECT * FROM subscript_table_1 t, LATERAL generate_subscripts(t.a, 2) g(s);$$, false, true, false, true); - explain_mask_costs ------------------------------------------------------------------------------ - Nested Loop (cost=N..N rows=100000 width=N) + explain_mask_costs +---------------------------------------------------------------------------- + Nested Loop (cost=N..N rows=10000 width=N) -> Seq Scan on subscript_table_1 t (cost=N..N rows=100 width=N) - -> Function Scan on generate_subscripts g (cost=N..N rows=1000 width=N) + -> Function Scan on generate_subscripts g (cost=N..N rows=100 width=N) (3 rows) RESET enable_memoize; -- 2.37.1 (Apple Git-137.1)
v1-0001-Add-a-planner-support-function-for-generate_subsc.patch (application/octet-stream, 20.1K) download From 576a5f36cc60b6c3c147ec9fad23c3765467b198 Mon Sep 17 00:00:00 2001 From: Zhong ShiHao <zhong950419@gmail.com> Date: Thu, 27 Aug 2026 22:14:14 -0400 Subject: [PATCH v1 1/2] Add a planner support function for generate_subscripts() Previously the planner had no way to estimate how many rows generate_subscripts() returns, so it always used the function's prorows value of 1000. Its close sibling unnest() has computed a proper estimate from its array argument since planner support functions were introduced in v12. Add generate_subscripts_support(), which handles SupportRequestRows as follows: * If any argument is a constant NULL, report zero rows: the function is strict. * If both the array and the dimension number are plan-time constants, report the length of the requested dimension exactly. * If only the dimension number is known and it is 1, use estimate_array_length(), which can consult the array column's statistics. For one-dimensional arrays, by far the common case, the total element count it reports equals the length of dimension 1. * Otherwise report nothing, and the planner falls back on prorows as before. --- src/backend/utils/adt/arrayfuncs.c | 111 ++++++++++++++ src/include/catalog/pg_proc.dat | 9 +- src/test/regress/expected/planner_est.out | 167 ++++++++++++++++++++++ src/test/regress/sql/planner_est.sql | 95 ++++++++++++ 4 files changed, 380 insertions(+), 2 deletions(-) diff --git a/src/backend/utils/adt/arrayfuncs.c b/src/backend/utils/adt/arrayfuncs.c index ef66182b047..c183ce9ea86 100644 --- a/src/backend/utils/adt/arrayfuncs.c +++ b/src/backend/utils/adt/arrayfuncs.c @@ -6000,6 +6000,117 @@ generate_subscripts_nodir(PG_FUNCTION_ARGS) return generate_subscripts(fcinfo); } +/* + * Planner support function for generate_subscripts(anyarray, int [, bool]) + * + * Unlike unnest(), generate_subscripts() returns one row per subscript of + * the *requested dimension*, not one row per array element. Those are the + * same thing for a one-dimensional array, but in general we need the length + * of dimension "dim", which we can only determine when the array itself is + * available as a constant. + */ +Datum +generate_subscripts_support(PG_FUNCTION_ARGS) +{ + Node *rawreq = (Node *) PG_GETARG_POINTER(0); + Node *ret = NULL; + + if (IsA(rawreq, SupportRequestRows)) + { + /* Try to estimate the number of rows returned */ + SupportRequestRows *req = (SupportRequestRows *) rawreq; + + if (is_funcclause(req->node)) /* be paranoid */ + { + List *args = ((FuncExpr *) req->node)->args; + Node *arg1, + *arg2, + *arg3; + + /* We can use estimated argument values here */ + arg1 = estimate_expression_value(req->root, linitial(args)); + arg2 = estimate_expression_value(req->root, lsecond(args)); + if (list_length(args) >= 3) + arg3 = estimate_expression_value(req->root, lthird(args)); + else + arg3 = NULL; + + /* + * The function is strict, so a constant NULL in any argument + * position means that no rows will be returned. Otherwise we + * need to know the dimension number to say anything at all. + */ + if ((IsA(arg1, Const) && + ((Const *) arg1)->constisnull) || + (IsA(arg2, Const) && + ((Const *) arg2)->constisnull) || + (arg3 != NULL && IsA(arg3, Const) && + ((Const *) arg3)->constisnull)) + { + req->rows = 0; + ret = (Node *) req; + } + else if (IsA(arg2, Const)) + { + int32 reqdim = DatumGetInt32(((Const *) arg2)->constvalue); + + if (reqdim <= 0) + { + /* generate_subscripts() returns no rows for such dims */ + req->rows = 0; + ret = (Node *) req; + } + else if (IsA(arg1, Const)) + { + ArrayType *arr; + + /* + * We know the array, so we can report the length of the + * requested dimension exactly. Note that the dimension's + * lower bound does not enter into it. A dimension the + * array doesn't have yields no rows, which also covers + * empty arrays, whose ndim is zero. + * + * Unlike estimate_array_length(), we don't bother to look + * through array coercions here; if one is in the way we + * simply fall through to the cases below. + */ + arr = DatumGetArrayTypeP(((Const *) arg1)->constvalue); + + if (reqdim > ARR_NDIM(arr)) + req->rows = 0; /* no such dimension */ + else + req->rows = ARR_DIMS(arr)[reqdim - 1]; + ret = (Node *) req; + } + else if (reqdim == 1) + { + /* + * All we have is estimate_array_length(), which counts + * every element rather than the length of one dimension. + * Those agree for 1-D arrays, and since dimension 1 was + * requested it's fair to suppose that's what we have. If + * not we'll overestimate, but no per-dimension statistics + * exist that could do better. + */ + req->rows = estimate_array_length(req->root, arg1); + ret = (Node *) req; + } + + /* + * Otherwise a dimension above the first was requested for an + * array that isn't a constant. We know nothing about the + * array's dimensionality, let alone the length of the + * requested dimension, so leave ret as NULL to make the + * caller fall back on prorows. + */ + } + } + } + + PG_RETURN_POINTER(ret); +} + /* * array_fill_with_lower_bounds * Create and fill array with defined lower bounds. diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat index 6979c7d1161..e35379afd33 100644 --- a/src/include/catalog/pg_proc.dat +++ b/src/include/catalog/pg_proc.dat @@ -1711,13 +1711,18 @@ proargtypes => 'anycompatiblearray anycompatible', prosrc => 'array_positions' }, { oid => '1191', descr => 'array subscripts generator', - proname => 'generate_subscripts', prorows => '1000', proretset => 't', + proname => 'generate_subscripts', prorows => '1000', + prosupport => 'generate_subscripts_support', proretset => 't', prorettype => 'int4', proargtypes => 'anyarray int4 bool', prosrc => 'generate_subscripts' }, { oid => '1192', descr => 'array subscripts generator', - proname => 'generate_subscripts', prorows => '1000', proretset => 't', + proname => 'generate_subscripts', prorows => '1000', + prosupport => 'generate_subscripts_support', proretset => 't', prorettype => 'int4', proargtypes => 'anyarray int4', prosrc => 'generate_subscripts_nodir' }, +{ oid => '9419', descr => 'planner support for generate_subscripts', + proname => 'generate_subscripts_support', prorettype => 'internal', + proargtypes => 'internal', prosrc => 'generate_subscripts_support' }, { oid => '1193', descr => 'array constructor with value', proname => 'array_fill', proisstrict => 'f', prorettype => 'anyarray', proargtypes => 'anyelement _int4', prosrc => 'array_fill' }, diff --git a/src/test/regress/expected/planner_est.out b/src/test/regress/expected/planner_est.out index 236cb274a78..91305e360f8 100644 --- a/src/test/regress/expected/planner_est.out +++ b/src/test/regress/expected/planner_est.out @@ -183,6 +183,173 @@ false, true, false, true); Function Scan on generate_series g (cost=N..N rows=1000 width=N) (1 row) +-- +-- Test the SupportRequestRows support function for generate_subscripts() +-- +-- A constant array gives an exact estimate for the requested dimension +SELECT explain_mask_costs($$ +SELECT * FROM generate_subscripts('{10,20,30,40,50}'::int[], 1) g(s);$$, +true, true, false, true); + explain_mask_costs +----------------------------------------------------------------------------------------------- + Function Scan on generate_subscripts g (cost=N..N rows=5 width=N) (actual rows=5.00 loops=1) +(1 row) + +-- As above but for the 3-argument form; "reverse" cannot change the row count +SELECT explain_mask_costs($$ +SELECT * FROM generate_subscripts('{10,20,30,40,50}'::int[], 1, true) g(s);$$, +true, true, false, true); + explain_mask_costs +----------------------------------------------------------------------------------------------- + Function Scan on generate_subscripts g (cost=N..N rows=5 width=N) (actual rows=5.00 loops=1) +(1 row) + +-- Ensure a non-zero lower bound does not affect the estimate +SELECT explain_mask_costs($$ +SELECT * FROM generate_subscripts('[5:9]={10,20,30,40,50}'::int[], 1) g(s);$$, +true, true, false, true); + explain_mask_costs +----------------------------------------------------------------------------------------------- + Function Scan on generate_subscripts g (cost=N..N rows=5 width=N) (actual rows=5.00 loops=1) +(1 row) + +-- Ensure each dimension of a multi-dimensional array is estimated separately +SELECT explain_mask_costs($$ +SELECT * FROM generate_subscripts('{{1,2,3},{4,5,6}}'::int[], 1) g(s);$$, +true, true, false, true); + explain_mask_costs +----------------------------------------------------------------------------------------------- + Function Scan on generate_subscripts g (cost=N..N rows=2 width=N) (actual rows=2.00 loops=1) +(1 row) + +SELECT explain_mask_costs($$ +SELECT * FROM generate_subscripts('{{1,2,3},{4,5,6}}'::int[], 2) g(s);$$, +true, true, false, true); + explain_mask_costs +----------------------------------------------------------------------------------------------- + Function Scan on generate_subscripts g (cost=N..N rows=3 width=N) (actual rows=3.00 loops=1) +(1 row) + +-- Ensure cases which return no rows estimate 1 row after clamping. Try an +-- out-of-range dimension, a dimension below the first, and an empty array. +SELECT explain_mask_costs($$ +SELECT * FROM generate_subscripts('{{1,2,3},{4,5,6}}'::int[], 3) g(s);$$, +true, true, false, true); + explain_mask_costs +----------------------------------------------------------------------------------------------- + Function Scan on generate_subscripts g (cost=N..N rows=1 width=N) (actual rows=0.00 loops=1) +(1 row) + +SELECT explain_mask_costs($$ +SELECT * FROM generate_subscripts('{10,20,30}'::int[], 0) g(s);$$, +true, true, false, true); + explain_mask_costs +----------------------------------------------------------------------------------------------- + Function Scan on generate_subscripts g (cost=N..N rows=1 width=N) (actual rows=0.00 loops=1) +(1 row) + +SELECT explain_mask_costs($$ +SELECT * FROM generate_subscripts('{}'::int[], 1) g(s);$$, +true, true, false, true); + explain_mask_costs +----------------------------------------------------------------------------------------------- + Function Scan on generate_subscripts g (cost=N..N rows=1 width=N) (actual rows=0.00 loops=1) +(1 row) + +-- Ensure a constant NULL in any argument position estimates no rows, since +-- generate_subscripts() is strict +SELECT explain_mask_costs($$ +SELECT * FROM generate_subscripts(NULL::int[], 1) g(s);$$, +true, true, false, true); + explain_mask_costs +----------------------------------------------------------------------------------------------- + Function Scan on generate_subscripts g (cost=N..N rows=1 width=N) (actual rows=0.00 loops=1) +(1 row) + +SELECT explain_mask_costs($$ +SELECT * FROM generate_subscripts('{10,20,30}'::int[], NULL) g(s);$$, +true, true, false, true); + explain_mask_costs +----------------------------------------------------------------------------------------------- + Function Scan on generate_subscripts g (cost=N..N rows=1 width=N) (actual rows=0.00 loops=1) +(1 row) + +SELECT explain_mask_costs($$ +SELECT * FROM generate_subscripts('{10,20,30}'::int[], 1, NULL) g(s);$$, +true, true, false, true); + explain_mask_costs +----------------------------------------------------------------------------------------------- + Function Scan on generate_subscripts g (cost=N..N rows=1 width=N) (actual rows=0.00 loops=1) +(1 row) + +-- An ArrayExpr is estimated by way of estimate_array_length() +SELECT explain_mask_costs($$ +SELECT * FROM generate_subscripts(ARRAY[1, 2, (SELECT 3)], 1) g(s);$$, +true, true, false, true); + explain_mask_costs +----------------------------------------------------------------------------------------------- + Function Scan on generate_subscripts g (cost=N..N rows=3 width=N) (actual rows=3.00 loops=1) + InitPlan expr_1 + -> Result (cost=N..N rows=1 width=N) (actual rows=1.00 loops=1) +(3 rows) + +-- Ensure we get the default row estimate when the dimension number isn't a +-- constant, and when a dimension above the first is requested for an array +-- which isn't a constant. Neither case can be estimated. +SELECT explain_mask_costs($$ +SELECT * FROM generate_subscripts(ARRAY[1, 2, (SELECT 3)], (SELECT 1)) g(s);$$, +false, true, false, true); + explain_mask_costs +----------------------------------------------------------------------- + Function Scan on generate_subscripts g (cost=N..N rows=1000 width=N) + InitPlan expr_1 + -> Result (cost=N..N rows=1 width=N) + InitPlan expr_2 + -> Result (cost=N..N rows=1 width=N) +(5 rows) + +SELECT explain_mask_costs($$ +SELECT * FROM generate_subscripts(ARRAY[1, 2, (SELECT 3)], 2) g(s);$$, +false, true, false, true); + explain_mask_costs +----------------------------------------------------------------------- + Function Scan on generate_subscripts g (cost=N..N rows=1000 width=N) + InitPlan expr_1 + -> Result (cost=N..N rows=1 width=N) +(3 rows) + +-- Ensure a Var array is estimated from the DECHIST statistics. Every array +-- below holds exactly 7 distinct elements, so the average distinct element +-- count does not depend on which rows ANALYZE happens to sample. +CREATE TEMP TABLE subscript_table_1 AS + SELECT array_agg(g) AS a FROM generate_series(1, 100) i, + LATERAL generate_series(1, 7) g GROUP BY i; +ANALYZE subscript_table_1; +-- Memoize is disabled here only to keep the plan shape stable; the node's +-- capacity and hit percentage are not masked by explain_mask_costs(). +SET enable_memoize = off; +SELECT explain_mask_costs($$ +SELECT * FROM subscript_table_1 t, LATERAL generate_subscripts(t.a, 1) g(s);$$, +true, true, false, true); + explain_mask_costs +------------------------------------------------------------------------------------------------------- + Nested Loop (cost=N..N rows=700 width=N) (actual rows=700.00 loops=1) + -> Seq Scan on subscript_table_1 t (cost=N..N rows=100 width=N) (actual rows=100.00 loops=1) + -> Function Scan on generate_subscripts g (cost=N..N rows=7 width=N) (actual rows=7.00 loops=100) +(3 rows) + +-- As above, but a dimension above the first still falls back on prorows +SELECT explain_mask_costs($$ +SELECT * FROM subscript_table_1 t, LATERAL generate_subscripts(t.a, 2) g(s);$$, +false, true, false, true); + explain_mask_costs +----------------------------------------------------------------------------- + Nested Loop (cost=N..N rows=100000 width=N) + -> Seq Scan on subscript_table_1 t (cost=N..N rows=100 width=N) + -> Function Scan on generate_subscripts g (cost=N..N rows=1000 width=N) +(3 rows) + +RESET enable_memoize; -- -- Test ScalarArrayOpExpr row estimates for <> ALL for arrays with NULLs. We -- expect the planner to estimate 1 row will match in both of the following diff --git a/src/test/regress/sql/planner_est.sql b/src/test/regress/sql/planner_est.sql index 2b696a4e4e5..b9d2dbc4a4b 100644 --- a/src/test/regress/sql/planner_est.sql +++ b/src/test/regress/sql/planner_est.sql @@ -131,6 +131,101 @@ SELECT explain_mask_costs($$ SELECT * FROM generate_series(25.0, 2.0, 0.0) g(s);$$, false, true, false, true); +-- +-- Test the SupportRequestRows support function for generate_subscripts() +-- + +-- A constant array gives an exact estimate for the requested dimension +SELECT explain_mask_costs($$ +SELECT * FROM generate_subscripts('{10,20,30,40,50}'::int[], 1) g(s);$$, +true, true, false, true); + +-- As above but for the 3-argument form; "reverse" cannot change the row count +SELECT explain_mask_costs($$ +SELECT * FROM generate_subscripts('{10,20,30,40,50}'::int[], 1, true) g(s);$$, +true, true, false, true); + +-- Ensure a non-zero lower bound does not affect the estimate +SELECT explain_mask_costs($$ +SELECT * FROM generate_subscripts('[5:9]={10,20,30,40,50}'::int[], 1) g(s);$$, +true, true, false, true); + +-- Ensure each dimension of a multi-dimensional array is estimated separately +SELECT explain_mask_costs($$ +SELECT * FROM generate_subscripts('{{1,2,3},{4,5,6}}'::int[], 1) g(s);$$, +true, true, false, true); + +SELECT explain_mask_costs($$ +SELECT * FROM generate_subscripts('{{1,2,3},{4,5,6}}'::int[], 2) g(s);$$, +true, true, false, true); + +-- Ensure cases which return no rows estimate 1 row after clamping. Try an +-- out-of-range dimension, a dimension below the first, and an empty array. +SELECT explain_mask_costs($$ +SELECT * FROM generate_subscripts('{{1,2,3},{4,5,6}}'::int[], 3) g(s);$$, +true, true, false, true); + +SELECT explain_mask_costs($$ +SELECT * FROM generate_subscripts('{10,20,30}'::int[], 0) g(s);$$, +true, true, false, true); + +SELECT explain_mask_costs($$ +SELECT * FROM generate_subscripts('{}'::int[], 1) g(s);$$, +true, true, false, true); + +-- Ensure a constant NULL in any argument position estimates no rows, since +-- generate_subscripts() is strict +SELECT explain_mask_costs($$ +SELECT * FROM generate_subscripts(NULL::int[], 1) g(s);$$, +true, true, false, true); + +SELECT explain_mask_costs($$ +SELECT * FROM generate_subscripts('{10,20,30}'::int[], NULL) g(s);$$, +true, true, false, true); + +SELECT explain_mask_costs($$ +SELECT * FROM generate_subscripts('{10,20,30}'::int[], 1, NULL) g(s);$$, +true, true, false, true); + +-- An ArrayExpr is estimated by way of estimate_array_length() +SELECT explain_mask_costs($$ +SELECT * FROM generate_subscripts(ARRAY[1, 2, (SELECT 3)], 1) g(s);$$, +true, true, false, true); + +-- Ensure we get the default row estimate when the dimension number isn't a +-- constant, and when a dimension above the first is requested for an array +-- which isn't a constant. Neither case can be estimated. +SELECT explain_mask_costs($$ +SELECT * FROM generate_subscripts(ARRAY[1, 2, (SELECT 3)], (SELECT 1)) g(s);$$, +false, true, false, true); + +SELECT explain_mask_costs($$ +SELECT * FROM generate_subscripts(ARRAY[1, 2, (SELECT 3)], 2) g(s);$$, +false, true, false, true); + +-- Ensure a Var array is estimated from the DECHIST statistics. Every array +-- below holds exactly 7 distinct elements, so the average distinct element +-- count does not depend on which rows ANALYZE happens to sample. +CREATE TEMP TABLE subscript_table_1 AS + SELECT array_agg(g) AS a FROM generate_series(1, 100) i, + LATERAL generate_series(1, 7) g GROUP BY i; +ANALYZE subscript_table_1; + +-- Memoize is disabled here only to keep the plan shape stable; the node's +-- capacity and hit percentage are not masked by explain_mask_costs(). +SET enable_memoize = off; + +SELECT explain_mask_costs($$ +SELECT * FROM subscript_table_1 t, LATERAL generate_subscripts(t.a, 1) g(s);$$, +true, true, false, true); + +-- As above, but a dimension above the first still falls back on prorows +SELECT explain_mask_costs($$ +SELECT * FROM subscript_table_1 t, LATERAL generate_subscripts(t.a, 2) g(s);$$, +false, true, false, true); + +RESET enable_memoize; + -- -- Test ScalarArrayOpExpr row estimates for <> ALL for arrays with NULLs. We -- expect the planner to estimate 1 row will match in both of the following -- 2.37.1 (Apple Git-137.1)
^ permalink raw reply [nested|flat] 8+ messages in thread

* Re: [PATCH] Planner support function for generate_subscripts()
  2026-08-31 02:04 [PATCH] Planner support function for generate_subscripts() shihao zhong <zhong950419@gmail.com>
@ 2026-09-07 12:27 ` Priyanka S <developerette@gmail.com>
  2026-09-08 01:21   ` Re: [PATCH] Planner support function for generate_subscripts() shihao zhong <zhong950419@gmail.com>
  0 siblings, 1 reply; 8+ messages in thread

From: Priyanka S @ 2026-09-07 12:27 UTC (permalink / raw)
  To: shihao zhong <zhong950419@gmail.com>; +Cc: pgsql-hackers <pgsql-hackers@lists.postgresql.org>

Hi,

I've applied the patch and done some debugging to understand the behaviour.
The approach looks good and all the cases work correctly for me. Please
find below some minor review comments. This is my first code review for
postgres, so please excuse me if I have given any wrong inputs.

1) It would be good to add a line to the description saying that
generate_subscripts() returns 0 for dimensions which do not exist in the
array. This seems like an important case which should be mentioned
specifically.

2) Missing NULL-initialisation of these vars, plus unnecessary newlines.

File: src/backend/utils/adt/arrayfuncs.c
+                       Node       *arg1,
+                                          *arg2,
+                                          *arg3;

3) Would be good to change the comment to something more descriptive like
'Check that this is a FuncExpr'. Or delete it, whichever you prefer.

File: src/backend/utils/adt/arrayfuncs.c

+               if (is_funcclause(req->node))   /* be paranoid */

4) The declaration and assignment should be combined into a single line.

File: src/backend/utils/adt/arrayfuncs.c
+                                       ArrayType  *arr;
+                                       ...
+                                       arr = DatumGetArrayTypeP(((Const *)
arg1)->constvalue);

to

+                                       ArrayType *arr =
DatumGetArrayTypeP(((Const *) arg1)->constvalue);

5) Could you please add a test case for a dimension greater than 2?  I've
tested this patch using a 4-dimensional array and it works. Here are my
query outputs, if you'd like to use them.

pgsql=# explain SELECT * FROM
generate_subscripts('{{{{1,2,3,4,5},{1,2,3,4,5},{1,2,3,4,5},{1,2,3,4,5}},{{1,2,3,4,5},{1,2,3,4,5},{1,2,3,4,5},{1,2,3,4,5}},{{1,2,3,4,5},{1,2,3,4,5},{1,2,3,4,5},{1,2,3,4,5}}},
{{{1,2,3,4,5},{1,2,3,4,5},{1,2,3,4,5},{1,2,3,4,5}},{{1,2,3,4,5},{1,2,3,4,5},{1,2,3,4,5},{1,2,3,4,5}},{{1,2,3,4,5},{1,2,3,4,5},{1,2,3,4,5},{1,2,3,4,5}}}}'::int[],
1);
                               QUERY PLAN
------------------------------------------------------------------------
 Function Scan on generate_subscripts  (cost=0.00..0.02 rows=2 width=4)
(1 row)

pgsql=# explain SELECT * FROM
generate_subscripts('{{{{1,2,3,4,5},{1,2,3,4,5},{1,2,3,4,5},{1,2,3,4,5}},{{1,2,3,4,5},{1,2,3,4,5},{1,2,3,4,5},{1,2,3,4,5}},{{1,2,3,4,5},{1,2,3,4,5},{1,2,3,4,5},{1,2,3,4,5}}},
{{{1,2,3,4,5},{1,2,3,4,5},{1,2,3,4,5},{1,2,3,4,5}},{{1,2,3,4,5},{1,2,3,4,5},{1,2,3,4,5},{1,2,3,4,5}},{{1,2,3,4,5},{1,2,3,4,5},{1,2,3,4,5},{1,2,3,4,5}}}}'::int[],
2);
                               QUERY PLAN
------------------------------------------------------------------------
 Function Scan on generate_subscripts  (cost=0.00..0.03 rows=3 width=4)
(1 row)

pgsql=# explain SELECT * FROM
generate_subscripts('{{{{1,2,3,4,5},{1,2,3,4,5},{1,2,3,4,5},{1,2,3,4,5}},{{1,2,3,4,5},{1,2,3,4,5},{1,2,3,4,5},{1,2,3,4,5}},{{1,2,3,4,5},{1,2,3,4,5},{1,2,3,4,5},{1,2,3,4,5}}},
{{{1,2,3,4,5},{1,2,3,4,5},{1,2,3,4,5},{1,2,3,4,5}},{{1,2,3,4,5},{1,2,3,4,5},{1,2,3,4,5},{1,2,3,4,5}},{{1,2,3,4,5},{1,2,3,4,5},{1,2,3,4,5},{1,2,3,4,5}}}}'::int[],
3);
                               QUERY PLAN
------------------------------------------------------------------------
 Function Scan on generate_subscripts  (cost=0.00..0.04 rows=4 width=4)
(1 row)

pgsql=# explain SELECT * FROM
generate_subscripts('{{{{1,2,3,4,5},{1,2,3,4,5},{1,2,3,4,5},{1,2,3,4,5}},{{1,2,3,4,5},{1,2,3,4,5},{1,2,3,4,5},{1,2,3,4,5}},{{1,2,3,4,5},{1,2,3,4,5},{1,2,3,4,5},{1,2,3,4,5}}},
{{{1,2,3,4,5},{1,2,3,4,5},{1,2,3,4,5},{1,2,3,4,5}},{{1,2,3,4,5},{1,2,3,4,5},{1,2,3,4,5},{1,2,3,4,5}},{{1,2,3,4,5},{1,2,3,4,5},{1,2,3,4,5},{1,2,3,4,5}}}}'::int[],
4);
                               QUERY PLAN
------------------------------------------------------------------------
 Function Scan on generate_subscripts  (cost=0.00..0.05 rows=5 width=4)
(1 row)

6) I debugged estimate_array_length() to understand the non-const array
case. For multi-dimensional arrays, it seems to use a default value of 10
to match a variable 'scalararraysel'. I was wondering if
generate_subscripts() and unnest() prorows should match this default value
of 10 instead of being set to 100?

Thanks & regards,
Priyanka

On Mon, Aug 31, 2026 at 7:34 AM shihao zhong <zhong950419@gmail.com> wrote:

> Hi hackers,
> generate_subscripts() has no planner support function, so its row
> estimate is always the prorows value of 1000, no matter what the
> arguments are.  unnest() has been estimating its row count from the
> array argument since v12.  The attached 0001 does the same for
> generate_subscripts().
>
> One difference from unnest() is that generate_subscripts() returns
> one row per subscript of the requested dimension, not one row per
> element.  An exact answer is therefore only possible when the array
> is a plan-time constant.
>
> The support function handles three cases:
>
> 1. If any argument is a constant NULL, it reports zero rows, since the
> function is strict.
> 2. If both the array and the dimension number are
> constants, it reports the exact length of that dimension.
> 3. If only the dimension number is known and it is 1, it uses
> estimate_array_length().
>
> That works because for one-dimensional arrays, the element count
> equals the length of dimension 1. In all other cases it declines and
> prorows applies as before.
>
> This can change plans for the better.  Joining five subscripts
> against an indexed table:
>  Hash Join  (cost=637.00..649.63 rows=1000 width=45)
>    Hash Cond: (s.s = items.id)
>    ->  Function Scan on generate_subscripts s  (rows=1000) (actual rows=5)
>    ->  Hash
>          ->  Seq Scan on items  (rows=20000)
> becomes
>  Nested Loop  (cost=0.29..41.58 rows=5 width=45)
>    ->  Function Scan on generate_subscripts s  (rows=5) (actual rows=5)
>    ->  Index Scan using items_pkey on items
>
> A note on the statistics path.  estimate_array_length() uses the
> DECHIST average, which counts distinct elements, so arrays with many
> duplicate or NULL elements get underestimated.  unnest() behaves the
> same way.  Fixing that centrally looks like separate work.  The new
> regression tests use arrays of distinct elements to keep the expected
> output deterministic.
>
> 0002 lowers prorows from 1000 to 100.  After 0001, prorows is only
> reached when the dimension number is unknown at plan time, or when a
> higher dimension of a non-constant array is requested.  100 matches
> what unnest() uses.  I kept it as a separate patch so it can be taken
> or dropped on its own.
>
> CatVersion bump is required.
>
> Thanks,
> Shihao
>

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

* Re: [PATCH] Planner support function for generate_subscripts()
  2026-08-31 02:04 [PATCH] Planner support function for generate_subscripts() shihao zhong <zhong950419@gmail.com>
  2026-09-07 12:27 ` Re: [PATCH] Planner support function for generate_subscripts() Priyanka S <developerette@gmail.com>
@ 2026-09-08 01:21   ` shihao zhong <zhong950419@gmail.com>
  2026-09-08 10:07     ` Re: [PATCH] Planner support function for generate_subscripts() Andrei Lepikhov <lepihov@gmail.com>
  0 siblings, 1 reply; 8+ messages in thread

From: shihao zhong @ 2026-09-08 01:21 UTC (permalink / raw)
  To: Priyanka S <developerette@gmail.com>; +Cc: pgsql-hackers <pgsql-hackers@lists.postgresql.org>

Hi Priyanka,

Thanks for the review, and for testing the patch yourself.  v2 is
attached.

1) This is already in the docs.  The text below the function table in
func-srf.sgml says: "Zero rows are returned for arrays that do not have
the requested dimension, or if any input is NULL."  The entries in the
table itself are kept to a line or two, so I left it where it is.

2) I set arg3 to NULL.  It is the only one that is not always given a
value.  arg1 and arg2 are set on the next line, so setting them to NULL
first would be a wasted store.  I did join their declarations and their
assignments, as you suggest in 4).

3) I left that comment as it is.  The same comment sits on the same
test in six other support functions, so it is how we usually write it.

4) I kept those two lines apart.  As one line it would be 87 columns
wide, which is too long.  The comment also makes more sense right above
the assignment than above the declaration.

5) Added.  I used a 3-D array where all three dimensions have a
different length, so a mistake in the dimension indexing could not
still print the right number.  I used one case instead of four, since
they all run the same line of code.  While there I dropped one of the
old cases: two of them checked the same rule, that we give up for a
dimension above the first when the array is not a constant.

6) You are right.  I think the reason is even better than the one you
give.

prorows is only used when the support function gives up.
array_unnest_support() never gives up: it sets req->rows every time it
is asked.  So unnest() never uses its prorows of 100.  For an array it
knows nothing about, unnest() really estimates 10, which is the default
in estimate_array_length().  My reason for picking 100 was to match
unnest(), but I was matching a number that is never read.

v2-0002 uses 10 instead.  Two cases still fall back on prorows, and 10
fits both:

* The dimension number is not known when we plan.  At run time it is
  almost always 1, and 10 is what the dimension-1 case gives for an
  array with no statistics.

* A dimension above the first is asked for on an array that is not a
  constant.  One dimension of an array is never longer than the whole
  array, so a large number is wrong here.

1000 fits neither case.

I kept 0002 as its own patch.  It only changes a number in the catalog,
and 0001 does not need it.  If people do not agree on the number, 0001
can still go in.

Thanks,
Shihao

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

v2-0002-Lower-generate_subscripts-s-prorows-estimate-to-1.patch (application/octet-stream, 3.5K) download From 13ae87d2feee6aafd5a9f531365d87fce0f2d702 Mon Sep 17 00:00:00 2001 From: Zhong ShiHao <zhong950419@gmail.com> Date: Mon, 7 Sep 2026 21:18:43 -0400 Subject: [PATCH v2 2/2] Lower generate_subscripts()'s prorows estimate to 10 With a support function in place, prorows is consulted only when that function declines: when the dimension number isn't known at plan time, or when a dimension above the first is requested for a non-constant array. The old value of 1000 has no particular justification. Use 10, which is what estimate_array_length() assumes for an array it knows nothing about, and hence what the dimension-one path already produces in that situation. --- src/include/catalog/pg_proc.dat | 4 ++-- src/test/regress/expected/planner_est.out | 14 +++++++------- 2 files changed, 9 insertions(+), 9 deletions(-) diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat index c1fa1984bd9..0c1debb26b3 100644 --- a/src/include/catalog/pg_proc.dat +++ b/src/include/catalog/pg_proc.dat @@ -1711,12 +1711,12 @@ proargtypes => 'anycompatiblearray anycompatible', prosrc => 'array_positions' }, { oid => '1191', descr => 'array subscripts generator', - proname => 'generate_subscripts', prorows => '1000', + proname => 'generate_subscripts', prorows => '10', prosupport => 'generate_subscripts_support', proretset => 't', prorettype => 'int4', proargtypes => 'anyarray int4 bool', prosrc => 'generate_subscripts' }, { oid => '1192', descr => 'array subscripts generator', - proname => 'generate_subscripts', prorows => '1000', + proname => 'generate_subscripts', prorows => '10', prosupport => 'generate_subscripts_support', proretset => 't', prorettype => 'int4', proargtypes => 'anyarray int4', prosrc => 'generate_subscripts_nodir' }, diff --git a/src/test/regress/expected/planner_est.out b/src/test/regress/expected/planner_est.out index 44eb5eeca32..64da9e2ca00 100644 --- a/src/test/regress/expected/planner_est.out +++ b/src/test/regress/expected/planner_est.out @@ -308,9 +308,9 @@ true, true, false, true); SELECT explain_mask_costs($$ SELECT * FROM generate_subscripts(ARRAY[1, 2, (SELECT 3)], (SELECT 1)) g(s);$$, false, true, false, true); - explain_mask_costs ------------------------------------------------------------------------ - Function Scan on generate_subscripts g (cost=N..N rows=1000 width=N) + explain_mask_costs +--------------------------------------------------------------------- + Function Scan on generate_subscripts g (cost=N..N rows=10 width=N) InitPlan expr_1 -> Result (cost=N..N rows=1 width=N) InitPlan expr_2 @@ -342,11 +342,11 @@ true, true, false, true); SELECT explain_mask_costs($$ SELECT * FROM subscript_table_1 t, LATERAL generate_subscripts(t.a, 2) g(s);$$, false, true, false, true); - explain_mask_costs ------------------------------------------------------------------------------ - Nested Loop (cost=N..N rows=100000 width=N) + explain_mask_costs +--------------------------------------------------------------------------- + Nested Loop (cost=N..N rows=1000 width=N) -> Seq Scan on subscript_table_1 t (cost=N..N rows=100 width=N) - -> Function Scan on generate_subscripts g (cost=N..N rows=1000 width=N) + -> Function Scan on generate_subscripts g (cost=N..N rows=10 width=N) (3 rows) RESET enable_memoize;
v2-0001-Add-a-planner-support-function-for-generate_subsc.patch (application/octet-stream, 20.6K) download From d9ec75289b57d2dd664a5a9f4775fdd95a37dfb2 Mon Sep 17 00:00:00 2001 From: Zhong ShiHao <zhong950419@gmail.com> Date: Mon, 7 Sep 2026 21:18:27 -0400 Subject: [PATCH v2 1/2] Add a planner support function for generate_subscripts() Previously the planner had no way to estimate how many rows generate_subscripts() returns, so it always used the function's prorows value of 1000. Its close sibling unnest() has computed a proper estimate from its array argument since planner support functions were introduced in v12. Add generate_subscripts_support(), which handles SupportRequestRows as follows: * If any argument is a constant NULL, report zero rows: the function is strict. * If both the array and the dimension number are plan-time constants, report the length of the requested dimension exactly. * If only the dimension number is known and it is 1, use estimate_array_length(), which can consult the array column's statistics. For one-dimensional arrays, by far the common case, the total element count it reports equals the length of dimension 1. * Otherwise report nothing, and the planner falls back on prorows as before. --- src/backend/utils/adt/arrayfuncs.c | 111 ++++++++++++++ src/include/catalog/pg_proc.dat | 9 +- src/test/regress/expected/planner_est.out | 167 ++++++++++++++++++++++ src/test/regress/sql/planner_est.sql | 97 +++++++++++++ 4 files changed, 382 insertions(+), 2 deletions(-) diff --git a/src/backend/utils/adt/arrayfuncs.c b/src/backend/utils/adt/arrayfuncs.c index ef66182b047..04dacacc512 100644 --- a/src/backend/utils/adt/arrayfuncs.c +++ b/src/backend/utils/adt/arrayfuncs.c @@ -6000,6 +6000,117 @@ generate_subscripts_nodir(PG_FUNCTION_ARGS) return generate_subscripts(fcinfo); } +/* + * Planner support function for generate_subscripts(anyarray, int [, bool]) + * + * Unlike unnest(), generate_subscripts() returns one row per subscript of + * the *requested dimension*, not one row per array element. Those are the + * same thing for a one-dimensional array, but in general we need the length + * of dimension "dim", which we can only determine when the array itself is + * available as a constant. + */ +Datum +generate_subscripts_support(PG_FUNCTION_ARGS) +{ + Node *rawreq = (Node *) PG_GETARG_POINTER(0); + Node *ret = NULL; + + if (IsA(rawreq, SupportRequestRows)) + { + /* Try to estimate the number of rows returned */ + SupportRequestRows *req = (SupportRequestRows *) rawreq; + + if (is_funcclause(req->node)) /* be paranoid */ + { + List *args = ((FuncExpr *) req->node)->args; + + /* We can use estimated argument values here */ + Node *arg1 = estimate_expression_value(req->root, + linitial(args)); + Node *arg2 = estimate_expression_value(req->root, + lsecond(args)); + Node *arg3 = NULL; + + /* The third argument, "reverse", is optional */ + if (list_length(args) >= 3) + arg3 = estimate_expression_value(req->root, lthird(args)); + + /* + * The function is strict, so a constant NULL in any argument + * position means that no rows will be returned. Otherwise we + * need to know the dimension number to say anything at all. + */ + if ((IsA(arg1, Const) && + ((Const *) arg1)->constisnull) || + (IsA(arg2, Const) && + ((Const *) arg2)->constisnull) || + (arg3 != NULL && IsA(arg3, Const) && + ((Const *) arg3)->constisnull)) + { + req->rows = 0; + ret = (Node *) req; + } + else if (IsA(arg2, Const)) + { + int32 reqdim = DatumGetInt32(((Const *) arg2)->constvalue); + + if (reqdim <= 0) + { + /* generate_subscripts() returns no rows for such dims */ + req->rows = 0; + ret = (Node *) req; + } + else if (IsA(arg1, Const)) + { + ArrayType *arr; + + /* + * We know the array, so we can report the length of the + * requested dimension exactly. Note that the dimension's + * lower bound does not enter into it. A dimension the + * array doesn't have yields no rows, which also covers + * empty arrays, whose ndim is zero. + * + * Unlike estimate_array_length(), we don't bother to look + * through array coercions here; if one is in the way we + * simply fall through to the cases below. + */ + arr = DatumGetArrayTypeP(((Const *) arg1)->constvalue); + + if (reqdim > ARR_NDIM(arr)) + req->rows = 0; /* no such dimension */ + else + req->rows = ARR_DIMS(arr)[reqdim - 1]; + ret = (Node *) req; + } + else if (reqdim == 1) + { + /* + * All we have is estimate_array_length(), which counts + * every element rather than the length of one dimension. + * Those agree for 1-D arrays, and since dimension 1 was + * requested it's fair to suppose that's what we have. If + * not we'll overestimate, but no per-dimension statistics + * exist that could do better. + */ + req->rows = estimate_array_length(req->root, arg1); + ret = (Node *) req; + } + + /* + * Otherwise a dimension above the first was requested for an + * array that isn't a constant. We know nothing about the + * array's dimensionality, let alone the length of the + * requested dimension, so leave ret as NULL to make the + * caller fall back on prorows. + */ + } + } + } + + PG_RETURN_POINTER(ret); +} + /* * array_fill_with_lower_bounds * Create and fill array with defined lower bounds. diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat index 960763ee50b..c1fa1984bd9 100644 --- a/src/include/catalog/pg_proc.dat +++ b/src/include/catalog/pg_proc.dat @@ -1711,13 +1711,18 @@ proargtypes => 'anycompatiblearray anycompatible', prosrc => 'array_positions' }, { oid => '1191', descr => 'array subscripts generator', - proname => 'generate_subscripts', prorows => '1000', proretset => 't', + proname => 'generate_subscripts', prorows => '1000', + prosupport => 'generate_subscripts_support', proretset => 't', prorettype => 'int4', proargtypes => 'anyarray int4 bool', prosrc => 'generate_subscripts' }, { oid => '1192', descr => 'array subscripts generator', - proname => 'generate_subscripts', prorows => '1000', proretset => 't', + proname => 'generate_subscripts', prorows => '1000', + prosupport => 'generate_subscripts_support', proretset => 't', prorettype => 'int4', proargtypes => 'anyarray int4', prosrc => 'generate_subscripts_nodir' }, +{ oid => '9419', descr => 'planner support for generate_subscripts', + proname => 'generate_subscripts_support', prorettype => 'internal', + proargtypes => 'internal', prosrc => 'generate_subscripts_support' }, { oid => '1193', descr => 'array constructor with value', proname => 'array_fill', proisstrict => 'f', prorettype => 'anyarray', proargtypes => 'anyelement _int4', prosrc => 'array_fill' }, diff --git a/src/test/regress/expected/planner_est.out b/src/test/regress/expected/planner_est.out index 236cb274a78..44eb5eeca32 100644 --- a/src/test/regress/expected/planner_est.out +++ b/src/test/regress/expected/planner_est.out @@ -183,6 +183,173 @@ false, true, false, true); Function Scan on generate_series g (cost=N..N rows=1000 width=N) (1 row) +-- +-- Test the SupportRequestRows support function for generate_subscripts() +-- +-- A constant array gives an exact estimate for the requested dimension +SELECT explain_mask_costs($$ +SELECT * FROM generate_subscripts('{10,20,30,40,50}'::int[], 1) g(s);$$, +true, true, false, true); + explain_mask_costs +----------------------------------------------------------------------------------------------- + Function Scan on generate_subscripts g (cost=N..N rows=5 width=N) (actual rows=5.00 loops=1) +(1 row) + +-- As above but for the 3-argument form; "reverse" cannot change the row count +SELECT explain_mask_costs($$ +SELECT * FROM generate_subscripts('{10,20,30,40,50}'::int[], 1, true) g(s);$$, +true, true, false, true); + explain_mask_costs +----------------------------------------------------------------------------------------------- + Function Scan on generate_subscripts g (cost=N..N rows=5 width=N) (actual rows=5.00 loops=1) +(1 row) + +-- Ensure a non-zero lower bound does not affect the estimate +SELECT explain_mask_costs($$ +SELECT * FROM generate_subscripts('[5:9]={10,20,30,40,50}'::int[], 1) g(s);$$, +true, true, false, true); + explain_mask_costs +----------------------------------------------------------------------------------------------- + Function Scan on generate_subscripts g (cost=N..N rows=5 width=N) (actual rows=5.00 loops=1) +(1 row) + +-- Ensure each dimension of a multi-dimensional array is estimated separately +SELECT explain_mask_costs($$ +SELECT * FROM generate_subscripts('{{1,2,3},{4,5,6}}'::int[], 1) g(s);$$, +true, true, false, true); + explain_mask_costs +----------------------------------------------------------------------------------------------- + Function Scan on generate_subscripts g (cost=N..N rows=2 width=N) (actual rows=2.00 loops=1) +(1 row) + +SELECT explain_mask_costs($$ +SELECT * FROM generate_subscripts('{{1,2,3},{4,5,6}}'::int[], 2) g(s);$$, +true, true, false, true); + explain_mask_costs +----------------------------------------------------------------------------------------------- + Function Scan on generate_subscripts g (cost=N..N rows=3 width=N) (actual rows=3.00 loops=1) +(1 row) + +-- Ensure a dimension above the second is handled too. Each dimension of this +-- array has a different length, so a mix-up could not go unnoticed. +SELECT explain_mask_costs($$ +SELECT * FROM generate_subscripts('{{{1,2,3,4},{5,6,7,8},{9,10,11,12}},{{13,14,15,16},{17,18,19,20},{21,22,23,24}}}'::int[], 3) g(s);$$, +true, true, false, true); + explain_mask_costs +----------------------------------------------------------------------------------------------- + Function Scan on generate_subscripts g (cost=N..N rows=4 width=N) (actual rows=4.00 loops=1) +(1 row) + +-- Ensure cases which return no rows estimate 1 row after clamping. Try an +-- out-of-range dimension, a dimension below the first, and an empty array. +SELECT explain_mask_costs($$ +SELECT * FROM generate_subscripts('{{1,2,3},{4,5,6}}'::int[], 3) g(s);$$, +true, true, false, true); + explain_mask_costs +----------------------------------------------------------------------------------------------- + Function Scan on generate_subscripts g (cost=N..N rows=1 width=N) (actual rows=0.00 loops=1) +(1 row) + +SELECT explain_mask_costs($$ +SELECT * FROM generate_subscripts('{10,20,30}'::int[], 0) g(s);$$, +true, true, false, true); + explain_mask_costs +----------------------------------------------------------------------------------------------- + Function Scan on generate_subscripts g (cost=N..N rows=1 width=N) (actual rows=0.00 loops=1) +(1 row) + +SELECT explain_mask_costs($$ +SELECT * FROM generate_subscripts('{}'::int[], 1) g(s);$$, +true, true, false, true); + explain_mask_costs +----------------------------------------------------------------------------------------------- + Function Scan on generate_subscripts g (cost=N..N rows=1 width=N) (actual rows=0.00 loops=1) +(1 row) + +-- Ensure a constant NULL in any argument position estimates no rows, since +-- generate_subscripts() is strict +SELECT explain_mask_costs($$ +SELECT * FROM generate_subscripts(NULL::int[], 1) g(s);$$, +true, true, false, true); + explain_mask_costs +----------------------------------------------------------------------------------------------- + Function Scan on generate_subscripts g (cost=N..N rows=1 width=N) (actual rows=0.00 loops=1) +(1 row) + +SELECT explain_mask_costs($$ +SELECT * FROM generate_subscripts('{10,20,30}'::int[], NULL) g(s);$$, +true, true, false, true); + explain_mask_costs +----------------------------------------------------------------------------------------------- + Function Scan on generate_subscripts g (cost=N..N rows=1 width=N) (actual rows=0.00 loops=1) +(1 row) + +SELECT explain_mask_costs($$ +SELECT * FROM generate_subscripts('{10,20,30}'::int[], 1, NULL) g(s);$$, +true, true, false, true); + explain_mask_costs +----------------------------------------------------------------------------------------------- + Function Scan on generate_subscripts g (cost=N..N rows=1 width=N) (actual rows=0.00 loops=1) +(1 row) + +-- An ArrayExpr is estimated by way of estimate_array_length() +SELECT explain_mask_costs($$ +SELECT * FROM generate_subscripts(ARRAY[1, 2, (SELECT 3)], 1) g(s);$$, +true, true, false, true); + explain_mask_costs +----------------------------------------------------------------------------------------------- + Function Scan on generate_subscripts g (cost=N..N rows=3 width=N) (actual rows=3.00 loops=1) + InitPlan expr_1 + -> Result (cost=N..N rows=1 width=N) (actual rows=1.00 loops=1) +(3 rows) + +-- Ensure we get the default row estimate when the dimension number isn't a +-- constant, since then we don't even know which dimension is wanted +SELECT explain_mask_costs($$ +SELECT * FROM generate_subscripts(ARRAY[1, 2, (SELECT 3)], (SELECT 1)) g(s);$$, +false, true, false, true); + explain_mask_costs +----------------------------------------------------------------------- + Function Scan on generate_subscripts g (cost=N..N rows=1000 width=N) + InitPlan expr_1 + -> Result (cost=N..N rows=1 width=N) + InitPlan expr_2 + -> Result (cost=N..N rows=1 width=N) +(5 rows) + +-- Ensure a Var array is estimated from the DECHIST statistics. Every array +-- below holds exactly 7 distinct elements, so the average distinct element +-- count does not depend on which rows ANALYZE happens to sample. +CREATE TEMP TABLE subscript_table_1 AS + SELECT array_agg(g) AS a FROM generate_series(1, 100) i, + LATERAL generate_series(1, 7) g GROUP BY i; +ANALYZE subscript_table_1; +-- Memoize is disabled here only to keep the plan shape stable; the node's +-- capacity and hit percentage are not masked by explain_mask_costs(). +SET enable_memoize = off; +SELECT explain_mask_costs($$ +SELECT * FROM subscript_table_1 t, LATERAL generate_subscripts(t.a, 1) g(s);$$, +true, true, false, true); + explain_mask_costs +------------------------------------------------------------------------------------------------------- + Nested Loop (cost=N..N rows=700 width=N) (actual rows=700.00 loops=1) + -> Seq Scan on subscript_table_1 t (cost=N..N rows=100 width=N) (actual rows=100.00 loops=1) + -> Function Scan on generate_subscripts g (cost=N..N rows=7 width=N) (actual rows=7.00 loops=100) +(3 rows) + +-- As above, but a dimension above the first falls back on prorows: the element +-- count in the statistics says nothing about the length of that dimension +SELECT explain_mask_costs($$ +SELECT * FROM subscript_table_1 t, LATERAL generate_subscripts(t.a, 2) g(s);$$, +false, true, false, true); + explain_mask_costs +----------------------------------------------------------------------------- + Nested Loop (cost=N..N rows=100000 width=N) + -> Seq Scan on subscript_table_1 t (cost=N..N rows=100 width=N) + -> Function Scan on generate_subscripts g (cost=N..N rows=1000 width=N) +(3 rows) + +RESET enable_memoize; -- -- Test ScalarArrayOpExpr row estimates for <> ALL for arrays with NULLs. We -- expect the planner to estimate 1 row will match in both of the following diff --git a/src/test/regress/sql/planner_est.sql b/src/test/regress/sql/planner_est.sql index 2b696a4e4e5..c4e7ba32cf3 100644 --- a/src/test/regress/sql/planner_est.sql +++ b/src/test/regress/sql/planner_est.sql @@ -131,6 +131,103 @@ SELECT explain_mask_costs($$ SELECT * FROM generate_series(25.0, 2.0, 0.0) g(s);$$, false, true, false, true); +-- +-- Test the SupportRequestRows support function for generate_subscripts() +-- + +-- A constant array gives an exact estimate for the requested dimension +SELECT explain_mask_costs($$ +SELECT * FROM generate_subscripts('{10,20,30,40,50}'::int[], 1) g(s);$$, +true, true, false, true); + +-- As above but for the 3-argument form; "reverse" cannot change the row count +SELECT explain_mask_costs($$ +SELECT * FROM generate_subscripts('{10,20,30,40,50}'::int[], 1, true) g(s);$$, +true, true, false, true); + +-- Ensure a non-zero lower bound does not affect the estimate +SELECT explain_mask_costs($$ +SELECT * FROM generate_subscripts('[5:9]={10,20,30,40,50}'::int[], 1) g(s);$$, +true, true, false, true); + +-- Ensure each dimension of a multi-dimensional array is estimated separately +SELECT explain_mask_costs($$ +SELECT * FROM generate_subscripts('{{1,2,3},{4,5,6}}'::int[], 1) g(s);$$, +true, true, false, true); + +SELECT explain_mask_costs($$ +SELECT * FROM generate_subscripts('{{1,2,3},{4,5,6}}'::int[], 2) g(s);$$, +true, true, false, true); + +-- Ensure a dimension above the second is handled too. Each dimension of this +-- array has a different length, so a mix-up could not go unnoticed. +SELECT explain_mask_costs($$ +SELECT * FROM generate_subscripts('{{{1,2,3,4},{5,6,7,8},{9,10,11,12}},{{13,14,15,16},{17,18,19,20},{21,22,23,24}}}'::int[], 3) g(s);$$, +true, true, false, true); + +-- Ensure cases which return no rows estimate 1 row after clamping. Try an +-- out-of-range dimension, a dimension below the first, and an empty array. +SELECT explain_mask_costs($$ +SELECT * FROM generate_subscripts('{{1,2,3},{4,5,6}}'::int[], 3) g(s);$$, +true, true, false, true); + +SELECT explain_mask_costs($$ +SELECT * FROM generate_subscripts('{10,20,30}'::int[], 0) g(s);$$, +true, true, false, true); + +SELECT explain_mask_costs($$ +SELECT * FROM generate_subscripts('{}'::int[], 1) g(s);$$, +true, true, false, true); + +-- Ensure a constant NULL in any argument position estimates no rows, since +-- generate_subscripts() is strict +SELECT explain_mask_costs($$ +SELECT * FROM generate_subscripts(NULL::int[], 1) g(s);$$, +true, true, false, true); + +SELECT explain_mask_costs($$ +SELECT * FROM generate_subscripts('{10,20,30}'::int[], NULL) g(s);$$, +true, true, false, true); + +SELECT explain_mask_costs($$ +SELECT * FROM generate_subscripts('{10,20,30}'::int[], 1, NULL) g(s);$$, +true, true, false, true); + +-- An ArrayExpr is estimated by way of estimate_array_length() +SELECT explain_mask_costs($$ +SELECT * FROM generate_subscripts(ARRAY[1, 2, (SELECT 3)], 1) g(s);$$, +true, true, false, true); + +-- Ensure we get the default row estimate when the dimension number isn't a +-- constant, since then we don't even know which dimension is wanted +SELECT explain_mask_costs($$ +SELECT * FROM generate_subscripts(ARRAY[1, 2, (SELECT 3)], (SELECT 1)) g(s);$$, +false, true, false, true); + +-- Ensure a Var array is estimated from the DECHIST statistics. Every array +-- below holds exactly 7 distinct elements, so the average distinct element +-- count does not depend on which rows ANALYZE happens to sample. +CREATE TEMP TABLE subscript_table_1 AS + SELECT array_agg(g) AS a FROM generate_series(1, 100) i, + LATERAL generate_series(1, 7) g GROUP BY i; +ANALYZE subscript_table_1; + +-- Memoize is disabled here only to keep the plan shape stable; the node's +-- capacity and hit percentage are not masked by explain_mask_costs(). +SET enable_memoize = off; + +SELECT explain_mask_costs($$ +SELECT * FROM subscript_table_1 t, LATERAL generate_subscripts(t.a, 1) g(s);$$, +true, true, false, true); + +-- As above, but a dimension above the first falls back on prorows: the element +-- count in the statistics says nothing about the length of that dimension +SELECT explain_mask_costs($$ +SELECT * FROM subscript_table_1 t, LATERAL generate_subscripts(t.a, 2) g(s);$$, +false, true, false, true); + +RESET enable_memoize; + -- -- Test ScalarArrayOpExpr row estimates for <> ALL for arrays with NULLs. We -- expect the planner to estimate 1 row will match in both of the following
^ permalink raw reply [nested|flat] 8+ messages in thread

* Re: [PATCH] Planner support function for generate_subscripts()
  2026-08-31 02:04 [PATCH] Planner support function for generate_subscripts() shihao zhong <zhong950419@gmail.com>
  2026-09-07 12:27 ` Re: [PATCH] Planner support function for generate_subscripts() Priyanka S <developerette@gmail.com>
  2026-09-08 01:21   ` Re: [PATCH] Planner support function for generate_subscripts() shihao zhong <zhong950419@gmail.com>
@ 2026-09-08 10:07     ` Andrei Lepikhov <lepihov@gmail.com>
  2026-09-09 01:20       ` Re: [PATCH] Planner support function for generate_subscripts() shihao zhong <zhong950419@gmail.com>
  0 siblings, 1 reply; 8+ messages in thread

From: Andrei Lepikhov @ 2026-09-08 10:07 UTC (permalink / raw)
  To: shihao zhong <zhong950419@gmail.com>; Priyanka S <developerette@gmail.com>; +Cc: pgsql-hackers <pgsql-hackers@lists.postgresql.org>

On 08/09/2026 03:21, shihao zhong wrote:
> * A dimension above the first is asked for on an array that is not a
>   constant.  One dimension of an array is never longer than the whole
>   array, so a large number is wrong here.
> 
> 1000 fits neither case.
> 
> I kept 0002 as its own patch.  It only changes a number in the catalog,
> and 0001 does not need it.  If people do not agree on the number, 0001
> can still go in.
I'd say that detecting the estimate_array_length's default value for the rows
number and returning constant 1000 as used before might make life of engineers
easier and query plans more stable during upgrade.
Hence, maybe it makes sense to follow the way of group-by estimations -
introduce something like one more 'isdefault' parameter to the
estimate_array_length?

Basically, this code looks good. But I'd like to see more assertions: if
something will be changed at the functions itself it would more quickly detect
issues in the prosupport routine. For example:
- Assert(req->root != NULL);
- Type of arg2
- Potentially, no more than 3 arguments of the function
- Maybe hard oid check on F_GENERATE_SUBSCRIPTS / F_GENERATE_SUBSCRIPTS_NODIR

This topic also raises the question of the practical usability of the average
total number of elements in an array column. Your tests highlight a gap in
estimates for more than two dimensions.

regards, Andrei Lepikhov,
pgEdge






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

* Re: [PATCH] Planner support function for generate_subscripts()
  2026-08-31 02:04 [PATCH] Planner support function for generate_subscripts() shihao zhong <zhong950419@gmail.com>
  2026-09-07 12:27 ` Re: [PATCH] Planner support function for generate_subscripts() Priyanka S <developerette@gmail.com>
  2026-09-08 01:21   ` Re: [PATCH] Planner support function for generate_subscripts() shihao zhong <zhong950419@gmail.com>
  2026-09-08 10:07     ` Re: [PATCH] Planner support function for generate_subscripts() Andrei Lepikhov <lepihov@gmail.com>
@ 2026-09-09 01:20       ` shihao zhong <zhong950419@gmail.com>
  2026-09-14 01:54         ` Re: [PATCH] Planner support function for generate_subscripts() shihao zhong <zhong950419@gmail.com>
  0 siblings, 1 reply; 8+ messages in thread

From: shihao zhong @ 2026-09-09 01:20 UTC (permalink / raw)
  To: Andrei Lepikhov <lepihov@gmail.com>; +Cc: Priyanka S <developerette@gmail.com>; pgsql-hackers <pgsql-hackers@lists.postgresql.org>

Hi Andrei,
Thanks for the review.  v3 attached.

> But I'd like to see more assertions

I took all of these.  One small change on the root check.  The
comment above get_function_rows() says root can be NULL.  So the
function now declines when root is NULL instead of asserting.
Without this check, estimate_expression_value() would crash.
The function also declines when req->funcid is not one of the two
generate_subscripts() entries, or when the call has fewer than two
arguments.  These are runtime checks on purpose.  Assertions go away
in production builds, and ALTER FUNCTION ... SUPPORT can attach this
function to anything.  Once the funcid is checked, the parser
guarantees the argument count and types.  So those two stay as plain
assertions.

> maybe it makes sense to follow the way of group-by estimations -
> introduce something like one more 'isdefault' parameter to the
> estimate_array_length?

After 0002, the fallback and the default guess are both 10.  So
detecting the default would not change any plan.  If you would
rather keep prorows at 1000, an isdefault flag would be the right
tool, and I can rework 0002 that way.  I still prefer 10.  unnest()
has given 10 for an array with no statistics since v12, and matching
it keeps the two functions consistent.

> Your tests highlight a gap in estimates for more than two
> dimensions.

Yes.  There are no statistics about single dimensions.  The DECHIST
number is only an average of distinct element counts.  So a higher
dimension of a non-constant array cannot be estimated today.  Making
array_typanalyze collect such data would be a separate project.
Until then the patch declines instead of guessing.

Thanks,
Shihao

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

v3-0001-Add-a-planner-support-function-for-generate_subsc.patch (application/octet-stream, 21.2K) download From dc3d43afa11345881f2f1cb42fdfcdaed831fa2b Mon Sep 17 00:00:00 2001 From: Zhong ShiHao <zhong950419@gmail.com> Date: Mon, 7 Sep 2026 21:18:27 -0400 Subject: [PATCH v3 1/2] Add a planner support function for generate_subscripts() Previously the planner had no way to estimate how many rows generate_subscripts() returns, so it always used the function's prorows value of 1000. Its close sibling unnest() has computed a proper estimate from its array argument since planner support functions were introduced in v12. Add generate_subscripts_support(), which handles SupportRequestRows as follows: * If any argument is a constant NULL, report zero rows: the function is strict. * If both the array and the dimension number are plan-time constants, report the length of the requested dimension exactly. * If only the dimension number is known and it is 1, use estimate_array_length(), which can consult the array column's statistics. For one-dimensional arrays, by far the common case, the total element count it reports equals the length of dimension 1. * Otherwise report nothing, and the planner falls back on prorows as before. --- src/backend/utils/adt/arrayfuncs.c | 126 ++++++++++++++++ src/include/catalog/pg_proc.dat | 9 +- src/test/regress/expected/planner_est.out | 167 ++++++++++++++++++++++ src/test/regress/sql/planner_est.sql | 97 +++++++++++++ 4 files changed, 397 insertions(+), 2 deletions(-) diff --git a/src/backend/utils/adt/arrayfuncs.c b/src/backend/utils/adt/arrayfuncs.c index ef66182b047..920b5ed1347 100644 --- a/src/backend/utils/adt/arrayfuncs.c +++ b/src/backend/utils/adt/arrayfuncs.c @@ -6000,6 +6000,132 @@ generate_subscripts_nodir(PG_FUNCTION_ARGS) return generate_subscripts(fcinfo); } +/* + * Planner support function for generate_subscripts(anyarray, int [, bool]) + * + * Unlike unnest(), generate_subscripts() returns one row per subscript of + * the *requested dimension*, not one row per array element. Those are the + * same thing for a one-dimensional array, but in general we need the length + * of dimension "dim", which we can only determine when the array itself is + * available as a constant. + */ +Datum +generate_subscripts_support(PG_FUNCTION_ARGS) +{ + Node *rawreq = (Node *) PG_GETARG_POINTER(0); + Node *ret = NULL; + + if (IsA(rawreq, SupportRequestRows)) + { + /* Try to estimate the number of rows returned */ + SupportRequestRows *req = (SupportRequestRows *) rawreq; + + /* + * Be paranoid: only proceed when we are attached to one of the + * generate_subscripts() entries, the call site is a FuncExpr carrying + * enough arguments, and root is available, since + * estimate_expression_value() requires it. Otherwise decline, and + * prorows applies. + */ + if ((req->funcid == F_GENERATE_SUBSCRIPTS_ANYARRAY_INT4 || + req->funcid == F_GENERATE_SUBSCRIPTS_ANYARRAY_INT4_BOOL) && + req->root != NULL && + is_funcclause(req->node) && + list_length(((FuncExpr *) req->node)->args) >= 2) + { + List *args = ((FuncExpr *) req->node)->args; + + /* The parser enforces the signature for these two functions */ + Assert(list_length(args) == 2 || list_length(args) == 3); + Assert(exprType(lsecond(args)) == INT4OID); + + /* We can use estimated argument values here */ + Node *arg1 = estimate_expression_value(req->root, + linitial(args)); + Node *arg2 = estimate_expression_value(req->root, + lsecond(args)); + Node *arg3 = NULL; + + /* The third argument, "reverse", is optional */ + if (list_length(args) >= 3) + arg3 = estimate_expression_value(req->root, lthird(args)); + + /* + * The function is strict, so a constant NULL in any argument + * position means that no rows will be returned. Otherwise we + * need to know the dimension number to say anything at all. + */ + if ((IsA(arg1, Const) && + ((Const *) arg1)->constisnull) || + (IsA(arg2, Const) && + ((Const *) arg2)->constisnull) || + (arg3 != NULL && IsA(arg3, Const) && + ((Const *) arg3)->constisnull)) + { + req->rows = 0; + ret = (Node *) req; + } + else if (IsA(arg2, Const)) + { + int32 reqdim = DatumGetInt32(((Const *) arg2)->constvalue); + + if (reqdim <= 0) + { + /* generate_subscripts() returns no rows for such dims */ + req->rows = 0; + ret = (Node *) req; + } + else if (IsA(arg1, Const)) + { + ArrayType *arr; + + /* + * We know the array, so we can report the length of the + * requested dimension exactly. Note that the dimension's + * lower bound does not enter into it. A dimension the + * array doesn't have yields no rows, which also covers + * empty arrays, whose ndim is zero. + * + * Unlike estimate_array_length(), we don't bother to look + * through array coercions here; if one is in the way we + * simply fall through to the cases below. + */ + arr = DatumGetArrayTypeP(((Const *) arg1)->constvalue); + + if (reqdim > ARR_NDIM(arr)) + req->rows = 0; /* no such dimension */ + else + req->rows = ARR_DIMS(arr)[reqdim - 1]; + ret = (Node *) req; + } + else if (reqdim == 1) + { + /* + * All we have is estimate_array_length(), which counts + * every element rather than the length of one dimension. + * Those agree for 1-D arrays, and since dimension 1 was + * requested it's fair to suppose that's what we have. If + * not we'll overestimate, but no per-dimension statistics + * exist that could do better. + */ + req->rows = estimate_array_length(req->root, arg1); + ret = (Node *) req; + } + + /* + * Otherwise a dimension above the first was requested for an + * array that isn't a constant. We know nothing about the + * array's dimensionality, let alone the length of the + * requested dimension, so leave ret as NULL to make the + * caller fall back on prorows. + */ + } + } + } + + PG_RETURN_POINTER(ret); +} + /* * array_fill_with_lower_bounds * Create and fill array with defined lower bounds. diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat index 960763ee50b..c1fa1984bd9 100644 --- a/src/include/catalog/pg_proc.dat +++ b/src/include/catalog/pg_proc.dat @@ -1711,13 +1711,18 @@ proargtypes => 'anycompatiblearray anycompatible', prosrc => 'array_positions' }, { oid => '1191', descr => 'array subscripts generator', - proname => 'generate_subscripts', prorows => '1000', proretset => 't', + proname => 'generate_subscripts', prorows => '1000', + prosupport => 'generate_subscripts_support', proretset => 't', prorettype => 'int4', proargtypes => 'anyarray int4 bool', prosrc => 'generate_subscripts' }, { oid => '1192', descr => 'array subscripts generator', - proname => 'generate_subscripts', prorows => '1000', proretset => 't', + proname => 'generate_subscripts', prorows => '1000', + prosupport => 'generate_subscripts_support', proretset => 't', prorettype => 'int4', proargtypes => 'anyarray int4', prosrc => 'generate_subscripts_nodir' }, +{ oid => '9419', descr => 'planner support for generate_subscripts', + proname => 'generate_subscripts_support', prorettype => 'internal', + proargtypes => 'internal', prosrc => 'generate_subscripts_support' }, { oid => '1193', descr => 'array constructor with value', proname => 'array_fill', proisstrict => 'f', prorettype => 'anyarray', proargtypes => 'anyelement _int4', prosrc => 'array_fill' }, diff --git a/src/test/regress/expected/planner_est.out b/src/test/regress/expected/planner_est.out index 236cb274a78..44eb5eeca32 100644 --- a/src/test/regress/expected/planner_est.out +++ b/src/test/regress/expected/planner_est.out @@ -183,6 +183,173 @@ false, true, false, true); Function Scan on generate_series g (cost=N..N rows=1000 width=N) (1 row) +-- +-- Test the SupportRequestRows support function for generate_subscripts() +-- +-- A constant array gives an exact estimate for the requested dimension +SELECT explain_mask_costs($$ +SELECT * FROM generate_subscripts('{10,20,30,40,50}'::int[], 1) g(s);$$, +true, true, false, true); + explain_mask_costs +----------------------------------------------------------------------------------------------- + Function Scan on generate_subscripts g (cost=N..N rows=5 width=N) (actual rows=5.00 loops=1) +(1 row) + +-- As above but for the 3-argument form; "reverse" cannot change the row count +SELECT explain_mask_costs($$ +SELECT * FROM generate_subscripts('{10,20,30,40,50}'::int[], 1, true) g(s);$$, +true, true, false, true); + explain_mask_costs +----------------------------------------------------------------------------------------------- + Function Scan on generate_subscripts g (cost=N..N rows=5 width=N) (actual rows=5.00 loops=1) +(1 row) + +-- Ensure a non-zero lower bound does not affect the estimate +SELECT explain_mask_costs($$ +SELECT * FROM generate_subscripts('[5:9]={10,20,30,40,50}'::int[], 1) g(s);$$, +true, true, false, true); + explain_mask_costs +----------------------------------------------------------------------------------------------- + Function Scan on generate_subscripts g (cost=N..N rows=5 width=N) (actual rows=5.00 loops=1) +(1 row) + +-- Ensure each dimension of a multi-dimensional array is estimated separately +SELECT explain_mask_costs($$ +SELECT * FROM generate_subscripts('{{1,2,3},{4,5,6}}'::int[], 1) g(s);$$, +true, true, false, true); + explain_mask_costs +----------------------------------------------------------------------------------------------- + Function Scan on generate_subscripts g (cost=N..N rows=2 width=N) (actual rows=2.00 loops=1) +(1 row) + +SELECT explain_mask_costs($$ +SELECT * FROM generate_subscripts('{{1,2,3},{4,5,6}}'::int[], 2) g(s);$$, +true, true, false, true); + explain_mask_costs +----------------------------------------------------------------------------------------------- + Function Scan on generate_subscripts g (cost=N..N rows=3 width=N) (actual rows=3.00 loops=1) +(1 row) + +-- Ensure a dimension above the second is handled too. Each dimension of this +-- array has a different length, so a mix-up could not go unnoticed. +SELECT explain_mask_costs($$ +SELECT * FROM generate_subscripts('{{{1,2,3,4},{5,6,7,8},{9,10,11,12}},{{13,14,15,16},{17,18,19,20},{21,22,23,24}}}'::int[], 3) g(s);$$, +true, true, false, true); + explain_mask_costs +----------------------------------------------------------------------------------------------- + Function Scan on generate_subscripts g (cost=N..N rows=4 width=N) (actual rows=4.00 loops=1) +(1 row) + +-- Ensure cases which return no rows estimate 1 row after clamping. Try an +-- out-of-range dimension, a dimension below the first, and an empty array. +SELECT explain_mask_costs($$ +SELECT * FROM generate_subscripts('{{1,2,3},{4,5,6}}'::int[], 3) g(s);$$, +true, true, false, true); + explain_mask_costs +----------------------------------------------------------------------------------------------- + Function Scan on generate_subscripts g (cost=N..N rows=1 width=N) (actual rows=0.00 loops=1) +(1 row) + +SELECT explain_mask_costs($$ +SELECT * FROM generate_subscripts('{10,20,30}'::int[], 0) g(s);$$, +true, true, false, true); + explain_mask_costs +----------------------------------------------------------------------------------------------- + Function Scan on generate_subscripts g (cost=N..N rows=1 width=N) (actual rows=0.00 loops=1) +(1 row) + +SELECT explain_mask_costs($$ +SELECT * FROM generate_subscripts('{}'::int[], 1) g(s);$$, +true, true, false, true); + explain_mask_costs +----------------------------------------------------------------------------------------------- + Function Scan on generate_subscripts g (cost=N..N rows=1 width=N) (actual rows=0.00 loops=1) +(1 row) + +-- Ensure a constant NULL in any argument position estimates no rows, since +-- generate_subscripts() is strict +SELECT explain_mask_costs($$ +SELECT * FROM generate_subscripts(NULL::int[], 1) g(s);$$, +true, true, false, true); + explain_mask_costs +----------------------------------------------------------------------------------------------- + Function Scan on generate_subscripts g (cost=N..N rows=1 width=N) (actual rows=0.00 loops=1) +(1 row) + +SELECT explain_mask_costs($$ +SELECT * FROM generate_subscripts('{10,20,30}'::int[], NULL) g(s);$$, +true, true, false, true); + explain_mask_costs +----------------------------------------------------------------------------------------------- + Function Scan on generate_subscripts g (cost=N..N rows=1 width=N) (actual rows=0.00 loops=1) +(1 row) + +SELECT explain_mask_costs($$ +SELECT * FROM generate_subscripts('{10,20,30}'::int[], 1, NULL) g(s);$$, +true, true, false, true); + explain_mask_costs +----------------------------------------------------------------------------------------------- + Function Scan on generate_subscripts g (cost=N..N rows=1 width=N) (actual rows=0.00 loops=1) +(1 row) + +-- An ArrayExpr is estimated by way of estimate_array_length() +SELECT explain_mask_costs($$ +SELECT * FROM generate_subscripts(ARRAY[1, 2, (SELECT 3)], 1) g(s);$$, +true, true, false, true); + explain_mask_costs +----------------------------------------------------------------------------------------------- + Function Scan on generate_subscripts g (cost=N..N rows=3 width=N) (actual rows=3.00 loops=1) + InitPlan expr_1 + -> Result (cost=N..N rows=1 width=N) (actual rows=1.00 loops=1) +(3 rows) + +-- Ensure we get the default row estimate when the dimension number isn't a +-- constant, since then we don't even know which dimension is wanted +SELECT explain_mask_costs($$ +SELECT * FROM generate_subscripts(ARRAY[1, 2, (SELECT 3)], (SELECT 1)) g(s);$$, +false, true, false, true); + explain_mask_costs +----------------------------------------------------------------------- + Function Scan on generate_subscripts g (cost=N..N rows=1000 width=N) + InitPlan expr_1 + -> Result (cost=N..N rows=1 width=N) + InitPlan expr_2 + -> Result (cost=N..N rows=1 width=N) +(5 rows) + +-- Ensure a Var array is estimated from the DECHIST statistics. Every array +-- below holds exactly 7 distinct elements, so the average distinct element +-- count does not depend on which rows ANALYZE happens to sample. +CREATE TEMP TABLE subscript_table_1 AS + SELECT array_agg(g) AS a FROM generate_series(1, 100) i, + LATERAL generate_series(1, 7) g GROUP BY i; +ANALYZE subscript_table_1; +-- Memoize is disabled here only to keep the plan shape stable; the node's +-- capacity and hit percentage are not masked by explain_mask_costs(). +SET enable_memoize = off; +SELECT explain_mask_costs($$ +SELECT * FROM subscript_table_1 t, LATERAL generate_subscripts(t.a, 1) g(s);$$, +true, true, false, true); + explain_mask_costs +------------------------------------------------------------------------------------------------------- + Nested Loop (cost=N..N rows=700 width=N) (actual rows=700.00 loops=1) + -> Seq Scan on subscript_table_1 t (cost=N..N rows=100 width=N) (actual rows=100.00 loops=1) + -> Function Scan on generate_subscripts g (cost=N..N rows=7 width=N) (actual rows=7.00 loops=100) +(3 rows) + +-- As above, but a dimension above the first falls back on prorows: the element +-- count in the statistics says nothing about the length of that dimension +SELECT explain_mask_costs($$ +SELECT * FROM subscript_table_1 t, LATERAL generate_subscripts(t.a, 2) g(s);$$, +false, true, false, true); + explain_mask_costs +----------------------------------------------------------------------------- + Nested Loop (cost=N..N rows=100000 width=N) + -> Seq Scan on subscript_table_1 t (cost=N..N rows=100 width=N) + -> Function Scan on generate_subscripts g (cost=N..N rows=1000 width=N) +(3 rows) + +RESET enable_memoize; -- -- Test ScalarArrayOpExpr row estimates for <> ALL for arrays with NULLs. We -- expect the planner to estimate 1 row will match in both of the following diff --git a/src/test/regress/sql/planner_est.sql b/src/test/regress/sql/planner_est.sql index 2b696a4e4e5..c4e7ba32cf3 100644 --- a/src/test/regress/sql/planner_est.sql +++ b/src/test/regress/sql/planner_est.sql @@ -131,6 +131,103 @@ SELECT explain_mask_costs($$ SELECT * FROM generate_series(25.0, 2.0, 0.0) g(s);$$, false, true, false, true); +-- +-- Test the SupportRequestRows support function for generate_subscripts() +-- + +-- A constant array gives an exact estimate for the requested dimension +SELECT explain_mask_costs($$ +SELECT * FROM generate_subscripts('{10,20,30,40,50}'::int[], 1) g(s);$$, +true, true, false, true); + +-- As above but for the 3-argument form; "reverse" cannot change the row count +SELECT explain_mask_costs($$ +SELECT * FROM generate_subscripts('{10,20,30,40,50}'::int[], 1, true) g(s);$$, +true, true, false, true); + +-- Ensure a non-zero lower bound does not affect the estimate +SELECT explain_mask_costs($$ +SELECT * FROM generate_subscripts('[5:9]={10,20,30,40,50}'::int[], 1) g(s);$$, +true, true, false, true); + +-- Ensure each dimension of a multi-dimensional array is estimated separately +SELECT explain_mask_costs($$ +SELECT * FROM generate_subscripts('{{1,2,3},{4,5,6}}'::int[], 1) g(s);$$, +true, true, false, true); + +SELECT explain_mask_costs($$ +SELECT * FROM generate_subscripts('{{1,2,3},{4,5,6}}'::int[], 2) g(s);$$, +true, true, false, true); + +-- Ensure a dimension above the second is handled too. Each dimension of this +-- array has a different length, so a mix-up could not go unnoticed. +SELECT explain_mask_costs($$ +SELECT * FROM generate_subscripts('{{{1,2,3,4},{5,6,7,8},{9,10,11,12}},{{13,14,15,16},{17,18,19,20},{21,22,23,24}}}'::int[], 3) g(s);$$, +true, true, false, true); + +-- Ensure cases which return no rows estimate 1 row after clamping. Try an +-- out-of-range dimension, a dimension below the first, and an empty array. +SELECT explain_mask_costs($$ +SELECT * FROM generate_subscripts('{{1,2,3},{4,5,6}}'::int[], 3) g(s);$$, +true, true, false, true); + +SELECT explain_mask_costs($$ +SELECT * FROM generate_subscripts('{10,20,30}'::int[], 0) g(s);$$, +true, true, false, true); + +SELECT explain_mask_costs($$ +SELECT * FROM generate_subscripts('{}'::int[], 1) g(s);$$, +true, true, false, true); + +-- Ensure a constant NULL in any argument position estimates no rows, since +-- generate_subscripts() is strict +SELECT explain_mask_costs($$ +SELECT * FROM generate_subscripts(NULL::int[], 1) g(s);$$, +true, true, false, true); + +SELECT explain_mask_costs($$ +SELECT * FROM generate_subscripts('{10,20,30}'::int[], NULL) g(s);$$, +true, true, false, true); + +SELECT explain_mask_costs($$ +SELECT * FROM generate_subscripts('{10,20,30}'::int[], 1, NULL) g(s);$$, +true, true, false, true); + +-- An ArrayExpr is estimated by way of estimate_array_length() +SELECT explain_mask_costs($$ +SELECT * FROM generate_subscripts(ARRAY[1, 2, (SELECT 3)], 1) g(s);$$, +true, true, false, true); + +-- Ensure we get the default row estimate when the dimension number isn't a +-- constant, since then we don't even know which dimension is wanted +SELECT explain_mask_costs($$ +SELECT * FROM generate_subscripts(ARRAY[1, 2, (SELECT 3)], (SELECT 1)) g(s);$$, +false, true, false, true); + +-- Ensure a Var array is estimated from the DECHIST statistics. Every array +-- below holds exactly 7 distinct elements, so the average distinct element +-- count does not depend on which rows ANALYZE happens to sample. +CREATE TEMP TABLE subscript_table_1 AS + SELECT array_agg(g) AS a FROM generate_series(1, 100) i, + LATERAL generate_series(1, 7) g GROUP BY i; +ANALYZE subscript_table_1; + +-- Memoize is disabled here only to keep the plan shape stable; the node's +-- capacity and hit percentage are not masked by explain_mask_costs(). +SET enable_memoize = off; + +SELECT explain_mask_costs($$ +SELECT * FROM subscript_table_1 t, LATERAL generate_subscripts(t.a, 1) g(s);$$, +true, true, false, true); + +-- As above, but a dimension above the first falls back on prorows: the element +-- count in the statistics says nothing about the length of that dimension +SELECT explain_mask_costs($$ +SELECT * FROM subscript_table_1 t, LATERAL generate_subscripts(t.a, 2) g(s);$$, +false, true, false, true); + +RESET enable_memoize; + -- -- Test ScalarArrayOpExpr row estimates for <> ALL for arrays with NULLs. We -- expect the planner to estimate 1 row will match in both of the following -- 2.37.1 (Apple Git-137.1)
v3-0002-Lower-generate_subscripts-s-prorows-estimate-to-1.patch (application/octet-stream, 3.5K) download From 278e7a58cc8c664125938c4913a584c5d7380458 Mon Sep 17 00:00:00 2001 From: Zhong ShiHao <zhong950419@gmail.com> Date: Mon, 7 Sep 2026 21:18:43 -0400 Subject: [PATCH v3 2/2] Lower generate_subscripts()'s prorows estimate to 10 With a support function in place, prorows is consulted only when that function declines: when the dimension number isn't known at plan time, or when a dimension above the first is requested for a non-constant array. The old value of 1000 has no particular justification. Use 10, which is what estimate_array_length() assumes for an array it knows nothing about, and hence what the dimension-one path already produces in that situation. --- src/include/catalog/pg_proc.dat | 4 ++-- src/test/regress/expected/planner_est.out | 14 +++++++------- 2 files changed, 9 insertions(+), 9 deletions(-) diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat index c1fa1984bd9..0c1debb26b3 100644 --- a/src/include/catalog/pg_proc.dat +++ b/src/include/catalog/pg_proc.dat @@ -1711,12 +1711,12 @@ proargtypes => 'anycompatiblearray anycompatible', prosrc => 'array_positions' }, { oid => '1191', descr => 'array subscripts generator', - proname => 'generate_subscripts', prorows => '1000', + proname => 'generate_subscripts', prorows => '10', prosupport => 'generate_subscripts_support', proretset => 't', prorettype => 'int4', proargtypes => 'anyarray int4 bool', prosrc => 'generate_subscripts' }, { oid => '1192', descr => 'array subscripts generator', - proname => 'generate_subscripts', prorows => '1000', + proname => 'generate_subscripts', prorows => '10', prosupport => 'generate_subscripts_support', proretset => 't', prorettype => 'int4', proargtypes => 'anyarray int4', prosrc => 'generate_subscripts_nodir' }, diff --git a/src/test/regress/expected/planner_est.out b/src/test/regress/expected/planner_est.out index 44eb5eeca32..64da9e2ca00 100644 --- a/src/test/regress/expected/planner_est.out +++ b/src/test/regress/expected/planner_est.out @@ -308,9 +308,9 @@ true, true, false, true); SELECT explain_mask_costs($$ SELECT * FROM generate_subscripts(ARRAY[1, 2, (SELECT 3)], (SELECT 1)) g(s);$$, false, true, false, true); - explain_mask_costs ------------------------------------------------------------------------ - Function Scan on generate_subscripts g (cost=N..N rows=1000 width=N) + explain_mask_costs +--------------------------------------------------------------------- + Function Scan on generate_subscripts g (cost=N..N rows=10 width=N) InitPlan expr_1 -> Result (cost=N..N rows=1 width=N) InitPlan expr_2 @@ -342,11 +342,11 @@ true, true, false, true); SELECT explain_mask_costs($$ SELECT * FROM subscript_table_1 t, LATERAL generate_subscripts(t.a, 2) g(s);$$, false, true, false, true); - explain_mask_costs ------------------------------------------------------------------------------ - Nested Loop (cost=N..N rows=100000 width=N) + explain_mask_costs +--------------------------------------------------------------------------- + Nested Loop (cost=N..N rows=1000 width=N) -> Seq Scan on subscript_table_1 t (cost=N..N rows=100 width=N) - -> Function Scan on generate_subscripts g (cost=N..N rows=1000 width=N) + -> Function Scan on generate_subscripts g (cost=N..N rows=10 width=N) (3 rows) RESET enable_memoize; -- 2.37.1 (Apple Git-137.1)
^ permalink raw reply [nested|flat] 8+ messages in thread

* Re: [PATCH] Planner support function for generate_subscripts()
  2026-08-31 02:04 [PATCH] Planner support function for generate_subscripts() shihao zhong <zhong950419@gmail.com>
  2026-09-07 12:27 ` Re: [PATCH] Planner support function for generate_subscripts() Priyanka S <developerette@gmail.com>
  2026-09-08 01:21   ` Re: [PATCH] Planner support function for generate_subscripts() shihao zhong <zhong950419@gmail.com>
  2026-09-08 10:07     ` Re: [PATCH] Planner support function for generate_subscripts() Andrei Lepikhov <lepihov@gmail.com>
  2026-09-09 01:20       ` Re: [PATCH] Planner support function for generate_subscripts() shihao zhong <zhong950419@gmail.com>
@ 2026-09-14 01:54         ` shihao zhong <zhong950419@gmail.com>
  2026-09-27 09:04           ` Re: [PATCH] Planner support function for generate_subscripts() Andrew Krylosov <krylosov.andrew@gmail.com>
  0 siblings, 1 reply; 8+ messages in thread

From: shihao zhong @ 2026-09-14 01:54 UTC (permalink / raw)
  To: Andrei Lepikhov <lepihov@gmail.com>; +Cc: Priyanka S <developerette@gmail.com>; pgsql-hackers <pgsql-hackers@lists.postgresql.org>

Hi,

v3 broke the CompilerWarnings CI task.  v4 attached fixes that; nothing
else has changed.

Thanks,
Shihao

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

v4-0001-Add-a-planner-support-function-for-generate_subsc.patch (application/octet-stream, 21.2K) download From d6f317dac5778815475102ae08e6ba95c84ead19 Mon Sep 17 00:00:00 2001 From: Zhong ShiHao <zhong950419@gmail.com> Date: Sun, 13 Sep 2026 21:50:02 -0400 Subject: [PATCH v4 1/2] Add a planner support function for generate_subscripts() Previously the planner had no way to estimate how many rows generate_subscripts() returns, so it always used the function's prorows value of 1000. Its close sibling unnest() has computed a proper estimate from its array argument since planner support functions were introduced in v12. Add generate_subscripts_support(), which handles SupportRequestRows as follows: * If any argument is a constant NULL, report zero rows: the function is strict. * If both the array and the dimension number are plan-time constants, report the length of the requested dimension exactly. * If only the dimension number is known and it is 1, use estimate_array_length(), which can consult the array column's statistics. For one-dimensional arrays, by far the common case, the total element count it reports equals the length of dimension 1. * Otherwise report nothing, and the planner falls back on prorows as before. --- src/backend/utils/adt/arrayfuncs.c | 126 ++++++++++++++++ src/include/catalog/pg_proc.dat | 9 +- src/test/regress/expected/planner_est.out | 167 ++++++++++++++++++++++ src/test/regress/sql/planner_est.sql | 97 +++++++++++++ 4 files changed, 397 insertions(+), 2 deletions(-) diff --git a/src/backend/utils/adt/arrayfuncs.c b/src/backend/utils/adt/arrayfuncs.c index ef66182b047..2219cf994a2 100644 --- a/src/backend/utils/adt/arrayfuncs.c +++ b/src/backend/utils/adt/arrayfuncs.c @@ -6000,6 +6000,132 @@ generate_subscripts_nodir(PG_FUNCTION_ARGS) return generate_subscripts(fcinfo); } +/* + * Planner support function for generate_subscripts(anyarray, int [, bool]) + * + * Unlike unnest(), generate_subscripts() returns one row per subscript of + * the *requested dimension*, not one row per array element. Those are the + * same thing for a one-dimensional array, but in general we need the length + * of dimension "dim", which we can only determine when the array itself is + * available as a constant. + */ +Datum +generate_subscripts_support(PG_FUNCTION_ARGS) +{ + Node *rawreq = (Node *) PG_GETARG_POINTER(0); + Node *ret = NULL; + + if (IsA(rawreq, SupportRequestRows)) + { + /* Try to estimate the number of rows returned */ + SupportRequestRows *req = (SupportRequestRows *) rawreq; + + /* + * Be paranoid: only proceed when we are attached to one of the + * generate_subscripts() entries, the call site is a FuncExpr carrying + * enough arguments, and root is available, since + * estimate_expression_value() requires it. Otherwise decline, and + * prorows applies. + */ + if ((req->funcid == F_GENERATE_SUBSCRIPTS_ANYARRAY_INT4 || + req->funcid == F_GENERATE_SUBSCRIPTS_ANYARRAY_INT4_BOOL) && + req->root != NULL && + is_funcclause(req->node) && + list_length(((FuncExpr *) req->node)->args) >= 2) + { + List *args = ((FuncExpr *) req->node)->args; + Node *arg1, + *arg2, + *arg3 = NULL; + + /* The parser enforces the signature for these two functions */ + Assert(list_length(args) == 2 || list_length(args) == 3); + Assert(exprType(lsecond(args)) == INT4OID); + + /* We can use estimated argument values here */ + arg1 = estimate_expression_value(req->root, linitial(args)); + arg2 = estimate_expression_value(req->root, lsecond(args)); + + /* The third argument, "reverse", is optional */ + if (list_length(args) >= 3) + arg3 = estimate_expression_value(req->root, lthird(args)); + + /* + * The function is strict, so a constant NULL in any argument + * position means that no rows will be returned. Otherwise we + * need to know the dimension number to say anything at all. + */ + if ((IsA(arg1, Const) && + ((Const *) arg1)->constisnull) || + (IsA(arg2, Const) && + ((Const *) arg2)->constisnull) || + (arg3 != NULL && IsA(arg3, Const) && + ((Const *) arg3)->constisnull)) + { + req->rows = 0; + ret = (Node *) req; + } + else if (IsA(arg2, Const)) + { + int32 reqdim = DatumGetInt32(((Const *) arg2)->constvalue); + + if (reqdim <= 0) + { + /* generate_subscripts() returns no rows for such dims */ + req->rows = 0; + ret = (Node *) req; + } + else if (IsA(arg1, Const)) + { + ArrayType *arr; + + /* + * We know the array, so we can report the length of the + * requested dimension exactly. Note that the dimension's + * lower bound does not enter into it. A dimension the + * array doesn't have yields no rows, which also covers + * empty arrays, whose ndim is zero. + * + * Unlike estimate_array_length(), we don't bother to look + * through array coercions here; if one is in the way we + * simply fall through to the cases below. + */ + arr = DatumGetArrayTypeP(((Const *) arg1)->constvalue); + + if (reqdim > ARR_NDIM(arr)) + req->rows = 0; /* no such dimension */ + else + req->rows = ARR_DIMS(arr)[reqdim - 1]; + ret = (Node *) req; + } + else if (reqdim == 1) + { + /* + * All we have is estimate_array_length(), which counts + * every element rather than the length of one dimension. + * Those agree for 1-D arrays, and since dimension 1 was + * requested it's fair to suppose that's what we have. If + * not we'll overestimate, but no per-dimension statistics + * exist that could do better. + */ + req->rows = estimate_array_length(req->root, arg1); + ret = (Node *) req; + } + + /* + * Otherwise a dimension above the first was requested for an + * array that isn't a constant. We know nothing about the + * array's dimensionality, let alone the length of the + * requested dimension, so leave ret as NULL to make the + * caller fall back on prorows. + */ + } + } + } + + PG_RETURN_POINTER(ret); +} + /* * array_fill_with_lower_bounds * Create and fill array with defined lower bounds. diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat index 74d386b868b..baacbec571b 100644 --- a/src/include/catalog/pg_proc.dat +++ b/src/include/catalog/pg_proc.dat @@ -1711,13 +1711,18 @@ proargtypes => 'anycompatiblearray anycompatible', prosrc => 'array_positions' }, { oid => '1191', descr => 'array subscripts generator', - proname => 'generate_subscripts', prorows => '1000', proretset => 't', + proname => 'generate_subscripts', prorows => '1000', + prosupport => 'generate_subscripts_support', proretset => 't', prorettype => 'int4', proargtypes => 'anyarray int4 bool', prosrc => 'generate_subscripts' }, { oid => '1192', descr => 'array subscripts generator', - proname => 'generate_subscripts', prorows => '1000', proretset => 't', + proname => 'generate_subscripts', prorows => '1000', + prosupport => 'generate_subscripts_support', proretset => 't', prorettype => 'int4', proargtypes => 'anyarray int4', prosrc => 'generate_subscripts_nodir' }, +{ oid => '9419', descr => 'planner support for generate_subscripts', + proname => 'generate_subscripts_support', prorettype => 'internal', + proargtypes => 'internal', prosrc => 'generate_subscripts_support' }, { oid => '1193', descr => 'array constructor with value', proname => 'array_fill', proisstrict => 'f', prorettype => 'anyarray', proargtypes => 'anyelement _int4', prosrc => 'array_fill' }, diff --git a/src/test/regress/expected/planner_est.out b/src/test/regress/expected/planner_est.out index 236cb274a78..44eb5eeca32 100644 --- a/src/test/regress/expected/planner_est.out +++ b/src/test/regress/expected/planner_est.out @@ -183,6 +183,173 @@ false, true, false, true); Function Scan on generate_series g (cost=N..N rows=1000 width=N) (1 row) +-- +-- Test the SupportRequestRows support function for generate_subscripts() +-- +-- A constant array gives an exact estimate for the requested dimension +SELECT explain_mask_costs($$ +SELECT * FROM generate_subscripts('{10,20,30,40,50}'::int[], 1) g(s);$$, +true, true, false, true); + explain_mask_costs +----------------------------------------------------------------------------------------------- + Function Scan on generate_subscripts g (cost=N..N rows=5 width=N) (actual rows=5.00 loops=1) +(1 row) + +-- As above but for the 3-argument form; "reverse" cannot change the row count +SELECT explain_mask_costs($$ +SELECT * FROM generate_subscripts('{10,20,30,40,50}'::int[], 1, true) g(s);$$, +true, true, false, true); + explain_mask_costs +----------------------------------------------------------------------------------------------- + Function Scan on generate_subscripts g (cost=N..N rows=5 width=N) (actual rows=5.00 loops=1) +(1 row) + +-- Ensure a non-zero lower bound does not affect the estimate +SELECT explain_mask_costs($$ +SELECT * FROM generate_subscripts('[5:9]={10,20,30,40,50}'::int[], 1) g(s);$$, +true, true, false, true); + explain_mask_costs +----------------------------------------------------------------------------------------------- + Function Scan on generate_subscripts g (cost=N..N rows=5 width=N) (actual rows=5.00 loops=1) +(1 row) + +-- Ensure each dimension of a multi-dimensional array is estimated separately +SELECT explain_mask_costs($$ +SELECT * FROM generate_subscripts('{{1,2,3},{4,5,6}}'::int[], 1) g(s);$$, +true, true, false, true); + explain_mask_costs +----------------------------------------------------------------------------------------------- + Function Scan on generate_subscripts g (cost=N..N rows=2 width=N) (actual rows=2.00 loops=1) +(1 row) + +SELECT explain_mask_costs($$ +SELECT * FROM generate_subscripts('{{1,2,3},{4,5,6}}'::int[], 2) g(s);$$, +true, true, false, true); + explain_mask_costs +----------------------------------------------------------------------------------------------- + Function Scan on generate_subscripts g (cost=N..N rows=3 width=N) (actual rows=3.00 loops=1) +(1 row) + +-- Ensure a dimension above the second is handled too. Each dimension of this +-- array has a different length, so a mix-up could not go unnoticed. +SELECT explain_mask_costs($$ +SELECT * FROM generate_subscripts('{{{1,2,3,4},{5,6,7,8},{9,10,11,12}},{{13,14,15,16},{17,18,19,20},{21,22,23,24}}}'::int[], 3) g(s);$$, +true, true, false, true); + explain_mask_costs +----------------------------------------------------------------------------------------------- + Function Scan on generate_subscripts g (cost=N..N rows=4 width=N) (actual rows=4.00 loops=1) +(1 row) + +-- Ensure cases which return no rows estimate 1 row after clamping. Try an +-- out-of-range dimension, a dimension below the first, and an empty array. +SELECT explain_mask_costs($$ +SELECT * FROM generate_subscripts('{{1,2,3},{4,5,6}}'::int[], 3) g(s);$$, +true, true, false, true); + explain_mask_costs +----------------------------------------------------------------------------------------------- + Function Scan on generate_subscripts g (cost=N..N rows=1 width=N) (actual rows=0.00 loops=1) +(1 row) + +SELECT explain_mask_costs($$ +SELECT * FROM generate_subscripts('{10,20,30}'::int[], 0) g(s);$$, +true, true, false, true); + explain_mask_costs +----------------------------------------------------------------------------------------------- + Function Scan on generate_subscripts g (cost=N..N rows=1 width=N) (actual rows=0.00 loops=1) +(1 row) + +SELECT explain_mask_costs($$ +SELECT * FROM generate_subscripts('{}'::int[], 1) g(s);$$, +true, true, false, true); + explain_mask_costs +----------------------------------------------------------------------------------------------- + Function Scan on generate_subscripts g (cost=N..N rows=1 width=N) (actual rows=0.00 loops=1) +(1 row) + +-- Ensure a constant NULL in any argument position estimates no rows, since +-- generate_subscripts() is strict +SELECT explain_mask_costs($$ +SELECT * FROM generate_subscripts(NULL::int[], 1) g(s);$$, +true, true, false, true); + explain_mask_costs +----------------------------------------------------------------------------------------------- + Function Scan on generate_subscripts g (cost=N..N rows=1 width=N) (actual rows=0.00 loops=1) +(1 row) + +SELECT explain_mask_costs($$ +SELECT * FROM generate_subscripts('{10,20,30}'::int[], NULL) g(s);$$, +true, true, false, true); + explain_mask_costs +----------------------------------------------------------------------------------------------- + Function Scan on generate_subscripts g (cost=N..N rows=1 width=N) (actual rows=0.00 loops=1) +(1 row) + +SELECT explain_mask_costs($$ +SELECT * FROM generate_subscripts('{10,20,30}'::int[], 1, NULL) g(s);$$, +true, true, false, true); + explain_mask_costs +----------------------------------------------------------------------------------------------- + Function Scan on generate_subscripts g (cost=N..N rows=1 width=N) (actual rows=0.00 loops=1) +(1 row) + +-- An ArrayExpr is estimated by way of estimate_array_length() +SELECT explain_mask_costs($$ +SELECT * FROM generate_subscripts(ARRAY[1, 2, (SELECT 3)], 1) g(s);$$, +true, true, false, true); + explain_mask_costs +----------------------------------------------------------------------------------------------- + Function Scan on generate_subscripts g (cost=N..N rows=3 width=N) (actual rows=3.00 loops=1) + InitPlan expr_1 + -> Result (cost=N..N rows=1 width=N) (actual rows=1.00 loops=1) +(3 rows) + +-- Ensure we get the default row estimate when the dimension number isn't a +-- constant, since then we don't even know which dimension is wanted +SELECT explain_mask_costs($$ +SELECT * FROM generate_subscripts(ARRAY[1, 2, (SELECT 3)], (SELECT 1)) g(s);$$, +false, true, false, true); + explain_mask_costs +----------------------------------------------------------------------- + Function Scan on generate_subscripts g (cost=N..N rows=1000 width=N) + InitPlan expr_1 + -> Result (cost=N..N rows=1 width=N) + InitPlan expr_2 + -> Result (cost=N..N rows=1 width=N) +(5 rows) + +-- Ensure a Var array is estimated from the DECHIST statistics. Every array +-- below holds exactly 7 distinct elements, so the average distinct element +-- count does not depend on which rows ANALYZE happens to sample. +CREATE TEMP TABLE subscript_table_1 AS + SELECT array_agg(g) AS a FROM generate_series(1, 100) i, + LATERAL generate_series(1, 7) g GROUP BY i; +ANALYZE subscript_table_1; +-- Memoize is disabled here only to keep the plan shape stable; the node's +-- capacity and hit percentage are not masked by explain_mask_costs(). +SET enable_memoize = off; +SELECT explain_mask_costs($$ +SELECT * FROM subscript_table_1 t, LATERAL generate_subscripts(t.a, 1) g(s);$$, +true, true, false, true); + explain_mask_costs +------------------------------------------------------------------------------------------------------- + Nested Loop (cost=N..N rows=700 width=N) (actual rows=700.00 loops=1) + -> Seq Scan on subscript_table_1 t (cost=N..N rows=100 width=N) (actual rows=100.00 loops=1) + -> Function Scan on generate_subscripts g (cost=N..N rows=7 width=N) (actual rows=7.00 loops=100) +(3 rows) + +-- As above, but a dimension above the first falls back on prorows: the element +-- count in the statistics says nothing about the length of that dimension +SELECT explain_mask_costs($$ +SELECT * FROM subscript_table_1 t, LATERAL generate_subscripts(t.a, 2) g(s);$$, +false, true, false, true); + explain_mask_costs +----------------------------------------------------------------------------- + Nested Loop (cost=N..N rows=100000 width=N) + -> Seq Scan on subscript_table_1 t (cost=N..N rows=100 width=N) + -> Function Scan on generate_subscripts g (cost=N..N rows=1000 width=N) +(3 rows) + +RESET enable_memoize; -- -- Test ScalarArrayOpExpr row estimates for <> ALL for arrays with NULLs. We -- expect the planner to estimate 1 row will match in both of the following diff --git a/src/test/regress/sql/planner_est.sql b/src/test/regress/sql/planner_est.sql index 2b696a4e4e5..c4e7ba32cf3 100644 --- a/src/test/regress/sql/planner_est.sql +++ b/src/test/regress/sql/planner_est.sql @@ -131,6 +131,103 @@ SELECT explain_mask_costs($$ SELECT * FROM generate_series(25.0, 2.0, 0.0) g(s);$$, false, true, false, true); +-- +-- Test the SupportRequestRows support function for generate_subscripts() +-- + +-- A constant array gives an exact estimate for the requested dimension +SELECT explain_mask_costs($$ +SELECT * FROM generate_subscripts('{10,20,30,40,50}'::int[], 1) g(s);$$, +true, true, false, true); + +-- As above but for the 3-argument form; "reverse" cannot change the row count +SELECT explain_mask_costs($$ +SELECT * FROM generate_subscripts('{10,20,30,40,50}'::int[], 1, true) g(s);$$, +true, true, false, true); + +-- Ensure a non-zero lower bound does not affect the estimate +SELECT explain_mask_costs($$ +SELECT * FROM generate_subscripts('[5:9]={10,20,30,40,50}'::int[], 1) g(s);$$, +true, true, false, true); + +-- Ensure each dimension of a multi-dimensional array is estimated separately +SELECT explain_mask_costs($$ +SELECT * FROM generate_subscripts('{{1,2,3},{4,5,6}}'::int[], 1) g(s);$$, +true, true, false, true); + +SELECT explain_mask_costs($$ +SELECT * FROM generate_subscripts('{{1,2,3},{4,5,6}}'::int[], 2) g(s);$$, +true, true, false, true); + +-- Ensure a dimension above the second is handled too. Each dimension of this +-- array has a different length, so a mix-up could not go unnoticed. +SELECT explain_mask_costs($$ +SELECT * FROM generate_subscripts('{{{1,2,3,4},{5,6,7,8},{9,10,11,12}},{{13,14,15,16},{17,18,19,20},{21,22,23,24}}}'::int[], 3) g(s);$$, +true, true, false, true); + +-- Ensure cases which return no rows estimate 1 row after clamping. Try an +-- out-of-range dimension, a dimension below the first, and an empty array. +SELECT explain_mask_costs($$ +SELECT * FROM generate_subscripts('{{1,2,3},{4,5,6}}'::int[], 3) g(s);$$, +true, true, false, true); + +SELECT explain_mask_costs($$ +SELECT * FROM generate_subscripts('{10,20,30}'::int[], 0) g(s);$$, +true, true, false, true); + +SELECT explain_mask_costs($$ +SELECT * FROM generate_subscripts('{}'::int[], 1) g(s);$$, +true, true, false, true); + +-- Ensure a constant NULL in any argument position estimates no rows, since +-- generate_subscripts() is strict +SELECT explain_mask_costs($$ +SELECT * FROM generate_subscripts(NULL::int[], 1) g(s);$$, +true, true, false, true); + +SELECT explain_mask_costs($$ +SELECT * FROM generate_subscripts('{10,20,30}'::int[], NULL) g(s);$$, +true, true, false, true); + +SELECT explain_mask_costs($$ +SELECT * FROM generate_subscripts('{10,20,30}'::int[], 1, NULL) g(s);$$, +true, true, false, true); + +-- An ArrayExpr is estimated by way of estimate_array_length() +SELECT explain_mask_costs($$ +SELECT * FROM generate_subscripts(ARRAY[1, 2, (SELECT 3)], 1) g(s);$$, +true, true, false, true); + +-- Ensure we get the default row estimate when the dimension number isn't a +-- constant, since then we don't even know which dimension is wanted +SELECT explain_mask_costs($$ +SELECT * FROM generate_subscripts(ARRAY[1, 2, (SELECT 3)], (SELECT 1)) g(s);$$, +false, true, false, true); + +-- Ensure a Var array is estimated from the DECHIST statistics. Every array +-- below holds exactly 7 distinct elements, so the average distinct element +-- count does not depend on which rows ANALYZE happens to sample. +CREATE TEMP TABLE subscript_table_1 AS + SELECT array_agg(g) AS a FROM generate_series(1, 100) i, + LATERAL generate_series(1, 7) g GROUP BY i; +ANALYZE subscript_table_1; + +-- Memoize is disabled here only to keep the plan shape stable; the node's +-- capacity and hit percentage are not masked by explain_mask_costs(). +SET enable_memoize = off; + +SELECT explain_mask_costs($$ +SELECT * FROM subscript_table_1 t, LATERAL generate_subscripts(t.a, 1) g(s);$$, +true, true, false, true); + +-- As above, but a dimension above the first falls back on prorows: the element +-- count in the statistics says nothing about the length of that dimension +SELECT explain_mask_costs($$ +SELECT * FROM subscript_table_1 t, LATERAL generate_subscripts(t.a, 2) g(s);$$, +false, true, false, true); + +RESET enable_memoize; + -- -- Test ScalarArrayOpExpr row estimates for <> ALL for arrays with NULLs. We -- expect the planner to estimate 1 row will match in both of the following -- 2.37.1 (Apple Git-137.1)
v4-0002-Lower-generate_subscripts-s-prorows-estimate-to-1.patch (application/octet-stream, 3.5K) download From d3c957eb73ee6a3e774806234c951af9eef5c6fb Mon Sep 17 00:00:00 2001 From: Zhong ShiHao <zhong950419@gmail.com> Date: Sun, 13 Sep 2026 21:50:02 -0400 Subject: [PATCH v4 2/2] Lower generate_subscripts()'s prorows estimate to 10 With a support function in place, prorows is consulted only when that function declines: when the dimension number isn't known at plan time, or when a dimension above the first is requested for a non-constant array. The old value of 1000 has no particular justification. Use 10, which is what estimate_array_length() assumes for an array it knows nothing about, and hence what the dimension-one path already produces in that situation. --- src/include/catalog/pg_proc.dat | 4 ++-- src/test/regress/expected/planner_est.out | 14 +++++++------- 2 files changed, 9 insertions(+), 9 deletions(-) diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat index baacbec571b..6418807bffb 100644 --- a/src/include/catalog/pg_proc.dat +++ b/src/include/catalog/pg_proc.dat @@ -1711,12 +1711,12 @@ proargtypes => 'anycompatiblearray anycompatible', prosrc => 'array_positions' }, { oid => '1191', descr => 'array subscripts generator', - proname => 'generate_subscripts', prorows => '1000', + proname => 'generate_subscripts', prorows => '10', prosupport => 'generate_subscripts_support', proretset => 't', prorettype => 'int4', proargtypes => 'anyarray int4 bool', prosrc => 'generate_subscripts' }, { oid => '1192', descr => 'array subscripts generator', - proname => 'generate_subscripts', prorows => '1000', + proname => 'generate_subscripts', prorows => '10', prosupport => 'generate_subscripts_support', proretset => 't', prorettype => 'int4', proargtypes => 'anyarray int4', prosrc => 'generate_subscripts_nodir' }, diff --git a/src/test/regress/expected/planner_est.out b/src/test/regress/expected/planner_est.out index 44eb5eeca32..64da9e2ca00 100644 --- a/src/test/regress/expected/planner_est.out +++ b/src/test/regress/expected/planner_est.out @@ -308,9 +308,9 @@ true, true, false, true); SELECT explain_mask_costs($$ SELECT * FROM generate_subscripts(ARRAY[1, 2, (SELECT 3)], (SELECT 1)) g(s);$$, false, true, false, true); - explain_mask_costs ------------------------------------------------------------------------ - Function Scan on generate_subscripts g (cost=N..N rows=1000 width=N) + explain_mask_costs +--------------------------------------------------------------------- + Function Scan on generate_subscripts g (cost=N..N rows=10 width=N) InitPlan expr_1 -> Result (cost=N..N rows=1 width=N) InitPlan expr_2 @@ -342,11 +342,11 @@ true, true, false, true); SELECT explain_mask_costs($$ SELECT * FROM subscript_table_1 t, LATERAL generate_subscripts(t.a, 2) g(s);$$, false, true, false, true); - explain_mask_costs ------------------------------------------------------------------------------ - Nested Loop (cost=N..N rows=100000 width=N) + explain_mask_costs +--------------------------------------------------------------------------- + Nested Loop (cost=N..N rows=1000 width=N) -> Seq Scan on subscript_table_1 t (cost=N..N rows=100 width=N) - -> Function Scan on generate_subscripts g (cost=N..N rows=1000 width=N) + -> Function Scan on generate_subscripts g (cost=N..N rows=10 width=N) (3 rows) RESET enable_memoize; -- 2.37.1 (Apple Git-137.1)
^ permalink raw reply [nested|flat] 8+ messages in thread

* Re: [PATCH] Planner support function for generate_subscripts()
  2026-08-31 02:04 [PATCH] Planner support function for generate_subscripts() shihao zhong <zhong950419@gmail.com>
  2026-09-07 12:27 ` Re: [PATCH] Planner support function for generate_subscripts() Priyanka S <developerette@gmail.com>
  2026-09-08 01:21   ` Re: [PATCH] Planner support function for generate_subscripts() shihao zhong <zhong950419@gmail.com>
  2026-09-08 10:07     ` Re: [PATCH] Planner support function for generate_subscripts() Andrei Lepikhov <lepihov@gmail.com>
  2026-09-09 01:20       ` Re: [PATCH] Planner support function for generate_subscripts() shihao zhong <zhong950419@gmail.com>
  2026-09-14 01:54         ` Re: [PATCH] Planner support function for generate_subscripts() shihao zhong <zhong950419@gmail.com>
@ 2026-09-27 09:04           ` Andrew Krylosov <krylosov.andrew@gmail.com>
  2026-09-27 15:54             ` Re: [PATCH] Planner support function for generate_subscripts() shihao zhong <zhong950419@gmail.com>
  0 siblings, 1 reply; 8+ messages in thread

From: Andrew Krylosov @ 2026-09-27 09:04 UTC (permalink / raw)
  To: shihao zhong <zhong950419@gmail.com>; +Cc: Andrei Lepikhov <lepihov@gmail.com>; Priyanka S <developerette@gmail.com>; pgsql-hackers <pgsql-hackers@lists.postgresql.org>

On Sun, Sep 13, 2026 at 09:54:37PM -0400, shihao zhong wrote:
> v3 broke the CompilerWarnings CI task.  v4 attached fixes that; nothing
> else has changed.

Hi,

I applied v4 on top of 1a846a555a, built with cassert on macOS arm64,
and ran the regress, isolation and postgres_fdw suites. All passed.
planner_est also passed with 0001 alone.

I also checked int2[]::int4[] and text[]::varchar[] casts, and
domains over int[] with and without a CHECK constraint. These all
gave exact row estimates. For the non-inlinable SQL function, a
four-element argument gave an estimate of 4 with a custom plan and
10 with a generic plan.

Using the same default estimate as unnest() for an unknown array seems
reasonable to me. I think this is ready for a committer. One minor
comment:

+                     * All we have is estimate_array_length(), which counts
+                     * every element rather than the length of one dimension.
+                     * Those agree for 1-D arrays, and since dimension 1 was
+                     * requested it's fair to suppose that's what we have.  If
+                     * not we'll overestimate, but no per-dimension statistics
+                     * exist that could do better.

The statistics path uses the average number of distinct non-null
elements. A column of 2-by-20 arrays filled with 1 gave an estimate of 1
for dimension 1, whose actual length is 2. I'd mention that limitation
here, since the estimate can also be too low.

Best regards,
Andrew Krylosov






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

* Re: [PATCH] Planner support function for generate_subscripts()
  2026-08-31 02:04 [PATCH] Planner support function for generate_subscripts() shihao zhong <zhong950419@gmail.com>
  2026-09-07 12:27 ` Re: [PATCH] Planner support function for generate_subscripts() Priyanka S <developerette@gmail.com>
  2026-09-08 01:21   ` Re: [PATCH] Planner support function for generate_subscripts() shihao zhong <zhong950419@gmail.com>
  2026-09-08 10:07     ` Re: [PATCH] Planner support function for generate_subscripts() Andrei Lepikhov <lepihov@gmail.com>
  2026-09-09 01:20       ` Re: [PATCH] Planner support function for generate_subscripts() shihao zhong <zhong950419@gmail.com>
  2026-09-14 01:54         ` Re: [PATCH] Planner support function for generate_subscripts() shihao zhong <zhong950419@gmail.com>
  2026-09-27 09:04           ` Re: [PATCH] Planner support function for generate_subscripts() Andrew Krylosov <krylosov.andrew@gmail.com>
@ 2026-09-27 15:54             ` shihao zhong <zhong950419@gmail.com>
  0 siblings, 0 replies; 8+ messages in thread

From: shihao zhong @ 2026-09-27 15:54 UTC (permalink / raw)
  To: Andrew Krylosov <krylosov.andrew@gmail.com>; +Cc: Andrei Lepikhov <lepihov@gmail.com>; Priyanka S <developerette@gmail.com>; pgsql-hackers <pgsql-hackers@lists.postgresql.org>

Hi Andrew,

Thanks for testing and for the review. You're right. From statistics,
estimate_array_length() counts only distinct non-null elements, so the
estimate can also be too low.

v5 rewords that comment.

Thanks,
Shihao

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

v5-0002-Lower-generate_subscripts-s-prorows-estimate-to-1.patch (application/octet-stream, 3.6K) download From 772335f8750571b8c4adde1207506b7a7a9c33d8 Mon Sep 17 00:00:00 2001 From: Zhong ShiHao <zhong950419@gmail.com> Date: Sun, 13 Sep 2026 21:50:02 -0400 Subject: [PATCH v5 2/2] Lower generate_subscripts()'s prorows estimate to 10 With the support function in place, prorows is used only when the dimension number is unknown at plan time, or when a dimension above the first is asked for on a non-constant array. The old value of 1000 had no basis. Use 10, which is what estimate_array_length() assumes for an array it knows nothing about, so dimension 1 gets the same guess in that case. Discussion: https://postgr.es/m/CAGRkXqQ6BLCkEBBC2OC_bvEaUPTg+z+2-euiJKKvAxgA7o1EAA@mail.gmail.com --- src/include/catalog/pg_proc.dat | 4 ++-- src/test/regress/expected/planner_est.out | 14 +++++++------- 2 files changed, 9 insertions(+), 9 deletions(-) diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat index 9ed0ebb8a78..6c18dee22a3 100644 --- a/src/include/catalog/pg_proc.dat +++ b/src/include/catalog/pg_proc.dat @@ -1711,12 +1711,12 @@ proargtypes => 'anycompatiblearray anycompatible', prosrc => 'array_positions' }, { oid => '1191', descr => 'array subscripts generator', - proname => 'generate_subscripts', prorows => '1000', + proname => 'generate_subscripts', prorows => '10', prosupport => 'generate_subscripts_support', proretset => 't', prorettype => 'int4', proargtypes => 'anyarray int4 bool', prosrc => 'generate_subscripts' }, { oid => '1192', descr => 'array subscripts generator', - proname => 'generate_subscripts', prorows => '1000', + proname => 'generate_subscripts', prorows => '10', prosupport => 'generate_subscripts_support', proretset => 't', prorettype => 'int4', proargtypes => 'anyarray int4', prosrc => 'generate_subscripts_nodir' }, diff --git a/src/test/regress/expected/planner_est.out b/src/test/regress/expected/planner_est.out index 44eb5eeca32..64da9e2ca00 100644 --- a/src/test/regress/expected/planner_est.out +++ b/src/test/regress/expected/planner_est.out @@ -308,9 +308,9 @@ true, true, false, true); SELECT explain_mask_costs($$ SELECT * FROM generate_subscripts(ARRAY[1, 2, (SELECT 3)], (SELECT 1)) g(s);$$, false, true, false, true); - explain_mask_costs ------------------------------------------------------------------------ - Function Scan on generate_subscripts g (cost=N..N rows=1000 width=N) + explain_mask_costs +--------------------------------------------------------------------- + Function Scan on generate_subscripts g (cost=N..N rows=10 width=N) InitPlan expr_1 -> Result (cost=N..N rows=1 width=N) InitPlan expr_2 @@ -342,11 +342,11 @@ true, true, false, true); SELECT explain_mask_costs($$ SELECT * FROM subscript_table_1 t, LATERAL generate_subscripts(t.a, 2) g(s);$$, false, true, false, true); - explain_mask_costs ------------------------------------------------------------------------------ - Nested Loop (cost=N..N rows=100000 width=N) + explain_mask_costs +--------------------------------------------------------------------------- + Nested Loop (cost=N..N rows=1000 width=N) -> Seq Scan on subscript_table_1 t (cost=N..N rows=100 width=N) - -> Function Scan on generate_subscripts g (cost=N..N rows=1000 width=N) + -> Function Scan on generate_subscripts g (cost=N..N rows=10 width=N) (3 rows) RESET enable_memoize; -- 2.37.1 (Apple Git-137.1)
v5-0001-Add-a-planner-support-function-for-generate_subsc.patch (application/octet-stream, 20.9K) download From fbf7a21b3c4adf295a62414a03d81c8e2ba09981 Mon Sep 17 00:00:00 2001 From: Zhong ShiHao <zhong950419@gmail.com> Date: Sun, 13 Sep 2026 21:50:02 -0400 Subject: [PATCH v5 1/2] Add a planner support function for generate_subscripts() The planner had no row estimate for generate_subscripts() and always used its prorows value of 1000. unnest() has had a support function since v12. The new support function reports zero rows if any argument is a constant NULL, and the exact length when both the array and the dimension are constants. For dimension 1 of any other array it uses estimate_array_length(), like unnest() does. In all other cases it declines and prorows applies. Discussion: https://postgr.es/m/CAGRkXqQ6BLCkEBBC2OC_bvEaUPTg+z+2-euiJKKvAxgA7o1EAA@mail.gmail.com --- src/backend/utils/adt/arrayfuncs.c | 127 ++++++++++++++++ src/include/catalog/pg_proc.dat | 9 +- src/test/regress/expected/planner_est.out | 167 ++++++++++++++++++++++ src/test/regress/sql/planner_est.sql | 97 +++++++++++++ 4 files changed, 398 insertions(+), 2 deletions(-) diff --git a/src/backend/utils/adt/arrayfuncs.c b/src/backend/utils/adt/arrayfuncs.c index ef66182b047..f9c7fe90e04 100644 --- a/src/backend/utils/adt/arrayfuncs.c +++ b/src/backend/utils/adt/arrayfuncs.c @@ -6000,6 +6000,133 @@ generate_subscripts_nodir(PG_FUNCTION_ARGS) return generate_subscripts(fcinfo); } +/* + * Planner support function for generate_subscripts(anyarray, int [, bool]) + * + * Unlike unnest(), generate_subscripts() returns one row per subscript of + * the *requested dimension*, not one row per array element. Those are the + * same thing for a one-dimensional array, but in general we need the length + * of dimension "dim", which we can only determine when the array itself is + * available as a constant. + */ +Datum +generate_subscripts_support(PG_FUNCTION_ARGS) +{ + Node *rawreq = (Node *) PG_GETARG_POINTER(0); + Node *ret = NULL; + + if (IsA(rawreq, SupportRequestRows)) + { + /* Try to estimate the number of rows returned */ + SupportRequestRows *req = (SupportRequestRows *) rawreq; + + /* + * Be paranoid: only proceed when we are attached to one of the + * generate_subscripts() entries, the call site is a FuncExpr carrying + * enough arguments, and root is available, since + * estimate_expression_value() requires it. Otherwise decline, and + * prorows applies. + */ + if ((req->funcid == F_GENERATE_SUBSCRIPTS_ANYARRAY_INT4 || + req->funcid == F_GENERATE_SUBSCRIPTS_ANYARRAY_INT4_BOOL) && + req->root != NULL && + is_funcclause(req->node) && + list_length(((FuncExpr *) req->node)->args) >= 2) + { + List *args = ((FuncExpr *) req->node)->args; + Node *arg1, + *arg2, + *arg3 = NULL; + + /* The parser enforces the signature for these two functions */ + Assert(list_length(args) == 2 || list_length(args) == 3); + Assert(exprType(lsecond(args)) == INT4OID); + + /* We can use estimated argument values here */ + arg1 = estimate_expression_value(req->root, linitial(args)); + arg2 = estimate_expression_value(req->root, lsecond(args)); + + /* The third argument, "reverse", is optional */ + if (list_length(args) >= 3) + arg3 = estimate_expression_value(req->root, lthird(args)); + + /* + * The function is strict, so a constant NULL in any argument + * position means that no rows will be returned. Otherwise we + * need to know the dimension number to say anything at all. + */ + if ((IsA(arg1, Const) && + ((Const *) arg1)->constisnull) || + (IsA(arg2, Const) && + ((Const *) arg2)->constisnull) || + (arg3 != NULL && IsA(arg3, Const) && + ((Const *) arg3)->constisnull)) + { + req->rows = 0; + ret = (Node *) req; + } + else if (IsA(arg2, Const)) + { + int32 reqdim = DatumGetInt32(((Const *) arg2)->constvalue); + + if (reqdim <= 0) + { + /* generate_subscripts() returns no rows for such dims */ + req->rows = 0; + ret = (Node *) req; + } + else if (IsA(arg1, Const)) + { + ArrayType *arr; + + /* + * We know the array, so we can report the length of the + * requested dimension exactly. Note that the dimension's + * lower bound does not enter into it. A dimension the + * array doesn't have yields no rows, which also covers + * empty arrays, whose ndim is zero. + * + * Unlike estimate_array_length(), we don't bother to look + * through array coercions here; if one is in the way we + * simply fall through to the cases below. + */ + arr = DatumGetArrayTypeP(((Const *) arg1)->constvalue); + + if (reqdim > ARR_NDIM(arr)) + req->rows = 0; /* no such dimension */ + else + req->rows = ARR_DIMS(arr)[reqdim - 1]; + ret = (Node *) req; + } + else if (reqdim == 1) + { + /* + * Fall back on estimate_array_length(), as unnest() does. + * That estimates the whole array's element count, not the + * length of dimension 1, and from column statistics it + * counts only distinct non-null elements. So the result + * can be too high for multidimensional arrays and too low + * when elements repeat or are null. No per-dimension + * statistics exist that could do better. + */ + req->rows = estimate_array_length(req->root, arg1); + ret = (Node *) req; + } + + /* + * Otherwise a dimension above the first was requested for an + * array that isn't a constant. We know nothing about the + * array's dimensionality, let alone the length of the + * requested dimension, so leave ret as NULL to make the + * caller fall back on prorows. + */ + } + } + } + + PG_RETURN_POINTER(ret); +} + /* * array_fill_with_lower_bounds * Create and fill array with defined lower bounds. diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat index f46427258e3..9ed0ebb8a78 100644 --- a/src/include/catalog/pg_proc.dat +++ b/src/include/catalog/pg_proc.dat @@ -1711,13 +1711,18 @@ proargtypes => 'anycompatiblearray anycompatible', prosrc => 'array_positions' }, { oid => '1191', descr => 'array subscripts generator', - proname => 'generate_subscripts', prorows => '1000', proretset => 't', + proname => 'generate_subscripts', prorows => '1000', + prosupport => 'generate_subscripts_support', proretset => 't', prorettype => 'int4', proargtypes => 'anyarray int4 bool', prosrc => 'generate_subscripts' }, { oid => '1192', descr => 'array subscripts generator', - proname => 'generate_subscripts', prorows => '1000', proretset => 't', + proname => 'generate_subscripts', prorows => '1000', + prosupport => 'generate_subscripts_support', proretset => 't', prorettype => 'int4', proargtypes => 'anyarray int4', prosrc => 'generate_subscripts_nodir' }, +{ oid => '9419', descr => 'planner support for generate_subscripts', + proname => 'generate_subscripts_support', prorettype => 'internal', + proargtypes => 'internal', prosrc => 'generate_subscripts_support' }, { oid => '1193', descr => 'array constructor with value', proname => 'array_fill', proisstrict => 'f', prorettype => 'anyarray', proargtypes => 'anyelement _int4', prosrc => 'array_fill' }, diff --git a/src/test/regress/expected/planner_est.out b/src/test/regress/expected/planner_est.out index 236cb274a78..44eb5eeca32 100644 --- a/src/test/regress/expected/planner_est.out +++ b/src/test/regress/expected/planner_est.out @@ -183,6 +183,173 @@ false, true, false, true); Function Scan on generate_series g (cost=N..N rows=1000 width=N) (1 row) +-- +-- Test the SupportRequestRows support function for generate_subscripts() +-- +-- A constant array gives an exact estimate for the requested dimension +SELECT explain_mask_costs($$ +SELECT * FROM generate_subscripts('{10,20,30,40,50}'::int[], 1) g(s);$$, +true, true, false, true); + explain_mask_costs +----------------------------------------------------------------------------------------------- + Function Scan on generate_subscripts g (cost=N..N rows=5 width=N) (actual rows=5.00 loops=1) +(1 row) + +-- As above but for the 3-argument form; "reverse" cannot change the row count +SELECT explain_mask_costs($$ +SELECT * FROM generate_subscripts('{10,20,30,40,50}'::int[], 1, true) g(s);$$, +true, true, false, true); + explain_mask_costs +----------------------------------------------------------------------------------------------- + Function Scan on generate_subscripts g (cost=N..N rows=5 width=N) (actual rows=5.00 loops=1) +(1 row) + +-- Ensure a non-zero lower bound does not affect the estimate +SELECT explain_mask_costs($$ +SELECT * FROM generate_subscripts('[5:9]={10,20,30,40,50}'::int[], 1) g(s);$$, +true, true, false, true); + explain_mask_costs +----------------------------------------------------------------------------------------------- + Function Scan on generate_subscripts g (cost=N..N rows=5 width=N) (actual rows=5.00 loops=1) +(1 row) + +-- Ensure each dimension of a multi-dimensional array is estimated separately +SELECT explain_mask_costs($$ +SELECT * FROM generate_subscripts('{{1,2,3},{4,5,6}}'::int[], 1) g(s);$$, +true, true, false, true); + explain_mask_costs +----------------------------------------------------------------------------------------------- + Function Scan on generate_subscripts g (cost=N..N rows=2 width=N) (actual rows=2.00 loops=1) +(1 row) + +SELECT explain_mask_costs($$ +SELECT * FROM generate_subscripts('{{1,2,3},{4,5,6}}'::int[], 2) g(s);$$, +true, true, false, true); + explain_mask_costs +----------------------------------------------------------------------------------------------- + Function Scan on generate_subscripts g (cost=N..N rows=3 width=N) (actual rows=3.00 loops=1) +(1 row) + +-- Ensure a dimension above the second is handled too. Each dimension of this +-- array has a different length, so a mix-up could not go unnoticed. +SELECT explain_mask_costs($$ +SELECT * FROM generate_subscripts('{{{1,2,3,4},{5,6,7,8},{9,10,11,12}},{{13,14,15,16},{17,18,19,20},{21,22,23,24}}}'::int[], 3) g(s);$$, +true, true, false, true); + explain_mask_costs +----------------------------------------------------------------------------------------------- + Function Scan on generate_subscripts g (cost=N..N rows=4 width=N) (actual rows=4.00 loops=1) +(1 row) + +-- Ensure cases which return no rows estimate 1 row after clamping. Try an +-- out-of-range dimension, a dimension below the first, and an empty array. +SELECT explain_mask_costs($$ +SELECT * FROM generate_subscripts('{{1,2,3},{4,5,6}}'::int[], 3) g(s);$$, +true, true, false, true); + explain_mask_costs +----------------------------------------------------------------------------------------------- + Function Scan on generate_subscripts g (cost=N..N rows=1 width=N) (actual rows=0.00 loops=1) +(1 row) + +SELECT explain_mask_costs($$ +SELECT * FROM generate_subscripts('{10,20,30}'::int[], 0) g(s);$$, +true, true, false, true); + explain_mask_costs +----------------------------------------------------------------------------------------------- + Function Scan on generate_subscripts g (cost=N..N rows=1 width=N) (actual rows=0.00 loops=1) +(1 row) + +SELECT explain_mask_costs($$ +SELECT * FROM generate_subscripts('{}'::int[], 1) g(s);$$, +true, true, false, true); + explain_mask_costs +----------------------------------------------------------------------------------------------- + Function Scan on generate_subscripts g (cost=N..N rows=1 width=N) (actual rows=0.00 loops=1) +(1 row) + +-- Ensure a constant NULL in any argument position estimates no rows, since +-- generate_subscripts() is strict +SELECT explain_mask_costs($$ +SELECT * FROM generate_subscripts(NULL::int[], 1) g(s);$$, +true, true, false, true); + explain_mask_costs +----------------------------------------------------------------------------------------------- + Function Scan on generate_subscripts g (cost=N..N rows=1 width=N) (actual rows=0.00 loops=1) +(1 row) + +SELECT explain_mask_costs($$ +SELECT * FROM generate_subscripts('{10,20,30}'::int[], NULL) g(s);$$, +true, true, false, true); + explain_mask_costs +----------------------------------------------------------------------------------------------- + Function Scan on generate_subscripts g (cost=N..N rows=1 width=N) (actual rows=0.00 loops=1) +(1 row) + +SELECT explain_mask_costs($$ +SELECT * FROM generate_subscripts('{10,20,30}'::int[], 1, NULL) g(s);$$, +true, true, false, true); + explain_mask_costs +----------------------------------------------------------------------------------------------- + Function Scan on generate_subscripts g (cost=N..N rows=1 width=N) (actual rows=0.00 loops=1) +(1 row) + +-- An ArrayExpr is estimated by way of estimate_array_length() +SELECT explain_mask_costs($$ +SELECT * FROM generate_subscripts(ARRAY[1, 2, (SELECT 3)], 1) g(s);$$, +true, true, false, true); + explain_mask_costs +----------------------------------------------------------------------------------------------- + Function Scan on generate_subscripts g (cost=N..N rows=3 width=N) (actual rows=3.00 loops=1) + InitPlan expr_1 + -> Result (cost=N..N rows=1 width=N) (actual rows=1.00 loops=1) +(3 rows) + +-- Ensure we get the default row estimate when the dimension number isn't a +-- constant, since then we don't even know which dimension is wanted +SELECT explain_mask_costs($$ +SELECT * FROM generate_subscripts(ARRAY[1, 2, (SELECT 3)], (SELECT 1)) g(s);$$, +false, true, false, true); + explain_mask_costs +----------------------------------------------------------------------- + Function Scan on generate_subscripts g (cost=N..N rows=1000 width=N) + InitPlan expr_1 + -> Result (cost=N..N rows=1 width=N) + InitPlan expr_2 + -> Result (cost=N..N rows=1 width=N) +(5 rows) + +-- Ensure a Var array is estimated from the DECHIST statistics. Every array +-- below holds exactly 7 distinct elements, so the average distinct element +-- count does not depend on which rows ANALYZE happens to sample. +CREATE TEMP TABLE subscript_table_1 AS + SELECT array_agg(g) AS a FROM generate_series(1, 100) i, + LATERAL generate_series(1, 7) g GROUP BY i; +ANALYZE subscript_table_1; +-- Memoize is disabled here only to keep the plan shape stable; the node's +-- capacity and hit percentage are not masked by explain_mask_costs(). +SET enable_memoize = off; +SELECT explain_mask_costs($$ +SELECT * FROM subscript_table_1 t, LATERAL generate_subscripts(t.a, 1) g(s);$$, +true, true, false, true); + explain_mask_costs +------------------------------------------------------------------------------------------------------- + Nested Loop (cost=N..N rows=700 width=N) (actual rows=700.00 loops=1) + -> Seq Scan on subscript_table_1 t (cost=N..N rows=100 width=N) (actual rows=100.00 loops=1) + -> Function Scan on generate_subscripts g (cost=N..N rows=7 width=N) (actual rows=7.00 loops=100) +(3 rows) + +-- As above, but a dimension above the first falls back on prorows: the element +-- count in the statistics says nothing about the length of that dimension +SELECT explain_mask_costs($$ +SELECT * FROM subscript_table_1 t, LATERAL generate_subscripts(t.a, 2) g(s);$$, +false, true, false, true); + explain_mask_costs +----------------------------------------------------------------------------- + Nested Loop (cost=N..N rows=100000 width=N) + -> Seq Scan on subscript_table_1 t (cost=N..N rows=100 width=N) + -> Function Scan on generate_subscripts g (cost=N..N rows=1000 width=N) +(3 rows) + +RESET enable_memoize; -- -- Test ScalarArrayOpExpr row estimates for <> ALL for arrays with NULLs. We -- expect the planner to estimate 1 row will match in both of the following diff --git a/src/test/regress/sql/planner_est.sql b/src/test/regress/sql/planner_est.sql index 2b696a4e4e5..c4e7ba32cf3 100644 --- a/src/test/regress/sql/planner_est.sql +++ b/src/test/regress/sql/planner_est.sql @@ -131,6 +131,103 @@ SELECT explain_mask_costs($$ SELECT * FROM generate_series(25.0, 2.0, 0.0) g(s);$$, false, true, false, true); +-- +-- Test the SupportRequestRows support function for generate_subscripts() +-- + +-- A constant array gives an exact estimate for the requested dimension +SELECT explain_mask_costs($$ +SELECT * FROM generate_subscripts('{10,20,30,40,50}'::int[], 1) g(s);$$, +true, true, false, true); + +-- As above but for the 3-argument form; "reverse" cannot change the row count +SELECT explain_mask_costs($$ +SELECT * FROM generate_subscripts('{10,20,30,40,50}'::int[], 1, true) g(s);$$, +true, true, false, true); + +-- Ensure a non-zero lower bound does not affect the estimate +SELECT explain_mask_costs($$ +SELECT * FROM generate_subscripts('[5:9]={10,20,30,40,50}'::int[], 1) g(s);$$, +true, true, false, true); + +-- Ensure each dimension of a multi-dimensional array is estimated separately +SELECT explain_mask_costs($$ +SELECT * FROM generate_subscripts('{{1,2,3},{4,5,6}}'::int[], 1) g(s);$$, +true, true, false, true); + +SELECT explain_mask_costs($$ +SELECT * FROM generate_subscripts('{{1,2,3},{4,5,6}}'::int[], 2) g(s);$$, +true, true, false, true); + +-- Ensure a dimension above the second is handled too. Each dimension of this +-- array has a different length, so a mix-up could not go unnoticed. +SELECT explain_mask_costs($$ +SELECT * FROM generate_subscripts('{{{1,2,3,4},{5,6,7,8},{9,10,11,12}},{{13,14,15,16},{17,18,19,20},{21,22,23,24}}}'::int[], 3) g(s);$$, +true, true, false, true); + +-- Ensure cases which return no rows estimate 1 row after clamping. Try an +-- out-of-range dimension, a dimension below the first, and an empty array. +SELECT explain_mask_costs($$ +SELECT * FROM generate_subscripts('{{1,2,3},{4,5,6}}'::int[], 3) g(s);$$, +true, true, false, true); + +SELECT explain_mask_costs($$ +SELECT * FROM generate_subscripts('{10,20,30}'::int[], 0) g(s);$$, +true, true, false, true); + +SELECT explain_mask_costs($$ +SELECT * FROM generate_subscripts('{}'::int[], 1) g(s);$$, +true, true, false, true); + +-- Ensure a constant NULL in any argument position estimates no rows, since +-- generate_subscripts() is strict +SELECT explain_mask_costs($$ +SELECT * FROM generate_subscripts(NULL::int[], 1) g(s);$$, +true, true, false, true); + +SELECT explain_mask_costs($$ +SELECT * FROM generate_subscripts('{10,20,30}'::int[], NULL) g(s);$$, +true, true, false, true); + +SELECT explain_mask_costs($$ +SELECT * FROM generate_subscripts('{10,20,30}'::int[], 1, NULL) g(s);$$, +true, true, false, true); + +-- An ArrayExpr is estimated by way of estimate_array_length() +SELECT explain_mask_costs($$ +SELECT * FROM generate_subscripts(ARRAY[1, 2, (SELECT 3)], 1) g(s);$$, +true, true, false, true); + +-- Ensure we get the default row estimate when the dimension number isn't a +-- constant, since then we don't even know which dimension is wanted +SELECT explain_mask_costs($$ +SELECT * FROM generate_subscripts(ARRAY[1, 2, (SELECT 3)], (SELECT 1)) g(s);$$, +false, true, false, true); + +-- Ensure a Var array is estimated from the DECHIST statistics. Every array +-- below holds exactly 7 distinct elements, so the average distinct element +-- count does not depend on which rows ANALYZE happens to sample. +CREATE TEMP TABLE subscript_table_1 AS + SELECT array_agg(g) AS a FROM generate_series(1, 100) i, + LATERAL generate_series(1, 7) g GROUP BY i; +ANALYZE subscript_table_1; + +-- Memoize is disabled here only to keep the plan shape stable; the node's +-- capacity and hit percentage are not masked by explain_mask_costs(). +SET enable_memoize = off; + +SELECT explain_mask_costs($$ +SELECT * FROM subscript_table_1 t, LATERAL generate_subscripts(t.a, 1) g(s);$$, +true, true, false, true); + +-- As above, but a dimension above the first falls back on prorows: the element +-- count in the statistics says nothing about the length of that dimension +SELECT explain_mask_costs($$ +SELECT * FROM subscript_table_1 t, LATERAL generate_subscripts(t.a, 2) g(s);$$, +false, true, false, true); + +RESET enable_memoize; + -- -- Test ScalarArrayOpExpr row estimates for <> ALL for arrays with NULLs. We -- expect the planner to estimate 1 row will match in both of the following -- 2.37.1 (Apple Git-137.1)
^ permalink raw reply [nested|flat] 8+ messages in thread


end of thread, other threads:[~2026-09-27 15:54 UTC | newest]

Thread overview: 8+ messages (download: mbox mbox.gz follow: Atom feed)
-- links below jump to the message on this page --
2026-08-31 02:04 [PATCH] Planner support function for generate_subscripts() shihao zhong <zhong950419@gmail.com>
2026-09-07 12:27 ` Priyanka S <developerette@gmail.com>
2026-09-08 01:21   ` shihao zhong <zhong950419@gmail.com>
2026-09-08 10:07     ` Andrei Lepikhov <lepihov@gmail.com>
2026-09-09 01:20       ` shihao zhong <zhong950419@gmail.com>
2026-09-14 01:54         ` shihao zhong <zhong950419@gmail.com>
2026-09-27 09:04           ` Andrew Krylosov <krylosov.andrew@gmail.com>
2026-09-27 15:54             ` shihao zhong <zhong950419@gmail.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