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

Generated by: LCOV version 1.14