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)
 

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 5939 of file planner.c.

References eval_const_expressions(), fix_opfuncids(), NULL, and result.

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

5940 {
5941  Node *result;
5942 
5943  /*
5944  * Convert named-argument function calls, insert default arguments and
5945  * simplify constant subexprs
5946  */
5947  result = eval_const_expressions(NULL, (Node *) expr);
5948 
5949  /* Fill in opfuncid values if missing */
5950  fix_opfuncids(result);
5951 
5952  return (Expr *) result;
5953 }
void fix_opfuncids(Node *node)
Definition: nodeFuncs.c:1582
Definition: nodes.h:509
Node * eval_const_expressions(PlannerInfo *root, Node *node)
Definition: clauses.c:2421
return result
Definition: formatting.c:1633
#define NULL
Definition: c.h:229
Path* get_cheapest_fractional_path ( RelOptInfo rel,
double  tuple_fraction 
)

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

5787 {
5788  Path *best_path = rel->cheapest_total_path;
5789  ListCell *l;
5790 
5791  /* If all tuples will be retrieved, just return the cheapest-total path */
5792  if (tuple_fraction <= 0.0)
5793  return best_path;
5794 
5795  /* Convert absolute # of tuples to a fraction; no need to clamp to 0..1 */
5796  if (tuple_fraction >= 1.0 && best_path->rows > 0)
5797  tuple_fraction /= best_path->rows;
5798 
5799  foreach(l, rel->pathlist)
5800  {
5801  Path *path = (Path *) lfirst(l);
5802 
5803  if (path == rel->cheapest_total_path ||
5804  compare_fractional_path_costs(best_path, path, tuple_fraction) <= 0)
5805  continue;
5806 
5807  best_path = path;
5808  }
5809 
5810  return best_path;
5811 }
struct Path * cheapest_total_path
Definition: relation.h:543
#define lfirst(lc)
Definition: pg_list.h:106
double rows
Definition: relation.h:964
int compare_fractional_path_costs(Path *path1, Path *path2, double fraction)
Definition: pathnode.c:107
List * pathlist
Definition: relation.h:539
Definition: relation.h:948
List* get_partitioned_child_rels ( PlannerInfo root,
Index  rti 
)

Definition at line 6076 of file planner.c.

References Assert, PartitionedChildRelInfo::child_rels, lfirst, list_length(), NIL, PartitionedChildRelInfo::parent_relid, PlannerInfo::pcinfo_list, and result.

Referenced by add_paths_to_append_rel(), and inheritance_planner().

6077 {
6078  List *result = NIL;
6079  ListCell *l;
6080 
6081  foreach(l, root->pcinfo_list)
6082  {
6084 
6085  if (pc->parent_relid == rti)
6086  {
6087  result = pc->child_rels;
6088  break;
6089  }
6090  }
6091 
6092  /* The root partitioned table is included as a child rel */
6093  Assert(list_length(result) >= 1);
6094 
6095  return result;
6096 }
#define NIL
Definition: pg_list.h:69
return result
Definition: formatting.c:1633
#define Assert(condition)
Definition: c.h:676
#define lfirst(lc)
Definition: pg_list.h:106
List * pcinfo_list
Definition: relation.h:254
static int list_length(const List *l)
Definition: pg_list.h:89
Definition: pg_list.h:45
bool is_dummy_plan ( Plan plan)

Definition at line 2300 of file planner.c.

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

2301 {
2302  if (IsA(plan, Result))
2303  {
2304  List *rcqual = (List *) ((Result *) plan)->resconstantqual;
2305 
2306  if (list_length(rcqual) == 1)
2307  {
2308  Const *constqual = (Const *) linitial(rcqual);
2309 
2310  if (constqual && IsA(constqual, Const))
2311  {
2312  if (!constqual->constisnull &&
2313  !DatumGetBool(constqual->constvalue))
2314  return true;
2315  }
2316  }
2317  }
2318  return false;
2319 }
Datum constvalue
Definition: primnodes.h:196
#define IsA(nodeptr, _type_)
Definition: nodes.h:560
#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 5235 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().

