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

Go to the source code of this file.

Macros

#define DEFAULT_CURSOR_TUPLE_FRACTION   0.1
 

Typedefs

typedef void(* query_pathkeys_callback )(PlannerInfo *root, void *extra)
 

Enumerations

enum  ForceParallelMode { FORCE_PARALLEL_OFF, FORCE_PARALLEL_ON, FORCE_PARALLEL_REGRESS }
 

Functions

RelOptInfoquery_planner (PlannerInfo *root, List *tlist, query_pathkeys_callback qp_callback, void *qp_extra)
 
void preprocess_minmax_aggregates (PlannerInfo *root, List *tlist)
 
Plancreate_plan (PlannerInfo *root, Path *best_path)
 
ForeignScanmake_foreignscan (List *qptlist, List *qpqual, Index scanrelid, List *fdw_exprs, List *fdw_private, List *fdw_scan_tlist, List *fdw_recheck_quals, Plan *outer_plan)
 
Planmaterialize_finished_plan (Plan *subplan)
 
bool is_projection_capable_path (Path *path)
 
bool is_projection_capable_plan (Plan *plan)
 
Sortmake_sort_from_sortclauses (List *sortcls, Plan *lefttree)
 
Aggmake_agg (List *tlist, List *qual, AggStrategy aggstrategy, AggSplit aggsplit, int numGroupCols, AttrNumber *grpColIdx, Oid *grpOperators, List *groupingSets, List *chain, double dNumGroups, Plan *lefttree)
 
Limitmake_limit (Plan *lefttree, Node *limitOffset, Node *limitCount)
 
void add_base_rels_to_query (PlannerInfo *root, Node *jtnode)
 
void build_base_rel_tlists (PlannerInfo *root, List *final_tlist)
 
void add_vars_to_targetlist (PlannerInfo *root, List *vars, Relids where_needed, bool create_new_ph)
 
void find_lateral_references (PlannerInfo *root)
 
void create_lateral_join_info (PlannerInfo *root)
 
Listdeconstruct_jointree (PlannerInfo *root)
 
void distribute_restrictinfo_to_rels (PlannerInfo *root, RestrictInfo *restrictinfo)
 
void process_implied_equality (PlannerInfo *root, Oid opno, Oid collation, Expr *item1, Expr *item2, Relids qualscope, Relids nullable_relids, Index security_level, bool below_outer_join, bool both_const)
 
RestrictInfobuild_implied_join_equality (Oid opno, Oid collation, Expr *item1, Expr *item2, Relids qualscope, Relids nullable_relids, Index security_level)
 
void match_foreign_keys_to_quals (PlannerInfo *root)
 
Listremove_useless_joins (PlannerInfo *root, List *joinlist)
 
bool query_supports_distinctness (Query *query)
 
bool query_is_distinct_for (Query *query, List *colnos, List *opids)
 
Planset_plan_references (PlannerInfo *root, Plan *plan)
 
void record_plan_function_dependency (PlannerInfo *root, Oid funcid)
 
void extract_query_dependencies (Node *query, List **relationOids, List **invalItems, bool *hasRowSecurity)
 

Variables

double cursor_tuple_fraction
 
int force_parallel_mode
 
int from_collapse_limit
 
int join_collapse_limit
 

Macro Definition Documentation

#define DEFAULT_CURSOR_TUPLE_FRACTION   0.1

Definition at line 29 of file planmain.h.

Typedef Documentation

typedef void(* query_pathkeys_callback)(PlannerInfo *root, void *extra)

Definition at line 34 of file planmain.h.

Enumeration Type Documentation

Enumerator
FORCE_PARALLEL_OFF 
FORCE_PARALLEL_ON 
FORCE_PARALLEL_REGRESS 

Definition at line 21 of file planmain.h.

Function Documentation

void add_base_rels_to_query ( PlannerInfo root,
Node jtnode 
)

Definition at line 104 of file initsplan.c.

References add_base_rels_to_query(), build_simple_rel(), elog, ERROR, FromExpr::fromlist, IsA, JoinExpr::larg, lfirst, nodeTag, NULL, JoinExpr::rarg, and RELOPT_BASEREL.

Referenced by add_base_rels_to_query(), and query_planner().

