Prevent pushing down WHERE clauses into unsafe UNION/INTERSECT nests.
authorTom Lane <tgl@sss.pgh.pa.us>
Thu, 6 Jun 2013 03:44:02 +0000 (23:44 -0400)
committerTom Lane <tgl@sss.pgh.pa.us>
Thu, 6 Jun 2013 03:45:11 +0000 (23:45 -0400)
commit964c0d0f80e485dd3a4073e073ddfd9bfdda90b2
treef1c88463b8892a5ac4031cb51fa52c376567b9ae
parenta3bd6096bdc6db70ec267116ba52a4cccbd34c2a
Prevent pushing down WHERE clauses into unsafe UNION/INTERSECT nests.

The planner is aware that it mustn't push down upper-level quals into
subqueries if the quals reference subquery output columns that contain
set-returning functions or volatile functions, or are non-DISTINCT outputs
of a DISTINCT ON subquery.  However, it missed making this check when
there were one or more levels of UNION or INTERSECT above the dangerous
expression.  This could lead to "set-valued function called in context that
cannot accept a set" errors, as seen in bug #8213 from Eric Soroos, or to
silently wrong answers in the other cases.

To fix, refactor the checks so that we make the column-is-unsafe checks
during subquery_is_pushdown_safe(), which already has to recursively
inspect all arms of a set-operation tree.  This makes
qual_is_pushdown_safe() considerably simpler, at the cost that we will
spend some cycles checking output columns that possibly aren't referenced
in any upper qual.  But the cases where this code gets executed at all
are already nontrivial queries, so it's unlikely anybody will notice any
slowdown of planning.

This has been broken since commit 05f916e6add9726bf4ee046e4060c1b03c9961f2,
which makes the bug over ten years old.  A bit surprising nobody noticed it
before now.
src/backend/optimizer/path/allpaths.c
src/test/regress/expected/union.out
src/test/regress/sql/union.sql