PostgreSQL Source Code git master
Loading...
Searching...
No Matches
clauses.c File Reference
#include "postgres.h"
#include "access/htup_details.h"
#include "access/table.h"
#include "catalog/pg_class.h"
#include "catalog/pg_inherits.h"
#include "catalog/pg_language.h"
#include "catalog/pg_operator.h"
#include "catalog/pg_proc.h"
#include "catalog/pg_type.h"
#include "executor/executor.h"
#include "executor/functions.h"
#include "funcapi.h"
#include "miscadmin.h"
#include "nodes/makefuncs.h"
#include "nodes/multibitmapset.h"
#include "nodes/nodeFuncs.h"
#include "nodes/subscripting.h"
#include "nodes/supportnodes.h"
#include "optimizer/clauses.h"
#include "optimizer/cost.h"
#include "optimizer/optimizer.h"
#include "optimizer/pathnode.h"
#include "optimizer/plancat.h"
#include "optimizer/planmain.h"
#include "parser/analyze.h"
#include "parser/parse_coerce.h"
#include "parser/parse_collate.h"
#include "parser/parse_func.h"
#include "parser/parse_oper.h"
#include "parser/parsetree.h"
#include "rewrite/rewriteHandler.h"
#include "rewrite/rewriteManip.h"
#include "tcop/tcopprot.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/datum.h"
#include "utils/fmgroids.h"
#include "utils/json.h"
#include "utils/jsonb.h"
#include "utils/jsonpath.h"
#include "utils/lsyscache.h"
#include "utils/memutils.h"
#include "utils/rel.h"
#include "utils/syscache.h"
#include "utils/typcache.h"
Include dependency graph for clauses.c:

Go to the source code of this file.

Data Structures

struct  eval_const_expressions_context
 
struct  substitute_actual_parameters_context
 
struct  substitute_actual_parameters_in_from_context
 
struct  inline_error_callback_arg
 
struct  max_parallel_hazard_context
 

Macros

#define CCDN_CASETESTEXPR_OK   0x0001 /* CaseTestExpr okay here? */
 
#define MIN_ARRAY_SIZE_FOR_HASHED_SAOP   9
 
#define ece_generic_processing(node)
 
#define ece_all_arguments_const(node)    (!expression_tree_walker((Node *) (node), contain_non_const_walker, NULL))
 
#define ece_evaluate_expr(node)
 

Functions

static bool contain_agg_clause_walker (Node *node, void *context)
 
static bool find_window_functions_walker (Node *node, WindowFuncLists *lists)
 
static bool contain_subplans_walker (Node *node, void *context)
 
static bool contain_mutable_functions_walker (Node *node, void *context)
 
static bool contain_volatile_functions_walker (Node *node, void *context)
 
static bool contain_volatile_functions_not_nextval_walker (Node *node, void *context)
 
static bool max_parallel_hazard_walker (Node *node, max_parallel_hazard_context *context)
 
static bool contain_nonstrict_functions_walker (Node *node, void *context)
 
static bool contain_exec_param_walker (Node *node, List *param_ids)
 
static bool contain_context_dependent_node (Node *clause)
 
static bool contain_context_dependent_node_walker (Node *node, int *flags)
 
static bool contain_leaked_vars_walker (Node *node, void *context)
 
static Relids find_nonnullable_rels_walker (Node *node, bool top_level)
 
static Listfind_nonnullable_vars_walker (Node *node, bool top_level)
 
static void find_subquery_safe_quals (Node *jtnode, List **safe_quals)
 
static bool is_strict_saop (ScalarArrayOpExpr *expr, bool falseOK)
 
static bool convert_saop_to_hashed_saop_walker (Node *node, void *context)
 
static Nodeeval_const_expressions_mutator (Node *node, eval_const_expressions_context *context)
 
static bool contain_non_const_walker (Node *node, void *context)
 
static bool ece_function_is_safe (Oid funcid, eval_const_expressions_context *context)
 
static Listsimplify_or_arguments (List *args, eval_const_expressions_context *context, bool *haveNull, bool *forceTrue)
 
static Listsimplify_and_arguments (List *args, eval_const_expressions_context *context, bool *haveNull, bool *forceFalse)
 
static Nodesimplify_boolean_equality (Oid opno, List *args)
 
static Exprsimplify_function (Oid funcid, Oid result_type, int32 result_typmod, Oid result_collid, Oid input_collid, List **args_p, bool funcvariadic, bool process_args, bool allow_non_const, eval_const_expressions_context *context)
 
static Nodesimplify_aggref (Aggref *aggref, eval_const_expressions_context *context)
 
static Listreorder_function_arguments (List *args, int pronargs, HeapTuple func_tuple)
 
static Listadd_function_defaults (List *args, int pronargs, HeapTuple func_tuple)
 
static Listfetch_function_defaults (HeapTuple func_tuple)
 
static void recheck_cast_function_args (List *args, Oid result_type, Oid *proargtypes, int pronargs, HeapTuple func_tuple)
 
static Exprevaluate_function (Oid funcid, Oid result_type, int32 result_typmod, Oid result_collid, Oid input_collid, List *args, bool funcvariadic, HeapTuple func_tuple, eval_const_expressions_context *context)
 
static Exprinline_function (Oid funcid, Oid result_type, Oid result_collid, Oid input_collid, List *args, bool funcvariadic, HeapTuple func_tuple, eval_const_expressions_context *context)
 
static Nodesubstitute_actual_parameters (Node *expr, int nargs, List *args, int *usecounts)
 
static Nodesubstitute_actual_parameters_mutator (Node *node, substitute_actual_parameters_context *context)
 
static void sql_inline_error_callback (void *arg)
 
static Queryinline_sql_function_in_from (PlannerInfo *root, RangeTblFunction *rtfunc, FuncExpr *fexpr, HeapTuple func_tuple, Form_pg_proc funcform, const char *src)
 
static Querysubstitute_actual_parameters_in_from (Query *expr, int nargs, List *args)
 
static Nodesubstitute_actual_parameters_in_from_mutator (Node *node, substitute_actual_parameters_in_from_context *context)
 
static bool pull_paramids_walker (Node *node, Bitmapset **context)
 
bool contain_agg_clause (Node *clause)
 
bool contain_window_function (Node *clause)
 
WindowFuncListsfind_window_functions (Node *clause, Index maxWinRef)
 
double expression_returns_set_rows (PlannerInfo *root, Node *clause)
 
bool contain_subplans (Node *clause)
 
bool contain_mutable_functions (Node *clause)
 
static bool contain_mutable_functions_checker (Oid func_id, void *context)
 
bool contain_mutable_functions_after_planning (Expr *expr)
 
bool contain_volatile_functions (Node *clause)
 
static bool contain_volatile_functions_checker (Oid func_id, void *context)
 
bool contain_volatile_functions_after_planning (Expr *expr)
 
bool contain_volatile_functions_not_nextval (Node *clause)
 
static bool contain_volatile_functions_not_nextval_checker (Oid func_id, void *context)
 
char max_parallel_hazard (Query *parse)
 
bool is_parallel_safe (PlannerInfo *root, Node *node)
 
static bool max_parallel_hazard_test (char proparallel, max_parallel_hazard_context *context)
 
static bool max_parallel_hazard_checker (Oid func_id, void *context)
 
bool contain_nonstrict_functions (Node *clause)
 
static bool contain_nonstrict_functions_checker (Oid func_id, void *context)
 
bool contain_exec_param (Node *clause, List *param_ids)
 
bool contain_leaked_vars (Node *clause)
 
static bool contain_leaked_vars_checker (Oid func_id, void *context)
 
Relids find_nonnullable_rels (Node *clause)
 
Listfind_nonnullable_vars (Node *clause)
 
Listfind_forced_null_vars (Node *node)
 
Varfind_forced_null_var (Node *node)
 
bool query_outputs_are_not_nullable (Query *query)
 
bool is_pseudo_constant_clause (Node *clause)
 
bool is_pseudo_constant_clause_relids (Node *clause, Relids relids)
 
int NumRelids (PlannerInfo *root, Node *clause)
 
void CommuteOpExpr (OpExpr *clause)
 
static bool rowtype_field_matches (Oid rowtypeid, int fieldnum, Oid expectedtype, int32 expectedtypmod, Oid expectedcollation)
 
Nodeeval_const_expressions (PlannerInfo *root, Node *node)
 
void convert_saop_to_hashed_saop (Node *node)
 
Nodeestimate_expression_value (PlannerInfo *root, Node *node)
 
bool var_is_nonnullable (PlannerInfo *root, Var *var, NotNullSource source)
 
bool expr_is_nonnullable (PlannerInfo *root, Expr *expr, NotNullSource source)
 
Listexpand_function_arguments (List *args, bool include_out_arguments, Oid result_type, HeapTuple func_tuple)
 
Exprevaluate_expr (Expr *expr, Oid result_type, int32 result_typmod, Oid result_collation)
 
Queryinline_function_in_from (PlannerInfo *root, RangeTblEntry *rte)
 
Bitmapsetpull_paramids (Expr *expr)
 
ScalarArrayOpExprmake_SAOP_expr (Oid oper, Node *leftexpr, Oid coltype, Oid arraycollid, Oid inputcollid, List *exprs, bool haveNonConst)
 

Macro Definition Documentation

◆ CCDN_CASETESTEXPR_OK

#define CCDN_CASETESTEXPR_OK   0x0001 /* CaseTestExpr okay here? */

Definition at line 1201 of file clauses.c.

◆ ece_all_arguments_const

#define ece_all_arguments_const (   node)     (!expression_tree_walker((Node *) (node), contain_non_const_walker, NULL))

Definition at line 2672 of file clauses.c.

2687{
2688
2689 /* since this function recurses, it could be driven to stack overflow */
2691
2692 if (node == NULL)
2693 return NULL;
2694 switch (nodeTag(node))
2695 {
2696 case T_Param:
2697 {
2698 Param *param = (Param *) node;
2699 ParamListInfo paramLI = context->boundParams;
2700
2701 /* Look to see if we've been given a value for this Param */
2702 if (param->paramkind == PARAM_EXTERN &&
2703 paramLI != NULL &&
2704 param->paramid > 0 &&
2705 param->paramid <= paramLI->numParams)
2706 {
2709
2710 /*
2711 * Give hook a chance in case parameter is dynamic. Tell
2712 * it that this fetch is speculative, so it should avoid
2713 * erroring out if parameter is unavailable.
2714 */
2715 if (paramLI->paramFetch != NULL)
2716 prm = paramLI->paramFetch(paramLI, param->paramid,
2717 true, &prmdata);
2718 else
2719 prm = &paramLI->params[param->paramid - 1];
2720
2721 /*
2722 * We don't just check OidIsValid, but insist that the
2723 * fetched type match the Param, just in case the hook did
2724 * something unexpected. No need to throw an error here
2725 * though; leave that for runtime.
2726 */
2727 if (OidIsValid(prm->ptype) &&
2728 prm->ptype == param->paramtype)
2729 {
2730 /* OK to substitute parameter value? */
2731 if (context->estimate ||
2732 (prm->pflags & PARAM_FLAG_CONST))
2733 {
2734 /*
2735 * Return a Const representing the param value.
2736 * Must copy pass-by-ref datatypes, since the
2737 * Param might be in a memory context
2738 * shorter-lived than our output plan should be.
2739 */
2740 int16 typLen;
2741 bool typByVal;
2742 Datum pval;
2743 Const *con;
2744
2746 &typLen, &typByVal);
2747 if (prm->isnull || typByVal)
2748 pval = prm->value;
2749 else
2750 pval = datumCopy(prm->value, typByVal, typLen);
2751 con = makeConst(param->paramtype,
2752 param->paramtypmod,
2753 param->paramcollid,
2754 (int) typLen,
2755 pval,
2756 prm->isnull,
2757 typByVal);
2758 con->location = param->location;
2759 return (Node *) con;
2760 }
2761 }
2762 }
2763
2764 /*
2765 * Not replaceable, so just copy the Param (no need to
2766 * recurse)
2767 */
2768 return (Node *) copyObject(param);
2769 }
2770 case T_WindowFunc:
2771 {
2772 WindowFunc *expr = (WindowFunc *) node;
2773 Oid funcid = expr->winfnoid;
2774 List *args;
2775 Expr *aggfilter;
2778
2779 /*
2780 * We can't really simplify a WindowFunc node, but we mustn't
2781 * just fall through to the default processing, because we
2782 * have to apply expand_function_arguments to its argument
2783 * list. That takes care of inserting default arguments and
2784 * expanding named-argument notation.
2785 */
2788 elog(ERROR, "cache lookup failed for function %u", funcid);
2789
2791 false, expr->wintype,
2792 func_tuple);
2793
2795
2796 /* Now, recursively simplify the args (which are a List) */
2797 args = (List *)
2800 context);
2801 /* ... and the filter expression, which isn't */
2802 aggfilter = (Expr *)
2804 context);
2805
2806 /* And build the replacement WindowFunc node */
2808 newexpr->winfnoid = expr->winfnoid;
2809 newexpr->wintype = expr->wintype;
2810 newexpr->wincollid = expr->wincollid;
2811 newexpr->inputcollid = expr->inputcollid;
2812 newexpr->args = args;
2813 newexpr->aggfilter = aggfilter;
2814 newexpr->runCondition = expr->runCondition;
2815 newexpr->winref = expr->winref;
2816 newexpr->winstar = expr->winstar;
2817 newexpr->winagg = expr->winagg;
2819 newexpr->location = expr->location;
2820
2821 return (Node *) newexpr;
2822 }
2823 case T_FuncExpr:
2824 {
2825 FuncExpr *expr = (FuncExpr *) node;
2826 List *args = expr->args;
2827 Expr *simple;
2829
2830 /*
2831 * Code for op/func reduction is pretty bulky, so split it out
2832 * as a separate function. Note: exprTypmod normally returns
2833 * -1 for a FuncExpr, but not when the node is recognizably a
2834 * length coercion; we want to preserve the typmod in the
2835 * eventual Const if so.
2836 */
2837 simple = simplify_function(expr->funcid,
2838 expr->funcresulttype,
2839 exprTypmod(node),
2840 expr->funccollid,
2841 expr->inputcollid,
2842 &args,
2843 expr->funcvariadic,
2844 true,
2845 true,
2846 context);
2847 if (simple) /* successfully simplified it */
2848 return (Node *) simple;
2849
2850 /*
2851 * The expression cannot be simplified any further, so build
2852 * and return a replacement FuncExpr node using the
2853 * possibly-simplified arguments. Note that we have also
2854 * converted the argument list to positional notation.
2855 */
2857 newexpr->funcid = expr->funcid;
2858 newexpr->funcresulttype = expr->funcresulttype;
2859 newexpr->funcretset = expr->funcretset;
2860 newexpr->funcvariadic = expr->funcvariadic;
2861 newexpr->funcformat = expr->funcformat;
2862 newexpr->funccollid = expr->funccollid;
2863 newexpr->inputcollid = expr->inputcollid;
2864 newexpr->args = args;
2865 newexpr->location = expr->location;
2866 return (Node *) newexpr;
2867 }
2868 case T_Aggref:
2869 node = ece_generic_processing(node);
2870 if (context->root != NULL)
2871 return simplify_aggref((Aggref *) node, context);
2872 return node;
2873 case T_OpExpr:
2874 {
2875 OpExpr *expr = (OpExpr *) node;
2876 List *args = expr->args;
2877 Expr *simple;
2878 OpExpr *newexpr;
2879
2880 /*
2881 * Need to get OID of underlying function. Okay to scribble
2882 * on input to this extent.
2883 */
2884 set_opfuncid(expr);
2885
2886 /*
2887 * Code for op/func reduction is pretty bulky, so split it out
2888 * as a separate function.
2889 */
2890 simple = simplify_function(expr->opfuncid,
2891 expr->opresulttype, -1,
2892 expr->opcollid,
2893 expr->inputcollid,
2894 &args,
2895 false,
2896 true,
2897 true,
2898 context);
2899 if (simple) /* successfully simplified it */
2900 return (Node *) simple;
2901
2902 /*
2903 * If the operator is boolean equality or inequality, we know
2904 * how to simplify cases involving one constant and one
2905 * non-constant argument.
2906 */
2907 if (expr->opno == BooleanEqualOperator ||
2909 {
2910 simple = (Expr *) simplify_boolean_equality(expr->opno,
2911 args);
2912 if (simple) /* successfully simplified it */
2913 return (Node *) simple;
2914 }
2915
2916 /*
2917 * The expression cannot be simplified any further, so build
2918 * and return a replacement OpExpr node using the
2919 * possibly-simplified arguments.
2920 */
2922 newexpr->opno = expr->opno;
2923 newexpr->opfuncid = expr->opfuncid;
2924 newexpr->opresulttype = expr->opresulttype;
2925 newexpr->opretset = expr->opretset;
2926 newexpr->opcollid = expr->opcollid;
2927 newexpr->inputcollid = expr->inputcollid;
2928 newexpr->args = args;
2929 newexpr->location = expr->location;
2930 return (Node *) newexpr;
2931 }
2932 case T_DistinctExpr:
2933 {
2934 DistinctExpr *expr = (DistinctExpr *) node;
2935 List *args;
2936 ListCell *arg;
2937 bool has_null_input = false;
2938 bool all_null_input = true;
2939 bool has_nonconst_input = false;
2940 bool has_nullable_nonconst = false;
2941 Expr *simple;
2943
2944 /*
2945 * Reduce constants in the DistinctExpr's arguments. We know
2946 * args is either NIL or a List node, so we can call
2947 * expression_tree_mutator directly rather than recursing to
2948 * self.
2949 */
2950 args = (List *) expression_tree_mutator((Node *) expr->args,
2952 context);
2953
2954 /*
2955 * We must do our own check for NULLs because DistinctExpr has
2956 * different results for NULL input than the underlying
2957 * operator does. We also check if any non-constant input is
2958 * potentially nullable.
2959 */
2960 foreach(arg, args)
2961 {
2962 if (IsA(lfirst(arg), Const))
2963 {
2966 }
2967 else
2968 {
2969 has_nonconst_input = true;
2970 all_null_input = false;
2971
2972 if (!has_nullable_nonconst &&
2973 !expr_is_nonnullable(context->root,
2974 (Expr *) lfirst(arg),
2976 has_nullable_nonconst = true;
2977 }
2978 }
2979
2980 if (!has_nonconst_input)
2981 {
2982 /*
2983 * All inputs are constants. We can optimize this out
2984 * completely.
2985 */
2986
2987 /* all nulls? then not distinct */
2988 if (all_null_input)
2989 return makeBoolConst(false, false);
2990
2991 /* one null? then distinct */
2992 if (has_null_input)
2993 return makeBoolConst(true, false);
2994
2995 /* otherwise try to evaluate the '=' operator */
2996 /* (NOT okay to try to inline it, though!) */
2997
2998 /*
2999 * Need to get OID of underlying function. Okay to
3000 * scribble on input to this extent.
3001 */
3002 set_opfuncid((OpExpr *) expr); /* rely on struct
3003 * equivalence */
3004
3005 /*
3006 * Code for op/func reduction is pretty bulky, so split it
3007 * out as a separate function.
3008 */
3009 simple = simplify_function(expr->opfuncid,
3010 expr->opresulttype, -1,
3011 expr->opcollid,
3012 expr->inputcollid,
3013 &args,
3014 false,
3015 false,
3016 false,
3017 context);
3018 if (simple) /* successfully simplified it */
3019 {
3020 /*
3021 * Since the underlying operator is "=", must negate
3022 * its result
3023 */
3024 Const *csimple = castNode(Const, simple);
3025
3026 csimple->constvalue =
3027 BoolGetDatum(!DatumGetBool(csimple->constvalue));
3028 return (Node *) csimple;
3029 }
3030 }
3031 else if (!has_nullable_nonconst)
3032 {
3033 /*
3034 * There are non-constant inputs, but since all of them
3035 * are proven non-nullable, "IS DISTINCT FROM" semantics
3036 * are much simpler.
3037 */
3038
3039 OpExpr *eqexpr;
3040
3041 /*
3042 * If one input is an explicit NULL constant, and the
3043 * other is a non-nullable expression, the result is
3044 * always TRUE.
3045 */
3046 if (has_null_input)
3047 return makeBoolConst(true, false);
3048
3049 /*
3050 * Otherwise, both inputs are known non-nullable. In this
3051 * case, "IS DISTINCT FROM" is equivalent to the standard
3052 * inequality operator (usually "<>"). We convert this to
3053 * an OpExpr, which is a more efficient representation for
3054 * the planner. It can enable the use of partial indexes
3055 * and constraint exclusion. Furthermore, if the clause
3056 * is negated (ie, "IS NOT DISTINCT FROM"), the resulting
3057 * "=" operator can allow the planner to use index scans,
3058 * merge joins, hash joins, and EC-based qual deductions.
3059 */
3061 eqexpr->opno = expr->opno;
3062 eqexpr->opfuncid = expr->opfuncid;
3063 eqexpr->opresulttype = BOOLOID;
3064 eqexpr->opretset = expr->opretset;
3065 eqexpr->opcollid = expr->opcollid;
3066 eqexpr->inputcollid = expr->inputcollid;
3067 eqexpr->args = args;
3068 eqexpr->location = expr->location;
3069
3071 context);
3072 }
3073 else if (has_null_input)
3074 {
3075 /*
3076 * One input is a nullable non-constant expression, and
3077 * the other is an explicit NULL constant. We can
3078 * transform this to a NullTest with !argisrow, which is
3079 * much more amenable to optimization.
3080 */
3081
3083
3084 nt->arg = (Expr *) (IsA(linitial(args), Const) ?
3085 lsecond(args) : linitial(args));
3086 nt->nulltesttype = IS_NOT_NULL;
3087
3088 /*
3089 * argisrow = false is correct whether or not arg is
3090 * composite
3091 */
3092 nt->argisrow = false;
3093 nt->location = expr->location;
3094
3095 return eval_const_expressions_mutator((Node *) nt, context);
3096 }
3097
3098 /*
3099 * The expression cannot be simplified any further, so build
3100 * and return a replacement DistinctExpr node using the
3101 * possibly-simplified arguments.
3102 */
3104 newexpr->opno = expr->opno;
3105 newexpr->opfuncid = expr->opfuncid;
3106 newexpr->opresulttype = expr->opresulttype;
3107 newexpr->opretset = expr->opretset;
3108 newexpr->opcollid = expr->opcollid;
3109 newexpr->inputcollid = expr->inputcollid;
3110 newexpr->args = args;
3111 newexpr->location = expr->location;
3112 return (Node *) newexpr;
3113 }
3114 case T_NullIfExpr:
3115 {
3116 NullIfExpr *expr;
3117 ListCell *arg;
3118 bool has_nonconst_input = false;
3119
3120 /* Copy the node and const-simplify its arguments */
3121 expr = (NullIfExpr *) ece_generic_processing(node);
3122
3123 /* If either argument is NULL they can't be equal */
3124 foreach(arg, expr->args)
3125 {
3126 if (!IsA(lfirst(arg), Const))
3127 has_nonconst_input = true;
3128 else if (((Const *) lfirst(arg))->constisnull)
3129 return (Node *) linitial(expr->args);
3130 }
3131
3132 /*
3133 * Need to get OID of underlying function before checking if
3134 * the function is OK to evaluate.
3135 */
3136 set_opfuncid((OpExpr *) expr);
3137
3138 if (!has_nonconst_input &&
3139 ece_function_is_safe(expr->opfuncid, context))
3140 return ece_evaluate_expr(expr);
3141
3142 return (Node *) expr;
3143 }
3145 {
3146 ScalarArrayOpExpr *saop;
3147
3148 /* Copy the node and const-simplify its arguments */
3150
3151 /* Make sure we know underlying function */
3152 set_sa_opfuncid(saop);
3153
3154 /*
3155 * If all arguments are Consts, and it's a safe function, we
3156 * can fold to a constant
3157 */
3158 if (ece_all_arguments_const(saop) &&
3159 ece_function_is_safe(saop->opfuncid, context))
3160 return ece_evaluate_expr(saop);
3161 return (Node *) saop;
3162 }
3163 case T_BoolExpr:
3164 {
3165 BoolExpr *expr = (BoolExpr *) node;
3166
3167 switch (expr->boolop)
3168 {
3169 case OR_EXPR:
3170 {
3171 List *newargs;
3172 bool haveNull = false;
3173 bool forceTrue = false;
3174
3176 context,
3177 &haveNull,
3178 &forceTrue);
3179 if (forceTrue)
3180 return makeBoolConst(true, false);
3181 if (haveNull)
3183 makeBoolConst(false, true));
3184 /* If all the inputs are FALSE, result is FALSE */
3185 if (newargs == NIL)
3186 return makeBoolConst(false, false);
3187
3188 /*
3189 * If only one nonconst-or-NULL input, it's the
3190 * result
3191 */
3192 if (list_length(newargs) == 1)
3193 return (Node *) linitial(newargs);
3194 /* Else we still need an OR node */
3195 return (Node *) make_orclause(newargs);
3196 }
3197 case AND_EXPR:
3198 {
3199 List *newargs;
3200 bool haveNull = false;
3201 bool forceFalse = false;
3202
3204 context,
3205 &haveNull,
3206 &forceFalse);
3207 if (forceFalse)
3208 return makeBoolConst(false, false);
3209 if (haveNull)
3211 makeBoolConst(false, true));
3212 /* If all the inputs are TRUE, result is TRUE */
3213 if (newargs == NIL)
3214 return makeBoolConst(true, false);
3215
3216 /*
3217 * If only one nonconst-or-NULL input, it's the
3218 * result
3219 */
3220 if (list_length(newargs) == 1)
3221 return (Node *) linitial(newargs);
3222 /* Else we still need an AND node */
3223 return (Node *) make_andclause(newargs);
3224 }
3225 case NOT_EXPR:
3226 {
3227 Node *arg;
3228
3229 Assert(list_length(expr->args) == 1);
3231 context);
3232
3233 /*
3234 * Use negate_clause() to see if we can simplify
3235 * away the NOT.
3236 */
3237 return negate_clause(arg);
3238 }
3239 default:
3240 elog(ERROR, "unrecognized boolop: %d",
3241 (int) expr->boolop);
3242 break;
3243 }
3244 break;
3245 }
3246 case T_JsonValueExpr:
3247 {
3248 JsonValueExpr *jve = (JsonValueExpr *) node;
3249 Node *raw_expr = (Node *) jve->raw_expr;
3250 Node *formatted_expr = (Node *) jve->formatted_expr;
3251
3252 /*
3253 * If we can fold formatted_expr to a constant, we can elide
3254 * the JsonValueExpr altogether. Otherwise we must process
3255 * raw_expr too. But JsonFormat is a flat node and requires
3256 * no simplification, only copying.
3257 */
3258 formatted_expr = eval_const_expressions_mutator(formatted_expr,
3259 context);
3260 if (formatted_expr && IsA(formatted_expr, Const))
3261 return formatted_expr;
3262
3263 raw_expr = eval_const_expressions_mutator(raw_expr, context);
3264
3265 return (Node *) makeJsonValueExpr((Expr *) raw_expr,
3266 (Expr *) formatted_expr,
3267 copyObject(jve->format));
3268 }
3270 {
3272
3273 /*
3274 * JSCTOR_JSON_ARRAY_QUERY carries a pre-built executable form
3275 * in its func field (a COALESCE-wrapped JSON_ARRAYAGG
3276 * subquery, constructed during parse analysis). Replace the
3277 * node with that expression and continue simplifying.
3278 */
3279 if (jce->type == JSCTOR_JSON_ARRAY_QUERY)
3280 return eval_const_expressions_mutator((Node *) jce->func,
3281 context);
3282 }
3283 break;
3284 case T_SubPlan:
3286
3287 /*
3288 * Return a SubPlan unchanged --- too late to do anything with it.
3289 *
3290 * XXX should we ereport() here instead? Probably this routine
3291 * should never be invoked after SubPlan creation.
3292 */
3293 return node;
3294 case T_RelabelType:
3295 {
3296 RelabelType *relabel = (RelabelType *) node;
3297 Node *arg;
3298
3299 /* Simplify the input ... */
3301 context);
3302 /* ... and attach a new RelabelType node, if needed */
3303 return applyRelabelType(arg,
3304 relabel->resulttype,
3305 relabel->resulttypmod,
3306 relabel->resultcollid,
3307 relabel->relabelformat,
3308 relabel->location,
3309 true);
3310 }
3311 case T_CoerceViaIO:
3312 {
3313 CoerceViaIO *expr = (CoerceViaIO *) node;
3314 List *args;
3315 Oid outfunc;
3316 bool outtypisvarlena;
3317 Oid infunc;
3319 Expr *simple;
3321
3322 /* Make a List so we can use simplify_function */
3323 args = list_make1(expr->arg);
3324
3325 /*
3326 * CoerceViaIO represents calling the source type's output
3327 * function then the result type's input function. So, try to
3328 * simplify it as though it were a stack of two such function
3329 * calls. First we need to know what the functions are.
3330 *
3331 * Note that the coercion functions are assumed not to care
3332 * about input collation, so we just pass InvalidOid for that.
3333 */
3337 &infunc, &intypioparam);
3338
3339 simple = simplify_function(outfunc,
3340 CSTRINGOID, -1,
3341 InvalidOid,
3342 InvalidOid,
3343 &args,
3344 false,
3345 true,
3346 true,
3347 context);
3348 if (simple) /* successfully simplified output fn */
3349 {
3350 /*
3351 * Input functions may want 1 to 3 arguments. We always
3352 * supply all three, trusting that nothing downstream will
3353 * complain.
3354 */
3355 args = list_make3(simple,
3357 -1,
3358 InvalidOid,
3359 sizeof(Oid),
3361 false,
3362 true),
3364 -1,
3365 InvalidOid,
3366 sizeof(int32),
3367 Int32GetDatum(-1),
3368 false,
3369 true));
3370
3371 simple = simplify_function(infunc,
3372 expr->resulttype, -1,
3373 expr->resultcollid,
3374 InvalidOid,
3375 &args,
3376 false,
3377 false,
3378 true,
3379 context);
3380 if (simple) /* successfully simplified input fn */
3381 return (Node *) simple;
3382 }
3383
3384 /*
3385 * The expression cannot be simplified any further, so build
3386 * and return a replacement CoerceViaIO node using the
3387 * possibly-simplified argument.
3388 */
3390 newexpr->arg = (Expr *) linitial(args);
3391 newexpr->resulttype = expr->resulttype;
3392 newexpr->resultcollid = expr->resultcollid;
3393 newexpr->coerceformat = expr->coerceformat;
3394 newexpr->location = expr->location;
3395 return (Node *) newexpr;
3396 }
3397 case T_ArrayCoerceExpr:
3398 {
3401
3402 /*
3403 * Copy the node and const-simplify its arguments. We can't
3404 * use ece_generic_processing() here because we need to mess
3405 * with case_val only while processing the elemexpr.
3406 */
3407 memcpy(ac, node, sizeof(ArrayCoerceExpr));
3408 ac->arg = (Expr *)
3410 context);
3411
3412 /*
3413 * Set up for the CaseTestExpr node contained in the elemexpr.
3414 * We must prevent it from absorbing any outer CASE value.
3415 */
3416 save_case_val = context->case_val;
3417 context->case_val = NULL;
3418
3419 ac->elemexpr = (Expr *)
3421 context);
3422
3423 context->case_val = save_case_val;
3424
3425 /*
3426 * If constant argument and the per-element expression is
3427 * immutable, we can simplify the whole thing to a constant.
3428 * Exception: although contain_mutable_functions considers
3429 * CoerceToDomain immutable for historical reasons, let's not
3430 * do so here; this ensures coercion to an array-over-domain
3431 * does not apply the domain's constraints until runtime.
3432 */
3433 if (ac->arg && IsA(ac->arg, Const) &&
3434 ac->elemexpr && !IsA(ac->elemexpr, CoerceToDomain) &&
3435 !contain_mutable_functions((Node *) ac->elemexpr))
3436 return ece_evaluate_expr(ac);
3437
3438 return (Node *) ac;
3439 }
3440 case T_CollateExpr:
3441 {
3442 /*
3443 * We replace CollateExpr with RelabelType, so as to improve
3444 * uniformity of expression representation and thus simplify
3445 * comparison of expressions. Hence this looks very nearly
3446 * the same as the RelabelType case, and we can apply the same
3447 * optimizations to avoid unnecessary RelabelTypes.
3448 */
3449 CollateExpr *collate = (CollateExpr *) node;
3450 Node *arg;
3451
3452 /* Simplify the input ... */
3454 context);
3455 /* ... and attach a new RelabelType node, if needed */
3456 return applyRelabelType(arg,
3457 exprType(arg),
3458 exprTypmod(arg),
3459 collate->collOid,
3461 collate->location,
3462 true);
3463 }
3464 case T_CaseExpr:
3465 {
3466 /*----------
3467 * CASE expressions can be simplified if there are constant
3468 * condition clauses:
3469 * FALSE (or NULL): drop the alternative
3470 * TRUE: drop all remaining alternatives
3471 * If the first non-FALSE alternative is a constant TRUE,
3472 * we can simplify the entire CASE to that alternative's
3473 * expression. If there are no non-FALSE alternatives,
3474 * we simplify the entire CASE to the default result (ELSE).
3475 *
3476 * If we have a simple-form CASE with constant test
3477 * expression, we substitute the constant value for contained
3478 * CaseTestExpr placeholder nodes, so that we have the
3479 * opportunity to reduce constant test conditions. For
3480 * example this allows
3481 * CASE 0 WHEN 0 THEN 1 ELSE 1/0 END
3482 * to reduce to 1 rather than drawing a divide-by-0 error.
3483 * Note that when the test expression is constant, we don't
3484 * have to include it in the resulting CASE; for example
3485 * CASE 0 WHEN x THEN y ELSE z END
3486 * is transformed by the parser to
3487 * CASE 0 WHEN CaseTestExpr = x THEN y ELSE z END
3488 * which we can simplify to
3489 * CASE WHEN 0 = x THEN y ELSE z END
3490 * It is not necessary for the executor to evaluate the "arg"
3491 * expression when executing the CASE, since any contained
3492 * CaseTestExprs that might have referred to it will have been
3493 * replaced by the constant.
3494 *----------
3495 */
3496 CaseExpr *caseexpr = (CaseExpr *) node;
3499 Node *newarg;
3500 List *newargs;
3501 bool const_true_cond;
3502 Node *defresult = NULL;
3503 ListCell *arg;
3504
3505 /* Simplify the test expression, if any */
3507 context);
3508
3509 /* Set up for contained CaseTestExpr nodes */
3510 save_case_val = context->case_val;
3511 if (newarg && IsA(newarg, Const))
3512 {
3513 context->case_val = newarg;
3514 newarg = NULL; /* not needed anymore, see above */
3515 }
3516 else
3517 context->case_val = NULL;
3518
3519 /* Simplify the WHEN clauses */
3520 newargs = NIL;
3521 const_true_cond = false;
3522 foreach(arg, caseexpr->args)
3523 {
3525 Node *casecond;
3527
3528 /* Simplify this alternative's test condition */
3530 context);
3531
3532 /*
3533 * If the test condition is constant FALSE (or NULL), then
3534 * drop this WHEN clause completely, without processing
3535 * the result.
3536 */
3537 if (casecond && IsA(casecond, Const))
3538 {
3540
3541 if (const_input->constisnull ||
3542 !DatumGetBool(const_input->constvalue))
3543 continue; /* drop alternative with FALSE cond */
3544 /* Else it's constant TRUE */
3545 const_true_cond = true;
3546 }
3547
3548 /* Simplify this alternative's result value */
3550 context);
3551
3552 /* If non-constant test condition, emit a new WHEN node */
3553 if (!const_true_cond)
3554 {
3556
3557 newcasewhen->expr = (Expr *) casecond;
3558 newcasewhen->result = (Expr *) caseresult;
3559 newcasewhen->location = oldcasewhen->location;
3561 continue;
3562 }
3563
3564 /*
3565 * Found a TRUE condition, so none of the remaining
3566 * alternatives can be reached. We treat the result as
3567 * the default result.
3568 */
3569 defresult = caseresult;
3570 break;
3571 }
3572
3573 /* Simplify the default result, unless we replaced it above */
3574 if (!const_true_cond)
3575 defresult = eval_const_expressions_mutator((Node *) caseexpr->defresult,
3576 context);
3577
3578 context->case_val = save_case_val;
3579
3580 /*
3581 * If no non-FALSE alternatives, CASE reduces to the default
3582 * result
3583 */
3584 if (newargs == NIL)
3585 return defresult;
3586 /* Otherwise we need a new CASE node */
3588 newcase->casetype = caseexpr->casetype;
3589 newcase->casecollid = caseexpr->casecollid;
3590 newcase->arg = (Expr *) newarg;
3591 newcase->args = newargs;
3592 newcase->defresult = (Expr *) defresult;
3593 newcase->location = caseexpr->location;
3594 return (Node *) newcase;
3595 }
3596 case T_CaseTestExpr:
3597 {
3598 /*
3599 * If we know a constant test value for the current CASE
3600 * construct, substitute it for the placeholder. Else just
3601 * return the placeholder as-is.
3602 */
3603 if (context->case_val)
3604 return copyObject(context->case_val);
3605 else
3606 return copyObject(node);
3607 }
3608 case T_SubscriptingRef:
3609 case T_ArrayExpr:
3610 case T_RowExpr:
3611 case T_MinMaxExpr:
3612 {
3613 /*
3614 * Generic handling for node types whose own processing is
3615 * known to be immutable, and for which we need no smarts
3616 * beyond "simplify if all inputs are constants".
3617 *
3618 * Treating SubscriptingRef this way assumes that subscripting
3619 * fetch and assignment are both immutable. This constrains
3620 * type-specific subscripting implementations; maybe we should
3621 * relax it someday.
3622 *
3623 * Treating MinMaxExpr this way amounts to assuming that the
3624 * btree comparison function it calls is immutable; see the
3625 * reasoning in contain_mutable_functions_walker.
3626 */
3627
3628 /* Copy the node and const-simplify its arguments */
3629 node = ece_generic_processing(node);
3630 /* If all arguments are Consts, we can fold to a constant */
3631 if (ece_all_arguments_const(node))
3632 return ece_evaluate_expr(node);
3633 return node;
3634 }
3635 case T_CoalesceExpr:
3636 {
3639 List *newargs;
3640 ListCell *arg;
3641
3642 newargs = NIL;
3643 foreach(arg, coalesceexpr->args)
3644 {
3645 Node *e;
3646
3648 context);
3649
3650 /*
3651 * We can remove null constants from the list. For a
3652 * nonnullable expression, if it has not been preceded by
3653 * any non-null-constant expressions then it is the
3654 * result. Otherwise, it's the next argument, but we can
3655 * drop following arguments since they will never be
3656 * reached.
3657 */
3658 if (IsA(e, Const))
3659 {
3660 if (((Const *) e)->constisnull)
3661 continue; /* drop null constant */
3662 if (newargs == NIL)
3663 return e; /* first expr */
3665 break;
3666 }
3667 if (expr_is_nonnullable(context->root, (Expr *) e,
3669 {
3670 if (newargs == NIL)
3671 return e; /* first expr */
3673 break;
3674 }
3675
3677 }
3678
3679 /*
3680 * If all the arguments were constant null, the result is just
3681 * null
3682 */
3683 if (newargs == NIL)
3684 return (Node *) makeNullConst(coalesceexpr->coalescetype,
3685 -1,
3686 coalesceexpr->coalescecollid);
3687
3688 /*
3689 * If there's exactly one surviving argument, we no longer
3690 * need COALESCE at all: the result is that argument
3691 */
3692 if (list_length(newargs) == 1)
3693 return (Node *) linitial(newargs);
3694
3696 newcoalesce->coalescetype = coalesceexpr->coalescetype;
3697 newcoalesce->coalescecollid = coalesceexpr->coalescecollid;
3698 newcoalesce->args = newargs;
3699 newcoalesce->location = coalesceexpr->location;
3700 return (Node *) newcoalesce;
3701 }
3702 case T_SQLValueFunction:
3703 {
3704 /*
3705 * All variants of SQLValueFunction are stable, so if we are
3706 * estimating the expression's value, we should evaluate the
3707 * current function value. Otherwise just copy.
3708 */
3709 SQLValueFunction *svf = (SQLValueFunction *) node;
3710
3711 if (context->estimate)
3712 return (Node *) evaluate_expr((Expr *) svf,
3713 svf->type,
3714 svf->typmod,
3715 InvalidOid);
3716 else
3717 return copyObject((Node *) svf);
3718 }
3719 case T_FieldSelect:
3720 {
3721 /*
3722 * We can optimize field selection from a whole-row Var into a
3723 * simple Var. (This case won't be generated directly by the
3724 * parser, because ParseComplexProjection short-circuits it.
3725 * But it can arise while simplifying functions.) Also, we
3726 * can optimize field selection from a RowExpr construct, or
3727 * of course from a constant.
3728 *
3729 * However, replacing a whole-row Var in this way has a
3730 * pitfall: if we've already built the rel targetlist for the
3731 * source relation, then the whole-row Var is scheduled to be
3732 * produced by the relation scan, but the simple Var probably
3733 * isn't, which will lead to a failure in setrefs.c. This is
3734 * not a problem when handling simple single-level queries, in
3735 * which expression simplification always happens first. It
3736 * is a risk for lateral references from subqueries, though.
3737 * To avoid such failures, don't optimize uplevel references.
3738 *
3739 * We must also check that the declared type of the field is
3740 * still the same as when the FieldSelect was created --- this
3741 * can change if someone did ALTER COLUMN TYPE on the rowtype.
3742 * If it isn't, we skip the optimization; the case will
3743 * probably fail at runtime, but that's not our problem here.
3744 */
3745 FieldSelect *fselect = (FieldSelect *) node;
3747 Node *arg;
3748
3750 context);
3751 if (arg && IsA(arg, Var) &&
3752 ((Var *) arg)->varattno == InvalidAttrNumber &&
3753 ((Var *) arg)->varlevelsup == 0)
3754 {
3755 if (rowtype_field_matches(((Var *) arg)->vartype,
3756 fselect->fieldnum,
3757 fselect->resulttype,
3758 fselect->resulttypmod,
3759 fselect->resultcollid))
3760 {
3761 Var *newvar;
3762
3763 newvar = makeVar(((Var *) arg)->varno,
3764 fselect->fieldnum,
3765 fselect->resulttype,
3766 fselect->resulttypmod,
3767 fselect->resultcollid,
3768 ((Var *) arg)->varlevelsup);
3769 /* New Var has same OLD/NEW returning as old one */
3770 newvar->varreturningtype = ((Var *) arg)->varreturningtype;
3771 /* New Var is nullable by same rels as the old one */
3772 newvar->varnullingrels = ((Var *) arg)->varnullingrels;
3773 return (Node *) newvar;
3774 }
3775 }
3776 if (arg && IsA(arg, RowExpr))
3777 {
3778 RowExpr *rowexpr = (RowExpr *) arg;
3779
3780 if (fselect->fieldnum > 0 &&
3781 fselect->fieldnum <= list_length(rowexpr->args))
3782 {
3783 Node *fld = (Node *) list_nth(rowexpr->args,
3784 fselect->fieldnum - 1);
3785
3786 if (rowtype_field_matches(rowexpr->row_typeid,
3787 fselect->fieldnum,
3788 fselect->resulttype,
3789 fselect->resulttypmod,
3790 fselect->resultcollid) &&
3791 fselect->resulttype == exprType(fld) &&
3792 fselect->resulttypmod == exprTypmod(fld) &&
3793 fselect->resultcollid == exprCollation(fld))
3794 return fld;
3795 }
3796 }
3798 newfselect->arg = (Expr *) arg;
3799 newfselect->fieldnum = fselect->fieldnum;
3800 newfselect->resulttype = fselect->resulttype;
3801 newfselect->resulttypmod = fselect->resulttypmod;
3802 newfselect->resultcollid = fselect->resultcollid;
3803 if (arg && IsA(arg, Const))
3804 {
3805 Const *con = (Const *) arg;
3806
3808 newfselect->fieldnum,
3809 newfselect->resulttype,
3810 newfselect->resulttypmod,
3811 newfselect->resultcollid))
3813 }
3814 return (Node *) newfselect;
3815 }
3816 case T_NullTest:
3817 {
3818 NullTest *ntest = (NullTest *) node;
3820 Node *arg;
3821
3823 context);
3824 if (ntest->argisrow && arg && IsA(arg, RowExpr))
3825 {
3826 /*
3827 * We break ROW(...) IS [NOT] NULL into separate tests on
3828 * its component fields. This form is usually more
3829 * efficient to evaluate, as well as being more amenable
3830 * to optimization.
3831 */
3832 RowExpr *rarg = (RowExpr *) arg;
3833 List *newargs = NIL;
3834 ListCell *l;
3835
3836 foreach(l, rarg->args)
3837 {
3838 Node *relem = (Node *) lfirst(l);
3839
3840 /*
3841 * A constant field refutes the whole NullTest if it's
3842 * of the wrong nullness; else we can discard it.
3843 */
3844 if (relem && IsA(relem, Const))
3845 {
3846 Const *carg = (Const *) relem;
3847
3848 if (carg->constisnull ?
3849 (ntest->nulltesttype == IS_NOT_NULL) :
3850 (ntest->nulltesttype == IS_NULL))
3851 return makeBoolConst(false, false);
3852 continue;
3853 }
3854
3855 /*
3856 * A proven non-nullable field refutes the whole
3857 * NullTest if the test is IS NULL; else we can
3858 * discard it.
3859 */
3860 if (relem &&
3861 expr_is_nonnullable(context->root, (Expr *) relem,
3863 {
3864 if (ntest->nulltesttype == IS_NULL)
3865 return makeBoolConst(false, false);
3866 continue;
3867 }
3868
3869 /*
3870 * Else, make a scalar (argisrow == false) NullTest
3871 * for this field. Scalar semantics are required
3872 * because IS [NOT] NULL doesn't recurse; see comments
3873 * in ExecEvalRowNullInt().
3874 */
3876 newntest->arg = (Expr *) relem;
3877 newntest->nulltesttype = ntest->nulltesttype;
3878 newntest->argisrow = false;
3879 newntest->location = ntest->location;
3881 }
3882 /* If all the inputs were constants, result is TRUE */
3883 if (newargs == NIL)
3884 return makeBoolConst(true, false);
3885 /* If only one nonconst input, it's the result */
3886 if (list_length(newargs) == 1)
3887 return (Node *) linitial(newargs);
3888 /* Else we need an AND node */
3889 return (Node *) make_andclause(newargs);
3890 }
3891 if (!ntest->argisrow && arg && IsA(arg, Const))
3892 {
3893 Const *carg = (Const *) arg;
3894 bool result;
3895
3896 switch (ntest->nulltesttype)
3897 {
3898 case IS_NULL:
3899 result = carg->constisnull;
3900 break;
3901 case IS_NOT_NULL:
3902 result = !carg->constisnull;
3903 break;
3904 default:
3905 elog(ERROR, "unrecognized nulltesttype: %d",
3906 (int) ntest->nulltesttype);
3907 result = false; /* keep compiler quiet */
3908 break;
3909 }
3910
3911 return makeBoolConst(result, false);
3912 }
3913 if (!ntest->argisrow && arg &&
3914 expr_is_nonnullable(context->root, (Expr *) arg,
3916 {
3917 bool result;
3918
3919 switch (ntest->nulltesttype)
3920 {
3921 case IS_NULL:
3922 result = false;
3923 break;
3924 case IS_NOT_NULL:
3925 result = true;
3926 break;
3927 default:
3928 elog(ERROR, "unrecognized nulltesttype: %d",
3929 (int) ntest->nulltesttype);
3930 result = false; /* keep compiler quiet */
3931 break;
3932 }
3933
3934 return makeBoolConst(result, false);
3935 }
3936
3938 newntest->arg = (Expr *) arg;
3939 newntest->nulltesttype = ntest->nulltesttype;
3940 newntest->argisrow = ntest->argisrow;
3941 newntest->location = ntest->location;
3942 return (Node *) newntest;
3943 }
3944 case T_BooleanTest:
3945 {
3946 /*
3947 * This case could be folded into the generic handling used
3948 * for ArrayExpr etc. But because the simplification logic is
3949 * so trivial, applying evaluate_expr() to perform it would be
3950 * a heavy overhead. BooleanTest is probably common enough to
3951 * justify keeping this bespoke implementation.
3952 */
3953 BooleanTest *btest = (BooleanTest *) node;
3955 Node *arg;
3956
3958 context);
3959 if (arg && IsA(arg, Const))
3960 {
3961 /*
3962 * If arg is Const, simplify to constant.
3963 */
3964 Const *carg = (Const *) arg;
3965 bool result;
3966
3967 switch (btest->booltesttype)
3968 {
3969 case IS_TRUE:
3970 result = (!carg->constisnull &&
3971 DatumGetBool(carg->constvalue));
3972 break;
3973 case IS_NOT_TRUE:
3974 result = (carg->constisnull ||
3975 !DatumGetBool(carg->constvalue));
3976 break;
3977 case IS_FALSE:
3978 result = (!carg->constisnull &&
3979 !DatumGetBool(carg->constvalue));
3980 break;
3981 case IS_NOT_FALSE:
3982 result = (carg->constisnull ||
3983 DatumGetBool(carg->constvalue));
3984 break;
3985 case IS_UNKNOWN:
3986 result = carg->constisnull;
3987 break;
3988 case IS_NOT_UNKNOWN:
3989 result = !carg->constisnull;
3990 break;
3991 default:
3992 elog(ERROR, "unrecognized booltesttype: %d",
3993 (int) btest->booltesttype);
3994 result = false; /* keep compiler quiet */
3995 break;
3996 }
3997
3998 return makeBoolConst(result, false);
3999 }
4000 if (arg &&
4001 expr_is_nonnullable(context->root, (Expr *) arg,
4003 {
4004 /*
4005 * If arg is proven non-nullable, simplify to boolean
4006 * expression or constant.
4007 */
4008 switch (btest->booltesttype)
4009 {
4010 case IS_TRUE:
4011 case IS_NOT_FALSE:
4012 return arg;
4013
4014 case IS_FALSE:
4015 case IS_NOT_TRUE:
4016 return (Node *) make_notclause((Expr *) arg);
4017
4018 case IS_UNKNOWN:
4019 return makeBoolConst(false, false);
4020
4021 case IS_NOT_UNKNOWN:
4022 return makeBoolConst(true, false);
4023
4024 default:
4025 elog(ERROR, "unrecognized booltesttype: %d",
4026 (int) btest->booltesttype);
4027 break;
4028 }
4029 }
4030
4032 newbtest->arg = (Expr *) arg;
4033 newbtest->booltesttype = btest->booltesttype;
4034 newbtest->location = btest->location;
4035 return (Node *) newbtest;
4036 }
4037 case T_CoerceToDomain:
4038 {
4039 /*
4040 * If the domain currently has no constraints, we replace the
4041 * CoerceToDomain node with a simple RelabelType, which is
4042 * both far faster to execute and more amenable to later
4043 * optimization. We must then mark the plan as needing to be
4044 * rebuilt if the domain's constraints change.
4045 *
4046 * Also, in estimation mode, always replace CoerceToDomain
4047 * nodes, effectively assuming that the coercion will succeed.
4048 */
4051 Node *arg;
4052
4054 context);
4055 if (context->estimate ||
4056 !DomainHasConstraints(cdomain->resulttype, NULL))
4057 {
4058 /* Record dependency, if this isn't estimation mode */
4059 if (context->root && !context->estimate)
4060 record_plan_type_dependency(context->root,
4061 cdomain->resulttype);
4062
4063 /* Generate RelabelType to substitute for CoerceToDomain */
4064 return applyRelabelType(arg,
4065 cdomain->resulttype,
4066 cdomain->resulttypmod,
4067 cdomain->resultcollid,
4068 cdomain->coercionformat,
4069 cdomain->location,
4070 true);
4071 }
4072
4074 newcdomain->arg = (Expr *) arg;
4075 newcdomain->resulttype = cdomain->resulttype;
4076 newcdomain->resulttypmod = cdomain->resulttypmod;
4077 newcdomain->resultcollid = cdomain->resultcollid;
4078 newcdomain->coercionformat = cdomain->coercionformat;
4079 newcdomain->location = cdomain->location;
4080 return (Node *) newcdomain;
4081 }
4082 case T_PlaceHolderVar:
4083
4084 /*
4085 * In estimation mode, just strip the PlaceHolderVar node
4086 * altogether; this amounts to estimating that the contained value
4087 * won't be forced to null by an outer join. In regular mode we
4088 * just use the default behavior (ie, simplify the expression but
4089 * leave the PlaceHolderVar node intact).
4090 */
4091 if (context->estimate)
4092 {
4093 PlaceHolderVar *phv = (PlaceHolderVar *) node;
4094
4095 return eval_const_expressions_mutator((Node *) phv->phexpr,
4096 context);
4097 }
4098 break;
4100 {
4102 Node *arg;
4104
4106 context);
4107
4109 newcre->resulttype = cre->resulttype;
4110 newcre->convertformat = cre->convertformat;
4111 newcre->location = cre->location;
4112
4113 /*
4114 * In case of a nested ConvertRowtypeExpr, we can convert the
4115 * leaf row directly to the topmost row format without any
4116 * intermediate conversions. (This works because
4117 * ConvertRowtypeExpr is used only for child->parent
4118 * conversion in inheritance trees, which works by exact match
4119 * of column name, and a column absent in an intermediate
4120 * result can't be present in the final result.)
4121 *
4122 * No need to check more than one level deep, because the
4123 * above recursion will have flattened anything else.
4124 */
4125 if (arg != NULL && IsA(arg, ConvertRowtypeExpr))
4126 {
4128
4129 arg = (Node *) argcre->arg;
4130
4131 /*
4132 * Make sure an outer implicit conversion can't hide an
4133 * inner explicit one.
4134 */
4135 if (newcre->convertformat == COERCE_IMPLICIT_CAST)
4136 newcre->convertformat = argcre->convertformat;
4137 }
4138
4139 newcre->arg = (Expr *) arg;
4140
4141 if (arg != NULL && IsA(arg, Const))
4142 return ece_evaluate_expr((Node *) newcre);
4143 return (Node *) newcre;
4144 }
4145 default:
4146 break;
4147 }
4148
4149 /*
4150 * For any node type not handled above, copy the node unchanged but
4151 * const-simplify its subexpressions. This is the correct thing for node
4152 * types whose behavior might change between planning and execution, such
4153 * as CurrentOfExpr. It's also a safe default for new node types not
4154 * known to this routine.
4155 */
4156 return ece_generic_processing(node);
4157}
4158
4159/*
4160 * Subroutine for eval_const_expressions: check for non-Const nodes.
4161 *
4162 * We can abort recursion immediately on finding a non-Const node. This is
4163 * critical for performance, else eval_const_expressions_mutator would take
4164 * O(N^2) time on non-simplifiable trees. However, we do need to descend
4165 * into List nodes since expression_tree_walker sometimes invokes the walker
4166 * function directly on List subtrees.
4167 */
4168static bool
4169contain_non_const_walker(Node *node, void *context)
4170{
4171 if (node == NULL)
4172 return false;
4173 if (IsA(node, Const))
4174 return false;
4175 if (IsA(node, List))
4176 return expression_tree_walker(node, contain_non_const_walker, context);
4177 /* Otherwise, abort the tree traversal and return true */
4178 return true;
4179}
4180
4181/*
4182 * Subroutine for eval_const_expressions: check if a function is OK to evaluate
4183 */
4184static bool
4186{
4187 char provolatile = func_volatile(funcid);
4188
4189 /*
4190 * Ordinarily we are only allowed to simplify immutable functions. But for
4191 * purposes of estimation, we consider it okay to simplify functions that
4192 * are merely stable; the risk that the result might change from planning
4193 * time to execution time is worth taking in preference to not being able
4194 * to estimate the value at all.
4195 */
4197 return true;
4198 if (context->estimate && provolatile == PROVOLATILE_STABLE)
4199 return true;
4200 return false;
4201}
4202
4203/*
4204 * Subroutine for eval_const_expressions: process arguments of an OR clause
4205 *
4206 * This includes flattening of nested ORs as well as recursion to
4207 * eval_const_expressions to simplify the OR arguments.
4208 *
4209 * After simplification, OR arguments are handled as follows:
4210 * non constant: keep
4211 * FALSE: drop (does not affect result)
4212 * TRUE: force result to TRUE
4213 * NULL: keep only one
4214 * We must keep one NULL input because OR expressions evaluate to NULL when no
4215 * input is TRUE and at least one is NULL. We don't actually include the NULL
4216 * here, that's supposed to be done by the caller.
4217 *
4218 * The output arguments *haveNull and *forceTrue must be initialized false
4219 * by the caller. They will be set true if a NULL constant or TRUE constant,
4220 * respectively, is detected anywhere in the argument list.
4221 */
4222static List *
4225 bool *haveNull, bool *forceTrue)
4226{
4227 List *newargs = NIL;
4229
4230 /*
4231 * We want to ensure that any OR immediately beneath another OR gets
4232 * flattened into a single OR-list, so as to simplify later reasoning.
4233 *
4234 * To avoid stack overflow from recursion of eval_const_expressions, we
4235 * resort to some tenseness here: we keep a list of not-yet-processed
4236 * inputs, and handle flattening of nested ORs by prepending to the to-do
4237 * list instead of recursing. Now that the parser generates N-argument
4238 * ORs from simple lists, this complexity is probably less necessary than
4239 * it once was, but we might as well keep the logic.
4240 */
4242 while (unprocessed_args)
4243 {
4245
4247
4248 /* flatten nested ORs as per above comment */
4249 if (is_orclause(arg))
4250 {
4251 List *subargs = ((BoolExpr *) arg)->args;
4253
4255 /* perhaps-overly-tense code to avoid leaking old lists */
4257 continue;
4258 }
4259
4260 /* If it's not an OR, simplify it */
4262
4263 /*
4264 * It is unlikely but not impossible for simplification of a non-OR
4265 * clause to produce an OR. Recheck, but don't be too tense about it
4266 * since it's not a mainstream case. In particular we don't worry
4267 * about const-simplifying the input twice, nor about list leakage.
4268 */
4269 if (is_orclause(arg))
4270 {
4271 List *subargs = ((BoolExpr *) arg)->args;
4272
4274 continue;
4275 }
4276
4277 /*
4278 * OK, we have a const-simplified non-OR argument. Process it per
4279 * comments above.
4280 */
4281 if (IsA(arg, Const))
4282 {
4283 Const *const_input = (Const *) arg;
4284
4285 if (const_input->constisnull)
4286 *haveNull = true;
4287 else if (DatumGetBool(const_input->constvalue))
4288 {
4289 *forceTrue = true;
4290
4291 /*
4292 * Once we detect a TRUE result we can just exit the loop
4293 * immediately. However, if we ever add a notion of
4294 * non-removable functions, we'd need to keep scanning.
4295 */
4296 return NIL;
4297 }
4298 /* otherwise, we can drop the constant-false input */
4299 continue;
4300 }
4301
4302 /* else emit the simplified arg into the result list */
4304 }
4305
4306 return newargs;
4307}
4308
4309/*
4310 * Subroutine for eval_const_expressions: process arguments of an AND clause
4311 *
4312 * This includes flattening of nested ANDs as well as recursion to
4313 * eval_const_expressions to simplify the AND arguments.
4314 *
4315 * After simplification, AND arguments are handled as follows:
4316 * non constant: keep
4317 * TRUE: drop (does not affect result)
4318 * FALSE: force result to FALSE
4319 * NULL: keep only one
4320 * We must keep one NULL input because AND expressions evaluate to NULL when
4321 * no input is FALSE and at least one is NULL. We don't actually include the
4322 * NULL here, that's supposed to be done by the caller.
4323 *
4324 * The output arguments *haveNull and *forceFalse must be initialized false
4325 * by the caller. They will be set true if a null constant or false constant,
4326 * respectively, is detected anywhere in the argument list.
4327 */
4328static List *
4331 bool *haveNull, bool *forceFalse)
4332{
4333 List *newargs = NIL;
4335
4336 /* See comments in simplify_or_arguments */
4338 while (unprocessed_args)
4339 {
4341
4343
4344 /* flatten nested ANDs as per above comment */
4345 if (is_andclause(arg))
4346 {
4347 List *subargs = ((BoolExpr *) arg)->args;
4349
4351 /* perhaps-overly-tense code to avoid leaking old lists */
4353 continue;
4354 }
4355
4356 /* If it's not an AND, simplify it */
4358
4359 /*
4360 * It is unlikely but not impossible for simplification of a non-AND
4361 * clause to produce an AND. Recheck, but don't be too tense about it
4362 * since it's not a mainstream case. In particular we don't worry
4363 * about const-simplifying the input twice, nor about list leakage.
4364 */
4365 if (is_andclause(arg))
4366 {
4367 List *subargs = ((BoolExpr *) arg)->args;
4368
4370 continue;
4371 }
4372
4373 /*
4374 * OK, we have a const-simplified non-AND argument. Process it per
4375 * comments above.
4376 */
4377 if (IsA(arg, Const))
4378 {
4379 Const *const_input = (Const *) arg;
4380
4381 if (const_input->constisnull)
4382 *haveNull = true;
4383 else if (!DatumGetBool(const_input->constvalue))
4384 {
4385 *forceFalse = true;
4386
4387 /*
4388 * Once we detect a FALSE result we can just exit the loop
4389 * immediately. However, if we ever add a notion of
4390 * non-removable functions, we'd need to keep scanning.
4391 */
4392 return NIL;
4393 }
4394 /* otherwise, we can drop the constant-true input */
4395 continue;
4396 }
4397
4398 /* else emit the simplified arg into the result list */
4400 }
4401
4402 return newargs;
4403}
4404
4405/*
4406 * Subroutine for eval_const_expressions: try to simplify boolean equality
4407 * or inequality condition
4408 *
4409 * Inputs are the operator OID and the simplified arguments to the operator.
4410 * Returns a simplified expression if successful, or NULL if cannot
4411 * simplify the expression.
4412 *
4413 * The idea here is to reduce "x = true" to "x" and "x = false" to "NOT x",
4414 * or similarly "x <> true" to "NOT x" and "x <> false" to "x".
4415 * This is only marginally useful in itself, but doing it in constant folding
4416 * ensures that we will recognize these forms as being equivalent in, for
4417 * example, partial index matching.
4418 *
4419 * We come here only if simplify_function has failed; therefore we cannot
4420 * see two constant inputs, nor a constant-NULL input.
4421 */
4422static Node *
4424{
4425 Node *leftop;
4426 Node *rightop;
4427
4428 Assert(list_length(args) == 2);
4429 leftop = linitial(args);
4430 rightop = lsecond(args);
4431 if (leftop && IsA(leftop, Const))
4432 {
4433 Assert(!((Const *) leftop)->constisnull);
4434 if (opno == BooleanEqualOperator)
4435 {
4436 if (DatumGetBool(((Const *) leftop)->constvalue))
4437 return rightop; /* true = foo */
4438 else
4439 return negate_clause(rightop); /* false = foo */
4440 }
4441 else
4442 {
4443 if (DatumGetBool(((Const *) leftop)->constvalue))
4444 return negate_clause(rightop); /* true <> foo */
4445 else
4446 return rightop; /* false <> foo */
4447 }
4448 }
4449 if (rightop && IsA(rightop, Const))
4450 {
4452 if (opno == BooleanEqualOperator)
4453 {
4455 return leftop; /* foo = true */
4456 else
4457 return negate_clause(leftop); /* foo = false */
4458 }
4459 else
4460 {
4462 return negate_clause(leftop); /* foo <> true */
4463 else
4464 return leftop; /* foo <> false */
4465 }
4466 }
4467 return NULL;
4468}
4469
4470/*
4471 * Subroutine for eval_const_expressions: try to simplify a function call
4472 * (which might originally have been an operator; we don't care)
4473 *
4474 * Inputs are the function OID, actual result type OID (which is needed for
4475 * polymorphic functions), result typmod, result collation, the input
4476 * collation to use for the function, the original argument list (not
4477 * const-simplified yet, unless process_args is false), and some flags;
4478 * also the context data for eval_const_expressions.
4479 *
4480 * Returns a simplified expression if successful, or NULL if cannot
4481 * simplify the function call.
4482 *
4483 * This function is also responsible for converting named-notation argument
4484 * lists into positional notation and/or adding any needed default argument
4485 * expressions; which is a bit grotty, but it avoids extra fetches of the
4486 * function's pg_proc tuple. For this reason, the args list is
4487 * pass-by-reference. Conversion and const-simplification of the args list
4488 * will be done even if simplification of the function call itself is not
4489 * possible.
4490 */
4491static Expr *
4492simplify_function(Oid funcid, Oid result_type, int32 result_typmod,
4494 bool funcvariadic, bool process_args, bool allow_non_const,
4496{
4497 List *args = *args_p;
4500 Expr *newexpr;
4501
4502 /*
4503 * We have three strategies for simplification: execute the function to
4504 * deliver a constant result, use a transform function to generate a
4505 * substitute node tree, or expand in-line the body of the function
4506 * definition (which only works for simple SQL-language functions, but
4507 * that is a common case). Each case needs access to the function's
4508 * pg_proc tuple, so fetch it just once.
4509 *
4510 * Note: the allow_non_const flag suppresses both the second and third
4511 * strategies; so if !allow_non_const, simplify_function can only return a
4512 * Const or NULL. Argument-list rewriting happens anyway, though.
4513 */
4516 elog(ERROR, "cache lookup failed for function %u", funcid);
4518
4519 /*
4520 * Process the function arguments, unless the caller did it already.
4521 *
4522 * Here we must deal with named or defaulted arguments, and then
4523 * recursively apply eval_const_expressions to the whole argument list.
4524 */
4525 if (process_args)
4526 {
4527 args = expand_function_arguments(args, false, result_type, func_tuple);
4530 context);
4531 /* Argument processing done, give it back to the caller */
4532 *args_p = args;
4533 }
4534
4535 /* Now attempt simplification of the function call proper. */
4536
4537 newexpr = evaluate_function(funcid, result_type, result_typmod,
4539 args, funcvariadic,
4540 func_tuple, context);
4541
4542 if (!newexpr && allow_non_const && OidIsValid(func_form->prosupport))
4543 {
4544 /*
4545 * Build a SupportRequestSimplify node to pass to the support
4546 * function, pointing to a dummy FuncExpr node containing the
4547 * simplified arg list. We use this approach to present a uniform
4548 * interface to the support function regardless of how the target
4549 * function is actually being invoked.
4550 */
4553
4554 fexpr.xpr.type = T_FuncExpr;
4555 fexpr.funcid = funcid;
4556 fexpr.funcresulttype = result_type;
4557 fexpr.funcretset = func_form->proretset;
4558 fexpr.funcvariadic = funcvariadic;
4559 fexpr.funcformat = COERCE_EXPLICIT_CALL;
4560 fexpr.funccollid = result_collid;
4561 fexpr.inputcollid = input_collid;
4562 fexpr.args = args;
4563 fexpr.location = -1;
4564
4566 req.root = context->root;
4567 req.fcall = &fexpr;
4568
4569 newexpr = (Expr *)
4571 PointerGetDatum(&req)));
4572
4573 /* catch a possible API misunderstanding */
4574 Assert(newexpr != (Expr *) &fexpr);
4575 }
4576
4577 if (!newexpr && allow_non_const)
4578 newexpr = inline_function(funcid, result_type, result_collid,
4580 func_tuple, context);
4581
4583
4584 return newexpr;
4585}
4586
4587/*
4588 * simplify_aggref
4589 * Call the Aggref.aggfnoid's prosupport function to allow it to
4590 * determine if simplification of the Aggref is possible. Returns the
4591 * newly simplified node if conversion took place; otherwise, returns the
4592 * original Aggref.
4593 *
4594 * See SupportRequestSimplifyAggref comments in supportnodes.h for further
4595 * details.
4596 */
4597static Node *
4599{
4601
4603 {
4605 Node *newnode;
4606
4607 /*
4608 * Build a SupportRequestSimplifyAggref node to pass to the support
4609 * function.
4610 */
4612 req.root = context->root;
4613 req.aggref = aggref;
4614
4616 PointerGetDatum(&req)));
4617
4618 /*
4619 * We expect the support function to return either a new Node or NULL
4620 * (when simplification isn't possible).
4621 */
4622 Assert(newnode != (Node *) aggref || newnode == NULL);
4623
4624 if (newnode != NULL)
4625 return newnode;
4626 }
4627
4628 return (Node *) aggref;
4629}
4630
4631/*
4632 * var_is_nonnullable: check to see if the Var cannot be NULL
4633 *
4634 * If the Var is defined NOT NULL and meanwhile is not nulled by any outer
4635 * joins or grouping sets, then we can know that it cannot be NULL.
4636 *
4637 * "source" specifies where we should look for NOT NULL proofs.
4638 */
4639bool
4641{
4642 Assert(IsA(var, Var));
4643
4644 /* skip upper-level Vars */
4645 if (var->varlevelsup != 0)
4646 return false;
4647
4648 /* could the Var be nulled by any outer joins or grouping sets? */
4649 if (!bms_is_empty(var->varnullingrels))
4650 return false;
4651
4652 /*
4653 * If the Var has a non-default returning type, it could be NULL
4654 * regardless of any NOT NULL constraint. For example, OLD.col is NULL
4655 * for INSERT, and NEW.col is NULL for DELETE.
4656 */
4658 return false;
4659
4660 /* system columns cannot be NULL */
4661 if (var->varattno < 0)
4662 return true;
4663
4664 /* we don't trust whole-row Vars */
4665 if (var->varattno == 0)
4666 return false;
4667
4668 /* Check if the Var is defined as NOT NULL. */
4669 switch (source)
4670 {
4672 {
4673 /*
4674 * We retrieve the column NOT NULL constraint information from
4675 * the corresponding RelOptInfo.
4676 */
4677 RelOptInfo *rel;
4678 Bitmapset *notnullattnums;
4679
4680 rel = find_base_rel(root, var->varno);
4681 notnullattnums = rel->notnullattnums;
4682
4683 return bms_is_member(var->varattno, notnullattnums);
4684 }
4686 {
4687 /*
4688 * We retrieve the column NOT NULL constraint information from
4689 * the hash table.
4690 */
4692 Bitmapset *notnullattnums;
4693
4694 rte = planner_rt_fetch(var->varno, root);
4695
4696 /* We can only reason about ordinary relations */
4697 if (rte->rtekind != RTE_RELATION)
4698 return false;
4699
4700 /*
4701 * We must skip inheritance parent tables, as some child
4702 * tables may have a NOT NULL constraint for a column while
4703 * others may not. This cannot happen with partitioned
4704 * tables, though.
4705 */
4706 if (rte->inh && rte->relkind != RELKIND_PARTITIONED_TABLE)
4707 return false;
4708
4709 notnullattnums = find_relation_notnullatts(root, rte->relid);
4710
4711 return bms_is_member(var->varattno, notnullattnums);
4712 }
4714 {
4715 /*
4716 * We check the attnullability field in the tuple descriptor.
4717 * This is necessary rather than checking the attnotnull field
4718 * from the attribute relation, because attnotnull is also set
4719 * for invalid (NOT VALID) NOT NULL constraints, which do not
4720 * guarantee the absence of NULLs.
4721 */
4723 Relation rel;
4724 CompactAttribute *attr;
4725 bool result;
4726
4727 rte = planner_rt_fetch(var->varno, root);
4728
4729 /* We can only reason about ordinary relations */
4730 if (rte->rtekind != RTE_RELATION)
4731 return false;
4732
4733 /*
4734 * We must skip inheritance parent tables, as some child
4735 * tables may have a NOT NULL constraint for a column while
4736 * others may not. This cannot happen with partitioned
4737 * tables, though.
4738 *
4739 * Note that we need to check if the relation actually has any
4740 * children, as we might not have done that yet.
4741 */
4742 if (rte->inh && has_subclass(rte->relid) &&
4743 rte->relkind != RELKIND_PARTITIONED_TABLE)
4744 return false;
4745
4746 /* We need not lock the relation since it was already locked */
4747 rel = table_open(rte->relid, NoLock);
4749 var->varattno - 1);
4751 table_close(rel, NoLock);
4752
4753 return result;
4754 }
4755 default:
4756 elog(ERROR, "unrecognized NotNullSource: %d",
4757 (int) source);
4758 break;
4759 }
4760
4761 return false;
4762}
4763
4764/*
4765 * expr_is_nonnullable: check to see if the Expr cannot be NULL
4766 *
4767 * Returns true iff the given 'expr' cannot produce SQL NULLs.
4768 *
4769 * source: specifies where we should look for NOT NULL proofs for Vars.
4770 * - NOTNULL_SOURCE_RELOPT: Used when RelOptInfos have been generated. We
4771 * retrieve nullability information directly from the RelOptInfo corresponding
4772 * to the Var.
4773 * - NOTNULL_SOURCE_HASHTABLE: Used when RelOptInfos are not yet available,
4774 * but we have already collected relation-level not-null constraints into the
4775 * global hash table.
4776 * - NOTNULL_SOURCE_CATALOG: Used for raw parse trees where neither
4777 * RelOptInfos nor the hash table are available. In this case, we check the
4778 * column's attnullability in the tuple descriptor.
4779 *
4780 * For now, we support only a limited set of expression types. Support for
4781 * additional node types can be added in the future.
4782 */
4783bool
4785{
4786 /* since this function recurses, it could be driven to stack overflow */
4788
4789 switch (nodeTag(expr))
4790 {
4791 case T_Var:
4792 {
4793 if (root)
4794 return var_is_nonnullable(root, (Var *) expr, source);
4795 }
4796 break;
4797 case T_Const:
4798 return !((Const *) expr)->constisnull;
4799 case T_CoalesceExpr:
4800 {
4801 /*
4802 * A CoalesceExpr returns NULL if and only if all its
4803 * arguments are NULL. Therefore, we can determine that a
4804 * CoalesceExpr cannot be NULL if at least one of its
4805 * arguments can be proven non-nullable.
4806 */
4808
4810 {
4812 return true;
4813 }
4814 }
4815 break;
4816 case T_MinMaxExpr:
4817 {
4818 /*
4819 * Like CoalesceExpr, a MinMaxExpr returns NULL only if all
4820 * its arguments evaluate to NULL.
4821 */
4822 MinMaxExpr *minmaxexpr = (MinMaxExpr *) expr;
4823
4825 {
4827 return true;
4828 }
4829 }
4830 break;
4831 case T_CaseExpr:
4832 {
4833 /*
4834 * A CASE expression is non-nullable if all branch results are
4835 * non-nullable. We must also verify that the default result
4836 * (ELSE) exists and is non-nullable.
4837 */
4838 CaseExpr *caseexpr = (CaseExpr *) expr;
4839
4840 /* The default result must be present and non-nullable */
4841 if (caseexpr->defresult == NULL ||
4842 !expr_is_nonnullable(root, caseexpr->defresult, source))
4843 return false;
4844
4845 /* All branch results must be non-nullable */
4847 {
4848 if (!expr_is_nonnullable(root, casewhen->result, source))
4849 return false;
4850 }
4851
4852 return true;
4853 }
4854 break;
4855 case T_ArrayExpr:
4856 {
4857 /*
4858 * An ARRAY[] expression always returns a valid Array object,
4859 * even if it is empty (ARRAY[]) or contains NULLs
4860 * (ARRAY[NULL]). It never evaluates to a SQL NULL.
4861 */
4862 return true;
4863 }
4864 case T_NullTest:
4865 {
4866 /*
4867 * An IS NULL / IS NOT NULL expression always returns a
4868 * boolean value. It never returns SQL NULL.
4869 */
4870 return true;
4871 }
4872 case T_BooleanTest:
4873 {
4874 /*
4875 * A BooleanTest expression always evaluates to a boolean
4876 * value. It never returns SQL NULL.
4877 */
4878 return true;
4879 }
4880 case T_DistinctExpr:
4881 {
4882 /*
4883 * IS DISTINCT FROM never returns NULL, effectively acting as
4884 * though NULL were a normal data value.
4885 */
4886 return true;
4887 }
4888 case T_RelabelType:
4889 {
4890 /*
4891 * RelabelType does not change the nullability of the data.
4892 * The result is non-nullable if and only if the argument is
4893 * non-nullable.
4894 */
4895 return expr_is_nonnullable(root, ((RelabelType *) expr)->arg,
4896 source);
4897 }
4898 default:
4899 break;
4900 }
4901
4902 return false;
4903}
4904
4905/*
4906 * expand_function_arguments: convert named-notation args to positional args
4907 * and/or insert default args, as needed
4908 *
4909 * Returns a possibly-transformed version of the args list.
4910 *
4911 * If include_out_arguments is true, then the args list and the result
4912 * include OUT arguments.
4913 *
4914 * The expected result type of the call must be given, for sanity-checking
4915 * purposes. Also, we ask the caller to provide the function's actual
4916 * pg_proc tuple, not just its OID.
4917 *
4918 * If we need to change anything, the input argument list is copied, not
4919 * modified.
4920 *
4921 * Note: this gets applied to operator argument lists too, even though the
4922 * cases it handles should never occur there. This should be OK since it
4923 * will fall through very quickly if there's nothing to do.
4924 */
4925List *
4927 Oid result_type, HeapTuple func_tuple)
4928{
4930 Oid *proargtypes = funcform->proargtypes.values;
4931 int pronargs = funcform->pronargs;
4932 bool has_named_args = false;
4933 ListCell *lc;
4934
4935 /*
4936 * If we are asked to match to OUT arguments, then use the proallargtypes
4937 * array (which includes those); otherwise use proargtypes (which
4938 * doesn't). Of course, if proallargtypes is null, we always use
4939 * proargtypes. (Fetching proallargtypes is annoyingly expensive
4940 * considering that we may have nothing to do here, but fortunately the
4941 * common case is include_out_arguments == false.)
4942 */
4944 {
4946 bool isNull;
4947
4950 &isNull);
4951 if (!isNull)
4952 {
4954
4955 pronargs = ARR_DIMS(arr)[0];
4956 if (ARR_NDIM(arr) != 1 ||
4957 pronargs < 0 ||
4958 ARR_HASNULL(arr) ||
4959 ARR_ELEMTYPE(arr) != OIDOID)
4960 elog(ERROR, "proallargtypes is not a 1-D Oid array or it contains nulls");
4961 Assert(pronargs >= funcform->pronargs);
4962 proargtypes = (Oid *) ARR_DATA_PTR(arr);
4963 }
4964 }
4965
4966 /* Do we have any named arguments? */
4967 foreach(lc, args)
4968 {
4969 Node *arg = (Node *) lfirst(lc);
4970
4971 if (IsA(arg, NamedArgExpr))
4972 {
4973 has_named_args = true;
4974 break;
4975 }
4976 }
4977
4978 /* If so, we must apply reorder_function_arguments */
4979 if (has_named_args)
4980 {
4982 /* Recheck argument types and add casts if needed */
4983 recheck_cast_function_args(args, result_type,
4985 func_tuple);
4986 }
4987 else if (list_length(args) < pronargs)
4988 {
4989 /* No named args, but we seem to be short some defaults */
4991 /* Recheck argument types and add casts if needed */
4992 recheck_cast_function_args(args, result_type,
4994 func_tuple);
4995 }
4996
4997 return args;
4998}
4999
5000/*
5001 * reorder_function_arguments: convert named-notation args to positional args
5002 *
5003 * This function also inserts default argument values as needed, since it's
5004 * impossible to form a truly valid positional call without that.
5005 */
5006static List *
5008{
5010 int nargsprovided = list_length(args);
5012 ListCell *lc;
5013 int i;
5014
5017 elog(ERROR, "too many function arguments");
5018 memset(argarray, 0, pronargs * sizeof(Node *));
5019
5020 /* Deconstruct the argument list into an array indexed by argnumber */
5021 i = 0;
5022 foreach(lc, args)
5023 {
5024 Node *arg = (Node *) lfirst(lc);
5025
5026 if (!IsA(arg, NamedArgExpr))
5027 {
5028 /* positional argument, assumed to precede all named args */
5029 Assert(argarray[i] == NULL);
5030 argarray[i++] = arg;
5031 }
5032 else
5033 {
5035
5036 Assert(na->argnumber >= 0 && na->argnumber < pronargs);
5037 Assert(argarray[na->argnumber] == NULL);
5038 argarray[na->argnumber] = (Node *) na->arg;
5039 }
5040 }
5041
5042 /*
5043 * Fetch default expressions, if needed, and insert into array at proper
5044 * locations (they aren't necessarily consecutive or all used)
5045 */
5046 if (nargsprovided < pronargs)
5047 {
5049
5050 i = pronargs - funcform->pronargdefaults;
5051 foreach(lc, defaults)
5052 {
5053 if (argarray[i] == NULL)
5054 argarray[i] = (Node *) lfirst(lc);
5055 i++;
5056 }
5057 }
5058
5059 /* Now reconstruct the args list in proper order */
5060 args = NIL;
5061 for (i = 0; i < pronargs; i++)
5062 {
5063 Assert(argarray[i] != NULL);
5064 args = lappend(args, argarray[i]);
5065 }
5066
5067 return args;
5068}
5069
5070/*
5071 * add_function_defaults: add missing function arguments from its defaults
5072 *
5073 * This is used only when the argument list was positional to begin with,
5074 * and so we know we just need to add defaults at the end.
5075 */
5076static List *
5078{
5079 int nargsprovided = list_length(args);
5080 List *defaults;
5081 int ndelete;
5082
5083 /* Get all the default expressions from the pg_proc tuple */
5085
5086 /* Delete any unused defaults from the list */
5087 ndelete = nargsprovided + list_length(defaults) - pronargs;
5088 if (ndelete < 0)
5089 elog(ERROR, "not enough default arguments");
5090 if (ndelete > 0)
5091 defaults = list_delete_first_n(defaults, ndelete);
5092
5093 /* And form the combined argument list, not modifying the input list */
5094 return list_concat_copy(args, defaults);
5095}
5096
5097/*
5098 * fetch_function_defaults: get function's default arguments as expression list
5099 */
5100static List *
5102{
5103 List *defaults;
5105 char *str;
5106
5110 defaults = castNode(List, stringToNode(str));
5111 pfree(str);
5112 return defaults;
5113}
5114
5115/*
5116 * recheck_cast_function_args: recheck function args and typecast as needed
5117 * after adding defaults.
5118 *
5119 * It is possible for some of the defaulted arguments to be polymorphic;
5120 * therefore we can't assume that the default expressions have the correct
5121 * data types already. We have to re-resolve polymorphics and do coercion
5122 * just like the parser did.
5123 *
5124 * This should be a no-op if there are no polymorphic arguments,
5125 * but we do it anyway to be sure.
5126 *
5127 * Note: if any casts are needed, the args list is modified in-place;
5128 * caller should have already copied the list structure.
5129 */
5130static void
5131recheck_cast_function_args(List *args, Oid result_type,
5132 Oid *proargtypes, int pronargs,
5134{
5136 int nargs;
5139 Oid rettype;
5140 ListCell *lc;
5141
5142 if (list_length(args) > FUNC_MAX_ARGS)
5143 elog(ERROR, "too many function arguments");
5144 nargs = 0;
5145 foreach(lc, args)
5146 {
5147 actual_arg_types[nargs++] = exprType((Node *) lfirst(lc));
5148 }
5149 Assert(nargs == pronargs);
5153 nargs,
5154 funcform->prorettype,
5155 false);
5156 /* let's just check we got the same answer as the parser did ... */
5157 if (rettype != result_type)
5158 elog(ERROR, "function's resolved result type changed during planning");
5159
5160 /* perform any necessary typecasting of arguments */
5162}
5163
5164/*
5165 * evaluate_function: try to pre-evaluate a function call
5166 *
5167 * We can do this if the function is strict and has any constant-null inputs
5168 * (just return a null constant), or if the function is immutable and has all
5169 * constant inputs (call it and return the result as a Const node). In
5170 * estimation mode we are willing to pre-evaluate stable functions too.
5171 *
5172 * Returns a simplified expression if successful, or NULL if cannot
5173 * simplify the function.
5174 */
5175static Expr *
5176evaluate_function(Oid funcid, Oid result_type, int32 result_typmod,
5178 bool funcvariadic,
5181{
5183 bool has_nonconst_input = false;
5184 bool has_null_input = false;
5185 ListCell *arg;
5187
5188 /*
5189 * Can't simplify if it returns a set.
5190 */
5191 if (funcform->proretset)
5192 return NULL;
5193
5194 /*
5195 * Can't simplify if it returns RECORD. The immediate problem is that it
5196 * will be needing an expected tupdesc which we can't supply here.
5197 *
5198 * In the case where it has OUT parameters, we could build an expected
5199 * tupdesc from those, but there may be other gotchas lurking. In
5200 * particular, if the function were to return NULL, we would produce a
5201 * null constant with no remaining indication of which concrete record
5202 * type it is. For now, seems best to leave the function call unreduced.
5203 */
5204 if (funcform->prorettype == RECORDOID)
5205 return NULL;
5206
5207 /*
5208 * Check for constant inputs and especially constant-NULL inputs.
5209 */
5210 foreach(arg, args)
5211 {
5212 if (IsA(lfirst(arg), Const))
5214 else
5215 has_nonconst_input = true;
5216 }
5217
5218 /*
5219 * If the function is strict and has a constant-NULL input, it will never
5220 * be called at all, so we can replace the call by a NULL constant, even
5221 * if there are other inputs that aren't constant, and even if the
5222 * function is not otherwise immutable.
5223 */
5224 if (funcform->proisstrict && has_null_input)
5225 return (Expr *) makeNullConst(result_type, result_typmod,
5227
5228 /*
5229 * Otherwise, can simplify only if all inputs are constants. (For a
5230 * non-strict function, constant NULL inputs are treated the same as
5231 * constant non-NULL inputs.)
5232 */
5234 return NULL;
5235
5236 /*
5237 * Ordinarily we are only allowed to simplify immutable functions. But for
5238 * purposes of estimation, we consider it okay to simplify functions that
5239 * are merely stable; the risk that the result might change from planning
5240 * time to execution time is worth taking in preference to not being able
5241 * to estimate the value at all.
5242 */
5243 if (funcform->provolatile == PROVOLATILE_IMMUTABLE)
5244 /* okay */ ;
5245 else if (context->estimate && funcform->provolatile == PROVOLATILE_STABLE)
5246 /* okay */ ;
5247 else
5248 return NULL;
5249
5250 /*
5251 * OK, looks like we can simplify this operator/function.
5252 *
5253 * Build a new FuncExpr node containing the already-simplified arguments.
5254 */
5256 newexpr->funcid = funcid;
5257 newexpr->funcresulttype = result_type;
5258 newexpr->funcretset = false;
5259 newexpr->funcvariadic = funcvariadic;
5260 newexpr->funcformat = COERCE_EXPLICIT_CALL; /* doesn't matter */
5261 newexpr->funccollid = result_collid; /* doesn't matter */
5262 newexpr->inputcollid = input_collid;
5263 newexpr->args = args;
5264 newexpr->location = -1;
5265
5266 return evaluate_expr((Expr *) newexpr, result_type, result_typmod,
5268}
5269
5270/*
5271 * inline_function: try to expand a function call inline
5272 *
5273 * If the function is a sufficiently simple SQL-language function
5274 * (just "SELECT expression"), then we can inline it and avoid the rather
5275 * high per-call overhead of SQL functions. Furthermore, this can expose
5276 * opportunities for constant-folding within the function expression.
5277 *
5278 * We have to beware of some special cases however. A directly or
5279 * indirectly recursive function would cause us to recurse forever,
5280 * so we keep track of which functions we are already expanding and
5281 * do not re-expand them. Also, if a parameter is used more than once
5282 * in the SQL-function body, we require it not to contain any volatile
5283 * functions (volatiles might deliver inconsistent answers) nor to be
5284 * unreasonably expensive to evaluate. The expensiveness check not only
5285 * prevents us from doing multiple evaluations of an expensive parameter
5286 * at runtime, but is a safety value to limit growth of an expression due
5287 * to repeated inlining.
5288 *
5289 * We must also beware of changing the volatility or strictness status of
5290 * functions by inlining them.
5291 *
5292 * Also, at the moment we can't inline functions returning RECORD. This
5293 * doesn't work in the general case because it discards information such
5294 * as OUT-parameter declarations.
5295 *
5296 * Also, context-dependent expression nodes in the argument list are trouble.
5297 *
5298 * Returns a simplified expression if successful, or NULL if cannot
5299 * simplify the function.
5300 */
5301static Expr *
5302inline_function(Oid funcid, Oid result_type, Oid result_collid,
5303 Oid input_collid, List *args,
5304 bool funcvariadic,
5307{
5309 char *src;
5310 Datum tmp;
5311 bool isNull;
5314 inline_error_callback_arg callback_arg;
5316 FuncExpr *fexpr;
5318 TupleDesc rettupdesc;
5319 ParseState *pstate;
5323 Node *newexpr;
5324 int *usecounts;
5325 ListCell *arg;
5326 int i;
5327
5328 /*
5329 * Forget it if the function is not SQL-language or has other showstopper
5330 * properties. (The prokind and nargs checks are just paranoia.)
5331 */
5332 if (funcform->prolang != SQLlanguageId ||
5333 funcform->prokind != PROKIND_FUNCTION ||
5334 funcform->prosecdef ||
5335 funcform->proretset ||
5336 funcform->prorettype == RECORDOID ||
5338 funcform->pronargs != list_length(args))
5339 return NULL;
5340
5341 /* Check for recursive function, and give up trying to expand if so */
5342 if (list_member_oid(context->active_fns, funcid))
5343 return NULL;
5344
5345 /* Check permission to call function (fail later, if not) */
5347 return NULL;
5348
5349 /* Check whether a plugin wants to hook function entry/exit */
5350 if (FmgrHookIsNeeded(funcid))
5351 return NULL;
5352
5353 /*
5354 * Make a temporary memory context, so that we don't leak all the stuff
5355 * that parsing might create.
5356 */
5358 "inline_function",
5361
5362 /*
5363 * We need a dummy FuncExpr node containing the already-simplified
5364 * arguments. (In some cases we don't really need it, but building it is
5365 * cheap enough that it's not worth contortions to avoid.)
5366 */
5368 fexpr->funcid = funcid;
5369 fexpr->funcresulttype = result_type;
5370 fexpr->funcretset = false;
5371 fexpr->funcvariadic = funcvariadic;
5372 fexpr->funcformat = COERCE_EXPLICIT_CALL; /* doesn't matter */
5373 fexpr->funccollid = result_collid; /* doesn't matter */
5374 fexpr->inputcollid = input_collid;
5375 fexpr->args = args;
5376 fexpr->location = -1;
5377
5378 /* Fetch the function body */
5380 src = TextDatumGetCString(tmp);
5381
5382 /*
5383 * Setup error traceback support for ereport(). This is so that we can
5384 * finger the function that bad information came from.
5385 */
5386 callback_arg.proname = NameStr(funcform->proname);
5387 callback_arg.prosrc = src;
5388
5390 sqlerrcontext.arg = &callback_arg;
5393
5394 /* If we have prosqlbody, pay attention to that not prosrc */
5396 func_tuple,
5398 &isNull);
5399 if (!isNull)
5400 {
5401 Node *n;
5402 List *query_list;
5403
5405 if (IsA(n, List))
5406 query_list = linitial_node(List, castNode(List, n));
5407 else
5408 query_list = list_make1(n);
5409 if (list_length(query_list) != 1)
5410 goto fail;
5411 querytree = linitial(query_list);
5412
5413 /*
5414 * Because we'll insist below that the querytree have an empty rtable
5415 * and no sublinks, it cannot have any relation references that need
5416 * to be locked or rewritten. So we can omit those steps.
5417 */
5418 }
5419 else
5420 {
5421 /* Set up to handle parameters while parsing the function body. */
5423 (Node *) fexpr,
5424 input_collid);
5425
5426 /*
5427 * We just do parsing and parse analysis, not rewriting, because
5428 * rewriting will not affect table-free-SELECT-only queries, which is
5429 * all that we care about. Also, we can punt as soon as we detect
5430 * more than one command in the function body.
5431 */
5434 goto fail;
5435
5436 pstate = make_parsestate(NULL);
5437 pstate->p_sourcetext = src;
5438 sql_fn_parser_setup(pstate, pinfo);
5439
5441
5442 free_parsestate(pstate);
5443 }
5444
5445 /*
5446 * The single command must be a simple "SELECT expression".
5447 *
5448 * Note: if you change the tests involved in this, see also plpgsql's
5449 * exec_simple_check_plan(). That generally needs to have the same idea
5450 * of what's a "simple expression", so that inlining a function that
5451 * previously wasn't inlined won't change plpgsql's conclusion.
5452 */
5453 if (!IsA(querytree, Query) ||
5454 querytree->commandType != CMD_SELECT ||
5455 querytree->hasAggs ||
5456 querytree->hasWindowFuncs ||
5457 querytree->hasTargetSRFs ||
5458 querytree->hasSubLinks ||
5459 querytree->cteList ||
5460 querytree->rtable ||
5461 querytree->jointree->fromlist ||
5462 querytree->jointree->quals ||
5463 querytree->groupClause ||
5464 querytree->groupingSets ||
5465 querytree->havingQual ||
5466 querytree->windowClause ||
5467 querytree->distinctClause ||
5468 querytree->sortClause ||
5469 querytree->limitOffset ||
5470 querytree->limitCount ||
5471 querytree->setOperations ||
5472 list_length(querytree->targetList) != 1)
5473 goto fail;
5474
5475 /* If the function result is composite, resolve it */
5477 NULL,
5478 &rettupdesc);
5479
5480 /*
5481 * Make sure the function (still) returns what it's declared to. This
5482 * will raise an error if wrong, but that's okay since the function would
5483 * fail at runtime anyway. Note that check_sql_fn_retval will also insert
5484 * a coercion if needed to make the tlist expression match the declared
5485 * type of the function.
5486 *
5487 * Note: we do not try this until we have verified that no rewriting was
5488 * needed; that's probably not important, but let's be careful.
5489 */
5492 result_type, rettupdesc,
5493 funcform->prokind,
5494 false))
5495 goto fail; /* reject whole-tuple-result cases */
5496
5497 /*
5498 * Given the tests above, check_sql_fn_retval shouldn't have decided to
5499 * inject a projection step, but let's just make sure.
5500 */
5502 goto fail;
5503
5504 /* Now we can grab the tlist expression */
5505 newexpr = (Node *) ((TargetEntry *) linitial(querytree->targetList))->expr;
5506
5507 /*
5508 * If the SQL function returns VOID, we can only inline it if it is a
5509 * SELECT of an expression returning VOID (ie, it's just a redirection to
5510 * another VOID-returning function). In all non-VOID-returning cases,
5511 * check_sql_fn_retval should ensure that newexpr returns the function's
5512 * declared result type, so this test shouldn't fail otherwise; but we may
5513 * as well cope gracefully if it does.
5514 */
5515 if (exprType(newexpr) != result_type)
5516 goto fail;
5517
5518 /*
5519 * Additional validity checks on the expression. It mustn't be more
5520 * volatile than the surrounding function (this is to avoid breaking hacks
5521 * that involve pretending a function is immutable when it really ain't).
5522 * If the surrounding function is declared strict, then the expression
5523 * must contain only strict constructs and must use all of the function
5524 * parameters (this is overkill, but an exact analysis is hard).
5525 */
5526 if (funcform->provolatile == PROVOLATILE_IMMUTABLE &&
5528 goto fail;
5529 else if (funcform->provolatile == PROVOLATILE_STABLE &&
5531 goto fail;
5532
5533 if (funcform->proisstrict &&
5535 goto fail;
5536
5537 /*
5538 * If any parameter expression contains a context-dependent node, we can't
5539 * inline, for fear of putting such a node into the wrong context.
5540 */
5542 goto fail;
5543
5544 /*
5545 * We may be able to do it; there are still checks on parameter usage to
5546 * make, but those are most easily done in combination with the actual
5547 * substitution of the inputs. So start building expression with inputs
5548 * substituted.
5549 */
5550 usecounts = (int *) palloc0(funcform->pronargs * sizeof(int));
5552 args, usecounts);
5553
5554 /* Now check for parameter usage */
5555 i = 0;
5556 foreach(arg, args)
5557 {
5558 Node *param = lfirst(arg);
5559
5560 if (usecounts[i] == 0)
5561 {
5562 /* Param not used at all: uncool if func is strict */
5563 if (funcform->proisstrict)
5564 goto fail;
5565 }
5566 else if (usecounts[i] != 1)
5567 {
5568 /* Param used multiple times: uncool if expensive or volatile */
5570
5571 /*
5572 * We define "expensive" as "contains any subplan or more than 10
5573 * operators". Note that the subplan search has to be done
5574 * explicitly, since cost_qual_eval() will barf on unplanned
5575 * subselects.
5576 */
5577 if (contain_subplans(param))
5578 goto fail;
5580 if (eval_cost.startup + eval_cost.per_tuple >
5581 10 * cpu_operator_cost)
5582 goto fail;
5583
5584 /*
5585 * Check volatility last since this is more expensive than the
5586 * above tests
5587 */
5588 if (contain_volatile_functions(param))
5589 goto fail;
5590 }
5591 i++;
5592 }
5593
5594 /*
5595 * Whew --- we can make the substitution. Copy the modified expression
5596 * out of the temporary memory context, and clean up.
5597 */
5599
5601
5603
5604 /*
5605 * If the result is of a collatable type, force the result to expose the
5606 * correct collation. In most cases this does not matter, but it's
5607 * possible that the function result is used directly as a sort key or in
5608 * other places where we expect exprCollation() to tell the truth.
5609 */
5611 {
5613
5615 {
5617
5618 newnode->arg = (Expr *) newexpr;
5619 newnode->collOid = result_collid;
5620 newnode->location = -1;
5621
5622 newexpr = (Node *) newnode;
5623 }
5624 }
5625
5626 /*
5627 * Since there is now no trace of the function in the plan tree, we must
5628 * explicitly record the plan's dependency on the function.
5629 */
5630 if (context->root)
5631 record_plan_function_dependency(context->root, funcid);
5632
5633 /*
5634 * Recursively try to simplify the modified expression. Here we must add
5635 * the current function to the context list of active functions.
5636 */
5637 context->active_fns = lappend_oid(context->active_fns, funcid);
5639 context->active_fns = list_delete_last(context->active_fns);
5640
5642
5643 return (Expr *) newexpr;
5644
5645 /* Here if func is not inlinable: release temp memory and return NULL */
5646fail:
5650
5651 return NULL;
5652}
5653
5654/*
5655 * Replace Param nodes by appropriate actual parameters
5656 */
5657static Node *
5658substitute_actual_parameters(Node *expr, int nargs, List *args,
5659 int *usecounts)
5660{
5662
5663 context.nargs = nargs;
5664 context.args = args;
5665 context.usecounts = usecounts;
5666
5667 return substitute_actual_parameters_mutator(expr, &context);
5668}
5669
5670static Node *
5673{
5674 if (node == NULL)
5675 return NULL;
5676 if (IsA(node, Param))
5677 {
5678 Param *param = (Param *) node;
5679
5680 if (param->paramkind != PARAM_EXTERN)
5681 elog(ERROR, "unexpected paramkind: %d", (int) param->paramkind);
5682 if (param->paramid <= 0 || param->paramid > context->nargs)
5683 elog(ERROR, "invalid paramid: %d", param->paramid);
5684
5685 /* Count usage of parameter */
5686 context->usecounts[param->paramid - 1]++;
5687
5688 /* Select the appropriate actual arg and replace the Param with it */
5689 /* We don't need to copy at this time (it'll get done later) */
5690 return list_nth(context->args, param->paramid - 1);
5691 }
5693}
5694
5695/*
5696 * error context callback to let us supply a call-stack traceback
5697 */
5698static void
5700{
5703
5704 /* If it's a syntax error, convert to internal syntax error report */
5706 if (syntaxerrposition > 0)
5707 {
5708 errposition(0);
5710 internalerrquery(callback_arg->prosrc);
5711 }
5712
5713 errcontext("SQL function \"%s\" during inlining", callback_arg->proname);
5714}
5715
5716/*
5717 * evaluate_expr: pre-evaluate a constant expression
5718 *
5719 * We use the executor's routine ExecEvalExpr() to avoid duplication of
5720 * code and ensure we get the same result as the executor would get.
5721 */
5722Expr *
5723evaluate_expr(Expr *expr, Oid result_type, int32 result_typmod,
5725{
5726 EState *estate;
5727 ExprState *exprstate;
5728 MemoryContext oldcontext;
5730 bool const_is_null;
5732 bool resultTypByVal;
5733
5734 /*
5735 * To use the executor, we need an EState.
5736 */
5737 estate = CreateExecutorState();
5738
5739 /* We can use the estate's working context to avoid memory leaks. */
5740 oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
5741
5742 /* Make sure any opfuncids are filled in. */
5743 fix_opfuncids((Node *) expr);
5744
5745 /*
5746 * Prepare expr for execution. (Note: we can't use ExecPrepareExpr
5747 * because it'd result in recursively invoking eval_const_expressions.)
5748 */
5749 exprstate = ExecInitExpr(expr, NULL);
5750
5751 /*
5752 * And evaluate it.
5753 *
5754 * It is OK to use a default econtext because none of the ExecEvalExpr()
5755 * code used in this situation will use econtext. That might seem
5756 * fortuitous, but it's not so unreasonable --- a constant expression does
5757 * not depend on context, by definition, n'est ce pas?
5758 */
5760 GetPerTupleExprContext(estate),
5761 &const_is_null);
5762
5763 /* Get info needed about result datatype */
5765
5766 /* Get back to outer memory context */
5767 MemoryContextSwitchTo(oldcontext);
5768
5769 /*
5770 * Must copy result out of sub-context used by expression eval.
5771 *
5772 * Also, if it's varlena, forcibly detoast it. This protects us against
5773 * storing TOAST pointers into plans that might outlive the referenced
5774 * data. (makeConst would handle detoasting anyway, but it's worth a few
5775 * extra lines here so that we can do the copy and detoast in one step.)
5776 */
5777 if (!const_is_null)
5778 {
5779 if (resultTypLen == -1)
5781 else
5783 }
5784
5785 /* Release all the junk we just created */
5786 FreeExecutorState(estate);
5787
5788 /*
5789 * Make the constant result node.
5790 */
5791 return (Expr *) makeConst(result_type, result_typmod, result_collation,
5795}
5796
5797
5798/*
5799 * inline_function_in_from
5800 * Attempt to "inline" a function in the FROM clause.
5801 *
5802 * "rte" is an RTE_FUNCTION rangetable entry. If it represents a call of a
5803 * function that can be inlined, expand the function and return the
5804 * substitute Query structure. Otherwise, return NULL.
5805 *
5806 * We assume that the RTE's expression has already been put through
5807 * eval_const_expressions(), which among other things will take care of
5808 * default arguments and named-argument notation.
5809 *
5810 * This has a good deal of similarity to inline_function(), but that's
5811 * for the general-expression case, and there are enough differences to
5812 * justify separate functions.
5813 */
5814Query *
5816{
5817 RangeTblFunction *rtfunc;
5818 FuncExpr *fexpr;
5819 Oid func_oid;
5824 Datum tmp;
5825 char *src;
5826 inline_error_callback_arg callback_arg;
5828 Query *querytree = NULL;
5829
5830 Assert(rte->rtekind == RTE_FUNCTION);
5831
5832 /*
5833 * Guard against infinite recursion during expansion by checking for stack
5834 * overflow. (There's no need to do more.)
5835 */
5837
5838 /* Fail if the RTE has ORDINALITY - we don't implement that here. */
5839 if (rte->funcordinality)
5840 return NULL;
5841
5842 /* Fail if RTE isn't a single, simple FuncExpr */
5843 if (list_length(rte->functions) != 1)
5844 return NULL;
5845 rtfunc = (RangeTblFunction *) linitial(rte->functions);
5846
5847 if (!IsA(rtfunc->funcexpr, FuncExpr))
5848 return NULL;
5849 fexpr = (FuncExpr *) rtfunc->funcexpr;
5850
5851 func_oid = fexpr->funcid;
5852
5853 /*
5854 * Refuse to inline if the arguments contain any volatile functions or
5855 * sub-selects. Volatile functions are rejected because inlining may
5856 * result in the arguments being evaluated multiple times, risking a
5857 * change in behavior. Sub-selects are rejected partly for implementation
5858 * reasons (pushing them down another level might change their behavior)
5859 * and partly because they're likely to be expensive and so multiple
5860 * evaluation would be bad.
5861 */
5862 if (contain_volatile_functions((Node *) fexpr->args) ||
5863 contain_subplans((Node *) fexpr->args))
5864 return NULL;
5865
5866 /* Check permission to call function (fail later, if not) */
5868 return NULL;
5869
5870 /* Check whether a plugin wants to hook function entry/exit */
5872 return NULL;
5873
5874 /*
5875 * OK, let's take a look at the function's pg_proc entry.
5876 */
5879 elog(ERROR, "cache lookup failed for function %u", func_oid);
5881
5882 /*
5883 * If the function SETs any configuration parameters, inlining would cause
5884 * us to miss making those changes.
5885 */
5887 {
5889 return NULL;
5890 }
5891
5892 /*
5893 * Make a temporary memory context, so that we don't leak all the stuff
5894 * that parsing and rewriting might create. If we succeed, we'll copy
5895 * just the finished query tree back up to the caller's context.
5896 */
5898 "inline_function_in_from",
5901
5902 /* Fetch the function body */
5904 src = TextDatumGetCString(tmp);
5905
5906 /*
5907 * If the function has an attached support function that can handle
5908 * SupportRequestInlineInFrom, then attempt to inline with that.
5909 */
5910 if (funcform->prosupport)
5911 {
5913
5915 req.root = root;
5916 req.rtfunc = rtfunc;
5917 req.proc = func_tuple;
5918
5919 querytree = (Query *)
5921 PointerGetDatum(&req)));
5922 }
5923
5924 /*
5925 * Setup error traceback support for ereport(). This is so that we can
5926 * finger the function that bad information came from. We don't install
5927 * this while running the support function, since it'd be likely to do the
5928 * wrong thing: any parse errors reported during that are very likely not
5929 * against the raw function source text.
5930 */
5931 callback_arg.proname = NameStr(funcform->proname);
5932 callback_arg.prosrc = src;
5933
5935 sqlerrcontext.arg = &callback_arg;
5938
5939 /*
5940 * If SupportRequestInlineInFrom didn't work, try our built-in inlining
5941 * mechanism.
5942 */
5943 if (!querytree)
5945 func_tuple, funcform, src);
5946
5947 if (!querytree)
5948 goto fail; /* no luck there either, fail */
5949
5950 /*
5951 * The result had better be a SELECT Query.
5952 */
5954 Assert(querytree->commandType == CMD_SELECT);
5955
5956 /*
5957 * Looks good --- substitute parameters into the query.
5958 */
5960 funcform->pronargs,
5961 fexpr->args);
5962
5963 /*
5964 * Copy the modified query out of the temporary memory context, and clean
5965 * up.
5966 */
5968
5970
5974
5975 /*
5976 * We don't have to fix collations here because the upper query is already
5977 * parsed, ie, the collations in the RTE are what count.
5978 */
5979
5980 /*
5981 * Since there is now no trace of the function in the plan tree, we must
5982 * explicitly record the plan's dependency on the function.
5983 */
5985
5986 /*
5987 * We must also notice if the inserted query adds a dependency on the
5988 * calling role due to RLS quals.
5989 */
5990 if (querytree->hasRowSecurity)
5991 root->glob->dependsOnRole = true;
5992
5993 return querytree;
5994
5995 /* Here if func is not inlinable: release temp memory and return NULL */
5996fail:
6001
6002 return NULL;
6003}
6004
6005/*
6006 * inline_sql_function_in_from
6007 *
6008 * This implements inline_function_in_from for SQL-language functions.
6009 * Returns NULL if the function couldn't be inlined.
6010 *
6011 * The division of labor between here and inline_function_in_from is based
6012 * on the rule that inline_function_in_from should make all checks that are
6013 * certain to be required in both this case and the support-function case.
6014 * Support functions might also want to make checks analogous to the ones
6015 * made here, but then again they might not, or they might just assume that
6016 * the function they are attached to can validly be inlined.
6017 */
6018static Query *
6020 RangeTblFunction *rtfunc,
6021 FuncExpr *fexpr,
6024 const char *src)
6025{
6026 Datum sqlbody;
6027 bool isNull;
6031 TupleDesc rettupdesc;
6032
6033 /*
6034 * The function must be declared to return a set, else inlining would
6035 * change the results if the contained SELECT didn't return exactly one
6036 * row.
6037 */
6038 if (!fexpr->funcretset)
6039 return NULL;
6040
6041 /*
6042 * Forget it if the function is not SQL-language or has other showstopper
6043 * properties. In particular it mustn't be declared STRICT, since we
6044 * couldn't enforce that. It also mustn't be VOLATILE, because that is
6045 * supposed to cause it to be executed with its own snapshot, rather than
6046 * sharing the snapshot of the calling query. We also disallow returning
6047 * SETOF VOID, because inlining would result in exposing the actual result
6048 * of the function's last SELECT, which should not happen in that case.
6049 * (Rechecking prokind, proretset, and pronargs is just paranoia.)
6050 */
6051 if (funcform->prolang != SQLlanguageId ||
6052 funcform->prokind != PROKIND_FUNCTION ||
6053 funcform->proisstrict ||
6054 funcform->provolatile == PROVOLATILE_VOLATILE ||
6055 funcform->prorettype == VOIDOID ||
6056 funcform->prosecdef ||
6057 !funcform->proretset ||
6058 list_length(fexpr->args) != funcform->pronargs)
6059 return NULL;
6060
6061 /* If we have prosqlbody, pay attention to that not prosrc */
6063 func_tuple,
6065 &isNull);
6066 if (!isNull)
6067 {
6068 Node *n;
6069
6071 if (IsA(n, List))
6073 else
6075 if (list_length(querytree_list) != 1)
6076 return NULL;
6078
6079 /* Acquire necessary locks, then apply rewriter. */
6080 AcquireRewriteLocks(querytree, true, false);
6082 if (list_length(querytree_list) != 1)
6083 return NULL;
6085 }
6086 else
6087 {
6090
6091 /*
6092 * Set up to handle parameters while parsing the function body. We
6093 * can use the FuncExpr just created as the input for
6094 * prepare_sql_fn_parse_info.
6095 */
6097 (Node *) fexpr,
6098 fexpr->inputcollid);
6099
6100 /*
6101 * Parse, analyze, and rewrite (unlike inline_function(), we can't
6102 * skip rewriting here). We can fail as soon as we find more than one
6103 * query, though.
6104 */
6107 return NULL;
6108
6110 src,
6112 pinfo, NULL);
6113 if (list_length(querytree_list) != 1)
6114 return NULL;
6116 }
6117
6118 /*
6119 * Also resolve the actual function result tupdesc, if composite. If we
6120 * have a coldeflist, believe that; otherwise use get_expr_result_type.
6121 * (This logic should match ExecInitFunctionScan.)
6122 */
6123 if (rtfunc->funccolnames != NIL)
6124 {
6126 rettupdesc = BuildDescFromLists(rtfunc->funccolnames,
6127 rtfunc->funccoltypes,
6128 rtfunc->funccoltypmods,
6129 rtfunc->funccolcollations);
6130 }
6131 else
6132 functypclass = get_expr_result_type((Node *) fexpr, NULL, &rettupdesc);
6133
6134 /*
6135 * The single command must be a plain SELECT.
6136 */
6137 if (!IsA(querytree, Query) ||
6138 querytree->commandType != CMD_SELECT)
6139 return NULL;
6140
6141 /*
6142 * Make sure the function (still) returns what it's declared to. This
6143 * will raise an error if wrong, but that's okay since the function would
6144 * fail at runtime anyway. Note that check_sql_fn_retval will also insert
6145 * coercions if needed to make the tlist expression(s) match the declared
6146 * type of the function. We also ask it to insert dummy NULL columns for
6147 * any dropped columns in rettupdesc, so that the elements of the modified
6148 * tlist match up to the attribute numbers.
6149 *
6150 * If the function returns a composite type, don't inline unless the check
6151 * shows it's returning a whole tuple result; otherwise what it's
6152 * returning is a single composite column which is not what we need.
6153 */
6155 fexpr->funcresulttype, rettupdesc,
6156 funcform->prokind,
6157 true) &&
6161 return NULL; /* reject not-whole-tuple-result cases */
6162
6163 /*
6164 * check_sql_fn_retval might've inserted a projection step, but that's
6165 * fine; just make sure we use the upper Query.
6166 */
6168
6169 return querytree;
6170}
6171
6172/*
6173 * Replace Param nodes by appropriate actual parameters
6174 *
6175 * This is just enough different from substitute_actual_parameters()
6176 * that it needs its own code.
6177 */
6178static Query *
6179substitute_actual_parameters_in_from(Query *expr, int nargs, List *args)
6180{
6182
6183 context.nargs = nargs;
6184 context.args = args;
6185 context.sublevels_up = 1;
6186
6187 return query_tree_mutator(expr,
6189 &context,
6190 0);
6191}
6192
6193static Node *
6196{
6197 Node *result;
6198
6199 if (node == NULL)
6200 return NULL;
6201 if (IsA(node, Query))
6202 {
6203 context->sublevels_up++;
6204 result = (Node *) query_tree_mutator((Query *) node,
6206 context,
6207 0);
6208 context->sublevels_up--;
6209 return result;
6210 }
6211 if (IsA(node, Param))
6212 {
6213 Param *param = (Param *) node;
6214
6215 if (param->paramkind == PARAM_EXTERN)
6216 {
6217 if (param->paramid <= 0 || param->paramid > context->nargs)
6218 elog(ERROR, "invalid paramid: %d", param->paramid);
6219
6220 /*
6221 * Since the parameter is being inserted into a subquery, we must
6222 * adjust levels.
6223 */
6224 result = copyObject(list_nth(context->args, param->paramid - 1));
6226 return result;
6227 }
6228 }
6229 return expression_tree_mutator(node,
6231 context);
6232}
6233
6234/*
6235 * pull_paramids
6236 * Returns a Bitmapset containing the paramids of all Params in 'expr'.
6237 */
6238Bitmapset *
6239pull_paramids(Expr *expr)
6240{
6242
6243 (void) pull_paramids_walker((Node *) expr, &result);
6244
6245 return result;
6246}
6247
6248static bool
6249pull_paramids_walker(Node *node, Bitmapset **context)
6250{
6251 if (node == NULL)
6252 return false;
6253 if (IsA(node, Param))
6254 {
6255 Param *param = (Param *) node;
6256
6257 *context = bms_add_member(*context, param->paramid);
6258 return false;
6259 }
6260 return expression_tree_walker(node, pull_paramids_walker, context);
6261}
6262
6263/*
6264 * Build ScalarArrayOpExpr on top of 'exprs.' 'haveNonConst' indicates
6265 * whether at least one of the expressions is not Const. When it's false,
6266 * the array constant is built directly; otherwise, we have to build a child
6267 * ArrayExpr. The 'exprs' list gets freed if not directly used in the output
6268 * expression tree.
6269 */
6272 Oid inputcollid, List *exprs, bool haveNonConst)
6273{
6274 Node *arrayNode = NULL;
6276 Oid arraytype = get_array_type(coltype);
6277
6278 if (!OidIsValid(arraytype))
6279 return NULL;
6280
6281 /*
6282 * Assemble an array from the list of constants. It seems more profitable
6283 * to build a const array. But in the presence of other nodes, we don't
6284 * have a specific value here and must employ an ArrayExpr instead.
6285 */
6286 if (haveNonConst)
6287 {
6289
6290 /* array_collid will be set by parse_collate.c */
6291 arrayExpr->element_typeid = coltype;
6292 arrayExpr->array_typeid = arraytype;
6293 arrayExpr->multidims = false;
6294 arrayExpr->elements = exprs;
6295 arrayExpr->location = -1;
6296
6297 arrayNode = (Node *) arrayExpr;
6298 }
6299 else
6300 {
6301 int16 typlen;
6302 bool typbyval;
6303 char typalign;
6304 Datum *elems;
6305 bool *nulls;
6306 int i = 0;
6308 int dims[1] = {list_length(exprs)};
6309 int lbs[1] = {1};
6310
6311 get_typlenbyvalalign(coltype, &typlen, &typbyval, &typalign);
6312
6313 elems = palloc_array(Datum, list_length(exprs));
6314 nulls = palloc_array(bool, list_length(exprs));
6315 foreach_node(Const, value, exprs)
6316 {
6317 elems[i] = value->constvalue;
6318 nulls[i++] = value->constisnull;
6319 }
6320
6321 arrayConst = construct_md_array(elems, nulls, 1, dims, lbs,
6322 coltype, typlen, typbyval, typalign);
6325 false, false);
6326
6327 pfree(elems);
6328 pfree(nulls);
6329 list_free(exprs);
6330 }
6331
6332 /* Build the SAOP expression node */
6334 saopexpr->opno = oper;
6335 saopexpr->opfuncid = get_opcode(oper);
6336 saopexpr->hashfuncid = InvalidOid;
6337 saopexpr->negfuncid = InvalidOid;
6338 saopexpr->useOr = true;
6339 saopexpr->inputcollid = inputcollid;
6341 saopexpr->location = -1;
6342
6343 return saopexpr;
6344}
Datum querytree(PG_FUNCTION_ARGS)
Definition _int_bool.c:711
@ ACLCHECK_OK
Definition acl.h:184
AclResult object_aclcheck(Oid classid, Oid objectid, Oid roleid, AclMode mode)
Definition aclchk.c:3880
#define ARR_NDIM(a)
Definition array.h:290
#define ARR_DATA_PTR(a)
Definition array.h:322
#define DatumGetArrayTypeP(X)
Definition array.h:261
#define ARR_ELEMTYPE(a)
Definition array.h:292
#define ARR_DIMS(a)
Definition array.h:294
#define ARR_HASNULL(a)
Definition array.h:291
ArrayType * construct_md_array(Datum *elems, bool *nulls, int ndims, int *dims, int *lbs, Oid elmtype, int elmlen, bool elmbyval, char elmalign)
#define InvalidAttrNumber
Definition attnum.h:23
bool bms_is_member(int x, const Bitmapset *a)
Definition bitmapset.c:510
Bitmapset * bms_add_member(Bitmapset *a, int x)
Definition bitmapset.c:799
#define bms_is_empty(a)
Definition bitmapset.h:118
#define TextDatumGetCString(d)
Definition builtins.h:99
#define NameStr(name)
Definition c.h:835
#define Assert(condition)
Definition c.h:943
int16_t int16
Definition c.h:619
int32_t int32
Definition c.h:620
#define OidIsValid(objectId)
Definition c.h:858
uint32 result
memcpy(sums, checksumBaseOffsets, sizeof(checksumBaseOffsets))
static List * simplify_or_arguments(List *args, eval_const_expressions_context *context, bool *haveNull, bool *forceTrue)
Definition clauses.c:4224
static bool rowtype_field_matches(Oid rowtypeid, int fieldnum, Oid expectedtype, int32 expectedtypmod, Oid expectedcollation)
Definition clauses.c:2431
Query * inline_function_in_from(PlannerInfo *root, RangeTblEntry *rte)
Definition clauses.c:5816
static List * add_function_defaults(List *args, int pronargs, HeapTuple func_tuple)
Definition clauses.c:5078
#define ece_all_arguments_const(node)
Definition clauses.c:2672
#define ece_evaluate_expr(node)
Definition clauses.c:2676
bool contain_mutable_functions(Node *clause)
Definition clauses.c:383
#define ece_generic_processing(node)
Definition clauses.c:2663
static Expr * evaluate_function(Oid funcid, Oid result_type, int32 result_typmod, Oid result_collid, Oid input_collid, List *args, bool funcvariadic, HeapTuple func_tuple, eval_const_expressions_context *context)
Definition clauses.c:5177
static Node * substitute_actual_parameters_mutator(Node *node, substitute_actual_parameters_context *context)
Definition clauses.c:5672
static bool ece_function_is_safe(Oid funcid, eval_const_expressions_context *context)
Definition clauses.c:4186
static List * simplify_and_arguments(List *args, eval_const_expressions_context *context, bool *haveNull, bool *forceFalse)
Definition clauses.c:4330
static Expr * simplify_function(Oid funcid, Oid result_type, int32 result_typmod, Oid result_collid, Oid input_collid, List **args_p, bool funcvariadic, bool process_args, bool allow_non_const, eval_const_expressions_context *context)
Definition clauses.c:4493
static Expr * inline_function(Oid funcid, Oid result_type, Oid result_collid, Oid input_collid, List *args, bool funcvariadic, HeapTuple func_tuple, eval_const_expressions_context *context)
Definition clauses.c:5303
static List * reorder_function_arguments(List *args, int pronargs, HeapTuple func_tuple)
Definition clauses.c:5008
static Node * simplify_aggref(Aggref *aggref, eval_const_expressions_context *context)
Definition clauses.c:4599
static Node * substitute_actual_parameters(Node *expr, int nargs, List *args, int *usecounts)
Definition clauses.c:5659
static Query * substitute_actual_parameters_in_from(Query *expr, int nargs, List *args)
Definition clauses.c:6180
bool expr_is_nonnullable(PlannerInfo *root, Expr *expr, NotNullSource source)
Definition clauses.c:4785
static void sql_inline_error_callback(void *arg)
Definition clauses.c:5700
static bool contain_non_const_walker(Node *node, void *context)
Definition clauses.c:4170
static bool contain_context_dependent_node(Node *clause)
Definition clauses.c:1194
static void recheck_cast_function_args(List *args, Oid result_type, Oid *proargtypes, int pronargs, HeapTuple func_tuple)
Definition clauses.c:5132
List * expand_function_arguments(List *args, bool include_out_arguments, Oid result_type, HeapTuple func_tuple)
Definition clauses.c:4927
bool contain_nonstrict_functions(Node *clause)
Definition clauses.c:1006
static Node * substitute_actual_parameters_in_from_mutator(Node *node, substitute_actual_parameters_in_from_context *context)
Definition clauses.c:6195
static Query * inline_sql_function_in_from(PlannerInfo *root, RangeTblFunction *rtfunc, FuncExpr *fexpr, HeapTuple func_tuple, Form_pg_proc funcform, const char *src)
Definition clauses.c:6020
bool contain_subplans(Node *clause)
Definition clauses.c:343
static Node * simplify_boolean_equality(Oid opno, List *args)
Definition clauses.c:4424
Bitmapset * pull_paramids(Expr *expr)
Definition clauses.c:6240
ScalarArrayOpExpr * make_SAOP_expr(Oid oper, Node *leftexpr, Oid coltype, Oid arraycollid, Oid inputcollid, List *exprs, bool haveNonConst)
Definition clauses.c:6272
bool var_is_nonnullable(PlannerInfo *root, Var *var, NotNullSource source)
Definition clauses.c:4641
static Node * eval_const_expressions_mutator(Node *node, eval_const_expressions_context *context)
Definition clauses.c:2686
static bool pull_paramids_walker(Node *node, Bitmapset **context)
Definition clauses.c:6250
Expr * evaluate_expr(Expr *expr, Oid result_type, int32 result_typmod, Oid result_collation)
Definition clauses.c:5724
static List * fetch_function_defaults(HeapTuple func_tuple)
Definition clauses.c:5102
bool contain_volatile_functions(Node *clause)
Definition clauses.c:551
double cpu_operator_cost
Definition costsize.c:135
void cost_qual_eval(QualCost *cost, List *quals, PlannerInfo *root)
Definition costsize.c:4900
Datum datumCopy(Datum value, bool typByVal, int typLen)
Definition datum.c:132
Datum arg
Definition elog.c:1323
ErrorContextCallback * error_context_stack
Definition elog.c:100
#define errcontext
Definition elog.h:200
int internalerrquery(const char *query)
int internalerrposition(int cursorpos)
#define ERROR
Definition elog.h:40
int geterrposition(void)
#define elog(elevel,...)
Definition elog.h:228
int errposition(int cursorpos)
ExprState * ExecInitExpr(Expr *node, PlanState *parent)
Definition execExpr.c:143
void FreeExecutorState(EState *estate)
Definition execUtils.c:197
EState * CreateExecutorState(void)
Definition execUtils.c:90
#define GetPerTupleExprContext(estate)
Definition executor.h:667
static Datum ExecEvalExprSwitchContext(ExprState *state, ExprContext *econtext, bool *isNull)
Definition executor.h:446
#define palloc_array(type, count)
Definition fe_memutils.h:91
#define OidFunctionCall1(functionId, arg1)
Definition fmgr.h:726
#define PG_DETOAST_DATUM_COPY(datum)
Definition fmgr.h:242
#define FmgrHookIsNeeded(fn_oid)
Definition fmgr.h:854
TypeFuncClass get_expr_result_type(Node *expr, Oid *resultTypeId, TupleDesc *resultTupleDesc)
Definition funcapi.c:299
TypeFuncClass
Definition funcapi.h:147
@ TYPEFUNC_COMPOSITE
Definition funcapi.h:149
@ TYPEFUNC_RECORD
Definition funcapi.h:151
@ TYPEFUNC_COMPOSITE_DOMAIN
Definition funcapi.h:150
bool check_sql_fn_retval(List *queryTreeLists, Oid rettype, TupleDesc rettupdesc, char prokind, bool insertDroppedCols)
Definition functions.c:2117
void sql_fn_parser_setup(struct ParseState *pstate, SQLFunctionParseInfoPtr pinfo)
Definition functions.c:341
SQLFunctionParseInfoPtr prepare_sql_fn_parse_info(HeapTuple procedureTuple, Node *call_expr, Oid inputCollation)
Definition functions.c:252
const char * str
bool heap_attisnull(HeapTuple tup, int attnum, TupleDesc tupleDesc)
Definition heaptuple.c:456
#define HeapTupleIsValid(tuple)
Definition htup.h:78
static void * GETSTRUCT(const HeapTupleData *tuple)
static struct @177 value
int i
Definition isn.c:77
List * lappend(List *list, void *datum)
Definition list.c:339
List * list_delete_first(List *list)
Definition list.c:943
List * list_concat_copy(const List *list1, const List *list2)
Definition list.c:598
List * list_copy(const List *oldlist)
Definition list.c:1573
List * lappend_oid(List *list, Oid datum)
Definition list.c:375
List * list_delete_last(List *list)
Definition list.c:957
void list_free(List *list)
Definition list.c:1546
bool list_member_oid(const List *list, Oid datum)
Definition list.c:722
List * list_delete_first_n(List *list, int n)
Definition list.c:983
#define NoLock
Definition lockdefs.h:34
RegProcedure get_func_support(Oid funcid)
Definition lsyscache.c:2089
void getTypeOutputInfo(Oid type, Oid *typOutput, bool *typIsVarlena)
Definition lsyscache.c:3140
void get_typlenbyvalalign(Oid typid, int16 *typlen, bool *typbyval, char *typalign)
Definition lsyscache.c:2502
void get_typlenbyval(Oid typid, int16 *typlen, bool *typbyval)
Definition lsyscache.c:2482
RegProcedure get_opcode(Oid opno)
Definition lsyscache.c:1516
void getTypeInputInfo(Oid type, Oid *typInput, Oid *typIOParam)
Definition lsyscache.c:3107
char func_volatile(Oid funcid)
Definition lsyscache.c:2011
Oid get_array_type(Oid typid)
Definition lsyscache.c:3020
Expr * make_orclause(List *orclauses)
Definition makefuncs.c:743
Var * makeVar(int varno, AttrNumber varattno, Oid vartype, int32 vartypmod, Oid varcollid, Index varlevelsup)
Definition makefuncs.c:66
Const * makeNullConst(Oid consttype, int32 consttypmod, Oid constcollid)
Definition makefuncs.c:388
Node * makeBoolConst(bool value, bool isnull)
Definition makefuncs.c:408
Expr * make_andclause(List *andclauses)
Definition makefuncs.c:727
Expr * make_notclause(Expr *notclause)
Definition makefuncs.c:759
JsonValueExpr * makeJsonValueExpr(Expr *raw_expr, Expr *formatted_expr, JsonFormat *format)
Definition makefuncs.c:938
Const * makeConst(Oid consttype, int32 consttypmod, Oid constcollid, int constlen, Datum constvalue, bool constisnull, bool constbyval)
Definition makefuncs.c:350
void pfree(void *pointer)
Definition mcxt.c:1619
void * palloc0(Size size)
Definition mcxt.c:1420
MemoryContext CurrentMemoryContext
Definition mcxt.c:161
void MemoryContextDelete(MemoryContext context)
Definition mcxt.c:475
#define AllocSetContextCreate
Definition memutils.h:129
#define ALLOCSET_DEFAULT_SIZES
Definition memutils.h:160
Oid GetUserId(void)
Definition miscinit.c:470
Oid exprType(const Node *expr)
Definition nodeFuncs.c:42
int32 exprTypmod(const Node *expr)
Definition nodeFuncs.c:304
Oid exprCollation(const Node *expr)
Definition nodeFuncs.c:826
Node * applyRelabelType(Node *arg, Oid rtype, int32 rtypmod, Oid rcollid, CoercionForm rformat, int rlocation, bool overwrite_ok)
Definition nodeFuncs.c:641
void fix_opfuncids(Node *node)
Definition nodeFuncs.c:1859
void set_sa_opfuncid(ScalarArrayOpExpr *opexpr)
Definition nodeFuncs.c:1901
void set_opfuncid(OpExpr *opexpr)
Definition nodeFuncs.c:1890
#define expression_tree_mutator(n, m, c)
Definition nodeFuncs.h:155
static bool is_andclause(const void *clause)
Definition nodeFuncs.h:107
static bool is_orclause(const void *clause)
Definition nodeFuncs.h:116
#define expression_tree_walker(n, w, c)
Definition nodeFuncs.h:153
#define query_tree_mutator(q, m, c, f)
Definition nodeFuncs.h:160
#define IsA(nodeptr, _type_)
Definition nodes.h:164
#define copyObject(obj)
Definition nodes.h:232
#define nodeTag(nodeptr)
Definition nodes.h:139
@ CMD_SELECT
Definition nodes.h:275
#define makeNode(_type_)
Definition nodes.h:161
#define castNode(_type_, nodeptr)
Definition nodes.h:182
NotNullSource
Definition optimizer.h:135
@ NOTNULL_SOURCE_HASHTABLE
Definition optimizer.h:137
@ NOTNULL_SOURCE_RELOPT
Definition optimizer.h:136
@ NOTNULL_SOURCE_CATALOG
Definition optimizer.h:138
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition palloc.h:138
#define PARAM_FLAG_CONST
Definition params.h:87
void(* ParserSetupHook)(ParseState *pstate, void *arg)
Definition params.h:107
Oid enforce_generic_type_consistency(const Oid *actual_arg_types, Oid *declared_arg_types, int nargs, Oid rettype, bool allow_poly)
void make_fn_arguments(ParseState *pstate, List *fargs, Oid *actual_arg_types, Oid *declared_arg_types)
void free_parsestate(ParseState *pstate)
Definition parse_node.c:72
ParseState * make_parsestate(ParseState *parentParseState)
Definition parse_node.c:39
Operator oper(ParseState *pstate, List *opname, Oid ltypeId, Oid rtypeId, bool noError, int location)
Definition parse_oper.c:376
@ RTE_FUNCTION
@ RTE_RELATION
#define ACL_EXECUTE
Definition parsenodes.h:83
Query * transformTopLevelStmt(ParseState *pstate, RawStmt *parseTree)
Definition analyze.c:271
#define planner_rt_fetch(rti, root)
Definition pathnodes.h:704
#define FUNC_MAX_ARGS
bool has_subclass(Oid relationId)
#define lfirst(lc)
Definition pg_list.h:172
#define lfirst_node(type, lc)
Definition pg_list.h:176
static int list_length(const List *l)
Definition pg_list.h:152
#define linitial_node(type, l)
Definition pg_list.h:181
#define NIL
Definition pg_list.h:68
#define list_make1(x1)
Definition pg_list.h:244
#define foreach_ptr(type, var, lst)
Definition pg_list.h:501
static void * list_nth(const List *list, int n)
Definition pg_list.h:331
#define linitial(l)
Definition pg_list.h:178
#define list_make3(x1, x2, x3)
Definition pg_list.h:248
#define lsecond(l)
Definition pg_list.h:183
#define foreach_node(type, var, lst)
Definition pg_list.h:528
#define list_make2(x1, x2)
Definition pg_list.h:246
int16 pronargs
Definition pg_proc.h:83
END_CATALOG_STRUCT typedef FormData_pg_proc * Form_pg_proc
Definition pg_proc.h:140
static rewind_source * source
Definition pg_rewind.c:89
char typalign
Definition pg_type.h:178
Bitmapset * find_relation_notnullatts(PlannerInfo *root, Oid relid)
Definition plancat.c:763
List * pg_analyze_and_rewrite_withcb(RawStmt *parsetree, const char *query_string, ParserSetupHook parserSetup, void *parserSetupArg, QueryEnvironment *queryEnv)
Definition postgres.c:775
List * pg_parse_query(const char *query_string)
Definition postgres.c:616
List * pg_rewrite_query(Query *query)
Definition postgres.c:815
static bool DatumGetBool(Datum X)
Definition postgres.h:100
static Datum BoolGetDatum(bool X)
Definition postgres.h:112
static Datum ObjectIdGetDatum(Oid X)
Definition postgres.h:252
uint64_t Datum
Definition postgres.h:70
static Pointer DatumGetPointer(Datum X)
Definition postgres.h:332
static Datum Int32GetDatum(int32 X)
Definition postgres.h:212
#define PointerGetDatum(X)
Definition postgres.h:354
#define InvalidOid
unsigned int Oid
Node * negate_clause(Node *node)
Definition prepqual.c:73
e
static int fb(int x)
@ IS_NOT_TRUE
Definition primnodes.h:2016
@ IS_NOT_FALSE
Definition primnodes.h:2016
@ IS_NOT_UNKNOWN
Definition primnodes.h:2016
@ IS_TRUE
Definition primnodes.h:2016
@ IS_UNKNOWN
Definition primnodes.h:2016
@ IS_FALSE
Definition primnodes.h:2016
@ AND_EXPR
Definition primnodes.h:964
@ OR_EXPR
Definition primnodes.h:964
@ NOT_EXPR
Definition primnodes.h:964
@ PARAM_EXTERN
Definition primnodes.h:385
@ VAR_RETURNING_DEFAULT
Definition primnodes.h:257
@ COERCE_IMPLICIT_CAST
Definition primnodes.h:769
@ COERCE_EXPLICIT_CALL
Definition primnodes.h:767
@ IS_NULL
Definition primnodes.h:1992
@ IS_NOT_NULL
Definition primnodes.h:1992
@ JSCTOR_JSON_ARRAY_QUERY
Definition primnodes.h:1719
tree ctl root
Definition radixtree.h:1857
void * stringToNode(const char *str)
Definition read.c:90
#define RelationGetDescr(relation)
Definition rel.h:542
RelOptInfo * find_base_rel(PlannerInfo *root, int relid)
Definition relnode.c:544
void AcquireRewriteLocks(Query *parsetree, bool forExecute, bool forUpdatePushedDown)
void IncrementVarSublevelsUp(Node *node, int delta_sublevels_up, int min_sublevels_up)
void record_plan_type_dependency(PlannerInfo *root, Oid typid)
Definition setrefs.c:3672
void record_plan_function_dependency(PlannerInfo *root, Oid funcid)
Definition setrefs.c:3632
void check_stack_depth(void)
Definition stack_depth.c:95
Oid aggfnoid
Definition primnodes.h:464
BoolExprType boolop
Definition primnodes.h:972
List * args
Definition primnodes.h:973
ParseLoc location
Definition primnodes.h:1249
ParseLoc location
Definition primnodes.h:1316
char attnullability
Definition tupdesc.h:80
Oid consttype
Definition primnodes.h:330
MemoryContext es_query_cxt
Definition execnodes.h:746
struct ErrorContextCallback * previous
Definition elog.h:299
Expr xpr
Definition primnodes.h:781
ParseLoc location
Definition primnodes.h:803
Oid funcid
Definition primnodes.h:783
List * args
Definition primnodes.h:801
Definition pg_list.h:54
Definition nodes.h:135
NodeTag type
Definition nodes.h:136
Oid opno
Definition primnodes.h:851
List * args
Definition primnodes.h:869
ParseLoc location
Definition primnodes.h:872
ParamExternData params[FLEXIBLE_ARRAY_MEMBER]
Definition params.h:124
ParamFetchHook paramFetch
Definition params.h:111
ParseLoc location
Definition primnodes.h:404
int32 paramtypmod
Definition primnodes.h:400
int paramid
Definition primnodes.h:397
Oid paramtype
Definition primnodes.h:398
ParamKind paramkind
Definition primnodes.h:396
Oid paramcollid
Definition primnodes.h:402
const char * p_sourcetext
Definition parse_node.h:214
Bitmapset * notnullattnums
Definition pathnodes.h:1083
List * args
Definition primnodes.h:1450
AttrNumber varattno
Definition primnodes.h:275
int varno
Definition primnodes.h:270
VarReturningType varreturningtype
Definition primnodes.h:298
Index varlevelsup
Definition primnodes.h:295
List * args
Definition primnodes.h:606
Index winref
Definition primnodes.h:612
Expr * aggfilter
Definition primnodes.h:608
ParseLoc location
Definition primnodes.h:620
int ignore_nulls
Definition primnodes.h:618
void ReleaseSysCache(HeapTuple tuple)
Definition syscache.c:265
Datum SysCacheGetAttrNotNull(SysCacheIdentifier cacheId, HeapTuple tup, AttrNumber attributeNumber)
Definition syscache.c:626
HeapTuple SearchSysCache1(SysCacheIdentifier cacheId, Datum key1)
Definition syscache.c:221
Datum SysCacheGetAttr(SysCacheIdentifier cacheId, HeapTuple tup, AttrNumber attributeNumber, bool *isNull)
Definition syscache.c:596
void table_close(Relation relation, LOCKMODE lockmode)
Definition table.c:126
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition table.c:40
TupleDesc BuildDescFromLists(const List *names, const List *types, const List *typmods, const List *collations)
Definition tupdesc.c:1109
#define ATTNULLABLE_VALID
Definition tupdesc.h:86
static CompactAttribute * TupleDescCompactAttr(TupleDesc tupdesc, int i)
Definition tupdesc.h:195
bool DomainHasConstraints(Oid type_id, bool *has_volatile)
Definition typcache.c:1495

◆ ece_evaluate_expr

#define ece_evaluate_expr (   node)
Value:
((Node *) evaluate_expr((Expr *) (node), \
exprType((Node *) (node)), \
exprTypmod((Node *) (node)), \
exprCollation((Node *) (node))))

Definition at line 2676 of file clauses.c.

◆ ece_generic_processing

#define ece_generic_processing (   node)
Value:

Definition at line 2663 of file clauses.c.

◆ MIN_ARRAY_SIZE_FOR_HASHED_SAOP

#define MIN_ARRAY_SIZE_FOR_HASHED_SAOP   9

Definition at line 2515 of file clauses.c.

Function Documentation

◆ add_function_defaults()

static List * add_function_defaults ( List args,
int  pronargs,
HeapTuple  func_tuple 
)
static

Definition at line 5078 of file clauses.c.

5079{
5080 int nargsprovided = list_length(args);
5081 List *defaults;
5082 int ndelete;
5083
5084 /* Get all the default expressions from the pg_proc tuple */
5086
5087 /* Delete any unused defaults from the list */
5088 ndelete = nargsprovided + list_length(defaults) - pronargs;
5089 if (ndelete < 0)
5090 elog(ERROR, "not enough default arguments");
5091 if (ndelete > 0)
5092 defaults = list_delete_first_n(defaults, ndelete);
5093
5094 /* And form the combined argument list, not modifying the input list */
5095 return list_concat_copy(args, defaults);
5096}

References elog, ERROR, fb(), fetch_function_defaults(), list_concat_copy(), list_delete_first_n(), list_length(), and pronargs.

Referenced by expand_function_arguments().

◆ CommuteOpExpr()

void CommuteOpExpr ( OpExpr clause)

Definition at line 2392 of file clauses.c.

2393{
2394 Oid opoid;
2395 Node *temp;
2396
2397 /* Sanity checks: caller is at fault if these fail */
2398 if (!is_opclause(clause) ||
2399 list_length(clause->args) != 2)
2400 elog(ERROR, "cannot commute non-binary-operator clause");
2401
2402 opoid = get_commutator(clause->opno);
2403
2404 if (!OidIsValid(opoid))
2405 elog(ERROR, "could not find commutator for operator %u",
2406 clause->opno);
2407
2408 /*
2409 * modify the clause in-place!
2410 */
2411 clause->opno = opoid;
2412 clause->opfuncid = InvalidOid;
2413 /* opresulttype, opretset, opcollid, inputcollid need not change */
2414
2415 temp = linitial(clause->args);
2416 linitial(clause->args) = lsecond(clause->args);
2417 lsecond(clause->args) = temp;
2418}
Oid get_commutator(Oid opno)
Definition lsyscache.c:1740
static bool is_opclause(const void *clause)
Definition nodeFuncs.h:76

References OpExpr::args, elog, ERROR, fb(), get_commutator(), InvalidOid, is_opclause(), linitial, list_length(), lsecond, OidIsValid, and OpExpr::opno.

Referenced by get_switched_clauses().

◆ contain_agg_clause()

bool contain_agg_clause ( Node clause)

Definition at line 194 of file clauses.c.

195{
196 return contain_agg_clause_walker(clause, NULL);
197}
static bool contain_agg_clause_walker(Node *node, void *context)
Definition clauses.c:200

References contain_agg_clause_walker(), and fb().

Referenced by get_eclass_for_sort_expr(), mark_nullable_by_grouping(), and subquery_planner().

◆ contain_agg_clause_walker()

static bool contain_agg_clause_walker ( Node node,
void context 
)
static

Definition at line 200 of file clauses.c.

201{
202 if (node == NULL)
203 return false;
204 if (IsA(node, Aggref))
205 {
206 Assert(((Aggref *) node)->agglevelsup == 0);
207 return true; /* abort the tree traversal and return true */
208 }
209 if (IsA(node, GroupingFunc))
210 {
211 Assert(((GroupingFunc *) node)->agglevelsup == 0);
212 return true; /* abort the tree traversal and return true */
213 }
214 Assert(!IsA(node, SubLink));
216}

References Assert, contain_agg_clause_walker(), expression_tree_walker, fb(), and IsA.

Referenced by contain_agg_clause(), and contain_agg_clause_walker().

◆ contain_context_dependent_node()

static bool contain_context_dependent_node ( Node clause)
static

Definition at line 1194 of file clauses.c.

1195{
1196 int flags = 0;
1197
1198 return contain_context_dependent_node_walker(clause, &flags);
1199}
static bool contain_context_dependent_node_walker(Node *node, int *flags)
Definition clauses.c:1204

References contain_context_dependent_node_walker().

Referenced by inline_function().

◆ contain_context_dependent_node_walker()

static bool contain_context_dependent_node_walker ( Node node,
int flags 
)
static

Definition at line 1204 of file clauses.c.

1205{
1206 if (node == NULL)
1207 return false;
1208 if (IsA(node, CaseTestExpr))
1209 return !(*flags & CCDN_CASETESTEXPR_OK);
1210 else if (IsA(node, CaseExpr))
1211 {
1212 CaseExpr *caseexpr = (CaseExpr *) node;
1213
1214 /*
1215 * If this CASE doesn't have a test expression, then it doesn't create
1216 * a context in which CaseTestExprs should appear, so just fall
1217 * through and treat it as a generic expression node.
1218 */
1219 if (caseexpr->arg)
1220 {
1221 int save_flags = *flags;
1222 bool res;
1223
1224 /*
1225 * Note: in principle, we could distinguish the various sub-parts
1226 * of a CASE construct and set the flag bit only for some of them,
1227 * since we are only expecting CaseTestExprs to appear in the
1228 * "expr" subtree of the CaseWhen nodes. But it doesn't really
1229 * seem worth any extra code. If there are any bare CaseTestExprs
1230 * elsewhere in the CASE, something's wrong already.
1231 */
1232 *flags |= CCDN_CASETESTEXPR_OK;
1233 res = expression_tree_walker(node,
1235 flags);
1236 *flags = save_flags;
1237 return res;
1238 }
1239 }
1240 else if (IsA(node, ArrayCoerceExpr))
1241 {
1243 int save_flags;
1244 bool res;
1245
1246 /* Check the array expression */
1247 if (contain_context_dependent_node_walker((Node *) ac->arg, flags))
1248 return true;
1249
1250 /* Check the elemexpr, which is allowed to contain CaseTestExpr */
1251 save_flags = *flags;
1252 *flags |= CCDN_CASETESTEXPR_OK;
1253 res = contain_context_dependent_node_walker((Node *) ac->elemexpr,
1254 flags);
1255 *flags = save_flags;
1256 return res;
1257 }
1259 flags);
1260}
#define CCDN_CASETESTEXPR_OK
Definition clauses.c:1201

References CCDN_CASETESTEXPR_OK, contain_context_dependent_node_walker(), expression_tree_walker, fb(), and IsA.

Referenced by contain_context_dependent_node(), and contain_context_dependent_node_walker().

◆ contain_exec_param()

bool contain_exec_param ( Node clause,
List param_ids 
)

Definition at line 1152 of file clauses.c.

1153{
1154 return contain_exec_param_walker(clause, param_ids);
1155}
static bool contain_exec_param_walker(Node *node, List *param_ids)
Definition clauses.c:1158

References contain_exec_param_walker(), and fb().

Referenced by test_opexpr_is_hashable().

◆ contain_exec_param_walker()

static bool contain_exec_param_walker ( Node node,
List param_ids 
)
static

Definition at line 1158 of file clauses.c.

1159{
1160 if (node == NULL)
1161 return false;
1162 if (IsA(node, Param))
1163 {
1164 Param *p = (Param *) node;
1165
1166 if (p->paramkind == PARAM_EXEC &&
1168 return true;
1169 }
1171}
bool list_member_int(const List *list, int datum)
Definition list.c:702
@ PARAM_EXEC
Definition primnodes.h:386

References contain_exec_param_walker(), expression_tree_walker, fb(), IsA, list_member_int(), PARAM_EXEC, Param::paramid, and Param::paramkind.

Referenced by contain_exec_param(), and contain_exec_param_walker().

◆ contain_leaked_vars()

bool contain_leaked_vars ( Node clause)

Definition at line 1278 of file clauses.c.

1279{
1280 return contain_leaked_vars_walker(clause, NULL);
1281}
static bool contain_leaked_vars_walker(Node *node, void *context)
Definition clauses.c:1290

References contain_leaked_vars_walker(), and fb().

Referenced by make_plain_restrictinfo(), and qual_is_pushdown_safe().

◆ contain_leaked_vars_checker()

static bool contain_leaked_vars_checker ( Oid  func_id,
void context 
)
static

Definition at line 1284 of file clauses.c.

1285{
1286 return !get_func_leakproof(func_id);
1287}
bool get_func_leakproof(Oid funcid)
Definition lsyscache.c:2068

References fb(), and get_func_leakproof().

Referenced by contain_leaked_vars_walker().

◆ contain_leaked_vars_walker()

static bool contain_leaked_vars_walker ( Node node,
void context 
)
static

Definition at line 1290 of file clauses.c.

1291{
1292 if (node == NULL)
1293 return false;
1294
1295 switch (nodeTag(node))
1296 {
1297 case T_Var:
1298 case T_Const:
1299 case T_Param:
1300 case T_ArrayExpr:
1301 case T_FieldSelect:
1302 case T_FieldStore:
1303 case T_NamedArgExpr:
1304 case T_BoolExpr:
1305 case T_RelabelType:
1306 case T_CollateExpr:
1307 case T_CaseExpr:
1308 case T_CaseTestExpr:
1309 case T_RowExpr:
1310 case T_SQLValueFunction:
1311 case T_NullTest:
1312 case T_BooleanTest:
1313 case T_NextValueExpr:
1314 case T_ReturningExpr:
1315 case T_List:
1316
1317 /*
1318 * We know these node types don't contain function calls; but
1319 * something further down in the node tree might.
1320 */
1321 break;
1322
1323 case T_FuncExpr:
1324 case T_OpExpr:
1325 case T_DistinctExpr:
1326 case T_NullIfExpr:
1328 case T_CoerceViaIO:
1329 case T_ArrayCoerceExpr:
1330
1331 /*
1332 * If node contains a leaky function call, and there's any Var
1333 * underneath it, reject.
1334 */
1336 context) &&
1337 contain_var_clause(node))
1338 return true;
1339 break;
1340
1341 case T_SubscriptingRef:
1342 {
1343 SubscriptingRef *sbsref = (SubscriptingRef *) node;
1345
1346 /* Consult the subscripting support method info */
1347 sbsroutines = getSubscriptingRoutines(sbsref->refcontainertype,
1348 NULL);
1349 if (!sbsroutines ||
1350 !(sbsref->refassgnexpr != NULL ?
1351 sbsroutines->store_leakproof :
1352 sbsroutines->fetch_leakproof))
1353 {
1354 /* Node is leaky, so reject if it contains Vars */
1355 if (contain_var_clause(node))
1356 return true;
1357 }
1358 }
1359 break;
1360
1361 case T_RowCompareExpr:
1362 {
1363 /*
1364 * It's worth special-casing this because a leaky comparison
1365 * function only compromises one pair of row elements, which
1366 * might not contain Vars while others do.
1367 */
1369 ListCell *opid;
1370 ListCell *larg;
1371 ListCell *rarg;
1372
1373 forthree(opid, rcexpr->opnos,
1374 larg, rcexpr->largs,
1375 rarg, rcexpr->rargs)
1376 {
1377 Oid funcid = get_opcode(lfirst_oid(opid));
1378
1379 if (!get_func_leakproof(funcid) &&
1380 (contain_var_clause((Node *) lfirst(larg)) ||
1381 contain_var_clause((Node *) lfirst(rarg))))
1382 return true;
1383 }
1384 }
1385 break;
1386
1387 case T_MinMaxExpr:
1388 {
1389 /*
1390 * MinMaxExpr is leakproof if the comparison function it calls
1391 * is leakproof.
1392 */
1393 MinMaxExpr *minmaxexpr = (MinMaxExpr *) node;
1394 TypeCacheEntry *typentry;
1395 bool leakproof;
1396
1397 /* Look up the btree comparison function for the datatype */
1398 typentry = lookup_type_cache(minmaxexpr->minmaxtype,
1400 if (OidIsValid(typentry->cmp_proc))
1402 else
1403 {
1404 /*
1405 * The executor will throw an error, but here we just
1406 * treat the missing function as leaky.
1407 */
1408 leakproof = false;
1409 }
1410
1411 if (!leakproof &&
1413 return true;
1414 }
1415 break;
1416
1417 case T_CurrentOfExpr:
1418
1419 /*
1420 * WHERE CURRENT OF doesn't contain leaky function calls.
1421 * Moreover, it is essential that this is considered non-leaky,
1422 * since the planner must always generate a TID scan when CURRENT
1423 * OF is present -- cf. cost_tidscan.
1424 */
1425 return false;
1426
1427 default:
1428
1429 /*
1430 * If we don't recognize the node tag, assume it might be leaky.
1431 * This prevents an unexpected security hole if someone adds a new
1432 * node type that can call a function.
1433 */
1434 return true;
1435 }
1437 context);
1438}
static bool contain_leaked_vars_checker(Oid func_id, void *context)
Definition clauses.c:1284
const struct SubscriptRoutines * getSubscriptingRoutines(Oid typid, Oid *typelemp)
Definition lsyscache.c:3363
bool check_functions_in_node(Node *node, check_function_callback checker, void *context)
Definition nodeFuncs.c:1928
#define forthree(cell1, list1, cell2, list2, cell3, list3)
Definition pg_list.h:595
#define lfirst_oid(lc)
Definition pg_list.h:174
Expr * refassgnexpr
Definition primnodes.h:736
TypeCacheEntry * lookup_type_cache(Oid type_id, int flags)
Definition typcache.c:389
#define TYPECACHE_CMP_PROC
Definition typcache.h:141
bool contain_var_clause(Node *node)
Definition var.c:406

References check_functions_in_node(), TypeCacheEntry::cmp_proc, contain_leaked_vars_checker(), contain_leaked_vars_walker(), contain_var_clause(), expression_tree_walker, fb(), forthree, get_func_leakproof(), get_opcode(), getSubscriptingRoutines(), lfirst, lfirst_oid, lookup_type_cache(), nodeTag, OidIsValid, SubscriptingRef::refassgnexpr, and TYPECACHE_CMP_PROC.

Referenced by contain_leaked_vars(), and contain_leaked_vars_walker().

◆ contain_mutable_functions()

◆ contain_mutable_functions_after_planning()

bool contain_mutable_functions_after_planning ( Expr expr)

Definition at line 503 of file clauses.c.

504{
505 /* We assume here that expression_planner() won't scribble on its input */
506 expr = expression_planner(expr);
507
508 /* Now we can search for non-immutable functions */
509 return contain_mutable_functions((Node *) expr);
510}
Expr * expression_planner(Expr *expr)
Definition planner.c:7081

References contain_mutable_functions(), and expression_planner().

Referenced by CheckPredicate(), ComputeIndexAttrs(), and cookDefault().

◆ contain_mutable_functions_checker()

static bool contain_mutable_functions_checker ( Oid  func_id,
void context 
)
static

Definition at line 389 of file clauses.c.

390{
392}

References fb(), and func_volatile().

Referenced by contain_mutable_functions_walker().

◆ contain_mutable_functions_walker()

static bool contain_mutable_functions_walker ( Node node,
void context 
)
static

Definition at line 395 of file clauses.c.

396{
397 if (node == NULL)
398 return false;
399 /* Check for mutable functions in node itself */
401 context))
402 return true;
403
404 if (IsA(node, JsonConstructorExpr))
405 {
407 ListCell *lc;
408 bool is_jsonb;
409
410 is_jsonb = ctor->returning->format->format_type == JS_FORMAT_JSONB;
411
412 /*
413 * Check argument_type => json[b] conversions specifically. We still
414 * recurse to check 'args' below, but here we want to specifically
415 * check whether or not the emitted clause would fail to be immutable
416 * because of TimeZone, for example.
417 */
418 foreach(lc, ctor->args)
419 {
420 Oid typid = exprType(lfirst(lc));
421
422 if (is_jsonb ?
423 !to_jsonb_is_immutable(typid) :
424 !to_json_is_immutable(typid))
425 return true;
426 }
427
428 /* Check all subnodes */
429 }
430
431 if (IsA(node, JsonExpr))
432 {
434 Const *cnst;
435
436 if (!IsA(jexpr->path_spec, Const))
437 return true;
438
439 cnst = castNode(Const, jexpr->path_spec);
440
441 Assert(cnst->consttype == JSONPATHOID);
442 if (cnst->constisnull)
443 return false;
444
445 if (jspIsMutable(DatumGetJsonPathP(cnst->constvalue),
446 jexpr->passing_names, jexpr->passing_values))
447 return true;
448 }
449
450 if (IsA(node, SQLValueFunction))
451 {
452 /* all variants of SQLValueFunction are stable */
453 return true;
454 }
455
456 if (IsA(node, NextValueExpr))
457 {
458 /* NextValueExpr is volatile */
459 return true;
460 }
461
462 /*
463 * It should be safe to treat MinMaxExpr as immutable, because it will
464 * depend on a non-cross-type btree comparison function, and those should
465 * always be immutable. Treating XmlExpr as immutable is more dubious,
466 * and treating CoerceToDomain as immutable is outright dangerous. But we
467 * have done so historically, and changing this would probably cause more
468 * problems than it would fix. In practice, if you have a non-immutable
469 * domain constraint you are in for pain anyhow.
470 */
471
472 /* Recurse to check arguments */
473 if (IsA(node, Query))
474 {
475 /* Recurse into subselects */
476 return query_tree_walker((Query *) node,
478 context, 0);
479 }
481 context);
482}
static bool contain_mutable_functions_checker(Oid func_id, void *context)
Definition clauses.c:389
return true
Definition isn.c:130
bool to_json_is_immutable(Oid typoid)
Definition json.c:696
bool to_jsonb_is_immutable(Oid typoid)
Definition jsonb.c:1081
bool jspIsMutable(JsonPath *path, List *varnames, List *varexprs)
Definition jsonpath.c:1381
static JsonPath * DatumGetJsonPathP(Datum d)
Definition jsonpath.h:35
#define query_tree_walker(q, w, c, f)
Definition nodeFuncs.h:158
@ JS_FORMAT_JSONB
Definition primnodes.h:1667

References Assert, castNode, check_functions_in_node(), contain_mutable_functions_checker(), contain_mutable_functions_walker(), DatumGetJsonPathP(), expression_tree_walker, exprType(), fb(), IsA, JS_FORMAT_JSONB, jspIsMutable(), lfirst, query_tree_walker, to_json_is_immutable(), and to_jsonb_is_immutable().

Referenced by contain_mutable_functions(), and contain_mutable_functions_walker().

◆ contain_non_const_walker()

static bool contain_non_const_walker ( Node node,
void context 
)
static

Definition at line 4170 of file clauses.c.

4171{
4172 if (node == NULL)
4173 return false;
4174 if (IsA(node, Const))
4175 return false;
4176 if (IsA(node, List))
4177 return expression_tree_walker(node, contain_non_const_walker, context);
4178 /* Otherwise, abort the tree traversal and return true */
4179 return true;
4180}

References contain_non_const_walker(), expression_tree_walker, fb(), and IsA.

Referenced by contain_non_const_walker().

◆ contain_nonstrict_functions()

bool contain_nonstrict_functions ( Node clause)

Definition at line 1006 of file clauses.c.

1007{
1009}
static bool contain_nonstrict_functions_walker(Node *node, void *context)
Definition clauses.c:1018

References contain_nonstrict_functions_walker(), and fb().

Referenced by inline_function(), and pullup_replace_vars_callback().

◆ contain_nonstrict_functions_checker()

static bool contain_nonstrict_functions_checker ( Oid  func_id,
void context 
)
static

Definition at line 1012 of file clauses.c.

1013{
1014 return !func_strict(func_id);
1015}
bool func_strict(Oid funcid)
Definition lsyscache.c:1992

References fb(), and func_strict().

Referenced by contain_nonstrict_functions_walker().

◆ contain_nonstrict_functions_walker()

static bool contain_nonstrict_functions_walker ( Node node,
void context 
)
static

Definition at line 1018 of file clauses.c.

1019{
1020 if (node == NULL)
1021 return false;
1022 if (IsA(node, Aggref))
1023 {
1024 /* an aggregate could return non-null with null input */
1025 return true;
1026 }
1027 if (IsA(node, GroupingFunc))
1028 {
1029 /*
1030 * A GroupingFunc doesn't evaluate its arguments, and therefore must
1031 * be treated as nonstrict.
1032 */
1033 return true;
1034 }
1035 if (IsA(node, WindowFunc))
1036 {
1037 /* a window function could return non-null with null input */
1038 return true;
1039 }
1040 if (IsA(node, SubscriptingRef))
1041 {
1042 SubscriptingRef *sbsref = (SubscriptingRef *) node;
1044
1045 /* Subscripting assignment is always presumed nonstrict */
1046 if (sbsref->refassgnexpr != NULL)
1047 return true;
1048 /* Otherwise we must look up the subscripting support methods */
1049 sbsroutines = getSubscriptingRoutines(sbsref->refcontainertype, NULL);
1050 if (!(sbsroutines && sbsroutines->fetch_strict))
1051 return true;
1052 /* else fall through to check args */
1053 }
1054 if (IsA(node, DistinctExpr))
1055 {
1056 /* IS DISTINCT FROM is inherently non-strict */
1057 return true;
1058 }
1059 if (IsA(node, NullIfExpr))
1060 {
1061 /* NULLIF is inherently non-strict */
1062 return true;
1063 }
1064 if (IsA(node, BoolExpr))
1065 {
1066 BoolExpr *expr = (BoolExpr *) node;
1067
1068 switch (expr->boolop)
1069 {
1070 case AND_EXPR:
1071 case OR_EXPR:
1072 /* AND, OR are inherently non-strict */
1073 return true;
1074 default:
1075 break;
1076 }
1077 }
1078 if (IsA(node, SubLink))
1079 {
1080 /* In some cases a sublink might be strict, but in general not */
1081 return true;
1082 }
1083 if (IsA(node, SubPlan))
1084 return true;
1085 if (IsA(node, AlternativeSubPlan))
1086 return true;
1087 if (IsA(node, FieldStore))
1088 return true;
1089 if (IsA(node, CoerceViaIO))
1090 {
1091 /*
1092 * CoerceViaIO is strict regardless of whether the I/O functions are,
1093 * so just go look at its argument; asking check_functions_in_node is
1094 * useless expense and could deliver the wrong answer.
1095 */
1097 context);
1098 }
1099 if (IsA(node, ArrayCoerceExpr))
1100 {
1101 /*
1102 * ArrayCoerceExpr is strict at the array level, regardless of what
1103 * the per-element expression is; so we should ignore elemexpr and
1104 * recurse only into the arg.
1105 */
1107 context);
1108 }
1109 if (IsA(node, CaseExpr))
1110 return true;
1111 if (IsA(node, ArrayExpr))
1112 return true;
1113 if (IsA(node, RowExpr))
1114 return true;
1115 if (IsA(node, RowCompareExpr))
1116 return true;
1117 if (IsA(node, CoalesceExpr))
1118 return true;
1119 if (IsA(node, MinMaxExpr))
1120 return true;
1121 if (IsA(node, XmlExpr))
1122 return true;
1123 if (IsA(node, NullTest))
1124 return true;
1125 if (IsA(node, BooleanTest))
1126 return true;
1127 if (IsA(node, JsonConstructorExpr))
1128 return true;
1129
1130 /* Check other function-containing nodes */
1132 context))
1133 return true;
1134
1136 context);
1137}
static bool contain_nonstrict_functions_checker(Oid func_id, void *context)
Definition clauses.c:1012

References AND_EXPR, arg, BoolExpr::boolop, check_functions_in_node(), contain_nonstrict_functions_checker(), contain_nonstrict_functions_walker(), expression_tree_walker, fb(), getSubscriptingRoutines(), IsA, OR_EXPR, and SubscriptingRef::refassgnexpr.

Referenced by contain_nonstrict_functions(), and contain_nonstrict_functions_walker().

◆ contain_subplans()

bool contain_subplans ( Node clause)

◆ contain_subplans_walker()

static bool contain_subplans_walker ( Node node,
void context 
)
static

Definition at line 349 of file clauses.c.

350{
351 if (node == NULL)
352 return false;
353 if (IsA(node, SubPlan) ||
354 IsA(node, AlternativeSubPlan) ||
355 IsA(node, SubLink))
356 return true; /* abort the tree traversal and return true */
357 return expression_tree_walker(node, contain_subplans_walker, context);
358}

References contain_subplans_walker(), expression_tree_walker, fb(), and IsA.

Referenced by contain_subplans(), and contain_subplans_walker().

◆ contain_volatile_functions()

bool contain_volatile_functions ( Node clause)

Definition at line 551 of file clauses.c.

552{
554}
static bool contain_volatile_functions_walker(Node *node, void *context)
Definition clauses.c:563

References contain_volatile_functions_walker(), and fb().

Referenced by apply_child_basequals(), ATExecAddColumn(), check_hashjoinable(), check_mergejoinable(), check_output_expressions(), compute_semijoin_info(), contain_volatile_functions_after_planning(), convert_ANY_sublink_to_join(), convert_EXISTS_sublink_to_join(), convert_EXISTS_to_ANY(), convert_VALUES_to_ANY(), CopyFrom(), create_agg_clause_infos(), distribute_qual_to_rels(), DomainHasConstraints(), estimate_num_groups(), ExecInitWindowAgg(), expand_indexqual_rowcompare(), find_compatible_agg(), find_simplified_clause(), get_eclass_for_sort_expr(), get_memoize_path(), group_similar_or_args(), initialize_peragg(), inline_function(), inline_function_in_from(), is_pseudo_constant_clause(), is_pseudo_constant_clause_relids(), is_pseudo_constant_for_index(), is_safe_restriction_clause_for(), is_simple_subquery(), is_simple_values(), IsBinaryTidClause(), IsTidEqualAnyClause(), make_sort_input_target(), mark_nullable_by_grouping(), match_clause_to_ordering_op(), match_clause_to_partition_key(), match_opclause_to_indexcol(), match_orclause_to_indexcol(), match_rowcompare_to_indexcol(), match_saopclause_to_indexcol(), paraminfo_get_equal_hashops(), qual_is_pushdown_safe(), remove_unused_subquery_outputs(), SS_process_ctes(), and subquery_planner().

◆ contain_volatile_functions_after_planning()

bool contain_volatile_functions_after_planning ( Expr expr)

Definition at line 672 of file clauses.c.

673{
674 /* We assume here that expression_planner() won't scribble on its input */
675 expr = expression_planner(expr);
676
677 /* Now we can search for volatile functions */
678 return contain_volatile_functions((Node *) expr);
679}

References contain_volatile_functions(), and expression_planner().

Referenced by transformForPortionOfClause().

◆ contain_volatile_functions_checker()

static bool contain_volatile_functions_checker ( Oid  func_id,
void context 
)
static

Definition at line 557 of file clauses.c.

558{
560}

References fb(), and func_volatile().

Referenced by contain_volatile_functions_walker().

◆ contain_volatile_functions_not_nextval()

bool contain_volatile_functions_not_nextval ( Node clause)

Definition at line 686 of file clauses.c.

687{
689}
static bool contain_volatile_functions_not_nextval_walker(Node *node, void *context)
Definition clauses.c:699

References contain_volatile_functions_not_nextval_walker(), and fb().

Referenced by BeginCopyFrom().

◆ contain_volatile_functions_not_nextval_checker()

static bool contain_volatile_functions_not_nextval_checker ( Oid  func_id,
void context 
)
static

Definition at line 692 of file clauses.c.

693{
694 return (func_id != F_NEXTVAL &&
696}

References fb(), and func_volatile().

Referenced by contain_volatile_functions_not_nextval_walker().

◆ contain_volatile_functions_not_nextval_walker()

static bool contain_volatile_functions_not_nextval_walker ( Node node,
void context 
)
static

Definition at line 699 of file clauses.c.

700{
701 if (node == NULL)
702 return false;
703 /* Check for volatile functions in node itself */
706 context))
707 return true;
708
709 /*
710 * See notes in contain_mutable_functions_walker about why we treat
711 * MinMaxExpr, XmlExpr, and CoerceToDomain as immutable, while
712 * SQLValueFunction is stable. Hence, none of them are of interest here.
713 * Also, since we're intentionally ignoring nextval(), presumably we
714 * should ignore NextValueExpr.
715 */
716
717 /* Recurse to check arguments */
718 if (IsA(node, Query))
719 {
720 /* Recurse into subselects */
721 return query_tree_walker((Query *) node,
723 context, 0);
724 }
725 return expression_tree_walker(node,
727 context);
728}
static bool contain_volatile_functions_not_nextval_checker(Oid func_id, void *context)
Definition clauses.c:692

References check_functions_in_node(), contain_volatile_functions_not_nextval_checker(), contain_volatile_functions_not_nextval_walker(), expression_tree_walker, fb(), IsA, and query_tree_walker.

Referenced by contain_volatile_functions_not_nextval(), and contain_volatile_functions_not_nextval_walker().

◆ contain_volatile_functions_walker()

static bool contain_volatile_functions_walker ( Node node,
void context 
)
static

Definition at line 563 of file clauses.c.

564{
565 if (node == NULL)
566 return false;
567 /* Check for volatile functions in node itself */
569 context))
570 return true;
571
572 if (IsA(node, NextValueExpr))
573 {
574 /* NextValueExpr is volatile */
575 return true;
576 }
577
578 if (IsA(node, RestrictInfo))
579 {
580 RestrictInfo *rinfo = (RestrictInfo *) node;
581
582 /*
583 * For RestrictInfo, check if we've checked the volatility of it
584 * before. If so, we can just use the cached value and not bother
585 * checking it again. Otherwise, check it and cache if whether we
586 * found any volatile functions.
587 */
588 if (rinfo->has_volatile == VOLATILITY_NOVOLATILE)
589 return false;
590 else if (rinfo->has_volatile == VOLATILITY_VOLATILE)
591 return true;
592 else
593 {
594 bool hasvolatile;
595
597 context);
598 if (hasvolatile)
599 rinfo->has_volatile = VOLATILITY_VOLATILE;
600 else
601 rinfo->has_volatile = VOLATILITY_NOVOLATILE;
602
603 return hasvolatile;
604 }
605 }
606
607 if (IsA(node, PathTarget))
608 {
609 PathTarget *target = (PathTarget *) node;
610
611 /*
612 * We also do caching for PathTarget the same as we do above for
613 * RestrictInfos.
614 */
616 return false;
617 else if (target->has_volatile_expr == VOLATILITY_VOLATILE)
618 return true;
619 else
620 {
621 bool hasvolatile;
622
624 context);
625
626 if (hasvolatile)
628 else
630
631 return hasvolatile;
632 }
633 }
634
635 /*
636 * See notes in contain_mutable_functions_walker about why we treat
637 * MinMaxExpr, XmlExpr, and CoerceToDomain as immutable, while
638 * SQLValueFunction is stable. Hence, none of them are of interest here.
639 */
640
641 /* Recurse to check arguments */
642 if (IsA(node, Query))
643 {
644 /* Recurse into subselects */
645 return query_tree_walker((Query *) node,
647 context, 0);
648 }
650 context);
651}
static bool contain_volatile_functions_checker(Oid func_id, void *context)
Definition clauses.c:557
@ VOLATILITY_NOVOLATILE
Definition pathnodes.h:1845
@ VOLATILITY_VOLATILE
Definition pathnodes.h:1844
VolatileFunctionStatus has_volatile_expr
Definition pathnodes.h:1890
List * exprs
Definition pathnodes.h:1878
Expr * clause
Definition pathnodes.h:2901

References check_functions_in_node(), RestrictInfo::clause, contain_volatile_functions_checker(), contain_volatile_functions_walker(), expression_tree_walker, PathTarget::exprs, fb(), PathTarget::has_volatile_expr, IsA, query_tree_walker, VOLATILITY_NOVOLATILE, and VOLATILITY_VOLATILE.

Referenced by contain_volatile_functions(), and contain_volatile_functions_walker().

◆ contain_window_function()

bool contain_window_function ( Node clause)

Definition at line 231 of file clauses.c.

232{
233 return contain_windowfuncs(clause);
234}
bool contain_windowfuncs(Node *node)

References contain_windowfuncs().

Referenced by get_eclass_for_sort_expr(), and mark_nullable_by_grouping().

◆ convert_saop_to_hashed_saop()

void convert_saop_to_hashed_saop ( Node node)

Definition at line 2533 of file clauses.c.

2534{
2536}
static bool convert_saop_to_hashed_saop_walker(Node *node, void *context)
Definition clauses.c:2539

References convert_saop_to_hashed_saop_walker(), and fb().

Referenced by preprocess_expression().

◆ convert_saop_to_hashed_saop_walker()

static bool convert_saop_to_hashed_saop_walker ( Node node,
void context 
)
static

Definition at line 2539 of file clauses.c.

2540{
2541 if (node == NULL)
2542 return false;
2543
2544 if (IsA(node, ScalarArrayOpExpr))
2545 {
2546 ScalarArrayOpExpr *saop = (ScalarArrayOpExpr *) node;
2547 Expr *arrayarg = (Expr *) lsecond(saop->args);
2550
2551 if (arrayarg && IsA(arrayarg, Const) &&
2552 !((Const *) arrayarg)->constisnull)
2553 {
2554 if (saop->useOr)
2555 {
2558 {
2559 Datum arrdatum = ((Const *) arrayarg)->constvalue;
2561 int nitems;
2562
2563 /*
2564 * Only fill in the hash functions if the array looks
2565 * large enough for it to be worth hashing instead of
2566 * doing a linear search.
2567 */
2568 nitems = ArrayGetNItems(ARR_NDIM(arr), ARR_DIMS(arr));
2569
2571 {
2572 /* Looks good. Fill in the hash functions */
2573 saop->hashfuncid = lefthashfunc;
2574 }
2575 return false;
2576 }
2577 }
2578 else /* !saop->useOr */
2579 {
2580 Oid negator = get_negator(saop->opno);
2581
2582 /*
2583 * Check if this is a NOT IN using an operator whose negator
2584 * is hashable. If so we can still build a hash table and
2585 * just ensure the lookup items are not in the hash table.
2586 */
2587 if (OidIsValid(negator) &&
2590 {
2591 Datum arrdatum = ((Const *) arrayarg)->constvalue;
2593 int nitems;
2594
2595 /*
2596 * Only fill in the hash functions if the array looks
2597 * large enough for it to be worth hashing instead of
2598 * doing a linear search.
2599 */
2600 nitems = ArrayGetNItems(ARR_NDIM(arr), ARR_DIMS(arr));
2601
2603 {
2604 /* Looks good. Fill in the hash functions */
2605 saop->hashfuncid = lefthashfunc;
2606
2607 /*
2608 * Also set the negfuncid. The executor will need
2609 * that to perform hashtable lookups.
2610 */
2611 saop->negfuncid = get_opcode(negator);
2612 }
2613 return false;
2614 }
2615 }
2616 }
2617 }
2618
2620}
int ArrayGetNItems(int ndim, const int *dims)
Definition arrayutils.c:57
#define MIN_ARRAY_SIZE_FOR_HASHED_SAOP
Definition clauses.c:2515
#define nitems(x)
Definition indent.h:31
bool get_op_hash_functions(Oid opno, RegProcedure *lhs_procno, RegProcedure *rhs_procno)
Definition lsyscache.c:577
Oid get_negator(Oid opno)
Definition lsyscache.c:1764

References ScalarArrayOpExpr::args, ARR_DIMS, ARR_NDIM, ArrayGetNItems(), convert_saop_to_hashed_saop_walker(), DatumGetPointer(), expression_tree_walker, fb(), get_negator(), get_op_hash_functions(), get_opcode(), IsA, lsecond, MIN_ARRAY_SIZE_FOR_HASHED_SAOP, nitems, OidIsValid, ScalarArrayOpExpr::opno, and ScalarArrayOpExpr::useOr.

Referenced by convert_saop_to_hashed_saop(), and convert_saop_to_hashed_saop_walker().

◆ ece_function_is_safe()

static bool ece_function_is_safe ( Oid  funcid,
eval_const_expressions_context context 
)
static

Definition at line 4186 of file clauses.c.

4187{
4188 char provolatile = func_volatile(funcid);
4189
4190 /*
4191 * Ordinarily we are only allowed to simplify immutable functions. But for
4192 * purposes of estimation, we consider it okay to simplify functions that
4193 * are merely stable; the risk that the result might change from planning
4194 * time to execution time is worth taking in preference to not being able
4195 * to estimate the value at all.
4196 */
4198 return true;
4199 if (context->estimate && provolatile == PROVOLATILE_STABLE)
4200 return true;
4201 return false;
4202}

References eval_const_expressions_context::estimate, fb(), and func_volatile().

Referenced by eval_const_expressions_mutator().

◆ estimate_expression_value()

Node * estimate_expression_value ( PlannerInfo root,
Node node 
)

◆ eval_const_expressions()

Node * eval_const_expressions ( PlannerInfo root,
Node node 
)

Definition at line 2500 of file clauses.c.

2501{
2503
2504 if (root)
2505 context.boundParams = root->glob->boundParams; /* bound Params */
2506 else
2507 context.boundParams = NULL;
2508 context.root = root; /* for inlined-function dependencies */
2509 context.active_fns = NIL; /* nothing being recursively simplified */
2510 context.case_val = NULL; /* no CASE being examined */
2511 context.estimate = false; /* safe transformations only */
2512 return eval_const_expressions_mutator(node, &context);
2513}

References eval_const_expressions_context::active_fns, eval_const_expressions_context::boundParams, eval_const_expressions_context::case_val, eval_const_expressions_context::estimate, eval_const_expressions_mutator(), fb(), NIL, eval_const_expressions_context::root, and root.

Referenced by apply_child_basequals(), ATExecAttachPartition(), ConstraintImpliedByRelConstraint(), convert_EXISTS_to_ANY(), convert_VALUES_to_ANY(), DoCopy(), expand_insert_targetlist(), expression_planner(), expression_planner_with_deps(), extended_statistics_update(), fetch_statentries_for_relation(), get_proposed_default_constraint(), get_relation_constraints(), get_relation_info(), get_relation_statistics(), infer_arbiter_indexes(), preprocess_expression(), preprocess_function_rtes(), process_implied_equality(), RelationBuildPartitionKey(), RelationGetIndexExpressions(), RelationGetIndexPredicate(), simplify_EXISTS_query(), and SplitPartitionMoveRows().

◆ eval_const_expressions_mutator()

static Node * eval_const_expressions_mutator ( Node node,
eval_const_expressions_context context 
)
static

Definition at line 2686 of file clauses.c.

2688{
2689
2690 /* since this function recurses, it could be driven to stack overflow */
2692
2693 if (node == NULL)
2694 return NULL;
2695 switch (nodeTag(node))
2696 {
2697 case T_Param:
2698 {
2699 Param *param = (Param *) node;
2700 ParamListInfo paramLI = context->boundParams;
2701
2702 /* Look to see if we've been given a value for this Param */
2703 if (param->paramkind == PARAM_EXTERN &&
2704 paramLI != NULL &&
2705 param->paramid > 0 &&
2706 param->paramid <= paramLI->numParams)
2707 {
2710
2711 /*
2712 * Give hook a chance in case parameter is dynamic. Tell
2713 * it that this fetch is speculative, so it should avoid
2714 * erroring out if parameter is unavailable.
2715 */
2716 if (paramLI->paramFetch != NULL)
2717 prm = paramLI->paramFetch(paramLI, param->paramid,
2718 true, &prmdata);
2719 else
2720 prm = &paramLI->params[param->paramid - 1];
2721
2722 /*
2723 * We don't just check OidIsValid, but insist that the
2724 * fetched type match the Param, just in case the hook did
2725 * something unexpected. No need to throw an error here
2726 * though; leave that for runtime.
2727 */
2728 if (OidIsValid(prm->ptype) &&
2729 prm->ptype == param->paramtype)
2730 {
2731 /* OK to substitute parameter value? */
2732 if (context->estimate ||
2733 (prm->pflags & PARAM_FLAG_CONST))
2734 {
2735 /*
2736 * Return a Const representing the param value.
2737 * Must copy pass-by-ref datatypes, since the
2738 * Param might be in a memory context
2739 * shorter-lived than our output plan should be.
2740 */
2741 int16 typLen;
2742 bool typByVal;
2743 Datum pval;
2744 Const *con;
2745
2747 &typLen, &typByVal);
2748 if (prm->isnull || typByVal)
2749 pval = prm->value;
2750 else
2751 pval = datumCopy(prm->value, typByVal, typLen);
2752 con = makeConst(param->paramtype,
2753 param->paramtypmod,
2754 param->paramcollid,
2755 (int) typLen,
2756 pval,
2757 prm->isnull,
2758 typByVal);
2759 con->location = param->location;
2760 return (Node *) con;
2761 }
2762 }
2763 }
2764
2765 /*
2766 * Not replaceable, so just copy the Param (no need to
2767 * recurse)
2768 */
2769 return (Node *) copyObject(param);
2770 }
2771 case T_WindowFunc:
2772 {
2773 WindowFunc *expr = (WindowFunc *) node;
2774 Oid funcid = expr->winfnoid;
2775 List *args;
2776 Expr *aggfilter;
2779
2780 /*
2781 * We can't really simplify a WindowFunc node, but we mustn't
2782 * just fall through to the default processing, because we
2783 * have to apply expand_function_arguments to its argument
2784 * list. That takes care of inserting default arguments and
2785 * expanding named-argument notation.
2786 */
2789 elog(ERROR, "cache lookup failed for function %u", funcid);
2790
2792 false, expr->wintype,
2793 func_tuple);
2794
2796
2797 /* Now, recursively simplify the args (which are a List) */
2798 args = (List *)
2801 context);
2802 /* ... and the filter expression, which isn't */
2803 aggfilter = (Expr *)
2805 context);
2806
2807 /* And build the replacement WindowFunc node */
2809 newexpr->winfnoid = expr->winfnoid;
2810 newexpr->wintype = expr->wintype;
2811 newexpr->wincollid = expr->wincollid;
2812 newexpr->inputcollid = expr->inputcollid;
2813 newexpr->args = args;
2814 newexpr->aggfilter = aggfilter;
2815 newexpr->runCondition = expr->runCondition;
2816 newexpr->winref = expr->winref;
2817 newexpr->winstar = expr->winstar;
2818 newexpr->winagg = expr->winagg;
2820 newexpr->location = expr->location;
2821
2822 return (Node *) newexpr;
2823 }
2824 case T_FuncExpr:
2825 {
2826 FuncExpr *expr = (FuncExpr *) node;
2827 List *args = expr->args;
2828 Expr *simple;
2830
2831 /*
2832 * Code for op/func reduction is pretty bulky, so split it out
2833 * as a separate function. Note: exprTypmod normally returns
2834 * -1 for a FuncExpr, but not when the node is recognizably a
2835 * length coercion; we want to preserve the typmod in the
2836 * eventual Const if so.
2837 */
2838 simple = simplify_function(expr->funcid,
2839 expr->funcresulttype,
2840 exprTypmod(node),
2841 expr->funccollid,
2842 expr->inputcollid,
2843 &args,
2844 expr->funcvariadic,
2845 true,
2846 true,
2847 context);
2848 if (simple) /* successfully simplified it */
2849 return (Node *) simple;
2850
2851 /*
2852 * The expression cannot be simplified any further, so build
2853 * and return a replacement FuncExpr node using the
2854 * possibly-simplified arguments. Note that we have also
2855 * converted the argument list to positional notation.
2856 */
2858 newexpr->funcid = expr->funcid;
2859 newexpr->funcresulttype = expr->funcresulttype;
2860 newexpr->funcretset = expr->funcretset;
2861 newexpr->funcvariadic = expr->funcvariadic;
2862 newexpr->funcformat = expr->funcformat;
2863 newexpr->funccollid = expr->funccollid;
2864 newexpr->inputcollid = expr->inputcollid;
2865 newexpr->args = args;
2866 newexpr->location = expr->location;
2867 return (Node *) newexpr;
2868 }
2869 case T_Aggref:
2870 node = ece_generic_processing(node);
2871 if (context->root != NULL)
2872 return simplify_aggref((Aggref *) node, context);
2873 return node;
2874 case T_OpExpr:
2875 {
2876 OpExpr *expr = (OpExpr *) node;
2877 List *args = expr->args;
2878 Expr *simple;
2879 OpExpr *newexpr;
2880
2881 /*
2882 * Need to get OID of underlying function. Okay to scribble
2883 * on input to this extent.
2884 */
2885 set_opfuncid(expr);
2886
2887 /*
2888 * Code for op/func reduction is pretty bulky, so split it out
2889 * as a separate function.
2890 */
2891 simple = simplify_function(expr->opfuncid,
2892 expr->opresulttype, -1,
2893 expr->opcollid,
2894 expr->inputcollid,
2895 &args,
2896 false,
2897 true,
2898 true,
2899 context);
2900 if (simple) /* successfully simplified it */
2901 return (Node *) simple;
2902
2903 /*
2904 * If the operator is boolean equality or inequality, we know
2905 * how to simplify cases involving one constant and one
2906 * non-constant argument.
2907 */
2908 if (expr->opno == BooleanEqualOperator ||
2910 {
2911 simple = (Expr *) simplify_boolean_equality(expr->opno,
2912 args);
2913 if (simple) /* successfully simplified it */
2914 return (Node *) simple;
2915 }
2916
2917 /*
2918 * The expression cannot be simplified any further, so build
2919 * and return a replacement OpExpr node using the
2920 * possibly-simplified arguments.
2921 */
2923 newexpr->opno = expr->opno;
2924 newexpr->opfuncid = expr->opfuncid;
2925 newexpr->opresulttype = expr->opresulttype;
2926 newexpr->opretset = expr->opretset;
2927 newexpr->opcollid = expr->opcollid;
2928 newexpr->inputcollid = expr->inputcollid;
2929 newexpr->args = args;
2930 newexpr->location = expr->location;
2931 return (Node *) newexpr;
2932 }
2933 case T_DistinctExpr:
2934 {
2935 DistinctExpr *expr = (DistinctExpr *) node;
2936 List *args;
2937 ListCell *arg;
2938 bool has_null_input = false;
2939 bool all_null_input = true;
2940 bool has_nonconst_input = false;
2941 bool has_nullable_nonconst = false;
2942 Expr *simple;
2944
2945 /*
2946 * Reduce constants in the DistinctExpr's arguments. We know
2947 * args is either NIL or a List node, so we can call
2948 * expression_tree_mutator directly rather than recursing to
2949 * self.
2950 */
2951 args = (List *) expression_tree_mutator((Node *) expr->args,
2953 context);
2954
2955 /*
2956 * We must do our own check for NULLs because DistinctExpr has
2957 * different results for NULL input than the underlying
2958 * operator does. We also check if any non-constant input is
2959 * potentially nullable.
2960 */
2961 foreach(arg, args)
2962 {
2963 if (IsA(lfirst(arg), Const))
2964 {
2967 }
2968 else
2969 {
2970 has_nonconst_input = true;
2971 all_null_input = false;
2972
2973 if (!has_nullable_nonconst &&
2974 !expr_is_nonnullable(context->root,
2975 (Expr *) lfirst(arg),
2977 has_nullable_nonconst = true;
2978 }
2979 }
2980
2981 if (!has_nonconst_input)
2982 {
2983 /*
2984 * All inputs are constants. We can optimize this out
2985 * completely.
2986 */
2987
2988 /* all nulls? then not distinct */
2989 if (all_null_input)
2990 return makeBoolConst(false, false);
2991
2992 /* one null? then distinct */
2993 if (has_null_input)
2994 return makeBoolConst(true, false);
2995
2996 /* otherwise try to evaluate the '=' operator */
2997 /* (NOT okay to try to inline it, though!) */
2998
2999 /*
3000 * Need to get OID of underlying function. Okay to
3001 * scribble on input to this extent.
3002 */
3003 set_opfuncid((OpExpr *) expr); /* rely on struct
3004 * equivalence */
3005
3006 /*
3007 * Code for op/func reduction is pretty bulky, so split it
3008 * out as a separate function.
3009 */
3010 simple = simplify_function(expr->opfuncid,
3011 expr->opresulttype, -1,
3012 expr->opcollid,
3013 expr->inputcollid,
3014 &args,
3015 false,
3016 false,
3017 false,
3018 context);
3019 if (simple) /* successfully simplified it */
3020 {
3021 /*
3022 * Since the underlying operator is "=", must negate
3023 * its result
3024 */
3025 Const *csimple = castNode(Const, simple);
3026
3027 csimple->constvalue =
3028 BoolGetDatum(!DatumGetBool(csimple->constvalue));
3029 return (Node *) csimple;
3030 }
3031 }
3032 else if (!has_nullable_nonconst)
3033 {
3034 /*
3035 * There are non-constant inputs, but since all of them
3036 * are proven non-nullable, "IS DISTINCT FROM" semantics
3037 * are much simpler.
3038 */
3039
3040 OpExpr *eqexpr;
3041
3042 /*
3043 * If one input is an explicit NULL constant, and the
3044 * other is a non-nullable expression, the result is
3045 * always TRUE.
3046 */
3047 if (has_null_input)
3048 return makeBoolConst(true, false);
3049
3050 /*
3051 * Otherwise, both inputs are known non-nullable. In this
3052 * case, "IS DISTINCT FROM" is equivalent to the standard
3053 * inequality operator (usually "<>"). We convert this to
3054 * an OpExpr, which is a more efficient representation for
3055 * the planner. It can enable the use of partial indexes
3056 * and constraint exclusion. Furthermore, if the clause
3057 * is negated (ie, "IS NOT DISTINCT FROM"), the resulting
3058 * "=" operator can allow the planner to use index scans,
3059 * merge joins, hash joins, and EC-based qual deductions.
3060 */
3062 eqexpr->opno = expr->opno;
3063 eqexpr->opfuncid = expr->opfuncid;
3064 eqexpr->opresulttype = BOOLOID;
3065 eqexpr->opretset = expr->opretset;
3066 eqexpr->opcollid = expr->opcollid;
3067 eqexpr->inputcollid = expr->inputcollid;
3068 eqexpr->args = args;
3069 eqexpr->location = expr->location;
3070
3072 context);
3073 }
3074 else if (has_null_input)
3075 {
3076 /*
3077 * One input is a nullable non-constant expression, and
3078 * the other is an explicit NULL constant. We can
3079 * transform this to a NullTest with !argisrow, which is
3080 * much more amenable to optimization.
3081 */
3082
3084
3085 nt->arg = (Expr *) (IsA(linitial(args), Const) ?
3086 lsecond(args) : linitial(args));
3087 nt->nulltesttype = IS_NOT_NULL;
3088
3089 /*
3090 * argisrow = false is correct whether or not arg is
3091 * composite
3092 */
3093 nt->argisrow = false;
3094 nt->location = expr->location;
3095
3096 return eval_const_expressions_mutator((Node *) nt, context);
3097 }
3098
3099 /*
3100 * The expression cannot be simplified any further, so build
3101 * and return a replacement DistinctExpr node using the
3102 * possibly-simplified arguments.
3103 */
3105 newexpr->opno = expr->opno;
3106 newexpr->opfuncid = expr->opfuncid;
3107 newexpr->opresulttype = expr->opresulttype;
3108 newexpr->opretset = expr->opretset;
3109 newexpr->opcollid = expr->opcollid;
3110 newexpr->inputcollid = expr->inputcollid;
3111 newexpr->args = args;
3112 newexpr->location = expr->location;
3113 return (Node *) newexpr;
3114 }
3115 case T_NullIfExpr:
3116 {
3117 NullIfExpr *expr;
3118 ListCell *arg;
3119 bool has_nonconst_input = false;
3120
3121 /* Copy the node and const-simplify its arguments */
3122 expr = (NullIfExpr *) ece_generic_processing(node);
3123
3124 /* If either argument is NULL they can't be equal */
3125 foreach(arg, expr->args)
3126 {
3127 if (!IsA(lfirst(arg), Const))
3128 has_nonconst_input = true;
3129 else if (((Const *) lfirst(arg))->constisnull)
3130 return (Node *) linitial(expr->args);
3131 }
3132
3133 /*
3134 * Need to get OID of underlying function before checking if
3135 * the function is OK to evaluate.
3136 */
3137 set_opfuncid((OpExpr *) expr);
3138
3139 if (!has_nonconst_input &&
3140 ece_function_is_safe(expr->opfuncid, context))
3141 return ece_evaluate_expr(expr);
3142
3143 return (Node *) expr;
3144 }
3146 {
3147 ScalarArrayOpExpr *saop;
3148
3149 /* Copy the node and const-simplify its arguments */
3151
3152 /* Make sure we know underlying function */
3153 set_sa_opfuncid(saop);
3154
3155 /*
3156 * If all arguments are Consts, and it's a safe function, we
3157 * can fold to a constant
3158 */
3159 if (ece_all_arguments_const(saop) &&
3160 ece_function_is_safe(saop->opfuncid, context))
3161 return ece_evaluate_expr(saop);
3162 return (Node *) saop;
3163 }
3164 case T_BoolExpr:
3165 {
3166 BoolExpr *expr = (BoolExpr *) node;
3167
3168 switch (expr->boolop)
3169 {
3170 case OR_EXPR:
3171 {
3172 List *newargs;
3173 bool haveNull = false;
3174 bool forceTrue = false;
3175
3177 context,
3178 &haveNull,
3179 &forceTrue);
3180 if (forceTrue)
3181 return makeBoolConst(true, false);
3182 if (haveNull)
3184 makeBoolConst(false, true));
3185 /* If all the inputs are FALSE, result is FALSE */
3186 if (newargs == NIL)
3187 return makeBoolConst(false, false);
3188
3189 /*
3190 * If only one nonconst-or-NULL input, it's the
3191 * result
3192 */
3193 if (list_length(newargs) == 1)
3194 return (Node *) linitial(newargs);
3195 /* Else we still need an OR node */
3196 return (Node *) make_orclause(newargs);
3197 }
3198 case AND_EXPR:
3199 {
3200 List *newargs;
3201 bool haveNull = false;
3202 bool forceFalse = false;
3203
3205 context,
3206 &haveNull,
3207 &forceFalse);
3208 if (forceFalse)
3209 return makeBoolConst(false, false);
3210 if (haveNull)
3212 makeBoolConst(false, true));
3213 /* If all the inputs are TRUE, result is TRUE */
3214 if (newargs == NIL)
3215 return makeBoolConst(true, false);
3216
3217 /*
3218 * If only one nonconst-or-NULL input, it's the
3219 * result
3220 */
3221 if (list_length(newargs) == 1)
3222 return (Node *) linitial(newargs);
3223 /* Else we still need an AND node */
3224 return (Node *) make_andclause(newargs);
3225 }
3226 case NOT_EXPR:
3227 {
3228 Node *arg;
3229
3230 Assert(list_length(expr->args) == 1);
3232 context);
3233
3234 /*
3235 * Use negate_clause() to see if we can simplify
3236 * away the NOT.
3237 */
3238 return negate_clause(arg);
3239 }
3240 default:
3241 elog(ERROR, "unrecognized boolop: %d",
3242 (int) expr->boolop);
3243 break;
3244 }
3245 break;
3246 }
3247 case T_JsonValueExpr:
3248 {
3249 JsonValueExpr *jve = (JsonValueExpr *) node;
3250 Node *raw_expr = (Node *) jve->raw_expr;
3251 Node *formatted_expr = (Node *) jve->formatted_expr;
3252
3253 /*
3254 * If we can fold formatted_expr to a constant, we can elide
3255 * the JsonValueExpr altogether. Otherwise we must process
3256 * raw_expr too. But JsonFormat is a flat node and requires
3257 * no simplification, only copying.
3258 */
3259 formatted_expr = eval_const_expressions_mutator(formatted_expr,
3260 context);
3261 if (formatted_expr && IsA(formatted_expr, Const))
3262 return formatted_expr;
3263
3264 raw_expr = eval_const_expressions_mutator(raw_expr, context);
3265
3266 return (Node *) makeJsonValueExpr((Expr *) raw_expr,
3267 (Expr *) formatted_expr,
3268 copyObject(jve->format));
3269 }
3271 {
3273
3274 /*
3275 * JSCTOR_JSON_ARRAY_QUERY carries a pre-built executable form
3276 * in its func field (a COALESCE-wrapped JSON_ARRAYAGG
3277 * subquery, constructed during parse analysis). Replace the
3278 * node with that expression and continue simplifying.
3279 */
3280 if (jce->type == JSCTOR_JSON_ARRAY_QUERY)
3281 return eval_const_expressions_mutator((Node *) jce->func,
3282 context);
3283 }
3284 break;
3285 case T_SubPlan:
3287
3288 /*
3289 * Return a SubPlan unchanged --- too late to do anything with it.
3290 *
3291 * XXX should we ereport() here instead? Probably this routine
3292 * should never be invoked after SubPlan creation.
3293 */
3294 return node;
3295 case T_RelabelType:
3296 {
3297 RelabelType *relabel = (RelabelType *) node;
3298 Node *arg;
3299
3300 /* Simplify the input ... */
3302 context);
3303 /* ... and attach a new RelabelType node, if needed */
3304 return applyRelabelType(arg,
3305 relabel->resulttype,
3306 relabel->resulttypmod,
3307 relabel->resultcollid,
3308 relabel->relabelformat,
3309 relabel->location,
3310 true);
3311 }
3312 case T_CoerceViaIO:
3313 {
3314 CoerceViaIO *expr = (CoerceViaIO *) node;
3315 List *args;
3316 Oid outfunc;
3317 bool outtypisvarlena;
3318 Oid infunc;
3320 Expr *simple;
3322
3323 /* Make a List so we can use simplify_function */
3324 args = list_make1(expr->arg);
3325
3326 /*
3327 * CoerceViaIO represents calling the source type's output
3328 * function then the result type's input function. So, try to
3329 * simplify it as though it were a stack of two such function
3330 * calls. First we need to know what the functions are.
3331 *
3332 * Note that the coercion functions are assumed not to care
3333 * about input collation, so we just pass InvalidOid for that.
3334 */
3338 &infunc, &intypioparam);
3339
3340 simple = simplify_function(outfunc,
3341 CSTRINGOID, -1,
3342 InvalidOid,
3343 InvalidOid,
3344 &args,
3345 false,
3346 true,
3347 true,
3348 context);
3349 if (simple) /* successfully simplified output fn */
3350 {
3351 /*
3352 * Input functions may want 1 to 3 arguments. We always
3353 * supply all three, trusting that nothing downstream will
3354 * complain.
3355 */
3356 args = list_make3(simple,
3358 -1,
3359 InvalidOid,
3360 sizeof(Oid),
3362 false,
3363 true),
3365 -1,
3366 InvalidOid,
3367 sizeof(int32),
3368 Int32GetDatum(-1),
3369 false,
3370 true));
3371
3372 simple = simplify_function(infunc,
3373 expr->resulttype, -1,
3374 expr->resultcollid,
3375 InvalidOid,
3376 &args,
3377 false,
3378 false,
3379 true,
3380 context);
3381 if (simple) /* successfully simplified input fn */
3382 return (Node *) simple;
3383 }
3384
3385 /*
3386 * The expression cannot be simplified any further, so build
3387 * and return a replacement CoerceViaIO node using the
3388 * possibly-simplified argument.
3389 */
3391 newexpr->arg = (Expr *) linitial(args);
3392 newexpr->resulttype = expr->resulttype;
3393 newexpr->resultcollid = expr->resultcollid;
3394 newexpr->coerceformat = expr->coerceformat;
3395 newexpr->location = expr->location;
3396 return (Node *) newexpr;
3397 }
3398 case T_ArrayCoerceExpr:
3399 {
3402
3403 /*
3404 * Copy the node and const-simplify its arguments. We can't
3405 * use ece_generic_processing() here because we need to mess
3406 * with case_val only while processing the elemexpr.
3407 */
3408 memcpy(ac, node, sizeof(ArrayCoerceExpr));
3409 ac->arg = (Expr *)
3411 context);
3412
3413 /*
3414 * Set up for the CaseTestExpr node contained in the elemexpr.
3415 * We must prevent it from absorbing any outer CASE value.
3416 */
3417 save_case_val = context->case_val;
3418 context->case_val = NULL;
3419
3420 ac->elemexpr = (Expr *)
3422 context);
3423
3424 context->case_val = save_case_val;
3425
3426 /*
3427 * If constant argument and the per-element expression is
3428 * immutable, we can simplify the whole thing to a constant.
3429 * Exception: although contain_mutable_functions considers
3430 * CoerceToDomain immutable for historical reasons, let's not
3431 * do so here; this ensures coercion to an array-over-domain
3432 * does not apply the domain's constraints until runtime.
3433 */
3434 if (ac->arg && IsA(ac->arg, Const) &&
3435 ac->elemexpr && !IsA(ac->elemexpr, CoerceToDomain) &&
3436 !contain_mutable_functions((Node *) ac->elemexpr))
3437 return ece_evaluate_expr(ac);
3438
3439 return (Node *) ac;
3440 }
3441 case T_CollateExpr:
3442 {
3443 /*
3444 * We replace CollateExpr with RelabelType, so as to improve
3445 * uniformity of expression representation and thus simplify
3446 * comparison of expressions. Hence this looks very nearly
3447 * the same as the RelabelType case, and we can apply the same
3448 * optimizations to avoid unnecessary RelabelTypes.
3449 */
3450 CollateExpr *collate = (CollateExpr *) node;
3451 Node *arg;
3452
3453 /* Simplify the input ... */
3455 context);
3456 /* ... and attach a new RelabelType node, if needed */
3457 return applyRelabelType(arg,
3458 exprType(arg),
3459 exprTypmod(arg),
3460 collate->collOid,
3462 collate->location,
3463 true);
3464 }
3465 case T_CaseExpr:
3466 {
3467 /*----------
3468 * CASE expressions can be simplified if there are constant
3469 * condition clauses:
3470 * FALSE (or NULL): drop the alternative
3471 * TRUE: drop all remaining alternatives
3472 * If the first non-FALSE alternative is a constant TRUE,
3473 * we can simplify the entire CASE to that alternative's
3474 * expression. If there are no non-FALSE alternatives,
3475 * we simplify the entire CASE to the default result (ELSE).
3476 *
3477 * If we have a simple-form CASE with constant test
3478 * expression, we substitute the constant value for contained
3479 * CaseTestExpr placeholder nodes, so that we have the
3480 * opportunity to reduce constant test conditions. For
3481 * example this allows
3482 * CASE 0 WHEN 0 THEN 1 ELSE 1/0 END
3483 * to reduce to 1 rather than drawing a divide-by-0 error.
3484 * Note that when the test expression is constant, we don't
3485 * have to include it in the resulting CASE; for example
3486 * CASE 0 WHEN x THEN y ELSE z END
3487 * is transformed by the parser to
3488 * CASE 0 WHEN CaseTestExpr = x THEN y ELSE z END
3489 * which we can simplify to
3490 * CASE WHEN 0 = x THEN y ELSE z END
3491 * It is not necessary for the executor to evaluate the "arg"
3492 * expression when executing the CASE, since any contained
3493 * CaseTestExprs that might have referred to it will have been
3494 * replaced by the constant.
3495 *----------
3496 */
3497 CaseExpr *caseexpr = (CaseExpr *) node;
3500 Node *newarg;
3501 List *newargs;
3502 bool const_true_cond;
3503 Node *defresult = NULL;
3504 ListCell *arg;
3505
3506 /* Simplify the test expression, if any */
3508 context);
3509
3510 /* Set up for contained CaseTestExpr nodes */
3511 save_case_val = context->case_val;
3512 if (newarg && IsA(newarg, Const))
3513 {
3514 context->case_val = newarg;
3515 newarg = NULL; /* not needed anymore, see above */
3516 }
3517 else
3518 context->case_val = NULL;
3519
3520 /* Simplify the WHEN clauses */
3521 newargs = NIL;
3522 const_true_cond = false;
3523 foreach(arg, caseexpr->args)
3524 {
3526 Node *casecond;
3528
3529 /* Simplify this alternative's test condition */
3531 context);
3532
3533 /*
3534 * If the test condition is constant FALSE (or NULL), then
3535 * drop this WHEN clause completely, without processing
3536 * the result.
3537 */
3538 if (casecond && IsA(casecond, Const))
3539 {
3541
3542 if (const_input->constisnull ||
3543 !DatumGetBool(const_input->constvalue))
3544 continue; /* drop alternative with FALSE cond */
3545 /* Else it's constant TRUE */
3546 const_true_cond = true;
3547 }
3548
3549 /* Simplify this alternative's result value */
3551 context);
3552
3553 /* If non-constant test condition, emit a new WHEN node */
3554 if (!const_true_cond)
3555 {
3557
3558 newcasewhen->expr = (Expr *) casecond;
3559 newcasewhen->result = (Expr *) caseresult;
3560 newcasewhen->location = oldcasewhen->location;
3562 continue;
3563 }
3564
3565 /*
3566 * Found a TRUE condition, so none of the remaining
3567 * alternatives can be reached. We treat the result as
3568 * the default result.
3569 */
3570 defresult = caseresult;
3571 break;
3572 }
3573
3574 /* Simplify the default result, unless we replaced it above */
3575 if (!const_true_cond)
3576 defresult = eval_const_expressions_mutator((Node *) caseexpr->defresult,
3577 context);
3578
3579 context->case_val = save_case_val;
3580
3581 /*
3582 * If no non-FALSE alternatives, CASE reduces to the default
3583 * result
3584 */
3585 if (newargs == NIL)
3586 return defresult;
3587 /* Otherwise we need a new CASE node */
3589 newcase->casetype = caseexpr->casetype;
3590 newcase->casecollid = caseexpr->casecollid;
3591 newcase->arg = (Expr *) newarg;
3592 newcase->args = newargs;
3593 newcase->defresult = (Expr *) defresult;
3594 newcase->location = caseexpr->location;
3595 return (Node *) newcase;
3596 }
3597 case T_CaseTestExpr:
3598 {
3599 /*
3600 * If we know a constant test value for the current CASE
3601 * construct, substitute it for the placeholder. Else just
3602 * return the placeholder as-is.
3603 */
3604 if (context->case_val)
3605 return copyObject(context->case_val);
3606 else
3607 return copyObject(node);
3608 }
3609 case T_SubscriptingRef:
3610 case T_ArrayExpr:
3611 case T_RowExpr:
3612 case T_MinMaxExpr:
3613 {
3614 /*
3615 * Generic handling for node types whose own processing is
3616 * known to be immutable, and for which we need no smarts
3617 * beyond "simplify if all inputs are constants".
3618 *
3619 * Treating SubscriptingRef this way assumes that subscripting
3620 * fetch and assignment are both immutable. This constrains
3621 * type-specific subscripting implementations; maybe we should
3622 * relax it someday.
3623 *
3624 * Treating MinMaxExpr this way amounts to assuming that the
3625 * btree comparison function it calls is immutable; see the
3626 * reasoning in contain_mutable_functions_walker.
3627 */
3628
3629 /* Copy the node and const-simplify its arguments */
3630 node = ece_generic_processing(node);
3631 /* If all arguments are Consts, we can fold to a constant */
3632 if (ece_all_arguments_const(node))
3633 return ece_evaluate_expr(node);
3634 return node;
3635 }
3636 case T_CoalesceExpr:
3637 {
3640 List *newargs;
3641 ListCell *arg;
3642
3643 newargs = NIL;
3644 foreach(arg, coalesceexpr->args)
3645 {
3646 Node *e;
3647
3649 context);
3650
3651 /*
3652 * We can remove null constants from the list. For a
3653 * nonnullable expression, if it has not been preceded by
3654 * any non-null-constant expressions then it is the
3655 * result. Otherwise, it's the next argument, but we can
3656 * drop following arguments since they will never be
3657 * reached.
3658 */
3659 if (IsA(e, Const))
3660 {
3661 if (((Const *) e)->constisnull)
3662 continue; /* drop null constant */
3663 if (newargs == NIL)
3664 return e; /* first expr */
3666 break;
3667 }
3668 if (expr_is_nonnullable(context->root, (Expr *) e,
3670 {
3671 if (newargs == NIL)
3672 return e; /* first expr */
3674 break;
3675 }
3676
3678 }
3679
3680 /*
3681 * If all the arguments were constant null, the result is just
3682 * null
3683 */
3684 if (newargs == NIL)
3685 return (Node *) makeNullConst(coalesceexpr->coalescetype,
3686 -1,
3687 coalesceexpr->coalescecollid);
3688
3689 /*
3690 * If there's exactly one surviving argument, we no longer
3691 * need COALESCE at all: the result is that argument
3692 */
3693 if (list_length(newargs) == 1)
3694 return (Node *) linitial(newargs);
3695
3697 newcoalesce->coalescetype = coalesceexpr->coalescetype;
3698 newcoalesce->coalescecollid = coalesceexpr->coalescecollid;
3699 newcoalesce->args = newargs;
3700 newcoalesce->location = coalesceexpr->location;
3701 return (Node *) newcoalesce;
3702 }
3703 case T_SQLValueFunction:
3704 {
3705 /*
3706 * All variants of SQLValueFunction are stable, so if we are
3707 * estimating the expression's value, we should evaluate the
3708 * current function value. Otherwise just copy.
3709 */
3710 SQLValueFunction *svf = (SQLValueFunction *) node;
3711
3712 if (context->estimate)
3713 return (Node *) evaluate_expr((Expr *) svf,
3714 svf->type,
3715 svf->typmod,
3716 InvalidOid);
3717 else
3718 return copyObject((Node *) svf);
3719 }
3720 case T_FieldSelect:
3721 {
3722 /*
3723 * We can optimize field selection from a whole-row Var into a
3724 * simple Var. (This case won't be generated directly by the
3725 * parser, because ParseComplexProjection short-circuits it.
3726 * But it can arise while simplifying functions.) Also, we
3727 * can optimize field selection from a RowExpr construct, or
3728 * of course from a constant.
3729 *
3730 * However, replacing a whole-row Var in this way has a
3731 * pitfall: if we've already built the rel targetlist for the
3732 * source relation, then the whole-row Var is scheduled to be
3733 * produced by the relation scan, but the simple Var probably
3734 * isn't, which will lead to a failure in setrefs.c. This is
3735 * not a problem when handling simple single-level queries, in
3736 * which expression simplification always happens first. It
3737 * is a risk for lateral references from subqueries, though.
3738 * To avoid such failures, don't optimize uplevel references.
3739 *
3740 * We must also check that the declared type of the field is
3741 * still the same as when the FieldSelect was created --- this
3742 * can change if someone did ALTER COLUMN TYPE on the rowtype.
3743 * If it isn't, we skip the optimization; the case will
3744 * probably fail at runtime, but that's not our problem here.
3745 */
3746 FieldSelect *fselect = (FieldSelect *) node;
3748 Node *arg;
3749
3751 context);
3752 if (arg && IsA(arg, Var) &&
3753 ((Var *) arg)->varattno == InvalidAttrNumber &&
3754 ((Var *) arg)->varlevelsup == 0)
3755 {
3756 if (rowtype_field_matches(((Var *) arg)->vartype,
3757 fselect->fieldnum,
3758 fselect->resulttype,
3759 fselect->resulttypmod,
3760 fselect->resultcollid))
3761 {
3762 Var *newvar;
3763
3764 newvar = makeVar(((Var *) arg)->varno,
3765 fselect->fieldnum,
3766 fselect->resulttype,
3767 fselect->resulttypmod,
3768 fselect->resultcollid,
3769 ((Var *) arg)->varlevelsup);
3770 /* New Var has same OLD/NEW returning as old one */
3771 newvar->varreturningtype = ((Var *) arg)->varreturningtype;
3772 /* New Var is nullable by same rels as the old one */
3773 newvar->varnullingrels = ((Var *) arg)->varnullingrels;
3774 return (Node *) newvar;
3775 }
3776 }
3777 if (arg && IsA(arg, RowExpr))
3778 {
3779 RowExpr *rowexpr = (RowExpr *) arg;
3780
3781 if (fselect->fieldnum > 0 &&
3782 fselect->fieldnum <= list_length(rowexpr->args))
3783 {
3784 Node *fld = (Node *) list_nth(rowexpr->args,
3785 fselect->fieldnum - 1);
3786
3787 if (rowtype_field_matches(rowexpr->row_typeid,
3788 fselect->fieldnum,
3789 fselect->resulttype,
3790 fselect->resulttypmod,
3791 fselect->resultcollid) &&
3792 fselect->resulttype == exprType(fld) &&
3793 fselect->resulttypmod == exprTypmod(fld) &&
3794 fselect->resultcollid == exprCollation(fld))
3795 return fld;
3796 }
3797 }
3799 newfselect->arg = (Expr *) arg;
3800 newfselect->fieldnum = fselect->fieldnum;
3801 newfselect->resulttype = fselect->resulttype;
3802 newfselect->resulttypmod = fselect->resulttypmod;
3803 newfselect->resultcollid = fselect->resultcollid;
3804 if (arg && IsA(arg, Const))
3805 {
3806 Const *con = (Const *) arg;
3807
3809 newfselect->fieldnum,
3810 newfselect->resulttype,
3811 newfselect->resulttypmod,
3812 newfselect->resultcollid))
3814 }
3815 return (Node *) newfselect;
3816 }
3817 case T_NullTest:
3818 {
3819 NullTest *ntest = (NullTest *) node;
3821 Node *arg;
3822
3824 context);
3825 if (ntest->argisrow && arg && IsA(arg, RowExpr))
3826 {
3827 /*
3828 * We break ROW(...) IS [NOT] NULL into separate tests on
3829 * its component fields. This form is usually more
3830 * efficient to evaluate, as well as being more amenable
3831 * to optimization.
3832 */
3833 RowExpr *rarg = (RowExpr *) arg;
3834 List *newargs = NIL;
3835 ListCell *l;
3836
3837 foreach(l, rarg->args)
3838 {
3839 Node *relem = (Node *) lfirst(l);
3840
3841 /*
3842 * A constant field refutes the whole NullTest if it's
3843 * of the wrong nullness; else we can discard it.
3844 */
3845 if (relem && IsA(relem, Const))
3846 {
3847 Const *carg = (Const *) relem;
3848
3849 if (carg->constisnull ?
3850 (ntest->nulltesttype == IS_NOT_NULL) :
3851 (ntest->nulltesttype == IS_NULL))
3852 return makeBoolConst(false, false);
3853 continue;
3854 }
3855
3856 /*
3857 * A proven non-nullable field refutes the whole
3858 * NullTest if the test is IS NULL; else we can
3859 * discard it.
3860 */
3861 if (relem &&
3862 expr_is_nonnullable(context->root, (Expr *) relem,
3864 {
3865 if (ntest->nulltesttype == IS_NULL)
3866 return makeBoolConst(false, false);
3867 continue;
3868 }
3869
3870 /*
3871 * Else, make a scalar (argisrow == false) NullTest
3872 * for this field. Scalar semantics are required
3873 * because IS [NOT] NULL doesn't recurse; see comments
3874 * in ExecEvalRowNullInt().
3875 */
3877 newntest->arg = (Expr *) relem;
3878 newntest->nulltesttype = ntest->nulltesttype;
3879 newntest->argisrow = false;
3880 newntest->location = ntest->location;
3882 }
3883 /* If all the inputs were constants, result is TRUE */
3884 if (newargs == NIL)
3885 return makeBoolConst(true, false);
3886 /* If only one nonconst input, it's the result */
3887 if (list_length(newargs) == 1)
3888 return (Node *) linitial(newargs);
3889 /* Else we need an AND node */
3890 return (Node *) make_andclause(newargs);
3891 }
3892 if (!ntest->argisrow && arg && IsA(arg, Const))
3893 {
3894 Const *carg = (Const *) arg;
3895 bool result;
3896
3897 switch (ntest->nulltesttype)
3898 {
3899 case IS_NULL:
3900 result = carg->constisnull;
3901 break;
3902 case IS_NOT_NULL:
3903 result = !carg->constisnull;
3904 break;
3905 default:
3906 elog(ERROR, "unrecognized nulltesttype: %d",
3907 (int) ntest->nulltesttype);
3908 result = false; /* keep compiler quiet */
3909 break;
3910 }
3911
3912 return makeBoolConst(result, false);
3913 }
3914 if (!ntest->argisrow && arg &&
3915 expr_is_nonnullable(context->root, (Expr *) arg,
3917 {
3918 bool result;
3919
3920 switch (ntest->nulltesttype)
3921 {
3922 case IS_NULL:
3923 result = false;
3924 break;
3925 case IS_NOT_NULL:
3926 result = true;
3927 break;
3928 default:
3929 elog(ERROR, "unrecognized nulltesttype: %d",
3930 (int) ntest->nulltesttype);
3931 result = false; /* keep compiler quiet */
3932 break;
3933 }
3934
3935 return makeBoolConst(result, false);
3936 }
3937
3939 newntest->arg = (Expr *) arg;
3940 newntest->nulltesttype = ntest->nulltesttype;
3941 newntest->argisrow = ntest->argisrow;
3942 newntest->location = ntest->location;
3943 return (Node *) newntest;
3944 }
3945 case T_BooleanTest:
3946 {
3947 /*
3948 * This case could be folded into the generic handling used
3949 * for ArrayExpr etc. But because the simplification logic is
3950 * so trivial, applying evaluate_expr() to perform it would be
3951 * a heavy overhead. BooleanTest is probably common enough to
3952 * justify keeping this bespoke implementation.
3953 */
3954 BooleanTest *btest = (BooleanTest *) node;
3956 Node *arg;
3957
3959 context);
3960 if (arg && IsA(arg, Const))
3961 {
3962 /*
3963 * If arg is Const, simplify to constant.
3964 */
3965 Const *carg = (Const *) arg;
3966 bool result;
3967
3968 switch (btest->booltesttype)
3969 {
3970 case IS_TRUE:
3971 result = (!carg->constisnull &&
3972 DatumGetBool(carg->constvalue));
3973 break;
3974 case IS_NOT_TRUE:
3975 result = (carg->constisnull ||
3976 !DatumGetBool(carg->constvalue));
3977 break;
3978 case IS_FALSE:
3979 result = (!carg->constisnull &&
3980 !DatumGetBool(carg->constvalue));
3981 break;
3982 case IS_NOT_FALSE:
3983 result = (carg->constisnull ||
3984 DatumGetBool(carg->constvalue));
3985 break;
3986 case IS_UNKNOWN:
3987 result = carg->constisnull;
3988 break;
3989 case IS_NOT_UNKNOWN:
3990 result = !carg->constisnull;
3991 break;
3992 default:
3993 elog(ERROR, "unrecognized booltesttype: %d",
3994 (int) btest->booltesttype);
3995 result = false; /* keep compiler quiet */
3996 break;
3997 }
3998
3999 return makeBoolConst(result, false);
4000 }
4001 if (arg &&
4002 expr_is_nonnullable(context->root, (Expr *) arg,
4004 {
4005 /*
4006 * If arg is proven non-nullable, simplify to boolean
4007 * expression or constant.
4008 */
4009 switch (btest->booltesttype)
4010 {
4011 case IS_TRUE:
4012 case IS_NOT_FALSE:
4013 return arg;
4014
4015 case IS_FALSE:
4016 case IS_NOT_TRUE:
4017 return (Node *) make_notclause((Expr *) arg);
4018
4019 case IS_UNKNOWN:
4020 return makeBoolConst(false, false);
4021
4022 case IS_NOT_UNKNOWN:
4023 return makeBoolConst(true, false);
4024
4025 default:
4026 elog(ERROR, "unrecognized booltesttype: %d",
4027 (int) btest->booltesttype);
4028 break;
4029 }
4030 }
4031
4033 newbtest->arg = (Expr *) arg;
4034 newbtest->booltesttype = btest->booltesttype;
4035 newbtest->location = btest->location;
4036 return (Node *) newbtest;
4037 }
4038 case T_CoerceToDomain:
4039 {
4040 /*
4041 * If the domain currently has no constraints, we replace the
4042 * CoerceToDomain node with a simple RelabelType, which is
4043 * both far faster to execute and more amenable to later
4044 * optimization. We must then mark the plan as needing to be
4045 * rebuilt if the domain's constraints change.
4046 *
4047 * Also, in estimation mode, always replace CoerceToDomain
4048 * nodes, effectively assuming that the coercion will succeed.
4049 */
4052 Node *arg;
4053
4055 context);
4056 if (context->estimate ||
4057 !DomainHasConstraints(cdomain->resulttype, NULL))
4058 {
4059 /* Record dependency, if this isn't estimation mode */
4060 if (context->root && !context->estimate)
4062 cdomain->resulttype);
4063
4064 /* Generate RelabelType to substitute for CoerceToDomain */
4065 return applyRelabelType(arg,
4066 cdomain->resulttype,
4067 cdomain->resulttypmod,
4068 cdomain->resultcollid,
4069 cdomain->coercionformat,
4070 cdomain->location,
4071 true);
4072 }
4073
4075 newcdomain->arg = (Expr *) arg;
4076 newcdomain->resulttype = cdomain->resulttype;
4077 newcdomain->resulttypmod = cdomain->resulttypmod;
4078 newcdomain->resultcollid = cdomain->resultcollid;
4079 newcdomain->coercionformat = cdomain->coercionformat;
4080 newcdomain->location = cdomain->location;
4081 return (Node *) newcdomain;
4082 }
4083 case T_PlaceHolderVar:
4084
4085 /*
4086 * In estimation mode, just strip the PlaceHolderVar node
4087 * altogether; this amounts to estimating that the contained value
4088 * won't be forced to null by an outer join. In regular mode we
4089 * just use the default behavior (ie, simplify the expression but
4090 * leave the PlaceHolderVar node intact).
4091 */
4092 if (context->estimate)
4093 {
4094 PlaceHolderVar *phv = (PlaceHolderVar *) node;
4095
4096 return eval_const_expressions_mutator((Node *) phv->phexpr,
4097 context);
4098 }
4099 break;
4101 {
4103 Node *arg;
4105
4107 context);
4108
4110 newcre->resulttype = cre->resulttype;
4111 newcre->convertformat = cre->convertformat;
4112 newcre->location = cre->location;
4113
4114 /*
4115 * In case of a nested ConvertRowtypeExpr, we can convert the
4116 * leaf row directly to the topmost row format without any
4117 * intermediate conversions. (This works because
4118 * ConvertRowtypeExpr is used only for child->parent
4119 * conversion in inheritance trees, which works by exact match
4120 * of column name, and a column absent in an intermediate
4121 * result can't be present in the final result.)
4122 *
4123 * No need to check more than one level deep, because the
4124 * above recursion will have flattened anything else.
4125 */
4126 if (arg != NULL && IsA(arg, ConvertRowtypeExpr))
4127 {
4129
4130 arg = (Node *) argcre->arg;
4131
4132 /*
4133 * Make sure an outer implicit conversion can't hide an
4134 * inner explicit one.
4135 */
4136 if (newcre->convertformat == COERCE_IMPLICIT_CAST)
4137 newcre->convertformat = argcre->convertformat;
4138 }
4139
4140 newcre->arg = (Expr *) arg;
4141
4142 if (arg != NULL && IsA(arg, Const))
4143 return ece_evaluate_expr((Node *) newcre);
4144 return (Node *) newcre;
4145 }
4146 default:
4147 break;
4148 }
4149
4150 /*
4151 * For any node type not handled above, copy the node unchanged but
4152 * const-simplify its subexpressions. This is the correct thing for node
4153 * types whose behavior might change between planning and execution, such
4154 * as CurrentOfExpr. It's also a safe default for new node types not
4155 * known to this routine.
4156 */
4157 return ece_generic_processing(node);
4158}

References WindowFunc::aggfilter, AND_EXPR, applyRelabelType(), arg, CoerceViaIO::arg, ConvertRowtypeExpr::arg, CollateExpr::arg, WindowFunc::args, FuncExpr::args, OpExpr::args, BoolExpr::args, RowExpr::args, Assert, BoolGetDatum(), BoolExpr::boolop, eval_const_expressions_context::boundParams, eval_const_expressions_context::case_val, castNode, check_stack_depth(), COERCE_IMPLICIT_CAST, CollateExpr::collOid, Const::consttype, contain_mutable_functions(), copyObject, datumCopy(), DatumGetBool(), DomainHasConstraints(), ece_all_arguments_const, ece_evaluate_expr, ece_function_is_safe(), ece_generic_processing, elog, ERROR, eval_const_expressions_context::estimate, eval_const_expressions_mutator(), evaluate_expr(), expand_function_arguments(), expr_is_nonnullable(), exprCollation(), expression_tree_mutator, exprType(), exprTypmod(), fb(), FuncExpr::funcid, get_typlenbyval(), getTypeInputInfo(), getTypeOutputInfo(), HeapTupleIsValid, WindowFunc::ignore_nulls, Int32GetDatum(), InvalidAttrNumber, InvalidOid, IS_FALSE, IS_NOT_FALSE, IS_NOT_NULL, IS_NOT_TRUE, IS_NOT_UNKNOWN, IS_NULL, IS_TRUE, IS_UNKNOWN, IsA, JSCTOR_JSON_ARRAY_QUERY, lappend(), lfirst, lfirst_node, linitial, list_length(), list_make1, list_make3, list_nth(), Param::location, WindowFunc::location, FuncExpr::location, OpExpr::location, CoerceViaIO::location, CollateExpr::location, lsecond, make_andclause(), make_notclause(), make_orclause(), makeBoolConst(), makeConst(), makeJsonValueExpr(), makeNode, makeNullConst(), makeVar(), memcpy(), negate_clause(), NIL, nodeTag, NOT_EXPR, NOTNULL_SOURCE_HASHTABLE, ParamListInfoData::numParams, ObjectIdGetDatum(), OidIsValid, OpExpr::opno, OR_EXPR, PARAM_EXTERN, PARAM_FLAG_CONST, Param::paramcollid, ParamListInfoData::paramFetch, Param::paramid, Param::paramkind, ParamListInfoData::params, Param::paramtype, Param::paramtypmod, record_plan_type_dependency(), ReleaseSysCache(), result, CoerceViaIO::resulttype, eval_const_expressions_context::root, rowtype_field_matches(), SearchSysCache1(), set_opfuncid(), set_sa_opfuncid(), simplify_aggref(), simplify_and_arguments(), simplify_boolean_equality(), simplify_function(), simplify_or_arguments(), SQLValueFunction::typmod, WindowFunc::winfnoid, and WindowFunc::winref.

Referenced by estimate_expression_value(), eval_const_expressions(), eval_const_expressions_mutator(), inline_function(), simplify_and_arguments(), simplify_function(), and simplify_or_arguments().

◆ evaluate_expr()

Expr * evaluate_expr ( Expr expr,
Oid  result_type,
int32  result_typmod,
Oid  result_collation 
)

Definition at line 5724 of file clauses.c.

5726{
5727 EState *estate;
5728 ExprState *exprstate;
5729 MemoryContext oldcontext;
5731 bool const_is_null;
5733 bool resultTypByVal;
5734
5735 /*
5736 * To use the executor, we need an EState.
5737 */
5738 estate = CreateExecutorState();
5739
5740 /* We can use the estate's working context to avoid memory leaks. */
5741 oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
5742
5743 /* Make sure any opfuncids are filled in. */
5744 fix_opfuncids((Node *) expr);
5745
5746 /*
5747 * Prepare expr for execution. (Note: we can't use ExecPrepareExpr
5748 * because it'd result in recursively invoking eval_const_expressions.)
5749 */
5750 exprstate = ExecInitExpr(expr, NULL);
5751
5752 /*
5753 * And evaluate it.
5754 *
5755 * It is OK to use a default econtext because none of the ExecEvalExpr()
5756 * code used in this situation will use econtext. That might seem
5757 * fortuitous, but it's not so unreasonable --- a constant expression does
5758 * not depend on context, by definition, n'est ce pas?
5759 */
5761 GetPerTupleExprContext(estate),
5762 &const_is_null);
5763
5764 /* Get info needed about result datatype */
5766
5767 /* Get back to outer memory context */
5768 MemoryContextSwitchTo(oldcontext);
5769
5770 /*
5771 * Must copy result out of sub-context used by expression eval.
5772 *
5773 * Also, if it's varlena, forcibly detoast it. This protects us against
5774 * storing TOAST pointers into plans that might outlive the referenced
5775 * data. (makeConst would handle detoasting anyway, but it's worth a few
5776 * extra lines here so that we can do the copy and detoast in one step.)
5777 */
5778 if (!const_is_null)
5779 {
5780 if (resultTypLen == -1)
5782 else
5784 }
5785
5786 /* Release all the junk we just created */
5787 FreeExecutorState(estate);
5788
5789 /*
5790 * Make the constant result node.
5791 */
5792 return (Expr *) makeConst(result_type, result_typmod, result_collation,
5796}

References CreateExecutorState(), datumCopy(), EState::es_query_cxt, ExecEvalExprSwitchContext(), ExecInitExpr(), fb(), fix_opfuncids(), FreeExecutorState(), get_typlenbyval(), GetPerTupleExprContext, makeConst(), MemoryContextSwitchTo(), PG_DETOAST_DATUM_COPY, and PointerGetDatum.

Referenced by eval_const_expressions_mutator(), evaluate_function(), and transformPartitionBoundValue().

◆ evaluate_function()

static Expr * evaluate_function ( Oid  funcid,
Oid  result_type,
int32  result_typmod,
Oid  result_collid,
Oid  input_collid,
List args,
bool  funcvariadic,
HeapTuple  func_tuple,
eval_const_expressions_context context 
)
static

Definition at line 5177 of file clauses.c.

5182{
5184 bool has_nonconst_input = false;
5185 bool has_null_input = false;
5186 ListCell *arg;
5188
5189 /*
5190 * Can't simplify if it returns a set.
5191 */
5192 if (funcform->proretset)
5193 return NULL;
5194
5195 /*
5196 * Can't simplify if it returns RECORD. The immediate problem is that it
5197 * will be needing an expected tupdesc which we can't supply here.
5198 *
5199 * In the case where it has OUT parameters, we could build an expected
5200 * tupdesc from those, but there may be other gotchas lurking. In
5201 * particular, if the function were to return NULL, we would produce a
5202 * null constant with no remaining indication of which concrete record
5203 * type it is. For now, seems best to leave the function call unreduced.
5204 */
5205 if (funcform->prorettype == RECORDOID)
5206 return NULL;
5207
5208 /*
5209 * Check for constant inputs and especially constant-NULL inputs.
5210 */
5211 foreach(arg, args)
5212 {
5213 if (IsA(lfirst(arg), Const))
5215 else
5216 has_nonconst_input = true;
5217 }
5218
5219 /*
5220 * If the function is strict and has a constant-NULL input, it will never
5221 * be called at all, so we can replace the call by a NULL constant, even
5222 * if there are other inputs that aren't constant, and even if the
5223 * function is not otherwise immutable.
5224 */
5225 if (funcform->proisstrict && has_null_input)
5226 return (Expr *) makeNullConst(result_type, result_typmod,
5228
5229 /*
5230 * Otherwise, can simplify only if all inputs are constants. (For a
5231 * non-strict function, constant NULL inputs are treated the same as
5232 * constant non-NULL inputs.)
5233 */
5235 return NULL;
5236
5237 /*
5238 * Ordinarily we are only allowed to simplify immutable functions. But for
5239 * purposes of estimation, we consider it okay to simplify functions that
5240 * are merely stable; the risk that the result might change from planning
5241 * time to execution time is worth taking in preference to not being able
5242 * to estimate the value at all.
5243 */
5244 if (funcform->provolatile == PROVOLATILE_IMMUTABLE)
5245 /* okay */ ;
5246 else if (context->estimate && funcform->provolatile == PROVOLATILE_STABLE)
5247 /* okay */ ;
5248 else
5249 return NULL;
5250
5251 /*
5252 * OK, looks like we can simplify this operator/function.
5253 *
5254 * Build a new FuncExpr node containing the already-simplified arguments.
5255 */
5257 newexpr->funcid = funcid;
5258 newexpr->funcresulttype = result_type;
5259 newexpr->funcretset = false;
5260 newexpr->funcvariadic = funcvariadic;
5261 newexpr->funcformat = COERCE_EXPLICIT_CALL; /* doesn't matter */
5262 newexpr->funccollid = result_collid; /* doesn't matter */
5263 newexpr->inputcollid = input_collid;
5264 newexpr->args = args;
5265 newexpr->location = -1;
5266
5267 return evaluate_expr((Expr *) newexpr, result_type, result_typmod,
5269}

References arg, COERCE_EXPLICIT_CALL, eval_const_expressions_context::estimate, evaluate_expr(), fb(), Form_pg_proc, GETSTRUCT(), IsA, lfirst, makeNode, and makeNullConst().

Referenced by simplify_function().

◆ expand_function_arguments()

List * expand_function_arguments ( List args,
bool  include_out_arguments,
Oid  result_type,
HeapTuple  func_tuple 
)

Definition at line 4927 of file clauses.c.

4929{
4931 Oid *proargtypes = funcform->proargtypes.values;
4932 int pronargs = funcform->pronargs;
4933 bool has_named_args = false;
4934 ListCell *lc;
4935
4936 /*
4937 * If we are asked to match to OUT arguments, then use the proallargtypes
4938 * array (which includes those); otherwise use proargtypes (which
4939 * doesn't). Of course, if proallargtypes is null, we always use
4940 * proargtypes. (Fetching proallargtypes is annoyingly expensive
4941 * considering that we may have nothing to do here, but fortunately the
4942 * common case is include_out_arguments == false.)
4943 */
4945 {
4947 bool isNull;
4948
4951 &isNull);
4952 if (!isNull)
4953 {
4955
4956 pronargs = ARR_DIMS(arr)[0];
4957 if (ARR_NDIM(arr) != 1 ||
4958 pronargs < 0 ||
4959 ARR_HASNULL(arr) ||
4960 ARR_ELEMTYPE(arr) != OIDOID)
4961 elog(ERROR, "proallargtypes is not a 1-D Oid array or it contains nulls");
4962 Assert(pronargs >= funcform->pronargs);
4963 proargtypes = (Oid *) ARR_DATA_PTR(arr);
4964 }
4965 }
4966
4967 /* Do we have any named arguments? */
4968 foreach(lc, args)
4969 {
4970 Node *arg = (Node *) lfirst(lc);
4971
4972 if (IsA(arg, NamedArgExpr))
4973 {
4974 has_named_args = true;
4975 break;
4976 }
4977 }
4978
4979 /* If so, we must apply reorder_function_arguments */
4980 if (has_named_args)
4981 {
4983 /* Recheck argument types and add casts if needed */
4984 recheck_cast_function_args(args, result_type,
4986 func_tuple);
4987 }
4988 else if (list_length(args) < pronargs)
4989 {
4990 /* No named args, but we seem to be short some defaults */
4992 /* Recheck argument types and add casts if needed */
4993 recheck_cast_function_args(args, result_type,
4995 func_tuple);
4996 }
4997
4998 return args;
4999}

References add_function_defaults(), arg, ARR_DATA_PTR, ARR_DIMS, ARR_ELEMTYPE, ARR_HASNULL, ARR_NDIM, Assert, DatumGetArrayTypeP, elog, ERROR, fb(), Form_pg_proc, GETSTRUCT(), IsA, lfirst, list_length(), pronargs, recheck_cast_function_args(), reorder_function_arguments(), and SysCacheGetAttr().

Referenced by eval_const_expressions_mutator(), simplify_function(), and transformCallStmt().

◆ expr_is_nonnullable()

bool expr_is_nonnullable ( PlannerInfo root,
Expr expr,
NotNullSource  source 
)

Definition at line 4785 of file clauses.c.

4786{
4787 /* since this function recurses, it could be driven to stack overflow */
4789
4790 switch (nodeTag(expr))
4791 {
4792 case T_Var:
4793 {
4794 if (root)
4795 return var_is_nonnullable(root, (Var *) expr, source);
4796 }
4797 break;
4798 case T_Const:
4799 return !((Const *) expr)->constisnull;
4800 case T_CoalesceExpr:
4801 {
4802 /*
4803 * A CoalesceExpr returns NULL if and only if all its
4804 * arguments are NULL. Therefore, we can determine that a
4805 * CoalesceExpr cannot be NULL if at least one of its
4806 * arguments can be proven non-nullable.
4807 */
4809
4811 {
4813 return true;
4814 }
4815 }
4816 break;
4817 case T_MinMaxExpr:
4818 {
4819 /*
4820 * Like CoalesceExpr, a MinMaxExpr returns NULL only if all
4821 * its arguments evaluate to NULL.
4822 */
4823 MinMaxExpr *minmaxexpr = (MinMaxExpr *) expr;
4824
4826 {
4828 return true;
4829 }
4830 }
4831 break;
4832 case T_CaseExpr:
4833 {
4834 /*
4835 * A CASE expression is non-nullable if all branch results are
4836 * non-nullable. We must also verify that the default result
4837 * (ELSE) exists and is non-nullable.
4838 */
4839 CaseExpr *caseexpr = (CaseExpr *) expr;
4840
4841 /* The default result must be present and non-nullable */
4842 if (caseexpr->defresult == NULL ||
4843 !expr_is_nonnullable(root, caseexpr->defresult, source))
4844 return false;
4845
4846 /* All branch results must be non-nullable */
4848 {
4849 if (!expr_is_nonnullable(root, casewhen->result, source))
4850 return false;
4851 }
4852
4853 return true;
4854 }
4855 break;
4856 case T_ArrayExpr:
4857 {
4858 /*
4859 * An ARRAY[] expression always returns a valid Array object,
4860 * even if it is empty (ARRAY[]) or contains NULLs
4861 * (ARRAY[NULL]). It never evaluates to a SQL NULL.
4862 */
4863 return true;
4864 }
4865 case T_NullTest:
4866 {
4867 /*
4868 * An IS NULL / IS NOT NULL expression always returns a
4869 * boolean value. It never returns SQL NULL.
4870 */
4871 return true;
4872 }
4873 case T_BooleanTest:
4874 {
4875 /*
4876 * A BooleanTest expression always evaluates to a boolean
4877 * value. It never returns SQL NULL.
4878 */
4879 return true;
4880 }
4881 case T_DistinctExpr:
4882 {
4883 /*
4884 * IS DISTINCT FROM never returns NULL, effectively acting as
4885 * though NULL were a normal data value.
4886 */
4887 return true;
4888 }
4889 case T_RelabelType:
4890 {
4891 /*
4892 * RelabelType does not change the nullability of the data.
4893 * The result is non-nullable if and only if the argument is
4894 * non-nullable.
4895 */
4896 return expr_is_nonnullable(root, ((RelabelType *) expr)->arg,
4897 source);
4898 }
4899 default:
4900 break;
4901 }
4902
4903 return false;
4904}

References arg, check_stack_depth(), expr_is_nonnullable(), fb(), foreach_ptr, nodeTag, root, source, and var_is_nonnullable().

Referenced by eval_const_expressions_mutator(), expr_is_nonnullable(), int8inc_support(), query_outputs_are_not_nullable(), restriction_is_always_false(), restriction_is_always_true(), and sublink_testexpr_is_not_nullable().

◆ expression_returns_set_rows()

double expression_returns_set_rows ( PlannerInfo root,
Node clause 
)

Definition at line 302 of file clauses.c.

303{
304 if (clause == NULL)
305 return 1.0;
306 if (IsA(clause, FuncExpr))
307 {
308 FuncExpr *expr = (FuncExpr *) clause;
309
310 if (expr->funcretset)
311 return clamp_row_est(get_function_rows(root, expr->funcid, clause));
312 }
313 if (IsA(clause, OpExpr))
314 {
315 OpExpr *expr = (OpExpr *) clause;
316
317 if (expr->opretset)
318 {
319 set_opfuncid(expr);
320 return clamp_row_est(get_function_rows(root, expr->opfuncid, clause));
321 }
322 }
323 return 1.0;
324}
double clamp_row_est(double nrows)
Definition costsize.c:214
double get_function_rows(PlannerInfo *root, Oid funcid, Node *node)
Definition plancat.c:2419

References clamp_row_est(), fb(), FuncExpr::funcid, get_function_rows(), IsA, root, and set_opfuncid().

Referenced by create_set_projection_path(), estimate_num_groups(), and set_function_size_estimates().

◆ fetch_function_defaults()

static List * fetch_function_defaults ( HeapTuple  func_tuple)
static

Definition at line 5102 of file clauses.c.

5103{
5104 List *defaults;
5106 char *str;
5107
5111 defaults = castNode(List, stringToNode(str));
5112 pfree(str);
5113 return defaults;
5114}

References castNode, fb(), pfree(), str, stringToNode(), SysCacheGetAttrNotNull(), and TextDatumGetCString.

Referenced by add_function_defaults(), and reorder_function_arguments().

◆ find_forced_null_var()

Var * find_forced_null_var ( Node node)

Definition at line 1997 of file clauses.c.

1998{
1999 if (node == NULL)
2000 return NULL;
2001 if (IsA(node, NullTest))
2002 {
2003 /* check for var IS NULL */
2004 NullTest *expr = (NullTest *) node;
2005
2006 if (expr->nulltesttype == IS_NULL && !expr->argisrow)
2007 {
2008 Var *var = (Var *) expr->arg;
2009
2010 if (var && IsA(var, Var) &&
2011 var->varlevelsup == 0)
2012 return var;
2013 }
2014 }
2015 else if (IsA(node, BooleanTest))
2016 {
2017 /* var IS UNKNOWN is equivalent to var IS NULL */
2018 BooleanTest *expr = (BooleanTest *) node;
2019
2020 if (expr->booltesttype == IS_UNKNOWN)
2021 {
2022 Var *var = (Var *) expr->arg;
2023
2024 if (var && IsA(var, Var) &&
2025 var->varlevelsup == 0)
2026 return var;
2027 }
2028 }
2029 return NULL;
2030}
BoolTestType booltesttype
Definition primnodes.h:2023
NullTestType nulltesttype
Definition primnodes.h:1999
Expr * arg
Definition primnodes.h:1998

References NullTest::arg, BooleanTest::arg, BooleanTest::booltesttype, fb(), IS_NULL, IS_UNKNOWN, IsA, NullTest::nulltesttype, and Var::varlevelsup.

Referenced by check_redundant_nullability_qual(), and find_forced_null_vars().

◆ find_forced_null_vars()

List * find_forced_null_vars ( Node node)

Definition at line 1936 of file clauses.c.

1937{
1938 List *result = NIL;
1939 Var *var;
1940 ListCell *l;
1941
1942 if (node == NULL)
1943 return NIL;
1944 /* Check single-clause cases using subroutine */
1945 var = find_forced_null_var(node);
1946 if (var)
1947 {
1949 var->varno,
1951 }
1952 /* Otherwise, handle AND-conditions */
1953 else if (IsA(node, List))
1954 {
1955 /*
1956 * At top level, we are examining an implicit-AND list: if any of the
1957 * arms produces FALSE-or-NULL then the result is FALSE-or-NULL.
1958 */
1959 foreach(l, (List *) node)
1960 {
1963 }
1964 }
1965 else if (IsA(node, BoolExpr))
1966 {
1967 BoolExpr *expr = (BoolExpr *) node;
1968
1969 /*
1970 * We don't bother considering the OR case, because it's fairly
1971 * unlikely anyone would write "v1 IS NULL OR v1 IS NULL". Likewise,
1972 * the NOT case isn't worth expending code on.
1973 */
1974 if (expr->boolop == AND_EXPR)
1975 {
1976 /* At top level we can just recurse (to the List case) */
1978 }
1979 }
1980 return result;
1981}
List * find_forced_null_vars(Node *node)
Definition clauses.c:1936
Var * find_forced_null_var(Node *node)
Definition clauses.c:1997
List * mbms_add_members(List *a, const List *b)
List * mbms_add_member(List *a, int listidx, int bitidx)
#define FirstLowInvalidHeapAttributeNumber
Definition sysattr.h:27

References AND_EXPR, BoolExpr::args, BoolExpr::boolop, fb(), find_forced_null_var(), find_forced_null_vars(), FirstLowInvalidHeapAttributeNumber, IsA, lfirst, mbms_add_member(), mbms_add_members(), NIL, result, Var::varattno, and Var::varno.

Referenced by find_forced_null_vars(), and reduce_outer_joins_pass2().

◆ find_nonnullable_rels()

Relids find_nonnullable_rels ( Node clause)

Definition at line 1476 of file clauses.c.

1477{
1478 return find_nonnullable_rels_walker(clause, true);
1479}
static Relids find_nonnullable_rels_walker(Node *node, bool top_level)
Definition clauses.c:1482

References find_nonnullable_rels_walker().

Referenced by make_outerjoininfo(), and reduce_outer_joins_pass2().

◆ find_nonnullable_rels_walker()

static Relids find_nonnullable_rels_walker ( Node node,
bool  top_level 
)
static

Definition at line 1482 of file clauses.c.

1483{
1484 Relids result = NULL;
1485 ListCell *l;
1486
1487 if (node == NULL)
1488 return NULL;
1489 if (IsA(node, Var))
1490 {
1491 Var *var = (Var *) node;
1492
1493 if (var->varlevelsup == 0)
1495 }
1496 else if (IsA(node, List))
1497 {
1498 /*
1499 * At top level, we are examining an implicit-AND list: if any of the
1500 * arms produces FALSE-or-NULL then the result is FALSE-or-NULL. If
1501 * not at top level, we are examining the arguments of a strict
1502 * function: if any of them produce NULL then the result of the
1503 * function must be NULL. So in both cases, the set of nonnullable
1504 * rels is the union of those found in the arms, and we pass down the
1505 * top_level flag unmodified.
1506 */
1507 foreach(l, (List *) node)
1508 {
1511 top_level));
1512 }
1513 }
1514 else if (IsA(node, FuncExpr))
1515 {
1516 FuncExpr *expr = (FuncExpr *) node;
1517
1518 if (func_strict(expr->funcid))
1519 result = find_nonnullable_rels_walker((Node *) expr->args, false);
1520 }
1521 else if (IsA(node, OpExpr))
1522 {
1523 OpExpr *expr = (OpExpr *) node;
1524
1525 set_opfuncid(expr);
1526 if (func_strict(expr->opfuncid))
1527 result = find_nonnullable_rels_walker((Node *) expr->args, false);
1528 }
1529 else if (IsA(node, ScalarArrayOpExpr))
1530 {
1531 ScalarArrayOpExpr *expr = (ScalarArrayOpExpr *) node;
1532
1533 if (is_strict_saop(expr, true))
1534 result = find_nonnullable_rels_walker((Node *) expr->args, false);
1535 }
1536 else if (IsA(node, BoolExpr))
1537 {
1538 BoolExpr *expr = (BoolExpr *) node;
1539
1540 switch (expr->boolop)
1541 {
1542 case AND_EXPR:
1543 /* At top level we can just recurse (to the List case) */
1544 if (top_level)
1545 {
1547 top_level);
1548 break;
1549 }
1550
1551 /*
1552 * Below top level, even if one arm produces NULL, the result
1553 * could be FALSE (hence not NULL). However, if *all* the
1554 * arms produce NULL then the result is NULL, so we can take
1555 * the intersection of the sets of nonnullable rels, just as
1556 * for OR. Fall through to share code.
1557 */
1559 case OR_EXPR:
1560
1561 /*
1562 * OR is strict if all of its arms are, so we can take the
1563 * intersection of the sets of nonnullable rels for each arm.
1564 * This works for both values of top_level.
1565 */
1566 foreach(l, expr->args)
1567 {
1569
1571 top_level);
1572 if (result == NULL) /* first subresult? */
1573 result = subresult;
1574 else
1576
1577 /*
1578 * If the intersection is empty, we can stop looking. This
1579 * also justifies the test for first-subresult above.
1580 */
1581 if (bms_is_empty(result))
1582 break;
1583 }
1584 break;
1585 case NOT_EXPR:
1586 /* NOT will return null if its arg is null */
1588 false);
1589 break;
1590 default:
1591 elog(ERROR, "unrecognized boolop: %d", (int) expr->boolop);
1592 break;
1593 }
1594 }
1595 else if (IsA(node, RelabelType))
1596 {
1597 RelabelType *expr = (RelabelType *) node;
1598
1599 result = find_nonnullable_rels_walker((Node *) expr->arg, top_level);
1600 }
1601 else if (IsA(node, CoerceViaIO))
1602 {
1603 /* not clear this is useful, but it can't hurt */
1604 CoerceViaIO *expr = (CoerceViaIO *) node;
1605
1606 result = find_nonnullable_rels_walker((Node *) expr->arg, top_level);
1607 }
1608 else if (IsA(node, ArrayCoerceExpr))
1609 {
1610 /* ArrayCoerceExpr is strict at the array level; ignore elemexpr */
1611 ArrayCoerceExpr *expr = (ArrayCoerceExpr *) node;
1612
1613 result = find_nonnullable_rels_walker((Node *) expr->arg, top_level);
1614 }
1615 else if (IsA(node, ConvertRowtypeExpr))
1616 {
1617 /* not clear this is useful, but it can't hurt */
1618 ConvertRowtypeExpr *expr = (ConvertRowtypeExpr *) node;
1619
1620 result = find_nonnullable_rels_walker((Node *) expr->arg, top_level);
1621 }
1622 else if (IsA(node, CollateExpr))
1623 {
1624 CollateExpr *expr = (CollateExpr *) node;
1625
1626 result = find_nonnullable_rels_walker((Node *) expr->arg, top_level);
1627 }
1628 else if (IsA(node, NullTest))
1629 {
1630 /* IS NOT NULL can be considered strict, but only at top level */
1631 NullTest *expr = (NullTest *) node;
1632
1633 if (top_level && expr->nulltesttype == IS_NOT_NULL && !expr->argisrow)
1634 result = find_nonnullable_rels_walker((Node *) expr->arg, false);
1635 }
1636 else if (IsA(node, BooleanTest))
1637 {
1638 /* Boolean tests that reject NULL are strict at top level */
1639 BooleanTest *expr = (BooleanTest *) node;
1640
1641 if (top_level &&
1642 (expr->booltesttype == IS_TRUE ||
1643 expr->booltesttype == IS_FALSE ||
1644 expr->booltesttype == IS_NOT_UNKNOWN))
1645 result = find_nonnullable_rels_walker((Node *) expr->arg, false);
1646 }
1647 else if (IsA(node, SubPlan))
1648 {
1649 SubPlan *splan = (SubPlan *) node;
1650
1651 /*
1652 * For some types of SubPlan, we can infer strictness from Vars in the
1653 * testexpr (the LHS of the original SubLink).
1654 *
1655 * For ANY_SUBLINK, if the subquery produces zero rows, the result is
1656 * always FALSE. If the subquery produces more than one row, the
1657 * per-row results of the testexpr are combined using OR semantics.
1658 * Hence ANY_SUBLINK can be strict only at top level, but there it's
1659 * as strict as the testexpr is.
1660 *
1661 * For ROWCOMPARE_SUBLINK, if the subquery produces zero rows, the
1662 * result is always NULL. Otherwise, the result is as strict as the
1663 * testexpr is. So we can check regardless of top_level.
1664 *
1665 * We can't prove anything for other sublink types (in particular,
1666 * note that ALL_SUBLINK will return TRUE if the subquery is empty).
1667 */
1668 if ((top_level && splan->subLinkType == ANY_SUBLINK) ||
1670 result = find_nonnullable_rels_walker(splan->testexpr, top_level);
1671 }
1672 else if (IsA(node, PlaceHolderVar))
1673 {
1674 PlaceHolderVar *phv = (PlaceHolderVar *) node;
1675
1676 /*
1677 * If the contained expression forces any rels non-nullable, so does
1678 * the PHV.
1679 */
1680 result = find_nonnullable_rels_walker((Node *) phv->phexpr, top_level);
1681
1682 /*
1683 * If the PHV's syntactic scope is exactly one rel, it will be forced
1684 * to be evaluated at that rel, and so it will behave like a Var of
1685 * that rel: if the rel's entire output goes to null, so will the PHV.
1686 * (If the syntactic scope is a join, we know that the PHV will go to
1687 * null if the whole join does; but that is AND semantics while we
1688 * need OR semantics for find_nonnullable_rels' result, so we can't do
1689 * anything with the knowledge.)
1690 */
1691 if (phv->phlevelsup == 0 &&
1692 bms_membership(phv->phrels) == BMS_SINGLETON)
1693 result = bms_add_members(result, phv->phrels);
1694 }
1695 return result;
1696}
Bitmapset * bms_make_singleton(int x)
Definition bitmapset.c:216
Bitmapset * bms_int_members(Bitmapset *a, const Bitmapset *b)
Definition bitmapset.c:1093
Bitmapset * bms_add_members(Bitmapset *a, const Bitmapset *b)
Definition bitmapset.c:901
BMS_Membership bms_membership(const Bitmapset *a)
Definition bitmapset.c:765
Bitmapset * bms_join(Bitmapset *a, Bitmapset *b)
Definition bitmapset.c:1214
@ BMS_SINGLETON
Definition bitmapset.h:72
#define pg_fallthrough
Definition c.h:161
static bool is_strict_saop(ScalarArrayOpExpr *expr, bool falseOK)
Definition clauses.c:2271
@ ANY_SUBLINK
Definition primnodes.h:1032
@ ROWCOMPARE_SUBLINK
Definition primnodes.h:1033
Node * testexpr
Definition primnodes.h:1100
SubLinkType subLinkType
Definition primnodes.h:1098

References AND_EXPR, ANY_SUBLINK, RelabelType::arg, CoerceViaIO::arg, ArrayCoerceExpr::arg, ConvertRowtypeExpr::arg, CollateExpr::arg, NullTest::arg, BooleanTest::arg, FuncExpr::args, OpExpr::args, ScalarArrayOpExpr::args, BoolExpr::args, bms_add_members(), bms_int_members(), bms_is_empty, bms_join(), bms_make_singleton(), bms_membership(), BMS_SINGLETON, BoolExpr::boolop, BooleanTest::booltesttype, elog, ERROR, fb(), find_nonnullable_rels_walker(), func_strict(), FuncExpr::funcid, IS_FALSE, IS_NOT_NULL, IS_NOT_UNKNOWN, is_strict_saop(), IS_TRUE, IsA, lfirst, NOT_EXPR, NullTest::nulltesttype, OR_EXPR, pg_fallthrough, result, ROWCOMPARE_SUBLINK, set_opfuncid(), SubPlan::subLinkType, SubPlan::testexpr, Var::varlevelsup, and Var::varno.

Referenced by find_nonnullable_rels(), and find_nonnullable_rels_walker().

◆ find_nonnullable_vars()

List * find_nonnullable_vars ( Node clause)

Definition at line 1727 of file clauses.c.

1728{
1729 return find_nonnullable_vars_walker(clause, true);
1730}
static List * find_nonnullable_vars_walker(Node *node, bool top_level)
Definition clauses.c:1733

References find_nonnullable_vars_walker().

Referenced by query_outputs_are_not_nullable(), and reduce_outer_joins_pass2().

◆ find_nonnullable_vars_walker()

static List * find_nonnullable_vars_walker ( Node node,
bool  top_level 
)
static

Definition at line 1733 of file clauses.c.

1734{
1735 List *result = NIL;
1736 ListCell *l;
1737
1738 if (node == NULL)
1739 return NIL;
1740 if (IsA(node, Var))
1741 {
1742 Var *var = (Var *) node;
1743
1744 if (var->varlevelsup == 0)
1746 var->varno,
1748 }
1749 else if (IsA(node, List))
1750 {
1751 /*
1752 * At top level, we are examining an implicit-AND list: if any of the
1753 * arms produces FALSE-or-NULL then the result is FALSE-or-NULL. If
1754 * not at top level, we are examining the arguments of a strict
1755 * function: if any of them produce NULL then the result of the
1756 * function must be NULL. So in both cases, the set of nonnullable
1757 * vars is the union of those found in the arms, and we pass down the
1758 * top_level flag unmodified.
1759 */
1760 foreach(l, (List *) node)
1761 {
1764 top_level));
1765 }
1766 }
1767 else if (IsA(node, FuncExpr))
1768 {
1769 FuncExpr *expr = (FuncExpr *) node;
1770
1771 if (func_strict(expr->funcid))
1772 result = find_nonnullable_vars_walker((Node *) expr->args, false);
1773 }
1774 else if (IsA(node, OpExpr))
1775 {
1776 OpExpr *expr = (OpExpr *) node;
1777
1778 set_opfuncid(expr);
1779 if (func_strict(expr->opfuncid))
1780 result = find_nonnullable_vars_walker((Node *) expr->args, false);
1781 }
1782 else if (IsA(node, ScalarArrayOpExpr))
1783 {
1784 ScalarArrayOpExpr *expr = (ScalarArrayOpExpr *) node;
1785
1786 if (is_strict_saop(expr, true))
1787 result = find_nonnullable_vars_walker((Node *) expr->args, false);
1788 }
1789 else if (IsA(node, BoolExpr))
1790 {
1791 BoolExpr *expr = (BoolExpr *) node;
1792
1793 switch (expr->boolop)
1794 {
1795 case AND_EXPR:
1796
1797 /*
1798 * At top level we can just recurse (to the List case), since
1799 * the result should be the union of what we can prove in each
1800 * arm.
1801 */
1802 if (top_level)
1803 {
1805 top_level);
1806 break;
1807 }
1808
1809 /*
1810 * Below top level, even if one arm produces NULL, the result
1811 * could be FALSE (hence not NULL). However, if *all* the
1812 * arms produce NULL then the result is NULL, so we can take
1813 * the intersection of the sets of nonnullable vars, just as
1814 * for OR. Fall through to share code.
1815 */
1817 case OR_EXPR:
1818
1819 /*
1820 * OR is strict if all of its arms are, so we can take the
1821 * intersection of the sets of nonnullable vars for each arm.
1822 * This works for both values of top_level.
1823 */
1824 foreach(l, expr->args)
1825 {
1826 List *subresult;
1827
1829 top_level);
1830 if (result == NIL) /* first subresult? */
1831 result = subresult;
1832 else
1834
1835 /*
1836 * If the intersection is empty, we can stop looking. This
1837 * also justifies the test for first-subresult above.
1838 */
1839 if (result == NIL)
1840 break;
1841 }
1842 break;
1843 case NOT_EXPR:
1844 /* NOT will return null if its arg is null */
1846 false);
1847 break;
1848 default:
1849 elog(ERROR, "unrecognized boolop: %d", (int) expr->boolop);
1850 break;
1851 }
1852 }
1853 else if (IsA(node, RelabelType))
1854 {
1855 RelabelType *expr = (RelabelType *) node;
1856
1857 result = find_nonnullable_vars_walker((Node *) expr->arg, top_level);
1858 }
1859 else if (IsA(node, CoerceViaIO))
1860 {
1861 /* not clear this is useful, but it can't hurt */
1862 CoerceViaIO *expr = (CoerceViaIO *) node;
1863
1864 result = find_nonnullable_vars_walker((Node *) expr->arg, false);
1865 }
1866 else if (IsA(node, ArrayCoerceExpr))
1867 {
1868 /* ArrayCoerceExpr is strict at the array level; ignore elemexpr */
1869 ArrayCoerceExpr *expr = (ArrayCoerceExpr *) node;
1870
1871 result = find_nonnullable_vars_walker((Node *) expr->arg, top_level);
1872 }
1873 else if (IsA(node, ConvertRowtypeExpr))
1874 {
1875 /* not clear this is useful, but it can't hurt */
1876 ConvertRowtypeExpr *expr = (ConvertRowtypeExpr *) node;
1877
1878 result = find_nonnullable_vars_walker((Node *) expr->arg, top_level);
1879 }
1880 else if (IsA(node, CollateExpr))
1881 {
1882 CollateExpr *expr = (CollateExpr *) node;
1883
1884 result = find_nonnullable_vars_walker((Node *) expr->arg, top_level);
1885 }
1886 else if (IsA(node, NullTest))
1887 {
1888 /* IS NOT NULL can be considered strict, but only at top level */
1889 NullTest *expr = (NullTest *) node;
1890
1891 if (top_level && expr->nulltesttype == IS_NOT_NULL && !expr->argisrow)
1892 result = find_nonnullable_vars_walker((Node *) expr->arg, false);
1893 }
1894 else if (IsA(node, BooleanTest))
1895 {
1896 /* Boolean tests that reject NULL are strict at top level */
1897 BooleanTest *expr = (BooleanTest *) node;
1898
1899 if (top_level &&
1900 (expr->booltesttype == IS_TRUE ||
1901 expr->booltesttype == IS_FALSE ||
1902 expr->booltesttype == IS_NOT_UNKNOWN))
1903 result = find_nonnullable_vars_walker((Node *) expr->arg, false);
1904 }
1905 else if (IsA(node, SubPlan))
1906 {
1907 SubPlan *splan = (SubPlan *) node;
1908
1909 /* See analysis in find_nonnullable_rels_walker */
1910 if ((top_level && splan->subLinkType == ANY_SUBLINK) ||
1912 result = find_nonnullable_vars_walker(splan->testexpr, top_level);
1913 }
1914 else if (IsA(node, PlaceHolderVar))
1915 {
1916 PlaceHolderVar *phv = (PlaceHolderVar *) node;
1917
1918 result = find_nonnullable_vars_walker((Node *) phv->phexpr, top_level);
1919 }
1920 return result;
1921}
List * mbms_int_members(List *a, const List *b)

References AND_EXPR, ANY_SUBLINK, RelabelType::arg, CoerceViaIO::arg, ArrayCoerceExpr::arg, ConvertRowtypeExpr::arg, CollateExpr::arg, NullTest::arg, BooleanTest::arg, FuncExpr::args, OpExpr::args, ScalarArrayOpExpr::args, BoolExpr::args, BoolExpr::boolop, BooleanTest::booltesttype, elog, ERROR, fb(), find_nonnullable_vars_walker(), FirstLowInvalidHeapAttributeNumber, func_strict(), FuncExpr::funcid, IS_FALSE, IS_NOT_NULL, IS_NOT_UNKNOWN, is_strict_saop(), IS_TRUE, IsA, lfirst, mbms_add_member(), mbms_add_members(), mbms_int_members(), NIL, NOT_EXPR, NullTest::nulltesttype, OR_EXPR, pg_fallthrough, result, ROWCOMPARE_SUBLINK, set_opfuncid(), SubPlan::subLinkType, SubPlan::testexpr, Var::varattno, Var::varlevelsup, and Var::varno.

Referenced by find_nonnullable_vars(), and find_nonnullable_vars_walker().

◆ find_subquery_safe_quals()

static void find_subquery_safe_quals ( Node jtnode,
List **  safe_quals 
)
static

Definition at line 2189 of file clauses.c.

2190{
2191 if (jtnode == NULL)
2192 return;
2193 if (IsA(jtnode, RangeTblRef))
2194 {
2195 /* Leaf node: nothing to do */
2196 return;
2197 }
2198 else if (IsA(jtnode, FromExpr))
2199 {
2200 FromExpr *f = (FromExpr *) jtnode;
2201
2202 /* All elements of the FROM list are allowable */
2205 /* ... and its WHERE quals are too */
2206 if (f->quals)
2207 *safe_quals = lappend(*safe_quals, f->quals);
2208 }
2209 else if (IsA(jtnode, JoinExpr))
2210 {
2211 JoinExpr *j = (JoinExpr *) jtnode;
2212
2213 switch (j->jointype)
2214 {
2215 case JOIN_INNER:
2216 /* visit both children */
2219 /* and grab the ON quals too */
2220 if (j->quals)
2221 *safe_quals = lappend(*safe_quals, j->quals);
2222 break;
2223
2224 case JOIN_LEFT:
2225 case JOIN_SEMI:
2226 case JOIN_ANTI:
2227
2228 /*
2229 * Only the left input is possibly non-nullable; furthermore,
2230 * the quals of this join don't constrain the left input.
2231 * Note: we probably can't see SEMI or ANTI joins at this
2232 * point, but if we do, we can treat them like LEFT joins.
2233 */
2235 break;
2236
2237 case JOIN_RIGHT:
2238 /* Reverse of the above case */
2240 break;
2241
2242 case JOIN_FULL:
2243 /* Neither side is non-nullable, so stop descending */
2244 break;
2245
2246 default:
2247 elog(ERROR, "unrecognized join type: %d",
2248 (int) j->jointype);
2249 break;
2250 }
2251 }
2252 else
2253 elog(ERROR, "unrecognized node type: %d",
2254 (int) nodeTag(jtnode));
2255}
static void find_subquery_safe_quals(Node *jtnode, List **safe_quals)
Definition clauses.c:2189
if(enc< 0)
int j
Definition isn.c:78
@ JOIN_SEMI
Definition nodes.h:317
@ JOIN_FULL
Definition nodes.h:305
@ JOIN_INNER
Definition nodes.h:303
@ JOIN_RIGHT
Definition nodes.h:306
@ JOIN_LEFT
Definition nodes.h:304
@ JOIN_ANTI
Definition nodes.h:318
List * fromlist
Definition primnodes.h:2396

References elog, ERROR, fb(), find_subquery_safe_quals(), foreach_ptr, FromExpr::fromlist, IsA, j, JOIN_ANTI, JOIN_FULL, JOIN_INNER, JOIN_LEFT, JOIN_RIGHT, JOIN_SEMI, lappend(), nodeTag, and FromExpr::quals.

Referenced by find_subquery_safe_quals(), and query_outputs_are_not_nullable().

◆ find_window_functions()

WindowFuncLists * find_window_functions ( Node clause,
Index  maxWinRef 
)

Definition at line 244 of file clauses.c.

245{
247
248 lists->numWindowFuncs = 0;
249 lists->maxWinRef = maxWinRef;
250 lists->windowFuncs = (List **) palloc0((maxWinRef + 1) * sizeof(List *));
252 return lists;
253}
static bool find_window_functions_walker(Node *node, WindowFuncLists *lists)
Definition clauses.c:256
#define palloc_object(type)
Definition fe_memutils.h:89

References fb(), find_window_functions_walker(), palloc0(), and palloc_object.

Referenced by grouping_planner().

◆ find_window_functions_walker()

static bool find_window_functions_walker ( Node node,
WindowFuncLists lists 
)
static

Definition at line 256 of file clauses.c.

257{
258 if (node == NULL)
259 return false;
260 if (IsA(node, WindowFunc))
261 {
262 WindowFunc *wfunc = (WindowFunc *) node;
263
264 /* winref is unsigned, so one-sided test is OK */
265 if (wfunc->winref > lists->maxWinRef)
266 elog(ERROR, "WindowFunc contains out-of-range winref %u",
267 wfunc->winref);
268
269 lists->windowFuncs[wfunc->winref] =
270 lappend(lists->windowFuncs[wfunc->winref], wfunc);
271 lists->numWindowFuncs++;
272
273 /*
274 * We assume that the parser checked that there are no window
275 * functions in the arguments or filter clause. Hence, we need not
276 * recurse into them. (If either the parser or the planner screws up
277 * on this point, the executor will still catch it; see ExecInitExpr.)
278 */
279 return false;
280 }
281 Assert(!IsA(node, SubLink));
283}

References Assert, elog, ERROR, expression_tree_walker, fb(), find_window_functions_walker(), IsA, lappend(), and WindowFunc::winref.

Referenced by find_window_functions(), and find_window_functions_walker().

◆ inline_function()

static Expr * inline_function ( Oid  funcid,
Oid  result_type,
Oid  result_collid,
Oid  input_collid,
List args,
bool  funcvariadic,
HeapTuple  func_tuple,
eval_const_expressions_context context 
)
static

Definition at line 5303 of file clauses.c.

5308{
5310 char *src;
5311 Datum tmp;
5312 bool isNull;
5315 inline_error_callback_arg callback_arg;
5317 FuncExpr *fexpr;
5319 TupleDesc rettupdesc;
5320 ParseState *pstate;
5324 Node *newexpr;
5325 int *usecounts;
5326 ListCell *arg;
5327 int i;
5328
5329 /*
5330 * Forget it if the function is not SQL-language or has other showstopper
5331 * properties. (The prokind and nargs checks are just paranoia.)
5332 */
5333 if (funcform->prolang != SQLlanguageId ||
5334 funcform->prokind != PROKIND_FUNCTION ||
5335 funcform->prosecdef ||
5336 funcform->proretset ||
5337 funcform->prorettype == RECORDOID ||
5339 funcform->pronargs != list_length(args))
5340 return NULL;
5341
5342 /* Check for recursive function, and give up trying to expand if so */
5343 if (list_member_oid(context->active_fns, funcid))
5344 return NULL;
5345
5346 /* Check permission to call function (fail later, if not) */
5348 return NULL;
5349
5350 /* Check whether a plugin wants to hook function entry/exit */
5351 if (FmgrHookIsNeeded(funcid))
5352 return NULL;
5353
5354 /*
5355 * Make a temporary memory context, so that we don't leak all the stuff
5356 * that parsing might create.
5357 */
5359 "inline_function",
5362
5363 /*
5364 * We need a dummy FuncExpr node containing the already-simplified
5365 * arguments. (In some cases we don't really need it, but building it is
5366 * cheap enough that it's not worth contortions to avoid.)
5367 */
5369 fexpr->funcid = funcid;
5370 fexpr->funcresulttype = result_type;
5371 fexpr->funcretset = false;
5372 fexpr->funcvariadic = funcvariadic;
5373 fexpr->funcformat = COERCE_EXPLICIT_CALL; /* doesn't matter */
5374 fexpr->funccollid = result_collid; /* doesn't matter */
5375 fexpr->inputcollid = input_collid;
5376 fexpr->args = args;
5377 fexpr->location = -1;
5378
5379 /* Fetch the function body */
5381 src = TextDatumGetCString(tmp);
5382
5383 /*
5384 * Setup error traceback support for ereport(). This is so that we can
5385 * finger the function that bad information came from.
5386 */
5387 callback_arg.proname = NameStr(funcform->proname);
5388 callback_arg.prosrc = src;
5389
5391 sqlerrcontext.arg = &callback_arg;
5394
5395 /* If we have prosqlbody, pay attention to that not prosrc */
5397 func_tuple,
5399 &isNull);
5400 if (!isNull)
5401 {
5402 Node *n;
5403 List *query_list;
5404
5406 if (IsA(n, List))
5407 query_list = linitial_node(List, castNode(List, n));
5408 else
5409 query_list = list_make1(n);
5410 if (list_length(query_list) != 1)
5411 goto fail;
5412 querytree = linitial(query_list);
5413
5414 /*
5415 * Because we'll insist below that the querytree have an empty rtable
5416 * and no sublinks, it cannot have any relation references that need
5417 * to be locked or rewritten. So we can omit those steps.
5418 */
5419 }
5420 else
5421 {
5422 /* Set up to handle parameters while parsing the function body. */
5424 (Node *) fexpr,
5425 input_collid);
5426
5427 /*
5428 * We just do parsing and parse analysis, not rewriting, because
5429 * rewriting will not affect table-free-SELECT-only queries, which is
5430 * all that we care about. Also, we can punt as soon as we detect
5431 * more than one command in the function body.
5432 */
5435 goto fail;
5436
5437 pstate = make_parsestate(NULL);
5438 pstate->p_sourcetext = src;
5439 sql_fn_parser_setup(pstate, pinfo);
5440
5442
5443 free_parsestate(pstate);
5444 }
5445
5446 /*
5447 * The single command must be a simple "SELECT expression".
5448 *
5449 * Note: if you change the tests involved in this, see also plpgsql's
5450 * exec_simple_check_plan(). That generally needs to have the same idea
5451 * of what's a "simple expression", so that inlining a function that
5452 * previously wasn't inlined won't change plpgsql's conclusion.
5453 */
5454 if (!IsA(querytree, Query) ||
5455 querytree->commandType != CMD_SELECT ||
5456 querytree->hasAggs ||
5457 querytree->hasWindowFuncs ||
5458 querytree->hasTargetSRFs ||
5459 querytree->hasSubLinks ||
5460 querytree->cteList ||
5461 querytree->rtable ||
5462 querytree->jointree->fromlist ||
5463 querytree->jointree->quals ||
5464 querytree->groupClause ||
5465 querytree->groupingSets ||
5466 querytree->havingQual ||
5467 querytree->windowClause ||
5468 querytree->distinctClause ||
5469 querytree->sortClause ||
5470 querytree->limitOffset ||
5471 querytree->limitCount ||
5472 querytree->setOperations ||
5473 list_length(querytree->targetList) != 1)
5474 goto fail;
5475
5476 /* If the function result is composite, resolve it */
5478 NULL,
5479 &rettupdesc);
5480
5481 /*
5482 * Make sure the function (still) returns what it's declared to. This
5483 * will raise an error if wrong, but that's okay since the function would
5484 * fail at runtime anyway. Note that check_sql_fn_retval will also insert
5485 * a coercion if needed to make the tlist expression match the declared
5486 * type of the function.
5487 *
5488 * Note: we do not try this until we have verified that no rewriting was
5489 * needed; that's probably not important, but let's be careful.
5490 */
5493 result_type, rettupdesc,
5494 funcform->prokind,
5495 false))
5496 goto fail; /* reject whole-tuple-result cases */
5497
5498 /*
5499 * Given the tests above, check_sql_fn_retval shouldn't have decided to
5500 * inject a projection step, but let's just make sure.
5501 */
5503 goto fail;
5504
5505 /* Now we can grab the tlist expression */
5506 newexpr = (Node *) ((TargetEntry *) linitial(querytree->targetList))->expr;
5507
5508 /*
5509 * If the SQL function returns VOID, we can only inline it if it is a
5510 * SELECT of an expression returning VOID (ie, it's just a redirection to
5511 * another VOID-returning function). In all non-VOID-returning cases,
5512 * check_sql_fn_retval should ensure that newexpr returns the function's
5513 * declared result type, so this test shouldn't fail otherwise; but we may
5514 * as well cope gracefully if it does.
5515 */
5516 if (exprType(newexpr) != result_type)
5517 goto fail;
5518
5519 /*
5520 * Additional validity checks on the expression. It mustn't be more
5521 * volatile than the surrounding function (this is to avoid breaking hacks
5522 * that involve pretending a function is immutable when it really ain't).
5523 * If the surrounding function is declared strict, then the expression
5524 * must contain only strict constructs and must use all of the function
5525 * parameters (this is overkill, but an exact analysis is hard).
5526 */
5527 if (funcform->provolatile == PROVOLATILE_IMMUTABLE &&
5529 goto fail;
5530 else if (funcform->provolatile == PROVOLATILE_STABLE &&
5532 goto fail;
5533
5534 if (funcform->proisstrict &&
5536 goto fail;
5537
5538 /*
5539 * If any parameter expression contains a context-dependent node, we can't
5540 * inline, for fear of putting such a node into the wrong context.
5541 */
5543 goto fail;
5544
5545 /*
5546 * We may be able to do it; there are still checks on parameter usage to
5547 * make, but those are most easily done in combination with the actual
5548 * substitution of the inputs. So start building expression with inputs
5549 * substituted.
5550 */
5551 usecounts = (int *) palloc0(funcform->pronargs * sizeof(int));
5553 args, usecounts);
5554
5555 /* Now check for parameter usage */
5556 i = 0;
5557 foreach(arg, args)
5558 {
5559 Node *param = lfirst(arg);
5560
5561 if (usecounts[i] == 0)
5562 {
5563 /* Param not used at all: uncool if func is strict */
5564 if (funcform->proisstrict)
5565 goto fail;
5566 }
5567 else if (usecounts[i] != 1)
5568 {
5569 /* Param used multiple times: uncool if expensive or volatile */
5571
5572 /*
5573 * We define "expensive" as "contains any subplan or more than 10
5574 * operators". Note that the subplan search has to be done
5575 * explicitly, since cost_qual_eval() will barf on unplanned
5576 * subselects.
5577 */
5578 if (contain_subplans(param))
5579 goto fail;
5581 if (eval_cost.startup + eval_cost.per_tuple >
5582 10 * cpu_operator_cost)
5583 goto fail;
5584
5585 /*
5586 * Check volatility last since this is more expensive than the
5587 * above tests
5588 */
5589 if (contain_volatile_functions(param))
5590 goto fail;
5591 }
5592 i++;
5593 }
5594
5595 /*
5596 * Whew --- we can make the substitution. Copy the modified expression
5597 * out of the temporary memory context, and clean up.
5598 */
5600
5602
5604
5605 /*
5606 * If the result is of a collatable type, force the result to expose the
5607 * correct collation. In most cases this does not matter, but it's
5608 * possible that the function result is used directly as a sort key or in
5609 * other places where we expect exprCollation() to tell the truth.
5610 */
5612 {
5614
5616 {
5618
5619 newnode->arg = (Expr *) newexpr;
5620 newnode->collOid = result_collid;
5621 newnode->location = -1;
5622
5623 newexpr = (Node *) newnode;
5624 }
5625 }
5626
5627 /*
5628 * Since there is now no trace of the function in the plan tree, we must
5629 * explicitly record the plan's dependency on the function.
5630 */
5631 if (context->root)
5632 record_plan_function_dependency(context->root, funcid);
5633
5634 /*
5635 * Recursively try to simplify the modified expression. Here we must add
5636 * the current function to the context list of active functions.
5637 */
5638 context->active_fns = lappend_oid(context->active_fns, funcid);
5640 context->active_fns = list_delete_last(context->active_fns);
5641
5643
5644 return (Expr *) newexpr;
5645
5646 /* Here if func is not inlinable: release temp memory and return NULL */
5647fail:
5651
5652 return NULL;
5653}

References ACL_EXECUTE, ACLCHECK_OK, eval_const_expressions_context::active_fns, ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate, arg, castNode, check_sql_fn_retval(), CMD_SELECT, COERCE_EXPLICIT_CALL, contain_context_dependent_node(), contain_mutable_functions(), contain_nonstrict_functions(), contain_subplans(), contain_volatile_functions(), copyObject, cost_qual_eval(), cpu_operator_cost, CurrentMemoryContext, error_context_stack, eval_const_expressions_mutator(), exprCollation(), exprType(), fb(), FmgrHookIsNeeded, Form_pg_proc, free_parsestate(), get_expr_result_type(), GETSTRUCT(), GetUserId(), heap_attisnull(), i, IsA, lappend_oid(), lfirst, linitial, linitial_node, list_delete_last(), list_length(), list_make1, list_member_oid(), make_parsestate(), makeNode, MemoryContextDelete(), MemoryContextSwitchTo(), NameStr, object_aclcheck(), OidIsValid, ParseState::p_sourcetext, palloc0(), pg_parse_query(), prepare_sql_fn_parse_info(), ErrorContextCallback::previous, inline_error_callback_arg::proname, inline_error_callback_arg::prosrc, querytree(), record_plan_function_dependency(), eval_const_expressions_context::root, sql_fn_parser_setup(), sql_inline_error_callback(), stringToNode(), substitute_actual_parameters(), SysCacheGetAttr(), SysCacheGetAttrNotNull(), TextDatumGetCString, and transformTopLevelStmt().

Referenced by simplify_function().

◆ inline_function_in_from()

Query * inline_function_in_from ( PlannerInfo root,
RangeTblEntry rte 
)

Definition at line 5816 of file clauses.c.

5817{
5818 RangeTblFunction *rtfunc;
5819 FuncExpr *fexpr;
5820 Oid func_oid;
5825 Datum tmp;
5826 char *src;
5827 inline_error_callback_arg callback_arg;
5829 Query *querytree = NULL;
5830
5831 Assert(rte->rtekind == RTE_FUNCTION);
5832
5833 /*
5834 * Guard against infinite recursion during expansion by checking for stack
5835 * overflow. (There's no need to do more.)
5836 */
5838
5839 /* Fail if the RTE has ORDINALITY - we don't implement that here. */
5840 if (rte->funcordinality)
5841 return NULL;
5842
5843 /* Fail if RTE isn't a single, simple FuncExpr */
5844 if (list_length(rte->functions) != 1)
5845 return NULL;
5846 rtfunc = (RangeTblFunction *) linitial(rte->functions);
5847
5848 if (!IsA(rtfunc->funcexpr, FuncExpr))
5849 return NULL;
5850 fexpr = (FuncExpr *) rtfunc->funcexpr;
5851
5852 func_oid = fexpr->funcid;
5853
5854 /*
5855 * Refuse to inline if the arguments contain any volatile functions or
5856 * sub-selects. Volatile functions are rejected because inlining may
5857 * result in the arguments being evaluated multiple times, risking a
5858 * change in behavior. Sub-selects are rejected partly for implementation
5859 * reasons (pushing them down another level might change their behavior)
5860 * and partly because they're likely to be expensive and so multiple
5861 * evaluation would be bad.
5862 */
5863 if (contain_volatile_functions((Node *) fexpr->args) ||
5864 contain_subplans((Node *) fexpr->args))
5865 return NULL;
5866
5867 /* Check permission to call function (fail later, if not) */
5869 return NULL;
5870
5871 /* Check whether a plugin wants to hook function entry/exit */
5873 return NULL;
5874
5875 /*
5876 * OK, let's take a look at the function's pg_proc entry.
5877 */
5880 elog(ERROR, "cache lookup failed for function %u", func_oid);
5882
5883 /*
5884 * If the function SETs any configuration parameters, inlining would cause
5885 * us to miss making those changes.
5886 */
5888 {
5890 return NULL;
5891 }
5892
5893 /*
5894 * Make a temporary memory context, so that we don't leak all the stuff
5895 * that parsing and rewriting might create. If we succeed, we'll copy
5896 * just the finished query tree back up to the caller's context.
5897 */
5899 "inline_function_in_from",
5902
5903 /* Fetch the function body */
5905 src = TextDatumGetCString(tmp);
5906
5907 /*
5908 * If the function has an attached support function that can handle
5909 * SupportRequestInlineInFrom, then attempt to inline with that.
5910 */
5911 if (funcform->prosupport)
5912 {
5914
5916 req.root = root;
5917 req.rtfunc = rtfunc;
5918 req.proc = func_tuple;
5919
5920 querytree = (Query *)
5922 PointerGetDatum(&req)));
5923 }
5924
5925 /*
5926 * Setup error traceback support for ereport(). This is so that we can
5927 * finger the function that bad information came from. We don't install
5928 * this while running the support function, since it'd be likely to do the
5929 * wrong thing: any parse errors reported during that are very likely not
5930 * against the raw function source text.
5931 */
5932 callback_arg.proname = NameStr(funcform->proname);
5933 callback_arg.prosrc = src;
5934
5936 sqlerrcontext.arg = &callback_arg;
5939
5940 /*
5941 * If SupportRequestInlineInFrom didn't work, try our built-in inlining
5942 * mechanism.
5943 */
5944 if (!querytree)
5946 func_tuple, funcform, src);
5947
5948 if (!querytree)
5949 goto fail; /* no luck there either, fail */
5950
5951 /*
5952 * The result had better be a SELECT Query.
5953 */
5955 Assert(querytree->commandType == CMD_SELECT);
5956
5957 /*
5958 * Looks good --- substitute parameters into the query.
5959 */
5961 funcform->pronargs,
5962 fexpr->args);
5963
5964 /*
5965 * Copy the modified query out of the temporary memory context, and clean
5966 * up.
5967 */
5969
5971
5975
5976 /*
5977 * We don't have to fix collations here because the upper query is already
5978 * parsed, ie, the collations in the RTE are what count.
5979 */
5980
5981 /*
5982 * Since there is now no trace of the function in the plan tree, we must
5983 * explicitly record the plan's dependency on the function.
5984 */
5986
5987 /*
5988 * We must also notice if the inserted query adds a dependency on the
5989 * calling role due to RLS quals.
5990 */
5991 if (querytree->hasRowSecurity)
5992 root->glob->dependsOnRole = true;
5993
5994 return querytree;
5995
5996 /* Here if func is not inlinable: release temp memory and return NULL */
5997fail:
6002
6003 return NULL;
6004}

References ACL_EXECUTE, ACLCHECK_OK, ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate, Assert, check_stack_depth(), CMD_SELECT, contain_subplans(), contain_volatile_functions(), copyObject, CurrentMemoryContext, DatumGetPointer(), elog, ERROR, error_context_stack, fb(), FmgrHookIsNeeded, Form_pg_proc, RangeTblFunction::funcexpr, GETSTRUCT(), GetUserId(), heap_attisnull(), HeapTupleIsValid, inline_sql_function_in_from(), IsA, linitial, list_length(), MemoryContextDelete(), MemoryContextSwitchTo(), NameStr, object_aclcheck(), ObjectIdGetDatum(), OidFunctionCall1, PointerGetDatum, ErrorContextCallback::previous, inline_error_callback_arg::proname, inline_error_callback_arg::prosrc, querytree(), record_plan_function_dependency(), ReleaseSysCache(), root, RTE_FUNCTION, SearchSysCache1(), sql_inline_error_callback(), substitute_actual_parameters_in_from(), SysCacheGetAttrNotNull(), TextDatumGetCString, and SupportRequestInlineInFrom::type.

Referenced by preprocess_function_rtes().

◆ inline_sql_function_in_from()

static Query * inline_sql_function_in_from ( PlannerInfo root,
RangeTblFunction rtfunc,
FuncExpr fexpr,
HeapTuple  func_tuple,
Form_pg_proc  funcform,
const char src 
)
static

Definition at line 6020 of file clauses.c.

6026{
6027 Datum sqlbody;
6028 bool isNull;
6032 TupleDesc rettupdesc;
6033
6034 /*
6035 * The function must be declared to return a set, else inlining would
6036 * change the results if the contained SELECT didn't return exactly one
6037 * row.
6038 */
6039 if (!fexpr->funcretset)
6040 return NULL;
6041
6042 /*
6043 * Forget it if the function is not SQL-language or has other showstopper
6044 * properties. In particular it mustn't be declared STRICT, since we
6045 * couldn't enforce that. It also mustn't be VOLATILE, because that is
6046 * supposed to cause it to be executed with its own snapshot, rather than
6047 * sharing the snapshot of the calling query. We also disallow returning
6048 * SETOF VOID, because inlining would result in exposing the actual result
6049 * of the function's last SELECT, which should not happen in that case.
6050 * (Rechecking prokind, proretset, and pronargs is just paranoia.)
6051 */
6052 if (funcform->prolang != SQLlanguageId ||
6053 funcform->prokind != PROKIND_FUNCTION ||
6054 funcform->proisstrict ||
6055 funcform->provolatile == PROVOLATILE_VOLATILE ||
6056 funcform->prorettype == VOIDOID ||
6057 funcform->prosecdef ||
6058 !funcform->proretset ||
6059 list_length(fexpr->args) != funcform->pronargs)
6060 return NULL;
6061
6062 /* If we have prosqlbody, pay attention to that not prosrc */
6064 func_tuple,
6066 &isNull);
6067 if (!isNull)
6068 {
6069 Node *n;
6070
6072 if (IsA(n, List))
6074 else
6076 if (list_length(querytree_list) != 1)
6077 return NULL;
6079
6080 /* Acquire necessary locks, then apply rewriter. */
6081 AcquireRewriteLocks(querytree, true, false);
6083 if (list_length(querytree_list) != 1)
6084 return NULL;
6086 }
6087 else
6088 {
6091
6092 /*
6093 * Set up to handle parameters while parsing the function body. We
6094 * can use the FuncExpr just created as the input for
6095 * prepare_sql_fn_parse_info.
6096 */
6098 (Node *) fexpr,
6099 fexpr->inputcollid);
6100
6101 /*
6102 * Parse, analyze, and rewrite (unlike inline_function(), we can't
6103 * skip rewriting here). We can fail as soon as we find more than one
6104 * query, though.
6105 */
6108 return NULL;
6109
6111 src,
6113 pinfo, NULL);
6114 if (list_length(querytree_list) != 1)
6115 return NULL;
6117 }
6118
6119 /*
6120 * Also resolve the actual function result tupdesc, if composite. If we
6121 * have a coldeflist, believe that; otherwise use get_expr_result_type.
6122 * (This logic should match ExecInitFunctionScan.)
6123 */
6124 if (rtfunc->funccolnames != NIL)
6125 {
6127 rettupdesc = BuildDescFromLists(rtfunc->funccolnames,
6128 rtfunc->funccoltypes,
6129 rtfunc->funccoltypmods,
6130 rtfunc->funccolcollations);
6131 }
6132 else
6133 functypclass = get_expr_result_type((Node *) fexpr, NULL, &rettupdesc);
6134
6135 /*
6136 * The single command must be a plain SELECT.
6137 */
6138 if (!IsA(querytree, Query) ||
6139 querytree->commandType != CMD_SELECT)
6140 return NULL;
6141
6142 /*
6143 * Make sure the function (still) returns what it's declared to. This
6144 * will raise an error if wrong, but that's okay since the function would
6145 * fail at runtime anyway. Note that check_sql_fn_retval will also insert
6146 * coercions if needed to make the tlist expression(s) match the declared
6147 * type of the function. We also ask it to insert dummy NULL columns for
6148 * any dropped columns in rettupdesc, so that the elements of the modified
6149 * tlist match up to the attribute numbers.
6150 *
6151 * If the function returns a composite type, don't inline unless the check
6152 * shows it's returning a whole tuple result; otherwise what it's
6153 * returning is a single composite column which is not what we need.
6154 */
6156 fexpr->funcresulttype, rettupdesc,
6157 funcform->prokind,
6158 true) &&
6162 return NULL; /* reject not-whole-tuple-result cases */
6163
6164 /*
6165 * check_sql_fn_retval might've inserted a projection step, but that's
6166 * fine; just make sure we use the upper Query.
6167 */
6169
6170 return querytree;
6171}

References AcquireRewriteLocks(), BuildDescFromLists(), castNode, check_sql_fn_retval(), CMD_SELECT, fb(), get_expr_result_type(), IsA, linitial, linitial_node, list_length(), list_make1, NIL, pg_analyze_and_rewrite_withcb(), pg_parse_query(), pg_rewrite_query(), prepare_sql_fn_parse_info(), querytree(), sql_fn_parser_setup(), stringToNode(), SysCacheGetAttr(), TextDatumGetCString, TYPEFUNC_COMPOSITE, TYPEFUNC_COMPOSITE_DOMAIN, and TYPEFUNC_RECORD.

Referenced by inline_function_in_from().

◆ is_parallel_safe()

bool is_parallel_safe ( PlannerInfo root,
Node node 
)

Definition at line 766 of file clauses.c.

767{
770 ListCell *l;
771
772 /*
773 * Even if the original querytree contained nothing unsafe, we need to
774 * search the expression if we have generated any PARAM_EXEC Params while
775 * planning, because those are parallel-restricted and there might be one
776 * in this expression. But otherwise we don't need to look.
777 */
778 if (root->glob->maxParallelHazard == PROPARALLEL_SAFE &&
779 root->glob->paramExecTypes == NIL)
780 return true;
781 /* Else use max_parallel_hazard's search logic, but stop on RESTRICTED */
784 context.safe_param_ids = NIL;
785
786 /*
787 * The params that refer to the same or parent query level are considered
788 * parallel-safe. The idea is that we compute such params at Gather or
789 * Gather Merge node and pass their value to workers.
790 */
791 for (proot = root; proot != NULL; proot = proot->parent_root)
792 {
793 foreach(l, proot->init_plans)
794 {
796
797 context.safe_param_ids = list_concat(context.safe_param_ids,
798 initsubplan->setParam);
799 }
800 }
801
802 return !max_parallel_hazard_walker(node, &context);
803}
static bool max_parallel_hazard_walker(Node *node, max_parallel_hazard_context *context)
Definition clauses.c:842
List * list_concat(List *list1, const List *list2)
Definition list.c:561

References fb(), lfirst, list_concat(), max_parallel_hazard_context::max_hazard, max_parallel_hazard_context::max_interesting, max_parallel_hazard_walker(), NIL, root, and max_parallel_hazard_context::safe_param_ids.

Referenced by apply_projection_to_path(), build_join_rel(), create_minmaxagg_path(), create_nestloop_plan(), create_partial_unique_paths(), create_projection_path(), create_set_projection_path(), create_window_paths(), find_computable_ec_member(), grouping_planner(), make_grouping_rel(), plan_create_index_workers(), query_planner(), relation_can_be_sorted_early(), and set_rel_consider_parallel().

◆ is_pseudo_constant_clause()

bool is_pseudo_constant_clause ( Node clause)

Definition at line 2333 of file clauses.c.

2334{
2335 /*
2336 * We could implement this check in one recursive scan. But since the
2337 * check for volatile functions is both moderately expensive and unlikely
2338 * to fail, it seems better to look for Vars first and only check for
2339 * volatile functions if we find no Vars.
2340 */
2341 if (!contain_var_clause(clause) &&
2343 return true;
2344 return false;
2345}

References contain_var_clause(), and contain_volatile_functions().

Referenced by clauselist_selectivity_ext(), dependency_is_compatible_clause(), dependency_is_compatible_expression(), and find_window_run_conditions().

◆ is_pseudo_constant_clause_relids()

bool is_pseudo_constant_clause_relids ( Node clause,
Relids  relids 
)

Definition at line 2353 of file clauses.c.

2354{
2355 if (bms_is_empty(relids) &&
2357 return true;
2358 return false;
2359}

References bms_is_empty, and contain_volatile_functions().

Referenced by clauselist_selectivity_ext().

◆ is_strict_saop()

static bool is_strict_saop ( ScalarArrayOpExpr expr,
bool  falseOK 
)
static

Definition at line 2271 of file clauses.c.

2272{
2273 Node *rightop;
2274
2275 /* The contained operator must be strict. */
2276 set_sa_opfuncid(expr);
2277 if (!func_strict(expr->opfuncid))
2278 return false;
2279 /* If ANY and falseOK, that's all we need to check. */
2280 if (expr->useOr && falseOK)
2281 return true;
2282 /* Else, we have to see if the array is provably non-empty. */
2283 Assert(list_length(expr->args) == 2);
2284 rightop = (Node *) lsecond(expr->args);
2285 if (rightop && IsA(rightop, Const))
2286 {
2287 Datum arraydatum = ((Const *) rightop)->constvalue;
2288 bool arrayisnull = ((Const *) rightop)->constisnull;
2290 int nitems;
2291
2292 if (arrayisnull)
2293 return false;
2296 if (nitems > 0)
2297 return true;
2298 }
2299 else if (rightop && IsA(rightop, ArrayExpr))
2300 {
2301 ArrayExpr *arrayexpr = (ArrayExpr *) rightop;
2302
2303 if (arrayexpr->elements != NIL && !arrayexpr->multidims)
2304 return true;
2305 }
2306 return false;
2307}

References ScalarArrayOpExpr::args, ARR_DIMS, ARR_NDIM, ArrayGetNItems(), Assert, DatumGetArrayTypeP, fb(), func_strict(), IsA, list_length(), lsecond, NIL, nitems, set_sa_opfuncid(), and ScalarArrayOpExpr::useOr.

Referenced by find_nonnullable_rels_walker(), and find_nonnullable_vars_walker().

◆ make_SAOP_expr()

ScalarArrayOpExpr * make_SAOP_expr ( Oid  oper,
Node leftexpr,
Oid  coltype,
Oid  arraycollid,
Oid  inputcollid,
List exprs,
bool  haveNonConst 
)

Definition at line 6272 of file clauses.c.

6274{
6275 Node *arrayNode = NULL;
6277 Oid arraytype = get_array_type(coltype);
6278
6279 if (!OidIsValid(arraytype))
6280 return NULL;
6281
6282 /*
6283 * Assemble an array from the list of constants. It seems more profitable
6284 * to build a const array. But in the presence of other nodes, we don't
6285 * have a specific value here and must employ an ArrayExpr instead.
6286 */
6287 if (haveNonConst)
6288 {
6290
6291 /* array_collid will be set by parse_collate.c */
6292 arrayExpr->element_typeid = coltype;
6293 arrayExpr->array_typeid = arraytype;
6294 arrayExpr->multidims = false;
6295 arrayExpr->elements = exprs;
6296 arrayExpr->location = -1;
6297
6298 arrayNode = (Node *) arrayExpr;
6299 }
6300 else
6301 {
6302 int16 typlen;
6303 bool typbyval;
6304 char typalign;
6305 Datum *elems;
6306 bool *nulls;
6307 int i = 0;
6309 int dims[1] = {list_length(exprs)};
6310 int lbs[1] = {1};
6311
6312 get_typlenbyvalalign(coltype, &typlen, &typbyval, &typalign);
6313
6314 elems = palloc_array(Datum, list_length(exprs));
6315 nulls = palloc_array(bool, list_length(exprs));
6316 foreach_node(Const, value, exprs)
6317 {
6318 elems[i] = value->constvalue;
6319 nulls[i++] = value->constisnull;
6320 }
6321
6322 arrayConst = construct_md_array(elems, nulls, 1, dims, lbs,
6323 coltype, typlen, typbyval, typalign);
6326 false, false);
6327
6328 pfree(elems);
6329 pfree(nulls);
6330 list_free(exprs);
6331 }
6332
6333 /* Build the SAOP expression node */
6335 saopexpr->opno = oper;
6336 saopexpr->opfuncid = get_opcode(oper);
6337 saopexpr->hashfuncid = InvalidOid;
6338 saopexpr->negfuncid = InvalidOid;
6339 saopexpr->useOr = true;
6340 saopexpr->inputcollid = inputcollid;
6342 saopexpr->location = -1;
6343
6344 return saopexpr;
6345}

References construct_md_array(), fb(), foreach_node, get_array_type(), get_opcode(), get_typlenbyvalalign(), i, InvalidOid, list_free(), list_length(), list_make2, makeConst(), makeNode, OidIsValid, oper(), palloc_array, pfree(), PointerGetDatum, typalign, and value.

Referenced by convert_VALUES_to_ANY(), and match_orclause_to_indexcol().

◆ max_parallel_hazard()

char max_parallel_hazard ( Query parse)

◆ max_parallel_hazard_checker()

static bool max_parallel_hazard_checker ( Oid  func_id,
void context 
)
static

Definition at line 835 of file clauses.c.

836{
838 (max_parallel_hazard_context *) context);
839}
static bool max_parallel_hazard_test(char proparallel, max_parallel_hazard_context *context)
Definition clauses.c:807
char func_parallel(Oid funcid)
Definition lsyscache.c:2030

References fb(), func_parallel(), and max_parallel_hazard_test().

Referenced by max_parallel_hazard_walker().

◆ max_parallel_hazard_test()

static bool max_parallel_hazard_test ( char  proparallel,
max_parallel_hazard_context context 
)
static

Definition at line 807 of file clauses.c.

808{
809 switch (proparallel)
810 {
811 case PROPARALLEL_SAFE:
812 /* nothing to see here, move along */
813 break;
815 /* increase max_hazard to RESTRICTED */
817 context->max_hazard = proparallel;
818 /* done if we are not expecting any unsafe functions */
819 if (context->max_interesting == proparallel)
820 return true;
821 break;
823 context->max_hazard = proparallel;
824 /* we're always done at the first unsafe construct */
825 return true;
826 default:
827 elog(ERROR, "unrecognized proparallel value \"%c\"", proparallel);
828 break;
829 }
830 return false;
831}

References Assert, elog, ERROR, fb(), max_parallel_hazard_context::max_hazard, and max_parallel_hazard_context::max_interesting.

Referenced by max_parallel_hazard_checker(), and max_parallel_hazard_walker().

◆ max_parallel_hazard_walker()

static bool max_parallel_hazard_walker ( Node node,
max_parallel_hazard_context context 
)
static

Definition at line 842 of file clauses.c.

843{
844 if (node == NULL)
845 return false;
846
847 /* Check for hazardous functions in node itself */
849 context))
850 return true;
851
852 /*
853 * It should be OK to treat MinMaxExpr as parallel-safe, since btree
854 * opclass support functions are generally parallel-safe. XmlExpr is a
855 * bit more dubious but we can probably get away with it. We err on the
856 * side of caution by treating CoerceToDomain as parallel-restricted.
857 * (Note: in principle that's wrong because a domain constraint could
858 * contain a parallel-unsafe function; but useful constraints probably
859 * never would have such, and assuming they do would cripple use of
860 * parallel query in the presence of domain types.) SQLValueFunction
861 * should be safe in all cases. NextValueExpr is parallel-unsafe.
862 */
863 if (IsA(node, CoerceToDomain))
864 {
866 return true;
867 }
868
869 else if (IsA(node, NextValueExpr))
870 {
872 return true;
873 }
874
875 /*
876 * Treat window functions as parallel-restricted because we aren't sure
877 * whether the input row ordering is fully deterministic, and the output
878 * of window functions might vary across workers if not. (In some cases,
879 * like where the window frame orders by a primary key, we could relax
880 * this restriction. But it doesn't currently seem worth expending extra
881 * effort to do so.)
882 */
883 else if (IsA(node, WindowFunc))
884 {
886 return true;
887 }
888
889 /*
890 * As a notational convenience for callers, look through RestrictInfo.
891 */
892 else if (IsA(node, RestrictInfo))
893 {
894 RestrictInfo *rinfo = (RestrictInfo *) node;
895
896 return max_parallel_hazard_walker((Node *) rinfo->clause, context);
897 }
898
899 /*
900 * Really we should not see SubLink during a max_interesting == restricted
901 * scan, but if we do, return true.
902 */
903 else if (IsA(node, SubLink))
904 {
906 return true;
907 }
908
909 /*
910 * Only parallel-safe SubPlans can be sent to workers. Within the
911 * testexpr of the SubPlan, Params representing the output columns of the
912 * subplan can be treated as parallel-safe, so temporarily add their IDs
913 * to the safe_param_ids list while examining the testexpr.
914 */
915 else if (IsA(node, SubPlan))
916 {
917 SubPlan *subplan = (SubPlan *) node;
919
920 if (!subplan->parallel_safe &&
922 return true;
925 subplan->paramIds);
926 if (max_parallel_hazard_walker(subplan->testexpr, context))
927 return true; /* no need to restore safe_param_ids */
928 list_free(context->safe_param_ids);
930 /* we must also check args, but no special Param treatment there */
931 if (max_parallel_hazard_walker((Node *) subplan->args, context))
932 return true;
933 /* don't want to recurse normally, so we're done */
934 return false;
935 }
936
937 /*
938 * We can't pass Params to workers at the moment either, so they are also
939 * parallel-restricted, unless they are PARAM_EXTERN Params or are
940 * PARAM_EXEC Params listed in safe_param_ids, meaning they could be
941 * either generated within workers or can be computed by the leader and
942 * then their value can be passed to workers.
943 */
944 else if (IsA(node, Param))
945 {
946 Param *param = (Param *) node;
947
948 if (param->paramkind == PARAM_EXTERN)
949 return false;
950
951 if (param->paramkind != PARAM_EXEC ||
952 !list_member_int(context->safe_param_ids, param->paramid))
953 {
955 return true;
956 }
957 return false; /* nothing to recurse to */
958 }
959
960 /*
961 * When we're first invoked on a completely unplanned tree, we must
962 * recurse into subqueries so to as to locate parallel-unsafe constructs
963 * anywhere in the tree.
964 */
965 else if (IsA(node, Query))
966 {
967 Query *query = (Query *) node;
968
969 /* SELECT FOR UPDATE/SHARE must be treated as unsafe */
970 if (query->rowMarks != NULL)
971 {
973 return true;
974 }
975
976 /* Recurse into subselects */
977 return query_tree_walker(query,
979 context, 0);
980 }
981
982 /* Recurse to check arguments */
983 return expression_tree_walker(node,
985 context);
986}
static bool max_parallel_hazard_checker(Oid func_id, void *context)
Definition clauses.c:835
List * rowMarks
Definition parsenodes.h:237
List * args
Definition primnodes.h:1125
List * paramIds
Definition primnodes.h:1101
bool parallel_safe
Definition primnodes.h:1118

References SubPlan::args, check_functions_in_node(), RestrictInfo::clause, expression_tree_walker, fb(), IsA, list_concat_copy(), list_free(), list_member_int(), max_parallel_hazard_context::max_hazard, max_parallel_hazard_checker(), max_parallel_hazard_test(), max_parallel_hazard_walker(), SubPlan::parallel_safe, PARAM_EXEC, PARAM_EXTERN, Param::paramid, SubPlan::paramIds, Param::paramkind, query_tree_walker, Query::rowMarks, max_parallel_hazard_context::safe_param_ids, and SubPlan::testexpr.

Referenced by is_parallel_safe(), max_parallel_hazard(), and max_parallel_hazard_walker().

◆ NumRelids()

int NumRelids ( PlannerInfo root,
Node clause 
)

Definition at line 2375 of file clauses.c.

2376{
2377 int result;
2378 Relids varnos = pull_varnos(root, clause);
2379
2380 varnos = bms_del_members(varnos, root->outer_join_rels);
2381 result = bms_num_members(varnos);
2382 bms_free(varnos);
2383 return result;
2384}
Bitmapset * bms_del_members(Bitmapset *a, const Bitmapset *b)
Definition bitmapset.c:1145
void bms_free(Bitmapset *a)
Definition bitmapset.c:239
int bms_num_members(const Bitmapset *a)
Definition bitmapset.c:744
Relids pull_varnos(PlannerInfo *root, Node *node)
Definition var.c:114

References bms_del_members(), bms_free(), bms_num_members(), pull_varnos(), result, and root.

Referenced by clauselist_selectivity_ext(), rowcomparesel(), and treat_as_join_clause().

◆ pull_paramids()

Bitmapset * pull_paramids ( Expr expr)

Definition at line 6240 of file clauses.c.

6241{
6243
6244 (void) pull_paramids_walker((Node *) expr, &result);
6245
6246 return result;
6247}

References fb(), pull_paramids_walker(), and result.

Referenced by create_memoize_plan().

◆ pull_paramids_walker()

static bool pull_paramids_walker ( Node node,
Bitmapset **  context 
)
static

Definition at line 6250 of file clauses.c.

6251{
6252 if (node == NULL)
6253 return false;
6254 if (IsA(node, Param))
6255 {
6256 Param *param = (Param *) node;
6257
6258 *context = bms_add_member(*context, param->paramid);
6259 return false;
6260 }
6261 return expression_tree_walker(node, pull_paramids_walker, context);
6262}

References bms_add_member(), expression_tree_walker, fb(), IsA, Param::paramid, and pull_paramids_walker().

Referenced by pull_paramids(), and pull_paramids_walker().

◆ query_outputs_are_not_nullable()

bool query_outputs_are_not_nullable ( Query query)

Definition at line 2051 of file clauses.c.

2052{
2053 PlannerInfo subroot;
2054 List *safe_quals = NIL;
2056 bool computed_nonnullable_vars = false;
2057
2058 /*
2059 * If the query contains set operations, punt. The set ops themselves
2060 * couldn't introduce nulls that weren't in their inputs, but the tlist
2061 * present in the top-level query is just dummy and won't give us useful
2062 * info. We could get an answer by recursing to examine each leaf query,
2063 * but for the moment it doesn't seem worth the extra complication.
2064 */
2065 if (query->setOperations)
2066 return false;
2067
2068 /*
2069 * If the query contains grouping sets, punt. Grouping sets can introduce
2070 * NULL values, and we currently lack the PlannerInfo needed to flatten
2071 * grouping Vars in the query's outputs.
2072 */
2073 if (query->groupingSets)
2074 return false;
2075
2076 /*
2077 * We need a PlannerInfo to pass to expr_is_nonnullable. Fortunately, we
2078 * can cons up an entirely dummy one, because only the "parse" link in the
2079 * struct is used by expr_is_nonnullable.
2080 */
2081 MemSet(&subroot, 0, sizeof(subroot));
2082 subroot.parse = query;
2083
2084 /*
2085 * Examine each targetlist entry to prove that it can't produce NULL.
2086 */
2088 {
2089 Expr *expr = tle->expr;
2090
2091 /* Resjunk columns can be ignored: they don't produce output values */
2092 if (tle->resjunk)
2093 continue;
2094
2095 /*
2096 * Look through binary relabelings, since we know those don't
2097 * introduce nulls.
2098 */
2099 while (expr && IsA(expr, RelabelType))
2100 expr = ((RelabelType *) expr)->arg;
2101
2102 if (expr == NULL) /* paranoia */
2103 return false;
2104
2105 /*
2106 * Since the subquery hasn't yet been through expression
2107 * preprocessing, we must explicitly flatten grouping Vars and join
2108 * alias Vars in the given expression. Note that flatten_group_exprs
2109 * must be applied before flatten_join_alias_vars, as grouping Vars
2110 * can wrap join alias Vars.
2111 *
2112 * We must also apply flatten_join_alias_vars to the quals extracted
2113 * by find_subquery_safe_quals. We do not need to apply
2114 * flatten_group_exprs to these quals, though, because grouping Vars
2115 * cannot appear in jointree quals.
2116 */
2117
2118 /*
2119 * We have verified that the query does not contain grouping sets,
2120 * meaning the grouping Vars will not have varnullingrels that need
2121 * preserving, so it's safe to use NULL as the root here.
2122 */
2123 if (query->hasGroupRTE)
2124 expr = (Expr *) flatten_group_exprs(NULL, query, (Node *) expr);
2125
2126 /*
2127 * We won't be dealing with arbitrary expressions, so it's safe to use
2128 * NULL as the root, so long as adjust_standard_join_alias_expression
2129 * can handle everything the parser would make as a join alias
2130 * expression.
2131 */
2132 expr = (Expr *) flatten_join_alias_vars(NULL, query, (Node *) expr);
2133
2134 /*
2135 * Check to see if the expr cannot be NULL. Since we're on a raw
2136 * parse tree, we need to look up the not-null constraints from the
2137 * system catalogs.
2138 */
2139 if (expr_is_nonnullable(&subroot, expr, NOTNULL_SOURCE_CATALOG))
2140 continue;
2141
2142 if (IsA(expr, Var))
2143 {
2144 Var *var = (Var *) expr;
2145
2146 /*
2147 * For a plain Var, even if that didn't work, we can conclude that
2148 * the Var is not nullable if find_nonnullable_vars can find a
2149 * "var IS NOT NULL" or similarly strict condition among the quals
2150 * on non-outerjoined-rels. Compute the list of Vars having such
2151 * quals if we didn't already.
2152 */
2154 {
2156 safe_quals = (List *)
2160 }
2161
2162 if (!mbms_is_member(var->varno,
2165 return false; /* we failed to prove the Var non-null */
2166 }
2167 else
2168 {
2169 /* Punt otherwise */
2170 return false;
2171 }
2172 }
2173
2174 return true;
2175}
#define MemSet(start, val, len)
Definition c.h:1107
List * find_nonnullable_vars(Node *clause)
Definition clauses.c:1727
bool mbms_is_member(int listidx, int bitidx, const List *a)
Query * parse
Definition pathnodes.h:309
FromExpr * jointree
Definition parsenodes.h:185
Node * setOperations
Definition parsenodes.h:239
List * targetList
Definition parsenodes.h:201
List * groupingSets
Definition parsenodes.h:223
Node * flatten_group_exprs(PlannerInfo *root, Query *query, Node *node)
Definition var.c:999
Node * flatten_join_alias_vars(PlannerInfo *root, Query *query, Node *node)
Definition var.c:781

References expr_is_nonnullable(), fb(), find_nonnullable_vars(), find_subquery_safe_quals(), FirstLowInvalidHeapAttributeNumber, flatten_group_exprs(), flatten_join_alias_vars(), foreach_node, Query::groupingSets, IsA, Query::jointree, mbms_is_member(), MemSet, NIL, NOTNULL_SOURCE_CATALOG, PlannerInfo::parse, Query::setOperations, Query::targetList, Var::varattno, and Var::varno.

Referenced by convert_ANY_sublink_to_join().

◆ recheck_cast_function_args()

static void recheck_cast_function_args ( List args,
Oid  result_type,
Oid proargtypes,
int  pronargs,
HeapTuple  func_tuple 
)
static

Definition at line 5132 of file clauses.c.

5135{
5137 int nargs;
5140 Oid rettype;
5141 ListCell *lc;
5142
5143 if (list_length(args) > FUNC_MAX_ARGS)
5144 elog(ERROR, "too many function arguments");
5145 nargs = 0;
5146 foreach(lc, args)
5147 {
5148 actual_arg_types[nargs++] = exprType((Node *) lfirst(lc));
5149 }
5150 Assert(nargs == pronargs);
5154 nargs,
5155 funcform->prorettype,
5156 false);
5157 /* let's just check we got the same answer as the parser did ... */
5158 if (rettype != result_type)
5159 elog(ERROR, "function's resolved result type changed during planning");
5160
5161 /* perform any necessary typecasting of arguments */
5163}

References Assert, elog, enforce_generic_type_consistency(), ERROR, exprType(), fb(), Form_pg_proc, FUNC_MAX_ARGS, GETSTRUCT(), lfirst, list_length(), make_fn_arguments(), memcpy(), and pronargs.

Referenced by expand_function_arguments().

◆ reorder_function_arguments()

static List * reorder_function_arguments ( List args,
int  pronargs,
HeapTuple  func_tuple 
)
static

Definition at line 5008 of file clauses.c.

5009{
5011 int nargsprovided = list_length(args);
5013 ListCell *lc;
5014 int i;
5015
5018 elog(ERROR, "too many function arguments");
5019 memset(argarray, 0, pronargs * sizeof(Node *));
5020
5021 /* Deconstruct the argument list into an array indexed by argnumber */
5022 i = 0;
5023 foreach(lc, args)
5024 {
5025 Node *arg = (Node *) lfirst(lc);
5026
5027 if (!IsA(arg, NamedArgExpr))
5028 {
5029 /* positional argument, assumed to precede all named args */
5030 Assert(argarray[i] == NULL);
5031 argarray[i++] = arg;
5032 }
5033 else
5034 {
5036
5037 Assert(na->argnumber >= 0 && na->argnumber < pronargs);
5038 Assert(argarray[na->argnumber] == NULL);
5039 argarray[na->argnumber] = (Node *) na->arg;
5040 }
5041 }
5042
5043 /*
5044 * Fetch default expressions, if needed, and insert into array at proper
5045 * locations (they aren't necessarily consecutive or all used)
5046 */
5047 if (nargsprovided < pronargs)
5048 {
5050
5051 i = pronargs - funcform->pronargdefaults;
5052 foreach(lc, defaults)
5053 {
5054 if (argarray[i] == NULL)
5055 argarray[i] = (Node *) lfirst(lc);
5056 i++;
5057 }
5058 }
5059
5060 /* Now reconstruct the args list in proper order */
5061 args = NIL;
5062 for (i = 0; i < pronargs; i++)
5063 {
5064 Assert(argarray[i] != NULL);
5065 args = lappend(args, argarray[i]);
5066 }
5067
5068 return args;
5069}

References arg, Assert, elog, ERROR, fb(), fetch_function_defaults(), Form_pg_proc, FUNC_MAX_ARGS, GETSTRUCT(), i, IsA, lappend(), lfirst, list_length(), NIL, and pronargs.

Referenced by expand_function_arguments().

◆ rowtype_field_matches()

static bool rowtype_field_matches ( Oid  rowtypeid,
int  fieldnum,
Oid  expectedtype,
int32  expectedtypmod,
Oid  expectedcollation 
)
static

Definition at line 2431 of file clauses.c.

2434{
2435 TupleDesc tupdesc;
2436 Form_pg_attribute attr;
2437
2438 /* No issue for RECORD, since there is no way to ALTER such a type */
2439 if (rowtypeid == RECORDOID)
2440 return true;
2441 tupdesc = lookup_rowtype_tupdesc_domain(rowtypeid, -1, false);
2443 {
2444 ReleaseTupleDesc(tupdesc);
2445 return false;
2446 }
2447 attr = TupleDescAttr(tupdesc, fieldnum - 1);
2448 if (attr->attisdropped ||
2449 attr->atttypid != expectedtype ||
2450 attr->atttypmod != expectedtypmod ||
2451 attr->attcollation != expectedcollation)
2452 {
2453 ReleaseTupleDesc(tupdesc);
2454 return false;
2455 }
2456 ReleaseTupleDesc(tupdesc);
2457 return true;
2458}
FormData_pg_attribute * Form_pg_attribute
#define ReleaseTupleDesc(tupdesc)
Definition tupdesc.h:240
static FormData_pg_attribute * TupleDescAttr(TupleDesc tupdesc, int i)
Definition tupdesc.h:178
TupleDesc lookup_rowtype_tupdesc_domain(Oid type_id, int32 typmod, bool noError)
Definition typcache.c:2003

References fb(), lookup_rowtype_tupdesc_domain(), TupleDescData::natts, ReleaseTupleDesc, and TupleDescAttr().

Referenced by eval_const_expressions_mutator().

◆ simplify_aggref()

static Node * simplify_aggref ( Aggref aggref,
eval_const_expressions_context context 
)
static

Definition at line 4599 of file clauses.c.

4600{
4602
4604 {
4606 Node *newnode;
4607
4608 /*
4609 * Build a SupportRequestSimplifyAggref node to pass to the support
4610 * function.
4611 */
4613 req.root = context->root;
4614 req.aggref = aggref;
4615
4617 PointerGetDatum(&req)));
4618
4619 /*
4620 * We expect the support function to return either a new Node or NULL
4621 * (when simplification isn't possible).
4622 */
4623 Assert(newnode != (Node *) aggref || newnode == NULL);
4624
4625 if (newnode != NULL)
4626 return newnode;
4627 }
4628
4629 return (Node *) aggref;
4630}

References Aggref::aggfnoid, Assert, DatumGetPointer(), fb(), get_func_support(), OidFunctionCall1, OidIsValid, PointerGetDatum, eval_const_expressions_context::root, and Node::type.

Referenced by eval_const_expressions_mutator().

◆ simplify_and_arguments()

static List * simplify_and_arguments ( List args,
eval_const_expressions_context context,
bool haveNull,
bool forceFalse 
)
static

Definition at line 4330 of file clauses.c.

4333{
4334 List *newargs = NIL;
4336
4337 /* See comments in simplify_or_arguments */
4339 while (unprocessed_args)
4340 {
4342
4344
4345 /* flatten nested ANDs as per above comment */
4346 if (is_andclause(arg))
4347 {
4348 List *subargs = ((BoolExpr *) arg)->args;
4350
4352 /* perhaps-overly-tense code to avoid leaking old lists */
4354 continue;
4355 }
4356
4357 /* If it's not an AND, simplify it */
4359
4360 /*
4361 * It is unlikely but not impossible for simplification of a non-AND
4362 * clause to produce an AND. Recheck, but don't be too tense about it
4363 * since it's not a mainstream case. In particular we don't worry
4364 * about const-simplifying the input twice, nor about list leakage.
4365 */
4366 if (is_andclause(arg))
4367 {
4368 List *subargs = ((BoolExpr *) arg)->args;
4369
4371 continue;
4372 }
4373
4374 /*
4375 * OK, we have a const-simplified non-AND argument. Process it per
4376 * comments above.
4377 */
4378 if (IsA(arg, Const))
4379 {
4380 Const *const_input = (Const *) arg;
4381
4382 if (const_input->constisnull)
4383 *haveNull = true;
4384 else if (!DatumGetBool(const_input->constvalue))
4385 {
4386 *forceFalse = true;
4387
4388 /*
4389 * Once we detect a FALSE result we can just exit the loop
4390 * immediately. However, if we ever add a notion of
4391 * non-removable functions, we'd need to keep scanning.
4392 */
4393 return NIL;
4394 }
4395 /* otherwise, we can drop the constant-true input */
4396 continue;
4397 }
4398
4399 /* else emit the simplified arg into the result list */
4401 }
4402
4403 return newargs;
4404}

References arg, DatumGetBool(), eval_const_expressions_mutator(), fb(), is_andclause(), IsA, lappend(), linitial, list_concat_copy(), list_copy(), list_delete_first(), list_free(), and NIL.

Referenced by eval_const_expressions_mutator().

◆ simplify_boolean_equality()

static Node * simplify_boolean_equality ( Oid  opno,
List args 
)
static

Definition at line 4424 of file clauses.c.

4425{
4426 Node *leftop;
4427 Node *rightop;
4428
4429 Assert(list_length(args) == 2);
4430 leftop = linitial(args);
4431 rightop = lsecond(args);
4432 if (leftop && IsA(leftop, Const))
4433 {
4434 Assert(!((Const *) leftop)->constisnull);
4435 if (opno == BooleanEqualOperator)
4436 {
4437 if (DatumGetBool(((Const *) leftop)->constvalue))
4438 return rightop; /* true = foo */
4439 else
4440 return negate_clause(rightop); /* false = foo */
4441 }
4442 else
4443 {
4444 if (DatumGetBool(((Const *) leftop)->constvalue))
4445 return negate_clause(rightop); /* true <> foo */
4446 else
4447 return rightop; /* false <> foo */
4448 }
4449 }
4450 if (rightop && IsA(rightop, Const))
4451 {
4453 if (opno == BooleanEqualOperator)
4454 {
4456 return leftop; /* foo = true */
4457 else
4458 return negate_clause(leftop); /* foo = false */
4459 }
4460 else
4461 {
4463 return negate_clause(leftop); /* foo <> true */
4464 else
4465 return leftop; /* foo <> false */
4466 }
4467 }
4468 return NULL;
4469}

References Assert, DatumGetBool(), fb(), IsA, linitial, list_length(), lsecond, and negate_clause().

Referenced by eval_const_expressions_mutator().

◆ simplify_function()

static Expr * simplify_function ( Oid  funcid,
Oid  result_type,
int32  result_typmod,
Oid  result_collid,
Oid  input_collid,
List **  args_p,
bool  funcvariadic,
bool  process_args,
bool  allow_non_const,
eval_const_expressions_context context 
)
static

Definition at line 4493 of file clauses.c.

4497{
4498 List *args = *args_p;
4501 Expr *newexpr;
4502
4503 /*
4504 * We have three strategies for simplification: execute the function to
4505 * deliver a constant result, use a transform function to generate a
4506 * substitute node tree, or expand in-line the body of the function
4507 * definition (which only works for simple SQL-language functions, but
4508 * that is a common case). Each case needs access to the function's
4509 * pg_proc tuple, so fetch it just once.
4510 *
4511 * Note: the allow_non_const flag suppresses both the second and third
4512 * strategies; so if !allow_non_const, simplify_function can only return a
4513 * Const or NULL. Argument-list rewriting happens anyway, though.
4514 */
4517 elog(ERROR, "cache lookup failed for function %u", funcid);
4519
4520 /*
4521 * Process the function arguments, unless the caller did it already.
4522 *
4523 * Here we must deal with named or defaulted arguments, and then
4524 * recursively apply eval_const_expressions to the whole argument list.
4525 */
4526 if (process_args)
4527 {
4528 args = expand_function_arguments(args, false, result_type, func_tuple);
4531 context);
4532 /* Argument processing done, give it back to the caller */
4533 *args_p = args;
4534 }
4535
4536 /* Now attempt simplification of the function call proper. */
4537
4538 newexpr = evaluate_function(funcid, result_type, result_typmod,
4540 args, funcvariadic,
4541 func_tuple, context);
4542
4543 if (!newexpr && allow_non_const && OidIsValid(func_form->prosupport))
4544 {
4545 /*
4546 * Build a SupportRequestSimplify node to pass to the support
4547 * function, pointing to a dummy FuncExpr node containing the
4548 * simplified arg list. We use this approach to present a uniform
4549 * interface to the support function regardless of how the target
4550 * function is actually being invoked.
4551 */
4554
4555 fexpr.xpr.type = T_FuncExpr;
4556 fexpr.funcid = funcid;
4557 fexpr.funcresulttype = result_type;
4558 fexpr.funcretset = func_form->proretset;
4559 fexpr.funcvariadic = funcvariadic;
4560 fexpr.funcformat = COERCE_EXPLICIT_CALL;
4561 fexpr.funccollid = result_collid;
4562 fexpr.inputcollid = input_collid;
4563 fexpr.args = args;
4564 fexpr.location = -1;
4565
4567 req.root = context->root;
4568 req.fcall = &fexpr;
4569
4570 newexpr = (Expr *)
4572 PointerGetDatum(&req)));
4573
4574 /* catch a possible API misunderstanding */
4575 Assert(newexpr != (Expr *) &fexpr);
4576 }
4577
4578 if (!newexpr && allow_non_const)
4579 newexpr = inline_function(funcid, result_type, result_collid,
4581 func_tuple, context);
4582
4584
4585 return newexpr;
4586}

References Assert, COERCE_EXPLICIT_CALL, DatumGetPointer(), elog, ERROR, eval_const_expressions_mutator(), evaluate_function(), expand_function_arguments(), expression_tree_mutator, fb(), Form_pg_proc, GETSTRUCT(), HeapTupleIsValid, inline_function(), ObjectIdGetDatum(), OidFunctionCall1, OidIsValid, PointerGetDatum, ReleaseSysCache(), eval_const_expressions_context::root, SearchSysCache1(), and FuncExpr::xpr.

Referenced by eval_const_expressions_mutator().

◆ simplify_or_arguments()

static List * simplify_or_arguments ( List args,
eval_const_expressions_context context,
bool haveNull,
bool forceTrue 
)
static

Definition at line 4224 of file clauses.c.

4227{
4228 List *newargs = NIL;
4230
4231 /*
4232 * We want to ensure that any OR immediately beneath another OR gets
4233 * flattened into a single OR-list, so as to simplify later reasoning.
4234 *
4235 * To avoid stack overflow from recursion of eval_const_expressions, we
4236 * resort to some tenseness here: we keep a list of not-yet-processed
4237 * inputs, and handle flattening of nested ORs by prepending to the to-do
4238 * list instead of recursing. Now that the parser generates N-argument
4239 * ORs from simple lists, this complexity is probably less necessary than
4240 * it once was, but we might as well keep the logic.
4241 */
4243 while (unprocessed_args)
4244 {
4246
4248
4249 /* flatten nested ORs as per above comment */
4250 if (is_orclause(arg))
4251 {
4252 List *subargs = ((BoolExpr *) arg)->args;
4254
4256 /* perhaps-overly-tense code to avoid leaking old lists */
4258 continue;
4259 }
4260
4261 /* If it's not an OR, simplify it */
4263
4264 /*
4265 * It is unlikely but not impossible for simplification of a non-OR
4266 * clause to produce an OR. Recheck, but don't be too tense about it
4267 * since it's not a mainstream case. In particular we don't worry
4268 * about const-simplifying the input twice, nor about list leakage.
4269 */
4270 if (is_orclause(arg))
4271 {
4272 List *subargs = ((BoolExpr *) arg)->args;
4273
4275 continue;
4276 }
4277
4278 /*
4279 * OK, we have a const-simplified non-OR argument. Process it per
4280 * comments above.
4281 */
4282 if (IsA(arg, Const))
4283 {
4284 Const *const_input = (Const *) arg;
4285
4286 if (const_input->constisnull)
4287 *haveNull = true;
4288 else if (DatumGetBool(const_input->constvalue))
4289 {
4290 *forceTrue = true;
4291
4292 /*
4293 * Once we detect a TRUE result we can just exit the loop
4294 * immediately. However, if we ever add a notion of
4295 * non-removable functions, we'd need to keep scanning.
4296 */
4297 return NIL;
4298 }
4299 /* otherwise, we can drop the constant-false input */
4300 continue;
4301 }
4302
4303 /* else emit the simplified arg into the result list */
4305 }
4306
4307 return newargs;
4308}

References arg, DatumGetBool(), eval_const_expressions_mutator(), fb(), is_orclause(), IsA, lappend(), linitial, list_concat_copy(), list_copy(), list_delete_first(), list_free(), and NIL.

Referenced by eval_const_expressions_mutator().

◆ sql_inline_error_callback()

static void sql_inline_error_callback ( void arg)
static

Definition at line 5700 of file clauses.c.

5701{
5704
5705 /* If it's a syntax error, convert to internal syntax error report */
5707 if (syntaxerrposition > 0)
5708 {
5709 errposition(0);
5711 internalerrquery(callback_arg->prosrc);
5712 }
5713
5714 errcontext("SQL function \"%s\" during inlining", callback_arg->proname);
5715}

References arg, errcontext, errposition(), fb(), geterrposition(), internalerrposition(), internalerrquery(), inline_error_callback_arg::proname, and inline_error_callback_arg::prosrc.

Referenced by inline_function(), and inline_function_in_from().

◆ substitute_actual_parameters()

static Node * substitute_actual_parameters ( Node expr,
int  nargs,
List args,
int usecounts 
)
static

Definition at line 5659 of file clauses.c.

5661{
5663
5664 context.nargs = nargs;
5665 context.args = args;
5666 context.usecounts = usecounts;
5667
5668 return substitute_actual_parameters_mutator(expr, &context);
5669}

References substitute_actual_parameters_context::args, substitute_actual_parameters_context::nargs, substitute_actual_parameters_mutator(), and substitute_actual_parameters_context::usecounts.

Referenced by inline_function().

◆ substitute_actual_parameters_in_from()

static Query * substitute_actual_parameters_in_from ( Query expr,
int  nargs,
List args 
)
static

◆ substitute_actual_parameters_in_from_mutator()

static Node * substitute_actual_parameters_in_from_mutator ( Node node,
substitute_actual_parameters_in_from_context context 
)
static

Definition at line 6195 of file clauses.c.

6197{
6198 Node *result;
6199
6200 if (node == NULL)
6201 return NULL;
6202 if (IsA(node, Query))
6203 {
6204 context->sublevels_up++;
6205 result = (Node *) query_tree_mutator((Query *) node,
6207 context,
6208 0);
6209 context->sublevels_up--;
6210 return result;
6211 }
6212 if (IsA(node, Param))
6213 {
6214 Param *param = (Param *) node;
6215
6216 if (param->paramkind == PARAM_EXTERN)
6217 {
6218 if (param->paramid <= 0 || param->paramid > context->nargs)
6219 elog(ERROR, "invalid paramid: %d", param->paramid);
6220
6221 /*
6222 * Since the parameter is being inserted into a subquery, we must
6223 * adjust levels.
6224 */
6225 result = copyObject(list_nth(context->args, param->paramid - 1));
6227 return result;
6228 }
6229 }
6230 return expression_tree_mutator(node,
6232 context);
6233}

References substitute_actual_parameters_in_from_context::args, copyObject, elog, ERROR, expression_tree_mutator, fb(), IncrementVarSublevelsUp(), IsA, list_nth(), substitute_actual_parameters_in_from_context::nargs, PARAM_EXTERN, Param::paramid, Param::paramkind, query_tree_mutator, result, substitute_actual_parameters_in_from_context::sublevels_up, and substitute_actual_parameters_in_from_mutator().

Referenced by substitute_actual_parameters_in_from(), and substitute_actual_parameters_in_from_mutator().

◆ substitute_actual_parameters_mutator()

static Node * substitute_actual_parameters_mutator ( Node node,
substitute_actual_parameters_context context 
)
static

Definition at line 5672 of file clauses.c.

5674{
5675 if (node == NULL)
5676 return NULL;
5677 if (IsA(node, Param))
5678 {
5679 Param *param = (Param *) node;
5680
5681 if (param->paramkind != PARAM_EXTERN)
5682 elog(ERROR, "unexpected paramkind: %d", (int) param->paramkind);
5683 if (param->paramid <= 0 || param->paramid > context->nargs)
5684 elog(ERROR, "invalid paramid: %d", param->paramid);
5685
5686 /* Count usage of parameter */
5687 context->usecounts[param->paramid - 1]++;
5688
5689 /* Select the appropriate actual arg and replace the Param with it */
5690 /* We don't need to copy at this time (it'll get done later) */
5691 return list_nth(context->args, param->paramid - 1);
5692 }
5694}

References substitute_actual_parameters_context::args, elog, ERROR, expression_tree_mutator, fb(), IsA, list_nth(), substitute_actual_parameters_context::nargs, PARAM_EXTERN, Param::paramid, Param::paramkind, substitute_actual_parameters_mutator(), and substitute_actual_parameters_context::usecounts.

Referenced by substitute_actual_parameters(), and substitute_actual_parameters_mutator().

◆ var_is_nonnullable()

bool var_is_nonnullable ( PlannerInfo root,
Var var,
NotNullSource  source 
)

Definition at line 4641 of file clauses.c.

4642{
4643 Assert(IsA(var, Var));
4644
4645 /* skip upper-level Vars */
4646 if (var->varlevelsup != 0)
4647 return false;
4648
4649 /* could the Var be nulled by any outer joins or grouping sets? */
4650 if (!bms_is_empty(var->varnullingrels))
4651 return false;
4652
4653 /*
4654 * If the Var has a non-default returning type, it could be NULL
4655 * regardless of any NOT NULL constraint. For example, OLD.col is NULL
4656 * for INSERT, and NEW.col is NULL for DELETE.
4657 */
4659 return false;
4660
4661 /* system columns cannot be NULL */
4662 if (var->varattno < 0)
4663 return true;
4664
4665 /* we don't trust whole-row Vars */
4666 if (var->varattno == 0)
4667 return false;
4668
4669 /* Check if the Var is defined as NOT NULL. */
4670 switch (source)
4671 {
4673 {
4674 /*
4675 * We retrieve the column NOT NULL constraint information from
4676 * the corresponding RelOptInfo.
4677 */
4678 RelOptInfo *rel;
4679 Bitmapset *notnullattnums;
4680
4681 rel = find_base_rel(root, var->varno);
4682 notnullattnums = rel->notnullattnums;
4683
4684 return bms_is_member(var->varattno, notnullattnums);
4685 }
4687 {
4688 /*
4689 * We retrieve the column NOT NULL constraint information from
4690 * the hash table.
4691 */
4693 Bitmapset *notnullattnums;
4694
4695 rte = planner_rt_fetch(var->varno, root);
4696
4697 /* We can only reason about ordinary relations */
4698 if (rte->rtekind != RTE_RELATION)
4699 return false;
4700
4701 /*
4702 * We must skip inheritance parent tables, as some child
4703 * tables may have a NOT NULL constraint for a column while
4704 * others may not. This cannot happen with partitioned
4705 * tables, though.
4706 */
4707 if (rte->inh && rte->relkind != RELKIND_PARTITIONED_TABLE)
4708 return false;
4709
4710 notnullattnums = find_relation_notnullatts(root, rte->relid);
4711
4712 return bms_is_member(var->varattno, notnullattnums);
4713 }
4715 {
4716 /*
4717 * We check the attnullability field in the tuple descriptor.
4718 * This is necessary rather than checking the attnotnull field
4719 * from the attribute relation, because attnotnull is also set
4720 * for invalid (NOT VALID) NOT NULL constraints, which do not
4721 * guarantee the absence of NULLs.
4722 */
4724 Relation rel;
4725 CompactAttribute *attr;
4726 bool result;
4727
4728 rte = planner_rt_fetch(var->varno, root);
4729
4730 /* We can only reason about ordinary relations */
4731 if (rte->rtekind != RTE_RELATION)
4732 return false;
4733
4734 /*
4735 * We must skip inheritance parent tables, as some child
4736 * tables may have a NOT NULL constraint for a column while
4737 * others may not. This cannot happen with partitioned
4738 * tables, though.
4739 *
4740 * Note that we need to check if the relation actually has any
4741 * children, as we might not have done that yet.
4742 */
4743 if (rte->inh && has_subclass(rte->relid) &&
4744 rte->relkind != RELKIND_PARTITIONED_TABLE)
4745 return false;
4746
4747 /* We need not lock the relation since it was already locked */
4748 rel = table_open(rte->relid, NoLock);
4750 var->varattno - 1);
4752 table_close(rel, NoLock);
4753
4754 return result;
4755 }
4756 default:
4757 elog(ERROR, "unrecognized NotNullSource: %d",
4758 (int) source);
4759 break;
4760 }
4761
4762 return false;
4763}

References Assert, CompactAttribute::attnullability, ATTNULLABLE_VALID, bms_is_empty, bms_is_member(), elog, ERROR, fb(), find_base_rel(), find_relation_notnullatts(), has_subclass(), IsA, NoLock, NOTNULL_SOURCE_CATALOG, NOTNULL_SOURCE_HASHTABLE, NOTNULL_SOURCE_RELOPT, RelOptInfo::notnullattnums, planner_rt_fetch, RelationGetDescr, result, root, RTE_RELATION, source, table_close(), table_open(), TupleDescCompactAttr(), VAR_RETURNING_DEFAULT, Var::varattno, Var::varlevelsup, Var::varno, and Var::varreturningtype.

Referenced by expr_is_nonnullable().