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