Propagate pathkeys from CTEs up to the outer query.
authorTom Lane <tgl@sss.pgh.pa.us>
Tue, 26 Mar 2024 17:05:49 +0000 (13:05 -0400)
committerTom Lane <tgl@sss.pgh.pa.us>
Tue, 26 Mar 2024 17:05:51 +0000 (13:05 -0400)
commita65724dfa73db8b451d0c874a9161935a34a914e
tree04bdd460d3344447dcc29501e733d3dd6e8928aa
parente648e77e25708874196326b6e4da30e7717156ab
Propagate pathkeys from CTEs up to the outer query.

If we know the sort order of a CTE's output, and it is relevant
to the outer query, label the CTE's outer-query access path using
those pathkeys.  This may enable optimizations such as avoiding
a sort in the outer query.

The code for hoisting pathkeys into the outer query already exists
for regular RTE_SUBQUERY subqueries, but it wasn't getting used for
CTEs, possibly out of concern for maintaining an optimization fence
between the CTE and the outer query.  However, on the same arguments
used for commit f7816aec2, there seems no harm in letting the outer
query know what the inner query decided to do.

In support of this, we now remember the best Path as well as Plan
for each subquery for the rest of the planner run.  There may be
future applications for having that at hand, and it surely costs
little to build one more List.

Richard Guo (minor mods by me)

Discussion: https://postgr.es/m/CAMbWs49xYd3f8CrE8-WW3--dV1zH_sDSDn-vs2DzHj81Wcnsew@mail.gmail.com
src/backend/optimizer/path/allpaths.c
src/backend/optimizer/plan/planner.c
src/backend/optimizer/plan/subselect.c
src/backend/optimizer/util/pathnode.c
src/include/nodes/pathnodes.h
src/include/optimizer/pathnode.h
src/test/regress/expected/with.out
src/test/regress/sql/with.sql