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

Generated by: LCOV version 1.16