Line data Source code
1 : /*-------------------------------------------------------------------------
2 : *
3 : * prepjointree.c
4 : * Planner preprocessing for subqueries and join tree manipulation.
5 : *
6 : * NOTE: the intended sequence for invoking these operations is
7 : * replace_empty_jointree
8 : * pull_up_sublinks
9 : * preprocess_function_rtes
10 : * pull_up_subqueries
11 : * flatten_simple_union_all
12 : * do expression preprocessing (including flattening JOIN alias vars)
13 : * reduce_outer_joins
14 : * remove_useless_result_rtes
15 : *
16 : *
17 : * Portions Copyright (c) 1996-2024, PostgreSQL Global Development Group
18 : * Portions Copyright (c) 1994, Regents of the University of California
19 : *
20 : *
21 : * IDENTIFICATION
22 : * src/backend/optimizer/prep/prepjointree.c
23 : *
24 : *-------------------------------------------------------------------------
25 : */
26 : #include "postgres.h"
27 :
28 : #include "catalog/pg_type.h"
29 : #include "funcapi.h"
30 : #include "miscadmin.h"
31 : #include "nodes/makefuncs.h"
32 : #include "nodes/multibitmapset.h"
33 : #include "nodes/nodeFuncs.h"
34 : #include "optimizer/clauses.h"
35 : #include "optimizer/optimizer.h"
36 : #include "optimizer/placeholder.h"
37 : #include "optimizer/prep.h"
38 : #include "optimizer/subselect.h"
39 : #include "optimizer/tlist.h"
40 : #include "parser/parse_relation.h"
41 : #include "parser/parsetree.h"
42 : #include "rewrite/rewriteManip.h"
43 :
44 :
45 : typedef struct pullup_replace_vars_context
46 : {
47 : PlannerInfo *root;
48 : List *targetlist; /* tlist of subquery being pulled up */
49 : RangeTblEntry *target_rte; /* RTE of subquery */
50 : Relids relids; /* relids within subquery, as numbered after
51 : * pullup (set only if target_rte->lateral) */
52 : bool *outer_hasSubLinks; /* -> outer query's hasSubLinks */
53 : int varno; /* varno of subquery */
54 : bool wrap_non_vars; /* do we need all non-Var outputs to be PHVs? */
55 : Node **rv_cache; /* cache for results with PHVs */
56 : } pullup_replace_vars_context;
57 :
58 : typedef struct reduce_outer_joins_pass1_state
59 : {
60 : Relids relids; /* base relids within this subtree */
61 : bool contains_outer; /* does subtree contain outer join(s)? */
62 : List *sub_states; /* List of states for subtree components */
63 : } reduce_outer_joins_pass1_state;
64 :
65 : typedef struct reduce_outer_joins_pass2_state
66 : {
67 : Relids inner_reduced; /* OJ relids reduced to plain inner joins */
68 : List *partial_reduced; /* List of partially reduced FULL joins */
69 : } reduce_outer_joins_pass2_state;
70 :
71 : typedef struct reduce_outer_joins_partial_state
72 : {
73 : int full_join_rti; /* RT index of a formerly-FULL join */
74 : Relids unreduced_side; /* relids in its still-nullable side */
75 : } reduce_outer_joins_partial_state;
76 :
77 : static Node *pull_up_sublinks_jointree_recurse(PlannerInfo *root, Node *jtnode,
78 : Relids *relids);
79 : static Node *pull_up_sublinks_qual_recurse(PlannerInfo *root, Node *node,
80 : Node **jtlink1, Relids available_rels1,
81 : Node **jtlink2, Relids available_rels2);
82 : static Node *pull_up_subqueries_recurse(PlannerInfo *root, Node *jtnode,
83 : JoinExpr *lowest_outer_join,
84 : AppendRelInfo *containing_appendrel);
85 : static Node *pull_up_simple_subquery(PlannerInfo *root, Node *jtnode,
86 : RangeTblEntry *rte,
87 : JoinExpr *lowest_outer_join,
88 : AppendRelInfo *containing_appendrel);
89 : static Node *pull_up_simple_union_all(PlannerInfo *root, Node *jtnode,
90 : RangeTblEntry *rte);
91 : static void pull_up_union_leaf_queries(Node *setOp, PlannerInfo *root,
92 : int parentRTindex, Query *setOpQuery,
93 : int childRToffset);
94 : static void make_setop_translation_list(Query *query, int newvarno,
95 : AppendRelInfo *appinfo);
96 : static bool is_simple_subquery(PlannerInfo *root, Query *subquery,
97 : RangeTblEntry *rte,
98 : JoinExpr *lowest_outer_join);
99 : static Node *pull_up_simple_values(PlannerInfo *root, Node *jtnode,
100 : RangeTblEntry *rte);
101 : static bool is_simple_values(PlannerInfo *root, RangeTblEntry *rte);
102 : static Node *pull_up_constant_function(PlannerInfo *root, Node *jtnode,
103 : RangeTblEntry *rte,
104 : AppendRelInfo *containing_appendrel);
105 : static bool is_simple_union_all(Query *subquery);
106 : static bool is_simple_union_all_recurse(Node *setOp, Query *setOpQuery,
107 : List *colTypes);
108 : static bool is_safe_append_member(Query *subquery);
109 : static bool jointree_contains_lateral_outer_refs(PlannerInfo *root,
110 : Node *jtnode, bool restricted,
111 : Relids safe_upper_varnos);
112 : static void perform_pullup_replace_vars(PlannerInfo *root,
113 : pullup_replace_vars_context *rvcontext,
114 : AppendRelInfo *containing_appendrel);
115 : static void replace_vars_in_jointree(Node *jtnode,
116 : pullup_replace_vars_context *context);
117 : static Node *pullup_replace_vars(Node *expr,
118 : pullup_replace_vars_context *context);
119 : static Node *pullup_replace_vars_callback(Var *var,
120 : replace_rte_variables_context *context);
121 : static Query *pullup_replace_vars_subquery(Query *query,
122 : pullup_replace_vars_context *context);
123 : static reduce_outer_joins_pass1_state *reduce_outer_joins_pass1(Node *jtnode);
124 : static void reduce_outer_joins_pass2(Node *jtnode,
125 : reduce_outer_joins_pass1_state *state1,
126 : reduce_outer_joins_pass2_state *state2,
127 : PlannerInfo *root,
128 : Relids nonnullable_rels,
129 : List *forced_null_vars);
130 : static void report_reduced_full_join(reduce_outer_joins_pass2_state *state2,
131 : int rtindex, Relids relids);
132 : static Node *remove_useless_results_recurse(PlannerInfo *root, Node *jtnode,
133 : Node **parent_quals,
134 : Relids *dropped_outer_joins);
135 : static int get_result_relid(PlannerInfo *root, Node *jtnode);
136 : static void remove_result_refs(PlannerInfo *root, int varno, Node *newjtloc);
137 : static bool find_dependent_phvs(PlannerInfo *root, int varno);
138 : static bool find_dependent_phvs_in_jointree(PlannerInfo *root,
139 : Node *node, int varno);
140 : static void substitute_phv_relids(Node *node,
141 : int varno, Relids subrelids);
142 : static void fix_append_rel_relids(PlannerInfo *root, int varno,
143 : Relids subrelids);
144 : static Node *find_jointree_node_for_rel(Node *jtnode, int relid);
145 :
146 :
147 : /*
148 : * transform_MERGE_to_join
149 : * Replace a MERGE's jointree to also include the target relation.
150 : */
151 : void
152 514726 : transform_MERGE_to_join(Query *parse)
153 : {
154 : RangeTblEntry *joinrte;
155 : JoinExpr *joinexpr;
156 : bool have_action[NUM_MERGE_MATCH_KINDS];
157 : JoinType jointype;
158 : int joinrti;
159 : List *vars;
160 : RangeTblRef *rtr;
161 : FromExpr *target;
162 : Node *source;
163 : int sourcerti;
164 :
165 514726 : if (parse->commandType != CMD_MERGE)
166 512968 : return;
167 :
168 : /* XXX probably bogus */
169 1758 : vars = NIL;
170 :
171 : /*
172 : * Work out what kind of join is required. If there any WHEN NOT MATCHED
173 : * BY SOURCE/TARGET actions, an outer join is required so that we process
174 : * all unmatched tuples from the source and/or target relations.
175 : * Otherwise, we can use an inner join.
176 : */
177 1758 : have_action[MERGE_WHEN_MATCHED] = false;
178 1758 : have_action[MERGE_WHEN_NOT_MATCHED_BY_SOURCE] = false;
179 1758 : have_action[MERGE_WHEN_NOT_MATCHED_BY_TARGET] = false;
180 :
181 6210 : foreach_node(MergeAction, action, parse->mergeActionList)
182 : {
183 2694 : if (action->commandType != CMD_NOTHING)
184 2628 : have_action[action->matchKind] = true;
185 : }
186 :
187 1758 : if (have_action[MERGE_WHEN_NOT_MATCHED_BY_SOURCE] &&
188 126 : have_action[MERGE_WHEN_NOT_MATCHED_BY_TARGET])
189 96 : jointype = JOIN_FULL;
190 1662 : else if (have_action[MERGE_WHEN_NOT_MATCHED_BY_SOURCE])
191 30 : jointype = JOIN_LEFT;
192 1632 : else if (have_action[MERGE_WHEN_NOT_MATCHED_BY_TARGET])
193 746 : jointype = JOIN_RIGHT;
194 : else
195 886 : jointype = JOIN_INNER;
196 :
197 : /* Manufacture a join RTE to use. */
198 1758 : joinrte = makeNode(RangeTblEntry);
199 1758 : joinrte->rtekind = RTE_JOIN;
200 1758 : joinrte->jointype = jointype;
201 1758 : joinrte->joinmergedcols = 0;
202 1758 : joinrte->joinaliasvars = vars;
203 1758 : joinrte->joinleftcols = NIL; /* MERGE does not allow JOIN USING */
204 1758 : joinrte->joinrightcols = NIL; /* ditto */
205 1758 : joinrte->join_using_alias = NULL;
206 :
207 1758 : joinrte->alias = NULL;
208 1758 : joinrte->eref = makeAlias("*MERGE*", NIL);
209 1758 : joinrte->lateral = false;
210 1758 : joinrte->inh = false;
211 1758 : joinrte->inFromCl = true;
212 :
213 : /*
214 : * Add completed RTE to pstate's range table list, so that we know its
215 : * index.
216 : */
217 1758 : parse->rtable = lappend(parse->rtable, joinrte);
218 1758 : joinrti = list_length(parse->rtable);
219 :
220 : /*
221 : * Create a JOIN between the target and the source relation.
222 : *
223 : * Here the target is identified by parse->mergeTargetRelation. For a
224 : * regular table, this will equal parse->resultRelation, but for a
225 : * trigger-updatable view, it will be the expanded view subquery that we
226 : * need to pull data from.
227 : *
228 : * The source relation is in parse->jointree->fromlist, but any quals in
229 : * parse->jointree->quals are restrictions on the target relation (if the
230 : * target relation is an auto-updatable view).
231 : */
232 : /* target rel, with any quals */
233 1758 : rtr = makeNode(RangeTblRef);
234 1758 : rtr->rtindex = parse->mergeTargetRelation;
235 1758 : target = makeFromExpr(list_make1(rtr), parse->jointree->quals);
236 :
237 : /* source rel (expect exactly one -- see transformMergeStmt()) */
238 : Assert(list_length(parse->jointree->fromlist) == 1);
239 1758 : source = linitial(parse->jointree->fromlist);
240 :
241 : /*
242 : * index of source rel (expect either a RangeTblRef or a JoinExpr -- see
243 : * transformFromClauseItem()).
244 : */
245 1758 : if (IsA(source, RangeTblRef))
246 1722 : sourcerti = ((RangeTblRef *) source)->rtindex;
247 36 : else if (IsA(source, JoinExpr))
248 36 : sourcerti = ((JoinExpr *) source)->rtindex;
249 : else
250 : {
251 0 : elog(ERROR, "unrecognized source node type: %d",
252 : (int) nodeTag(source));
253 : sourcerti = 0; /* keep compiler quiet */
254 : }
255 :
256 : /* Join the source and target */
257 1758 : joinexpr = makeNode(JoinExpr);
258 1758 : joinexpr->jointype = jointype;
259 1758 : joinexpr->isNatural = false;
260 1758 : joinexpr->larg = (Node *) target;
261 1758 : joinexpr->rarg = source;
262 1758 : joinexpr->usingClause = NIL;
263 1758 : joinexpr->join_using_alias = NULL;
264 1758 : joinexpr->quals = parse->mergeJoinCondition;
265 1758 : joinexpr->alias = NULL;
266 1758 : joinexpr->rtindex = joinrti;
267 :
268 : /* Make the new join be the sole entry in the query's jointree */
269 1758 : parse->jointree->fromlist = list_make1(joinexpr);
270 1758 : parse->jointree->quals = NULL;
271 :
272 : /*
273 : * If necessary, mark parse->targetlist entries that refer to the target
274 : * as nullable by the join. Normally the targetlist will be empty for a
275 : * MERGE, but if the target is a trigger-updatable view, it will contain a
276 : * whole-row Var referring to the expanded view query.
277 : */
278 1758 : if (parse->targetList != NIL &&
279 42 : (jointype == JOIN_RIGHT || jointype == JOIN_FULL))
280 42 : parse->targetList = (List *)
281 42 : add_nulling_relids((Node *) parse->targetList,
282 42 : bms_make_singleton(parse->mergeTargetRelation),
283 42 : bms_make_singleton(joinrti));
284 :
285 : /*
286 : * If the source relation is on the outer side of the join, mark any
287 : * source relation Vars in the join condition, actions, and RETURNING list
288 : * as nullable by the join. These Vars will be added to the targetlist by
289 : * preprocess_targetlist(), so it's important to mark them correctly here.
290 : *
291 : * It might seem that this is not necessary for Vars in the join
292 : * condition, since it is inside the join, but it is also needed above the
293 : * join (in the ModifyTable node) to distinguish between the MATCHED and
294 : * NOT MATCHED BY SOURCE cases -- see ExecMergeMatched(). Note that this
295 : * creates a modified copy of the join condition, for use above the join,
296 : * without modifying the original join condition, inside the join.
297 : */
298 1758 : if (jointype == JOIN_LEFT || jointype == JOIN_FULL)
299 : {
300 126 : parse->mergeJoinCondition =
301 126 : add_nulling_relids(parse->mergeJoinCondition,
302 126 : bms_make_singleton(sourcerti),
303 126 : bms_make_singleton(joinrti));
304 :
305 600 : foreach_node(MergeAction, action, parse->mergeActionList)
306 : {
307 348 : action->qual =
308 348 : add_nulling_relids(action->qual,
309 348 : bms_make_singleton(sourcerti),
310 348 : bms_make_singleton(joinrti));
311 :
312 348 : action->targetList = (List *)
313 348 : add_nulling_relids((Node *) action->targetList,
314 348 : bms_make_singleton(sourcerti),
315 348 : bms_make_singleton(joinrti));
316 : }
317 :
318 126 : parse->returningList = (List *)
319 126 : add_nulling_relids((Node *) parse->returningList,
320 126 : bms_make_singleton(sourcerti),
321 126 : bms_make_singleton(joinrti));
322 : }
323 :
324 : /*
325 : * If there are any WHEN NOT MATCHED BY SOURCE actions, the executor will
326 : * use the join condition to distinguish between MATCHED and NOT MATCHED
327 : * BY SOURCE cases. Otherwise, it's no longer needed, and we set it to
328 : * NULL, saving cycles during planning and execution.
329 : *
330 : * We need to be careful though: the executor evaluates this condition
331 : * using the output of the join subplan node, which nulls the output from
332 : * the source relation when the join condition doesn't match. That risks
333 : * producing incorrect results when rechecking using a "non-strict" join
334 : * condition, such as "src.col IS NOT DISTINCT FROM tgt.col". To guard
335 : * against that, we add an additional "src IS NOT NULL" check to the join
336 : * condition, so that it does the right thing when performing a recheck
337 : * based on the output of the join subplan.
338 : */
339 1758 : if (have_action[MERGE_WHEN_NOT_MATCHED_BY_SOURCE])
340 : {
341 : Var *var;
342 : NullTest *ntest;
343 :
344 : /* source wholerow Var (nullable by the new join) */
345 126 : var = makeWholeRowVar(rt_fetch(sourcerti, parse->rtable),
346 : sourcerti, 0, false);
347 126 : var->varnullingrels = bms_make_singleton(joinrti);
348 :
349 : /* "src IS NOT NULL" check */
350 126 : ntest = makeNode(NullTest);
351 126 : ntest->arg = (Expr *) var;
352 126 : ntest->nulltesttype = IS_NOT_NULL;
353 126 : ntest->argisrow = false;
354 126 : ntest->location = -1;
355 :
356 : /* combine it with the original join condition */
357 126 : parse->mergeJoinCondition =
358 126 : (Node *) make_and_qual((Node *) ntest, parse->mergeJoinCondition);
359 : }
360 : else
361 1632 : parse->mergeJoinCondition = NULL; /* join condition not needed */
362 : }
363 :
364 : /*
365 : * replace_empty_jointree
366 : * If the Query's jointree is empty, replace it with a dummy RTE_RESULT
367 : * relation.
368 : *
369 : * By doing this, we can avoid a bunch of corner cases that formerly existed
370 : * for SELECTs with omitted FROM clauses. An example is that a subquery
371 : * with empty jointree previously could not be pulled up, because that would
372 : * have resulted in an empty relid set, making the subquery not uniquely
373 : * identifiable for join or PlaceHolderVar processing.
374 : *
375 : * Unlike most other functions in this file, this function doesn't recurse;
376 : * we rely on other processing to invoke it on sub-queries at suitable times.
377 : */
378 : void
379 548418 : replace_empty_jointree(Query *parse)
380 : {
381 : RangeTblEntry *rte;
382 : Index rti;
383 : RangeTblRef *rtr;
384 :
385 : /* Nothing to do if jointree is already nonempty */
386 548418 : if (parse->jointree->fromlist != NIL)
387 329476 : return;
388 :
389 : /* We mustn't change it in the top level of a setop tree, either */
390 224710 : if (parse->setOperations)
391 5768 : return;
392 :
393 : /* Create suitable RTE */
394 218942 : rte = makeNode(RangeTblEntry);
395 218942 : rte->rtekind = RTE_RESULT;
396 218942 : rte->eref = makeAlias("*RESULT*", NIL);
397 :
398 : /* Add it to rangetable */
399 218942 : parse->rtable = lappend(parse->rtable, rte);
400 218942 : rti = list_length(parse->rtable);
401 :
402 : /* And jam a reference into the jointree */
403 218942 : rtr = makeNode(RangeTblRef);
404 218942 : rtr->rtindex = rti;
405 218942 : parse->jointree->fromlist = list_make1(rtr);
406 : }
407 :
408 : /*
409 : * pull_up_sublinks
410 : * Attempt to pull up ANY and EXISTS SubLinks to be treated as
411 : * semijoins or anti-semijoins.
412 : *
413 : * A clause "foo op ANY (sub-SELECT)" can be processed by pulling the
414 : * sub-SELECT up to become a rangetable entry and treating the implied
415 : * comparisons as quals of a semijoin. However, this optimization *only*
416 : * works at the top level of WHERE or a JOIN/ON clause, because we cannot
417 : * distinguish whether the ANY ought to return FALSE or NULL in cases
418 : * involving NULL inputs. Also, in an outer join's ON clause we can only
419 : * do this if the sublink is degenerate (ie, references only the nullable
420 : * side of the join). In that case it is legal to push the semijoin
421 : * down into the nullable side of the join. If the sublink references any
422 : * nonnullable-side variables then it would have to be evaluated as part
423 : * of the outer join, which makes things way too complicated.
424 : *
425 : * Under similar conditions, EXISTS and NOT EXISTS clauses can be handled
426 : * by pulling up the sub-SELECT and creating a semijoin or anti-semijoin.
427 : *
428 : * This routine searches for such clauses and does the necessary parsetree
429 : * transformations if any are found.
430 : *
431 : * This routine has to run before preprocess_expression(), so the quals
432 : * clauses are not yet reduced to implicit-AND format, and are not guaranteed
433 : * to be AND/OR-flat either. That means we need to recursively search through
434 : * explicit AND clauses. We stop as soon as we hit a non-AND item.
435 : */
436 : void
437 32194 : pull_up_sublinks(PlannerInfo *root)
438 : {
439 : Node *jtnode;
440 : Relids relids;
441 :
442 : /* Begin recursion through the jointree */
443 32194 : jtnode = pull_up_sublinks_jointree_recurse(root,
444 32194 : (Node *) root->parse->jointree,
445 : &relids);
446 :
447 : /*
448 : * root->parse->jointree must always be a FromExpr, so insert a dummy one
449 : * if we got a bare RangeTblRef or JoinExpr out of the recursion.
450 : */
451 32194 : if (IsA(jtnode, FromExpr))
452 27892 : root->parse->jointree = (FromExpr *) jtnode;
453 : else
454 4302 : root->parse->jointree = makeFromExpr(list_make1(jtnode), NULL);
455 32194 : }
456 :
457 : /*
458 : * Recurse through jointree nodes for pull_up_sublinks()
459 : *
460 : * In addition to returning the possibly-modified jointree node, we return
461 : * a relids set of the contained rels into *relids.
462 : */
463 : static Node *
464 108072 : pull_up_sublinks_jointree_recurse(PlannerInfo *root, Node *jtnode,
465 : Relids *relids)
466 : {
467 : /* Since this function recurses, it could be driven to stack overflow. */
468 108072 : check_stack_depth();
469 :
470 108072 : if (jtnode == NULL)
471 : {
472 0 : *relids = NULL;
473 : }
474 108072 : else if (IsA(jtnode, RangeTblRef))
475 : {
476 57752 : int varno = ((RangeTblRef *) jtnode)->rtindex;
477 :
478 57752 : *relids = bms_make_singleton(varno);
479 : /* jtnode is returned unmodified */
480 : }
481 50320 : else if (IsA(jtnode, FromExpr))
482 : {
483 32386 : FromExpr *f = (FromExpr *) jtnode;
484 32386 : List *newfromlist = NIL;
485 32386 : Relids frelids = NULL;
486 : FromExpr *newf;
487 : Node *jtlink;
488 : ListCell *l;
489 :
490 : /* First, recurse to process children and collect their relids */
491 67882 : foreach(l, f->fromlist)
492 : {
493 : Node *newchild;
494 : Relids childrelids;
495 :
496 35496 : newchild = pull_up_sublinks_jointree_recurse(root,
497 35496 : lfirst(l),
498 : &childrelids);
499 35496 : newfromlist = lappend(newfromlist, newchild);
500 35496 : frelids = bms_join(frelids, childrelids);
501 : }
502 : /* Build the replacement FromExpr; no quals yet */
503 32386 : newf = makeFromExpr(newfromlist, NULL);
504 : /* Set up a link representing the rebuilt jointree */
505 32386 : jtlink = (Node *) newf;
506 : /* Now process qual --- all children are available for use */
507 32386 : newf->quals = pull_up_sublinks_qual_recurse(root, f->quals,
508 : &jtlink, frelids,
509 : NULL, NULL);
510 :
511 : /*
512 : * Note that the result will be either newf, or a stack of JoinExprs
513 : * with newf at the base. We rely on subsequent optimization steps to
514 : * flatten this and rearrange the joins as needed.
515 : *
516 : * Although we could include the pulled-up subqueries in the returned
517 : * relids, there's no need since upper quals couldn't refer to their
518 : * outputs anyway.
519 : */
520 32386 : *relids = frelids;
521 32386 : jtnode = jtlink;
522 : }
523 17934 : else if (IsA(jtnode, JoinExpr))
524 : {
525 : JoinExpr *j;
526 : Relids leftrelids;
527 : Relids rightrelids;
528 : Node *jtlink;
529 :
530 : /*
531 : * Make a modifiable copy of join node, but don't bother copying its
532 : * subnodes (yet).
533 : */
534 17934 : j = (JoinExpr *) palloc(sizeof(JoinExpr));
535 17934 : memcpy(j, jtnode, sizeof(JoinExpr));
536 17934 : jtlink = (Node *) j;
537 :
538 : /* Recurse to process children and collect their relids */
539 17934 : j->larg = pull_up_sublinks_jointree_recurse(root, j->larg,
540 : &leftrelids);
541 17934 : j->rarg = pull_up_sublinks_jointree_recurse(root, j->rarg,
542 : &rightrelids);
543 :
544 : /*
545 : * Now process qual, showing appropriate child relids as available,
546 : * and attach any pulled-up jointree items at the right place. In the
547 : * inner-join case we put new JoinExprs above the existing one (much
548 : * as for a FromExpr-style join). In outer-join cases the new
549 : * JoinExprs must go into the nullable side of the outer join. The
550 : * point of the available_rels machinations is to ensure that we only
551 : * pull up quals for which that's okay.
552 : *
553 : * We don't expect to see any pre-existing JOIN_SEMI, JOIN_ANTI,
554 : * JOIN_RIGHT_SEMI, or JOIN_RIGHT_ANTI jointypes here.
555 : */
556 17934 : switch (j->jointype)
557 : {
558 8140 : case JOIN_INNER:
559 8140 : j->quals = pull_up_sublinks_qual_recurse(root, j->quals,
560 : &jtlink,
561 : bms_union(leftrelids,
562 : rightrelids),
563 : NULL, NULL);
564 8140 : break;
565 9710 : case JOIN_LEFT:
566 9710 : j->quals = pull_up_sublinks_qual_recurse(root, j->quals,
567 : &j->rarg,
568 : rightrelids,
569 : NULL, NULL);
570 9710 : break;
571 0 : case JOIN_FULL:
572 : /* can't do anything with full-join quals */
573 0 : break;
574 84 : case JOIN_RIGHT:
575 84 : j->quals = pull_up_sublinks_qual_recurse(root, j->quals,
576 : &j->larg,
577 : leftrelids,
578 : NULL, NULL);
579 84 : break;
580 0 : default:
581 0 : elog(ERROR, "unrecognized join type: %d",
582 : (int) j->jointype);
583 : break;
584 : }
585 :
586 : /*
587 : * Although we could include the pulled-up subqueries in the returned
588 : * relids, there's no need since upper quals couldn't refer to their
589 : * outputs anyway. But we *do* need to include the join's own rtindex
590 : * because we haven't yet collapsed join alias variables, so upper
591 : * levels would mistakenly think they couldn't use references to this
592 : * join.
593 : */
594 17934 : *relids = bms_join(leftrelids, rightrelids);
595 17934 : if (j->rtindex)
596 17934 : *relids = bms_add_member(*relids, j->rtindex);
597 17934 : jtnode = jtlink;
598 : }
599 : else
600 0 : elog(ERROR, "unrecognized node type: %d",
601 : (int) nodeTag(jtnode));
602 108072 : return jtnode;
603 : }
604 :
605 : /*
606 : * Recurse through top-level qual nodes for pull_up_sublinks()
607 : *
608 : * jtlink1 points to the link in the jointree where any new JoinExprs should
609 : * be inserted if they reference available_rels1 (i.e., available_rels1
610 : * denotes the relations present underneath jtlink1). Optionally, jtlink2 can
611 : * point to a second link where new JoinExprs should be inserted if they
612 : * reference available_rels2 (pass NULL for both those arguments if not used).
613 : * Note that SubLinks referencing both sets of variables cannot be optimized.
614 : * If we find multiple pull-up-able SubLinks, they'll get stacked onto jtlink1
615 : * and/or jtlink2 in the order we encounter them. We rely on subsequent
616 : * optimization to rearrange the stack if appropriate.
617 : *
618 : * Returns the replacement qual node, or NULL if the qual should be removed.
619 : */
620 : static Node *
621 93342 : pull_up_sublinks_qual_recurse(PlannerInfo *root, Node *node,
622 : Node **jtlink1, Relids available_rels1,
623 : Node **jtlink2, Relids available_rels2)
624 : {
625 93342 : if (node == NULL)
626 6730 : return NULL;
627 86612 : if (IsA(node, SubLink))
628 : {
629 2274 : SubLink *sublink = (SubLink *) node;
630 : JoinExpr *j;
631 : Relids child_rels;
632 :
633 : /* Is it a convertible ANY or EXISTS clause? */
634 2274 : if (sublink->subLinkType == ANY_SUBLINK)
635 : {
636 1502 : if ((j = convert_ANY_sublink_to_join(root, sublink,
637 : available_rels1)) != NULL)
638 : {
639 : /* Yes; insert the new join node into the join tree */
640 1408 : j->larg = *jtlink1;
641 1408 : *jtlink1 = (Node *) j;
642 : /* Recursively process pulled-up jointree nodes */
643 1408 : j->rarg = pull_up_sublinks_jointree_recurse(root,
644 : j->rarg,
645 : &child_rels);
646 :
647 : /*
648 : * Now recursively process the pulled-up quals. Any inserted
649 : * joins can get stacked onto either j->larg or j->rarg,
650 : * depending on which rels they reference.
651 : */
652 1408 : j->quals = pull_up_sublinks_qual_recurse(root,
653 : j->quals,
654 : &j->larg,
655 : available_rels1,
656 : &j->rarg,
657 : child_rels);
658 : /* Return NULL representing constant TRUE */
659 1408 : return NULL;
660 : }
661 100 : if (available_rels2 != NULL &&
662 6 : (j = convert_ANY_sublink_to_join(root, sublink,
663 : available_rels2)) != NULL)
664 : {
665 : /* Yes; insert the new join node into the join tree */
666 0 : j->larg = *jtlink2;
667 0 : *jtlink2 = (Node *) j;
668 : /* Recursively process pulled-up jointree nodes */
669 0 : j->rarg = pull_up_sublinks_jointree_recurse(root,
670 : j->rarg,
671 : &child_rels);
672 :
673 : /*
674 : * Now recursively process the pulled-up quals. Any inserted
675 : * joins can get stacked onto either j->larg or j->rarg,
676 : * depending on which rels they reference.
677 : */
678 0 : j->quals = pull_up_sublinks_qual_recurse(root,
679 : j->quals,
680 : &j->larg,
681 : available_rels2,
682 : &j->rarg,
683 : child_rels);
684 : /* Return NULL representing constant TRUE */
685 0 : return NULL;
686 : }
687 : }
688 772 : else if (sublink->subLinkType == EXISTS_SUBLINK)
689 : {
690 712 : if ((j = convert_EXISTS_sublink_to_join(root, sublink, false,
691 : available_rels1)) != NULL)
692 : {
693 : /* Yes; insert the new join node into the join tree */
694 600 : j->larg = *jtlink1;
695 600 : *jtlink1 = (Node *) j;
696 : /* Recursively process pulled-up jointree nodes */
697 600 : j->rarg = pull_up_sublinks_jointree_recurse(root,
698 : j->rarg,
699 : &child_rels);
700 :
701 : /*
702 : * Now recursively process the pulled-up quals. Any inserted
703 : * joins can get stacked onto either j->larg or j->rarg,
704 : * depending on which rels they reference.
705 : */
706 600 : j->quals = pull_up_sublinks_qual_recurse(root,
707 : j->quals,
708 : &j->larg,
709 : available_rels1,
710 : &j->rarg,
711 : child_rels);
712 : /* Return NULL representing constant TRUE */
713 600 : return NULL;
714 : }
715 144 : if (available_rels2 != NULL &&
716 32 : (j = convert_EXISTS_sublink_to_join(root, sublink, false,
717 : available_rels2)) != NULL)
718 : {
719 : /* Yes; insert the new join node into the join tree */
720 32 : j->larg = *jtlink2;
721 32 : *jtlink2 = (Node *) j;
722 : /* Recursively process pulled-up jointree nodes */
723 32 : j->rarg = pull_up_sublinks_jointree_recurse(root,
724 : j->rarg,
725 : &child_rels);
726 :
727 : /*
728 : * Now recursively process the pulled-up quals. Any inserted
729 : * joins can get stacked onto either j->larg or j->rarg,
730 : * depending on which rels they reference.
731 : */
732 32 : j->quals = pull_up_sublinks_qual_recurse(root,
733 : j->quals,
734 : &j->larg,
735 : available_rels2,
736 : &j->rarg,
737 : child_rels);
738 : /* Return NULL representing constant TRUE */
739 32 : return NULL;
740 : }
741 : }
742 : /* Else return it unmodified */
743 234 : return node;
744 : }
745 84338 : if (is_notclause(node))
746 : {
747 : /* If the immediate argument of NOT is EXISTS, try to convert */
748 6438 : SubLink *sublink = (SubLink *) get_notclausearg((Expr *) node);
749 : JoinExpr *j;
750 : Relids child_rels;
751 :
752 6438 : if (sublink && IsA(sublink, SubLink))
753 : {
754 2584 : if (sublink->subLinkType == EXISTS_SUBLINK)
755 : {
756 2488 : if ((j = convert_EXISTS_sublink_to_join(root, sublink, true,
757 : available_rels1)) != NULL)
758 : {
759 : /* Yes; insert the new join node into the join tree */
760 2474 : j->larg = *jtlink1;
761 2474 : *jtlink1 = (Node *) j;
762 : /* Recursively process pulled-up jointree nodes */
763 2474 : j->rarg = pull_up_sublinks_jointree_recurse(root,
764 : j->rarg,
765 : &child_rels);
766 :
767 : /*
768 : * Now recursively process the pulled-up quals. Because
769 : * we are underneath a NOT, we can't pull up sublinks that
770 : * reference the left-hand stuff, but it's still okay to
771 : * pull up sublinks referencing j->rarg.
772 : */
773 2474 : j->quals = pull_up_sublinks_qual_recurse(root,
774 : j->quals,
775 : &j->rarg,
776 : child_rels,
777 : NULL, NULL);
778 : /* Return NULL representing constant TRUE */
779 2474 : return NULL;
780 : }
781 14 : if (available_rels2 != NULL &&
782 0 : (j = convert_EXISTS_sublink_to_join(root, sublink, true,
783 : available_rels2)) != NULL)
784 : {
785 : /* Yes; insert the new join node into the join tree */
786 0 : j->larg = *jtlink2;
787 0 : *jtlink2 = (Node *) j;
788 : /* Recursively process pulled-up jointree nodes */
789 0 : j->rarg = pull_up_sublinks_jointree_recurse(root,
790 : j->rarg,
791 : &child_rels);
792 :
793 : /*
794 : * Now recursively process the pulled-up quals. Because
795 : * we are underneath a NOT, we can't pull up sublinks that
796 : * reference the left-hand stuff, but it's still okay to
797 : * pull up sublinks referencing j->rarg.
798 : */
799 0 : j->quals = pull_up_sublinks_qual_recurse(root,
800 : j->quals,
801 : &j->rarg,
802 : child_rels,
803 : NULL, NULL);
804 : /* Return NULL representing constant TRUE */
805 0 : return NULL;
806 : }
807 : }
808 : }
809 : /* Else return it unmodified */
810 3964 : return node;
811 : }
812 77900 : if (is_andclause(node))
813 : {
814 : /* Recurse into AND clause */
815 13522 : List *newclauses = NIL;
816 : ListCell *l;
817 :
818 52030 : foreach(l, ((BoolExpr *) node)->args)
819 : {
820 38508 : Node *oldclause = (Node *) lfirst(l);
821 : Node *newclause;
822 :
823 38508 : newclause = pull_up_sublinks_qual_recurse(root,
824 : oldclause,
825 : jtlink1,
826 : available_rels1,
827 : jtlink2,
828 : available_rels2);
829 38508 : if (newclause)
830 35994 : newclauses = lappend(newclauses, newclause);
831 : }
832 : /* We might have got back fewer clauses than we started with */
833 13522 : if (newclauses == NIL)
834 114 : return NULL;
835 13408 : else if (list_length(newclauses) == 1)
836 1036 : return (Node *) linitial(newclauses);
837 : else
838 12372 : return (Node *) make_andclause(newclauses);
839 : }
840 : /* Stop if not an AND */
841 64378 : return node;
842 : }
843 :
844 : /*
845 : * preprocess_function_rtes
846 : * Constant-simplify any FUNCTION RTEs in the FROM clause, and then
847 : * attempt to "inline" any that are set-returning functions.
848 : *
849 : * If an RTE_FUNCTION rtable entry invokes a set-returning function that
850 : * contains just a simple SELECT, we can convert the rtable entry to an
851 : * RTE_SUBQUERY entry exposing the SELECT directly. This is especially
852 : * useful if the subquery can then be "pulled up" for further optimization,
853 : * but we do it even if not, to reduce executor overhead.
854 : *
855 : * This has to be done before we have started to do any optimization of
856 : * subqueries, else any such steps wouldn't get applied to subqueries
857 : * obtained via inlining. However, we do it after pull_up_sublinks
858 : * so that we can inline any functions used in SubLink subselects.
859 : *
860 : * The reason for applying const-simplification at this stage is that
861 : * (a) we'd need to do it anyway to inline a SRF, and (b) by doing it now,
862 : * we can be sure that pull_up_constant_function() will see constants
863 : * if there are constants to be seen. This approach also guarantees
864 : * that every FUNCTION RTE has been const-simplified, allowing planner.c's
865 : * preprocess_expression() to skip doing it again.
866 : *
867 : * Like most of the planner, this feels free to scribble on its input data
868 : * structure.
869 : */
870 : void
871 545280 : preprocess_function_rtes(PlannerInfo *root)
872 : {
873 : ListCell *rt;
874 :
875 1389134 : foreach(rt, root->parse->rtable)
876 : {
877 843860 : RangeTblEntry *rte = (RangeTblEntry *) lfirst(rt);
878 :
879 843860 : if (rte->rtekind == RTE_FUNCTION)
880 : {
881 : Query *funcquery;
882 :
883 : /* Apply const-simplification */
884 44524 : rte->functions = (List *)
885 44524 : eval_const_expressions(root, (Node *) rte->functions);
886 :
887 : /* Check safety of expansion, and expand if possible */
888 44524 : funcquery = inline_set_returning_function(root, rte);
889 44518 : if (funcquery)
890 : {
891 : /* Successful expansion, convert the RTE to a subquery */
892 210 : rte->rtekind = RTE_SUBQUERY;
893 210 : rte->subquery = funcquery;
894 210 : rte->security_barrier = false;
895 : /* Clear fields that should not be set in a subquery RTE */
896 210 : rte->functions = NIL;
897 210 : rte->funcordinality = false;
898 : }
899 : }
900 : }
901 545274 : }
902 :
903 : /*
904 : * pull_up_subqueries
905 : * Look for subqueries in the rangetable that can be pulled up into
906 : * the parent query. If the subquery has no special features like
907 : * grouping/aggregation then we can merge it into the parent's jointree.
908 : * Also, subqueries that are simple UNION ALL structures can be
909 : * converted into "append relations".
910 : */
911 : void
912 545274 : pull_up_subqueries(PlannerInfo *root)
913 : {
914 : /* Top level of jointree must always be a FromExpr */
915 : Assert(IsA(root->parse->jointree, FromExpr));
916 : /* Recursion starts with no containing join nor appendrel */
917 1090542 : root->parse->jointree = (FromExpr *)
918 545274 : pull_up_subqueries_recurse(root, (Node *) root->parse->jointree,
919 : NULL, NULL);
920 : /* We should still have a FromExpr */
921 : Assert(IsA(root->parse->jointree, FromExpr));
922 545268 : }
923 :
924 : /*
925 : * pull_up_subqueries_recurse
926 : * Recursive guts of pull_up_subqueries.
927 : *
928 : * This recursively processes the jointree and returns a modified jointree.
929 : *
930 : * If this jointree node is within either side of an outer join, then
931 : * lowest_outer_join references the lowest such JoinExpr node; otherwise
932 : * it is NULL. We use this to constrain the effects of LATERAL subqueries.
933 : *
934 : * If we are looking at a member subquery of an append relation,
935 : * containing_appendrel describes that relation; else it is NULL.
936 : * This forces use of the PlaceHolderVar mechanism for all non-Var targetlist
937 : * items, and puts some additional restrictions on what can be pulled up.
938 : *
939 : * A tricky aspect of this code is that if we pull up a subquery we have
940 : * to replace Vars that reference the subquery's outputs throughout the
941 : * parent query, including quals attached to jointree nodes above the one
942 : * we are currently processing! We handle this by being careful to maintain
943 : * validity of the jointree structure while recursing, in the following sense:
944 : * whenever we recurse, all qual expressions in the tree must be reachable
945 : * from the top level, in case the recursive call needs to modify them.
946 : *
947 : * Notice also that we can't turn pullup_replace_vars loose on the whole
948 : * jointree, because it'd return a mutated copy of the tree; we have to
949 : * invoke it just on the quals, instead. This behavior is what makes it
950 : * reasonable to pass lowest_outer_join as a pointer rather than some
951 : * more-indirect way of identifying the lowest OJ. Likewise, we don't
952 : * replace append_rel_list members but only their substructure, so the
953 : * containing_appendrel reference is safe to use.
954 : */
955 : static Node *
956 1304580 : pull_up_subqueries_recurse(PlannerInfo *root, Node *jtnode,
957 : JoinExpr *lowest_outer_join,
958 : AppendRelInfo *containing_appendrel)
959 : {
960 : /* Since this function recurses, it could be driven to stack overflow. */
961 1304580 : check_stack_depth();
962 : /* Also, since it's a bit expensive, let's check for query cancel. */
963 1304580 : CHECK_FOR_INTERRUPTS();
964 :
965 : Assert(jtnode != NULL);
966 1304580 : if (IsA(jtnode, RangeTblRef))
967 : {
968 672284 : int varno = ((RangeTblRef *) jtnode)->rtindex;
969 672284 : RangeTblEntry *rte = rt_fetch(varno, root->parse->rtable);
970 :
971 : /*
972 : * Is this a subquery RTE, and if so, is the subquery simple enough to
973 : * pull up?
974 : *
975 : * If we are looking at an append-relation member, we can't pull it up
976 : * unless is_safe_append_member says so.
977 : */
978 712392 : if (rte->rtekind == RTE_SUBQUERY &&
979 71368 : is_simple_subquery(root, rte->subquery, rte, lowest_outer_join) &&
980 3704 : (containing_appendrel == NULL ||
981 3704 : is_safe_append_member(rte->subquery)))
982 30554 : return pull_up_simple_subquery(root, jtnode, rte,
983 : lowest_outer_join,
984 : containing_appendrel);
985 :
986 : /*
987 : * Alternatively, is it a simple UNION ALL subquery? If so, flatten
988 : * into an "append relation".
989 : *
990 : * It's safe to do this regardless of whether this query is itself an
991 : * appendrel member. (If you're thinking we should try to flatten the
992 : * two levels of appendrel together, you're right; but we handle that
993 : * in set_append_rel_pathlist, not here.)
994 : */
995 651284 : if (rte->rtekind == RTE_SUBQUERY &&
996 9554 : is_simple_union_all(rte->subquery))
997 1530 : return pull_up_simple_union_all(root, jtnode, rte);
998 :
999 : /*
1000 : * Or perhaps it's a simple VALUES RTE?
1001 : *
1002 : * We don't allow VALUES pullup below an outer join nor into an
1003 : * appendrel (such cases are impossible anyway at the moment).
1004 : */
1005 640200 : if (rte->rtekind == RTE_VALUES &&
1006 9776 : lowest_outer_join == NULL &&
1007 9776 : containing_appendrel == NULL &&
1008 9776 : is_simple_values(root, rte))
1009 1868 : return pull_up_simple_values(root, jtnode, rte);
1010 :
1011 : /*
1012 : * Or perhaps it's a FUNCTION RTE that we could inline?
1013 : */
1014 638332 : if (rte->rtekind == RTE_FUNCTION)
1015 44308 : return pull_up_constant_function(root, jtnode, rte,
1016 : containing_appendrel);
1017 :
1018 : /* Otherwise, do nothing at this node. */
1019 : }
1020 632296 : else if (IsA(jtnode, FromExpr))
1021 : {
1022 551340 : FromExpr *f = (FromExpr *) jtnode;
1023 : ListCell *l;
1024 :
1025 : Assert(containing_appendrel == NULL);
1026 : /* Recursively transform all the child nodes */
1027 1144404 : foreach(l, f->fromlist)
1028 : {
1029 593070 : lfirst(l) = pull_up_subqueries_recurse(root, lfirst(l),
1030 : lowest_outer_join,
1031 : NULL);
1032 : }
1033 : }
1034 80956 : else if (IsA(jtnode, JoinExpr))
1035 : {
1036 80956 : JoinExpr *j = (JoinExpr *) jtnode;
1037 :
1038 : Assert(containing_appendrel == NULL);
1039 : /* Recurse, being careful to tell myself when inside outer join */
1040 80956 : switch (j->jointype)
1041 : {
1042 33564 : case JOIN_INNER:
1043 33564 : j->larg = pull_up_subqueries_recurse(root, j->larg,
1044 : lowest_outer_join,
1045 : NULL);
1046 33564 : j->rarg = pull_up_subqueries_recurse(root, j->rarg,
1047 : lowest_outer_join,
1048 : NULL);
1049 33564 : break;
1050 45242 : case JOIN_LEFT:
1051 : case JOIN_SEMI:
1052 : case JOIN_ANTI:
1053 45242 : j->larg = pull_up_subqueries_recurse(root, j->larg,
1054 : j,
1055 : NULL);
1056 45242 : j->rarg = pull_up_subqueries_recurse(root, j->rarg,
1057 : j,
1058 : NULL);
1059 45242 : break;
1060 1066 : case JOIN_FULL:
1061 1066 : j->larg = pull_up_subqueries_recurse(root, j->larg,
1062 : j,
1063 : NULL);
1064 1066 : j->rarg = pull_up_subqueries_recurse(root, j->rarg,
1065 : j,
1066 : NULL);
1067 1066 : break;
1068 1084 : case JOIN_RIGHT:
1069 1084 : j->larg = pull_up_subqueries_recurse(root, j->larg,
1070 : j,
1071 : NULL);
1072 1084 : j->rarg = pull_up_subqueries_recurse(root, j->rarg,
1073 : j,
1074 : NULL);
1075 1084 : break;
1076 0 : default:
1077 0 : elog(ERROR, "unrecognized join type: %d",
1078 : (int) j->jointype);
1079 : break;
1080 : }
1081 : }
1082 : else
1083 0 : elog(ERROR, "unrecognized node type: %d",
1084 : (int) nodeTag(jtnode));
1085 1226314 : return jtnode;
1086 : }
1087 :
1088 : /*
1089 : * pull_up_simple_subquery
1090 : * Attempt to pull up a single simple subquery.
1091 : *
1092 : * jtnode is a RangeTblRef that has been tentatively identified as a simple
1093 : * subquery by pull_up_subqueries. We return the replacement jointree node,
1094 : * or jtnode itself if we determine that the subquery can't be pulled up
1095 : * after all.
1096 : *
1097 : * rte is the RangeTblEntry referenced by jtnode. Remaining parameters are
1098 : * as for pull_up_subqueries_recurse.
1099 : */
1100 : static Node *
1101 30554 : pull_up_simple_subquery(PlannerInfo *root, Node *jtnode, RangeTblEntry *rte,
1102 : JoinExpr *lowest_outer_join,
1103 : AppendRelInfo *containing_appendrel)
1104 : {
1105 30554 : Query *parse = root->parse;
1106 30554 : int varno = ((RangeTblRef *) jtnode)->rtindex;
1107 : Query *subquery;
1108 : PlannerInfo *subroot;
1109 : int rtoffset;
1110 : pullup_replace_vars_context rvcontext;
1111 : ListCell *lc;
1112 :
1113 : /*
1114 : * Make a modifiable copy of the subquery to hack on, so that the RTE will
1115 : * be left unchanged in case we decide below that we can't pull it up
1116 : * after all.
1117 : */
1118 30554 : subquery = copyObject(rte->subquery);
1119 :
1120 : /*
1121 : * Create a PlannerInfo data structure for this subquery.
1122 : *
1123 : * NOTE: the next few steps should match the first processing in
1124 : * subquery_planner(). Can we refactor to avoid code duplication, or
1125 : * would that just make things uglier?
1126 : */
1127 30554 : subroot = makeNode(PlannerInfo);
1128 30554 : subroot->parse = subquery;
1129 30554 : subroot->glob = root->glob;
1130 30554 : subroot->query_level = root->query_level;
1131 30554 : subroot->parent_root = root->parent_root;
1132 30554 : subroot->plan_params = NIL;
1133 30554 : subroot->outer_params = NULL;
1134 30554 : subroot->planner_cxt = CurrentMemoryContext;
1135 30554 : subroot->init_plans = NIL;
1136 30554 : subroot->cte_plan_ids = NIL;
1137 30554 : subroot->multiexpr_params = NIL;
1138 30554 : subroot->join_domains = NIL;
1139 30554 : subroot->eq_classes = NIL;
1140 30554 : subroot->ec_merging_done = false;
1141 30554 : subroot->last_rinfo_serial = 0;
1142 30554 : subroot->all_result_relids = NULL;
1143 30554 : subroot->leaf_result_relids = NULL;
1144 30554 : subroot->append_rel_list = NIL;
1145 30554 : subroot->row_identity_vars = NIL;
1146 30554 : subroot->rowMarks = NIL;
1147 30554 : memset(subroot->upper_rels, 0, sizeof(subroot->upper_rels));
1148 30554 : memset(subroot->upper_targets, 0, sizeof(subroot->upper_targets));
1149 30554 : subroot->processed_groupClause = NIL;
1150 30554 : subroot->processed_distinctClause = NIL;
1151 30554 : subroot->processed_tlist = NIL;
1152 30554 : subroot->update_colnos = NIL;
1153 30554 : subroot->grouping_map = NULL;
1154 30554 : subroot->minmax_aggs = NIL;
1155 30554 : subroot->qual_security_level = 0;
1156 30554 : subroot->placeholdersFrozen = false;
1157 30554 : subroot->hasRecursion = false;
1158 30554 : subroot->wt_param_id = -1;
1159 30554 : subroot->non_recursive_path = NULL;
1160 : /* We don't currently need a top JoinDomain for the subroot */
1161 :
1162 : /* No CTEs to worry about */
1163 : Assert(subquery->cteList == NIL);
1164 :
1165 : /*
1166 : * If the FROM clause is empty, replace it with a dummy RTE_RESULT RTE, so
1167 : * that we don't need so many special cases to deal with that situation.
1168 : */
1169 30554 : replace_empty_jointree(subquery);
1170 :
1171 : /*
1172 : * Pull up any SubLinks within the subquery's quals, so that we don't
1173 : * leave unoptimized SubLinks behind.
1174 : */
1175 30554 : if (subquery->hasSubLinks)
1176 1950 : pull_up_sublinks(subroot);
1177 :
1178 : /*
1179 : * Similarly, preprocess its function RTEs to inline any set-returning
1180 : * functions in its rangetable.
1181 : */
1182 30554 : preprocess_function_rtes(subroot);
1183 :
1184 : /*
1185 : * Recursively pull up the subquery's subqueries, so that
1186 : * pull_up_subqueries' processing is complete for its jointree and
1187 : * rangetable.
1188 : *
1189 : * Note: it's okay that the subquery's recursion starts with NULL for
1190 : * containing-join info, even if we are within an outer join in the upper
1191 : * query; the lower query starts with a clean slate for outer-join
1192 : * semantics. Likewise, we needn't pass down appendrel state.
1193 : */
1194 30554 : pull_up_subqueries(subroot);
1195 :
1196 : /*
1197 : * Now we must recheck whether the subquery is still simple enough to pull
1198 : * up. If not, abandon processing it.
1199 : *
1200 : * We don't really need to recheck all the conditions involved, but it's
1201 : * easier just to keep this "if" looking the same as the one in
1202 : * pull_up_subqueries_recurse.
1203 : */
1204 30554 : if (is_simple_subquery(root, subquery, rte, lowest_outer_join) &&
1205 2998 : (containing_appendrel == NULL || is_safe_append_member(subquery)))
1206 : {
1207 : /* good to go */
1208 : }
1209 : else
1210 : {
1211 : /*
1212 : * Give up, return unmodified RangeTblRef.
1213 : *
1214 : * Note: The work we just did will be redone when the subquery gets
1215 : * planned on its own. Perhaps we could avoid that by storing the
1216 : * modified subquery back into the rangetable, but I'm not gonna risk
1217 : * it now.
1218 : */
1219 104 : return jtnode;
1220 : }
1221 :
1222 : /*
1223 : * We must flatten any join alias Vars in the subquery's targetlist,
1224 : * because pulling up the subquery's subqueries might have changed their
1225 : * expansions into arbitrary expressions, which could affect
1226 : * pullup_replace_vars' decisions about whether PlaceHolderVar wrappers
1227 : * are needed for tlist entries. (Likely it'd be better to do
1228 : * flatten_join_alias_vars on the whole query tree at some earlier stage,
1229 : * maybe even in the rewriter; but for now let's just fix this case here.)
1230 : */
1231 30450 : subquery->targetList = (List *)
1232 30450 : flatten_join_alias_vars(subroot, subroot->parse,
1233 30450 : (Node *) subquery->targetList);
1234 :
1235 : /*
1236 : * Adjust level-0 varnos in subquery so that we can append its rangetable
1237 : * to upper query's. We have to fix the subquery's append_rel_list as
1238 : * well.
1239 : */
1240 30450 : rtoffset = list_length(parse->rtable);
1241 30450 : OffsetVarNodes((Node *) subquery, rtoffset, 0);
1242 30450 : OffsetVarNodes((Node *) subroot->append_rel_list, rtoffset, 0);
1243 :
1244 : /*
1245 : * Upper-level vars in subquery are now one level closer to their parent
1246 : * than before.
1247 : */
1248 30450 : IncrementVarSublevelsUp((Node *) subquery, -1, 1);
1249 30450 : IncrementVarSublevelsUp((Node *) subroot->append_rel_list, -1, 1);
1250 :
1251 : /*
1252 : * The subquery's targetlist items are now in the appropriate form to
1253 : * insert into the top query, except that we may need to wrap them in
1254 : * PlaceHolderVars. Set up required context data for pullup_replace_vars.
1255 : * (Note that we should include the subquery's inner joins in relids,
1256 : * since it may include join alias vars referencing them.)
1257 : */
1258 30450 : rvcontext.root = root;
1259 30450 : rvcontext.targetlist = subquery->targetList;
1260 30450 : rvcontext.target_rte = rte;
1261 30450 : if (rte->lateral)
1262 812 : rvcontext.relids = get_relids_in_jointree((Node *) subquery->jointree,
1263 : true, true);
1264 : else /* won't need relids */
1265 29638 : rvcontext.relids = NULL;
1266 30450 : rvcontext.outer_hasSubLinks = &parse->hasSubLinks;
1267 30450 : rvcontext.varno = varno;
1268 : /* this flag will be set below, if needed */
1269 30450 : rvcontext.wrap_non_vars = false;
1270 : /* initialize cache array with indexes 0 .. length(tlist) */
1271 30450 : rvcontext.rv_cache = palloc0((list_length(subquery->targetList) + 1) *
1272 : sizeof(Node *));
1273 :
1274 : /*
1275 : * If we are dealing with an appendrel member then anything that's not a
1276 : * simple Var has to be turned into a PlaceHolderVar. We force this to
1277 : * ensure that what we pull up doesn't get merged into a surrounding
1278 : * expression during later processing and then fail to match the
1279 : * expression actually available from the appendrel.
1280 : */
1281 30450 : if (containing_appendrel != NULL)
1282 2894 : rvcontext.wrap_non_vars = true;
1283 :
1284 : /*
1285 : * If the parent query uses grouping sets, we need a PlaceHolderVar for
1286 : * anything that's not a simple Var. Again, this ensures that expressions
1287 : * retain their separate identity so that they will match grouping set
1288 : * columns when appropriate. (It'd be sufficient to wrap values used in
1289 : * grouping set columns, and do so only in non-aggregated portions of the
1290 : * tlist and havingQual, but that would require a lot of infrastructure
1291 : * that pullup_replace_vars hasn't currently got.)
1292 : */
1293 30450 : if (parse->groupingSets)
1294 320 : rvcontext.wrap_non_vars = true;
1295 :
1296 : /*
1297 : * Replace all of the top query's references to the subquery's outputs
1298 : * with copies of the adjusted subtlist items, being careful not to
1299 : * replace any of the jointree structure.
1300 : */
1301 30450 : perform_pullup_replace_vars(root, &rvcontext,
1302 : containing_appendrel);
1303 :
1304 : /*
1305 : * If the subquery had a LATERAL marker, propagate that to any of its
1306 : * child RTEs that could possibly now contain lateral cross-references.
1307 : * The children might or might not contain any actual lateral
1308 : * cross-references, but we have to mark the pulled-up child RTEs so that
1309 : * later planner stages will check for such.
1310 : */
1311 30444 : if (rte->lateral)
1312 : {
1313 1984 : foreach(lc, subquery->rtable)
1314 : {
1315 1172 : RangeTblEntry *child_rte = (RangeTblEntry *) lfirst(lc);
1316 :
1317 1172 : switch (child_rte->rtekind)
1318 : {
1319 558 : case RTE_RELATION:
1320 558 : if (child_rte->tablesample)
1321 30 : child_rte->lateral = true;
1322 558 : break;
1323 238 : case RTE_SUBQUERY:
1324 : case RTE_FUNCTION:
1325 : case RTE_VALUES:
1326 : case RTE_TABLEFUNC:
1327 238 : child_rte->lateral = true;
1328 238 : break;
1329 376 : case RTE_JOIN:
1330 : case RTE_CTE:
1331 : case RTE_NAMEDTUPLESTORE:
1332 : case RTE_RESULT:
1333 : case RTE_GROUP:
1334 : /* these can't contain any lateral references */
1335 376 : break;
1336 : }
1337 1172 : }
1338 : }
1339 :
1340 : /*
1341 : * Now append the adjusted rtable entries and their perminfos to upper
1342 : * query. (We hold off until after fixing the upper rtable entries; no
1343 : * point in running that code on the subquery ones too.)
1344 : */
1345 30444 : CombineRangeTables(&parse->rtable, &parse->rteperminfos,
1346 : subquery->rtable, subquery->rteperminfos);
1347 :
1348 : /*
1349 : * Pull up any FOR UPDATE/SHARE markers, too. (OffsetVarNodes already
1350 : * adjusted the marker rtindexes, so just concat the lists.)
1351 : */
1352 30444 : parse->rowMarks = list_concat(parse->rowMarks, subquery->rowMarks);
1353 :
1354 : /*
1355 : * We also have to fix the relid sets of any PlaceHolderVar nodes in the
1356 : * parent query. (This could perhaps be done by pullup_replace_vars(),
1357 : * but it seems cleaner to use two passes.) Note in particular that any
1358 : * PlaceHolderVar nodes just created by pullup_replace_vars() will be
1359 : * adjusted, so having created them with the subquery's varno is correct.
1360 : *
1361 : * Likewise, relids appearing in AppendRelInfo nodes have to be fixed. We
1362 : * already checked that this won't require introducing multiple subrelids
1363 : * into the single-slot AppendRelInfo structs.
1364 : */
1365 30444 : if (root->glob->lastPHId != 0 || root->append_rel_list)
1366 : {
1367 : Relids subrelids;
1368 :
1369 4390 : subrelids = get_relids_in_jointree((Node *) subquery->jointree,
1370 : true, false);
1371 4390 : if (root->glob->lastPHId != 0)
1372 1550 : substitute_phv_relids((Node *) parse, varno, subrelids);
1373 4390 : fix_append_rel_relids(root, varno, subrelids);
1374 : }
1375 :
1376 : /*
1377 : * And now add subquery's AppendRelInfos to our list.
1378 : */
1379 60888 : root->append_rel_list = list_concat(root->append_rel_list,
1380 30444 : subroot->append_rel_list);
1381 :
1382 : /*
1383 : * We don't have to do the equivalent bookkeeping for outer-join info,
1384 : * because that hasn't been set up yet. placeholder_list likewise.
1385 : */
1386 : Assert(root->join_info_list == NIL);
1387 : Assert(subroot->join_info_list == NIL);
1388 : Assert(root->placeholder_list == NIL);
1389 : Assert(subroot->placeholder_list == NIL);
1390 :
1391 : /*
1392 : * We no longer need the RTE's copy of the subquery's query tree. Getting
1393 : * rid of it saves nothing in particular so far as this level of query is
1394 : * concerned; but if this query level is in turn pulled up into a parent,
1395 : * we'd waste cycles copying the now-unused query tree.
1396 : */
1397 30444 : rte->subquery = NULL;
1398 :
1399 : /*
1400 : * Miscellaneous housekeeping.
1401 : *
1402 : * Although replace_rte_variables() faithfully updated parse->hasSubLinks
1403 : * if it copied any SubLinks out of the subquery's targetlist, we still
1404 : * could have SubLinks added to the query in the expressions of FUNCTION
1405 : * and VALUES RTEs copied up from the subquery. So it's necessary to copy
1406 : * subquery->hasSubLinks anyway. Perhaps this can be improved someday.
1407 : */
1408 30444 : parse->hasSubLinks |= subquery->hasSubLinks;
1409 :
1410 : /* If subquery had any RLS conditions, now main query does too */
1411 30444 : parse->hasRowSecurity |= subquery->hasRowSecurity;
1412 :
1413 : /*
1414 : * subquery won't be pulled up if it hasAggs, hasWindowFuncs, or
1415 : * hasTargetSRFs, so no work needed on those flags
1416 : */
1417 :
1418 : /*
1419 : * Return the adjusted subquery jointree to replace the RangeTblRef entry
1420 : * in parent's jointree; or, if the FromExpr is degenerate, just return
1421 : * its single member.
1422 : */
1423 : Assert(IsA(subquery->jointree, FromExpr));
1424 : Assert(subquery->jointree->fromlist != NIL);
1425 56092 : if (subquery->jointree->quals == NULL &&
1426 25648 : list_length(subquery->jointree->fromlist) == 1)
1427 25334 : return (Node *) linitial(subquery->jointree->fromlist);
1428 :
1429 5110 : return (Node *) subquery->jointree;
1430 : }
1431 :
1432 : /*
1433 : * pull_up_simple_union_all
1434 : * Pull up a single simple UNION ALL subquery.
1435 : *
1436 : * jtnode is a RangeTblRef that has been identified as a simple UNION ALL
1437 : * subquery by pull_up_subqueries. We pull up the leaf subqueries and
1438 : * build an "append relation" for the union set. The result value is just
1439 : * jtnode, since we don't actually need to change the query jointree.
1440 : */
1441 : static Node *
1442 1530 : pull_up_simple_union_all(PlannerInfo *root, Node *jtnode, RangeTblEntry *rte)
1443 : {
1444 1530 : int varno = ((RangeTblRef *) jtnode)->rtindex;
1445 1530 : Query *subquery = rte->subquery;
1446 1530 : int rtoffset = list_length(root->parse->rtable);
1447 : List *rtable;
1448 :
1449 : /*
1450 : * Make a modifiable copy of the subquery's rtable, so we can adjust
1451 : * upper-level Vars in it. There are no such Vars in the setOperations
1452 : * tree proper, so fixing the rtable should be sufficient.
1453 : */
1454 1530 : rtable = copyObject(subquery->rtable);
1455 :
1456 : /*
1457 : * Upper-level vars in subquery are now one level closer to their parent
1458 : * than before. We don't have to worry about offsetting varnos, though,
1459 : * because the UNION leaf queries can't cross-reference each other.
1460 : */
1461 1530 : IncrementVarSublevelsUp_rtable(rtable, -1, 1);
1462 :
1463 : /*
1464 : * If the UNION ALL subquery had a LATERAL marker, propagate that to all
1465 : * its children. The individual children might or might not contain any
1466 : * actual lateral cross-references, but we have to mark the pulled-up
1467 : * child RTEs so that later planner stages will check for such.
1468 : */
1469 1530 : if (rte->lateral)
1470 : {
1471 : ListCell *rt;
1472 :
1473 198 : foreach(rt, rtable)
1474 : {
1475 132 : RangeTblEntry *child_rte = (RangeTblEntry *) lfirst(rt);
1476 :
1477 : Assert(child_rte->rtekind == RTE_SUBQUERY);
1478 132 : child_rte->lateral = true;
1479 : }
1480 : }
1481 :
1482 : /*
1483 : * Append child RTEs (and their perminfos) to parent rtable.
1484 : */
1485 1530 : CombineRangeTables(&root->parse->rtable, &root->parse->rteperminfos,
1486 : rtable, subquery->rteperminfos);
1487 :
1488 : /*
1489 : * Recursively scan the subquery's setOperations tree and add
1490 : * AppendRelInfo nodes for leaf subqueries to the parent's
1491 : * append_rel_list. Also apply pull_up_subqueries to the leaf subqueries.
1492 : */
1493 : Assert(subquery->setOperations);
1494 1530 : pull_up_union_leaf_queries(subquery->setOperations, root, varno, subquery,
1495 : rtoffset);
1496 :
1497 : /*
1498 : * Mark the parent as an append relation.
1499 : */
1500 1530 : rte->inh = true;
1501 :
1502 1530 : return jtnode;
1503 : }
1504 :
1505 : /*
1506 : * pull_up_union_leaf_queries -- recursive guts of pull_up_simple_union_all
1507 : *
1508 : * Build an AppendRelInfo for each leaf query in the setop tree, and then
1509 : * apply pull_up_subqueries to the leaf query.
1510 : *
1511 : * Note that setOpQuery is the Query containing the setOp node, whose tlist
1512 : * contains references to all the setop output columns. When called from
1513 : * pull_up_simple_union_all, this is *not* the same as root->parse, which is
1514 : * the parent Query we are pulling up into.
1515 : *
1516 : * parentRTindex is the appendrel parent's index in root->parse->rtable.
1517 : *
1518 : * The child RTEs have already been copied to the parent. childRToffset
1519 : * tells us where in the parent's range table they were copied. When called
1520 : * from flatten_simple_union_all, childRToffset is 0 since the child RTEs
1521 : * were already in root->parse->rtable and no RT index adjustment is needed.
1522 : */
1523 : static void
1524 6794 : pull_up_union_leaf_queries(Node *setOp, PlannerInfo *root, int parentRTindex,
1525 : Query *setOpQuery, int childRToffset)
1526 : {
1527 6794 : if (IsA(setOp, RangeTblRef))
1528 : {
1529 4324 : RangeTblRef *rtr = (RangeTblRef *) setOp;
1530 : int childRTindex;
1531 : AppendRelInfo *appinfo;
1532 :
1533 : /*
1534 : * Calculate the index in the parent's range table
1535 : */
1536 4324 : childRTindex = childRToffset + rtr->rtindex;
1537 :
1538 : /*
1539 : * Build a suitable AppendRelInfo, and attach to parent's list.
1540 : */
1541 4324 : appinfo = makeNode(AppendRelInfo);
1542 4324 : appinfo->parent_relid = parentRTindex;
1543 4324 : appinfo->child_relid = childRTindex;
1544 4324 : appinfo->parent_reltype = InvalidOid;
1545 4324 : appinfo->child_reltype = InvalidOid;
1546 4324 : make_setop_translation_list(setOpQuery, childRTindex, appinfo);
1547 4324 : appinfo->parent_reloid = InvalidOid;
1548 4324 : root->append_rel_list = lappend(root->append_rel_list, appinfo);
1549 :
1550 : /*
1551 : * Recursively apply pull_up_subqueries to the new child RTE. (We
1552 : * must build the AppendRelInfo first, because this will modify it;
1553 : * indeed, that's the only part of the upper query where Vars
1554 : * referencing childRTindex can exist at this point.)
1555 : *
1556 : * Note that we can pass NULL for containing-join info even if we're
1557 : * actually under an outer join, because the child's expressions
1558 : * aren't going to propagate up to the join. Also, we ignore the
1559 : * possibility that pull_up_subqueries_recurse() returns a different
1560 : * jointree node than what we pass it; if it does, the important thing
1561 : * is that it replaced the child relid in the AppendRelInfo node.
1562 : */
1563 4324 : rtr = makeNode(RangeTblRef);
1564 4324 : rtr->rtindex = childRTindex;
1565 4324 : (void) pull_up_subqueries_recurse(root, (Node *) rtr,
1566 : NULL, appinfo);
1567 : }
1568 2470 : else if (IsA(setOp, SetOperationStmt))
1569 : {
1570 2470 : SetOperationStmt *op = (SetOperationStmt *) setOp;
1571 :
1572 : /* Recurse to reach leaf queries */
1573 2470 : pull_up_union_leaf_queries(op->larg, root, parentRTindex, setOpQuery,
1574 : childRToffset);
1575 2470 : pull_up_union_leaf_queries(op->rarg, root, parentRTindex, setOpQuery,
1576 : childRToffset);
1577 : }
1578 : else
1579 : {
1580 0 : elog(ERROR, "unrecognized node type: %d",
1581 : (int) nodeTag(setOp));
1582 : }
1583 6794 : }
1584 :
1585 : /*
1586 : * make_setop_translation_list
1587 : * Build the list of translations from parent Vars to child Vars for
1588 : * a UNION ALL member. (At this point it's just a simple list of
1589 : * referencing Vars, but if we succeed in pulling up the member
1590 : * subquery, the Vars will get replaced by pulled-up expressions.)
1591 : * Also create the rather trivial reverse-translation array.
1592 : */
1593 : static void
1594 4324 : make_setop_translation_list(Query *query, int newvarno,
1595 : AppendRelInfo *appinfo)
1596 : {
1597 4324 : List *vars = NIL;
1598 : AttrNumber *pcolnos;
1599 : ListCell *l;
1600 :
1601 : /* Initialize reverse-translation array with all entries zero */
1602 : /* (entries for resjunk columns will stay that way) */
1603 4324 : appinfo->num_child_cols = list_length(query->targetList);
1604 4324 : appinfo->parent_colnos = pcolnos =
1605 4324 : (AttrNumber *) palloc0(appinfo->num_child_cols * sizeof(AttrNumber));
1606 :
1607 13802 : foreach(l, query->targetList)
1608 : {
1609 9478 : TargetEntry *tle = (TargetEntry *) lfirst(l);
1610 :
1611 9478 : if (tle->resjunk)
1612 0 : continue;
1613 :
1614 9478 : vars = lappend(vars, makeVarFromTargetEntry(newvarno, tle));
1615 9478 : pcolnos[tle->resno - 1] = tle->resno;
1616 : }
1617 :
1618 4324 : appinfo->translated_vars = vars;
1619 4324 : }
1620 :
1621 : /*
1622 : * is_simple_subquery
1623 : * Check a subquery in the range table to see if it's simple enough
1624 : * to pull up into the parent query.
1625 : *
1626 : * rte is the RTE_SUBQUERY RangeTblEntry that contained the subquery.
1627 : * (Note subquery is not necessarily equal to rte->subquery; it could be a
1628 : * processed copy of that.)
1629 : * lowest_outer_join is the lowest outer join above the subquery, or NULL.
1630 : */
1631 : static bool
1632 70662 : is_simple_subquery(PlannerInfo *root, Query *subquery, RangeTblEntry *rte,
1633 : JoinExpr *lowest_outer_join)
1634 : {
1635 : /*
1636 : * Let's just make sure it's a valid subselect ...
1637 : */
1638 70662 : if (!IsA(subquery, Query) ||
1639 70662 : subquery->commandType != CMD_SELECT)
1640 0 : elog(ERROR, "subquery is bogus");
1641 :
1642 : /*
1643 : * Can't currently pull up a query with setops (unless it's simple UNION
1644 : * ALL, which is handled by a different code path). Maybe after querytree
1645 : * redesign...
1646 : */
1647 70662 : if (subquery->setOperations)
1648 2098 : return false;
1649 :
1650 : /*
1651 : * Can't pull up a subquery involving grouping, aggregation, SRFs,
1652 : * sorting, limiting, or WITH. (XXX WITH could possibly be allowed later)
1653 : *
1654 : * We also don't pull up a subquery that has explicit FOR UPDATE/SHARE
1655 : * clauses, because pullup would cause the locking to occur semantically
1656 : * higher than it should. Implicit FOR UPDATE/SHARE is okay because in
1657 : * that case the locking was originally declared in the upper query
1658 : * anyway.
1659 : */
1660 68564 : if (subquery->hasAggs ||
1661 67092 : subquery->hasWindowFuncs ||
1662 66720 : subquery->hasTargetSRFs ||
1663 65126 : subquery->groupClause ||
1664 65058 : subquery->groupingSets ||
1665 65058 : subquery->havingQual ||
1666 65058 : subquery->sortClause ||
1667 64234 : subquery->distinctClause ||
1668 63984 : subquery->limitOffset ||
1669 63600 : subquery->limitCount ||
1670 63332 : subquery->hasForUpdate ||
1671 62714 : subquery->cteList)
1672 6012 : return false;
1673 :
1674 : /*
1675 : * Don't pull up if the RTE represents a security-barrier view; we
1676 : * couldn't prevent information leakage once the RTE's Vars are scattered
1677 : * about in the upper query.
1678 : */
1679 62552 : if (rte->security_barrier)
1680 486 : return false;
1681 :
1682 : /*
1683 : * If the subquery is LATERAL, check for pullup restrictions from that.
1684 : */
1685 62066 : if (rte->lateral)
1686 : {
1687 : bool restricted;
1688 : Relids safe_upper_varnos;
1689 :
1690 : /*
1691 : * The subquery's WHERE and JOIN/ON quals mustn't contain any lateral
1692 : * references to rels outside a higher outer join (including the case
1693 : * where the outer join is within the subquery itself). In such a
1694 : * case, pulling up would result in a situation where we need to
1695 : * postpone quals from below an outer join to above it, which is
1696 : * probably completely wrong and in any case is a complication that
1697 : * doesn't seem worth addressing at the moment.
1698 : */
1699 1690 : if (lowest_outer_join != NULL)
1700 : {
1701 708 : restricted = true;
1702 708 : safe_upper_varnos = get_relids_in_jointree((Node *) lowest_outer_join,
1703 : true, true);
1704 : }
1705 : else
1706 : {
1707 982 : restricted = false;
1708 982 : safe_upper_varnos = NULL; /* doesn't matter */
1709 : }
1710 :
1711 1690 : if (jointree_contains_lateral_outer_refs(root,
1712 1690 : (Node *) subquery->jointree,
1713 : restricted, safe_upper_varnos))
1714 12 : return false;
1715 :
1716 : /*
1717 : * If there's an outer join above the LATERAL subquery, also disallow
1718 : * pullup if the subquery's targetlist has any references to rels
1719 : * outside the outer join, since these might get pulled into quals
1720 : * above the subquery (but in or below the outer join) and then lead
1721 : * to qual-postponement issues similar to the case checked for above.
1722 : * (We wouldn't need to prevent pullup if no such references appear in
1723 : * outer-query quals, but we don't have enough info here to check
1724 : * that. Also, maybe this restriction could be removed if we forced
1725 : * such refs to be wrapped in PlaceHolderVars, even when they're below
1726 : * the nearest outer join? But it's a pretty hokey usage, so not
1727 : * clear this is worth sweating over.)
1728 : */
1729 1678 : if (lowest_outer_join != NULL)
1730 : {
1731 708 : Relids lvarnos = pull_varnos_of_level(root,
1732 708 : (Node *) subquery->targetList,
1733 : 1);
1734 :
1735 708 : if (!bms_is_subset(lvarnos, safe_upper_varnos))
1736 12 : return false;
1737 : }
1738 : }
1739 :
1740 : /*
1741 : * Don't pull up a subquery that has any volatile functions in its
1742 : * targetlist. Otherwise we might introduce multiple evaluations of these
1743 : * functions, if they get copied to multiple places in the upper query,
1744 : * leading to surprising results. (Note: the PlaceHolderVar mechanism
1745 : * doesn't quite guarantee single evaluation; else we could pull up anyway
1746 : * and just wrap such items in PlaceHolderVars ...)
1747 : */
1748 62042 : if (contain_volatile_functions((Node *) subquery->targetList))
1749 228 : return false;
1750 :
1751 61814 : return true;
1752 : }
1753 :
1754 : /*
1755 : * pull_up_simple_values
1756 : * Pull up a single simple VALUES RTE.
1757 : *
1758 : * jtnode is a RangeTblRef that has been identified as a simple VALUES RTE
1759 : * by pull_up_subqueries. We always return a RangeTblRef representing a
1760 : * RESULT RTE to replace it (all failure cases should have been detected by
1761 : * is_simple_values()). Actually, what we return is just jtnode, because
1762 : * we replace the VALUES RTE in the rangetable with the RESULT RTE.
1763 : *
1764 : * rte is the RangeTblEntry referenced by jtnode. Because of the limited
1765 : * possible usage of VALUES RTEs, we do not need the remaining parameters
1766 : * of pull_up_subqueries_recurse.
1767 : */
1768 : static Node *
1769 1868 : pull_up_simple_values(PlannerInfo *root, Node *jtnode, RangeTblEntry *rte)
1770 : {
1771 1868 : Query *parse = root->parse;
1772 1868 : int varno = ((RangeTblRef *) jtnode)->rtindex;
1773 : List *values_list;
1774 : List *tlist;
1775 : AttrNumber attrno;
1776 : pullup_replace_vars_context rvcontext;
1777 : ListCell *lc;
1778 :
1779 : Assert(rte->rtekind == RTE_VALUES);
1780 : Assert(list_length(rte->values_lists) == 1);
1781 :
1782 : /*
1783 : * Need a modifiable copy of the VALUES list to hack on, just in case it's
1784 : * multiply referenced.
1785 : */
1786 1868 : values_list = copyObject(linitial(rte->values_lists));
1787 :
1788 : /*
1789 : * The VALUES RTE can't contain any Vars of level zero, let alone any that
1790 : * are join aliases, so no need to flatten join alias Vars.
1791 : */
1792 : Assert(!contain_vars_of_level((Node *) values_list, 0));
1793 :
1794 : /*
1795 : * Set up required context data for pullup_replace_vars. In particular,
1796 : * we have to make the VALUES list look like a subquery targetlist.
1797 : */
1798 1868 : tlist = NIL;
1799 1868 : attrno = 1;
1800 4360 : foreach(lc, values_list)
1801 : {
1802 2492 : tlist = lappend(tlist,
1803 2492 : makeTargetEntry((Expr *) lfirst(lc),
1804 : attrno,
1805 : NULL,
1806 : false));
1807 2492 : attrno++;
1808 : }
1809 1868 : rvcontext.root = root;
1810 1868 : rvcontext.targetlist = tlist;
1811 1868 : rvcontext.target_rte = rte;
1812 1868 : rvcontext.relids = NULL;
1813 1868 : rvcontext.outer_hasSubLinks = &parse->hasSubLinks;
1814 1868 : rvcontext.varno = varno;
1815 1868 : rvcontext.wrap_non_vars = false;
1816 : /* initialize cache array with indexes 0 .. length(tlist) */
1817 1868 : rvcontext.rv_cache = palloc0((list_length(tlist) + 1) *
1818 : sizeof(Node *));
1819 :
1820 : /*
1821 : * Replace all of the top query's references to the RTE's outputs with
1822 : * copies of the adjusted VALUES expressions, being careful not to replace
1823 : * any of the jointree structure. We can assume there's no outer joins or
1824 : * appendrels in the dummy Query that surrounds a VALUES RTE.
1825 : */
1826 1868 : perform_pullup_replace_vars(root, &rvcontext, NULL);
1827 :
1828 : /*
1829 : * There should be no appendrels to fix, nor any outer joins and hence no
1830 : * PlaceHolderVars.
1831 : */
1832 : Assert(root->append_rel_list == NIL);
1833 : Assert(root->join_info_list == NIL);
1834 : Assert(root->placeholder_list == NIL);
1835 :
1836 : /*
1837 : * Replace the VALUES RTE with a RESULT RTE. The VALUES RTE is the only
1838 : * rtable entry in the current query level, so this is easy.
1839 : */
1840 : Assert(list_length(parse->rtable) == 1);
1841 :
1842 : /* Create suitable RTE */
1843 1868 : rte = makeNode(RangeTblEntry);
1844 1868 : rte->rtekind = RTE_RESULT;
1845 1868 : rte->eref = makeAlias("*RESULT*", NIL);
1846 :
1847 : /* Replace rangetable */
1848 1868 : parse->rtable = list_make1(rte);
1849 :
1850 : /* We could manufacture a new RangeTblRef, but the one we have is fine */
1851 : Assert(varno == 1);
1852 :
1853 1868 : return jtnode;
1854 : }
1855 :
1856 : /*
1857 : * is_simple_values
1858 : * Check a VALUES RTE in the range table to see if it's simple enough
1859 : * to pull up into the parent query.
1860 : *
1861 : * rte is the RTE_VALUES RangeTblEntry to check.
1862 : */
1863 : static bool
1864 9776 : is_simple_values(PlannerInfo *root, RangeTblEntry *rte)
1865 : {
1866 : Assert(rte->rtekind == RTE_VALUES);
1867 :
1868 : /*
1869 : * There must be exactly one VALUES list, else it's not semantically
1870 : * correct to replace the VALUES RTE with a RESULT RTE, nor would we have
1871 : * a unique set of expressions to substitute into the parent query.
1872 : */
1873 9776 : if (list_length(rte->values_lists) != 1)
1874 7908 : return false;
1875 :
1876 : /*
1877 : * Because VALUES can't appear under an outer join (or at least, we won't
1878 : * try to pull it up if it does), we need not worry about LATERAL, nor
1879 : * about validity of PHVs for the VALUES' outputs.
1880 : */
1881 :
1882 : /*
1883 : * Don't pull up a VALUES that contains any set-returning or volatile
1884 : * functions. The considerations here are basically identical to the
1885 : * restrictions on a pull-able subquery's targetlist.
1886 : */
1887 3736 : if (expression_returns_set((Node *) rte->values_lists) ||
1888 1868 : contain_volatile_functions((Node *) rte->values_lists))
1889 0 : return false;
1890 :
1891 : /*
1892 : * Do not pull up a VALUES that's not the only RTE in its parent query.
1893 : * This is actually the only case that the parser will generate at the
1894 : * moment, and assuming this is true greatly simplifies
1895 : * pull_up_simple_values().
1896 : */
1897 1868 : if (list_length(root->parse->rtable) != 1 ||
1898 1868 : rte != (RangeTblEntry *) linitial(root->parse->rtable))
1899 0 : return false;
1900 :
1901 1868 : return true;
1902 : }
1903 :
1904 : /*
1905 : * pull_up_constant_function
1906 : * Pull up an RTE_FUNCTION expression that was simplified to a constant.
1907 : *
1908 : * jtnode is a RangeTblRef that has been identified as a FUNCTION RTE by
1909 : * pull_up_subqueries. If its expression is just a Const, hoist that value
1910 : * up into the parent query, and replace the RTE_FUNCTION with RTE_RESULT.
1911 : *
1912 : * In principle we could pull up any immutable expression, but we don't.
1913 : * That might result in multiple evaluations of the expression, which could
1914 : * be costly if it's not just a Const. Also, the main value of this is
1915 : * to let the constant participate in further const-folding, and of course
1916 : * that won't happen for a non-Const.
1917 : *
1918 : * The pulled-up value might need to be wrapped in a PlaceHolderVar if the
1919 : * RTE is below an outer join or is part of an appendrel; the extra
1920 : * parameters show whether that's needed.
1921 : */
1922 : static Node *
1923 44308 : pull_up_constant_function(PlannerInfo *root, Node *jtnode,
1924 : RangeTblEntry *rte,
1925 : AppendRelInfo *containing_appendrel)
1926 : {
1927 44308 : Query *parse = root->parse;
1928 : RangeTblFunction *rtf;
1929 : TypeFuncClass functypclass;
1930 : Oid funcrettype;
1931 : TupleDesc tupdesc;
1932 : pullup_replace_vars_context rvcontext;
1933 :
1934 : /* Fail if the RTE has ORDINALITY - we don't implement that here. */
1935 44308 : if (rte->funcordinality)
1936 698 : return jtnode;
1937 :
1938 : /* Fail if RTE isn't a single, simple Const expr */
1939 43610 : if (list_length(rte->functions) != 1)
1940 72 : return jtnode;
1941 43538 : rtf = linitial_node(RangeTblFunction, rte->functions);
1942 43538 : if (!IsA(rtf->funcexpr, Const))
1943 43166 : return jtnode;
1944 :
1945 : /*
1946 : * If the function's result is not a scalar, we punt. In principle we
1947 : * could break the composite constant value apart into per-column
1948 : * constants, but for now it seems not worth the work.
1949 : */
1950 372 : if (rtf->funccolcount != 1)
1951 30 : return jtnode; /* definitely composite */
1952 :
1953 : /* If it has a coldeflist, it certainly returns RECORD */
1954 342 : if (rtf->funccolnames != NIL)
1955 0 : return jtnode; /* must be a one-column RECORD type */
1956 :
1957 342 : functypclass = get_expr_result_type(rtf->funcexpr,
1958 : &funcrettype,
1959 : &tupdesc);
1960 342 : if (functypclass != TYPEFUNC_SCALAR)
1961 12 : return jtnode; /* must be a one-column composite type */
1962 :
1963 : /* Create context for applying pullup_replace_vars */
1964 330 : rvcontext.root = root;
1965 330 : rvcontext.targetlist = list_make1(makeTargetEntry((Expr *) rtf->funcexpr,
1966 : 1, /* resno */
1967 : NULL, /* resname */
1968 : false)); /* resjunk */
1969 330 : rvcontext.target_rte = rte;
1970 :
1971 : /*
1972 : * Since this function was reduced to a Const, it doesn't contain any
1973 : * lateral references, even if it's marked as LATERAL. This means we
1974 : * don't need to fill relids.
1975 : */
1976 330 : rvcontext.relids = NULL;
1977 :
1978 330 : rvcontext.outer_hasSubLinks = &parse->hasSubLinks;
1979 330 : rvcontext.varno = ((RangeTblRef *) jtnode)->rtindex;
1980 : /* this flag will be set below, if needed */
1981 330 : rvcontext.wrap_non_vars = false;
1982 : /* initialize cache array with indexes 0 .. length(tlist) */
1983 330 : rvcontext.rv_cache = palloc0((list_length(rvcontext.targetlist) + 1) *
1984 : sizeof(Node *));
1985 :
1986 : /*
1987 : * If we are dealing with an appendrel member then anything that's not a
1988 : * simple Var has to be turned into a PlaceHolderVar. (See comments in
1989 : * pull_up_simple_subquery().)
1990 : */
1991 330 : if (containing_appendrel != NULL)
1992 0 : rvcontext.wrap_non_vars = true;
1993 :
1994 : /*
1995 : * If the parent query uses grouping sets, we need a PlaceHolderVar for
1996 : * anything that's not a simple Var.
1997 : */
1998 330 : if (parse->groupingSets)
1999 0 : rvcontext.wrap_non_vars = true;
2000 :
2001 : /*
2002 : * Replace all of the top query's references to the RTE's output with
2003 : * copies of the funcexpr, being careful not to replace any of the
2004 : * jointree structure.
2005 : */
2006 330 : perform_pullup_replace_vars(root, &rvcontext,
2007 : containing_appendrel);
2008 :
2009 : /*
2010 : * We don't need to bother with changing PlaceHolderVars in the parent
2011 : * query. Their references to the RT index are still good for now, and
2012 : * will get removed later if we're able to drop the RTE_RESULT.
2013 : */
2014 :
2015 : /*
2016 : * Convert the RTE to be RTE_RESULT type, signifying that we don't need to
2017 : * scan it anymore, and zero out RTE_FUNCTION-specific fields. Also make
2018 : * sure the RTE is not marked LATERAL, since elsewhere we don't expect
2019 : * RTE_RESULTs to be LATERAL.
2020 : */
2021 330 : rte->rtekind = RTE_RESULT;
2022 330 : rte->functions = NIL;
2023 330 : rte->lateral = false;
2024 :
2025 : /*
2026 : * We can reuse the RangeTblRef node.
2027 : */
2028 330 : return jtnode;
2029 : }
2030 :
2031 : /*
2032 : * is_simple_union_all
2033 : * Check a subquery to see if it's a simple UNION ALL.
2034 : *
2035 : * We require all the setops to be UNION ALL (no mixing) and there can't be
2036 : * any datatype coercions involved, ie, all the leaf queries must emit the
2037 : * same datatypes.
2038 : */
2039 : static bool
2040 9554 : is_simple_union_all(Query *subquery)
2041 : {
2042 : SetOperationStmt *topop;
2043 :
2044 : /* Let's just make sure it's a valid subselect ... */
2045 9554 : if (!IsA(subquery, Query) ||
2046 9554 : subquery->commandType != CMD_SELECT)
2047 0 : elog(ERROR, "subquery is bogus");
2048 :
2049 : /* Is it a set-operation query at all? */
2050 9554 : topop = castNode(SetOperationStmt, subquery->setOperations);
2051 9554 : if (!topop)
2052 7456 : return false;
2053 :
2054 : /* Can't handle ORDER BY, LIMIT/OFFSET, locking, or WITH */
2055 2098 : if (subquery->sortClause ||
2056 2058 : subquery->limitOffset ||
2057 2058 : subquery->limitCount ||
2058 2058 : subquery->rowMarks ||
2059 2058 : subquery->cteList)
2060 132 : return false;
2061 :
2062 : /* Recursively check the tree of set operations */
2063 1966 : return is_simple_union_all_recurse((Node *) topop, subquery,
2064 : topop->colTypes);
2065 : }
2066 :
2067 : static bool
2068 13298 : is_simple_union_all_recurse(Node *setOp, Query *setOpQuery, List *colTypes)
2069 : {
2070 : /* Since this function recurses, it could be driven to stack overflow. */
2071 13298 : check_stack_depth();
2072 :
2073 13298 : if (IsA(setOp, RangeTblRef))
2074 : {
2075 5362 : RangeTblRef *rtr = (RangeTblRef *) setOp;
2076 5362 : RangeTblEntry *rte = rt_fetch(rtr->rtindex, setOpQuery->rtable);
2077 5362 : Query *subquery = rte->subquery;
2078 :
2079 : Assert(subquery != NULL);
2080 :
2081 : /* Leaf nodes are OK if they match the toplevel column types */
2082 : /* We don't have to compare typmods or collations here */
2083 5362 : return tlist_same_datatypes(subquery->targetList, colTypes, true);
2084 : }
2085 7936 : else if (IsA(setOp, SetOperationStmt))
2086 : {
2087 7936 : SetOperationStmt *op = (SetOperationStmt *) setOp;
2088 :
2089 : /* Must be UNION ALL */
2090 7936 : if (op->op != SETOP_UNION || !op->all)
2091 4500 : return false;
2092 :
2093 : /* Recurse to check inputs */
2094 6376 : return is_simple_union_all_recurse(op->larg, setOpQuery, colTypes) &&
2095 2940 : is_simple_union_all_recurse(op->rarg, setOpQuery, colTypes);
2096 : }
2097 : else
2098 : {
2099 0 : elog(ERROR, "unrecognized node type: %d",
2100 : (int) nodeTag(setOp));
2101 : return false; /* keep compiler quiet */
2102 : }
2103 : }
2104 :
2105 : /*
2106 : * is_safe_append_member
2107 : * Check a subquery that is a leaf of a UNION ALL appendrel to see if it's
2108 : * safe to pull up.
2109 : */
2110 : static bool
2111 6702 : is_safe_append_member(Query *subquery)
2112 : {
2113 : FromExpr *jtnode;
2114 :
2115 : /*
2116 : * It's only safe to pull up the child if its jointree contains exactly
2117 : * one RTE, else the AppendRelInfo data structure breaks. The one base RTE
2118 : * could be buried in several levels of FromExpr, however. Also, if the
2119 : * child's jointree is completely empty, we can pull up because
2120 : * pull_up_simple_subquery will insert a single RTE_RESULT RTE instead.
2121 : *
2122 : * Also, the child can't have any WHERE quals because there's no place to
2123 : * put them in an appendrel. (This is a bit annoying...) If we didn't
2124 : * need to check this, we'd just test whether get_relids_in_jointree()
2125 : * yields a singleton set, to be more consistent with the coding of
2126 : * fix_append_rel_relids().
2127 : */
2128 6702 : jtnode = subquery->jointree;
2129 : Assert(IsA(jtnode, FromExpr));
2130 : /* Check the completely-empty case */
2131 6702 : if (jtnode->fromlist == NIL && jtnode->quals == NULL)
2132 542 : return true;
2133 : /* Check the more general case */
2134 11664 : while (IsA(jtnode, FromExpr))
2135 : {
2136 6172 : if (jtnode->quals != NULL)
2137 668 : return false;
2138 5504 : if (list_length(jtnode->fromlist) != 1)
2139 0 : return false;
2140 5504 : jtnode = linitial(jtnode->fromlist);
2141 : }
2142 5492 : if (!IsA(jtnode, RangeTblRef))
2143 142 : return false;
2144 :
2145 5350 : return true;
2146 : }
2147 :
2148 : /*
2149 : * jointree_contains_lateral_outer_refs
2150 : * Check for disallowed lateral references in a jointree's quals
2151 : *
2152 : * If restricted is false, all level-1 Vars are allowed (but we still must
2153 : * search the jointree, since it might contain outer joins below which there
2154 : * will be restrictions). If restricted is true, return true when any qual
2155 : * in the jointree contains level-1 Vars coming from outside the rels listed
2156 : * in safe_upper_varnos.
2157 : */
2158 : static bool
2159 3834 : jointree_contains_lateral_outer_refs(PlannerInfo *root, Node *jtnode,
2160 : bool restricted,
2161 : Relids safe_upper_varnos)
2162 : {
2163 3834 : if (jtnode == NULL)
2164 0 : return false;
2165 3834 : if (IsA(jtnode, RangeTblRef))
2166 1842 : return false;
2167 1992 : else if (IsA(jtnode, FromExpr))
2168 : {
2169 1714 : FromExpr *f = (FromExpr *) jtnode;
2170 : ListCell *l;
2171 :
2172 : /* First, recurse to check child joins */
2173 3290 : foreach(l, f->fromlist)
2174 : {
2175 1588 : if (jointree_contains_lateral_outer_refs(root,
2176 1588 : lfirst(l),
2177 : restricted,
2178 : safe_upper_varnos))
2179 12 : return true;
2180 : }
2181 :
2182 : /* Then check the top-level quals */
2183 1702 : if (restricted &&
2184 732 : !bms_is_subset(pull_varnos_of_level(root, f->quals, 1),
2185 : safe_upper_varnos))
2186 0 : return true;
2187 : }
2188 278 : else if (IsA(jtnode, JoinExpr))
2189 : {
2190 278 : JoinExpr *j = (JoinExpr *) jtnode;
2191 :
2192 : /*
2193 : * If this is an outer join, we mustn't allow any upper lateral
2194 : * references in or below it.
2195 : */
2196 278 : if (j->jointype != JOIN_INNER)
2197 : {
2198 134 : restricted = true;
2199 134 : safe_upper_varnos = NULL;
2200 : }
2201 :
2202 : /* Check the child joins */
2203 278 : if (jointree_contains_lateral_outer_refs(root,
2204 : j->larg,
2205 : restricted,
2206 : safe_upper_varnos))
2207 0 : return true;
2208 278 : if (jointree_contains_lateral_outer_refs(root,
2209 : j->rarg,
2210 : restricted,
2211 : safe_upper_varnos))
2212 0 : return true;
2213 :
2214 : /* Check the JOIN's qual clauses */
2215 278 : if (restricted &&
2216 254 : !bms_is_subset(pull_varnos_of_level(root, j->quals, 1),
2217 : safe_upper_varnos))
2218 12 : return true;
2219 : }
2220 : else
2221 0 : elog(ERROR, "unrecognized node type: %d",
2222 : (int) nodeTag(jtnode));
2223 1968 : return false;
2224 : }
2225 :
2226 : /*
2227 : * Perform pullup_replace_vars everyplace it's needed in the query tree.
2228 : *
2229 : * Caller has already filled *rvcontext with data describing what to
2230 : * substitute for Vars referencing the target subquery. In addition
2231 : * we need the identity of the containing appendrel if any.
2232 : */
2233 : static void
2234 32648 : perform_pullup_replace_vars(PlannerInfo *root,
2235 : pullup_replace_vars_context *rvcontext,
2236 : AppendRelInfo *containing_appendrel)
2237 : {
2238 32648 : Query *parse = root->parse;
2239 : ListCell *lc;
2240 :
2241 : /*
2242 : * If we are considering an appendrel child subquery (that is, a UNION ALL
2243 : * member query that we're pulling up), then the only part of the upper
2244 : * query that could reference the child yet is the translated_vars list of
2245 : * the associated AppendRelInfo. Furthermore, we do not want to force use
2246 : * of PHVs in the AppendRelInfo --- there isn't any outer join between.
2247 : */
2248 32648 : if (containing_appendrel)
2249 : {
2250 2894 : bool save_wrap_non_vars = rvcontext->wrap_non_vars;
2251 :
2252 2894 : rvcontext->wrap_non_vars = false;
2253 2894 : containing_appendrel->translated_vars = (List *)
2254 2894 : pullup_replace_vars((Node *) containing_appendrel->translated_vars,
2255 : rvcontext);
2256 2894 : rvcontext->wrap_non_vars = save_wrap_non_vars;
2257 2894 : return;
2258 : }
2259 :
2260 : /*
2261 : * Replace all of the top query's references to the subquery's outputs
2262 : * with copies of the adjusted subtlist items, being careful not to
2263 : * replace any of the jointree structure. (This'd be a lot cleaner if we
2264 : * could use query_tree_mutator.) We have to use PHVs in the targetList,
2265 : * returningList, and havingQual, since those are certainly above any
2266 : * outer join. replace_vars_in_jointree tracks its location in the
2267 : * jointree and uses PHVs or not appropriately.
2268 : */
2269 29754 : parse->targetList = (List *)
2270 29754 : pullup_replace_vars((Node *) parse->targetList, rvcontext);
2271 29754 : parse->returningList = (List *)
2272 29754 : pullup_replace_vars((Node *) parse->returningList, rvcontext);
2273 :
2274 29754 : if (parse->onConflict)
2275 : {
2276 44 : parse->onConflict->onConflictSet = (List *)
2277 22 : pullup_replace_vars((Node *) parse->onConflict->onConflictSet,
2278 : rvcontext);
2279 22 : parse->onConflict->onConflictWhere =
2280 22 : pullup_replace_vars(parse->onConflict->onConflictWhere,
2281 : rvcontext);
2282 :
2283 : /*
2284 : * We assume ON CONFLICT's arbiterElems, arbiterWhere, exclRelTlist
2285 : * can't contain any references to a subquery.
2286 : */
2287 : }
2288 29754 : if (parse->mergeActionList)
2289 : {
2290 2708 : foreach(lc, parse->mergeActionList)
2291 : {
2292 1610 : MergeAction *action = lfirst(lc);
2293 :
2294 1610 : action->qual = pullup_replace_vars(action->qual, rvcontext);
2295 1610 : action->targetList = (List *)
2296 1610 : pullup_replace_vars((Node *) action->targetList, rvcontext);
2297 : }
2298 : }
2299 29754 : parse->mergeJoinCondition = pullup_replace_vars(parse->mergeJoinCondition,
2300 : rvcontext);
2301 29754 : replace_vars_in_jointree((Node *) parse->jointree, rvcontext);
2302 : Assert(parse->setOperations == NULL);
2303 29748 : parse->havingQual = pullup_replace_vars(parse->havingQual, rvcontext);
2304 :
2305 : /*
2306 : * Replace references in the translated_vars lists of appendrels.
2307 : */
2308 29760 : foreach(lc, root->append_rel_list)
2309 : {
2310 12 : AppendRelInfo *appinfo = (AppendRelInfo *) lfirst(lc);
2311 :
2312 12 : appinfo->translated_vars = (List *)
2313 12 : pullup_replace_vars((Node *) appinfo->translated_vars, rvcontext);
2314 : }
2315 :
2316 : /*
2317 : * Replace references in the joinaliasvars lists of join RTEs and the
2318 : * groupexprs list of group RTE.
2319 : */
2320 83904 : foreach(lc, parse->rtable)
2321 : {
2322 54156 : RangeTblEntry *otherrte = (RangeTblEntry *) lfirst(lc);
2323 :
2324 54156 : if (otherrte->rtekind == RTE_JOIN)
2325 5414 : otherrte->joinaliasvars = (List *)
2326 5414 : pullup_replace_vars((Node *) otherrte->joinaliasvars,
2327 : rvcontext);
2328 48742 : else if (otherrte->rtekind == RTE_GROUP)
2329 706 : otherrte->groupexprs = (List *)
2330 706 : pullup_replace_vars((Node *) otherrte->groupexprs,
2331 : rvcontext);
2332 : }
2333 : }
2334 :
2335 : /*
2336 : * Helper routine for perform_pullup_replace_vars: do pullup_replace_vars on
2337 : * every expression in the jointree, without changing the jointree structure
2338 : * itself. Ugly, but there's no other way...
2339 : */
2340 : static void
2341 77232 : replace_vars_in_jointree(Node *jtnode,
2342 : pullup_replace_vars_context *context)
2343 : {
2344 77232 : if (jtnode == NULL)
2345 0 : return;
2346 77232 : if (IsA(jtnode, RangeTblRef))
2347 : {
2348 : /*
2349 : * If the RangeTblRef refers to a LATERAL subquery (that isn't the
2350 : * same subquery we're pulling up), it might contain references to the
2351 : * target subquery, which we must replace. We drive this from the
2352 : * jointree scan, rather than a scan of the rtable, so that we can
2353 : * avoid processing no-longer-referenced RTEs.
2354 : */
2355 38792 : int varno = ((RangeTblRef *) jtnode)->rtindex;
2356 :
2357 38792 : if (varno != context->varno) /* ignore target subquery itself */
2358 : {
2359 9038 : RangeTblEntry *rte = rt_fetch(varno, context->root->parse->rtable);
2360 :
2361 : Assert(rte != context->target_rte);
2362 9038 : if (rte->lateral)
2363 : {
2364 828 : switch (rte->rtekind)
2365 : {
2366 0 : case RTE_RELATION:
2367 : /* shouldn't be marked LATERAL unless tablesample */
2368 : Assert(rte->tablesample);
2369 0 : rte->tablesample = (TableSampleClause *)
2370 0 : pullup_replace_vars((Node *) rte->tablesample,
2371 : context);
2372 0 : break;
2373 384 : case RTE_SUBQUERY:
2374 384 : rte->subquery =
2375 384 : pullup_replace_vars_subquery(rte->subquery,
2376 : context);
2377 384 : break;
2378 336 : case RTE_FUNCTION:
2379 336 : rte->functions = (List *)
2380 336 : pullup_replace_vars((Node *) rte->functions,
2381 : context);
2382 336 : break;
2383 108 : case RTE_TABLEFUNC:
2384 108 : rte->tablefunc = (TableFunc *)
2385 108 : pullup_replace_vars((Node *) rte->tablefunc,
2386 : context);
2387 108 : break;
2388 0 : case RTE_VALUES:
2389 0 : rte->values_lists = (List *)
2390 0 : pullup_replace_vars((Node *) rte->values_lists,
2391 : context);
2392 0 : break;
2393 0 : case RTE_JOIN:
2394 : case RTE_CTE:
2395 : case RTE_NAMEDTUPLESTORE:
2396 : case RTE_RESULT:
2397 : case RTE_GROUP:
2398 : /* these shouldn't be marked LATERAL */
2399 : Assert(false);
2400 0 : break;
2401 : }
2402 38792 : }
2403 : }
2404 : }
2405 38440 : else if (IsA(jtnode, FromExpr))
2406 : {
2407 32070 : FromExpr *f = (FromExpr *) jtnode;
2408 : ListCell *l;
2409 :
2410 66808 : foreach(l, f->fromlist)
2411 34738 : replace_vars_in_jointree(lfirst(l), context);
2412 32070 : f->quals = pullup_replace_vars(f->quals, context);
2413 : }
2414 6370 : else if (IsA(jtnode, JoinExpr))
2415 : {
2416 6370 : JoinExpr *j = (JoinExpr *) jtnode;
2417 6370 : bool save_wrap_non_vars = context->wrap_non_vars;
2418 :
2419 6370 : replace_vars_in_jointree(j->larg, context);
2420 6370 : replace_vars_in_jointree(j->rarg, context);
2421 :
2422 : /*
2423 : * Use PHVs within the join quals of a full join. Otherwise, we
2424 : * cannot identify which side of the join a pulled-up var-free
2425 : * expression came from, which can lead to failure to make a plan at
2426 : * all because none of the quals appear to be mergeable or hashable
2427 : * conditions.
2428 : */
2429 6370 : if (j->jointype == JOIN_FULL)
2430 610 : context->wrap_non_vars = true;
2431 :
2432 6370 : j->quals = pullup_replace_vars(j->quals, context);
2433 :
2434 6370 : context->wrap_non_vars = save_wrap_non_vars;
2435 : }
2436 : else
2437 0 : elog(ERROR, "unrecognized node type: %d",
2438 : (int) nodeTag(jtnode));
2439 : }
2440 :
2441 : /*
2442 : * Apply pullup variable replacement throughout an expression tree
2443 : *
2444 : * Returns a modified copy of the tree, so this can't be used where we
2445 : * need to do in-place replacement.
2446 : */
2447 : static Node *
2448 170184 : pullup_replace_vars(Node *expr, pullup_replace_vars_context *context)
2449 : {
2450 170184 : return replace_rte_variables(expr,
2451 : context->varno, 0,
2452 : pullup_replace_vars_callback,
2453 : (void *) context,
2454 : context->outer_hasSubLinks);
2455 : }
2456 :
2457 : static Node *
2458 99656 : pullup_replace_vars_callback(Var *var,
2459 : replace_rte_variables_context *context)
2460 : {
2461 99656 : pullup_replace_vars_context *rcon = (pullup_replace_vars_context *) context->callback_arg;
2462 99656 : int varattno = var->varattno;
2463 : bool need_phv;
2464 : Node *newnode;
2465 :
2466 : /*
2467 : * We need a PlaceHolderVar if the Var-to-be-replaced has nonempty
2468 : * varnullingrels (unless we find below that the replacement expression is
2469 : * a Var or PlaceHolderVar that we can just add the nullingrels to). We
2470 : * also need one if the caller has instructed us that all non-Var/PHV
2471 : * replacements need to be wrapped for identification purposes.
2472 : */
2473 99656 : need_phv = (var->varnullingrels != NULL) || rcon->wrap_non_vars;
2474 :
2475 : /*
2476 : * If PlaceHolderVars are needed, we cache the modified expressions in
2477 : * rcon->rv_cache[]. This is not in hopes of any material speed gain
2478 : * within this function, but to avoid generating identical PHVs with
2479 : * different IDs. That would result in duplicate evaluations at runtime,
2480 : * and possibly prevent optimizations that rely on recognizing different
2481 : * references to the same subquery output as being equal(). So it's worth
2482 : * a bit of extra effort to avoid it.
2483 : *
2484 : * The cached items have phlevelsup = 0 and phnullingrels = NULL; we'll
2485 : * copy them and adjust those values for this reference site below.
2486 : */
2487 99656 : if (need_phv &&
2488 12828 : varattno >= InvalidAttrNumber &&
2489 12828 : varattno <= list_length(rcon->targetlist) &&
2490 12828 : rcon->rv_cache[varattno] != NULL)
2491 : {
2492 : /* Just copy the entry and fall through to adjust phlevelsup etc */
2493 1910 : newnode = copyObject(rcon->rv_cache[varattno]);
2494 : }
2495 97746 : else if (varattno == InvalidAttrNumber)
2496 : {
2497 : /* Must expand whole-tuple reference into RowExpr */
2498 : RowExpr *rowexpr;
2499 : List *colnames;
2500 : List *fields;
2501 544 : bool save_wrap_non_vars = rcon->wrap_non_vars;
2502 544 : int save_sublevelsup = context->sublevels_up;
2503 :
2504 : /*
2505 : * If generating an expansion for a var of a named rowtype (ie, this
2506 : * is a plain relation RTE), then we must include dummy items for
2507 : * dropped columns. If the var is RECORD (ie, this is a JOIN), then
2508 : * omit dropped columns. In the latter case, attach column names to
2509 : * the RowExpr for use of the executor and ruleutils.c.
2510 : *
2511 : * In order to be able to cache the results, we always generate the
2512 : * expansion with varlevelsup = 0, and then adjust below if needed.
2513 : */
2514 544 : expandRTE(rcon->target_rte,
2515 : var->varno, 0 /* not varlevelsup */ , var->location,
2516 544 : (var->vartype != RECORDOID),
2517 : &colnames, &fields);
2518 : /* Expand the generated per-field Vars, but don't insert PHVs there */
2519 544 : rcon->wrap_non_vars = false;
2520 544 : context->sublevels_up = 0; /* to match the expandRTE output */
2521 544 : fields = (List *) replace_rte_variables_mutator((Node *) fields,
2522 : context);
2523 544 : rcon->wrap_non_vars = save_wrap_non_vars;
2524 544 : context->sublevels_up = save_sublevelsup;
2525 :
2526 544 : rowexpr = makeNode(RowExpr);
2527 544 : rowexpr->args = fields;
2528 544 : rowexpr->row_typeid = var->vartype;
2529 544 : rowexpr->row_format = COERCE_IMPLICIT_CAST;
2530 544 : rowexpr->colnames = (var->vartype == RECORDOID) ? colnames : NIL;
2531 544 : rowexpr->location = var->location;
2532 544 : newnode = (Node *) rowexpr;
2533 :
2534 : /*
2535 : * Insert PlaceHolderVar if needed. Notice that we are wrapping one
2536 : * PlaceHolderVar around the whole RowExpr, rather than putting one
2537 : * around each element of the row. This is because we need the
2538 : * expression to yield NULL, not ROW(NULL,NULL,...) when it is forced
2539 : * to null by an outer join.
2540 : */
2541 544 : if (need_phv)
2542 : {
2543 : newnode = (Node *)
2544 66 : make_placeholder_expr(rcon->root,
2545 : (Expr *) newnode,
2546 : bms_make_singleton(rcon->varno));
2547 : /* cache it with the PHV, and with phlevelsup etc not set yet */
2548 66 : rcon->rv_cache[InvalidAttrNumber] = copyObject(newnode);
2549 : }
2550 : }
2551 : else
2552 : {
2553 : /* Normal case referencing one targetlist element */
2554 97202 : TargetEntry *tle = get_tle_by_resno(rcon->targetlist, varattno);
2555 :
2556 97202 : if (tle == NULL) /* shouldn't happen */
2557 0 : elog(ERROR, "could not find attribute %d in subquery targetlist",
2558 : varattno);
2559 :
2560 : /* Make a copy of the tlist item to return */
2561 97202 : newnode = (Node *) copyObject(tle->expr);
2562 :
2563 : /* Insert PlaceHolderVar if needed */
2564 97202 : if (need_phv)
2565 : {
2566 : bool wrap;
2567 :
2568 10852 : if (newnode && IsA(newnode, Var) &&
2569 9126 : ((Var *) newnode)->varlevelsup == 0)
2570 : {
2571 : /*
2572 : * Simple Vars always escape being wrapped, unless they are
2573 : * lateral references to something outside the subquery being
2574 : * pulled up. (Even then, we could omit the PlaceHolderVar if
2575 : * the referenced rel is under the same lowest outer join, but
2576 : * it doesn't seem worth the trouble to check that.)
2577 : */
2578 9110 : if (rcon->target_rte->lateral &&
2579 954 : !bms_is_member(((Var *) newnode)->varno, rcon->relids))
2580 78 : wrap = true;
2581 : else
2582 9032 : wrap = false;
2583 : }
2584 1742 : else if (newnode && IsA(newnode, PlaceHolderVar) &&
2585 144 : ((PlaceHolderVar *) newnode)->phlevelsup == 0)
2586 : {
2587 : /* The same rules apply for a PlaceHolderVar */
2588 144 : if (rcon->target_rte->lateral &&
2589 12 : !bms_is_subset(((PlaceHolderVar *) newnode)->phrels,
2590 12 : rcon->relids))
2591 12 : wrap = true;
2592 : else
2593 132 : wrap = false;
2594 : }
2595 1598 : else if (rcon->wrap_non_vars)
2596 : {
2597 : /* Caller told us to wrap all non-Vars in a PlaceHolderVar */
2598 188 : wrap = true;
2599 : }
2600 : else
2601 : {
2602 : /*
2603 : * If the node contains Var(s) or PlaceHolderVar(s) of the
2604 : * subquery being pulled up, and does not contain any
2605 : * non-strict constructs, then instead of adding a PHV on top
2606 : * we can add the required nullingrels to those Vars/PHVs.
2607 : * (This is fundamentally a generalization of the above cases
2608 : * for bare Vars and PHVs.)
2609 : *
2610 : * This test is somewhat expensive, but it avoids pessimizing
2611 : * the plan in cases where the nullingrels get removed again
2612 : * later by outer join reduction.
2613 : *
2614 : * This analysis could be tighter: in particular, a non-strict
2615 : * construct hidden within a lower-level PlaceHolderVar is not
2616 : * reason to add another PHV. But for now it doesn't seem
2617 : * worth the code to be more exact.
2618 : *
2619 : * For a LATERAL subquery, we have to check the actual var
2620 : * membership of the node, but if it's non-lateral then any
2621 : * level-zero var must belong to the subquery.
2622 : */
2623 1542 : if ((rcon->target_rte->lateral ?
2624 132 : bms_overlap(pull_varnos(rcon->root, newnode),
2625 132 : rcon->relids) :
2626 1278 : contain_vars_of_level(newnode, 0)) &&
2627 348 : !contain_nonstrict_functions(newnode))
2628 : {
2629 : /* No wrap needed */
2630 108 : wrap = false;
2631 : }
2632 : else
2633 : {
2634 : /* Else wrap it in a PlaceHolderVar */
2635 1302 : wrap = true;
2636 : }
2637 : }
2638 :
2639 10852 : if (wrap)
2640 : {
2641 : newnode = (Node *)
2642 1580 : make_placeholder_expr(rcon->root,
2643 : (Expr *) newnode,
2644 : bms_make_singleton(rcon->varno));
2645 :
2646 : /*
2647 : * Cache it if possible (ie, if the attno is in range, which
2648 : * it probably always should be).
2649 : */
2650 3160 : if (varattno > InvalidAttrNumber &&
2651 1580 : varattno <= list_length(rcon->targetlist))
2652 1580 : rcon->rv_cache[varattno] = copyObject(newnode);
2653 : }
2654 : }
2655 : }
2656 :
2657 : /* Propagate any varnullingrels into the replacement expression */
2658 99656 : if (var->varnullingrels != NULL)
2659 : {
2660 10952 : if (IsA(newnode, Var))
2661 : {
2662 7426 : Var *newvar = (Var *) newnode;
2663 :
2664 : Assert(newvar->varlevelsup == 0);
2665 7426 : newvar->varnullingrels = bms_add_members(newvar->varnullingrels,
2666 7426 : var->varnullingrels);
2667 : }
2668 3526 : else if (IsA(newnode, PlaceHolderVar))
2669 : {
2670 3418 : PlaceHolderVar *newphv = (PlaceHolderVar *) newnode;
2671 :
2672 : Assert(newphv->phlevelsup == 0);
2673 3418 : newphv->phnullingrels = bms_add_members(newphv->phnullingrels,
2674 3418 : var->varnullingrels);
2675 : }
2676 : else
2677 : {
2678 : /* There should be lower-level Vars/PHVs we can modify */
2679 108 : newnode = add_nulling_relids(newnode,
2680 : NULL, /* modify all Vars/PHVs */
2681 108 : var->varnullingrels);
2682 : /* Assert we did put the varnullingrels into the expression */
2683 : Assert(bms_is_subset(var->varnullingrels,
2684 : pull_varnos(rcon->root, newnode)));
2685 : }
2686 : }
2687 :
2688 : /* Must adjust varlevelsup if replaced Var is within a subquery */
2689 99656 : if (var->varlevelsup > 0)
2690 982 : IncrementVarSublevelsUp(newnode, var->varlevelsup, 0);
2691 :
2692 99656 : return newnode;
2693 : }
2694 :
2695 : /*
2696 : * Apply pullup variable replacement to a subquery
2697 : *
2698 : * This needs to be different from pullup_replace_vars() because
2699 : * replace_rte_variables will think that it shouldn't increment sublevels_up
2700 : * before entering the Query; so we need to call it with sublevels_up == 1.
2701 : */
2702 : static Query *
2703 384 : pullup_replace_vars_subquery(Query *query,
2704 : pullup_replace_vars_context *context)
2705 : {
2706 : Assert(IsA(query, Query));
2707 384 : return (Query *) replace_rte_variables((Node *) query,
2708 : context->varno, 1,
2709 : pullup_replace_vars_callback,
2710 : (void *) context,
2711 : NULL);
2712 : }
2713 :
2714 :
2715 : /*
2716 : * flatten_simple_union_all
2717 : * Try to optimize top-level UNION ALL structure into an appendrel
2718 : *
2719 : * If a query's setOperations tree consists entirely of simple UNION ALL
2720 : * operations, flatten it into an append relation, which we can process more
2721 : * intelligently than the general setops case. Otherwise, do nothing.
2722 : *
2723 : * In most cases, this can succeed only for a top-level query, because for a
2724 : * subquery in FROM, the parent query's invocation of pull_up_subqueries would
2725 : * already have flattened the UNION via pull_up_simple_union_all. But there
2726 : * are a few cases we can support here but not in that code path, for example
2727 : * when the subquery also contains ORDER BY.
2728 : */
2729 : void
2730 5768 : flatten_simple_union_all(PlannerInfo *root)
2731 : {
2732 5768 : Query *parse = root->parse;
2733 : SetOperationStmt *topop;
2734 : Node *leftmostjtnode;
2735 : int leftmostRTI;
2736 : RangeTblEntry *leftmostRTE;
2737 : int childRTI;
2738 : RangeTblEntry *childRTE;
2739 : RangeTblRef *rtr;
2740 :
2741 : /* Shouldn't be called unless query has setops */
2742 5768 : topop = castNode(SetOperationStmt, parse->setOperations);
2743 : Assert(topop);
2744 :
2745 : /* Can't optimize away a recursive UNION */
2746 5768 : if (root->hasRecursion)
2747 5444 : return;
2748 :
2749 : /*
2750 : * Recursively check the tree of set operations. If not all UNION ALL
2751 : * with identical column types, punt.
2752 : */
2753 4956 : if (!is_simple_union_all_recurse((Node *) topop, parse, topop->colTypes))
2754 4632 : return;
2755 :
2756 : /*
2757 : * Locate the leftmost leaf query in the setops tree. The upper query's
2758 : * Vars all refer to this RTE (see transformSetOperationStmt).
2759 : */
2760 324 : leftmostjtnode = topop->larg;
2761 532 : while (leftmostjtnode && IsA(leftmostjtnode, SetOperationStmt))
2762 208 : leftmostjtnode = ((SetOperationStmt *) leftmostjtnode)->larg;
2763 : Assert(leftmostjtnode && IsA(leftmostjtnode, RangeTblRef));
2764 324 : leftmostRTI = ((RangeTblRef *) leftmostjtnode)->rtindex;
2765 324 : leftmostRTE = rt_fetch(leftmostRTI, parse->rtable);
2766 : Assert(leftmostRTE->rtekind == RTE_SUBQUERY);
2767 :
2768 : /*
2769 : * Make a copy of the leftmost RTE and add it to the rtable. This copy
2770 : * will represent the leftmost leaf query in its capacity as a member of
2771 : * the appendrel. The original will represent the appendrel as a whole.
2772 : * (We must do things this way because the upper query's Vars have to be
2773 : * seen as referring to the whole appendrel.)
2774 : */
2775 324 : childRTE = copyObject(leftmostRTE);
2776 324 : parse->rtable = lappend(parse->rtable, childRTE);
2777 324 : childRTI = list_length(parse->rtable);
2778 :
2779 : /* Modify the setops tree to reference the child copy */
2780 324 : ((RangeTblRef *) leftmostjtnode)->rtindex = childRTI;
2781 :
2782 : /* Modify the formerly-leftmost RTE to mark it as an appendrel parent */
2783 324 : leftmostRTE->inh = true;
2784 :
2785 : /*
2786 : * Form a RangeTblRef for the appendrel, and insert it into FROM. The top
2787 : * Query of a setops tree should have had an empty FromClause initially.
2788 : */
2789 324 : rtr = makeNode(RangeTblRef);
2790 324 : rtr->rtindex = leftmostRTI;
2791 : Assert(parse->jointree->fromlist == NIL);
2792 324 : parse->jointree->fromlist = list_make1(rtr);
2793 :
2794 : /*
2795 : * Now pretend the query has no setops. We must do this before trying to
2796 : * do subquery pullup, because of Assert in pull_up_simple_subquery.
2797 : */
2798 324 : parse->setOperations = NULL;
2799 :
2800 : /*
2801 : * Build AppendRelInfo information, and apply pull_up_subqueries to the
2802 : * leaf queries of the UNION ALL. (We must do that now because they
2803 : * weren't previously referenced by the jointree, and so were missed by
2804 : * the main invocation of pull_up_subqueries.)
2805 : */
2806 324 : pull_up_union_leaf_queries((Node *) topop, root, leftmostRTI, parse, 0);
2807 : }
2808 :
2809 :
2810 : /*
2811 : * reduce_outer_joins
2812 : * Attempt to reduce outer joins to plain inner joins.
2813 : *
2814 : * The idea here is that given a query like
2815 : * SELECT ... FROM a LEFT JOIN b ON (...) WHERE b.y = 42;
2816 : * we can reduce the LEFT JOIN to a plain JOIN if the "=" operator in WHERE
2817 : * is strict. The strict operator will always return NULL, causing the outer
2818 : * WHERE to fail, on any row where the LEFT JOIN filled in NULLs for b's
2819 : * columns. Therefore, there's no need for the join to produce null-extended
2820 : * rows in the first place --- which makes it a plain join not an outer join.
2821 : * (This scenario may not be very likely in a query written out by hand, but
2822 : * it's reasonably likely when pushing quals down into complex views.)
2823 : *
2824 : * More generally, an outer join can be reduced in strength if there is a
2825 : * strict qual above it in the qual tree that constrains a Var from the
2826 : * nullable side of the join to be non-null. (For FULL joins this applies
2827 : * to each side separately.)
2828 : *
2829 : * Another transformation we apply here is to recognize cases like
2830 : * SELECT ... FROM a LEFT JOIN b ON (a.x = b.y) WHERE b.y IS NULL;
2831 : * If the join clause is strict for b.y, then only null-extended rows could
2832 : * pass the upper WHERE, and we can conclude that what the query is really
2833 : * specifying is an anti-semijoin. We change the join type from JOIN_LEFT
2834 : * to JOIN_ANTI. The IS NULL clause then becomes redundant, and must be
2835 : * removed to prevent bogus selectivity calculations, but we leave it to
2836 : * distribute_qual_to_rels to get rid of such clauses.
2837 : *
2838 : * Also, we get rid of JOIN_RIGHT cases by flipping them around to become
2839 : * JOIN_LEFT. This saves some code here and in some later planner routines;
2840 : * the main benefit is to reduce the number of jointypes that can appear in
2841 : * SpecialJoinInfo nodes. Note that we can still generate Paths and Plans
2842 : * that use JOIN_RIGHT (or JOIN_RIGHT_ANTI) by switching the inputs again.
2843 : *
2844 : * To ease recognition of strict qual clauses, we require this routine to be
2845 : * run after expression preprocessing (i.e., qual canonicalization and JOIN
2846 : * alias-var expansion).
2847 : */
2848 : void
2849 30190 : reduce_outer_joins(PlannerInfo *root)
2850 : {
2851 : reduce_outer_joins_pass1_state *state1;
2852 : reduce_outer_joins_pass2_state state2;
2853 : ListCell *lc;
2854 :
2855 : /*
2856 : * To avoid doing strictness checks on more quals than necessary, we want
2857 : * to stop descending the jointree as soon as there are no outer joins
2858 : * below our current point. This consideration forces a two-pass process.
2859 : * The first pass gathers information about which base rels appear below
2860 : * each side of each join clause, and about whether there are outer
2861 : * join(s) below each side of each join clause. The second pass examines
2862 : * qual clauses and changes join types as it descends the tree.
2863 : */
2864 30190 : state1 = reduce_outer_joins_pass1((Node *) root->parse->jointree);
2865 :
2866 : /* planner.c shouldn't have called me if no outer joins */
2867 30190 : if (state1 == NULL || !state1->contains_outer)
2868 0 : elog(ERROR, "so where are the outer joins?");
2869 :
2870 30190 : state2.inner_reduced = NULL;
2871 30190 : state2.partial_reduced = NIL;
2872 :
2873 30190 : reduce_outer_joins_pass2((Node *) root->parse->jointree,
2874 : state1, &state2,
2875 : root, NULL, NIL);
2876 :
2877 : /*
2878 : * If we successfully reduced the strength of any outer joins, we must
2879 : * remove references to those joins as nulling rels. This is handled as
2880 : * an additional pass, for simplicity and because we can handle all
2881 : * fully-reduced joins in a single pass over the parse tree.
2882 : */
2883 30190 : if (!bms_is_empty(state2.inner_reduced))
2884 : {
2885 1716 : root->parse = (Query *)
2886 1716 : remove_nulling_relids((Node *) root->parse,
2887 1716 : state2.inner_reduced,
2888 : NULL);
2889 : /* There could be references in the append_rel_list, too */
2890 1716 : root->append_rel_list = (List *)
2891 1716 : remove_nulling_relids((Node *) root->append_rel_list,
2892 1716 : state2.inner_reduced,
2893 : NULL);
2894 : }
2895 :
2896 : /*
2897 : * Partially-reduced full joins have to be done one at a time, since
2898 : * they'll each need a different setting of except_relids.
2899 : */
2900 30240 : foreach(lc, state2.partial_reduced)
2901 : {
2902 50 : reduce_outer_joins_partial_state *statep = lfirst(lc);
2903 50 : Relids full_join_relids = bms_make_singleton(statep->full_join_rti);
2904 :
2905 50 : root->parse = (Query *)
2906 50 : remove_nulling_relids((Node *) root->parse,
2907 : full_join_relids,
2908 50 : statep->unreduced_side);
2909 50 : root->append_rel_list = (List *)
2910 50 : remove_nulling_relids((Node *) root->append_rel_list,
2911 : full_join_relids,
2912 50 : statep->unreduced_side);
2913 : }
2914 30190 : }
2915 :
2916 : /*
2917 : * reduce_outer_joins_pass1 - phase 1 data collection
2918 : *
2919 : * Returns a state node describing the given jointree node.
2920 : */
2921 : static reduce_outer_joins_pass1_state *
2922 170246 : reduce_outer_joins_pass1(Node *jtnode)
2923 : {
2924 : reduce_outer_joins_pass1_state *result;
2925 :
2926 : result = (reduce_outer_joins_pass1_state *)
2927 170246 : palloc(sizeof(reduce_outer_joins_pass1_state));
2928 170246 : result->relids = NULL;
2929 170246 : result->contains_outer = false;
2930 170246 : result->sub_states = NIL;
2931 :
2932 170246 : if (jtnode == NULL)
2933 0 : return result;
2934 170246 : if (IsA(jtnode, RangeTblRef))
2935 : {
2936 84956 : int varno = ((RangeTblRef *) jtnode)->rtindex;
2937 :
2938 84956 : result->relids = bms_make_singleton(varno);
2939 : }
2940 85290 : else if (IsA(jtnode, FromExpr))
2941 : {
2942 33124 : FromExpr *f = (FromExpr *) jtnode;
2943 : ListCell *l;
2944 :
2945 68848 : foreach(l, f->fromlist)
2946 : {
2947 : reduce_outer_joins_pass1_state *sub_state;
2948 :
2949 35724 : sub_state = reduce_outer_joins_pass1(lfirst(l));
2950 71448 : result->relids = bms_add_members(result->relids,
2951 35724 : sub_state->relids);
2952 35724 : result->contains_outer |= sub_state->contains_outer;
2953 35724 : result->sub_states = lappend(result->sub_states, sub_state);
2954 : }
2955 : }
2956 52166 : else if (IsA(jtnode, JoinExpr))
2957 : {
2958 52166 : JoinExpr *j = (JoinExpr *) jtnode;
2959 : reduce_outer_joins_pass1_state *sub_state;
2960 :
2961 : /* join's own RT index is not wanted in result->relids */
2962 52166 : if (IS_OUTER_JOIN(j->jointype))
2963 43242 : result->contains_outer = true;
2964 :
2965 52166 : sub_state = reduce_outer_joins_pass1(j->larg);
2966 104332 : result->relids = bms_add_members(result->relids,
2967 52166 : sub_state->relids);
2968 52166 : result->contains_outer |= sub_state->contains_outer;
2969 52166 : result->sub_states = lappend(result->sub_states, sub_state);
2970 :
2971 52166 : sub_state = reduce_outer_joins_pass1(j->rarg);
2972 104332 : result->relids = bms_add_members(result->relids,
2973 52166 : sub_state->relids);
2974 52166 : result->contains_outer |= sub_state->contains_outer;
2975 52166 : result->sub_states = lappend(result->sub_states, sub_state);
2976 : }
2977 : else
2978 0 : elog(ERROR, "unrecognized node type: %d",
2979 : (int) nodeTag(jtnode));
2980 170246 : return result;
2981 : }
2982 :
2983 : /*
2984 : * reduce_outer_joins_pass2 - phase 2 processing
2985 : *
2986 : * jtnode: current jointree node
2987 : * state1: state data collected by phase 1 for this node
2988 : * state2: where to accumulate info about successfully-reduced joins
2989 : * root: toplevel planner state
2990 : * nonnullable_rels: set of base relids forced non-null by upper quals
2991 : * forced_null_vars: multibitmapset of Vars forced null by upper quals
2992 : *
2993 : * Returns info in state2 about outer joins that were successfully simplified.
2994 : * Joins that were fully reduced to inner joins are all added to
2995 : * state2->inner_reduced. If a full join is reduced to a left join,
2996 : * it needs its own entry in state2->partial_reduced, since that will
2997 : * require custom processing to remove only the correct nullingrel markers.
2998 : */
2999 : static void
3000 75276 : reduce_outer_joins_pass2(Node *jtnode,
3001 : reduce_outer_joins_pass1_state *state1,
3002 : reduce_outer_joins_pass2_state *state2,
3003 : PlannerInfo *root,
3004 : Relids nonnullable_rels,
3005 : List *forced_null_vars)
3006 : {
3007 : /*
3008 : * pass 2 should never descend as far as an empty subnode or base rel,
3009 : * because it's only called on subtrees marked as contains_outer.
3010 : */
3011 75276 : if (jtnode == NULL)
3012 0 : elog(ERROR, "reached empty jointree");
3013 75276 : if (IsA(jtnode, RangeTblRef))
3014 0 : elog(ERROR, "reached base rel");
3015 75276 : else if (IsA(jtnode, FromExpr))
3016 : {
3017 31446 : FromExpr *f = (FromExpr *) jtnode;
3018 : ListCell *l;
3019 : ListCell *s;
3020 : Relids pass_nonnullable_rels;
3021 : List *pass_forced_null_vars;
3022 :
3023 : /* Scan quals to see if we can add any constraints */
3024 31446 : pass_nonnullable_rels = find_nonnullable_rels(f->quals);
3025 31446 : pass_nonnullable_rels = bms_add_members(pass_nonnullable_rels,
3026 : nonnullable_rels);
3027 31446 : pass_forced_null_vars = find_forced_null_vars(f->quals);
3028 31446 : pass_forced_null_vars = mbms_add_members(pass_forced_null_vars,
3029 : forced_null_vars);
3030 : /* And recurse --- but only into interesting subtrees */
3031 : Assert(list_length(f->fromlist) == list_length(state1->sub_states));
3032 65366 : forboth(l, f->fromlist, s, state1->sub_states)
3033 : {
3034 33920 : reduce_outer_joins_pass1_state *sub_state = lfirst(s);
3035 :
3036 33920 : if (sub_state->contains_outer)
3037 31476 : reduce_outer_joins_pass2(lfirst(l), sub_state,
3038 : state2, root,
3039 : pass_nonnullable_rels,
3040 : pass_forced_null_vars);
3041 : }
3042 31446 : bms_free(pass_nonnullable_rels);
3043 : /* can't so easily clean up var lists, unfortunately */
3044 : }
3045 43830 : else if (IsA(jtnode, JoinExpr))
3046 : {
3047 43830 : JoinExpr *j = (JoinExpr *) jtnode;
3048 43830 : int rtindex = j->rtindex;
3049 43830 : JoinType jointype = j->jointype;
3050 43830 : reduce_outer_joins_pass1_state *left_state = linitial(state1->sub_states);
3051 43830 : reduce_outer_joins_pass1_state *right_state = lsecond(state1->sub_states);
3052 :
3053 : /* Can we simplify this join? */
3054 43830 : switch (jointype)
3055 : {
3056 552 : case JOIN_INNER:
3057 552 : break;
3058 40728 : case JOIN_LEFT:
3059 40728 : if (bms_overlap(nonnullable_rels, right_state->relids))
3060 1786 : jointype = JOIN_INNER;
3061 40728 : break;
3062 1084 : case JOIN_RIGHT:
3063 1084 : if (bms_overlap(nonnullable_rels, left_state->relids))
3064 62 : jointype = JOIN_INNER;
3065 1084 : break;
3066 1066 : case JOIN_FULL:
3067 1066 : if (bms_overlap(nonnullable_rels, left_state->relids))
3068 : {
3069 24 : if (bms_overlap(nonnullable_rels, right_state->relids))
3070 12 : jointype = JOIN_INNER;
3071 : else
3072 : {
3073 12 : jointype = JOIN_LEFT;
3074 : /* Also report partial reduction in state2 */
3075 12 : report_reduced_full_join(state2, rtindex,
3076 : right_state->relids);
3077 : }
3078 : }
3079 : else
3080 : {
3081 1042 : if (bms_overlap(nonnullable_rels, right_state->relids))
3082 : {
3083 38 : jointype = JOIN_RIGHT;
3084 : /* Also report partial reduction in state2 */
3085 38 : report_reduced_full_join(state2, rtindex,
3086 : left_state->relids);
3087 : }
3088 : }
3089 1066 : break;
3090 400 : case JOIN_SEMI:
3091 : case JOIN_ANTI:
3092 :
3093 : /*
3094 : * These could only have been introduced by pull_up_sublinks,
3095 : * so there's no way that upper quals could refer to their
3096 : * righthand sides, and no point in checking. We don't expect
3097 : * to see JOIN_RIGHT_SEMI or JOIN_RIGHT_ANTI yet.
3098 : */
3099 400 : break;
3100 0 : default:
3101 0 : elog(ERROR, "unrecognized join type: %d",
3102 : (int) jointype);
3103 : break;
3104 : }
3105 :
3106 : /*
3107 : * Convert JOIN_RIGHT to JOIN_LEFT. Note that in the case where we
3108 : * reduced JOIN_FULL to JOIN_RIGHT, this will mean the JoinExpr no
3109 : * longer matches the internal ordering of any CoalesceExpr's built to
3110 : * represent merged join variables. We don't care about that at
3111 : * present, but be wary of it ...
3112 : */
3113 43830 : if (jointype == JOIN_RIGHT)
3114 : {
3115 : Node *tmparg;
3116 :
3117 1060 : tmparg = j->larg;
3118 1060 : j->larg = j->rarg;
3119 1060 : j->rarg = tmparg;
3120 1060 : jointype = JOIN_LEFT;
3121 1060 : right_state = linitial(state1->sub_states);
3122 1060 : left_state = lsecond(state1->sub_states);
3123 : }
3124 :
3125 : /*
3126 : * See if we can reduce JOIN_LEFT to JOIN_ANTI. This is the case if
3127 : * the join's own quals are strict for any var that was forced null by
3128 : * higher qual levels. NOTE: there are other ways that we could
3129 : * detect an anti-join, in particular if we were to check whether Vars
3130 : * coming from the RHS must be non-null because of table constraints.
3131 : * That seems complicated and expensive though (in particular, one
3132 : * would have to be wary of lower outer joins). For the moment this
3133 : * seems sufficient.
3134 : */
3135 43830 : if (jointype == JOIN_LEFT)
3136 : {
3137 : List *nonnullable_vars;
3138 : Bitmapset *overlap;
3139 :
3140 : /* Find Vars in j->quals that must be non-null in joined rows */
3141 40014 : nonnullable_vars = find_nonnullable_vars(j->quals);
3142 :
3143 : /*
3144 : * It's not sufficient to check whether nonnullable_vars and
3145 : * forced_null_vars overlap: we need to know if the overlap
3146 : * includes any RHS variables.
3147 : */
3148 40014 : overlap = mbms_overlap_sets(nonnullable_vars, forced_null_vars);
3149 40014 : if (bms_overlap(overlap, right_state->relids))
3150 1020 : jointype = JOIN_ANTI;
3151 : }
3152 :
3153 : /*
3154 : * Apply the jointype change, if any, to both jointree node and RTE.
3155 : * Also, if we changed an RTE to INNER, add its RTI to inner_reduced.
3156 : */
3157 43830 : if (rtindex && jointype != j->jointype)
3158 : {
3159 3952 : RangeTblEntry *rte = rt_fetch(rtindex, root->parse->rtable);
3160 :
3161 : Assert(rte->rtekind == RTE_JOIN);
3162 : Assert(rte->jointype == j->jointype);
3163 3952 : rte->jointype = jointype;
3164 3952 : if (jointype == JOIN_INNER)
3165 1860 : state2->inner_reduced = bms_add_member(state2->inner_reduced,
3166 : rtindex);
3167 : }
3168 43830 : j->jointype = jointype;
3169 :
3170 : /* Only recurse if there's more to do below here */
3171 43830 : if (left_state->contains_outer || right_state->contains_outer)
3172 : {
3173 : Relids local_nonnullable_rels;
3174 : List *local_forced_null_vars;
3175 : Relids pass_nonnullable_rels;
3176 : List *pass_forced_null_vars;
3177 :
3178 : /*
3179 : * If this join is (now) inner, we can add any constraints its
3180 : * quals provide to those we got from above. But if it is outer,
3181 : * we can pass down the local constraints only into the nullable
3182 : * side, because an outer join never eliminates any rows from its
3183 : * non-nullable side. Also, there is no point in passing upper
3184 : * constraints into the nullable side, since if there were any
3185 : * we'd have been able to reduce the join. (In the case of upper
3186 : * forced-null constraints, we *must not* pass them into the
3187 : * nullable side --- they either applied here, or not.) The upshot
3188 : * is that we pass either the local or the upper constraints,
3189 : * never both, to the children of an outer join.
3190 : *
3191 : * Note that a SEMI join works like an inner join here: it's okay
3192 : * to pass down both local and upper constraints. (There can't be
3193 : * any upper constraints affecting its inner side, but it's not
3194 : * worth having a separate code path to avoid passing them.)
3195 : *
3196 : * At a FULL join we just punt and pass nothing down --- is it
3197 : * possible to be smarter?
3198 : */
3199 13542 : if (jointype != JOIN_FULL)
3200 : {
3201 13406 : local_nonnullable_rels = find_nonnullable_rels(j->quals);
3202 13406 : local_forced_null_vars = find_forced_null_vars(j->quals);
3203 13406 : if (jointype == JOIN_INNER || jointype == JOIN_SEMI)
3204 : {
3205 : /* OK to merge upper and local constraints */
3206 956 : local_nonnullable_rels = bms_add_members(local_nonnullable_rels,
3207 : nonnullable_rels);
3208 956 : local_forced_null_vars = mbms_add_members(local_forced_null_vars,
3209 : forced_null_vars);
3210 : }
3211 : }
3212 : else
3213 : {
3214 : /* no use in calculating these */
3215 136 : local_nonnullable_rels = NULL;
3216 136 : local_forced_null_vars = NIL;
3217 : }
3218 :
3219 13542 : if (left_state->contains_outer)
3220 : {
3221 12840 : if (jointype == JOIN_INNER || jointype == JOIN_SEMI)
3222 : {
3223 : /* pass union of local and upper constraints */
3224 736 : pass_nonnullable_rels = local_nonnullable_rels;
3225 736 : pass_forced_null_vars = local_forced_null_vars;
3226 : }
3227 12104 : else if (jointype != JOIN_FULL) /* ie, LEFT or ANTI */
3228 : {
3229 : /* can't pass local constraints to non-nullable side */
3230 11996 : pass_nonnullable_rels = nonnullable_rels;
3231 11996 : pass_forced_null_vars = forced_null_vars;
3232 : }
3233 : else
3234 : {
3235 : /* no constraints pass through JOIN_FULL */
3236 108 : pass_nonnullable_rels = NULL;
3237 108 : pass_forced_null_vars = NIL;
3238 : }
3239 12840 : reduce_outer_joins_pass2(j->larg, left_state,
3240 : state2, root,
3241 : pass_nonnullable_rels,
3242 : pass_forced_null_vars);
3243 : }
3244 :
3245 13542 : if (right_state->contains_outer)
3246 : {
3247 770 : if (jointype != JOIN_FULL) /* ie, INNER/LEFT/SEMI/ANTI */
3248 : {
3249 : /* pass appropriate constraints, per comment above */
3250 742 : pass_nonnullable_rels = local_nonnullable_rels;
3251 742 : pass_forced_null_vars = local_forced_null_vars;
3252 : }
3253 : else
3254 : {
3255 : /* no constraints pass through JOIN_FULL */
3256 28 : pass_nonnullable_rels = NULL;
3257 28 : pass_forced_null_vars = NIL;
3258 : }
3259 770 : reduce_outer_joins_pass2(j->rarg, right_state,
3260 : state2, root,
3261 : pass_nonnullable_rels,
3262 : pass_forced_null_vars);
3263 : }
3264 13542 : bms_free(local_nonnullable_rels);
3265 : }
3266 : }
3267 : else
3268 0 : elog(ERROR, "unrecognized node type: %d",
3269 : (int) nodeTag(jtnode));
3270 75276 : }
3271 :
3272 : /* Helper for reduce_outer_joins_pass2 */
3273 : static void
3274 50 : report_reduced_full_join(reduce_outer_joins_pass2_state *state2,
3275 : int rtindex, Relids relids)
3276 : {
3277 : reduce_outer_joins_partial_state *statep;
3278 :
3279 50 : statep = palloc(sizeof(reduce_outer_joins_partial_state));
3280 50 : statep->full_join_rti = rtindex;
3281 50 : statep->unreduced_side = relids;
3282 50 : state2->partial_reduced = lappend(state2->partial_reduced, statep);
3283 50 : }
3284 :
3285 :
3286 : /*
3287 : * remove_useless_result_rtes
3288 : * Attempt to remove RTE_RESULT RTEs from the join tree.
3289 : * Also, elide single-child FromExprs where possible.
3290 : *
3291 : * We can remove RTE_RESULT entries from the join tree using the knowledge
3292 : * that RTE_RESULT returns exactly one row and has no output columns. Hence,
3293 : * if one is inner-joined to anything else, we can delete it. Optimizations
3294 : * are also possible for some outer-join cases, as detailed below.
3295 : *
3296 : * This pass also replaces single-child FromExprs with their child node
3297 : * where possible. It's appropriate to do that here and not earlier because
3298 : * RTE_RESULT removal might reduce a multiple-child FromExpr to have only one
3299 : * child. We can remove such a FromExpr if its quals are empty, or if it's
3300 : * semantically valid to merge the quals into those of the parent node.
3301 : * While removing unnecessary join tree nodes has some micro-efficiency value,
3302 : * the real reason to do this is to eliminate cases where the nullable side of
3303 : * an outer join node is a FromExpr whose single child is another outer join.
3304 : * To correctly determine whether the two outer joins can commute,
3305 : * deconstruct_jointree() must treat any quals of such a FromExpr as being
3306 : * degenerate quals of the upper outer join. The best way to do that is to
3307 : * make them actually *be* quals of the upper join, by dropping the FromExpr
3308 : * and hoisting the quals up into the upper join's quals. (Note that there is
3309 : * no hazard when the intermediate FromExpr has multiple children, since then
3310 : * it represents an inner join that cannot commute with the upper outer join.)
3311 : * As long as we have to do that, we might as well elide such FromExprs
3312 : * everywhere.
3313 : *
3314 : * Some of these optimizations depend on recognizing empty (constant-true)
3315 : * quals for FromExprs and JoinExprs. That makes it useful to apply this
3316 : * optimization pass after expression preprocessing, since that will have
3317 : * eliminated constant-true quals, allowing more cases to be recognized as
3318 : * optimizable. What's more, the usual reason for an RTE_RESULT to be present
3319 : * is that we pulled up a subquery or VALUES clause, thus very possibly
3320 : * replacing Vars with constants, making it more likely that a qual can be
3321 : * reduced to constant true. Also, because some optimizations depend on
3322 : * the outer-join type, it's best to have done reduce_outer_joins() first.
3323 : *
3324 : * A PlaceHolderVar referencing an RTE_RESULT RTE poses an obstacle to this
3325 : * process: we must remove the RTE_RESULT's relid from the PHV's phrels, but
3326 : * we must not reduce the phrels set to empty. If that would happen, and
3327 : * the RTE_RESULT is an immediate child of an outer join, we have to give up
3328 : * and not remove the RTE_RESULT: there is noplace else to evaluate the
3329 : * PlaceHolderVar. (That is, in such cases the RTE_RESULT *does* have output
3330 : * columns.) But if the RTE_RESULT is an immediate child of an inner join,
3331 : * we can usually change the PlaceHolderVar's phrels so as to evaluate it at
3332 : * the inner join instead. This is OK because we really only care that PHVs
3333 : * are evaluated above or below the correct outer joins. We can't, however,
3334 : * postpone the evaluation of a PHV to above where it is used; so there are
3335 : * some checks below on whether output PHVs are laterally referenced in the
3336 : * other join input rel(s).
3337 : *
3338 : * We used to try to do this work as part of pull_up_subqueries() where the
3339 : * potentially-optimizable cases get introduced; but it's way simpler, and
3340 : * more effective, to do it separately.
3341 : */
3342 : void
3343 246658 : remove_useless_result_rtes(PlannerInfo *root)
3344 : {
3345 246658 : Relids dropped_outer_joins = NULL;
3346 : ListCell *cell;
3347 :
3348 : /* Top level of jointree must always be a FromExpr */
3349 : Assert(IsA(root->parse->jointree, FromExpr));
3350 : /* Recurse ... */
3351 493316 : root->parse->jointree = (FromExpr *)
3352 246658 : remove_useless_results_recurse(root,
3353 246658 : (Node *) root->parse->jointree,
3354 : NULL,
3355 : &dropped_outer_joins);
3356 : /* We should still have a FromExpr */
3357 : Assert(IsA(root->parse->jointree, FromExpr));
3358 :
3359 : /*
3360 : * If we removed any outer-join nodes from the jointree, run around and
3361 : * remove references to those joins as nulling rels. (There could be such
3362 : * references in PHVs that we pulled up out of the original subquery that
3363 : * the RESULT rel replaced. This is kosher on the grounds that we now
3364 : * know that such an outer join wouldn't really have nulled anything.) We
3365 : * don't do this during the main recursion, for simplicity and because we
3366 : * can handle all such joins in a single pass over the parse tree.
3367 : */
3368 246658 : if (!bms_is_empty(dropped_outer_joins))
3369 : {
3370 60 : root->parse = (Query *)
3371 60 : remove_nulling_relids((Node *) root->parse,
3372 : dropped_outer_joins,
3373 : NULL);
3374 : /* There could be references in the append_rel_list, too */
3375 60 : root->append_rel_list = (List *)
3376 60 : remove_nulling_relids((Node *) root->append_rel_list,
3377 : dropped_outer_joins,
3378 : NULL);
3379 : }
3380 :
3381 : /*
3382 : * Remove any PlanRowMark referencing an RTE_RESULT RTE. We obviously
3383 : * must do that for any RTE_RESULT that we just removed. But one for a
3384 : * RTE that we did not remove can be dropped anyway: since the RTE has
3385 : * only one possible output row, there is no need for EPQ to mark and
3386 : * restore that row.
3387 : *
3388 : * It's necessary, not optional, to remove the PlanRowMark for a surviving
3389 : * RTE_RESULT RTE; otherwise we'll generate a whole-row Var for the
3390 : * RTE_RESULT, which the executor has no support for.
3391 : */
3392 248558 : foreach(cell, root->rowMarks)
3393 : {
3394 1900 : PlanRowMark *rc = (PlanRowMark *) lfirst(cell);
3395 :
3396 1900 : if (rt_fetch(rc->rti, root->parse->rtable)->rtekind == RTE_RESULT)
3397 834 : root->rowMarks = foreach_delete_current(root->rowMarks, cell);
3398 : }
3399 246658 : }
3400 :
3401 : /*
3402 : * remove_useless_results_recurse
3403 : * Recursive guts of remove_useless_result_rtes.
3404 : *
3405 : * This recursively processes the jointree and returns a modified jointree.
3406 : * In addition, the RT indexes of any removed outer-join nodes are added to
3407 : * *dropped_outer_joins.
3408 : *
3409 : * jtnode is the current jointree node. If it could be valid to merge
3410 : * its quals into those of the parent node, parent_quals should point to
3411 : * the parent's quals list; otherwise, pass NULL for parent_quals.
3412 : * (Note that in some cases, parent_quals points to the quals of a parent
3413 : * more than one level up in the tree.)
3414 : */
3415 : static Node *
3416 607188 : remove_useless_results_recurse(PlannerInfo *root, Node *jtnode,
3417 : Node **parent_quals,
3418 : Relids *dropped_outer_joins)
3419 : {
3420 : Assert(jtnode != NULL);
3421 607188 : if (IsA(jtnode, RangeTblRef))
3422 : {
3423 : /* Can't immediately do anything with a RangeTblRef */
3424 : }
3425 303994 : else if (IsA(jtnode, FromExpr))
3426 : {
3427 250674 : FromExpr *f = (FromExpr *) jtnode;
3428 250674 : Relids result_relids = NULL;
3429 : ListCell *cell;
3430 :
3431 : /*
3432 : * We can drop RTE_RESULT rels from the fromlist so long as at least
3433 : * one child remains, since joining to a one-row table changes
3434 : * nothing. (But we can't drop a RTE_RESULT that computes PHV(s) that
3435 : * are needed by some sibling. The cleanup transformation below would
3436 : * reassign the PHVs to be computed at the join, which is too late for
3437 : * the sibling's use.) The easiest way to mechanize this rule is to
3438 : * modify the list in-place.
3439 : */
3440 504564 : foreach(cell, f->fromlist)
3441 : {
3442 253890 : Node *child = (Node *) lfirst(cell);
3443 : int varno;
3444 :
3445 : /* Recursively transform child, allowing it to push up quals ... */
3446 253890 : child = remove_useless_results_recurse(root, child,
3447 : &f->quals,
3448 : dropped_outer_joins);
3449 : /* ... and stick it back into the tree */
3450 253890 : lfirst(cell) = child;
3451 :
3452 : /*
3453 : * If it's an RTE_RESULT with at least one sibling, and no sibling
3454 : * references dependent PHVs, we can drop it. We don't yet know
3455 : * what the inner join's final relid set will be, so postpone
3456 : * cleanup of PHVs etc till after this loop.
3457 : */
3458 259034 : if (list_length(f->fromlist) > 1 &&
3459 5144 : (varno = get_result_relid(root, child)) != 0 &&
3460 334 : !find_dependent_phvs_in_jointree(root, (Node *) f, varno))
3461 : {
3462 310 : f->fromlist = foreach_delete_current(f->fromlist, cell);
3463 310 : result_relids = bms_add_member(result_relids, varno);
3464 : }
3465 : }
3466 :
3467 : /*
3468 : * Clean up if we dropped any RTE_RESULT RTEs. This is a bit
3469 : * inefficient if there's more than one, but it seems better to
3470 : * optimize the support code for the single-relid case.
3471 : */
3472 250674 : if (result_relids)
3473 : {
3474 298 : int varno = -1;
3475 :
3476 608 : while ((varno = bms_next_member(result_relids, varno)) >= 0)
3477 310 : remove_result_refs(root, varno, (Node *) f);
3478 : }
3479 :
3480 : /*
3481 : * If the FromExpr now has only one child, see if we can elide it.
3482 : * This is always valid if there are no quals, except at the top of
3483 : * the jointree (since Query.jointree is required to point to a
3484 : * FromExpr). Otherwise, we can do it if we can push the quals up to
3485 : * the parent node.
3486 : *
3487 : * Note: while it would not be terribly hard to generalize this
3488 : * transformation to merge multi-child FromExprs into their parent
3489 : * FromExpr, that risks making the parent join too expensive to plan.
3490 : * We leave it to later processing to decide heuristically whether
3491 : * that's a good idea. Pulling up a single child is always OK,
3492 : * however.
3493 : */
3494 250674 : if (list_length(f->fromlist) == 1 &&
3495 248942 : f != root->parse->jointree &&
3496 3830 : (f->quals == NULL || parent_quals != NULL))
3497 : {
3498 : /*
3499 : * Merge any quals up to parent. They should be in implicit-AND
3500 : * format by now, so we just need to concatenate lists. Put the
3501 : * child quals at the front, on the grounds that they should
3502 : * nominally be evaluated earlier.
3503 : */
3504 2636 : if (f->quals != NULL)
3505 1266 : *parent_quals = (Node *)
3506 1266 : list_concat(castNode(List, f->quals),
3507 : castNode(List, *parent_quals));
3508 2636 : return (Node *) linitial(f->fromlist);
3509 : }
3510 : }
3511 53320 : else if (IsA(jtnode, JoinExpr))
3512 : {
3513 53320 : JoinExpr *j = (JoinExpr *) jtnode;
3514 : int varno;
3515 :
3516 : /*
3517 : * First, recurse. We can absorb pushed-up FromExpr quals from either
3518 : * child into this node if the jointype is INNER, since then this is
3519 : * equivalent to a FromExpr. When the jointype is LEFT, we can absorb
3520 : * quals from the RHS child into the current node, as they're
3521 : * essentially degenerate quals of the outer join. Moreover, if we've
3522 : * been passed down a parent_quals pointer then we can allow quals of
3523 : * the LHS child to be absorbed into the parent. (This is important
3524 : * to ensure we remove single-child FromExprs immediately below
3525 : * commutable left joins.) For other jointypes, we can't move child
3526 : * quals up, or at least there's no particular reason to.
3527 : */
3528 53320 : j->larg = remove_useless_results_recurse(root, j->larg,
3529 53320 : (j->jointype == JOIN_INNER) ?
3530 : &j->quals :
3531 41986 : (j->jointype == JOIN_LEFT) ?
3532 41986 : parent_quals : NULL,
3533 : dropped_outer_joins);
3534 53320 : j->rarg = remove_useless_results_recurse(root, j->rarg,
3535 53320 : (j->jointype == JOIN_INNER ||
3536 41986 : j->jointype == JOIN_LEFT) ?
3537 : &j->quals : NULL,
3538 : dropped_outer_joins);
3539 :
3540 : /* Apply join-type-specific optimization rules */
3541 53320 : switch (j->jointype)
3542 : {
3543 11334 : case JOIN_INNER:
3544 :
3545 : /*
3546 : * An inner join is equivalent to a FromExpr, so if either
3547 : * side was simplified to an RTE_RESULT rel, we can replace
3548 : * the join with a FromExpr with just the other side.
3549 : * Furthermore, we can elide that FromExpr according to the
3550 : * same rules as above.
3551 : *
3552 : * Just as in the FromExpr case, we can't simplify if the
3553 : * other input rel references any PHVs that are marked as to
3554 : * be evaluated at the RTE_RESULT rel, because we can't
3555 : * postpone their evaluation in that case. But we only have
3556 : * to check this in cases where it's syntactically legal for
3557 : * the other input to have a LATERAL reference to the
3558 : * RTE_RESULT rel. Only RHSes of inner and left joins are
3559 : * allowed to have such refs.
3560 : */
3561 11334 : if ((varno = get_result_relid(root, j->larg)) != 0 &&
3562 48 : !find_dependent_phvs_in_jointree(root, j->rarg, varno))
3563 : {
3564 48 : remove_result_refs(root, varno, j->rarg);
3565 48 : if (j->quals != NULL && parent_quals == NULL)
3566 12 : jtnode = (Node *)
3567 12 : makeFromExpr(list_make1(j->rarg), j->quals);
3568 : else
3569 : {
3570 : /* Merge any quals up to parent */
3571 36 : if (j->quals != NULL)
3572 12 : *parent_quals = (Node *)
3573 12 : list_concat(castNode(List, j->quals),
3574 : castNode(List, *parent_quals));
3575 36 : jtnode = j->rarg;
3576 : }
3577 : }
3578 11286 : else if ((varno = get_result_relid(root, j->rarg)) != 0)
3579 : {
3580 644 : remove_result_refs(root, varno, j->larg);
3581 644 : if (j->quals != NULL && parent_quals == NULL)
3582 12 : jtnode = (Node *)
3583 12 : makeFromExpr(list_make1(j->larg), j->quals);
3584 : else
3585 : {
3586 : /* Merge any quals up to parent */
3587 632 : if (j->quals != NULL)
3588 582 : *parent_quals = (Node *)
3589 582 : list_concat(castNode(List, j->quals),
3590 : castNode(List, *parent_quals));
3591 632 : jtnode = j->larg;
3592 : }
3593 : }
3594 11334 : break;
3595 38994 : case JOIN_LEFT:
3596 :
3597 : /*
3598 : * We can simplify this case if the RHS is an RTE_RESULT, with
3599 : * two different possibilities:
3600 : *
3601 : * If the qual is empty (JOIN ON TRUE), then the join can be
3602 : * strength-reduced to a plain inner join, since each LHS row
3603 : * necessarily has exactly one join partner. So we can always
3604 : * discard the RHS, much as in the JOIN_INNER case above.
3605 : * (Again, the LHS could not contain a lateral reference to
3606 : * the RHS.)
3607 : *
3608 : * Otherwise, it's still true that each LHS row should be
3609 : * returned exactly once, and since the RHS returns no columns
3610 : * (unless there are PHVs that have to be evaluated there), we
3611 : * don't much care if it's null-extended or not. So in this
3612 : * case also, we can just ignore the qual and discard the left
3613 : * join.
3614 : */
3615 38994 : if ((varno = get_result_relid(root, j->rarg)) != 0 &&
3616 150 : (j->quals == NULL ||
3617 90 : !find_dependent_phvs(root, varno)))
3618 : {
3619 60 : remove_result_refs(root, varno, j->larg);
3620 60 : *dropped_outer_joins = bms_add_member(*dropped_outer_joins,
3621 : j->rtindex);
3622 60 : jtnode = j->larg;
3623 : }
3624 38994 : break;
3625 604 : case JOIN_SEMI:
3626 :
3627 : /*
3628 : * We may simplify this case if the RHS is an RTE_RESULT; the
3629 : * join qual becomes effectively just a filter qual for the
3630 : * LHS, since we should either return the LHS row or not. The
3631 : * filter clause must go into a new FromExpr if we can't push
3632 : * it up to the parent.
3633 : *
3634 : * There is a fine point about PHVs that are supposed to be
3635 : * evaluated at the RHS. Such PHVs could only appear in the
3636 : * semijoin's qual, since the rest of the query cannot
3637 : * reference any outputs of the semijoin's RHS. Therefore,
3638 : * they can't actually go to null before being examined, and
3639 : * it'd be OK to just remove the PHV wrapping. We don't have
3640 : * infrastructure for that, but remove_result_refs() will
3641 : * relabel them as to be evaluated at the LHS, which is fine.
3642 : *
3643 : * Also, we don't need to worry about removing traces of the
3644 : * join's rtindex, since it hasn't got one.
3645 : */
3646 604 : if ((varno = get_result_relid(root, j->rarg)) != 0)
3647 : {
3648 : Assert(j->rtindex == 0);
3649 36 : remove_result_refs(root, varno, j->larg);
3650 36 : if (j->quals != NULL && parent_quals == NULL)
3651 0 : jtnode = (Node *)
3652 0 : makeFromExpr(list_make1(j->larg), j->quals);
3653 : else
3654 : {
3655 : /* Merge any quals up to parent */
3656 36 : if (j->quals != NULL)
3657 36 : *parent_quals = (Node *)
3658 36 : list_concat(castNode(List, j->quals),
3659 : castNode(List, *parent_quals));
3660 36 : jtnode = j->larg;
3661 : }
3662 : }
3663 604 : break;
3664 2388 : case JOIN_FULL:
3665 : case JOIN_ANTI:
3666 : /* We have no special smarts for these cases */
3667 2388 : break;
3668 0 : default:
3669 : /* Note: JOIN_RIGHT should be gone at this point */
3670 0 : elog(ERROR, "unrecognized join type: %d",
3671 : (int) j->jointype);
3672 : break;
3673 : }
3674 : }
3675 : else
3676 0 : elog(ERROR, "unrecognized node type: %d",
3677 : (int) nodeTag(jtnode));
3678 604552 : return jtnode;
3679 : }
3680 :
3681 : /*
3682 : * get_result_relid
3683 : * If jtnode is a RangeTblRef for an RTE_RESULT RTE, return its relid;
3684 : * otherwise return 0.
3685 : */
3686 : static int
3687 67362 : get_result_relid(PlannerInfo *root, Node *jtnode)
3688 : {
3689 : int varno;
3690 :
3691 67362 : if (!IsA(jtnode, RangeTblRef))
3692 5548 : return 0;
3693 61814 : varno = ((RangeTblRef *) jtnode)->rtindex;
3694 61814 : if (rt_fetch(varno, root->parse->rtable)->rtekind != RTE_RESULT)
3695 60602 : return 0;
3696 1212 : return varno;
3697 : }
3698 :
3699 : /*
3700 : * remove_result_refs
3701 : * Helper routine for dropping an unneeded RTE_RESULT RTE.
3702 : *
3703 : * This doesn't physically remove the RTE from the jointree, because that's
3704 : * more easily handled in remove_useless_results_recurse. What it does do
3705 : * is the necessary cleanup in the rest of the tree: we must adjust any PHVs
3706 : * that may reference the RTE. Be sure to call this at a point where the
3707 : * jointree is valid (no disconnected nodes).
3708 : *
3709 : * Note that we don't need to process the append_rel_list, since RTEs
3710 : * referenced directly in the jointree won't be appendrel members.
3711 : *
3712 : * varno is the RTE_RESULT's relid.
3713 : * newjtloc is the jointree location at which any PHVs referencing the
3714 : * RTE_RESULT should be evaluated instead.
3715 : */
3716 : static void
3717 1098 : remove_result_refs(PlannerInfo *root, int varno, Node *newjtloc)
3718 : {
3719 : /* Fix up PlaceHolderVars as needed */
3720 : /* If there are no PHVs anywhere, we can skip this bit */
3721 1098 : if (root->glob->lastPHId != 0)
3722 : {
3723 : Relids subrelids;
3724 :
3725 176 : subrelids = get_relids_in_jointree(newjtloc, true, false);
3726 : Assert(!bms_is_empty(subrelids));
3727 176 : substitute_phv_relids((Node *) root->parse, varno, subrelids);
3728 176 : fix_append_rel_relids(root, varno, subrelids);
3729 : }
3730 :
3731 : /*
3732 : * We also need to remove any PlanRowMark referencing the RTE, but we
3733 : * postpone that work until we return to remove_useless_result_rtes.
3734 : */
3735 1098 : }
3736 :
3737 :
3738 : /*
3739 : * find_dependent_phvs - are there any PlaceHolderVars whose relids are
3740 : * exactly the given varno?
3741 : *
3742 : * find_dependent_phvs should be used when we want to see if there are
3743 : * any such PHVs anywhere in the Query. Another use-case is to see if
3744 : * a subtree of the join tree contains such PHVs; but for that, we have
3745 : * to look not only at the join tree nodes themselves but at the
3746 : * referenced RTEs. For that, use find_dependent_phvs_in_jointree.
3747 : */
3748 :
3749 : typedef struct
3750 : {
3751 : Relids relids;
3752 : int sublevels_up;
3753 : } find_dependent_phvs_context;
3754 :
3755 : static bool
3756 2400 : find_dependent_phvs_walker(Node *node,
3757 : find_dependent_phvs_context *context)
3758 : {
3759 2400 : if (node == NULL)
3760 564 : return false;
3761 1836 : if (IsA(node, PlaceHolderVar))
3762 : {
3763 156 : PlaceHolderVar *phv = (PlaceHolderVar *) node;
3764 :
3765 312 : if (phv->phlevelsup == context->sublevels_up &&
3766 156 : bms_equal(context->relids, phv->phrels))
3767 114 : return true;
3768 : /* fall through to examine children */
3769 : }
3770 1722 : if (IsA(node, Query))
3771 : {
3772 : /* Recurse into subselects */
3773 : bool result;
3774 :
3775 48 : context->sublevels_up++;
3776 48 : result = query_tree_walker((Query *) node,
3777 : find_dependent_phvs_walker,
3778 : (void *) context, 0);
3779 48 : context->sublevels_up--;
3780 48 : return result;
3781 : }
3782 : /* Shouldn't need to handle most planner auxiliary nodes here */
3783 : Assert(!IsA(node, SpecialJoinInfo));
3784 : Assert(!IsA(node, PlaceHolderInfo));
3785 : Assert(!IsA(node, MinMaxAggInfo));
3786 :
3787 1674 : return expression_tree_walker(node, find_dependent_phvs_walker,
3788 : (void *) context);
3789 : }
3790 :
3791 : static bool
3792 90 : find_dependent_phvs(PlannerInfo *root, int varno)
3793 : {
3794 : find_dependent_phvs_context context;
3795 :
3796 : /* If there are no PHVs anywhere, we needn't work hard */
3797 90 : if (root->glob->lastPHId == 0)
3798 0 : return false;
3799 :
3800 90 : context.relids = bms_make_singleton(varno);
3801 90 : context.sublevels_up = 0;
3802 :
3803 90 : if (query_tree_walker(root->parse,
3804 : find_dependent_phvs_walker,
3805 : (void *) &context,
3806 : 0))
3807 90 : return true;
3808 : /* The append_rel_list could be populated already, so check it too */
3809 0 : if (expression_tree_walker((Node *) root->append_rel_list,
3810 : find_dependent_phvs_walker,
3811 : (void *) &context))
3812 0 : return true;
3813 0 : return false;
3814 : }
3815 :
3816 : static bool
3817 382 : find_dependent_phvs_in_jointree(PlannerInfo *root, Node *node, int varno)
3818 : {
3819 : find_dependent_phvs_context context;
3820 : Relids subrelids;
3821 : int relid;
3822 :
3823 : /* If there are no PHVs anywhere, we needn't work hard */
3824 382 : if (root->glob->lastPHId == 0)
3825 316 : return false;
3826 :
3827 66 : context.relids = bms_make_singleton(varno);
3828 66 : context.sublevels_up = 0;
3829 :
3830 : /*
3831 : * See if the jointree fragment itself contains references (in join quals)
3832 : */
3833 66 : if (find_dependent_phvs_walker(node, &context))
3834 0 : return true;
3835 :
3836 : /*
3837 : * Otherwise, identify the set of referenced RTEs (we can ignore joins,
3838 : * since they should be flattened already, so their join alias lists no
3839 : * longer matter), and tediously check each RTE. We can ignore RTEs that
3840 : * are not marked LATERAL, though, since they couldn't possibly contain
3841 : * any cross-references to other RTEs.
3842 : */
3843 66 : subrelids = get_relids_in_jointree(node, false, false);
3844 66 : relid = -1;
3845 144 : while ((relid = bms_next_member(subrelids, relid)) >= 0)
3846 : {
3847 102 : RangeTblEntry *rte = rt_fetch(relid, root->parse->rtable);
3848 :
3849 126 : if (rte->lateral &&
3850 24 : range_table_entry_walker(rte,
3851 : find_dependent_phvs_walker,
3852 : (void *) &context,
3853 : 0))
3854 24 : return true;
3855 : }
3856 :
3857 42 : return false;
3858 : }
3859 :
3860 : /*
3861 : * substitute_phv_relids - adjust PlaceHolderVar relid sets after pulling up
3862 : * a subquery or removing an RTE_RESULT jointree item
3863 : *
3864 : * Find any PlaceHolderVar nodes in the given tree that reference the
3865 : * pulled-up relid, and change them to reference the replacement relid(s).
3866 : *
3867 : * NOTE: although this has the form of a walker, we cheat and modify the
3868 : * nodes in-place. This should be OK since the tree was copied by
3869 : * pullup_replace_vars earlier. Avoid scribbling on the original values of
3870 : * the bitmapsets, though, because expression_tree_mutator doesn't copy those.
3871 : */
3872 :
3873 : typedef struct
3874 : {
3875 : int varno;
3876 : int sublevels_up;
3877 : Relids subrelids;
3878 : } substitute_phv_relids_context;
3879 :
3880 : static bool
3881 193810 : substitute_phv_relids_walker(Node *node,
3882 : substitute_phv_relids_context *context)
3883 : {
3884 193810 : if (node == NULL)
3885 74564 : return false;
3886 119246 : if (IsA(node, PlaceHolderVar))
3887 : {
3888 5558 : PlaceHolderVar *phv = (PlaceHolderVar *) node;
3889 :
3890 11084 : if (phv->phlevelsup == context->sublevels_up &&
3891 5526 : bms_is_member(context->varno, phv->phrels))
3892 : {
3893 7564 : phv->phrels = bms_union(phv->phrels,
3894 3782 : context->subrelids);
3895 3782 : phv->phrels = bms_del_member(phv->phrels,
3896 : context->varno);
3897 : /* Assert we haven't broken the PHV */
3898 : Assert(!bms_is_empty(phv->phrels));
3899 : }
3900 : /* fall through to examine children */
3901 : }
3902 119246 : if (IsA(node, Query))
3903 : {
3904 : /* Recurse into subselects */
3905 : bool result;
3906 :
3907 3082 : context->sublevels_up++;
3908 3082 : result = query_tree_walker((Query *) node,
3909 : substitute_phv_relids_walker,
3910 : (void *) context, 0);
3911 3082 : context->sublevels_up--;
3912 3082 : return result;
3913 : }
3914 : /* Shouldn't need to handle planner auxiliary nodes here */
3915 : Assert(!IsA(node, SpecialJoinInfo));
3916 : Assert(!IsA(node, AppendRelInfo));
3917 : Assert(!IsA(node, PlaceHolderInfo));
3918 : Assert(!IsA(node, MinMaxAggInfo));
3919 :
3920 116164 : return expression_tree_walker(node, substitute_phv_relids_walker,
3921 : (void *) context);
3922 : }
3923 :
3924 : static void
3925 1840 : substitute_phv_relids(Node *node, int varno, Relids subrelids)
3926 : {
3927 : substitute_phv_relids_context context;
3928 :
3929 1840 : context.varno = varno;
3930 1840 : context.sublevels_up = 0;
3931 1840 : context.subrelids = subrelids;
3932 :
3933 : /*
3934 : * Must be prepared to start with a Query or a bare expression tree.
3935 : */
3936 1840 : query_or_expression_tree_walker(node,
3937 : substitute_phv_relids_walker,
3938 : (void *) &context,
3939 : 0);
3940 1840 : }
3941 :
3942 : /*
3943 : * fix_append_rel_relids: update RT-index fields of AppendRelInfo nodes
3944 : *
3945 : * When we pull up a subquery, any AppendRelInfo references to the subquery's
3946 : * RT index have to be replaced by the substituted relid (and there had better
3947 : * be only one). We also need to apply substitute_phv_relids to their
3948 : * translated_vars lists, since those might contain PlaceHolderVars.
3949 : *
3950 : * We assume we may modify the AppendRelInfo nodes in-place.
3951 : */
3952 : static void
3953 4566 : fix_append_rel_relids(PlannerInfo *root, int varno, Relids subrelids)
3954 : {
3955 : ListCell *l;
3956 4566 : int subvarno = -1;
3957 :
3958 : /*
3959 : * We only want to extract the member relid once, but we mustn't fail
3960 : * immediately if there are multiple members; it could be that none of the
3961 : * AppendRelInfo nodes refer to it. So compute it on first use. Note that
3962 : * bms_singleton_member will complain if set is not singleton.
3963 : */
3964 9790 : foreach(l, root->append_rel_list)
3965 : {
3966 5224 : AppendRelInfo *appinfo = (AppendRelInfo *) lfirst(l);
3967 :
3968 : /* The parent_relid shouldn't ever be a pullup target */
3969 : Assert(appinfo->parent_relid != varno);
3970 :
3971 5224 : if (appinfo->child_relid == varno)
3972 : {
3973 2894 : if (subvarno < 0)
3974 2894 : subvarno = bms_singleton_member(subrelids);
3975 2894 : appinfo->child_relid = subvarno;
3976 : }
3977 :
3978 : /* Also fix up any PHVs in its translated vars */
3979 5224 : if (root->glob->lastPHId != 0)
3980 114 : substitute_phv_relids((Node *) appinfo->translated_vars,
3981 : varno, subrelids);
3982 : }
3983 4566 : }
3984 :
3985 : /*
3986 : * get_relids_in_jointree: get set of RT indexes present in a jointree
3987 : *
3988 : * Base-relation relids are always included in the result.
3989 : * If include_outer_joins is true, outer-join RT indexes are included.
3990 : * If include_inner_joins is true, inner-join RT indexes are included.
3991 : *
3992 : * Note that for most purposes in the planner, outer joins are included
3993 : * in standard relid sets. Setting include_inner_joins true is only
3994 : * appropriate for special purposes during subquery flattening.
3995 : */
3996 : Relids
3997 77620 : get_relids_in_jointree(Node *jtnode, bool include_outer_joins,
3998 : bool include_inner_joins)
3999 : {
4000 77620 : Relids result = NULL;
4001 :
4002 77620 : if (jtnode == NULL)
4003 0 : return result;
4004 77620 : if (IsA(jtnode, RangeTblRef))
4005 : {
4006 38796 : int varno = ((RangeTblRef *) jtnode)->rtindex;
4007 :
4008 38796 : result = bms_make_singleton(varno);
4009 : }
4010 38824 : else if (IsA(jtnode, FromExpr))
4011 : {
4012 34498 : FromExpr *f = (FromExpr *) jtnode;
4013 : ListCell *l;
4014 :
4015 70084 : foreach(l, f->fromlist)
4016 : {
4017 35586 : result = bms_join(result,
4018 35586 : get_relids_in_jointree(lfirst(l),
4019 : include_outer_joins,
4020 : include_inner_joins));
4021 : }
4022 : }
4023 4326 : else if (IsA(jtnode, JoinExpr))
4024 : {
4025 4326 : JoinExpr *j = (JoinExpr *) jtnode;
4026 :
4027 4326 : result = get_relids_in_jointree(j->larg,
4028 : include_outer_joins,
4029 : include_inner_joins);
4030 4326 : result = bms_join(result,
4031 : get_relids_in_jointree(j->rarg,
4032 : include_outer_joins,
4033 : include_inner_joins));
4034 4326 : if (j->rtindex)
4035 : {
4036 4048 : if (j->jointype == JOIN_INNER)
4037 : {
4038 1550 : if (include_inner_joins)
4039 168 : result = bms_add_member(result, j->rtindex);
4040 : }
4041 : else
4042 : {
4043 2498 : if (include_outer_joins)
4044 1430 : result = bms_add_member(result, j->rtindex);
4045 : }
4046 : }
4047 : }
4048 : else
4049 0 : elog(ERROR, "unrecognized node type: %d",
4050 : (int) nodeTag(jtnode));
4051 77620 : return result;
4052 : }
4053 :
4054 : /*
4055 : * get_relids_for_join: get set of base+OJ RT indexes making up a join
4056 : */
4057 : Relids
4058 322 : get_relids_for_join(Query *query, int joinrelid)
4059 : {
4060 : Node *jtnode;
4061 :
4062 322 : jtnode = find_jointree_node_for_rel((Node *) query->jointree,
4063 : joinrelid);
4064 322 : if (!jtnode)
4065 0 : elog(ERROR, "could not find join node %d", joinrelid);
4066 322 : return get_relids_in_jointree(jtnode, true, false);
4067 : }
4068 :
4069 : /*
4070 : * find_jointree_node_for_rel: locate jointree node for a base or join RT index
4071 : *
4072 : * Returns NULL if not found
4073 : */
4074 : static Node *
4075 1562 : find_jointree_node_for_rel(Node *jtnode, int relid)
4076 : {
4077 1562 : if (jtnode == NULL)
4078 0 : return NULL;
4079 1562 : if (IsA(jtnode, RangeTblRef))
4080 : {
4081 406 : int varno = ((RangeTblRef *) jtnode)->rtindex;
4082 :
4083 406 : if (relid == varno)
4084 0 : return jtnode;
4085 : }
4086 1156 : else if (IsA(jtnode, FromExpr))
4087 : {
4088 332 : FromExpr *f = (FromExpr *) jtnode;
4089 : ListCell *l;
4090 :
4091 350 : foreach(l, f->fromlist)
4092 : {
4093 350 : jtnode = find_jointree_node_for_rel(lfirst(l), relid);
4094 350 : if (jtnode)
4095 332 : return jtnode;
4096 : }
4097 : }
4098 824 : else if (IsA(jtnode, JoinExpr))
4099 : {
4100 824 : JoinExpr *j = (JoinExpr *) jtnode;
4101 :
4102 824 : if (relid == j->rtindex)
4103 322 : return jtnode;
4104 502 : jtnode = find_jointree_node_for_rel(j->larg, relid);
4105 502 : if (jtnode)
4106 114 : return jtnode;
4107 388 : jtnode = find_jointree_node_for_rel(j->rarg, relid);
4108 388 : if (jtnode)
4109 388 : return jtnode;
4110 : }
4111 : else
4112 0 : elog(ERROR, "unrecognized node type: %d",
4113 : (int) nodeTag(jtnode));
4114 406 : return NULL;
4115 : }
|