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)
 
void reduce_unique_semijoins (PlannerInfo *root)
 
bool query_supports_distinctness (Query *query)
 
bool query_is_distinct_for (Query *query, List *colnos, List *opids)
 
bool innerrel_is_unique (PlannerInfo *root, Relids outerrelids, RelOptInfo *innerrel, JoinType jointype, List *restrictlist, bool force_cache)
 
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:1471
Node * larg
Definition: primnodes.h:1451
#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:1452
#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:2066
#define IsA(nodeptr, _type_)
Definition: nodes.h:560
Relids * attr_needed
Definition: relation.h:558
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:525
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:884
#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:622
struct PathTarget * reltarget
Definition: relation.h:536
Bitmapset * bms_add_members(Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:755
AttrNumber min_attr
Definition: relation.h:556
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:155
#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:622
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:2064
RelOptKind reloptkind
Definition: relation.h:522
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:179
Relids lateral_relids
Definition: relation.h:550
bool hasLateralRTEs
Definition: relation.h:300
PlaceHolderInfo * find_placeholder_info(PlannerInfo *root, PlaceHolderVar *phv, bool create_new_ph)
Definition: placeholder.c:69
int simple_rel_array_size
Definition: relation.h:180
Index relid
Definition: relation.h:553
RangeTblEntry ** simple_rte_array
Definition: relation.h:188
Relids lateral_referencers
Definition: relation.h:561
bool bms_is_empty(const Bitmapset *a)
Definition: bitmapset.c:663
Index varno
Definition: primnodes.h:166
Relids direct_lateral_relids
Definition: relation.h:549
List * append_rel_list
Definition: relation.h:252
Relids ph_lateral
Definition: relation.h:2065
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:560
Bitmapset * bms_add_member(Bitmapset *a, int x)
Definition: bitmapset.c:698
List * placeholder_list
Definition: relation.h:258
Index child_relid
Definition: relation.h:1976
RelOptInfo * find_base_rel(PlannerInfo *root, int relid)
Definition: relnode.c:243
Index parent_relid
Definition: relation.h:1975
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 303 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().

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

2538 {
2539  PlannerGlobal glob;
2540  PlannerInfo root;
2541 
2542  /* Make up dummy planner state so we can use this module's machinery */
2543  MemSet(&glob, 0, sizeof(glob));
2544  glob.type = T_PlannerGlobal;
2545  glob.relationOids = NIL;
2546  glob.invalItems = NIL;
2547  /* Hack: we use glob.dependsOnRole to collect hasRowSecurity flags */
2548  glob.dependsOnRole = false;
2549 
2550  MemSet(&root, 0, sizeof(root));
2551  root.type = T_PlannerInfo;
2552  root.glob = &glob;
2553 
2554  (void) extract_query_dependencies_walker(query, &root);
2555 
2556  *relationOids = glob.relationOids;
2557  *invalItems = glob.invalItems;
2558  *hasRowSecurity = glob.dependsOnRole;
2559 }
#define NIL
Definition: pg_list.h:69
#define MemSet(start, val, len)
Definition: c.h:857
bool dependsOnRole
Definition: relation.h:127
PlannerGlobal * glob
Definition: relation.h:157
List * invalItems
Definition: relation.h:115
NodeTag type
Definition: relation.h:153
static bool extract_query_dependencies_walker(Node *node, PlannerInfo *context)
Definition: setrefs.c:2562
NodeTag type
Definition: relation.h:94
List * relationOids
Definition: relation.h:113
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:522
struct RelOptInfo ** simple_rel_array
Definition: relation.h:179
bool hasLateralRTEs
Definition: relation.h:300
int simple_rel_array_size
Definition: relation.h:180
Index relid
Definition: relation.h:553
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,
Relids  outerrelids,
RelOptInfo innerrel,
JoinType  jointype,
List restrictlist,
bool  force_cache 
)

Definition at line 962 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(), and RelOptInfo::unique_for_rels.

Referenced by add_paths_to_joinrel(), and reduce_unique_semijoins().

