PostgreSQL Source Code  git master
createplan.c File Reference
#include "postgres.h"
#include <limits.h>
#include <math.h>
#include "access/stratnum.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/paths.h"
#include "optimizer/placeholder.h"
#include "optimizer/plancat.h"
#include "optimizer/planmain.h"
#include "optimizer/planner.h"
#include "optimizer/predtest.h"
#include "optimizer/restrictinfo.h"
#include "optimizer/subselect.h"
#include "optimizer/tlist.h"
#include "optimizer/var.h"
#include "parser/parse_clause.h"
#include "parser/parsetree.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 */
 

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 Plancreate_append_plan (PlannerInfo *root, AppendPath *best_path)
 
static Plancreate_merge_append_plan (PlannerInfo *root, MergeAppendPath *best_path)
 
static Resultcreate_result_plan (PlannerInfo *root, ResultPath *best_path)
 
static ProjectSetcreate_project_set_plan (PlannerInfo *root, ProjectSetPath *best_path)
 
static Materialcreate_material_plan (PlannerInfo *root, MaterialPath *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)
 
static Planinject_projection_plan (Plan *subplan, List *tlist, bool parallel_safe)
 
static Sortcreate_sort_plan (PlannerInfo *root, SortPath *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 void get_column_info_for_window (PlannerInfo *root, WindowClause *wc, List *tlist, int numSortCols, AttrNumber *sortColIdx, int *partNumCols, AttrNumber **partColIdx, Oid **partOperators, int *ordNumCols, AttrNumber **ordColIdx, Oid **ordOperators)
 
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 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 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 process_subquery_nestloop_params (PlannerInfo *root, List *subplan_params)
 
static Listfix_indexqual_references (PlannerInfo *root, IndexPath *index_path)
 
static Listfix_indexorderby_references (PlannerInfo *root, IndexPath *index_path)
 
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 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 Appendmake_append (List *appendplans, int first_partial_plan, List *tlist, List *partitioned_rels)
 
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, Plan *lefttree, Plan *righttree, JoinType jointype, bool inner_unique)
 
static Hashmake_hash (Plan *lefttree, 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 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 EquivalenceMemberfind_ec_member_for_tle (EquivalenceClass *ec, TargetEntry *tle, Relids relids)
 
static Sortmake_sort_from_pathkeys (Plan *lefttree, List *pathkeys, Relids relids)
 
static Sortmake_sort_from_groupcols (List *groupcls, AttrNumber *grpColIdx, Plan *lefttree)
 
static Materialmake_material (Plan *lefttree)
 
static WindowAggmake_windowagg (List *tlist, Index winref, int partNumCols, AttrNumber *partColIdx, Oid *partOperators, int ordNumCols, AttrNumber *ordColIdx, Oid *ordOperators, 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, 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, CmdType operation, bool canSetTag, Index nominalRelation, List *partitioned_rels, bool partColsUpdated, List *resultRelations, List *subplans, 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)
 
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, List *groupingSets, List *chain, double dNumGroups, Plan *lefttree)
 
Limitmake_limit (Plan *lefttree, Node *limitOffset, Node *limitCount)
 
bool is_projection_capable_path (Path *path)
 
bool is_projection_capable_plan (Plan *plan)
 

Macro Definition Documentation

◆ CP_EXACT_TLIST

◆ CP_LABEL_TLIST

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

◆ CP_SMALL_TLIST

#define CP_SMALL_TLIST   0x0002 /* Prefer narrower tlists */

Function Documentation

◆ bitmap_subplan_mark_shared()

static void bitmap_subplan_mark_shared ( Plan plan)
static

Definition at line 4959 of file createplan.c.

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

Referenced by create_bitmap_scan_plan().

4960 {
4961  if (IsA(plan, BitmapAnd))
4963  linitial(((BitmapAnd *) plan)->bitmapplans));
4964  else if (IsA(plan, BitmapOr))
4965  {
4966  ((BitmapOr *) plan)->isshared = true;
4968  linitial(((BitmapOr *) plan)->bitmapplans));
4969  }
4970  else if (IsA(plan, BitmapIndexScan))
4971  ((BitmapIndexScan *) plan)->isshared = true;
4972  else
4973  elog(ERROR, "unrecognized node type: %d", nodeTag(plan));
4974 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:564
#define linitial(l)
Definition: pg_list.h:111
#define ERROR
Definition: elog.h:43
static void bitmap_subplan_mark_shared(Plan *plan)
Definition: createplan.c:4959
#define nodeTag(nodeptr)
Definition: nodes.h:518
#define elog
Definition: elog.h:219

◆ build_path_tlist()

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

Definition at line 736 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_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_result_plan(), create_scan_plan(), create_unique_plan(), and create_windowagg_plan().

737 {
738  List *tlist = NIL;
739  Index *sortgrouprefs = path->pathtarget->sortgrouprefs;
740  int resno = 1;
741  ListCell *v;
742 
743  foreach(v, path->pathtarget->exprs)
744  {
745  Node *node = (Node *) lfirst(v);
746  TargetEntry *tle;
747 
748  /*
749  * If it's a parameterized path, there might be lateral references in
750  * the tlist, which need to be replaced with Params. There's no need
751  * to remake the TargetEntry nodes, so apply this to each list item
752  * separately.
753  */
754  if (path->param_info)
755  node = replace_nestloop_params(root, node);
756 
757  tle = makeTargetEntry((Expr *) node,
758  resno,
759  NULL,
760  false);
761  if (sortgrouprefs)
762  tle->ressortgroupref = sortgrouprefs[resno - 1];
763 
764  tlist = lappend(tlist, tle);
765  resno++;
766  }
767  return tlist;
768 }
#define NIL
Definition: pg_list.h:69
PathTarget * pathtarget
Definition: relation.h:1047
static Node * replace_nestloop_params(PlannerInfo *root, Node *expr)
Definition: createplan.c:4244
ParamPathInfo * param_info
Definition: relation.h:1049
Definition: nodes.h:513
Index * sortgrouprefs
Definition: relation.h:977
TargetEntry * makeTargetEntry(Expr *expr, AttrNumber resno, char *resname, bool resjunk)
Definition: makefuncs.c:237
List * lappend(List *list, void *datum)
Definition: list.c:128
List * exprs
Definition: relation.h:976
unsigned int Index
Definition: c.h:431
#define lfirst(lc)
Definition: pg_list.h:106
Index ressortgroupref
Definition: primnodes.h:1378
Definition: pg_list.h:45

◆ copy_generic_path_info()

static void copy_generic_path_info ( Plan dest,
Path src 
)
static

Definition at line 4896 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_groupingsets_plan(), create_hashjoin_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_result_plan(), create_samplescan_plan(), create_seqscan_plan(), create_setop_plan(), create_sort_plan(), create_subqueryscan_plan(), create_tablefuncscan_plan(), create_tidscan_plan(), create_unique_plan(), create_upper_unique_plan(), create_valuesscan_plan(), create_windowagg_plan(), and create_worktablescan_plan().

4897 {
4898  dest->startup_cost = src->startup_cost;
4899  dest->total_cost = src->total_cost;
4900  dest->plan_rows = src->rows;
4901  dest->plan_width = src->pathtarget->width;
4902  dest->parallel_aware = src->parallel_aware;
4903  dest->parallel_safe = src->parallel_safe;
4904 }
double plan_rows
Definition: plannodes.h:131
PathTarget * pathtarget
Definition: relation.h:1047
Cost startup_cost
Definition: relation.h:1057
Cost startup_cost
Definition: plannodes.h:125
bool parallel_aware
Definition: plannodes.h:137
Cost total_cost
Definition: relation.h:1058
int plan_width
Definition: plannodes.h:132
double rows
Definition: relation.h:1056
bool parallel_safe
Definition: relation.h:1052
int width
Definition: relation.h:979
Cost total_cost
Definition: plannodes.h:126
bool parallel_aware
Definition: relation.h:1051
bool parallel_safe
Definition: plannodes.h:138

◆ copy_plan_costsize()

static void copy_plan_costsize ( Plan dest,
Plan src 
)
static

Definition at line 4911 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().

4912 {
4913  dest->startup_cost = src->startup_cost;
4914  dest->total_cost = src->total_cost;
4915  dest->plan_rows = src->plan_rows;
4916  dest->plan_width = src->plan_width;
4917  /* Assume the inserted node is not parallel-aware. */
4918  dest->parallel_aware = false;
4919  /* Assume the inserted node is parallel-safe, if child plan is. */
4920  dest->parallel_safe = src->parallel_safe;
4921 }
double plan_rows
Definition: plannodes.h:131
Cost startup_cost
Definition: plannodes.h:125
bool parallel_aware
Definition: plannodes.h:137
int plan_width
Definition: plannodes.h:132
Cost total_cost
Definition: plannodes.h:126
bool parallel_safe
Definition: plannodes.h:138

◆ create_agg_plan()

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

Definition at line 1752 of file createplan.c.

References AggPath::aggsplit, AggPath::aggstrategy, build_path_tlist(), copy_generic_path_info(), CP_LABEL_TLIST, create_plan_recurse(), 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, and Plan::targetlist.

Referenced by create_plan_recurse().

1753 {
1754  Agg *plan;
1755  Plan *subplan;
1756  List *tlist;
1757  List *quals;
1758 
1759  /*
1760  * Agg can project, so no need to be terribly picky about child tlist, but
1761  * we do need grouping columns to be available
1762  */
1763  subplan = create_plan_recurse(root, best_path->subpath, CP_LABEL_TLIST);
1764 
1765  tlist = build_path_tlist(root, &best_path->path);
1766 
1767  quals = order_qual_clauses(root, best_path->qual);
1768 
1769  plan = make_agg(tlist, quals,
1770  best_path->aggstrategy,
1771  best_path->aggsplit,
1772  list_length(best_path->groupClause),
1774  subplan->targetlist),
1775  extract_grouping_ops(best_path->groupClause),
1776  NIL,
1777  NIL,
1778  best_path->numGroups,
1779  subplan);
1780 
1781  copy_generic_path_info(&plan->plan, (Path *) best_path);
1782 
1783  return plan;
1784 }
#define NIL
Definition: pg_list.h:69
AggStrategy aggstrategy
Definition: relation.h:1560
List * qual
Definition: relation.h:1564
static List * order_qual_clauses(PlannerInfo *root, List *clauses)
Definition: createplan.c:4802
AggSplit aggsplit
Definition: relation.h:1561
Oid * extract_grouping_ops(List *groupClause)
Definition: tlist.c:466
double numGroups
Definition: relation.h:1562
AttrNumber * extract_grouping_cols(List *groupClause, List *tlist)
Definition: tlist.c:492
Agg * make_agg(List *tlist, List *qual, AggStrategy aggstrategy, AggSplit aggsplit, int numGroupCols, AttrNumber *grpColIdx, Oid *grpOperators, List *groupingSets, List *chain, double dNumGroups, Plan *lefttree)
Definition: createplan.c:6049
static Plan * create_plan_recurse(PlannerInfo *root, Path *best_path, int flags)
Definition: createplan.c:359
static void copy_generic_path_info(Plan *dest, Path *src)
Definition: createplan.c:4896
static List * build_path_tlist(PlannerInfo *root, Path *path)
Definition: createplan.c:736
List * groupClause
Definition: relation.h:1563
Plan plan
Definition: plannodes.h:784
#define CP_LABEL_TLIST
Definition: createplan.c:68
static int list_length(const List *l)
Definition: pg_list.h:89
Path * subpath
Definition: relation.h:1559
List * targetlist
Definition: plannodes.h:144
Definition: plannodes.h:782
Definition: pg_list.h:45
Path path
Definition: relation.h:1558

◆ create_append_plan()

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

Definition at line 1019 of file createplan.c.

References build_path_tlist(), copy_generic_path_info(), CP_EXACT_TLIST, create_plan_recurse(), AppendPath::first_partial_path, lappend(), lfirst, list_make1, make_append(), make_result(), makeBoolConst(), NIL, AppendPath::partitioned_rels, AppendPath::path, Append::plan, subpath(), and AppendPath::subpaths.

Referenced by create_plan_recurse().

1020 {
1021  Append *plan;
1022  List *tlist = build_path_tlist(root, &best_path->path);
1023  List *subplans = NIL;
1024  ListCell *subpaths;
1025 
1026  /*
1027  * The subpaths list could be empty, if every child was proven empty by
1028  * constraint exclusion. In that case generate a dummy plan that returns
1029  * no rows.
1030  *
1031  * Note that an AppendPath with no members is also generated in certain
1032  * cases where there was no appending construct at all, but we know the
1033  * relation is empty (see set_dummy_rel_pathlist).
1034  */
1035  if (best_path->subpaths == NIL)
1036  {
1037  /* Generate a Result plan with constant-FALSE gating qual */
1038  Plan *plan;
1039 
1040  plan = (Plan *) make_result(tlist,
1041  (Node *) list_make1(makeBoolConst(false,
1042  false)),
1043  NULL);
1044 
1045  copy_generic_path_info(plan, (Path *) best_path);
1046 
1047  return plan;
1048  }
1049 
1050  /* Build the plan for each child */
1051  foreach(subpaths, best_path->subpaths)
1052  {
1053  Path *subpath = (Path *) lfirst(subpaths);
1054  Plan *subplan;
1055 
1056  /* Must insist that all children return the same tlist */
1057  subplan = create_plan_recurse(root, subpath, CP_EXACT_TLIST);
1058 
1059  subplans = lappend(subplans, subplan);
1060  }
1061 
1062  /*
1063  * XXX ideally, if there's just one child, we'd not bother to generate an
1064  * Append node but just return the single child. At the moment this does
1065  * not work because the varno of the child scan plan won't match the
1066  * parent-rel Vars it'll be asked to emit.
1067  */
1068 
1069  plan = make_append(subplans, best_path->first_partial_path,
1070  tlist, best_path->partitioned_rels);
1071 
1072  copy_generic_path_info(&plan->plan, (Path *) best_path);
1073 
1074  return (Plan *) plan;
1075 }
#define NIL
Definition: pg_list.h:69
static Append * make_append(List *appendplans, int first_partial_plan, List *tlist, List *partitioned_rels)
Definition: createplan.c:5317
Definition: nodes.h:513
Path path
Definition: relation.h:1272
int first_partial_path
Definition: relation.h:1278
#define list_make1(x1)
Definition: pg_list.h:139
List * subpaths
Definition: relation.h:1275
static Plan * create_plan_recurse(PlannerInfo *root, Path *best_path, int flags)
Definition: createplan.c:359
static void copy_generic_path_info(Plan *dest, Path *src)
Definition: createplan.c:4896
static List * build_path_tlist(PlannerInfo *root, Path *path)
Definition: createplan.c:736
Node * makeBoolConst(bool value, bool isnull)
Definition: makefuncs.c:356
static Result * make_result(List *tlist, Node *resconstantqual, Plan *subplan)
Definition: createplan.c:6416
List * lappend(List *list, void *datum)
Definition: list.c:128
#define lfirst(lc)
Definition: pg_list.h:106
List * partitioned_rels
Definition: relation.h:1274
#define CP_EXACT_TLIST
Definition: createplan.c:66
Definition: pg_list.h:45
Datum subpath(PG_FUNCTION_ARGS)
Definition: ltree_op.c:234

◆ create_bitmap_scan_plan()

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

Definition at line 2704 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().

2708 {
2709  Index baserelid = best_path->path.parent->relid;
2710  Plan *bitmapqualplan;
2711  List *bitmapqualorig;
2712  List *indexquals;
2713  List *indexECs;
2714  List *qpqual;
2715  ListCell *l;
2716  BitmapHeapScan *scan_plan;
2717 
2718  /* it should be a base rel... */
2719  Assert(baserelid > 0);
2720  Assert(best_path->path.parent->rtekind == RTE_RELATION);
2721 
2722  /* Process the bitmapqual tree into a Plan tree and qual lists */
2723  bitmapqualplan = create_bitmap_subplan(root, best_path->bitmapqual,
2724  &bitmapqualorig, &indexquals,
2725  &indexECs);
2726 
2727  if (best_path->path.parallel_aware)
2728  bitmap_subplan_mark_shared(bitmapqualplan);
2729 
2730  /*
2731  * The qpqual list must contain all restrictions not automatically handled
2732  * by the index, other than pseudoconstant clauses which will be handled
2733  * by a separate gating plan node. All the predicates in the indexquals
2734  * will be checked (either by the index itself, or by
2735  * nodeBitmapHeapscan.c), but if there are any "special" operators
2736  * involved then they must be added to qpqual. The upshot is that qpqual
2737  * must contain scan_clauses minus whatever appears in indexquals.
2738  *
2739  * This loop is similar to the comparable code in create_indexscan_plan(),
2740  * but with some differences because it has to compare the scan clauses to
2741  * stripped (no RestrictInfos) indexquals. See comments there for more
2742  * info.
2743  *
2744  * In normal cases simple equal() checks will be enough to spot duplicate
2745  * clauses, so we try that first. We next see if the scan clause is
2746  * redundant with any top-level indexqual by virtue of being generated
2747  * from the same EC. After that, try predicate_implied_by().
2748  *
2749  * Unlike create_indexscan_plan(), the predicate_implied_by() test here is
2750  * useful for getting rid of qpquals that are implied by index predicates,
2751  * because the predicate conditions are included in the "indexquals"
2752  * returned by create_bitmap_subplan(). Bitmap scans have to do it that
2753  * way because predicate conditions need to be rechecked if the scan
2754  * becomes lossy, so they have to be included in bitmapqualorig.
2755  */
2756  qpqual = NIL;
2757  foreach(l, scan_clauses)
2758  {
2759  RestrictInfo *rinfo = lfirst_node(RestrictInfo, l);
2760  Node *clause = (Node *) rinfo->clause;
2761 
2762  if (rinfo->pseudoconstant)
2763  continue; /* we may drop pseudoconstants here */
2764  if (list_member(indexquals, clause))
2765  continue; /* simple duplicate */
2766  if (rinfo->parent_ec && list_member_ptr(indexECs, rinfo->parent_ec))
2767  continue; /* derived from same EquivalenceClass */
2768  if (!contain_mutable_functions(clause) &&
2769  predicate_implied_by(list_make1(clause), indexquals, false))
2770  continue; /* provably implied by indexquals */
2771  qpqual = lappend(qpqual, rinfo);
2772  }
2773 
2774  /* Sort clauses into best execution order */
2775  qpqual = order_qual_clauses(root, qpqual);
2776 
2777  /* Reduce RestrictInfo list to bare expressions; ignore pseudoconstants */
2778  qpqual = extract_actual_clauses(qpqual, false);
2779 
2780  /*
2781  * When dealing with special operators, we will at this point have
2782  * duplicate clauses in qpqual and bitmapqualorig. We may as well drop
2783  * 'em from bitmapqualorig, since there's no point in making the tests
2784  * twice.
2785  */
2786  bitmapqualorig = list_difference_ptr(bitmapqualorig, qpqual);
2787 
2788  /*
2789  * We have to replace any outer-relation variables with nestloop params in
2790  * the qpqual and bitmapqualorig expressions. (This was already done for
2791  * expressions attached to plan nodes in the bitmapqualplan tree.)
2792  */
2793  if (best_path->path.param_info)
2794  {
2795  qpqual = (List *)
2796  replace_nestloop_params(root, (Node *) qpqual);
2797  bitmapqualorig = (List *)
2798  replace_nestloop_params(root, (Node *) bitmapqualorig);
2799  }
2800 
2801  /* Finally ready to build the plan node */
2802  scan_plan = make_bitmap_heapscan(tlist,
2803  qpqual,
2804  bitmapqualplan,
2805  bitmapqualorig,
2806  baserelid);
2807 
2808  copy_generic_path_info(&scan_plan->scan.plan, &best_path->path);
2809 
2810  return scan_plan;
2811 }
#define NIL
Definition: pg_list.h:69
bool predicate_implied_by(List *predicate_list, List *clause_list, bool clause_is_check)
Definition: predtest.c:135
Plan plan
Definition: plannodes.h:330
static Node * replace_nestloop_params(PlannerInfo *root, Node *expr)
Definition: createplan.c:4244
List * list_difference_ptr(const List *list1, const List *list2)
Definition: list.c:884
bool pseudoconstant
Definition: relation.h:1855
ParamPathInfo * param_info
Definition: relation.h:1049
Definition: nodes.h:513
static List * order_qual_clauses(PlannerInfo *root, List *clauses)
Definition: createplan.c:4802
static Plan * create_bitmap_subplan(PlannerInfo *root, Path *bitmapqual, List **qual, List **indexqual, List **indexECs)
Definition: createplan.c:2834
#define list_make1(x1)
Definition: pg_list.h:139
static BitmapHeapScan * make_bitmap_heapscan(List *qptlist, List *qpqual, Plan *lefttree, List *bitmapqualorig, Index scanrelid)
Definition: createplan.c:5106
static void copy_generic_path_info(Plan *dest, Path *src)
Definition: createplan.c:4896
bool list_member(const List *list, const void *datum)
Definition: list.c:444
EquivalenceClass * parent_ec
Definition: relation.h:1881
RelOptInfo * parent
Definition: relation.h:1046
Path * bitmapqual
Definition: relation.h:1154
#define lfirst_node(type, lc)
Definition: pg_list.h:109
Index relid
Definition: relation.h:613
List * lappend(List *list, void *datum)
Definition: list.c:128
static void bitmap_subplan_mark_shared(Plan *plan)
Definition: createplan.c:4959
Expr * clause
Definition: relation.h:1847
unsigned int Index
Definition: c.h:431
RTEKind rtekind
Definition: relation.h:615
bool list_member_ptr(const List *list, const void *datum)
Definition: list.c:465
#define Assert(condition)
Definition: c.h:688
List * extract_actual_clauses(List *restrictinfo_list, bool pseudoconstant)
Definition: restrictinfo.c:356
bool contain_mutable_functions(Node *clause)
Definition: clauses.c:881
bool parallel_aware
Definition: relation.h:1051
Definition: pg_list.h:45

