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

Go to the source code of this file.

Functions

void transform_MERGE_to_join (Query *parse)
 
void replace_empty_jointree (Query *parse)
 
void pull_up_sublinks (PlannerInfo *root)
 
void preprocess_function_rtes (PlannerInfo *root)
 
void pull_up_subqueries (PlannerInfo *root)
 
void flatten_simple_union_all (PlannerInfo *root)
 
void reduce_outer_joins (PlannerInfo *root)
 
void remove_useless_result_rtes (PlannerInfo *root)
 
Relids get_relids_in_jointree (Node *jtnode, bool include_outer_joins, bool include_inner_joins)
 
Relids get_relids_for_join (Query *query, int joinrelid)
 
void preprocess_targetlist (PlannerInfo *root)
 
Listextract_update_targetlist_colnos (List *tlist)
 
PlanRowMarkget_plan_rowmark (List *rowmarks, Index rtindex)
 
void get_agg_clause_costs (PlannerInfo *root, AggSplit aggsplit, AggClauseCosts *costs)
 
void preprocess_aggrefs (PlannerInfo *root, Node *clause)
 
RelOptInfoplan_set_operations (PlannerInfo *root)
 
bool set_operation_ordered_results_useful (SetOperationStmt *setop)
 

Function Documentation

◆ extract_update_targetlist_colnos()

List* extract_update_targetlist_colnos ( List tlist)

Definition at line 345 of file preptlist.c.

346 {
347  List *update_colnos = NIL;
348  AttrNumber nextresno = 1;
349  ListCell *lc;
350 
351  foreach(lc, tlist)
352  {
353  TargetEntry *tle = (TargetEntry *) lfirst(lc);
354 
355  if (!tle->resjunk)
356  update_colnos = lappend_int(update_colnos, tle->resno);
357  tle->resno = nextresno++;
358  }
359  return update_colnos;
360 }
int16 AttrNumber
Definition: attnum.h:21
List * lappend_int(List *list, int datum)
Definition: list.c:357
#define lfirst(lc)
Definition: pg_list.h:172
#define NIL
Definition: pg_list.h:68
Definition: pg_list.h:54
AttrNumber resno
Definition: primnodes.h:2192

References lappend_int(), lfirst, NIL, and TargetEntry::resno.

Referenced by make_modifytable(), and preprocess_targetlist().

◆ flatten_simple_union_all()

void flatten_simple_union_all ( PlannerInfo root)

Definition at line 2815 of file prepjointree.c.

2816 {
2817  Query *parse = root->parse;
2818  SetOperationStmt *topop;
2819  Node *leftmostjtnode;
2820  int leftmostRTI;
2821  RangeTblEntry *leftmostRTE;
2822  int childRTI;
2823  RangeTblEntry *childRTE;
2824  RangeTblRef *rtr;
2825 
2826  /* Shouldn't be called unless query has setops */
2827  topop = castNode(SetOperationStmt, parse->setOperations);
2828  Assert(topop);
2829 
2830  /* Can't optimize away a recursive UNION */
2831  if (root->hasRecursion)
2832  return;
2833 
2834  /*
2835  * Recursively check the tree of set operations. If not all UNION ALL
2836  * with identical column types, punt.
2837  */
2838  if (!is_simple_union_all_recurse((Node *) topop, parse, topop->colTypes))
2839  return;
2840 
2841  /*
2842  * Locate the leftmost leaf query in the setops tree. The upper query's
2843  * Vars all refer to this RTE (see transformSetOperationStmt).
2844  */
2845  leftmostjtnode = topop->larg;
2846  while (leftmostjtnode && IsA(leftmostjtnode, SetOperationStmt))
2847  leftmostjtnode = ((SetOperationStmt *) leftmostjtnode)->larg;
2848  Assert(leftmostjtnode && IsA(leftmostjtnode, RangeTblRef));
2849  leftmostRTI = ((RangeTblRef *) leftmostjtnode)->rtindex;
2850  leftmostRTE = rt_fetch(leftmostRTI, parse->rtable);
2851  Assert(leftmostRTE->rtekind == RTE_SUBQUERY);
2852 
2853  /*
2854  * Make a copy of the leftmost RTE and add it to the rtable. This copy
2855  * will represent the leftmost leaf query in its capacity as a member of
2856  * the appendrel. The original will represent the appendrel as a whole.
2857  * (We must do things this way because the upper query's Vars have to be
2858  * seen as referring to the whole appendrel.)
2859  */
2860  childRTE = copyObject(leftmostRTE);
2861  parse->rtable = lappend(parse->rtable, childRTE);
2862  childRTI = list_length(parse->rtable);
2863 
2864  /* Modify the setops tree to reference the child copy */
2865  ((RangeTblRef *) leftmostjtnode)->rtindex = childRTI;
2866 
2867  /* Modify the formerly-leftmost RTE to mark it as an appendrel parent */
2868  leftmostRTE->inh = true;
2869 
2870  /*
2871  * Form a RangeTblRef for the appendrel, and insert it into FROM. The top
2872  * Query of a setops tree should have had an empty FromClause initially.
2873  */
2874  rtr = makeNode(RangeTblRef);
2875  rtr->rtindex = leftmostRTI;
2876  Assert(parse->jointree->fromlist == NIL);
2877  parse->jointree->fromlist = list_make1(rtr);
2878 
2879  /*
2880  * Now pretend the query has no setops. We must do this before trying to
2881  * do subquery pullup, because of Assert in pull_up_simple_subquery.
2882  */
2883  parse->setOperations = NULL;
2884 
2885  /*
2886  * Build AppendRelInfo information, and apply pull_up_subqueries to the
2887  * leaf queries of the UNION ALL. (We must do that now because they
2888  * weren't previously referenced by the jointree, and so were missed by
2889  * the main invocation of pull_up_subqueries.)
2890  */
2891  pull_up_union_leaf_queries((Node *) topop, root, leftmostRTI, parse, 0);
2892 }
#define Assert(condition)
Definition: c.h:837
List * lappend(List *list, void *datum)
Definition: list.c:339
#define IsA(nodeptr, _type_)
Definition: nodes.h:158
#define copyObject(obj)
Definition: nodes.h:224
#define makeNode(_type_)
Definition: nodes.h:155
#define castNode(_type_, nodeptr)
Definition: nodes.h:176
@ RTE_SUBQUERY
Definition: parsenodes.h:1018
#define rt_fetch(rangetable_index, rangetable)
Definition: parsetree.h:31
static int list_length(const List *l)
Definition: pg_list.h:152
#define list_make1(x1)
Definition: pg_list.h:212
static void pull_up_union_leaf_queries(Node *setOp, PlannerInfo *root, int parentRTindex, Query *setOpQuery, int childRToffset)
static bool is_simple_union_all_recurse(Node *setOp, Query *setOpQuery, List *colTypes)
tree ctl root
Definition: radixtree.h:1886
static struct subre * parse(struct vars *v, int stopper, int type, struct state *init, struct state *final)
Definition: regcomp.c:717
Definition: nodes.h:129
RTEKind rtekind
Definition: parsenodes.h:1047

References Assert, castNode, copyObject, RangeTblEntry::inh, is_simple_union_all_recurse(), IsA, lappend(), SetOperationStmt::larg, list_length(), list_make1, makeNode, NIL, parse(), pull_up_union_leaf_queries(), root, rt_fetch, RTE_SUBQUERY, RangeTblEntry::rtekind, and RangeTblRef::rtindex.

Referenced by subquery_planner().

◆ get_agg_clause_costs()

void get_agg_clause_costs ( PlannerInfo root,
AggSplit  aggsplit,
AggClauseCosts costs 
)

Definition at line 559 of file prepagg.c.

