LCOV - differential code coverage report
Current view: top level - src/backend/optimizer/util - clauses.c (source / functions) Coverage Total Hit UNC UBC GBC GNC CBC DUB DCB
Current: 1a1248818fb8b8b0353c292c632d6a6af77e8209 vs 8e82d6610e7280d7870c0c36ff1c797e3cfb3e09 Lines: 88.5 % 2181 1930 251 4 14 1912 1 12
Current Date: 2026-10-12 11:56:10 +0200 Functions: 98.8 % 85 84 1 7 77 1
Baseline: lcov-20261012-baseline Branches: 70.8 % 1704 1206 3 495 2 13 1191
Baseline Date: 2026-10-12 10:36:06 +0200 Line coverage date bins:
Legend: Lines:     hit not hit
Branches: + taken - not taken # not executed
(1,7] days: 100.0 % 9 9 9
(7,30] days: 92.6 % 27 25 2 25
(30,360] days: 90.3 % 445 402 43 4 14 384
(360..) days: 87.9 % 1700 1494 206 1494
Function coverage date bins:
(30,360] days: 100.0 % 14 14 2 12
(360..) days: 98.6 % 71 70 1 5 65
Branch coverage date bins:
(1,7] days: 75.0 % 12 9 3 9
(7,30] days: 80.0 % 10 8 2 8
(30,360] days: 73.4 % 428 314 3 111 2 13 299
(360..) days: 69.8 % 1254 875 379 875

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

Generated by: LCOV version 2.0-1