]> granicus.if.org Git - postgresql/blob - src/backend/optimizer/util/clauses.c
de2e66b0f160ddb1356e545ba09fa28e4abca706
[postgresql] / src / backend / optimizer / util / clauses.c
1 /*-------------------------------------------------------------------------
2  *
3  * clauses.c
4  *        routines to manipulate qualification clauses
5  *
6  * Portions Copyright (c) 1996-2010, PostgreSQL Global Development Group
7  * Portions Copyright (c) 1994, Regents of the University of California
8  *
9  *
10  * IDENTIFICATION
11  *        src/backend/optimizer/util/clauses.c
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_aggregate.h"
23 #include "catalog/pg_language.h"
24 #include "catalog/pg_operator.h"
25 #include "catalog/pg_proc.h"
26 #include "catalog/pg_type.h"
27 #include "executor/executor.h"
28 #include "executor/functions.h"
29 #include "miscadmin.h"
30 #include "nodes/makefuncs.h"
31 #include "nodes/nodeFuncs.h"
32 #include "optimizer/clauses.h"
33 #include "optimizer/cost.h"
34 #include "optimizer/planmain.h"
35 #include "optimizer/prep.h"
36 #include "optimizer/var.h"
37 #include "parser/analyze.h"
38 #include "parser/parse_coerce.h"
39 #include "parser/parse_func.h"
40 #include "rewrite/rewriteManip.h"
41 #include "tcop/tcopprot.h"
42 #include "utils/acl.h"
43 #include "utils/builtins.h"
44 #include "utils/datum.h"
45 #include "utils/lsyscache.h"
46 #include "utils/memutils.h"
47 #include "utils/syscache.h"
48 #include "utils/typcache.h"
49
50
51 typedef struct
52 {
53         ParamListInfo boundParams;
54         PlannerGlobal *glob;
55         List       *active_fns;
56         Node       *case_val;
57         bool            estimate;
58 } eval_const_expressions_context;
59
60 typedef struct
61 {
62         int                     nargs;
63         List       *args;
64         int                *usecounts;
65 } substitute_actual_parameters_context;
66
67 typedef struct
68 {
69         int                     nargs;
70         List       *args;
71         int                     sublevels_up;
72 } substitute_actual_srf_parameters_context;
73
74 typedef struct
75 {
76         char       *proname;
77         char       *prosrc;
78 } inline_error_callback_arg;
79
80 static bool contain_agg_clause_walker(Node *node, void *context);
81 static bool pull_agg_clause_walker(Node *node, List **context);
82 static bool count_agg_clauses_walker(Node *node, AggClauseCounts *counts);
83 static bool find_window_functions_walker(Node *node, WindowFuncLists *lists);
84 static bool expression_returns_set_rows_walker(Node *node, double *count);
85 static bool contain_subplans_walker(Node *node, void *context);
86 static bool contain_mutable_functions_walker(Node *node, void *context);
87 static bool contain_volatile_functions_walker(Node *node, void *context);
88 static bool contain_nonstrict_functions_walker(Node *node, void *context);
89 static Relids find_nonnullable_rels_walker(Node *node, bool top_level);
90 static List *find_nonnullable_vars_walker(Node *node, bool top_level);
91 static bool is_strict_saop(ScalarArrayOpExpr *expr, bool falseOK);
92 static bool set_coercionform_dontcare_walker(Node *node, void *context);
93 static Node *eval_const_expressions_mutator(Node *node,
94                                                            eval_const_expressions_context *context);
95 static List *simplify_or_arguments(List *args,
96                                           eval_const_expressions_context *context,
97                                           bool *haveNull, bool *forceTrue);
98 static List *simplify_and_arguments(List *args,
99                                            eval_const_expressions_context *context,
100                                            bool *haveNull, bool *forceFalse);
101 static Node *simplify_boolean_equality(Oid opno, List *args);
102 static Expr *simplify_function(Oid funcid,
103                                   Oid result_type, int32 result_typmod, List **args,
104                                   bool has_named_args,
105                                   bool allow_inline,
106                                   eval_const_expressions_context *context);
107 static List *reorder_function_arguments(List *args, Oid result_type,
108                                                    HeapTuple func_tuple,
109                                                    eval_const_expressions_context *context);
110 static List *add_function_defaults(List *args, Oid result_type,
111                                           HeapTuple func_tuple,
112                                           eval_const_expressions_context *context);
113 static List *fetch_function_defaults(HeapTuple func_tuple);
114 static void recheck_cast_function_args(List *args, Oid result_type,
115                                                    HeapTuple func_tuple);
116 static Expr *evaluate_function(Oid funcid,
117                                   Oid result_type, int32 result_typmod, List *args,
118                                   HeapTuple func_tuple,
119                                   eval_const_expressions_context *context);
120 static Expr *inline_function(Oid funcid, Oid result_type, List *args,
121                                 HeapTuple func_tuple,
122                                 eval_const_expressions_context *context);
123 static Node *substitute_actual_parameters(Node *expr, int nargs, List *args,
124                                                          int *usecounts);
125 static Node *substitute_actual_parameters_mutator(Node *node,
126                                                           substitute_actual_parameters_context *context);
127 static void sql_inline_error_callback(void *arg);
128 static Expr *evaluate_expr(Expr *expr, Oid result_type, int32 result_typmod);
129 static Query *substitute_actual_srf_parameters(Query *expr,
130                                                                  int nargs, List *args);
131 static Node *substitute_actual_srf_parameters_mutator(Node *node,
132                                                   substitute_actual_srf_parameters_context *context);
133 static bool tlist_matches_coltypelist(List *tlist, List *coltypelist);
134
135
136 /*****************************************************************************
137  *              OPERATOR clause functions
138  *****************************************************************************/
139
140 /*
141  * make_opclause
142  *        Creates an operator clause given its operator info, left operand,
143  *        and right operand (pass NULL to create single-operand clause).
144  */
145 Expr *
146 make_opclause(Oid opno, Oid opresulttype, bool opretset,
147                           Expr *leftop, Expr *rightop)
148 {
149         OpExpr     *expr = makeNode(OpExpr);
150
151         expr->opno = opno;
152         expr->opfuncid = InvalidOid;
153         expr->opresulttype = opresulttype;
154         expr->opretset = opretset;
155         if (rightop)
156                 expr->args = list_make2(leftop, rightop);
157         else
158                 expr->args = list_make1(leftop);
159         expr->location = -1;
160         return (Expr *) expr;
161 }
162
163 /*
164  * get_leftop
165  *
166  * Returns the left operand of a clause of the form (op expr expr)
167  *              or (op expr)
168  */
169 Node *
170 get_leftop(Expr *clause)
171 {
172         OpExpr     *expr = (OpExpr *) clause;
173
174         if (expr->args != NIL)
175                 return linitial(expr->args);
176         else
177                 return NULL;
178 }
179
180 /*
181  * get_rightop
182  *
183  * Returns the right operand in a clause of the form (op expr expr).
184  * NB: result will be NULL if applied to a unary op clause.
185  */
186 Node *
187 get_rightop(Expr *clause)
188 {
189         OpExpr     *expr = (OpExpr *) clause;
190
191         if (list_length(expr->args) >= 2)
192                 return lsecond(expr->args);
193         else
194                 return NULL;
195 }
196
197 /*****************************************************************************
198  *              NOT clause functions
199  *****************************************************************************/
200
201 /*
202  * not_clause
203  *
204  * Returns t iff this is a 'not' clause: (NOT expr).
205  */
206 bool
207 not_clause(Node *clause)
208 {
209         return (clause != NULL &&
210                         IsA(clause, BoolExpr) &&
211                         ((BoolExpr *) clause)->boolop == NOT_EXPR);
212 }
213
214 /*
215  * make_notclause
216  *
217  * Create a 'not' clause given the expression to be negated.
218  */
219 Expr *
220 make_notclause(Expr *notclause)
221 {
222         BoolExpr   *expr = makeNode(BoolExpr);
223
224         expr->boolop = NOT_EXPR;
225         expr->args = list_make1(notclause);
226         expr->location = -1;
227         return (Expr *) expr;
228 }
229
230 /*
231  * get_notclausearg
232  *
233  * Retrieve the clause within a 'not' clause
234  */
235 Expr *
236 get_notclausearg(Expr *notclause)
237 {
238         return linitial(((BoolExpr *) notclause)->args);
239 }
240
241 /*****************************************************************************
242  *              OR clause functions
243  *****************************************************************************/
244
245 /*
246  * or_clause
247  *
248  * Returns t iff the clause is an 'or' clause: (OR { expr }).
249  */
250 bool
251 or_clause(Node *clause)
252 {
253         return (clause != NULL &&
254                         IsA(clause, BoolExpr) &&
255                         ((BoolExpr *) clause)->boolop == OR_EXPR);
256 }
257
258 /*
259  * make_orclause
260  *
261  * Creates an 'or' clause given a list of its subclauses.
262  */
263 Expr *
264 make_orclause(List *orclauses)
265 {
266         BoolExpr   *expr = makeNode(BoolExpr);
267
268         expr->boolop = OR_EXPR;
269         expr->args = orclauses;
270         expr->location = -1;
271         return (Expr *) expr;
272 }
273
274 /*****************************************************************************
275  *              AND clause functions
276  *****************************************************************************/
277
278
279 /*
280  * and_clause
281  *
282  * Returns t iff its argument is an 'and' clause: (AND { expr }).
283  */
284 bool
285 and_clause(Node *clause)
286 {
287         return (clause != NULL &&
288                         IsA(clause, BoolExpr) &&
289                         ((BoolExpr *) clause)->boolop == AND_EXPR);
290 }
291
292 /*
293  * make_andclause
294  *
295  * Creates an 'and' clause given a list of its subclauses.
296  */
297 Expr *
298 make_andclause(List *andclauses)
299 {
300         BoolExpr   *expr = makeNode(BoolExpr);
301
302         expr->boolop = AND_EXPR;
303         expr->args = andclauses;
304         expr->location = -1;
305         return (Expr *) expr;
306 }
307
308 /*
309  * make_and_qual
310  *
311  * Variant of make_andclause for ANDing two qual conditions together.
312  * Qual conditions have the property that a NULL nodetree is interpreted
313  * as 'true'.
314  *
315  * NB: this makes no attempt to preserve AND/OR flatness; so it should not
316  * be used on a qual that has already been run through prepqual.c.
317  */
318 Node *
319 make_and_qual(Node *qual1, Node *qual2)
320 {
321         if (qual1 == NULL)
322                 return qual2;
323         if (qual2 == NULL)
324                 return qual1;
325         return (Node *) make_andclause(list_make2(qual1, qual2));
326 }
327
328 /*
329  * Sometimes (such as in the input of ExecQual), we use lists of expression
330  * nodes with implicit AND semantics.
331  *
332  * These functions convert between an AND-semantics expression list and the
333  * ordinary representation of a boolean expression.
334  *
335  * Note that an empty list is considered equivalent to TRUE.
336  */
337 Expr *
338 make_ands_explicit(List *andclauses)
339 {
340         if (andclauses == NIL)
341                 return (Expr *) makeBoolConst(true, false);
342         else if (list_length(andclauses) == 1)
343                 return (Expr *) linitial(andclauses);
344         else
345                 return make_andclause(andclauses);
346 }
347
348 List *
349 make_ands_implicit(Expr *clause)
350 {
351         /*
352          * NB: because the parser sets the qual field to NULL in a query that has
353          * no WHERE clause, we must consider a NULL input clause as TRUE, even
354          * though one might more reasonably think it FALSE.  Grumble. If this
355          * causes trouble, consider changing the parser's behavior.
356          */
357         if (clause == NULL)
358                 return NIL;                             /* NULL -> NIL list == TRUE */
359         else if (and_clause((Node *) clause))
360                 return ((BoolExpr *) clause)->args;
361         else if (IsA(clause, Const) &&
362                          !((Const *) clause)->constisnull &&
363                          DatumGetBool(((Const *) clause)->constvalue))
364                 return NIL;                             /* constant TRUE input -> NIL list */
365         else
366                 return list_make1(clause);
367 }
368
369
370 /*****************************************************************************
371  *              Aggregate-function clause manipulation
372  *****************************************************************************/
373
374 /*
375  * contain_agg_clause
376  *        Recursively search for Aggref nodes within a clause.
377  *
378  *        Returns true if any aggregate found.
379  *
380  * This does not descend into subqueries, and so should be used only after
381  * reduction of sublinks to subplans, or in contexts where it's known there
382  * are no subqueries.  There mustn't be outer-aggregate references either.
383  *
384  * (If you want something like this but able to deal with subqueries,
385  * see rewriteManip.c's contain_aggs_of_level().)
386  */
387 bool
388 contain_agg_clause(Node *clause)
389 {
390         return contain_agg_clause_walker(clause, NULL);
391 }
392
393 static bool
394 contain_agg_clause_walker(Node *node, void *context)
395 {
396         if (node == NULL)
397                 return false;
398         if (IsA(node, Aggref))
399         {
400                 Assert(((Aggref *) node)->agglevelsup == 0);
401                 return true;                    /* abort the tree traversal and return true */
402         }
403         Assert(!IsA(node, SubLink));
404         return expression_tree_walker(node, contain_agg_clause_walker, context);
405 }
406
407 /*
408  * pull_agg_clause
409  *        Recursively search for Aggref nodes within a clause.
410  *
411  *        Returns a List of all Aggrefs found.
412  *
413  * This does not descend into subqueries, and so should be used only after
414  * reduction of sublinks to subplans, or in contexts where it's known there
415  * are no subqueries.  There mustn't be outer-aggregate references either.
416  */
417 List *
418 pull_agg_clause(Node *clause)
419 {
420         List       *result = NIL;
421
422         (void) pull_agg_clause_walker(clause, &result);
423         return result;
424 }
425
426 static bool
427 pull_agg_clause_walker(Node *node, List **context)
428 {
429         if (node == NULL)
430                 return false;
431         if (IsA(node, Aggref))
432         {
433                 Assert(((Aggref *) node)->agglevelsup == 0);
434                 *context = lappend(*context, node);
435                 return false;                   /* no need to descend into arguments */
436         }
437         Assert(!IsA(node, SubLink));
438         return expression_tree_walker(node, pull_agg_clause_walker,
439                                                                   (void *) context);
440 }
441
442 /*
443  * count_agg_clauses
444  *        Recursively count the Aggref nodes in an expression tree.
445  *
446  *        Note: this also checks for nested aggregates, which are an error.
447  *
448  * We not only count the nodes, but attempt to estimate the total space
449  * needed for their transition state values if all are evaluated in parallel
450  * (as would be done in a HashAgg plan).  See AggClauseCounts for the exact
451  * set of statistics returned.
452  *
453  * NOTE that the counts are ADDED to those already in *counts ... so the
454  * caller is responsible for zeroing the struct initially.
455  *
456  * This does not descend into subqueries, and so should be used only after
457  * reduction of sublinks to subplans, or in contexts where it's known there
458  * are no subqueries.  There mustn't be outer-aggregate references either.
459  */
460 void
461 count_agg_clauses(Node *clause, AggClauseCounts *counts)
462 {
463         /* no setup needed */
464         count_agg_clauses_walker(clause, counts);
465 }
466
467 static bool
468 count_agg_clauses_walker(Node *node, AggClauseCounts *counts)
469 {
470         if (node == NULL)
471                 return false;
472         if (IsA(node, Aggref))
473         {
474                 Aggref     *aggref = (Aggref *) node;
475                 Oid                *inputTypes;
476                 int                     numArguments;
477                 HeapTuple       aggTuple;
478                 Form_pg_aggregate aggform;
479                 Oid                     aggtranstype;
480                 ListCell   *l;
481
482                 Assert(aggref->agglevelsup == 0);
483                 counts->numAggs++;
484                 if (aggref->aggorder != NIL || aggref->aggdistinct != NIL)
485                         counts->numOrderedAggs++;
486
487                 /* extract argument types (ignoring any ORDER BY expressions) */
488                 inputTypes = (Oid *) palloc(sizeof(Oid) * list_length(aggref->args));
489                 numArguments = 0;
490                 foreach(l, aggref->args)
491                 {
492                         TargetEntry *tle = (TargetEntry *) lfirst(l);
493
494                         if (!tle->resjunk)
495                                 inputTypes[numArguments++] = exprType((Node *) tle->expr);
496                 }
497
498                 /* fetch aggregate transition datatype from pg_aggregate */
499                 aggTuple = SearchSysCache1(AGGFNOID,
500                                                                    ObjectIdGetDatum(aggref->aggfnoid));
501                 if (!HeapTupleIsValid(aggTuple))
502                         elog(ERROR, "cache lookup failed for aggregate %u",
503                                  aggref->aggfnoid);
504                 aggform = (Form_pg_aggregate) GETSTRUCT(aggTuple);
505                 aggtranstype = aggform->aggtranstype;
506                 ReleaseSysCache(aggTuple);
507
508                 /* resolve actual type of transition state, if polymorphic */
509                 if (IsPolymorphicType(aggtranstype))
510                 {
511                         /* have to fetch the agg's declared input types... */
512                         Oid                *declaredArgTypes;
513                         int                     agg_nargs;
514
515                         (void) get_func_signature(aggref->aggfnoid,
516                                                                           &declaredArgTypes, &agg_nargs);
517                         Assert(agg_nargs == numArguments);
518                         aggtranstype = enforce_generic_type_consistency(inputTypes,
519                                                                                                                         declaredArgTypes,
520                                                                                                                         agg_nargs,
521                                                                                                                         aggtranstype,
522                                                                                                                         false);
523                         pfree(declaredArgTypes);
524                 }
525
526                 /*
527                  * If the transition type is pass-by-value then it doesn't add
528                  * anything to the required size of the hashtable.      If it is
529                  * pass-by-reference then we have to add the estimated size of the
530                  * value itself, plus palloc overhead.
531                  */
532                 if (!get_typbyval(aggtranstype))
533                 {
534                         int32           aggtranstypmod;
535                         int32           avgwidth;
536
537                         /*
538                          * If transition state is of same type as first input, assume it's
539                          * the same typmod (same width) as well.  This works for cases
540                          * like MAX/MIN and is probably somewhat reasonable otherwise.
541                          */
542                         if (numArguments > 0 && aggtranstype == inputTypes[0])
543                                 aggtranstypmod = exprTypmod((Node *) linitial(aggref->args));
544                         else
545                                 aggtranstypmod = -1;
546
547                         avgwidth = get_typavgwidth(aggtranstype, aggtranstypmod);
548                         avgwidth = MAXALIGN(avgwidth);
549
550                         counts->transitionSpace += avgwidth + 2 * sizeof(void *);
551                 }
552                 else if (aggtranstype == INTERNALOID)
553                 {
554                         /*
555                          * INTERNAL transition type is a special case: although INTERNAL
556                          * is pass-by-value, it's almost certainly being used as a pointer
557                          * to some large data structure.  We assume usage of
558                          * ALLOCSET_DEFAULT_INITSIZE, which is a good guess if the data is
559                          * being kept in a private memory context, as is done by
560                          * array_agg() for instance.
561                          */
562                         counts->transitionSpace += ALLOCSET_DEFAULT_INITSIZE;
563                 }
564
565                 /*
566                  * Complain if the aggregate's arguments contain any aggregates;
567                  * nested agg functions are semantically nonsensical.
568                  */
569                 if (contain_agg_clause((Node *) aggref->args))
570                         ereport(ERROR,
571                                         (errcode(ERRCODE_GROUPING_ERROR),
572                                          errmsg("aggregate function calls cannot be nested")));
573
574                 /*
575                  * Having checked that, we need not recurse into the argument.
576                  */
577                 return false;
578         }
579         Assert(!IsA(node, SubLink));
580         return expression_tree_walker(node, count_agg_clauses_walker,
581                                                                   (void *) counts);
582 }
583
584
585 /*****************************************************************************
586  *              Window-function clause manipulation
587  *****************************************************************************/
588
589 /*
590  * contain_window_function
591  *        Recursively search for WindowFunc nodes within a clause.
592  *
593  * Since window functions don't have level fields, but are hard-wired to
594  * be associated with the current query level, this is just the same as
595  * rewriteManip.c's function.
596  */
597 bool
598 contain_window_function(Node *clause)
599 {
600         return checkExprHasWindowFuncs(clause);
601 }
602
603 /*
604  * find_window_functions
605  *        Locate all the WindowFunc nodes in an expression tree, and organize
606  *        them by winref ID number.
607  *
608  * Caller must provide an upper bound on the winref IDs expected in the tree.
609  */
610 WindowFuncLists *
611 find_window_functions(Node *clause, Index maxWinRef)
612 {
613         WindowFuncLists *lists = palloc(sizeof(WindowFuncLists));
614
615         lists->numWindowFuncs = 0;
616         lists->maxWinRef = maxWinRef;
617         lists->windowFuncs = (List **) palloc0((maxWinRef + 1) * sizeof(List *));
618         (void) find_window_functions_walker(clause, lists);
619         return lists;
620 }
621
622 static bool
623 find_window_functions_walker(Node *node, WindowFuncLists *lists)
624 {
625         if (node == NULL)
626                 return false;
627         if (IsA(node, WindowFunc))
628         {
629                 WindowFunc *wfunc = (WindowFunc *) node;
630
631                 /* winref is unsigned, so one-sided test is OK */
632                 if (wfunc->winref > lists->maxWinRef)
633                         elog(ERROR, "WindowFunc contains out-of-range winref %u",
634                                  wfunc->winref);
635                 lists->windowFuncs[wfunc->winref] =
636                         lappend(lists->windowFuncs[wfunc->winref], wfunc);
637                 lists->numWindowFuncs++;
638
639                 /*
640                  * Complain if the window function's arguments contain window
641                  * functions
642                  */
643                 if (contain_window_function((Node *) wfunc->args))
644                         ereport(ERROR,
645                                         (errcode(ERRCODE_WINDOWING_ERROR),
646                                          errmsg("window function calls cannot be nested")));
647
648                 /*
649                  * Having checked that, we need not recurse into the argument.
650                  */
651                 return false;
652         }
653         Assert(!IsA(node, SubLink));
654         return expression_tree_walker(node, find_window_functions_walker,
655                                                                   (void *) lists);
656 }
657
658
659 /*****************************************************************************
660  *              Support for expressions returning sets
661  *****************************************************************************/
662
663 /*
664  * expression_returns_set_rows
665  *        Estimate the number of rows in a set result.
666  *
667  * We use the product of the rowcount estimates of all the functions in
668  * the given tree.      The result is 1 if there are no set-returning functions.
669  *
670  * Note: keep this in sync with expression_returns_set() in nodes/nodeFuncs.c.
671  */
672 double
673 expression_returns_set_rows(Node *clause)
674 {
675         double          result = 1;
676
677         (void) expression_returns_set_rows_walker(clause, &result);
678         return result;
679 }
680
681 static bool
682 expression_returns_set_rows_walker(Node *node, double *count)
683 {
684         if (node == NULL)
685                 return false;
686         if (IsA(node, FuncExpr))
687         {
688                 FuncExpr   *expr = (FuncExpr *) node;
689
690                 if (expr->funcretset)
691                         *count *= get_func_rows(expr->funcid);
692         }
693         if (IsA(node, OpExpr))
694         {
695                 OpExpr     *expr = (OpExpr *) node;
696
697                 if (expr->opretset)
698                 {
699                         set_opfuncid(expr);
700                         *count *= get_func_rows(expr->opfuncid);
701                 }
702         }
703
704         /* Avoid recursion for some cases that can't return a set */
705         if (IsA(node, Aggref))
706                 return false;
707         if (IsA(node, WindowFunc))
708                 return false;
709         if (IsA(node, DistinctExpr))
710                 return false;
711         if (IsA(node, ScalarArrayOpExpr))
712                 return false;
713         if (IsA(node, BoolExpr))
714                 return false;
715         if (IsA(node, SubLink))
716                 return false;
717         if (IsA(node, SubPlan))
718                 return false;
719         if (IsA(node, AlternativeSubPlan))
720                 return false;
721         if (IsA(node, ArrayExpr))
722                 return false;
723         if (IsA(node, RowExpr))
724                 return false;
725         if (IsA(node, RowCompareExpr))
726                 return false;
727         if (IsA(node, CoalesceExpr))
728                 return false;
729         if (IsA(node, MinMaxExpr))
730                 return false;
731         if (IsA(node, XmlExpr))
732                 return false;
733         if (IsA(node, NullIfExpr))
734                 return false;
735
736         return expression_tree_walker(node, expression_returns_set_rows_walker,
737                                                                   (void *) count);
738 }
739
740
741 /*****************************************************************************
742  *              Subplan clause manipulation
743  *****************************************************************************/
744
745 /*
746  * contain_subplans
747  *        Recursively search for subplan nodes within a clause.
748  *
749  * If we see a SubLink node, we will return TRUE.  This is only possible if
750  * the expression tree hasn't yet been transformed by subselect.c.  We do not
751  * know whether the node will produce a true subplan or just an initplan,
752  * but we make the conservative assumption that it will be a subplan.
753  *
754  * Returns true if any subplan found.
755  */
756 bool
757 contain_subplans(Node *clause)
758 {
759         return contain_subplans_walker(clause, NULL);
760 }
761
762 static bool
763 contain_subplans_walker(Node *node, void *context)
764 {
765         if (node == NULL)
766                 return false;
767         if (IsA(node, SubPlan) ||
768                 IsA(node, AlternativeSubPlan) ||
769                 IsA(node, SubLink))
770                 return true;                    /* abort the tree traversal and return true */
771         return expression_tree_walker(node, contain_subplans_walker, context);
772 }
773
774
775 /*****************************************************************************
776  *              Check clauses for mutable functions
777  *****************************************************************************/
778
779 /*
780  * contain_mutable_functions
781  *        Recursively search for mutable functions within a clause.
782  *
783  * Returns true if any mutable function (or operator implemented by a
784  * mutable function) is found.  This test is needed so that we don't
785  * mistakenly think that something like "WHERE random() < 0.5" can be treated
786  * as a constant qualification.
787  *
788  * XXX we do not examine sub-selects to see if they contain uses of
789  * mutable functions.  It's not real clear if that is correct or not...
790  */
791 bool
792 contain_mutable_functions(Node *clause)
793 {
794         return contain_mutable_functions_walker(clause, NULL);
795 }
796
797 static bool
798 contain_mutable_functions_walker(Node *node, void *context)
799 {
800         if (node == NULL)
801                 return false;
802         if (IsA(node, FuncExpr))
803         {
804                 FuncExpr   *expr = (FuncExpr *) node;
805
806                 if (func_volatile(expr->funcid) != PROVOLATILE_IMMUTABLE)
807                         return true;
808                 /* else fall through to check args */
809         }
810         else if (IsA(node, OpExpr))
811         {
812                 OpExpr     *expr = (OpExpr *) node;
813
814                 set_opfuncid(expr);
815                 if (func_volatile(expr->opfuncid) != PROVOLATILE_IMMUTABLE)
816                         return true;
817                 /* else fall through to check args */
818         }
819         else if (IsA(node, DistinctExpr))
820         {
821                 DistinctExpr *expr = (DistinctExpr *) node;
822
823                 set_opfuncid((OpExpr *) expr);  /* rely on struct equivalence */
824                 if (func_volatile(expr->opfuncid) != PROVOLATILE_IMMUTABLE)
825                         return true;
826                 /* else fall through to check args */
827         }
828         else if (IsA(node, ScalarArrayOpExpr))
829         {
830                 ScalarArrayOpExpr *expr = (ScalarArrayOpExpr *) node;
831
832                 set_sa_opfuncid(expr);
833                 if (func_volatile(expr->opfuncid) != PROVOLATILE_IMMUTABLE)
834                         return true;
835                 /* else fall through to check args */
836         }
837         else if (IsA(node, CoerceViaIO))
838         {
839                 CoerceViaIO *expr = (CoerceViaIO *) node;
840                 Oid                     iofunc;
841                 Oid                     typioparam;
842                 bool            typisvarlena;
843
844                 /* check the result type's input function */
845                 getTypeInputInfo(expr->resulttype,
846                                                  &iofunc, &typioparam);
847                 if (func_volatile(iofunc) != PROVOLATILE_IMMUTABLE)
848                         return true;
849                 /* check the input type's output function */
850                 getTypeOutputInfo(exprType((Node *) expr->arg),
851                                                   &iofunc, &typisvarlena);
852                 if (func_volatile(iofunc) != PROVOLATILE_IMMUTABLE)
853                         return true;
854                 /* else fall through to check args */
855         }
856         else if (IsA(node, ArrayCoerceExpr))
857         {
858                 ArrayCoerceExpr *expr = (ArrayCoerceExpr *) node;
859
860                 if (OidIsValid(expr->elemfuncid) &&
861                         func_volatile(expr->elemfuncid) != PROVOLATILE_IMMUTABLE)
862                         return true;
863                 /* else fall through to check args */
864         }
865         else if (IsA(node, NullIfExpr))
866         {
867                 NullIfExpr *expr = (NullIfExpr *) node;
868
869                 set_opfuncid((OpExpr *) expr);  /* rely on struct equivalence */
870                 if (func_volatile(expr->opfuncid) != PROVOLATILE_IMMUTABLE)
871                         return true;
872                 /* else fall through to check args */
873         }
874         else if (IsA(node, RowCompareExpr))
875         {
876                 RowCompareExpr *rcexpr = (RowCompareExpr *) node;
877                 ListCell   *opid;
878
879                 foreach(opid, rcexpr->opnos)
880                 {
881                         if (op_volatile(lfirst_oid(opid)) != PROVOLATILE_IMMUTABLE)
882                                 return true;
883                 }
884                 /* else fall through to check args */
885         }
886         return expression_tree_walker(node, contain_mutable_functions_walker,
887                                                                   context);
888 }
889
890
891 /*****************************************************************************
892  *              Check clauses for volatile functions
893  *****************************************************************************/
894
895 /*
896  * contain_volatile_functions
897  *        Recursively search for volatile functions within a clause.
898  *
899  * Returns true if any volatile function (or operator implemented by a
900  * volatile function) is found. This test prevents invalid conversions
901  * of volatile expressions into indexscan quals.
902  *
903  * XXX we do not examine sub-selects to see if they contain uses of
904  * volatile functions.  It's not real clear if that is correct or not...
905  */
906 bool
907 contain_volatile_functions(Node *clause)
908 {
909         return contain_volatile_functions_walker(clause, NULL);
910 }
911
912 static bool
913 contain_volatile_functions_walker(Node *node, void *context)
914 {
915         if (node == NULL)
916                 return false;
917         if (IsA(node, FuncExpr))
918         {
919                 FuncExpr   *expr = (FuncExpr *) node;
920
921                 if (func_volatile(expr->funcid) == PROVOLATILE_VOLATILE)
922                         return true;
923                 /* else fall through to check args */
924         }
925         else if (IsA(node, OpExpr))
926         {
927                 OpExpr     *expr = (OpExpr *) node;
928
929                 set_opfuncid(expr);
930                 if (func_volatile(expr->opfuncid) == PROVOLATILE_VOLATILE)
931                         return true;
932                 /* else fall through to check args */
933         }
934         else if (IsA(node, DistinctExpr))
935         {
936                 DistinctExpr *expr = (DistinctExpr *) node;
937
938                 set_opfuncid((OpExpr *) expr);  /* rely on struct equivalence */
939                 if (func_volatile(expr->opfuncid) == PROVOLATILE_VOLATILE)
940                         return true;
941                 /* else fall through to check args */
942         }
943         else if (IsA(node, ScalarArrayOpExpr))
944         {
945                 ScalarArrayOpExpr *expr = (ScalarArrayOpExpr *) node;
946
947                 set_sa_opfuncid(expr);
948                 if (func_volatile(expr->opfuncid) == PROVOLATILE_VOLATILE)
949                         return true;
950                 /* else fall through to check args */
951         }
952         else if (IsA(node, CoerceViaIO))
953         {
954                 CoerceViaIO *expr = (CoerceViaIO *) node;
955                 Oid                     iofunc;
956                 Oid                     typioparam;
957                 bool            typisvarlena;
958
959                 /* check the result type's input function */
960                 getTypeInputInfo(expr->resulttype,
961                                                  &iofunc, &typioparam);
962                 if (func_volatile(iofunc) == PROVOLATILE_VOLATILE)
963                         return true;
964                 /* check the input type's output function */
965                 getTypeOutputInfo(exprType((Node *) expr->arg),
966                                                   &iofunc, &typisvarlena);
967                 if (func_volatile(iofunc) == PROVOLATILE_VOLATILE)
968                         return true;
969                 /* else fall through to check args */
970         }
971         else if (IsA(node, ArrayCoerceExpr))
972         {
973                 ArrayCoerceExpr *expr = (ArrayCoerceExpr *) node;
974
975                 if (OidIsValid(expr->elemfuncid) &&
976                         func_volatile(expr->elemfuncid) == PROVOLATILE_VOLATILE)
977                         return true;
978                 /* else fall through to check args */
979         }
980         else if (IsA(node, NullIfExpr))
981         {
982                 NullIfExpr *expr = (NullIfExpr *) node;
983
984                 set_opfuncid((OpExpr *) expr);  /* rely on struct equivalence */
985                 if (func_volatile(expr->opfuncid) == PROVOLATILE_VOLATILE)
986                         return true;
987                 /* else fall through to check args */
988         }
989         else if (IsA(node, RowCompareExpr))
990         {
991                 /* RowCompare probably can't have volatile ops, but check anyway */
992                 RowCompareExpr *rcexpr = (RowCompareExpr *) node;
993                 ListCell   *opid;
994
995                 foreach(opid, rcexpr->opnos)
996                 {
997                         if (op_volatile(lfirst_oid(opid)) == PROVOLATILE_VOLATILE)
998                                 return true;
999                 }
1000                 /* else fall through to check args */
1001         }
1002         return expression_tree_walker(node, contain_volatile_functions_walker,
1003                                                                   context);
1004 }
1005
1006
1007 /*****************************************************************************
1008  *              Check clauses for nonstrict functions
1009  *****************************************************************************/
1010
1011 /*
1012  * contain_nonstrict_functions
1013  *        Recursively search for nonstrict functions within a clause.
1014  *
1015  * Returns true if any nonstrict construct is found --- ie, anything that
1016  * could produce non-NULL output with a NULL input.
1017  *
1018  * The idea here is that the caller has verified that the expression contains
1019  * one or more Var or Param nodes (as appropriate for the caller's need), and
1020  * now wishes to prove that the expression result will be NULL if any of these
1021  * inputs is NULL.      If we return false, then the proof succeeded.
1022  */
1023 bool
1024 contain_nonstrict_functions(Node *clause)
1025 {
1026         return contain_nonstrict_functions_walker(clause, NULL);
1027 }
1028
1029 static bool
1030 contain_nonstrict_functions_walker(Node *node, void *context)
1031 {
1032         if (node == NULL)
1033                 return false;
1034         if (IsA(node, Aggref))
1035         {
1036                 /* an aggregate could return non-null with null input */
1037                 return true;
1038         }
1039         if (IsA(node, WindowFunc))
1040         {
1041                 /* a window function could return non-null with null input */
1042                 return true;
1043         }
1044         if (IsA(node, ArrayRef))
1045         {
1046                 /* array assignment is nonstrict, but subscripting is strict */
1047                 if (((ArrayRef *) node)->refassgnexpr != NULL)
1048                         return true;
1049                 /* else fall through to check args */
1050         }
1051         if (IsA(node, FuncExpr))
1052         {
1053                 FuncExpr   *expr = (FuncExpr *) node;
1054
1055                 if (!func_strict(expr->funcid))
1056                         return true;
1057                 /* else fall through to check args */
1058         }
1059         if (IsA(node, OpExpr))
1060         {
1061                 OpExpr     *expr = (OpExpr *) node;
1062
1063                 set_opfuncid(expr);
1064                 if (!func_strict(expr->opfuncid))
1065                         return true;
1066                 /* else fall through to check args */
1067         }
1068         if (IsA(node, DistinctExpr))
1069         {
1070                 /* IS DISTINCT FROM is inherently non-strict */
1071                 return true;
1072         }
1073         if (IsA(node, ScalarArrayOpExpr))
1074         {
1075                 ScalarArrayOpExpr *expr = (ScalarArrayOpExpr *) node;
1076
1077                 if (!is_strict_saop(expr, false))
1078                         return true;
1079                 /* else fall through to check args */
1080         }
1081         if (IsA(node, BoolExpr))
1082         {
1083                 BoolExpr   *expr = (BoolExpr *) node;
1084
1085                 switch (expr->boolop)
1086                 {
1087                         case AND_EXPR:
1088                         case OR_EXPR:
1089                                 /* AND, OR are inherently non-strict */
1090                                 return true;
1091                         default:
1092                                 break;
1093                 }
1094         }
1095         if (IsA(node, SubLink))
1096         {
1097                 /* In some cases a sublink might be strict, but in general not */
1098                 return true;
1099         }
1100         if (IsA(node, SubPlan))
1101                 return true;
1102         if (IsA(node, AlternativeSubPlan))
1103                 return true;
1104         /* ArrayCoerceExpr is strict at the array level, regardless of elemfunc */
1105         if (IsA(node, FieldStore))
1106                 return true;
1107         if (IsA(node, CaseExpr))
1108                 return true;
1109         if (IsA(node, ArrayExpr))
1110                 return true;
1111         if (IsA(node, RowExpr))
1112                 return true;
1113         if (IsA(node, RowCompareExpr))
1114                 return true;
1115         if (IsA(node, CoalesceExpr))
1116                 return true;
1117         if (IsA(node, MinMaxExpr))
1118                 return true;
1119         if (IsA(node, XmlExpr))
1120                 return true;
1121         if (IsA(node, NullIfExpr))
1122                 return true;
1123         if (IsA(node, NullTest))
1124                 return true;
1125         if (IsA(node, BooleanTest))
1126                 return true;
1127         return expression_tree_walker(node, contain_nonstrict_functions_walker,
1128                                                                   context);
1129 }
1130
1131
1132 /*
1133  * find_nonnullable_rels
1134  *              Determine which base rels are forced nonnullable by given clause.
1135  *
1136  * Returns the set of all Relids that are referenced in the clause in such
1137  * a way that the clause cannot possibly return TRUE if any of these Relids
1138  * is an all-NULL row.  (It is OK to err on the side of conservatism; hence
1139  * the analysis here is simplistic.)
1140  *
1141  * The semantics here are subtly different from contain_nonstrict_functions:
1142  * that function is concerned with NULL results from arbitrary expressions,
1143  * but here we assume that the input is a Boolean expression, and wish to
1144  * see if NULL inputs will provably cause a FALSE-or-NULL result.  We expect
1145  * the expression to have been AND/OR flattened and converted to implicit-AND
1146  * format.
1147  *
1148  * Note: this function is largely duplicative of find_nonnullable_vars().
1149  * The reason not to simplify this function into a thin wrapper around
1150  * find_nonnullable_vars() is that the tested conditions really are different:
1151  * a clause like "t1.v1 IS NOT NULL OR t1.v2 IS NOT NULL" does not prove
1152  * that either v1 or v2 can't be NULL, but it does prove that the t1 row
1153  * as a whole can't be all-NULL.
1154  *
1155  * top_level is TRUE while scanning top-level AND/OR structure; here, showing
1156  * the result is either FALSE or NULL is good enough.  top_level is FALSE when
1157  * we have descended below a NOT or a strict function: now we must be able to
1158  * prove that the subexpression goes to NULL.
1159  *
1160  * We don't use expression_tree_walker here because we don't want to descend
1161  * through very many kinds of nodes; only the ones we can be sure are strict.
1162  */
1163 Relids
1164 find_nonnullable_rels(Node *clause)
1165 {
1166         return find_nonnullable_rels_walker(clause, true);
1167 }
1168
1169 static Relids
1170 find_nonnullable_rels_walker(Node *node, bool top_level)
1171 {
1172         Relids          result = NULL;
1173         ListCell   *l;
1174
1175         if (node == NULL)
1176                 return NULL;
1177         if (IsA(node, Var))
1178         {
1179                 Var                *var = (Var *) node;
1180
1181                 if (var->varlevelsup == 0)
1182                         result = bms_make_singleton(var->varno);
1183         }
1184         else if (IsA(node, List))
1185         {
1186                 /*
1187                  * At top level, we are examining an implicit-AND list: if any of the
1188                  * arms produces FALSE-or-NULL then the result is FALSE-or-NULL. If
1189                  * not at top level, we are examining the arguments of a strict
1190                  * function: if any of them produce NULL then the result of the
1191                  * function must be NULL.  So in both cases, the set of nonnullable
1192                  * rels is the union of those found in the arms, and we pass down the
1193                  * top_level flag unmodified.
1194                  */
1195                 foreach(l, (List *) node)
1196                 {
1197                         result = bms_join(result,
1198                                                           find_nonnullable_rels_walker(lfirst(l),
1199                                                                                                                    top_level));
1200                 }
1201         }
1202         else if (IsA(node, FuncExpr))
1203         {
1204                 FuncExpr   *expr = (FuncExpr *) node;
1205
1206                 if (func_strict(expr->funcid))
1207                         result = find_nonnullable_rels_walker((Node *) expr->args, false);
1208         }
1209         else if (IsA(node, OpExpr))
1210         {
1211                 OpExpr     *expr = (OpExpr *) node;
1212
1213                 set_opfuncid(expr);
1214                 if (func_strict(expr->opfuncid))
1215                         result = find_nonnullable_rels_walker((Node *) expr->args, false);
1216         }
1217         else if (IsA(node, ScalarArrayOpExpr))
1218         {
1219                 ScalarArrayOpExpr *expr = (ScalarArrayOpExpr *) node;
1220
1221                 if (is_strict_saop(expr, true))
1222                         result = find_nonnullable_rels_walker((Node *) expr->args, false);
1223         }
1224         else if (IsA(node, BoolExpr))
1225         {
1226                 BoolExpr   *expr = (BoolExpr *) node;
1227
1228                 switch (expr->boolop)
1229                 {
1230                         case AND_EXPR:
1231                                 /* At top level we can just recurse (to the List case) */
1232                                 if (top_level)
1233                                 {
1234                                         result = find_nonnullable_rels_walker((Node *) expr->args,
1235                                                                                                                   top_level);
1236                                         break;
1237                                 }
1238
1239                                 /*
1240                                  * Below top level, even if one arm produces NULL, the result
1241                                  * could be FALSE (hence not NULL).  However, if *all* the
1242                                  * arms produce NULL then the result is NULL, so we can take
1243                                  * the intersection of the sets of nonnullable rels, just as
1244                                  * for OR.      Fall through to share code.
1245                                  */
1246                                 /* FALL THRU */
1247                         case OR_EXPR:
1248
1249                                 /*
1250                                  * OR is strict if all of its arms are, so we can take the
1251                                  * intersection of the sets of nonnullable rels for each arm.
1252                                  * This works for both values of top_level.
1253                                  */
1254                                 foreach(l, expr->args)
1255                                 {
1256                                         Relids          subresult;
1257
1258                                         subresult = find_nonnullable_rels_walker(lfirst(l),
1259                                                                                                                          top_level);
1260                                         if (result == NULL) /* first subresult? */
1261                                                 result = subresult;
1262                                         else
1263                                                 result = bms_int_members(result, subresult);
1264
1265                                         /*
1266                                          * If the intersection is empty, we can stop looking. This
1267                                          * also justifies the test for first-subresult above.
1268                                          */
1269                                         if (bms_is_empty(result))
1270                                                 break;
1271                                 }
1272                                 break;
1273                         case NOT_EXPR:
1274                                 /* NOT will return null if its arg is null */
1275                                 result = find_nonnullable_rels_walker((Node *) expr->args,
1276                                                                                                           false);
1277                                 break;
1278                         default:
1279                                 elog(ERROR, "unrecognized boolop: %d", (int) expr->boolop);
1280                                 break;
1281                 }
1282         }
1283         else if (IsA(node, RelabelType))
1284         {
1285                 RelabelType *expr = (RelabelType *) node;
1286
1287                 result = find_nonnullable_rels_walker((Node *) expr->arg, top_level);
1288         }
1289         else if (IsA(node, CoerceViaIO))
1290         {
1291                 /* not clear this is useful, but it can't hurt */
1292                 CoerceViaIO *expr = (CoerceViaIO *) node;
1293
1294                 result = find_nonnullable_rels_walker((Node *) expr->arg, top_level);
1295         }
1296         else if (IsA(node, ArrayCoerceExpr))
1297         {
1298                 /* ArrayCoerceExpr is strict at the array level */
1299                 ArrayCoerceExpr *expr = (ArrayCoerceExpr *) node;
1300
1301                 result = find_nonnullable_rels_walker((Node *) expr->arg, top_level);
1302         }
1303         else if (IsA(node, ConvertRowtypeExpr))
1304         {
1305                 /* not clear this is useful, but it can't hurt */
1306                 ConvertRowtypeExpr *expr = (ConvertRowtypeExpr *) node;
1307
1308                 result = find_nonnullable_rels_walker((Node *) expr->arg, top_level);
1309         }
1310         else if (IsA(node, NullTest))
1311         {
1312                 /* IS NOT NULL can be considered strict, but only at top level */
1313                 NullTest   *expr = (NullTest *) node;
1314
1315                 if (top_level && expr->nulltesttype == IS_NOT_NULL && !expr->argisrow)
1316                         result = find_nonnullable_rels_walker((Node *) expr->arg, false);
1317         }
1318         else if (IsA(node, BooleanTest))
1319         {
1320                 /* Boolean tests that reject NULL are strict at top level */
1321                 BooleanTest *expr = (BooleanTest *) node;
1322
1323                 if (top_level &&
1324                         (expr->booltesttype == IS_TRUE ||
1325                          expr->booltesttype == IS_FALSE ||
1326                          expr->booltesttype == IS_NOT_UNKNOWN))
1327                         result = find_nonnullable_rels_walker((Node *) expr->arg, false);
1328         }
1329         else if (IsA(node, PlaceHolderVar))
1330         {
1331                 PlaceHolderVar *phv = (PlaceHolderVar *) node;
1332
1333                 result = find_nonnullable_rels_walker((Node *) phv->phexpr, top_level);
1334         }
1335         return result;
1336 }
1337
1338 /*
1339  * find_nonnullable_vars
1340  *              Determine which Vars are forced nonnullable by given clause.
1341  *
1342  * Returns a list of all level-zero Vars that are referenced in the clause in
1343  * such a way that the clause cannot possibly return TRUE if any of these Vars
1344  * is NULL.  (It is OK to err on the side of conservatism; hence the analysis
1345  * here is simplistic.)
1346  *
1347  * The semantics here are subtly different from contain_nonstrict_functions:
1348  * that function is concerned with NULL results from arbitrary expressions,
1349  * but here we assume that the input is a Boolean expression, and wish to
1350  * see if NULL inputs will provably cause a FALSE-or-NULL result.  We expect
1351  * the expression to have been AND/OR flattened and converted to implicit-AND
1352  * format.
1353  *
1354  * The result is a palloc'd List, but we have not copied the member Var nodes.
1355  * Also, we don't bother trying to eliminate duplicate entries.
1356  *
1357  * top_level is TRUE while scanning top-level AND/OR structure; here, showing
1358  * the result is either FALSE or NULL is good enough.  top_level is FALSE when
1359  * we have descended below a NOT or a strict function: now we must be able to
1360  * prove that the subexpression goes to NULL.
1361  *
1362  * We don't use expression_tree_walker here because we don't want to descend
1363  * through very many kinds of nodes; only the ones we can be sure are strict.
1364  */
1365 List *
1366 find_nonnullable_vars(Node *clause)
1367 {
1368         return find_nonnullable_vars_walker(clause, true);
1369 }
1370
1371 static List *
1372 find_nonnullable_vars_walker(Node *node, bool top_level)
1373 {
1374         List       *result = NIL;
1375         ListCell   *l;
1376
1377         if (node == NULL)
1378                 return NIL;
1379         if (IsA(node, Var))
1380         {
1381                 Var                *var = (Var *) node;
1382
1383                 if (var->varlevelsup == 0)
1384                         result = list_make1(var);
1385         }
1386         else if (IsA(node, List))
1387         {
1388                 /*
1389                  * At top level, we are examining an implicit-AND list: if any of the
1390                  * arms produces FALSE-or-NULL then the result is FALSE-or-NULL. If
1391                  * not at top level, we are examining the arguments of a strict
1392                  * function: if any of them produce NULL then the result of the
1393                  * function must be NULL.  So in both cases, the set of nonnullable
1394                  * vars is the union of those found in the arms, and we pass down the
1395                  * top_level flag unmodified.
1396                  */
1397                 foreach(l, (List *) node)
1398                 {
1399                         result = list_concat(result,
1400                                                                  find_nonnullable_vars_walker(lfirst(l),
1401                                                                                                                           top_level));
1402                 }
1403         }
1404         else if (IsA(node, FuncExpr))
1405         {
1406                 FuncExpr   *expr = (FuncExpr *) node;
1407
1408                 if (func_strict(expr->funcid))
1409                         result = find_nonnullable_vars_walker((Node *) expr->args, false);
1410         }
1411         else if (IsA(node, OpExpr))
1412         {
1413                 OpExpr     *expr = (OpExpr *) node;
1414
1415                 set_opfuncid(expr);
1416                 if (func_strict(expr->opfuncid))
1417                         result = find_nonnullable_vars_walker((Node *) expr->args, false);
1418         }
1419         else if (IsA(node, ScalarArrayOpExpr))
1420         {
1421                 ScalarArrayOpExpr *expr = (ScalarArrayOpExpr *) node;
1422
1423                 if (is_strict_saop(expr, true))
1424                         result = find_nonnullable_vars_walker((Node *) expr->args, false);
1425         }
1426         else if (IsA(node, BoolExpr))
1427         {
1428                 BoolExpr   *expr = (BoolExpr *) node;
1429
1430                 switch (expr->boolop)
1431                 {
1432                         case AND_EXPR:
1433                                 /* At top level we can just recurse (to the List case) */
1434                                 if (top_level)
1435                                 {
1436                                         result = find_nonnullable_vars_walker((Node *) expr->args,
1437                                                                                                                   top_level);
1438                                         break;
1439                                 }
1440
1441                                 /*
1442                                  * Below top level, even if one arm produces NULL, the result
1443                                  * could be FALSE (hence not NULL).  However, if *all* the
1444                                  * arms produce NULL then the result is NULL, so we can take
1445                                  * the intersection of the sets of nonnullable vars, just as
1446                                  * for OR.      Fall through to share code.
1447                                  */
1448                                 /* FALL THRU */
1449                         case OR_EXPR:
1450
1451                                 /*
1452                                  * OR is strict if all of its arms are, so we can take the
1453                                  * intersection of the sets of nonnullable vars for each arm.
1454                                  * This works for both values of top_level.
1455                                  */
1456                                 foreach(l, expr->args)
1457                                 {
1458                                         List       *subresult;
1459
1460                                         subresult = find_nonnullable_vars_walker(lfirst(l),
1461                                                                                                                          top_level);
1462                                         if (result == NIL)      /* first subresult? */
1463                                                 result = subresult;
1464                                         else
1465                                                 result = list_intersection(result, subresult);
1466
1467                                         /*
1468                                          * If the intersection is empty, we can stop looking. This
1469                                          * also justifies the test for first-subresult above.
1470                                          */
1471                                         if (result == NIL)
1472                                                 break;
1473                                 }
1474                                 break;
1475                         case NOT_EXPR:
1476                                 /* NOT will return null if its arg is null */
1477                                 result = find_nonnullable_vars_walker((Node *) expr->args,
1478                                                                                                           false);
1479                                 break;
1480                         default:
1481                                 elog(ERROR, "unrecognized boolop: %d", (int) expr->boolop);
1482                                 break;
1483                 }
1484         }
1485         else if (IsA(node, RelabelType))
1486         {
1487                 RelabelType *expr = (RelabelType *) node;
1488
1489                 result = find_nonnullable_vars_walker((Node *) expr->arg, top_level);
1490         }
1491         else if (IsA(node, CoerceViaIO))
1492         {
1493                 /* not clear this is useful, but it can't hurt */
1494                 CoerceViaIO *expr = (CoerceViaIO *) node;
1495
1496                 result = find_nonnullable_vars_walker((Node *) expr->arg, false);
1497         }
1498         else if (IsA(node, ArrayCoerceExpr))
1499         {
1500                 /* ArrayCoerceExpr is strict at the array level */
1501                 ArrayCoerceExpr *expr = (ArrayCoerceExpr *) node;
1502
1503                 result = find_nonnullable_vars_walker((Node *) expr->arg, top_level);
1504         }
1505         else if (IsA(node, ConvertRowtypeExpr))
1506         {
1507                 /* not clear this is useful, but it can't hurt */
1508                 ConvertRowtypeExpr *expr = (ConvertRowtypeExpr *) node;
1509
1510                 result = find_nonnullable_vars_walker((Node *) expr->arg, top_level);
1511         }
1512         else if (IsA(node, NullTest))
1513         {
1514                 /* IS NOT NULL can be considered strict, but only at top level */
1515                 NullTest   *expr = (NullTest *) node;
1516
1517                 if (top_level && expr->nulltesttype == IS_NOT_NULL && !expr->argisrow)
1518                         result = find_nonnullable_vars_walker((Node *) expr->arg, false);
1519         }
1520         else if (IsA(node, BooleanTest))
1521         {
1522                 /* Boolean tests that reject NULL are strict at top level */
1523                 BooleanTest *expr = (BooleanTest *) node;
1524
1525                 if (top_level &&
1526                         (expr->booltesttype == IS_TRUE ||
1527                          expr->booltesttype == IS_FALSE ||
1528                          expr->booltesttype == IS_NOT_UNKNOWN))
1529                         result = find_nonnullable_vars_walker((Node *) expr->arg, false);
1530         }
1531         else if (IsA(node, PlaceHolderVar))
1532         {
1533                 PlaceHolderVar *phv = (PlaceHolderVar *) node;
1534
1535                 result = find_nonnullable_vars_walker((Node *) phv->phexpr, top_level);
1536         }
1537         return result;
1538 }
1539
1540 /*
1541  * find_forced_null_vars
1542  *              Determine which Vars must be NULL for the given clause to return TRUE.
1543  *
1544  * This is the complement of find_nonnullable_vars: find the level-zero Vars
1545  * that must be NULL for the clause to return TRUE.  (It is OK to err on the
1546  * side of conservatism; hence the analysis here is simplistic.  In fact,
1547  * we only detect simple "var IS NULL" tests at the top level.)
1548  *
1549  * The result is a palloc'd List, but we have not copied the member Var nodes.
1550  * Also, we don't bother trying to eliminate duplicate entries.
1551  */
1552 List *
1553 find_forced_null_vars(Node *node)
1554 {
1555         List       *result = NIL;
1556         Var                *var;
1557         ListCell   *l;
1558
1559         if (node == NULL)
1560                 return NIL;
1561         /* Check single-clause cases using subroutine */
1562         var = find_forced_null_var(node);
1563         if (var)
1564         {
1565                 result = list_make1(var);
1566         }
1567         /* Otherwise, handle AND-conditions */
1568         else if (IsA(node, List))
1569         {
1570                 /*
1571                  * At top level, we are examining an implicit-AND list: if any of the
1572                  * arms produces FALSE-or-NULL then the result is FALSE-or-NULL.
1573                  */
1574                 foreach(l, (List *) node)
1575                 {
1576                         result = list_concat(result,
1577                                                                  find_forced_null_vars(lfirst(l)));
1578                 }
1579         }
1580         else if (IsA(node, BoolExpr))
1581         {
1582                 BoolExpr   *expr = (BoolExpr *) node;
1583
1584                 /*
1585                  * We don't bother considering the OR case, because it's fairly
1586                  * unlikely anyone would write "v1 IS NULL OR v1 IS NULL". Likewise,
1587                  * the NOT case isn't worth expending code on.
1588                  */
1589                 if (expr->boolop == AND_EXPR)
1590                 {
1591                         /* At top level we can just recurse (to the List case) */
1592                         result = find_forced_null_vars((Node *) expr->args);
1593                 }
1594         }
1595         return result;
1596 }
1597
1598 /*
1599  * find_forced_null_var
1600  *              Return the Var forced null by the given clause, or NULL if it's
1601  *              not an IS NULL-type clause.  For success, the clause must enforce
1602  *              *only* nullness of the particular Var, not any other conditions.
1603  *
1604  * This is just the single-clause case of find_forced_null_vars(), without
1605  * any allowance for AND conditions.  It's used by initsplan.c on individual
1606  * qual clauses.  The reason for not just applying find_forced_null_vars()
1607  * is that if an AND of an IS NULL clause with something else were to somehow
1608  * survive AND/OR flattening, initsplan.c might get fooled into discarding
1609  * the whole clause when only the IS NULL part of it had been proved redundant.
1610  */
1611 Var *
1612 find_forced_null_var(Node *node)
1613 {
1614         if (node == NULL)
1615                 return NULL;
1616         if (IsA(node, NullTest))
1617         {
1618                 /* check for var IS NULL */
1619                 NullTest   *expr = (NullTest *) node;
1620
1621                 if (expr->nulltesttype == IS_NULL && !expr->argisrow)
1622                 {
1623                         Var                *var = (Var *) expr->arg;
1624
1625                         if (var && IsA(var, Var) &&
1626                                 var->varlevelsup == 0)
1627                                 return var;
1628                 }
1629         }
1630         else if (IsA(node, BooleanTest))
1631         {
1632                 /* var IS UNKNOWN is equivalent to var IS NULL */
1633                 BooleanTest *expr = (BooleanTest *) node;
1634
1635                 if (expr->booltesttype == IS_UNKNOWN)
1636                 {
1637                         Var                *var = (Var *) expr->arg;
1638
1639                         if (var && IsA(var, Var) &&
1640                                 var->varlevelsup == 0)
1641                                 return var;
1642                 }
1643         }
1644         return NULL;
1645 }
1646
1647 /*
1648  * Can we treat a ScalarArrayOpExpr as strict?
1649  *
1650  * If "falseOK" is true, then a "false" result can be considered strict,
1651  * else we need to guarantee an actual NULL result for NULL input.
1652  *
1653  * "foo op ALL array" is strict if the op is strict *and* we can prove
1654  * that the array input isn't an empty array.  We can check that
1655  * for the cases of an array constant and an ARRAY[] construct.
1656  *
1657  * "foo op ANY array" is strict in the falseOK sense if the op is strict.
1658  * If not falseOK, the test is the same as for "foo op ALL array".
1659  */
1660 static bool
1661 is_strict_saop(ScalarArrayOpExpr *expr, bool falseOK)
1662 {
1663         Node       *rightop;
1664
1665         /* The contained operator must be strict. */
1666         set_sa_opfuncid(expr);
1667         if (!func_strict(expr->opfuncid))
1668                 return false;
1669         /* If ANY and falseOK, that's all we need to check. */
1670         if (expr->useOr && falseOK)
1671                 return true;
1672         /* Else, we have to see if the array is provably non-empty. */
1673         Assert(list_length(expr->args) == 2);
1674         rightop = (Node *) lsecond(expr->args);
1675         if (rightop && IsA(rightop, Const))
1676         {
1677                 Datum           arraydatum = ((Const *) rightop)->constvalue;
1678                 bool            arrayisnull = ((Const *) rightop)->constisnull;
1679                 ArrayType  *arrayval;
1680                 int                     nitems;
1681
1682                 if (arrayisnull)
1683                         return false;
1684                 arrayval = DatumGetArrayTypeP(arraydatum);
1685                 nitems = ArrayGetNItems(ARR_NDIM(arrayval), ARR_DIMS(arrayval));
1686                 if (nitems > 0)
1687                         return true;
1688         }
1689         else if (rightop && IsA(rightop, ArrayExpr))
1690         {
1691                 ArrayExpr  *arrayexpr = (ArrayExpr *) rightop;
1692
1693                 if (arrayexpr->elements != NIL && !arrayexpr->multidims)
1694                         return true;
1695         }
1696         return false;
1697 }
1698
1699
1700 /*****************************************************************************
1701  *              Check for "pseudo-constant" clauses
1702  *****************************************************************************/
1703
1704 /*
1705  * is_pseudo_constant_clause
1706  *        Detect whether an expression is "pseudo constant", ie, it contains no
1707  *        variables of the current query level and no uses of volatile functions.
1708  *        Such an expr is not necessarily a true constant: it can still contain
1709  *        Params and outer-level Vars, not to mention functions whose results
1710  *        may vary from one statement to the next.      However, the expr's value
1711  *        will be constant over any one scan of the current query, so it can be
1712  *        used as, eg, an indexscan key.
1713  *
1714  * CAUTION: this function omits to test for one very important class of
1715  * not-constant expressions, namely aggregates (Aggrefs).  In current usage
1716  * this is only applied to WHERE clauses and so a check for Aggrefs would be
1717  * a waste of cycles; but be sure to also check contain_agg_clause() if you
1718  * want to know about pseudo-constness in other contexts.  The same goes
1719  * for window functions (WindowFuncs).
1720  */
1721 bool
1722 is_pseudo_constant_clause(Node *clause)
1723 {
1724         /*
1725          * We could implement this check in one recursive scan.  But since the
1726          * check for volatile functions is both moderately expensive and unlikely
1727          * to fail, it seems better to look for Vars first and only check for
1728          * volatile functions if we find no Vars.
1729          */
1730         if (!contain_var_clause(clause) &&
1731                 !contain_volatile_functions(clause))
1732                 return true;
1733         return false;
1734 }
1735
1736 /*
1737  * is_pseudo_constant_clause_relids
1738  *        Same as above, except caller already has available the var membership
1739  *        of the expression; this lets us avoid the contain_var_clause() scan.
1740  */
1741 bool
1742 is_pseudo_constant_clause_relids(Node *clause, Relids relids)
1743 {
1744         if (bms_is_empty(relids) &&
1745                 !contain_volatile_functions(clause))
1746                 return true;
1747         return false;
1748 }
1749
1750
1751 /*****************************************************************************
1752  *                                                                                                                                                       *
1753  *              General clause-manipulating routines                                                             *
1754  *                                                                                                                                                       *
1755  *****************************************************************************/
1756
1757 /*
1758  * NumRelids
1759  *              (formerly clause_relids)
1760  *
1761  * Returns the number of different relations referenced in 'clause'.
1762  */
1763 int
1764 NumRelids(Node *clause)
1765 {
1766         Relids          varnos = pull_varnos(clause);
1767         int                     result = bms_num_members(varnos);
1768
1769         bms_free(varnos);
1770         return result;
1771 }
1772
1773 /*
1774  * CommuteOpExpr: commute a binary operator clause
1775  *
1776  * XXX the clause is destructively modified!
1777  */
1778 void
1779 CommuteOpExpr(OpExpr *clause)
1780 {
1781         Oid                     opoid;
1782         Node       *temp;
1783
1784         /* Sanity checks: caller is at fault if these fail */
1785         if (!is_opclause(clause) ||
1786                 list_length(clause->args) != 2)
1787                 elog(ERROR, "cannot commute non-binary-operator clause");
1788
1789         opoid = get_commutator(clause->opno);
1790
1791         if (!OidIsValid(opoid))
1792                 elog(ERROR, "could not find commutator for operator %u",
1793                          clause->opno);
1794
1795         /*
1796          * modify the clause in-place!
1797          */
1798         clause->opno = opoid;
1799         clause->opfuncid = InvalidOid;
1800         /* opresulttype and opretset are assumed not to change */
1801
1802         temp = linitial(clause->args);
1803         linitial(clause->args) = lsecond(clause->args);
1804         lsecond(clause->args) = temp;
1805 }
1806
1807 /*
1808  * CommuteRowCompareExpr: commute a RowCompareExpr clause
1809  *
1810  * XXX the clause is destructively modified!
1811  */
1812 void
1813 CommuteRowCompareExpr(RowCompareExpr *clause)
1814 {
1815         List       *newops;
1816         List       *temp;
1817         ListCell   *l;
1818
1819         /* Sanity checks: caller is at fault if these fail */
1820         if (!IsA(clause, RowCompareExpr))
1821                 elog(ERROR, "expected a RowCompareExpr");
1822
1823         /* Build list of commuted operators */
1824         newops = NIL;
1825         foreach(l, clause->opnos)
1826         {
1827                 Oid                     opoid = lfirst_oid(l);
1828
1829                 opoid = get_commutator(opoid);
1830                 if (!OidIsValid(opoid))
1831                         elog(ERROR, "could not find commutator for operator %u",
1832                                  lfirst_oid(l));
1833                 newops = lappend_oid(newops, opoid);
1834         }
1835
1836         /*
1837          * modify the clause in-place!
1838          */
1839         switch (clause->rctype)
1840         {
1841                 case ROWCOMPARE_LT:
1842                         clause->rctype = ROWCOMPARE_GT;
1843                         break;
1844                 case ROWCOMPARE_LE:
1845                         clause->rctype = ROWCOMPARE_GE;
1846                         break;
1847                 case ROWCOMPARE_GE:
1848                         clause->rctype = ROWCOMPARE_LE;
1849                         break;
1850                 case ROWCOMPARE_GT:
1851                         clause->rctype = ROWCOMPARE_LT;
1852                         break;
1853                 default:
1854                         elog(ERROR, "unexpected RowCompare type: %d",
1855                                  (int) clause->rctype);
1856                         break;
1857         }
1858
1859         clause->opnos = newops;
1860
1861         /*
1862          * Note: we need not change the opfamilies list; we assume any btree
1863          * opfamily containing an operator will also contain its commutator.
1864          */
1865
1866         temp = clause->largs;
1867         clause->largs = clause->rargs;
1868         clause->rargs = temp;
1869 }
1870
1871 /*
1872  * strip_implicit_coercions: remove implicit coercions at top level of tree
1873  *
1874  * Note: there isn't any useful thing we can do with a RowExpr here, so
1875  * just return it unchanged, even if it's marked as an implicit coercion.
1876  */
1877 Node *
1878 strip_implicit_coercions(Node *node)
1879 {
1880         if (node == NULL)
1881                 return NULL;
1882         if (IsA(node, FuncExpr))
1883         {
1884                 FuncExpr   *f = (FuncExpr *) node;
1885
1886                 if (f->funcformat == COERCE_IMPLICIT_CAST)
1887                         return strip_implicit_coercions(linitial(f->args));
1888         }
1889         else if (IsA(node, RelabelType))
1890         {
1891                 RelabelType *r = (RelabelType *) node;
1892
1893                 if (r->relabelformat == COERCE_IMPLICIT_CAST)
1894                         return strip_implicit_coercions((Node *) r->arg);
1895         }
1896         else if (IsA(node, CoerceViaIO))
1897         {
1898                 CoerceViaIO *c = (CoerceViaIO *) node;
1899
1900                 if (c->coerceformat == COERCE_IMPLICIT_CAST)
1901                         return strip_implicit_coercions((Node *) c->arg);
1902         }
1903         else if (IsA(node, ArrayCoerceExpr))
1904         {
1905                 ArrayCoerceExpr *c = (ArrayCoerceExpr *) node;
1906
1907                 if (c->coerceformat == COERCE_IMPLICIT_CAST)
1908                         return strip_implicit_coercions((Node *) c->arg);
1909         }
1910         else if (IsA(node, ConvertRowtypeExpr))
1911         {
1912                 ConvertRowtypeExpr *c = (ConvertRowtypeExpr *) node;
1913
1914                 if (c->convertformat == COERCE_IMPLICIT_CAST)
1915                         return strip_implicit_coercions((Node *) c->arg);
1916         }
1917         else if (IsA(node, CoerceToDomain))
1918         {
1919                 CoerceToDomain *c = (CoerceToDomain *) node;
1920
1921                 if (c->coercionformat == COERCE_IMPLICIT_CAST)
1922                         return strip_implicit_coercions((Node *) c->arg);
1923         }
1924         return node;
1925 }
1926
1927 /*
1928  * set_coercionform_dontcare: set all CoercionForm fields to COERCE_DONTCARE
1929  *
1930  * This is used to make index expressions and index predicates more easily
1931  * comparable to clauses of queries.  CoercionForm is not semantically
1932  * significant (for cases where it does matter, the significant info is
1933  * coded into the coercion function arguments) so we can ignore it during
1934  * comparisons.  Thus, for example, an index on "foo::int4" can match an
1935  * implicit coercion to int4.
1936  *
1937  * Caution: the passed expression tree is modified in-place.
1938  */
1939 void
1940 set_coercionform_dontcare(Node *node)
1941 {
1942         (void) set_coercionform_dontcare_walker(node, NULL);
1943 }
1944
1945 static bool
1946 set_coercionform_dontcare_walker(Node *node, void *context)
1947 {
1948         if (node == NULL)
1949                 return false;
1950         if (IsA(node, FuncExpr))
1951                 ((FuncExpr *) node)->funcformat = COERCE_DONTCARE;
1952         else if (IsA(node, RelabelType))
1953                 ((RelabelType *) node)->relabelformat = COERCE_DONTCARE;
1954         else if (IsA(node, CoerceViaIO))
1955                 ((CoerceViaIO *) node)->coerceformat = COERCE_DONTCARE;
1956         else if (IsA(node, ArrayCoerceExpr))
1957                 ((ArrayCoerceExpr *) node)->coerceformat = COERCE_DONTCARE;
1958         else if (IsA(node, ConvertRowtypeExpr))
1959                 ((ConvertRowtypeExpr *) node)->convertformat = COERCE_DONTCARE;
1960         else if (IsA(node, RowExpr))
1961                 ((RowExpr *) node)->row_format = COERCE_DONTCARE;
1962         else if (IsA(node, CoerceToDomain))
1963                 ((CoerceToDomain *) node)->coercionformat = COERCE_DONTCARE;
1964         return expression_tree_walker(node, set_coercionform_dontcare_walker,
1965                                                                   context);
1966 }
1967
1968 /*
1969  * Helper for eval_const_expressions: check that datatype of an attribute
1970  * is still what it was when the expression was parsed.  This is needed to
1971  * guard against improper simplification after ALTER COLUMN TYPE.  (XXX we
1972  * may well need to make similar checks elsewhere?)
1973  */
1974 static bool
1975 rowtype_field_matches(Oid rowtypeid, int fieldnum,
1976                                           Oid expectedtype, int32 expectedtypmod)
1977 {
1978         TupleDesc       tupdesc;
1979         Form_pg_attribute attr;
1980
1981         /* No issue for RECORD, since there is no way to ALTER such a type */
1982         if (rowtypeid == RECORDOID)
1983                 return true;
1984         tupdesc = lookup_rowtype_tupdesc(rowtypeid, -1);
1985         if (fieldnum <= 0 || fieldnum > tupdesc->natts)
1986         {
1987                 ReleaseTupleDesc(tupdesc);
1988                 return false;
1989         }
1990         attr = tupdesc->attrs[fieldnum - 1];
1991         if (attr->attisdropped ||
1992                 attr->atttypid != expectedtype ||
1993                 attr->atttypmod != expectedtypmod)
1994         {
1995                 ReleaseTupleDesc(tupdesc);
1996                 return false;
1997         }
1998         ReleaseTupleDesc(tupdesc);
1999         return true;
2000 }
2001
2002
2003 /*--------------------
2004  * eval_const_expressions
2005  *
2006  * Reduce any recognizably constant subexpressions of the given
2007  * expression tree, for example "2 + 2" => "4".  More interestingly,
2008  * we can reduce certain boolean expressions even when they contain
2009  * non-constant subexpressions: "x OR true" => "true" no matter what
2010  * the subexpression x is.      (XXX We assume that no such subexpression
2011  * will have important side-effects, which is not necessarily a good
2012  * assumption in the presence of user-defined functions; do we need a
2013  * pg_proc flag that prevents discarding the execution of a function?)
2014  *
2015  * We do understand that certain functions may deliver non-constant
2016  * results even with constant inputs, "nextval()" being the classic
2017  * example.  Functions that are not marked "immutable" in pg_proc
2018  * will not be pre-evaluated here, although we will reduce their
2019  * arguments as far as possible.
2020  *
2021  * Whenever a function is eliminated from the expression by means of
2022  * constant-expression evaluation or inlining, we add the function to
2023  * root->glob->invalItems.  This ensures the plan is known to depend on
2024  * such functions, even though they aren't referenced anymore.
2025  *
2026  * We assume that the tree has already been type-checked and contains
2027  * only operators and functions that are reasonable to try to execute.
2028  *
2029  * NOTE: "root" can be passed as NULL if the caller never wants to do any
2030  * Param substitutions nor receive info about inlined functions.
2031  *
2032  * NOTE: the planner assumes that this will always flatten nested AND and
2033  * OR clauses into N-argument form.  See comments in prepqual.c.
2034  *
2035  * NOTE: another critical effect is that any function calls that require
2036  * default arguments will be expanded, and named-argument calls will be
2037  * converted to positional notation.  The executor won't handle either.
2038  *--------------------
2039  */
2040 Node *
2041 eval_const_expressions(PlannerInfo *root, Node *node)
2042 {
2043         eval_const_expressions_context context;
2044
2045         if (root)
2046         {
2047                 context.boundParams = root->glob->boundParams;  /* bound Params */
2048                 context.glob = root->glob;              /* for inlined-function dependencies */
2049         }
2050         else
2051         {
2052                 context.boundParams = NULL;
2053                 context.glob = NULL;
2054         }
2055         context.active_fns = NIL;       /* nothing being recursively simplified */
2056         context.case_val = NULL;        /* no CASE being examined */
2057         context.estimate = false;       /* safe transformations only */
2058         return eval_const_expressions_mutator(node, &context);
2059 }
2060
2061 /*--------------------
2062  * estimate_expression_value
2063  *
2064  * This function attempts to estimate the value of an expression for
2065  * planning purposes.  It is in essence a more aggressive version of
2066  * eval_const_expressions(): we will perform constant reductions that are
2067  * not necessarily 100% safe, but are reasonable for estimation purposes.
2068  *
2069  * Currently the extra steps that are taken in this mode are:
2070  * 1. Substitute values for Params, where a bound Param value has been made
2071  *        available by the caller of planner(), even if the Param isn't marked
2072  *        constant.  This effectively means that we plan using the first supplied
2073  *        value of the Param.
2074  * 2. Fold stable, as well as immutable, functions to constants.
2075  * 3. Reduce PlaceHolderVar nodes to their contained expressions.
2076  *--------------------
2077  */
2078 Node *
2079 estimate_expression_value(PlannerInfo *root, Node *node)
2080 {
2081         eval_const_expressions_context context;
2082
2083         context.boundParams = root->glob->boundParams;          /* bound Params */
2084         /* we do not need to mark the plan as depending on inlined functions */
2085         context.glob = NULL;
2086         context.active_fns = NIL;       /* nothing being recursively simplified */
2087         context.case_val = NULL;        /* no CASE being examined */
2088         context.estimate = true;        /* unsafe transformations OK */
2089         return eval_const_expressions_mutator(node, &context);
2090 }
2091
2092 static Node *
2093 eval_const_expressions_mutator(Node *node,
2094                                                            eval_const_expressions_context *context)
2095 {
2096         if (node == NULL)
2097                 return NULL;
2098         if (IsA(node, Param))
2099         {
2100                 Param      *param = (Param *) node;
2101
2102                 /* Look to see if we've been given a value for this Param */
2103                 if (param->paramkind == PARAM_EXTERN &&
2104                         context->boundParams != NULL &&
2105                         param->paramid > 0 &&
2106                         param->paramid <= context->boundParams->numParams)
2107                 {
2108                         ParamExternData *prm = &context->boundParams->params[param->paramid - 1];
2109
2110                         if (OidIsValid(prm->ptype))
2111                         {
2112                                 /* OK to substitute parameter value? */
2113                                 if (context->estimate || (prm->pflags & PARAM_FLAG_CONST))
2114                                 {
2115                                         /*
2116                                          * Return a Const representing the param value.  Must copy
2117                                          * pass-by-ref datatypes, since the Param might be in a
2118                                          * memory context shorter-lived than our output plan
2119                                          * should be.
2120                                          */
2121                                         int16           typLen;
2122                                         bool            typByVal;
2123                                         Datum           pval;
2124
2125                                         Assert(prm->ptype == param->paramtype);
2126                                         get_typlenbyval(param->paramtype, &typLen, &typByVal);
2127                                         if (prm->isnull || typByVal)
2128                                                 pval = prm->value;
2129                                         else
2130                                                 pval = datumCopy(prm->value, typByVal, typLen);
2131                                         return (Node *) makeConst(param->paramtype,
2132                                                                                           param->paramtypmod,
2133                                                                                           (int) typLen,
2134                                                                                           pval,
2135                                                                                           prm->isnull,
2136                                                                                           typByVal);
2137                                 }
2138                         }
2139                 }
2140                 /* Not replaceable, so just copy the Param (no need to recurse) */
2141                 return (Node *) copyObject(param);
2142         }
2143         if (IsA(node, FuncExpr))
2144         {
2145                 FuncExpr   *expr = (FuncExpr *) node;
2146                 List       *args;
2147                 bool            has_named_args;
2148                 Expr       *simple;
2149                 FuncExpr   *newexpr;
2150                 ListCell   *lc;
2151
2152                 /*
2153                  * Reduce constants in the FuncExpr's arguments, and check to see if
2154                  * there are any named args.
2155                  */
2156                 args = NIL;
2157                 has_named_args = false;
2158                 foreach(lc, expr->args)
2159                 {
2160                         Node       *arg = (Node *) lfirst(lc);
2161
2162                         arg = eval_const_expressions_mutator(arg, context);
2163                         if (IsA(arg, NamedArgExpr))
2164                                 has_named_args = true;
2165                         args = lappend(args, arg);
2166                 }
2167
2168                 /*
2169                  * Code for op/func reduction is pretty bulky, so split it out as a
2170                  * separate function.  Note: exprTypmod normally returns -1 for a
2171                  * FuncExpr, but not when the node is recognizably a length coercion;
2172                  * we want to preserve the typmod in the eventual Const if so.
2173                  */
2174                 simple = simplify_function(expr->funcid,
2175                                                                    expr->funcresulttype, exprTypmod(node),
2176                                                                    &args,
2177                                                                    has_named_args, true, context);
2178                 if (simple)                             /* successfully simplified it */
2179                         return (Node *) simple;
2180
2181                 /*
2182                  * The expression cannot be simplified any further, so build and
2183                  * return a replacement FuncExpr node using the possibly-simplified
2184                  * arguments.  Note that we have also converted the argument list to
2185                  * positional notation.
2186                  */
2187                 newexpr = makeNode(FuncExpr);
2188                 newexpr->funcid = expr->funcid;
2189                 newexpr->funcresulttype = expr->funcresulttype;
2190                 newexpr->funcretset = expr->funcretset;
2191                 newexpr->funcformat = expr->funcformat;
2192                 newexpr->args = args;
2193                 newexpr->location = expr->location;
2194                 return (Node *) newexpr;
2195         }
2196         if (IsA(node, OpExpr))
2197         {
2198                 OpExpr     *expr = (OpExpr *) node;
2199                 List       *args;
2200                 Expr       *simple;
2201                 OpExpr     *newexpr;
2202
2203                 /*
2204                  * Reduce constants in the OpExpr's arguments.  We know args is either
2205                  * NIL or a List node, so we can call expression_tree_mutator directly
2206                  * rather than recursing to self.
2207                  */
2208                 args = (List *) expression_tree_mutator((Node *) expr->args,
2209                                                                                           eval_const_expressions_mutator,
2210                                                                                                 (void *) context);
2211
2212                 /*
2213                  * Need to get OID of underlying function.      Okay to scribble on input
2214                  * to this extent.
2215                  */
2216                 set_opfuncid(expr);
2217
2218                 /*
2219                  * Code for op/func reduction is pretty bulky, so split it out as a
2220                  * separate function.
2221                  */
2222                 simple = simplify_function(expr->opfuncid,
2223                                                                    expr->opresulttype, -1,
2224                                                                    &args,
2225                                                                    false, true, context);
2226                 if (simple)                             /* successfully simplified it */
2227                         return (Node *) simple;
2228
2229                 /*
2230                  * If the operator is boolean equality or inequality, we know how to
2231                  * simplify cases involving one constant and one non-constant
2232                  * argument.
2233                  */
2234                 if (expr->opno == BooleanEqualOperator ||
2235                         expr->opno == BooleanNotEqualOperator)
2236                 {
2237                         simple = (Expr *) simplify_boolean_equality(expr->opno, args);
2238                         if (simple)                     /* successfully simplified it */
2239                                 return (Node *) simple;
2240                 }
2241
2242                 /*
2243                  * The expression cannot be simplified any further, so build and
2244                  * return a replacement OpExpr node using the possibly-simplified
2245                  * arguments.
2246                  */
2247                 newexpr = makeNode(OpExpr);
2248                 newexpr->opno = expr->opno;
2249                 newexpr->opfuncid = expr->opfuncid;
2250                 newexpr->opresulttype = expr->opresulttype;
2251                 newexpr->opretset = expr->opretset;
2252                 newexpr->args = args;
2253                 newexpr->location = expr->location;
2254                 return (Node *) newexpr;
2255         }
2256         if (IsA(node, DistinctExpr))
2257         {
2258                 DistinctExpr *expr = (DistinctExpr *) node;
2259                 List       *args;
2260                 ListCell   *arg;
2261                 bool            has_null_input = false;
2262                 bool            all_null_input = true;
2263                 bool            has_nonconst_input = false;
2264                 Expr       *simple;
2265                 DistinctExpr *newexpr;
2266
2267                 /*
2268                  * Reduce constants in the DistinctExpr's arguments.  We know args is
2269                  * either NIL or a List node, so we can call expression_tree_mutator
2270                  * directly rather than recursing to self.
2271                  */
2272                 args = (List *) expression_tree_mutator((Node *) expr->args,
2273                                                                                           eval_const_expressions_mutator,
2274                                                                                                 (void *) context);
2275
2276                 /*
2277                  * We must do our own check for NULLs because DistinctExpr has
2278                  * different results for NULL input than the underlying operator does.
2279                  */
2280                 foreach(arg, args)
2281                 {
2282                         if (IsA(lfirst(arg), Const))
2283                         {
2284                                 has_null_input |= ((Const *) lfirst(arg))->constisnull;
2285                                 all_null_input &= ((Const *) lfirst(arg))->constisnull;
2286                         }
2287                         else
2288                                 has_nonconst_input = true;
2289                 }
2290
2291                 /* all constants? then can optimize this out */
2292                 if (!has_nonconst_input)
2293                 {
2294                         /* all nulls? then not distinct */
2295                         if (all_null_input)
2296                                 return makeBoolConst(false, false);
2297
2298                         /* one null? then distinct */
2299                         if (has_null_input)
2300                                 return makeBoolConst(true, false);
2301
2302                         /* otherwise try to evaluate the '=' operator */
2303                         /* (NOT okay to try to inline it, though!) */
2304
2305                         /*
2306                          * Need to get OID of underlying function.      Okay to scribble on
2307                          * input to this extent.
2308                          */
2309                         set_opfuncid((OpExpr *) expr);          /* rely on struct equivalence */
2310
2311                         /*
2312                          * Code for op/func reduction is pretty bulky, so split it out as
2313                          * a separate function.
2314                          */
2315                         simple = simplify_function(expr->opfuncid,
2316                                                                            expr->opresulttype, -1,
2317                                                                            &args,
2318                                                                            false, false, context);
2319                         if (simple)                     /* successfully simplified it */
2320                         {
2321                                 /*
2322                                  * Since the underlying operator is "=", must negate its
2323                                  * result
2324                                  */
2325                                 Const      *csimple = (Const *) simple;
2326
2327                                 Assert(IsA(csimple, Const));
2328                                 csimple->constvalue =
2329                                         BoolGetDatum(!DatumGetBool(csimple->constvalue));
2330                                 return (Node *) csimple;
2331                         }
2332                 }
2333
2334                 /*
2335                  * The expression cannot be simplified any further, so build and
2336                  * return a replacement DistinctExpr node using the
2337                  * possibly-simplified arguments.
2338                  */
2339                 newexpr = makeNode(DistinctExpr);
2340                 newexpr->opno = expr->opno;
2341                 newexpr->opfuncid = expr->opfuncid;
2342                 newexpr->opresulttype = expr->opresulttype;
2343                 newexpr->opretset = expr->opretset;
2344                 newexpr->args = args;
2345                 newexpr->location = expr->location;
2346                 return (Node *) newexpr;
2347         }
2348         if (IsA(node, BoolExpr))
2349         {
2350                 BoolExpr   *expr = (BoolExpr *) node;
2351
2352                 switch (expr->boolop)
2353                 {
2354                         case OR_EXPR:
2355                                 {
2356                                         List       *newargs;
2357                                         bool            haveNull = false;
2358                                         bool            forceTrue = false;
2359
2360                                         newargs = simplify_or_arguments(expr->args, context,
2361                                                                                                         &haveNull, &forceTrue);
2362                                         if (forceTrue)
2363                                                 return makeBoolConst(true, false);
2364                                         if (haveNull)
2365                                                 newargs = lappend(newargs, makeBoolConst(false, true));
2366                                         /* If all the inputs are FALSE, result is FALSE */
2367                                         if (newargs == NIL)
2368                                                 return makeBoolConst(false, false);
2369                                         /* If only one nonconst-or-NULL input, it's the result */
2370                                         if (list_length(newargs) == 1)
2371                                                 return (Node *) linitial(newargs);
2372                                         /* Else we still need an OR node */
2373                                         return (Node *) make_orclause(newargs);
2374                                 }
2375                         case AND_EXPR:
2376                                 {
2377                                         List       *newargs;
2378                                         bool            haveNull = false;
2379                                         bool            forceFalse = false;
2380
2381                                         newargs = simplify_and_arguments(expr->args, context,
2382                                                                                                          &haveNull, &forceFalse);
2383                                         if (forceFalse)
2384                                                 return makeBoolConst(false, false);
2385                                         if (haveNull)
2386                                                 newargs = lappend(newargs, makeBoolConst(false, true));
2387                                         /* If all the inputs are TRUE, result is TRUE */
2388                                         if (newargs == NIL)
2389                                                 return makeBoolConst(true, false);
2390                                         /* If only one nonconst-or-NULL input, it's the result */
2391                                         if (list_length(newargs) == 1)
2392                                                 return (Node *) linitial(newargs);
2393                                         /* Else we still need an AND node */
2394                                         return (Node *) make_andclause(newargs);
2395                                 }
2396                         case NOT_EXPR:
2397                                 {
2398                                         Node       *arg;
2399
2400                                         Assert(list_length(expr->args) == 1);
2401                                         arg = eval_const_expressions_mutator(linitial(expr->args),
2402                                                                                                                  context);
2403
2404                                         /*
2405                                          * Use negate_clause() to see if we can simplify away
2406                                          * the NOT.
2407                                          */
2408                                         return negate_clause(arg);
2409                                 }
2410                         default:
2411                                 elog(ERROR, "unrecognized boolop: %d",
2412                                          (int) expr->boolop);
2413                                 break;
2414                 }
2415         }
2416         if (IsA(node, SubPlan) ||
2417                 IsA(node, AlternativeSubPlan))
2418         {
2419                 /*
2420                  * Return a SubPlan unchanged --- too late to do anything with it.
2421                  *
2422                  * XXX should we ereport() here instead?  Probably this routine should
2423                  * never be invoked after SubPlan creation.
2424                  */
2425                 return node;
2426         }
2427         if (IsA(node, RelabelType))
2428         {
2429                 /*
2430                  * If we can simplify the input to a constant, then we don't need the
2431                  * RelabelType node anymore: just change the type field of the Const
2432                  * node.  Otherwise, must copy the RelabelType node.
2433                  */
2434                 RelabelType *relabel = (RelabelType *) node;
2435                 Node       *arg;
2436
2437                 arg = eval_const_expressions_mutator((Node *) relabel->arg,
2438                                                                                          context);
2439
2440                 /*
2441                  * If we find stacked RelabelTypes (eg, from foo :: int :: oid) we can
2442                  * discard all but the top one.
2443                  */
2444                 while (arg && IsA(arg, RelabelType))
2445                         arg = (Node *) ((RelabelType *) arg)->arg;
2446
2447                 if (arg && IsA(arg, Const))
2448                 {
2449                         Const      *con = (Const *) arg;
2450
2451                         con->consttype = relabel->resulttype;
2452                         con->consttypmod = relabel->resulttypmod;
2453                         return (Node *) con;
2454                 }
2455                 else
2456                 {
2457                         RelabelType *newrelabel = makeNode(RelabelType);
2458
2459                         newrelabel->arg = (Expr *) arg;
2460                         newrelabel->resulttype = relabel->resulttype;
2461                         newrelabel->resulttypmod = relabel->resulttypmod;
2462                         newrelabel->relabelformat = relabel->relabelformat;
2463                         newrelabel->location = relabel->location;
2464                         return (Node *) newrelabel;
2465                 }
2466         }
2467         if (IsA(node, CoerceViaIO))
2468         {
2469                 CoerceViaIO *expr = (CoerceViaIO *) node;
2470                 Expr       *arg;
2471                 List       *args;
2472                 Oid                     outfunc;
2473                 bool            outtypisvarlena;
2474                 Oid                     infunc;
2475                 Oid                     intypioparam;
2476                 Expr       *simple;
2477                 CoerceViaIO *newexpr;
2478
2479                 /*
2480                  * Reduce constants in the CoerceViaIO's argument.
2481                  */
2482                 arg = (Expr *) eval_const_expressions_mutator((Node *) expr->arg,
2483                                                                                                           context);
2484                 args = list_make1(arg);
2485
2486                 /*
2487                  * CoerceViaIO represents calling the source type's output function
2488                  * then the result type's input function.  So, try to simplify it as
2489                  * though it were a stack of two such function calls.  First we need
2490                  * to know what the functions are.
2491                  */
2492                 getTypeOutputInfo(exprType((Node *) arg), &outfunc, &outtypisvarlena);
2493                 getTypeInputInfo(expr->resulttype, &infunc, &intypioparam);
2494
2495                 simple = simplify_function(outfunc,
2496                                                                    CSTRINGOID, -1,
2497                                                                    &args,
2498                                                                    false, true, context);
2499                 if (simple)                             /* successfully simplified output fn */
2500                 {
2501                         /*
2502                          * Input functions may want 1 to 3 arguments.  We always supply
2503                          * all three, trusting that nothing downstream will complain.
2504                          */
2505                         args = list_make3(simple,
2506                                                           makeConst(OIDOID, -1, sizeof(Oid),
2507                                                                                 ObjectIdGetDatum(intypioparam),
2508                                                                                 false, true),
2509                                                           makeConst(INT4OID, -1, sizeof(int32),
2510                                                                                 Int32GetDatum(-1),
2511                                                                                 false, true));
2512
2513                         simple = simplify_function(infunc,
2514                                                                            expr->resulttype, -1,
2515                                                                            &args,
2516                                                                            false, true, context);
2517                         if (simple)                     /* successfully simplified input fn */
2518                                 return (Node *) simple;
2519                 }
2520
2521                 /*
2522                  * The expression cannot be simplified any further, so build and
2523                  * return a replacement CoerceViaIO node using the possibly-simplified
2524                  * argument.
2525                  */
2526                 newexpr = makeNode(CoerceViaIO);
2527                 newexpr->arg = arg;
2528                 newexpr->resulttype = expr->resulttype;
2529                 newexpr->coerceformat = expr->coerceformat;
2530                 newexpr->location = expr->location;
2531                 return (Node *) newexpr;
2532         }
2533         if (IsA(node, ArrayCoerceExpr))
2534         {
2535                 ArrayCoerceExpr *expr = (ArrayCoerceExpr *) node;
2536                 Expr       *arg;
2537                 ArrayCoerceExpr *newexpr;
2538
2539                 /*
2540                  * Reduce constants in the ArrayCoerceExpr's argument, then build a
2541                  * new ArrayCoerceExpr.
2542                  */
2543                 arg = (Expr *) eval_const_expressions_mutator((Node *) expr->arg,
2544                                                                                                           context);
2545
2546                 newexpr = makeNode(ArrayCoerceExpr);
2547                 newexpr->arg = arg;
2548                 newexpr->elemfuncid = expr->elemfuncid;
2549                 newexpr->resulttype = expr->resulttype;
2550                 newexpr->resulttypmod = expr->resulttypmod;
2551                 newexpr->isExplicit = expr->isExplicit;
2552                 newexpr->coerceformat = expr->coerceformat;
2553                 newexpr->location = expr->location;
2554
2555                 /*
2556                  * If constant argument and it's a binary-coercible or immutable
2557                  * conversion, we can simplify it to a constant.
2558                  */
2559                 if (arg && IsA(arg, Const) &&
2560                         (!OidIsValid(newexpr->elemfuncid) ||
2561                          func_volatile(newexpr->elemfuncid) == PROVOLATILE_IMMUTABLE))
2562                         return (Node *) evaluate_expr((Expr *) newexpr,
2563                                                                                   newexpr->resulttype,
2564                                                                                   newexpr->resulttypmod);
2565
2566                 /* Else we must return the partially-simplified node */
2567                 return (Node *) newexpr;
2568         }
2569         if (IsA(node, CaseExpr))
2570         {
2571                 /*----------
2572                  * CASE expressions can be simplified if there are constant
2573                  * condition clauses:
2574                  *              FALSE (or NULL): drop the alternative
2575                  *              TRUE: drop all remaining alternatives
2576                  * If the first non-FALSE alternative is a constant TRUE, we can
2577                  * simplify the entire CASE to that alternative's expression.
2578                  * If there are no non-FALSE alternatives, we simplify the entire
2579                  * CASE to the default result (ELSE result).
2580                  *
2581                  * If we have a simple-form CASE with constant test expression,
2582                  * we substitute the constant value for contained CaseTestExpr
2583                  * placeholder nodes, so that we have the opportunity to reduce
2584                  * constant test conditions.  For example this allows
2585                  *              CASE 0 WHEN 0 THEN 1 ELSE 1/0 END
2586                  * to reduce to 1 rather than drawing a divide-by-0 error.
2587                  *----------
2588                  */
2589                 CaseExpr   *caseexpr = (CaseExpr *) node;
2590                 CaseExpr   *newcase;
2591                 Node       *save_case_val;
2592                 Node       *newarg;
2593                 List       *newargs;
2594                 bool            const_true_cond;
2595                 Node       *defresult = NULL;
2596                 ListCell   *arg;
2597
2598                 /* Simplify the test expression, if any */
2599                 newarg = eval_const_expressions_mutator((Node *) caseexpr->arg,
2600                                                                                                 context);
2601
2602                 /* Set up for contained CaseTestExpr nodes */
2603                 save_case_val = context->case_val;
2604                 if (newarg && IsA(newarg, Const))
2605                         context->case_val = newarg;
2606                 else
2607                         context->case_val = NULL;
2608
2609                 /* Simplify the WHEN clauses */
2610                 newargs = NIL;
2611                 const_true_cond = false;
2612                 foreach(arg, caseexpr->args)
2613                 {
2614                         CaseWhen   *oldcasewhen = (CaseWhen *) lfirst(arg);
2615                         Node       *casecond;
2616                         Node       *caseresult;
2617
2618                         Assert(IsA(oldcasewhen, CaseWhen));
2619
2620                         /* Simplify this alternative's test condition */
2621                         casecond =
2622                                 eval_const_expressions_mutator((Node *) oldcasewhen->expr,
2623                                                                                            context);
2624
2625                         /*
2626                          * If the test condition is constant FALSE (or NULL), then drop
2627                          * this WHEN clause completely, without processing the result.
2628                          */
2629                         if (casecond && IsA(casecond, Const))
2630                         {
2631                                 Const      *const_input = (Const *) casecond;
2632
2633                                 if (const_input->constisnull ||
2634                                         !DatumGetBool(const_input->constvalue))
2635                                         continue;       /* drop alternative with FALSE condition */
2636                                 /* Else it's constant TRUE */
2637                                 const_true_cond = true;
2638                         }
2639
2640                         /* Simplify this alternative's result value */
2641                         caseresult =
2642                                 eval_const_expressions_mutator((Node *) oldcasewhen->result,
2643                                                                                            context);
2644
2645                         /* If non-constant test condition, emit a new WHEN node */
2646                         if (!const_true_cond)
2647                         {
2648                                 CaseWhen   *newcasewhen = makeNode(CaseWhen);
2649
2650                                 newcasewhen->expr = (Expr *) casecond;
2651                                 newcasewhen->result = (Expr *) caseresult;
2652                                 newcasewhen->location = oldcasewhen->location;
2653                                 newargs = lappend(newargs, newcasewhen);
2654                                 continue;
2655                         }
2656
2657                         /*
2658                          * Found a TRUE condition, so none of the remaining alternatives
2659                          * can be reached.      We treat the result as the default result.
2660                          */
2661                         defresult = caseresult;
2662                         break;
2663                 }
2664
2665                 /* Simplify the default result, unless we replaced it above */
2666                 if (!const_true_cond)
2667                         defresult =
2668                                 eval_const_expressions_mutator((Node *) caseexpr->defresult,
2669                                                                                            context);
2670
2671                 context->case_val = save_case_val;
2672
2673                 /* If no non-FALSE alternatives, CASE reduces to the default result */
2674                 if (newargs == NIL)
2675                         return defresult;
2676                 /* Otherwise we need a new CASE node */
2677                 newcase = makeNode(CaseExpr);
2678                 newcase->casetype = caseexpr->casetype;
2679                 newcase->arg = (Expr *) newarg;
2680                 newcase->args = newargs;
2681                 newcase->defresult = (Expr *) defresult;
2682                 newcase->location = caseexpr->location;
2683                 return (Node *) newcase;
2684         }
2685         if (IsA(node, CaseTestExpr))
2686         {
2687                 /*
2688                  * If we know a constant test value for the current CASE construct,
2689                  * substitute it for the placeholder.  Else just return the
2690                  * placeholder as-is.
2691                  */
2692                 if (context->case_val)
2693                         return copyObject(context->case_val);
2694                 else
2695                         return copyObject(node);
2696         }
2697         if (IsA(node, ArrayExpr))
2698         {
2699                 ArrayExpr  *arrayexpr = (ArrayExpr *) node;
2700                 ArrayExpr  *newarray;
2701                 bool            all_const = true;
2702                 List       *newelems;
2703                 ListCell   *element;
2704
2705                 newelems = NIL;
2706                 foreach(element, arrayexpr->elements)
2707                 {
2708                         Node       *e;
2709
2710                         e = eval_const_expressions_mutator((Node *) lfirst(element),
2711                                                                                            context);
2712                         if (!IsA(e, Const))
2713                                 all_const = false;
2714                         newelems = lappend(newelems, e);
2715                 }
2716
2717                 newarray = makeNode(ArrayExpr);
2718                 newarray->array_typeid = arrayexpr->array_typeid;
2719                 newarray->element_typeid = arrayexpr->element_typeid;
2720                 newarray->elements = newelems;
2721                 newarray->multidims = arrayexpr->multidims;
2722                 newarray->location = arrayexpr->location;
2723
2724                 if (all_const)
2725                         return (Node *) evaluate_expr((Expr *) newarray,
2726                                                                                   newarray->array_typeid,
2727                                                                                   exprTypmod(node));
2728
2729                 return (Node *) newarray;
2730         }
2731         if (IsA(node, CoalesceExpr))
2732         {
2733                 CoalesceExpr *coalesceexpr = (CoalesceExpr *) node;
2734                 CoalesceExpr *newcoalesce;
2735                 List       *newargs;
2736                 ListCell   *arg;
2737
2738                 newargs = NIL;
2739                 foreach(arg, coalesceexpr->args)
2740                 {
2741                         Node       *e;
2742
2743                         e = eval_const_expressions_mutator((Node *) lfirst(arg),
2744                                                                                            context);
2745
2746                         /*
2747                          * We can remove null constants from the list. For a non-null
2748                          * constant, if it has not been preceded by any other
2749                          * non-null-constant expressions then it is the result.  Otherwise,
2750                          * it's the next argument, but we can drop following arguments
2751                          * since they will never be reached.
2752                          */
2753                         if (IsA(e, Const))
2754                         {
2755                                 if (((Const *) e)->constisnull)
2756                                         continue;       /* drop null constant */
2757                                 if (newargs == NIL)
2758                                         return e;       /* first expr */
2759                                 newargs = lappend(newargs, e);
2760                                 break;
2761                         }
2762                         newargs = lappend(newargs, e);
2763                 }
2764
2765                 /* If all the arguments were constant null, the result is just null */
2766                 if (newargs == NIL)
2767                         return (Node *) makeNullConst(coalesceexpr->coalescetype, -1);
2768
2769                 newcoalesce = makeNode(CoalesceExpr);
2770                 newcoalesce->coalescetype = coalesceexpr->coalescetype;
2771                 newcoalesce->args = newargs;
2772                 newcoalesce->location = coalesceexpr->location;
2773                 return (Node *) newcoalesce;
2774         }
2775         if (IsA(node, FieldSelect))
2776         {
2777                 /*
2778                  * We can optimize field selection from a whole-row Var into a simple
2779                  * Var.  (This case won't be generated directly by the parser, because
2780                  * ParseComplexProjection short-circuits it. But it can arise while
2781                  * simplifying functions.)      Also, we can optimize field selection from
2782                  * a RowExpr construct.
2783                  *
2784                  * We must however check that the declared type of the field is still
2785                  * the same as when the FieldSelect was created --- this can change if
2786                  * someone did ALTER COLUMN TYPE on the rowtype.
2787                  */
2788                 FieldSelect *fselect = (FieldSelect *) node;
2789                 FieldSelect *newfselect;
2790                 Node       *arg;
2791
2792                 arg = eval_const_expressions_mutator((Node *) fselect->arg,
2793                                                                                          context);
2794                 if (arg && IsA(arg, Var) &&
2795                         ((Var *) arg)->varattno == InvalidAttrNumber)
2796                 {
2797                         if (rowtype_field_matches(((Var *) arg)->vartype,
2798                                                                           fselect->fieldnum,
2799                                                                           fselect->resulttype,
2800                                                                           fselect->resulttypmod))
2801                                 return (Node *) makeVar(((Var *) arg)->varno,
2802                                                                                 fselect->fieldnum,
2803                                                                                 fselect->resulttype,
2804                                                                                 fselect->resulttypmod,
2805                                                                                 ((Var *) arg)->varlevelsup);
2806                 }
2807                 if (arg && IsA(arg, RowExpr))
2808                 {
2809                         RowExpr    *rowexpr = (RowExpr *) arg;
2810
2811                         if (fselect->fieldnum > 0 &&
2812                                 fselect->fieldnum <= list_length(rowexpr->args))
2813                         {
2814                                 Node       *fld = (Node *) list_nth(rowexpr->args,
2815                                                                                                         fselect->fieldnum - 1);
2816
2817                                 if (rowtype_field_matches(rowexpr->row_typeid,
2818                                                                                   fselect->fieldnum,
2819                                                                                   fselect->resulttype,
2820                                                                                   fselect->resulttypmod) &&
2821                                         fselect->resulttype == exprType(fld) &&
2822                                         fselect->resulttypmod == exprTypmod(fld))
2823                                         return fld;
2824                         }
2825                 }
2826                 newfselect = makeNode(FieldSelect);
2827                 newfselect->arg = (Expr *) arg;
2828                 newfselect->fieldnum = fselect->fieldnum;
2829                 newfselect->resulttype = fselect->resulttype;
2830                 newfselect->resulttypmod = fselect->resulttypmod;
2831                 return (Node *) newfselect;
2832         }
2833         if (IsA(node, NullTest))
2834         {
2835                 NullTest   *ntest = (NullTest *) node;
2836                 NullTest   *newntest;
2837                 Node       *arg;
2838
2839                 arg = eval_const_expressions_mutator((Node *) ntest->arg,
2840                                                                                          context);
2841                 if (arg && IsA(arg, RowExpr))
2842                 {
2843                         /*
2844                          * We break ROW(...) IS [NOT] NULL into separate tests on its
2845                          * component fields.  This form is usually more efficient to
2846                          * evaluate, as well as being more amenable to optimization.
2847                          */
2848                         RowExpr    *rarg = (RowExpr *) arg;
2849                         List       *newargs = NIL;
2850                         ListCell   *l;
2851
2852                         Assert(ntest->argisrow);
2853
2854                         foreach(l, rarg->args)
2855                         {
2856                                 Node       *relem = (Node *) lfirst(l);
2857
2858                                 /*
2859                                  * A constant field refutes the whole NullTest if it's of the
2860                                  * wrong nullness; else we can discard it.
2861                                  */
2862                                 if (relem && IsA(relem, Const))
2863                                 {
2864                                         Const      *carg = (Const *) relem;
2865
2866                                         if (carg->constisnull ?
2867                                                 (ntest->nulltesttype == IS_NOT_NULL) :
2868                                                 (ntest->nulltesttype == IS_NULL))
2869                                                 return makeBoolConst(false, false);
2870                                         continue;
2871                                 }
2872                                 newntest = makeNode(NullTest);
2873                                 newntest->arg = (Expr *) relem;
2874                                 newntest->nulltesttype = ntest->nulltesttype;
2875                                 newntest->argisrow = type_is_rowtype(exprType(relem));
2876                                 newargs = lappend(newargs, newntest);
2877                         }
2878                         /* If all the inputs were constants, result is TRUE */
2879                         if (newargs == NIL)
2880                                 return makeBoolConst(true, false);
2881                         /* If only one nonconst input, it's the result */
2882                         if (list_length(newargs) == 1)
2883                                 return (Node *) linitial(newargs);
2884                         /* Else we need an AND node */
2885                         return (Node *) make_andclause(newargs);
2886                 }
2887                 if (!ntest->argisrow && arg && IsA(arg, Const))
2888                 {
2889                         Const      *carg = (Const *) arg;
2890                         bool            result;
2891
2892                         switch (ntest->nulltesttype)
2893                         {
2894                                 case IS_NULL:
2895                                         result = carg->constisnull;
2896                                         break;
2897                                 case IS_NOT_NULL:
2898                                         result = !carg->constisnull;
2899                                         break;
2900                                 default:
2901                                         elog(ERROR, "unrecognized nulltesttype: %d",
2902                                                  (int) ntest->nulltesttype);
2903                                         result = false;         /* keep compiler quiet */
2904                                         break;
2905                         }
2906
2907                         return makeBoolConst(result, false);
2908                 }
2909
2910                 newntest = makeNode(NullTest);
2911                 newntest->arg = (Expr *) arg;
2912                 newntest->nulltesttype = ntest->nulltesttype;
2913                 newntest->argisrow = ntest->argisrow;
2914                 return (Node *) newntest;
2915         }
2916         if (IsA(node, BooleanTest))
2917         {
2918                 BooleanTest *btest = (BooleanTest *) node;
2919                 BooleanTest *newbtest;
2920                 Node       *arg;
2921
2922                 arg = eval_const_expressions_mutator((Node *) btest->arg,
2923                                                                                          context);
2924                 if (arg && IsA(arg, Const))
2925                 {
2926                         Const      *carg = (Const *) arg;
2927                         bool            result;
2928
2929                         switch (btest->booltesttype)
2930                         {
2931                                 case IS_TRUE:
2932                                         result = (!carg->constisnull &&
2933                                                           DatumGetBool(carg->constvalue));
2934                                         break;
2935                                 case IS_NOT_TRUE:
2936                                         result = (carg->constisnull ||
2937                                                           !DatumGetBool(carg->constvalue));
2938                                         break;
2939                                 case IS_FALSE:
2940                                         result = (!carg->constisnull &&
2941                                                           !DatumGetBool(carg->constvalue));
2942                                         break;
2943                                 case IS_NOT_FALSE:
2944                                         result = (carg->constisnull ||
2945                                                           DatumGetBool(carg->constvalue));
2946                                         break;
2947                                 case IS_UNKNOWN:
2948                                         result = carg->constisnull;
2949                                         break;
2950                                 case IS_NOT_UNKNOWN:
2951                                         result = !carg->constisnull;
2952                                         break;
2953                                 default:
2954                                         elog(ERROR, "unrecognized booltesttype: %d",
2955                                                  (int) btest->booltesttype);
2956                                         result = false;         /* keep compiler quiet */
2957                                         break;
2958                         }
2959
2960                         return makeBoolConst(result, false);
2961                 }
2962
2963                 newbtest = makeNode(BooleanTest);
2964                 newbtest->arg = (Expr *) arg;
2965                 newbtest->booltesttype = btest->booltesttype;
2966                 return (Node *) newbtest;
2967         }
2968         if (IsA(node, PlaceHolderVar) &&context->estimate)
2969         {
2970                 /*
2971                  * In estimation mode, just strip the PlaceHolderVar node altogether;
2972                  * this amounts to estimating that the contained value won't be forced
2973                  * to null by an outer join.  In regular mode we just use the default
2974                  * behavior (ie, simplify the expression but leave the PlaceHolderVar
2975                  * node intact).
2976                  */
2977                 PlaceHolderVar *phv = (PlaceHolderVar *) node;
2978
2979                 return eval_const_expressions_mutator((Node *) phv->phexpr,
2980                                                                                           context);
2981         }
2982
2983         /*
2984          * For any node type not handled above, we recurse using
2985          * expression_tree_mutator, which will copy the node unchanged but try to
2986          * simplify its arguments (if any) using this routine. For example: we
2987          * cannot eliminate an ArrayRef node, but we might be able to simplify
2988          * constant expressions in its subscripts.
2989          */
2990         return expression_tree_mutator(node, eval_const_expressions_mutator,
2991                                                                    (void *) context);
2992 }
2993
2994 /*
2995  * Subroutine for eval_const_expressions: process arguments of an OR clause
2996  *
2997  * This includes flattening of nested ORs as well as recursion to
2998  * eval_const_expressions to simplify the OR arguments.
2999  *
3000  * After simplification, OR arguments are handled as follows:
3001  *              non constant: keep
3002  *              FALSE: drop (does not affect result)
3003  *              TRUE: force result to TRUE
3004  *              NULL: keep only one
3005  * We must keep one NULL input because ExecEvalOr returns NULL when no input
3006  * is TRUE and at least one is NULL.  We don't actually include the NULL
3007  * here, that's supposed to be done by the caller.
3008  *
3009  * The output arguments *haveNull and *forceTrue must be initialized FALSE
3010  * by the caller.  They will be set TRUE if a null constant or true constant,
3011  * respectively, is detected anywhere in the argument list.
3012  */
3013 static List *
3014 simplify_or_arguments(List *args,
3015                                           eval_const_expressions_context *context,
3016                                           bool *haveNull, bool *forceTrue)
3017 {
3018         List       *newargs = NIL;
3019         List       *unprocessed_args;
3020
3021         /*
3022          * Since the parser considers OR to be a binary operator, long OR lists
3023          * become deeply nested expressions.  We must flatten these into long
3024          * argument lists of a single OR operator.      To avoid blowing out the stack
3025          * with recursion of eval_const_expressions, we resort to some tenseness
3026          * here: we keep a list of not-yet-processed inputs, and handle flattening
3027          * of nested ORs by prepending to the to-do list instead of recursing.
3028          */
3029         unprocessed_args = list_copy(args);
3030         while (unprocessed_args)
3031         {
3032                 Node       *arg = (Node *) linitial(unprocessed_args);
3033
3034                 unprocessed_args = list_delete_first(unprocessed_args);
3035
3036                 /* flatten nested ORs as per above comment */
3037                 if (or_clause(arg))
3038                 {
3039                         List       *subargs = list_copy(((BoolExpr *) arg)->args);
3040
3041                         /* overly tense code to avoid leaking unused list header */
3042                         if (!unprocessed_args)
3043                                 unprocessed_args = subargs;
3044                         else
3045                         {
3046                                 List       *oldhdr = unprocessed_args;
3047
3048                                 unprocessed_args = list_concat(subargs, unprocessed_args);
3049                                 pfree(oldhdr);
3050                         }
3051                         continue;
3052                 }
3053
3054                 /* If it's not an OR, simplify it */
3055                 arg = eval_const_expressions_mutator(arg, context);
3056
3057                 /*
3058                  * It is unlikely but not impossible for simplification of a non-OR
3059                  * clause to produce an OR.  Recheck, but don't be too tense about it
3060                  * since it's not a mainstream case. In particular we don't worry
3061                  * about const-simplifying the input twice.
3062                  */
3063                 if (or_clause(arg))
3064                 {
3065                         List       *subargs = list_copy(((BoolExpr *) arg)->args);
3066
3067                         unprocessed_args = list_concat(subargs, unprocessed_args);
3068                         continue;
3069                 }
3070
3071                 /*
3072                  * OK, we have a const-simplified non-OR argument.      Process it per
3073                  * comments above.
3074                  */
3075                 if (IsA(arg, Const))
3076                 {
3077                         Const      *const_input = (Const *) arg;
3078
3079                         if (const_input->constisnull)
3080                                 *haveNull = true;
3081                         else if (DatumGetBool(const_input->constvalue))
3082                         {
3083                                 *forceTrue = true;
3084
3085                                 /*
3086                                  * Once we detect a TRUE result we can just exit the loop
3087                                  * immediately.  However, if we ever add a notion of
3088                                  * non-removable functions, we'd need to keep scanning.
3089                                  */
3090                                 return NIL;
3091                         }
3092                         /* otherwise, we can drop the constant-false input */
3093                         continue;
3094                 }
3095
3096                 /* else emit the simplified arg into the result list */
3097                 newargs = lappend(newargs, arg);
3098         }
3099
3100         return newargs;
3101 }
3102
3103 /*
3104  * Subroutine for eval_const_expressions: process arguments of an AND clause
3105  *
3106  * This includes flattening of nested ANDs as well as recursion to
3107  * eval_const_expressions to simplify the AND arguments.
3108  *
3109  * After simplification, AND arguments are handled as follows:
3110  *              non constant: keep
3111  *              TRUE: drop (does not affect result)
3112  *              FALSE: force result to FALSE
3113  *              NULL: keep only one
3114  * We must keep one NULL input because ExecEvalAnd returns NULL when no input
3115  * is FALSE and at least one is NULL.  We don't actually include the NULL
3116  * here, that's supposed to be done by the caller.
3117  *
3118  * The output arguments *haveNull and *forceFalse must be initialized FALSE
3119  * by the caller.  They will be set TRUE if a null constant or false constant,
3120  * respectively, is detected anywhere in the argument list.
3121  */
3122 static List *
3123 simplify_and_arguments(List *args,
3124                                            eval_const_expressions_context *context,
3125                                            bool *haveNull, bool *forceFalse)
3126 {
3127         List       *newargs = NIL;
3128         List       *unprocessed_args;
3129
3130         /* See comments in simplify_or_arguments */
3131         unprocessed_args = list_copy(args);
3132         while (unprocessed_args)
3133         {
3134                 Node       *arg = (Node *) linitial(unprocessed_args);
3135
3136                 unprocessed_args = list_delete_first(unprocessed_args);
3137
3138                 /* flatten nested ANDs as per above comment */
3139                 if (and_clause(arg))
3140                 {
3141                         List       *subargs = list_copy(((BoolExpr *) arg)->args);
3142
3143                         /* overly tense code to avoid leaking unused list header */
3144                         if (!unprocessed_args)
3145                                 unprocessed_args = subargs;
3146                         else
3147                         {
3148                                 List       *oldhdr = unprocessed_args;
3149
3150                                 unprocessed_args = list_concat(subargs, unprocessed_args);
3151                                 pfree(oldhdr);
3152                         }
3153                         continue;
3154                 }
3155
3156                 /* If it's not an AND, simplify it */
3157                 arg = eval_const_expressions_mutator(arg, context);
3158
3159                 /*
3160                  * It is unlikely but not impossible for simplification of a non-AND
3161                  * clause to produce an AND.  Recheck, but don't be too tense about it
3162                  * since it's not a mainstream case. In particular we don't worry
3163                  * about const-simplifying the input twice.
3164                  */
3165                 if (and_clause(arg))
3166                 {
3167                         List       *subargs = list_copy(((BoolExpr *) arg)->args);
3168
3169                         unprocessed_args = list_concat(subargs, unprocessed_args);
3170                         continue;
3171                 }
3172
3173                 /*
3174                  * OK, we have a const-simplified non-AND argument.  Process it per
3175                  * comments above.
3176                  */
3177                 if (IsA(arg, Const))
3178                 {
3179                         Const      *const_input = (Const *) arg;
3180
3181                         if (const_input->constisnull)
3182                                 *haveNull = true;
3183                         else if (!DatumGetBool(const_input->constvalue))
3184                         {
3185                                 *forceFalse = true;
3186
3187                                 /*
3188                                  * Once we detect a FALSE result we can just exit the loop
3189                                  * immediately.  However, if we ever add a notion of
3190                                  * non-removable functions, we'd need to keep scanning.
3191                                  */
3192                                 return NIL;
3193                         }
3194                         /* otherwise, we can drop the constant-true input */
3195                         continue;
3196                 }
3197
3198                 /* else emit the simplified arg into the result list */
3199                 newargs = lappend(newargs, arg);
3200         }
3201
3202         return newargs;
3203 }
3204
3205 /*
3206  * Subroutine for eval_const_expressions: try to simplify boolean equality
3207  * or inequality condition
3208  *
3209  * Inputs are the operator OID and the simplified arguments to the operator.
3210  * Returns a simplified expression if successful, or NULL if cannot
3211  * simplify the expression.
3212  *
3213  * The idea here is to reduce "x = true" to "x" and "x = false" to "NOT x",
3214  * or similarly "x <> true" to "NOT x" and "x <> false" to "x".
3215  * This is only marginally useful in itself, but doing it in constant folding
3216  * ensures that we will recognize these forms as being equivalent in, for
3217  * example, partial index matching.
3218  *
3219  * We come here only if simplify_function has failed; therefore we cannot
3220  * see two constant inputs, nor a constant-NULL input.
3221  */
3222 static Node *
3223 simplify_boolean_equality(Oid opno, List *args)
3224 {
3225         Node       *leftop;
3226         Node       *rightop;
3227
3228         Assert(list_length(args) == 2);
3229         leftop = linitial(args);
3230         rightop = lsecond(args);
3231         if (leftop && IsA(leftop, Const))
3232         {
3233                 Assert(!((Const *) leftop)->constisnull);
3234                 if (opno == BooleanEqualOperator)
3235                 {
3236                         if (DatumGetBool(((Const *) leftop)->constvalue))
3237                                 return rightop; /* true = foo */
3238                         else
3239                                 return negate_clause(rightop); /* false = foo */
3240                 }
3241                 else
3242                 {
3243                         if (DatumGetBool(((Const *) leftop)->constvalue))
3244                                 return negate_clause(rightop); /* true <> foo */
3245                         else
3246                                 return rightop; /* false <> foo */
3247                 }
3248         }
3249         if (rightop && IsA(rightop, Const))
3250         {
3251                 Assert(!((Const *) rightop)->constisnull);
3252                 if (opno == BooleanEqualOperator)
3253                 {
3254                         if (DatumGetBool(((Const *) rightop)->constvalue))
3255                                 return leftop;  /* foo = true */
3256                         else
3257                                 return negate_clause(leftop);   /* foo = false */
3258                 }
3259                 else
3260                 {
3261                         if (DatumGetBool(((Const *) rightop)->constvalue))
3262                                 return negate_clause(leftop);   /* foo <> true */
3263                         else
3264                                 return leftop;  /* foo <> false */
3265                 }
3266         }
3267         return NULL;
3268 }
3269
3270 /*
3271  * Subroutine for eval_const_expressions: try to simplify a function call
3272  * (which might originally have been an operator; we don't care)
3273  *
3274  * Inputs are the function OID, actual result type OID (which is needed for
3275  * polymorphic functions) and typmod, and the pre-simplified argument list;
3276  * also the context data for eval_const_expressions.
3277  *
3278  * Returns a simplified expression if successful, or NULL if cannot
3279  * simplify the function call.
3280  *
3281  * This function is also responsible for converting named-notation argument
3282  * lists into positional notation and/or adding any needed default argument
3283  * expressions; which is a bit grotty, but it avoids an extra fetch of the
3284  * function's pg_proc tuple.  For this reason, the args list is
3285  * pass-by-reference, and it may get modified even if simplification fails.
3286  */
3287 static Expr *
3288 simplify_function(Oid funcid, Oid result_type, int32 result_typmod,
3289                                   List **args,
3290                                   bool has_named_args,
3291                                   bool allow_inline,
3292                                   eval_const_expressions_context *context)
3293 {
3294         HeapTuple       func_tuple;
3295         Expr       *newexpr;
3296
3297         /*
3298          * We have two strategies for simplification: either execute the function
3299          * to deliver a constant result, or expand in-line the body of the
3300          * function definition (which only works for simple SQL-language
3301          * functions, but that is a common case).  In either case we need access
3302          * to the function's pg_proc tuple, so fetch it just once to use in both
3303          * attempts.
3304          */
3305         func_tuple = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcid));
3306         if (!HeapTupleIsValid(func_tuple))
3307                 elog(ERROR, "cache lookup failed for function %u", funcid);
3308
3309         /*
3310          * While we have the tuple, reorder named arguments and add default
3311          * arguments if needed.
3312          */
3313         if (has_named_args)
3314                 *args = reorder_function_arguments(*args, result_type, func_tuple,
3315                                                                                    context);
3316         else if (((Form_pg_proc) GETSTRUCT(func_tuple))->pronargs > list_length(*args))
3317                 *args = add_function_defaults(*args, result_type, func_tuple, context);
3318
3319         newexpr = evaluate_function(funcid, result_type, result_typmod, *args,
3320                                                                 func_tuple, context);
3321
3322         if (!newexpr && allow_inline)
3323                 newexpr = inline_function(funcid, result_type, *args,
3324                                                                   func_tuple, context);
3325
3326         ReleaseSysCache(func_tuple);
3327
3328         return newexpr;
3329 }
3330
3331 /*
3332  * reorder_function_arguments: convert named-notation args to positional args
3333  *
3334  * This function also inserts default argument values as needed, since it's
3335  * impossible to form a truly valid positional call without that.
3336  */
3337 static List *
3338 reorder_function_arguments(List *args, Oid result_type, HeapTuple func_tuple,
3339                                                    eval_const_expressions_context *context)
3340 {
3341         Form_pg_proc funcform = (Form_pg_proc) GETSTRUCT(func_tuple);
3342         int                     pronargs = funcform->pronargs;
3343         int                     nargsprovided = list_length(args);
3344         Node       *argarray[FUNC_MAX_ARGS];
3345         Bitmapset  *defargnumbers;
3346         ListCell   *lc;
3347         int                     i;
3348
3349         Assert(nargsprovided <= pronargs);
3350         if (pronargs > FUNC_MAX_ARGS)
3351                 elog(ERROR, "too many function arguments");
3352         MemSet(argarray, 0, pronargs * sizeof(Node *));
3353
3354         /* Deconstruct the argument list into an array indexed by argnumber */
3355         i = 0;
3356         foreach(lc, args)
3357         {
3358                 Node       *arg = (Node *) lfirst(lc);
3359
3360                 if (!IsA(arg, NamedArgExpr))
3361                 {
3362                         /* positional argument, assumed to precede all named args */
3363                         Assert(argarray[i] == NULL);
3364                         argarray[i++] = arg;
3365                 }
3366                 else
3367                 {
3368                         NamedArgExpr *na = (NamedArgExpr *) arg;
3369
3370                         Assert(argarray[na->argnumber] == NULL);
3371                         argarray[na->argnumber] = (Node *) na->arg;
3372                 }
3373         }
3374
3375         /*
3376          * Fetch default expressions, if needed, and insert into array at proper
3377          * locations (they aren't necessarily consecutive or all used)
3378          */
3379         defargnumbers = NULL;
3380         if (nargsprovided < pronargs)
3381         {
3382                 List       *defaults = fetch_function_defaults(func_tuple);
3383
3384                 i = pronargs - funcform->pronargdefaults;
3385                 foreach(lc, defaults)
3386                 {
3387                         if (argarray[i] == NULL)
3388                         {
3389                                 argarray[i] = (Node *) lfirst(lc);
3390                                 defargnumbers = bms_add_member(defargnumbers, i);
3391                         }
3392                         i++;
3393                 }
3394         }
3395
3396         /* Now reconstruct the args list in proper order */
3397         args = NIL;
3398         for (i = 0; i < pronargs; i++)
3399         {
3400                 Assert(argarray[i] != NULL);
3401                 args = lappend(args, argarray[i]);
3402         }
3403
3404         /* Recheck argument types and add casts if needed */
3405         recheck_cast_function_args(args, result_type, func_tuple);
3406
3407         /*
3408          * Lastly, we have to recursively simplify the defaults we just added (but
3409          * don't recurse on the args passed in, as we already did those). This
3410          * isn't merely an optimization, it's *necessary* since there could be
3411          * functions with named or defaulted arguments down in there.
3412          *
3413          * Note that we do this last in hopes of simplifying any typecasts that
3414          * were added by recheck_cast_function_args --- there shouldn't be any new
3415          * casts added to the explicit arguments, but casts on the defaults are
3416          * possible.
3417          */
3418         if (defargnumbers != NULL)
3419         {
3420                 i = 0;
3421                 foreach(lc, args)
3422                 {
3423                         if (bms_is_member(i, defargnumbers))
3424                                 lfirst(lc) = eval_const_expressions_mutator((Node *) lfirst(lc),
3425                                                                                                                         context);
3426                         i++;
3427                 }
3428         }
3429
3430         return args;
3431 }
3432
3433 /*
3434  * add_function_defaults: add missing function arguments from its defaults
3435  *
3436  * This is used only when the argument list was positional to begin with,
3437  * and so we know we just need to add defaults at the end.
3438  */
3439 static List *
3440 add_function_defaults(List *args, Oid result_type, HeapTuple func_tuple,
3441                                           eval_const_expressions_context *context)
3442 {
3443         Form_pg_proc funcform = (Form_pg_proc) GETSTRUCT(func_tuple);
3444         int                     nargsprovided = list_length(args);
3445         List       *defaults;
3446         int                     ndelete;
3447         ListCell   *lc;
3448
3449         /* Get all the default expressions from the pg_proc tuple */
3450         defaults = fetch_function_defaults(func_tuple);
3451
3452         /* Delete any unused defaults from the list */
3453         ndelete = nargsprovided + list_length(defaults) - funcform->pronargs;
3454         if (ndelete < 0)
3455                 elog(ERROR, "not enough default arguments");
3456         while (ndelete-- > 0)
3457                 defaults = list_delete_first(defaults);
3458
3459         /* And form the combined argument list */
3460         args = list_concat(args, defaults);
3461
3462         /* Recheck argument types and add casts if needed */
3463         recheck_cast_function_args(args, result_type, func_tuple);
3464
3465         /*
3466          * Lastly, we have to recursively simplify the defaults we just added (but
3467          * don't recurse on the args passed in, as we already did those). This
3468          * isn't merely an optimization, it's *necessary* since there could be
3469          * functions with named or defaulted arguments down in there.
3470          *
3471          * Note that we do this last in hopes of simplifying any typecasts that
3472          * were added by recheck_cast_function_args --- there shouldn't be any new
3473          * casts added to the explicit arguments, but casts on the defaults are
3474          * possible.
3475          */
3476         foreach(lc, args)
3477         {
3478                 if (nargsprovided-- > 0)
3479                         continue;                       /* skip original arg positions */
3480                 lfirst(lc) = eval_const_expressions_mutator((Node *) lfirst(lc),
3481                                                                                                         context);
3482         }
3483
3484         return args;
3485 }
3486
3487 /*
3488  * fetch_function_defaults: get function's default arguments as expression list
3489  */
3490 static List *
3491 fetch_function_defaults(HeapTuple func_tuple)
3492 {
3493         List       *defaults;
3494         Datum           proargdefaults;
3495         bool            isnull;
3496         char       *str;
3497
3498         /* The error cases here shouldn't happen, but check anyway */
3499         proargdefaults = SysCacheGetAttr(PROCOID, func_tuple,
3500                                                                          Anum_pg_proc_proargdefaults,
3501                                                                          &isnull);
3502         if (isnull)
3503                 elog(ERROR, "not enough default arguments");
3504         str = TextDatumGetCString(proargdefaults);
3505         defaults = (List *) stringToNode(str);
3506         Assert(IsA(defaults, List));
3507         pfree(str);
3508         return defaults;
3509 }
3510
3511 /*
3512  * recheck_cast_function_args: recheck function args and typecast as needed
3513  * after adding defaults.
3514  *
3515  * It is possible for some of the defaulted arguments to be polymorphic;
3516  * therefore we can't assume that the default expressions have the correct
3517  * data types already.  We have to re-resolve polymorphics and do coercion
3518  * just like the parser did.
3519  *
3520  * This should be a no-op if there are no polymorphic arguments,
3521  * but we do it anyway to be sure.
3522  *
3523  * Note: if any casts are needed, the args list is modified in-place.
3524  */
3525 static void
3526 recheck_cast_function_args(List *args, Oid result_type, HeapTuple func_tuple)
3527 {
3528         Form_pg_proc funcform = (Form_pg_proc) GETSTRUCT(func_tuple);
3529         int                     nargs;
3530         Oid                     actual_arg_types[FUNC_MAX_ARGS];
3531         Oid                     declared_arg_types[FUNC_MAX_ARGS];
3532         Oid                     rettype;
3533         ListCell   *lc;
3534
3535         if (list_length(args) > FUNC_MAX_ARGS)
3536                 elog(ERROR, "too many function arguments");
3537         nargs = 0;
3538         foreach(lc, args)
3539         {
3540                 actual_arg_types[nargs++] = exprType((Node *) lfirst(lc));
3541         }
3542         Assert(nargs == funcform->pronargs);
3543         memcpy(declared_arg_types, funcform->proargtypes.values,
3544                    funcform->pronargs * sizeof(Oid));
3545         rettype = enforce_generic_type_consistency(actual_arg_types,
3546                                                                                            declared_arg_types,
3547                                                                                            nargs,
3548                                                                                            funcform->prorettype,
3549                                                                                            false);
3550         /* let's just check we got the same answer as the parser did ... */
3551         if (rettype != result_type)
3552                 elog(ERROR, "function's resolved result type changed during planning");
3553
3554         /* perform any necessary typecasting of arguments */
3555         make_fn_arguments(NULL, args, actual_arg_types, declared_arg_types);
3556 }
3557
3558 /*
3559  * evaluate_function: try to pre-evaluate a function call
3560  *
3561  * We can do this if the function is strict and has any constant-null inputs
3562  * (just return a null constant), or if the function is immutable and has all
3563  * constant inputs (call it and return the result as a Const node).  In
3564  * estimation mode we are willing to pre-evaluate stable functions too.
3565  *
3566  * Returns a simplified expression if successful, or NULL if cannot
3567  * simplify the function.
3568  */
3569 static Expr *
3570 evaluate_function(Oid funcid, Oid result_type, int32 result_typmod, List *args,
3571                                   HeapTuple func_tuple,
3572                                   eval_const_expressions_context *context)
3573 {
3574         Form_pg_proc funcform = (Form_pg_proc) GETSTRUCT(func_tuple);
3575         bool            has_nonconst_input = false;
3576         bool            has_null_input = false;
3577         ListCell   *arg;
3578         FuncExpr   *newexpr;
3579
3580         /*
3581          * Can't simplify if it returns a set.
3582          */
3583         if (funcform->proretset)
3584                 return NULL;
3585
3586         /*
3587          * Can't simplify if it returns RECORD.  The immediate problem is that it
3588          * will be needing an expected tupdesc which we can't supply here.
3589          *
3590          * In the case where it has OUT parameters, it could get by without an
3591          * expected tupdesc, but we still have issues: get_expr_result_type()
3592          * doesn't know how to extract type info from a RECORD constant, and in
3593          * the case of a NULL function result there doesn't seem to be any clean
3594          * way to fix that.  In view of the likelihood of there being still other
3595          * gotchas, seems best to leave the function call unreduced.
3596          */
3597         if (funcform->prorettype == RECORDOID)
3598                 return NULL;
3599
3600         /*
3601          * Check for constant inputs and especially constant-NULL inputs.
3602          */
3603         foreach(arg, args)
3604         {
3605                 if (IsA(lfirst(arg), Const))
3606                         has_null_input |= ((Const *) lfirst(arg))->constisnull;
3607                 else
3608                         has_nonconst_input = true;
3609         }
3610
3611         /*
3612          * If the function is strict and has a constant-NULL input, it will never
3613          * be called at all, so we can replace the call by a NULL constant, even
3614          * if there are other inputs that aren't constant, and even if the
3615          * function is not otherwise immutable.
3616          */
3617         if (funcform->proisstrict && has_null_input)
3618                 return (Expr *) makeNullConst(result_type, result_typmod);
3619
3620         /*
3621          * Otherwise, can simplify only if all inputs are constants. (For a
3622          * non-strict function, constant NULL inputs are treated the same as
3623          * constant non-NULL inputs.)
3624          */
3625         if (has_nonconst_input)
3626                 return NULL;
3627
3628         /*
3629          * Ordinarily we are only allowed to simplify immutable functions. But for
3630          * purposes of estimation, we consider it okay to simplify functions that
3631          * are merely stable; the risk that the result might change from planning
3632          * time to execution time is worth taking in preference to not being able
3633          * to estimate the value at all.
3634          */
3635         if (funcform->provolatile == PROVOLATILE_IMMUTABLE)
3636                  /* okay */ ;
3637         else if (context->estimate && funcform->provolatile == PROVOLATILE_STABLE)
3638                  /* okay */ ;
3639         else
3640                 return NULL;
3641
3642         /*
3643          * OK, looks like we can simplify this operator/function.
3644          *
3645          * Build a new FuncExpr node containing the already-simplified arguments.
3646          */
3647         newexpr = makeNode(FuncExpr);
3648         newexpr->funcid = funcid;
3649         newexpr->funcresulttype = result_type;
3650         newexpr->funcretset = false;
3651         newexpr->funcformat = COERCE_DONTCARE;          /* doesn't matter */
3652         newexpr->args = args;
3653         newexpr->location = -1;
3654
3655         return evaluate_expr((Expr *) newexpr, result_type, result_typmod);
3656 }
3657
3658 /*
3659  * inline_function: try to expand a function call inline
3660  *
3661  * If the function is a sufficiently simple SQL-language function
3662  * (just "SELECT expression"), then we can inline it and avoid the rather
3663  * high per-call overhead of SQL functions.  Furthermore, this can expose
3664  * opportunities for constant-folding within the function expression.
3665  *
3666  * We have to beware of some special cases however.  A directly or
3667  * indirectly recursive function would cause us to recurse forever,
3668  * so we keep track of which functions we are already expanding and
3669  * do not re-expand them.  Also, if a parameter is used more than once
3670  * in the SQL-function body, we require it not to contain any volatile
3671  * functions (volatiles might deliver inconsistent answers) nor to be
3672  * unreasonably expensive to evaluate.  The expensiveness check not only
3673  * prevents us from doing multiple evaluations of an expensive parameter
3674  * at runtime, but is a safety value to limit growth of an expression due
3675  * to repeated inlining.
3676  *
3677  * We must also beware of changing the volatility or strictness status of
3678  * functions by inlining them.
3679  *
3680  * Returns a simplified expression if successful, or NULL if cannot
3681  * simplify the function.
3682  */
3683 static Expr *
3684 inline_function(Oid funcid, Oid result_type, List *args,
3685                                 HeapTuple func_tuple,
3686                                 eval_const_expressions_context *context)
3687 {
3688         Form_pg_proc funcform = (Form_pg_proc) GETSTRUCT(func_tuple);
3689         Oid                *argtypes;
3690         char       *src;
3691         Datum           tmp;
3692         bool            isNull;
3693         bool            modifyTargetList;
3694         MemoryContext oldcxt;
3695         MemoryContext mycxt;
3696         inline_error_callback_arg callback_arg;
3697         ErrorContextCallback sqlerrcontext;
3698         List       *raw_parsetree_list;
3699         Query      *querytree;
3700         Node       *newexpr;
3701         int                *usecounts;
3702         ListCell   *arg;
3703         int                     i;
3704
3705         /*
3706          * Forget it if the function is not SQL-language or has other showstopper
3707          * properties.  (The nargs check is just paranoia.)
3708          */
3709         if (funcform->prolang != SQLlanguageId ||
3710                 funcform->prosecdef ||
3711                 funcform->proretset ||
3712                 !heap_attisnull(func_tuple, Anum_pg_proc_proconfig) ||
3713                 funcform->pronargs != list_length(args))
3714                 return NULL;
3715
3716         /* Check for recursive function, and give up trying to expand if so */
3717         if (list_member_oid(context->active_fns, funcid))
3718                 return NULL;
3719
3720         /* Check permission to call function (fail later, if not) */
3721         if (pg_proc_aclcheck(funcid, GetUserId(), ACL_EXECUTE) != ACLCHECK_OK)
3722                 return NULL;
3723
3724         /*
3725          * Make a temporary memory context, so that we don't leak all the stuff
3726          * that parsing might create.
3727          */
3728         mycxt = AllocSetContextCreate(CurrentMemoryContext,
3729                                                                   "inline_function",
3730                                                                   ALLOCSET_DEFAULT_MINSIZE,
3731                                                                   ALLOCSET_DEFAULT_INITSIZE,
3732                                                                   ALLOCSET_DEFAULT_MAXSIZE);
3733         oldcxt = MemoryContextSwitchTo(mycxt);
3734
3735         /* Fetch the function body */
3736         tmp = SysCacheGetAttr(PROCOID,
3737                                                   func_tuple,
3738                                                   Anum_pg_proc_prosrc,
3739                                                   &isNull);
3740         if (isNull)
3741                 elog(ERROR, "null prosrc for function %u", funcid);
3742         src = TextDatumGetCString(tmp);
3743
3744         /*
3745          * Setup error traceback support for ereport().  This is so that we can
3746          * finger the function that bad information came from.
3747          */
3748         callback_arg.proname = NameStr(funcform->proname);
3749         callback_arg.prosrc = src;
3750
3751         sqlerrcontext.callback = sql_inline_error_callback;
3752         sqlerrcontext.arg = (void *) &callback_arg;
3753         sqlerrcontext.previous = error_context_stack;
3754         error_context_stack = &sqlerrcontext;
3755
3756         /* Check for polymorphic arguments, and substitute actual arg types */
3757         argtypes = (Oid *) palloc(funcform->pronargs * sizeof(Oid));
3758         memcpy(argtypes, funcform->proargtypes.values,
3759                    funcform->pronargs * sizeof(Oid));
3760         for (i = 0; i < funcform->pronargs; i++)
3761         {
3762                 if (IsPolymorphicType(argtypes[i]))
3763                 {
3764                         argtypes[i] = exprType((Node *) list_nth(args, i));
3765                 }
3766         }
3767
3768         /*
3769          * We just do parsing and parse analysis, not rewriting, because rewriting
3770          * will not affect table-free-SELECT-only queries, which is all that we
3771          * care about.  Also, we can punt as soon as we detect more than one
3772          * command in the function body.
3773          */
3774         raw_parsetree_list = pg_parse_query(src);
3775         if (list_length(raw_parsetree_list) != 1)
3776                 goto fail;
3777
3778         querytree = parse_analyze(linitial(raw_parsetree_list), src,
3779                                                           argtypes, funcform->pronargs);
3780
3781         /*
3782          * The single command must be a simple "SELECT expression".
3783          */
3784         if (!IsA(querytree, Query) ||
3785                 querytree->commandType != CMD_SELECT ||
3786                 querytree->utilityStmt ||
3787                 querytree->intoClause ||
3788                 querytree->hasAggs ||
3789                 querytree->hasWindowFuncs ||
3790                 querytree->hasSubLinks ||
3791                 querytree->cteList ||
3792                 querytree->rtable ||
3793                 querytree->jointree->fromlist ||
3794                 querytree->jointree->quals ||
3795                 querytree->groupClause ||
3796                 querytree->havingQual ||
3797                 querytree->windowClause ||
3798                 querytree->distinctClause ||
3799                 querytree->sortClause ||
3800                 querytree->limitOffset ||
3801                 querytree->limitCount ||
3802                 querytree->setOperations ||
3803                 list_length(querytree->targetList) != 1)
3804                 goto fail;
3805
3806         /*
3807          * Make sure the function (still) returns what it's declared to.  This
3808          * will raise an error if wrong, but that's okay since the function would
3809          * fail at runtime anyway.      Note that check_sql_fn_retval will also insert
3810          * a RelabelType if needed to make the tlist expression match the declared
3811          * type of the function.
3812          *
3813          * Note: we do not try this until we have verified that no rewriting was
3814          * needed; that's probably not important, but let's be careful.
3815          */
3816         if (check_sql_fn_retval(funcid, result_type, list_make1(querytree),
3817                                                         &modifyTargetList, NULL))
3818                 goto fail;                              /* reject whole-tuple-result cases */
3819
3820         /* Now we can grab the tlist expression */
3821         newexpr = (Node *) ((TargetEntry *) linitial(querytree->targetList))->expr;
3822
3823         /* Assert that check_sql_fn_retval did the right thing */
3824         Assert(exprType(newexpr) == result_type);
3825         /* It couldn't have made any dangerous tlist changes, either */
3826         Assert(!modifyTargetList);
3827
3828         /*
3829          * Additional validity checks on the expression.  It mustn't return a set,
3830          * and it mustn't be more volatile than the surrounding function (this is
3831          * to avoid breaking hacks that involve pretending a function is immutable
3832          * when it really ain't).  If the surrounding function is declared strict,
3833          * then the expression must contain only strict constructs and must use
3834          * all of the function parameters (this is overkill, but an exact analysis
3835          * is hard).
3836          */
3837         if (expression_returns_set(newexpr))
3838                 goto fail;
3839
3840         if (funcform->provolatile == PROVOLATILE_IMMUTABLE &&
3841                 contain_mutable_functions(newexpr))
3842                 goto fail;
3843         else if (funcform->provolatile == PROVOLATILE_STABLE &&
3844                          contain_volatile_functions(newexpr))
3845                 goto fail;
3846
3847         if (funcform->proisstrict &&
3848                 contain_nonstrict_functions(newexpr))
3849                 goto fail;
3850
3851         /*
3852          * We may be able to do it; there are still checks on parameter usage to
3853          * make, but those are most easily done in combination with the actual
3854          * substitution of the inputs.  So start building expression with inputs
3855          * substituted.
3856          */
3857         usecounts = (int *) palloc0(funcform->pronargs * sizeof(int));
3858         newexpr = substitute_actual_parameters(newexpr, funcform->pronargs,
3859                                                                                    args, usecounts);
3860
3861         /* Now check for parameter usage */
3862         i = 0;
3863         foreach(arg, args)
3864         {
3865                 Node       *param = lfirst(arg);
3866
3867                 if (usecounts[i] == 0)
3868                 {
3869                         /* Param not used at all: uncool if func is strict */
3870                         if (funcform->proisstrict)
3871                                 goto fail;
3872                 }
3873                 else if (usecounts[i] != 1)
3874                 {
3875                         /* Param used multiple times: uncool if expensive or volatile */
3876                         QualCost        eval_cost;
3877
3878                         /*
3879                          * We define "expensive" as "contains any subplan or more than 10
3880                          * operators".  Note that the subplan search has to be done
3881                          * explicitly, since cost_qual_eval() will barf on unplanned
3882                          * subselects.
3883                          */
3884                         if (contain_subplans(param))
3885                                 goto fail;
3886                         cost_qual_eval(&eval_cost, list_make1(param), NULL);
3887                         if (eval_cost.startup + eval_cost.per_tuple >
3888                                 10 * cpu_operator_cost)
3889                                 goto fail;
3890
3891                         /*
3892                          * Check volatility last since this is more expensive than the
3893                          * above tests
3894                          */
3895                         if (contain_volatile_functions(param))
3896                                 goto fail;
3897                 }
3898                 i++;
3899         }
3900
3901         /*
3902          * Whew --- we can make the substitution.  Copy the modified expression
3903          * out of the temporary memory context, and clean up.
3904          */
3905         MemoryContextSwitchTo(oldcxt);
3906
3907         newexpr = copyObject(newexpr);
3908
3909         MemoryContextDelete(mycxt);
3910
3911         /*
3912          * Since there is now no trace of the function in the plan tree, we must
3913          * explicitly record the plan's dependency on the function.
3914          */
3915         if (context->glob)
3916                 record_plan_function_dependency(context->glob, funcid);
3917
3918         /*
3919          * Recursively try to simplify the modified expression.  Here we must add
3920          * the current function to the context list of active functions.
3921          */
3922         context->active_fns = lcons_oid(funcid, context->active_fns);
3923         newexpr = eval_const_expressions_mutator(newexpr, context);
3924         context->active_fns = list_delete_first(context->active_fns);
3925
3926         error_context_stack = sqlerrcontext.previous;
3927
3928         return (Expr *) newexpr;
3929
3930         /* Here if func is not inlinable: release temp memory and return NULL */
3931 fail:
3932         MemoryContextSwitchTo(oldcxt);
3933         MemoryContextDelete(mycxt);
3934         error_context_stack = sqlerrcontext.previous;
3935
3936         return NULL;
3937 }
3938
3939 /*
3940  * Replace Param nodes by appropriate actual parameters
3941  */
3942 static Node *
3943 substitute_actual_parameters(Node *expr, int nargs, List *args,
3944                                                          int *usecounts)
3945 {
3946         substitute_actual_parameters_context context;
3947
3948         context.nargs = nargs;
3949         context.args = args;
3950         context.usecounts = usecounts;
3951
3952         return substitute_actual_parameters_mutator(expr, &context);
3953 }
3954
3955 static Node *
3956 substitute_actual_parameters_mutator(Node *node,
3957                                                            substitute_actual_parameters_context *context)
3958 {
3959         if (node == NULL)
3960                 return NULL;
3961         if (IsA(node, Param))
3962         {
3963                 Param      *param = (Param *) node;
3964
3965                 if (param->paramkind != PARAM_EXTERN)
3966                         elog(ERROR, "unexpected paramkind: %d", (int) param->paramkind);
3967                 if (param->paramid <= 0 || param->paramid > context->nargs)
3968                         elog(ERROR, "invalid paramid: %d", param->paramid);
3969
3970                 /* Count usage of parameter */
3971                 context->usecounts[param->paramid - 1]++;
3972
3973                 /* Select the appropriate actual arg and replace the Param with it */
3974                 /* We don't need to copy at this time (it'll get done later) */
3975                 return list_nth(context->args, param->paramid - 1);
3976         }
3977         return expression_tree_mutator(node, substitute_actual_parameters_mutator,
3978                                                                    (void *) context);
3979 }
3980
3981 /*
3982  * error context callback to let us supply a call-stack traceback
3983  */
3984 static void
3985 sql_inline_error_callback(void *arg)
3986 {
3987         inline_error_callback_arg *callback_arg = (inline_error_callback_arg *) arg;
3988         int                     syntaxerrposition;
3989
3990         /* If it's a syntax error, convert to internal syntax error report */
3991         syntaxerrposition = geterrposition();
3992         if (syntaxerrposition > 0)
3993         {
3994                 errposition(0);
3995                 internalerrposition(syntaxerrposition);
3996                 internalerrquery(callback_arg->prosrc);
3997         }
3998
3999         errcontext("SQL function \"%s\" during inlining", callback_arg->proname);
4000 }
4001
4002 /*
4003  * evaluate_expr: pre-evaluate a constant expression
4004  *
4005  * We use the executor's routine ExecEvalExpr() to avoid duplication of
4006  * code and ensure we get the same result as the executor would get.
4007  */
4008 static Expr *
4009 evaluate_expr(Expr *expr, Oid result_type, int32 result_typmod)
4010 {
4011         EState     *estate;
4012         ExprState  *exprstate;
4013         MemoryContext oldcontext;
4014         Datum           const_val;
4015         bool            const_is_null;
4016         int16           resultTypLen;
4017         bool            resultTypByVal;
4018
4019         /*
4020          * To use the executor, we need an EState.
4021          */
4022         estate = CreateExecutorState();
4023
4024         /* We can use the estate's working context to avoid memory leaks. */
4025         oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
4026
4027         /* Make sure any opfuncids are filled in. */
4028         fix_opfuncids((Node *) expr);
4029
4030         /*
4031          * Prepare expr for execution.  (Note: we can't use ExecPrepareExpr
4032          * because it'd result in recursively invoking eval_const_expressions.)
4033          */
4034         exprstate = ExecInitExpr(expr, NULL);
4035
4036         /*
4037          * And evaluate it.
4038          *
4039          * It is OK to use a default econtext because none of the ExecEvalExpr()
4040          * code used in this situation will use econtext.  That might seem
4041          * fortuitous, but it's not so unreasonable --- a constant expression does
4042          * not depend on context, by definition, n'est ce pas?
4043          */
4044         const_val = ExecEvalExprSwitchContext(exprstate,
4045                                                                                   GetPerTupleExprContext(estate),
4046                                                                                   &const_is_null, NULL);
4047
4048         /* Get info needed about result datatype */
4049         get_typlenbyval(result_type, &resultTypLen, &resultTypByVal);
4050
4051         /* Get back to outer memory context */
4052         MemoryContextSwitchTo(oldcontext);
4053
4054         /*
4055          * Must copy result out of sub-context used by expression eval.
4056          *
4057          * Also, if it's varlena, forcibly detoast it.  This protects us against
4058          * storing TOAST pointers into plans that might outlive the referenced
4059          * data.
4060          */
4061         if (!const_is_null)
4062         {
4063                 if (resultTypLen == -1)
4064                         const_val = PointerGetDatum(PG_DETOAST_DATUM_COPY(const_val));
4065                 else
4066                         const_val = datumCopy(const_val, resultTypByVal, resultTypLen);
4067         }
4068
4069         /* Release all the junk we just created */
4070         FreeExecutorState(estate);
4071
4072         /*
4073          * Make the constant result node.
4074          */
4075         return (Expr *) makeConst(result_type, result_typmod, resultTypLen,
4076                                                           const_val, const_is_null,
4077                                                           resultTypByVal);
4078 }
4079
4080
4081 /*
4082  * inline_set_returning_function
4083  *              Attempt to "inline" a set-returning function in the FROM clause.
4084  *
4085  * "rte" is an RTE_FUNCTION rangetable entry.  If it represents a call of a
4086  * set-returning SQL function that can safely be inlined, expand the function
4087  * and return the substitute Query structure.  Otherwise, return NULL.
4088  *
4089  * This has a good deal of similarity to inline_function(), but that's
4090  * for the non-set-returning case, and there are enough differences to
4091  * justify separate functions.
4092  */
4093 Query *
4094 inline_set_returning_function(PlannerInfo *root, RangeTblEntry *rte)
4095 {
4096         FuncExpr   *fexpr;
4097         Oid                     func_oid;
4098         HeapTuple       func_tuple;
4099         Form_pg_proc funcform;
4100         Oid                *argtypes;
4101         char       *src;
4102         Datum           tmp;
4103         bool            isNull;
4104         bool            modifyTargetList;
4105         MemoryContext oldcxt;
4106         MemoryContext mycxt;
4107         List       *saveInvalItems;
4108         inline_error_callback_arg callback_arg;
4109         ErrorContextCallback sqlerrcontext;
4110         List       *raw_parsetree_list;
4111         List       *querytree_list;
4112         Query      *querytree;
4113         int                     i;
4114
4115         Assert(rte->rtekind == RTE_FUNCTION);
4116
4117         /*
4118          * It doesn't make a lot of sense for a SQL SRF to refer to itself in its
4119          * own FROM clause, since that must cause infinite recursion at runtime.
4120          * It will cause this code to recurse too, so check for stack overflow.
4121          * (There's no need to do more.)
4122          */
4123         check_stack_depth();
4124
4125         /* Fail if FROM item isn't a simple FuncExpr */
4126         fexpr = (FuncExpr *) rte->funcexpr;
4127         if (fexpr == NULL || !IsA(fexpr, FuncExpr))
4128                 return NULL;
4129         func_oid = fexpr->funcid;
4130
4131         /*
4132          * The function must be declared to return a set, else inlining would
4133          * change the results if the contained SELECT didn't return exactly one
4134          * row.
4135          */
4136         if (!fexpr->funcretset)
4137                 return NULL;
4138
4139         /*
4140          * Refuse to inline if the arguments contain any volatile functions or
4141          * sub-selects.  Volatile functions are rejected because inlining may
4142          * result in the arguments being evaluated multiple times, risking a
4143          * change in behavior.  Sub-selects are rejected partly for implementation
4144          * reasons (pushing them down another level might change their behavior)
4145          * and partly because they're likely to be expensive and so multiple
4146          * evaluation would be bad.
4147          */
4148         if (contain_volatile_functions((Node *) fexpr->args) ||
4149                 contain_subplans((Node *) fexpr->args))
4150                 return NULL;
4151
4152         /* Check permission to call function (fail later, if not) */
4153         if (pg_proc_aclcheck(func_oid, GetUserId(), ACL_EXECUTE) != ACLCHECK_OK)
4154                 return NULL;
4155
4156         /*
4157          * OK, let's take a look at the function's pg_proc entry.
4158          */
4159         func_tuple = SearchSysCache1(PROCOID, ObjectIdGetDatum(func_oid));
4160         if (!HeapTupleIsValid(func_tuple))
4161                 elog(ERROR, "cache lookup failed for function %u", func_oid);
4162         funcform = (Form_pg_proc) GETSTRUCT(func_tuple);
4163
4164         /*
4165          * Forget it if the function is not SQL-language or has other showstopper
4166          * properties.  In particular it mustn't be declared STRICT, since we
4167          * couldn't enforce that.  It also mustn't be VOLATILE, because that is
4168          * supposed to cause it to be executed with its own snapshot, rather than
4169          * sharing the snapshot of the calling query.  (Rechecking proretset is
4170          * just paranoia.)
4171          */
4172         if (funcform->prolang != SQLlanguageId ||
4173                 funcform->proisstrict ||
4174                 funcform->provolatile == PROVOLATILE_VOLATILE ||
4175                 funcform->prosecdef ||
4176                 !funcform->proretset ||
4177                 !heap_attisnull(func_tuple, Anum_pg_proc_proconfig))
4178         {
4179                 ReleaseSysCache(func_tuple);
4180                 return NULL;
4181         }
4182
4183         /*
4184          * Make a temporary memory context, so that we don't leak all the stuff
4185          * that parsing might create.
4186          */
4187         mycxt = AllocSetContextCreate(CurrentMemoryContext,
4188                                                                   "inline_set_returning_function",
4189                                                                   ALLOCSET_DEFAULT_MINSIZE,
4190                                                                   ALLOCSET_DEFAULT_INITSIZE,
4191                                                                   ALLOCSET_DEFAULT_MAXSIZE);
4192         oldcxt = MemoryContextSwitchTo(mycxt);
4193
4194         /*
4195          * When we call eval_const_expressions below, it might try to add items
4196          * to root->glob->invalItems.  Since it is running in the temp context,
4197          * those items will be in that context, and will need to be copied out
4198          * if we're successful.  Temporarily reset the list so that we can keep
4199          * those items separate from the pre-existing list contents.
4200          */
4201         saveInvalItems = root->glob->invalItems;
4202         root->glob->invalItems = NIL;
4203
4204         /* Fetch the function body */
4205         tmp = SysCacheGetAttr(PROCOID,
4206                                                   func_tuple,
4207                                                   Anum_pg_proc_prosrc,
4208                                                   &isNull);
4209         if (isNull)
4210                 elog(ERROR, "null prosrc for function %u", func_oid);
4211         src = TextDatumGetCString(tmp);
4212
4213         /*
4214          * Setup error traceback support for ereport().  This is so that we can
4215          * finger the function that bad information came from.
4216          */
4217         callback_arg.proname = NameStr(funcform->proname);
4218         callback_arg.prosrc = src;
4219
4220         sqlerrcontext.callback = sql_inline_error_callback;
4221         sqlerrcontext.arg = (void *) &callback_arg;
4222         sqlerrcontext.previous = error_context_stack;
4223         error_context_stack = &sqlerrcontext;
4224
4225         /*
4226          * Run eval_const_expressions on the function call.  This is necessary to
4227          * ensure that named-argument notation is converted to positional notation
4228          * and any default arguments are inserted.      It's a bit of overkill for the
4229          * arguments, since they'll get processed again later, but no harm will be
4230          * done.
4231          */
4232         fexpr = (FuncExpr *) eval_const_expressions(root, (Node *) fexpr);
4233
4234         /* It should still be a call of the same function, but let's check */
4235         if (!IsA(fexpr, FuncExpr) ||
4236                 fexpr->funcid != func_oid)
4237                 goto fail;
4238
4239         /* Arg list length should now match the function */
4240         if (list_length(fexpr->args) != funcform->pronargs)
4241                 goto fail;
4242
4243         /* Check for polymorphic arguments, and substitute actual arg types */
4244         argtypes = (Oid *) palloc(funcform->pronargs * sizeof(Oid));
4245         memcpy(argtypes, funcform->proargtypes.values,
4246                    funcform->pronargs * sizeof(Oid));
4247         for (i = 0; i < funcform->pronargs; i++)
4248         {
4249                 if (IsPolymorphicType(argtypes[i]))
4250                 {
4251                         argtypes[i] = exprType((Node *) list_nth(fexpr->args, i));
4252                 }
4253         }
4254
4255         /*
4256          * Parse, analyze, and rewrite (unlike inline_function(), we can't skip
4257          * rewriting here).  We can fail as soon as we find more than one query,
4258          * though.
4259          */
4260         raw_parsetree_list = pg_parse_query(src);
4261         if (list_length(raw_parsetree_list) != 1)
4262                 goto fail;
4263
4264         querytree_list = pg_analyze_and_rewrite(linitial(raw_parsetree_list), src,
4265                                                                                         argtypes, funcform->pronargs);
4266         if (list_length(querytree_list) != 1)
4267                 goto fail;
4268         querytree = linitial(querytree_list);
4269
4270         /*
4271          * The single command must be a regular results-returning SELECT.
4272          */
4273         if (!IsA(querytree, Query) ||
4274                 querytree->commandType != CMD_SELECT ||
4275                 querytree->utilityStmt ||
4276                 querytree->intoClause)
4277                 goto fail;
4278
4279         /*
4280          * Make sure the function (still) returns what it's declared to.  This
4281          * will raise an error if wrong, but that's okay since the function would
4282          * fail at runtime anyway.      Note that check_sql_fn_retval will also insert
4283          * RelabelType(s) and/or NULL columns if needed to make the tlist
4284          * expression(s) match the declared type of the function.
4285          *
4286          * If the function returns a composite type, don't inline unless the check
4287          * shows it's returning a whole tuple result; otherwise what it's
4288          * returning is a single composite column which is not what we need.
4289          */
4290         if (!check_sql_fn_retval(func_oid, fexpr->funcresulttype,
4291                                                          querytree_list,
4292                                                          &modifyTargetList, NULL) &&
4293                 (get_typtype(fexpr->funcresulttype) == TYPTYPE_COMPOSITE ||
4294                  fexpr->funcresulttype == RECORDOID))
4295                 goto fail;                              /* reject not-whole-tuple-result cases */
4296
4297         /*
4298          * If we had to modify the tlist to make it match, and the statement is
4299          * one in which changing the tlist contents could change semantics, we
4300          * have to punt and not inline.
4301          */
4302         if (modifyTargetList)
4303                 goto fail;
4304
4305         /*
4306          * If it returns RECORD, we have to check against the column type list
4307          * provided in the RTE; check_sql_fn_retval can't do that.  (If no match,
4308          * we just fail to inline, rather than complaining; see notes for
4309          * tlist_matches_coltypelist.)
4310          */
4311         if (fexpr->funcresulttype == RECORDOID &&
4312                 !tlist_matches_coltypelist(querytree->targetList, rte->funccoltypes))
4313                 goto fail;
4314
4315         /*
4316          * Looks good --- substitute parameters into the query.
4317          */
4318         querytree = substitute_actual_srf_parameters(querytree,
4319                                                                                                  funcform->pronargs,
4320                                                                                                  fexpr->args);
4321
4322         /*
4323          * Copy the modified query out of the temporary memory context, and clean
4324          * up.
4325          */
4326         MemoryContextSwitchTo(oldcxt);
4327
4328         querytree = copyObject(querytree);
4329
4330         /* copy up any new invalItems, too */
4331         root->glob->invalItems = list_concat(saveInvalItems,
4332                                                                                  copyObject(root->glob->invalItems));
4333
4334         MemoryContextDelete(mycxt);
4335         error_context_stack = sqlerrcontext.previous;
4336         ReleaseSysCache(func_tuple);
4337
4338         /*
4339          * Since there is now no trace of the function in the plan tree, we must
4340          * explicitly record the plan's dependency on the function.
4341          */
4342         record_plan_function_dependency(root->glob, func_oid);
4343
4344         return querytree;
4345
4346         /* Here if func is not inlinable: release temp memory and return NULL */
4347 fail:
4348         MemoryContextSwitchTo(oldcxt);
4349         root->glob->invalItems = saveInvalItems;
4350         MemoryContextDelete(mycxt);
4351         error_context_stack = sqlerrcontext.previous;
4352         ReleaseSysCache(func_tuple);
4353
4354         return NULL;
4355 }
4356
4357 /*
4358  * Replace Param nodes by appropriate actual parameters
4359  *
4360  * This is just enough different from substitute_actual_parameters()
4361  * that it needs its own code.
4362  */
4363 static Query *
4364 substitute_actual_srf_parameters(Query *expr, int nargs, List *args)
4365 {
4366         substitute_actual_srf_parameters_context context;
4367
4368         context.nargs = nargs;
4369         context.args = args;
4370         context.sublevels_up = 1;
4371
4372         return query_tree_mutator(expr,
4373                                                           substitute_actual_srf_parameters_mutator,
4374                                                           &context,
4375                                                           0);
4376 }
4377
4378 static Node *
4379 substitute_actual_srf_parameters_mutator(Node *node,
4380                                                    substitute_actual_srf_parameters_context *context)
4381 {
4382         Node       *result;
4383
4384         if (node == NULL)
4385                 return NULL;
4386         if (IsA(node, Query))
4387         {
4388                 context->sublevels_up++;
4389                 result = (Node *) query_tree_mutator((Query *) node,
4390                                                                         substitute_actual_srf_parameters_mutator,
4391                                                                                          (void *) context,
4392                                                                                          0);
4393                 context->sublevels_up--;
4394                 return result;
4395         }
4396         if (IsA(node, Param))
4397         {
4398                 Param      *param = (Param *) node;
4399
4400                 if (param->paramkind == PARAM_EXTERN)
4401                 {
4402                         if (param->paramid <= 0 || param->paramid > context->nargs)
4403                                 elog(ERROR, "invalid paramid: %d", param->paramid);
4404
4405                         /*
4406                          * Since the parameter is being inserted into a subquery, we must
4407                          * adjust levels.
4408                          */
4409                         result = copyObject(list_nth(context->args, param->paramid - 1));
4410                         IncrementVarSublevelsUp(result, context->sublevels_up, 0);
4411                         return result;
4412                 }
4413         }
4414         return expression_tree_mutator(node,
4415                                                                    substitute_actual_srf_parameters_mutator,
4416                                                                    (void *) context);
4417 }
4418
4419 /*
4420  * Check whether a SELECT targetlist emits the specified column types,
4421  * to see if it's safe to inline a function returning record.
4422  *
4423  * We insist on exact match here.  The executor allows binary-coercible
4424  * cases too, but we don't have a way to preserve the correct column types
4425  * in the correct places if we inline the function in such a case.
4426  *
4427  * Note that we only check type OIDs not typmods; this agrees with what the
4428  * executor would do at runtime, and attributing a specific typmod to a
4429  * function result is largely wishful thinking anyway.
4430  */
4431 static bool
4432 tlist_matches_coltypelist(List *tlist, List *coltypelist)
4433 {
4434         ListCell   *tlistitem;
4435         ListCell   *clistitem;
4436
4437         clistitem = list_head(coltypelist);
4438         foreach(tlistitem, tlist)
4439         {
4440                 TargetEntry *tle = (TargetEntry *) lfirst(tlistitem);
4441                 Oid                     coltype;
4442
4443                 if (tle->resjunk)
4444                         continue;                       /* ignore junk columns */
4445
4446                 if (clistitem == NULL)
4447                         return false;           /* too many tlist items */
4448
4449                 coltype = lfirst_oid(clistitem);
4450                 clistitem = lnext(clistitem);
4451
4452                 if (exprType((Node *) tle->expr) != coltype)
4453                         return false;           /* column type mismatch */
4454         }
4455
4456         if (clistitem != NULL)
4457                 return false;                   /* too few tlist items */
4458
4459         return true;
4460 }