examine_variable ignored CollateExpr

Поиск
Список
Период
Сортировка
Искать

examine_variable ignored CollateExpr

От:
jian he <jian.universality@gmail.com>
Дата:
Вложения:
hi.

ComputeIndexAttrs:
src/backend/commands/indexcmds.c, line 1995:
            /*
             * Strip any top-level COLLATE clause.  This ensures that we treat
             * "x COLLATE y" and "(x COLLATE y)" alike.
             */
            while (IsA(expr, CollateExpr))
                expr = (Node *) ((CollateExpr *) expr)->arg;

That means in function examine_variable:
``foreach(ilist, onerel->indexlist)``
we don't need to worry about RelabelType transformed from COLLATE clause.

CreateStatistics does not have special handling for CollateExpr. Query like:
CREATE STATISTICS t_stx1 ON (a collate "C" collate "C" collate "C"
collate "POSIX") FROM t;
the stored statistics expression node will be a nested CollateExpr.

For the above example,
get_relation_info->get_relation_statistics->eval_const_expressions will
transform the nested CollateExpr into one RelabelType node if column "a"
collation is not POSIX.

RelabelType can be from the CollateExpr transformation, as mentioned above.  For
statistics, say ndistinct, ``GROUP BY A COLLATE "C"`` can have different results
from ``GROUP BY A COLLATE case_insensitive``.

Therefore in examine_variable, we can not just simple use:
``
       while (IsA(basenode, RelabelType))
               basenode = (Node *) ((RelabelType *) basenode)->arg;
``

demo:
CREATE TABLE test_stats_ext_coll (a text, b text, c int);
INSERT INTO test_stats_ext_coll SELECT chr(65 + g % 52) FROM
generate_series(1, 500) g;
CREATE STATISTICS test_stats_ext_coll_stx ON (a COLLATE
case_insensitive) FROM test_stats_ext_coll;
ANALYZE test_stats_ext_coll;

SELECT * FROM check_estimated_rows ($$SELECT count(*) FROM
test_stats_ext_coll GROUP BY a COLLATE case_insensitive $$);

with HEAD:
 estimated | actual
-----------+--------
        52 |     32

with attached PATCH:
 estimated | actual
-----------+--------
        32 |     32

function check_estimated_rows is in src/test/regress/sql/stats_ext.sql.

While working on this, I wondered whether we could move check_estimated_rows
from stats_ext.sql to test_setup.sql so that it can be reused more broadly.



--
jian
https://www.enterprisedb.com/

Re: examine_variable ignored CollateExpr

От:
shihao zhong <zhong950419@gmail.com>
Дата:
Hi Jian,

With v1 or v4 I get a worse estimate when the table has no
statistics object.

  CREATE TABLE t (a text);
  INSERT INTO t SELECT chr(65 + g % 52)
    FROM generate_series(1, 5200) g;
  ANALYZE t;
  EXPLAIN SELECT * FROM t WHERE a COLLATE "C" = 'A';

On master I get
  Seq Scan on t  (cost=0.00..89.00 rows=100 width=2)
With v1 or v4 I get
  Seq Scan on t  (cost=0.00..89.00 rows=26 width=2)

Could we keep the stripping, and check the statistics expressions
first only when a COLLATE was stripped from a plain column? A
table without extended statistics pays one test of rel->statlist.

Thanks,
Shihao

Re: examine_variable ignored CollateExpr

От:
"ZizhuanLiu X-MAN" <44973863@qq.com>
Дата:
Вложения:
Original
>From: shihao zhong 
>Date: 2026-10-05 11:59
>To: ZizhuanLiu X-MAN <44973863@qq.com>
>Cc: pgsql-hackers , jian he , tgl , Guo 
>Subject: Re: examine_variable ignored CollateExpr
>Hi Jian,
>
>With v1 or v4 I get a worse estimate when the table has no
>statistics object.
>
>  CREATE TABLE t (a text);
>  INSERT INTO t SELECT chr(65 + g % 52)
>    FROM generate_series(1, 5200) g;
>  ANALYZE t;
>  EXPLAIN SELECT * FROM t WHERE a COLLATE "C" = 'A';
>
>On master I get
>  Seq Scan on t  (cost=0.00..89.00 rows=100 width=2)
>With v1 or v4 I get
>  Seq Scan on t  (cost=0.00..89.00 rows=26 width=2)
>
>Could we keep the stripping, and check the statistics expressions
>first only when a COLLATE was stripped from a plain column? A
>table without extended statistics pays one test of rel->statlist.
>
>Thanks,
>Shihao
       
