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