105 {
106  if (jtnode == NULL)
107  return;
108  if (IsA(jtnode, RangeTblRef))
109  {
110  int varno = ((RangeTblRef *) jtnode)->rtindex;
111 
112  (void) build_simple_rel(root, varno, RELOPT_BASEREL);
113  }
114  else if (IsA(jtnode, FromExpr))
115  {
116  FromExpr *f = (FromExpr *) jtnode;
117  ListCell *l;
118 
119  foreach(l, f->fromlist)
120  add_base_rels_to_query(root, lfirst(l));
121  }
122  else if (IsA(jtnode, JoinExpr))
123  {
124  JoinExpr *j = (JoinExpr *) jtnode;
125 
126  add_base_rels_to_query(root, j->larg);
127  add_base_rels_to_query(root, j->rarg);
128  }
129  else
130  elog(ERROR, "unrecognized node type: %d",
131  (int) nodeTag(jtnode));
132 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:560
void add_base_rels_to_query(PlannerInfo *root, Node *jtnode)
Definition: initsplan.c:104
List * fromlist
Definition: primnodes.h:1433
Node * larg
Definition: primnodes.h:1413
#define ERROR
Definition: elog.h:43
RelOptInfo * build_simple_rel(PlannerInfo *root, int relid, RelOptKind reloptkind)
Definition: relnode.c:88
Node * rarg
Definition: primnodes.h:1414
#define NULL
Definition: c.h:226
#define lfirst(lc)
Definition: pg_list.h:106
#define nodeTag(nodeptr)
Definition: nodes.h:514
#define elog
Definition: elog.h:219
void add_vars_to_targetlist ( PlannerInfo root,
List vars,
Relids  where_needed,
bool  create_new_ph 
)

Definition at line 197 of file initsplan.c.

References Assert, RelOptInfo::attr_needed, bms_add_members(), bms_is_empty(), bms_is_subset(), copyObject(), elog, ERROR, PathTarget::exprs, find_base_rel(), find_placeholder_info(), IsA, lappend(), lfirst, RelOptInfo::min_attr, nodeTag, NULL, PlaceHolderInfo::ph_needed, RelOptInfo::relids, RelOptInfo::reltarget, Var::varattno, and Var::varno.

Referenced by build_base_rel_tlists(), distribute_qual_to_rels(), extract_lateral_references(), fix_placeholder_input_needed_levels(), and generate_base_implied_equalities_no_const().

199 {
200  ListCell *temp;
201 
202  Assert(!bms_is_empty(where_needed));
203 
204  foreach(temp, vars)
205  {
206  Node *node = (Node *) lfirst(temp);
207 
208  if (IsA(node, Var))
209  {
210  Var *var = (Var *) node;
211  RelOptInfo *rel = find_base_rel(root, var->varno);
212  int attno = var->varattno;
213 
214  if (bms_is_subset(where_needed, rel->relids))
215  continue;
216  Assert(attno >= rel->min_attr && attno <= rel->max_attr);
217  attno -= rel->min_attr;
218  if (rel->attr_needed[attno] == NULL)
219  {
220  /* Variable not yet requested, so add to rel's targetlist */
221  /* XXX is copyObject necessary here? */
222  rel->reltarget->exprs = lappend(rel->reltarget->exprs,
223  copyObject(var));
224  /* reltarget cost and width will be computed later */
225  }
226  rel->attr_needed[attno] = bms_add_members(rel->attr_needed[attno],
227  where_needed);
228  }
229  else if (IsA(node, PlaceHolderVar))
230  {
231  PlaceHolderVar *phv = (PlaceHolderVar *) node;
232  PlaceHolderInfo *phinfo = find_placeholder_info(root, phv,
233  create_new_ph);
234 
235  phinfo->ph_needed = bms_add_members(phinfo->ph_needed,
236  where_needed);
237  }
238  else
239  elog(ERROR, "unrecognized node type: %d", (int) nodeTag(node));
240  }
241 }
Relids ph_needed
Definition: relation.h:1937
#define IsA(nodeptr, _type_)
Definition: nodes.h:560
Relids * attr_needed
Definition: relation.h:523
Definition: nodes.h:509
AttrNumber varattno
Definition: primnodes.h:146
Definition: primnodes.h:141
void * copyObject(const void *from)
Definition: copyfuncs.c:4475
#define ERROR
Definition: elog.h:43
bool bms_is_subset(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:307
PlaceHolderInfo * find_placeholder_info(PlannerInfo *root, PlaceHolderVar *phv, bool create_new_ph)
Definition: placeholder.c:69
Relids relids
Definition: relation.h:490
List * lappend(List *list, void *datum)
Definition: list.c:128
bool bms_is_empty(const Bitmapset *a)
Definition: bitmapset.c:633
Index varno
Definition: primnodes.h:144
List * exprs
Definition: relation.h:824
#define NULL
Definition: c.h:226
#define Assert(condition)
Definition: c.h:671
#define lfirst(lc)
Definition: pg_list.h:106
#define nodeTag(nodeptr)
Definition: nodes.h:514
#define elog
Definition: elog.h:219
RelOptInfo * find_base_rel(PlannerInfo *root, int relid)
Definition: relnode.c:219
struct PathTarget * reltarget
Definition: relation.h:501
Bitmapset * bms_add_members(Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:725
AttrNumber min_attr
Definition: relation.h:521
void build_base_rel_tlists ( PlannerInfo root,
List final_tlist 
)

Definition at line 150 of file initsplan.c.

References add_vars_to_targetlist(), bms_make_singleton(), Query::havingQual, list_free(), NIL, PlannerInfo::parse, pull_var_clause(), PVC_INCLUDE_PLACEHOLDERS, PVC_RECURSE_AGGREGATES, and PVC_RECURSE_WINDOWFUNCS.

Referenced by query_planner().

151 {
152  List *tlist_vars = pull_var_clause((Node *) final_tlist,
156 
157  if (tlist_vars != NIL)
158  {
159  add_vars_to_targetlist(root, tlist_vars, bms_make_singleton(0), true);
160  list_free(tlist_vars);
161  }
162 
163  /*
164  * If there's a HAVING clause, we'll need the Vars it uses, too. Note
165  * that HAVING can contain Aggrefs but not WindowFuncs.
166  */
167  if (root->parse->havingQual)
168  {
169  List *having_vars = pull_var_clause(root->parse->havingQual,
172 
173  if (having_vars != NIL)
174  {
175  add_vars_to_targetlist(root, having_vars,
176  bms_make_singleton(0), true);
177  list_free(having_vars);
178  }
179  }
180 }
#define NIL
Definition: pg_list.h:69
Query * parse
Definition: relation.h:152
#define PVC_RECURSE_AGGREGATES
Definition: var.h:21
Definition: nodes.h:509
List * pull_var_clause(Node *node, int flags)
Definition: var.c:535
void add_vars_to_targetlist(PlannerInfo *root, List *vars, Relids where_needed, bool create_new_ph)
Definition: initsplan.c:197
#define PVC_INCLUDE_PLACEHOLDERS
Definition: var.h:24
Bitmapset * bms_make_singleton(int x)
Definition: bitmapset.c:178
#define PVC_RECURSE_WINDOWFUNCS
Definition: var.h:23
void list_free(List *list)
Definition: list.c:1133
Node * havingQual
Definition: parsenodes.h:141
Definition: pg_list.h:45
RestrictInfo* build_implied_join_equality ( Oid  opno,
Oid  collation,
Expr item1,
Expr item2,
Relids  qualscope,
Relids  nullable_relids,
Index  security_level 
)

Definition at line 2352 of file initsplan.c.

References BOOLOID, check_hashjoinable(), check_mergejoinable(), copyObject(), InvalidOid, make_opclause(), make_restrictinfo(), and NULL.

Referenced by create_join_clause(), reconsider_full_join_clause(), and reconsider_outer_join_clause().

2359 {
2360  RestrictInfo *restrictinfo;
2361  Expr *clause;
2362 
2363  /*
2364  * Build the new clause. Copy to ensure it shares no substructure with
2365  * original (this is necessary in case there are subselects in there...)
2366  */
2367  clause = make_opclause(opno,
2368  BOOLOID, /* opresulttype */
2369  false, /* opretset */
2370  (Expr *) copyObject(item1),
2371  (Expr *) copyObject(item2),
2372  InvalidOid,
2373  collation);
2374 
2375  /*
2376  * Build the RestrictInfo node itself.
2377  */
2378  restrictinfo = make_restrictinfo(clause,
2379  true, /* is_pushed_down */
2380  false, /* outerjoin_delayed */
2381  false, /* pseudoconstant */
2382  security_level, /* security_level */
2383  qualscope, /* required_relids */
2384  NULL, /* outer_relids */
2385  nullable_relids); /* nullable_relids */
2386 
2387  /* Set mergejoinability/hashjoinability flags */
2388  check_mergejoinable(restrictinfo);
2389  check_hashjoinable(restrictinfo);
2390 
2391  return restrictinfo;
2392 }
RestrictInfo * make_restrictinfo(Expr *clause, bool is_pushed_down, bool outerjoin_delayed, bool pseudoconstant, Index security_level, Relids required_relids, Relids outer_relids, Relids nullable_relids)
Definition: restrictinfo.c:57
Expr * make_opclause(Oid opno, Oid opresulttype, bool opretset, Expr *leftop, Expr *rightop, Oid opcollid, Oid inputcollid)
Definition: clauses.c:171
void * copyObject(const void *from)
Definition: copyfuncs.c:4475
#define InvalidOid
Definition: postgres_ext.h:36
#define NULL
Definition: c.h:226
static void check_mergejoinable(RestrictInfo *restrictinfo)
Definition: initsplan.c:2579
#define BOOLOID
Definition: pg_type.h:288
static void check_hashjoinable(RestrictInfo *restrictinfo)
Definition: initsplan.c:2616
void create_lateral_join_info ( PlannerInfo root)

Definition at line 415 of file initsplan.c.

References PlannerInfo::append_rel_list, Assert, bms_add_member(), bms_add_members(), bms_copy(), bms_get_singleton_member(), bms_is_empty(), bms_is_member(), bms_next_member(), AppendRelInfo::child_relid, RelOptInfo::direct_lateral_relids, find_base_rel(), find_placeholder_info(), PlannerInfo::hasLateralRTEs, RangeTblEntry::inh, IsA, RelOptInfo::lateral_referencers, RelOptInfo::lateral_relids, RelOptInfo::lateral_vars, lfirst, NULL, AppendRelInfo::parent_relid, PlaceHolderInfo::ph_eval_at, PlaceHolderInfo::ph_lateral, PlannerInfo::placeholder_list, RelOptInfo::relid, RELOPT_BASEREL, RELOPT_OTHER_MEMBER_REL, RelOptInfo::reloptkind, PlannerInfo::simple_rel_array, PlannerInfo::simple_rel_array_size, PlannerInfo::simple_rte_array, and Var::varno.

Referenced by query_planner().

416 {
417  bool found_laterals = false;
418  Index rti;
419  ListCell *lc;
420 
421  /* We need do nothing if the query contains no LATERAL RTEs */
422  if (!root->hasLateralRTEs)
423  return;
424 
425  /*
426  * Examine all baserels (the rel array has been set up by now).
427  */
428  for (rti = 1; rti < root->simple_rel_array_size; rti++)
429  {
430  RelOptInfo *brel = root->simple_rel_array[rti];
431  Relids lateral_relids;
432 
433  /* there may be empty slots corresponding to non-baserel RTEs */
434  if (brel == NULL)
435  continue;
436 
437  Assert(brel->relid == rti); /* sanity check on array */
438 
439  /* ignore RTEs that are "other rels" */
440  if (brel->reloptkind != RELOPT_BASEREL)
441  continue;
442 
443  lateral_relids = NULL;
444 
445  /* consider each laterally-referenced Var or PHV */
446  foreach(lc, brel->lateral_vars)
447  {
448  Node *node = (Node *) lfirst(lc);
449 
450  if (IsA(node, Var))
451  {
452  Var *var = (Var *) node;
453 
454  found_laterals = true;
455  lateral_relids = bms_add_member(lateral_relids,
456  var->varno);
457  }
458  else if (IsA(node, PlaceHolderVar))
459  {
460  PlaceHolderVar *phv = (PlaceHolderVar *) node;
461  PlaceHolderInfo *phinfo = find_placeholder_info(root, phv,
462  false);
463 
464  found_laterals = true;
465  lateral_relids = bms_add_members(lateral_relids,
466  phinfo->ph_eval_at);
467  }
468  else
469  Assert(false);
470  }
471 
472  /* We now have all the simple lateral refs from this rel */
473  brel->direct_lateral_relids = lateral_relids;
474  brel->lateral_relids = bms_copy(lateral_relids);
475  }
476 
477  /*
478  * Now check for lateral references within PlaceHolderVars, and mark their
479  * eval_at rels as having lateral references to the source rels.
480  *
481  * For a PHV that is due to be evaluated at a baserel, mark its source(s)
482  * as direct lateral dependencies of the baserel (adding onto the ones
483  * recorded above). If it's due to be evaluated at a join, mark its
484  * source(s) as indirect lateral dependencies of each baserel in the join,
485  * ie put them into lateral_relids but not direct_lateral_relids. This is
486  * appropriate because we can't put any such baserel on the outside of a
487  * join to one of the PHV's lateral dependencies, but on the other hand we
488  * also can't yet join it directly to the dependency.
489  */
490  foreach(lc, root->placeholder_list)
491  {
492  PlaceHolderInfo *phinfo = (PlaceHolderInfo *) lfirst(lc);
493  Relids eval_at = phinfo->ph_eval_at;
494  int varno;
495 
496  if (phinfo->ph_lateral == NULL)
497  continue; /* PHV is uninteresting if no lateral refs */
498 
499  found_laterals = true;
500 
501  if (bms_get_singleton_member(eval_at, &varno))
502  {
503  /* Evaluation site is a baserel */
504  RelOptInfo *brel = find_base_rel(root, varno);
505 
506  brel->direct_lateral_relids =
508  phinfo->ph_lateral);
509  brel->lateral_relids =
511  phinfo->ph_lateral);
512  }
513  else
514  {
515  /* Evaluation site is a join */
516  varno = -1;
517  while ((varno = bms_next_member(eval_at, varno)) >= 0)
518  {
519  RelOptInfo *brel = find_base_rel(root, varno);
520 
522  phinfo->ph_lateral);
523  }
524  }
525  }
526 
527  /*
528  * If we found no actual lateral references, we're done; but reset the
529  * hasLateralRTEs flag to avoid useless work later.
530  */
531  if (!found_laterals)
532  {
533  root->hasLateralRTEs = false;
534  return;
535  }
536 
537  /*
538  * Calculate the transitive closure of the lateral_relids sets, so that
539  * they describe both direct and indirect lateral references. If relation
540  * X references Y laterally, and Y references Z laterally, then we will
541  * have to scan X on the inside of a nestloop with Z, so for all intents
542  * and purposes X is laterally dependent on Z too.
543  *
544  * This code is essentially Warshall's algorithm for transitive closure.
545  * The outer loop considers each baserel, and propagates its lateral
546  * dependencies to those baserels that have a lateral dependency on it.
547  */
548  for (rti = 1; rti < root->simple_rel_array_size; rti++)
549  {
550  RelOptInfo *brel = root->simple_rel_array[rti];
551  Relids outer_lateral_relids;
552  Index rti2;
553 
554  if (brel == NULL || brel->reloptkind != RELOPT_BASEREL)
555  continue;
556 
557  /* need not consider baserel further if it has no lateral refs */
558  outer_lateral_relids = brel->lateral_relids;
559  if (outer_lateral_relids == NULL)
560  continue;
561 
562  /* else scan all baserels */
563  for (rti2 = 1; rti2 < root->simple_rel_array_size; rti2++)
564  {
565  RelOptInfo *brel2 = root->simple_rel_array[rti2];
566 
567  if (brel2 == NULL || brel2->reloptkind != RELOPT_BASEREL)
568  continue;
569 
570  /* if brel2 has lateral ref to brel, propagate brel's refs */
571  if (bms_is_member(rti, brel2->lateral_relids))
573  outer_lateral_relids);
574  }
575  }
576 
577  /*
578  * Now that we've identified all lateral references, mark each baserel
579  * with the set of relids of rels that reference it laterally (possibly
580  * indirectly) --- that is, the inverse mapping of lateral_relids.
581  */
582  for (rti = 1; rti < root->simple_rel_array_size; rti++)
583  {
584  RelOptInfo *brel = root->simple_rel_array[rti];
585  Relids lateral_relids;
586  int rti2;
587 
588  if (brel == NULL || brel->reloptkind != RELOPT_BASEREL)
589  continue;
590 
591  /* Nothing to do at rels with no lateral refs */
592  lateral_relids = brel->lateral_relids;
593  if (lateral_relids == NULL)
594  continue;
595 
596  /*
597  * We should not have broken the invariant that lateral_relids is
598  * exactly NULL if empty.
599  */
600  Assert(!bms_is_empty(lateral_relids));
601 
602  /* Also, no rel should have a lateral dependency on itself */
603  Assert(!bms_is_member(rti, lateral_relids));
604 
605  /* Mark this rel's referencees */
606  rti2 = -1;
607  while ((rti2 = bms_next_member(lateral_relids, rti2)) >= 0)
608  {
609  RelOptInfo *brel2 = root->simple_rel_array[rti2];
610 
611  Assert(brel2 != NULL && brel2->reloptkind == RELOPT_BASEREL);
612  brel2->lateral_referencers =
613  bms_add_member(brel2->lateral_referencers, rti);
614  }
615  }
616 
617  /*
618  * Lastly, propagate lateral_relids and lateral_referencers from appendrel
619  * parent rels to their child rels. We intentionally give each child rel
620  * the same minimum parameterization, even though it's quite possible that
621  * some don't reference all the lateral rels. This is because any append
622  * path for the parent will have to have the same parameterization for
623  * every child anyway, and there's no value in forcing extra
624  * reparameterize_path() calls. Similarly, a lateral reference to the
625  * parent prevents use of otherwise-movable join rels for each child.
626  */
627  for (rti = 1; rti < root->simple_rel_array_size; rti++)
628  {
629  RelOptInfo *brel = root->simple_rel_array[rti];
630 
631  if (brel == NULL || brel->reloptkind != RELOPT_BASEREL)
632  continue;
633 
634  if (root->simple_rte_array[rti]->inh)
635  {
636  foreach(lc, root->append_rel_list)
637  {
638  AppendRelInfo *appinfo = (AppendRelInfo *) lfirst(lc);
639  RelOptInfo *childrel;
640 
641  if (appinfo->parent_relid != rti)
642  continue;
643  childrel = root->simple_rel_array[appinfo->child_relid];
645  Assert(childrel->direct_lateral_relids == NULL);
647  Assert(childrel->lateral_relids == NULL);
648  childrel->lateral_relids = brel->lateral_relids;
649  Assert(childrel->lateral_referencers == NULL);
650  childrel->lateral_referencers = brel->lateral_referencers;
651  }
652  }
653  }
654 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:560
Bitmapset * bms_copy(const Bitmapset *a)
Definition: bitmapset.c:110
Relids ph_eval_at
Definition: relation.h:1935
RelOptKind reloptkind
Definition: relation.h:487
int bms_next_member(const Bitmapset *a, int prevbit)
Definition: bitmapset.c:907
Definition: nodes.h:509
bool bms_get_singleton_member(const Bitmapset *a, int *member)
Definition: bitmapset.c:539
Definition: primnodes.h:141
struct RelOptInfo ** simple_rel_array
Definition: relation.h:176
Relids lateral_relids
Definition: relation.h:515
bool hasLateralRTEs
Definition: relation.h:295
PlaceHolderInfo * find_placeholder_info(PlannerInfo *root, PlaceHolderVar *phv, bool create_new_ph)
Definition: placeholder.c:69
int simple_rel_array_size
Definition: relation.h:177
Index relid
Definition: relation.h:518
RangeTblEntry ** simple_rte_array
Definition: relation.h:185
Relids lateral_referencers
Definition: relation.h:526
bool bms_is_empty(const Bitmapset *a)
Definition: bitmapset.c:633
Index varno
Definition: primnodes.h:144
Relids direct_lateral_relids
Definition: relation.h:514
List * append_rel_list
Definition: relation.h:249
Relids ph_lateral
Definition: relation.h:1936
unsigned int Index
Definition: c.h:362
#define NULL
Definition: c.h:226
#define Assert(condition)
Definition: c.h:671
#define lfirst(lc)
Definition: pg_list.h:106
List * lateral_vars
Definition: relation.h:525
Bitmapset * bms_add_member(Bitmapset *a, int x)
Definition: bitmapset.c:668
List * placeholder_list
Definition: relation.h:253
Index child_relid
Definition: relation.h:1866
RelOptInfo * find_base_rel(PlannerInfo *root, int relid)
Definition: relnode.c:219
Index parent_relid
Definition: relation.h:1865
bool bms_is_member(int x, const Bitmapset *a)
Definition: bitmapset.c:419
Bitmapset * bms_add_members(Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:725
Plan* create_plan ( PlannerInfo root,
Path best_path 
)

Definition at line 293 of file createplan.c.

References apply_tlist_labeling(), Assert, CP_EXACT_TLIST, create_plan_recurse(), PlannerInfo::curOuterParams, PlannerInfo::curOuterRels, elog, ERROR, IsA, NIL, NULL, PlannerInfo::plan_params, PlannerInfo::processed_tlist, SS_attach_initplans(), and Plan::targetlist.

Referenced by create_minmaxagg_plan(), create_subqueryscan_plan(), make_subplan(), SS_process_ctes(), and standard_planner().

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

Definition at line 690 of file initsplan.c.

References Assert, deconstruct_recurse(), IsA, Query::jointree, NIL, NULL, PlannerInfo::nullable_baserels, and PlannerInfo::parse.

Referenced by query_planner().

691 {
692  List *result;
693  Relids qualscope;
694  Relids inner_join_rels;
695  List *postponed_qual_list = NIL;
696 
697  /* Start recursion at top of jointree */
698  Assert(root->parse->jointree != NULL &&
699  IsA(root->parse->jointree, FromExpr));
700 
701  /* this is filled as we scan the jointree */
702  root->nullable_baserels = NULL;
703 
704  result = deconstruct_recurse(root, (Node *) root->parse->jointree, false,
705  &qualscope, &inner_join_rels,
706  &postponed_qual_list);
707 
708  /* Shouldn't be any leftover quals */
709  Assert(postponed_qual_list == NIL);
710 
711  return result;
712 }
#define NIL
Definition: pg_list.h:69
#define IsA(nodeptr, _type_)
Definition: nodes.h:560
Query * parse
Definition: relation.h:152
FromExpr * jointree
Definition: parsenodes.h:129
Definition: nodes.h:509
#define NULL
Definition: c.h:226
#define Assert(condition)
Definition: c.h:671
static List * deconstruct_recurse(PlannerInfo *root, Node *jtnode, bool below_outer_join, Relids *qualscope, Relids *inner_join_rels, List **postponed_qual_list)
Definition: initsplan.c:736
Relids nullable_baserels
Definition: relation.h:201
Definition: pg_list.h:45
void distribute_restrictinfo_to_rels ( PlannerInfo root,
RestrictInfo restrictinfo 
)

Definition at line 2203 of file initsplan.c.

References add_join_clause_to_rels(), RelOptInfo::baserestrict_min_security, RelOptInfo::baserestrictinfo, bms_membership(), BMS_MULTIPLE, BMS_SINGLETON, bms_singleton_member(), check_hashjoinable(), elog, ERROR, find_base_rel(), lappend(), Min, RestrictInfo::required_relids, and RestrictInfo::security_level.

Referenced by distribute_qual_to_rels(), generate_base_implied_equalities_broken(), generate_base_implied_equalities_const(), reconsider_outer_join_clauses(), and remove_rel_from_query().

2205 {
2206  Relids relids = restrictinfo->required_relids;
2207  RelOptInfo *rel;
2208 
2209  switch (bms_membership(relids))
2210  {
2211  case BMS_SINGLETON:
2212 
2213  /*
2214  * There is only one relation participating in the clause, so it
2215  * is a restriction clause for that relation.
2216  */
2217  rel = find_base_rel(root, bms_singleton_member(relids));
2218 
2219  /* Add clause to rel's restriction list */
2221  restrictinfo);
2222  /* Update security level info */
2224  restrictinfo->security_level);
2225  break;
2226  case BMS_MULTIPLE:
2227 
2228  /*
2229  * The clause is a join clause, since there is more than one rel
2230  * in its relid set.
2231  */
2232 
2233  /*
2234  * Check for hashjoinable operators. (We don't bother setting the
2235  * hashjoin info except in true join clauses.)
2236  */
2237  check_hashjoinable(restrictinfo);
2238 
2239  /*
2240  * Add clause to the join lists of all the relevant relations.
2241  */
2242  add_join_clause_to_rels(root, restrictinfo, relids);
2243  break;
2244  default:
2245 
2246  /*
2247  * clause references no rels, and therefore we have no place to
2248  * attach it. Shouldn't get here if callers are working properly.
2249  */
2250  elog(ERROR, "cannot cope with variable-free clause");
2251  break;
2252  }
2253 }
Index security_level
Definition: relation.h:1649
Relids required_relids
Definition: relation.h:1655
List * baserestrictinfo
Definition: relation.h:544
#define Min(x, y)
Definition: c.h:802
Index baserestrict_min_security
Definition: relation.h:547
#define ERROR
Definition: elog.h:43
List * lappend(List *list, void *datum)
Definition: list.c:128
BMS_Membership bms_membership(const Bitmapset *a)
Definition: bitmapset.c:604
int bms_singleton_member(const Bitmapset *a)
Definition: bitmapset.c:496
void add_join_clause_to_rels(PlannerInfo *root, RestrictInfo *restrictinfo, Relids join_relids)
Definition: joininfo.c:95
static void check_hashjoinable(RestrictInfo *restrictinfo)
Definition: initsplan.c:2616
#define elog
Definition: elog.h:219
RelOptInfo * find_base_rel(PlannerInfo *root, int relid)
Definition: relnode.c:219
void extract_query_dependencies ( Node query,
List **  relationOids,
List **  invalItems,
bool hasRowSecurity 
)

Definition at line 2475 of file setrefs.c.

References PlannerGlobal::dependsOnRole, extract_query_dependencies_walker(), PlannerInfo::glob, PlannerGlobal::invalItems, MemSet, NIL, PlannerGlobal::relationOids, T_PlannerGlobal, T_PlannerInfo, PlannerGlobal::type, and PlannerInfo::type.

Referenced by CompleteCachedPlan(), and RevalidateCachedQuery().

2479 {
2480  PlannerGlobal glob;
2481  PlannerInfo root;
2482 
2483  /* Make up dummy planner state so we can use this module's machinery */
2484  MemSet(&glob, 0, sizeof(glob));
2485  glob.type = T_PlannerGlobal;
2486  glob.relationOids = NIL;
2487  glob.invalItems = NIL;
2488  /* Hack: we use glob.dependsOnRole to collect hasRowSecurity flags */
2489  glob.dependsOnRole = false;
2490 
2491  MemSet(&root, 0, sizeof(root));
2492  root.type = T_PlannerInfo;
2493  root.glob = &glob;
2494 
2495  (void) extract_query_dependencies_walker(query, &root);
2496 
2497  *relationOids = glob.relationOids;
2498  *invalItems = glob.invalItems;
2499  *hasRowSecurity = glob.dependsOnRole;
2500 }
#define NIL
Definition: pg_list.h:69
#define MemSet(start, val, len)
Definition: c.h:853
bool dependsOnRole
Definition: relation.h:124
PlannerGlobal * glob
Definition: relation.h:154
List * invalItems
Definition: relation.h:112
NodeTag type
Definition: relation.h:150
static bool extract_query_dependencies_walker(Node *node, PlannerInfo *context)
Definition: setrefs.c:2503
NodeTag type
Definition: relation.h:94
List * relationOids
Definition: relation.h:110
void find_lateral_references ( PlannerInfo root)

Definition at line 271 of file initsplan.c.

References Assert, extract_lateral_references(), PlannerInfo::hasLateralRTEs, NULL, RelOptInfo::relid, RELOPT_BASEREL, RelOptInfo::reloptkind, PlannerInfo::simple_rel_array, and PlannerInfo::simple_rel_array_size.

Referenced by query_planner().

272 {
273  Index rti;
274 
275  /* We need do nothing if the query contains no LATERAL RTEs */
276  if (!root->hasLateralRTEs)
277  return;
278 
279  /*
280  * Examine all baserels (the rel array has been set up by now).
281  */
282  for (rti = 1; rti < root->simple_rel_array_size; rti++)
283  {
284  RelOptInfo *brel = root->simple_rel_array[rti];
285 
286  /* there may be empty slots corresponding to non-baserel RTEs */
287  if (brel == NULL)
288  continue;
289 
290  Assert(brel->relid == rti); /* sanity check on array */
291 
292  /*
293  * This bit is less obvious than it might look. We ignore appendrel
294  * otherrels and consider only their parent baserels. In a case where
295  * a LATERAL-containing UNION ALL subquery was pulled up, it is the
296  * otherrel that is actually going to be in the plan. However, we
297  * want to mark all its lateral references as needed by the parent,
298  * because it is the parent's relid that will be used for join
299  * planning purposes. And the parent's RTE will contain all the
300  * lateral references we need to know, since the pulled-up member is
301  * nothing but a copy of parts of the original RTE's subquery. We
302  * could visit the parent's children instead and transform their
303  * references back to the parent's relid, but it would be much more
304  * complicated for no real gain. (Important here is that the child
305  * members have not yet received any processing beyond being pulled
306  * up.) Similarly, in appendrels created by inheritance expansion,
307  * it's sufficient to look at the parent relation.
308  */
309 
310  /* ignore RTEs that are "other rels" */
311  if (brel->reloptkind != RELOPT_BASEREL)
312  continue;
313 
314  extract_lateral_references(root, brel, rti);
315  }
316 }
RelOptKind reloptkind
Definition: relation.h:487
struct RelOptInfo ** simple_rel_array
Definition: relation.h:176
bool hasLateralRTEs
Definition: relation.h:295
int simple_rel_array_size
Definition: relation.h:177
Index relid
Definition: relation.h:518
unsigned int Index
Definition: c.h:362
#define NULL
Definition: c.h:226
#define Assert(condition)
Definition: c.h:671
static void extract_lateral_references(PlannerInfo *root, RelOptInfo *brel, Index rtindex)
Definition: initsplan.c:319
bool is_projection_capable_path ( Path path)

Definition at line 6261 of file createplan.c.

References IS_DUMMY_PATH, Path::pathtype, T_Append, T_Hash, T_Limit, T_LockRows, T_Material, T_MergeAppend, T_ModifyTable, T_ProjectSet, T_RecursiveUnion, T_SetOp, T_Sort, and T_Unique.

Referenced by apply_projection_to_path(), create_projection_path(), and create_projection_plan().

6262 {
6263  /* Most plan types can project, so just list the ones that can't */
6264  switch (path->pathtype)
6265  {
6266  case T_Hash:
6267  case T_Material:
6268  case T_Sort:
6269  case T_Unique:
6270  case T_SetOp:
6271  case T_LockRows:
6272  case T_Limit:
6273  case T_ModifyTable:
6274  case T_MergeAppend:
6275  case T_RecursiveUnion:
6276  return false;
6277  case T_Append:
6278 
6279  /*
6280  * Append can't project, but if it's being used to represent a
6281  * dummy path, claim that it can project. This prevents us from
6282  * converting a rel from dummy to non-dummy status by applying a
6283  * projection to its dummy path.
6284  */
6285  return IS_DUMMY_PATH(path);
6286  case T_ProjectSet:
6287 
6288  /*
6289  * Although ProjectSet certainly projects, say "no" because we
6290  * don't want the planner to randomly replace its tlist with
6291  * something else; the SRFs have to stay at top level. This might
6292  * get relaxed later.
6293  */
6294  return false;
6295  default:
6296  break;
6297  }
6298  return true;
6299 }
Definition: nodes.h:77
Definition: nodes.h:48
Definition: nodes.h:73
#define IS_DUMMY_PATH(p)
Definition: relation.h:1122
NodeTag pathtype
Definition: relation.h:892
Definition: nodes.h:79
Definition: nodes.h:80
Definition: nodes.h:82
bool is_projection_capable_plan ( Plan plan)

Definition at line 6306 of file createplan.c.

References nodeTag, T_Append, T_Hash, T_Limit, T_LockRows, T_Material, T_MergeAppend, T_ModifyTable, T_ProjectSet, T_RecursiveUnion, T_SetOp, T_Sort, and T_Unique.

Referenced by create_unique_plan(), and prepare_sort_from_pathkeys().

6307 {
6308  /* Most plan types can project, so just list the ones that can't */
6309  switch (nodeTag(plan))
6310  {
6311  case T_Hash:
6312  case T_Material:
6313  case T_Sort:
6314  case T_Unique:
6315  case T_SetOp:
6316  case T_LockRows:
6317  case T_Limit:
6318  case T_ModifyTable:
6319  case T_Append:
6320  case T_MergeAppend:
6321  case T_RecursiveUnion:
6322  return false;
6323  case T_ProjectSet:
6324 
6325  /*
6326  * Although ProjectSet certainly projects, say "no" because we
6327  * don't want the planner to randomly replace its tlist with
6328  * something else; the SRFs have to stay at top level. This might
6329  * get relaxed later.
6330  */
6331  return false;
6332  default:
6333  break;
6334  }
6335  return true;
6336 }
Definition: nodes.h:77
Definition: nodes.h:48
Definition: nodes.h:73
Definition: nodes.h:79
#define nodeTag(nodeptr)
Definition: nodes.h:514
Definition: nodes.h:80
Definition: nodes.h:82
Agg* make_agg ( List tlist,
List qual,
AggStrategy  aggstrategy,
AggSplit  aggsplit,
int  numGroupCols,
AttrNumber grpColIdx,
Oid grpOperators,
List groupingSets,
List chain,
double  dNumGroups,
Plan lefttree 
)

Definition at line 5727 of file createplan.c.

References Agg::aggParams, Agg::aggsplit, Agg::aggstrategy, Agg::chain, Agg::groupingSets, Agg::grpColIdx, Agg::grpOperators, Plan::lefttree, makeNode, Min, NULL, Agg::numCols, Agg::numGroups, Agg::plan, Plan::qual, Plan::righttree, and Plan::targetlist.

Referenced by create_agg_plan(), create_groupingsets_plan(), and create_unique_plan().

5732 {
5733  Agg *node = makeNode(Agg);
5734  Plan *plan = &node->plan;
5735  long numGroups;
5736 
5737  /* Reduce to long, but 'ware overflow! */
5738  numGroups = (long) Min(dNumGroups, (double) LONG_MAX);
5739 
5740  node->aggstrategy = aggstrategy;
5741  node->aggsplit = aggsplit;
5742  node->numCols = numGroupCols;
5743  node->grpColIdx = grpColIdx;
5744  node->grpOperators = grpOperators;
5745  node->numGroups = numGroups;
5746  node->aggParams = NULL; /* SS_finalize_plan() will fill this */
5747  node->groupingSets = groupingSets;
5748  node->chain = chain;
5749 
5750  plan->qual = qual;
5751  plan->targetlist = tlist;
5752  plan->lefttree = lefttree;
5753  plan->righttree = NULL;
5754 
5755  return node;
5756 }
int numCols
Definition: plannodes.h:735
List * qual
Definition: plannodes.h:130
AttrNumber * grpColIdx
Definition: plannodes.h:736
#define Min(x, y)
Definition: c.h:802
struct Plan * righttree
Definition: plannodes.h:132
AggStrategy aggstrategy
Definition: plannodes.h:733
Bitmapset * aggParams
Definition: plannodes.h:739
Plan plan
Definition: plannodes.h:732
List * groupingSets
Definition: plannodes.h:741
#define makeNode(_type_)
Definition: nodes.h:557
#define NULL
Definition: c.h:226
AggSplit aggsplit
Definition: plannodes.h:734
long numGroups
Definition: plannodes.h:738
struct Plan * lefttree
Definition: plannodes.h:131
List * targetlist
Definition: plannodes.h:129
Oid * grpOperators
Definition: plannodes.h:737
List * chain
Definition: plannodes.h:742
Definition: plannodes.h:730
ForeignScan* make_foreignscan ( List qptlist,
List qpqual,
Index  scanrelid,
List fdw_exprs,
List fdw_private,
List fdw_scan_tlist,
List fdw_recheck_quals,
Plan outer_plan 
)

Definition at line 4972 of file createplan.c.

References CMD_SELECT, ForeignScan::fdw_exprs, ForeignScan::fdw_private, ForeignScan::fdw_recheck_quals, ForeignScan::fdw_scan_tlist, ForeignScan::fs_relids, ForeignScan::fs_server, ForeignScan::fsSystemCol, InvalidOid, Plan::lefttree, makeNode, NULL, ForeignScan::operation, Scan::plan, Plan::qual, Plan::righttree, ForeignScan::scan, Scan::scanrelid, and Plan::targetlist.

Referenced by fileGetForeignPlan(), and postgresGetForeignPlan().

4980 {
4981  ForeignScan *node = makeNode(ForeignScan);
4982  Plan *plan = &node->scan.plan;
4983 
4984  /* cost will be filled in by create_foreignscan_plan */
4985  plan->targetlist = qptlist;
4986  plan->qual = qpqual;
4987  plan->lefttree = outer_plan;
4988  plan->righttree = NULL;
4989  node->scan.scanrelid = scanrelid;
4990  node->operation = CMD_SELECT;
4991  /* fs_server will be filled in by create_foreignscan_plan */
4992  node->fs_server = InvalidOid;
4993  node->fdw_exprs = fdw_exprs;
4994  node->fdw_private = fdw_private;
4995  node->fdw_scan_tlist = fdw_scan_tlist;
4996  node->fdw_recheck_quals = fdw_recheck_quals;
4997  /* fs_relids will be filled in by create_foreignscan_plan */
4998  node->fs_relids = NULL;
4999  /* fsSystemCol will be filled in by create_foreignscan_plan */
5000  node->fsSystemCol = false;
5001 
5002  return node;
5003 }
List * qual
Definition: plannodes.h:130
Plan plan
Definition: plannodes.h:305
Index scanrelid
Definition: plannodes.h:306
Oid fs_server
Definition: plannodes.h:555
List * fdw_exprs
Definition: plannodes.h:556
List * fdw_private
Definition: plannodes.h:557
List * fdw_scan_tlist
Definition: plannodes.h:558
CmdType operation
Definition: plannodes.h:554
struct Plan * righttree
Definition: plannodes.h:132
List * fdw_recheck_quals
Definition: plannodes.h:559
#define InvalidOid
Definition: postgres_ext.h:36
#define makeNode(_type_)
Definition: nodes.h:557
#define NULL
Definition: c.h:226
struct Plan * lefttree
Definition: plannodes.h:131
List * targetlist
Definition: plannodes.h:129
bool fsSystemCol
Definition: plannodes.h:562
Bitmapset * fs_relids
Definition: plannodes.h:561
Limit* make_limit ( Plan lefttree,
Node limitOffset,
Node limitCount 
)

Definition at line 6064 of file createplan.c.

References Plan::lefttree, Limit::limitCount, Limit::limitOffset, makeNode, NIL, NULL, Limit::plan, Plan::qual, Plan::righttree, and Plan::targetlist.

Referenced by create_limit_plan(), and create_minmaxagg_plan().

6065 {
6066  Limit *node = makeNode(Limit);
6067  Plan *plan = &node->plan;
6068 
6069  plan->targetlist = lefttree->targetlist;
6070  plan->qual = NIL;
6071  plan->lefttree = lefttree;
6072  plan->righttree = NULL;
6073 
6074  node->limitOffset = limitOffset;
6075  node->limitCount = limitCount;
6076 
6077  return node;
6078 }
#define NIL
Definition: pg_list.h:69
List * qual
Definition: plannodes.h:130
Plan plan
Definition: plannodes.h:851
Node * limitOffset
Definition: plannodes.h:852
struct Plan * righttree
Definition: plannodes.h:132
Node * limitCount
Definition: plannodes.h:853
#define makeNode(_type_)
Definition: nodes.h:557
#define NULL
Definition: c.h:226
struct Plan * lefttree
Definition: plannodes.h:131
List * targetlist
Definition: plannodes.h:129
Sort* make_sort_from_sortclauses ( List sortcls,
Plan lefttree 
)

Definition at line 5582 of file createplan.c.

References TargetEntry::expr, exprCollation(), get_sortgroupclause_tle(), lfirst, list_length(), make_sort(), SortGroupClause::nulls_first, palloc(), TargetEntry::resno, SortGroupClause::sortop, and Plan::targetlist.

Referenced by create_unique_plan().

5583 {
5584  List *sub_tlist = lefttree->targetlist;
5585  ListCell *l;
5586  int numsortkeys;
5587  AttrNumber *sortColIdx;
5588  Oid *sortOperators;
5589  Oid *collations;
5590  bool *nullsFirst;
5591 
5592  /* Convert list-ish representation to arrays wanted by executor */
5593  numsortkeys = list_length(sortcls);
5594  sortColIdx = (AttrNumber *) palloc(numsortkeys * sizeof(AttrNumber));
5595  sortOperators = (Oid *) palloc(numsortkeys * sizeof(Oid));
5596  collations = (Oid *) palloc(numsortkeys * sizeof(Oid));
5597  nullsFirst = (bool *) palloc(numsortkeys * sizeof(bool));
5598 
5599  numsortkeys = 0;
5600  foreach(l, sortcls)
5601  {
5602  SortGroupClause *sortcl = (SortGroupClause *) lfirst(l);
5603  TargetEntry *tle = get_sortgroupclause_tle(sortcl, sub_tlist);
5604 
5605  sortColIdx[numsortkeys] = tle->resno;
5606  sortOperators[numsortkeys] = sortcl->sortop;
5607  collations[numsortkeys] = exprCollation((Node *) tle->expr);
5608  nullsFirst[numsortkeys] = sortcl->nulls_first;
5609  numsortkeys++;
5610  }
5611 
5612  return make_sort(lefttree, numsortkeys,
5613  sortColIdx, sortOperators,
5614  collations, nullsFirst);
5615 }
TargetEntry * get_sortgroupclause_tle(SortGroupClause *sgClause, List *targetList)
Definition: tlist.c:370
Definition: nodes.h:509
unsigned int Oid
Definition: postgres_ext.h:31
AttrNumber resno
Definition: primnodes.h:1331
static Sort * make_sort(Plan *lefttree, int numCols, AttrNumber *sortColIdx, Oid *sortOperators, Oid *collations, bool *nullsFirst)
Definition: createplan.c:5211
#define lfirst(lc)
Definition: pg_list.h:106
Expr * expr
Definition: primnodes.h:1330
static int list_length(const List *l)
Definition: pg_list.h:89
Oid exprCollation(const Node *expr)
Definition: nodeFuncs.c:745
List * targetlist
Definition: plannodes.h:129
void * palloc(Size size)
Definition: mcxt.c:891
Definition: pg_list.h:45
int16 AttrNumber
Definition: attnum.h:21
void match_foreign_keys_to_quals ( PlannerInfo root)

Definition at line 2410 of file initsplan.c.

References OpExpr::args, RestrictInfo::clause, ForeignKeyOptInfo::con_relid, ForeignKeyOptInfo::confkey, ForeignKeyOptInfo::conkey, ForeignKeyOptInfo::conpfeqop, ForeignKeyOptInfo::eclass, PlannerInfo::fkey_list, get_commutator(), get_leftop(), get_rightop(), InvalidOid, IsA, RelOptInfo::joininfo, lappend(), lfirst, list_length(), match_eclasses_to_foreign_key_col(), NIL, ForeignKeyOptInfo::nkeys, ForeignKeyOptInfo::nmatched_ec, ForeignKeyOptInfo::nmatched_rcols, ForeignKeyOptInfo::nmatched_ri, NULL, OidIsValid, OpExpr::opno, RestrictInfo::outerjoin_delayed, ForeignKeyOptInfo::ref_relid, RELOPT_BASEREL, RelOptInfo::reloptkind, ForeignKeyOptInfo::rinfos, PlannerInfo::simple_rel_array, and PlannerInfo::simple_rel_array_size.

Referenced by query_planner().

2411 {
2412  List *newlist = NIL;
2413  ListCell *lc;
2414 
2415  foreach(lc, root->fkey_list)
2416  {
2417  ForeignKeyOptInfo *fkinfo = (ForeignKeyOptInfo *) lfirst(lc);
2418  RelOptInfo *con_rel;
2419  RelOptInfo *ref_rel;
2420  int colno;
2421 
2422  /*
2423  * Either relid might identify a rel that is in the query's rtable but
2424  * isn't referenced by the jointree so won't have a RelOptInfo. Hence
2425  * don't use find_base_rel() here. We can ignore such FKs.
2426  */
2427  if (fkinfo->con_relid >= root->simple_rel_array_size ||
2428  fkinfo->ref_relid >= root->simple_rel_array_size)
2429  continue; /* just paranoia */
2430  con_rel = root->simple_rel_array[fkinfo->con_relid];
2431  if (con_rel == NULL)
2432  continue;
2433  ref_rel = root->simple_rel_array[fkinfo->ref_relid];
2434  if (ref_rel == NULL)
2435  continue;
2436 
2437  /*
2438  * Ignore FK unless both rels are baserels. This gets rid of FKs that
2439  * link to inheritance child rels (otherrels) and those that link to
2440  * rels removed by join removal (dead rels).
2441  */
2442  if (con_rel->reloptkind != RELOPT_BASEREL ||
2443  ref_rel->reloptkind != RELOPT_BASEREL)
2444  continue;
2445 
2446  /*
2447  * Scan the columns and try to match them to eclasses and quals.
2448  *
2449  * Note: for simple inner joins, any match should be in an eclass.
2450  * "Loose" quals that syntactically match an FK equality must have
2451  * been rejected for EC status because they are outer-join quals or
2452  * similar. We can still consider them to match the FK if they are
2453  * not outerjoin_delayed.
2454  */
2455  for (colno = 0; colno < fkinfo->nkeys; colno++)
2456  {
2457  AttrNumber con_attno,
2458  ref_attno;
2459  Oid fpeqop;
2460  ListCell *lc2;
2461 
2462  fkinfo->eclass[colno] = match_eclasses_to_foreign_key_col(root,
2463  fkinfo,
2464  colno);
2465  /* Don't bother looking for loose quals if we got an EC match */
2466  if (fkinfo->eclass[colno] != NULL)
2467  {
2468  fkinfo->nmatched_ec++;
2469  continue;
2470  }
2471 
2472  /*
2473  * Scan joininfo list for relevant clauses. Either rel's joininfo
2474  * list would do equally well; we use con_rel's.
2475  */
2476  con_attno = fkinfo->conkey[colno];
2477  ref_attno = fkinfo->confkey[colno];
2478  fpeqop = InvalidOid; /* we'll look this up only if needed */
2479 
2480  foreach(lc2, con_rel->joininfo)
2481  {
2482  RestrictInfo *rinfo = (RestrictInfo *) lfirst(lc2);
2483  OpExpr *clause = (OpExpr *) rinfo->clause;
2484  Var *leftvar;
2485  Var *rightvar;
2486 
2487  /* Ignore outerjoin-delayed clauses */
2488  if (rinfo->outerjoin_delayed)
2489  continue;
2490 
2491  /* Only binary OpExprs are useful for consideration */
2492  if (!IsA(clause, OpExpr) ||
2493  list_length(clause->args) != 2)
2494  continue;
2495  leftvar = (Var *) get_leftop((Expr *) clause);
2496  rightvar = (Var *) get_rightop((Expr *) clause);
2497 
2498  /* Operands must be Vars, possibly with RelabelType */
2499  while (leftvar && IsA(leftvar, RelabelType))
2500  leftvar = (Var *) ((RelabelType *) leftvar)->arg;
2501  if (!(leftvar && IsA(leftvar, Var)))
2502  continue;
2503  while (rightvar && IsA(rightvar, RelabelType))
2504  rightvar = (Var *) ((RelabelType *) rightvar)->arg;
2505  if (!(rightvar && IsA(rightvar, Var)))
2506  continue;
2507 
2508  /* Now try to match the vars to the current foreign key cols */
2509  if (fkinfo->ref_relid == leftvar->varno &&
2510  ref_attno == leftvar->varattno &&
2511  fkinfo->con_relid == rightvar->varno &&
2512  con_attno == rightvar->varattno)
2513  {
2514  /* Vars match, but is it the right operator? */
2515  if (clause->opno == fkinfo->conpfeqop[colno])
2516  {
2517  fkinfo->rinfos[colno] = lappend(fkinfo->rinfos[colno],
2518  rinfo);
2519  fkinfo->nmatched_ri++;
2520  }
2521  }
2522  else if (fkinfo->ref_relid == rightvar->varno &&
2523  ref_attno == rightvar->varattno &&
2524  fkinfo->con_relid == leftvar->varno &&
2525  con_attno == leftvar->varattno)
2526  {
2527  /*
2528  * Reverse match, must check commutator operator. Look it
2529  * up if we didn't already. (In the worst case we might
2530  * do multiple lookups here, but that would require an FK
2531  * equality operator without commutator, which is
2532  * unlikely.)
2533  */
2534  if (!OidIsValid(fpeqop))
2535  fpeqop = get_commutator(fkinfo->conpfeqop[colno]);
2536  if (clause->opno == fpeqop)
2537  {
2538  fkinfo->rinfos[colno] = lappend(fkinfo->rinfos[colno],
2539  rinfo);
2540  fkinfo->nmatched_ri++;
2541  }
2542  }
2543  }
2544  /* If we found any matching loose quals, count col as matched */
2545  if (fkinfo->rinfos[colno])
2546  fkinfo->nmatched_rcols++;
2547  }
2548 
2549  /*
2550  * Currently, we drop multicolumn FKs that aren't fully matched to the
2551  * query. Later we might figure out how to derive some sort of
2552  * estimate from them, in which case this test should be weakened to
2553  * "if ((fkinfo->nmatched_ec + fkinfo->nmatched_rcols) > 0)".
2554  */
2555  if ((fkinfo->nmatched_ec + fkinfo->nmatched_rcols) == fkinfo->nkeys)
2556  newlist = lappend(newlist, fkinfo);
2557  }
2558  /* Replace fkey_list, thereby discarding any useless entries */
2559  root->fkey_list = newlist;
2560 }
#define NIL
Definition: pg_list.h:69
#define IsA(nodeptr, _type_)
Definition: nodes.h:560
Oid get_commutator(Oid opno)
Definition: lsyscache.c:1281
RelOptKind reloptkind
Definition: relation.h:487
unsigned int Oid
Definition: postgres_ext.h:31
Definition: primnodes.h:141
List * fkey_list
Definition: relation.h:255
#define OidIsValid(objectId)
Definition: c.h:534
struct RelOptInfo ** simple_rel_array
Definition: relation.h:176
Node * get_leftop(const Expr *clause)
Definition: clauses.c:198
Oid conpfeqop[INDEX_MAX_KEYS]
Definition: relation.h:655
bool outerjoin_delayed
Definition: relation.h:1641
List * joininfo
Definition: relation.h:549
int simple_rel_array_size
Definition: relation.h:177
List * lappend(List *list, void *datum)
Definition: list.c:128
Expr * clause
Definition: relation.h:1637
struct EquivalenceClass * eclass[INDEX_MAX_KEYS]
Definition: relation.h:662
AttrNumber conkey[INDEX_MAX_KEYS]
Definition: relation.h:653
EquivalenceClass * match_eclasses_to_foreign_key_col(PlannerInfo *root, ForeignKeyOptInfo *fkinfo, int colno)
Definition: equivclass.c:1990
#define InvalidOid
Definition: postgres_ext.h:36
#define NULL
Definition: c.h:226
#define lfirst(lc)
Definition: pg_list.h:106
static int list_length(const List *l)
Definition: pg_list.h:89
Node * get_rightop(const Expr *clause)
Definition: clauses.c:215
Oid opno
Definition: primnodes.h:473
List * args
Definition: primnodes.h:479
Definition: pg_list.h:45
AttrNumber confkey[INDEX_MAX_KEYS]
Definition: relation.h:654
int16 AttrNumber
Definition: attnum.h:21
List * rinfos[INDEX_MAX_KEYS]
Definition: relation.h:664
Plan* materialize_finished_plan ( Plan subplan)

Definition at line 5694 of file createplan.c.

References cost_material(), Plan::initPlan, make_material(), NIL, Plan::parallel_aware, Plan::plan_rows, Plan::plan_width, Plan::startup_cost, Path::startup_cost, Plan::total_cost, and Path::total_cost.

Referenced by build_subplan(), and standard_planner().

5695 {
5696  Plan *matplan;
5697  Path matpath; /* dummy for result of cost_material */
5698 
5699  matplan = (Plan *) make_material(subplan);
5700 
5701  /*
5702  * XXX horrid kluge: if there are any initPlans attached to the subplan,
5703  * move them up to the Material node, which is now effectively the top
5704  * plan node in its query level. This prevents failure in
5705  * SS_finalize_plan(), which see for comments. We don't bother adjusting
5706  * the subplan's cost estimate for this.
5707  */
5708  matplan->initPlan = subplan->initPlan;
5709  subplan->initPlan = NIL;
5710 
5711  /* Set cost data */
5712  cost_material(&matpath,
5713  subplan->startup_cost,
5714  subplan->total_cost,
5715  subplan->plan_rows,
5716  subplan->plan_width);
5717  matplan->startup_cost = matpath.startup_cost;
5718  matplan->total_cost = matpath.total_cost;
5719  matplan->plan_rows = subplan->plan_rows;
5720  matplan->plan_width = subplan->plan_width;
5721  matplan->parallel_aware = false;
5722 
5723  return matplan;
5724 }
#define NIL
Definition: pg_list.h:69
double plan_rows
Definition: plannodes.h:117
static Material * make_material(Plan *lefttree)
Definition: createplan.c:5672
Cost startup_cost
Definition: relation.h:906
Cost startup_cost
Definition: plannodes.h:111
bool parallel_aware
Definition: plannodes.h:123
Cost total_cost
Definition: relation.h:907
void cost_material(Path *path, Cost input_startup_cost, Cost input_total_cost, double tuples, int width)
Definition: costsize.c:1637
int plan_width
Definition: plannodes.h:118
List * initPlan
Definition: plannodes.h:133
Cost total_cost
Definition: plannodes.h:112
Definition: relation.h:888
void preprocess_minmax_aggregates ( PlannerInfo root,
List tlist 
)

Definition at line 75 of file planagg.c.

References add_path(), MinMaxAggInfo::aggsortop, Assert, build_minmax_path(), create_minmaxagg_path(), create_pathtarget, Query::cteList, elog, ERROR, exprCollation(), exprType(), fetch_upper_rel(), find_minmax_aggs_walker(), FromExpr::fromlist, get_equality_op_for_ordering_op(), Query::groupClause, Query::groupingSets, Query::hasAggs, Query::hasWindowFuncs, Query::havingQual, RangeTblEntry::inh, IsA, Query::jointree, lfirst, linitial, list_length(), PlannerInfo::minmax_aggs, NIL, NULL, OidIsValid, MinMaxAggInfo::param, parse(), PlannerInfo::parse, planner_rt_fetch, Query::rowMarks, RTE_RELATION, RTE_SUBQUERY, RangeTblEntry::rtekind, RangeTblRef::rtindex, Query::setOperations, SS_make_initplan_output_param(), MinMaxAggInfo::target, and UPPERREL_GROUP_AGG.

Referenced by grouping_planner().

76 {
77  Query *parse = root->parse;
78  FromExpr *jtnode;
79  RangeTblRef *rtr;
80  RangeTblEntry *rte;
81  List *aggs_list;
82  RelOptInfo *grouped_rel;
83  ListCell *lc;
84 
85  /* minmax_aggs list should be empty at this point */
86  Assert(root->minmax_aggs == NIL);
87 
88  /* Nothing to do if query has no aggregates */
89  if (!parse->hasAggs)
90  return;
91 
92  Assert(!parse->setOperations); /* shouldn't get here if a setop */
93  Assert(parse->rowMarks == NIL); /* nor if FOR UPDATE */
94 
95  /*
96  * Reject unoptimizable cases.
97  *
98  * We don't handle GROUP BY or windowing, because our current
99  * implementations of grouping require looking at all the rows anyway, and
100  * so there's not much point in optimizing MIN/MAX.
101  */
102  if (parse->groupClause || list_length(parse->groupingSets) > 1 ||
103  parse->hasWindowFuncs)
104  return;
105 
106  /*
107  * Reject if query contains any CTEs; there's no way to build an indexscan
108  * on one so we couldn't succeed here. (If the CTEs are unreferenced,
109  * that's not true, but it doesn't seem worth expending cycles to check.)
110  */
111  if (parse->cteList)
112  return;
113 
114  /*
115  * We also restrict the query to reference exactly one table, since join
116  * conditions can't be handled reasonably. (We could perhaps handle a
117  * query containing cartesian-product joins, but it hardly seems worth the
118  * trouble.) However, the single table could be buried in several levels
119  * of FromExpr due to subqueries. Note the "single" table could be an
120  * inheritance parent, too, including the case of a UNION ALL subquery
121  * that's been flattened to an appendrel.
122  */
123  jtnode = parse->jointree;
124  while (IsA(jtnode, FromExpr))
125  {
126  if (list_length(jtnode->fromlist) != 1)
127  return;
128  jtnode = linitial(jtnode->fromlist);
129  }
130  if (!IsA(jtnode, RangeTblRef))
131  return;
132  rtr = (RangeTblRef *) jtnode;
133  rte = planner_rt_fetch(rtr->rtindex, root);
134  if (rte->rtekind == RTE_RELATION)
135  /* ordinary relation, ok */ ;
136  else if (rte->rtekind == RTE_SUBQUERY && rte->inh)
137  /* flattened UNION ALL subquery, ok */ ;
138  else
139  return;
140 
141  /*
142  * Scan the tlist and HAVING qual to find all the aggregates and verify
143  * all are MIN/MAX aggregates. Stop as soon as we find one that isn't.
144  */
145  aggs_list = NIL;
146  if (find_minmax_aggs_walker((Node *) tlist, &aggs_list))
147  return;
148  if (find_minmax_aggs_walker(parse->havingQual, &aggs_list))
149  return;
150 
151  /*
152  * OK, there is at least the possibility of performing the optimization.
153  * Build an access path for each aggregate. If any of the aggregates
154  * prove to be non-indexable, give up; there is no point in optimizing
155  * just some of them.
156  */
157  foreach(lc, aggs_list)
158  {
159  MinMaxAggInfo *mminfo = (MinMaxAggInfo *) lfirst(lc);
160  Oid eqop;
161  bool reverse;
162 
163  /*
164  * We'll need the equality operator that goes with the aggregate's
165  * ordering operator.
166  */
167  eqop = get_equality_op_for_ordering_op(mminfo->aggsortop, &reverse);
168  if (!OidIsValid(eqop)) /* shouldn't happen */
169  elog(ERROR, "could not find equality operator for ordering operator %u",
170  mminfo->aggsortop);
171 
172  /*
173  * We can use either an ordering that gives NULLS FIRST or one that
174  * gives NULLS LAST; furthermore there's unlikely to be much
175  * performance difference between them, so it doesn't seem worth
176  * costing out both ways if we get a hit on the first one. NULLS
177  * FIRST is more likely to be available if the operator is a
178  * reverse-sort operator, so try that first if reverse.
179  */
180  if (build_minmax_path(root, mminfo, eqop, mminfo->aggsortop, reverse))
181  continue;
182  if (build_minmax_path(root, mminfo, eqop, mminfo->aggsortop, !reverse))
183  continue;
184 
185  /* No indexable path for this aggregate, so fail */
186  return;
187  }
188 
189  /*
190  * OK, we can do the query this way. Prepare to create a MinMaxAggPath
191  * node.
192  *
193  * First, create an output Param node for each agg. (If we end up not
194  * using the MinMaxAggPath, we'll waste a PARAM_EXEC slot for each agg,
195  * which is not worth worrying about. We can't wait till create_plan time
196  * to decide whether to make the Param, unfortunately.)
197  */
198  foreach(lc, aggs_list)
199  {
200  MinMaxAggInfo *mminfo = (MinMaxAggInfo *) lfirst(lc);
201 
202  mminfo->param =
204  exprType((Node *) mminfo->target),
205  -1,
206  exprCollation((Node *) mminfo->target));
207  }
208 
209  /*
210  * Create a MinMaxAggPath node with the appropriate estimated costs and
211  * other needed data, and add it to the UPPERREL_GROUP_AGG upperrel, where
212  * it will compete against the standard aggregate implementation. (It
213  * will likely always win, but we need not assume that here.)
214  *
215  * Note: grouping_planner won't have created this upperrel yet, but it's
216  * fine for us to create it first. We will not have inserted the correct
217  * consider_parallel value in it, but MinMaxAggPath paths are currently
218  * never parallel-safe anyway, so that doesn't matter. Likewise, it
219  * doesn't matter that we haven't filled FDW-related fields in the rel.
220  */
221  grouped_rel = fetch_upper_rel(root, UPPERREL_GROUP_AGG, NULL);
222  add_path(grouped_rel, (Path *)
223  create_minmaxagg_path(root, grouped_rel,
224  create_pathtarget(root, tlist),
225  aggs_list,
226  (List *) parse->havingQual));
227 }
#define NIL
Definition: pg_list.h:69
static bool find_minmax_aggs_walker(Node *node, List **context)
Definition: planagg.c:247
MinMaxAggPath * create_minmaxagg_path(PlannerInfo *root, RelOptInfo *rel, PathTarget *target, List *mmaggregates, List *quals)
Definition: pathnode.c:2733
#define IsA(nodeptr, _type_)
Definition: nodes.h:560
Query * parse
Definition: relation.h:152
void add_path(RelOptInfo *parent_rel, Path *new_path)
Definition: pathnode.c:412
FromExpr * jointree
Definition: parsenodes.h:129
bool hasAggs
Definition: parsenodes.h:116
Oid get_equality_op_for_ordering_op(Oid opno, bool *reverse)
Definition: lsyscache.c:264
Param * param
Definition: relation.h:1956
List * groupingSets
Definition: parsenodes.h:139
Definition: nodes.h:509
List * minmax_aggs
Definition: relation.h:280
List * fromlist
Definition: primnodes.h:1433
unsigned int Oid
Definition: postgres_ext.h:31
List * rowMarks
Definition: parsenodes.h:152
#define OidIsValid(objectId)
Definition: c.h:534
#define linitial(l)
Definition: pg_list.h:110
#define planner_rt_fetch(rti, root)
Definition: relation.h:320
#define ERROR
Definition: elog.h:43
RelOptInfo * fetch_upper_rel(PlannerInfo *root, UpperRelationKind kind, Relids relids)
Definition: relnode.c:870
#define create_pathtarget(root, tlist)
Definition: tlist.h:69
#define NULL
Definition: c.h:226
#define Assert(condition)
Definition: c.h:671
#define lfirst(lc)
Definition: pg_list.h:106
Expr * target
Definition: relation.h:1952
bool hasWindowFuncs
Definition: parsenodes.h:117
Param * SS_make_initplan_output_param(PlannerInfo *root, Oid resulttype, int32 resulttypmod, Oid resultcollation)
Definition: subselect.c:2877
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:42
static int list_length(const List *l)
Definition: pg_list.h:89
Oid exprCollation(const Node *expr)
Definition: nodeFuncs.c:745
static bool build_minmax_path(PlannerInfo *root, MinMaxAggInfo *mminfo, Oid eqop, Oid sortop, bool nulls_first)
Definition: planagg.c:342
RTEKind rtekind
Definition: parsenodes.h:882
List * cteList
Definition: parsenodes.h:126
Node * setOperations
Definition: parsenodes.h:154
List * groupClause
Definition: parsenodes.h:137
#define elog
Definition: elog.h:219
Node * havingQual
Definition: parsenodes.h:141
Definition: pg_list.h:45
Definition: relation.h:888
static struct subre * parse(struct vars *, int, int, struct state *, struct state *)
Definition: regcomp.c:651
void process_implied_equality ( PlannerInfo root,
Oid  opno,
Oid  collation,
Expr item1,
Expr item2,
Relids  qualscope,
Relids  nullable_relids,
Index  security_level,
bool  below_outer_join,
bool  both_const 
)

