PostgreSQL Source Code  git master
planmain.h File Reference
#include "nodes/pathnodes.h"
#include "nodes/plannodes.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)
 

Functions

RelOptInfoquery_planner (PlannerInfo *root, query_pathkeys_callback qp_callback, void *qp_extra)
 
void preprocess_minmax_aggregates (PlannerInfo *root)
 
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)
 
Planchange_plan_targetlist (Plan *subplan, List *tlist, bool tlist_parallel_safe)
 
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, Oid *grpCollations, 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 add_other_rels_to_query (PlannerInfo *root)
 
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 joinrelids, 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 record_plan_type_dependency (PlannerInfo *root, Oid typid)
 
bool extract_query_dependencies_walker (Node *node, PlannerInfo *root)
 

Variables

double cursor_tuple_fraction
 
int from_collapse_limit
 
int join_collapse_limit
 

Macro Definition Documentation

◆ DEFAULT_CURSOR_TUPLE_FRACTION

#define DEFAULT_CURSOR_TUPLE_FRACTION   0.1

Definition at line 21 of file planmain.h.

Typedef Documentation

◆ query_pathkeys_callback

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

Definition at line 25 of file planmain.h.

Function Documentation

◆ add_base_rels_to_query()

void add_base_rels_to_query ( PlannerInfo root,
Node jtnode 
)

Definition at line 105 of file initsplan.c.

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

Referenced by add_base_rels_to_query(), and query_planner().

