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