Definition at line 2287 of file initsplan.c.

References Assert, BOOLOID, Const::constisnull, Const::consttype, Const::constvalue, copyObject(), DatumGetBool, distribute_qual_to_rels(), eval_const_expressions(), InvalidOid, IsA, JOIN_INNER, make_opclause(), and NULL.

Referenced by generate_base_implied_equalities_const(), and generate_base_implied_equalities_no_const().

2297 {
2298  Expr *clause;
2299 
2300  /*
2301  * Build the new clause. Copy to ensure it shares no substructure with
2302  * original (this is necessary in case there are subselects in there...)
2303  */
2304  clause = make_opclause(opno,
2305  BOOLOID, /* opresulttype */
2306  false, /* opretset */
2307  (Expr *) copyObject(item1),
2308  (Expr *) copyObject(item2),
2309  InvalidOid,
2310  collation);
2311 
2312  /* If both constant, try to reduce to a boolean constant. */
2313  if (both_const)
2314  {
2315  clause = (Expr *) eval_const_expressions(root, (Node *) clause);
2316 
2317  /* If we produced const TRUE, just drop the clause */
2318  if (clause && IsA(clause, Const))
2319  {
2320  Const *cclause = (Const *) clause;
2321 
2322  Assert(cclause->consttype == BOOLOID);
2323  if (!cclause->constisnull && DatumGetBool(cclause->constvalue))
2324  return;
2325  }
2326  }
2327 
2328  /*
2329  * Push the new clause into all the appropriate restrictinfo lists.
2330  */
2331  distribute_qual_to_rels(root, (Node *) clause,
2332  true, below_outer_join, JOIN_INNER,
2333  security_level,
2334  qualscope, NULL, NULL, nullable_relids,
2335  NULL);
2336 }
Datum constvalue
Definition: primnodes.h:174
#define IsA(nodeptr, _type_)
Definition: nodes.h:560
static void distribute_qual_to_rels(PlannerInfo *root, Node *clause, bool is_deduced, bool below_outer_join, JoinType jointype, Index security_level, Relids qualscope, Relids ojscope, Relids outerjoin_nonnullable, Relids deduced_nullable_relids, List **postponed_qual_list)
Definition: initsplan.c:1619
Definition: nodes.h:509
Node * eval_const_expressions(PlannerInfo *root, Node *node)
Definition: clauses.c:2366
Expr * make_opclause(Oid opno, Oid opresulttype, bool opretset, Expr *leftop, Expr *rightop, Oid opcollid, Oid inputcollid)
Definition: clauses.c:171
void * copyObject(const void *from)
Definition: copyfuncs.c:4475
Oid consttype
Definition: primnodes.h:170
#define DatumGetBool(X)
Definition: postgres.h:401
#define InvalidOid
Definition: postgres_ext.h:36
#define NULL
Definition: c.h:226
#define Assert(condition)
Definition: c.h:671
#define BOOLOID
Definition: pg_type.h:288
bool constisnull
Definition: primnodes.h:175
bool query_is_distinct_for ( Query query,
List colnos,
List opids 
)

