PostgreSQL Source Code  git master
createplan.c File Reference
#include "postgres.h"
#include <limits.h>
#include <math.h>
#include "access/sysattr.h"
#include "catalog/pg_class.h"
#include "foreign/fdwapi.h"
#include "miscadmin.h"
#include "nodes/extensible.h"
#include "nodes/makefuncs.h"
#include "nodes/nodeFuncs.h"
#include "optimizer/clauses.h"
#include "optimizer/cost.h"
#include "optimizer/optimizer.h"
#include "optimizer/paramassign.h"
#include "optimizer/paths.h"
#include "optimizer/placeholder.h"
#include "optimizer/plancat.h"
#include "optimizer/planmain.h"
#include "optimizer/restrictinfo.h"
#include "optimizer/subselect.h"
#include "optimizer/tlist.h"
#include "parser/parse_clause.h"
#include "parser/parsetree.h"
#include "partitioning/partprune.h"
#include "utils/lsyscache.h"
Include dependency graph for createplan.c:

Go to the source code of this file.

Macros

#define CP_EXACT_TLIST   0x0001 /* Plan must return specified tlist */
 
#define CP_SMALL_TLIST   0x0002 /* Prefer narrower tlists */
 
#define CP_LABEL_TLIST   0x0004 /* tlist must contain sortgrouprefs */
 
#define CP_IGNORE_TLIST   0x0008 /* caller will replace tlist */
 

Functions

static Plancreate_plan_recurse (PlannerInfo *root, Path *best_path, int flags)
 
static Plancreate_scan_plan (PlannerInfo *root, Path *best_path, int flags)
 
static Listbuild_path_tlist (PlannerInfo *root, Path *path)
 
static bool use_physical_tlist (PlannerInfo *root, Path *path, int flags)
 
static Listget_gating_quals (PlannerInfo *root, List *quals)
 
static Plancreate_gating_plan (PlannerInfo *root, Path *path, Plan *plan, List *gating_quals)
 
static Plancreate_join_plan (PlannerInfo *root, JoinPath *best_path)
 
static bool is_async_capable_path (Path *path)
 
static Plancreate_append_plan (PlannerInfo *root, AppendPath *best_path, int flags)
 
static Plancreate_merge_append_plan (PlannerInfo *root, MergeAppendPath *best_path, int flags)
 
static Resultcreate_group_result_plan (PlannerInfo *root, GroupResultPath *best_path)
 
static ProjectSetcreate_project_set_plan (PlannerInfo *root, ProjectSetPath *best_path)
 
static Materialcreate_material_plan (PlannerInfo *root, MaterialPath *best_path, int flags)
 
static ResultCachecreate_resultcache_plan (PlannerInfo *root, ResultCachePath *best_path, int flags)
 
static Plancreate_unique_plan (PlannerInfo *root, UniquePath *best_path, int flags)
 
static Gathercreate_gather_plan (PlannerInfo *root, GatherPath *best_path)
 
static Plancreate_projection_plan (PlannerInfo *root, ProjectionPath *best_path, int flags)
 
static Planinject_projection_plan (Plan *subplan, List *tlist, bool parallel_safe)
 
static Sortcreate_sort_plan (PlannerInfo *root, SortPath *best_path, int flags)
 
static IncrementalSortcreate_incrementalsort_plan (PlannerInfo *root, IncrementalSortPath *best_path, int flags)
 
static Groupcreate_group_plan (PlannerInfo *root, GroupPath *best_path)
 
static Uniquecreate_upper_unique_plan (PlannerInfo *root, UpperUniquePath *best_path, int flags)
 
static Aggcreate_agg_plan (PlannerInfo *root, AggPath *best_path)
 
static Plancreate_groupingsets_plan (PlannerInfo *root, GroupingSetsPath *best_path)
 
static Resultcreate_minmaxagg_plan (PlannerInfo *root, MinMaxAggPath *best_path)
 
static WindowAggcreate_windowagg_plan (PlannerInfo *root, WindowAggPath *best_path)
 
static SetOpcreate_setop_plan (PlannerInfo *root, SetOpPath *best_path, int flags)
 
static RecursiveUnioncreate_recursiveunion_plan (PlannerInfo *root, RecursiveUnionPath *best_path)
 
static LockRowscreate_lockrows_plan (PlannerInfo *root, LockRowsPath *best_path, int flags)
 
static ModifyTablecreate_modifytable_plan (PlannerInfo *root, ModifyTablePath *best_path)
 
static Limitcreate_limit_plan (PlannerInfo *root, LimitPath *best_path, int flags)
 
static SeqScancreate_seqscan_plan (PlannerInfo *root, Path *best_path, List *tlist, List *scan_clauses)
 
static SampleScancreate_samplescan_plan (PlannerInfo *root, Path *best_path, List *tlist, List *scan_clauses)
 
static Scancreate_indexscan_plan (PlannerInfo *root, IndexPath *best_path, List *tlist, List *scan_clauses, bool indexonly)
 
static BitmapHeapScancreate_bitmap_scan_plan (PlannerInfo *root, BitmapHeapPath *best_path, List *tlist, List *scan_clauses)
 
static Plancreate_bitmap_subplan (PlannerInfo *root, Path *bitmapqual, List **qual, List **indexqual, List **indexECs)
 
static void bitmap_subplan_mark_shared (Plan *plan)
 
static TidScancreate_tidscan_plan (PlannerInfo *root, TidPath *best_path, List *tlist, List *scan_clauses)
 
static TidRangeScancreate_tidrangescan_plan (PlannerInfo *root, TidRangePath *best_path, List *tlist, List *scan_clauses)
 
static SubqueryScancreate_subqueryscan_plan (PlannerInfo *root, SubqueryScanPath *best_path, List *tlist, List *scan_clauses)
 
static FunctionScancreate_functionscan_plan (PlannerInfo *root, Path *best_path, List *tlist, List *scan_clauses)
 
static ValuesScancreate_valuesscan_plan (PlannerInfo *root, Path *best_path, List *tlist, List *scan_clauses)
 
static TableFuncScancreate_tablefuncscan_plan (PlannerInfo *root, Path *best_path, List *tlist, List *scan_clauses)
 
static CteScancreate_ctescan_plan (PlannerInfo *root, Path *best_path, List *tlist, List *scan_clauses)
 
static NamedTuplestoreScancreate_namedtuplestorescan_plan (PlannerInfo *root, Path *best_path, List *tlist, List *scan_clauses)
 
static Resultcreate_resultscan_plan (PlannerInfo *root, Path *best_path, List *tlist, List *scan_clauses)
 
static WorkTableScancreate_worktablescan_plan (PlannerInfo *root, Path *best_path, List *tlist, List *scan_clauses)
 
static ForeignScancreate_foreignscan_plan (PlannerInfo *root, ForeignPath *best_path, List *tlist, List *scan_clauses)
 
static CustomScancreate_customscan_plan (PlannerInfo *root, CustomPath *best_path, List *tlist, List *scan_clauses)
 
static NestLoopcreate_nestloop_plan (PlannerInfo *root, NestPath *best_path)
 
static MergeJoincreate_mergejoin_plan (PlannerInfo *root, MergePath *best_path)
 
static HashJoincreate_hashjoin_plan (PlannerInfo *root, HashPath *best_path)
 
static Nodereplace_nestloop_params (PlannerInfo *root, Node *expr)
 
static Nodereplace_nestloop_params_mutator (Node *node, PlannerInfo *root)
 
static void fix_indexqual_references (PlannerInfo *root, IndexPath *index_path, List **stripped_indexquals_p, List **fixed_indexquals_p)
 
static Listfix_indexorderby_references (PlannerInfo *root, IndexPath *index_path)
 
static Nodefix_indexqual_clause (PlannerInfo *root, IndexOptInfo *index, int indexcol, Node *clause, List *indexcolnos)
 
static Nodefix_indexqual_operand (Node *node, IndexOptInfo *index, int indexcol)
 
static Listget_switched_clauses (List *clauses, Relids outerrelids)
 
static Listorder_qual_clauses (PlannerInfo *root, List *clauses)
 
static void copy_generic_path_info (Plan *dest, Path *src)
 
static void copy_plan_costsize (Plan *dest, Plan *src)
 
static void label_sort_with_costsize (PlannerInfo *root, Sort *plan, double limit_tuples)
 
static SeqScanmake_seqscan (List *qptlist, List *qpqual, Index scanrelid)
 
static SampleScanmake_samplescan (List *qptlist, List *qpqual, Index scanrelid, TableSampleClause *tsc)
 
static IndexScanmake_indexscan (List *qptlist, List *qpqual, Index scanrelid, Oid indexid, List *indexqual, List *indexqualorig, List *indexorderby, List *indexorderbyorig, List *indexorderbyops, ScanDirection indexscandir)
 
static IndexOnlyScanmake_indexonlyscan (List *qptlist, List *qpqual, Index scanrelid, Oid indexid, List *indexqual, List *indexorderby, List *indextlist, ScanDirection indexscandir)
 
static BitmapIndexScanmake_bitmap_indexscan (Index scanrelid, Oid indexid, List *indexqual, List *indexqualorig)
 
static BitmapHeapScanmake_bitmap_heapscan (List *qptlist, List *qpqual, Plan *lefttree, List *bitmapqualorig, Index scanrelid)
 
static TidScanmake_tidscan (List *qptlist, List *qpqual, Index scanrelid, List *tidquals)
 
static TidRangeScanmake_tidrangescan (List *qptlist, List *qpqual, Index scanrelid, List *tidrangequals)
 
static SubqueryScanmake_subqueryscan (List *qptlist, List *qpqual, Index scanrelid, Plan *subplan)
 
static FunctionScanmake_functionscan (List *qptlist, List *qpqual, Index scanrelid, List *functions, bool funcordinality)
 
static ValuesScanmake_valuesscan (List *qptlist, List *qpqual, Index scanrelid, List *values_lists)
 
static TableFuncScanmake_tablefuncscan (List *qptlist, List *qpqual, Index scanrelid, TableFunc *tablefunc)
 
static CteScanmake_ctescan (List *qptlist, List *qpqual, Index scanrelid, int ctePlanId, int cteParam)
 
static NamedTuplestoreScanmake_namedtuplestorescan (List *qptlist, List *qpqual, Index scanrelid, char *enrname)
 
static WorkTableScanmake_worktablescan (List *qptlist, List *qpqual, Index scanrelid, int wtParam)
 
static RecursiveUnionmake_recursive_union (List *tlist, Plan *lefttree, Plan *righttree, int wtParam, List *distinctList, long numGroups)
 
static BitmapAndmake_bitmap_and (List *bitmapplans)
 
static BitmapOrmake_bitmap_or (List *bitmapplans)
 
static NestLoopmake_nestloop (List *tlist, List *joinclauses, List *otherclauses, List *nestParams, Plan *lefttree, Plan *righttree, JoinType jointype, bool inner_unique)
 
static HashJoinmake_hashjoin (List *tlist, List *joinclauses, List *otherclauses, List *hashclauses, List *hashoperators, List *hashcollations, List *hashkeys, Plan *lefttree, Plan *righttree, JoinType jointype, bool inner_unique)
 
static Hashmake_hash (Plan *lefttree, List *hashkeys, Oid skewTable, AttrNumber skewColumn, bool skewInherit)
 
static MergeJoinmake_mergejoin (List *tlist, List *joinclauses, List *otherclauses, List *mergeclauses, Oid *mergefamilies, Oid *mergecollations, int *mergestrategies, bool *mergenullsfirst, Plan *lefttree, Plan *righttree, JoinType jointype, bool inner_unique, bool skip_mark_restore)
 
static Sortmake_sort (Plan *lefttree, int numCols, AttrNumber *sortColIdx, Oid *sortOperators, Oid *collations, bool *nullsFirst)
 
static IncrementalSortmake_incrementalsort (Plan *lefttree, int numCols, int nPresortedCols, AttrNumber *sortColIdx, Oid *sortOperators, Oid *collations, bool *nullsFirst)
 
static Planprepare_sort_from_pathkeys (Plan *lefttree, List *pathkeys, Relids relids, const AttrNumber *reqColIdx, bool adjust_tlist_in_place, int *p_numsortkeys, AttrNumber **p_sortColIdx, Oid **p_sortOperators, Oid **p_collations, bool **p_nullsFirst)
 
static Sortmake_sort_from_pathkeys (Plan *lefttree, List *pathkeys, Relids relids)
 
static IncrementalSortmake_incrementalsort_from_pathkeys (Plan *lefttree, List *pathkeys, Relids relids, int nPresortedCols)
 
static Sortmake_sort_from_groupcols (List *groupcls, AttrNumber *grpColIdx, Plan *lefttree)
 
static Materialmake_material (Plan *lefttree)
 
static ResultCachemake_resultcache (Plan *lefttree, Oid *hashoperators, Oid *collations, List *param_exprs, bool singlerow, uint32 est_entries)
 
static WindowAggmake_windowagg (List *tlist, Index winref, int partNumCols, AttrNumber *partColIdx, Oid *partOperators, Oid *partCollations, int ordNumCols, AttrNumber *ordColIdx, Oid *ordOperators, Oid *ordCollations, int frameOptions, Node *startOffset, Node *endOffset, Oid startInRangeFunc, Oid endInRangeFunc, Oid inRangeColl, bool inRangeAsc, bool inRangeNullsFirst, Plan *lefttree)
 
static Groupmake_group (List *tlist, List *qual, int numGroupCols, AttrNumber *grpColIdx, Oid *grpOperators, Oid *grpCollations, Plan *lefttree)
 
static Uniquemake_unique_from_sortclauses (Plan *lefttree, List *distinctList)
 
static Uniquemake_unique_from_pathkeys (Plan *lefttree, List *pathkeys, int numCols)
 
static Gathermake_gather (List *qptlist, List *qpqual, int nworkers, int rescan_param, bool single_copy, Plan *subplan)
 
static SetOpmake_setop (SetOpCmd cmd, SetOpStrategy strategy, Plan *lefttree, List *distinctList, AttrNumber flagColIdx, int firstFlag, long numGroups)
 
static LockRowsmake_lockrows (Plan *lefttree, List *rowMarks, int epqParam)
 
static Resultmake_result (List *tlist, Node *resconstantqual, Plan *subplan)
 
static ProjectSetmake_project_set (List *tlist, Plan *subplan)
 
static ModifyTablemake_modifytable (PlannerInfo *root, Plan *subplan, CmdType operation, bool canSetTag, Index nominalRelation, Index rootRelation, bool partColsUpdated, List *resultRelations, List *updateColnosLists, List *withCheckOptionLists, List *returningLists, List *rowMarks, OnConflictExpr *onconflict, int epqParam)
 
static GatherMergecreate_gather_merge_plan (PlannerInfo *root, GatherMergePath *best_path)
 
Plancreate_plan (PlannerInfo *root, Path *best_path)
 
Planchange_plan_targetlist (Plan *subplan, List *tlist, bool tlist_parallel_safe)
 
static AttrNumberremap_groupColIdx (PlannerInfo *root, List *groupClause)
 
ForeignScanmake_foreignscan (List *qptlist, List *qpqual, Index scanrelid, List *fdw_exprs, List *fdw_private, List *fdw_scan_tlist, List *fdw_recheck_quals, Plan *outer_plan)
 
Sortmake_sort_from_sortclauses (List *sortcls, Plan *lefttree)
 
Planmaterialize_finished_plan (Plan *subplan)
 
Aggmake_agg (List *tlist, List *qual, AggStrategy aggstrategy, AggSplit aggsplit, int numGroupCols, AttrNumber *grpColIdx, Oid *grpOperators, Oid *grpCollations, List *groupingSets, List *chain, double dNumGroups, Size transitionSpace, Plan *lefttree)
 
Limitmake_limit (Plan *lefttree, Node *limitOffset, Node *limitCount, LimitOption limitOption, int uniqNumCols, AttrNumber *uniqColIdx, Oid *uniqOperators, Oid *uniqCollations)
 
bool is_projection_capable_path (Path *path)
 
bool is_projection_capable_plan (Plan *plan)
 

Macro Definition Documentation

◆ CP_EXACT_TLIST

◆ CP_IGNORE_TLIST

#define CP_IGNORE_TLIST   0x0008 /* caller will replace tlist */

Definition at line 71 of file createplan.c.

Referenced by create_projection_plan(), and create_scan_plan().

◆ CP_LABEL_TLIST

#define CP_LABEL_TLIST   0x0004 /* tlist must contain sortgrouprefs */

◆ CP_SMALL_TLIST

Function Documentation

◆ bitmap_subplan_mark_shared()

static void bitmap_subplan_mark_shared ( Plan plan)
static

Definition at line 5338 of file createplan.c.

References elog, ERROR, IsA, linitial, and nodeTag.

Referenced by create_bitmap_scan_plan().

5339 {
5340  if (IsA(plan, BitmapAnd))
5341  bitmap_subplan_mark_shared(linitial(((BitmapAnd *) plan)->bitmapplans));
5342  else if (IsA(plan, BitmapOr))
5343  {
5344  ((BitmapOr *) plan)->isshared = true;
5345  bitmap_subplan_mark_shared(linitial(((BitmapOr *) plan)->bitmapplans));
5346  }
5347  else if (IsA(plan, BitmapIndexScan))
5348  ((BitmapIndexScan *) plan)->isshared = true;
5349  else
5350  elog(ERROR, "unrecognized node type: %d", nodeTag(plan));
5351 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:590
#define linitial(l)
Definition: pg_list.h:174
#define ERROR
Definition: elog.h:46
static void bitmap_subplan_mark_shared(Plan *plan)
Definition: createplan.c:5338
#define nodeTag(nodeptr)
Definition: nodes.h:544
#define elog(elevel,...)
Definition: elog.h:232

◆ build_path_tlist()

static List * build_path_tlist ( PlannerInfo root,
Path path 
)
static

Definition at line 803 of file createplan.c.

References PathTarget::exprs, lappend(), lfirst, makeTargetEntry(), NIL, Path::param_info, Path::pathtarget, replace_nestloop_params(), TargetEntry::ressortgroupref, and PathTarget::sortgrouprefs.

Referenced by create_agg_plan(), create_append_plan(), create_gather_merge_plan(), create_gather_plan(), create_gating_plan(), create_group_plan(), create_group_result_plan(), create_groupingsets_plan(), create_hashjoin_plan(), create_merge_append_plan(), create_mergejoin_plan(), create_minmaxagg_plan(), create_nestloop_plan(), create_project_set_plan(), create_projection_plan(), create_recursiveunion_plan(), create_scan_plan(), create_unique_plan(), and create_windowagg_plan().

804 {
805  List *tlist = NIL;
806  Index *sortgrouprefs = path->pathtarget->sortgrouprefs;
807  int resno = 1;
808  ListCell *v;
809 
810  foreach(v, path->pathtarget->exprs)
811  {
812  Node *node = (Node *) lfirst(v);
813  TargetEntry *tle;
814 
815  /*
816  * If it's a parameterized path, there might be lateral references in
817  * the tlist, which need to be replaced with Params. There's no need
818  * to remake the TargetEntry nodes, so apply this to each list item
819  * separately.
820  */
821  if (path->param_info)
822  node = replace_nestloop_params(root, node);
823 
824  tle = makeTargetEntry((Expr *) node,
825  resno,
826  NULL,
827  false);
828  if (sortgrouprefs)
829  tle->ressortgroupref = sortgrouprefs[resno - 1];
830 
831  tlist = lappend(tlist, tle);
832  resno++;
833  }
834  return tlist;
835 }
#define NIL
Definition: pg_list.h:65
PathTarget * pathtarget
Definition: pathnodes.h:1175
static Node * replace_nestloop_params(PlannerInfo *root, Node *expr)
Definition: createplan.c:4791
ParamPathInfo * param_info
Definition: pathnodes.h:1177
Definition: nodes.h:539
Index * sortgrouprefs
Definition: pathnodes.h:1103
TargetEntry * makeTargetEntry(Expr *expr, AttrNumber resno, char *resname, bool resjunk)
Definition: makefuncs.c:238
List * lappend(List *list, void *datum)
Definition: list.c:336
List * exprs
Definition: pathnodes.h:1102
unsigned int Index
Definition: c.h:549
#define lfirst(lc)
Definition: pg_list.h:169
Index ressortgroupref
Definition: primnodes.h:1447
Definition: pg_list.h:50

◆ change_plan_targetlist()

Plan* change_plan_targetlist ( Plan subplan,
List tlist,
bool  tlist_parallel_safe 
)

Definition at line 2068 of file createplan.c.

References inject_projection_plan(), is_projection_capable_plan(), Plan::parallel_safe, Plan::targetlist, and tlist_same_exprs().

Referenced by create_unique_plan(), and postgresGetForeignPlan().

2069 {
2070  /*
2071  * If the top plan node can't do projections and its existing target list
2072  * isn't already what we need, we need to add a Result node to help it
2073  * along.
2074  */
2075  if (!is_projection_capable_plan(subplan) &&
2076  !tlist_same_exprs(tlist, subplan->targetlist))
2077  subplan = inject_projection_plan(subplan, tlist,
2078  subplan->parallel_safe &&
2079  tlist_parallel_safe);
2080  else
2081  {
2082  /* Else we can just replace the plan node's tlist */
2083  subplan->targetlist = tlist;
2084  subplan->parallel_safe &= tlist_parallel_safe;
2085  }
2086  return subplan;
2087 }
bool is_projection_capable_plan(Plan *plan)
Definition: createplan.c:7065
static Plan * inject_projection_plan(Plan *subplan, List *tlist, bool parallel_safe)
Definition: createplan.c:2036
bool tlist_same_exprs(List *tlist1, List *tlist2)
Definition: tlist.c:207
List * targetlist
Definition: plannodes.h:141
bool parallel_safe
Definition: plannodes.h:130

◆ copy_generic_path_info()

static void copy_generic_path_info ( Plan dest,
Path src 
)
static

Definition at line 5269 of file createplan.c.

References Plan::parallel_aware, Path::parallel_aware, Plan::parallel_safe, Path::parallel_safe, Path::pathtarget, Plan::plan_rows, Plan::plan_width, Path::rows, Plan::startup_cost, Path::startup_cost, Plan::total_cost, Path::total_cost, and PathTarget::width.

Referenced by create_agg_plan(), create_append_plan(), create_bitmap_scan_plan(), create_ctescan_plan(), create_customscan_plan(), create_foreignscan_plan(), create_functionscan_plan(), create_gather_merge_plan(), create_gather_plan(), create_group_plan(), create_group_result_plan(), create_groupingsets_plan(), create_hashjoin_plan(), create_incrementalsort_plan(), create_indexscan_plan(), create_limit_plan(), create_lockrows_plan(), create_material_plan(), create_merge_append_plan(), create_mergejoin_plan(), create_minmaxagg_plan(), create_modifytable_plan(), create_namedtuplestorescan_plan(), create_nestloop_plan(), create_project_set_plan(), create_projection_plan(), create_recursiveunion_plan(), create_resultcache_plan(), create_resultscan_plan(), create_samplescan_plan(), create_seqscan_plan(), create_setop_plan(), create_sort_plan(), create_subqueryscan_plan(), create_tablefuncscan_plan(), create_tidrangescan_plan(), create_tidscan_plan(), create_unique_plan(), create_upper_unique_plan(), create_valuesscan_plan(), create_windowagg_plan(), and create_worktablescan_plan().

5270 {
5271  dest->startup_cost = src->startup_cost;
5272  dest->total_cost = src->total_cost;
5273  dest->plan_rows = src->rows;
5274  dest->plan_width = src->pathtarget->width;
5275  dest->parallel_aware = src->parallel_aware;
5276  dest->parallel_safe = src->parallel_safe;
5277 }
double plan_rows
Definition: plannodes.h:123
PathTarget * pathtarget
Definition: pathnodes.h:1175
Cost startup_cost
Definition: pathnodes.h:1185
Cost startup_cost
Definition: plannodes.h:117
bool parallel_aware
Definition: plannodes.h:129
Cost total_cost
Definition: pathnodes.h:1186
int plan_width
Definition: plannodes.h:124
double rows
Definition: pathnodes.h:1184
bool parallel_safe
Definition: pathnodes.h:1180
Cost total_cost
Definition: plannodes.h:118
bool parallel_aware
Definition: pathnodes.h:1179
bool parallel_safe
Definition: plannodes.h:130

◆ copy_plan_costsize()

static void copy_plan_costsize ( Plan dest,
Plan src 
)
static

Definition at line 5284 of file createplan.c.

References Plan::parallel_aware, Plan::parallel_safe, Plan::plan_rows, Plan::plan_width, Plan::startup_cost, and Plan::total_cost.

Referenced by create_gating_plan(), create_hashjoin_plan(), create_mergejoin_plan(), and inject_projection_plan().

5285 {
5286  dest->startup_cost = src->startup_cost;
5287  dest->total_cost = src->total_cost;
5288  dest->plan_rows = src->plan_rows;
5289  dest->plan_width = src->plan_width;
5290  /* Assume the inserted node is not parallel-aware. */
5291  dest->parallel_aware = false;
5292  /* Assume the inserted node is parallel-safe, if child plan is. */
5293  dest->parallel_safe = src->parallel_safe;
5294 }
double plan_rows
Definition: plannodes.h:123
Cost startup_cost
Definition: plannodes.h:117
bool parallel_aware
Definition: plannodes.h:129
int plan_width
Definition: plannodes.h:124
Cost total_cost
Definition: plannodes.h:118
bool parallel_safe
Definition: plannodes.h:130

◆ create_agg_plan()

static Agg * create_agg_plan ( PlannerInfo root,
AggPath best_path 
)
static

Definition at line 2224 of file createplan.c.

References AggPath::aggsplit, AggPath::aggstrategy, build_path_tlist(), copy_generic_path_info(), CP_LABEL_TLIST, create_plan_recurse(), extract_grouping_collations(), extract_grouping_cols(), extract_grouping_ops(), AggPath::groupClause, list_length(), make_agg(), NIL, AggPath::numGroups, order_qual_clauses(), AggPath::path, Agg::plan, AggPath::qual, AggPath::subpath, Plan::targetlist, and AggPath::transitionSpace.

Referenced by create_plan_recurse().

2225 {
2226  Agg *plan;
2227  Plan *subplan;
2228  List *tlist;
2229  List *quals;
2230 
2231  /*
2232  * Agg can project, so no need to be terribly picky about child tlist, but
2233  * we do need grouping columns to be available
2234  */
2235  subplan = create_plan_recurse(root, best_path->subpath, CP_LABEL_TLIST);
2236 
2237  tlist = build_path_tlist(root, &best_path->path);
2238 
2239  quals = order_qual_clauses(root, best_path->qual);
2240 
2241  plan = make_agg(tlist, quals,
2242  best_path->aggstrategy,
2243  best_path->aggsplit,
2244  list_length(best_path->groupClause),
2246  subplan->targetlist),
2247  extract_grouping_ops(best_path->groupClause),
2249  subplan->targetlist),
2250  NIL,
2251  NIL,
2252  best_path->numGroups,
2253  best_path->transitionSpace,
2254  subplan);
2255 
2256  copy_generic_path_info(&plan->plan, (Path *) best_path);
2257 
2258  return plan;
2259 }
#define NIL
Definition: pg_list.h:65
AggStrategy aggstrategy
Definition: pathnodes.h:1760
Oid * extract_grouping_collations(List *groupClause, List *tlist)
Definition: tlist.c:478
List * qual
Definition: pathnodes.h:1765
static List * order_qual_clauses(PlannerInfo *root, List *clauses)
Definition: createplan.c:5175
AggSplit aggsplit
Definition: pathnodes.h:1761
Oid * extract_grouping_ops(List *groupClause)
Definition: tlist.c:452
double numGroups
Definition: pathnodes.h:1762
AttrNumber * extract_grouping_cols(List *groupClause, List *tlist)
Definition: tlist.c:503
static Plan * create_plan_recurse(PlannerInfo *root, Path *best_path, int flags)
Definition: createplan.c:385
static void copy_generic_path_info(Plan *dest, Path *src)
Definition: createplan.c:5269
Agg * make_agg(List *tlist, List *qual, AggStrategy aggstrategy, AggSplit aggsplit, int numGroupCols, AttrNumber *grpColIdx, Oid *grpOperators, Oid *grpCollations, List *groupingSets, List *chain, double dNumGroups, Size transitionSpace, Plan *lefttree)
Definition: createplan.c:6441
static List * build_path_tlist(PlannerInfo *root, Path *path)
Definition: createplan.c:803
List * groupClause
Definition: pathnodes.h:1764
Plan plan
Definition: plannodes.h:858
#define CP_LABEL_TLIST
Definition: createplan.c:70
uint64 transitionSpace
Definition: pathnodes.h:1763
static int list_length(const List *l)
Definition: pg_list.h:149
Path * subpath
Definition: pathnodes.h:1759
List * targetlist
Definition: plannodes.h:141
Definition: plannodes.h:856
Definition: pg_list.h:50
Path path
Definition: pathnodes.h:1758