◆ create_bitmap_subplan()

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

Definition at line 2834 of file createplan.c.

References BitmapAndPath::bitmapquals, BitmapOrPath::bitmapquals, BitmapAndPath::bitmapselectivity, BitmapOrPath::bitmapselectivity, castNode, clamp_row_est(), create_indexscan_plan(), elog, ERROR, get_actual_clauses(), IndexPath::indexclauses, IndexScan::indexid, IndexPath::indexinfo, IndexScan::indexqual, IndexScan::indexqualorig, IndexPath::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(), 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().

2836 {
2837  Plan *plan;
2838 
2839  if (IsA(bitmapqual, BitmapAndPath))
2840  {
2841  BitmapAndPath *apath = (BitmapAndPath *) bitmapqual;
2842  List *subplans = NIL;
2843  List *subquals = NIL;
2844  List *subindexquals = NIL;
2845  List *subindexECs = NIL;
2846  ListCell *l;
2847 
2848  /*
2849  * There may well be redundant quals among the subplans, since a
2850  * top-level WHERE qual might have gotten used to form several
2851  * different index quals. We don't try exceedingly hard to eliminate
2852  * redundancies, but we do eliminate obvious duplicates by using
2853  * list_concat_unique.
2854  */
2855  foreach(l, apath->bitmapquals)
2856  {
2857  Plan *subplan;
2858  List *subqual;
2859  List *subindexqual;
2860  List *subindexEC;
2861 
2862  subplan = create_bitmap_subplan(root, (Path *) lfirst(l),
2863  &subqual, &subindexqual,
2864  &subindexEC);
2865  subplans = lappend(subplans, subplan);
2866  subquals = list_concat_unique(subquals, subqual);
2867  subindexquals = list_concat_unique(subindexquals, subindexqual);
2868  /* Duplicates in indexECs aren't worth getting rid of */
2869  subindexECs = list_concat(subindexECs, subindexEC);
2870  }
2871  plan = (Plan *) make_bitmap_and(subplans);
2872  plan->startup_cost = apath->path.startup_cost;
2873  plan->total_cost = apath->path.total_cost;
2874  plan->plan_rows =
2875  clamp_row_est(apath->bitmapselectivity * apath->path.parent->tuples);
2876  plan->plan_width = 0; /* meaningless */
2877  plan->parallel_aware = false;
2878  plan->parallel_safe = apath->path.parallel_safe;
2879  *qual = subquals;
2880  *indexqual = subindexquals;
2881  *indexECs = subindexECs;
2882  }
2883  else if (IsA(bitmapqual, BitmapOrPath))
2884  {
2885  BitmapOrPath *opath = (BitmapOrPath *) bitmapqual;
2886  List *subplans = NIL;
2887  List *subquals = NIL;
2888  List *subindexquals = NIL;
2889  bool const_true_subqual = false;
2890  bool const_true_subindexqual = false;
2891  ListCell *l;
2892 
2893  /*
2894  * Here, we only detect qual-free subplans. A qual-free subplan would
2895  * cause us to generate "... OR true ..." which we may as well reduce
2896  * to just "true". We do not try to eliminate redundant subclauses
2897  * because (a) it's not as likely as in the AND case, and (b) we might
2898  * well be working with hundreds or even thousands of OR conditions,
2899  * perhaps from a long IN list. The performance of list_append_unique
2900  * would be unacceptable.
2901  */
2902  foreach(l, opath->bitmapquals)
2903  {
2904  Plan *subplan;
2905  List *subqual;
2906  List *subindexqual;
2907  List *subindexEC;
2908 
2909  subplan = create_bitmap_subplan(root, (Path *) lfirst(l),
2910  &subqual, &subindexqual,
2911  &subindexEC);
2912  subplans = lappend(subplans, subplan);
2913  if (subqual == NIL)
2914  const_true_subqual = true;
2915  else if (!const_true_subqual)
2916  subquals = lappend(subquals,
2917  make_ands_explicit(subqual));
2918  if (subindexqual == NIL)
2919  const_true_subindexqual = true;
2920  else if (!const_true_subindexqual)
2921  subindexquals = lappend(subindexquals,
2922  make_ands_explicit(subindexqual));
2923  }
2924 
2925  /*
2926  * In the presence of ScalarArrayOpExpr quals, we might have built
2927  * BitmapOrPaths with just one subpath; don't add an OR step.
2928  */
2929  if (list_length(subplans) == 1)
2930  {
2931  plan = (Plan *) linitial(subplans);
2932  }
2933  else
2934  {
2935  plan = (Plan *) make_bitmap_or(subplans);
2936  plan->startup_cost = opath->path.startup_cost;
2937  plan->total_cost = opath->path.total_cost;
2938  plan->plan_rows =
2939  clamp_row_est(opath->bitmapselectivity * opath->path.parent->tuples);
2940  plan->plan_width = 0; /* meaningless */
2941  plan->parallel_aware = false;
2942  plan->parallel_safe = opath->path.parallel_safe;
2943  }
2944 
2945  /*
2946  * If there were constant-TRUE subquals, the OR reduces to constant
2947  * TRUE. Also, avoid generating one-element ORs, which could happen
2948  * due to redundancy elimination or ScalarArrayOpExpr quals.
2949  */
2950  if (const_true_subqual)
2951  *qual = NIL;
2952  else if (list_length(subquals) <= 1)
2953  *qual = subquals;
2954  else
2955  *qual = list_make1(make_orclause(subquals));
2956  if (const_true_subindexqual)
2957  *indexqual = NIL;
2958  else if (list_length(subindexquals) <= 1)
2959  *indexqual = subindexquals;
2960  else
2961  *indexqual = list_make1(make_orclause(subindexquals));
2962  *indexECs = NIL;
2963  }
2964  else if (IsA(bitmapqual, IndexPath))
2965  {
2966  IndexPath *ipath = (IndexPath *) bitmapqual;
2967  IndexScan *iscan;
2968  List *subindexECs;
2969  ListCell *l;
2970 
2971  /* Use the regular indexscan plan build machinery... */
2972  iscan = castNode(IndexScan,
2973  create_indexscan_plan(root, ipath,
2974  NIL, NIL, false));
2975  /* then convert to a bitmap indexscan */
2976  plan = (Plan *) make_bitmap_indexscan(iscan->scan.scanrelid,
2977  iscan->indexid,
2978  iscan->indexqual,
2979  iscan->indexqualorig);
2980  /* and set its cost/width fields appropriately */
2981  plan->startup_cost = 0.0;
2982  plan->total_cost = ipath->indextotalcost;
2983  plan->plan_rows =
2984  clamp_row_est(ipath->indexselectivity * ipath->path.parent->tuples);
2985  plan->plan_width = 0; /* meaningless */
2986  plan->parallel_aware = false;
2987  plan->parallel_safe = ipath->path.parallel_safe;
2988  *qual = get_actual_clauses(ipath->indexclauses);
2989  *indexqual = get_actual_clauses(ipath->indexquals);
2990  foreach(l, ipath->indexinfo->indpred)
2991  {
2992  Expr *pred = (Expr *) lfirst(l);
2993 
2994  /*
2995  * We know that the index predicate must have been implied by the
2996  * query condition as a whole, but it may or may not be implied by
2997  * the conditions that got pushed into the bitmapqual. Avoid
2998  * generating redundant conditions.
2999  */
3000  if (!predicate_implied_by(list_make1(pred), ipath->indexclauses,
3001  false))
3002  {
3003  *qual = lappend(*qual, pred);
3004  *indexqual = lappend(*indexqual, pred);
3005  }
3006  }
3007  subindexECs = NIL;
3008  foreach(l, ipath->indexquals)
3009  {
3010  RestrictInfo *rinfo = (RestrictInfo *) lfirst(l);
3011 
3012  if (rinfo->parent_ec)
3013  subindexECs = lappend(subindexECs, rinfo->parent_ec);
3014  }
3015  *indexECs = subindexECs;
3016  }
3017  else
3018  {
3019  elog(ERROR, "unrecognized node type: %d", nodeTag(bitmapqual));
3020  plan = NULL; /* keep compiler quiet */
3021  }
3022 
3023  return plan;
3024 }
#define NIL
Definition: pg_list.h:69
bool predicate_implied_by(List *predicate_list, List *clause_list, bool clause_is_check)
Definition: predtest.c:135
double plan_rows
Definition: plannodes.h:131
#define IsA(nodeptr, _type_)
Definition: nodes.h:564
Path path
Definition: relation.h:1122
IndexOptInfo * indexinfo
Definition: relation.h:1123
Index scanrelid
Definition: plannodes.h:331
#define castNode(_type_, nodeptr)
Definition: nodes.h:582
double tuples
Definition: relation.h:625
List * indexqualorig
Definition: plannodes.h:393
List * get_actual_clauses(List *restrictinfo_list)
Definition: restrictinfo.c:333
List * list_concat(List *list1, List *list2)
Definition: list.c:321
List * indexclauses
Definition: relation.h:1124
static Plan * create_bitmap_subplan(PlannerInfo *root, Path *bitmapqual, List **qual, List **indexqual, List **indexECs)
Definition: createplan.c:2834
Selectivity bitmapselectivity
Definition: relation.h:1167
static BitmapAnd * make_bitmap_and(List *bitmapplans)
Definition: createplan.c:5387
Oid indexid
Definition: plannodes.h:391
List * bitmapquals
Definition: relation.h:1166
List * bitmapquals
Definition: relation.h:1179
Expr * make_ands_explicit(List *andclauses)
Definition: clauses.c:370
#define list_make1(x1)
Definition: pg_list.h:139
List * indexquals
Definition: relation.h:1125
#define linitial(l)
Definition: pg_list.h:111
#define ERROR
Definition: elog.h:43
Cost indextotalcost
Definition: relation.h:1130
Cost startup_cost
Definition: relation.h:1057
Scan scan
Definition: plannodes.h:390
EquivalenceClass * parent_ec
Definition: relation.h:1881
RelOptInfo * parent
Definition: relation.h:1046
Selectivity indexselectivity
Definition: relation.h:1131
Cost startup_cost
Definition: plannodes.h:125
bool parallel_aware
Definition: plannodes.h:137
Selectivity bitmapselectivity
Definition: relation.h:1180
List * indexqual
Definition: plannodes.h:392
List * lappend(List *list, void *datum)
Definition: list.c:128
static BitmapOr * make_bitmap_or(List *bitmapplans)
Definition: createplan.c:5402
Cost total_cost
Definition: relation.h:1058
int plan_width
Definition: plannodes.h:132
#define lfirst(lc)
Definition: pg_list.h:106
bool parallel_safe
Definition: relation.h:1052
static int list_length(const List *l)
Definition: pg_list.h:89
List * list_concat_unique(List *list1, List *list2)
Definition: list.c:1018
static BitmapIndexScan * make_bitmap_indexscan(Index scanrelid, Oid indexid, List *indexqual, List *indexqualorig)
Definition: createplan.c:5085
#define nodeTag(nodeptr)
Definition: nodes.h:518
Cost total_cost
Definition: plannodes.h:126
bool parallel_safe
Definition: plannodes.h:138
#define elog
Definition: elog.h:219
List * indpred
Definition: relation.h:746
double clamp_row_est(double nrows)
Definition: costsize.c:185
Definition: pg_list.h:45
Expr * make_orclause(List *orclauses)
Definition: clauses.c:296
static Scan * create_indexscan_plan(PlannerInfo *root, IndexPath *best_path, List *tlist, List *scan_clauses, bool indexonly)
Definition: createplan.c:2528

◆ create_ctescan_plan()

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

Definition at line 3264 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().

3266 {
3267  CteScan *scan_plan;
3268  Index scan_relid = best_path->parent->relid;
3269  RangeTblEntry *rte;
3270  SubPlan *ctesplan = NULL;
3271  int plan_id;
3272  int cte_param_id;
3273  PlannerInfo *cteroot;
3274  Index levelsup;
3275  int ndx;
3276  ListCell *lc;
3277 
3278  Assert(scan_relid > 0);
3279  rte = planner_rt_fetch(scan_relid, root);
3280  Assert(rte->rtekind == RTE_CTE);
3281  Assert(!rte->self_reference);
3282 
3283  /*
3284  * Find the referenced CTE, and locate the SubPlan previously made for it.
3285  */
3286  levelsup = rte->ctelevelsup;
3287  cteroot = root;
3288  while (levelsup-- > 0)
3289  {
3290  cteroot = cteroot->parent_root;
3291  if (!cteroot) /* shouldn't happen */
3292  elog(ERROR, "bad levelsup for CTE \"%s\"", rte->ctename);
3293  }
3294 
3295  /*
3296  * Note: cte_plan_ids can be shorter than cteList, if we are still working
3297  * on planning the CTEs (ie, this is a side-reference from another CTE).
3298  * So we mustn't use forboth here.
3299  */
3300  ndx = 0;
3301  foreach(lc, cteroot->parse->cteList)
3302  {
3303  CommonTableExpr *cte = (CommonTableExpr *) lfirst(lc);
3304 
3305  if (strcmp(cte->ctename, rte->ctename) == 0)
3306  break;
3307  ndx++;
3308  }
3309  if (lc == NULL) /* shouldn't happen */
3310  elog(ERROR, "could not find CTE \"%s\"", rte->ctename);
3311  if (ndx >= list_length(cteroot->cte_plan_ids))
3312  elog(ERROR, "could not find plan for CTE \"%s\"", rte->ctename);
3313  plan_id = list_nth_int(cteroot->cte_plan_ids, ndx);
3314  Assert(plan_id > 0);
3315  foreach(lc, cteroot->init_plans)
3316  {
3317  ctesplan = (SubPlan *) lfirst(lc);
3318  if (ctesplan->plan_id == plan_id)
3319  break;
3320  }
3321  if (lc == NULL) /* shouldn't happen */
3322  elog(ERROR, "could not find plan for CTE \"%s\"", rte->ctename);
3323 
3324  /*
3325  * We need the CTE param ID, which is the sole member of the SubPlan's
3326  * setParam list.
3327  */
3328  cte_param_id = linitial_int(ctesplan->setParam);
3329 
3330  /* Sort clauses into best execution order */
3331  scan_clauses = order_qual_clauses(root, scan_clauses);
3332 
3333  /* Reduce RestrictInfo list to bare expressions; ignore pseudoconstants */
3334  scan_clauses = extract_actual_clauses(scan_clauses, false);
3335 
3336  /* Replace any outer-relation variables with nestloop params */
3337  if (best_path->param_info)
3338  {
3339  scan_clauses = (List *)
3340  replace_nestloop_params(root, (Node *) scan_clauses);
3341  }
3342 
3343  scan_plan = make_ctescan(tlist, scan_clauses, scan_relid,
3344  plan_id, cte_param_id);
3345 
3346  copy_generic_path_info(&scan_plan->scan.plan, best_path);
3347 
3348  return scan_plan;
3349 }
Plan plan
Definition: plannodes.h:330
Query * parse
Definition: relation.h:155
static Node * replace_nestloop_params(PlannerInfo *root, Node *expr)
Definition: createplan.c:4244
int plan_id
Definition: primnodes.h:689
ParamPathInfo * param_info
Definition: relation.h:1049
Definition: nodes.h:513
static List * order_qual_clauses(PlannerInfo *root, List *clauses)
Definition: createplan.c:4802
#define linitial_int(l)
Definition: pg_list.h:112
static void copy_generic_path_info(Plan *dest, Path *src)
Definition: createplan.c:4896
#define planner_rt_fetch(rti, root)
Definition: relation.h:328
#define ERROR
Definition: elog.h:43
Scan scan
Definition: plannodes.h:540
RelOptInfo * parent
Definition: relation.h:1046
Index relid
Definition: relation.h:613
struct PlannerInfo * parent_root
Definition: relation.h:161
static CteScan * make_ctescan(List *qptlist, List *qpqual, Index scanrelid, int ctePlanId, int cteParam)
Definition: createplan.c:5223
int list_nth_int(const List *list, int n)
Definition: list.c:421
List * cte_plan_ids
Definition: relation.h:230
bool self_reference
Definition: parsenodes.h:1031
unsigned int Index
Definition: c.h:431
List * init_plans
Definition: relation.h:228
#define Assert(condition)
Definition: c.h:688
#define lfirst(lc)
Definition: pg_list.h:106
List * setParam
Definition: primnodes.h:707
static int list_length(const List *l)
Definition: pg_list.h:89
List * extract_actual_clauses(List *restrictinfo_list, bool pseudoconstant)
Definition: restrictinfo.c:356
Index ctelevelsup
Definition: parsenodes.h:1030
RTEKind rtekind
Definition: parsenodes.h:959
List * cteList
Definition: parsenodes.h:133
char * ctename
Definition: parsenodes.h:1029
#define elog
Definition: elog.h:219
Definition: pg_list.h:45

◆ create_customscan_plan()

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

Definition at line 3600 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().

3602 {
3603  CustomScan *cplan;
3604  RelOptInfo *rel = best_path->path.parent;
3605  List *custom_plans = NIL;
3606  ListCell *lc;
3607 
3608  /* Recursively transform child paths. */
3609  foreach(lc, best_path->custom_paths)
3610  {
3611  Plan *plan = create_plan_recurse(root, (Path *) lfirst(lc),
3612  CP_EXACT_TLIST);
3613 
3614  custom_plans = lappend(custom_plans, plan);
3615  }
3616 
3617  /*
3618  * Sort clauses into the best execution order, although custom-scan
3619  * provider can reorder them again.
3620  */
3621  scan_clauses = order_qual_clauses(root, scan_clauses);
3622 
3623  /*
3624  * Invoke custom plan provider to create the Plan node represented by the
3625  * CustomPath.
3626  */
3627  cplan = castNode(CustomScan,
3628  best_path->methods->PlanCustomPath(root,
3629  rel,
3630  best_path,
3631  tlist,
3632  scan_clauses,
3633  custom_plans));
3634 
3635  /*
3636  * Copy cost data from Path to Plan; no need to make custom-plan providers
3637  * do this
3638  */
3639  copy_generic_path_info(&cplan->scan.plan, &best_path->path);
3640 
3641  /* Likewise, copy the relids that are represented by this custom scan */
3642  cplan->custom_relids = best_path->path.parent->relids;
3643 
3644  /*
3645  * Replace any outer-relation variables with nestloop params in the qual
3646  * and custom_exprs expressions. We do this last so that the custom-plan
3647  * provider doesn't have to be involved. (Note that parts of custom_exprs
3648  * could have come from join clauses, so doing this beforehand on the
3649  * scan_clauses wouldn't work.) We assume custom_scan_tlist contains no
3650  * such variables.
3651  */
3652  if (best_path->path.param_info)
3653  {
3654  cplan->scan.plan.qual = (List *)
3655  replace_nestloop_params(root, (Node *) cplan->scan.plan.qual);
3656  cplan->custom_exprs = (List *)
3657  replace_nestloop_params(root, (Node *) cplan->custom_exprs);
3658  }
3659 
3660  return cplan;
3661 }
#define NIL
Definition: pg_list.h:69
List * qual
Definition: plannodes.h:145
Plan plan
Definition: plannodes.h:330
static Node * replace_nestloop_params(PlannerInfo *root, Node *expr)
Definition: createplan.c:4244
List * custom_paths
Definition: relation.h:1253
#define castNode(_type_, nodeptr)
Definition: nodes.h:582
ParamPathInfo * param_info
Definition: relation.h:1049
Definition: nodes.h:513
List * custom_exprs
Definition: plannodes.h:631
static List * order_qual_clauses(PlannerInfo *root, List *clauses)
Definition: createplan.c:4802
static Plan * create_plan_recurse(PlannerInfo *root, Path *best_path, int flags)
Definition: createplan.c:359
const struct CustomPathMethods * methods
Definition: relation.h:1255
static void copy_generic_path_info(Plan *dest, Path *src)
Definition: createplan.c:4896
RelOptInfo * parent
Definition: relation.h:1046
Relids relids
Definition: relation.h:585
Path path
Definition: relation.h:1250
List * lappend(List *list, void *datum)
Definition: list.c:128
Scan scan
Definition: plannodes.h:627
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:106
Bitmapset * custom_relids
Definition: plannodes.h:634
#define CP_EXACT_TLIST
Definition: createplan.c:66
Definition: pg_list.h:45