106 {
107  if (jtnode == NULL)
108  return;
109  if (IsA(jtnode, RangeTblRef))
110  {
111  int varno = ((RangeTblRef *) jtnode)->rtindex;
112 
113  (void) build_simple_rel(root, varno, NULL);
114  }
115  else if (IsA(jtnode, FromExpr))
116  {
117  FromExpr *f = (FromExpr *) jtnode;
118  ListCell *l;
119 
120  foreach(l, f->fromlist)
121  add_base_rels_to_query(root, lfirst(l));
122  }
123  else if (IsA(jtnode, JoinExpr))
124  {
125  JoinExpr *j = (JoinExpr *) jtnode;
126 
127  add_base_rels_to_query(root, j->larg);
128  add_base_rels_to_query(root, j->rarg);
129  }
130  else
131  elog(ERROR, "unrecognized node type: %d",
132  (int) nodeTag(jtnode));
133 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:576
void add_base_rels_to_query(PlannerInfo *root, Node *jtnode)
Definition: initsplan.c:105
List * fromlist
Definition: primnodes.h:1496
Node * larg
Definition: primnodes.h:1476
#define ERROR
Definition: elog.h:43
RelOptInfo * build_simple_rel(PlannerInfo *root, int relid, RelOptInfo *parent)
Definition: relnode.c:185
Node * rarg
Definition: primnodes.h:1477
#define lfirst(lc)
Definition: pg_list.h:190
#define nodeTag(nodeptr)
Definition: nodes.h:530
#define elog(elevel,...)
Definition: elog.h:228

◆ add_other_rels_to_query()

void add_other_rels_to_query ( PlannerInfo root)

Definition at line 143 of file initsplan.c.

References expand_inherited_rtentry(), RangeTblEntry::inh, RELOPT_BASEREL, RelOptInfo::reloptkind, PlannerInfo::simple_rel_array, PlannerInfo::simple_rel_array_size, and PlannerInfo::simple_rte_array.

Referenced by query_planner().

144 {
145  int rti;
146 
147  for (rti = 1; rti < root->simple_rel_array_size; rti++)
148  {
149  RelOptInfo *rel = root->simple_rel_array[rti];
150  RangeTblEntry *rte = root->simple_rte_array[rti];
151 
152  /* there may be empty slots corresponding to non-baserel RTEs */
153  if (rel == NULL)
154  continue;
155 
156  /* Ignore any "otherrels" that were already added. */
157  if (rel->reloptkind != RELOPT_BASEREL)
158  continue;
159 
160  /* If it's marked as inheritable, look for children. */
161  if (rte->inh)
162  expand_inherited_rtentry(root, rel, rte, rti);
163  }
164 }
RelOptKind reloptkind
Definition: pathnodes.h:638
struct RelOptInfo ** simple_rel_array
Definition: pathnodes.h:201
int simple_rel_array_size
Definition: pathnodes.h:202
RangeTblEntry ** simple_rte_array
Definition: pathnodes.h:209
void expand_inherited_rtentry(PlannerInfo *root, RelOptInfo *rel, RangeTblEntry *rte, Index rti)
Definition: inherit.c:79

◆ add_vars_to_targetlist()

void add_vars_to_targetlist ( PlannerInfo root,
List vars,
Relids  where_needed,
bool  create_new_ph 
)

Definition at line 229 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, PlaceHolderInfo::ph_needed, RelOptInfo::relids, RelOptInfo::reltarget, Var::varattno, and Var::varno.

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

231 {
232  ListCell *temp;
233 
234  Assert(!bms_is_empty(where_needed));
235 
236  foreach(temp, vars)
237  {
238  Node *node = (Node *) lfirst(temp);
239 
240  if (IsA(node, Var))
241  {
242  Var *var = (Var *) node;
243  RelOptInfo *rel = find_base_rel(root, var->varno);
244  int attno = var->varattno;
245 
246  if (bms_is_subset(where_needed, rel->relids))
247  continue;
248  Assert(attno >= rel->min_attr && attno <= rel->max_attr);
249  attno -= rel->min_attr;
250  if (rel->attr_needed[attno] == NULL)
251  {
252  /* Variable not yet requested, so add to rel's targetlist */
253  /* XXX is copyObject necessary here? */
254  rel->reltarget->exprs = lappend(rel->reltarget->exprs,
255  copyObject(var));
256  /* reltarget cost and width will be computed later */
257  }
258  rel->attr_needed[attno] = bms_add_members(rel->attr_needed[attno],
259  where_needed);
260  }
261  else if (IsA(node, PlaceHolderVar))
262  {
263  PlaceHolderVar *phv = (PlaceHolderVar *) node;
264  PlaceHolderInfo *phinfo = find_placeholder_info(root, phv,
265  create_new_ph);
266 
267  phinfo->ph_needed = bms_add_members(phinfo->ph_needed,
268  where_needed);
269  }
270  else
271  elog(ERROR, "unrecognized node type: %d", (int) nodeTag(node));
272  }
273 }
Relids ph_needed
Definition: pathnodes.h:2268
#define IsA(nodeptr, _type_)
Definition: nodes.h:576
Relids * attr_needed
Definition: pathnodes.h:674
Definition: nodes.h:525
AttrNumber varattno
Definition: primnodes.h:172
Definition: primnodes.h:167
#define ERROR
Definition: elog.h:43
bool bms_is_subset(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:315
PlaceHolderInfo * find_placeholder_info(PlannerInfo *root, PlaceHolderVar *phv, bool create_new_ph)
Definition: placeholder.c:69
Relids relids
Definition: pathnodes.h:641
List * lappend(List *list, void *datum)
Definition: list.c:322
bool bms_is_empty(const Bitmapset *a)
Definition: bitmapset.c:701
Index varno
Definition: primnodes.h:170
List * exprs
Definition: pathnodes.h:1044
#define Assert(condition)
Definition: c.h:739
#define lfirst(lc)
Definition: pg_list.h:190
#define nodeTag(nodeptr)
Definition: nodes.h:530
#define elog(elevel,...)
Definition: elog.h:228
RelOptInfo * find_base_rel(PlannerInfo *root, int relid)
Definition: relnode.c:363
#define copyObject(obj)
Definition: nodes.h:641
struct PathTarget * reltarget
Definition: pathnodes.h:652
Bitmapset * bms_add_members(Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:793
AttrNumber min_attr
Definition: pathnodes.h:672

◆ build_base_rel_tlists()

void build_base_rel_tlists ( PlannerInfo root,
List final_tlist 
)

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

183 {
184  List *tlist_vars = pull_var_clause((Node *) final_tlist,
188 
189  if (tlist_vars != NIL)
190  {
191  add_vars_to_targetlist(root, tlist_vars, bms_make_singleton(0), true);
192  list_free(tlist_vars);
193  }
194 
195  /*
196  * If there's a HAVING clause, we'll need the Vars it uses, too. Note
197  * that HAVING can contain Aggrefs but not WindowFuncs.
198  */
199  if (root->parse->havingQual)
200  {
201  List *having_vars = pull_var_clause(root->parse->havingQual,
204 
205  if (having_vars != NIL)
206  {
207  add_vars_to_targetlist(root, having_vars,
208  bms_make_singleton(0), true);
209  list_free(having_vars);
210  }
211  }
212 }
#define NIL
Definition: pg_list.h:65
Query * parse
Definition: pathnodes.h:177
Definition: nodes.h:525
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:229
Bitmapset * bms_make_singleton(int x)
Definition: bitmapset.c:186
#define PVC_INCLUDE_PLACEHOLDERS
Definition: optimizer.h:174
#define PVC_RECURSE_WINDOWFUNCS
Definition: optimizer.h:173
void list_free(List *list)
Definition: list.c:1377
Node * havingQual
Definition: parsenodes.h:152
Definition: pg_list.h:50
#define PVC_RECURSE_AGGREGATES
Definition: optimizer.h:171

◆ build_implied_join_equality()

RestrictInfo* build_implied_join_equality ( Oid  opno,
Oid  collation,
Expr item1,
Expr item2,
Relids  qualscope,
Relids  nullable_relids,
Index  security_level 
)

Definition at line 2353 of file initsplan.c.

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

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

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

◆ change_plan_targetlist()

Plan* change_plan_targetlist ( Plan subplan,
List tlist,
bool  tlist_parallel_safe 
)

Definition at line 1938 of file createplan.c.

References inject_projection_plan(), is_projection_capable_plan(), Plan::parallel_safe, Plan::targetlist, and tlist_same_exprs().

Referenced by create_unique_plan(), and postgresGetForeignPlan().

1939 {
1940  /*
1941  * If the top plan node can't do projections and its existing target list
1942  * isn't already what we need, we need to add a Result node to help it
1943  * along.
1944  */
1945  if (!is_projection_capable_plan(subplan) &&
1946  !tlist_same_exprs(tlist, subplan->targetlist))
1947  subplan = inject_projection_plan(subplan, tlist,
1948  subplan->parallel_safe &&
1949  tlist_parallel_safe);
1950  else
1951  {
1952  /* Else we can just replace the plan node's tlist */
1953  subplan->targetlist = tlist;
1954  subplan->parallel_safe &= tlist_parallel_safe;
1955  }
1956  return subplan;
1957 }
bool is_projection_capable_plan(Plan *plan)
Definition: createplan.c:6808
static Plan * inject_projection_plan(Plan *subplan, List *tlist, bool parallel_safe)
Definition: createplan.c:1906
bool tlist_same_exprs(List *tlist1, List *tlist2)
Definition: tlist.c:240
List * targetlist
Definition: plannodes.h:140
bool parallel_safe
Definition: plannodes.h:134

◆ create_lateral_join_info()

void create_lateral_join_info ( PlannerInfo root)

Definition at line 449 of file initsplan.c.

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

Referenced by query_planner().

450 {
451  bool found_laterals = false;
452  Index rti;
453  ListCell *lc;
454 
455  /* We need do nothing if the query contains no LATERAL RTEs */
456  if (!root->hasLateralRTEs)
457  return;
458 
459  /*
460  * Examine all baserels (the rel array has been set up by now).
461  */
462  for (rti = 1; rti < root->simple_rel_array_size; rti++)
463  {
464  RelOptInfo *brel = root->simple_rel_array[rti];
465  Relids lateral_relids;
466 
467  /* there may be empty slots corresponding to non-baserel RTEs */
468  if (brel == NULL)
469  continue;
470 
471  Assert(brel->relid == rti); /* sanity check on array */
472 
473  /* ignore RTEs that are "other rels" */
474  if (brel->reloptkind != RELOPT_BASEREL)
475  continue;
476 
477  lateral_relids = NULL;
478 
479  /* consider each laterally-referenced Var or PHV */
480  foreach(lc, brel->lateral_vars)
481  {
482  Node *node = (Node *) lfirst(lc);
483 
484  if (IsA(node, Var))
485  {
486  Var *var = (Var *) node;
487 
488  found_laterals = true;
489  lateral_relids = bms_add_member(lateral_relids,
490  var->varno);
491  }
492  else if (IsA(node, PlaceHolderVar))
493  {
494  PlaceHolderVar *phv = (PlaceHolderVar *) node;
495  PlaceHolderInfo *phinfo = find_placeholder_info(root, phv,
496  false);
497 
498  found_laterals = true;
499  lateral_relids = bms_add_members(lateral_relids,
500  phinfo->ph_eval_at);
501  }
502  else
503  Assert(false);
504  }
505 
506  /* We now have all the simple lateral refs from this rel */
507  brel->direct_lateral_relids = lateral_relids;
508  brel->lateral_relids = bms_copy(lateral_relids);
509  }
510 
511  /*
512  * Now check for lateral references within PlaceHolderVars, and mark their
513  * eval_at rels as having lateral references to the source rels.
514  *
515  * For a PHV that is due to be evaluated at a baserel, mark its source(s)
516  * as direct lateral dependencies of the baserel (adding onto the ones
517  * recorded above). If it's due to be evaluated at a join, mark its
518  * source(s) as indirect lateral dependencies of each baserel in the join,
519  * ie put them into lateral_relids but not direct_lateral_relids. This is
520  * appropriate because we can't put any such baserel on the outside of a
521  * join to one of the PHV's lateral dependencies, but on the other hand we
522  * also can't yet join it directly to the dependency.
523  */
524  foreach(lc, root->placeholder_list)
525  {
526  PlaceHolderInfo *phinfo = (PlaceHolderInfo *) lfirst(lc);
527  Relids eval_at = phinfo->ph_eval_at;
528  int varno;
529 
530  if (phinfo->ph_lateral == NULL)
531  continue; /* PHV is uninteresting if no lateral refs */
532 
533  found_laterals = true;
534 
535  if (bms_get_singleton_member(eval_at, &varno))
536  {
537  /* Evaluation site is a baserel */
538  RelOptInfo *brel = find_base_rel(root, varno);
539 
540  brel->direct_lateral_relids =
542  phinfo->ph_lateral);
543  brel->lateral_relids =
545  phinfo->ph_lateral);
546  }
547  else
548  {
549  /* Evaluation site is a join */
550  varno = -1;
551  while ((varno = bms_next_member(eval_at, varno)) >= 0)
552  {
553  RelOptInfo *brel = find_base_rel(root, varno);
554 
556  phinfo->ph_lateral);
557  }
558  }
559  }
560 
561  /*
562  * If we found no actual lateral references, we're done; but reset the
563  * hasLateralRTEs flag to avoid useless work later.
564  */
565  if (!found_laterals)
566  {
567  root->hasLateralRTEs = false;
568  return;
569  }
570 
571  /*
572  * Calculate the transitive closure of the lateral_relids sets, so that
573  * they describe both direct and indirect lateral references. If relation
574  * X references Y laterally, and Y references Z laterally, then we will
575  * have to scan X on the inside of a nestloop with Z, so for all intents
576  * and purposes X is laterally dependent on Z too.
577  *
578  * This code is essentially Warshall's algorithm for transitive closure.
579  * The outer loop considers each baserel, and propagates its lateral
580  * dependencies to those baserels that have a lateral dependency on it.
581  */
582  for (rti = 1; rti < root->simple_rel_array_size; rti++)
583  {
584  RelOptInfo *brel = root->simple_rel_array[rti];
585  Relids outer_lateral_relids;
586  Index rti2;
587 
588  if (brel == NULL || brel->reloptkind != RELOPT_BASEREL)
589  continue;
590 
591  /* need not consider baserel further if it has no lateral refs */
592  outer_lateral_relids = brel->lateral_relids;
593  if (outer_lateral_relids == NULL)
594  continue;
595 
596  /* else scan all baserels */
597  for (rti2 = 1; rti2 < root->simple_rel_array_size; rti2++)
598  {
599  RelOptInfo *brel2 = root->simple_rel_array[rti2];
600 
601  if (brel2 == NULL || brel2->reloptkind != RELOPT_BASEREL)
602  continue;
603 
604  /* if brel2 has lateral ref to brel, propagate brel's refs */
605  if (bms_is_member(rti, brel2->lateral_relids))
607  outer_lateral_relids);
608  }
609  }
610 
611  /*
612  * Now that we've identified all lateral references, mark each baserel
613  * with the set of relids of rels that reference it laterally (possibly
614  * indirectly) --- that is, the inverse mapping of lateral_relids.
615  */
616  for (rti = 1; rti < root->simple_rel_array_size; rti++)
617  {
618  RelOptInfo *brel = root->simple_rel_array[rti];
619  Relids lateral_relids;
620  int rti2;
621 
622  if (brel == NULL || brel->reloptkind != RELOPT_BASEREL)
623  continue;
624 
625  /* Nothing to do at rels with no lateral refs */
626  lateral_relids = brel->lateral_relids;
627  if (lateral_relids == NULL)
628  continue;
629 
630  /*
631  * We should not have broken the invariant that lateral_relids is
632  * exactly NULL if empty.
633  */
634  Assert(!bms_is_empty(lateral_relids));
635 
636  /* Also, no rel should have a lateral dependency on itself */
637  Assert(!bms_is_member(rti, lateral_relids));
638 
639  /* Mark this rel's referencees */
640  rti2 = -1;
641  while ((rti2 = bms_next_member(lateral_relids, rti2)) >= 0)
642  {
643  RelOptInfo *brel2 = root->simple_rel_array[rti2];
644 
645  Assert(brel2 != NULL && brel2->reloptkind == RELOPT_BASEREL);
646  brel2->lateral_referencers =
647  bms_add_member(brel2->lateral_referencers, rti);
648  }
649  }
650 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:576
Bitmapset * bms_copy(const Bitmapset *a)
Definition: bitmapset.c:74
Relids ph_eval_at
Definition: pathnodes.h:2266
RelOptKind reloptkind
Definition: pathnodes.h:638
int bms_next_member(const Bitmapset *a, int prevbit)
Definition: bitmapset.c:1043
Definition: nodes.h:525
bool bms_get_singleton_member(const Bitmapset *a, int *member)
Definition: bitmapset.c:615
Definition: primnodes.h:167
struct RelOptInfo ** simple_rel_array
Definition: pathnodes.h:201
Relids lateral_relids
Definition: pathnodes.h:666
bool hasLateralRTEs
Definition: pathnodes.h:344
PlaceHolderInfo * find_placeholder_info(PlannerInfo *root, PlaceHolderVar *phv, bool create_new_ph)
Definition: placeholder.c:69
int simple_rel_array_size
Definition: pathnodes.h:202
Index relid
Definition: pathnodes.h:669
Relids lateral_referencers
Definition: pathnodes.h:677
bool bms_is_empty(const Bitmapset *a)
Definition: bitmapset.c:701
Index varno
Definition: primnodes.h:170
Relids direct_lateral_relids
Definition: pathnodes.h:665
Relids ph_lateral
Definition: pathnodes.h:2267
unsigned int Index
Definition: c.h:476
#define Assert(condition)
Definition: c.h:739
#define lfirst(lc)
Definition: pg_list.h:190
List * lateral_vars
Definition: pathnodes.h:676
Bitmapset * bms_add_member(Bitmapset *a, int x)
Definition: bitmapset.c:736
List * placeholder_list
Definition: pathnodes.h:292
RelOptInfo * find_base_rel(PlannerInfo *root, int relid)
Definition: relnode.c:363
bool bms_is_member(int x, const Bitmapset *a)
Definition: bitmapset.c:427
Bitmapset * bms_add_members(Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:793

◆ create_plan()

Plan* create_plan ( PlannerInfo root,
Path best_path 
)

Definition at line 313 of file createplan.c.

References apply_tlist_labeling(), Assert, CP_EXACT_TLIST, create_plan_recurse(), PlannerInfo::curOuterParams, PlannerInfo::curOuterRels, elog, ERROR, IsA, NIL, 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().

314 {
315  Plan *plan;
316 
317  /* plan_params should not be in use in current query level */
318  Assert(root->plan_params == NIL);
319 
320  /* Initialize this module's workspace in PlannerInfo */
321  root->curOuterRels = NULL;
322  root->curOuterParams = NIL;
323 
324  /* Recursively process the path tree, demanding the correct tlist result */
325  plan = create_plan_recurse(root, best_path, CP_EXACT_TLIST);
326 
327  /*
328  * Make sure the topmost plan node's targetlist exposes the original
329  * column names and other decorative info. Targetlists generated within
330  * the planner don't bother with that stuff, but we must have it on the
331  * top-level tlist seen at execution time. However, ModifyTable plan
332  * nodes don't have a tlist matching the querytree targetlist.
333  */
334  if (!IsA(plan, ModifyTable))
336 
337  /*
338  * Attach any initPlans created in this query level to the topmost plan
339  * node. (In principle the initplans could go in any plan node at or
340  * above where they're referenced, but there seems no reason to put them
341  * any lower than the topmost node for the query level. Also, see
342  * comments for SS_finalize_plan before you try to change this.)
343  */
344  SS_attach_initplans(root, plan);
345 
346  /* Check we successfully assigned all NestLoopParams to plan nodes */
347  if (root->curOuterParams != NIL)
348  elog(ERROR, "failed to assign all NestLoopParams to plan nodes");
349 
350  /*
351  * Reset plan_params to ensure param IDs used for nestloop params are not
352  * re-used later
353  */
354  root->plan_params = NIL;
355 
356  return plan;
357 }
#define NIL
Definition: pg_list.h:65
void apply_tlist_labeling(List *dest_tlist, List *src_tlist)
Definition: tlist.c:340
#define IsA(nodeptr, _type_)
Definition: nodes.h:576
List * plan_params
Definition: pathnodes.h:191
Relids curOuterRels
Definition: pathnodes.h:355
static Plan * create_plan_recurse(PlannerInfo *root, Path *best_path, int flags)
Definition: createplan.c:364
#define ERROR
Definition: elog.h:43
List * curOuterParams
Definition: pathnodes.h:356
#define Assert(condition)
Definition: c.h:739
void SS_attach_initplans(PlannerInfo *root, Plan *plan)
Definition: subselect.c:2118
List * targetlist
Definition: plannodes.h:140
#define elog(elevel,...)
Definition: elog.h:228
List * processed_tlist
Definition: pathnodes.h:323
#define CP_EXACT_TLIST
Definition: createplan.c:68

◆ deconstruct_jointree()

List* deconstruct_jointree ( PlannerInfo root)

Definition at line 686 of file initsplan.c.

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

Referenced by query_planner().

687 {
688  List *result;
689  Relids qualscope;
690  Relids inner_join_rels;
691  List *postponed_qual_list = NIL;
692 
693  /* Start recursion at top of jointree */
694  Assert(root->parse->jointree != NULL &&
695  IsA(root->parse->jointree, FromExpr));
696 
697  /* this is filled as we scan the jointree */
698  root->nullable_baserels = NULL;
699 
700  result = deconstruct_recurse(root, (Node *) root->parse->jointree, false,
701  &qualscope, &inner_join_rels,
702  &postponed_qual_list);
703 
704  /* Shouldn't be any leftover quals */
705  Assert(postponed_qual_list == NIL);
706 
707  return result;
708 }
#define NIL
Definition: pg_list.h:65
#define IsA(nodeptr, _type_)
Definition: nodes.h:576
Query * parse
Definition: pathnodes.h:177
FromExpr * jointree
Definition: parsenodes.h:138
Definition: nodes.h:525
#define Assert(condition)
Definition: c.h:739
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:732
Relids nullable_baserels
Definition: pathnodes.h:233
Definition: pg_list.h:50

◆ distribute_restrictinfo_to_rels()

void distribute_restrictinfo_to_rels ( PlannerInfo root,
RestrictInfo restrictinfo 
)

Definition at line 2204 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, PostponedQual::relids, 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().

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

◆ extract_query_dependencies_walker()

bool extract_query_dependencies_walker ( Node node,
PlannerInfo root 
)

Definition at line 2794 of file setrefs.c.

References Assert, CMD_UTILITY, Query::commandType, PlannerGlobal::dependsOnRole, expression_tree_walker(), extract_query_dependencies_walker(), fix_expr_common(), PlannerInfo::glob, Query::hasRowSecurity, IsA, lappend_oid(), lfirst, OidIsValid, query_tree_walker(), PlannerGlobal::relationOids, RangeTblEntry::relid, Query::rtable, RTE_NAMEDTUPLESTORE, RTE_RELATION, RangeTblEntry::rtekind, UtilityContainsQuery(), and Query::utilityStmt.

Referenced by expression_planner_with_deps(), extract_query_dependencies(), and extract_query_dependencies_walker().

2795 {
2796  if (node == NULL)
2797  return false;
2798  Assert(!IsA(node, PlaceHolderVar));
2799  if (IsA(node, Query))
2800  {
2801  Query *query = (Query *) node;
2802  ListCell *lc;
2803 
2804  if (query->commandType == CMD_UTILITY)
2805  {
2806  /*
2807  * Ignore utility statements, except those (such as EXPLAIN) that
2808  * contain a parsed-but-not-planned query.
2809  */
2810  query = UtilityContainsQuery(query->utilityStmt);
2811  if (query == NULL)
2812  return false;
2813  }
2814 
2815  /* Remember if any Query has RLS quals applied by rewriter */
2816  if (query->hasRowSecurity)
2817  context->glob->dependsOnRole = true;
2818 
2819  /* Collect relation OIDs in this Query's rtable */
2820  foreach(lc, query->rtable)
2821  {
2822  RangeTblEntry *rte = (RangeTblEntry *) lfirst(lc);
2823 
2824  if (rte->rtekind == RTE_RELATION)
2825  context->glob->relationOids =
2826  lappend_oid(context->glob->relationOids, rte->relid);
2827  else if (rte->rtekind == RTE_NAMEDTUPLESTORE &&
2828  OidIsValid(rte->relid))
2829  context->glob->relationOids =
2830  lappend_oid(context->glob->relationOids,
2831  rte->relid);
2832  }
2833 
2834  /* And recurse into the query's subexpressions */
2836  (void *) context, 0);
2837  }
2838  /* Extract function dependencies and check for regclass Consts */
2839  fix_expr_common(context, node);
2841  (void *) context);
2842 }
bool query_tree_walker(Query *query, bool(*walker)(), void *context, int flags)
Definition: nodeFuncs.c:2273
#define IsA(nodeptr, _type_)
Definition: nodes.h:576
Node * utilityStmt
Definition: parsenodes.h:120
List * lappend_oid(List *list, Oid datum)
Definition: list.c:358
#define OidIsValid(objectId)
Definition: c.h:645
Query * UtilityContainsQuery(Node *parsetree)
Definition: utility.c:1907
List * rtable
Definition: parsenodes.h:137
bool extract_query_dependencies_walker(Node *node, PlannerInfo *context)
Definition: setrefs.c:2794
static void fix_expr_common(PlannerInfo *root, Node *node)
Definition: setrefs.c:1487
CmdType commandType
Definition: parsenodes.h:112
#define Assert(condition)
Definition: c.h:739
#define lfirst(lc)
Definition: pg_list.h:190
bool expression_tree_walker(Node *node, bool(*walker)(), void *context)
Definition: nodeFuncs.c:1839
RTEKind rtekind
Definition: parsenodes.h:974
bool hasRowSecurity
Definition: parsenodes.h:133

◆ find_lateral_references()

void find_lateral_references ( PlannerInfo root)

Definition at line 303 of file initsplan.c.

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

Referenced by query_planner().

304 {
305  Index rti;
306 
307  /* We need do nothing if the query contains no LATERAL RTEs */
308  if (!root->hasLateralRTEs)
309  return;
310 
311  /*
312  * Examine all baserels (the rel array has been set up by now).
313  */
314  for (rti = 1; rti < root->simple_rel_array_size; rti++)
315  {
316  RelOptInfo *brel = root->simple_rel_array[rti];
317 
318  /* there may be empty slots corresponding to non-baserel RTEs */
319  if (brel == NULL)
320  continue;
321 
322  Assert(brel->relid == rti); /* sanity check on array */
323 
324  /*
325  * This bit is less obvious than it might look. We ignore appendrel
326  * otherrels and consider only their parent baserels. In a case where
327  * a LATERAL-containing UNION ALL subquery was pulled up, it is the
328  * otherrel that is actually going to be in the plan. However, we
329  * want to mark all its lateral references as needed by the parent,
330  * because it is the parent's relid that will be used for join
331  * planning purposes. And the parent's RTE will contain all the
332  * lateral references we need to know, since the pulled-up member is
333  * nothing but a copy of parts of the original RTE's subquery. We
334  * could visit the parent's children instead and transform their
335  * references back to the parent's relid, but it would be much more
336  * complicated for no real gain. (Important here is that the child
337  * members have not yet received any processing beyond being pulled
338  * up.) Similarly, in appendrels created by inheritance expansion,
339  * it's sufficient to look at the parent relation.
340  */
341 
342  /* ignore RTEs that are "other rels" */
343  if (brel->reloptkind != RELOPT_BASEREL)
344  continue;
345 
346  extract_lateral_references(root, brel, rti);
347  }
348 }
RelOptKind reloptkind
Definition: pathnodes.h:638
struct RelOptInfo ** simple_rel_array
Definition: pathnodes.h:201
bool hasLateralRTEs
Definition: pathnodes.h:344
int simple_rel_array_size
Definition: pathnodes.h:202
Index relid
Definition: pathnodes.h:669
unsigned int Index
Definition: c.h:476
#define Assert(condition)
Definition: c.h:739
static void extract_lateral_references(PlannerInfo *root, RelOptInfo *brel, Index rtindex)
Definition: initsplan.c:351

◆ innerrel_is_unique()

bool innerrel_is_unique ( PlannerInfo root,
Relids  joinrelids,
Relids  outerrelids,
RelOptInfo innerrel,
JoinType  jointype,
List restrictlist,
bool  force_cache 
)

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

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

◆ is_projection_capable_path()

bool is_projection_capable_path ( Path path)

Definition at line 6764 of file createplan.c.

References IS_DUMMY_APPEND, 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().

6765 {
6766  /* Most plan types can project, so just list the ones that can't */
6767  switch (path->pathtype)
6768  {
6769  case T_Hash:
6770  case T_Material:
6771  case T_Sort:
6772  case T_Unique:
6773  case T_SetOp:
6774  case T_LockRows:
6775  case T_Limit:
6776  case T_ModifyTable:
6777  case T_MergeAppend:
6778  case T_RecursiveUnion:
6779  return false;
6780  case T_Append:
6781 
6782  /*
6783  * Append can't project, but if an AppendPath is being used to
6784  * represent a dummy path, what will actually be generated is a
6785  * Result which can project.
6786  */
6787  return IS_DUMMY_APPEND(path);
6788  case T_ProjectSet:
6789 
6790  /*
6791  * Although ProjectSet certainly projects, say "no" because we
6792  * don't want the planner to randomly replace its tlist with
6793  * something else; the SRFs have to stay at top level. This might
6794  * get relaxed later.
6795  */
6796  return false;
6797  default:
6798  break;
6799  }
6800  return true;
6801 }
Definition: nodes.h:80
Definition: nodes.h:49
Definition: nodes.h:76
NodeTag pathtype
Definition: pathnodes.h:1112
Definition: nodes.h:83
#define IS_DUMMY_APPEND(p)
Definition: pathnodes.h:1380
Definition: nodes.h:84
Definition: nodes.h:86

◆ is_projection_capable_plan()

bool is_projection_capable_plan ( Plan plan)

Definition at line 6808 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 change_plan_targetlist(), and prepare_sort_from_pathkeys().

6809 {
6810  /* Most plan types can project, so just list the ones that can't */
6811  switch (nodeTag(plan))
6812  {
6813  case T_Hash:
6814  case T_Material:
6815  case T_Sort:
6816  case T_Unique:
6817  case T_SetOp:
6818  case T_LockRows:
6819  case T_Limit:
6820  case T_ModifyTable:
6821  case T_Append:
6822  case T_MergeAppend:
6823  case T_RecursiveUnion:
6824  return false;
6825  case T_ProjectSet:
6826 
6827  /*
6828  * Although ProjectSet certainly projects, say "no" because we
6829  * don't want the planner to randomly replace its tlist with
6830  * something else; the SRFs have to stay at top level. This might
6831  * get relaxed later.
6832  */
6833  return false;
6834  default:
6835  break;
6836  }
6837  return true;
6838 }
Definition: nodes.h:80
Definition: nodes.h:49
Definition: nodes.h:76
Definition: nodes.h:83
#define nodeTag(nodeptr)
Definition: nodes.h:530
Definition: nodes.h:84
Definition: nodes.h:86

◆ make_agg()

Agg* make_agg ( List tlist,
List qual,
AggStrategy  aggstrategy,
AggSplit  aggsplit,
int  numGroupCols,
AttrNumber grpColIdx,
Oid grpOperators,
Oid grpCollations,
List groupingSets,
List chain,
double  dNumGroups,
Plan lefttree 
)

Definition at line 6192 of file createplan.c.

References Agg::aggParams, Agg::aggsplit, Agg::aggstrategy, Agg::chain, Agg::groupingSets, Agg::grpColIdx, Agg::grpCollations, Agg::grpOperators, Plan::lefttree, makeNode, Min, 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().

6197 {
6198  Agg *node = makeNode(Agg);
6199  Plan *plan = &node->plan;
6200  long numGroups;
6201 
6202  /* Reduce to long, but 'ware overflow! */
6203  numGroups = (long) Min(dNumGroups, (double) LONG_MAX);
6204 
6205  node->aggstrategy = aggstrategy;
6206  node->aggsplit = aggsplit;
6207  node->numCols = numGroupCols;
6208  node->grpColIdx = grpColIdx;
6209  node->grpOperators = grpOperators;
6210  node->grpCollations = grpCollations;
6211  node->numGroups = numGroups;
6212  node->aggParams = NULL; /* SS_finalize_plan() will fill this */
6213  node->groupingSets = groupingSets;
6214  node->chain = chain;
6215 
6216  plan->qual = qual;
6217  plan->targetlist = tlist;
6218  plan->lefttree = lefttree;
6219  plan->righttree = NULL;
6220 
6221  return node;
6222 }
int numCols
Definition: plannodes.h:807
List * qual
Definition: plannodes.h:141
AttrNumber * grpColIdx
Definition: plannodes.h:808
Oid * grpCollations
Definition: plannodes.h:810
#define Min(x, y)
Definition: c.h:911
struct Plan * righttree
Definition: plannodes.h:143
AggStrategy aggstrategy
Definition: plannodes.h:805
Bitmapset * aggParams
Definition: plannodes.h:812
Plan plan
Definition: plannodes.h:804
List * groupingSets
Definition: plannodes.h:814
#define makeNode(_type_)
Definition: nodes.h:573
AggSplit aggsplit
Definition: plannodes.h:806
long numGroups
Definition: plannodes.h:811
struct Plan * lefttree
Definition: plannodes.h:142
List * targetlist
Definition: plannodes.h:140
Oid * grpOperators
Definition: plannodes.h:809
List * chain
Definition: plannodes.h:815
Definition: plannodes.h:802

◆ make_foreignscan()

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 5432 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, ForeignScan::operation, Scan::plan, Plan::qual, Plan::righttree, ForeignScan::scan, Scan::scanrelid, and Plan::targetlist.

Referenced by fileGetForeignPlan(), and postgresGetForeignPlan().

5440 {
5441  ForeignScan *node = makeNode(ForeignScan);
5442  Plan *plan = &node->scan.plan;
5443 
5444  /* cost will be filled in by create_foreignscan_plan */
5445  plan->targetlist = qptlist;
5446  plan->qual = qpqual;
5447  plan->lefttree = outer_plan;
5448  plan->righttree = NULL;
5449  node->scan.scanrelid = scanrelid;
5450  node->operation = CMD_SELECT;
5451  /* fs_server will be filled in by create_foreignscan_plan */
5452  node->fs_server = InvalidOid;
5453  node->fdw_exprs = fdw_exprs;
5454  node->fdw_private = fdw_private;
5455  node->fdw_scan_tlist = fdw_scan_tlist;
5456  node->fdw_recheck_quals = fdw_recheck_quals;
5457  /* fs_relids will be filled in by create_foreignscan_plan */
5458  node->fs_relids = NULL;
5459  /* fsSystemCol will be filled in by create_foreignscan_plan */
5460  node->fsSystemCol = false;
5461 
5462  return node;
5463 }
List * qual
Definition: plannodes.h:141
Plan plan
Definition: plannodes.h:340
Index scanrelid
Definition: plannodes.h:341
Oid fs_server
Definition: plannodes.h:612
List * fdw_exprs
Definition: plannodes.h:613
List * fdw_private
Definition: plannodes.h:614
List * fdw_scan_tlist
Definition: plannodes.h:615
CmdType operation
Definition: plannodes.h:611
struct Plan * righttree
Definition: plannodes.h:143
List * fdw_recheck_quals
Definition: plannodes.h:616
#define InvalidOid
Definition: postgres_ext.h:36
#define makeNode(_type_)
Definition: nodes.h:573
struct Plan * lefttree
Definition: plannodes.h:142
List * targetlist
Definition: plannodes.h:140
bool fsSystemCol
Definition: plannodes.h:618
Bitmapset * fs_relids
Definition: plannodes.h:617

◆ make_limit()

Limit* make_limit ( Plan lefttree,
Node limitOffset,
Node limitCount 
)

Definition at line 6555 of file createplan.c.

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

Referenced by create_limit_plan(), and create_minmaxagg_plan().

6556 {
6557  Limit *node = makeNode(Limit);
6558  Plan *plan = &node->plan;
6559 
6560  plan->targetlist = lefttree->targetlist;
6561  plan->qual = NIL;
6562  plan->lefttree = lefttree;
6563  plan->righttree = NULL;
6564 
6565  node->limitOffset = limitOffset;
6566  node->limitCount = limitCount;
6567 
6568  return node;
6569 }
#define NIL
Definition: pg_list.h:65
List * qual
Definition: plannodes.h:141
Plan plan
Definition: plannodes.h:967
Node * limitOffset
Definition: plannodes.h:968
struct Plan * righttree
Definition: plannodes.h:143
Node * limitCount
Definition: plannodes.h:969
#define makeNode(_type_)
Definition: nodes.h:573
struct Plan * lefttree
Definition: plannodes.h:142
List * targetlist
Definition: plannodes.h:140

◆ make_sort_from_sortclauses()

Sort* make_sort_from_sortclauses ( List sortcls,
Plan lefttree 
)

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

6047 {
6048  List *sub_tlist = lefttree->targetlist;
6049  ListCell *l;
6050  int numsortkeys;
6051  AttrNumber *sortColIdx;
6052  Oid *sortOperators;
6053  Oid *collations;
6054  bool *nullsFirst;
6055 
6056  /* Convert list-ish representation to arrays wanted by executor */
6057  numsortkeys = list_length(sortcls);
6058  sortColIdx = (AttrNumber *) palloc(numsortkeys * sizeof(AttrNumber));
6059  sortOperators = (Oid *) palloc(numsortkeys * sizeof(Oid));
6060  collations = (Oid *) palloc(numsortkeys * sizeof(Oid));
6061  nullsFirst = (bool *) palloc(numsortkeys * sizeof(bool));
6062 
6063  numsortkeys = 0;
6064  foreach(l, sortcls)
6065  {
6066  SortGroupClause *sortcl = (SortGroupClause *) lfirst(l);
6067  TargetEntry *tle = get_sortgroupclause_tle(sortcl, sub_tlist);
6068 
6069  sortColIdx[numsortkeys] = tle->resno;
6070  sortOperators[numsortkeys] = sortcl->sortop;
6071  collations[numsortkeys] = exprCollation((Node *) tle->expr);
6072  nullsFirst[numsortkeys] = sortcl->nulls_first;
6073  numsortkeys++;
6074  }
6075 
6076  return make_sort(lefttree, numsortkeys,
6077  sortColIdx, sortOperators,
6078  collations, nullsFirst);
6079 }
TargetEntry * get_sortgroupclause_tle(SortGroupClause *sgClause, List *targetList)
Definition: tlist.c:389
Definition: nodes.h:525
unsigned int Oid
Definition: postgres_ext.h:31
AttrNumber resno
Definition: primnodes.h:1394
static Sort * make_sort(Plan *lefttree, int numCols, AttrNumber *sortColIdx, Oid *sortOperators, Oid *collations, bool *nullsFirst)
Definition: createplan.c:5672
#define lfirst(lc)
Definition: pg_list.h:190
Expr * expr
Definition: primnodes.h:1393
static int list_length(const List *l)
Definition: pg_list.h:169
Oid exprCollation(const Node *expr)
Definition: nodeFuncs.c:719
List * targetlist
Definition: plannodes.h:140
void * palloc(Size size)
Definition: mcxt.c:949
Definition: pg_list.h:50
int16 AttrNumber
Definition: attnum.h:21

◆ match_foreign_keys_to_quals()

void match_foreign_keys_to_quals ( PlannerInfo root)

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

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

◆ materialize_finished_plan()

Plan* materialize_finished_plan ( Plan subplan)

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

6159 {
6160  Plan *matplan;
6161  Path matpath; /* dummy for result of cost_material */
6162 
6163  matplan = (Plan *) make_material(subplan);
6164 
6165  /*
6166  * XXX horrid kluge: if there are any initPlans attached to the subplan,
6167  * move them up to the Material node, which is now effectively the top
6168  * plan node in its query level. This prevents failure in
6169  * SS_finalize_plan(), which see for comments. We don't bother adjusting
6170  * the subplan's cost estimate for this.
6171  */
6172  matplan->initPlan = subplan->initPlan;
6173  subplan->initPlan = NIL;
6174 
6175  /* Set cost data */
6176  cost_material(&matpath,
6177  subplan->startup_cost,
6178  subplan->total_cost,
6179  subplan->plan_rows,
6180  subplan->plan_width);
6181  matplan->startup_cost = matpath.startup_cost;
6182  matplan->total_cost = matpath.total_cost;
6183  matplan->plan_rows = subplan->plan_rows;
6184  matplan->plan_width = subplan->plan_width;
6185  matplan->parallel_aware = false;
6186  matplan->parallel_safe = subplan->parallel_safe;
6187 
6188  return matplan;
6189 }
#define NIL
Definition: pg_list.h:65
double plan_rows
Definition: plannodes.h:127
static Material * make_material(Plan *lefttree)
Definition: createplan.c:6136
Cost startup_cost
Definition: pathnodes.h:1125
Cost startup_cost
Definition: plannodes.h:121
bool parallel_aware
Definition: plannodes.h:133
Cost total_cost
Definition: pathnodes.h:1126
void cost_material(Path *path, Cost input_startup_cost, Cost input_total_cost, double tuples, int width)
Definition: costsize.c:2097
int plan_width
Definition: plannodes.h:128
List * initPlan
Definition: plannodes.h:144
Cost total_cost
Definition: plannodes.h:122
bool parallel_safe
Definition: plannodes.h:134

◆ preprocess_minmax_aggregates()

void preprocess_minmax_aggregates ( PlannerInfo root)

Definition at line 72 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, OidIsValid, MinMaxAggInfo::param, parse(), PlannerInfo::parse, planner_rt_fetch, PlannerInfo::processed_tlist, 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().

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

◆ process_implied_equality()

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 2288 of file initsplan.c.

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

Referenced by generate_base_implied_equalities_const(), and generate_base_implied_equalities_no_const().

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

◆ query_is_distinct_for()

bool query_is_distinct_for ( Query query,
List colnos,
List opids 
)

Definition at line 775 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(), OidIsValid, SetOperationStmt::op, TargetEntry::resjunk, TargetEntry::resno, SETOP_NONE, Query::setOperations, and Query::targetList.

Referenced by create_unique_path(), and rel_is_distinct_for().

776 {
777  ListCell *l;
778  Oid opid;
779 
780  Assert(list_length(colnos) == list_length(opids));
781 
782  /*
783  * DISTINCT (including DISTINCT ON) guarantees uniqueness if all the
784  * columns in the DISTINCT clause appear in colnos and operator semantics
785  * match. This is true even if there are SRFs in the DISTINCT columns or
786  * elsewhere in the tlist.
787  */
788  if (query->distinctClause)
789  {
790  foreach(l, query->distinctClause)
791  {
792  SortGroupClause *sgc = (SortGroupClause *) lfirst(l);
794  query->targetList);
795 
796  opid = distinct_col_search(tle->resno, colnos, opids);
797  if (!OidIsValid(opid) ||
798  !equality_ops_are_compatible(opid, sgc->eqop))
799  break; /* exit early if no match */
800  }
801  if (l == NULL) /* had matches for all? */
802  return true;
803  }
804 
805  /*
806  * Otherwise, a set-returning function in the query's targetlist can
807  * result in returning duplicate rows, despite any grouping that might
808  * occur before tlist evaluation. (If all tlist SRFs are within GROUP BY
809  * columns, it would be safe because they'd be expanded before grouping.
810  * But it doesn't currently seem worth the effort to check for that.)
811  */
812  if (query->hasTargetSRFs)
813  return false;
814 
815  /*
816  * Similarly, GROUP BY without GROUPING SETS guarantees uniqueness if all
817  * the grouped columns appear in colnos and operator semantics match.
818  */
819  if (query->groupClause && !query->groupingSets)
820  {
821  foreach(l, query->groupClause)
822  {
823  SortGroupClause *sgc = (SortGroupClause *) lfirst(l);
825  query->targetList);
826 
827  opid = distinct_col_search(tle->resno, colnos, opids);
828  if (!OidIsValid(opid) ||
829  !equality_ops_are_compatible(opid, sgc->eqop))
830  break; /* exit early if no match */
831  }
832  if (l == NULL) /* had matches for all? */
833  return true;
834  }
835  else if (query->groupingSets)
836  {
837  /*
838  * If we have grouping sets with expressions, we probably don't have
839  * uniqueness and analysis would be hard. Punt.
840  */
841  if (query->groupClause)
842  return false;
843 
844  /*
845  * If we have no groupClause (therefore no grouping expressions), we
846  * might have one or many empty grouping sets. If there's just one,
847  * then we're returning only one row and are certainly unique. But
848  * otherwise, we know we're certainly not unique.
849  */
850  if (list_length(query->groupingSets) == 1 &&
851  ((GroupingSet *) linitial(query->groupingSets))->kind == GROUPING_SET_EMPTY)
852  return true;
853  else
854  return false;
855  }
856  else
857  {
858  /*
859  * If we have no GROUP BY, but do have aggregates or HAVING, then the
860  * result is at most one row so it's surely unique, for any operators.
861  */
862  if (query->hasAggs || query->havingQual)
863  return true;
864  }
865 
866  /*
867  * UNION, INTERSECT, EXCEPT guarantee uniqueness of the whole output row,
868  * except with ALL.
869  */
870  if (query->setOperations)
871  {
873 
874  Assert(topop->op != SETOP_NONE);
875 
876  if (!topop->all)
877  {
878  ListCell *lg;
879 
880  /* We're good if all the nonjunk output columns are in colnos */
881  lg = list_head(topop->groupClauses);
882  foreach(l, query->targetList)
883  {
884  TargetEntry *tle = (TargetEntry *) lfirst(l);
885  SortGroupClause *sgc;
886 
887  if (tle->resjunk)
888  continue; /* ignore resjunk columns */
889 
890  /* non-resjunk columns should have grouping clauses */
891  Assert(lg != NULL);
892  sgc = (SortGroupClause *) lfirst(lg);
893  lg = lnext(topop->groupClauses, lg);
894 
895  opid = distinct_col_search(tle->resno, colnos, opids);
896  if (!OidIsValid(opid) ||
897  !equality_ops_are_compatible(opid, sgc->eqop))
898  break; /* exit early if no match */
899  }
900  if (l == NULL) /* had matches for all? */
901  return true;
902  }
903  }
904 
905  /*
906  * XXX Are there any other cases in which we can easily see the result
907  * must be distinct?
908  *
909  * If you do add more smarts to this function, be sure to update
910  * query_supports_distinctness() to match.
911  */
912 
913  return false;
914 }
TargetEntry * get_sortgroupclause_tle(SortGroupClause *sgClause, List *targetList)
Definition: tlist.c:389
static ListCell * lnext(const List *l, const ListCell *c)
Definition: pg_list.h:321
#define castNode(_type_, nodeptr)
Definition: nodes.h:594
static Oid distinct_col_search(int colno, List *colnos, List *opids)
Definition: analyzejoins.c:924
bool hasAggs
Definition: parsenodes.h:125
List * groupingSets
Definition: parsenodes.h:150
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:645
List * targetList
Definition: parsenodes.h:140
bool resjunk
Definition: primnodes.h:1400
#define linitial(l)
Definition: pg_list.h:195
List * distinctClause
Definition: parsenodes.h:156
AttrNumber resno
Definition: primnodes.h:1394
static ListCell * list_head(const List *l)
Definition: pg_list.h:125
bool hasTargetSRFs
Definition: parsenodes.h:127
#define Assert(condition)
Definition: c.h:739
#define lfirst(lc)
Definition: pg_list.h:190
bool equality_ops_are_compatible(Oid opno1, Oid opno2)
Definition: lsyscache.c:695
static int list_length(const List *l)
Definition: pg_list.h:169
SetOperation op
Definition: parsenodes.h:1634
Node * setOperations
Definition: parsenodes.h:165
List * groupClause
Definition: parsenodes.h:148
Node * havingQual
Definition: parsenodes.h:152

