]> granicus.if.org Git - postgresql/blob - src/backend/optimizer/plan/setrefs.c
Restructure parsetree representation of DECLARE CURSOR: now it's a
[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, and compute regproc values for operators
6  *
7  * Portions Copyright (c) 1996-2002, PostgreSQL Global Development Group
8  * Portions Copyright (c) 1994, Regents of the University of California
9  *
10  *
11  * IDENTIFICATION
12  *        $Header: /cvsroot/pgsql/src/backend/optimizer/plan/setrefs.c,v 1.92 2003/02/16 02:30:38 tgl Exp $
13  *
14  *-------------------------------------------------------------------------
15  */
16 #include "postgres.h"
17
18
19 #include "nodes/makefuncs.h"
20 #include "nodes/nodeFuncs.h"
21 #include "optimizer/clauses.h"
22 #include "optimizer/planmain.h"
23 #include "optimizer/tlist.h"
24 #include "optimizer/var.h"
25 #include "parser/parsetree.h"
26
27
28 typedef struct
29 {
30         List       *rtable;
31         List       *outer_tlist;
32         List       *inner_tlist;
33         Index           acceptable_rel;
34         bool            tlists_have_non_vars;
35 } join_references_context;
36
37 typedef struct
38 {
39         Index           subvarno;
40         List       *subplan_targetlist;
41         bool            tlist_has_non_vars;
42 } replace_vars_with_subplan_refs_context;
43
44 static void fix_expr_references(Plan *plan, Node *node);
45 static bool fix_expr_references_walker(Node *node, void *context);
46 static void set_join_references(Join *join, List *rtable);
47 static void set_uppernode_references(Plan *plan, Index subvarno);
48 static bool targetlist_has_non_vars(List *tlist);
49 static List *join_references(List *clauses,
50                                                          List *rtable,
51                                                          List *outer_tlist,
52                                                          List *inner_tlist,
53                                                          Index acceptable_rel,
54                                                          bool tlists_have_non_vars);
55 static Node *join_references_mutator(Node *node,
56                                                 join_references_context *context);
57 static Node *replace_vars_with_subplan_refs(Node *node,
58                                                            Index subvarno,
59                                                            List *subplan_targetlist,
60                                                            bool tlist_has_non_vars);
61 static Node *replace_vars_with_subplan_refs_mutator(Node *node,
62                                                 replace_vars_with_subplan_refs_context *context);
63 static bool fix_opfuncids_walker(Node *node, void *context);
64
65 /*****************************************************************************
66  *
67  *              SUBPLAN REFERENCES
68  *
69  *****************************************************************************/
70
71 /*
72  * set_plan_references
73  *        This is the final processing pass of the planner/optimizer.  The plan
74  *        tree is complete; we just have to adjust some representational details
75  *        for the convenience of the executor.  We update Vars in upper plan nodes
76  *        to refer to the outputs of their subplans, and we compute regproc OIDs
77  *        for operators (ie, we look up the function that implements each op).
78  *
79  *        set_plan_references recursively traverses the whole plan tree.
80  *
81  * Returns nothing of interest, but modifies internal fields of nodes.
82  */
83 void
84 set_plan_references(Plan *plan, List *rtable)
85 {
86         List       *pl;
87
88         if (plan == NULL)
89                 return;
90
91         /*
92          * Plan-type-specific fixes
93          */
94         switch (nodeTag(plan))
95         {
96                 case T_SeqScan:
97                         fix_expr_references(plan, (Node *) plan->targetlist);
98                         fix_expr_references(plan, (Node *) plan->qual);
99                         break;
100                 case T_IndexScan:
101                         fix_expr_references(plan, (Node *) plan->targetlist);
102                         fix_expr_references(plan, (Node *) plan->qual);
103                         fix_expr_references(plan,
104                                                                 (Node *) ((IndexScan *) plan)->indxqual);
105                         fix_expr_references(plan,
106                                                         (Node *) ((IndexScan *) plan)->indxqualorig);
107                         break;
108                 case T_TidScan:
109                         fix_expr_references(plan, (Node *) plan->targetlist);
110                         fix_expr_references(plan, (Node *) plan->qual);
111                         fix_expr_references(plan,
112                                                                 (Node *) ((TidScan *) plan)->tideval);
113                         break;
114                 case T_SubqueryScan:
115                         {
116                                 RangeTblEntry *rte;
117
118                                 /*
119                                  * We do not do set_uppernode_references() here, because a
120                                  * SubqueryScan will always have been created with correct
121                                  * references to its subplan's outputs to begin with.
122                                  */
123                                 fix_expr_references(plan, (Node *) plan->targetlist);
124                                 fix_expr_references(plan, (Node *) plan->qual);
125
126                                 /* Recurse into subplan too */
127                                 rte = rt_fetch(((SubqueryScan *) plan)->scan.scanrelid,
128                                                            rtable);
129                                 Assert(rte->rtekind == RTE_SUBQUERY);
130                                 set_plan_references(((SubqueryScan *) plan)->subplan,
131                                                                         rte->subquery->rtable);
132                         }
133                         break;
134                 case T_FunctionScan:
135                         {
136                                 RangeTblEntry *rte;
137
138                                 fix_expr_references(plan, (Node *) plan->targetlist);
139                                 fix_expr_references(plan, (Node *) plan->qual);
140                                 rte = rt_fetch(((FunctionScan *) plan)->scan.scanrelid,
141                                                            rtable);
142                                 Assert(rte->rtekind == RTE_FUNCTION);
143                                 fix_expr_references(plan, rte->funcexpr);
144                         }
145                         break;
146                 case T_NestLoop:
147                         set_join_references((Join *) plan, rtable);
148                         fix_expr_references(plan, (Node *) plan->targetlist);
149                         fix_expr_references(plan, (Node *) plan->qual);
150                         fix_expr_references(plan, (Node *) ((Join *) plan)->joinqual);
151                         break;
152                 case T_MergeJoin:
153                         set_join_references((Join *) plan, rtable);
154                         fix_expr_references(plan, (Node *) plan->targetlist);
155                         fix_expr_references(plan, (Node *) plan->qual);
156                         fix_expr_references(plan, (Node *) ((Join *) plan)->joinqual);
157                         fix_expr_references(plan,
158                                                         (Node *) ((MergeJoin *) plan)->mergeclauses);
159                         break;
160                 case T_HashJoin:
161                         set_join_references((Join *) plan, rtable);
162                         fix_expr_references(plan, (Node *) plan->targetlist);
163                         fix_expr_references(plan, (Node *) plan->qual);
164                         fix_expr_references(plan, (Node *) ((Join *) plan)->joinqual);
165                         fix_expr_references(plan,
166                                                           (Node *) ((HashJoin *) plan)->hashclauses);
167                         break;
168                 case T_Hash:
169                         /*
170                          * Hash does not evaluate its targetlist or quals, so don't
171                          * touch those (see comments below).  But we do need to fix its
172                          * hashkeys.  The hashkeys are a little bizarre because they
173                          * need to match the hashclauses of the parent HashJoin node,
174                          * so we use join_references to fix them.
175                          */
176                         ((Hash *) plan)->hashkeys =
177                                 join_references(((Hash *) plan)->hashkeys,
178                                                                 rtable,
179                                                                 NIL,
180                                                                 plan->lefttree->targetlist,
181                                                                 (Index) 0,
182                                                                 targetlist_has_non_vars(plan->lefttree->targetlist));
183                         fix_expr_references(plan,
184                                                                 (Node *) ((Hash *) plan)->hashkeys);
185                         break;
186                 case T_Material:
187                 case T_Sort:
188                 case T_Unique:
189                 case T_SetOp:
190                 case T_Limit:
191
192                         /*
193                          * These plan types don't actually bother to evaluate their
194                          * targetlists or quals (because they just return their
195                          * unmodified input tuples).  The optimizer is lazy about
196                          * creating really valid targetlists for them.  Best to just
197                          * leave the targetlist alone.  In particular, we do not want
198                          * to process subplans for them, since we will likely end
199                          * up reprocessing subplans that also appear in lower levels
200                          * of the plan tree!
201                          */
202                         break;
203                 case T_Agg:
204                 case T_Group:
205                         set_uppernode_references(plan, (Index) 0);
206                         fix_expr_references(plan, (Node *) plan->targetlist);
207                         fix_expr_references(plan, (Node *) plan->qual);
208                         break;
209                 case T_Result:
210
211                         /*
212                          * Result may or may not have a subplan; no need to fix up
213                          * subplan references if it hasn't got one...
214                          *
215                          * XXX why does Result use a different subvarno from Agg/Group?
216                          */
217                         if (plan->lefttree != NULL)
218                                 set_uppernode_references(plan, (Index) OUTER);
219                         fix_expr_references(plan, (Node *) plan->targetlist);
220                         fix_expr_references(plan, (Node *) plan->qual);
221                         fix_expr_references(plan, ((Result *) plan)->resconstantqual);
222                         break;
223                 case T_Append:
224
225                         /*
226                          * Append, like Sort et al, doesn't actually evaluate its
227                          * targetlist or quals, and we haven't bothered to give it its
228                          * own tlist copy.      So, don't fix targetlist/qual. But do
229                          * recurse into child plans.
230                          */
231                         foreach(pl, ((Append *) plan)->appendplans)
232                                 set_plan_references((Plan *) lfirst(pl), rtable);
233                         break;
234                 default:
235                         elog(ERROR, "set_plan_references: unknown plan type %d",
236                                  nodeTag(plan));
237                         break;
238         }
239
240         /*
241          * Now recurse into child plans and initplans, if any
242          *
243          * NOTE: it is essential that we recurse into child plans AFTER we set
244          * subplan references in this plan's tlist and quals.  If we did the
245          * reference-adjustments bottom-up, then we would fail to match this
246          * plan's var nodes against the already-modified nodes of the
247          * children.  Fortunately, that consideration doesn't apply to SubPlan
248          * nodes; else we'd need two passes over the expression trees.
249          */
250         set_plan_references(plan->lefttree, rtable);
251         set_plan_references(plan->righttree, rtable);
252
253         foreach(pl, plan->initPlan)
254         {
255                 SubPlan *sp = (SubPlan *) lfirst(pl);
256
257                 Assert(IsA(sp, SubPlan));
258                 set_plan_references(sp->plan, sp->rtable);
259         }
260 }
261
262 /*
263  * fix_expr_references
264  *        Do final cleanup on expressions (targetlists or quals).
265  *
266  * This consists of looking up operator opcode info for OpExpr nodes
267  * and recursively performing set_plan_references on subplans.
268  *
269  * The Plan argument is currently unused, but might be needed again someday.
270  */
271 static void
272 fix_expr_references(Plan *plan, Node *node)
273 {
274         /* This tree walk requires no special setup, so away we go... */
275         fix_expr_references_walker(node, NULL);
276 }
277
278 static bool
279 fix_expr_references_walker(Node *node, void *context)
280 {
281         if (node == NULL)
282                 return false;
283         if (IsA(node, OpExpr))
284                 set_opfuncid((OpExpr *) node);
285         else if (IsA(node, DistinctExpr))
286                 set_opfuncid((OpExpr *) node); /* rely on struct equivalence */
287         else if (IsA(node, NullIfExpr))
288                 set_opfuncid((OpExpr *) node); /* rely on struct equivalence */
289         else if (IsA(node, SubPlan))
290         {
291                 SubPlan *sp = (SubPlan *) node;
292
293                 set_plan_references(sp->plan, sp->rtable);
294         }
295         return expression_tree_walker(node, fix_expr_references_walker, context);
296 }
297
298 /*
299  * set_join_references
300  *        Modifies the target list and quals of a join node to reference its
301  *        subplans, by setting the varnos to OUTER or INNER and setting attno
302  *        values to the result domain number of either the corresponding outer
303  *        or inner join tuple item.
304  *
305  * In the case of a nestloop with inner indexscan, we will also need to
306  * apply the same transformation to any outer vars appearing in the
307  * quals of the child indexscan.
308  *
309  *      'join' is a join plan node
310  *      'rtable' is the associated range table
311  */
312 static void
313 set_join_references(Join *join, List *rtable)
314 {
315         Plan       *outer_plan = join->plan.lefttree;
316         Plan       *inner_plan = join->plan.righttree;
317         List       *outer_tlist = outer_plan->targetlist;
318         List       *inner_tlist = inner_plan->targetlist;
319         bool            tlists_have_non_vars;
320
321         tlists_have_non_vars = targetlist_has_non_vars(outer_tlist) ||
322                 targetlist_has_non_vars(inner_tlist);
323
324         /* All join plans have tlist, qual, and joinqual */
325         join->plan.targetlist = join_references(join->plan.targetlist,
326                                                                                         rtable,
327                                                                                         outer_tlist,
328                                                                                         inner_tlist,
329                                                                                         (Index) 0,
330                                                                                         tlists_have_non_vars);
331         join->plan.qual = join_references(join->plan.qual,
332                                                                           rtable,
333                                                                           outer_tlist,
334                                                                           inner_tlist,
335                                                                           (Index) 0,
336                                                                           tlists_have_non_vars);
337         join->joinqual = join_references(join->joinqual,
338                                                                          rtable,
339                                                                          outer_tlist,
340                                                                          inner_tlist,
341                                                                          (Index) 0,
342                                                                          tlists_have_non_vars);
343
344         /* Now do join-type-specific stuff */
345         if (IsA(join, NestLoop))
346         {
347                 if (IsA(inner_plan, IndexScan))
348                 {
349                         /*
350                          * An index is being used to reduce the number of tuples scanned
351                          * in the inner relation.  If there are join clauses being used
352                          * with the index, we must update their outer-rel var nodes to
353                          * refer to the outer side of the join.
354                          */
355                         IndexScan  *innerscan = (IndexScan *) inner_plan;
356                         List       *indxqualorig = innerscan->indxqualorig;
357
358                         /* No work needed if indxqual refers only to its own rel... */
359                         if (NumRelids((Node *) indxqualorig) > 1)
360                         {
361                                 Index           innerrel = innerscan->scan.scanrelid;
362
363                                 /* only refs to outer vars get changed in the inner qual */
364                                 innerscan->indxqualorig = join_references(indxqualorig,
365                                                                                                                   rtable,
366                                                                                                                   outer_tlist,
367                                                                                                                   NIL,
368                                                                                                                   innerrel,
369                                                                                                                   tlists_have_non_vars);
370                                 innerscan->indxqual = join_references(innerscan->indxqual,
371                                                                                                           rtable,
372                                                                                                           outer_tlist,
373                                                                                                           NIL,
374                                                                                                           innerrel,
375                                                                                                           tlists_have_non_vars);
376                                 /*
377                                  * We must fix the inner qpqual too, if it has join clauses
378                                  * (this could happen if the index is lossy: some indxquals
379                                  * may get rechecked as qpquals).
380                                  */
381                                 if (NumRelids((Node *) inner_plan->qual) > 1)
382                                         inner_plan->qual = join_references(inner_plan->qual,
383                                                                                                            rtable,
384                                                                                                            outer_tlist,
385                                                                                                            NIL,
386                                                                                                            innerrel,
387                                                                                                            tlists_have_non_vars);
388                         }
389                 }
390                 else if (IsA(inner_plan, TidScan))
391                 {
392                         TidScan    *innerscan = (TidScan *) inner_plan;
393                         Index           innerrel = innerscan->scan.scanrelid;
394
395                         innerscan->tideval = join_references(innerscan->tideval,
396                                                                                                  rtable,
397                                                                                                  outer_tlist,
398                                                                                                  NIL,
399                                                                                                  innerrel,
400                                                                                                  tlists_have_non_vars);
401                 }
402         }
403         else if (IsA(join, MergeJoin))
404         {
405                 MergeJoin  *mj = (MergeJoin *) join;
406
407                 mj->mergeclauses = join_references(mj->mergeclauses,
408                                                                                    rtable,
409                                                                                    outer_tlist,
410                                                                                    inner_tlist,
411                                                                                    (Index) 0,
412                                                                                    tlists_have_non_vars);
413         }
414         else if (IsA(join, HashJoin))
415         {
416                 HashJoin   *hj = (HashJoin *) join;
417
418                 hj->hashclauses = join_references(hj->hashclauses,
419                                                                                   rtable,
420                                                                                   outer_tlist,
421                                                                                   inner_tlist,
422                                                                                   (Index) 0,
423                                                                                   tlists_have_non_vars);
424         }
425 }
426
427 /*
428  * set_uppernode_references
429  *        Update the targetlist and quals of an upper-level plan node
430  *        to refer to the tuples returned by its lefttree subplan.
431  *
432  * This is used for single-input plan types like Agg, Group, Result.
433  *
434  * In most cases, we have to match up individual Vars in the tlist and
435  * qual expressions with elements of the subplan's tlist (which was
436  * generated by flatten_tlist() from these selfsame expressions, so it
437  * should have all the required variables).  There is an important exception,
438  * however: GROUP BY and ORDER BY expressions will have been pushed into the
439  * subplan tlist unflattened.  If these values are also needed in the output
440  * then we want to reference the subplan tlist element rather than recomputing
441  * the expression.
442  */
443 static void
444 set_uppernode_references(Plan *plan, Index subvarno)
445 {
446         Plan       *subplan = plan->lefttree;
447         List       *subplan_targetlist,
448                            *output_targetlist,
449                            *l;
450         bool            tlist_has_non_vars;
451
452         if (subplan != NULL)
453                 subplan_targetlist = subplan->targetlist;
454         else
455                 subplan_targetlist = NIL;
456
457         tlist_has_non_vars = targetlist_has_non_vars(subplan_targetlist);
458
459         output_targetlist = NIL;
460         foreach(l, plan->targetlist)
461         {
462                 TargetEntry *tle = (TargetEntry *) lfirst(l);
463                 Node       *newexpr;
464
465                 newexpr = replace_vars_with_subplan_refs((Node *) tle->expr,
466                                                                                                  subvarno,
467                                                                                                  subplan_targetlist,
468                                                                                                  tlist_has_non_vars);
469                 output_targetlist = lappend(output_targetlist,
470                                                                   makeTargetEntry(tle->resdom,
471                                                                                                   (Expr *) newexpr));
472         }
473         plan->targetlist = output_targetlist;
474
475         plan->qual = (List *)
476                 replace_vars_with_subplan_refs((Node *) plan->qual,
477                                                                            subvarno,
478                                                                            subplan_targetlist,
479                                                                            tlist_has_non_vars);
480 }
481
482 /*
483  * targetlist_has_non_vars --- are there any non-Var entries in tlist?
484  *
485  * In most cases, subplan tlists will be "flat" tlists with only Vars.
486  * Checking for this allows us to save comparisons in common cases.
487  */
488 static bool
489 targetlist_has_non_vars(List *tlist)
490 {
491         List   *l;
492
493         foreach(l, tlist)
494         {
495                 TargetEntry *tle = (TargetEntry *) lfirst(l);
496
497                 if (tle->expr && !IsA(tle->expr, Var))
498                         return true;
499         }
500         return false;
501 }
502
503 /*
504  * join_references
505  *         Creates a new set of targetlist entries or join qual clauses by
506  *         changing the varno/varattno values of variables in the clauses
507  *         to reference target list values from the outer and inner join
508  *         relation target lists.
509  *
510  * This is used in two different scenarios: a normal join clause, where
511  * all the Vars in the clause *must* be replaced by OUTER or INNER references;
512  * and an indexscan being used on the inner side of a nestloop join.
513  * In the latter case we want to replace the outer-relation Vars by OUTER
514  * references, but not touch the Vars of the inner relation.
515  *
516  * For a normal join, acceptable_rel should be zero so that any failure to
517  * match a Var will be reported as an error.  For the indexscan case,
518  * pass inner_tlist = NIL and acceptable_rel = the ID of the inner relation.
519  *
520  * 'clauses' is the targetlist or list of join clauses
521  * 'rtable' is the current range table
522  * 'outer_tlist' is the target list of the outer join relation
523  * 'inner_tlist' is the target list of the inner join relation, or NIL
524  * 'acceptable_rel' is either zero or the rangetable index of a relation
525  *              whose Vars may appear in the clause without provoking an error.
526  *
527  * Returns the new expression tree.  The original clause structure is
528  * not modified.
529  */
530 static List *
531 join_references(List *clauses,
532                                 List *rtable,
533                                 List *outer_tlist,
534                                 List *inner_tlist,
535                                 Index acceptable_rel,
536                                 bool tlists_have_non_vars)
537 {
538         join_references_context context;
539
540         context.rtable = rtable;
541         context.outer_tlist = outer_tlist;
542         context.inner_tlist = inner_tlist;
543         context.acceptable_rel = acceptable_rel;
544         context.tlists_have_non_vars = tlists_have_non_vars;
545         return (List *) join_references_mutator((Node *) clauses, &context);
546 }
547
548 static Node *
549 join_references_mutator(Node *node,
550                                                 join_references_context *context)
551 {
552         if (node == NULL)
553                 return NULL;
554         if (IsA(node, Var))
555         {
556                 Var                *var = (Var *) node;
557                 Resdom     *resdom;
558
559                 /* First look for the var in the input tlists */
560                 resdom = tlist_member((Node *) var, context->outer_tlist);
561                 if (resdom)
562                 {
563                         Var                *newvar = (Var *) copyObject(var);
564
565                         newvar->varno = OUTER;
566                         newvar->varattno = resdom->resno;
567                         return (Node *) newvar;
568                 }
569                 resdom = tlist_member((Node *) var, context->inner_tlist);
570                 if (resdom)
571                 {
572                         Var                *newvar = (Var *) copyObject(var);
573
574                         newvar->varno = INNER;
575                         newvar->varattno = resdom->resno;
576                         return (Node *) newvar;
577                 }
578
579                 /* Return the Var unmodified, if it's for acceptable_rel */
580                 if (var->varno == context->acceptable_rel)
581                         return (Node *) copyObject(var);
582
583                 /* No referent found for Var */
584                 elog(ERROR, "join_references: variable not in subplan target lists");
585         }
586         /* Try matching more complex expressions too, if tlists have any */
587         if (context->tlists_have_non_vars)
588         {
589                 Resdom     *resdom;
590
591                 resdom = tlist_member(node, context->outer_tlist);
592                 if (resdom)
593                 {
594                         /* Found a matching subplan output expression */
595                         Var                *newvar;
596
597                         newvar = makeVar(OUTER,
598                                                          resdom->resno,
599                                                          resdom->restype,
600                                                          resdom->restypmod,
601                                                          0);
602                         newvar->varnoold = 0;           /* wasn't ever a plain Var */
603                         newvar->varoattno = 0;
604                         return (Node *) newvar;
605                 }
606                 resdom = tlist_member(node, context->inner_tlist);
607                 if (resdom)
608                 {
609                         /* Found a matching subplan output expression */
610                         Var                *newvar;
611
612                         newvar = makeVar(INNER,
613                                                          resdom->resno,
614                                                          resdom->restype,
615                                                          resdom->restypmod,
616                                                          0);
617                         newvar->varnoold = 0;           /* wasn't ever a plain Var */
618                         newvar->varoattno = 0;
619                         return (Node *) newvar;
620                 }
621         }
622         return expression_tree_mutator(node,
623                                                                    join_references_mutator,
624                                                                    (void *) context);
625 }
626
627 /*
628  * replace_vars_with_subplan_refs
629  *              This routine modifies an expression tree so that all Var nodes
630  *              reference target nodes of a subplan.  It is used to fix up
631  *              target and qual expressions of non-join upper-level plan nodes.
632  *
633  * An error is raised if no matching var can be found in the subplan tlist
634  * --- so this routine should only be applied to nodes whose subplans'
635  * targetlists were generated via flatten_tlist() or some such method.
636  *
637  * If tlist_has_non_vars is true, then we try to match whole subexpressions
638  * against elements of the subplan tlist, so that we can avoid recomputing
639  * expressions that were already computed by the subplan.  (This is relatively
640  * expensive, so we don't want to try it in the common case where the
641  * subplan tlist is just a flattened list of Vars.)
642  *
643  * 'node': the tree to be fixed (a target item or qual)
644  * 'subvarno': varno to be assigned to all Vars
645  * 'subplan_targetlist': target list for subplan
646  * 'tlist_has_non_vars': true if subplan_targetlist contains non-Var exprs
647  *
648  * The resulting tree is a copy of the original in which all Var nodes have
649  * varno = subvarno, varattno = resno of corresponding subplan target.
650  * The original tree is not modified.
651  */
652 static Node *
653 replace_vars_with_subplan_refs(Node *node,
654                                                            Index subvarno,
655                                                            List *subplan_targetlist,
656                                                            bool tlist_has_non_vars)
657 {
658         replace_vars_with_subplan_refs_context context;
659
660         context.subvarno = subvarno;
661         context.subplan_targetlist = subplan_targetlist;
662         context.tlist_has_non_vars = tlist_has_non_vars;
663         return replace_vars_with_subplan_refs_mutator(node, &context);
664 }
665
666 static Node *
667 replace_vars_with_subplan_refs_mutator(Node *node,
668                                                  replace_vars_with_subplan_refs_context *context)
669 {
670         if (node == NULL)
671                 return NULL;
672         if (IsA(node, Var))
673         {
674                 Var                *var = (Var *) node;
675                 Resdom     *resdom;
676                 Var                *newvar;
677
678                 resdom = tlist_member((Node *) var, context->subplan_targetlist);
679                 if (!resdom)
680                         elog(ERROR, "replace_vars_with_subplan_refs: variable not in subplan target list");
681                 newvar = (Var *) copyObject(var);
682                 newvar->varno = context->subvarno;
683                 newvar->varattno = resdom->resno;
684                 return (Node *) newvar;
685         }
686         /* Try matching more complex expressions too, if tlist has any */
687         if (context->tlist_has_non_vars)
688         {
689                 Resdom     *resdom;
690
691                 resdom = tlist_member(node, context->subplan_targetlist);
692                 if (resdom)
693                 {
694                         /* Found a matching subplan output expression */
695                         Var                *newvar;
696
697                         newvar = makeVar(context->subvarno,
698                                                          resdom->resno,
699                                                          resdom->restype,
700                                                          resdom->restypmod,
701                                                          0);
702                         newvar->varnoold = 0;           /* wasn't ever a plain Var */
703                         newvar->varoattno = 0;
704                         return (Node *) newvar;
705                 }
706         }
707         return expression_tree_mutator(node,
708                                                                    replace_vars_with_subplan_refs_mutator,
709                                                                    (void *) context);
710 }
711
712 /*****************************************************************************
713  *                                      OPERATOR REGPROC LOOKUP
714  *****************************************************************************/
715
716 /*
717  * fix_opfuncids
718  *        Calculate opfuncid field from opno for each OpExpr node in given tree.
719  *        The given tree can be anything expression_tree_walker handles.
720  *
721  * The argument is modified in-place.  (This is OK since we'd want the
722  * same change for any node, even if it gets visited more than once due to
723  * shared structure.)
724  */
725 void
726 fix_opfuncids(Node *node)
727 {
728         /* This tree walk requires no special setup, so away we go... */
729         fix_opfuncids_walker(node, NULL);
730 }
731
732 static bool
733 fix_opfuncids_walker(Node *node, void *context)
734 {
735         if (node == NULL)
736                 return false;
737         if (IsA(node, OpExpr))
738                 set_opfuncid((OpExpr *) node);
739         else if (IsA(node, DistinctExpr))
740                 set_opfuncid((OpExpr *) node); /* rely on struct equivalence */
741         else if (IsA(node, NullIfExpr))
742                 set_opfuncid((OpExpr *) node); /* rely on struct equivalence */
743         return expression_tree_walker(node, fix_opfuncids_walker, context);
744 }