Branch data Line data Source code
1 : : /*-------------------------------------------------------------------------
2 : : *
3 : : * prepjointree.c
4 : : * Planner preprocessing for subqueries and join tree manipulation.
5 : : *
6 : : * NOTE: the intended sequence for invoking these operations is
7 : : * preprocess_relation_rtes
8 : : * replace_empty_jointree
9 : : * pull_up_sublinks
10 : : * preprocess_function_rtes
11 : : * pull_up_subqueries
12 : : * flatten_simple_union_all
13 : : * do expression preprocessing (including flattening JOIN alias vars)
14 : : * reduce_outer_joins
15 : : * remove_useless_result_rtes
16 : : *
17 : : *
18 : : * Portions Copyright (c) 1996-2026, PostgreSQL Global Development Group
19 : : * Portions Copyright (c) 1994, Regents of the University of California
20 : : *
21 : : *
22 : : * IDENTIFICATION
23 : : * src/backend/optimizer/prep/prepjointree.c
24 : : *
25 : : *-------------------------------------------------------------------------
26 : : */
27 : : #include "postgres.h"
28 : :
29 : : #include "access/table.h"
30 : : #include "catalog/pg_type.h"
31 : : #include "funcapi.h"
32 : : #include "miscadmin.h"
33 : : #include "nodes/makefuncs.h"
34 : : #include "nodes/multibitmapset.h"
35 : : #include "nodes/nodeFuncs.h"
36 : : #include "optimizer/clauses.h"
37 : : #include "optimizer/optimizer.h"
38 : : #include "optimizer/placeholder.h"
39 : : #include "optimizer/plancat.h"
40 : : #include "optimizer/prep.h"
41 : : #include "optimizer/subselect.h"
42 : : #include "optimizer/tlist.h"
43 : : #include "parser/parse_relation.h"
44 : : #include "parser/parsetree.h"
45 : : #include "rewrite/rewriteHandler.h"
46 : : #include "rewrite/rewriteManip.h"
47 : : #include "utils/rel.h"
48 : :
49 : :
50 : : typedef struct nullingrel_info
51 : : {
52 : : /*
53 : : * For each leaf RTE, nullingrels[rti] is the set of relids of outer joins
54 : : * that potentially null that RTE.
55 : : */
56 : : Relids *nullingrels;
57 : : /* Length of range table (maximum index in nullingrels[]) */
58 : : int rtlength; /* used only for assertion checks */
59 : : } nullingrel_info;
60 : :
61 : : /* Options for wrapping an expression for identification purposes */
62 : : typedef enum ReplaceWrapOption
63 : : {
64 : : REPLACE_WRAP_NONE, /* no expressions need to be wrapped */
65 : : REPLACE_WRAP_ALL, /* all expressions need to be wrapped */
66 : : REPLACE_WRAP_VARFREE, /* variable-free expressions need to be
67 : : * wrapped */
68 : : } ReplaceWrapOption;
69 : :
70 : : typedef struct pullup_replace_vars_context
71 : : {
72 : : PlannerInfo *root;
73 : : List *targetlist; /* tlist of subquery being pulled up */
74 : : RangeTblEntry *target_rte; /* RTE of subquery */
75 : : int result_relation; /* the index of the result relation in the
76 : : * rewritten query */
77 : : Relids relids; /* relids within subquery, as numbered after
78 : : * pullup (set only if target_rte->lateral) */
79 : : nullingrel_info *nullinfo; /* per-RTE nullingrel info (set only if
80 : : * target_rte->lateral) */
81 : : bool *outer_hasSubLinks; /* -> outer query's hasSubLinks */
82 : : int varno; /* varno of subquery */
83 : : ReplaceWrapOption wrap_option; /* do we need certain outputs to be PHVs? */
84 : : Node **rv_cache; /* cache for results with PHVs */
85 : : } pullup_replace_vars_context;
86 : :
87 : : typedef struct reduce_outer_joins_pass1_state
88 : : {
89 : : Relids relids; /* base relids within this subtree */
90 : : bool contains_outer; /* does subtree contain outer join(s)? */
91 : : Relids nullable_rels; /* base relids that are nullable within this
92 : : * subtree */
93 : : Node *jtnode; /* the jointree node this state describes */
94 : : List *sub_states; /* List of states for subtree components */
95 : : } reduce_outer_joins_pass1_state;
96 : :
97 : : typedef struct reduce_outer_joins_pass2_state
98 : : {
99 : : Relids inner_reduced; /* OJ relids reduced to plain inner joins */
100 : : List *partial_reduced; /* List of partially reduced FULL joins */
101 : : Relids anti_reduced; /* OJ relids reduced to antijoins */
102 : : } reduce_outer_joins_pass2_state;
103 : :
104 : : typedef struct reduce_outer_joins_partial_state
105 : : {
106 : : int full_join_rti; /* RT index of a formerly-FULL join */
107 : : Relids unreduced_side; /* relids in its still-nullable side */
108 : : } reduce_outer_joins_partial_state;
109 : :
110 : : static Query *expand_virtual_generated_columns(PlannerInfo *root, Query *parse,
111 : : RangeTblEntry *rte, int rt_index,
112 : : Relation relation);
113 : : static Node *pull_up_sublinks_jointree_recurse(PlannerInfo *root, Node *jtnode,
114 : : Relids *relids);
115 : : static Node *pull_up_sublinks_qual_recurse(PlannerInfo *root, Node *node,
116 : : Node **jtlink1, Relids available_rels1,
117 : : Node **jtlink2, Relids available_rels2);
118 : : static Node *pull_up_subqueries_recurse(PlannerInfo *root, Node *jtnode,
119 : : JoinExpr *lowest_outer_join,
120 : : AppendRelInfo *containing_appendrel);
121 : : static Node *pull_up_simple_subquery(PlannerInfo *root, Node *jtnode,
122 : : RangeTblEntry *rte,
123 : : JoinExpr *lowest_outer_join,
124 : : AppendRelInfo *containing_appendrel);
125 : : static Node *pull_up_simple_union_all(PlannerInfo *root, Node *jtnode,
126 : : RangeTblEntry *rte);
127 : : static void pull_up_union_leaf_queries(Node *setOp, PlannerInfo *root,
128 : : int parentRTindex, Query *setOpQuery,
129 : : int childRToffset);
130 : : static void make_setop_translation_list(Query *query, int newvarno,
131 : : AppendRelInfo *appinfo);
132 : : static bool is_simple_subquery(PlannerInfo *root, Query *subquery,
133 : : RangeTblEntry *rte,
134 : : JoinExpr *lowest_outer_join);
135 : : static Node *pull_up_simple_values(PlannerInfo *root, Node *jtnode,
136 : : RangeTblEntry *rte);
137 : : static bool is_simple_values(PlannerInfo *root, RangeTblEntry *rte);
138 : : static Node *pull_up_constant_function(PlannerInfo *root, Node *jtnode,
139 : : RangeTblEntry *rte,
140 : : AppendRelInfo *containing_appendrel);
141 : : static bool is_simple_union_all(Query *subquery);
142 : : static bool is_simple_union_all_recurse(Node *setOp, Query *setOpQuery,
143 : : List *colTypes);
144 : : static bool is_safe_append_member(Query *subquery);
145 : : static bool jointree_contains_lateral_outer_refs(PlannerInfo *root,
146 : : Node *jtnode, bool restricted,
147 : : Relids safe_upper_varnos);
148 : : static void perform_pullup_replace_vars(PlannerInfo *root,
149 : : pullup_replace_vars_context *rvcontext,
150 : : AppendRelInfo *containing_appendrel);
151 : : static void replace_vars_in_jointree(Node *jtnode,
152 : : pullup_replace_vars_context *context);
153 : : static Node *pullup_replace_vars(Node *expr,
154 : : pullup_replace_vars_context *context);
155 : : static Node *pullup_replace_vars_callback(const Var *var,
156 : : replace_rte_variables_context *context);
157 : : static Query *pullup_replace_vars_subquery(Query *query,
158 : : pullup_replace_vars_context *context);
159 : : static reduce_outer_joins_pass1_state *reduce_outer_joins_pass1(Node *jtnode);
160 : : static void reduce_outer_joins_pass2(Node *jtnode,
161 : : reduce_outer_joins_pass1_state *state1,
162 : : reduce_outer_joins_pass2_state *state2,
163 : : PlannerInfo *root,
164 : : Relids nonnullable_rels,
165 : : List *forced_null_vars);
166 : : static void report_reduced_full_join(reduce_outer_joins_pass2_state *state2,
167 : : int rtindex, Relids relids);
168 : : static void remove_redundant_nullability_quals(Node *jtnode,
169 : : Relids antijoins);
170 : : static Node *strip_redundant_nullability_quals(Node *quals, Relids antijoins);
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 : 398743 : 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 [ + + ]: 398743 : if (parse->commandType != CMD_MERGE)
217 : 397179 : 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 : 436313 : preprocess_relation_rtes(PlannerInfo *root)
434 : : {
435 : 436313 : Query *parse = root->parse;
436 : : int rtable_size;
437 : : int rt_index;
438 : :
439 : 436313 : rtable_size = list_length(parse->rtable);
440 : :
441 [ + + ]: 979300 : for (rt_index = 0; rt_index < rtable_size; rt_index++)
442 : : {
443 : 542987 : RangeTblEntry *rte = rt_fetch(rt_index + 1, parse->rtable);
444 : : Relation relation;
445 : :
446 : : /* We only care about relation RTEs. */
447 [ + + ]: 542987 : if (rte->rtekind != RTE_RELATION)
448 : 176376 : continue;
449 : :
450 : : /*
451 : : * We need not lock the relation since it was already locked by the
452 : : * rewriter.
453 : : */
454 : 366611 : 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 [ + + ]: 366611 : if (rte->inh)
466 : 306763 : 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 : 366611 : 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 : 366611 : parse = expand_virtual_generated_columns(root, parse,
481 : : rte, rt_index + 1,
482 : : relation);
483 : :
484 : 366611 : table_close(relation, NoLock);
485 : : }
486 : :
487 : 436313 : 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 : 366611 : 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 : 366611 : tupdesc = RelationGetDescr(relation);
512 [ + + + + ]: 366611 : if (tupdesc->constr && tupdesc->constr->has_generated_virtual)
513 : : {
514 : 1156 : List *tlist = NIL;
515 : : pullup_replace_vars_context rvcontext;
516 : 1156 : List *save_exclRelTlist = NIL;
517 : :
518 [ + + ]: 4632 : for (int i = 0; i < tupdesc->natts; i++)
519 : : {
520 : 3476 : Form_pg_attribute attr = TupleDescAttr(tupdesc, i);
521 : : TargetEntry *tle;
522 : :
523 [ + + ]: 3476 : if (attr->attgenerated == ATTRIBUTE_GENERATED_VIRTUAL)
524 : : {
525 : : Node *defexpr;
526 : :
527 : 1531 : defexpr = build_generation_expression(relation, i + 1);
528 : 1531 : ChangeVarNodes(defexpr, 1, rt_index, 0);
529 : :
530 : 1531 : tle = makeTargetEntry((Expr *) defexpr, i + 1, 0, false);
531 : 1531 : tlist = lappend(tlist, tle);
532 : : }
533 : : else
534 : : {
535 : : Var *var;
536 : :
537 : 1945 : var = makeVar(rt_index,
538 : 1945 : i + 1,
539 : : attr->atttypid,
540 : : attr->atttypmod,
541 : : attr->attcollation,
542 : : 0);
543 : :
544 : 1945 : tle = makeTargetEntry((Expr *) var, i + 1, 0, false);
545 : 1945 : 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 : 1156 : rvcontext.root = root;
559 : 1156 : rvcontext.targetlist = tlist;
560 : 1156 : rvcontext.target_rte = rte;
561 : 1156 : rvcontext.result_relation = parse->resultRelation;
562 : : /* won't need these values */
563 : 1156 : rvcontext.relids = NULL;
564 : 1156 : rvcontext.nullinfo = NULL;
565 : : /* pass NULL for outer_hasSubLinks */
566 : 1156 : rvcontext.outer_hasSubLinks = NULL;
567 : 1156 : rvcontext.varno = rt_index;
568 : : /* this flag will be set below, if needed */
569 : 1156 : rvcontext.wrap_option = REPLACE_WRAP_NONE;
570 : : /* initialize cache array with indexes 0 .. length(tlist) */
571 : 1156 : 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 [ + + ]: 1156 : 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 [ + + ]: 1156 : if (parse->onConflict)
594 : : {
595 : 50 : save_exclRelTlist = parse->onConflict->exclRelTlist;
596 : 50 : parse->onConflict->exclRelTlist = NIL;
597 : : }
598 : :
599 : 1156 : parse = (Query *) pullup_replace_vars((Node *) parse, &rvcontext);
600 : :
601 [ + + ]: 1156 : if (parse->onConflict)
602 : 50 : parse->onConflict->exclRelTlist = save_exclRelTlist;
603 : : }
604 : :
605 : 366611 : 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 : 436313 : 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 [ + + ]: 436313 : if (parse->jointree->fromlist != NIL)
631 : 285080 : return;
632 : :
633 : : /* We mustn't change it in the top level of a setop tree, either */
634 [ + + ]: 151233 : if (parse->setOperations)
635 : 5469 : return;
636 : :
637 : : /* Create suitable RTE */
638 : 145764 : rte = makeNode(RangeTblEntry);
639 : 145764 : rte->rtekind = RTE_RESULT;
640 : 145764 : rte->eref = makeAlias("*RESULT*", NIL);
641 : :
642 : : /* Add it to rangetable */
643 : 145764 : parse->rtable = lappend(parse->rtable, rte);
644 : 145764 : rti = list_length(parse->rtable);
645 : :
646 : : /* And jam a reference into the jointree */
647 : 145764 : rtr = makeNode(RangeTblRef);
648 : 145764 : rtr->rtindex = rti;
649 : 145764 : 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 : 31754 : pull_up_sublinks(PlannerInfo *root)
682 : : {
683 : : Node *jtnode;
684 : : Relids relids;
685 : :
686 : : /* Begin recursion through the jointree */
687 : 31754 : jtnode = pull_up_sublinks_jointree_recurse(root,
688 : 31754 : (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 [ + + ]: 31754 : if (IsA(jtnode, FromExpr))
696 : 20147 : root->parse->jointree = (FromExpr *) jtnode;
697 : : else
698 : 11607 : root->parse->jointree = makeFromExpr(list_make1(jtnode), NULL);
699 : 31754 : }
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 : 109223 : 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 : 109223 : check_stack_depth();
713 : :
714 [ - + ]: 109223 : if (jtnode == NULL)
715 : : {
716 : 0 : *relids = NULL;
717 : : }
718 [ + + ]: 109223 : else if (IsA(jtnode, RangeTblRef))
719 : : {
720 : 61785 : int varno = ((RangeTblRef *) jtnode)->rtindex;
721 : :
722 : 61785 : *relids = bms_make_singleton(varno);
723 : : /* jtnode is returned unmodified */
724 : : }
725 [ + + ]: 47438 : else if (IsA(jtnode, FromExpr))
726 : : {
727 : 31945 : FromExpr *f = (FromExpr *) jtnode;
728 : 31945 : List *newfromlist = NIL;
729 : 31945 : Relids frelids = NULL;
730 : : FromExpr *newf;
731 : : Node *jtlink;
732 : : ListCell *l;
733 : :
734 : : /* First, recurse to process children and collect their relids */
735 [ + - + + : 66677 : foreach(l, f->fromlist)
+ + ]
736 : : {
737 : : Node *newchild;
738 : : Relids childrelids;
739 : :
740 : 34732 : newchild = pull_up_sublinks_jointree_recurse(root,
741 : 34732 : lfirst(l),
742 : : &childrelids);
743 : 34732 : newfromlist = lappend(newfromlist, newchild);
744 : 34732 : frelids = bms_join(frelids, childrelids);
745 : : }
746 : : /* Build the replacement FromExpr; no quals yet */
747 : 31945 : newf = makeFromExpr(newfromlist, NULL);
748 : : /* Set up a link representing the rebuilt jointree */
749 : 31945 : jtlink = (Node *) newf;
750 : : /* Now process qual --- all children are available for use */
751 : 31945 : 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 : 31945 : *relids = frelids;
765 : 31945 : jtnode = jtlink;
766 : : }
767 [ + - ]: 15493 : 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 : 15493 : j = palloc_object(JoinExpr);
779 : 15493 : memcpy(j, jtnode, sizeof(JoinExpr));
780 : 15493 : jtlink = (Node *) j;
781 : :
782 : : /* Recurse to process children and collect their relids */
783 : 15493 : j->larg = pull_up_sublinks_jointree_recurse(root, j->larg,
784 : : &leftrelids);
785 : 15493 : 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 [ + + + + : 15493 : switch (j->jointype)
- ]
801 : : {
802 : 7422 : case JOIN_INNER:
803 : 7422 : j->quals = pull_up_sublinks_qual_recurse(root, j->quals,
804 : : &jtlink,
805 : : bms_union(leftrelids,
806 : : rightrelids),
807 : : NULL, NULL);
808 : 7422 : break;
809 : 7971 : case JOIN_LEFT:
810 : 7971 : j->quals = pull_up_sublinks_qual_recurse(root, j->quals,
811 : : &j->rarg,
812 : : rightrelids,
813 : : NULL, NULL);
814 : 7971 : 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 : 15493 : *relids = bms_join(leftrelids, rightrelids);
839 [ + - ]: 15493 : if (j->rtindex)
840 : 15493 : *relids = bms_add_member(*relids, j->rtindex);
841 : 15493 : jtnode = jtlink;
842 : : }
843 : : else
844 [ # # ]: 0 : elog(ERROR, "unrecognized node type: %d",
845 : : (int) nodeTag(jtnode));
846 : 109223 : 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 : 127852 : pull_up_sublinks_qual_recurse(PlannerInfo *root, Node *node,
866 : : Node **jtlink1, Relids available_rels1,
867 : : Node **jtlink2, Relids available_rels2)
868 : : {
869 [ + + ]: 127852 : if (node == NULL)
870 : 4834 : return NULL;
871 [ + + ]: 123018 : if (IsA(node, SubLink))
872 : : {
873 : 4479 : SubLink *sublink = (SubLink *) node;
874 : : JoinExpr *j;
875 : : Relids child_rels;
876 : :
877 : : /* Is it a convertible ANY or EXISTS clause? */
878 [ + + ]: 4479 : if (sublink->subLinkType == ANY_SUBLINK)
879 : : {
880 : : ScalarArrayOpExpr *saop;
881 : :
882 [ + + ]: 3766 : if ((saop = convert_VALUES_to_ANY(root,
883 : : sublink->testexpr,
884 : 3766 : (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 [ + + ]: 3696 : 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 : 3609 : j->larg = *jtlink1;
898 : 3609 : *jtlink1 = (Node *) j;
899 : : /* Recursively process pulled-up jointree nodes */
900 : 3609 : 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 : 3609 : 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 : 3609 : 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 [ + + ]: 713 : else if (sublink->subLinkType == EXISTS_SUBLINK)
946 : : {
947 [ + + ]: 663 : 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 : 551 : j->larg = *jtlink1;
952 : 551 : *jtlink1 = (Node *) j;
953 : : /* Recursively process pulled-up jointree nodes */
954 : 551 : 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 : 551 : 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 : 551 : 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 [ + + ]: 118539 : if (is_notclause(node))
1003 : : {
1004 : : /* If the immediate argument of NOT is ANY or EXISTS, try to convert */
1005 : 14626 : SubLink *sublink = (SubLink *) get_notclausearg((Expr *) node);
1006 : : JoinExpr *j;
1007 : : Relids child_rels;
1008 : :
1009 [ + - + + ]: 14626 : if (sublink && IsA(sublink, SubLink))
1010 : : {
1011 [ + + ]: 7729 : 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 [ + - ]: 7509 : else if (sublink->subLinkType == EXISTS_SUBLINK)
1066 : : {
1067 [ + + ]: 7509 : 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 : 7500 : j->larg = *jtlink1;
1072 : 7500 : *jtlink1 = (Node *) j;
1073 : : /* Recursively process pulled-up jointree nodes */
1074 : 7500 : 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 : 7500 : 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 : 7500 : 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 : 7051 : return node;
1122 : : }
1123 [ + + ]: 103913 : if (is_andclause(node))
1124 : : {
1125 : : /* Recurse into AND clause */
1126 : 25408 : List *newclauses = NIL;
1127 : : ListCell *l;
1128 : :
1129 [ + - + + : 94091 : foreach(l, ((BoolExpr *) node)->args)
+ + ]
1130 : : {
1131 : 68683 : Node *oldclause = (Node *) lfirst(l);
1132 : : Node *newclause;
1133 : :
1134 : 68683 : newclause = pull_up_sublinks_qual_recurse(root,
1135 : : oldclause,
1136 : : jtlink1,
1137 : : available_rels1,
1138 : : jtlink2,
1139 : : available_rels2);
1140 [ + + ]: 68683 : if (newclause)
1141 : 58919 : newclauses = lappend(newclauses, newclause);
1142 : : }
1143 : : /* We might have got back fewer clauses than we started with */
1144 [ + + ]: 25408 : if (newclauses == NIL)
1145 : 68 : return NULL;
1146 [ + + ]: 25340 : else if (list_length(newclauses) == 1)
1147 : 917 : return (Node *) linitial(newclauses);
1148 : : else
1149 : 24423 : return (Node *) make_andclause(newclauses);
1150 : : }
1151 : : /* Stop if not an AND */
1152 : 78505 : 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 : 428220 : preprocess_function_rtes(PlannerInfo *root)
1185 : : {
1186 : : ListCell *rt;
1187 : :
1188 [ + - + + : 1120595 : foreach(rt, root->parse->rtable)
+ + ]
1189 : : {
1190 : 692379 : RangeTblEntry *rte = (RangeTblEntry *) lfirst(rt);
1191 : :
1192 [ + + ]: 692379 : if (rte->rtekind == RTE_FUNCTION)
1193 : : {
1194 : : Query *funcquery;
1195 : :
1196 : : /* Apply const-simplification */
1197 : 35771 : rte->functions = (List *)
1198 : 35771 : eval_const_expressions(root, (Node *) rte->functions);
1199 : :
1200 : : /* Check safety of expansion, and expand if possible */
1201 : 35771 : funcquery = inline_function_in_from(root, rte);
1202 [ + + ]: 35767 : 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 : 428216 : }
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 : 428216 : 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 : 856432 : root->parse->jointree = (FromExpr *)
1237 : 428216 : 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 : 428216 : }
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 : 1081129 : 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 : 1081129 : check_stack_depth();
1281 : : /* Also, since it's a bit expensive, let's check for query cancel. */
1282 [ + + ]: 1081129 : CHECK_FOR_INTERRUPTS();
1283 : :
1284 : : Assert(jtnode != NULL);
1285 [ + + ]: 1081129 : if (IsA(jtnode, RangeTblRef))
1286 : : {
1287 : 556341 : int varno = ((RangeTblRef *) jtnode)->rtindex;
1288 : 556341 : 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 [ + + + + ]: 606938 : if (rte->rtekind == RTE_SUBQUERY &&
1298 [ + + ]: 83966 : is_simple_subquery(root, rte->subquery, rte, lowest_outer_join) &&
1299 [ + + ]: 9169 : (containing_appendrel == NULL ||
1300 : 9169 : is_safe_append_member(rte->subquery)))
1301 : 29493 : 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 [ + + + + ]: 547952 : if (rte->rtekind == RTE_SUBQUERY &&
1315 : 21104 : is_simple_union_all(rte->subquery))
1316 : 4005 : 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 [ + + + - ]: 522843 : if (rte->rtekind == RTE_VALUES &&
1325 [ + - ]: 10702 : lowest_outer_join == NULL &&
1326 [ + + ]: 10702 : containing_appendrel == NULL &&
1327 : 10702 : is_simple_values(root, rte))
1328 : 3768 : return pull_up_simple_values(root, jtnode, rte);
1329 : :
1330 : : /*
1331 : : * Or perhaps it's a FUNCTION RTE that we could inline?
1332 : : */
1333 [ + + ]: 519075 : if (rte->rtekind == RTE_FUNCTION)
1334 : 35562 : return pull_up_constant_function(root, jtnode, rte,
1335 : : containing_appendrel);
1336 : :
1337 : : /* Otherwise, do nothing at this node. */
1338 : : }
1339 [ + + ]: 524788 : else if (IsA(jtnode, FromExpr))
1340 : : {
1341 : 441403 : FromExpr *f = (FromExpr *) jtnode;
1342 : : ListCell *l;
1343 : :
1344 : : Assert(containing_appendrel == NULL);
1345 : : /* Recursively transform all the child nodes */
1346 [ + + + + : 915355 : foreach(l, f->fromlist)
+ + ]
1347 : : {
1348 : 473952 : lfirst(l) = pull_up_subqueries_recurse(root, lfirst(l),
1349 : : lowest_outer_join,
1350 : : NULL);
1351 : : }
1352 : : }
1353 [ + - ]: 83385 : else if (IsA(jtnode, JoinExpr))
1354 : : {
1355 : 83385 : JoinExpr *j = (JoinExpr *) jtnode;
1356 : :
1357 : : Assert(containing_appendrel == NULL);
1358 : : /* Recurse, being careful to tell myself when inside outer join */
1359 [ + + + + : 83385 : switch (j->jointype)
- ]
1360 : : {
1361 : 35007 : case JOIN_INNER:
1362 : 35007 : j->larg = pull_up_subqueries_recurse(root, j->larg,
1363 : : lowest_outer_join,
1364 : : NULL);
1365 : 35007 : j->rarg = pull_up_subqueries_recurse(root, j->rarg,
1366 : : lowest_outer_join,
1367 : : NULL);
1368 : 35007 : break;
1369 : 46435 : case JOIN_LEFT:
1370 : : case JOIN_SEMI:
1371 : : case JOIN_ANTI:
1372 : 46435 : j->larg = pull_up_subqueries_recurse(root, j->larg,
1373 : : j,
1374 : : NULL);
1375 : 46435 : j->rarg = pull_up_subqueries_recurse(root, j->rarg,
1376 : : j,
1377 : : NULL);
1378 : 46435 : break;
1379 : 970 : case JOIN_FULL:
1380 : 970 : j->larg = pull_up_subqueries_recurse(root, j->larg,
1381 : : j,
1382 : : NULL);
1383 : 970 : j->rarg = pull_up_subqueries_recurse(root, j->rarg,
1384 : : j,
1385 : : NULL);
1386 : 970 : 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 : 1008301 : 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 : 29493 : pull_up_simple_subquery(PlannerInfo *root, Node *jtnode, RangeTblEntry *rte,
1421 : : JoinExpr *lowest_outer_join,
1422 : : AppendRelInfo *containing_appendrel)
1423 : : {
1424 : 29493 : Query *parse = root->parse;
1425 : 29493 : 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 : 29493 : 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 : 29493 : subroot = makeNode(PlannerInfo);
1447 : 29493 : subroot->parse = subquery;
1448 : 29493 : subroot->glob = root->glob;
1449 : 29493 : subroot->query_level = root->query_level;
1450 : 29493 : subroot->plan_name = root->plan_name;
1451 : 29493 : subroot->alternative_plan_name = root->alternative_plan_name;
1452 : 29493 : subroot->parent_root = root->parent_root;
1453 : 29493 : subroot->plan_params = NIL;
1454 : 29493 : subroot->outer_params = NULL;
1455 : 29493 : subroot->planner_cxt = CurrentMemoryContext;
1456 : 29493 : subroot->init_plans = NIL;
1457 : 29493 : subroot->cte_plan_ids = NIL;
1458 : 29493 : subroot->multiexpr_params = NIL;
1459 : 29493 : subroot->join_domains = NIL;
1460 : 29493 : subroot->eq_classes = NIL;
1461 : 29493 : subroot->ec_merging_done = false;
1462 : 29493 : subroot->last_rinfo_serial = 0;
1463 : 29493 : subroot->all_result_relids = NULL;
1464 : 29493 : subroot->leaf_result_relids = NULL;
1465 : 29493 : subroot->append_rel_list = NIL;
1466 : 29493 : subroot->row_identity_vars = NIL;
1467 : 29493 : subroot->rowMarks = NIL;
1468 : 29493 : memset(subroot->upper_rels, 0, sizeof(subroot->upper_rels));
1469 : 29493 : memset(subroot->upper_targets, 0, sizeof(subroot->upper_targets));
1470 : 29493 : subroot->processed_groupClause = NIL;
1471 : 29493 : subroot->processed_distinctClause = NIL;
1472 : 29493 : subroot->processed_tlist = NIL;
1473 : 29493 : subroot->update_colnos = NIL;
1474 : 29493 : subroot->grouping_map = NULL;
1475 : 29493 : subroot->minmax_aggs = NIL;
1476 : 29493 : subroot->qual_security_level = 0;
1477 : 29493 : subroot->placeholdersFrozen = false;
1478 : 29493 : subroot->hasRecursion = false;
1479 : 29493 : subroot->assumeReplanning = false;
1480 : 29493 : subroot->wt_param_id = -1;
1481 : 29493 : 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 : 29493 : 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 : 29493 : 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 [ + + ]: 29493 : 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 : 29493 : 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 : 29493 : 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 [ + + + + ]: 34658 : if (is_simple_subquery(root, subquery, rte, lowest_outer_join) &&
1537 [ + + ]: 5293 : (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 : 29355 : subquery->targetList = (List *)
1564 : 29355 : flatten_join_alias_vars(subroot, subroot->parse,
1565 : 29355 : (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 : 29355 : rtoffset = list_length(parse->rtable);
1573 : 29355 : OffsetVarNodes((Node *) subquery, rtoffset, 0);
1574 : 29355 : 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 : 29355 : IncrementVarSublevelsUp((Node *) subquery, -1, 1);
1581 : 29355 : 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 : 29355 : rvcontext.root = root;
1591 : 29355 : rvcontext.targetlist = subquery->targetList;
1592 : 29355 : rvcontext.target_rte = rte;
1593 : 29355 : rvcontext.result_relation = 0;
1594 [ + + ]: 29355 : if (rte->lateral)
1595 : : {
1596 : 1390 : rvcontext.relids = get_relids_in_jointree((Node *) subquery->jointree,
1597 : : true, true);
1598 : 1390 : rvcontext.nullinfo = get_nullingrels(parse);
1599 : : }
1600 : : else /* won't need these values */
1601 : : {
1602 : 27965 : rvcontext.relids = NULL;
1603 : 27965 : rvcontext.nullinfo = NULL;
1604 : : }
1605 : 29355 : rvcontext.outer_hasSubLinks = &parse->hasSubLinks;
1606 : 29355 : rvcontext.varno = varno;
1607 : : /* this flag will be set below, if needed */
1608 : 29355 : rvcontext.wrap_option = REPLACE_WRAP_NONE;
1609 : : /* initialize cache array with indexes 0 .. length(tlist) */
1610 : 29355 : 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 [ + + ]: 29355 : 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 : 29355 : 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 [ + + ]: 29355 : if (rte->lateral)
1640 : : {
1641 [ + - + + : 3682 : foreach(lc, subquery->rtable)
+ + ]
1642 : : {
1643 : 2292 : RangeTblEntry *child_rte = (RangeTblEntry *) lfirst(lc);
1644 : :
1645 [ + + + - : 2292 : 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 : 452 : 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 : 452 : 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 : 29355 : 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 : 29355 : 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 [ + + + + ]: 29355 : if (root->glob->lastPHId != 0 || root->append_rel_list)
1698 : : {
1699 : : Relids subrelids;
1700 : :
1701 : 6958 : subrelids = get_relids_in_jointree((Node *) subquery->jointree,
1702 : : true, false);
1703 [ + + ]: 6958 : if (root->glob->lastPHId != 0)
1704 : 1823 : substitute_phv_relids((Node *) parse, varno, subrelids);
1705 : 6958 : fix_append_rel_relids(root, varno, subrelids);
1706 : : }
1707 : :
1708 : : /*
1709 : : * And now add subquery's AppendRelInfos to our list.
1710 : : */
1711 : 58710 : root->append_rel_list = list_concat(root->append_rel_list,
1712 : 29355 : 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 : 29355 : 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 : 29355 : parse->hasSubLinks |= subquery->hasSubLinks;
1741 : :
1742 : : /* If subquery had any RLS conditions, now main query does too */
1743 : 29355 : 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 [ + + + + ]: 54229 : if (subquery->jointree->quals == NULL &&
1758 : 24874 : list_length(subquery->jointree->fromlist) == 1)
1759 : 24611 : return (Node *) linitial(subquery->jointree->fromlist);
1760 : :
1761 : 4744 : 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 : 4005 : pull_up_simple_union_all(PlannerInfo *root, Node *jtnode, RangeTblEntry *rte)
1775 : : {
1776 : 4005 : int varno = ((RangeTblRef *) jtnode)->rtindex;
1777 : 4005 : Query *subquery = rte->subquery;
1778 : 4005 : 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 : 4005 : 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 : 4005 : 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 [ + + ]: 4005 : 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 : 4005 : 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 : 4005 : pull_up_union_leaf_queries(subquery->setOperations, root, varno, subquery,
1827 : : rtoffset);
1828 : :
1829 : : /*
1830 : : * Mark the parent as an append relation.
1831 : : */
1832 : 4005 : rte->inh = true;
1833 : :
1834 : 4005 : 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 : 19826 : pull_up_union_leaf_queries(Node *setOp, PlannerInfo *root, int parentRTindex,
1857 : : Query *setOpQuery, int childRToffset)
1858 : : {
1859 [ + + ]: 19826 : if (IsA(setOp, RangeTblRef))
1860 : : {
1861 : 12191 : RangeTblRef *rtr = (RangeTblRef *) setOp;
1862 : : int childRTindex;
1863 : : AppendRelInfo *appinfo;
1864 : :
1865 : : /*
1866 : : * Calculate the index in the parent's range table
1867 : : */
1868 : 12191 : childRTindex = childRToffset + rtr->rtindex;
1869 : :
1870 : : /*
1871 : : * Build a suitable AppendRelInfo, and attach to parent's list.
1872 : : */
1873 : 12191 : appinfo = makeNode(AppendRelInfo);
1874 : 12191 : appinfo->parent_relid = parentRTindex;
1875 : 12191 : appinfo->child_relid = childRTindex;
1876 : 12191 : appinfo->parent_reltype = InvalidOid;
1877 : 12191 : appinfo->child_reltype = InvalidOid;
1878 : 12191 : make_setop_translation_list(setOpQuery, childRTindex, appinfo);
1879 : 12191 : appinfo->parent_reloid = InvalidOid;
1880 : 12191 : 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 : 12191 : rtr = makeNode(RangeTblRef);
1896 : 12191 : rtr->rtindex = childRTindex;
1897 : 12191 : (void) pull_up_subqueries_recurse(root, (Node *) rtr,
1898 : : NULL, appinfo);
1899 : : }
1900 [ + - ]: 7635 : else if (IsA(setOp, SetOperationStmt))
1901 : : {
1902 : 7635 : SetOperationStmt *op = (SetOperationStmt *) setOp;
1903 : :
1904 : : /* Recurse to reach leaf queries */
1905 : 7635 : pull_up_union_leaf_queries(op->larg, root, parentRTindex, setOpQuery,
1906 : : childRToffset);
1907 : 7635 : 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 : 19826 : }
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 : 12191 : make_setop_translation_list(Query *query, int newvarno,
1927 : : AppendRelInfo *appinfo)
1928 : : {
1929 : 12191 : 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 : 12191 : appinfo->num_child_cols = list_length(query->targetList);
1936 : 12191 : appinfo->parent_colnos = pcolnos = palloc0_array(AttrNumber, appinfo->num_child_cols);
1937 : :
1938 [ + + + + : 48600 : foreach(l, query->targetList)
+ + ]
1939 : : {
1940 : 36409 : TargetEntry *tle = (TargetEntry *) lfirst(l);
1941 : :
1942 [ - + ]: 36409 : if (tle->resjunk)
1943 : 0 : continue;
1944 : :
1945 : 36409 : vars = lappend(vars, makeVarFromTargetEntry(newvarno, tle));
1946 : 36409 : pcolnos[tle->resno - 1] = tle->resno;
1947 : : }
1948 : :
1949 : 12191 : appinfo->translated_vars = vars;
1950 : 12191 : }
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 : 80090 : 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 [ + - ]: 80090 : if (!IsA(subquery, Query) ||
1970 [ - + ]: 80090 : 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 [ + + ]: 80090 : if (subquery->setOperations)
1979 : 4713 : 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 [ + + ]: 75377 : if (subquery->hasAggs ||
1992 [ + + ]: 73847 : subquery->hasWindowFuncs ||
1993 [ + + ]: 73437 : subquery->hasTargetSRFs ||
1994 [ + + ]: 69768 : subquery->groupClause ||
1995 [ + + ]: 69684 : subquery->groupingSets ||
1996 [ + - ]: 69654 : subquery->havingQual ||
1997 [ + + ]: 69654 : subquery->sortClause ||
1998 [ + + ]: 68877 : subquery->distinctClause ||
1999 [ + + ]: 68219 : subquery->limitOffset ||
2000 [ + + ]: 67834 : subquery->limitCount ||
2001 [ + + ]: 67550 : subquery->hasForUpdate ||
2002 [ + + ]: 64276 : subquery->cteList)
2003 : 11246 : 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 [ + + ]: 64131 : if (rte->security_barrier)
2011 : 1029 : return false;
2012 : :
2013 : : /*
2014 : : * If the subquery is LATERAL, check for pullup restrictions from that.
2015 : : */
2016 [ + + ]: 63102 : 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 [ + + ]: 3502 : if (lowest_outer_join != NULL)
2031 : : {
2032 : 1038 : restricted = true;
2033 : 1038 : 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 [ + + ]: 3502 : if (jointree_contains_lateral_outer_refs(root,
2043 : 3502 : (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 [ + + ]: 3482 : if (lowest_outer_join != NULL)
2064 : : {
2065 : 1038 : Relids lvarnos = pull_varnos_of_level(root,
2066 : 1038 : (Node *) subquery->targetList,
2067 : : 1);
2068 : :
2069 [ + + ]: 1038 : 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 [ + + ]: 63072 : if (contain_volatile_functions((Node *) subquery->targetList))
2083 : 220 : return false;
2084 : :
2085 : 62852 : 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 : 3768 : pull_up_simple_values(PlannerInfo *root, Node *jtnode, RangeTblEntry *rte)
2104 : : {
2105 : 3768 : Query *parse = root->parse;
2106 : 3768 : 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 : 3768 : 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 : 3768 : tlist = NIL;
2133 : 3768 : attrno = 1;
2134 [ + + + + : 8057 : foreach(lc, values_list)
+ + ]
2135 : : {
2136 : 4289 : tlist = lappend(tlist,
2137 : 4289 : makeTargetEntry((Expr *) lfirst(lc),
2138 : : attrno,
2139 : : NULL,
2140 : : false));
2141 : 4289 : attrno++;
2142 : : }
2143 : 3768 : rvcontext.root = root;
2144 : 3768 : rvcontext.targetlist = tlist;
2145 : 3768 : rvcontext.target_rte = rte;
2146 : 3768 : rvcontext.result_relation = 0;
2147 : 3768 : rvcontext.relids = NULL; /* can't be any lateral references here */
2148 : 3768 : rvcontext.nullinfo = NULL;
2149 : 3768 : rvcontext.outer_hasSubLinks = &parse->hasSubLinks;
2150 : 3768 : rvcontext.varno = varno;
2151 : 3768 : rvcontext.wrap_option = REPLACE_WRAP_NONE;
2152 : : /* initialize cache array with indexes 0 .. length(tlist) */
2153 : 3768 : 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 : 3768 : 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 : 3768 : rte = makeNode(RangeTblEntry);
2179 : 3768 : rte->rtekind = RTE_RESULT;
2180 : 3768 : rte->eref = makeAlias("*RESULT*", NIL);
2181 : :
2182 : : /* Replace rangetable */
2183 : 3768 : 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 : 3768 : 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 : 10702 : 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 [ + + ]: 10702 : if (list_length(rte->values_lists) != 1)
2209 : 6934 : 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 [ + - - + ]: 7536 : if (expression_returns_set((Node *) rte->values_lists) ||
2223 : 3768 : 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 [ + - ]: 3768 : if (list_length(root->parse->rtable) != 1 ||
2233 [ - + ]: 3768 : rte != (RangeTblEntry *) linitial(root->parse->rtable))
2234 : 0 : return false;
2235 : :
2236 : 3768 : 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 : 35562 : pull_up_constant_function(PlannerInfo *root, Node *jtnode,
2259 : : RangeTblEntry *rte,
2260 : : AppendRelInfo *containing_appendrel)
2261 : : {
2262 : 35562 : 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 [ + + ]: 35562 : if (rte->funcordinality)
2271 : 761 : return jtnode;
2272 : :
2273 : : /* Fail if RTE isn't a single, simple Const expr */
2274 [ + + ]: 34801 : if (list_length(rte->functions) != 1)
2275 : 72 : return jtnode;
2276 : 34729 : rtf = linitial_node(RangeTblFunction, rte->functions);
2277 [ + + ]: 34729 : if (!IsA(rtf->funcexpr, Const))
2278 : 34419 : 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 : 21104 : is_simple_union_all(Query *subquery)
2370 : : {
2371 : : SetOperationStmt *topop;
2372 : :
2373 : : /* Let's just make sure it's a valid subselect ... */
2374 [ + - ]: 21104 : if (!IsA(subquery, Query) ||
2375 [ - + ]: 21104 : subquery->commandType != CMD_SELECT)
2376 [ # # ]: 0 : elog(ERROR, "subquery is bogus");
2377 : :
2378 : : /* Is it a set-operation query at all? */
2379 : 21104 : topop = castNode(SetOperationStmt, subquery->setOperations);
2380 [ + + ]: 21104 : if (!topop)
2381 : 16391 : return false;
2382 : :
2383 : : /* Can't handle ORDER BY, LIMIT/OFFSET, locking, or WITH */
2384 [ + + ]: 4713 : if (subquery->sortClause ||
2385 [ + - ]: 4661 : subquery->limitOffset ||
2386 [ + - ]: 4661 : subquery->limitCount ||
2387 [ + - ]: 4661 : subquery->rowMarks ||
2388 [ + + ]: 4661 : subquery->cteList)
2389 : 162 : return false;
2390 : :
2391 : : /* Recursively check the tree of set operations */
2392 : 4551 : return is_simple_union_all_recurse((Node *) topop, subquery,
2393 : : topop->colTypes);
2394 : : }
2395 : :
2396 : : static bool
2397 : 25893 : 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 : 25893 : check_stack_depth();
2401 : :
2402 [ + + ]: 25893 : if (IsA(setOp, RangeTblRef))
2403 : : {
2404 : 12946 : RangeTblRef *rtr = (RangeTblRef *) setOp;
2405 : 12946 : RangeTblEntry *rte = rt_fetch(rtr->rtindex, setOpQuery->rtable);
2406 : 12946 : 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 : 12946 : return tlist_same_datatypes(subquery->targetList, colTypes, true);
2413 : : }
2414 [ + - ]: 12947 : else if (IsA(setOp, SetOperationStmt))
2415 : : {
2416 : 12947 : SetOperationStmt *op = (SetOperationStmt *) setOp;
2417 : :
2418 : : /* Must be UNION ALL */
2419 [ + + + + ]: 12947 : if (op->op != SETOP_UNION || !op->all)
2420 : 4362 : return false;
2421 : :
2422 : : /* Recurse to check inputs */
2423 [ + + + + ]: 16514 : return is_simple_union_all_recurse(op->larg, setOpQuery, colTypes) &&
2424 : 7929 : 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 : 14462 : 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 : 14462 : jtnode = subquery->jointree;
2458 : : Assert(IsA(jtnode, FromExpr));
2459 : : /* Check the completely-empty case */
2460 [ + + + + ]: 14462 : if (jtnode->fromlist == NIL && jtnode->quals == NULL)
2461 : 569 : return true;
2462 : : /* Check the more general case */
2463 [ + + ]: 24717 : while (IsA(jtnode, FromExpr))
2464 : : {
2465 [ + + ]: 13903 : if (jtnode->quals != NULL)
2466 : 3079 : return false;
2467 [ - + ]: 10824 : if (list_length(jtnode->fromlist) != 1)
2468 : 0 : return false;
2469 : 10824 : jtnode = linitial(jtnode->fromlist);
2470 : : }
2471 [ + + ]: 10814 : if (!IsA(jtnode, RangeTblRef))
2472 : 925 : return false;
2473 : :
2474 : 9889 : 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 : 10289 : jointree_contains_lateral_outer_refs(PlannerInfo *root, Node *jtnode,
2489 : : bool restricted,
2490 : : Relids safe_upper_varnos)
2491 : : {
2492 [ - + ]: 10289 : if (jtnode == NULL)
2493 : 0 : return false;
2494 [ + + ]: 10289 : if (IsA(jtnode, RangeTblRef))
2495 : 6488 : return false;
2496 [ + + ]: 3801 : else if (IsA(jtnode, FromExpr))
2497 : : {
2498 : 3542 : FromExpr *f = (FromExpr *) jtnode;
2499 : : ListCell *l;
2500 : :
2501 : : /* First, recurse to check child joins */
2502 [ + + + + : 9791 : foreach(l, f->fromlist)
+ + ]
2503 : : {
2504 [ + + ]: 6269 : if (jointree_contains_lateral_outer_refs(root,
2505 : 6269 : lfirst(l),
2506 : : restricted,
2507 : : safe_upper_varnos))
2508 : 20 : return true;
2509 : : }
2510 : :
2511 : : /* Then check the top-level quals */
2512 [ + + ]: 3522 : if (restricted &&
2513 [ - + ]: 1078 : !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 : 3761 : 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 : 33398 : perform_pullup_replace_vars(PlannerInfo *root,
2564 : : pullup_replace_vars_context *rvcontext,
2565 : : AppendRelInfo *containing_appendrel)
2566 : : {
2567 : 33398 : 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 [ + + ]: 33398 : if (containing_appendrel)
2578 : : {
2579 : 5165 : ReplaceWrapOption save_wrap_option = rvcontext->wrap_option;
2580 : :
2581 : 5165 : rvcontext->wrap_option = REPLACE_WRAP_NONE;
2582 : 5165 : containing_appendrel->translated_vars = (List *)
2583 : 5165 : pullup_replace_vars((Node *) containing_appendrel->translated_vars,
2584 : : rvcontext);
2585 : 5165 : rvcontext->wrap_option = save_wrap_option;
2586 : 5165 : 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 : 28233 : parse->targetList = (List *)
2599 : 28233 : pullup_replace_vars((Node *) parse->targetList, rvcontext);
2600 : 28233 : parse->returningList = (List *)
2601 : 28233 : pullup_replace_vars((Node *) parse->returningList, rvcontext);
2602 : :
2603 [ + + ]: 28233 : 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 [ + + ]: 28233 : 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 : 28233 : parse->mergeJoinCondition = pullup_replace_vars(parse->mergeJoinCondition,
2629 : : rvcontext);
2630 : 28233 : replace_vars_in_jointree((Node *) parse->jointree, rvcontext);
2631 : : Assert(parse->setOperations == NULL);
2632 : 28233 : parse->havingQual = pullup_replace_vars(parse->havingQual, rvcontext);
2633 : :
2634 : : /*
2635 : : * Replace references in the translated_vars lists of appendrels.
2636 : : */
2637 [ + + + + : 28303 : 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 [ + - + + : 79405 : foreach(lc, parse->rtable)
+ + ]
2650 : : {
2651 : 51172 : RangeTblEntry *otherrte = (RangeTblEntry *) lfirst(lc);
2652 : :
2653 [ + + ]: 51172 : if (otherrte->rtekind == RTE_JOIN)
2654 : 5619 : otherrte->joinaliasvars = (List *)
2655 : 5619 : pullup_replace_vars((Node *) otherrte->joinaliasvars,
2656 : : rvcontext);
2657 [ + + ]: 45553 : 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 : 74306 : replace_vars_in_jointree(Node *jtnode,
2671 : : pullup_replace_vars_context *context)
2672 : : {
2673 [ - + ]: 74306 : if (jtnode == NULL)
2674 : 0 : return;
2675 [ + + ]: 74306 : 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 : 37276 : int varno = ((RangeTblRef *) jtnode)->rtindex;
2685 : :
2686 [ + + ]: 37276 : if (varno != context->varno) /* ignore target subquery itself */
2687 : : {
2688 : 9043 : RangeTblEntry *rte = rt_fetch(varno, context->root->parse->rtable);
2689 : :
2690 : : Assert(rte != context->target_rte);
2691 [ + + ]: 9043 : 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 [ + + ]: 37030 : else if (IsA(jtnode, FromExpr))
2739 : : {
2740 : 30442 : FromExpr *f = (FromExpr *) jtnode;
2741 : : ListCell *l;
2742 : :
2743 [ + - + + : 63339 : foreach(l, f->fromlist)
+ + ]
2744 : 32897 : replace_vars_in_jointree(lfirst(l), context);
2745 : 30442 : f->quals = pullup_replace_vars(f->quals, context);
2746 : : }
2747 [ + - ]: 6588 : else if (IsA(jtnode, JoinExpr))
2748 : : {
2749 : 6588 : JoinExpr *j = (JoinExpr *) jtnode;
2750 : 6588 : ReplaceWrapOption save_wrap_option = context->wrap_option;
2751 : :
2752 : 6588 : replace_vars_in_jointree(j->larg, context);
2753 : 6588 : 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 [ + + ]: 6588 : if (j->jointype == JOIN_FULL)
2763 : 525 : context->wrap_option = REPLACE_WRAP_VARFREE;
2764 : :
2765 : 6588 : j->quals = pullup_replace_vars(j->quals, context);
2766 : :
2767 : 6588 : 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 : 165937 : pullup_replace_vars(Node *expr, pullup_replace_vars_context *context)
2782 : : {
2783 : 165937 : 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 : 97456 : pullup_replace_vars_callback(const Var *var,
2792 : : replace_rte_variables_context *context)
2793 : : {
2794 : 97456 : pullup_replace_vars_context *rcon = (pullup_replace_vars_context *) context->callback_arg;
2795 : 97456 : int varattno = var->varattno;
2796 : : bool need_phv;
2797 : : Node *newnode;
2798 : :
2799 : : /* System columns are not replaced. */
2800 [ + + ]: 97456 : 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 [ + + ]: 185075 : need_phv = (var->varnullingrels != NULL) ||
2811 [ + + ]: 87654 : (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 [ + + + - ]: 97421 : if (need_phv &&
2826 [ + - ]: 11725 : varattno >= InvalidAttrNumber &&
2827 : 11725 : varattno <= list_length(rcon->targetlist) &&
2828 [ + + ]: 11725 : rcon->rv_cache[varattno] != NULL)
2829 : : {
2830 : : /* Just copy the entry and fall through to adjust phlevelsup etc */
2831 : 2520 : 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 : 94901 : 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 [ + + ]: 94901 : if (need_phv)
2848 : : {
2849 : : bool wrap;
2850 : :
2851 [ + + ]: 9205 : 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 [ + + ]: 8298 : 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 [ + - + + ]: 8243 : else if (newnode && IsA(newnode, Var) &&
2869 [ + + ]: 6578 : ((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 : 6566 : wrap = false;
2878 [ + + ]: 6566 : 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 [ + - + + ]: 1677 : 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 : 1527 : bool contain_nullable_vars = false;
2958 : :
2959 [ + + ]: 1527 : if (!rcon->target_rte->lateral)
2960 : : {
2961 [ + + ]: 1337 : 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 [ + + ]: 1527 : 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 : 1287 : wrap = true;
3000 : : }
3001 : : }
3002 : :
3003 [ + + ]: 9205 : if (wrap)
3004 : : {
3005 : : newnode = (Node *)
3006 : 2359 : 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 [ + - + - ]: 4718 : if (varattno >= InvalidAttrNumber &&
3015 : 2359 : varattno <= list_length(rcon->targetlist))
3016 : 2359 : rcon->rv_cache[varattno] = copyObject(newnode);
3017 : : }
3018 : : }
3019 : : }
3020 : :
3021 : : /* Propagate any varnullingrels into the replacement expression */
3022 [ + + ]: 97421 : if (var->varnullingrels != NULL)
3023 : : {
3024 [ + + ]: 9767 : if (IsA(newnode, Var))
3025 : : {
3026 : 6097 : Var *newvar = (Var *) newnode;
3027 : :
3028 : : Assert(newvar->varlevelsup == 0);
3029 : 6097 : newvar->varnullingrels = bms_add_members(newvar->varnullingrels,
3030 : 6097 : var->varnullingrels);
3031 : : }
3032 [ + + ]: 3670 : else if (IsA(newnode, PlaceHolderVar))
3033 : : {
3034 : 3430 : PlaceHolderVar *newphv = (PlaceHolderVar *) newnode;
3035 : :
3036 : : Assert(newphv->phlevelsup == 0);
3037 : 3430 : newphv->phnullingrels = bms_add_members(newphv->phnullingrels,
3038 : 3430 : 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 [ + + ]: 97421 : if (var->varlevelsup > 0)
3101 : 899 : IncrementVarSublevelsUp(newnode, var->varlevelsup, 0);
3102 : :
3103 : 97421 : 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 : 5469 : flatten_simple_union_all(PlannerInfo *root)
3142 : : {
3143 : 5469 : 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 : 5469 : topop = castNode(SetOperationStmt, parse->setOperations);
3154 : : Assert(topop);
3155 : :
3156 : : /* Can't optimize away a recursive UNION */
3157 [ + + ]: 5469 : if (root->hasRecursion)
3158 : 641 : return;
3159 : :
3160 : : /*
3161 : : * Recursively check the tree of set operations. If not all UNION ALL
3162 : : * with identical column types, punt.
3163 : : */
3164 [ + + ]: 4828 : if (!is_simple_union_all_recurse((Node *) topop, parse, topop->colTypes))
3165 : 4277 : 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 : 551 : leftmostjtnode = topop->larg;
3172 [ + - + + ]: 789 : while (leftmostjtnode && IsA(leftmostjtnode, SetOperationStmt))
3173 : 238 : leftmostjtnode = ((SetOperationStmt *) leftmostjtnode)->larg;
3174 : : Assert(leftmostjtnode && IsA(leftmostjtnode, RangeTblRef));
3175 : 551 : leftmostRTI = ((RangeTblRef *) leftmostjtnode)->rtindex;
3176 : 551 : 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 : 551 : childRTE = copyObject(leftmostRTE);
3187 : 551 : parse->rtable = lappend(parse->rtable, childRTE);
3188 : 551 : childRTI = list_length(parse->rtable);
3189 : :
3190 : : /* Modify the setops tree to reference the child copy */
3191 : 551 : ((RangeTblRef *) leftmostjtnode)->rtindex = childRTI;
3192 : :
3193 : : /* Modify the formerly-leftmost RTE to mark it as an appendrel parent */
3194 : 551 : 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 : 551 : rtr = makeNode(RangeTblRef);
3201 : 551 : rtr->rtindex = leftmostRTI;
3202 : : Assert(parse->jointree->fromlist == NIL);
3203 : 551 : 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 : 551 : 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 : 551 : 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 is removed
3250 : : * at the end of this phase; see remove_redundant_nullability_quals.
3251 : : *
3252 : : * A whole-row Var works too. "WHERE b IS NULL" in row-format semantics is
3253 : : * true when b's whole-row value is NULL or when every column of b is NULL;
3254 : : * for a matching row only the latter is possible, so proving any one column
3255 : : * of b non-null in matching rows justifies the same reduction.
3256 : : *
3257 : : * The same recognition reduces a FULL join to an anti-semijoin when a
3258 : : * forced-null Var on either side is proven non-null: only the other side's
3259 : : * unmatched rows can survive. If that surviving side is the right-hand
3260 : : * input, we switch the inputs (as we do for JOIN_RIGHT below) so that it
3261 : : * ends up on the left, where JOIN_ANTI requires the surviving side to be.
3262 : : *
3263 : : * Also, we get rid of JOIN_RIGHT cases by flipping them around to become
3264 : : * JOIN_LEFT. This saves some code here and in some later planner routines;
3265 : : * the main benefit is to reduce the number of jointypes that can appear in
3266 : : * SpecialJoinInfo nodes. Note that we can still generate Paths and Plans
3267 : : * that use JOIN_RIGHT (or JOIN_RIGHT_ANTI) by switching the inputs again.
3268 : : *
3269 : : * To ease recognition of strict qual clauses, we require this routine to be
3270 : : * run after expression preprocessing (i.e., qual canonicalization and JOIN
3271 : : * alias-var expansion).
3272 : : */
3273 : : void
3274 : 25435 : reduce_outer_joins(PlannerInfo *root)
3275 : : {
3276 : : reduce_outer_joins_pass1_state *state1;
3277 : : reduce_outer_joins_pass2_state state2;
3278 : : ListCell *lc;
3279 : :
3280 : : /*
3281 : : * To avoid doing strictness checks on more quals than necessary, we want
3282 : : * to stop descending the jointree as soon as there are no outer joins
3283 : : * below our current point. This consideration forces a two-pass process.
3284 : : * The first pass gathers information about which base rels appear below
3285 : : * each side of each join clause, about whether there are outer join(s)
3286 : : * below each side of each join clause, and about which base rels are from
3287 : : * the nullable side of those outer join(s). The second pass examines
3288 : : * qual clauses and changes join types as it descends the tree.
3289 : : */
3290 : 25435 : state1 = reduce_outer_joins_pass1((Node *) root->parse->jointree);
3291 : :
3292 : : /* planner.c shouldn't have called me if no outer joins */
3293 [ + - - + ]: 25435 : if (state1 == NULL || !state1->contains_outer)
3294 [ # # ]: 0 : elog(ERROR, "so where are the outer joins?");
3295 : :
3296 : 25435 : state2.inner_reduced = NULL;
3297 : 25435 : state2.partial_reduced = NIL;
3298 : 25435 : state2.anti_reduced = NULL;
3299 : :
3300 : 25435 : 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 [ + + ]: 25435 : if (!bms_is_empty(state2.inner_reduced))
3311 : : {
3312 : 2171 : root->parse = (Query *)
3313 : 2171 : remove_nulling_relids((Node *) root->parse,
3314 : 2171 : state2.inner_reduced,
3315 : : NULL);
3316 : : /* There could be references in the append_rel_list, too */
3317 : 2171 : root->append_rel_list = (List *)
3318 : 2171 : remove_nulling_relids((Node *) root->append_rel_list,
3319 : 2171 : 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 [ + + + + : 25554 : foreach(lc, state2.partial_reduced)
+ + ]
3328 : : {
3329 : 119 : reduce_outer_joins_partial_state *statep = lfirst(lc);
3330 : 119 : Relids full_join_relids = bms_make_singleton(statep->full_join_rti);
3331 : :
3332 : 119 : root->parse = (Query *)
3333 : 119 : remove_nulling_relids((Node *) root->parse,
3334 : : full_join_relids,
3335 : 119 : statep->unreduced_side);
3336 : 119 : root->append_rel_list = (List *)
3337 : 119 : remove_nulling_relids((Node *) root->append_rel_list,
3338 : : full_join_relids,
3339 : 119 : statep->unreduced_side);
3340 : : }
3341 : :
3342 : : /*
3343 : : * Finally, remove any quals made redundant by reducing outer joins to
3344 : : * antijoins.
3345 : : */
3346 [ + + ]: 25435 : if (!bms_is_empty(state2.anti_reduced))
3347 : 1097 : remove_redundant_nullability_quals((Node *) root->parse->jointree,
3348 : : state2.anti_reduced);
3349 : 25435 : }
3350 : :
3351 : : /*
3352 : : * remove_redundant_nullability_quals
3353 : : * Remove quals made redundant by reducing outer joins to antijoins.
3354 : : *
3355 : : * An IS NULL qual on a Var from the nullable side of a lower antijoin is
3356 : : * necessarily true. Keeping such a qual would not be wrong, but it would
3357 : : * generate bogus selectivity estimates, and it could prevent join removal
3358 : : * from later removing the rel(s) it references.
3359 : : */
3360 : : static void
3361 : 4653 : remove_redundant_nullability_quals(Node *jtnode, Relids antijoins)
3362 : : {
3363 [ - + ]: 4653 : if (jtnode == NULL)
3364 : 0 : return;
3365 [ + + ]: 4653 : if (IsA(jtnode, RangeTblRef))
3366 : : {
3367 : : /* nothing to do here */
3368 : : }
3369 [ + + ]: 2329 : else if (IsA(jtnode, FromExpr))
3370 : : {
3371 : 1107 : FromExpr *f = (FromExpr *) jtnode;
3372 : : ListCell *l;
3373 : :
3374 [ + - + + : 2219 : foreach(l, f->fromlist)
+ + ]
3375 : 1112 : remove_redundant_nullability_quals(lfirst(l), antijoins);
3376 : 1107 : f->quals = strip_redundant_nullability_quals(f->quals, antijoins);
3377 : : }
3378 [ + - ]: 1222 : else if (IsA(jtnode, JoinExpr))
3379 : : {
3380 : 1222 : JoinExpr *j = (JoinExpr *) jtnode;
3381 : :
3382 : 1222 : remove_redundant_nullability_quals(j->larg, antijoins);
3383 : 1222 : remove_redundant_nullability_quals(j->rarg, antijoins);
3384 : 1222 : j->quals = strip_redundant_nullability_quals(j->quals, antijoins);
3385 : : }
3386 : : else
3387 [ # # ]: 0 : elog(ERROR, "unrecognized jointree node type: %d",
3388 : : (int) nodeTag(jtnode));
3389 : : }
3390 : :
3391 : : /*
3392 : : * strip_redundant_nullability_quals
3393 : : * Strip redundant IS NULL quals from one implicit-AND qual list.
3394 : : */
3395 : : static Node *
3396 : 2329 : strip_redundant_nullability_quals(Node *quals, Relids antijoins)
3397 : : {
3398 : 2329 : List *newquals = NIL;
3399 : :
3400 [ + + + + : 8434 : foreach_ptr(Node, clause, castNode(List, quals))
+ + ]
3401 : : {
3402 : 3776 : Var *var = find_forced_null_var(clause);
3403 : :
3404 [ + + + + ]: 3776 : if (var && bms_overlap(var->varnullingrels, antijoins))
3405 : 1112 : continue;
3406 : 2664 : newquals = lappend(newquals, clause);
3407 : : }
3408 : 2329 : return (Node *) newquals;
3409 : : }
3410 : :
3411 : : /*
3412 : : * reduce_outer_joins_pass1 - phase 1 data collection
3413 : : *
3414 : : * Returns a state node describing the given jointree node.
3415 : : */
3416 : : static reduce_outer_joins_pass1_state *
3417 : 144159 : reduce_outer_joins_pass1(Node *jtnode)
3418 : : {
3419 : : reduce_outer_joins_pass1_state *result;
3420 : :
3421 : 144159 : result = palloc_object(reduce_outer_joins_pass1_state);
3422 : 144159 : result->relids = NULL;
3423 : 144159 : result->contains_outer = false;
3424 : 144159 : result->nullable_rels = NULL;
3425 : 144159 : result->jtnode = jtnode;
3426 : 144159 : result->sub_states = NIL;
3427 : :
3428 [ - + ]: 144159 : if (jtnode == NULL)
3429 : 0 : return result;
3430 [ + + ]: 144159 : if (IsA(jtnode, RangeTblRef))
3431 : : {
3432 : 71955 : int varno = ((RangeTblRef *) jtnode)->rtindex;
3433 : :
3434 : 71955 : result->relids = bms_make_singleton(varno);
3435 : : }
3436 [ + + ]: 72204 : else if (IsA(jtnode, FromExpr))
3437 : : {
3438 : 27995 : FromExpr *f = (FromExpr *) jtnode;
3439 : : ListCell *l;
3440 : :
3441 [ + - + + : 58301 : foreach(l, f->fromlist)
+ + ]
3442 : : {
3443 : : reduce_outer_joins_pass1_state *sub_state;
3444 : :
3445 : 30306 : sub_state = reduce_outer_joins_pass1(lfirst(l));
3446 : 60612 : result->relids = bms_add_members(result->relids,
3447 : 30306 : sub_state->relids);
3448 : 30306 : result->contains_outer |= sub_state->contains_outer;
3449 : 60612 : result->nullable_rels = bms_add_members(result->nullable_rels,
3450 : 30306 : sub_state->nullable_rels);
3451 : 30306 : result->sub_states = lappend(result->sub_states, sub_state);
3452 : : }
3453 : : }
3454 [ + - ]: 44209 : else if (IsA(jtnode, JoinExpr))
3455 : : {
3456 : 44209 : JoinExpr *j = (JoinExpr *) jtnode;
3457 : : reduce_outer_joins_pass1_state *left_state;
3458 : : reduce_outer_joins_pass1_state *right_state;
3459 : :
3460 : : /* Recurse to children */
3461 : 44209 : left_state = reduce_outer_joins_pass1(j->larg);
3462 : 44209 : right_state = reduce_outer_joins_pass1(j->rarg);
3463 : :
3464 : : /* join's own RT index is not wanted in result->relids */
3465 : 44209 : result->relids = bms_union(left_state->relids, right_state->relids);
3466 : :
3467 : : /* Store children's states for pass 2 */
3468 : 44209 : result->sub_states = list_make2(left_state, right_state);
3469 : :
3470 : : /* Collect outer join information */
3471 [ + + + + : 44209 : switch (j->jointype)
- ]
3472 : : {
3473 : 7321 : case JOIN_INNER:
3474 : : case JOIN_SEMI:
3475 : : /* No new nullability; propagate state from children */
3476 [ + + ]: 14015 : result->contains_outer = left_state->contains_outer ||
3477 [ + + ]: 6694 : right_state->contains_outer;
3478 : 14642 : result->nullable_rels = bms_union(left_state->nullable_rels,
3479 : 7321 : right_state->nullable_rels);
3480 : 7321 : break;
3481 : 34953 : case JOIN_LEFT:
3482 : : case JOIN_ANTI:
3483 : : /* RHS is nullable; LHS keeps existing status */
3484 : 34953 : result->contains_outer = true;
3485 : 69906 : result->nullable_rels = bms_union(left_state->nullable_rels,
3486 : 34953 : right_state->relids);
3487 : 34953 : break;
3488 : 965 : case JOIN_RIGHT:
3489 : : /* LHS is nullable; RHS keeps existing status */
3490 : 965 : result->contains_outer = true;
3491 : 1930 : result->nullable_rels = bms_union(left_state->relids,
3492 : 965 : right_state->nullable_rels);
3493 : 965 : break;
3494 : 970 : case JOIN_FULL:
3495 : : /* Both sides are nullable */
3496 : 970 : result->contains_outer = true;
3497 : 1940 : result->nullable_rels = bms_union(left_state->relids,
3498 : 970 : right_state->relids);
3499 : 970 : break;
3500 : 0 : default:
3501 [ # # ]: 0 : elog(ERROR, "unrecognized join type: %d",
3502 : : (int) j->jointype);
3503 : : break;
3504 : : }
3505 : : }
3506 : : else
3507 [ # # ]: 0 : elog(ERROR, "unrecognized node type: %d",
3508 : : (int) nodeTag(jtnode));
3509 : 144159 : return result;
3510 : : }
3511 : :
3512 : : /*
3513 : : * reduce_outer_joins_pass2 - phase 2 processing
3514 : : *
3515 : : * jtnode: current jointree node
3516 : : * state1: state data collected by phase 1 for this node
3517 : : * state2: where to accumulate info about successfully-reduced joins
3518 : : * root: toplevel planner state
3519 : : * nonnullable_rels: set of base relids forced non-null by upper quals
3520 : : * forced_null_vars: multibitmapset of Vars forced null by upper quals
3521 : : *
3522 : : * Returns info in state2 about outer joins that were successfully simplified.
3523 : : * Joins that were fully reduced to inner joins are all added to
3524 : : * state2->inner_reduced, and joins that became antijoins are all added to
3525 : : * state2->anti_reduced. If a full join is reduced to a left join or an
3526 : : * antijoin, it also needs its own entry in state2->partial_reduced, since
3527 : : * that will require custom processing to remove only the correct nullingrel
3528 : : * markers.
3529 : : */
3530 : : static void
3531 : 64128 : reduce_outer_joins_pass2(Node *jtnode,
3532 : : reduce_outer_joins_pass1_state *state1,
3533 : : reduce_outer_joins_pass2_state *state2,
3534 : : PlannerInfo *root,
3535 : : Relids nonnullable_rels,
3536 : : List *forced_null_vars)
3537 : : {
3538 : : /*
3539 : : * pass 2 should never descend as far as an empty subnode or base rel,
3540 : : * because it's only called on subtrees marked as contains_outer.
3541 : : */
3542 [ - + ]: 64128 : if (jtnode == NULL)
3543 [ # # ]: 0 : elog(ERROR, "reached empty jointree");
3544 [ - + ]: 64128 : if (IsA(jtnode, RangeTblRef))
3545 [ # # ]: 0 : elog(ERROR, "reached base rel");
3546 [ + + ]: 64128 : else if (IsA(jtnode, FromExpr))
3547 : : {
3548 : 26488 : FromExpr *f = (FromExpr *) jtnode;
3549 : : ListCell *l;
3550 : : ListCell *s;
3551 : : Relids pass_nonnullable_rels;
3552 : : List *pass_forced_null_vars;
3553 : :
3554 : : /* Scan quals to see if we can add any constraints */
3555 : 26488 : pass_nonnullable_rels = find_nonnullable_rels(f->quals);
3556 : 26488 : pass_nonnullable_rels = bms_add_members(pass_nonnullable_rels,
3557 : : nonnullable_rels);
3558 : 26488 : pass_forced_null_vars = find_forced_null_vars(f->quals);
3559 : 26488 : pass_forced_null_vars = mbms_add_members(pass_forced_null_vars,
3560 : : forced_null_vars);
3561 : : /* And recurse --- but only into interesting subtrees */
3562 : : Assert(list_length(f->fromlist) == list_length(state1->sub_states));
3563 [ + - + + : 55142 : forboth(l, f->fromlist, s, state1->sub_states)
+ - + + +
+ + - +
+ ]
3564 : : {
3565 : 28654 : reduce_outer_joins_pass1_state *sub_state = lfirst(s);
3566 : :
3567 [ + + ]: 28654 : if (sub_state->contains_outer)
3568 : 26513 : reduce_outer_joins_pass2(lfirst(l), sub_state,
3569 : : state2, root,
3570 : : pass_nonnullable_rels,
3571 : : pass_forced_null_vars);
3572 : : }
3573 : 26488 : bms_free(pass_nonnullable_rels);
3574 : : /* can't so easily clean up var lists, unfortunately */
3575 : : }
3576 [ + - ]: 37640 : else if (IsA(jtnode, JoinExpr))
3577 : : {
3578 : 37640 : JoinExpr *j = (JoinExpr *) jtnode;
3579 : 37640 : int rtindex = j->rtindex;
3580 : 37640 : JoinType jointype = j->jointype;
3581 : 37640 : reduce_outer_joins_pass1_state *left_state = linitial(state1->sub_states);
3582 : 37640 : reduce_outer_joins_pass1_state *right_state = lsecond(state1->sub_states);
3583 : :
3584 : : /* Can we simplify this join? */
3585 [ + + + + : 37640 : switch (jointype)
+ - ]
3586 : : {
3587 : 704 : case JOIN_INNER:
3588 : 704 : break;
3589 : 34684 : case JOIN_LEFT:
3590 [ + + ]: 34684 : if (bms_overlap(nonnullable_rels, right_state->relids))
3591 : 2423 : jointype = JOIN_INNER;
3592 : 34684 : break;
3593 : 965 : case JOIN_RIGHT:
3594 [ + + ]: 965 : if (bms_overlap(nonnullable_rels, left_state->relids))
3595 : 69 : jointype = JOIN_INNER;
3596 : 965 : break;
3597 : 970 : case JOIN_FULL:
3598 [ + + ]: 970 : if (bms_overlap(nonnullable_rels, left_state->relids))
3599 : : {
3600 [ + + ]: 35 : if (bms_overlap(nonnullable_rels, right_state->relids))
3601 : 10 : jointype = JOIN_INNER;
3602 : : else
3603 : : {
3604 : 25 : jointype = JOIN_LEFT;
3605 : : /* Also report partial reduction in state2 */
3606 : 25 : report_reduced_full_join(state2, rtindex,
3607 : : right_state->relids);
3608 : : }
3609 : : }
3610 [ + + ]: 935 : else if (bms_overlap(nonnullable_rels, right_state->relids))
3611 : : {
3612 : 29 : jointype = JOIN_RIGHT;
3613 : : /* Also report partial reduction in state2 */
3614 : 29 : report_reduced_full_join(state2, rtindex,
3615 : : left_state->relids);
3616 : : }
3617 [ + + ]: 906 : else if (forced_null_vars != NIL)
3618 : : {
3619 : : /*
3620 : : * Neither side is forced non-null by a strict upper qual,
3621 : : * but an upper qual may force a Var on one side to be
3622 : : * NULL while that Var is non-null in every row that side
3623 : : * emits (proven by quals within the side's own subtree,
3624 : : * or a NOT NULL constraint). Then only rows where that
3625 : : * side was null-extended can satisfy the upper qual: the
3626 : : * matched rows and that side's unmatched rows all drop
3627 : : * out, leaving an anti-join.
3628 : : *
3629 : : * Unlike the JOIN_LEFT case below, we must not consult
3630 : : * the join's own ON quals here: they do not hold for the
3631 : : * unmatched rows that this proof has to cover.
3632 : : *
3633 : : * If the constrained Var is on the RHS the result is a
3634 : : * plain anti-join; if it is on the LHS it is a right
3635 : : * anti-join, which the input-switching step below
3636 : : * normalizes to a plain anti-join (just as it does for
3637 : : * JOIN_RIGHT).
3638 : : */
3639 [ + + ]: 85 : if (forced_null_var_is_nonnullable(root,
3640 : : forced_null_vars,
3641 : : right_state, NIL))
3642 : : {
3643 : 45 : jointype = JOIN_ANTI;
3644 : 45 : report_reduced_full_join(state2, rtindex,
3645 : : right_state->relids);
3646 : : }
3647 [ + + ]: 40 : else if (forced_null_var_is_nonnullable(root,
3648 : : forced_null_vars,
3649 : : left_state, NIL))
3650 : : {
3651 : 20 : jointype = JOIN_RIGHT_ANTI;
3652 : 20 : report_reduced_full_join(state2, rtindex,
3653 : : left_state->relids);
3654 : : }
3655 : : }
3656 : 970 : break;
3657 : 317 : case JOIN_SEMI:
3658 : : case JOIN_ANTI:
3659 : :
3660 : : /*
3661 : : * These could only have been introduced by pull_up_sublinks,
3662 : : * so there's no way that upper quals could refer to their
3663 : : * righthand sides, and no point in checking. We don't expect
3664 : : * a JOIN_RIGHT_SEMI or JOIN_RIGHT_ANTI input here; the
3665 : : * JOIN_FULL case above produces JOIN_RIGHT_ANTI only as a
3666 : : * transient, which is converted to JOIN_ANTI below.
3667 : : */
3668 : 317 : break;
3669 : 0 : default:
3670 [ # # ]: 0 : elog(ERROR, "unrecognized join type: %d",
3671 : : (int) jointype);
3672 : : break;
3673 : : }
3674 : :
3675 : : /*
3676 : : * Convert JOIN_RIGHT to JOIN_LEFT, and likewise the JOIN_RIGHT_ANTI
3677 : : * that the JOIN_FULL arm may have produced just above to JOIN_ANTI,
3678 : : * by switching the inputs. Note that in the case where we reduced
3679 : : * JOIN_FULL this way, this will mean the JoinExpr no longer matches
3680 : : * the internal ordering of any CoalesceExpr's built to represent
3681 : : * merged join variables. We don't care about that at present, but be
3682 : : * wary of it ...
3683 : : */
3684 [ + + + + ]: 37640 : if (jointype == JOIN_RIGHT || jointype == JOIN_RIGHT_ANTI)
3685 : : {
3686 : : Node *tmparg;
3687 : :
3688 : 945 : tmparg = j->larg;
3689 : 945 : j->larg = j->rarg;
3690 : 945 : j->rarg = tmparg;
3691 [ + + ]: 945 : jointype = (jointype == JOIN_RIGHT) ? JOIN_LEFT : JOIN_ANTI;
3692 : 945 : right_state = linitial(state1->sub_states);
3693 : 945 : left_state = lsecond(state1->sub_states);
3694 : : }
3695 : :
3696 : : /*
3697 : : * See if we can reduce JOIN_LEFT to JOIN_ANTI. This is the case if
3698 : : * any var from the RHS was forced null by higher qual levels, but is
3699 : : * known to be non-nullable in any matching row. We can prove that in
3700 : : * any of these ways: the join's own quals are strict for the var;
3701 : : * strict quals applied within the RHS subtree prove it; or the var is
3702 : : * defined NOT NULL by table constraints (being careful to exclude
3703 : : * vars that are nullable due to lower-level outer joins). In each
3704 : : * such case, the only way the higher qual clause's requirement for
3705 : : * NULL can be met is if the join fails to match, producing a
3706 : : * null-extended row. Thus, we can treat this as an anti-join.
3707 : : */
3708 [ + + + + ]: 37640 : if (jointype == JOIN_LEFT && forced_null_vars != NIL)
3709 : : {
3710 : : /*
3711 : : * A forced-null RHS Var that is proven non-null can be NULL here
3712 : : * only by null-extension. That makes this an anti-join.
3713 : : */
3714 [ + + ]: 1213 : if (forced_null_var_is_nonnullable(root, forced_null_vars,
3715 : 1213 : right_state, (List *) j->quals))
3716 : 1032 : jointype = JOIN_ANTI;
3717 : : }
3718 : :
3719 : : /*
3720 : : * Apply the jointype change, if any, to both jointree node and RTE.
3721 : : * Also, if we changed an RTE to INNER, add its RTI to inner_reduced;
3722 : : * if we changed it to ANTI, add its RTI to anti_reduced.
3723 : : */
3724 [ + + + + ]: 37640 : if (rtindex && jointype != j->jointype)
3725 : : {
3726 : 4549 : RangeTblEntry *rte = rt_fetch(rtindex, root->parse->rtable);
3727 : :
3728 : : Assert(rte->rtekind == RTE_JOIN);
3729 : : Assert(rte->jointype == j->jointype);
3730 : 4549 : rte->jointype = jointype;
3731 [ + + ]: 4549 : if (jointype == JOIN_INNER)
3732 : 2502 : state2->inner_reduced = bms_add_member(state2->inner_reduced,
3733 : : rtindex);
3734 [ + + ]: 2047 : else if (jointype == JOIN_ANTI)
3735 : 1097 : state2->anti_reduced = bms_add_member(state2->anti_reduced,
3736 : : rtindex);
3737 : : }
3738 : 37640 : j->jointype = jointype;
3739 : :
3740 : : /* Only recurse if there's more to do below here */
3741 [ + + + + ]: 37640 : if (left_state->contains_outer || right_state->contains_outer)
3742 : : {
3743 : : Relids local_nonnullable_rels;
3744 : : List *local_forced_null_vars;
3745 : : Relids pass_nonnullable_rels;
3746 : : List *pass_forced_null_vars;
3747 : :
3748 : : /*
3749 : : * If this join is (now) inner, we can add any constraints its
3750 : : * quals provide to those we got from above. But if it is outer,
3751 : : * we can pass down the local constraints only into the nullable
3752 : : * side, because an outer join never eliminates any rows from its
3753 : : * non-nullable side. Also, there is no point in passing upper
3754 : : * constraints into the nullable side, since if there were any
3755 : : * we'd have been able to reduce the join. (In the case of upper
3756 : : * forced-null constraints, we *must not* pass them into the
3757 : : * nullable side --- they either applied here, or not.) The upshot
3758 : : * is that we pass either the local or the upper constraints,
3759 : : * never both, to the children of an outer join.
3760 : : *
3761 : : * Note that a SEMI join works like an inner join here: it's okay
3762 : : * to pass down both local and upper constraints. (There can't be
3763 : : * any upper constraints affecting its inner side, but it's not
3764 : : * worth having a separate code path to avoid passing them.)
3765 : : *
3766 : : * At a FULL join we just punt and pass nothing down --- is it
3767 : : * possible to be smarter?
3768 : : */
3769 [ + + ]: 12126 : if (jointype != JOIN_FULL)
3770 : : {
3771 : 12013 : local_nonnullable_rels = find_nonnullable_rels(j->quals);
3772 : 12013 : local_forced_null_vars = find_forced_null_vars(j->quals);
3773 [ + + + + ]: 12013 : if (jointype == JOIN_INNER || jointype == JOIN_SEMI)
3774 : : {
3775 : : /* OK to merge upper and local constraints */
3776 : 1552 : local_nonnullable_rels = bms_add_members(local_nonnullable_rels,
3777 : : nonnullable_rels);
3778 : 1552 : local_forced_null_vars = mbms_add_members(local_forced_null_vars,
3779 : : forced_null_vars);
3780 : : }
3781 : : }
3782 : : else
3783 : : {
3784 : : /* no use in calculating these */
3785 : 113 : local_nonnullable_rels = NULL;
3786 : 113 : local_forced_null_vars = NIL;
3787 : : }
3788 : :
3789 [ + + ]: 12126 : if (left_state->contains_outer)
3790 : : {
3791 [ + + + + ]: 11396 : if (jointype == JOIN_INNER || jointype == JOIN_SEMI)
3792 : : {
3793 : : /* pass union of local and upper constraints */
3794 : 1371 : pass_nonnullable_rels = local_nonnullable_rels;
3795 : 1371 : pass_forced_null_vars = local_forced_null_vars;
3796 : : }
3797 [ + + ]: 10025 : else if (jointype != JOIN_FULL) /* ie, LEFT or ANTI */
3798 : : {
3799 : : /* can't pass local constraints to non-nullable side */
3800 : 9945 : pass_nonnullable_rels = nonnullable_rels;
3801 : 9945 : pass_forced_null_vars = forced_null_vars;
3802 : : }
3803 : : else
3804 : : {
3805 : : /* no constraints pass through JOIN_FULL */
3806 : 80 : pass_nonnullable_rels = NULL;
3807 : 80 : pass_forced_null_vars = NIL;
3808 : : }
3809 : 11396 : reduce_outer_joins_pass2(j->larg, left_state,
3810 : : state2, root,
3811 : : pass_nonnullable_rels,
3812 : : pass_forced_null_vars);
3813 : : }
3814 : :
3815 [ + + ]: 12126 : if (right_state->contains_outer)
3816 : : {
3817 [ + + ]: 784 : if (jointype != JOIN_FULL) /* ie, INNER/LEFT/SEMI/ANTI */
3818 : : {
3819 : : /* pass appropriate constraints, per comment above */
3820 : 751 : pass_nonnullable_rels = local_nonnullable_rels;
3821 : 751 : pass_forced_null_vars = local_forced_null_vars;
3822 : : }
3823 : : else
3824 : : {
3825 : : /* no constraints pass through JOIN_FULL */
3826 : 33 : pass_nonnullable_rels = NULL;
3827 : 33 : pass_forced_null_vars = NIL;
3828 : : }
3829 : 784 : reduce_outer_joins_pass2(j->rarg, right_state,
3830 : : state2, root,
3831 : : pass_nonnullable_rels,
3832 : : pass_forced_null_vars);
3833 : : }
3834 : 12126 : bms_free(local_nonnullable_rels);
3835 : : }
3836 : : }
3837 : : else
3838 [ # # ]: 0 : elog(ERROR, "unrecognized node type: %d",
3839 : : (int) nodeTag(jtnode));
3840 : 64128 : }
3841 : :
3842 : : /* Helper for reduce_outer_joins_pass2 */
3843 : : static void
3844 : 119 : report_reduced_full_join(reduce_outer_joins_pass2_state *state2,
3845 : : int rtindex, Relids relids)
3846 : : {
3847 : : reduce_outer_joins_partial_state *statep;
3848 : :
3849 : 119 : statep = palloc_object(reduce_outer_joins_partial_state);
3850 : 119 : statep->full_join_rti = rtindex;
3851 : 119 : statep->unreduced_side = relids;
3852 : 119 : state2->partial_reduced = lappend(state2->partial_reduced, statep);
3853 : 119 : }
3854 : :
3855 : : /*
3856 : : * forced_null_var_is_attnotnull
3857 : : * Check if "forced_null_vars" contains any Vars belonging to the subtree
3858 : : * indicated by "state" that are known to be non-nullable due to table
3859 : : * constraints.
3860 : : *
3861 : : * A whole-row Var, in any matching row, requires every column of its relation
3862 : : * to be NULL, so any NOT NULL column of the relation refutes it.
3863 : : *
3864 : : * Note that we must also consider the situation where a NOT NULL Var can be
3865 : : * nulled by lower-level outer joins.
3866 : : *
3867 : : * Helper for reduce_outer_joins_pass2.
3868 : : */
3869 : : static bool
3870 : 321 : forced_null_var_is_attnotnull(PlannerInfo *root, List *forced_null_vars,
3871 : : reduce_outer_joins_pass1_state *state)
3872 : : {
3873 : 321 : int varno = -1;
3874 : :
3875 [ + - + + : 1918 : foreach_node(Bitmapset, attrs, forced_null_vars)
+ + ]
3876 : : {
3877 : : RangeTblEntry *rte;
3878 : : Bitmapset *notnullattnums;
3879 : : Bitmapset *forcednullattnums;
3880 : 1436 : bool wholerow = false;
3881 : : int lowest_attno;
3882 : :
3883 : 1436 : varno++;
3884 : :
3885 : : /* Skip empty bitmaps */
3886 [ + + ]: 1436 : if (bms_is_empty(attrs))
3887 : 1110 : continue;
3888 : :
3889 : : /* Skip Vars that do not belong to the target relations */
3890 [ + + ]: 326 : if (!bms_is_member(varno, state->relids))
3891 : 115 : continue;
3892 : :
3893 : : /*
3894 : : * Skip Vars that can be nulled by lower-level outer joins within the
3895 : : * given subtree. These Vars might be NULL even if the schema defines
3896 : : * them as NOT NULL.
3897 : : */
3898 [ + + ]: 211 : if (bms_is_member(varno, state->nullable_rels))
3899 : 25 : continue;
3900 : :
3901 : : /* find the lowest member to check if system columns are present */
3902 : 186 : lowest_attno = bms_next_member(attrs, -1);
3903 : :
3904 : : /* we checked for an empty set above */
3905 : : Assert(lowest_attno >= 0);
3906 : :
3907 : : /* system columns cannot be NULL */
3908 [ - + ]: 186 : if (lowest_attno + FirstLowInvalidHeapAttributeNumber < 0)
3909 : 80 : return true;
3910 : :
3911 : : /* attno 0 is a whole-row Var, which forces every column null */
3912 [ + + ]: 186 : if (lowest_attno + FirstLowInvalidHeapAttributeNumber == 0)
3913 : 40 : wholerow = true;
3914 : :
3915 : 186 : rte = rt_fetch(varno, root->parse->rtable);
3916 : :
3917 : : /* We can only reason about ordinary relations */
3918 [ + + ]: 186 : if (rte->rtekind != RTE_RELATION)
3919 : 31 : continue;
3920 : :
3921 : : /*
3922 : : * We must skip inheritance parent tables, as some child tables may
3923 : : * have a NOT NULL constraint for a column while others may not. This
3924 : : * cannot happen with partitioned tables, though.
3925 : : */
3926 [ - + - - ]: 155 : if (rte->inh && rte->relkind != RELKIND_PARTITIONED_TABLE)
3927 : 0 : continue;
3928 : :
3929 : : /* Get the column not-null constraint information for this relation */
3930 : 155 : notnullattnums = find_relation_notnullatts(root, rte->relid);
3931 : :
3932 : : /*
3933 : : * A forced-null whole-row Var, in any matching row, requires every
3934 : : * column of the relation to be NULL, so any NOT NULL column refutes
3935 : : * it.
3936 : : */
3937 [ + + + + ]: 155 : if (wholerow && !bms_is_empty(notnullattnums))
3938 : 10 : return true;
3939 : :
3940 : : /*
3941 : : * Offset the bitmap members by FirstLowInvalidHeapAttributeNumber to
3942 : : * get the actual attribute numbers.
3943 : : */
3944 : 145 : forcednullattnums = bms_offset_members(attrs,
3945 : : FirstLowInvalidHeapAttributeNumber);
3946 : :
3947 : : /*
3948 : : * Check if any forced-null attributes are defined as NOT NULL by
3949 : : * table constraints.
3950 : : */
3951 [ + + ]: 145 : if (bms_overlap(notnullattnums, forcednullattnums))
3952 : : {
3953 : 70 : bms_free(forcednullattnums);
3954 : 70 : return true;
3955 : : }
3956 : :
3957 : 75 : bms_free(forcednullattnums);
3958 : : }
3959 : :
3960 : 241 : return false;
3961 : : }
3962 : :
3963 : : /*
3964 : : * forced_null_var_is_nonnullable
3965 : : * Detect whether some Var that "forced_null_vars" requires to be NULL is
3966 : : * actually non-nullable in every row that the given subtree emits.
3967 : : *
3968 : : * We prove non-nullness from quals that hold for every such row: the subtree's
3969 : : * safe quals, plus any "extra_quals" the caller knows also constrain the Var,
3970 : : * or a NOT NULL table constraint (excluding Vars nullable due to lower-level
3971 : : * outer joins).
3972 : : *
3973 : : * A whole-row Var in "forced_null_vars" requires, in any matching row, every
3974 : : * column of its relation to be NULL, so it is refuted by proving any one of
3975 : : * those columns non-null.
3976 : : *
3977 : : * Helper for reduce_outer_joins_pass2.
3978 : : */
3979 : : static bool
3980 : 1338 : forced_null_var_is_nonnullable(PlannerInfo *root, List *forced_null_vars,
3981 : : reduce_outer_joins_pass1_state *state,
3982 : : List *extra_quals)
3983 : : {
3984 : 1338 : List *all_quals = NIL;
3985 : : List *nonnullable_vars;
3986 : 1338 : int wholerow_attno = 0 - FirstLowInvalidHeapAttributeNumber;
3987 : 1338 : int varno = -1;
3988 : :
3989 : 1338 : find_safe_quals(state->jtnode, &all_quals);
3990 : 1338 : all_quals = list_concat(all_quals, extra_quals);
3991 : 1338 : nonnullable_vars = find_nonnullable_vars((Node *) all_quals);
3992 : :
3993 : : /*
3994 : : * It's not sufficient to consider all matches between nonnullable_vars
3995 : : * and forced_null_vars: a match counts only for a Var belonging to this
3996 : : * subtree, and the whole-row attribute needs special treatment.
3997 : : */
3998 [ + - + + : 4614 : foreach_node(Bitmapset, attrs, forced_null_vars)
+ + ]
3999 : : {
4000 : : Bitmapset *nonnull_attrs;
4001 : :
4002 : 4177 : varno++;
4003 : :
4004 : : /* Beyond the end of nonnullable_vars there is nothing left to prove */
4005 [ + + ]: 4177 : if (varno >= list_length(nonnullable_vars))
4006 : 205 : break;
4007 : :
4008 : : /* Skip empty bitmaps */
4009 [ + + ]: 3972 : if (bms_is_empty(attrs))
4010 : 2839 : continue;
4011 : :
4012 : : /* Skip Vars that do not belong to the target relations */
4013 [ + + ]: 1133 : if (!bms_is_member(varno, state->relids))
4014 : 44 : continue;
4015 : :
4016 : : /* Get what the quals prove non-null for this relation, if anything */
4017 : 1089 : nonnull_attrs = list_nth_node(Bitmapset, nonnullable_vars, varno);
4018 : :
4019 : : /*
4020 : : * A proof for the whole-row attribute refutes nothing: it shows only
4021 : : * that the composite datum is non-null, and such a datum can still
4022 : : * have all columns NULL. Discard it up front.
4023 : : */
4024 : 1089 : nonnull_attrs = bms_del_member(nonnull_attrs, wholerow_attno);
4025 : :
4026 : : /* A forced-null attribute that is proven non-null settles it. */
4027 [ + + ]: 1089 : if (bms_overlap(attrs, nonnull_attrs))
4028 : 1017 : return true;
4029 : :
4030 : : /*
4031 : : * So does any real column proven non-null, if the whole-row Var is
4032 : : * forced null: in a matching row (whose whole-row datum is non-null)
4033 : : * the row-format IS NULL test is true only when every column is NULL.
4034 : : * System attributes don't count, since they are not part of the row
4035 : : * value; conveniently they sort below the whole-row attribute in the
4036 : : * bitmap.
4037 : : */
4038 [ + + + + ]: 122 : if (bms_is_member(wholerow_attno, attrs) &&
4039 : 35 : bms_next_member(nonnull_attrs, wholerow_attno) >= 0)
4040 : 15 : return true;
4041 : : }
4042 : :
4043 : : /*
4044 : : * Otherwise, check if any forced-null var is defined NOT NULL by table
4045 : : * constraints.
4046 : : */
4047 : 321 : return forced_null_var_is_attnotnull(root, forced_null_vars, state);
4048 : : }
4049 : :
4050 : :
4051 : : /*
4052 : : * remove_useless_result_rtes
4053 : : * Attempt to remove RTE_RESULT RTEs from the join tree.
4054 : : * Also, elide single-child FromExprs where possible.
4055 : : *
4056 : : * We can remove RTE_RESULT entries from the join tree using the knowledge
4057 : : * that RTE_RESULT returns exactly one row and has no output columns. Hence,
4058 : : * if one is inner-joined to anything else, we can delete it. Optimizations
4059 : : * are also possible for some outer-join cases, as detailed below.
4060 : : *
4061 : : * This pass also replaces single-child FromExprs with their child node
4062 : : * where possible. It's appropriate to do that here and not earlier because
4063 : : * RTE_RESULT removal might reduce a multiple-child FromExpr to have only one
4064 : : * child. We can remove such a FromExpr if its quals are empty, or if it's
4065 : : * semantically valid to merge the quals into those of the parent node.
4066 : : * While removing unnecessary join tree nodes has some micro-efficiency value,
4067 : : * the real reason to do this is to eliminate cases where the nullable side of
4068 : : * an outer join node is a FromExpr whose single child is another outer join.
4069 : : * To correctly determine whether the two outer joins can commute,
4070 : : * deconstruct_jointree() must treat any quals of such a FromExpr as being
4071 : : * degenerate quals of the upper outer join. The best way to do that is to
4072 : : * make them actually *be* quals of the upper join, by dropping the FromExpr
4073 : : * and hoisting the quals up into the upper join's quals. (Note that there is
4074 : : * no hazard when the intermediate FromExpr has multiple children, since then
4075 : : * it represents an inner join that cannot commute with the upper outer join.)
4076 : : * As long as we have to do that, we might as well elide such FromExprs
4077 : : * everywhere.
4078 : : *
4079 : : * Some of these optimizations depend on recognizing empty (constant-true)
4080 : : * quals for FromExprs and JoinExprs. That makes it useful to apply this
4081 : : * optimization pass after expression preprocessing, since that will have
4082 : : * eliminated constant-true quals, allowing more cases to be recognized as
4083 : : * optimizable. What's more, the usual reason for an RTE_RESULT to be present
4084 : : * is that we pulled up a subquery or VALUES clause, thus very possibly
4085 : : * replacing Vars with constants, making it more likely that a qual can be
4086 : : * reduced to constant true. Also, because some optimizations depend on
4087 : : * the outer-join type, it's best to have done reduce_outer_joins() first.
4088 : : *
4089 : : * A PlaceHolderVar referencing an RTE_RESULT RTE poses an obstacle to this
4090 : : * process: we must remove the RTE_RESULT's relid from the PHV's phrels, but
4091 : : * we must not reduce the phrels set to empty. If that would happen, and
4092 : : * the RTE_RESULT is an immediate child of an outer join, we have to give up
4093 : : * and not remove the RTE_RESULT: there is noplace else to evaluate the
4094 : : * PlaceHolderVar. (That is, in such cases the RTE_RESULT *does* have output
4095 : : * columns.) But if the RTE_RESULT is an immediate child of an inner join,
4096 : : * we can usually change the PlaceHolderVar's phrels so as to evaluate it at
4097 : : * the inner join instead. This is OK because we really only care that PHVs
4098 : : * are evaluated above or below the correct outer joins. We can't, however,
4099 : : * postpone the evaluation of a PHV to above where it is used; so there are
4100 : : * some checks below on whether output PHVs are laterally referenced in the
4101 : : * other join input rel(s).
4102 : : *
4103 : : * We used to try to do this work as part of pull_up_subqueries() where the
4104 : : * potentially-optimizable cases get introduced; but it's way simpler, and
4105 : : * more effective, to do it separately.
4106 : : */
4107 : : void
4108 : 171250 : remove_useless_result_rtes(PlannerInfo *root)
4109 : : {
4110 : 171250 : Relids baserels = NULL;
4111 : 171250 : Relids dropped_outer_joins = NULL;
4112 : : ListCell *cell;
4113 : :
4114 : : /*
4115 : : * We'll need the set of baserels in the jointree to perform
4116 : : * find_dependent_phvs() checks. But if there are no PHVs anywhere in the
4117 : : * query, those checks are no-ops, so we can skip the work.
4118 : : */
4119 [ + + ]: 171250 : if (root->glob->lastPHId != 0)
4120 : 1321 : baserels = get_relids_in_jointree((Node *) root->parse->jointree,
4121 : : false, false);
4122 : :
4123 : : /* Top level of jointree must always be a FromExpr */
4124 : : Assert(IsA(root->parse->jointree, FromExpr));
4125 : : /* Recurse ... */
4126 : 342500 : root->parse->jointree = (FromExpr *)
4127 : 171250 : remove_useless_results_recurse(root,
4128 : 171250 : (Node *) root->parse->jointree,
4129 : : baserels,
4130 : : NULL,
4131 : : &dropped_outer_joins);
4132 : : /* We should still have a FromExpr */
4133 : : Assert(IsA(root->parse->jointree, FromExpr));
4134 : :
4135 : : /*
4136 : : * If we removed any outer-join nodes from the jointree, run around and
4137 : : * remove references to those joins as nulling rels. (There could be such
4138 : : * references in PHVs that we pulled up out of the original subquery that
4139 : : * the RESULT rel replaced. This is kosher on the grounds that we now
4140 : : * know that such an outer join wouldn't really have nulled anything.) We
4141 : : * don't do this during the main recursion, for simplicity and because we
4142 : : * can handle all such joins in a single pass over the parse tree.
4143 : : */
4144 [ + + ]: 171250 : if (!bms_is_empty(dropped_outer_joins))
4145 : : {
4146 : 65 : root->parse = (Query *)
4147 : 65 : remove_nulling_relids((Node *) root->parse,
4148 : : dropped_outer_joins,
4149 : : NULL);
4150 : : /* There could be references in the append_rel_list, too */
4151 : 65 : root->append_rel_list = (List *)
4152 : 65 : remove_nulling_relids((Node *) root->append_rel_list,
4153 : : dropped_outer_joins,
4154 : : NULL);
4155 : : }
4156 : :
4157 : : /*
4158 : : * Remove any PlanRowMark referencing an RTE_RESULT RTE. We obviously
4159 : : * must do that for any RTE_RESULT that we just removed. But one for a
4160 : : * RTE that we did not remove can be dropped anyway: since the RTE has
4161 : : * only one possible output row, there is no need for EPQ to mark and
4162 : : * restore that row.
4163 : : *
4164 : : * It's necessary, not optional, to remove the PlanRowMark for a surviving
4165 : : * RTE_RESULT RTE; otherwise we'll generate a whole-row Var for the
4166 : : * RTE_RESULT, which the executor has no support for.
4167 : : */
4168 [ + + + + : 172831 : foreach(cell, root->rowMarks)
+ + ]
4169 : : {
4170 : 1581 : PlanRowMark *rc = (PlanRowMark *) lfirst(cell);
4171 : :
4172 [ + + ]: 1581 : if (rt_fetch(rc->rti, root->parse->rtable)->rtekind == RTE_RESULT)
4173 : 660 : root->rowMarks = foreach_delete_current(root->rowMarks, cell);
4174 : : }
4175 : 171250 : }
4176 : :
4177 : : /*
4178 : : * remove_useless_results_recurse
4179 : : * Recursive guts of remove_useless_result_rtes.
4180 : : *
4181 : : * This recursively processes the jointree and returns a modified jointree.
4182 : : * In addition, the RT indexes of any removed outer-join nodes are added to
4183 : : * *dropped_outer_joins.
4184 : : *
4185 : : * jtnode is the current jointree node. If it could be valid to merge
4186 : : * its quals into those of the parent node, parent_quals should point to
4187 : : * the parent's quals list; otherwise, pass NULL for parent_quals.
4188 : : * (Note that in some cases, parent_quals points to the quals of a parent
4189 : : * more than one level up in the tree.)
4190 : : *
4191 : : * baserels is the set of base (non-join) RT indexes in the whole jointree;
4192 : : * it can be NULL if the query contains no PHVs.
4193 : : */
4194 : : static Node *
4195 : 445654 : remove_useless_results_recurse(PlannerInfo *root, Node *jtnode,
4196 : : Relids baserels,
4197 : : Node **parent_quals,
4198 : : Relids *dropped_outer_joins)
4199 : : {
4200 : : Assert(jtnode != NULL);
4201 [ + + ]: 445654 : if (IsA(jtnode, RangeTblRef))
4202 : : {
4203 : : /* Can't immediately do anything with a RangeTblRef */
4204 : : }
4205 [ + + ]: 224166 : else if (IsA(jtnode, FromExpr))
4206 : : {
4207 : 176839 : FromExpr *f = (FromExpr *) jtnode;
4208 : 176839 : Relids result_relids = NULL;
4209 : : ListCell *cell;
4210 : :
4211 : : /*
4212 : : * We can drop RTE_RESULT rels from the fromlist so long as at least
4213 : : * one child remains, since joining to a one-row table changes
4214 : : * nothing. (But we can't drop a RTE_RESULT that computes PHV(s) that
4215 : : * are needed by some sibling. The cleanup transformation below would
4216 : : * reassign the PHVs to be computed at the join, which is too late for
4217 : : * the sibling's use.) The easiest way to mechanize this rule is to
4218 : : * modify the list in-place.
4219 : : */
4220 [ + - + + : 356589 : foreach(cell, f->fromlist)
+ + ]
4221 : : {
4222 : 179750 : Node *child = (Node *) lfirst(cell);
4223 : : int varno;
4224 : :
4225 : : /* Recursively transform child, allowing it to push up quals ... */
4226 : 179750 : child = remove_useless_results_recurse(root, child,
4227 : : baserels,
4228 : : &f->quals,
4229 : : dropped_outer_joins);
4230 : : /* ... and stick it back into the tree */
4231 : 179750 : lfirst(cell) = child;
4232 : :
4233 : : /*
4234 : : * If it's an RTE_RESULT with at least one sibling, and no sibling
4235 : : * references dependent PHVs, we can drop it. We don't yet know
4236 : : * what the inner join's final relid set will be, so postpone
4237 : : * cleanup of PHVs etc till after this loop.
4238 : : */
4239 [ + + + + ]: 184403 : if (list_length(f->fromlist) > 1 &&
4240 : 4653 : (varno = get_result_relid(root, child)) != 0 &&
4241 [ + + ]: 290 : !find_dependent_phvs_in_jointree(root, (Node *) f, varno,
4242 : : baserels))
4243 : : {
4244 : 270 : f->fromlist = foreach_delete_current(f->fromlist, cell);
4245 : 270 : result_relids = bms_add_member(result_relids, varno);
4246 : : }
4247 : : }
4248 : :
4249 : : /*
4250 : : * Clean up if we dropped any RTE_RESULT RTEs. This is a bit
4251 : : * inefficient if there's more than one, but it seems better to
4252 : : * optimize the support code for the single-relid case.
4253 : : */
4254 [ + + ]: 176839 : if (result_relids)
4255 : : {
4256 : 260 : int varno = -1;
4257 : :
4258 [ + + ]: 530 : while ((varno = bms_next_member(result_relids, varno)) >= 0)
4259 : 270 : remove_result_refs(root, varno, (Node *) f);
4260 : : }
4261 : :
4262 : : /*
4263 : : * If the FromExpr now has only one child, see if we can elide it.
4264 : : * This is always valid if there are no quals, except at the top of
4265 : : * the jointree (since Query.jointree is required to point to a
4266 : : * FromExpr). Otherwise, we can do it if we can push the quals up to
4267 : : * the parent node.
4268 : : *
4269 : : * Note: while it would not be terribly hard to generalize this
4270 : : * transformation to merge multi-child FromExprs into their parent
4271 : : * FromExpr, that risks making the parent join too expensive to plan.
4272 : : * We leave it to later processing to decide heuristically whether
4273 : : * that's a good idea. Pulling up a single child is always OK,
4274 : : * however.
4275 : : */
4276 [ + + ]: 176839 : if (list_length(f->fromlist) == 1 &&
4277 [ + + ]: 175271 : f != root->parse->jointree &&
4278 [ + + + + ]: 5378 : (f->quals == NULL || parent_quals != NULL))
4279 : : {
4280 : : /*
4281 : : * Merge any quals up to parent. They should be in implicit-AND
4282 : : * format by now, so we just need to concatenate lists. Put the
4283 : : * child quals at the front, on the grounds that they should
4284 : : * nominally be evaluated earlier.
4285 : : */
4286 [ + + ]: 2282 : if (f->quals != NULL)
4287 : 1163 : *parent_quals = (Node *)
4288 : 1163 : list_concat(castNode(List, f->quals),
4289 : : castNode(List, *parent_quals));
4290 : 2282 : return (Node *) linitial(f->fromlist);
4291 : : }
4292 : : }
4293 [ + - ]: 47327 : else if (IsA(jtnode, JoinExpr))
4294 : : {
4295 : 47327 : JoinExpr *j = (JoinExpr *) jtnode;
4296 : : int varno;
4297 : :
4298 : : /*
4299 : : * First, recurse. We can absorb pushed-up FromExpr quals from either
4300 : : * child into this node if the jointype is INNER, since then this is
4301 : : * equivalent to a FromExpr. When the jointype is LEFT, we can absorb
4302 : : * quals from the RHS child into the current node, as they're
4303 : : * essentially degenerate quals of the outer join. Moreover, if we've
4304 : : * been passed down a parent_quals pointer then we can allow quals of
4305 : : * the LHS child to be absorbed into the parent. (This is important
4306 : : * to ensure we remove single-child FromExprs immediately below
4307 : : * commutable left joins.) For other jointypes, we can't move child
4308 : : * quals up, or at least there's no particular reason to.
4309 : : */
4310 : 47327 : j->larg = remove_useless_results_recurse(root, j->larg,
4311 : : baserels,
4312 [ + + ]: 47327 : (j->jointype == JOIN_INNER) ?
4313 : : &j->quals :
4314 : 37092 : (j->jointype == JOIN_LEFT) ?
4315 [ + + ]: 37092 : parent_quals : NULL,
4316 : : dropped_outer_joins);
4317 : 47327 : j->rarg = remove_useless_results_recurse(root, j->rarg,
4318 : : baserels,
4319 [ + + ]: 47327 : (j->jointype == JOIN_INNER ||
4320 [ + + ]: 37092 : j->jointype == JOIN_LEFT) ?
4321 : : &j->quals : NULL,
4322 : : dropped_outer_joins);
4323 : :
4324 : : /* Apply join-type-specific optimization rules */
4325 [ + + + + : 47327 : switch (j->jointype)
- ]
4326 : : {
4327 : 10235 : case JOIN_INNER:
4328 : :
4329 : : /*
4330 : : * An inner join is equivalent to a FromExpr, so if either
4331 : : * side was simplified to an RTE_RESULT rel, we can replace
4332 : : * the join with a FromExpr with just the other side.
4333 : : * Furthermore, we can elide that FromExpr according to the
4334 : : * same rules as above.
4335 : : *
4336 : : * Just as in the FromExpr case, we can't simplify if the
4337 : : * other input rel references any PHVs that are marked as to
4338 : : * be evaluated at the RTE_RESULT rel, because we can't
4339 : : * postpone their evaluation in that case. But we only have
4340 : : * to check this in cases where it's syntactically legal for
4341 : : * the other input to have a LATERAL reference to the
4342 : : * RTE_RESULT rel. Only RHSes of inner and left joins are
4343 : : * allowed to have such refs.
4344 : : */
4345 [ + + ]: 10235 : if ((varno = get_result_relid(root, j->larg)) != 0 &&
4346 [ + - ]: 86 : !find_dependent_phvs_in_jointree(root, j->rarg, varno,
4347 : : baserels))
4348 : : {
4349 : 86 : remove_result_refs(root, varno, j->rarg);
4350 [ + + + + ]: 86 : if (j->quals != NULL && parent_quals == NULL)
4351 : 10 : jtnode = (Node *)
4352 : 10 : makeFromExpr(list_make1(j->rarg), j->quals);
4353 : : else
4354 : : {
4355 : : /* Merge any quals up to parent */
4356 [ + + ]: 76 : if (j->quals != NULL)
4357 : 58 : *parent_quals = (Node *)
4358 : 58 : list_concat(castNode(List, j->quals),
4359 : : castNode(List, *parent_quals));
4360 : 76 : jtnode = j->rarg;
4361 : : }
4362 : : }
4363 [ + + ]: 10149 : else if ((varno = get_result_relid(root, j->rarg)) != 0)
4364 : : {
4365 : 584 : remove_result_refs(root, varno, j->larg);
4366 [ + + + + ]: 584 : if (j->quals != NULL && parent_quals == NULL)
4367 : 10 : jtnode = (Node *)
4368 : 10 : makeFromExpr(list_make1(j->larg), j->quals);
4369 : : else
4370 : : {
4371 : : /* Merge any quals up to parent */
4372 [ + + ]: 574 : if (j->quals != NULL)
4373 : 399 : *parent_quals = (Node *)
4374 : 399 : list_concat(castNode(List, j->quals),
4375 : : castNode(List, *parent_quals));
4376 : 574 : jtnode = j->larg;
4377 : : }
4378 : : }
4379 : 10235 : break;
4380 : 32179 : case JOIN_LEFT:
4381 : :
4382 : : /*
4383 : : * We can simplify this case if the RHS is an RTE_RESULT, with
4384 : : * two different possibilities:
4385 : : *
4386 : : * If the qual is empty (JOIN ON TRUE), then the join can be
4387 : : * strength-reduced to a plain inner join, since each LHS row
4388 : : * necessarily has exactly one join partner. So we can always
4389 : : * discard the RHS, much as in the JOIN_INNER case above.
4390 : : * (Again, the LHS could not contain a lateral reference to
4391 : : * the RHS.)
4392 : : *
4393 : : * Otherwise, it's still true that each LHS row should be
4394 : : * returned exactly once, and since the RHS returns no columns
4395 : : * (unless there are PHVs that have to be evaluated there), we
4396 : : * don't much care if it's null-extended or not. So in this
4397 : : * case also, we can just ignore the qual and discard the left
4398 : : * join.
4399 : : */
4400 [ + + ]: 32179 : if ((varno = get_result_relid(root, j->rarg)) != 0 &&
4401 [ + + ]: 134 : (j->quals == NULL ||
4402 [ - + ]: 69 : !find_dependent_phvs(root, varno, baserels)))
4403 : : {
4404 : 65 : remove_result_refs(root, varno, j->larg);
4405 : 65 : *dropped_outer_joins = bms_add_member(*dropped_outer_joins,
4406 : : j->rtindex);
4407 : 65 : jtnode = j->larg;
4408 : : }
4409 : 32179 : break;
4410 : 2706 : case JOIN_SEMI:
4411 : :
4412 : : /*
4413 : : * We may simplify this case if the RHS is an RTE_RESULT; the
4414 : : * join qual becomes effectively just a filter qual for the
4415 : : * LHS, since we should either return the LHS row or not. The
4416 : : * filter clause must go into a new FromExpr if we can't push
4417 : : * it up to the parent.
4418 : : *
4419 : : * There is a fine point about PHVs that are supposed to be
4420 : : * evaluated at the RHS. Such PHVs could only appear in the
4421 : : * semijoin's qual, since the rest of the query cannot
4422 : : * reference any outputs of the semijoin's RHS. Therefore,
4423 : : * they can't actually go to null before being examined, and
4424 : : * it'd be OK to just remove the PHV wrapping. We don't have
4425 : : * infrastructure for that, but remove_result_refs() will
4426 : : * relabel them as to be evaluated at the LHS, which is fine.
4427 : : *
4428 : : * Also, we don't need to worry about removing traces of the
4429 : : * join's rtindex, since it hasn't got one.
4430 : : */
4431 [ + + ]: 2706 : if ((varno = get_result_relid(root, j->rarg)) != 0)
4432 : : {
4433 : : Assert(j->rtindex == 0);
4434 : 30 : remove_result_refs(root, varno, j->larg);
4435 [ + - - + ]: 30 : if (j->quals != NULL && parent_quals == NULL)
4436 : 0 : jtnode = (Node *)
4437 : 0 : makeFromExpr(list_make1(j->larg), j->quals);
4438 : : else
4439 : : {
4440 : : /* Merge any quals up to parent */
4441 [ + - ]: 30 : if (j->quals != NULL)
4442 : 30 : *parent_quals = (Node *)
4443 : 30 : list_concat(castNode(List, j->quals),
4444 : : castNode(List, *parent_quals));
4445 : 30 : jtnode = j->larg;
4446 : : }
4447 : : }
4448 : 2706 : break;
4449 : 2207 : case JOIN_FULL:
4450 : : case JOIN_ANTI:
4451 : : /* We have no special smarts for these cases */
4452 : 2207 : break;
4453 : 0 : default:
4454 : : /* Note: JOIN_RIGHT should be gone at this point */
4455 [ # # ]: 0 : elog(ERROR, "unrecognized join type: %d",
4456 : : (int) j->jointype);
4457 : : break;
4458 : : }
4459 : : }
4460 : : else
4461 [ # # ]: 0 : elog(ERROR, "unrecognized node type: %d",
4462 : : (int) nodeTag(jtnode));
4463 : 443372 : return jtnode;
4464 : : }
4465 : :
4466 : : /*
4467 : : * get_result_relid
4468 : : * If jtnode is a RangeTblRef for an RTE_RESULT RTE, return its relid;
4469 : : * otherwise return 0.
4470 : : */
4471 : : static int
4472 : 59922 : get_result_relid(PlannerInfo *root, Node *jtnode)
4473 : : {
4474 : : int varno;
4475 : :
4476 [ + + ]: 59922 : if (!IsA(jtnode, RangeTblRef))
4477 : 6286 : return 0;
4478 : 53636 : varno = ((RangeTblRef *) jtnode)->rtindex;
4479 [ + + ]: 53636 : if (rt_fetch(varno, root->parse->rtable)->rtekind != RTE_RESULT)
4480 : 52512 : return 0;
4481 : 1124 : return varno;
4482 : : }
4483 : :
4484 : : /*
4485 : : * remove_result_refs
4486 : : * Helper routine for dropping an unneeded RTE_RESULT RTE.
4487 : : *
4488 : : * This doesn't physically remove the RTE from the jointree, because that's
4489 : : * more easily handled in remove_useless_results_recurse. What it does do
4490 : : * is the necessary cleanup in the rest of the tree: we must adjust any PHVs
4491 : : * that may reference the RTE. Be sure to call this at a point where the
4492 : : * jointree is valid (no disconnected nodes).
4493 : : *
4494 : : * Note that we don't need to process the append_rel_list, since RTEs
4495 : : * referenced directly in the jointree won't be appendrel members.
4496 : : *
4497 : : * varno is the RTE_RESULT's relid.
4498 : : * newjtloc is the jointree location at which any PHVs referencing the
4499 : : * RTE_RESULT should be evaluated instead.
4500 : : */
4501 : : static void
4502 : 1035 : remove_result_refs(PlannerInfo *root, int varno, Node *newjtloc)
4503 : : {
4504 : : /* Fix up PlaceHolderVars as needed */
4505 : : /* If there are no PHVs anywhere, we can skip this bit */
4506 [ + + ]: 1035 : if (root->glob->lastPHId != 0)
4507 : : {
4508 : : Relids subrelids;
4509 : :
4510 : 225 : subrelids = get_relids_in_jointree(newjtloc, true, false);
4511 : : Assert(!bms_is_empty(subrelids));
4512 : 225 : substitute_phv_relids((Node *) root->parse, varno, subrelids);
4513 : 225 : fix_append_rel_relids(root, varno, subrelids);
4514 : : }
4515 : :
4516 : : /*
4517 : : * We also need to remove any PlanRowMark referencing the RTE, but we
4518 : : * postpone that work until we return to remove_useless_result_rtes.
4519 : : */
4520 : 1035 : }
4521 : :
4522 : :
4523 : : /*
4524 : : * find_dependent_phvs - are there any PlaceHolderVars whose base relids are
4525 : : * exactly the given varno?
4526 : : *
4527 : : * We ignore outer-join relids present in a PHV's phrels, by intersecting
4528 : : * with the caller-supplied "baserels" set. This is necessary in part
4529 : : * because some of the OJ relids may be stale, that is we may have
4530 : : * already decided to remove those joins in remove_useless_result_rtes
4531 : : * and not yet have cleaned their relid bits out of upper PHVs.
4532 : : * But in general, it's the set of baserels that identify possible places
4533 : : * to evaluate a PHV, and we mustn't let that go to empty. (The caller is
4534 : : * allowed to pass baserels as NULL if the query contains no PHVs at all,
4535 : : * since then there is no work to do anyway.)
4536 : : *
4537 : : * find_dependent_phvs should be used when we want to see if there are
4538 : : * any such PHVs anywhere in the Query. Another use-case is to see if
4539 : : * a subtree of the join tree contains such PHVs; but for that, we have
4540 : : * to look not only at the join tree nodes themselves but at the
4541 : : * referenced RTEs. For that, use find_dependent_phvs_in_jointree.
4542 : : */
4543 : :
4544 : : typedef struct
4545 : : {
4546 : : Relids relids; /* target relid, represented as a relid set */
4547 : : Relids baserels; /* base RT indexes in query, NULL if no PHVs */
4548 : : int sublevels_up; /* current nesting level */
4549 : : } find_dependent_phvs_context;
4550 : :
4551 : : static bool
4552 : 1785 : find_dependent_phvs_walker(Node *node,
4553 : : find_dependent_phvs_context *context)
4554 : : {
4555 [ + + ]: 1785 : if (node == NULL)
4556 : 451 : return false;
4557 [ + + ]: 1334 : if (IsA(node, PlaceHolderVar))
4558 : : {
4559 : 124 : PlaceHolderVar *phv = (PlaceHolderVar *) node;
4560 : :
4561 [ + - ]: 124 : if (phv->phlevelsup == context->sublevels_up)
4562 : : {
4563 : 124 : Relids phbaserels = bms_intersect(phv->phrels,
4564 : 124 : context->baserels);
4565 : 124 : bool match = bms_equal(context->relids, phbaserels);
4566 : :
4567 : 124 : bms_free(phbaserels);
4568 [ + + ]: 124 : if (match)
4569 : 89 : return true;
4570 : : }
4571 : : /* fall through to examine children */
4572 : : }
4573 [ + + ]: 1245 : if (IsA(node, Query))
4574 : : {
4575 : : /* Recurse into subselects */
4576 : : bool result;
4577 : :
4578 : 40 : context->sublevels_up++;
4579 : 40 : result = query_tree_walker((Query *) node,
4580 : : find_dependent_phvs_walker,
4581 : : context, 0);
4582 : 40 : context->sublevels_up--;
4583 : 40 : return result;
4584 : : }
4585 : : /* Shouldn't need to handle most planner auxiliary nodes here */
4586 : : Assert(!IsA(node, SpecialJoinInfo));
4587 : : Assert(!IsA(node, PlaceHolderInfo));
4588 : : Assert(!IsA(node, MinMaxAggInfo));
4589 : :
4590 : 1205 : return expression_tree_walker(node, find_dependent_phvs_walker, context);
4591 : : }
4592 : :
4593 : : static bool
4594 : 69 : find_dependent_phvs(PlannerInfo *root, int varno, Relids baserels)
4595 : : {
4596 : : find_dependent_phvs_context context;
4597 : :
4598 : : /* If there are no PHVs anywhere, we needn't work hard */
4599 [ - + ]: 69 : if (root->glob->lastPHId == 0)
4600 : 0 : return false;
4601 : :
4602 : 69 : context.relids = bms_make_singleton(varno);
4603 : 69 : context.baserels = baserels;
4604 : 69 : context.sublevels_up = 0;
4605 : :
4606 [ + - ]: 69 : if (query_tree_walker(root->parse, find_dependent_phvs_walker, &context, 0))
4607 : 69 : return true;
4608 : : /* The append_rel_list could be populated already, so check it too */
4609 [ # # ]: 0 : if (expression_tree_walker((Node *) root->append_rel_list,
4610 : : find_dependent_phvs_walker,
4611 : : &context))
4612 : 0 : return true;
4613 : 0 : return false;
4614 : : }
4615 : :
4616 : : static bool
4617 : 376 : find_dependent_phvs_in_jointree(PlannerInfo *root, Node *node, int varno,
4618 : : Relids baserels)
4619 : : {
4620 : : find_dependent_phvs_context context;
4621 : : Relids subrelids;
4622 : : int relid;
4623 : :
4624 : : /* If there are no PHVs anywhere, we needn't work hard */
4625 [ + + ]: 376 : if (root->glob->lastPHId == 0)
4626 : 321 : return false;
4627 : :
4628 : 55 : context.relids = bms_make_singleton(varno);
4629 : 55 : context.baserels = baserels;
4630 : 55 : context.sublevels_up = 0;
4631 : :
4632 : : /*
4633 : : * See if the jointree fragment itself contains references (in join quals)
4634 : : */
4635 [ - + ]: 55 : if (find_dependent_phvs_walker(node, &context))
4636 : 0 : return true;
4637 : :
4638 : : /*
4639 : : * Otherwise, identify the set of referenced RTEs (we can ignore joins,
4640 : : * since they should be flattened already, so their join alias lists no
4641 : : * longer matter), and tediously check each RTE. We can ignore RTEs that
4642 : : * are not marked LATERAL, though, since they couldn't possibly contain
4643 : : * any cross-references to other RTEs.
4644 : : */
4645 : 55 : subrelids = get_relids_in_jointree(node, false, false);
4646 : 55 : relid = -1;
4647 [ + + ]: 120 : while ((relid = bms_next_member(subrelids, relid)) >= 0)
4648 : : {
4649 : 85 : RangeTblEntry *rte = rt_fetch(relid, root->parse->rtable);
4650 : :
4651 [ + + + - ]: 105 : if (rte->lateral &&
4652 : 20 : range_table_entry_walker(rte, find_dependent_phvs_walker, &context, 0))
4653 : 20 : return true;
4654 : : }
4655 : :
4656 : 35 : return false;
4657 : : }
4658 : :
4659 : : /*
4660 : : * substitute_phv_relids - adjust PlaceHolderVar relid sets after pulling up
4661 : : * a subquery or removing an RTE_RESULT jointree item
4662 : : *
4663 : : * Find any PlaceHolderVar nodes in the given tree that reference the
4664 : : * pulled-up relid, and change them to reference the replacement relid(s).
4665 : : *
4666 : : * NOTE: although this has the form of a walker, we cheat and modify the
4667 : : * nodes in-place. This should be OK since the tree was copied by
4668 : : * pullup_replace_vars earlier. Avoid scribbling on the original values of
4669 : : * the bitmapsets, though, because expression_tree_mutator doesn't copy those.
4670 : : */
4671 : :
4672 : : typedef struct
4673 : : {
4674 : : int varno;
4675 : : int sublevels_up;
4676 : : Relids subrelids;
4677 : : } substitute_phv_relids_context;
4678 : :
4679 : : static bool
4680 : 236092 : substitute_phv_relids_walker(Node *node,
4681 : : substitute_phv_relids_context *context)
4682 : : {
4683 [ + + ]: 236092 : if (node == NULL)
4684 : 97270 : return false;
4685 [ + + ]: 138822 : if (IsA(node, PlaceHolderVar))
4686 : : {
4687 : 6782 : PlaceHolderVar *phv = (PlaceHolderVar *) node;
4688 : :
4689 [ + + + + ]: 13540 : if (phv->phlevelsup == context->sublevels_up &&
4690 : 6758 : bms_is_member(context->varno, phv->phrels))
4691 : : {
4692 : 9832 : phv->phrels = bms_union(phv->phrels,
4693 : 4916 : context->subrelids);
4694 : 4916 : phv->phrels = bms_del_member(phv->phrels,
4695 : : context->varno);
4696 : : /* Assert we haven't broken the PHV */
4697 : : Assert(!bms_is_empty(phv->phrels));
4698 : : }
4699 : : /* fall through to examine children */
4700 : : }
4701 [ + + ]: 138822 : if (IsA(node, Query))
4702 : : {
4703 : : /* Recurse into subselects */
4704 : : bool result;
4705 : :
4706 : 3967 : context->sublevels_up++;
4707 : 3967 : result = query_tree_walker((Query *) node,
4708 : : substitute_phv_relids_walker,
4709 : : context, 0);
4710 : 3967 : context->sublevels_up--;
4711 : 3967 : return result;
4712 : : }
4713 : : /* Shouldn't need to handle planner auxiliary nodes here */
4714 : : Assert(!IsA(node, SpecialJoinInfo));
4715 : : Assert(!IsA(node, AppendRelInfo));
4716 : : Assert(!IsA(node, PlaceHolderInfo));
4717 : : Assert(!IsA(node, MinMaxAggInfo));
4718 : :
4719 : 134855 : return expression_tree_walker(node, substitute_phv_relids_walker, context);
4720 : : }
4721 : :
4722 : : static void
4723 : 2203 : substitute_phv_relids(Node *node, int varno, Relids subrelids)
4724 : : {
4725 : : substitute_phv_relids_context context;
4726 : :
4727 : 2203 : context.varno = varno;
4728 : 2203 : context.sublevels_up = 0;
4729 : 2203 : context.subrelids = subrelids;
4730 : :
4731 : : /*
4732 : : * Must be prepared to start with a Query or a bare expression tree.
4733 : : */
4734 : 2203 : query_or_expression_tree_walker(node,
4735 : : substitute_phv_relids_walker,
4736 : : &context,
4737 : : 0);
4738 : 2203 : }
4739 : :
4740 : : /*
4741 : : * fix_append_rel_relids: update RT-index fields of AppendRelInfo nodes
4742 : : *
4743 : : * When we pull up a subquery, any AppendRelInfo references to the subquery's
4744 : : * RT index have to be replaced by the substituted relid (and there had better
4745 : : * be only one). We also need to apply substitute_phv_relids to their
4746 : : * translated_vars lists, since those might contain PlaceHolderVars.
4747 : : *
4748 : : * We assume we may modify the AppendRelInfo nodes in-place.
4749 : : */
4750 : : static void
4751 : 7183 : fix_append_rel_relids(PlannerInfo *root, int varno, Relids subrelids)
4752 : : {
4753 : : ListCell *l;
4754 : 7183 : int subvarno = -1;
4755 : :
4756 : : /*
4757 : : * We only want to extract the member relid once, but we mustn't fail
4758 : : * immediately if there are multiple members; it could be that none of the
4759 : : * AppendRelInfo nodes refer to it. So compute it on first use. Note that
4760 : : * bms_singleton_member will complain if set is not singleton.
4761 : : */
4762 [ + + + + : 16827 : foreach(l, root->append_rel_list)
+ + ]
4763 : : {
4764 : 9644 : AppendRelInfo *appinfo = (AppendRelInfo *) lfirst(l);
4765 : :
4766 : : /* The parent_relid shouldn't ever be a pullup target */
4767 : : Assert(appinfo->parent_relid != varno);
4768 : :
4769 [ + + ]: 9644 : if (appinfo->child_relid == varno)
4770 : : {
4771 [ + - ]: 5165 : if (subvarno < 0)
4772 : 5165 : subvarno = bms_singleton_member(subrelids);
4773 : 5165 : appinfo->child_relid = subvarno;
4774 : : }
4775 : :
4776 : : /* Also fix up any PHVs in its translated vars */
4777 [ + + ]: 9644 : if (root->glob->lastPHId != 0)
4778 : 155 : substitute_phv_relids((Node *) appinfo->translated_vars,
4779 : : varno, subrelids);
4780 : : }
4781 : 7183 : }
4782 : :
4783 : : /*
4784 : : * get_relids_in_jointree: get set of RT indexes present in a jointree
4785 : : *
4786 : : * Base-relation relids are always included in the result.
4787 : : * If include_outer_joins is true, outer-join RT indexes are included.
4788 : : * If include_inner_joins is true, inner-join RT indexes are included.
4789 : : *
4790 : : * Note that for most purposes in the planner, outer joins are included
4791 : : * in standard relid sets. Setting include_inner_joins true is only
4792 : : * appropriate for special purposes during subquery flattening.
4793 : : */
4794 : : Relids
4795 : 83958 : get_relids_in_jointree(Node *jtnode, bool include_outer_joins,
4796 : : bool include_inner_joins)
4797 : : {
4798 : 83958 : Relids result = NULL;
4799 : :
4800 [ - + ]: 83958 : if (jtnode == NULL)
4801 : 0 : return result;
4802 [ + + ]: 83958 : if (IsA(jtnode, RangeTblRef))
4803 : : {
4804 : 42599 : int varno = ((RangeTblRef *) jtnode)->rtindex;
4805 : :
4806 : 42599 : result = bms_make_singleton(varno);
4807 : : }
4808 [ + + ]: 41359 : else if (IsA(jtnode, FromExpr))
4809 : : {
4810 : 34563 : FromExpr *f = (FromExpr *) jtnode;
4811 : : ListCell *l;
4812 : :
4813 [ + - + + : 70918 : foreach(l, f->fromlist)
+ + ]
4814 : : {
4815 : 36355 : result = bms_join(result,
4816 : 36355 : get_relids_in_jointree(lfirst(l),
4817 : : include_outer_joins,
4818 : : include_inner_joins));
4819 : : }
4820 : : }
4821 [ + - ]: 6796 : else if (IsA(jtnode, JoinExpr))
4822 : : {
4823 : 6796 : JoinExpr *j = (JoinExpr *) jtnode;
4824 : :
4825 : 6796 : result = get_relids_in_jointree(j->larg,
4826 : : include_outer_joins,
4827 : : include_inner_joins);
4828 : 6796 : result = bms_join(result,
4829 : : get_relids_in_jointree(j->rarg,
4830 : : include_outer_joins,
4831 : : include_inner_joins));
4832 [ + + ]: 6796 : if (j->rtindex)
4833 : : {
4834 [ + + ]: 6526 : if (j->jointype == JOIN_INNER)
4835 : : {
4836 [ + + ]: 2520 : if (include_inner_joins)
4837 : 651 : result = bms_add_member(result, j->rtindex);
4838 : : }
4839 : : else
4840 : : {
4841 [ + + ]: 4006 : if (include_outer_joins)
4842 : 1780 : result = bms_add_member(result, j->rtindex);
4843 : : }
4844 : : }
4845 : : }
4846 : : else
4847 [ # # ]: 0 : elog(ERROR, "unrecognized node type: %d",
4848 : : (int) nodeTag(jtnode));
4849 : 83958 : return result;
4850 : : }
4851 : :
4852 : : /*
4853 : : * get_relids_for_join: get set of base+OJ RT indexes making up a join
4854 : : */
4855 : : Relids
4856 : 347 : get_relids_for_join(Query *query, int joinrelid)
4857 : : {
4858 : : Node *jtnode;
4859 : :
4860 : 347 : jtnode = find_jointree_node_for_rel((Node *) query->jointree,
4861 : : joinrelid);
4862 [ - + ]: 347 : if (!jtnode)
4863 [ # # ]: 0 : elog(ERROR, "could not find join node %d", joinrelid);
4864 : 347 : return get_relids_in_jointree(jtnode, true, false);
4865 : : }
4866 : :
4867 : : /*
4868 : : * find_jointree_node_for_rel: locate jointree node for a base or join RT index
4869 : : *
4870 : : * Returns NULL if not found
4871 : : */
4872 : : static Node *
4873 : 1625 : find_jointree_node_for_rel(Node *jtnode, int relid)
4874 : : {
4875 [ - + ]: 1625 : if (jtnode == NULL)
4876 : 0 : return NULL;
4877 [ + + ]: 1625 : if (IsA(jtnode, RangeTblRef))
4878 : : {
4879 : 422 : int varno = ((RangeTblRef *) jtnode)->rtindex;
4880 : :
4881 [ - + ]: 422 : if (relid == varno)
4882 : 0 : return jtnode;
4883 : : }
4884 [ + + ]: 1203 : else if (IsA(jtnode, FromExpr))
4885 : : {
4886 : 354 : FromExpr *f = (FromExpr *) jtnode;
4887 : : ListCell *l;
4888 : :
4889 [ + - + - : 369 : foreach(l, f->fromlist)
+ - ]
4890 : : {
4891 : 369 : jtnode = find_jointree_node_for_rel(lfirst(l), relid);
4892 [ + + ]: 369 : if (jtnode)
4893 : 354 : return jtnode;
4894 : : }
4895 : : }
4896 [ + - ]: 849 : else if (IsA(jtnode, JoinExpr))
4897 : : {
4898 : 849 : JoinExpr *j = (JoinExpr *) jtnode;
4899 : :
4900 [ + + ]: 849 : if (relid == j->rtindex)
4901 : 347 : return jtnode;
4902 : 502 : jtnode = find_jointree_node_for_rel(j->larg, relid);
4903 [ + + ]: 502 : if (jtnode)
4904 : 95 : return jtnode;
4905 : 407 : jtnode = find_jointree_node_for_rel(j->rarg, relid);
4906 [ + - ]: 407 : if (jtnode)
4907 : 407 : return jtnode;
4908 : : }
4909 : : else
4910 [ # # ]: 0 : elog(ERROR, "unrecognized node type: %d",
4911 : : (int) nodeTag(jtnode));
4912 : 422 : return NULL;
4913 : : }
4914 : :
4915 : : /*
4916 : : * get_nullingrels: collect info about which outer joins null which relations
4917 : : *
4918 : : * The result struct contains, for each leaf relation used in the query,
4919 : : * the set of relids of outer joins that potentially null that rel.
4920 : : */
4921 : : static nullingrel_info *
4922 : 1390 : get_nullingrels(Query *parse)
4923 : : {
4924 : 1390 : nullingrel_info *result = palloc_object(nullingrel_info);
4925 : :
4926 : 1390 : result->rtlength = list_length(parse->rtable);
4927 : 1390 : result->nullingrels = palloc0_array(Relids, result->rtlength + 1);
4928 : 1390 : get_nullingrels_recurse((Node *) parse->jointree, NULL, result);
4929 : 1390 : return result;
4930 : : }
4931 : :
4932 : : /*
4933 : : * Recursive guts of get_nullingrels().
4934 : : *
4935 : : * Note: at any recursion level, the passed-down upper_nullingrels must be
4936 : : * treated as a constant, but it can be stored directly into *info
4937 : : * if we're at leaf level. Upper recursion levels do not free their mutated
4938 : : * copies of the nullingrels, because those are probably referenced by
4939 : : * at least one leaf rel.
4940 : : */
4941 : : static void
4942 : 5699 : get_nullingrels_recurse(Node *jtnode, Relids upper_nullingrels,
4943 : : nullingrel_info *info)
4944 : : {
4945 [ - + ]: 5699 : if (jtnode == NULL)
4946 : 0 : return;
4947 [ + + ]: 5699 : if (IsA(jtnode, RangeTblRef))
4948 : : {
4949 : 3010 : int varno = ((RangeTblRef *) jtnode)->rtindex;
4950 : :
4951 : : Assert(varno > 0 && varno <= info->rtlength);
4952 : 3010 : info->nullingrels[varno] = upper_nullingrels;
4953 : : }
4954 [ + + ]: 2689 : else if (IsA(jtnode, FromExpr))
4955 : : {
4956 : 1460 : FromExpr *f = (FromExpr *) jtnode;
4957 : : ListCell *l;
4958 : :
4959 [ + - + + : 3311 : foreach(l, f->fromlist)
+ + ]
4960 : : {
4961 : 1851 : get_nullingrels_recurse(lfirst(l), upper_nullingrels, info);
4962 : : }
4963 : : }
4964 [ + - ]: 1229 : else if (IsA(jtnode, JoinExpr))
4965 : : {
4966 : 1229 : JoinExpr *j = (JoinExpr *) jtnode;
4967 : : Relids local_nullingrels;
4968 : :
4969 [ + + + - : 1229 : switch (j->jointype)
- ]
4970 : : {
4971 : 403 : case JOIN_INNER:
4972 : 403 : get_nullingrels_recurse(j->larg, upper_nullingrels, info);
4973 : 403 : get_nullingrels_recurse(j->rarg, upper_nullingrels, info);
4974 : 403 : break;
4975 : 821 : case JOIN_LEFT:
4976 : : case JOIN_SEMI:
4977 : : case JOIN_ANTI:
4978 : 821 : local_nullingrels = bms_add_member(bms_copy(upper_nullingrels),
4979 : : j->rtindex);
4980 : 821 : get_nullingrels_recurse(j->larg, upper_nullingrels, info);
4981 : 821 : get_nullingrels_recurse(j->rarg, local_nullingrels, info);
4982 : 821 : break;
4983 : 5 : case JOIN_FULL:
4984 : 5 : local_nullingrels = bms_add_member(bms_copy(upper_nullingrels),
4985 : : j->rtindex);
4986 : 5 : get_nullingrels_recurse(j->larg, local_nullingrels, info);
4987 : 5 : get_nullingrels_recurse(j->rarg, local_nullingrels, info);
4988 : 5 : break;
4989 : 0 : case JOIN_RIGHT:
4990 : 0 : local_nullingrels = bms_add_member(bms_copy(upper_nullingrels),
4991 : : j->rtindex);
4992 : 0 : get_nullingrels_recurse(j->larg, local_nullingrels, info);
4993 : 0 : get_nullingrels_recurse(j->rarg, upper_nullingrels, info);
4994 : 0 : break;
4995 : 0 : default:
4996 [ # # ]: 0 : elog(ERROR, "unrecognized join type: %d",
4997 : : (int) j->jointype);
4998 : : break;
4999 : : }
5000 : : }
5001 : : else
5002 [ # # ]: 0 : elog(ERROR, "unrecognized node type: %d",
5003 : : (int) nodeTag(jtnode));
5004 : : }
|