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