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)
 
bool innerrel_is_unique (PlannerInfo *root, RelOptInfo *outerrel, RelOptInfo *innerrel, JoinType jointype, List *restrictlist)
 
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, and JoinExpr::rarg.

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, NULL);
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:1470
Node * larg
Definition: primnodes.h:1450
#define ERROR
Definition: elog.h:43
RelOptInfo * build_simple_rel(PlannerInfo *root, int relid, RelOptInfo *parent)
Definition: relnode.c:91
Node * rarg
Definition: primnodes.h:1451
#define NULL
Definition: c.h:229
#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:2065
#define IsA(nodeptr, _type_)
Definition: nodes.h:560
Relids * attr_needed
Definition: relation.h:557
Definition: nodes.h:509
AttrNumber varattno
Definition: primnodes.h:168
Definition: primnodes.h:163
#define ERROR
Definition: elog.h:43
bool bms_is_subset(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:308
PlaceHolderInfo * find_placeholder_info(PlannerInfo *root, PlaceHolderVar *phv, bool create_new_ph)
Definition: placeholder.c:69
Relids relids
Definition: relation.h:524
List * lappend(List *list, void *datum)
Definition: list.c:128
bool bms_is_empty(const Bitmapset *a)
Definition: bitmapset.c:663
Index varno
Definition: primnodes.h:166
List * exprs
Definition: relation.h:882
#define NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:675
#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:243
#define copyObject(obj)
Definition: nodes.h:621
struct PathTarget * reltarget
Definition: relation.h:535
Bitmapset * bms_add_members(Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:755
AttrNumber min_attr
Definition: relation.h:555
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:154
#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:179
#define PVC_RECURSE_WINDOWFUNCS
Definition: var.h:23
void list_free(List *list)
Definition: list.c:1133
Node * havingQual
Definition: parsenodes.h:150
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 2354 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().

2361 {
2362  RestrictInfo *restrictinfo;
2363  Expr *clause;
2364 
2365  /*
2366  * Build the new clause. Copy to ensure it shares no substructure with
2367  * original (this is necessary in case there are subselects in there...)
2368  */
2369  clause = make_opclause(opno,
2370  BOOLOID, /* opresulttype */
2371  false, /* opretset */
2372  copyObject(item1),
2373  copyObject(item2),
2374  InvalidOid,
2375  collation);
2376 
2377  /*
2378  * Build the RestrictInfo node itself.
2379  */
2380  restrictinfo = make_restrictinfo(clause,
2381  true, /* is_pushed_down */
2382  false, /* outerjoin_delayed */
2383  false, /* pseudoconstant */
2384  security_level, /* security_level */
2385  qualscope, /* required_relids */
2386  NULL, /* outer_relids */
2387  nullable_relids); /* nullable_relids */
2388 
2389  /* Set mergejoinability/hashjoinability flags */
2390  check_mergejoinable(restrictinfo);
2391  check_hashjoinable(restrictinfo);
2392 
2393  return restrictinfo;
2394 }
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:172
#define InvalidOid
Definition: postgres_ext.h:36
#define NULL
Definition: c.h:229
static void check_mergejoinable(RestrictInfo *restrictinfo)
Definition: initsplan.c:2581
#define BOOLOID
Definition: pg_type.h:288
static void check_hashjoinable(RestrictInfo *restrictinfo)
Definition: initsplan.c:2618
#define copyObject(obj)
Definition: nodes.h:621
void create_lateral_join_info ( PlannerInfo root)

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

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

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

306 {
307  Plan *plan;
308 
309  /* plan_params should not be in use in current query level */
310  Assert(root->plan_params == NIL);
311 
312  /* Initialize this module's private workspace in PlannerInfo */
313  root->curOuterRels = NULL;
314  root->curOuterParams = NIL;
315 
316  /* Recursively process the path tree, demanding the correct tlist result */
317  plan = create_plan_recurse(root, best_path, CP_EXACT_TLIST);
318 
319  /*
320  * Make sure the topmost plan node's targetlist exposes the original
321  * column names and other decorative info. Targetlists generated within
322  * the planner don't bother with that stuff, but we must have it on the
323  * top-level tlist seen at execution time. However, ModifyTable plan
324  * nodes don't have a tlist matching the querytree targetlist.
325  */
326  if (!IsA(plan, ModifyTable))
328 
329  /*
330  * Attach any initPlans created in this query level to the topmost plan
331  * node. (In principle the initplans could go in any plan node at or
332  * above where they're referenced, but there seems no reason to put them
333  * any lower than the topmost node for the query level. Also, see
334  * comments for SS_finalize_plan before you try to change this.)
335  */
336  SS_attach_initplans(root, plan);
337 
338  /* Check we successfully assigned all NestLoopParams to plan nodes */
339  if (root->curOuterParams != NIL)
340  elog(ERROR, "failed to assign all NestLoopParams to plan nodes");
341 
342  /*
343  * Reset plan_params to ensure param IDs used for nestloop params are not
344  * re-used later
345  */
346  root->plan_params = NIL;
347 
348  return plan;
349 }
#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:168
Relids curOuterRels
Definition: relation.h:311
static Plan * create_plan_recurse(PlannerInfo *root, Path *best_path, int flags)
Definition: createplan.c:356
#define ERROR
Definition: elog.h:43
List * curOuterParams
Definition: relation.h:312
#define NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:675
void SS_attach_initplans(PlannerInfo *root, Plan *plan)
Definition: subselect.c:2202
List * targetlist
Definition: plannodes.h:134
#define elog
Definition: elog.h:219
List * processed_tlist
Definition: relation.h:280
#define CP_EXACT_TLIST
Definition: createplan.c:66
List* deconstruct_jointree ( PlannerInfo root)

Definition at line 692 of file initsplan.c.

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

Referenced by query_planner().

693 {
694  List *result;
695  Relids qualscope;
696  Relids inner_join_rels;
697  List *postponed_qual_list = NIL;
698 
699  /* Start recursion at top of jointree */
700  Assert(root->parse->jointree != NULL &&
701  IsA(root->parse->jointree, FromExpr));
702 
703  /* this is filled as we scan the jointree */
704  root->nullable_baserels = NULL;
705 
706  result = deconstruct_recurse(root, (Node *) root->parse->jointree, false,
707  &qualscope, &inner_join_rels,
708  &postponed_qual_list);
709 
710  /* Shouldn't be any leftover quals */
711  Assert(postponed_qual_list == NIL);
712 
713  return result;
714 }
#define NIL
Definition: pg_list.h:69
#define IsA(nodeptr, _type_)
Definition: nodes.h:560
Query * parse
Definition: relation.h:154
FromExpr * jointree
Definition: parsenodes.h:136
Definition: nodes.h:509
return result
Definition: formatting.c:1618
#define NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:675
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:738
Relids nullable_baserels
Definition: relation.h:203
Definition: pg_list.h:45
void distribute_restrictinfo_to_rels ( PlannerInfo root,
RestrictInfo restrictinfo 
)

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

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

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

2526 {
2527  PlannerGlobal glob;
2528  PlannerInfo root;
2529 
2530  /* Make up dummy planner state so we can use this module's machinery */
2531  MemSet(&glob, 0, sizeof(glob));
2532  glob.type = T_PlannerGlobal;
2533  glob.relationOids = NIL;
2534  glob.invalItems = NIL;
2535  /* Hack: we use glob.dependsOnRole to collect hasRowSecurity flags */
2536  glob.dependsOnRole = false;
2537 
2538  MemSet(&root, 0, sizeof(root));
2539  root.type = T_PlannerInfo;
2540  root.glob = &glob;
2541 
2542  (void) extract_query_dependencies_walker(query, &root);
2543 
2544  *relationOids = glob.relationOids;
2545  *invalItems = glob.invalItems;
2546  *hasRowSecurity = glob.dependsOnRole;
2547 }
#define NIL
Definition: pg_list.h:69
#define MemSet(start, val, len)
Definition: c.h:857
bool dependsOnRole
Definition: relation.h:126
PlannerGlobal * glob
Definition: relation.h:156
List * invalItems
Definition: relation.h:114
NodeTag type
Definition: relation.h:152
static bool extract_query_dependencies_walker(Node *node, PlannerInfo *context)
Definition: setrefs.c:2550
NodeTag type
Definition: relation.h:94
List * relationOids
Definition: relation.h:112
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:521
struct RelOptInfo ** simple_rel_array
Definition: relation.h:178
bool hasLateralRTEs
Definition: relation.h:299
int simple_rel_array_size
Definition: relation.h:179
Index relid
Definition: relation.h:552
unsigned int Index
Definition: c.h:365
#define NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:675
static void extract_lateral_references(PlannerInfo *root, RelOptInfo *brel, Index rtindex)
Definition: initsplan.c:319
bool innerrel_is_unique ( PlannerInfo root,
RelOptInfo outerrel,
RelOptInfo innerrel,
JoinType  jointype,
List restrictlist 
)

Definition at line 872 of file analyzejoins.c.

References bms_copy(), bms_is_subset(), is_innerrel_unique_for(), PlannerInfo::join_search_private, lappend(), lfirst, MemoryContextSwitchTo(), NIL, RelOptInfo::non_unique_for_rels, PlannerInfo::planner_cxt, rel_supports_distinctness(), RelOptInfo::relids, and RelOptInfo::unique_for_rels.

Referenced by add_paths_to_joinrel().

877 {
878  MemoryContext old_context;
879  ListCell *lc;
880 
881  /* Certainly can't prove uniqueness when there are no joinclauses */
882  if (restrictlist == NIL)
883  return false;
884 
885  /*
886  * Make a quick check to eliminate cases in which we will surely be unable
887  * to prove uniqueness of the innerrel.
888  */
889  if (!rel_supports_distinctness(root, innerrel))
890  return false;
891 
892  /*
893  * Query the cache to see if we've managed to prove that innerrel is
894  * unique for any subset of this outerrel. We don't need an exact match,
895  * as extra outerrels can't make the innerrel any less unique (or more
896  * formally, the restrictlist for a join to a superset outerrel must be a
897  * superset of the conditions we successfully used before).
898  */
899  foreach(lc, innerrel->unique_for_rels)
900  {
901  Relids unique_for_rels = (Relids) lfirst(lc);
902 
903  if (bms_is_subset(unique_for_rels, outerrel->relids))
904  return true; /* Success! */
905  }
906 
907  /*
908  * Conversely, we may have already determined that this outerrel, or some
909  * superset thereof, cannot prove this innerrel to be unique.
910  */
911  foreach(lc, innerrel->non_unique_for_rels)
912  {
913  Relids unique_for_rels = (Relids) lfirst(lc);
914 
915  if (bms_is_subset(outerrel->relids, unique_for_rels))
916  return false;
917  }
918 
919  /* No cached information, so try to make the proof. */
920  if (is_innerrel_unique_for(root, outerrel, innerrel,
921  jointype, restrictlist))
922  {
923  /*
924  * Cache the positive result for future probes, being sure to keep it
925  * in the planner_cxt even if we are working in GEQO.
926  *
927  * Note: one might consider trying to isolate the minimal subset of
928  * the outerrels that proved the innerrel unique. But it's not worth
929  * the trouble, because the planner builds up joinrels incrementally
930  * and so we'll see the minimally sufficient outerrels before any
931  * supersets of them anyway.
932  */
933  old_context = MemoryContextSwitchTo(root->planner_cxt);
934  innerrel->unique_for_rels = lappend(innerrel->unique_for_rels,
935  bms_copy(outerrel->relids));
936  MemoryContextSwitchTo(old_context);
937 
938  return true; /* Success! */
939  }
940  else
941  {
942  /*
943  * None of the join conditions for outerrel proved innerrel unique, so
944  * we can safely reject this outerrel or any subset of it in future
945  * checks.
946  *
947  * However, in normal planning mode, caching this knowledge is totally
948  * pointless; it won't be queried again, because we build up joinrels
949  * from smaller to larger. It is useful in GEQO mode, where the
950  * knowledge can be carried across successive planning attempts; and
951  * it's likely to be useful when using join-search plugins, too. Hence
952  * cache only when join_search_private is non-NULL. (Yeah, that's a
953  * hack, but it seems reasonable.)
954  */
955  if (root->join_search_private)
956  {
957  old_context = MemoryContextSwitchTo(root->planner_cxt);
958  innerrel->non_unique_for_rels =
959  lappend(innerrel->non_unique_for_rels,
960  bms_copy(outerrel->relids));
961  MemoryContextSwitchTo(old_context);
962  }
963 
964  return false;
965  }
966 }
#define NIL
Definition: pg_list.h:69
List * unique_for_rels
Definition: relation.h:579
Bitmapset * bms_copy(const Bitmapset *a)
Definition: bitmapset.c:111
void * join_search_private
Definition: relation.h:315
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
static bool is_innerrel_unique_for(PlannerInfo *root, RelOptInfo *outerrel, RelOptInfo *innerrel, JoinType jointype, List *restrictlist)
Definition: analyzejoins.c:974
bool bms_is_subset(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:308
Relids relids
Definition: relation.h:524
List * non_unique_for_rels
Definition: relation.h:580
Bitmapset * Relids
Definition: relation.h:28
List * lappend(List *list, void *datum)
Definition: list.c:128
#define lfirst(lc)
Definition: pg_list.h:106
MemoryContext planner_cxt
Definition: relation.h:286
static bool rel_supports_distinctness(PlannerInfo *root, RelOptInfo *rel)
Definition: analyzejoins.c:510
bool is_projection_capable_path ( Path path)

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

6547 {
6548  /* Most plan types can project, so just list the ones that can't */
6549  switch (path->pathtype)
6550  {
6551  case T_Hash:
6552  case T_Material:
6553  case T_Sort:
6554  case T_Unique:
6555  case T_SetOp:
6556  case T_LockRows:
6557  case T_Limit:
6558  case T_ModifyTable:
6559  case T_MergeAppend:
6560  case T_RecursiveUnion:
6561  return false;
6562  case T_Append:
6563 
6564  /*
6565  * Append can't project, but if it's being used to represent a
6566  * dummy path, claim that it can project. This prevents us from
6567  * converting a rel from dummy to non-dummy status by applying a
6568  * projection to its dummy path.
6569  */
6570  return IS_DUMMY_PATH(path);
6571  case T_ProjectSet:
6572 
6573  /*
6574  * Although ProjectSet certainly projects, say "no" because we
6575  * don't want the planner to randomly replace its tlist with
6576  * something else; the SRFs have to stay at top level. This might
6577  * get relaxed later.
6578  */
6579  return false;
6580  default:
6581  break;
6582  }
6583  return true;
6584 }
Definition: nodes.h:79
Definition: nodes.h:48
Definition: nodes.h:75
#define IS_DUMMY_PATH(p)
Definition: relation.h:1182
NodeTag pathtype
Definition: relation.h:950
Definition: nodes.h:82
Definition: nodes.h:83
Definition: nodes.h:85
bool is_projection_capable_plan ( Plan plan)

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

6592 {
6593  /* Most plan types can project, so just list the ones that can't */
6594  switch (nodeTag(plan))
6595  {
6596  case T_Hash:
6597  case T_Material:
6598  case T_Sort:
6599  case T_Unique:
6600  case T_SetOp:
6601  case T_LockRows:
6602  case T_Limit:
6603  case T_ModifyTable:
6604  case T_Append:
6605  case T_MergeAppend:
6606  case T_RecursiveUnion:
6607  return false;
6608  case T_ProjectSet:
6609 
6610  /*
6611  * Although ProjectSet certainly projects, say "no" because we
6612  * don't want the planner to randomly replace its tlist with
6613  * something else; the SRFs have to stay at top level. This might
6614  * get relaxed later.
6615  */
6616  return false;
6617  default:
6618  break;
6619  }
6620  return true;
6621 }
Definition: nodes.h:79
Definition: nodes.h:48
Definition: nodes.h:75
Definition: nodes.h:82
#define nodeTag(nodeptr)
Definition: nodes.h:514
Definition: nodes.h:83
Definition: nodes.h:85
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 6011 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().

6016 {
6017  Agg *node = makeNode(Agg);
6018  Plan *plan = &node->plan;
6019  long numGroups;
6020 
6021  /* Reduce to long, but 'ware overflow! */
6022  numGroups = (long) Min(dNumGroups, (double) LONG_MAX);
6023 
6024  node->aggstrategy = aggstrategy;
6025  node->aggsplit = aggsplit;
6026  node->numCols = numGroupCols;
6027  node->grpColIdx = grpColIdx;
6028  node->grpOperators = grpOperators;
6029  node->numGroups = numGroups;
6030  node->aggParams = NULL; /* SS_finalize_plan() will fill this */
6031  node->groupingSets = groupingSets;
6032  node->chain = chain;
6033 
6034  plan->qual = qual;
6035  plan->targetlist = tlist;
6036  plan->lefttree = lefttree;
6037  plan->righttree = NULL;
6038 
6039  return node;
6040 }
int numCols
Definition: plannodes.h:776
List * qual
Definition: plannodes.h:135
AttrNumber * grpColIdx
Definition: plannodes.h:777
#define Min(x, y)
Definition: c.h:806
struct Plan * righttree
Definition: plannodes.h:137
AggStrategy aggstrategy
Definition: plannodes.h:774
Bitmapset * aggParams
Definition: plannodes.h:780
Plan plan
Definition: plannodes.h:773
List * groupingSets
Definition: plannodes.h:782
#define makeNode(_type_)
Definition: nodes.h:557
#define NULL
Definition: c.h:229
AggSplit aggsplit
Definition: plannodes.h:775
long numGroups
Definition: plannodes.h:779
struct Plan * lefttree
Definition: plannodes.h:136
List * targetlist
Definition: plannodes.h:134
Oid * grpOperators
Definition: plannodes.h:778
List * chain
Definition: plannodes.h:783
Definition: plannodes.h:771
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 5245 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().

5253 {
5254  ForeignScan *node = makeNode(ForeignScan);
5255  Plan *plan = &node->scan.plan;
5256 
5257  /* cost will be filled in by create_foreignscan_plan */
5258  plan->targetlist = qptlist;
5259  plan->qual = qpqual;
5260  plan->lefttree = outer_plan;
5261  plan->righttree = NULL;
5262  node->scan.scanrelid = scanrelid;
5263  node->operation = CMD_SELECT;
5264  /* fs_server will be filled in by create_foreignscan_plan */
5265  node->fs_server = InvalidOid;
5266  node->fdw_exprs = fdw_exprs;
5267  node->fdw_private = fdw_private;
5268  node->fdw_scan_tlist = fdw_scan_tlist;
5269  node->fdw_recheck_quals = fdw_recheck_quals;
5270  /* fs_relids will be filled in by create_foreignscan_plan */
5271  node->fs_relids = NULL;
5272  /* fsSystemCol will be filled in by create_foreignscan_plan */
5273  node->fsSystemCol = false;
5274 
5275  return node;
5276 }
List * qual
Definition: plannodes.h:135
Plan plan
Definition: plannodes.h:317
Index scanrelid
Definition: plannodes.h:318
Oid fs_server
Definition: plannodes.h:588
List * fdw_exprs
Definition: plannodes.h:589
List * fdw_private
Definition: plannodes.h:590
List * fdw_scan_tlist
Definition: plannodes.h:591
CmdType operation
Definition: plannodes.h:587
struct Plan * righttree
Definition: plannodes.h:137
List * fdw_recheck_quals
Definition: plannodes.h:592
#define InvalidOid
Definition: postgres_ext.h:36
#define makeNode(_type_)
Definition: nodes.h:557
#define NULL
Definition: c.h:229
struct Plan * lefttree
Definition: plannodes.h:136
List * targetlist
Definition: plannodes.h:134
bool fsSystemCol
Definition: plannodes.h:595
Bitmapset * fs_relids
Definition: plannodes.h:594
Limit* make_limit ( Plan lefttree,
Node limitOffset,
Node limitCount 
)

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

6349 {
6350  Limit *node = makeNode(Limit);
6351  Plan *plan = &node->plan;
6352 
6353  plan->targetlist = lefttree->targetlist;
6354  plan->qual = NIL;
6355  plan->lefttree = lefttree;
6356  plan->righttree = NULL;
6357 
6358  node->limitOffset = limitOffset;
6359  node->limitCount = limitCount;
6360 
6361  return node;
6362 }
#define NIL
Definition: pg_list.h:69
List * qual
Definition: plannodes.h:135
Plan plan
Definition: plannodes.h:908
Node * limitOffset
Definition: plannodes.h:909
struct Plan * righttree
Definition: plannodes.h:137
Node * limitCount
Definition: plannodes.h:910
#define makeNode(_type_)
Definition: nodes.h:557
#define NULL
Definition: c.h:229
struct Plan * lefttree
Definition: plannodes.h:136
List * targetlist
Definition: plannodes.h:134
Sort* make_sort_from_sortclauses ( List sortcls,
Plan lefttree 
)

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

5866 {
5867  List *sub_tlist = lefttree->targetlist;
5868  ListCell *l;
5869  int numsortkeys;
5870  AttrNumber *sortColIdx;
5871  Oid *sortOperators;
5872  Oid *collations;
5873  bool *nullsFirst;
5874 
5875  /* Convert list-ish representation to arrays wanted by executor */
5876  numsortkeys = list_length(sortcls);
5877  sortColIdx = (AttrNumber *) palloc(numsortkeys * sizeof(AttrNumber));
5878  sortOperators = (Oid *) palloc(numsortkeys * sizeof(Oid));
5879  collations = (Oid *) palloc(numsortkeys * sizeof(Oid));
5880  nullsFirst = (bool *) palloc(numsortkeys * sizeof(bool));
5881 
5882  numsortkeys = 0;
5883  foreach(l, sortcls)
5884  {
5885  SortGroupClause *sortcl = (SortGroupClause *) lfirst(l);
5886  TargetEntry *tle = get_sortgroupclause_tle(sortcl, sub_tlist);
5887 
5888  sortColIdx[numsortkeys] = tle->resno;
5889  sortOperators[numsortkeys] = sortcl->sortop;
5890  collations[numsortkeys] = exprCollation((Node *) tle->expr);
5891  nullsFirst[numsortkeys] = sortcl->nulls_first;
5892  numsortkeys++;
5893  }
5894 
5895  return make_sort(lefttree, numsortkeys,
5896  sortColIdx, sortOperators,
5897  collations, nullsFirst);
5898 }
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:1368
static Sort * make_sort(Plan *lefttree, int numCols, AttrNumber *sortColIdx, Oid *sortOperators, Oid *collations, bool *nullsFirst)
Definition: createplan.c:5493
#define lfirst(lc)
Definition: pg_list.h:106
Expr * expr
Definition: primnodes.h:1367
static int list_length(const List *l)
Definition: pg_list.h:89
Oid exprCollation(const Node *expr)
Definition: nodeFuncs.c:748
List * targetlist
Definition: plannodes.h:134
void * palloc(Size size)
Definition: mcxt.c:849
Definition: pg_list.h:45
int16 AttrNumber
Definition: attnum.h:21
void match_foreign_keys_to_quals ( PlannerInfo root)

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

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

Definition at line 5977 of file createplan.c.

References cost_material(), Plan::initPlan, make_material(), NIL, Plan::parallel_aware, Plan::parallel_safe, 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().

5978 {
5979  Plan *matplan;
5980  Path matpath; /* dummy for result of cost_material */
5981 
5982  matplan = (Plan *) make_material(subplan);
5983 
5984  /*
5985  * XXX horrid kluge: if there are any initPlans attached to the subplan,
5986  * move them up to the Material node, which is now effectively the top
5987  * plan node in its query level. This prevents failure in
5988  * SS_finalize_plan(), which see for comments. We don't bother adjusting
5989  * the subplan's cost estimate for this.
5990  */
5991  matplan->initPlan = subplan->initPlan;
5992  subplan->initPlan = NIL;
5993 
5994  /* Set cost data */
5995  cost_material(&matpath,
5996  subplan->startup_cost,
5997  subplan->total_cost,
5998  subplan->plan_rows,
5999  subplan->plan_width);
6000  matplan->startup_cost = matpath.startup_cost;
6001  matplan->total_cost = matpath.total_cost;
6002  matplan->plan_rows = subplan->plan_rows;
6003  matplan->plan_width = subplan->plan_width;
6004  matplan->parallel_aware = false;
6005  matplan->parallel_safe = subplan->parallel_safe;
6006 
6007  return matplan;
6008 }
#define NIL
Definition: pg_list.h:69
double plan_rows
Definition: plannodes.h:121
static Material * make_material(Plan *lefttree)
Definition: createplan.c:5955
Cost startup_cost
Definition: relation.h:964
Cost startup_cost
Definition: plannodes.h:115
bool parallel_aware
Definition: plannodes.h:127
Cost total_cost
Definition: relation.h:965
void cost_material(Path *path, Cost input_startup_cost, Cost input_total_cost, double tuples, int width)
Definition: costsize.c:1819
int plan_width
Definition: plannodes.h:122
List * initPlan
Definition: plannodes.h:138
Cost total_cost
Definition: plannodes.h:116
bool parallel_safe
Definition: plannodes.h:128
Definition: relation.h:946
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:2886
#define IsA(nodeptr, _type_)
Definition: nodes.h:560
Query * parse
Definition: relation.h:154
void add_path(RelOptInfo *parent_rel, Path *new_path)
Definition: pathnode.c:412
FromExpr * jointree
Definition: parsenodes.h:136
bool hasAggs
Definition: parsenodes.h:123
Oid get_equality_op_for_ordering_op(Oid opno, bool *reverse)
Definition: lsyscache.c:264
Param * param
Definition: relation.h:2084
List * groupingSets
Definition: parsenodes.h:148
Definition: nodes.h:509
List * minmax_aggs
Definition: relation.h:284
List * fromlist
Definition: primnodes.h:1470
unsigned int Oid
Definition: postgres_ext.h:31
List * rowMarks
Definition: parsenodes.h:161
#define OidIsValid(objectId)
Definition: c.h:538
#define linitial(l)
Definition: pg_list.h:111
#define planner_rt_fetch(rti, root)
Definition: relation.h:324
#define ERROR
Definition: elog.h:43
RelOptInfo * fetch_upper_rel(PlannerInfo *root, UpperRelationKind kind, Relids relids)
Definition: relnode.c:919
#define create_pathtarget(root, tlist)
Definition: tlist.h:69
#define NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:675
#define lfirst(lc)
Definition: pg_list.h:106
Expr * target
Definition: relation.h:2080
bool hasWindowFuncs
Definition: parsenodes.h:124
Param * SS_make_initplan_output_param(PlannerInfo *root, Oid resulttype, int32 resulttypmod, Oid resultcollation)
Definition: subselect.c:2887
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:748
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:929
List * cteList
Definition: parsenodes.h:133
Node * setOperations
Definition: parsenodes.h:163
List * groupClause
Definition: parsenodes.h:146
#define elog
Definition: elog.h:219
Node * havingQual
Definition: parsenodes.h:150
Definition: pg_list.h:45
Definition: relation.h:946
static struct subre * parse(struct vars *, int, int, struct state *, struct state *)
Definition: regcomp.c:649
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 2289 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().

2299 {
2300  Expr *clause;
2301 
2302  /*
2303  * Build the new clause. Copy to ensure it shares no substructure with
2304  * original (this is necessary in case there are subselects in there...)
2305  */
2306  clause = make_opclause(opno,
2307  BOOLOID, /* opresulttype */
2308  false, /* opretset */
2309  copyObject(item1),
2310  copyObject(item2),
2311  InvalidOid,
2312  collation);
2313 
2314  /* If both constant, try to reduce to a boolean constant. */
2315  if (both_const)
2316  {
2317  clause = (Expr *) eval_const_expressions(root, (Node *) clause);
2318 
2319  /* If we produced const TRUE, just drop the clause */
2320  if (clause && IsA(clause, Const))
2321  {
2322  Const *cclause = (Const *) clause;
2323 
2324  Assert(cclause->consttype == BOOLOID);
2325  if (!cclause->constisnull && DatumGetBool(cclause->constvalue))
2326  return;
2327  }
2328  }
2329 
2330  /*
2331  * Push the new clause into all the appropriate restrictinfo lists.
2332  */
2333  distribute_qual_to_rels(root, (Node *) clause,
2334  true, below_outer_join, JOIN_INNER,
2335  security_level,
2336  qualscope, NULL, NULL, nullable_relids,
2337  NULL);
2338 }
Datum constvalue
Definition: primnodes.h:196
#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:1621
Definition: nodes.h:509
Node * eval_const_expressions(PlannerInfo *root, Node *node)
Definition: clauses.c:2400
Expr * make_opclause(Oid opno, Oid opresulttype, bool opretset, Expr *leftop, Expr *rightop, Oid opcollid, Oid inputcollid)
Definition: clauses.c:172
Oid consttype
Definition: primnodes.h:192
#define DatumGetBool(X)
Definition: postgres.h:399
#define InvalidOid
Definition: postgres_ext.h:36
#define NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:675
#define BOOLOID
Definition: pg_type.h:288
#define copyObject(obj)
Definition: nodes.h:621
bool constisnull
Definition: primnodes.h:197
bool query_is_distinct_for ( Query query,
List colnos,
List opids 
)

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

693 {
694  ListCell *l;
695  Oid opid;
696 
697  Assert(list_length(colnos) == list_length(opids));
698 
699  /*
700  * A set-returning function in the query's targetlist can result in
701  * returning duplicate rows, if the SRF is evaluated after the
702  * de-duplication step; so we play it safe and say "no" if there are any
703  * SRFs. (We could be certain that it's okay if SRFs appear only in the
704  * specified columns, since those must be evaluated before de-duplication;
705  * but it doesn't presently seem worth the complication to check that.)
706  */
707  if (query->hasTargetSRFs)
708  return false;
709 
710  /*
711  * DISTINCT (including DISTINCT ON) guarantees uniqueness if all the
712  * columns in the DISTINCT clause appear in colnos and operator semantics
713  * match.
714  */
715  if (query->distinctClause)
716  {
717  foreach(l, query->distinctClause)
718  {
719  SortGroupClause *sgc = (SortGroupClause *) lfirst(l);
721  query->targetList);
722 
723  opid = distinct_col_search(tle->resno, colnos, opids);
724  if (!OidIsValid(opid) ||
725  !equality_ops_are_compatible(opid, sgc->eqop))
726  break; /* exit early if no match */
727  }
728  if (l == NULL) /* had matches for all? */
729  return true;
730  }
731 
732  /*
733  * Similarly, GROUP BY without GROUPING SETS guarantees uniqueness if all
734  * the grouped columns appear in colnos and operator semantics match.
735  */
736  if (query->groupClause && !query->groupingSets)
737  {
738  foreach(l, query->groupClause)
739  {
740  SortGroupClause *sgc = (SortGroupClause *) lfirst(l);
742  query->targetList);
743 
744  opid = distinct_col_search(tle->resno, colnos, opids);
745  if (!OidIsValid(opid) ||
746  !equality_ops_are_compatible(opid, sgc->eqop))
747  break; /* exit early if no match */
748  }
749  if (l == NULL) /* had matches for all? */
750  return true;
751  }
752  else if (query->groupingSets)
753  {
754  /*
755  * If we have grouping sets with expressions, we probably don't have
756  * uniqueness and analysis would be hard. Punt.
757  */
758  if (query->groupClause)
759  return false;
760 
761  /*
762  * If we have no groupClause (therefore no grouping expressions), we
763  * might have one or many empty grouping sets. If there's just one,
764  * then we're returning only one row and are certainly unique. But
765  * otherwise, we know we're certainly not unique.
766  */
767  if (list_length(query->groupingSets) == 1 &&
768  ((GroupingSet *) linitial(query->groupingSets))->kind == GROUPING_SET_EMPTY)
769  return true;
770  else
771  return false;
772  }
773  else
774  {
775  /*
776  * If we have no GROUP BY, but do have aggregates or HAVING, then the
777  * result is at most one row so it's surely unique, for any operators.
778  */
779  if (query->hasAggs || query->havingQual)
780  return true;
781  }
782 
783  /*
784  * UNION, INTERSECT, EXCEPT guarantee uniqueness of the whole output row,
785  * except with ALL.
786  */
787  if (query->setOperations)
788  {
790 
791  Assert(topop->op != SETOP_NONE);
792 
793  if (!topop->all)
794  {
795  ListCell *lg;
796 
797  /* We're good if all the nonjunk output columns are in colnos */
798  lg = list_head(topop->groupClauses);
799  foreach(l, query->targetList)
800  {
801  TargetEntry *tle = (TargetEntry *) lfirst(l);
802  SortGroupClause *sgc;
803 
804  if (tle->resjunk)
805  continue; /* ignore resjunk columns */
806 
807  /* non-resjunk columns should have grouping clauses */
808  Assert(lg != NULL);
809  sgc = (SortGroupClause *) lfirst(lg);
810  lg = lnext(lg);
811 
812  opid = distinct_col_search(tle->resno, colnos, opids);
813  if (!OidIsValid(opid) ||
814  !equality_ops_are_compatible(opid, sgc->eqop))
815  break; /* exit early if no match */
816  }
817  if (l == NULL) /* had matches for all? */
818  return true;
819  }
820  }
821 
822  /*
823  * XXX Are there any other cases in which we can easily see the result
824  * must be distinct?
825  *
826  * If you do add more smarts to this function, be sure to update
827  * query_supports_distinctness() to match.
828  */
829 
830  return false;
831 }
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:841
bool hasAggs
Definition: parsenodes.h:123
List * groupingSets
Definition: parsenodes.h:148
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:538
List * targetList
Definition: parsenodes.h:138
bool resjunk
Definition: primnodes.h:1374
#define linitial(l)
Definition: pg_list.h:111
List * distinctClause
Definition: parsenodes.h:154
AttrNumber resno
Definition: primnodes.h:1368
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:125
#define NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:675
#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:1541
Node * setOperations
Definition: parsenodes.h:163
List * groupClause
Definition: parsenodes.h:146
Node * havingQual
Definition: parsenodes.h:150
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(), IS_SIMPLE_REL, 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, 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 (IS_SIMPLE_REL(brel))
246  total_pages += (double) brel->pages;
247  }
248  root->total_table_pages = total_pages;
249 
250  /*
251  * Ready to do the primary planning.
252  */
253  final_rel = make_one_rel(root, joinlist);
254 
255  /* Check that we got at least one usable path */
256  if (!final_rel || !final_rel->cheapest_total_path ||
257  final_rel->cheapest_total_path->param_info != NULL)
258  elog(ERROR, "failed to construct the join relation");
259 
260  return final_rel;
261 }
#define NIL
Definition: pg_list.h:69
int join_cur_level
Definition: relation.h:225
RelOptInfo * make_one_rel(PlannerInfo *root, List *joinlist)
Definition: allpaths.c:145
Query * parse
Definition: relation.h:154
void add_path(RelOptInfo *parent_rel, Path *new_path)
Definition: pathnode.c:412
void add_base_rels_to_query(PlannerInfo *root, Node *jtnode)
Definition: initsplan.c:104
List * join_info_list
Definition: relation.h:249
FromExpr * jointree
Definition: parsenodes.h:136
void extract_restriction_or_clauses(PlannerInfo *root)
Definition: orclauses.c:73
List * deconstruct_jointree(PlannerInfo *root)
Definition: initsplan.c:692
ParamPathInfo * param_info
Definition: relation.h:955
Definition: nodes.h:509
List * join_rel_list
Definition: relation.h:214
List * fromlist
Definition: primnodes.h:1470
List * fkey_list
Definition: relation.h:259
void add_placeholders_to_base_rels(PlannerInfo *root)
Definition: placeholder.c:379
Node * quals
Definition: primnodes.h:1471
#define IS_SIMPLE_REL(rel)
Definition: relation.h:504
bool is_parallel_safe(PlannerInfo *root, Node *node)
Definition: clauses.c:1073
#define ERROR
Definition: elog.h:43
bool parallelModeOK
Definition: relation.h:128
struct Path * cheapest_total_path
Definition: relation.h:542
PlannerGlobal * glob
Definition: relation.h:156
List * left_join_clauses
Definition: relation.h:238
List * full_join_clauses
Definition: relation.h:246
List * canon_pathkeys
Definition: relation.h:236
Index relid
Definition: relation.h:552
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:365
void reconsider_outer_join_clauses(PlannerInfo *root)
Definition: equivclass.c:1533
BlockNumber pages
Definition: relation.h:563
#define NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:675
RelOptInfo * build_empty_join_rel(PlannerInfo *root)
Definition: relnode.c:885
List ** join_rel_level
Definition: relation.h:224
void setup_simple_rel_arrays(PlannerInfo *root)
Definition: relnode.c:62
List * remove_useless_joins(PlannerInfo *root, List *joinlist)
Definition: analyzejoins.c:60
struct HTAB * join_rel_hash
Definition: relation.h:215
void build_base_rel_tlists(PlannerInfo *root, List *final_tlist)
Definition: initsplan.c:150
bool consider_parallel
Definition: relation.h:532
void match_foreign_keys_to_quals(PlannerInfo *root)
Definition: initsplan.c:2412
List * placeholder_list
Definition: relation.h:257
ResultPath * create_result_path(PlannerInfo *root, RelOptInfo *rel, PathTarget *target, List *resconstantqual)
Definition: pathnode.c:1350
List * initial_rels
Definition: relation.h:268
List * right_join_clauses
Definition: relation.h:242
#define elog
Definition: elog.h:219
Definition: pg_list.h:45
struct PathTarget * reltarget
Definition: relation.h:535
void create_lateral_join_info(PlannerInfo *root)
Definition: initsplan.c:417
Definition: relation.h:946
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:649
bool query_supports_distinctness ( Query query)

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

