Branch data 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 : : * preprocess_relation_rtes
8 : : * replace_empty_jointree
9 : : * pull_up_sublinks
10 : : * preprocess_function_rtes
11 : : * pull_up_subqueries
12 : : * flatten_simple_union_all
13 : : * do expression preprocessing (including flattening JOIN alias vars)
14 : : * reduce_outer_joins
15 : : * remove_useless_result_rtes
16 : : *
17 : : *
18 : : * Portions Copyright (c) 1996-2026, PostgreSQL Global Development Group
19 : : * Portions Copyright (c) 1994, Regents of the University of California
20 : : *
21 : : *
22 : : * IDENTIFICATION
23 : : * src/backend/optimizer/prep/prepjointree.c
24 : : *
25 : : *-------------------------------------------------------------------------
26 : : */
27 : : #include "postgres.h"
28 : :
29 : : #include "access/table.h"
30 : : #include "catalog/pg_type.h"
31 : : #include "funcapi.h"
32 : : #include "miscadmin.h"
33 : : #include "nodes/makefuncs.h"
34 : : #include "nodes/multibitmapset.h"
35 : : #include "nodes/nodeFuncs.h"
36 : : #include "optimizer/clauses.h"
37 : : #include "optimizer/optimizer.h"
38 : : #include "optimizer/placeholder.h"
39 : : #include "optimizer/plancat.h"
40 : : #include "optimizer/prep.h"
41 : : #include "optimizer/subselect.h"
42 : : #include "optimizer/tlist.h"
43 : : #include "parser/parse_relation.h"
44 : : #include "parser/parsetree.h"
45 : : #include "rewrite/rewriteHandler.h"
46 : : #include "rewrite/rewriteManip.h"
47 : : #include "utils/rel.h"
48 : :
49 : :
50 : : typedef struct nullingrel_info
51 : : {
52 : : /*
53 : : * For each leaf RTE, nullingrels[rti] is the set of relids of outer joins
54 : : * that potentially null that RTE.
55 : : */
56 : : Relids *nullingrels;
57 : : /* Length of range table (maximum index in nullingrels[]) */
58 : : int rtlength; /* used only for assertion checks */
59 : : } nullingrel_info;
60 : :
61 : : /* Options for wrapping an expression for identification purposes */
62 : : typedef enum ReplaceWrapOption
63 : : {
64 : : REPLACE_WRAP_NONE, /* no expressions need to be wrapped */
65 : : REPLACE_WRAP_ALL, /* all expressions need to be wrapped */
66 : : REPLACE_WRAP_VARFREE, /* variable-free expressions need to be
67 : : * wrapped */
68 : : } ReplaceWrapOption;
69 : :
70 : : typedef struct pullup_replace_vars_context
71 : : {
72 : : PlannerInfo *root;
73 : : List *targetlist; /* tlist of subquery being pulled up */
74 : : RangeTblEntry *target_rte; /* RTE of subquery */
75 : : int result_relation; /* the index of the result relation in the
76 : : * rewritten query */
77 : : Relids relids; /* relids within subquery, as numbered after
78 : : * pullup (set only if target_rte->lateral) */
79 : : nullingrel_info *nullinfo; /* per-RTE nullingrel info (set only if
80 : : * target_rte->lateral) */
81 : : bool *outer_hasSubLinks; /* -> outer query's hasSubLinks */
82 : : int varno; /* varno of subquery */
83 : : ReplaceWrapOption wrap_option; /* do we need certain outputs to be PHVs? */
84 : : Node **rv_cache; /* cache for results with PHVs */
85 : : } pullup_replace_vars_context;
86 : :
87 : : typedef struct reduce_outer_joins_pass1_state
88 : : {
89 : : Relids relids; /* base relids within this subtree */
90 : : bool contains_outer; /* does subtree contain outer join(s)? */
91 : : Relids nullable_rels; /* base relids that are nullable within this
92 : : * subtree */
93 : : Node *jtnode; /* the jointree node this state describes */
94 : : List *sub_states; /* List of states for subtree components */
95 : : } reduce_outer_joins_pass1_state;
96 : :
97 : : typedef struct reduce_outer_joins_pass2_state
98 : : {
99 : : Relids inner_reduced; /* OJ relids reduced to plain inner joins */
100 : : List *partial_reduced; /* List of partially reduced FULL joins */
101 : : Relids anti_reduced; /* OJ relids reduced to antijoins */
102 : : } reduce_outer_joins_pass2_state;
103 : :
104 : : typedef struct reduce_outer_joins_partial_state
105 : : {
106 : : int full_join_rti; /* RT index of a formerly-FULL join */
107 : : Relids unreduced_side; /* relids in its still-nullable side */
108 : : } reduce_outer_joins_partial_state;
109 : :
110 : : static Query *expand_virtual_generated_columns(PlannerInfo *root, Query *parse,
111 : : RangeTblEntry *rte, int rt_index,
112 : : Relation relation);
113 : : static Node *pull_up_sublinks_jointree_recurse(PlannerInfo *root, Node *jtnode,
114 : : Relids *relids);
115 : : static Node *pull_up_sublinks_qual_recurse(PlannerInfo *root, Node *node,
116 : : Node **jtlink1, Relids available_rels1,
117 : : Node **jtlink2, Relids available_rels2);
118 : : static Node *pull_up_subqueries_recurse(PlannerInfo *root, Node *jtnode,
119 : : JoinExpr *lowest_outer_join,
120 : : AppendRelInfo *containing_appendrel);
121 : : static Node *pull_up_simple_subquery(PlannerInfo *root, Node *jtnode,
122 : : RangeTblEntry *rte,
123 : : JoinExpr *lowest_outer_join,
124 : : AppendRelInfo *containing_appendrel);
125 : : static Node *pull_up_simple_union_all(PlannerInfo *root, Node *jtnode,
126 : : RangeTblEntry *rte);
127 : : static void pull_up_union_leaf_queries(Node *setOp, PlannerInfo *root,
128 : : int parentRTindex, Query *setOpQuery,
129 : : int childRToffset);
130 : : static void make_setop_translation_list(Query *query, int newvarno,
131 : : AppendRelInfo *appinfo);
132 : : static bool is_simple_subquery(PlannerInfo *root, Query *subquery,
133 : : RangeTblEntry *rte,
134 : : JoinExpr *lowest_outer_join);
135 : : static Node *pull_up_simple_values(PlannerInfo *root, Node *jtnode,
136 : : RangeTblEntry *rte);
137 : : static bool is_simple_values(PlannerInfo *root, RangeTblEntry *rte);
138 : : static Node *pull_up_constant_function(PlannerInfo *root, Node *jtnode,
139 : : RangeTblEntry *rte,
140 : : AppendRelInfo *containing_appendrel);
141 : : static bool is_simple_union_all(Query *subquery);
142 : : static bool is_simple_union_all_recurse(Node *setOp, Query *setOpQuery,
143 : : List *colTypes);
144 : : static bool is_safe_append_member(Query *subquery);
145 : : static bool jointree_contains_lateral_outer_refs(PlannerInfo *root,
146 : : Node *jtnode, bool restricted,
147 : : Relids safe_upper_varnos);
148 : : static void flatten_join_alias_vars_in_jointree(PlannerInfo *root,
149 : : Node *jtnode);
150 : : static void perform_pullup_replace_vars(PlannerInfo *root,
151 : : pullup_replace_vars_context *rvcontext,
152 : : AppendRelInfo *containing_appendrel);
153 : : static void replace_vars_in_jointree(Node *jtnode,
154 : : pullup_replace_vars_context *context);
155 : : static Node *pullup_replace_vars(Node *expr,
156 : : pullup_replace_vars_context *context);
157 : : static Node *pullup_replace_vars_callback(const Var *var,
158 : : replace_rte_variables_context *context);
159 : : static Query *pullup_replace_vars_subquery(Query *query,
160 : : pullup_replace_vars_context *context);
161 : : static reduce_outer_joins_pass1_state *reduce_outer_joins_pass1(Node *jtnode);
162 : : static void reduce_outer_joins_pass2(Node *jtnode,
163 : : reduce_outer_joins_pass1_state *state1,
164 : : reduce_outer_joins_pass2_state *state2,
165 : : PlannerInfo *root,
166 : : Relids nonnullable_rels,
167 : : List *forced_null_vars);
168 : : static void report_reduced_full_join(reduce_outer_joins_pass2_state *state2,
169 : : int rtindex, Relids relids);
170 : : static void remove_redundant_nullability_quals(Node *jtnode,
171 : : Relids antijoins);
172 : : static Node *strip_redundant_nullability_quals(Node *quals, Relids antijoins);
173 : : static bool forced_null_var_is_attnotnull(PlannerInfo *root,
174 : : List *forced_null_vars,
175 : : reduce_outer_joins_pass1_state *state);
176 : : static bool forced_null_var_is_nonnullable(PlannerInfo *root,
177 : : List *forced_null_vars,
178 : : reduce_outer_joins_pass1_state *state,
179 : : List *extra_quals);
180 : : static Node *remove_useless_results_recurse(PlannerInfo *root, Node *jtnode,
181 : : Relids baserels,
182 : : Node **parent_quals,
183 : : Relids *dropped_outer_joins);
184 : : static int get_result_relid(PlannerInfo *root, Node *jtnode);
185 : : static void remove_result_refs(PlannerInfo *root, int varno, Node *newjtloc);
186 : : static bool find_dependent_phvs(PlannerInfo *root, int varno, Relids baserels);
187 : : static bool find_dependent_phvs_in_jointree(PlannerInfo *root,
188 : : Node *node, int varno,
189 : : Relids baserels);
190 : : static void substitute_phv_relids(Node *node,
191 : : int varno, Relids subrelids);
192 : : static void fix_append_rel_relids(PlannerInfo *root, int varno,
193 : : Relids subrelids);
194 : : static Node *find_jointree_node_for_rel(Node *jtnode, int relid);
195 : : static nullingrel_info *get_nullingrels(Query *parse);
196 : : static void get_nullingrels_recurse(Node *jtnode, Relids upper_nullingrels,
197 : : nullingrel_info *info);
198 : :
199 : :
200 : : /*
201 : : * transform_MERGE_to_join
202 : : * Replace a MERGE's jointree to also include the target relation.
203 : : */
204 : : void
205 : 406319 : transform_MERGE_to_join(Query *parse)
206 : : {
207 : : RangeTblEntry *joinrte;
208 : : JoinExpr *joinexpr;
209 : : bool have_action[NUM_MERGE_MATCH_KINDS];
210 : : JoinType jointype;
211 : : int joinrti;
212 : : List *vars;
213 : : RangeTblRef *rtr;
214 : : FromExpr *target;
215 : : Node *source;
216 : : int sourcerti;
217 : : Relids nullable_relids;
218 : : Relids nullingrel;
219 : :
220 [ + + ]: 406319 : if (parse->commandType != CMD_MERGE)
221 : 404676 : return;
222 : :
223 : : /* XXX probably bogus */
224 : 1643 : vars = NIL;
225 : :
226 : : /*
227 : : * Work out what kind of join is required. If there any WHEN NOT MATCHED
228 : : * BY SOURCE/TARGET actions, an outer join is required so that we process
229 : : * all unmatched tuples from the source and/or target relations.
230 : : * Otherwise, we can use an inner join.
231 : : */
232 : 1643 : have_action[MERGE_WHEN_MATCHED] = false;
233 : 1643 : have_action[MERGE_WHEN_NOT_MATCHED_BY_SOURCE] = false;
234 : 1643 : have_action[MERGE_WHEN_NOT_MATCHED_BY_TARGET] = false;
235 : :
236 [ + - + + : 5837 : foreach_node(MergeAction, action, parse->mergeActionList)
+ + ]
237 : : {
238 [ + + ]: 2551 : if (action->commandType != CMD_NOTHING)
239 : 2478 : have_action[action->matchKind] = true;
240 : : }
241 : :
242 [ + + ]: 1643 : if (have_action[MERGE_WHEN_NOT_MATCHED_BY_SOURCE] &&
243 [ + + ]: 134 : have_action[MERGE_WHEN_NOT_MATCHED_BY_TARGET])
244 : 95 : jointype = JOIN_FULL;
245 [ + + ]: 1548 : else if (have_action[MERGE_WHEN_NOT_MATCHED_BY_SOURCE])
246 : 39 : jointype = JOIN_LEFT;
247 [ + + ]: 1509 : else if (have_action[MERGE_WHEN_NOT_MATCHED_BY_TARGET])
248 : 724 : jointype = JOIN_RIGHT;
249 : : else
250 : 785 : jointype = JOIN_INNER;
251 : :
252 : : /* Manufacture a join RTE to use. */
253 : 1643 : joinrte = makeNode(RangeTblEntry);
254 : 1643 : joinrte->rtekind = RTE_JOIN;
255 : 1643 : joinrte->jointype = jointype;
256 : 1643 : joinrte->joinmergedcols = 0;
257 : 1643 : joinrte->joinaliasvars = vars;
258 : 1643 : joinrte->joinleftcols = NIL; /* MERGE does not allow JOIN USING */
259 : 1643 : joinrte->joinrightcols = NIL; /* ditto */
260 : 1643 : joinrte->join_using_alias = NULL;
261 : :
262 : 1643 : joinrte->alias = NULL;
263 : 1643 : joinrte->eref = makeAlias("*MERGE*", NIL);
264 : 1643 : joinrte->lateral = false;
265 : 1643 : joinrte->inh = false;
266 : 1643 : joinrte->inFromCl = true;
267 : :
268 : : /*
269 : : * Add completed RTE to pstate's range table list, so that we know its
270 : : * index.
271 : : */
272 : 1643 : parse->rtable = lappend(parse->rtable, joinrte);
273 : 1643 : joinrti = list_length(parse->rtable);
274 : :
275 : : /*
276 : : * Create a JOIN between the target and the source relation.
277 : : *
278 : : * Here the target is identified by parse->mergeTargetRelation. For a
279 : : * regular table, this will equal parse->resultRelation, but for a
280 : : * trigger-updatable view, it will be the expanded view subquery that we
281 : : * need to pull data from.
282 : : *
283 : : * The source relation is in parse->jointree->fromlist, but any quals in
284 : : * parse->jointree->quals are restrictions on the target relation (if the
285 : : * target relation is an auto-updatable view).
286 : : */
287 : : /* target rel, with any quals */
288 : 1643 : rtr = makeNode(RangeTblRef);
289 : 1643 : rtr->rtindex = parse->mergeTargetRelation;
290 : 1643 : target = makeFromExpr(list_make1(rtr), parse->jointree->quals);
291 : :
292 : : /* source rel (expect exactly one -- see transformMergeStmt()) */
293 : : Assert(list_length(parse->jointree->fromlist) == 1);
294 : 1643 : source = linitial(parse->jointree->fromlist);
295 : :
296 : : /*
297 : : * index of source rel (expect either a RangeTblRef or a JoinExpr -- see
298 : : * transformFromClauseItem()).
299 : : */
300 [ + + ]: 1643 : if (IsA(source, RangeTblRef))
301 : 1558 : sourcerti = ((RangeTblRef *) source)->rtindex;
302 [ + - ]: 85 : else if (IsA(source, JoinExpr))
303 : 85 : sourcerti = ((JoinExpr *) source)->rtindex;
304 : : else
305 : : {
306 [ # # ]: 0 : elog(ERROR, "unrecognized source node type: %d",
307 : : (int) nodeTag(source));
308 : : sourcerti = 0; /* keep compiler quiet */
309 : : }
310 : :
311 : : /* Join the source and target */
312 : 1643 : joinexpr = makeNode(JoinExpr);
313 : 1643 : joinexpr->jointype = jointype;
314 : 1643 : joinexpr->isNatural = false;
315 : 1643 : joinexpr->larg = (Node *) target;
316 : 1643 : joinexpr->rarg = source;
317 : 1643 : joinexpr->usingClause = NIL;
318 : 1643 : joinexpr->join_using_alias = NULL;
319 : 1643 : joinexpr->quals = parse->mergeJoinCondition;
320 : 1643 : joinexpr->alias = NULL;
321 : 1643 : joinexpr->rtindex = joinrti;
322 : :
323 : : /* Make the new join be the sole entry in the query's jointree */
324 : 1643 : parse->jointree->fromlist = list_make1(joinexpr);
325 : 1643 : parse->jointree->quals = NULL;
326 : :
327 : : /*
328 : : * Find all relations nullable by the join. If that includes the source
329 : : * relation, and it is itself a join, we must include all relations under
330 : : * it, since there may be Vars above the new join referring to relations
331 : : * under the source join. If the target relation is a trigger-updatable
332 : : * view, we pull data from the expanded view subquery (identified by
333 : : * parse->mergeTargetRelation), so it must be included if it's on the
334 : : * nullable side of the join (but we don't need to include relations under
335 : : * it, since the query cannot reference them directly). If
336 : : * parse->mergeTargetRelation == parse->resultRelation, we have a regular
337 : : * target table, whose attributes are not read from the join.
338 : : *
339 : : * Note: for a trigger-updatable view, this causes Vars in MERGE actions
340 : : * to be marked, but not target Vars in the RETURNING list --- see
341 : : * ApplyRetrieveRule(), which points the latter at parse->resultRelation
342 : : * (the unmodified copy of the target RTE, whose values are supplied by
343 : : * ModifyTable, not read from the join), while leaving the former to refer
344 : : * to the expanded view subquery (parse->mergeTargetRelation).
345 : : */
346 [ + + ]: 1643 : if (jointype == JOIN_LEFT)
347 : 39 : nullable_relids = get_relids_in_jointree(source, true, true);
348 [ + + ]: 1604 : else if (jointype == JOIN_RIGHT &&
349 [ + + ]: 724 : parse->mergeTargetRelation != parse->resultRelation)
350 : 35 : nullable_relids = bms_make_singleton(parse->mergeTargetRelation);
351 [ + + ]: 1569 : else if (jointype == JOIN_FULL)
352 : : {
353 : 95 : nullable_relids = get_relids_in_jointree(source, true, true);
354 [ + + ]: 95 : if (parse->mergeTargetRelation != parse->resultRelation)
355 : 5 : nullable_relids = bms_add_member(nullable_relids,
356 : : parse->mergeTargetRelation);
357 : : }
358 : : else
359 : 1474 : nullable_relids = NULL;
360 : :
361 [ + + ]: 1643 : nullingrel = nullable_relids ? bms_make_singleton(joinrti) : NULL;
362 : :
363 : : /*
364 : : * Mark Vars used above the join as nullable by the join. This includes
365 : : * Vars in the query targetlist, action expressions, and RETURNING list.
366 : : * Vars from the latter expressions will be added to the targetlist by
367 : : * preprocess_targetlist(), so they must be marked correctly here.
368 : : *
369 : : * Normally the query targetlist is empty for MERGE, but for a
370 : : * trigger-updatable view it contains a whole-row Var referring to the
371 : : * expanded view query.
372 : : */
373 [ + + ]: 1643 : if (nullable_relids != NULL)
374 : : {
375 : 169 : parse->targetList = (List *)
376 : 169 : add_nulling_relids((Node *) parse->targetList,
377 : : nullable_relids, nullingrel);
378 : :
379 [ + - + + : 776 : foreach_node(MergeAction, action, parse->mergeActionList)
+ + ]
380 : : {
381 : 438 : action->qual =
382 : 438 : add_nulling_relids(action->qual,
383 : : nullable_relids, nullingrel);
384 : :
385 : 438 : action->targetList = (List *)
386 : 438 : add_nulling_relids((Node *) action->targetList,
387 : : nullable_relids, nullingrel);
388 : : }
389 : :
390 : 169 : parse->returningList = (List *)
391 : 169 : add_nulling_relids((Node *) parse->returningList,
392 : : nullable_relids, nullingrel);
393 : : }
394 : :
395 : : /*
396 : : * If there are any WHEN NOT MATCHED BY SOURCE actions, the executor will
397 : : * use the join condition to distinguish between MATCHED and NOT MATCHED
398 : : * BY SOURCE cases. Otherwise, it's no longer needed, and we set it to
399 : : * NULL, saving cycles during planning and execution.
400 : : *
401 : : * We need to be careful though: the executor evaluates this condition
402 : : * using the output of the join subplan node, which nulls the output from
403 : : * the source relation when the join condition doesn't match. That risks
404 : : * producing incorrect results when rechecking using a "non-strict" join
405 : : * condition, such as "src.col IS NOT DISTINCT FROM tgt.col". To guard
406 : : * against that, we add an additional "src IS NOT NULL" check to the join
407 : : * condition, so that it does the right thing when performing a recheck
408 : : * based on the output of the join subplan.
409 : : */
410 [ + + ]: 1643 : if (have_action[MERGE_WHEN_NOT_MATCHED_BY_SOURCE])
411 : : {
412 : : Var *var;
413 : : NullTest *ntest;
414 : :
415 : : /* source wholerow Var */
416 : 134 : var = makeWholeRowVar(rt_fetch(sourcerti, parse->rtable),
417 : : sourcerti, 0, false);
418 : :
419 : : /* "src IS NOT NULL" check */
420 : 134 : ntest = makeNode(NullTest);
421 : 134 : ntest->arg = (Expr *) var;
422 : 134 : ntest->nulltesttype = IS_NOT_NULL;
423 : 134 : ntest->argisrow = false;
424 : 134 : ntest->location = -1;
425 : :
426 : : /* combine it with the original join condition */
427 : 134 : parse->mergeJoinCondition =
428 : 134 : (Node *) make_and_qual((Node *) ntest, parse->mergeJoinCondition);
429 : :
430 : : /*
431 : : * Mark Vars used in the new join condition as nullable by the join,
432 : : * since it will be used above the join. This creates a copy, without
433 : : * modifying the original join condition inside the join.
434 : : */
435 : 134 : parse->mergeJoinCondition =
436 : 134 : add_nulling_relids(parse->mergeJoinCondition,
437 : : nullable_relids, nullingrel);
438 : : }
439 : : else
440 : 1509 : parse->mergeJoinCondition = NULL; /* join condition not needed */
441 : : }
442 : :
443 : : /*
444 : : * preprocess_relation_rtes
445 : : * Do the preprocessing work for any relation RTEs in the FROM clause.
446 : : *
447 : : * This scans the rangetable for relation RTEs and retrieves the necessary
448 : : * catalog information for each relation. Using this information, it clears
449 : : * the inh flag for any relation that has no children, collects not-null
450 : : * attribute numbers for any relation that has column not-null constraints, and
451 : : * expands virtual generated columns for any relation that contains them.
452 : : *
453 : : * Note that expanding virtual generated columns may cause the query tree to
454 : : * have new copies of rangetable entries. Therefore, we have to use list_nth
455 : : * instead of foreach when iterating over the query's rangetable.
456 : : *
457 : : * Returns a modified copy of the query tree, if any relations with virtual
458 : : * generated columns are present.
459 : : */
460 : : Query *
461 : 445530 : preprocess_relation_rtes(PlannerInfo *root)
462 : : {
463 : 445530 : Query *parse = root->parse;
464 : : int rtable_size;
465 : : int rt_index;
466 : :
467 : 445530 : rtable_size = list_length(parse->rtable);
468 : :
469 [ + + ]: 999158 : for (rt_index = 0; rt_index < rtable_size; rt_index++)
470 : : {
471 : 553628 : RangeTblEntry *rte = rt_fetch(rt_index + 1, parse->rtable);
472 : : Relation relation;
473 : :
474 : : /* We only care about relation RTEs. */
475 [ + + ]: 553628 : if (rte->rtekind != RTE_RELATION)
476 : 184127 : continue;
477 : :
478 : : /*
479 : : * We need not lock the relation since it was already locked by the
480 : : * rewriter.
481 : : */
482 : 369501 : relation = table_open(rte->relid, NoLock);
483 : :
484 : : /*
485 : : * Check to see if the relation actually has any children; if not,
486 : : * clear the inh flag so we can treat it as a plain base relation.
487 : : *
488 : : * Note: this could give a false-positive result, if the rel once had
489 : : * children but no longer does. We used to be able to clear rte->inh
490 : : * later on when we discovered that, but no more; we have to handle
491 : : * such cases as full-fledged inheritance.
492 : : */
493 [ + + ]: 369501 : if (rte->inh)
494 : 308523 : rte->inh = relation->rd_rel->relhassubclass;
495 : :
496 : : /*
497 : : * Check to see if the relation has any column not-null constraints;
498 : : * if so, retrieve the constraint information and store it in a
499 : : * relation OID based hash table.
500 : : */
501 : 369501 : get_relation_notnullatts(root, relation);
502 : :
503 : : /*
504 : : * Check to see if the relation has any virtual generated columns; if
505 : : * so, replace all Var nodes in the query that reference these columns
506 : : * with the generation expressions.
507 : : */
508 : 369501 : parse = expand_virtual_generated_columns(root, parse,
509 : : rte, rt_index + 1,
510 : : relation);
511 : :
512 : 369501 : table_close(relation, NoLock);
513 : : }
514 : :
515 : 445530 : return parse;
516 : : }
517 : :
518 : : /*
519 : : * expand_virtual_generated_columns
520 : : * Expand virtual generated columns for the given relation.
521 : : *
522 : : * This checks whether the given relation has any virtual generated columns,
523 : : * and if so, replaces all Var nodes in the query that reference those columns
524 : : * with their generation expressions.
525 : : *
526 : : * Returns a modified copy of the query tree if the relation contains virtual
527 : : * generated columns.
528 : : */
529 : : static Query *
530 : 369501 : expand_virtual_generated_columns(PlannerInfo *root, Query *parse,
531 : : RangeTblEntry *rte, int rt_index,
532 : : Relation relation)
533 : : {
534 : : TupleDesc tupdesc;
535 : :
536 : : /* Only normal relations can have virtual generated columns */
537 : : Assert(rte->rtekind == RTE_RELATION);
538 : :
539 : 369501 : tupdesc = RelationGetDescr(relation);
540 [ + + + + ]: 369501 : if (tupdesc->constr && tupdesc->constr->has_generated_virtual)
541 : : {
542 : 1179 : List *tlist = NIL;
543 : : pullup_replace_vars_context rvcontext;
544 : 1179 : List *save_exclRelTlist = NIL;
545 : :
546 [ + + ]: 4714 : for (int i = 0; i < tupdesc->natts; i++)
547 : : {
548 : 3535 : Form_pg_attribute attr = TupleDescAttr(tupdesc, i);
549 : : TargetEntry *tle;
550 : :
551 [ + + ]: 3535 : if (attr->attgenerated == ATTRIBUTE_GENERATED_VIRTUAL)
552 : : {
553 : : Node *defexpr;
554 : :
555 : 1569 : defexpr = build_generation_expression(relation, i + 1);
556 : 1569 : ChangeVarNodes(defexpr, 1, rt_index, 0);
557 : :
558 : 1569 : tle = makeTargetEntry((Expr *) defexpr, i + 1, 0, false);
559 : 1569 : tlist = lappend(tlist, tle);
560 : : }
561 : : else
562 : : {
563 : : Var *var;
564 : :
565 : 1966 : var = makeVar(rt_index,
566 : 1966 : i + 1,
567 : : attr->atttypid,
568 : : attr->atttypmod,
569 : : attr->attcollation,
570 : : 0);
571 : :
572 : 1966 : tle = makeTargetEntry((Expr *) var, i + 1, 0, false);
573 : 1966 : tlist = lappend(tlist, tle);
574 : : }
575 : : }
576 : :
577 : : Assert(list_length(tlist) > 0);
578 : : Assert(!rte->lateral);
579 : :
580 : : /*
581 : : * The relation's targetlist items are now in the appropriate form to
582 : : * insert into the query, except that we may need to wrap them in
583 : : * PlaceHolderVars. Set up required context data for
584 : : * pullup_replace_vars.
585 : : */
586 : 1179 : rvcontext.root = root;
587 : 1179 : rvcontext.targetlist = tlist;
588 : 1179 : rvcontext.target_rte = rte;
589 : 1179 : rvcontext.result_relation = parse->resultRelation;
590 : : /* won't need these values */
591 : 1179 : rvcontext.relids = NULL;
592 : 1179 : rvcontext.nullinfo = NULL;
593 : : /* pass NULL for outer_hasSubLinks */
594 : 1179 : rvcontext.outer_hasSubLinks = NULL;
595 : 1179 : rvcontext.varno = rt_index;
596 : : /* this flag will be set below, if needed */
597 : 1179 : rvcontext.wrap_option = REPLACE_WRAP_NONE;
598 : : /* initialize cache array with indexes 0 .. length(tlist) */
599 : 1179 : rvcontext.rv_cache = palloc0_array(Node *, list_length(tlist) + 1);
600 : :
601 : : /*
602 : : * If the query uses grouping sets, we need a PlaceHolderVar for each
603 : : * expression of the relation's targetlist items. (See comments in
604 : : * pull_up_simple_subquery().)
605 : : */
606 [ + + ]: 1179 : if (parse->groupingSets)
607 : 10 : rvcontext.wrap_option = REPLACE_WRAP_ALL;
608 : :
609 : : /*
610 : : * Apply pullup variable replacement throughout the query tree.
611 : : *
612 : : * We intentionally do not touch the EXCLUDED pseudo-relation's
613 : : * targetlist here. Various places in the planner assume that it
614 : : * contains only Vars, and we want that to remain the case. More
615 : : * importantly, we don't want setrefs.c to turn any expanded
616 : : * EXCLUDED.virtual_column expressions in other parts of the query
617 : : * back into Vars referencing the original virtual column, which
618 : : * set_plan_refs() would do if exclRelTlist contained matching
619 : : * expressions.
620 : : */
621 [ + + ]: 1179 : if (parse->onConflict)
622 : : {
623 : 56 : save_exclRelTlist = parse->onConflict->exclRelTlist;
624 : 56 : parse->onConflict->exclRelTlist = NIL;
625 : : }
626 : :
627 : 1179 : parse = (Query *) pullup_replace_vars((Node *) parse, &rvcontext);
628 : :
629 [ + + ]: 1179 : if (parse->onConflict)
630 : 56 : parse->onConflict->exclRelTlist = save_exclRelTlist;
631 : : }
632 : :
633 : 369501 : return parse;
634 : : }
635 : :
636 : : /*
637 : : * replace_empty_jointree
638 : : * If the Query's jointree is empty, replace it with a dummy RTE_RESULT
639 : : * relation.
640 : : *
641 : : * By doing this, we can avoid a bunch of corner cases that formerly existed
642 : : * for SELECTs with omitted FROM clauses. An example is that a subquery
643 : : * with empty jointree previously could not be pulled up, because that would
644 : : * have resulted in an empty relid set, making the subquery not uniquely
645 : : * identifiable for join or PlaceHolderVar processing.
646 : : *
647 : : * Unlike most other functions in this file, this function doesn't recurse;
648 : : * we rely on other processing to invoke it on sub-queries at suitable times.
649 : : */
650 : : void
651 : 445530 : replace_empty_jointree(Query *parse)
652 : : {
653 : : RangeTblEntry *rte;
654 : : Index rti;
655 : : RangeTblRef *rtr;
656 : :
657 : : /* Nothing to do if jointree is already nonempty */
658 [ + + ]: 445530 : if (parse->jointree->fromlist != NIL)
659 : 289359 : return;
660 : :
661 : : /* We mustn't change it in the top level of a setop tree, either */
662 [ + + ]: 156171 : if (parse->setOperations)
663 : 5777 : return;
664 : :
665 : : /* Create suitable RTE */
666 : 150394 : rte = makeNode(RangeTblEntry);
667 : 150394 : rte->rtekind = RTE_RESULT;
668 : 150394 : rte->eref = makeAlias("*RESULT*", NIL);
669 : :
670 : : /* Add it to rangetable */
671 : 150394 : parse->rtable = lappend(parse->rtable, rte);
672 : 150394 : rti = list_length(parse->rtable);
673 : :
674 : : /* And jam a reference into the jointree */
675 : 150394 : rtr = makeNode(RangeTblRef);
676 : 150394 : rtr->rtindex = rti;
677 : 150394 : parse->jointree->fromlist = list_make1(rtr);
678 : : }
679 : :
680 : : /*
681 : : * pull_up_sublinks
682 : : * Attempt to pull up ANY and EXISTS SubLinks to be treated as
683 : : * semijoins or anti-semijoins.
684 : : *
685 : : * A clause "foo op ANY (sub-SELECT)" can be processed by pulling the
686 : : * sub-SELECT up to become a rangetable entry and treating the implied
687 : : * comparisons as quals of a semijoin. However, this optimization *only*
688 : : * works at the top level of WHERE or a JOIN/ON clause, because we cannot
689 : : * distinguish whether the ANY ought to return FALSE or NULL in cases
690 : : * involving NULL inputs. Also, in an outer join's ON clause we can only
691 : : * do this if the sublink is degenerate (ie, references only the nullable
692 : : * side of the join). In that case it is legal to push the semijoin
693 : : * down into the nullable side of the join. If the sublink references any
694 : : * nonnullable-side variables then it would have to be evaluated as part
695 : : * of the outer join, which makes things way too complicated.
696 : : *
697 : : * Under similar conditions, EXISTS and NOT EXISTS clauses can be handled
698 : : * by pulling up the sub-SELECT and creating a semijoin or anti-semijoin.
699 : : *
700 : : * This routine searches for such clauses and does the necessary parsetree
701 : : * transformations if any are found.
702 : : *
703 : : * This routine has to run before preprocess_expression(), so the quals
704 : : * clauses are not yet reduced to implicit-AND format, and are not guaranteed
705 : : * to be AND/OR-flat either. That means we need to recursively search through
706 : : * explicit AND clauses. We stop as soon as we hit a non-AND item.
707 : : */
708 : : void
709 : 32621 : pull_up_sublinks(PlannerInfo *root)
710 : : {
711 : : Node *jtnode;
712 : : Relids relids;
713 : :
714 : : /* Begin recursion through the jointree */
715 : 32621 : jtnode = pull_up_sublinks_jointree_recurse(root,
716 : 32621 : (Node *) root->parse->jointree,
717 : : &relids);
718 : :
719 : : /*
720 : : * root->parse->jointree must always be a FromExpr, so insert a dummy one
721 : : * if we got a bare RangeTblRef or JoinExpr out of the recursion.
722 : : */
723 [ + + ]: 32621 : if (IsA(jtnode, FromExpr))
724 : 20904 : root->parse->jointree = (FromExpr *) jtnode;
725 : : else
726 : 11717 : root->parse->jointree = makeFromExpr(list_make1(jtnode), NULL);
727 : 32621 : }
728 : :
729 : : /*
730 : : * Recurse through jointree nodes for pull_up_sublinks()
731 : : *
732 : : * In addition to returning the possibly-modified jointree node, we return
733 : : * a relids set of the contained rels into *relids.
734 : : */
735 : : static Node *
736 : 112483 : pull_up_sublinks_jointree_recurse(PlannerInfo *root, Node *jtnode,
737 : : Relids *relids)
738 : : {
739 : : /* Since this function recurses, it could be driven to stack overflow. */
740 : 112483 : check_stack_depth();
741 : :
742 [ - + ]: 112483 : if (jtnode == NULL)
743 : : {
744 : 0 : *relids = NULL;
745 : : }
746 [ + + ]: 112483 : else if (IsA(jtnode, RangeTblRef))
747 : : {
748 : 63511 : int varno = ((RangeTblRef *) jtnode)->rtindex;
749 : :
750 : 63511 : *relids = bms_make_singleton(varno);
751 : : /* jtnode is returned unmodified */
752 : : }
753 [ + + ]: 48972 : else if (IsA(jtnode, FromExpr))
754 : : {
755 : 32822 : FromExpr *f = (FromExpr *) jtnode;
756 : 32822 : List *newfromlist = NIL;
757 : 32822 : Relids frelids = NULL;
758 : : FromExpr *newf;
759 : : Node *jtlink;
760 : : ListCell *l;
761 : :
762 : : /* First, recurse to process children and collect their relids */
763 [ + - + + : 68518 : foreach(l, f->fromlist)
+ + ]
764 : : {
765 : : Node *newchild;
766 : : Relids childrelids;
767 : :
768 : 35696 : newchild = pull_up_sublinks_jointree_recurse(root,
769 : 35696 : lfirst(l),
770 : : &childrelids);
771 : 35696 : newfromlist = lappend(newfromlist, newchild);
772 : 35696 : frelids = bms_join(frelids, childrelids);
773 : : }
774 : : /* Build the replacement FromExpr; no quals yet */
775 : 32822 : newf = makeFromExpr(newfromlist, NULL);
776 : : /* Set up a link representing the rebuilt jointree */
777 : 32822 : jtlink = (Node *) newf;
778 : : /* Now process qual --- all children are available for use */
779 : 32822 : newf->quals = pull_up_sublinks_qual_recurse(root, f->quals,
780 : : &jtlink, frelids,
781 : : NULL, NULL);
782 : :
783 : : /*
784 : : * Note that the result will be either newf, or a stack of JoinExprs
785 : : * with newf at the base. We rely on subsequent optimization steps to
786 : : * flatten this and rearrange the joins as needed.
787 : : *
788 : : * Although we could include the pulled-up subqueries in the returned
789 : : * relids, there's no need since upper quals couldn't refer to their
790 : : * outputs anyway.
791 : : */
792 : 32822 : *relids = frelids;
793 : 32822 : jtnode = jtlink;
794 : : }
795 [ + - ]: 16150 : else if (IsA(jtnode, JoinExpr))
796 : : {
797 : : JoinExpr *j;
798 : : Relids leftrelids;
799 : : Relids rightrelids;
800 : : Node *jtlink;
801 : :
802 : : /*
803 : : * Make a modifiable copy of join node, but don't bother copying its
804 : : * subnodes (yet).
805 : : */
806 : 16150 : j = palloc_object(JoinExpr);
807 : 16150 : memcpy(j, jtnode, sizeof(JoinExpr));
808 : 16150 : jtlink = (Node *) j;
809 : :
810 : : /* Recurse to process children and collect their relids */
811 : 16150 : j->larg = pull_up_sublinks_jointree_recurse(root, j->larg,
812 : : &leftrelids);
813 : 16150 : j->rarg = pull_up_sublinks_jointree_recurse(root, j->rarg,
814 : : &rightrelids);
815 : :
816 : : /*
817 : : * Now process qual, showing appropriate child relids as available,
818 : : * and attach any pulled-up jointree items at the right place. In the
819 : : * inner-join case we put new JoinExprs above the existing one (much
820 : : * as for a FromExpr-style join). In outer-join cases the new
821 : : * JoinExprs must go into the nullable side of the outer join. The
822 : : * point of the available_rels machinations is to ensure that we only
823 : : * pull up quals for which that's okay.
824 : : *
825 : : * We don't expect to see any pre-existing JOIN_SEMI, JOIN_ANTI,
826 : : * JOIN_RIGHT_SEMI, or JOIN_RIGHT_ANTI jointypes here.
827 : : */
828 [ + + + + : 16150 : switch (j->jointype)
- ]
829 : : {
830 : 7623 : case JOIN_INNER:
831 : 7623 : j->quals = pull_up_sublinks_qual_recurse(root, j->quals,
832 : : &jtlink,
833 : : bms_union(leftrelids,
834 : : rightrelids),
835 : : NULL, NULL);
836 : 7623 : break;
837 : 8372 : case JOIN_LEFT:
838 : 8372 : j->quals = pull_up_sublinks_qual_recurse(root, j->quals,
839 : : &j->rarg,
840 : : rightrelids,
841 : : NULL, NULL);
842 : 8372 : break;
843 : 45 : case JOIN_FULL:
844 : : /* can't do anything with full-join quals */
845 : 45 : break;
846 : 110 : case JOIN_RIGHT:
847 : 110 : j->quals = pull_up_sublinks_qual_recurse(root, j->quals,
848 : : &j->larg,
849 : : leftrelids,
850 : : NULL, NULL);
851 : 110 : break;
852 : 0 : default:
853 [ # # ]: 0 : elog(ERROR, "unrecognized join type: %d",
854 : : (int) j->jointype);
855 : : break;
856 : : }
857 : :
858 : : /*
859 : : * Although we could include the pulled-up subqueries in the returned
860 : : * relids, there's no need since upper quals couldn't refer to their
861 : : * outputs anyway. But we *do* need to include the join's own rtindex
862 : : * because we haven't yet collapsed join alias variables, so upper
863 : : * levels would mistakenly think they couldn't use references to this
864 : : * join.
865 : : */
866 : 16150 : *relids = bms_join(leftrelids, rightrelids);
867 [ + - ]: 16150 : if (j->rtindex)
868 : 16150 : *relids = bms_add_member(*relids, j->rtindex);
869 : 16150 : jtnode = jtlink;
870 : : }
871 : : else
872 [ # # ]: 0 : elog(ERROR, "unrecognized node type: %d",
873 : : (int) nodeTag(jtnode));
874 : 112483 : return jtnode;
875 : : }
876 : :
877 : : /*
878 : : * Recurse through top-level qual nodes for pull_up_sublinks()
879 : : *
880 : : * jtlink1 points to the link in the jointree where any new JoinExprs should
881 : : * be inserted if they reference available_rels1 (i.e., available_rels1
882 : : * denotes the relations present underneath jtlink1). Optionally, jtlink2 can
883 : : * point to a second link where new JoinExprs should be inserted if they
884 : : * reference available_rels2 (pass NULL for both those arguments if not used).
885 : : * Note that SubLinks referencing both sets of variables cannot be optimized.
886 : : * If we find multiple pull-up-able SubLinks, they'll get stacked onto jtlink1
887 : : * and/or jtlink2 in the order we encounter them. We rely on subsequent
888 : : * optimization to rearrange the stack if appropriate.
889 : : *
890 : : * Returns the replacement qual node, or NULL if the qual should be removed.
891 : : */
892 : : static Node *
893 : 130633 : pull_up_sublinks_qual_recurse(PlannerInfo *root, Node *node,
894 : : Node **jtlink1, Relids available_rels1,
895 : : Node **jtlink2, Relids available_rels2)
896 : : {
897 [ + + ]: 130633 : if (node == NULL)
898 : 5437 : return NULL;
899 [ + + ]: 125196 : if (IsA(node, SubLink))
900 : : {
901 : 4613 : SubLink *sublink = (SubLink *) node;
902 : : JoinExpr *j;
903 : : Relids child_rels;
904 : :
905 : : /* Is it a convertible ANY or EXISTS clause? */
906 [ + + ]: 4613 : if (sublink->subLinkType == ANY_SUBLINK)
907 : : {
908 : : ScalarArrayOpExpr *saop;
909 : :
910 [ + + ]: 3890 : if ((saop = convert_VALUES_to_ANY(root,
911 : : sublink->testexpr,
912 : 3890 : (Query *) sublink->subselect)) != NULL)
913 : : {
914 : : /*
915 : : * The VALUES sequence was simplified. Nothing more to do
916 : : * here.
917 : : */
918 : 70 : return (Node *) saop;
919 : : }
920 : :
921 [ + + ]: 3820 : if ((j = convert_ANY_sublink_to_join(root, sublink, false,
922 : : available_rels1)) != NULL)
923 : : {
924 : : /* Yes; insert the new join node into the join tree */
925 : 3728 : j->larg = *jtlink1;
926 : 3728 : *jtlink1 = (Node *) j;
927 : : /* Recursively process pulled-up jointree nodes */
928 : 3728 : j->rarg = pull_up_sublinks_jointree_recurse(root,
929 : : j->rarg,
930 : : &child_rels);
931 : :
932 : : /*
933 : : * Now recursively process the pulled-up quals. Any inserted
934 : : * joins can get stacked onto either j->larg or j->rarg,
935 : : * depending on which rels they reference.
936 : : */
937 : 3728 : j->quals = pull_up_sublinks_qual_recurse(root,
938 : : j->quals,
939 : : &j->larg,
940 : : available_rels1,
941 : : &j->rarg,
942 : : child_rels);
943 : : /* Return NULL representing constant TRUE */
944 : 3728 : return NULL;
945 : : }
946 [ + + - + ]: 97 : if (available_rels2 != NULL &&
947 : 5 : (j = convert_ANY_sublink_to_join(root, sublink, false,
948 : : available_rels2)) != NULL)
949 : : {
950 : : /* Yes; insert the new join node into the join tree */
951 : 0 : j->larg = *jtlink2;
952 : 0 : *jtlink2 = (Node *) j;
953 : : /* Recursively process pulled-up jointree nodes */
954 : 0 : j->rarg = pull_up_sublinks_jointree_recurse(root,
955 : : j->rarg,
956 : : &child_rels);
957 : :
958 : : /*
959 : : * Now recursively process the pulled-up quals. Any inserted
960 : : * joins can get stacked onto either j->larg or j->rarg,
961 : : * depending on which rels they reference.
962 : : */
963 : 0 : j->quals = pull_up_sublinks_qual_recurse(root,
964 : : j->quals,
965 : : &j->larg,
966 : : available_rels2,
967 : : &j->rarg,
968 : : child_rels);
969 : : /* Return NULL representing constant TRUE */
970 : 0 : return NULL;
971 : : }
972 : : }
973 [ + + ]: 723 : else if (sublink->subLinkType == EXISTS_SUBLINK)
974 : : {
975 [ + + ]: 673 : if ((j = convert_EXISTS_sublink_to_join(root, sublink, false,
976 : : available_rels1)) != NULL)
977 : : {
978 : : /* Yes; insert the new join node into the join tree */
979 : 551 : j->larg = *jtlink1;
980 : 551 : *jtlink1 = (Node *) j;
981 : : /* Recursively process pulled-up jointree nodes */
982 : 551 : j->rarg = pull_up_sublinks_jointree_recurse(root,
983 : : j->rarg,
984 : : &child_rels);
985 : :
986 : : /*
987 : : * Now recursively process the pulled-up quals. Any inserted
988 : : * joins can get stacked onto either j->larg or j->rarg,
989 : : * depending on which rels they reference.
990 : : */
991 : 551 : j->quals = pull_up_sublinks_qual_recurse(root,
992 : : j->quals,
993 : : &j->larg,
994 : : available_rels1,
995 : : &j->rarg,
996 : : child_rels);
997 : : /* Return NULL representing constant TRUE */
998 : 551 : return NULL;
999 : : }
1000 [ + + + - ]: 138 : if (available_rels2 != NULL &&
1001 : 16 : (j = convert_EXISTS_sublink_to_join(root, sublink, false,
1002 : : available_rels2)) != NULL)
1003 : : {
1004 : : /* Yes; insert the new join node into the join tree */
1005 : 16 : j->larg = *jtlink2;
1006 : 16 : *jtlink2 = (Node *) j;
1007 : : /* Recursively process pulled-up jointree nodes */
1008 : 16 : j->rarg = pull_up_sublinks_jointree_recurse(root,
1009 : : j->rarg,
1010 : : &child_rels);
1011 : :
1012 : : /*
1013 : : * Now recursively process the pulled-up quals. Any inserted
1014 : : * joins can get stacked onto either j->larg or j->rarg,
1015 : : * depending on which rels they reference.
1016 : : */
1017 : 16 : j->quals = pull_up_sublinks_qual_recurse(root,
1018 : : j->quals,
1019 : : &j->larg,
1020 : : available_rels2,
1021 : : &j->rarg,
1022 : : child_rels);
1023 : : /* Return NULL representing constant TRUE */
1024 : 16 : return NULL;
1025 : : }
1026 : : }
1027 : : /* Else return it unmodified */
1028 : 248 : return node;
1029 : : }
1030 [ + + ]: 120583 : if (is_notclause(node))
1031 : : {
1032 : : /* If the immediate argument of NOT is ANY or EXISTS, try to convert */
1033 : 14694 : SubLink *sublink = (SubLink *) get_notclausearg((Expr *) node);
1034 : : JoinExpr *j;
1035 : : Relids child_rels;
1036 : :
1037 [ + - + + ]: 14694 : if (sublink && IsA(sublink, SubLink))
1038 : : {
1039 [ + + ]: 7740 : if (sublink->subLinkType == ANY_SUBLINK)
1040 : : {
1041 [ + + ]: 245 : if ((j = convert_ANY_sublink_to_join(root, sublink, true,
1042 : : available_rels1)) != NULL)
1043 : : {
1044 : : /* Yes; insert the new join node into the join tree */
1045 : 85 : j->larg = *jtlink1;
1046 : 85 : *jtlink1 = (Node *) j;
1047 : : /* Recursively process pulled-up jointree nodes */
1048 : 85 : j->rarg = pull_up_sublinks_jointree_recurse(root,
1049 : : j->rarg,
1050 : : &child_rels);
1051 : :
1052 : : /*
1053 : : * Now recursively process the pulled-up quals. Because
1054 : : * we are underneath a NOT, we can't pull up sublinks that
1055 : : * reference the left-hand stuff, but it's still okay to
1056 : : * pull up sublinks referencing j->rarg.
1057 : : */
1058 : 85 : j->quals = pull_up_sublinks_qual_recurse(root,
1059 : : j->quals,
1060 : : &j->rarg,
1061 : : child_rels,
1062 : : NULL, NULL);
1063 : : /* Return NULL representing constant TRUE */
1064 : 85 : return NULL;
1065 : : }
1066 [ - + - - ]: 160 : if (available_rels2 != NULL &&
1067 : 0 : (j = convert_ANY_sublink_to_join(root, sublink, true,
1068 : : available_rels2)) != NULL)
1069 : : {
1070 : : /* Yes; insert the new join node into the join tree */
1071 : 0 : j->larg = *jtlink2;
1072 : 0 : *jtlink2 = (Node *) j;
1073 : : /* Recursively process pulled-up jointree nodes */
1074 : 0 : j->rarg = pull_up_sublinks_jointree_recurse(root,
1075 : : j->rarg,
1076 : : &child_rels);
1077 : :
1078 : : /*
1079 : : * Now recursively process the pulled-up quals. Because
1080 : : * we are underneath a NOT, we can't pull up sublinks that
1081 : : * reference the left-hand stuff, but it's still okay to
1082 : : * pull up sublinks referencing j->rarg.
1083 : : */
1084 : 0 : j->quals = pull_up_sublinks_qual_recurse(root,
1085 : : j->quals,
1086 : : &j->rarg,
1087 : : child_rels,
1088 : : NULL, NULL);
1089 : : /* Return NULL representing constant TRUE */
1090 : 0 : return NULL;
1091 : : }
1092 : : }
1093 [ + - ]: 7495 : else if (sublink->subLinkType == EXISTS_SUBLINK)
1094 : : {
1095 [ + + ]: 7495 : if ((j = convert_EXISTS_sublink_to_join(root, sublink, true,
1096 : : available_rels1)) != NULL)
1097 : : {
1098 : : /* Yes; insert the new join node into the join tree */
1099 : 7486 : j->larg = *jtlink1;
1100 : 7486 : *jtlink1 = (Node *) j;
1101 : : /* Recursively process pulled-up jointree nodes */
1102 : 7486 : j->rarg = pull_up_sublinks_jointree_recurse(root,
1103 : : j->rarg,
1104 : : &child_rels);
1105 : :
1106 : : /*
1107 : : * Now recursively process the pulled-up quals. Because
1108 : : * we are underneath a NOT, we can't pull up sublinks that
1109 : : * reference the left-hand stuff, but it's still okay to
1110 : : * pull up sublinks referencing j->rarg.
1111 : : */
1112 : 7486 : j->quals = pull_up_sublinks_qual_recurse(root,
1113 : : j->quals,
1114 : : &j->rarg,
1115 : : child_rels,
1116 : : NULL, NULL);
1117 : : /* Return NULL representing constant TRUE */
1118 : 7486 : return NULL;
1119 : : }
1120 [ - + - - ]: 9 : if (available_rels2 != NULL &&
1121 : 0 : (j = convert_EXISTS_sublink_to_join(root, sublink, true,
1122 : : available_rels2)) != NULL)
1123 : : {
1124 : : /* Yes; insert the new join node into the join tree */
1125 : 0 : j->larg = *jtlink2;
1126 : 0 : *jtlink2 = (Node *) j;
1127 : : /* Recursively process pulled-up jointree nodes */
1128 : 0 : j->rarg = pull_up_sublinks_jointree_recurse(root,
1129 : : j->rarg,
1130 : : &child_rels);
1131 : :
1132 : : /*
1133 : : * Now recursively process the pulled-up quals. Because
1134 : : * we are underneath a NOT, we can't pull up sublinks that
1135 : : * reference the left-hand stuff, but it's still okay to
1136 : : * pull up sublinks referencing j->rarg.
1137 : : */
1138 : 0 : j->quals = pull_up_sublinks_qual_recurse(root,
1139 : : j->quals,
1140 : : &j->rarg,
1141 : : child_rels,
1142 : : NULL, NULL);
1143 : : /* Return NULL representing constant TRUE */
1144 : 0 : return NULL;
1145 : : }
1146 : : }
1147 : : }
1148 : : /* Else return it unmodified */
1149 : 7123 : return node;
1150 : : }
1151 [ + + ]: 105889 : if (is_andclause(node))
1152 : : {
1153 : : /* Recurse into AND clause */
1154 : 25675 : List *newclauses = NIL;
1155 : : ListCell *l;
1156 : :
1157 [ + - + + : 95515 : foreach(l, ((BoolExpr *) node)->args)
+ + ]
1158 : : {
1159 : 69840 : Node *oldclause = (Node *) lfirst(l);
1160 : : Node *newclause;
1161 : :
1162 : 69840 : newclause = pull_up_sublinks_qual_recurse(root,
1163 : : oldclause,
1164 : : jtlink1,
1165 : : available_rels1,
1166 : : jtlink2,
1167 : : available_rels2);
1168 [ + + ]: 69840 : if (newclause)
1169 : 59991 : newclauses = lappend(newclauses, newclause);
1170 : : }
1171 : : /* We might have got back fewer clauses than we started with */
1172 [ + + ]: 25675 : if (newclauses == NIL)
1173 : 73 : return NULL;
1174 [ + + ]: 25602 : else if (list_length(newclauses) == 1)
1175 : 902 : return (Node *) linitial(newclauses);
1176 : : else
1177 : 24700 : return (Node *) make_andclause(newclauses);
1178 : : }
1179 : : /* Stop if not an AND */
1180 : 80214 : return node;
1181 : : }
1182 : :
1183 : : /*
1184 : : * preprocess_function_rtes
1185 : : * Constant-simplify any FUNCTION RTEs in the FROM clause, and then
1186 : : * attempt to "inline" any that can be converted to simple subqueries.
1187 : : *
1188 : : * If an RTE_FUNCTION rtable entry invokes a set-returning SQL function that
1189 : : * contains just a simple SELECT, we can convert the rtable entry to an
1190 : : * RTE_SUBQUERY entry exposing the SELECT directly. Other sorts of functions
1191 : : * are also inline-able if they have a support function that can generate
1192 : : * the replacement sub-Query. This is especially useful if the subquery can
1193 : : * then be "pulled up" for further optimization, but we do it even if not,
1194 : : * to reduce executor overhead.
1195 : : *
1196 : : * This has to be done before we have started to do any optimization of
1197 : : * subqueries, else any such steps wouldn't get applied to subqueries
1198 : : * obtained via inlining. However, we do it after pull_up_sublinks
1199 : : * so that we can inline any functions used in SubLink subselects.
1200 : : *
1201 : : * The reason for applying const-simplification at this stage is that
1202 : : * (a) we'd need to do it anyway to inline a SRF, and (b) by doing it now,
1203 : : * we can be sure that pull_up_constant_function() will see constants
1204 : : * if there are constants to be seen. This approach also guarantees
1205 : : * that every FUNCTION RTE has been const-simplified, allowing planner.c's
1206 : : * preprocess_expression() to skip doing it again.
1207 : : *
1208 : : * Like most of the planner, this feels free to scribble on its input data
1209 : : * structure.
1210 : : */
1211 : : void
1212 : 437451 : preprocess_function_rtes(PlannerInfo *root)
1213 : : {
1214 : : ListCell *rt;
1215 : :
1216 [ + - + + : 1152797 : foreach(rt, root->parse->rtable)
+ + ]
1217 : : {
1218 : 715350 : RangeTblEntry *rte = (RangeTblEntry *) lfirst(rt);
1219 : :
1220 [ + + ]: 715350 : if (rte->rtekind == RTE_FUNCTION)
1221 : : {
1222 : : Query *funcquery;
1223 : :
1224 : : /* Apply const-simplification */
1225 : 36872 : rte->functions = (List *)
1226 : 36872 : eval_const_expressions(root, (Node *) rte->functions);
1227 : :
1228 : : /* Check safety of expansion, and expand if possible */
1229 : 36872 : funcquery = inline_function_in_from(root, rte);
1230 [ + + ]: 36868 : if (funcquery)
1231 : : {
1232 : : /* Successful expansion, convert the RTE to a subquery */
1233 : 208 : rte->rtekind = RTE_SUBQUERY;
1234 : 208 : rte->subquery = funcquery;
1235 : 208 : rte->security_barrier = false;
1236 : :
1237 : : /*
1238 : : * Clear fields that should not be set in a subquery RTE.
1239 : : * However, we leave rte->functions filled in for the moment,
1240 : : * in case makeWholeRowVar needs to consult it. We'll clear
1241 : : * it in setrefs.c (see add_rte_to_flat_rtable) so that this
1242 : : * abuse of the data structure doesn't escape the planner.
1243 : : */
1244 : 208 : rte->funcordinality = false;
1245 : : }
1246 : : }
1247 : : }
1248 : 437447 : }
1249 : :
1250 : : /*
1251 : : * pull_up_subqueries
1252 : : * Look for subqueries in the rangetable that can be pulled up into
1253 : : * the parent query. If the subquery has no special features like
1254 : : * grouping/aggregation then we can merge it into the parent's jointree.
1255 : : * Also, subqueries that are simple UNION ALL structures can be
1256 : : * converted into "append relations".
1257 : : */
1258 : : void
1259 : 437447 : pull_up_subqueries(PlannerInfo *root)
1260 : : {
1261 : : /* Top level of jointree must always be a FromExpr */
1262 : : Assert(IsA(root->parse->jointree, FromExpr));
1263 : : /* Recursion starts with no containing join nor appendrel */
1264 : 874894 : root->parse->jointree = (FromExpr *)
1265 : 437447 : pull_up_subqueries_recurse(root, (Node *) root->parse->jointree,
1266 : : NULL, NULL);
1267 : : /* We should still have a FromExpr */
1268 : : Assert(IsA(root->parse->jointree, FromExpr));
1269 : 437447 : }
1270 : :
1271 : : /*
1272 : : * pull_up_subqueries_recurse
1273 : : * Recursive guts of pull_up_subqueries.
1274 : : *
1275 : : * This recursively processes the jointree and returns a modified jointree.
1276 : : *
1277 : : * If this jointree node is within either side of an outer join, then
1278 : : * lowest_outer_join references the lowest such JoinExpr node; otherwise
1279 : : * it is NULL. We use this to constrain the effects of LATERAL subqueries.
1280 : : *
1281 : : * If we are looking at a member subquery of an append relation,
1282 : : * containing_appendrel describes that relation; else it is NULL.
1283 : : * This forces use of the PlaceHolderVar mechanism for all non-Var targetlist
1284 : : * items, and puts some additional restrictions on what can be pulled up.
1285 : : *
1286 : : * A tricky aspect of this code is that if we pull up a subquery we have
1287 : : * to replace Vars that reference the subquery's outputs throughout the
1288 : : * parent query, including quals attached to jointree nodes above the one
1289 : : * we are currently processing! We handle this by being careful to maintain
1290 : : * validity of the jointree structure while recursing, in the following sense:
1291 : : * whenever we recurse, all qual expressions in the tree must be reachable
1292 : : * from the top level, in case the recursive call needs to modify them.
1293 : : *
1294 : : * Notice also that we can't turn pullup_replace_vars loose on the whole
1295 : : * jointree, because it'd return a mutated copy of the tree; we have to
1296 : : * invoke it just on the quals, instead. This behavior is what makes it
1297 : : * reasonable to pass lowest_outer_join as a pointer rather than some
1298 : : * more-indirect way of identifying the lowest OJ. Likewise, we don't
1299 : : * replace append_rel_list members but only their substructure, so the
1300 : : * containing_appendrel reference is safe to use.
1301 : : */
1302 : : static Node *
1303 : 1103907 : pull_up_subqueries_recurse(PlannerInfo *root, Node *jtnode,
1304 : : JoinExpr *lowest_outer_join,
1305 : : AppendRelInfo *containing_appendrel)
1306 : : {
1307 : : /* Since this function recurses, it could be driven to stack overflow. */
1308 : 1103907 : check_stack_depth();
1309 : : /* Also, since it's a bit expensive, let's check for query cancel. */
1310 [ + + ]: 1103907 : CHECK_FOR_INTERRUPTS();
1311 : :
1312 : : Assert(jtnode != NULL);
1313 [ + + ]: 1103907 : if (IsA(jtnode, RangeTblRef))
1314 : : {
1315 : 566591 : int varno = ((RangeTblRef *) jtnode)->rtindex;
1316 : 566591 : RangeTblEntry *rte = rt_fetch(varno, root->parse->rtable);
1317 : :
1318 : : /*
1319 : : * Is this a subquery RTE, and if so, is the subquery simple enough to
1320 : : * pull up?
1321 : : *
1322 : : * If we are looking at an append-relation member, we can't pull it up
1323 : : * unless is_safe_append_member says so.
1324 : : */
1325 [ + + + + ]: 619217 : if (rte->rtekind == RTE_SUBQUERY &&
1326 [ + + ]: 87608 : is_simple_subquery(root, rte->subquery, rte, lowest_outer_join) &&
1327 [ + + ]: 9356 : (containing_appendrel == NULL ||
1328 : 9356 : is_safe_append_member(rte->subquery)))
1329 : 31132 : return pull_up_simple_subquery(root, jtnode, rte,
1330 : : lowest_outer_join,
1331 : : containing_appendrel);
1332 : :
1333 : : /*
1334 : : * Alternatively, is it a simple UNION ALL subquery? If so, flatten
1335 : : * into an "append relation".
1336 : : *
1337 : : * It's safe to do this regardless of whether this query is itself an
1338 : : * appendrel member. (If you're thinking we should try to flatten the
1339 : : * two levels of appendrel together, you're right; but we handle that
1340 : : * in set_append_rel_pathlist, not here.)
1341 : : */
1342 [ + + + + ]: 556953 : if (rte->rtekind == RTE_SUBQUERY &&
1343 : 21494 : is_simple_union_all(rte->subquery))
1344 : 3963 : return pull_up_simple_union_all(root, jtnode, rte);
1345 : :
1346 : : /*
1347 : : * Or perhaps it's a simple VALUES RTE?
1348 : : *
1349 : : * We don't allow VALUES pullup below an outer join nor into an
1350 : : * appendrel (such cases are impossible anyway at the moment).
1351 : : */
1352 [ + + + - ]: 531496 : if (rte->rtekind == RTE_VALUES &&
1353 [ + - ]: 11120 : lowest_outer_join == NULL &&
1354 [ + + ]: 11120 : containing_appendrel == NULL &&
1355 : 11120 : is_simple_values(root, rte))
1356 : 3862 : return pull_up_simple_values(root, jtnode, rte);
1357 : :
1358 : : /*
1359 : : * Or perhaps it's a FUNCTION RTE that we could inline?
1360 : : */
1361 [ + + ]: 527634 : if (rte->rtekind == RTE_FUNCTION)
1362 : 36660 : return pull_up_constant_function(root, jtnode, rte,
1363 : : containing_appendrel);
1364 : :
1365 : : /* Otherwise, do nothing at this node. */
1366 : : }
1367 [ + + ]: 537316 : else if (IsA(jtnode, FromExpr))
1368 : : {
1369 : 450823 : FromExpr *f = (FromExpr *) jtnode;
1370 : : ListCell *l;
1371 : :
1372 : : Assert(containing_appendrel == NULL);
1373 : : /* Recursively transform all the child nodes */
1374 [ + + + + : 931879 : foreach(l, f->fromlist)
+ + ]
1375 : : {
1376 : 481056 : lfirst(l) = pull_up_subqueries_recurse(root, lfirst(l),
1377 : : lowest_outer_join,
1378 : : NULL);
1379 : : }
1380 : : }
1381 [ + - ]: 86493 : else if (IsA(jtnode, JoinExpr))
1382 : : {
1383 : 86493 : JoinExpr *j = (JoinExpr *) jtnode;
1384 : :
1385 : : Assert(containing_appendrel == NULL);
1386 : : /* Recurse, being careful to tell myself when inside outer join */
1387 [ + + + + : 86493 : switch (j->jointype)
- ]
1388 : : {
1389 : 36616 : case JOIN_INNER:
1390 : 36616 : j->larg = pull_up_subqueries_recurse(root, j->larg,
1391 : : lowest_outer_join,
1392 : : NULL);
1393 : 36616 : j->rarg = pull_up_subqueries_recurse(root, j->rarg,
1394 : : lowest_outer_join,
1395 : : NULL);
1396 : 36616 : break;
1397 : 47629 : case JOIN_LEFT:
1398 : : case JOIN_SEMI:
1399 : : case JOIN_ANTI:
1400 : 47629 : j->larg = pull_up_subqueries_recurse(root, j->larg,
1401 : : j,
1402 : : NULL);
1403 : 47629 : j->rarg = pull_up_subqueries_recurse(root, j->rarg,
1404 : : j,
1405 : : NULL);
1406 : 47629 : break;
1407 : 1175 : case JOIN_FULL:
1408 : 1175 : j->larg = pull_up_subqueries_recurse(root, j->larg,
1409 : : j,
1410 : : NULL);
1411 : 1175 : j->rarg = pull_up_subqueries_recurse(root, j->rarg,
1412 : : j,
1413 : : NULL);
1414 : 1175 : break;
1415 : 1073 : case JOIN_RIGHT:
1416 : 1073 : j->larg = pull_up_subqueries_recurse(root, j->larg,
1417 : : j,
1418 : : NULL);
1419 : 1073 : j->rarg = pull_up_subqueries_recurse(root, j->rarg,
1420 : : j,
1421 : : NULL);
1422 : 1073 : break;
1423 : 0 : default:
1424 [ # # ]: 0 : elog(ERROR, "unrecognized join type: %d",
1425 : : (int) j->jointype);
1426 : : break;
1427 : : }
1428 : : }
1429 : : else
1430 [ # # ]: 0 : elog(ERROR, "unrecognized node type: %d",
1431 : : (int) nodeTag(jtnode));
1432 : 1028290 : return jtnode;
1433 : : }
1434 : :
1435 : : /*
1436 : : * pull_up_simple_subquery
1437 : : * Attempt to pull up a single simple subquery.
1438 : : *
1439 : : * jtnode is a RangeTblRef that has been tentatively identified as a simple
1440 : : * subquery by pull_up_subqueries. We return the replacement jointree node,
1441 : : * or jtnode itself if we determine that the subquery can't be pulled up
1442 : : * after all.
1443 : : *
1444 : : * rte is the RangeTblEntry referenced by jtnode. Remaining parameters are
1445 : : * as for pull_up_subqueries_recurse.
1446 : : */
1447 : : static Node *
1448 : 31132 : pull_up_simple_subquery(PlannerInfo *root, Node *jtnode, RangeTblEntry *rte,
1449 : : JoinExpr *lowest_outer_join,
1450 : : AppendRelInfo *containing_appendrel)
1451 : : {
1452 : 31132 : Query *parse = root->parse;
1453 : 31132 : int varno = ((RangeTblRef *) jtnode)->rtindex;
1454 : : Query *subquery;
1455 : : PlannerInfo *subroot;
1456 : : int rtoffset;
1457 : : pullup_replace_vars_context rvcontext;
1458 : : ListCell *lc;
1459 : :
1460 : : /*
1461 : : * Make a modifiable copy of the subquery to hack on, so that the RTE will
1462 : : * be left unchanged in case we decide below that we can't pull it up
1463 : : * after all.
1464 : : */
1465 : 31132 : subquery = copyObject(rte->subquery);
1466 : :
1467 : : /*
1468 : : * Create a PlannerInfo data structure for this subquery.
1469 : : *
1470 : : * NOTE: the next few steps should match the first processing in
1471 : : * subquery_planner(). Can we refactor to avoid code duplication, or
1472 : : * would that just make things uglier?
1473 : : */
1474 : 31132 : subroot = makeNode(PlannerInfo);
1475 : 31132 : subroot->parse = subquery;
1476 : 31132 : subroot->glob = root->glob;
1477 : 31132 : subroot->query_level = root->query_level;
1478 : 31132 : subroot->plan_name = root->plan_name;
1479 : 31132 : subroot->alternative_plan_name = root->alternative_plan_name;
1480 : 31132 : subroot->parent_root = root->parent_root;
1481 : 31132 : subroot->plan_params = NIL;
1482 : 31132 : subroot->outer_params = NULL;
1483 : 31132 : subroot->planner_cxt = CurrentMemoryContext;
1484 : 31132 : subroot->init_plans = NIL;
1485 : 31132 : subroot->cte_plan_ids = NIL;
1486 : 31132 : subroot->multiexpr_params = NIL;
1487 : 31132 : subroot->join_domains = NIL;
1488 : 31132 : subroot->eq_classes = NIL;
1489 : 31132 : subroot->ec_merging_done = false;
1490 : 31132 : subroot->last_rinfo_serial = 0;
1491 : 31132 : subroot->all_result_relids = NULL;
1492 : 31132 : subroot->leaf_result_relids = NULL;
1493 : 31132 : subroot->append_rel_list = NIL;
1494 : 31132 : subroot->row_identity_vars = NIL;
1495 : 31132 : subroot->rowMarks = NIL;
1496 : 31132 : subroot->join_alias_phvs = NIL;
1497 : 31132 : memset(subroot->upper_rels, 0, sizeof(subroot->upper_rels));
1498 : 31132 : memset(subroot->upper_targets, 0, sizeof(subroot->upper_targets));
1499 : 31132 : subroot->processed_groupClause = NIL;
1500 : 31132 : subroot->processed_distinctClause = NIL;
1501 : 31132 : subroot->processed_tlist = NIL;
1502 : 31132 : subroot->update_colnos = NIL;
1503 : 31132 : subroot->grouping_map = NULL;
1504 : 31132 : subroot->minmax_aggs = NIL;
1505 : 31132 : subroot->qual_security_level = 0;
1506 : 31132 : subroot->placeholdersFrozen = false;
1507 : 31132 : subroot->hasRecursion = false;
1508 : 31132 : subroot->assumeReplanning = false;
1509 : 31132 : subroot->wt_param_id = -1;
1510 : 31132 : subroot->non_recursive_path = NULL;
1511 : : /* We don't currently need a top JoinDomain for the subroot */
1512 : :
1513 : : /* No CTEs to worry about */
1514 : : Assert(subquery->cteList == NIL);
1515 : :
1516 : : /*
1517 : : * Scan the rangetable for relation RTEs and retrieve the necessary
1518 : : * catalog information for each relation. Using this information, clear
1519 : : * the inh flag for any relation that has no children, collect not-null
1520 : : * attribute numbers for any relation that has column not-null
1521 : : * constraints, and expand virtual generated columns for any relation that
1522 : : * contains them.
1523 : : */
1524 : 31132 : subquery = subroot->parse = preprocess_relation_rtes(subroot);
1525 : :
1526 : : /*
1527 : : * If the FROM clause is empty, replace it with a dummy RTE_RESULT RTE, so
1528 : : * that we don't need so many special cases to deal with that situation.
1529 : : */
1530 : 31132 : replace_empty_jointree(subquery);
1531 : :
1532 : : /*
1533 : : * Pull up any SubLinks within the subquery's quals, so that we don't
1534 : : * leave unoptimized SubLinks behind.
1535 : : */
1536 [ + + ]: 31132 : if (subquery->hasSubLinks)
1537 : 1775 : pull_up_sublinks(subroot);
1538 : :
1539 : : /*
1540 : : * Similarly, preprocess its function RTEs to inline any set-returning
1541 : : * functions in its rangetable.
1542 : : */
1543 : 31132 : preprocess_function_rtes(subroot);
1544 : :
1545 : : /*
1546 : : * Recursively pull up the subquery's subqueries, so that
1547 : : * pull_up_subqueries' processing is complete for its jointree and
1548 : : * rangetable.
1549 : : *
1550 : : * Note: it's okay that the subquery's recursion starts with NULL for
1551 : : * containing-join info, even if we are within an outer join in the upper
1552 : : * query; the lower query starts with a clean slate for outer-join
1553 : : * semantics. Likewise, we needn't pass down appendrel state.
1554 : : */
1555 : 31132 : pull_up_subqueries(subroot);
1556 : :
1557 : : /*
1558 : : * We must flatten any join alias Vars in the subquery's targetlist,
1559 : : * because pulling up the subquery's subqueries might have changed their
1560 : : * expansions into arbitrary expressions. That could affect
1561 : : * pullup_replace_vars' decisions about whether PlaceHolderVar wrappers
1562 : : * are needed for tlist entries, and if the subquery is LATERAL, the
1563 : : * expansions might contain lateral references that the is_simple_subquery
1564 : : * recheck below has to see. The latter also requires flattening join
1565 : : * alias Vars in the jointree quals of a LATERAL subquery. (Likely it'd
1566 : : * be better to do flatten_join_alias_vars on the whole query tree at some
1567 : : * earlier stage, maybe even in the rewriter; but for now let's just fix
1568 : : * these cases here.)
1569 : : */
1570 : 31132 : subquery->targetList = (List *)
1571 : 31132 : flatten_join_alias_vars(subroot, subroot->parse,
1572 : 31132 : (Node *) subquery->targetList);
1573 [ + + ]: 31132 : if (rte->lateral)
1574 : 1203 : flatten_join_alias_vars_in_jointree(subroot,
1575 : 1203 : (Node *) subquery->jointree);
1576 : :
1577 : : /*
1578 : : * Now we must recheck whether the subquery is still simple enough to pull
1579 : : * up. If not, abandon processing it.
1580 : : *
1581 : : * We don't really need to recheck all the conditions involved, but it's
1582 : : * easier just to keep this "if" looking the same as the one in
1583 : : * pull_up_subqueries_recurse.
1584 : : */
1585 [ + + + + ]: 36496 : if (is_simple_subquery(root, subquery, rte, lowest_outer_join) &&
1586 [ + + ]: 5506 : (containing_appendrel == NULL || is_safe_append_member(subquery)))
1587 : : {
1588 : : /* good to go */
1589 : : }
1590 : : else
1591 : : {
1592 : : /*
1593 : : * Give up, return unmodified RangeTblRef.
1594 : : *
1595 : : * Note: The work we just did will be redone when the subquery gets
1596 : : * planned on its own. Perhaps we could avoid that by storing the
1597 : : * modified subquery back into the rangetable, but I'm not gonna risk
1598 : : * it now.
1599 : : */
1600 : 172 : return jtnode;
1601 : : }
1602 : :
1603 : : /*
1604 : : * Adjust level-0 varnos in subquery so that we can append its rangetable
1605 : : * to upper query's. We have to fix the subquery's append_rel_list and
1606 : : * join_alias_phvs as well.
1607 : : */
1608 : 30960 : rtoffset = list_length(parse->rtable);
1609 : 30960 : OffsetVarNodes((Node *) subquery, rtoffset, 0);
1610 : 30960 : OffsetVarNodes((Node *) subroot->append_rel_list, rtoffset, 0);
1611 : 30960 : OffsetVarNodes((Node *) subroot->join_alias_phvs, rtoffset, 0);
1612 : :
1613 : : /*
1614 : : * Upper-level vars in subquery are now one level closer to their parent
1615 : : * than before.
1616 : : */
1617 : 30960 : IncrementVarSublevelsUp((Node *) subquery, -1, 1);
1618 : 30960 : IncrementVarSublevelsUp((Node *) subroot->append_rel_list, -1, 1);
1619 : 30960 : IncrementVarSublevelsUp((Node *) subroot->join_alias_phvs, -1, 1);
1620 : :
1621 : : /*
1622 : : * The subquery's targetlist items are now in the appropriate form to
1623 : : * insert into the top query, except that we may need to wrap them in
1624 : : * PlaceHolderVars. Set up required context data for pullup_replace_vars.
1625 : : * (Note that we should include the subquery's inner joins in relids,
1626 : : * since it may include join alias vars referencing them.)
1627 : : */
1628 : 30960 : rvcontext.root = root;
1629 : 30960 : rvcontext.targetlist = subquery->targetList;
1630 : 30960 : rvcontext.target_rte = rte;
1631 : 30960 : rvcontext.result_relation = 0;
1632 [ + + ]: 30960 : if (rte->lateral)
1633 : : {
1634 : 1173 : rvcontext.relids = get_relids_in_jointree((Node *) subquery->jointree,
1635 : : true, true);
1636 : 1173 : rvcontext.nullinfo = get_nullingrels(parse);
1637 : : }
1638 : : else /* won't need these values */
1639 : : {
1640 : 29787 : rvcontext.relids = NULL;
1641 : 29787 : rvcontext.nullinfo = NULL;
1642 : : }
1643 : 30960 : rvcontext.outer_hasSubLinks = &parse->hasSubLinks;
1644 : 30960 : rvcontext.varno = varno;
1645 : : /* this flag will be set below, if needed */
1646 : 30960 : rvcontext.wrap_option = REPLACE_WRAP_NONE;
1647 : : /* initialize cache array with indexes 0 .. length(tlist) */
1648 : 30960 : rvcontext.rv_cache = palloc0_array(Node *, list_length(subquery->targetList) + 1);
1649 : :
1650 : : /*
1651 : : * If the parent query uses grouping sets, we need a PlaceHolderVar for
1652 : : * each expression of the subquery's targetlist items. This ensures that
1653 : : * expressions retain their separate identity so that they will match
1654 : : * grouping set columns when appropriate. (It'd be sufficient to wrap
1655 : : * values used in grouping set columns, and do so only in non-aggregated
1656 : : * portions of the tlist and havingQual, but that would require a lot of
1657 : : * infrastructure that pullup_replace_vars hasn't currently got.)
1658 : : */
1659 [ + + ]: 30960 : if (parse->groupingSets)
1660 : 451 : rvcontext.wrap_option = REPLACE_WRAP_ALL;
1661 : :
1662 : : /*
1663 : : * Replace all of the top query's references to the subquery's outputs
1664 : : * with copies of the adjusted subtlist items, being careful not to
1665 : : * replace any of the jointree structure.
1666 : : */
1667 : 30960 : perform_pullup_replace_vars(root, &rvcontext,
1668 : : containing_appendrel);
1669 : :
1670 : : /*
1671 : : * If the subquery had a LATERAL marker, propagate that to any of its
1672 : : * child RTEs that could possibly now contain lateral cross-references.
1673 : : * The children might or might not contain any actual lateral
1674 : : * cross-references, but we have to mark the pulled-up child RTEs so that
1675 : : * later planner stages will check for such.
1676 : : */
1677 [ + + ]: 30960 : if (rte->lateral)
1678 : : {
1679 [ + - + + : 2762 : foreach(lc, subquery->rtable)
+ + ]
1680 : : {
1681 : 1589 : RangeTblEntry *child_rte = (RangeTblEntry *) lfirst(lc);
1682 : :
1683 [ + + + - ]: 1589 : switch (child_rte->rtekind)
1684 : : {
1685 : 687 : case RTE_RELATION:
1686 [ + + ]: 687 : if (child_rte->tablesample)
1687 : 41 : child_rte->lateral = true;
1688 : 687 : break;
1689 : 297 : case RTE_SUBQUERY:
1690 : : case RTE_FUNCTION:
1691 : : case RTE_VALUES:
1692 : : case RTE_TABLEFUNC:
1693 : 297 : child_rte->lateral = true;
1694 : 297 : break;
1695 : 605 : case RTE_JOIN:
1696 : : case RTE_CTE:
1697 : : case RTE_NAMEDTUPLESTORE:
1698 : : case RTE_RESULT:
1699 : : case RTE_GROUP:
1700 : : /* these can't contain any lateral references */
1701 : 605 : break;
1702 : : }
1703 : : }
1704 : : }
1705 : :
1706 : : /*
1707 : : * Now append the adjusted rtable entries and their perminfos to upper
1708 : : * query. (We hold off until after fixing the upper rtable entries; no
1709 : : * point in running that code on the subquery ones too.)
1710 : : */
1711 : 30960 : CombineRangeTables(&parse->rtable, &parse->rteperminfos,
1712 : : subquery->rtable, subquery->rteperminfos);
1713 : :
1714 : : /*
1715 : : * Pull up any FOR UPDATE/SHARE markers, too. (OffsetVarNodes already
1716 : : * adjusted the marker rtindexes, so just concat the lists.)
1717 : : */
1718 : 30960 : parse->rowMarks = list_concat(parse->rowMarks, subquery->rowMarks);
1719 : :
1720 : : /*
1721 : : * We also have to fix the relid sets of any PlaceHolderVar nodes in the
1722 : : * parent query. (This could perhaps be done by pullup_replace_vars(),
1723 : : * but it seems cleaner to use two passes.) Note in particular that any
1724 : : * PlaceHolderVar nodes just created by pullup_replace_vars() will be
1725 : : * adjusted, so having created them with the subquery's varno is correct.
1726 : : *
1727 : : * Likewise, relids appearing in AppendRelInfo nodes have to be fixed. We
1728 : : * already checked that this won't require introducing multiple subrelids
1729 : : * into the single-slot AppendRelInfo structs.
1730 : : */
1731 [ + + + + ]: 30960 : if (root->glob->lastPHId != 0 || root->append_rel_list)
1732 : : {
1733 : : Relids subrelids;
1734 : :
1735 : 7628 : subrelids = get_relids_in_jointree((Node *) subquery->jointree,
1736 : : true, false);
1737 [ + + ]: 7628 : if (root->glob->lastPHId != 0)
1738 : 2319 : substitute_phv_relids((Node *) parse, varno, subrelids);
1739 : 7628 : fix_append_rel_relids(root, varno, subrelids);
1740 : : }
1741 : :
1742 : : /*
1743 : : * And now add subquery's AppendRelInfos to our list.
1744 : : */
1745 : 61920 : root->append_rel_list = list_concat(root->append_rel_list,
1746 : 30960 : subroot->append_rel_list);
1747 : :
1748 : : /*
1749 : : * Also add the PHVs made while flattening the subquery's join alias Vars,
1750 : : * so that the parent's flattening of the rest of the subquery reuses them
1751 : : * rather than making new PHVs with different phids.
1752 : : */
1753 : 61920 : root->join_alias_phvs = list_concat(root->join_alias_phvs,
1754 : 30960 : subroot->join_alias_phvs);
1755 : :
1756 : : /*
1757 : : * We don't have to do the equivalent bookkeeping for outer-join info,
1758 : : * because that hasn't been set up yet. placeholder_list likewise.
1759 : : */
1760 : : Assert(root->join_info_list == NIL);
1761 : : Assert(subroot->join_info_list == NIL);
1762 : : Assert(root->placeholder_list == NIL);
1763 : : Assert(subroot->placeholder_list == NIL);
1764 : :
1765 : : /*
1766 : : * We no longer need the RTE's copy of the subquery's query tree. Getting
1767 : : * rid of it saves nothing in particular so far as this level of query is
1768 : : * concerned; but if this query level is in turn pulled up into a parent,
1769 : : * we'd waste cycles copying the now-unused query tree.
1770 : : */
1771 : 30960 : rte->subquery = NULL;
1772 : :
1773 : : /*
1774 : : * Miscellaneous housekeeping.
1775 : : *
1776 : : * Although replace_rte_variables() faithfully updated parse->hasSubLinks
1777 : : * if it copied any SubLinks out of the subquery's targetlist, we still
1778 : : * could have SubLinks added to the query in the expressions of FUNCTION
1779 : : * and VALUES RTEs copied up from the subquery. So it's necessary to copy
1780 : : * subquery->hasSubLinks anyway. Perhaps this can be improved someday.
1781 : : */
1782 : 30960 : parse->hasSubLinks |= subquery->hasSubLinks;
1783 : :
1784 : : /* If subquery had any RLS conditions, now main query does too */
1785 : 30960 : parse->hasRowSecurity |= subquery->hasRowSecurity;
1786 : :
1787 : : /*
1788 : : * subquery won't be pulled up if it hasAggs, hasWindowFuncs, or
1789 : : * hasTargetSRFs, so no work needed on those flags
1790 : : */
1791 : :
1792 : : /*
1793 : : * Return the adjusted subquery jointree to replace the RangeTblRef entry
1794 : : * in parent's jointree; or, if the FromExpr is degenerate, just return
1795 : : * its single member.
1796 : : */
1797 : : Assert(IsA(subquery->jointree, FromExpr));
1798 : : Assert(subquery->jointree->fromlist != NIL);
1799 [ + + + + ]: 57624 : if (subquery->jointree->quals == NULL &&
1800 : 26664 : list_length(subquery->jointree->fromlist) == 1)
1801 : 26151 : return (Node *) linitial(subquery->jointree->fromlist);
1802 : :
1803 : 4809 : return (Node *) subquery->jointree;
1804 : : }
1805 : :
1806 : : /*
1807 : : * pull_up_simple_union_all
1808 : : * Pull up a single simple UNION ALL subquery.
1809 : : *
1810 : : * jtnode is a RangeTblRef that has been identified as a simple UNION ALL
1811 : : * subquery by pull_up_subqueries. We pull up the leaf subqueries and
1812 : : * build an "append relation" for the union set. The result value is just
1813 : : * jtnode, since we don't actually need to change the query jointree.
1814 : : */
1815 : : static Node *
1816 : 3963 : pull_up_simple_union_all(PlannerInfo *root, Node *jtnode, RangeTblEntry *rte)
1817 : : {
1818 : 3963 : int varno = ((RangeTblRef *) jtnode)->rtindex;
1819 : 3963 : Query *subquery = rte->subquery;
1820 : 3963 : int rtoffset = list_length(root->parse->rtable);
1821 : : List *rtable;
1822 : :
1823 : : /*
1824 : : * Make a modifiable copy of the subquery's rtable, so we can adjust
1825 : : * upper-level Vars in it. There are no such Vars in the setOperations
1826 : : * tree proper, so fixing the rtable should be sufficient.
1827 : : */
1828 : 3963 : rtable = copyObject(subquery->rtable);
1829 : :
1830 : : /*
1831 : : * Upper-level vars in subquery are now one level closer to their parent
1832 : : * than before. We don't have to worry about offsetting varnos, though,
1833 : : * because the UNION leaf queries can't cross-reference each other.
1834 : : */
1835 : 3963 : IncrementVarSublevelsUp_rtable(rtable, -1, 1);
1836 : :
1837 : : /*
1838 : : * If the UNION ALL subquery had a LATERAL marker, propagate that to all
1839 : : * its children. The individual children might or might not contain any
1840 : : * actual lateral cross-references, but we have to mark the pulled-up
1841 : : * child RTEs so that later planner stages will check for such.
1842 : : */
1843 [ + + ]: 3963 : if (rte->lateral)
1844 : : {
1845 : : ListCell *rt;
1846 : :
1847 [ + - + + : 390 : foreach(rt, rtable)
+ + ]
1848 : : {
1849 : 260 : RangeTblEntry *child_rte = (RangeTblEntry *) lfirst(rt);
1850 : :
1851 : : Assert(child_rte->rtekind == RTE_SUBQUERY);
1852 : 260 : child_rte->lateral = true;
1853 : : }
1854 : : }
1855 : :
1856 : : /*
1857 : : * Append child RTEs (and their perminfos) to parent rtable.
1858 : : */
1859 : 3963 : CombineRangeTables(&root->parse->rtable, &root->parse->rteperminfos,
1860 : : rtable, subquery->rteperminfos);
1861 : :
1862 : : /*
1863 : : * Recursively scan the subquery's setOperations tree and add
1864 : : * AppendRelInfo nodes for leaf subqueries to the parent's
1865 : : * append_rel_list. Also apply pull_up_subqueries to the leaf subqueries.
1866 : : */
1867 : : Assert(subquery->setOperations);
1868 : 3963 : pull_up_union_leaf_queries(subquery->setOperations, root, varno, subquery,
1869 : : rtoffset);
1870 : :
1871 : : /*
1872 : : * Mark the parent as an append relation.
1873 : : */
1874 : 3963 : rte->inh = true;
1875 : :
1876 : 3963 : return jtnode;
1877 : : }
1878 : :
1879 : : /*
1880 : : * pull_up_union_leaf_queries -- recursive guts of pull_up_simple_union_all
1881 : : *
1882 : : * Build an AppendRelInfo for each leaf query in the setop tree, and then
1883 : : * apply pull_up_subqueries to the leaf query.
1884 : : *
1885 : : * Note that setOpQuery is the Query containing the setOp node, whose tlist
1886 : : * contains references to all the setop output columns. When called from
1887 : : * pull_up_simple_union_all, this is *not* the same as root->parse, which is
1888 : : * the parent Query we are pulling up into.
1889 : : *
1890 : : * parentRTindex is the appendrel parent's index in root->parse->rtable.
1891 : : *
1892 : : * The child RTEs have already been copied to the parent. childRToffset
1893 : : * tells us where in the parent's range table they were copied. When called
1894 : : * from flatten_simple_union_all, childRToffset is 0 since the child RTEs
1895 : : * were already in root->parse->rtable and no RT index adjustment is needed.
1896 : : */
1897 : : static void
1898 : 20199 : pull_up_union_leaf_queries(Node *setOp, PlannerInfo *root, int parentRTindex,
1899 : : Query *setOpQuery, int childRToffset)
1900 : : {
1901 [ + + ]: 20199 : if (IsA(setOp, RangeTblRef))
1902 : : {
1903 : 12418 : RangeTblRef *rtr = (RangeTblRef *) setOp;
1904 : : int childRTindex;
1905 : : AppendRelInfo *appinfo;
1906 : :
1907 : : /*
1908 : : * Calculate the index in the parent's range table
1909 : : */
1910 : 12418 : childRTindex = childRToffset + rtr->rtindex;
1911 : :
1912 : : /*
1913 : : * Build a suitable AppendRelInfo, and attach to parent's list.
1914 : : */
1915 : 12418 : appinfo = makeNode(AppendRelInfo);
1916 : 12418 : appinfo->parent_relid = parentRTindex;
1917 : 12418 : appinfo->child_relid = childRTindex;
1918 : 12418 : appinfo->parent_reltype = InvalidOid;
1919 : 12418 : appinfo->child_reltype = InvalidOid;
1920 : 12418 : make_setop_translation_list(setOpQuery, childRTindex, appinfo);
1921 : 12418 : appinfo->parent_reloid = InvalidOid;
1922 : 12418 : root->append_rel_list = lappend(root->append_rel_list, appinfo);
1923 : :
1924 : : /*
1925 : : * Recursively apply pull_up_subqueries to the new child RTE. (We
1926 : : * must build the AppendRelInfo first, because this will modify it;
1927 : : * indeed, that's the only part of the upper query where Vars
1928 : : * referencing childRTindex can exist at this point.)
1929 : : *
1930 : : * Note that we can pass NULL for containing-join info even if we're
1931 : : * actually under an outer join, because the child's expressions
1932 : : * aren't going to propagate up to the join. Also, we ignore the
1933 : : * possibility that pull_up_subqueries_recurse() returns a different
1934 : : * jointree node than what we pass it; if it does, the important thing
1935 : : * is that it replaced the child relid in the AppendRelInfo node.
1936 : : */
1937 : 12418 : rtr = makeNode(RangeTblRef);
1938 : 12418 : rtr->rtindex = childRTindex;
1939 : 12418 : (void) pull_up_subqueries_recurse(root, (Node *) rtr,
1940 : : NULL, appinfo);
1941 : : }
1942 [ + - ]: 7781 : else if (IsA(setOp, SetOperationStmt))
1943 : : {
1944 : 7781 : SetOperationStmt *op = (SetOperationStmt *) setOp;
1945 : :
1946 : : /* Recurse to reach leaf queries */
1947 : 7781 : pull_up_union_leaf_queries(op->larg, root, parentRTindex, setOpQuery,
1948 : : childRToffset);
1949 : 7781 : pull_up_union_leaf_queries(op->rarg, root, parentRTindex, setOpQuery,
1950 : : childRToffset);
1951 : : }
1952 : : else
1953 : : {
1954 [ # # ]: 0 : elog(ERROR, "unrecognized node type: %d",
1955 : : (int) nodeTag(setOp));
1956 : : }
1957 : 20199 : }
1958 : :
1959 : : /*
1960 : : * make_setop_translation_list
1961 : : * Build the list of translations from parent Vars to child Vars for
1962 : : * a UNION ALL member. (At this point it's just a simple list of
1963 : : * referencing Vars, but if we succeed in pulling up the member
1964 : : * subquery, the Vars will get replaced by pulled-up expressions.)
1965 : : * Also create the rather trivial reverse-translation array.
1966 : : */
1967 : : static void
1968 : 12418 : make_setop_translation_list(Query *query, int newvarno,
1969 : : AppendRelInfo *appinfo)
1970 : : {
1971 : 12418 : List *vars = NIL;
1972 : : AttrNumber *pcolnos;
1973 : : ListCell *l;
1974 : :
1975 : : /* Initialize reverse-translation array with all entries zero */
1976 : : /* (entries for resjunk columns will stay that way) */
1977 : 12418 : appinfo->num_child_cols = list_length(query->targetList);
1978 : 12418 : appinfo->parent_colnos = pcolnos = palloc0_array(AttrNumber, appinfo->num_child_cols);
1979 : :
1980 [ + + + + : 50273 : foreach(l, query->targetList)
+ + ]
1981 : : {
1982 : 37855 : TargetEntry *tle = (TargetEntry *) lfirst(l);
1983 : :
1984 [ - + ]: 37855 : if (tle->resjunk)
1985 : 0 : continue;
1986 : :
1987 : 37855 : vars = lappend(vars, makeVarFromTargetEntry(newvarno, tle));
1988 : 37855 : pcolnos[tle->resno - 1] = tle->resno;
1989 : : }
1990 : :
1991 : 12418 : appinfo->translated_vars = vars;
1992 : 12418 : }
1993 : :
1994 : : /*
1995 : : * is_simple_subquery
1996 : : * Check a subquery in the range table to see if it's simple enough
1997 : : * to pull up into the parent query.
1998 : : *
1999 : : * rte is the RTE_SUBQUERY RangeTblEntry that contained the subquery.
2000 : : * (Note subquery is not necessarily equal to rte->subquery; it could be a
2001 : : * processed copy of that.)
2002 : : * lowest_outer_join is the lowest outer join above the subquery, or NULL.
2003 : : */
2004 : : static bool
2005 : 83758 : is_simple_subquery(PlannerInfo *root, Query *subquery, RangeTblEntry *rte,
2006 : : JoinExpr *lowest_outer_join)
2007 : : {
2008 : : /*
2009 : : * Let's just make sure it's a valid subselect ...
2010 : : */
2011 [ + - ]: 83758 : if (!IsA(subquery, Query) ||
2012 [ - + ]: 83758 : subquery->commandType != CMD_SELECT)
2013 [ # # ]: 0 : elog(ERROR, "subquery is bogus");
2014 : :
2015 : : /*
2016 : : * Can't currently pull up a query with setops (unless it's simple UNION
2017 : : * ALL, which is handled by a different code path). Maybe after querytree
2018 : : * redesign...
2019 : : */
2020 [ + + ]: 83758 : if (subquery->setOperations)
2021 : 4774 : return false;
2022 : :
2023 : : /*
2024 : : * Can't pull up a subquery involving grouping, aggregation, SRFs,
2025 : : * sorting, limiting, or WITH. (XXX WITH could possibly be allowed later)
2026 : : *
2027 : : * We also don't pull up a subquery that has explicit FOR UPDATE/SHARE
2028 : : * clauses, because pullup would cause the locking to occur semantically
2029 : : * higher than it should. Implicit FOR UPDATE/SHARE is okay because in
2030 : : * that case the locking was originally declared in the upper query
2031 : : * anyway.
2032 : : */
2033 [ + + ]: 78984 : if (subquery->hasAggs ||
2034 [ + + ]: 77403 : subquery->hasWindowFuncs ||
2035 [ + + ]: 76973 : subquery->hasTargetSRFs ||
2036 [ + + ]: 73301 : subquery->groupClause ||
2037 [ + + ]: 73197 : subquery->groupingSets ||
2038 [ + - ]: 73167 : subquery->havingQual ||
2039 [ + + ]: 73167 : subquery->sortClause ||
2040 [ + + ]: 72360 : subquery->distinctClause ||
2041 [ + + ]: 71697 : subquery->limitOffset ||
2042 [ + + ]: 71105 : subquery->limitCount ||
2043 [ + + ]: 70841 : subquery->hasForUpdate ||
2044 [ + + ]: 67602 : subquery->cteList)
2045 : 11527 : return false;
2046 : :
2047 : : /*
2048 : : * Don't pull up if the RTE represents a security-barrier view; we
2049 : : * couldn't prevent information leakage once the RTE's Vars are scattered
2050 : : * about in the upper query.
2051 : : */
2052 [ + + ]: 67457 : if (rte->security_barrier)
2053 : 1082 : return false;
2054 : :
2055 : : /*
2056 : : * If the subquery is LATERAL, check for pullup restrictions from that.
2057 : : */
2058 [ + + ]: 66375 : if (rte->lateral)
2059 : : {
2060 : : bool restricted;
2061 : : Relids safe_upper_varnos;
2062 : :
2063 : : /*
2064 : : * The subquery's WHERE and JOIN/ON quals mustn't contain any lateral
2065 : : * references to rels outside a higher outer join (including the case
2066 : : * where the outer join is within the subquery itself). In such a
2067 : : * case, pulling up would result in a situation where we need to
2068 : : * postpone quals from below an outer join to above it, which is
2069 : : * probably completely wrong and in any case is a complication that
2070 : : * doesn't seem worth addressing at the moment.
2071 : : */
2072 [ + + ]: 2486 : if (lowest_outer_join != NULL)
2073 : : {
2074 : 1264 : restricted = true;
2075 : 1264 : safe_upper_varnos = get_relids_in_jointree((Node *) lowest_outer_join,
2076 : : true, true);
2077 : : }
2078 : : else
2079 : : {
2080 : 1222 : restricted = false;
2081 : 1222 : safe_upper_varnos = NULL; /* doesn't matter */
2082 : : }
2083 : :
2084 [ + + ]: 2486 : if (jointree_contains_lateral_outer_refs(root,
2085 : 2486 : (Node *) subquery->jointree,
2086 : : restricted, safe_upper_varnos))
2087 : 30 : return false;
2088 : :
2089 : : /*
2090 : : * If there's an outer join above the LATERAL subquery, also disallow
2091 : : * pullup if the subquery's targetlist has any references to rels
2092 : : * outside the outer join, since these might get pulled into quals
2093 : : * above the subquery (but in or below the outer join) and then lead
2094 : : * to qual-postponement issues similar to the case checked for above.
2095 : : * (We wouldn't need to prevent pullup if no such references appear in
2096 : : * outer-query quals, but we don't have enough info here to check
2097 : : * that. Also, maybe this restriction could be removed if we forced
2098 : : * such refs to be wrapped in PlaceHolderVars, even when they're below
2099 : : * the nearest outer join? But it's a pretty hokey usage, so not
2100 : : * clear this is worth sweating over.)
2101 : : *
2102 : : * If you change this, see also the comments about lateral references
2103 : : * in pullup_replace_vars_callback().
2104 : : */
2105 [ + + ]: 2456 : if (lowest_outer_join != NULL)
2106 : : {
2107 : 1254 : Relids lvarnos = pull_varnos_of_level(root,
2108 : 1254 : (Node *) subquery->targetList,
2109 : : 1);
2110 : :
2111 [ + + ]: 1254 : if (!bms_is_subset(lvarnos, safe_upper_varnos))
2112 : 20 : return false;
2113 : : }
2114 : : }
2115 : :
2116 : : /*
2117 : : * Don't pull up a subquery that has any volatile functions in its
2118 : : * targetlist. Otherwise we might introduce multiple evaluations of these
2119 : : * functions, if they get copied to multiple places in the upper query,
2120 : : * leading to surprising results. (Note: the PlaceHolderVar mechanism
2121 : : * doesn't quite guarantee single evaluation; else we could pull up anyway
2122 : : * and just wrap such items in PlaceHolderVars ...)
2123 : : */
2124 [ + + ]: 66325 : if (contain_volatile_functions((Node *) subquery->targetList))
2125 : 241 : return false;
2126 : :
2127 : 66084 : return true;
2128 : : }
2129 : :
2130 : : /*
2131 : : * pull_up_simple_values
2132 : : * Pull up a single simple VALUES RTE.
2133 : : *
2134 : : * jtnode is a RangeTblRef that has been identified as a simple VALUES RTE
2135 : : * by pull_up_subqueries. We always return a RangeTblRef representing a
2136 : : * RESULT RTE to replace it (all failure cases should have been detected by
2137 : : * is_simple_values()). Actually, what we return is just jtnode, because
2138 : : * we replace the VALUES RTE in the rangetable with the RESULT RTE.
2139 : : *
2140 : : * rte is the RangeTblEntry referenced by jtnode. Because of the limited
2141 : : * possible usage of VALUES RTEs, we do not need the remaining parameters
2142 : : * of pull_up_subqueries_recurse.
2143 : : */
2144 : : static Node *
2145 : 3862 : pull_up_simple_values(PlannerInfo *root, Node *jtnode, RangeTblEntry *rte)
2146 : : {
2147 : 3862 : Query *parse = root->parse;
2148 : 3862 : int varno = ((RangeTblRef *) jtnode)->rtindex;
2149 : : List *values_list;
2150 : : List *tlist;
2151 : : AttrNumber attrno;
2152 : : pullup_replace_vars_context rvcontext;
2153 : : ListCell *lc;
2154 : :
2155 : : Assert(rte->rtekind == RTE_VALUES);
2156 : : Assert(list_length(rte->values_lists) == 1);
2157 : :
2158 : : /*
2159 : : * Need a modifiable copy of the VALUES list to hack on, just in case it's
2160 : : * multiply referenced.
2161 : : */
2162 : 3862 : values_list = copyObject(linitial(rte->values_lists));
2163 : :
2164 : : /*
2165 : : * The VALUES RTE can't contain any Vars of level zero, let alone any that
2166 : : * are join aliases, so no need to flatten join alias Vars.
2167 : : */
2168 : : Assert(!contain_vars_of_level((Node *) values_list, 0));
2169 : :
2170 : : /*
2171 : : * Set up required context data for pullup_replace_vars. In particular,
2172 : : * we have to make the VALUES list look like a subquery targetlist.
2173 : : */
2174 : 3862 : tlist = NIL;
2175 : 3862 : attrno = 1;
2176 [ + + + + : 8271 : foreach(lc, values_list)
+ + ]
2177 : : {
2178 : 4409 : tlist = lappend(tlist,
2179 : 4409 : makeTargetEntry((Expr *) lfirst(lc),
2180 : : attrno,
2181 : : NULL,
2182 : : false));
2183 : 4409 : attrno++;
2184 : : }
2185 : 3862 : rvcontext.root = root;
2186 : 3862 : rvcontext.targetlist = tlist;
2187 : 3862 : rvcontext.target_rte = rte;
2188 : 3862 : rvcontext.result_relation = 0;
2189 : 3862 : rvcontext.relids = NULL; /* can't be any lateral references here */
2190 : 3862 : rvcontext.nullinfo = NULL;
2191 : 3862 : rvcontext.outer_hasSubLinks = &parse->hasSubLinks;
2192 : 3862 : rvcontext.varno = varno;
2193 : 3862 : rvcontext.wrap_option = REPLACE_WRAP_NONE;
2194 : : /* initialize cache array with indexes 0 .. length(tlist) */
2195 : 3862 : rvcontext.rv_cache = palloc0_array(Node *, list_length(tlist) + 1);
2196 : :
2197 : : /*
2198 : : * Replace all of the top query's references to the RTE's outputs with
2199 : : * copies of the adjusted VALUES expressions, being careful not to replace
2200 : : * any of the jointree structure. We can assume there's no outer joins or
2201 : : * appendrels in the dummy Query that surrounds a VALUES RTE.
2202 : : */
2203 : 3862 : perform_pullup_replace_vars(root, &rvcontext, NULL);
2204 : :
2205 : : /*
2206 : : * There should be no appendrels to fix, nor any outer joins and hence no
2207 : : * PlaceHolderVars.
2208 : : */
2209 : : Assert(root->append_rel_list == NIL);
2210 : : Assert(root->join_info_list == NIL);
2211 : : Assert(root->placeholder_list == NIL);
2212 : :
2213 : : /*
2214 : : * Replace the VALUES RTE with a RESULT RTE. The VALUES RTE is the only
2215 : : * rtable entry in the current query level, so this is easy.
2216 : : */
2217 : : Assert(list_length(parse->rtable) == 1);
2218 : :
2219 : : /* Create suitable RTE */
2220 : 3862 : rte = makeNode(RangeTblEntry);
2221 : 3862 : rte->rtekind = RTE_RESULT;
2222 : 3862 : rte->eref = makeAlias("*RESULT*", NIL);
2223 : :
2224 : : /* Replace rangetable */
2225 : 3862 : parse->rtable = list_make1(rte);
2226 : :
2227 : : /* We could manufacture a new RangeTblRef, but the one we have is fine */
2228 : : Assert(varno == 1);
2229 : :
2230 : 3862 : return jtnode;
2231 : : }
2232 : :
2233 : : /*
2234 : : * is_simple_values
2235 : : * Check a VALUES RTE in the range table to see if it's simple enough
2236 : : * to pull up into the parent query.
2237 : : *
2238 : : * rte is the RTE_VALUES RangeTblEntry to check.
2239 : : */
2240 : : static bool
2241 : 11120 : is_simple_values(PlannerInfo *root, RangeTblEntry *rte)
2242 : : {
2243 : : Assert(rte->rtekind == RTE_VALUES);
2244 : :
2245 : : /*
2246 : : * There must be exactly one VALUES list, else it's not semantically
2247 : : * correct to replace the VALUES RTE with a RESULT RTE, nor would we have
2248 : : * a unique set of expressions to substitute into the parent query.
2249 : : */
2250 [ + + ]: 11120 : if (list_length(rte->values_lists) != 1)
2251 : 7258 : return false;
2252 : :
2253 : : /*
2254 : : * Because VALUES can't appear under an outer join (or at least, we won't
2255 : : * try to pull it up if it does), we need not worry about LATERAL, nor
2256 : : * about validity of PHVs for the VALUES' outputs.
2257 : : */
2258 : :
2259 : : /*
2260 : : * Don't pull up a VALUES that contains any set-returning or volatile
2261 : : * functions. The considerations here are basically identical to the
2262 : : * restrictions on a pull-able subquery's targetlist.
2263 : : */
2264 [ + - - + ]: 7724 : if (expression_returns_set((Node *) rte->values_lists) ||
2265 : 3862 : contain_volatile_functions((Node *) rte->values_lists))
2266 : 0 : return false;
2267 : :
2268 : : /*
2269 : : * Do not pull up a VALUES that's not the only RTE in its parent query.
2270 : : * This is actually the only case that the parser will generate at the
2271 : : * moment, and assuming this is true greatly simplifies
2272 : : * pull_up_simple_values().
2273 : : */
2274 [ + - ]: 3862 : if (list_length(root->parse->rtable) != 1 ||
2275 [ - + ]: 3862 : rte != (RangeTblEntry *) linitial(root->parse->rtable))
2276 : 0 : return false;
2277 : :
2278 : 3862 : return true;
2279 : : }
2280 : :
2281 : : /*
2282 : : * pull_up_constant_function
2283 : : * Pull up an RTE_FUNCTION expression that was simplified to a constant.
2284 : : *
2285 : : * jtnode is a RangeTblRef that has been identified as a FUNCTION RTE by
2286 : : * pull_up_subqueries. If its expression is just a Const, hoist that value
2287 : : * up into the parent query, and replace the RTE_FUNCTION with RTE_RESULT.
2288 : : *
2289 : : * In principle we could pull up any immutable expression, but we don't.
2290 : : * That might result in multiple evaluations of the expression, which could
2291 : : * be costly if it's not just a Const. Also, the main value of this is
2292 : : * to let the constant participate in further const-folding, and of course
2293 : : * that won't happen for a non-Const.
2294 : : *
2295 : : * The pulled-up value might need to be wrapped in a PlaceHolderVar if the
2296 : : * RTE is below an outer join or is part of an appendrel; the extra
2297 : : * parameters show whether that's needed.
2298 : : */
2299 : : static Node *
2300 : 36660 : pull_up_constant_function(PlannerInfo *root, Node *jtnode,
2301 : : RangeTblEntry *rte,
2302 : : AppendRelInfo *containing_appendrel)
2303 : : {
2304 : 36660 : Query *parse = root->parse;
2305 : : RangeTblFunction *rtf;
2306 : : TypeFuncClass functypclass;
2307 : : Oid funcrettype;
2308 : : TupleDesc tupdesc;
2309 : : pullup_replace_vars_context rvcontext;
2310 : :
2311 : : /* Fail if the RTE has ORDINALITY - we don't implement that here. */
2312 [ + + ]: 36660 : if (rte->funcordinality)
2313 : 731 : return jtnode;
2314 : :
2315 : : /* Fail if RTE isn't a single, simple Const expr */
2316 [ + + ]: 35929 : if (list_length(rte->functions) != 1)
2317 : 79 : return jtnode;
2318 : 35850 : rtf = linitial_node(RangeTblFunction, rte->functions);
2319 [ + + ]: 35850 : if (!IsA(rtf->funcexpr, Const))
2320 : 35540 : return jtnode;
2321 : :
2322 : : /*
2323 : : * If the function's result is not a scalar, we punt. In principle we
2324 : : * could break the composite constant value apart into per-column
2325 : : * constants, but for now it seems not worth the work.
2326 : : */
2327 [ + + ]: 310 : if (rtf->funccolcount != 1)
2328 : 25 : return jtnode; /* definitely composite */
2329 : :
2330 : : /* If it has a coldeflist, it certainly returns RECORD */
2331 [ - + ]: 285 : if (rtf->funccolnames != NIL)
2332 : 0 : return jtnode; /* must be a one-column RECORD type */
2333 : :
2334 : 285 : functypclass = get_expr_result_type(rtf->funcexpr,
2335 : : &funcrettype,
2336 : : &tupdesc);
2337 [ + + ]: 285 : if (functypclass != TYPEFUNC_SCALAR)
2338 : 10 : return jtnode; /* must be a one-column composite type */
2339 : :
2340 : : /* Create context for applying pullup_replace_vars */
2341 : 275 : rvcontext.root = root;
2342 : 275 : rvcontext.targetlist = list_make1(makeTargetEntry((Expr *) rtf->funcexpr,
2343 : : 1, /* resno */
2344 : : NULL, /* resname */
2345 : : false)); /* resjunk */
2346 : 275 : rvcontext.target_rte = rte;
2347 : 275 : rvcontext.result_relation = 0;
2348 : :
2349 : : /*
2350 : : * Since this function was reduced to a Const, it doesn't contain any
2351 : : * lateral references, even if it's marked as LATERAL. This means we
2352 : : * don't need to fill relids or nullinfo.
2353 : : */
2354 : 275 : rvcontext.relids = NULL;
2355 : 275 : rvcontext.nullinfo = NULL;
2356 : :
2357 : 275 : rvcontext.outer_hasSubLinks = &parse->hasSubLinks;
2358 : 275 : rvcontext.varno = ((RangeTblRef *) jtnode)->rtindex;
2359 : : /* this flag will be set below, if needed */
2360 : 275 : rvcontext.wrap_option = REPLACE_WRAP_NONE;
2361 : : /* initialize cache array with indexes 0 .. length(tlist) */
2362 : 275 : rvcontext.rv_cache = palloc0_array(Node *, list_length(rvcontext.targetlist) + 1);
2363 : :
2364 : : /*
2365 : : * If the parent query uses grouping sets, we need a PlaceHolderVar for
2366 : : * each expression of the subquery's targetlist items. (See comments in
2367 : : * pull_up_simple_subquery().)
2368 : : */
2369 [ - + ]: 275 : if (parse->groupingSets)
2370 : 0 : rvcontext.wrap_option = REPLACE_WRAP_ALL;
2371 : :
2372 : : /*
2373 : : * Replace all of the top query's references to the RTE's output with
2374 : : * copies of the funcexpr, being careful not to replace any of the
2375 : : * jointree structure.
2376 : : */
2377 : 275 : perform_pullup_replace_vars(root, &rvcontext,
2378 : : containing_appendrel);
2379 : :
2380 : : /*
2381 : : * We don't need to bother with changing PlaceHolderVars in the parent
2382 : : * query. Their references to the RT index are still good for now, and
2383 : : * will get removed later if we're able to drop the RTE_RESULT.
2384 : : */
2385 : :
2386 : : /*
2387 : : * Convert the RTE to be RTE_RESULT type, signifying that we don't need to
2388 : : * scan it anymore, and zero out RTE_FUNCTION-specific fields. Also make
2389 : : * sure the RTE is not marked LATERAL, since elsewhere we don't expect
2390 : : * RTE_RESULTs to be LATERAL.
2391 : : */
2392 : 275 : rte->rtekind = RTE_RESULT;
2393 : 275 : rte->functions = NIL;
2394 : 275 : rte->lateral = false;
2395 : :
2396 : : /*
2397 : : * We can reuse the RangeTblRef node.
2398 : : */
2399 : 275 : return jtnode;
2400 : : }
2401 : :
2402 : : /*
2403 : : * is_simple_union_all
2404 : : * Check a subquery to see if it's a simple UNION ALL.
2405 : : *
2406 : : * We require all the setops to be UNION ALL (no mixing) and there can't be
2407 : : * any datatype coercions involved, ie, all the leaf queries must emit the
2408 : : * same datatypes.
2409 : : */
2410 : : static bool
2411 : 21494 : is_simple_union_all(Query *subquery)
2412 : : {
2413 : : SetOperationStmt *topop;
2414 : :
2415 : : /* Let's just make sure it's a valid subselect ... */
2416 [ + - ]: 21494 : if (!IsA(subquery, Query) ||
2417 [ - + ]: 21494 : subquery->commandType != CMD_SELECT)
2418 [ # # ]: 0 : elog(ERROR, "subquery is bogus");
2419 : :
2420 : : /* Is it a set-operation query at all? */
2421 : 21494 : topop = castNode(SetOperationStmt, subquery->setOperations);
2422 [ + + ]: 21494 : if (!topop)
2423 : 16720 : return false;
2424 : :
2425 : : /* Can't handle ORDER BY, LIMIT/OFFSET, locking, or WITH */
2426 [ + + ]: 4774 : if (subquery->sortClause ||
2427 [ + - ]: 4722 : subquery->limitOffset ||
2428 [ + - ]: 4722 : subquery->limitCount ||
2429 [ + - ]: 4722 : subquery->rowMarks ||
2430 [ + + ]: 4722 : subquery->cteList)
2431 : 236 : return false;
2432 : :
2433 : : /* Recursively check the tree of set operations */
2434 : 4538 : return is_simple_union_all_recurse((Node *) topop, subquery,
2435 : : topop->colTypes);
2436 : : }
2437 : :
2438 : : static bool
2439 : 26255 : is_simple_union_all_recurse(Node *setOp, Query *setOpQuery, List *colTypes)
2440 : : {
2441 : : /* Since this function recurses, it could be driven to stack overflow. */
2442 : 26255 : check_stack_depth();
2443 : :
2444 [ + + ]: 26255 : if (IsA(setOp, RangeTblRef))
2445 : : {
2446 : 13219 : RangeTblRef *rtr = (RangeTblRef *) setOp;
2447 : 13219 : RangeTblEntry *rte = rt_fetch(rtr->rtindex, setOpQuery->rtable);
2448 : 13219 : Query *subquery = rte->subquery;
2449 : :
2450 : : Assert(subquery != NULL);
2451 : :
2452 : : /* Leaf nodes are OK if they match the toplevel column types */
2453 : : /* We don't have to compare typmods or collations here */
2454 : 13219 : return tlist_same_datatypes(subquery->targetList, colTypes, true);
2455 : : }
2456 [ + - ]: 13036 : else if (IsA(setOp, SetOperationStmt))
2457 : : {
2458 : 13036 : SetOperationStmt *op = (SetOperationStmt *) setOp;
2459 : :
2460 : : /* Must be UNION ALL */
2461 [ + + + + ]: 13036 : if (op->op != SETOP_UNION || !op->all)
2462 : 4451 : return false;
2463 : :
2464 : : /* Recurse to check inputs */
2465 [ + + + + ]: 16683 : return is_simple_union_all_recurse(op->larg, setOpQuery, colTypes) &&
2466 : 8098 : is_simple_union_all_recurse(op->rarg, setOpQuery, colTypes);
2467 : : }
2468 : : else
2469 : : {
2470 [ # # ]: 0 : elog(ERROR, "unrecognized node type: %d",
2471 : : (int) nodeTag(setOp));
2472 : : return false; /* keep compiler quiet */
2473 : : }
2474 : : }
2475 : :
2476 : : /*
2477 : : * is_safe_append_member
2478 : : * Check a subquery that is a leaf of a UNION ALL appendrel to see if it's
2479 : : * safe to pull up.
2480 : : */
2481 : : static bool
2482 : 14862 : is_safe_append_member(Query *subquery)
2483 : : {
2484 : : FromExpr *jtnode;
2485 : :
2486 : : /*
2487 : : * It's only safe to pull up the child if its jointree contains exactly
2488 : : * one RTE, else the AppendRelInfo data structure breaks. The one base RTE
2489 : : * could be buried in several levels of FromExpr, however. Also, if the
2490 : : * child's jointree is completely empty, we can pull up because
2491 : : * pull_up_simple_subquery will insert a single RTE_RESULT RTE instead.
2492 : : *
2493 : : * Also, the child can't have any WHERE quals because there's no place to
2494 : : * put them in an appendrel. (This is a bit annoying...) If we didn't
2495 : : * need to check this, we'd just test whether get_relids_in_jointree()
2496 : : * yields a singleton set, to be more consistent with the coding of
2497 : : * fix_append_rel_relids().
2498 : : */
2499 : 14862 : jtnode = subquery->jointree;
2500 : : Assert(IsA(jtnode, FromExpr));
2501 : : /* Check the completely-empty case */
2502 [ + + + + ]: 14862 : if (jtnode->fromlist == NIL && jtnode->quals == NULL)
2503 : 699 : return true;
2504 : : /* Check the more general case */
2505 [ + + ]: 25375 : while (IsA(jtnode, FromExpr))
2506 : : {
2507 [ + + ]: 14173 : if (jtnode->quals != NULL)
2508 : 2961 : return false;
2509 [ - + ]: 11212 : if (list_length(jtnode->fromlist) != 1)
2510 : 0 : return false;
2511 : 11212 : jtnode = linitial(jtnode->fromlist);
2512 : : }
2513 [ + + ]: 11202 : if (!IsA(jtnode, RangeTblRef))
2514 : 1031 : return false;
2515 : :
2516 : 10171 : return true;
2517 : : }
2518 : :
2519 : : /*
2520 : : * jointree_contains_lateral_outer_refs
2521 : : * Check for disallowed lateral references in a jointree's quals
2522 : : *
2523 : : * If restricted is false, all level-1 Vars are allowed (but we still must
2524 : : * search the jointree, since it might contain outer joins below which there
2525 : : * will be restrictions). If restricted is true, return true when any qual
2526 : : * in the jointree contains level-1 Vars coming from outside the rels listed
2527 : : * in safe_upper_varnos.
2528 : : */
2529 : : static bool
2530 : 5357 : jointree_contains_lateral_outer_refs(PlannerInfo *root, Node *jtnode,
2531 : : bool restricted,
2532 : : Relids safe_upper_varnos)
2533 : : {
2534 [ - + ]: 5357 : if (jtnode == NULL)
2535 : 0 : return false;
2536 [ + + ]: 5357 : if (IsA(jtnode, RangeTblRef))
2537 : 2512 : return false;
2538 [ + + ]: 2845 : else if (IsA(jtnode, FromExpr))
2539 : : {
2540 : 2526 : FromExpr *f = (FromExpr *) jtnode;
2541 : : ListCell *l;
2542 : :
2543 : : /* First, recurse to check child joins */
2544 [ + + + + : 4739 : foreach(l, f->fromlist)
+ + ]
2545 : : {
2546 [ + + ]: 2233 : if (jointree_contains_lateral_outer_refs(root,
2547 : 2233 : lfirst(l),
2548 : : restricted,
2549 : : safe_upper_varnos))
2550 : 20 : return true;
2551 : : }
2552 : :
2553 : : /* Then check the top-level quals */
2554 [ + + ]: 2506 : if (restricted &&
2555 [ + + ]: 1304 : !bms_is_subset(pull_varnos_of_level(root, f->quals, 1),
2556 : : safe_upper_varnos))
2557 : 10 : return true;
2558 : : }
2559 [ + - ]: 319 : else if (IsA(jtnode, JoinExpr))
2560 : : {
2561 : 319 : JoinExpr *j = (JoinExpr *) jtnode;
2562 : :
2563 : : /*
2564 : : * If this is an outer join, we mustn't allow any upper lateral
2565 : : * references in or below it.
2566 : : */
2567 [ + + ]: 319 : if (j->jointype != JOIN_INNER)
2568 : : {
2569 : 169 : restricted = true;
2570 : 169 : safe_upper_varnos = NULL;
2571 : : }
2572 : :
2573 : : /* Check the child joins */
2574 [ - + ]: 319 : if (jointree_contains_lateral_outer_refs(root,
2575 : : j->larg,
2576 : : restricted,
2577 : : safe_upper_varnos))
2578 : 0 : return true;
2579 [ - + ]: 319 : if (jointree_contains_lateral_outer_refs(root,
2580 : : j->rarg,
2581 : : restricted,
2582 : : safe_upper_varnos))
2583 : 0 : return true;
2584 : :
2585 : : /* Check the JOIN's qual clauses */
2586 [ + + ]: 319 : if (restricted &&
2587 [ + + ]: 279 : !bms_is_subset(pull_varnos_of_level(root, j->quals, 1),
2588 : : safe_upper_varnos))
2589 : 20 : return true;
2590 : : }
2591 : : else
2592 [ # # ]: 0 : elog(ERROR, "unrecognized node type: %d",
2593 : : (int) nodeTag(jtnode));
2594 : 2795 : return false;
2595 : : }
2596 : :
2597 : : /*
2598 : : * flatten_join_alias_vars_in_jointree
2599 : : * Apply flatten_join_alias_vars to all quals in the given jointree,
2600 : : * replacing them in place. The jointree must belong to root->parse.
2601 : : */
2602 : : static void
2603 : 2845 : flatten_join_alias_vars_in_jointree(PlannerInfo *root, Node *jtnode)
2604 : : {
2605 [ - + ]: 2845 : if (jtnode == NULL)
2606 : 0 : return;
2607 [ + + ]: 2845 : if (IsA(jtnode, RangeTblRef))
2608 : 1430 : return;
2609 [ + + ]: 1415 : else if (IsA(jtnode, FromExpr))
2610 : : {
2611 : 1243 : FromExpr *f = (FromExpr *) jtnode;
2612 : : ListCell *l;
2613 : :
2614 [ + - + + : 2541 : foreach(l, f->fromlist)
+ + ]
2615 : 1298 : flatten_join_alias_vars_in_jointree(root, lfirst(l));
2616 : 1243 : f->quals = flatten_join_alias_vars(root, root->parse, f->quals);
2617 : : }
2618 [ + - ]: 172 : else if (IsA(jtnode, JoinExpr))
2619 : : {
2620 : 172 : JoinExpr *j = (JoinExpr *) jtnode;
2621 : :
2622 : 172 : flatten_join_alias_vars_in_jointree(root, j->larg);
2623 : 172 : flatten_join_alias_vars_in_jointree(root, j->rarg);
2624 : 172 : j->quals = flatten_join_alias_vars(root, root->parse, j->quals);
2625 : : }
2626 : : else
2627 [ # # ]: 0 : elog(ERROR, "unrecognized node type: %d",
2628 : : (int) nodeTag(jtnode));
2629 : : }
2630 : :
2631 : : /*
2632 : : * Perform pullup_replace_vars everyplace it's needed in the query tree.
2633 : : *
2634 : : * Caller has already filled *rvcontext with data describing what to
2635 : : * substitute for Vars referencing the target subquery. In addition
2636 : : * we need the identity of the containing appendrel if any.
2637 : : */
2638 : : static void
2639 : 35097 : perform_pullup_replace_vars(PlannerInfo *root,
2640 : : pullup_replace_vars_context *rvcontext,
2641 : : AppendRelInfo *containing_appendrel)
2642 : : {
2643 : 35097 : Query *parse = root->parse;
2644 : : ListCell *lc;
2645 : :
2646 : : /*
2647 : : * If we are considering an appendrel child subquery (that is, a UNION ALL
2648 : : * member query that we're pulling up), then the only part of the upper
2649 : : * query that could reference the child yet is the translated_vars list of
2650 : : * the associated AppendRelInfo. Furthermore, we do not want to force use
2651 : : * of PHVs in the AppendRelInfo --- there isn't any outer join between.
2652 : : */
2653 [ + + ]: 35097 : if (containing_appendrel)
2654 : : {
2655 : 5364 : ReplaceWrapOption save_wrap_option = rvcontext->wrap_option;
2656 : :
2657 : 5364 : rvcontext->wrap_option = REPLACE_WRAP_NONE;
2658 : 5364 : containing_appendrel->translated_vars = (List *)
2659 : 5364 : pullup_replace_vars((Node *) containing_appendrel->translated_vars,
2660 : : rvcontext);
2661 : 5364 : rvcontext->wrap_option = save_wrap_option;
2662 : 5364 : return;
2663 : : }
2664 : :
2665 : : /*
2666 : : * Replace all of the top query's references to the subquery's outputs
2667 : : * with copies of the adjusted subtlist items, being careful not to
2668 : : * replace any of the jointree structure. (This'd be a lot cleaner if we
2669 : : * could use query_tree_mutator.) We have to use PHVs in the targetList,
2670 : : * returningList, and havingQual, since those are certainly above any
2671 : : * outer join. replace_vars_in_jointree tracks its location in the
2672 : : * jointree and uses PHVs or not appropriately.
2673 : : */
2674 : 29733 : parse->targetList = (List *)
2675 : 29733 : pullup_replace_vars((Node *) parse->targetList, rvcontext);
2676 : 29733 : parse->returningList = (List *)
2677 : 29733 : pullup_replace_vars((Node *) parse->returningList, rvcontext);
2678 : :
2679 [ + + ]: 29733 : if (parse->onConflict)
2680 : : {
2681 : 34 : parse->onConflict->onConflictSet = (List *)
2682 : 17 : pullup_replace_vars((Node *) parse->onConflict->onConflictSet,
2683 : : rvcontext);
2684 : 17 : parse->onConflict->onConflictWhere =
2685 : 17 : pullup_replace_vars(parse->onConflict->onConflictWhere,
2686 : : rvcontext);
2687 : :
2688 : : /*
2689 : : * We assume ON CONFLICT's arbiterElems, arbiterWhere, exclRelTlist
2690 : : * can't contain any references to a subquery.
2691 : : */
2692 : : }
2693 [ + + ]: 29733 : if (parse->mergeActionList)
2694 : : {
2695 [ + - + + : 2563 : foreach(lc, parse->mergeActionList)
+ + ]
2696 : : {
2697 : 1544 : MergeAction *action = lfirst(lc);
2698 : :
2699 : 1544 : action->qual = pullup_replace_vars(action->qual, rvcontext);
2700 : 1544 : action->targetList = (List *)
2701 : 1544 : pullup_replace_vars((Node *) action->targetList, rvcontext);
2702 : : }
2703 : : }
2704 : 29733 : parse->mergeJoinCondition = pullup_replace_vars(parse->mergeJoinCondition,
2705 : : rvcontext);
2706 : 29733 : replace_vars_in_jointree((Node *) parse->jointree, rvcontext);
2707 : : Assert(parse->setOperations == NULL);
2708 : 29733 : parse->havingQual = pullup_replace_vars(parse->havingQual, rvcontext);
2709 : :
2710 : : /*
2711 : : * Replace references in the translated_vars lists of appendrels.
2712 : : */
2713 [ + + + + : 29793 : foreach(lc, root->append_rel_list)
+ + ]
2714 : : {
2715 : 60 : AppendRelInfo *appinfo = (AppendRelInfo *) lfirst(lc);
2716 : :
2717 : 60 : appinfo->translated_vars = (List *)
2718 : 60 : pullup_replace_vars((Node *) appinfo->translated_vars, rvcontext);
2719 : : }
2720 : :
2721 : : /*
2722 : : * Replace references in the joinaliasvars lists of join RTEs and the
2723 : : * groupexprs list of group RTE.
2724 : : */
2725 [ + - + + : 86113 : foreach(lc, parse->rtable)
+ + ]
2726 : : {
2727 : 56380 : RangeTblEntry *otherrte = (RangeTblEntry *) lfirst(lc);
2728 : :
2729 [ + + ]: 56380 : if (otherrte->rtekind == RTE_JOIN)
2730 : 7089 : otherrte->joinaliasvars = (List *)
2731 : 7089 : pullup_replace_vars((Node *) otherrte->joinaliasvars,
2732 : : rvcontext);
2733 [ + + ]: 49291 : else if (otherrte->rtekind == RTE_GROUP)
2734 : 813 : otherrte->groupexprs = (List *)
2735 : 813 : pullup_replace_vars((Node *) otherrte->groupexprs,
2736 : : rvcontext);
2737 : : }
2738 : : }
2739 : :
2740 : : /*
2741 : : * Helper routine for perform_pullup_replace_vars: do pullup_replace_vars on
2742 : : * every expression in the jointree, without changing the jointree structure
2743 : : * itself. Ugly, but there's no other way...
2744 : : */
2745 : : static void
2746 : 80534 : replace_vars_in_jointree(Node *jtnode,
2747 : : pullup_replace_vars_context *context)
2748 : : {
2749 [ - + ]: 80534 : if (jtnode == NULL)
2750 : 0 : return;
2751 [ + + ]: 80534 : if (IsA(jtnode, RangeTblRef))
2752 : : {
2753 : : /*
2754 : : * If the RangeTblRef refers to a LATERAL subquery (that isn't the
2755 : : * same subquery we're pulling up), it might contain references to the
2756 : : * target subquery, which we must replace. We drive this from the
2757 : : * jointree scan, rather than a scan of the rtable, so that we can
2758 : : * avoid processing no-longer-referenced RTEs.
2759 : : */
2760 : 40483 : int varno = ((RangeTblRef *) jtnode)->rtindex;
2761 : :
2762 [ + + ]: 40483 : if (varno != context->varno) /* ignore target subquery itself */
2763 : : {
2764 : 10750 : RangeTblEntry *rte = rt_fetch(varno, context->root->parse->rtable);
2765 : :
2766 : : Assert(rte != context->target_rte);
2767 [ + + ]: 10750 : if (rte->lateral)
2768 : : {
2769 [ - + + + : 1052 : switch (rte->rtekind)
- - - ]
2770 : : {
2771 : 0 : case RTE_RELATION:
2772 : : /* shouldn't be marked LATERAL unless tablesample */
2773 : : Assert(rte->tablesample);
2774 : 0 : rte->tablesample = (TableSampleClause *)
2775 : 0 : pullup_replace_vars((Node *) rte->tablesample,
2776 : : context);
2777 : 0 : break;
2778 : 593 : case RTE_SUBQUERY:
2779 : 593 : rte->subquery =
2780 : 593 : pullup_replace_vars_subquery(rte->subquery,
2781 : : context);
2782 : 593 : break;
2783 : 369 : case RTE_FUNCTION:
2784 : 369 : rte->functions = (List *)
2785 : 369 : pullup_replace_vars((Node *) rte->functions,
2786 : : context);
2787 : 369 : break;
2788 : 90 : case RTE_TABLEFUNC:
2789 : 90 : rte->tablefunc = (TableFunc *)
2790 : 90 : pullup_replace_vars((Node *) rte->tablefunc,
2791 : : context);
2792 : 90 : break;
2793 : 0 : case RTE_VALUES:
2794 : 0 : rte->values_lists = (List *)
2795 : 0 : pullup_replace_vars((Node *) rte->values_lists,
2796 : : context);
2797 : 0 : break;
2798 : 0 : case RTE_JOIN:
2799 : : case RTE_CTE:
2800 : : case RTE_NAMEDTUPLESTORE:
2801 : : case RTE_RESULT:
2802 : : case RTE_GROUP:
2803 : : /* these shouldn't be marked LATERAL */
2804 : : Assert(false);
2805 : 0 : break;
2806 : : }
2807 : : }
2808 : : }
2809 : : }
2810 [ + + ]: 40051 : else if (IsA(jtnode, FromExpr))
2811 : : {
2812 : 32107 : FromExpr *f = (FromExpr *) jtnode;
2813 : : ListCell *l;
2814 : :
2815 [ + - + + : 67020 : foreach(l, f->fromlist)
+ + ]
2816 : 34913 : replace_vars_in_jointree(lfirst(l), context);
2817 : 32107 : f->quals = pullup_replace_vars(f->quals, context);
2818 : : }
2819 [ + - ]: 7944 : else if (IsA(jtnode, JoinExpr))
2820 : : {
2821 : 7944 : JoinExpr *j = (JoinExpr *) jtnode;
2822 : 7944 : ReplaceWrapOption save_wrap_option = context->wrap_option;
2823 : :
2824 : 7944 : replace_vars_in_jointree(j->larg, context);
2825 : 7944 : replace_vars_in_jointree(j->rarg, context);
2826 : :
2827 : : /*
2828 : : * Use PHVs within the join quals of a full join for variable-free
2829 : : * expressions. Otherwise, we cannot identify which side of the join
2830 : : * a pulled-up variable-free expression came from, which can lead to
2831 : : * failure to make a plan at all because none of the quals appear to
2832 : : * be mergeable or hashable conditions.
2833 : : */
2834 [ + + ]: 7944 : if (j->jointype == JOIN_FULL)
2835 : 701 : context->wrap_option = REPLACE_WRAP_VARFREE;
2836 : :
2837 : 7944 : j->quals = pullup_replace_vars(j->quals, context);
2838 : :
2839 : 7944 : context->wrap_option = save_wrap_option;
2840 : : }
2841 : : else
2842 [ # # ]: 0 : elog(ERROR, "unrecognized node type: %d",
2843 : : (int) nodeTag(jtnode));
2844 : : }
2845 : :
2846 : : /*
2847 : : * Apply pullup variable replacement throughout an expression tree
2848 : : *
2849 : : * Returns a modified copy of the tree, so this can't be used where we
2850 : : * need to do in-place replacement.
2851 : : */
2852 : : static Node *
2853 : 177069 : pullup_replace_vars(Node *expr, pullup_replace_vars_context *context)
2854 : : {
2855 : 177069 : return replace_rte_variables(expr,
2856 : : context->varno, 0,
2857 : : pullup_replace_vars_callback,
2858 : : context,
2859 : : context->outer_hasSubLinks);
2860 : : }
2861 : :
2862 : : static Node *
2863 : 100179 : pullup_replace_vars_callback(const Var *var,
2864 : : replace_rte_variables_context *context)
2865 : : {
2866 : 100179 : pullup_replace_vars_context *rcon = (pullup_replace_vars_context *) context->callback_arg;
2867 : 100179 : int varattno = var->varattno;
2868 : : bool need_phv;
2869 : : Node *newnode;
2870 : :
2871 : : /* System columns are not replaced. */
2872 [ + + ]: 100179 : if (varattno < InvalidAttrNumber)
2873 : 35 : return (Node *) copyObject(var);
2874 : :
2875 : : /*
2876 : : * We need a PlaceHolderVar if the Var-to-be-replaced has nonempty
2877 : : * varnullingrels (unless we find below that the replacement expression is
2878 : : * a Var or PlaceHolderVar that we can just add the nullingrels to). We
2879 : : * also need one if the caller has instructed us that certain expression
2880 : : * replacements need to be wrapped for identification purposes.
2881 : : */
2882 [ + + ]: 187987 : need_phv = (var->varnullingrels != NULL) ||
2883 [ + + ]: 87843 : (rcon->wrap_option != REPLACE_WRAP_NONE);
2884 : :
2885 : : /*
2886 : : * If PlaceHolderVars are needed, we cache the modified expressions in
2887 : : * rcon->rv_cache[]. This is not in hopes of any material speed gain
2888 : : * within this function, but to avoid generating identical PHVs with
2889 : : * different IDs. That would result in duplicate evaluations at runtime,
2890 : : * and possibly prevent optimizations that rely on recognizing different
2891 : : * references to the same subquery output as being equal(). So it's worth
2892 : : * a bit of extra effort to avoid it.
2893 : : *
2894 : : * The cached items have phlevelsup = 0 and phnullingrels = NULL; we'll
2895 : : * copy them and adjust those values for this reference site below.
2896 : : */
2897 [ + + + - ]: 100144 : if (need_phv &&
2898 [ + - ]: 14525 : varattno >= InvalidAttrNumber &&
2899 : 14525 : varattno <= list_length(rcon->targetlist) &&
2900 [ + + ]: 14525 : rcon->rv_cache[varattno] != NULL)
2901 : : {
2902 : : /* Just copy the entry and fall through to adjust phlevelsup etc */
2903 : 3153 : newnode = copyObject(rcon->rv_cache[varattno]);
2904 : : }
2905 : : else
2906 : : {
2907 : : /*
2908 : : * Generate the replacement expression. This takes care of expanding
2909 : : * wholerow references and dealing with non-default varreturningtype.
2910 : : */
2911 : 96991 : newnode = ReplaceVarFromTargetList(var,
2912 : : rcon->target_rte,
2913 : : rcon->targetlist,
2914 : : rcon->result_relation,
2915 : : REPLACEVARS_REPORT_ERROR,
2916 : : 0);
2917 : :
2918 : : /* Insert PlaceHolderVar if needed */
2919 [ + + ]: 96991 : if (need_phv)
2920 : : {
2921 : : bool wrap;
2922 : :
2923 [ + + ]: 11372 : if (rcon->wrap_option == REPLACE_WRAP_ALL)
2924 : : {
2925 : : /* Caller told us to wrap all expressions in a PlaceHolderVar */
2926 : 967 : wrap = true;
2927 : : }
2928 [ + + ]: 10405 : else if (varattno == InvalidAttrNumber)
2929 : : {
2930 : : /*
2931 : : * Insert PlaceHolderVar for whole-tuple reference. Notice
2932 : : * that we are wrapping one PlaceHolderVar around the whole
2933 : : * RowExpr, rather than putting one around each element of the
2934 : : * row. This is because we need the expression to yield NULL,
2935 : : * not ROW(NULL,NULL,...) when it is forced to null by an
2936 : : * outer join.
2937 : : */
2938 : 71 : wrap = true;
2939 : : }
2940 [ + - + + ]: 10334 : else if (newnode && IsA(newnode, Var) &&
2941 [ + + ]: 8332 : ((Var *) newnode)->varlevelsup == 0)
2942 : : {
2943 : : /*
2944 : : * Simple Vars always escape being wrapped, unless they are
2945 : : * lateral references to something outside the subquery being
2946 : : * pulled up and the referenced rel is not under the same
2947 : : * lowest nulling outer join.
2948 : : */
2949 : 8320 : wrap = false;
2950 [ + + ]: 8320 : if (rcon->target_rte->lateral &&
2951 [ + + ]: 1290 : !bms_is_member(((Var *) newnode)->varno, rcon->relids))
2952 : : {
2953 : 175 : nullingrel_info *nullinfo = rcon->nullinfo;
2954 : 175 : int lvarno = ((Var *) newnode)->varno;
2955 : :
2956 : : Assert(lvarno > 0 && lvarno <= nullinfo->rtlength);
2957 [ + + ]: 175 : if (!bms_is_subset(nullinfo->nullingrels[rcon->varno],
2958 : 175 : nullinfo->nullingrels[lvarno]))
2959 : 155 : wrap = true;
2960 : : }
2961 : : }
2962 [ + - + + ]: 2014 : else if (newnode && IsA(newnode, PlaceHolderVar) &&
2963 [ + - ]: 160 : ((PlaceHolderVar *) newnode)->phlevelsup == 0)
2964 : : {
2965 : : /* The same rules apply for a PlaceHolderVar */
2966 : 160 : wrap = false;
2967 [ + + ]: 160 : if (rcon->target_rte->lateral &&
2968 [ + - ]: 50 : !bms_is_subset(((PlaceHolderVar *) newnode)->phrels,
2969 : 50 : rcon->relids))
2970 : : {
2971 : 50 : nullingrel_info *nullinfo = rcon->nullinfo;
2972 : 50 : Relids lvarnos = ((PlaceHolderVar *) newnode)->phrels;
2973 : : int lvarno;
2974 : :
2975 : 50 : lvarno = -1;
2976 [ + + ]: 70 : while ((lvarno = bms_next_member(lvarnos, lvarno)) >= 0)
2977 : : {
2978 : : Assert(lvarno > 0 && lvarno <= nullinfo->rtlength);
2979 [ + + ]: 50 : if (!bms_is_subset(nullinfo->nullingrels[rcon->varno],
2980 : 50 : nullinfo->nullingrels[lvarno]))
2981 : : {
2982 : 30 : wrap = true;
2983 : 30 : break;
2984 : : }
2985 : : }
2986 : : }
2987 : : }
2988 : : else
2989 : : {
2990 : : /*
2991 : : * If the node contains Var(s) or PlaceHolderVar(s) of the
2992 : : * subquery being pulled up, or of rels that are under the
2993 : : * same lowest nulling outer join as the subquery, and does
2994 : : * not contain any non-strict constructs, then instead of
2995 : : * adding a PHV on top we can add the required nullingrels to
2996 : : * those Vars/PHVs. (This is fundamentally a generalization
2997 : : * of the above cases for bare Vars and PHVs.)
2998 : : *
2999 : : * This test is somewhat expensive, but it avoids pessimizing
3000 : : * the plan in cases where the nullingrels get removed again
3001 : : * later by outer join reduction.
3002 : : *
3003 : : * Note that we don't force wrapping of expressions containing
3004 : : * lateral references, so long as they also contain Vars/PHVs
3005 : : * of the subquery, or of rels that are under the same lowest
3006 : : * nulling outer join as the subquery. This is okay because
3007 : : * of the restriction to strict constructs: if those Vars/PHVs
3008 : : * have been forced to NULL by an outer join then the end
3009 : : * result of the expression will be NULL too, regardless of
3010 : : * the lateral references. So it's not necessary to force the
3011 : : * expression to be evaluated below the outer join. This can
3012 : : * be a very valuable optimization, because it may allow us to
3013 : : * avoid using a nested loop to pass the lateral reference
3014 : : * down.
3015 : : *
3016 : : * This analysis could be tighter: in particular, a non-strict
3017 : : * construct hidden within a lower-level PlaceHolderVar is not
3018 : : * reason to add another PHV. But for now it doesn't seem
3019 : : * worth the code to be more exact. This is also why it's
3020 : : * preferable to handle bare PHVs in the above branch, rather
3021 : : * than this branch. We also prefer to handle bare Vars in a
3022 : : * separate branch, as it's cheaper this way and parallels the
3023 : : * handling of PHVs.
3024 : : *
3025 : : * For a LATERAL subquery, we have to check the actual var
3026 : : * membership of the node, but if it's non-lateral then any
3027 : : * level-zero var must belong to the subquery.
3028 : : */
3029 : 1854 : bool contain_nullable_vars = false;
3030 : :
3031 [ + + ]: 1854 : if (!rcon->target_rte->lateral)
3032 : : {
3033 [ + + ]: 1644 : if (contain_vars_of_level(newnode, 0))
3034 : 598 : contain_nullable_vars = true;
3035 : : }
3036 : : else
3037 : : {
3038 : : Relids all_varnos;
3039 : :
3040 : 210 : all_varnos = pull_varnos(rcon->root, newnode);
3041 [ + + ]: 210 : if (bms_overlap(all_varnos, rcon->relids))
3042 : 115 : contain_nullable_vars = true;
3043 : : else
3044 : : {
3045 : 95 : nullingrel_info *nullinfo = rcon->nullinfo;
3046 : : int varno;
3047 : :
3048 : 95 : varno = -1;
3049 [ + + ]: 175 : while ((varno = bms_next_member(all_varnos, varno)) >= 0)
3050 : : {
3051 : : Assert(varno > 0 && varno <= nullinfo->rtlength);
3052 [ + + ]: 110 : if (bms_is_subset(nullinfo->nullingrels[rcon->varno],
3053 : 110 : nullinfo->nullingrels[varno]))
3054 : : {
3055 : 30 : contain_nullable_vars = true;
3056 : 30 : break;
3057 : : }
3058 : : }
3059 : : }
3060 : : }
3061 : :
3062 [ + + ]: 1854 : if (contain_nullable_vars &&
3063 [ + + ]: 743 : !contain_nonstrict_functions(newnode))
3064 : : {
3065 : : /* No wrap needed */
3066 : 260 : wrap = false;
3067 : : }
3068 : : else
3069 : : {
3070 : : /* Else wrap it in a PlaceHolderVar */
3071 : 1594 : wrap = true;
3072 : : }
3073 : : }
3074 : :
3075 [ + + ]: 11372 : if (wrap)
3076 : : {
3077 : : newnode = (Node *)
3078 : 2817 : make_placeholder_expr(rcon->root,
3079 : : (Expr *) newnode,
3080 : : bms_make_singleton(rcon->varno));
3081 : :
3082 : : /*
3083 : : * Cache it if possible (ie, if the attno is in range, which
3084 : : * it probably always should be).
3085 : : */
3086 [ + - + - ]: 5634 : if (varattno >= InvalidAttrNumber &&
3087 : 2817 : varattno <= list_length(rcon->targetlist))
3088 : 2817 : rcon->rv_cache[varattno] = copyObject(newnode);
3089 : : }
3090 : : }
3091 : : }
3092 : :
3093 : : /* Propagate any varnullingrels into the replacement expression */
3094 [ + + ]: 100144 : if (var->varnullingrels != NULL)
3095 : : {
3096 [ + + ]: 12301 : if (IsA(newnode, Var))
3097 : : {
3098 : 7711 : Var *newvar = (Var *) newnode;
3099 : :
3100 : : Assert(newvar->varlevelsup == 0);
3101 : 7711 : newvar->varnullingrels = bms_add_members(newvar->varnullingrels,
3102 : 7711 : var->varnullingrels);
3103 : : }
3104 [ + + ]: 4590 : else if (IsA(newnode, PlaceHolderVar))
3105 : : {
3106 : 4340 : PlaceHolderVar *newphv = (PlaceHolderVar *) newnode;
3107 : :
3108 : : Assert(newphv->phlevelsup == 0);
3109 : 4340 : newphv->phnullingrels = bms_add_members(newphv->phnullingrels,
3110 : 4340 : var->varnullingrels);
3111 : : }
3112 : : else
3113 : : {
3114 : : /*
3115 : : * There should be Vars/PHVs within the expression that we can
3116 : : * modify. Vars/PHVs of the subquery should have the full
3117 : : * var->varnullingrels added to them, but if there are lateral
3118 : : * references within the expression, those must be marked with
3119 : : * only the nullingrels that potentially apply to them. (This
3120 : : * corresponds to the fact that the expression will now be
3121 : : * evaluated at the join level of the Var that we are replacing:
3122 : : * the lateral references may have bubbled up through fewer outer
3123 : : * joins than the subquery's Vars have. Per the discussion above,
3124 : : * we'll still get the right answers.) That relid set could be
3125 : : * different for different lateral relations, so we have to do
3126 : : * this work for each one.
3127 : : *
3128 : : * (Currently, the restrictions in is_simple_subquery() mean that
3129 : : * at most we have to remove the lowest outer join's relid from
3130 : : * the nullingrels of a lateral reference. However, we might
3131 : : * relax those restrictions someday, so let's do this right.)
3132 : : */
3133 [ + + ]: 250 : if (rcon->target_rte->lateral)
3134 : : {
3135 : 70 : nullingrel_info *nullinfo = rcon->nullinfo;
3136 : : Relids lvarnos;
3137 : : int lvarno;
3138 : :
3139 : : /*
3140 : : * Identify lateral varnos used within newnode. We must do
3141 : : * this before injecting var->varnullingrels into the tree.
3142 : : */
3143 : 70 : lvarnos = pull_varnos(rcon->root, newnode);
3144 : 70 : lvarnos = bms_del_members(lvarnos, rcon->relids);
3145 : : /* For each one, add relevant nullingrels if any */
3146 : 70 : lvarno = -1;
3147 [ + + ]: 140 : while ((lvarno = bms_next_member(lvarnos, lvarno)) >= 0)
3148 : : {
3149 : : Relids lnullingrels;
3150 : :
3151 : : Assert(lvarno > 0 && lvarno <= nullinfo->rtlength);
3152 : 70 : lnullingrels = bms_intersect(var->varnullingrels,
3153 : 70 : nullinfo->nullingrels[lvarno]);
3154 [ + + ]: 70 : if (!bms_is_empty(lnullingrels))
3155 : 40 : newnode = add_nulling_relids(newnode,
3156 : 40 : bms_make_singleton(lvarno),
3157 : : lnullingrels);
3158 : : }
3159 : : }
3160 : :
3161 : : /* Finally, deal with Vars/PHVs of the subquery itself */
3162 : 250 : newnode = add_nulling_relids(newnode,
3163 : 250 : rcon->relids,
3164 : 250 : var->varnullingrels);
3165 : : /* Assert we did put the varnullingrels into the expression */
3166 : : Assert(bms_is_subset(var->varnullingrels,
3167 : : pull_varnos(rcon->root, newnode)));
3168 : : }
3169 : : }
3170 : :
3171 : : /* Must adjust varlevelsup if replaced Var is within a subquery */
3172 [ + + ]: 100144 : if (var->varlevelsup > 0)
3173 : 1072 : IncrementVarSublevelsUp(newnode, var->varlevelsup, 0);
3174 : :
3175 : 100144 : return newnode;
3176 : : }
3177 : :
3178 : : /*
3179 : : * Apply pullup variable replacement to a subquery
3180 : : *
3181 : : * This needs to be different from pullup_replace_vars() because
3182 : : * replace_rte_variables will think that it shouldn't increment sublevels_up
3183 : : * before entering the Query; so we need to call it with sublevels_up == 1.
3184 : : */
3185 : : static Query *
3186 : 593 : pullup_replace_vars_subquery(Query *query,
3187 : : pullup_replace_vars_context *context)
3188 : : {
3189 : : Assert(IsA(query, Query));
3190 : 593 : return (Query *) replace_rte_variables((Node *) query,
3191 : : context->varno, 1,
3192 : : pullup_replace_vars_callback,
3193 : : context,
3194 : : NULL);
3195 : : }
3196 : :
3197 : :
3198 : : /*
3199 : : * flatten_simple_union_all
3200 : : * Try to optimize top-level UNION ALL structure into an appendrel
3201 : : *
3202 : : * If a query's setOperations tree consists entirely of simple UNION ALL
3203 : : * operations, flatten it into an append relation, which we can process more
3204 : : * intelligently than the general setops case. Otherwise, do nothing.
3205 : : *
3206 : : * In most cases, this can succeed only for a top-level query, because for a
3207 : : * subquery in FROM, the parent query's invocation of pull_up_subqueries would
3208 : : * already have flattened the UNION via pull_up_simple_union_all. But there
3209 : : * are a few cases we can support here but not in that code path, for example
3210 : : * when the subquery also contains ORDER BY.
3211 : : */
3212 : : void
3213 : 5777 : flatten_simple_union_all(PlannerInfo *root)
3214 : : {
3215 : 5777 : Query *parse = root->parse;
3216 : : SetOperationStmt *topop;
3217 : : Node *leftmostjtnode;
3218 : : int leftmostRTI;
3219 : : RangeTblEntry *leftmostRTE;
3220 : : int childRTI;
3221 : : RangeTblEntry *childRTE;
3222 : : RangeTblRef *rtr;
3223 : :
3224 : : /* Shouldn't be called unless query has setops */
3225 : 5777 : topop = castNode(SetOperationStmt, parse->setOperations);
3226 : : Assert(topop);
3227 : :
3228 : : /* Can't optimize away a recursive UNION */
3229 [ + + ]: 5777 : if (root->hasRecursion)
3230 : 743 : return;
3231 : :
3232 : : /*
3233 : : * Recursively check the tree of set operations. If not all UNION ALL
3234 : : * with identical column types, punt.
3235 : : */
3236 [ + + ]: 5034 : if (!is_simple_union_all_recurse((Node *) topop, parse, topop->colTypes))
3237 : 4360 : return;
3238 : :
3239 : : /*
3240 : : * Locate the leftmost leaf query in the setops tree. The upper query's
3241 : : * Vars all refer to this RTE (see transformSetOperationStmt).
3242 : : */
3243 : 674 : leftmostjtnode = topop->larg;
3244 [ + - + + ]: 1065 : while (leftmostjtnode && IsA(leftmostjtnode, SetOperationStmt))
3245 : 391 : leftmostjtnode = ((SetOperationStmt *) leftmostjtnode)->larg;
3246 : : Assert(leftmostjtnode && IsA(leftmostjtnode, RangeTblRef));
3247 : 674 : leftmostRTI = ((RangeTblRef *) leftmostjtnode)->rtindex;
3248 : 674 : leftmostRTE = rt_fetch(leftmostRTI, parse->rtable);
3249 : : Assert(leftmostRTE->rtekind == RTE_SUBQUERY);
3250 : :
3251 : : /*
3252 : : * Make a copy of the leftmost RTE and add it to the rtable. This copy
3253 : : * will represent the leftmost leaf query in its capacity as a member of
3254 : : * the appendrel. The original will represent the appendrel as a whole.
3255 : : * (We must do things this way because the upper query's Vars have to be
3256 : : * seen as referring to the whole appendrel.)
3257 : : */
3258 : 674 : childRTE = copyObject(leftmostRTE);
3259 : 674 : parse->rtable = lappend(parse->rtable, childRTE);
3260 : 674 : childRTI = list_length(parse->rtable);
3261 : :
3262 : : /* Modify the setops tree to reference the child copy */
3263 : 674 : ((RangeTblRef *) leftmostjtnode)->rtindex = childRTI;
3264 : :
3265 : : /* Modify the formerly-leftmost RTE to mark it as an appendrel parent */
3266 : 674 : leftmostRTE->inh = true;
3267 : :
3268 : : /*
3269 : : * Form a RangeTblRef for the appendrel, and insert it into FROM. The top
3270 : : * Query of a setops tree should have had an empty FromClause initially.
3271 : : */
3272 : 674 : rtr = makeNode(RangeTblRef);
3273 : 674 : rtr->rtindex = leftmostRTI;
3274 : : Assert(parse->jointree->fromlist == NIL);
3275 : 674 : parse->jointree->fromlist = list_make1(rtr);
3276 : :
3277 : : /*
3278 : : * Now pretend the query has no setops. We must do this before trying to
3279 : : * do subquery pullup, because of Assert in pull_up_simple_subquery.
3280 : : */
3281 : 674 : parse->setOperations = NULL;
3282 : :
3283 : : /*
3284 : : * Build AppendRelInfo information, and apply pull_up_subqueries to the
3285 : : * leaf queries of the UNION ALL. (We must do that now because they
3286 : : * weren't previously referenced by the jointree, and so were missed by
3287 : : * the main invocation of pull_up_subqueries.)
3288 : : */
3289 : 674 : pull_up_union_leaf_queries((Node *) topop, root, leftmostRTI, parse, 0);
3290 : : }
3291 : :
3292 : :
3293 : : /*
3294 : : * reduce_outer_joins
3295 : : * Attempt to reduce outer joins to plain inner joins.
3296 : : *
3297 : : * The idea here is that given a query like
3298 : : * SELECT ... FROM a LEFT JOIN b ON (...) WHERE b.y = 42;
3299 : : * we can reduce the LEFT JOIN to a plain JOIN if the "=" operator in WHERE
3300 : : * is strict. The strict operator will always return NULL, causing the outer
3301 : : * WHERE to fail, on any row where the LEFT JOIN filled in NULLs for b's
3302 : : * columns. Therefore, there's no need for the join to produce null-extended
3303 : : * rows in the first place --- which makes it a plain join not an outer join.
3304 : : * (This scenario may not be very likely in a query written out by hand, but
3305 : : * it's reasonably likely when pushing quals down into complex views.)
3306 : : *
3307 : : * More generally, an outer join can be reduced in strength if there is a
3308 : : * strict qual above it in the qual tree that constrains a Var from the
3309 : : * nullable side of the join to be non-null. (For FULL joins this applies
3310 : : * to each side separately.)
3311 : : *
3312 : : * Another transformation we apply here is to recognize cases like
3313 : : * SELECT ... FROM a LEFT JOIN b ON (a.x = b.y) WHERE b.z IS NULL;
3314 : : * If we can prove that b.z must be non-null for any matching row, because
3315 : : * the join clause is strict for b.z and b.z happens to be the join key b.y,
3316 : : * because a strict qual within b's own subtree forces b.z non-null, or
3317 : : * because b.z is defined NOT NULL by table constraints and is not nullable
3318 : : * due to lower-level outer joins, then only null-extended rows could pass
3319 : : * the upper WHERE, and we can conclude that what the query is really
3320 : : * specifying is an anti-semijoin. We change the join type from JOIN_LEFT
3321 : : * to JOIN_ANTI. The IS NULL clause then becomes redundant, and is removed
3322 : : * at the end of this phase; see remove_redundant_nullability_quals.
3323 : : *
3324 : : * A whole-row Var works too. "WHERE b IS NULL" in row-format semantics is
3325 : : * true when b's whole-row value is NULL or when every column of b is NULL;
3326 : : * for a matching row only the latter is possible, so proving any one column
3327 : : * of b non-null in matching rows justifies the same reduction.
3328 : : *
3329 : : * The same recognition reduces a FULL join to an anti-semijoin when a
3330 : : * forced-null Var on either side is proven non-null: only the other side's
3331 : : * unmatched rows can survive. If that surviving side is the right-hand
3332 : : * input, we switch the inputs (as we do for JOIN_RIGHT below) so that it
3333 : : * ends up on the left, where JOIN_ANTI requires the surviving side to be.
3334 : : *
3335 : : * Also, we get rid of JOIN_RIGHT cases by flipping them around to become
3336 : : * JOIN_LEFT. This saves some code here and in some later planner routines;
3337 : : * the main benefit is to reduce the number of jointypes that can appear in
3338 : : * SpecialJoinInfo nodes. Note that we can still generate Paths and Plans
3339 : : * that use JOIN_RIGHT (or JOIN_RIGHT_ANTI) by switching the inputs again.
3340 : : *
3341 : : * To ease recognition of strict qual clauses, we require this routine to be
3342 : : * run after expression preprocessing (i.e., qual canonicalization and JOIN
3343 : : * alias-var expansion).
3344 : : */
3345 : : void
3346 : 33445 : reduce_outer_joins(PlannerInfo *root)
3347 : : {
3348 : : reduce_outer_joins_pass1_state *state1;
3349 : : reduce_outer_joins_pass2_state state2;
3350 : : ListCell *lc;
3351 : :
3352 : : /*
3353 : : * To avoid doing strictness checks on more quals than necessary, we want
3354 : : * to stop descending the jointree as soon as there are no outer joins
3355 : : * below our current point. This consideration forces a two-pass process.
3356 : : * The first pass gathers information about which base rels appear below
3357 : : * each side of each join clause, about whether there are outer join(s)
3358 : : * below each side of each join clause, and about which base rels are from
3359 : : * the nullable side of those outer join(s). The second pass examines
3360 : : * qual clauses and changes join types as it descends the tree.
3361 : : */
3362 : 33445 : state1 = reduce_outer_joins_pass1((Node *) root->parse->jointree);
3363 : :
3364 : : /* planner.c shouldn't have called me if no outer joins */
3365 [ + - - + ]: 33445 : if (state1 == NULL || !state1->contains_outer)
3366 [ # # ]: 0 : elog(ERROR, "so where are the outer joins?");
3367 : :
3368 : 33445 : state2.inner_reduced = NULL;
3369 : 33445 : state2.partial_reduced = NIL;
3370 : 33445 : state2.anti_reduced = NULL;
3371 : :
3372 : 33445 : reduce_outer_joins_pass2((Node *) root->parse->jointree,
3373 : : state1, &state2,
3374 : : root, NULL, NIL);
3375 : :
3376 : : /*
3377 : : * If we successfully reduced the strength of any outer joins, we must
3378 : : * remove references to those joins as nulling rels. This is handled as
3379 : : * an additional pass, for simplicity and because we can handle all
3380 : : * fully-reduced joins in a single pass over the parse tree.
3381 : : */
3382 [ + + ]: 33445 : if (!bms_is_empty(state2.inner_reduced))
3383 : : {
3384 : 2325 : root->parse = (Query *)
3385 : 2325 : remove_nulling_relids((Node *) root->parse,
3386 : 2325 : state2.inner_reduced,
3387 : : NULL);
3388 : : /* There could be references in the append_rel_list, too */
3389 : 2325 : root->append_rel_list = (List *)
3390 : 2325 : remove_nulling_relids((Node *) root->append_rel_list,
3391 : 2325 : state2.inner_reduced,
3392 : : NULL);
3393 : : }
3394 : :
3395 : : /*
3396 : : * Partially-reduced full joins have to be done one at a time, since
3397 : : * they'll each need a different setting of except_relids.
3398 : : */
3399 [ + + + + : 33569 : foreach(lc, state2.partial_reduced)
+ + ]
3400 : : {
3401 : 124 : reduce_outer_joins_partial_state *statep = lfirst(lc);
3402 : 124 : Relids full_join_relids = bms_make_singleton(statep->full_join_rti);
3403 : :
3404 : 124 : root->parse = (Query *)
3405 : 124 : remove_nulling_relids((Node *) root->parse,
3406 : : full_join_relids,
3407 : 124 : statep->unreduced_side);
3408 : 124 : root->append_rel_list = (List *)
3409 : 124 : remove_nulling_relids((Node *) root->append_rel_list,
3410 : : full_join_relids,
3411 : 124 : statep->unreduced_side);
3412 : : }
3413 : :
3414 : : /*
3415 : : * Finally, remove any quals made redundant by reducing outer joins to
3416 : : * antijoins.
3417 : : */
3418 [ + + ]: 33445 : if (!bms_is_empty(state2.anti_reduced))
3419 : 593 : remove_redundant_nullability_quals((Node *) root->parse->jointree,
3420 : : state2.anti_reduced);
3421 : 33445 : }
3422 : :
3423 : : /*
3424 : : * remove_redundant_nullability_quals
3425 : : * Remove quals made redundant by reducing outer joins to antijoins.
3426 : : *
3427 : : * An IS NULL qual on a Var from the nullable side of a lower antijoin is
3428 : : * necessarily true. Keeping such a qual would not be wrong, but it would
3429 : : * generate bogus selectivity estimates, and it could prevent join removal
3430 : : * from later removing the rel(s) it references.
3431 : : */
3432 : : static void
3433 : 2651 : remove_redundant_nullability_quals(Node *jtnode, Relids antijoins)
3434 : : {
3435 [ - + ]: 2651 : if (jtnode == NULL)
3436 : 0 : return;
3437 [ + + ]: 2651 : if (IsA(jtnode, RangeTblRef))
3438 : : {
3439 : : /* nothing to do here */
3440 : : }
3441 [ + + ]: 1328 : else if (IsA(jtnode, FromExpr))
3442 : : {
3443 : 603 : FromExpr *f = (FromExpr *) jtnode;
3444 : : ListCell *l;
3445 : :
3446 [ + - + + : 1211 : foreach(l, f->fromlist)
+ + ]
3447 : 608 : remove_redundant_nullability_quals(lfirst(l), antijoins);
3448 : 603 : f->quals = strip_redundant_nullability_quals(f->quals, antijoins);
3449 : : }
3450 [ + - ]: 725 : else if (IsA(jtnode, JoinExpr))
3451 : : {
3452 : 725 : JoinExpr *j = (JoinExpr *) jtnode;
3453 : :
3454 : 725 : remove_redundant_nullability_quals(j->larg, antijoins);
3455 : 725 : remove_redundant_nullability_quals(j->rarg, antijoins);
3456 : 725 : j->quals = strip_redundant_nullability_quals(j->quals, antijoins);
3457 : : }
3458 : : else
3459 [ # # ]: 0 : elog(ERROR, "unrecognized jointree node type: %d",
3460 : : (int) nodeTag(jtnode));
3461 : : }
3462 : :
3463 : : /*
3464 : : * strip_redundant_nullability_quals
3465 : : * Strip redundant IS NULL quals from one implicit-AND qual list.
3466 : : */
3467 : : static Node *
3468 : 1328 : strip_redundant_nullability_quals(Node *quals, Relids antijoins)
3469 : : {
3470 : 1328 : List *newquals = NIL;
3471 : :
3472 [ + + + + : 4614 : foreach_ptr(Node, clause, castNode(List, quals))
+ + ]
3473 : : {
3474 : 1958 : Var *var = find_forced_null_var(clause);
3475 : :
3476 [ + + + + ]: 1958 : if (var && bms_overlap(var->varnullingrels, antijoins))
3477 : 608 : continue;
3478 : 1350 : newquals = lappend(newquals, clause);
3479 : : }
3480 : 1328 : return (Node *) newquals;
3481 : : }
3482 : :
3483 : : /*
3484 : : * reduce_outer_joins_pass1 - phase 1 data collection
3485 : : *
3486 : : * Returns a state node describing the given jointree node.
3487 : : */
3488 : : static reduce_outer_joins_pass1_state *
3489 : 197957 : reduce_outer_joins_pass1(Node *jtnode)
3490 : : {
3491 : : reduce_outer_joins_pass1_state *result;
3492 : :
3493 : 197957 : result = palloc_object(reduce_outer_joins_pass1_state);
3494 : 197957 : result->relids = NULL;
3495 : 197957 : result->contains_outer = false;
3496 : 197957 : result->nullable_rels = NULL;
3497 : 197957 : result->jtnode = jtnode;
3498 : 197957 : result->sub_states = NIL;
3499 : :
3500 [ - + ]: 197957 : if (jtnode == NULL)
3501 : 0 : return result;
3502 [ + + ]: 197957 : if (IsA(jtnode, RangeTblRef))
3503 : : {
3504 : 95535 : int varno = ((RangeTblRef *) jtnode)->rtindex;
3505 : :
3506 : 95535 : result->relids = bms_make_singleton(varno);
3507 : : }
3508 [ + + ]: 102422 : else if (IsA(jtnode, FromExpr))
3509 : : {
3510 : 43705 : FromExpr *f = (FromExpr *) jtnode;
3511 : : ListCell *l;
3512 : :
3513 [ + - + + : 90783 : foreach(l, f->fromlist)
+ + ]
3514 : : {
3515 : : reduce_outer_joins_pass1_state *sub_state;
3516 : :
3517 : 47078 : sub_state = reduce_outer_joins_pass1(lfirst(l));
3518 : 94156 : result->relids = bms_add_members(result->relids,
3519 : 47078 : sub_state->relids);
3520 : 47078 : result->contains_outer |= sub_state->contains_outer;
3521 : 94156 : result->nullable_rels = bms_add_members(result->nullable_rels,
3522 : 47078 : sub_state->nullable_rels);
3523 : 47078 : result->sub_states = lappend(result->sub_states, sub_state);
3524 : : }
3525 : : }
3526 [ + - ]: 58717 : else if (IsA(jtnode, JoinExpr))
3527 : : {
3528 : 58717 : JoinExpr *j = (JoinExpr *) jtnode;
3529 : : reduce_outer_joins_pass1_state *left_state;
3530 : : reduce_outer_joins_pass1_state *right_state;
3531 : :
3532 : : /* Recurse to children */
3533 : 58717 : left_state = reduce_outer_joins_pass1(j->larg);
3534 : 58717 : right_state = reduce_outer_joins_pass1(j->rarg);
3535 : :
3536 : : /* join's own RT index is not wanted in result->relids */
3537 : 58717 : result->relids = bms_union(left_state->relids, right_state->relids);
3538 : :
3539 : : /* Store children's states for pass 2 */
3540 : 58717 : result->sub_states = list_make2(left_state, right_state);
3541 : :
3542 : : /* Collect outer join information */
3543 [ + + + + : 58717 : switch (j->jointype)
- ]
3544 : : {
3545 : 13163 : case JOIN_INNER:
3546 : : case JOIN_SEMI:
3547 : : /* No new nullability; propagate state from children */
3548 [ + + ]: 25617 : result->contains_outer = left_state->contains_outer ||
3549 [ + + ]: 12454 : right_state->contains_outer;
3550 : 26326 : result->nullable_rels = bms_union(left_state->nullable_rels,
3551 : 13163 : right_state->nullable_rels);
3552 : 13163 : break;
3553 : 43314 : case JOIN_LEFT:
3554 : : case JOIN_ANTI:
3555 : : /* RHS is nullable; LHS keeps existing status */
3556 : 43314 : result->contains_outer = true;
3557 : 86628 : result->nullable_rels = bms_union(left_state->nullable_rels,
3558 : 43314 : right_state->relids);
3559 : 43314 : break;
3560 : 1065 : case JOIN_RIGHT:
3561 : : /* LHS is nullable; RHS keeps existing status */
3562 : 1065 : result->contains_outer = true;
3563 : 2130 : result->nullable_rels = bms_union(left_state->relids,
3564 : 1065 : right_state->nullable_rels);
3565 : 1065 : break;
3566 : 1175 : case JOIN_FULL:
3567 : : /* Both sides are nullable */
3568 : 1175 : result->contains_outer = true;
3569 : 2350 : result->nullable_rels = bms_union(left_state->relids,
3570 : 1175 : right_state->relids);
3571 : 1175 : break;
3572 : 0 : default:
3573 [ # # ]: 0 : elog(ERROR, "unrecognized join type: %d",
3574 : : (int) j->jointype);
3575 : : break;
3576 : : }
3577 : : }
3578 : : else
3579 [ # # ]: 0 : elog(ERROR, "unrecognized node type: %d",
3580 : : (int) nodeTag(jtnode));
3581 : 197957 : return result;
3582 : : }
3583 : :
3584 : : /*
3585 : : * reduce_outer_joins_pass2 - phase 2 processing
3586 : : *
3587 : : * jtnode: current jointree node
3588 : : * state1: state data collected by phase 1 for this node
3589 : : * state2: where to accumulate info about successfully-reduced joins
3590 : : * root: toplevel planner state
3591 : : * nonnullable_rels: set of base relids forced non-null by upper quals
3592 : : * forced_null_vars: multibitmapset of Vars forced null by upper quals
3593 : : *
3594 : : * Returns info in state2 about outer joins that were successfully simplified.
3595 : : * Joins that were fully reduced to inner joins are all added to
3596 : : * state2->inner_reduced, and joins that became antijoins are all added to
3597 : : * state2->anti_reduced. If a full join is reduced to a left join or an
3598 : : * antijoin, it also needs its own entry in state2->partial_reduced, since
3599 : : * that will require custom processing to remove only the correct nullingrel
3600 : : * markers.
3601 : : */
3602 : : static void
3603 : 80945 : reduce_outer_joins_pass2(Node *jtnode,
3604 : : reduce_outer_joins_pass1_state *state1,
3605 : : reduce_outer_joins_pass2_state *state2,
3606 : : PlannerInfo *root,
3607 : : Relids nonnullable_rels,
3608 : : List *forced_null_vars)
3609 : : {
3610 : : /*
3611 : : * pass 2 should never descend as far as an empty subnode or base rel,
3612 : : * because it's only called on subtrees marked as contains_outer.
3613 : : */
3614 [ - + ]: 80945 : if (jtnode == NULL)
3615 [ # # ]: 0 : elog(ERROR, "reached empty jointree");
3616 [ - + ]: 80945 : if (IsA(jtnode, RangeTblRef))
3617 [ # # ]: 0 : elog(ERROR, "reached base rel");
3618 [ + + ]: 80945 : else if (IsA(jtnode, FromExpr))
3619 : : {
3620 : 34547 : FromExpr *f = (FromExpr *) jtnode;
3621 : : ListCell *l;
3622 : : ListCell *s;
3623 : : Relids pass_nonnullable_rels;
3624 : : List *pass_forced_null_vars;
3625 : :
3626 : : /* Scan quals to see if we can add any constraints */
3627 : 34547 : pass_nonnullable_rels = find_nonnullable_rels(f->quals);
3628 : 34547 : pass_nonnullable_rels = bms_add_members(pass_nonnullable_rels,
3629 : : nonnullable_rels);
3630 : 34547 : pass_forced_null_vars = find_forced_null_vars(f->quals);
3631 : 34547 : pass_forced_null_vars = mbms_add_members(pass_forced_null_vars,
3632 : : forced_null_vars);
3633 : : /* And recurse --- but only into interesting subtrees */
3634 : : Assert(list_length(f->fromlist) == list_length(state1->sub_states));
3635 [ + - + + : 71481 : forboth(l, f->fromlist, s, state1->sub_states)
+ - + + +
+ + - +
+ ]
3636 : : {
3637 : 36934 : reduce_outer_joins_pass1_state *sub_state = lfirst(s);
3638 : :
3639 [ + + ]: 36934 : if (sub_state->contains_outer)
3640 : 34592 : reduce_outer_joins_pass2(lfirst(l), sub_state,
3641 : : state2, root,
3642 : : pass_nonnullable_rels,
3643 : : pass_forced_null_vars);
3644 : : }
3645 : 34547 : bms_free(pass_nonnullable_rels);
3646 : : /* can't so easily clean up var lists, unfortunately */
3647 : : }
3648 [ + - ]: 46398 : else if (IsA(jtnode, JoinExpr))
3649 : : {
3650 : 46398 : JoinExpr *j = (JoinExpr *) jtnode;
3651 : 46398 : int rtindex = j->rtindex;
3652 : 46398 : JoinType jointype = j->jointype;
3653 : 46398 : reduce_outer_joins_pass1_state *left_state = linitial(state1->sub_states);
3654 : 46398 : reduce_outer_joins_pass1_state *right_state = lsecond(state1->sub_states);
3655 : :
3656 : : /* Can we simplify this join? */
3657 [ + + + + : 46398 : switch (jointype)
+ - ]
3658 : : {
3659 : 781 : case JOIN_INNER:
3660 : 781 : break;
3661 : 35743 : case JOIN_LEFT:
3662 [ + + ]: 35743 : if (bms_overlap(nonnullable_rels, right_state->relids))
3663 : 2606 : jointype = JOIN_INNER;
3664 : 35743 : break;
3665 : 1065 : case JOIN_RIGHT:
3666 [ + + ]: 1065 : if (bms_overlap(nonnullable_rels, left_state->relids))
3667 : 69 : jointype = JOIN_INNER;
3668 : 1065 : break;
3669 : 1175 : case JOIN_FULL:
3670 [ + + ]: 1175 : if (bms_overlap(nonnullable_rels, left_state->relids))
3671 : : {
3672 [ + + ]: 35 : if (bms_overlap(nonnullable_rels, right_state->relids))
3673 : 10 : jointype = JOIN_INNER;
3674 : : else
3675 : : {
3676 : 25 : jointype = JOIN_LEFT;
3677 : : /* Also report partial reduction in state2 */
3678 : 25 : report_reduced_full_join(state2, rtindex,
3679 : : right_state->relids);
3680 : : }
3681 : : }
3682 [ + + ]: 1140 : else if (bms_overlap(nonnullable_rels, right_state->relids))
3683 : : {
3684 : 34 : jointype = JOIN_RIGHT;
3685 : : /* Also report partial reduction in state2 */
3686 : 34 : report_reduced_full_join(state2, rtindex,
3687 : : left_state->relids);
3688 : : }
3689 [ + + ]: 1106 : else if (forced_null_vars != NIL)
3690 : : {
3691 : : /*
3692 : : * Neither side is forced non-null by a strict upper qual,
3693 : : * but an upper qual may force a Var on one side to be
3694 : : * NULL while that Var is non-null in every row that side
3695 : : * emits (proven by quals within the side's own subtree,
3696 : : * or a NOT NULL constraint). Then only rows where that
3697 : : * side was null-extended can satisfy the upper qual: the
3698 : : * matched rows and that side's unmatched rows all drop
3699 : : * out, leaving an anti-join.
3700 : : *
3701 : : * Unlike the JOIN_LEFT case below, we must not consult
3702 : : * the join's own ON quals here: they do not hold for the
3703 : : * unmatched rows that this proof has to cover.
3704 : : *
3705 : : * If the constrained Var is on the RHS the result is a
3706 : : * plain anti-join; if it is on the LHS it is a right
3707 : : * anti-join, which the input-switching step below
3708 : : * normalizes to a plain anti-join (just as it does for
3709 : : * JOIN_RIGHT).
3710 : : */
3711 [ + + ]: 85 : if (forced_null_var_is_nonnullable(root,
3712 : : forced_null_vars,
3713 : : right_state, NIL))
3714 : : {
3715 : 45 : jointype = JOIN_ANTI;
3716 : 45 : report_reduced_full_join(state2, rtindex,
3717 : : right_state->relids);
3718 : : }
3719 [ + + ]: 40 : else if (forced_null_var_is_nonnullable(root,
3720 : : forced_null_vars,
3721 : : left_state, NIL))
3722 : : {
3723 : 20 : jointype = JOIN_RIGHT_ANTI;
3724 : 20 : report_reduced_full_join(state2, rtindex,
3725 : : left_state->relids);
3726 : : }
3727 : : }
3728 : 1175 : break;
3729 : 7634 : case JOIN_SEMI:
3730 : : case JOIN_ANTI:
3731 : :
3732 : : /*
3733 : : * These could only have been introduced by pull_up_sublinks,
3734 : : * so there's no way that upper quals could refer to their
3735 : : * righthand sides, and no point in checking. We don't expect
3736 : : * a JOIN_RIGHT_SEMI or JOIN_RIGHT_ANTI input here; the
3737 : : * JOIN_FULL case above produces JOIN_RIGHT_ANTI only as a
3738 : : * transient, which is converted to JOIN_ANTI below.
3739 : : */
3740 : 7634 : break;
3741 : 0 : default:
3742 [ # # ]: 0 : elog(ERROR, "unrecognized join type: %d",
3743 : : (int) jointype);
3744 : : break;
3745 : : }
3746 : :
3747 : : /*
3748 : : * Convert JOIN_RIGHT to JOIN_LEFT, and likewise the JOIN_RIGHT_ANTI
3749 : : * that the JOIN_FULL arm may have produced just above to JOIN_ANTI,
3750 : : * by switching the inputs. Note that in the case where we reduced
3751 : : * JOIN_FULL this way, this will mean the JoinExpr no longer matches
3752 : : * the internal ordering of any CoalesceExpr's built to represent
3753 : : * merged join variables. We don't care about that at present, but be
3754 : : * wary of it ...
3755 : : */
3756 [ + + + + ]: 46398 : if (jointype == JOIN_RIGHT || jointype == JOIN_RIGHT_ANTI)
3757 : : {
3758 : : Node *tmparg;
3759 : :
3760 : 1050 : tmparg = j->larg;
3761 : 1050 : j->larg = j->rarg;
3762 : 1050 : j->rarg = tmparg;
3763 [ + + ]: 1050 : jointype = (jointype == JOIN_RIGHT) ? JOIN_LEFT : JOIN_ANTI;
3764 : 1050 : right_state = linitial(state1->sub_states);
3765 : 1050 : left_state = lsecond(state1->sub_states);
3766 : : }
3767 : :
3768 : : /*
3769 : : * See if we can reduce JOIN_LEFT to JOIN_ANTI. This is the case if
3770 : : * any var from the RHS was forced null by higher qual levels, but is
3771 : : * known to be non-nullable in any matching row. We can prove that in
3772 : : * any of these ways: the join's own quals are strict for the var;
3773 : : * strict quals applied within the RHS subtree prove it; or the var is
3774 : : * defined NOT NULL by table constraints (being careful to exclude
3775 : : * vars that are nullable due to lower-level outer joins). In each
3776 : : * such case, the only way the higher qual clause's requirement for
3777 : : * NULL can be met is if the join fails to match, producing a
3778 : : * null-extended row. Thus, we can treat this as an anti-join.
3779 : : */
3780 [ + + + + ]: 46398 : if (jointype == JOIN_LEFT && forced_null_vars != NIL)
3781 : : {
3782 : : /*
3783 : : * A forced-null RHS Var that is proven non-null can be NULL here
3784 : : * only by null-extension. That makes this an anti-join.
3785 : : */
3786 [ + + ]: 712 : if (forced_null_var_is_nonnullable(root, forced_null_vars,
3787 : 712 : right_state, (List *) j->quals))
3788 : 528 : jointype = JOIN_ANTI;
3789 : : }
3790 : :
3791 : : /*
3792 : : * Apply the jointype change, if any, to both jointree node and RTE.
3793 : : * Also, if we changed an RTE to INNER, add its RTI to inner_reduced;
3794 : : * if we changed it to ANTI, add its RTI to anti_reduced.
3795 : : */
3796 [ + + + + ]: 46398 : if (rtindex && jointype != j->jointype)
3797 : : {
3798 : 4333 : RangeTblEntry *rte = rt_fetch(rtindex, root->parse->rtable);
3799 : :
3800 : : Assert(rte->rtekind == RTE_JOIN);
3801 : : Assert(rte->jointype == j->jointype);
3802 : 4333 : rte->jointype = jointype;
3803 [ + + ]: 4333 : if (jointype == JOIN_INNER)
3804 : 2685 : state2->inner_reduced = bms_add_member(state2->inner_reduced,
3805 : : rtindex);
3806 [ + + ]: 1648 : else if (jointype == JOIN_ANTI)
3807 : 593 : state2->anti_reduced = bms_add_member(state2->anti_reduced,
3808 : : rtindex);
3809 : : }
3810 : 46398 : j->jointype = jointype;
3811 : :
3812 : : /* Only recurse if there's more to do below here */
3813 [ + + + + ]: 46398 : if (left_state->contains_outer || right_state->contains_outer)
3814 : : {
3815 : : Relids local_nonnullable_rels;
3816 : : List *local_forced_null_vars;
3817 : : Relids pass_nonnullable_rels;
3818 : : List *pass_forced_null_vars;
3819 : :
3820 : : /*
3821 : : * If this join is (now) inner, we can add any constraints its
3822 : : * quals provide to those we got from above. But if it is outer,
3823 : : * we can pass down the local constraints only into the nullable
3824 : : * side, because an outer join never eliminates any rows from its
3825 : : * non-nullable side. Also, there is no point in passing upper
3826 : : * constraints into the nullable side, since if there were any
3827 : : * we'd have been able to reduce the join. (In the case of upper
3828 : : * forced-null constraints, we *must not* pass them into the
3829 : : * nullable side --- they either applied here, or not.) The upshot
3830 : : * is that we pass either the local or the upper constraints,
3831 : : * never both, to the children of an outer join.
3832 : : *
3833 : : * Note that a SEMI join works like an inner join here: it's okay
3834 : : * to pass down both local and upper constraints. (There can't be
3835 : : * any upper constraints affecting its inner side, but it's not
3836 : : * worth having a separate code path to avoid passing them.)
3837 : : *
3838 : : * At a FULL join we just punt and pass nothing down --- is it
3839 : : * possible to be smarter?
3840 : : */
3841 [ + + ]: 12839 : if (jointype != JOIN_FULL)
3842 : : {
3843 : 12686 : local_nonnullable_rels = find_nonnullable_rels(j->quals);
3844 : 12686 : local_forced_null_vars = find_forced_null_vars(j->quals);
3845 [ + + + + ]: 12686 : if (jointype == JOIN_INNER || jointype == JOIN_SEMI)
3846 : : {
3847 : : /* OK to merge upper and local constraints */
3848 : 1722 : local_nonnullable_rels = bms_add_members(local_nonnullable_rels,
3849 : : nonnullable_rels);
3850 : 1722 : local_forced_null_vars = mbms_add_members(local_forced_null_vars,
3851 : : forced_null_vars);
3852 : : }
3853 : : }
3854 : : else
3855 : : {
3856 : : /* no use in calculating these */
3857 : 153 : local_nonnullable_rels = NULL;
3858 : 153 : local_forced_null_vars = NIL;
3859 : : }
3860 : :
3861 [ + + ]: 12839 : if (left_state->contains_outer)
3862 : : {
3863 [ + + + + ]: 11964 : if (jointype == JOIN_INNER || jointype == JOIN_SEMI)
3864 : : {
3865 : : /* pass union of local and upper constraints */
3866 : 1501 : pass_nonnullable_rels = local_nonnullable_rels;
3867 : 1501 : pass_forced_null_vars = local_forced_null_vars;
3868 : : }
3869 [ + + ]: 10463 : else if (jointype != JOIN_FULL) /* ie, LEFT or ANTI */
3870 : : {
3871 : : /* can't pass local constraints to non-nullable side */
3872 : 10343 : pass_nonnullable_rels = nonnullable_rels;
3873 : 10343 : pass_forced_null_vars = forced_null_vars;
3874 : : }
3875 : : else
3876 : : {
3877 : : /* no constraints pass through JOIN_FULL */
3878 : 120 : pass_nonnullable_rels = NULL;
3879 : 120 : pass_forced_null_vars = NIL;
3880 : : }
3881 : 11964 : reduce_outer_joins_pass2(j->larg, left_state,
3882 : : state2, root,
3883 : : pass_nonnullable_rels,
3884 : : pass_forced_null_vars);
3885 : : }
3886 : :
3887 [ + + ]: 12839 : if (right_state->contains_outer)
3888 : : {
3889 [ + + ]: 944 : if (jointype != JOIN_FULL) /* ie, INNER/LEFT/SEMI/ANTI */
3890 : : {
3891 : : /* pass appropriate constraints, per comment above */
3892 : 911 : pass_nonnullable_rels = local_nonnullable_rels;
3893 : 911 : pass_forced_null_vars = local_forced_null_vars;
3894 : : }
3895 : : else
3896 : : {
3897 : : /* no constraints pass through JOIN_FULL */
3898 : 33 : pass_nonnullable_rels = NULL;
3899 : 33 : pass_forced_null_vars = NIL;
3900 : : }
3901 : 944 : reduce_outer_joins_pass2(j->rarg, right_state,
3902 : : state2, root,
3903 : : pass_nonnullable_rels,
3904 : : pass_forced_null_vars);
3905 : : }
3906 : 12839 : bms_free(local_nonnullable_rels);
3907 : : }
3908 : : }
3909 : : else
3910 [ # # ]: 0 : elog(ERROR, "unrecognized node type: %d",
3911 : : (int) nodeTag(jtnode));
3912 : 80945 : }
3913 : :
3914 : : /* Helper for reduce_outer_joins_pass2 */
3915 : : static void
3916 : 124 : report_reduced_full_join(reduce_outer_joins_pass2_state *state2,
3917 : : int rtindex, Relids relids)
3918 : : {
3919 : : reduce_outer_joins_partial_state *statep;
3920 : :
3921 : 124 : statep = palloc_object(reduce_outer_joins_partial_state);
3922 : 124 : statep->full_join_rti = rtindex;
3923 : 124 : statep->unreduced_side = relids;
3924 : 124 : state2->partial_reduced = lappend(state2->partial_reduced, statep);
3925 : 124 : }
3926 : :
3927 : : /*
3928 : : * forced_null_var_is_attnotnull
3929 : : * Check if "forced_null_vars" contains any Vars belonging to the subtree
3930 : : * indicated by "state" that are known to be non-nullable due to table
3931 : : * constraints.
3932 : : *
3933 : : * A whole-row Var, in any matching row, requires every column of its relation
3934 : : * to be NULL, so any NOT NULL column of the relation refutes it.
3935 : : *
3936 : : * Note that we must also consider the situation where a NOT NULL Var can be
3937 : : * nulled by lower-level outer joins.
3938 : : *
3939 : : * Helper for reduce_outer_joins_pass2.
3940 : : */
3941 : : static bool
3942 : 324 : forced_null_var_is_attnotnull(PlannerInfo *root, List *forced_null_vars,
3943 : : reduce_outer_joins_pass1_state *state)
3944 : : {
3945 : 324 : int varno = -1;
3946 : :
3947 [ + - + + : 1946 : foreach_node(Bitmapset, attrs, forced_null_vars)
+ + ]
3948 : : {
3949 : : RangeTblEntry *rte;
3950 : : Bitmapset *notnullattnums;
3951 : : Bitmapset *forcednullattnums;
3952 : 1458 : bool wholerow = false;
3953 : : int lowest_attno;
3954 : :
3955 : 1458 : varno++;
3956 : :
3957 : : /* Skip empty bitmaps */
3958 [ + + ]: 1458 : if (bms_is_empty(attrs))
3959 : 1129 : continue;
3960 : :
3961 : : /* Skip Vars that do not belong to the target relations */
3962 [ + + ]: 329 : if (!bms_is_member(varno, state->relids))
3963 : 115 : continue;
3964 : :
3965 : : /*
3966 : : * Skip Vars that can be nulled by lower-level outer joins within the
3967 : : * given subtree. These Vars might be NULL even if the schema defines
3968 : : * them as NOT NULL.
3969 : : */
3970 [ + + ]: 214 : if (bms_is_member(varno, state->nullable_rels))
3971 : 25 : continue;
3972 : :
3973 : : /* find the lowest member to check if system columns are present */
3974 : 189 : lowest_attno = bms_next_member(attrs, -1);
3975 : :
3976 : : /* we checked for an empty set above */
3977 : : Assert(lowest_attno >= 0);
3978 : :
3979 : : /* system columns cannot be NULL */
3980 [ - + ]: 189 : if (lowest_attno + FirstLowInvalidHeapAttributeNumber < 0)
3981 : 80 : return true;
3982 : :
3983 : : /* attno 0 is a whole-row Var, which forces every column null */
3984 [ + + ]: 189 : if (lowest_attno + FirstLowInvalidHeapAttributeNumber == 0)
3985 : 40 : wholerow = true;
3986 : :
3987 : 189 : rte = rt_fetch(varno, root->parse->rtable);
3988 : :
3989 : : /* We can only reason about ordinary relations */
3990 [ + + ]: 189 : if (rte->rtekind != RTE_RELATION)
3991 : 34 : continue;
3992 : :
3993 : : /*
3994 : : * We must skip inheritance parent tables, as some child tables may
3995 : : * have a NOT NULL constraint for a column while others may not. This
3996 : : * cannot happen with partitioned tables, though.
3997 : : */
3998 [ - + - - ]: 155 : if (rte->inh && rte->relkind != RELKIND_PARTITIONED_TABLE)
3999 : 0 : continue;
4000 : :
4001 : : /* Get the column not-null constraint information for this relation */
4002 : 155 : notnullattnums = find_relation_notnullatts(root, rte->relid);
4003 : :
4004 : : /*
4005 : : * A forced-null whole-row Var, in any matching row, requires every
4006 : : * column of the relation to be NULL, so any NOT NULL column refutes
4007 : : * it.
4008 : : */
4009 [ + + + + ]: 155 : if (wholerow && !bms_is_empty(notnullattnums))
4010 : 10 : return true;
4011 : :
4012 : : /*
4013 : : * Offset the bitmap members by FirstLowInvalidHeapAttributeNumber to
4014 : : * get the actual attribute numbers.
4015 : : */
4016 : 145 : forcednullattnums = bms_offset_members(attrs,
4017 : : FirstLowInvalidHeapAttributeNumber);
4018 : :
4019 : : /*
4020 : : * Check if any forced-null attributes are defined as NOT NULL by
4021 : : * table constraints.
4022 : : */
4023 [ + + ]: 145 : if (bms_overlap(notnullattnums, forcednullattnums))
4024 : : {
4025 : 70 : bms_free(forcednullattnums);
4026 : 70 : return true;
4027 : : }
4028 : :
4029 : 75 : bms_free(forcednullattnums);
4030 : : }
4031 : :
4032 : 244 : return false;
4033 : : }
4034 : :
4035 : : /*
4036 : : * forced_null_var_is_nonnullable
4037 : : * Detect whether some Var that "forced_null_vars" requires to be NULL is
4038 : : * actually non-nullable in every row that the given subtree emits.
4039 : : *
4040 : : * We prove non-nullness from quals that hold for every such row: the subtree's
4041 : : * safe quals, plus any "extra_quals" the caller knows also constrain the Var,
4042 : : * or a NOT NULL table constraint (excluding Vars nullable due to lower-level
4043 : : * outer joins).
4044 : : *
4045 : : * A whole-row Var in "forced_null_vars" requires, in any matching row, every
4046 : : * column of its relation to be NULL, so it is refuted by proving any one of
4047 : : * those columns non-null.
4048 : : *
4049 : : * Helper for reduce_outer_joins_pass2.
4050 : : */
4051 : : static bool
4052 : 837 : forced_null_var_is_nonnullable(PlannerInfo *root, List *forced_null_vars,
4053 : : reduce_outer_joins_pass1_state *state,
4054 : : List *extra_quals)
4055 : : {
4056 : 837 : List *all_quals = NIL;
4057 : : List *nonnullable_vars;
4058 : 837 : int wholerow_attno = 0 - FirstLowInvalidHeapAttributeNumber;
4059 : 837 : int varno = -1;
4060 : :
4061 : 837 : find_safe_quals(state->jtnode, &all_quals);
4062 : 837 : all_quals = list_concat(all_quals, extra_quals);
4063 : 837 : nonnullable_vars = find_nonnullable_vars((Node *) all_quals);
4064 : :
4065 : : /*
4066 : : * It's not sufficient to consider all matches between nonnullable_vars
4067 : : * and forced_null_vars: a match counts only for a Var belonging to this
4068 : : * subtree, and the whole-row attribute needs special treatment.
4069 : : */
4070 [ + - + + : 3123 : foreach_node(Bitmapset, attrs, forced_null_vars)
+ + ]
4071 : : {
4072 : : Bitmapset *nonnull_attrs;
4073 : :
4074 : 2681 : varno++;
4075 : :
4076 : : /* Beyond the end of nonnullable_vars there is nothing left to prove */
4077 [ + + ]: 2681 : if (varno >= list_length(nonnullable_vars))
4078 : 206 : break;
4079 : :
4080 : : /* Skip empty bitmaps */
4081 [ + + ]: 2475 : if (bms_is_empty(attrs))
4082 : 1844 : continue;
4083 : :
4084 : : /* Skip Vars that do not belong to the target relations */
4085 [ + + ]: 631 : if (!bms_is_member(varno, state->relids))
4086 : 44 : continue;
4087 : :
4088 : : /* Get what the quals prove non-null for this relation, if anything */
4089 : 587 : nonnull_attrs = list_nth_node(Bitmapset, nonnullable_vars, varno);
4090 : :
4091 : : /*
4092 : : * A proof for the whole-row attribute refutes nothing: it shows only
4093 : : * that the composite datum is non-null, and such a datum can still
4094 : : * have all columns NULL. Discard it up front.
4095 : : */
4096 : 587 : nonnull_attrs = bms_del_member(nonnull_attrs, wholerow_attno);
4097 : :
4098 : : /* A forced-null attribute that is proven non-null settles it. */
4099 [ + + ]: 587 : if (bms_overlap(attrs, nonnull_attrs))
4100 : 513 : return true;
4101 : :
4102 : : /*
4103 : : * So does any real column proven non-null, if the whole-row Var is
4104 : : * forced null: in a matching row (whose whole-row datum is non-null)
4105 : : * the row-format IS NULL test is true only when every column is NULL.
4106 : : * System attributes don't count, since they are not part of the row
4107 : : * value; conveniently they sort below the whole-row attribute in the
4108 : : * bitmap.
4109 : : */
4110 [ + + + + ]: 124 : if (bms_is_member(wholerow_attno, attrs) &&
4111 : 35 : bms_next_member(nonnull_attrs, wholerow_attno) >= 0)
4112 : 15 : return true;
4113 : : }
4114 : :
4115 : : /*
4116 : : * Otherwise, check if any forced-null var is defined NOT NULL by table
4117 : : * constraints.
4118 : : */
4119 : 324 : return forced_null_var_is_attnotnull(root, forced_null_vars, state);
4120 : : }
4121 : :
4122 : :
4123 : : /*
4124 : : * remove_useless_result_rtes
4125 : : * Attempt to remove RTE_RESULT RTEs from the join tree.
4126 : : * Also, elide single-child FromExprs where possible.
4127 : : *
4128 : : * We can remove RTE_RESULT entries from the join tree using the knowledge
4129 : : * that RTE_RESULT returns exactly one row and has no output columns. Hence,
4130 : : * if one is inner-joined to anything else, we can delete it. Optimizations
4131 : : * are also possible for some outer-join cases, as detailed below.
4132 : : *
4133 : : * This pass also replaces single-child FromExprs with their child node
4134 : : * where possible. It's appropriate to do that here and not earlier because
4135 : : * RTE_RESULT removal might reduce a multiple-child FromExpr to have only one
4136 : : * child. We can remove such a FromExpr if its quals are empty, or if it's
4137 : : * semantically valid to merge the quals into those of the parent node.
4138 : : * While removing unnecessary join tree nodes has some micro-efficiency value,
4139 : : * the real reason to do this is to eliminate cases where the nullable side of
4140 : : * an outer join node is a FromExpr whose single child is another outer join.
4141 : : * To correctly determine whether the two outer joins can commute,
4142 : : * deconstruct_jointree() must treat any quals of such a FromExpr as being
4143 : : * degenerate quals of the upper outer join. The best way to do that is to
4144 : : * make them actually *be* quals of the upper join, by dropping the FromExpr
4145 : : * and hoisting the quals up into the upper join's quals. (Note that there is
4146 : : * no hazard when the intermediate FromExpr has multiple children, since then
4147 : : * it represents an inner join that cannot commute with the upper outer join.)
4148 : : * As long as we have to do that, we might as well elide such FromExprs
4149 : : * everywhere.
4150 : : *
4151 : : * Some of these optimizations depend on recognizing empty (constant-true)
4152 : : * quals for FromExprs and JoinExprs. That makes it useful to apply this
4153 : : * optimization pass after expression preprocessing, since that will have
4154 : : * eliminated constant-true quals, allowing more cases to be recognized as
4155 : : * optimizable. What's more, the usual reason for an RTE_RESULT to be present
4156 : : * is that we pulled up a subquery or VALUES clause, thus very possibly
4157 : : * replacing Vars with constants, making it more likely that a qual can be
4158 : : * reduced to constant true. Also, because some optimizations depend on
4159 : : * the outer-join type, it's best to have done reduce_outer_joins() first.
4160 : : *
4161 : : * A PlaceHolderVar referencing an RTE_RESULT RTE poses an obstacle to this
4162 : : * process: we must remove the RTE_RESULT's relid from the PHV's phrels, but
4163 : : * we must not reduce the phrels set to empty. If that would happen, and
4164 : : * the RTE_RESULT is an immediate child of an outer join, we have to give up
4165 : : * and not remove the RTE_RESULT: there is noplace else to evaluate the
4166 : : * PlaceHolderVar. (That is, in such cases the RTE_RESULT *does* have output
4167 : : * columns.) But if the RTE_RESULT is an immediate child of an inner join,
4168 : : * we can usually change the PlaceHolderVar's phrels so as to evaluate it at
4169 : : * the inner join instead. This is OK because we really only care that PHVs
4170 : : * are evaluated above or below the correct outer joins. We can't, however,
4171 : : * postpone the evaluation of a PHV to above where it is used; so there are
4172 : : * some checks below on whether output PHVs are laterally referenced in the
4173 : : * other join input rel(s).
4174 : : *
4175 : : * We used to try to do this work as part of pull_up_subqueries() where the
4176 : : * potentially-optimizable cases get introduced; but it's way simpler, and
4177 : : * more effective, to do it separately.
4178 : : */
4179 : : void
4180 : 183536 : remove_useless_result_rtes(PlannerInfo *root)
4181 : : {
4182 : 183536 : Relids baserels = NULL;
4183 : 183536 : Relids dropped_outer_joins = NULL;
4184 : : ListCell *cell;
4185 : :
4186 : : /*
4187 : : * We'll need the set of baserels in the jointree to perform
4188 : : * find_dependent_phvs() checks. But if there are no PHVs anywhere in the
4189 : : * query, those checks are no-ops, so we can skip the work.
4190 : : */
4191 [ + + ]: 183536 : if (root->glob->lastPHId != 0)
4192 : 1907 : baserels = get_relids_in_jointree((Node *) root->parse->jointree,
4193 : : false, false);
4194 : :
4195 : : /* Top level of jointree must always be a FromExpr */
4196 : : Assert(IsA(root->parse->jointree, FromExpr));
4197 : : /* Recurse ... */
4198 : 367072 : root->parse->jointree = (FromExpr *)
4199 : 183536 : remove_useless_results_recurse(root,
4200 : 183536 : (Node *) root->parse->jointree,
4201 : : baserels,
4202 : : NULL,
4203 : : &dropped_outer_joins);
4204 : : /* We should still have a FromExpr */
4205 : : Assert(IsA(root->parse->jointree, FromExpr));
4206 : :
4207 : : /*
4208 : : * If we removed any outer-join nodes from the jointree, run around and
4209 : : * remove references to those joins as nulling rels. (There could be such
4210 : : * references in PHVs that we pulled up out of the original subquery that
4211 : : * the RESULT rel replaced. This is kosher on the grounds that we now
4212 : : * know that such an outer join wouldn't really have nulled anything.) We
4213 : : * don't do this during the main recursion, for simplicity and because we
4214 : : * can handle all such joins in a single pass over the parse tree.
4215 : : */
4216 [ + + ]: 183536 : if (!bms_is_empty(dropped_outer_joins))
4217 : : {
4218 : 75 : root->parse = (Query *)
4219 : 75 : remove_nulling_relids((Node *) root->parse,
4220 : : dropped_outer_joins,
4221 : : NULL);
4222 : : /* There could be references in the append_rel_list, too */
4223 : 75 : root->append_rel_list = (List *)
4224 : 75 : remove_nulling_relids((Node *) root->append_rel_list,
4225 : : dropped_outer_joins,
4226 : : NULL);
4227 : : }
4228 : :
4229 : : /*
4230 : : * Remove any PlanRowMark referencing an RTE_RESULT RTE. We obviously
4231 : : * must do that for any RTE_RESULT that we just removed. But one for a
4232 : : * RTE that we did not remove can be dropped anyway: since the RTE has
4233 : : * only one possible output row, there is no need for EPQ to mark and
4234 : : * restore that row.
4235 : : *
4236 : : * It's necessary, not optional, to remove the PlanRowMark for a surviving
4237 : : * RTE_RESULT RTE; otherwise we'll generate a whole-row Var for the
4238 : : * RTE_RESULT, which the executor has no support for.
4239 : : */
4240 [ + + + + : 185239 : foreach(cell, root->rowMarks)
+ + ]
4241 : : {
4242 : 1703 : PlanRowMark *rc = (PlanRowMark *) lfirst(cell);
4243 : :
4244 [ + + ]: 1703 : if (rt_fetch(rc->rti, root->parse->rtable)->rtekind == RTE_RESULT)
4245 : 674 : root->rowMarks = foreach_delete_current(root->rowMarks, cell);
4246 : : }
4247 : 183536 : }
4248 : :
4249 : : /*
4250 : : * remove_useless_results_recurse
4251 : : * Recursive guts of remove_useless_result_rtes.
4252 : : *
4253 : : * This recursively processes the jointree and returns a modified jointree.
4254 : : * In addition, the RT indexes of any removed outer-join nodes are added to
4255 : : * *dropped_outer_joins.
4256 : : *
4257 : : * jtnode is the current jointree node. If it could be valid to merge
4258 : : * its quals into those of the parent node, parent_quals should point to
4259 : : * the parent's quals list; otherwise, pass NULL for parent_quals.
4260 : : * (Note that in some cases, parent_quals points to the quals of a parent
4261 : : * more than one level up in the tree.)
4262 : : *
4263 : : * baserels is the set of base (non-join) RT indexes in the whole jointree;
4264 : : * it can be NULL if the query contains no PHVs.
4265 : : */
4266 : : static Node *
4267 : 508008 : remove_useless_results_recurse(PlannerInfo *root, Node *jtnode,
4268 : : Relids baserels,
4269 : : Node **parent_quals,
4270 : : Relids *dropped_outer_joins)
4271 : : {
4272 : : Assert(jtnode != NULL);
4273 [ + + ]: 508008 : if (IsA(jtnode, RangeTblRef))
4274 : : {
4275 : : /* Can't immediately do anything with a RangeTblRef */
4276 : : }
4277 [ + + ]: 258655 : else if (IsA(jtnode, FromExpr))
4278 : : {
4279 : 196805 : FromExpr *f = (FromExpr *) jtnode;
4280 : 196805 : Relids result_relids = NULL;
4281 : : ListCell *cell;
4282 : :
4283 : : /*
4284 : : * We can drop RTE_RESULT rels from the fromlist so long as at least
4285 : : * one child remains, since joining to a one-row table changes
4286 : : * nothing. (But we can't drop a RTE_RESULT that computes PHV(s) that
4287 : : * are needed by some sibling. The cleanup transformation below would
4288 : : * reassign the PHVs to be computed at the join, which is too late for
4289 : : * the sibling's use.) The easiest way to mechanize this rule is to
4290 : : * modify the list in-place.
4291 : : */
4292 [ + - + + : 397577 : foreach(cell, f->fromlist)
+ + ]
4293 : : {
4294 : 200772 : Node *child = (Node *) lfirst(cell);
4295 : : int varno;
4296 : :
4297 : : /* Recursively transform child, allowing it to push up quals ... */
4298 : 200772 : child = remove_useless_results_recurse(root, child,
4299 : : baserels,
4300 : : &f->quals,
4301 : : dropped_outer_joins);
4302 : : /* ... and stick it back into the tree */
4303 : 200772 : lfirst(cell) = child;
4304 : :
4305 : : /*
4306 : : * If it's an RTE_RESULT with at least one sibling, and no sibling
4307 : : * references dependent PHVs, we can drop it. We don't yet know
4308 : : * what the inner join's final relid set will be, so postpone
4309 : : * cleanup of PHVs etc till after this loop.
4310 : : */
4311 [ + + + + ]: 207221 : if (list_length(f->fromlist) > 1 &&
4312 : 6449 : (varno = get_result_relid(root, child)) != 0 &&
4313 [ + + ]: 299 : !find_dependent_phvs_in_jointree(root, (Node *) f, varno,
4314 : : baserels))
4315 : : {
4316 : 269 : f->fromlist = foreach_delete_current(f->fromlist, cell);
4317 : 269 : result_relids = bms_add_member(result_relids, varno);
4318 : : }
4319 : : }
4320 : :
4321 : : /*
4322 : : * Clean up if we dropped any RTE_RESULT RTEs. This is a bit
4323 : : * inefficient if there's more than one, but it seems better to
4324 : : * optimize the support code for the single-relid case.
4325 : : */
4326 [ + + ]: 196805 : if (result_relids)
4327 : : {
4328 : 259 : int varno = -1;
4329 : :
4330 [ + + ]: 528 : while ((varno = bms_next_member(result_relids, varno)) >= 0)
4331 : 269 : remove_result_refs(root, varno, (Node *) f);
4332 : : }
4333 : :
4334 : : /*
4335 : : * If the FromExpr now has only one child, see if we can elide it.
4336 : : * This is always valid if there are no quals, except at the top of
4337 : : * the jointree (since Query.jointree is required to point to a
4338 : : * FromExpr). Otherwise, we can do it if we can push the quals up to
4339 : : * the parent node.
4340 : : *
4341 : : * Note: while it would not be terribly hard to generalize this
4342 : : * transformation to merge multi-child FromExprs into their parent
4343 : : * FromExpr, that risks making the parent join too expensive to plan.
4344 : : * We leave it to later processing to decide heuristically whether
4345 : : * that's a good idea. Pulling up a single child is always OK,
4346 : : * however.
4347 : : */
4348 [ + + ]: 196805 : if (list_length(f->fromlist) == 1 &&
4349 [ + + ]: 194490 : f != root->parse->jointree &&
4350 [ + + + + ]: 12502 : (f->quals == NULL || parent_quals != NULL))
4351 : : {
4352 : : /*
4353 : : * Merge any quals up to parent. They should be in implicit-AND
4354 : : * format by now, so we just need to concatenate lists. Put the
4355 : : * child quals at the front, on the grounds that they should
4356 : : * nominally be evaluated earlier.
4357 : : */
4358 [ + + ]: 3589 : if (f->quals != NULL)
4359 : 1255 : *parent_quals = (Node *)
4360 : 1255 : list_concat(castNode(List, f->quals),
4361 : : castNode(List, *parent_quals));
4362 : 3589 : return (Node *) linitial(f->fromlist);
4363 : : }
4364 : : }
4365 [ + - ]: 61850 : else if (IsA(jtnode, JoinExpr))
4366 : : {
4367 : 61850 : JoinExpr *j = (JoinExpr *) jtnode;
4368 : : int varno;
4369 : :
4370 : : /*
4371 : : * First, recurse. We can absorb pushed-up FromExpr quals from either
4372 : : * child into this node if the jointype is INNER, since then this is
4373 : : * equivalent to a FromExpr. When the jointype is LEFT, we can absorb
4374 : : * quals from the RHS child into the current node, as they're
4375 : : * essentially degenerate quals of the outer join. Moreover, if we've
4376 : : * been passed down a parent_quals pointer then we can allow quals of
4377 : : * the LHS child to be absorbed into the parent. (This is important
4378 : : * to ensure we remove single-child FromExprs immediately below
4379 : : * commutable left joins.) For other jointypes, we can't move child
4380 : : * quals up, or at least there's no particular reason to.
4381 : : */
4382 : 61850 : j->larg = remove_useless_results_recurse(root, j->larg,
4383 : : baserels,
4384 [ + + ]: 61850 : (j->jointype == JOIN_INNER) ?
4385 : : &j->quals :
4386 : 45580 : (j->jointype == JOIN_LEFT) ?
4387 [ + + ]: 45580 : parent_quals : NULL,
4388 : : dropped_outer_joins);
4389 : 61850 : j->rarg = remove_useless_results_recurse(root, j->rarg,
4390 : : baserels,
4391 [ + + ]: 61850 : (j->jointype == JOIN_INNER ||
4392 [ + + ]: 45580 : j->jointype == JOIN_LEFT) ?
4393 : : &j->quals : NULL,
4394 : : dropped_outer_joins);
4395 : :
4396 : : /* Apply join-type-specific optimization rules */
4397 [ + + + + : 61850 : switch (j->jointype)
- ]
4398 : : {
4399 : 16270 : case JOIN_INNER:
4400 : :
4401 : : /*
4402 : : * An inner join is equivalent to a FromExpr, so if either
4403 : : * side was simplified to an RTE_RESULT rel, we can replace
4404 : : * the join with a FromExpr with just the other side.
4405 : : * Furthermore, we can elide that FromExpr according to the
4406 : : * same rules as above.
4407 : : *
4408 : : * Just as in the FromExpr case, we can't simplify if the
4409 : : * other input rel references any PHVs that are marked as to
4410 : : * be evaluated at the RTE_RESULT rel, because we can't
4411 : : * postpone their evaluation in that case. But we only have
4412 : : * to check this in cases where it's syntactically legal for
4413 : : * the other input to have a LATERAL reference to the
4414 : : * RTE_RESULT rel. Only RHSes of inner and left joins are
4415 : : * allowed to have such refs.
4416 : : */
4417 [ + + ]: 16270 : if ((varno = get_result_relid(root, j->larg)) != 0 &&
4418 [ + + ]: 171 : !find_dependent_phvs_in_jointree(root, j->rarg, varno,
4419 : : baserels))
4420 : : {
4421 : 151 : remove_result_refs(root, varno, j->rarg);
4422 [ + + + + ]: 151 : if (j->quals != NULL && parent_quals == NULL)
4423 : 10 : jtnode = (Node *)
4424 : 10 : makeFromExpr(list_make1(j->rarg), j->quals);
4425 : : else
4426 : : {
4427 : : /* Merge any quals up to parent */
4428 [ + + ]: 141 : if (j->quals != NULL)
4429 : 58 : *parent_quals = (Node *)
4430 : 58 : list_concat(castNode(List, j->quals),
4431 : : castNode(List, *parent_quals));
4432 : 141 : jtnode = j->rarg;
4433 : : }
4434 : : }
4435 [ + + ]: 16119 : else if ((varno = get_result_relid(root, j->rarg)) != 0)
4436 : : {
4437 : 617 : remove_result_refs(root, varno, j->larg);
4438 [ + + + + ]: 617 : if (j->quals != NULL && parent_quals == NULL)
4439 : 10 : jtnode = (Node *)
4440 : 10 : makeFromExpr(list_make1(j->larg), j->quals);
4441 : : else
4442 : : {
4443 : : /* Merge any quals up to parent */
4444 [ + + ]: 607 : if (j->quals != NULL)
4445 : 399 : *parent_quals = (Node *)
4446 : 399 : list_concat(castNode(List, j->quals),
4447 : : castNode(List, *parent_quals));
4448 : 607 : jtnode = j->larg;
4449 : : }
4450 : : }
4451 : 16270 : break;
4452 : 33664 : case JOIN_LEFT:
4453 : :
4454 : : /*
4455 : : * We can simplify this case if the RHS is an RTE_RESULT, with
4456 : : * two different possibilities:
4457 : : *
4458 : : * If the qual is empty (JOIN ON TRUE), then the join can be
4459 : : * strength-reduced to a plain inner join, since each LHS row
4460 : : * necessarily has exactly one join partner. So we can always
4461 : : * discard the RHS, much as in the JOIN_INNER case above.
4462 : : * (Again, the LHS could not contain a lateral reference to
4463 : : * the RHS.)
4464 : : *
4465 : : * Otherwise, it's still true that each LHS row should be
4466 : : * returned exactly once, and since the RHS returns no columns
4467 : : * (unless there are PHVs that have to be evaluated there), we
4468 : : * don't much care if it's null-extended or not. So in this
4469 : : * case also, we can just ignore the qual and discard the left
4470 : : * join.
4471 : : */
4472 [ + + ]: 33664 : if ((varno = get_result_relid(root, j->rarg)) != 0 &&
4473 [ + + ]: 174 : (j->quals == NULL ||
4474 [ - + ]: 99 : !find_dependent_phvs(root, varno, baserels)))
4475 : : {
4476 : 75 : remove_result_refs(root, varno, j->larg);
4477 : 75 : *dropped_outer_joins = bms_add_member(*dropped_outer_joins,
4478 : : j->rtindex);
4479 : 75 : jtnode = j->larg;
4480 : : }
4481 : 33664 : break;
4482 : 2711 : case JOIN_SEMI:
4483 : :
4484 : : /*
4485 : : * We may simplify this case if the RHS is an RTE_RESULT; the
4486 : : * join qual becomes effectively just a filter qual for the
4487 : : * LHS, since we should either return the LHS row or not. The
4488 : : * filter clause must go into a new FromExpr if we can't push
4489 : : * it up to the parent.
4490 : : *
4491 : : * There is a fine point about PHVs that are supposed to be
4492 : : * evaluated at the RHS. Such PHVs could only appear in the
4493 : : * semijoin's qual, since the rest of the query cannot
4494 : : * reference any outputs of the semijoin's RHS. Therefore,
4495 : : * they can't actually go to null before being examined, and
4496 : : * it'd be OK to just remove the PHV wrapping. We don't have
4497 : : * infrastructure for that, but remove_result_refs() will
4498 : : * relabel them as to be evaluated at the LHS, which is fine.
4499 : : *
4500 : : * Also, we don't need to worry about removing traces of the
4501 : : * join's rtindex, since it hasn't got one.
4502 : : */
4503 [ + + ]: 2711 : if ((varno = get_result_relid(root, j->rarg)) != 0)
4504 : : {
4505 : : Assert(j->rtindex == 0);
4506 : 30 : remove_result_refs(root, varno, j->larg);
4507 [ + - - + ]: 30 : if (j->quals != NULL && parent_quals == NULL)
4508 : 0 : jtnode = (Node *)
4509 : 0 : makeFromExpr(list_make1(j->larg), j->quals);
4510 : : else
4511 : : {
4512 : : /* Merge any quals up to parent */
4513 [ + - ]: 30 : if (j->quals != NULL)
4514 : 30 : *parent_quals = (Node *)
4515 : 30 : list_concat(castNode(List, j->quals),
4516 : : castNode(List, *parent_quals));
4517 : 30 : jtnode = j->larg;
4518 : : }
4519 : : }
4520 : 2711 : break;
4521 : 9205 : case JOIN_FULL:
4522 : : case JOIN_ANTI:
4523 : : /* We have no special smarts for these cases */
4524 : 9205 : break;
4525 : 0 : default:
4526 : : /* Note: JOIN_RIGHT should be gone at this point */
4527 [ # # ]: 0 : elog(ERROR, "unrecognized join type: %d",
4528 : : (int) j->jointype);
4529 : : break;
4530 : : }
4531 : : }
4532 : : else
4533 [ # # ]: 0 : elog(ERROR, "unrecognized node type: %d",
4534 : : (int) nodeTag(jtnode));
4535 : 504419 : return jtnode;
4536 : : }
4537 : :
4538 : : /*
4539 : : * get_result_relid
4540 : : * If jtnode is a RangeTblRef for an RTE_RESULT RTE, return its relid;
4541 : : * otherwise return 0.
4542 : : */
4543 : : static int
4544 : 75213 : get_result_relid(PlannerInfo *root, Node *jtnode)
4545 : : {
4546 : : int varno;
4547 : :
4548 [ + + ]: 75213 : if (!IsA(jtnode, RangeTblRef))
4549 : 9781 : return 0;
4550 : 65432 : varno = ((RangeTblRef *) jtnode)->rtindex;
4551 [ + + ]: 65432 : if (rt_fetch(varno, root->parse->rtable)->rtekind != RTE_RESULT)
4552 : 64141 : return 0;
4553 : 1291 : return varno;
4554 : : }
4555 : :
4556 : : /*
4557 : : * remove_result_refs
4558 : : * Helper routine for dropping an unneeded RTE_RESULT RTE.
4559 : : *
4560 : : * This doesn't physically remove the RTE from the jointree, because that's
4561 : : * more easily handled in remove_useless_results_recurse. What it does do
4562 : : * is the necessary cleanup in the rest of the tree: we must adjust any PHVs
4563 : : * that may reference the RTE. Be sure to call this at a point where the
4564 : : * jointree is valid (no disconnected nodes).
4565 : : *
4566 : : * Note that we don't need to process the append_rel_list, since RTEs
4567 : : * referenced directly in the jointree won't be appendrel members.
4568 : : *
4569 : : * varno is the RTE_RESULT's relid.
4570 : : * newjtloc is the jointree location at which any PHVs referencing the
4571 : : * RTE_RESULT should be evaluated instead.
4572 : : */
4573 : : static void
4574 : 1142 : remove_result_refs(PlannerInfo *root, int varno, Node *newjtloc)
4575 : : {
4576 : : /* Fix up PlaceHolderVars as needed */
4577 : : /* If there are no PHVs anywhere, we can skip this bit */
4578 [ + + ]: 1142 : if (root->glob->lastPHId != 0)
4579 : : {
4580 : : Relids subrelids;
4581 : :
4582 : 320 : subrelids = get_relids_in_jointree(newjtloc, true, false);
4583 : : Assert(!bms_is_empty(subrelids));
4584 : 320 : substitute_phv_relids((Node *) root->parse, varno, subrelids);
4585 : 320 : fix_append_rel_relids(root, varno, subrelids);
4586 : : }
4587 : :
4588 : : /*
4589 : : * We also need to remove any PlanRowMark referencing the RTE, but we
4590 : : * postpone that work until we return to remove_useless_result_rtes.
4591 : : */
4592 : 1142 : }
4593 : :
4594 : :
4595 : : /*
4596 : : * find_dependent_phvs - are there any PlaceHolderVars whose base relids are
4597 : : * exactly the given varno?
4598 : : *
4599 : : * We ignore outer-join relids present in a PHV's phrels, by intersecting
4600 : : * with the caller-supplied "baserels" set. This is necessary in part
4601 : : * because some of the OJ relids may be stale, that is we may have
4602 : : * already decided to remove those joins in remove_useless_result_rtes
4603 : : * and not yet have cleaned their relid bits out of upper PHVs.
4604 : : * But in general, it's the set of baserels that identify possible places
4605 : : * to evaluate a PHV, and we mustn't let that go to empty. (The caller is
4606 : : * allowed to pass baserels as NULL if the query contains no PHVs at all,
4607 : : * since then there is no work to do anyway.)
4608 : : *
4609 : : * find_dependent_phvs should be used when we want to see if there are
4610 : : * any such PHVs anywhere in the Query. Another use-case is to see if
4611 : : * a subtree of the join tree needs such PHVs; but for that, we have
4612 : : * to look not only at the join tree nodes themselves but at the
4613 : : * referenced RTEs, and also inside any PHVs elsewhere in the Query that
4614 : : * are evaluated within the subtree. For that, use
4615 : : * find_dependent_phvs_in_jointree.
4616 : : */
4617 : :
4618 : : typedef struct
4619 : : {
4620 : : Relids relids; /* target relid, represented as a relid set */
4621 : : Relids baserels; /* base RT indexes in query, NULL if no PHVs */
4622 : : Relids siblingrels; /* base RT indexes of target's sibling rels */
4623 : : int sublevels_up; /* current nesting level */
4624 : : } find_dependent_phvs_context;
4625 : :
4626 : : static bool
4627 : 2944 : find_dependent_phvs_walker(Node *node,
4628 : : find_dependent_phvs_context *context)
4629 : : {
4630 [ + + ]: 2944 : if (node == NULL)
4631 : 635 : return false;
4632 [ + + ]: 2309 : if (IsA(node, PlaceHolderVar))
4633 : : {
4634 : 204 : PlaceHolderVar *phv = (PlaceHolderVar *) node;
4635 : :
4636 [ + - ]: 204 : if (phv->phlevelsup == context->sublevels_up)
4637 : : {
4638 : 204 : Relids phbaserels = bms_intersect(phv->phrels,
4639 : 204 : context->baserels);
4640 : 204 : bool match = bms_equal(context->relids, phbaserels);
4641 : :
4642 : 204 : bms_free(phbaserels);
4643 [ + + ]: 204 : if (match)
4644 : 149 : return true;
4645 : : }
4646 : : /* fall through to examine children */
4647 : : }
4648 [ + + ]: 2160 : if (IsA(node, Query))
4649 : : {
4650 : : /* Recurse into subselects */
4651 : : bool result;
4652 : :
4653 : 50 : context->sublevels_up++;
4654 : 50 : result = query_tree_walker((Query *) node,
4655 : : find_dependent_phvs_walker,
4656 : : context, 0);
4657 : 50 : context->sublevels_up--;
4658 : 50 : return result;
4659 : : }
4660 : : /* Shouldn't need to handle most planner auxiliary nodes here */
4661 : : Assert(!IsA(node, SpecialJoinInfo));
4662 : : Assert(!IsA(node, PlaceHolderInfo));
4663 : : Assert(!IsA(node, MinMaxAggInfo));
4664 : :
4665 : 2110 : return expression_tree_walker(node, find_dependent_phvs_walker, context);
4666 : : }
4667 : :
4668 : : /*
4669 : : * Look for PlaceHolderVars that are to be evaluated at some but not all of
4670 : : * context->siblingrels and contain a dependent PHV in their expressions.
4671 : : */
4672 : : static bool
4673 : 4890 : find_nested_dependent_phvs_walker(Node *node,
4674 : : find_dependent_phvs_context *context)
4675 : : {
4676 [ + + ]: 4890 : if (node == NULL)
4677 : 2420 : return false;
4678 [ + + ]: 2470 : if (IsA(node, PlaceHolderVar))
4679 : : {
4680 : 230 : PlaceHolderVar *phv = (PlaceHolderVar *) node;
4681 : :
4682 [ + - ]: 230 : if (phv->phlevelsup == context->sublevels_up)
4683 : : {
4684 : 230 : Relids phbaserels = bms_intersect(phv->phrels,
4685 : 230 : context->baserels);
4686 : : bool match;
4687 : :
4688 [ + + ]: 410 : match = (!bms_is_subset(context->relids, phbaserels) &&
4689 [ + + ]: 410 : bms_overlap(phbaserels, context->siblingrels) &&
4690 [ + + ]: 135 : !bms_is_subset(context->siblingrels, phbaserels));
4691 : 230 : bms_free(phbaserels);
4692 [ + + + + ]: 270 : if (match &&
4693 : 40 : find_dependent_phvs_walker((Node *) phv->phexpr, context))
4694 : 20 : return true;
4695 : : }
4696 : : /* fall through to examine children */
4697 : : }
4698 [ - + ]: 2450 : if (IsA(node, Query))
4699 : : {
4700 : : /* Recurse into subselects */
4701 : : bool result;
4702 : :
4703 : 0 : context->sublevels_up++;
4704 : 0 : result = query_tree_walker((Query *) node,
4705 : : find_nested_dependent_phvs_walker,
4706 : : context, 0);
4707 : 0 : context->sublevels_up--;
4708 : 0 : return result;
4709 : : }
4710 : :
4711 : 2450 : return expression_tree_walker(node, find_nested_dependent_phvs_walker,
4712 : : context);
4713 : : }
4714 : :
4715 : : static bool
4716 : 99 : find_dependent_phvs(PlannerInfo *root, int varno, Relids baserels)
4717 : : {
4718 : : find_dependent_phvs_context context;
4719 : :
4720 : : /* If there are no PHVs anywhere, we needn't work hard */
4721 [ - + ]: 99 : if (root->glob->lastPHId == 0)
4722 : 0 : return false;
4723 : :
4724 : 99 : context.relids = bms_make_singleton(varno);
4725 : 99 : context.baserels = baserels;
4726 : 99 : context.siblingrels = NULL;
4727 : 99 : context.sublevels_up = 0;
4728 : :
4729 [ + - ]: 99 : if (query_tree_walker(root->parse, find_dependent_phvs_walker, &context, 0))
4730 : 99 : return true;
4731 : : /* The append_rel_list could be populated already, so check it too */
4732 [ # # ]: 0 : if (expression_tree_walker((Node *) root->append_rel_list,
4733 : : find_dependent_phvs_walker,
4734 : : &context))
4735 : 0 : return true;
4736 : 0 : return false;
4737 : : }
4738 : :
4739 : : static bool
4740 : 470 : find_dependent_phvs_in_jointree(PlannerInfo *root, Node *node, int varno,
4741 : : Relids baserels)
4742 : : {
4743 : : find_dependent_phvs_context context;
4744 : : Relids subrelids;
4745 : : int relid;
4746 : :
4747 : : /* If there are no PHVs anywhere, we needn't work hard */
4748 [ + + ]: 470 : if (root->glob->lastPHId == 0)
4749 : 330 : return false;
4750 : :
4751 : 140 : context.relids = bms_make_singleton(varno);
4752 : 140 : context.baserels = baserels;
4753 : 140 : context.siblingrels = NULL;
4754 : 140 : context.sublevels_up = 0;
4755 : :
4756 : : /*
4757 : : * See if the jointree fragment itself contains references (in join quals)
4758 : : */
4759 [ - + ]: 140 : if (find_dependent_phvs_walker(node, &context))
4760 : 0 : return true;
4761 : :
4762 : : /*
4763 : : * Otherwise, identify the set of referenced RTEs (we can ignore joins,
4764 : : * since they should be flattened already, so their join alias lists no
4765 : : * longer matter), and tediously check each RTE. We can ignore RTEs that
4766 : : * are not marked LATERAL, though, since they couldn't possibly contain
4767 : : * any cross-references to other RTEs.
4768 : : */
4769 : 140 : subrelids = get_relids_in_jointree(node, false, false);
4770 : 140 : relid = -1;
4771 [ + + ]: 355 : while ((relid = bms_next_member(subrelids, relid)) >= 0)
4772 : : {
4773 : 245 : RangeTblEntry *rte = rt_fetch(relid, root->parse->rtable);
4774 : :
4775 [ + + + + ]: 295 : if (rte->lateral &&
4776 : 50 : range_table_entry_walker(rte, find_dependent_phvs_walker, &context, 0))
4777 : 30 : return true;
4778 : : }
4779 : :
4780 : : /*
4781 : : * Lastly, check for PHVs that are evaluated at some but not all of the
4782 : : * sibling rels and contain a dependent PHV. Removing the RTE_RESULT
4783 : : * would move the dependent PHV up to the join of all the sibling rels, so
4784 : : * it would not yet be available where the outer PHV is evaluated. The
4785 : : * outer PHV can appear anywhere in the query (e.g., in the targetlist),
4786 : : * so search the whole query.
4787 : : */
4788 : 110 : context.siblingrels = bms_del_member(subrelids, varno);
4789 [ + + ]: 110 : if (query_tree_walker(root->parse, find_nested_dependent_phvs_walker,
4790 : : &context, 0))
4791 : 20 : return true;
4792 : :
4793 : 90 : return false;
4794 : : }
4795 : :
4796 : : /*
4797 : : * substitute_phv_relids - adjust PlaceHolderVar relid sets after pulling up
4798 : : * a subquery or removing an RTE_RESULT jointree item
4799 : : *
4800 : : * Find any PlaceHolderVar nodes in the given tree that reference the
4801 : : * pulled-up relid, and change them to reference the replacement relid(s).
4802 : : *
4803 : : * NOTE: although this has the form of a walker, we cheat and modify the
4804 : : * nodes in-place. This should be OK since the tree was copied by
4805 : : * pullup_replace_vars earlier. Avoid scribbling on the original values of
4806 : : * the bitmapsets, though, because expression_tree_mutator doesn't copy those.
4807 : : */
4808 : :
4809 : : typedef struct
4810 : : {
4811 : : int varno;
4812 : : int sublevels_up;
4813 : : Relids subrelids;
4814 : : } substitute_phv_relids_context;
4815 : :
4816 : : static bool
4817 : 286066 : substitute_phv_relids_walker(Node *node,
4818 : : substitute_phv_relids_context *context)
4819 : : {
4820 [ + + ]: 286066 : if (node == NULL)
4821 : 117730 : return false;
4822 [ + + ]: 168336 : if (IsA(node, PlaceHolderVar))
4823 : : {
4824 : 8688 : PlaceHolderVar *phv = (PlaceHolderVar *) node;
4825 : :
4826 [ + + + + ]: 17352 : if (phv->phlevelsup == context->sublevels_up &&
4827 : 8664 : bms_is_member(context->varno, phv->phrels))
4828 : : {
4829 : 12254 : phv->phrels = bms_union(phv->phrels,
4830 : 6127 : context->subrelids);
4831 : 6127 : phv->phrels = bms_del_member(phv->phrels,
4832 : : context->varno);
4833 : : /* Assert we haven't broken the PHV */
4834 : : Assert(!bms_is_empty(phv->phrels));
4835 : : }
4836 : : /* fall through to examine children */
4837 : : }
4838 [ + + ]: 168336 : if (IsA(node, Query))
4839 : : {
4840 : : /* Recurse into subselects */
4841 : : bool result;
4842 : :
4843 : 5048 : context->sublevels_up++;
4844 : 5048 : result = query_tree_walker((Query *) node,
4845 : : substitute_phv_relids_walker,
4846 : : context, 0);
4847 : 5048 : context->sublevels_up--;
4848 : 5048 : return result;
4849 : : }
4850 : : /* Shouldn't need to handle planner auxiliary nodes here */
4851 : : Assert(!IsA(node, SpecialJoinInfo));
4852 : : Assert(!IsA(node, AppendRelInfo));
4853 : : Assert(!IsA(node, PlaceHolderInfo));
4854 : : Assert(!IsA(node, MinMaxAggInfo));
4855 : :
4856 : 163288 : return expression_tree_walker(node, substitute_phv_relids_walker, context);
4857 : : }
4858 : :
4859 : : static void
4860 : 2829 : substitute_phv_relids(Node *node, int varno, Relids subrelids)
4861 : : {
4862 : : substitute_phv_relids_context context;
4863 : :
4864 : 2829 : context.varno = varno;
4865 : 2829 : context.sublevels_up = 0;
4866 : 2829 : context.subrelids = subrelids;
4867 : :
4868 : : /*
4869 : : * Must be prepared to start with a Query or a bare expression tree.
4870 : : */
4871 : 2829 : query_or_expression_tree_walker(node,
4872 : : substitute_phv_relids_walker,
4873 : : &context,
4874 : : 0);
4875 : 2829 : }
4876 : :
4877 : : /*
4878 : : * fix_append_rel_relids: update RT-index fields of AppendRelInfo nodes
4879 : : *
4880 : : * When we pull up a subquery, any AppendRelInfo references to the subquery's
4881 : : * RT index have to be replaced by the substituted relid (and there had better
4882 : : * be only one). We also need to apply substitute_phv_relids to their
4883 : : * translated_vars lists, since those might contain PlaceHolderVars.
4884 : : *
4885 : : * We assume we may modify the AppendRelInfo nodes in-place.
4886 : : */
4887 : : static void
4888 : 7948 : fix_append_rel_relids(PlannerInfo *root, int varno, Relids subrelids)
4889 : : {
4890 : : ListCell *l;
4891 : 7948 : int subvarno = -1;
4892 : :
4893 : : /*
4894 : : * We only want to extract the member relid once, but we mustn't fail
4895 : : * immediately if there are multiple members; it could be that none of the
4896 : : * AppendRelInfo nodes refer to it. So compute it on first use. Note that
4897 : : * bms_singleton_member will complain if set is not singleton.
4898 : : */
4899 [ + + + + : 17881 : foreach(l, root->append_rel_list)
+ + ]
4900 : : {
4901 : 9933 : AppendRelInfo *appinfo = (AppendRelInfo *) lfirst(l);
4902 : :
4903 : : /* The parent_relid shouldn't ever be a pullup target */
4904 : : Assert(appinfo->parent_relid != varno);
4905 : :
4906 [ + + ]: 9933 : if (appinfo->child_relid == varno)
4907 : : {
4908 [ + - ]: 5364 : if (subvarno < 0)
4909 : 5364 : subvarno = bms_singleton_member(subrelids);
4910 : 5364 : appinfo->child_relid = subvarno;
4911 : : }
4912 : :
4913 : : /* Also fix up any PHVs in its translated vars */
4914 [ + + ]: 9933 : if (root->glob->lastPHId != 0)
4915 : 190 : substitute_phv_relids((Node *) appinfo->translated_vars,
4916 : : varno, subrelids);
4917 : : }
4918 : 7948 : }
4919 : :
4920 : : /*
4921 : : * get_relids_in_jointree: get set of RT indexes present in a jointree
4922 : : *
4923 : : * Base-relation relids are always included in the result.
4924 : : * If include_outer_joins is true, outer-join RT indexes are included.
4925 : : * If include_inner_joins is true, inner-join RT indexes are included.
4926 : : *
4927 : : * Note that for most purposes in the planner, outer joins are included
4928 : : * in standard relid sets. Setting include_inner_joins true is only
4929 : : * appropriate for special purposes during subquery flattening.
4930 : : */
4931 : : Relids
4932 : 90450 : get_relids_in_jointree(Node *jtnode, bool include_outer_joins,
4933 : : bool include_inner_joins)
4934 : : {
4935 : 90450 : Relids result = NULL;
4936 : :
4937 [ - + ]: 90450 : if (jtnode == NULL)
4938 : 0 : return result;
4939 [ + + ]: 90450 : if (IsA(jtnode, RangeTblRef))
4940 : : {
4941 : 45883 : int varno = ((RangeTblRef *) jtnode)->rtindex;
4942 : :
4943 : 45883 : result = bms_make_singleton(varno);
4944 : : }
4945 [ + + ]: 44567 : else if (IsA(jtnode, FromExpr))
4946 : : {
4947 : 35706 : FromExpr *f = (FromExpr *) jtnode;
4948 : : ListCell *l;
4949 : :
4950 [ + - + + : 72898 : foreach(l, f->fromlist)
+ + ]
4951 : : {
4952 : 37192 : result = bms_join(result,
4953 : 37192 : get_relids_in_jointree(lfirst(l),
4954 : : include_outer_joins,
4955 : : include_inner_joins));
4956 : : }
4957 : : }
4958 [ + - ]: 8861 : else if (IsA(jtnode, JoinExpr))
4959 : : {
4960 : 8861 : JoinExpr *j = (JoinExpr *) jtnode;
4961 : :
4962 : 8861 : result = get_relids_in_jointree(j->larg,
4963 : : include_outer_joins,
4964 : : include_inner_joins);
4965 : 8861 : result = bms_join(result,
4966 : : get_relids_in_jointree(j->rarg,
4967 : : include_outer_joins,
4968 : : include_inner_joins));
4969 [ + + ]: 8861 : if (j->rtindex)
4970 : : {
4971 [ + + ]: 8596 : if (j->jointype == JOIN_INNER)
4972 : : {
4973 [ + + ]: 3209 : if (include_inner_joins)
4974 : 803 : result = bms_add_member(result, j->rtindex);
4975 : : }
4976 : : else
4977 : : {
4978 [ + + ]: 5387 : if (include_outer_joins)
4979 : 2466 : result = bms_add_member(result, j->rtindex);
4980 : : }
4981 : : }
4982 : : }
4983 : : else
4984 [ # # ]: 0 : elog(ERROR, "unrecognized node type: %d",
4985 : : (int) nodeTag(jtnode));
4986 : 90450 : return result;
4987 : : }
4988 : :
4989 : : /*
4990 : : * get_relids_for_join: get set of base+OJ RT indexes making up a join
4991 : : */
4992 : : Relids
4993 : 692 : get_relids_for_join(Query *query, int joinrelid)
4994 : : {
4995 : : Node *jtnode;
4996 : :
4997 : 692 : jtnode = find_jointree_node_for_rel((Node *) query->jointree,
4998 : : joinrelid);
4999 [ - + ]: 692 : if (!jtnode)
5000 [ # # ]: 0 : elog(ERROR, "could not find join node %d", joinrelid);
5001 : 692 : return get_relids_in_jointree(jtnode, true, false);
5002 : : }
5003 : :
5004 : : /*
5005 : : * find_jointree_node_for_rel: locate jointree node for a base or join RT index
5006 : : *
5007 : : * Returns NULL if not found
5008 : : */
5009 : : static Node *
5010 : 3070 : find_jointree_node_for_rel(Node *jtnode, int relid)
5011 : : {
5012 [ - + ]: 3070 : if (jtnode == NULL)
5013 : 0 : return NULL;
5014 [ + + ]: 3070 : if (IsA(jtnode, RangeTblRef))
5015 : : {
5016 : 707 : int varno = ((RangeTblRef *) jtnode)->rtindex;
5017 : :
5018 [ - + ]: 707 : if (relid == varno)
5019 : 0 : return jtnode;
5020 : : }
5021 [ + + ]: 2363 : else if (IsA(jtnode, FromExpr))
5022 : : {
5023 : 739 : FromExpr *f = (FromExpr *) jtnode;
5024 : : ListCell *l;
5025 : :
5026 [ + - + + : 789 : foreach(l, f->fromlist)
+ + ]
5027 : : {
5028 : 779 : jtnode = find_jointree_node_for_rel(lfirst(l), relid);
5029 [ + + ]: 779 : if (jtnode)
5030 : 729 : return jtnode;
5031 : : }
5032 : : }
5033 [ + - ]: 1624 : else if (IsA(jtnode, JoinExpr))
5034 : : {
5035 : 1624 : JoinExpr *j = (JoinExpr *) jtnode;
5036 : :
5037 [ + + ]: 1624 : if (relid == j->rtindex)
5038 : 692 : return jtnode;
5039 : 932 : jtnode = find_jointree_node_for_rel(j->larg, relid);
5040 [ + + ]: 932 : if (jtnode)
5041 : 265 : return jtnode;
5042 : 667 : jtnode = find_jointree_node_for_rel(j->rarg, relid);
5043 [ + - ]: 667 : if (jtnode)
5044 : 667 : return jtnode;
5045 : : }
5046 : : else
5047 [ # # ]: 0 : elog(ERROR, "unrecognized node type: %d",
5048 : : (int) nodeTag(jtnode));
5049 : 717 : return NULL;
5050 : : }
5051 : :
5052 : : /*
5053 : : * get_nullingrels: collect info about which outer joins null which relations
5054 : : *
5055 : : * The result struct contains, for each leaf relation used in the query,
5056 : : * the set of relids of outer joins that potentially null that rel.
5057 : : */
5058 : : static nullingrel_info *
5059 : 1173 : get_nullingrels(Query *parse)
5060 : : {
5061 : 1173 : nullingrel_info *result = palloc_object(nullingrel_info);
5062 : :
5063 : 1173 : result->rtlength = list_length(parse->rtable);
5064 : 1173 : result->nullingrels = palloc0_array(Relids, result->rtlength + 1);
5065 : 1173 : get_nullingrels_recurse((Node *) parse->jointree, NULL, result);
5066 : 1173 : return result;
5067 : : }
5068 : :
5069 : : /*
5070 : : * Recursive guts of get_nullingrels().
5071 : : *
5072 : : * Note: at any recursion level, the passed-down upper_nullingrels must be
5073 : : * treated as a constant, but it can be stored directly into *info
5074 : : * if we're at leaf level. Upper recursion levels do not free their mutated
5075 : : * copies of the nullingrels, because those are probably referenced by
5076 : : * at least one leaf rel.
5077 : : */
5078 : : static void
5079 : 6348 : get_nullingrels_recurse(Node *jtnode, Relids upper_nullingrels,
5080 : : nullingrel_info *info)
5081 : : {
5082 [ - + ]: 6348 : if (jtnode == NULL)
5083 : 0 : return;
5084 [ + + ]: 6348 : if (IsA(jtnode, RangeTblRef))
5085 : : {
5086 : 3387 : int varno = ((RangeTblRef *) jtnode)->rtindex;
5087 : :
5088 : : Assert(varno > 0 && varno <= info->rtlength);
5089 : 3387 : info->nullingrels[varno] = upper_nullingrels;
5090 : : }
5091 [ + + ]: 2961 : else if (IsA(jtnode, FromExpr))
5092 : : {
5093 : 1253 : FromExpr *f = (FromExpr *) jtnode;
5094 : : ListCell *l;
5095 : :
5096 [ + - + + : 3012 : foreach(l, f->fromlist)
+ + ]
5097 : : {
5098 : 1759 : get_nullingrels_recurse(lfirst(l), upper_nullingrels, info);
5099 : : }
5100 : : }
5101 [ + - ]: 1708 : else if (IsA(jtnode, JoinExpr))
5102 : : {
5103 : 1708 : JoinExpr *j = (JoinExpr *) jtnode;
5104 : : Relids local_nullingrels;
5105 : :
5106 [ + + + + : 1708 : switch (j->jointype)
- ]
5107 : : {
5108 : 569 : case JOIN_INNER:
5109 : 569 : get_nullingrels_recurse(j->larg, upper_nullingrels, info);
5110 : 569 : get_nullingrels_recurse(j->rarg, upper_nullingrels, info);
5111 : 569 : break;
5112 : 1089 : case JOIN_LEFT:
5113 : : case JOIN_SEMI:
5114 : : case JOIN_ANTI:
5115 : 1089 : local_nullingrels = bms_add_member(bms_copy(upper_nullingrels),
5116 : : j->rtindex);
5117 : 1089 : get_nullingrels_recurse(j->larg, upper_nullingrels, info);
5118 : 1089 : get_nullingrels_recurse(j->rarg, local_nullingrels, info);
5119 : 1089 : break;
5120 : 35 : case JOIN_FULL:
5121 : 35 : local_nullingrels = bms_add_member(bms_copy(upper_nullingrels),
5122 : : j->rtindex);
5123 : 35 : get_nullingrels_recurse(j->larg, local_nullingrels, info);
5124 : 35 : get_nullingrels_recurse(j->rarg, local_nullingrels, info);
5125 : 35 : break;
5126 : 15 : case JOIN_RIGHT:
5127 : 15 : local_nullingrels = bms_add_member(bms_copy(upper_nullingrels),
5128 : : j->rtindex);
5129 : 15 : get_nullingrels_recurse(j->larg, local_nullingrels, info);
5130 : 15 : get_nullingrels_recurse(j->rarg, upper_nullingrels, info);
5131 : 15 : break;
5132 : 0 : default:
5133 [ # # ]: 0 : elog(ERROR, "unrecognized join type: %d",
5134 : : (int) j->jointype);
5135 : : break;
5136 : : }
5137 : : }
5138 : : else
5139 [ # # ]: 0 : elog(ERROR, "unrecognized node type: %d",
5140 : : (int) nodeTag(jtnode));
5141 : : }
|