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