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)
 
Querypreprocess_relation_rtes (PlannerInfo *root)
 
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 348 of file preptlist.c.

349{
350 List *update_colnos = NIL;
351 AttrNumber nextresno = 1;
352 ListCell *lc;
353
354 foreach(lc, tlist)
355 {
356 TargetEntry *tle = (TargetEntry *) lfirst(lc);
357
358 if (!tle->resjunk)
359 update_colnos = lappend_int(update_colnos, tle->resno);
360 tle->resno = nextresno++;
361 }
362 return update_colnos;
363}
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:2241

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

3048{
3049 Query *parse = root->parse;
3050 SetOperationStmt *topop;
3051 Node *leftmostjtnode;
3052 int leftmostRTI;
3053 RangeTblEntry *leftmostRTE;
3054 int childRTI;
3055 RangeTblEntry *childRTE;
3056 RangeTblRef *rtr;
3057
3058 /* Shouldn't be called unless query has setops */
3059 topop = castNode(SetOperationStmt, parse->setOperations);
3060 Assert(topop);
3061
3062 /* Can't optimize away a recursive UNION */
3063 if (root->hasRecursion)
3064 return;
3065
3066 /*
3067 * Recursively check the tree of set operations. If not all UNION ALL
3068 * with identical column types, punt.
3069 */
3070 if (!is_simple_union_all_recurse((Node *) topop, parse, topop->colTypes))
3071 return;
3072
3073 /*
3074 * Locate the leftmost leaf query in the setops tree. The upper query's
3075 * Vars all refer to this RTE (see transformSetOperationStmt).
3076 */
3077 leftmostjtnode = topop->larg;
3078 while (leftmostjtnode && IsA(leftmostjtnode, SetOperationStmt))
3079 leftmostjtnode = ((SetOperationStmt *) leftmostjtnode)->larg;
3080 Assert(leftmostjtnode && IsA(leftmostjtnode, RangeTblRef));
3081 leftmostRTI = ((RangeTblRef *) leftmostjtnode)->rtindex;
3082 leftmostRTE = rt_fetch(leftmostRTI, parse->rtable);
3083 Assert(leftmostRTE->rtekind == RTE_SUBQUERY);
3084
3085 /*
3086 * Make a copy of the leftmost RTE and add it to the rtable. This copy
3087 * will represent the leftmost leaf query in its capacity as a member of
3088 * the appendrel. The original will represent the appendrel as a whole.
3089 * (We must do things this way because the upper query's Vars have to be
3090 * seen as referring to the whole appendrel.)
3091 */
3092 childRTE = copyObject(leftmostRTE);
3093 parse->rtable = lappend(parse->rtable, childRTE);
3094 childRTI = list_length(parse->rtable);
3095
3096 /* Modify the setops tree to reference the child copy */
3097 ((RangeTblRef *) leftmostjtnode)->rtindex = childRTI;
3098
3099 /* Modify the formerly-leftmost RTE to mark it as an appendrel parent */
3100 leftmostRTE->inh = true;
3101
3102 /*
3103 * Form a RangeTblRef for the appendrel, and insert it into FROM. The top
3104 * Query of a setops tree should have had an empty FromClause initially.
3105 */
3106 rtr = makeNode(RangeTblRef);
3107 rtr->rtindex = leftmostRTI;
3108 Assert(parse->jointree->fromlist == NIL);
3109 parse->jointree->fromlist = list_make1(rtr);
3110
3111 /*
3112 * Now pretend the query has no setops. We must do this before trying to
3113 * do subquery pullup, because of Assert in pull_up_simple_subquery.
3114 */
3115 parse->setOperations = NULL;
3116
3117 /*
3118 * Build AppendRelInfo information, and apply pull_up_subqueries to the
3119 * leaf queries of the UNION ALL. (We must do that now because they
3120 * weren't previously referenced by the jointree, and so were missed by
3121 * the main invocation of pull_up_subqueries.)
3122 */
3123 pull_up_union_leaf_queries((Node *) topop, root, leftmostRTI, parse, 0);
3124}
Assert(PointerIsAligned(start, uint64))
List * lappend(List *list, void *datum)
Definition: list.c:339
#define IsA(nodeptr, _type_)
Definition: nodes.h:164
#define copyObject(obj)
Definition: nodes.h:232
#define makeNode(_type_)
Definition: nodes.h:161
#define castNode(_type_, nodeptr)
Definition: nodes.h:182
@ RTE_SUBQUERY
Definition: parsenodes.h:1044
#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:135
RTEKind rtekind
Definition: parsenodes.h:1078

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:813
int32_t int32
Definition: c.h:537
#define OidIsValid(objectId)
Definition: c.h:777
void cost_qual_eval_node(QualCost *cost, Node *qual, PlannerInfo *root)
Definition: costsize.c:4807
int32 get_typavgwidth(Oid typid, int32 typmod)
Definition: lsyscache.c:2745
#define ALLOCSET_SMALL_INITSIZE
Definition: memutils.h:168
#define ALLOCSET_DEFAULT_INITSIZE
Definition: memutils.h:158
#define DO_AGGSPLIT_SKIPFINAL(as)
Definition: nodes.h:396
#define DO_AGGSPLIT_DESERIALIZE(as)
Definition: nodes.h:398
#define DO_AGGSPLIT_COMBINE(as)
Definition: nodes.h:395
#define DO_AGGSPLIT_SERIALIZE(as)
Definition: nodes.h:397
#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:2316
QualCost finalCost
Definition: pathnodes.h:61
Size transitionSpace
Definition: pathnodes.h:62
QualCost transCost
Definition: pathnodes.h:60
List * aggrefs
Definition: pathnodes.h:3642
Oid finalfn_oid
Definition: pathnodes.h:3654
List * args
Definition: pathnodes.h:3671
int32 aggtransspace
Definition: pathnodes.h:3695
bool transtypeByVal
Definition: pathnodes.h:3692
Oid combinefn_oid
Definition: pathnodes.h:3684
Oid deserialfn_oid
Definition: pathnodes.h:3681
int32 aggtranstypmod
Definition: pathnodes.h:3690
Oid serialfn_oid
Definition: pathnodes.h:3678
Oid aggtranstype
Definition: pathnodes.h:3687
Expr * aggfilter
Definition: pathnodes.h:3672
List * aggdirectargs
Definition: primnodes.h:484
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(), estimate_path_cost_size(), and generate_grouped_paths().