560 {
561  ListCell *lc;
562 
563  foreach(lc, root->aggtransinfos)
564  {
565  AggTransInfo *transinfo = lfirst_node(AggTransInfo, lc);
566 
567  /*
568  * Add the appropriate component function execution costs to
569  * appropriate totals.
570  */
571  if (DO_AGGSPLIT_COMBINE(aggsplit))
572  {
573  /* charge for combining previously aggregated states */
574  add_function_cost(root, transinfo->combinefn_oid, NULL,
575  &costs->transCost);
576  }
577  else
578  add_function_cost(root, transinfo->transfn_oid, NULL,
579  &costs->transCost);
580  if (DO_AGGSPLIT_DESERIALIZE(aggsplit) &&
581  OidIsValid(transinfo->deserialfn_oid))
582  add_function_cost(root, transinfo->deserialfn_oid, NULL,
583  &costs->transCost);
584  if (DO_AGGSPLIT_SERIALIZE(aggsplit) &&
585  OidIsValid(transinfo->serialfn_oid))
586  add_function_cost(root, transinfo->serialfn_oid, NULL,
587  &costs->finalCost);
588 
589  /*
590  * These costs are incurred only by the initial aggregate node, so we
591  * mustn't include them again at upper levels.
592  */
593  if (!DO_AGGSPLIT_COMBINE(aggsplit))
594  {
595  /* add the input expressions' cost to per-input-row costs */
596  QualCost argcosts;
597 
598  cost_qual_eval_node(&argcosts, (Node *) transinfo->args, root);
599  costs->transCost.startup += argcosts.startup;
600  costs->transCost.per_tuple += argcosts.per_tuple;
601 
602  /*
603  * Add any filter's cost to per-input-row costs.
604  *
605  * XXX Ideally we should reduce input expression costs according
606  * to filter selectivity, but it's not clear it's worth the
607  * trouble.
608  */
609  if (transinfo->aggfilter)
610  {
611  cost_qual_eval_node(&argcosts, (Node *) transinfo->aggfilter,
612  root);
613  costs->transCost.startup += argcosts.startup;
614  costs->transCost.per_tuple += argcosts.per_tuple;
615  }
616  }
617 
618  /*
619  * If the transition type is pass-by-value then it doesn't add
620  * anything to the required size of the hashtable. If it is
621  * pass-by-reference then we have to add the estimated size of the
622  * value itself, plus palloc overhead.
623  */
624  if (!transinfo->transtypeByVal)
625  {
626  int32 avgwidth;
627 
628  /* Use average width if aggregate definition gave one */
629  if (transinfo->aggtransspace > 0)
630  avgwidth = transinfo->aggtransspace;
631  else if (transinfo->transfn_oid == F_ARRAY_APPEND)
632  {
633  /*
634  * If the transition function is array_append(), it'll use an
635  * expanded array as transvalue, which will occupy at least
636  * ALLOCSET_SMALL_INITSIZE and possibly more. Use that as the
637  * estimate for lack of a better idea.
638  */
639  avgwidth = ALLOCSET_SMALL_INITSIZE;
640  }
641  else
642  {
643  avgwidth = get_typavgwidth(transinfo->aggtranstype, transinfo->aggtranstypmod);
644  }
645 
646  avgwidth = MAXALIGN(avgwidth);
647  costs->transitionSpace += avgwidth + 2 * sizeof(void *);
648  }
649  else if (transinfo->aggtranstype == INTERNALOID)
650  {
651  /*
652  * INTERNAL transition type is a special case: although INTERNAL
653  * is pass-by-value, it's almost certainly being used as a pointer
654  * to some large data structure. The aggregate definition can
655  * provide an estimate of the size. If it doesn't, then we assume
656  * ALLOCSET_DEFAULT_INITSIZE, which is a good guess if the data is
657  * being kept in a private memory context, as is done by
658  * array_agg() for instance.
659  */
660  if (transinfo->aggtransspace > 0)
661  costs->transitionSpace += transinfo->aggtransspace;
662  else
664  }
665  }
666 
667  foreach(lc, root->agginfos)
668  {
669  AggInfo *agginfo = lfirst_node(AggInfo, lc);
670  Aggref *aggref = linitial_node(Aggref, agginfo->aggrefs);
671 
672  /*
673  * Add the appropriate component function execution costs to
674  * appropriate totals.
675  */
676  if (!DO_AGGSPLIT_SKIPFINAL(aggsplit) &&
677  OidIsValid(agginfo->finalfn_oid))
678  add_function_cost(root, agginfo->finalfn_oid, NULL,
679  &costs->finalCost);
680 
681  /*
682  * If there are direct arguments, treat their evaluation cost like the
683  * cost of the finalfn.
684  */
685  if (aggref->aggdirectargs)
686  {
687  QualCost argcosts;
688 
689  cost_qual_eval_node(&argcosts, (Node *) aggref->aggdirectargs,
690  root);
691  costs->finalCost.startup += argcosts.startup;
692  costs->finalCost.per_tuple += argcosts.per_tuple;
693  }
694  }
695 }
#define MAXALIGN(LEN)
Definition: c.h:790
signed int int32
Definition: c.h:482
#define OidIsValid(objectId)
Definition: c.h:754
void cost_qual_eval_node(QualCost *cost, Node *qual, PlannerInfo *root)
Definition: costsize.c:4758
int32 get_typavgwidth(Oid typid, int32 typmod)
Definition: lsyscache.c:2578
#define ALLOCSET_SMALL_INITSIZE
Definition: memutils.h:168
#define ALLOCSET_DEFAULT_INITSIZE
Definition: memutils.h:158
#define DO_AGGSPLIT_SKIPFINAL(as)
Definition: nodes.h:386
#define DO_AGGSPLIT_DESERIALIZE(as)
Definition: nodes.h:388
#define DO_AGGSPLIT_COMBINE(as)
Definition: nodes.h:385
#define DO_AGGSPLIT_SERIALIZE(as)
Definition: nodes.h:387
#define lfirst_node(type, lc)
Definition: pg_list.h:176
#define linitial_node(type, l)
Definition: pg_list.h:181
void add_function_cost(PlannerInfo *root, Oid funcid, Node *node, QualCost *cost)
Definition: plancat.c:2097
QualCost finalCost
Definition: pathnodes.h:61
Size transitionSpace
Definition: pathnodes.h:62
QualCost transCost
Definition: pathnodes.h:60
List * aggrefs
Definition: pathnodes.h:3386
Oid finalfn_oid
Definition: pathnodes.h:3398
List * args
Definition: pathnodes.h:3415
int32 aggtransspace
Definition: pathnodes.h:3439
bool transtypeByVal
Definition: pathnodes.h:3436
Oid combinefn_oid
Definition: pathnodes.h:3428
Oid deserialfn_oid
Definition: pathnodes.h:3425
int32 aggtranstypmod
Definition: pathnodes.h:3434
Oid serialfn_oid
Definition: pathnodes.h:3422
Oid aggtranstype
Definition: pathnodes.h:3431
Expr * aggfilter
Definition: pathnodes.h:3416
List * aggdirectargs
Definition: primnodes.h:465
Cost per_tuple
Definition: pathnodes.h:48
Cost startup
Definition: pathnodes.h:47

References add_function_cost(), Aggref::aggdirectargs, AggTransInfo::aggfilter, AggInfo::aggrefs, AggTransInfo::aggtransspace, AggTransInfo::aggtranstype, AggTransInfo::aggtranstypmod, ALLOCSET_DEFAULT_INITSIZE, ALLOCSET_SMALL_INITSIZE, AggTransInfo::args, AggTransInfo::combinefn_oid, cost_qual_eval_node(), AggTransInfo::deserialfn_oid, DO_AGGSPLIT_COMBINE, DO_AGGSPLIT_DESERIALIZE, DO_AGGSPLIT_SERIALIZE, DO_AGGSPLIT_SKIPFINAL, AggClauseCosts::finalCost, AggInfo::finalfn_oid, get_typavgwidth(), lfirst_node, linitial_node, MAXALIGN, OidIsValid, QualCost::per_tuple, root, AggTransInfo::serialfn_oid, QualCost::startup, AggClauseCosts::transCost, AggTransInfo::transfn_oid, AggClauseCosts::transitionSpace, and AggTransInfo::transtypeByVal.