◆ create_append_plan()

static Plan * create_append_plan ( PlannerInfo root,
AppendPath best_path,
int  flags 
)
static

Definition at line 1128 of file createplan.c.

References Append::appendplans, Append::apprelids, Assert, Plan::async_capable, RelOptInfo::baserestrictinfo, build_path_tlist(), copy_generic_path_info(), CP_EXACT_TLIST, CP_SMALL_TLIST, create_plan_recurse(), elog, enable_async_append, enable_partition_pruning, ERROR, extract_actual_clauses(), AppendPath::first_partial_path, Append::first_partial_plan, inject_projection_plan(), is_async_capable_path(), label_sort_with_costsize(), lappend(), Plan::lefttree, lfirst, AppendPath::limit_tuples, list_concat(), list_copy(), list_length(), list_make1, list_truncate(), make_partition_pruneinfo(), make_result(), make_sort(), makeBoolConst(), makeNode, Append::nasyncplans, NIL, Plan::parallel_safe, Path::parallel_safe, Path::param_info, Path::parent, Append::part_prune_info, AppendPath::path, Path::pathkeys, pathkeys_contained_in(), Append::plan, ParamPathInfo::ppi_clauses, prepare_sort_from_pathkeys(), Plan::qual, RelOptInfo::relids, replace_nestloop_params(), Plan::righttree, sort(), subpath(), AppendPath::subpaths, and Plan::targetlist.

Referenced by create_plan_recurse().

1129 {
1130  Append *plan;
1131  List *tlist = build_path_tlist(root, &best_path->path);
1132  int orig_tlist_length = list_length(tlist);
1133  bool tlist_was_changed = false;
1134  List *pathkeys = best_path->path.pathkeys;
1135  List *subplans = NIL;
1136  ListCell *subpaths;
1137  int nasyncplans = 0;
1138  RelOptInfo *rel = best_path->path.parent;
1139  PartitionPruneInfo *partpruneinfo = NULL;
1140  int nodenumsortkeys = 0;
1141  AttrNumber *nodeSortColIdx = NULL;
1142  Oid *nodeSortOperators = NULL;
1143  Oid *nodeCollations = NULL;
1144  bool *nodeNullsFirst = NULL;
1145  bool consider_async = false;
1146 
1147  /*
1148  * The subpaths list could be empty, if every child was proven empty by
1149  * constraint exclusion. In that case generate a dummy plan that returns
1150  * no rows.
1151  *
1152  * Note that an AppendPath with no members is also generated in certain
1153  * cases where there was no appending construct at all, but we know the
1154  * relation is empty (see set_dummy_rel_pathlist and mark_dummy_rel).
1155  */
1156  if (best_path->subpaths == NIL)
1157  {
1158  /* Generate a Result plan with constant-FALSE gating qual */
1159  Plan *plan;
1160 
1161  plan = (Plan *) make_result(tlist,
1162  (Node *) list_make1(makeBoolConst(false,
1163  false)),
1164  NULL);
1165 
1166  copy_generic_path_info(plan, (Path *) best_path);
1167 
1168  return plan;
1169  }
1170 
1171  /*
1172  * Otherwise build an Append plan. Note that if there's just one child,
1173  * the Append is pretty useless; but we wait till setrefs.c to get rid of
1174  * it. Doing so here doesn't work because the varno of the child scan
1175  * plan won't match the parent-rel Vars it'll be asked to emit.
1176  *
1177  * We don't have the actual creation of the Append node split out into a
1178  * separate make_xxx function. This is because we want to run
1179  * prepare_sort_from_pathkeys on it before we do so on the individual
1180  * child plans, to make cross-checking the sort info easier.
1181  */
1182  plan = makeNode(Append);
1183  plan->plan.targetlist = tlist;
1184  plan->plan.qual = NIL;
1185  plan->plan.lefttree = NULL;
1186  plan->plan.righttree = NULL;
1187  plan->apprelids = rel->relids;
1188 
1189  if (pathkeys != NIL)
1190  {
1191  /*
1192  * Compute sort column info, and adjust the Append's tlist as needed.
1193  * Because we pass adjust_tlist_in_place = true, we may ignore the
1194  * function result; it must be the same plan node. However, we then
1195  * need to detect whether any tlist entries were added.
1196  */
1197  (void) prepare_sort_from_pathkeys((Plan *) plan, pathkeys,
1198  best_path->path.parent->relids,
1199  NULL,
1200  true,
1201  &nodenumsortkeys,
1202  &nodeSortColIdx,
1203  &nodeSortOperators,
1204  &nodeCollations,
1205  &nodeNullsFirst);
1206  tlist_was_changed = (orig_tlist_length != list_length(plan->plan.targetlist));
1207  }
1208 
1209  /* If appropriate, consider async append */
1210  consider_async = (enable_async_append && pathkeys == NIL &&
1211  !best_path->path.parallel_safe &&
1212  list_length(best_path->subpaths) > 1);
1213 
1214  /* Build the plan for each child */
1215  foreach(subpaths, best_path->subpaths)
1216  {
1217  Path *subpath = (Path *) lfirst(subpaths);
1218  Plan *subplan;
1219 
1220  /* Must insist that all children return the same tlist */
1221  subplan = create_plan_recurse(root, subpath, CP_EXACT_TLIST);
1222 
1223  /*
1224  * For ordered Appends, we must insert a Sort node if subplan isn't
1225  * sufficiently ordered.
1226  */
1227  if (pathkeys != NIL)
1228  {
1229  int numsortkeys;
1230  AttrNumber *sortColIdx;
1231  Oid *sortOperators;
1232  Oid *collations;
1233  bool *nullsFirst;
1234 
1235  /*
1236  * Compute sort column info, and adjust subplan's tlist as needed.
1237  * We must apply prepare_sort_from_pathkeys even to subplans that
1238  * don't need an explicit sort, to make sure they are returning
1239  * the same sort key columns the Append expects.
1240  */
1241  subplan = prepare_sort_from_pathkeys(subplan, pathkeys,
1242  subpath->parent->relids,
1243  nodeSortColIdx,
1244  false,
1245  &numsortkeys,
1246  &sortColIdx,
1247  &sortOperators,
1248  &collations,
1249  &nullsFirst);
1250 
1251  /*
1252  * Check that we got the same sort key information. We just
1253  * Assert that the sortops match, since those depend only on the
1254  * pathkeys; but it seems like a good idea to check the sort
1255  * column numbers explicitly, to ensure the tlists match up.
1256  */
1257  Assert(numsortkeys == nodenumsortkeys);
1258  if (memcmp(sortColIdx, nodeSortColIdx,
1259  numsortkeys * sizeof(AttrNumber)) != 0)
1260  elog(ERROR, "Append child's targetlist doesn't match Append");
1261  Assert(memcmp(sortOperators, nodeSortOperators,
1262  numsortkeys * sizeof(Oid)) == 0);
1263  Assert(memcmp(collations, nodeCollations,
1264  numsortkeys * sizeof(Oid)) == 0);
1265  Assert(memcmp(nullsFirst, nodeNullsFirst,
1266  numsortkeys * sizeof(bool)) == 0);
1267 
1268  /* Now, insert a Sort node if subplan isn't sufficiently ordered */
1269  if (!pathkeys_contained_in(pathkeys, subpath->pathkeys))
1270  {
1271  Sort *sort = make_sort(subplan, numsortkeys,
1272  sortColIdx, sortOperators,
1273  collations, nullsFirst);
1274 
1275  label_sort_with_costsize(root, sort, best_path->limit_tuples);
1276  subplan = (Plan *) sort;
1277  }
1278  }
1279 
1280  subplans = lappend(subplans, subplan);
1281 
1282  /* Check to see if subplan can be executed asynchronously */
1283  if (consider_async && is_async_capable_path(subpath))
1284  {
1285  subplan->async_capable = true;
1286  ++nasyncplans;
1287  }
1288  }
1289 
1290  /*
1291  * If any quals exist, they may be useful to perform further partition
1292  * pruning during execution. Gather information needed by the executor to
1293  * do partition pruning.
1294  */
1296  {
1297  List *prunequal;
1298 
1299  prunequal = extract_actual_clauses(rel->baserestrictinfo, false);
1300 
1301  if (best_path->path.param_info)
1302  {
1303  List *prmquals = best_path->path.param_info->ppi_clauses;
1304 
1305  prmquals = extract_actual_clauses(prmquals, false);
1306  prmquals = (List *) replace_nestloop_params(root,
1307  (Node *) prmquals);
1308 
1309  prunequal = list_concat(prunequal, prmquals);
1310  }
1311 
1312  if (prunequal != NIL)
1313  partpruneinfo =
1314  make_partition_pruneinfo(root, rel,
1315  best_path->subpaths,
1316  prunequal);
1317  }
1318 
1319  plan->appendplans = subplans;
1320  plan->nasyncplans = nasyncplans;
1321  plan->first_partial_plan = best_path->first_partial_path;
1322  plan->part_prune_info = partpruneinfo;
1323 
1324  copy_generic_path_info(&plan->plan, (Path *) best_path);
1325 
1326  /*
1327  * If prepare_sort_from_pathkeys added sort columns, but we were told to
1328  * produce either the exact tlist or a narrow tlist, we should get rid of
1329  * the sort columns again. We must inject a projection node to do so.
1330  */
1331  if (tlist_was_changed && (flags & (CP_EXACT_TLIST | CP_SMALL_TLIST)))
1332  {
1333  tlist = list_truncate(list_copy(plan->plan.targetlist),
1334  orig_tlist_length);
1335  return inject_projection_plan((Plan *) plan, tlist,
1336  plan->plan.parallel_safe);
1337  }
1338  else
1339  return (Plan *) plan;
1340 }
#define NIL
Definition: pg_list.h:65
List * qual
Definition: plannodes.h:142
static Node * replace_nestloop_params(PlannerInfo *root, Node *expr)
Definition: createplan.c:4791
double limit_tuples
Definition: pathnodes.h:1447
List * baserestrictinfo
Definition: pathnodes.h:740
List * list_truncate(List *list, int new_size)
Definition: list.c:600
ParamPathInfo * param_info
Definition: pathnodes.h:1177
#define CP_SMALL_TLIST
Definition: createplan.c:69
List * list_copy(const List *oldlist)
Definition: list.c:1418
Definition: nodes.h:539
List * list_concat(List *list1, const List *list2)
Definition: list.c:530
unsigned int Oid
Definition: postgres_ext.h:31
int first_partial_path
Definition: pathnodes.h:1446
#define list_make1(x1)
Definition: pg_list.h:206
List * subpaths
Definition: pathnodes.h:1444
bool async_capable
Definition: plannodes.h:135
static Plan * create_plan_recurse(PlannerInfo *root, Path *best_path, int flags)
Definition: createplan.c:385
struct Plan * righttree
Definition: plannodes.h:144
static void copy_generic_path_info(Plan *dest, Path *src)
Definition: createplan.c:5269
#define ERROR
Definition: elog.h:46
static List * build_path_tlist(PlannerInfo *root, Path *path)
Definition: createplan.c:803
Node * makeBoolConst(bool value, bool isnull)
Definition: makefuncs.c:357
RelOptInfo * parent
Definition: pathnodes.h:1174
Datum sort(PG_FUNCTION_ARGS)
Definition: _int_op.c:195
Relids relids
Definition: pathnodes.h:676
bool enable_async_append
Definition: costsize.c:152
static Result * make_result(List *tlist, Node *resconstantqual, Plan *subplan)
Definition: createplan.c:6833
List * lappend(List *list, void *datum)
Definition: list.c:336
bool pathkeys_contained_in(List *keys1, List *keys2)
Definition: pathkeys.c:324
bool enable_partition_pruning
Definition: costsize.c:151
List * pathkeys
Definition: pathnodes.h:1188
static Sort * make_sort(Plan *lefttree, int numCols, AttrNumber *sortColIdx, Oid *sortOperators, Oid *collations, bool *nullsFirst)
Definition: createplan.c:5923
#define makeNode(_type_)
Definition: nodes.h:587
#define Assert(condition)
Definition: c.h:804
#define lfirst(lc)
Definition: pg_list.h:169
bool parallel_safe
Definition: pathnodes.h:1180
List * ppi_clauses
Definition: pathnodes.h:1135
static Plan * inject_projection_plan(Plan *subplan, List *tlist, bool parallel_safe)
Definition: createplan.c:2036
static int list_length(const List *l)
Definition: pg_list.h:149
List * extract_actual_clauses(List *restrictinfo_list, bool pseudoconstant)
Definition: restrictinfo.c:443
struct Plan * lefttree
Definition: plannodes.h:143
static bool is_async_capable_path(Path *path)
Definition: createplan.c:1100
List * targetlist
Definition: plannodes.h:141
PartitionPruneInfo * make_partition_pruneinfo(PlannerInfo *root, RelOptInfo *parentrel, List *subpaths, List *prunequal)
Definition: partprune.c:222
#define elog(elevel,...)
Definition: elog.h:232
bool parallel_safe
Definition: plannodes.h:130
#define CP_EXACT_TLIST
Definition: createplan.c:68
Definition: pg_list.h:50
int16 AttrNumber
Definition: attnum.h:21
static void label_sort_with_costsize(PlannerInfo *root, Sort *plan, double limit_tuples)
Definition: createplan.c:5306
Datum subpath(PG_FUNCTION_ARGS)
Definition: ltree_op.c:241
static Plan * prepare_sort_from_pathkeys(Plan *lefttree, List *pathkeys, Relids relids, const AttrNumber *reqColIdx, bool adjust_tlist_in_place, int *p_numsortkeys, AttrNumber **p_sortColIdx, Oid **p_sortOperators, Oid **p_collations, bool **p_nullsFirst)
Definition: createplan.c:6019

◆ create_bitmap_scan_plan()

static BitmapHeapScan * create_bitmap_scan_plan ( PlannerInfo root,
BitmapHeapPath best_path,
List tlist,
List scan_clauses 
)
static

Definition at line 3094 of file createplan.c.

References Assert, bitmap_subplan_mark_shared(), BitmapHeapPath::bitmapqual, RestrictInfo::clause, contain_mutable_functions(), copy_generic_path_info(), create_bitmap_subplan(), extract_actual_clauses(), lappend(), lfirst_node, list_difference_ptr(), list_make1, list_member(), list_member_ptr(), make_bitmap_heapscan(), NIL, order_qual_clauses(), Path::parallel_aware, Path::param_info, Path::parent, RestrictInfo::parent_ec, BitmapHeapPath::path, Scan::plan, predicate_implied_by(), RestrictInfo::pseudoconstant, RelOptInfo::relid, replace_nestloop_params(), RTE_RELATION, RelOptInfo::rtekind, and BitmapHeapScan::scan.

Referenced by create_scan_plan().

3098 {
3099  Index baserelid = best_path->path.parent->relid;
3100  Plan *bitmapqualplan;
3101  List *bitmapqualorig;
3102  List *indexquals;
3103  List *indexECs;
3104  List *qpqual;
3105  ListCell *l;
3106  BitmapHeapScan *scan_plan;
3107 
3108  /* it should be a base rel... */
3109  Assert(baserelid > 0);
3110  Assert(best_path->path.parent->rtekind == RTE_RELATION);
3111 
3112  /* Process the bitmapqual tree into a Plan tree and qual lists */
3113  bitmapqualplan = create_bitmap_subplan(root, best_path->bitmapqual,
3114  &bitmapqualorig, &indexquals,
3115  &indexECs);
3116 
3117  if (best_path->path.parallel_aware)
3118  bitmap_subplan_mark_shared(bitmapqualplan);
3119 
3120  /*
3121  * The qpqual list must contain all restrictions not automatically handled
3122  * by the index, other than pseudoconstant clauses which will be handled
3123  * by a separate gating plan node. All the predicates in the indexquals
3124  * will be checked (either by the index itself, or by
3125  * nodeBitmapHeapscan.c), but if there are any "special" operators
3126  * involved then they must be added to qpqual. The upshot is that qpqual
3127  * must contain scan_clauses minus whatever appears in indexquals.
3128  *
3129  * This loop is similar to the comparable code in create_indexscan_plan(),
3130  * but with some differences because it has to compare the scan clauses to
3131  * stripped (no RestrictInfos) indexquals. See comments there for more
3132  * info.
3133  *
3134  * In normal cases simple equal() checks will be enough to spot duplicate
3135  * clauses, so we try that first. We next see if the scan clause is
3136  * redundant with any top-level indexqual by virtue of being generated
3137  * from the same EC. After that, try predicate_implied_by().
3138  *
3139  * Unlike create_indexscan_plan(), the predicate_implied_by() test here is
3140  * useful for getting rid of qpquals that are implied by index predicates,
3141  * because the predicate conditions are included in the "indexquals"
3142  * returned by create_bitmap_subplan(). Bitmap scans have to do it that
3143  * way because predicate conditions need to be rechecked if the scan
3144  * becomes lossy, so they have to be included in bitmapqualorig.
3145  */
3146  qpqual = NIL;
3147  foreach(l, scan_clauses)
3148  {
3149  RestrictInfo *rinfo = lfirst_node(RestrictInfo, l);
3150  Node *clause = (Node *) rinfo->clause;
3151 
3152  if (rinfo->pseudoconstant)
3153  continue; /* we may drop pseudoconstants here */
3154  if (list_member(indexquals, clause))
3155  continue; /* simple duplicate */
3156  if (rinfo->parent_ec && list_member_ptr(indexECs, rinfo->parent_ec))
3157  continue; /* derived from same EquivalenceClass */
3158  if (!contain_mutable_functions(clause) &&
3159  predicate_implied_by(list_make1(clause), indexquals, false))
3160  continue; /* provably implied by indexquals */
3161  qpqual = lappend(qpqual, rinfo);
3162  }
3163 
3164  /* Sort clauses into best execution order */
3165  qpqual = order_qual_clauses(root, qpqual);
3166 
3167  /* Reduce RestrictInfo list to bare expressions; ignore pseudoconstants */
3168  qpqual = extract_actual_clauses(qpqual, false);
3169 
3170  /*
3171  * When dealing with special operators, we will at this point have
3172  * duplicate clauses in qpqual and bitmapqualorig. We may as well drop
3173  * 'em from bitmapqualorig, since there's no point in making the tests
3174  * twice.
3175  */
3176  bitmapqualorig = list_difference_ptr(bitmapqualorig, qpqual);
3177 
3178  /*
3179  * We have to replace any outer-relation variables with nestloop params in
3180  * the qpqual and bitmapqualorig expressions. (This was already done for
3181  * expressions attached to plan nodes in the bitmapqualplan tree.)
3182  */
3183  if (best_path->path.param_info)
3184  {
3185  qpqual = (List *)
3186  replace_nestloop_params(root, (Node *) qpqual);
3187  bitmapqualorig = (List *)
3188  replace_nestloop_params(root, (Node *) bitmapqualorig);
3189  }
3190 
3191  /* Finally ready to build the plan node */
3192  scan_plan = make_bitmap_heapscan(tlist,
3193  qpqual,
3194  bitmapqualplan,
3195  bitmapqualorig,
3196  baserelid);
3197 
3198  copy_generic_path_info(&scan_plan->scan.plan, &best_path->path);
3199 
3200  return scan_plan;
3201 }
#define NIL
Definition: pg_list.h:65
Plan plan
Definition: plannodes.h:342
static Node * replace_nestloop_params(PlannerInfo *root, Node *expr)
Definition: createplan.c:4791
List * list_difference_ptr(const List *list1, const List *list2)
Definition: list.c:1117
bool pseudoconstant
Definition: pathnodes.h:2053
ParamPathInfo * param_info
Definition: pathnodes.h:1177
Definition: nodes.h:539
static List * order_qual_clauses(PlannerInfo *root, List *clauses)
Definition: createplan.c:5175
static Plan * create_bitmap_subplan(PlannerInfo *root, Path *bitmapqual, List **qual, List **indexqual, List **indexECs)
Definition: createplan.c:3224
#define list_make1(x1)
Definition: pg_list.h:206
static BitmapHeapScan * make_bitmap_heapscan(List *qptlist, List *qpqual, Plan *lefttree, List *bitmapqualorig, Index scanrelid)
Definition: createplan.c:5483
static void copy_generic_path_info(Plan *dest, Path *src)
Definition: createplan.c:5269
bool list_member(const List *list, const void *datum)
Definition: list.c:628
EquivalenceClass * parent_ec
Definition: pathnodes.h:2082
RelOptInfo * parent
Definition: pathnodes.h:1174
Path * bitmapqual
Definition: pathnodes.h:1310
#define lfirst_node(type, lc)
Definition: pg_list.h:172
Index relid
Definition: pathnodes.h:704
List * lappend(List *list, void *datum)
Definition: list.c:336
static void bitmap_subplan_mark_shared(Plan *plan)
Definition: createplan.c:5338
Expr * clause
Definition: pathnodes.h:2045
unsigned int Index
Definition: c.h:549
RTEKind rtekind
Definition: pathnodes.h:706
bool list_member_ptr(const List *list, const void *datum)
Definition: list.c:649
#define Assert(condition)
Definition: c.h:804
List * extract_actual_clauses(List *restrictinfo_list, bool pseudoconstant)
Definition: restrictinfo.c:443
bool contain_mutable_functions(Node *clause)
Definition: clauses.c:359
bool parallel_aware
Definition: pathnodes.h:1179
bool predicate_implied_by(List *predicate_list, List *clause_list, bool weak)
Definition: predtest.c:151
Definition: pg_list.h:50

◆ create_bitmap_subplan()

static Plan * create_bitmap_subplan ( PlannerInfo root,
Path bitmapqual,
List **  qual,
List **  indexqual,
List **  indexECs 
)
static

Definition at line 3224 of file createplan.c.