Hi, Shihao
   Thank you for your feedback!


Hi, all

Fix RelabelType handling in statistics lookup

Regarding examine_variable() in src/backend/utils/adt/selfuncs.c:
1. Handling adjacent RelabelType nodes after stripping PHVs
PATCH[1] added PHV stripping for node, followed by the following loop on 
the resulting basenode:
```C
while (IsA(basenode, RelabelType))
    basenode = (Node *) ((RelabelType *) basenode)->arg;
```C
This loop strips only consecutive RelabelType nodes at the top level.
It does not handle adjacent RelabelType nodes that may arise deeper
in the expression tree.

Since stripping PHVs, as introduced by PATCH[1], can bring previously
separated RelabelType nodes into adjacency, I think it would be better to
strip these adjacent nodes at the point where this adjacency can arise.
This keeps the creation and removal of adjacent RelabelType nodes together
as a single, cohesive operation, without requiring a heavyweight function.

I therefore chose to call the new helper function strip_all_adjacency_relabeltypes()
from within strip_all_phvs_mutator().

(Sorry, my previous version of strip_all_adjacency_relabeltypes() 
did not actually return the stripped expression.)

2. Preserving the previous lookup behavior
Before PATCH[1], there was a symmetric attempt to strip the topmost RelabelType
from the input node, index expressions, and extended statistics expressions
before comparing them. The relevant code is as follows:
```C
--for node
   if (IsA(node, RelabelType))
       basenode = (Node *) ((RelabelType *) node)->arg;
   else
       basenode = node;

--for index's expr
if (indexkey && IsA(indexkey, RelabelType))
						indexkey = (Node *) ((RelabelType *) indexkey)->arg;

--for extended statistics
if (expr && IsA(expr, RelabelType))
					expr = (Node *) ((RelabelType *) expr)->arg;
```C

The original behavior was to strip the topmost RelabelType before comparing
expressions with equal().

However, this is not entirely satisfactory. Ideally, we should use statistics
associated with expressions that match exactly according to equal(). 
Stripping the topmost RelabelType before comparison should be a fallback
rather than the preferred approach.

Therefore, the new PATCH first compares the input expression, index expressions,
and extended statistics expressions as they are, without stripping their topmost
RelabelType nodes. If no matching statistics are found, it retries the lookup under
certain conditions, symmetrically stripping the topmost RelabelType from the
input expression and the candidate expressions before comparing them. 
This preserves the behavior that existed before PATCH[1] as a fallback, maintaining
compatibility with the previous lookup logic.

(The normalization performed by strip_all_phvs_mutator(), following logic similar to
applyRelabelType(), is a separate matter and remains appropriate. It normalizes
adjacent RelabelType nodes that may arise when PHVs are stripped, while preserving
the semantics of the outermost relabeling. This is consistent with the normalization
already applied to index expressions and extended statistics expressions.)

Feedback is welcome.

[1] https://git.postgresql.org/gitweb/?p=postgresql.git;a=commitdiff;h=7e9f852a79fe19d4d0f18aabc32a620797fb676e
[1] https://www.postgresql.org/message-id/flat/E1va3GH-003FBe-35%40gemulon.postgresql.org


The following are the relevant test SQL statements:
1. After strip_all_phvs_mutator() and strip_all_adjacency_relabeltypes(),
statistics are successfully found for the corresponding index expressions
and extended statistics expressions:
--setup
DROP TABLE IF EXISTS phv_left, phv_right CASCADE;
DROP COLLATION IF EXISTS case_insensitive;

CREATE COLLATION case_insensitive
    (provider = icu,
     locale = 'und-u-ks-level2',
     deterministic = false);

CREATE TABLE phv_left ( id int );

CREATE TABLE phv_right( id   int, name text COLLATE "C");

INSERT INTO phv_left
SELECT g
FROM generate_series(1, 1100) AS g;

INSERT INTO phv_right
SELECT g,
       CASE WHEN g % 17 = 0 THEN NULL
            ELSE chr(65 + (g % 26))
       END
FROM generate_series(1, 1000) AS g;

-- Matches the statistics for index phv_right_index_5
create index phv_right_index_5 on phv_right(COALESCE(name COLLATE "C", ''::text COLLATE "C"));
analyze phv_right;

EXPLAIN analyze
SELECT r.x COLLATE "C" AS k,
       count(*)
FROM phv_left AS l
LEFT JOIN
(
    SELECT id,
           (COALESCE(name COLLATE "C", ''::text COLLATE "C") COLLATE case_insensitive) AS x
    FROM phv_right
) AS r
    ON r.id = l.id
