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