656 {
657  /* we don't cope with SRFs, see comment below */
658  if (query->hasTargetSRFs)
659  return false;
660 
661  /* check for features we can prove distinctness with */
662  if (query->distinctClause != NIL ||
663  query->groupClause != NIL ||
664  query->groupingSets != NIL ||
665  query->hasAggs ||
666  query->havingQual ||
667  query->setOperations)
668  return true;
669 
670  return false;
671 }
#define NIL
Definition: pg_list.h:69
bool hasAggs
Definition: parsenodes.h:123
List * groupingSets
Definition: parsenodes.h:148
List * distinctClause
Definition: parsenodes.h:154
bool hasTargetSRFs
Definition: parsenodes.h:125
Node * setOperations
Definition: parsenodes.h:163
List * groupClause
Definition: parsenodes.h:146
Node * havingQual
Definition: parsenodes.h:150
void record_plan_function_dependency ( PlannerInfo root,
Oid  funcid 
)

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

2485 {
2486  /*
2487  * For performance reasons, we don't bother to track built-in functions;
2488  * we just assume they'll never change (or at least not in ways that'd
2489  * invalidate plans using them). For this purpose we can consider a
2490  * built-in function to be one with OID less than FirstBootstrapObjectId.
2491  * Note that the OID generator guarantees never to generate such an OID
2492  * after startup, even at OID wraparound.
2493  */
2494  if (funcid >= (Oid) FirstBootstrapObjectId)
2495  {
2496  PlanInvalItem *inval_item = makeNode(PlanInvalItem);
2497 
2498  /*
2499  * It would work to use any syscache on pg_proc, but the easiest is
2500  * PROCOID since we already have the function's OID at hand. Note
2501  * that plancache.c knows we use PROCOID.
2502  */
2503  inval_item->cacheId = PROCOID;
2504  inval_item->hashValue = GetSysCacheHashValue1(PROCOID,
2505  ObjectIdGetDatum(funcid));
2506 
2507  root->glob->invalItems = lappend(root->glob->invalItems, inval_item);
2508  }
2509 }
#define GetSysCacheHashValue1(cacheId, key1)
Definition: syscache.h:188
unsigned int Oid
Definition: postgres_ext.h:31
#define ObjectIdGetDatum(X)
Definition: postgres.h:513
PlannerGlobal * glob
Definition: relation.h:156
#define FirstBootstrapObjectId
Definition: transam.h:93
List * lappend(List *list, void *datum)
Definition: list.c:128
List * invalItems
Definition: relation.h:114
uint32 hashValue
Definition: plannodes.h:1022
#define makeNode(_type_)
Definition: nodes.h:557
List* remove_useless_joins ( PlannerInfo root,
List joinlist 
)

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

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

Definition at line 209 of file setrefs.c.

References add_rtes_to_flat_rtable(), PlannerGlobal::finalrowmarks, PlannerGlobal::finalrtable, PlannerInfo::glob, lappend(), lfirst_node, 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:255
Index prti
Definition: plannodes.h:999
static Plan * set_plan_refs(PlannerInfo *root, Plan *plan, int rtoffset)
Definition: setrefs.c:434
#define lfirst_node(type, lc)
Definition: pg_list.h:109
PlannerGlobal * glob
Definition: relation.h:156
List * lappend(List *list, void *datum)
Definition: list.c:128
Index rti
Definition: plannodes.h:998
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:849
List * finalrowmarks
Definition: relation.h:106

Variable Documentation

double cursor_tuple_fraction

Definition at line 62 of file planner.c.

Referenced by standard_planner().

int force_parallel_mode

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