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 5928 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 transformPartitionBound().

5929 {
5930  Node *result;
5931 
5932  /*
5933  * Convert named-argument function calls, insert default arguments and
5934  * simplify constant subexprs
5935  */
5936  result = eval_const_expressions(NULL, (Node *) expr);
5937 
5938  /* Fill in opfuncid values if missing */
5939  fix_opfuncids(result);
5940 
5941  return (Expr *) result;
5942 }
void fix_opfuncids(Node *node)
Definition: nodeFuncs.c:1603
Definition: nodes.h:509
Node * eval_const_expressions(PlannerInfo *root, Node *node)
Definition: clauses.c:2400
return result
Definition: formatting.c:1618
#define NULL
Definition: c.h:229
Path* get_cheapest_fractional_path ( RelOptInfo rel,
double  tuple_fraction 
)

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

5776 {
5777  Path *best_path = rel->cheapest_total_path;
5778  ListCell *l;
5779 
5780  /* If all tuples will be retrieved, just return the cheapest-total path */
5781  if (tuple_fraction <= 0.0)
5782  return best_path;
5783 
5784  /* Convert absolute # of tuples to a fraction; no need to clamp to 0..1 */
5785  if (tuple_fraction >= 1.0 && best_path->rows > 0)
5786  tuple_fraction /= best_path->rows;
5787 
5788  foreach(l, rel->pathlist)
5789  {
5790  Path *path = (Path *) lfirst(l);
5791 
5792  if (path == rel->cheapest_total_path ||
5793  compare_fractional_path_costs(best_path, path, tuple_fraction) <= 0)
5794  continue;
5795 
5796  best_path = path;
5797  }
5798 
5799  return best_path;
5800 }
struct Path * cheapest_total_path
Definition: relation.h:542
#define lfirst(lc)
Definition: pg_list.h:106
double rows
Definition: relation.h:963
int compare_fractional_path_costs(Path *path1, Path *path2, double fraction)
Definition: pathnode.c:107
List * pathlist
Definition: relation.h:538
Definition: relation.h:946
List* get_partitioned_child_rels ( PlannerInfo root,
Index  rti 
)

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

6066 {
6067  List *result = NIL;
6068  ListCell *l;
6069 
6070  foreach(l, root->pcinfo_list)
6071  {
6073 
6074  if (pc->parent_relid == rti)
6075  {
6076  result = pc->child_rels;
6077  break;
6078  }
6079  }
6080 
6081  /* The root partitioned table is included as a child rel */
6082  Assert(list_length(result) >= 1);
6083 
6084  return result;
6085 }
#define NIL
Definition: pg_list.h:69
return result
Definition: formatting.c:1618
#define Assert(condition)
Definition: c.h:675
#define lfirst(lc)
Definition: pg_list.h:106
List * pcinfo_list
Definition: relation.h:253
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 2289 of file planner.c.

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

2290 {
2291  if (IsA(plan, Result))
2292  {
2293  List *rcqual = (List *) ((Result *) plan)->resconstantqual;
2294 
2295  if (list_length(rcqual) == 1)
2296  {
2297  Const *constqual = (Const *) linitial(rcqual);
2298 
2299  if (constqual && IsA(constqual, Const))
2300  {
2301  if (!constqual->constisnull &&
2302  !DatumGetBool(constqual->constvalue))
2303  return true;
2304  }
2305  }
2306  }
2307  return false;
2308 }
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 5224 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().