◆ get_plan_rowmark()

PlanRowMark * get_plan_rowmark ( List rowmarks,
Index  rtindex 
)

Definition at line 526 of file preptlist.c.

527{
528 ListCell *l;
529
530 foreach(l, rowmarks)
531 {
532 PlanRowMark *rc = (PlanRowMark *) lfirst(l);
533
534 if (rc->rti == rtindex)
535 return rc;
536 }
537 return NULL;
538}

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

4368{
4369 Node *jtnode;
4370
4371 jtnode = find_jointree_node_for_rel((Node *) query->jointree,
4372 joinrelid);
4373 if (!jtnode)
4374 elog(ERROR, "could not find join node %d", joinrelid);
4375 return get_relids_in_jointree(jtnode, true, false);
4376}
#define ERROR
Definition: elog.h:39
#define elog(elevel,...)
Definition: elog.h:226
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:182

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

4308{
4309 Relids result = NULL;
4310
4311 if (jtnode == NULL)
4312 return result;
4313 if (IsA(jtnode, RangeTblRef))
4314 {
4315 int varno = ((RangeTblRef *) jtnode)->rtindex;
4316
4317 result = bms_make_singleton(varno);
4318 }
4319 else if (IsA(jtnode, FromExpr))
4320 {
4321 FromExpr *f = (FromExpr *) jtnode;
4322 ListCell *l;
4323
4324 foreach(l, f->fromlist)
4325 {
4326 result = bms_join(result,
4328 include_outer_joins,
4329 include_inner_joins));
4330 }
4331 }
4332 else if (IsA(jtnode, JoinExpr))
4333 {
4334 JoinExpr *j = (JoinExpr *) jtnode;
4335
4336 result = get_relids_in_jointree(j->larg,
4337 include_outer_joins,
4338 include_inner_joins);
4339 result = bms_join(result,
4341 include_outer_joins,
4342 include_inner_joins));
4343 if (j->rtindex)
4344 {
4345 if (j->jointype == JOIN_INNER)
4346 {
4347 if (include_inner_joins)
4348 result = bms_add_member(result, j->rtindex);
4349 }
4350 else
4351 {
4352 if (include_outer_joins)
4353 result = bms_add_member(result, j->rtindex);
4354 }
4355 }
4356 }
4357 else
4358 elog(ERROR, "unrecognized node type: %d",
4359 (int) nodeTag(jtnode));
4360 return result;
4361}
Bitmapset * bms_make_singleton(int x)
Definition: bitmapset.c:216
Bitmapset * bms_add_member(Bitmapset *a, int x)
Definition: bitmapset.c:814
Bitmapset * bms_join(Bitmapset *a, Bitmapset *b)
Definition: bitmapset.c:1229
int j
Definition: isn.c:78
#define nodeTag(nodeptr)
Definition: nodes.h:139
@ JOIN_INNER
Definition: nodes.h:303
List * fromlist
Definition: primnodes.h:2357

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 97 of file prepunion.c.

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

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

