PostgreSQL Source Code  git master
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros
planner.h File Reference
#include "nodes/plannodes.h"
#include "nodes/relation.h"
Include dependency graph for planner.h:
This graph shows which files directly or indirectly include this file:

Go to the source code of this file.

Typedefs

typedef PlannedStmt *(* planner_hook_type )(Query *parse, int cursorOptions, ParamListInfo boundParams)
 
typedef void(* create_upper_paths_hook_type )(PlannerInfo *root, UpperRelationKind stage, RelOptInfo *input_rel, RelOptInfo *output_rel)
 

Functions

PlannedStmtplanner (Query *parse, int cursorOptions, ParamListInfo boundParams)
 
PlannedStmtstandard_planner (Query *parse, int cursorOptions, ParamListInfo boundParams)
 
PlannerInfosubquery_planner (PlannerGlobal *glob, Query *parse, PlannerInfo *parent_root, bool hasRecursion, double tuple_fraction)
 
bool is_dummy_plan (Plan *plan)
 
RowMarkType select_rowmark_type (RangeTblEntry *rte, LockClauseStrength strength)
 
void mark_partial_aggref (Aggref *agg, AggSplit aggsplit)
 
Pathget_cheapest_fractional_path (RelOptInfo *rel, double tuple_fraction)
 
Exprexpression_planner (Expr *expr)
 
Exprpreprocess_phv_expression (PlannerInfo *root, Expr *expr)
 
bool plan_cluster_use_sort (Oid tableOid, Oid indexOid)
 
Listget_partitioned_child_rels (PlannerInfo *root, Index rti)
 
Listget_partitioned_child_rels_for_join (PlannerInfo *root, Relids join_relids)
 

Variables

PGDLLIMPORT planner_hook_type planner_hook
 
PGDLLIMPORT
create_upper_paths_hook_type 
create_upper_paths_hook
 

Typedef Documentation

typedef void(* create_upper_paths_hook_type)(PlannerInfo *root, UpperRelationKind stage, RelOptInfo *input_rel, RelOptInfo *output_rel)

Definition at line 28 of file planner.h.

typedef PlannedStmt*(* planner_hook_type)(Query *parse, int cursorOptions, ParamListInfo boundParams)

Definition at line 22 of file planner.h.

Function Documentation

Expr* expression_planner ( Expr expr)

Definition at line 5997 of file planner.c.

References eval_const_expressions(), and fix_opfuncids().

Referenced by ATExecAddColumn(), ATPrepAlterColumnType(), BeginCopyFrom(), CheckMutability(), ComputePartitionAttrs(), ExecPrepareCheck(), ExecPrepareExpr(), ExecPrepareQual(), get_cast_hashentry(), load_domaintype_info(), slot_fill_defaults(), and transformPartitionBoundValue().

5998 {
5999  Node *result;
6000 
6001  /*
6002  * Convert named-argument function calls, insert default arguments and
6003  * simplify constant subexprs
6004  */
6005  result = eval_const_expressions(NULL, (Node *) expr);
6006 
6007  /* Fill in opfuncid values if missing */
6008  fix_opfuncids(result);
6009 
6010  return (Expr *) result;
6011 }
void fix_opfuncids(Node *node)
Definition: nodeFuncs.c:1582
Definition: nodes.h:510
Node * eval_const_expressions(PlannerInfo *root, Node *node)
Definition: clauses.c:2429
Path* get_cheapest_fractional_path ( RelOptInfo rel,
double  tuple_fraction 
)

Definition at line 5844 of file planner.c.

References RelOptInfo::cheapest_total_path, compare_fractional_path_costs(), lfirst, RelOptInfo::pathlist, and Path::rows.

Referenced by make_subplan(), recurse_set_operations(), and standard_planner().

5845 {
5846  Path *best_path = rel->cheapest_total_path;
5847  ListCell *l;
5848 
5849  /* If all tuples will be retrieved, just return the cheapest-total path */
5850  if (tuple_fraction <= 0.0)
5851  return best_path;
5852 
5853  /* Convert absolute # of tuples to a fraction; no need to clamp to 0..1 */
5854  if (tuple_fraction >= 1.0 && best_path->rows > 0)
5855  tuple_fraction /= best_path->rows;
5856 
5857  foreach(l, rel->pathlist)
5858  {
5859  Path *path = (Path *) lfirst(l);
5860 
5861  if (path == rel->cheapest_total_path ||
5862  compare_fractional_path_costs(best_path, path, tuple_fraction) <= 0)
5863  continue;
5864 
5865  best_path = path;
5866  }
5867 
5868  return best_path;
5869 }
struct Path * cheapest_total_path
Definition: relation.h:603
#define lfirst(lc)
Definition: pg_list.h:106
double rows
Definition: relation.h:1052
int compare_fractional_path_costs(Path *path1, Path *path2, double fraction)
Definition: pathnode.c:115
List * pathlist
Definition: relation.h:599
List* get_partitioned_child_rels ( PlannerInfo root,
Index  rti 
)

Definition at line 6135 of file planner.c.

References PartitionedChildRelInfo::child_rels, lfirst_node, NIL, PartitionedChildRelInfo::parent_relid, and PlannerInfo::pcinfo_list.

Referenced by add_paths_to_append_rel(), and inheritance_planner().

6136 {
6137  List *result = NIL;
6138  ListCell *l;
6139 
6140  foreach(l, root->pcinfo_list)
6141  {
6143 
6144  if (pc->parent_relid == rti)
6145  {
6146  result = pc->child_rels;
6147  break;
6148  }
6149  }
6150 
6151  return result;
6152 }
#define NIL
Definition: pg_list.h:69
#define lfirst_node(type, lc)
Definition: pg_list.h:109
List * pcinfo_list
Definition: relation.h:254
Definition: pg_list.h:45
List* get_partitioned_child_rels_for_join ( PlannerInfo root,
Relids  join_relids 
)

Definition at line 6160 of file planner.c.

References bms_is_member(), PartitionedChildRelInfo::child_rels, lfirst, list_concat(), list_copy(), NIL, PartitionedChildRelInfo::parent_relid, and PlannerInfo::pcinfo_list.

Referenced by add_paths_to_append_rel().

6161 {
6162  List *result = NIL;
6163  ListCell *l;
6164 
6165  foreach(l, root->pcinfo_list)
6166  {
6168 
6169  if (bms_is_member(pc->parent_relid, join_relids))
6170  result = list_concat(result, list_copy(pc->child_rels));
6171  }
6172 
6173  return result;
6174 }
#define NIL
Definition: pg_list.h:69
List * list_copy(const List *oldlist)
Definition: list.c:1160
List * list_concat(List *list1, List *list2)
Definition: list.c:321
#define lfirst(lc)
Definition: pg_list.h:106
List * pcinfo_list
Definition: relation.h:254
Definition: pg_list.h:45
bool bms_is_member(int x, const Bitmapset *a)
Definition: bitmapset.c:420
bool is_dummy_plan ( Plan plan)

Definition at line 2358 of file planner.c.

References Const::constisnull, Const::constvalue, DatumGetBool, IsA, linitial, and list_length().

2359 {
2360  if (IsA(plan, Result))
2361  {
2362  List *rcqual = (List *) ((Result *) plan)->resconstantqual;
2363 
2364  if (list_length(rcqual) == 1)
2365  {
2366  Const *constqual = (Const *) linitial(rcqual);
2367 
2368  if (constqual && IsA(constqual, Const))
2369  {
2370  if (!constqual->constisnull &&
2371  !DatumGetBool(constqual->constvalue))
2372  return true;
2373  }
2374  }
2375  }
2376  return false;
2377 }
Datum constvalue
Definition: primnodes.h:196
#define IsA(nodeptr, _type_)
Definition: nodes.h:561
#define linitial(l)
Definition: pg_list.h:111
#define DatumGetBool(X)
Definition: postgres.h:399
static int list_length(const List *l)
Definition: pg_list.h:89
Definition: pg_list.h:45
bool constisnull
Definition: primnodes.h:197
void mark_partial_aggref ( Aggref agg,
AggSplit  aggsplit 
)

Definition at line 5293 of file planner.c.