968 {
969  MemoryContext old_context;
970  ListCell *lc;
971 
972  /* Certainly can't prove uniqueness when there are no joinclauses */
973  if (restrictlist == NIL)
974  return false;
975 
976  /*
977  * Make a quick check to eliminate cases in which we will surely be unable
978  * to prove uniqueness of the innerrel.
979  */
980  if (!rel_supports_distinctness(root, innerrel))
981  return false;
982 
983  /*
984  * Query the cache to see if we've managed to prove that innerrel is
985  * unique for any subset of this outerrel. We don't need an exact match,
986  * as extra outerrels can't make the innerrel any less unique (or more
987  * formally, the restrictlist for a join to a superset outerrel must be a
988  * superset of the conditions we successfully used before).
989  */
990  foreach(lc, innerrel->unique_for_rels)
991  {
992  Relids unique_for_rels = (Relids) lfirst(lc);
993 
994  if (bms_is_subset(unique_for_rels, outerrelids))
995  return true; /* Success! */
996  }
997 
998  /*
999  * Conversely, we may have already determined that this outerrel, or some
1000  * superset thereof, cannot prove this innerrel to be unique.
1001  */
1002  foreach(lc, innerrel->non_unique_for_rels)
1003  {
1004  Relids unique_for_rels = (Relids) lfirst(lc);
1005 
1006  if (bms_is_subset(outerrelids, unique_for_rels))
1007  return false;
1008  }
1009 
1010  /* No cached information, so try to make the proof. */
1011  if (is_innerrel_unique_for(root, outerrelids, innerrel,
1012  jointype, restrictlist))
1013  {
1014  /*
1015  * Cache the positive result for future probes, being sure to keep it
1016  * in the planner_cxt even if we are working in GEQO.
1017  *
1018  * Note: one might consider trying to isolate the minimal subset of
1019  * the outerrels that proved the innerrel unique. But it's not worth
1020  * the trouble, because the planner builds up joinrels incrementally
1021  * and so we'll see the minimally sufficient outerrels before any
1022  * supersets of them anyway.
1023  */
1024  old_context = MemoryContextSwitchTo(root->planner_cxt);
1025  innerrel->unique_for_rels = lappend(innerrel->unique_for_rels,
1026  bms_copy(outerrelids));
1027  MemoryContextSwitchTo(old_context);
1028 
1029  return true; /* Success! */
1030  }
1031  else
1032  {
1033  /*
1034  * None of the join conditions for outerrel proved innerrel unique, so
1035  * we can safely reject this outerrel or any subset of it in future
1036  * checks.
1037  *
1038  * However, in normal planning mode, caching this knowledge is totally
1039  * pointless; it won't be queried again, because we build up joinrels
1040  * from smaller to larger. It is useful in GEQO mode, where the
1041  * knowledge can be carried across successive planning attempts; and
1042  * it's likely to be useful when using join-search plugins, too. Hence
1043  * cache when join_search_private is non-NULL. (Yeah, that's a hack,
1044  * but it seems reasonable.)
1045  *
1046  * Also, allow callers to override that heuristic and force caching;
1047  * that's useful for reduce_unique_semijoins, which calls here before
1048  * the normal join search starts.
1049  */
1050  if (force_cache || root->join_search_private)
1051  {
1052  old_context = MemoryContextSwitchTo(root->planner_cxt);
1053  innerrel->non_unique_for_rels =
1054  lappend(innerrel->non_unique_for_rels,
1055  bms_copy(outerrelids));
1056  MemoryContextSwitchTo(old_context);
1057  }
1058 
1059  return false;
1060  }
1061 }
#define NIL
Definition: pg_list.h:69
List * unique_for_rels
Definition: relation.h:580
Bitmapset * bms_copy(const Bitmapset *a)
Definition: bitmapset.c:111
void * join_search_private
Definition: relation.h:316
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
bool bms_is_subset(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:308
List * non_unique_for_rels
Definition: relation.h:582
Bitmapset * Relids
Definition: relation.h:28
List * lappend(List *list, void *datum)
Definition: list.c:128
#define lfirst(lc)
Definition: pg_list.h:106
static bool is_innerrel_unique_for(PlannerInfo *root, Relids outerrelids, RelOptInfo *innerrel, JoinType jointype, List *restrictlist)
MemoryContext planner_cxt
Definition: relation.h:287
static bool rel_supports_distinctness(PlannerInfo *root, RelOptInfo *rel)
Definition: analyzejoins.c:592
bool is_projection_capable_path ( Path path)

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

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

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

6582 {
6583  /* Most plan types can project, so just list the ones that can't */
6584  switch (nodeTag(plan))
6585  {
6586  case T_Hash:
6587  case T_Material:
6588  case T_Sort:
6589  case T_Unique:
6590  case T_SetOp:
6591  case T_LockRows:
6592  case T_Limit:
6593  case T_ModifyTable:
6594  case T_Append:
6595  case T_MergeAppend:
6596  case T_RecursiveUnion:
6597  return false;
6598  case T_ProjectSet:
6599 
6600  /*
6601  * Although ProjectSet certainly projects, say "no" because we
6602  * don't want the planner to randomly replace its tlist with
6603  * something else; the SRFs have to stay at top level. This might
6604  * get relaxed later.
6605  */
6606  return false;
6607  default:
6608  break;
6609  }
6610  return true;
6611 }
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 6000 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().

6005 {
6006  Agg *node = makeNode(Agg);
6007  Plan *plan = &node->plan;
6008  long numGroups;
6009 
6010  /* Reduce to long, but 'ware overflow! */
6011  numGroups = (long) Min(dNumGroups, (double) LONG_MAX);
6012 
6013  node->aggstrategy = aggstrategy;
6014  node->aggsplit = aggsplit;
6015  node->numCols = numGroupCols;
6016  node->grpColIdx = grpColIdx;
6017  node->grpOperators = grpOperators;
6018  node->numGroups = numGroups;
6019  node->aggParams = NULL; /* SS_finalize_plan() will fill this */
6020  node->groupingSets = groupingSets;
6021  node->chain = chain;
6022 
6023  plan->qual = qual;
6024  plan->targetlist = tlist;
6025  plan->lefttree = lefttree;
6026  plan->righttree = NULL;
6027 
6028  return node;
6029 }
int numCols
Definition: plannodes.h:785
List * qual
Definition: plannodes.h:145
AttrNumber * grpColIdx
Definition: plannodes.h:786
#define Min(x, y)
Definition: c.h:806
struct Plan * righttree
Definition: plannodes.h:147
AggStrategy aggstrategy
Definition: plannodes.h:783
Bitmapset * aggParams
Definition: plannodes.h:789
Plan plan
Definition: plannodes.h:782
List * groupingSets
Definition: plannodes.h:791
#define makeNode(_type_)
Definition: nodes.h:557
#define NULL
Definition: c.h:229
AggSplit aggsplit
Definition: plannodes.h:784
long numGroups
Definition: plannodes.h:788
struct Plan * lefttree
Definition: plannodes.h:146
List * targetlist
Definition: plannodes.h:144
Oid * grpOperators
Definition: plannodes.h:787
List * chain
Definition: plannodes.h:792
Definition: plannodes.h:780
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 5238 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().

5246 {
5247  ForeignScan *node = makeNode(ForeignScan);
5248  Plan *plan = &node->scan.plan;
5249 
5250  /* cost will be filled in by create_foreignscan_plan */
5251  plan->targetlist = qptlist;
5252  plan->qual = qpqual;
5253  plan->lefttree = outer_plan;
5254  plan->righttree = NULL;
5255  node->scan.scanrelid = scanrelid;
5256  node->operation = CMD_SELECT;
5257  /* fs_server will be filled in by create_foreignscan_plan */
5258  node->fs_server = InvalidOid;
5259  node->fdw_exprs = fdw_exprs;
5260  node->fdw_private = fdw_private;
5261  node->fdw_scan_tlist = fdw_scan_tlist;
5262  node->fdw_recheck_quals = fdw_recheck_quals;
5263  /* fs_relids will be filled in by create_foreignscan_plan */
5264  node->fs_relids = NULL;
5265  /* fsSystemCol will be filled in by create_foreignscan_plan */
5266  node->fsSystemCol = false;
5267 
5268  return node;
5269 }
List * qual
Definition: plannodes.h:145
Plan plan
Definition: plannodes.h:328
Index scanrelid
Definition: plannodes.h:329
Oid fs_server
Definition: plannodes.h:599
List * fdw_exprs
Definition: plannodes.h:600
List * fdw_private
Definition: plannodes.h:601
List * fdw_scan_tlist
Definition: plannodes.h:602
CmdType operation
Definition: plannodes.h:598
struct Plan * righttree
Definition: plannodes.h:147
List * fdw_recheck_quals
Definition: plannodes.h:603
#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:146
List * targetlist
Definition: plannodes.h:144
bool fsSystemCol
Definition: plannodes.h:605
Bitmapset * fs_relids
Definition: plannodes.h:604
Limit* make_limit ( Plan lefttree,
Node limitOffset,
Node limitCount 
)

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

6338 {
6339  Limit *node = makeNode(Limit);
6340  Plan *plan = &node->plan;
6341 
6342  plan->targetlist = lefttree->targetlist;
6343  plan->qual = NIL;
6344  plan->lefttree = lefttree;
6345  plan->righttree = NULL;
6346 
6347  node->limitOffset = limitOffset;
6348  node->limitCount = limitCount;
6349 
6350  return node;
6351 }
#define NIL
Definition: pg_list.h:69
List * qual
Definition: plannodes.h:145
Plan plan
Definition: plannodes.h:914
Node * limitOffset
Definition: plannodes.h:915
struct Plan * righttree
Definition: plannodes.h:147
Node * limitCount
Definition: plannodes.h:916
#define makeNode(_type_)
Definition: nodes.h:557
#define NULL
Definition: c.h:229
struct Plan * lefttree
Definition: plannodes.h:146
List * targetlist
Definition: plannodes.h:144
Sort* make_sort_from_sortclauses ( List sortcls,
Plan lefttree 
)

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

5855 {
5856  List *sub_tlist = lefttree->targetlist;
5857  ListCell *l;
5858  int numsortkeys;
5859  AttrNumber *sortColIdx;
5860  Oid *sortOperators;
5861  Oid *collations;
5862  bool *nullsFirst;
5863 
5864  /* Convert list-ish representation to arrays wanted by executor */
5865  numsortkeys = list_length(sortcls);
5866  sortColIdx = (AttrNumber *) palloc(numsortkeys * sizeof(AttrNumber));
5867  sortOperators = (Oid *) palloc(numsortkeys * sizeof(Oid));
5868  collations = (Oid *) palloc(numsortkeys * sizeof(Oid));
5869  nullsFirst = (bool *) palloc(numsortkeys * sizeof(bool));
5870 
5871  numsortkeys = 0;
5872  foreach(l, sortcls)
5873  {
5874  SortGroupClause *sortcl = (SortGroupClause *) lfirst(l);
5875  TargetEntry *tle = get_sortgroupclause_tle(sortcl, sub_tlist);
5876 
5877  sortColIdx[numsortkeys] = tle->resno;
5878  sortOperators[numsortkeys] = sortcl->sortop;
5879  collations[numsortkeys] = exprCollation((Node *) tle->expr);
5880  nullsFirst[numsortkeys] = sortcl->nulls_first;
5881  numsortkeys++;
5882  }
5883 
5884  return make_sort(lefttree, numsortkeys,
5885  sortColIdx, sortOperators,
5886  collations, nullsFirst);
5887 }
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:1369
static Sort * make_sort(Plan *lefttree, int numCols, AttrNumber *sortColIdx, Oid *sortOperators, Oid *collations, bool *nullsFirst)
Definition: createplan.c:5482
#define lfirst(lc)
Definition: pg_list.h:106
Expr * expr
Definition: primnodes.h:1368
static int list_length(const List *l)
Definition: pg_list.h:89
Oid exprCollation(const Node *expr)
Definition: nodeFuncs.c:720
List * targetlist
Definition: plannodes.h:144
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:522
unsigned int Oid
Definition: postgres_ext.h:31
Definition: primnodes.h:163
List * fkey_list
Definition: relation.h:260
#define OidIsValid(objectId)
Definition: c.h:538
struct RelOptInfo ** simple_rel_array
Definition: relation.h:179
Node * get_leftop(const Expr *clause)
Definition: clauses.c:199
Oid conpfeqop[INDEX_MAX_KEYS]
Definition: relation.h:699
bool outerjoin_delayed
Definition: relation.h:1751
List * joininfo
Definition: relation.h:589
int simple_rel_array_size
Definition: relation.h:180
List * lappend(List *list, void *datum)
Definition: list.c:128
Expr * clause
Definition: relation.h:1747
struct EquivalenceClass * eclass[INDEX_MAX_KEYS]
Definition: relation.h:706
AttrNumber conkey[INDEX_MAX_KEYS]
Definition: relation.h:697
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:496
List * args
Definition: primnodes.h:502
Definition: pg_list.h:45
AttrNumber confkey[INDEX_MAX_KEYS]
Definition: relation.h:698
int16 AttrNumber
Definition: attnum.h:21
List * rinfos[INDEX_MAX_KEYS]
Definition: relation.h:708
Plan* materialize_finished_plan ( Plan subplan)

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

5967 {
5968  Plan *matplan;
5969  Path matpath; /* dummy for result of cost_material */
5970 
5971  matplan = (Plan *) make_material(subplan);
5972 
5973  /*
5974  * XXX horrid kluge: if there are any initPlans attached to the subplan,
5975  * move them up to the Material node, which is now effectively the top
5976  * plan node in its query level. This prevents failure in
5977  * SS_finalize_plan(), which see for comments. We don't bother adjusting
5978  * the subplan's cost estimate for this.
5979  */
5980  matplan->initPlan = subplan->initPlan;
5981  subplan->initPlan = NIL;
5982 
5983  /* Set cost data */
5984  cost_material(&matpath,
5985  subplan->startup_cost,
5986  subplan->total_cost,
5987  subplan->plan_rows,
5988  subplan->plan_width);
5989  matplan->startup_cost = matpath.startup_cost;
5990  matplan->total_cost = matpath.total_cost;
5991  matplan->plan_rows = subplan->plan_rows;
5992  matplan->plan_width = subplan->plan_width;
5993  matplan->parallel_aware = false;
5994  matplan->parallel_safe = subplan->parallel_safe;
5995 
5996  return matplan;
5997 }
#define NIL
Definition: pg_list.h:69
double plan_rows
Definition: plannodes.h:131
static Material * make_material(Plan *lefttree)
Definition: createplan.c:5944
Cost startup_cost
Definition: relation.h:965
Cost startup_cost
Definition: plannodes.h:125
bool parallel_aware
Definition: plannodes.h:137
Cost total_cost
Definition: relation.h:966
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:132
List * initPlan
Definition: plannodes.h:148
Cost total_cost
Definition: plannodes.h:126
bool parallel_safe
Definition: plannodes.h:138
Definition: relation.h:948
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:2885
#define IsA(nodeptr, _type_)
Definition: nodes.h:560
Query * parse
Definition: relation.h:155
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:2085
List * groupingSets
Definition: parsenodes.h:148
Definition: nodes.h:509
List * minmax_aggs
Definition: relation.h:285
List * fromlist
Definition: primnodes.h:1471
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:325
#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:2081
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:720
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:936
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:948
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:622
bool constisnull
Definition: primnodes.h:197
bool query_is_distinct_for ( Query query,
List colnos,
List opids 
)

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

775 {
776  ListCell *l;
777  Oid opid;
778 
779  Assert(list_length(colnos) == list_length(opids));
780 
781  /*
782  * A set-returning function in the query's targetlist can result in
783  * returning duplicate rows, if the SRF is evaluated after the
784  * de-duplication step; so we play it safe and say "no" if there are any
785  * SRFs. (We could be certain that it's okay if SRFs appear only in the
786  * specified columns, since those must be evaluated before de-duplication;
787  * but it doesn't presently seem worth the complication to check that.)
788  */
789  if (query->hasTargetSRFs)
790  return false;
791 
792  /*
793  * DISTINCT (including DISTINCT ON) guarantees uniqueness if all the
794  * columns in the DISTINCT clause appear in colnos and operator semantics
795  * match.
796  */
797  if (query->distinctClause)
798  {
799  foreach(l, query->distinctClause)
800  {
801  SortGroupClause *sgc = (SortGroupClause *) lfirst(l);
803  query->targetList);
804 
805  opid = distinct_col_search(tle->resno, colnos, opids);
806  if (!OidIsValid(opid) ||
807  !equality_ops_are_compatible(opid, sgc->eqop))
808  break; /* exit early if no match */
809  }
810  if (l == NULL) /* had matches for all? */
811  return true;
812  }
813 
814  /*
815  * Similarly, GROUP BY without GROUPING SETS guarantees uniqueness if all
816  * the grouped columns appear in colnos and operator semantics match.
817  */
818  if (query->groupClause && !query->groupingSets)
819  {
820  foreach(l, query->groupClause)
821  {
822  SortGroupClause *sgc = (SortGroupClause *) lfirst(l);
824  query->targetList);
825 
826  opid = distinct_col_search(tle->resno, colnos, opids);
827  if (!OidIsValid(opid) ||
828  !equality_ops_are_compatible(opid, sgc->eqop))
829  break; /* exit early if no match */
830  }
831  if (l == NULL) /* had matches for all? */
832  return true;
833  }
834  else if (query->groupingSets)
835  {
836  /*
837  * If we have grouping sets with expressions, we probably don't have
838  * uniqueness and analysis would be hard. Punt.
839  */
840  if (query->groupClause)
841  return false;
842 
843  /*
844  * If we have no groupClause (therefore no grouping expressions), we
845  * might have one or many empty grouping sets. If there's just one,
846  * then we're returning only one row and are certainly unique. But
847  * otherwise, we know we're certainly not unique.
848  */
849  if (list_length(query->groupingSets) == 1 &&
850  ((GroupingSet *) linitial(query->groupingSets))->kind == GROUPING_SET_EMPTY)
851  return true;
852  else
853  return false;
854  }
855  else
856  {
857  /*
858  * If we have no GROUP BY, but do have aggregates or HAVING, then the
859  * result is at most one row so it's surely unique, for any operators.
860  */
861  if (query->hasAggs || query->havingQual)
862  return true;
863  }
864 
865  /*
866  * UNION, INTERSECT, EXCEPT guarantee uniqueness of the whole output row,
867  * except with ALL.
868  */
869  if (query->setOperations)
870  {
872 
873  Assert(topop->op != SETOP_NONE);
874 
875  if (!topop->all)
876  {
877  ListCell *lg;
878 
879  /* We're good if all the nonjunk output columns are in colnos */
880  lg = list_head(topop->groupClauses);
881  foreach(l, query->targetList)
882  {
883  TargetEntry *tle = (TargetEntry *) lfirst(l);
884  SortGroupClause *sgc;
885 
886  if (tle->resjunk)
887  continue; /* ignore resjunk columns */
888 
889  /* non-resjunk columns should have grouping clauses */
890  Assert(lg != NULL);
891  sgc = (SortGroupClause *) lfirst(lg);
892  lg = lnext(lg);
893 
894  opid = distinct_col_search(tle->resno, colnos, opids);
895  if (!OidIsValid(opid) ||
896  !equality_ops_are_compatible(opid, sgc->eqop))
897  break; /* exit early if no match */
898  }
899  if (l == NULL) /* had matches for all? */
900  return true;
901  }
902  }
903 
904  /*
905  * XXX Are there any other cases in which we can easily see the result
906  * must be distinct?
907  *
908  * If you do add more smarts to this function, be sure to update
909  * query_supports_distinctness() to match.
910  */
911 
912  return false;
913 }
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:923
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:1375
#define linitial(l)
Definition: pg_list.h:111
List * distinctClause
Definition: parsenodes.h:154
AttrNumber resno
Definition: primnodes.h:1369
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:1560
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(), reduce_unique_semijoins(), 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  * Also, reduce any semijoins with unique inner rels to plain inner joins.
197  * Likewise, this can't be done until now for lack of needed info.
198  */
200 
201  /*
202  * Now distribute "placeholders" to base rels as needed. This has to be
203  * done after join removal because removal could change whether a
204  * placeholder is evaluable at a base rel.
205  */
207 
208  /*
209  * Construct the lateral reference sets now that we have finalized
210  * PlaceHolderVar eval levels.
211  */
213 
214  /*
215  * Match foreign keys to equivalence classes and join quals. This must be
216  * done after finalizing equivalence classes, and it's useful to wait till
217  * after join removal so that we can skip processing foreign keys
218  * involving removed relations.
219  */
221 
222  /*
223  * Look for join OR clauses that we can extract single-relation
224  * restriction OR clauses from.
225  */
227 
228  /*
229  * We should now have size estimates for every actual table involved in
230  * the query, and we also know which if any have been deleted from the
231  * query by join removal; so we can compute total_table_pages.
232  *
233  * Note that appendrels are not double-counted here, even though we don't
234  * bother to distinguish RelOptInfos for appendrel parents, because the
235  * parents will still have size zero.
236  *
237  * XXX if a table is self-joined, we will count it once per appearance,
238  * which perhaps is the wrong thing ... but that's not completely clear,
239  * and detecting self-joins here is difficult, so ignore it for now.
240  */
241  total_pages = 0;
242  for (rti = 1; rti < root->simple_rel_array_size; rti++)
243  {
244  RelOptInfo *brel = root->simple_rel_array[rti];
245 
246  if (brel == NULL)
247  continue;
248 
249  Assert(brel->relid == rti); /* sanity check on array */
250 
251  if (IS_SIMPLE_REL(brel))
252  total_pages += (double) brel->pages;
253  }
254  root->total_table_pages = total_pages;
255 
256  /*
257  * Ready to do the primary planning.
258  */
259  final_rel = make_one_rel(root, joinlist);
260 
261  /* Check that we got at least one usable path */
262  if (!final_rel || !final_rel->cheapest_total_path ||
263  final_rel->cheapest_total_path->param_info != NULL)
264  elog(ERROR, "failed to construct the join relation");
265 
266  return final_rel;
267 }
#define NIL
Definition: pg_list.h:69
int join_cur_level
Definition: relation.h:226
RelOptInfo * make_one_rel(PlannerInfo *root, List *joinlist)
Definition: allpaths.c:145
Query * parse
Definition: relation.h:155
void add_path(RelOptInfo *parent_rel, Path *new_path)
Definition: pathnode.c:412
void reduce_unique_semijoins(PlannerInfo *root)
Definition: analyzejoins.c:512
void add_base_rels_to_query(PlannerInfo *root, Node *jtnode)
Definition: initsplan.c:104
List * join_info_list
Definition: relation.h:250
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:957
Definition: nodes.h:509
List * join_rel_list
Definition: relation.h:215
List * fromlist
Definition: primnodes.h:1471
List * fkey_list
Definition: relation.h:260
void add_placeholders_to_base_rels(PlannerInfo *root)
Definition: placeholder.c:379
Node * quals
Definition: primnodes.h:1472
#define IS_SIMPLE_REL(rel)
Definition: relation.h:505
bool is_parallel_safe(PlannerInfo *root, Node *node)
Definition: clauses.c:1073
#define ERROR
Definition: elog.h:43
bool parallelModeOK
Definition: relation.h:129
struct Path * cheapest_total_path
Definition: relation.h:543
PlannerGlobal * glob
Definition: relation.h:157
List * left_join_clauses
Definition: relation.h:239
List * full_join_clauses
Definition: relation.h:247
List * canon_pathkeys
Definition: relation.h:237
Index relid
Definition: relation.h:553
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:564
#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:225
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:216
void build_base_rel_tlists(PlannerInfo *root, List *final_tlist)
Definition: initsplan.c:150
bool consider_parallel
Definition: relation.h:533
void match_foreign_keys_to_quals(PlannerInfo *root)
Definition: initsplan.c:2412
List * placeholder_list
Definition: relation.h:258
ResultPath * create_result_path(PlannerInfo *root, RelOptInfo *rel, PathTarget *target, List *resconstantqual)
Definition: pathnode.c:1349
List * initial_rels
Definition: relation.h:269
List * right_join_clauses
Definition: relation.h:243
#define elog
Definition: elog.h:219
Definition: pg_list.h:45
struct PathTarget * reltarget
Definition: relation.h:536
void create_lateral_join_info(PlannerInfo *root)
Definition: initsplan.c:417
Definition: relation.h:948
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 737 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().

