]> granicus.if.org Git - postgresql/blob - src/backend/optimizer/plan/setrefs.c
Support multi-argument UNNEST(), and TABLE() syntax for multiple functions.
[postgresql] / src / backend / optimizer / plan / setrefs.c
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-2013, PostgreSQL Global Development Group
8  * Portions Copyright (c) 1994, Regents of the University of California
9  *
10  *
11  * IDENTIFICATION
12  *        src/backend/optimizer/plan/setrefs.c
13  *
14  *-------------------------------------------------------------------------
15  */
16 #include "postgres.h"
17
18 #include "access/transam.h"
19 #include "catalog/pg_type.h"
20 #include "nodes/makefuncs.h"
21 #include "nodes/nodeFuncs.h"
22 #include "optimizer/pathnode.h"
23 #include "optimizer/planmain.h"
24 #include "optimizer/planner.h"
25 #include "optimizer/tlist.h"
26 #include "tcop/utility.h"
27 #include "utils/lsyscache.h"
28 #include "utils/syscache.h"
29
30
31 typedef struct
32 {
33         Index           varno;                  /* RT index of Var */
34         AttrNumber      varattno;               /* attr number of Var */
35         AttrNumber      resno;                  /* TLE position of Var */
36 } tlist_vinfo;
37
38 typedef struct
39 {
40         List       *tlist;                      /* underlying target list */
41         int                     num_vars;               /* number of plain Var tlist entries */
42         bool            has_ph_vars;    /* are there PlaceHolderVar entries? */
43         bool            has_non_vars;   /* are there other entries? */
44         /* array of num_vars entries: */
45         tlist_vinfo vars[1];            /* VARIABLE LENGTH ARRAY */
46 } indexed_tlist;                                /* VARIABLE LENGTH STRUCT */
47
48 typedef struct
49 {
50         PlannerInfo *root;
51         int                     rtoffset;
52 } fix_scan_expr_context;
53
54 typedef struct
55 {
56         PlannerInfo *root;
57         indexed_tlist *outer_itlist;
58         indexed_tlist *inner_itlist;
59         Index           acceptable_rel;
60         int                     rtoffset;
61 } fix_join_expr_context;
62
63 typedef struct
64 {
65         PlannerInfo *root;
66         indexed_tlist *subplan_itlist;
67         Index           newvarno;
68         int                     rtoffset;
69 } fix_upper_expr_context;
70
71 /*
72  * Check if a Const node is a regclass value.  We accept plain OID too,
73  * since a regclass Const will get folded to that type if it's an argument
74  * to oideq or similar operators.  (This might result in some extraneous
75  * values in a plan's list of relation dependencies, but the worst result
76  * would be occasional useless replans.)
77  */
78 #define ISREGCLASSCONST(con) \
79         (((con)->consttype == REGCLASSOID || (con)->consttype == OIDOID) && \
80          !(con)->constisnull)
81
82 #define fix_scan_list(root, lst, rtoffset) \
83         ((List *) fix_scan_expr(root, (Node *) (lst), rtoffset))
84
85 static void add_rtes_to_flat_rtable(PlannerInfo *root, bool recursing);
86 static void flatten_unplanned_rtes(PlannerGlobal *glob, RangeTblEntry *rte);
87 static bool flatten_rtes_walker(Node *node, PlannerGlobal *glob);
88 static void add_rte_to_flat_rtable(PlannerGlobal *glob, RangeTblEntry *rte);
89 static Plan *set_plan_refs(PlannerInfo *root, Plan *plan, int rtoffset);
90 static Plan *set_indexonlyscan_references(PlannerInfo *root,
91                                                          IndexOnlyScan *plan,
92                                                          int rtoffset);
93 static Plan *set_subqueryscan_references(PlannerInfo *root,
94                                                         SubqueryScan *plan,
95                                                         int rtoffset);
96 static bool trivial_subqueryscan(SubqueryScan *plan);
97 static Node *fix_scan_expr(PlannerInfo *root, Node *node, int rtoffset);
98 static Node *fix_scan_expr_mutator(Node *node, fix_scan_expr_context *context);
99 static bool fix_scan_expr_walker(Node *node, fix_scan_expr_context *context);
100 static void set_join_references(PlannerInfo *root, Join *join, int rtoffset);
101 static void set_upper_references(PlannerInfo *root, Plan *plan, int rtoffset);
102 static void set_dummy_tlist_references(Plan *plan, int rtoffset);
103 static indexed_tlist *build_tlist_index(List *tlist);
104 static Var *search_indexed_tlist_for_var(Var *var,
105                                                          indexed_tlist *itlist,
106                                                          Index newvarno,
107                                                          int rtoffset);
108 static Var *search_indexed_tlist_for_non_var(Node *node,
109                                                                  indexed_tlist *itlist,
110                                                                  Index newvarno);
111 static Var *search_indexed_tlist_for_sortgroupref(Node *node,
112                                                                           Index sortgroupref,
113                                                                           indexed_tlist *itlist,
114                                                                           Index newvarno);
115 static List *fix_join_expr(PlannerInfo *root,
116                           List *clauses,
117                           indexed_tlist *outer_itlist,
118                           indexed_tlist *inner_itlist,
119                           Index acceptable_rel, int rtoffset);
120 static Node *fix_join_expr_mutator(Node *node,
121                                           fix_join_expr_context *context);
122 static Node *fix_upper_expr(PlannerInfo *root,
123                            Node *node,
124                            indexed_tlist *subplan_itlist,
125                            Index newvarno,
126                            int rtoffset);
127 static Node *fix_upper_expr_mutator(Node *node,
128                                            fix_upper_expr_context *context);
129 static List *set_returning_clause_references(PlannerInfo *root,
130                                                                 List *rlist,
131                                                                 Plan *topplan,
132                                                                 Index resultRelation,
133                                                                 int rtoffset);
134 static bool fix_opfuncids_walker(Node *node, void *context);
135 static bool extract_query_dependencies_walker(Node *node,
136                                                                   PlannerInfo *context);
137
138
139 /*****************************************************************************
140  *
141  *              SUBPLAN REFERENCES
142  *
143  *****************************************************************************/
144
145 /*
146  * set_plan_references
147  *
148  * This is the final processing pass of the planner/optimizer.  The plan
149  * tree is complete; we just have to adjust some representational details
150  * for the convenience of the executor:
151  *
152  * 1. We flatten the various subquery rangetables into a single list, and
153  * zero out RangeTblEntry fields that are not useful to the executor.
154  *
155  * 2. We adjust Vars in scan nodes to be consistent with the flat rangetable.
156  *
157  * 3. We adjust Vars in upper plan nodes to refer to the outputs of their
158  * subplans.
159  *
160  * 4. We compute regproc OIDs for operators (ie, we look up the function
161  * that implements each op).
162  *
163  * 5. We create lists of specific objects that the plan depends on.
164  * This will be used by plancache.c to drive invalidation of cached plans.
165  * Relation dependencies are represented by OIDs, and everything else by
166  * PlanInvalItems (this distinction is motivated by the shared-inval APIs).
167  * Currently, relations and user-defined functions are the only types of
168  * objects that are explicitly tracked this way.
169  *
170  * We also perform one final optimization step, which is to delete
171  * SubqueryScan plan nodes that aren't doing anything useful (ie, have
172  * no qual and a no-op targetlist).  The reason for doing this last is that
173  * it can't readily be done before set_plan_references, because it would
174  * break set_upper_references: the Vars in the subquery's top tlist
175  * wouldn't match up with the Vars in the outer plan tree.  The SubqueryScan
176  * serves a necessary function as a buffer between outer query and subquery
177  * variable numbering ... but after we've flattened the rangetable this is
178  * no longer a problem, since then there's only one rtindex namespace.
179  *
180  * set_plan_references recursively traverses the whole plan tree.
181  *
182  * The return value is normally the same Plan node passed in, but can be
183  * different when the passed-in Plan is a SubqueryScan we decide isn't needed.
184  *
185  * The flattened rangetable entries are appended to root->glob->finalrtable.
186  * Also, rowmarks entries are appended to root->glob->finalrowmarks, and the
187  * RT indexes of ModifyTable result relations to root->glob->resultRelations.
188  * Plan dependencies are appended to root->glob->relationOids (for relations)
189  * and root->glob->invalItems (for everything else).
190  *
191  * Notice that we modify Plan nodes in-place, but use expression_tree_mutator
192  * to process targetlist and qual expressions.  We can assume that the Plan
193  * nodes were just built by the planner and are not multiply referenced, but
194  * it's not so safe to assume that for expression tree nodes.
195  */
196 Plan *
197 set_plan_references(PlannerInfo *root, Plan *plan)
198 {
199         PlannerGlobal *glob = root->glob;
200         int                     rtoffset = list_length(glob->finalrtable);
201         ListCell   *lc;
202
203         /*
204          * Add all the query's RTEs to the flattened rangetable.  The live ones
205          * will have their rangetable indexes increased by rtoffset.  (Additional
206          * RTEs, not referenced by the Plan tree, might get added after those.)
207          */
208         add_rtes_to_flat_rtable(root, false);
209
210         /*
211          * Adjust RT indexes of PlanRowMarks and add to final rowmarks list
212          */
213         foreach(lc, root->rowMarks)
214         {
215                 PlanRowMark *rc = (PlanRowMark *) lfirst(lc);
216                 PlanRowMark *newrc;
217
218                 Assert(IsA(rc, PlanRowMark));
219
220                 /* flat copy is enough since all fields are scalars */
221                 newrc = (PlanRowMark *) palloc(sizeof(PlanRowMark));
222                 memcpy(newrc, rc, sizeof(PlanRowMark));
223
224                 /* adjust indexes ... but *not* the rowmarkId */
225                 newrc->rti += rtoffset;
226                 newrc->prti += rtoffset;
227
228                 glob->finalrowmarks = lappend(glob->finalrowmarks, newrc);
229         }
230
231         /* Now fix the Plan tree */
232         return set_plan_refs(root, plan, rtoffset);
233 }
234
235 /*
236  * Extract RangeTblEntries from the plan's rangetable, and add to flat rtable
237  *
238  * This can recurse into subquery plans; "recursing" is true if so.
239  */
240 static void
241 add_rtes_to_flat_rtable(PlannerInfo *root, bool recursing)
242 {
243         PlannerGlobal *glob = root->glob;
244         Index           rti;
245         ListCell   *lc;
246
247         /*
248          * Add the query's own RTEs to the flattened rangetable.
249          *
250          * At top level, we must add all RTEs so that their indexes in the
251          * flattened rangetable match up with their original indexes.  When
252          * recursing, we only care about extracting relation RTEs.
253          */
254         foreach(lc, root->parse->rtable)
255         {
256                 RangeTblEntry *rte = (RangeTblEntry *) lfirst(lc);
257
258                 if (!recursing || rte->rtekind == RTE_RELATION)
259                         add_rte_to_flat_rtable(glob, rte);
260         }
261
262         /*
263          * If there are any dead subqueries, they are not referenced in the Plan
264          * tree, so we must add RTEs contained in them to the flattened rtable
265          * separately.  (If we failed to do this, the executor would not perform
266          * expected permission checks for tables mentioned in such subqueries.)
267          *
268          * Note: this pass over the rangetable can't be combined with the previous
269          * one, because that would mess up the numbering of the live RTEs in the
270          * flattened rangetable.
271          */
272         rti = 1;
273         foreach(lc, root->parse->rtable)
274         {
275                 RangeTblEntry *rte = (RangeTblEntry *) lfirst(lc);
276
277                 /*
278                  * We should ignore inheritance-parent RTEs: their contents have been
279                  * pulled up into our rangetable already.  Also ignore any subquery
280                  * RTEs without matching RelOptInfos, as they likewise have been
281                  * pulled up.
282                  */
283                 if (rte->rtekind == RTE_SUBQUERY && !rte->inh)
284                 {
285                         RelOptInfo *rel = root->simple_rel_array[rti];
286
287                         if (rel != NULL)
288                         {
289                                 Assert(rel->relid == rti);              /* sanity check on array */
290
291                                 /*
292                                  * The subquery might never have been planned at all, if it
293                                  * was excluded on the basis of self-contradictory constraints
294                                  * in our query level.  In this case apply
295                                  * flatten_unplanned_rtes.
296                                  *
297                                  * If it was planned but the plan is dummy, we assume that it
298                                  * has been omitted from our plan tree (see
299                                  * set_subquery_pathlist), and recurse to pull up its RTEs.
300                                  *
301                                  * Otherwise, it should be represented by a SubqueryScan node
302                                  * somewhere in our plan tree, and we'll pull up its RTEs when
303                                  * we process that plan node.
304                                  *
305                                  * However, if we're recursing, then we should pull up RTEs
306                                  * whether the subplan is dummy or not, because we've found
307                                  * that some upper query level is treating this one as dummy,
308                                  * and so we won't scan this level's plan tree at all.
309                                  */
310                                 if (rel->subplan == NULL)
311                                         flatten_unplanned_rtes(glob, rte);
312                                 else if (recursing || is_dummy_plan(rel->subplan))
313                                 {
314                                         Assert(rel->subroot != NULL);
315                                         add_rtes_to_flat_rtable(rel->subroot, true);
316                                 }
317                         }
318                 }
319                 rti++;
320         }
321 }
322
323 /*
324  * Extract RangeTblEntries from a subquery that was never planned at all
325  */
326 static void
327 flatten_unplanned_rtes(PlannerGlobal *glob, RangeTblEntry *rte)
328 {
329         /* Use query_tree_walker to find all RTEs in the parse tree */
330         (void) query_tree_walker(rte->subquery,
331                                                          flatten_rtes_walker,
332                                                          (void *) glob,
333                                                          QTW_EXAMINE_RTES);
334 }
335
336 static bool
337 flatten_rtes_walker(Node *node, PlannerGlobal *glob)
338 {
339         if (node == NULL)
340                 return false;
341         if (IsA(node, RangeTblEntry))
342         {
343                 RangeTblEntry *rte = (RangeTblEntry *) node;
344
345                 /* As above, we need only save relation RTEs */
346                 if (rte->rtekind == RTE_RELATION)
347                         add_rte_to_flat_rtable(glob, rte);
348                 return false;
349         }
350         if (IsA(node, Query))
351         {
352                 /* Recurse into subselects */
353                 return query_tree_walker((Query *) node,
354                                                                  flatten_rtes_walker,
355                                                                  (void *) glob,
356                                                                  QTW_EXAMINE_RTES);
357         }
358         return expression_tree_walker(node, flatten_rtes_walker,
359                                                                   (void *) glob);
360 }
361
362 /*
363  * Add (a copy of) the given RTE to the final rangetable
364  *
365  * In the flat rangetable, we zero out substructure pointers that are not
366  * needed by the executor; this reduces the storage space and copying cost
367  * for cached plans.  We keep only the alias and eref Alias fields, which
368  * are needed by EXPLAIN, and the selectedCols and modifiedCols bitmaps,
369  * which are needed for executor-startup permissions checking and for
370  * trigger event checking.
371  */
372 static void
373 add_rte_to_flat_rtable(PlannerGlobal *glob, RangeTblEntry *rte)
374 {
375         RangeTblEntry *newrte;
376
377         /* flat copy to duplicate all the scalar fields */
378         newrte = (RangeTblEntry *) palloc(sizeof(RangeTblEntry));
379         memcpy(newrte, rte, sizeof(RangeTblEntry));
380
381         /* zap unneeded sub-structure */
382         newrte->subquery = NULL;
383         newrte->joinaliasvars = NIL;
384         newrte->functions = NIL;
385         newrte->values_lists = NIL;
386         newrte->values_collations = NIL;
387         newrte->ctecoltypes = NIL;
388         newrte->ctecoltypmods = NIL;
389         newrte->ctecolcollations = NIL;
390
391         glob->finalrtable = lappend(glob->finalrtable, newrte);
392
393         /*
394          * Check for RT index overflow; it's very unlikely, but if it did happen,
395          * the executor would get confused by varnos that match the special varno
396          * values.
397          */
398         if (IS_SPECIAL_VARNO(list_length(glob->finalrtable)))
399                 ereport(ERROR,
400                                 (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
401                                  errmsg("too many range table entries")));
402
403         /*
404          * If it's a plain relation RTE, add the table to relationOids.
405          *
406          * We do this even though the RTE might be unreferenced in the plan tree;
407          * this would correspond to cases such as views that were expanded, child
408          * tables that were eliminated by constraint exclusion, etc. Schema
409          * invalidation on such a rel must still force rebuilding of the plan.
410          *
411          * Note we don't bother to avoid making duplicate list entries.  We could,
412          * but it would probably cost more cycles than it would save.
413          */
414         if (newrte->rtekind == RTE_RELATION)
415                 glob->relationOids = lappend_oid(glob->relationOids, newrte->relid);
416 }
417
418 /*
419  * set_plan_refs: recurse through the Plan nodes of a single subquery level
420  */
421 static Plan *
422 set_plan_refs(PlannerInfo *root, Plan *plan, int rtoffset)
423 {
424         ListCell   *l;
425
426         if (plan == NULL)
427                 return NULL;
428
429         /*
430          * Plan-type-specific fixes
431          */
432         switch (nodeTag(plan))
433         {
434                 case T_SeqScan:
435                         {
436                                 SeqScan    *splan = (SeqScan *) plan;
437
438                                 splan->scanrelid += rtoffset;
439                                 splan->plan.targetlist =
440                                         fix_scan_list(root, splan->plan.targetlist, rtoffset);
441                                 splan->plan.qual =
442                                         fix_scan_list(root, splan->plan.qual, rtoffset);
443                         }
444                         break;
445                 case T_IndexScan:
446                         {
447                                 IndexScan  *splan = (IndexScan *) plan;
448
449                                 splan->scan.scanrelid += rtoffset;
450                                 splan->scan.plan.targetlist =
451                                         fix_scan_list(root, splan->scan.plan.targetlist, rtoffset);
452                                 splan->scan.plan.qual =
453                                         fix_scan_list(root, splan->scan.plan.qual, rtoffset);
454                                 splan->indexqual =
455                                         fix_scan_list(root, splan->indexqual, rtoffset);
456                                 splan->indexqualorig =
457                                         fix_scan_list(root, splan->indexqualorig, rtoffset);
458                                 splan->indexorderby =
459                                         fix_scan_list(root, splan->indexorderby, rtoffset);
460                                 splan->indexorderbyorig =
461                                         fix_scan_list(root, splan->indexorderbyorig, rtoffset);
462                         }
463                         break;
464                 case T_IndexOnlyScan:
465                         {
466                                 IndexOnlyScan *splan = (IndexOnlyScan *) plan;
467
468                                 return set_indexonlyscan_references(root, splan, rtoffset);
469                         }
470                         break;
471                 case T_BitmapIndexScan:
472                         {
473                                 BitmapIndexScan *splan = (BitmapIndexScan *) plan;
474
475                                 splan->scan.scanrelid += rtoffset;
476                                 /* no need to fix targetlist and qual */
477                                 Assert(splan->scan.plan.targetlist == NIL);
478                                 Assert(splan->scan.plan.qual == NIL);
479                                 splan->indexqual =
480                                         fix_scan_list(root, splan->indexqual, rtoffset);
481                                 splan->indexqualorig =
482                                         fix_scan_list(root, splan->indexqualorig, rtoffset);
483                         }
484                         break;
485                 case T_BitmapHeapScan:
486                         {
487                                 BitmapHeapScan *splan = (BitmapHeapScan *) plan;
488
489                                 splan->scan.scanrelid += rtoffset;
490                                 splan->scan.plan.targetlist =
491                                         fix_scan_list(root, splan->scan.plan.targetlist, rtoffset);
492                                 splan->scan.plan.qual =
493                                         fix_scan_list(root, splan->scan.plan.qual, rtoffset);
494                                 splan->bitmapqualorig =
495                                         fix_scan_list(root, splan->bitmapqualorig, rtoffset);
496                         }
497                         break;
498                 case T_TidScan:
499                         {
500                                 TidScan    *splan = (TidScan *) plan;
501
502                                 splan->scan.scanrelid += rtoffset;
503                                 splan->scan.plan.targetlist =
504                                         fix_scan_list(root, splan->scan.plan.targetlist, rtoffset);
505                                 splan->scan.plan.qual =
506                                         fix_scan_list(root, splan->scan.plan.qual, rtoffset);
507                                 splan->tidquals =
508                                         fix_scan_list(root, splan->tidquals, rtoffset);
509                         }
510                         break;
511                 case T_SubqueryScan:
512                         /* Needs special treatment, see comments below */
513                         return set_subqueryscan_references(root,
514                                                                                            (SubqueryScan *) plan,
515                                                                                            rtoffset);
516                 case T_FunctionScan:
517                         {
518                                 FunctionScan *splan = (FunctionScan *) plan;
519
520                                 splan->scan.scanrelid += rtoffset;
521                                 splan->scan.plan.targetlist =
522                                         fix_scan_list(root, splan->scan.plan.targetlist, rtoffset);
523                                 splan->scan.plan.qual =
524                                         fix_scan_list(root, splan->scan.plan.qual, rtoffset);
525                                 splan->functions =
526                                         fix_scan_list(root, splan->functions, rtoffset);
527                         }
528                         break;
529                 case T_ValuesScan:
530                         {
531                                 ValuesScan *splan = (ValuesScan *) plan;
532
533                                 splan->scan.scanrelid += rtoffset;
534                                 splan->scan.plan.targetlist =
535                                         fix_scan_list(root, splan->scan.plan.targetlist, rtoffset);
536                                 splan->scan.plan.qual =
537                                         fix_scan_list(root, splan->scan.plan.qual, rtoffset);
538                                 splan->values_lists =
539                                         fix_scan_list(root, splan->values_lists, rtoffset);
540                         }
541                         break;
542                 case T_CteScan:
543                         {
544                                 CteScan    *splan = (CteScan *) plan;
545
546                                 splan->scan.scanrelid += rtoffset;
547                                 splan->scan.plan.targetlist =
548                                         fix_scan_list(root, splan->scan.plan.targetlist, rtoffset);
549                                 splan->scan.plan.qual =
550                                         fix_scan_list(root, splan->scan.plan.qual, rtoffset);
551                         }
552                         break;
553                 case T_WorkTableScan:
554                         {
555                                 WorkTableScan *splan = (WorkTableScan *) plan;
556
557                                 splan->scan.scanrelid += rtoffset;
558                                 splan->scan.plan.targetlist =
559                                         fix_scan_list(root, splan->scan.plan.targetlist, rtoffset);
560                                 splan->scan.plan.qual =
561                                         fix_scan_list(root, splan->scan.plan.qual, rtoffset);
562                         }
563                         break;
564                 case T_ForeignScan:
565                         {
566                                 ForeignScan *splan = (ForeignScan *) plan;
567
568                                 splan->scan.scanrelid += rtoffset;
569                                 splan->scan.plan.targetlist =
570                                         fix_scan_list(root, splan->scan.plan.targetlist, rtoffset);
571                                 splan->scan.plan.qual =
572                                         fix_scan_list(root, splan->scan.plan.qual, rtoffset);
573                                 splan->fdw_exprs =
574                                         fix_scan_list(root, splan->fdw_exprs, rtoffset);
575                         }
576                         break;
577
578                 case T_NestLoop:
579                 case T_MergeJoin:
580                 case T_HashJoin:
581                         set_join_references(root, (Join *) plan, rtoffset);
582                         break;
583
584                 case T_Hash:
585                 case T_Material:
586                 case T_Sort:
587                 case T_Unique:
588                 case T_SetOp:
589
590                         /*
591                          * These plan types don't actually bother to evaluate their
592                          * targetlists, because they just return their unmodified input
593                          * tuples.      Even though the targetlist won't be used by the
594                          * executor, we fix it up for possible use by EXPLAIN (not to
595                          * mention ease of debugging --- wrong varnos are very confusing).
596                          */
597                         set_dummy_tlist_references(plan, rtoffset);
598
599                         /*
600                          * Since these plan types don't check quals either, we should not
601                          * find any qual expression attached to them.
602                          */
603                         Assert(plan->qual == NIL);
604                         break;
605                 case T_LockRows:
606                         {
607                                 LockRows   *splan = (LockRows *) plan;
608
609                                 /*
610                                  * Like the plan types above, LockRows doesn't evaluate its
611                                  * tlist or quals.      But we have to fix up the RT indexes in
612                                  * its rowmarks.
613                                  */
614                                 set_dummy_tlist_references(plan, rtoffset);
615                                 Assert(splan->plan.qual == NIL);
616
617                                 foreach(l, splan->rowMarks)
618                                 {
619                                         PlanRowMark *rc = (PlanRowMark *) lfirst(l);
620
621                                         rc->rti += rtoffset;
622                                         rc->prti += rtoffset;
623                                 }
624                         }
625                         break;
626                 case T_Limit:
627                         {
628                                 Limit      *splan = (Limit *) plan;
629
630                                 /*
631                                  * Like the plan types above, Limit doesn't evaluate its tlist
632                                  * or quals.  It does have live expressions for limit/offset,
633                                  * however; and those cannot contain subplan variable refs, so
634                                  * fix_scan_expr works for them.
635                                  */
636                                 set_dummy_tlist_references(plan, rtoffset);
637                                 Assert(splan->plan.qual == NIL);
638
639                                 splan->limitOffset =
640                                         fix_scan_expr(root, splan->limitOffset, rtoffset);
641                                 splan->limitCount =
642                                         fix_scan_expr(root, splan->limitCount, rtoffset);
643                         }
644                         break;
645                 case T_Agg:
646                 case T_Group:
647                         set_upper_references(root, plan, rtoffset);
648                         break;
649                 case T_WindowAgg:
650                         {
651                                 WindowAgg  *wplan = (WindowAgg *) plan;
652
653                                 set_upper_references(root, plan, rtoffset);
654
655                                 /*
656                                  * Like Limit node limit/offset expressions, WindowAgg has
657                                  * frame offset expressions, which cannot contain subplan
658                                  * variable refs, so fix_scan_expr works for them.
659                                  */
660                                 wplan->startOffset =
661                                         fix_scan_expr(root, wplan->startOffset, rtoffset);
662                                 wplan->endOffset =
663                                         fix_scan_expr(root, wplan->endOffset, rtoffset);
664                         }
665                         break;
666                 case T_Result:
667                         {
668                                 Result     *splan = (Result *) plan;
669
670                                 /*
671                                  * Result may or may not have a subplan; if not, it's more
672                                  * like a scan node than an upper node.
673                                  */
674                                 if (splan->plan.lefttree != NULL)
675                                         set_upper_references(root, plan, rtoffset);
676                                 else
677                                 {
678                                         splan->plan.targetlist =
679                                                 fix_scan_list(root, splan->plan.targetlist, rtoffset);
680                                         splan->plan.qual =
681                                                 fix_scan_list(root, splan->plan.qual, rtoffset);
682                                 }
683                                 /* resconstantqual can't contain any subplan variable refs */
684                                 splan->resconstantqual =
685                                         fix_scan_expr(root, splan->resconstantqual, rtoffset);
686                         }
687                         break;
688                 case T_ModifyTable:
689                         {
690                                 ModifyTable *splan = (ModifyTable *) plan;
691
692                                 Assert(splan->plan.targetlist == NIL);
693                                 Assert(splan->plan.qual == NIL);
694
695                                 if (splan->returningLists)
696                                 {
697                                         List       *newRL = NIL;
698                                         ListCell   *lcrl,
699                                                            *lcrr,
700                                                            *lcp;
701
702                                         /*
703                                          * Pass each per-subplan returningList through
704                                          * set_returning_clause_references().
705                                          */
706                                         Assert(list_length(splan->returningLists) == list_length(splan->resultRelations));
707                                         Assert(list_length(splan->returningLists) == list_length(splan->plans));
708                                         forthree(lcrl, splan->returningLists,
709                                                          lcrr, splan->resultRelations,
710                                                          lcp, splan->plans)
711                                         {
712                                                 List       *rlist = (List *) lfirst(lcrl);
713                                                 Index           resultrel = lfirst_int(lcrr);
714                                                 Plan       *subplan = (Plan *) lfirst(lcp);
715
716                                                 rlist = set_returning_clause_references(root,
717                                                                                                                                 rlist,
718                                                                                                                                 subplan,
719                                                                                                                                 resultrel,
720                                                                                                                                 rtoffset);
721                                                 newRL = lappend(newRL, rlist);
722                                         }
723                                         splan->returningLists = newRL;
724
725                                         /*
726                                          * Set up the visible plan targetlist as being the same as
727                                          * the first RETURNING list. This is for the use of
728                                          * EXPLAIN; the executor won't pay any attention to the
729                                          * targetlist.  We postpone this step until here so that
730                                          * we don't have to do set_returning_clause_references()
731                                          * twice on identical targetlists.
732                                          */
733                                         splan->plan.targetlist = copyObject(linitial(newRL));
734                                 }
735
736                                 foreach(l, splan->resultRelations)
737                                 {
738                                         lfirst_int(l) += rtoffset;
739                                 }
740                                 foreach(l, splan->rowMarks)
741                                 {
742                                         PlanRowMark *rc = (PlanRowMark *) lfirst(l);
743
744                                         rc->rti += rtoffset;
745                                         rc->prti += rtoffset;
746                                 }
747                                 foreach(l, splan->plans)
748                                 {
749                                         lfirst(l) = set_plan_refs(root,
750                                                                                           (Plan *) lfirst(l),
751                                                                                           rtoffset);
752                                 }
753
754                                 /*
755                                  * Append this ModifyTable node's final result relation RT
756                                  * index(es) to the global list for the plan, and set its
757                                  * resultRelIndex to reflect their starting position in the
758                                  * global list.
759                                  */
760                                 splan->resultRelIndex = list_length(root->glob->resultRelations);
761                                 root->glob->resultRelations =
762                                         list_concat(root->glob->resultRelations,
763                                                                 list_copy(splan->resultRelations));
764                         }
765                         break;
766                 case T_Append:
767                         {
768                                 Append     *splan = (Append *) plan;
769
770                                 /*
771                                  * Append, like Sort et al, doesn't actually evaluate its
772                                  * targetlist or check quals.
773                                  */
774                                 set_dummy_tlist_references(plan, rtoffset);
775                                 Assert(splan->plan.qual == NIL);
776                                 foreach(l, splan->appendplans)
777                                 {
778                                         lfirst(l) = set_plan_refs(root,
779                                                                                           (Plan *) lfirst(l),
780                                                                                           rtoffset);
781                                 }
782                         }
783                         break;
784                 case T_MergeAppend:
785                         {
786                                 MergeAppend *splan = (MergeAppend *) plan;
787
788                                 /*
789                                  * MergeAppend, like Sort et al, doesn't actually evaluate its
790                                  * targetlist or check quals.
791                                  */
792                                 set_dummy_tlist_references(plan, rtoffset);
793                                 Assert(splan->plan.qual == NIL);
794                                 foreach(l, splan->mergeplans)
795                                 {
796                                         lfirst(l) = set_plan_refs(root,
797                                                                                           (Plan *) lfirst(l),
798                                                                                           rtoffset);
799                                 }
800                         }
801                         break;
802                 case T_RecursiveUnion:
803                         /* This doesn't evaluate targetlist or check quals either */
804                         set_dummy_tlist_references(plan, rtoffset);
805                         Assert(plan->qual == NIL);
806                         break;
807                 case T_BitmapAnd:
808                         {
809                                 BitmapAnd  *splan = (BitmapAnd *) plan;
810
811                                 /* BitmapAnd works like Append, but has no tlist */
812                                 Assert(splan->plan.targetlist == NIL);
813                                 Assert(splan->plan.qual == NIL);
814                                 foreach(l, splan->bitmapplans)
815                                 {
816                                         lfirst(l) = set_plan_refs(root,
817                                                                                           (Plan *) lfirst(l),
818                                                                                           rtoffset);
819                                 }
820                         }
821                         break;
822                 case T_BitmapOr:
823                         {
824                                 BitmapOr   *splan = (BitmapOr *) plan;
825
826                                 /* BitmapOr works like Append, but has no tlist */
827                                 Assert(splan->plan.targetlist == NIL);
828                                 Assert(splan->plan.qual == NIL);
829                                 foreach(l, splan->bitmapplans)
830                                 {
831                                         lfirst(l) = set_plan_refs(root,
832                                                                                           (Plan *) lfirst(l),
833                                                                                           rtoffset);
834                                 }
835                         }
836                         break;
837                 default:
838                         elog(ERROR, "unrecognized node type: %d",
839                                  (int) nodeTag(plan));
840                         break;
841         }
842
843         /*
844          * Now recurse into child plans, if any
845          *
846          * NOTE: it is essential that we recurse into child plans AFTER we set
847          * subplan references in this plan's tlist and quals.  If we did the
848          * reference-adjustments bottom-up, then we would fail to match this
849          * plan's var nodes against the already-modified nodes of the children.
850          */
851         plan->lefttree = set_plan_refs(root, plan->lefttree, rtoffset);
852         plan->righttree = set_plan_refs(root, plan->righttree, rtoffset);
853
854         return plan;
855 }
856
857 /*
858  * set_indexonlyscan_references
859  *              Do set_plan_references processing on an IndexOnlyScan
860  *
861  * This is unlike the handling of a plain IndexScan because we have to
862  * convert Vars referencing the heap into Vars referencing the index.
863  * We can use the fix_upper_expr machinery for that, by working from a
864  * targetlist describing the index columns.
865  */
866 static Plan *
867 set_indexonlyscan_references(PlannerInfo *root,
868                                                          IndexOnlyScan *plan,
869                                                          int rtoffset)
870 {
871         indexed_tlist *index_itlist;
872
873         index_itlist = build_tlist_index(plan->indextlist);
874
875         plan->scan.scanrelid += rtoffset;
876         plan->scan.plan.targetlist = (List *)
877                 fix_upper_expr(root,
878                                            (Node *) plan->scan.plan.targetlist,
879                                            index_itlist,
880                                            INDEX_VAR,
881                                            rtoffset);
882         plan->scan.plan.qual = (List *)
883                 fix_upper_expr(root,
884                                            (Node *) plan->scan.plan.qual,
885                                            index_itlist,
886                                            INDEX_VAR,
887                                            rtoffset);
888         /* indexqual is already transformed to reference index columns */
889         plan->indexqual = fix_scan_list(root, plan->indexqual, rtoffset);
890         /* indexorderby is already transformed to reference index columns */
891         plan->indexorderby = fix_scan_list(root, plan->indexorderby, rtoffset);
892         /* indextlist must NOT be transformed to reference index columns */
893         plan->indextlist = fix_scan_list(root, plan->indextlist, rtoffset);
894
895         pfree(index_itlist);
896
897         return (Plan *) plan;
898 }
899
900 /*
901  * set_subqueryscan_references
902  *              Do set_plan_references processing on a SubqueryScan
903  *
904  * We try to strip out the SubqueryScan entirely; if we can't, we have
905  * to do the normal processing on it.
906  */
907 static Plan *
908 set_subqueryscan_references(PlannerInfo *root,
909                                                         SubqueryScan *plan,
910                                                         int rtoffset)
911 {
912         RelOptInfo *rel;
913         Plan       *result;
914
915         /* Need to look up the subquery's RelOptInfo, since we need its subroot */
916         rel = find_base_rel(root, plan->scan.scanrelid);
917         Assert(rel->subplan == plan->subplan);
918
919         /* Recursively process the subplan */
920         plan->subplan = set_plan_references(rel->subroot, plan->subplan);
921
922         if (trivial_subqueryscan(plan))
923         {
924                 /*
925                  * We can omit the SubqueryScan node and just pull up the subplan.
926                  */
927                 ListCell   *lp,
928                                    *lc;
929
930                 result = plan->subplan;
931
932                 /* We have to be sure we don't lose any initplans */
933                 result->initPlan = list_concat(plan->scan.plan.initPlan,
934                                                                            result->initPlan);
935
936                 /*
937                  * We also have to transfer the SubqueryScan's result-column names
938                  * into the subplan, else columns sent to client will be improperly
939                  * labeled if this is the topmost plan level.  Copy the "source
940                  * column" information too.
941                  */
942                 forboth(lp, plan->scan.plan.targetlist, lc, result->targetlist)
943                 {
944                         TargetEntry *ptle = (TargetEntry *) lfirst(lp);
945                         TargetEntry *ctle = (TargetEntry *) lfirst(lc);
946
947                         ctle->resname = ptle->resname;
948                         ctle->resorigtbl = ptle->resorigtbl;
949                         ctle->resorigcol = ptle->resorigcol;
950                 }
951         }
952         else
953         {
954                 /*
955                  * Keep the SubqueryScan node.  We have to do the processing that
956                  * set_plan_references would otherwise have done on it.  Notice we do
957                  * not do set_upper_references() here, because a SubqueryScan will
958                  * always have been created with correct references to its subplan's
959                  * outputs to begin with.
960                  */
961                 plan->scan.scanrelid += rtoffset;
962                 plan->scan.plan.targetlist =
963                         fix_scan_list(root, plan->scan.plan.targetlist, rtoffset);
964                 plan->scan.plan.qual =
965                         fix_scan_list(root, plan->scan.plan.qual, rtoffset);
966
967                 result = (Plan *) plan;
968         }
969
970         return result;
971 }
972
973 /*
974  * trivial_subqueryscan
975  *              Detect whether a SubqueryScan can be deleted from the plan tree.
976  *
977  * We can delete it if it has no qual to check and the targetlist just
978  * regurgitates the output of the child plan.
979  */
980 static bool
981 trivial_subqueryscan(SubqueryScan *plan)
982 {
983         int                     attrno;
984         ListCell   *lp,
985                            *lc;
986
987         if (plan->scan.plan.qual != NIL)
988                 return false;
989
990         if (list_length(plan->scan.plan.targetlist) !=
991                 list_length(plan->subplan->targetlist))
992                 return false;                   /* tlists not same length */
993
994         attrno = 1;
995         forboth(lp, plan->scan.plan.targetlist, lc, plan->subplan->targetlist)
996         {
997                 TargetEntry *ptle = (TargetEntry *) lfirst(lp);
998                 TargetEntry *ctle = (TargetEntry *) lfirst(lc);
999
1000                 if (ptle->resjunk != ctle->resjunk)
1001                         return false;           /* tlist doesn't match junk status */
1002
1003                 /*
1004                  * We accept either a Var referencing the corresponding element of the
1005                  * subplan tlist, or a Const equaling the subplan element. See
1006                  * generate_setop_tlist() for motivation.
1007                  */
1008                 if (ptle->expr && IsA(ptle->expr, Var))
1009                 {
1010                         Var                *var = (Var *) ptle->expr;
1011
1012                         Assert(var->varno == plan->scan.scanrelid);
1013                         Assert(var->varlevelsup == 0);
1014                         if (var->varattno != attrno)
1015                                 return false;   /* out of order */
1016                 }
1017                 else if (ptle->expr && IsA(ptle->expr, Const))
1018                 {
1019                         if (!equal(ptle->expr, ctle->expr))
1020                                 return false;
1021                 }
1022                 else
1023                         return false;
1024
1025                 attrno++;
1026         }
1027
1028         return true;
1029 }
1030
1031 /*
1032  * copyVar
1033  *              Copy a Var node.
1034  *
1035  * fix_scan_expr and friends do this enough times that it's worth having
1036  * a bespoke routine instead of using the generic copyObject() function.
1037  */
1038 static inline Var *
1039 copyVar(Var *var)
1040 {
1041         Var                *newvar = (Var *) palloc(sizeof(Var));
1042
1043         *newvar = *var;
1044         return newvar;
1045 }
1046
1047 /*
1048  * fix_expr_common
1049  *              Do generic set_plan_references processing on an expression node
1050  *
1051  * This is code that is common to all variants of expression-fixing.
1052  * We must look up operator opcode info for OpExpr and related nodes,
1053  * add OIDs from regclass Const nodes into root->glob->relationOids, and
1054  * add catalog TIDs for user-defined functions into root->glob->invalItems.
1055  *
1056  * We assume it's okay to update opcode info in-place.  So this could possibly
1057  * scribble on the planner's input data structures, but it's OK.
1058  */
1059 static void
1060 fix_expr_common(PlannerInfo *root, Node *node)
1061 {
1062         /* We assume callers won't call us on a NULL pointer */
1063         if (IsA(node, Aggref))
1064         {
1065                 record_plan_function_dependency(root,
1066                                                                                 ((Aggref *) node)->aggfnoid);
1067         }
1068         else if (IsA(node, WindowFunc))
1069         {
1070                 record_plan_function_dependency(root,
1071                                                                                 ((WindowFunc *) node)->winfnoid);
1072         }
1073         else if (IsA(node, FuncExpr))
1074         {
1075                 record_plan_function_dependency(root,
1076                                                                                 ((FuncExpr *) node)->funcid);
1077         }
1078         else if (IsA(node, OpExpr))
1079         {
1080                 set_opfuncid((OpExpr *) node);
1081                 record_plan_function_dependency(root,
1082                                                                                 ((OpExpr *) node)->opfuncid);
1083         }
1084         else if (IsA(node, DistinctExpr))
1085         {
1086                 set_opfuncid((OpExpr *) node);  /* rely on struct equivalence */
1087                 record_plan_function_dependency(root,
1088                                                                                 ((DistinctExpr *) node)->opfuncid);
1089         }
1090         else if (IsA(node, NullIfExpr))
1091         {
1092                 set_opfuncid((OpExpr *) node);  /* rely on struct equivalence */
1093                 record_plan_function_dependency(root,
1094                                                                                 ((NullIfExpr *) node)->opfuncid);
1095         }
1096         else if (IsA(node, ScalarArrayOpExpr))
1097         {
1098                 set_sa_opfuncid((ScalarArrayOpExpr *) node);
1099                 record_plan_function_dependency(root,
1100                                                                          ((ScalarArrayOpExpr *) node)->opfuncid);
1101         }
1102         else if (IsA(node, ArrayCoerceExpr))
1103         {
1104                 if (OidIsValid(((ArrayCoerceExpr *) node)->elemfuncid))
1105                         record_plan_function_dependency(root,
1106                                                                          ((ArrayCoerceExpr *) node)->elemfuncid);
1107         }
1108         else if (IsA(node, Const))
1109         {
1110                 Const      *con = (Const *) node;
1111
1112                 /* Check for regclass reference */
1113                 if (ISREGCLASSCONST(con))
1114                         root->glob->relationOids =
1115                                 lappend_oid(root->glob->relationOids,
1116                                                         DatumGetObjectId(con->constvalue));
1117         }
1118 }
1119
1120 /*
1121  * fix_scan_expr
1122  *              Do set_plan_references processing on a scan-level expression
1123  *
1124  * This consists of incrementing all Vars' varnos by rtoffset,
1125  * looking up operator opcode info for OpExpr and related nodes,
1126  * and adding OIDs from regclass Const nodes into root->glob->relationOids.
1127  */
1128 static Node *
1129 fix_scan_expr(PlannerInfo *root, Node *node, int rtoffset)
1130 {
1131         fix_scan_expr_context context;
1132
1133         context.root = root;
1134         context.rtoffset = rtoffset;
1135
1136         if (rtoffset != 0 || root->glob->lastPHId != 0)
1137         {
1138                 return fix_scan_expr_mutator(node, &context);
1139         }
1140         else
1141         {
1142                 /*
1143                  * If rtoffset == 0, we don't need to change any Vars, and if there
1144                  * are no placeholders anywhere we won't need to remove them.  Then
1145                  * it's OK to just scribble on the input node tree instead of copying
1146                  * (since the only change, filling in any unset opfuncid fields, is
1147                  * harmless).  This saves just enough cycles to be noticeable on
1148                  * trivial queries.
1149                  */
1150                 (void) fix_scan_expr_walker(node, &context);
1151                 return node;
1152         }
1153 }
1154
1155 static Node *
1156 fix_scan_expr_mutator(Node *node, fix_scan_expr_context *context)
1157 {
1158         if (node == NULL)
1159                 return NULL;
1160         if (IsA(node, Var))
1161         {
1162                 Var                *var = copyVar((Var *) node);
1163
1164                 Assert(var->varlevelsup == 0);
1165
1166                 /*
1167                  * We should not see any Vars marked INNER_VAR or OUTER_VAR.  But an
1168                  * indexqual expression could contain INDEX_VAR Vars.
1169                  */
1170                 Assert(var->varno != INNER_VAR);
1171                 Assert(var->varno != OUTER_VAR);
1172                 if (!IS_SPECIAL_VARNO(var->varno))
1173                         var->varno += context->rtoffset;
1174                 if (var->varnoold > 0)
1175                         var->varnoold += context->rtoffset;
1176                 return (Node *) var;
1177         }
1178         if (IsA(node, CurrentOfExpr))
1179         {
1180                 CurrentOfExpr *cexpr = (CurrentOfExpr *) copyObject(node);
1181
1182                 Assert(cexpr->cvarno != INNER_VAR);
1183                 Assert(cexpr->cvarno != OUTER_VAR);
1184                 if (!IS_SPECIAL_VARNO(cexpr->cvarno))
1185                         cexpr->cvarno += context->rtoffset;
1186                 return (Node *) cexpr;
1187         }
1188         if (IsA(node, PlaceHolderVar))
1189         {
1190                 /* At scan level, we should always just evaluate the contained expr */
1191                 PlaceHolderVar *phv = (PlaceHolderVar *) node;
1192
1193                 return fix_scan_expr_mutator((Node *) phv->phexpr, context);
1194         }
1195         fix_expr_common(context->root, node);
1196         return expression_tree_mutator(node, fix_scan_expr_mutator,
1197                                                                    (void *) context);
1198 }
1199
1200 static bool
1201 fix_scan_expr_walker(Node *node, fix_scan_expr_context *context)
1202 {
1203         if (node == NULL)
1204                 return false;
1205         Assert(!IsA(node, PlaceHolderVar));
1206         fix_expr_common(context->root, node);
1207         return expression_tree_walker(node, fix_scan_expr_walker,
1208                                                                   (void *) context);
1209 }
1210
1211 /*
1212  * set_join_references
1213  *        Modify the target list and quals of a join node to reference its
1214  *        subplans, by setting the varnos to OUTER_VAR or INNER_VAR and setting
1215  *        attno values to the result domain number of either the corresponding
1216  *        outer or inner join tuple item.  Also perform opcode lookup for these
1217  *        expressions. and add regclass OIDs to root->glob->relationOids.
1218  */
1219 static void
1220 set_join_references(PlannerInfo *root, Join *join, int rtoffset)
1221 {
1222         Plan       *outer_plan = join->plan.lefttree;
1223         Plan       *inner_plan = join->plan.righttree;
1224         indexed_tlist *outer_itlist;
1225         indexed_tlist *inner_itlist;
1226
1227         outer_itlist = build_tlist_index(outer_plan->targetlist);
1228         inner_itlist = build_tlist_index(inner_plan->targetlist);
1229
1230         /* All join plans have tlist, qual, and joinqual */
1231         join->plan.targetlist = fix_join_expr(root,
1232                                                                                   join->plan.targetlist,
1233                                                                                   outer_itlist,
1234                                                                                   inner_itlist,
1235                                                                                   (Index) 0,
1236                                                                                   rtoffset);
1237         join->plan.qual = fix_join_expr(root,
1238                                                                         join->plan.qual,
1239                                                                         outer_itlist,
1240                                                                         inner_itlist,
1241                                                                         (Index) 0,
1242                                                                         rtoffset);
1243         join->joinqual = fix_join_expr(root,
1244                                                                    join->joinqual,
1245                                                                    outer_itlist,
1246                                                                    inner_itlist,
1247                                                                    (Index) 0,
1248                                                                    rtoffset);
1249
1250         /* Now do join-type-specific stuff */
1251         if (IsA(join, NestLoop))
1252         {
1253                 NestLoop   *nl = (NestLoop *) join;
1254                 ListCell   *lc;
1255
1256                 foreach(lc, nl->nestParams)
1257                 {
1258                         NestLoopParam *nlp = (NestLoopParam *) lfirst(lc);
1259
1260                         nlp->paramval = (Var *) fix_upper_expr(root,
1261                                                                                                    (Node *) nlp->paramval,
1262                                                                                                    outer_itlist,
1263                                                                                                    OUTER_VAR,
1264                                                                                                    rtoffset);
1265                         /* Check we replaced any PlaceHolderVar with simple Var */
1266                         if (!(IsA(nlp->paramval, Var) &&
1267                                   nlp->paramval->varno == OUTER_VAR))
1268                                 elog(ERROR, "NestLoopParam was not reduced to a simple Var");
1269                 }
1270         }
1271         else if (IsA(join, MergeJoin))
1272         {
1273                 MergeJoin  *mj = (MergeJoin *) join;
1274
1275                 mj->mergeclauses = fix_join_expr(root,
1276                                                                                  mj->mergeclauses,
1277                                                                                  outer_itlist,
1278                                                                                  inner_itlist,
1279                                                                                  (Index) 0,
1280                                                                                  rtoffset);
1281         }
1282         else if (IsA(join, HashJoin))
1283         {
1284                 HashJoin   *hj = (HashJoin *) join;
1285
1286                 hj->hashclauses = fix_join_expr(root,
1287                                                                                 hj->hashclauses,
1288                                                                                 outer_itlist,
1289                                                                                 inner_itlist,
1290                                                                                 (Index) 0,
1291                                                                                 rtoffset);
1292         }
1293
1294         pfree(outer_itlist);
1295         pfree(inner_itlist);
1296 }
1297
1298 /*
1299  * set_upper_references
1300  *        Update the targetlist and quals of an upper-level plan node
1301  *        to refer to the tuples returned by its lefttree subplan.
1302  *        Also perform opcode lookup for these expressions, and
1303  *        add regclass OIDs to root->glob->relationOids.
1304  *
1305  * This is used for single-input plan types like Agg, Group, Result.
1306  *
1307  * In most cases, we have to match up individual Vars in the tlist and
1308  * qual expressions with elements of the subplan's tlist (which was
1309  * generated by flatten_tlist() from these selfsame expressions, so it
1310  * should have all the required variables).  There is an important exception,
1311  * however: GROUP BY and ORDER BY expressions will have been pushed into the
1312  * subplan tlist unflattened.  If these values are also needed in the output
1313  * then we want to reference the subplan tlist element rather than recomputing
1314  * the expression.
1315  */
1316 static void
1317 set_upper_references(PlannerInfo *root, Plan *plan, int rtoffset)
1318 {
1319         Plan       *subplan = plan->lefttree;
1320         indexed_tlist *subplan_itlist;
1321         List       *output_targetlist;
1322         ListCell   *l;
1323
1324         subplan_itlist = build_tlist_index(subplan->targetlist);
1325
1326         output_targetlist = NIL;
1327         foreach(l, plan->targetlist)
1328         {
1329                 TargetEntry *tle = (TargetEntry *) lfirst(l);
1330                 Node       *newexpr;
1331
1332                 /* If it's a non-Var sort/group item, first try to match by sortref */
1333                 if (tle->ressortgroupref != 0 && !IsA(tle->expr, Var))
1334                 {
1335                         newexpr = (Node *)
1336                                 search_indexed_tlist_for_sortgroupref((Node *) tle->expr,
1337                                                                                                           tle->ressortgroupref,
1338                                                                                                           subplan_itlist,
1339                                                                                                           OUTER_VAR);
1340                         if (!newexpr)
1341                                 newexpr = fix_upper_expr(root,
1342                                                                                  (Node *) tle->expr,
1343                                                                                  subplan_itlist,
1344                                                                                  OUTER_VAR,
1345                                                                                  rtoffset);
1346                 }
1347                 else
1348                         newexpr = fix_upper_expr(root,
1349                                                                          (Node *) tle->expr,
1350                                                                          subplan_itlist,
1351                                                                          OUTER_VAR,
1352                                                                          rtoffset);
1353                 tle = flatCopyTargetEntry(tle);
1354                 tle->expr = (Expr *) newexpr;
1355                 output_targetlist = lappend(output_targetlist, tle);
1356         }
1357         plan->targetlist = output_targetlist;
1358
1359         plan->qual = (List *)
1360                 fix_upper_expr(root,
1361                                            (Node *) plan->qual,
1362                                            subplan_itlist,
1363                                            OUTER_VAR,
1364                                            rtoffset);
1365
1366         pfree(subplan_itlist);
1367 }
1368
1369 /*
1370  * set_dummy_tlist_references
1371  *        Replace the targetlist of an upper-level plan node with a simple
1372  *        list of OUTER_VAR references to its child.
1373  *
1374  * This is used for plan types like Sort and Append that don't evaluate
1375  * their targetlists.  Although the executor doesn't care at all what's in
1376  * the tlist, EXPLAIN needs it to be realistic.
1377  *
1378  * Note: we could almost use set_upper_references() here, but it fails for
1379  * Append for lack of a lefttree subplan.  Single-purpose code is faster
1380  * anyway.
1381  */
1382 static void
1383 set_dummy_tlist_references(Plan *plan, int rtoffset)
1384 {
1385         List       *output_targetlist;
1386         ListCell   *l;
1387
1388         output_targetlist = NIL;
1389         foreach(l, plan->targetlist)
1390         {
1391                 TargetEntry *tle = (TargetEntry *) lfirst(l);
1392                 Var                *oldvar = (Var *) tle->expr;
1393                 Var                *newvar;
1394
1395                 newvar = makeVar(OUTER_VAR,
1396                                                  tle->resno,
1397                                                  exprType((Node *) oldvar),
1398                                                  exprTypmod((Node *) oldvar),
1399                                                  exprCollation((Node *) oldvar),
1400                                                  0);
1401                 if (IsA(oldvar, Var))
1402                 {
1403                         newvar->varnoold = oldvar->varno + rtoffset;
1404                         newvar->varoattno = oldvar->varattno;
1405                 }
1406                 else
1407                 {
1408                         newvar->varnoold = 0;           /* wasn't ever a plain Var */
1409                         newvar->varoattno = 0;
1410                 }
1411
1412                 tle = flatCopyTargetEntry(tle);
1413                 tle->expr = (Expr *) newvar;
1414                 output_targetlist = lappend(output_targetlist, tle);
1415         }
1416         plan->targetlist = output_targetlist;
1417
1418         /* We don't touch plan->qual here */
1419 }
1420
1421
1422 /*
1423  * build_tlist_index --- build an index data structure for a child tlist
1424  *
1425  * In most cases, subplan tlists will be "flat" tlists with only Vars,
1426  * so we try to optimize that case by extracting information about Vars
1427  * in advance.  Matching a parent tlist to a child is still an O(N^2)
1428  * operation, but at least with a much smaller constant factor than plain
1429  * tlist_member() searches.
1430  *
1431  * The result of this function is an indexed_tlist struct to pass to
1432  * search_indexed_tlist_for_var() or search_indexed_tlist_for_non_var().
1433  * When done, the indexed_tlist may be freed with a single pfree().
1434  */
1435 static indexed_tlist *
1436 build_tlist_index(List *tlist)
1437 {
1438         indexed_tlist *itlist;
1439         tlist_vinfo *vinfo;
1440         ListCell   *l;
1441
1442         /* Create data structure with enough slots for all tlist entries */
1443         itlist = (indexed_tlist *)
1444                 palloc(offsetof(indexed_tlist, vars) +
1445                            list_length(tlist) * sizeof(tlist_vinfo));
1446
1447         itlist->tlist = tlist;
1448         itlist->has_ph_vars = false;
1449         itlist->has_non_vars = false;
1450
1451         /* Find the Vars and fill in the index array */
1452         vinfo = itlist->vars;
1453         foreach(l, tlist)
1454         {
1455                 TargetEntry *tle = (TargetEntry *) lfirst(l);
1456
1457                 if (tle->expr && IsA(tle->expr, Var))
1458                 {
1459                         Var                *var = (Var *) tle->expr;
1460
1461                         vinfo->varno = var->varno;
1462                         vinfo->varattno = var->varattno;
1463                         vinfo->resno = tle->resno;
1464                         vinfo++;
1465                 }
1466                 else if (tle->expr && IsA(tle->expr, PlaceHolderVar))
1467                         itlist->has_ph_vars = true;
1468                 else
1469                         itlist->has_non_vars = true;
1470         }
1471
1472         itlist->num_vars = (vinfo - itlist->vars);
1473
1474         return itlist;
1475 }
1476
1477 /*
1478  * build_tlist_index_other_vars --- build a restricted tlist index
1479  *
1480  * This is like build_tlist_index, but we only index tlist entries that
1481  * are Vars belonging to some rel other than the one specified.  We will set
1482  * has_ph_vars (allowing PlaceHolderVars to be matched), but not has_non_vars
1483  * (so nothing other than Vars and PlaceHolderVars can be matched).
1484  */
1485 static indexed_tlist *
1486 build_tlist_index_other_vars(List *tlist, Index ignore_rel)
1487 {
1488         indexed_tlist *itlist;
1489         tlist_vinfo *vinfo;
1490         ListCell   *l;
1491
1492         /* Create data structure with enough slots for all tlist entries */
1493         itlist = (indexed_tlist *)
1494                 palloc(offsetof(indexed_tlist, vars) +
1495                            list_length(tlist) * sizeof(tlist_vinfo));
1496
1497         itlist->tlist = tlist;
1498         itlist->has_ph_vars = false;
1499         itlist->has_non_vars = false;
1500
1501         /* Find the desired Vars and fill in the index array */
1502         vinfo = itlist->vars;
1503         foreach(l, tlist)
1504         {
1505                 TargetEntry *tle = (TargetEntry *) lfirst(l);
1506
1507                 if (tle->expr && IsA(tle->expr, Var))
1508                 {
1509                         Var                *var = (Var *) tle->expr;
1510
1511                         if (var->varno != ignore_rel)
1512                         {
1513                                 vinfo->varno = var->varno;
1514                                 vinfo->varattno = var->varattno;
1515                                 vinfo->resno = tle->resno;
1516                                 vinfo++;
1517                         }
1518                 }
1519                 else if (tle->expr && IsA(tle->expr, PlaceHolderVar))
1520                         itlist->has_ph_vars = true;
1521         }
1522
1523         itlist->num_vars = (vinfo - itlist->vars);
1524
1525         return itlist;
1526 }
1527
1528 /*
1529  * search_indexed_tlist_for_var --- find a Var in an indexed tlist
1530  *
1531  * If a match is found, return a copy of the given Var with suitably
1532  * modified varno/varattno (to wit, newvarno and the resno of the TLE entry).
1533  * Also ensure that varnoold is incremented by rtoffset.
1534  * If no match, return NULL.
1535  */
1536 static Var *
1537 search_indexed_tlist_for_var(Var *var, indexed_tlist *itlist,
1538                                                          Index newvarno, int rtoffset)
1539 {
1540         Index           varno = var->varno;
1541         AttrNumber      varattno = var->varattno;
1542         tlist_vinfo *vinfo;
1543         int                     i;
1544
1545         vinfo = itlist->vars;
1546         i = itlist->num_vars;
1547         while (i-- > 0)
1548         {
1549                 if (vinfo->varno == varno && vinfo->varattno == varattno)
1550                 {
1551                         /* Found a match */
1552                         Var                *newvar = copyVar(var);
1553
1554                         newvar->varno = newvarno;
1555                         newvar->varattno = vinfo->resno;
1556                         if (newvar->varnoold > 0)
1557                                 newvar->varnoold += rtoffset;
1558                         return newvar;
1559                 }
1560                 vinfo++;
1561         }
1562         return NULL;                            /* no match */
1563 }
1564
1565 /*
1566  * search_indexed_tlist_for_non_var --- find a non-Var in an indexed tlist
1567  *
1568  * If a match is found, return a Var constructed to reference the tlist item.
1569  * If no match, return NULL.
1570  *
1571  * NOTE: it is a waste of time to call this unless itlist->has_ph_vars or
1572  * itlist->has_non_vars
1573  */
1574 static Var *
1575 search_indexed_tlist_for_non_var(Node *node,
1576                                                                  indexed_tlist *itlist, Index newvarno)
1577 {
1578         TargetEntry *tle;
1579
1580         tle = tlist_member(node, itlist->tlist);
1581         if (tle)
1582         {
1583                 /* Found a matching subplan output expression */
1584                 Var                *newvar;
1585
1586                 newvar = makeVarFromTargetEntry(newvarno, tle);
1587                 newvar->varnoold = 0;   /* wasn't ever a plain Var */
1588                 newvar->varoattno = 0;
1589                 return newvar;
1590         }
1591         return NULL;                            /* no match */
1592 }
1593
1594 /*
1595  * search_indexed_tlist_for_sortgroupref --- find a sort/group expression
1596  *              (which is assumed not to be just a Var)
1597  *
1598  * If a match is found, return a Var constructed to reference the tlist item.
1599  * If no match, return NULL.
1600  *
1601  * This is needed to ensure that we select the right subplan TLE in cases
1602  * where there are multiple textually-equal()-but-volatile sort expressions.
1603  * And it's also faster than search_indexed_tlist_for_non_var.
1604  */
1605 static Var *
1606 search_indexed_tlist_for_sortgroupref(Node *node,
1607                                                                           Index sortgroupref,
1608                                                                           indexed_tlist *itlist,
1609                                                                           Index newvarno)
1610 {
1611         ListCell   *lc;
1612
1613         foreach(lc, itlist->tlist)
1614         {
1615                 TargetEntry *tle = (TargetEntry *) lfirst(lc);
1616
1617                 /* The equal() check should be redundant, but let's be paranoid */
1618                 if (tle->ressortgroupref == sortgroupref &&
1619                         equal(node, tle->expr))
1620                 {
1621                         /* Found a matching subplan output expression */
1622                         Var                *newvar;
1623
1624                         newvar = makeVarFromTargetEntry(newvarno, tle);
1625                         newvar->varnoold = 0;           /* wasn't ever a plain Var */
1626                         newvar->varoattno = 0;
1627                         return newvar;
1628                 }
1629         }
1630         return NULL;                            /* no match */
1631 }
1632
1633 /*
1634  * fix_join_expr
1635  *         Create a new set of targetlist entries or join qual clauses by
1636  *         changing the varno/varattno values of variables in the clauses
1637  *         to reference target list values from the outer and inner join
1638  *         relation target lists.  Also perform opcode lookup and add
1639  *         regclass OIDs to root->glob->relationOids.
1640  *
1641  * This is used in two different scenarios: a normal join clause, where all
1642  * the Vars in the clause *must* be replaced by OUTER_VAR or INNER_VAR
1643  * references; and a RETURNING clause, which may contain both Vars of the
1644  * target relation and Vars of other relations.  In the latter case we want
1645  * to replace the other-relation Vars by OUTER_VAR references, while leaving
1646  * target Vars alone.
1647  *
1648  * For a normal join, acceptable_rel should be zero so that any failure to
1649  * match a Var will be reported as an error.  For the RETURNING case, pass
1650  * inner_itlist = NULL and acceptable_rel = the ID of the target relation.
1651  *
1652  * 'clauses' is the targetlist or list of join clauses
1653  * 'outer_itlist' is the indexed target list of the outer join relation
1654  * 'inner_itlist' is the indexed target list of the inner join relation,
1655  *              or NULL
1656  * 'acceptable_rel' is either zero or the rangetable index of a relation
1657  *              whose Vars may appear in the clause without provoking an error
1658  * 'rtoffset': how much to increment varnoold by
1659  *
1660  * Returns the new expression tree.  The original clause structure is
1661  * not modified.
1662  */
1663 static List *
1664 fix_join_expr(PlannerInfo *root,
1665                           List *clauses,
1666                           indexed_tlist *outer_itlist,
1667                           indexed_tlist *inner_itlist,
1668                           Index acceptable_rel,
1669                           int rtoffset)
1670 {
1671         fix_join_expr_context context;
1672
1673         context.root = root;
1674         context.outer_itlist = outer_itlist;
1675         context.inner_itlist = inner_itlist;
1676         context.acceptable_rel = acceptable_rel;
1677         context.rtoffset = rtoffset;
1678         return (List *) fix_join_expr_mutator((Node *) clauses, &context);
1679 }
1680
1681 static Node *
1682 fix_join_expr_mutator(Node *node, fix_join_expr_context *context)
1683 {
1684         Var                *newvar;
1685
1686         if (node == NULL)
1687                 return NULL;
1688         if (IsA(node, Var))
1689         {
1690                 Var                *var = (Var *) node;
1691
1692                 /* First look for the var in the input tlists */
1693                 newvar = search_indexed_tlist_for_var(var,
1694                                                                                           context->outer_itlist,
1695                                                                                           OUTER_VAR,
1696                                                                                           context->rtoffset);
1697                 if (newvar)
1698                         return (Node *) newvar;
1699                 if (context->inner_itlist)
1700                 {
1701                         newvar = search_indexed_tlist_for_var(var,
1702                                                                                                   context->inner_itlist,
1703                                                                                                   INNER_VAR,
1704                                                                                                   context->rtoffset);
1705                         if (newvar)
1706                                 return (Node *) newvar;
1707                 }
1708
1709                 /* If it's for acceptable_rel, adjust and return it */
1710                 if (var->varno == context->acceptable_rel)
1711                 {
1712                         var = copyVar(var);
1713                         var->varno += context->rtoffset;
1714                         if (var->varnoold > 0)
1715                                 var->varnoold += context->rtoffset;
1716                         return (Node *) var;
1717                 }
1718
1719                 /* No referent found for Var */
1720                 elog(ERROR, "variable not found in subplan target lists");
1721         }
1722         if (IsA(node, PlaceHolderVar))
1723         {
1724                 PlaceHolderVar *phv = (PlaceHolderVar *) node;
1725
1726                 /* See if the PlaceHolderVar has bubbled up from a lower plan node */
1727                 if (context->outer_itlist->has_ph_vars)
1728                 {
1729                         newvar = search_indexed_tlist_for_non_var((Node *) phv,
1730                                                                                                           context->outer_itlist,
1731                                                                                                           OUTER_VAR);
1732                         if (newvar)
1733                                 return (Node *) newvar;
1734                 }
1735                 if (context->inner_itlist && context->inner_itlist->has_ph_vars)
1736                 {
1737                         newvar = search_indexed_tlist_for_non_var((Node *) phv,
1738                                                                                                           context->inner_itlist,
1739                                                                                                           INNER_VAR);
1740                         if (newvar)
1741                                 return (Node *) newvar;
1742                 }
1743
1744                 /* If not supplied by input plans, evaluate the contained expr */
1745                 return fix_join_expr_mutator((Node *) phv->phexpr, context);
1746         }
1747         /* Try matching more complex expressions too, if tlists have any */
1748         if (context->outer_itlist->has_non_vars)
1749         {
1750                 newvar = search_indexed_tlist_for_non_var(node,
1751                                                                                                   context->outer_itlist,
1752                                                                                                   OUTER_VAR);
1753                 if (newvar)
1754                         return (Node *) newvar;
1755         }
1756         if (context->inner_itlist && context->inner_itlist->has_non_vars)
1757         {
1758                 newvar = search_indexed_tlist_for_non_var(node,
1759                                                                                                   context->inner_itlist,
1760                                                                                                   INNER_VAR);
1761                 if (newvar)
1762                         return (Node *) newvar;
1763         }
1764         fix_expr_common(context->root, node);
1765         return expression_tree_mutator(node,
1766                                                                    fix_join_expr_mutator,
1767                                                                    (void *) context);
1768 }
1769
1770 /*
1771  * fix_upper_expr
1772  *              Modifies an expression tree so that all Var nodes reference outputs
1773  *              of a subplan.  Also performs opcode lookup, and adds regclass OIDs to
1774  *              root->glob->relationOids.
1775  *
1776  * This is used to fix up target and qual expressions of non-join upper-level
1777  * plan nodes, as well as index-only scan nodes.
1778  *
1779  * An error is raised if no matching var can be found in the subplan tlist
1780  * --- so this routine should only be applied to nodes whose subplans'
1781  * targetlists were generated via flatten_tlist() or some such method.
1782  *
1783  * If itlist->has_non_vars is true, then we try to match whole subexpressions
1784  * against elements of the subplan tlist, so that we can avoid recomputing
1785  * expressions that were already computed by the subplan.  (This is relatively
1786  * expensive, so we don't want to try it in the common case where the
1787  * subplan tlist is just a flattened list of Vars.)
1788  *
1789  * 'node': the tree to be fixed (a target item or qual)
1790  * 'subplan_itlist': indexed target list for subplan (or index)
1791  * 'newvarno': varno to use for Vars referencing tlist elements
1792  * 'rtoffset': how much to increment varnoold by
1793  *
1794  * The resulting tree is a copy of the original in which all Var nodes have
1795  * varno = newvarno, varattno = resno of corresponding targetlist element.
1796  * The original tree is not modified.
1797  */
1798 static Node *
1799 fix_upper_expr(PlannerInfo *root,
1800                            Node *node,
1801                            indexed_tlist *subplan_itlist,
1802                            Index newvarno,
1803                            int rtoffset)
1804 {
1805         fix_upper_expr_context context;
1806
1807         context.root = root;
1808         context.subplan_itlist = subplan_itlist;
1809         context.newvarno = newvarno;
1810         context.rtoffset = rtoffset;
1811         return fix_upper_expr_mutator(node, &context);
1812 }
1813
1814 static Node *
1815 fix_upper_expr_mutator(Node *node, fix_upper_expr_context *context)
1816 {
1817         Var                *newvar;
1818
1819         if (node == NULL)
1820                 return NULL;
1821         if (IsA(node, Var))
1822         {
1823                 Var                *var = (Var *) node;
1824
1825                 newvar = search_indexed_tlist_for_var(var,
1826                                                                                           context->subplan_itlist,
1827                                                                                           context->newvarno,
1828                                                                                           context->rtoffset);
1829                 if (!newvar)
1830                         elog(ERROR, "variable not found in subplan target list");
1831                 return (Node *) newvar;
1832         }
1833         if (IsA(node, PlaceHolderVar))
1834         {
1835                 PlaceHolderVar *phv = (PlaceHolderVar *) node;
1836
1837                 /* See if the PlaceHolderVar has bubbled up from a lower plan node */
1838                 if (context->subplan_itlist->has_ph_vars)
1839                 {
1840                         newvar = search_indexed_tlist_for_non_var((Node *) phv,
1841                                                                                                           context->subplan_itlist,
1842                                                                                                           context->newvarno);
1843                         if (newvar)
1844                                 return (Node *) newvar;
1845                 }
1846                 /* If not supplied by input plan, evaluate the contained expr */
1847                 return fix_upper_expr_mutator((Node *) phv->phexpr, context);
1848         }
1849         /* Try matching more complex expressions too, if tlist has any */
1850         if (context->subplan_itlist->has_non_vars)
1851         {
1852                 newvar = search_indexed_tlist_for_non_var(node,
1853                                                                                                   context->subplan_itlist,
1854                                                                                                   context->newvarno);
1855                 if (newvar)
1856                         return (Node *) newvar;
1857         }
1858         fix_expr_common(context->root, node);
1859         return expression_tree_mutator(node,
1860                                                                    fix_upper_expr_mutator,
1861                                                                    (void *) context);
1862 }
1863
1864 /*
1865  * set_returning_clause_references
1866  *              Perform setrefs.c's work on a RETURNING targetlist
1867  *
1868  * If the query involves more than just the result table, we have to
1869  * adjust any Vars that refer to other tables to reference junk tlist
1870  * entries in the top subplan's targetlist.  Vars referencing the result
1871  * table should be left alone, however (the executor will evaluate them
1872  * using the actual heap tuple, after firing triggers if any).  In the
1873  * adjusted RETURNING list, result-table Vars will have their original
1874  * varno (plus rtoffset), but Vars for other rels will have varno OUTER_VAR.
1875  *
1876  * We also must perform opcode lookup and add regclass OIDs to
1877  * root->glob->relationOids.
1878  *
1879  * 'rlist': the RETURNING targetlist to be fixed
1880  * 'topplan': the top subplan node that will be just below the ModifyTable
1881  *              node (note it's not yet passed through set_plan_refs)
1882  * 'resultRelation': RT index of the associated result relation
1883  * 'rtoffset': how much to increment varnos by
1884  *
1885  * Note: the given 'root' is for the parent query level, not the 'topplan'.
1886  * This does not matter currently since we only access the dependency-item
1887  * lists in root->glob, but it would need some hacking if we wanted a root
1888  * that actually matches the subplan.
1889  *
1890  * Note: resultRelation is not yet adjusted by rtoffset.
1891  */
1892 static List *
1893 set_returning_clause_references(PlannerInfo *root,
1894                                                                 List *rlist,
1895                                                                 Plan *topplan,
1896                                                                 Index resultRelation,
1897                                                                 int rtoffset)
1898 {
1899         indexed_tlist *itlist;
1900
1901         /*
1902          * We can perform the desired Var fixup by abusing the fix_join_expr
1903          * machinery that formerly handled inner indexscan fixup.  We search the
1904          * top plan's targetlist for Vars of non-result relations, and use
1905          * fix_join_expr to convert RETURNING Vars into references to those tlist
1906          * entries, while leaving result-rel Vars as-is.
1907          *
1908          * PlaceHolderVars will also be sought in the targetlist, but no
1909          * more-complex expressions will be.  Note that it is not possible for a
1910          * PlaceHolderVar to refer to the result relation, since the result is
1911          * never below an outer join.  If that case could happen, we'd have to be
1912          * prepared to pick apart the PlaceHolderVar and evaluate its contained
1913          * expression instead.
1914          */
1915         itlist = build_tlist_index_other_vars(topplan->targetlist, resultRelation);
1916
1917         rlist = fix_join_expr(root,
1918                                                   rlist,
1919                                                   itlist,
1920                                                   NULL,
1921                                                   resultRelation,
1922                                                   rtoffset);
1923
1924         pfree(itlist);
1925
1926         return rlist;
1927 }
1928
1929 /*****************************************************************************
1930  *                                      OPERATOR REGPROC LOOKUP
1931  *****************************************************************************/
1932
1933 /*
1934  * fix_opfuncids
1935  *        Calculate opfuncid field from opno for each OpExpr node in given tree.
1936  *        The given tree can be anything expression_tree_walker handles.
1937  *
1938  * The argument is modified in-place.  (This is OK since we'd want the
1939  * same change for any node, even if it gets visited more than once due to
1940  * shared structure.)
1941  */
1942 void
1943 fix_opfuncids(Node *node)
1944 {
1945         /* This tree walk requires no special setup, so away we go... */
1946         fix_opfuncids_walker(node, NULL);
1947 }
1948
1949 static bool
1950 fix_opfuncids_walker(Node *node, void *context)
1951 {
1952         if (node == NULL)
1953                 return false;
1954         if (IsA(node, OpExpr))
1955                 set_opfuncid((OpExpr *) node);
1956         else if (IsA(node, DistinctExpr))
1957                 set_opfuncid((OpExpr *) node);  /* rely on struct equivalence */
1958         else if (IsA(node, NullIfExpr))
1959                 set_opfuncid((OpExpr *) node);  /* rely on struct equivalence */
1960         else if (IsA(node, ScalarArrayOpExpr))
1961                 set_sa_opfuncid((ScalarArrayOpExpr *) node);
1962         return expression_tree_walker(node, fix_opfuncids_walker, context);
1963 }
1964
1965 /*
1966  * set_opfuncid
1967  *              Set the opfuncid (procedure OID) in an OpExpr node,
1968  *              if it hasn't been set already.
1969  *
1970  * Because of struct equivalence, this can also be used for
1971  * DistinctExpr and NullIfExpr nodes.
1972  */
1973 void
1974 set_opfuncid(OpExpr *opexpr)
1975 {
1976         if (opexpr->opfuncid == InvalidOid)
1977                 opexpr->opfuncid = get_opcode(opexpr->opno);
1978 }
1979
1980 /*
1981  * set_sa_opfuncid
1982  *              As above, for ScalarArrayOpExpr nodes.
1983  */
1984 void
1985 set_sa_opfuncid(ScalarArrayOpExpr *opexpr)
1986 {
1987         if (opexpr->opfuncid == InvalidOid)
1988                 opexpr->opfuncid = get_opcode(opexpr->opno);
1989 }
1990
1991 /*****************************************************************************
1992  *                                      QUERY DEPENDENCY MANAGEMENT
1993  *****************************************************************************/
1994
1995 /*
1996  * record_plan_function_dependency
1997  *              Mark the current plan as depending on a particular function.
1998  *
1999  * This is exported so that the function-inlining code can record a
2000  * dependency on a function that it's removed from the plan tree.
2001  */
2002 void
2003 record_plan_function_dependency(PlannerInfo *root, Oid funcid)
2004 {
2005         /*
2006          * For performance reasons, we don't bother to track built-in functions;
2007          * we just assume they'll never change (or at least not in ways that'd
2008          * invalidate plans using them).  For this purpose we can consider a
2009          * built-in function to be one with OID less than FirstBootstrapObjectId.
2010          * Note that the OID generator guarantees never to generate such an OID
2011          * after startup, even at OID wraparound.
2012          */
2013         if (funcid >= (Oid) FirstBootstrapObjectId)
2014         {
2015                 PlanInvalItem *inval_item = makeNode(PlanInvalItem);
2016
2017                 /*
2018                  * It would work to use any syscache on pg_proc, but the easiest is
2019                  * PROCOID since we already have the function's OID at hand.  Note
2020                  * that plancache.c knows we use PROCOID.
2021                  */
2022                 inval_item->cacheId = PROCOID;
2023                 inval_item->hashValue = GetSysCacheHashValue1(PROCOID,
2024                                                                                                    ObjectIdGetDatum(funcid));
2025
2026                 root->glob->invalItems = lappend(root->glob->invalItems, inval_item);
2027         }
2028 }
2029
2030 /*
2031  * extract_query_dependencies
2032  *              Given a not-yet-planned query or queries (i.e. a Query node or list
2033  *              of Query nodes), extract dependencies just as set_plan_references
2034  *              would do.
2035  *
2036  * This is needed by plancache.c to handle invalidation of cached unplanned
2037  * queries.
2038  */
2039 void
2040 extract_query_dependencies(Node *query,
2041                                                    List **relationOids,
2042                                                    List **invalItems)
2043 {
2044         PlannerGlobal glob;
2045         PlannerInfo root;
2046
2047         /* Make up dummy planner state so we can use this module's machinery */
2048         MemSet(&glob, 0, sizeof(glob));
2049         glob.type = T_PlannerGlobal;
2050         glob.relationOids = NIL;
2051         glob.invalItems = NIL;
2052
2053         MemSet(&root, 0, sizeof(root));
2054         root.type = T_PlannerInfo;
2055         root.glob = &glob;
2056
2057         (void) extract_query_dependencies_walker(query, &root);
2058
2059         *relationOids = glob.relationOids;
2060         *invalItems = glob.invalItems;
2061 }
2062
2063 static bool
2064 extract_query_dependencies_walker(Node *node, PlannerInfo *context)
2065 {
2066         if (node == NULL)
2067                 return false;
2068         Assert(!IsA(node, PlaceHolderVar));
2069         /* Extract function dependencies and check for regclass Consts */
2070         fix_expr_common(context, node);
2071         if (IsA(node, Query))
2072         {
2073                 Query      *query = (Query *) node;
2074                 ListCell   *lc;
2075
2076                 if (query->commandType == CMD_UTILITY)
2077                 {
2078                         /*
2079                          * Ignore utility statements, except those (such as EXPLAIN) that
2080                          * contain a parsed-but-not-planned query.
2081                          */
2082                         query = UtilityContainsQuery(query->utilityStmt);
2083                         if (query == NULL)
2084                                 return false;
2085                 }
2086
2087                 /* Collect relation OIDs in this Query's rtable */
2088                 foreach(lc, query->rtable)
2089                 {
2090                         RangeTblEntry *rte = (RangeTblEntry *) lfirst(lc);
2091
2092                         if (rte->rtekind == RTE_RELATION)
2093                                 context->glob->relationOids =
2094                                         lappend_oid(context->glob->relationOids, rte->relid);
2095                 }
2096
2097                 /* And recurse into the query's subexpressions */
2098                 return query_tree_walker(query, extract_query_dependencies_walker,
2099                                                                  (void *) context, 0);
2100         }
2101         return expression_tree_walker(node, extract_query_dependencies_walker,
2102                                                                   (void *) context);
2103 }