1096{
1097 ListCell *rt;
1098
1099 foreach(rt, root->parse->rtable)
1100 {
1101 RangeTblEntry *rte = (RangeTblEntry *) lfirst(rt);
1102
1103 if (rte->rtekind == RTE_FUNCTION)
1104 {
1105 Query *funcquery;
1106
1107 /* Apply const-simplification */
1108 rte->functions = (List *)
1110
1111 /* Check safety of expansion, and expand if possible */
1112 funcquery = inline_function_in_from(root, rte);
1113 if (funcquery)
1114 {
1115 /* Successful expansion, convert the RTE to a subquery */
1116 rte->rtekind = RTE_SUBQUERY;
1117 rte->subquery = funcquery;
1118 rte->security_barrier = false;
1119
1120 /*
1121 * Clear fields that should not be set in a subquery RTE.
1122 * However, we leave rte->functions filled in for the moment,
1123 * in case makeWholeRowVar needs to consult it. We'll clear
1124 * it in setrefs.c (see add_rte_to_flat_rtable) so that this
1125 * abuse of the data structure doesn't escape the planner.
1126 */
1127 rte->funcordinality = false;
1128 }
1129 }
1130 }
1131}
Query * inline_function_in_from(PlannerInfo *root, RangeTblEntry *rte)
Definition: clauses.c:5249
Node * eval_const_expressions(PlannerInfo *root, Node *node)
Definition: clauses.c:2270
@ RTE_FUNCTION
Definition: parsenodes.h:1046
bool funcordinality
Definition: parsenodes.h:1210
List * functions
Definition: parsenodes.h:1208

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

Referenced by pull_up_simple_subquery(), and subquery_planner().

◆ preprocess_relation_rtes()

Query * preprocess_relation_rtes ( PlannerInfo root)

Definition at line 417 of file prepjointree.c.

418{
419 Query *parse = root->parse;
420 int rtable_size;
421 int rt_index;
422
423 rtable_size = list_length(parse->rtable);
424
425 for (rt_index = 0; rt_index < rtable_size; rt_index++)
426 {
427 RangeTblEntry *rte = rt_fetch(rt_index + 1, parse->rtable);
428 Relation relation;
429
430 /* We only care about relation RTEs. */
431 if (rte->rtekind != RTE_RELATION)
432 continue;
433
434 /*
435 * We need not lock the relation since it was already locked by the
436 * rewriter.
437 */
438 relation = table_open(rte->relid, NoLock);
439
440 /*
441 * Check to see if the relation actually has any children; if not,
442 * clear the inh flag so we can treat it as a plain base relation.
443 *
444 * Note: this could give a false-positive result, if the rel once had
445 * children but no longer does. We used to be able to clear rte->inh
446 * later on when we discovered that, but no more; we have to handle
447 * such cases as full-fledged inheritance.
448 */
449 if (rte->inh)
450 rte->inh = relation->rd_rel->relhassubclass;
451
452 /*
453 * Check to see if the relation has any column not-null constraints;
454 * if so, retrieve the constraint information and store it in a
455 * relation OID based hash table.
456 */
458
459 /*
460 * Check to see if the relation has any virtual generated columns; if
461 * so, replace all Var nodes in the query that reference these columns
462 * with the generation expressions.
463 */
465 rte, rt_index + 1,
466 relation);
467
468 table_close(relation, NoLock);
469 }
470
471 return parse;
472}
#define NoLock
Definition: lockdefs.h:34
@ RTE_RELATION
Definition: parsenodes.h:1043
void get_relation_notnullatts(PlannerInfo *root, Relation relation)
Definition: plancat.c:682
static Query * expand_virtual_generated_columns(PlannerInfo *root, Query *parse, RangeTblEntry *rte, int rt_index, Relation relation)
Definition: prepjointree.c:486
Form_pg_class rd_rel
Definition: rel.h:111
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:126
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:40

