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