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