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