Definition at line 687 of file analyzejoins.c.

References SetOperationStmt::all, Assert, castNode, distinct_col_search(), Query::distinctClause, SortGroupClause::eqop, equality_ops_are_compatible(), get_sortgroupclause_tle(), Query::groupClause, SetOperationStmt::groupClauses, GROUPING_SET_EMPTY, Query::groupingSets, Query::hasAggs, Query::hasTargetSRFs, Query::havingQual, lfirst, linitial, list_head(), list_length(), lnext, NULL, OidIsValid, SetOperationStmt::op, TargetEntry::resjunk, TargetEntry::resno, SETOP_NONE, Query::setOperations, and Query::targetList.

Referenced by create_unique_path(), and rel_is_distinct_for().

688 {
689  ListCell *l;
690  Oid opid;
691 
692  Assert(list_length(colnos) == list_length(opids));
693 
694  /*
695  * A set-returning function in the query's targetlist can result in
696  * returning duplicate rows, if the SRF is evaluated after the
697  * de-duplication step; so we play it safe and say "no" if there are any
698  * SRFs. (We could be certain that it's okay if SRFs appear only in the
699  * specified columns, since those must be evaluated before de-duplication;
700  * but it doesn't presently seem worth the complication to check that.)
701  */
702  if (query->hasTargetSRFs)
703  return false;
704 
705  /*
706  * DISTINCT (including DISTINCT ON) guarantees uniqueness if all the
707  * columns in the DISTINCT clause appear in colnos and operator semantics
708  * match.
709  */
710  if (query->distinctClause)
711  {
712  foreach(l, query->distinctClause)
713  {
714  SortGroupClause *sgc = (SortGroupClause *) lfirst(l);
716  query->targetList);
717 
718  opid = distinct_col_search(tle->resno, colnos, opids);
719  if (!OidIsValid(opid) ||
720  !equality_ops_are_compatible(opid, sgc->eqop))
721  break; /* exit early if no match */
722  }
723  if (l == NULL) /* had matches for all? */
724  return true;
725  }
726 
727  /*
728  * Similarly, GROUP BY without GROUPING SETS guarantees uniqueness if all
729  * the grouped columns appear in colnos and operator semantics match.
730  */
731  if (query->groupClause && !query->groupingSets)
732  {
733  foreach(l, query->groupClause)
734  {
735  SortGroupClause *sgc = (SortGroupClause *) lfirst(l);
737  query->targetList);
738 
739  opid = distinct_col_search(tle->resno, colnos, opids);
740  if (!OidIsValid(opid) ||
741  !equality_ops_are_compatible(opid, sgc->eqop))
742  break; /* exit early if no match */
743  }
744  if (l == NULL) /* had matches for all? */
745  return true;
746  }
747  else if (query->groupingSets)
748  {
749  /*
750  * If we have grouping sets with expressions, we probably don't have
751  * uniqueness and analysis would be hard. Punt.
752  */
753  if (query->groupClause)
754  return false;
755 
756  /*
757  * If we have no groupClause (therefore no grouping expressions), we
758  * might have one or many empty grouping sets. If there's just one,
759  * then we're returning only one row and are certainly unique. But
760  * otherwise, we know we're certainly not unique.
761  */
762  if (list_length(query->groupingSets) == 1 &&
763  ((GroupingSet *) linitial(query->groupingSets))->kind == GROUPING_SET_EMPTY)
764  return true;
765  else
766  return false;
767  }
768  else
769  {
770  /*
771  * If we have no GROUP BY, but do have aggregates or HAVING, then the
772  * result is at most one row so it's surely unique, for any operators.
773  */
774  if (query->hasAggs || query->havingQual)
775  return true;
776  }
777 
778  /*
779  * UNION, INTERSECT, EXCEPT guarantee uniqueness of the whole output row,
780  * except with ALL.
781  */
782  if (query->setOperations)
783  {
785 
786  Assert(topop->op != SETOP_NONE);
787 
788  if (!topop->all)
789  {
790  ListCell *lg;
791 
792  /* We're good if all the nonjunk output columns are in colnos */
793  lg = list_head(topop->groupClauses);
794  foreach(l, query->targetList)
795  {
796  TargetEntry *tle = (TargetEntry *) lfirst(l);
797  SortGroupClause *sgc;
798 
799  if (tle->resjunk)
800  continue; /* ignore resjunk columns */
801 
802  /* non-resjunk columns should have grouping clauses */
803  Assert(lg != NULL);
804  sgc = (SortGroupClause *) lfirst(lg);
805  lg = lnext(lg);
806 
807  opid = distinct_col_search(tle->resno, colnos, opids);
808  if (!OidIsValid(opid) ||
809  !equality_ops_are_compatible(opid, sgc->eqop))
810  break; /* exit early if no match */
811  }
812  if (l == NULL) /* had matches for all? */
813  return true;
814  }
815  }
816 
817  /*
818  * XXX Are there any other cases in which we can easily see the result
819  * must be distinct?
820  *
821  * If you do add more smarts to this function, be sure to update
822  * query_supports_distinctness() to match.
823  */
824 
825  return false;
826 }
TargetEntry * get_sortgroupclause_tle(SortGroupClause *sgClause, List *targetList)
Definition: tlist.c:370
#define castNode(_type_, nodeptr)
Definition: nodes.h:578
static Oid distinct_col_search(int colno, List *colnos, List *opids)
Definition: analyzejoins.c:836
bool hasAggs
Definition: parsenodes.h:116
List * groupingSets
Definition: parsenodes.h:139
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:534
List * targetList
Definition: parsenodes.h:131
bool resjunk
Definition: primnodes.h:1337
#define linitial(l)
Definition: pg_list.h:110
List * distinctClause
Definition: parsenodes.h:145
AttrNumber resno
Definition: primnodes.h:1331
static ListCell * list_head(const List *l)
Definition: pg_list.h:77
#define lnext(lc)
Definition: pg_list.h:105
bool hasTargetSRFs
Definition: parsenodes.h:118
#define NULL
Definition: c.h:226
#define Assert(condition)
Definition: c.h:671
#define lfirst(lc)
Definition: pg_list.h:106
bool equality_ops_are_compatible(Oid opno1, Oid opno2)
Definition: lsyscache.c:695
static int list_length(const List *l)
Definition: pg_list.h:89
SetOperation op
Definition: parsenodes.h:1485
Node * setOperations
Definition: parsenodes.h:154
List * groupClause
Definition: parsenodes.h:137
Node * havingQual
Definition: parsenodes.h:141
RelOptInfo* query_planner ( PlannerInfo root,
List tlist,
query_pathkeys_callback  qp_callback,
void *  qp_extra 
)

