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