◆ create_foreignscan_plan()

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

Definition at line 3456 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, IS_UPPER_REL, 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, RelOptInfo::reltarget, replace_nestloop_params(), RTE_RELATION, RelOptInfo::rtekind, RangeTblEntry::rtekind, ForeignScan::scan, RelOptInfo::serverid, and RelOptInfo::useridiscurrent.

Referenced by create_scan_plan().

3458 {
3459  ForeignScan *scan_plan;
3460  RelOptInfo *rel = best_path->path.parent;
3461  Index scan_relid = rel->relid;
3462  Oid rel_oid = InvalidOid;
3463  Plan *outer_plan = NULL;
3464 
3465  Assert(rel->fdwroutine != NULL);
3466 
3467  /* transform the child path if any */
3468  if (best_path->fdw_outerpath)
3469  outer_plan = create_plan_recurse(root, best_path->fdw_outerpath,
3470  CP_EXACT_TLIST);
3471 
3472  /*
3473  * If we're scanning a base relation, fetch its OID. (Irrelevant if
3474  * scanning a join relation.)
3475  */
3476  if (scan_relid > 0)
3477  {
3478  RangeTblEntry *rte;
3479 
3480  Assert(rel->rtekind == RTE_RELATION);
3481  rte = planner_rt_fetch(scan_relid, root);
3482  Assert(rte->rtekind == RTE_RELATION);
3483  rel_oid = rte->relid;
3484  }
3485 
3486  /*
3487  * Sort clauses into best execution order. We do this first since the FDW
3488  * might have more info than we do and wish to adjust the ordering.
3489  */
3490  scan_clauses = order_qual_clauses(root, scan_clauses);
3491 
3492  /*
3493  * Let the FDW perform its processing on the restriction clauses and
3494  * generate the plan node. Note that the FDW might remove restriction
3495  * clauses that it intends to execute remotely, or even add more (if it
3496  * has selected some join clauses for remote use but also wants them
3497  * rechecked locally).
3498  */
3499  scan_plan = rel->fdwroutine->GetForeignPlan(root, rel, rel_oid,
3500  best_path,
3501  tlist, scan_clauses,
3502  outer_plan);
3503 
3504  /* Copy cost data from Path to Plan; no need to make FDW do this */
3505  copy_generic_path_info(&scan_plan->scan.plan, &best_path->path);
3506 
3507  /* Copy foreign server OID; likewise, no need to make FDW do this */
3508  scan_plan->fs_server = rel->serverid;
3509 
3510  /*
3511  * Likewise, copy the relids that are represented by this foreign scan. An
3512  * upper rel doesn't have relids set, but it covers all the base relations
3513  * participating in the underlying scan, so use root's all_baserels.
3514  */
3515  if (IS_UPPER_REL(rel))
3516  scan_plan->fs_relids = root->all_baserels;
3517  else
3518  scan_plan->fs_relids = best_path->path.parent->relids;
3519 
3520  /*
3521  * If this is a foreign join, and to make it valid to push down we had to
3522  * assume that the current user is the same as some user explicitly named
3523  * in the query, mark the finished plan as depending on the current user.
3524  */
3525  if (rel->useridiscurrent)
3526  root->glob->dependsOnRole = true;
3527 
3528  /*
3529  * Replace any outer-relation variables with nestloop params in the qual,
3530  * fdw_exprs and fdw_recheck_quals expressions. We do this last so that
3531  * the FDW doesn't have to be involved. (Note that parts of fdw_exprs or
3532  * fdw_recheck_quals could have come from join clauses, so doing this
3533  * beforehand on the scan_clauses wouldn't work.) We assume
3534  * fdw_scan_tlist contains no such variables.
3535  */
3536  if (best_path->path.param_info)
3537  {
3538  scan_plan->scan.plan.qual = (List *)
3539  replace_nestloop_params(root, (Node *) scan_plan->scan.plan.qual);
3540  scan_plan->fdw_exprs = (List *)
3541  replace_nestloop_params(root, (Node *) scan_plan->fdw_exprs);
3542  scan_plan->fdw_recheck_quals = (List *)
3544  (Node *) scan_plan->fdw_recheck_quals);
3545  }
3546 
3547  /*
3548  * If rel is a base relation, detect whether any system columns are
3549  * requested from the rel. (If rel is a join relation, rel->relid will be
3550  * 0, but there can be no Var with relid 0 in the rel's targetlist or the
3551  * restriction clauses, so we skip this in that case. Note that any such
3552  * columns in base relations that were joined are assumed to be contained
3553  * in fdw_scan_tlist.) This is a bit of a kluge and might go away
3554  * someday, so we intentionally leave it out of the API presented to FDWs.
3555  */
3556  scan_plan->fsSystemCol = false;
3557  if (scan_relid > 0)
3558  {
3559  Bitmapset *attrs_used = NULL;
3560  ListCell *lc;
3561  int i;
3562 
3563  /*
3564  * First, examine all the attributes needed for joins or final output.
3565  * Note: we must look at rel's targetlist, not the attr_needed data,
3566  * because attr_needed isn't computed for inheritance child rels.
3567  */
3568  pull_varattnos((Node *) rel->reltarget->exprs, scan_relid, &attrs_used);
3569 
3570  /* Add all the attributes used by restriction clauses. */
3571  foreach(lc, rel->baserestrictinfo)
3572  {
3573  RestrictInfo *rinfo = (RestrictInfo *) lfirst(lc);
3574 
3575  pull_varattnos((Node *) rinfo->clause, scan_relid, &attrs_used);
3576  }
3577 
3578  /* Now, are any system columns requested from rel? */
3579  for (i = FirstLowInvalidHeapAttributeNumber + 1; i < 0; i++)
3580  {
3582  {
3583  scan_plan->fsSystemCol = true;
3584  break;
3585  }
3586  }
3587 
3588  bms_free(attrs_used);
3589  }
3590 
3591  return scan_plan;
3592 }
GetForeignPlan_function GetForeignPlan
Definition: fdwapi.h:182
List * qual
Definition: plannodes.h:145
Plan plan
Definition: plannodes.h:330
static Node * replace_nestloop_params(PlannerInfo *root, Node *expr)
Definition: createplan.c:4244
Path * fdw_outerpath
Definition: relation.h:1223
Oid fs_server
Definition: plannodes.h:601
List * baserestrictinfo
Definition: relation.h:645
List * fdw_exprs
Definition: plannodes.h:602
#define IS_UPPER_REL(rel)
Definition: relation.h:571
ParamPathInfo * param_info
Definition: relation.h:1049
Definition: nodes.h:513
static List * order_qual_clauses(PlannerInfo *root, List *clauses)
Definition: createplan.c:4802
#define FirstLowInvalidHeapAttributeNumber
Definition: sysattr.h:28
bool useridiscurrent
Definition: relation.h:634
unsigned int Oid
Definition: postgres_ext.h:31
void pull_varattnos(Node *node, Index varno, Bitmapset **varattnos)
Definition: var.c:219
bool dependsOnRole
Definition: relation.h:127
static Plan * create_plan_recurse(PlannerInfo *root, Path *best_path, int flags)
Definition: createplan.c:359
static void copy_generic_path_info(Plan *dest, Path *src)
Definition: createplan.c:4896
#define planner_rt_fetch(rti, root)
Definition: relation.h:328
Relids all_baserels
Definition: relation.h:196
RelOptInfo * parent
Definition: relation.h:1046
PlannerGlobal * glob
Definition: relation.h:157
struct FdwRoutine * fdwroutine
Definition: relation.h:636
Relids relids
Definition: relation.h:585
List * fdw_recheck_quals
Definition: plannodes.h:605
Index relid
Definition: relation.h:613
Expr * clause
Definition: relation.h:1847
Oid serverid
Definition: relation.h:632
List * exprs
Definition: relation.h:976
unsigned int Index
Definition: c.h:431
RTEKind rtekind
Definition: relation.h:615
#define InvalidOid
Definition: postgres_ext.h:36
void bms_free(Bitmapset *a)
Definition: bitmapset.c:245
#define Assert(condition)
Definition: c.h:688
#define lfirst(lc)
Definition: pg_list.h:106
RTEKind rtekind
Definition: parsenodes.h:959
int i
#define CP_EXACT_TLIST
Definition: createplan.c:66
Definition: pg_list.h:45
bool bms_is_member(int x, const Bitmapset *a)
Definition: bitmapset.c:464
struct PathTarget * reltarget
Definition: relation.h:596
bool fsSystemCol
Definition: plannodes.h:607
Bitmapset * fs_relids
Definition: plannodes.h:606

◆ create_functionscan_plan()

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

Definition at line 3134 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().

3136 {
3137  FunctionScan *scan_plan;
3138  Index scan_relid = best_path->parent->relid;
3139  RangeTblEntry *rte;
3140  List *functions;
3141 
3142  /* it should be a function base rel... */
3143  Assert(scan_relid > 0);
3144  rte = planner_rt_fetch(scan_relid, root);
3145  Assert(rte->rtekind == RTE_FUNCTION);
3146  functions = rte->functions;
3147 
3148  /* Sort clauses into best execution order */
3149  scan_clauses = order_qual_clauses(root, scan_clauses);
3150 
3151  /* Reduce RestrictInfo list to bare expressions; ignore pseudoconstants */
3152  scan_clauses = extract_actual_clauses(scan_clauses, false);
3153 
3154  /* Replace any outer-relation variables with nestloop params */
3155  if (best_path->param_info)
3156  {
3157  scan_clauses = (List *)
3158  replace_nestloop_params(root, (Node *) scan_clauses);
3159  /* The function expressions could contain nestloop params, too */
3160  functions = (List *) replace_nestloop_params(root, (Node *) functions);
3161  }
3162 
3163  scan_plan = make_functionscan(tlist, scan_clauses, scan_relid,
3164  functions, rte->funcordinality);
3165 
3166  copy_generic_path_info(&scan_plan->scan.plan, best_path);
3167 
3168  return scan_plan;
3169 }
Plan plan
Definition: plannodes.h:330
static Node * replace_nestloop_params(PlannerInfo *root, Node *expr)
Definition: createplan.c:4244
ParamPathInfo * param_info
Definition: relation.h:1049
Definition: nodes.h:513
static List * order_qual_clauses(PlannerInfo *root, List *clauses)
Definition: createplan.c:4802
bool funcordinality
Definition: parsenodes.h:1014
static void copy_generic_path_info(Plan *dest, Path *src)
Definition: createplan.c:4896
#define planner_rt_fetch(rti, root)
Definition: relation.h:328
RelOptInfo * parent
Definition: relation.h:1046
Index relid
Definition: relation.h:613
unsigned int Index
Definition: c.h:431
static FunctionScan * make_functionscan(List *qptlist, List *qpqual, Index scanrelid, List *functions, bool funcordinality)
Definition: createplan.c:5164
#define Assert(condition)
Definition: c.h:688
List * functions
Definition: parsenodes.h:1013
List * extract_actual_clauses(List *restrictinfo_list, bool pseudoconstant)
Definition: restrictinfo.c:356
static const struct fns functions
Definition: regcomp.c:299
RTEKind rtekind
Definition: parsenodes.h:959
Definition: pg_list.h:45

◆ create_gather_merge_plan()

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

Definition at line 1511 of file createplan.c.

References Assert, build_path_tlist(), GatherMerge::collations, copy_generic_path_info(), CP_EXACT_TLIST, create_plan_recurse(), PlannerInfo::glob, Plan::lefttree, make_sort(), 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, SS_assign_special_param(), GatherMergePath::subpath, and Plan::targetlist.

Referenced by create_plan_recurse().

1512 {
1513  GatherMerge *gm_plan;
1514  Plan *subplan;
1515  List *pathkeys = best_path->path.pathkeys;
1516  List *tlist = build_path_tlist(root, &best_path->path);
1517 
1518  /* As with Gather, it's best to project away columns in the workers. */
1519  subplan = create_plan_recurse(root, best_path->subpath, CP_EXACT_TLIST);
1520 
1521  /* Create a shell for a GatherMerge plan. */
1522  gm_plan = makeNode(GatherMerge);
1523  gm_plan->plan.targetlist = tlist;
1524  gm_plan->num_workers = best_path->num_workers;
1525  copy_generic_path_info(&gm_plan->plan, &best_path->path);
1526 
1527  /* Assign the rescan Param. */
1528  gm_plan->rescan_param = SS_assign_special_param(root);
1529 
1530  /* Gather Merge is pointless with no pathkeys; use Gather instead. */
1531  Assert(pathkeys != NIL);
1532 
1533  /* Compute sort column info, and adjust subplan's tlist as needed */
1534  subplan = prepare_sort_from_pathkeys(subplan, pathkeys,
1535  best_path->subpath->parent->relids,
1536  gm_plan->sortColIdx,
1537  false,
1538  &gm_plan->numCols,
1539  &gm_plan->sortColIdx,
1540  &gm_plan->sortOperators,
1541  &gm_plan->collations,
1542  &gm_plan->nullsFirst);
1543 
1544 
1545  /* Now, insert a Sort node if subplan isn't sufficiently ordered */
1546  if (!pathkeys_contained_in(pathkeys, best_path->subpath->pathkeys))
1547  subplan = (Plan *) make_sort(subplan, gm_plan->numCols,
1548  gm_plan->sortColIdx,
1549  gm_plan->sortOperators,
1550  gm_plan->collations,
1551  gm_plan->nullsFirst);
1552 
1553  /* Now insert the subplan under GatherMerge. */
1554  gm_plan->plan.lefttree = subplan;
1555 
1556  /* use parallel mode for parallel plans. */
1557  root->glob->parallelModeNeeded = true;
1558 
1559  return gm_plan;
1560 }
#define NIL
Definition: pg_list.h:69
Oid * collations
Definition: plannodes.h:869
int SS_assign_special_param(PlannerInfo *root)
Definition: subselect.c:429
AttrNumber * sortColIdx
Definition: plannodes.h:867
bool * nullsFirst
Definition: plannodes.h:870
static Plan * create_plan_recurse(PlannerInfo *root, Path *best_path, int flags)
Definition: createplan.c:359
static void copy_generic_path_info(Plan *dest, Path *src)
Definition: createplan.c:4896
bool parallelModeNeeded
Definition: relation.h:131
static List * build_path_tlist(PlannerInfo *root, Path *path)
Definition: createplan.c:736
RelOptInfo * parent
Definition: relation.h:1046
PlannerGlobal * glob
Definition: relation.h:157
Relids relids
Definition: relation.h:585
Oid * sortOperators
Definition: plannodes.h:868
bool pathkeys_contained_in(List *keys1, List *keys2)
Definition: pathkeys.c:317
List * pathkeys
Definition: relation.h:1060
static Sort * make_sort(Plan *lefttree, int numCols, AttrNumber *sortColIdx, Oid *sortOperators, Oid *collations, bool *nullsFirst)
Definition: createplan.c:5529
#define makeNode(_type_)
Definition: nodes.h:561
#define Assert(condition)
Definition: c.h:688
struct Plan * lefttree
Definition: plannodes.h:146
List * targetlist
Definition: plannodes.h:144
Path * subpath
Definition: relation.h:1376
int num_workers
Definition: plannodes.h:863
int rescan_param
Definition: plannodes.h:864
#define CP_EXACT_TLIST
Definition: createplan.c:66
Definition: pg_list.h:45
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:5591

◆ create_gather_plan()

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

Definition at line 1475 of file createplan.c.

References 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, SS_assign_special_param(), and GatherPath::subpath.

Referenced by create_plan_recurse().

1476 {
1477  Gather *gather_plan;
1478  Plan *subplan;
1479  List *tlist;
1480 
1481  /*
1482  * Although the Gather node can project, we prefer to push down such work
1483  * to its child node, so demand an exact tlist from the child.
1484  */
1485  subplan = create_plan_recurse(root, best_path->subpath, CP_EXACT_TLIST);
1486 
1487  tlist = build_path_tlist(root, &best_path->path);
1488 
1489  gather_plan = make_gather(tlist,
1490  NIL,
1491  best_path->num_workers,
1493  best_path->single_copy,
1494  subplan);
1495 
1496  copy_generic_path_info(&gather_plan->plan, &best_path->path);
1497 
1498  /* use parallel mode for parallel plans. */
1499  root->glob->parallelModeNeeded = true;
1500 
1501  return gather_plan;
1502 }
#define NIL
Definition: pg_list.h:69
int SS_assign_special_param(PlannerInfo *root)
Definition: subselect.c:429
bool single_copy
Definition: relation.h:1364
int num_workers
Definition: relation.h:1365
static Plan * create_plan_recurse(PlannerInfo *root, Path *best_path, int flags)
Definition: createplan.c:359
static void copy_generic_path_info(Plan *dest, Path *src)
Definition: createplan.c:4896
bool parallelModeNeeded
Definition: relation.h:131
static List * build_path_tlist(PlannerInfo *root, Path *path)
Definition: createplan.c:736
Plan plan
Definition: plannodes.h:847
PlannerGlobal * glob
Definition: relation.h:157
Path * subpath
Definition: relation.h:1363
static Gather * make_gather(List *qptlist, List *qpqual, int nworkers, int rescan_param, bool single_copy, Plan *subplan)
Definition: createplan.c:6293
Path path
Definition: relation.h:1362
#define CP_EXACT_TLIST
Definition: createplan.c:66
Definition: pg_list.h:45

◆ create_gating_plan()

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

Definition at line 917 of file createplan.c.

References Assert, build_path_tlist(), copy_plan_costsize(), make_result(), Plan::parallel_safe, and Path::parallel_safe.

Referenced by create_join_plan(), and create_scan_plan().

919 {
920  Plan *gplan;
921 
922  Assert(gating_quals);
923 
924  /*
925  * Since we need a Result node anyway, always return the path's requested
926  * tlist; that's never a wrong choice, even if the parent node didn't ask
927  * for CP_EXACT_TLIST.
928  */
929  gplan = (Plan *) make_result(build_path_tlist(root, path),
930  (Node *) gating_quals,
931  plan);
932 
933  /*
934  * Notice that we don't change cost or size estimates when doing gating.
935  * The costs of qual eval were already included in the subplan's cost.
936  * Leaving the size alone amounts to assuming that the gating qual will
937  * succeed, which is the conservative estimate for planning upper queries.
938  * We certainly don't want to assume the output size is zero (unless the
939  * gating qual is actually constant FALSE, and that case is dealt with in
940  * clausesel.c). Interpolating between the two cases is silly, because it
941  * doesn't reflect what will really happen at runtime, and besides which
942  * in most cases we have only a very bad idea of the probability of the
943  * gating qual being true.
944  */
945  copy_plan_costsize(gplan, plan);
946 
947  /* Gating quals could be unsafe, so better use the Path's safety flag */
948  gplan->parallel_safe = path->parallel_safe;
949 
950  return gplan;
951 }
Definition: nodes.h:513
static List * build_path_tlist(PlannerInfo *root, Path *path)
Definition: createplan.c:736
static void copy_plan_costsize(Plan *dest, Plan *src)
Definition: createplan.c:4911
static Result * make_result(List *tlist, Node *resconstantqual, Plan *subplan)
Definition: createplan.c:6416
#define Assert(condition)
Definition: c.h:688
bool parallel_safe
Definition: relation.h:1052
bool parallel_safe
Definition: plannodes.h:138

◆ create_group_plan()

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

Definition at line 1687 of file createplan.c.

References build_path_tlist(), copy_generic_path_info(), CP_LABEL_TLIST, create_plan_recurse(), 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().

1688 {
1689  Group *plan;
1690  Plan *subplan;
1691  List *tlist;
1692  List *quals;
1693 
1694  /*
1695  * Group can project, so no need to be terribly picky about child tlist,
1696  * but we do need grouping columns to be available
1697  */
1698  subplan = create_plan_recurse(root, best_path->subpath, CP_LABEL_TLIST);
1699 
1700  tlist = build_path_tlist(root, &best_path->path);
1701 
1702  quals = order_qual_clauses(root, best_path->qual);
1703 
1704  plan = make_group(tlist,
1705  quals,
1706  list_length(best_path->groupClause),
1708  subplan->targetlist),
1709  extract_grouping_ops(best_path->groupClause),
1710  subplan);
1711 
1712  copy_generic_path_info(&plan->plan, (Path *) best_path);
1713 
1714  return plan;
1715 }
List * qual
Definition: relation.h:1533
static List * order_qual_clauses(PlannerInfo *root, List *clauses)
Definition: createplan.c:4802
Oid * extract_grouping_ops(List *groupClause)
Definition: tlist.c:466
AttrNumber * extract_grouping_cols(List *groupClause, List *tlist)
Definition: tlist.c:492
static Plan * create_plan_recurse(PlannerInfo *root, Path *best_path, int flags)
Definition: createplan.c:359
static void copy_generic_path_info(Plan *dest, Path *src)
Definition: createplan.c:4896
static List * build_path_tlist(PlannerInfo *root, Path *path)
Definition: createplan.c:736
Path path
Definition: relation.h:1530
static Group * make_group(List *tlist, List *qual, int numGroupCols, AttrNumber *grpColIdx, Oid *grpOperators, Plan *lefttree)
Definition: createplan.c:6118
List * groupClause
Definition: relation.h:1532
#define CP_LABEL_TLIST
Definition: createplan.c:68
Path * subpath
Definition: relation.h:1531
Plan plan
Definition: plannodes.h:762
static int list_length(const List *l)
Definition: pg_list.h:89
List * targetlist
Definition: plannodes.h:144
Definition: pg_list.h:45