References Assert, BitmapAndPath::bitmapquals, BitmapOrPath::bitmapquals, BitmapAndPath::bitmapselectivity, BitmapOrPath::bitmapselectivity, castNode, clamp_row_est(), RestrictInfo::clause, create_indexscan_plan(), elog, ERROR, get_actual_clauses(), IndexPath::indexclauses, IndexScan::indexid, IndexPath::indexinfo, IndexScan::indexqual, IndexScan::indexqualorig, IndexClause::indexquals, IndexPath::indexselectivity, IndexPath::indextotalcost, IndexOptInfo::indpred, IsA, lappend(), lfirst, linitial, list_concat(), list_concat_unique(), list_length(), list_make1, make_ands_explicit(), make_bitmap_and(), make_bitmap_indexscan(), make_bitmap_or(), make_orclause(), NIL, nodeTag, Plan::parallel_aware, Plan::parallel_safe, Path::parallel_safe, Path::parent, RestrictInfo::parent_ec, IndexPath::path, BitmapAndPath::path, BitmapOrPath::path, Plan::plan_rows, Plan::plan_width, predicate_implied_by(), RestrictInfo::pseudoconstant, IndexClause::rinfo, IndexScan::scan, Scan::scanrelid, Plan::startup_cost, Path::startup_cost, Plan::total_cost, Path::total_cost, and RelOptInfo::tuples.

Referenced by create_bitmap_scan_plan().

3226 {
3227  Plan *plan;
3228 
3229  if (IsA(bitmapqual, BitmapAndPath))
3230  {
3231  BitmapAndPath *apath = (BitmapAndPath *) bitmapqual;
3232  List *subplans = NIL;
3233  List *subquals = NIL;
3234  List *subindexquals = NIL;
3235  List *subindexECs = NIL;
3236  ListCell *l;
3237 
3238  /*
3239  * There may well be redundant quals among the subplans, since a
3240  * top-level WHERE qual might have gotten used to form several
3241  * different index quals. We don't try exceedingly hard to eliminate
3242  * redundancies, but we do eliminate obvious duplicates by using
3243  * list_concat_unique.
3244  */
3245  foreach(l, apath->bitmapquals)
3246  {
3247  Plan *subplan;
3248  List *subqual;
3249  List *subindexqual;
3250  List *subindexEC;
3251 
3252  subplan = create_bitmap_subplan(root, (Path *) lfirst(l),
3253  &subqual, &subindexqual,
3254  &subindexEC);
3255  subplans = lappend(subplans, subplan);
3256  subquals = list_concat_unique(subquals, subqual);
3257  subindexquals = list_concat_unique(subindexquals, subindexqual);
3258  /* Duplicates in indexECs aren't worth getting rid of */
3259  subindexECs = list_concat(subindexECs, subindexEC);
3260  }
3261  plan = (Plan *) make_bitmap_and(subplans);
3262  plan->startup_cost = apath->path.startup_cost;
3263  plan->total_cost = apath->path.total_cost;
3264  plan->plan_rows =
3265  clamp_row_est(apath->bitmapselectivity * apath->path.parent->tuples);
3266  plan->plan_width = 0; /* meaningless */
3267  plan->parallel_aware = false;
3268  plan->parallel_safe = apath->path.parallel_safe;
3269  *qual = subquals;
3270  *indexqual = subindexquals;
3271  *indexECs = subindexECs;
3272  }
3273  else if (IsA(bitmapqual, BitmapOrPath))
3274  {
3275  BitmapOrPath *opath = (BitmapOrPath *) bitmapqual;
3276  List *subplans = NIL;
3277  List *subquals = NIL;
3278  List *subindexquals = NIL;
3279  bool const_true_subqual = false;
3280  bool const_true_subindexqual = false;
3281  ListCell *l;
3282 
3283  /*
3284  * Here, we only detect qual-free subplans. A qual-free subplan would
3285  * cause us to generate "... OR true ..." which we may as well reduce
3286  * to just "true". We do not try to eliminate redundant subclauses
3287  * because (a) it's not as likely as in the AND case, and (b) we might
3288  * well be working with hundreds or even thousands of OR conditions,
3289  * perhaps from a long IN list. The performance of list_append_unique
3290  * would be unacceptable.
3291  */
3292  foreach(l, opath->bitmapquals)
3293  {
3294  Plan *subplan;
3295  List *subqual;
3296  List *subindexqual;
3297  List *subindexEC;
3298 
3299  subplan = create_bitmap_subplan(root, (Path *) lfirst(l),
3300  &subqual, &subindexqual,
3301  &subindexEC);
3302  subplans = lappend(subplans, subplan);
3303  if (subqual == NIL)
3304  const_true_subqual = true;
3305  else if (!const_true_subqual)
3306  subquals = lappend(subquals,
3307  make_ands_explicit(subqual));
3308  if (subindexqual == NIL)
3309  const_true_subindexqual = true;
3310  else if (!const_true_subindexqual)
3311  subindexquals = lappend(subindexquals,
3312  make_ands_explicit(subindexqual));
3313  }
3314 
3315  /*
3316  * In the presence of ScalarArrayOpExpr quals, we might have built
3317  * BitmapOrPaths with just one subpath; don't add an OR step.
3318  */
3319  if (list_length(subplans) == 1)
3320  {
3321  plan = (Plan *) linitial(subplans);
3322  }
3323  else
3324  {
3325  plan = (Plan *) make_bitmap_or(subplans);
3326  plan->startup_cost = opath->path.startup_cost;
3327  plan->total_cost = opath->path.total_cost;
3328  plan->plan_rows =
3329  clamp_row_est(opath->bitmapselectivity * opath->path.parent->tuples);
3330  plan->plan_width = 0; /* meaningless */
3331  plan->parallel_aware = false;
3332  plan->parallel_safe = opath->path.parallel_safe;
3333  }
3334 
3335  /*
3336  * If there were constant-TRUE subquals, the OR reduces to constant
3337  * TRUE. Also, avoid generating one-element ORs, which could happen
3338  * due to redundancy elimination or ScalarArrayOpExpr quals.
3339  */
3340  if (const_true_subqual)
3341  *qual = NIL;
3342  else if (list_length(subquals) <= 1)
3343  *qual = subquals;
3344  else
3345  *qual = list_make1(make_orclause(subquals));
3346  if (const_true_subindexqual)
3347  *indexqual = NIL;
3348  else if (list_length(subindexquals) <= 1)
3349  *indexqual = subindexquals;
3350  else
3351  *indexqual = list_make1(make_orclause(subindexquals));
3352  *indexECs = NIL;
3353  }
3354  else if (IsA(bitmapqual, IndexPath))
3355  {
3356  IndexPath *ipath = (IndexPath *) bitmapqual;
3357  IndexScan *iscan;
3358  List *subquals;
3359  List *subindexquals;
3360  List *subindexECs;
3361  ListCell *l;
3362 
3363  /* Use the regular indexscan plan build machinery... */
3364  iscan = castNode(IndexScan,
3365  create_indexscan_plan(root, ipath,
3366  NIL, NIL, false));
3367  /* then convert to a bitmap indexscan */
3368  plan = (Plan *) make_bitmap_indexscan(iscan->scan.scanrelid,
3369  iscan->indexid,
3370  iscan->indexqual,
3371  iscan->indexqualorig);
3372  /* and set its cost/width fields appropriately */
3373  plan->startup_cost = 0.0;
3374  plan->total_cost = ipath->indextotalcost;
3375  plan->plan_rows =
3376  clamp_row_est(ipath->indexselectivity * ipath->path.parent->tuples);
3377  plan->plan_width = 0; /* meaningless */
3378  plan->parallel_aware = false;
3379  plan->parallel_safe = ipath->path.parallel_safe;
3380  /* Extract original index clauses, actual index quals, relevant ECs */
3381  subquals = NIL;
3382  subindexquals = NIL;
3383  subindexECs = NIL;
3384  foreach(l, ipath->indexclauses)
3385  {
3386  IndexClause *iclause = (IndexClause *) lfirst(l);
3387  RestrictInfo *rinfo = iclause->rinfo;
3388 
3389  Assert(!rinfo->pseudoconstant);
3390  subquals = lappend(subquals, rinfo->clause);
3391  subindexquals = list_concat(subindexquals,
3392  get_actual_clauses(iclause->indexquals));
3393  if (rinfo->parent_ec)
3394  subindexECs = lappend(subindexECs, rinfo->parent_ec);
3395  }
3396  /* We can add any index predicate conditions, too */
3397  foreach(l, ipath->indexinfo->indpred)
3398  {
3399  Expr *pred = (Expr *) lfirst(l);
3400 
3401  /*
3402  * We know that the index predicate must have been implied by the
3403  * query condition as a whole, but it may or may not be implied by
3404  * the conditions that got pushed into the bitmapqual. Avoid
3405  * generating redundant conditions.
3406  */
3407  if (!predicate_implied_by(list_make1(pred), subquals, false))
3408  {
3409  subquals = lappend(subquals, pred);
3410  subindexquals = lappend(subindexquals, pred);
3411  }
3412  }
3413  *qual = subquals;
3414  *indexqual = subindexquals;
3415  *indexECs = subindexECs;
3416  }
3417  else
3418  {
3419  elog(ERROR, "unrecognized node type: %d", nodeTag(bitmapqual));
3420  plan = NULL; /* keep compiler quiet */
3421  }
3422 
3423  return plan;
3424 }
#define NIL
Definition: pg_list.h:65
double plan_rows
Definition: plannodes.h:123
#define IsA(nodeptr, _type_)
Definition: nodes.h:590
Path path
Definition: pathnodes.h:1236
IndexOptInfo * indexinfo
Definition: pathnodes.h:1237
Index scanrelid
Definition: plannodes.h:343
#define castNode(_type_, nodeptr)
Definition: nodes.h:608
double tuples
Definition: pathnodes.h:716
bool pseudoconstant
Definition: pathnodes.h:2053
List * indexqualorig
Definition: plannodes.h:405
List * get_actual_clauses(List *restrictinfo_list)
Definition: restrictinfo.c:420
List * list_concat(List *list1, const List *list2)
Definition: list.c:530
List * indexclauses
Definition: pathnodes.h:1238
static Plan * create_bitmap_subplan(PlannerInfo *root, Path *bitmapqual, List **qual, List **indexqual, List **indexECs)
Definition: createplan.c:3224
Selectivity bitmapselectivity
Definition: pathnodes.h:1323
Expr * make_orclause(List *orclauses)
Definition: makefuncs.c:652
static BitmapAnd * make_bitmap_and(List *bitmapplans)
Definition: createplan.c:5773
Oid indexid
Definition: plannodes.h:403
List * bitmapquals
Definition: pathnodes.h:1322
List * bitmapquals
Definition: pathnodes.h:1335
#define list_make1(x1)
Definition: pg_list.h:206
#define linitial(l)
Definition: pg_list.h:174
#define ERROR
Definition: elog.h:46
Cost indextotalcost
Definition: pathnodes.h:1242
Cost startup_cost
Definition: pathnodes.h:1185
Scan scan
Definition: plannodes.h:402
EquivalenceClass * parent_ec
Definition: pathnodes.h:2082
RelOptInfo * parent
Definition: pathnodes.h:1174
Selectivity indexselectivity
Definition: pathnodes.h:1243
struct RestrictInfo * rinfo
Definition: pathnodes.h:1283
Cost startup_cost
Definition: plannodes.h:117
bool parallel_aware
Definition: plannodes.h:129
Selectivity bitmapselectivity
Definition: pathnodes.h:1336
List * indexqual
Definition: plannodes.h:404
List * indexquals
Definition: pathnodes.h:1284
List * lappend(List *list, void *datum)
Definition: list.c:336
Expr * clause
Definition: pathnodes.h:2045
Expr * make_ands_explicit(List *andclauses)
Definition: makefuncs.c:708
static BitmapOr * make_bitmap_or(List *bitmapplans)
Definition: createplan.c:5788
Cost total_cost
Definition: pathnodes.h:1186
int plan_width
Definition: plannodes.h:124
#define Assert(condition)
Definition: c.h:804
#define lfirst(lc)
Definition: pg_list.h:169
bool parallel_safe
Definition: pathnodes.h:1180
static int list_length(const List *l)
Definition: pg_list.h:149
static BitmapIndexScan * make_bitmap_indexscan(Index scanrelid, Oid indexid, List *indexqual, List *indexqualorig)
Definition: createplan.c:5462
#define nodeTag(nodeptr)
Definition: nodes.h:544
#define elog(elevel,...)
Definition: elog.h:232
Cost total_cost
Definition: plannodes.h:118
bool parallel_safe
Definition: plannodes.h:130
List * indpred
Definition: pathnodes.h:856
double clamp_row_est(double nrows)
Definition: costsize.c:199
bool predicate_implied_by(List *predicate_list, List *clause_list, bool weak)
Definition: predtest.c:151
Definition: pg_list.h:50
static Scan * create_indexscan_plan(PlannerInfo *root, IndexPath *best_path, List *tlist, List *scan_clauses, bool indexonly)
Definition: createplan.c:2921
List * list_concat_unique(List *list1, const List *list2)
Definition: list.c:1252

◆ create_ctescan_plan()

static CteScan * create_ctescan_plan ( PlannerInfo root,
Path best_path,
List tlist,
List scan_clauses 
)
static

Definition at line 3774 of file createplan.c.

References Assert, copy_generic_path_info(), PlannerInfo::cte_plan_ids, RangeTblEntry::ctelevelsup, Query::cteList, RangeTblEntry::ctename, CommonTableExpr::ctename, elog, ERROR, extract_actual_clauses(), PlannerInfo::init_plans, lfirst, linitial_int, list_length(), list_nth_int(), make_ctescan(), order_qual_clauses(), Path::param_info, Path::parent, PlannerInfo::parent_root, PlannerInfo::parse, Scan::plan, SubPlan::plan_id, planner_rt_fetch, RelOptInfo::relid, replace_nestloop_params(), RTE_CTE, RangeTblEntry::rtekind, CteScan::scan, RangeTblEntry::self_reference, and SubPlan::setParam.

Referenced by create_scan_plan().

3776 {
3777  CteScan *scan_plan;
3778  Index scan_relid = best_path->parent->relid;
3779  RangeTblEntry *rte;
3780  SubPlan *ctesplan = NULL;
3781  int plan_id;
3782  int cte_param_id;
3783  PlannerInfo *cteroot;
3784  Index levelsup;
3785  int ndx;
3786  ListCell *lc;
3787 
3788  Assert(scan_relid > 0);
3789  rte = planner_rt_fetch(scan_relid, root);
3790  Assert(rte->rtekind == RTE_CTE);
3791  Assert(!rte->self_reference);
3792 
3793  /*
3794  * Find the referenced CTE, and locate the SubPlan previously made for it.
3795  */
3796  levelsup = rte->ctelevelsup;
3797  cteroot = root;
3798  while (levelsup-- > 0)
3799  {
3800  cteroot = cteroot->parent_root;
3801  if (!cteroot) /* shouldn't happen */
3802  elog(ERROR, "bad levelsup for CTE \"%s\"", rte->ctename);
3803  }
3804 
3805  /*
3806  * Note: cte_plan_ids can be shorter than cteList, if we are still working
3807  * on planning the CTEs (ie, this is a side-reference from another CTE).
3808  * So we mustn't use forboth here.
3809  */
3810  ndx = 0;
3811  foreach(lc, cteroot->parse->cteList)
3812  {
3813  CommonTableExpr *cte = (CommonTableExpr *) lfirst(lc);
3814 
3815  if (strcmp(cte->ctename, rte->ctename) == 0)
3816  break;
3817  ndx++;
3818  }
3819  if (lc == NULL) /* shouldn't happen */
3820  elog(ERROR, "could not find CTE \"%s\"", rte->ctename);
3821  if (ndx >= list_length(cteroot->cte_plan_ids))
3822  elog(ERROR, "could not find plan for CTE \"%s\"", rte->ctename);
3823  plan_id = list_nth_int(cteroot->cte_plan_ids, ndx);
3824  Assert(plan_id > 0);
3825  foreach(lc, cteroot->init_plans)
3826  {
3827  ctesplan = (SubPlan *) lfirst(lc);
3828  if (ctesplan->plan_id == plan_id)
3829  break;
3830  }
3831  if (lc == NULL) /* shouldn't happen */
3832  elog(ERROR, "could not find plan for CTE \"%s\"", rte->ctename);
3833 
3834  /*
3835  * We need the CTE param ID, which is the sole member of the SubPlan's
3836  * setParam list.
3837  */
3838  cte_param_id = linitial_int(ctesplan->setParam);
3839 
3840  /* Sort clauses into best execution order */
3841  scan_clauses = order_qual_clauses(root, scan_clauses);
3842 
3843  /* Reduce RestrictInfo list to bare expressions; ignore pseudoconstants */
3844  scan_clauses = extract_actual_clauses(scan_clauses, false);
3845 
3846  /* Replace any outer-relation variables with nestloop params */
3847  if (best_path->param_info)
3848  {
3849  scan_clauses = (List *)
3850  replace_nestloop_params(root, (Node *) scan_clauses);
3851  }
3852 
3853  scan_plan = make_ctescan(tlist, scan_clauses, scan_relid,
3854  plan_id, cte_param_id);
3855 
3856  copy_generic_path_info(&scan_plan->scan.plan, best_path);
3857 
3858  return scan_plan;
3859 }
Plan plan
Definition: plannodes.h:342
Query * parse
Definition: pathnodes.h:161
static Node * replace_nestloop_params(PlannerInfo *root, Node *expr)
Definition: createplan.c:4791
int plan_id
Definition: primnodes.h:742
PlannerInfo * parent_root
Definition: pathnodes.h:167
ParamPathInfo * param_info
Definition: pathnodes.h:1177
Definition: nodes.h:539
static List * order_qual_clauses(PlannerInfo *root, List *clauses)
Definition: createplan.c:5175
static int list_nth_int(const List *list, int n)
Definition: pg_list.h:289
#define linitial_int(l)
Definition: pg_list.h:175
static void copy_generic_path_info(Plan *dest, Path *src)
Definition: createplan.c:5269
#define ERROR
Definition: elog.h:46
Scan scan
Definition: plannodes.h:566
#define planner_rt_fetch(rti, root)
Definition: pathnodes.h:383
RelOptInfo * parent
Definition: pathnodes.h:1174
Index relid
Definition: pathnodes.h:704
static CteScan * make_ctescan(List *qptlist, List *qpqual, Index scanrelid, int ctePlanId, int cteParam)
Definition: createplan.c:5619
List * cte_plan_ids
Definition: pathnodes.h:243
bool self_reference
Definition: parsenodes.h:1107
unsigned int Index
Definition: c.h:549
List * init_plans
Definition: pathnodes.h:241
#define Assert(condition)
Definition: c.h:804
#define lfirst(lc)
Definition: pg_list.h:169
List * setParam
Definition: primnodes.h:760
static int list_length(const List *l)
Definition: pg_list.h:149
List * extract_actual_clauses(List *restrictinfo_list, bool pseudoconstant)
Definition: restrictinfo.c:443
Index ctelevelsup
Definition: parsenodes.h:1106
RTEKind rtekind
Definition: parsenodes.h:995
List * cteList
Definition: parsenodes.h:145
char * ctename
Definition: parsenodes.h:1105
#define elog(elevel,...)
Definition: elog.h:232
Definition: pg_list.h:50

◆ create_customscan_plan()

static CustomScan * create_customscan_plan ( PlannerInfo root,
CustomPath best_path,
List tlist,
List scan_clauses 
)
static

Definition at line 4148 of file createplan.c.

References castNode, copy_generic_path_info(), CP_EXACT_TLIST, create_plan_recurse(), CustomScan::custom_exprs, CustomPath::custom_paths, CustomScan::custom_relids, lappend(), lfirst, CustomPath::methods, NIL, order_qual_clauses(), Path::param_info, Path::parent, CustomPath::path, Scan::plan, CustomPathMethods::PlanCustomPath, Plan::qual, RelOptInfo::relids, replace_nestloop_params(), and CustomScan::scan.

Referenced by create_scan_plan().

4150 {
4151  CustomScan *cplan;
4152  RelOptInfo *rel = best_path->path.parent;
4153  List *custom_plans = NIL;
4154  ListCell *lc;
4155 
4156  /* Recursively transform child paths. */
4157  foreach(lc, best_path->custom_paths)
4158  {
4159  Plan *plan = create_plan_recurse(root, (Path *) lfirst(lc),
4160  CP_EXACT_TLIST);
4161 
4162  custom_plans = lappend(custom_plans, plan);
4163  }
4164 
4165  /*
4166  * Sort clauses into the best execution order, although custom-scan
4167  * provider can reorder them again.
4168  */
4169  scan_clauses = order_qual_clauses(root, scan_clauses);
4170 
4171  /*
4172  * Invoke custom plan provider to create the Plan node represented by the
4173  * CustomPath.
4174  */
4175  cplan = castNode(CustomScan,
4176  best_path->methods->PlanCustomPath(root,
4177  rel,
4178  best_path,
4179  tlist,
4180  scan_clauses,
4181  custom_plans));
4182 
4183  /*
4184  * Copy cost data from Path to Plan; no need to make custom-plan providers
4185  * do this
4186  */
4187  copy_generic_path_info(&cplan->scan.plan, &best_path->path);
4188 
4189  /* Likewise, copy the relids that are represented by this custom scan */
4190  cplan->custom_relids = best_path->path.parent->relids;
4191 
4192  /*
4193  * Replace any outer-relation variables with nestloop params in the qual
4194  * and custom_exprs expressions. We do this last so that the custom-plan
4195  * provider doesn't have to be involved. (Note that parts of custom_exprs
4196  * could have come from join clauses, so doing this beforehand on the
4197  * scan_clauses wouldn't work.) We assume custom_scan_tlist contains no
4198  * such variables.
4199  */
4200  if (best_path->path.param_info)
4201  {
4202  cplan->scan.plan.qual = (List *)
4203  replace_nestloop_params(root, (Node *) cplan->scan.plan.qual);
4204  cplan->custom_exprs = (List *)
4205  replace_nestloop_params(root, (Node *) cplan->custom_exprs);
4206  }
4207 
4208  return cplan;
4209 }
#define NIL
Definition: pg_list.h:65
List * qual
Definition: plannodes.h:142
Plan plan
Definition: plannodes.h:342
static Node * replace_nestloop_params(PlannerInfo *root, Node *expr)
Definition: createplan.c:4791
List * custom_paths
Definition: pathnodes.h:1421
#define castNode(_type_, nodeptr)
Definition: nodes.h:608
ParamPathInfo * param_info
Definition: pathnodes.h:1177
Definition: nodes.h:539
List * custom_exprs
Definition: plannodes.h:665
static List * order_qual_clauses(PlannerInfo *root, List *clauses)
Definition: createplan.c:5175
static Plan * create_plan_recurse(PlannerInfo *root, Path *best_path, int flags)
Definition: createplan.c:385
const struct CustomPathMethods * methods
Definition: pathnodes.h:1423
static void copy_generic_path_info(Plan *dest, Path *src)
Definition: createplan.c:5269
RelOptInfo * parent
Definition: pathnodes.h:1174
Relids relids
Definition: pathnodes.h:676
List * lappend(List *list, void *datum)
Definition: list.c:336
Scan scan
Definition: plannodes.h:661
struct Plan *(* PlanCustomPath)(PlannerInfo *root, RelOptInfo *rel, struct CustomPath *best_path, List *tlist, List *clauses, List *custom_plans)
Definition: extensible.h:93
#define lfirst(lc)
Definition: pg_list.h:169
Bitmapset * custom_relids
Definition: plannodes.h:668
#define CP_EXACT_TLIST
Definition: createplan.c:68
Definition: pg_list.h:50

◆ create_foreignscan_plan()

static ForeignScan * create_foreignscan_plan ( PlannerInfo root,
ForeignPath best_path,
List tlist,
List scan_clauses 
)
static

Definition at line 4004 of file createplan.c.

References PlannerInfo::all_baserels, Assert, RelOptInfo::baserestrictinfo, bms_free(), bms_is_member(), RestrictInfo::clause, copy_generic_path_info(), CP_EXACT_TLIST, create_plan_recurse(), PlannerGlobal::dependsOnRole, PathTarget::exprs, ForeignScan::fdw_exprs, ForeignPath::fdw_outerpath, ForeignScan::fdw_recheck_quals, RelOptInfo::fdwroutine, FirstLowInvalidHeapAttributeNumber, ForeignScan::fs_relids, ForeignScan::fs_server, ForeignScan::fsSystemCol, FdwRoutine::GetForeignPlan, PlannerInfo::glob, i, InvalidOid, lfirst, order_qual_clauses(), Path::param_info, Path::parent, ForeignPath::path, Scan::plan, planner_rt_fetch, pull_varattnos(), Plan::qual, RelOptInfo::relid, RangeTblEntry::relid, RelOptInfo::relids, RELOPT_UPPER_REL, RelOptInfo::reloptkind, RelOptInfo::reltarget, replace_nestloop_params(), RTE_RELATION, RelOptInfo::rtekind, RangeTblEntry::rtekind, ForeignScan::scan, RelOptInfo::serverid, and RelOptInfo::useridiscurrent.

Referenced by create_scan_plan().

