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