PostgreSQL Source Code  git master
setrefs.c
Go to the documentation of this file.
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-2020, 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/tlist.h"
27 #include "tcop/utility.h"
28 #include "utils/lsyscache.h"
29 #include "utils/syscache.h"
30 
31 
32 typedef struct
33 {
34  Index varno; /* RT index of Var */
35  AttrNumber varattno; /* attr number of Var */
36  AttrNumber resno; /* TLE position of Var */
37 } tlist_vinfo;
38 
39 typedef struct
40 {
41  List *tlist; /* underlying target list */
42  int num_vars; /* number of plain Var tlist entries */
43  bool has_ph_vars; /* are there PlaceHolderVar entries? */
44  bool has_non_vars; /* are there other entries? */
45  tlist_vinfo vars[FLEXIBLE_ARRAY_MEMBER]; /* has num_vars entries */
47 
48 typedef struct
49 {
51  int rtoffset;
52  double num_exec;
54 
55 typedef struct
56 {
61  int rtoffset;
62  double num_exec;
64 
65 typedef struct
66 {
70  int rtoffset;
71  double num_exec;
73 
74 /*
75  * Selecting the best alternative in an AlternativeSubPlan expression requires
76  * estimating how many times that expression will be evaluated. For an
77  * expression in a plan node's targetlist, the plan's estimated number of
78  * output rows is clearly what to use, but for an expression in a qual it's
79  * far less clear. Since AlternativeSubPlans aren't heavily used, we don't
80  * want to expend a lot of cycles making such estimates. What we use is twice
81  * the number of output rows. That's not entirely unfounded: we know that
82  * clause_selectivity() would fall back to a default selectivity estimate
83  * of 0.5 for any SubPlan, so if the qual containing the SubPlan is the last
84  * to be applied (which it likely would be, thanks to order_qual_clauses()),
85  * this matches what we could have estimated in a far more laborious fashion.
86  * Obviously there are many other scenarios, but it's probably not worth the
87  * trouble to try to improve on this estimate, especially not when we don't
88  * have a better estimate for the selectivity of the SubPlan qual itself.
89  */
90 #define NUM_EXEC_TLIST(parentplan) ((parentplan)->plan_rows)
91 #define NUM_EXEC_QUAL(parentplan) ((parentplan)->plan_rows * 2.0)
92 
93 /*
94  * Check if a Const node is a regclass value. We accept plain OID too,
95  * since a regclass Const will get folded to that type if it's an argument
96  * to oideq or similar operators. (This might result in some extraneous
97  * values in a plan's list of relation dependencies, but the worst result
98  * would be occasional useless replans.)
99  */
100 #define ISREGCLASSCONST(con) \
101  (((con)->consttype == REGCLASSOID || (con)->consttype == OIDOID) && \
102  !(con)->constisnull)
103 
104 #define fix_scan_list(root, lst, rtoffset, num_exec) \
105  ((List *) fix_scan_expr(root, (Node *) (lst), rtoffset, num_exec))
106 
107 static void add_rtes_to_flat_rtable(PlannerInfo *root, bool recursing);
108 static void flatten_unplanned_rtes(PlannerGlobal *glob, RangeTblEntry *rte);
109 static bool flatten_rtes_walker(Node *node, PlannerGlobal *glob);
110 static void add_rte_to_flat_rtable(PlannerGlobal *glob, RangeTblEntry *rte);
111 static Plan *set_plan_refs(PlannerInfo *root, Plan *plan, int rtoffset);
113  IndexOnlyScan *plan,
114  int rtoffset);
116  SubqueryScan *plan,
117  int rtoffset);
118 static bool trivial_subqueryscan(SubqueryScan *plan);
119 static Plan *clean_up_removed_plan_level(Plan *parent, Plan *child);
120 static void set_foreignscan_references(PlannerInfo *root,
121  ForeignScan *fscan,
122  int rtoffset);
123 static void set_customscan_references(PlannerInfo *root,
124  CustomScan *cscan,
125  int rtoffset);
127  Append *aplan,
128  int rtoffset);
130  MergeAppend *mplan,
131  int rtoffset);
132 static void set_hash_references(PlannerInfo *root, Plan *plan, int rtoffset);
133 static Relids offset_relid_set(Relids relids, int rtoffset);
134 static Node *fix_scan_expr(PlannerInfo *root, Node *node,
135  int rtoffset, double num_exec);
136 static Node *fix_scan_expr_mutator(Node *node, fix_scan_expr_context *context);
137 static bool fix_scan_expr_walker(Node *node, fix_scan_expr_context *context);
138 static void set_join_references(PlannerInfo *root, Join *join, int rtoffset);
139 static void set_upper_references(PlannerInfo *root, Plan *plan, int rtoffset);
140 static void set_param_references(PlannerInfo *root, Plan *plan);
141 static Node *convert_combining_aggrefs(Node *node, void *context);
142 static void set_dummy_tlist_references(Plan *plan, int rtoffset);
143 static indexed_tlist *build_tlist_index(List *tlist);
145  indexed_tlist *itlist,
146  Index newvarno,
147  int rtoffset);
149  indexed_tlist *itlist,
150  Index newvarno);
152  Index sortgroupref,
153  indexed_tlist *itlist,
154  Index newvarno);
155 static List *fix_join_expr(PlannerInfo *root,
156  List *clauses,
157  indexed_tlist *outer_itlist,
158  indexed_tlist *inner_itlist,
159  Index acceptable_rel,
160  int rtoffset, double num_exec);
161 static Node *fix_join_expr_mutator(Node *node,
162  fix_join_expr_context *context);
163 static Node *fix_upper_expr(PlannerInfo *root,
164  Node *node,
165  indexed_tlist *subplan_itlist,
166  Index newvarno,
167  int rtoffset, double num_exec);
168 static Node *fix_upper_expr_mutator(Node *node,
169  fix_upper_expr_context *context);
171  List *rlist,
172  Plan *topplan,
173  Index resultRelation,
174  int rtoffset);
175 
176 
177 /*****************************************************************************
178  *
179  * SUBPLAN REFERENCES
180  *
181  *****************************************************************************/
182 
183 /*
184  * set_plan_references
185  *
186  * This is the final processing pass of the planner/optimizer. The plan
187  * tree is complete; we just have to adjust some representational details
188  * for the convenience of the executor:
189  *
190  * 1. We flatten the various subquery rangetables into a single list, and
191  * zero out RangeTblEntry fields that are not useful to the executor.
192  *
193  * 2. We adjust Vars in scan nodes to be consistent with the flat rangetable.
194  *
195  * 3. We adjust Vars in upper plan nodes to refer to the outputs of their
196  * subplans.
197  *
198  * 4. Aggrefs in Agg plan nodes need to be adjusted in some cases involving
199  * partial aggregation or minmax aggregate optimization.
200  *
201  * 5. PARAM_MULTIEXPR Params are replaced by regular PARAM_EXEC Params,
202  * now that we have finished planning all MULTIEXPR subplans.
203  *
204  * 6. AlternativeSubPlan expressions are replaced by just one of their
205  * alternatives, using an estimate of how many times they'll be executed.
206  *
207  * 7. We compute regproc OIDs for operators (ie, we look up the function
208  * that implements each op).
209  *
210  * 8. We create lists of specific objects that the plan depends on.
211  * This will be used by plancache.c to drive invalidation of cached plans.
212  * Relation dependencies are represented by OIDs, and everything else by
213  * PlanInvalItems (this distinction is motivated by the shared-inval APIs).
214  * Currently, relations, user-defined functions, and domains are the only
215  * types of objects that are explicitly tracked this way.
216  *
217  * 9. We assign every plan node in the tree a unique ID.
218  *
219  * We also perform one final optimization step, which is to delete
220  * SubqueryScan, Append, and MergeAppend plan nodes that aren't doing
221  * anything useful. The reason for doing this last is that
222  * it can't readily be done before set_plan_references, because it would
223  * break set_upper_references: the Vars in the child plan's top tlist
224  * wouldn't match up with the Vars in the outer plan tree. A SubqueryScan
225  * serves a necessary function as a buffer between outer query and subquery
226  * variable numbering ... but after we've flattened the rangetable this is
227  * no longer a problem, since then there's only one rtindex namespace.
228  * Likewise, Append and MergeAppend buffer between the parent and child vars
229  * of an appendrel, but we don't need to worry about that once we've done
230  * set_plan_references.
231  *
232  * set_plan_references recursively traverses the whole plan tree.
233  *
234  * The return value is normally the same Plan node passed in, but can be
235  * different when the passed-in Plan is a node we decide isn't needed.
236  *
237  * The flattened rangetable entries are appended to root->glob->finalrtable.
238  * Also, rowmarks entries are appended to root->glob->finalrowmarks, and the
239  * RT indexes of ModifyTable result relations to root->glob->resultRelations,
240  * and flattened AppendRelInfos are appended to root->glob->appendRelations.
241  * Plan dependencies are appended to root->glob->relationOids (for relations)
242  * and root->glob->invalItems (for everything else).
243  *
244  * Notice that we modify Plan nodes in-place, but use expression_tree_mutator
245  * to process targetlist and qual expressions. We can assume that the Plan
246  * nodes were just built by the planner and are not multiply referenced, but
247  * it's not so safe to assume that for expression tree nodes.
248  */
249 Plan *
251 {
252  PlannerGlobal *glob = root->glob;
253  int rtoffset = list_length(glob->finalrtable);
254  ListCell *lc;
255 
256  /*
257  * Add all the query's RTEs to the flattened rangetable. The live ones
258  * will have their rangetable indexes increased by rtoffset. (Additional
259  * RTEs, not referenced by the Plan tree, might get added after those.)
260  */
261  add_rtes_to_flat_rtable(root, false);
262 
263  /*
264  * Adjust RT indexes of PlanRowMarks and add to final rowmarks list
265  */
266  foreach(lc, root->rowMarks)
267  {
269  PlanRowMark *newrc;
270 
271  /* flat copy is enough since all fields are scalars */
272  newrc = (PlanRowMark *) palloc(sizeof(PlanRowMark));
273  memcpy(newrc, rc, sizeof(PlanRowMark));
274 
275  /* adjust indexes ... but *not* the rowmarkId */
276  newrc->rti += rtoffset;
277  newrc->prti += rtoffset;
278 
279  glob->finalrowmarks = lappend(glob->finalrowmarks, newrc);
280  }
281 
282  /*
283  * Adjust RT indexes of AppendRelInfos and add to final appendrels list.
284  * We assume the AppendRelInfos were built during planning and don't need
285  * to be copied.
286  */
287  foreach(lc, root->append_rel_list)
288  {
289  AppendRelInfo *appinfo = lfirst_node(AppendRelInfo, lc);
290 
291  /* adjust RT indexes */
292  appinfo->parent_relid += rtoffset;
293  appinfo->child_relid += rtoffset;
294 
295  /*
296  * Rather than adjust the translated_vars entries, just drop 'em.
297  * Neither the executor nor EXPLAIN currently need that data.
298  */
299  appinfo->translated_vars = NIL;
300 
301  glob->appendRelations = lappend(glob->appendRelations, appinfo);
302  }
303 
304  /* Now fix the Plan tree */
305  return set_plan_refs(root, plan, rtoffset);
306 }
307 
308 /*
309  * Extract RangeTblEntries from the plan's rangetable, and add to flat rtable
310  *
311  * This can recurse into subquery plans; "recursing" is true if so.
312  */
313 static void
314 add_rtes_to_flat_rtable(PlannerInfo *root, bool recursing)
315 {
316  PlannerGlobal *glob = root->glob;
317  Index rti;
318  ListCell *lc;
319 
320  /*
321  * Add the query's own RTEs to the flattened rangetable.
322  *
323  * At top level, we must add all RTEs so that their indexes in the
324  * flattened rangetable match up with their original indexes. When
325  * recursing, we only care about extracting relation RTEs.
326  */
327  foreach(lc, root->parse->rtable)
328  {
329  RangeTblEntry *rte = (RangeTblEntry *) lfirst(lc);
330 
331  if (!recursing || rte->rtekind == RTE_RELATION)
332  add_rte_to_flat_rtable(glob, rte);
333  }
334 
335  /*
336  * If there are any dead subqueries, they are not referenced in the Plan
337  * tree, so we must add RTEs contained in them to the flattened rtable
338  * separately. (If we failed to do this, the executor would not perform
339  * expected permission checks for tables mentioned in such subqueries.)
340  *
341  * Note: this pass over the rangetable can't be combined with the previous
342  * one, because that would mess up the numbering of the live RTEs in the
343  * flattened rangetable.
344  */
345  rti = 1;
346  foreach(lc, root->parse->rtable)
347  {
348  RangeTblEntry *rte = (RangeTblEntry *) lfirst(lc);
349 
350  /*
351  * We should ignore inheritance-parent RTEs: their contents have been
352  * pulled up into our rangetable already. Also ignore any subquery
353  * RTEs without matching RelOptInfos, as they likewise have been
354  * pulled up.
355  */
356  if (rte->rtekind == RTE_SUBQUERY && !rte->inh &&
357  rti < root->simple_rel_array_size)
358  {
359  RelOptInfo *rel = root->simple_rel_array[rti];
360 
361  if (rel != NULL)
362  {
363  Assert(rel->relid == rti); /* sanity check on array */
364 
365  /*
366  * The subquery might never have been planned at all, if it
367  * was excluded on the basis of self-contradictory constraints
368  * in our query level. In this case apply
369  * flatten_unplanned_rtes.
370  *
371  * If it was planned but the result rel is dummy, we assume
372  * that it has been omitted from our plan tree (see
373  * set_subquery_pathlist), and recurse to pull up its RTEs.
374  *
375  * Otherwise, it should be represented by a SubqueryScan node
376  * somewhere in our plan tree, and we'll pull up its RTEs when
377  * we process that plan node.
378  *
379  * However, if we're recursing, then we should pull up RTEs
380  * whether the subquery is dummy or not, because we've found
381  * that some upper query level is treating this one as dummy,
382  * and so we won't scan this level's plan tree at all.
383  */
384  if (rel->subroot == NULL)
385  flatten_unplanned_rtes(glob, rte);
386  else if (recursing ||
388  UPPERREL_FINAL, NULL)))
389  add_rtes_to_flat_rtable(rel->subroot, true);
390  }
391  }
392  rti++;
393  }
394 }
395 
396 /*
397  * Extract RangeTblEntries from a subquery that was never planned at all
398  */
399 static void
401 {
402  /* Use query_tree_walker to find all RTEs in the parse tree */
403  (void) query_tree_walker(rte->subquery,
405  (void *) glob,
407 }
408 
409 static bool
411 {
412  if (node == NULL)
413  return false;
414  if (IsA(node, RangeTblEntry))
415  {
416  RangeTblEntry *rte = (RangeTblEntry *) node;
417 
418  /* As above, we need only save relation RTEs */
419  if (rte->rtekind == RTE_RELATION)
420  add_rte_to_flat_rtable(glob, rte);
421  return false;
422  }
423  if (IsA(node, Query))
424  {
425  /* Recurse into subselects */
426  return query_tree_walker((Query *) node,
428  (void *) glob,
430  }
432  (void *) glob);
433 }
434 
435 /*
436  * Add (a copy of) the given RTE to the final rangetable
437  *
438  * In the flat rangetable, we zero out substructure pointers that are not
439  * needed by the executor; this reduces the storage space and copying cost
440  * for cached plans. We keep only the ctename, alias and eref Alias fields,
441  * which are needed by EXPLAIN, and the selectedCols, insertedCols and
442  * updatedCols bitmaps, which are needed for executor-startup permissions
443  * checking and for trigger event checking.
444  */
445 static void
447 {
448  RangeTblEntry *newrte;
449 
450  /* flat copy to duplicate all the scalar fields */
451  newrte = (RangeTblEntry *) palloc(sizeof(RangeTblEntry));
452  memcpy(newrte, rte, sizeof(RangeTblEntry));
453 
454  /* zap unneeded sub-structure */
455  newrte->tablesample = NULL;
456  newrte->subquery = NULL;
457  newrte->joinaliasvars = NIL;
458  newrte->joinleftcols = NIL;
459  newrte->joinrightcols = NIL;
460  newrte->functions = NIL;
461  newrte->tablefunc = NULL;
462  newrte->values_lists = NIL;
463  newrte->coltypes = NIL;
464  newrte->coltypmods = NIL;
465  newrte->colcollations = NIL;
466  newrte->securityQuals = NIL;
467 
468  glob->finalrtable = lappend(glob->finalrtable, newrte);
469 
470  /*
471  * Check for RT index overflow; it's very unlikely, but if it did happen,
472  * the executor would get confused by varnos that match the special varno
473  * values.
474  */
476  ereport(ERROR,
477  (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
478  errmsg("too many range table entries")));
479 
480  /*
481  * If it's a plain relation RTE, add the table to relationOids.
482  *
483  * We do this even though the RTE might be unreferenced in the plan tree;
484  * this would correspond to cases such as views that were expanded, child
485  * tables that were eliminated by constraint exclusion, etc. Schema
486  * invalidation on such a rel must still force rebuilding of the plan.
487  *
488  * Note we don't bother to avoid making duplicate list entries. We could,
489  * but it would probably cost more cycles than it would save.
490  */
491  if (newrte->rtekind == RTE_RELATION)
492  glob->relationOids = lappend_oid(glob->relationOids, newrte->relid);
493 }
494 
495 /*
496  * set_plan_refs: recurse through the Plan nodes of a single subquery level
497  */
498 static Plan *
499 set_plan_refs(PlannerInfo *root, Plan *plan, int rtoffset)
500 {
501  ListCell *l;
502 
503  if (plan == NULL)
504  return NULL;
505 
506  /* Assign this node a unique ID. */
507  plan->plan_node_id = root->glob->lastPlanNodeId++;
508 
509  /*
510  * Plan-type-specific fixes
511  */
512  switch (nodeTag(plan))
513  {
514  case T_SeqScan:
515  {
516  SeqScan *splan = (SeqScan *) plan;
517 
518  splan->scanrelid += rtoffset;
519  splan->plan.targetlist =
520  fix_scan_list(root, splan->plan.targetlist,
521  rtoffset, NUM_EXEC_TLIST(plan));
522  splan->plan.qual =
523  fix_scan_list(root, splan->plan.qual,
524  rtoffset, NUM_EXEC_QUAL(plan));
525  }
526  break;
527  case T_SampleScan:
528  {
529  SampleScan *splan = (SampleScan *) plan;
530 
531  splan->scan.scanrelid += rtoffset;
532  splan->scan.plan.targetlist =
533  fix_scan_list(root, splan->scan.plan.targetlist,
534  rtoffset, NUM_EXEC_TLIST(plan));
535  splan->scan.plan.qual =
536  fix_scan_list(root, splan->scan.plan.qual,
537  rtoffset, NUM_EXEC_QUAL(plan));
538  splan->tablesample = (TableSampleClause *)
539  fix_scan_expr(root, (Node *) splan->tablesample,
540  rtoffset, 1);
541  }
542  break;
543  case T_IndexScan:
544  {
545  IndexScan *splan = (IndexScan *) plan;
546 
547  splan->scan.scanrelid += rtoffset;
548  splan->scan.plan.targetlist =
549  fix_scan_list(root, splan->scan.plan.targetlist,
550  rtoffset, NUM_EXEC_TLIST(plan));
551  splan->scan.plan.qual =
552  fix_scan_list(root, splan->scan.plan.qual,
553  rtoffset, NUM_EXEC_QUAL(plan));
554  splan->indexqual =
555  fix_scan_list(root, splan->indexqual,
556  rtoffset, 1);
557  splan->indexqualorig =
558  fix_scan_list(root, splan->indexqualorig,
559  rtoffset, NUM_EXEC_QUAL(plan));
560  splan->indexorderby =
561  fix_scan_list(root, splan->indexorderby,
562  rtoffset, 1);
563  splan->indexorderbyorig =
564  fix_scan_list(root, splan->indexorderbyorig,
565  rtoffset, NUM_EXEC_QUAL(plan));
566  }
567  break;
568  case T_IndexOnlyScan:
569  {
570  IndexOnlyScan *splan = (IndexOnlyScan *) plan;
571 
572  return set_indexonlyscan_references(root, splan, rtoffset);
573  }
574  break;
575  case T_BitmapIndexScan:
576  {
578 
579  splan->scan.scanrelid += rtoffset;
580  /* no need to fix targetlist and qual */
581  Assert(splan->scan.plan.targetlist == NIL);
582  Assert(splan->scan.plan.qual == NIL);
583  splan->indexqual =
584  fix_scan_list(root, splan->indexqual, rtoffset, 1);
585  splan->indexqualorig =
586  fix_scan_list(root, splan->indexqualorig,
587  rtoffset, NUM_EXEC_QUAL(plan));
588  }
589  break;
590  case T_BitmapHeapScan:
591  {
592  BitmapHeapScan *splan = (BitmapHeapScan *) plan;
593 
594  splan->scan.scanrelid += rtoffset;
595  splan->scan.plan.targetlist =
596  fix_scan_list(root, splan->scan.plan.targetlist,
597  rtoffset, NUM_EXEC_TLIST(plan));
598  splan->scan.plan.qual =
599  fix_scan_list(root, splan->scan.plan.qual,
600  rtoffset, NUM_EXEC_QUAL(plan));
601  splan->bitmapqualorig =
602  fix_scan_list(root, splan->bitmapqualorig,
603  rtoffset, NUM_EXEC_QUAL(plan));
604  }
605  break;
606  case T_TidScan:
607  {
608  TidScan *splan = (TidScan *) plan;
609 
610  splan->scan.scanrelid += rtoffset;
611  splan->scan.plan.targetlist =
612  fix_scan_list(root, splan->scan.plan.targetlist,
613  rtoffset, NUM_EXEC_TLIST(plan));
614  splan->scan.plan.qual =
615  fix_scan_list(root, splan->scan.plan.qual,
616  rtoffset, NUM_EXEC_QUAL(plan));
617  splan->tidquals =
618  fix_scan_list(root, splan->tidquals,
619  rtoffset, 1);
620  }
621  break;
622  case T_SubqueryScan:
623  /* Needs special treatment, see comments below */
624  return set_subqueryscan_references(root,
625  (SubqueryScan *) plan,
626  rtoffset);
627  case T_FunctionScan:
628  {
629  FunctionScan *splan = (FunctionScan *) plan;
630 
631  splan->scan.scanrelid += rtoffset;
632  splan->scan.plan.targetlist =
633  fix_scan_list(root, splan->scan.plan.targetlist,
634  rtoffset, NUM_EXEC_TLIST(plan));
635  splan->scan.plan.qual =
636  fix_scan_list(root, splan->scan.plan.qual,
637  rtoffset, NUM_EXEC_QUAL(plan));
638  splan->functions =
639  fix_scan_list(root, splan->functions, rtoffset, 1);
640  }
641  break;
642  case T_TableFuncScan:
643  {
644  TableFuncScan *splan = (TableFuncScan *) plan;
645 
646  splan->scan.scanrelid += rtoffset;
647  splan->scan.plan.targetlist =
648  fix_scan_list(root, splan->scan.plan.targetlist,
649  rtoffset, NUM_EXEC_TLIST(plan));
650  splan->scan.plan.qual =
651  fix_scan_list(root, splan->scan.plan.qual,
652  rtoffset, NUM_EXEC_QUAL(plan));
653  splan->tablefunc = (TableFunc *)
654  fix_scan_expr(root, (Node *) splan->tablefunc,
655  rtoffset, 1);
656  }
657  break;
658  case T_ValuesScan:
659  {
660  ValuesScan *splan = (ValuesScan *) plan;
661 
662  splan->scan.scanrelid += rtoffset;
663  splan->scan.plan.targetlist =
664  fix_scan_list(root, splan->scan.plan.targetlist,
665  rtoffset, NUM_EXEC_TLIST(plan));
666  splan->scan.plan.qual =
667  fix_scan_list(root, splan->scan.plan.qual,
668  rtoffset, NUM_EXEC_QUAL(plan));
669  splan->values_lists =
670  fix_scan_list(root, splan->values_lists,
671  rtoffset, 1);
672  }
673  break;
674  case T_CteScan:
675  {
676  CteScan *splan = (CteScan *) plan;
677 
678  splan->scan.scanrelid += rtoffset;
679  splan->scan.plan.targetlist =
680  fix_scan_list(root, splan->scan.plan.targetlist,
681  rtoffset, NUM_EXEC_TLIST(plan));
682  splan->scan.plan.qual =
683  fix_scan_list(root, splan->scan.plan.qual,
684  rtoffset, NUM_EXEC_QUAL(plan));
685  }
686  break;
688  {
690 
691  splan->scan.scanrelid += rtoffset;
692  splan->scan.plan.targetlist =
693  fix_scan_list(root, splan->scan.plan.targetlist,
694  rtoffset, NUM_EXEC_TLIST(plan));
695  splan->scan.plan.qual =
696  fix_scan_list(root, splan->scan.plan.qual,
697  rtoffset, NUM_EXEC_QUAL(plan));
698  }
699  break;
700  case T_WorkTableScan:
701  {
702  WorkTableScan *splan = (WorkTableScan *) plan;
703 
704  splan->scan.scanrelid += rtoffset;
705  splan->scan.plan.targetlist =
706  fix_scan_list(root, splan->scan.plan.targetlist,
707  rtoffset, NUM_EXEC_TLIST(plan));
708  splan->scan.plan.qual =
709  fix_scan_list(root, splan->scan.plan.qual,
710  rtoffset, NUM_EXEC_QUAL(plan));
711  }
712  break;
713  case T_ForeignScan:
714  set_foreignscan_references(root, (ForeignScan *) plan, rtoffset);
715  break;
716  case T_CustomScan:
717  set_customscan_references(root, (CustomScan *) plan, rtoffset);
718  break;
719 
720  case T_NestLoop:
721  case T_MergeJoin:
722  case T_HashJoin:
723  set_join_references(root, (Join *) plan, rtoffset);
724  break;
725 
726  case T_Gather:
727  case T_GatherMerge:
728  {
729  set_upper_references(root, plan, rtoffset);
730  set_param_references(root, plan);
731  }
732  break;
733 
734  case T_Hash:
735  set_hash_references(root, plan, rtoffset);
736  break;
737 
738  case T_Material:
739  case T_Sort:
740  case T_IncrementalSort:
741  case T_Unique:
742  case T_SetOp:
743 
744  /*
745  * These plan types don't actually bother to evaluate their
746  * targetlists, because they just return their unmodified input
747  * tuples. Even though the targetlist won't be used by the
748  * executor, we fix it up for possible use by EXPLAIN (not to
749  * mention ease of debugging --- wrong varnos are very confusing).
750  */
751  set_dummy_tlist_references(plan, rtoffset);
752 
753  /*
754  * Since these plan types don't check quals either, we should not
755  * find any qual expression attached to them.
756  */
757  Assert(plan->qual == NIL);
758  break;
759  case T_LockRows:
760  {
761  LockRows *splan = (LockRows *) plan;
762 
763  /*
764  * Like the plan types above, LockRows doesn't evaluate its
765  * tlist or quals. But we have to fix up the RT indexes in
766  * its rowmarks.
767  */
768  set_dummy_tlist_references(plan, rtoffset);
769  Assert(splan->plan.qual == NIL);
770 
771  foreach(l, splan->rowMarks)
772  {
773  PlanRowMark *rc = (PlanRowMark *) lfirst(l);
774 
775  rc->rti += rtoffset;
776  rc->prti += rtoffset;
777  }
778  }
779  break;
780  case T_Limit:
781  {
782  Limit *splan = (Limit *) plan;
783 
784  /*
785  * Like the plan types above, Limit doesn't evaluate its tlist
786  * or quals. It does have live expressions for limit/offset,
787  * however; and those cannot contain subplan variable refs, so
788  * fix_scan_expr works for them.
789  */
790  set_dummy_tlist_references(plan, rtoffset);
791  Assert(splan->plan.qual == NIL);
792 
793  splan->limitOffset =
794  fix_scan_expr(root, splan->limitOffset, rtoffset, 1);
795  splan->limitCount =
796  fix_scan_expr(root, splan->limitCount, rtoffset, 1);
797  }
798  break;
799  case T_Agg:
800  {
801  Agg *agg = (Agg *) plan;
802 
803  /*
804  * If this node is combining partial-aggregation results, we
805  * must convert its Aggrefs to contain references to the
806  * partial-aggregate subexpressions that will be available
807  * from the child plan node.
808  */
809  if (DO_AGGSPLIT_COMBINE(agg->aggsplit))
810  {
811  plan->targetlist = (List *)
812  convert_combining_aggrefs((Node *) plan->targetlist,
813  NULL);
814  plan->qual = (List *)
815  convert_combining_aggrefs((Node *) plan->qual,
816  NULL);
817  }
818 
819  set_upper_references(root, plan, rtoffset);
820  }
821  break;
822  case T_Group:
823  set_upper_references(root, plan, rtoffset);
824  break;
825  case T_WindowAgg:
826  {
827  WindowAgg *wplan = (WindowAgg *) plan;
828 
829  set_upper_references(root, plan, rtoffset);
830 
831  /*
832  * Like Limit node limit/offset expressions, WindowAgg has
833  * frame offset expressions, which cannot contain subplan
834  * variable refs, so fix_scan_expr works for them.
835  */
836  wplan->startOffset =
837  fix_scan_expr(root, wplan->startOffset, rtoffset, 1);
838  wplan->endOffset =
839  fix_scan_expr(root, wplan->endOffset, rtoffset, 1);
840  }
841  break;
842  case T_Result:
843  {
844  Result *splan = (Result *) plan;
845 
846  /*
847  * Result may or may not have a subplan; if not, it's more
848  * like a scan node than an upper node.
849  */
850  if (splan->plan.lefttree != NULL)
851  set_upper_references(root, plan, rtoffset);
852  else
853  {
854  splan->plan.targetlist =
855  fix_scan_list(root, splan->plan.targetlist,
856  rtoffset, NUM_EXEC_TLIST(plan));
857  splan->plan.qual =
858  fix_scan_list(root, splan->plan.qual,
859  rtoffset, NUM_EXEC_QUAL(plan));
860  }
861  /* resconstantqual can't contain any subplan variable refs */
862  splan->resconstantqual =
863  fix_scan_expr(root, splan->resconstantqual, rtoffset, 1);
864  }
865  break;
866  case T_ProjectSet:
867  set_upper_references(root, plan, rtoffset);
868  break;
869  case T_ModifyTable:
870  {
871  ModifyTable *splan = (ModifyTable *) plan;
872 
873  Assert(splan->plan.targetlist == NIL);
874  Assert(splan->plan.qual == NIL);
875 
876  splan->withCheckOptionLists =
877  fix_scan_list(root, splan->withCheckOptionLists,
878  rtoffset, 1);
879 
880  if (splan->returningLists)
881  {
882  List *newRL = NIL;
883  ListCell *lcrl,
884  *lcrr,
885  *lcp;
886 
887  /*
888  * Pass each per-subplan returningList through
889  * set_returning_clause_references().
890  */
892  Assert(list_length(splan->returningLists) == list_length(splan->plans));
893  forthree(lcrl, splan->returningLists,
894  lcrr, splan->resultRelations,
895  lcp, splan->plans)
896  {
897  List *rlist = (List *) lfirst(lcrl);
898  Index resultrel = lfirst_int(lcrr);
899  Plan *subplan = (Plan *) lfirst(lcp);
900 
901  rlist = set_returning_clause_references(root,
902  rlist,
903  subplan,
904  resultrel,
905  rtoffset);
906  newRL = lappend(newRL, rlist);
907  }
908  splan->returningLists = newRL;
909 
910  /*
911  * Set up the visible plan targetlist as being the same as
912  * the first RETURNING list. This is for the use of
913  * EXPLAIN; the executor won't pay any attention to the
914  * targetlist. We postpone this step until here so that
915  * we don't have to do set_returning_clause_references()
916  * twice on identical targetlists.
917  */
918  splan->plan.targetlist = copyObject(linitial(newRL));
919  }
920 
921  /*
922  * We treat ModifyTable with ON CONFLICT as a form of 'pseudo
923  * join', where the inner side is the EXCLUDED tuple.
924  * Therefore use fix_join_expr to setup the relevant variables
925  * to INNER_VAR. We explicitly don't create any OUTER_VARs as
926  * those are already used by RETURNING and it seems better to
927  * be non-conflicting.
928  */
929  if (splan->onConflictSet)
930  {
931  indexed_tlist *itlist;
932 
933  itlist = build_tlist_index(splan->exclRelTlist);
934 
935  splan->onConflictSet =
936  fix_join_expr(root, splan->onConflictSet,
937  NULL, itlist,
939  rtoffset, NUM_EXEC_QUAL(plan));
940 
941  splan->onConflictWhere = (Node *)
942  fix_join_expr(root, (List *) splan->onConflictWhere,
943  NULL, itlist,
945  rtoffset, NUM_EXEC_QUAL(plan));
946 
947  pfree(itlist);
948 
949  splan->exclRelTlist =
950  fix_scan_list(root, splan->exclRelTlist, rtoffset, 1);
951  }
952 
953  splan->nominalRelation += rtoffset;
954  if (splan->rootRelation)
955  splan->rootRelation += rtoffset;
956  splan->exclRelRTI += rtoffset;
957 
958  foreach(l, splan->resultRelations)
959  {
960  lfirst_int(l) += rtoffset;
961  }
962  foreach(l, splan->rowMarks)
963  {
964  PlanRowMark *rc = (PlanRowMark *) lfirst(l);
965 
966  rc->rti += rtoffset;
967  rc->prti += rtoffset;
968  }
969  foreach(l, splan->plans)
970  {
971  lfirst(l) = set_plan_refs(root,
972  (Plan *) lfirst(l),
973  rtoffset);
974  }
975 
976  /*
977  * Append this ModifyTable node's final result relation RT
978  * index(es) to the global list for the plan, and set its
979  * resultRelIndex to reflect their starting position in the
980  * global list.
981  */
983  root->glob->resultRelations =
985  splan->resultRelations);
986 
987  /*
988  * If the main target relation is a partitioned table, also
989  * add the partition root's RT index to rootResultRelations,
990  * and remember its index in that list in rootResultRelIndex.
991  */
992  if (splan->rootRelation)
993  {
994  splan->rootResultRelIndex =
996  root->glob->rootResultRelations =
998  splan->rootRelation);
999  }
1000  }
1001  break;
1002  case T_Append:
1003  /* Needs special treatment, see comments below */
1004  return set_append_references(root,
1005  (Append *) plan,
1006  rtoffset);
1007  case T_MergeAppend:
1008  /* Needs special treatment, see comments below */
1009  return set_mergeappend_references(root,
1010  (MergeAppend *) plan,
1011  rtoffset);
1012  case T_RecursiveUnion:
1013  /* This doesn't evaluate targetlist or check quals either */
1014  set_dummy_tlist_references(plan, rtoffset);
1015  Assert(plan->qual == NIL);
1016  break;
1017  case T_BitmapAnd:
1018  {
1019  BitmapAnd *splan = (BitmapAnd *) plan;
1020 
1021  /* BitmapAnd works like Append, but has no tlist */
1022  Assert(splan->plan.targetlist == NIL);
1023  Assert(splan->plan.qual == NIL);
1024  foreach(l, splan->bitmapplans)
1025  {
1026  lfirst(l) = set_plan_refs(root,
1027  (Plan *) lfirst(l),
1028  rtoffset);
1029  }
1030  }
1031  break;
1032  case T_BitmapOr:
1033  {
1034  BitmapOr *splan = (BitmapOr *) plan;
1035 
1036  /* BitmapOr works like Append, but has no tlist */
1037  Assert(splan->plan.targetlist == NIL);
1038  Assert(splan->plan.qual == NIL);
1039  foreach(l, splan->bitmapplans)
1040  {
1041  lfirst(l) = set_plan_refs(root,
1042  (Plan *) lfirst(l),
1043  rtoffset);
1044  }
1045  }
1046  break;
1047  default:
1048  elog(ERROR, "unrecognized node type: %d",
1049  (int) nodeTag(plan));
1050  break;
1051  }
1052 
1053  /*
1054  * Now recurse into child plans, if any
1055  *
1056  * NOTE: it is essential that we recurse into child plans AFTER we set
1057  * subplan references in this plan's tlist and quals. If we did the
1058  * reference-adjustments bottom-up, then we would fail to match this
1059  * plan's var nodes against the already-modified nodes of the children.
1060  */
1061  plan->lefttree = set_plan_refs(root, plan->lefttree, rtoffset);
1062  plan->righttree = set_plan_refs(root, plan->righttree, rtoffset);
1063 
1064  return plan;
1065 }
1066 
1067 /*
1068  * set_indexonlyscan_references
1069  * Do set_plan_references processing on an IndexOnlyScan
1070  *
1071  * This is unlike the handling of a plain IndexScan because we have to
1072  * convert Vars referencing the heap into Vars referencing the index.
1073  * We can use the fix_upper_expr machinery for that, by working from a
1074  * targetlist describing the index columns.
1075  */
1076 static Plan *
1078  IndexOnlyScan *plan,
1079  int rtoffset)
1080 {
1081  indexed_tlist *index_itlist;
1082 
1083  index_itlist = build_tlist_index(plan->indextlist);
1084 
1085  plan->scan.scanrelid += rtoffset;
1086  plan->scan.plan.targetlist = (List *)
1087  fix_upper_expr(root,
1088  (Node *) plan->scan.plan.targetlist,
1089  index_itlist,
1090  INDEX_VAR,
1091  rtoffset,
1092  NUM_EXEC_TLIST((Plan *) plan));
1093  plan->scan.plan.qual = (List *)
1094  fix_upper_expr(root,
1095  (Node *) plan->scan.plan.qual,
1096  index_itlist,
1097  INDEX_VAR,
1098  rtoffset,
1099  NUM_EXEC_QUAL((Plan *) plan));
1100  /* indexqual is already transformed to reference index columns */
1101  plan->indexqual = fix_scan_list(root, plan->indexqual,
1102  rtoffset, 1);
1103  /* indexorderby is already transformed to reference index columns */
1104  plan->indexorderby = fix_scan_list(root, plan->indexorderby,
1105  rtoffset, 1);
1106  /* indextlist must NOT be transformed to reference index columns */
1107  plan->indextlist = fix_scan_list(root, plan->indextlist,
1108  rtoffset, NUM_EXEC_TLIST((Plan *) plan));
1109 
1110  pfree(index_itlist);
1111 
1112  return (Plan *) plan;
1113 }
1114 
1115 /*
1116  * set_subqueryscan_references
1117  * Do set_plan_references processing on a SubqueryScan
1118  *
1119  * We try to strip out the SubqueryScan entirely; if we can't, we have
1120  * to do the normal processing on it.
1121  */
1122 static Plan *
1124  SubqueryScan *plan,
1125  int rtoffset)
1126 {
1127  RelOptInfo *rel;
1128  Plan *result;
1129 
1130  /* Need to look up the subquery's RelOptInfo, since we need its subroot */
1131  rel = find_base_rel(root, plan->scan.scanrelid);
1132 
1133  /* Recursively process the subplan */
1134  plan->subplan = set_plan_references(rel->subroot, plan->subplan);
1135 
1136  if (trivial_subqueryscan(plan))
1137  {
1138  /*
1139  * We can omit the SubqueryScan node and just pull up the subplan.
1140  */
1141  result = clean_up_removed_plan_level((Plan *) plan, plan->subplan);
1142  }
1143  else
1144  {
1145  /*
1146  * Keep the SubqueryScan node. We have to do the processing that
1147  * set_plan_references would otherwise have done on it. Notice we do
1148  * not do set_upper_references() here, because a SubqueryScan will
1149  * always have been created with correct references to its subplan's
1150  * outputs to begin with.
1151  */
1152  plan->scan.scanrelid += rtoffset;
1153  plan->scan.plan.targetlist =
1154  fix_scan_list(root, plan->scan.plan.targetlist,
1155  rtoffset, NUM_EXEC_TLIST((Plan *) plan));
1156  plan->scan.plan.qual =
1157  fix_scan_list(root, plan->scan.plan.qual,
1158  rtoffset, NUM_EXEC_QUAL((Plan *) plan));
1159 
1160  result = (Plan *) plan;
1161  }
1162 
1163  return result;
1164 }
1165 
1166 /*
1167  * trivial_subqueryscan
1168  * Detect whether a SubqueryScan can be deleted from the plan tree.
1169  *
1170  * We can delete it if it has no qual to check and the targetlist just
1171  * regurgitates the output of the child plan.
1172  */
1173 static bool
1175 {
1176  int attrno;
1177  ListCell *lp,
1178  *lc;
1179 
1180  if (plan->scan.plan.qual != NIL)
1181  return false;
1182 
1183  if (list_length(plan->scan.plan.targetlist) !=
1184  list_length(plan->subplan->targetlist))
1185  return false; /* tlists not same length */
1186 
1187  attrno = 1;
1188  forboth(lp, plan->scan.plan.targetlist, lc, plan->subplan->targetlist)
1189  {
1190  TargetEntry *ptle = (TargetEntry *) lfirst(lp);
1191  TargetEntry *ctle = (TargetEntry *) lfirst(lc);
1192 
1193  if (ptle->resjunk != ctle->resjunk)
1194  return false; /* tlist doesn't match junk status */
1195 
1196  /*
1197  * We accept either a Var referencing the corresponding element of the
1198  * subplan tlist, or a Const equaling the subplan element. See
1199  * generate_setop_tlist() for motivation.
1200  */
1201  if (ptle->expr && IsA(ptle->expr, Var))
1202  {
1203  Var *var = (Var *) ptle->expr;
1204 
1205  Assert(var->varno == plan->scan.scanrelid);
1206  Assert(var->varlevelsup == 0);
1207  if (var->varattno != attrno)
1208  return false; /* out of order */
1209  }
1210  else if (ptle->expr && IsA(ptle->expr, Const))
1211  {
1212  if (!equal(ptle->expr, ctle->expr))
1213  return false;
1214  }
1215  else
1216  return false;
1217 
1218  attrno++;
1219  }
1220 
1221  return true;
1222 }
1223 
1224 /*
1225  * clean_up_removed_plan_level
1226  * Do necessary cleanup when we strip out a SubqueryScan, Append, etc
1227  *
1228  * We are dropping the "parent" plan in favor of returning just its "child".
1229  * A few small tweaks are needed.
1230  */
1231 static Plan *
1233 {
1234  /* We have to be sure we don't lose any initplans */
1235  child->initPlan = list_concat(parent->initPlan,
1236  child->initPlan);
1237 
1238  /*
1239  * We also have to transfer the parent's column labeling info into the
1240  * child, else columns sent to client will be improperly labeled if this
1241  * is the topmost plan level. resjunk and so on may be important too.
1242  */
1243  apply_tlist_labeling(child->targetlist, parent->targetlist);
1244 
1245  return child;
1246 }
1247 
1248 /*
1249  * set_foreignscan_references
1250  * Do set_plan_references processing on a ForeignScan
1251  */
1252 static void
1254  ForeignScan *fscan,
1255  int rtoffset)
1256 {
1257  /* Adjust scanrelid if it's valid */
1258  if (fscan->scan.scanrelid > 0)
1259  fscan->scan.scanrelid += rtoffset;
1260 
1261  if (fscan->fdw_scan_tlist != NIL || fscan->scan.scanrelid == 0)
1262  {
1263  /*
1264  * Adjust tlist, qual, fdw_exprs, fdw_recheck_quals to reference
1265  * foreign scan tuple
1266  */
1268 
1269  fscan->scan.plan.targetlist = (List *)
1270  fix_upper_expr(root,
1271  (Node *) fscan->scan.plan.targetlist,
1272  itlist,
1273  INDEX_VAR,
1274  rtoffset,
1275  NUM_EXEC_TLIST((Plan *) fscan));
1276  fscan->scan.plan.qual = (List *)
1277  fix_upper_expr(root,
1278  (Node *) fscan->scan.plan.qual,
1279  itlist,
1280  INDEX_VAR,
1281  rtoffset,
1282  NUM_EXEC_QUAL((Plan *) fscan));
1283  fscan->fdw_exprs = (List *)
1284  fix_upper_expr(root,
1285  (Node *) fscan->fdw_exprs,
1286  itlist,
1287  INDEX_VAR,
1288  rtoffset,
1289  NUM_EXEC_QUAL((Plan *) fscan));
1290  fscan->fdw_recheck_quals = (List *)
1291  fix_upper_expr(root,
1292  (Node *) fscan->fdw_recheck_quals,
1293  itlist,
1294  INDEX_VAR,
1295  rtoffset,
1296  NUM_EXEC_QUAL((Plan *) fscan));
1297  pfree(itlist);
1298  /* fdw_scan_tlist itself just needs fix_scan_list() adjustments */
1299  fscan->fdw_scan_tlist =
1300  fix_scan_list(root, fscan->fdw_scan_tlist,
1301  rtoffset, NUM_EXEC_TLIST((Plan *) fscan));
1302  }
1303  else
1304  {
1305  /*
1306  * Adjust tlist, qual, fdw_exprs, fdw_recheck_quals in the standard
1307  * way
1308  */
1309  fscan->scan.plan.targetlist =
1310  fix_scan_list(root, fscan->scan.plan.targetlist,
1311  rtoffset, NUM_EXEC_TLIST((Plan *) fscan));
1312  fscan->scan.plan.qual =
1313  fix_scan_list(root, fscan->scan.plan.qual,
1314  rtoffset, NUM_EXEC_QUAL((Plan *) fscan));
1315  fscan->fdw_exprs =
1316  fix_scan_list(root, fscan->fdw_exprs,
1317  rtoffset, NUM_EXEC_QUAL((Plan *) fscan));
1318  fscan->fdw_recheck_quals =
1319  fix_scan_list(root, fscan->fdw_recheck_quals,
1320  rtoffset, NUM_EXEC_QUAL((Plan *) fscan));
1321  }
1322 
1323  fscan->fs_relids = offset_relid_set(fscan->fs_relids, rtoffset);
1324 }
1325 
1326 /*
1327  * set_customscan_references
1328  * Do set_plan_references processing on a CustomScan
1329  */
1330 static void
1332  CustomScan *cscan,
1333  int rtoffset)
1334 {
1335  ListCell *lc;
1336 
1337  /* Adjust scanrelid if it's valid */
1338  if (cscan->scan.scanrelid > 0)
1339  cscan->scan.scanrelid += rtoffset;
1340 
1341  if (cscan->custom_scan_tlist != NIL || cscan->scan.scanrelid == 0)
1342  {
1343  /* Adjust tlist, qual, custom_exprs to reference custom scan tuple */
1345 
1346  cscan->scan.plan.targetlist = (List *)
1347  fix_upper_expr(root,
1348  (Node *) cscan->scan.plan.targetlist,
1349  itlist,
1350  INDEX_VAR,
1351  rtoffset,
1352  NUM_EXEC_TLIST((Plan *) cscan));
1353  cscan->scan.plan.qual = (List *)
1354  fix_upper_expr(root,
1355  (Node *) cscan->scan.plan.qual,
1356  itlist,
1357  INDEX_VAR,
1358  rtoffset,
1359  NUM_EXEC_QUAL((Plan *) cscan));
1360  cscan->custom_exprs = (List *)
1361  fix_upper_expr(root,
1362  (Node *) cscan->custom_exprs,
1363  itlist,
1364  INDEX_VAR,
1365  rtoffset,
1366  NUM_EXEC_QUAL((Plan *) cscan));
1367  pfree(itlist);
1368  /* custom_scan_tlist itself just needs fix_scan_list() adjustments */
1369  cscan->custom_scan_tlist =
1370  fix_scan_list(root, cscan->custom_scan_tlist,
1371  rtoffset, NUM_EXEC_TLIST((Plan *) cscan));
1372  }
1373  else
1374  {
1375  /* Adjust tlist, qual, custom_exprs in the standard way */
1376  cscan->scan.plan.targetlist =
1377  fix_scan_list(root, cscan->scan.plan.targetlist,
1378  rtoffset, NUM_EXEC_TLIST((Plan *) cscan));
1379  cscan->scan.plan.qual =
1380  fix_scan_list(root, cscan->scan.plan.qual,
1381  rtoffset, NUM_EXEC_QUAL((Plan *) cscan));
1382  cscan->custom_exprs =
1383  fix_scan_list(root, cscan->custom_exprs,
1384  rtoffset, NUM_EXEC_QUAL((Plan *) cscan));
1385  }
1386 
1387  /* Adjust child plan-nodes recursively, if needed */
1388  foreach(lc, cscan->custom_plans)
1389  {
1390  lfirst(lc) = set_plan_refs(root, (Plan *) lfirst(lc), rtoffset);
1391  }
1392 
1393  cscan->custom_relids = offset_relid_set(cscan->custom_relids, rtoffset);
1394 }
1395 
1396 /*
1397  * set_append_references
1398  * Do set_plan_references processing on an Append
1399  *
1400  * We try to strip out the Append entirely; if we can't, we have
1401  * to do the normal processing on it.
1402  */
1403 static Plan *
1405  Append *aplan,
1406  int rtoffset)
1407 {
1408  ListCell *l;
1409 
1410  /*
1411  * Append, like Sort et al, doesn't actually evaluate its targetlist or
1412  * check quals. If it's got exactly one child plan, then it's not doing
1413  * anything useful at all, and we can strip it out.
1414  */
1415  Assert(aplan->plan.qual == NIL);
1416 
1417  /* First, we gotta recurse on the children */
1418  foreach(l, aplan->appendplans)
1419  {
1420  lfirst(l) = set_plan_refs(root, (Plan *) lfirst(l), rtoffset);
1421  }
1422 
1423  /* Now, if there's just one, forget the Append and return that child */
1424  if (list_length(aplan->appendplans) == 1)
1425  return clean_up_removed_plan_level((Plan *) aplan,
1426  (Plan *) linitial(aplan->appendplans));
1427 
1428  /*
1429  * Otherwise, clean up the Append as needed. It's okay to do this after
1430  * recursing to the children, because set_dummy_tlist_references doesn't
1431  * look at those.
1432  */
1433  set_dummy_tlist_references((Plan *) aplan, rtoffset);
1434 
1435  aplan->apprelids = offset_relid_set(aplan->apprelids, rtoffset);
1436 
1437  if (aplan->part_prune_info)
1438  {
1439  foreach(l, aplan->part_prune_info->prune_infos)
1440  {
1441  List *prune_infos = lfirst(l);
1442  ListCell *l2;
1443 
1444  foreach(l2, prune_infos)
1445  {
1446  PartitionedRelPruneInfo *pinfo = lfirst(l2);
1447 
1448  pinfo->rtindex += rtoffset;
1449  }
1450  }
1451  }
1452 
1453  /* We don't need to recurse to lefttree or righttree ... */
1454  Assert(aplan->plan.lefttree == NULL);
1455  Assert(aplan->plan.righttree == NULL);
1456 
1457  return (Plan *) aplan;
1458 }
1459 
1460 /*
1461  * set_mergeappend_references
1462  * Do set_plan_references processing on a MergeAppend
1463  *
1464  * We try to strip out the MergeAppend entirely; if we can't, we have
1465  * to do the normal processing on it.
1466  */
1467 static Plan *
1469  MergeAppend *mplan,
1470  int rtoffset)
1471 {
1472  ListCell *l;
1473 
1474  /*
1475  * MergeAppend, like Sort et al, doesn't actually evaluate its targetlist
1476  * or check quals. If it's got exactly one child plan, then it's not
1477  * doing anything useful at all, and we can strip it out.
1478  */
1479  Assert(mplan->plan.qual == NIL);
1480 
1481  /* First, we gotta recurse on the children */
1482  foreach(l, mplan->mergeplans)
1483  {
1484  lfirst(l) = set_plan_refs(root, (Plan *) lfirst(l), rtoffset);
1485  }
1486 
1487  /* Now, if there's just one, forget the MergeAppend and return that child */
1488  if (list_length(mplan->mergeplans) == 1)
1489  return clean_up_removed_plan_level((Plan *) mplan,
1490  (Plan *) linitial(mplan->mergeplans));
1491 
1492  /*
1493  * Otherwise, clean up the MergeAppend as needed. It's okay to do this
1494  * after recursing to the children, because set_dummy_tlist_references
1495  * doesn't look at those.
1496  */
1497  set_dummy_tlist_references((Plan *) mplan, rtoffset);
1498 
1499  mplan->apprelids = offset_relid_set(mplan->apprelids, rtoffset);
1500 
1501  if (mplan->part_prune_info)
1502  {
1503  foreach(l, mplan->part_prune_info->prune_infos)
1504  {
1505  List *prune_infos = lfirst(l);
1506  ListCell *l2;
1507 
1508  foreach(l2, prune_infos)
1509  {
1510  PartitionedRelPruneInfo *pinfo = lfirst(l2);
1511 
1512  pinfo->rtindex += rtoffset;
1513  }
1514  }
1515  }
1516 
1517  /* We don't need to recurse to lefttree or righttree ... */
1518  Assert(mplan->plan.lefttree == NULL);
1519  Assert(mplan->plan.righttree == NULL);
1520 
1521  return (Plan *) mplan;
1522 }
1523 
1524 /*
1525  * set_hash_references
1526  * Do set_plan_references processing on a Hash node
1527  */
1528 static void
1529 set_hash_references(PlannerInfo *root, Plan *plan, int rtoffset)
1530 {
1531  Hash *hplan = (Hash *) plan;
1532  Plan *outer_plan = plan->lefttree;
1533  indexed_tlist *outer_itlist;
1534 
1535  /*
1536  * Hash's hashkeys are used when feeding tuples into the hashtable,
1537  * therefore have them reference Hash's outer plan (which itself is the
1538  * inner plan of the HashJoin).
1539  */
1540  outer_itlist = build_tlist_index(outer_plan->targetlist);
1541  hplan->hashkeys = (List *)
1542  fix_upper_expr(root,
1543  (Node *) hplan->hashkeys,
1544  outer_itlist,
1545  OUTER_VAR,
1546  rtoffset,
1547  NUM_EXEC_QUAL(plan));
1548 
1549  /* Hash doesn't project */
1550  set_dummy_tlist_references(plan, rtoffset);
1551 
1552  /* Hash nodes don't have their own quals */
1553  Assert(plan->qual == NIL);
1554 }
1555 
1556 /*
1557  * offset_relid_set
1558  * Apply rtoffset to the members of a Relids set.
1559  */
1560 static Relids
1561 offset_relid_set(Relids relids, int rtoffset)
1562 {
1563  Relids result = NULL;
1564  int rtindex;
1565 
1566  /* If there's no offset to apply, we needn't recompute the value */
1567  if (rtoffset == 0)
1568  return relids;
1569  rtindex = -1;
1570  while ((rtindex = bms_next_member(relids, rtindex)) >= 0)
1571  result = bms_add_member(result, rtindex + rtoffset);
1572  return result;
1573 }
1574 
1575 /*
1576  * copyVar
1577  * Copy a Var node.
1578  *
1579  * fix_scan_expr and friends do this enough times that it's worth having
1580  * a bespoke routine instead of using the generic copyObject() function.
1581  */
1582 static inline Var *
1584 {
1585  Var *newvar = (Var *) palloc(sizeof(Var));
1586 
1587  *newvar = *var;
1588  return newvar;
1589 }
1590 
1591 /*
1592  * fix_expr_common
1593  * Do generic set_plan_references processing on an expression node
1594  *
1595  * This is code that is common to all variants of expression-fixing.
1596  * We must look up operator opcode info for OpExpr and related nodes,
1597  * add OIDs from regclass Const nodes into root->glob->relationOids, and
1598  * add PlanInvalItems for user-defined functions into root->glob->invalItems.
1599  * We also fill in column index lists for GROUPING() expressions.
1600  *
1601  * We assume it's okay to update opcode info in-place. So this could possibly
1602  * scribble on the planner's input data structures, but it's OK.
1603  */
1604 static void
1606 {
1607  /* We assume callers won't call us on a NULL pointer */
1608  if (IsA(node, Aggref))
1609  {
1611  ((Aggref *) node)->aggfnoid);
1612  }
1613  else if (IsA(node, WindowFunc))
1614  {
1616  ((WindowFunc *) node)->winfnoid);
1617  }
1618  else if (IsA(node, FuncExpr))
1619  {
1621  ((FuncExpr *) node)->funcid);
1622  }
1623  else if (IsA(node, OpExpr))
1624  {
1625  set_opfuncid((OpExpr *) node);
1627  ((OpExpr *) node)->opfuncid);
1628  }
1629  else if (IsA(node, DistinctExpr))
1630  {
1631  set_opfuncid((OpExpr *) node); /* rely on struct equivalence */
1633  ((DistinctExpr *) node)->opfuncid);
1634  }
1635  else if (IsA(node, NullIfExpr))
1636  {
1637  set_opfuncid((OpExpr *) node); /* rely on struct equivalence */
1639  ((NullIfExpr *) node)->opfuncid);
1640  }
1641  else if (IsA(node, ScalarArrayOpExpr))
1642  {
1645  ((ScalarArrayOpExpr *) node)->opfuncid);
1646  }
1647  else if (IsA(node, Const))
1648  {
1649  Const *con = (Const *) node;
1650 
1651  /* Check for regclass reference */
1652  if (ISREGCLASSCONST(con))
1653  root->glob->relationOids =
1654  lappend_oid(root->glob->relationOids,
1656  }
1657  else if (IsA(node, GroupingFunc))
1658  {
1659  GroupingFunc *g = (GroupingFunc *) node;
1660  AttrNumber *grouping_map = root->grouping_map;
1661 
1662  /* If there are no grouping sets, we don't need this. */
1663 
1664  Assert(grouping_map || g->cols == NIL);
1665 
1666  if (grouping_map)
1667  {
1668  ListCell *lc;
1669  List *cols = NIL;
1670 
1671  foreach(lc, g->refs)
1672  {
1673  cols = lappend_int(cols, grouping_map[lfirst_int(lc)]);
1674  }
1675 
1676  Assert(!g->cols || equal(cols, g->cols));
1677 
1678  if (!g->cols)
1679  g->cols = cols;
1680  }
1681  }
1682 }
1683 
1684 /*
1685  * fix_param_node
1686  * Do set_plan_references processing on a Param
1687  *
1688  * If it's a PARAM_MULTIEXPR, replace it with the appropriate Param from
1689  * root->multiexpr_params; otherwise no change is needed.
1690  * Just for paranoia's sake, we make a copy of the node in either case.
1691  */
1692 static Node *
1694 {
1695  if (p->paramkind == PARAM_MULTIEXPR)
1696  {
1697  int subqueryid = p->paramid >> 16;
1698  int colno = p->paramid & 0xFFFF;
1699  List *params;
1700 
1701  if (subqueryid <= 0 ||
1702  subqueryid > list_length(root->multiexpr_params))
1703  elog(ERROR, "unexpected PARAM_MULTIEXPR ID: %d", p->paramid);
1704  params = (List *) list_nth(root->multiexpr_params, subqueryid - 1);
1705  if (colno <= 0 || colno > list_length(params))
1706  elog(ERROR, "unexpected PARAM_MULTIEXPR ID: %d", p->paramid);
1707  return copyObject(list_nth(params, colno - 1));
1708  }
1709  return (Node *) copyObject(p);
1710 }
1711 
1712 /*
1713  * fix_alternative_subplan
1714  * Do set_plan_references processing on an AlternativeSubPlan
1715  *
1716  * Choose one of the alternative implementations and return just that one,
1717  * discarding the rest of the AlternativeSubPlan structure.
1718  * Note: caller must still recurse into the result!
1719  *
1720  * We don't make any attempt to fix up cost estimates in the parent plan
1721  * node or higher-level nodes. However, we do remove the rejected subplan(s)
1722  * from root->glob->subplans, to minimize cycles expended on them later.
1723  */
1724 static Node *
1726  double num_exec)
1727 {
1728  SubPlan *bestplan = NULL;
1729  Cost bestcost = 0;
1730  ListCell *lc;
1731 
1732  /*
1733  * Compute the estimated cost of each subplan assuming num_exec
1734  * executions, and keep the cheapest one. Replace discarded subplans with
1735  * NULL pointers in the global subplans list. In event of exact equality
1736  * of estimates, we prefer the later plan; this is a bit arbitrary, but in
1737  * current usage it biases us to break ties against fast-start subplans.
1738  */
1739  Assert(asplan->subplans != NIL);
1740 
1741  foreach(lc, asplan->subplans)
1742  {
1743  SubPlan *curplan = (SubPlan *) lfirst(lc);
1744  Cost curcost;
1745 
1746  curcost = curplan->startup_cost + num_exec * curplan->per_call_cost;
1747  if (bestplan == NULL)
1748  {
1749  bestplan = curplan;
1750  bestcost = curcost;
1751  }
1752  else if (curcost <= bestcost)
1753  {
1754  /* drop old bestplan */
1755  ListCell *lc2 = list_nth_cell(root->glob->subplans,
1756  bestplan->plan_id - 1);
1757 
1758  lfirst(lc2) = NULL;
1759  bestplan = curplan;
1760  bestcost = curcost;
1761  }
1762  else
1763  {
1764  /* drop curplan */
1765  ListCell *lc2 = list_nth_cell(root->glob->subplans,
1766  curplan->plan_id - 1);
1767 
1768  lfirst(lc2) = NULL;
1769  }
1770  }
1771 
1772  return (Node *) bestplan;
1773 }
1774 
1775 /*
1776  * fix_scan_expr
1777  * Do set_plan_references processing on a scan-level expression
1778  *
1779  * This consists of incrementing all Vars' varnos by rtoffset,
1780  * replacing PARAM_MULTIEXPR Params, expanding PlaceHolderVars,
1781  * replacing Aggref nodes that should be replaced by initplan output Params,
1782  * choosing the best implementation for AlternativeSubPlans,
1783  * looking up operator opcode info for OpExpr and related nodes,
1784  * and adding OIDs from regclass Const nodes into root->glob->relationOids.
1785  */
1786 static Node *
1787 fix_scan_expr(PlannerInfo *root, Node *node, int rtoffset, double num_exec)
1788 {
1789  fix_scan_expr_context context;
1790 
1791  context.root = root;
1792  context.rtoffset = rtoffset;
1793  context.num_exec = num_exec;
1794 
1795  if (rtoffset != 0 ||
1796  root->multiexpr_params != NIL ||
1797  root->glob->lastPHId != 0 ||
1798  root->minmax_aggs != NIL ||
1799  root->hasAlternativeSubPlans)
1800  {
1801  return fix_scan_expr_mutator(node, &context);
1802  }
1803  else
1804  {
1805  /*
1806  * If rtoffset == 0, we don't need to change any Vars, and if there
1807  * are no MULTIEXPR subqueries then we don't need to replace
1808  * PARAM_MULTIEXPR Params, and if there are no placeholders anywhere
1809  * we won't need to remove them, and if there are no minmax Aggrefs we
1810  * won't need to replace them, and if there are no AlternativeSubPlans
1811  * we won't need to remove them. Then it's OK to just scribble on the
1812  * input node tree instead of copying (since the only change, filling
1813  * in any unset opfuncid fields, is harmless). This saves just enough
1814  * cycles to be noticeable on trivial queries.
1815  */
1816  (void) fix_scan_expr_walker(node, &context);
1817  return node;
1818  }
1819 }
1820 
1821 static Node *
1823 {
1824  if (node == NULL)
1825  return NULL;
1826  if (IsA(node, Var))
1827  {
1828  Var *var = copyVar((Var *) node);
1829 
1830  Assert(var->varlevelsup == 0);
1831 
1832  /*
1833  * We should not see any Vars marked INNER_VAR or OUTER_VAR. But an
1834  * indexqual expression could contain INDEX_VAR Vars.
1835  */
1836  Assert(var->varno != INNER_VAR);
1837  Assert(var->varno != OUTER_VAR);
1838  if (!IS_SPECIAL_VARNO(var->varno))
1839  var->varno += context->rtoffset;
1840  if (var->varnosyn > 0)
1841  var->varnosyn += context->rtoffset;
1842  return (Node *) var;
1843  }
1844  if (IsA(node, Param))
1845  return fix_param_node(context->root, (Param *) node);
1846  if (IsA(node, Aggref))
1847  {
1848  Aggref *aggref = (Aggref *) node;
1849 
1850  /* See if the Aggref should be replaced by a Param */
1851  if (context->root->minmax_aggs != NIL &&
1852  list_length(aggref->args) == 1)
1853  {
1854  TargetEntry *curTarget = (TargetEntry *) linitial(aggref->args);
1855  ListCell *lc;
1856 
1857  foreach(lc, context->root->minmax_aggs)
1858  {
1859  MinMaxAggInfo *mminfo = (MinMaxAggInfo *) lfirst(lc);
1860 
1861  if (mminfo->aggfnoid == aggref->aggfnoid &&
1862  equal(mminfo->target, curTarget->expr))
1863  return (Node *) copyObject(mminfo->param);
1864  }
1865  }
1866  /* If no match, just fall through to process it normally */
1867  }
1868  if (IsA(node, CurrentOfExpr))
1869  {
1870  CurrentOfExpr *cexpr = (CurrentOfExpr *) copyObject(node);
1871 
1872  Assert(cexpr->cvarno != INNER_VAR);
1873  Assert(cexpr->cvarno != OUTER_VAR);
1874  if (!IS_SPECIAL_VARNO(cexpr->cvarno))
1875  cexpr->cvarno += context->rtoffset;
1876  return (Node *) cexpr;
1877  }
1878  if (IsA(node, PlaceHolderVar))
1879  {
1880  /* At scan level, we should always just evaluate the contained expr */
1881  PlaceHolderVar *phv = (PlaceHolderVar *) node;
1882 
1883  return fix_scan_expr_mutator((Node *) phv->phexpr, context);
1884  }
1885  if (IsA(node, AlternativeSubPlan))
1887  (AlternativeSubPlan *) node,
1888  context->num_exec),
1889  context);
1890  fix_expr_common(context->root, node);
1892  (void *) context);
1893 }
1894 
1895 static bool
1897 {
1898  if (node == NULL)
1899  return false;
1900  Assert(!IsA(node, PlaceHolderVar));
1901  Assert(!IsA(node, AlternativeSubPlan));
1902  fix_expr_common(context->root, node);
1904  (void *) context);
1905 }
1906 
1907 /*
1908  * set_join_references
1909  * Modify the target list and quals of a join node to reference its
1910  * subplans, by setting the varnos to OUTER_VAR or INNER_VAR and setting
1911  * attno values to the result domain number of either the corresponding
1912  * outer or inner join tuple item. Also perform opcode lookup for these
1913  * expressions, and add regclass OIDs to root->glob->relationOids.
1914  */
1915 static void
1916 set_join_references(PlannerInfo *root, Join *join, int rtoffset)
1917 {
1918  Plan *outer_plan = join->plan.lefttree;
1919  Plan *inner_plan = join->plan.righttree;
1920  indexed_tlist *outer_itlist;
1921  indexed_tlist *inner_itlist;
1922 
1923  outer_itlist = build_tlist_index(outer_plan->targetlist);
1924  inner_itlist = build_tlist_index(inner_plan->targetlist);
1925 
1926  /*
1927  * First process the joinquals (including merge or hash clauses). These
1928  * are logically below the join so they can always use all values
1929  * available from the input tlists. It's okay to also handle
1930  * NestLoopParams now, because those couldn't refer to nullable
1931  * subexpressions.
1932  */
1933  join->joinqual = fix_join_expr(root,
1934  join->joinqual,
1935  outer_itlist,
1936  inner_itlist,
1937  (Index) 0,
1938  rtoffset,
1939  NUM_EXEC_QUAL((Plan *) join));
1940 
1941  /* Now do join-type-specific stuff */
1942  if (IsA(join, NestLoop))
1943  {
1944  NestLoop *nl = (NestLoop *) join;
1945  ListCell *lc;
1946 
1947  foreach(lc, nl->nestParams)
1948  {
1949  NestLoopParam *nlp = (NestLoopParam *) lfirst(lc);
1950 
1951  nlp->paramval = (Var *) fix_upper_expr(root,
1952  (Node *) nlp->paramval,
1953  outer_itlist,
1954  OUTER_VAR,
1955  rtoffset,
1956  NUM_EXEC_TLIST(outer_plan));
1957  /* Check we replaced any PlaceHolderVar with simple Var */
1958  if (!(IsA(nlp->paramval, Var) &&
1959  nlp->paramval->varno == OUTER_VAR))
1960  elog(ERROR, "NestLoopParam was not reduced to a simple Var");
1961  }
1962  }
1963  else if (IsA(join, MergeJoin))
1964  {
1965  MergeJoin *mj = (MergeJoin *) join;
1966 
1967  mj->mergeclauses = fix_join_expr(root,
1968  mj->mergeclauses,
1969  outer_itlist,
1970  inner_itlist,
1971  (Index) 0,
1972  rtoffset,
1973  NUM_EXEC_QUAL((Plan *) join));
1974  }
1975  else if (IsA(join, HashJoin))
1976  {
1977  HashJoin *hj = (HashJoin *) join;
1978 
1979  hj->hashclauses = fix_join_expr(root,
1980  hj->hashclauses,
1981  outer_itlist,
1982  inner_itlist,
1983  (Index) 0,
1984  rtoffset,
1985  NUM_EXEC_QUAL((Plan *) join));
1986 
1987  /*
1988  * HashJoin's hashkeys are used to look for matching tuples from its
1989  * outer plan (not the Hash node!) in the hashtable.
1990  */
1991  hj->hashkeys = (List *) fix_upper_expr(root,
1992  (Node *) hj->hashkeys,
1993  outer_itlist,
1994  OUTER_VAR,
1995  rtoffset,
1996  NUM_EXEC_QUAL((Plan *) join));
1997  }
1998 
1999  /*
2000  * Now we need to fix up the targetlist and qpqual, which are logically
2001  * above the join. This means they should not re-use any input expression
2002  * that was computed in the nullable side of an outer join. Vars and
2003  * PlaceHolderVars are fine, so we can implement this restriction just by
2004  * clearing has_non_vars in the indexed_tlist structs.
2005  *
2006  * XXX This is a grotty workaround for the fact that we don't clearly
2007  * distinguish between a Var appearing below an outer join and the "same"
2008  * Var appearing above it. If we did, we'd not need to hack the matching
2009  * rules this way.
2010  */
2011  switch (join->jointype)
2012  {
2013  case JOIN_LEFT:
2014  case JOIN_SEMI:
2015  case JOIN_ANTI:
2016  inner_itlist->has_non_vars = false;
2017  break;
2018  case JOIN_RIGHT:
2019  outer_itlist->has_non_vars = false;
2020  break;
2021  case JOIN_FULL:
2022  outer_itlist->has_non_vars = false;
2023  inner_itlist->has_non_vars = false;
2024  break;
2025  default:
2026  break;
2027  }
2028 
2029  join->plan.targetlist = fix_join_expr(root,
2030  join->plan.targetlist,
2031  outer_itlist,
2032  inner_itlist,
2033  (Index) 0,
2034  rtoffset,
2035  NUM_EXEC_TLIST((Plan *) join));
2036  join->plan.qual = fix_join_expr(root,
2037  join->plan.qual,
2038  outer_itlist,
2039  inner_itlist,
2040  (Index) 0,
2041  rtoffset,
2042  NUM_EXEC_QUAL((Plan *) join));
2043 
2044  pfree(outer_itlist);
2045  pfree(inner_itlist);
2046 }
2047 
2048 /*
2049  * set_upper_references
2050  * Update the targetlist and quals of an upper-level plan node
2051  * to refer to the tuples returned by its lefttree subplan.
2052  * Also perform opcode lookup for these expressions, and
2053  * add regclass OIDs to root->glob->relationOids.
2054  *
2055  * This is used for single-input plan types like Agg, Group, Result.
2056  *
2057  * In most cases, we have to match up individual Vars in the tlist and
2058  * qual expressions with elements of the subplan's tlist (which was
2059  * generated by flattening these selfsame expressions, so it should have all
2060  * the required variables). There is an important exception, however:
2061  * depending on where we are in the plan tree, sort/group columns may have
2062  * been pushed into the subplan tlist unflattened. If these values are also
2063  * needed in the output then we want to reference the subplan tlist element
2064  * rather than recomputing the expression.
2065  */
2066 static void
2067 set_upper_references(PlannerInfo *root, Plan *plan, int rtoffset)
2068 {
2069  Plan *subplan = plan->lefttree;
2070  indexed_tlist *subplan_itlist;
2071  List *output_targetlist;
2072  ListCell *l;
2073 
2074  subplan_itlist = build_tlist_index(subplan->targetlist);
2075 
2076  output_targetlist = NIL;
2077  foreach(l, plan->targetlist)
2078  {
2079  TargetEntry *tle = (TargetEntry *) lfirst(l);
2080  Node *newexpr;
2081 
2082  /* If it's a sort/group item, first try to match by sortref */
2083  if (tle->ressortgroupref != 0)
2084  {
2085  newexpr = (Node *)
2087  tle->ressortgroupref,
2088  subplan_itlist,
2089  OUTER_VAR);
2090  if (!newexpr)
2091  newexpr = fix_upper_expr(root,
2092  (Node *) tle->expr,
2093  subplan_itlist,
2094  OUTER_VAR,
2095  rtoffset,
2096  NUM_EXEC_TLIST(plan));
2097  }
2098  else
2099  newexpr = fix_upper_expr(root,
2100  (Node *) tle->expr,
2101  subplan_itlist,
2102  OUTER_VAR,
2103  rtoffset,
2104  NUM_EXEC_TLIST(plan));
2105  tle = flatCopyTargetEntry(tle);
2106  tle->expr = (Expr *) newexpr;
2107  output_targetlist = lappend(output_targetlist, tle);
2108  }
2109  plan->targetlist = output_targetlist;
2110 
2111  plan->qual = (List *)
2112  fix_upper_expr(root,
2113  (Node *) plan->qual,
2114  subplan_itlist,
2115  OUTER_VAR,
2116  rtoffset,
2117  NUM_EXEC_QUAL(plan));
2118 
2119  pfree(subplan_itlist);
2120 }
2121 
2122 /*
2123  * set_param_references
2124  * Initialize the initParam list in Gather or Gather merge node such that
2125  * it contains reference of all the params that needs to be evaluated
2126  * before execution of the node. It contains the initplan params that are
2127  * being passed to the plan nodes below it.
2128  */
2129 static void
2131 {
2132  Assert(IsA(plan, Gather) || IsA(plan, GatherMerge));
2133 
2134  if (plan->lefttree->extParam)
2135  {
2136  PlannerInfo *proot;
2137  Bitmapset *initSetParam = NULL;
2138  ListCell *l;
2139 
2140  for (proot = root; proot != NULL; proot = proot->parent_root)
2141  {
2142  foreach(l, proot->init_plans)
2143  {
2144  SubPlan *initsubplan = (SubPlan *) lfirst(l);
2145  ListCell *l2;
2146 
2147  foreach(l2, initsubplan->setParam)
2148  {
2149  initSetParam = bms_add_member(initSetParam, lfirst_int(l2));
2150  }
2151  }
2152  }
2153 
2154  /*
2155  * Remember the list of all external initplan params that are used by
2156  * the children of Gather or Gather merge node.
2157  */
2158  if (IsA(plan, Gather))
2159  ((Gather *) plan)->initParam =
2160  bms_intersect(plan->lefttree->extParam, initSetParam);
2161  else
2162  ((GatherMerge *) plan)->initParam =
2163  bms_intersect(plan->lefttree->extParam, initSetParam);
2164  }
2165 }
2166 
2167 /*
2168  * Recursively scan an expression tree and convert Aggrefs to the proper
2169  * intermediate form for combining aggregates. This means (1) replacing each
2170  * one's argument list with a single argument that is the original Aggref
2171  * modified to show partial aggregation and (2) changing the upper Aggref to
2172  * show combining aggregation.
2173  *
2174  * After this step, set_upper_references will replace the partial Aggrefs
2175  * with Vars referencing the lower Agg plan node's outputs, so that the final
2176  * form seen by the executor is a combining Aggref with a Var as input.
2177  *
2178  * It's rather messy to postpone this step until setrefs.c; ideally it'd be
2179  * done in createplan.c. The difficulty is that once we modify the Aggref
2180  * expressions, they will no longer be equal() to their original form and
2181  * so cross-plan-node-level matches will fail. So this has to happen after
2182  * the plan node above the Agg has resolved its subplan references.
2183  */
2184 static Node *
2185 convert_combining_aggrefs(Node *node, void *context)
2186 {
2187  if (node == NULL)
2188  return NULL;
2189  if (IsA(node, Aggref))
2190  {
2191  Aggref *orig_agg = (Aggref *) node;
2192  Aggref *child_agg;
2193  Aggref *parent_agg;
2194 
2195  /* Assert we've not chosen to partial-ize any unsupported cases */
2196  Assert(orig_agg->aggorder == NIL);
2197  Assert(orig_agg->aggdistinct == NIL);
2198 
2199  /*
2200  * Since aggregate calls can't be nested, we needn't recurse into the
2201  * arguments. But for safety, flat-copy the Aggref node itself rather
2202  * than modifying it in-place.
2203  */
2204  child_agg = makeNode(Aggref);
2205  memcpy(child_agg, orig_agg, sizeof(Aggref));
2206 
2207  /*
2208  * For the parent Aggref, we want to copy all the fields of the
2209  * original aggregate *except* the args list, which we'll replace
2210  * below, and the aggfilter expression, which should be applied only
2211  * by the child not the parent. Rather than explicitly knowing about
2212  * all the other fields here, we can momentarily modify child_agg to
2213  * provide a suitable source for copyObject.
2214  */
2215  child_agg->args = NIL;
2216  child_agg->aggfilter = NULL;
2217  parent_agg = copyObject(child_agg);
2218  child_agg->args = orig_agg->args;
2219  child_agg->aggfilter = orig_agg->aggfilter;
2220 
2221  /*
2222  * Now, set up child_agg to represent the first phase of partial
2223  * aggregation. For now, assume serialization is required.
2224  */
2226 
2227  /*
2228  * And set up parent_agg to represent the second phase.
2229  */
2230  parent_agg->args = list_make1(makeTargetEntry((Expr *) child_agg,
2231  1, NULL, false));
2233 
2234  return (Node *) parent_agg;
2235  }
2237  (void *) context);
2238 }
2239 
2240 /*
2241  * set_dummy_tlist_references
2242  * Replace the targetlist of an upper-level plan node with a simple
2243  * list of OUTER_VAR references to its child.
2244  *
2245  * This is used for plan types like Sort and Append that don't evaluate
2246  * their targetlists. Although the executor doesn't care at all what's in
2247  * the tlist, EXPLAIN needs it to be realistic.
2248  *
2249  * Note: we could almost use set_upper_references() here, but it fails for
2250  * Append for lack of a lefttree subplan. Single-purpose code is faster
2251  * anyway.
2252  */
2253 static void
2254 set_dummy_tlist_references(Plan *plan, int rtoffset)
2255 {
2256  List *output_targetlist;
2257  ListCell *l;
2258 
2259  output_targetlist = NIL;
2260  foreach(l, plan->targetlist)
2261  {
2262  TargetEntry *tle = (TargetEntry *) lfirst(l);
2263  Var *oldvar = (Var *) tle->expr;
2264  Var *newvar;
2265 
2266  /*
2267  * As in search_indexed_tlist_for_non_var(), we prefer to keep Consts
2268  * as Consts, not Vars referencing Consts. Here, there's no speed
2269  * advantage to be had, but it makes EXPLAIN output look cleaner, and
2270  * again it avoids confusing the executor.
2271  */
2272  if (IsA(oldvar, Const))
2273  {
2274  /* just reuse the existing TLE node */
2275  output_targetlist = lappend(output_targetlist, tle);
2276  continue;
2277  }
2278 
2279  newvar = makeVar(OUTER_VAR,
2280  tle->resno,
2281  exprType((Node *) oldvar),
2282  exprTypmod((Node *) oldvar),
2283  exprCollation((Node *) oldvar),
2284  0);
2285  if (IsA(oldvar, Var) &&
2286  oldvar->varnosyn > 0)
2287  {
2288  newvar->varnosyn = oldvar->varnosyn + rtoffset;
2289  newvar->varattnosyn = oldvar->varattnosyn;
2290  }
2291  else
2292  {
2293  newvar->varnosyn = 0; /* wasn't ever a plain Var */
2294  newvar->varattnosyn = 0;
2295  }
2296 
2297  tle = flatCopyTargetEntry(tle);
2298  tle->expr = (Expr *) newvar;
2299  output_targetlist = lappend(output_targetlist, tle);
2300  }
2301  plan->targetlist = output_targetlist;
2302 
2303  /* We don't touch plan->qual here */
2304 }
2305 
2306 
2307 /*
2308  * build_tlist_index --- build an index data structure for a child tlist
2309  *
2310  * In most cases, subplan tlists will be "flat" tlists with only Vars,
2311  * so we try to optimize that case by extracting information about Vars
2312  * in advance. Matching a parent tlist to a child is still an O(N^2)
2313  * operation, but at least with a much smaller constant factor than plain
2314  * tlist_member() searches.
2315  *
2316  * The result of this function is an indexed_tlist struct to pass to
2317  * search_indexed_tlist_for_var() or search_indexed_tlist_for_non_var().
2318  * When done, the indexed_tlist may be freed with a single pfree().
2319  */
2320 static indexed_tlist *
2322 {
2323  indexed_tlist *itlist;
2324  tlist_vinfo *vinfo;
2325  ListCell *l;
2326 
2327  /* Create data structure with enough slots for all tlist entries */
2328  itlist = (indexed_tlist *)
2330  list_length(tlist) * sizeof(tlist_vinfo));
2331 
2332  itlist->tlist = tlist;
2333  itlist->has_ph_vars = false;
2334  itlist->has_non_vars = false;
2335 
2336  /* Find the Vars and fill in the index array */
2337  vinfo = itlist->vars;
2338  foreach(l, tlist)
2339  {
2340  TargetEntry *tle = (TargetEntry *) lfirst(l);
2341 
2342  if (tle->expr && IsA(tle->expr, Var))
2343  {
2344  Var *var = (Var *) tle->expr;
2345 
2346  vinfo->varno = var->varno;
2347  vinfo->varattno = var->varattno;
2348  vinfo->resno = tle->resno;
2349  vinfo++;
2350  }
2351  else if (tle->expr && IsA(tle->expr, PlaceHolderVar))
2352  itlist->has_ph_vars = true;
2353  else
2354  itlist->has_non_vars = true;
2355  }
2356 
2357  itlist->num_vars = (vinfo - itlist->vars);
2358 
2359  return itlist;
2360 }
2361 
2362 /*
2363  * build_tlist_index_other_vars --- build a restricted tlist index
2364  *
2365  * This is like build_tlist_index, but we only index tlist entries that
2366  * are Vars belonging to some rel other than the one specified. We will set
2367  * has_ph_vars (allowing PlaceHolderVars to be matched), but not has_non_vars
2368  * (so nothing other than Vars and PlaceHolderVars can be matched).
2369  */
2370 static indexed_tlist *
2372 {
2373  indexed_tlist *itlist;
2374  tlist_vinfo *vinfo;
2375  ListCell *l;
2376 
2377  /* Create data structure with enough slots for all tlist entries */
2378  itlist = (indexed_tlist *)
2380  list_length(tlist) * sizeof(tlist_vinfo));
2381 
2382  itlist->tlist = tlist;
2383  itlist->has_ph_vars = false;
2384  itlist->has_non_vars = false;
2385 
2386  /* Find the desired Vars and fill in the index array */
2387  vinfo = itlist->vars;
2388  foreach(l, tlist)
2389  {
2390  TargetEntry *tle = (TargetEntry *) lfirst(l);
2391 
2392  if (tle->expr && IsA(tle->expr, Var))
2393  {
2394  Var *var = (Var *) tle->expr;
2395 
2396  if (var->varno != ignore_rel)
2397  {
2398  vinfo->varno = var->varno;
2399  vinfo->varattno = var->varattno;
2400  vinfo->resno = tle->resno;
2401  vinfo++;
2402  }
2403  }
2404  else if (tle->expr && IsA(tle->expr, PlaceHolderVar))
2405  itlist->has_ph_vars = true;
2406  }
2407 
2408  itlist->num_vars = (vinfo - itlist->vars);
2409 
2410  return itlist;
2411 }
2412 
2413 /*
2414  * search_indexed_tlist_for_var --- find a Var in an indexed tlist
2415  *
2416  * If a match is found, return a copy of the given Var with suitably
2417  * modified varno/varattno (to wit, newvarno and the resno of the TLE entry).
2418  * Also ensure that varnosyn is incremented by rtoffset.
2419  * If no match, return NULL.
2420  */
2421 static Var *
2423  Index newvarno, int rtoffset)
2424 {
2425  Index varno = var->varno;
2426  AttrNumber varattno = var->varattno;
2427  tlist_vinfo *vinfo;
2428  int i;
2429 
2430  vinfo = itlist->vars;
2431  i = itlist->num_vars;
2432  while (i-- > 0)
2433  {
2434  if (vinfo->varno == varno && vinfo->varattno == varattno)
2435  {
2436  /* Found a match */
2437  Var *newvar = copyVar(var);
2438 
2439  newvar->varno = newvarno;
2440  newvar->varattno = vinfo->resno;
2441  if (newvar->varnosyn > 0)
2442  newvar->varnosyn += rtoffset;
2443  return newvar;
2444  }
2445  vinfo++;
2446  }
2447  return NULL; /* no match */
2448 }
2449 
2450 /*
2451  * search_indexed_tlist_for_non_var --- find a non-Var in an indexed tlist
2452  *
2453  * If a match is found, return a Var constructed to reference the tlist item.
2454  * If no match, return NULL.
2455  *
2456  * NOTE: it is a waste of time to call this unless itlist->has_ph_vars or
2457  * itlist->has_non_vars. Furthermore, set_join_references() relies on being
2458  * able to prevent matching of non-Vars by clearing itlist->has_non_vars,
2459  * so there's a correctness reason not to call it unless that's set.
2460  */
2461 static Var *
2463  indexed_tlist *itlist, Index newvarno)
2464 {
2465  TargetEntry *tle;
2466 
2467  /*
2468  * If it's a simple Const, replacing it with a Var is silly, even if there
2469  * happens to be an identical Const below; a Var is more expensive to
2470  * execute than a Const. What's more, replacing it could confuse some
2471  * places in the executor that expect to see simple Consts for, eg,
2472  * dropped columns.
2473  */
2474  if (IsA(node, Const))
2475  return NULL;
2476 
2477  tle = tlist_member(node, itlist->tlist);
2478  if (tle)
2479  {
2480  /* Found a matching subplan output expression */
2481  Var *newvar;
2482 
2483  newvar = makeVarFromTargetEntry(newvarno, tle);
2484  newvar->varnosyn = 0; /* wasn't ever a plain Var */
2485  newvar->varattnosyn = 0;
2486  return newvar;
2487  }
2488  return NULL; /* no match */
2489 }
2490 
2491 /*
2492  * search_indexed_tlist_for_sortgroupref --- find a sort/group expression
2493  *
2494  * If a match is found, return a Var constructed to reference the tlist item.
2495  * If no match, return NULL.
2496  *
2497  * This is needed to ensure that we select the right subplan TLE in cases
2498  * where there are multiple textually-equal()-but-volatile sort expressions.
2499  * And it's also faster than search_indexed_tlist_for_non_var.
2500  */
2501 static Var *
2503  Index sortgroupref,
2504  indexed_tlist *itlist,
2505  Index newvarno)
2506 {
2507  ListCell *lc;
2508 
2509  foreach(lc, itlist->tlist)
2510  {
2511  TargetEntry *tle = (TargetEntry *) lfirst(lc);
2512 
2513  /* The equal() check should be redundant, but let's be paranoid */
2514  if (tle->ressortgroupref == sortgroupref &&
2515  equal(node, tle->expr))
2516  {
2517  /* Found a matching subplan output expression */
2518  Var *newvar;
2519 
2520  newvar = makeVarFromTargetEntry(newvarno, tle);
2521  newvar->varnosyn = 0; /* wasn't ever a plain Var */
2522  newvar->varattnosyn = 0;
2523  return newvar;
2524  }
2525  }
2526  return NULL; /* no match */
2527 }
2528 
2529 /*
2530  * fix_join_expr
2531  * Create a new set of targetlist entries or join qual clauses by
2532  * changing the varno/varattno values of variables in the clauses
2533  * to reference target list values from the outer and inner join
2534  * relation target lists. Also perform opcode lookup and add
2535  * regclass OIDs to root->glob->relationOids.
2536  *
2537  * This is used in three different scenarios:
2538  * 1) a normal join clause, where all the Vars in the clause *must* be
2539  * replaced by OUTER_VAR or INNER_VAR references. In this case
2540  * acceptable_rel should be zero so that any failure to match a Var will be
2541  * reported as an error.
2542  * 2) RETURNING clauses, which may contain both Vars of the target relation
2543  * and Vars of other relations. In this case we want to replace the
2544  * other-relation Vars by OUTER_VAR references, while leaving target Vars
2545  * alone. Thus inner_itlist = NULL and acceptable_rel = the ID of the
2546  * target relation should be passed.
2547  * 3) ON CONFLICT UPDATE SET/WHERE clauses. Here references to EXCLUDED are
2548  * to be replaced with INNER_VAR references, while leaving target Vars (the
2549  * to-be-updated relation) alone. Correspondingly inner_itlist is to be
2550  * EXCLUDED elements, outer_itlist = NULL and acceptable_rel the target
2551  * relation.
2552  *
2553  * 'clauses' is the targetlist or list of join clauses
2554  * 'outer_itlist' is the indexed target list of the outer join relation,
2555  * or NULL
2556  * 'inner_itlist' is the indexed target list of the inner join relation,
2557  * or NULL
2558  * 'acceptable_rel' is either zero or the rangetable index of a relation
2559  * whose Vars may appear in the clause without provoking an error
2560  * 'rtoffset': how much to increment varnos by
2561  * 'num_exec': estimated number of executions of expression
2562  *
2563  * Returns the new expression tree. The original clause structure is
2564  * not modified.
2565  */
2566 static List *
2568  List *clauses,
2569  indexed_tlist *outer_itlist,
2570  indexed_tlist *inner_itlist,
2571  Index acceptable_rel,
2572  int rtoffset,
2573  double num_exec)
2574 {
2575  fix_join_expr_context context;
2576 
2577  context.root = root;
2578  context.outer_itlist = outer_itlist;
2579  context.inner_itlist = inner_itlist;
2580  context.acceptable_rel = acceptable_rel;
2581  context.rtoffset = rtoffset;
2582  context.num_exec = num_exec;
2583  return (List *) fix_join_expr_mutator((Node *) clauses, &context);
2584 }
2585 
2586 static Node *
2588 {
2589  Var *newvar;
2590 
2591  if (node == NULL)
2592  return NULL;
2593  if (IsA(node, Var))
2594  {
2595  Var *var = (Var *) node;
2596 
2597  /* Look for the var in the input tlists, first in the outer */
2598  if (context->outer_itlist)
2599  {
2600  newvar = search_indexed_tlist_for_var(var,
2601  context->outer_itlist,
2602  OUTER_VAR,
2603  context->rtoffset);
2604  if (newvar)
2605  return (Node *) newvar;
2606  }
2607 
2608  /* then in the inner. */
2609  if (context->inner_itlist)
2610  {
2611  newvar = search_indexed_tlist_for_var(var,
2612  context->inner_itlist,
2613  INNER_VAR,
2614  context->rtoffset);
2615  if (newvar)
2616  return (Node *) newvar;
2617  }
2618 
2619  /* If it's for acceptable_rel, adjust and return it */
2620  if (var->varno == context->acceptable_rel)
2621  {
2622  var = copyVar(var);
2623  var->varno += context->rtoffset;
2624  if (var->varnosyn > 0)
2625  var->varnosyn += context->rtoffset;
2626  return (Node *) var;
2627  }
2628 
2629  /* No referent found for Var */
2630  elog(ERROR, "variable not found in subplan target lists");
2631  }
2632  if (IsA(node, PlaceHolderVar))
2633  {
2634  PlaceHolderVar *phv = (PlaceHolderVar *) node;
2635 
2636  /* See if the PlaceHolderVar has bubbled up from a lower plan node */
2637  if (context->outer_itlist && context->outer_itlist->has_ph_vars)
2638  {
2639  newvar = search_indexed_tlist_for_non_var((Expr *) phv,
2640  context->outer_itlist,
2641  OUTER_VAR);
2642  if (newvar)
2643  return (Node *) newvar;
2644  }
2645  if (context->inner_itlist && context->inner_itlist->has_ph_vars)
2646  {
2647  newvar = search_indexed_tlist_for_non_var((Expr *) phv,
2648  context->inner_itlist,
2649  INNER_VAR);
2650  if (newvar)
2651  return (Node *) newvar;
2652  }
2653 
2654  /* If not supplied by input plans, evaluate the contained expr */
2655  return fix_join_expr_mutator((Node *) phv->phexpr, context);
2656  }
2657  /* Try matching more complex expressions too, if tlists have any */
2658  if (context->outer_itlist && context->outer_itlist->has_non_vars)
2659  {
2660  newvar = search_indexed_tlist_for_non_var((Expr *) node,
2661  context->outer_itlist,
2662  OUTER_VAR);
2663  if (newvar)
2664  return (Node *) newvar;
2665  }
2666  if (context->inner_itlist && context->inner_itlist->has_non_vars)
2667  {
2668  newvar = search_indexed_tlist_for_non_var((Expr *) node,
2669  context->inner_itlist,
2670  INNER_VAR);
2671  if (newvar)
2672  return (Node *) newvar;
2673  }
2674  /* Special cases (apply only AFTER failing to match to lower tlist) */
2675  if (IsA(node, Param))
2676  return fix_param_node(context->root, (Param *) node);
2677  if (IsA(node, AlternativeSubPlan))
2679  (AlternativeSubPlan *) node,
2680  context->num_exec),
2681  context);
2682  fix_expr_common(context->root, node);
2683  return expression_tree_mutator(node,
2685  (void *) context);
2686 }
2687 
2688 /*
2689  * fix_upper_expr
2690  * Modifies an expression tree so that all Var nodes reference outputs
2691  * of a subplan. Also looks for Aggref nodes that should be replaced
2692  * by initplan output Params. Also performs opcode lookup, and adds
2693  * regclass OIDs to root->glob->relationOids.
2694  *
2695  * This is used to fix up target and qual expressions of non-join upper-level
2696  * plan nodes, as well as index-only scan nodes.
2697  *
2698  * An error is raised if no matching var can be found in the subplan tlist
2699  * --- so this routine should only be applied to nodes whose subplans'
2700  * targetlists were generated by flattening the expressions used in the
2701  * parent node.
2702  *
2703  * If itlist->has_non_vars is true, then we try to match whole subexpressions
2704  * against elements of the subplan tlist, so that we can avoid recomputing
2705  * expressions that were already computed by the subplan. (This is relatively
2706  * expensive, so we don't want to try it in the common case where the
2707  * subplan tlist is just a flattened list of Vars.)
2708  *
2709  * 'node': the tree to be fixed (a target item or qual)
2710  * 'subplan_itlist': indexed target list for subplan (or index)
2711  * 'newvarno': varno to use for Vars referencing tlist elements
2712  * 'rtoffset': how much to increment varnos by
2713  * 'num_exec': estimated number of executions of expression
2714  *
2715  * The resulting tree is a copy of the original in which all Var nodes have
2716  * varno = newvarno, varattno = resno of corresponding targetlist element.
2717  * The original tree is not modified.
2718  */
2719 static Node *
2721  Node *node,
2722  indexed_tlist *subplan_itlist,
2723  Index newvarno,
2724  int rtoffset,
2725  double num_exec)
2726 {
2727  fix_upper_expr_context context;
2728 
2729  context.root = root;
2730  context.subplan_itlist = subplan_itlist;
2731  context.newvarno = newvarno;
2732  context.rtoffset = rtoffset;
2733  context.num_exec = num_exec;
2734  return fix_upper_expr_mutator(node, &context);
2735 }
2736 
2737 static Node *
2739 {
2740  Var *newvar;
2741 
2742  if (node == NULL)
2743  return NULL;
2744  if (IsA(node, Var))
2745  {
2746  Var *var = (Var *) node;
2747 
2748  newvar = search_indexed_tlist_for_var(var,
2749  context->subplan_itlist,
2750  context->newvarno,
2751  context->rtoffset);
2752  if (!newvar)
2753  elog(ERROR, "variable not found in subplan target list");
2754  return (Node *) newvar;
2755  }
2756  if (IsA(node, PlaceHolderVar))
2757  {
2758  PlaceHolderVar *phv = (PlaceHolderVar *) node;
2759 
2760  /* See if the PlaceHolderVar has bubbled up from a lower plan node */
2761  if (context->subplan_itlist->has_ph_vars)
2762  {
2763  newvar = search_indexed_tlist_for_non_var((Expr *) phv,
2764  context->subplan_itlist,
2765  context->newvarno);
2766  if (newvar)
2767  return (Node *) newvar;
2768  }
2769  /* If not supplied by input plan, evaluate the contained expr */
2770  return fix_upper_expr_mutator((Node *) phv->phexpr, context);
2771  }
2772  /* Try matching more complex expressions too, if tlist has any */
2773  if (context->subplan_itlist->has_non_vars)
2774  {
2775  newvar = search_indexed_tlist_for_non_var((Expr *) node,
2776  context->subplan_itlist,
2777  context->newvarno);
2778  if (newvar)
2779  return (Node *) newvar;
2780  }
2781  /* Special cases (apply only AFTER failing to match to lower tlist) */
2782  if (IsA(node, Param))
2783  return fix_param_node(context->root, (Param *) node);
2784  if (IsA(node, Aggref))
2785  {
2786  Aggref *aggref = (Aggref *) node;
2787 
2788  /* See if the Aggref should be replaced by a Param */
2789  if (context->root->minmax_aggs != NIL &&
2790  list_length(aggref->args) == 1)
2791  {
2792  TargetEntry *curTarget = (TargetEntry *) linitial(aggref->args);
2793  ListCell *lc;
2794 
2795  foreach(lc, context->root->minmax_aggs)
2796  {
2797  MinMaxAggInfo *mminfo = (MinMaxAggInfo *) lfirst(lc);
2798 
2799  if (mminfo->aggfnoid == aggref->aggfnoid &&
2800  equal(mminfo->target, curTarget->expr))
2801  return (Node *) copyObject(mminfo->param);
2802  }
2803  }
2804  /* If no match, just fall through to process it normally */
2805  }
2806  if (IsA(node, AlternativeSubPlan))
2808  (AlternativeSubPlan *) node,
2809  context->num_exec),
2810  context);
2811  fix_expr_common(context->root, node);
2812  return expression_tree_mutator(node,
2814  (void *) context);
2815 }
2816 
2817 /*
2818  * set_returning_clause_references
2819  * Perform setrefs.c's work on a RETURNING targetlist
2820  *
2821  * If the query involves more than just the result table, we have to
2822  * adjust any Vars that refer to other tables to reference junk tlist
2823  * entries in the top subplan's targetlist. Vars referencing the result
2824  * table should be left alone, however (the executor will evaluate them
2825  * using the actual heap tuple, after firing triggers if any). In the
2826  * adjusted RETURNING list, result-table Vars will have their original
2827  * varno (plus rtoffset), but Vars for other rels will have varno OUTER_VAR.
2828  *
2829  * We also must perform opcode lookup and add regclass OIDs to
2830  * root->glob->relationOids.
2831  *
2832  * 'rlist': the RETURNING targetlist to be fixed
2833  * 'topplan': the top subplan node that will be just below the ModifyTable
2834  * node (note it's not yet passed through set_plan_refs)
2835  * 'resultRelation': RT index of the associated result relation
2836  * 'rtoffset': how much to increment varnos by
2837  *
2838  * Note: the given 'root' is for the parent query level, not the 'topplan'.
2839  * This does not matter currently since we only access the dependency-item
2840  * lists in root->glob, but it would need some hacking if we wanted a root
2841  * that actually matches the subplan.
2842  *
2843  * Note: resultRelation is not yet adjusted by rtoffset.
2844  */
2845 static List *
2847  List *rlist,
2848  Plan *topplan,
2849  Index resultRelation,
2850  int rtoffset)
2851 {
2852  indexed_tlist *itlist;
2853 
2854  /*
2855  * We can perform the desired Var fixup by abusing the fix_join_expr
2856  * machinery that formerly handled inner indexscan fixup. We search the
2857  * top plan's targetlist for Vars of non-result relations, and use
2858  * fix_join_expr to convert RETURNING Vars into references to those tlist
2859  * entries, while leaving result-rel Vars as-is.
2860  *
2861  * PlaceHolderVars will also be sought in the targetlist, but no
2862  * more-complex expressions will be. Note that it is not possible for a
2863  * PlaceHolderVar to refer to the result relation, since the result is
2864  * never below an outer join. If that case could happen, we'd have to be
2865  * prepared to pick apart the PlaceHolderVar and evaluate its contained
2866  * expression instead.
2867  */
2868  itlist = build_tlist_index_other_vars(topplan->targetlist, resultRelation);
2869 
2870  rlist = fix_join_expr(root,
2871  rlist,
2872  itlist,
2873  NULL,
2874  resultRelation,
2875  rtoffset,
2876  NUM_EXEC_TLIST(topplan));
2877 
2878  pfree(itlist);
2879 
2880  return rlist;
2881 }
2882 
2883 
2884 /*****************************************************************************
2885  * QUERY DEPENDENCY MANAGEMENT
2886  *****************************************************************************/
2887 
2888 /*
2889  * record_plan_function_dependency
2890  * Mark the current plan as depending on a particular function.
2891  *
2892  * This is exported so that the function-inlining code can record a
2893  * dependency on a function that it's removed from the plan tree.
2894  */
2895 void
2897 {
2898  /*
2899  * For performance reasons, we don't bother to track built-in functions;
2900  * we just assume they'll never change (or at least not in ways that'd
2901  * invalidate plans using them). For this purpose we can consider a
2902  * built-in function to be one with OID less than FirstBootstrapObjectId.
2903  * Note that the OID generator guarantees never to generate such an OID
2904  * after startup, even at OID wraparound.
2905  */
2906  if (funcid >= (Oid) FirstBootstrapObjectId)
2907  {
2908  PlanInvalItem *inval_item = makeNode(PlanInvalItem);
2909 
2910  /*
2911  * It would work to use any syscache on pg_proc, but the easiest is
2912  * PROCOID since we already have the function's OID at hand. Note
2913  * that plancache.c knows we use PROCOID.
2914  */
2915  inval_item->cacheId = PROCOID;
2916  inval_item->hashValue = GetSysCacheHashValue1(PROCOID,
2917  ObjectIdGetDatum(funcid));
2918 
2919  root->glob->invalItems = lappend(root->glob->invalItems, inval_item);
2920  }
2921 }
2922 
2923 /*
2924  * record_plan_type_dependency
2925  * Mark the current plan as depending on a particular type.
2926  *
2927  * This is exported so that eval_const_expressions can record a
2928  * dependency on a domain that it's removed a CoerceToDomain node for.
2929  *
2930  * We don't currently need to record dependencies on domains that the
2931  * plan contains CoerceToDomain nodes for, though that might change in
2932  * future. Hence, this isn't actually called in this module, though
2933  * someday fix_expr_common might call it.
2934  */
2935 void
2937 {
2938  /*
2939  * As in record_plan_function_dependency, ignore the possibility that
2940  * someone would change a built-in domain.
2941  */
2942  if (typid >= (Oid) FirstBootstrapObjectId)
2943  {
2944  PlanInvalItem *inval_item = makeNode(PlanInvalItem);
2945 
2946  /*
2947  * It would work to use any syscache on pg_type, but the easiest is
2948  * TYPEOID since we already have the type's OID at hand. Note that
2949  * plancache.c knows we use TYPEOID.
2950  */
2951  inval_item->cacheId = TYPEOID;
2952  inval_item->hashValue = GetSysCacheHashValue1(TYPEOID,
2953  ObjectIdGetDatum(typid));
2954 
2955  root->glob->invalItems = lappend(root->glob->invalItems, inval_item);
2956  }
2957 }
2958 
2959 /*
2960  * extract_query_dependencies
2961  * Given a rewritten, but not yet planned, query or queries
2962  * (i.e. a Query node or list of Query nodes), extract dependencies
2963  * just as set_plan_references would do. Also detect whether any
2964  * rewrite steps were affected by RLS.
2965  *
2966  * This is needed by plancache.c to handle invalidation of cached unplanned
2967  * queries.
2968  *
2969  * Note: this does not go through eval_const_expressions, and hence doesn't
2970  * reflect its additions of inlined functions and elided CoerceToDomain nodes
2971  * to the invalItems list. This is obviously OK for functions, since we'll
2972  * see them in the original query tree anyway. For domains, it's OK because
2973  * we don't care about domains unless they get elided. That is, a plan might
2974  * have domain dependencies that the query tree doesn't.
2975  */
2976 void
2978  List **relationOids,
2979  List **invalItems,
2980  bool *hasRowSecurity)
2981 {
2982  PlannerGlobal glob;
2983  PlannerInfo root;
2984 
2985  /* Make up dummy planner state so we can use this module's machinery */
2986  MemSet(&glob, 0, sizeof(glob));
2987  glob.type = T_PlannerGlobal;
2988  glob.relationOids = NIL;
2989  glob.invalItems = NIL;
2990  /* Hack: we use glob.dependsOnRole to collect hasRowSecurity flags */
2991  glob.dependsOnRole = false;
2992 
2993  MemSet(&root, 0, sizeof(root));
2994  root.type = T_PlannerInfo;
2995  root.glob = &glob;
2996 
2997  (void) extract_query_dependencies_walker(query, &root);
2998 
2999  *relationOids = glob.relationOids;
3000  *invalItems = glob.invalItems;
3001  *hasRowSecurity = glob.dependsOnRole;
3002 }
3003 
3004 /*
3005  * Tree walker for extract_query_dependencies.
3006  *
3007  * This is exported so that expression_planner_with_deps can call it on
3008  * simple expressions (post-planning, not before planning, in that case).
3009  * In that usage, glob.dependsOnRole isn't meaningful, but the relationOids
3010  * and invalItems lists are added to as needed.
3011  */
3012 bool
3014 {
3015  if (node == NULL)
3016  return false;
3017  Assert(!IsA(node, PlaceHolderVar));
3018  if (IsA(node, Query))
3019  {
3020  Query *query = (Query *) node;
3021  ListCell *lc;
3022 
3023  if (query->commandType == CMD_UTILITY)
3024  {
3025  /*
3026  * Ignore utility statements, except those (such as EXPLAIN) that
3027  * contain a parsed-but-not-planned query.
3028  */
3029  query = UtilityContainsQuery(query->utilityStmt);
3030  if (query == NULL)
3031  return false;
3032  }
3033 
3034  /* Remember if any Query has RLS quals applied by rewriter */
3035  if (query->hasRowSecurity)
3036  context->glob->dependsOnRole = true;
3037 
3038  /* Collect relation OIDs in this Query's rtable */
3039  foreach(lc, query->rtable)
3040  {
3041  RangeTblEntry *rte = (RangeTblEntry *) lfirst(lc);
3042 
3043  if (rte->rtekind == RTE_RELATION)
3044  context->glob->relationOids =
3045  lappend_oid(context->glob->relationOids, rte->relid);
3046  else if (rte->rtekind == RTE_NAMEDTUPLESTORE &&
3047  OidIsValid(rte->relid))
3048  context->glob->relationOids =
3049  lappend_oid(context->glob->relationOids,
3050  rte->relid);
3051  }
3052 
3053  /* And recurse into the query's subexpressions */
3055  (void *) context, 0);
3056  }
3057  /* Extract function dependencies and check for regclass Consts */
3058  fix_expr_common(context, node);
3060  (void *) context);
3061 }
Datum constvalue
Definition: primnodes.h:214
List * aggdistinct
Definition: primnodes.h:321
List * bitmapplans
Definition: plannodes.h:319
#define NIL
Definition: pg_list.h:65
List * rowMarks
Definition: pathnodes.h:292
Plan plan
Definition: plannodes.h:188
void apply_tlist_labeling(List *dest_tlist, List *src_tlist)
Definition: tlist.c:340
bool query_tree_walker(Query *query, bool(*walker)(), void *context, int flags)
Definition: nodeFuncs.c:2322
List * qual
Definition: plannodes.h:143
Index varno
Definition: setrefs.c:34
static Node * fix_alternative_subplan(PlannerInfo *root, AlternativeSubPlan *asplan, double num_exec)
Definition: setrefs.c:1725
#define ISREGCLASSCONST(con)
Definition: setrefs.c:100
Definition: nodes.h:79
#define fix_scan_list(root, lst, rtoffset, num_exec)
Definition: setrefs.c:104
Plan plan
Definition: plannodes.h:344
#define IsA(nodeptr, _type_)
Definition: nodes.h:579
Query * parse
Definition: pathnodes.h:179
indexed_tlist * inner_itlist
Definition: setrefs.c:59
List * joinaliasvars
Definition: parsenodes.h:1052
Index varlevelsup
Definition: primnodes.h:191
Node * expression_tree_mutator(Node *node, Node *(*mutator)(), void *context)
Definition: nodeFuncs.c:2565
Plan plan
Definition: plannodes.h:982
#define forboth(cell1, list1, cell2, list2)
Definition: pg_list.h:434
Index nominalRelation
Definition: plannodes.h:223
int plan_id
Definition: primnodes.h:709
static Node * fix_param_node(PlannerInfo *root, Param *p)
Definition: setrefs.c:1693
Definition: nodes.h:81
Index scanrelid
Definition: plannodes.h:345
tlist_vinfo vars[FLEXIBLE_ARRAY_MEMBER]
Definition: setrefs.c:45
List * refs
Definition: primnodes.h:361
List * nestParams
Definition: plannodes.h:703
Plan plan
Definition: plannodes.h:968
List * hashkeys
Definition: plannodes.h:751
static ListCell * list_nth_cell(const List *list, int n)
Definition: pg_list.h:244
static void flatten_unplanned_rtes(PlannerGlobal *glob, RangeTblEntry *rte)
Definition: setrefs.c:400
bool equal(const void *a, const void *b)
Definition: equalfuncs.c:3032
AttrNumber resno
Definition: setrefs.c:36
PlannerInfo * parent_root
Definition: pathnodes.h:185
List * withCheckOptionLists
Definition: plannodes.h:230
#define QTW_EXAMINE_RTES_BEFORE
Definition: nodeFuncs.h:25
List * functions
Definition: plannodes.h:525
static void set_join_references(PlannerInfo *root, Join *join, int rtoffset)
Definition: setrefs.c:1916
int resultRelIndex
Definition: plannodes.h:227
int32 exprTypmod(const Node *expr)
Definition: nodeFuncs.c:275
#define forthree(cell1, list1, cell2, list2, cell3, list3)
Definition: pg_list.h:479
List * hashclauses
Definition: plannodes.h:743
List * securityQuals
Definition: parsenodes.h:1126
#define DatumGetObjectId(X)
Definition: postgres.h:500
int lastPlanNodeId
Definition: pathnodes.h:137
List * indexqual
Definition: plannodes.h:463
List * coltypmods
Definition: parsenodes.h:1103
Param * param
Definition: pathnodes.h:2330
List * tidquals
Definition: plannodes.h:493
int bms_next_member(const Bitmapset *a, int prevbit)
Definition: bitmapset.c:1043
TableFunc * tablefunc
Definition: plannodes.h:546
void mark_partial_aggref(Aggref *agg, AggSplit aggsplit)
Definition: planner.c:5418
int plan_node_id
Definition: plannodes.h:141
List * resultRelations
Definition: pathnodes.h:121
List * indexqualorig
Definition: plannodes.h:407
Var * makeVarFromTargetEntry(Index varno, TargetEntry *tle)
Definition: makefuncs.c:103
struct TableSampleClause * tablesample
Definition: plannodes.h:362
PlannerInfo * root
Definition: setrefs.c:50
ParamKind paramkind
Definition: primnodes.h:262
#define FLEXIBLE_ARRAY_MEMBER
Definition: c.h:283
Definition: nodes.h:528
List * appendRelations
Definition: pathnodes.h:125
List * list_concat(List *list1, const List *list2)
Definition: list.c:515
Definition: nodes.h:49
int errcode(int sqlerrcode)
Definition: elog.c:610
List * args
Definition: primnodes.h:319
Index prti
Definition: plannodes.h:1078
#define MemSet(start, val, len)
Definition: c.h:949
AttrNumber varattno
Definition: primnodes.h:186
List * values_lists
Definition: plannodes.h:536
static void set_param_references(PlannerInfo *root, Plan *plan)
Definition: setrefs.c:2130
List * minmax_aggs
Definition: pathnodes.h:329
static Node * fix_upper_expr(PlannerInfo *root, Node *node, indexed_tlist *subplan_itlist, Index newvarno, int rtoffset, double num_exec)
Definition: setrefs.c:2720
#define GetSysCacheHashValue1(cacheId, key1)
Definition: syscache.h:201
List * fdw_scan_tlist
Definition: plannodes.h:619
Definition: nodes.h:76
unsigned int Oid
Definition: postgres_ext.h:31
Node * utilityStmt
Definition: parsenodes.h:120
Definition: primnodes.h:181
static Relids offset_relid_set(Relids relids, int rtoffset)
Definition: setrefs.c:1561
AttrNumber * grouping_map
Definition: pathnodes.h:328
Scan scan
Definition: plannodes.h:535
List * custom_plans
Definition: plannodes.h:645
Node * limitOffset
Definition: plannodes.h:983
List * lappend_oid(List *list, Oid datum)
Definition: list.c:357
#define OidIsValid(objectId)
Definition: c.h:651
#define DO_AGGSPLIT_COMBINE(as)
Definition: nodes.h:790
List * colcollations
Definition: parsenodes.h:1104
static Plan * set_append_references(PlannerInfo *root, Append *aplan, int rtoffset)
Definition: setrefs.c:1404
List * translated_vars
Definition: pathnodes.h:2258
List * values_lists
Definition: parsenodes.h:1075
List * plans
Definition: plannodes.h:229
static bool trivial_subqueryscan(SubqueryScan *plan)
Definition: setrefs.c:1174
static Plan * set_plan_refs(PlannerInfo *root, Plan *plan, int rtoffset)
Definition: setrefs.c:499
static Node * fix_join_expr_mutator(Node *node, fix_join_expr_context *context)
Definition: setrefs.c:2587
static void add_rte_to_flat_rtable(PlannerGlobal *glob, RangeTblEntry *rte)
Definition: setrefs.c:446
List * onConflictSet
Definition: plannodes.h:238
int rootResultRelIndex
Definition: plannodes.h:228
Index rootRelation
Definition: plannodes.h:224
List * resultRelations
Definition: plannodes.h:226
List * mergeclauses
Definition: plannodes.h:728
struct RelOptInfo ** simple_rel_array
Definition: pathnodes.h:203
static void set_foreignscan_references(PlannerInfo *root, ForeignScan *fscan, int rtoffset)
Definition: setrefs.c:1253
List * rootResultRelations
Definition: pathnodes.h:123
List * multiexpr_params
Definition: pathnodes.h:263
Query * UtilityContainsQuery(Node *parsetree)
Definition: utility.c:2110
List * appendplans
Definition: plannodes.h:255
#define list_make1(x1)
Definition: pg_list.h:206
#define linitial_int(l)
Definition: pg_list.h:175
PlannerInfo * subroot
Definition: pathnodes.h:710
AttrNumber varattno
Definition: setrefs.c:35
Node * startOffset
Definition: plannodes.h:850
bool dependsOnRole
Definition: pathnodes.h:141
Node * resconstantqual
Definition: plannodes.h:189
List * rowMarks
Definition: plannodes.h:234
struct Plan * righttree
Definition: plannodes.h:145
void pfree(void *pointer)
Definition: mcxt.c:1057
#define IS_SPECIAL_VARNO(varno)
Definition: primnodes.h:175
Var * paramval
Definition: plannodes.h:710
bool has_ph_vars
Definition: setrefs.c:43
bool resjunk
Definition: primnodes.h:1417
#define linitial(l)
Definition: pg_list.h:174
Definition: nodes.h:46
List * rtable
Definition: parsenodes.h:137
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
#define ERROR
Definition: elog.h:43
List * indexorderbyorig
Definition: plannodes.h:409
TableFunc * tablefunc
Definition: parsenodes.h:1070
#define lfirst_int(lc)
Definition: pg_list.h:170
static void * list_nth(const List *list, int n)
Definition: pg_list.h:266
Scan scan
Definition: plannodes.h:360
Scan scan
Definition: plannodes.h:555
Node * limitCount
Definition: plannodes.h:984
Scan scan
Definition: plannodes.h:404
#define IS_DUMMY_REL(r)
Definition: pathnodes.h:1419
#define NUM_EXEC_TLIST(parentplan)
Definition: setrefs.c:90
bool hasAlternativeSubPlans
Definition: pathnodes.h:350
int num_vars
Definition: setrefs.c:42
static Node * fix_upper_expr_mutator(Node *node, fix_upper_expr_context *context)
Definition: setrefs.c:2738
Definition: nodes.h:78
RelOptInfo * fetch_upper_rel(PlannerInfo *root, UpperRelationKind kind, Relids relids)
Definition: relnode.c:1192
#define lfirst_node(type, lc)
Definition: pg_list.h:172
static bool flatten_rtes_walker(Node *node, PlannerGlobal *glob)
Definition: setrefs.c:410
static Var * copyVar(Var *var)
Definition: setrefs.c:1583
List * subplans
Definition: pathnodes.h:111
PlannerGlobal * glob
Definition: pathnodes.h:181
Node * endOffset
Definition: plannodes.h:851
List * aggorder
Definition: primnodes.h:320
AttrNumber resno
Definition: primnodes.h:1411
#define FirstBootstrapObjectId
Definition: transam.h:189
TargetEntry * flatCopyTargetEntry(TargetEntry *src_tle)
Definition: makefuncs.c:271
List * joinrightcols
Definition: parsenodes.h:1054
static SPIPlanPtr splan
Definition: regress.c:259
static void set_customscan_references(PlannerInfo *root, CustomScan *cscan, int rtoffset)
Definition: setrefs.c:1331
static Plan * set_subqueryscan_references(PlannerInfo *root, SubqueryScan *plan, int rtoffset)
Definition: setrefs.c:1123
List * indexqual
Definition: plannodes.h:406
List * bitmapqualorig
Definition: plannodes.h:479
TargetEntry * makeTargetEntry(Expr *expr, AttrNumber resno, char *resname, bool resjunk)
Definition: makefuncs.c:238
Var * makeVar(Index varno, AttrNumber varattno, Oid vartype, int32 vartypmod, Oid varcollid, Index varlevelsup)
Definition: makefuncs.c:66
PlannerInfo * root
Definition: setrefs.c:57
List * lappend_int(List *list, int datum)
Definition: list.c:339
Index relid
Definition: pathnodes.h:694
List * cols
Definition: primnodes.h:362
Index varnosyn
Definition: primnodes.h:194
List * lappend(List *list, void *datum)
Definition: list.c:321
Plan plan
Definition: plannodes.h:332
Index varno
Definition: primnodes.h:184
Scan scan
Definition: plannodes.h:642
static bool fix_scan_expr_walker(Node *node, fix_scan_expr_context *context)
Definition: setrefs.c:1896
List * invalItems
Definition: pathnodes.h:129
static Node * fix_scan_expr_mutator(Node *node, fix_scan_expr_context *context)
Definition: setrefs.c:1822
static Plan * set_indexonlyscan_references(PlannerInfo *root, IndexOnlyScan *plan, int rtoffset)
Definition: setrefs.c:1077
List * bitmapplans
Definition: plannodes.h:334
NodeTag type
Definition: pathnodes.h:177
AttrNumber varattnosyn
Definition: primnodes.h:195
List * append_rel_list
Definition: pathnodes.h:290
Index lastPHId
Definition: pathnodes.h:133
static void set_upper_references(PlannerInfo *root, Plan *plan, int rtoffset)
Definition: setrefs.c:2067
static Plan * clean_up_removed_plan_level(Plan *parent, Plan *child)
Definition: setrefs.c:1232
Bitmapset * bms_intersect(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:259
List * hashkeys
Definition: plannodes.h:930
bool has_non_vars
Definition: setrefs.c:44
void record_plan_function_dependency(PlannerInfo *root, Oid funcid)
Definition: setrefs.c:2896
#define NUM_EXEC_QUAL(parentplan)
Definition: setrefs.c:91
unsigned int Index
Definition: c.h:482
TargetEntry * tlist_member(Expr *node, List *targetlist)
Definition: tlist.c:73
List * init_plans
Definition: pathnodes.h:259
Definition: nodes.h:84
uint32 hashValue
Definition: plannodes.h:1248
Cost per_call_cost
Definition: primnodes.h:733
static Var * search_indexed_tlist_for_non_var(Expr *node, indexed_tlist *itlist, Index newvarno)
Definition: setrefs.c:2462
static Node * convert_combining_aggrefs(Node *node, void *context)
Definition: setrefs.c:2185
Oid aggfnoid
Definition: primnodes.h:312
#define ereport(elevel,...)
Definition: elog.h:144
List * joinleftcols
Definition: parsenodes.h:1053
bool extract_query_dependencies_walker(Node *node, PlannerInfo *context)
Definition: setrefs.c:3013
static void fix_expr_common(PlannerInfo *root, Node *node)
Definition: setrefs.c:1605
#define INNER_VAR
Definition: primnodes.h:171
List * indextlist
Definition: plannodes.h:437
CmdType commandType
Definition: parsenodes.h:112
#define makeNode(_type_)
Definition: nodes.h:576
List * indexorderby
Definition: plannodes.h:408
#define Assert(condition)
Definition: c.h:745
#define lfirst(lc)
Definition: pg_list.h:169
Expr * target
Definition: pathnodes.h:2326
static void add_rtes_to_flat_rtable(PlannerInfo *root, bool recursing)
Definition: setrefs.c:314
void extract_query_dependencies(Node *query, List **relationOids, List **invalItems, bool *hasRowSecurity)
Definition: setrefs.c:2977
AggSplit aggsplit
Definition: plannodes.h:820
List * functions
Definition: parsenodes.h:1064
NodeTag type
Definition: pathnodes.h:107
List * custom_scan_tlist
Definition: plannodes.h:648
List * setParam
Definition: primnodes.h:727
static Var * search_indexed_tlist_for_var(Var *var, indexed_tlist *itlist, Index newvarno, int rtoffset)
Definition: setrefs.c:2422
Expr * expr
Definition: primnodes.h:1410
List * rowMarks
Definition: plannodes.h:969
static indexed_tlist * build_tlist_index(List *tlist)
Definition: setrefs.c:2321
int paramid
Definition: primnodes.h:263
Scan scan
Definition: plannodes.h:492
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:41
bool expression_tree_walker(Node *node, bool(*walker)(), void *context)
Definition: nodeFuncs.c:1888
static int list_length(const List *l)
Definition: pg_list.h:149
List * relationOids
Definition: pathnodes.h:127
Oid exprCollation(const Node *expr)
Definition: nodeFuncs.c:768
Expr * aggfilter
Definition: primnodes.h:322
Bitmapset * extParam
Definition: plannodes.h:160
Bitmapset * bms_add_member(Bitmapset *a, int x)
Definition: bitmapset.c:736
struct Plan * lefttree
Definition: plannodes.h:144
Bitmapset * custom_relids
Definition: plannodes.h:649
static indexed_tlist * build_tlist_index_other_vars(List *tlist, Index ignore_rel)
Definition: setrefs.c:2371
List * indexqualorig
Definition: plannodes.h:464
#define nodeTag(nodeptr)
Definition: nodes.h:533
List * targetlist
Definition: plannodes.h:142
RTEKind rtekind
Definition: parsenodes.h:977
Definition: nodes.h:85
static List * set_returning_clause_references(PlannerInfo *root, List *rlist, Plan *topplan, Index resultRelation, int rtoffset)
Definition: setrefs.c:2846
List * mergeplans
Definition: plannodes.h:276
List * finalrtable
Definition: pathnodes.h:117
Query * subquery
Definition: parsenodes.h:1012
void * palloc(Size size)
Definition: mcxt.c:950
int errmsg(const char *fmt,...)
Definition: elog.c:824
void set_opfuncid(OpExpr *opexpr)
Definition: nodeFuncs.c:1667
List * initPlan
Definition: plannodes.h:146
Definition: nodes.h:82
#define elog(elevel,...)
Definition: elog.h:214
int i
Index ressortgroupref
Definition: primnodes.h:1413
indexed_tlist * outer_itlist
Definition: setrefs.c:58
List * returningLists
Definition: plannodes.h:231
Cost startup_cost
Definition: primnodes.h:732
PlannerInfo * root
Definition: setrefs.c:67
Plan plan
Definition: plannodes.h:318
Definition: plannodes.h:816
Index child_relid
Definition: pathnodes.h:2231
Plan * set_plan_references(PlannerInfo *root, Plan *plan)
Definition: setrefs.c:250
RelOptInfo * find_base_rel(PlannerInfo *root, int relid)
Definition: relnode.c:374
#define copyObject(obj)
Definition: nodes.h:644
static Var * search_indexed_tlist_for_sortgroupref(Expr *node, Index sortgroupref, indexed_tlist *itlist, Index newvarno)
Definition: setrefs.c:2502
Index exclRelRTI
Definition: plannodes.h:240
List * coltypes
Definition: parsenodes.h:1102
Index parent_relid
Definition: pathnodes.h:2230
#define INDEX_VAR
Definition: primnodes.h:173
static Plan * set_mergeappend_references(PlannerInfo *root, MergeAppend *mplan, int rtoffset)
Definition: setrefs.c:1468
Definition: regcomp.c:224
List * finalrowmarks
Definition: pathnodes.h:119
Definition: pg_list.h:50
struct TableSampleClause * tablesample
Definition: parsenodes.h:1007
int16 AttrNumber
Definition: attnum.h:21
static Node * fix_scan_expr(PlannerInfo *root, Node *node, int rtoffset, double num_exec)
Definition: setrefs.c:1787
#define OUTER_VAR
Definition: primnodes.h:172
void set_sa_opfuncid(ScalarArrayOpExpr *opexpr)
Definition: nodeFuncs.c:1678
indexed_tlist * subplan_itlist
Definition: setrefs.c:68
List * joinqual
Definition: plannodes.h:686
static void set_dummy_tlist_references(Plan *plan, int rtoffset)
Definition: setrefs.c:2254
List * exclRelTlist
Definition: plannodes.h:241
double Cost
Definition: nodes.h:662
#define offsetof(type, field)
Definition: c.h:668
static void set_hash_references(PlannerInfo *root, Plan *plan, int rtoffset)
Definition: setrefs.c:1529
Plan * subplan
Definition: plannodes.h:515
bool hasRowSecurity
Definition: parsenodes.h:133
Plan plan
Definition: plannodes.h:253
Node * onConflictWhere
Definition: plannodes.h:239
static List * fix_join_expr(PlannerInfo *root, List *clauses, indexed_tlist *outer_itlist, indexed_tlist *inner_itlist, Index acceptable_rel, int rtoffset, double num_exec)
Definition: setrefs.c:2567
void record_plan_type_dependency(PlannerInfo *root, Oid typid)
Definition: setrefs.c:2936
Bitmapset * fs_relids
Definition: plannodes.h:621
Definition: nodes.h:87
Plan plan
Definition: plannodes.h:683
List * tlist
Definition: setrefs.c:41