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