Fix edge case in remove_useless_result_rtes() with outer joins.

find_dependent_phvs() and find_dependent_phvs_in_jointree() decide
whether a PlaceHolderVar depends on the RTE_RESULT rel we're
considering removing by comparing the PHV's phrels to a singleton set
containing that rel's RT index, reasoning that if phrels contains any
other relid bits then those define an appropriate place where we can
evaluate the PHV.  But since this code was originally written, we've
redefined phrels to include outer-join relids, and that breaks this
logic, potentially allowing us to remove an RTE_RESULT that leaves no
valid place to evaluate the PHV.  The planner doesn't throw an error
when that happens, but it does produce an incorrect plan that will not
replace the PHV's value with NULL when needed.

In the known test case for this bug, the "extra" OJ relid is one that
we've actually decided to remove but haven't yet cleaned out of the
query's PHVs.  It's not entirely clear though that that would always
be the case.  Let's restore this code to the way it was designed to
work, by considering only base relids within the PHV's phrels.

Bug: #19553
Reported-by: Viktor Leis <[email protected]>
Author: Matheus Alcantara <[email protected]>
Co-authored-by: Richard Guo <[email protected]>
Reviewed-by: Tom Lane <[email protected]>
Discussion: https://postgr.es/m/[email protected]
Backpatch-through: 16

Branch
------
master

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

Modified Files
--------------
src/backend/optimizer/prep/prepjointree.c | 64 ++++++++++++++++++++++++-------
src/test/regress/expected/join.out        | 27 +++++++++++++
src/test/regress/sql/join.sql             | 10 +++++
3 files changed, 88 insertions(+), 13 deletions(-)

Reply via email to