References Aggref::aggsplit, AGGSPLIT_SIMPLE, Aggref::aggtranstype, Aggref::aggtype, Assert, BYTEAOID, DO_AGGSPLIT_SERIALIZE, DO_AGGSPLIT_SKIPFINAL, INTERNALOID, and OidIsValid.

Referenced by convert_combining_aggrefs(), and make_partial_grouping_target().

5294 {
5295  /* aggtranstype should be computed by this point */
5297  /* ... but aggsplit should still be as the parser left it */
5298  Assert(agg->aggsplit == AGGSPLIT_SIMPLE);
5299 
5300  /* Mark the Aggref with the intended partial-aggregation mode */
5301  agg->aggsplit = aggsplit;
5302 
5303  /*
5304  * Adjust result type if needed. Normally, a partial aggregate returns
5305  * the aggregate's transition type; but if that's INTERNAL and we're
5306  * serializing, it returns BYTEA instead.
5307  */
5308  if (DO_AGGSPLIT_SKIPFINAL(aggsplit))
5309  {
5310  if (agg->aggtranstype == INTERNALOID && DO_AGGSPLIT_SERIALIZE(aggsplit))
5311  agg->aggtype = BYTEAOID;
5312  else
5313  agg->aggtype = agg->aggtranstype;
5314  }
5315 }
#define OidIsValid(objectId)
Definition: c.h:532
#define DO_AGGSPLIT_SERIALIZE(as)
Definition: nodes.h:771
#define INTERNALOID
Definition: pg_type.h:698
#define Assert(condition)
Definition: c.h:681
AggSplit aggsplit
Definition: primnodes.h:310
#define DO_AGGSPLIT_SKIPFINAL(as)
Definition: nodes.h:770
#define BYTEAOID
Definition: pg_type.h:292
Oid aggtranstype
Definition: primnodes.h:298
Oid aggtype
Definition: primnodes.h:295
bool plan_cluster_use_sort ( Oid  tableOid,
Oid  indexOid 
)

Definition at line 6026 of file planner.c.

References build_simple_rel(), CMD_SELECT, Query::commandType, cost_qual_eval(), cost_sort(), create_index_path(), create_seqscan_path(), CurrentMemoryContext, enable_indexscan, ForwardScanDirection, get_relation_data_width(), PlannerInfo::glob, RelOptInfo::indexlist, IndexOptInfo::indexoid, IndexOptInfo::indexprs, RangeTblEntry::inFromCl, RangeTblEntry::inh, RangeTblEntry::lateral, lfirst_node, list_make1, maintenance_work_mem, makeNode, NIL, RelOptInfo::pages, PlannerInfo::parse, IndexPath::path, QualCost::per_tuple, PlannerInfo::planner_cxt, PlannerInfo::query_level, RangeTblEntry::relid, RangeTblEntry::relkind, RELKIND_RELATION, RelOptInfo::reltarget, RelOptInfo::rows, Query::rtable, RTE_RELATION, RangeTblEntry::rtekind, setup_simple_rel_arrays(), QualCost::startup, Path::total_cost, PlannerInfo::total_table_pages, RelOptInfo::tuples, PathTarget::width, and PlannerInfo::wt_param_id.

Referenced by copy_heap_data().

6027 {
6028  PlannerInfo *root;
6029  Query *query;
6030  PlannerGlobal *glob;
6031  RangeTblEntry *rte;
6032  RelOptInfo *rel;
6033  IndexOptInfo *indexInfo;
6034  QualCost indexExprCost;
6035  Cost comparisonCost;
6036  Path *seqScanPath;
6037  Path seqScanAndSortPath;
6038  IndexPath *indexScanPath;
6039  ListCell *lc;
6040 
6041  /* We can short-circuit the cost comparison if indexscans are disabled */
6042  if (!enable_indexscan)
6043  return true; /* use sort */
6044 
6045  /* Set up mostly-dummy planner state */
6046  query = makeNode(Query);
6047  query->commandType = CMD_SELECT;
6048 
6049  glob = makeNode(PlannerGlobal);
6050 
6051  root = makeNode(PlannerInfo);
6052  root->parse = query;
6053  root->glob = glob;
6054  root->query_level = 1;
6056  root->wt_param_id = -1;
6057 
6058  /* Build a minimal RTE for the rel */
6059  rte = makeNode(RangeTblEntry);
6060  rte->rtekind = RTE_RELATION;
6061  rte->relid = tableOid;
6062  rte->relkind = RELKIND_RELATION; /* Don't be too picky. */
6063  rte->lateral = false;
6064  rte->inh = false;
6065  rte->inFromCl = true;
6066  query->rtable = list_make1(rte);
6067 
6068  /* Set up RTE/RelOptInfo arrays */
6070 
6071  /* Build RelOptInfo */
6072  rel = build_simple_rel(root, 1, NULL);
6073 
6074  /* Locate IndexOptInfo for the target index */
6075  indexInfo = NULL;
6076  foreach(lc, rel->indexlist)
6077  {
6078  indexInfo = lfirst_node(IndexOptInfo, lc);
6079  if (indexInfo->indexoid == indexOid)
6080  break;
6081  }
6082 
6083  /*
6084  * It's possible that get_relation_info did not generate an IndexOptInfo
6085  * for the desired index; this could happen if it's not yet reached its
6086  * indcheckxmin usability horizon, or if it's a system index and we're
6087  * ignoring system indexes. In such cases we should tell CLUSTER to not
6088  * trust the index contents but use seqscan-and-sort.
6089  */
6090  if (lc == NULL) /* not in the list? */
6091  return true; /* use sort */
6092 
6093  /*
6094  * Rather than doing all the pushups that would be needed to use
6095  * set_baserel_size_estimates, just do a quick hack for rows and width.
6096  */
6097  rel->rows = rel->tuples;
6098  rel->reltarget->width = get_relation_data_width(tableOid, NULL);
6099 
6100  root->total_table_pages = rel->pages;
6101 
6102  /*
6103  * Determine eval cost of the index expressions, if any. We need to
6104  * charge twice that amount for each tuple comparison that happens during
6105  * the sort, since tuplesort.c will have to re-evaluate the index
6106  * expressions each time. (XXX that's pretty inefficient...)
6107  */
6108  cost_qual_eval(&indexExprCost, indexInfo->indexprs, root);
6109  comparisonCost = 2.0 * (indexExprCost.startup + indexExprCost.per_tuple);
6110 
6111  /* Estimate the cost of seq scan + sort */
6112  seqScanPath = create_seqscan_path(root, rel, NULL, 0);
6113  cost_sort(&seqScanAndSortPath, root, NIL,
6114  seqScanPath->total_cost, rel->tuples, rel->reltarget->width,
6115  comparisonCost, maintenance_work_mem, -1.0);
6116 
6117  /* Estimate the cost of index scan */
6118  indexScanPath = create_index_path(root, indexInfo,
6119  NIL, NIL, NIL, NIL, NIL,
6120  ForwardScanDirection, false,
6121  NULL, 1.0, false);
6122 
6123  return (seqScanAndSortPath.total_cost < indexScanPath->path.total_cost);
6124 }
#define NIL
Definition: pg_list.h:69
Query * parse
Definition: relation.h:155
Path path
Definition: relation.h:1118
double tuples
Definition: relation.h:625
IndexPath * create_index_path(PlannerInfo *root, IndexOptInfo *index, List *indexclauses, List *indexclausecols, List *indexorderbys, List *indexorderbycols, List *pathkeys, ScanDirection indexscandir, bool indexonly, Relids required_outer, double loop_count, bool partial_path)
Definition: pathnode.c:1016
Cost startup
Definition: relation.h:45
#define list_make1(x1)
Definition: pg_list.h:139
Cost per_tuple
Definition: relation.h:46
int wt_param_id
Definition: relation.h:311
List * rtable
Definition: parsenodes.h:135
void cost_qual_eval(QualCost *cost, List *quals, PlannerInfo *root)
Definition: costsize.c:3464
#define lfirst_node(type, lc)
Definition: pg_list.h:109
PlannerGlobal * glob
Definition: relation.h:157
RelOptInfo * build_simple_rel(PlannerInfo *root, int relid, RelOptInfo *parent)
Definition: relnode.c:96
MemoryContext CurrentMemoryContext
Definition: mcxt.c:37
double total_table_pages
Definition: relation.h:292
int32 get_relation_data_width(Oid relid, int32 *attr_widths)
Definition: plancat.c:1122
void cost_sort(Path *path, PlannerInfo *root, List *pathkeys, Cost input_cost, double tuples, int width, Cost comparison_cost, int sort_mem, double limit_tuples)
Definition: costsize.c:1645
List * indexlist
Definition: relation.h:622
double rows
Definition: relation.h:588
int maintenance_work_mem
Definition: globals.c:114
Cost total_cost
Definition: relation.h:1054
CmdType commandType
Definition: parsenodes.h:110
#define makeNode(_type_)
Definition: nodes.h:558
BlockNumber pages
Definition: relation.h:624
void setup_simple_rel_arrays(PlannerInfo *root)
Definition: relnode.c:67
Index query_level
Definition: relation.h:159
RTEKind rtekind
Definition: parsenodes.h:945
int width
Definition: relation.h:975
MemoryContext planner_cxt
Definition: relation.h:290
Oid indexoid
Definition: relation.h:719
#define RELKIND_RELATION
Definition: pg_class.h:160
struct PathTarget * reltarget
Definition: relation.h:596
bool enable_indexscan
Definition: costsize.c:119
Path * create_seqscan_path(PlannerInfo *root, RelOptInfo *rel, Relids required_outer, int parallel_workers)
Definition: pathnode.c:946
double Cost
Definition: nodes.h:641
List * indexprs
Definition: relation.h:741
PlannedStmt* planner ( Query parse,
int  cursorOptions,
ParamListInfo  boundParams 
)