4006 {
4007  ForeignScan *scan_plan;
4008  RelOptInfo *rel = best_path->path.parent;
4009  Index scan_relid = rel->relid;
4010  Oid rel_oid = InvalidOid;
4011  Plan *outer_plan = NULL;
4012 
4013  Assert(rel->fdwroutine != NULL);
4014 
4015  /* transform the child path if any */
4016  if (best_path->fdw_outerpath)
4017  outer_plan = create_plan_recurse(root, best_path->fdw_outerpath,
4018  CP_EXACT_TLIST);
4019 
4020  /*
4021  * If we're scanning a base relation, fetch its OID. (Irrelevant if
4022  * scanning a join relation.)
4023  */
4024  if (scan_relid > 0)
4025  {
4026  RangeTblEntry *rte;
4027 
4028  Assert(rel->rtekind == RTE_RELATION);
4029  rte = planner_rt_fetch(scan_relid, root);
4030  Assert(rte->rtekind == RTE_RELATION);
4031  rel_oid = rte->relid;
4032  }
4033 
4034  /*
4035  * Sort clauses into best execution order. We do this first since the FDW
4036  * might have more info than we do and wish to adjust the ordering.
4037  */
4038  scan_clauses = order_qual_clauses(root, scan_clauses);
4039 
4040  /*
4041  * Let the FDW perform its processing on the restriction clauses and
4042  * generate the plan node. Note that the FDW might remove restriction
4043  * clauses that it intends to execute remotely, or even add more (if it
4044  * has selected some join clauses for remote use but also wants them
4045  * rechecked locally).
4046  */
4047  scan_plan = rel->fdwroutine->GetForeignPlan(root, rel, rel_oid,
4048  best_path,
4049  tlist, scan_clauses,
4050  outer_plan);
4051 
4052  /* Copy cost data from Path to Plan; no need to make FDW do this */
4053  copy_generic_path_info(&scan_plan->scan.plan, &best_path->path);
4054 
4055  /* Copy foreign server OID; likewise, no need to make FDW do this */
4056  scan_plan->fs_server = rel->serverid;
4057 
4058  /*
4059  * Likewise, copy the relids that are represented by this foreign scan. An
4060  * upper rel doesn't have relids set, but it covers all the base relations
4061  * participating in the underlying scan, so use root's all_baserels.
4062  */
4063  if (rel->reloptkind == RELOPT_UPPER_REL)
4064  scan_plan->fs_relids = root->all_baserels;
4065  else
4066  scan_plan->fs_relids = best_path->path.parent->relids;
4067 
4068  /*
4069  * If this is a foreign join, and to make it valid to push down we had to
4070  * assume that the current user is the same as some user explicitly named
4071  * in the query, mark the finished plan as depending on the current user.
4072  */
4073  if (rel->useridiscurrent)
4074  root->glob->dependsOnRole = true;
4075 
4076  /*
4077  * Replace any outer-relation variables with nestloop params in the qual,
4078  * fdw_exprs and fdw_recheck_quals expressions. We do this last so that
4079  * the FDW doesn't have to be involved. (Note that parts of fdw_exprs or
4080  * fdw_recheck_quals could have come from join clauses, so doing this
4081  * beforehand on the scan_clauses wouldn't work.) We assume
4082  * fdw_scan_tlist contains no such variables.
4083  */
4084  if (best_path->path.param_info)
4085  {
4086  scan_plan->scan.plan.qual = (List *)
4087  replace_nestloop_params(root, (Node *) scan_plan->scan.plan.qual);
4088  scan_plan->fdw_exprs = (List *)
4089  replace_nestloop_params(root, (Node *) scan_plan->fdw_exprs);
4090  scan_plan->fdw_recheck_quals = (List *)
4092  (Node *) scan_plan->fdw_recheck_quals);
4093  }
4094 
4095  /*
4096  * If rel is a base relation, detect whether any system columns are
4097  * requested from the rel. (If rel is a join relation, rel->relid will be
4098  * 0, but there can be no Var with relid 0 in the rel's targetlist or the
4099  * restriction clauses, so we skip this in that case. Note that any such
4100  * columns in base relations that were joined are assumed to be contained
4101  * in fdw_scan_tlist.) This is a bit of a kluge and might go away
4102  * someday, so we intentionally leave it out of the API presented to FDWs.
4103  */
4104  scan_plan->fsSystemCol = false;
4105  if (scan_relid > 0)
4106  {
4107  Bitmapset *attrs_used = NULL;
4108  ListCell *lc;
4109  int i;
4110 
4111  /*
4112  * First, examine all the attributes needed for joins or final output.
4113  * Note: we must look at rel's targetlist, not the attr_needed data,
4114  * because attr_needed isn't computed for inheritance child rels.
4115  */
4116  pull_varattnos((Node *) rel->reltarget->exprs, scan_relid, &attrs_used);
4117 
4118  /* Add all the attributes used by restriction clauses. */
4119  foreach(lc, rel->baserestrictinfo)
4120  {
4121  RestrictInfo *rinfo = (RestrictInfo *) lfirst(lc);
4122 
4123  pull_varattnos((Node *) rinfo->clause, scan_relid, &attrs_used);
4124  }
4125 
4126  /* Now, are any system columns requested from rel? */
4127  for (i = FirstLowInvalidHeapAttributeNumber + 1; i < 0; i++)
4128  {
4130  {
4131  scan_plan->fsSystemCol = true;
4132  break;
4133  }
4134  }
4135 
4136  bms_free(attrs_used);
4137  }
4138 
4139  return scan_plan;
4140 }
GetForeignPlan_function GetForeignPlan
Definition: fdwapi.h:212
List * qual
Definition: plannodes.h:142
Plan plan
Definition: plannodes.h:342
static Node * replace_nestloop_params(PlannerInfo *root, Node *expr)
Definition: createplan.c:4791
Path * fdw_outerpath
Definition: pathnodes.h:1391
RelOptKind reloptkind
Definition: pathnodes.h:673
Oid fs_server
Definition: plannodes.h:635
List * baserestrictinfo
Definition: pathnodes.h:740
List * fdw_exprs
Definition: plannodes.h:636
ParamPathInfo * param_info
Definition: pathnodes.h:1177
Definition: nodes.h:539
static List * order_qual_clauses(PlannerInfo *root, List *clauses)
Definition: createplan.c:5175
#define FirstLowInvalidHeapAttributeNumber
Definition: sysattr.h:27
bool useridiscurrent
Definition: pathnodes.h:729
unsigned int Oid
Definition: postgres_ext.h:31
void pull_varattnos(Node *node, Index varno, Bitmapset **varattnos)
Definition: var.c:246
bool dependsOnRole
Definition: pathnodes.h:123
static Plan * create_plan_recurse(PlannerInfo *root, Path *best_path, int flags)
Definition: createplan.c:385
static void copy_generic_path_info(Plan *dest, Path *src)
Definition: createplan.c:5269
Relids all_baserels
Definition: pathnodes.h:209
#define planner_rt_fetch(rti, root)
Definition: pathnodes.h:383
RelOptInfo * parent
Definition: pathnodes.h:1174
PlannerGlobal * glob
Definition: pathnodes.h:163
struct FdwRoutine * fdwroutine
Definition: pathnodes.h:731
Relids relids
Definition: pathnodes.h:676
List * fdw_recheck_quals
Definition: plannodes.h:639
Index relid
Definition: pathnodes.h:704
Expr * clause
Definition: pathnodes.h:2045
Oid serverid
Definition: pathnodes.h:727
List * exprs
Definition: pathnodes.h:1102
unsigned int Index
Definition: c.h:549
RTEKind rtekind
Definition: pathnodes.h:706
#define InvalidOid
Definition: postgres_ext.h:36
void bms_free(Bitmapset *a)
Definition: bitmapset.c:208
#define Assert(condition)
Definition: c.h:804
#define lfirst(lc)
Definition: pg_list.h:169
RTEKind rtekind
Definition: parsenodes.h:995
int i
#define CP_EXACT_TLIST
Definition: createplan.c:68
Definition: pg_list.h:50
bool bms_is_member(int x, const Bitmapset *a)
Definition: bitmapset.c:427
struct PathTarget * reltarget
Definition: pathnodes.h:687
bool fsSystemCol
Definition: plannodes.h:641
Bitmapset * fs_relids
Definition: plannodes.h:640

◆ create_functionscan_plan()

static FunctionScan * create_functionscan_plan ( PlannerInfo root,
Path best_path,
List tlist,
List scan_clauses 
)
static

Definition at line 3644 of file createplan.c.

References Assert, copy_generic_path_info(), extract_actual_clauses(), RangeTblEntry::funcordinality, functions, RangeTblEntry::functions, make_functionscan(), order_qual_clauses(), Path::param_info, Path::parent, Scan::plan, planner_rt_fetch, RelOptInfo::relid, replace_nestloop_params(), RTE_FUNCTION, RangeTblEntry::rtekind, and FunctionScan::scan.

Referenced by create_scan_plan().

3646 {
3647  FunctionScan *scan_plan;
3648  Index scan_relid = best_path->parent->relid;
3649  RangeTblEntry *rte;
3650  List *functions;
3651 
3652  /* it should be a function base rel... */
3653  Assert(scan_relid > 0);
3654  rte = planner_rt_fetch(scan_relid, root);
3655  Assert(rte->rtekind == RTE_FUNCTION);
3656  functions = rte->functions;
3657 
3658  /* Sort clauses into best execution order */
3659  scan_clauses = order_qual_clauses(root, scan_clauses);
3660 
3661  /* Reduce RestrictInfo list to bare expressions; ignore pseudoconstants */
3662  scan_clauses = extract_actual_clauses(scan_clauses, false);
3663 
3664  /* Replace any outer-relation variables with nestloop params */
3665  if (best_path->param_info)
3666  {
3667  scan_clauses = (List *)
3668  replace_nestloop_params(root, (Node *) scan_clauses);
3669  /* The function expressions could contain nestloop params, too */
3670  functions = (List *) replace_nestloop_params(root, (Node *) functions);
3671  }
3672 
3673  scan_plan = make_functionscan(tlist, scan_clauses, scan_relid,
3674  functions, rte->funcordinality);
3675 
3676  copy_generic_path_info(&scan_plan->scan.plan, best_path);
3677 
3678  return scan_plan;
3679 }
Plan plan
Definition: plannodes.h:342
static Node * replace_nestloop_params(PlannerInfo *root, Node *expr)
Definition: createplan.c:4791
ParamPathInfo * param_info
Definition: pathnodes.h:1177
Definition: nodes.h:539
static List * order_qual_clauses(PlannerInfo *root, List *clauses)
Definition: createplan.c:5175
bool funcordinality
Definition: parsenodes.h:1090
static void copy_generic_path_info(Plan *dest, Path *src)
Definition: createplan.c:5269
#define planner_rt_fetch(rti, root)
Definition: pathnodes.h:383
RelOptInfo * parent
Definition: pathnodes.h:1174
Index relid
Definition: pathnodes.h:704
unsigned int Index
Definition: c.h:549
static FunctionScan * make_functionscan(List *qptlist, List *qpqual, Index scanrelid, List *functions, bool funcordinality)
Definition: createplan.c:5560
#define Assert(condition)
Definition: c.h:804
List * functions
Definition: parsenodes.h:1089
List * extract_actual_clauses(List *restrictinfo_list, bool pseudoconstant)
Definition: restrictinfo.c:443
static const struct fns functions
Definition: regcomp.c:314
RTEKind rtekind
Definition: parsenodes.h:995
Definition: pg_list.h:50

◆ create_gather_merge_plan()

static GatherMerge * create_gather_merge_plan ( PlannerInfo root,
GatherMergePath best_path 
)
static

Definition at line 1874 of file createplan.c.

References Assert, assign_special_exec_param(), build_path_tlist(), GatherMerge::collations, copy_generic_path_info(), CP_EXACT_TLIST, create_plan_recurse(), elog, ERROR, PlannerInfo::glob, Plan::lefttree, makeNode, NIL, GatherMerge::nullsFirst, GatherMerge::num_workers, GatherMergePath::num_workers, GatherMerge::numCols, PlannerGlobal::parallelModeNeeded, Path::parent, GatherMergePath::path, Path::pathkeys, pathkeys_contained_in(), GatherMerge::plan, prepare_sort_from_pathkeys(), RelOptInfo::relids, GatherMerge::rescan_param, GatherMerge::sortColIdx, GatherMerge::sortOperators, GatherMergePath::subpath, and Plan::targetlist.

Referenced by create_plan_recurse().

1875 {
1876  GatherMerge *gm_plan;
1877  Plan *subplan;
1878  List *pathkeys = best_path->path.pathkeys;
1879  List *tlist = build_path_tlist(root, &best_path->path);
1880 
1881  /* As with Gather, project away columns in the workers. */
1882  subplan = create_plan_recurse(root, best_path->subpath, CP_EXACT_TLIST);
1883 
1884  /* Create a shell for a GatherMerge plan. */
1885  gm_plan = makeNode(GatherMerge);
1886  gm_plan->plan.targetlist = tlist;
1887  gm_plan->num_workers = best_path->num_workers;
1888  copy_generic_path_info(&gm_plan->plan, &best_path->path);
1889 
1890  /* Assign the rescan Param. */
1891  gm_plan->rescan_param = assign_special_exec_param(root);
1892 
1893  /* Gather Merge is pointless with no pathkeys; use Gather instead. */
1894  Assert(pathkeys != NIL);
1895 
1896  /* Compute sort column info, and adjust subplan's tlist as needed */
1897  subplan = prepare_sort_from_pathkeys(subplan, pathkeys,
1898  best_path->subpath->parent->relids,
1899  gm_plan->sortColIdx,
1900  false,
1901  &gm_plan->numCols,
1902  &gm_plan->sortColIdx,
1903  &gm_plan->sortOperators,
1904  &gm_plan->collations,
1905  &gm_plan->nullsFirst);
1906 
1907 
1908  /*
1909  * All gather merge paths should have already guaranteed the necessary sort
1910  * order either by adding an explicit sort node or by using presorted input.
1911  * We can't simply add a sort here on additional pathkeys, because we can't
1912  * guarantee the sort would be safe. For example, expressions may be
1913  * volatile or otherwise parallel unsafe.
1914  */
1915  if (!pathkeys_contained_in(pathkeys, best_path->subpath->pathkeys))
1916  elog(ERROR, "gather merge input not sufficiently sorted");
1917 
1918  /* Now insert the subplan under GatherMerge. */
1919  gm_plan->plan.lefttree = subplan;
1920 
1921  /* use parallel mode for parallel plans. */
1922  root->glob->parallelModeNeeded = true;
1923 
1924  return gm_plan;
1925 }
#define NIL
Definition: pg_list.h:65
Oid * collations
Definition: plannodes.h:948
AttrNumber * sortColIdx
Definition: plannodes.h:946
bool * nullsFirst
Definition: plannodes.h:949
int assign_special_exec_param(PlannerInfo *root)
Definition: paramassign.c:584
static Plan * create_plan_recurse(PlannerInfo *root, Path *best_path, int flags)
Definition: createplan.c:385
static void copy_generic_path_info(Plan *dest, Path *src)
Definition: createplan.c:5269
bool parallelModeNeeded
Definition: pathnodes.h:127
#define ERROR
Definition: elog.h:46
static List * build_path_tlist(PlannerInfo *root, Path *path)
Definition: createplan.c:803
RelOptInfo * parent
Definition: pathnodes.h:1174
PlannerGlobal * glob
Definition: pathnodes.h:163
Relids relids
Definition: pathnodes.h:676
Oid * sortOperators
Definition: plannodes.h:947
bool pathkeys_contained_in(List *keys1, List *keys2)
Definition: pathkeys.c:324
List * pathkeys
Definition: pathnodes.h:1188
#define makeNode(_type_)
Definition: nodes.h:587
#define Assert(condition)
Definition: c.h:804
struct Plan * lefttree
Definition: plannodes.h:143
List * targetlist
Definition: plannodes.h:141
int num_workers
Definition: plannodes.h:942
#define elog(elevel,...)
Definition: elog.h:232
int rescan_param
Definition: plannodes.h:943
#define CP_EXACT_TLIST
Definition: createplan.c:68
Definition: pg_list.h:50
static Plan * prepare_sort_from_pathkeys(Plan *lefttree, List *pathkeys, Relids relids, const AttrNumber *reqColIdx, bool adjust_tlist_in_place, int *p_numsortkeys, AttrNumber **p_sortColIdx, Oid **p_sortOperators, Oid **p_collations, bool **p_nullsFirst)
Definition: createplan.c:6019

◆ create_gather_plan()

static Gather * create_gather_plan ( PlannerInfo root,
GatherPath best_path 
)
static

Definition at line 1836 of file createplan.c.

References assign_special_exec_param(), build_path_tlist(), copy_generic_path_info(), CP_EXACT_TLIST, create_plan_recurse(), PlannerInfo::glob, make_gather(), NIL, GatherPath::num_workers, PlannerGlobal::parallelModeNeeded, GatherPath::path, Gather::plan, GatherPath::single_copy, and GatherPath::subpath.

Referenced by create_plan_recurse().

1837 {
1838  Gather *gather_plan;
1839  Plan *subplan;
1840  List *tlist;
1841 
1842  /*
1843  * Push projection down to the child node. That way, the projection work
1844  * is parallelized, and there can be no system columns in the result (they
1845  * can't travel through a tuple queue because it uses MinimalTuple
1846  * representation).
1847  */
1848  subplan = create_plan_recurse(root, best_path->subpath, CP_EXACT_TLIST);
1849 
1850  tlist = build_path_tlist(root, &best_path->path);
1851 
1852  gather_plan = make_gather(tlist,
1853  NIL,
1854  best_path->num_workers,
1856  best_path->single_copy,
1857  subplan);
1858 
1859  copy_generic_path_info(&gather_plan->plan, &best_path->path);
1860 
1861  /* use parallel mode for parallel plans. */
1862  root->glob->parallelModeNeeded = true;
1863 
1864  return gather_plan;
1865 }
#define NIL
Definition: pg_list.h:65
bool single_copy
Definition: pathnodes.h:1553
int assign_special_exec_param(PlannerInfo *root)
Definition: paramassign.c:584
int num_workers
Definition: pathnodes.h:1554
static Plan * create_plan_recurse(PlannerInfo *root, Path *best_path, int flags)
Definition: createplan.c:385
static void copy_generic_path_info(Plan *dest, Path *src)
Definition: createplan.c:5269
bool parallelModeNeeded
Definition: pathnodes.h:127
static List * build_path_tlist(PlannerInfo *root, Path *path)
Definition: createplan.c:803
Plan plan
Definition: plannodes.h:926
PlannerGlobal * glob
Definition: pathnodes.h:163
Path * subpath
Definition: pathnodes.h:1552
static Gather * make_gather(List *qptlist, List *qpqual, int nworkers, int rescan_param, bool single_copy, Plan *subplan)
Definition: createplan.c:6699
#define CP_EXACT_TLIST
Definition: createplan.c:68
Definition: pg_list.h:50

◆ create_gating_plan()

static Plan * create_gating_plan ( PlannerInfo root,
Path path,
Plan plan,
List gating_quals 
)
static

Definition at line 984 of file createplan.c.

References Assert, build_path_tlist(), copy_plan_costsize(), IsA, Plan::lefttree, make_result(), Plan::parallel_safe, Path::parallel_safe, Result::plan, Result::resconstantqual, and splan.

Referenced by create_join_plan(), and create_scan_plan().

986 {
987  Plan *gplan;
988  Plan *splan;
989 
990  Assert(gating_quals);
991 
992  /*
993  * We might have a trivial Result plan already. Stacking one Result atop
994  * another is silly, so if that applies, just discard the input plan.
995  * (We're assuming its targetlist is uninteresting; it should be either
996  * the same as the result of build_path_tlist, or a simplified version.)
997  */
998  splan = plan;
999  if (IsA(plan, Result))
1000  {
1001  Result *rplan = (Result *) plan;
1002 
1003  if (rplan->plan.lefttree == NULL &&
1004  rplan->resconstantqual == NULL)
1005  splan = NULL;
1006  }
1007 
1008  /*
1009  * Since we need a Result node anyway, always return the path's requested
1010  * tlist; that's never a wrong choice, even if the parent node didn't ask
1011  * for CP_EXACT_TLIST.
1012  */
1013  gplan = (Plan *) make_result(build_path_tlist(root, path),
1014  (Node *) gating_quals,
1015  splan);
1016 
1017  /*
1018  * Notice that we don't change cost or size estimates when doing gating.
1019  * The costs of qual eval were already included in the subplan's cost.
1020  * Leaving the size alone amounts to assuming that the gating qual will
1021  * succeed, which is the conservative estimate for planning upper queries.
1022  * We certainly don't want to assume the output size is zero (unless the
1023  * gating qual is actually constant FALSE, and that case is dealt with in
1024  * clausesel.c). Interpolating between the two cases is silly, because it
1025  * doesn't reflect what will really happen at runtime, and besides which
1026  * in most cases we have only a very bad idea of the probability of the
1027  * gating qual being true.
1028  */
1029  copy_plan_costsize(gplan, plan);
1030 
1031  /* Gating quals could be unsafe, so better use the Path's safety flag */
1032  gplan->parallel_safe = path->parallel_safe;
1033 
1034  return gplan;
1035 }
Plan plan
Definition: plannodes.h:187
#define IsA(nodeptr, _type_)
Definition: nodes.h:590
Definition: nodes.h:539
Node * resconstantqual
Definition: plannodes.h:188
static List * build_path_tlist(PlannerInfo *root, Path *path)
Definition: createplan.c:803
static void copy_plan_costsize(Plan *dest, Plan *src)
Definition: createplan.c:5284
static SPIPlanPtr splan
Definition: regress.c:262
static Result * make_result(List *tlist, Node *resconstantqual, Plan *subplan)
Definition: createplan.c:6833
#define Assert(condition)
Definition: c.h:804
bool parallel_safe
Definition: pathnodes.h:1180
struct Plan * lefttree
Definition: plannodes.h:143
bool parallel_safe
Definition: plannodes.h:130

◆ create_group_plan()

static Group * create_group_plan ( PlannerInfo root,
GroupPath best_path 
)
static

Definition at line 2157 of file createplan.c.

References build_path_tlist(), copy_generic_path_info(), CP_LABEL_TLIST, create_plan_recurse(), extract_grouping_collations(), extract_grouping_cols(), extract_grouping_ops(), GroupPath::groupClause, list_length(), make_group(), order_qual_clauses(), GroupPath::path, Group::plan, GroupPath::qual, GroupPath::subpath, and Plan::targetlist.

Referenced by create_plan_recurse().

2158 {
2159  Group *plan;
2160  Plan *subplan;
2161  List *tlist;
2162  List *quals;
2163 
2164  /*
2165  * Group can project, so no need to be terribly picky about child tlist,
2166  * but we do need grouping columns to be available
2167  */
2168  subplan = create_plan_recurse(root, best_path->subpath, CP_LABEL_TLIST);
2169 
2170  tlist = build_path_tlist(root, &best_path->path);
2171 
2172  quals = order_qual_clauses(root, best_path->qual);
2173 
2174  plan = make_group(tlist,
2175  quals,
2176  list_length(best_path->groupClause),
2178  subplan->targetlist),
2179  extract_grouping_ops(best_path->groupClause),
2181  subplan->targetlist),
2182  subplan);
2183 
2184  copy_generic_path_info(&plan->plan, (Path *) best_path);
2185 
2186  return plan;
2187 }
List * qual
Definition: pathnodes.h:1733
Oid * extract_grouping_collations(List *groupClause, List *tlist)
Definition: tlist.c:478
static List * order_qual_clauses(PlannerInfo *root, List *clauses)
Definition: createplan.c:5175
Oid * extract_grouping_ops(List *groupClause)
Definition: tlist.c:452
AttrNumber * extract_grouping_cols(List *groupClause, List *tlist)
Definition: tlist.c:503
static Plan * create_plan_recurse(PlannerInfo *root, Path *best_path, int flags)
Definition: createplan.c:385
static void copy_generic_path_info(Plan *dest, Path *src)
Definition: createplan.c:5269
static Group * make_group(List *tlist, List *qual, int numGroupCols, AttrNumber *grpColIdx, Oid *grpOperators, Oid *grpCollations, Plan *lefttree)
Definition: createplan.c:6514
static List * build_path_tlist(PlannerInfo *root, Path *path)
Definition: createplan.c:803
Path path
Definition: pathnodes.h:1730
List * groupClause
Definition: pathnodes.h:1732
#define CP_LABEL_TLIST
Definition: createplan.c:70
Path * subpath
Definition: pathnodes.h:1731
Plan plan
Definition: plannodes.h:835
static int list_length(const List *l)
Definition: pg_list.h:149
List * targetlist
Definition: plannodes.h:141
Definition: pg_list.h:50

◆ create_group_result_plan()

static Result * create_group_result_plan ( PlannerInfo root,
GroupResultPath best_path 
)
static

Definition at line 1508 of file createplan.c.

References build_path_tlist(), copy_generic_path_info(), make_result(), order_qual_clauses(), GroupResultPath::path, Result::plan, and GroupResultPath::quals.

Referenced by create_plan_recurse().

1509 {
1510  Result *plan;
1511  List *tlist;
1512  List *quals;
1513 
1514  tlist = build_path_tlist(root, &best_path->path);
1515 
1516  /* best_path->quals is just bare clauses */
1517  quals = order_qual_clauses(root, best_path->quals);
1518 
1519  plan = make_result(tlist, (Node *) quals, NULL);
1520 
1521  copy_generic_path_info(&plan->plan, (Path *) best_path);
1522 
1523  return plan;
1524 }
Plan plan
Definition: plannodes.h:187
Definition: nodes.h:539
static List * order_qual_clauses(PlannerInfo *root, List *clauses)
Definition: createplan.c:5175
static void copy_generic_path_info(Plan *dest, Path *src)
Definition: createplan.c:5269
static List * build_path_tlist(PlannerInfo *root, Path *path)
Definition: createplan.c:803
static Result * make_result(List *tlist, Node *resconstantqual, Plan *subplan)
Definition: createplan.c:6833
Definition: pg_list.h:50

