PostgreSQL Source Code git master
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)
 

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:2247

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 2870 of file prepjointree.c.

2871{
2872 Query *parse = root->parse;
2873 SetOperationStmt *topop;
2874 Node *leftmostjtnode;
2875 int leftmostRTI;
2876 RangeTblEntry *leftmostRTE;
2877 int childRTI;
2878 RangeTblEntry *childRTE;
2879 RangeTblRef *rtr;
2880
2881 /* Shouldn't be called unless query has setops */
2882 topop = castNode(SetOperationStmt, parse->setOperations);
2883 Assert(topop);
2884
2885 /* Can't optimize away a recursive UNION */
2886 if (root->hasRecursion)
2887 return;
2888
2889 /*
2890 * Recursively check the tree of set operations. If not all UNION ALL
2891 * with identical column types, punt.
2892 */
2893 if (!is_simple_union_all_recurse((Node *) topop, parse, topop->colTypes))
2894 return;
2895
2896 /*
2897 * Locate the leftmost leaf query in the setops tree. The upper query's
2898 * Vars all refer to this RTE (see transformSetOperationStmt).
2899 */
2900 leftmostjtnode = topop->larg;
2901 while (leftmostjtnode && IsA(leftmostjtnode, SetOperationStmt))
2902 leftmostjtnode = ((SetOperationStmt *) leftmostjtnode)->larg;
2903 Assert(leftmostjtnode && IsA(leftmostjtnode, RangeTblRef));
2904 leftmostRTI = ((RangeTblRef *) leftmostjtnode)->rtindex;
2905 leftmostRTE = rt_fetch(leftmostRTI, parse->rtable);
2906 Assert(leftmostRTE->rtekind == RTE_SUBQUERY);
2907
2908 /*
2909 * Make a copy of the leftmost RTE and add it to the rtable. This copy
2910 * will represent the leftmost leaf query in its capacity as a member of
2911 * the appendrel. The original will represent the appendrel as a whole.
2912 * (We must do things this way because the upper query's Vars have to be
2913 * seen as referring to the whole appendrel.)
2914 */
2915 childRTE = copyObject(leftmostRTE);
2916 parse->rtable = lappend(parse->rtable, childRTE);
2917 childRTI = list_length(parse->rtable);
2918
2919 /* Modify the setops tree to reference the child copy */
2920 ((RangeTblRef *) leftmostjtnode)->rtindex = childRTI;
2921
2922 /* Modify the formerly-leftmost RTE to mark it as an appendrel parent */
2923 leftmostRTE->inh = true;
2924
2925 /*
2926 * Form a RangeTblRef for the appendrel, and insert it into FROM. The top
2927 * Query of a setops tree should have had an empty FromClause initially.
2928 */
2929 rtr = makeNode(RangeTblRef);
2930 rtr->rtindex = leftmostRTI;
2931 Assert(parse->jointree->fromlist == NIL);
2932 parse->jointree->fromlist = list_make1(rtr);
2933
2934 /*
2935 * Now pretend the query has no setops. We must do this before trying to
2936 * do subquery pullup, because of Assert in pull_up_simple_subquery.
2937 */
2938 parse->setOperations = NULL;
2939
2940 /*
2941 * Build AppendRelInfo information, and apply pull_up_subqueries to the
2942 * leaf queries of the UNION ALL. (We must do that now because they
2943 * weren't previously referenced by the jointree, and so were missed by
2944 * the main invocation of pull_up_subqueries.)
2945 */
2946 pull_up_union_leaf_queries((Node *) topop, root, leftmostRTI, parse, 0);
2947}
#define Assert(condition)
Definition: c.h:815
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:1027
#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:1857
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:1056

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:768
int32_t int32
Definition: c.h:484
#define OidIsValid(objectId)
Definition: c.h:732
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:2109
QualCost finalCost
Definition: pathnodes.h:61
Size transitionSpace
Definition: pathnodes.h:62
QualCost transCost
Definition: pathnodes.h:60
List * aggrefs
Definition: pathnodes.h:3387
Oid finalfn_oid
Definition: pathnodes.h:3399
List * args
Definition: pathnodes.h:3416
int32 aggtransspace
Definition: pathnodes.h:3440
bool transtypeByVal
Definition: pathnodes.h:3437
Oid combinefn_oid
Definition: pathnodes.h:3429
Oid deserialfn_oid
Definition: pathnodes.h:3426
int32 aggtranstypmod
Definition: pathnodes.h:3435
Oid serialfn_oid
Definition: pathnodes.h:3423
Oid aggtranstype
Definition: pathnodes.h:3432
Expr * aggfilter
Definition: pathnodes.h:3417
List * aggdirectargs
Definition: primnodes.h:481
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 4190 of file prepjointree.c.

4191{
4192 Node *jtnode;
4193
4194 jtnode = find_jointree_node_for_rel((Node *) query->jointree,
4195 joinrelid);
4196 if (!jtnode)
4197 elog(ERROR, "could not find join node %d", joinrelid);
4198 return get_relids_in_jointree(jtnode, true, false);
4199}
#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 4129 of file prepjointree.c.

