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