◆ query_planner()

RelOptInfo* query_planner ( PlannerInfo root,
query_pathkeys_callback  qp_callback,
void *  qp_extra 
)

Definition at line 55 of file planmain.c.

References add_base_rels_to_query(), add_other_rels_to_query(), add_path(), add_placeholders_to_base_rels(), Assert, build_base_rel_tlists(), build_simple_rel(), PlannerInfo::canon_pathkeys, RelOptInfo::cheapest_total_path, RelOptInfo::consider_parallel, create_group_result_path(), create_lateral_join_info(), deconstruct_jointree(), PlannerInfo::ec_merging_done, elog, ERROR, extract_restriction_or_clauses(), find_lateral_references(), find_placeholders_in_jointree(), fix_placeholder_input_needed_levels(), PlannerInfo::fkey_list, force_parallel_mode, FORCE_PARALLEL_OFF, FromExpr::fromlist, PlannerInfo::full_join_clauses, generate_base_implied_equalities(), PlannerInfo::glob, PlannerInfo::initial_rels, is_parallel_safe(), IsA, 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, linitial, list_length(), make_one_rel(), match_foreign_keys_to_quals(), NIL, PlannerGlobal::parallelModeOK, Path::param_info, parse(), PlannerInfo::parse, PlannerInfo::placeholder_list, PlannerInfo::processed_tlist, FromExpr::quals, reconsider_outer_join_clauses(), reduce_unique_semijoins(), RelOptInfo::reltarget, remove_useless_joins(), PlannerInfo::right_join_clauses, RTE_RESULT, RangeTblEntry::rtekind, set_cheapest(), setup_simple_rel_arrays(), and PlannerInfo::simple_rte_array.