5225 {
5226  /* aggtranstype should be computed by this point */
5228  /* ... but aggsplit should still be as the parser left it */
5229  Assert(agg->aggsplit == AGGSPLIT_SIMPLE);
5230 
5231  /* Mark the Aggref with the intended partial-aggregation mode */
5232  agg->aggsplit = aggsplit;
5233 
5234  /*
5235  * Adjust result type if needed. Normally, a partial aggregate returns
5236  * the aggregate's transition type; but if that's INTERNAL and we're
5237  * serializing, it returns BYTEA instead.
5238  */
5239  if (DO_AGGSPLIT_SKIPFINAL(aggsplit))
5240  {
5241  if (agg->aggtranstype == INTERNALOID && DO_AGGSPLIT_SERIALIZE(aggsplit))
5242  agg->aggtype = BYTEAOID;
5243  else
5244  agg->aggtype = agg->aggtranstype;
5245  }
5246 }
#define OidIsValid(objectId)
Definition: c.h:538
#define DO_AGGSPLIT_SERIALIZE(as)
Definition: nodes.h:769
#define INTERNALOID
Definition: pg_type.h:698
#define Assert(condition)
Definition: c.h:675
AggSplit aggsplit
Definition: primnodes.h:310
#define DO_AGGSPLIT_SKIPFINAL(as)
Definition: nodes.h:768
#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 5957 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().

5958 {
5959  PlannerInfo *root;
5960  Query *query;
5961  PlannerGlobal *glob;
5962  RangeTblEntry *rte;
5963  RelOptInfo *rel;
5964  IndexOptInfo *indexInfo;
5965  QualCost indexExprCost;
5966  Cost comparisonCost;
5967  Path *seqScanPath;
5968  Path seqScanAndSortPath;
5969  IndexPath *indexScanPath;
5970  ListCell *lc;
5971 
5972  /* We can short-circuit the cost comparison if indexscans are disabled */
5973  if (!enable_indexscan)
5974  return true; /* use sort */
5975 
5976  /* Set up mostly-dummy planner state */
5977  query = makeNode(Query);
5978  query->commandType = CMD_SELECT;
5979 
5980  glob = makeNode(PlannerGlobal);
5981 
5982  root = makeNode(PlannerInfo);
5983  root->parse = query;
5984  root->glob = glob;
5985  root->query_level = 1;
5987  root->wt_param_id = -1;
5988 
5989  /* Build a minimal RTE for the rel */
5990  rte = makeNode(RangeTblEntry);
5991  rte->rtekind = RTE_RELATION;
5992  rte->relid = tableOid;
5993  rte->relkind = RELKIND_RELATION; /* Don't be too picky. */
5994  rte->lateral = false;
5995  rte->inh = false;
5996  rte->inFromCl = true;
5997  query->rtable = list_make1(rte);
5998 
5999  /* Set up RTE/RelOptInfo arrays */
6001 
6002  /* Build RelOptInfo */
6003  rel = build_simple_rel(root, 1, NULL);
6004 
6005  /* Locate IndexOptInfo for the target index */
6006  indexInfo = NULL;
6007  foreach(lc, rel->indexlist)
6008  {
6009  indexInfo = (IndexOptInfo *) lfirst(lc);
6010  if (indexInfo->indexoid == indexOid)
6011  break;
6012  }
6013 
6014  /*
6015  * It's possible that get_relation_info did not generate an IndexOptInfo
6016  * for the desired index; this could happen if it's not yet reached its
6017  * indcheckxmin usability horizon, or if it's a system index and we're
6018  * ignoring system indexes. In such cases we should tell CLUSTER to not
6019  * trust the index contents but use seqscan-and-sort.
6020  */
6021  if (lc == NULL) /* not in the list? */
6022  return true; /* use sort */
6023 
6024  /*
6025  * Rather than doing all the pushups that would be needed to use
6026  * set_baserel_size_estimates, just do a quick hack for rows and width.
6027  */
6028  rel->rows = rel->tuples;
6029  rel->reltarget->width = get_relation_data_width(tableOid, NULL);
6030 
6031  root->total_table_pages = rel->pages;
6032 
6033  /*
6034  * Determine eval cost of the index expressions, if any. We need to
6035  * charge twice that amount for each tuple comparison that happens during
6036  * the sort, since tuplesort.c will have to re-evaluate the index
6037  * expressions each time. (XXX that's pretty inefficient...)
6038  */
6039  cost_qual_eval(&indexExprCost, indexInfo->indexprs, root);
6040  comparisonCost = 2.0 * (indexExprCost.startup + indexExprCost.per_tuple);
6041 
6042  /* Estimate the cost of seq scan + sort */
6043  seqScanPath = create_seqscan_path(root, rel, NULL, 0);
6044  cost_sort(&seqScanAndSortPath, root, NIL,
6045  seqScanPath->total_cost, rel->tuples, rel->reltarget->width,
6046  comparisonCost, maintenance_work_mem, -1.0);
6047 
6048  /* Estimate the cost of index scan */
6049  indexScanPath = create_index_path(root, indexInfo,
6050  NIL, NIL, NIL, NIL, NIL,
6051  ForwardScanDirection, false,
6052  NULL, 1.0, false);
6053 
6054  return (seqScanAndSortPath.total_cost < indexScanPath->path.total_cost);
6055 }
#define NIL
Definition: pg_list.h:69
Query * parse
Definition: relation.h:154
Path path
Definition: relation.h:1029
double tuples
Definition: relation.h:564
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:307
List * rtable
Definition: parsenodes.h:135
void cost_qual_eval(QualCost *cost, List *quals, PlannerInfo *root)
Definition: costsize.c:3428
PlannerGlobal * glob
Definition: relation.h:156
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:288
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:561
double rows
Definition: relation.h:527
int maintenance_work_mem
Definition: globals.c:113
Cost total_cost
Definition: relation.h:965
CmdType commandType
Definition: parsenodes.h:110
#define makeNode(_type_)
Definition: nodes.h:557
BlockNumber pages
Definition: relation.h:563
#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:158
RTEKind rtekind
Definition: parsenodes.h:929
int width
Definition: relation.h:885
MemoryContext planner_cxt
Definition: relation.h:286
Oid indexoid
Definition: relation.h:630
#define RELKIND_RELATION
Definition: pg_class.h:160
struct PathTarget * reltarget
Definition: relation.h:535
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:946
double Cost
Definition: nodes.h:639
List * indexprs
Definition: relation.h:652
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:1618
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 996 of file planner.c.