Definition at line 203 of file planner.c.

References parse(), planner_hook, and standard_planner().

Referenced by pg_plan_query().

204 {
205  PlannedStmt *result;
206 
207  if (planner_hook)
208  result = (*planner_hook) (parse, cursorOptions, boundParams);
209  else
210  result = standard_planner(parse, cursorOptions, boundParams);
211  return result;
212 }
PlannedStmt * standard_planner(Query *parse, int cursorOptions, ParamListInfo boundParams)
Definition: planner.c:215
planner_hook_type planner_hook
Definition: planner.c:66
static struct subre * parse(struct vars *, int, int, struct state *, struct state *)
Definition: regcomp.c:649
Expr* preprocess_phv_expression ( PlannerInfo root,
Expr expr 
)

Definition at line 1023 of file planner.c.

References EXPRKIND_PHV, and preprocess_expression().

Referenced by extract_lateral_references().

1024 {
1025  return (Expr *) preprocess_expression(root, (Node *) expr, EXPRKIND_PHV);
1026 }
Definition: nodes.h:510
static Node * preprocess_expression(PlannerInfo *root, Node *expr, int kind)
Definition: planner.c:893
#define EXPRKIND_PHV
Definition: planner.c:81
RowMarkType select_rowmark_type ( RangeTblEntry rte,
LockClauseStrength  strength 
)

Definition at line 2494 of file planner.c.

References elog, ERROR, GetFdwRoutineByRelId(), FdwRoutine::GetForeignRowMarkType, LCS_FORKEYSHARE, LCS_FORNOKEYUPDATE, LCS_FORSHARE, LCS_FORUPDATE, LCS_NONE, RangeTblEntry::relid, RangeTblEntry::relkind, RELKIND_FOREIGN_TABLE, ROW_MARK_COPY, ROW_MARK_EXCLUSIVE, ROW_MARK_KEYSHARE, ROW_MARK_NOKEYEXCLUSIVE, ROW_MARK_REFERENCE, ROW_MARK_SHARE, RTE_RELATION, and RangeTblEntry::rtekind.

Referenced by expand_single_inheritance_child(), and preprocess_rowmarks().

2495 {
2496  if (rte->rtekind != RTE_RELATION)
2497  {
2498  /* If it's not a table at all, use ROW_MARK_COPY */
2499  return ROW_MARK_COPY;
2500  }
2501  else if (rte->relkind == RELKIND_FOREIGN_TABLE)
2502  {
2503  /* Let the FDW select the rowmark type, if it wants to */
2504  FdwRoutine *fdwroutine = GetFdwRoutineByRelId(rte->relid);
2505 
2506  if (fdwroutine->GetForeignRowMarkType != NULL)
2507  return fdwroutine->GetForeignRowMarkType(rte, strength);
2508  /* Otherwise, use ROW_MARK_COPY by default */
2509  return ROW_MARK_COPY;
2510  }
2511  else
2512  {
2513  /* Regular table, apply the appropriate lock type */
2514  switch (strength)
2515  {
2516  case LCS_NONE:
2517 
2518  /*
2519  * We don't need a tuple lock, only the ability to re-fetch
2520  * the row.
2521  */
2522  return ROW_MARK_REFERENCE;
2523  break;
2524  case LCS_FORKEYSHARE:
2525  return ROW_MARK_KEYSHARE;
2526  break;
2527  case LCS_FORSHARE:
2528  return ROW_MARK_SHARE;
2529  break;
2530  case LCS_FORNOKEYUPDATE:
2531  return ROW_MARK_NOKEYEXCLUSIVE;
2532  break;
2533  case LCS_FORUPDATE:
2534  return ROW_MARK_EXCLUSIVE;
2535  break;
2536  }
2537  elog(ERROR, "unrecognized LockClauseStrength %d", (int) strength);
2538  return ROW_MARK_EXCLUSIVE; /* keep compiler quiet */
2539  }
2540 }
#define ERROR
Definition: elog.h:43
#define RELKIND_FOREIGN_TABLE
Definition: pg_class.h:167
FdwRoutine * GetFdwRoutineByRelId(Oid relid)
Definition: foreign.c:372
GetForeignRowMarkType_function GetForeignRowMarkType
Definition: fdwapi.h:214
RTEKind rtekind
Definition: parsenodes.h:945
#define elog
Definition: elog.h:219
PlannedStmt* standard_planner ( Query parse,
int  cursorOptions,
ParamListInfo  boundParams 
)

Definition at line 215 of file planner.c.

References Assert, PlannerGlobal::boundParams, PlannedStmt::canSetTag, Query::canSetTag, CMD_SELECT, PlannedStmt::commandType, Query::commandType, create_plan(), CURSOR_OPT_FAST_PLAN, CURSOR_OPT_PARALLEL_OK, CURSOR_OPT_SCROLL, cursor_tuple_fraction, PlannedStmt::dependsOnRole, PlannerGlobal::dependsOnRole, DSM_IMPL_NONE, dynamic_shared_memory_type, ExecSupportsBackwardScan(), fetch_upper_rel(), PlannerGlobal::finalrowmarks, PlannerGlobal::finalrtable, forboth, force_parallel_mode, FORCE_PARALLEL_OFF, FORCE_PARALLEL_REGRESS, get_cheapest_fractional_path(), PlannerInfo::glob, PlannedStmt::hasModifyingCTE, Query::hasModifyingCTE, PlannedStmt::hasReturning, PlannedStmt::invalItems, PlannerGlobal::invalItems, Gather::invisible, IsolationIsSerializable, IsParallelWorker, IsUnderPostmaster, PlannerGlobal::lastPHId, PlannerGlobal::lastPlanNodeId, PlannerGlobal::lastRowMarkId, Plan::lefttree, lfirst, lfirst_node, list_length(), makeNode, materialize_finished_plan(), max_parallel_hazard(), max_parallel_workers_per_gather, PlannerGlobal::maxParallelHazard, NIL, PlannedStmt::nonleafResultRelations, PlannerGlobal::nonleafResultRelations, PlannedStmt::nParamExec, PlannerGlobal::nParamExec, Gather::num_workers, Plan::parallel_aware, Plan::parallel_safe, parallel_setup_cost, parallel_tuple_cost, PlannedStmt::parallelModeNeeded, PlannerGlobal::parallelModeNeeded, PlannerGlobal::parallelModeOK, Gather::plan, Plan::plan_rows, Plan::plan_width, PlannedStmt::planTree, PROPARALLEL_UNSAFE, Plan::qual, PlannedStmt::queryId, Query::queryId, PlannedStmt::relationOids, PlannerGlobal::relationOids, Gather::rescan_param, PlannedStmt::resultRelations, PlannerGlobal::resultRelations, Query::returningList, PlannedStmt::rewindPlanIDs, PlannerGlobal::rewindPlanIDs, Plan::righttree, PlannedStmt::rootResultRelations, PlannerGlobal::rootResultRelations, PlannedStmt::rowMarks, PlannedStmt::rtable, set_plan_references(), Gather::single_copy, SS_finalize_plan(), Plan::startup_cost, PlannedStmt::stmt_len, Query::stmt_len, PlannedStmt::stmt_location, Query::stmt_location, PlannedStmt::subplans, PlannerGlobal::subplans, subquery_planner(), PlannerGlobal::subroots, Plan::targetlist, Plan::total_cost, PlannedStmt::transientPlan, PlannerGlobal::transientPlan, UPPERREL_FINAL, PlannedStmt::utilityStmt, and Query::utilityStmt.

