LCOV - code coverage report
Current view: top level - src/backend/optimizer/util - clauses.c (source / functions) Coverage Total Hit
Test: PostgreSQL 20devel Lines: 88.4 % 2091 1848
Test Date: 2026-08-15 14:15:41 Functions: 98.8 % 84 83
Legend: Lines:     hit not hit
Branches: + taken - not taken # not executed
Branches: 71.5 % 1623 1160

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

Generated by: LCOV version 2.0-1