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