Referenced by planner().

216 {
217  PlannedStmt *result;
218  PlannerGlobal *glob;
219  double tuple_fraction;
220  PlannerInfo *root;
221  RelOptInfo *final_rel;
222  Path *best_path;
223  Plan *top_plan;
224  ListCell *lp,
225  *lr;
226 
227  /*
228  * Set up global state for this planner invocation. This data is needed
229  * across all levels of sub-Query that might exist in the given command,
230  * so we keep it in a separate struct that's linked to by each per-Query
231  * PlannerInfo.
232  */
233  glob = makeNode(PlannerGlobal);
234 
235  glob->boundParams = boundParams;
236  glob->subplans = NIL;
237  glob->subroots = NIL;
238  glob->rewindPlanIDs = NULL;
239  glob->finalrtable = NIL;
240  glob->finalrowmarks = NIL;
241  glob->resultRelations = NIL;
242  glob->nonleafResultRelations = NIL;
243  glob->rootResultRelations = NIL;
244  glob->relationOids = NIL;
245  glob->invalItems = NIL;
246  glob->nParamExec = 0;
247  glob->lastPHId = 0;
248  glob->lastRowMarkId = 0;
249  glob->lastPlanNodeId = 0;
250  glob->transientPlan = false;
251  glob->dependsOnRole = false;
252 
253  /*
254  * Assess whether it's feasible to use parallel mode for this query. We
255  * can't do this in a standalone backend, or if the command will try to
256  * modify any data, or if this is a cursor operation, or if GUCs are set
257  * to values that don't permit parallelism, or if parallel-unsafe
258  * functions are present in the query tree.
259  *
260  * (Note that we do allow CREATE TABLE AS, SELECT INTO, and CREATE
261  * MATERIALIZED VIEW to use parallel plans, but this is safe only because
262  * the command is writing into a completely new table which workers won't
263  * be able to see. If the workers could see the table, the fact that
264  * group locking would cause them to ignore the leader's heavyweight
265  * relation extension lock and GIN page locks would make this unsafe.
266  * We'll have to fix that somehow if we want to allow parallel inserts in
267  * general; updates and deletes have additional problems especially around
268  * combo CIDs.)
269  *
270  * For now, we don't try to use parallel mode if we're running inside a
271  * parallel worker. We might eventually be able to relax this
272  * restriction, but for now it seems best not to have parallel workers
273  * trying to create their own parallel workers.
274  *
275  * We can't use parallelism in serializable mode because the predicate
276  * locking code is not parallel-aware. It's not catastrophic if someone
277  * tries to run a parallel plan in serializable mode; it just won't get
278  * any workers and will run serially. But it seems like a good heuristic
279  * to assume that the same serialization level will be in effect at plan
280  * time and execution time, so don't generate a parallel plan if we're in
281  * serializable mode.
282  */
283  if ((cursorOptions & CURSOR_OPT_PARALLEL_OK) != 0 &&
286  parse->commandType == CMD_SELECT &&
287  !parse->hasModifyingCTE &&
289  !IsParallelWorker() &&
291  {
292  /* all the cheap tests pass, so scan the query tree */
293  glob->maxParallelHazard = max_parallel_hazard(parse);
295  }
296  else
297  {
298  /* skip the query tree scan, just assume it's unsafe */
300  glob->parallelModeOK = false;
301  }
302 
303  /*
304  * glob->parallelModeNeeded is normally set to false here and changed to
305  * true during plan creation if a Gather or Gather Merge plan is actually
306  * created (cf. create_gather_plan, create_gather_merge_plan).
307  *
308  * However, if force_parallel_mode = on or force_parallel_mode = regress,
309  * then we impose parallel mode whenever it's safe to do so, even if the
310  * final plan doesn't use parallelism. It's not safe to do so if the
311  * query contains anything parallel-unsafe; parallelModeOK will be false
312  * in that case. Note that parallelModeOK can't change after this point.
313  * Otherwise, everything in the query is either parallel-safe or
314  * parallel-restricted, and in either case it should be OK to impose
315  * parallel-mode restrictions. If that ends up breaking something, then
316  * either some function the user included in the query is incorrectly
317  * labelled as parallel-safe or parallel-restricted when in reality it's
318  * parallel-unsafe, or else the query planner itself has a bug.
319  */
320  glob->parallelModeNeeded = glob->parallelModeOK &&
322 
323  /* Determine what fraction of the plan is likely to be scanned */
324  if (cursorOptions & CURSOR_OPT_FAST_PLAN)
325  {
326  /*
327  * We have no real idea how many tuples the user will ultimately FETCH
328  * from a cursor, but it is often the case that he doesn't want 'em
329  * all, or would prefer a fast-start plan anyway so that he can
330  * process some of the tuples sooner. Use a GUC parameter to decide
331  * what fraction to optimize for.
332  */
333  tuple_fraction = cursor_tuple_fraction;
334 
335  /*
336  * We document cursor_tuple_fraction as simply being a fraction, which
337  * means the edge cases 0 and 1 have to be treated specially here. We
338  * convert 1 to 0 ("all the tuples") and 0 to a very small fraction.
339  */
340  if (tuple_fraction >= 1.0)
341  tuple_fraction = 0.0;
342  else if (tuple_fraction <= 0.0)
343  tuple_fraction = 1e-10;
344  }
345  else
346  {
347  /* Default assumption is we need all the tuples */
348  tuple_fraction = 0.0;
349  }
350 
351  /* primary planning entry point (may recurse for subqueries) */
352  root = subquery_planner(glob, parse, NULL,
353  false, tuple_fraction);
354 
355  /* Select best Path and turn it into a Plan */
356  final_rel = fetch_upper_rel(root, UPPERREL_FINAL, NULL);
357  best_path = get_cheapest_fractional_path(final_rel, tuple_fraction);
358 
359  top_plan = create_plan(root, best_path);
360 
361  /*
362  * If creating a plan for a scrollable cursor, make sure it can run
363  * backwards on demand. Add a Material node at the top at need.
364  */
365  if (cursorOptions & CURSOR_OPT_SCROLL)
366  {
367  if (!ExecSupportsBackwardScan(top_plan))
368  top_plan = materialize_finished_plan(top_plan);
369  }
370 
371  /*
372  * Optionally add a Gather node for testing purposes, provided this is
373  * actually a safe thing to do.
374  */
376  {
377  Gather *gather = makeNode(Gather);
378 
379  gather->plan.targetlist = top_plan->targetlist;
380  gather->plan.qual = NIL;
381  gather->plan.lefttree = top_plan;
382  gather->plan.righttree = NULL;
383  gather->num_workers = 1;
384  gather->single_copy = true;
386 
387  /*
388  * Since this Gather has no parallel-aware descendants to signal to,
389  * we don't need a rescan Param.
390  */
391  gather->rescan_param = -1;
392 
393  /*
394  * Ideally we'd use cost_gather here, but setting up dummy path data
395  * to satisfy it doesn't seem much cleaner than knowing what it does.
396  */
397  gather->plan.startup_cost = top_plan->startup_cost +
399  gather->plan.total_cost = top_plan->total_cost +
401  gather->plan.plan_rows = top_plan->plan_rows;
402  gather->plan.plan_width = top_plan->plan_width;
403  gather->plan.parallel_aware = false;
404  gather->plan.parallel_safe = false;
405 
406  /* use parallel mode for parallel plans. */
407  root->glob->parallelModeNeeded = true;
408 
409  top_plan = &gather->plan;
410  }
411 
412  /*
413  * If any Params were generated, run through the plan tree and compute
414  * each plan node's extParam/allParam sets. Ideally we'd merge this into
415  * set_plan_references' tree traversal, but for now it has to be separate
416  * because we need to visit subplans before not after main plan.
417  */
418  if (glob->nParamExec > 0)
419  {
420  Assert(list_length(glob->subplans) == list_length(glob->subroots));
421  forboth(lp, glob->subplans, lr, glob->subroots)
422  {
423  Plan *subplan = (Plan *) lfirst(lp);
424  PlannerInfo *subroot = lfirst_node(PlannerInfo, lr);
425 
426  SS_finalize_plan(subroot, subplan);
427  }
428  SS_finalize_plan(root, top_plan);
429  }
430 
431  /* final cleanup of the plan */
432  Assert(glob->finalrtable == NIL);
433  Assert(glob->finalrowmarks == NIL);
434  Assert(glob->resultRelations == NIL);
436  Assert(glob->rootResultRelations == NIL);
437  top_plan = set_plan_references(root, top_plan);
438  /* ... and the subplans (both regular subplans and initplans) */
439  Assert(list_length(glob->subplans) == list_length(glob->subroots));
440  forboth(lp, glob->subplans, lr, glob->subroots)
441  {
442  Plan *subplan = (Plan *) lfirst(lp);
443  PlannerInfo *subroot = lfirst_node(PlannerInfo, lr);
444 
445  lfirst(lp) = set_plan_references(subroot, subplan);
446  }
447 
448  /* build the PlannedStmt result */
449  result = makeNode(PlannedStmt);
450 
451  result->commandType = parse->commandType;
452  result->queryId = parse->queryId;
453  result->hasReturning = (parse->returningList != NIL);
454  result->hasModifyingCTE = parse->hasModifyingCTE;
455  result->canSetTag = parse->canSetTag;
456  result->transientPlan = glob->transientPlan;
457  result->dependsOnRole = glob->dependsOnRole;
458  result->parallelModeNeeded = glob->parallelModeNeeded;
459  result->planTree = top_plan;
460  result->rtable = glob->finalrtable;
461  result->resultRelations = glob->resultRelations;
464  result->subplans = glob->subplans;
465  result->rewindPlanIDs = glob->rewindPlanIDs;
466  result->rowMarks = glob->finalrowmarks;
467  result->relationOids = glob->relationOids;
468  result->invalItems = glob->invalItems;
469  result->nParamExec = glob->nParamExec;
470  /* utilityStmt should be null, but we might as well copy it */
471  result->utilityStmt = parse->utilityStmt;
472  result->stmt_location = parse->stmt_location;
473  result->stmt_len = parse->stmt_len;
474 
475  return result;
476 }
char maxParallelHazard
Definition: relation.h:133
bool dependsOnRole
Definition: plannodes.h:57
#define NIL
Definition: pg_list.h:69
List * qual
Definition: plannodes.h:145
double plan_rows
Definition: plannodes.h:131
#define forboth(cell1, list1, cell2, list2)
Definition: pg_list.h:180
int stmt_location
Definition: parsenodes.h:179
List * nonleafResultRelations
Definition: plannodes.h:72
List * relationOids
Definition: plannodes.h:88
int lastPlanNodeId
Definition: relation.h:123
List * resultRelations
Definition: relation.h:108
double parallel_setup_cost
Definition: costsize.c:110
Node * utilityStmt
Definition: parsenodes.h:118
bool transientPlan
Definition: plannodes.h:55
int stmt_len
Definition: plannodes.h:98
char max_parallel_hazard(Query *parse)
Definition: clauses.c:1068
struct Plan * planTree
Definition: plannodes.h:61
List * invalItems
Definition: plannodes.h:90
List * rootResultRelations
Definition: relation.h:111
Plan * create_plan(PlannerInfo *root, Path *best_path)
Definition: createplan.c:304
bool dependsOnRole
Definition: relation.h:127
int nParamExec
Definition: plannodes.h:92
struct Plan * righttree
Definition: plannodes.h:147
bool parallelModeNeeded
Definition: relation.h:131
Plan plan
Definition: plannodes.h:839
bool single_copy
Definition: plannodes.h:842
bool parallelModeOK
Definition: relation.h:129
Bitmapset * rewindPlanIDs
Definition: relation.h:102
RelOptInfo * fetch_upper_rel(PlannerInfo *root, UpperRelationKind kind, Relids relids)
Definition: relnode.c:1138
#define lfirst_node(type, lc)
Definition: pg_list.h:109
int stmt_location
Definition: plannodes.h:97
List * subplans
Definition: relation.h:98
Cost startup_cost
Definition: plannodes.h:125
PlannerGlobal * glob
Definition: relation.h:157
bool IsUnderPostmaster
Definition: globals.c:101
bool hasReturning
Definition: plannodes.h:49
Plan * materialize_finished_plan(Plan *subplan)
Definition: createplan.c:5984
List * rootResultRelations
Definition: plannodes.h:79
Node * utilityStmt
Definition: plannodes.h:94
int dynamic_shared_memory_type
Definition: dsm_impl.c:113
bool parallel_aware
Definition: plannodes.h:137
double cursor_tuple_fraction
Definition: planner.c:62
List * returningList
Definition: parsenodes.h:144
#define IsParallelWorker()
Definition: parallel.h:52
#define PROPARALLEL_UNSAFE
Definition: pg_proc.h:5544
uint64 queryId
Definition: parsenodes.h:114
List * invalItems
Definition: relation.h:115
bool canSetTag
Definition: plannodes.h:53
CmdType commandType
Definition: plannodes.h:45
#define CURSOR_OPT_FAST_PLAN
Definition: parsenodes.h:2636
bool ExecSupportsBackwardScan(Plan *node)
Definition: execAmi.c:462
Index lastPHId
Definition: relation.h:119
List * rowMarks
Definition: plannodes.h:86
int num_workers
Definition: plannodes.h:840
CmdType commandType
Definition: parsenodes.h:110
#define makeNode(_type_)
Definition: nodes.h:558
List * subplans
Definition: plannodes.h:81
List * nonleafResultRelations
Definition: relation.h:110
int plan_width
Definition: plannodes.h:132
int force_parallel_mode
Definition: planner.c:63
ParamListInfo boundParams
Definition: relation.h:96
#define Assert(condition)
Definition: c.h:681
#define lfirst(lc)
Definition: pg_list.h:106
Bitmapset * rewindPlanIDs
Definition: plannodes.h:84
bool hasModifyingCTE
Definition: plannodes.h:51
bool canSetTag
Definition: parsenodes.h:116
#define DSM_IMPL_NONE
Definition: dsm_impl.h:17
int rescan_param
Definition: plannodes.h:841
static int list_length(const List *l)
Definition: pg_list.h:89
List * relationOids
Definition: relation.h:113
List * subroots
Definition: relation.h:100
List * rtable
Definition: plannodes.h:63
struct Plan * lefttree
Definition: plannodes.h:146
List * targetlist
Definition: plannodes.h:144
bool invisible
Definition: plannodes.h:843
e
Definition: preproc-init.c:82
List * finalrtable
Definition: relation.h:104
#define CURSOR_OPT_PARALLEL_OK
Definition: parsenodes.h:2639
Index lastRowMarkId
Definition: relation.h:121
uint64 queryId
Definition: plannodes.h:47
#define IsolationIsSerializable()
Definition: xact.h:44
List * resultRelations
Definition: plannodes.h:66
bool parallelModeNeeded
Definition: plannodes.h:59
#define CURSOR_OPT_SCROLL
Definition: parsenodes.h:2631
Cost total_cost
Definition: plannodes.h:126
int nParamExec
Definition: relation.h:117
bool hasModifyingCTE
Definition: parsenodes.h:129
bool parallel_safe
Definition: plannodes.h:138
Plan * set_plan_references(PlannerInfo *root, Plan *plan)
Definition: setrefs.c:213
void SS_finalize_plan(PlannerInfo *root, Plan *plan)
Definition: subselect.c:2218
int max_parallel_workers_per_gather
Definition: costsize.c:116
List * finalrowmarks
Definition: relation.h:106
int stmt_len
Definition: parsenodes.h:180
PlannerInfo * subquery_planner(PlannerGlobal *glob, Query *parse, PlannerInfo *parent_root, bool hasRecursion, double tuple_fraction)
Definition: planner.c:508
Path * get_cheapest_fractional_path(RelOptInfo *rel, double tuple_fraction)
Definition: planner.c:5844
bool transientPlan
Definition: relation.h:125
double parallel_tuple_cost
Definition: costsize.c:109
PlannerInfo* subquery_planner ( PlannerGlobal glob,
Query parse,
PlannerInfo parent_root,
bool  hasRecursion,
double  tuple_fraction 
)

Definition at line 508 of file planner.c.

References PlannerInfo::append_rel_list, OnConflictExpr::arbiterElems, OnConflictExpr::arbiterWhere, contain_agg_clause(), contain_subplans(), contain_volatile_functions(), copyObject, PlannerInfo::cte_plan_ids, Query::cteList, CurrentMemoryContext, WindowClause::endOffset, PlannerInfo::eq_classes, expand_inherited_tables(), expression_returns_set(), EXPRKIND_APPINFO, EXPRKIND_ARBITER_ELEM, EXPRKIND_LIMIT, EXPRKIND_QUAL, EXPRKIND_RTFUNC, EXPRKIND_RTFUNC_LATERAL, EXPRKIND_TABLEFUNC, EXPRKIND_TABLEFUNC_LATERAL, EXPRKIND_TABLESAMPLE, EXPRKIND_TARGET, EXPRKIND_VALUES, EXPRKIND_VALUES_LATERAL, fetch_upper_rel(), flatten_join_alias_vars(), flatten_simple_union_all(), RangeTblEntry::functions, PlannerInfo::glob, Query::groupClause, PlannerInfo::grouping_map, grouping_planner(), Query::groupingSets, PlannerInfo::hasHavingQual, PlannerInfo::hasInheritedTarget, PlannerInfo::hasJoinRTEs, PlannerInfo::hasLateralRTEs, PlannerInfo::hasPseudoConstantQuals, PlannerInfo::hasRecursion, Query::hasSubLinks, Query::hasTargetSRFs, Query::havingQual, inheritance_planner(), PlannerInfo::init_plans, inline_set_returning_functions(), IS_OUTER_JOIN, Query::jointree, RangeTblEntry::jointype, lappend(), RangeTblEntry::lateral, lfirst, lfirst_node, Query::limitCount, Query::limitOffset, makeNode, PlannerInfo::minmax_aggs, PlannerInfo::multiexpr_params, NIL, PlannerInfo::non_recursive_path, Query::onConflict, OnConflictExpr::onConflictSet, OnConflictExpr::onConflictWhere, PlannerInfo::outer_params, PlannerInfo::parent_root, parse(), PlannerInfo::parse, PlannerInfo::pcinfo_list, PlannerInfo::plan_params, PlannerInfo::planner_cxt, preprocess_expression(), preprocess_qual_conditions(), preprocess_rowmarks(), PlannerInfo::processed_tlist, pull_up_sublinks(), pull_up_subqueries(), WithCheckOption::qual, PlannerInfo::qual_security_level, FromExpr::quals, PlannerInfo::query_level, reduce_outer_joins(), remove_useless_groupby_columns(), Query::resultRelation, Query::returningList, PlannerInfo::rowMarks, rt_fetch, Query::rtable, RTE_FUNCTION, RTE_JOIN, RTE_RELATION, RTE_SUBQUERY, RTE_TABLEFUNC, RTE_VALUES, RangeTblEntry::rtekind, RangeTblEntry::securityQuals, set_cheapest(), Query::setOperations, SS_assign_special_param(), SS_charge_for_initplans(), SS_identify_outer_params(), SS_process_ctes(), WindowClause::startOffset, RangeTblEntry::subquery, RangeTblEntry::tablefunc, RangeTblEntry::tablesample, Query::targetList, PlannerInfo::upper_rels, PlannerInfo::upper_targets, UPPERREL_FINAL, RangeTblEntry::values_lists, Query::windowClause, Query::withCheckOptions, and PlannerInfo::wt_param_id.

Referenced by make_subplan(), recurse_set_operations(), set_subquery_pathlist(), SS_process_ctes(), and standard_planner().

511 {
512  PlannerInfo *root;
513  List *newWithCheckOptions;
514  List *newHaving;
515  bool hasOuterJoins;
516  RelOptInfo *final_rel;
517  ListCell *l;
518 
519  /* Create a PlannerInfo data structure for this subquery */
520  root = makeNode(PlannerInfo);
521  root->parse = parse;
522  root->glob = glob;
523  root->query_level = parent_root ? parent_root->query_level + 1 : 1;
524  root->parent_root = parent_root;
525  root->plan_params = NIL;
526  root->outer_params = NULL;
528  root->init_plans = NIL;
529  root->cte_plan_ids = NIL;
530  root->multiexpr_params = NIL;
531  root->eq_classes = NIL;
532  root->append_rel_list = NIL;
533  root->pcinfo_list = NIL;
534  root->rowMarks = NIL;
535  memset(root->upper_rels, 0, sizeof(root->upper_rels));
536  memset(root->upper_targets, 0, sizeof(root->upper_targets));
537  root->processed_tlist = NIL;
538  root->grouping_map = NULL;
539  root->minmax_aggs = NIL;
540  root->qual_security_level = 0;
541  root->hasInheritedTarget = false;
542  root->hasRecursion = hasRecursion;
543  if (hasRecursion)
544  root->wt_param_id = SS_assign_special_param(root);
545  else
546  root->wt_param_id = -1;
547  root->non_recursive_path = NULL;
548 
549  /*
550  * If there is a WITH list, process each WITH query and build an initplan
551  * SubPlan structure for it.
552  */
553  if (parse->cteList)
554  SS_process_ctes(root);
555 
556  /*
557  * Look for ANY and EXISTS SubLinks in WHERE and JOIN/ON clauses, and try
558  * to transform them into joins. Note that this step does not descend
559  * into subqueries; if we pull up any subqueries below, their SubLinks are
560  * processed just before pulling them up.
561  */
562  if (parse->hasSubLinks)
563  pull_up_sublinks(root);
564 
565  /*
566  * Scan the rangetable for set-returning functions, and inline them if
567  * possible (producing subqueries that might get pulled up next).
568  * Recursion issues here are handled in the same way as for SubLinks.
569  */
571 
572  /*
573  * Check to see if any subqueries in the jointree can be merged into this
574  * query.
575  */
576  pull_up_subqueries(root);
577 
578  /*
579  * If this is a simple UNION ALL query, flatten it into an appendrel. We
580  * do this now because it requires applying pull_up_subqueries to the leaf
581  * queries of the UNION ALL, which weren't touched above because they
582  * weren't referenced by the jointree (they will be after we do this).
583  */
584  if (parse->setOperations)
586 
587  /*
588  * Detect whether any rangetable entries are RTE_JOIN kind; if not, we can
589  * avoid the expense of doing flatten_join_alias_vars(). Also check for
590  * outer joins --- if none, we can skip reduce_outer_joins(). And check
591  * for LATERAL RTEs, too. This must be done after we have done
592  * pull_up_subqueries(), of course.
593  */
594  root->hasJoinRTEs = false;
595  root->hasLateralRTEs = false;
596  hasOuterJoins = false;
597  foreach(l, parse->rtable)
598  {
600 
601  if (rte->rtekind == RTE_JOIN)
602  {
603  root->hasJoinRTEs = true;
604  if (IS_OUTER_JOIN(rte->jointype))
605  hasOuterJoins = true;
606  }
607  if (rte->lateral)
608  root->hasLateralRTEs = true;
609  }
610 
611  /*
612  * Preprocess RowMark information. We need to do this after subquery
613  * pullup (so that all non-inherited RTEs are present) and before
614  * inheritance expansion (so that the info is available for
615  * expand_inherited_tables to examine and modify).
616  */
617  preprocess_rowmarks(root);
618 
619  /*
620  * Expand any rangetable entries that are inheritance sets into "append
621  * relations". This can add entries to the rangetable, but they must be
622  * plain base relations not joins, so it's OK (and marginally more
623  * efficient) to do it after checking for join RTEs. We must do it after
624  * pulling up subqueries, else we'd fail to handle inherited tables in
625  * subqueries.
626  */
628 
629  /*
630  * Set hasHavingQual to remember if HAVING clause is present. Needed
631  * because preprocess_expression will reduce a constant-true condition to
632  * an empty qual list ... but "HAVING TRUE" is not a semantic no-op.
633  */
634  root->hasHavingQual = (parse->havingQual != NULL);
635 
636  /* Clear this flag; might get set in distribute_qual_to_rels */
637  root->hasPseudoConstantQuals = false;
638 
639  /*
640  * Do expression preprocessing on targetlist and quals, as well as other
641  * random expressions in the querytree. Note that we do not need to
642  * handle sort/group expressions explicitly, because they are actually
643  * part of the targetlist.
644  */
645  parse->targetList = (List *)
646  preprocess_expression(root, (Node *) parse->targetList,
648 
649  /* Constant-folding might have removed all set-returning functions */
650  if (parse->hasTargetSRFs)
652 
653  newWithCheckOptions = NIL;
654  foreach(l, parse->withCheckOptions)
655  {
657 
658  wco->qual = preprocess_expression(root, wco->qual,
659  EXPRKIND_QUAL);
660  if (wco->qual != NULL)
661  newWithCheckOptions = lappend(newWithCheckOptions, wco);
662  }
663  parse->withCheckOptions = newWithCheckOptions;
664 
665  parse->returningList = (List *)
666  preprocess_expression(root, (Node *) parse->returningList,
668 
669  preprocess_qual_conditions(root, (Node *) parse->jointree);
670 
671  parse->havingQual = preprocess_expression(root, parse->havingQual,
672  EXPRKIND_QUAL);
673 
674  foreach(l, parse->windowClause)
675  {
677 
678  /* partitionClause/orderClause are sort/group expressions */
681  wc->endOffset = preprocess_expression(root, wc->endOffset,
683  }
684 
685  parse->limitOffset = preprocess_expression(root, parse->limitOffset,
687  parse->limitCount = preprocess_expression(root, parse->limitCount,
689 
690  if (parse->onConflict)
691  {
692  parse->onConflict->arbiterElems = (List *)
694  (Node *) parse->onConflict->arbiterElems,
696  parse->onConflict->arbiterWhere =
698  parse->onConflict->arbiterWhere,
699  EXPRKIND_QUAL);
700  parse->onConflict->onConflictSet = (List *)
702  (Node *) parse->onConflict->onConflictSet,
704  parse->onConflict->onConflictWhere =
706  parse->onConflict->onConflictWhere,
707  EXPRKIND_QUAL);
708  /* exclRelTlist contains only Vars, so no preprocessing needed */
709  }
710 
711  root->append_rel_list = (List *)
714 
715  /* Also need to preprocess expressions within RTEs */
716  foreach(l, parse->rtable)
717  {
719  int kind;
720  ListCell *lcsq;
721 
722  if (rte->rtekind == RTE_RELATION)
723  {
724  if (rte->tablesample)
725  rte->tablesample = (TableSampleClause *)
727  (Node *) rte->tablesample,
729  }
730  else if (rte->rtekind == RTE_SUBQUERY)
731  {
732  /*
733  * We don't want to do all preprocessing yet on the subquery's
734  * expressions, since that will happen when we plan it. But if it
735  * contains any join aliases of our level, those have to get
736  * expanded now, because planning of the subquery won't do it.
737  * That's only possible if the subquery is LATERAL.
738  */
739  if (rte->lateral && root->hasJoinRTEs)
740  rte->subquery = (Query *)
741  flatten_join_alias_vars(root, (Node *) rte->subquery);
742  }
743  else if (rte->rtekind == RTE_FUNCTION)
744  {
745  /* Preprocess the function expression(s) fully */
747  rte->functions = (List *)
748  preprocess_expression(root, (Node *) rte->functions, kind);
749  }
750  else if (rte->rtekind == RTE_TABLEFUNC)
751  {
752  /* Preprocess the function expression(s) fully */
754  rte->tablefunc = (TableFunc *)
755  preprocess_expression(root, (Node *) rte->tablefunc, kind);
756  }
757  else if (rte->rtekind == RTE_VALUES)
758  {
759  /* Preprocess the values lists fully */
761  rte->values_lists = (List *)
762  preprocess_expression(root, (Node *) rte->values_lists, kind);
763  }
764 
765  /*
766  * Process each element of the securityQuals list as if it were a
767  * separate qual expression (as indeed it is). We need to do it this
768  * way to get proper canonicalization of AND/OR structure. Note that
769  * this converts each element into an implicit-AND sublist.
770  */
771  foreach(lcsq, rte->securityQuals)
772  {
773  lfirst(lcsq) = preprocess_expression(root,
774  (Node *) lfirst(lcsq),
775  EXPRKIND_QUAL);
776  }
777  }
778 
779  /*
780  * In some cases we may want to transfer a HAVING clause into WHERE. We
781  * cannot do so if the HAVING clause contains aggregates (obviously) or
782  * volatile functions (since a HAVING clause is supposed to be executed
783  * only once per group). We also can't do this if there are any nonempty
784  * grouping sets; moving such a clause into WHERE would potentially change
785  * the results, if any referenced column isn't present in all the grouping
786  * sets. (If there are only empty grouping sets, then the HAVING clause
787  * must be degenerate as discussed below.)
788  *
789  * Also, it may be that the clause is so expensive to execute that we're
790  * better off doing it only once per group, despite the loss of
791  * selectivity. This is hard to estimate short of doing the entire
792  * planning process twice, so we use a heuristic: clauses containing
793  * subplans are left in HAVING. Otherwise, we move or copy the HAVING
794  * clause into WHERE, in hopes of eliminating tuples before aggregation
795  * instead of after.
796  *
797  * If the query has explicit grouping then we can simply move such a
798  * clause into WHERE; any group that fails the clause will not be in the
799  * output because none of its tuples will reach the grouping or
800  * aggregation stage. Otherwise we must have a degenerate (variable-free)
801  * HAVING clause, which we put in WHERE so that query_planner() can use it
802  * in a gating Result node, but also keep in HAVING to ensure that we
803  * don't emit a bogus aggregated row. (This could be done better, but it
804  * seems not worth optimizing.)
805  *
806  * Note that both havingQual and parse->jointree->quals are in
807  * implicitly-ANDed-list form at this point, even though they are declared
808  * as Node *.
809  */
810  newHaving = NIL;
811  foreach(l, (List *) parse->havingQual)
812  {
813  Node *havingclause = (Node *) lfirst(l);
814 
815  if ((parse->groupClause && parse->groupingSets) ||
816  contain_agg_clause(havingclause) ||
817  contain_volatile_functions(havingclause) ||
818  contain_subplans(havingclause))
819  {
820  /* keep it in HAVING */
821  newHaving = lappend(newHaving, havingclause);
822  }
823  else if (parse->groupClause && !parse->groupingSets)
824  {
825  /* move it to WHERE */
826  parse->jointree->quals = (Node *)
827  lappend((List *) parse->jointree->quals, havingclause);
828  }
829  else
830  {
831  /* put a copy in WHERE, keep it in HAVING */
832  parse->jointree->quals = (Node *)
833  lappend((List *) parse->jointree->quals,
834  copyObject(havingclause));
835  newHaving = lappend(newHaving, havingclause);
836  }
837  }
838  parse->havingQual = (Node *) newHaving;
839 
840  /* Remove any redundant GROUP BY columns */
842 
843  /*
844  * If we have any outer joins, try to reduce them to plain inner joins.
845  * This step is most easily done after we've done expression
846  * preprocessing.
847  */
848  if (hasOuterJoins)
849  reduce_outer_joins(root);
850 
851  /*
852  * Do the main planning. If we have an inherited target relation, that
853  * needs special processing, else go straight to grouping_planner.
854  */
855  if (parse->resultRelation &&
856  rt_fetch(parse->resultRelation, parse->rtable)->inh)
857  inheritance_planner(root);
858  else
859  grouping_planner(root, false, tuple_fraction);
860 
861  /*
862  * Capture the set of outer-level param IDs we have access to, for use in
863  * extParam/allParam calculations later.
864  */
866 
867  /*
868  * If any initPlans were created in this query level, adjust the surviving
869  * Paths' costs and parallel-safety flags to account for them. The
870  * initPlans won't actually get attached to the plan tree till
871  * create_plan() runs, but we must include their effects now.
872  */
873  final_rel = fetch_upper_rel(root, UPPERREL_FINAL, NULL);
874  SS_charge_for_initplans(root, final_rel);
875 
876  /*
877  * Make sure we've identified the cheapest Path for the final rel. (By
878  * doing this here not in grouping_planner, we include initPlan costs in
879  * the decision, though it's unlikely that will change anything.)
880  */
881  set_cheapest(final_rel);
882 
883  return root;
884 }
Node * limitOffset
Definition: parsenodes.h:158
#define NIL
Definition: pg_list.h:69
List * rowMarks
Definition: relation.h:256
Query * parse
Definition: relation.h:155
List * plan_params
Definition: relation.h:169
bool hasJoinRTEs
Definition: relation.h:302
#define EXPRKIND_ARBITER_ELEM
Definition: planner.c:83
void reduce_outer_joins(PlannerInfo *root)
FromExpr * jointree
Definition: parsenodes.h:136
int SS_assign_special_param(PlannerInfo *root)
Definition: subselect.c:416
OnConflictExpr * onConflict
Definition: parsenodes.h:142
static void preprocess_rowmarks(PlannerInfo *root)
Definition: planner.c:2383
List * securityQuals
Definition: parsenodes.h:1058
List * withCheckOptions
Definition: parsenodes.h:169
#define EXPRKIND_APPINFO
Definition: planner.c:80
#define EXPRKIND_QUAL
Definition: planner.c:73
#define EXPRKIND_TABLEFUNC_LATERAL
Definition: planner.c:85
bool expression_returns_set(Node *clause)
Definition: nodeFuncs.c:670
int resultRelation
Definition: parsenodes.h:120
void SS_charge_for_initplans(PlannerInfo *root, RelOptInfo *final_rel)
Definition: subselect.c:2153
#define IS_OUTER_JOIN(jointype)
Definition: nodes.h:723
#define EXPRKIND_RTFUNC
Definition: planner.c:75
List * groupingSets
Definition: parsenodes.h:148
Definition: nodes.h:510
static Node * preprocess_expression(PlannerInfo *root, Node *expr, int kind)
Definition: planner.c:893
List * minmax_aggs
Definition: relation.h:288
bool contain_volatile_functions(Node *clause)
Definition: clauses.c:957
#define EXPRKIND_VALUES_LATERAL
Definition: planner.c:78
void expand_inherited_tables(PlannerInfo *root)
Definition: prepunion.c:1342
AttrNumber * grouping_map
Definition: relation.h:287
bool hasRecursion
Definition: relation.h:308
void pull_up_subqueries(PlannerInfo *root)
Definition: prepjointree.c:607
#define EXPRKIND_TARGET
Definition: planner.c:74
List * values_lists
Definition: parsenodes.h:1010
Node * quals
Definition: primnodes.h:1472
List * windowClause
Definition: parsenodes.h:152
List * targetList
Definition: parsenodes.h:138
List * arbiterElems
Definition: primnodes.h:1490
List * multiexpr_params
Definition: relation.h:232
bool contain_subplans(Node *clause)
Definition: clauses.c:843
#define EXPRKIND_LIMIT
Definition: planner.c:79
int wt_param_id
Definition: relation.h:311
List * rtable
Definition: parsenodes.h:135
TableFunc * tablefunc
Definition: parsenodes.h:1005
bool hasLateralRTEs
Definition: relation.h:303
void inline_set_returning_functions(PlannerInfo *root)
Definition: prepjointree.c:573
RelOptInfo * fetch_upper_rel(PlannerInfo *root, UpperRelationKind kind, Relids relids)
Definition: relnode.c:1138
#define lfirst_node(type, lc)
Definition: pg_list.h:109
static void remove_useless_groupby_columns(PlannerInfo *root)
Definition: planner.c:2802
Node * limitCount
Definition: parsenodes.h:159
PlannerGlobal * glob
Definition: relation.h:157
JoinType jointype
Definition: parsenodes.h:988
MemoryContext CurrentMemoryContext
Definition: mcxt.c:37
void SS_process_ctes(PlannerInfo *root)
Definition: subselect.c:1141
List * returningList
Definition: parsenodes.h:144
#define rt_fetch(rangetable_index, rangetable)
Definition: parsetree.h:31
List * lappend(List *list, void *datum)
Definition: list.c:128
struct PlannerInfo * parent_root
Definition: relation.h:161
void set_cheapest(RelOptInfo *parent_rel)
Definition: pathnode.c:242
Node * startOffset
Definition: parsenodes.h:1286
Node * flatten_join_alias_vars(PlannerInfo *root, Node *node)
Definition: var.c:670
List * append_rel_list
Definition: relation.h:252
List * cte_plan_ids
Definition: relation.h:230
List * init_plans
Definition: relation.h:228
bool hasPseudoConstantQuals
Definition: relation.h:306
static void inheritance_planner(PlannerInfo *root)
Definition: planner.c:1048
bool hasTargetSRFs
Definition: parsenodes.h:125
#define makeNode(_type_)
Definition: nodes.h:558
#define lfirst(lc)
Definition: pg_list.h:106
List * pcinfo_list
Definition: relation.h:254
void SS_identify_outer_params(PlannerInfo *root)
Definition: subselect.c:2091
List * eq_classes
Definition: relation.h:235
List * functions
Definition: parsenodes.h:999
bool hasInheritedTarget
Definition: relation.h:300
void flatten_simple_union_all(PlannerInfo *root)
Bitmapset * outer_params
Definition: relation.h:170
struct Path * non_recursive_path
Definition: relation.h:312
Node * endOffset
Definition: parsenodes.h:1287
#define EXPRKIND_RTFUNC_LATERAL
Definition: planner.c:76
Index qual_security_level
Definition: relation.h:297
Index query_level
Definition: relation.h:159
void pull_up_sublinks(PlannerInfo *root)
Definition: prepjointree.c:150
RTEKind rtekind
Definition: parsenodes.h:945
Node * arbiterWhere
Definition: primnodes.h:1492
List * cteList
Definition: parsenodes.h:133
Node * setOperations
Definition: parsenodes.h:163
bool contain_agg_clause(Node *clause)
Definition: clauses.c:417
Query * subquery
Definition: parsenodes.h:968
List * groupClause
Definition: parsenodes.h:146
bool hasSubLinks
Definition: parsenodes.h:126
static void grouping_planner(PlannerInfo *root, bool inheritance_update, double tuple_fraction)
Definition: planner.c:1523
static void preprocess_qual_conditions(PlannerInfo *root, Node *jtnode)
Definition: planner.c:979
List * onConflictSet
Definition: primnodes.h:1496
bool hasHavingQual
Definition: relation.h:305
#define EXPRKIND_TABLESAMPLE
Definition: planner.c:82
MemoryContext planner_cxt
Definition: relation.h:290
#define copyObject(obj)
Definition: nodes.h:623
#define EXPRKIND_VALUES
Definition: planner.c:77
Node * havingQual
Definition: parsenodes.h:150
List * processed_tlist
Definition: relation.h:284
Node * onConflictWhere
Definition: primnodes.h:1497
Definition: pg_list.h:45
struct TableSampleClause * tablesample
Definition: parsenodes.h:963
static struct subre * parse(struct vars *, int, int, struct state *, struct state *)
Definition: regcomp.c:649
struct PathTarget * upper_targets[UPPERREL_FINAL+1]
Definition: relation.h:278
#define EXPRKIND_TABLEFUNC
Definition: planner.c:84
List * upper_rels[UPPERREL_FINAL+1]
Definition: relation.h:275

Variable Documentation

Definition at line 66 of file planner.c.

Referenced by planner().