GROUP BY r.x COLLATE "C";

-- Matches the statistics for extended statistics object phv_right_expr_stats_5
drop index phv_right_index_5;      --drop phv_right_index_5 first
create STATISTICS phv_right_expr_stats_5 
on (COALESCE(name COLLATE "C", ''::text COLLATE "C")) 
  FROM phv_right; ANALYZE phv_right;
analyze phv_right;

EXPLAIN analyze
SELECT r.x COLLATE "C" AS k,
       count(*)
FROM phv_left AS l
LEFT JOIN
(
    SELECT id,
           (COALESCE(name COLLATE "C", ''::text COLLATE "C") COLLATE case_insensitive) AS x
    FROM phv_right
) AS r
    ON r.id = l.id
GROUP BY r.x COLLATE "C";

2. Statistics for the underlying Var are found after stripping the topmost RelabelType from basenode on the second attempt:
CREATE TABLE t (a text);
  INSERT INTO t SELECT chr(65 + g % 52)
    FROM generate_series(1, 5200) g;
  ANALYZE t;
  EXPLAIN SELECT * FROM t WHERE a COLLATE "C" = 'A';


regards,
--
ZizhuanLiu (X-MAN) 
44973863@qq.com

Re: examine_variable ignored CollateExpr

От:
shihao zhong <zhong950419@gmail.com>
Дата:
Hi Zizhuan,

Thanks for v5. My example is fixed, I get rows=100 again. The
regression tests pass, and I could not measure any change in
planning time for varchar columns.

One more issue 

  CREATE TABLE t (a text);
  INSERT INTO t SELECT chr(65 + g % 52) || g
    FROM generate_series(1, 5200) g;
  CREATE STATISTICS s ON (left(a, 1) COLLATE "C") FROM t;
  ANALYZE t;
  EXPLAIN SELECT * FROM t WHERE left(a, 1) = 'A';

On master I get rows=100, with v5 I get rows=26. I think the retry
only runs when the query has the COLLATE, not when only the
statistics expression has it.

v5 also dropped the tests that v1 had. Could you add them back,
with this case and my earlier one?

Thanks,
Shihao

Re: examine_variable ignored CollateExpr

От:
"ZizhuanLiu X-MAN" <44973863@qq.com>
Дата:
Вложения:
>Original
>From: shihao zhong 
>Date: 2026-10-11 10:38
>To: ZizhuanLiu X-MAN <44973863@qq.com>
>Cc: pgsql-hackers , jian he , tgl , Guo 
>Subject: Re: examine_variable ignored CollateExpr
>
>Hi Zizhuan,
>
>Thanks for v5. My example is fixed, I get rows=100 again. The
>regression tests pass, and I could not measure any change in
>planning time for varchar columns.
>
>One more issue 
>
>  CREATE TABLE t (a text);
>  INSERT INTO t SELECT chr(65 + g % 52) || g
>    FROM generate_series(1, 5200) g;
>  CREATE STATISTICS s ON (left(a, 1) COLLATE "C") FROM t;
>  ANALYZE t;
>  EXPLAIN SELECT * FROM t WHERE left(a, 1) = 'A';
>
>On master I get rows=100, with v5 I get rows=26. I think the retry
>only runs when the query has the COLLATE, not when only the
>statistics expression has it.
>
>v5 also dropped the tests that v1 had. Could you add them back,
>with this case and my earlier one?
>
>Thanks,
>Shihao       

Hi, Shihao,hackers

Thank you for your prompt and constructive feedback.

I've updated the code to avoid unnecessary comparisons on retry.
It now separately tracks whether node, indexpr, and statexpr have 
a topmost RelabelType associated with COLLATE, and uses these 
flags to determine which comparisons are necessary:
  - indexpr is compared only if basenode_is_topmost_relabeltype or indexkey_is_topmost_relabeltype is true.
  - statexpr is compared only if basenode_is_topmost_relabeltype or statexpr_is_topmost_relabeltype is true.

All the issues you mentioned have been addressed, and the missing test cases have been added. 
The corresponding regression tests and expected output have also been updated in the .sql and .out files.

Thanks again for your review and suggestions.

regards,           
--                 
ZizhuanLiu (X-MAN) 
44973863@qq.com

Re: examine_variable ignored CollateExpr

От:
"ZizhuanLiu X-MAN" <44973863@qq.com>
Дата:
Вложения:
Sorry, 
there was a mistake in stats_import.out. I've fixed it and updated the patch.

regards,
--
ZizhuanLiu (X-MAN) 
44973863@qq.com


FAQ