◆ create_groupingsets_plan()

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

Definition at line 1833 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_ops(), for_each_cell, get_sortgroupclause_tle(), Query::groupClause, RollupData::groupClause, PlannerInfo::grouping_map, Query::groupingSets, RollupData::gsets, PlannerInfo::hasInheritedTarget, RollupData::is_hashed, lappend(), Plan::lefttree, lfirst, linitial, list_head(), list_length(), lnext, 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, and SortGroupClause::tleSortGroupRef.

Referenced by create_plan_recurse().

1834 {
1835  Agg *plan;
1836  Plan *subplan;
1837  List *rollups = best_path->rollups;
1838  AttrNumber *grouping_map;
1839  int maxref;
1840  List *chain;
1841  ListCell *lc;
1842 
1843  /* Shouldn't get here without grouping sets */
1844  Assert(root->parse->groupingSets);
1845  Assert(rollups != NIL);
1846 
1847  /*
1848  * Agg can project, so no need to be terribly picky about child tlist, but
1849  * we do need grouping columns to be available
1850  */
1851  subplan = create_plan_recurse(root, best_path->subpath, CP_LABEL_TLIST);
1852 
1853  /*
1854  * Compute the mapping from tleSortGroupRef to column index in the child's
1855  * tlist. First, identify max SortGroupRef in groupClause, for array
1856  * sizing.
1857  */
1858  maxref = 0;
1859  foreach(lc, root->parse->groupClause)
1860  {
1861  SortGroupClause *gc = (SortGroupClause *) lfirst(lc);
1862 
1863  if (gc->tleSortGroupRef > maxref)
1864  maxref = gc->tleSortGroupRef;
1865  }
1866 
1867  grouping_map = (AttrNumber *) palloc0((maxref + 1) * sizeof(AttrNumber));
1868 
1869  /* Now look up the column numbers in the child's tlist */
1870  foreach(lc, root->parse->groupClause)
1871  {
1872  SortGroupClause *gc = (SortGroupClause *) lfirst(lc);
1873  TargetEntry *tle = get_sortgroupclause_tle(gc, subplan->targetlist);
1874 
1875  grouping_map[gc->tleSortGroupRef] = tle->resno;
1876  }
1877 
1878  /*
1879  * During setrefs.c, we'll need the grouping_map to fix up the cols lists
1880  * in GroupingFunc nodes. Save it for setrefs.c to use.
1881  *
1882  * This doesn't work if we're in an inheritance subtree (see notes in
1883  * create_modifytable_plan). Fortunately we can't be because there would
1884  * never be grouping in an UPDATE/DELETE; but let's Assert that.
1885  */
1886  Assert(!root->hasInheritedTarget);
1887  Assert(root->grouping_map == NULL);
1888  root->grouping_map = grouping_map;
1889 
1890  /*
1891  * Generate the side nodes that describe the other sort and group
1892  * operations besides the top one. Note that we don't worry about putting
1893  * accurate cost estimates in the side nodes; only the topmost Agg node's
1894  * costs will be shown by EXPLAIN.
1895  */
1896  chain = NIL;
1897  if (list_length(rollups) > 1)
1898  {
1899  ListCell *lc2 = lnext(list_head(rollups));
1900  bool is_first_sort = ((RollupData *) linitial(rollups))->is_hashed;
1901 
1902  for_each_cell(lc, lc2)
1903  {
1904  RollupData *rollup = lfirst(lc);
1905  AttrNumber *new_grpColIdx;
1906  Plan *sort_plan = NULL;
1907  Plan *agg_plan;
1908  AggStrategy strat;
1909 
1910  new_grpColIdx = remap_groupColIdx(root, rollup->groupClause);
1911 
1912  if (!rollup->is_hashed && !is_first_sort)
1913  {
1914  sort_plan = (Plan *)
1916  new_grpColIdx,
1917  subplan);
1918  }
1919 
1920  if (!rollup->is_hashed)
1921  is_first_sort = false;
1922 
1923  if (rollup->is_hashed)
1924  strat = AGG_HASHED;
1925  else if (list_length(linitial(rollup->gsets)) == 0)
1926  strat = AGG_PLAIN;
1927  else
1928  strat = AGG_SORTED;
1929 
1930  agg_plan = (Plan *) make_agg(NIL,
1931  NIL,
1932  strat,
1934  list_length((List *) linitial(rollup->gsets)),
1935  new_grpColIdx,
1937  rollup->gsets,
1938  NIL,
1939  rollup->numGroups,
1940  sort_plan);
1941 
1942  /*
1943  * Remove stuff we don't need to avoid bloating debug output.
1944  */
1945  if (sort_plan)
1946  {
1947  sort_plan->targetlist = NIL;
1948  sort_plan->lefttree = NULL;
1949  }
1950 
1951  chain = lappend(chain, agg_plan);
1952  }
1953  }
1954 
1955  /*
1956  * Now make the real Agg node
1957  */
1958  {
1959  RollupData *rollup = linitial(rollups);
1960  AttrNumber *top_grpColIdx;
1961  int numGroupCols;
1962 
1963  top_grpColIdx = remap_groupColIdx(root, rollup->groupClause);
1964 
1965  numGroupCols = list_length((List *) linitial(rollup->gsets));
1966 
1967  plan = make_agg(build_path_tlist(root, &best_path->path),
1968  best_path->qual,
1969  best_path->aggstrategy,
1971  numGroupCols,
1972  top_grpColIdx,
1974  rollup->gsets,
1975  chain,
1976  rollup->numGroups,
1977  subplan);
1978 
1979  /* Copy cost data from Path to Plan */
1980  copy_generic_path_info(&plan->plan, &best_path->path);
1981  }
1982 
1983  return (Plan *) plan;
1984 }
#define NIL
Definition: pg_list.h:69
Query * parse
Definition: relation.h:155
TargetEntry * get_sortgroupclause_tle(SortGroupClause *sgClause, List *targetList)
Definition: tlist.c:370
List * groupClause
Definition: relation.h:1581
static AttrNumber * remap_groupColIdx(PlannerInfo *root, List *groupClause)
Definition: createplan.c:1795
Index tleSortGroupRef
Definition: parsenodes.h:1204
bool is_hashed
Definition: relation.h:1586
List * groupingSets
Definition: parsenodes.h:148
Oid * extract_grouping_ops(List *groupClause)
Definition: tlist.c:466
AttrNumber * grouping_map
Definition: relation.h:287
double numGroups
Definition: relation.h:1584
Agg * make_agg(List *tlist, List *qual, AggStrategy aggstrategy, AggSplit aggsplit, int numGroupCols, AttrNumber *grpColIdx, Oid *grpOperators, List *groupingSets, List *chain, double dNumGroups, Plan *lefttree)
Definition: createplan.c:6049
static Plan * create_plan_recurse(PlannerInfo *root, Path *best_path, int flags)
Definition: createplan.c:359
static void copy_generic_path_info(Plan *dest, Path *src)
Definition: createplan.c:4896
#define linitial(l)
Definition: pg_list.h:111
static List * build_path_tlist(PlannerInfo *root, Path *path)
Definition: createplan.c:736
AttrNumber resno
Definition: primnodes.h:1376
static ListCell * list_head(const List *l)
Definition: pg_list.h:77
static Sort * make_sort_from_groupcols(List *groupcls, AttrNumber *grpColIdx, Plan *lefttree)
Definition: createplan.c:5952
AggStrategy aggstrategy
Definition: relation.h:1597
#define lnext(lc)
Definition: pg_list.h:105
List * lappend(List *list, void *datum)
Definition: list.c:128
Plan plan
Definition: plannodes.h:784
void * palloc0(Size size)
Definition: mcxt.c:864
#define CP_LABEL_TLIST
Definition: createplan.c:68
#define Assert(condition)
Definition: c.h:688
#define lfirst(lc)
Definition: pg_list.h:106
bool hasInheritedTarget
Definition: relation.h:300
static int list_length(const List *l)
Definition: pg_list.h:89
#define for_each_cell(cell, initcell)
Definition: pg_list.h:169
struct Plan * lefttree
Definition: plannodes.h:146
List * targetlist
Definition: plannodes.h:144
AggStrategy
Definition: nodes.h:739
List * groupClause
Definition: parsenodes.h:146
Definition: plannodes.h:782
Definition: pg_list.h:45
int16 AttrNumber
Definition: attnum.h:21
List * gsets
Definition: relation.h:1582

◆ create_hashjoin_plan()

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

Definition at line 4083 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, InvalidAttrNumber, InvalidOid, is_opclause, IS_OUTER_JOIN, IsA, HashJoin::join, JoinPath::joinrestrictinfo, JoinPath::jointype, HashPath::jpath, linitial, list_difference(), list_length(), make_hash(), make_hashjoin(), NIL, HashPath::num_batches, 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().

4085 {
4086  HashJoin *join_plan;
4087  Hash *hash_plan;
4088  Plan *outer_plan;
4089  Plan *inner_plan;
4090  List *tlist = build_path_tlist(root, &best_path->jpath.path);
4091  List *joinclauses;
4092  List *otherclauses;
4093  List *hashclauses;
4094  Oid skewTable = InvalidOid;
4095  AttrNumber skewColumn = InvalidAttrNumber;
4096  bool skewInherit = false;
4097 
4098  /*
4099  * HashJoin can project, so we don't have to demand exact tlists from the
4100  * inputs. However, it's best to request a small tlist from the inner
4101  * side, so that we aren't storing more data than necessary. Likewise, if
4102  * we anticipate batching, request a small tlist from the outer side so
4103  * that we don't put extra data in the outer batch files.
4104  */
4105  outer_plan = create_plan_recurse(root, best_path->jpath.outerjoinpath,
4106  (best_path->num_batches > 1) ? CP_SMALL_TLIST : 0);
4107 
4108  inner_plan = create_plan_recurse(root, best_path->jpath.innerjoinpath,
4109  CP_SMALL_TLIST);
4110 
4111  /* Sort join qual clauses into best execution order */
4112  joinclauses = order_qual_clauses(root, best_path->jpath.joinrestrictinfo);
4113  /* There's no point in sorting the hash clauses ... */
4114 
4115  /* Get the join qual clauses (in plain expression form) */
4116  /* Any pseudoconstant clauses are ignored here */
4117  if (IS_OUTER_JOIN(best_path->jpath.jointype))
4118  {
4119  extract_actual_join_clauses(joinclauses,
4120  &joinclauses, &otherclauses);
4121  }
4122  else
4123  {
4124  /* We can treat all clauses alike for an inner join */
4125  joinclauses = extract_actual_clauses(joinclauses, false);
4126  otherclauses = NIL;
4127  }
4128 
4129  /*
4130  * Remove the hashclauses from the list of join qual clauses, leaving the
4131  * list of quals that must be checked as qpquals.
4132  */
4133  hashclauses = get_actual_clauses(best_path->path_hashclauses);
4134  joinclauses = list_difference(joinclauses, hashclauses);
4135 
4136  /*
4137  * Replace any outer-relation variables with nestloop params. There
4138  * should not be any in the hashclauses.
4139  */
4140  if (best_path->jpath.path.param_info)
4141  {
4142  joinclauses = (List *)
4143  replace_nestloop_params(root, (Node *) joinclauses);
4144  otherclauses = (List *)
4145  replace_nestloop_params(root, (Node *) otherclauses);
4146  }
4147 
4148  /*
4149  * Rearrange hashclauses, if needed, so that the outer variable is always
4150  * on the left.
4151  */
4152  hashclauses = get_switched_clauses(best_path->path_hashclauses,
4153  best_path->jpath.outerjoinpath->parent->relids);
4154 
4155  /*
4156  * If there is a single join clause and we can identify the outer variable
4157  * as a simple column reference, supply its identity for possible use in
4158  * skew optimization. (Note: in principle we could do skew optimization
4159  * with multiple join clauses, but we'd have to be able to determine the
4160  * most common combinations of outer values, which we don't currently have
4161  * enough stats for.)
4162  */
4163  if (list_length(hashclauses) == 1)
4164  {
4165  OpExpr *clause = (OpExpr *) linitial(hashclauses);
4166  Node *node;
4167 
4168  Assert(is_opclause(clause));
4169  node = (Node *) linitial(clause->args);
4170  if (IsA(node, RelabelType))
4171  node = (Node *) ((RelabelType *) node)->arg;
4172  if (IsA(node, Var))
4173  {
4174  Var *var = (Var *) node;
4175  RangeTblEntry *rte;
4176 
4177  rte = root->simple_rte_array[var->varno];
4178  if (rte->rtekind == RTE_RELATION)
4179  {
4180  skewTable = rte->relid;
4181  skewColumn = var->varattno;
4182  skewInherit = rte->inh;
4183  }
4184  }
4185  }
4186 
4187  /*
4188  * Build the hash node and hash join node.
4189  */
4190  hash_plan = make_hash(inner_plan,
4191  skewTable,
4192  skewColumn,
4193  skewInherit);
4194 
4195  /*
4196  * Set Hash node's startup & total costs equal to total cost of input
4197  * plan; this only affects EXPLAIN display not decisions.
4198  */
4199  copy_plan_costsize(&hash_plan->plan, inner_plan);
4200  hash_plan->plan.startup_cost = hash_plan->plan.total_cost;
4201 
4202  /*
4203  * If parallel-aware, the executor will also need an estimate of the total
4204  * number of rows expected from all participants so that it can size the
4205  * shared hash table.
4206  */
4207  if (best_path->jpath.path.parallel_aware)
4208  {
4209  hash_plan->plan.parallel_aware = true;
4210  hash_plan->rows_total = best_path->inner_rows_total;
4211  }
4212 
4213  join_plan = make_hashjoin(tlist,
4214  joinclauses,
4215  otherclauses,
4216  hashclauses,
4217  outer_plan,
4218  (Plan *) hash_plan,
4219  best_path->jpath.jointype,
4220  best_path->jpath.inner_unique);
4221 
4222  copy_generic_path_info(&join_plan->join.plan, &best_path->jpath.path);
4223 
4224  return join_plan;
4225 }
double rows_total
Definition: plannodes.h:890
#define NIL
Definition: pg_list.h:69
#define IsA(nodeptr, _type_)
Definition: nodes.h:564
JoinPath jpath
Definition: relation.h:1468
static Node * replace_nestloop_params(PlannerInfo *root, Node *expr)
Definition: createplan.c:4244
static List * get_switched_clauses(List *clauses, Relids outerrelids)
Definition: createplan.c:4725
int num_batches
Definition: relation.h:1470
static HashJoin * make_hashjoin(List *tlist, List *joinclauses, List *otherclauses, List *hashclauses, Plan *lefttree, Plan *righttree, JoinType jointype, bool inner_unique)
Definition: createplan.c:5442
void extract_actual_join_clauses(List *restrictinfo_list, List **joinquals, List **otherquals)
Definition: restrictinfo.c:383
Path * innerjoinpath
Definition: relation.h:1395
#define IS_OUTER_JOIN(jointype)
Definition: nodes.h:726
ParamPathInfo * param_info
Definition: relation.h:1049
#define CP_SMALL_TLIST
Definition: createplan.c:67
Definition: nodes.h:513
List * get_actual_clauses(List *restrictinfo_list)
Definition: restrictinfo.c:333
AttrNumber varattno
Definition: primnodes.h:168
static List * order_qual_clauses(PlannerInfo *root, List *clauses)
Definition: createplan.c:4802
unsigned int Oid
Definition: postgres_ext.h:31
Definition: primnodes.h:163
double inner_rows_total
Definition: relation.h:1471
Join join
Definition: plannodes.h:727
static Plan * create_plan_recurse(PlannerInfo *root, Path *best_path, int flags)
Definition: createplan.c:359
static void copy_generic_path_info(Plan *dest, Path *src)
Definition: createplan.c:4896
#define linitial(l)
Definition: pg_list.h:111
static List * build_path_tlist(PlannerInfo *root, Path *path)
Definition: createplan.c:736
#define is_opclause(clause)
Definition: clauses.h:20
List * joinrestrictinfo
Definition: relation.h:1397
RelOptInfo * parent
Definition: relation.h:1046
Cost startup_cost
Definition: plannodes.h:125
static void copy_plan_costsize(Plan *dest, Plan *src)
Definition: createplan.c:4911
bool parallel_aware
Definition: plannodes.h:137
Relids relids
Definition: relation.h:585
RangeTblEntry ** simple_rte_array
Definition: relation.h:188
Index varno
Definition: primnodes.h:166
Path * outerjoinpath
Definition: relation.h:1394
#define InvalidOid
Definition: postgres_ext.h:36
Path path
Definition: relation.h:1387
#define Assert(condition)
Definition: c.h:688
static int list_length(const List *l)
Definition: pg_list.h:89
List * extract_actual_clauses(List *restrictinfo_list, bool pseudoconstant)
Definition: restrictinfo.c:356
bool inner_unique
Definition: relation.h:1391
List * list_difference(const List *list1, const List *list2)
Definition: list.c:858
#define InvalidAttrNumber
Definition: attnum.h:23
RTEKind rtekind
Definition: parsenodes.h:959
Plan plan
Definition: plannodes.h:885
JoinType jointype
Definition: relation.h:1389
static Hash * make_hash(Plan *lefttree, Oid skewTable, AttrNumber skewColumn, bool skewInherit)
Definition: createplan.c:5467
Cost total_cost
Definition: plannodes.h:126
bool parallel_aware
Definition: relation.h:1051
List * path_hashclauses
Definition: relation.h:1469
List * args
Definition: primnodes.h:502
Definition: pg_list.h:45
int16 AttrNumber
Definition: attnum.h:21
Plan plan
Definition: plannodes.h:668

◆ create_indexscan_plan()

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

Definition at line 2528 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_actual_clauses(), get_opfamily_member(), IndexPath::indexinfo, IndexOptInfo::indexoid, IndexPath::indexorderbys, IndexPath::indexquals, IndexPath::indexscandir, IndexOptInfo::indextlist, is_redundant_derived_clause(), lappend(), lappend_oid(), lfirst, lfirst_node, list_length(), list_make1, list_member_ptr(), 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().