References expand_virtual_generated_columns(), get_relation_notnullatts(), RangeTblEntry::inh, list_length(), NoLock, parse(), RelationData::rd_rel, root, rt_fetch, RTE_RELATION, RangeTblEntry::rtekind, table_close(), and table_open().

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

◆ preprocess_targetlist()

void preprocess_targetlist ( PlannerInfo root)

Definition at line 64 of file preptlist.c.

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

648{
649 Node *jtnode;
650 Relids relids;
651
652 /* Begin recursion through the jointree */
654 (Node *) root->parse->jointree,
655 &relids);
656
657 /*
658 * root->parse->jointree must always be a FromExpr, so insert a dummy one
659 * if we got a bare RangeTblRef or JoinExpr out of the recursion.
660 */
661 if (IsA(jtnode, FromExpr))
662 root->parse->jointree = (FromExpr *) jtnode;
663 else
664 root->parse->jointree = makeFromExpr(list_make1(jtnode), NULL);
665}
FromExpr * makeFromExpr(List *fromlist, Node *quals)
Definition: makefuncs.c:336
static Node * pull_up_sublinks_jointree_recurse(PlannerInfo *root, Node *jtnode, Relids *relids)
Definition: prepjointree.c:674

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

1143{
1144 /* Top level of jointree must always be a FromExpr */
1145 Assert(IsA(root->parse->jointree, FromExpr));
1146 /* Recursion starts with no containing join nor appendrel */
1147 root->parse->jointree = (FromExpr *)
1148 pull_up_subqueries_recurse(root, (Node *) root->parse->jointree,
1149 NULL, NULL);
1150 /* We should still have a FromExpr */
1151 Assert(IsA(root->parse->jointree, FromExpr));
1152}
static Node * pull_up_subqueries_recurse(PlannerInfo *root, Node *jtnode, JoinExpr *lowest_outer_join, AppendRelInfo *containing_appendrel)

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

3167{
3170 ListCell *lc;
3171
3172 /*
3173 * To avoid doing strictness checks on more quals than necessary, we want
3174 * to stop descending the jointree as soon as there are no outer joins
3175 * below our current point. This consideration forces a two-pass process.
3176 * The first pass gathers information about which base rels appear below
3177 * each side of each join clause, and about whether there are outer
3178 * join(s) below each side of each join clause. The second pass examines
3179 * qual clauses and changes join types as it descends the tree.
3180 */
3181 state1 = reduce_outer_joins_pass1((Node *) root->parse->jointree);
3182
3183 /* planner.c shouldn't have called me if no outer joins */
3184 if (state1 == NULL || !state1->contains_outer)
3185 elog(ERROR, "so where are the outer joins?");
3186
3187 state2.inner_reduced = NULL;
3188 state2.partial_reduced = NIL;
3189
3190 reduce_outer_joins_pass2((Node *) root->parse->jointree,
3191 state1, &state2,
3192 root, NULL, NIL);
3193
3194 /*
3195 * If we successfully reduced the strength of any outer joins, we must
3196 * remove references to those joins as nulling rels. This is handled as
3197 * an additional pass, for simplicity and because we can handle all
3198 * fully-reduced joins in a single pass over the parse tree.
3199 */
3200 if (!bms_is_empty(state2.inner_reduced))
3201 {
3202 root->parse = (Query *)
3203 remove_nulling_relids((Node *) root->parse,
3204 state2.inner_reduced,
3205 NULL);
3206 /* There could be references in the append_rel_list, too */
3207 root->append_rel_list = (List *)
3208 remove_nulling_relids((Node *) root->append_rel_list,
3209 state2.inner_reduced,
3210 NULL);
3211 }
3212
3213 /*
3214 * Partially-reduced full joins have to be done one at a time, since
3215 * they'll each need a different setting of except_relids.
3216 */
3217 foreach(lc, state2.partial_reduced)
3218 {
3220 Relids full_join_relids = bms_make_singleton(statep->full_join_rti);
3221
3222 root->parse = (Query *)
3223 remove_nulling_relids((Node *) root->parse,
3224 full_join_relids,
3225 statep->unreduced_side);
3226 root->append_rel_list = (List *)
3227 remove_nulling_relids((Node *) root->append_rel_list,
3228 full_join_relids,
3229 statep->unreduced_side);
3230 }
3231}
#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 3660 of file prepjointree.c.

