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 2675 of file clauses.c.

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

◆ 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 2679 of file clauses.c.

◆ ece_generic_processing

#define ece_generic_processing (   node)
Value:

Definition at line 2666 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 5081 of file clauses.c.

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

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:1815
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:2143

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:3438
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:726
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:1648

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 4173 of file clauses.c.

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

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:2067

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(), init_notnull_info(), 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 Node *leftarg = (Node *) linitial(saop->args);
2548 Node *arrayarg = (Node *) lsecond(saop->args);
2551
2552 if (arrayarg && IsA(arrayarg, Const) &&
2553 !((Const *) arrayarg)->constisnull)
2554 {
2555 if (saop->useOr)
2556 {
2560 {
2561 Datum arrdatum = ((Const *) arrayarg)->constvalue;
2563 int nitems;
2564
2565 /*
2566 * Only fill in the hash functions if the array looks
2567 * large enough for it to be worth hashing instead of
2568 * doing a linear search.
2569 */
2570 nitems = ArrayGetNItems(ARR_NDIM(arr), ARR_DIMS(arr));
2571
2573 {
2574 /* Looks good. Fill in the hash functions */
2575 saop->hashfuncid = lefthashfunc;
2576 }
2577 return false;
2578 }
2579 }
2580 else /* !saop->useOr */
2581 {
2582 Oid negator = get_negator(saop->opno);
2583
2584 /*
2585 * Check if this is a NOT IN using an operator whose negator
2586 * is hashable. If so we can still build a hash table and
2587 * just ensure the lookup items are not in the hash table.
2588 */
2589 if (OidIsValid(negator) &&
2593 {
2594 Datum arrdatum = ((Const *) arrayarg)->constvalue;
2596 int nitems;
2597
2598 /*
2599 * Only fill in the hash functions if the array looks
2600 * large enough for it to be worth hashing instead of
2601 * doing a linear search.
2602 */
2603 nitems = ArrayGetNItems(ARR_NDIM(arr), ARR_DIMS(arr));
2604
2606 {
2607 /* Looks good. Fill in the hash functions */
2608 saop->hashfuncid = lefthashfunc;
2609
2610 /*
2611 * Also set the negfuncid. The executor will need
2612 * that to perform hashtable lookups.
2613 */
2614 saop->negfuncid = get_opcode(negator);
2615 }
2616 return false;
2617 }
2618 }
2619 }
2620 }
2621
2623}
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_ext(Oid opno, Oid inputtype, RegProcedure *lhs_procno, RegProcedure *rhs_procno)
Definition lsyscache.c:677
Oid get_negator(Oid opno)
Definition lsyscache.c:1839

References ScalarArrayOpExpr::args, ARR_DIMS, ARR_NDIM, ArrayGetNItems(), convert_saop_to_hashed_saop_walker(), DatumGetPointer(), expression_tree_walker, exprType(), fb(), get_negator(), get_op_hash_functions_ext(), get_opcode(), IsA, linitial, 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 4189 of file clauses.c.

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

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 2689 of file clauses.c.

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

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 5727 of file clauses.c.

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

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 5180 of file clauses.c.

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

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 4930 of file clauses.c.

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

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 4788 of file clauses.c.

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

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 5105 of file clauses.c.

5106{
5107 List *defaults;
5109 char *str;
5110
5114 defaults = castNode(List, stringToNode(str));
5115 pfree(str);
5116 return defaults;
5117}

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:2004
NullTestType nulltesttype
Definition primnodes.h:1980
Expr * arg
Definition primnodes.h:1979

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) ||
1669 splan->subLinkType == ROWCOMPARE_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:1013
@ ROWCOMPARE_SUBLINK
Definition primnodes.h:1014

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(), 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) ||
1911 splan->subLinkType == ROWCOMPARE_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(), 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:315
@ JOIN_FULL
Definition nodes.h:303
@ JOIN_INNER
Definition nodes.h:301
@ JOIN_RIGHT
Definition nodes.h:304
@ JOIN_LEFT
Definition nodes.h:302
@ JOIN_ANTI
Definition nodes.h:316
List * fromlist
Definition primnodes.h:2377

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 5306 of file clauses.c.

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

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 5819 of file clauses.c.

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

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 6023 of file clauses.c.

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

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 6275 of file clauses.c.

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

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:2105

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:239
List * args
Definition primnodes.h:1106
List * paramIds
Definition primnodes.h:1082
Node * testexpr
Definition primnodes.h:1081
bool parallel_safe
Definition primnodes.h:1099

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 6243 of file clauses.c.

6244{
6246
6247 (void) pull_paramids_walker((Node *) expr, &result);
6248
6249 return result;
6250}

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 6253 of file clauses.c.

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

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:187
Node * setOperations
Definition parsenodes.h:241
List * targetList
Definition parsenodes.h:203
List * groupingSets
Definition parsenodes.h:225
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 5135 of file clauses.c.

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

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 5011 of file clauses.c.

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

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:2005

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 4602 of file clauses.c.

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

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 4333 of file clauses.c.

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

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 4427 of file clauses.c.

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

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 4496 of file clauses.c.

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

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 4227 of file clauses.c.

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

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 5703 of file clauses.c.

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

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 5662 of file clauses.c.

5664{
5666
5667 context.nargs = nargs;
5668 context.args = args;
5669 context.usecounts = usecounts;
5670
5671 return substitute_actual_parameters_mutator(expr, &context);
5672}

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 6198 of file clauses.c.

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

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 5675 of file clauses.c.

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

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 4644 of file clauses.c.

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

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().