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