References EXPRKIND_PHV, and preprocess_expression().

Referenced by extract_lateral_references().

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

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

2426 {
2427  if (rte->rtekind != RTE_RELATION)
2428  {
2429  /* If it's not a table at all, use ROW_MARK_COPY */
2430  return ROW_MARK_COPY;
2431  }
2432  else if (rte->relkind == RELKIND_FOREIGN_TABLE)
2433  {
2434  /* Let the FDW select the rowmark type, if it wants to */
2435  FdwRoutine *fdwroutine = GetFdwRoutineByRelId(rte->relid);
2436 
2437  if (fdwroutine->GetForeignRowMarkType != NULL)
2438  return fdwroutine->GetForeignRowMarkType(rte, strength);
2439  /* Otherwise, use ROW_MARK_COPY by default */
2440  return ROW_MARK_COPY;
2441  }
2442  else
2443  {
2444  /* Regular table, apply the appropriate lock type */
2445  switch (strength)
2446  {
2447  case LCS_NONE:
2448 
2449  /*
2450  * We don't need a tuple lock, only the ability to re-fetch
2451  * the row.
2452  */
2453  return ROW_MARK_REFERENCE;
2454  break;
2455  case LCS_FORKEYSHARE:
2456  return ROW_MARK_KEYSHARE;
2457  break;
2458  case LCS_FORSHARE:
2459  return ROW_MARK_SHARE;
2460  break;
2461  case LCS_FORNOKEYUPDATE:
2462  return ROW_MARK_NOKEYEXCLUSIVE;
2463  break;
2464  case LCS_FORUPDATE:
2465  return ROW_MARK_EXCLUSIVE;
2466  break;
2467  }
2468  elog(ERROR, "unrecognized LockClauseStrength %d", (int) strength);
2469  return ROW_MARK_EXCLUSIVE; /* keep compiler quiet */
2470  }
2471 }
#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:929
#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::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->relationOids = NIL;
244  glob->invalItems = NIL;
245  glob->nParamExec = 0;
246  glob->lastPHId = 0;
247  glob->lastRowMarkId = 0;
248  glob->lastPlanNodeId = 0;
249  glob->transientPlan = false;
250  glob->dependsOnRole = false;
251 
252  /*
253  * Assess whether it's feasible to use parallel mode for this query. We
254  * can't do this in a standalone backend, or if the command will try to
255  * modify any data, or if this is a cursor operation, or if GUCs are set
256  * to values that don't permit parallelism, or if parallel-unsafe
257  * functions are present in the query tree.
258  *
259  * For now, we don't try to use parallel mode if we're running inside a
260  * parallel worker. We might eventually be able to relax this
261  * restriction, but for now it seems best not to have parallel workers
262  * trying to create their own parallel workers.
263  *
264  * We can't use parallelism in serializable mode because the predicate
265  * locking code is not parallel-aware. It's not catastrophic if someone
266  * tries to run a parallel plan in serializable mode; it just won't get
267  * any workers and will run serially. But it seems like a good heuristic
268  * to assume that the same serialization level will be in effect at plan
269  * time and execution time, so don't generate a parallel plan if we're in
270  * serializable mode.
271  */
272  if ((cursorOptions & CURSOR_OPT_PARALLEL_OK) != 0 &&
275  parse->commandType == CMD_SELECT &&
276  !parse->hasModifyingCTE &&
278  !IsParallelWorker() &&
280  {
281  /* all the cheap tests pass, so scan the query tree */
282  glob->maxParallelHazard = max_parallel_hazard(parse);
284  }
285  else
286  {
287  /* skip the query tree scan, just assume it's unsafe */
289  glob->parallelModeOK = false;
290  }
291 
292  /*
293  * glob->parallelModeNeeded should tell us whether it's necessary to
294  * impose the parallel mode restrictions, but we don't actually want to
295  * impose them unless we choose a parallel plan, so it is normally set
296  * only if a parallel plan is chosen (see create_gather_plan). That way,
297  * people who mislabel their functions but don't use parallelism anyway
298  * aren't harmed. But when force_parallel_mode is set, we enable the
299  * restrictions whenever possible for testing purposes.
300  */
301  glob->parallelModeNeeded = glob->parallelModeOK &&
303 
304  /* Determine what fraction of the plan is likely to be scanned */
305  if (cursorOptions & CURSOR_OPT_FAST_PLAN)
306  {
307  /*
308  * We have no real idea how many tuples the user will ultimately FETCH
309  * from a cursor, but it is often the case that he doesn't want 'em
310  * all, or would prefer a fast-start plan anyway so that he can
311  * process some of the tuples sooner. Use a GUC parameter to decide
312  * what fraction to optimize for.
313  */
314  tuple_fraction = cursor_tuple_fraction;
315 
316  /*
317  * We document cursor_tuple_fraction as simply being a fraction, which
318  * means the edge cases 0 and 1 have to be treated specially here. We
319  * convert 1 to 0 ("all the tuples") and 0 to a very small fraction.
320  */
321  if (tuple_fraction >= 1.0)
322  tuple_fraction = 0.0;
323  else if (tuple_fraction <= 0.0)
324  tuple_fraction = 1e-10;
325  }
326  else
327  {
328  /* Default assumption is we need all the tuples */
329  tuple_fraction = 0.0;
330  }
331 
332  /* primary planning entry point (may recurse for subqueries) */
333  root = subquery_planner(glob, parse, NULL,
334  false, tuple_fraction);
335 
336  /* Select best Path and turn it into a Plan */
337  final_rel = fetch_upper_rel(root, UPPERREL_FINAL, NULL);
338  best_path = get_cheapest_fractional_path(final_rel, tuple_fraction);
339 
340  top_plan = create_plan(root, best_path);
341 
342  /*
343  * If creating a plan for a scrollable cursor, make sure it can run
344  * backwards on demand. Add a Material node at the top at need.
345  */
346  if (cursorOptions & CURSOR_OPT_SCROLL)
347  {
348  if (!ExecSupportsBackwardScan(top_plan))
349  top_plan = materialize_finished_plan(top_plan);
350  }
351 
352  /*
353  * Optionally add a Gather node for testing purposes, provided this is
354  * actually a safe thing to do.
355  */
357  {
358  Gather *gather = makeNode(Gather);
359 
360  gather->plan.targetlist = top_plan->targetlist;
361  gather->plan.qual = NIL;
362  gather->plan.lefttree = top_plan;
363  gather->plan.righttree = NULL;
364  gather->num_workers = 1;
365  gather->single_copy = true;
367 
368  /*
369  * Ideally we'd use cost_gather here, but setting up dummy path data
370  * to satisfy it doesn't seem much cleaner than knowing what it does.
371  */
372  gather->plan.startup_cost = top_plan->startup_cost +
374  gather->plan.total_cost = top_plan->total_cost +
376  gather->plan.plan_rows = top_plan->plan_rows;
377  gather->plan.plan_width = top_plan->plan_width;
378  gather->plan.parallel_aware = false;
379  gather->plan.parallel_safe = false;
380 
381  /* use parallel mode for parallel plans. */
382  root->glob->parallelModeNeeded = true;
383 
384  top_plan = &gather->plan;
385  }
386 
387  /*
388  * If any Params were generated, run through the plan tree and compute
389  * each plan node's extParam/allParam sets. Ideally we'd merge this into
390  * set_plan_references' tree traversal, but for now it has to be separate
391  * because we need to visit subplans before not after main plan.
392  */
393  if (glob->nParamExec > 0)
394  {
395  Assert(list_length(glob->subplans) == list_length(glob->subroots));
396  forboth(lp, glob->subplans, lr, glob->subroots)
397  {
398  Plan *subplan = (Plan *) lfirst(lp);
399  PlannerInfo *subroot = (PlannerInfo *) lfirst(lr);
400 
401  SS_finalize_plan(subroot, subplan);
402  }
403  SS_finalize_plan(root, top_plan);
404  }
405 
406  /* final cleanup of the plan */
407  Assert(glob->finalrtable == NIL);
408  Assert(glob->finalrowmarks == NIL);
409  Assert(glob->resultRelations == NIL);
411  top_plan = set_plan_references(root, top_plan);
412  /* ... and the subplans (both regular subplans and initplans) */
413  Assert(list_length(glob->subplans) == list_length(glob->subroots));
414  forboth(lp, glob->subplans, lr, glob->subroots)
415  {
416  Plan *subplan = (Plan *) lfirst(lp);
417  PlannerInfo *subroot = (PlannerInfo *) lfirst(lr);
418 
419  lfirst(lp) = set_plan_references(subroot, subplan);
420  }
421 
422  /* build the PlannedStmt result */
423  result = makeNode(PlannedStmt);
424 
425  result->commandType = parse->commandType;
426  result->queryId = parse->queryId;
427  result->hasReturning = (parse->returningList != NIL);
428  result->hasModifyingCTE = parse->hasModifyingCTE;
429  result->canSetTag = parse->canSetTag;
430  result->transientPlan = glob->transientPlan;
431  result->dependsOnRole = glob->dependsOnRole;
432  result->parallelModeNeeded = glob->parallelModeNeeded;
433  result->planTree = top_plan;
434  result->rtable = glob->finalrtable;
435  result->resultRelations = glob->resultRelations;
437  result->subplans = glob->subplans;
438  result->rewindPlanIDs = glob->rewindPlanIDs;
439  result->rowMarks = glob->finalrowmarks;
440  result->relationOids = glob->relationOids;
441  result->invalItems = glob->invalItems;
442  result->nParamExec = glob->nParamExec;
443  /* utilityStmt should be null, but we might as well copy it */
444  result->utilityStmt = parse->utilityStmt;
445  result->stmt_location = parse->stmt_location;
446  result->stmt_len = parse->stmt_len;
447 
448  return result;
449 }
char maxParallelHazard
Definition: relation.h:132
bool dependsOnRole
Definition: plannodes.h:57
#define NIL
Definition: pg_list.h:69
List * qual
Definition: plannodes.h:135
uint32 queryId
Definition: parsenodes.h:114
double plan_rows
Definition: plannodes.h:121
uint32 queryId
Definition: plannodes.h:47
#define forboth(cell1, list1, cell2, list2)
Definition: pg_list.h:180
int stmt_location
Definition: parsenodes.h:180
List * nonleafResultRelations
Definition: plannodes.h:69
List * relationOids
Definition: plannodes.h:78
int lastPlanNodeId
Definition: relation.h:122
List * resultRelations
Definition: relation.h:108
double parallel_setup_cost
Definition: costsize.c:110
return result
Definition: formatting.c:1618
Node * utilityStmt
Definition: parsenodes.h:118
bool transientPlan
Definition: plannodes.h:55
int stmt_len
Definition: plannodes.h:88
char max_parallel_hazard(Query *parse)
Definition: clauses.c:1054
struct Plan * planTree
Definition: plannodes.h:61
List * invalItems
Definition: plannodes.h:80
Plan * create_plan(PlannerInfo *root, Path *best_path)
Definition: createplan.c:305
bool dependsOnRole
Definition: relation.h:126
int nParamExec
Definition: plannodes.h:82
struct Plan * righttree
Definition: plannodes.h:137
bool parallelModeNeeded
Definition: relation.h:130
Plan plan
Definition: plannodes.h:823
bool single_copy
Definition: plannodes.h:825
bool parallelModeOK
Definition: relation.h:128
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:87
List * subplans
Definition: relation.h:98
Cost startup_cost
Definition: plannodes.h:115
PlannerGlobal * glob
Definition: relation.h:156
bool IsUnderPostmaster
Definition: globals.c:100
bool hasReturning
Definition: plannodes.h:49
Plan * materialize_finished_plan(Plan *subplan)
Definition: createplan.c:5977
Node * utilityStmt
Definition: plannodes.h:84
int dynamic_shared_memory_type
Definition: dsm_impl.c:112
bool parallel_aware
Definition: plannodes.h:127
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:5490
List * invalItems
Definition: relation.h:114
bool canSetTag
Definition: plannodes.h:53
CmdType commandType
Definition: plannodes.h:45
#define CURSOR_OPT_FAST_PLAN
Definition: parsenodes.h:2600
bool ExecSupportsBackwardScan(Plan *node)
Definition: execAmi.c:456
Index lastPHId
Definition: relation.h:118
List * rowMarks
Definition: plannodes.h:76
int num_workers
Definition: plannodes.h:824
CmdType commandType
Definition: parsenodes.h:110
#define makeNode(_type_)
Definition: nodes.h:557
List * subplans
Definition: plannodes.h:71
List * nonleafResultRelations
Definition: relation.h:110
int plan_width
Definition: plannodes.h:122
#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:675
#define lfirst(lc)
Definition: pg_list.h:106
Bitmapset * rewindPlanIDs
Definition: plannodes.h:74
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:112
List * subroots
Definition: relation.h:100
List * rtable
Definition: plannodes.h:63
struct Plan * lefttree
Definition: plannodes.h:136
List * targetlist
Definition: plannodes.h:134
bool invisible
Definition: plannodes.h:826
e
Definition: preproc-init.c:82
List * finalrtable
Definition: relation.h:104
#define CURSOR_OPT_PARALLEL_OK
Definition: parsenodes.h:2603
Index lastRowMarkId
Definition: relation.h:120
#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:2595
Cost total_cost
Definition: plannodes.h:116
int nParamExec
Definition: relation.h:116
bool hasModifyingCTE
Definition: parsenodes.h:129
bool parallel_safe
Definition: plannodes.h:128
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:181
PlannerInfo * subquery_planner(PlannerGlobal *glob, Query *parse, PlannerInfo *parent_root, bool hasRecursion, double tuple_fraction)
Definition: planner.c:481
Definition: relation.h:946
Path * get_cheapest_fractional_path(RelOptInfo *rel, double tuple_fraction)
Definition: planner.c:5775
bool transientPlan
Definition: relation.h:124
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 481 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().

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

Variable Documentation

Definition at line 66 of file planner.c.

Referenced by planner().