LCOV - differential code coverage report
Current view: top level - src/backend/optimizer/util - clauses.c (source / functions) Coverage Total Hit UBC CBC
Current: 603a3335f2b60b2c798da5c627b3bb288b92a7bd vs e395fbd32a07557de4ac98088928c1749d4845d8 Lines: 88.5 % 2111 1869 242 1869
Current Date: 2026-07-25 17:13:00 -0400 Functions: 98.8 % 84 83 1 83
Baseline: lcov-20260726-baseline Branches: 70.7 % 1669 1180 489 1180
Baseline Date: 2026-07-25 19:16:42 +0200 Line coverage date bins:
Legend: Lines:     hit not hit
Branches: + taken - not taken # not executed
(7,30] days: 90.9 % 77 70 7 70
(30,360] days: 89.6 % 297 266 31 266
(360..) days: 88.3 % 1737 1533 204 1533
Function coverage date bins:
(7,30] days: 100.0 % 4 4 4
(30,360] days: 100.0 % 9 9 9
(360..) days: 98.6 % 71 70 1 70
Branch coverage date bins:
(7,30] days: 70.3 % 118 83 35 83
(30,360] days: 74.6 % 228 170 58 170
(360..) days: 70.1 % 1323 927 396 927

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

Generated by: LCOV version 2.0-1