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