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

Generated by: LCOV version 1.14