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