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