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