5236 {
5237  /* aggtranstype should be computed by this point */
5239  /* ... but aggsplit should still be as the parser left it */
5240  Assert(agg->aggsplit == AGGSPLIT_SIMPLE);
5241 
5242  /* Mark the Aggref with the intended partial-aggregation mode */
5243  agg->aggsplit = aggsplit;
5244 
5245  /*
5246  * Adjust result type if needed. Normally, a partial aggregate returns
5247  * the aggregate's transition type; but if that's INTERNAL and we're
5248  * serializing, it returns BYTEA instead.
5249  */
5250  if (DO_AGGSPLIT_SKIPFINAL(aggsplit))
5251  {
5252  if (agg->aggtranstype == INTERNALOID && DO_AGGSPLIT_SERIALIZE(aggsplit))
5253  agg->aggtype = BYTEAOID;
5254  else
5255  agg->aggtype = agg->aggtranstype;
5256  }
5257 }
#define OidIsValid(objectId)
Definition: c.h:538
#define DO_AGGSPLIT_SERIALIZE(as)
Definition: nodes.h:770
#define INTERNALOID
Definition: pg_type.h:698
#define Assert(condition)
Definition: c.h:676
AggSplit aggsplit
Definition: primnodes.h:310
#define DO_AGGSPLIT_SKIPFINAL(as)
Definition: nodes.h:769
#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 5968 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, list_make1, maintenance_work_mem, makeNode, NIL, NULL, 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().