Referenced by build_minmax_path(), and grouping_planner().

57 {
58  Query *parse = root->parse;
59  List *joinlist;
60  RelOptInfo *final_rel;
61 
62  /*
63  * Init planner lists to empty.
64  *
65  * NOTE: append_rel_list was set up by subquery_planner, so do not touch
66  * here.
67  */
68  root->join_rel_list = NIL;
69  root->join_rel_hash = NULL;
70  root->join_rel_level = NULL;
71  root->join_cur_level = 0;
72  root->canon_pathkeys = NIL;
73  root->left_join_clauses = NIL;
74  root->right_join_clauses = NIL;
75  root->full_join_clauses = NIL;
76  root->join_info_list = NIL;
77  root->placeholder_list = NIL;
78  root->fkey_list = NIL;
79  root->initial_rels = NIL;
80 
81  /*
82  * Set up arrays for accessing base relations and AppendRelInfos.
83  */
85 
86  /*
87  * In the trivial case where the jointree is a single RTE_RESULT relation,
88  * bypass all the rest of this function and just make a RelOptInfo and its
89  * one access path. This is worth optimizing because it applies for
90  * common cases like "SELECT expression" and "INSERT ... VALUES()".
91  */
92  Assert(parse->jointree->fromlist != NIL);
93  if (list_length(parse->jointree->fromlist) == 1)
94  {
95  Node *jtnode = (Node *) linitial(parse->jointree->fromlist);
96 
97  if (IsA(jtnode, RangeTblRef))
98  {
99  int varno = ((RangeTblRef *) jtnode)->rtindex;
100  RangeTblEntry *rte = root->simple_rte_array[varno];
101 
102  Assert(rte != NULL);
103  if (rte->rtekind == RTE_RESULT)
104  {
105  /* Make the RelOptInfo for it directly */
106  final_rel = build_simple_rel(root, varno, NULL);
107 
108  /*
109  * If query allows parallelism in general, check whether the
110  * quals are parallel-restricted. (We need not check
111  * final_rel->reltarget because it's empty at this point.
112  * Anything parallel-restricted in the query tlist will be
113  * dealt with later.) This is normally pretty silly, because
114  * a Result-only plan would never be interesting to
115  * parallelize. However, if force_parallel_mode is on, then
116  * we want to execute the Result in a parallel worker if
117  * possible, so we must do this.
118  */
119  if (root->glob->parallelModeOK &&
121  final_rel->consider_parallel =
122  is_parallel_safe(root, parse->jointree->quals);
123 
124  /*
125  * The only path for it is a trivial Result path. We cheat a
126  * bit here by using a GroupResultPath, because that way we
127  * can just jam the quals into it without preprocessing them.
128  * (But, if you hold your head at the right angle, a FROM-less
129  * SELECT is a kind of degenerate-grouping case, so it's not
130  * that much of a cheat.)
131  */
132  add_path(final_rel, (Path *)
133  create_group_result_path(root, final_rel,
134  final_rel->reltarget,
135  (List *) parse->jointree->quals));
136 
137  /* Select cheapest path (pretty easy in this case...) */
138  set_cheapest(final_rel);
139 
140  /*
141  * We don't need to run generate_base_implied_equalities, but
142  * we do need to pretend that EC merging is complete.
143  */
144  root->ec_merging_done = true;
145 
146  /*
147  * We still are required to call qp_callback, in case it's
148  * something like "SELECT 2+2 ORDER BY 1".
149  */
150  (*qp_callback) (root, qp_extra);
151 
152  return final_rel;
153  }
154  }
155  }
156 
157  /*
158  * Construct RelOptInfo nodes for all base relations used in the query.
159  * Appendrel member relations ("other rels") will be added later.
160  *
161  * Note: the reason we find the baserels by searching the jointree, rather
162  * than scanning the rangetable, is that the rangetable may contain RTEs
163  * for rels not actively part of the query, for example views. We don't
164  * want to make RelOptInfos for them.
165  */
166  add_base_rels_to_query(root, (Node *) parse->jointree);
167 
168  /*
169  * Examine the targetlist and join tree, adding entries to baserel
170  * targetlists for all referenced Vars, and generating PlaceHolderInfo
171  * entries for all referenced PlaceHolderVars. Restrict and join clauses
172  * are added to appropriate lists belonging to the mentioned relations. We
173  * also build EquivalenceClasses for provably equivalent expressions. The
174  * SpecialJoinInfo list is also built to hold information about join order
175  * restrictions. Finally, we form a target joinlist for make_one_rel() to
176  * work from.
177  */
179 
181 
183 
184  joinlist = deconstruct_jointree(root);
185 
186  /*
187  * Reconsider any postponed outer-join quals now that we have built up
188  * equivalence classes. (This could result in further additions or
189  * mergings of classes.)
190  */
192 
193  /*
194  * If we formed any equivalence classes, generate additional restriction
195  * clauses as appropriate. (Implied join clauses are formed on-the-fly
196  * later.)
197  */
199 
200  /*
201  * We have completed merging equivalence sets, so it's now possible to
202  * generate pathkeys in canonical form; so compute query_pathkeys and
203  * other pathkeys fields in PlannerInfo.
204  */
205  (*qp_callback) (root, qp_extra);
206 
207  /*
208  * Examine any "placeholder" expressions generated during subquery pullup.
209  * Make sure that the Vars they need are marked as needed at the relevant
210  * join level. This must be done before join removal because it might
211  * cause Vars or placeholders to be needed above a join when they weren't
212  * so marked before.
213  */
215 
216  /*
217  * Remove any useless outer joins. Ideally this would be done during
218  * jointree preprocessing, but the necessary information isn't available
219  * until we've built baserel data structures and classified qual clauses.
220  */
221  joinlist = remove_useless_joins(root, joinlist);
222 
223  /*
224  * Also, reduce any semijoins with unique inner rels to plain inner joins.
225  * Likewise, this can't be done until now for lack of needed info.
226  */
228 
229  /*
230  * Now distribute "placeholders" to base rels as needed. This has to be
231  * done after join removal because removal could change whether a
232  * placeholder is evaluable at a base rel.
233  */
235 
236  /*
237  * Construct the lateral reference sets now that we have finalized
238  * PlaceHolderVar eval levels.
239  */
241 
242  /*
243  * Match foreign keys to equivalence classes and join quals. This must be
244  * done after finalizing equivalence classes, and it's useful to wait till
245  * after join removal so that we can skip processing foreign keys
246  * involving removed relations.
247  */
249 
250  /*
251  * Look for join OR clauses that we can extract single-relation
252  * restriction OR clauses from.
253  */
255 
256  /*
257  * Now expand appendrels by adding "otherrels" for their children. We
258  * delay this to the end so that we have as much information as possible
259  * available for each baserel, including all restriction clauses. That
260  * let us prune away partitions that don't satisfy a restriction clause.
261  * Also note that some information such as lateral_relids is propagated
262  * from baserels to otherrels here, so we must have computed it already.
263  */
265 
266  /*
267  * Ready to do the primary planning.
268  */
269  final_rel = make_one_rel(root, joinlist);
270 
271  /* Check that we got at least one usable path */
272  if (!final_rel || !final_rel->cheapest_total_path ||
273  final_rel->cheapest_total_path->param_info != NULL)
274  elog(ERROR, "failed to construct the join relation");
275 
276  return final_rel;
277 }
#define NIL
Definition: pg_list.h:65
int join_cur_level
Definition: pathnodes.h:255
RelOptInfo * make_one_rel(PlannerInfo *root, List *joinlist)
Definition: allpaths.c:152
#define IsA(nodeptr, _type_)
Definition: nodes.h:576
Query * parse
Definition: pathnodes.h:177
void add_path(RelOptInfo *parent_rel, Path *new_path)
Definition: pathnode.c:422
void reduce_unique_semijoins(PlannerInfo *root)
Definition: analyzejoins.c:508
bool ec_merging_done
Definition: pathnodes.h:266
void add_base_rels_to_query(PlannerInfo *root, Node *jtnode)
Definition: initsplan.c:105
List * join_info_list
Definition: pathnodes.h:281
FromExpr * jointree
Definition: parsenodes.h:138
void extract_restriction_or_clauses(PlannerInfo *root)
Definition: orclauses.c:76
List * deconstruct_jointree(PlannerInfo *root)
Definition: initsplan.c:686
ParamPathInfo * param_info
Definition: pathnodes.h:1117
Definition: nodes.h:525
List * join_rel_list
Definition: pathnodes.h:244
List * fromlist
Definition: primnodes.h:1496
List * fkey_list
Definition: pathnodes.h:294
void add_placeholders_to_base_rels(PlannerInfo *root)
Definition: placeholder.c:379
Node * quals
Definition: primnodes.h:1497
void add_other_rels_to_query(PlannerInfo *root)
Definition: initsplan.c:143
bool is_parallel_safe(PlannerInfo *root, Node *node)
Definition: clauses.c:854
#define linitial(l)
Definition: pg_list.h:195
#define ERROR
Definition: elog.h:43
bool parallelModeOK
Definition: pathnodes.h:141
struct Path * cheapest_total_path
Definition: pathnodes.h:659
PlannerGlobal * glob
Definition: pathnodes.h:179
List * left_join_clauses
Definition: pathnodes.h:270
List * full_join_clauses
Definition: pathnodes.h:278
RelOptInfo * build_simple_rel(PlannerInfo *root, int relid, RelOptInfo *parent)
Definition: relnode.c:185
List * canon_pathkeys
Definition: pathnodes.h:268
RangeTblEntry ** simple_rte_array
Definition: pathnodes.h:209
void fix_placeholder_input_needed_levels(PlannerInfo *root)
Definition: placeholder.c:350
void set_cheapest(RelOptInfo *parent_rel)
Definition: pathnode.c:244
void find_placeholders_in_jointree(PlannerInfo *root)
Definition: placeholder.c:144
void generate_base_implied_equalities(PlannerInfo *root)
Definition: equivclass.c:827
void reconsider_outer_join_clauses(PlannerInfo *root)
Definition: equivclass.c:1688
int force_parallel_mode
Definition: planner.c:70
#define Assert(condition)
Definition: c.h:739
List ** join_rel_level
Definition: pathnodes.h:254
void setup_simple_rel_arrays(PlannerInfo *root)
Definition: relnode.c:74
List * remove_useless_joins(PlannerInfo *root, List *joinlist)
Definition: analyzejoins.c:61
static int list_length(const List *l)
Definition: pg_list.h:169
struct HTAB * join_rel_hash
Definition: pathnodes.h:245
void build_base_rel_tlists(PlannerInfo *root, List *final_tlist)
Definition: initsplan.c:182
bool consider_parallel
Definition: pathnodes.h:649
RTEKind rtekind
Definition: parsenodes.h:974
void match_foreign_keys_to_quals(PlannerInfo *root)
Definition: initsplan.c:2411
#define elog(elevel,...)
Definition: elog.h:228
List * placeholder_list
Definition: pathnodes.h:292
GroupResultPath * create_group_result_path(PlannerInfo *root, RelOptInfo *rel, PathTarget *target, List *havingqual)
Definition: pathnode.c:1447
List * initial_rels
Definition: pathnodes.h:306
List * right_join_clauses
Definition: pathnodes.h:274
List * processed_tlist
Definition: pathnodes.h:323
Definition: pg_list.h:50
struct PathTarget * reltarget
Definition: pathnodes.h:652
void create_lateral_join_info(PlannerInfo *root)
Definition: initsplan.c:449
void find_lateral_references(PlannerInfo *root)
Definition: initsplan.c:303
static struct subre * parse(struct vars *, int, int, struct state *, struct state *)
Definition: regcomp.c:648

◆ query_supports_distinctness()

bool query_supports_distinctness ( Query query)

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

739 {
740  /* SRFs break distinctness except with DISTINCT, see below */
741  if (query->hasTargetSRFs && query->distinctClause == NIL)
742  return false;
743 
744  /* check for features we can prove distinctness with */
745  if (query->distinctClause != NIL ||
746  query->groupClause != NIL ||
747  query->groupingSets != NIL ||
748  query->hasAggs ||
749  query->havingQual ||
750  query->setOperations)
751  return true;
752 
753  return false;
754 }
#define NIL
Definition: pg_list.h:65
bool hasAggs
Definition: parsenodes.h:125
List * groupingSets
Definition: parsenodes.h:150
List * distinctClause
Definition: parsenodes.h:156
bool hasTargetSRFs
Definition: parsenodes.h:127
Node * setOperations
Definition: parsenodes.h:165
List * groupClause
Definition: parsenodes.h:148
Node * havingQual
Definition: parsenodes.h:152

◆ record_plan_function_dependency()

void record_plan_function_dependency ( PlannerInfo root,
Oid  funcid 
)

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

2678 {
2679  /*
2680  * For performance reasons, we don't bother to track built-in functions;
2681  * we just assume they'll never change (or at least not in ways that'd
2682  * invalidate plans using them). For this purpose we can consider a
2683  * built-in function to be one with OID less than FirstBootstrapObjectId.
2684  * Note that the OID generator guarantees never to generate such an OID
2685  * after startup, even at OID wraparound.
2686  */
2687  if (funcid >= (Oid) FirstBootstrapObjectId)
2688  {
2689  PlanInvalItem *inval_item = makeNode(PlanInvalItem);
2690 
2691  /*
2692  * It would work to use any syscache on pg_proc, but the easiest is
2693  * PROCOID since we already have the function's OID at hand. Note
2694  * that plancache.c knows we use PROCOID.
2695  */
2696  inval_item->cacheId = PROCOID;
2697  inval_item->hashValue = GetSysCacheHashValue1(PROCOID,
2698  ObjectIdGetDatum(funcid));
2699 
2700  root->glob->invalItems = lappend(root->glob->invalItems, inval_item);
2701  }
2702 }
#define GetSysCacheHashValue1(cacheId, key1)
Definition: syscache.h:201
unsigned int Oid
Definition: postgres_ext.h:31
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
PlannerGlobal * glob
Definition: pathnodes.h:179
#define FirstBootstrapObjectId
Definition: transam.h:140
List * lappend(List *list, void *datum)
Definition: list.c:322
List * invalItems
Definition: pathnodes.h:127
uint32 hashValue
Definition: plannodes.h:1228
#define makeNode(_type_)
Definition: nodes.h:573

◆ record_plan_type_dependency()

void record_plan_type_dependency ( PlannerInfo root,
Oid  typid 
)

Definition at line 2717 of file setrefs.c.

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

Referenced by eval_const_expressions_mutator().

2718 {
2719  /*
2720  * As in record_plan_function_dependency, ignore the possibility that
2721  * someone would change a built-in domain.
2722  */
2723  if (typid >= (Oid) FirstBootstrapObjectId)
2724  {
2725  PlanInvalItem *inval_item = makeNode(PlanInvalItem);
2726 
2727  /*
2728  * It would work to use any syscache on pg_type, but the easiest is
2729  * TYPEOID since we already have the type's OID at hand. Note that
2730  * plancache.c knows we use TYPEOID.
2731  */
2732  inval_item->cacheId = TYPEOID;
2733  inval_item->hashValue = GetSysCacheHashValue1(TYPEOID,
2734  ObjectIdGetDatum(typid));
2735 
2736  root->glob->invalItems = lappend(root->glob->invalItems, inval_item);
2737  }
2738 }
#define GetSysCacheHashValue1(cacheId, key1)
Definition: syscache.h:201
unsigned int Oid
Definition: postgres_ext.h:31
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
PlannerGlobal * glob
Definition: pathnodes.h:179
#define FirstBootstrapObjectId
Definition: transam.h:140
List * lappend(List *list, void *datum)
Definition: list.c:322
List * invalItems
Definition: pathnodes.h:127
uint32 hashValue
Definition: plannodes.h:1228
#define makeNode(_type_)
Definition: nodes.h:573

◆ reduce_unique_semijoins()

void reduce_unique_semijoins ( PlannerInfo root)

Definition at line 508 of file analyzejoins.c.

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

Referenced by query_planner().

509 {
510  ListCell *lc;
511 
512  /*
513  * Scan the join_info_list to find semijoins.
514  */
515  foreach(lc, root->join_info_list)
516  {
517  SpecialJoinInfo *sjinfo = (SpecialJoinInfo *) lfirst(lc);
518  int innerrelid;
519  RelOptInfo *innerrel;
520  Relids joinrelids;
521  List *restrictlist;
522 
523  /*
524  * Must be a non-delaying semijoin to a single baserel, else we aren't
525  * going to be able to do anything with it. (It's probably not
526  * possible for delay_upper_joins to be set on a semijoin, but we
527  * might as well check.)
528  */
529  if (sjinfo->jointype != JOIN_SEMI ||
530  sjinfo->delay_upper_joins)
531  continue;
532 
533  if (!bms_get_singleton_member(sjinfo->min_righthand, &innerrelid))
534  continue;
535 
536  innerrel = find_base_rel(root, innerrelid);
537 
538  /*
539  * Before we trouble to run generate_join_implied_equalities, make a
540  * quick check to eliminate cases in which we will surely be unable to
541  * prove uniqueness of the innerrel.
542  */
543  if (!rel_supports_distinctness(root, innerrel))
544  continue;
545 
546  /* Compute the relid set for the join we are considering */
547  joinrelids = bms_union(sjinfo->min_lefthand, sjinfo->min_righthand);
548 
549  /*
550  * Since we're only considering a single-rel RHS, any join clauses it
551  * has must be clauses linking it to the semijoin's min_lefthand. We
552  * can also consider EC-derived join clauses.
553  */
554  restrictlist =
556  joinrelids,
557  sjinfo->min_lefthand,
558  innerrel),
559  innerrel->joininfo);
560 
561  /* Test whether the innerrel is unique for those clauses. */
562  if (!innerrel_is_unique(root,
563  joinrelids, sjinfo->min_lefthand, innerrel,
564  JOIN_SEMI, restrictlist, true))
565  continue;
566 
567  /* OK, remove the SpecialJoinInfo from the list. */
569  }
570 }
List * join_info_list
Definition: pathnodes.h:281
Relids min_righthand
Definition: pathnodes.h:2134
List * list_concat(List *list1, const List *list2)
Definition: list.c:516
bool bms_get_singleton_member(const Bitmapset *a, int *member)
Definition: bitmapset.c:615
bool innerrel_is_unique(PlannerInfo *root, Relids joinrelids, Relids outerrelids, RelOptInfo *innerrel, JoinType jointype, List *restrictlist, bool force_cache)
Definition: analyzejoins.c:964
#define foreach_delete_current(lst, cell)
Definition: pg_list.h:368
List * generate_join_implied_equalities(PlannerInfo *root, Relids join_relids, Relids outer_relids, RelOptInfo *inner_rel)
Definition: equivclass.c:1126
List * joininfo
Definition: pathnodes.h:707
bool delay_upper_joins
Definition: pathnodes.h:2139
#define lfirst(lc)
Definition: pg_list.h:190
JoinType jointype
Definition: pathnodes.h:2137
Bitmapset * bms_union(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:225
RelOptInfo * find_base_rel(PlannerInfo *root, int relid)
Definition: relnode.c:363
static bool rel_supports_distinctness(PlannerInfo *root, RelOptInfo *rel)
Definition: analyzejoins.c:585
Definition: pg_list.h:50
Relids min_lefthand
Definition: pathnodes.h:2133

◆ remove_useless_joins()

List* remove_useless_joins ( PlannerInfo root,
List joinlist 
)

Definition at line 61 of file analyzejoins.c.

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

Referenced by query_planner().

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

◆ set_plan_references()

Plan* set_plan_references ( PlannerInfo root,
Plan plan 
)

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

222 {
223  PlannerGlobal *glob = root->glob;
224  int rtoffset = list_length(glob->finalrtable);
225  ListCell *lc;
226 
227  /*
228  * Add all the query's RTEs to the flattened rangetable. The live ones
229  * will have their rangetable indexes increased by rtoffset. (Additional
230  * RTEs, not referenced by the Plan tree, might get added after those.)
231  */
232  add_rtes_to_flat_rtable(root, false);
233 
234  /*
235  * Adjust RT indexes of PlanRowMarks and add to final rowmarks list
236  */
237  foreach(lc, root->rowMarks)
238  {
240  PlanRowMark *newrc;
241 
242  /* flat copy is enough since all fields are scalars */
243  newrc = (PlanRowMark *) palloc(sizeof(PlanRowMark));
244  memcpy(newrc, rc, sizeof(PlanRowMark));
245 
246  /* adjust indexes ... but *not* the rowmarkId */
247  newrc->rti += rtoffset;
248  newrc->prti += rtoffset;
249 
250  glob->finalrowmarks = lappend(glob->finalrowmarks, newrc);
251  }
252 
253  /* Now fix the Plan tree */
254  return set_plan_refs(root, plan, rtoffset);
255 }
List * rowMarks
Definition: pathnodes.h:290
Index prti
Definition: plannodes.h:1058
static Plan * set_plan_refs(PlannerInfo *root, Plan *plan, int rtoffset)
Definition: setrefs.c:446
#define lfirst_node(type, lc)
Definition: pg_list.h:193
PlannerGlobal * glob
Definition: pathnodes.h:179
List * lappend(List *list, void *datum)
Definition: list.c:322
static void add_rtes_to_flat_rtable(PlannerInfo *root, bool recursing)
Definition: setrefs.c:263
static int list_length(const List *l)
Definition: pg_list.h:169
List * finalrtable
Definition: pathnodes.h:117
void * palloc(Size size)
Definition: mcxt.c:949
List * finalrowmarks
Definition: pathnodes.h:119

Variable Documentation

◆ cursor_tuple_fraction

double cursor_tuple_fraction

Definition at line 69 of file planner.c.

Referenced by standard_planner().

◆ from_collapse_limit

int from_collapse_limit

Definition at line 38 of file initsplan.c.

Referenced by deconstruct_recurse().

◆ join_collapse_limit

int join_collapse_limit

Definition at line 39 of file initsplan.c.

Referenced by deconstruct_recurse().