◆ create_groupingsets_plan()

static Plan * create_groupingsets_plan ( PlannerInfo root,
GroupingSetsPath best_path 
)
static

Definition at line 2308 of file createplan.c.

References AGG_HASHED, AGG_PLAIN, AGG_SORTED, AGGSPLIT_SIMPLE, GroupingSetsPath::aggstrategy, Assert, build_path_tlist(), copy_generic_path_info(), CP_LABEL_TLIST, create_plan_recurse(), extract_grouping_collations(), extract_grouping_ops(), for_each_from, get_sortgroupclause_tle(), Query::groupClause, RollupData::groupClause, PlannerInfo::grouping_map, Query::groupingSets, RollupData::gsets, RollupData::is_hashed, lappend(), Plan::lefttree, lfirst, linitial, list_length(), make_agg(), make_sort_from_groupcols(), NIL, RollupData::numGroups, palloc0(), PlannerInfo::parse, GroupingSetsPath::path, Agg::plan, GroupingSetsPath::qual, remap_groupColIdx(), TargetEntry::resno, GroupingSetsPath::rollups, GroupingSetsPath::subpath, Plan::targetlist, SortGroupClause::tleSortGroupRef, and GroupingSetsPath::transitionSpace.

Referenced by create_plan_recurse().

2309 {
2310  Agg *plan;
2311  Plan *subplan;
2312  List *rollups = best_path->rollups;
2313  AttrNumber *grouping_map;
2314  int maxref;
2315  List *chain;
2316  ListCell *lc;
2317 
2318  /* Shouldn't get here without grouping sets */
2319  Assert(root->parse->groupingSets);
2320  Assert(rollups != NIL);
2321 
2322  /*
2323  * Agg can project, so no need to be terribly picky about child tlist, but
2324  * we do need grouping columns to be available
2325  */
2326  subplan = create_plan_recurse(root, best_path->subpath, CP_LABEL_TLIST);
2327 
2328  /*
2329  * Compute the mapping from tleSortGroupRef to column index in the child's
2330  * tlist. First, identify max SortGroupRef in groupClause, for array
2331  * sizing.
2332  */
2333  maxref = 0;
2334  foreach(lc, root->parse->groupClause)
2335  {
2336  SortGroupClause *gc = (SortGroupClause *) lfirst(lc);
2337 
2338  if (gc->tleSortGroupRef > maxref)
2339  maxref = gc->tleSortGroupRef;
2340  }
2341 
2342  grouping_map = (AttrNumber *) palloc0((maxref + 1) * sizeof(AttrNumber));
2343 
2344  /* Now look up the column numbers in the child's tlist */
2345  foreach(lc, root->parse->groupClause)
2346  {
2347  SortGroupClause *gc = (SortGroupClause *) lfirst(lc);
2348  TargetEntry *tle = get_sortgroupclause_tle(gc, subplan->targetlist);
2349 
2350  grouping_map[gc->tleSortGroupRef] = tle->resno;
2351  }
2352 
2353  /*
2354  * During setrefs.c, we'll need the grouping_map to fix up the cols lists
2355  * in GroupingFunc nodes. Save it for setrefs.c to use.
2356  */
2357  Assert(root->grouping_map == NULL);
2358  root->grouping_map = grouping_map;
2359 
2360  /*
2361  * Generate the side nodes that describe the other sort and group
2362  * operations besides the top one. Note that we don't worry about putting
2363  * accurate cost estimates in the side nodes; only the topmost Agg node's
2364  * costs will be shown by EXPLAIN.
2365  */
2366  chain = NIL;
2367  if (list_length(rollups) > 1)
2368  {
2369  bool is_first_sort = ((RollupData *) linitial(rollups))->is_hashed;
2370 
2371  for_each_from(lc, rollups, 1)
2372  {
2373  RollupData *rollup = lfirst(lc);
2374  AttrNumber *new_grpColIdx;
2375  Plan *sort_plan = NULL;
2376  Plan *agg_plan;
2377  AggStrategy strat;
2378 
2379  new_grpColIdx = remap_groupColIdx(root, rollup->groupClause);
2380 
2381  if (!rollup->is_hashed && !is_first_sort)
2382  {
2383  sort_plan = (Plan *)
2385  new_grpColIdx,
2386  subplan);
2387  }
2388 
2389  if (!rollup->is_hashed)
2390  is_first_sort = false;
2391 
2392  if (rollup->is_hashed)
2393  strat = AGG_HASHED;
2394  else if (list_length(linitial(rollup->gsets)) == 0)
2395  strat = AGG_PLAIN;
2396  else
2397  strat = AGG_SORTED;
2398 
2399  agg_plan = (Plan *) make_agg(NIL,
2400  NIL,
2401  strat,
2403  list_length((List *) linitial(rollup->gsets)),
2404  new_grpColIdx,
2407  rollup->gsets,
2408  NIL,
2409  rollup->numGroups,
2410  best_path->transitionSpace,
2411  sort_plan);
2412 
2413  /*
2414  * Remove stuff we don't need to avoid bloating debug output.
2415  */
2416  if (sort_plan)
2417  {
2418  sort_plan->targetlist = NIL;
2419  sort_plan->lefttree = NULL;
2420  }
2421 
2422  chain = lappend(chain, agg_plan);
2423  }
2424  }
2425 
2426  /*
2427  * Now make the real Agg node
2428  */
2429  {
2430  RollupData *rollup = linitial(rollups);
2431  AttrNumber *top_grpColIdx;
2432  int numGroupCols;
2433 
2434  top_grpColIdx = remap_groupColIdx(root, rollup->groupClause);
2435 
2436  numGroupCols = list_length((List *) linitial(rollup->gsets));
2437 
2438  plan = make_agg(build_path_tlist(root, &best_path->path),
2439  best_path->qual,
2440  best_path->aggstrategy,
2442  numGroupCols,
2443  top_grpColIdx,
2446  rollup->gsets,
2447  chain,
2448  rollup->numGroups,
2449  best_path->transitionSpace,
2450  subplan);
2451 
2452  /* Copy cost data from Path to Plan */
2453  copy_generic_path_info(&plan->plan, &best_path->path);
2454  }
2455 
2456  return (Plan *) plan;
2457 }
#define NIL
Definition: pg_list.h:65
Query * parse
Definition: pathnodes.h:161
TargetEntry * get_sortgroupclause_tle(SortGroupClause *sgClause, List *targetList)
Definition: tlist.c:356
List * groupClause
Definition: pathnodes.h:1782
Oid * extract_grouping_collations(List *groupClause, List *tlist)
Definition: tlist.c:478
static AttrNumber * remap_groupColIdx(PlannerInfo *root, List *groupClause)
Definition: createplan.c:2270
Index tleSortGroupRef
Definition: parsenodes.h:1283
bool is_hashed
Definition: pathnodes.h:1787
List * groupingSets
Definition: parsenodes.h:161
Oid * extract_grouping_ops(List *groupClause)
Definition: tlist.c:452
AttrNumber * grouping_map
Definition: pathnodes.h:331
double numGroups
Definition: pathnodes.h:1785
uint64 transitionSpace
Definition: pathnodes.h:1801
static Plan * create_plan_recurse(PlannerInfo *root, Path *best_path, int flags)
Definition: createplan.c:385
static void copy_generic_path_info(Plan *dest, Path *src)
Definition: createplan.c:5269
Agg * make_agg(List *tlist, List *qual, AggStrategy aggstrategy, AggSplit aggsplit, int numGroupCols, AttrNumber *grpColIdx, Oid *grpOperators, Oid *grpCollations, List *groupingSets, List *chain, double dNumGroups, Size transitionSpace, Plan *lefttree)
Definition: createplan.c:6441
#define linitial(l)
Definition: pg_list.h:174
static List * build_path_tlist(PlannerInfo *root, Path *path)
Definition: createplan.c:803
AttrNumber resno
Definition: primnodes.h:1445
static Sort * make_sort_from_groupcols(List *groupcls, AttrNumber *grpColIdx, Plan *lefttree)
Definition: createplan.c:6322
AggStrategy aggstrategy
Definition: pathnodes.h:1798
List * lappend(List *list, void *datum)
Definition: list.c:336
Plan plan
Definition: plannodes.h:858
void * palloc0(Size size)
Definition: mcxt.c:1093
#define CP_LABEL_TLIST
Definition: createplan.c:70
#define Assert(condition)
Definition: c.h:804
#define lfirst(lc)
Definition: pg_list.h:169
static int list_length(const List *l)
Definition: pg_list.h:149
#define for_each_from(cell, lst, N)
Definition: pg_list.h:393
struct Plan * lefttree
Definition: plannodes.h:143
List * targetlist
Definition: plannodes.h:141
AggStrategy
Definition: nodes.h:768
List * groupClause
Definition: parsenodes.h:158
Definition: plannodes.h:856
Definition: pg_list.h:50
int16 AttrNumber
Definition: attnum.h:21
List * gsets
Definition: pathnodes.h:1783

◆ create_hashjoin_plan()

static HashJoin * create_hashjoin_plan ( PlannerInfo root,
HashPath best_path 
)
static

Definition at line 4602 of file createplan.c.

References OpExpr::args, Assert, build_path_tlist(), copy_generic_path_info(), copy_plan_costsize(), CP_SMALL_TLIST, create_plan_recurse(), extract_actual_clauses(), extract_actual_join_clauses(), get_actual_clauses(), get_switched_clauses(), RangeTblEntry::inh, HashPath::inner_rows_total, JoinPath::inner_unique, JoinPath::innerjoinpath, OpExpr::inputcollid, InvalidAttrNumber, InvalidOid, is_opclause(), IS_OUTER_JOIN, IsA, HashJoin::join, JoinPath::joinrestrictinfo, JoinPath::jointype, HashPath::jpath, lappend(), lappend_oid(), lfirst_node, linitial, list_difference(), list_length(), lsecond, make_hash(), make_hashjoin(), NIL, HashPath::num_batches, OpExpr::opno, order_qual_clauses(), JoinPath::outerjoinpath, Plan::parallel_aware, Path::parallel_aware, Path::param_info, Path::parent, JoinPath::path, HashPath::path_hashclauses, Join::plan, Hash::plan, RangeTblEntry::relid, RelOptInfo::relids, replace_nestloop_params(), Hash::rows_total, RTE_RELATION, RangeTblEntry::rtekind, PlannerInfo::simple_rte_array, Plan::startup_cost, Plan::total_cost, RangeQueryClause::var, Var::varattno, and Var::varno.

Referenced by create_join_plan().

4604 {
4605  HashJoin *join_plan;
4606  Hash *hash_plan;
4607  Plan *outer_plan;
4608  Plan *inner_plan;
4609  List *tlist = build_path_tlist(root, &best_path->jpath.path);
4610  List *joinclauses;
4611  List *otherclauses;
4612  List *hashclauses;
4613  List *hashoperators = NIL;
4614  List *hashcollations = NIL;
4615  List *inner_hashkeys = NIL;
4616  List *outer_hashkeys = NIL;
4617  Oid skewTable = InvalidOid;
4618  AttrNumber skewColumn = InvalidAttrNumber;
4619  bool skewInherit = false;
4620  ListCell *lc;
4621 
4622  /*
4623  * HashJoin can project, so we don't have to demand exact tlists from the
4624  * inputs. However, it's best to request a small tlist from the inner
4625  * side, so that we aren't storing more data than necessary. Likewise, if
4626  * we anticipate batching, request a small tlist from the outer side so
4627  * that we don't put extra data in the outer batch files.
4628  */
4629  outer_plan = create_plan_recurse(root, best_path->jpath.outerjoinpath,
4630  (best_path->num_batches > 1) ? CP_SMALL_TLIST : 0);
4631 
4632  inner_plan = create_plan_recurse(root, best_path->jpath.innerjoinpath,
4633  CP_SMALL_TLIST);
4634 
4635  /* Sort join qual clauses into best execution order */
4636  joinclauses = order_qual_clauses(root, best_path->jpath.joinrestrictinfo);
4637  /* There's no point in sorting the hash clauses ... */
4638 
4639  /* Get the join qual clauses (in plain expression form) */
4640  /* Any pseudoconstant clauses are ignored here */
4641  if (IS_OUTER_JOIN(best_path->jpath.jointype))
4642  {
4643  extract_actual_join_clauses(joinclauses,
4644  best_path->jpath.path.parent->relids,
4645  &joinclauses, &otherclauses);
4646  }
4647  else
4648  {
4649  /* We can treat all clauses alike for an inner join */
4650  joinclauses = extract_actual_clauses(joinclauses, false);
4651  otherclauses = NIL;
4652  }
4653 
4654  /*
4655  * Remove the hashclauses from the list of join qual clauses, leaving the
4656  * list of quals that must be checked as qpquals.
4657  */
4658  hashclauses = get_actual_clauses(best_path->path_hashclauses);
4659  joinclauses = list_difference(joinclauses, hashclauses);
4660 
4661  /*
4662  * Replace any outer-relation variables with nestloop params. There
4663  * should not be any in the hashclauses.
4664  */
4665  if (best_path->jpath.path.param_info)
4666  {
4667  joinclauses = (List *)
4668  replace_nestloop_params(root, (Node *) joinclauses);
4669  otherclauses = (List *)
4670  replace_nestloop_params(root, (Node *) otherclauses);
4671  }
4672 
4673  /*
4674  * Rearrange hashclauses, if needed, so that the outer variable is always
4675  * on the left.
4676  */
4677  hashclauses = get_switched_clauses(best_path->path_hashclauses,
4678  best_path->jpath.outerjoinpath->parent->relids);
4679 
4680  /*
4681  * If there is a single join clause and we can identify the outer variable
4682  * as a simple column reference, supply its identity for possible use in
4683  * skew optimization. (Note: in principle we could do skew optimization
4684  * with multiple join clauses, but we'd have to be able to determine the
4685  * most common combinations of outer values, which we don't currently have
4686  * enough stats for.)
4687  */
4688  if (list_length(hashclauses) == 1)
4689  {
4690  OpExpr *clause = (OpExpr *) linitial(hashclauses);
4691  Node *node;
4692 
4693  Assert(is_opclause(clause));
4694  node = (Node *) linitial(clause->args);
4695  if (IsA(node, RelabelType))
4696  node = (Node *) ((RelabelType *) node)->arg;
4697  if (IsA(node, Var))
4698  {
4699  Var *var = (Var *) node;
4700  RangeTblEntry *rte;
4701 
4702  rte = root->simple_rte_array[var->varno];
4703  if (rte->rtekind == RTE_RELATION)
4704  {
4705  skewTable = rte->relid;
4706  skewColumn = var->varattno;
4707  skewInherit = rte->inh;
4708  }
4709  }
4710  }
4711 
4712  /*
4713  * Collect hash related information. The hashed expressions are
4714  * deconstructed into outer/inner expressions, so they can be computed
4715  * separately (inner expressions are used to build the hashtable via Hash,
4716  * outer expressions to perform lookups of tuples from HashJoin's outer
4717  * plan in the hashtable). Also collect operator information necessary to
4718  * build the hashtable.
4719  */
4720  foreach(lc, hashclauses)
4721  {
4722  OpExpr *hclause = lfirst_node(OpExpr, lc);
4723 
4724  hashoperators = lappend_oid(hashoperators, hclause->opno);
4725  hashcollations = lappend_oid(hashcollations, hclause->inputcollid);
4726  outer_hashkeys = lappend(outer_hashkeys, linitial(hclause->args));
4727  inner_hashkeys = lappend(inner_hashkeys, lsecond(hclause->args));
4728  }
4729 
4730  /*
4731  * Build the hash node and hash join node.
4732  */
4733  hash_plan = make_hash(inner_plan,
4734  inner_hashkeys,
4735  skewTable,
4736  skewColumn,
4737  skewInherit);
4738 
4739  /*
4740  * Set Hash node's startup & total costs equal to total cost of input
4741  * plan; this only affects EXPLAIN display not decisions.
4742  */
4743  copy_plan_costsize(&hash_plan->plan, inner_plan);
4744  hash_plan->plan.startup_cost = hash_plan->plan.total_cost;
4745 
4746  /*
4747  * If parallel-aware, the executor will also need an estimate of the total
4748  * number of rows expected from all participants so that it can size the
4749  * shared hash table.
4750  */
4751  if (best_path->jpath.path.parallel_aware)
4752  {
4753  hash_plan->plan.parallel_aware = true;
4754  hash_plan->rows_total = best_path->inner_rows_total;
4755  }
4756 
4757  join_plan = make_hashjoin(tlist,
4758  joinclauses,
4759  otherclauses,
4760  hashclauses,
4761  hashoperators,
4762  hashcollations,
4763  outer_hashkeys,
4764  outer_plan,
4765  (Plan *) hash_plan,
4766  best_path->jpath.jointype,
4767  best_path->jpath.inner_unique);
4768 
4769  copy_generic_path_info(&join_plan->join.plan, &best_path->jpath.path);
4770 
4771  return join_plan;
4772 }
double rows_total
Definition: plannodes.h:975
#define NIL
Definition: pg_list.h:65
#define IsA(nodeptr, _type_)
Definition: nodes.h:590
JoinPath jpath
Definition: pathnodes.h:1656
static Node * replace_nestloop_params(PlannerInfo *root, Node *expr)
Definition: createplan.c:4791
static List * get_switched_clauses(List *clauses, Relids outerrelids)
Definition: createplan.c:5098
int num_batches
Definition: pathnodes.h:1658
void extract_actual_join_clauses(List *restrictinfo_list, Relids joinrelids, List **joinquals, List **otherquals)
Definition: restrictinfo.c:470
Path * innerjoinpath
Definition: pathnodes.h:1583
static Hash * make_hash(Plan *lefttree, List *hashkeys, Oid skewTable, AttrNumber skewColumn, bool skewInherit)
Definition: createplan.c:5859
#define IS_OUTER_JOIN(jointype)
Definition: nodes.h:755
ParamPathInfo * param_info
Definition: pathnodes.h:1177
#define CP_SMALL_TLIST
Definition: createplan.c:69
Definition: nodes.h:539
List * get_actual_clauses(List *restrictinfo_list)
Definition: restrictinfo.c:420
AttrNumber varattno
Definition: primnodes.h:191
static List * order_qual_clauses(PlannerInfo *root, List *clauses)
Definition: createplan.c:5175
unsigned int Oid
Definition: postgres_ext.h:31
Definition: primnodes.h:186
List * lappend_oid(List *list, Oid datum)
Definition: list.c:372
double inner_rows_total
Definition: pathnodes.h:1659
#define lsecond(l)
Definition: pg_list.h:179
Join join
Definition: plannodes.h:761
static Plan * create_plan_recurse(PlannerInfo *root, Path *best_path, int flags)
Definition: createplan.c:385
static void copy_generic_path_info(Plan *dest, Path *src)
Definition: createplan.c:5269
#define linitial(l)
Definition: pg_list.h:174
static List * build_path_tlist(PlannerInfo *root, Path *path)
Definition: createplan.c:803
List * joinrestrictinfo
Definition: pathnodes.h:1585
RelOptInfo * parent
Definition: pathnodes.h:1174
#define lfirst_node(type, lc)
Definition: pg_list.h:172
Cost startup_cost
Definition: plannodes.h:117
static void copy_plan_costsize(Plan *dest, Plan *src)
Definition: createplan.c:5284
bool parallel_aware
Definition: plannodes.h:129
Relids relids
Definition: pathnodes.h:676
List * lappend(List *list, void *datum)
Definition: list.c:336
RangeTblEntry ** simple_rte_array
Definition: pathnodes.h:193
Index varno
Definition: primnodes.h:189
Path * outerjoinpath
Definition: pathnodes.h:1582
#define InvalidOid
Definition: postgres_ext.h:36
Path path
Definition: pathnodes.h:1575
#define Assert(condition)
Definition: c.h:804
static HashJoin * make_hashjoin(List *tlist, List *joinclauses, List *otherclauses, List *hashclauses, List *hashoperators, List *hashcollations, List *hashkeys, Plan *lefttree, Plan *righttree, JoinType jointype, bool inner_unique)
Definition: createplan.c:5828
static int list_length(const List *l)
Definition: pg_list.h:149
List * extract_actual_clauses(List *restrictinfo_list, bool pseudoconstant)
Definition: restrictinfo.c:443
Oid inputcollid
Definition: primnodes.h:547
bool inner_unique
Definition: pathnodes.h:1579
List * list_difference(const List *list1, const List *list2)
Definition: list.c:1091
#define InvalidAttrNumber
Definition: attnum.h:23
RTEKind rtekind
Definition: parsenodes.h:995
Plan plan
Definition: plannodes.h:964
JoinType jointype
Definition: pathnodes.h:1577
Cost total_cost
Definition: plannodes.h:118
bool parallel_aware
Definition: pathnodes.h:1179
List * path_hashclauses
Definition: pathnodes.h:1657
Oid opno
Definition: primnodes.h:542
static bool is_opclause(const void *clause)
Definition: nodeFuncs.h:66
List * args
Definition: primnodes.h:548
Definition: pg_list.h:50
int16 AttrNumber
Definition: attnum.h:21
Plan plan
Definition: plannodes.h:702

◆ create_incrementalsort_plan()

static IncrementalSort * create_incrementalsort_plan ( PlannerInfo root,
IncrementalSortPath best_path,
int  flags 
)
static

Definition at line 2130 of file createplan.c.

References copy_generic_path_info(), CP_SMALL_TLIST, create_plan_recurse(), IS_OTHER_REL, make_incrementalsort_from_pathkeys(), IncrementalSortPath::nPresortedCols, Path::parent, SortPath::path, Path::pathkeys, Sort::plan, RelOptInfo::relids, IncrementalSort::sort, IncrementalSortPath::spath, and SortPath::subpath.

Referenced by create_plan_recurse().

2132 {
2133  IncrementalSort *plan;
2134  Plan *subplan;
2135 
2136  /* See comments in create_sort_plan() above */
2137  subplan = create_plan_recurse(root, best_path->spath.subpath,
2138  flags | CP_SMALL_TLIST);
2139  plan = make_incrementalsort_from_pathkeys(subplan,
2140  best_path->spath.path.pathkeys,
2141  IS_OTHER_REL(best_path->spath.subpath->parent) ?
2142  best_path->spath.path.parent->relids : NULL,
2143  best_path->nPresortedCols);
2144 
2145  copy_generic_path_info(&plan->sort.plan, (Path *) best_path);
2146 
2147  return plan;
2148 }
Path * subpath
Definition: pathnodes.h:1705
Plan plan
Definition: plannodes.h:809
#define IS_OTHER_REL(rel)
Definition: pathnodes.h:664
#define CP_SMALL_TLIST
Definition: createplan.c:69
static Plan * create_plan_recurse(PlannerInfo *root, Path *best_path, int flags)
Definition: createplan.c:385
static void copy_generic_path_info(Plan *dest, Path *src)
Definition: createplan.c:5269
RelOptInfo * parent
Definition: pathnodes.h:1174
static IncrementalSort * make_incrementalsort_from_pathkeys(Plan *lefttree, List *pathkeys, Relids relids, int nPresortedCols)
Definition: createplan.c:6239
Relids relids
Definition: pathnodes.h:676
List * pathkeys
Definition: pathnodes.h:1188
Path path
Definition: pathnodes.h:1704

◆ create_indexscan_plan()

static Scan * create_indexscan_plan ( PlannerInfo root,
IndexPath best_path,
List tlist,
List scan_clauses,
bool  indexonly 
)
static

Definition at line 2921 of file createplan.c.

References Assert, RestrictInfo::clause, contain_mutable_functions(), copy_generic_path_info(), elog, ERROR, exprType(), extract_actual_clauses(), fix_indexorderby_references(), fix_indexqual_references(), forboth, get_opfamily_member(), IndexPath::indexclauses, IndexPath::indexinfo, IndexOptInfo::indexoid, IndexPath::indexorderbys, IndexPath::indexscandir, IndexOptInfo::indextlist, is_redundant_with_indexclauses(), lappend(), lappend_oid(), lfirst, lfirst_node, list_length(), list_make1, make_indexonlyscan(), make_indexscan(), NIL, OidIsValid, order_qual_clauses(), Path::param_info, Path::parent, IndexPath::path, Path::pathkeys, PathKey::pk_opfamily, PathKey::pk_strategy, Scan::plan, predicate_implied_by(), RestrictInfo::pseudoconstant, RelOptInfo::relid, replace_nestloop_params(), RTE_RELATION, and RelOptInfo::rtekind.

Referenced by create_bitmap_subplan(), and create_scan_plan().