Definition at line 54 of file planmain.c.

References add_base_rels_to_query(), add_path(), add_placeholders_to_base_rels(), Assert, build_base_rel_tlists(), build_empty_join_rel(), PlannerInfo::canon_pathkeys, RelOptInfo::cheapest_total_path, RelOptInfo::consider_parallel, create_lateral_join_info(), create_result_path(), deconstruct_jointree(), elog, ERROR, extract_restriction_or_clauses(), find_lateral_references(), find_placeholders_in_jointree(), fix_placeholder_input_needed_levels(), PlannerInfo::fkey_list, FromExpr::fromlist, PlannerInfo::full_join_clauses, generate_base_implied_equalities(), PlannerInfo::glob, PlannerInfo::initial_rels, is_parallel_safe(), PlannerInfo::join_cur_level, PlannerInfo::join_info_list, PlannerInfo::join_rel_hash, PlannerInfo::join_rel_level, PlannerInfo::join_rel_list, Query::jointree, PlannerInfo::left_join_clauses, make_one_rel(), match_foreign_keys_to_quals(), NIL, NULL, RelOptInfo::pages, PlannerGlobal::parallelModeOK, Path::param_info, parse(), PlannerInfo::parse, PlannerInfo::placeholder_list, FromExpr::quals, reconsider_outer_join_clauses(), RelOptInfo::relid, RELOPT_BASEREL, RELOPT_OTHER_MEMBER_REL, RelOptInfo::reloptkind, RelOptInfo::reltarget, remove_useless_joins(), PlannerInfo::right_join_clauses, set_cheapest(), and setup_simple_rel_arrays().

