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