2926 {
2927  Scan *scan_plan;
2928  List *indexclauses = best_path->indexclauses;
2929  List *indexorderbys = best_path->indexorderbys;
2930  Index baserelid = best_path->path.parent->relid;
2931  Oid indexoid = best_path->indexinfo->indexoid;
2932  List *qpqual;
2933  List *stripped_indexquals;
2934  List *fixed_indexquals;
2935  List *fixed_indexorderbys;
2936  List *indexorderbyops = NIL;
2937  ListCell *l;
2938 
2939  /* it should be a base rel... */
2940  Assert(baserelid > 0);
2941  Assert(best_path->path.parent->rtekind == RTE_RELATION);
2942 
2943  /*
2944  * Extract the index qual expressions (stripped of RestrictInfos) from the
2945  * IndexClauses list, and prepare a copy with index Vars substituted for
2946  * table Vars. (This step also does replace_nestloop_params on the
2947  * fixed_indexquals.)
2948  */
2949  fix_indexqual_references(root, best_path,
2950  &stripped_indexquals,
2951  &fixed_indexquals);
2952 
2953  /*
2954  * Likewise fix up index attr references in the ORDER BY expressions.
2955  */
2956  fixed_indexorderbys = fix_indexorderby_references(root, best_path);
2957 
2958  /*
2959  * The qpqual list must contain all restrictions not automatically handled
2960  * by the index, other than pseudoconstant clauses which will be handled
2961  * by a separate gating plan node. All the predicates in the indexquals
2962  * will be checked (either by the index itself, or by nodeIndexscan.c),
2963  * but if there are any "special" operators involved then they must be
2964  * included in qpqual. The upshot is that qpqual must contain
2965  * scan_clauses minus whatever appears in indexquals.
2966  *
2967  * is_redundant_with_indexclauses() detects cases where a scan clause is
2968  * present in the indexclauses list or is generated from the same
2969  * EquivalenceClass as some indexclause, and is therefore redundant with
2970  * it, though not equal. (The latter happens when indxpath.c prefers a
2971  * different derived equality than what generate_join_implied_equalities
2972  * picked for a parameterized scan's ppi_clauses.) Note that it will not
2973  * match to lossy index clauses, which is critical because we have to
2974  * include the original clause in qpqual in that case.
2975  *
2976  * In some situations (particularly with OR'd index conditions) we may
2977  * have scan_clauses that are not equal to, but are logically implied by,
2978  * the index quals; so we also try a predicate_implied_by() check to see
2979  * if we can discard quals that way. (predicate_implied_by assumes its
2980  * first input contains only immutable functions, so we have to check
2981  * that.)
2982  *
2983  * Note: if you change this bit of code you should also look at
2984  * extract_nonindex_conditions() in costsize.c.
2985  */
2986  qpqual = NIL;
2987  foreach(l, scan_clauses)
2988  {
2989  RestrictInfo *rinfo = lfirst_node(RestrictInfo, l);
2990 
2991  if (rinfo->pseudoconstant)
2992  continue; /* we may drop pseudoconstants here */
2993  if (is_redundant_with_indexclauses(rinfo, indexclauses))
2994  continue; /* dup or derived from same EquivalenceClass */
2995  if (!contain_mutable_functions((Node *) rinfo->clause) &&
2996  predicate_implied_by(list_make1(rinfo->clause), stripped_indexquals,
2997  false))
2998  continue; /* provably implied by indexquals */
2999  qpqual = lappend(qpqual, rinfo);
3000  }
3001 
3002  /* Sort clauses into best execution order */
3003  qpqual = order_qual_clauses(root, qpqual);
3004 
3005  /* Reduce RestrictInfo list to bare expressions; ignore pseudoconstants */
3006  qpqual = extract_actual_clauses(qpqual, false);
3007 
3008  /*
3009  * We have to replace any outer-relation variables with nestloop params in
3010  * the indexqualorig, qpqual, and indexorderbyorig expressions. A bit
3011  * annoying to have to do this separately from the processing in
3012  * fix_indexqual_references --- rethink this when generalizing the inner
3013  * indexscan support. But note we can't really do this earlier because
3014  * it'd break the comparisons to predicates above ... (or would it? Those
3015  * wouldn't have outer refs)
3016  */
3017  if (best_path->path.param_info)
3018  {
3019  stripped_indexquals = (List *)
3020  replace_nestloop_params(root, (Node *) stripped_indexquals);
3021  qpqual = (List *)
3022  replace_nestloop_params(root, (Node *) qpqual);
3023  indexorderbys = (List *)
3024  replace_nestloop_params(root, (Node *) indexorderbys);
3025  }
3026 
3027  /*
3028  * If there are ORDER BY expressions, look up the sort operators for their
3029  * result datatypes.
3030  */
3031  if (indexorderbys)
3032  {
3033  ListCell *pathkeyCell,
3034  *exprCell;
3035 
3036  /*
3037  * PathKey contains OID of the btree opfamily we're sorting by, but
3038  * that's not quite enough because we need the expression's datatype
3039  * to look up the sort operator in the operator family.
3040  */
3041  Assert(list_length(best_path->path.pathkeys) == list_length(indexorderbys));
3042  forboth(pathkeyCell, best_path->path.pathkeys, exprCell, indexorderbys)
3043  {
3044  PathKey *pathkey = (PathKey *) lfirst(pathkeyCell);
3045  Node *expr = (Node *) lfirst(exprCell);
3046  Oid exprtype = exprType(expr);
3047  Oid sortop;
3048 
3049  /* Get sort operator from opfamily */
3050  sortop = get_opfamily_member(pathkey->pk_opfamily,
3051  exprtype,
3052  exprtype,
3053  pathkey->pk_strategy);
3054  if (!OidIsValid(sortop))
3055  elog(ERROR, "missing operator %d(%u,%u) in opfamily %u",
3056  pathkey->pk_strategy, exprtype, exprtype, pathkey->pk_opfamily);
3057  indexorderbyops = lappend_oid(indexorderbyops, sortop);
3058  }
3059  }
3060 
3061  /* Finally ready to build the plan node */
3062  if (indexonly)
3063  scan_plan = (Scan *) make_indexonlyscan(tlist,
3064  qpqual,
3065  baserelid,
3066  indexoid,
3067  fixed_indexquals,
3068  fixed_indexorderbys,
3069  best_path->indexinfo->indextlist,
3070  best_path->indexscandir);
3071  else
3072  scan_plan = (Scan *) make_indexscan(tlist,
3073  qpqual,
3074  baserelid,
3075  indexoid,
3076  fixed_indexquals,
3077  stripped_indexquals,
3078  fixed_indexorderbys,
3079  indexorderbys,
3080  indexorderbyops,
3081  best_path->indexscandir);
3082 
3083  copy_generic_path_info(&scan_plan->plan, &best_path->path);
3084 
3085  return scan_plan;
3086 }
#define NIL
Definition: pg_list.h:65
Plan plan
Definition: plannodes.h:342
static Node * replace_nestloop_params(PlannerInfo *root, Node *expr)
Definition: createplan.c:4791
#define forboth(cell1, list1, cell2, list2)
Definition: pg_list.h:446
Path path
Definition: pathnodes.h:1236
IndexOptInfo * indexinfo
Definition: pathnodes.h:1237
List * indextlist
Definition: pathnodes.h:858
bool pseudoconstant
Definition: pathnodes.h:2053
ParamPathInfo * param_info
Definition: pathnodes.h:1177
Definition: nodes.h:539
static List * order_qual_clauses(PlannerInfo *root, List *clauses)
Definition: createplan.c:5175
List * indexclauses
Definition: pathnodes.h:1238
unsigned int Oid
Definition: postgres_ext.h:31
List * lappend_oid(List *list, Oid datum)
Definition: list.c:372
#define OidIsValid(objectId)
Definition: c.h:710
int pk_strategy
Definition: pathnodes.h:1060
#define list_make1(x1)
Definition: pg_list.h:206
static void copy_generic_path_info(Plan *dest, Path *src)
Definition: createplan.c:5269
#define ERROR
Definition: elog.h:46
static IndexScan * make_indexscan(List *qptlist, List *qpqual, Index scanrelid, Oid indexid, List *indexqual, List *indexqualorig, List *indexorderby, List *indexorderbyorig, List *indexorderbyops, ScanDirection indexscandir)
Definition: createplan.c:5404
RelOptInfo * parent
Definition: pathnodes.h:1174
bool is_redundant_with_indexclauses(RestrictInfo *rinfo, List *indexclauses)
Definition: equivclass.c:3176
#define lfirst_node(type, lc)
Definition: pg_list.h:172
Oid get_opfamily_member(Oid opfamily, Oid lefttype, Oid righttype, int16 strategy)
Definition: lsyscache.c:164
static List * fix_indexorderby_references(PlannerInfo *root, IndexPath *index_path)
Definition: createplan.c:4923
Index relid
Definition: pathnodes.h:704
List * lappend(List *list, void *datum)
Definition: list.c:336
Expr * clause
Definition: pathnodes.h:2045
List * indexorderbys
Definition: pathnodes.h:1239
unsigned int Index
Definition: c.h:549
RTEKind rtekind
Definition: pathnodes.h:706
List * pathkeys
Definition: pathnodes.h:1188
static IndexOnlyScan * make_indexonlyscan(List *qptlist, List *qpqual, Index scanrelid, Oid indexid, List *indexqual, List *indexorderby, List *indextlist, ScanDirection indexscandir)
Definition: createplan.c:5435
#define Assert(condition)
Definition: c.h:804
#define lfirst(lc)
Definition: pg_list.h:169
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:41
static int list_length(const List *l)
Definition: pg_list.h:149
List * extract_actual_clauses(List *restrictinfo_list, bool pseudoconstant)
Definition: restrictinfo.c:443
Oid pk_opfamily
Definition: pathnodes.h:1059
ScanDirection indexscandir
Definition: pathnodes.h:1241
static void fix_indexqual_references(PlannerInfo *root, IndexPath *index_path, List **stripped_indexquals_p, List **fixed_indexquals_p)
Definition: createplan.c:4882
#define elog(elevel,...)
Definition: elog.h:232
bool contain_mutable_functions(Node *clause)
Definition: clauses.c:359
bool predicate_implied_by(List *predicate_list, List *clause_list, bool weak)
Definition: predtest.c:151
Definition: pg_list.h:50

◆ create_join_plan()

static Plan * create_join_plan ( PlannerInfo root,
JoinPath best_path 
)
static

Definition at line 1043 of file createplan.c.

References create_gating_plan(), create_hashjoin_plan(), create_mergejoin_plan(), create_nestloop_plan(), elog, ERROR, get_actual_clauses(), get_gating_quals(), JoinPath::joinrestrictinfo, list_concat(), NIL, JoinPath::path, Path::pathtype, T_HashJoin, T_MergeJoin, and T_NestLoop.

Referenced by create_plan_recurse().

1044 {
1045  Plan *plan;
1046  List *gating_clauses;
1047 
1048  switch (best_path->path.pathtype)
1049  {
1050  case T_MergeJoin:
1051  plan = (Plan *) create_mergejoin_plan(root,
1052  (MergePath *) best_path);
1053  break;
1054  case T_HashJoin:
1055  plan = (Plan *) create_hashjoin_plan(root,
1056  (HashPath *) best_path);
1057  break;
1058  case T_NestLoop:
1059  plan = (Plan *) create_nestloop_plan(root,
1060  (NestPath *) best_path);
1061  break;
1062  default:
1063  elog(ERROR, "unrecognized node type: %d",
1064  (int) best_path->path.pathtype);
1065  plan = NULL; /* keep compiler quiet */
1066  break;
1067  }
1068 
1069  /*
1070  * If there are any pseudoconstant clauses attached to this node, insert a
1071  * gating Result node that evaluates the pseudoconstants as one-time
1072  * quals.
1073  */
1074  gating_clauses = get_gating_quals(root, best_path->joinrestrictinfo);
1075  if (gating_clauses)
1076  plan = create_gating_plan(root, (Path *) best_path, plan,
1077  gating_clauses);
1078 
1079 #ifdef NOT_USED
1080 
1081  /*
1082  * * Expensive function pullups may have pulled local predicates * into
1083  * this path node. Put them in the qpqual of the plan node. * JMH,
1084  * 6/15/92
1085  */
1086  if (get_loc_restrictinfo(best_path) != NIL)
1087  set_qpqual((Plan) plan,
1088  list_concat(get_qpqual((Plan) plan),
1089  get_actual_clauses(get_loc_restrictinfo(best_path))));
1090 #endif
1091 
1092  return plan;
1093 }
#define NIL
Definition: pg_list.h:65
List * get_actual_clauses(List *restrictinfo_list)
Definition: restrictinfo.c:420
List * list_concat(List *list1, const List *list2)
Definition: list.c:530
static NestLoop * create_nestloop_plan(PlannerInfo *root, NestPath *best_path)
Definition: createplan.c:4219
NodeTag pathtype
Definition: pathnodes.h:1172
#define ERROR
Definition: elog.h:46
List * joinrestrictinfo
Definition: pathnodes.h:1585
Path path
Definition: pathnodes.h:1575
static HashJoin * create_hashjoin_plan(PlannerInfo *root, HashPath *best_path)
Definition: createplan.c:4602
static Plan * create_gating_plan(PlannerInfo *root, Path *path, Plan *plan, List *gating_quals)
Definition: createplan.c:984
#define elog(elevel,...)
Definition: elog.h:232
static MergeJoin * create_mergejoin_plan(PlannerInfo *root, MergePath *best_path)
Definition: createplan.c:4295
Definition: pg_list.h:50
static List * get_gating_quals(PlannerInfo *root, List *quals)
Definition: createplan.c:964

◆ create_limit_plan()

static Limit * create_limit_plan ( PlannerInfo root,
LimitPath best_path,
int  flags 
)
static

Definition at line 2771 of file createplan.c.

References copy_generic_path_info(), create_plan_recurse(), SortGroupClause::eqop, TargetEntry::expr, exprCollation(), get_sortgroupclause_tle(), lfirst, LIMIT_OPTION_WITH_TIES, LimitPath::limitCount, LimitPath::limitOffset, LimitPath::limitOption, list_length(), make_limit(), palloc(), parse(), PlannerInfo::parse, Limit::plan, TargetEntry::resno, Query::sortClause, LimitPath::subpath, and Query::targetList.

Referenced by create_plan_recurse().

2772 {
2773  Limit *plan;
2774  Plan *subplan;
2775  int numUniqkeys = 0;
2776  AttrNumber *uniqColIdx = NULL;
2777  Oid *uniqOperators = NULL;
2778  Oid *uniqCollations = NULL;
2779 
2780  /* Limit doesn't project, so tlist requirements pass through */
2781  subplan = create_plan_recurse(root, best_path->subpath, flags);
2782 
2783  /* Extract information necessary for comparing rows for WITH TIES. */
2784  if (best_path->limitOption == LIMIT_OPTION_WITH_TIES)
2785  {
2786  Query *parse = root->parse;
2787  ListCell *l;
2788 
2789  numUniqkeys = list_length(parse->sortClause);
2790  uniqColIdx = (AttrNumber *) palloc(numUniqkeys * sizeof(AttrNumber));
2791  uniqOperators = (Oid *) palloc(numUniqkeys * sizeof(Oid));
2792  uniqCollations = (Oid *) palloc(numUniqkeys * sizeof(Oid));
2793 
2794  numUniqkeys = 0;
2795  foreach(l, parse->sortClause)
2796  {
2797  SortGroupClause *sortcl = (SortGroupClause *) lfirst(l);
2798  TargetEntry *tle = get_sortgroupclause_tle(sortcl, parse->targetList);
2799 
2800  uniqColIdx[numUniqkeys] = tle->resno;
2801  uniqOperators[numUniqkeys] = sortcl->eqop;
2802  uniqCollations[numUniqkeys] = exprCollation((Node *) tle->expr);
2803  numUniqkeys++;
2804  }
2805  }
2806 
2807  plan = make_limit(subplan,
2808  best_path->limitOffset,
2809  best_path->limitCount,
2810  best_path->limitOption,
2811  numUniqkeys, uniqColIdx, uniqOperators, uniqCollations);
2812 
2813  copy_generic_path_info(&plan->plan, (Path *) best_path);
2814 
2815  return plan;
2816 }
Query * parse
Definition: pathnodes.h:161
LimitOption limitOption
Definition: pathnodes.h:1897
TargetEntry * get_sortgroupclause_tle(SortGroupClause *sgClause, List *targetList)
Definition: tlist.c:356
Plan plan
Definition: plannodes.h:1022
Node * limitOffset
Definition: pathnodes.h:1895
List * sortClause
Definition: parsenodes.h:169
Definition: nodes.h:539
unsigned int Oid
Definition: postgres_ext.h:31
List * targetList
Definition: parsenodes.h:150
static Plan * create_plan_recurse(PlannerInfo *root, Path *best_path, int flags)
Definition: createplan.c:385
static void copy_generic_path_info(Plan *dest, Path *src)
Definition: createplan.c:5269
Path * subpath
Definition: pathnodes.h:1894
AttrNumber resno
Definition: primnodes.h:1445
Limit * make_limit(Plan *lefttree, Node *limitOffset, Node *limitCount, LimitOption limitOption, int uniqNumCols, AttrNumber *uniqColIdx, Oid *uniqOperators, Oid *uniqCollations)
Definition: createplan.c:6805
#define lfirst(lc)
Definition: pg_list.h:169
Expr * expr
Definition: primnodes.h:1444
static int list_length(const List *l)
Definition: pg_list.h:149
Oid exprCollation(const Node *expr)
Definition: nodeFuncs.c:759
void * palloc(Size size)
Definition: mcxt.c:1062
Node * limitCount
Definition: pathnodes.h:1896
int16 AttrNumber
Definition: attnum.h:21
static struct subre * parse(struct vars *, int, int, struct state *, struct state *)
Definition: regcomp.c:666

◆ create_lockrows_plan()

static LockRows * create_lockrows_plan ( PlannerInfo root,
LockRowsPath best_path,
int  flags 
)
static

Definition at line 2709 of file createplan.c.

References copy_generic_path_info(), create_plan_recurse(), LockRowsPath::epqParam, make_lockrows(), LockRows::plan, LockRowsPath::rowMarks, and LockRowsPath::subpath.

Referenced by create_plan_recurse().

2711 {
2712  LockRows *plan;
2713  Plan *subplan;
2714 
2715  /* LockRows doesn't project, so tlist requirements pass through */
2716  subplan = create_plan_recurse(root, best_path->subpath, flags);
2717 
2718  plan = make_lockrows(subplan, best_path->rowMarks, best_path->epqParam);
2719 
2720  copy_generic_path_info(&plan->plan, (Path *) best_path);
2721 
2722  return plan;
2723 }
Plan plan
Definition: plannodes.h:1008
List * rowMarks
Definition: pathnodes.h:1859
static Plan * create_plan_recurse(PlannerInfo *root, Path *best_path, int flags)
Definition: createplan.c:385
static void copy_generic_path_info(Plan *dest, Path *src)
Definition: createplan.c:5269
Path * subpath
Definition: pathnodes.h:1858
static LockRows * make_lockrows(Plan *lefttree, List *rowMarks, int epqParam)
Definition: createplan.c:6784

◆ create_material_plan()

static Material * create_material_plan ( PlannerInfo root,
MaterialPath best_path,
int  flags 
)
static

Definition at line 1559 of file createplan.c.

References copy_generic_path_info(), CP_SMALL_TLIST, create_plan_recurse(), make_material(), Material::plan, and MaterialPath::subpath.

Referenced by create_plan_recurse().

1560 {
1561  Material *plan;
1562  Plan *subplan;
1563 
1564  /*
1565  * We don't want any excess columns in the materialized tuples, so request
1566  * a smaller tlist. Otherwise, since Material doesn't project, tlist
1567  * requirements pass through.
1568  */
1569  subplan = create_plan_recurse(root, best_path->subpath,
1570  flags | CP_SMALL_TLIST);
1571 
1572  plan = make_material(subplan);
1573 
1574  copy_generic_path_info(&plan->plan, (Path *) best_path);
1575 
1576  return plan;
1577 }
#define CP_SMALL_TLIST
Definition: createplan.c:69
Path * subpath
Definition: pathnodes.h:1494
static Plan * create_plan_recurse(PlannerInfo *root, Path *best_path, int flags)
Definition: createplan.c:385
static Material * make_material(Plan *lefttree)
Definition: createplan.c:6363
static void copy_generic_path_info(Plan *dest, Path *src)
Definition: createplan.c:5269
Plan plan
Definition: plannodes.h:779

◆ create_merge_append_plan()

static Plan * create_merge_append_plan ( PlannerInfo root,
MergeAppendPath best_path,
int  flags 
)
static

Definition at line 1350 of file createplan.c.

References MergeAppend::apprelids, Assert, RelOptInfo::baserestrictinfo, build_path_tlist(), MergeAppend::collations, copy_generic_path_info(), CP_EXACT_TLIST, CP_SMALL_TLIST, create_plan_recurse(), elog, enable_partition_pruning, ERROR, extract_actual_clauses(), inject_projection_plan(), label_sort_with_costsize(), lappend(), Plan::lefttree, lfirst, list_concat(), list_copy(), list_length(), list_truncate(), make_partition_pruneinfo(), make_sort(), makeNode, MergeAppend::mergeplans, NIL, MergeAppend::nullsFirst, MergeAppend::numCols, Plan::parallel_safe, Path::param_info, Path::parent, MergeAppend::part_prune_info, MergeAppendPath::path, Path::pathkeys, pathkeys_contained_in(), MergeAppend::plan, ParamPathInfo::ppi_clauses, prepare_sort_from_pathkeys(), Plan::qual, RelOptInfo::relids, replace_nestloop_params(), Plan::righttree, sort(), MergeAppend::sortColIdx, MergeAppend::sortOperators, subpath(), and Plan::targetlist.

Referenced by create_plan_recurse().

