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 5927 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().

5928 {
5929  Node *result;
5930 
5931  /*
5932  * Convert named-argument function calls, insert default arguments and
5933  * simplify constant subexprs
5934  */
5935  result = eval_const_expressions(NULL, (Node *) expr);
5936 
5937  /* Fill in opfuncid values if missing */
5938  fix_opfuncids(result);
5939 
5940  return (Expr *) result;
5941 }
void fix_opfuncids(Node *node)
Definition: nodeFuncs.c:1594
Definition: nodes.h:506
Node * eval_const_expressions(PlannerInfo *root, Node *node)
Definition: clauses.c:2366
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 5774 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().

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

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

6065 {
6066  List *result = NIL;
6067  ListCell *l;
6068 
6069  foreach(l, root->pcinfo_list)
6070  {
6072 
6073  if (pc->parent_relid == rti)
6074  {
6075  result = pc->child_rels;
6076  break;
6077  }
6078  }
6079 
6080  /* The root partitioned table is included as a child rel */
6081  Assert(list_length(result) >= 1);
6082 
6083  return result;
6084 }
#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 2290 of file planner.c.

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

2291 {
2292  if (IsA(plan, Result))
2293  {
2294  List *rcqual = (List *) ((Result *) plan)->resconstantqual;
2295 
2296  if (list_length(rcqual) == 1)
2297  {
2298  Const *constqual = (Const *) linitial(rcqual);
2299 
2300  if (constqual && IsA(constqual, Const))
2301  {
2302  if (!constqual->constisnull &&
2303  !DatumGetBool(constqual->constvalue))
2304  return true;
2305  }
2306  }
2307  }
2308  return false;
2309 }
Datum constvalue
Definition: primnodes.h:196
#define IsA(nodeptr, _type_)
Definition: nodes.h:557
#define linitial(l)
Definition: pg_list.h:110
#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 5223 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().

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

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

References EXPRKIND_PHV, and preprocess_expression().

Referenced by extract_lateral_references().

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

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

