Fix preprocessing of PHV copies pushed down into subqueries

Commit e28cf96e9 preprocessed the copies of a query level's
PlaceHolderVars that were pushed down into its subqueries in a single
walk at the start of subquery_planner.  That was wrong in two ways.

First, such copies can also be inserted later, when a join alias Var
of the outer level is expanded within a LATERAL subquery or a
SubLink's subselect and the alias expression contains a PHV.  Those
copies were never preprocessed, so a SubLink within them survived into
the subquery's lateral references or into a SubPlan's argument list,
tripping an assertion in identify_current_nestloop_params or failing
in cost_qual_eval.

Second, when a pushed-down copy directly contains another PHV of the
same level, the walk preprocessed the inner one first and then the
outer one, so the outer one's preprocessing ran into the SubPlans just
created in the inner one and tripped an assertion in
flatten_join_alias_vars.

To fix, preprocess the copies right after join alias expansion
instead: within preprocess_expression, just before SubLinks are turned
into SubPlans, and for LATERAL subquery RTEs, right after their
aliases are flattened.  Preprocessing a copy handles everything within
it, including any further copies nested inside its SubLinks, so the
walker no longer looks inside a copy.

Back-patch to v16, as with commit e28cf96e9.

Reported-by: Fujii Masao <[email protected]>
Author: Richard Guo <[email protected]>
Discussion: 
https://postgr.es/m/CAHGQGwH-acRnAk1=Ki4EiAJEt67+Rz=_jyg7pbp_c6bk4oh...@mail.gmail.com
Backpatch-through: 16

Branch
------
REL_19_STABLE

Details
-------
https://git.postgresql.org/pg/commitdiff/22a8f53397ee6d70d8da01bef6835b5843a90df8

Modified Files
--------------
src/backend/optimizer/plan/planner.c   |  52 ++++++-----
src/backend/optimizer/plan/subselect.c |   7 +-
src/backend/optimizer/util/var.c       |   9 +-
src/test/regress/expected/join.out     | 154 ++++++++++++++++++++++++++++++---
src/test/regress/sql/join.sql          |  35 ++++++++
5 files changed, 216 insertions(+), 41 deletions(-)

Reply via email to