OSDN Git Service

Phase 2 of read-only-plans project: restructure expression-tree nodes
[pg-rex/syncrep.git] / src / backend / optimizer / util / clauses.c
1 /*-------------------------------------------------------------------------
2  *
3  * clauses.c
4  *        routines to manipulate qualification clauses
5  *
6  * Portions Copyright (c) 1996-2002, PostgreSQL Global Development Group
7  * Portions Copyright (c) 1994, Regents of the University of California
8  *
9  *
10  * IDENTIFICATION
11  *        $Header: /cvsroot/pgsql/src/backend/optimizer/util/clauses.c,v 1.116 2002/12/12 15:49:32 tgl Exp $
12  *
13  * HISTORY
14  *        AUTHOR                        DATE                    MAJOR EVENT
15  *        Andrew Yu                     Nov 3, 1994             clause.c and clauses.c combined
16  *
17  *-------------------------------------------------------------------------
18  */
19
20 #include "postgres.h"
21
22 #include "catalog/pg_language.h"
23 #include "catalog/pg_operator.h"
24 #include "catalog/pg_proc.h"
25 #include "catalog/pg_type.h"
26 #include "executor/executor.h"
27 #include "miscadmin.h"
28 #include "nodes/makefuncs.h"
29 #include "nodes/nodeFuncs.h"
30 #include "optimizer/clauses.h"
31 #include "optimizer/tlist.h"
32 #include "optimizer/var.h"
33 #include "parser/analyze.h"
34 #include "parser/parsetree.h"
35 #include "tcop/tcopprot.h"
36 #include "utils/acl.h"
37 #include "utils/builtins.h"
38 #include "utils/datum.h"
39 #include "utils/lsyscache.h"
40 #include "utils/memutils.h"
41 #include "utils/syscache.h"
42
43
44 /* note that pg_type.h hardwires size of bool as 1 ... duplicate it */
45 #define MAKEBOOLCONST(val,isnull) \
46         ((Node *) makeConst(BOOLOID, 1, (Datum) (val), (isnull), true))
47
48 typedef struct
49 {
50         Query      *query;
51         List       *groupClauses;
52 } check_subplans_for_ungrouped_vars_context;
53
54 typedef struct
55 {
56         int                     nargs;
57         List       *args;
58         int                *usecounts;
59 } substitute_actual_parameters_context;
60
61 static bool contain_agg_clause_walker(Node *node, void *context);
62 static bool contain_distinct_agg_clause_walker(Node *node, void *context);
63 static bool pull_agg_clause_walker(Node *node, List **listptr);
64 static bool expression_returns_set_walker(Node *node, void *context);
65 static bool contain_subplans_walker(Node *node, void *context);
66 static bool pull_subplans_walker(Node *node, List **listptr);
67 static bool check_subplans_for_ungrouped_vars_walker(Node *node,
68                                          check_subplans_for_ungrouped_vars_context *context);
69 static bool contain_mutable_functions_walker(Node *node, void *context);
70 static bool contain_volatile_functions_walker(Node *node, void *context);
71 static bool contain_nonstrict_functions_walker(Node *node, void *context);
72 static Node *eval_const_expressions_mutator(Node *node, List *active_fns);
73 static Expr *simplify_function(Oid funcid, List *args, bool allow_inline,
74                                                            List *active_fns);
75 static Expr *evaluate_function(Oid funcid, List *args, HeapTuple func_tuple);
76 static Expr *inline_function(Oid funcid, List *args, HeapTuple func_tuple,
77                                                          List *active_fns);
78 static Node *substitute_actual_parameters(Node *expr, int nargs, List *args,
79                                                                                   int *usecounts);
80 static Node *substitute_actual_parameters_mutator(Node *node,
81                                          substitute_actual_parameters_context *context);
82
83
84 /*****************************************************************************
85  *              OPERATOR clause functions
86  *****************************************************************************/
87
88 /*
89  * make_opclause
90  *        Creates an operator clause given its operator info, left operand,
91  *        and right operand (pass NULL to create single-operand clause).
92  */
93 Expr *
94 make_opclause(Oid opno, Oid opresulttype, bool opretset,
95                           Expr *leftop, Expr *rightop)
96 {
97         OpExpr     *expr = makeNode(OpExpr);
98
99         expr->opno = opno;
100         expr->opfuncid = InvalidOid;
101         expr->opresulttype = opresulttype;
102         expr->opretset = opretset;
103         if (rightop)
104                 expr->args = makeList2(leftop, rightop);
105         else
106                 expr->args = makeList1(leftop);
107         return (Expr *) expr;
108 }
109
110 /*
111  * get_leftop
112  *
113  * Returns the left operand of a clause of the form (op expr expr)
114  *              or (op expr)
115  *
116  * NB: for historical reasons, the result is declared Var *, even
117  * though many callers can cope with results that are not Vars.
118  * The result really ought to be declared Expr * or Node *.
119  */
120 Var *
121 get_leftop(Expr *clause)
122 {
123         OpExpr *expr = (OpExpr *) clause;
124
125         if (expr->args != NULL)
126                 return lfirst(expr->args);
127         else
128                 return NULL;
129 }
130
131 /*
132  * get_rightop
133  *
134  * Returns the right operand in a clause of the form (op expr expr).
135  * NB: result will be NULL if applied to a unary op clause.
136  */
137 Var *
138 get_rightop(Expr *clause)
139 {
140         OpExpr *expr = (OpExpr *) clause;
141
142         if (expr->args != NULL && lnext(expr->args) != NULL)
143                 return lfirst(lnext(expr->args));
144         else
145                 return NULL;
146 }
147
148 /*****************************************************************************
149  *              FUNCTION clause functions
150  *****************************************************************************/
151
152 /*
153  * make_funcclause
154  *        Creates a function clause given its function info and argument list.
155  */
156 Expr *
157 make_funcclause(Oid funcid, Oid funcresulttype, bool funcretset,
158                                 CoercionForm funcformat, List *funcargs)
159 {
160         FuncExpr   *expr = makeNode(FuncExpr);
161
162         expr->funcid = funcid;
163         expr->funcresulttype = funcresulttype;
164         expr->funcretset = funcretset;
165         expr->funcformat = funcformat;
166         expr->args = funcargs;
167         return (Expr *) expr;
168 }
169
170 /*****************************************************************************
171  *              NOT clause functions
172  *****************************************************************************/
173
174 /*
175  * not_clause
176  *
177  * Returns t iff this is a 'not' clause: (NOT expr).
178  */
179 bool
180 not_clause(Node *clause)
181 {
182         return (clause != NULL &&
183                         IsA(clause, BoolExpr) &&
184                         ((BoolExpr *) clause)->boolop == NOT_EXPR);
185 }
186
187 /*
188  * make_notclause
189  *
190  * Create a 'not' clause given the expression to be negated.
191  */
192 Expr *
193 make_notclause(Expr *notclause)
194 {
195         BoolExpr   *expr = makeNode(BoolExpr);
196
197         expr->boolop = NOT_EXPR;
198         expr->args = makeList1(notclause);
199         return (Expr *) expr;
200 }
201
202 /*
203  * get_notclausearg
204  *
205  * Retrieve the clause within a 'not' clause
206  */
207 Expr *
208 get_notclausearg(Expr *notclause)
209 {
210         return lfirst(((BoolExpr *) notclause)->args);
211 }
212
213 /*****************************************************************************
214  *              OR clause functions
215  *****************************************************************************/
216
217 /*
218  * or_clause
219  *
220  * Returns t iff the clause is an 'or' clause: (OR { expr }).
221  */
222 bool
223 or_clause(Node *clause)
224 {
225         return (clause != NULL &&
226                         IsA(clause, BoolExpr) &&
227                         ((BoolExpr *) clause)->boolop == OR_EXPR);
228 }
229
230 /*
231  * make_orclause
232  *
233  * Creates an 'or' clause given a list of its subclauses.
234  */
235 Expr *
236 make_orclause(List *orclauses)
237 {
238         BoolExpr   *expr = makeNode(BoolExpr);
239
240         expr->boolop = OR_EXPR;
241         expr->args = orclauses;
242         return (Expr *) expr;
243 }
244
245 /*****************************************************************************
246  *              AND clause functions
247  *****************************************************************************/
248
249
250 /*
251  * and_clause
252  *
253  * Returns t iff its argument is an 'and' clause: (AND { expr }).
254  */
255 bool
256 and_clause(Node *clause)
257 {
258         return (clause != NULL &&
259                         IsA(clause, BoolExpr) &&
260                         ((BoolExpr *) clause)->boolop == AND_EXPR);
261 }
262
263 /*
264  * make_andclause
265  *
266  * Creates an 'and' clause given a list of its subclauses.
267  */
268 Expr *
269 make_andclause(List *andclauses)
270 {
271         BoolExpr   *expr = makeNode(BoolExpr);
272
273         expr->boolop = AND_EXPR;
274         expr->args = andclauses;
275         return (Expr *) expr;
276 }
277
278 /*
279  * make_and_qual
280  *
281  * Variant of make_andclause for ANDing two qual conditions together.
282  * Qual conditions have the property that a NULL nodetree is interpreted
283  * as 'true'.
284  */
285 Node *
286 make_and_qual(Node *qual1, Node *qual2)
287 {
288         if (qual1 == NULL)
289                 return qual2;
290         if (qual2 == NULL)
291                 return qual1;
292         return (Node *) make_andclause(makeList2(qual1, qual2));
293 }
294
295 /*
296  * Sometimes (such as in the result of canonicalize_qual or the input of
297  * ExecQual), we use lists of expression nodes with implicit AND semantics.
298  *
299  * These functions convert between an AND-semantics expression list and the
300  * ordinary representation of a boolean expression.
301  *
302  * Note that an empty list is considered equivalent to TRUE.
303  */
304 Expr *
305 make_ands_explicit(List *andclauses)
306 {
307         if (andclauses == NIL)
308                 return (Expr *) MAKEBOOLCONST(true, false);
309         else if (lnext(andclauses) == NIL)
310                 return (Expr *) lfirst(andclauses);
311         else
312                 return make_andclause(andclauses);
313 }
314
315 List *
316 make_ands_implicit(Expr *clause)
317 {
318         /*
319          * NB: because the parser sets the qual field to NULL in a query that
320          * has no WHERE clause, we must consider a NULL input clause as TRUE,
321          * even though one might more reasonably think it FALSE.  Grumble. If
322          * this causes trouble, consider changing the parser's behavior.
323          */
324         if (clause == NULL)
325                 return NIL;                             /* NULL -> NIL list == TRUE */
326         else if (and_clause((Node *) clause))
327                 return ((BoolExpr *) clause)->args;
328         else if (IsA(clause, Const) &&
329                          !((Const *) clause)->constisnull &&
330                          DatumGetBool(((Const *) clause)->constvalue))
331                 return NIL;                             /* constant TRUE input -> NIL list */
332         else
333                 return makeList1(clause);
334 }
335
336
337 /*****************************************************************************
338  *              Aggregate-function clause manipulation
339  *****************************************************************************/
340
341 /*
342  * contain_agg_clause
343  *        Recursively search for Aggref nodes within a clause.
344  *
345  *        Returns true if any aggregate found.
346  */
347 bool
348 contain_agg_clause(Node *clause)
349 {
350         return contain_agg_clause_walker(clause, NULL);
351 }
352
353 static bool
354 contain_agg_clause_walker(Node *node, void *context)
355 {
356         if (node == NULL)
357                 return false;
358         if (IsA(node, Aggref))
359                 return true;                    /* abort the tree traversal and return
360                                                                  * true */
361         return expression_tree_walker(node, contain_agg_clause_walker, context);
362 }
363
364 /*
365  * contain_distinct_agg_clause
366  *        Recursively search for DISTINCT Aggref nodes within a clause.
367  *
368  *        Returns true if any DISTINCT aggregate found.
369  */
370 bool
371 contain_distinct_agg_clause(Node *clause)
372 {
373         return contain_distinct_agg_clause_walker(clause, NULL);
374 }
375
376 static bool
377 contain_distinct_agg_clause_walker(Node *node, void *context)
378 {
379         if (node == NULL)
380                 return false;
381         if (IsA(node, Aggref))
382         {
383                 if (((Aggref *) node)->aggdistinct)
384                         return true;            /* abort the tree traversal and return
385                                                                  * true */
386         }
387         return expression_tree_walker(node, contain_distinct_agg_clause_walker, context);
388 }
389
390 /*
391  * pull_agg_clause
392  *        Recursively pulls all Aggref nodes from an expression tree.
393  *
394  *        Returns list of Aggref nodes found.  Note the nodes themselves are not
395  *        copied, only referenced.
396  *
397  *        Note: this also checks for nested aggregates, which are an error.
398  */
399 List *
400 pull_agg_clause(Node *clause)
401 {
402         List       *result = NIL;
403
404         pull_agg_clause_walker(clause, &result);
405         return result;
406 }
407
408 static bool
409 pull_agg_clause_walker(Node *node, List **listptr)
410 {
411         if (node == NULL)
412                 return false;
413         if (IsA(node, Aggref))
414         {
415                 *listptr = lappend(*listptr, node);
416
417                 /*
418                  * Complain if the aggregate's argument contains any aggregates;
419                  * nested agg functions are semantically nonsensical.
420                  */
421                 if (contain_agg_clause((Node *) ((Aggref *) node)->target))
422                         elog(ERROR, "Aggregate function calls may not be nested");
423
424                 /*
425                  * Having checked that, we need not recurse into the argument.
426                  */
427                 return false;
428         }
429         return expression_tree_walker(node, pull_agg_clause_walker,
430                                                                   (void *) listptr);
431 }
432
433
434 /*****************************************************************************
435  *              Support for expressions returning sets
436  *****************************************************************************/
437
438 /*
439  * expression_returns_set
440  *        Test whether an expression returns a set result.
441  *
442  * Because we use expression_tree_walker(), this can also be applied to
443  * whole targetlists; it'll produce TRUE if any one of the tlist items
444  * returns a set.
445  */
446 bool
447 expression_returns_set(Node *clause)
448 {
449         return expression_returns_set_walker(clause, NULL);
450 }
451
452 static bool
453 expression_returns_set_walker(Node *node, void *context)
454 {
455         if (node == NULL)
456                 return false;
457         if (IsA(node, FuncExpr))
458         {
459                 FuncExpr   *expr = (FuncExpr *) node;
460
461                 if (expr->funcretset)
462                         return true;
463                 /* else fall through to check args */
464         }
465         if (IsA(node, OpExpr))
466         {
467                 OpExpr   *expr = (OpExpr *) node;
468
469                 if (expr->opretset)
470                         return true;
471                 /* else fall through to check args */
472         }
473         if (IsA(node, DistinctExpr))
474         {
475                 DistinctExpr   *expr = (DistinctExpr *) node;
476
477                 if (expr->opretset)
478                         return true;
479                 /* else fall through to check args */
480         }
481
482         /* Avoid recursion for some cases that can't return a set */
483         if (IsA(node, BoolExpr))
484                 return false;
485         if (IsA(node, Aggref))
486                 return false;
487         if (IsA(node, SubLink))
488                 return false;
489         if (IsA(node, SubPlanExpr))
490                 return false;
491
492         return expression_tree_walker(node, expression_returns_set_walker,
493                                                                   context);
494 }
495
496 /*****************************************************************************
497  *              Subplan clause manipulation
498  *****************************************************************************/
499
500 /*
501  * contain_subplans
502  *        Recursively search for subplan nodes within a clause.
503  *
504  * If we see a SubLink node, we will return TRUE.  This is only possible if
505  * the expression tree hasn't yet been transformed by subselect.c.  We do not
506  * know whether the node will produce a true subplan or just an initplan,
507  * but we make the conservative assumption that it will be a subplan.
508  *
509  * Returns true if any subplan found.
510  */
511 bool
512 contain_subplans(Node *clause)
513 {
514         return contain_subplans_walker(clause, NULL);
515 }
516
517 static bool
518 contain_subplans_walker(Node *node, void *context)
519 {
520         if (node == NULL)
521                 return false;
522         if (IsA(node, SubPlanExpr) ||
523                 IsA(node, SubLink))
524                 return true;                    /* abort the tree traversal and return
525                                                                  * true */
526         return expression_tree_walker(node, contain_subplans_walker, context);
527 }
528
529 /*
530  * pull_subplans
531  *        Recursively pulls all subplans from an expression tree.
532  *
533  *        Returns list of SubPlanExpr nodes found.  Note the nodes themselves
534  *        are not copied, only referenced.
535  */
536 List *
537 pull_subplans(Node *clause)
538 {
539         List       *result = NIL;
540
541         pull_subplans_walker(clause, &result);
542         return result;
543 }
544
545 static bool
546 pull_subplans_walker(Node *node, List **listptr)
547 {
548         if (node == NULL)
549                 return false;
550         if (is_subplan(node))
551         {
552                 *listptr = lappend(*listptr, node);
553                 /* fall through to check args to subplan */
554         }
555         return expression_tree_walker(node, pull_subplans_walker,
556                                                                   (void *) listptr);
557 }
558
559 /*
560  * check_subplans_for_ungrouped_vars
561  *              Check for subplans that are being passed ungrouped variables as
562  *              parameters; generate an error message if any are found.
563  *
564  * In most contexts, ungrouped variables will be detected by the parser (see
565  * parse_agg.c, check_ungrouped_columns()). But that routine currently does
566  * not check subplans, because the necessary info is not computed until the
567  * planner runs.  So we do it here, after we have processed sublinks into
568  * subplans.  This ought to be cleaned up someday.
569  *
570  * A deficiency in this scheme is that any outer reference var must be
571  * grouped by itself; we don't recognize groupable expressions within
572  * subselects.  For example, consider
573  *              SELECT
574  *                      (SELECT x FROM bar where y = (foo.a + foo.b))
575  *              FROM foo
576  *              GROUP BY a + b;
577  * This query will be rejected although it could be allowed.
578  */
579 void
580 check_subplans_for_ungrouped_vars(Query *query)
581 {
582         check_subplans_for_ungrouped_vars_context context;
583         List       *gl;
584
585         context.query = query;
586
587         /*
588          * Build a list of the acceptable GROUP BY expressions for use in the
589          * walker (to avoid repeated scans of the targetlist within the
590          * recursive routine).
591          */
592         context.groupClauses = NIL;
593         foreach(gl, query->groupClause)
594         {
595                 GroupClause *grpcl = lfirst(gl);
596                 Node       *expr;
597
598                 expr = get_sortgroupclause_expr(grpcl, query->targetList);
599                 context.groupClauses = lcons(expr, context.groupClauses);
600         }
601
602         /*
603          * Recursively scan the targetlist and the HAVING clause. WHERE and
604          * JOIN/ON conditions are not examined, since they are evaluated
605          * before grouping.
606          */
607         check_subplans_for_ungrouped_vars_walker((Node *) query->targetList,
608                                                                                          &context);
609         check_subplans_for_ungrouped_vars_walker(query->havingQual,
610                                                                                          &context);
611
612         freeList(context.groupClauses);
613 }
614
615 static bool
616 check_subplans_for_ungrouped_vars_walker(Node *node,
617                                           check_subplans_for_ungrouped_vars_context *context)
618 {
619         List       *gl;
620
621         if (node == NULL)
622                 return false;
623         if (IsA(node, Const) ||
624                 IsA(node, Param))
625                 return false;                   /* constants are always acceptable */
626
627         /*
628          * If we find an aggregate function, do not recurse into its
629          * arguments.  Subplans invoked within aggregate calls are allowed to
630          * receive ungrouped variables.  (This test and the next one should
631          * match the logic in parse_agg.c's check_ungrouped_columns().)
632          */
633         if (IsA(node, Aggref))
634                 return false;
635
636         /*
637          * Check to see if subexpression as a whole matches any GROUP BY item.
638          * We need to do this at every recursion level so that we recognize
639          * GROUPed-BY expressions before reaching variables within them.
640          */
641         foreach(gl, context->groupClauses)
642         {
643                 if (equal(node, lfirst(gl)))
644                         return false;           /* acceptable, do not descend more */
645         }
646
647         /*
648          * We can ignore Vars other than in subplan args lists, since the
649          * parser already checked 'em.
650          */
651         if (is_subplan(node))
652         {
653                 /*
654                  * The args list of the subplan node represents attributes from
655                  * outside passed into the sublink.
656                  */
657                 List       *t;
658
659                 foreach(t, ((SubPlanExpr *) node)->args)
660                 {
661                         Node       *thisarg = lfirst(t);
662                         Var                *var;
663                         bool            contained_in_group_clause;
664
665                         /*
666                          * We do not care about args that are not local variables;
667                          * params or outer-level vars are not our responsibility to
668                          * check.  (The outer-level query passing them to us needs to
669                          * worry, instead.)
670                          */
671                         if (!IsA(thisarg, Var))
672                                 continue;
673                         var = (Var *) thisarg;
674                         if (var->varlevelsup > 0)
675                                 continue;
676
677                         /*
678                          * Else, see if it is a grouping column.
679                          */
680                         contained_in_group_clause = false;
681                         foreach(gl, context->groupClauses)
682                         {
683                                 if (equal(thisarg, lfirst(gl)))
684                                 {
685                                         contained_in_group_clause = true;
686                                         break;
687                                 }
688                         }
689
690                         if (!contained_in_group_clause)
691                         {
692                                 /* Found an ungrouped argument.  Complain. */
693                                 RangeTblEntry *rte;
694                                 char       *attname;
695
696                                 Assert(var->varno > 0 &&
697                                          (int) var->varno <= length(context->query->rtable));
698                                 rte = rt_fetch(var->varno, context->query->rtable);
699                                 attname = get_rte_attribute_name(rte, var->varattno);
700                                 elog(ERROR, "Sub-SELECT uses un-GROUPed attribute %s.%s from outer query",
701                                          rte->eref->aliasname, attname);
702                         }
703                 }
704         }
705         return expression_tree_walker(node,
706                                                                 check_subplans_for_ungrouped_vars_walker,
707                                                                   (void *) context);
708 }
709
710
711 /*****************************************************************************
712  *              Check clauses for mutable functions
713  *****************************************************************************/
714
715 /*
716  * contain_mutable_functions
717  *        Recursively search for mutable functions within a clause.
718  *
719  * Returns true if any mutable function (or operator implemented by a
720  * mutable function) is found.  This test is needed so that we don't
721  * mistakenly think that something like "WHERE random() < 0.5" can be treated
722  * as a constant qualification.
723  *
724  * XXX we do not examine sublinks/subplans to see if they contain uses of
725  * mutable functions.  It's not real clear if that is correct or not...
726  */
727 bool
728 contain_mutable_functions(Node *clause)
729 {
730         return contain_mutable_functions_walker(clause, NULL);
731 }
732
733 static bool
734 contain_mutable_functions_walker(Node *node, void *context)
735 {
736         if (node == NULL)
737                 return false;
738         if (IsA(node, FuncExpr))
739         {
740                 FuncExpr   *expr = (FuncExpr *) node;
741
742                 if (func_volatile(expr->funcid) != PROVOLATILE_IMMUTABLE)
743                         return true;
744                 /* else fall through to check args */
745         }
746         if (IsA(node, OpExpr))
747         {
748                 OpExpr   *expr = (OpExpr *) node;
749
750                 if (op_volatile(expr->opno) != PROVOLATILE_IMMUTABLE)
751                         return true;
752                 /* else fall through to check args */
753         }
754         if (IsA(node, DistinctExpr))
755         {
756                 DistinctExpr   *expr = (DistinctExpr *) node;
757
758                 if (op_volatile(expr->opno) != PROVOLATILE_IMMUTABLE)
759                         return true;
760                 /* else fall through to check args */
761         }
762         return expression_tree_walker(node, contain_mutable_functions_walker,
763                                                                   context);
764 }
765
766
767 /*****************************************************************************
768  *              Check clauses for volatile functions
769  *****************************************************************************/
770
771 /*
772  * contain_volatile_functions
773  *        Recursively search for volatile functions within a clause.
774  *
775  * Returns true if any volatile function (or operator implemented by a
776  * volatile function) is found. This test prevents invalid conversions
777  * of volatile expressions into indexscan quals.
778  *
779  * XXX we do not examine sublinks/subplans to see if they contain uses of
780  * volatile functions.  It's not real clear if that is correct or not...
781  */
782 bool
783 contain_volatile_functions(Node *clause)
784 {
785         return contain_volatile_functions_walker(clause, NULL);
786 }
787
788 static bool
789 contain_volatile_functions_walker(Node *node, void *context)
790 {
791         if (node == NULL)
792                 return false;
793         if (IsA(node, FuncExpr))
794         {
795                 FuncExpr   *expr = (FuncExpr *) node;
796
797                 if (func_volatile(expr->funcid) == PROVOLATILE_VOLATILE)
798                         return true;
799                 /* else fall through to check args */
800         }
801         if (IsA(node, OpExpr))
802         {
803                 OpExpr   *expr = (OpExpr *) node;
804
805                 if (op_volatile(expr->opno) == PROVOLATILE_VOLATILE)
806                         return true;
807                 /* else fall through to check args */
808         }
809         if (IsA(node, DistinctExpr))
810         {
811                 DistinctExpr   *expr = (DistinctExpr *) node;
812
813                 if (op_volatile(expr->opno) == PROVOLATILE_VOLATILE)
814                         return true;
815                 /* else fall through to check args */
816         }
817         return expression_tree_walker(node, contain_volatile_functions_walker,
818                                                                   context);
819 }
820
821
822 /*****************************************************************************
823  *              Check clauses for nonstrict functions
824  *****************************************************************************/
825
826 /*
827  * contain_nonstrict_functions
828  *        Recursively search for nonstrict functions within a clause.
829  *
830  * Returns true if any nonstrict construct is found --- ie, anything that
831  * could produce non-NULL output with a NULL input.
832  *
833  * XXX we do not examine sublinks/subplans to see if they contain uses of
834  * nonstrict functions. It's not real clear if that is correct or not...
835  * for the current usage it does not matter, since inline_function()
836  * rejects cases with sublinks.
837  */
838 bool
839 contain_nonstrict_functions(Node *clause)
840 {
841         return contain_nonstrict_functions_walker(clause, NULL);
842 }
843
844 static bool
845 contain_nonstrict_functions_walker(Node *node, void *context)
846 {
847         if (node == NULL)
848                 return false;
849         if (IsA(node, FuncExpr))
850         {
851                 FuncExpr   *expr = (FuncExpr *) node;
852
853                 if (!func_strict(expr->funcid))
854                         return true;
855                 /* else fall through to check args */
856         }
857         if (IsA(node, OpExpr))
858         {
859                 OpExpr   *expr = (OpExpr *) node;
860
861                 if (!op_strict(expr->opno))
862                         return true;
863                 /* else fall through to check args */
864         }
865         if (IsA(node, DistinctExpr))
866         {
867                 /* IS DISTINCT FROM is inherently non-strict */
868                 return true;
869         }
870         if (IsA(node, BoolExpr))
871         {
872                 BoolExpr   *expr = (BoolExpr *) node;
873
874                 switch (expr->boolop)
875                 {
876                         case OR_EXPR:
877                         case AND_EXPR:
878                                 /* OR, AND are inherently non-strict */
879                                 return true;
880                         default:
881                                 break;
882                 }
883         }
884         if (IsA(node, CaseExpr))
885                 return true;
886         if (IsA(node, NullTest))
887                 return true;
888         if (IsA(node, BooleanTest))
889                 return true;
890         return expression_tree_walker(node, contain_nonstrict_functions_walker,
891                                                                   context);
892 }
893
894
895 /*****************************************************************************
896  *              Check for "pseudo-constant" clauses
897  *****************************************************************************/
898
899 /*
900  * is_pseudo_constant_clause
901  *        Detect whether a clause is "constant", ie, it contains no variables
902  *        of the current query level and no uses of volatile functions.
903  *        Such a clause is not necessarily a true constant: it can still contain
904  *        Params and outer-level Vars, not to mention functions whose results
905  *        may vary from one statement to the next.      However, the clause's value
906  *        will be constant over any one scan of the current query, so it can be
907  *        used as an indexscan key or (if a top-level qual) can be pushed up to
908  *        become a gating qual.
909  */
910 bool
911 is_pseudo_constant_clause(Node *clause)
912 {
913         /*
914          * We could implement this check in one recursive scan.  But since the
915          * check for volatile functions is both moderately expensive and
916          * unlikely to fail, it seems better to look for Vars first and only
917          * check for volatile functions if we find no Vars.
918          */
919         if (!contain_var_clause(clause) &&
920                 !contain_volatile_functions(clause))
921                 return true;
922         return false;
923 }
924
925 /*
926  * pull_constant_clauses
927  *              Scan through a list of qualifications and separate "constant" quals
928  *              from those that are not.
929  *
930  * Returns a list of the pseudo-constant clauses in constantQual and the
931  * remaining quals as the return value.
932  */
933 List *
934 pull_constant_clauses(List *quals, List **constantQual)
935 {
936         List       *constqual = NIL;
937         List       *restqual = NIL;
938         List       *q;
939
940         foreach(q, quals)
941         {
942                 Node       *qual = (Node *) lfirst(q);
943
944                 if (is_pseudo_constant_clause(qual))
945                         constqual = lappend(constqual, qual);
946                 else
947                         restqual = lappend(restqual, qual);
948         }
949         *constantQual = constqual;
950         return restqual;
951 }
952
953
954 /*****************************************************************************
955  *              Tests on clauses of queries
956  *
957  * Possibly this code should go someplace else, since this isn't quite the
958  * same meaning of "clause" as is used elsewhere in this module.  But I can't
959  * think of a better place for it...
960  *****************************************************************************/
961
962 /*
963  * Test whether a sort/group reference value appears in the given list of
964  * SortClause (or GroupClause) nodes.
965  *
966  * Because GroupClause is typedef'd as SortClause, either kind of
967  * node list can be passed without casting.
968  */
969 static bool
970 sortgroupref_is_present(Index sortgroupref, List *clauselist)
971 {
972         List       *clause;
973
974         foreach(clause, clauselist)
975         {
976                 SortClause *scl = (SortClause *) lfirst(clause);
977
978                 if (scl->tleSortGroupRef == sortgroupref)
979                         return true;
980         }
981         return false;
982 }
983
984 /*
985  * Test whether a query uses DISTINCT ON, ie, has a distinct-list that is
986  * not the same as the set of output columns.
987  */
988 bool
989 has_distinct_on_clause(Query *query)
990 {
991         List       *targetList;
992
993         /* Is there a DISTINCT clause at all? */
994         if (query->distinctClause == NIL)
995                 return false;
996
997         /*
998          * If the DISTINCT list contains all the nonjunk targetlist items, and
999          * nothing else (ie, no junk tlist items), then it's a simple
1000          * DISTINCT, else it's DISTINCT ON.  We do not require the lists to be
1001          * in the same order (since the parser may have adjusted the DISTINCT
1002          * clause ordering to agree with ORDER BY).  Furthermore, a
1003          * non-DISTINCT junk tlist item that is in the sortClause is also
1004          * evidence of DISTINCT ON, since we don't allow ORDER BY on junk
1005          * tlist items when plain DISTINCT is used.
1006          *
1007          * This code assumes that the DISTINCT list is valid, ie, all its entries
1008          * match some entry of the tlist.
1009          */
1010         foreach(targetList, query->targetList)
1011         {
1012                 TargetEntry *tle = (TargetEntry *) lfirst(targetList);
1013                 Index           ressortgroupref = tle->resdom->ressortgroupref;
1014
1015                 if (ressortgroupref == 0)
1016                 {
1017                         if (tle->resdom->resjunk)
1018                                 continue;               /* we can ignore unsorted junk cols */
1019                         return true;            /* definitely not in DISTINCT list */
1020                 }
1021                 if (sortgroupref_is_present(ressortgroupref, query->distinctClause))
1022                 {
1023                         if (tle->resdom->resjunk)
1024                                 return true;    /* junk TLE in DISTINCT means DISTINCT ON */
1025                         /* else this TLE is okay, keep looking */
1026                 }
1027                 else
1028                 {
1029                         /* This TLE is not in DISTINCT list */
1030                         if (!tle->resdom->resjunk)
1031                                 return true;    /* non-junk, non-DISTINCT, so DISTINCT ON */
1032                         if (sortgroupref_is_present(ressortgroupref, query->sortClause))
1033                                 return true;    /* sorted, non-distinct junk */
1034                         /* unsorted junk is okay, keep looking */
1035                 }
1036         }
1037         /* It's a simple DISTINCT */
1038         return false;
1039 }
1040
1041
1042 /*****************************************************************************
1043  *                                                                                                                                                       *
1044  *              General clause-manipulating routines                                                             *
1045  *                                                                                                                                                       *
1046  *****************************************************************************/
1047
1048 /*
1049  * clause_get_relids_vars
1050  *        Retrieves distinct relids and vars appearing within a clause.
1051  *
1052  * '*relids' is set to an integer list of all distinct "varno"s appearing
1053  *              in Vars within the clause.
1054  * '*vars' is set to a list of all distinct Vars appearing within the clause.
1055  *              Var nodes are considered distinct if they have different varno
1056  *              or varattno values.  If there are several occurrences of the same
1057  *              varno/varattno, you get a randomly chosen one...
1058  *
1059  * Note that upper-level vars are ignored, since they normally will
1060  * become Params with respect to this query level.
1061  */
1062 void
1063 clause_get_relids_vars(Node *clause, Relids *relids, List **vars)
1064 {
1065         List       *clvars = pull_var_clause(clause, false);
1066         List       *varno_list = NIL;
1067         List       *var_list = NIL;
1068         List       *i;
1069
1070         foreach(i, clvars)
1071         {
1072                 Var                *var = (Var *) lfirst(i);
1073                 List       *vi;
1074
1075                 if (!intMember(var->varno, varno_list))
1076                         varno_list = lconsi(var->varno, varno_list);
1077                 foreach(vi, var_list)
1078                 {
1079                         Var                *in_list = (Var *) lfirst(vi);
1080
1081                         if (in_list->varno == var->varno &&
1082                                 in_list->varattno == var->varattno)
1083                                 break;
1084                 }
1085                 if (vi == NIL)
1086                         var_list = lcons(var, var_list);
1087         }
1088         freeList(clvars);
1089
1090         *relids = varno_list;
1091         *vars = var_list;
1092 }
1093
1094 /*
1095  * NumRelids
1096  *              (formerly clause_relids)
1097  *
1098  * Returns the number of different relations referenced in 'clause'.
1099  */
1100 int
1101 NumRelids(Node *clause)
1102 {
1103         List       *varno_list = pull_varnos(clause);
1104         int                     result = length(varno_list);
1105
1106         freeList(varno_list);
1107         return result;
1108 }
1109
1110 /*
1111  * CommuteClause: commute a binary operator clause
1112  *
1113  * XXX the clause is destructively modified!
1114  */
1115 void
1116 CommuteClause(OpExpr *clause)
1117 {
1118         Oid                     opoid;
1119         Node       *temp;
1120
1121         if (!is_opclause(clause) ||
1122                 length(clause->args) != 2)
1123                 elog(ERROR, "CommuteClause: applied to non-binary-operator clause");
1124
1125         opoid = get_commutator(clause->opno);
1126
1127         if (!OidIsValid(opoid))
1128                 elog(ERROR, "CommuteClause: no commutator for operator %u",
1129                          clause->opno);
1130
1131         /*
1132          * modify the clause in-place!
1133          */
1134         clause->opno = opoid;
1135         clause->opfuncid = InvalidOid;
1136         /* opresulttype and opretset are assumed not to change */
1137
1138         temp = lfirst(clause->args);
1139         lfirst(clause->args) = lsecond(clause->args);
1140         lsecond(clause->args) = temp;
1141 }
1142
1143
1144 /*--------------------
1145  * eval_const_expressions
1146  *
1147  * Reduce any recognizably constant subexpressions of the given
1148  * expression tree, for example "2 + 2" => "4".  More interestingly,
1149  * we can reduce certain boolean expressions even when they contain
1150  * non-constant subexpressions: "x OR true" => "true" no matter what
1151  * the subexpression x is.      (XXX We assume that no such subexpression
1152  * will have important side-effects, which is not necessarily a good
1153  * assumption in the presence of user-defined functions; do we need a
1154  * pg_proc flag that prevents discarding the execution of a function?)
1155  *
1156  * We do understand that certain functions may deliver non-constant
1157  * results even with constant inputs, "nextval()" being the classic
1158  * example.  Functions that are not marked "immutable" in pg_proc
1159  * will not be pre-evaluated here, although we will reduce their
1160  * arguments as far as possible.
1161  *
1162  * We assume that the tree has already been type-checked and contains
1163  * only operators and functions that are reasonable to try to execute.
1164  *--------------------
1165  */
1166 Node *
1167 eval_const_expressions(Node *node)
1168 {
1169         /*
1170          * The context for the mutator is a list of SQL functions being
1171          * recursively simplified, so we start with an empty list.
1172          */
1173         return eval_const_expressions_mutator(node, NIL);
1174 }
1175
1176 static Node *
1177 eval_const_expressions_mutator(Node *node, List *active_fns)
1178 {
1179         if (node == NULL)
1180                 return NULL;
1181         if (IsA(node, FuncExpr))
1182         {
1183                 FuncExpr   *expr = (FuncExpr *) node;
1184                 List       *args;
1185                 Expr       *simple;
1186                 FuncExpr   *newexpr;
1187
1188                 /*
1189                  * Reduce constants in the FuncExpr's arguments.  We know args is
1190                  * either NIL or a List node, so we can call
1191                  * expression_tree_mutator directly rather than recursing to self.
1192                  */
1193                 args = (List *) expression_tree_mutator((Node *) expr->args,
1194                                                                                   eval_const_expressions_mutator,
1195                                                                                                 (void *) active_fns);
1196                 /*
1197                  * Code for op/func reduction is pretty bulky, so split it out
1198                  * as a separate function.
1199                  */
1200                 simple = simplify_function(expr->funcid, args, true, active_fns);
1201                 if (simple)                             /* successfully simplified it */
1202                         return (Node *) simple;
1203                 /*
1204                  * The expression cannot be simplified any further, so build and
1205                  * return a replacement FuncExpr node using the possibly-simplified
1206                  * arguments.
1207                  */
1208                 newexpr = makeNode(FuncExpr);
1209                 newexpr->funcid = expr->funcid;
1210                 newexpr->funcresulttype = expr->funcresulttype;
1211                 newexpr->funcretset = expr->funcretset;
1212                 newexpr->funcformat = expr->funcformat;
1213                 newexpr->args = args;
1214                 return (Node *) newexpr;
1215         }
1216         if (IsA(node, OpExpr))
1217         {
1218                 OpExpr     *expr = (OpExpr *) node;
1219                 List       *args;
1220                 Expr       *simple;
1221                 OpExpr     *newexpr;
1222
1223                 /*
1224                  * Reduce constants in the OpExpr's arguments.  We know args is
1225                  * either NIL or a List node, so we can call
1226                  * expression_tree_mutator directly rather than recursing to self.
1227                  */
1228                 args = (List *) expression_tree_mutator((Node *) expr->args,
1229                                                                                   eval_const_expressions_mutator,
1230                                                                                                 (void *) active_fns);
1231                 /*
1232                  * Need to get OID of underlying function.  Okay to scribble on
1233                  * input to this extent.
1234                  */
1235                 set_opfuncid(expr);
1236                 /*
1237                  * Code for op/func reduction is pretty bulky, so split it out
1238                  * as a separate function.
1239                  */
1240                 simple = simplify_function(expr->opfuncid, args, true, active_fns);
1241                 if (simple)                             /* successfully simplified it */
1242                         return (Node *) simple;
1243                 /*
1244                  * The expression cannot be simplified any further, so build and
1245                  * return a replacement OpExpr node using the possibly-simplified
1246                  * arguments.
1247                  */
1248                 newexpr = makeNode(OpExpr);
1249                 newexpr->opno = expr->opno;
1250                 newexpr->opfuncid = expr->opfuncid;
1251                 newexpr->opresulttype = expr->opresulttype;
1252                 newexpr->opretset = expr->opretset;
1253                 newexpr->args = args;
1254                 return (Node *) newexpr;
1255         }
1256         if (IsA(node, DistinctExpr))
1257         {
1258                 DistinctExpr *expr = (DistinctExpr *) node;
1259                 List       *args;
1260                 List       *arg;
1261                 bool            has_null_input = false;
1262                 bool            all_null_input = true;
1263                 bool            has_nonconst_input = false;
1264                 Expr       *simple;
1265                 DistinctExpr *newexpr;
1266
1267                 /*
1268                  * Reduce constants in the DistinctExpr's arguments.  We know args is
1269                  * either NIL or a List node, so we can call
1270                  * expression_tree_mutator directly rather than recursing to self.
1271                  */
1272                 args = (List *) expression_tree_mutator((Node *) expr->args,
1273                                                                                   eval_const_expressions_mutator,
1274                                                                                                 (void *) active_fns);
1275
1276                 /*
1277                  * We must do our own check for NULLs because
1278                  * DistinctExpr has different results for NULL input
1279                  * than the underlying operator does.
1280                  */
1281                 foreach(arg, args)
1282                 {
1283                         if (IsA(lfirst(arg), Const))
1284                         {
1285                                 has_null_input |= ((Const *) lfirst(arg))->constisnull;
1286                                 all_null_input &= ((Const *) lfirst(arg))->constisnull;
1287                         }
1288                         else
1289                                 has_nonconst_input = true;
1290                 }
1291
1292                 /* all constants? then can optimize this out */
1293                 if (!has_nonconst_input)
1294                 {
1295                         /* all nulls? then not distinct */
1296                         if (all_null_input)
1297                                 return MAKEBOOLCONST(false, false);
1298
1299                         /* one null? then distinct */
1300                         if (has_null_input)
1301                                 return MAKEBOOLCONST(true, false);
1302
1303                         /* otherwise try to evaluate the '=' operator */
1304                         /* (NOT okay to try to inline it, though!) */
1305
1306                         /*
1307                          * Need to get OID of underlying function.  Okay to scribble on
1308                          * input to this extent.
1309                          */
1310                         set_opfuncid((OpExpr *) expr); /* rely on struct equivalence */
1311                         /*
1312                          * Code for op/func reduction is pretty bulky, so split it out
1313                          * as a separate function.
1314                          */
1315                         simple = simplify_function(expr->opfuncid, args,
1316                                                                            false, active_fns);
1317                         if (simple)                     /* successfully simplified it */
1318                                 return (Node *) simple;
1319                 }
1320
1321                 /*
1322                  * The expression cannot be simplified any further, so build and
1323                  * return a replacement DistinctExpr node using the
1324                  * possibly-simplified arguments.
1325                  */
1326                 newexpr = makeNode(DistinctExpr);
1327                 newexpr->opno = expr->opno;
1328                 newexpr->opfuncid = expr->opfuncid;
1329                 newexpr->opresulttype = expr->opresulttype;
1330                 newexpr->opretset = expr->opretset;
1331                 newexpr->args = args;
1332                 return (Node *) newexpr;
1333         }
1334         if (IsA(node, BoolExpr))
1335         {
1336                 BoolExpr   *expr = (BoolExpr *) node;
1337                 List       *args;
1338                 Const      *const_input;
1339
1340                 /*
1341                  * Reduce constants in the BoolExpr's arguments.  We know args is
1342                  * either NIL or a List node, so we can call
1343                  * expression_tree_mutator directly rather than recursing to self.
1344                  */
1345                 args = (List *) expression_tree_mutator((Node *) expr->args,
1346                                                                                   eval_const_expressions_mutator,
1347                                                                                                 (void *) active_fns);
1348
1349                 switch (expr->boolop)
1350                 {
1351                         case OR_EXPR:
1352                                 {
1353                                         /*----------
1354                                          * OR arguments are handled as follows:
1355                                          *      non constant: keep
1356                                          *      FALSE: drop (does not affect result)
1357                                          *      TRUE: force result to TRUE
1358                                          *      NULL: keep only one
1359                                          * We keep one NULL input because ExecEvalOr returns NULL
1360                                          * when no input is TRUE and at least one is NULL.
1361                                          *----------
1362                                          */
1363                                         List       *newargs = NIL;
1364                                         List       *arg;
1365                                         bool            haveNull = false;
1366                                         bool            forceTrue = false;
1367
1368                                         foreach(arg, args)
1369                                         {
1370                                                 if (!IsA(lfirst(arg), Const))
1371                                                 {
1372                                                         newargs = lappend(newargs, lfirst(arg));
1373                                                         continue;
1374                                                 }
1375                                                 const_input = (Const *) lfirst(arg);
1376                                                 if (const_input->constisnull)
1377                                                         haveNull = true;
1378                                                 else if (DatumGetBool(const_input->constvalue))
1379                                                         forceTrue = true;
1380                                                 /* otherwise, we can drop the constant-false input */
1381                                         }
1382
1383                                         /*
1384                                          * We could return TRUE before falling out of the
1385                                          * loop, but this coding method will be easier to
1386                                          * adapt if we ever add a notion of non-removable
1387                                          * functions. We'd need to check all the inputs for
1388                                          * non-removability.
1389                                          */
1390                                         if (forceTrue)
1391                                                 return MAKEBOOLCONST(true, false);
1392                                         if (haveNull)
1393                                                 newargs = lappend(newargs, MAKEBOOLCONST(false, true));
1394                                         /* If all the inputs are FALSE, result is FALSE */
1395                                         if (newargs == NIL)
1396                                                 return MAKEBOOLCONST(false, false);
1397                                         /* If only one nonconst-or-NULL input, it's the result */
1398                                         if (lnext(newargs) == NIL)
1399                                                 return (Node *) lfirst(newargs);
1400                                         /* Else we still need an OR node */
1401                                         return (Node *) make_orclause(newargs);
1402                                 }
1403                         case AND_EXPR:
1404                                 {
1405                                         /*----------
1406                                          * AND arguments are handled as follows:
1407                                          *      non constant: keep
1408                                          *      TRUE: drop (does not affect result)
1409                                          *      FALSE: force result to FALSE
1410                                          *      NULL: keep only one
1411                                          * We keep one NULL input because ExecEvalAnd returns NULL
1412                                          * when no input is FALSE and at least one is NULL.
1413                                          *----------
1414                                          */
1415                                         List       *newargs = NIL;
1416                                         List       *arg;
1417                                         bool            haveNull = false;
1418                                         bool            forceFalse = false;
1419
1420                                         foreach(arg, args)
1421                                         {
1422                                                 if (!IsA(lfirst(arg), Const))
1423                                                 {
1424                                                         newargs = lappend(newargs, lfirst(arg));
1425                                                         continue;
1426                                                 }
1427                                                 const_input = (Const *) lfirst(arg);
1428                                                 if (const_input->constisnull)
1429                                                         haveNull = true;
1430                                                 else if (!DatumGetBool(const_input->constvalue))
1431                                                         forceFalse = true;
1432                                                 /* otherwise, we can drop the constant-true input */
1433                                         }
1434
1435                                         /*
1436                                          * We could return FALSE before falling out of the
1437                                          * loop, but this coding method will be easier to
1438                                          * adapt if we ever add a notion of non-removable
1439                                          * functions. We'd need to check all the inputs for
1440                                          * non-removability.
1441                                          */
1442                                         if (forceFalse)
1443                                                 return MAKEBOOLCONST(false, false);
1444                                         if (haveNull)
1445                                                 newargs = lappend(newargs, MAKEBOOLCONST(false, true));
1446                                         /* If all the inputs are TRUE, result is TRUE */
1447                                         if (newargs == NIL)
1448                                                 return MAKEBOOLCONST(true, false);
1449                                         /* If only one nonconst-or-NULL input, it's the result */
1450                                         if (lnext(newargs) == NIL)
1451                                                 return (Node *) lfirst(newargs);
1452                                         /* Else we still need an AND node */
1453                                         return (Node *) make_andclause(newargs);
1454                                 }
1455                         case NOT_EXPR:
1456                                 Assert(length(args) == 1);
1457                                 if (IsA(lfirst(args), Const))
1458                                 {
1459                                         const_input = (Const *) lfirst(args);
1460                                         /* NOT NULL => NULL */
1461                                         if (const_input->constisnull)
1462                                                 return MAKEBOOLCONST(false, true);
1463                                         /* otherwise pretty easy */
1464                                         return MAKEBOOLCONST(!DatumGetBool(const_input->constvalue),
1465                                                                                  false);
1466                                 }
1467                                 /* Else we still need a NOT node */
1468                                 return (Node *) make_notclause(lfirst(args));
1469                         default:
1470                                 elog(ERROR, "eval_const_expressions: unexpected boolop %d",
1471                                          (int) expr->boolop);
1472                                 break;
1473                 }
1474         }
1475         if (IsA(node, SubPlanExpr))
1476         {
1477                 /*
1478                  * Return a SubPlanExpr unchanged --- too late to do anything
1479                  * with it.
1480                  *
1481                  * XXX should we elog() here instead?  Probably this routine
1482                  * should never be invoked after SubPlanExpr creation.
1483                  */
1484                 return node;
1485         }
1486         if (IsA(node, RelabelType))
1487         {
1488                 /*
1489                  * If we can simplify the input to a constant, then we don't need
1490                  * the RelabelType node anymore: just change the type field of the
1491                  * Const node.  Otherwise, must copy the RelabelType node.
1492                  */
1493                 RelabelType *relabel = (RelabelType *) node;
1494                 Node       *arg;
1495
1496                 arg = eval_const_expressions_mutator((Node *) relabel->arg,
1497                                                                                          active_fns);
1498
1499                 /*
1500                  * If we find stacked RelabelTypes (eg, from foo :: int :: oid) we
1501                  * can discard all but the top one.
1502                  */
1503                 while (arg && IsA(arg, RelabelType))
1504                         arg = (Node *) ((RelabelType *) arg)->arg;
1505
1506                 if (arg && IsA(arg, Const))
1507                 {
1508                         Const      *con = (Const *) arg;
1509
1510                         con->consttype = relabel->resulttype;
1511
1512                         /*
1513                          * relabel's resulttypmod is discarded, which is OK for now;
1514                          * if the type actually needs a runtime length coercion then
1515                          * there should be a function call to do it just above this
1516                          * node.
1517                          */
1518                         return (Node *) con;
1519                 }
1520                 else
1521                 {
1522                         RelabelType *newrelabel = makeNode(RelabelType);
1523
1524                         newrelabel->arg = (Expr *) arg;
1525                         newrelabel->resulttype = relabel->resulttype;
1526                         newrelabel->resulttypmod = relabel->resulttypmod;
1527                         return (Node *) newrelabel;
1528                 }
1529         }
1530         if (IsA(node, CaseExpr))
1531         {
1532
1533                 /*----------
1534                  * CASE expressions can be simplified if there are constant
1535                  * condition clauses:
1536                  *              FALSE (or NULL): drop the alternative
1537                  *              TRUE: drop all remaining alternatives
1538                  * If the first non-FALSE alternative is a constant TRUE, we can
1539                  * simplify the entire CASE to that alternative's expression.
1540                  * If there are no non-FALSE alternatives, we simplify the entire
1541                  * CASE to the default result (ELSE result).
1542                  *----------
1543                  */
1544                 CaseExpr   *caseexpr = (CaseExpr *) node;
1545                 CaseExpr   *newcase;
1546                 List       *newargs = NIL;
1547                 Node       *defresult;
1548                 Const      *const_input;
1549                 List       *arg;
1550
1551                 foreach(arg, caseexpr->args)
1552                 {
1553                         /* Simplify this alternative's condition and result */
1554                         CaseWhen   *casewhen = (CaseWhen *)
1555                         expression_tree_mutator((Node *) lfirst(arg),
1556                                                                         eval_const_expressions_mutator,
1557                                                                         (void *) active_fns);
1558
1559                         Assert(IsA(casewhen, CaseWhen));
1560                         if (casewhen->expr == NULL ||
1561                                 !IsA(casewhen->expr, Const))
1562                         {
1563                                 newargs = lappend(newargs, casewhen);
1564                                 continue;
1565                         }
1566                         const_input = (Const *) casewhen->expr;
1567                         if (const_input->constisnull ||
1568                                 !DatumGetBool(const_input->constvalue))
1569                                 continue;               /* drop alternative with FALSE condition */
1570
1571                         /*
1572                          * Found a TRUE condition.      If it's the first (un-dropped)
1573                          * alternative, the CASE reduces to just this alternative.
1574                          */
1575                         if (newargs == NIL)
1576                                 return (Node *) casewhen->result;
1577
1578                         /*
1579                          * Otherwise, add it to the list, and drop all the rest.
1580                          */
1581                         newargs = lappend(newargs, casewhen);
1582                         break;
1583                 }
1584
1585                 /* Simplify the default result */
1586                 defresult = eval_const_expressions_mutator((Node *) caseexpr->defresult,
1587                                                                                                    active_fns);
1588
1589                 /*
1590                  * If no non-FALSE alternatives, CASE reduces to the default
1591                  * result
1592                  */
1593                 if (newargs == NIL)
1594                         return defresult;
1595                 /* Otherwise we need a new CASE node */
1596                 newcase = makeNode(CaseExpr);
1597                 newcase->casetype = caseexpr->casetype;
1598                 newcase->arg = NULL;
1599                 newcase->args = newargs;
1600                 newcase->defresult = (Expr *) defresult;
1601                 return (Node *) newcase;
1602         }
1603
1604         /*
1605          * For any node type not handled above, we recurse using
1606          * expression_tree_mutator, which will copy the node unchanged but try
1607          * to simplify its arguments (if any) using this routine. For example:
1608          * we cannot eliminate an ArrayRef node, but we might be able to
1609          * simplify constant expressions in its subscripts.
1610          */
1611         return expression_tree_mutator(node, eval_const_expressions_mutator,
1612                                                                    (void *) active_fns);
1613 }
1614
1615 /*
1616  * Subroutine for eval_const_expressions: try to simplify a function call
1617  * (which might originally have been an operator; we don't care)
1618  *
1619  * Inputs are the function OID and the pre-simplified argument list;
1620  * also a list of already-active inline function expansions.
1621  *
1622  * Returns a simplified expression if successful, or NULL if cannot
1623  * simplify the function call.
1624  */
1625 static Expr *
1626 simplify_function(Oid funcid, List *args, bool allow_inline, List *active_fns)
1627 {
1628         HeapTuple       func_tuple;
1629         Expr       *newexpr;
1630
1631         /*
1632          * We have two strategies for simplification: either execute the function
1633          * to deliver a constant result, or expand in-line the body of the
1634          * function definition (which only works for simple SQL-language
1635          * functions, but that is a common case).  In either case we need access
1636          * to the function's pg_proc tuple, so fetch it just once to use in both
1637          * attempts.
1638          */
1639         func_tuple = SearchSysCache(PROCOID,
1640                                                                 ObjectIdGetDatum(funcid),
1641                                                                 0, 0, 0);
1642         if (!HeapTupleIsValid(func_tuple))
1643                 elog(ERROR, "Function OID %u does not exist", funcid);
1644
1645         newexpr = evaluate_function(funcid, args, func_tuple);
1646
1647         if (!newexpr && allow_inline)
1648                 newexpr = inline_function(funcid, args, func_tuple, active_fns);
1649
1650         ReleaseSysCache(func_tuple);
1651
1652         return newexpr;
1653 }
1654
1655 /*
1656  * evaluate_function: try to pre-evaluate a function call
1657  *
1658  * We can do this if the function is strict and has any constant-null inputs
1659  * (just return a null constant), or if the function is immutable and has all
1660  * constant inputs (call it and return the result as a Const node).
1661  *
1662  * Returns a simplified expression if successful, or NULL if cannot
1663  * simplify the function.
1664  */
1665 static Expr *
1666 evaluate_function(Oid funcid, List *args, HeapTuple func_tuple)
1667 {
1668         Form_pg_proc funcform = (Form_pg_proc) GETSTRUCT(func_tuple);
1669         Oid                     result_typeid = funcform->prorettype;
1670         int16           resultTypLen;
1671         bool            resultTypByVal;
1672         bool            has_nonconst_input = false;
1673         bool            has_null_input = false;
1674         FuncExpr   *newexpr;
1675         ExprContext *econtext;
1676         Datum           const_val;
1677         bool            const_is_null;
1678         List       *arg;
1679
1680         /*
1681          * Can't simplify if it returns a set.
1682          */
1683         if (funcform->proretset)
1684                 return NULL;
1685
1686         /*
1687          * Check for constant inputs and especially constant-NULL inputs.
1688          */
1689         foreach(arg, args)
1690         {
1691                 if (IsA(lfirst(arg), Const))
1692                         has_null_input |= ((Const *) lfirst(arg))->constisnull;
1693                 else
1694                         has_nonconst_input = true;
1695         }
1696
1697         /*
1698          * If the function is strict and has a constant-NULL input, it will
1699          * never be called at all, so we can replace the call by a NULL
1700          * constant, even if there are other inputs that aren't constant,
1701          * and even if the function is not otherwise immutable.
1702          */
1703         if (funcform->proisstrict && has_null_input)
1704                 return (Expr *) makeNullConst(result_typeid);
1705
1706         /*
1707          * Otherwise, can simplify only if the function is immutable and
1708          * all inputs are constants. (For a non-strict function, constant NULL
1709          * inputs are treated the same as constant non-NULL inputs.)
1710          */
1711         if (funcform->provolatile != PROVOLATILE_IMMUTABLE ||
1712                 has_nonconst_input)
1713                 return NULL;
1714
1715         /*
1716          * OK, looks like we can simplify this operator/function.
1717          *
1718          * We use the executor's routine ExecEvalExpr() to avoid duplication of
1719          * code and ensure we get the same result as the executor would get.
1720          *
1721          * Build a new FuncExpr node containing the already-simplified arguments.
1722          */
1723         newexpr = makeNode(FuncExpr);
1724         newexpr->funcid = funcid;
1725         newexpr->funcresulttype = result_typeid;
1726         newexpr->funcretset = false;
1727         newexpr->funcformat = COERCE_EXPLICIT_CALL;     /* doesn't matter */
1728         newexpr->args = args;
1729
1730         /* Get info needed about result datatype */
1731         get_typlenbyval(result_typeid, &resultTypLen, &resultTypByVal);
1732
1733         /*
1734          * It is OK to use a dummy econtext because none of the
1735          * ExecEvalExpr() code used in this situation will use econtext.  That
1736          * might seem fortuitous, but it's not so unreasonable --- a constant
1737          * expression does not depend on context, by definition, n'est ce pas?
1738          */
1739         econtext = MakeExprContext(NULL, CurrentMemoryContext);
1740
1741         const_val = ExecEvalExprSwitchContext((Node *) newexpr, econtext,
1742                                                                                   &const_is_null, NULL);
1743
1744         /* Must copy result out of sub-context used by expression eval */
1745         if (!const_is_null)
1746                 const_val = datumCopy(const_val, resultTypByVal, resultTypLen);
1747
1748         FreeExprContext(econtext);
1749         pfree(newexpr);
1750
1751         /*
1752          * Make the constant result node.
1753          */
1754         return (Expr *) makeConst(result_typeid, resultTypLen,
1755                                                           const_val, const_is_null,
1756                                                           resultTypByVal);
1757 }
1758
1759 /*
1760  * inline_function: try to expand a function call inline
1761  *
1762  * If the function is a sufficiently simple SQL-language function
1763  * (just "SELECT expression"), then we can inline it and avoid the rather
1764  * high per-call overhead of SQL functions.  Furthermore, this can expose
1765  * opportunities for constant-folding within the function expression.
1766  *
1767  * We have to beware of some special cases however.  A directly or
1768  * indirectly recursive function would cause us to recurse forever,
1769  * so we keep track of which functions we are already expanding and
1770  * do not re-expand them.  Also, if a parameter is used more than once
1771  * in the SQL-function body, we require it not to contain any volatile
1772  * functions or sublinks --- volatiles might deliver inconsistent answers,
1773  * and subplans might be unreasonably expensive to evaluate multiple times.
1774  * We must also beware of changing the volatility or strictness status of
1775  * functions by inlining them.
1776  *
1777  * Returns a simplified expression if successful, or NULL if cannot
1778  * simplify the function.
1779  */
1780 static Expr *
1781 inline_function(Oid funcid, List *args, HeapTuple func_tuple,
1782                                 List *active_fns)
1783 {
1784         Form_pg_proc funcform = (Form_pg_proc) GETSTRUCT(func_tuple);
1785         Oid                     result_typeid = funcform->prorettype;
1786         char            result_typtype;
1787         char       *src;
1788         Datum           tmp;
1789         bool            isNull;
1790         MemoryContext oldcxt;
1791         MemoryContext mycxt;
1792         StringInfoData stri;
1793         List       *raw_parsetree_list;
1794         List       *querytree_list;
1795         Query      *querytree;
1796         Node       *newexpr;
1797         int                *usecounts;
1798         List       *arg;
1799         int                     i;
1800
1801         /*
1802          * Forget it if the function is not SQL-language or has other
1803          * showstopper properties.  (The nargs check is just paranoia.)
1804          */
1805         if (funcform->prolang != SQLlanguageId ||
1806                 funcform->prosecdef ||
1807                 funcform->proretset ||
1808                 funcform->pronargs != length(args))
1809                 return NULL;
1810
1811         /* Forget it if return type is tuple or void */
1812         result_typtype = get_typtype(result_typeid);
1813         if (result_typtype != 'b' &&
1814                 result_typtype != 'd')
1815                 return NULL;
1816
1817         /* Check for recursive function, and give up trying to expand if so */
1818         if (intMember(funcid, active_fns))
1819                 return NULL;
1820
1821         /* Check permission to call function (fail later, if not) */
1822         if (pg_proc_aclcheck(funcid, GetUserId(), ACL_EXECUTE) != ACLCHECK_OK)
1823                 return NULL;
1824
1825         /*
1826          * Make a temporary memory context, so that we don't leak all the
1827          * stuff that parsing might create.
1828          */
1829         mycxt = AllocSetContextCreate(CurrentMemoryContext,
1830                                                                   "inline_function",
1831                                                                   ALLOCSET_DEFAULT_MINSIZE,
1832                                                                   ALLOCSET_DEFAULT_INITSIZE,
1833                                                                   ALLOCSET_DEFAULT_MAXSIZE);
1834         oldcxt = MemoryContextSwitchTo(mycxt);
1835
1836         /* Fetch and parse the function body */
1837         tmp = SysCacheGetAttr(PROCOID,
1838                                                   func_tuple,
1839                                                   Anum_pg_proc_prosrc,
1840                                                   &isNull);
1841         if (isNull)
1842                 elog(ERROR, "inline_function: null prosrc for procedure %u",
1843                          funcid);
1844         src = DatumGetCString(DirectFunctionCall1(textout, tmp));
1845
1846         /*
1847          * We just do parsing and parse analysis, not rewriting, because
1848          * rewriting will not affect SELECT-only queries, which is all that
1849          * we care about.  Also, we can punt as soon as we detect more than
1850          * one command in the function body.
1851          */
1852         initStringInfo(&stri);
1853         appendStringInfo(&stri, "%s", src);
1854
1855         raw_parsetree_list = pg_parse_query(&stri,
1856                                                                                 funcform->proargtypes,
1857                                                                                 funcform->pronargs);
1858         if (length(raw_parsetree_list) != 1)
1859                 goto fail;
1860
1861         querytree_list = parse_analyze(lfirst(raw_parsetree_list), NULL);
1862
1863         if (length(querytree_list) != 1)
1864                 goto fail;
1865
1866         querytree = (Query *) lfirst(querytree_list);
1867
1868         /*
1869          * The single command must be a simple "SELECT expression".
1870          */
1871         if (!IsA(querytree, Query) ||
1872                 querytree->commandType != CMD_SELECT ||
1873                 querytree->resultRelation != 0 ||
1874                 querytree->into ||
1875                 querytree->isPortal ||
1876                 querytree->hasAggs ||
1877                 querytree->hasSubLinks ||
1878                 querytree->rtable ||
1879                 querytree->jointree->fromlist ||
1880                 querytree->jointree->quals ||
1881                 querytree->groupClause ||
1882                 querytree->havingQual ||
1883                 querytree->distinctClause ||
1884                 querytree->sortClause ||
1885                 querytree->limitOffset ||
1886                 querytree->limitCount ||
1887                 querytree->setOperations ||
1888                 length(querytree->targetList) != 1)
1889                 goto fail;
1890
1891         newexpr = (Node *) ((TargetEntry *) lfirst(querytree->targetList))->expr;
1892
1893         /*
1894          * Additional validity checks on the expression.  It mustn't return a
1895          * set, and it mustn't be more volatile than the surrounding function
1896          * (this is to avoid breaking hacks that involve pretending a function
1897          * is immutable when it really ain't).  If the surrounding function is
1898          * declared strict, then the expression must contain only strict constructs
1899          * and must use all of the function parameters (this is overkill, but
1900          * an exact analysis is hard).
1901          */
1902         if (expression_returns_set(newexpr))
1903                 goto fail;
1904
1905         if (funcform->provolatile == PROVOLATILE_IMMUTABLE &&
1906                 contain_mutable_functions(newexpr))
1907                 goto fail;
1908         else if (funcform->provolatile == PROVOLATILE_STABLE &&
1909                 contain_volatile_functions(newexpr))
1910                 goto fail;
1911
1912         if (funcform->proisstrict &&
1913                 contain_nonstrict_functions(newexpr))
1914                 goto fail;
1915
1916         /*
1917          * We may be able to do it; there are still checks on parameter usage
1918          * to make, but those are most easily done in combination with the
1919          * actual substitution of the inputs.  So start building expression
1920          * with inputs substituted.
1921          */
1922         usecounts = (int *) palloc0((funcform->pronargs + 1) * sizeof(int));
1923         newexpr = substitute_actual_parameters(newexpr, funcform->pronargs,
1924                                                                                    args, usecounts);
1925
1926         /* Now check for parameter usage */
1927         i = 0;
1928         foreach(arg, args)
1929         {
1930                 Node   *param = lfirst(arg);
1931
1932                 if (usecounts[i] == 0)
1933                 {
1934                         /* Param not used at all: uncool if func is strict */
1935                         if (funcform->proisstrict)
1936                                 goto fail;
1937                 }
1938                 else if (usecounts[i] != 1)
1939                 {
1940                         /* Param used multiple times: uncool if volatile or expensive */
1941                         if (contain_volatile_functions(param) ||
1942                                 contain_subplans(param))
1943                                 goto fail;
1944                 }
1945                 i++;
1946         }
1947
1948         /*
1949          * Whew --- we can make the substitution.  Copy the modified expression
1950          * out of the temporary memory context, and clean up.
1951          */
1952         MemoryContextSwitchTo(oldcxt);
1953
1954         newexpr = copyObject(newexpr);
1955
1956         MemoryContextDelete(mycxt);
1957
1958         /*
1959          * Recursively try to simplify the modified expression.  Here we must
1960          * add the current function to the context list of active functions.
1961          */
1962         newexpr = eval_const_expressions_mutator(newexpr,
1963                                                                                          lconsi(funcid, active_fns));
1964
1965         return (Expr *) newexpr;
1966
1967         /* Here if func is not inlinable: release temp memory and return NULL */
1968 fail:
1969         MemoryContextSwitchTo(oldcxt);
1970         MemoryContextDelete(mycxt);
1971
1972         return NULL;
1973 }
1974
1975 /*
1976  * Replace Param nodes by appropriate actual parameters
1977  */
1978 static Node *
1979 substitute_actual_parameters(Node *expr, int nargs, List *args,
1980                                                          int *usecounts)
1981 {
1982         substitute_actual_parameters_context context;
1983
1984         context.nargs = nargs;
1985         context.args = args;
1986         context.usecounts = usecounts;
1987
1988         return substitute_actual_parameters_mutator(expr, &context);
1989 }
1990
1991 static Node *
1992 substitute_actual_parameters_mutator(Node *node,
1993                                                                          substitute_actual_parameters_context *context)
1994 {
1995         if (node == NULL)
1996                 return NULL;
1997         if (IsA(node, Param))
1998         {
1999                 Param      *param = (Param *) node;
2000
2001                 if (param->paramkind != PARAM_NUM)
2002                         elog(ERROR, "substitute_actual_parameters_mutator: unexpected paramkind");
2003                 if (param->paramid <= 0 || param->paramid > context->nargs)
2004                         elog(ERROR, "substitute_actual_parameters_mutator: unexpected paramid");
2005
2006                 /* Count usage of parameter */
2007                 context->usecounts[param->paramid - 1]++;
2008
2009                 /* Select the appropriate actual arg and replace the Param with it */
2010                 /* We don't need to copy at this time (it'll get done later) */
2011                 return nth(param->paramid - 1, context->args);
2012         }
2013         return expression_tree_mutator(node, substitute_actual_parameters_mutator,
2014                                                                    (void *) context);
2015 }
2016
2017
2018 /*
2019  * Standard expression-tree walking support
2020  *
2021  * We used to have near-duplicate code in many different routines that
2022  * understood how to recurse through an expression node tree.  That was
2023  * a pain to maintain, and we frequently had bugs due to some particular
2024  * routine neglecting to support a particular node type.  In most cases,
2025  * these routines only actually care about certain node types, and don't
2026  * care about other types except insofar as they have to recurse through
2027  * non-primitive node types.  Therefore, we now provide generic tree-walking
2028  * logic to consolidate the redundant "boilerplate" code.  There are
2029  * two versions: expression_tree_walker() and expression_tree_mutator().
2030  */
2031
2032 /*--------------------
2033  * expression_tree_walker() is designed to support routines that traverse
2034  * a tree in a read-only fashion (although it will also work for routines
2035  * that modify nodes in-place but never add/delete/replace nodes).
2036  * A walker routine should look like this:
2037  *
2038  * bool my_walker (Node *node, my_struct *context)
2039  * {
2040  *              if (node == NULL)
2041  *                      return false;
2042  *              // check for nodes that special work is required for, eg:
2043  *              if (IsA(node, Var))
2044  *              {
2045  *                      ... do special actions for Var nodes
2046  *              }
2047  *              else if (IsA(node, ...))
2048  *              {
2049  *                      ... do special actions for other node types
2050  *              }
2051  *              // for any node type not specially processed, do:
2052  *              return expression_tree_walker(node, my_walker, (void *) context);
2053  * }
2054  *
2055  * The "context" argument points to a struct that holds whatever context
2056  * information the walker routine needs --- it can be used to return data
2057  * gathered by the walker, too.  This argument is not touched by
2058  * expression_tree_walker, but it is passed down to recursive sub-invocations
2059  * of my_walker.  The tree walk is started from a setup routine that
2060  * fills in the appropriate context struct, calls my_walker with the top-level
2061  * node of the tree, and then examines the results.
2062  *
2063  * The walker routine should return "false" to continue the tree walk, or
2064  * "true" to abort the walk and immediately return "true" to the top-level
2065  * caller.      This can be used to short-circuit the traversal if the walker
2066  * has found what it came for.  "false" is returned to the top-level caller
2067  * iff no invocation of the walker returned "true".
2068  *
2069  * The node types handled by expression_tree_walker include all those
2070  * normally found in target lists and qualifier clauses during the planning
2071  * stage.  In particular, it handles List nodes since a cnf-ified qual clause
2072  * will have List structure at the top level, and it handles TargetEntry nodes
2073  * so that a scan of a target list can be handled without additional code.
2074  * (But only the "expr" part of a TargetEntry is examined, unless the walker
2075  * chooses to process TargetEntry nodes specially.)  Also, RangeTblRef,
2076  * FromExpr, JoinExpr, and SetOperationStmt nodes are handled, so that query
2077  * jointrees and setOperation trees can be processed without additional code.
2078  *
2079  * expression_tree_walker will handle SubLink and SubPlanExpr nodes by
2080  * recursing normally into the "lefthand" arguments (which are expressions
2081  * belonging to the outer plan).  It will also call the walker on the
2082  * sub-Query node; however, when expression_tree_walker itself is called on a
2083  * Query node, it does nothing and returns "false".  The net effect is that
2084  * unless the walker does something special at a Query node, sub-selects will
2085  * not be visited during an expression tree walk. This is exactly the behavior
2086  * wanted in many cases --- and for those walkers that do want to recurse into
2087  * sub-selects, special behavior is typically needed anyway at the entry to a
2088  * sub-select (such as incrementing a depth counter). A walker that wants to
2089  * examine sub-selects should include code along the lines of:
2090  *
2091  *              if (IsA(node, Query))
2092  *              {
2093  *                      adjust context for subquery;
2094  *                      result = query_tree_walker((Query *) node, my_walker, context,
2095  *                                                                         0); // to visit rtable items too
2096  *                      restore context if needed;
2097  *                      return result;
2098  *              }
2099  *
2100  * query_tree_walker is a convenience routine (see below) that calls the
2101  * walker on all the expression subtrees of the given Query node.
2102  *
2103  * NOTE: currently, because make_subplan() clears the subselect link in
2104  * a SubLink node, it is not actually possible to recurse into subselects
2105  * of an already-planned expression tree.  This is OK for current uses,
2106  * but ought to be cleaned up when we redesign querytree processing.
2107  *--------------------
2108  */
2109
2110 bool
2111 expression_tree_walker(Node *node,
2112                                            bool (*walker) (),
2113                                            void *context)
2114 {
2115         List       *temp;
2116
2117         /*
2118          * The walker has already visited the current node, and so we need
2119          * only recurse into any sub-nodes it has.
2120          *
2121          * We assume that the walker is not interested in List nodes per se, so
2122          * when we expect a List we just recurse directly to self without
2123          * bothering to call the walker.
2124          */
2125         if (node == NULL)
2126                 return false;
2127         switch (nodeTag(node))
2128         {
2129                 case T_Var:
2130                 case T_Const:
2131                 case T_Param:
2132                 case T_RangeTblRef:
2133                         /* primitive node types with no subnodes */
2134                         break;
2135                 case T_Aggref:
2136                         return walker(((Aggref *) node)->target, context);
2137                 case T_ArrayRef:
2138                         {
2139                                 ArrayRef   *aref = (ArrayRef *) node;
2140
2141                                 /* recurse directly for upper/lower array index lists */
2142                                 if (expression_tree_walker((Node *) aref->refupperindexpr,
2143                                                                                    walker, context))
2144                                         return true;
2145                                 if (expression_tree_walker((Node *) aref->reflowerindexpr,
2146                                                                                    walker, context))
2147                                         return true;
2148                                 /* walker must see the refexpr and refassgnexpr, however */
2149                                 if (walker(aref->refexpr, context))
2150                                         return true;
2151                                 if (walker(aref->refassgnexpr, context))
2152                                         return true;
2153                         }
2154                         break;
2155                 case T_FuncExpr:
2156                         {
2157                                 FuncExpr   *expr = (FuncExpr *) node;
2158
2159                                 if (expression_tree_walker((Node *) expr->args,
2160                                                                                    walker, context))
2161                                         return true;
2162                         }
2163                         break;
2164                 case T_OpExpr:
2165                         {
2166                                 OpExpr     *expr = (OpExpr *) node;
2167
2168                                 if (expression_tree_walker((Node *) expr->args,
2169                                                                                    walker, context))
2170                                         return true;
2171                         }
2172                         break;
2173                 case T_DistinctExpr:
2174                         {
2175                                 DistinctExpr *expr = (DistinctExpr *) node;
2176
2177                                 if (expression_tree_walker((Node *) expr->args,
2178                                                                                    walker, context))
2179                                         return true;
2180                         }
2181                         break;
2182                 case T_BoolExpr:
2183                         {
2184                                 BoolExpr   *expr = (BoolExpr *) node;
2185
2186                                 if (expression_tree_walker((Node *) expr->args,
2187                                                                                    walker, context))
2188                                         return true;
2189                         }
2190                         break;
2191                 case T_SubLink:
2192                         {
2193                                 SubLink    *sublink = (SubLink *) node;
2194
2195                                 /*
2196                                  * If the SubLink has already been processed by
2197                                  * subselect.c, it will have lefthand=NIL, and we need to
2198                                  * scan the oper list.  Otherwise we only need to look at
2199                                  * the lefthand list (the incomplete OpExpr nodes in the
2200                                  * oper list are deemed uninteresting, perhaps even
2201                                  * confusing).
2202                                  */
2203                                 if (sublink->lefthand)
2204                                 {
2205                                         if (walker((Node *) sublink->lefthand, context))
2206                                                 return true;
2207                                 }
2208                                 else
2209                                 {
2210                                         if (walker((Node *) sublink->oper, context))
2211                                                 return true;
2212                                 }
2213
2214                                 /*
2215                                  * Also invoke the walker on the sublink's Query node, so
2216                                  * it can recurse into the sub-query if it wants to.
2217                                  */
2218                                 return walker(sublink->subselect, context);
2219                         }
2220                         break;
2221                 case T_SubPlanExpr:
2222                         {
2223                                 SubPlanExpr *expr = (SubPlanExpr *) node;
2224
2225                                 /* recurse to the SubLink node, but not into the Plan */
2226                                 if (walker((Node *) expr->sublink, context))
2227                                         return true;
2228                                 /* also examine args list */
2229                                 if (expression_tree_walker((Node *) expr->args,
2230                                                                                    walker, context))
2231                                         return true;
2232                         }
2233                         break;
2234                 case T_FieldSelect:
2235                         return walker(((FieldSelect *) node)->arg, context);
2236                 case T_RelabelType:
2237                         return walker(((RelabelType *) node)->arg, context);
2238                 case T_CaseExpr:
2239                         {
2240                                 CaseExpr   *caseexpr = (CaseExpr *) node;
2241
2242                                 /* we assume walker doesn't care about CaseWhens, either */
2243                                 foreach(temp, caseexpr->args)
2244                                 {
2245                                         CaseWhen   *when = (CaseWhen *) lfirst(temp);
2246
2247                                         Assert(IsA(when, CaseWhen));
2248                                         if (walker(when->expr, context))
2249                                                 return true;
2250                                         if (walker(when->result, context))
2251                                                 return true;
2252                                 }
2253                                 /* caseexpr->arg should be null, but we'll check it anyway */
2254                                 if (walker(caseexpr->arg, context))
2255                                         return true;
2256                                 if (walker(caseexpr->defresult, context))
2257                                         return true;
2258                         }
2259                         break;
2260                 case T_NullTest:
2261                         return walker(((NullTest *) node)->arg, context);
2262                 case T_BooleanTest:
2263                         return walker(((BooleanTest *) node)->arg, context);
2264                 case T_ConstraintTest:
2265                         if (walker(((ConstraintTest *) node)->arg, context))
2266                                 return true;
2267                         return walker(((ConstraintTest *) node)->check_expr, context);
2268                 case T_ConstraintTestValue:
2269                         break;
2270                 case T_TargetEntry:
2271                         return walker(((TargetEntry *) node)->expr, context);
2272                 case T_Query:
2273                         /* Do nothing with a sub-Query, per discussion above */
2274                         break;
2275                 case T_List:
2276                         foreach(temp, (List *) node)
2277                         {
2278                                 if (walker((Node *) lfirst(temp), context))
2279                                         return true;
2280                         }
2281                         break;
2282                 case T_FromExpr:
2283                         {
2284                                 FromExpr   *from = (FromExpr *) node;
2285
2286                                 if (walker(from->fromlist, context))
2287                                         return true;
2288                                 if (walker(from->quals, context))
2289                                         return true;
2290                         }
2291                         break;
2292                 case T_JoinExpr:
2293                         {
2294                                 JoinExpr   *join = (JoinExpr *) node;
2295
2296                                 if (walker(join->larg, context))
2297                                         return true;
2298                                 if (walker(join->rarg, context))
2299                                         return true;
2300                                 if (walker(join->quals, context))
2301                                         return true;
2302
2303                                 /*
2304                                  * alias clause, using list are deemed uninteresting.
2305                                  */
2306                         }
2307                         break;
2308                 case T_SetOperationStmt:
2309                         {
2310                                 SetOperationStmt *setop = (SetOperationStmt *) node;
2311
2312                                 if (walker(setop->larg, context))
2313                                         return true;
2314                                 if (walker(setop->rarg, context))
2315                                         return true;
2316                         }
2317                         break;
2318                 default:
2319                         elog(ERROR, "expression_tree_walker: Unexpected node type %d",
2320                                  nodeTag(node));
2321                         break;
2322         }
2323         return false;
2324 }
2325
2326 /*
2327  * query_tree_walker --- initiate a walk of a Query's expressions
2328  *
2329  * This routine exists just to reduce the number of places that need to know
2330  * where all the expression subtrees of a Query are.  Note it can be used
2331  * for starting a walk at top level of a Query regardless of whether the
2332  * walker intends to descend into subqueries.  It is also useful for
2333  * descending into subqueries within a walker.
2334  *
2335  * Some callers want to suppress visitation of certain items in the sub-Query,
2336  * typically because they need to process them specially, or don't actually
2337  * want to recurse into subqueries.  This is supported by the flags argument,
2338  * which is the bitwise OR of flag values to suppress visitation of
2339  * indicated items.  (More flag bits may be added as needed.)
2340  */
2341 bool
2342 query_tree_walker(Query *query,
2343                                   bool (*walker) (),
2344                                   void *context,
2345                                   int flags)
2346 {
2347         List       *rt;
2348
2349         Assert(query != NULL && IsA(query, Query));
2350
2351         if (walker((Node *) query->targetList, context))
2352                 return true;
2353         if (walker((Node *) query->jointree, context))
2354                 return true;
2355         if (walker(query->setOperations, context))
2356                 return true;
2357         if (walker(query->havingQual, context))
2358                 return true;
2359         foreach(rt, query->rtable)
2360         {
2361                 RangeTblEntry *rte = (RangeTblEntry *) lfirst(rt);
2362
2363                 switch (rte->rtekind)
2364                 {
2365                         case RTE_RELATION:
2366                         case RTE_SPECIAL:
2367                                 /* nothing to do */
2368                                 break;
2369                         case RTE_SUBQUERY:
2370                                 if (! (flags & QTW_IGNORE_SUBQUERIES))
2371                                         if (walker(rte->subquery, context))
2372                                                 return true;
2373                                 break;
2374                         case RTE_JOIN:
2375                                 if (! (flags & QTW_IGNORE_JOINALIASES))
2376                                         if (walker(rte->joinaliasvars, context))
2377                                                 return true;
2378                                 break;
2379                         case RTE_FUNCTION:
2380                                 if (walker(rte->funcexpr, context))
2381                                         return true;
2382                                 break;
2383                 }
2384         }
2385         return false;
2386 }
2387
2388
2389 /*--------------------
2390  * expression_tree_mutator() is designed to support routines that make a
2391  * modified copy of an expression tree, with some nodes being added,
2392  * removed, or replaced by new subtrees.  The original tree is (normally)
2393  * not changed.  Each recursion level is responsible for returning a copy of
2394  * (or appropriately modified substitute for) the subtree it is handed.
2395  * A mutator routine should look like this:
2396  *
2397  * Node * my_mutator (Node *node, my_struct *context)
2398  * {
2399  *              if (node == NULL)
2400  *                      return NULL;
2401  *              // check for nodes that special work is required for, eg:
2402  *              if (IsA(node, Var))
2403  *              {
2404  *                      ... create and return modified copy of Var node
2405  *              }
2406  *              else if (IsA(node, ...))
2407  *              {
2408  *                      ... do special transformations of other node types
2409  *              }
2410  *              // for any node type not specially processed, do:
2411  *              return expression_tree_mutator(node, my_mutator, (void *) context);
2412  * }
2413  *
2414  * The "context" argument points to a struct that holds whatever context
2415  * information the mutator routine needs --- it can be used to return extra
2416  * data gathered by the mutator, too.  This argument is not touched by
2417  * expression_tree_mutator, but it is passed down to recursive sub-invocations
2418  * of my_mutator.  The tree walk is started from a setup routine that
2419  * fills in the appropriate context struct, calls my_mutator with the
2420  * top-level node of the tree, and does any required post-processing.
2421  *
2422  * Each level of recursion must return an appropriately modified Node.
2423  * If expression_tree_mutator() is called, it will make an exact copy
2424  * of the given Node, but invoke my_mutator() to copy the sub-node(s)
2425  * of that Node.  In this way, my_mutator() has full control over the
2426  * copying process but need not directly deal with expression trees
2427  * that it has no interest in.
2428  *
2429  * Just as for expression_tree_walker, the node types handled by
2430  * expression_tree_mutator include all those normally found in target lists
2431  * and qualifier clauses during the planning stage.
2432  *
2433  * expression_tree_mutator will handle a SubPlanExpr node by recursing into
2434  * the args and sublink->oper lists (which belong to the outer plan), but it
2435  * will simply copy the link to the inner plan, since that's typically what
2436  * expression tree mutators want.  A mutator that wants to modify the subplan
2437  * can force appropriate behavior by recognizing subplan expression nodes
2438  * and doing the right thing.
2439  *
2440  * Bare SubLink nodes (without a SubPlanExpr) are handled by recursing into
2441  * the "lefthand" argument list only.  (A bare SubLink should be seen only if
2442  * the tree has not yet been processed by subselect.c.)  Again, this can be
2443  * overridden by the mutator, but it seems to be the most useful default
2444  * behavior.
2445  *--------------------
2446  */
2447
2448 Node *
2449 expression_tree_mutator(Node *node,
2450                                                 Node *(*mutator) (),
2451                                                 void *context)
2452 {
2453         /*
2454          * The mutator has already decided not to modify the current node, but
2455          * we must call the mutator for any sub-nodes.
2456          */
2457
2458 #define FLATCOPY(newnode, node, nodetype)  \
2459         ( (newnode) = makeNode(nodetype), \
2460           memcpy((newnode), (node), sizeof(nodetype)) )
2461
2462 #define CHECKFLATCOPY(newnode, node, nodetype)  \
2463         ( AssertMacro(IsA((node), nodetype)), \
2464           (newnode) = makeNode(nodetype), \
2465           memcpy((newnode), (node), sizeof(nodetype)) )
2466
2467 #define MUTATE(newfield, oldfield, fieldtype)  \
2468                 ( (newfield) = (fieldtype) mutator((Node *) (oldfield), context) )
2469
2470         if (node == NULL)
2471                 return NULL;
2472         switch (nodeTag(node))
2473         {
2474                 case T_Var:
2475                 case T_Const:
2476                 case T_Param:
2477                 case T_RangeTblRef:
2478                         /* primitive node types with no subnodes */
2479                         return (Node *) copyObject(node);
2480                 case T_Aggref:
2481                         {
2482                                 Aggref     *aggref = (Aggref *) node;
2483                                 Aggref     *newnode;
2484
2485                                 FLATCOPY(newnode, aggref, Aggref);
2486                                 MUTATE(newnode->target, aggref->target, Expr *);
2487                                 return (Node *) newnode;
2488                         }
2489                         break;
2490                 case T_ArrayRef:
2491                         {
2492                                 ArrayRef   *arrayref = (ArrayRef *) node;
2493                                 ArrayRef   *newnode;
2494
2495                                 FLATCOPY(newnode, arrayref, ArrayRef);
2496                                 MUTATE(newnode->refupperindexpr, arrayref->refupperindexpr,
2497                                            List *);
2498                                 MUTATE(newnode->reflowerindexpr, arrayref->reflowerindexpr,
2499                                            List *);
2500                                 MUTATE(newnode->refexpr, arrayref->refexpr,
2501                                            Expr *);
2502                                 MUTATE(newnode->refassgnexpr, arrayref->refassgnexpr,
2503                                            Expr *);
2504                                 return (Node *) newnode;
2505                         }
2506                         break;
2507                 case T_FuncExpr:
2508                         {
2509                                 FuncExpr   *expr = (FuncExpr *) node;
2510                                 FuncExpr   *newnode;
2511
2512                                 FLATCOPY(newnode, expr, FuncExpr);
2513                                 MUTATE(newnode->args, expr->args, List *);
2514                                 return (Node *) newnode;
2515                         }
2516                         break;
2517                 case T_OpExpr:
2518                         {
2519                                 OpExpr     *expr = (OpExpr *) node;
2520                                 OpExpr     *newnode;
2521
2522                                 FLATCOPY(newnode, expr, OpExpr);
2523                                 MUTATE(newnode->args, expr->args, List *);
2524                                 return (Node *) newnode;
2525                         }
2526                         break;
2527                 case T_DistinctExpr:
2528                         {
2529                                 DistinctExpr   *expr = (DistinctExpr *) node;
2530                                 DistinctExpr   *newnode;
2531
2532                                 FLATCOPY(newnode, expr, DistinctExpr);
2533                                 MUTATE(newnode->args, expr->args, List *);
2534                                 return (Node *) newnode;
2535                         }
2536                         break;
2537                 case T_BoolExpr:
2538                         {
2539                                 BoolExpr   *expr = (BoolExpr *) node;
2540                                 BoolExpr   *newnode;
2541
2542                                 FLATCOPY(newnode, expr, BoolExpr);
2543                                 MUTATE(newnode->args, expr->args, List *);
2544                                 return (Node *) newnode;
2545                         }
2546                         break;
2547                 case T_SubLink:
2548                         {
2549                                 /*
2550                                  * A "bare" SubLink (note we will not come here if we
2551                                  * found a SubPlanExpr node above it).  Transform the
2552                                  * lefthand side, but not the oper list nor the subquery.
2553                                  */
2554                                 SubLink    *sublink = (SubLink *) node;
2555                                 SubLink    *newnode;
2556
2557                                 FLATCOPY(newnode, sublink, SubLink);
2558                                 MUTATE(newnode->lefthand, sublink->lefthand, List *);
2559                                 return (Node *) newnode;
2560                         }
2561                         break;
2562                 case T_SubPlanExpr:
2563                         {
2564                                 SubPlanExpr   *expr = (SubPlanExpr *) node;
2565                                 SubLink           *oldsublink = expr->sublink;
2566                                 SubPlanExpr   *newnode;
2567
2568                                 FLATCOPY(newnode, expr, SubPlanExpr);
2569                                 /* flat-copy the SubLink node */
2570                                 CHECKFLATCOPY(newnode->sublink, oldsublink, SubLink);
2571                                 /* transform args list (params to be passed to subplan) */
2572                                 MUTATE(newnode->args, expr->args, List *);
2573                                 /* transform sublink's oper list as well */
2574                                 MUTATE(newnode->sublink->oper, oldsublink->oper, List *);
2575                                 /* but not the subplan itself, which is referenced as-is */
2576                                 return (Node *) newnode;
2577                         }
2578                         break;
2579                 case T_FieldSelect:
2580                         {
2581                                 FieldSelect *fselect = (FieldSelect *) node;
2582                                 FieldSelect *newnode;
2583
2584                                 FLATCOPY(newnode, fselect, FieldSelect);
2585                                 MUTATE(newnode->arg, fselect->arg, Expr *);
2586                                 return (Node *) newnode;
2587                         }
2588                         break;
2589                 case T_RelabelType:
2590                         {
2591                                 RelabelType *relabel = (RelabelType *) node;
2592                                 RelabelType *newnode;
2593
2594                                 FLATCOPY(newnode, relabel, RelabelType);
2595                                 MUTATE(newnode->arg, relabel->arg, Expr *);
2596                                 return (Node *) newnode;
2597                         }
2598                         break;
2599                 case T_CaseExpr:
2600                         {
2601                                 CaseExpr   *caseexpr = (CaseExpr *) node;
2602                                 CaseExpr   *newnode;
2603
2604                                 FLATCOPY(newnode, caseexpr, CaseExpr);
2605                                 MUTATE(newnode->args, caseexpr->args, List *);
2606                                 /* caseexpr->arg should be null, but we'll check it anyway */
2607                                 MUTATE(newnode->arg, caseexpr->arg, Expr *);
2608                                 MUTATE(newnode->defresult, caseexpr->defresult, Expr *);
2609                                 return (Node *) newnode;
2610                         }
2611                         break;
2612                 case T_CaseWhen:
2613                         {
2614                                 CaseWhen   *casewhen = (CaseWhen *) node;
2615                                 CaseWhen   *newnode;
2616
2617                                 FLATCOPY(newnode, casewhen, CaseWhen);
2618                                 MUTATE(newnode->expr, casewhen->expr, Expr *);
2619                                 MUTATE(newnode->result, casewhen->result, Expr *);
2620                                 return (Node *) newnode;
2621                         }
2622                         break;
2623                 case T_NullTest:
2624                         {
2625                                 NullTest   *ntest = (NullTest *) node;
2626                                 NullTest   *newnode;
2627
2628                                 FLATCOPY(newnode, ntest, NullTest);
2629                                 MUTATE(newnode->arg, ntest->arg, Expr *);
2630                                 return (Node *) newnode;
2631                         }
2632                         break;
2633                 case T_BooleanTest:
2634                         {
2635                                 BooleanTest *btest = (BooleanTest *) node;
2636                                 BooleanTest *newnode;
2637
2638                                 FLATCOPY(newnode, btest, BooleanTest);
2639                                 MUTATE(newnode->arg, btest->arg, Expr *);
2640                                 return (Node *) newnode;
2641                         }
2642                         break;
2643                 case T_ConstraintTest:
2644                         {
2645                                 ConstraintTest *ctest = (ConstraintTest *) node;
2646                                 ConstraintTest *newnode;
2647
2648                                 FLATCOPY(newnode, ctest, ConstraintTest);
2649                                 MUTATE(newnode->arg, ctest->arg, Expr *);
2650                                 MUTATE(newnode->check_expr, ctest->check_expr, Expr *);
2651                                 return (Node *) newnode;
2652                         }
2653                         break;
2654                 case T_ConstraintTestValue:
2655                         {
2656                                 ConstraintTestValue *ctest = (ConstraintTestValue *) node;
2657                                 ConstraintTestValue *newnode;
2658
2659                                 FLATCOPY(newnode, ctest, ConstraintTestValue);
2660                                 return (Node *) newnode;
2661                         }
2662                         break;
2663                 case T_TargetEntry:
2664                         {
2665                                 /*
2666                                  * We mutate the expression, but not the resdom, by
2667                                  * default.
2668                                  */
2669                                 TargetEntry *targetentry = (TargetEntry *) node;
2670                                 TargetEntry *newnode;
2671
2672                                 FLATCOPY(newnode, targetentry, TargetEntry);
2673                                 MUTATE(newnode->expr, targetentry->expr, Expr *);
2674                                 return (Node *) newnode;
2675                         }
2676                         break;
2677                 case T_List:
2678                         {
2679                                 /*
2680                                  * We assume the mutator isn't interested in the list
2681                                  * nodes per se, so just invoke it on each list element.
2682                                  * NOTE: this would fail badly on a list with integer
2683                                  * elements!
2684                                  */
2685                                 List       *resultlist = NIL;
2686                                 List       *temp;
2687
2688                                 foreach(temp, (List *) node)
2689                                 {
2690                                         resultlist = lappend(resultlist,
2691                                                                                  mutator((Node *) lfirst(temp),
2692                                                                                                  context));
2693                                 }
2694                                 return (Node *) resultlist;
2695                         }
2696                         break;
2697                 case T_FromExpr:
2698                         {
2699                                 FromExpr   *from = (FromExpr *) node;
2700                                 FromExpr   *newnode;
2701
2702                                 FLATCOPY(newnode, from, FromExpr);
2703                                 MUTATE(newnode->fromlist, from->fromlist, List *);
2704                                 MUTATE(newnode->quals, from->quals, Node *);
2705                                 return (Node *) newnode;
2706                         }
2707                         break;
2708                 case T_JoinExpr:
2709                         {
2710                                 JoinExpr   *join = (JoinExpr *) node;
2711                                 JoinExpr   *newnode;
2712
2713                                 FLATCOPY(newnode, join, JoinExpr);
2714                                 MUTATE(newnode->larg, join->larg, Node *);
2715                                 MUTATE(newnode->rarg, join->rarg, Node *);
2716                                 MUTATE(newnode->quals, join->quals, Node *);
2717                                 /* We do not mutate alias or using by default */
2718                                 return (Node *) newnode;
2719                         }
2720                         break;
2721                 case T_SetOperationStmt:
2722                         {
2723                                 SetOperationStmt *setop = (SetOperationStmt *) node;
2724                                 SetOperationStmt *newnode;
2725
2726                                 FLATCOPY(newnode, setop, SetOperationStmt);
2727                                 MUTATE(newnode->larg, setop->larg, Node *);
2728                                 MUTATE(newnode->rarg, setop->rarg, Node *);
2729                                 return (Node *) newnode;
2730                         }
2731                         break;
2732                 default:
2733                         elog(ERROR, "expression_tree_mutator: Unexpected node type %d",
2734                                  nodeTag(node));
2735                         break;
2736         }
2737         /* can't get here, but keep compiler happy */
2738         return NULL;
2739 }
2740
2741
2742 /*
2743  * query_tree_mutator --- initiate modification of a Query's expressions
2744  *
2745  * This routine exists just to reduce the number of places that need to know
2746  * where all the expression subtrees of a Query are.  Note it can be used
2747  * for starting a walk at top level of a Query regardless of whether the
2748  * mutator intends to descend into subqueries.  It is also useful for
2749  * descending into subqueries within a mutator.
2750  *
2751  * The specified Query node is modified-in-place; do a FLATCOPY() beforehand
2752  * if you don't want to change the original.  All substructure is safely
2753  * copied, however.
2754  *
2755  * Some callers want to suppress mutating of certain items in the sub-Query,
2756  * typically because they need to process them specially, or don't actually
2757  * want to recurse into subqueries.  This is supported by the flags argument,
2758  * which is the bitwise OR of flag values to suppress mutating of
2759  * indicated items.  (More flag bits may be added as needed.)
2760  */
2761 void
2762 query_tree_mutator(Query *query,
2763                                    Node *(*mutator) (),
2764                                    void *context,
2765                                    int flags)
2766 {
2767         List       *newrt = NIL;
2768         List       *rt;
2769
2770         Assert(query != NULL && IsA(query, Query));
2771
2772         MUTATE(query->targetList, query->targetList, List *);
2773         MUTATE(query->jointree, query->jointree, FromExpr *);
2774         MUTATE(query->setOperations, query->setOperations, Node *);
2775         MUTATE(query->havingQual, query->havingQual, Node *);
2776         foreach(rt, query->rtable)
2777         {
2778                 RangeTblEntry *rte = (RangeTblEntry *) lfirst(rt);
2779                 RangeTblEntry *newrte;
2780
2781                 switch (rte->rtekind)
2782                 {
2783                         case RTE_RELATION:
2784                         case RTE_SPECIAL:
2785                                 /* nothing to do, don't bother to make a copy */
2786                                 break;
2787                         case RTE_SUBQUERY:
2788                                 if (! (flags & QTW_IGNORE_SUBQUERIES))
2789                                 {
2790                                         FLATCOPY(newrte, rte, RangeTblEntry);
2791                                         CHECKFLATCOPY(newrte->subquery, rte->subquery, Query);
2792                                         MUTATE(newrte->subquery, newrte->subquery, Query *);
2793                                         rte = newrte;
2794                                 }
2795                                 break;
2796                         case RTE_JOIN:
2797                                 if (! (flags & QTW_IGNORE_JOINALIASES))
2798                                 {
2799                                         FLATCOPY(newrte, rte, RangeTblEntry);
2800                                         MUTATE(newrte->joinaliasvars, rte->joinaliasvars, List *);
2801                                         rte = newrte;
2802                                 }
2803                                 break;
2804                         case RTE_FUNCTION:
2805                                 FLATCOPY(newrte, rte, RangeTblEntry);
2806                                 MUTATE(newrte->funcexpr, rte->funcexpr, Node *);
2807                                 rte = newrte;
2808                                 break;
2809                 }
2810                 newrt = lappend(newrt, rte);
2811         }
2812         query->rtable = newrt;
2813 }