3661{
3662 Relids dropped_outer_joins = NULL;
3663 ListCell *cell;
3664
3665 /* Top level of jointree must always be a FromExpr */
3666 Assert(IsA(root->parse->jointree, FromExpr));
3667 /* Recurse ... */
3668 root->parse->jointree = (FromExpr *)
3670 (Node *) root->parse->jointree,
3671 NULL,
3672 &dropped_outer_joins);
3673 /* We should still have a FromExpr */
3674 Assert(IsA(root->parse->jointree, FromExpr));
3675
3676 /*
3677 * If we removed any outer-join nodes from the jointree, run around and
3678 * remove references to those joins as nulling rels. (There could be such
3679 * references in PHVs that we pulled up out of the original subquery that
3680 * the RESULT rel replaced. This is kosher on the grounds that we now
3681 * know that such an outer join wouldn't really have nulled anything.) We
3682 * don't do this during the main recursion, for simplicity and because we
3683 * can handle all such joins in a single pass over the parse tree.
3684 */
3685 if (!bms_is_empty(dropped_outer_joins))
3686 {
3687 root->parse = (Query *)
3688 remove_nulling_relids((Node *) root->parse,
3689 dropped_outer_joins,
3690 NULL);
3691 /* There could be references in the append_rel_list, too */
3692 root->append_rel_list = (List *)
3693 remove_nulling_relids((Node *) root->append_rel_list,
3694 dropped_outer_joins,
3695 NULL);
3696 }
3697
3698 /*
3699 * Remove any PlanRowMark referencing an RTE_RESULT RTE. We obviously
3700 * must do that for any RTE_RESULT that we just removed. But one for a
3701 * RTE that we did not remove can be dropped anyway: since the RTE has
3702 * only one possible output row, there is no need for EPQ to mark and
3703 * restore that row.
3704 *
3705 * It's necessary, not optional, to remove the PlanRowMark for a surviving
3706 * RTE_RESULT RTE; otherwise we'll generate a whole-row Var for the
3707 * RTE_RESULT, which the executor has no support for.
3708 */
3709 foreach(cell, root->rowMarks)
3710 {
3711 PlanRowMark *rc = (PlanRowMark *) lfirst(cell);
3712
3713 if (rt_fetch(rc->rti, root->parse->rtable)->rtekind == RTE_RESULT)
3714 root->rowMarks = foreach_delete_current(root->rowMarks, cell);
3715 }
3716}
@ RTE_RESULT
Definition: parsenodes.h:1051
#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 589 of file prepjointree.c.

590{
591 RangeTblEntry *rte;
592 Index rti;
593 RangeTblRef *rtr;
594
595 /* Nothing to do if jointree is already nonempty */
596 if (parse->jointree->fromlist != NIL)
597 return;
598
599 /* We mustn't change it in the top level of a setop tree, either */
600 if (parse->setOperations)
601 return;
602
603 /* Create suitable RTE */
604 rte = makeNode(RangeTblEntry);
605 rte->rtekind = RTE_RESULT;
606 rte->eref = makeAlias("*RESULT*", NIL);
607
608 /* Add it to rangetable */
609 parse->rtable = lappend(parse->rtable, rte);
610 rti = list_length(parse->rtable);
611
612 /* And jam a reference into the jointree */
613 rtr = makeNode(RangeTblRef);
614 rtr->rtindex = rti;
615 parse->jointree->fromlist = list_make1(rtr);
616}
unsigned int Index
Definition: c.h:622
Alias * makeAlias(const char *aliasname, List *colnames)
Definition: makefuncs.c:438

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

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

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