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