4131{
4132 Relids result = NULL;
4133
4134 if (jtnode == NULL)
4135 return result;
4136 if (IsA(jtnode, RangeTblRef))
4137 {
4138 int varno = ((RangeTblRef *) jtnode)->rtindex;
4139
4140 result = bms_make_singleton(varno);
4141 }
4142 else if (IsA(jtnode, FromExpr))
4143 {
4144 FromExpr *f = (FromExpr *) jtnode;
4145 ListCell *l;
4146
4147 foreach(l, f->fromlist)
4148 {
4149 result = bms_join(result,
4151 include_outer_joins,
4152 include_inner_joins));
4153 }
4154 }
4155 else if (IsA(jtnode, JoinExpr))
4156 {
4157 JoinExpr *j = (JoinExpr *) jtnode;
4158
4159 result = get_relids_in_jointree(j->larg,
4160 include_outer_joins,
4161 include_inner_joins);
4162 result = bms_join(result,
4164 include_outer_joins,
4165 include_inner_joins));
4166 if (j->rtindex)
4167 {
4168 if (j->jointype == JOIN_INNER)
4169 {
4170 if (include_inner_joins)
4171 result = bms_add_member(result, j->rtindex);
4172 }
4173 else
4174 {
4175 if (include_outer_joins)
4176 result = bms_add_member(result, j->rtindex);
4177 }
4178 }
4179 }
4180 else
4181 elog(ERROR, "unrecognized node type: %d",
4182 (int) nodeTag(jtnode));
4183 return result;
4184}
Bitmapset * bms_make_singleton(int x)
Definition: bitmapset.c:216
Bitmapset * bms_add_member(Bitmapset *a, int x)
Definition: bitmapset.c:815
Bitmapset * bms_join(Bitmapset *a, Bitmapset *b)
Definition: bitmapset.c:1230
int j
Definition: isn.c:73
#define nodeTag(nodeptr)
Definition: nodes.h:133
@ JOIN_INNER
Definition: nodes.h:293
List * fromlist
Definition: primnodes.h:2363

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

Referenced by find_dependent_phvs_in_jointree(), get_relids_for_join(), get_relids_in_jointree(), 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 93 of file prepunion.c.

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

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:5066
Node * eval_const_expressions(PlannerInfo *root, Node *node)
Definition: clauses.c:2254
@ RTE_FUNCTION
Definition: parsenodes.h:1029
bool funcordinality
Definition: parsenodes.h:1188
List * functions
Definition: parsenodes.h:1186

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 }
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,
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,
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 }
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:904
List * list_concat_copy(const List *list1, const List *list2)
Definition: list.c:598
void list_free(List *list)
Definition: list.c:1546
#define NoLock
Definition: lockdefs.h:34
Var * makeVar(int varno, AttrNumber varattno, Oid vartype, int32 vartypmod, Oid varcollid, Index varlevelsup)
Definition: makefuncs.c:66
Var * makeWholeRowVar(RangeTblEntry *rte, int varno, Index varlevelsup, bool allowScalar)
Definition: makefuncs.c:137
TargetEntry * makeTargetEntry(Expr *expr, AttrNumber resno, char *resname, bool resjunk)
Definition: makefuncs.c:242
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:1026
@ ROW_MARK_COPY
Definition: plannodes.h:1334
#define snprintf
Definition: port.h:238
#define InvalidOid
Definition: postgres_ext.h:37
List * extract_update_targetlist_colnos(List *tlist)
Definition: preptlist.c:345
static List * expand_insert_targetlist(List *tlist, Relation rel)
Definition: preptlist.c:379
Index prti
Definition: plannodes.h:1383
bool isParent
Definition: plannodes.h:1389
Index rowmarkId
Definition: plannodes.h:1384
int allMarkTypes
Definition: plannodes.h:1386
Definition: primnodes.h:261
int varno
Definition: primnodes.h:268
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:653

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:289
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 2989 of file prepjointree.c.