2533 {
2534  Scan *scan_plan;
2535  List *indexquals = best_path->indexquals;
2536  List *indexorderbys = best_path->indexorderbys;
2537  Index baserelid = best_path->path.parent->relid;
2538  Oid indexoid = best_path->indexinfo->indexoid;
2539  List *qpqual;
2540  List *stripped_indexquals;
2541  List *fixed_indexquals;
2542  List *fixed_indexorderbys;
2543  List *indexorderbyops = NIL;
2544  ListCell *l;
2545 
2546  /* it should be a base rel... */
2547  Assert(baserelid > 0);
2548  Assert(best_path->path.parent->rtekind == RTE_RELATION);
2549 
2550  /*
2551  * Build "stripped" indexquals structure (no RestrictInfos) to pass to
2552  * executor as indexqualorig
2553  */
2554  stripped_indexquals = get_actual_clauses(indexquals);
2555 
2556  /*
2557  * The executor needs a copy with the indexkey on the left of each clause
2558  * and with index Vars substituted for table ones.
2559  */
2560  fixed_indexquals = fix_indexqual_references(root, best_path);
2561 
2562  /*
2563  * Likewise fix up index attr references in the ORDER BY expressions.
2564  */
2565  fixed_indexorderbys = fix_indexorderby_references(root, best_path);
2566 
2567  /*
2568  * The qpqual list must contain all restrictions not automatically handled
2569  * by the index, other than pseudoconstant clauses which will be handled
2570  * by a separate gating plan node. All the predicates in the indexquals
2571  * will be checked (either by the index itself, or by nodeIndexscan.c),
2572  * but if there are any "special" operators involved then they must be
2573  * included in qpqual. The upshot is that qpqual must contain
2574  * scan_clauses minus whatever appears in indexquals.
2575  *
2576  * In normal cases simple pointer equality checks will be enough to spot
2577  * duplicate RestrictInfos, so we try that first.
2578  *
2579  * Another common case is that a scan_clauses entry is generated from the
2580  * same EquivalenceClass as some indexqual, and is therefore redundant
2581  * with it, though not equal. (This happens when indxpath.c prefers a
2582  * different derived equality than what generate_join_implied_equalities
2583  * picked for a parameterized scan's ppi_clauses.)
2584  *
2585  * In some situations (particularly with OR'd index conditions) we may
2586  * have scan_clauses that are not equal to, but are logically implied by,
2587  * the index quals; so we also try a predicate_implied_by() check to see
2588  * if we can discard quals that way. (predicate_implied_by assumes its
2589  * first input contains only immutable functions, so we have to check
2590  * that.)
2591  *
2592  * Note: if you change this bit of code you should also look at
2593  * extract_nonindex_conditions() in costsize.c.
2594  */
2595  qpqual = NIL;
2596  foreach(l, scan_clauses)
2597  {
2598  RestrictInfo *rinfo = lfirst_node(RestrictInfo, l);
2599 
2600  if (rinfo->pseudoconstant)
2601  continue; /* we may drop pseudoconstants here */
2602  if (list_member_ptr(indexquals, rinfo))
2603  continue; /* simple duplicate */
2604  if (is_redundant_derived_clause(rinfo, indexquals))
2605  continue; /* derived from same EquivalenceClass */
2606  if (!contain_mutable_functions((Node *) rinfo->clause) &&
2607  predicate_implied_by(list_make1(rinfo->clause), indexquals, false))
2608  continue; /* provably implied by indexquals */
2609  qpqual = lappend(qpqual, rinfo);
2610  }
2611 
2612  /* Sort clauses into best execution order */
2613  qpqual = order_qual_clauses(root, qpqual);
2614 
2615  /* Reduce RestrictInfo list to bare expressions; ignore pseudoconstants */
2616  qpqual = extract_actual_clauses(qpqual, false);
2617 
2618  /*
2619  * We have to replace any outer-relation variables with nestloop params in
2620  * the indexqualorig, qpqual, and indexorderbyorig expressions. A bit
2621  * annoying to have to do this separately from the processing in
2622  * fix_indexqual_references --- rethink this when generalizing the inner
2623  * indexscan support. But note we can't really do this earlier because
2624  * it'd break the comparisons to predicates above ... (or would it? Those
2625  * wouldn't have outer refs)
2626  */
2627  if (best_path->path.param_info)
2628  {
2629  stripped_indexquals = (List *)
2630  replace_nestloop_params(root, (Node *) stripped_indexquals);
2631  qpqual = (List *)
2632  replace_nestloop_params(root, (Node *) qpqual);
2633  indexorderbys = (List *)
2634  replace_nestloop_params(root, (Node *) indexorderbys);
2635  }
2636 
2637  /*
2638  * If there are ORDER BY expressions, look up the sort operators for their
2639  * result datatypes.
2640  */
2641  if (indexorderbys)
2642  {
2643  ListCell *pathkeyCell,
2644  *exprCell;
2645 
2646  /*
2647  * PathKey contains OID of the btree opfamily we're sorting by, but
2648  * that's not quite enough because we need the expression's datatype
2649  * to look up the sort operator in the operator family.
2650  */
2651  Assert(list_length(best_path->path.pathkeys) == list_length(indexorderbys));
2652  forboth(pathkeyCell, best_path->path.pathkeys, exprCell, indexorderbys)
2653  {
2654  PathKey *pathkey = (PathKey *) lfirst(pathkeyCell);
2655  Node *expr = (Node *) lfirst(exprCell);
2656  Oid exprtype = exprType(expr);
2657  Oid sortop;
2658 
2659  /* Get sort operator from opfamily */
2660  sortop = get_opfamily_member(pathkey->pk_opfamily,
2661  exprtype,
2662  exprtype,
2663  pathkey->pk_strategy);
2664  if (!OidIsValid(sortop))
2665  elog(ERROR, "missing operator %d(%u,%u) in opfamily %u",
2666  pathkey->pk_strategy, exprtype, exprtype, pathkey->pk_opfamily);
2667  indexorderbyops = lappend_oid(indexorderbyops, sortop);
2668  }
2669  }
2670 
2671  /* Finally ready to build the plan node */
2672  if (indexonly)
2673  scan_plan = (Scan *) make_indexonlyscan(tlist,
2674  qpqual,
2675  baserelid,
2676  indexoid,
2677  fixed_indexquals,
2678  fixed_indexorderbys,
2679  best_path->indexinfo->indextlist,
2680  best_path->indexscandir);
2681  else
2682  scan_plan = (Scan *) make_indexscan(tlist,
2683  qpqual,
2684  baserelid,
2685  indexoid,
2686  fixed_indexquals,
2687  stripped_indexquals,
2688  fixed_indexorderbys,
2689  indexorderbys,
2690  indexorderbyops,
2691  best_path->indexscandir);
2692 
2693  copy_generic_path_info(&scan_plan->plan, &best_path->path);
2694 
2695  return scan_plan;
2696 }
#define NIL
Definition: pg_list.h:69
bool predicate_implied_by(List *predicate_list, List *clause_list, bool clause_is_check)
Definition: predtest.c:135
Plan plan
Definition: plannodes.h:330
static Node * replace_nestloop_params(PlannerInfo *root, Node *expr)
Definition: createplan.c:4244
#define forboth(cell1, list1, cell2, list2)
Definition: pg_list.h:180
Path path
Definition: relation.h:1122
bool is_redundant_derived_clause(RestrictInfo *rinfo, List *clauselist)
Definition: equivclass.c:2494
IndexOptInfo * indexinfo
Definition: relation.h:1123
List * indextlist
Definition: relation.h:748
bool pseudoconstant
Definition: relation.h:1855
ParamPathInfo * param_info
Definition: relation.h:1049
Definition: nodes.h:513
List * get_actual_clauses(List *restrictinfo_list)
Definition: restrictinfo.c:333
static List * order_qual_clauses(PlannerInfo *root, List *clauses)
Definition: createplan.c:4802
unsigned int Oid
Definition: postgres_ext.h:31
List * lappend_oid(List *list, Oid datum)
Definition: list.c:164
#define OidIsValid(objectId)
Definition: c.h:594
int pk_strategy
Definition: relation.h:945
#define list_make1(x1)
Definition: pg_list.h:139
List * indexquals
Definition: relation.h:1125
static void copy_generic_path_info(Plan *dest, Path *src)
Definition: createplan.c:4896
#define ERROR
Definition: elog.h:43
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:5027
RelOptInfo * parent
Definition: relation.h:1046
#define lfirst_node(type, lc)
Definition: pg_list.h:109
Oid get_opfamily_member(Oid opfamily, Oid lefttype, Oid righttype, int16 strategy)
Definition: lsyscache.c:163
static List * fix_indexorderby_references(PlannerInfo *root, IndexPath *index_path)
Definition: createplan.c:4593
static List * fix_indexqual_references(PlannerInfo *root, IndexPath *index_path)
Definition: createplan.c:4462
Index relid
Definition: relation.h:613
List * lappend(List *list, void *datum)
Definition: list.c:128
Expr * clause
Definition: relation.h:1847
List * indexorderbys
Definition: relation.h:1127
unsigned int Index
Definition: c.h:431
RTEKind rtekind
Definition: relation.h:615
bool list_member_ptr(const List *list, const void *datum)
Definition: list.c:465
List * pathkeys
Definition: relation.h:1060
static IndexOnlyScan * make_indexonlyscan(List *qptlist, List *qpqual, Index scanrelid, Oid indexid, List *indexqual, List *indexorderby, List *indextlist, ScanDirection indexscandir)
Definition: createplan.c:5058
#define Assert(condition)
Definition: c.h:688
#define lfirst(lc)
Definition: pg_list.h:106
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:42
static int list_length(const List *l)
Definition: pg_list.h:89
List * extract_actual_clauses(List *restrictinfo_list, bool pseudoconstant)
Definition: restrictinfo.c:356
Oid pk_opfamily
Definition: relation.h:944
ScanDirection indexscandir
Definition: relation.h:1129
bool contain_mutable_functions(Node *clause)
Definition: clauses.c:881
#define elog
Definition: elog.h:219
Oid indexoid
Definition: relation.h:723
Definition: pg_list.h:45

◆ create_join_plan()

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

Definition at line 959 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().

960 {
961  Plan *plan;
962  List *gating_clauses;
963 
964  switch (best_path->path.pathtype)
965  {
966  case T_MergeJoin:
967  plan = (Plan *) create_mergejoin_plan(root,
968  (MergePath *) best_path);
969  break;
970  case T_HashJoin:
971  plan = (Plan *) create_hashjoin_plan(root,
972  (HashPath *) best_path);
973  break;
974  case T_NestLoop:
975  plan = (Plan *) create_nestloop_plan(root,
976  (NestPath *) best_path);
977  break;
978  default:
979  elog(ERROR, "unrecognized node type: %d",
980  (int) best_path->path.pathtype);
981  plan = NULL; /* keep compiler quiet */
982  break;
983  }
984 
985  /*
986  * If there are any pseudoconstant clauses attached to this node, insert a
987  * gating Result node that evaluates the pseudoconstants as one-time
988  * quals.
989  */
990  gating_clauses = get_gating_quals(root, best_path->joinrestrictinfo);
991  if (gating_clauses)
992  plan = create_gating_plan(root, (Path *) best_path, plan,
993  gating_clauses);
994 
995 #ifdef NOT_USED
996 
997  /*
998  * * Expensive function pullups may have pulled local predicates * into
999  * this path node. Put them in the qpqual of the plan node. * JMH,
1000  * 6/15/92
1001  */
1002  if (get_loc_restrictinfo(best_path) != NIL)
1003  set_qpqual((Plan) plan,
1004  list_concat(get_qpqual((Plan) plan),
1005  get_actual_clauses(get_loc_restrictinfo(best_path))));
1006 #endif
1007 
1008  return plan;
1009 }
#define NIL
Definition: pg_list.h:69
List * get_actual_clauses(List *restrictinfo_list)
Definition: restrictinfo.c:333
List * list_concat(List *list1, List *list2)
Definition: list.c:321
static NestLoop * create_nestloop_plan(PlannerInfo *root, NestPath *best_path)
Definition: createplan.c:3671
NodeTag pathtype
Definition: relation.h:1044
#define ERROR
Definition: elog.h:43
List * joinrestrictinfo
Definition: relation.h:1397
Path path
Definition: relation.h:1387
static HashJoin * create_hashjoin_plan(PlannerInfo *root, HashPath *best_path)
Definition: createplan.c:4083
static Plan * create_gating_plan(PlannerInfo *root, Path *path, Plan *plan, List *gating_quals)
Definition: createplan.c:917
#define elog
Definition: elog.h:219
static MergeJoin * create_mergejoin_plan(PlannerInfo *root, MergePath *best_path)
Definition: createplan.c:3777
Definition: pg_list.h:45
static List * get_gating_quals(PlannerInfo *root, List *quals)
Definition: createplan.c:897

◆ create_limit_plan()

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

Definition at line 2408 of file createplan.c.

References copy_generic_path_info(), create_plan_recurse(), LimitPath::limitCount, LimitPath::limitOffset, make_limit(), Limit::plan, and LimitPath::subpath.

Referenced by create_plan_recurse().

2409 {
2410  Limit *plan;
2411  Plan *subplan;
2412 
2413  /* Limit doesn't project, so tlist requirements pass through */
2414  subplan = create_plan_recurse(root, best_path->subpath, flags);
2415 
2416  plan = make_limit(subplan,
2417  best_path->limitOffset,
2418  best_path->limitCount);
2419 
2420  copy_generic_path_info(&plan->plan, (Path *) best_path);
2421 
2422  return plan;
2423 }
Plan plan
Definition: plannodes.h:936
Node * limitOffset
Definition: relation.h:1699
static Plan * create_plan_recurse(PlannerInfo *root, Path *best_path, int flags)
Definition: createplan.c:359
static void copy_generic_path_info(Plan *dest, Path *src)
Definition: createplan.c:4896
Path * subpath
Definition: relation.h:1698
Limit * make_limit(Plan *lefttree, Node *limitOffset, Node *limitCount)
Definition: createplan.c:6395
Node * limitCount
Definition: relation.h:1700

◆ create_lockrows_plan()

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

Definition at line 2325 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().

2327 {
2328  LockRows *plan;
2329  Plan *subplan;
2330 
2331  /* LockRows doesn't project, so tlist requirements pass through */
2332  subplan = create_plan_recurse(root, best_path->subpath, flags);
2333 
2334  plan = make_lockrows(subplan, best_path->rowMarks, best_path->epqParam);
2335 
2336  copy_generic_path_info(&plan->plan, (Path *) best_path);
2337 
2338  return plan;
2339 }
Plan plan
Definition: plannodes.h:922
List * rowMarks
Definition: relation.h:1662
static Plan * create_plan_recurse(PlannerInfo *root, Path *best_path, int flags)
Definition: createplan.c:359
static void copy_generic_path_info(Plan *dest, Path *src)
Definition: createplan.c:4896
Path * subpath
Definition: relation.h:1661
static LockRows * make_lockrows(Plan *lefttree, List *rowMarks, int epqParam)
Definition: createplan.c:6374

◆ create_material_plan()

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

Definition at line 1244 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().

1245 {
1246  Material *plan;
1247  Plan *subplan;
1248 
1249  /*
1250  * We don't want any excess columns in the materialized tuples, so request
1251  * a smaller tlist. Otherwise, since Material doesn't project, tlist
1252  * requirements pass through.
1253  */
1254  subplan = create_plan_recurse(root, best_path->subpath,
1255  flags | CP_SMALL_TLIST);
1256 
1257  plan = make_material(subplan);
1258 
1259  copy_generic_path_info(&plan->plan, (Path *) best_path);
1260 
1261  return plan;
1262 }
#define CP_SMALL_TLIST
Definition: createplan.c:67
Path * subpath
Definition: relation.h:1324
static Plan * create_plan_recurse(PlannerInfo *root, Path *best_path, int flags)
Definition: createplan.c:359
static Material * make_material(Plan *lefttree)
Definition: createplan.c:5993
static void copy_generic_path_info(Plan *dest, Path *src)
Definition: createplan.c:4896
Plan plan
Definition: plannodes.h:737

◆ create_merge_append_plan()

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

Definition at line 1085 of file createplan.c.

References Assert, build_path_tlist(), MergeAppend::collations, copy_generic_path_info(), CP_EXACT_TLIST, create_plan_recurse(), elog, ERROR, label_sort_with_costsize(), lappend(), Plan::lefttree, lfirst, make_sort(), makeNode, MergeAppend::mergeplans, NIL, MergeAppend::nullsFirst, MergeAppend::numCols, Path::parent, MergeAppend::partitioned_rels, MergeAppendPath::path, Path::pathkeys, pathkeys_contained_in(), MergeAppend::plan, prepare_sort_from_pathkeys(), Plan::qual, RelOptInfo::relids, Plan::righttree, sort(), MergeAppend::sortColIdx, MergeAppend::sortOperators, subpath(), and Plan::targetlist.

Referenced by create_plan_recurse().

1086 {
1087  MergeAppend *node = makeNode(MergeAppend);
1088  Plan *plan = &node->plan;
1089  List *tlist = build_path_tlist(root, &best_path->path);
1090  List *pathkeys = best_path->path.pathkeys;
1091  List *subplans = NIL;
1092  ListCell *subpaths;
1093 
1094  /*
1095  * We don't have the actual creation of the MergeAppend node split out
1096  * into a separate make_xxx function. This is because we want to run
1097  * prepare_sort_from_pathkeys on it before we do so on the individual
1098  * child plans, to make cross-checking the sort info easier.
1099  */
1100  copy_generic_path_info(plan, (Path *) best_path);
1101  plan->targetlist = tlist;
1102  plan->qual = NIL;
1103  plan->lefttree = NULL;
1104  plan->righttree = NULL;
1105 
1106  /* Compute sort column info, and adjust MergeAppend's tlist as needed */
1107  (void) prepare_sort_from_pathkeys(plan, pathkeys,
1108  best_path->path.parent->relids,
1109  NULL,
1110  true,
1111  &node->numCols,
1112  &node->sortColIdx,
1113  &node->sortOperators,
1114  &node->collations,
1115  &node->nullsFirst);
1116 
1117  /*
1118  * Now prepare the child plans. We must apply prepare_sort_from_pathkeys
1119  * even to subplans that don't need an explicit sort, to make sure they
1120  * are returning the same sort key columns the MergeAppend expects.
1121  */
1122  foreach(subpaths, best_path->subpaths)
1123  {
1124  Path *subpath = (Path *) lfirst(subpaths);
1125  Plan *subplan;
1126  int numsortkeys;
1127  AttrNumber *sortColIdx;
1128  Oid *sortOperators;
1129  Oid *collations;
1130  bool *nullsFirst;
1131 
1132  /* Build the child plan */
1133  /* Must insist that all children return the same tlist */
1134  subplan = create_plan_recurse(root, subpath, CP_EXACT_TLIST);
1135 
1136  /* Compute sort column info, and adjust subplan's tlist as needed */
1137  subplan = prepare_sort_from_pathkeys(subplan, pathkeys,
1138  subpath->parent->relids,
1139  node->sortColIdx,
1140  false,
1141  &numsortkeys,
1142  &sortColIdx,
1143  &sortOperators,
1144  &collations,
1145  &nullsFirst);
1146 
1147  /*
1148  * Check that we got the same sort key information. We just Assert
1149  * that the sortops match, since those depend only on the pathkeys;
1150  * but it seems like a good idea to check the sort column numbers
1151  * explicitly, to ensure the tlists really do match up.
1152  */
1153  Assert(numsortkeys == node->numCols);
1154  if (memcmp(sortColIdx, node->sortColIdx,
1155  numsortkeys * sizeof(AttrNumber)) != 0)
1156  elog(ERROR, "MergeAppend child's targetlist doesn't match MergeAppend");
1157  Assert(memcmp(sortOperators, node->sortOperators,
1158  numsortkeys * sizeof(Oid)) == 0);
1159  Assert(memcmp(collations, node->collations,
1160  numsortkeys * sizeof(Oid)) == 0);
1161  Assert(memcmp(nullsFirst, node->nullsFirst,
1162  numsortkeys * sizeof(bool)) == 0);
1163 
1164  /* Now, insert a Sort node if subplan isn't sufficiently ordered */
1165  if (!pathkeys_contained_in(pathkeys, subpath->pathkeys))
1166  {
1167  Sort *sort = make_sort(subplan, numsortkeys,
1168  sortColIdx, sortOperators,
1169  collations, nullsFirst);
1170 
1171  label_sort_with_costsize(root, sort, best_path->limit_tuples);
1172  subplan = (Plan *) sort;
1173  }
1174 
1175  subplans = lappend(subplans, subplan);
1176  }
1177 
1178  node->partitioned_rels = best_path->partitioned_rels;
1179  node->mergeplans = subplans;
1180 
1181  return (Plan *) node;
1182 }
#define NIL
Definition: pg_list.h:69
List * qual
Definition: plannodes.h:145
Oid * collations
Definition: plannodes.h:270
List * partitioned_rels
Definition: relation.h:1297
unsigned int Oid
Definition: postgres_ext.h:31
static Plan * create_plan_recurse(PlannerInfo *root, Path *best_path, int flags)
Definition: createplan.c:359
struct Plan * righttree
Definition: plannodes.h:147
static void copy_generic_path_info(Plan *dest, Path *src)
Definition: createplan.c:4896
#define ERROR
Definition: elog.h:43
static List * build_path_tlist(PlannerInfo *root, Path *path)
Definition: createplan.c:736
RelOptInfo * parent
Definition: relation.h:1046
List * partitioned_rels
Definition: plannodes.h:264
Datum sort(PG_FUNCTION_ARGS)
Definition: _int_op.c:200
Relids relids
Definition: relation.h:585
List * lappend(List *list, void *datum)
Definition: list.c:128
bool pathkeys_contained_in(List *keys1, List *keys2)
Definition: pathkeys.c:317
List * pathkeys
Definition: relation.h:1060
static Sort * make_sort(Plan *lefttree, int numCols, AttrNumber *sortColIdx, Oid *sortOperators, Oid *collations, bool *nullsFirst)
Definition: createplan.c:5529
#define makeNode(_type_)
Definition: nodes.h:561
#define Assert(condition)
Definition: c.h:688
#define lfirst(lc)
Definition: pg_list.h:106
AttrNumber * sortColIdx
Definition: plannodes.h:268
struct Plan * lefttree
Definition: plannodes.h:146
List * targetlist
Definition: plannodes.h:144
bool * nullsFirst
Definition: plannodes.h:271
List * mergeplans
Definition: plannodes.h:265
Oid * sortOperators
Definition: plannodes.h:269
List * subpaths
Definition: relation.h:1298
#define elog
Definition: elog.h:219
#define CP_EXACT_TLIST
Definition: createplan.c:66
Definition: pg_list.h:45
int16 AttrNumber
Definition: attnum.h:21
static void label_sort_with_costsize(PlannerInfo *root, Sort *plan, double limit_tuples)
Definition: createplan.c:4933
double limit_tuples
Definition: relation.h:1299
Datum subpath(PG_FUNCTION_ARGS)
Definition: ltree_op.c:234
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:5591