Referenced by create_grouping_paths(), create_partial_grouping_paths(), and estimate_path_cost_size().

◆ get_plan_rowmark()

PlanRowMark* get_plan_rowmark ( List rowmarks,
Index  rtindex 
)

Definition at line 509 of file preptlist.c.

510 {
511  ListCell *l;
512 
513  foreach(l, rowmarks)
514  {
515  PlanRowMark *rc = (PlanRowMark *) lfirst(l);
516 
517  if (rc->rti == rtindex)
518  return rc;
519  }
520  return NULL;
521 }

References lfirst, and PlanRowMark::rti.

Referenced by check_index_predicates(), deparseLockingClause(), and expand_inherited_rtentry().

◆ get_relids_for_join()

Relids get_relids_for_join ( Query query,
int  joinrelid 
)

Definition at line 4135 of file prepjointree.c.

4136 {
4137  Node *jtnode;
4138 
4139  jtnode = find_jointree_node_for_rel((Node *) query->jointree,
4140  joinrelid);
4141  if (!jtnode)
4142  elog(ERROR, "could not find join node %d", joinrelid);
4143  return get_relids_in_jointree(jtnode, true, false);
4144 }
#define ERROR
Definition: elog.h:39
#define elog(elevel,...)
Definition: elog.h:225
static Node * find_jointree_node_for_rel(Node *jtnode, int relid)
Relids get_relids_in_jointree(Node *jtnode, bool include_outer_joins, bool include_inner_joins)
FromExpr * jointree
Definition: parsenodes.h:177

References elog, ERROR, find_jointree_node_for_rel(), get_relids_in_jointree(), and Query::jointree.

Referenced by add_nullingrels_if_needed(), and alias_relid_set().

◆ get_relids_in_jointree()

Relids get_relids_in_jointree ( Node jtnode,
bool  include_outer_joins,
bool  include_inner_joins 
)

Definition at line 4074 of file prepjointree.c.

4076 {
4077  Relids result = NULL;
4078 
4079  if (jtnode == NULL)
4080  return result;
4081  if (IsA(jtnode, RangeTblRef))
4082  {
4083  int varno = ((RangeTblRef *) jtnode)->rtindex;
4084 
4085  result = bms_make_singleton(varno);
4086  }
4087  else if (IsA(jtnode, FromExpr))
4088  {
4089  FromExpr *f = (FromExpr *) jtnode;
4090  ListCell *l;
4091 
4092  foreach(l, f->fromlist)
4093  {
4094  result = bms_join(result,
4096  include_outer_joins,
4097  include_inner_joins));
4098  }
4099  }
4100  else if (IsA(jtnode, JoinExpr))
4101  {
4102  JoinExpr *j = (JoinExpr *) jtnode;
4103 
4104  result = get_relids_in_jointree(j->larg,
4105  include_outer_joins,
4106  include_inner_joins);
4107  result = bms_join(result,
4108  get_relids_in_jointree(j->rarg,
4109  include_outer_joins,
4110  include_inner_joins));
4111  if (j->rtindex)
4112  {
4113  if (j->jointype == JOIN_INNER)
4114  {
4115  if (include_inner_joins)
4116  result = bms_add_member(result, j->rtindex);
4117  }
4118  else
4119  {
4120  if (include_outer_joins)
4121  result = bms_add_member(result, j->rtindex);
4122  }
4123  }
4124  }
4125  else
4126  elog(ERROR, "unrecognized node type: %d",
4127  (int) nodeTag(jtnode));
4128  return result;
4129 }
Bitmapset * bms_join(Bitmapset *a, Bitmapset *b)
Definition: bitmapset.c:1230
Bitmapset * bms_make_singleton(int x)
Definition: bitmapset.c:216
Bitmapset * bms_add_member(Bitmapset *a, int x)
Definition: bitmapset.c:815
int j
Definition: isn.c:73
#define nodeTag(nodeptr)
Definition: nodes.h:133
@ JOIN_INNER
Definition: nodes.h:293
List * fromlist
Definition: primnodes.h:2308

References bms_add_member(), bms_join(), bms_make_singleton(), elog, ERROR, FromExpr::fromlist, IsA, j, JOIN_INNER, lfirst, and nodeTag.

Referenced by find_dependent_phvs_in_jointree(), get_relids_for_join(), is_simple_subquery(), mark_nullable_by_grouping(), preprocess_rowmarks(), pull_up_simple_subquery(), and remove_result_refs().

◆ plan_set_operations()

RelOptInfo* plan_set_operations ( PlannerInfo root)

Definition at line 99 of file prepunion.c.

100 {
101  Query *parse = root->parse;
102  SetOperationStmt *topop = castNode(SetOperationStmt, parse->setOperations);
103  Node *node;
104  RangeTblEntry *leftmostRTE;
105  Query *leftmostQuery;
106  RelOptInfo *setop_rel;
107  List *top_tlist;
108 
109  Assert(topop);
110 
111  /* check for unsupported stuff */
112  Assert(parse->jointree->fromlist == NIL);
113  Assert(parse->jointree->quals == NULL);
114  Assert(parse->groupClause == NIL);
115  Assert(parse->havingQual == NULL);
116  Assert(parse->windowClause == NIL);
117  Assert(parse->distinctClause == NIL);
118 
119  /*
120  * In the outer query level, equivalence classes are limited to classes
121  * which define that the top-level target entry is equivalent to the
122  * corresponding child target entry. There won't be any equivalence class
123  * merging. Mark that merging is complete to allow us to make pathkeys.
124  */
125  Assert(root->eq_classes == NIL);
126  root->ec_merging_done = true;
127 
128  /*
129  * We'll need to build RelOptInfos for each of the leaf subqueries, which
130  * are RTE_SUBQUERY rangetable entries in this Query. Prepare the index
131  * arrays for those, and for AppendRelInfos in case they're needed.
132  */
134 
135  /*
136  * Find the leftmost component Query. We need to use its column names for
137  * all generated tlists (else SELECT INTO won't work right).
138  */
139  node = topop->larg;
140  while (node && IsA(node, SetOperationStmt))
141  node = ((SetOperationStmt *) node)->larg;
142  Assert(node && IsA(node, RangeTblRef));
143  leftmostRTE = root->simple_rte_array[((RangeTblRef *) node)->rtindex];
144  leftmostQuery = leftmostRTE->subquery;
145  Assert(leftmostQuery != NULL);
146 
147  /*
148  * If the topmost node is a recursive union, it needs special processing.
149  */
150  if (root->hasRecursion)
151  {
152  setop_rel = generate_recursion_path(topop, root,
153  leftmostQuery->targetList,
154  &top_tlist);
155  }
156  else
157  {
158  bool trivial_tlist;
159 
160  /*
161  * Recurse on setOperations tree to generate paths for set ops. The
162  * final output paths should have just the column types shown as the
163  * output from the top-level node, plus possibly resjunk working
164  * columns (we can rely on upper-level nodes to deal with that).
165  */
166  setop_rel = recurse_set_operations((Node *) topop, root,
167  topop->colTypes, topop->colCollations,
168  true, -1,
169  leftmostQuery->targetList,
170  &top_tlist,
171  &trivial_tlist);
172  }
173 
174  /* Must return the built tlist into root->processed_tlist. */
175  root->processed_tlist = top_tlist;
176 
177  return setop_rel;
178 }
static RelOptInfo * recurse_set_operations(Node *setOp, PlannerInfo *root, List *colTypes, List *colCollations, bool junkOK, int flag, List *refnames_tlist, List **pTargetList, bool *istrivial_tlist)
Definition: prepunion.c:230
static RelOptInfo * generate_recursion_path(SetOperationStmt *setOp, PlannerInfo *root, List *refnames_tlist, List **pTargetList)
Definition: prepunion.c:384
void setup_simple_rel_arrays(PlannerInfo *root)
Definition: relnode.c:94
List * targetList
Definition: parsenodes.h:193
Query * subquery
Definition: parsenodes.h:1104

