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