2990{
2993 ListCell *lc;
2994
2995 /*
2996 * To avoid doing strictness checks on more quals than necessary, we want
2997 * to stop descending the jointree as soon as there are no outer joins
2998 * below our current point. This consideration forces a two-pass process.
2999 * The first pass gathers information about which base rels appear below
3000 * each side of each join clause, and about whether there are outer
3001 * join(s) below each side of each join clause. The second pass examines
3002 * qual clauses and changes join types as it descends the tree.
3003 */
3004 state1 = reduce_outer_joins_pass1((Node *) root->parse->jointree);
3005
3006 /* planner.c shouldn't have called me if no outer joins */
3007 if (state1 == NULL || !state1->contains_outer)
3008 elog(ERROR, "so where are the outer joins?");
3009
3010 state2.inner_reduced = NULL;
3011 state2.partial_reduced = NIL;
3012
3013 reduce_outer_joins_pass2((Node *) root->parse->jointree,
3014 state1, &state2,
3015 root, NULL, NIL);
3016
3017 /*
3018 * If we successfully reduced the strength of any outer joins, we must
3019 * remove references to those joins as nulling rels. This is handled as
3020 * an additional pass, for simplicity and because we can handle all
3021 * fully-reduced joins in a single pass over the parse tree.
3022 */
3023 if (!bms_is_empty(state2.inner_reduced))
3024 {
3025 root->parse = (Query *)
3026 remove_nulling_relids((Node *) root->parse,
3027 state2.inner_reduced,
3028 NULL);
3029 /* There could be references in the append_rel_list, too */
3030 root->append_rel_list = (List *)
3031 remove_nulling_relids((Node *) root->append_rel_list,
3032 state2.inner_reduced,
3033 NULL);
3034 }
3035
3036 /*
3037 * Partially-reduced full joins have to be done one at a time, since
3038 * they'll each need a different setting of except_relids.
3039 */
3040 foreach(lc, state2.partial_reduced)
3041 {
3043 Relids full_join_relids = bms_make_singleton(statep->full_join_rti);
3044
3045 root->parse = (Query *)
3046 remove_nulling_relids((Node *) root->parse,
3047 full_join_relids,
3048 statep->unreduced_side);
3049 root->append_rel_list = (List *)
3050 remove_nulling_relids((Node *) root->append_rel_list,
3051 full_join_relids,
3052 statep->unreduced_side);
3053 }
3054}
#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 3483 of file prepjointree.c.

3484{
3485 Relids dropped_outer_joins = NULL;
3486 ListCell *cell;
3487
3488 /* Top level of jointree must always be a FromExpr */
3489 Assert(IsA(root->parse->jointree, FromExpr));
3490 /* Recurse ... */
3491 root->parse->jointree = (FromExpr *)
3493 (Node *) root->parse->jointree,
3494 NULL,
3495 &dropped_outer_joins);
3496 /* We should still have a FromExpr */
3497 Assert(IsA(root->parse->jointree, FromExpr));
3498
3499 /*
3500 * If we removed any outer-join nodes from the jointree, run around and
3501 * remove references to those joins as nulling rels. (There could be such
3502 * references in PHVs that we pulled up out of the original subquery that
3503 * the RESULT rel replaced. This is kosher on the grounds that we now
3504 * know that such an outer join wouldn't really have nulled anything.) We
3505 * don't do this during the main recursion, for simplicity and because we
3506 * can handle all such joins in a single pass over the parse tree.
3507 */
3508 if (!bms_is_empty(dropped_outer_joins))
3509 {
3510 root->parse = (Query *)
3511 remove_nulling_relids((Node *) root->parse,
3512 dropped_outer_joins,
3513 NULL);
3514 /* There could be references in the append_rel_list, too */
3515 root->append_rel_list = (List *)
3516 remove_nulling_relids((Node *) root->append_rel_list,
3517 dropped_outer_joins,
3518 NULL);
3519 }
3520
3521 /*
3522 * Remove any PlanRowMark referencing an RTE_RESULT RTE. We obviously
3523 * must do that for any RTE_RESULT that we just removed. But one for a
3524 * RTE that we did not remove can be dropped anyway: since the RTE has
3525 * only one possible output row, there is no need for EPQ to mark and
3526 * restore that row.
3527 *
3528 * It's necessary, not optional, to remove the PlanRowMark for a surviving
3529 * RTE_RESULT RTE; otherwise we'll generate a whole-row Var for the
3530 * RTE_RESULT, which the executor has no support for.
3531 */
3532 foreach(cell, root->rowMarks)
3533 {
3534 PlanRowMark *rc = (PlanRowMark *) lfirst(cell);
3535
3536 if (rt_fetch(rc->rti, root->parse->rtable)->rtekind == RTE_RESULT)
3537 root->rowMarks = foreach_delete_current(root->rowMarks, cell);
3538 }
3539}
@ RTE_RESULT
Definition: parsenodes.h:1034
#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:571
Alias * makeAlias(const char *aliasname, List *colnames)
Definition: makefuncs.c:391

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().

◆ 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:733
@ 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:1028
#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:2032
@ IS_NOT_NULL
Definition: primnodes.h:1983
@ MERGE_WHEN_NOT_MATCHED_BY_TARGET
Definition: primnodes.h:2029
@ MERGE_WHEN_NOT_MATCHED_BY_SOURCE
Definition: primnodes.h:2028
@ MERGE_WHEN_MATCHED
Definition: primnodes.h:2027
Node * add_nulling_relids(Node *node, const Bitmapset *target_relids, const Bitmapset *added_relids)
Node * quals
Definition: primnodes.h:2344
JoinType jointype
Definition: primnodes.h:2335
int rtindex
Definition: primnodes.h:2348
Node * larg
Definition: primnodes.h:2337
bool isNatural
Definition: primnodes.h:2336
Node * rarg
Definition: primnodes.h:2338
NullTestType nulltesttype
Definition: primnodes.h:1990
ParseLoc location
Definition: primnodes.h:1993
Expr * arg
Definition: primnodes.h:1989
JoinType jointype
Definition: parsenodes.h:1160

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().