References Assert, castNode, generate_recursion_path(), IsA, SetOperationStmt::larg, NIL, parse(), recurse_set_operations(), root, setup_simple_rel_arrays(), RangeTblEntry::subquery, and Query::targetList.

Referenced by grouping_planner().

◆ preprocess_aggrefs()

void preprocess_aggrefs ( PlannerInfo root,
Node clause 
)

Definition at line 110 of file prepagg.c.

111 {
112  (void) preprocess_aggrefs_walker(clause, root);
113 }
static bool preprocess_aggrefs_walker(Node *node, PlannerInfo *root)
Definition: prepagg.c:344

References preprocess_aggrefs_walker(), and root.

Referenced by grouping_planner().

◆ preprocess_function_rtes()

void preprocess_function_rtes ( PlannerInfo root)

Definition at line 887 of file prepjointree.c.

888 {
889  ListCell *rt;
890 
891  foreach(rt, root->parse->rtable)
892  {
893  RangeTblEntry *rte = (RangeTblEntry *) lfirst(rt);
894 
895  if (rte->rtekind == RTE_FUNCTION)
896  {
897  Query *funcquery;
898 
899  /* Apply const-simplification */
900  rte->functions = (List *)
902 
903  /* Check safety of expansion, and expand if possible */
904  funcquery = inline_set_returning_function(root, rte);
905  if (funcquery)
906  {
907  /* Successful expansion, convert the RTE to a subquery */
908  rte->rtekind = RTE_SUBQUERY;
909  rte->subquery = funcquery;
910  rte->security_barrier = false;
911  /* Clear fields that should not be set in a subquery RTE */
912  rte->functions = NIL;
913  rte->funcordinality = false;
914  }
915  }
916  }
917 }
Query * inline_set_returning_function(PlannerInfo *root, RangeTblEntry *rte)
Definition: clauses.c:5063
Node * eval_const_expressions(PlannerInfo *root, Node *node)
Definition: clauses.c:2253
@ RTE_FUNCTION
Definition: parsenodes.h:1020
bool funcordinality
Definition: parsenodes.h:1179
List * functions
Definition: parsenodes.h:1177

References eval_const_expressions(), RangeTblEntry::funcordinality, RangeTblEntry::functions, inline_set_returning_function(), lfirst, NIL, root, RTE_FUNCTION, RTE_SUBQUERY, RangeTblEntry::rtekind, and RangeTblEntry::subquery.

Referenced by pull_up_simple_subquery(), and subquery_planner().

◆ preprocess_targetlist()

void preprocess_targetlist ( PlannerInfo root)

Definition at line 62 of file preptlist.c.