◆ create_mergejoin_plan()

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

Definition at line 3777 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().

3779 {
3780  MergeJoin *join_plan;
3781  Plan *outer_plan;
3782  Plan *inner_plan;
3783  List *tlist = build_path_tlist(root, &best_path->jpath.path);
3784  List *joinclauses;
3785  List *otherclauses;
3786  List *mergeclauses;
3787  List *outerpathkeys;
3788  List *innerpathkeys;
3789  int nClauses;
3790  Oid *mergefamilies;
3791  Oid *mergecollations;
3792  int *mergestrategies;
3793  bool *mergenullsfirst;
3794  PathKey *opathkey;
3795  EquivalenceClass *opeclass;
3796  int i;
3797  ListCell *lc;
3798  ListCell *lop;
3799  ListCell *lip;
3800  Path *outer_path = best_path->jpath.outerjoinpath;
3801  Path *inner_path = best_path->jpath.innerjoinpath;
3802 
3803  /*
3804  * MergeJoin can project, so we don't have to demand exact tlists from the
3805  * inputs. However, if we're intending to sort an input's result, it's
3806  * best to request a small tlist so we aren't sorting more data than
3807  * necessary.
3808  */
3809  outer_plan = create_plan_recurse(root, best_path->jpath.outerjoinpath,
3810  (best_path->outersortkeys != NIL) ? CP_SMALL_TLIST : 0);
3811 
3812  inner_plan = create_plan_recurse(root, best_path->jpath.innerjoinpath,
3813  (best_path->innersortkeys != NIL) ? CP_SMALL_TLIST : 0);
3814 
3815  /* Sort join qual clauses into best execution order */
3816  /* NB: do NOT reorder the mergeclauses */
3817  joinclauses = order_qual_clauses(root, best_path->jpath.joinrestrictinfo);
3818 
3819  /* Get the join qual clauses (in plain expression form) */
3820  /* Any pseudoconstant clauses are ignored here */
3821  if (IS_OUTER_JOIN(best_path->jpath.jointype))
3822  {
3823  extract_actual_join_clauses(joinclauses,
3824  &joinclauses, &otherclauses);
3825  }
3826  else
3827  {
3828  /* We can treat all clauses alike for an inner join */
3829  joinclauses = extract_actual_clauses(joinclauses, false);
3830  otherclauses = NIL;
3831  }
3832 
3833  /*
3834  * Remove the mergeclauses from the list of join qual clauses, leaving the
3835  * list of quals that must be checked as qpquals.
3836  */
3837  mergeclauses = get_actual_clauses(best_path->path_mergeclauses);
3838  joinclauses = list_difference(joinclauses, mergeclauses);
3839 
3840  /*
3841  * Replace any outer-relation variables with nestloop params. There
3842  * should not be any in the mergeclauses.
3843  */
3844  if (best_path->jpath.path.param_info)
3845  {
3846  joinclauses = (List *)
3847  replace_nestloop_params(root, (Node *) joinclauses);
3848  otherclauses = (List *)
3849  replace_nestloop_params(root, (Node *) otherclauses);
3850  }
3851 
3852  /*
3853  * Rearrange mergeclauses, if needed, so that the outer variable is always
3854  * on the left; mark the mergeclause restrictinfos with correct
3855  * outer_is_left status.
3856  */
3857  mergeclauses = get_switched_clauses(best_path->path_mergeclauses,
3858  best_path->jpath.outerjoinpath->parent->relids);
3859 
3860  /*
3861  * Create explicit sort nodes for the outer and inner paths if necessary.
3862  */
3863  if (best_path->outersortkeys)
3864  {
3865  Relids outer_relids = outer_path->parent->relids;
3866  Sort *sort = make_sort_from_pathkeys(outer_plan,
3867  best_path->outersortkeys,
3868  outer_relids);
3869 
3870  label_sort_with_costsize(root, sort, -1.0);
3871  outer_plan = (Plan *) sort;
3872  outerpathkeys = best_path->outersortkeys;
3873  }
3874  else
3875  outerpathkeys = best_path->jpath.outerjoinpath->pathkeys;
3876 
3877  if (best_path->innersortkeys)
3878  {
3879  Relids inner_relids = inner_path->parent->relids;
3880  Sort *sort = make_sort_from_pathkeys(inner_plan,
3881  best_path->innersortkeys,
3882  inner_relids);
3883 
3884  label_sort_with_costsize(root, sort, -1.0);
3885  inner_plan = (Plan *) sort;
3886  innerpathkeys = best_path->innersortkeys;
3887  }
3888  else
3889  innerpathkeys = best_path->jpath.innerjoinpath->pathkeys;
3890 
3891  /*
3892  * If specified, add a materialize node to shield the inner plan from the
3893  * need to handle mark/restore.
3894  */
3895  if (best_path->materialize_inner)
3896  {
3897  Plan *matplan = (Plan *) make_material(inner_plan);
3898 
3899  /*
3900  * We assume the materialize will not spill to disk, and therefore
3901  * charge just cpu_operator_cost per tuple. (Keep this estimate in
3902  * sync with final_cost_mergejoin.)
3903  */
3904  copy_plan_costsize(matplan, inner_plan);
3905  matplan->total_cost += cpu_operator_cost * matplan->plan_rows;
3906 
3907  inner_plan = matplan;
3908  }
3909 
3910  /*
3911  * Compute the opfamily/collation/strategy/nullsfirst arrays needed by the
3912  * executor. The information is in the pathkeys for the two inputs, but
3913  * we need to be careful about the possibility of mergeclauses sharing a
3914  * pathkey, as well as the possibility that the inner pathkeys are not in
3915  * an order matching the mergeclauses.
3916  */
3917  nClauses = list_length(mergeclauses);
3918  Assert(nClauses == list_length(best_path->path_mergeclauses));
3919  mergefamilies = (Oid *) palloc(nClauses * sizeof(Oid));
3920  mergecollations = (Oid *) palloc(nClauses * sizeof(Oid));
3921  mergestrategies = (int *) palloc(nClauses * sizeof(int));
3922  mergenullsfirst = (bool *) palloc(nClauses * sizeof(bool));
3923 
3924  opathkey = NULL;
3925  opeclass = NULL;
3926  lop = list_head(outerpathkeys);
3927  lip = list_head(innerpathkeys);
3928  i = 0;
3929  foreach(lc, best_path->path_mergeclauses)
3930  {
3931  RestrictInfo *rinfo = lfirst_node(RestrictInfo, lc);
3932  EquivalenceClass *oeclass;
3933  EquivalenceClass *ieclass;
3934  PathKey *ipathkey = NULL;
3935  EquivalenceClass *ipeclass = NULL;
3936  bool first_inner_match = false;
3937 
3938  /* fetch outer/inner eclass from mergeclause */
3939  if (rinfo->outer_is_left)
3940  {
3941  oeclass = rinfo->left_ec;
3942  ieclass = rinfo->right_ec;
3943  }
3944  else
3945  {
3946  oeclass = rinfo->right_ec;
3947  ieclass = rinfo->left_ec;
3948  }
3949  Assert(oeclass != NULL);
3950  Assert(ieclass != NULL);
3951 
3952  /*
3953  * We must identify the pathkey elements associated with this clause
3954  * by matching the eclasses (which should give a unique match, since
3955  * the pathkey lists should be canonical). In typical cases the merge
3956  * clauses are one-to-one with the pathkeys, but when dealing with
3957  * partially redundant query conditions, things are more complicated.
3958  *
3959  * lop and lip reference the first as-yet-unmatched pathkey elements.
3960  * If they're NULL then all pathkey elements have been matched.
3961  *
3962  * The ordering of the outer pathkeys should match the mergeclauses,
3963  * by construction (see find_mergeclauses_for_outer_pathkeys()). There
3964  * could be more than one mergeclause for the same outer pathkey, but
3965  * no pathkey may be entirely skipped over.
3966  */
3967  if (oeclass != opeclass) /* multiple matches are not interesting */
3968  {
3969  /* doesn't match the current opathkey, so must match the next */
3970  if (lop == NULL)
3971  elog(ERROR, "outer pathkeys do not match mergeclauses");
3972  opathkey = (PathKey *) lfirst(lop);
3973  opeclass = opathkey->pk_eclass;
3974  lop = lnext(lop);
3975  if (oeclass != opeclass)
3976  elog(ERROR, "outer pathkeys do not match mergeclauses");
3977  }
3978 
3979  /*
3980  * The inner pathkeys likewise should not have skipped-over keys, but
3981  * it's possible for a mergeclause to reference some earlier inner
3982  * pathkey if we had redundant pathkeys. For example we might have
3983  * mergeclauses like "o.a = i.x AND o.b = i.y AND o.c = i.x". The
3984  * implied inner ordering is then "ORDER BY x, y, x", but the pathkey
3985  * mechanism drops the second sort by x as redundant, and this code
3986  * must cope.
3987  *
3988  * It's also possible for the implied inner-rel ordering to be like
3989  * "ORDER BY x, y, x DESC". We still drop the second instance of x as
3990  * redundant; but this means that the sort ordering of a redundant
3991  * inner pathkey should not be considered significant. So we must
3992  * detect whether this is the first clause matching an inner pathkey.
3993  */
3994  if (lip)
3995  {
3996  ipathkey = (PathKey *) lfirst(lip);
3997  ipeclass = ipathkey->pk_eclass;
3998  if (ieclass == ipeclass)
3999  {
4000  /* successful first match to this inner pathkey */
4001  lip = lnext(lip);
4002  first_inner_match = true;
4003  }
4004  }
4005  if (!first_inner_match)
4006  {
4007  /* redundant clause ... must match something before lip */
4008  ListCell *l2;
4009 
4010  foreach(l2, innerpathkeys)
4011  {
4012  if (l2 == lip)
4013  break;
4014  ipathkey = (PathKey *) lfirst(l2);
4015  ipeclass = ipathkey->pk_eclass;
4016  if (ieclass == ipeclass)
4017  break;
4018  }
4019  if (ieclass != ipeclass)
4020  elog(ERROR, "inner pathkeys do not match mergeclauses");
4021  }
4022 
4023  /*
4024  * The pathkeys should always match each other as to opfamily and
4025  * collation (which affect equality), but if we're considering a
4026  * redundant inner pathkey, its sort ordering might not match. In
4027  * such cases we may ignore the inner pathkey's sort ordering and use
4028  * the outer's. (In effect, we're lying to the executor about the
4029  * sort direction of this inner column, but it does not matter since
4030  * the run-time row comparisons would only reach this column when
4031  * there's equality for the earlier column containing the same eclass.
4032  * There could be only one value in this column for the range of inner
4033  * rows having a given value in the earlier column, so it does not
4034  * matter which way we imagine this column to be ordered.) But a
4035  * non-redundant inner pathkey had better match outer's ordering too.
4036  */
4037  if (opathkey->pk_opfamily != ipathkey->pk_opfamily ||
4038  opathkey->pk_eclass->ec_collation != ipathkey->pk_eclass->ec_collation)
4039  elog(ERROR, "left and right pathkeys do not match in mergejoin");
4040  if (first_inner_match &&
4041  (opathkey->pk_strategy != ipathkey->pk_strategy ||
4042  opathkey->pk_nulls_first != ipathkey->pk_nulls_first))
4043  elog(ERROR, "left and right pathkeys do not match in mergejoin");
4044 
4045  /* OK, save info for executor */
4046  mergefamilies[i] = opathkey->pk_opfamily;
4047  mergecollations[i] = opathkey->pk_eclass->ec_collation;
4048  mergestrategies[i] = opathkey->pk_strategy;
4049  mergenullsfirst[i] = opathkey->pk_nulls_first;
4050  i++;
4051  }
4052 
4053  /*
4054  * Note: it is not an error if we have additional pathkey elements (i.e.,
4055  * lop or lip isn't NULL here). The input paths might be better-sorted
4056  * than we need for the current mergejoin.
4057  */
4058 
4059  /*
4060  * Now we can build the mergejoin node.
4061  */
4062  join_plan = make_mergejoin(tlist,
4063  joinclauses,
4064  otherclauses,
4065  mergeclauses,
4066  mergefamilies,
4067  mergecollations,
4068  mergestrategies,
4069  mergenullsfirst,
4070  outer_plan,
4071  inner_plan,
4072  best_path->jpath.jointype,
4073  best_path->jpath.inner_unique,
4074  best_path->skip_mark_restore);
4075 
4076  /* Costs of sort and material steps are included in path cost already */
4077  copy_generic_path_info(&join_plan->join.plan, &best_path->jpath.path);
4078 
4079  return join_plan;
4080 }
#define NIL
Definition: pg_list.h:69
List * path_mergeclauses
Definition: relation.h:1450
List * outersortkeys
Definition: relation.h:1451
double plan_rows
Definition: plannodes.h:131
static Sort * make_sort_from_pathkeys(Plan *lefttree, List *pathkeys, Relids relids)
Definition: createplan.c:5870
static Node * replace_nestloop_params(PlannerInfo *root, Node *expr)
Definition: createplan.c:4244
static List * get_switched_clauses(List *clauses, Relids outerrelids)
Definition: createplan.c:4725
bool materialize_inner
Definition: relation.h:1454
void extract_actual_join_clauses(List *restrictinfo_list, List **joinquals, List **otherquals)
Definition: restrictinfo.c:383
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:5488
Path * innerjoinpath
Definition: relation.h:1395
#define IS_OUTER_JOIN(jointype)
Definition: nodes.h:726
ParamPathInfo * param_info
Definition: relation.h:1049
#define CP_SMALL_TLIST
Definition: createplan.c:67
Definition: nodes.h:513
List * get_actual_clauses(List *restrictinfo_list)
Definition: restrictinfo.c:333
static List * order_qual_clauses(PlannerInfo *root, List *clauses)
Definition: createplan.c:4802
EquivalenceClass * right_ec
Definition: relation.h:1896
unsigned int Oid
Definition: postgres_ext.h:31
int pk_strategy
Definition: relation.h:945
static Plan * create_plan_recurse(PlannerInfo *root, Path *best_path, int flags)
Definition: createplan.c:359
static Material * make_material(Plan *lefttree)
Definition: createplan.c:5993
bool skip_mark_restore
Definition: relation.h:1453
static void copy_generic_path_info(Plan *dest, Path *src)
Definition: createplan.c:4896
bool pk_nulls_first
Definition: relation.h:946
#define ERROR
Definition: elog.h:43
static List * build_path_tlist(PlannerInfo *root, Path *path)
Definition: createplan.c:736
List * joinrestrictinfo
Definition: relation.h:1397
RelOptInfo * parent
Definition: relation.h:1046
#define lfirst_node(type, lc)
Definition: pg_list.h:109
bool outer_is_left
Definition: relation.h:1902
Datum sort(PG_FUNCTION_ARGS)
Definition: _int_op.c:200
static void copy_plan_costsize(Plan *dest, Plan *src)
Definition: createplan.c:4911
static ListCell * list_head(const List *l)
Definition: pg_list.h:77
Relids relids
Definition: relation.h:585
double cpu_operator_cost
Definition: costsize.c:115
#define lnext(lc)
Definition: pg_list.h:105
Path * outerjoinpath
Definition: relation.h:1394
List * pathkeys
Definition: relation.h:1060
Path path
Definition: relation.h:1387
#define Assert(condition)
Definition: c.h:688
#define lfirst(lc)
Definition: pg_list.h:106
EquivalenceClass * pk_eclass
Definition: relation.h:943
static int list_length(const List *l)
Definition: pg_list.h:89
List * extract_actual_clauses(List *restrictinfo_list, bool pseudoconstant)
Definition: restrictinfo.c:356
bool inner_unique
Definition: relation.h:1391
List * list_difference(const List *list1, const List *list2)
Definition: list.c:858
List * innersortkeys
Definition: relation.h:1452
Oid pk_opfamily
Definition: relation.h:944
void * palloc(Size size)
Definition: mcxt.c:835
EquivalenceClass * left_ec
Definition: relation.h:1895
Join join
Definition: plannodes.h:711
JoinType jointype
Definition: relation.h:1389
int i
Cost total_cost
Definition: plannodes.h:126
JoinPath jpath
Definition: relation.h:1449
#define elog
Definition: elog.h:219
Definition: pg_list.h:45
static void label_sort_with_costsize(PlannerInfo *root, Sort *plan, double limit_tuples)
Definition: createplan.c:4933
Plan plan
Definition: plannodes.h:668

◆ create_minmaxagg_plan()

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

Definition at line 1993 of file createplan.c.

References Assert, build_path_tlist(), copy_generic_path_info(), create_plan(), PlannerInfo::hasInheritedTarget, lfirst, Query::limitCount, Query::limitOffset, 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().

1994 {
1995  Result *plan;
1996  List *tlist;
1997  ListCell *lc;
1998 
1999  /* Prepare an InitPlan for each aggregate's subquery. */
2000  foreach(lc, best_path->mmaggregates)
2001  {
2002  MinMaxAggInfo *mminfo = (MinMaxAggInfo *) lfirst(lc);
2003  PlannerInfo *subroot = mminfo->subroot;
2004  Query *subparse = subroot->parse;
2005  Plan *plan;
2006 
2007  /*
2008  * Generate the plan for the subquery. We already have a Path, but we
2009  * have to convert it to a Plan and attach a LIMIT node above it.
2010  * Since we are entering a different planner context (subroot),
2011  * recurse to create_plan not create_plan_recurse.
2012  */
2013  plan = create_plan(subroot, mminfo->path);
2014 
2015  plan = (Plan *) make_limit(plan,
2016  subparse->limitOffset,
2017  subparse->limitCount);
2018 
2019  /* Must apply correct cost/width data to Limit node */
2020  plan->startup_cost = mminfo->path->startup_cost;
2021  plan->total_cost = mminfo->pathcost;
2022  plan->plan_rows = 1;
2023  plan->plan_width = mminfo->path->pathtarget->width;
2024  plan->parallel_aware = false;
2025  plan->parallel_safe = mminfo->path->parallel_safe;
2026 
2027  /* Convert the plan into an InitPlan in the outer query. */
2028  SS_make_initplan_from_plan(root, subroot, plan, mminfo->param);
2029  }
2030 
2031  /* Generate the output plan --- basically just a Result */
2032  tlist = build_path_tlist(root, &best_path->path);
2033 
2034  plan = make_result(tlist, (Node *) best_path->quals, NULL);
2035 
2036  copy_generic_path_info(&plan->plan, (Path *) best_path);
2037 
2038  /*
2039  * During setrefs.c, we'll need to replace references to the Agg nodes
2040  * with InitPlan output params. (We can't just do that locally in the
2041  * MinMaxAgg node, because path nodes above here may have Agg references
2042  * as well.) Save the mmaggregates list to tell setrefs.c to do that.
2043  *
2044  * This doesn't work if we're in an inheritance subtree (see notes in
2045  * create_modifytable_plan). Fortunately we can't be because there would
2046  * never be aggregates in an UPDATE/DELETE; but let's Assert that.
2047  */
2048  Assert(!root->hasInheritedTarget);
2049  Assert(root->minmax_aggs == NIL);
2050  root->minmax_aggs = best_path->mmaggregates;
2051 
2052  return plan;
2053 }
Node * limitOffset
Definition: parsenodes.h:158
#define NIL
Definition: pg_list.h:69
double plan_rows
Definition: plannodes.h:131
PathTarget * pathtarget
Definition: relation.h:1047
Query * parse
Definition: relation.h:155
Param * param
Definition: relation.h:2189
Definition: nodes.h:513
List * minmax_aggs
Definition: relation.h:288
List * quals
Definition: relation.h:1609
Plan * create_plan(PlannerInfo *root, Path *best_path)
Definition: createplan.c:308
static void copy_generic_path_info(Plan *dest, Path *src)
Definition: createplan.c:4896
Path * path
Definition: relation.h:2187
static List * build_path_tlist(PlannerInfo *root, Path *path)
Definition: createplan.c:736
Cost startup_cost
Definition: relation.h:1057
Node * limitCount
Definition: parsenodes.h:159
Cost startup_cost
Definition: plannodes.h:125
bool parallel_aware
Definition: plannodes.h:137
static Result * make_result(List *tlist, Node *resconstantqual, Plan *subplan)
Definition: createplan.c:6416
List * mmaggregates
Definition: relation.h:1608
int plan_width
Definition: plannodes.h:132
#define Assert(condition)
Definition: c.h:688
#define lfirst(lc)
Definition: pg_list.h:106
bool parallel_safe
Definition: relation.h:1052
bool hasInheritedTarget
Definition: relation.h:300
void SS_make_initplan_from_plan(PlannerInfo *root, PlannerInfo *subroot, Plan *plan, Param *prm)
Definition: subselect.c:2984
Limit * make_limit(Plan *lefttree, Node *limitOffset, Node *limitCount)
Definition: createplan.c:6395
int width
Definition: relation.h:979
Cost total_cost
Definition: plannodes.h:126
bool parallel_safe
Definition: plannodes.h:138
Definition: pg_list.h:45
PlannerInfo * subroot
Definition: relation.h:2186

