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-2024, 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 "rewrite/rewriteManip.h"
30 #include "tcop/utility.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);
147  ForeignScan *fscan,
148  int rtoffset);
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);
164 static void set_join_references(PlannerInfo *root, Join *join, int rtoffset);
165 static void set_upper_references(PlannerInfo *root, Plan *plan, int rtoffset);
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);
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,
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,
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  */
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
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  &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  cxt,
521  cxt->query = save_query;
522  return result;
523  }
524  return expression_tree_walker(node, flatten_rtes_walker, cxt);
525 }
526 
527 /*
528  * Add (a copy of) the given RTE to the final rangetable and also the
529  * corresponding RTEPermissionInfo, if any, to final rteperminfos.
530  *
531  * In the flat rangetable, we zero out substructure pointers that are not
532  * needed by the executor; this reduces the storage space and copying cost
533  * for cached plans. We keep only the ctename, alias, eref Alias fields,
534  * which are needed by EXPLAIN, and perminfoindex which is needed by the
535  * executor to fetch the RTE's RTEPermissionInfo.
536  */
537 static void
539  RangeTblEntry *rte)
540 {
541  RangeTblEntry *newrte;
542 
543  /* flat copy to duplicate all the scalar fields */
544  newrte = (RangeTblEntry *) palloc(sizeof(RangeTblEntry));
545  memcpy(newrte, rte, sizeof(RangeTblEntry));
546 
547  /* zap unneeded sub-structure */
548  newrte->tablesample = NULL;
549  newrte->subquery = NULL;
550  newrte->joinaliasvars = NIL;
551  newrte->joinleftcols = NIL;
552  newrte->joinrightcols = NIL;
553  newrte->join_using_alias = NULL;
554  newrte->functions = NIL;
555  newrte->tablefunc = NULL;
556  newrte->values_lists = NIL;
557  newrte->coltypes = NIL;
558  newrte->coltypmods = NIL;
559  newrte->colcollations = NIL;
560  newrte->groupexprs = 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 *
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 */
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:
841  break;
842  case T_CustomScan:
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);
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);
995  wplan->runCondition,
996  rtoffset,
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 
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  List *newMJC = NIL;
1148  ListCell *lca,
1149  *lcj,
1150  *lcr;
1151 
1152  /*
1153  * Fix the targetList of individual action nodes so that
1154  * the so-called "source relation" Vars are referenced as
1155  * INNER_VAR. Note that for this to work correctly during
1156  * execution, the ecxt_innertuple must be set to the tuple
1157  * obtained by executing the subplan, which is what
1158  * constitutes the "source relation".
1159  *
1160  * We leave the Vars from the result relation (i.e. the
1161  * target relation) unchanged i.e. those Vars would be
1162  * picked from the scan slot. So during execution, we must
1163  * ensure that ecxt_scantuple is setup correctly to refer
1164  * to the tuple from the target relation.
1165  */
1166  indexed_tlist *itlist;
1167 
1168  itlist = build_tlist_index(subplan->targetlist);
1169 
1170  forthree(lca, splan->mergeActionLists,
1171  lcj, splan->mergeJoinConditions,
1172  lcr, splan->resultRelations)
1173  {
1174  List *mergeActionList = lfirst(lca);
1175  Node *mergeJoinCondition = lfirst(lcj);
1176  Index resultrel = lfirst_int(lcr);
1177 
1178  foreach(l, mergeActionList)
1179  {
1181 
1182  /* Fix targetList of each action. */
1183  action->targetList = fix_join_expr(root,
1184  action->targetList,
1185  NULL, itlist,
1186  resultrel,
1187  rtoffset,
1188  NRM_EQUAL,
1189  NUM_EXEC_TLIST(plan));
1190 
1191  /* Fix quals too. */
1192  action->qual = (Node *) fix_join_expr(root,
1193  (List *) action->qual,
1194  NULL, itlist,
1195  resultrel,
1196  rtoffset,
1197  NRM_EQUAL,
1198  NUM_EXEC_QUAL(plan));
1199  }
1200 
1201  /* Fix join condition too. */
1202  mergeJoinCondition = (Node *)
1204  (List *) mergeJoinCondition,
1205  NULL, itlist,
1206  resultrel,
1207  rtoffset,
1208  NRM_EQUAL,
1209  NUM_EXEC_QUAL(plan));
1210  newMJC = lappend(newMJC, mergeJoinCondition);
1211  }
1212  splan->mergeJoinConditions = newMJC;
1213  }
1214 
1215  splan->nominalRelation += rtoffset;
1216  if (splan->rootRelation)
1217  splan->rootRelation += rtoffset;
1218  splan->exclRelRTI += rtoffset;
1219 
1220  foreach(l, splan->resultRelations)
1221  {
1222  lfirst_int(l) += rtoffset;
1223  }
1224  foreach(l, splan->rowMarks)
1225  {
1226  PlanRowMark *rc = (PlanRowMark *) lfirst(l);
1227 
1228  rc->rti += rtoffset;
1229  rc->prti += rtoffset;
1230  }
1231 
1232  /*
1233  * Append this ModifyTable node's final result relation RT
1234  * index(es) to the global list for the plan.
1235  */
1236  root->glob->resultRelations =
1237  list_concat(root->glob->resultRelations,
1238  splan->resultRelations);
1239  if (splan->rootRelation)
1240  {
1241  root->glob->resultRelations =
1242  lappend_int(root->glob->resultRelations,
1243  splan->rootRelation);
1244  }
1245  }
1246  break;
1247  case T_Append:
1248  /* Needs special treatment, see comments below */
1249  return set_append_references(root,
1250  (Append *) plan,
1251  rtoffset);
1252  case T_MergeAppend:
1253  /* Needs special treatment, see comments below */
1255  (MergeAppend *) plan,
1256  rtoffset);
1257  case T_RecursiveUnion:
1258  /* This doesn't evaluate targetlist or check quals either */
1259  set_dummy_tlist_references(plan, rtoffset);
1260  Assert(plan->qual == NIL);
1261  break;
1262  case T_BitmapAnd:
1263  {
1264  BitmapAnd *splan = (BitmapAnd *) plan;
1265 
1266  /* BitmapAnd works like Append, but has no tlist */
1267  Assert(splan->plan.targetlist == NIL);
1268  Assert(splan->plan.qual == NIL);
1269  foreach(l, splan->bitmapplans)
1270  {
1271  lfirst(l) = set_plan_refs(root,
1272  (Plan *) lfirst(l),
1273  rtoffset);
1274  }
1275  }
1276  break;
1277  case T_BitmapOr:
1278  {
1279  BitmapOr *splan = (BitmapOr *) plan;
1280 
1281  /* BitmapOr works like Append, but has no tlist */
1282  Assert(splan->plan.targetlist == NIL);
1283  Assert(splan->plan.qual == NIL);
1284  foreach(l, splan->bitmapplans)
1285  {
1286  lfirst(l) = set_plan_refs(root,
1287  (Plan *) lfirst(l),
1288  rtoffset);
1289  }
1290  }
1291  break;
1292  default:
1293  elog(ERROR, "unrecognized node type: %d",
1294  (int) nodeTag(plan));
1295  break;
1296  }
1297 
1298  /*
1299  * Now recurse into child plans, if any
1300  *
1301  * NOTE: it is essential that we recurse into child plans AFTER we set
1302  * subplan references in this plan's tlist and quals. If we did the
1303  * reference-adjustments bottom-up, then we would fail to match this
1304  * plan's var nodes against the already-modified nodes of the children.
1305  */
1306  plan->lefttree = set_plan_refs(root, plan->lefttree, rtoffset);
1307  plan->righttree = set_plan_refs(root, plan->righttree, rtoffset);
1308 
1309  return plan;
1310 }
1311 
1312 /*
1313  * set_indexonlyscan_references
1314  * Do set_plan_references processing on an IndexOnlyScan
1315  *
1316  * This is unlike the handling of a plain IndexScan because we have to
1317  * convert Vars referencing the heap into Vars referencing the index.
1318  * We can use the fix_upper_expr machinery for that, by working from a
1319  * targetlist describing the index columns.
1320  */
1321 static Plan *
1324  int rtoffset)
1325 {
1326  indexed_tlist *index_itlist;
1327  List *stripped_indextlist;
1328  ListCell *lc;
1329 
1330  /*
1331  * Vars in the plan node's targetlist, qual, and recheckqual must only
1332  * reference columns that the index AM can actually return. To ensure
1333  * this, remove non-returnable columns (which are marked as resjunk) from
1334  * the indexed tlist. We can just drop them because the indexed_tlist
1335  * machinery pays attention to TLE resnos, not physical list position.
1336  */
1337  stripped_indextlist = NIL;
1338  foreach(lc, plan->indextlist)
1339  {
1340  TargetEntry *indextle = (TargetEntry *) lfirst(lc);
1341 
1342  if (!indextle->resjunk)
1343  stripped_indextlist = lappend(stripped_indextlist, indextle);
1344  }
1345 
1346  index_itlist = build_tlist_index(stripped_indextlist);
1347 
1348  plan->scan.scanrelid += rtoffset;
1349  plan->scan.plan.targetlist = (List *)
1351  (Node *) plan->scan.plan.targetlist,
1352  index_itlist,
1353  INDEX_VAR,
1354  rtoffset,
1355  NRM_EQUAL,
1356  NUM_EXEC_TLIST((Plan *) plan));
1357  plan->scan.plan.qual = (List *)
1359  (Node *) plan->scan.plan.qual,
1360  index_itlist,
1361  INDEX_VAR,
1362  rtoffset,
1363  NRM_EQUAL,
1364  NUM_EXEC_QUAL((Plan *) plan));
1365  plan->recheckqual = (List *)
1367  (Node *) plan->recheckqual,
1368  index_itlist,
1369  INDEX_VAR,
1370  rtoffset,
1371  NRM_EQUAL,
1372  NUM_EXEC_QUAL((Plan *) plan));
1373  /* indexqual is already transformed to reference index columns */
1374  plan->indexqual = fix_scan_list(root, plan->indexqual,
1375  rtoffset, 1);
1376  /* indexorderby is already transformed to reference index columns */
1377  plan->indexorderby = fix_scan_list(root, plan->indexorderby,
1378  rtoffset, 1);
1379  /* indextlist must NOT be transformed to reference index columns */
1380  plan->indextlist = fix_scan_list(root, plan->indextlist,
1381  rtoffset, NUM_EXEC_TLIST((Plan *) plan));
1382 
1383  pfree(index_itlist);
1384 
1385  return (Plan *) plan;
1386 }
1387 
1388 /*
1389  * set_subqueryscan_references
1390  * Do set_plan_references processing on a SubqueryScan
1391  *
1392  * We try to strip out the SubqueryScan entirely; if we can't, we have
1393  * to do the normal processing on it.
1394  */
1395 static Plan *
1397  SubqueryScan *plan,
1398  int rtoffset)
1399 {
1400  RelOptInfo *rel;
1401  Plan *result;
1402 
1403  /* Need to look up the subquery's RelOptInfo, since we need its subroot */
1404  rel = find_base_rel(root, plan->scan.scanrelid);
1405 
1406  /* Recursively process the subplan */
1407  plan->subplan = set_plan_references(rel->subroot, plan->subplan);
1408 
1410  {
1411  /*
1412  * We can omit the SubqueryScan node and just pull up the subplan.
1413  */
1414  result = clean_up_removed_plan_level((Plan *) plan, plan->subplan);
1415  }
1416  else
1417  {
1418  /*
1419  * Keep the SubqueryScan node. We have to do the processing that
1420  * set_plan_references would otherwise have done on it. Notice we do
1421  * not do set_upper_references() here, because a SubqueryScan will
1422  * always have been created with correct references to its subplan's
1423  * outputs to begin with.
1424  */
1425  plan->scan.scanrelid += rtoffset;
1426  plan->scan.plan.targetlist =
1427  fix_scan_list(root, plan->scan.plan.targetlist,
1428  rtoffset, NUM_EXEC_TLIST((Plan *) plan));
1429  plan->scan.plan.qual =
1430  fix_scan_list(root, plan->scan.plan.qual,
1431  rtoffset, NUM_EXEC_QUAL((Plan *) plan));
1432 
1433  result = (Plan *) plan;
1434  }
1435 
1436  return result;
1437 }
1438 
1439 /*
1440  * trivial_subqueryscan
1441  * Detect whether a SubqueryScan can be deleted from the plan tree.
1442  *
1443  * We can delete it if it has no qual to check and the targetlist just
1444  * regurgitates the output of the child plan.
1445  *
1446  * This can be called from mark_async_capable_plan(), a helper function for
1447  * create_append_plan(), before set_subqueryscan_references(), to determine
1448  * triviality of a SubqueryScan that is a child of an Append node. So we
1449  * cache the result in the SubqueryScan node to avoid repeated computation.
1450  *
1451  * Note: when called from mark_async_capable_plan(), we determine the result
1452  * before running finalize_plan() on the SubqueryScan node (if needed) and
1453  * set_plan_references() on the subplan tree, but this would be safe, because
1454  * 1) finalize_plan() doesn't modify the tlist or quals for the SubqueryScan
1455  * node (or that for any plan node in the subplan tree), and
1456  * 2) set_plan_references() modifies the tlist for every plan node in the
1457  * subplan tree, but keeps const/resjunk columns as const/resjunk ones and
1458  * preserves the length and order of the tlist, and
1459  * 3) set_plan_references() might delete the topmost plan node like an Append
1460  * or MergeAppend from the subplan tree and pull up the child plan node,
1461  * but in that case, the tlist for the child plan node exactly matches the
1462  * parent.
1463  */
1464 bool
1466 {
1467  int attrno;
1468  ListCell *lp,
1469  *lc;
1470 
1471  /* We might have detected this already; in which case reuse the result */
1472  if (plan->scanstatus == SUBQUERY_SCAN_TRIVIAL)
1473  return true;
1474  if (plan->scanstatus == SUBQUERY_SCAN_NONTRIVIAL)
1475  return false;
1476  Assert(plan->scanstatus == SUBQUERY_SCAN_UNKNOWN);
1477  /* Initially, mark the SubqueryScan as non-deletable from the plan tree */
1478  plan->scanstatus = SUBQUERY_SCAN_NONTRIVIAL;
1479 
1480  if (plan->scan.plan.qual != NIL)
1481  return false;
1482 
1483  if (list_length(plan->scan.plan.targetlist) !=
1484  list_length(plan->subplan->targetlist))
1485  return false; /* tlists not same length */
1486 
1487  attrno = 1;
1488  forboth(lp, plan->scan.plan.targetlist, lc, plan->subplan->targetlist)
1489  {
1490  TargetEntry *ptle = (TargetEntry *) lfirst(lp);
1491  TargetEntry *ctle = (TargetEntry *) lfirst(lc);
1492 
1493  if (ptle->resjunk != ctle->resjunk)
1494  return false; /* tlist doesn't match junk status */
1495 
1496  /*
1497  * We accept either a Var referencing the corresponding element of the
1498  * subplan tlist, or a Const equaling the subplan element. See
1499  * generate_setop_tlist() for motivation.
1500  */
1501  if (ptle->expr && IsA(ptle->expr, Var))
1502  {
1503  Var *var = (Var *) ptle->expr;
1504 
1505  Assert(var->varno == plan->scan.scanrelid);
1506  Assert(var->varlevelsup == 0);
1507  if (var->varattno != attrno)
1508  return false; /* out of order */
1509  }
1510  else if (ptle->expr && IsA(ptle->expr, Const))
1511  {
1512  if (!equal(ptle->expr, ctle->expr))
1513  return false;
1514  }
1515  else
1516  return false;
1517 
1518  attrno++;
1519  }
1520 
1521  /* Re-mark the SubqueryScan as deletable from the plan tree */
1522  plan->scanstatus = SUBQUERY_SCAN_TRIVIAL;
1523 
1524  return true;
1525 }
1526 
1527 /*
1528  * clean_up_removed_plan_level
1529  * Do necessary cleanup when we strip out a SubqueryScan, Append, etc
1530  *
1531  * We are dropping the "parent" plan in favor of returning just its "child".
1532  * A few small tweaks are needed.
1533  */
1534 static Plan *
1536 {
1537  /*
1538  * We have to be sure we don't lose any initplans, so move any that were
1539  * attached to the parent plan to the child. If any are parallel-unsafe,
1540  * the child is no longer parallel-safe. As a cosmetic matter, also add
1541  * the initplans' run costs to the child's costs.
1542  */
1543  if (parent->initPlan)
1544  {
1545  Cost initplan_cost;
1546  bool unsafe_initplans;
1547 
1549  &initplan_cost, &unsafe_initplans);
1550  child->startup_cost += initplan_cost;
1551  child->total_cost += initplan_cost;
1552  if (unsafe_initplans)
1553  child->parallel_safe = false;
1554 
1555  /*
1556  * Attach plans this way so that parent's initplans are processed
1557  * before any pre-existing initplans of the child. Probably doesn't
1558  * matter, but let's preserve the ordering just in case.
1559  */
1560  child->initPlan = list_concat(parent->initPlan,
1561  child->initPlan);
1562  }
1563 
1564  /*
1565  * We also have to transfer the parent's column labeling info into the
1566  * child, else columns sent to client will be improperly labeled if this
1567  * is the topmost plan level. resjunk and so on may be important too.
1568  */
1569  apply_tlist_labeling(child->targetlist, parent->targetlist);
1570 
1571  return child;
1572 }
1573 
1574 /*
1575  * set_foreignscan_references
1576  * Do set_plan_references processing on a ForeignScan
1577  */
1578 static void
1580  ForeignScan *fscan,
1581  int rtoffset)
1582 {
1583  /* Adjust scanrelid if it's valid */
1584  if (fscan->scan.scanrelid > 0)
1585  fscan->scan.scanrelid += rtoffset;
1586 
1587  if (fscan->fdw_scan_tlist != NIL || fscan->scan.scanrelid == 0)
1588  {
1589  /*
1590  * Adjust tlist, qual, fdw_exprs, fdw_recheck_quals to reference
1591  * foreign scan tuple
1592  */
1594 
1595  fscan->scan.plan.targetlist = (List *)
1597  (Node *) fscan->scan.plan.targetlist,
1598  itlist,
1599  INDEX_VAR,
1600  rtoffset,
1601  NRM_EQUAL,
1602  NUM_EXEC_TLIST((Plan *) fscan));
1603  fscan->scan.plan.qual = (List *)
1605  (Node *) fscan->scan.plan.qual,
1606  itlist,
1607  INDEX_VAR,
1608  rtoffset,
1609  NRM_EQUAL,
1610  NUM_EXEC_QUAL((Plan *) fscan));
1611  fscan->fdw_exprs = (List *)
1613  (Node *) fscan->fdw_exprs,
1614  itlist,
1615  INDEX_VAR,
1616  rtoffset,
1617  NRM_EQUAL,
1618  NUM_EXEC_QUAL((Plan *) fscan));
1619  fscan->fdw_recheck_quals = (List *)
1621  (Node *) fscan->fdw_recheck_quals,
1622  itlist,
1623  INDEX_VAR,
1624  rtoffset,
1625  NRM_EQUAL,
1626  NUM_EXEC_QUAL((Plan *) fscan));
1627  pfree(itlist);
1628  /* fdw_scan_tlist itself just needs fix_scan_list() adjustments */
1629  fscan->fdw_scan_tlist =
1630  fix_scan_list(root, fscan->fdw_scan_tlist,
1631  rtoffset, NUM_EXEC_TLIST((Plan *) fscan));
1632  }
1633  else
1634  {
1635  /*
1636  * Adjust tlist, qual, fdw_exprs, fdw_recheck_quals in the standard
1637  * way
1638  */
1639  fscan->scan.plan.targetlist =
1640  fix_scan_list(root, fscan->scan.plan.targetlist,
1641  rtoffset, NUM_EXEC_TLIST((Plan *) fscan));
1642  fscan->scan.plan.qual =
1643  fix_scan_list(root, fscan->scan.plan.qual,
1644  rtoffset, NUM_EXEC_QUAL((Plan *) fscan));
1645  fscan->fdw_exprs =
1646  fix_scan_list(root, fscan->fdw_exprs,
1647  rtoffset, NUM_EXEC_QUAL((Plan *) fscan));
1648  fscan->fdw_recheck_quals =
1649  fix_scan_list(root, fscan->fdw_recheck_quals,
1650  rtoffset, NUM_EXEC_QUAL((Plan *) fscan));
1651  }
1652 
1653  fscan->fs_relids = offset_relid_set(fscan->fs_relids, rtoffset);
1654  fscan->fs_base_relids = offset_relid_set(fscan->fs_base_relids, rtoffset);
1655 
1656  /* Adjust resultRelation if it's valid */
1657  if (fscan->resultRelation > 0)
1658  fscan->resultRelation += rtoffset;
1659 }
1660 
1661 /*
1662  * set_customscan_references
1663  * Do set_plan_references processing on a CustomScan
1664  */
1665 static void
1667  CustomScan *cscan,
1668  int rtoffset)
1669 {
1670  ListCell *lc;
1671 
1672  /* Adjust scanrelid if it's valid */
1673  if (cscan->scan.scanrelid > 0)
1674  cscan->scan.scanrelid += rtoffset;
1675 
1676  if (cscan->custom_scan_tlist != NIL || cscan->scan.scanrelid == 0)
1677  {
1678  /* Adjust tlist, qual, custom_exprs to reference custom scan tuple */
1680 
1681  cscan->scan.plan.targetlist = (List *)
1683  (Node *) cscan->scan.plan.targetlist,
1684  itlist,
1685  INDEX_VAR,
1686  rtoffset,
1687  NRM_EQUAL,
1688  NUM_EXEC_TLIST((Plan *) cscan));
1689  cscan->scan.plan.qual = (List *)
1691  (Node *) cscan->scan.plan.qual,
1692  itlist,
1693  INDEX_VAR,
1694  rtoffset,
1695  NRM_EQUAL,
1696  NUM_EXEC_QUAL((Plan *) cscan));
1697  cscan->custom_exprs = (List *)
1699  (Node *) cscan->custom_exprs,
1700  itlist,
1701  INDEX_VAR,
1702  rtoffset,
1703  NRM_EQUAL,
1704  NUM_EXEC_QUAL((Plan *) cscan));
1705  pfree(itlist);
1706  /* custom_scan_tlist itself just needs fix_scan_list() adjustments */
1707  cscan->custom_scan_tlist =
1708  fix_scan_list(root, cscan->custom_scan_tlist,
1709  rtoffset, NUM_EXEC_TLIST((Plan *) cscan));
1710  }
1711  else
1712  {
1713  /* Adjust tlist, qual, custom_exprs in the standard way */
1714  cscan->scan.plan.targetlist =
1715  fix_scan_list(root, cscan->scan.plan.targetlist,
1716  rtoffset, NUM_EXEC_TLIST((Plan *) cscan));
1717  cscan->scan.plan.qual =
1718  fix_scan_list(root, cscan->scan.plan.qual,
1719  rtoffset, NUM_EXEC_QUAL((Plan *) cscan));
1720  cscan->custom_exprs =
1721  fix_scan_list(root, cscan->custom_exprs,
1722  rtoffset, NUM_EXEC_QUAL((Plan *) cscan));
1723  }
1724 
1725  /* Adjust child plan-nodes recursively, if needed */
1726  foreach(lc, cscan->custom_plans)
1727  {
1728  lfirst(lc) = set_plan_refs(root, (Plan *) lfirst(lc), rtoffset);
1729  }
1730 
1731  cscan->custom_relids = offset_relid_set(cscan->custom_relids, rtoffset);
1732 }
1733 
1734 /*
1735  * set_append_references
1736  * Do set_plan_references processing on an Append
1737  *
1738  * We try to strip out the Append entirely; if we can't, we have
1739  * to do the normal processing on it.
1740  */
1741 static Plan *
1743  Append *aplan,
1744  int rtoffset)
1745 {
1746  ListCell *l;
1747 
1748  /*
1749  * Append, like Sort et al, doesn't actually evaluate its targetlist or
1750  * check quals. If it's got exactly one child plan, then it's not doing
1751  * anything useful at all, and we can strip it out.
1752  */
1753  Assert(aplan->plan.qual == NIL);
1754 
1755  /* First, we gotta recurse on the children */
1756  foreach(l, aplan->appendplans)
1757  {
1758  lfirst(l) = set_plan_refs(root, (Plan *) lfirst(l), rtoffset);
1759  }
1760 
1761  /*
1762  * See if it's safe to get rid of the Append entirely. For this to be
1763  * safe, there must be only one child plan and that child plan's parallel
1764  * awareness must match the Append's. The reason for the latter is that
1765  * if the Append is parallel aware and the child is not, then the calling
1766  * plan may execute the non-parallel aware child multiple times. (If you
1767  * change these rules, update create_append_path to match.)
1768  */
1769  if (list_length(aplan->appendplans) == 1)
1770  {
1771  Plan *p = (Plan *) linitial(aplan->appendplans);
1772 
1773  if (p->parallel_aware == aplan->plan.parallel_aware)
1774  return clean_up_removed_plan_level((Plan *) aplan, p);
1775  }
1776 
1777  /*
1778  * Otherwise, clean up the Append as needed. It's okay to do this after
1779  * recursing to the children, because set_dummy_tlist_references doesn't
1780  * look at those.
1781  */
1782  set_dummy_tlist_references((Plan *) aplan, rtoffset);
1783 
1784  aplan->apprelids = offset_relid_set(aplan->apprelids, rtoffset);
1785 
1786  if (aplan->part_prune_info)
1787  {
1788  foreach(l, aplan->part_prune_info->prune_infos)
1789  {
1790  List *prune_infos = lfirst(l);
1791  ListCell *l2;
1792 
1793  foreach(l2, prune_infos)
1794  {
1795  PartitionedRelPruneInfo *pinfo = lfirst(l2);
1796 
1797  pinfo->rtindex += rtoffset;
1798  }
1799  }
1800  }
1801 
1802  /* We don't need to recurse to lefttree or righttree ... */
1803  Assert(aplan->plan.lefttree == NULL);
1804  Assert(aplan->plan.righttree == NULL);
1805 
1806  return (Plan *) aplan;
1807 }
1808 
1809 /*
1810  * set_mergeappend_references
1811  * Do set_plan_references processing on a MergeAppend
1812  *
1813  * We try to strip out the MergeAppend entirely; if we can't, we have
1814  * to do the normal processing on it.
1815  */
1816 static Plan *
1818  MergeAppend *mplan,
1819  int rtoffset)
1820 {
1821  ListCell *l;
1822 
1823  /*
1824  * MergeAppend, like Sort et al, doesn't actually evaluate its targetlist
1825  * or check quals. If it's got exactly one child plan, then it's not
1826  * doing anything useful at all, and we can strip it out.
1827  */
1828  Assert(mplan->plan.qual == NIL);
1829 
1830  /* First, we gotta recurse on the children */
1831  foreach(l, mplan->mergeplans)
1832  {
1833  lfirst(l) = set_plan_refs(root, (Plan *) lfirst(l), rtoffset);
1834  }
1835 
1836  /*
1837  * See if it's safe to get rid of the MergeAppend entirely. For this to
1838  * be safe, there must be only one child plan and that child plan's
1839  * parallel awareness must match the MergeAppend's. The reason for the
1840  * latter is that if the MergeAppend is parallel aware and the child is
1841  * not, then the calling plan may execute the non-parallel aware child
1842  * multiple times. (If you change these rules, update
1843  * create_merge_append_path to match.)
1844  */
1845  if (list_length(mplan->mergeplans) == 1)
1846  {
1847  Plan *p = (Plan *) linitial(mplan->mergeplans);
1848 
1849  if (p->parallel_aware == mplan->plan.parallel_aware)
1850  return clean_up_removed_plan_level((Plan *) mplan, p);
1851  }
1852 
1853  /*
1854  * Otherwise, clean up the MergeAppend as needed. It's okay to do this
1855  * after recursing to the children, because set_dummy_tlist_references
1856  * doesn't look at those.
1857  */
1858  set_dummy_tlist_references((Plan *) mplan, rtoffset);
1859 
1860  mplan->apprelids = offset_relid_set(mplan->apprelids, rtoffset);
1861 
1862  if (mplan->part_prune_info)
1863  {
1864  foreach(l, mplan->part_prune_info->prune_infos)
1865  {
1866  List *prune_infos = lfirst(l);
1867  ListCell *l2;
1868 
1869  foreach(l2, prune_infos)
1870  {
1871  PartitionedRelPruneInfo *pinfo = lfirst(l2);
1872 
1873  pinfo->rtindex += rtoffset;
1874  }
1875  }
1876  }
1877 
1878  /* We don't need to recurse to lefttree or righttree ... */
1879  Assert(mplan->plan.lefttree == NULL);
1880  Assert(mplan->plan.righttree == NULL);
1881 
1882  return (Plan *) mplan;
1883 }
1884 
1885 /*
1886  * set_hash_references
1887  * Do set_plan_references processing on a Hash node
1888  */
1889 static void
1891 {
1892  Hash *hplan = (Hash *) plan;
1893  Plan *outer_plan = plan->lefttree;
1894  indexed_tlist *outer_itlist;
1895 
1896  /*
1897  * Hash's hashkeys are used when feeding tuples into the hashtable,
1898  * therefore have them reference Hash's outer plan (which itself is the
1899  * inner plan of the HashJoin).
1900  */
1901  outer_itlist = build_tlist_index(outer_plan->targetlist);
1902  hplan->hashkeys = (List *)
1904  (Node *) hplan->hashkeys,
1905  outer_itlist,
1906  OUTER_VAR,
1907  rtoffset,
1908  NRM_EQUAL,
1909  NUM_EXEC_QUAL(plan));
1910 
1911  /* Hash doesn't project */
1912  set_dummy_tlist_references(plan, rtoffset);
1913 
1914  /* Hash nodes don't have their own quals */
1915  Assert(plan->qual == NIL);
1916 }
1917 
1918 /*
1919  * offset_relid_set
1920  * Apply rtoffset to the members of a Relids set.
1921  */
1922 static Relids
1923 offset_relid_set(Relids relids, int rtoffset)
1924 {
1925  Relids result = NULL;
1926  int rtindex;
1927 
1928  /* If there's no offset to apply, we needn't recompute the value */
1929  if (rtoffset == 0)
1930  return relids;
1931  rtindex = -1;
1932  while ((rtindex = bms_next_member(relids, rtindex)) >= 0)
1933  result = bms_add_member(result, rtindex + rtoffset);
1934  return result;
1935 }
1936 
1937 /*
1938  * copyVar
1939  * Copy a Var node.
1940  *
1941  * fix_scan_expr and friends do this enough times that it's worth having
1942  * a bespoke routine instead of using the generic copyObject() function.
1943  */
1944 static inline Var *
1946 {
1947  Var *newvar = (Var *) palloc(sizeof(Var));
1948 
1949  *newvar = *var;
1950  return newvar;
1951 }
1952 
1953 /*
1954  * fix_expr_common
1955  * Do generic set_plan_references processing on an expression node
1956  *
1957  * This is code that is common to all variants of expression-fixing.
1958  * We must look up operator opcode info for OpExpr and related nodes,
1959  * add OIDs from regclass Const nodes into root->glob->relationOids, and
1960  * add PlanInvalItems for user-defined functions into root->glob->invalItems.
1961  * We also fill in column index lists for GROUPING() expressions.
1962  *
1963  * We assume it's okay to update opcode info in-place. So this could possibly
1964  * scribble on the planner's input data structures, but it's OK.
1965  */
1966 static void
1968 {
1969  /* We assume callers won't call us on a NULL pointer */
1970  if (IsA(node, Aggref))
1971  {
1973  ((Aggref *) node)->aggfnoid);
1974  }
1975  else if (IsA(node, WindowFunc))
1976  {
1978  ((WindowFunc *) node)->winfnoid);
1979  }
1980  else if (IsA(node, FuncExpr))
1981  {
1983  ((FuncExpr *) node)->funcid);
1984  }
1985  else if (IsA(node, OpExpr))
1986  {
1987  set_opfuncid((OpExpr *) node);
1989  ((OpExpr *) node)->opfuncid);
1990  }
1991  else if (IsA(node, DistinctExpr))
1992  {
1993  set_opfuncid((OpExpr *) node); /* rely on struct equivalence */
1995  ((DistinctExpr *) node)->opfuncid);
1996  }
1997  else if (IsA(node, NullIfExpr))
1998  {
1999  set_opfuncid((OpExpr *) node); /* rely on struct equivalence */
2001  ((NullIfExpr *) node)->opfuncid);
2002  }
2003  else if (IsA(node, ScalarArrayOpExpr))
2004  {
2005  ScalarArrayOpExpr *saop = (ScalarArrayOpExpr *) node;
2006 
2007  set_sa_opfuncid(saop);
2008  record_plan_function_dependency(root, saop->opfuncid);
2009 
2010  if (OidIsValid(saop->hashfuncid))
2011  record_plan_function_dependency(root, saop->hashfuncid);
2012 
2013  if (OidIsValid(saop->negfuncid))
2014  record_plan_function_dependency(root, saop->negfuncid);
2015  }
2016  else if (IsA(node, Const))
2017  {
2018  Const *con = (Const *) node;
2019 
2020  /* Check for regclass reference */
2021  if (ISREGCLASSCONST(con))
2022  root->glob->relationOids =
2023  lappend_oid(root->glob->relationOids,
2024  DatumGetObjectId(con->constvalue));
2025  }
2026  else if (IsA(node, GroupingFunc))
2027  {
2028  GroupingFunc *g = (GroupingFunc *) node;
2029  AttrNumber *grouping_map = root->grouping_map;
2030 
2031  /* If there are no grouping sets, we don't need this. */
2032 
2033  Assert(grouping_map || g->cols == NIL);
2034 
2035  if (grouping_map)
2036  {
2037  ListCell *lc;
2038  List *cols = NIL;
2039 
2040  foreach(lc, g->refs)
2041  {
2042  cols = lappend_int(cols, grouping_map[lfirst_int(lc)]);
2043  }
2044 
2045  Assert(!g->cols || equal(cols, g->cols));
2046 
2047  if (!g->cols)
2048  g->cols = cols;
2049  }
2050  }
2051 }
2052 
2053 /*
2054  * fix_param_node
2055  * Do set_plan_references processing on a Param
2056  *
2057  * If it's a PARAM_MULTIEXPR, replace it with the appropriate Param from
2058  * root->multiexpr_params; otherwise no change is needed.
2059  * Just for paranoia's sake, we make a copy of the node in either case.
2060  */
2061 static Node *
2063 {
2064  if (p->paramkind == PARAM_MULTIEXPR)
2065  {
2066  int subqueryid = p->paramid >> 16;
2067  int colno = p->paramid & 0xFFFF;
2068  List *params;
2069 
2070  if (subqueryid <= 0 ||
2071  subqueryid > list_length(root->multiexpr_params))
2072  elog(ERROR, "unexpected PARAM_MULTIEXPR ID: %d", p->paramid);
2073  params = (List *) list_nth(root->multiexpr_params, subqueryid - 1);
2074  if (colno <= 0 || colno > list_length(params))
2075  elog(ERROR, "unexpected PARAM_MULTIEXPR ID: %d", p->paramid);
2076  return copyObject(list_nth(params, colno - 1));
2077  }
2078  return (Node *) copyObject(p);
2079 }
2080 
2081 /*
2082  * fix_alternative_subplan
2083  * Do set_plan_references processing on an AlternativeSubPlan
2084  *
2085  * Choose one of the alternative implementations and return just that one,
2086  * discarding the rest of the AlternativeSubPlan structure.
2087  * Note: caller must still recurse into the result!
2088  *
2089  * We don't make any attempt to fix up cost estimates in the parent plan
2090  * node or higher-level nodes.
2091  */
2092 static Node *
2094  double num_exec)
2095 {
2096  SubPlan *bestplan = NULL;
2097  Cost bestcost = 0;
2098  ListCell *lc;
2099 
2100  /*
2101  * Compute the estimated cost of each subplan assuming num_exec
2102  * executions, and keep the cheapest one. In event of exact equality of
2103  * estimates, we prefer the later plan; this is a bit arbitrary, but in
2104  * current usage it biases us to break ties against fast-start subplans.
2105  */
2106  Assert(asplan->subplans != NIL);
2107 
2108  foreach(lc, asplan->subplans)
2109  {
2110  SubPlan *curplan = (SubPlan *) lfirst(lc);
2111  Cost curcost;
2112 
2113  curcost = curplan->startup_cost + num_exec * curplan->per_call_cost;
2114  if (bestplan == NULL || curcost <= bestcost)
2115  {
2116  bestplan = curplan;
2117  bestcost = curcost;
2118  }
2119 
2120  /* Also mark all subplans that are in AlternativeSubPlans */
2121  root->isAltSubplan[curplan->plan_id - 1] = true;
2122  }
2123 
2124  /* Mark the subplan we selected */
2125  root->isUsedSubplan[bestplan->plan_id - 1] = true;
2126 
2127  return (Node *) bestplan;
2128 }
2129 
2130 /*
2131  * fix_scan_expr
2132  * Do set_plan_references processing on a scan-level expression
2133  *
2134  * This consists of incrementing all Vars' varnos by rtoffset,
2135  * replacing PARAM_MULTIEXPR Params, expanding PlaceHolderVars,
2136  * replacing Aggref nodes that should be replaced by initplan output Params,
2137  * choosing the best implementation for AlternativeSubPlans,
2138  * looking up operator opcode info for OpExpr and related nodes,
2139  * and adding OIDs from regclass Const nodes into root->glob->relationOids.
2140  *
2141  * 'node': the expression to be modified
2142  * 'rtoffset': how much to increment varnos by
2143  * 'num_exec': estimated number of executions of expression
2144  *
2145  * The expression tree is either copied-and-modified, or modified in-place
2146  * if that seems safe.
2147  */
2148 static Node *
2149 fix_scan_expr(PlannerInfo *root, Node *node, int rtoffset, double num_exec)
2150 {
2152 
2153  context.root = root;
2154  context.rtoffset = rtoffset;
2155  context.num_exec = num_exec;
2156 
2157  if (rtoffset != 0 ||
2158  root->multiexpr_params != NIL ||
2159  root->glob->lastPHId != 0 ||
2160  root->minmax_aggs != NIL ||
2161  root->hasAlternativeSubPlans)
2162  {
2163  return fix_scan_expr_mutator(node, &context);
2164  }
2165  else
2166  {
2167  /*
2168  * If rtoffset == 0, we don't need to change any Vars, and if there
2169  * are no MULTIEXPR subqueries then we don't need to replace
2170  * PARAM_MULTIEXPR Params, and if there are no placeholders anywhere
2171  * we won't need to remove them, and if there are no minmax Aggrefs we
2172  * won't need to replace them, and if there are no AlternativeSubPlans
2173  * we won't need to remove them. Then it's OK to just scribble on the
2174  * input node tree instead of copying (since the only change, filling
2175  * in any unset opfuncid fields, is harmless). This saves just enough
2176  * cycles to be noticeable on trivial queries.
2177  */
2178  (void) fix_scan_expr_walker(node, &context);
2179  return node;
2180  }
2181 }
2182 
2183 static Node *
2185 {
2186  if (node == NULL)
2187  return NULL;
2188  if (IsA(node, Var))
2189  {
2190  Var *var = copyVar((Var *) node);
2191 
2192  Assert(var->varlevelsup == 0);
2193 
2194  /*
2195  * We should not see Vars marked INNER_VAR, OUTER_VAR, or ROWID_VAR.
2196  * But an indexqual expression could contain INDEX_VAR Vars.
2197  */
2198  Assert(var->varno != INNER_VAR);
2199  Assert(var->varno != OUTER_VAR);
2200  Assert(var->varno != ROWID_VAR);
2201  if (!IS_SPECIAL_VARNO(var->varno))
2202  var->varno += context->rtoffset;
2203  if (var->varnosyn > 0)
2204  var->varnosyn += context->rtoffset;
2205  return (Node *) var;
2206  }
2207  if (IsA(node, Param))
2208  return fix_param_node(context->root, (Param *) node);
2209  if (IsA(node, Aggref))
2210  {
2211  Aggref *aggref = (Aggref *) node;
2212  Param *aggparam;
2213 
2214  /* See if the Aggref should be replaced by a Param */
2215  aggparam = find_minmax_agg_replacement_param(context->root, aggref);
2216  if (aggparam != NULL)
2217  {
2218  /* Make a copy of the Param for paranoia's sake */
2219  return (Node *) copyObject(aggparam);
2220  }
2221  /* If no match, just fall through to process it normally */
2222  }
2223  if (IsA(node, CurrentOfExpr))
2224  {
2225  CurrentOfExpr *cexpr = (CurrentOfExpr *) copyObject(node);
2226 
2227  Assert(!IS_SPECIAL_VARNO(cexpr->cvarno));
2228  cexpr->cvarno += context->rtoffset;
2229  return (Node *) cexpr;
2230  }
2231  if (IsA(node, PlaceHolderVar))
2232  {
2233  /* At scan level, we should always just evaluate the contained expr */
2234  PlaceHolderVar *phv = (PlaceHolderVar *) node;
2235 
2236  /* XXX can we assert something about phnullingrels? */
2237  return fix_scan_expr_mutator((Node *) phv->phexpr, context);
2238  }
2239  if (IsA(node, AlternativeSubPlan))
2241  (AlternativeSubPlan *) node,
2242  context->num_exec),
2243  context);
2244  fix_expr_common(context->root, node);
2246 }
2247 
2248 static bool
2250 {
2251  if (node == NULL)
2252  return false;
2253  Assert(!(IsA(node, Var) && ((Var *) node)->varno == ROWID_VAR));
2254  Assert(!IsA(node, PlaceHolderVar));
2255  Assert(!IsA(node, AlternativeSubPlan));
2256  fix_expr_common(context->root, node);
2258 }
2259 
2260 /*
2261  * set_join_references
2262  * Modify the target list and quals of a join node to reference its
2263  * subplans, by setting the varnos to OUTER_VAR or INNER_VAR and setting
2264  * attno values to the result domain number of either the corresponding
2265  * outer or inner join tuple item. Also perform opcode lookup for these
2266  * expressions, and add regclass OIDs to root->glob->relationOids.
2267  */
2268 static void
2270 {
2271  Plan *outer_plan = join->plan.lefttree;
2272  Plan *inner_plan = join->plan.righttree;
2273  indexed_tlist *outer_itlist;
2274  indexed_tlist *inner_itlist;
2275 
2276  outer_itlist = build_tlist_index(outer_plan->targetlist);
2277  inner_itlist = build_tlist_index(inner_plan->targetlist);
2278 
2279  /*
2280  * First process the joinquals (including merge or hash clauses). These
2281  * are logically below the join so they can always use all values
2282  * available from the input tlists. It's okay to also handle
2283  * NestLoopParams now, because those couldn't refer to nullable
2284  * subexpressions.
2285  */
2286  join->joinqual = fix_join_expr(root,
2287  join->joinqual,
2288  outer_itlist,
2289  inner_itlist,
2290  (Index) 0,
2291  rtoffset,
2292  NRM_EQUAL,
2293  NUM_EXEC_QUAL((Plan *) join));
2294 
2295  /* Now do join-type-specific stuff */
2296  if (IsA(join, NestLoop))
2297  {
2298  NestLoop *nl = (NestLoop *) join;
2299  ListCell *lc;
2300 
2301  foreach(lc, nl->nestParams)
2302  {
2303  NestLoopParam *nlp = (NestLoopParam *) lfirst(lc);
2304 
2305  /*
2306  * Because we don't reparameterize parameterized paths to match
2307  * the outer-join level at which they are used, Vars seen in the
2308  * NestLoopParam expression may have nullingrels that are just a
2309  * subset of those in the Vars actually available from the outer
2310  * side. (Lateral references can also cause this, as explained in
2311  * the comments for identify_current_nestloop_params.) Not
2312  * checking this exactly is a bit grotty, but the work needed to
2313  * make things match up perfectly seems well out of proportion to
2314  * the value.
2315  */
2316  nlp->paramval = (Var *) fix_upper_expr(root,
2317  (Node *) nlp->paramval,
2318  outer_itlist,
2319  OUTER_VAR,
2320  rtoffset,
2321  NRM_SUBSET,
2322  NUM_EXEC_TLIST(outer_plan));
2323  /* Check we replaced any PlaceHolderVar with simple Var */
2324  if (!(IsA(nlp->paramval, Var) &&
2325  nlp->paramval->varno == OUTER_VAR))
2326  elog(ERROR, "NestLoopParam was not reduced to a simple Var");
2327  }
2328  }
2329  else if (IsA(join, MergeJoin))
2330  {
2331  MergeJoin *mj = (MergeJoin *) join;
2332 
2334  mj->mergeclauses,
2335  outer_itlist,
2336  inner_itlist,
2337  (Index) 0,
2338  rtoffset,
2339  NRM_EQUAL,
2340  NUM_EXEC_QUAL((Plan *) join));
2341  }
2342  else if (IsA(join, HashJoin))
2343  {
2344  HashJoin *hj = (HashJoin *) join;
2345 
2347  hj->hashclauses,
2348  outer_itlist,
2349  inner_itlist,
2350  (Index) 0,
2351  rtoffset,
2352  NRM_EQUAL,
2353  NUM_EXEC_QUAL((Plan *) join));
2354 
2355  /*
2356  * HashJoin's hashkeys are used to look for matching tuples from its
2357  * outer plan (not the Hash node!) in the hashtable.
2358  */
2359  hj->hashkeys = (List *) fix_upper_expr(root,
2360  (Node *) hj->hashkeys,
2361  outer_itlist,
2362  OUTER_VAR,
2363  rtoffset,
2364  NRM_EQUAL,
2365  NUM_EXEC_QUAL((Plan *) join));
2366  }
2367 
2368  /*
2369  * Now we need to fix up the targetlist and qpqual, which are logically
2370  * above the join. This means that, if it's not an inner join, any Vars
2371  * and PHVs appearing here should have nullingrels that include the
2372  * effects of the outer join, ie they will have nullingrels equal to the
2373  * input Vars' nullingrels plus the bit added by the outer join. We don't
2374  * currently have enough info available here to identify what that should
2375  * be, so we just tell fix_join_expr to accept superset nullingrels
2376  * matches instead of exact ones.
2377  */
2378  join->plan.targetlist = fix_join_expr(root,
2379  join->plan.targetlist,
2380  outer_itlist,
2381  inner_itlist,
2382  (Index) 0,
2383  rtoffset,
2384  (join->jointype == JOIN_INNER ? NRM_EQUAL : NRM_SUPERSET),
2385  NUM_EXEC_TLIST((Plan *) join));
2386  join->plan.qual = fix_join_expr(root,
2387  join->plan.qual,
2388  outer_itlist,
2389  inner_itlist,
2390  (Index) 0,
2391  rtoffset,
2392  (join->jointype == JOIN_INNER ? NRM_EQUAL : NRM_SUPERSET),
2393  NUM_EXEC_QUAL((Plan *) join));
2394 
2395  pfree(outer_itlist);
2396  pfree(inner_itlist);
2397 }
2398 
2399 /*
2400  * set_upper_references
2401  * Update the targetlist and quals of an upper-level plan node
2402  * to refer to the tuples returned by its lefttree subplan.
2403  * Also perform opcode lookup for these expressions, and
2404  * add regclass OIDs to root->glob->relationOids.
2405  *
2406  * This is used for single-input plan types like Agg, Group, Result.
2407  *
2408  * In most cases, we have to match up individual Vars in the tlist and
2409  * qual expressions with elements of the subplan's tlist (which was
2410  * generated by flattening these selfsame expressions, so it should have all
2411  * the required variables). There is an important exception, however:
2412  * depending on where we are in the plan tree, sort/group columns may have
2413  * been pushed into the subplan tlist unflattened. If these values are also
2414  * needed in the output then we want to reference the subplan tlist element
2415  * rather than recomputing the expression.
2416  */
2417 static void
2419 {
2420  Plan *subplan = plan->lefttree;
2421  indexed_tlist *subplan_itlist;
2422  List *output_targetlist;
2423  ListCell *l;
2424 
2425  subplan_itlist = build_tlist_index(subplan->targetlist);
2426 
2427  /*
2428  * If it's a grouping node with grouping sets, any Vars and PHVs appearing
2429  * in the targetlist and quals should have nullingrels that include the
2430  * effects of the grouping step, ie they will have nullingrels equal to
2431  * the input Vars/PHVs' nullingrels plus the RT index of the grouping
2432  * step. In order to perform exact nullingrels matches, we remove the RT
2433  * index of the grouping step first.
2434  */
2435  if (IsA(plan, Agg) &&
2436  root->group_rtindex > 0 &&
2437  ((Agg *) plan)->groupingSets)
2438  {
2439  plan->targetlist = (List *)
2440  remove_nulling_relids((Node *) plan->targetlist,
2441  bms_make_singleton(root->group_rtindex),
2442  NULL);
2443  plan->qual = (List *)
2444  remove_nulling_relids((Node *) plan->qual,
2445  bms_make_singleton(root->group_rtindex),
2446  NULL);
2447  }
2448 
2449  output_targetlist = NIL;
2450  foreach(l, plan->targetlist)
2451  {
2452  TargetEntry *tle = (TargetEntry *) lfirst(l);
2453  Node *newexpr;
2454 
2455  /* If it's a sort/group item, first try to match by sortref */
2456  if (tle->ressortgroupref != 0)
2457  {
2458  newexpr = (Node *)
2460  tle->ressortgroupref,
2461  subplan_itlist,
2462  OUTER_VAR);
2463  if (!newexpr)
2464  newexpr = fix_upper_expr(root,
2465  (Node *) tle->expr,
2466  subplan_itlist,
2467  OUTER_VAR,
2468  rtoffset,
2469  NRM_EQUAL,
2470  NUM_EXEC_TLIST(plan));
2471  }
2472  else
2473  newexpr = fix_upper_expr(root,
2474  (Node *) tle->expr,
2475  subplan_itlist,
2476  OUTER_VAR,
2477  rtoffset,
2478  NRM_EQUAL,
2479  NUM_EXEC_TLIST(plan));
2480  tle = flatCopyTargetEntry(tle);
2481  tle->expr = (Expr *) newexpr;
2482  output_targetlist = lappend(output_targetlist, tle);
2483  }
2484  plan->targetlist = output_targetlist;
2485 
2486  plan->qual = (List *)
2488  (Node *) plan->qual,
2489  subplan_itlist,
2490  OUTER_VAR,
2491  rtoffset,
2492  NRM_EQUAL,
2493  NUM_EXEC_QUAL(plan));
2494 
2495  pfree(subplan_itlist);
2496 }
2497 
2498 /*
2499  * set_param_references
2500  * Initialize the initParam list in Gather or Gather merge node such that
2501  * it contains reference of all the params that needs to be evaluated
2502  * before execution of the node. It contains the initplan params that are
2503  * being passed to the plan nodes below it.
2504  */
2505 static void
2507 {
2509 
2510  if (plan->lefttree->extParam)
2511  {
2512  PlannerInfo *proot;
2513  Bitmapset *initSetParam = NULL;
2514  ListCell *l;
2515 
2516  for (proot = root; proot != NULL; proot = proot->parent_root)
2517  {
2518  foreach(l, proot->init_plans)
2519  {
2520  SubPlan *initsubplan = (SubPlan *) lfirst(l);
2521  ListCell *l2;
2522 
2523  foreach(l2, initsubplan->setParam)
2524  {
2525  initSetParam = bms_add_member(initSetParam, lfirst_int(l2));
2526  }
2527  }
2528  }
2529 
2530  /*
2531  * Remember the list of all external initplan params that are used by
2532  * the children of Gather or Gather merge node.
2533  */
2534  if (IsA(plan, Gather))
2535  ((Gather *) plan)->initParam =
2536  bms_intersect(plan->lefttree->extParam, initSetParam);
2537  else
2538  ((GatherMerge *) plan)->initParam =
2539  bms_intersect(plan->lefttree->extParam, initSetParam);
2540  }
2541 }
2542 
2543 /*
2544  * Recursively scan an expression tree and convert Aggrefs to the proper
2545  * intermediate form for combining aggregates. This means (1) replacing each
2546  * one's argument list with a single argument that is the original Aggref
2547  * modified to show partial aggregation and (2) changing the upper Aggref to
2548  * show combining aggregation.
2549  *
2550  * After this step, set_upper_references will replace the partial Aggrefs
2551  * with Vars referencing the lower Agg plan node's outputs, so that the final
2552  * form seen by the executor is a combining Aggref with a Var as input.
2553  *
2554  * It's rather messy to postpone this step until setrefs.c; ideally it'd be
2555  * done in createplan.c. The difficulty is that once we modify the Aggref
2556  * expressions, they will no longer be equal() to their original form and
2557  * so cross-plan-node-level matches will fail. So this has to happen after
2558  * the plan node above the Agg has resolved its subplan references.
2559  */
2560 static Node *
2562 {
2563  if (node == NULL)
2564  return NULL;
2565  if (IsA(node, Aggref))
2566  {
2567  Aggref *orig_agg = (Aggref *) node;
2568  Aggref *child_agg;
2569  Aggref *parent_agg;
2570 
2571  /* Assert we've not chosen to partial-ize any unsupported cases */
2572  Assert(orig_agg->aggorder == NIL);
2573  Assert(orig_agg->aggdistinct == NIL);
2574 
2575  /*
2576  * Since aggregate calls can't be nested, we needn't recurse into the
2577  * arguments. But for safety, flat-copy the Aggref node itself rather
2578  * than modifying it in-place.
2579  */
2580  child_agg = makeNode(Aggref);
2581  memcpy(child_agg, orig_agg, sizeof(Aggref));
2582 
2583  /*
2584  * For the parent Aggref, we want to copy all the fields of the
2585  * original aggregate *except* the args list, which we'll replace
2586  * below, and the aggfilter expression, which should be applied only
2587  * by the child not the parent. Rather than explicitly knowing about
2588  * all the other fields here, we can momentarily modify child_agg to
2589  * provide a suitable source for copyObject.
2590  */
2591  child_agg->args = NIL;
2592  child_agg->aggfilter = NULL;
2593  parent_agg = copyObject(child_agg);
2594  child_agg->args = orig_agg->args;
2595  child_agg->aggfilter = orig_agg->aggfilter;
2596 
2597  /*
2598  * Now, set up child_agg to represent the first phase of partial
2599  * aggregation. For now, assume serialization is required.
2600  */
2602 
2603  /*
2604  * And set up parent_agg to represent the second phase.
2605  */
2606  parent_agg->args = list_make1(makeTargetEntry((Expr *) child_agg,
2607  1, NULL, false));
2609 
2610  return (Node *) parent_agg;
2611  }
2613 }
2614 
2615 /*
2616  * set_dummy_tlist_references
2617  * Replace the targetlist of an upper-level plan node with a simple
2618  * list of OUTER_VAR references to its child.
2619  *
2620  * This is used for plan types like Sort and Append that don't evaluate
2621  * their targetlists. Although the executor doesn't care at all what's in
2622  * the tlist, EXPLAIN needs it to be realistic.
2623  *
2624  * Note: we could almost use set_upper_references() here, but it fails for
2625  * Append for lack of a lefttree subplan. Single-purpose code is faster
2626  * anyway.
2627  */
2628 static void
2630 {
2631  List *output_targetlist;
2632  ListCell *l;
2633 
2634  output_targetlist = NIL;
2635  foreach(l, plan->targetlist)
2636  {
2637  TargetEntry *tle = (TargetEntry *) lfirst(l);
2638  Var *oldvar = (Var *) tle->expr;
2639  Var *newvar;
2640 
2641  /*
2642  * As in search_indexed_tlist_for_non_var(), we prefer to keep Consts
2643  * as Consts, not Vars referencing Consts. Here, there's no speed
2644  * advantage to be had, but it makes EXPLAIN output look cleaner, and
2645  * again it avoids confusing the executor.
2646  */
2647  if (IsA(oldvar, Const))
2648  {
2649  /* just reuse the existing TLE node */
2650  output_targetlist = lappend(output_targetlist, tle);
2651  continue;
2652  }
2653 
2654  newvar = makeVar(OUTER_VAR,
2655  tle->resno,
2656  exprType((Node *) oldvar),
2657  exprTypmod((Node *) oldvar),
2658  exprCollation((Node *) oldvar),
2659  0);
2660  if (IsA(oldvar, Var) &&
2661  oldvar->varnosyn > 0)
2662  {
2663  newvar->varnosyn = oldvar->varnosyn + rtoffset;
2664  newvar->varattnosyn = oldvar->varattnosyn;
2665  }
2666  else
2667  {
2668  newvar->varnosyn = 0; /* wasn't ever a plain Var */
2669  newvar->varattnosyn = 0;
2670  }
2671 
2672  tle = flatCopyTargetEntry(tle);
2673  tle->expr = (Expr *) newvar;
2674  output_targetlist = lappend(output_targetlist, tle);
2675  }
2676  plan->targetlist = output_targetlist;
2677 
2678  /* We don't touch plan->qual here */
2679 }
2680 
2681 
2682 /*
2683  * build_tlist_index --- build an index data structure for a child tlist
2684  *
2685  * In most cases, subplan tlists will be "flat" tlists with only Vars,
2686  * so we try to optimize that case by extracting information about Vars
2687  * in advance. Matching a parent tlist to a child is still an O(N^2)
2688  * operation, but at least with a much smaller constant factor than plain
2689  * tlist_member() searches.
2690  *
2691  * The result of this function is an indexed_tlist struct to pass to
2692  * search_indexed_tlist_for_var() and siblings.
2693  * When done, the indexed_tlist may be freed with a single pfree().
2694  */
2695 static indexed_tlist *
2697 {
2698  indexed_tlist *itlist;
2699  tlist_vinfo *vinfo;
2700  ListCell *l;
2701 
2702  /* Create data structure with enough slots for all tlist entries */
2703  itlist = (indexed_tlist *)
2704  palloc(offsetof(indexed_tlist, vars) +
2705  list_length(tlist) * sizeof(tlist_vinfo));
2706 
2707  itlist->tlist = tlist;
2708  itlist->has_ph_vars = false;
2709  itlist->has_non_vars = false;
2710 
2711  /* Find the Vars and fill in the index array */
2712  vinfo = itlist->vars;
2713  foreach(l, tlist)
2714  {
2715  TargetEntry *tle = (TargetEntry *) lfirst(l);
2716 
2717  if (tle->expr && IsA(tle->expr, Var))
2718  {
2719  Var *var = (Var *) tle->expr;
2720 
2721  vinfo->varno = var->varno;
2722  vinfo->varattno = var->varattno;
2723  vinfo->resno = tle->resno;
2724  vinfo->varnullingrels = var->varnullingrels;
2725  vinfo++;
2726  }
2727  else if (tle->expr && IsA(tle->expr, PlaceHolderVar))
2728  itlist->has_ph_vars = true;
2729  else
2730  itlist->has_non_vars = true;
2731  }
2732 
2733  itlist->num_vars = (vinfo - itlist->vars);
2734 
2735  return itlist;
2736 }
2737 
2738 /*
2739  * build_tlist_index_other_vars --- build a restricted tlist index
2740  *
2741  * This is like build_tlist_index, but we only index tlist entries that
2742  * are Vars belonging to some rel other than the one specified. We will set
2743  * has_ph_vars (allowing PlaceHolderVars to be matched), but not has_non_vars
2744  * (so nothing other than Vars and PlaceHolderVars can be matched).
2745  */
2746 static indexed_tlist *
2747 build_tlist_index_other_vars(List *tlist, int ignore_rel)
2748 {
2749  indexed_tlist *itlist;
2750  tlist_vinfo *vinfo;
2751  ListCell *l;
2752 
2753  /* Create data structure with enough slots for all tlist entries */
2754  itlist = (indexed_tlist *)
2755  palloc(offsetof(indexed_tlist, vars) +
2756  list_length(tlist) * sizeof(tlist_vinfo));
2757 
2758  itlist->tlist = tlist;
2759  itlist->has_ph_vars = false;
2760  itlist->has_non_vars = false;
2761 
2762  /* Find the desired Vars and fill in the index array */
2763  vinfo = itlist->vars;
2764  foreach(l, tlist)
2765  {
2766  TargetEntry *tle = (TargetEntry *) lfirst(l);
2767 
2768  if (tle->expr && IsA(tle->expr, Var))
2769  {
2770  Var *var = (Var *) tle->expr;
2771 
2772  if (var->varno != ignore_rel)
2773  {
2774  vinfo->varno = var->varno;
2775  vinfo->varattno = var->varattno;
2776  vinfo->resno = tle->resno;
2777  vinfo->varnullingrels = var->varnullingrels;
2778  vinfo++;
2779  }
2780  }
2781  else if (tle->expr && IsA(tle->expr, PlaceHolderVar))
2782  itlist->has_ph_vars = true;
2783  }
2784 
2785  itlist->num_vars = (vinfo - itlist->vars);
2786 
2787  return itlist;
2788 }
2789 
2790 /*
2791  * search_indexed_tlist_for_var --- find a Var in an indexed tlist
2792  *
2793  * If a match is found, return a copy of the given Var with suitably
2794  * modified varno/varattno (to wit, newvarno and the resno of the TLE entry).
2795  * Also ensure that varnosyn is incremented by rtoffset.
2796  * If no match, return NULL.
2797  *
2798  * We cross-check the varnullingrels of the subplan output Var based on
2799  * nrm_match. Most call sites should pass NRM_EQUAL indicating we expect
2800  * an exact match. However, there are places where we haven't cleaned
2801  * things up completely, and we have to settle for allowing subset or
2802  * superset matches.
2803  */
2804 static Var *
2806  int newvarno, int rtoffset,
2807  NullingRelsMatch nrm_match)
2808 {
2809  int varno = var->varno;
2810  AttrNumber varattno = var->varattno;
2811  tlist_vinfo *vinfo;
2812  int i;
2813 
2814  vinfo = itlist->vars;
2815  i = itlist->num_vars;
2816  while (i-- > 0)
2817  {
2818  if (vinfo->varno == varno && vinfo->varattno == varattno)
2819  {
2820  /* Found a match */
2821  Var *newvar = copyVar(var);
2822 
2823  /*
2824  * Verify that we kept all the nullingrels machinations straight.
2825  *
2826  * XXX we skip the check for system columns and whole-row Vars.
2827  * That's because such Vars might be row identity Vars, which are
2828  * generated without any varnullingrels. It'd be hard to do
2829  * otherwise, since they're normally made very early in planning,
2830  * when we haven't looked at the jointree yet and don't know which
2831  * joins might null such Vars. Doesn't seem worth the expense to
2832  * make them fully valid. (While it's slightly annoying that we
2833  * thereby lose checking for user-written references to such
2834  * columns, it seems unlikely that a bug in nullingrels logic
2835  * would affect only system columns.)
2836  */
2837  if (!(varattno <= 0 ||
2838  (nrm_match == NRM_SUBSET ?
2839  bms_is_subset(var->varnullingrels, vinfo->varnullingrels) :
2840  nrm_match == NRM_SUPERSET ?
2841  bms_is_subset(vinfo->varnullingrels, var->varnullingrels) :
2842  bms_equal(vinfo->varnullingrels, var->varnullingrels))))
2843  elog(ERROR, "wrong varnullingrels %s (expected %s) for Var %d/%d",
2844  bmsToString(var->varnullingrels),
2845  bmsToString(vinfo->varnullingrels),
2846  varno, varattno);
2847 
2848  newvar->varno = newvarno;
2849  newvar->varattno = vinfo->resno;
2850  if (newvar->varnosyn > 0)
2851  newvar->varnosyn += rtoffset;
2852  return newvar;
2853  }
2854  vinfo++;
2855  }
2856  return NULL; /* no match */
2857 }
2858 
2859 /*
2860  * search_indexed_tlist_for_phv --- find a PlaceHolderVar in an indexed tlist
2861  *
2862  * If a match is found, return a Var constructed to reference the tlist item.
2863  * If no match, return NULL.
2864  *
2865  * Cross-check phnullingrels as in search_indexed_tlist_for_var.
2866  *
2867  * NOTE: it is a waste of time to call this unless itlist->has_ph_vars.
2868  */
2869 static Var *
2871  indexed_tlist *itlist, int newvarno,
2872  NullingRelsMatch nrm_match)
2873 {
2874  ListCell *lc;
2875 
2876  foreach(lc, itlist->tlist)
2877  {
2878  TargetEntry *tle = (TargetEntry *) lfirst(lc);
2879 
2880  if (tle->expr && IsA(tle->expr, PlaceHolderVar))
2881  {
2882  PlaceHolderVar *subphv = (PlaceHolderVar *) tle->expr;
2883  Var *newvar;
2884 
2885  /*
2886  * Analogously to search_indexed_tlist_for_var, we match on phid
2887  * only. We don't use equal(), partially for speed but mostly
2888  * because phnullingrels might not be exactly equal.
2889  */
2890  if (phv->phid != subphv->phid)
2891  continue;
2892 
2893  /* Verify that we kept all the nullingrels machinations straight */
2894  if (!(nrm_match == NRM_SUBSET ?
2895  bms_is_subset(phv->phnullingrels, subphv->phnullingrels) :
2896  nrm_match == NRM_SUPERSET ?
2897  bms_is_subset(subphv->phnullingrels, phv->phnullingrels) :
2898  bms_equal(subphv->phnullingrels, phv->phnullingrels)))
2899  elog(ERROR, "wrong phnullingrels %s (expected %s) for PlaceHolderVar %d",
2900  bmsToString(phv->phnullingrels),
2901  bmsToString(subphv->phnullingrels),
2902  phv->phid);
2903 
2904  /* Found a matching subplan output expression */
2905  newvar = makeVarFromTargetEntry(newvarno, tle);
2906  newvar->varnosyn = 0; /* wasn't ever a plain Var */
2907  newvar->varattnosyn = 0;
2908  return newvar;
2909  }
2910  }
2911  return NULL; /* no match */
2912 }
2913 
2914 /*
2915  * search_indexed_tlist_for_non_var --- find a non-Var/PHV in an indexed tlist
2916  *
2917  * If a match is found, return a Var constructed to reference the tlist item.
2918  * If no match, return NULL.
2919  *
2920  * NOTE: it is a waste of time to call this unless itlist->has_non_vars.
2921  */
2922 static Var *
2924  indexed_tlist *itlist, int newvarno)
2925 {
2926  TargetEntry *tle;
2927 
2928  /*
2929  * If it's a simple Const, replacing it with a Var is silly, even if there
2930  * happens to be an identical Const below; a Var is more expensive to
2931  * execute than a Const. What's more, replacing it could confuse some
2932  * places in the executor that expect to see simple Consts for, eg,
2933  * dropped columns.
2934  */
2935  if (IsA(node, Const))
2936  return NULL;
2937 
2938  tle = tlist_member(node, itlist->tlist);
2939  if (tle)
2940  {
2941  /* Found a matching subplan output expression */
2942  Var *newvar;
2943 
2944  newvar = makeVarFromTargetEntry(newvarno, tle);
2945  newvar->varnosyn = 0; /* wasn't ever a plain Var */
2946  newvar->varattnosyn = 0;
2947  return newvar;
2948  }
2949  return NULL; /* no match */
2950 }
2951 
2952 /*
2953  * search_indexed_tlist_for_sortgroupref --- find a sort/group expression
2954  *
2955  * If a match is found, return a Var constructed to reference the tlist item.
2956  * If no match, return NULL.
2957  *
2958  * This is needed to ensure that we select the right subplan TLE in cases
2959  * where there are multiple textually-equal()-but-volatile sort expressions.
2960  * And it's also faster than search_indexed_tlist_for_non_var.
2961  */
2962 static Var *
2964  Index sortgroupref,
2965  indexed_tlist *itlist,
2966  int newvarno)
2967 {
2968  ListCell *lc;
2969 
2970  foreach(lc, itlist->tlist)
2971  {
2972  TargetEntry *tle = (TargetEntry *) lfirst(lc);
2973 
2974  /*
2975  * Usually the equal() check is redundant, but in setop plans it may
2976  * not be, since prepunion.c assigns ressortgroupref equal to the
2977  * column resno without regard to whether that matches the topmost
2978  * level's sortgrouprefs and without regard to whether any implicit
2979  * coercions are added in the setop tree. We might have to clean that
2980  * up someday; but for now, just ignore any false matches.
2981  */
2982  if (tle->ressortgroupref == sortgroupref &&
2983  equal(node, tle->expr))
2984  {
2985  /* Found a matching subplan output expression */
2986  Var *newvar;
2987 
2988  newvar = makeVarFromTargetEntry(newvarno, tle);
2989  newvar->varnosyn = 0; /* wasn't ever a plain Var */
2990  newvar->varattnosyn = 0;
2991  return newvar;
2992  }
2993  }
2994  return NULL; /* no match */
2995 }
2996 
2997 /*
2998  * fix_join_expr
2999  * Create a new set of targetlist entries or join qual clauses by
3000  * changing the varno/varattno values of variables in the clauses
3001  * to reference target list values from the outer and inner join
3002  * relation target lists. Also perform opcode lookup and add
3003  * regclass OIDs to root->glob->relationOids.
3004  *
3005  * This is used in four different scenarios:
3006  * 1) a normal join clause, where all the Vars in the clause *must* be
3007  * replaced by OUTER_VAR or INNER_VAR references. In this case
3008  * acceptable_rel should be zero so that any failure to match a Var will be
3009  * reported as an error.
3010  * 2) RETURNING clauses, which may contain both Vars of the target relation
3011  * and Vars of other relations. In this case we want to replace the
3012  * other-relation Vars by OUTER_VAR references, while leaving target Vars
3013  * alone. Thus inner_itlist = NULL and acceptable_rel = the ID of the
3014  * target relation should be passed.
3015  * 3) ON CONFLICT UPDATE SET/WHERE clauses. Here references to EXCLUDED are
3016  * to be replaced with INNER_VAR references, while leaving target Vars (the
3017  * to-be-updated relation) alone. Correspondingly inner_itlist is to be
3018  * EXCLUDED elements, outer_itlist = NULL and acceptable_rel the target
3019  * relation.
3020  * 4) MERGE. In this case, references to the source relation are to be
3021  * replaced with INNER_VAR references, leaving Vars of the target
3022  * relation (the to-be-modified relation) alone. So inner_itlist is to be
3023  * the source relation elements, outer_itlist = NULL and acceptable_rel
3024  * the target relation.
3025  *
3026  * 'clauses' is the targetlist or list of join clauses
3027  * 'outer_itlist' is the indexed target list of the outer join relation,
3028  * or NULL
3029  * 'inner_itlist' is the indexed target list of the inner join relation,
3030  * or NULL
3031  * 'acceptable_rel' is either zero or the rangetable index of a relation
3032  * whose Vars may appear in the clause without provoking an error
3033  * 'rtoffset': how much to increment varnos by
3034  * 'nrm_match': as for search_indexed_tlist_for_var()
3035  * 'num_exec': estimated number of executions of expression
3036  *
3037  * Returns the new expression tree. The original clause structure is
3038  * not modified.
3039  */
3040 static List *
3042  List *clauses,
3043  indexed_tlist *outer_itlist,
3044  indexed_tlist *inner_itlist,
3045  Index acceptable_rel,
3046  int rtoffset,
3047  NullingRelsMatch nrm_match,
3048  double num_exec)
3049 {
3051 
3052  context.root = root;
3053  context.outer_itlist = outer_itlist;
3054  context.inner_itlist = inner_itlist;
3055  context.acceptable_rel = acceptable_rel;
3056  context.rtoffset = rtoffset;
3057  context.nrm_match = nrm_match;
3058  context.num_exec = num_exec;
3059  return (List *) fix_join_expr_mutator((Node *) clauses, &context);
3060 }
3061 
3062 static Node *
3064 {
3065  Var *newvar;
3066 
3067  if (node == NULL)
3068  return NULL;
3069  if (IsA(node, Var))
3070  {
3071  Var *var = (Var *) node;
3072 
3073  /* Look for the var in the input tlists, first in the outer */
3074  if (context->outer_itlist)
3075  {
3076  newvar = search_indexed_tlist_for_var(var,
3077  context->outer_itlist,
3078  OUTER_VAR,
3079  context->rtoffset,
3080  context->nrm_match);
3081  if (newvar)
3082  return (Node *) newvar;
3083  }
3084 
3085  /* then in the inner. */
3086  if (context->inner_itlist)
3087  {
3088  newvar = search_indexed_tlist_for_var(var,
3089  context->inner_itlist,
3090  INNER_VAR,
3091  context->rtoffset,
3092  context->nrm_match);
3093  if (newvar)
3094  return (Node *) newvar;
3095  }
3096 
3097  /* If it's for acceptable_rel, adjust and return it */
3098  if (var->varno == context->acceptable_rel)
3099  {
3100  var = copyVar(var);
3101  var->varno += context->rtoffset;
3102  if (var->varnosyn > 0)
3103  var->varnosyn += context->rtoffset;
3104  return (Node *) var;
3105  }
3106 
3107  /* No referent found for Var */
3108  elog(ERROR, "variable not found in subplan target lists");
3109  }
3110  if (IsA(node, PlaceHolderVar))
3111  {
3112  PlaceHolderVar *phv = (PlaceHolderVar *) node;
3113 
3114  /* See if the PlaceHolderVar has bubbled up from a lower plan node */
3115  if (context->outer_itlist && context->outer_itlist->has_ph_vars)
3116  {
3117  newvar = search_indexed_tlist_for_phv(phv,
3118  context->outer_itlist,
3119  OUTER_VAR,
3120  context->nrm_match);
3121  if (newvar)
3122  return (Node *) newvar;
3123  }
3124  if (context->inner_itlist && context->inner_itlist->has_ph_vars)
3125  {
3126  newvar = search_indexed_tlist_for_phv(phv,
3127  context->inner_itlist,
3128  INNER_VAR,
3129  context->nrm_match);
3130  if (newvar)
3131  return (Node *) newvar;
3132  }
3133 
3134  /* If not supplied by input plans, evaluate the contained expr */
3135  /* XXX can we assert something about phnullingrels? */
3136  return fix_join_expr_mutator((Node *) phv->phexpr, context);
3137  }
3138  /* Try matching more complex expressions too, if tlists have any */
3139  if (context->outer_itlist && context->outer_itlist->has_non_vars)
3140  {
3141  newvar = search_indexed_tlist_for_non_var((Expr *) node,
3142  context->outer_itlist,
3143  OUTER_VAR);
3144  if (newvar)
3145  return (Node *) newvar;
3146  }
3147  if (context->inner_itlist && context->inner_itlist->has_non_vars)
3148  {
3149  newvar = search_indexed_tlist_for_non_var((Expr *) node,
3150  context->inner_itlist,
3151  INNER_VAR);
3152  if (newvar)
3153  return (Node *) newvar;
3154  }
3155  /* Special cases (apply only AFTER failing to match to lower tlist) */
3156  if (IsA(node, Param))
3157  return fix_param_node(context->root, (Param *) node);
3158  if (IsA(node, AlternativeSubPlan))
3160  (AlternativeSubPlan *) node,
3161  context->num_exec),
3162  context);
3163  fix_expr_common(context->root, node);
3165 }
3166 
3167 /*
3168  * fix_upper_expr
3169  * Modifies an expression tree so that all Var nodes reference outputs
3170  * of a subplan. Also looks for Aggref nodes that should be replaced
3171  * by initplan output Params. Also performs opcode lookup, and adds
3172  * regclass OIDs to root->glob->relationOids.
3173  *
3174  * This is used to fix up target and qual expressions of non-join upper-level
3175  * plan nodes, as well as index-only scan nodes.
3176  *
3177  * An error is raised if no matching var can be found in the subplan tlist
3178  * --- so this routine should only be applied to nodes whose subplans'
3179  * targetlists were generated by flattening the expressions used in the
3180  * parent node.
3181  *
3182  * If itlist->has_non_vars is true, then we try to match whole subexpressions
3183  * against elements of the subplan tlist, so that we can avoid recomputing
3184  * expressions that were already computed by the subplan. (This is relatively
3185  * expensive, so we don't want to try it in the common case where the
3186  * subplan tlist is just a flattened list of Vars.)
3187  *
3188  * 'node': the tree to be fixed (a target item or qual)
3189  * 'subplan_itlist': indexed target list for subplan (or index)
3190  * 'newvarno': varno to use for Vars referencing tlist elements
3191  * 'rtoffset': how much to increment varnos by
3192  * 'nrm_match': as for search_indexed_tlist_for_var()
3193  * 'num_exec': estimated number of executions of expression
3194  *
3195  * The resulting tree is a copy of the original in which all Var nodes have
3196  * varno = newvarno, varattno = resno of corresponding targetlist element.
3197  * The original tree is not modified.
3198  */
3199 static Node *
3201  Node *node,
3202  indexed_tlist *subplan_itlist,
3203  int newvarno,
3204  int rtoffset,
3205  NullingRelsMatch nrm_match,
3206  double num_exec)
3207 {
3209 
3210  context.root = root;
3211  context.subplan_itlist = subplan_itlist;
3212  context.newvarno = newvarno;
3213  context.rtoffset = rtoffset;
3214  context.nrm_match = nrm_match;
3215  context.num_exec = num_exec;
3216  return fix_upper_expr_mutator(node, &context);
3217 }
3218 
3219 static Node *
3221 {
3222  Var *newvar;
3223 
3224  if (node == NULL)
3225  return NULL;
3226  if (IsA(node, Var))
3227  {
3228  Var *var = (Var *) node;
3229 
3230  newvar = search_indexed_tlist_for_var(var,
3231  context->subplan_itlist,
3232  context->newvarno,
3233  context->rtoffset,
3234  context->nrm_match);
3235  if (!newvar)
3236  elog(ERROR, "variable not found in subplan target list");
3237  return (Node *) newvar;
3238  }
3239  if (IsA(node, PlaceHolderVar))
3240  {
3241  PlaceHolderVar *phv = (PlaceHolderVar *) node;
3242 
3243  /* See if the PlaceHolderVar has bubbled up from a lower plan node */
3244  if (context->subplan_itlist->has_ph_vars)
3245  {
3246  newvar = search_indexed_tlist_for_phv(phv,
3247  context->subplan_itlist,
3248  context->newvarno,
3249  context->nrm_match);
3250  if (newvar)
3251  return (Node *) newvar;
3252  }
3253  /* If not supplied by input plan, evaluate the contained expr */
3254  /* XXX can we assert something about phnullingrels? */
3255  return fix_upper_expr_mutator((Node *) phv->phexpr, context);
3256  }
3257  /* Try matching more complex expressions too, if tlist has any */
3258  if (context->subplan_itlist->has_non_vars)
3259  {
3260  newvar = search_indexed_tlist_for_non_var((Expr *) node,
3261  context->subplan_itlist,
3262  context->newvarno);
3263  if (newvar)
3264  return (Node *) newvar;
3265  }
3266  /* Special cases (apply only AFTER failing to match to lower tlist) */
3267  if (IsA(node, Param))
3268  return fix_param_node(context->root, (Param *) node);
3269  if (IsA(node, Aggref))
3270  {
3271  Aggref *aggref = (Aggref *) node;
3272  Param *aggparam;
3273 
3274  /* See if the Aggref should be replaced by a Param */
3275  aggparam = find_minmax_agg_replacement_param(context->root, aggref);
3276  if (aggparam != NULL)
3277  {
3278  /* Make a copy of the Param for paranoia's sake */
3279  return (Node *) copyObject(aggparam);
3280  }
3281  /* If no match, just fall through to process it normally */
3282  }
3283  if (IsA(node, AlternativeSubPlan))
3285  (AlternativeSubPlan *) node,
3286  context->num_exec),
3287  context);
3288  fix_expr_common(context->root, node);
3290 }
3291 
3292 /*
3293  * set_returning_clause_references
3294  * Perform setrefs.c's work on a RETURNING targetlist
3295  *
3296  * If the query involves more than just the result table, we have to
3297  * adjust any Vars that refer to other tables to reference junk tlist
3298  * entries in the top subplan's targetlist. Vars referencing the result
3299  * table should be left alone, however (the executor will evaluate them
3300  * using the actual heap tuple, after firing triggers if any). In the
3301  * adjusted RETURNING list, result-table Vars will have their original
3302  * varno (plus rtoffset), but Vars for other rels will have varno OUTER_VAR.
3303  *
3304  * We also must perform opcode lookup and add regclass OIDs to
3305  * root->glob->relationOids.
3306  *
3307  * 'rlist': the RETURNING targetlist to be fixed
3308  * 'topplan': the top subplan node that will be just below the ModifyTable
3309  * node (note it's not yet passed through set_plan_refs)
3310  * 'resultRelation': RT index of the associated result relation
3311  * 'rtoffset': how much to increment varnos by
3312  *
3313  * Note: the given 'root' is for the parent query level, not the 'topplan'.
3314  * This does not matter currently since we only access the dependency-item
3315  * lists in root->glob, but it would need some hacking if we wanted a root
3316  * that actually matches the subplan.
3317  *
3318  * Note: resultRelation is not yet adjusted by rtoffset.
3319  */
3320 static List *
3322  List *rlist,
3323  Plan *topplan,
3324  Index resultRelation,
3325  int rtoffset)
3326 {
3327  indexed_tlist *itlist;
3328 
3329  /*
3330  * We can perform the desired Var fixup by abusing the fix_join_expr
3331  * machinery that formerly handled inner indexscan fixup. We search the
3332  * top plan's targetlist for Vars of non-result relations, and use
3333  * fix_join_expr to convert RETURNING Vars into references to those tlist
3334  * entries, while leaving result-rel Vars as-is.
3335  *
3336  * PlaceHolderVars will also be sought in the targetlist, but no
3337  * more-complex expressions will be. Note that it is not possible for a
3338  * PlaceHolderVar to refer to the result relation, since the result is
3339  * never below an outer join. If that case could happen, we'd have to be
3340  * prepared to pick apart the PlaceHolderVar and evaluate its contained
3341  * expression instead.
3342  */
3343  itlist = build_tlist_index_other_vars(topplan->targetlist, resultRelation);
3344 
3345  rlist = fix_join_expr(root,
3346  rlist,
3347  itlist,
3348  NULL,
3349  resultRelation,
3350  rtoffset,
3351  NRM_EQUAL,
3352  NUM_EXEC_TLIST(topplan));
3353 
3354  pfree(itlist);
3355 
3356  return rlist;
3357 }
3358 
3359 /*
3360  * fix_windowagg_condition_expr_mutator
3361  * Mutator function for replacing WindowFuncs with the corresponding Var
3362  * in the targetlist which references that WindowFunc.
3363  */
3364 static Node *
3367 {
3368  if (node == NULL)
3369  return NULL;
3370 
3371  if (IsA(node, WindowFunc))
3372  {
3373  Var *newvar;
3374 
3375  newvar = search_indexed_tlist_for_non_var((Expr *) node,
3376  context->subplan_itlist,
3377  context->newvarno);
3378  if (newvar)
3379  return (Node *) newvar;
3380  elog(ERROR, "WindowFunc not found in subplan target lists");
3381  }
3382 
3383  return expression_tree_mutator(node,
3385  context);
3386 }
3387 
3388 /*
3389  * fix_windowagg_condition_expr
3390  * Converts references in 'runcondition' so that any WindowFunc
3391  * references are swapped out for a Var which references the matching
3392  * WindowFunc in 'subplan_itlist'.
3393  */
3394 static List *
3396  List *runcondition,
3397  indexed_tlist *subplan_itlist)
3398 {
3400 
3401  context.root = root;
3402  context.subplan_itlist = subplan_itlist;
3403  context.newvarno = 0;
3404 
3405  return (List *) fix_windowagg_condition_expr_mutator((Node *) runcondition,
3406  &context);
3407 }
3408 
3409 /*
3410  * set_windowagg_runcondition_references
3411  * Converts references in 'runcondition' so that any WindowFunc
3412  * references are swapped out for a Var which references the matching
3413  * WindowFunc in 'plan' targetlist.
3414  */
3415 static List *
3417  List *runcondition,
3418  Plan *plan)
3419 {
3420  List *newlist;
3421  indexed_tlist *itlist;
3422 
3423  itlist = build_tlist_index(plan->targetlist);
3424 
3425  newlist = fix_windowagg_condition_expr(root, runcondition, itlist);
3426 
3427  pfree(itlist);
3428 
3429  return newlist;
3430 }
3431 
3432 /*
3433  * find_minmax_agg_replacement_param
3434  * If the given Aggref is one that we are optimizing into a subquery
3435  * (cf. planagg.c), then return the Param that should replace it.
3436  * Else return NULL.
3437  *
3438  * This is exported so that SS_finalize_plan can use it before setrefs.c runs.
3439  * Note that it will not find anything until we have built a Plan from a
3440  * MinMaxAggPath, as root->minmax_aggs will never be filled otherwise.
3441  */
3442 Param *
3444 {
3445  if (root->minmax_aggs != NIL &&
3446  list_length(aggref->args) == 1)
3447  {
3448  TargetEntry *curTarget = (TargetEntry *) linitial(aggref->args);
3449  ListCell *lc;
3450 
3451  foreach(lc, root->minmax_aggs)
3452  {
3453  MinMaxAggInfo *mminfo = (MinMaxAggInfo *) lfirst(lc);
3454 
3455  if (mminfo->aggfnoid == aggref->aggfnoid &&
3456  equal(mminfo->target, curTarget->expr))
3457  return mminfo->param;
3458  }
3459  }
3460  return NULL;
3461 }
3462 
3463 
3464 /*****************************************************************************
3465  * QUERY DEPENDENCY MANAGEMENT
3466  *****************************************************************************/
3467 
3468 /*
3469  * record_plan_function_dependency
3470  * Mark the current plan as depending on a particular function.
3471  *
3472  * This is exported so that the function-inlining code can record a
3473  * dependency on a function that it's removed from the plan tree.
3474  */
3475 void
3477 {
3478  /*
3479  * For performance reasons, we don't bother to track built-in functions;
3480  * we just assume they'll never change (or at least not in ways that'd
3481  * invalidate plans using them). For this purpose we can consider a
3482  * built-in function to be one with OID less than FirstUnpinnedObjectId.
3483  * Note that the OID generator guarantees never to generate such an OID
3484  * after startup, even at OID wraparound.
3485  */
3486  if (funcid >= (Oid) FirstUnpinnedObjectId)
3487  {
3488  PlanInvalItem *inval_item = makeNode(PlanInvalItem);
3489 
3490  /*
3491  * It would work to use any syscache on pg_proc, but the easiest is
3492  * PROCOID since we already have the function's OID at hand. Note
3493  * that plancache.c knows we use PROCOID.
3494  */
3495  inval_item->cacheId = PROCOID;
3496  inval_item->hashValue = GetSysCacheHashValue1(PROCOID,
3497  ObjectIdGetDatum(funcid));
3498 
3499  root->glob->invalItems = lappend(root->glob->invalItems, inval_item);
3500  }
3501 }
3502 
3503 /*
3504  * record_plan_type_dependency
3505  * Mark the current plan as depending on a particular type.
3506  *
3507  * This is exported so that eval_const_expressions can record a
3508  * dependency on a domain that it's removed a CoerceToDomain node for.
3509  *
3510  * We don't currently need to record dependencies on domains that the
3511  * plan contains CoerceToDomain nodes for, though that might change in
3512  * future. Hence, this isn't actually called in this module, though
3513  * someday fix_expr_common might call it.
3514  */
3515 void
3517 {
3518  /*
3519  * As in record_plan_function_dependency, ignore the possibility that
3520  * someone would change a built-in domain.
3521  */
3522  if (typid >= (Oid) FirstUnpinnedObjectId)
3523  {
3524  PlanInvalItem *inval_item = makeNode(PlanInvalItem);
3525 
3526  /*
3527  * It would work to use any syscache on pg_type, but the easiest is
3528  * TYPEOID since we already have the type's OID at hand. Note that
3529  * plancache.c knows we use TYPEOID.
3530  */
3531  inval_item->cacheId = TYPEOID;
3532  inval_item->hashValue = GetSysCacheHashValue1(TYPEOID,
3533  ObjectIdGetDatum(typid));
3534 
3535  root->glob->invalItems = lappend(root->glob->invalItems, inval_item);
3536  }
3537 }
3538 
3539 /*
3540  * extract_query_dependencies
3541  * Given a rewritten, but not yet planned, query or queries
3542  * (i.e. a Query node or list of Query nodes), extract dependencies
3543  * just as set_plan_references would do. Also detect whether any
3544  * rewrite steps were affected by RLS.
3545  *
3546  * This is needed by plancache.c to handle invalidation of cached unplanned
3547  * queries.
3548  *
3549  * Note: this does not go through eval_const_expressions, and hence doesn't
3550  * reflect its additions of inlined functions and elided CoerceToDomain nodes
3551  * to the invalItems list. This is obviously OK for functions, since we'll
3552  * see them in the original query tree anyway. For domains, it's OK because
3553  * we don't care about domains unless they get elided. That is, a plan might
3554  * have domain dependencies that the query tree doesn't.
3555  */
3556 void
3558  List **relationOids,
3559  List **invalItems,
3560  bool *hasRowSecurity)
3561 {
3562  PlannerGlobal glob;
3563  PlannerInfo root;
3564 
3565  /* Make up dummy planner state so we can use this module's machinery */
3566  MemSet(&glob, 0, sizeof(glob));
3567  glob.type = T_PlannerGlobal;
3568  glob.relationOids = NIL;
3569  glob.invalItems = NIL;
3570  /* Hack: we use glob.dependsOnRole to collect hasRowSecurity flags */
3571  glob.dependsOnRole = false;
3572 
3573  MemSet(&root, 0, sizeof(root));
3574  root.type = T_PlannerInfo;
3575  root.glob = &glob;
3576 
3577  (void) extract_query_dependencies_walker(query, &root);
3578 
3579  *relationOids = glob.relationOids;
3580  *invalItems = glob.invalItems;
3581  *hasRowSecurity = glob.dependsOnRole;
3582 }
3583 
3584 /*
3585  * Tree walker for extract_query_dependencies.
3586  *
3587  * This is exported so that expression_planner_with_deps can call it on
3588  * simple expressions (post-planning, not before planning, in that case).
3589  * In that usage, glob.dependsOnRole isn't meaningful, but the relationOids
3590  * and invalItems lists are added to as needed.
3591  */
3592 bool
3594 {
3595  if (node == NULL)
3596  return false;
3597  Assert(!IsA(node, PlaceHolderVar));
3598  if (IsA(node, Query))
3599  {
3600  Query *query = (Query *) node;
3601  ListCell *lc;
3602 
3603  if (query->commandType == CMD_UTILITY)
3604  {
3605  /*
3606  * This logic must handle any utility command for which parse
3607  * analysis was nontrivial (cf. stmt_requires_parse_analysis).
3608  *
3609  * Notably, CALL requires its own processing.
3610  */
3611  if (IsA(query->utilityStmt, CallStmt))
3612  {
3613  CallStmt *callstmt = (CallStmt *) query->utilityStmt;
3614 
3615  /* We need not examine funccall, just the transformed exprs */
3616  (void) extract_query_dependencies_walker((Node *) callstmt->funcexpr,
3617  context);
3618  (void) extract_query_dependencies_walker((Node *) callstmt->outargs,
3619  context);
3620  return false;
3621  }
3622 
3623  /*
3624  * Ignore other utility statements, except those (such as EXPLAIN)
3625  * that contain a parsed-but-not-planned query. For those, we
3626  * just need to transfer our attention to the contained query.
3627  */
3628  query = UtilityContainsQuery(query->utilityStmt);
3629  if (query == NULL)
3630  return false;
3631  }
3632 
3633  /* Remember if any Query has RLS quals applied by rewriter */
3634  if (query->hasRowSecurity)
3635  context->glob->dependsOnRole = true;
3636 
3637  /* Collect relation OIDs in this Query's rtable */
3638  foreach(lc, query->rtable)
3639  {
3640  RangeTblEntry *rte = (RangeTblEntry *) lfirst(lc);
3641 
3642  if (rte->rtekind == RTE_RELATION ||
3643  (rte->rtekind == RTE_SUBQUERY && OidIsValid(rte->relid)) ||
3644  (rte->rtekind == RTE_NAMEDTUPLESTORE && OidIsValid(rte->relid)))
3645  context->glob->relationOids =
3646  lappend_oid(context->glob->relationOids, rte->relid);
3647  }
3648 
3649  /* And recurse into the query's subexpressions */
3651  context, 0);
3652  }
3653  /* Extract function dependencies and check for regclass Consts */
3654  fix_expr_common(context, node);
3656  context);
3657 }
int16 AttrNumber
Definition: attnum.h:21
bool bms_equal(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:142
int bms_next_member(const Bitmapset *a, int prevbit)
Definition: bitmapset.c:1306
bool bms_is_subset(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:412
Bitmapset * bms_make_singleton(int x)
Definition: bitmapset.c:216
Bitmapset * bms_add_member(Bitmapset *a, int x)
Definition: bitmapset.c:815
Bitmapset * bms_intersect(const Bitmapset *a, const Bitmapset *b)
Definition: bitmapset.c:292
#define Assert(condition)
Definition: c.h:812
#define FLEXIBLE_ARRAY_MEMBER
Definition: c.h:417
unsigned int Index
Definition: c.h:568
#define MemSet(start, val, len)
Definition: c.h:974
#define OidIsValid(objectId)
Definition: c.h:729
#define ERROR
Definition: elog.h:39
#define elog(elevel,...)
Definition: elog.h:225
bool equal(const void *a, const void *b)
Definition: equalfuncs.c:223
int i
Definition: isn.c:72
if(TABLE==NULL||TABLE_index==NULL)
Definition: isn.c:76
List * lappend(List *list, void *datum)
Definition: list.c:339
List * lappend_int(List *list, int datum)
Definition: list.c:357
List * lappend_oid(List *list, Oid datum)
Definition: list.c:375
List * list_concat(List *list1, const List *list2)
Definition: list.c:561
Datum lca(PG_FUNCTION_ARGS)
Definition: ltree_op.c:568
Var * makeVarFromTargetEntry(int varno, TargetEntry *tle)
Definition: makefuncs.c:105
TargetEntry * makeTargetEntry(Expr *expr, AttrNumber resno, char *resname, bool resjunk)
Definition: makefuncs.c:240
Const * makeNullConst(Oid consttype, int32 consttypmod, Oid constcollid)
Definition: makefuncs.c:339
Var * makeVar(int varno, AttrNumber varattno, Oid vartype, int32 vartypmod, Oid varcollid, Index varlevelsup)
Definition: makefuncs.c:66
TargetEntry * flatCopyTargetEntry(TargetEntry *src_tle)
Definition: makefuncs.c:273
void pfree(void *pointer)
Definition: mcxt.c:1521
void * palloc0(Size size)
Definition: mcxt.c:1347
void * palloc(Size size)
Definition: mcxt.c:1317
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:42
int32 exprTypmod(const Node *expr)
Definition: nodeFuncs.c:298
Oid exprCollation(const Node *expr)
Definition: nodeFuncs.c:816
void set_sa_opfuncid(ScalarArrayOpExpr *opexpr)
Definition: nodeFuncs.c:1872
void set_opfuncid(OpExpr *opexpr)
Definition: nodeFuncs.c:1861
#define expression_tree_mutator(n, m, c)
Definition: nodeFuncs.h:155
#define query_tree_walker(q, w, c, f)
Definition: nodeFuncs.h:158
#define expression_tree_walker(n, w, c)
Definition: nodeFuncs.h:153
#define QTW_EXAMINE_RTES_BEFORE
Definition: nodeFuncs.h:27
#define IsA(nodeptr, _type_)
Definition: nodes.h:158
#define copyObject(obj)
Definition: nodes.h:224
double Cost
Definition: nodes.h:251
#define nodeTag(nodeptr)
Definition: nodes.h:133
#define DO_AGGSPLIT_COMBINE(as)
Definition: nodes.h:385
@ CMD_UTILITY
Definition: nodes.h:270
@ AGGSPLIT_FINAL_DESERIAL
Definition: nodes.h:381
@ AGGSPLIT_INITIAL_SERIAL
Definition: nodes.h:379
#define makeNode(_type_)
Definition: nodes.h:155
@ JOIN_INNER
Definition: nodes.h:293
char * bmsToString(const Bitmapset *bms)
Definition: outfuncs.c:811
RTEPermissionInfo * addRTEPermissionInfo(List **rteperminfos, RangeTblEntry *rte)
RTEPermissionInfo * getRTEPermissionInfo(List *rteperminfos, RangeTblEntry *rte)
@ RTE_NAMEDTUPLESTORE
Definition: parsenodes.h:1024
@ RTE_SUBQUERY
Definition: parsenodes.h:1018
@ RTE_RELATION
Definition: parsenodes.h:1017
#define IS_DUMMY_REL(r)
Definition: pathnodes.h:1958
@ 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:518
#define foreach_current_index(var_or_cell)
Definition: pg_list.h:403
#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 forthree(cell1, list1, cell2, list2, cell3, list3)
Definition: pg_list.h:563
#define linitial(l)
Definition: pg_list.h:178
static void * list_nth(const List *list, int n)
Definition: pg_list.h:299
#define plan(x)
Definition: pg_regress.c:161
void mark_partial_aggref(Aggref *agg, AggSplit aggsplit)
Definition: planner.c:5624
@ SUBQUERY_SCAN_NONTRIVIAL
Definition: plannodes.h:596
@ SUBQUERY_SCAN_UNKNOWN
Definition: plannodes.h:594
@ SUBQUERY_SCAN_TRIVIAL
Definition: plannodes.h:595
#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:239
@ PARAM_MULTIEXPR
Definition: primnodes.h:370
#define IS_SPECIAL_VARNO(varno)
Definition: primnodes.h:241
#define OUTER_VAR
Definition: primnodes.h:237
#define INNER_VAR
Definition: primnodes.h:236
#define INDEX_VAR
Definition: primnodes.h:238
tree context
Definition: radixtree.h:1837
tree ctl root
Definition: radixtree.h:1888
static SPIPlanPtr splan
Definition: regress.c:267
RelOptInfo * find_base_rel(PlannerInfo *root, int relid)
Definition: relnode.c:414
RelOptInfo * fetch_upper_rel(PlannerInfo *root, UpperRelationKind kind, Relids relids)
Definition: relnode.c:1458
Node * remove_nulling_relids(Node *node, const Bitmapset *removable_relids, const Bitmapset *except_relids)
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:3516
#define NUM_EXEC_QUAL(parentplan)
Definition: setrefs.c:117
static void set_hash_references(PlannerInfo *root, Plan *plan, int rtoffset)
Definition: setrefs.c:1890
static void fix_expr_common(PlannerInfo *root, Node *node)
Definition: setrefs.c:1967
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:3063
static void add_rte_to_flat_rtable(PlannerGlobal *glob, List *rteperminfos, RangeTblEntry *rte)
Definition: setrefs.c:538
static Plan * set_append_references(PlannerInfo *root, Append *aplan, int rtoffset)
Definition: setrefs.c:1742
static Node * fix_param_node(PlannerInfo *root, Param *p)
Definition: setrefs.c:2062
static Plan * set_mergeappend_references(PlannerInfo *root, MergeAppend *mplan, int rtoffset)
Definition: setrefs.c:1817
static indexed_tlist * build_tlist_index_other_vars(List *tlist, int ignore_rel)
Definition: setrefs.c:2747
static List * set_returning_clause_references(PlannerInfo *root, List *rlist, Plan *topplan, Index resultRelation, int rtoffset)
Definition: setrefs.c:3321
void record_plan_function_dependency(PlannerInfo *root, Oid funcid)
Definition: setrefs.c:3476
static Relids offset_relid_set(Relids relids, int rtoffset)
Definition: setrefs.c:1923
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:2696
static List * set_windowagg_runcondition_references(PlannerInfo *root, List *runcondition, Plan *plan)
Definition: setrefs.c:3416
bool trivial_subqueryscan(SubqueryScan *plan)
Definition: setrefs.c:1465
static void set_upper_references(PlannerInfo *root, Plan *plan, int rtoffset)
Definition: setrefs.c:2418
static Node * fix_alternative_subplan(PlannerInfo *root, AlternativeSubPlan *asplan, double num_exec)
Definition: setrefs.c:2093
static Var * search_indexed_tlist_for_sortgroupref(Expr *node, Index sortgroupref, indexed_tlist *itlist, int newvarno)
Definition: setrefs.c:2963
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:3200
static void set_param_references(PlannerInfo *root, Plan *plan)
Definition: setrefs.c:2506
static Var * search_indexed_tlist_for_non_var(Expr *node, indexed_tlist *itlist, int newvarno)
Definition: setrefs.c:2923
static Node * fix_upper_expr_mutator(Node *node, fix_upper_expr_context *context)
Definition: setrefs.c:3220
static Node * fix_scan_expr_mutator(Node *node, fix_scan_expr_context *context)
Definition: setrefs.c:2184
static void set_foreignscan_references(PlannerInfo *root, ForeignScan *fscan, int rtoffset)
Definition: setrefs.c:1579
static Plan * set_subqueryscan_references(PlannerInfo *root, SubqueryScan *plan, int rtoffset)
Definition: setrefs.c:1396
static Var * search_indexed_tlist_for_phv(PlaceHolderVar *phv, indexed_tlist *itlist, int newvarno, NullingRelsMatch nrm_match)
Definition: setrefs.c:2870
static Plan * set_indexonlyscan_references(PlannerInfo *root, IndexOnlyScan *plan, int rtoffset)
Definition: setrefs.c:1322
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:3041
static Node * convert_combining_aggrefs(Node *node, void *context)
Definition: setrefs.c:2561
static void set_dummy_tlist_references(Plan *plan, int rtoffset)
Definition: setrefs.c:2629
static void set_customscan_references(PlannerInfo *root, CustomScan *cscan, int rtoffset)
Definition: setrefs.c:1666
static Node * fix_windowagg_condition_expr_mutator(Node *node, fix_windowagg_cond_context *context)
Definition: setrefs.c:3365
#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:3557
bool extract_query_dependencies_walker(Node *node, PlannerInfo *context)
Definition: setrefs.c:3593
static Var * copyVar(Var *var)
Definition: setrefs.c:1945
#define NUM_EXEC_TLIST(parentplan)
Definition: setrefs.c:116
Param * find_minmax_agg_replacement_param(PlannerInfo *root, Aggref *aggref)
Definition: setrefs.c:3443
static void set_join_references(PlannerInfo *root, Join *join, int rtoffset)
Definition: setrefs.c:2269
static List * fix_windowagg_condition_expr(PlannerInfo *root, List *runcondition, indexed_tlist *subplan_itlist)
Definition: setrefs.c:3395
static Plan * clean_up_removed_plan_level(Plan *parent, Plan *child)
Definition: setrefs.c:1535
static Node * fix_scan_expr(PlannerInfo *root, Node *node, int rtoffset, double num_exec)
Definition: setrefs.c:2149
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:2249
static Var * search_indexed_tlist_for_var(Var *var, indexed_tlist *itlist, int newvarno, int rtoffset, NullingRelsMatch nrm_match)
Definition: setrefs.c:2805
#define fix_scan_list(root, lst, rtoffset, num_exec)
Definition: setrefs.c:130
Definition: plannodes.h:998
AggSplit aggsplit
Definition: plannodes.h:1005
Oid aggfnoid
Definition: primnodes.h:444
List * aggdistinct
Definition: primnodes.h:474
List * args
Definition: primnodes.h:468
Expr * aggfilter
Definition: primnodes.h:477
List * aggorder
Definition: primnodes.h:471
Index child_relid
Definition: pathnodes.h:2982
List * translated_vars
Definition: pathnodes.h:3009
Index parent_relid
Definition: pathnodes.h:2981
struct PartitionPruneInfo * part_prune_info
Definition: plannodes.h:280
Bitmapset * apprelids
Definition: plannodes.h:269
Plan plan
Definition: plannodes.h:268
List * appendplans
Definition: plannodes.h:270
FuncExpr * funcexpr
Definition: parsenodes.h:3536
List * outargs
Definition: parsenodes.h:3538
List * custom_scan_tlist
Definition: plannodes.h:748
Scan scan
Definition: plannodes.h:742
Bitmapset * custom_relids
Definition: plannodes.h:749
List * custom_plans
Definition: plannodes.h:745
Bitmapset * fs_relids
Definition: plannodes.h:720
Bitmapset * fs_base_relids
Definition: plannodes.h:721
Index resultRelation
Definition: plannodes.h:712
List * fdw_scan_tlist
Definition: plannodes.h:718
List * hashclauses
Definition: plannodes.h:866
List * hashkeys
Definition: plannodes.h:874
List * hashkeys
Definition: plannodes.h:1206
List * joinqual
Definition: plannodes.h:794
JoinType jointype
Definition: plannodes.h:792
Definition: pg_list.h:54
List * param_exprs
Definition: plannodes.h:904
struct PartitionPruneInfo * part_prune_info
Definition: plannodes.h:315
Bitmapset * apprelids
Definition: plannodes.h:293
List * mergeplans
Definition: plannodes.h:295
List * mergeclauses
Definition: plannodes.h:842
Param * param
Definition: pathnodes.h:3145
Expr * target
Definition: pathnodes.h:3130
Var * paramval
Definition: plannodes.h:820
List * nestParams
Definition: plannodes.h:811
Definition: nodes.h:129
int paramid
Definition: primnodes.h:377
ParamKind paramkind
Definition: primnodes.h:376
Relids phnullingrels
Definition: pathnodes.h:2803
uint32 hashValue
Definition: plannodes.h:1574
Index prti
Definition: plannodes.h:1384
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
List * subplans
Definition: pathnodes.h:105
bool dependsOnRole
Definition: pathnodes.h:153
List * appendRelations
Definition: pathnodes.h:129
List * finalrowmarks
Definition: pathnodes.h:123
List * invalItems
Definition: pathnodes.h:135
List * relationOids
Definition: pathnodes.h:132
List * finalrteperminfos
Definition: pathnodes.h:120
List * finalrtable
Definition: pathnodes.h:117
List * init_plans
Definition: pathnodes.h:299
List * rtable
Definition: parsenodes.h:170
CmdType commandType
Definition: parsenodes.h:121
Node * utilityStmt
Definition: parsenodes.h:136
TableFunc * tablefunc
Definition: parsenodes.h:1184
struct TableSampleClause * tablesample
Definition: parsenodes.h:1098
Query * subquery
Definition: parsenodes.h:1104
List * values_lists
Definition: parsenodes.h:1190
List * functions
Definition: parsenodes.h:1177
RTEKind rtekind
Definition: parsenodes.h:1047
Index relid
Definition: pathnodes.h:918
PlannerInfo * subroot
Definition: pathnodes.h:953
Index scanrelid
Definition: plannodes.h:390
int plan_id
Definition: primnodes.h:1070
List * setParam
Definition: primnodes.h:1088
Cost startup_cost
Definition: primnodes.h:1093
Cost per_call_cost
Definition: primnodes.h:1094
Expr * expr
Definition: primnodes.h:2190
AttrNumber resno
Definition: primnodes.h:2192
Index ressortgroupref
Definition: primnodes.h:2196
Definition: primnodes.h:248
AttrNumber varattno
Definition: primnodes.h:260
int varno
Definition: primnodes.h:255
Index varlevelsup
Definition: primnodes.h:280
Node * endOffset
Definition: plannodes.h:1077
List * runConditionOrig
Definition: plannodes.h:1083
Node * startOffset
Definition: plannodes.h:1074
List * runCondition
Definition: plannodes.h:1080
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:282
void SS_compute_initplan_cost(List *init_plans, Cost *initplan_cost_p, bool *unsafe_initplans_p)
Definition: subselect.c:2217
#define GetSysCacheHashValue1(cacheId, key1)
Definition: syscache.h:118
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:2179