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_19_STABLE Details ------- https://git.postgresql.org/pg/commitdiff/0b5f59d541ca63a1fccaad8a384cc70856d35d45 Modified Files -------------- src/backend/optimizer/plan/createplan.c | 58 +++++++++++++--------- src/test/regress/expected/join.out | 87 +++++++++++++++++++++++++++++++++ src/test/regress/sql/join.sql | 34 +++++++++++++ 3 files changed, 156 insertions(+), 23 deletions(-)