Referenced by build_minmax_path(), and grouping_planner().

56 {
57  Query *parse = root->parse;
58  List *joinlist;
59  RelOptInfo *final_rel;
60  Index rti;
61  double total_pages;
62 
63  /*
64  * If the query has an empty join tree, then it's something easy like
65  * "SELECT 2+2;" or "INSERT ... VALUES()". Fall through quickly.
66  */
67  if (parse->jointree->fromlist == NIL)
68  {
69  /* We need a dummy joinrel to describe the empty set of baserels */
70  final_rel = build_empty_join_rel(root);
71 
72  /*
73  * If query allows parallelism in general, check whether the quals are
74  * parallel-restricted. (We need not check final_rel->reltarget
75  * because it's empty at this point. Anything parallel-restricted in
76  * the query tlist will be dealt with later.)
77  */
78  if (root->glob->parallelModeOK)
79  final_rel->consider_parallel =
80  is_parallel_safe(root, parse->jointree->quals);
81 
82  /* The only path for it is a trivial Result path */
83  add_path(final_rel, (Path *)
84  create_result_path(root, final_rel,
85  final_rel->reltarget,
86  (List *) parse->jointree->quals));
87 
88  /* Select cheapest path (pretty easy in this case...) */
89  set_cheapest(final_rel);
90 
91  /*
92  * We still are required to call qp_callback, in case it's something
93  * like "SELECT 2+2 ORDER BY 1".
94  */
95  root->canon_pathkeys = NIL;
96  (*qp_callback) (root, qp_extra);
97 
98  return final_rel;
99  }
100 
101  /*
102  * Init planner lists to empty.
103  *
104  * NOTE: append_rel_list was set up by subquery_planner, so do not touch
105  * here.
106  */
107  root->join_rel_list = NIL;
108  root->join_rel_hash = NULL;
109  root->join_rel_level = NULL;
110  root->join_cur_level = 0;
111  root->canon_pathkeys = NIL;
112  root->left_join_clauses = NIL;
113  root->right_join_clauses = NIL;
114  root->full_join_clauses = NIL;
115  root->join_info_list = NIL;
116  root->placeholder_list = NIL;
117  root->fkey_list = NIL;
118  root->initial_rels = NIL;
119 
120  /*
121  * Make a flattened version of the rangetable for faster access (this is
122  * OK because the rangetable won't change any more), and set up an empty
123  * array for indexing base relations.
124  */
126 
127  /*
128  * Construct RelOptInfo nodes for all base relations in query, and
129  * indirectly for all appendrel member relations ("other rels"). This
130  * will give us a RelOptInfo for every "simple" (non-join) rel involved in
131  * the query.
132  *
133  * Note: the reason we find the rels by searching the jointree and
134  * appendrel list, rather than just scanning the rangetable, is that the
135  * rangetable may contain RTEs for rels not actively part of the query,
136  * for example views. We don't want to make RelOptInfos for them.
137  */
138  add_base_rels_to_query(root, (Node *) parse->jointree);
139 
140  /*
141  * Examine the targetlist and join tree, adding entries to baserel
142  * targetlists for all referenced Vars, and generating PlaceHolderInfo
143  * entries for all referenced PlaceHolderVars. Restrict and join clauses
144  * are added to appropriate lists belonging to the mentioned relations. We
145  * also build EquivalenceClasses for provably equivalent expressions. The
146  * SpecialJoinInfo list is also built to hold information about join order
147  * restrictions. Finally, we form a target joinlist for make_one_rel() to
148  * work from.
149  */
150  build_base_rel_tlists(root, tlist);
151 
153 
155 
156  joinlist = deconstruct_jointree(root);
157 
158  /*
159  * Reconsider any postponed outer-join quals now that we have built up
160  * equivalence classes. (This could result in further additions or
161  * mergings of classes.)
162  */
164 
165  /*
166  * If we formed any equivalence classes, generate additional restriction
167  * clauses as appropriate. (Implied join clauses are formed on-the-fly
168  * later.)
169  */
171 
172  /*
173  * We have completed merging equivalence sets, so it's now possible to
174  * generate pathkeys in canonical form; so compute query_pathkeys and
175  * other pathkeys fields in PlannerInfo.
176  */
177  (*qp_callback) (root, qp_extra);
178 
179  /*
180  * Examine any "placeholder" expressions generated during subquery pullup.
181  * Make sure that the Vars they need are marked as needed at the relevant
182  * join level. This must be done before join removal because it might
183  * cause Vars or placeholders to be needed above a join when they weren't
184  * so marked before.
185  */
187 
188  /*
189  * Remove any useless outer joins. Ideally this would be done during
190  * jointree preprocessing, but the necessary information isn't available
191  * until we've built baserel data structures and classified qual clauses.
192  */
193  joinlist = remove_useless_joins(root, joinlist);
194 
195  /*
196  * Now distribute "placeholders" to base rels as needed. This has to be
197  * done after join removal because removal could change whether a
198  * placeholder is evaluable at a base rel.
199  */
201 
202  /*
203  * Construct the lateral reference sets now that we have finalized
204  * PlaceHolderVar eval levels.
205  */
207 
208  /*
209  * Match foreign keys to equivalence classes and join quals. This must be
210  * done after finalizing equivalence classes, and it's useful to wait till
211  * after join removal so that we can skip processing foreign keys
212  * involving removed relations.
213  */
215 
216  /*
217  * Look for join OR clauses that we can extract single-relation
218  * restriction OR clauses from.
219  */
221 
222  /*
223  * We should now have size estimates for every actual table involved in
224  * the query, and we also know which if any have been deleted from the
225  * query by join removal; so we can compute total_table_pages.
226  *
227  * Note that appendrels are not double-counted here, even though we don't
228  * bother to distinguish RelOptInfos for appendrel parents, because the
229  * parents will still have size zero.
230  *
231  * XXX if a table is self-joined, we will count it once per appearance,
232  * which perhaps is the wrong thing ... but that's not completely clear,
233  * and detecting self-joins here is difficult, so ignore it for now.
234  */
235  total_pages = 0;
236  for (rti = 1; rti < root->simple_rel_array_size; rti++)
237  {
238  RelOptInfo *brel = root->simple_rel_array[rti];
239 
240  if (brel == NULL)
241  continue;
242 
243  Assert(brel->relid == rti); /* sanity check on array */
244 
245  if (brel->reloptkind == RELOPT_BASEREL ||
247  total_pages += (double) brel->pages;
248  }
249  root->total_table_pages = total_pages;
250 
251  /*
252  * Ready to do the primary planning.
253  */
254  final_rel = make_one_rel(root, joinlist);
255 
256  /* Check that we got at least one usable path */
257  if (!final_rel || !final_rel->cheapest_total_path ||
258  final_rel->cheapest_total_path->param_info != NULL)
259  elog(ERROR, "failed to construct the join relation");
260 
261  return final_rel;
262 }
#define NIL
Definition: pg_list.h:69
int join_cur_level
Definition: relation.h:223
RelOptInfo * make_one_rel(PlannerInfo *root, List *joinlist)
Definition: allpaths.c:138
Query * parse
Definition: relation.h:152
void add_path(RelOptInfo *parent_rel, Path *new_path)
Definition: pathnode.c:412
RelOptKind reloptkind
Definition: relation.h:487
void add_base_rels_to_query(PlannerInfo *root, Node *jtnode)
Definition: initsplan.c:104
List * join_info_list
Definition: relation.h:247
FromExpr * jointree
Definition: parsenodes.h:129
void extract_restriction_or_clauses(PlannerInfo *root)
Definition: orclauses.c:73
List * deconstruct_jointree(PlannerInfo *root)
Definition: initsplan.c:690
ParamPathInfo * param_info
Definition: relation.h:897
Definition: nodes.h:509
List * join_rel_list
Definition: relation.h:212
List * fromlist
Definition: primnodes.h:1433
List * fkey_list
Definition: relation.h:255
void add_placeholders_to_base_rels(PlannerInfo *root)
Definition: placeholder.c:379
Node * quals
Definition: primnodes.h:1434
bool is_parallel_safe(PlannerInfo *root, Node *node)
Definition: clauses.c:1071
#define ERROR
Definition: elog.h:43
bool parallelModeOK
Definition: relation.h:126
struct Path * cheapest_total_path
Definition: relation.h:508
PlannerGlobal * glob
Definition: relation.h:154
List * left_join_clauses
Definition: relation.h:236
List * full_join_clauses
Definition: relation.h:244
List * canon_pathkeys
Definition: relation.h:234
Index relid
Definition: relation.h:518
void fix_placeholder_input_needed_levels(PlannerInfo *root)
Definition: placeholder.c:350
void set_cheapest(RelOptInfo *parent_rel)
Definition: pathnode.c:234
void find_placeholders_in_jointree(PlannerInfo *root)
Definition: placeholder.c:144
void generate_base_implied_equalities(PlannerInfo *root)
Definition: equivclass.c:762
unsigned int Index
Definition: c.h:362
void reconsider_outer_join_clauses(PlannerInfo *root)
Definition: equivclass.c:1532
BlockNumber pages
Definition: relation.h:528
#define NULL
Definition: c.h:226
#define Assert(condition)
Definition: c.h:671
RelOptInfo * build_empty_join_rel(PlannerInfo *root)
Definition: relnode.c:836
List ** join_rel_level
Definition: relation.h:222
void setup_simple_rel_arrays(PlannerInfo *root)
Definition: relnode.c:59
List * remove_useless_joins(PlannerInfo *root, List *joinlist)
Definition: analyzejoins.c:55
struct HTAB * join_rel_hash
Definition: relation.h:213
void build_base_rel_tlists(PlannerInfo *root, List *final_tlist)
Definition: initsplan.c:150
bool consider_parallel
Definition: relation.h:498
void match_foreign_keys_to_quals(PlannerInfo *root)
Definition: initsplan.c:2410
List * placeholder_list
Definition: relation.h:253
ResultPath * create_result_path(PlannerInfo *root, RelOptInfo *rel, PathTarget *target, List *resconstantqual)
Definition: pathnode.c:1346
List * initial_rels
Definition: relation.h:264
List * right_join_clauses
Definition: relation.h:240
#define elog
Definition: elog.h:219
Definition: pg_list.h:45
struct PathTarget * reltarget
Definition: relation.h:501
void create_lateral_join_info(PlannerInfo *root)
Definition: initsplan.c:415
Definition: relation.h:888
void find_lateral_references(PlannerInfo *root)
Definition: initsplan.c:271
static struct subre * parse(struct vars *, int, int, struct state *, struct state *)
Definition: regcomp.c:651
bool query_supports_distinctness ( Query query)

Definition at line 650 of file analyzejoins.c.

References Query::distinctClause, Query::groupClause, Query::groupingSets, Query::hasAggs, Query::hasTargetSRFs, Query::havingQual, NIL, and Query::setOperations.

Referenced by create_unique_path(), and rel_supports_distinctness().

651 {
652  /* we don't cope with SRFs, see comment below */
653  if (query->hasTargetSRFs)
654  return false;
655 
656  /* check for features we can prove distinctness with */
657  if (query->distinctClause != NIL ||
658  query->groupClause != NIL ||
659  query->groupingSets != NIL ||
660  query->hasAggs ||
661  query->havingQual ||
662  query->setOperations)
663  return true;
664 
665  return false;
666 }
#define NIL
Definition: pg_list.h:69
bool hasAggs
Definition: parsenodes.h:116
List * groupingSets
Definition: parsenodes.h:139
List * distinctClause
Definition: parsenodes.h:145
bool hasTargetSRFs
Definition: parsenodes.h:118
Node * setOperations
Definition: parsenodes.h:154
List * groupClause
Definition: parsenodes.h:137
Node * havingQual
Definition: parsenodes.h:141
void record_plan_function_dependency ( PlannerInfo root,
Oid  funcid 
)

Definition at line 2437 of file setrefs.c.

References PlanInvalItem::cacheId, FirstBootstrapObjectId, GetSysCacheHashValue1, PlannerInfo::glob, PlanInvalItem::hashValue, PlannerGlobal::invalItems, lappend(), makeNode, ObjectIdGetDatum, and PROCOID.

Referenced by fix_expr_common(), inline_function(), and inline_set_returning_function().

2438 {
2439  /*
2440  * For performance reasons, we don't bother to track built-in functions;
2441  * we just assume they'll never change (or at least not in ways that'd
2442  * invalidate plans using them). For this purpose we can consider a
2443  * built-in function to be one with OID less than FirstBootstrapObjectId.
2444  * Note that the OID generator guarantees never to generate such an OID
2445  * after startup, even at OID wraparound.
2446  */
2447  if (funcid >= (Oid) FirstBootstrapObjectId)
2448  {
2449  PlanInvalItem *inval_item = makeNode(PlanInvalItem);
2450 
2451  /*
2452  * It would work to use any syscache on pg_proc, but the easiest is
2453  * PROCOID since we already have the function's OID at hand. Note
2454  * that plancache.c knows we use PROCOID.
2455  */
2456  inval_item->cacheId = PROCOID;
2457  inval_item->hashValue = GetSysCacheHashValue1(PROCOID,
2458  ObjectIdGetDatum(funcid));
2459 
2460  root->glob->invalItems = lappend(root->glob->invalItems, inval_item);
2461  }
2462 }
#define GetSysCacheHashValue1(cacheId, key1)
Definition: syscache.h:185
unsigned int Oid
Definition: postgres_ext.h:31
#define ObjectIdGetDatum(X)
Definition: postgres.h:515
PlannerGlobal * glob
Definition: relation.h:154
#define FirstBootstrapObjectId
Definition: transam.h:93
List * lappend(List *list, void *datum)
Definition: list.c:128
List * invalItems
Definition: relation.h:112
uint32 hashValue
Definition: plannodes.h:964
#define makeNode(_type_)
Definition: nodes.h:557
List* remove_useless_joins ( PlannerInfo root,
List joinlist 
)

Definition at line 55 of file analyzejoins.c.

References bms_singleton_member(), bms_union(), elog, ERROR, PlannerInfo::join_info_list, join_is_removable(), lfirst, list_delete_ptr(), SpecialJoinInfo::min_lefthand, SpecialJoinInfo::min_righthand, remove_rel_from_joinlist(), and remove_rel_from_query().

Referenced by query_planner().

56 {
57  ListCell *lc;
58 
59  /*
60  * We are only interested in relations that are left-joined to, so we can
61  * scan the join_info_list to find them easily.
62  */
63 restart:
64  foreach(lc, root->join_info_list)
65  {
66  SpecialJoinInfo *sjinfo = (SpecialJoinInfo *) lfirst(lc);
67  int innerrelid;
68  int nremoved;
69 
70  /* Skip if not removable */
71  if (!join_is_removable(root, sjinfo))
72  continue;
73 
74  /*
75  * Currently, join_is_removable can only succeed when the sjinfo's
76  * righthand is a single baserel. Remove that rel from the query and
77  * joinlist.
78  */
79  innerrelid = bms_singleton_member(sjinfo->min_righthand);
80 
81  remove_rel_from_query(root, innerrelid,
82  bms_union(sjinfo->min_lefthand,
83  sjinfo->min_righthand));
84 
85  /* We verify that exactly one reference gets removed from joinlist */
86  nremoved = 0;
87  joinlist = remove_rel_from_joinlist(joinlist, innerrelid, &nremoved);
88  if (nremoved != 1)
89  elog(ERROR, "failed to find relation %d in joinlist", innerrelid);
90 
91  /*
92  * We can delete this SpecialJoinInfo from the list too, since it's no
93  * longer of interest.
94  */
95  root->join_info_list = list_delete_ptr(root->join_info_list, sjinfo);
96 
97  /*
98  * Restart the scan. This is necessary to ensure we find all
99  * removable joins independently of ordering of the join_info_list
100  * (note that removal of attr_needed bits may make a join appear
101  * removable that did not before). Also, since we just deleted the
102  * current list cell, we'd have to have some kluge to continue the
103  * list scan anyway.
104  */
105  goto restart;
106  }
107 
108  return joinlist;
109 }
List * join_info_list
Definition: relation.h:247
Relids min_righthand
Definition: relation.h:1808
static void remove_rel_from_query(PlannerInfo *root, int relid, Relids joinrelids)
Definition: analyzejoins.c:308
List * list_delete_ptr(List *list, void *datum)
Definition: list.c:590
#define ERROR
Definition: elog.h:43
static bool join_is_removable(PlannerInfo *root, SpecialJoinInfo *sjinfo)
Definition: analyzejoins.c:154
int bms_singleton_member(const Bitmapset *a)
Definition: bitmapset.c:496
#define lfirst(lc)
Definition: pg_list.h:106
Bitmapset * bms_union(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:217
static List * remove_rel_from_joinlist(List *joinlist, int relid, int *nremoved)
Definition: analyzejoins.c:453
#define elog
Definition: elog.h:219
Relids min_lefthand
Definition: relation.h:1807
Plan* set_plan_references ( PlannerInfo root,
Plan plan 
)

Definition at line 209 of file setrefs.c.

References add_rtes_to_flat_rtable(), castNode, PlannerGlobal::finalrowmarks, PlannerGlobal::finalrtable, PlannerInfo::glob, lappend(), lfirst, list_length(), palloc(), PlanRowMark::prti, PlannerInfo::rowMarks, PlanRowMark::rti, and set_plan_refs().

Referenced by set_subqueryscan_references(), and standard_planner().

210 {
211  PlannerGlobal *glob = root->glob;
212  int rtoffset = list_length(glob->finalrtable);
213  ListCell *lc;
214 
215  /*
216  * Add all the query's RTEs to the flattened rangetable. The live ones
217  * will have their rangetable indexes increased by rtoffset. (Additional
218  * RTEs, not referenced by the Plan tree, might get added after those.)
219  */
220  add_rtes_to_flat_rtable(root, false);
221 
222  /*
223  * Adjust RT indexes of PlanRowMarks and add to final rowmarks list
224  */
225  foreach(lc, root->rowMarks)
226  {
228  PlanRowMark *newrc;
229 
230  /* flat copy is enough since all fields are scalars */
231  newrc = (PlanRowMark *) palloc(sizeof(PlanRowMark));
232  memcpy(newrc, rc, sizeof(PlanRowMark));
233 
234  /* adjust indexes ... but *not* the rowmarkId */
235  newrc->rti += rtoffset;
236  newrc->prti += rtoffset;
237 
238  glob->finalrowmarks = lappend(glob->finalrowmarks, newrc);
239  }
240 
241  /* Now fix the Plan tree */
242  return set_plan_refs(root, plan, rtoffset);
243 }
List * rowMarks
Definition: relation.h:251
#define castNode(_type_, nodeptr)
Definition: nodes.h:578
Index prti
Definition: plannodes.h:941
static Plan * set_plan_refs(PlannerInfo *root, Plan *plan, int rtoffset)
Definition: setrefs.c:433
PlannerGlobal * glob
Definition: relation.h:154
List * lappend(List *list, void *datum)
Definition: list.c:128
Index rti
Definition: plannodes.h:940
#define lfirst(lc)
Definition: pg_list.h:106
static void add_rtes_to_flat_rtable(PlannerInfo *root, bool recursing)
Definition: setrefs.c:251
static int list_length(const List *l)
Definition: pg_list.h:89
List * finalrtable
Definition: relation.h:104
void * palloc(Size size)
Definition: mcxt.c:891
List * finalrowmarks
Definition: relation.h:106

Variable Documentation

double cursor_tuple_fraction

Definition at line 61 of file planner.c.

Referenced by standard_planner().

int force_parallel_mode

Definition at line 62 of file planner.c.

Referenced by HandleParallelMessage(), and standard_planner().

int from_collapse_limit

Definition at line 36 of file initsplan.c.

Referenced by deconstruct_recurse().

int join_collapse_limit

Definition at line 37 of file initsplan.c.

Referenced by deconstruct_recurse().