2427 {
2428  if (rte->rtekind != RTE_RELATION)
2429  {
2430  /* If it's not a table at all, use ROW_MARK_COPY */
2431  return ROW_MARK_COPY;
2432  }
2433  else if (rte->relkind == RELKIND_FOREIGN_TABLE)
2434  {
2435  /* Let the FDW select the rowmark type, if it wants to */
2436  FdwRoutine *fdwroutine = GetFdwRoutineByRelId(rte->relid);
2437 
2438  if (fdwroutine->GetForeignRowMarkType != NULL)
2439  return fdwroutine->GetForeignRowMarkType(rte, strength);
2440  /* Otherwise, use ROW_MARK_COPY by default */
2441  return ROW_MARK_COPY;
2442  }
2443  else
2444  {
2445  /* Regular table, apply the appropriate lock type */
2446  switch (strength)
2447  {
2448  case LCS_NONE:
2449 
2450  /*
2451  * We don't need a tuple lock, only the ability to re-fetch
2452  * the row.
2453  */
2454  return ROW_MARK_REFERENCE;
2455  break;
2456  case LCS_FORKEYSHARE:
2457  return ROW_MARK_KEYSHARE;
2458  break;
2459  case LCS_FORSHARE:
2460  return ROW_MARK_SHARE;
2461  break;
2462  case LCS_FORNOKEYUPDATE:
2463  return ROW_MARK_NOKEYEXCLUSIVE;
2464  break;
2465  case LCS_FORUPDATE:
2466  return ROW_MARK_EXCLUSIVE;
2467  break;
2468  }
2469  elog(ERROR, "unrecognized LockClauseStrength %d", (int) strength);
2470  return ROW_MARK_EXCLUSIVE; /* keep compiler quiet */
2471  }
2472 }
#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:916
#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, Path::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. (Note: we assume adding a Material node
355  * above did not change the parallel safety of the plan, so we can still
356  * rely on best_path->parallel_safe.)
357  */
359  {
360  Gather *gather = makeNode(Gather);
361 
362  gather->plan.targetlist = top_plan->targetlist;
363  gather->plan.qual = NIL;
364  gather->plan.lefttree = top_plan;
365  gather->plan.righttree = NULL;
366  gather->num_workers = 1;
367  gather->single_copy = true;
369 
370  /*
371  * Ideally we'd use cost_gather here, but setting up dummy path data
372  * to satisfy it doesn't seem much cleaner than knowing what it does.
373  */
374  gather->plan.startup_cost = top_plan->startup_cost +
376  gather->plan.total_cost = top_plan->total_cost +
378  gather->plan.plan_rows = top_plan->plan_rows;
379  gather->plan.plan_width = top_plan->plan_width;
380  gather->plan.parallel_aware = false;
381 
382  /* use parallel mode for parallel plans. */
383  root->glob->parallelModeNeeded = true;
384 
385  top_plan = &gather->plan;
386  }
387 
388  /*
389  * If any Params were generated, run through the plan tree and compute
390  * each plan node's extParam/allParam sets. Ideally we'd merge this into
391  * set_plan_references' tree traversal, but for now it has to be separate
392  * because we need to visit subplans before not after main plan.
393  */
394  if (glob->nParamExec > 0)
395  {
396  Assert(list_length(glob->subplans) == list_length(glob->subroots));
397  forboth(lp, glob->subplans, lr, glob->subroots)
398  {
399  Plan *subplan = (Plan *) lfirst(lp);
400  PlannerInfo *subroot = (PlannerInfo *) lfirst(lr);
401 
402  SS_finalize_plan(subroot, subplan);
403  }
404  SS_finalize_plan(root, top_plan);
405  }
406 
407  /* final cleanup of the plan */
408  Assert(glob->finalrtable == NIL);
409  Assert(glob->finalrowmarks == NIL);
410  Assert(glob->resultRelations == NIL);
412  top_plan = set_plan_references(root, top_plan);
413  /* ... and the subplans (both regular subplans and initplans) */
414  Assert(list_length(glob->subplans) == list_length(glob->subroots));
415  forboth(lp, glob->subplans, lr, glob->subroots)
416  {
417  Plan *subplan = (Plan *) lfirst(lp);
418  PlannerInfo *subroot = (PlannerInfo *) lfirst(lr);
419 
420  lfirst(lp) = set_plan_references(subroot, subplan);
421  }
422 
423  /* build the PlannedStmt result */
424  result = makeNode(PlannedStmt);
425 
426  result->commandType = parse->commandType;
427  result->queryId = parse->queryId;
428  result->hasReturning = (parse->returningList != NIL);
429  result->hasModifyingCTE = parse->hasModifyingCTE;
430  result->canSetTag = parse->canSetTag;
431  result->transientPlan = glob->transientPlan;
432  result->dependsOnRole = glob->dependsOnRole;
433  result->parallelModeNeeded = glob->parallelModeNeeded;
434  result->planTree = top_plan;
435  result->rtable = glob->finalrtable;
436  result->resultRelations = glob->resultRelations;
438  result->subplans = glob->subplans;
439  result->rewindPlanIDs = glob->rewindPlanIDs;
440  result->rowMarks = glob->finalrowmarks;
441  result->relationOids = glob->relationOids;
442  result->invalItems = glob->invalItems;
443  result->nParamExec = glob->nParamExec;
444  /* utilityStmt should be null, but we might as well copy it */
445  result->utilityStmt = parse->utilityStmt;
446  result->stmt_location = parse->stmt_location;
447  result->stmt_len = parse->stmt_len;
448 
449  return result;
450 }
char maxParallelHazard
Definition: relation.h:132
bool dependsOnRole
Definition: plannodes.h:57
#define NIL
Definition: pg_list.h:69
List * qual
Definition: plannodes.h:133
uint32 queryId
Definition: parsenodes.h:107
double plan_rows
Definition: plannodes.h:120
uint32 queryId
Definition: plannodes.h:47
#define forboth(cell1, list1, cell2, list2)
Definition: pg_list.h:174
int stmt_location
Definition: parsenodes.h:171
List * nonleafResultRelations
Definition: plannodes.h:69
List * relationOids
Definition: plannodes.h:77
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:111
bool transientPlan
Definition: plannodes.h:55
int stmt_len
Definition: plannodes.h:87
char max_parallel_hazard(Query *parse)
Definition: clauses.c:1053
struct Plan * planTree
Definition: plannodes.h:61
List * invalItems
Definition: plannodes.h:79
Plan * create_plan(PlannerInfo *root, Path *best_path)
Definition: createplan.c:300
bool dependsOnRole
Definition: relation.h:126
int nParamExec
Definition: plannodes.h:81
struct Plan * righttree
Definition: plannodes.h:135
bool parallelModeNeeded
Definition: relation.h:130
Plan plan
Definition: plannodes.h:803
bool single_copy
Definition: plannodes.h:805
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:895
int stmt_location
Definition: plannodes.h:86
List * subplans
Definition: relation.h:98
Cost startup_cost
Definition: plannodes.h:114
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:5866
Node * utilityStmt
Definition: plannodes.h:83
int dynamic_shared_memory_type
Definition: dsm_impl.c:112
bool parallel_aware
Definition: plannodes.h:126
double cursor_tuple_fraction
Definition: planner.c:62
List * returningList
Definition: parsenodes.h:135
#define IsParallelWorker()
Definition: parallel.h:53
#define PROPARALLEL_UNSAFE
Definition: pg_proc.h:5445
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:2576
bool ExecSupportsBackwardScan(Plan *node)
Definition: execAmi.c:451
Index lastPHId
Definition: relation.h:118
List * rowMarks
Definition: plannodes.h:75
int num_workers
Definition: plannodes.h:804
CmdType commandType
Definition: parsenodes.h:103
#define makeNode(_type_)
Definition: nodes.h:554
List * subplans
Definition: plannodes.h:71
List * nonleafResultRelations
Definition: relation.h:110
int plan_width
Definition: plannodes.h:121
#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:73
bool hasModifyingCTE
Definition: plannodes.h:51
bool parallel_safe
Definition: relation.h:923
bool canSetTag
Definition: parsenodes.h:109
#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:134
List * targetlist
Definition: plannodes.h:132
bool invisible
Definition: plannodes.h:806
e
Definition: preproc-init.c:82
List * finalrtable
Definition: relation.h:104
#define CURSOR_OPT_PARALLEL_OK
Definition: parsenodes.h:2579
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:2571
Cost total_cost
Definition: plannodes.h:115
int nParamExec
Definition: relation.h:116
bool hasModifyingCTE
Definition: parsenodes.h:122
Plan * set_plan_references(PlannerInfo *root, Plan *plan)
Definition: setrefs.c:209
void SS_finalize_plan(PlannerInfo *root, Plan *plan)
Definition: subselect.c:2218
int max_parallel_workers_per_gather
Definition: costsize.c:116
List * finalrowmarks
Definition: relation.h:106
int stmt_len
Definition: parsenodes.h:172
PlannerInfo * subquery_planner(PlannerGlobal *glob, Query *parse, PlannerInfo *parent_root, bool hasRecursion, double tuple_fraction)
Definition: planner.c:482
Definition: relation.h:911
Path * get_cheapest_fractional_path(RelOptInfo *rel, double tuple_fraction)
Definition: planner.c:5774
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 482 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().

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