Fix qual pushdown past grouping through simple CASE

Commit 44fb59fc6 taught the grouping-conflict walker to treat the arg
of a simple CASE as a direct operand of each WHEN comparison, but it
only checked the collation, on the assumption that the WHEN operator
is always the type-default "=" and thus matches the grouping eqop.
That assumption fails once the arg is relabeled to another type: the
WHEN then compares under that type's "=", which need not agree with
the grouping equality.  For instance, with a DISTINCT over a citext
column, a qual such as "CASE t::text WHEN 'A' THEN ..." was pushed
below the Unique, although the equivalent "t::text = 'A'" is correctly
kept above it.

Instead of special-casing the arg, have the walker bind a Var arg
while walking the WHEN conditions and resolve each CaseTestExpr to it,
so that the arg is checked exactly as each WHEN uses it: with the
opfamily and collation checks of a direct operand when the WHEN is a
comparison, and as a non-operand reference otherwise.  A non-Var arg
is walked once as a non-operand, as before.  The CaseTestExpr in an
ArrayCoerceExpr's elemexpr and a JsonConstructorExpr's coercion stand
for something else and are left alone.

Reported-by: Tender Wang <[email protected]>
Author: Richard Guo <[email protected]>
Reviewed-by: Tender Wang <[email protected]>
Reviewed-by: Ewan Young <[email protected]>
Discussion: 
https://postgr.es/m/CAHewXNkvGTOgijRLjmudpg=wz0d-j8chy2o7ksh3be+q_bx...@mail.gmail.com
Backpatch-through: 18

Branch
------
REL_19_STABLE

Details
-------
https://git.postgresql.org/pg/commitdiff/a3bc7f2c0de8ad5c6ae746cb6c1c5c187a60c124

Modified Files
--------------
src/backend/optimizer/util/clauses.c           | 127 +++++++++++++++++--------
src/test/regress/expected/collate.icu.utf8.out |  35 +++++++
src/test/regress/expected/subselect.out        |  27 ++++++
src/test/regress/sql/collate.icu.utf8.sql      |  12 +++
src/test/regress/sql/subselect.sql             |  11 +++
5 files changed, 171 insertions(+), 41 deletions(-)

Reply via email to