63 {
64  Query *parse = root->parse;
65  int result_relation = parse->resultRelation;
66  List *range_table = parse->rtable;
67  CmdType command_type = parse->commandType;
68  RangeTblEntry *target_rte = NULL;
69  Relation target_relation = NULL;
70  List *tlist;
71  ListCell *lc;
72 
73  /*
74  * If there is a result relation, open it so we can look for missing
75  * columns and so on. We assume that previous code already acquired at
76  * least AccessShareLock on the relation, so we need no lock here.
77  */
78  if (result_relation)
79  {
80  target_rte = rt_fetch(result_relation, range_table);
81 
82  /*
83  * Sanity check: it'd better be a real relation not, say, a subquery.
84  * Else parser or rewriter messed up.
85  */
86  if (target_rte->rtekind != RTE_RELATION)
87  elog(ERROR, "result relation must be a regular relation");
88 
89  target_relation = table_open(target_rte->relid, NoLock);
90  }
91  else
92  Assert(command_type == CMD_SELECT);
93 
94  /*
95  * In an INSERT, the executor expects the targetlist to match the exact
96  * order of the target table's attributes, including entries for
97  * attributes not mentioned in the source query.
98  *
99  * In an UPDATE, we don't rearrange the tlist order, but we need to make a
100  * separate list of the target attribute numbers, in tlist order, and then
101  * renumber the processed_tlist entries to be consecutive.
102  */
103  tlist = parse->targetList;
104  if (command_type == CMD_INSERT)
105  tlist = expand_insert_targetlist(tlist, target_relation);
106  else if (command_type == CMD_UPDATE)
107  root->update_colnos = extract_update_targetlist_colnos(tlist);
108 
109  /*
110  * For non-inherited UPDATE/DELETE/MERGE, register any junk column(s)
111  * needed to allow the executor to identify the rows to be updated or
112  * deleted. In the inheritance case, we do nothing now, leaving this to
113  * be dealt with when expand_inherited_rtentry() makes the leaf target
114  * relations. (But there might not be any leaf target relations, in which
115  * case we must do this in distribute_row_identity_vars().)
116  */
117  if ((command_type == CMD_UPDATE || command_type == CMD_DELETE ||
118  command_type == CMD_MERGE) &&
119  !target_rte->inh)
120  {
121  /* row-identity logic expects to add stuff to processed_tlist */
122  root->processed_tlist = tlist;
123  add_row_identity_columns(root, result_relation,
124  target_rte, target_relation);
125  tlist = root->processed_tlist;
126  }
127 
128  /*
129  * For MERGE we also need to handle the target list for each INSERT and
130  * UPDATE action separately. In addition, we examine the qual of each
131  * action and add any Vars there (other than those of the target rel) to
132  * the subplan targetlist.
133  */
134  if (command_type == CMD_MERGE)
135  {
136  ListCell *l;
137  List *vars;
138 
139  /*
140  * For MERGE, handle targetlist of each MergeAction separately. Give
141  * the same treatment to MergeAction->targetList as we would have
142  * given to a regular INSERT. For UPDATE, collect the column numbers
143  * being modified.
144  */
145  foreach(l, parse->mergeActionList)
146  {
148  ListCell *l2;
149 
150  if (action->commandType == CMD_INSERT)
151  action->targetList = expand_insert_targetlist(action->targetList,
152  target_relation);
153  else if (action->commandType == CMD_UPDATE)
154  action->updateColnos =
156 
157  /*
158  * Add resjunk entries for any Vars and PlaceHolderVars used in
159  * each action's targetlist and WHEN condition that belong to
160  * relations other than the target. We don't expect to see any
161  * aggregates or window functions here.
162  */
164  list_concat_copy((List *) action->qual,
165  action->targetList),
167  foreach(l2, vars)
168  {
169  Var *var = (Var *) lfirst(l2);
170  TargetEntry *tle;
171 
172  if (IsA(var, Var) && var->varno == result_relation)
173  continue; /* don't need it */
174 
175  if (tlist_member((Expr *) var, tlist))
176  continue; /* already got it */
177 
178  tle = makeTargetEntry((Expr *) var,
179  list_length(tlist) + 1,
180  NULL, true);
181  tlist = lappend(tlist, tle);
182  }
183  list_free(vars);
184  }
185 
186  /*
187  * Add resjunk entries for any Vars and PlaceHolderVars used in the
188  * join condition that belong to relations other than the target. We
189  * don't expect to see any aggregates or window functions here.
190  */
191  vars = pull_var_clause(parse->mergeJoinCondition,
193  foreach(l, vars)
194  {
195  Var *var = (Var *) lfirst(l);
196  TargetEntry *tle;
197 
198  if (IsA(var, Var) && var->varno == result_relation)
199  continue; /* don't need it */
200 
201  if (tlist_member((Expr *) var, tlist))
202  continue; /* already got it */
203 
204  tle = makeTargetEntry((Expr *) var,
205  list_length(tlist) + 1,
206  NULL, true);
207  tlist = lappend(tlist, tle);
208  }
209  }
210 
211  /*
212  * Add necessary junk columns for rowmarked rels. These values are needed
213  * for locking of rels selected FOR UPDATE/SHARE, and to do EvalPlanQual
214  * rechecking. See comments for PlanRowMark in plannodes.h. If you
215  * change this stanza, see also expand_inherited_rtentry(), which has to
216  * be able to add on junk columns equivalent to these.
217  *
218  * (Someday it might be useful to fold these resjunk columns into the
219  * row-identity-column management used for UPDATE/DELETE. Today is not
220  * that day, however. One notable issue is that it seems important that
221  * the whole-row Vars made here use the real table rowtype, not RECORD, so
222  * that conversion to/from child relations' rowtypes will happen. Also,
223  * since these entries don't potentially bloat with more and more child
224  * relations, there's not really much need for column sharing.)
225  */
226  foreach(lc, root->rowMarks)
227  {
228  PlanRowMark *rc = (PlanRowMark *) lfirst(lc);
229  Var *var;
230  char resname[32];
231  TargetEntry *tle;
232 
233  /* child rels use the same junk attrs as their parents */
234  if (rc->rti != rc->prti)
235  continue;
236 
237  if (rc->allMarkTypes & ~(1 << ROW_MARK_COPY))
238  {
239  /* Need to fetch TID */
240  var = makeVar(rc->rti,
242  TIDOID,
243  -1,
244  InvalidOid,
245  0);
246  snprintf(resname, sizeof(resname), "ctid%u", rc->rowmarkId);
247  tle = makeTargetEntry((Expr *) var,
248  list_length(tlist) + 1,
249  pstrdup(resname),
250  true);
251  tlist = lappend(tlist, tle);
252  }
253  if (rc->allMarkTypes & (1 << ROW_MARK_COPY))
254  {
255  /* Need the whole row as a junk var */
256  var = makeWholeRowVar(rt_fetch(rc->rti, range_table),
257  rc->rti,
258  0,
259  false);
260  snprintf(resname, sizeof(resname), "wholerow%u", rc->rowmarkId);
261  tle = makeTargetEntry((Expr *) var,
262  list_length(tlist) + 1,
263  pstrdup(resname),
264  true);
265  tlist = lappend(tlist, tle);
266  }
267 
268  /* If parent of inheritance tree, always fetch the tableoid too. */
269  if (rc->isParent)
270  {
271  var = makeVar(rc->rti,
273  OIDOID,
274  -1,
275  InvalidOid,
276  0);
277  snprintf(resname, sizeof(resname), "tableoid%u", rc->rowmarkId);
278  tle = makeTargetEntry((Expr *) var,
279  list_length(tlist) + 1,
280  pstrdup(resname),
281  true);
282  tlist = lappend(tlist, tle);
283  }
284  }
285 
286  /*
287  * If the query has a RETURNING list, add resjunk entries for any Vars
288  * used in RETURNING that belong to other relations. We need to do this
289  * to make these Vars available for the RETURNING calculation. Vars that
290  * belong to the result rel don't need to be added, because they will be
291  * made to refer to the actual heap tuple.
292  */
293  if (parse->returningList && list_length(parse->rtable) > 1)
294  {
295  List *vars;
296  ListCell *l;
297 
298  vars = pull_var_clause((Node *) parse->returningList,
302  foreach(l, vars)
303  {
304  Var *var = (Var *) lfirst(l);
305  TargetEntry *tle;
306 
307  if (IsA(var, Var) &&
308  var->varno == result_relation)
309  continue; /* don't need it */
310 
311  if (tlist_member((Expr *) var, tlist))
312  continue; /* already got it */
313 
314  tle = makeTargetEntry((Expr *) var,
315  list_length(tlist) + 1,
316  NULL,
317  true);
318 
319  tlist = lappend(tlist, tle);
320  }
321  list_free(vars);
322  }
323 
324  root->processed_tlist = tlist;
325 
326  if (target_relation)
327  table_close(target_relation, NoLock);
328 }
void add_row_identity_columns(PlannerInfo *root, Index rtindex, RangeTblEntry *target_rte, Relation target_relation)
Definition: appendinfo.c:887
void list_free(List *list)
Definition: list.c:1546
List * list_concat_copy(const List *list1, const List *list2)
Definition: list.c:598
#define NoLock
Definition: lockdefs.h:34
Var * makeWholeRowVar(RangeTblEntry *rte, int varno, Index varlevelsup, bool allowScalar)
Definition: makefuncs.c:135
TargetEntry * makeTargetEntry(Expr *expr, AttrNumber resno, char *resname, bool resjunk)
Definition: makefuncs.c:240
Var * makeVar(int varno, AttrNumber varattno, Oid vartype, int32 vartypmod, Oid varcollid, Index varlevelsup)
Definition: makefuncs.c:66
char * pstrdup(const char *in)
Definition: mcxt.c:1696
CmdType
Definition: nodes.h:263
@ CMD_MERGE
Definition: nodes.h:269
@ CMD_INSERT
Definition: nodes.h:267
@ CMD_DELETE
Definition: nodes.h:268
@ CMD_UPDATE
Definition: nodes.h:266
@ CMD_SELECT
Definition: nodes.h:265
#define PVC_RECURSE_AGGREGATES
Definition: optimizer.h:188
#define PVC_RECURSE_WINDOWFUNCS
Definition: optimizer.h:190
#define PVC_INCLUDE_PLACEHOLDERS
Definition: optimizer.h:191
@ RTE_RELATION
Definition: parsenodes.h:1017
@ ROW_MARK_COPY
Definition: plannodes.h:1335
#define snprintf
Definition: port.h:238
#define InvalidOid
Definition: postgres_ext.h:36
static List * expand_insert_targetlist(List *tlist, Relation rel)
Definition: preptlist.c:379
List * extract_update_targetlist_colnos(List *tlist)
Definition: preptlist.c:345
Index prti
Definition: plannodes.h:1384
bool isParent
Definition: plannodes.h:1390
Index rowmarkId
Definition: plannodes.h:1385
int allMarkTypes
Definition: plannodes.h:1387
Definition: primnodes.h:248
int varno
Definition: primnodes.h:255
Definition: regcomp.c:282
#define TableOidAttributeNumber
Definition: sysattr.h:26
#define SelfItemPointerAttributeNumber
Definition: sysattr.h:21
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:126
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:40
TargetEntry * tlist_member(Expr *node, List *targetlist)
Definition: tlist.c:79
List * pull_var_clause(Node *node, int flags)
Definition: var.c:609

References generate_unaccent_rules::action, add_row_identity_columns(), PlanRowMark::allMarkTypes, Assert, CMD_DELETE, CMD_INSERT, CMD_MERGE, CMD_SELECT, CMD_UPDATE, elog, ERROR, expand_insert_targetlist(), extract_update_targetlist_colnos(), RangeTblEntry::inh, InvalidOid, IsA, PlanRowMark::isParent, lappend(), lfirst, list_concat_copy(), list_free(), list_length(), makeTargetEntry(), makeVar(), makeWholeRowVar(), NoLock, parse(), PlanRowMark::prti, pstrdup(), pull_var_clause(), PVC_INCLUDE_PLACEHOLDERS, PVC_RECURSE_AGGREGATES, PVC_RECURSE_WINDOWFUNCS, RangeTblEntry::relid, root, ROW_MARK_COPY, PlanRowMark::rowmarkId, rt_fetch, RTE_RELATION, RangeTblEntry::rtekind, PlanRowMark::rti, SelfItemPointerAttributeNumber, snprintf, table_close(), table_open(), TableOidAttributeNumber, tlist_member(), and Var::varno.

Referenced by grouping_planner().

◆ pull_up_sublinks()

void pull_up_sublinks ( PlannerInfo root)

Definition at line 453 of file prepjointree.c.

454 {
455  Node *jtnode;
456  Relids relids;
457 
458  /* Begin recursion through the jointree */
460  (Node *) root->parse->jointree,
461  &relids);
462 
463  /*
464  * root->parse->jointree must always be a FromExpr, so insert a dummy one
465  * if we got a bare RangeTblRef or JoinExpr out of the recursion.
466  */
467  if (IsA(jtnode, FromExpr))
468  root->parse->jointree = (FromExpr *) jtnode;
469  else
470  root->parse->jointree = makeFromExpr(list_make1(jtnode), NULL);
471 }
FromExpr * makeFromExpr(List *fromlist, Node *quals)
Definition: makefuncs.c:287
static Node * pull_up_sublinks_jointree_recurse(PlannerInfo *root, Node *jtnode, Relids *relids)
Definition: prepjointree.c:480

References IsA, list_make1, makeFromExpr(), pull_up_sublinks_jointree_recurse(), and root.

Referenced by pull_up_simple_subquery(), and subquery_planner().

◆ pull_up_subqueries()

void pull_up_subqueries ( PlannerInfo root)

Definition at line 928 of file prepjointree.c.

929 {
930  /* Top level of jointree must always be a FromExpr */
931  Assert(IsA(root->parse->jointree, FromExpr));
932  /* Recursion starts with no containing join nor appendrel */
933  root->parse->jointree = (FromExpr *)
934  pull_up_subqueries_recurse(root, (Node *) root->parse->jointree,
935  NULL, NULL);
936  /* We should still have a FromExpr */
937  Assert(IsA(root->parse->jointree, FromExpr));
938 }
static Node * pull_up_subqueries_recurse(PlannerInfo *root, Node *jtnode, JoinExpr *lowest_outer_join, AppendRelInfo *containing_appendrel)
Definition: prepjointree.c:972

References Assert, IsA, pull_up_subqueries_recurse(), and root.

Referenced by pull_up_simple_subquery(), and subquery_planner().

◆ reduce_outer_joins()

void reduce_outer_joins ( PlannerInfo root)

Definition at line 2934 of file prepjointree.c.

2935 {
2938  ListCell *lc;
2939 
2940  /*
2941  * To avoid doing strictness checks on more quals than necessary, we want
2942  * to stop descending the jointree as soon as there are no outer joins
2943  * below our current point. This consideration forces a two-pass process.
2944  * The first pass gathers information about which base rels appear below
2945  * each side of each join clause, and about whether there are outer
2946  * join(s) below each side of each join clause. The second pass examines
2947  * qual clauses and changes join types as it descends the tree.
2948  */
2949  state1 = reduce_outer_joins_pass1((Node *) root->parse->jointree);
2950 
2951  /* planner.c shouldn't have called me if no outer joins */
2952  if (state1 == NULL || !state1->contains_outer)
2953  elog(ERROR, "so where are the outer joins?");
2954 
2955  state2.inner_reduced = NULL;
2956  state2.partial_reduced = NIL;
2957 
2958  reduce_outer_joins_pass2((Node *) root->parse->jointree,
2959  state1, &state2,
2960  root, NULL, NIL);
2961 
2962  /*
2963  * If we successfully reduced the strength of any outer joins, we must
2964  * remove references to those joins as nulling rels. This is handled as
2965  * an additional pass, for simplicity and because we can handle all
2966  * fully-reduced joins in a single pass over the parse tree.
2967  */
2968  if (!bms_is_empty(state2.inner_reduced))
2969  {
2970  root->parse = (Query *)
2971  remove_nulling_relids((Node *) root->parse,
2972  state2.inner_reduced,
2973  NULL);
2974  /* There could be references in the append_rel_list, too */
2975  root->append_rel_list = (List *)
2976  remove_nulling_relids((Node *) root->append_rel_list,
2977  state2.inner_reduced,
2978  NULL);
2979  }
2980 
2981  /*
2982  * Partially-reduced full joins have to be done one at a time, since
2983  * they'll each need a different setting of except_relids.
2984  */
2985  foreach(lc, state2.partial_reduced)
2986  {
2988  Relids full_join_relids = bms_make_singleton(statep->full_join_rti);
2989 
2990  root->parse = (Query *)
2991  remove_nulling_relids((Node *) root->parse,
2992  full_join_relids,
2993  statep->unreduced_side);
2994  root->append_rel_list = (List *)
2995  remove_nulling_relids((Node *) root->append_rel_list,
2996  full_join_relids,
2997  statep->unreduced_side);
2998  }
2999 }
#define bms_is_empty(a)
Definition: bitmapset.h:118
static void reduce_outer_joins_pass2(Node *jtnode, reduce_outer_joins_pass1_state *state1, reduce_outer_joins_pass2_state *state2, PlannerInfo *root, Relids nonnullable_rels, List *forced_null_vars)
static reduce_outer_joins_pass1_state * reduce_outer_joins_pass1(Node *jtnode)
Node * remove_nulling_relids(Node *node, const Bitmapset *removable_relids, const Bitmapset *except_relids)

References bms_is_empty, bms_make_singleton(), reduce_outer_joins_pass1_state::contains_outer, elog, ERROR, reduce_outer_joins_partial_state::full_join_rti, reduce_outer_joins_pass2_state::inner_reduced, lfirst, NIL, reduce_outer_joins_pass2_state::partial_reduced, reduce_outer_joins_pass1(), reduce_outer_joins_pass2(), remove_nulling_relids(), root, and reduce_outer_joins_partial_state::unreduced_side.

Referenced by subquery_planner().

◆ remove_useless_result_rtes()

void remove_useless_result_rtes ( PlannerInfo root)

Definition at line 3428 of file prepjointree.c.

3429 {
3430  Relids dropped_outer_joins = NULL;
3431  ListCell *cell;
3432 
3433  /* Top level of jointree must always be a FromExpr */
3434  Assert(IsA(root->parse->jointree, FromExpr));
3435  /* Recurse ... */
3436  root->parse->jointree = (FromExpr *)
3438  (Node *) root->parse->jointree,
3439  NULL,
3440  &dropped_outer_joins);
3441  /* We should still have a FromExpr */
3442  Assert(IsA(root->parse->jointree, FromExpr));
3443 
3444  /*
3445  * If we removed any outer-join nodes from the jointree, run around and
3446  * remove references to those joins as nulling rels. (There could be such
3447  * references in PHVs that we pulled up out of the original subquery that
3448  * the RESULT rel replaced. This is kosher on the grounds that we now
3449  * know that such an outer join wouldn't really have nulled anything.) We
3450  * don't do this during the main recursion, for simplicity and because we
3451  * can handle all such joins in a single pass over the parse tree.
3452  */
3453  if (!bms_is_empty(dropped_outer_joins))
3454  {
3455  root->parse = (Query *)
3456  remove_nulling_relids((Node *) root->parse,
3457  dropped_outer_joins,
3458  NULL);
3459  /* There could be references in the append_rel_list, too */
3460  root->append_rel_list = (List *)
3461  remove_nulling_relids((Node *) root->append_rel_list,
3462  dropped_outer_joins,
3463  NULL);
3464  }
3465 
3466  /*
3467  * Remove any PlanRowMark referencing an RTE_RESULT RTE. We obviously
3468  * must do that for any RTE_RESULT that we just removed. But one for a
3469  * RTE that we did not remove can be dropped anyway: since the RTE has
3470  * only one possible output row, there is no need for EPQ to mark and
3471  * restore that row.
3472  *
3473  * It's necessary, not optional, to remove the PlanRowMark for a surviving
3474  * RTE_RESULT RTE; otherwise we'll generate a whole-row Var for the
3475  * RTE_RESULT, which the executor has no support for.
3476  */
3477  foreach(cell, root->rowMarks)
3478  {
3479  PlanRowMark *rc = (PlanRowMark *) lfirst(cell);
3480 
3481  if (rt_fetch(rc->rti, root->parse->rtable)->rtekind == RTE_RESULT)
3482  root->rowMarks = foreach_delete_current(root->rowMarks, cell);
3483  }
3484 }
@ RTE_RESULT
Definition: parsenodes.h:1025
#define foreach_delete_current(lst, var_or_cell)
Definition: pg_list.h:391
static Node * remove_useless_results_recurse(PlannerInfo *root, Node *jtnode, Node **parent_quals, Relids *dropped_outer_joins)