◆ create_modifytable_plan()

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

Definition at line 2348 of file createplan.c.

References apply_tlist_labeling(), ModifyTablePath::canSetTag, copy_generic_path_info(), CP_EXACT_TLIST, create_plan_recurse(), ModifyTablePath::epqParam, forboth, lappend(), lfirst, make_modifytable(), NIL, ModifyTablePath::nominalRelation, ModifyTablePath::onconflict, ModifyTablePath::operation, ModifyTablePath::partColsUpdated, ModifyTablePath::partitioned_rels, ModifyTablePath::path, ModifyTable::plan, PlannerInfo::processed_tlist, ModifyTablePath::resultRelations, ModifyTablePath::returningLists, ModifyTablePath::rowMarks, subpath(), ModifyTablePath::subpaths, ModifyTablePath::subroots, Plan::targetlist, and ModifyTablePath::withCheckOptionLists.

Referenced by create_plan_recurse().

2349 {
2350  ModifyTable *plan;
2351  List *subplans = NIL;
2352  ListCell *subpaths,
2353  *subroots;
2354 
2355  /* Build the plan for each input path */
2356  forboth(subpaths, best_path->subpaths,
2357  subroots, best_path->subroots)
2358  {
2359  Path *subpath = (Path *) lfirst(subpaths);
2360  PlannerInfo *subroot = (PlannerInfo *) lfirst(subroots);
2361  Plan *subplan;
2362 
2363  /*
2364  * In an inherited UPDATE/DELETE, reference the per-child modified
2365  * subroot while creating Plans from Paths for the child rel. This is
2366  * a kluge, but otherwise it's too hard to ensure that Plan creation
2367  * functions (particularly in FDWs) don't depend on the contents of
2368  * "root" matching what they saw at Path creation time. The main
2369  * downside is that creation functions for Plans that might appear
2370  * below a ModifyTable cannot expect to modify the contents of "root"
2371  * and have it "stick" for subsequent processing such as setrefs.c.
2372  * That's not great, but it seems better than the alternative.
2373  */
2374  subplan = create_plan_recurse(subroot, subpath, CP_EXACT_TLIST);
2375 
2376  /* Transfer resname/resjunk labeling, too, to keep executor happy */
2377  apply_tlist_labeling(subplan->targetlist, subroot->processed_tlist);
2378 
2379  subplans = lappend(subplans, subplan);
2380  }
2381 
2382  plan = make_modifytable(root,
2383  best_path->operation,
2384  best_path->canSetTag,
2385  best_path->nominalRelation,
2386  best_path->partitioned_rels,
2387  best_path->partColsUpdated,
2388  best_path->resultRelations,
2389  subplans,
2390  best_path->withCheckOptionLists,
2391  best_path->returningLists,
2392  best_path->rowMarks,
2393  best_path->onconflict,
2394  best_path->epqParam);
2395 
2396  copy_generic_path_info(&plan->plan, &best_path->path);
2397 
2398  return plan;
2399 }
#define NIL
Definition: pg_list.h:69
void apply_tlist_labeling(List *dest_tlist, List *src_tlist)
Definition: tlist.c:321
List * returningLists
Definition: relation.h:1686
OnConflictExpr * onconflict
Definition: relation.h:1688
#define forboth(cell1, list1, cell2, list2)
Definition: pg_list.h:180
Index nominalRelation
Definition: relation.h:1678
List * rowMarks
Definition: relation.h:1687
static Plan * create_plan_recurse(PlannerInfo *root, Path *best_path, int flags)
Definition: createplan.c:359
static void copy_generic_path_info(Plan *dest, Path *src)
Definition: createplan.c:4896
bool partColsUpdated
Definition: relation.h:1681
List * subroots
Definition: relation.h:1684
List * subpaths
Definition: relation.h:1683
List * lappend(List *list, void *datum)
Definition: list.c:128
List * partitioned_rels
Definition: relation.h:1680
#define lfirst(lc)
Definition: pg_list.h:106
static ModifyTable * make_modifytable(PlannerInfo *root, CmdType operation, bool canSetTag, Index nominalRelation, List *partitioned_rels, bool partColsUpdated, List *resultRelations, List *subplans, List *withCheckOptionLists, List *returningLists, List *rowMarks, OnConflictExpr *onconflict, int epqParam)
Definition: createplan.c:6456
List * targetlist
Definition: plannodes.h:144
List * withCheckOptionLists
Definition: relation.h:1685
CmdType operation
Definition: relation.h:1676
List * resultRelations
Definition: relation.h:1682
List * processed_tlist
Definition: relation.h:284
#define CP_EXACT_TLIST
Definition: createplan.c:66
Definition: pg_list.h:45
Datum subpath(PG_FUNCTION_ARGS)
Definition: ltree_op.c:234

◆ create_namedtuplestorescan_plan()

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

Definition at line 3358 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().

3360 {
3361  NamedTuplestoreScan *scan_plan;
3362  Index scan_relid = best_path->parent->relid;
3363  RangeTblEntry *rte;
3364 
3365  Assert(scan_relid > 0);
3366  rte = planner_rt_fetch(scan_relid, root);
3368 
3369  /* Sort clauses into best execution order */
3370  scan_clauses = order_qual_clauses(root, scan_clauses);
3371 
3372  /* Reduce RestrictInfo list to bare expressions; ignore pseudoconstants */
3373  scan_clauses = extract_actual_clauses(scan_clauses, false);
3374 
3375  /* Replace any outer-relation variables with nestloop params */
3376  if (best_path->param_info)
3377  {
3378  scan_clauses = (List *)
3379  replace_nestloop_params(root, (Node *) scan_clauses);
3380  }
3381 
3382  scan_plan = make_namedtuplestorescan(tlist, scan_clauses, scan_relid,
3383  rte->enrname);
3384 
3385  copy_generic_path_info(&scan_plan->scan.plan, best_path);
3386 
3387  return scan_plan;
3388 }
Plan plan
Definition: plannodes.h:330
static Node * replace_nestloop_params(PlannerInfo *root, Node *expr)
Definition: createplan.c:4244
ParamPathInfo * param_info
Definition: relation.h:1049
Definition: nodes.h:513
static List * order_qual_clauses(PlannerInfo *root, List *clauses)
Definition: createplan.c:4802
static void copy_generic_path_info(Plan *dest, Path *src)
Definition: createplan.c:4896
#define planner_rt_fetch(rti, root)
Definition: relation.h:328
RelOptInfo * parent
Definition: relation.h:1046
char * enrname
Definition: parsenodes.h:1056
Index relid
Definition: relation.h:613
static NamedTuplestoreScan * make_namedtuplestorescan(List *qptlist, List *qpqual, Index scanrelid, char *enrname)
Definition: createplan.c:5244
unsigned int Index
Definition: c.h:431
#define Assert(condition)
Definition: c.h:688
List * extract_actual_clauses(List *restrictinfo_list, bool pseudoconstant)
Definition: restrictinfo.c:356
RTEKind rtekind
Definition: parsenodes.h:959
Definition: pg_list.h:45

◆ create_nestloop_plan()

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

Definition at line 3671 of file createplan.c.

References bms_free(), bms_is_member(), bms_is_subset(), bms_overlap(), bms_union(), build_path_tlist(), copy_generic_path_info(), create_plan_recurse(), PlannerInfo::curOuterParams, PlannerInfo::curOuterRels, extract_actual_clauses(), extract_actual_join_clauses(), find_placeholder_info(), JoinPath::inner_unique, JoinPath::innerjoinpath, IS_OUTER_JOIN, IsA, NestLoop::join, JoinPath::joinrestrictinfo, JoinPath::jointype, lappend(), lfirst, list_delete_cell(), list_head(), lnext, make_nestloop(), next, NIL, order_qual_clauses(), JoinPath::outerjoinpath, Path::param_info, NestLoopParam::paramval, Path::parent, JoinPath::path, PlaceHolderInfo::ph_eval_at, Join::plan, RelOptInfo::relids, replace_nestloop_params(), and Var::varno.

Referenced by create_join_plan().