1352 {
1353  MergeAppend *node = makeNode(MergeAppend);
1354  Plan *plan = &node->plan;
1355  List *tlist = build_path_tlist(root, &best_path->path);
1356  int orig_tlist_length = list_length(tlist);
1357  bool tlist_was_changed;
1358  List *pathkeys = best_path->path.pathkeys;
1359  List *subplans = NIL;
1360  ListCell *subpaths;
1361  RelOptInfo *rel = best_path->path.parent;
1362  PartitionPruneInfo *partpruneinfo = NULL;
1363 
1364  /*
1365  * We don't have the actual creation of the MergeAppend node split out
1366  * into a separate make_xxx function. This is because we want to run
1367  * prepare_sort_from_pathkeys on it before we do so on the individual
1368  * child plans, to make cross-checking the sort info easier.
1369  */
1370  copy_generic_path_info(plan, (Path *) best_path);
1371  plan->targetlist = tlist;
1372  plan->qual = NIL;
1373  plan->lefttree = NULL;
1374  plan->righttree = NULL;
1375  node->apprelids = rel->relids;
1376 
1377  /*
1378  * Compute sort column info, and adjust MergeAppend's tlist as needed.
1379  * Because we pass adjust_tlist_in_place = true, we may ignore the
1380  * function result; it must be the same plan node. However, we then need
1381  * to detect whether any tlist entries were added.
1382  */
1383  (void) prepare_sort_from_pathkeys(plan, pathkeys,
1384  best_path->path.parent->relids,
1385  NULL,
1386  true,
1387  &node->numCols,
1388  &node->sortColIdx,
1389  &node->sortOperators,
1390  &node->collations,
1391  &node->nullsFirst);
1392  tlist_was_changed = (orig_tlist_length != list_length(plan->targetlist));
1393 
1394  /*
1395  * Now prepare the child plans. We must apply prepare_sort_from_pathkeys
1396  * even to subplans that don't need an explicit sort, to make sure they
1397  * are returning the same sort key columns the MergeAppend expects.
1398  */
1399  foreach(subpaths, best_path->subpaths)
1400  {
1401  Path *subpath = (Path *) lfirst(subpaths);
1402  Plan *subplan;
1403  int numsortkeys;
1404  AttrNumber *sortColIdx;
1405  Oid *sortOperators;
1406  Oid *collations;
1407  bool *nullsFirst;
1408 
1409  /* Build the child plan */
1410  /* Must insist that all children return the same tlist */
1411  subplan = create_plan_recurse(root, subpath, CP_EXACT_TLIST);
1412 
1413  /* Compute sort column info, and adjust subplan's tlist as needed */
1414  subplan = prepare_sort_from_pathkeys(subplan, pathkeys,
1415  subpath->parent->relids,
1416  node->sortColIdx,
1417  false,
1418  &numsortkeys,
1419  &sortColIdx,
1420  &sortOperators,
1421  &collations,
1422  &nullsFirst);
1423 
1424  /*
1425  * Check that we got the same sort key information. We just Assert
1426  * that the sortops match, since those depend only on the pathkeys;
1427  * but it seems like a good idea to check the sort column numbers
1428  * explicitly, to ensure the tlists really do match up.
1429  */
1430  Assert(numsortkeys == node->numCols);
1431  if (memcmp(sortColIdx, node->sortColIdx,
1432  numsortkeys * sizeof(AttrNumber)) != 0)
1433  elog(ERROR, "MergeAppend child's targetlist doesn't match MergeAppend");
1434  Assert(memcmp(sortOperators, node->sortOperators,
1435  numsortkeys * sizeof(Oid)) == 0);
1436  Assert(memcmp(collations, node->collations,
1437  numsortkeys * sizeof(Oid)) == 0);
1438  Assert(memcmp(nullsFirst, node->nullsFirst,
1439  numsortkeys * sizeof(bool)) == 0);
1440 
1441  /* Now, insert a Sort node if subplan isn't sufficiently ordered */
1442  if (!pathkeys_contained_in(pathkeys, subpath->pathkeys))
1443  {
1444  Sort *sort = make_sort(subplan, numsortkeys,
1445  sortColIdx, sortOperators,
1446  collations, nullsFirst);
1447 
1448  label_sort_with_costsize(root, sort, best_path->limit_tuples);
1449  subplan = (Plan *) sort;
1450  }
1451 
1452  subplans = lappend(subplans, subplan);
1453  }
1454 
1455  /*
1456  * If any quals exist, they may be useful to perform further partition
1457  * pruning during execution. Gather information needed by the executor to
1458  * do partition pruning.
1459  */
1461  {
1462  List *prunequal;
1463 
1464  prunequal = extract_actual_clauses(rel->baserestrictinfo, false);
1465 
1466  if (best_path->path.param_info)
1467  {
1468  List *prmquals = best_path->path.param_info->ppi_clauses;
1469 
1470  prmquals = extract_actual_clauses(prmquals, false);
1471  prmquals = (List *) replace_nestloop_params(root,
1472  (Node *) prmquals);
1473 
1474  prunequal = list_concat(prunequal, prmquals);
1475  }
1476 
1477  if (prunequal != NIL)
1478  partpruneinfo = make_partition_pruneinfo(root, rel,
1479  best_path->subpaths,
1480  prunequal);
1481  }
1482 
1483  node->mergeplans = subplans;
1484  node->part_prune_info = partpruneinfo;
1485 
1486  /*
1487  * If prepare_sort_from_pathkeys added sort columns, but we were told to
1488  * produce either the exact tlist or a narrow tlist, we should get rid of
1489  * the sort columns again. We must inject a projection node to do so.
1490  */
1491  if (tlist_was_changed && (flags & (CP_EXACT_TLIST | CP_SMALL_TLIST)))
1492  {
1493  tlist = list_truncate(list_copy(plan->targetlist), orig_tlist_length);
1494  return inject_projection_plan(plan, tlist, plan->parallel_safe);
1495  }
1496  else
1497  return plan;
1498 }
#define NIL
Definition: pg_list.h:65
List * qual
Definition: plannodes.h:142
static Node * replace_nestloop_params(PlannerInfo *root, Node *expr)
Definition: createplan.c:4791
Oid * collations
Definition: plannodes.h:279
List * baserestrictinfo
Definition: pathnodes.h:740
List * list_truncate(List *list, int new_size)
Definition: list.c:600
ParamPathInfo * param_info
Definition: pathnodes.h:1177
#define CP_SMALL_TLIST
Definition: createplan.c:69
List * list_copy(const List *oldlist)
Definition: list.c:1418
Definition: nodes.h:539
List * list_concat(List *list1, const List *list2)
Definition: list.c:530
struct PartitionPruneInfo * part_prune_info
Definition: plannodes.h:282
unsigned int Oid
Definition: postgres_ext.h:31
static Plan * create_plan_recurse(PlannerInfo *root, Path *best_path, int flags)
Definition: createplan.c:385
struct Plan * righttree
Definition: plannodes.h:144
static void copy_generic_path_info(Plan *dest, Path *src)
Definition: createplan.c:5269
#define ERROR
Definition: elog.h:46
static List * build_path_tlist(PlannerInfo *root, Path *path)
Definition: createplan.c:803
RelOptInfo * parent
Definition: pathnodes.h:1174
Datum sort(PG_FUNCTION_ARGS)
Definition: _int_op.c:195
Relids relids
Definition: pathnodes.h:676
List * lappend(List *list, void *datum)
Definition: list.c:336
Bitmapset * apprelids
Definition: plannodes.h:273
bool pathkeys_contained_in(List *keys1, List *keys2)
Definition: pathkeys.c:324
bool enable_partition_pruning
Definition: costsize.c:151
List * pathkeys
Definition: pathnodes.h:1188
static Sort * make_sort(Plan *lefttree, int numCols, AttrNumber *sortColIdx, Oid *sortOperators, Oid *collations, bool *nullsFirst)
Definition: createplan.c:5923
#define makeNode(_type_)
Definition: nodes.h:587
#define Assert(condition)
Definition: c.h:804
#define lfirst(lc)
Definition: pg_list.h:169
AttrNumber * sortColIdx
Definition: plannodes.h:277
List * ppi_clauses
Definition: pathnodes.h:1135
static Plan * inject_projection_plan(Plan *subplan, List *tlist, bool parallel_safe)
Definition: createplan.c:2036
static int list_length(const List *l)
Definition: pg_list.h:149
List * extract_actual_clauses(List *restrictinfo_list, bool pseudoconstant)
Definition: restrictinfo.c:443
struct Plan * lefttree
Definition: plannodes.h:143
List * targetlist
Definition: plannodes.h:141
bool * nullsFirst
Definition: plannodes.h:280
List * mergeplans
Definition: plannodes.h:274
PartitionPruneInfo * make_partition_pruneinfo(PlannerInfo *root, RelOptInfo *parentrel, List *subpaths, List *prunequal)
Definition: partprune.c:222
#define elog(elevel,...)
Definition: elog.h:232
bool parallel_safe
Definition: plannodes.h:130
Oid * sortOperators
Definition: plannodes.h:278
#define CP_EXACT_TLIST
Definition: createplan.c:68
Definition: pg_list.h:50
int16 AttrNumber
Definition: attnum.h:21
static void label_sort_with_costsize(PlannerInfo *root, Sort *plan, double limit_tuples)
Definition: createplan.c:5306
double limit_tuples
Definition: pathnodes.h:1469
Datum subpath(PG_FUNCTION_ARGS)
Definition: ltree_op.c:241
static Plan * prepare_sort_from_pathkeys(Plan *lefttree, List *pathkeys, Relids relids, const AttrNumber *reqColIdx, bool adjust_tlist_in_place, int *p_numsortkeys, AttrNumber **p_sortColIdx, Oid **p_sortOperators, Oid **p_collations, bool **p_nullsFirst)
Definition: createplan.c:6019

◆ create_mergejoin_plan()

static MergeJoin * create_mergejoin_plan ( PlannerInfo root,
MergePath best_path 
)
static

Definition at line 4295 of file createplan.c.

References Assert, build_path_tlist(), copy_generic_path_info(), copy_plan_costsize(), CP_SMALL_TLIST, cpu_operator_cost, create_plan_recurse(), EquivalenceClass::ec_collation, elog, ERROR, extract_actual_clauses(), extract_actual_join_clauses(), get_actual_clauses(), get_switched_clauses(), i, JoinPath::inner_unique, JoinPath::innerjoinpath, MergePath::innersortkeys, IS_OUTER_JOIN, MergeJoin::join, JoinPath::joinrestrictinfo, JoinPath::jointype, MergePath::jpath, label_sort_with_costsize(), RestrictInfo::left_ec, lfirst, lfirst_node, list_difference(), list_head(), list_length(), lnext(), make_material(), make_mergejoin(), make_sort_from_pathkeys(), MergePath::materialize_inner, NIL, order_qual_clauses(), RestrictInfo::outer_is_left, JoinPath::outerjoinpath, MergePath::outersortkeys, palloc(), Path::param_info, Path::parent, JoinPath::path, MergePath::path_mergeclauses, Path::pathkeys, PathKey::pk_eclass, PathKey::pk_nulls_first, PathKey::pk_opfamily, PathKey::pk_strategy, Join::plan, Plan::plan_rows, RelOptInfo::relids, replace_nestloop_params(), RestrictInfo::right_ec, MergePath::skip_mark_restore, sort(), and Plan::total_cost.

Referenced by create_join_plan().

4297 {
4298  MergeJoin *join_plan;
4299  Plan *outer_plan;
4300  Plan *inner_plan;
4301  List *tlist = build_path_tlist(root, &best_path->jpath.path);
4302  List *joinclauses;
4303  List *otherclauses;
4304  List *mergeclauses;
4305  List *outerpathkeys;
4306  List *innerpathkeys;
4307  int nClauses;
4308  Oid *mergefamilies;
4309  Oid *mergecollations;
4310  int *mergestrategies;
4311  bool *mergenullsfirst;
4312  PathKey *opathkey;
4313  EquivalenceClass *opeclass;
4314  int i;
4315  ListCell *lc;
4316  ListCell *lop;
4317  ListCell *lip;
4318  Path *outer_path = best_path->jpath.outerjoinpath;
4319  Path *inner_path = best_path->jpath.innerjoinpath;
4320 
4321  /*
4322  * MergeJoin can project, so we don't have to demand exact tlists from the
4323  * inputs. However, if we're intending to sort an input's result, it's
4324  * best to request a small tlist so we aren't sorting more data than
4325  * necessary.
4326  */
4327  outer_plan = create_plan_recurse(root, best_path->jpath.outerjoinpath,
4328  (best_path->outersortkeys != NIL) ? CP_SMALL_TLIST : 0);
4329 
4330  inner_plan = create_plan_recurse(root, best_path->jpath.innerjoinpath,
4331  (best_path->innersortkeys != NIL) ? CP_SMALL_TLIST : 0);
4332 
4333  /* Sort join qual clauses into best execution order */
4334  /* NB: do NOT reorder the mergeclauses */
4335  joinclauses = order_qual_clauses(root, best_path->jpath.joinrestrictinfo);
4336 
4337  /* Get the join qual clauses (in plain expression form) */
4338  /* Any pseudoconstant clauses are ignored here */
4339  if (IS_OUTER_JOIN(best_path->jpath.jointype))
4340  {
4341  extract_actual_join_clauses(joinclauses,
4342  best_path->jpath.path.parent->relids,
4343  &joinclauses, &otherclauses);
4344  }
4345  else
4346  {
4347  /* We can treat all clauses alike for an inner join */
4348  joinclauses = extract_actual_clauses(joinclauses, false);
4349  otherclauses = NIL;
4350  }
4351 
4352  /*
4353  * Remove the mergeclauses from the list of join qual clauses, leaving the
4354  * list of quals that must be checked as qpquals.
4355  */
4356  mergeclauses = get_actual_clauses(best_path->path_mergeclauses);
4357  joinclauses = list_difference(joinclauses, mergeclauses);
4358 
4359  /*
4360  * Replace any outer-relation variables with nestloop params. There
4361  * should not be any in the mergeclauses.
4362  */
4363  if (best_path->jpath.path.param_info)
4364  {
4365  joinclauses = (List *)
4366  replace_nestloop_params(root, (Node *) joinclauses);
4367  otherclauses = (List *)
4368  replace_nestloop_params(root, (Node *) otherclauses);
4369  }
4370 
4371  /*
4372  * Rearrange mergeclauses, if needed, so that the outer variable is always
4373  * on the left; mark the mergeclause restrictinfos with correct
4374  * outer_is_left status.
4375  */
4376  mergeclauses = get_switched_clauses(best_path->path_mergeclauses,
4377  best_path->jpath.outerjoinpath->parent->relids);
4378 
4379  /*
4380  * Create explicit sort nodes for the outer and inner paths if necessary.
4381  */
4382  if (best_path->outersortkeys)
4383  {
4384  Relids outer_relids = outer_path->parent->relids;
4385  Sort *sort = make_sort_from_pathkeys(outer_plan,
4386  best_path->outersortkeys,
4387  outer_relids);
4388 
4389  label_sort_with_costsize(root, sort, -1.0);
4390  outer_plan = (Plan *) sort;
4391  outerpathkeys = best_path->outersortkeys;
4392  }
4393  else
4394  outerpathkeys = best_path->jpath.outerjoinpath->pathkeys;
4395 
4396  if (best_path->innersortkeys)
4397  {
4398  Relids inner_relids = inner_path->parent->relids;
4399  Sort *sort = make_sort_from_pathkeys(inner_plan,
4400  best_path->innersortkeys,
4401  inner_relids);
4402 
4403  label_sort_with_costsize(root, sort, -1.0);
4404  inner_plan = (Plan *) sort;
4405  innerpathkeys = best_path->innersortkeys;
4406  }
4407  else
4408  innerpathkeys = best_path->jpath.innerjoinpath->pathkeys;
4409 
4410  /*
4411  * If specified, add a materialize node to shield the inner plan from the
4412  * need to handle mark/restore.
4413  */
4414  if (best_path->materialize_inner)
4415  {
4416  Plan *matplan = (Plan *) make_material(inner_plan);
4417 
4418  /*
4419  * We assume the materialize will not spill to disk, and therefore
4420  * charge just cpu_operator_cost per tuple. (Keep this estimate in
4421  * sync with final_cost_mergejoin.)
4422  */
4423  copy_plan_costsize(matplan, inner_plan);
4424  matplan->total_cost += cpu_operator_cost * matplan->plan_rows;
4425 
4426  inner_plan = matplan;
4427  }
4428 
4429  /*
4430  * Compute the opfamily/collation/strategy/nullsfirst arrays needed by the
4431  * executor. The information is in the pathkeys for the two inputs, but
4432  * we need to be careful about the possibility of mergeclauses sharing a
4433  * pathkey, as well as the possibility that the inner pathkeys are not in
4434  * an order matching the mergeclauses.
4435  */
4436  nClauses = list_length(mergeclauses);
4437  Assert(nClauses == list_length(best_path->path_mergeclauses));
4438  mergefamilies = (Oid *) palloc(nClauses * sizeof(Oid));
4439  mergecollations = (Oid *) palloc(nClauses * sizeof(Oid));
4440  mergestrategies = (int *) palloc(nClauses * sizeof(int));
4441  mergenullsfirst = (bool *) palloc(nClauses * sizeof(bool));
4442 
4443  opathkey = NULL;
4444  opeclass = NULL;
4445  lop = list_head(outerpathkeys);
4446  lip = list_head(innerpathkeys);
4447  i = 0;
4448  foreach(lc, best_path->path_mergeclauses)
4449  {
4450  RestrictInfo *rinfo = lfirst_node(RestrictInfo, lc);
4451  EquivalenceClass *oeclass;
4452  EquivalenceClass *ieclass;
4453  PathKey *ipathkey = NULL;
4454  EquivalenceClass *ipeclass = NULL;
4455  bool first_inner_match = false;
4456 
4457  /* fetch outer/inner eclass from mergeclause */
4458  if (rinfo->outer_is_left)
4459  {
4460  oeclass = rinfo->left_ec;
4461  ieclass = rinfo->right_ec;
4462  }
4463  else
4464  {
4465  oeclass = rinfo->right_ec;
4466  ieclass = rinfo->left_ec;
4467  }
4468  Assert(oeclass != NULL);
4469  Assert(ieclass != NULL);
4470 
4471  /*
4472  * We must identify the pathkey elements associated with this clause
4473  * by matching the eclasses (which should give a unique match, since
4474  * the pathkey lists should be canonical). In typical cases the merge
4475  * clauses are one-to-one with the pathkeys, but when dealing with
4476  * partially redundant query conditions, things are more complicated.
4477  *
4478  * lop and lip reference the first as-yet-unmatched pathkey elements.
4479  * If they're NULL then all pathkey elements have been matched.
4480  *
4481  * The ordering of the outer pathkeys should match the mergeclauses,
4482  * by construction (see find_mergeclauses_for_outer_pathkeys()). There
4483  * could be more than one mergeclause for the same outer pathkey, but
4484  * no pathkey may be entirely skipped over.
4485  */
4486  if (oeclass != opeclass) /* multiple matches are not interesting */
4487  {
4488  /* doesn't match the current opathkey, so must match the next */
4489  if (lop == NULL)
4490  elog(ERROR, "outer pathkeys do not match mergeclauses");
4491  opathkey = (PathKey *) lfirst(lop);
4492  opeclass = opathkey->pk_eclass;
4493  lop = lnext(outerpathkeys, lop);
4494  if (oeclass != opeclass)
4495  elog(ERROR, "outer pathkeys do not match mergeclauses");
4496  }
4497 
4498  /*
4499  * The inner pathkeys likewise should not have skipped-over keys, but
4500  * it's possible for a mergeclause to reference some earlier inner
4501  * pathkey if we had redundant pathkeys. For example we might have
4502  * mergeclauses like "o.a = i.x AND o.b = i.y AND o.c = i.x". The
4503  * implied inner ordering is then "ORDER BY x, y, x", but the pathkey
4504  * mechanism drops the second sort by x as redundant, and this code
4505  * must cope.
4506  *
4507  * It's also possible for the implied inner-rel ordering to be like
4508  * "ORDER BY x, y, x DESC". We still drop the second instance of x as
4509  * redundant; but this means that the sort ordering of a redundant
4510  * inner pathkey should not be considered significant. So we must
4511  * detect whether this is the first clause matching an inner pathkey.
4512  */
4513  if (lip)
4514  {
4515  ipathkey = (PathKey *) lfirst(lip);
4516  ipeclass = ipathkey->pk_eclass;
4517  if (ieclass == ipeclass)
4518  {
4519  /* successful first match to this inner pathkey */
4520  lip = lnext(innerpathkeys, lip);
4521  first_inner_match = true;
4522  }
4523  }
4524  if (!first_inner_match)
4525  {
4526  /* redundant clause ... must match something before lip */
4527  ListCell *l2;
4528 
4529  foreach(l2, innerpathkeys)
4530  {
4531  if (l2 == lip)
4532  break;
4533  ipathkey = (PathKey *) lfirst(l2);
4534  ipeclass = ipathkey->pk_eclass;
4535  if (ieclass == ipeclass)
4536  break;
4537  }
4538  if (ieclass != ipeclass)
4539  elog(ERROR, "inner pathkeys do not match mergeclauses");
4540  }
4541 
4542  /*
4543  * The pathkeys should always match each other as to opfamily and
4544  * collation (which affect equality), but if we're considering a
4545  * redundant inner pathkey, its sort ordering might not match. In
4546  * such cases we may ignore the inner pathkey's sort ordering and use
4547  * the outer's. (In effect, we're lying to the executor about the
4548  * sort direction of this inner column, but it does not matter since
4549  * the run-time row comparisons would only reach this column when
4550  * there's equality for the earlier column containing the same eclass.
4551  * There could be only one value in this column for the range of inner
4552  * rows having a given value in the earlier column, so it does not
4553  * matter which way we imagine this column to be ordered.) But a
4554  * non-redundant inner pathkey had better match outer's ordering too.
4555  */
4556  if (opathkey->pk_opfamily != ipathkey->pk_opfamily ||
4557  opathkey->pk_eclass->ec_collation != ipathkey->pk_eclass->ec_collation)
4558  elog(ERROR, "left and right pathkeys do not match in mergejoin");
4559  if (first_inner_match &&
4560  (opathkey->pk_strategy != ipathkey->pk_strategy ||
4561  opathkey->pk_nulls_first != ipathkey->pk_nulls_first))
4562  elog(ERROR, "left and right pathkeys do not match in mergejoin");
4563 
4564  /* OK, save info for executor */
4565  mergefamilies[i] = opathkey->pk_opfamily;
4566  mergecollations[i] = opathkey->pk_eclass->ec_collation;
4567  mergestrategies[i] = opathkey->pk_strategy;
4568  mergenullsfirst[i] = opathkey->pk_nulls_first;
4569  i++;
4570  }
4571 
4572  /*
4573  * Note: it is not an error if we have additional pathkey elements (i.e.,
4574  * lop or lip isn't NULL here). The input paths might be better-sorted
4575  * than we need for the current mergejoin.
4576  */
4577 
4578  /*
4579  * Now we can build the mergejoin node.
4580  */
4581  join_plan = make_mergejoin(tlist,
4582  joinclauses,
4583  otherclauses,
4584  mergeclauses,
4585  mergefamilies,
4586  mergecollations,
4587  mergestrategies,
4588  mergenullsfirst,
4589  outer_plan,
4590  inner_plan,
4591  best_path->jpath.jointype,
4592  best_path->jpath.inner_unique,
4593  best_path->skip_mark_restore);
4594 
4595  /* Costs of sort and material steps are included in path cost already */
4596  copy_generic_path_info(&join_plan->join.plan, &best_path->jpath.path);
4597 
4598  return join_plan;
4599 }
#define NIL
Definition: pg_list.h:65
List * path_mergeclauses
Definition: pathnodes.h:1638
List * outersortkeys
Definition: pathnodes.h:1639
double plan_rows
Definition: plannodes.h:123
static Sort * make_sort_from_pathkeys(Plan *lefttree, List *pathkeys, Relids relids)
Definition: createplan.c:6204
static Node * replace_nestloop_params(PlannerInfo *root, Node *expr)
Definition: createplan.c:4791
static List * get_switched_clauses(List *clauses, Relids outerrelids)
Definition: createplan.c:5098
bool materialize_inner
Definition: pathnodes.h:1642
static ListCell * lnext(const List *l, const ListCell *c)
Definition: pg_list.h:322
void extract_actual_join_clauses(List *restrictinfo_list, Relids joinrelids, List **joinquals, List **otherquals)
Definition: restrictinfo.c:470
static MergeJoin * make_mergejoin(List *tlist, List *joinclauses, List *otherclauses, List *mergeclauses, Oid *mergefamilies, Oid *mergecollations, int *mergestrategies, bool *mergenullsfirst, Plan *lefttree, Plan *righttree, JoinType jointype, bool inner_unique, bool skip_mark_restore)
Definition: createplan.c:5882
Path * innerjoinpath
Definition: pathnodes.h:1583
#define IS_OUTER_JOIN(jointype)
Definition: nodes.h:755
ParamPathInfo * param_info
Definition: pathnodes.h:1177
#define CP_SMALL_TLIST
Definition: createplan.c:69
Definition: nodes.h:539
List * get_actual_clauses(List *restrictinfo_list)
Definition: restrictinfo.c:420
static List * order_qual_clauses(PlannerInfo *root, List *clauses)
Definition: createplan.c:5175
EquivalenceClass * right_ec
Definition: pathnodes.h:2097
unsigned int Oid
Definition: postgres_ext.h:31
int pk_strategy
Definition: pathnodes.h:1060
static Plan * create_plan_recurse(PlannerInfo *root, Path *best_path, int flags)
Definition: createplan.c:385
static Material * make_material(Plan *lefttree)
Definition: createplan.c:6363
bool skip_mark_restore
Definition: pathnodes.h:1641
static void copy_generic_path_info(Plan *dest, Path *src)
Definition: createplan.c:5269
bool pk_nulls_first
Definition: pathnodes.h:1061
#define ERROR
Definition: elog.h:46
static List * build_path_tlist(PlannerInfo *root, Path *path)
Definition: createplan.c:803
List * joinrestrictinfo
Definition: pathnodes.h:1585
RelOptInfo * parent
Definition: pathnodes.h:1174
#define lfirst_node(type, lc)
Definition: pg_list.h:172
bool outer_is_left
Definition: pathnodes.h:2103
Datum sort(PG_FUNCTION_ARGS)
Definition: _int_op.c:195
static void copy_plan_costsize(Plan *dest, Plan *src)
Definition: createplan.c:5284
static ListCell * list_head(const List *l)
Definition: pg_list.h:125
Relids relids
Definition: pathnodes.h:676
double cpu_operator_cost
Definition: costsize.c:123
Path * outerjoinpath
Definition: pathnodes.h:1582
List * pathkeys
Definition: pathnodes.h:1188
Path path
Definition: pathnodes.h:1575
#define Assert(condition)
Definition: c.h:804
#define lfirst(lc)
Definition: pg_list.h:169
EquivalenceClass * pk_eclass
Definition: pathnodes.h:1058
static int list_length(const List *l)
Definition: pg_list.h:149
List * extract_actual_clauses(List *restrictinfo_list, bool pseudoconstant)
Definition: restrictinfo.c:443
bool inner_unique
Definition: pathnodes.h:1579
List * list_difference(const List *list1, const List *list2)
Definition: list.c:1091
List * innersortkeys
Definition: pathnodes.h:1640
Oid pk_opfamily
Definition: pathnodes.h:1059
void * palloc(Size size)
Definition: mcxt.c:1062
EquivalenceClass * left_ec
Definition: pathnodes.h:2096
Join join
Definition: plannodes.h:745
JoinType jointype
Definition: pathnodes.h:1577
#define elog(elevel,...)
Definition: elog.h:232
int i
Cost total_cost
Definition: plannodes.h:118
JoinPath jpath
Definition: pathnodes.h:1637
Definition: pg_list.h:50
static void label_sort_with_costsize(PlannerInfo *root, Sort *plan, double limit_tuples)
Definition: createplan.c:5306
Plan plan
Definition: plannodes.h:702

◆ create_minmaxagg_plan()

static Result * create_minmaxagg_plan ( PlannerInfo root,
MinMaxAggPath best_path 
)
static

Definition at line 2466 of file createplan.c.

References Assert, build_path_tlist(), copy_generic_path_info(), create_plan(), lfirst, Query::limitCount, Query::limitOffset, Query::limitOption, make_limit(), make_result(), PlannerInfo::minmax_aggs, MinMaxAggPath::mmaggregates, NIL, Plan::parallel_aware, Plan::parallel_safe, Path::parallel_safe, MinMaxAggInfo::param, PlannerInfo::parse, MinMaxAggPath::path, MinMaxAggInfo::path, MinMaxAggInfo::pathcost, Path::pathtarget, Result::plan, Plan::plan_rows, Plan::plan_width, MinMaxAggPath::quals, SS_make_initplan_from_plan(), Plan::startup_cost, Path::startup_cost, MinMaxAggInfo::subroot, Plan::total_cost, and PathTarget::width.

Referenced by create_plan_recurse().

