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