3673 {
3674  NestLoop *join_plan;
3675  Plan *outer_plan;
3676  Plan *inner_plan;
3677  List *tlist = build_path_tlist(root, &best_path->path);
3678  List *joinrestrictclauses = best_path->joinrestrictinfo;
3679  List *joinclauses;
3680  List *otherclauses;
3681  Relids outerrelids;
3682  List *nestParams;
3683  Relids saveOuterRels = root->curOuterRels;
3684  ListCell *cell;
3685  ListCell *prev;
3686  ListCell *next;
3687 
3688  /* NestLoop can project, so no need to be picky about child tlists */
3689  outer_plan = create_plan_recurse(root, best_path->outerjoinpath, 0);
3690 
3691  /* For a nestloop, include outer relids in curOuterRels for inner side */
3692  root->curOuterRels = bms_union(root->curOuterRels,
3693  best_path->outerjoinpath->parent->relids);
3694 
3695  inner_plan = create_plan_recurse(root, best_path->innerjoinpath, 0);
3696 
3697  /* Restore curOuterRels */
3698  bms_free(root->curOuterRels);
3699  root->curOuterRels = saveOuterRels;
3700 
3701  /* Sort join qual clauses into best execution order */
3702  joinrestrictclauses = order_qual_clauses(root, joinrestrictclauses);
3703 
3704  /* Get the join qual clauses (in plain expression form) */
3705  /* Any pseudoconstant clauses are ignored here */
3706  if (IS_OUTER_JOIN(best_path->jointype))
3707  {
3708  extract_actual_join_clauses(joinrestrictclauses,
3709  &joinclauses, &otherclauses);
3710  }
3711  else
3712  {
3713  /* We can treat all clauses alike for an inner join */
3714  joinclauses = extract_actual_clauses(joinrestrictclauses, false);
3715  otherclauses = NIL;
3716  }
3717 
3718  /* Replace any outer-relation variables with nestloop params */
3719  if (best_path->path.param_info)
3720  {
3721  joinclauses = (List *)
3722  replace_nestloop_params(root, (Node *) joinclauses);
3723  otherclauses = (List *)
3724  replace_nestloop_params(root, (Node *) otherclauses);
3725  }
3726 
3727  /*
3728  * Identify any nestloop parameters that should be supplied by this join
3729  * node, and move them from root->curOuterParams to the nestParams list.
3730  */
3731  outerrelids = best_path->outerjoinpath->parent->relids;
3732  nestParams = NIL;
3733  prev = NULL;
3734  for (cell = list_head(root->curOuterParams); cell; cell = next)
3735  {
3736  NestLoopParam *nlp = (NestLoopParam *) lfirst(cell);
3737 
3738  next = lnext(cell);
3739  if (IsA(nlp->paramval, Var) &&
3740  bms_is_member(nlp->paramval->varno, outerrelids))
3741  {
3743  cell, prev);
3744  nestParams = lappend(nestParams, nlp);
3745  }
3746  else if (IsA(nlp->paramval, PlaceHolderVar) &&
3747  bms_overlap(((PlaceHolderVar *) nlp->paramval)->phrels,
3748  outerrelids) &&
3750  (PlaceHolderVar *) nlp->paramval,
3751  false)->ph_eval_at,
3752  outerrelids))
3753  {
3755  cell, prev);
3756  nestParams = lappend(nestParams, nlp);
3757  }
3758  else
3759  prev = cell;
3760  }
3761 
3762  join_plan = make_nestloop(tlist,
3763  joinclauses,
3764  otherclauses,
3765  nestParams,
3766  outer_plan,
3767  inner_plan,
3768  best_path->jointype,
3769  best_path->inner_unique);
3770 
3771  copy_generic_path_info(&join_plan->join.plan, &best_path->path);
3772 
3773  return join_plan;
3774 }
#define NIL
Definition: pg_list.h:69
#define IsA(nodeptr, _type_)
Definition: nodes.h:564
static Node * replace_nestloop_params(PlannerInfo *root, Node *expr)
Definition: createplan.c:4244
Relids ph_eval_at
Definition: relation.h:2168
static int32 next
Definition: blutils.c:210
void extract_actual_join_clauses(List *restrictinfo_list, List **joinquals, List **otherquals)
Definition: restrictinfo.c:383
Relids curOuterRels
Definition: relation.h:315
Path * innerjoinpath
Definition: relation.h:1395
#define IS_OUTER_JOIN(jointype)
Definition: nodes.h:726
ParamPathInfo * param_info
Definition: relation.h:1049
Definition: nodes.h:513
static List * order_qual_clauses(PlannerInfo *root, List *clauses)
Definition: createplan.c:4802
Definition: primnodes.h:163
static Plan * create_plan_recurse(PlannerInfo *root, Path *best_path, int flags)
Definition: createplan.c:359
static void copy_generic_path_info(Plan *dest, Path *src)
Definition: createplan.c:4896
Var * paramval
Definition: plannodes.h:695
Join join
Definition: plannodes.h:687
static List * build_path_tlist(PlannerInfo *root, Path *path)
Definition: createplan.c:736
List * joinrestrictinfo
Definition: relation.h:1397
RelOptInfo * parent
Definition: relation.h:1046
bool bms_is_subset(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:352
static NestLoop * make_nestloop(List *tlist, List *joinclauses, List *otherclauses, List *nestParams, Plan *lefttree, Plan *righttree, JoinType jointype, bool inner_unique)
Definition: createplan.c:5417
List * curOuterParams
Definition: relation.h:316
PlaceHolderInfo * find_placeholder_info(PlannerInfo *root, PlaceHolderVar *phv, bool create_new_ph)
Definition: placeholder.c:70
static ListCell * list_head(const List *l)
Definition: pg_list.h:77
Relids relids
Definition: relation.h:585
#define lnext(lc)
Definition: pg_list.h:105
List * lappend(List *list, void *datum)
Definition: list.c:128
Index varno
Definition: primnodes.h:166
List * list_delete_cell(List *list, ListCell *cell, ListCell *prev)
Definition: list.c:528
Path * outerjoinpath
Definition: relation.h:1394
void bms_free(Bitmapset *a)
Definition: bitmapset.c:245
Path path
Definition: relation.h:1387
#define lfirst(lc)
Definition: pg_list.h:106
Bitmapset * bms_union(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:262
List * extract_actual_clauses(List *restrictinfo_list, bool pseudoconstant)
Definition: restrictinfo.c:356
bool inner_unique
Definition: relation.h:1391
bool bms_overlap(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:487
JoinType jointype
Definition: relation.h:1389
Definition: pg_list.h:45
bool bms_is_member(int x, const Bitmapset *a)
Definition: bitmapset.c:464
Plan plan
Definition: plannodes.h:668

◆ create_plan()

Plan* create_plan ( PlannerInfo root,
Path best_path 
)

Definition at line 308 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().

309 {
310  Plan *plan;
311 
312  /* plan_params should not be in use in current query level */
313  Assert(root->plan_params == NIL);
314 
315  /* Initialize this module's private workspace in PlannerInfo */
316  root->curOuterRels = NULL;
317  root->curOuterParams = NIL;
318 
319  /* Recursively process the path tree, demanding the correct tlist result */
320  plan = create_plan_recurse(root, best_path, CP_EXACT_TLIST);
321 
322  /*
323  * Make sure the topmost plan node's targetlist exposes the original
324  * column names and other decorative info. Targetlists generated within
325  * the planner don't bother with that stuff, but we must have it on the
326  * top-level tlist seen at execution time. However, ModifyTable plan
327  * nodes don't have a tlist matching the querytree targetlist.
328  */
329  if (!IsA(plan, ModifyTable))
331 
332  /*
333  * Attach any initPlans created in this query level to the topmost plan
334  * node. (In principle the initplans could go in any plan node at or
335  * above where they're referenced, but there seems no reason to put them
336  * any lower than the topmost node for the query level. Also, see
337  * comments for SS_finalize_plan before you try to change this.)
338  */
339  SS_attach_initplans(root, plan);
340 
341  /* Check we successfully assigned all NestLoopParams to plan nodes */
342  if (root->curOuterParams != NIL)
343  elog(ERROR, "failed to assign all NestLoopParams to plan nodes");
344 
345  /*
346  * Reset plan_params to ensure param IDs used for nestloop params are not
347  * re-used later
348  */
349  root->plan_params = NIL;
350 
351  return plan;
352 }
#define NIL
Definition: pg_list.h:69
void apply_tlist_labeling(List *dest_tlist, List *src_tlist)
Definition: tlist.c:321
#define IsA(nodeptr, _type_)
Definition: nodes.h:564
List * plan_params
Definition: relation.h:169
Relids curOuterRels
Definition: relation.h:315
static Plan * create_plan_recurse(PlannerInfo *root, Path *best_path, int flags)
Definition: createplan.c:359
#define ERROR
Definition: elog.h:43
List * curOuterParams
Definition: relation.h:316
#define Assert(condition)
Definition: c.h:688
void SS_attach_initplans(PlannerInfo *root, Plan *plan)
Definition: subselect.c:2220
List * targetlist
Definition: plannodes.h:144
#define elog
Definition: elog.h:219
List * processed_tlist
Definition: relation.h:284
#define CP_EXACT_TLIST
Definition: createplan.c:66

◆ create_plan_recurse()

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

Definition at line 359 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_groupingsets_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_result_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_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_SampleScan, T_SeqScan, T_SetOp, T_Sort, T_SubqueryScan, T_TableFuncScan, 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_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_setop_plan(), create_sort_plan(), create_unique_plan(), create_upper_unique_plan(), and create_windowagg_plan().

360 {
361  Plan *plan;
362 
363  /* Guard against stack overflow due to overly complex plans */
365 
366  switch (best_path->pathtype)
367  {
368  case T_SeqScan:
369  case T_SampleScan:
370  case T_IndexScan:
371  case T_IndexOnlyScan:
372  case T_BitmapHeapScan:
373  case T_TidScan:
374  case T_SubqueryScan:
375  case T_FunctionScan:
376  case T_TableFuncScan:
377  case T_ValuesScan:
378  case T_CteScan:
379  case T_WorkTableScan:
381  case T_ForeignScan:
382  case T_CustomScan:
383  plan = create_scan_plan(root, best_path, flags);
384  break;
385  case T_HashJoin:
386  case T_MergeJoin:
387  case T_NestLoop:
388  plan = create_join_plan(root,
389  (JoinPath *) best_path);
390  break;
391  case T_Append:
392  plan = create_append_plan(root,
393  (AppendPath *) best_path);
394  break;
395  case T_MergeAppend:
396  plan = create_merge_append_plan(root,
397  (MergeAppendPath *) best_path);
398  break;
399  case T_Result:
400  if (IsA(best_path, ProjectionPath))
401  {
402  plan = create_projection_plan(root,
403  (ProjectionPath *) best_path);
404  }
405  else if (IsA(best_path, MinMaxAggPath))
406  {
407  plan = (Plan *) create_minmaxagg_plan(root,
408  (MinMaxAggPath *) best_path);
409  }
410  else
411  {
412  Assert(IsA(best_path, ResultPath));
413  plan = (Plan *) create_result_plan(root,
414  (ResultPath *) best_path);
415  }
416  break;
417  case T_ProjectSet:
418  plan = (Plan *) create_project_set_plan(root,
419  (ProjectSetPath *) best_path);
420  break;
421  case T_Material:
422  plan = (Plan *) create_material_plan(root,
423  (MaterialPath *) best_path,
424  flags);
425  break;
426  case T_Unique:
427  if (IsA(best_path, UpperUniquePath))
428  {
429  plan = (Plan *) create_upper_unique_plan(root,
430  (UpperUniquePath *) best_path,
431  flags);
432  }
433  else
434  {
435  Assert(IsA(best_path, UniquePath));
436  plan = create_unique_plan(root,
437  (UniquePath *) best_path,
438  flags);
439  }
440  break;
441  case T_Gather:
442  plan = (Plan *) create_gather_plan(root,
443  (GatherPath *) best_path);
444  break;
445  case T_Sort:
446  plan = (Plan *) create_sort_plan(root,
447  (SortPath *) best_path,
448  flags);
449  break;
450  case T_Group:
451  plan = (Plan *) create_group_plan(root,
452  (GroupPath *) best_path);
453  break;
454  case T_Agg:
455  if (IsA(best_path, GroupingSetsPath))
456  plan = create_groupingsets_plan(root,
457  (GroupingSetsPath *) best_path);
458  else
459  {
460  Assert(IsA(best_path, AggPath));
461  plan = (Plan *) create_agg_plan(root,
462  (AggPath *) best_path);
463  }
464  break;
465  case T_WindowAgg:
466  plan = (Plan *) create_windowagg_plan(root,
467  (WindowAggPath *) best_path);
468  break;
469  case T_SetOp:
470  plan = (Plan *) create_setop_plan(root,
471  (SetOpPath *) best_path,
472  flags);
473  break;
474  case T_RecursiveUnion:
475  plan = (Plan *) create_recursiveunion_plan(root,
476  (RecursiveUnionPath *) best_path);
477  break;
478  case T_LockRows:
479  plan = (Plan *) create_lockrows_plan(root,
480  (LockRowsPath *) best_path,
481  flags);
482  break;
483  case T_ModifyTable:
484  plan = (Plan *) create_modifytable_plan(root,
485  (ModifyTablePath *) best_path);
486  break;
487  case T_Limit:
488  plan = (Plan *) create_limit_plan(root,
489  (LimitPath *) best_path,
490  flags);
491  break;
492  case T_GatherMerge:
493  plan = (Plan *) create_gather_merge_plan(root,
494  (GatherMergePath *) best_path);
495  break;
496  default:
497  elog(ERROR, "unrecognized node type: %d",
498  (int) best_path->pathtype);
499  plan = NULL; /* keep compiler quiet */
500  break;
501  }
502 
503  return plan;
504 }
static Plan * create_unique_plan(PlannerInfo *root, UniquePath *best_path, int flags)
Definition: createplan.c:1272
static Result * create_minmaxagg_plan(PlannerInfo *root, MinMaxAggPath *best_path)
Definition: createplan.c:1993
static Result * create_result_plan(PlannerInfo *root, ResultPath *best_path)
Definition: createplan.c:1193
Definition: nodes.h:77
static Group * create_group_plan(PlannerInfo *root, GroupPath *best_path)
Definition: createplan.c:1687
#define IsA(nodeptr, _type_)
Definition: nodes.h:564
Definition: nodes.h:79
static Sort * create_sort_plan(PlannerInfo *root, SortPath *best_path, int flags)
Definition: createplan.c:1660
static Plan * create_scan_plan(PlannerInfo *root, Path *best_path, int flags)
Definition: createplan.c:511
static LockRows * create_lockrows_plan(PlannerInfo *root, LockRowsPath *best_path, int flags)
Definition: createplan.c:2325
static ProjectSet * create_project_set_plan(PlannerInfo *root, ProjectSetPath *best_path)
Definition: createplan.c:1218
static RecursiveUnion * create_recursiveunion_plan(PlannerInfo *root, RecursiveUnionPath *best_path)
Definition: createplan.c:2289
static Agg * create_agg_plan(PlannerInfo *root, AggPath *best_path)
Definition: createplan.c:1752
static Unique * create_upper_unique_plan(PlannerInfo *root, UpperUniquePath *best_path, int flags)
Definition: createplan.c:1724
Definition: nodes.h:48
Definition: nodes.h:75
static ModifyTable * create_modifytable_plan(PlannerInfo *root, ModifyTablePath *best_path)
Definition: createplan.c:2348
NodeTag pathtype
Definition: relation.h:1044
Definition: nodes.h:45
#define ERROR
Definition: elog.h:43
static Plan * create_projection_plan(PlannerInfo *root, ProjectionPath *best_path)
Definition: createplan.c:1570
Definition: nodes.h:76
static Plan * create_join_plan(PlannerInfo *root, JoinPath *best_path)
Definition: createplan.c:959
void check_stack_depth(void)
Definition: postgres.c:3154
static GatherMerge * create_gather_merge_plan(PlannerInfo *root, GatherMergePath *best_path)
Definition: createplan.c:1511
static SetOp * create_setop_plan(PlannerInfo *root, SetOpPath *best_path, int flags)
Definition: createplan.c:2253
#define Assert(condition)
Definition: c.h:688
static Gather * create_gather_plan(PlannerInfo *root, GatherPath *best_path)
Definition: createplan.c:1475
static Plan * create_append_plan(PlannerInfo *root, AppendPath *best_path)
Definition: createplan.c:1019
static WindowAgg * create_windowagg_plan(PlannerInfo *root, WindowAggPath *best_path)
Definition: createplan.c:2062
static Material * create_material_plan(PlannerInfo *root, MaterialPath *best_path, int flags)
Definition: createplan.c:1244
Definition: nodes.h:83
Definition: nodes.h:80
static Plan * create_groupingsets_plan(PlannerInfo *root, GroupingSetsPath *best_path)
Definition: createplan.c:1833
static Limit * create_limit_plan(PlannerInfo *root, LimitPath *best_path, int flags)
Definition: createplan.c:2408
#define elog
Definition: elog.h:219
static Plan * create_merge_append_plan(PlannerInfo *root, MergeAppendPath *best_path)
Definition: createplan.c:1085
Definition: nodes.h:85

◆ create_project_set_plan()

static ProjectSet * create_project_set_plan ( PlannerInfo root,
ProjectSetPath best_path 
)
static

Definition at line 1218 of file createplan.c.

References build_path_tlist(), copy_generic_path_info(), create_plan_recurse(), make_project_set(), ProjectSetPath::path, ProjectSet::plan, and ProjectSetPath::subpath.

Referenced by create_plan_recurse().

1219 {
1220  ProjectSet *plan;
1221  Plan *subplan;
1222  List *tlist;
1223 
1224  /* Since we intend to project, we don't need to constrain child tlist */
1225  subplan = create_plan_recurse(root, best_path->subpath, 0);
1226 
1227  tlist = build_path_tlist(root, &best_path->path);
1228 
1229  plan = make_project_set(tlist, subplan);
1230 
1231  copy_generic_path_info(&plan->plan, (Path *) best_path);
1232 
1233  return plan;
1234 }
static Plan * create_plan_recurse(PlannerInfo *root, Path *best_path, int flags)
Definition: createplan.c:359
static ProjectSet * make_project_set(List *tlist, Plan *subplan)
Definition: createplan.c:6437
static void copy_generic_path_info(Plan *dest, Path *src)
Definition: createplan.c:4896
static List * build_path_tlist(PlannerInfo *root, Path *path)
Definition: createplan.c:736
Path * subpath
Definition: relation.h:1503
Definition: pg_list.h:45
Plan plan
Definition: plannodes.h:202

◆ create_projection_plan()

static Plan * create_projection_plan ( PlannerInfo root,
ProjectionPath best_path 
)
static

Definition at line 1570 of file createplan.c.

References build_path_tlist(), copy_generic_path_info(), create_plan_recurse(), is_projection_capable_path(), make_result(), Plan::parallel_safe, Path::parallel_safe, ProjectionPath::path, Path::pathtarget, Plan::plan_rows, Plan::plan_width, Path::rows, Plan::startup_cost, Path::startup_cost, ProjectionPath::subpath, Plan::targetlist, tlist_same_exprs(), Plan::total_cost, Path::total_cost, and PathTarget::width.

Referenced by create_plan_recurse().

1571 {
1572  Plan *plan;
1573  Plan *subplan;
1574  List *tlist;
1575 
1576  /* Since we intend to project, we don't need to constrain child tlist */
1577  subplan = create_plan_recurse(root, best_path->subpath, 0);
1578 
1579  tlist = build_path_tlist(root, &best_path->path);
1580 
1581  /*
1582  * We might not really need a Result node here, either because the subplan
1583  * can project or because it's returning the right list of expressions
1584  * anyway. Usually create_projection_path will have detected that and set
1585  * dummypp if we don't need a Result; but its decision can't be final,
1586  * because some createplan.c routines change the tlists of their nodes.
1587  * (An example is that create_merge_append_plan might add resjunk sort
1588  * columns to a MergeAppend.) So we have to recheck here. If we do
1589  * arrive at a different answer than create_projection_path did, we'll
1590  * have made slightly wrong cost estimates; but label the plan with the
1591  * cost estimates we actually used, not "corrected" ones. (XXX this could
1592  * be cleaned up if we moved more of the sortcolumn setup logic into Path
1593  * creation, but that would add expense to creating Paths we might end up
1594  * not using.)
1595  */
1596  if (is_projection_capable_path(best_path->subpath) ||
1597  tlist_same_exprs(tlist, subplan->targetlist))
1598  {
1599  /* Don't need a separate Result, just assign tlist to subplan */
1600  plan = subplan;
1601  plan->targetlist = tlist;
1602 
1603  /* Label plan with the estimated costs we actually used */
1604  plan->startup_cost = best_path->path.startup_cost;
1605  plan->total_cost = best_path->path.total_cost;
1606  plan->plan_rows = best_path->path.rows;
1607  plan->plan_width = best_path->path.pathtarget->width;
1608  plan->parallel_safe = best_path->path.parallel_safe;
1609  /* ... but don't change subplan's parallel_aware flag */
1610  }
1611  else
1612  {
1613  /* We need a Result node */
1614  plan = (Plan *) make_result(tlist, NULL, subplan);
1615 
1616  copy_generic_path_info(plan, (Path *) best_path);
1617  }
1618 
1619  return plan;
1620 }
double plan_rows
Definition: plannodes.h:131
PathTarget * pathtarget
Definition: relation.h:1047
static Plan * create_plan_recurse(PlannerInfo *root, Path *best_path, int flags)
Definition: createplan.c:359
static void copy_generic_path_info(Plan *dest, Path *src)
Definition: createplan.c:4896
static List * build_path_tlist(PlannerInfo *root, Path *path)
Definition: createplan.c:736
Cost startup_cost
Definition: relation.h:1057
Cost startup_cost
Definition: plannodes.h:125
static Result * make_result(List *tlist, Node *resconstantqual, Plan *subplan)
Definition: createplan.c:6416
Cost total_cost
Definition: relation.h:1058
int plan_width
Definition: plannodes.h:132
double rows
Definition: relation.h:1056
bool parallel_safe
Definition: relation.h:1052
bool tlist_same_exprs(List *tlist1, List *tlist2)
Definition: tlist.c:221
List * targetlist
Definition: plannodes.h:144
int width
Definition: relation.h:979
bool is_projection_capable_path(Path *path)
Definition: createplan.c:6599
Cost total_cost
Definition: plannodes.h:126
bool parallel_safe
Definition: plannodes.h:138
Path * subpath
Definition: relation.h:1491
Definition: pg_list.h:45

◆ create_recursiveunion_plan()

static RecursiveUnion * create_recursiveunion_plan ( PlannerInfo root,
RecursiveUnionPath best_path 
)
static

Definition at line 2289 of file createplan.c.

References build_path_tlist(), copy_generic_path_info(), CP_EXACT_TLIST, create_plan_recurse(), RecursiveUnionPath::distinctList, RecursiveUnionPath::leftpath, make_recursive_union(), Min, RecursiveUnionPath::numGroups, RecursiveUnionPath::path, RecursiveUnion::plan, RecursiveUnionPath::rightpath, and RecursiveUnionPath::wtParam.

Referenced by create_plan_recurse().

2290 {
2291  RecursiveUnion *plan;
2292  Plan *leftplan;
2293  Plan *rightplan;
2294  List *tlist;
2295  long numGroups;
2296 
2297  /* Need both children to produce same tlist, so force it */
2298  leftplan = create_plan_recurse(root, best_path->leftpath, CP_EXACT_TLIST);
2299  rightplan = create_plan_recurse(root, best_path->rightpath, CP_EXACT_TLIST);
2300 
2301  tlist = build_path_tlist(root, &best_path->path);
2302 
2303  /* Convert numGroups to long int --- but 'ware overflow! */
2304  numGroups = (long) Min(best_path->numGroups, (double) LONG_MAX);
2305 
2306  plan = make_recursive_union(tlist,
2307  leftplan,
2308  rightplan,
2309  best_path->wtParam,
2310  best_path->distinctList,
2311  numGroups);
2312 
2313  copy_generic_path_info(&plan->plan, (Path *) best_path);
2314 
2315  return plan;
2316 }
static RecursiveUnion * make_recursive_union(List *tlist, Plan *lefttree, Plan *righttree, int wtParam, List *distinctList, long numGroups)
Definition: createplan.c:5335
#define Min(x, y)
Definition: c.h:846
static Plan * create_plan_recurse(PlannerInfo *root, Path *best_path, int flags)
Definition: createplan.c:359
static void copy_generic_path_info(Plan *dest, Path *src)
Definition: createplan.c:4896
static List * build_path_tlist(PlannerInfo *root, Path *path)
Definition: createplan.c:736
#define CP_EXACT_TLIST
Definition: createplan.c:66
Definition: pg_list.h:45

◆ create_result_plan()

static Result * create_result_plan ( PlannerInfo root,
ResultPath best_path 
)
static

Definition at line 1193 of file createplan.c.

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

Referenced by create_plan_recurse().

1194 {
1195  Result *plan;
1196  List *tlist;
1197  List *quals;
1198 
1199  tlist = build_path_tlist(root, &best_path->path);
1200 
1201  /* best_path->quals is just bare clauses */
1202  quals = order_qual_clauses(root, best_path->quals);
1203 
1204  plan = make_result(tlist, (Node *) quals, NULL);
1205 
1206  copy_generic_path_info(&plan->plan, (Path *) best_path);
1207 
1208  return plan;
1209 }
Plan plan
Definition: plannodes.h:190
Definition: nodes.h:513
static List * order_qual_clauses(PlannerInfo *root, List *clauses)
Definition: createplan.c:4802
static void copy_generic_path_info(Plan *dest, Path *src)
Definition: createplan.c:4896
Path path
Definition: relation.h:1311
static List * build_path_tlist(PlannerInfo *root, Path *path)
Definition: createplan.c:736
static Result * make_result(List *tlist, Node *resconstantqual, Plan *subplan)
Definition: createplan.c:6416
List * quals
Definition: relation.h:1312
Definition: pg_list.h:45

◆ create_samplescan_plan()

static SampleScan * create_samplescan_plan ( PlannerInfo root,
Path best_path,
List tlist,
List scan_clauses 
)
static

Definition at line 2477 of file createplan.c.

References Assert, copy_generic_path_info(), extract_actual_clauses(), make_samplescan(), order_qual_clauses(), Path::param_info, Path::parent, Scan::plan, planner_rt_fetch, RelOptInfo::relid, replace_nestloop_params(), RTE_RELATION, RangeTblEntry::rtekind, SampleScan::scan, and RangeTblEntry::tablesample.

Referenced by create_scan_plan().

2479 {
2480  SampleScan *scan_plan;
2481  Index scan_relid = best_path->parent->relid;
2482  RangeTblEntry *rte;
2483  TableSampleClause *tsc;
2484 
2485  /* it should be a base rel with a tablesample clause... */
2486  Assert(scan_relid > 0);
2487  rte = planner_rt_fetch(scan_relid, root);
2488  Assert(rte->rtekind == RTE_RELATION);
2489  tsc = rte->tablesample;
2490  Assert(tsc != NULL);
2491 
2492  /* Sort clauses into best execution order */
2493  scan_clauses = order_qual_clauses(root, scan_clauses);
2494 
2495  /* Reduce RestrictInfo list to bare expressions; ignore pseudoconstants */
2496  scan_clauses = extract_actual_clauses(scan_clauses, false);
2497 
2498  /* Replace any outer-relation variables with nestloop params */
2499  if (best_path->param_info)
2500  {
2501  scan_clauses = (List *)
2502  replace_nestloop_params(root, (Node *) scan_clauses);
2503  tsc = (TableSampleClause *)
2504  replace_nestloop_params(root, (Node *) tsc);
2505  }
2506 
2507  scan_plan = make_samplescan(tlist,
2508  scan_clauses,
2509  scan_relid,
2510  tsc);
2511 
2512  copy_generic_path_info(&scan_plan->scan.plan, best_path);
2513 
2514  return scan_plan;
2515 }
Plan plan
Definition: plannodes.h:330
static Node * replace_nestloop_params(PlannerInfo *root, Node *expr)
Definition: createplan.c:4244
ParamPathInfo * param_info
Definition: relation.h:1049
Definition: nodes.h:513
static List * order_qual_clauses(PlannerInfo *root, List *clauses)
Definition: createplan.c:4802
static void copy_generic_path_info(Plan *dest, Path *src)
Definition: createplan.c:4896
#define planner_rt_fetch(rti, root)
Definition: relation.h:328
Scan scan
Definition: plannodes.h:346
RelOptInfo * parent
Definition: relation.h:1046
Index relid
Definition: relation.h:613
static SampleScan * make_samplescan(List *qptlist, List *qpqual, Index scanrelid, TableSampleClause *tsc)
Definition: createplan.c:5008
unsigned int Index
Definition: c.h:431
#define Assert(condition)
Definition: c.h:688
List * extract_actual_clauses(List *restrictinfo_list, bool pseudoconstant)
Definition: restrictinfo.c:356
RTEKind rtekind
Definition: parsenodes.h:959
Definition: pg_list.h:45
struct TableSampleClause * tablesample
Definition: parsenodes.h:977

◆ create_scan_plan()

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

Definition at line 511 of file createplan.c.

References apply_pathtarget_labeling_to_tlist(), RelOptInfo::baserestrictinfo, build_path_tlist(), build_physical_tlist(), castNode, copyObject, create_bitmap_scan_plan(), create_ctescan_plan(), create_customscan_plan(), create_foreignscan_plan(), create_functionscan_plan(), create_gating_plan(), create_indexscan_plan(), create_namedtuplestorescan_plan(), create_samplescan_plan(), create_seqscan_plan(), create_subqueryscan_plan(), create_tablefuncscan_plan(), create_tidscan_plan(), create_valuesscan_plan(), create_worktablescan_plan(), elog, ERROR, get_gating_quals(), list_concat(), list_copy(), NIL, Path::param_info, Path::parent, Path::pathtarget, Path::pathtype, ParamPathInfo::ppi_clauses, T_BitmapHeapScan, T_CteScan, T_CustomScan, T_ForeignScan, T_FunctionScan, T_IndexOnlyScan, T_IndexScan, T_NamedTuplestoreScan, T_SampleScan, T_SeqScan, T_SubqueryScan, T_TableFuncScan, T_TidScan, T_ValuesScan, T_WorkTableScan, and use_physical_tlist().

Referenced by create_plan_recurse().

512 {
513  RelOptInfo *rel = best_path->parent;
514  List *scan_clauses;
515  List *gating_clauses;
516  List *tlist;
517  Plan *plan;
518 
519  /*
520  * Extract the relevant restriction clauses from the parent relation. The
521  * executor must apply all these restrictions during the scan, except for
522  * pseudoconstants which we'll take care of below.
523  *
524  * If this is a plain indexscan or index-only scan, we need not consider
525  * restriction clauses that are implied by the index's predicate, so use
526  * indrestrictinfo not baserestrictinfo. Note that we can't do that for
527  * bitmap indexscans, since there's not necessarily a single index
528  * involved; but it doesn't matter since create_bitmap_scan_plan() will be
529  * able to get rid of such clauses anyway via predicate proof.
530  */
531  switch (best_path->pathtype)
532  {
533  case T_IndexScan:
534  case T_IndexOnlyScan:
535  scan_clauses = castNode(IndexPath, best_path)->indexinfo->indrestrictinfo;
536  break;
537  default:
538  scan_clauses = rel->baserestrictinfo;
539  break;
540  }
541 
542  /*
543  * If this is a parameterized scan, we also need to enforce all the join
544  * clauses available from the outer relation(s).
545  *
546  * For paranoia's sake, don't modify the stored baserestrictinfo list.
547  */
548  if (best_path->param_info)
549  scan_clauses = list_concat(list_copy(scan_clauses),
550  best_path->param_info->ppi_clauses);
551 
552  /*
553  * Detect whether we have any pseudoconstant quals to deal with. Then, if
554  * we'll need a gating Result node, it will be able to project, so there
555  * are no requirements on the child's tlist.
556  */
557  gating_clauses = get_gating_quals(root, scan_clauses);
558  if (gating_clauses)
559  flags = 0;
560 
561  /*
562  * For table scans, rather than using the relation targetlist (which is
563  * only those Vars actually needed by the query), we prefer to generate a
564  * tlist containing all Vars in order. This will allow the executor to
565  * optimize away projection of the table tuples, if possible.
566  */
567  if (use_physical_tlist(root, best_path, flags))
568  {
569  if (best_path->pathtype == T_IndexOnlyScan)
570  {
571  /* For index-only scan, the preferred tlist is the index's */
572  tlist = copyObject(((IndexPath *) best_path)->indexinfo->indextlist);
573 
574  /*
575  * Transfer any sortgroupref data to the replacement tlist, unless
576  * we don't care because the gating Result will handle it.
577  */
578  if (!gating_clauses)
580  }
581  else
582  {
583  tlist = build_physical_tlist(root, rel);
584  if (tlist == NIL)
585  {
586  /* Failed because of dropped cols, so use regular method */
587  tlist = build_path_tlist(root, best_path);
588  }
589  else
590  {
591  /* As above, transfer sortgroupref data to replacement tlist */
592  if (!gating_clauses)
594  }
595  }
596  }
597  else
598  {
599  tlist = build_path_tlist(root, best_path);
600  }
601 
602  switch (best_path->pathtype)
603  {
604  case T_SeqScan:
605  plan = (Plan *) create_seqscan_plan(root,
606  best_path,
607  tlist,
608  scan_clauses);
609  break;
610 
611  case T_SampleScan:
612  plan = (