LCOV - code coverage report
Current view: top level - src/backend/optimizer/util - clauses.c (source / functions) Hit Total Coverage
Test: PostgreSQL 13beta1 Lines: 1432 1622 88.3 %
Date: 2020-06-01 08:06:25 Functions: 68 68 100.0 %
Legend: Lines: hit not hit

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

Generated by: LCOV version 1.13