Age Owner Branch data TLA Line data Source code
1 : : /*-------------------------------------------------------------------------
2 : : *
3 : : * setrefs.c
4 : : * Post-processing of a completed plan tree: fix references to subplan
5 : : * vars, compute regproc values for operators, etc
6 : : *
7 : : * Portions Copyright (c) 1996-2025, PostgreSQL Global Development Group
8 : : * Portions Copyright (c) 1994, Regents of the University of California
9 : : *
10 : : *
11 : : * IDENTIFICATION
12 : : * src/backend/optimizer/plan/setrefs.c
13 : : *
14 : : *-------------------------------------------------------------------------
15 : : */
16 : : #include "postgres.h"
17 : :
18 : : #include "access/transam.h"
19 : : #include "catalog/pg_type.h"
20 : : #include "nodes/makefuncs.h"
21 : : #include "nodes/nodeFuncs.h"
22 : : #include "optimizer/optimizer.h"
23 : : #include "optimizer/pathnode.h"
24 : : #include "optimizer/planmain.h"
25 : : #include "optimizer/planner.h"
26 : : #include "optimizer/subselect.h"
27 : : #include "optimizer/tlist.h"
28 : : #include "parser/parse_relation.h"
29 : : #include "rewrite/rewriteManip.h"
30 : : #include "tcop/utility.h"
31 : : #include "utils/syscache.h"
32 : :
33 : :
34 : : typedef enum
35 : : {
36 : : NRM_EQUAL, /* expect exact match of nullingrels */
37 : : NRM_SUBSET, /* actual Var may have a subset of input */
38 : : NRM_SUPERSET, /* actual Var may have a superset of input */
39 : : } NullingRelsMatch;
40 : :
41 : : typedef struct
42 : : {
43 : : int varno; /* RT index of Var */
44 : : AttrNumber varattno; /* attr number of Var */
45 : : AttrNumber resno; /* TLE position of Var */
46 : : Bitmapset *varnullingrels; /* Var's varnullingrels */
47 : : } tlist_vinfo;
48 : :
49 : : typedef struct
50 : : {
51 : : List *tlist; /* underlying target list */
52 : : int num_vars; /* number of plain Var tlist entries */
53 : : bool has_ph_vars; /* are there PlaceHolderVar entries? */
54 : : bool has_non_vars; /* are there other entries? */
55 : : tlist_vinfo vars[FLEXIBLE_ARRAY_MEMBER]; /* has num_vars entries */
56 : : } indexed_tlist;
57 : :
58 : : typedef struct
59 : : {
60 : : PlannerInfo *root;
61 : : int rtoffset;
62 : : double num_exec;
63 : : } fix_scan_expr_context;
64 : :
65 : : typedef struct
66 : : {
67 : : PlannerInfo *root;
68 : : indexed_tlist *outer_itlist;
69 : : indexed_tlist *inner_itlist;
70 : : Index acceptable_rel;
71 : : int rtoffset;
72 : : NullingRelsMatch nrm_match;
73 : : double num_exec;
74 : : } fix_join_expr_context;
75 : :
76 : : typedef struct
77 : : {
78 : : PlannerInfo *root;
79 : : indexed_tlist *subplan_itlist;
80 : : int newvarno;
81 : : int rtoffset;
82 : : NullingRelsMatch nrm_match;
83 : : double num_exec;
84 : : } fix_upper_expr_context;
85 : :
86 : : typedef struct
87 : : {
88 : : PlannerInfo *root;
89 : : indexed_tlist *subplan_itlist;
90 : : int newvarno;
91 : : } fix_windowagg_cond_context;
92 : :
93 : : /* Context info for flatten_rtes_walker() */
94 : : typedef struct
95 : : {
96 : : PlannerGlobal *glob;
97 : : Query *query;
98 : : } flatten_rtes_walker_context;
99 : :
100 : : /*
101 : : * Selecting the best alternative in an AlternativeSubPlan expression requires
102 : : * estimating how many times that expression will be evaluated. For an
103 : : * expression in a plan node's targetlist, the plan's estimated number of
104 : : * output rows is clearly what to use, but for an expression in a qual it's
105 : : * far less clear. Since AlternativeSubPlans aren't heavily used, we don't
106 : : * want to expend a lot of cycles making such estimates. What we use is twice
107 : : * the number of output rows. That's not entirely unfounded: we know that
108 : : * clause_selectivity() would fall back to a default selectivity estimate
109 : : * of 0.5 for any SubPlan, so if the qual containing the SubPlan is the last
110 : : * to be applied (which it likely would be, thanks to order_qual_clauses()),
111 : : * this matches what we could have estimated in a far more laborious fashion.
112 : : * Obviously there are many other scenarios, but it's probably not worth the
113 : : * trouble to try to improve on this estimate, especially not when we don't
114 : : * have a better estimate for the selectivity of the SubPlan qual itself.
115 : : */
116 : : #define NUM_EXEC_TLIST(parentplan) ((parentplan)->plan_rows)
117 : : #define NUM_EXEC_QUAL(parentplan) ((parentplan)->plan_rows * 2.0)
118 : :
119 : : /*
120 : : * Check if a Const node is a regclass value. We accept plain OID too,
121 : : * since a regclass Const will get folded to that type if it's an argument
122 : : * to oideq or similar operators. (This might result in some extraneous
123 : : * values in a plan's list of relation dependencies, but the worst result
124 : : * would be occasional useless replans.)
125 : : */
126 : : #define ISREGCLASSCONST(con) \
127 : : (((con)->consttype == REGCLASSOID || (con)->consttype == OIDOID) && \
128 : : !(con)->constisnull)
129 : :
130 : : #define fix_scan_list(root, lst, rtoffset, num_exec) \
131 : : ((List *) fix_scan_expr(root, (Node *) (lst), rtoffset, num_exec))
132 : :
133 : : static void add_rtes_to_flat_rtable(PlannerInfo *root, bool recursing);
134 : : static void flatten_unplanned_rtes(PlannerGlobal *glob, RangeTblEntry *rte);
135 : : static bool flatten_rtes_walker(Node *node, flatten_rtes_walker_context *cxt);
136 : : static void add_rte_to_flat_rtable(PlannerGlobal *glob, List *rteperminfos,
137 : : RangeTblEntry *rte);
138 : : static Plan *set_plan_refs(PlannerInfo *root, Plan *plan, int rtoffset);
139 : : static Plan *set_indexonlyscan_references(PlannerInfo *root,
140 : : IndexOnlyScan *plan,
141 : : int rtoffset);
142 : : static Plan *set_subqueryscan_references(PlannerInfo *root,
143 : : SubqueryScan *plan,
144 : : int rtoffset);
145 : : static Plan *clean_up_removed_plan_level(Plan *parent, Plan *child);
146 : : static void set_foreignscan_references(PlannerInfo *root,
147 : : ForeignScan *fscan,
148 : : int rtoffset);
149 : : static void set_customscan_references(PlannerInfo *root,
150 : : CustomScan *cscan,
151 : : int rtoffset);
152 : : static Plan *set_append_references(PlannerInfo *root,
153 : : Append *aplan,
154 : : int rtoffset);
155 : : static Plan *set_mergeappend_references(PlannerInfo *root,
156 : : MergeAppend *mplan,
157 : : int rtoffset);
158 : : static void set_hash_references(PlannerInfo *root, Plan *plan, int rtoffset);
159 : : static Relids offset_relid_set(Relids relids, int rtoffset);
160 : : static Node *fix_scan_expr(PlannerInfo *root, Node *node,
161 : : int rtoffset, double num_exec);
162 : : static Node *fix_scan_expr_mutator(Node *node, fix_scan_expr_context *context);
163 : : static bool fix_scan_expr_walker(Node *node, fix_scan_expr_context *context);
164 : : static void set_join_references(PlannerInfo *root, Join *join, int rtoffset);
165 : : static void set_upper_references(PlannerInfo *root, Plan *plan, int rtoffset);
166 : : static void set_param_references(PlannerInfo *root, Plan *plan);
167 : : static Node *convert_combining_aggrefs(Node *node, void *context);
168 : : static void set_dummy_tlist_references(Plan *plan, int rtoffset);
169 : : static indexed_tlist *build_tlist_index(List *tlist);
170 : : static Var *search_indexed_tlist_for_var(Var *var,
171 : : indexed_tlist *itlist,
172 : : int newvarno,
173 : : int rtoffset,
174 : : NullingRelsMatch nrm_match);
175 : : static Var *search_indexed_tlist_for_phv(PlaceHolderVar *phv,
176 : : indexed_tlist *itlist,
177 : : int newvarno,
178 : : NullingRelsMatch nrm_match);
179 : : static Var *search_indexed_tlist_for_non_var(Expr *node,
180 : : indexed_tlist *itlist,
181 : : int newvarno);
182 : : static Var *search_indexed_tlist_for_sortgroupref(Expr *node,
183 : : Index sortgroupref,
184 : : indexed_tlist *itlist,
185 : : int newvarno);
186 : : static List *fix_join_expr(PlannerInfo *root,
187 : : List *clauses,
188 : : indexed_tlist *outer_itlist,
189 : : indexed_tlist *inner_itlist,
190 : : Index acceptable_rel,
191 : : int rtoffset,
192 : : NullingRelsMatch nrm_match,
193 : : double num_exec);
194 : : static Node *fix_join_expr_mutator(Node *node,
195 : : fix_join_expr_context *context);
196 : : static Node *fix_upper_expr(PlannerInfo *root,
197 : : Node *node,
198 : : indexed_tlist *subplan_itlist,
199 : : int newvarno,
200 : : int rtoffset,
201 : : NullingRelsMatch nrm_match,
202 : : double num_exec);
203 : : static Node *fix_upper_expr_mutator(Node *node,
204 : : fix_upper_expr_context *context);
205 : : static List *set_returning_clause_references(PlannerInfo *root,
206 : : List *rlist,
207 : : Plan *topplan,
208 : : Index resultRelation,
209 : : int rtoffset);
210 : : static List *set_windowagg_runcondition_references(PlannerInfo *root,
211 : : List *runcondition,
212 : : Plan *plan);
213 : :
214 : :
215 : : /*****************************************************************************
216 : : *
217 : : * SUBPLAN REFERENCES
218 : : *
219 : : *****************************************************************************/
220 : :
221 : : /*
222 : : * set_plan_references
223 : : *
224 : : * This is the final processing pass of the planner/optimizer. The plan
225 : : * tree is complete; we just have to adjust some representational details
226 : : * for the convenience of the executor:
227 : : *
228 : : * 1. We flatten the various subquery rangetables into a single list, and
229 : : * zero out RangeTblEntry fields that are not useful to the executor.
230 : : *
231 : : * 2. We adjust Vars in scan nodes to be consistent with the flat rangetable.
232 : : *
233 : : * 3. We adjust Vars in upper plan nodes to refer to the outputs of their
234 : : * subplans.
235 : : *
236 : : * 4. Aggrefs in Agg plan nodes need to be adjusted in some cases involving
237 : : * partial aggregation or minmax aggregate optimization.
238 : : *
239 : : * 5. PARAM_MULTIEXPR Params are replaced by regular PARAM_EXEC Params,
240 : : * now that we have finished planning all MULTIEXPR subplans.
241 : : *
242 : : * 6. AlternativeSubPlan expressions are replaced by just one of their
243 : : * alternatives, using an estimate of how many times they'll be executed.
244 : : *
245 : : * 7. We compute regproc OIDs for operators (ie, we look up the function
246 : : * that implements each op).
247 : : *
248 : : * 8. We create lists of specific objects that the plan depends on.
249 : : * This will be used by plancache.c to drive invalidation of cached plans.
250 : : * Relation dependencies are represented by OIDs, and everything else by
251 : : * PlanInvalItems (this distinction is motivated by the shared-inval APIs).
252 : : * Currently, relations, user-defined functions, and domains are the only
253 : : * types of objects that are explicitly tracked this way.
254 : : *
255 : : * 9. We assign every plan node in the tree a unique ID.
256 : : *
257 : : * We also perform one final optimization step, which is to delete
258 : : * SubqueryScan, Append, and MergeAppend plan nodes that aren't doing
259 : : * anything useful. The reason for doing this last is that
260 : : * it can't readily be done before set_plan_references, because it would
261 : : * break set_upper_references: the Vars in the child plan's top tlist
262 : : * wouldn't match up with the Vars in the outer plan tree. A SubqueryScan
263 : : * serves a necessary function as a buffer between outer query and subquery
264 : : * variable numbering ... but after we've flattened the rangetable this is
265 : : * no longer a problem, since then there's only one rtindex namespace.
266 : : * Likewise, Append and MergeAppend buffer between the parent and child vars
267 : : * of an appendrel, but we don't need to worry about that once we've done
268 : : * set_plan_references.
269 : : *
270 : : * set_plan_references recursively traverses the whole plan tree.
271 : : *
272 : : * The return value is normally the same Plan node passed in, but can be
273 : : * different when the passed-in Plan is a node we decide isn't needed.
274 : : *
275 : : * The flattened rangetable entries are appended to root->glob->finalrtable.
276 : : * Also, rowmarks entries are appended to root->glob->finalrowmarks, and the
277 : : * RT indexes of ModifyTable result relations to root->glob->resultRelations,
278 : : * and flattened AppendRelInfos are appended to root->glob->appendRelations.
279 : : * Plan dependencies are appended to root->glob->relationOids (for relations)
280 : : * and root->glob->invalItems (for everything else).
281 : : *
282 : : * Notice that we modify Plan nodes in-place, but use expression_tree_mutator
283 : : * to process targetlist and qual expressions. We can assume that the Plan
284 : : * nodes were just built by the planner and are not multiply referenced, but
285 : : * it's not so safe to assume that for expression tree nodes.
286 : : */
287 : : Plan *
5219 tgl@sss.pgh.pa.us 288 :CBC 269774 : set_plan_references(PlannerInfo *root, Plan *plan)
289 : : {
290 : : Plan *result;
291 : 269774 : PlannerGlobal *glob = root->glob;
6873 292 : 269774 : int rtoffset = list_length(glob->finalrtable);
293 : : ListCell *lc;
294 : :
295 : : /*
296 : : * Add all the query's RTEs to the flattened rangetable. The live ones
297 : : * will have their rangetable indexes increased by rtoffset. (Additional
298 : : * RTEs, not referenced by the Plan tree, might get added after those.)
299 : : */
4606 300 : 269774 : add_rtes_to_flat_rtable(root, false);
301 : :
302 : : /*
303 : : * Adjust RT indexes of PlanRowMarks and add to final rowmarks list
304 : : */
5219 305 [ + + + + : 279257 : foreach(lc, root->rowMarks)
+ + ]
306 : : {
3173 307 : 9483 : PlanRowMark *rc = lfirst_node(PlanRowMark, lc);
308 : : PlanRowMark *newrc;
309 : :
310 : : /* sanity check on existing row marks */
115 akorotkov@postgresql 311 [ + - - + ]: 9483 : Assert(root->simple_rel_array[rc->rti] != NULL &&
312 : : root->simple_rte_array[rc->rti] != NULL);
313 : :
314 : : /* flat copy is enough since all fields are scalars */
7 michael@paquier.xyz 315 :GNC 9483 : newrc = palloc_object(PlanRowMark);
5896 tgl@sss.pgh.pa.us 316 :CBC 9483 : memcpy(newrc, rc, sizeof(PlanRowMark));
317 : :
318 : : /* adjust indexes ... but *not* the rowmarkId */
5910 319 : 9483 : newrc->rti += rtoffset;
320 : 9483 : newrc->prti += rtoffset;
321 : :
322 : 9483 : glob->finalrowmarks = lappend(glob->finalrowmarks, newrc);
323 : : }
324 : :
325 : : /*
326 : : * Adjust RT indexes of AppendRelInfos and add to final appendrels list.
327 : : * We assume the AppendRelInfos were built during planning and don't need
328 : : * to be copied.
329 : : */
2198 330 [ + + + + : 299422 : foreach(lc, root->append_rel_list)
+ + ]
331 : : {
332 : 29648 : AppendRelInfo *appinfo = lfirst_node(AppendRelInfo, lc);
333 : :
334 : : /* adjust RT indexes */
335 : 29648 : appinfo->parent_relid += rtoffset;
336 : 29648 : appinfo->child_relid += rtoffset;
337 : :
338 : : /*
339 : : * Rather than adjust the translated_vars entries, just drop 'em.
340 : : * Neither the executor nor EXPLAIN currently need that data.
341 : : */
342 : 29648 : appinfo->translated_vars = NIL;
343 : :
344 : 29648 : glob->appendRelations = lappend(glob->appendRelations, appinfo);
345 : : }
346 : :
347 : : /* If needed, create workspace for processing AlternativeSubPlans */
1555 348 [ + + ]: 269774 : if (root->hasAlternativeSubPlans)
349 : : {
350 : 554 : root->isAltSubplan = (bool *)
351 : 554 : palloc0(list_length(glob->subplans) * sizeof(bool));
352 : 554 : root->isUsedSubplan = (bool *)
353 : 554 : palloc0(list_length(glob->subplans) * sizeof(bool));
354 : : }
355 : :
356 : : /* Now fix the Plan tree */
357 : 269774 : result = set_plan_refs(root, plan, rtoffset);
358 : :
359 : : /*
360 : : * If we have AlternativeSubPlans, it is likely that we now have some
361 : : * unreferenced subplans in glob->subplans. To avoid expending cycles on
362 : : * those subplans later, get rid of them by setting those list entries to
363 : : * NULL. (Note: we can't do this immediately upon processing an
364 : : * AlternativeSubPlan, because there may be multiple copies of the
365 : : * AlternativeSubPlan, and they can get resolved differently.)
366 : : */
367 [ + + ]: 269774 : if (root->hasAlternativeSubPlans)
368 : : {
369 [ + - + + : 2688 : foreach(lc, glob->subplans)
+ + ]
370 : : {
371 : 2134 : int ndx = foreach_current_index(lc);
372 : :
373 : : /*
374 : : * If it was used by some AlternativeSubPlan in this query level,
375 : : * but wasn't selected as best by any AlternativeSubPlan, then we
376 : : * don't need it. Do not touch subplans that aren't parts of
377 : : * AlternativeSubPlans.
378 : : */
379 [ + + + + ]: 2134 : if (root->isAltSubplan[ndx] && !root->isUsedSubplan[ndx])
380 : 849 : lfirst(lc) = NULL;
381 : : }
382 : : }
383 : :
384 : 269774 : return result;
385 : : }
386 : :
387 : : /*
388 : : * Extract RangeTblEntries from the plan's rangetable, and add to flat rtable
389 : : *
390 : : * This can recurse into subquery plans; "recursing" is true if so.
391 : : *
392 : : * This also seems like a good place to add the query's RTEPermissionInfos to
393 : : * the flat rteperminfos.
394 : : */
395 : : static void
4606 396 : 269909 : add_rtes_to_flat_rtable(PlannerInfo *root, bool recursing)
397 : : {
398 : 269909 : PlannerGlobal *glob = root->glob;
399 : : Index rti;
400 : : ListCell *lc;
401 : :
402 : : /*
403 : : * Add the query's own RTEs to the flattened rangetable.
404 : : *
405 : : * At top level, we must add all RTEs so that their indexes in the
406 : : * flattened rangetable match up with their original indexes. When
407 : : * recursing, we only care about extracting relation RTEs (and subquery
408 : : * RTEs that were once relation RTEs).
409 : : */
410 [ + - + + : 756652 : foreach(lc, root->parse->rtable)
+ + ]
411 : : {
412 : 486743 : RangeTblEntry *rte = (RangeTblEntry *) lfirst(lc);
413 : :
1064 414 [ + + + + ]: 486743 : if (!recursing || rte->rtekind == RTE_RELATION ||
415 [ + + - + ]: 123 : (rte->rtekind == RTE_SUBQUERY && OidIsValid(rte->relid)))
1107 alvherre@alvh.no-ip. 416 : 486620 : add_rte_to_flat_rtable(glob, root->parse->rteperminfos, rte);
417 : : }
418 : :
419 : : /*
420 : : * If there are any dead subqueries, they are not referenced in the Plan
421 : : * tree, so we must add RTEs contained in them to the flattened rtable
422 : : * separately. (If we failed to do this, the executor would not perform
423 : : * expected permission checks for tables mentioned in such subqueries.)
424 : : *
425 : : * Note: this pass over the rangetable can't be combined with the previous
426 : : * one, because that would mess up the numbering of the live RTEs in the
427 : : * flattened rangetable.
428 : : */
4606 tgl@sss.pgh.pa.us 429 : 269909 : rti = 1;
430 [ + - + + : 756652 : foreach(lc, root->parse->rtable)
+ + ]
431 : : {
432 : 486743 : RangeTblEntry *rte = (RangeTblEntry *) lfirst(lc);
433 : :
434 : : /*
435 : : * We should ignore inheritance-parent RTEs: their contents have been
436 : : * pulled up into our rangetable already. Also ignore any subquery
437 : : * RTEs without matching RelOptInfos, as they likewise have been
438 : : * pulled up.
439 : : */
4386 440 [ + + + + ]: 486743 : if (rte->rtekind == RTE_SUBQUERY && !rte->inh &&
441 [ + - ]: 38395 : rti < root->simple_rel_array_size)
442 : : {
4606 443 : 38395 : RelOptInfo *rel = root->simple_rel_array[rti];
444 : :
445 [ + + ]: 38395 : if (rel != NULL)
446 : : {
3101 447 [ - + ]: 19949 : Assert(rel->relid == rti); /* sanity check on array */
448 : :
449 : : /*
450 : : * The subquery might never have been planned at all, if it
451 : : * was excluded on the basis of self-contradictory constraints
452 : : * in our query level. In this case apply
453 : : * flatten_unplanned_rtes.
454 : : *
455 : : * If it was planned but the result rel is dummy, we assume
456 : : * that it has been omitted from our plan tree (see
457 : : * set_subquery_pathlist), and recurse to pull up its RTEs.
458 : : *
459 : : * Otherwise, it should be represented by a SubqueryScan node
460 : : * somewhere in our plan tree, and we'll pull up its RTEs when
461 : : * we process that plan node.
462 : : *
463 : : * However, if we're recursing, then we should pull up RTEs
464 : : * whether the subquery is dummy or not, because we've found
465 : : * that some upper query level is treating this one as dummy,
466 : : * and so we won't scan this level's plan tree at all.
467 : : */
3572 468 [ + + ]: 19949 : if (rel->subroot == NULL)
4606 469 : 12 : flatten_unplanned_rtes(glob, rte);
3572 470 [ + + + + ]: 39850 : else if (recursing ||
471 : 19913 : IS_DUMMY_REL(fetch_upper_rel(rel->subroot,
472 : : UPPERREL_FINAL, NULL)))
4606 473 : 135 : add_rtes_to_flat_rtable(rel->subroot, true);
474 : : }
475 : : }
476 : 486743 : rti++;
477 : : }
478 : 269909 : }
479 : :
480 : : /*
481 : : * Extract RangeTblEntries from a subquery that was never planned at all
482 : : */
483 : :
484 : : static void
485 : 12 : flatten_unplanned_rtes(PlannerGlobal *glob, RangeTblEntry *rte)
486 : : {
1107 alvherre@alvh.no-ip. 487 : 12 : flatten_rtes_walker_context cxt = {glob, rte->subquery};
488 : :
489 : : /* Use query_tree_walker to find all RTEs in the parse tree */
4606 tgl@sss.pgh.pa.us 490 : 12 : (void) query_tree_walker(rte->subquery,
491 : : flatten_rtes_walker,
492 : : &cxt,
493 : : QTW_EXAMINE_RTES_BEFORE);
494 : 12 : }
495 : :
496 : : static bool
1107 alvherre@alvh.no-ip. 497 : 300 : flatten_rtes_walker(Node *node, flatten_rtes_walker_context *cxt)
498 : : {
4606 tgl@sss.pgh.pa.us 499 [ + + ]: 300 : if (node == NULL)
500 : 174 : return false;
501 [ + + ]: 126 : if (IsA(node, RangeTblEntry))
502 : : {
503 : 9 : RangeTblEntry *rte = (RangeTblEntry *) node;
504 : :
505 : : /* As above, we need only save relation RTEs and former relations */
1064 506 [ - + ]: 9 : if (rte->rtekind == RTE_RELATION ||
1064 tgl@sss.pgh.pa.us 507 [ # # # # ]:UBC 0 : (rte->rtekind == RTE_SUBQUERY && OidIsValid(rte->relid)))
1107 alvherre@alvh.no-ip. 508 :CBC 9 : add_rte_to_flat_rtable(cxt->glob, cxt->query->rteperminfos, rte);
4606 tgl@sss.pgh.pa.us 509 : 9 : return false;
510 : : }
511 [ + + ]: 117 : if (IsA(node, Query))
512 : : {
513 : : /*
514 : : * Recurse into subselects. Must update cxt->query to this query so
515 : : * that the rtable and rteperminfos correspond with each other.
516 : : */
1038 517 : 3 : Query *save_query = cxt->query;
518 : : bool result;
519 : :
1107 alvherre@alvh.no-ip. 520 : 3 : cxt->query = (Query *) node;
1038 tgl@sss.pgh.pa.us 521 : 3 : result = query_tree_walker((Query *) node,
522 : : flatten_rtes_walker,
523 : : cxt,
524 : : QTW_EXAMINE_RTES_BEFORE);
525 : 3 : cxt->query = save_query;
526 : 3 : return result;
527 : : }
384 peter@eisentraut.org 528 : 114 : return expression_tree_walker(node, flatten_rtes_walker, cxt);
529 : : }
530 : :
531 : : /*
532 : : * Add (a copy of) the given RTE to the final rangetable and also the
533 : : * corresponding RTEPermissionInfo, if any, to final rteperminfos.
534 : : *
535 : : * In the flat rangetable, we zero out substructure pointers that are not
536 : : * needed by the executor; this reduces the storage space and copying cost
537 : : * for cached plans. We keep only the ctename, alias, eref Alias fields,
538 : : * which are needed by EXPLAIN, and perminfoindex which is needed by the
539 : : * executor to fetch the RTE's RTEPermissionInfo.
540 : : */
541 : : static void
1107 alvherre@alvh.no-ip. 542 : 486629 : add_rte_to_flat_rtable(PlannerGlobal *glob, List *rteperminfos,
543 : : RangeTblEntry *rte)
544 : : {
545 : : RangeTblEntry *newrte;
546 : :
547 : : /* flat copy to duplicate all the scalar fields */
7 michael@paquier.xyz 548 :GNC 486629 : newrte = palloc_object(RangeTblEntry);
4606 tgl@sss.pgh.pa.us 549 :CBC 486629 : memcpy(newrte, rte, sizeof(RangeTblEntry));
550 : :
551 : : /* zap unneeded sub-structure */
3798 552 : 486629 : newrte->tablesample = NULL;
4606 553 : 486629 : newrte->subquery = NULL;
554 : 486629 : newrte->joinaliasvars = NIL;
2169 555 : 486629 : newrte->joinleftcols = NIL;
556 : 486629 : newrte->joinrightcols = NIL;
1722 peter@eisentraut.org 557 : 486629 : newrte->join_using_alias = NULL;
4409 tgl@sss.pgh.pa.us 558 : 486629 : newrte->functions = NIL;
3206 alvherre@alvh.no-ip. 559 : 486629 : newrte->tablefunc = NULL;
4606 tgl@sss.pgh.pa.us 560 : 486629 : newrte->values_lists = NIL;
3296 561 : 486629 : newrte->coltypes = NIL;
562 : 486629 : newrte->coltypmods = NIL;
563 : 486629 : newrte->colcollations = NIL;
463 rguo@postgresql.org 564 : 486629 : newrte->groupexprs = NIL;
3802 tgl@sss.pgh.pa.us 565 : 486629 : newrte->securityQuals = NIL;
566 : :
4606 567 : 486629 : glob->finalrtable = lappend(glob->finalrtable, newrte);
568 : :
569 : : /*
570 : : * If it's a plain relation RTE (or a subquery that was once a view
571 : : * reference), add the relation OID to relationOids. Also add its new RT
572 : : * index to the set of relations to be potentially accessed during
573 : : * execution.
574 : : *
575 : : * We do this even though the RTE might be unreferenced in the plan tree;
576 : : * this would correspond to cases such as views that were expanded, child
577 : : * tables that were eliminated by constraint exclusion, etc. Schema
578 : : * invalidation on such a rel must still force rebuilding of the plan.
579 : : *
580 : : * Note we don't bother to avoid making duplicate list entries. We could,
581 : : * but it would probably cost more cycles than it would save.
582 : : */
1064 583 [ + + ]: 486629 : if (newrte->rtekind == RTE_RELATION ||
584 [ + + + + ]: 222026 : (newrte->rtekind == RTE_SUBQUERY && OidIsValid(newrte->relid)))
585 : : {
4606 586 : 272648 : glob->relationOids = lappend_oid(glob->relationOids, newrte->relid);
313 amitlan@postgresql.o 587 : 272648 : glob->allRelids = bms_add_member(glob->allRelids,
588 : 272648 : list_length(glob->finalrtable));
589 : : }
590 : :
591 : : /*
592 : : * Add a copy of the RTEPermissionInfo, if any, corresponding to this RTE
593 : : * to the flattened global list.
594 : : */
1107 alvherre@alvh.no-ip. 595 [ + + ]: 486629 : if (rte->perminfoindex > 0)
596 : : {
597 : : RTEPermissionInfo *perminfo;
598 : : RTEPermissionInfo *newperminfo;
599 : :
600 : : /* Get the existing one from this query's rteperminfos. */
601 : 250954 : perminfo = getRTEPermissionInfo(rteperminfos, newrte);
602 : :
603 : : /*
604 : : * Add a new one to finalrteperminfos and copy the contents of the
605 : : * existing one into it. Note that addRTEPermissionInfo() also
606 : : * updates newrte->perminfoindex to point to newperminfo in
607 : : * finalrteperminfos.
608 : : */
609 : 250954 : newrte->perminfoindex = 0; /* expected by addRTEPermissionInfo() */
610 : 250954 : newperminfo = addRTEPermissionInfo(&glob->finalrteperminfos, newrte);
611 : 250954 : memcpy(newperminfo, perminfo, sizeof(RTEPermissionInfo));
612 : : }
4606 tgl@sss.pgh.pa.us 613 : 486629 : }
614 : :
615 : : /*
616 : : * set_plan_refs: recurse through the Plan nodes of a single subquery level
617 : : */
618 : : static Plan *
5219 619 : 1447895 : set_plan_refs(PlannerInfo *root, Plan *plan, int rtoffset)
620 : : {
621 : : ListCell *l;
622 : :
10328 bruce@momjian.us 623 [ + + ]: 1447895 : if (plan == NULL)
7514 tgl@sss.pgh.pa.us 624 : 833952 : return NULL;
625 : :
626 : : /* Assign this node a unique ID. */
3733 rhaas@postgresql.org 627 : 613943 : plan->plan_node_id = root->glob->lastPlanNodeId++;
628 : :
629 : : /*
630 : : * Plan-type-specific fixes
631 : : */
9614 tgl@sss.pgh.pa.us 632 [ + + + + : 613943 : switch (nodeTag(plan))
+ + + + +
+ + + + +
+ + - + +
+ + + + +
+ + + + +
+ + + + +
+ - ]
633 : : {
634 : 110484 : case T_SeqScan:
635 : : {
6607 bruce@momjian.us 636 : 110484 : SeqScan *splan = (SeqScan *) plan;
637 : :
1592 peter@eisentraut.org 638 : 110484 : splan->scan.scanrelid += rtoffset;
639 : 110484 : splan->scan.plan.targetlist =
640 : 110484 : fix_scan_list(root, splan->scan.plan.targetlist,
641 : : rtoffset, NUM_EXEC_TLIST(plan));
642 : 110484 : splan->scan.plan.qual =
643 : 110484 : fix_scan_list(root, splan->scan.plan.qual,
644 : : rtoffset, NUM_EXEC_QUAL(plan));
645 : : }
9614 tgl@sss.pgh.pa.us 646 : 110484 : break;
3869 simon@2ndQuadrant.co 647 : 153 : case T_SampleScan:
648 : : {
3861 bruce@momjian.us 649 : 153 : SampleScan *splan = (SampleScan *) plan;
650 : :
3798 tgl@sss.pgh.pa.us 651 : 153 : splan->scan.scanrelid += rtoffset;
652 : 153 : splan->scan.plan.targetlist =
1907 653 : 153 : fix_scan_list(root, splan->scan.plan.targetlist,
654 : : rtoffset, NUM_EXEC_TLIST(plan));
3798 655 : 153 : splan->scan.plan.qual =
1907 656 : 153 : fix_scan_list(root, splan->scan.plan.qual,
657 : : rtoffset, NUM_EXEC_QUAL(plan));
3798 658 : 153 : splan->tablesample = (TableSampleClause *)
1907 659 : 153 : fix_scan_expr(root, (Node *) splan->tablesample,
660 : : rtoffset, 1);
661 : : }
3869 simon@2ndQuadrant.co 662 : 153 : break;
9614 tgl@sss.pgh.pa.us 663 : 74724 : case T_IndexScan:
664 : : {
6607 bruce@momjian.us 665 : 74724 : IndexScan *splan = (IndexScan *) plan;
666 : :
6873 tgl@sss.pgh.pa.us 667 : 74724 : splan->scan.scanrelid += rtoffset;
668 : 74724 : splan->scan.plan.targetlist =
1907 669 : 74724 : fix_scan_list(root, splan->scan.plan.targetlist,
670 : : rtoffset, NUM_EXEC_TLIST(plan));
6873 671 : 74724 : splan->scan.plan.qual =
1907 672 : 74724 : fix_scan_list(root, splan->scan.plan.qual,
673 : : rtoffset, NUM_EXEC_QUAL(plan));
6873 674 : 74724 : splan->indexqual =
1907 675 : 74724 : fix_scan_list(root, splan->indexqual,
676 : : rtoffset, 1);
6873 677 : 74724 : splan->indexqualorig =
1907 678 : 74724 : fix_scan_list(root, splan->indexqualorig,
679 : : rtoffset, NUM_EXEC_QUAL(plan));
5494 680 : 74724 : splan->indexorderby =
1907 681 : 74724 : fix_scan_list(root, splan->indexorderby,
682 : : rtoffset, 1);
5494 683 : 74724 : splan->indexorderbyorig =
1907 684 : 74724 : fix_scan_list(root, splan->indexorderbyorig,
685 : : rtoffset, NUM_EXEC_QUAL(plan));
686 : : }
9327 687 : 74724 : break;
5181 688 : 8502 : case T_IndexOnlyScan:
689 : : {
4938 bruce@momjian.us 690 : 8502 : IndexOnlyScan *splan = (IndexOnlyScan *) plan;
691 : :
5181 tgl@sss.pgh.pa.us 692 : 8502 : return set_indexonlyscan_references(root, splan, rtoffset);
693 : : }
694 : : break;
7547 695 : 12996 : case T_BitmapIndexScan:
696 : : {
6873 697 : 12996 : BitmapIndexScan *splan = (BitmapIndexScan *) plan;
698 : :
699 : 12996 : splan->scan.scanrelid += rtoffset;
700 : : /* no need to fix targetlist and qual */
701 [ - + ]: 12996 : Assert(splan->scan.plan.targetlist == NIL);
702 [ - + ]: 12996 : Assert(splan->scan.plan.qual == NIL);
703 : 12996 : splan->indexqual =
1907 704 : 12996 : fix_scan_list(root, splan->indexqual, rtoffset, 1);
6873 705 : 12996 : splan->indexqualorig =
1907 706 : 12996 : fix_scan_list(root, splan->indexqualorig,
707 : : rtoffset, NUM_EXEC_QUAL(plan));
708 : : }
7547 709 : 12996 : break;
710 : 12653 : case T_BitmapHeapScan:
711 : : {
6873 712 : 12653 : BitmapHeapScan *splan = (BitmapHeapScan *) plan;
713 : :
714 : 12653 : splan->scan.scanrelid += rtoffset;
715 : 12653 : splan->scan.plan.targetlist =
1907 716 : 12653 : fix_scan_list(root, splan->scan.plan.targetlist,
717 : : rtoffset, NUM_EXEC_TLIST(plan));
6873 718 : 12653 : splan->scan.plan.qual =
1907 719 : 12653 : fix_scan_list(root, splan->scan.plan.qual,
720 : : rtoffset, NUM_EXEC_QUAL(plan));
6873 721 : 12653 : splan->bitmapqualorig =
1907 722 : 12653 : fix_scan_list(root, splan->bitmapqualorig,
723 : : rtoffset, NUM_EXEC_QUAL(plan));
724 : : }
7547 725 : 12653 : break;
9327 726 : 378 : case T_TidScan:
727 : : {
6607 bruce@momjian.us 728 : 378 : TidScan *splan = (TidScan *) plan;
729 : :
6873 tgl@sss.pgh.pa.us 730 : 378 : splan->scan.scanrelid += rtoffset;
731 : 378 : splan->scan.plan.targetlist =
1907 732 : 378 : fix_scan_list(root, splan->scan.plan.targetlist,
733 : : rtoffset, NUM_EXEC_TLIST(plan));
6873 734 : 378 : splan->scan.plan.qual =
1907 735 : 378 : fix_scan_list(root, splan->scan.plan.qual,
736 : : rtoffset, NUM_EXEC_QUAL(plan));
6873 737 : 378 : splan->tidquals =
1907 738 : 378 : fix_scan_list(root, splan->tidquals,
739 : : rtoffset, 1);
740 : : }
9614 741 : 378 : break;
1754 drowley@postgresql.o 742 : 1000 : case T_TidRangeScan:
743 : : {
744 : 1000 : TidRangeScan *splan = (TidRangeScan *) plan;
745 : :
746 : 1000 : splan->scan.scanrelid += rtoffset;
747 : 1000 : splan->scan.plan.targetlist =
748 : 1000 : fix_scan_list(root, splan->scan.plan.targetlist,
749 : : rtoffset, NUM_EXEC_TLIST(plan));
750 : 1000 : splan->scan.plan.qual =
751 : 1000 : fix_scan_list(root, splan->scan.plan.qual,
752 : : rtoffset, NUM_EXEC_QUAL(plan));
753 : 1000 : splan->tidrangequals =
754 : 1000 : fix_scan_list(root, splan->tidrangequals,
755 : : rtoffset, 1);
756 : : }
757 : 1000 : break;
9210 tgl@sss.pgh.pa.us 758 : 19784 : case T_SubqueryScan:
759 : : /* Needs special treatment, see comments below */
5219 760 : 19784 : return set_subqueryscan_references(root,
761 : : (SubqueryScan *) plan,
762 : : rtoffset);
8620 763 : 25133 : case T_FunctionScan:
764 : : {
6873 765 : 25133 : FunctionScan *splan = (FunctionScan *) plan;
766 : :
767 : 25133 : splan->scan.scanrelid += rtoffset;
768 : 25133 : splan->scan.plan.targetlist =
1907 769 : 25133 : fix_scan_list(root, splan->scan.plan.targetlist,
770 : : rtoffset, NUM_EXEC_TLIST(plan));
6873 771 : 25133 : splan->scan.plan.qual =
1907 772 : 25133 : fix_scan_list(root, splan->scan.plan.qual,
773 : : rtoffset, NUM_EXEC_QUAL(plan));
4409 774 : 25133 : splan->functions =
1907 775 : 25133 : fix_scan_list(root, splan->functions, rtoffset, 1);
776 : : }
8620 777 : 25133 : break;
3206 alvherre@alvh.no-ip. 778 : 311 : case T_TableFuncScan:
779 : : {
780 : 311 : TableFuncScan *splan = (TableFuncScan *) plan;
781 : :
782 : 311 : splan->scan.scanrelid += rtoffset;
783 : 311 : splan->scan.plan.targetlist =
1907 tgl@sss.pgh.pa.us 784 : 311 : fix_scan_list(root, splan->scan.plan.targetlist,
785 : : rtoffset, NUM_EXEC_TLIST(plan));
3206 alvherre@alvh.no-ip. 786 : 311 : splan->scan.plan.qual =
1907 tgl@sss.pgh.pa.us 787 : 311 : fix_scan_list(root, splan->scan.plan.qual,
788 : : rtoffset, NUM_EXEC_QUAL(plan));
3206 alvherre@alvh.no-ip. 789 : 311 : splan->tablefunc = (TableFunc *)
1907 tgl@sss.pgh.pa.us 790 : 311 : fix_scan_expr(root, (Node *) splan->tablefunc,
791 : : rtoffset, 1);
792 : : }
3206 alvherre@alvh.no-ip. 793 : 311 : break;
7077 mail@joeconway.com 794 : 4236 : case T_ValuesScan:
795 : : {
6873 tgl@sss.pgh.pa.us 796 : 4236 : ValuesScan *splan = (ValuesScan *) plan;
797 : :
798 : 4236 : splan->scan.scanrelid += rtoffset;
799 : 4236 : splan->scan.plan.targetlist =
1907 800 : 4236 : fix_scan_list(root, splan->scan.plan.targetlist,
801 : : rtoffset, NUM_EXEC_TLIST(plan));
6873 802 : 4236 : splan->scan.plan.qual =
1907 803 : 4236 : fix_scan_list(root, splan->scan.plan.qual,
804 : : rtoffset, NUM_EXEC_QUAL(plan));
6873 805 : 4236 : splan->values_lists =
1907 806 : 4236 : fix_scan_list(root, splan->values_lists,
807 : : rtoffset, 1);
808 : : }
7077 mail@joeconway.com 809 : 4236 : break;
6283 tgl@sss.pgh.pa.us 810 : 2179 : case T_CteScan:
811 : : {
6033 bruce@momjian.us 812 : 2179 : CteScan *splan = (CteScan *) plan;
813 : :
6283 tgl@sss.pgh.pa.us 814 : 2179 : splan->scan.scanrelid += rtoffset;
815 : 2179 : splan->scan.plan.targetlist =
1907 816 : 2179 : fix_scan_list(root, splan->scan.plan.targetlist,
817 : : rtoffset, NUM_EXEC_TLIST(plan));
6283 818 : 2179 : splan->scan.plan.qual =
1907 819 : 2179 : fix_scan_list(root, splan->scan.plan.qual,
820 : : rtoffset, NUM_EXEC_QUAL(plan));
821 : : }
6283 822 : 2179 : break;
3183 kgrittn@postgresql.o 823 : 241 : case T_NamedTuplestoreScan:
824 : : {
825 : 241 : NamedTuplestoreScan *splan = (NamedTuplestoreScan *) plan;
826 : :
827 : 241 : splan->scan.scanrelid += rtoffset;
828 : 241 : splan->scan.plan.targetlist =
1907 tgl@sss.pgh.pa.us 829 : 241 : fix_scan_list(root, splan->scan.plan.targetlist,
830 : : rtoffset, NUM_EXEC_TLIST(plan));
3183 kgrittn@postgresql.o 831 : 241 : splan->scan.plan.qual =
1907 tgl@sss.pgh.pa.us 832 : 241 : fix_scan_list(root, splan->scan.plan.qual,
833 : : rtoffset, NUM_EXEC_QUAL(plan));
834 : : }
3183 kgrittn@postgresql.o 835 : 241 : break;
6283 tgl@sss.pgh.pa.us 836 : 471 : case T_WorkTableScan:
837 : : {
838 : 471 : WorkTableScan *splan = (WorkTableScan *) plan;
839 : :
840 : 471 : splan->scan.scanrelid += rtoffset;
841 : 471 : splan->scan.plan.targetlist =
1907 842 : 471 : fix_scan_list(root, splan->scan.plan.targetlist,
843 : : rtoffset, NUM_EXEC_TLIST(plan));
6283 844 : 471 : splan->scan.plan.qual =
1907 845 : 471 : fix_scan_list(root, splan->scan.plan.qual,
846 : : rtoffset, NUM_EXEC_QUAL(plan));
847 : : }
6283 848 : 471 : break;
5414 849 : 1027 : case T_ForeignScan:
3883 rhaas@postgresql.org 850 : 1027 : set_foreignscan_references(root, (ForeignScan *) plan, rtoffset);
5414 tgl@sss.pgh.pa.us 851 : 1027 : break;
4058 rhaas@postgresql.org 852 :UBC 0 : case T_CustomScan:
3883 853 : 0 : set_customscan_references(root, (CustomScan *) plan, rtoffset);
4058 854 : 0 : break;
855 : :
9614 tgl@sss.pgh.pa.us 856 :CBC 71471 : case T_NestLoop:
857 : : case T_MergeJoin:
858 : : case T_HashJoin:
5219 859 : 71471 : set_join_references(root, (Join *) plan, rtoffset);
9614 860 : 71471 : break;
861 : :
3703 rhaas@postgresql.org 862 : 750 : case T_Gather:
863 : : case T_GatherMerge:
864 : : {
2953 865 : 750 : set_upper_references(root, plan, rtoffset);
866 : 750 : set_param_references(root, plan);
867 : : }
3703 868 : 750 : break;
869 : :
8372 tgl@sss.pgh.pa.us 870 : 18056 : case T_Hash:
2329 andres@anarazel.de 871 : 18056 : set_hash_references(root, plan, rtoffset);
872 : 18056 : break;
873 : :
1617 drowley@postgresql.o 874 : 1022 : case T_Memoize:
875 : : {
876 : 1022 : Memoize *mplan = (Memoize *) plan;
877 : :
878 : : /*
879 : : * Memoize does not evaluate its targetlist. It just uses the
880 : : * same targetlist from its outer subnode.
881 : : */
1667 882 : 1022 : set_dummy_tlist_references(plan, rtoffset);
883 : :
1617 884 : 1022 : mplan->param_exprs = fix_scan_list(root, mplan->param_exprs,
885 : : rtoffset,
886 : : NUM_EXEC_TLIST(plan));
1720 887 : 1022 : break;
888 : : }
889 : :
9614 tgl@sss.pgh.pa.us 890 : 45915 : case T_Material:
891 : : case T_Sort:
892 : : case T_IncrementalSort:
893 : : case T_Unique:
894 : : case T_SetOp:
895 : :
896 : : /*
897 : : * These plan types don't actually bother to evaluate their
898 : : * targetlists, because they just return their unmodified input
899 : : * tuples. Even though the targetlist won't be used by the
900 : : * executor, we fix it up for possible use by EXPLAIN (not to
901 : : * mention ease of debugging --- wrong varnos are very confusing).
902 : : */
6872 903 : 45915 : set_dummy_tlist_references(plan, rtoffset);
904 : :
905 : : /*
906 : : * Since these plan types don't check quals either, we should not
907 : : * find any qual expression attached to them.
908 : : */
7514 909 [ - + ]: 45915 : Assert(plan->qual == NIL);
9614 910 : 45915 : break;
5910 911 : 6764 : case T_LockRows:
912 : : {
913 : 6764 : LockRows *splan = (LockRows *) plan;
914 : :
915 : : /*
916 : : * Like the plan types above, LockRows doesn't evaluate its
917 : : * tlist or quals. But we have to fix up the RT indexes in
918 : : * its rowmarks.
919 : : */
920 : 6764 : set_dummy_tlist_references(plan, rtoffset);
921 [ - + ]: 6764 : Assert(splan->plan.qual == NIL);
922 : :
923 [ + - + + : 14756 : foreach(l, splan->rowMarks)
+ + ]
924 : : {
5896 925 : 7992 : PlanRowMark *rc = (PlanRowMark *) lfirst(l);
926 : :
5910 927 : 7992 : rc->rti += rtoffset;
928 : 7992 : rc->prti += rtoffset;
929 : : }
930 : : }
931 : 6764 : break;
7890 932 : 2442 : case T_Limit:
933 : : {
6607 bruce@momjian.us 934 : 2442 : Limit *splan = (Limit *) plan;
935 : :
936 : : /*
937 : : * Like the plan types above, Limit doesn't evaluate its tlist
938 : : * or quals. It does have live expressions for limit/offset,
939 : : * however; and those cannot contain subplan variable refs, so
940 : : * fix_scan_expr works for them.
941 : : */
6872 tgl@sss.pgh.pa.us 942 : 2442 : set_dummy_tlist_references(plan, rtoffset);
6873 943 [ - + ]: 2442 : Assert(splan->plan.qual == NIL);
944 : :
945 : 2442 : splan->limitOffset =
1907 946 : 2442 : fix_scan_expr(root, splan->limitOffset, rtoffset, 1);
6873 947 : 2442 : splan->limitCount =
1907 948 : 2442 : fix_scan_expr(root, splan->limitCount, rtoffset, 1);
949 : : }
7890 950 : 2442 : break;
9614 951 : 23518 : case T_Agg:
952 : : {
3461 953 : 23518 : Agg *agg = (Agg *) plan;
954 : :
955 : : /*
956 : : * If this node is combining partial-aggregation results, we
957 : : * must convert its Aggrefs to contain references to the
958 : : * partial-aggregate subexpressions that will be available
959 : : * from the child plan node.
960 : : */
961 [ + + ]: 23518 : if (DO_AGGSPLIT_COMBINE(agg->aggsplit))
962 : : {
963 : 703 : plan->targetlist = (List *)
964 : 703 : convert_combining_aggrefs((Node *) plan->targetlist,
965 : : NULL);
966 : 703 : plan->qual = (List *)
967 : 703 : convert_combining_aggrefs((Node *) plan->qual,
968 : : NULL);
969 : : }
970 : :
971 : 23518 : set_upper_references(root, plan, rtoffset);
972 : : }
973 : 23518 : break;
9614 974 : 123 : case T_Group:
5219 975 : 123 : set_upper_references(root, plan, rtoffset);
9614 976 : 123 : break;
5787 977 : 1381 : case T_WindowAgg:
978 : : {
5773 bruce@momjian.us 979 : 1381 : WindowAgg *wplan = (WindowAgg *) plan;
980 : :
981 : : /*
982 : : * Adjust the WindowAgg's run conditions by swapping the
983 : : * WindowFuncs references out to instead reference the Var in
984 : : * the scan slot so that when the executor evaluates the
985 : : * runCondition, it receives the WindowFunc's value from the
986 : : * slot that the result has just been stored into rather than
987 : : * evaluating the WindowFunc all over again.
988 : : */
1349 drowley@postgresql.o 989 : 1381 : wplan->runCondition = set_windowagg_runcondition_references(root,
990 : : wplan->runCondition,
991 : : (Plan *) wplan);
992 : :
5219 tgl@sss.pgh.pa.us 993 : 1381 : set_upper_references(root, plan, rtoffset);
994 : :
995 : : /*
996 : : * Like Limit node limit/offset expressions, WindowAgg has
997 : : * frame offset expressions, which cannot contain subplan
998 : : * variable refs, so fix_scan_expr works for them.
999 : : */
5787 1000 : 1381 : wplan->startOffset =
1907 1001 : 1381 : fix_scan_expr(root, wplan->startOffset, rtoffset, 1);
5787 1002 : 1381 : wplan->endOffset =
1907 1003 : 1381 : fix_scan_expr(root, wplan->endOffset, rtoffset, 1);
1349 drowley@postgresql.o 1004 : 1381 : wplan->runCondition = fix_scan_list(root,
1005 : : wplan->runCondition,
1006 : : rtoffset,
1007 : : NUM_EXEC_TLIST(plan));
1008 : 1381 : wplan->runConditionOrig = fix_scan_list(root,
1009 : : wplan->runConditionOrig,
1010 : : rtoffset,
1011 : : NUM_EXEC_TLIST(plan));
1012 : : }
5787 tgl@sss.pgh.pa.us 1013 : 1381 : break;
9614 1014 : 104793 : case T_Result:
1015 : : {
6607 bruce@momjian.us 1016 : 104793 : Result *splan = (Result *) plan;
1017 : :
1018 : : /*
1019 : : * Result may or may not have a subplan; if not, it's more
1020 : : * like a scan node than an upper node.
1021 : : */
6873 tgl@sss.pgh.pa.us 1022 [ + + ]: 104793 : if (splan->plan.lefttree != NULL)
5219 1023 : 5984 : set_upper_references(root, plan, rtoffset);
1024 : : else
1025 : : {
1026 : : /*
1027 : : * The tlist of a childless Result could contain
1028 : : * unresolved ROWID_VAR Vars, in case it's representing a
1029 : : * target relation which is completely empty because of
1030 : : * constraint exclusion. Replace any such Vars by null
1031 : : * constants, as though they'd been resolved for a leaf
1032 : : * scan node that doesn't support them. We could have
1033 : : * fix_scan_expr do this, but since the case is only
1034 : : * expected to occur here, it seems safer to special-case
1035 : : * it here and keep the assertions that ROWID_VARs
1036 : : * shouldn't be seen by fix_scan_expr.
1037 : : *
1038 : : * We also must handle the case where set operations have
1039 : : * been short-circuited resulting in a dummy Result node.
1040 : : * prepunion.c uses varno==0 for the set op targetlist.
1041 : : * See generate_setop_tlist() and generate_setop_tlist().
1042 : : * Here we rewrite these to use varno==1, which is the
1043 : : * varno of the first set-op child. Without this, EXPLAIN
1044 : : * will have trouble displaying targetlists of dummy set
1045 : : * operations.
1046 : : */
1722 1047 [ + + + + : 228942 : foreach(l, splan->plan.targetlist)
+ + ]
1048 : : {
1049 : 130133 : TargetEntry *tle = (TargetEntry *) lfirst(l);
1050 : 130133 : Var *var = (Var *) tle->expr;
1051 : :
71 drowley@postgresql.o 1052 [ + - + + ]:GNC 130133 : if (var && IsA(var, Var))
1053 : : {
1054 [ + + ]: 835 : if (var->varno == ROWID_VAR)
1055 : 36 : tle->expr = (Expr *) makeNullConst(var->vartype,
1056 : : var->vartypmod,
1057 : : var->varcollid);
1058 [ + + ]: 799 : else if (var->varno == 0)
1059 : 15 : tle->expr = (Expr *) makeVar(1,
1060 : 15 : var->varattno,
1061 : : var->vartype,
1062 : : var->vartypmod,
1063 : : var->varcollid,
1064 : : var->varlevelsup);
1065 : : }
1066 : : }
1067 : :
6873 tgl@sss.pgh.pa.us 1068 :CBC 98809 : splan->plan.targetlist =
1907 1069 : 98809 : fix_scan_list(root, splan->plan.targetlist,
1070 : : rtoffset, NUM_EXEC_TLIST(plan));
6873 1071 : 98809 : splan->plan.qual =
1907 1072 : 98809 : fix_scan_list(root, splan->plan.qual,
1073 : : rtoffset, NUM_EXEC_QUAL(plan));
1074 : : }
1075 : : /* resconstantqual can't contain any subplan variable refs */
6873 1076 : 104793 : splan->resconstantqual =
1907 1077 : 104793 : fix_scan_expr(root, splan->resconstantqual, rtoffset, 1);
1078 : : /* adjust the relids set */
85 rhaas@postgresql.org 1079 :GNC 104793 : splan->relids = offset_relid_set(splan->relids, rtoffset);
1080 : : }
9614 tgl@sss.pgh.pa.us 1081 :CBC 104793 : break;
3255 andres@anarazel.de 1082 : 6018 : case T_ProjectSet:
1083 : 6018 : set_upper_references(root, plan, rtoffset);
1084 : 6018 : break;
5912 tgl@sss.pgh.pa.us 1085 : 43865 : case T_ModifyTable:
1086 : : {
1087 : 43865 : ModifyTable *splan = (ModifyTable *) plan;
1360 alvherre@alvh.no-ip. 1088 : 43865 : Plan *subplan = outerPlan(splan);
1089 : :
4984 tgl@sss.pgh.pa.us 1090 [ - + ]: 43865 : Assert(splan->plan.targetlist == NIL);
5912 1091 [ - + ]: 43865 : Assert(splan->plan.qual == NIL);
1092 : :
4104 sfrost@snowman.net 1093 : 43865 : splan->withCheckOptionLists =
1907 tgl@sss.pgh.pa.us 1094 : 43865 : fix_scan_list(root, splan->withCheckOptionLists,
1095 : : rtoffset, 1);
1096 : :
4984 1097 [ + + ]: 43865 : if (splan->returningLists)
1098 : : {
1099 : 1489 : List *newRL = NIL;
1100 : : ListCell *lcrl,
1101 : : *lcrr;
1102 : :
1103 : : /*
1104 : : * Pass each per-resultrel returningList through
1105 : : * set_returning_clause_references().
1106 : : */
1107 [ - + ]: 1489 : Assert(list_length(splan->returningLists) == list_length(splan->resultRelations));
1722 1108 [ + - + + : 3174 : forboth(lcrl, splan->returningLists,
+ - + + +
+ + - +
+ ]
1109 : : lcrr, splan->resultRelations)
1110 : : {
4938 bruce@momjian.us 1111 : 1685 : List *rlist = (List *) lfirst(lcrl);
1112 : 1685 : Index resultrel = lfirst_int(lcrr);
1113 : :
4984 tgl@sss.pgh.pa.us 1114 : 1685 : rlist = set_returning_clause_references(root,
1115 : : rlist,
1116 : : subplan,
1117 : : resultrel,
1118 : : rtoffset);
1119 : 1685 : newRL = lappend(newRL, rlist);
1120 : : }
1121 : 1489 : splan->returningLists = newRL;
1122 : :
1123 : : /*
1124 : : * Set up the visible plan targetlist as being the same as
1125 : : * the first RETURNING list. This is mostly for the use
1126 : : * of EXPLAIN; the executor won't execute that targetlist,
1127 : : * although it does use it to prepare the node's result
1128 : : * tuple slot. We postpone this step until here so that
1129 : : * we don't have to do set_returning_clause_references()
1130 : : * twice on identical targetlists.
1131 : : */
1132 : 1489 : splan->plan.targetlist = copyObject(linitial(newRL));
1133 : : }
1134 : :
1135 : : /*
1136 : : * We treat ModifyTable with ON CONFLICT as a form of 'pseudo
1137 : : * join', where the inner side is the EXCLUDED tuple.
1138 : : * Therefore use fix_join_expr to setup the relevant variables
1139 : : * to INNER_VAR. We explicitly don't create any OUTER_VARs as
1140 : : * those are already used by RETURNING and it seems better to
1141 : : * be non-conflicting.
1142 : : */
3876 andres@anarazel.de 1143 [ + + ]: 43865 : if (splan->onConflictSet)
1144 : : {
1145 : : indexed_tlist *itlist;
1146 : :
1147 : 497 : itlist = build_tlist_index(splan->exclRelTlist);
1148 : :
1149 : 497 : splan->onConflictSet =
1150 : 994 : fix_join_expr(root, splan->onConflictSet,
1151 : : NULL, itlist,
1152 : 497 : linitial_int(splan->resultRelations),
1052 tgl@sss.pgh.pa.us 1153 : 497 : rtoffset, NRM_EQUAL, NUM_EXEC_QUAL(plan));
1154 : :
3876 andres@anarazel.de 1155 : 497 : splan->onConflictWhere = (Node *)
1156 : 994 : fix_join_expr(root, (List *) splan->onConflictWhere,
1157 : : NULL, itlist,
1158 : 497 : linitial_int(splan->resultRelations),
1052 tgl@sss.pgh.pa.us 1159 : 497 : rtoffset, NRM_EQUAL, NUM_EXEC_QUAL(plan));
1160 : :
3811 andres@anarazel.de 1161 : 497 : pfree(itlist);
1162 : :
3871 1163 : 497 : splan->exclRelTlist =
1907 tgl@sss.pgh.pa.us 1164 : 497 : fix_scan_list(root, splan->exclRelTlist, rtoffset, 1);
1165 : : }
1166 : :
1167 : : /*
1168 : : * The MERGE statement produces the target rows by performing
1169 : : * a right join between the target relation and the source
1170 : : * relation (which could be a plain relation or a subquery).
1171 : : * The INSERT and UPDATE actions of the MERGE statement
1172 : : * require access to the columns from the source relation. We
1173 : : * arrange things so that the source relation attributes are
1174 : : * available as INNER_VAR and the target relation attributes
1175 : : * are available from the scan tuple.
1176 : : */
1360 alvherre@alvh.no-ip. 1177 [ + + ]: 43865 : if (splan->mergeActionLists != NIL)
1178 : : {
627 dean.a.rasheed@gmail 1179 : 920 : List *newMJC = NIL;
1180 : : ListCell *lca,
1181 : : *lcj,
1182 : : *lcr;
1183 : :
1184 : : /*
1185 : : * Fix the targetList of individual action nodes so that
1186 : : * the so-called "source relation" Vars are referenced as
1187 : : * INNER_VAR. Note that for this to work correctly during
1188 : : * execution, the ecxt_innertuple must be set to the tuple
1189 : : * obtained by executing the subplan, which is what
1190 : : * constitutes the "source relation".
1191 : : *
1192 : : * We leave the Vars from the result relation (i.e. the
1193 : : * target relation) unchanged i.e. those Vars would be
1194 : : * picked from the scan slot. So during execution, we must
1195 : : * ensure that ecxt_scantuple is setup correctly to refer
1196 : : * to the tuple from the target relation.
1197 : : */
1198 : : indexed_tlist *itlist;
1199 : :
1360 alvherre@alvh.no-ip. 1200 : 920 : itlist = build_tlist_index(subplan->targetlist);
1201 : :
627 dean.a.rasheed@gmail 1202 [ + - + + : 1985 : forthree(lca, splan->mergeActionLists,
+ - + + +
- + + + +
+ - + - +
+ ]
1203 : : lcj, splan->mergeJoinConditions,
1204 : : lcr, splan->resultRelations)
1205 : : {
1360 alvherre@alvh.no-ip. 1206 : 1065 : List *mergeActionList = lfirst(lca);
627 dean.a.rasheed@gmail 1207 : 1065 : Node *mergeJoinCondition = lfirst(lcj);
1360 alvherre@alvh.no-ip. 1208 : 1065 : Index resultrel = lfirst_int(lcr);
1209 : :
1210 [ + - + + : 2847 : foreach(l, mergeActionList)
+ + ]
1211 : : {
1212 : 1782 : MergeAction *action = (MergeAction *) lfirst(l);
1213 : :
1214 : : /* Fix targetList of each action. */
1215 : 1782 : action->targetList = fix_join_expr(root,
1216 : : action->targetList,
1217 : : NULL, itlist,
1218 : : resultrel,
1219 : : rtoffset,
1220 : : NRM_EQUAL,
1221 : : NUM_EXEC_TLIST(plan));
1222 : :
1223 : : /* Fix quals too. */
1224 : 1782 : action->qual = (Node *) fix_join_expr(root,
1225 : 1782 : (List *) action->qual,
1226 : : NULL, itlist,
1227 : : resultrel,
1228 : : rtoffset,
1229 : : NRM_EQUAL,
1230 : 1782 : NUM_EXEC_QUAL(plan));
1231 : : }
1232 : :
1233 : : /* Fix join condition too. */
1234 : : mergeJoinCondition = (Node *)
627 dean.a.rasheed@gmail 1235 : 1065 : fix_join_expr(root,
1236 : : (List *) mergeJoinCondition,
1237 : : NULL, itlist,
1238 : : resultrel,
1239 : : rtoffset,
1240 : : NRM_EQUAL,
1241 : 1065 : NUM_EXEC_QUAL(plan));
1242 : 1065 : newMJC = lappend(newMJC, mergeJoinCondition);
1243 : : }
1244 : 920 : splan->mergeJoinConditions = newMJC;
1245 : : }
1246 : :
3956 tgl@sss.pgh.pa.us 1247 : 43865 : splan->nominalRelation += rtoffset;
2628 1248 [ + + ]: 43865 : if (splan->rootRelation)
1249 : 1451 : splan->rootRelation += rtoffset;
3876 andres@anarazel.de 1250 : 43865 : splan->exclRelRTI += rtoffset;
1251 : :
5912 tgl@sss.pgh.pa.us 1252 [ + - + + : 88978 : foreach(l, splan->resultRelations)
+ + ]
1253 : : {
1254 : 45113 : lfirst_int(l) += rtoffset;
1255 : : }
5896 1256 [ + + + + : 45336 : foreach(l, splan->rowMarks)
+ + ]
1257 : : {
1258 : 1471 : PlanRowMark *rc = (PlanRowMark *) lfirst(l);
1259 : :
1260 : 1471 : rc->rti += rtoffset;
1261 : 1471 : rc->prti += rtoffset;
1262 : : }
1263 : :
1264 : : /*
1265 : : * Append this ModifyTable node's final result relation RT
1266 : : * index(es) to the global list for the plan.
1267 : : */
5219 1268 : 87730 : root->glob->resultRelations =
1269 : 43865 : list_concat(root->glob->resultRelations,
2319 1270 : 43865 : splan->resultRelations);
2628 1271 [ + + ]: 43865 : if (splan->rootRelation)
1272 : : {
1891 heikki.linnakangas@i 1273 : 1451 : root->glob->resultRelations =
1274 : 1451 : lappend_int(root->glob->resultRelations,
2628 tgl@sss.pgh.pa.us 1275 : 1451 : splan->rootRelation);
1276 : : }
1277 : : }
5912 1278 : 43865 : break;
9614 1279 : 12453 : case T_Append:
1280 : : /* Needs special treatment, see comments below */
2459 1281 : 12453 : return set_append_references(root,
1282 : : (Append *) plan,
1283 : : rtoffset);
5543 1284 : 289 : case T_MergeAppend:
1285 : : /* Needs special treatment, see comments below */
2459 1286 : 289 : return set_mergeappend_references(root,
1287 : : (MergeAppend *) plan,
1288 : : rtoffset);
6283 1289 : 471 : case T_RecursiveUnion:
1290 : : /* This doesn't evaluate targetlist or check quals either */
1291 : 471 : set_dummy_tlist_references(plan, rtoffset);
1292 [ - + ]: 471 : Assert(plan->qual == NIL);
1293 : 471 : break;
7547 1294 : 125 : case T_BitmapAnd:
1295 : : {
6607 bruce@momjian.us 1296 : 125 : BitmapAnd *splan = (BitmapAnd *) plan;
1297 : :
1298 : : /* BitmapAnd works like Append, but has no tlist */
6873 tgl@sss.pgh.pa.us 1299 [ - + ]: 125 : Assert(splan->plan.targetlist == NIL);
1300 [ - + ]: 125 : Assert(splan->plan.qual == NIL);
1301 [ + - + + : 375 : foreach(l, splan->bitmapplans)
+ + ]
1302 : : {
5219 1303 : 250 : lfirst(l) = set_plan_refs(root,
6873 1304 : 250 : (Plan *) lfirst(l),
1305 : : rtoffset);
1306 : : }
1307 : : }
7547 1308 : 125 : break;
1309 : 215 : case T_BitmapOr:
1310 : : {
6607 bruce@momjian.us 1311 : 215 : BitmapOr *splan = (BitmapOr *) plan;
1312 : :
1313 : : /* BitmapOr works like Append, but has no tlist */
6873 tgl@sss.pgh.pa.us 1314 [ - + ]: 215 : Assert(splan->plan.targetlist == NIL);
1315 [ - + ]: 215 : Assert(splan->plan.qual == NIL);
1316 [ + - + + : 648 : foreach(l, splan->bitmapplans)
+ + ]
1317 : : {
5219 1318 : 433 : lfirst(l) = set_plan_refs(root,
6873 1319 : 433 : (Plan *) lfirst(l),
1320 : : rtoffset);
1321 : : }
1322 : : }
7547 1323 : 215 : break;
9614 tgl@sss.pgh.pa.us 1324 :UBC 0 : default:
8181 1325 [ # # ]: 0 : elog(ERROR, "unrecognized node type: %d",
1326 : : (int) nodeTag(plan));
1327 : : break;
1328 : : }
1329 : :
1330 : : /*
1331 : : * Now recurse into child plans, if any
1332 : : *
1333 : : * NOTE: it is essential that we recurse into child plans AFTER we set
1334 : : * subplan references in this plan's tlist and quals. If we did the
1335 : : * reference-adjustments bottom-up, then we would fail to match this
1336 : : * plan's var nodes against the already-modified nodes of the children.
1337 : : */
5219 tgl@sss.pgh.pa.us 1338 :CBC 572915 : plan->lefttree = set_plan_refs(root, plan->lefttree, rtoffset);
1339 : 572915 : plan->righttree = set_plan_refs(root, plan->righttree, rtoffset);
1340 : :
7514 1341 : 572915 : return plan;
1342 : : }
1343 : :
1344 : : /*
1345 : : * set_indexonlyscan_references
1346 : : * Do set_plan_references processing on an IndexOnlyScan
1347 : : *
1348 : : * This is unlike the handling of a plain IndexScan because we have to
1349 : : * convert Vars referencing the heap into Vars referencing the index.
1350 : : * We can use the fix_upper_expr machinery for that, by working from a
1351 : : * targetlist describing the index columns.
1352 : : */
1353 : : static Plan *
5181 1354 : 8502 : set_indexonlyscan_references(PlannerInfo *root,
1355 : : IndexOnlyScan *plan,
1356 : : int rtoffset)
1357 : : {
1358 : : indexed_tlist *index_itlist;
1359 : : List *stripped_indextlist;
1360 : : ListCell *lc;
1361 : :
1362 : : /*
1363 : : * Vars in the plan node's targetlist, qual, and recheckqual must only
1364 : : * reference columns that the index AM can actually return. To ensure
1365 : : * this, remove non-returnable columns (which are marked as resjunk) from
1366 : : * the indexed tlist. We can just drop them because the indexed_tlist
1367 : : * machinery pays attention to TLE resnos, not physical list position.
1368 : : */
1444 1369 : 8502 : stripped_indextlist = NIL;
1370 [ + - + + : 19390 : foreach(lc, plan->indextlist)
+ + ]
1371 : : {
1372 : 10888 : TargetEntry *indextle = (TargetEntry *) lfirst(lc);
1373 : :
1374 [ + + ]: 10888 : if (!indextle->resjunk)
1375 : 10862 : stripped_indextlist = lappend(stripped_indextlist, indextle);
1376 : : }
1377 : :
1378 : 8502 : index_itlist = build_tlist_index(stripped_indextlist);
1379 : :
5181 1380 : 8502 : plan->scan.scanrelid += rtoffset;
1381 : 8502 : plan->scan.plan.targetlist = (List *)
1382 : 8502 : fix_upper_expr(root,
1383 : 8502 : (Node *) plan->scan.plan.targetlist,
1384 : : index_itlist,
1385 : : INDEX_VAR,
1386 : : rtoffset,
1387 : : NRM_EQUAL,
1388 : : NUM_EXEC_TLIST((Plan *) plan));
1389 : 8502 : plan->scan.plan.qual = (List *)
1390 : 8502 : fix_upper_expr(root,
1391 : 8502 : (Node *) plan->scan.plan.qual,
1392 : : index_itlist,
1393 : : INDEX_VAR,
1394 : : rtoffset,
1395 : : NRM_EQUAL,
1907 1396 : 8502 : NUM_EXEC_QUAL((Plan *) plan));
1444 1397 : 8502 : plan->recheckqual = (List *)
1398 : 8502 : fix_upper_expr(root,
1399 : 8502 : (Node *) plan->recheckqual,
1400 : : index_itlist,
1401 : : INDEX_VAR,
1402 : : rtoffset,
1403 : : NRM_EQUAL,
1404 : 8502 : NUM_EXEC_QUAL((Plan *) plan));
1405 : : /* indexqual is already transformed to reference index columns */
1907 1406 : 8502 : plan->indexqual = fix_scan_list(root, plan->indexqual,
1407 : : rtoffset, 1);
1408 : : /* indexorderby is already transformed to reference index columns */
1409 : 8502 : plan->indexorderby = fix_scan_list(root, plan->indexorderby,
1410 : : rtoffset, 1);
1411 : : /* indextlist must NOT be transformed to reference index columns */
1412 : 8502 : plan->indextlist = fix_scan_list(root, plan->indextlist,
1413 : : rtoffset, NUM_EXEC_TLIST((Plan *) plan));
1414 : :
5181 1415 : 8502 : pfree(index_itlist);
1416 : :
1417 : 8502 : return (Plan *) plan;
1418 : : }
1419 : :
1420 : : /*
1421 : : * set_subqueryscan_references
1422 : : * Do set_plan_references processing on a SubqueryScan
1423 : : *
1424 : : * We try to strip out the SubqueryScan entirely; if we can't, we have
1425 : : * to do the normal processing on it.
1426 : : */
1427 : : static Plan *
5219 1428 : 19784 : set_subqueryscan_references(PlannerInfo *root,
1429 : : SubqueryScan *plan,
1430 : : int rtoffset)
1431 : : {
1432 : : RelOptInfo *rel;
1433 : : Plan *result;
1434 : :
1435 : : /* Need to look up the subquery's RelOptInfo, since we need its subroot */
1436 : 19784 : rel = find_base_rel(root, plan->scan.scanrelid);
1437 : :
1438 : : /* Recursively process the subplan */
1439 : 19784 : plan->subplan = set_plan_references(rel->subroot, plan->subplan);
1440 : :
7514 1441 [ + + ]: 19784 : if (trivial_subqueryscan(plan))
1442 : : {
1443 : : /*
1444 : : * We can omit the SubqueryScan node and just pull up the subplan.
1445 : : */
2459 1446 : 9008 : result = clean_up_removed_plan_level((Plan *) plan, plan->subplan);
1447 : : }
1448 : : else
1449 : : {
1450 : : /*
1451 : : * Keep the SubqueryScan node. We have to do the processing that
1452 : : * set_plan_references would otherwise have done on it. Notice we do
1453 : : * not do set_upper_references() here, because a SubqueryScan will
1454 : : * always have been created with correct references to its subplan's
1455 : : * outputs to begin with.
1456 : : */
6873 1457 : 10776 : plan->scan.scanrelid += rtoffset;
1458 : 10776 : plan->scan.plan.targetlist =
1907 1459 : 10776 : fix_scan_list(root, plan->scan.plan.targetlist,
1460 : : rtoffset, NUM_EXEC_TLIST((Plan *) plan));
6873 1461 : 10776 : plan->scan.plan.qual =
1907 1462 : 10776 : fix_scan_list(root, plan->scan.plan.qual,
1463 : : rtoffset, NUM_EXEC_QUAL((Plan *) plan));
1464 : :
6873 1465 : 10776 : result = (Plan *) plan;
1466 : : }
1467 : :
7514 1468 : 19784 : return result;
1469 : : }
1470 : :
1471 : : /*
1472 : : * trivial_subqueryscan
1473 : : * Detect whether a SubqueryScan can be deleted from the plan tree.
1474 : : *
1475 : : * We can delete it if it has no qual to check and the targetlist just
1476 : : * regurgitates the output of the child plan.
1477 : : *
1478 : : * This can be called from mark_async_capable_plan(), a helper function for
1479 : : * create_append_plan(), before set_subqueryscan_references(), to determine
1480 : : * triviality of a SubqueryScan that is a child of an Append node. So we
1481 : : * cache the result in the SubqueryScan node to avoid repeated computation.
1482 : : *
1483 : : * Note: when called from mark_async_capable_plan(), we determine the result
1484 : : * before running finalize_plan() on the SubqueryScan node (if needed) and
1485 : : * set_plan_references() on the subplan tree, but this would be safe, because
1486 : : * 1) finalize_plan() doesn't modify the tlist or quals for the SubqueryScan
1487 : : * node (or that for any plan node in the subplan tree), and
1488 : : * 2) set_plan_references() modifies the tlist for every plan node in the
1489 : : * subplan tree, but keeps const/resjunk columns as const/resjunk ones and
1490 : : * preserves the length and order of the tlist, and
1491 : : * 3) set_plan_references() might delete the topmost plan node like an Append
1492 : : * or MergeAppend from the subplan tree and pull up the child plan node,
1493 : : * but in that case, the tlist for the child plan node exactly matches the
1494 : : * parent.
1495 : : */
1496 : : bool
1497 : 25473 : trivial_subqueryscan(SubqueryScan *plan)
1498 : : {
1499 : : int attrno;
1500 : : ListCell *lp,
1501 : : *lc;
1502 : :
1503 : : /* We might have detected this already; in which case reuse the result */
1351 efujita@postgresql.o 1504 [ + + ]: 25473 : if (plan->scanstatus == SUBQUERY_SCAN_TRIVIAL)
1505 : 2314 : return true;
1506 [ + + ]: 23159 : if (plan->scanstatus == SUBQUERY_SCAN_NONTRIVIAL)
1507 : 3375 : return false;
1508 [ - + ]: 19784 : Assert(plan->scanstatus == SUBQUERY_SCAN_UNKNOWN);
1509 : : /* Initially, mark the SubqueryScan as non-deletable from the plan tree */
1510 : 19784 : plan->scanstatus = SUBQUERY_SCAN_NONTRIVIAL;
1511 : :
7514 tgl@sss.pgh.pa.us 1512 [ + + ]: 19784 : if (plan->scan.plan.qual != NIL)
1513 : 344 : return false;
1514 : :
7408 1515 [ + + ]: 38880 : if (list_length(plan->scan.plan.targetlist) !=
1516 : 19440 : list_length(plan->subplan->targetlist))
1517 : 6283 : return false; /* tlists not same length */
1518 : :
7514 1519 : 13157 : attrno = 1;
1520 [ + + + + : 40290 : forboth(lp, plan->scan.plan.targetlist, lc, plan->subplan->targetlist)
+ + + + +
+ + - +
+ ]
1521 : : {
1522 : 31282 : TargetEntry *ptle = (TargetEntry *) lfirst(lp);
1523 : 31282 : TargetEntry *ctle = (TargetEntry *) lfirst(lc);
1524 : :
1525 [ + + ]: 31282 : if (ptle->resjunk != ctle->resjunk)
1526 : 4149 : return false; /* tlist doesn't match junk status */
1527 : :
1528 : : /*
1529 : : * We accept either a Var referencing the corresponding element of the
1530 : : * subplan tlist, or a Const equaling the subplan element. See
1531 : : * generate_setop_tlist() for motivation.
1532 : : */
7051 1533 [ + - + + ]: 31270 : if (ptle->expr && IsA(ptle->expr, Var))
1534 : 25916 : {
7014 bruce@momjian.us 1535 : 26012 : Var *var = (Var *) ptle->expr;
1536 : :
7051 tgl@sss.pgh.pa.us 1537 [ - + ]: 26012 : Assert(var->varno == plan->scan.scanrelid);
1538 [ - + ]: 26012 : Assert(var->varlevelsup == 0);
1539 [ + + ]: 26012 : if (var->varattno != attrno)
1540 : 96 : return false; /* out of order */
1541 : : }
1542 [ + - + + ]: 5258 : else if (ptle->expr && IsA(ptle->expr, Const))
1543 : : {
1544 [ + + ]: 4505 : if (!equal(ptle->expr, ctle->expr))
1545 : 3288 : return false;
1546 : : }
1547 : : else
1548 : 753 : return false;
1549 : :
7514 1550 : 27133 : attrno++;
1551 : : }
1552 : :
1553 : : /* Re-mark the SubqueryScan as deletable from the plan tree */
1351 efujita@postgresql.o 1554 : 9008 : plan->scanstatus = SUBQUERY_SCAN_TRIVIAL;
1555 : :
7514 tgl@sss.pgh.pa.us 1556 : 9008 : return true;
1557 : : }
1558 : :
1559 : : /*
1560 : : * clean_up_removed_plan_level
1561 : : * Do necessary cleanup when we strip out a SubqueryScan, Append, etc
1562 : : *
1563 : : * We are dropping the "parent" plan in favor of returning just its "child".
1564 : : * A few small tweaks are needed.
1565 : : */
1566 : : static Plan *
2459 1567 : 12368 : clean_up_removed_plan_level(Plan *parent, Plan *child)
1568 : : {
1569 : : /*
1570 : : * We have to be sure we don't lose any initplans, so move any that were
1571 : : * attached to the parent plan to the child. If any are parallel-unsafe,
1572 : : * the child is no longer parallel-safe. As a cosmetic matter, also add
1573 : : * the initplans' run costs to the child's costs.
1574 : : */
980 1575 [ + + ]: 12368 : if (parent->initPlan)
1576 : : {
1577 : : Cost initplan_cost;
1578 : : bool unsafe_initplans;
1579 : :
888 1580 : 21 : SS_compute_initplan_cost(parent->initPlan,
1581 : : &initplan_cost, &unsafe_initplans);
1582 : 21 : child->startup_cost += initplan_cost;
1583 : 21 : child->total_cost += initplan_cost;
1584 [ + + ]: 21 : if (unsafe_initplans)
1585 : 9 : child->parallel_safe = false;
1586 : :
1587 : : /*
1588 : : * Attach plans this way so that parent's initplans are processed
1589 : : * before any pre-existing initplans of the child. Probably doesn't
1590 : : * matter, but let's preserve the ordering just in case.
1591 : : */
1592 : 21 : child->initPlan = list_concat(parent->initPlan,
1593 : 21 : child->initPlan);
1594 : : }
1595 : :
1596 : : /*
1597 : : * We also have to transfer the parent's column labeling info into the
1598 : : * child, else columns sent to client will be improperly labeled if this
1599 : : * is the topmost plan level. resjunk and so on may be important too.
1600 : : */
2459 1601 : 12368 : apply_tlist_labeling(child->targetlist, parent->targetlist);
1602 : :
1603 : 12368 : return child;
1604 : : }
1605 : :
1606 : : /*
1607 : : * set_foreignscan_references
1608 : : * Do set_plan_references processing on a ForeignScan
1609 : : */
1610 : : static void
3874 1611 : 1027 : set_foreignscan_references(PlannerInfo *root,
1612 : : ForeignScan *fscan,
1613 : : int rtoffset)
1614 : : {
1615 : : /* Adjust scanrelid if it's valid */
1616 [ + + ]: 1027 : if (fscan->scan.scanrelid > 0)
1617 : 741 : fscan->scan.scanrelid += rtoffset;
1618 : :
1619 [ + + + + ]: 1027 : if (fscan->fdw_scan_tlist != NIL || fscan->scan.scanrelid == 0)
1620 : 286 : {
1621 : : /*
1622 : : * Adjust tlist, qual, fdw_exprs, fdw_recheck_quals to reference
1623 : : * foreign scan tuple
1624 : : */
1625 : 286 : indexed_tlist *itlist = build_tlist_index(fscan->fdw_scan_tlist);
1626 : :
1627 : 286 : fscan->scan.plan.targetlist = (List *)
1628 : 286 : fix_upper_expr(root,
1629 : 286 : (Node *) fscan->scan.plan.targetlist,
1630 : : itlist,
1631 : : INDEX_VAR,
1632 : : rtoffset,
1633 : : NRM_EQUAL,
1634 : : NUM_EXEC_TLIST((Plan *) fscan));
1635 : 286 : fscan->scan.plan.qual = (List *)
1636 : 286 : fix_upper_expr(root,
1637 : 286 : (Node *) fscan->scan.plan.qual,
1638 : : itlist,
1639 : : INDEX_VAR,
1640 : : rtoffset,
1641 : : NRM_EQUAL,
1907 1642 : 286 : NUM_EXEC_QUAL((Plan *) fscan));
3874 1643 : 286 : fscan->fdw_exprs = (List *)
1644 : 286 : fix_upper_expr(root,
1645 : 286 : (Node *) fscan->fdw_exprs,
1646 : : itlist,
1647 : : INDEX_VAR,
1648 : : rtoffset,
1649 : : NRM_EQUAL,
1907 1650 : 286 : NUM_EXEC_QUAL((Plan *) fscan));
3682 rhaas@postgresql.org 1651 : 286 : fscan->fdw_recheck_quals = (List *)
1652 : 286 : fix_upper_expr(root,
1653 : 286 : (Node *) fscan->fdw_recheck_quals,
1654 : : itlist,
1655 : : INDEX_VAR,
1656 : : rtoffset,
1657 : : NRM_EQUAL,
1907 tgl@sss.pgh.pa.us 1658 : 286 : NUM_EXEC_QUAL((Plan *) fscan));
3874 1659 : 286 : pfree(itlist);
1660 : : /* fdw_scan_tlist itself just needs fix_scan_list() adjustments */
1661 : 286 : fscan->fdw_scan_tlist =
1907 1662 : 286 : fix_scan_list(root, fscan->fdw_scan_tlist,
1663 : : rtoffset, NUM_EXEC_TLIST((Plan *) fscan));
1664 : : }
1665 : : else
1666 : : {
1667 : : /*
1668 : : * Adjust tlist, qual, fdw_exprs, fdw_recheck_quals in the standard
1669 : : * way
1670 : : */
3874 1671 : 741 : fscan->scan.plan.targetlist =
1907 1672 : 741 : fix_scan_list(root, fscan->scan.plan.targetlist,
1673 : : rtoffset, NUM_EXEC_TLIST((Plan *) fscan));
3874 1674 : 741 : fscan->scan.plan.qual =
1907 1675 : 741 : fix_scan_list(root, fscan->scan.plan.qual,
1676 : : rtoffset, NUM_EXEC_QUAL((Plan *) fscan));
3874 1677 : 741 : fscan->fdw_exprs =
1907 1678 : 741 : fix_scan_list(root, fscan->fdw_exprs,
1679 : : rtoffset, NUM_EXEC_QUAL((Plan *) fscan));
3716 rhaas@postgresql.org 1680 : 741 : fscan->fdw_recheck_quals =
1907 tgl@sss.pgh.pa.us 1681 : 741 : fix_scan_list(root, fscan->fdw_recheck_quals,
1682 : : rtoffset, NUM_EXEC_QUAL((Plan *) fscan));
1683 : : }
1684 : :
2198 1685 : 1027 : fscan->fs_relids = offset_relid_set(fscan->fs_relids, rtoffset);
1052 1686 : 1027 : fscan->fs_base_relids = offset_relid_set(fscan->fs_base_relids, rtoffset);
1687 : :
1688 : : /* Adjust resultRelation if it's valid */
1890 heikki.linnakangas@i 1689 [ + + ]: 1027 : if (fscan->resultRelation > 0)
1690 : 104 : fscan->resultRelation += rtoffset;
3874 tgl@sss.pgh.pa.us 1691 : 1027 : }
1692 : :
1693 : : /*
1694 : : * set_customscan_references
1695 : : * Do set_plan_references processing on a CustomScan
1696 : : */
1697 : : static void
3874 tgl@sss.pgh.pa.us 1698 :UBC 0 : set_customscan_references(PlannerInfo *root,
1699 : : CustomScan *cscan,
1700 : : int rtoffset)
1701 : : {
1702 : : ListCell *lc;
1703 : :
1704 : : /* Adjust scanrelid if it's valid */
1705 [ # # ]: 0 : if (cscan->scan.scanrelid > 0)
1706 : 0 : cscan->scan.scanrelid += rtoffset;
1707 : :
1708 [ # # # # ]: 0 : if (cscan->custom_scan_tlist != NIL || cscan->scan.scanrelid == 0)
1709 : 0 : {
1710 : : /* Adjust tlist, qual, custom_exprs to reference custom scan tuple */
1711 : 0 : indexed_tlist *itlist = build_tlist_index(cscan->custom_scan_tlist);
1712 : :
1713 : 0 : cscan->scan.plan.targetlist = (List *)
1714 : 0 : fix_upper_expr(root,
1715 : 0 : (Node *) cscan->scan.plan.targetlist,
1716 : : itlist,
1717 : : INDEX_VAR,
1718 : : rtoffset,
1719 : : NRM_EQUAL,
1720 : : NUM_EXEC_TLIST((Plan *) cscan));
1721 : 0 : cscan->scan.plan.qual = (List *)
1722 : 0 : fix_upper_expr(root,
1723 : 0 : (Node *) cscan->scan.plan.qual,
1724 : : itlist,
1725 : : INDEX_VAR,
1726 : : rtoffset,
1727 : : NRM_EQUAL,
1907 1728 : 0 : NUM_EXEC_QUAL((Plan *) cscan));
3874 1729 : 0 : cscan->custom_exprs = (List *)
1730 : 0 : fix_upper_expr(root,
1731 : 0 : (Node *) cscan->custom_exprs,
1732 : : itlist,
1733 : : INDEX_VAR,
1734 : : rtoffset,
1735 : : NRM_EQUAL,
1907 1736 : 0 : NUM_EXEC_QUAL((Plan *) cscan));
3874 1737 : 0 : pfree(itlist);
1738 : : /* custom_scan_tlist itself just needs fix_scan_list() adjustments */
1739 : 0 : cscan->custom_scan_tlist =
1907 1740 : 0 : fix_scan_list(root, cscan->custom_scan_tlist,
1741 : : rtoffset, NUM_EXEC_TLIST((Plan *) cscan));
1742 : : }
1743 : : else
1744 : : {
1745 : : /* Adjust tlist, qual, custom_exprs in the standard way */
3874 1746 : 0 : cscan->scan.plan.targetlist =
1907 1747 : 0 : fix_scan_list(root, cscan->scan.plan.targetlist,
1748 : : rtoffset, NUM_EXEC_TLIST((Plan *) cscan));
3874 1749 : 0 : cscan->scan.plan.qual =
1907 1750 : 0 : fix_scan_list(root, cscan->scan.plan.qual,
1751 : : rtoffset, NUM_EXEC_QUAL((Plan *) cscan));
3874 1752 : 0 : cscan->custom_exprs =
1907 1753 : 0 : fix_scan_list(root, cscan->custom_exprs,
1754 : : rtoffset, NUM_EXEC_QUAL((Plan *) cscan));
1755 : : }
1756 : :
1757 : : /* Adjust child plan-nodes recursively, if needed */
3802 1758 [ # # # # : 0 : foreach(lc, cscan->custom_plans)
# # ]
1759 : : {
3827 rhaas@postgresql.org 1760 : 0 : lfirst(lc) = set_plan_refs(root, (Plan *) lfirst(lc), rtoffset);
1761 : : }
1762 : :
2198 tgl@sss.pgh.pa.us 1763 : 0 : cscan->custom_relids = offset_relid_set(cscan->custom_relids, rtoffset);
3874 1764 : 0 : }
1765 : :
1766 : : /*
1767 : : * register_partpruneinfo
1768 : : * Subroutine for set_append_references and set_mergeappend_references
1769 : : *
1770 : : * Add the PartitionPruneInfo from root->partPruneInfos at the given index
1771 : : * into PlannerGlobal->partPruneInfos and return its index there.
1772 : : *
1773 : : * Also update the RT indexes present in PartitionedRelPruneInfos to add the
1774 : : * offset.
1775 : : *
1776 : : * Finally, if there are initial pruning steps, add the RT indexes of the
1777 : : * leaf partitions to the set of relations that are prunable at execution
1778 : : * startup time.
1779 : : */
1780 : : static int
321 amitlan@postgresql.o 1781 :CBC 285 : register_partpruneinfo(PlannerInfo *root, int part_prune_index, int rtoffset)
1782 : : {
1783 : 285 : PlannerGlobal *glob = root->glob;
1784 : : PartitionPruneInfo *pinfo;
1785 : : ListCell *l;
1786 : :
1787 [ + - - + ]: 285 : Assert(part_prune_index >= 0 &&
1788 : : part_prune_index < list_length(root->partPruneInfos));
1789 : 285 : pinfo = list_nth_node(PartitionPruneInfo, root->partPruneInfos,
1790 : : part_prune_index);
1791 : :
1792 : 285 : pinfo->relids = offset_relid_set(pinfo->relids, rtoffset);
1793 [ + - + + : 576 : foreach(l, pinfo->prune_infos)
+ + ]
1794 : : {
1795 : 291 : List *prune_infos = lfirst(l);
1796 : : ListCell *l2;
1797 : :
1798 [ + - + + : 795 : foreach(l2, prune_infos)
+ + ]
1799 : : {
1800 : 504 : PartitionedRelPruneInfo *prelinfo = lfirst(l2);
1801 : : int i;
1802 : :
1803 : 504 : prelinfo->rtindex += rtoffset;
1804 : 504 : prelinfo->initial_pruning_steps =
1805 : 504 : fix_scan_list(root, prelinfo->initial_pruning_steps,
1806 : : rtoffset, 1);
1807 : 504 : prelinfo->exec_pruning_steps =
1808 : 504 : fix_scan_list(root, prelinfo->exec_pruning_steps,
1809 : : rtoffset, 1);
1810 : :
313 1811 [ + + ]: 1993 : for (i = 0; i < prelinfo->nparts; i++)
1812 : : {
1813 : : /*
1814 : : * Non-leaf partitions and partitions that do not have a
1815 : : * subplan are not included in this map as mentioned in
1816 : : * make_partitionedrel_pruneinfo().
1817 : : */
1818 [ + + ]: 1489 : if (prelinfo->leafpart_rti_map[i])
1819 : : {
1820 : 1205 : prelinfo->leafpart_rti_map[i] += rtoffset;
1821 [ + + ]: 1205 : if (prelinfo->initial_pruning_steps)
1822 : 374 : glob->prunableRelids = bms_add_member(glob->prunableRelids,
1823 : 374 : prelinfo->leafpart_rti_map[i]);
1824 : : }
1825 : : }
1826 : : }
1827 : : }
1828 : :
321 1829 : 285 : glob->partPruneInfos = lappend(glob->partPruneInfos, pinfo);
1830 : :
1831 : 285 : return list_length(glob->partPruneInfos) - 1;
1832 : : }
1833 : :
1834 : : /*
1835 : : * set_append_references
1836 : : * Do set_plan_references processing on an Append
1837 : : *
1838 : : * We try to strip out the Append entirely; if we can't, we have
1839 : : * to do the normal processing on it.
1840 : : */
1841 : : static Plan *
2459 tgl@sss.pgh.pa.us 1842 : 12453 : set_append_references(PlannerInfo *root,
1843 : : Append *aplan,
1844 : : int rtoffset)
1845 : : {
1846 : : ListCell *l;
1847 : :
1848 : : /*
1849 : : * Append, like Sort et al, doesn't actually evaluate its targetlist or
1850 : : * check quals. If it's got exactly one child plan, then it's not doing
1851 : : * anything useful at all, and we can strip it out.
1852 : : */
1853 [ - + ]: 12453 : Assert(aplan->plan.qual == NIL);
1854 : :
1855 : : /* First, we gotta recurse on the children */
1856 [ + - + + : 43250 : foreach(l, aplan->appendplans)
+ + ]
1857 : : {
1858 : 30797 : lfirst(l) = set_plan_refs(root, (Plan *) lfirst(l), rtoffset);
1859 : : }
1860 : :
1861 : : /*
1862 : : * See if it's safe to get rid of the Append entirely. For this to be
1863 : : * safe, there must be only one child plan and that child plan's parallel
1864 : : * awareness must match the Append's. The reason for the latter is that
1865 : : * if the Append is parallel aware and the child is not, then the calling
1866 : : * plan may execute the non-parallel aware child multiple times. (If you
1867 : : * change these rules, update create_append_path to match.)
1868 : : */
1247 alvherre@alvh.no-ip. 1869 [ + + ]: 12453 : if (list_length(aplan->appendplans) == 1)
1870 : : {
1871 : 3358 : Plan *p = (Plan *) linitial(aplan->appendplans);
1872 : :
1873 [ + - ]: 3358 : if (p->parallel_aware == aplan->plan.parallel_aware)
1874 : 3358 : return clean_up_removed_plan_level((Plan *) aplan, p);
1875 : : }
1876 : :
1877 : : /*
1878 : : * Otherwise, clean up the Append as needed. It's okay to do this after
1879 : : * recursing to the children, because set_dummy_tlist_references doesn't
1880 : : * look at those.
1881 : : */
2459 tgl@sss.pgh.pa.us 1882 : 9095 : set_dummy_tlist_references((Plan *) aplan, rtoffset);
1883 : :
2198 1884 : 9095 : aplan->apprelids = offset_relid_set(aplan->apprelids, rtoffset);
1885 : :
1886 : : /*
1887 : : * Add PartitionPruneInfo, if any, to PlannerGlobal and update the index.
1888 : : * Also update the RT indexes present in it to add the offset.
1889 : : */
321 amitlan@postgresql.o 1890 [ + + ]: 9095 : if (aplan->part_prune_index >= 0)
1891 : 267 : aplan->part_prune_index =
1892 : 267 : register_partpruneinfo(root, aplan->part_prune_index, rtoffset);
1893 : :
1894 : : /* We don't need to recurse to lefttree or righttree ... */
2459 tgl@sss.pgh.pa.us 1895 [ - + ]: 9095 : Assert(aplan->plan.lefttree == NULL);
1896 [ - + ]: 9095 : Assert(aplan->plan.righttree == NULL);
1897 : :
1898 : 9095 : return (Plan *) aplan;
1899 : : }
1900 : :
1901 : : /*
1902 : : * set_mergeappend_references
1903 : : * Do set_plan_references processing on a MergeAppend
1904 : : *
1905 : : * We try to strip out the MergeAppend entirely; if we can't, we have
1906 : : * to do the normal processing on it.
1907 : : */
1908 : : static Plan *
1909 : 289 : set_mergeappend_references(PlannerInfo *root,
1910 : : MergeAppend *mplan,
1911 : : int rtoffset)
1912 : : {
1913 : : ListCell *l;
1914 : :
1915 : : /*
1916 : : * MergeAppend, like Sort et al, doesn't actually evaluate its targetlist
1917 : : * or check quals. If it's got exactly one child plan, then it's not
1918 : : * doing anything useful at all, and we can strip it out.
1919 : : */
1920 [ - + ]: 289 : Assert(mplan->plan.qual == NIL);
1921 : :
1922 : : /* First, we gotta recurse on the children */
1923 [ + - + + : 1100 : foreach(l, mplan->mergeplans)
+ + ]
1924 : : {
1925 : 811 : lfirst(l) = set_plan_refs(root, (Plan *) lfirst(l), rtoffset);
1926 : : }
1927 : :
1928 : : /*
1929 : : * See if it's safe to get rid of the MergeAppend entirely. For this to
1930 : : * be safe, there must be only one child plan and that child plan's
1931 : : * parallel awareness must match the MergeAppend's. The reason for the
1932 : : * latter is that if the MergeAppend is parallel aware and the child is
1933 : : * not, then the calling plan may execute the non-parallel aware child
1934 : : * multiple times. (If you change these rules, update
1935 : : * create_merge_append_path to match.)
1936 : : */
1247 alvherre@alvh.no-ip. 1937 [ + + ]: 289 : if (list_length(mplan->mergeplans) == 1)
1938 : : {
1939 : 2 : Plan *p = (Plan *) linitial(mplan->mergeplans);
1940 : :
1941 [ + - ]: 2 : if (p->parallel_aware == mplan->plan.parallel_aware)
1942 : 2 : return clean_up_removed_plan_level((Plan *) mplan, p);
1943 : : }
1944 : :
1945 : : /*
1946 : : * Otherwise, clean up the MergeAppend as needed. It's okay to do this
1947 : : * after recursing to the children, because set_dummy_tlist_references
1948 : : * doesn't look at those.
1949 : : */
2459 tgl@sss.pgh.pa.us 1950 : 287 : set_dummy_tlist_references((Plan *) mplan, rtoffset);
1951 : :
2198 1952 : 287 : mplan->apprelids = offset_relid_set(mplan->apprelids, rtoffset);
1953 : :
1954 : : /*
1955 : : * Add PartitionPruneInfo, if any, to PlannerGlobal and update the index.
1956 : : * Also update the RT indexes present in it to add the offset.
1957 : : */
321 amitlan@postgresql.o 1958 [ + + ]: 287 : if (mplan->part_prune_index >= 0)
1959 : 18 : mplan->part_prune_index =
1960 : 18 : register_partpruneinfo(root, mplan->part_prune_index, rtoffset);
1961 : :
1962 : : /* We don't need to recurse to lefttree or righttree ... */
2459 tgl@sss.pgh.pa.us 1963 [ - + ]: 287 : Assert(mplan->plan.lefttree == NULL);
1964 [ - + ]: 287 : Assert(mplan->plan.righttree == NULL);
1965 : :
1966 : 287 : return (Plan *) mplan;
1967 : : }
1968 : :
1969 : : /*
1970 : : * set_hash_references
1971 : : * Do set_plan_references processing on a Hash node
1972 : : */
1973 : : static void
2329 andres@anarazel.de 1974 : 18056 : set_hash_references(PlannerInfo *root, Plan *plan, int rtoffset)
1975 : : {
1976 : 18056 : Hash *hplan = (Hash *) plan;
1977 : 18056 : Plan *outer_plan = plan->lefttree;
1978 : : indexed_tlist *outer_itlist;
1979 : :
1980 : : /*
1981 : : * Hash's hashkeys are used when feeding tuples into the hashtable,
1982 : : * therefore have them reference Hash's outer plan (which itself is the
1983 : : * inner plan of the HashJoin).
1984 : : */
1985 : 18056 : outer_itlist = build_tlist_index(outer_plan->targetlist);
1986 : 18056 : hplan->hashkeys = (List *)
1987 : 18056 : fix_upper_expr(root,
1988 : 18056 : (Node *) hplan->hashkeys,
1989 : : outer_itlist,
1990 : : OUTER_VAR,
1991 : : rtoffset,
1992 : : NRM_EQUAL,
1907 tgl@sss.pgh.pa.us 1993 : 18056 : NUM_EXEC_QUAL(plan));
1994 : :
1995 : : /* Hash doesn't project */
2329 andres@anarazel.de 1996 : 18056 : set_dummy_tlist_references(plan, rtoffset);
1997 : :
1998 : : /* Hash nodes don't have their own quals */
1999 [ - + ]: 18056 : Assert(plan->qual == NIL);
2000 : 18056 : }
2001 : :
2002 : : /*
2003 : : * offset_relid_set
2004 : : * Apply rtoffset to the members of a Relids set.
2005 : : */
2006 : : static Relids
2198 tgl@sss.pgh.pa.us 2007 : 116514 : offset_relid_set(Relids relids, int rtoffset)
2008 : : {
2009 : 116514 : Relids result = NULL;
2010 : : int rtindex;
2011 : :
2012 : : /* If there's no offset to apply, we needn't recompute the value */
2013 [ + + ]: 116514 : if (rtoffset == 0)
2014 : 106118 : return relids;
2015 : 10396 : rtindex = -1;
2016 [ + + ]: 15858 : while ((rtindex = bms_next_member(relids, rtindex)) >= 0)
2017 : 5462 : result = bms_add_member(result, rtindex + rtoffset);
2018 : 10396 : return result;
2019 : : }
2020 : :
2021 : : /*
2022 : : * copyVar
2023 : : * Copy a Var node.
2024 : : *
2025 : : * fix_scan_expr and friends do this enough times that it's worth having
2026 : : * a bespoke routine instead of using the generic copyObject() function.
2027 : : */
2028 : : static inline Var *
6806 2029 : 1070375 : copyVar(Var *var)
2030 : : {
7 michael@paquier.xyz 2031 :GNC 1070375 : Var *newvar = palloc_object(Var);
2032 : :
6806 tgl@sss.pgh.pa.us 2033 :CBC 1070375 : *newvar = *var;
2034 : 1070375 : return newvar;
2035 : : }
2036 : :
2037 : : /*
2038 : : * fix_expr_common
2039 : : * Do generic set_plan_references processing on an expression node
2040 : : *
2041 : : * This is code that is common to all variants of expression-fixing.
2042 : : * We must look up operator opcode info for OpExpr and related nodes,
2043 : : * add OIDs from regclass Const nodes into root->glob->relationOids, and
2044 : : * add PlanInvalItems for user-defined functions into root->glob->invalItems.
2045 : : * We also fill in column index lists for GROUPING() expressions.
2046 : : *
2047 : : * We assume it's okay to update opcode info in-place. So this could possibly
2048 : : * scribble on the planner's input data structures, but it's OK.
2049 : : */
2050 : : static void
5219 2051 : 7284140 : fix_expr_common(PlannerInfo *root, Node *node)
2052 : : {
2053 : : /* We assume callers won't call us on a NULL pointer */
6308 2054 [ + + ]: 7284140 : if (IsA(node, Aggref))
2055 : : {
5219 2056 : 30063 : record_plan_function_dependency(root,
2057 : : ((Aggref *) node)->aggfnoid);
2058 : : }
6198 2059 [ + + ]: 7254077 : else if (IsA(node, WindowFunc))
2060 : : {
5219 2061 : 1945 : record_plan_function_dependency(root,
2062 : : ((WindowFunc *) node)->winfnoid);
2063 : : }
6308 2064 [ + + ]: 7252132 : else if (IsA(node, FuncExpr))
2065 : : {
5219 2066 : 151324 : record_plan_function_dependency(root,
2067 : : ((FuncExpr *) node)->funcid);
2068 : : }
6308 2069 [ + + ]: 7100808 : else if (IsA(node, OpExpr))
2070 : : {
2071 : 444519 : set_opfuncid((OpExpr *) node);
5219 2072 : 444519 : record_plan_function_dependency(root,
2073 : : ((OpExpr *) node)->opfuncid);
2074 : : }
6308 2075 [ + + ]: 6656289 : else if (IsA(node, DistinctExpr))
2076 : : {
2077 : 552 : set_opfuncid((OpExpr *) node); /* rely on struct equivalence */
5219 2078 : 552 : record_plan_function_dependency(root,
2079 : : ((DistinctExpr *) node)->opfuncid);
2080 : : }
6308 2081 [ + + ]: 6655737 : else if (IsA(node, NullIfExpr))
2082 : : {
2083 : 64 : set_opfuncid((OpExpr *) node); /* rely on struct equivalence */
5219 2084 : 64 : record_plan_function_dependency(root,
2085 : : ((NullIfExpr *) node)->opfuncid);
2086 : : }
6308 2087 [ + + ]: 6655673 : else if (IsA(node, ScalarArrayOpExpr))
2088 : : {
1714 drowley@postgresql.o 2089 : 19524 : ScalarArrayOpExpr *saop = (ScalarArrayOpExpr *) node;
2090 : :
2091 : 19524 : set_sa_opfuncid(saop);
2092 : 19524 : record_plan_function_dependency(root, saop->opfuncid);
2093 : :
825 2094 [ + + ]: 19524 : if (OidIsValid(saop->hashfuncid))
1714 2095 : 332 : record_plan_function_dependency(root, saop->hashfuncid);
2096 : :
825 2097 [ + + ]: 19524 : if (OidIsValid(saop->negfuncid))
1624 2098 : 35 : record_plan_function_dependency(root, saop->negfuncid);
2099 : : }
6308 tgl@sss.pgh.pa.us 2100 [ + + ]: 6636149 : else if (IsA(node, Const))
2101 : : {
2102 : 723257 : Const *con = (Const *) node;
2103 : :
2104 : : /* Check for regclass reference */
2105 [ + + + + : 723257 : if (ISREGCLASSCONST(con))
+ + ]
5219 2106 : 136993 : root->glob->relationOids =
2107 : 136993 : lappend_oid(root->glob->relationOids,
2108 : : DatumGetObjectId(con->constvalue));
2109 : : }
3868 andres@anarazel.de 2110 [ + + ]: 5912892 : else if (IsA(node, GroupingFunc))
2111 : : {
2112 : 175 : GroupingFunc *g = (GroupingFunc *) node;
2113 : 175 : AttrNumber *grouping_map = root->grouping_map;
2114 : :
2115 : : /* If there are no grouping sets, we don't need this. */
2116 : :
2117 [ + + - + ]: 175 : Assert(grouping_map || g->cols == NIL);
2118 : :
2119 [ + + ]: 175 : if (grouping_map)
2120 : : {
2121 : : ListCell *lc;
2122 : 130 : List *cols = NIL;
2123 : :
2124 [ + - + + : 342 : foreach(lc, g->refs)
+ + ]
2125 : : {
2126 : 212 : cols = lappend_int(cols, grouping_map[lfirst_int(lc)]);
2127 : : }
2128 : :
2129 [ - + - - ]: 130 : Assert(!g->cols || equal(cols, g->cols));
2130 : :
2131 [ + - ]: 130 : if (!g->cols)
2132 : 130 : g->cols = cols;
2133 : : }
2134 : : }
6308 tgl@sss.pgh.pa.us 2135 : 7284140 : }
2136 : :
2137 : : /*
2138 : : * fix_param_node
2139 : : * Do set_plan_references processing on a Param
2140 : : *
2141 : : * If it's a PARAM_MULTIEXPR, replace it with the appropriate Param from
2142 : : * root->multiexpr_params; otherwise no change is needed.
2143 : : * Just for paranoia's sake, we make a copy of the node in either case.
2144 : : */
2145 : : static Node *
4200 2146 : 55440 : fix_param_node(PlannerInfo *root, Param *p)
2147 : : {
2148 [ + + ]: 55440 : if (p->paramkind == PARAM_MULTIEXPR)
2149 : : {
2150 : 143 : int subqueryid = p->paramid >> 16;
2151 : 143 : int colno = p->paramid & 0xFFFF;
2152 : : List *params;
2153 : :
2154 [ + - - + ]: 286 : if (subqueryid <= 0 ||
2155 : 143 : subqueryid > list_length(root->multiexpr_params))
4200 tgl@sss.pgh.pa.us 2156 [ # # ]:UBC 0 : elog(ERROR, "unexpected PARAM_MULTIEXPR ID: %d", p->paramid);
4200 tgl@sss.pgh.pa.us 2157 :CBC 143 : params = (List *) list_nth(root->multiexpr_params, subqueryid - 1);
2158 [ + - - + ]: 143 : if (colno <= 0 || colno > list_length(params))
4200 tgl@sss.pgh.pa.us 2159 [ # # ]:UBC 0 : elog(ERROR, "unexpected PARAM_MULTIEXPR ID: %d", p->paramid);
4200 tgl@sss.pgh.pa.us 2160 :CBC 143 : return copyObject(list_nth(params, colno - 1));
2161 : : }
3205 peter_e@gmx.net 2162 : 55297 : return (Node *) copyObject(p);
2163 : : }
2164 : :
2165 : : /*
2166 : : * fix_alternative_subplan
2167 : : * Do set_plan_references processing on an AlternativeSubPlan
2168 : : *
2169 : : * Choose one of the alternative implementations and return just that one,
2170 : : * discarding the rest of the AlternativeSubPlan structure.
2171 : : * Note: caller must still recurse into the result!
2172 : : *
2173 : : * We don't make any attempt to fix up cost estimates in the parent plan
2174 : : * node or higher-level nodes.
2175 : : */
2176 : : static Node *
1907 tgl@sss.pgh.pa.us 2177 : 921 : fix_alternative_subplan(PlannerInfo *root, AlternativeSubPlan *asplan,
2178 : : double num_exec)
2179 : : {
2180 : 921 : SubPlan *bestplan = NULL;
2181 : 921 : Cost bestcost = 0;
2182 : : ListCell *lc;
2183 : :
2184 : : /*
2185 : : * Compute the estimated cost of each subplan assuming num_exec
2186 : : * executions, and keep the cheapest one. In event of exact equality of
2187 : : * estimates, we prefer the later plan; this is a bit arbitrary, but in
2188 : : * current usage it biases us to break ties against fast-start subplans.
2189 : : */
2190 [ - + ]: 921 : Assert(asplan->subplans != NIL);
2191 : :
2192 [ + - + + : 2763 : foreach(lc, asplan->subplans)
+ + ]
2193 : : {
2194 : 1842 : SubPlan *curplan = (SubPlan *) lfirst(lc);
2195 : : Cost curcost;
2196 : :
2197 : 1842 : curcost = curplan->startup_cost + num_exec * curplan->per_call_cost;
1555 2198 [ + + + + ]: 1842 : if (bestplan == NULL || curcost <= bestcost)
2199 : : {
1907 2200 : 1299 : bestplan = curplan;
2201 : 1299 : bestcost = curcost;
2202 : : }
2203 : :
2204 : : /* Also mark all subplans that are in AlternativeSubPlans */
1555 2205 : 1842 : root->isAltSubplan[curplan->plan_id - 1] = true;
2206 : : }
2207 : :
2208 : : /* Mark the subplan we selected */
2209 : 921 : root->isUsedSubplan[bestplan->plan_id - 1] = true;
2210 : :
1907 2211 : 921 : return (Node *) bestplan;
2212 : : }
2213 : :
2214 : : /*
2215 : : * fix_scan_expr
2216 : : * Do set_plan_references processing on a scan-level expression
2217 : : *
2218 : : * This consists of incrementing all Vars' varnos by rtoffset,
2219 : : * replacing PARAM_MULTIEXPR Params, expanding PlaceHolderVars,
2220 : : * replacing Aggref nodes that should be replaced by initplan output Params,
2221 : : * choosing the best implementation for AlternativeSubPlans,
2222 : : * looking up operator opcode info for OpExpr and related nodes,
2223 : : * and adding OIDs from regclass Const nodes into root->glob->relationOids.
2224 : : *
2225 : : * 'node': the expression to be modified
2226 : : * 'rtoffset': how much to increment varnos by
2227 : : * 'num_exec': estimated number of executions of expression
2228 : : *
2229 : : * The expression tree is either copied-and-modified, or modified in-place
2230 : : * if that seems safe.
2231 : : */
2232 : : static Node *
2233 : 1242197 : fix_scan_expr(PlannerInfo *root, Node *node, int rtoffset, double num_exec)
2234 : : {
2235 : : fix_scan_expr_context context;
2236 : :
5219 2237 : 1242197 : context.root = root;
6873 2238 : 1242197 : context.rtoffset = rtoffset;
1907 2239 : 1242197 : context.num_exec = num_exec;
2240 : :
4200 2241 [ + + ]: 1242197 : if (rtoffset != 0 ||
2242 [ + + ]: 1024267 : root->multiexpr_params != NIL ||
3572 2243 [ + + ]: 1023976 : root->glob->lastPHId != 0 ||
1907 2244 [ + + ]: 1018618 : root->minmax_aggs != NIL ||
2245 [ + + ]: 1018213 : root->hasAlternativeSubPlans)
2246 : : {
6598 2247 : 230717 : return fix_scan_expr_mutator(node, &context);
2248 : : }
2249 : : else
2250 : : {
2251 : : /*
2252 : : * If rtoffset == 0, we don't need to change any Vars, and if there
2253 : : * are no MULTIEXPR subqueries then we don't need to replace
2254 : : * PARAM_MULTIEXPR Params, and if there are no placeholders anywhere
2255 : : * we won't need to remove them, and if there are no minmax Aggrefs we
2256 : : * won't need to replace them, and if there are no AlternativeSubPlans
2257 : : * we won't need to remove them. Then it's OK to just scribble on the
2258 : : * input node tree instead of copying (since the only change, filling
2259 : : * in any unset opfuncid fields, is harmless). This saves just enough
2260 : : * cycles to be noticeable on trivial queries.
2261 : : */
2262 : 1011480 : (void) fix_scan_expr_walker(node, &context);
2263 : 1011480 : return node;
2264 : : }
2265 : : }
2266 : :
2267 : : static Node *
6607 bruce@momjian.us 2268 : 1410982 : fix_scan_expr_mutator(Node *node, fix_scan_expr_context *context)
2269 : : {
7514 tgl@sss.pgh.pa.us 2270 [ + + ]: 1410982 : if (node == NULL)
6873 2271 : 88312 : return NULL;
7514 2272 [ + + ]: 1322670 : if (IsA(node, Var))
2273 : : {
6806 2274 : 451884 : Var *var = copyVar((Var *) node);
2275 : :
7514 2276 [ - + ]: 451884 : Assert(var->varlevelsup == 0);
2277 : :
2278 : : /*
2279 : : * We should not see Vars marked INNER_VAR, OUTER_VAR, or ROWID_VAR.
2280 : : * But an indexqual expression could contain INDEX_VAR Vars.
2281 : : */
5181 2282 [ - + ]: 451884 : Assert(var->varno != INNER_VAR);
2283 [ - + ]: 451884 : Assert(var->varno != OUTER_VAR);
1722 2284 [ - + ]: 451884 : Assert(var->varno != ROWID_VAR);
5181 2285 [ + + ]: 451884 : if (!IS_SPECIAL_VARNO(var->varno))
2286 : 424594 : var->varno += context->rtoffset;
2169 2287 [ + + ]: 451884 : if (var->varnosyn > 0)
2288 : 451410 : var->varnosyn += context->rtoffset;
6873 2289 : 451884 : return (Node *) var;
2290 : : }
4200 2291 [ + + ]: 870786 : if (IsA(node, Param))
2292 : 47570 : return fix_param_node(context->root, (Param *) node);
3572 2293 [ + + ]: 823216 : if (IsA(node, Aggref))
2294 : : {
2295 : 227 : Aggref *aggref = (Aggref *) node;
2296 : : Param *aggparam;
2297 : :
2298 : : /* See if the Aggref should be replaced by a Param */
888 2299 : 227 : aggparam = find_minmax_agg_replacement_param(context->root, aggref);
2300 [ + + ]: 227 : if (aggparam != NULL)
2301 : : {
2302 : : /* Make a copy of the Param for paranoia's sake */
2303 : 212 : return (Node *) copyObject(aggparam);
2304 : : }
2305 : : /* If no match, just fall through to process it normally */
2306 : : }
6764 2307 [ - + ]: 823004 : if (IsA(node, CurrentOfExpr))
2308 : : {
6764 tgl@sss.pgh.pa.us 2309 :UBC 0 : CurrentOfExpr *cexpr = (CurrentOfExpr *) copyObject(node);
2310 : :
1554 2311 [ # # ]: 0 : Assert(!IS_SPECIAL_VARNO(cexpr->cvarno));
2312 : 0 : cexpr->cvarno += context->rtoffset;
6764 2313 : 0 : return (Node *) cexpr;
2314 : : }
6266 tgl@sss.pgh.pa.us 2315 [ + + ]:CBC 823004 : if (IsA(node, PlaceHolderVar))
2316 : : {
2317 : : /* At scan level, we should always just evaluate the contained expr */
2318 : 1245 : PlaceHolderVar *phv = (PlaceHolderVar *) node;
2319 : :
2320 : : /* XXX can we assert something about phnullingrels? */
2321 : 1245 : return fix_scan_expr_mutator((Node *) phv->phexpr, context);
2322 : : }
1907 2323 [ + + ]: 821759 : if (IsA(node, AlternativeSubPlan))
2324 : 147 : return fix_scan_expr_mutator(fix_alternative_subplan(context->root,
2325 : : (AlternativeSubPlan *) node,
2326 : : context->num_exec),
2327 : : context);
5219 2328 : 821612 : fix_expr_common(context->root, node);
384 peter@eisentraut.org 2329 : 821612 : return expression_tree_mutator(node, fix_scan_expr_mutator, context);
2330 : : }
2331 : :
2332 : : static bool
6598 tgl@sss.pgh.pa.us 2333 : 5467339 : fix_scan_expr_walker(Node *node, fix_scan_expr_context *context)
2334 : : {
2335 [ + + ]: 5467339 : if (node == NULL)
2336 : 514782 : return false;
1722 2337 [ + + - + ]: 4952557 : Assert(!(IsA(node, Var) && ((Var *) node)->varno == ROWID_VAR));
6266 2338 [ - + ]: 4952557 : Assert(!IsA(node, PlaceHolderVar));
1907 2339 [ - + ]: 4952557 : Assert(!IsA(node, AlternativeSubPlan));
5219 2340 : 4952557 : fix_expr_common(context->root, node);
384 peter@eisentraut.org 2341 : 4952557 : return expression_tree_walker(node, fix_scan_expr_walker, context);
2342 : : }
2343 : :
2344 : : /*
2345 : : * set_join_references
2346 : : * Modify the target list and quals of a join node to reference its
2347 : : * subplans, by setting the varnos to OUTER_VAR or INNER_VAR and setting
2348 : : * attno values to the result domain number of either the corresponding
2349 : : * outer or inner join tuple item. Also perform opcode lookup for these
2350 : : * expressions, and add regclass OIDs to root->glob->relationOids.
2351 : : */
2352 : : static void
5219 tgl@sss.pgh.pa.us 2353 : 71471 : set_join_references(PlannerInfo *root, Join *join, int rtoffset)
2354 : : {
8372 2355 : 71471 : Plan *outer_plan = join->plan.lefttree;
2356 : 71471 : Plan *inner_plan = join->plan.righttree;
2357 : : indexed_tlist *outer_itlist;
2358 : : indexed_tlist *inner_itlist;
2359 : :
7495 2360 : 71471 : outer_itlist = build_tlist_index(outer_plan->targetlist);
2361 : 71471 : inner_itlist = build_tlist_index(inner_plan->targetlist);
2362 : :
2363 : : /*
2364 : : * First process the joinquals (including merge or hash clauses). These
2365 : : * are logically below the join so they can always use all values
2366 : : * available from the input tlists. It's okay to also handle
2367 : : * NestLoopParams now, because those couldn't refer to nullable
2368 : : * subexpressions.
2369 : : */
5219 2370 : 142942 : join->joinqual = fix_join_expr(root,
2371 : : join->joinqual,
2372 : : outer_itlist,
2373 : : inner_itlist,
2374 : : (Index) 0,
2375 : : rtoffset,
2376 : : NRM_EQUAL,
1907 2377 : 71471 : NUM_EXEC_QUAL((Plan *) join));
2378 : :
2379 : : /* Now do join-type-specific stuff */
8372 2380 [ + + ]: 71471 : if (IsA(join, NestLoop))
2381 : : {
5637 2382 : 49624 : NestLoop *nl = (NestLoop *) join;
2383 : : ListCell *lc;
2384 : :
2385 [ + + + + : 78293 : foreach(lc, nl->nestParams)
+ + ]
2386 : : {
2387 : 28669 : NestLoopParam *nlp = (NestLoopParam *) lfirst(lc);
2388 : :
2389 : : /*
2390 : : * Because we don't reparameterize parameterized paths to match
2391 : : * the outer-join level at which they are used, Vars seen in the
2392 : : * NestLoopParam expression may have nullingrels that are just a
2393 : : * subset of those in the Vars actually available from the outer
2394 : : * side. (Lateral references can also cause this, as explained in
2395 : : * the comments for identify_current_nestloop_params.) Not
2396 : : * checking this exactly is a bit grotty, but the work needed to
2397 : : * make things match up perfectly seems well out of proportion to
2398 : : * the value.
2399 : : */
5219 2400 : 57338 : nlp->paramval = (Var *) fix_upper_expr(root,
5637 2401 : 28669 : (Node *) nlp->paramval,
2402 : : outer_itlist,
2403 : : OUTER_VAR,
2404 : : rtoffset,
2405 : : NRM_SUBSET,
2406 : : NUM_EXEC_TLIST(outer_plan));
2407 : : /* Check we replaced any PlaceHolderVar with simple Var */
5158 2408 [ + - ]: 28669 : if (!(IsA(nlp->paramval, Var) &&
2409 [ - + ]: 28669 : nlp->paramval->varno == OUTER_VAR))
5158 tgl@sss.pgh.pa.us 2410 [ # # ]:UBC 0 : elog(ERROR, "NestLoopParam was not reduced to a simple Var");
2411 : : }
2412 : : }
8372 tgl@sss.pgh.pa.us 2413 [ + + ]:CBC 21847 : else if (IsA(join, MergeJoin))
2414 : : {
2415 : 3791 : MergeJoin *mj = (MergeJoin *) join;
2416 : :
5219 2417 : 3791 : mj->mergeclauses = fix_join_expr(root,
2418 : : mj->mergeclauses,
2419 : : outer_itlist,
2420 : : inner_itlist,
2421 : : (Index) 0,
2422 : : rtoffset,
2423 : : NRM_EQUAL,
1907 2424 : 3791 : NUM_EXEC_QUAL((Plan *) join));
2425 : : }
8372 2426 [ + - ]: 18056 : else if (IsA(join, HashJoin))
2427 : : {
2428 : 18056 : HashJoin *hj = (HashJoin *) join;
2429 : :
5219 2430 : 36112 : hj->hashclauses = fix_join_expr(root,
2431 : : hj->hashclauses,
2432 : : outer_itlist,
2433 : : inner_itlist,
2434 : : (Index) 0,
2435 : : rtoffset,
2436 : : NRM_EQUAL,
1907 2437 : 18056 : NUM_EXEC_QUAL((Plan *) join));
2438 : :
2439 : : /*
2440 : : * HashJoin's hashkeys are used to look for matching tuples from its
2441 : : * outer plan (not the Hash node!) in the hashtable.
2442 : : */
2329 andres@anarazel.de 2443 : 18056 : hj->hashkeys = (List *) fix_upper_expr(root,
2444 : 18056 : (Node *) hj->hashkeys,
2445 : : outer_itlist,
2446 : : OUTER_VAR,
2447 : : rtoffset,
2448 : : NRM_EQUAL,
1907 tgl@sss.pgh.pa.us 2449 : 18056 : NUM_EXEC_QUAL((Plan *) join));
2450 : : }
2451 : :
2452 : : /*
2453 : : * Now we need to fix up the targetlist and qpqual, which are logically
2454 : : * above the join. This means that, if it's not an inner join, any Vars
2455 : : * and PHVs appearing here should have nullingrels that include the
2456 : : * effects of the outer join, ie they will have nullingrels equal to the
2457 : : * input Vars' nullingrels plus the bit added by the outer join. We don't
2458 : : * currently have enough info available here to identify what that should
2459 : : * be, so we just tell fix_join_expr to accept superset nullingrels
2460 : : * matches instead of exact ones.
2461 : : */
3910 2462 : 71471 : join->plan.targetlist = fix_join_expr(root,
2463 : : join->plan.targetlist,
2464 : : outer_itlist,
2465 : : inner_itlist,
2466 : : (Index) 0,
2467 : : rtoffset,
1052 2468 [ + + ]: 71471 : (join->jointype == JOIN_INNER ? NRM_EQUAL : NRM_SUPERSET),
2469 : : NUM_EXEC_TLIST((Plan *) join));
3910 2470 : 71471 : join->plan.qual = fix_join_expr(root,
2471 : : join->plan.qual,
2472 : : outer_itlist,
2473 : : inner_itlist,
2474 : : (Index) 0,
2475 : : rtoffset,
1052 2476 : 71471 : (join->jointype == JOIN_INNER ? NRM_EQUAL : NRM_SUPERSET),
1907 2477 [ + + ]: 71471 : NUM_EXEC_QUAL((Plan *) join));
2478 : :
7495 2479 : 71471 : pfree(outer_itlist);
2480 : 71471 : pfree(inner_itlist);
10753 scrappy@hub.org 2481 : 71471 : }
2482 : :
2483 : : /*
2484 : : * set_upper_references
2485 : : * Update the targetlist and quals of an upper-level plan node
2486 : : * to refer to the tuples returned by its lefttree subplan.
2487 : : * Also perform opcode lookup for these expressions, and
2488 : : * add regclass OIDs to root->glob->relationOids.
2489 : : *
2490 : : * This is used for single-input plan types like Agg, Group, Result.
2491 : : *
2492 : : * In most cases, we have to match up individual Vars in the tlist and
2493 : : * qual expressions with elements of the subplan's tlist (which was
2494 : : * generated by flattening these selfsame expressions, so it should have all
2495 : : * the required variables). There is an important exception, however:
2496 : : * depending on where we are in the plan tree, sort/group columns may have
2497 : : * been pushed into the subplan tlist unflattened. If these values are also
2498 : : * needed in the output then we want to reference the subplan tlist element
2499 : : * rather than recomputing the expression.
2500 : : */
2501 : : static void
5219 tgl@sss.pgh.pa.us 2502 : 37774 : set_upper_references(PlannerInfo *root, Plan *plan, int rtoffset)
2503 : : {
9614 2504 : 37774 : Plan *subplan = plan->lefttree;
2505 : : indexed_tlist *subplan_itlist;
2506 : : List *output_targetlist;
2507 : : ListCell *l;
2508 : :
6872 2509 : 37774 : subplan_itlist = build_tlist_index(subplan->targetlist);
2510 : :
2511 : : /*
2512 : : * If it's a grouping node with grouping sets, any Vars and PHVs appearing
2513 : : * in the targetlist and quals should have nullingrels that include the
2514 : : * effects of the grouping step, ie they will have nullingrels equal to
2515 : : * the input Vars/PHVs' nullingrels plus the RT index of the grouping
2516 : : * step. In order to perform exact nullingrels matches, we remove the RT
2517 : : * index of the grouping step first.
2518 : : */
463 rguo@postgresql.org 2519 [ + + ]: 37774 : if (IsA(plan, Agg) &&
2520 [ + + ]: 23518 : root->group_rtindex > 0 &&
2521 [ + + ]: 3349 : ((Agg *) plan)->groupingSets)
2522 : : {
2523 : 433 : plan->targetlist = (List *)
2524 : 433 : remove_nulling_relids((Node *) plan->targetlist,
2525 : 433 : bms_make_singleton(root->group_rtindex),
2526 : : NULL);
2527 : 433 : plan->qual = (List *)
2528 : 433 : remove_nulling_relids((Node *) plan->qual,
2529 : 433 : bms_make_singleton(root->group_rtindex),
2530 : : NULL);
2531 : : }
2532 : :
8814 tgl@sss.pgh.pa.us 2533 : 37774 : output_targetlist = NIL;
2534 [ + + + + : 102004 : foreach(l, plan->targetlist)
+ + ]
2535 : : {
2536 : 64230 : TargetEntry *tle = (TargetEntry *) lfirst(l);
2537 : : Node *newexpr;
2538 : :
2539 : : /* If it's a sort/group item, first try to match by sortref */
2974 2540 [ + + ]: 64230 : if (tle->ressortgroupref != 0)
2541 : : {
2542 : : newexpr = (Node *)
3205 peter_e@gmx.net 2543 : 19806 : search_indexed_tlist_for_sortgroupref(tle->expr,
2544 : : tle->ressortgroupref,
2545 : : subplan_itlist,
2546 : : OUTER_VAR);
5875 tgl@sss.pgh.pa.us 2547 [ + + ]: 19806 : if (!newexpr)
5219 2548 : 11086 : newexpr = fix_upper_expr(root,
5875 2549 : 11086 : (Node *) tle->expr,
2550 : : subplan_itlist,
2551 : : OUTER_VAR,
2552 : : rtoffset,
2553 : : NRM_EQUAL,
2554 : : NUM_EXEC_TLIST(plan));
2555 : : }
2556 : : else
5219 2557 : 44424 : newexpr = fix_upper_expr(root,
5875 2558 : 44424 : (Node *) tle->expr,
2559 : : subplan_itlist,
2560 : : OUTER_VAR,
2561 : : rtoffset,
2562 : : NRM_EQUAL,
2563 : : NUM_EXEC_TLIST(plan));
7560 2564 : 64230 : tle = flatCopyTargetEntry(tle);
2565 : 64230 : tle->expr = (Expr *) newexpr;
2566 : 64230 : output_targetlist = lappend(output_targetlist, tle);
2567 : : }
8814 2568 : 37774 : plan->targetlist = output_targetlist;
2569 : :
9614 2570 : 37774 : plan->qual = (List *)
5219 2571 : 37774 : fix_upper_expr(root,
6642 2572 : 37774 : (Node *) plan->qual,
2573 : : subplan_itlist,
2574 : : OUTER_VAR,
2575 : : rtoffset,
2576 : : NRM_EQUAL,
1907 2577 : 37774 : NUM_EXEC_QUAL(plan));
2578 : :
7495 2579 : 37774 : pfree(subplan_itlist);
10753 scrappy@hub.org 2580 : 37774 : }
2581 : :
2582 : : /*
2583 : : * set_param_references
2584 : : * Initialize the initParam list in Gather or Gather merge node such that
2585 : : * it contains reference of all the params that needs to be evaluated
2586 : : * before execution of the node. It contains the initplan params that are
2587 : : * being passed to the plan nodes below it.
2588 : : */
2589 : : static void
2953 rhaas@postgresql.org 2590 : 750 : set_param_references(PlannerInfo *root, Plan *plan)
2591 : : {
2041 tgl@sss.pgh.pa.us 2592 [ + + - + ]: 750 : Assert(IsA(plan, Gather) || IsA(plan, GatherMerge));
2593 : :
2953 rhaas@postgresql.org 2594 [ + + ]: 750 : if (plan->lefttree->extParam)
2595 : : {
2596 : : PlannerInfo *proot;
2597 : 686 : Bitmapset *initSetParam = NULL;
2598 : : ListCell *l;
2599 : :
2600 [ + + ]: 1459 : for (proot = root; proot != NULL; proot = proot->parent_root)
2601 : : {
2602 [ + + + + : 812 : foreach(l, proot->init_plans)
+ + ]
2603 : : {
2604 : 39 : SubPlan *initsubplan = (SubPlan *) lfirst(l);
2605 : : ListCell *l2;
2606 : :
2607 [ + - + + : 78 : foreach(l2, initsubplan->setParam)
+ + ]
2608 : : {
2609 : 39 : initSetParam = bms_add_member(initSetParam, lfirst_int(l2));
2610 : : }
2611 : : }
2612 : : }
2613 : :
2614 : : /*
2615 : : * Remember the list of all external initplan params that are used by
2616 : : * the children of Gather or Gather merge node.
2617 : : */
2618 [ + + ]: 686 : if (IsA(plan, Gather))
2619 : 509 : ((Gather *) plan)->initParam =
2620 : 509 : bms_intersect(plan->lefttree->extParam, initSetParam);
2621 : : else
2622 : 177 : ((GatherMerge *) plan)->initParam =
2623 : 177 : bms_intersect(plan->lefttree->extParam, initSetParam);
2624 : : }
2625 : 750 : }
2626 : :
2627 : : /*
2628 : : * Recursively scan an expression tree and convert Aggrefs to the proper
2629 : : * intermediate form for combining aggregates. This means (1) replacing each
2630 : : * one's argument list with a single argument that is the original Aggref
2631 : : * modified to show partial aggregation and (2) changing the upper Aggref to
2632 : : * show combining aggregation.
2633 : : *
2634 : : * After this step, set_upper_references will replace the partial Aggrefs
2635 : : * with Vars referencing the lower Agg plan node's outputs, so that the final
2636 : : * form seen by the executor is a combining Aggref with a Var as input.
2637 : : *
2638 : : * It's rather messy to postpone this step until setrefs.c; ideally it'd be
2639 : : * done in createplan.c. The difficulty is that once we modify the Aggref
2640 : : * expressions, they will no longer be equal() to their original form and
2641 : : * so cross-plan-node-level matches will fail. So this has to happen after
2642 : : * the plan node above the Agg has resolved its subplan references.
2643 : : */
2644 : : static Node *
3461 tgl@sss.pgh.pa.us 2645 : 5097 : convert_combining_aggrefs(Node *node, void *context)
2646 : : {
2647 [ + + ]: 5097 : if (node == NULL)
2648 : 609 : return NULL;
2649 [ + + ]: 4488 : if (IsA(node, Aggref))
2650 : : {
2651 : 1153 : Aggref *orig_agg = (Aggref *) node;
2652 : : Aggref *child_agg;
2653 : : Aggref *parent_agg;
2654 : :
2655 : : /* Assert we've not chosen to partial-ize any unsupported cases */
3434 2656 [ - + ]: 1153 : Assert(orig_agg->aggorder == NIL);
2657 [ - + ]: 1153 : Assert(orig_agg->aggdistinct == NIL);
2658 : :
2659 : : /*
2660 : : * Since aggregate calls can't be nested, we needn't recurse into the
2661 : : * arguments. But for safety, flat-copy the Aggref node itself rather
2662 : : * than modifying it in-place.
2663 : : */
3461 2664 : 1153 : child_agg = makeNode(Aggref);
2665 : 1153 : memcpy(child_agg, orig_agg, sizeof(Aggref));
2666 : :
2667 : : /*
2668 : : * For the parent Aggref, we want to copy all the fields of the
2669 : : * original aggregate *except* the args list, which we'll replace
2670 : : * below, and the aggfilter expression, which should be applied only
2671 : : * by the child not the parent. Rather than explicitly knowing about
2672 : : * all the other fields here, we can momentarily modify child_agg to
2673 : : * provide a suitable source for copyObject.
2674 : : */
2675 : 1153 : child_agg->args = NIL;
3434 2676 : 1153 : child_agg->aggfilter = NULL;
3205 peter_e@gmx.net 2677 : 1153 : parent_agg = copyObject(child_agg);
3461 tgl@sss.pgh.pa.us 2678 : 1153 : child_agg->args = orig_agg->args;
3434 2679 : 1153 : child_agg->aggfilter = orig_agg->aggfilter;
2680 : :
2681 : : /*
2682 : : * Now, set up child_agg to represent the first phase of partial
2683 : : * aggregation. For now, assume serialization is required.
2684 : : */
3461 2685 : 1153 : mark_partial_aggref(child_agg, AGGSPLIT_INITIAL_SERIAL);
2686 : :
2687 : : /*
2688 : : * And set up parent_agg to represent the second phase.
2689 : : */
2690 : 1153 : parent_agg->args = list_make1(makeTargetEntry((Expr *) child_agg,
2691 : : 1, NULL, false));
2692 : 1153 : mark_partial_aggref(parent_agg, AGGSPLIT_FINAL_DESERIAL);
2693 : :
2694 : 1153 : return (Node *) parent_agg;
2695 : : }
384 peter@eisentraut.org 2696 : 3335 : return expression_tree_mutator(node, convert_combining_aggrefs, context);
2697 : : }
2698 : :
2699 : : /*
2700 : : * set_dummy_tlist_references
2701 : : * Replace the targetlist of an upper-level plan node with a simple
2702 : : * list of OUTER_VAR references to its child.
2703 : : *
2704 : : * This is used for plan types like Sort and Append that don't evaluate
2705 : : * their targetlists. Although the executor doesn't care at all what's in
2706 : : * the tlist, EXPLAIN needs it to be realistic.
2707 : : *
2708 : : * Note: we could almost use set_upper_references() here, but it fails for
2709 : : * Append for lack of a lefttree subplan. Single-purpose code is faster
2710 : : * anyway.
2711 : : */
2712 : : static void
6872 tgl@sss.pgh.pa.us 2713 : 84052 : set_dummy_tlist_references(Plan *plan, int rtoffset)
2714 : : {
2715 : : List *output_targetlist;
2716 : : ListCell *l;
2717 : :
2718 : 84052 : output_targetlist = NIL;
2719 [ + + + + : 370776 : foreach(l, plan->targetlist)
+ + ]
2720 : : {
2721 : 286724 : TargetEntry *tle = (TargetEntry *) lfirst(l);
2722 : 286724 : Var *oldvar = (Var *) tle->expr;
2723 : : Var *newvar;
2724 : :
2725 : : /*
2726 : : * As in search_indexed_tlist_for_non_var(), we prefer to keep Consts
2727 : : * as Consts, not Vars referencing Consts. Here, there's no speed
2728 : : * advantage to be had, but it makes EXPLAIN output look cleaner, and
2729 : : * again it avoids confusing the executor.
2730 : : */
3332 2731 [ + + ]: 286724 : if (IsA(oldvar, Const))
2732 : : {
2733 : : /* just reuse the existing TLE node */
2734 : 11200 : output_targetlist = lappend(output_targetlist, tle);
2735 : 11200 : continue;
2736 : : }
2737 : :
5181 2738 : 275524 : newvar = makeVar(OUTER_VAR,
6872 2739 : 275524 : tle->resno,
2740 : : exprType((Node *) oldvar),
2741 : : exprTypmod((Node *) oldvar),
2742 : : exprCollation((Node *) oldvar),
2743 : : 0);
2169 2744 [ + + ]: 275524 : if (IsA(oldvar, Var) &&
2745 [ + + ]: 220058 : oldvar->varnosyn > 0)
2746 : : {
2747 : 199611 : newvar->varnosyn = oldvar->varnosyn + rtoffset;
2748 : 199611 : newvar->varattnosyn = oldvar->varattnosyn;
2749 : : }
2750 : : else
2751 : : {
2752 : 75913 : newvar->varnosyn = 0; /* wasn't ever a plain Var */
2753 : 75913 : newvar->varattnosyn = 0;
2754 : : }
2755 : :
6872 2756 : 275524 : tle = flatCopyTargetEntry(tle);
2757 : 275524 : tle->expr = (Expr *) newvar;
2758 : 275524 : output_targetlist = lappend(output_targetlist, tle);
2759 : : }
2760 : 84052 : plan->targetlist = output_targetlist;
2761 : :
2762 : : /* We don't touch plan->qual here */
2763 : 84052 : }
2764 : :
2765 : :
2766 : : /*
2767 : : * build_tlist_index --- build an index data structure for a child tlist
2768 : : *
2769 : : * In most cases, subplan tlists will be "flat" tlists with only Vars,
2770 : : * so we try to optimize that case by extracting information about Vars
2771 : : * in advance. Matching a parent tlist to a child is still an O(N^2)
2772 : : * operation, but at least with a much smaller constant factor than plain
2773 : : * tlist_member() searches.
2774 : : *
2775 : : * The result of this function is an indexed_tlist struct to pass to
2776 : : * search_indexed_tlist_for_var() and siblings.
2777 : : * When done, the indexed_tlist may be freed with a single pfree().
2778 : : */
2779 : : static indexed_tlist *
7495 2780 : 210358 : build_tlist_index(List *tlist)
2781 : : {
2782 : : indexed_tlist *itlist;
2783 : : tlist_vinfo *vinfo;
2784 : : ListCell *l;
2785 : :
2786 : : /* Create data structure with enough slots for all tlist entries */
2787 : : itlist = (indexed_tlist *)
2788 : 210358 : palloc(offsetof(indexed_tlist, vars) +
2789 : 210358 : list_length(tlist) * sizeof(tlist_vinfo));
2790 : :
2791 : 210358 : itlist->tlist = tlist;
6266 2792 : 210358 : itlist->has_ph_vars = false;
7495 2793 : 210358 : itlist->has_non_vars = false;
2794 : :
2795 : : /* Find the Vars and fill in the index array */
2796 : 210358 : vinfo = itlist->vars;
8367 2797 [ + + + + : 1969727 : foreach(l, tlist)
+ + ]
2798 : : {
2799 : 1759369 : TargetEntry *tle = (TargetEntry *) lfirst(l);
2800 : :
7495 2801 [ + - + + ]: 1759369 : if (tle->expr && IsA(tle->expr, Var))
2802 : 1749388 : {
7368 bruce@momjian.us 2803 : 1749388 : Var *var = (Var *) tle->expr;
2804 : :
7495 tgl@sss.pgh.pa.us 2805 : 1749388 : vinfo->varno = var->varno;
2806 : 1749388 : vinfo->varattno = var->varattno;
2807 : 1749388 : vinfo->resno = tle->resno;
1052 2808 : 1749388 : vinfo->varnullingrels = var->varnullingrels;
7495 2809 : 1749388 : vinfo++;
2810 : : }
6266 2811 [ + - + + ]: 9981 : else if (tle->expr && IsA(tle->expr, PlaceHolderVar))
2812 : 1745 : itlist->has_ph_vars = true;
2813 : : else
7495 2814 : 8236 : itlist->has_non_vars = true;
2815 : : }
2816 : :
2817 : 210358 : itlist->num_vars = (vinfo - itlist->vars);
2818 : :
2819 : 210358 : return itlist;
2820 : : }
2821 : :
2822 : : /*
2823 : : * build_tlist_index_other_vars --- build a restricted tlist index
2824 : : *
2825 : : * This is like build_tlist_index, but we only index tlist entries that
2826 : : * are Vars belonging to some rel other than the one specified. We will set
2827 : : * has_ph_vars (allowing PlaceHolderVars to be matched), but not has_non_vars
2828 : : * (so nothing other than Vars and PlaceHolderVars can be matched).
2829 : : */
2830 : : static indexed_tlist *
1554 2831 : 1685 : build_tlist_index_other_vars(List *tlist, int ignore_rel)
2832 : : {
2833 : : indexed_tlist *itlist;
2834 : : tlist_vinfo *vinfo;
2835 : : ListCell *l;
2836 : :
2837 : : /* Create data structure with enough slots for all tlist entries */
2838 : : itlist = (indexed_tlist *)
7067 2839 : 1685 : palloc(offsetof(indexed_tlist, vars) +
2840 : 1685 : list_length(tlist) * sizeof(tlist_vinfo));
2841 : :
2842 : 1685 : itlist->tlist = tlist;
6266 2843 : 1685 : itlist->has_ph_vars = false;
7067 2844 : 1685 : itlist->has_non_vars = false;
2845 : :
2846 : : /* Find the desired Vars and fill in the index array */
2847 : 1685 : vinfo = itlist->vars;
2848 [ + + + + : 6513 : foreach(l, tlist)
+ + ]
2849 : : {
2850 : 4828 : TargetEntry *tle = (TargetEntry *) lfirst(l);
2851 : :
2852 [ + - + + ]: 4828 : if (tle->expr && IsA(tle->expr, Var))
2853 : 2761 : {
2854 : 2761 : Var *var = (Var *) tle->expr;
2855 : :
2856 [ + + ]: 2761 : if (var->varno != ignore_rel)
2857 : : {
2858 : 2106 : vinfo->varno = var->varno;
2859 : 2106 : vinfo->varattno = var->varattno;
2860 : 2106 : vinfo->resno = tle->resno;
1052 2861 : 2106 : vinfo->varnullingrels = var->varnullingrels;
7067 2862 : 2106 : vinfo++;
2863 : : }
2864 : : }
6266 2865 [ + - + + ]: 2067 : else if (tle->expr && IsA(tle->expr, PlaceHolderVar))
2866 : 60 : itlist->has_ph_vars = true;
2867 : : }
2868 : :
7067 2869 : 1685 : itlist->num_vars = (vinfo - itlist->vars);
2870 : :
2871 : 1685 : return itlist;
2872 : : }
2873 : :
2874 : : /*
2875 : : * search_indexed_tlist_for_var --- find a Var in an indexed tlist
2876 : : *
2877 : : * If a match is found, return a copy of the given Var with suitably
2878 : : * modified varno/varattno (to wit, newvarno and the resno of the TLE entry).
2879 : : * Also ensure that varnosyn is incremented by rtoffset.
2880 : : * If no match, return NULL.
2881 : : *
2882 : : * We cross-check the varnullingrels of the subplan output Var based on
2883 : : * nrm_match. Most call sites should pass NRM_EQUAL indicating we expect
2884 : : * an exact match. However, there are places where we haven't cleaned
2885 : : * things up completely, and we have to settle for allowing subset or
2886 : : * superset matches.
2887 : : */
2888 : : static Var *
6873 2889 : 793346 : search_indexed_tlist_for_var(Var *var, indexed_tlist *itlist,
2890 : : int newvarno, int rtoffset,
2891 : : NullingRelsMatch nrm_match)
2892 : : {
1554 2893 : 793346 : int varno = var->varno;
7495 2894 : 793346 : AttrNumber varattno = var->varattno;
2895 : : tlist_vinfo *vinfo;
2896 : : int i;
2897 : :
2898 : 793346 : vinfo = itlist->vars;
2899 : 793346 : i = itlist->num_vars;
2900 [ + + ]: 5704901 : while (i-- > 0)
2901 : : {
2902 [ + + + + ]: 5522951 : if (vinfo->varno == varno && vinfo->varattno == varattno)
2903 : : {
2904 : : /* Found a match */
6806 2905 : 611396 : Var *newvar = copyVar(var);
2906 : :
2907 : : /*
2908 : : * Verify that we kept all the nullingrels machinations straight.
2909 : : *
2910 : : * XXX we skip the check for system columns and whole-row Vars.
2911 : : * That's because such Vars might be row identity Vars, which are
2912 : : * generated without any varnullingrels. It'd be hard to do
2913 : : * otherwise, since they're normally made very early in planning,
2914 : : * when we haven't looked at the jointree yet and don't know which
2915 : : * joins might null such Vars. Doesn't seem worth the expense to
2916 : : * make them fully valid. (While it's slightly annoying that we
2917 : : * thereby lose checking for user-written references to such
2918 : : * columns, it seems unlikely that a bug in nullingrels logic
2919 : : * would affect only system columns.)
2920 : : */
945 2921 [ + + + + : 1205609 : if (!(varattno <= 0 ||
+ + - + ]
2922 : : (nrm_match == NRM_SUBSET ?
2923 : 28229 : bms_is_subset(var->varnullingrels, vinfo->varnullingrels) :
2924 : : nrm_match == NRM_SUPERSET ?
2925 : 184119 : bms_is_subset(vinfo->varnullingrels, var->varnullingrels) :
2926 : 381865 : bms_equal(vinfo->varnullingrels, var->varnullingrels))))
945 tgl@sss.pgh.pa.us 2927 [ # # ]:UBC 0 : elog(ERROR, "wrong varnullingrels %s (expected %s) for Var %d/%d",
2928 : : bmsToString(var->varnullingrels),
2929 : : bmsToString(vinfo->varnullingrels),
2930 : : varno, varattno);
2931 : :
7495 tgl@sss.pgh.pa.us 2932 :CBC 611396 : newvar->varno = newvarno;
2933 : 611396 : newvar->varattno = vinfo->resno;
2169 2934 [ + + ]: 611396 : if (newvar->varnosyn > 0)
2935 : 611093 : newvar->varnosyn += rtoffset;
7495 2936 : 611396 : return newvar;
2937 : : }
2938 : 4911555 : vinfo++;
2939 : : }
2940 : 181950 : return NULL; /* no match */
2941 : : }
2942 : :
2943 : : /*
2944 : : * search_indexed_tlist_for_phv --- find a PlaceHolderVar in an indexed tlist
2945 : : *
2946 : : * If a match is found, return a Var constructed to reference the tlist item.
2947 : : * If no match, return NULL.
2948 : : *
2949 : : * Cross-check phnullingrels as in search_indexed_tlist_for_var.
2950 : : *
2951 : : * NOTE: it is a waste of time to call this unless itlist->has_ph_vars.
2952 : : */
2953 : : static Var *
1052 2954 : 1821 : search_indexed_tlist_for_phv(PlaceHolderVar *phv,
2955 : : indexed_tlist *itlist, int newvarno,
2956 : : NullingRelsMatch nrm_match)
2957 : : {
2958 : : ListCell *lc;
2959 : :
2960 [ + - + + : 4603 : foreach(lc, itlist->tlist)
+ + ]
2961 : : {
2962 : 4415 : TargetEntry *tle = (TargetEntry *) lfirst(lc);
2963 : :
2964 [ + - + + ]: 4415 : if (tle->expr && IsA(tle->expr, PlaceHolderVar))
2965 : : {
2966 : 2394 : PlaceHolderVar *subphv = (PlaceHolderVar *) tle->expr;
2967 : : Var *newvar;
2968 : :
2969 : : /*
2970 : : * Analogously to search_indexed_tlist_for_var, we match on phid
2971 : : * only. We don't use equal(), partially for speed but mostly
2972 : : * because phnullingrels might not be exactly equal.
2973 : : */
2974 [ + + ]: 2394 : if (phv->phid != subphv->phid)
2975 : 761 : continue;
2976 : :
2977 : : /* Verify that we kept all the nullingrels machinations straight */
945 2978 [ + + + + : 3266 : if (!(nrm_match == NRM_SUBSET ?
- + ]
2979 : 126 : bms_is_subset(phv->phnullingrels, subphv->phnullingrels) :
2980 : : nrm_match == NRM_SUPERSET ?
2981 : 846 : bms_is_subset(subphv->phnullingrels, phv->phnullingrels) :
2982 : 661 : bms_equal(subphv->phnullingrels, phv->phnullingrels)))
945 tgl@sss.pgh.pa.us 2983 [ # # ]:UBC 0 : elog(ERROR, "wrong phnullingrels %s (expected %s) for PlaceHolderVar %d",
2984 : : bmsToString(phv->phnullingrels),
2985 : : bmsToString(subphv->phnullingrels),
2986 : : phv->phid);
2987 : :
2988 : : /* Found a matching subplan output expression */
1052 tgl@sss.pgh.pa.us 2989 :CBC 1633 : newvar = makeVarFromTargetEntry(newvarno, tle);
2990 : 1633 : newvar->varnosyn = 0; /* wasn't ever a plain Var */
2991 : 1633 : newvar->varattnosyn = 0;
2992 : 1633 : return newvar;
2993 : : }
2994 : : }
2995 : 188 : return NULL; /* no match */
2996 : : }
2997 : :
2998 : : /*
2999 : : * search_indexed_tlist_for_non_var --- find a non-Var/PHV in an indexed tlist
3000 : : *
3001 : : * If a match is found, return a Var constructed to reference the tlist item.
3002 : : * If no match, return NULL.
3003 : : *
3004 : : * NOTE: it is a waste of time to call this unless itlist->has_non_vars.
3005 : : */
3006 : : static Var *
3205 peter_e@gmx.net 3007 : 18790 : search_indexed_tlist_for_non_var(Expr *node,
3008 : : indexed_tlist *itlist, int newvarno)
3009 : : {
3010 : : TargetEntry *tle;
3011 : :
3012 : : /*
3013 : : * If it's a simple Const, replacing it with a Var is silly, even if there
3014 : : * happens to be an identical Const below; a Var is more expensive to
3015 : : * execute than a Const. What's more, replacing it could confuse some
3016 : : * places in the executor that expect to see simple Consts for, eg,
3017 : : * dropped columns.
3018 : : */
3332 tgl@sss.pgh.pa.us 3019 [ + + ]: 18790 : if (IsA(node, Const))
3020 : 969 : return NULL;
3021 : :
7495 3022 : 17821 : tle = tlist_member(node, itlist->tlist);
3023 [ + + ]: 17821 : if (tle)
3024 : : {
3025 : : /* Found a matching subplan output expression */
3026 : : Var *newvar;
3027 : :
5591 peter_e@gmx.net 3028 : 4635 : newvar = makeVarFromTargetEntry(newvarno, tle);
2169 tgl@sss.pgh.pa.us 3029 : 4635 : newvar->varnosyn = 0; /* wasn't ever a plain Var */
3030 : 4635 : newvar->varattnosyn = 0;
7495 3031 : 4635 : return newvar;
3032 : : }
3033 : 13186 : return NULL; /* no match */
3034 : : }
3035 : :
3036 : : /*
3037 : : * search_indexed_tlist_for_sortgroupref --- find a sort/group expression
3038 : : *
3039 : : * If a match is found, return a Var constructed to reference the tlist item.
3040 : : * If no match, return NULL.
3041 : : *
3042 : : * This is needed to ensure that we select the right subplan TLE in cases
3043 : : * where there are multiple textually-equal()-but-volatile sort expressions.
3044 : : * And it's also faster than search_indexed_tlist_for_non_var.
3045 : : */
3046 : : static Var *
3205 peter_e@gmx.net 3047 : 19806 : search_indexed_tlist_for_sortgroupref(Expr *node,
3048 : : Index sortgroupref,
3049 : : indexed_tlist *itlist,
3050 : : int newvarno)
3051 : : {
3052 : : ListCell *lc;
3053 : :
5875 tgl@sss.pgh.pa.us 3054 [ + + + + : 89616 : foreach(lc, itlist->tlist)
+ + ]
3055 : : {
3056 : 78530 : TargetEntry *tle = (TargetEntry *) lfirst(lc);
3057 : :
3058 : : /*
3059 : : * Usually the equal() check is redundant, but in setop plans it may
3060 : : * not be, since prepunion.c assigns ressortgroupref equal to the
3061 : : * column resno without regard to whether that matches the topmost
3062 : : * level's sortgrouprefs and without regard to whether any implicit
3063 : : * coercions are added in the setop tree. We might have to clean that
3064 : : * up someday; but for now, just ignore any false matches.
3065 : : */
3066 [ + + + + ]: 87316 : if (tle->ressortgroupref == sortgroupref &&
3067 : 8786 : equal(node, tle->expr))
3068 : : {
3069 : : /* Found a matching subplan output expression */
3070 : : Var *newvar;
3071 : :
5591 peter_e@gmx.net 3072 : 8720 : newvar = makeVarFromTargetEntry(newvarno, tle);
2169 tgl@sss.pgh.pa.us 3073 : 8720 : newvar->varnosyn = 0; /* wasn't ever a plain Var */
3074 : 8720 : newvar->varattnosyn = 0;
5875 3075 : 8720 : return newvar;
3076 : : }
3077 : : }
3078 : 11086 : return NULL; /* no match */
3079 : : }
3080 : :
3081 : : /*
3082 : : * fix_join_expr
3083 : : * Create a new set of targetlist entries or join qual clauses by
3084 : : * changing the varno/varattno values of variables in the clauses
3085 : : * to reference target list values from the outer and inner join
3086 : : * relation target lists. Also perform opcode lookup and add
3087 : : * regclass OIDs to root->glob->relationOids.
3088 : : *
3089 : : * This is used in four different scenarios:
3090 : : * 1) a normal join clause, where all the Vars in the clause *must* be
3091 : : * replaced by OUTER_VAR or INNER_VAR references. In this case
3092 : : * acceptable_rel should be zero so that any failure to match a Var will be
3093 : : * reported as an error.
3094 : : * 2) RETURNING clauses, which may contain both Vars of the target relation
3095 : : * and Vars of other relations. In this case we want to replace the
3096 : : * other-relation Vars by OUTER_VAR references, while leaving target Vars
3097 : : * alone. Thus inner_itlist = NULL and acceptable_rel = the ID of the
3098 : : * target relation should be passed.
3099 : : * 3) ON CONFLICT UPDATE SET/WHERE clauses. Here references to EXCLUDED are
3100 : : * to be replaced with INNER_VAR references, while leaving target Vars (the
3101 : : * to-be-updated relation) alone. Correspondingly inner_itlist is to be
3102 : : * EXCLUDED elements, outer_itlist = NULL and acceptable_rel the target
3103 : : * relation.
3104 : : * 4) MERGE. In this case, references to the source relation are to be
3105 : : * replaced with INNER_VAR references, leaving Vars of the target
3106 : : * relation (the to-be-modified relation) alone. So inner_itlist is to be
3107 : : * the source relation elements, outer_itlist = NULL and acceptable_rel
3108 : : * the target relation.
3109 : : *
3110 : : * 'clauses' is the targetlist or list of join clauses
3111 : : * 'outer_itlist' is the indexed target list of the outer join relation,
3112 : : * or NULL
3113 : : * 'inner_itlist' is the indexed target list of the inner join relation,
3114 : : * or NULL
3115 : : * 'acceptable_rel' is either zero or the rangetable index of a relation
3116 : : * whose Vars may appear in the clause without provoking an error
3117 : : * 'rtoffset': how much to increment varnos by
3118 : : * 'nrm_match': as for search_indexed_tlist_for_var()
3119 : : * 'num_exec': estimated number of executions of expression
3120 : : *
3121 : : * Returns the new expression tree. The original clause structure is
3122 : : * not modified.
3123 : : */
3124 : : static List *
5219 3125 : 243568 : fix_join_expr(PlannerInfo *root,
3126 : : List *clauses,
3127 : : indexed_tlist *outer_itlist,
3128 : : indexed_tlist *inner_itlist,
3129 : : Index acceptable_rel,
3130 : : int rtoffset,
3131 : : NullingRelsMatch nrm_match,
3132 : : double num_exec)
3133 : : {
3134 : : fix_join_expr_context context;
3135 : :
3136 : 243568 : context.root = root;
7495 3137 : 243568 : context.outer_itlist = outer_itlist;
3138 : 243568 : context.inner_itlist = inner_itlist;
9614 3139 : 243568 : context.acceptable_rel = acceptable_rel;
6873 3140 : 243568 : context.rtoffset = rtoffset;
1052 3141 : 243568 : context.nrm_match = nrm_match;
1907 3142 : 243568 : context.num_exec = num_exec;
6873 3143 : 243568 : return (List *) fix_join_expr_mutator((Node *) clauses, &context);
3144 : : }
3145 : :
3146 : : static Node *
6607 bruce@momjian.us 3147 : 1535428 : fix_join_expr_mutator(Node *node, fix_join_expr_context *context)
3148 : : {
3149 : : Var *newvar;
3150 : :
9627 tgl@sss.pgh.pa.us 3151 [ + + ]: 1535428 : if (node == NULL)
3152 : 152815 : return NULL;
3153 [ + + ]: 1382613 : if (IsA(node, Var))
3154 : : {
3155 : 501724 : Var *var = (Var *) node;
3156 : :
3157 : : /*
3158 : : * Verify that Vars with non-default varreturningtype only appear in
3159 : : * the RETURNING list, and refer to the target relation.
3160 : : */
335 dean.a.rasheed@gmail 3161 [ + + ]: 501724 : if (var->varreturningtype != VAR_RETURNING_DEFAULT)
3162 : : {
3163 [ + - ]: 1353 : if (context->inner_itlist != NULL ||
3164 [ + - ]: 1353 : context->outer_itlist == NULL ||
3165 [ - + ]: 1353 : context->acceptable_rel == 0)
335 dean.a.rasheed@gmail 3166 [ # # ]:UBC 0 : elog(ERROR, "variable returning old/new found outside RETURNING list");
335 dean.a.rasheed@gmail 3167 [ - + ]:CBC 1353 : if (var->varno != context->acceptable_rel)
335 dean.a.rasheed@gmail 3168 [ # # ]:UBC 0 : elog(ERROR, "wrong varno %d (expected %d) for variable returning old/new",
3169 : : var->varno, context->acceptable_rel);
3170 : : }
3171 : :
3172 : : /* Look for the var in the input tlists, first in the outer */
3876 andres@anarazel.de 3173 [ + + ]:CBC 501724 : if (context->outer_itlist)
3174 : : {
3175 : 498138 : newvar = search_indexed_tlist_for_var(var,
3176 : : context->outer_itlist,
3177 : : OUTER_VAR,
3178 : : context->rtoffset,
3179 : : context->nrm_match);
3180 [ + + ]: 498138 : if (newvar)
3181 : 317859 : return (Node *) newvar;
3182 : : }
3183 : :
3184 : : /* then in the inner. */
7495 tgl@sss.pgh.pa.us 3185 [ + + ]: 183865 : if (context->inner_itlist)
3186 : : {
3187 : 178441 : newvar = search_indexed_tlist_for_var(var,
3188 : : context->inner_itlist,
3189 : : INNER_VAR,
3190 : : context->rtoffset,
3191 : : context->nrm_match);
3192 [ + + ]: 178441 : if (newvar)
3193 : 176770 : return (Node *) newvar;
3194 : : }
3195 : :
3196 : : /* If it's for acceptable_rel, adjust and return it */
8429 3197 [ + - ]: 7095 : if (var->varno == context->acceptable_rel)
3198 : : {
6806 3199 : 7095 : var = copyVar(var);
4984 3200 : 7095 : var->varno += context->rtoffset;
2169 3201 [ + + ]: 7095 : if (var->varnosyn > 0)
3202 : 6758 : var->varnosyn += context->rtoffset;
6873 3203 : 7095 : return (Node *) var;
3204 : : }
3205 : :
3206 : : /* No referent found for Var */
8181 tgl@sss.pgh.pa.us 3207 [ # # ]:UBC 0 : elog(ERROR, "variable not found in subplan target lists");
3208 : : }
6266 tgl@sss.pgh.pa.us 3209 [ + + ]:CBC 880889 : if (IsA(node, PlaceHolderVar))
3210 : : {
3211 : 1382 : PlaceHolderVar *phv = (PlaceHolderVar *) node;
3212 : :
3213 : : /* See if the PlaceHolderVar has bubbled up from a lower plan node */
3876 andres@anarazel.de 3214 [ + + + + ]: 1382 : if (context->outer_itlist && context->outer_itlist->has_ph_vars)
3215 : : {
1052 tgl@sss.pgh.pa.us 3216 : 522 : newvar = search_indexed_tlist_for_phv(phv,
3217 : : context->outer_itlist,
3218 : : OUTER_VAR,
3219 : : context->nrm_match);
6266 3220 [ + + ]: 522 : if (newvar)
3221 : 364 : return (Node *) newvar;
3222 : : }
3223 [ + - + + ]: 1018 : if (context->inner_itlist && context->inner_itlist->has_ph_vars)
3224 : : {
1052 3225 : 820 : newvar = search_indexed_tlist_for_phv(phv,
3226 : : context->inner_itlist,
3227 : : INNER_VAR,
3228 : : context->nrm_match);
6266 3229 [ + + ]: 820 : if (newvar)
3230 : 790 : return (Node *) newvar;
3231 : : }
3232 : :
3233 : : /* If not supplied by input plans, evaluate the contained expr */
3234 : : /* XXX can we assert something about phnullingrels? */
3235 : 228 : return fix_join_expr_mutator((Node *) phv->phexpr, context);
3236 : : }
3237 : : /* Try matching more complex expressions too, if tlists have any */
2665 efujita@postgresql.o 3238 [ + + + + ]: 879507 : if (context->outer_itlist && context->outer_itlist->has_non_vars)
3239 : : {
3205 peter_e@gmx.net 3240 : 741 : newvar = search_indexed_tlist_for_non_var((Expr *) node,
3241 : : context->outer_itlist,
3242 : : OUTER_VAR);
7495 tgl@sss.pgh.pa.us 3243 [ + + ]: 741 : if (newvar)
8367 3244 : 62 : return (Node *) newvar;
3245 : : }
2665 efujita@postgresql.o 3246 [ + + + + ]: 879445 : if (context->inner_itlist && context->inner_itlist->has_non_vars)
3247 : : {
3205 peter_e@gmx.net 3248 : 3229 : newvar = search_indexed_tlist_for_non_var((Expr *) node,
3249 : : context->inner_itlist,
3250 : : INNER_VAR);
7495 tgl@sss.pgh.pa.us 3251 [ + + ]: 3229 : if (newvar)
8367 3252 : 590 : return (Node *) newvar;
3253 : : }
3254 : : /* Special cases (apply only AFTER failing to match to lower tlist) */
2562 3255 [ + + ]: 878855 : if (IsA(node, Param))
3256 : 2997 : return fix_param_node(context->root, (Param *) node);
1907 3257 [ + + ]: 875858 : if (IsA(node, AlternativeSubPlan))
3258 : 756 : return fix_join_expr_mutator(fix_alternative_subplan(context->root,
3259 : : (AlternativeSubPlan *) node,
3260 : : context->num_exec),
3261 : : context);
5219 3262 : 875102 : fix_expr_common(context->root, node);
384 peter@eisentraut.org 3263 : 875102 : return expression_tree_mutator(node, fix_join_expr_mutator, context);
3264 : : }
3265 : :
3266 : : /*
3267 : : * fix_upper_expr
3268 : : * Modifies an expression tree so that all Var nodes reference outputs
3269 : : * of a subplan. Also looks for Aggref nodes that should be replaced
3270 : : * by initplan output Params. Also performs opcode lookup, and adds
3271 : : * regclass OIDs to root->glob->relationOids.
3272 : : *
3273 : : * This is used to fix up target and qual expressions of non-join upper-level
3274 : : * plan nodes, as well as index-only scan nodes.
3275 : : *
3276 : : * An error is raised if no matching var can be found in the subplan tlist
3277 : : * --- so this routine should only be applied to nodes whose subplans'
3278 : : * targetlists were generated by flattening the expressions used in the
3279 : : * parent node.
3280 : : *
3281 : : * If itlist->has_non_vars is true, then we try to match whole subexpressions
3282 : : * against elements of the subplan tlist, so that we can avoid recomputing
3283 : : * expressions that were already computed by the subplan. (This is relatively
3284 : : * expensive, so we don't want to try it in the common case where the
3285 : : * subplan tlist is just a flattened list of Vars.)
3286 : : *
3287 : : * 'node': the tree to be fixed (a target item or qual)
3288 : : * 'subplan_itlist': indexed target list for subplan (or index)
3289 : : * 'newvarno': varno to use for Vars referencing tlist elements
3290 : : * 'rtoffset': how much to increment varnos by
3291 : : * 'nrm_match': as for search_indexed_tlist_for_var()
3292 : : * 'num_exec': estimated number of executions of expression
3293 : : *
3294 : : * The resulting tree is a copy of the original in which all Var nodes have
3295 : : * varno = newvarno, varattno = resno of corresponding targetlist element.
3296 : : * The original tree is not modified.
3297 : : */
3298 : : static Node *
5219 tgl@sss.pgh.pa.us 3299 : 184715 : fix_upper_expr(PlannerInfo *root,
3300 : : Node *node,
3301 : : indexed_tlist *subplan_itlist,
3302 : : int newvarno,
3303 : : int rtoffset,
3304 : : NullingRelsMatch nrm_match,
3305 : : double num_exec)
3306 : : {
3307 : : fix_upper_expr_context context;
3308 : :
3309 : 184715 : context.root = root;
7495 3310 : 184715 : context.subplan_itlist = subplan_itlist;
5181 3311 : 184715 : context.newvarno = newvarno;
6873 3312 : 184715 : context.rtoffset = rtoffset;
1052 3313 : 184715 : context.nrm_match = nrm_match;
1907 3314 : 184715 : context.num_exec = num_exec;
6873 3315 : 184715 : return fix_upper_expr_mutator(node, &context);
3316 : : }
3317 : :
3318 : : static Node *
6607 bruce@momjian.us 3319 : 522266 : fix_upper_expr_mutator(Node *node, fix_upper_expr_context *context)
3320 : : {
3321 : : Var *newvar;
3322 : :
9627 tgl@sss.pgh.pa.us 3323 [ + + ]: 522266 : if (node == NULL)
9614 3324 : 167862 : return NULL;
9627 3325 [ + + ]: 354404 : if (IsA(node, Var))
3326 : : {
3327 : 116767 : Var *var = (Var *) node;
3328 : :
7495 3329 : 116767 : newvar = search_indexed_tlist_for_var(var,
3330 : : context->subplan_itlist,
3331 : : context->newvarno,
3332 : : context->rtoffset,
3333 : : context->nrm_match);
3334 [ - + ]: 116767 : if (!newvar)
8181 tgl@sss.pgh.pa.us 3335 [ # # ]:UBC 0 : elog(ERROR, "variable not found in subplan target list");
9614 tgl@sss.pgh.pa.us 3336 :CBC 116767 : return (Node *) newvar;
3337 : : }
6266 3338 [ + + ]: 237637 : if (IsA(node, PlaceHolderVar))
3339 : : {
3340 : 548 : PlaceHolderVar *phv = (PlaceHolderVar *) node;
3341 : :
3342 : : /* See if the PlaceHolderVar has bubbled up from a lower plan node */
3343 [ + + ]: 548 : if (context->subplan_itlist->has_ph_vars)
3344 : : {
1052 3345 : 479 : newvar = search_indexed_tlist_for_phv(phv,
3346 : : context->subplan_itlist,
3347 : : context->newvarno,
3348 : : context->nrm_match);
6266 3349 [ + - ]: 479 : if (newvar)
3350 : 479 : return (Node *) newvar;
3351 : : }
3352 : : /* If not supplied by input plan, evaluate the contained expr */
3353 : : /* XXX can we assert something about phnullingrels? */
3354 : 69 : return fix_upper_expr_mutator((Node *) phv->phexpr, context);
3355 : : }
3356 : : /* Try matching more complex expressions too, if tlist has any */
2562 3357 [ + + ]: 237089 : if (context->subplan_itlist->has_non_vars)
3358 : : {
3359 : 14730 : newvar = search_indexed_tlist_for_non_var((Expr *) node,
3360 : : context->subplan_itlist,
3361 : : context->newvarno);
3362 [ + + ]: 14730 : if (newvar)
3363 : 3893 : return (Node *) newvar;
3364 : : }
3365 : : /* Special cases (apply only AFTER failing to match to lower tlist) */
4200 3366 [ + + ]: 233196 : if (IsA(node, Param))
3367 : 4873 : return fix_param_node(context->root, (Param *) node);
3572 3368 [ + + ]: 228323 : if (IsA(node, Aggref))
3369 : : {
3370 : 26074 : Aggref *aggref = (Aggref *) node;
3371 : : Param *aggparam;
3372 : :
3373 : : /* See if the Aggref should be replaced by a Param */
888 3374 : 26074 : aggparam = find_minmax_agg_replacement_param(context->root, aggref);
3375 [ - + ]: 26074 : if (aggparam != NULL)
3376 : : {
3377 : : /* Make a copy of the Param for paranoia's sake */
888 tgl@sss.pgh.pa.us 3378 :UBC 0 : return (Node *) copyObject(aggparam);
3379 : : }
3380 : : /* If no match, just fall through to process it normally */
3381 : : }
1907 tgl@sss.pgh.pa.us 3382 [ + + ]:CBC 228323 : if (IsA(node, AlternativeSubPlan))
3383 : 18 : return fix_upper_expr_mutator(fix_alternative_subplan(context->root,
3384 : : (AlternativeSubPlan *) node,
3385 : : context->num_exec),
3386 : : context);
5219 3387 : 228305 : fix_expr_common(context->root, node);
384 peter@eisentraut.org 3388 : 228305 : return expression_tree_mutator(node, fix_upper_expr_mutator, context);
3389 : : }
3390 : :
3391 : : /*
3392 : : * set_returning_clause_references
3393 : : * Perform setrefs.c's work on a RETURNING targetlist
3394 : : *
3395 : : * If the query involves more than just the result table, we have to
3396 : : * adjust any Vars that refer to other tables to reference junk tlist
3397 : : * entries in the top subplan's targetlist. Vars referencing the result
3398 : : * table should be left alone, however (the executor will evaluate them
3399 : : * using the actual heap tuple, after firing triggers if any). In the
3400 : : * adjusted RETURNING list, result-table Vars will have their original
3401 : : * varno (plus rtoffset), but Vars for other rels will have varno OUTER_VAR.
3402 : : *
3403 : : * We also must perform opcode lookup and add regclass OIDs to
3404 : : * root->glob->relationOids.
3405 : : *
3406 : : * 'rlist': the RETURNING targetlist to be fixed
3407 : : * 'topplan': the top subplan node that will be just below the ModifyTable
3408 : : * node (note it's not yet passed through set_plan_refs)
3409 : : * 'resultRelation': RT index of the associated result relation
3410 : : * 'rtoffset': how much to increment varnos by
3411 : : *
3412 : : * Note: the given 'root' is for the parent query level, not the 'topplan'.
3413 : : * This does not matter currently since we only access the dependency-item
3414 : : * lists in root->glob, but it would need some hacking if we wanted a root
3415 : : * that actually matches the subplan.
3416 : : *
3417 : : * Note: resultRelation is not yet adjusted by rtoffset.
3418 : : */
3419 : : static List *
5219 tgl@sss.pgh.pa.us 3420 : 1685 : set_returning_clause_references(PlannerInfo *root,
3421 : : List *rlist,
3422 : : Plan *topplan,
3423 : : Index resultRelation,
3424 : : int rtoffset)
3425 : : {
3426 : : indexed_tlist *itlist;
3427 : :
3428 : : /*
3429 : : * We can perform the desired Var fixup by abusing the fix_join_expr
3430 : : * machinery that formerly handled inner indexscan fixup. We search the
3431 : : * top plan's targetlist for Vars of non-result relations, and use
3432 : : * fix_join_expr to convert RETURNING Vars into references to those tlist
3433 : : * entries, while leaving result-rel Vars as-is.
3434 : : *
3435 : : * PlaceHolderVars will also be sought in the targetlist, but no
3436 : : * more-complex expressions will be. Note that it is not possible for a
3437 : : * PlaceHolderVar to refer to the result relation, since the result is
3438 : : * never below an outer join. If that case could happen, we'd have to be
3439 : : * prepared to pick apart the PlaceHolderVar and evaluate its contained
3440 : : * expression instead.
3441 : : */
7067 3442 : 1685 : itlist = build_tlist_index_other_vars(topplan->targetlist, resultRelation);
3443 : :
5219 3444 : 1685 : rlist = fix_join_expr(root,
3445 : : rlist,
3446 : : itlist,
3447 : : NULL,
3448 : : resultRelation,
3449 : : rtoffset,
3450 : : NRM_EQUAL,
3451 : : NUM_EXEC_TLIST(topplan));
3452 : :
7067 3453 : 1685 : pfree(itlist);
3454 : :
3455 : 1685 : return rlist;
3456 : : }
3457 : :
3458 : : /*
3459 : : * fix_windowagg_condition_expr_mutator
3460 : : * Mutator function for replacing WindowFuncs with the corresponding Var
3461 : : * in the targetlist which references that WindowFunc.
3462 : : */
3463 : : static Node *
1349 drowley@postgresql.o 3464 : 1741 : fix_windowagg_condition_expr_mutator(Node *node,
3465 : : fix_windowagg_cond_context *context)
3466 : : {
3467 [ + + ]: 1741 : if (node == NULL)
3468 : 1297 : return NULL;
3469 : :
3470 [ + + ]: 444 : if (IsA(node, WindowFunc))
3471 : : {
3472 : : Var *newvar;
3473 : :
3474 : 90 : newvar = search_indexed_tlist_for_non_var((Expr *) node,
3475 : : context->subplan_itlist,
3476 : : context->newvarno);
3477 [ + - ]: 90 : if (newvar)
3478 : 90 : return (Node *) newvar;
1349 drowley@postgresql.o 3479 [ # # ]:UBC 0 : elog(ERROR, "WindowFunc not found in subplan target lists");
3480 : : }
3481 : :
1349 drowley@postgresql.o 3482 :CBC 354 : return expression_tree_mutator(node,
3483 : : fix_windowagg_condition_expr_mutator,
3484 : : context);
3485 : : }
3486 : :
3487 : : /*
3488 : : * fix_windowagg_condition_expr
3489 : : * Converts references in 'runcondition' so that any WindowFunc
3490 : : * references are swapped out for a Var which references the matching
3491 : : * WindowFunc in 'subplan_itlist'.
3492 : : */
3493 : : static List *
3494 : 1381 : fix_windowagg_condition_expr(PlannerInfo *root,
3495 : : List *runcondition,
3496 : : indexed_tlist *subplan_itlist)
3497 : : {
3498 : : fix_windowagg_cond_context context;
3499 : :
3500 : 1381 : context.root = root;
3501 : 1381 : context.subplan_itlist = subplan_itlist;
3502 : 1381 : context.newvarno = 0;
3503 : :
3504 : 1381 : return (List *) fix_windowagg_condition_expr_mutator((Node *) runcondition,
3505 : : &context);
3506 : : }
3507 : :
3508 : : /*
3509 : : * set_windowagg_runcondition_references
3510 : : * Converts references in 'runcondition' so that any WindowFunc
3511 : : * references are swapped out for a Var which references the matching
3512 : : * WindowFunc in 'plan' targetlist.
3513 : : */
3514 : : static List *
3515 : 1381 : set_windowagg_runcondition_references(PlannerInfo *root,
3516 : : List *runcondition,
3517 : : Plan *plan)
3518 : : {
3519 : : List *newlist;
3520 : : indexed_tlist *itlist;
3521 : :
3522 : 1381 : itlist = build_tlist_index(plan->targetlist);
3523 : :
3524 : 1381 : newlist = fix_windowagg_condition_expr(root, runcondition, itlist);
3525 : :
3526 : 1381 : pfree(itlist);
3527 : :
3528 : 1381 : return newlist;
3529 : : }
3530 : :
3531 : : /*
3532 : : * find_minmax_agg_replacement_param
3533 : : * If the given Aggref is one that we are optimizing into a subquery
3534 : : * (cf. planagg.c), then return the Param that should replace it.
3535 : : * Else return NULL.
3536 : : *
3537 : : * This is exported so that SS_finalize_plan can use it before setrefs.c runs.
3538 : : * Note that it will not find anything until we have built a Plan from a
3539 : : * MinMaxAggPath, as root->minmax_aggs will never be filled otherwise.
3540 : : */
3541 : : Param *
888 tgl@sss.pgh.pa.us 3542 : 37023 : find_minmax_agg_replacement_param(PlannerInfo *root, Aggref *aggref)
3543 : : {
3544 [ + + + - ]: 37519 : if (root->minmax_aggs != NIL &&
3545 : 496 : list_length(aggref->args) == 1)
3546 : : {
3547 : 496 : TargetEntry *curTarget = (TargetEntry *) linitial(aggref->args);
3548 : : ListCell *lc;
3549 : :
3550 [ + - + - : 544 : foreach(lc, root->minmax_aggs)
+ - ]
3551 : : {
3552 : 544 : MinMaxAggInfo *mminfo = (MinMaxAggInfo *) lfirst(lc);
3553 : :
3554 [ + + + - ]: 1040 : if (mminfo->aggfnoid == aggref->aggfnoid &&
3555 : 496 : equal(mminfo->target, curTarget->expr))
3556 : 496 : return mminfo->param;
3557 : : }
3558 : : }
3559 : 36527 : return NULL;
3560 : : }
3561 : :
3562 : :
3563 : : /*****************************************************************************
3564 : : * QUERY DEPENDENCY MANAGEMENT
3565 : : *****************************************************************************/
3566 : :
3567 : : /*
3568 : : * record_plan_function_dependency
3569 : : * Mark the current plan as depending on a particular function.
3570 : : *
3571 : : * This is exported so that the function-inlining code can record a
3572 : : * dependency on a function that it's removed from the plan tree.
3573 : : */
3574 : : void
5219 3575 : 649972 : record_plan_function_dependency(PlannerInfo *root, Oid funcid)
3576 : : {
3577 : : /*
3578 : : * For performance reasons, we don't bother to track built-in functions;
3579 : : * we just assume they'll never change (or at least not in ways that'd
3580 : : * invalidate plans using them). For this purpose we can consider a
3581 : : * built-in function to be one with OID less than FirstUnpinnedObjectId.
3582 : : * Note that the OID generator guarantees never to generate such an OID
3583 : : * after startup, even at OID wraparound.
3584 : : */
1616 3585 [ + + ]: 649972 : if (funcid >= (Oid) FirstUnpinnedObjectId)
3586 : : {
5237 3587 : 21290 : PlanInvalItem *inval_item = makeNode(PlanInvalItem);
3588 : :
3589 : : /*
3590 : : * It would work to use any syscache on pg_proc, but the easiest is
3591 : : * PROCOID since we already have the function's OID at hand. Note
3592 : : * that plancache.c knows we use PROCOID.
3593 : : */
6308 3594 : 21290 : inval_item->cacheId = PROCOID;
5033 3595 : 21290 : inval_item->hashValue = GetSysCacheHashValue1(PROCOID,
3596 : : ObjectIdGetDatum(funcid));
3597 : :
5219 3598 : 21290 : root->glob->invalItems = lappend(root->glob->invalItems, inval_item);
3599 : : }
6308 3600 : 649972 : }
3601 : :
3602 : : /*
3603 : : * record_plan_type_dependency
3604 : : * Mark the current plan as depending on a particular type.
3605 : : *
3606 : : * This is exported so that eval_const_expressions can record a
3607 : : * dependency on a domain that it's removed a CoerceToDomain node for.
3608 : : *
3609 : : * We don't currently need to record dependencies on domains that the
3610 : : * plan contains CoerceToDomain nodes for, though that might change in
3611 : : * future. Hence, this isn't actually called in this module, though
3612 : : * someday fix_expr_common might call it.
3613 : : */
3614 : : void
2533 3615 : 9269 : record_plan_type_dependency(PlannerInfo *root, Oid typid)
3616 : : {
3617 : : /*
3618 : : * As in record_plan_function_dependency, ignore the possibility that
3619 : : * someone would change a built-in domain.
3620 : : */
1616 3621 [ + - ]: 9269 : if (typid >= (Oid) FirstUnpinnedObjectId)
3622 : : {
2561 3623 : 9269 : PlanInvalItem *inval_item = makeNode(PlanInvalItem);
3624 : :
3625 : : /*
3626 : : * It would work to use any syscache on pg_type, but the easiest is
3627 : : * TYPEOID since we already have the type's OID at hand. Note that
3628 : : * plancache.c knows we use TYPEOID.
3629 : : */
3630 : 9269 : inval_item->cacheId = TYPEOID;
3631 : 9269 : inval_item->hashValue = GetSysCacheHashValue1(TYPEOID,
3632 : : ObjectIdGetDatum(typid));
3633 : :
3634 : 9269 : root->glob->invalItems = lappend(root->glob->invalItems, inval_item);
3635 : : }
3636 : 9269 : }
3637 : :
3638 : : /*
3639 : : * extract_query_dependencies
3640 : : * Given a rewritten, but not yet planned, query or queries
3641 : : * (i.e. a Query node or list of Query nodes), extract dependencies
3642 : : * just as set_plan_references would do. Also detect whether any
3643 : : * rewrite steps were affected by RLS.
3644 : : *
3645 : : * This is needed by plancache.c to handle invalidation of cached unplanned
3646 : : * queries.
3647 : : *
3648 : : * Note: this does not go through eval_const_expressions, and hence doesn't
3649 : : * reflect its additions of inlined functions and elided CoerceToDomain nodes
3650 : : * to the invalItems list. This is obviously OK for functions, since we'll
3651 : : * see them in the original query tree anyway. For domains, it's OK because
3652 : : * we don't care about domains unless they get elided. That is, a plan might
3653 : : * have domain dependencies that the query tree doesn't.
3654 : : */
3655 : : void
5815 3656 : 30686 : extract_query_dependencies(Node *query,
3657 : : List **relationOids,
3658 : : List **invalItems,
3659 : : bool *hasRowSecurity)
3660 : : {
3661 : : PlannerGlobal glob;
3662 : : PlannerInfo root;
3663 : :
3664 : : /* Make up dummy planner state so we can use this module's machinery */
6308 3665 [ + - + - : 797836 : MemSet(&glob, 0, sizeof(glob));
+ - + - +
+ ]
3666 : 30686 : glob.type = T_PlannerGlobal;
3667 : 30686 : glob.relationOids = NIL;
3668 : 30686 : glob.invalItems = NIL;
3669 : : /* Hack: we use glob.dependsOnRole to collect hasRowSecurity flags */
3442 3670 : 30686 : glob.dependsOnRole = false;
3671 : :
5219 3672 [ + - + - : 2853798 : MemSet(&root, 0, sizeof(root));
+ - + - +
+ ]
3673 : 30686 : root.type = T_PlannerInfo;
3674 : 30686 : root.glob = &glob;
3675 : :
3676 : 30686 : (void) extract_query_dependencies_walker(query, &root);
3677 : :
6308 3678 : 30686 : *relationOids = glob.relationOids;
3679 : 30686 : *invalItems = glob.invalItems;
3442 3680 : 30686 : *hasRowSecurity = glob.dependsOnRole;
6308 3681 : 30686 : }
3682 : :
3683 : : /*
3684 : : * Tree walker for extract_query_dependencies.
3685 : : *
3686 : : * This is exported so that expression_planner_with_deps can call it on
3687 : : * simple expressions (post-planning, not before planning, in that case).
3688 : : * In that usage, glob.dependsOnRole isn't meaningful, but the relationOids
3689 : : * and invalItems lists are added to as needed.
3690 : : */
3691 : : bool
5219 3692 : 834815 : extract_query_dependencies_walker(Node *node, PlannerInfo *context)
3693 : : {
6308 3694 [ + + ]: 834815 : if (node == NULL)
3695 : 395121 : return false;
6266 3696 [ - + ]: 439694 : Assert(!IsA(node, PlaceHolderVar));
6308 3697 [ + + ]: 439694 : if (IsA(node, Query))
3698 : : {
3699 : 33130 : Query *query = (Query *) node;
3700 : : ListCell *lc;
3701 : :
4921 3702 [ + + ]: 33130 : if (query->commandType == CMD_UTILITY)
3703 : : {
3704 : : /*
3705 : : * This logic must handle any utility command for which parse
3706 : : * analysis was nontrivial (cf. stmt_requires_parse_analysis).
3707 : : *
3708 : : * Notably, CALL requires its own processing.
3709 : : */
814 3710 [ + + ]: 4976 : if (IsA(query->utilityStmt, CallStmt))
3711 : : {
3712 : 58 : CallStmt *callstmt = (CallStmt *) query->utilityStmt;
3713 : :
3714 : : /* We need not examine funccall, just the transformed exprs */
3715 : 58 : (void) extract_query_dependencies_walker((Node *) callstmt->funcexpr,
3716 : : context);
3717 : 58 : (void) extract_query_dependencies_walker((Node *) callstmt->outargs,
3718 : : context);
3719 : 58 : return false;
3720 : : }
3721 : :
3722 : : /*
3723 : : * Ignore other utility statements, except those (such as EXPLAIN)
3724 : : * that contain a parsed-but-not-planned query. For those, we
3725 : : * just need to transfer our attention to the contained query.
3726 : : */
5021 3727 : 4918 : query = UtilityContainsQuery(query->utilityStmt);
3728 [ + + ]: 4918 : if (query == NULL)
5815 3729 : 18 : return false;
3730 : : }
3731 : :
3732 : : /* Remember if any Query has RLS quals applied by rewriter */
3442 3733 [ + + ]: 33054 : if (query->hasRowSecurity)
3734 : 112 : context->glob->dependsOnRole = true;
3735 : :
3736 : : /* Collect relation OIDs in this Query's rtable */
6308 3737 [ + + + + : 52539 : foreach(lc, query->rtable)
+ + ]
3738 : : {
3739 : 19485 : RangeTblEntry *rte = (RangeTblEntry *) lfirst(lc);
3740 : :
1064 3741 [ + + ]: 19485 : if (rte->rtekind == RTE_RELATION ||
3742 [ + + + + ]: 3843 : (rte->rtekind == RTE_SUBQUERY && OidIsValid(rte->relid)) ||
3743 [ + + + - ]: 3473 : (rte->rtekind == RTE_NAMEDTUPLESTORE && OidIsValid(rte->relid)))
5219 3744 : 16249 : context->glob->relationOids =
3745 : 16249 : lappend_oid(context->glob->relationOids, rte->relid);
3746 : : }
3747 : :
3748 : : /* And recurse into the query's subexpressions */
6308 3749 : 33054 : return query_tree_walker(query, extract_query_dependencies_walker,
3750 : : context, 0);
3751 : : }
3752 : : /* Extract function dependencies and check for regclass Consts */
2561 3753 : 406564 : fix_expr_common(context, node);
6308 3754 : 406564 : return expression_tree_walker(node, extract_query_dependencies_walker,
3755 : : context);
3756 : : }
|