5969 {
5970  PlannerInfo *root;
5971  Query *query;
5972  PlannerGlobal *glob;
5973  RangeTblEntry *rte;
5974  RelOptInfo *rel;
5975  IndexOptInfo *indexInfo;
5976  QualCost indexExprCost;
5977  Cost comparisonCost;
5978  Path *seqScanPath;
5979  Path seqScanAndSortPath;
5980  IndexPath *indexScanPath;
5981  ListCell *lc;
5982 
5983  /* We can short-circuit the cost comparison if indexscans are disabled */
5984  if (!enable_indexscan)
5985  return true; /* use sort */
5986 
5987  /* Set up mostly-dummy planner state */
5988  query = makeNode(Query);
5989  query->commandType = CMD_SELECT;
5990 
5991  glob = makeNode(PlannerGlobal);
5992 
5993  root = makeNode(PlannerInfo);
5994  root->parse = query;
5995  root->glob = glob;
5996  root->query_level = 1;
5998  root->wt_param_id = -1;
5999 
6000  /* Build a minimal RTE for the rel */
6001  rte = makeNode(RangeTblEntry);
6002  rte->rtekind = RTE_RELATION;
6003  rte->relid = tableOid;
6004  rte->relkind = RELKIND_RELATION; /* Don't be too picky. */
6005  rte->lateral = false;
6006  rte->inh = false;
6007  rte->inFromCl = true;
6008  query->rtable = list_make1(rte);
6009 
6010  /* Set up RTE/RelOptInfo arrays */
6012 
6013  /* Build RelOptInfo */
6014  rel = build_simple_rel(root, 1, NULL);
6015 
6016  /* Locate IndexOptInfo for the target index */
6017  indexInfo = NULL;
6018  foreach(lc, rel->indexlist)
6019  {
6020  indexInfo = (IndexOptInfo *) lfirst(lc);
6021  if (indexInfo->indexoid == indexOid)
6022  break;
6023  }
6024 
6025  /*
6026  * It's possible that get_relation_info did not generate an IndexOptInfo
6027  * for the desired index; this could happen if it's not yet reached its
6028  * indcheckxmin usability horizon, or if it's a system index and we're
6029  * ignoring system indexes. In such cases we should tell CLUSTER to not
6030  * trust the index contents but use seqscan-and-sort.
6031  */
6032  if (lc == NULL) /* not in the list? */
6033  return true; /* use sort */
6034 
6035  /*
6036  * Rather than doing all the pushups that would be needed to use
6037  * set_baserel_size_estimates, just do a quick hack for rows and width.
6038  */
6039  rel->rows = rel->tuples;
6040  rel->reltarget->width = get_relation_data_width(tableOid, NULL);
6041 
6042  root->total_table_pages = rel->pages;
6043 
6044  /*
6045  * Determine eval cost of the index expressions, if any. We need to
6046  * charge twice that amount for each tuple comparison that happens during
6047  * the sort, since tuplesort.c will have to re-evaluate the index
6048  * expressions each time. (XXX that's pretty inefficient...)
6049  */
6050  cost_qual_eval(&indexExprCost, indexInfo->indexprs, root);
6051  comparisonCost = 2.0 * (indexExprCost.startup + indexExprCost.per_tuple);
6052 
6053  /* Estimate the cost of seq scan + sort */
6054  seqScanPath = create_seqscan_path(root, rel, NULL, 0);
6055  cost_sort(&seqScanAndSortPath, root, NIL,
6056  seqScanPath->total_cost, rel->tuples, rel->reltarget->width,
6057  comparisonCost, maintenance_work_mem, -1.0);
6058 
6059  /* Estimate the cost of index scan */
6060  indexScanPath = create_index_path(root, indexInfo,
6061  NIL, NIL, NIL, NIL, NIL,
6062  ForwardScanDirection, false,
6063  NULL, 1.0, false);
6064 
6065  return (seqScanAndSortPath.total_cost < indexScanPath->path.total_cost);
6066 }
#define NIL
Definition: pg_list.h:69
Query * parse
Definition: relation.h:155
Path path
Definition: relation.h:1030
double tuples
Definition: relation.h:565
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:1008
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:308
List * rtable
Definition: parsenodes.h:135
void cost_qual_eval(QualCost *cost, List *quals, PlannerInfo *root)
Definition: costsize.c:3463
PlannerGlobal * glob
Definition: relation.h:157
RelOptInfo * build_simple_rel(PlannerInfo *root, int relid, RelOptInfo *parent)
Definition: relnode.c:91
MemoryContext CurrentMemoryContext
Definition: mcxt.c:37
double total_table_pages
Definition: relation.h:289
int32 get_relation_data_width(Oid relid, int32 *attr_widths)
Definition: plancat.c:1110
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:1644
List * indexlist
Definition: relation.h:562
double rows
Definition: relation.h:528
int maintenance_work_mem
Definition: globals.c:114
Cost total_cost
Definition: relation.h:966
CmdType commandType
Definition: parsenodes.h:110
#define makeNode(_type_)
Definition: nodes.h:557
BlockNumber pages
Definition: relation.h:564
#define NULL
Definition: c.h:229
#define lfirst(lc)
Definition: pg_list.h:106
void setup_simple_rel_arrays(PlannerInfo *root)
Definition: relnode.c:62
Index query_level
Definition: relation.h:159
RTEKind rtekind
Definition: parsenodes.h:944
int width
Definition: relation.h:887
MemoryContext planner_cxt
Definition: relation.h:287
Oid indexoid
Definition: relation.h:631
#define RELKIND_RELATION
Definition: pg_class.h:160
struct PathTarget * reltarget
Definition: relation.h:536
bool enable_indexscan
Definition: costsize.c:119
Path * create_seqscan_path(PlannerInfo *root, RelOptInfo *rel, Relids required_outer, int parallel_workers)
Definition: pathnode.c:938
Definition: relation.h:948
double Cost
Definition: nodes.h:640
List * indexprs
Definition: relation.h:653
PlannedStmt* planner ( Query parse,
int  cursorOptions,
ParamListInfo  boundParams 
)

Definition at line 203 of file planner.c.

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

Referenced by pg_plan_query().

