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