References Assert, bms_is_empty, foreach_delete_current, IsA, lfirst, remove_nulling_relids(), remove_useless_results_recurse(), root, rt_fetch, RTE_RESULT, and PlanRowMark::rti.

Referenced by subquery_planner().

◆ replace_empty_jointree()

void replace_empty_jointree ( Query parse)

Definition at line 395 of file prepjointree.c.

396 {
397  RangeTblEntry *rte;
398  Index rti;
399  RangeTblRef *rtr;
400 
401  /* Nothing to do if jointree is already nonempty */
402  if (parse->jointree->fromlist != NIL)
403  return;
404 
405  /* We mustn't change it in the top level of a setop tree, either */
406  if (parse->setOperations)
407  return;
408 
409  /* Create suitable RTE */
410  rte = makeNode(RangeTblEntry);
411  rte->rtekind = RTE_RESULT;
412  rte->eref = makeAlias("*RESULT*", NIL);
413 
414  /* Add it to rangetable */
415  parse->rtable = lappend(parse->rtable, rte);
416  rti = list_length(parse->rtable);
417 
418  /* And jam a reference into the jointree */
419  rtr = makeNode(RangeTblRef);
420  rtr->rtindex = rti;
421  parse->jointree->fromlist = list_make1(rtr);
422 }
unsigned int Index
Definition: c.h:593
Alias * makeAlias(const char *aliasname, List *colnames)
Definition: makefuncs.c:389