204 {
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
return result
Definition: formatting.c:1633
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 1007 of file planner.c.

References EXPRKIND_PHV, and preprocess_expression().

Referenced by extract_lateral_references().

1008 {
1009  return (Expr *) preprocess_expression(root, (Node *) expr, EXPRKIND_PHV);
1010 }
Definition: nodes.h:509
static Node * preprocess_expression(PlannerInfo *root, Node *expr, int kind)
Definition: planner.c:877
#define EXPRKIND_PHV
Definition: planner.c:81
RowMarkType select_rowmark_type ( RangeTblEntry rte,
LockClauseStrength  strength 
)

Definition at line 2436 of file planner.c.

References elog, ERROR, GetFdwRoutineByRelId(), FdwRoutine::GetForeignRowMarkType, LCS_FORKEYSHARE, LCS_FORNOKEYUPDATE, LCS_FORSHARE, LCS_FORUPDATE, LCS_NONE, NULL, 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_inherited_rtentry(), and preprocess_rowmarks().

2437 {
2438  if (rte->rtekind != RTE_RELATION)
2439  {
2440  /* If it's not a table at all, use ROW_MARK_COPY */
2441  return ROW_MARK_COPY;
2442  }
2443  else if (rte->relkind == RELKIND_FOREIGN_TABLE)
2444  {
2445  /* Let the FDW select the rowmark type, if it wants to */
2446  FdwRoutine *fdwroutine = GetFdwRoutineByRelId(rte->relid);
2447 
2448  if (fdwroutine->GetForeignRowMarkType != NULL)
2449  return fdwroutine->GetForeignRowMarkType(rte, strength);
2450  /* Otherwise, use ROW_MARK_COPY by default */
2451  return ROW_MARK_COPY;
2452  }
2453  else
2454  {
2455  /* Regular table, apply the appropriate lock type */
2456  switch (strength)
2457  {
2458  case LCS_NONE:
2459 
2460  /*
2461  * We don't need a tuple lock, only the ability to re-fetch
2462  * the row.
2463  */
2464  return ROW_MARK_REFERENCE;
2465  break;
2466  case LCS_FORKEYSHARE:
2467  return ROW_MARK_KEYSHARE;
2468  break;
2469  case LCS_FORSHARE:
2470  return ROW_MARK_SHARE;
2471  break;
2472  case LCS_FORNOKEYUPDATE:
2473  return ROW_MARK_NOKEYEXCLUSIVE;
2474  break;
2475  case LCS_FORUPDATE:
2476  return ROW_MARK_EXCLUSIVE;
2477  break;
2478  }
2479  elog(ERROR, "unrecognized LockClauseStrength %d", (int) strength);
2480  return ROW_MARK_EXCLUSIVE; /* keep compiler quiet */
2481  }
2482 }
#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:208
#define NULL
Definition: c.h:229
RTEKind rtekind
Definition: parsenodes.h:944
#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, 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, NULL, 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, result, 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 {
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  * For now, we don't try to use parallel mode if we're running inside a
261  * parallel worker. We might eventually be able to relax this
262  * restriction, but for now it seems best not to have parallel workers
263  * trying to create their own parallel workers.
264  *
265  * We can't use parallelism in serializable mode because the predicate
266  * locking code is not parallel-aware. It's not catastrophic if someone
267  * tries to run a parallel plan in serializable mode; it just won't get
268  * any workers and will run serially. But it seems like a good heuristic
269  * to assume that the same serialization level will be in effect at plan
270  * time and execution time, so don't generate a parallel plan if we're in
271  * serializable mode.
272  */
273  if ((cursorOptions & CURSOR_OPT_PARALLEL_OK) != 0 &&
276  parse->commandType == CMD_SELECT &&
277  !parse->hasModifyingCTE &&
279  !IsParallelWorker() &&
281  {
282  /* all the cheap tests pass, so scan the query tree */
283  glob->maxParallelHazard = max_parallel_hazard(parse);
285  }
286  else
287  {
288  /* skip the query tree scan, just assume it's unsafe */
290  glob->parallelModeOK = false;
291  }
292 
293  /*
294  * glob->parallelModeNeeded is normally set to false here and changed to
295  * true during plan creation if a Gather or Gather Merge plan is actually
296  * created (cf. create_gather_plan, create_gather_merge_plan).
297  *
298  * However, if force_parallel_mode = on or force_parallel_mode = regress,
299  * then we impose parallel mode whenever it's safe to do so, even if the
300  * final plan doesn't use parallelism. It's not safe to do so if the
301  * query contains anything parallel-unsafe; parallelModeOK will be false
302  * in that case. Note that parallelModeOK can't change after this point.
303  * Otherwise, everything in the query is either parallel-safe or
304  * parallel-restricted, and in either case it should be OK to impose
305  * parallel-mode restrictions. If that ends up breaking something, then
306  * either some function the user included in the query is incorrectly
307  * labelled as parallel-safe or parallel-restricted when in reality it's
308  * parallel-unsafe, or else the query planner itself has a bug.
309  */
310  glob->parallelModeNeeded = glob->parallelModeOK &&
312 
313  /* Determine what fraction of the plan is likely to be scanned */
314  if (cursorOptions & CURSOR_OPT_FAST_PLAN)
315  {
316  /*
317  * We have no real idea how many tuples the user will ultimately FETCH
318  * from a cursor, but it is often the case that he doesn't want 'em
319  * all, or would prefer a fast-start plan anyway so that he can
320  * process some of the tuples sooner. Use a GUC parameter to decide
321  * what fraction to optimize for.
322  */
323  tuple_fraction = cursor_tuple_fraction;
324 
325  /*
326  * We document cursor_tuple_fraction as simply being a fraction, which
327  * means the edge cases 0 and 1 have to be treated specially here. We
328  * convert 1 to 0 ("all the tuples") and 0 to a very small fraction.
329  */
330  if (tuple_fraction >= 1.0)
331  tuple_fraction = 0.0;
332  else if (tuple_fraction <= 0.0)
333  tuple_fraction = 1e-10;
334  }
335  else
336  {
337  /* Default assumption is we need all the tuples */
338  tuple_fraction = 0.0;
339  }
340 
341  /* primary planning entry point (may recurse for subqueries) */
342  root = subquery_planner(glob, parse, NULL,
343  false, tuple_fraction);
344 
345  /* Select best Path and turn it into a Plan */
346  final_rel = fetch_upper_rel(root, UPPERREL_FINAL, NULL);
347  best_path = get_cheapest_fractional_path(final_rel, tuple_fraction);
348 
349  top_plan = create_plan(root, best_path);
350 
351  /*
352  * If creating a plan for a scrollable cursor, make sure it can run
353  * backwards on demand. Add a Material node at the top at need.
354  */
355  if (cursorOptions & CURSOR_OPT_SCROLL)
356  {
357  if (!ExecSupportsBackwardScan(top_plan))
358  top_plan = materialize_finished_plan(top_plan);
359  }
360 
361  /*
362  * Optionally add a Gather node for testing purposes, provided this is
363  * actually a safe thing to do.
364  */
366  {
367  Gather *gather = makeNode(Gather);
368 
369  gather->plan.targetlist = top_plan->targetlist;
370  gather->plan.qual = NIL;
371  gather->plan.lefttree = top_plan;
372  gather->plan.righttree = NULL;
373  gather->num_workers = 1;
374  gather->single_copy = true;
376 
377  /*
378  * Ideally we'd use cost_gather here, but setting up dummy path data
379  * to satisfy it doesn't seem much cleaner than knowing what it does.
380  */
381  gather->plan.startup_cost = top_plan->startup_cost +
383  gather->plan.total_cost = top_plan->total_cost +
385  gather->plan.plan_rows = top_plan->plan_rows;
386  gather->plan.plan_width = top_plan->plan_width;
387  gather->plan.parallel_aware = false;
388  gather->plan.parallel_safe = false;
389 
390  /* use parallel mode for parallel plans. */
391  root->glob->parallelModeNeeded = true;
392 
393  top_plan = &gather->plan;
394  }
395 
396  /*
397  * If any Params were generated, run through the plan tree and compute
398  * each plan node's extParam/allParam sets. Ideally we'd merge this into
399  * set_plan_references' tree traversal, but for now it has to be separate
400  * because we need to visit subplans before not after main plan.
401  */
402  if (glob->nParamExec > 0)
403  {
404  Assert(list_length(glob->subplans) == list_length(glob->subroots));
405  forboth(lp, glob->subplans, lr, glob->subroots)
406  {
407  Plan *subplan = (Plan *) lfirst(lp);
408  PlannerInfo *subroot = (PlannerInfo *) lfirst(lr);
409 
410  SS_finalize_plan(subroot, subplan);
411  }
412  SS_finalize_plan(root, top_plan);
413  }
414 
415  /* final cleanup of the plan */
416  Assert(glob->finalrtable == NIL);
417  Assert(glob->finalrowmarks == NIL);
418  Assert(glob->resultRelations == NIL);
420  Assert(glob->rootResultRelations == NIL);
421  top_plan = set_plan_references(root, top_plan);
422  /* ... and the subplans (both regular subplans and initplans) */
423  Assert(list_length(glob->subplans) == list_length(glob->subroots));
424  forboth(lp, glob->subplans, lr, glob->subroots)
425  {
426  Plan *subplan = (Plan *) lfirst(lp);
427  PlannerInfo *subroot = (PlannerInfo *) lfirst(lr);
428 
429  lfirst(lp) = set_plan_references(subroot, subplan);
430  }
431 
432  /* build the PlannedStmt result */
433  result = makeNode(PlannedStmt);
434 
435  result->commandType = parse->commandType;
436  result->queryId = parse->queryId;
437  result->hasReturning = (parse->returningList != NIL);
438  result->hasModifyingCTE = parse->hasModifyingCTE;
439  result->canSetTag = parse->canSetTag;
440  result->transientPlan = glob->transientPlan;
441  result->dependsOnRole = glob->dependsOnRole;
442  result->parallelModeNeeded = glob->parallelModeNeeded;
443  result->planTree = top_plan;
444  result->rtable = glob->finalrtable;
445  result->resultRelations = glob->resultRelations;
448  result->subplans = glob->subplans;
449  result->rewindPlanIDs = glob->rewindPlanIDs;
450  result->rowMarks = glob->finalrowmarks;
451  result->relationOids = glob->relationOids;
452  result->invalItems = glob->invalItems;
453  result->nParamExec = glob->nParamExec;
454  /* utilityStmt should be null, but we might as well copy it */
455  result->utilityStmt = parse->utilityStmt;
456  result->stmt_location = parse->stmt_location;
457  result->stmt_len = parse->stmt_len;
458 
459  return result;
460 }
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
uint32 queryId
Definition: parsenodes.h:114
double plan_rows
Definition: plannodes.h:131
uint32 queryId
Definition: plannodes.h:47
#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
return result
Definition: formatting.c:1633
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:303
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:832
bool single_copy
Definition: plannodes.h:834
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:919
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:5967
List * rootResultRelations
Definition: plannodes.h:79
Node * utilityStmt
Definition: plannodes.h:94
int dynamic_shared_memory_type
Definition: dsm_impl.c:112
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:5497
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:2628
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:833
CmdType commandType
Definition: parsenodes.h:110
#define makeNode(_type_)
Definition: nodes.h:557
List * subplans
Definition: plannodes.h:81
List * nonleafResultRelations
Definition: relation.h:110
int plan_width
Definition: plannodes.h:132
#define NULL
Definition: c.h:229
int force_parallel_mode
Definition: planner.c:63
ParamListInfo boundParams
Definition: relation.h:96
#define Assert(condition)
Definition: c.h:676
#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
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:835
e
Definition: preproc-init.c:82
List * finalrtable
Definition: relation.h:104
#define CURSOR_OPT_PARALLEL_OK
Definition: parsenodes.h:2631
Index lastRowMarkId
Definition: relation.h:121
#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:2623
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:209
void SS_finalize_plan(PlannerInfo *root, Plan *plan)
Definition: subselect.c:2217
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:492
Definition: relation.h:948
Path * get_cheapest_fractional_path(RelOptInfo *rel, double tuple_fraction)
Definition: planner.c:5786
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 492 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, Query::limitCount, Query::limitOffset, makeNode, PlannerInfo::minmax_aggs, PlannerInfo::multiexpr_params, NIL, PlannerInfo::non_recursive_path, NULL, 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().

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

Variable Documentation

Definition at line 66 of file planner.c.

Referenced by planner().