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