References lappend(), list_length(), list_make1, makeAlias(), makeNode, NIL, parse(), RTE_RESULT, RangeTblEntry::rtekind, and RangeTblRef::rtindex.

Referenced by convert_EXISTS_sublink_to_join(), pull_up_simple_subquery(), and subquery_planner().

◆ set_operation_ordered_results_useful()

bool set_operation_ordered_results_useful ( SetOperationStmt setop)

Definition at line 188 of file prepunion.c.

189 {
190  /*
191  * Paths sorted by the targetlist are useful for UNION as we can opt to
192  * MergeAppend the sorted paths then Unique them. Ordered paths are no
193  * more useful than unordered ones for UNION ALL.
194  */
195  if (!setop->all && setop->op == SETOP_UNION)
196  return true;
197 
198  /*
199  * EXCEPT / EXCEPT ALL / INTERSECT / INTERSECT ALL cannot yet utilize
200  * correctly sorted input paths.
201  */
202  return false;
203 }
@ SETOP_UNION
Definition: parsenodes.h:2119
SetOperation op
Definition: parsenodes.h:2198

References SetOperationStmt::all, SetOperationStmt::op, and SETOP_UNION.

Referenced by standard_qp_callback().

◆ transform_MERGE_to_join()

void transform_MERGE_to_join ( Query parse)

Definition at line 168 of file prepjointree.c.

