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