2467 {
2468  Result *plan;
2469  List *tlist;
2470  ListCell *lc;
2471 
2472  /* Prepare an InitPlan for each aggregate's subquery. */
2473  foreach(lc, best_path->mmaggregates)
2474  {
2475  MinMaxAggInfo *mminfo = (MinMaxAggInfo *) lfirst(lc);
2476  PlannerInfo *subroot = mminfo->subroot;
2477  Query *subparse = subroot->parse;
2478  Plan *plan;
2479 
2480  /*
2481  * Generate the plan for the subquery. We already have a Path, but we
2482  * have to convert it to a Plan and attach a LIMIT node above it.
2483  * Since we are entering a different planner context (subroot),
2484  * recurse to create_plan not create_plan_recurse.
2485  */
2486  plan = create_plan(subroot, mminfo->path);
2487 
2488  plan = (Plan *) make_limit(plan,
2489  subparse->limitOffset,
2490  subparse->limitCount,
2491  subparse->limitOption,
2492  0, NULL, NULL, NULL);
2493 
2494  /* Must apply correct cost/width data to Limit node */
2495  plan->startup_cost = mminfo->path->startup_cost;
2496  plan->total_cost = mminfo->pathcost;
2497  plan->plan_rows = 1;
2498  plan->plan_width = mminfo->path->pathtarget->width;
2499  plan->parallel_aware = false;
2500  plan->parallel_safe = mminfo->path->parallel_safe;
2501 
2502  /* Convert the plan into an InitPlan in the outer query. */
2503  SS_make_initplan_from_plan(root, subroot, plan, mminfo->param);
2504  }
2505 
2506  /* Generate the output plan --- basically just a Result */
2507  tlist = build_path_tlist(root, &best_path->path);
2508 
2509  plan = make_result(tlist, (Node *) best_path->quals, NULL);
2510 
2511  copy_generic_path_info(&plan->plan, (Path *) best_path);
2512 
2513  /*
2514  * During setrefs.c, we'll need to replace references to the Agg nodes
2515  * with InitPlan output params. (We can't just do that locally in the
2516  * MinMaxAgg node, because path nodes above here may have Agg references
2517  * as well.) Save the mmaggregates list to tell setrefs.c to do that.
2518  */
2519  Assert(root->minmax_aggs == NIL);
2520  root->minmax_aggs = best_path->mmaggregates;
2521 
2522  return plan;
2523 }
Node * limitOffset
Definition: parsenodes.h:171
#define NIL
Definition: pg_list.h:65
double plan_rows
Definition: plannodes.h:123
PathTarget * pathtarget
Definition: pathnodes.h:1175
Query * parse
Definition: pathnodes.h:161
Param * param
Definition: pathnodes.h:2423
Definition: nodes.h:539
List * minmax_aggs
Definition: pathnodes.h:332
List * quals
Definition: pathnodes.h:1811
Plan * create_plan(PlannerInfo *root, Path *best_path)
Definition: createplan.c:334
static void copy_generic_path_info(Plan *dest, Path *src)
Definition: createplan.c:5269
static List * build_path_tlist(PlannerInfo *root, Path *path)
Definition: createplan.c:803
Cost startup_cost
Definition: pathnodes.h:1185
Node * limitCount
Definition: parsenodes.h:172
Cost startup_cost
Definition: plannodes.h:117
bool parallel_aware
Definition: plannodes.h:129
Limit * make_limit(Plan *lefttree, Node *limitOffset, Node *limitCount, LimitOption limitOption, int uniqNumCols, AttrNumber *uniqColIdx, Oid *uniqOperators, Oid *uniqCollations)
Definition: createplan.c:6805
static Result * make_result(List *tlist, Node *resconstantqual, Plan *subplan)
Definition: createplan.c:6833
LimitOption limitOption
Definition: parsenodes.h:173
List * mmaggregates
Definition: pathnodes.h:1810
int plan_width
Definition: plannodes.h:124
#define Assert(condition)
Definition: c.h:804
#define lfirst(lc)
Definition: pg_list.h:169
bool parallel_safe
Definition: pathnodes.h:1180
void SS_make_initplan_from_plan(PlannerInfo *root, PlannerInfo *subroot, Plan *plan, Param *prm)
Definition: subselect.c:2958
Cost total_cost
Definition: plannodes.h:118
bool parallel_safe
Definition: plannodes.h:130
Definition: pg_list.h:50
PlannerInfo * subroot
Definition: pathnodes.h:2420

◆ create_modifytable_plan()

static ModifyTable * create_modifytable_plan ( PlannerInfo root,
ModifyTablePath best_path 
)
static

Definition at line 2732 of file createplan.c.

References apply_tlist_labeling(), ModifyTablePath::canSetTag, copy_generic_path_info(), CP_EXACT_TLIST, create_plan_recurse(), ModifyTablePath::epqParam, make_modifytable(), ModifyTablePath::nominalRelation, ModifyTablePath::onconflict, ModifyTablePath::operation, ModifyTablePath::partColsUpdated, ModifyTablePath::path, ModifyTable::plan, PlannerInfo::processed_tlist, ModifyTablePath::resultRelations, ModifyTablePath::returningLists, ModifyTablePath::rootRelation, ModifyTablePath::rowMarks, subpath(), ModifyTablePath::subpath, Plan::targetlist, ModifyTablePath::updateColnosLists, and ModifyTablePath::withCheckOptionLists.

Referenced by create_plan_recurse().

2733 {
2734  ModifyTable *plan;
2735  Path *subpath = best_path->subpath;
2736  Plan *subplan;
2737 
2738  /* Subplan must produce exactly the specified tlist */
2739  subplan = create_plan_recurse(root, subpath, CP_EXACT_TLIST);
2740 
2741  /* Transfer resname/resjunk labeling, too, to keep executor happy */
2743 
2744  plan = make_modifytable(root,
2745  subplan,
2746  best_path->operation,
2747  best_path->canSetTag,
2748  best_path->nominalRelation,
2749  best_path->rootRelation,
2750  best_path->partColsUpdated,
2751  best_path->resultRelations,
2752  best_path->updateColnosLists,
2753  best_path->withCheckOptionLists,
2754  best_path->returningLists,
2755  best_path->rowMarks,
2756  best_path->onconflict,
2757  best_path->epqParam);
2758 
2759  copy_generic_path_info(&plan->plan, &best_path->path);
2760 
2761  return plan;
2762 }
void apply_tlist_labeling(List *dest_tlist, List *src_tlist)
Definition: tlist.c:307
List * returningLists
Definition: pathnodes.h:1882
OnConflictExpr * onconflict
Definition: pathnodes.h:1884
Index nominalRelation
Definition: pathnodes.h:1876
static Plan * create_plan_recurse(PlannerInfo *root, Path *best_path, int flags)
Definition: createplan.c:385
static void copy_generic_path_info(Plan *dest, Path *src)
Definition: createplan.c:5269
bool partColsUpdated
Definition: pathnodes.h:1878
static ModifyTable * make_modifytable(PlannerInfo *root, Plan *subplan, CmdType operation, bool canSetTag, Index nominalRelation, Index rootRelation, bool partColsUpdated, List *resultRelations, List *updateColnosLists, List *withCheckOptionLists, List *returningLists, List *rowMarks, OnConflictExpr *onconflict, int epqParam)
Definition: createplan.c:6873
Index rootRelation
Definition: pathnodes.h:1877
List * targetlist
Definition: plannodes.h:141
List * withCheckOptionLists
Definition: pathnodes.h:1881
CmdType operation
Definition: pathnodes.h:1874
List * resultRelations
Definition: pathnodes.h:1879
List * updateColnosLists
Definition: pathnodes.h:1880
List * processed_tlist
Definition: pathnodes.h:320
#define CP_EXACT_TLIST
Definition: createplan.c:68
Datum subpath(PG_FUNCTION_ARGS)
Definition: ltree_op.c:241

◆ create_namedtuplestorescan_plan()

static NamedTuplestoreScan * create_namedtuplestorescan_plan ( PlannerInfo root,
Path best_path,
List tlist,
List scan_clauses 
)
static

Definition at line 3868 of file createplan.c.

References Assert, copy_generic_path_info(), RangeTblEntry::enrname, extract_actual_clauses(), make_namedtuplestorescan(), order_qual_clauses(), Path::param_info, Path::parent, Scan::plan, planner_rt_fetch, RelOptInfo::relid, replace_nestloop_params(), RTE_NAMEDTUPLESTORE, RangeTblEntry::rtekind, and NamedTuplestoreScan::scan.

Referenced by create_scan_plan().

3870 {
3871  NamedTuplestoreScan *scan_plan;
3872  Index scan_relid = best_path->parent->relid;
3873  RangeTblEntry *rte;
3874 
3875  Assert(scan_relid > 0);
3876  rte = planner_rt_fetch(scan_relid, root);
3878 
3879  /* Sort clauses into best execution order */
3880  scan_clauses = order_qual_clauses(root, scan_clauses);
3881 
3882  /* Reduce RestrictInfo list to bare expressions; ignore pseudoconstants */
3883  scan_clauses = extract_actual_clauses(scan_clauses, false);
3884 
3885  /* Replace any outer-relation variables with nestloop params */
3886  if (best_path->param_info)
3887  {
3888  scan_clauses = (List *)
3889  replace_nestloop_params(root, (Node *) scan_clauses);
3890  }
3891 
3892  scan_plan = make_namedtuplestorescan(tlist, scan_clauses, scan_relid,
3893  rte->enrname);
3894 
3895  copy_generic_path_info(&scan_plan->scan.plan, best_path);
3896 
3897  return scan_plan;
3898 }
Plan plan
Definition: plannodes.h:342
static Node * replace_nestloop_params(PlannerInfo *root, Node *expr)
Definition: createplan.c:4791
ParamPathInfo * param_info
Definition: pathnodes.h:1177
Definition: nodes.h:539
static List * order_qual_clauses(PlannerInfo *root, List *clauses)
Definition: createplan.c:5175
static void copy_generic_path_info(Plan *dest, Path *src)
Definition: createplan.c:5269
#define planner_rt_fetch(rti, root)
Definition: pathnodes.h:383
RelOptInfo * parent
Definition: pathnodes.h:1174
char * enrname
Definition: parsenodes.h:1134
Index relid
Definition: pathnodes.h:704
static NamedTuplestoreScan * make_namedtuplestorescan(List *qptlist, List *qpqual, Index scanrelid, char *enrname)
Definition: createplan.c:5640
unsigned int Index
Definition: c.h:549
#define Assert(condition)
Definition: c.h:804
List * extract_actual_clauses(List *restrictinfo_list, bool pseudoconstant)
Definition: restrictinfo.c:443
RTEKind rtekind
Definition: parsenodes.h:995
Definition: pg_list.h:50

◆ create_nestloop_plan()

static NestLoop * create_nestloop_plan ( PlannerInfo root,
NestPath best_path 
)
static

Definition at line 4219 of file createplan.c.

References bms_free(), bms_union(), build_path_tlist(), copy_generic_path_info(), create_plan_recurse(), PlannerInfo::curOuterRels, extract_actual_clauses(), extract_actual_join_clauses(), identify_current_nestloop_params(), JoinPath::inner_unique, JoinPath::innerjoinpath, IS_OUTER_JOIN, NestLoop::join, JoinPath::joinrestrictinfo, JoinPath::jointype, make_nestloop(), NIL, order_qual_clauses(), JoinPath::outerjoinpath, Path::param_info, Path::parent, JoinPath::path, Join::plan, RelOptInfo::relids, and replace_nestloop_params().

Referenced by create_join_plan().

4221 {
4222  NestLoop *join_plan;
4223  Plan *outer_plan;
4224  Plan *inner_plan;
4225  List *tlist = build_path_tlist(root, &best_path->path);
4226  List *joinrestrictclauses = best_path->joinrestrictinfo;
4227  List *joinclauses;
4228  List *otherclauses;
4229  Relids outerrelids;
4230  List *nestParams;
4231  Relids saveOuterRels = root->curOuterRels;
4232 
4233  /* NestLoop can project, so no need to be picky about child tlists */
4234  outer_plan = create_plan_recurse(root, best_path->outerjoinpath, 0);
4235 
4236  /* For a nestloop, include outer relids in curOuterRels for inner side */
4237  root->curOuterRels = bms_union(root->curOuterRels,
4238  best_path->outerjoinpath->parent->relids);
4239 
4240  inner_plan = create_plan_recurse(root, best_path->innerjoinpath, 0);
4241 
4242  /* Restore curOuterRels */
4243  bms_free(root->curOuterRels);
4244  root->curOuterRels = saveOuterRels;
4245 
4246  /* Sort join qual clauses into best execution order */
4247  joinrestrictclauses = order_qual_clauses(root, joinrestrictclauses);
4248 
4249  /* Get the join qual clauses (in plain expression form) */
4250  /* Any pseudoconstant clauses are ignored here */
4251  if (IS_OUTER_JOIN(best_path->jointype))
4252  {
4253  extract_actual_join_clauses(joinrestrictclauses,
4254  best_path->path.parent->relids,
4255  &joinclauses, &otherclauses);
4256  }
4257  else
4258  {
4259  /* We can treat all clauses alike for an inner join */
4260  joinclauses = extract_actual_clauses(joinrestrictclauses, false);
4261  otherclauses = NIL;
4262  }
4263 
4264  /* Replace any outer-relation variables with nestloop params */
4265  if (best_path->path.param_info)
4266  {
4267  joinclauses = (List *)
4268  replace_nestloop_params(root, (Node *) joinclauses);
4269  otherclauses = (List *)
4270  replace_nestloop_params(root, (Node *) otherclauses);
4271  }
4272 
4273  /*
4274  * Identify any nestloop parameters that should be supplied by this join
4275  * node, and remove them from root->curOuterParams.
4276  */
4277  outerrelids = best_path->outerjoinpath->parent->relids;
4278  nestParams = identify_current_nestloop_params(root, outerrelids);
4279 
4280  join_plan = make_nestloop(tlist,
4281  joinclauses,
4282  otherclauses,
4283  nestParams,
4284  outer_plan,
4285  inner_plan,
4286  best_path->jointype,
4287  best_path->inner_unique);
4288 
4289  copy_generic_path_info(&join_plan->join.plan, &best_path->path);
4290 
4291  return join_plan;
4292 }
#define NIL
Definition: pg_list.h:65
List * identify_current_nestloop_params(PlannerInfo *root, Relids leftrelids)
Definition: paramassign.c:508
static Node * replace_nestloop_params(PlannerInfo *root, Node *expr)
Definition: createplan.c:4791
Relids curOuterRels
Definition: pathnodes.h:367
void extract_actual_join_clauses(List *restrictinfo_list, Relids joinrelids, List **joinquals, List **otherquals)
Definition: restrictinfo.c:470
Path * innerjoinpath
Definition: pathnodes.h:1583
#define IS_OUTER_JOIN(jointype)
Definition: nodes.h:755
ParamPathInfo * param_info
Definition: pathnodes.h:1177
Definition: nodes.h:539
static List * order_qual_clauses(PlannerInfo *root, List *clauses)
Definition: createplan.c:5175
static Plan * create_plan_recurse(PlannerInfo *root, Path *best_path, int flags)
Definition: createplan.c:385
static void copy_generic_path_info(Plan *dest, Path *src)
Definition: createplan.c:5269
Join join
Definition: plannodes.h:721
static List * build_path_tlist(PlannerInfo *root, Path *path)
Definition: createplan.c:803
List * joinrestrictinfo
Definition: pathnodes.h:1585
RelOptInfo * parent
Definition: pathnodes.h:1174
static NestLoop * make_nestloop(List *tlist, List *joinclauses, List *otherclauses, List *nestParams, Plan *lefttree, Plan *righttree, JoinType jointype, bool inner_unique)
Definition: createplan.c:5803
Relids relids
Definition: pathnodes.h:676
Path * outerjoinpath
Definition: pathnodes.h:1582
void bms_free(Bitmapset *a)
Definition: bitmapset.c:208
Path path
Definition: pathnodes.h:1575
Bitmapset * bms_union(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:225
List * extract_actual_clauses(List *restrictinfo_list, bool pseudoconstant)
Definition: restrictinfo.c:443
bool inner_unique
Definition: pathnodes.h:1579
JoinType jointype
Definition: pathnodes.h:1577
Definition: pg_list.h:50
Plan plan
Definition: plannodes.h:702

◆ create_plan()

Plan* create_plan ( PlannerInfo root,
Path best_path 
)

Definition at line 334 of file createplan.c.

References apply_tlist_labeling(), Assert, CP_EXACT_TLIST, create_plan_recurse(), PlannerInfo::curOuterParams, PlannerInfo::curOuterRels, elog, ERROR, IsA, NIL, PlannerInfo::plan_params, PlannerInfo::processed_tlist, SS_attach_initplans(), and Plan::targetlist.

Referenced by create_minmaxagg_plan(), create_subqueryscan_plan(), make_subplan(), SS_process_ctes(), and standard_planner().

335 {
336  Plan *plan;
337 
338  /* plan_params should not be in use in current query level */
339  Assert(root->plan_params == NIL);
340 
341  /* Initialize this module's workspace in PlannerInfo */
342  root->curOuterRels = NULL;
343  root->curOuterParams = NIL;
344 
345  /* Recursively process the path tree, demanding the correct tlist result */
346  plan = create_plan_recurse(root, best_path, CP_EXACT_TLIST);
347 
348  /*
349  * Make sure the topmost plan node's targetlist exposes the original
350  * column names and other decorative info. Targetlists generated within
351  * the planner don't bother with that stuff, but we must have it on the
352  * top-level tlist seen at execution time. However, ModifyTable plan
353  * nodes don't have a tlist matching the querytree targetlist.
354  */
355  if (!IsA(plan, ModifyTable))
357 
358  /*
359  * Attach any initPlans created in this query level to the topmost plan
360  * node. (In principle the initplans could go in any plan node at or
361  * above where they're referenced, but there seems no reason to put them
362  * any lower than the topmost node for the query level. Also, see
363  * comments for SS_finalize_plan before you try to change this.)
364  */
365  SS_attach_initplans(root, plan);
366 
367  /* Check we successfully assigned all NestLoopParams to plan nodes */
368  if (root->curOuterParams != NIL)
369  elog(ERROR, "failed to assign all NestLoopParams to plan nodes");
370 
371  /*
372  * Reset plan_params to ensure param IDs used for nestloop params are not
373  * re-used later
374  */
375  root->plan_params = NIL;
376 
377  return plan;
378 }
#define NIL
Definition: pg_list.h:65
void apply_tlist_labeling(List *dest_tlist, List *src_tlist)
Definition: tlist.c:307
#define IsA(nodeptr, _type_)
Definition: nodes.h:590
List * plan_params
Definition: pathnodes.h:175
Relids curOuterRels
Definition: pathnodes.h:367
static Plan * create_plan_recurse(PlannerInfo *root, Path *best_path, int flags)
Definition: createplan.c:385
#define ERROR
Definition: elog.h:46
List * curOuterParams
Definition: pathnodes.h:368
#define Assert(condition)
Definition: c.h:804
void SS_attach_initplans(PlannerInfo *root, Plan *plan)
Definition: subselect.c:2186
List * targetlist
Definition: plannodes.h:141
#define elog(elevel,...)
Definition: elog.h:232
List * processed_tlist
Definition: pathnodes.h:320
#define CP_EXACT_TLIST
Definition: createplan.c:68

◆ create_plan_recurse()

static Plan * create_plan_recurse ( PlannerInfo root,
Path best_path,
int  flags 
)
static

Definition at line 385 of file createplan.c.

References Assert, check_stack_depth(), create_agg_plan(), create_append_plan(), create_gather_merge_plan(), create_gather_plan(), create_group_plan(), create_group_result_plan(), create_groupingsets_plan(), create_incrementalsort_plan(), create_join_plan(), create_limit_plan(), create_lockrows_plan(), create_material_plan(), create_merge_append_plan(), create_minmaxagg_plan(), create_modifytable_plan(), create_project_set_plan(), create_projection_plan(), create_recursiveunion_plan(), create_resultcache_plan(), create_scan_plan(), create_setop_plan(), create_sort_plan(), create_unique_plan(), create_upper_unique_plan(), create_windowagg_plan(), elog, ERROR, IsA, Path::pathtype, T_Agg, T_Append, T_BitmapHeapScan, T_CteScan, T_CustomScan, T_ForeignScan, T_FunctionScan, T_Gather, T_GatherMerge, T_Group, T_HashJoin, T_IncrementalSort, T_IndexOnlyScan, T_IndexScan, T_Limit, T_LockRows, T_Material, T_MergeAppend, T_MergeJoin, T_ModifyTable, T_NamedTuplestoreScan, T_NestLoop, T_ProjectSet, T_RecursiveUnion, T_Result, T_ResultCache, T_SampleScan, T_SeqScan, T_SetOp, T_Sort, T_SubqueryScan, T_TableFuncScan, T_TidRangeScan, T_TidScan, T_Unique, T_ValuesScan, T_WindowAgg, and T_WorkTableScan.

Referenced by create_agg_plan(), create_append_plan(), create_customscan_plan(), create_foreignscan_plan(), create_gather_merge_plan(), create_gather_plan(), create_group_plan(), create_groupingsets_plan(), create_hashjoin_plan(), create_incrementalsort_plan(), create_limit_plan(), create_lockrows_plan(), create_material_plan(), create_merge_append_plan(), create_mergejoin_plan(), create_modifytable_plan(), create_nestloop_plan(), create_plan(), create_project_set_plan(), create_projection_plan(), create_recursiveunion_plan(), create_resultcache_plan(), create_setop_plan(), create_sort_plan(), create_unique_plan(), create_upper_unique_plan(), and create_windowagg_plan().

386 {
387  Plan *plan;
388 
389  /* Guard against stack overflow due to overly complex plans */
391 
392  switch (best_path->pathtype)
393  {
394  case T_SeqScan:
395  case T_SampleScan:
396  case T_IndexScan:
397  case T_IndexOnlyScan:
398  case T_BitmapHeapScan:
399  case T_TidScan:
400  case T_TidRangeScan:
401  case T_SubqueryScan:
402  case T_FunctionScan:
403  case T_TableFuncScan:
404  case T_ValuesScan:
405  case T_CteScan:
406  case T_WorkTableScan:
408  case T_ForeignScan:
409  case T_CustomScan:
410  plan = create_scan_plan(root, best_path, flags);
411  break;
412  case T_HashJoin:
413  case T_MergeJoin:
414  case T_NestLoop:
415  plan = create_join_plan(root,
416  (JoinPath *) best_path);
417  break;
418  case T_Append:
419  plan = create_append_plan(root,
420  (AppendPath *) best_path,
421  flags);
422  break;
423  case T_MergeAppend:
424  plan = create_merge_append_plan(root,
425  (MergeAppendPath *) best_path,
426  flags);
427  break;
428  case T_Result:
429  if (IsA(best_path, ProjectionPath))
430  {
431  plan = create_projection_plan(root,
432  (ProjectionPath *) best_path,
433  flags);
434  }
435  else if (IsA(best_path, MinMaxAggPath))
436  {
437  plan = (Plan *) create_minmaxagg_plan(root,
438  (MinMaxAggPath *) best_path);
439  }
440  else if (IsA(best_path, GroupResultPath))
441  {
442  plan = (Plan *) create_group_result_plan(root,
443  (GroupResultPath *) best_path);
444  }
445  else
446  {
447  /* Simple RTE_RESULT base relation */
448  Assert(IsA(best_path, Path));
449  plan = create_scan_plan(root, best_path, flags);
450  }
451  break;
452  case T_ProjectSet:
453  plan = (Plan *) create_project_set_plan(root,
454  (ProjectSetPath *) best_path);
455  break;
456  case T_Material:
457  plan = (Plan *) create_material_plan(root,
458  (MaterialPath *) best_path,
459  flags);
460  break;
461  case T_ResultCache:
462  plan = (Plan *) create_resultcache_plan(root,
463  (ResultCachePath *) best_path,
464  flags);
465  break;
466  case T_Unique:
467  if (IsA(best_path, UpperUniquePath))
468  {
469  plan = (Plan *) create_upper_unique_plan(root,
470  (UpperUniquePath *) best_path,
471  flags);
472  }
473  else
474  {
475  Assert(IsA(best_path, UniquePath));
476  plan = create_unique_plan(root,
477  (UniquePath *) best_path,
478  flags);
479  }
480  break;
481  case T_Gather:
482  plan = (Plan *) create_gather_plan(root,
483  (GatherPath *) best_path);
484  break;
485  case T_Sort:
486  plan = (Plan *) create_sort_plan(root,
487  (SortPath *) best_path,
488  flags);
489  break;
490  case T_IncrementalSort:
491  plan = (Plan *) create_incrementalsort_plan(root,
492  (IncrementalSortPath *) best_path,
493  flags);
494  break;
495  case T_Group:
496  plan = (Plan *) create_group_plan(root,
497  (GroupPath *) best_path);
498  break;
499  case T_Agg:
500  if (IsA(best_path, GroupingSetsPath))
501  plan = create_groupingsets_plan(root,
502  (GroupingSetsPath *) best_path);
503  else
504  {
505  Assert(IsA(best_path, AggPath));
506  plan = (Plan *) create_agg_plan(root,
507  (AggPath *) best_path);
508  }
509  break;
510  case T_WindowAgg:
511  plan = (Plan *) create_windowagg_plan(root,
512  (WindowAggPath *) best_path);
513  break;
514  case T_SetOp:
515  plan = (Plan *) create_setop_plan(root,
516  (SetOpPath *) best_path,
517  flags);
518  break;
519  case T_RecursiveUnion:
520  plan = (Plan *) create_recursiveunion_plan(root,
521  (RecursiveUnionPath *) best_path);
522  break;
523  case T_LockRows:
524  plan = (Plan *) create_lockrows_plan(root,
525  (LockRowsPath *) best_path,
526  flags);
527  break;
528  case T_ModifyTable:
529  plan = (Plan *) create_modifytable_plan(root,
530  (ModifyTablePath *) best_path);
531  break;
532  case T_Limit:
533  plan = (Plan *) create_limit_plan(root,
534  (LimitPath *) best_path,
535  flags);
536  break;
537  case T_GatherMerge:
538  plan = (Plan *) create_gather_merge_plan(root,
539  (GatherMergePath *) best_path);
540  break;
541  default:
542  elog(ERROR, "unrecognized node type: %d",
543  (int) best_path->pathtype);
544  plan = NULL; /* keep compiler quiet */