169 {
170  RangeTblEntry *joinrte;
171  JoinExpr *joinexpr;
172  bool have_action[NUM_MERGE_MATCH_KINDS];
173  JoinType jointype;
174  int joinrti;
175  List *vars;
176  RangeTblRef *rtr;
177  FromExpr *target;
178  Node *source;
179  int sourcerti;
180 
181  if (parse->commandType != CMD_MERGE)
182  return;
183 
184  /* XXX probably bogus */
185  vars = NIL;
186 
187  /*
188  * Work out what kind of join is required. If there any WHEN NOT MATCHED
189  * BY SOURCE/TARGET actions, an outer join is required so that we process
190  * all unmatched tuples from the source and/or target relations.
191  * Otherwise, we can use an inner join.
192  */
193  have_action[MERGE_WHEN_MATCHED] = false;
194  have_action[MERGE_WHEN_NOT_MATCHED_BY_SOURCE] = false;
195  have_action[MERGE_WHEN_NOT_MATCHED_BY_TARGET] = false;
196 
197  foreach_node(MergeAction, action, parse->mergeActionList)
198  {
199  if (action->commandType != CMD_NOTHING)
200  have_action[action->matchKind] = true;
201  }
202 
203  if (have_action[MERGE_WHEN_NOT_MATCHED_BY_SOURCE] &&
205  jointype = JOIN_FULL;
206  else if (have_action[MERGE_WHEN_NOT_MATCHED_BY_SOURCE])
207  jointype = JOIN_LEFT;
208  else if (have_action[MERGE_WHEN_NOT_MATCHED_BY_TARGET])
209  jointype = JOIN_RIGHT;
210  else
211  jointype = JOIN_INNER;
212 
213  /* Manufacture a join RTE to use. */
214  joinrte = makeNode(RangeTblEntry);
215  joinrte->rtekind = RTE_JOIN;
216  joinrte->jointype = jointype;
217  joinrte->joinmergedcols = 0;
218  joinrte->joinaliasvars = vars;
219  joinrte->joinleftcols = NIL; /* MERGE does not allow JOIN USING */
220  joinrte->joinrightcols = NIL; /* ditto */
221  joinrte->join_using_alias = NULL;
222 
223  joinrte->alias = NULL;
224  joinrte->eref = makeAlias("*MERGE*", NIL);
225  joinrte->lateral = false;
226  joinrte->inh = false;
227  joinrte->inFromCl = true;
228 
229  /*
230  * Add completed RTE to pstate's range table list, so that we know its
231  * index.
232  */
233  parse->rtable = lappend(parse->rtable, joinrte);
234  joinrti = list_length(parse->rtable);
235 
236  /*
237  * Create a JOIN between the target and the source relation.
238  *
239  * Here the target is identified by parse->mergeTargetRelation. For a
240  * regular table, this will equal parse->resultRelation, but for a
241  * trigger-updatable view, it will be the expanded view subquery that we
242  * need to pull data from.
243  *
244  * The source relation is in parse->jointree->fromlist, but any quals in
245  * parse->jointree->quals are restrictions on the target relation (if the
246  * target relation is an auto-updatable view).
247  */
248  /* target rel, with any quals */
249  rtr = makeNode(RangeTblRef);
250  rtr->rtindex = parse->mergeTargetRelation;
251  target = makeFromExpr(list_make1(rtr), parse->jointree->quals);
252 
253  /* source rel (expect exactly one -- see transformMergeStmt()) */
254  Assert(list_length(parse->jointree->fromlist) == 1);
255  source = linitial(parse->jointree->fromlist);
256 
257  /*
258  * index of source rel (expect either a RangeTblRef or a JoinExpr -- see
259  * transformFromClauseItem()).
260  */
261  if (IsA(source, RangeTblRef))
262  sourcerti = ((RangeTblRef *) source)->rtindex;
263  else if (IsA(source, JoinExpr))
264  sourcerti = ((JoinExpr *) source)->rtindex;
265  else
266  {
267  elog(ERROR, "unrecognized source node type: %d",
268  (int) nodeTag(source));
269  sourcerti = 0; /* keep compiler quiet */
270  }
271 
272  /* Join the source and target */
273  joinexpr = makeNode(JoinExpr);
274  joinexpr->jointype = jointype;
275  joinexpr->isNatural = false;
276  joinexpr->larg = (Node *) target;
277  joinexpr->rarg = source;
278  joinexpr->usingClause = NIL;
279  joinexpr->join_using_alias = NULL;
280  joinexpr->quals = parse->mergeJoinCondition;
281  joinexpr->alias = NULL;
282  joinexpr->rtindex = joinrti;
283 
284  /* Make the new join be the sole entry in the query's jointree */
285  parse->jointree->fromlist = list_make1(joinexpr);
286  parse->jointree->quals = NULL;
287 
288  /*
289  * If necessary, mark parse->targetlist entries that refer to the target
290  * as nullable by the join. Normally the targetlist will be empty for a
291  * MERGE, but if the target is a trigger-updatable view, it will contain a
292  * whole-row Var referring to the expanded view query.
293  */
294  if (parse->targetList != NIL &&
295  (jointype == JOIN_RIGHT || jointype == JOIN_FULL))
296  parse->targetList = (List *)
297  add_nulling_relids((Node *) parse->targetList,
298  bms_make_singleton(parse->mergeTargetRelation),
299  bms_make_singleton(joinrti));
300 
301  /*
302  * If the source relation is on the outer side of the join, mark any
303  * source relation Vars in the join condition, actions, and RETURNING list
304  * as nullable by the join. These Vars will be added to the targetlist by
305  * preprocess_targetlist(), so it's important to mark them correctly here.
306  *
307  * It might seem that this is not necessary for Vars in the join
308  * condition, since it is inside the join, but it is also needed above the
309  * join (in the ModifyTable node) to distinguish between the MATCHED and
310  * NOT MATCHED BY SOURCE cases -- see ExecMergeMatched(). Note that this
311  * creates a modified copy of the join condition, for use above the join,
312  * without modifying the original join condition, inside the join.
313  */
314  if (jointype == JOIN_LEFT || jointype == JOIN_FULL)
315  {
316  parse->mergeJoinCondition =
317  add_nulling_relids(parse->mergeJoinCondition,
318  bms_make_singleton(sourcerti),
319  bms_make_singleton(joinrti));
320 
321  foreach_node(MergeAction, action, parse->mergeActionList)
322  {
323  action->qual =
325  bms_make_singleton(sourcerti),
326  bms_make_singleton(joinrti));
327 
328  action->targetList = (List *)
329  add_nulling_relids((Node *) action->targetList,
330  bms_make_singleton(sourcerti),
331  bms_make_singleton(joinrti));
332  }
333 
334  parse->returningList = (List *)
335  add_nulling_relids((Node *) parse->returningList,
336  bms_make_singleton(sourcerti),
337  bms_make_singleton(joinrti));
338  }
339 
340  /*
341  * If there are any WHEN NOT MATCHED BY SOURCE actions, the executor will
342  * use the join condition to distinguish between MATCHED and NOT MATCHED
343  * BY SOURCE cases. Otherwise, it's no longer needed, and we set it to
344  * NULL, saving cycles during planning and execution.
345  *
346  * We need to be careful though: the executor evaluates this condition
347  * using the output of the join subplan node, which nulls the output from
348  * the source relation when the join condition doesn't match. That risks
349  * producing incorrect results when rechecking using a "non-strict" join
350  * condition, such as "src.col IS NOT DISTINCT FROM tgt.col". To guard
351  * against that, we add an additional "src IS NOT NULL" check to the join
352  * condition, so that it does the right thing when performing a recheck
353  * based on the output of the join subplan.
354  */
355  if (have_action[MERGE_WHEN_NOT_MATCHED_BY_SOURCE])
356  {
357  Var *var;
358  NullTest *ntest;
359 
360  /* source wholerow Var (nullable by the new join) */
361  var = makeWholeRowVar(rt_fetch(sourcerti, parse->rtable),
362  sourcerti, 0, false);
363  var->varnullingrels = bms_make_singleton(joinrti);
364 
365  /* "src IS NOT NULL" check */
366  ntest = makeNode(NullTest);
367  ntest->arg = (Expr *) var;
368  ntest->nulltesttype = IS_NOT_NULL;
369  ntest->argisrow = false;
370  ntest->location = -1;
371 
372  /* combine it with the original join condition */
373  parse->mergeJoinCondition =
374  (Node *) make_and_qual((Node *) ntest, parse->mergeJoinCondition);
375  }
376  else
377  parse->mergeJoinCondition = NULL; /* join condition not needed */
378 }
Node * make_and_qual(Node *qual1, Node *qual2)
Definition: makefuncs.c:730
@ CMD_NOTHING
Definition: nodes.h:272
JoinType
Definition: nodes.h:288
@ JOIN_FULL
Definition: nodes.h:295
@ JOIN_RIGHT
Definition: nodes.h:296
@ JOIN_LEFT
Definition: nodes.h:294
@ RTE_JOIN
Definition: parsenodes.h:1019
#define linitial(l)
Definition: pg_list.h:178
#define foreach_node(type, var, lst)
Definition: pg_list.h:496
static rewind_source * source
Definition: pg_rewind.c:89
#define NUM_MERGE_MATCH_KINDS
Definition: primnodes.h:2001
@ IS_NOT_NULL
Definition: primnodes.h:1952
@ MERGE_WHEN_NOT_MATCHED_BY_TARGET
Definition: primnodes.h:1998
@ MERGE_WHEN_NOT_MATCHED_BY_SOURCE
Definition: primnodes.h:1997
@ MERGE_WHEN_MATCHED
Definition: primnodes.h:1996
Node * add_nulling_relids(Node *node, const Bitmapset *target_relids, const Bitmapset *added_relids)
Node * quals
Definition: primnodes.h:2289
JoinType jointype
Definition: primnodes.h:2280
int rtindex
Definition: primnodes.h:2293
Node * larg
Definition: primnodes.h:2282
bool isNatural
Definition: primnodes.h:2281
Node * rarg
Definition: primnodes.h:2283
NullTestType nulltesttype
Definition: primnodes.h:1959
ParseLoc location
Definition: primnodes.h:1962
Expr * arg
Definition: primnodes.h:1958
JoinType jointype
Definition: parsenodes.h:1151

References generate_unaccent_rules::action, add_nulling_relids(), NullTest::arg, Assert, bms_make_singleton(), CMD_MERGE, CMD_NOTHING, elog, ERROR, foreach_node, RangeTblEntry::inh, IS_NOT_NULL, IsA, JoinExpr::isNatural, JOIN_FULL, JOIN_INNER, JOIN_LEFT, JOIN_RIGHT, RangeTblEntry::jointype, JoinExpr::jointype, lappend(), JoinExpr::larg, linitial, list_length(), list_make1, NullTest::location, make_and_qual(), makeAlias(), makeFromExpr(), makeNode, makeWholeRowVar(), MERGE_WHEN_MATCHED, MERGE_WHEN_NOT_MATCHED_BY_SOURCE, MERGE_WHEN_NOT_MATCHED_BY_TARGET, NIL, nodeTag, NullTest::nulltesttype, NUM_MERGE_MATCH_KINDS, parse(), JoinExpr::quals, JoinExpr::rarg, rt_fetch, RTE_JOIN, RangeTblEntry::rtekind, RangeTblRef::rtindex, JoinExpr::rtindex, and source.

Referenced by subquery_planner().