Fix lateral references in sort keys added by createplan.c

When prepare_sort_from_pathkeys() cannot find a pathkey's expression
in the input plan's targetlist, it adds a resjunk entry computing an
EquivalenceClass member's expression.  It copied that expression
as-is, without replacing lateral references with nestloop Params the
way build_path_tlist() does for the rest of the targetlist.

This matters when the sort key contains a PlaceHolderVar whose
expression has a lateral reference, and the sort is placed directly
atop the plan node that evaluates the PlaceHolderVar.  The targetlist
already contains the PlaceHolderVar, so the sort key is considered
computable, but the entry added for it still has the outer relation's
Var inside the PlaceHolderVar.  If the node is a join, setrefs.c fails
with "variable not found in subplan target lists".  If it is a scan,
setrefs.c leaves the Var in place, and the executor fetches it from
the scan tuple, leading to wrong results.

To fix, pass root to prepare_sort_from_pathkeys() and apply
replace_nestloop_params() to the expression before adding it to the
targetlist.

Back-patch to all supported branches.

Author: Richard Guo <[email protected]>
Discussion: 
https://postgr.es/m/cambws49lwnm7_oxuw1v71wli+ev3kbfy1bmy36uydnkwspn...@mail.gmail.com
Backpatch-through: 14

Branch
------
REL_14_STABLE

Details
-------
https://git.postgresql.org/pg/commitdiff/1fcd7dd80fbd4381b374230cc7168ee7c4bf37ab

Modified Files
--------------
src/backend/optimizer/plan/createplan.c | 56 ++++++++++++---------
src/test/regress/expected/join.out      | 86 +++++++++++++++++++++++++++++++++
src/test/regress/sql/join.sql           | 34 +++++++++++++
3 files changed, 154 insertions(+), 22 deletions(-)

Reply via email to