738 {
739  /* we don't cope with SRFs, see comment below */
740  if (query->hasTargetSRFs)
741  return false;
742 
743  /* check for features we can prove distinctness with */
744  if (query->distinctClause != NIL ||
745  query->groupClause != NIL ||
746  query->groupingSets != NIL ||
747  query->hasAggs ||
748  query->havingQual ||
749  query->setOperations)
750  return true;
751 
752  return false;
753 }
#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 2496 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().

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

Definition at line 512 of file analyzejoins.c.

References bms_get_singleton_member(), bms_union(), SpecialJoinInfo::delay_upper_joins, find_base_rel(), generate_join_implied_equalities(), innerrel_is_unique(), PlannerInfo::join_info_list, JOIN_SEMI, RelOptInfo::joininfo, SpecialJoinInfo::jointype, lfirst, list_concat(), list_delete_ptr(), list_head(), lnext, SpecialJoinInfo::min_lefthand, SpecialJoinInfo::min_righthand, next, NULL, and rel_supports_distinctness().

Referenced by query_planner().

513 {
514  ListCell *lc;
515  ListCell *next;
516 
517  /*
518  * Scan the join_info_list to find semijoins. We can't use foreach
519  * because we may delete the current cell.
520  */
521  for (lc = list_head(root->join_info_list); lc != NULL; lc = next)
522  {
523  SpecialJoinInfo *sjinfo = (SpecialJoinInfo *) lfirst(lc);
524  int innerrelid;
525  RelOptInfo *innerrel;
526  Relids joinrelids;
527  List *restrictlist;
528 
529  next = lnext(lc);
530 
531  /*
532  * Must be a non-delaying semijoin to a single baserel, else we aren't
533  * going to be able to do anything with it. (It's probably not
534  * possible for delay_upper_joins to be set on a semijoin, but we
535  * might as well check.)
536  */
537  if (sjinfo->jointype != JOIN_SEMI ||
538  sjinfo->delay_upper_joins)
539  continue;
540 
541  if (!bms_get_singleton_member(sjinfo->min_righthand, &innerrelid))
542  continue;
543 
544  innerrel = find_base_rel(root, innerrelid);
545 
546  /*
547  * Before we trouble to run generate_join_implied_equalities, make a
548  * quick check to eliminate cases in which we will surely be unable to
549  * prove uniqueness of the innerrel.
550  */
551  if (!rel_supports_distinctness(root, innerrel))
552  continue;
553 
554  /* Compute the relid set for the join we are considering */
555  joinrelids = bms_union(sjinfo->min_lefthand, sjinfo->min_righthand);
556 
557  /*
558  * Since we're only considering a single-rel RHS, any join clauses it
559  * has must be clauses linking it to the semijoin's min_lefthand. We
560  * can also consider EC-derived join clauses.
561  */
562  restrictlist =
564  joinrelids,
565  sjinfo->min_lefthand,
566  innerrel),
567  innerrel->joininfo);
568 
569  /* Test whether the innerrel is unique for those clauses. */
570  if (!innerrel_is_unique(root, sjinfo->min_lefthand, innerrel,
571  JOIN_SEMI, restrictlist, true))
572  continue;
573 
574  /* OK, remove the SpecialJoinInfo from the list. */
575  root->join_info_list = list_delete_ptr(root->join_info_list, sjinfo);
576  }
577 }
static int32 next
Definition: blutils.c:210
List * join_info_list
Definition: relation.h:250
Relids min_righthand
Definition: relation.h:1918
bool bms_get_singleton_member(const Bitmapset *a, int *member)
Definition: bitmapset.c:569
List * list_concat(List *list1, List *list2)
Definition: list.c:321
List * list_delete_ptr(List *list, void *datum)
Definition: list.c:590
List * generate_join_implied_equalities(PlannerInfo *root, Relids join_relids, Relids outer_relids, RelOptInfo *inner_rel)
Definition: equivclass.c:1033
List * joininfo
Definition: relation.h:589
static ListCell * list_head(const List *l)
Definition: pg_list.h:77
#define lnext(lc)
Definition: pg_list.h:105
bool innerrel_is_unique(PlannerInfo *root, Relids outerrelids, RelOptInfo *innerrel, JoinType jointype, List *restrictlist, bool force_cache)
Definition: analyzejoins.c:962
bool delay_upper_joins
Definition: relation.h:1923
#define NULL
Definition: c.h:229
#define lfirst(lc)
Definition: pg_list.h:106
JoinType jointype
Definition: relation.h:1921
Bitmapset * bms_union(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:218
RelOptInfo * find_base_rel(PlannerInfo *root, int relid)
Definition: relnode.c:243
static bool rel_supports_distinctness(PlannerInfo *root, RelOptInfo *rel)
Definition: analyzejoins.c:592
Definition: pg_list.h:45
Relids min_lefthand
Definition: relation.h:1917
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:250
Relids min_righthand
Definition: relation.h:1918
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:1917
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:256
Index prti
Definition: plannodes.h:1005
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:157
List * lappend(List *list, void *datum)
Definition: list.c:128
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().