PostgreSQL Source Code git master
Loading...
Searching...
No Matches
clauses.c File Reference
#include "postgres.h"
#include "access/htup_details.h"
#include "catalog/pg_class.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/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 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 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, bool use_rel_info)
 
bool expr_is_nonnullable (PlannerInfo *root, Expr *expr, bool use_rel_info)
 
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 1197 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 2439 of file clauses.c.

2454{
2455
2456 /* since this function recurses, it could be driven to stack overflow */
2458
2459 if (node == NULL)
2460 return NULL;
2461 switch (nodeTag(node))
2462 {
2463 case T_Param:
2464 {
2465 Param *param = (Param *) node;
2466 ParamListInfo paramLI = context->boundParams;
2467
2468 /* Look to see if we've been given a value for this Param */
2469 if (param->paramkind == PARAM_EXTERN &&
2470 paramLI != NULL &&
2471 param->paramid > 0 &&
2472 param->paramid <= paramLI->numParams)
2473 {
2476
2477 /*
2478 * Give hook a chance in case parameter is dynamic. Tell
2479 * it that this fetch is speculative, so it should avoid
2480 * erroring out if parameter is unavailable.
2481 */
2482 if (paramLI->paramFetch != NULL)
2483 prm = paramLI->paramFetch(paramLI, param->paramid,
2484 true, &prmdata);
2485 else
2486 prm = &paramLI->params[param->paramid - 1];
2487
2488 /*
2489 * We don't just check OidIsValid, but insist that the
2490 * fetched type match the Param, just in case the hook did
2491 * something unexpected. No need to throw an error here
2492 * though; leave that for runtime.
2493 */
2494 if (OidIsValid(prm->ptype) &&
2495 prm->ptype == param->paramtype)
2496 {
2497 /* OK to substitute parameter value? */
2498 if (context->estimate ||
2499 (prm->pflags & PARAM_FLAG_CONST))
2500 {
2501 /*
2502 * Return a Const representing the param value.
2503 * Must copy pass-by-ref datatypes, since the
2504 * Param might be in a memory context
2505 * shorter-lived than our output plan should be.
2506 */
2507 int16 typLen;
2508 bool typByVal;
2509 Datum pval;
2510 Const *con;
2511
2513 &typLen, &typByVal);
2514 if (prm->isnull || typByVal)
2515 pval = prm->value;
2516 else
2517 pval = datumCopy(prm->value, typByVal, typLen);
2518 con = makeConst(param->paramtype,
2519 param->paramtypmod,
2520 param->paramcollid,
2521 (int) typLen,
2522 pval,
2523 prm->isnull,
2524 typByVal);
2525 con->location = param->location;
2526 return (Node *) con;
2527 }
2528 }
2529 }
2530
2531 /*
2532 * Not replaceable, so just copy the Param (no need to
2533 * recurse)
2534 */
2535 return (Node *) copyObject(param);
2536 }
2537 case T_WindowFunc:
2538 {
2539 WindowFunc *expr = (WindowFunc *) node;
2540 Oid funcid = expr->winfnoid;
2541 List *args;
2542 Expr *aggfilter;
2545
2546 /*
2547 * We can't really simplify a WindowFunc node, but we mustn't
2548 * just fall through to the default processing, because we
2549 * have to apply expand_function_arguments to its argument
2550 * list. That takes care of inserting default arguments and
2551 * expanding named-argument notation.
2552 */
2555 elog(ERROR, "cache lookup failed for function %u", funcid);
2556
2558 false, expr->wintype,
2559 func_tuple);
2560
2562
2563 /* Now, recursively simplify the args (which are a List) */
2564 args = (List *)
2567 context);
2568 /* ... and the filter expression, which isn't */
2569 aggfilter = (Expr *)
2571 context);
2572
2573 /* And build the replacement WindowFunc node */
2575 newexpr->winfnoid = expr->winfnoid;
2576 newexpr->wintype = expr->wintype;
2577 newexpr->wincollid = expr->wincollid;
2578 newexpr->inputcollid = expr->inputcollid;
2579 newexpr->args = args;
2580 newexpr->aggfilter = aggfilter;
2581 newexpr->runCondition = expr->runCondition;
2582 newexpr->winref = expr->winref;
2583 newexpr->winstar = expr->winstar;
2584 newexpr->winagg = expr->winagg;
2586 newexpr->location = expr->location;
2587
2588 return (Node *) newexpr;
2589 }
2590 case T_FuncExpr:
2591 {
2592 FuncExpr *expr = (FuncExpr *) node;
2593 List *args = expr->args;
2594 Expr *simple;
2596
2597 /*
2598 * Code for op/func reduction is pretty bulky, so split it out
2599 * as a separate function. Note: exprTypmod normally returns
2600 * -1 for a FuncExpr, but not when the node is recognizably a
2601 * length coercion; we want to preserve the typmod in the
2602 * eventual Const if so.
2603 */
2604 simple = simplify_function(expr->funcid,
2605 expr->funcresulttype,
2606 exprTypmod(node),
2607 expr->funccollid,
2608 expr->inputcollid,
2609 &args,
2610 expr->funcvariadic,
2611 true,
2612 true,
2613 context);
2614 if (simple) /* successfully simplified it */
2615 return (Node *) simple;
2616
2617 /*
2618 * The expression cannot be simplified any further, so build
2619 * and return a replacement FuncExpr node using the
2620 * possibly-simplified arguments. Note that we have also
2621 * converted the argument list to positional notation.
2622 */
2624 newexpr->funcid = expr->funcid;
2625 newexpr->funcresulttype = expr->funcresulttype;
2626 newexpr->funcretset = expr->funcretset;
2627 newexpr->funcvariadic = expr->funcvariadic;
2628 newexpr->funcformat = expr->funcformat;
2629 newexpr->funccollid = expr->funccollid;
2630 newexpr->inputcollid = expr->inputcollid;
2631 newexpr->args = args;
2632 newexpr->location = expr->location;
2633 return (Node *) newexpr;
2634 }
2635 case T_Aggref:
2636 node = ece_generic_processing(node);
2637 if (context->root != NULL)
2638 return simplify_aggref((Aggref *) node, context);
2639 return node;
2640 case T_OpExpr:
2641 {
2642 OpExpr *expr = (OpExpr *) node;
2643 List *args = expr->args;
2644 Expr *simple;
2645 OpExpr *newexpr;
2646
2647 /*
2648 * Need to get OID of underlying function. Okay to scribble
2649 * on input to this extent.
2650 */
2651 set_opfuncid(expr);
2652
2653 /*
2654 * Code for op/func reduction is pretty bulky, so split it out
2655 * as a separate function.
2656 */
2657 simple = simplify_function(expr->opfuncid,
2658 expr->opresulttype, -1,
2659 expr->opcollid,
2660 expr->inputcollid,
2661 &args,
2662 false,
2663 true,
2664 true,
2665 context);
2666 if (simple) /* successfully simplified it */
2667 return (Node *) simple;
2668
2669 /*
2670 * If the operator is boolean equality or inequality, we know
2671 * how to simplify cases involving one constant and one
2672 * non-constant argument.
2673 */
2674 if (expr->opno == BooleanEqualOperator ||
2676 {
2677 simple = (Expr *) simplify_boolean_equality(expr->opno,
2678 args);
2679 if (simple) /* successfully simplified it */
2680 return (Node *) simple;
2681 }
2682
2683 /*
2684 * The expression cannot be simplified any further, so build
2685 * and return a replacement OpExpr node using the
2686 * possibly-simplified arguments.
2687 */
2689 newexpr->opno = expr->opno;
2690 newexpr->opfuncid = expr->opfuncid;
2691 newexpr->opresulttype = expr->opresulttype;
2692 newexpr->opretset = expr->opretset;
2693 newexpr->opcollid = expr->opcollid;
2694 newexpr->inputcollid = expr->inputcollid;
2695 newexpr->args = args;
2696 newexpr->location = expr->location;
2697 return (Node *) newexpr;
2698 }
2699 case T_DistinctExpr:
2700 {
2701 DistinctExpr *expr = (DistinctExpr *) node;
2702 List *args;
2703 ListCell *arg;
2704 bool has_null_input = false;
2705 bool all_null_input = true;
2706 bool has_nonconst_input = false;
2707 bool has_nullable_nonconst = false;
2708 Expr *simple;
2710
2711 /*
2712 * Reduce constants in the DistinctExpr's arguments. We know
2713 * args is either NIL or a List node, so we can call
2714 * expression_tree_mutator directly rather than recursing to
2715 * self.
2716 */
2717 args = (List *) expression_tree_mutator((Node *) expr->args,
2719 context);
2720
2721 /*
2722 * We must do our own check for NULLs because DistinctExpr has
2723 * different results for NULL input than the underlying
2724 * operator does. We also check if any non-constant input is
2725 * potentially nullable.
2726 */
2727 foreach(arg, args)
2728 {
2729 if (IsA(lfirst(arg), Const))
2730 {
2733 }
2734 else
2735 {
2736 has_nonconst_input = true;
2737 all_null_input = false;
2738
2739 if (!has_nullable_nonconst &&
2740 !expr_is_nonnullable(context->root,
2741 (Expr *) lfirst(arg), false))
2742 has_nullable_nonconst = true;
2743 }
2744 }
2745
2746 if (!has_nonconst_input)
2747 {
2748 /*
2749 * All inputs are constants. We can optimize this out
2750 * completely.
2751 */
2752
2753 /* all nulls? then not distinct */
2754 if (all_null_input)
2755 return makeBoolConst(false, false);
2756
2757 /* one null? then distinct */
2758 if (has_null_input)
2759 return makeBoolConst(true, false);
2760
2761 /* otherwise try to evaluate the '=' operator */
2762 /* (NOT okay to try to inline it, though!) */
2763
2764 /*
2765 * Need to get OID of underlying function. Okay to
2766 * scribble on input to this extent.
2767 */
2768 set_opfuncid((OpExpr *) expr); /* rely on struct
2769 * equivalence */
2770
2771 /*
2772 * Code for op/func reduction is pretty bulky, so split it
2773 * out as a separate function.
2774 */
2775 simple = simplify_function(expr->opfuncid,
2776 expr->opresulttype, -1,
2777 expr->opcollid,
2778 expr->inputcollid,
2779 &args,
2780 false,
2781 false,
2782 false,
2783 context);
2784 if (simple) /* successfully simplified it */
2785 {
2786 /*
2787 * Since the underlying operator is "=", must negate
2788 * its result
2789 */
2790 Const *csimple = castNode(Const, simple);
2791
2792 csimple->constvalue =
2793 BoolGetDatum(!DatumGetBool(csimple->constvalue));
2794 return (Node *) csimple;
2795 }
2796 }
2797 else if (!has_nullable_nonconst)
2798 {
2799 /*
2800 * There are non-constant inputs, but since all of them
2801 * are proven non-nullable, "IS DISTINCT FROM" semantics
2802 * are much simpler.
2803 */
2804
2805 OpExpr *eqexpr;
2806
2807 /*
2808 * If one input is an explicit NULL constant, and the
2809 * other is a non-nullable expression, the result is
2810 * always TRUE.
2811 */
2812 if (has_null_input)
2813 return makeBoolConst(true, false);
2814
2815 /*
2816 * Otherwise, both inputs are known non-nullable. In this
2817 * case, "IS DISTINCT FROM" is equivalent to the standard
2818 * inequality operator (usually "<>"). We convert this to
2819 * an OpExpr, which is a more efficient representation for
2820 * the planner. It can enable the use of partial indexes
2821 * and constraint exclusion. Furthermore, if the clause
2822 * is negated (ie, "IS NOT DISTINCT FROM"), the resulting
2823 * "=" operator can allow the planner to use index scans,
2824 * merge joins, hash joins, and EC-based qual deductions.
2825 */
2827 eqexpr->opno = expr->opno;
2828 eqexpr->opfuncid = expr->opfuncid;
2829 eqexpr->opresulttype = BOOLOID;
2830 eqexpr->opretset = expr->opretset;
2831 eqexpr->opcollid = expr->opcollid;
2832 eqexpr->inputcollid = expr->inputcollid;
2833 eqexpr->args = args;
2834 eqexpr->location = expr->location;
2835
2837 context);
2838 }
2839 else if (has_null_input)
2840 {
2841 /*
2842 * One input is a nullable non-constant expression, and
2843 * the other is an explicit NULL constant. We can
2844 * transform this to a NullTest with !argisrow, which is
2845 * much more amenable to optimization.
2846 */
2847
2849
2850 nt->arg = (Expr *) (IsA(linitial(args), Const) ?
2851 lsecond(args) : linitial(args));
2852 nt->nulltesttype = IS_NOT_NULL;
2853
2854 /*
2855 * argisrow = false is correct whether or not arg is
2856 * composite
2857 */
2858 nt->argisrow = false;
2859 nt->location = expr->location;
2860
2861 return eval_const_expressions_mutator((Node *) nt, context);
2862 }
2863
2864 /*
2865 * The expression cannot be simplified any further, so build
2866 * and return a replacement DistinctExpr node using the
2867 * possibly-simplified arguments.
2868 */
2870 newexpr->opno = expr->opno;
2871 newexpr->opfuncid = expr->opfuncid;
2872 newexpr->opresulttype = expr->opresulttype;
2873 newexpr->opretset = expr->opretset;
2874 newexpr->opcollid = expr->opcollid;
2875 newexpr->inputcollid = expr->inputcollid;
2876 newexpr->args = args;
2877 newexpr->location = expr->location;
2878 return (Node *) newexpr;
2879 }
2880 case T_NullIfExpr:
2881 {
2882 NullIfExpr *expr;
2883 ListCell *arg;
2884 bool has_nonconst_input = false;
2885
2886 /* Copy the node and const-simplify its arguments */
2887 expr = (NullIfExpr *) ece_generic_processing(node);
2888
2889 /* If either argument is NULL they can't be equal */
2890 foreach(arg, expr->args)
2891 {
2892 if (!IsA(lfirst(arg), Const))
2893 has_nonconst_input = true;
2894 else if (((Const *) lfirst(arg))->constisnull)
2895 return (Node *) linitial(expr->args);
2896 }
2897
2898 /*
2899 * Need to get OID of underlying function before checking if
2900 * the function is OK to evaluate.
2901 */
2902 set_opfuncid((OpExpr *) expr);
2903
2904 if (!has_nonconst_input &&
2905 ece_function_is_safe(expr->opfuncid, context))
2906 return ece_evaluate_expr(expr);
2907
2908 return (Node *) expr;
2909 }
2911 {
2912 ScalarArrayOpExpr *saop;
2913
2914 /* Copy the node and const-simplify its arguments */
2916
2917 /* Make sure we know underlying function */
2918 set_sa_opfuncid(saop);
2919
2920 /*
2921 * If all arguments are Consts, and it's a safe function, we
2922 * can fold to a constant
2923 */
2924 if (ece_all_arguments_const(saop) &&
2925 ece_function_is_safe(saop->opfuncid, context))
2926 return ece_evaluate_expr(saop);
2927 return (Node *) saop;
2928 }
2929 case T_BoolExpr:
2930 {
2931 BoolExpr *expr = (BoolExpr *) node;
2932
2933 switch (expr->boolop)
2934 {
2935 case OR_EXPR:
2936 {
2937 List *newargs;
2938 bool haveNull = false;
2939 bool forceTrue = false;
2940
2942 context,
2943 &haveNull,
2944 &forceTrue);
2945 if (forceTrue)
2946 return makeBoolConst(true, false);
2947 if (haveNull)
2949 makeBoolConst(false, true));
2950 /* If all the inputs are FALSE, result is FALSE */
2951 if (newargs == NIL)
2952 return makeBoolConst(false, false);
2953
2954 /*
2955 * If only one nonconst-or-NULL input, it's the
2956 * result
2957 */
2958 if (list_length(newargs) == 1)
2959 return (Node *) linitial(newargs);
2960 /* Else we still need an OR node */
2961 return (Node *) make_orclause(newargs);
2962 }
2963 case AND_EXPR:
2964 {
2965 List *newargs;
2966 bool haveNull = false;
2967 bool forceFalse = false;
2968
2970 context,
2971 &haveNull,
2972 &forceFalse);
2973 if (forceFalse)
2974 return makeBoolConst(false, false);
2975 if (haveNull)
2977 makeBoolConst(false, true));
2978 /* If all the inputs are TRUE, result is TRUE */
2979 if (newargs == NIL)
2980 return makeBoolConst(true, false);
2981
2982 /*
2983 * If only one nonconst-or-NULL input, it's the
2984 * result
2985 */
2986 if (list_length(newargs) == 1)
2987 return (Node *) linitial(newargs);
2988 /* Else we still need an AND node */
2989 return (Node *) make_andclause(newargs);
2990 }
2991 case NOT_EXPR:
2992 {
2993 Node *arg;
2994
2995 Assert(list_length(expr->args) == 1);
2997 context);
2998
2999 /*
3000 * Use negate_clause() to see if we can simplify
3001 * away the NOT.
3002 */
3003 return negate_clause(arg);
3004 }
3005 default:
3006 elog(ERROR, "unrecognized boolop: %d",
3007 (int) expr->boolop);
3008 break;
3009 }
3010 break;
3011 }
3012
3013 case T_JsonValueExpr:
3014 {
3015 JsonValueExpr *jve = (JsonValueExpr *) node;
3016 Node *raw_expr = (Node *) jve->raw_expr;
3017 Node *formatted_expr = (Node *) jve->formatted_expr;
3018
3019 /*
3020 * If we can fold formatted_expr to a constant, we can elide
3021 * the JsonValueExpr altogether. Otherwise we must process
3022 * raw_expr too. But JsonFormat is a flat node and requires
3023 * no simplification, only copying.
3024 */
3025 formatted_expr = eval_const_expressions_mutator(formatted_expr,
3026 context);
3027 if (formatted_expr && IsA(formatted_expr, Const))
3028 return formatted_expr;
3029
3030 raw_expr = eval_const_expressions_mutator(raw_expr, context);
3031
3032 return (Node *) makeJsonValueExpr((Expr *) raw_expr,
3033 (Expr *) formatted_expr,
3034 copyObject(jve->format));
3035 }
3036
3037 case T_SubPlan:
3039
3040 /*
3041 * Return a SubPlan unchanged --- too late to do anything with it.
3042 *
3043 * XXX should we ereport() here instead? Probably this routine
3044 * should never be invoked after SubPlan creation.
3045 */
3046 return node;
3047 case T_RelabelType:
3048 {
3049 RelabelType *relabel = (RelabelType *) node;
3050 Node *arg;
3051
3052 /* Simplify the input ... */
3054 context);
3055 /* ... and attach a new RelabelType node, if needed */
3056 return applyRelabelType(arg,
3057 relabel->resulttype,
3058 relabel->resulttypmod,
3059 relabel->resultcollid,
3060 relabel->relabelformat,
3061 relabel->location,
3062 true);
3063 }
3064 case T_CoerceViaIO:
3065 {
3066 CoerceViaIO *expr = (CoerceViaIO *) node;
3067 List *args;
3068 Oid outfunc;
3069 bool outtypisvarlena;
3070 Oid infunc;
3072 Expr *simple;
3074
3075 /* Make a List so we can use simplify_function */
3076 args = list_make1(expr->arg);
3077
3078 /*
3079 * CoerceViaIO represents calling the source type's output
3080 * function then the result type's input function. So, try to
3081 * simplify it as though it were a stack of two such function
3082 * calls. First we need to know what the functions are.
3083 *
3084 * Note that the coercion functions are assumed not to care
3085 * about input collation, so we just pass InvalidOid for that.
3086 */
3090 &infunc, &intypioparam);
3091
3092 simple = simplify_function(outfunc,
3093 CSTRINGOID, -1,
3094 InvalidOid,
3095 InvalidOid,
3096 &args,
3097 false,
3098 true,
3099 true,
3100 context);
3101 if (simple) /* successfully simplified output fn */
3102 {
3103 /*
3104 * Input functions may want 1 to 3 arguments. We always
3105 * supply all three, trusting that nothing downstream will
3106 * complain.
3107 */
3108 args = list_make3(simple,
3110 -1,
3111 InvalidOid,
3112 sizeof(Oid),
3114 false,
3115 true),
3117 -1,
3118 InvalidOid,
3119 sizeof(int32),
3120 Int32GetDatum(-1),
3121 false,
3122 true));
3123
3124 simple = simplify_function(infunc,
3125 expr->resulttype, -1,
3126 expr->resultcollid,
3127 InvalidOid,
3128 &args,
3129 false,
3130 false,
3131 true,
3132 context);
3133 if (simple) /* successfully simplified input fn */
3134 return (Node *) simple;
3135 }
3136
3137 /*
3138 * The expression cannot be simplified any further, so build
3139 * and return a replacement CoerceViaIO node using the
3140 * possibly-simplified argument.
3141 */
3143 newexpr->arg = (Expr *) linitial(args);
3144 newexpr->resulttype = expr->resulttype;
3145 newexpr->resultcollid = expr->resultcollid;
3146 newexpr->coerceformat = expr->coerceformat;
3147 newexpr->location = expr->location;
3148 return (Node *) newexpr;
3149 }
3150 case T_ArrayCoerceExpr:
3151 {
3154
3155 /*
3156 * Copy the node and const-simplify its arguments. We can't
3157 * use ece_generic_processing() here because we need to mess
3158 * with case_val only while processing the elemexpr.
3159 */
3160 memcpy(ac, node, sizeof(ArrayCoerceExpr));
3161 ac->arg = (Expr *)
3163 context);
3164
3165 /*
3166 * Set up for the CaseTestExpr node contained in the elemexpr.
3167 * We must prevent it from absorbing any outer CASE value.
3168 */
3169 save_case_val = context->case_val;
3170 context->case_val = NULL;
3171
3172 ac->elemexpr = (Expr *)
3174 context);
3175
3176 context->case_val = save_case_val;
3177
3178 /*
3179 * If constant argument and the per-element expression is
3180 * immutable, we can simplify the whole thing to a constant.
3181 * Exception: although contain_mutable_functions considers
3182 * CoerceToDomain immutable for historical reasons, let's not
3183 * do so here; this ensures coercion to an array-over-domain
3184 * does not apply the domain's constraints until runtime.
3185 */
3186 if (ac->arg && IsA(ac->arg, Const) &&
3187 ac->elemexpr && !IsA(ac->elemexpr, CoerceToDomain) &&
3188 !contain_mutable_functions((Node *) ac->elemexpr))
3189 return ece_evaluate_expr(ac);
3190
3191 return (Node *) ac;
3192 }
3193 case T_CollateExpr:
3194 {
3195 /*
3196 * We replace CollateExpr with RelabelType, so as to improve
3197 * uniformity of expression representation and thus simplify
3198 * comparison of expressions. Hence this looks very nearly
3199 * the same as the RelabelType case, and we can apply the same
3200 * optimizations to avoid unnecessary RelabelTypes.
3201 */
3202 CollateExpr *collate = (CollateExpr *) node;
3203 Node *arg;
3204
3205 /* Simplify the input ... */
3207 context);
3208 /* ... and attach a new RelabelType node, if needed */
3209 return applyRelabelType(arg,
3210 exprType(arg),
3211 exprTypmod(arg),
3212 collate->collOid,
3214 collate->location,
3215 true);
3216 }
3217 case T_CaseExpr:
3218 {
3219 /*----------
3220 * CASE expressions can be simplified if there are constant
3221 * condition clauses:
3222 * FALSE (or NULL): drop the alternative
3223 * TRUE: drop all remaining alternatives
3224 * If the first non-FALSE alternative is a constant TRUE,
3225 * we can simplify the entire CASE to that alternative's
3226 * expression. If there are no non-FALSE alternatives,
3227 * we simplify the entire CASE to the default result (ELSE).
3228 *
3229 * If we have a simple-form CASE with constant test
3230 * expression, we substitute the constant value for contained
3231 * CaseTestExpr placeholder nodes, so that we have the
3232 * opportunity to reduce constant test conditions. For
3233 * example this allows
3234 * CASE 0 WHEN 0 THEN 1 ELSE 1/0 END
3235 * to reduce to 1 rather than drawing a divide-by-0 error.
3236 * Note that when the test expression is constant, we don't
3237 * have to include it in the resulting CASE; for example
3238 * CASE 0 WHEN x THEN y ELSE z END
3239 * is transformed by the parser to
3240 * CASE 0 WHEN CaseTestExpr = x THEN y ELSE z END
3241 * which we can simplify to
3242 * CASE WHEN 0 = x THEN y ELSE z END
3243 * It is not necessary for the executor to evaluate the "arg"
3244 * expression when executing the CASE, since any contained
3245 * CaseTestExprs that might have referred to it will have been
3246 * replaced by the constant.
3247 *----------
3248 */
3249 CaseExpr *caseexpr = (CaseExpr *) node;
3252 Node *newarg;
3253 List *newargs;
3254 bool const_true_cond;
3255 Node *defresult = NULL;
3256 ListCell *arg;
3257
3258 /* Simplify the test expression, if any */
3260 context);
3261
3262 /* Set up for contained CaseTestExpr nodes */
3263 save_case_val = context->case_val;
3264 if (newarg && IsA(newarg, Const))
3265 {
3266 context->case_val = newarg;
3267 newarg = NULL; /* not needed anymore, see above */
3268 }
3269 else
3270 context->case_val = NULL;
3271
3272 /* Simplify the WHEN clauses */
3273 newargs = NIL;
3274 const_true_cond = false;
3275 foreach(arg, caseexpr->args)
3276 {
3278 Node *casecond;
3280
3281 /* Simplify this alternative's test condition */
3283 context);
3284
3285 /*
3286 * If the test condition is constant FALSE (or NULL), then
3287 * drop this WHEN clause completely, without processing
3288 * the result.
3289 */
3290 if (casecond && IsA(casecond, Const))
3291 {
3293
3294 if (const_input->constisnull ||
3295 !DatumGetBool(const_input->constvalue))
3296 continue; /* drop alternative with FALSE cond */
3297 /* Else it's constant TRUE */
3298 const_true_cond = true;
3299 }
3300
3301 /* Simplify this alternative's result value */
3303 context);
3304
3305 /* If non-constant test condition, emit a new WHEN node */
3306 if (!const_true_cond)
3307 {
3309
3310 newcasewhen->expr = (Expr *) casecond;
3311 newcasewhen->result = (Expr *) caseresult;
3312 newcasewhen->location = oldcasewhen->location;
3314 continue;
3315 }
3316
3317 /*
3318 * Found a TRUE condition, so none of the remaining
3319 * alternatives can be reached. We treat the result as
3320 * the default result.
3321 */
3322 defresult = caseresult;
3323 break;
3324 }
3325
3326 /* Simplify the default result, unless we replaced it above */
3327 if (!const_true_cond)
3328 defresult = eval_const_expressions_mutator((Node *) caseexpr->defresult,
3329 context);
3330
3331 context->case_val = save_case_val;
3332
3333 /*
3334 * If no non-FALSE alternatives, CASE reduces to the default
3335 * result
3336 */
3337 if (newargs == NIL)
3338 return defresult;
3339 /* Otherwise we need a new CASE node */
3341 newcase->casetype = caseexpr->casetype;
3342 newcase->casecollid = caseexpr->casecollid;
3343 newcase->arg = (Expr *) newarg;
3344 newcase->args = newargs;
3345 newcase->defresult = (Expr *) defresult;
3346 newcase->location = caseexpr->location;
3347 return (Node *) newcase;
3348 }
3349 case T_CaseTestExpr:
3350 {
3351 /*
3352 * If we know a constant test value for the current CASE
3353 * construct, substitute it for the placeholder. Else just
3354 * return the placeholder as-is.
3355 */
3356 if (context->case_val)
3357 return copyObject(context->case_val);
3358 else
3359 return copyObject(node);
3360 }
3361 case T_SubscriptingRef:
3362 case T_ArrayExpr:
3363 case T_RowExpr:
3364 case T_MinMaxExpr:
3365 {
3366 /*
3367 * Generic handling for node types whose own processing is
3368 * known to be immutable, and for which we need no smarts
3369 * beyond "simplify if all inputs are constants".
3370 *
3371 * Treating SubscriptingRef this way assumes that subscripting
3372 * fetch and assignment are both immutable. This constrains
3373 * type-specific subscripting implementations; maybe we should
3374 * relax it someday.
3375 *
3376 * Treating MinMaxExpr this way amounts to assuming that the
3377 * btree comparison function it calls is immutable; see the
3378 * reasoning in contain_mutable_functions_walker.
3379 */
3380
3381 /* Copy the node and const-simplify its arguments */
3382 node = ece_generic_processing(node);
3383 /* If all arguments are Consts, we can fold to a constant */
3384 if (ece_all_arguments_const(node))
3385 return ece_evaluate_expr(node);
3386 return node;
3387 }
3388 case T_CoalesceExpr:
3389 {
3392 List *newargs;
3393 ListCell *arg;
3394
3395 newargs = NIL;
3396 foreach(arg, coalesceexpr->args)
3397 {
3398 Node *e;
3399
3401 context);
3402
3403 /*
3404 * We can remove null constants from the list. For a
3405 * nonnullable expression, if it has not been preceded by
3406 * any non-null-constant expressions then it is the
3407 * result. Otherwise, it's the next argument, but we can
3408 * drop following arguments since they will never be
3409 * reached.
3410 */
3411 if (IsA(e, Const))
3412 {
3413 if (((Const *) e)->constisnull)
3414 continue; /* drop null constant */
3415 if (newargs == NIL)
3416 return e; /* first expr */
3418 break;
3419 }
3420 if (expr_is_nonnullable(context->root, (Expr *) e, false))
3421 {
3422 if (newargs == NIL)
3423 return e; /* first expr */
3425 break;
3426 }
3427
3429 }
3430
3431 /*
3432 * If all the arguments were constant null, the result is just
3433 * null
3434 */
3435 if (newargs == NIL)
3436 return (Node *) makeNullConst(coalesceexpr->coalescetype,
3437 -1,
3438 coalesceexpr->coalescecollid);
3439
3440 /*
3441 * If there's exactly one surviving argument, we no longer
3442 * need COALESCE at all: the result is that argument
3443 */
3444 if (list_length(newargs) == 1)
3445 return (Node *) linitial(newargs);
3446
3448 newcoalesce->coalescetype = coalesceexpr->coalescetype;
3449 newcoalesce->coalescecollid = coalesceexpr->coalescecollid;
3450 newcoalesce->args = newargs;
3451 newcoalesce->location = coalesceexpr->location;
3452 return (Node *) newcoalesce;
3453 }
3454 case T_SQLValueFunction:
3455 {
3456 /*
3457 * All variants of SQLValueFunction are stable, so if we are
3458 * estimating the expression's value, we should evaluate the
3459 * current function value. Otherwise just copy.
3460 */
3461 SQLValueFunction *svf = (SQLValueFunction *) node;
3462
3463 if (context->estimate)
3464 return (Node *) evaluate_expr((Expr *) svf,
3465 svf->type,
3466 svf->typmod,
3467 InvalidOid);
3468 else
3469 return copyObject((Node *) svf);
3470 }
3471 case T_FieldSelect:
3472 {
3473 /*
3474 * We can optimize field selection from a whole-row Var into a
3475 * simple Var. (This case won't be generated directly by the
3476 * parser, because ParseComplexProjection short-circuits it.
3477 * But it can arise while simplifying functions.) Also, we
3478 * can optimize field selection from a RowExpr construct, or
3479 * of course from a constant.
3480 *
3481 * However, replacing a whole-row Var in this way has a
3482 * pitfall: if we've already built the rel targetlist for the
3483 * source relation, then the whole-row Var is scheduled to be
3484 * produced by the relation scan, but the simple Var probably
3485 * isn't, which will lead to a failure in setrefs.c. This is
3486 * not a problem when handling simple single-level queries, in
3487 * which expression simplification always happens first. It
3488 * is a risk for lateral references from subqueries, though.
3489 * To avoid such failures, don't optimize uplevel references.
3490 *
3491 * We must also check that the declared type of the field is
3492 * still the same as when the FieldSelect was created --- this
3493 * can change if someone did ALTER COLUMN TYPE on the rowtype.
3494 * If it isn't, we skip the optimization; the case will
3495 * probably fail at runtime, but that's not our problem here.
3496 */
3497 FieldSelect *fselect = (FieldSelect *) node;
3499 Node *arg;
3500
3502 context);
3503 if (arg && IsA(arg, Var) &&
3504 ((Var *) arg)->varattno == InvalidAttrNumber &&
3505 ((Var *) arg)->varlevelsup == 0)
3506 {
3507 if (rowtype_field_matches(((Var *) arg)->vartype,
3508 fselect->fieldnum,
3509 fselect->resulttype,
3510 fselect->resulttypmod,
3511 fselect->resultcollid))
3512 {
3513 Var *newvar;
3514
3515 newvar = makeVar(((Var *) arg)->varno,
3516 fselect->fieldnum,
3517 fselect->resulttype,
3518 fselect->resulttypmod,
3519 fselect->resultcollid,
3520 ((Var *) arg)->varlevelsup);
3521 /* New Var has same OLD/NEW returning as old one */
3522 newvar->varreturningtype = ((Var *) arg)->varreturningtype;
3523 /* New Var is nullable by same rels as the old one */
3524 newvar->varnullingrels = ((Var *) arg)->varnullingrels;
3525 return (Node *) newvar;
3526 }
3527 }
3528 if (arg && IsA(arg, RowExpr))
3529 {
3530 RowExpr *rowexpr = (RowExpr *) arg;
3531
3532 if (fselect->fieldnum > 0 &&
3533 fselect->fieldnum <= list_length(rowexpr->args))
3534 {
3535 Node *fld = (Node *) list_nth(rowexpr->args,
3536 fselect->fieldnum - 1);
3537
3538 if (rowtype_field_matches(rowexpr->row_typeid,
3539 fselect->fieldnum,
3540 fselect->resulttype,
3541 fselect->resulttypmod,
3542 fselect->resultcollid) &&
3543 fselect->resulttype == exprType(fld) &&
3544 fselect->resulttypmod == exprTypmod(fld) &&
3545 fselect->resultcollid == exprCollation(fld))
3546 return fld;
3547 }
3548 }
3550 newfselect->arg = (Expr *) arg;
3551 newfselect->fieldnum = fselect->fieldnum;
3552 newfselect->resulttype = fselect->resulttype;
3553 newfselect->resulttypmod = fselect->resulttypmod;
3554 newfselect->resultcollid = fselect->resultcollid;
3555 if (arg && IsA(arg, Const))
3556 {
3557 Const *con = (Const *) arg;
3558
3560 newfselect->fieldnum,
3561 newfselect->resulttype,
3562 newfselect->resulttypmod,
3563 newfselect->resultcollid))
3565 }
3566 return (Node *) newfselect;
3567 }
3568 case T_NullTest:
3569 {
3570 NullTest *ntest = (NullTest *) node;
3572 Node *arg;
3573
3575 context);
3576 if (ntest->argisrow && arg && IsA(arg, RowExpr))
3577 {
3578 /*
3579 * We break ROW(...) IS [NOT] NULL into separate tests on
3580 * its component fields. This form is usually more
3581 * efficient to evaluate, as well as being more amenable
3582 * to optimization.
3583 */
3584 RowExpr *rarg = (RowExpr *) arg;
3585 List *newargs = NIL;
3586 ListCell *l;
3587
3588 foreach(l, rarg->args)
3589 {
3590 Node *relem = (Node *) lfirst(l);
3591
3592 /*
3593 * A constant field refutes the whole NullTest if it's
3594 * of the wrong nullness; else we can discard it.
3595 */
3596 if (relem && IsA(relem, Const))
3597 {
3598 Const *carg = (Const *) relem;
3599
3600 if (carg->constisnull ?
3601 (ntest->nulltesttype == IS_NOT_NULL) :
3602 (ntest->nulltesttype == IS_NULL))
3603 return makeBoolConst(false, false);
3604 continue;
3605 }
3606
3607 /*
3608 * A proven non-nullable field refutes the whole
3609 * NullTest if the test is IS NULL; else we can
3610 * discard it.
3611 */
3612 if (relem &&
3613 expr_is_nonnullable(context->root, (Expr *) relem,
3614 false))
3615 {
3616 if (ntest->nulltesttype == IS_NULL)
3617 return makeBoolConst(false, false);
3618 continue;
3619 }
3620
3621 /*
3622 * Else, make a scalar (argisrow == false) NullTest
3623 * for this field. Scalar semantics are required
3624 * because IS [NOT] NULL doesn't recurse; see comments
3625 * in ExecEvalRowNullInt().
3626 */
3628 newntest->arg = (Expr *) relem;
3629 newntest->nulltesttype = ntest->nulltesttype;
3630 newntest->argisrow = false;
3631 newntest->location = ntest->location;
3633 }
3634 /* If all the inputs were constants, result is TRUE */
3635 if (newargs == NIL)
3636 return makeBoolConst(true, false);
3637 /* If only one nonconst input, it's the result */
3638 if (list_length(newargs) == 1)
3639 return (Node *) linitial(newargs);
3640 /* Else we need an AND node */
3641 return (Node *) make_andclause(newargs);
3642 }
3643 if (!ntest->argisrow && arg && IsA(arg, Const))
3644 {
3645 Const *carg = (Const *) arg;
3646 bool result;
3647
3648 switch (ntest->nulltesttype)
3649 {
3650 case IS_NULL:
3651 result = carg->constisnull;
3652 break;
3653 case IS_NOT_NULL:
3654 result = !carg->constisnull;
3655 break;
3656 default:
3657 elog(ERROR, "unrecognized nulltesttype: %d",
3658 (int) ntest->nulltesttype);
3659 result = false; /* keep compiler quiet */
3660 break;
3661 }
3662
3663 return makeBoolConst(result, false);
3664 }
3665 if (!ntest->argisrow && arg &&
3666 expr_is_nonnullable(context->root, (Expr *) arg, false))
3667 {
3668 bool result;
3669
3670 switch (ntest->nulltesttype)
3671 {
3672 case IS_NULL:
3673 result = false;
3674 break;
3675 case IS_NOT_NULL:
3676 result = true;
3677 break;
3678 default:
3679 elog(ERROR, "unrecognized nulltesttype: %d",
3680 (int) ntest->nulltesttype);
3681 result = false; /* keep compiler quiet */
3682 break;
3683 }
3684
3685 return makeBoolConst(result, false);
3686 }
3687
3689 newntest->arg = (Expr *) arg;
3690 newntest->nulltesttype = ntest->nulltesttype;
3691 newntest->argisrow = ntest->argisrow;
3692 newntest->location = ntest->location;
3693 return (Node *) newntest;
3694 }
3695 case T_BooleanTest:
3696 {
3697 /*
3698 * This case could be folded into the generic handling used
3699 * for ArrayExpr etc. But because the simplification logic is
3700 * so trivial, applying evaluate_expr() to perform it would be
3701 * a heavy overhead. BooleanTest is probably common enough to
3702 * justify keeping this bespoke implementation.
3703 */
3704 BooleanTest *btest = (BooleanTest *) node;
3706 Node *arg;
3707
3709 context);
3710 if (arg && IsA(arg, Const))
3711 {
3712 /*
3713 * If arg is Const, simplify to constant.
3714 */
3715 Const *carg = (Const *) arg;
3716 bool result;
3717
3718 switch (btest->booltesttype)
3719 {
3720 case IS_TRUE:
3721 result = (!carg->constisnull &&
3722 DatumGetBool(carg->constvalue));
3723 break;
3724 case IS_NOT_TRUE:
3725 result = (carg->constisnull ||
3726 !DatumGetBool(carg->constvalue));
3727 break;
3728 case IS_FALSE:
3729 result = (!carg->constisnull &&
3730 !DatumGetBool(carg->constvalue));
3731 break;
3732 case IS_NOT_FALSE:
3733 result = (carg->constisnull ||
3734 DatumGetBool(carg->constvalue));
3735 break;
3736 case IS_UNKNOWN:
3737 result = carg->constisnull;
3738 break;
3739 case IS_NOT_UNKNOWN:
3740 result = !carg->constisnull;
3741 break;
3742 default:
3743 elog(ERROR, "unrecognized booltesttype: %d",
3744 (int) btest->booltesttype);
3745 result = false; /* keep compiler quiet */
3746 break;
3747 }
3748
3749 return makeBoolConst(result, false);
3750 }
3751 if (arg && expr_is_nonnullable(context->root, (Expr *) arg, false))
3752 {
3753 /*
3754 * If arg is proven non-nullable, simplify to boolean
3755 * expression or constant.
3756 */
3757 switch (btest->booltesttype)
3758 {
3759 case IS_TRUE:
3760 case IS_NOT_FALSE:
3761 return arg;
3762
3763 case IS_FALSE:
3764 case IS_NOT_TRUE:
3765 return (Node *) make_notclause((Expr *) arg);
3766
3767 case IS_UNKNOWN:
3768 return makeBoolConst(false, false);
3769
3770 case IS_NOT_UNKNOWN:
3771 return makeBoolConst(true, false);
3772
3773 default:
3774 elog(ERROR, "unrecognized booltesttype: %d",
3775 (int) btest->booltesttype);
3776 break;
3777 }
3778 }
3779
3781 newbtest->arg = (Expr *) arg;
3782 newbtest->booltesttype = btest->booltesttype;
3783 newbtest->location = btest->location;
3784 return (Node *) newbtest;
3785 }
3786 case T_CoerceToDomain:
3787 {
3788 /*
3789 * If the domain currently has no constraints, we replace the
3790 * CoerceToDomain node with a simple RelabelType, which is
3791 * both far faster to execute and more amenable to later
3792 * optimization. We must then mark the plan as needing to be
3793 * rebuilt if the domain's constraints change.
3794 *
3795 * Also, in estimation mode, always replace CoerceToDomain
3796 * nodes, effectively assuming that the coercion will succeed.
3797 */
3800 Node *arg;
3801
3803 context);
3804 if (context->estimate ||
3805 !DomainHasConstraints(cdomain->resulttype))
3806 {
3807 /* Record dependency, if this isn't estimation mode */
3808 if (context->root && !context->estimate)
3809 record_plan_type_dependency(context->root,
3810 cdomain->resulttype);
3811
3812 /* Generate RelabelType to substitute for CoerceToDomain */
3813 return applyRelabelType(arg,
3814 cdomain->resulttype,
3815 cdomain->resulttypmod,
3816 cdomain->resultcollid,
3817 cdomain->coercionformat,
3818 cdomain->location,
3819 true);
3820 }
3821
3823 newcdomain->arg = (Expr *) arg;
3824 newcdomain->resulttype = cdomain->resulttype;
3825 newcdomain->resulttypmod = cdomain->resulttypmod;
3826 newcdomain->resultcollid = cdomain->resultcollid;
3827 newcdomain->coercionformat = cdomain->coercionformat;
3828 newcdomain->location = cdomain->location;
3829 return (Node *) newcdomain;
3830 }
3831 case T_PlaceHolderVar:
3832
3833 /*
3834 * In estimation mode, just strip the PlaceHolderVar node
3835 * altogether; this amounts to estimating that the contained value
3836 * won't be forced to null by an outer join. In regular mode we
3837 * just use the default behavior (ie, simplify the expression but
3838 * leave the PlaceHolderVar node intact).
3839 */
3840 if (context->estimate)
3841 {
3842 PlaceHolderVar *phv = (PlaceHolderVar *) node;
3843
3844 return eval_const_expressions_mutator((Node *) phv->phexpr,
3845 context);
3846 }
3847 break;
3849 {
3851 Node *arg;
3853
3855 context);
3856
3858 newcre->resulttype = cre->resulttype;
3859 newcre->convertformat = cre->convertformat;
3860 newcre->location = cre->location;
3861
3862 /*
3863 * In case of a nested ConvertRowtypeExpr, we can convert the
3864 * leaf row directly to the topmost row format without any
3865 * intermediate conversions. (This works because
3866 * ConvertRowtypeExpr is used only for child->parent
3867 * conversion in inheritance trees, which works by exact match
3868 * of column name, and a column absent in an intermediate
3869 * result can't be present in the final result.)
3870 *
3871 * No need to check more than one level deep, because the
3872 * above recursion will have flattened anything else.
3873 */
3874 if (arg != NULL && IsA(arg, ConvertRowtypeExpr))
3875 {
3877
3878 arg = (Node *) argcre->arg;
3879
3880 /*
3881 * Make sure an outer implicit conversion can't hide an
3882 * inner explicit one.
3883 */
3884 if (newcre->convertformat == COERCE_IMPLICIT_CAST)
3885 newcre->convertformat = argcre->convertformat;
3886 }
3887
3888 newcre->arg = (Expr *) arg;
3889
3890 if (arg != NULL && IsA(arg, Const))
3891 return ece_evaluate_expr((Node *) newcre);
3892 return (Node *) newcre;
3893 }
3894 default:
3895 break;
3896 }
3897
3898 /*
3899 * For any node type not handled above, copy the node unchanged but
3900 * const-simplify its subexpressions. This is the correct thing for node
3901 * types whose behavior might change between planning and execution, such
3902 * as CurrentOfExpr. It's also a safe default for new node types not
3903 * known to this routine.
3904 */
3905 return ece_generic_processing(node);
3906}
3907
3908/*
3909 * Subroutine for eval_const_expressions: check for non-Const nodes.
3910 *
3911 * We can abort recursion immediately on finding a non-Const node. This is
3912 * critical for performance, else eval_const_expressions_mutator would take
3913 * O(N^2) time on non-simplifiable trees. However, we do need to descend
3914 * into List nodes since expression_tree_walker sometimes invokes the walker
3915 * function directly on List subtrees.
3916 */
3917static bool
3918contain_non_const_walker(Node *node, void *context)
3919{
3920 if (node == NULL)
3921 return false;
3922 if (IsA(node, Const))
3923 return false;
3924 if (IsA(node, List))
3925 return expression_tree_walker(node, contain_non_const_walker, context);
3926 /* Otherwise, abort the tree traversal and return true */
3927 return true;
3928}
3929
3930/*
3931 * Subroutine for eval_const_expressions: check if a function is OK to evaluate
3932 */
3933static bool
3935{
3936 char provolatile = func_volatile(funcid);
3937
3938 /*
3939 * Ordinarily we are only allowed to simplify immutable functions. But for
3940 * purposes of estimation, we consider it okay to simplify functions that
3941 * are merely stable; the risk that the result might change from planning
3942 * time to execution time is worth taking in preference to not being able
3943 * to estimate the value at all.
3944 */
3946 return true;
3947 if (context->estimate && provolatile == PROVOLATILE_STABLE)
3948 return true;
3949 return false;
3950}
3951
3952/*
3953 * Subroutine for eval_const_expressions: process arguments of an OR clause
3954 *
3955 * This includes flattening of nested ORs as well as recursion to
3956 * eval_const_expressions to simplify the OR arguments.
3957 *
3958 * After simplification, OR arguments are handled as follows:
3959 * non constant: keep
3960 * FALSE: drop (does not affect result)
3961 * TRUE: force result to TRUE
3962 * NULL: keep only one
3963 * We must keep one NULL input because OR expressions evaluate to NULL when no
3964 * input is TRUE and at least one is NULL. We don't actually include the NULL
3965 * here, that's supposed to be done by the caller.
3966 *
3967 * The output arguments *haveNull and *forceTrue must be initialized false
3968 * by the caller. They will be set true if a NULL constant or TRUE constant,
3969 * respectively, is detected anywhere in the argument list.
3970 */
3971static List *
3974 bool *haveNull, bool *forceTrue)
3975{
3976 List *newargs = NIL;
3978
3979 /*
3980 * We want to ensure that any OR immediately beneath another OR gets
3981 * flattened into a single OR-list, so as to simplify later reasoning.
3982 *
3983 * To avoid stack overflow from recursion of eval_const_expressions, we
3984 * resort to some tenseness here: we keep a list of not-yet-processed
3985 * inputs, and handle flattening of nested ORs by prepending to the to-do
3986 * list instead of recursing. Now that the parser generates N-argument
3987 * ORs from simple lists, this complexity is probably less necessary than
3988 * it once was, but we might as well keep the logic.
3989 */
3991 while (unprocessed_args)
3992 {
3994
3996
3997 /* flatten nested ORs as per above comment */
3998 if (is_orclause(arg))
3999 {
4000 List *subargs = ((BoolExpr *) arg)->args;
4002
4004 /* perhaps-overly-tense code to avoid leaking old lists */
4006 continue;
4007 }
4008
4009 /* If it's not an OR, simplify it */
4011
4012 /*
4013 * It is unlikely but not impossible for simplification of a non-OR
4014 * clause to produce an OR. Recheck, but don't be too tense about it
4015 * since it's not a mainstream case. In particular we don't worry
4016 * about const-simplifying the input twice, nor about list leakage.
4017 */
4018 if (is_orclause(arg))
4019 {
4020 List *subargs = ((BoolExpr *) arg)->args;
4021
4023 continue;
4024 }
4025
4026 /*
4027 * OK, we have a const-simplified non-OR argument. Process it per
4028 * comments above.
4029 */
4030 if (IsA(arg, Const))
4031 {
4032 Const *const_input = (Const *) arg;
4033
4034 if (const_input->constisnull)
4035 *haveNull = true;
4036 else if (DatumGetBool(const_input->constvalue))
4037 {
4038 *forceTrue = true;
4039
4040 /*
4041 * Once we detect a TRUE result we can just exit the loop
4042 * immediately. However, if we ever add a notion of
4043 * non-removable functions, we'd need to keep scanning.
4044 */
4045 return NIL;
4046 }
4047 /* otherwise, we can drop the constant-false input */
4048 continue;
4049 }
4050
4051 /* else emit the simplified arg into the result list */
4053 }
4054
4055 return newargs;
4056}
4057
4058/*
4059 * Subroutine for eval_const_expressions: process arguments of an AND clause
4060 *
4061 * This includes flattening of nested ANDs as well as recursion to
4062 * eval_const_expressions to simplify the AND arguments.
4063 *
4064 * After simplification, AND arguments are handled as follows:
4065 * non constant: keep
4066 * TRUE: drop (does not affect result)
4067 * FALSE: force result to FALSE
4068 * NULL: keep only one
4069 * We must keep one NULL input because AND expressions evaluate to NULL when
4070 * no input is FALSE and at least one is NULL. We don't actually include the
4071 * NULL here, that's supposed to be done by the caller.
4072 *
4073 * The output arguments *haveNull and *forceFalse must be initialized false
4074 * by the caller. They will be set true if a null constant or false constant,
4075 * respectively, is detected anywhere in the argument list.
4076 */
4077static List *
4080 bool *haveNull, bool *forceFalse)
4081{
4082 List *newargs = NIL;
4084
4085 /* See comments in simplify_or_arguments */
4087 while (unprocessed_args)
4088 {
4090
4092
4093 /* flatten nested ANDs as per above comment */
4094 if (is_andclause(arg))
4095 {
4096 List *subargs = ((BoolExpr *) arg)->args;
4098
4100 /* perhaps-overly-tense code to avoid leaking old lists */
4102 continue;
4103 }
4104
4105 /* If it's not an AND, simplify it */
4107
4108 /*
4109 * It is unlikely but not impossible for simplification of a non-AND
4110 * clause to produce an AND. Recheck, but don't be too tense about it
4111 * since it's not a mainstream case. In particular we don't worry
4112 * about const-simplifying the input twice, nor about list leakage.
4113 */
4114 if (is_andclause(arg))
4115 {
4116 List *subargs = ((BoolExpr *) arg)->args;
4117
4119 continue;
4120 }
4121
4122 /*
4123 * OK, we have a const-simplified non-AND argument. Process it per
4124 * comments above.
4125 */
4126 if (IsA(arg, Const))
4127 {
4128 Const *const_input = (Const *) arg;
4129
4130 if (const_input->constisnull)
4131 *haveNull = true;
4132 else if (!DatumGetBool(const_input->constvalue))
4133 {
4134 *forceFalse = true;
4135
4136 /*
4137 * Once we detect a FALSE result we can just exit the loop
4138 * immediately. However, if we ever add a notion of
4139 * non-removable functions, we'd need to keep scanning.
4140 */
4141 return NIL;
4142 }
4143 /* otherwise, we can drop the constant-true input */
4144 continue;
4145 }
4146
4147 /* else emit the simplified arg into the result list */
4149 }
4150
4151 return newargs;
4152}
4153
4154/*
4155 * Subroutine for eval_const_expressions: try to simplify boolean equality
4156 * or inequality condition
4157 *
4158 * Inputs are the operator OID and the simplified arguments to the operator.
4159 * Returns a simplified expression if successful, or NULL if cannot
4160 * simplify the expression.
4161 *
4162 * The idea here is to reduce "x = true" to "x" and "x = false" to "NOT x",
4163 * or similarly "x <> true" to "NOT x" and "x <> false" to "x".
4164 * This is only marginally useful in itself, but doing it in constant folding
4165 * ensures that we will recognize these forms as being equivalent in, for
4166 * example, partial index matching.
4167 *
4168 * We come here only if simplify_function has failed; therefore we cannot
4169 * see two constant inputs, nor a constant-NULL input.
4170 */
4171static Node *
4173{
4174 Node *leftop;
4175 Node *rightop;
4176
4177 Assert(list_length(args) == 2);
4178 leftop = linitial(args);
4179 rightop = lsecond(args);
4180 if (leftop && IsA(leftop, Const))
4181 {
4182 Assert(!((Const *) leftop)->constisnull);
4183 if (opno == BooleanEqualOperator)
4184 {
4185 if (DatumGetBool(((Const *) leftop)->constvalue))
4186 return rightop; /* true = foo */
4187 else
4188 return negate_clause(rightop); /* false = foo */
4189 }
4190 else
4191 {
4192 if (DatumGetBool(((Const *) leftop)->constvalue))
4193 return negate_clause(rightop); /* true <> foo */
4194 else
4195 return rightop; /* false <> foo */
4196 }
4197 }
4198 if (rightop && IsA(rightop, Const))
4199 {
4201 if (opno == BooleanEqualOperator)
4202 {
4204 return leftop; /* foo = true */
4205 else
4206 return negate_clause(leftop); /* foo = false */
4207 }
4208 else
4209 {
4211 return negate_clause(leftop); /* foo <> true */
4212 else
4213 return leftop; /* foo <> false */
4214 }
4215 }
4216 return NULL;
4217}
4218
4219/*
4220 * Subroutine for eval_const_expressions: try to simplify a function call
4221 * (which might originally have been an operator; we don't care)
4222 *
4223 * Inputs are the function OID, actual result type OID (which is needed for
4224 * polymorphic functions), result typmod, result collation, the input
4225 * collation to use for the function, the original argument list (not
4226 * const-simplified yet, unless process_args is false), and some flags;
4227 * also the context data for eval_const_expressions.
4228 *
4229 * Returns a simplified expression if successful, or NULL if cannot
4230 * simplify the function call.
4231 *
4232 * This function is also responsible for converting named-notation argument
4233 * lists into positional notation and/or adding any needed default argument
4234 * expressions; which is a bit grotty, but it avoids extra fetches of the
4235 * function's pg_proc tuple. For this reason, the args list is
4236 * pass-by-reference. Conversion and const-simplification of the args list
4237 * will be done even if simplification of the function call itself is not
4238 * possible.
4239 */
4240static Expr *
4241simplify_function(Oid funcid, Oid result_type, int32 result_typmod,
4243 bool funcvariadic, bool process_args, bool allow_non_const,
4245{
4246 List *args = *args_p;
4249 Expr *newexpr;
4250
4251 /*
4252 * We have three strategies for simplification: execute the function to
4253 * deliver a constant result, use a transform function to generate a
4254 * substitute node tree, or expand in-line the body of the function
4255 * definition (which only works for simple SQL-language functions, but
4256 * that is a common case). Each case needs access to the function's
4257 * pg_proc tuple, so fetch it just once.
4258 *
4259 * Note: the allow_non_const flag suppresses both the second and third
4260 * strategies; so if !allow_non_const, simplify_function can only return a
4261 * Const or NULL. Argument-list rewriting happens anyway, though.
4262 */
4265 elog(ERROR, "cache lookup failed for function %u", funcid);
4267
4268 /*
4269 * Process the function arguments, unless the caller did it already.
4270 *
4271 * Here we must deal with named or defaulted arguments, and then
4272 * recursively apply eval_const_expressions to the whole argument list.
4273 */
4274 if (process_args)
4275 {
4276 args = expand_function_arguments(args, false, result_type, func_tuple);
4279 context);
4280 /* Argument processing done, give it back to the caller */
4281 *args_p = args;
4282 }
4283
4284 /* Now attempt simplification of the function call proper. */
4285
4286 newexpr = evaluate_function(funcid, result_type, result_typmod,
4288 args, funcvariadic,
4289 func_tuple, context);
4290
4291 if (!newexpr && allow_non_const && OidIsValid(func_form->prosupport))
4292 {
4293 /*
4294 * Build a SupportRequestSimplify node to pass to the support
4295 * function, pointing to a dummy FuncExpr node containing the
4296 * simplified arg list. We use this approach to present a uniform
4297 * interface to the support function regardless of how the target
4298 * function is actually being invoked.
4299 */
4302
4303 fexpr.xpr.type = T_FuncExpr;
4304 fexpr.funcid = funcid;
4305 fexpr.funcresulttype = result_type;
4306 fexpr.funcretset = func_form->proretset;
4307 fexpr.funcvariadic = funcvariadic;
4308 fexpr.funcformat = COERCE_EXPLICIT_CALL;
4309 fexpr.funccollid = result_collid;
4310 fexpr.inputcollid = input_collid;
4311 fexpr.args = args;
4312 fexpr.location = -1;
4313
4315 req.root = context->root;
4316 req.fcall = &fexpr;
4317
4318 newexpr = (Expr *)
4320 PointerGetDatum(&req)));
4321
4322 /* catch a possible API misunderstanding */
4323 Assert(newexpr != (Expr *) &fexpr);
4324 }
4325
4326 if (!newexpr && allow_non_const)
4327 newexpr = inline_function(funcid, result_type, result_collid,
4329 func_tuple, context);
4330
4332
4333 return newexpr;
4334}
4335
4336/*
4337 * simplify_aggref
4338 * Call the Aggref.aggfnoid's prosupport function to allow it to
4339 * determine if simplification of the Aggref is possible. Returns the
4340 * newly simplified node if conversion took place; otherwise, returns the
4341 * original Aggref.
4342 *
4343 * See SupportRequestSimplifyAggref comments in supportnodes.h for further
4344 * details.
4345 */
4346static Node *
4348{
4350
4352 {
4354 Node *newnode;
4355
4356 /*
4357 * Build a SupportRequestSimplifyAggref node to pass to the support
4358 * function.
4359 */
4361 req.root = context->root;
4362 req.aggref = aggref;
4363
4365 PointerGetDatum(&req)));
4366
4367 /*
4368 * We expect the support function to return either a new Node or NULL
4369 * (when simplification isn't possible).
4370 */
4371 Assert(newnode != (Node *) aggref || newnode == NULL);
4372
4373 if (newnode != NULL)
4374 return newnode;
4375 }
4376
4377 return (Node *) aggref;
4378}
4379
4380/*
4381 * var_is_nonnullable: check to see if the Var cannot be NULL
4382 *
4383 * If the Var is defined NOT NULL and meanwhile is not nulled by any outer
4384 * joins or grouping sets, then we can know that it cannot be NULL.
4385 *
4386 * use_rel_info indicates whether the corresponding RelOptInfo is available for
4387 * use.
4388 */
4389bool
4391{
4392 Bitmapset *notnullattnums = NULL;
4393
4394 Assert(IsA(var, Var));
4395
4396 /* skip upper-level Vars */
4397 if (var->varlevelsup != 0)
4398 return false;
4399
4400 /* could the Var be nulled by any outer joins or grouping sets? */
4401 if (!bms_is_empty(var->varnullingrels))
4402 return false;
4403
4404 /* system columns cannot be NULL */
4405 if (var->varattno < 0)
4406 return true;
4407
4408 /*
4409 * Check if the Var is defined as NOT NULL. We retrieve the column NOT
4410 * NULL constraint information from the corresponding RelOptInfo if it is
4411 * available; otherwise, we search the hash table for this information.
4412 */
4413 if (use_rel_info)
4414 {
4415 RelOptInfo *rel = find_base_rel(root, var->varno);
4416
4417 notnullattnums = rel->notnullattnums;
4418 }
4419 else
4420 {
4422
4423 /*
4424 * We must skip inheritance parent tables, as some child tables may
4425 * have a NOT NULL constraint for a column while others may not. This
4426 * cannot happen with partitioned tables, though.
4427 */
4428 if (rte->inh && rte->relkind != RELKIND_PARTITIONED_TABLE)
4429 return false;
4430
4431 notnullattnums = find_relation_notnullatts(root, rte->relid);
4432 }
4433
4434 if (var->varattno > 0 &&
4435 bms_is_member(var->varattno, notnullattnums))
4436 return true;
4437
4438 return false;
4439}
4440
4441/*
4442 * expr_is_nonnullable: check to see if the Expr cannot be NULL
4443 *
4444 * Returns true iff the given 'expr' cannot produce SQL NULLs.
4445 *
4446 * If 'use_rel_info' is true, nullability of Vars is checked via the
4447 * corresponding RelOptInfo for the given Var. Some callers require
4448 * nullability information before RelOptInfos are generated. These should
4449 * pass 'use_rel_info' as false.
4450 *
4451 * For now, we support only a limited set of expression types. Support for
4452 * additional node types can be added in the future.
4453 */
4454bool
4456{
4457 /* since this function recurses, it could be driven to stack overflow */
4459
4460 switch (nodeTag(expr))
4461 {
4462 case T_Var:
4463 {
4464 if (root)
4465 return var_is_nonnullable(root, (Var *) expr, use_rel_info);
4466 }
4467 break;
4468 case T_Const:
4469 return !((Const *) expr)->constisnull;
4470 case T_CoalesceExpr:
4471 {
4472 /*
4473 * A CoalesceExpr returns NULL if and only if all its
4474 * arguments are NULL. Therefore, we can determine that a
4475 * CoalesceExpr cannot be NULL if at least one of its
4476 * arguments can be proven non-nullable.
4477 */
4479
4481 {
4483 return true;
4484 }
4485 }
4486 break;
4487 case T_MinMaxExpr:
4488 {
4489 /*
4490 * Like CoalesceExpr, a MinMaxExpr returns NULL only if all
4491 * its arguments evaluate to NULL.
4492 */
4493 MinMaxExpr *minmaxexpr = (MinMaxExpr *) expr;
4494
4496 {
4498 return true;
4499 }
4500 }
4501 break;
4502 case T_CaseExpr:
4503 {
4504 /*
4505 * A CASE expression is non-nullable if all branch results are
4506 * non-nullable. We must also verify that the default result
4507 * (ELSE) exists and is non-nullable.
4508 */
4509 CaseExpr *caseexpr = (CaseExpr *) expr;
4510
4511 /* The default result must be present and non-nullable */
4512 if (caseexpr->defresult == NULL ||
4514 return false;
4515
4516 /* All branch results must be non-nullable */
4518 {
4520 return false;
4521 }
4522
4523 return true;
4524 }
4525 break;
4526 case T_ArrayExpr:
4527 {
4528 /*
4529 * An ARRAY[] expression always returns a valid Array object,
4530 * even if it is empty (ARRAY[]) or contains NULLs
4531 * (ARRAY[NULL]). It never evaluates to a SQL NULL.
4532 */
4533 return true;
4534 }
4535 case T_NullTest:
4536 {
4537 /*
4538 * An IS NULL / IS NOT NULL expression always returns a
4539 * boolean value. It never returns SQL NULL.
4540 */
4541 return true;
4542 }
4543 case T_BooleanTest:
4544 {
4545 /*
4546 * A BooleanTest expression always evaluates to a boolean
4547 * value. It never returns SQL NULL.
4548 */
4549 return true;
4550 }
4551 case T_DistinctExpr:
4552 {
4553 /*
4554 * IS DISTINCT FROM never returns NULL, effectively acting as
4555 * though NULL were a normal data value.
4556 */
4557 return true;
4558 }
4559 case T_RelabelType:
4560 {
4561 /*
4562 * RelabelType does not change the nullability of the data.
4563 * The result is non-nullable if and only if the argument is
4564 * non-nullable.
4565 */
4566 return expr_is_nonnullable(root, ((RelabelType *) expr)->arg,
4567 use_rel_info);
4568 }
4569 default:
4570 break;
4571 }
4572
4573 return false;
4574}
4575
4576/*
4577 * expand_function_arguments: convert named-notation args to positional args
4578 * and/or insert default args, as needed
4579 *
4580 * Returns a possibly-transformed version of the args list.
4581 *
4582 * If include_out_arguments is true, then the args list and the result
4583 * include OUT arguments.
4584 *
4585 * The expected result type of the call must be given, for sanity-checking
4586 * purposes. Also, we ask the caller to provide the function's actual
4587 * pg_proc tuple, not just its OID.
4588 *
4589 * If we need to change anything, the input argument list is copied, not
4590 * modified.
4591 *
4592 * Note: this gets applied to operator argument lists too, even though the
4593 * cases it handles should never occur there. This should be OK since it
4594 * will fall through very quickly if there's nothing to do.
4595 */
4596List *
4598 Oid result_type, HeapTuple func_tuple)
4599{
4601 Oid *proargtypes = funcform->proargtypes.values;
4602 int pronargs = funcform->pronargs;
4603 bool has_named_args = false;
4604 ListCell *lc;
4605
4606 /*
4607 * If we are asked to match to OUT arguments, then use the proallargtypes
4608 * array (which includes those); otherwise use proargtypes (which
4609 * doesn't). Of course, if proallargtypes is null, we always use
4610 * proargtypes. (Fetching proallargtypes is annoyingly expensive
4611 * considering that we may have nothing to do here, but fortunately the
4612 * common case is include_out_arguments == false.)
4613 */
4615 {
4617 bool isNull;
4618
4621 &isNull);
4622 if (!isNull)
4623 {
4625
4626 pronargs = ARR_DIMS(arr)[0];
4627 if (ARR_NDIM(arr) != 1 ||
4628 pronargs < 0 ||
4629 ARR_HASNULL(arr) ||
4630 ARR_ELEMTYPE(arr) != OIDOID)
4631 elog(ERROR, "proallargtypes is not a 1-D Oid array or it contains nulls");
4632 Assert(pronargs >= funcform->pronargs);
4633 proargtypes = (Oid *) ARR_DATA_PTR(arr);
4634 }
4635 }
4636
4637 /* Do we have any named arguments? */
4638 foreach(lc, args)
4639 {
4640 Node *arg = (Node *) lfirst(lc);
4641
4642 if (IsA(arg, NamedArgExpr))
4643 {
4644 has_named_args = true;
4645 break;
4646 }
4647 }
4648
4649 /* If so, we must apply reorder_function_arguments */
4650 if (has_named_args)
4651 {
4653 /* Recheck argument types and add casts if needed */
4654 recheck_cast_function_args(args, result_type,
4656 func_tuple);
4657 }
4658 else if (list_length(args) < pronargs)
4659 {
4660 /* No named args, but we seem to be short some defaults */
4662 /* Recheck argument types and add casts if needed */
4663 recheck_cast_function_args(args, result_type,
4665 func_tuple);
4666 }
4667
4668 return args;
4669}
4670
4671/*
4672 * reorder_function_arguments: convert named-notation args to positional args
4673 *
4674 * This function also inserts default argument values as needed, since it's
4675 * impossible to form a truly valid positional call without that.
4676 */
4677static List *
4679{
4681 int nargsprovided = list_length(args);
4683 ListCell *lc;
4684 int i;
4685
4688 elog(ERROR, "too many function arguments");
4689 memset(argarray, 0, pronargs * sizeof(Node *));
4690
4691 /* Deconstruct the argument list into an array indexed by argnumber */
4692 i = 0;
4693 foreach(lc, args)
4694 {
4695 Node *arg = (Node *) lfirst(lc);
4696
4697 if (!IsA(arg, NamedArgExpr))
4698 {
4699 /* positional argument, assumed to precede all named args */
4700 Assert(argarray[i] == NULL);
4701 argarray[i++] = arg;
4702 }
4703 else
4704 {
4706
4707 Assert(na->argnumber >= 0 && na->argnumber < pronargs);
4708 Assert(argarray[na->argnumber] == NULL);
4709 argarray[na->argnumber] = (Node *) na->arg;
4710 }
4711 }
4712
4713 /*
4714 * Fetch default expressions, if needed, and insert into array at proper
4715 * locations (they aren't necessarily consecutive or all used)
4716 */
4717 if (nargsprovided < pronargs)
4718 {
4720
4721 i = pronargs - funcform->pronargdefaults;
4722 foreach(lc, defaults)
4723 {
4724 if (argarray[i] == NULL)
4725 argarray[i] = (Node *) lfirst(lc);
4726 i++;
4727 }
4728 }
4729
4730 /* Now reconstruct the args list in proper order */
4731 args = NIL;
4732 for (i = 0; i < pronargs; i++)
4733 {
4734 Assert(argarray[i] != NULL);
4735 args = lappend(args, argarray[i]);
4736 }
4737
4738 return args;
4739}
4740
4741/*
4742 * add_function_defaults: add missing function arguments from its defaults
4743 *
4744 * This is used only when the argument list was positional to begin with,
4745 * and so we know we just need to add defaults at the end.
4746 */
4747static List *
4749{
4750 int nargsprovided = list_length(args);
4751 List *defaults;
4752 int ndelete;
4753
4754 /* Get all the default expressions from the pg_proc tuple */
4756
4757 /* Delete any unused defaults from the list */
4758 ndelete = nargsprovided + list_length(defaults) - pronargs;
4759 if (ndelete < 0)
4760 elog(ERROR, "not enough default arguments");
4761 if (ndelete > 0)
4762 defaults = list_delete_first_n(defaults, ndelete);
4763
4764 /* And form the combined argument list, not modifying the input list */
4765 return list_concat_copy(args, defaults);
4766}
4767
4768/*
4769 * fetch_function_defaults: get function's default arguments as expression list
4770 */
4771static List *
4773{
4774 List *defaults;
4776 char *str;
4777
4781 defaults = castNode(List, stringToNode(str));
4782 pfree(str);
4783 return defaults;
4784}
4785
4786/*
4787 * recheck_cast_function_args: recheck function args and typecast as needed
4788 * after adding defaults.
4789 *
4790 * It is possible for some of the defaulted arguments to be polymorphic;
4791 * therefore we can't assume that the default expressions have the correct
4792 * data types already. We have to re-resolve polymorphics and do coercion
4793 * just like the parser did.
4794 *
4795 * This should be a no-op if there are no polymorphic arguments,
4796 * but we do it anyway to be sure.
4797 *
4798 * Note: if any casts are needed, the args list is modified in-place;
4799 * caller should have already copied the list structure.
4800 */
4801static void
4802recheck_cast_function_args(List *args, Oid result_type,
4803 Oid *proargtypes, int pronargs,
4805{
4807 int nargs;
4810 Oid rettype;
4811 ListCell *lc;
4812
4813 if (list_length(args) > FUNC_MAX_ARGS)
4814 elog(ERROR, "too many function arguments");
4815 nargs = 0;
4816 foreach(lc, args)
4817 {
4818 actual_arg_types[nargs++] = exprType((Node *) lfirst(lc));
4819 }
4820 Assert(nargs == pronargs);
4824 nargs,
4825 funcform->prorettype,
4826 false);
4827 /* let's just check we got the same answer as the parser did ... */
4828 if (rettype != result_type)
4829 elog(ERROR, "function's resolved result type changed during planning");
4830
4831 /* perform any necessary typecasting of arguments */
4833}
4834
4835/*
4836 * evaluate_function: try to pre-evaluate a function call
4837 *
4838 * We can do this if the function is strict and has any constant-null inputs
4839 * (just return a null constant), or if the function is immutable and has all
4840 * constant inputs (call it and return the result as a Const node). In
4841 * estimation mode we are willing to pre-evaluate stable functions too.
4842 *
4843 * Returns a simplified expression if successful, or NULL if cannot
4844 * simplify the function.
4845 */
4846static Expr *
4847evaluate_function(Oid funcid, Oid result_type, int32 result_typmod,
4849 bool funcvariadic,
4852{
4854 bool has_nonconst_input = false;
4855 bool has_null_input = false;
4856 ListCell *arg;
4858
4859 /*
4860 * Can't simplify if it returns a set.
4861 */
4862 if (funcform->proretset)
4863 return NULL;
4864
4865 /*
4866 * Can't simplify if it returns RECORD. The immediate problem is that it
4867 * will be needing an expected tupdesc which we can't supply here.
4868 *
4869 * In the case where it has OUT parameters, we could build an expected
4870 * tupdesc from those, but there may be other gotchas lurking. In
4871 * particular, if the function were to return NULL, we would produce a
4872 * null constant with no remaining indication of which concrete record
4873 * type it is. For now, seems best to leave the function call unreduced.
4874 */
4875 if (funcform->prorettype == RECORDOID)
4876 return NULL;
4877
4878 /*
4879 * Check for constant inputs and especially constant-NULL inputs.
4880 */
4881 foreach(arg, args)
4882 {
4883 if (IsA(lfirst(arg), Const))
4885 else
4886 has_nonconst_input = true;
4887 }
4888
4889 /*
4890 * If the function is strict and has a constant-NULL input, it will never
4891 * be called at all, so we can replace the call by a NULL constant, even
4892 * if there are other inputs that aren't constant, and even if the
4893 * function is not otherwise immutable.
4894 */
4895 if (funcform->proisstrict && has_null_input)
4896 return (Expr *) makeNullConst(result_type, result_typmod,
4898
4899 /*
4900 * Otherwise, can simplify only if all inputs are constants. (For a
4901 * non-strict function, constant NULL inputs are treated the same as
4902 * constant non-NULL inputs.)
4903 */
4905 return NULL;
4906
4907 /*
4908 * Ordinarily we are only allowed to simplify immutable functions. But for
4909 * purposes of estimation, we consider it okay to simplify functions that
4910 * are merely stable; the risk that the result might change from planning
4911 * time to execution time is worth taking in preference to not being able
4912 * to estimate the value at all.
4913 */
4914 if (funcform->provolatile == PROVOLATILE_IMMUTABLE)
4915 /* okay */ ;
4916 else if (context->estimate && funcform->provolatile == PROVOLATILE_STABLE)
4917 /* okay */ ;
4918 else
4919 return NULL;
4920
4921 /*
4922 * OK, looks like we can simplify this operator/function.
4923 *
4924 * Build a new FuncExpr node containing the already-simplified arguments.
4925 */
4927 newexpr->funcid = funcid;
4928 newexpr->funcresulttype = result_type;
4929 newexpr->funcretset = false;
4930 newexpr->funcvariadic = funcvariadic;
4931 newexpr->funcformat = COERCE_EXPLICIT_CALL; /* doesn't matter */
4932 newexpr->funccollid = result_collid; /* doesn't matter */
4933 newexpr->inputcollid = input_collid;
4934 newexpr->args = args;
4935 newexpr->location = -1;
4936
4937 return evaluate_expr((Expr *) newexpr, result_type, result_typmod,
4939}
4940
4941/*
4942 * inline_function: try to expand a function call inline
4943 *
4944 * If the function is a sufficiently simple SQL-language function
4945 * (just "SELECT expression"), then we can inline it and avoid the rather
4946 * high per-call overhead of SQL functions. Furthermore, this can expose
4947 * opportunities for constant-folding within the function expression.
4948 *
4949 * We have to beware of some special cases however. A directly or
4950 * indirectly recursive function would cause us to recurse forever,
4951 * so we keep track of which functions we are already expanding and
4952 * do not re-expand them. Also, if a parameter is used more than once
4953 * in the SQL-function body, we require it not to contain any volatile
4954 * functions (volatiles might deliver inconsistent answers) nor to be
4955 * unreasonably expensive to evaluate. The expensiveness check not only
4956 * prevents us from doing multiple evaluations of an expensive parameter
4957 * at runtime, but is a safety value to limit growth of an expression due
4958 * to repeated inlining.
4959 *
4960 * We must also beware of changing the volatility or strictness status of
4961 * functions by inlining them.
4962 *
4963 * Also, at the moment we can't inline functions returning RECORD. This
4964 * doesn't work in the general case because it discards information such
4965 * as OUT-parameter declarations.
4966 *
4967 * Also, context-dependent expression nodes in the argument list are trouble.
4968 *
4969 * Returns a simplified expression if successful, or NULL if cannot
4970 * simplify the function.
4971 */
4972static Expr *
4973inline_function(Oid funcid, Oid result_type, Oid result_collid,
4974 Oid input_collid, List *args,
4975 bool funcvariadic,
4978{
4980 char *src;
4981 Datum tmp;
4982 bool isNull;
4985 inline_error_callback_arg callback_arg;
4987 FuncExpr *fexpr;
4989 TupleDesc rettupdesc;
4990 ParseState *pstate;
4994 Node *newexpr;
4995 int *usecounts;
4996 ListCell *arg;
4997 int i;
4998
4999 /*
5000 * Forget it if the function is not SQL-language or has other showstopper
5001 * properties. (The prokind and nargs checks are just paranoia.)
5002 */
5003 if (funcform->prolang != SQLlanguageId ||
5004 funcform->prokind != PROKIND_FUNCTION ||
5005 funcform->prosecdef ||
5006 funcform->proretset ||
5007 funcform->prorettype == RECORDOID ||
5009 funcform->pronargs != list_length(args))
5010 return NULL;
5011
5012 /* Check for recursive function, and give up trying to expand if so */
5013 if (list_member_oid(context->active_fns, funcid))
5014 return NULL;
5015
5016 /* Check permission to call function (fail later, if not) */
5018 return NULL;
5019
5020 /* Check whether a plugin wants to hook function entry/exit */
5021 if (FmgrHookIsNeeded(funcid))
5022 return NULL;
5023
5024 /*
5025 * Make a temporary memory context, so that we don't leak all the stuff
5026 * that parsing might create.
5027 */
5029 "inline_function",
5032
5033 /*
5034 * We need a dummy FuncExpr node containing the already-simplified
5035 * arguments. (In some cases we don't really need it, but building it is
5036 * cheap enough that it's not worth contortions to avoid.)
5037 */
5039 fexpr->funcid = funcid;
5040 fexpr->funcresulttype = result_type;
5041 fexpr->funcretset = false;
5042 fexpr->funcvariadic = funcvariadic;
5043 fexpr->funcformat = COERCE_EXPLICIT_CALL; /* doesn't matter */
5044 fexpr->funccollid = result_collid; /* doesn't matter */
5045 fexpr->inputcollid = input_collid;
5046 fexpr->args = args;
5047 fexpr->location = -1;
5048
5049 /* Fetch the function body */
5051 src = TextDatumGetCString(tmp);
5052
5053 /*
5054 * Setup error traceback support for ereport(). This is so that we can
5055 * finger the function that bad information came from.
5056 */
5057 callback_arg.proname = NameStr(funcform->proname);
5058 callback_arg.prosrc = src;
5059
5061 sqlerrcontext.arg = &callback_arg;
5064
5065 /* If we have prosqlbody, pay attention to that not prosrc */
5067 func_tuple,
5069 &isNull);
5070 if (!isNull)
5071 {
5072 Node *n;
5073 List *query_list;
5074
5076 if (IsA(n, List))
5077 query_list = linitial_node(List, castNode(List, n));
5078 else
5079 query_list = list_make1(n);
5080 if (list_length(query_list) != 1)
5081 goto fail;
5082 querytree = linitial(query_list);
5083
5084 /*
5085 * Because we'll insist below that the querytree have an empty rtable
5086 * and no sublinks, it cannot have any relation references that need
5087 * to be locked or rewritten. So we can omit those steps.
5088 */
5089 }
5090 else
5091 {
5092 /* Set up to handle parameters while parsing the function body. */
5094 (Node *) fexpr,
5095 input_collid);
5096
5097 /*
5098 * We just do parsing and parse analysis, not rewriting, because
5099 * rewriting will not affect table-free-SELECT-only queries, which is
5100 * all that we care about. Also, we can punt as soon as we detect
5101 * more than one command in the function body.
5102 */
5105 goto fail;
5106
5107 pstate = make_parsestate(NULL);
5108 pstate->p_sourcetext = src;
5109 sql_fn_parser_setup(pstate, pinfo);
5110
5112
5113 free_parsestate(pstate);
5114 }
5115
5116 /*
5117 * The single command must be a simple "SELECT expression".
5118 *
5119 * Note: if you change the tests involved in this, see also plpgsql's
5120 * exec_simple_check_plan(). That generally needs to have the same idea
5121 * of what's a "simple expression", so that inlining a function that
5122 * previously wasn't inlined won't change plpgsql's conclusion.
5123 */
5124 if (!IsA(querytree, Query) ||
5125 querytree->commandType != CMD_SELECT ||
5126 querytree->hasAggs ||
5127 querytree->hasWindowFuncs ||
5128 querytree->hasTargetSRFs ||
5129 querytree->hasSubLinks ||
5130 querytree->cteList ||
5131 querytree->rtable ||
5132 querytree->jointree->fromlist ||
5133 querytree->jointree->quals ||
5134 querytree->groupClause ||
5135 querytree->groupingSets ||
5136 querytree->havingQual ||
5137 querytree->windowClause ||
5138 querytree->distinctClause ||
5139 querytree->sortClause ||
5140 querytree->limitOffset ||
5141 querytree->limitCount ||
5142 querytree->setOperations ||
5143 list_length(querytree->targetList) != 1)
5144 goto fail;
5145
5146 /* If the function result is composite, resolve it */
5148 NULL,
5149 &rettupdesc);
5150
5151 /*
5152 * Make sure the function (still) returns what it's declared to. This
5153 * will raise an error if wrong, but that's okay since the function would
5154 * fail at runtime anyway. Note that check_sql_fn_retval will also insert
5155 * a coercion if needed to make the tlist expression match the declared
5156 * type of the function.
5157 *
5158 * Note: we do not try this until we have verified that no rewriting was
5159 * needed; that's probably not important, but let's be careful.
5160 */
5163 result_type, rettupdesc,
5164 funcform->prokind,
5165 false))
5166 goto fail; /* reject whole-tuple-result cases */
5167
5168 /*
5169 * Given the tests above, check_sql_fn_retval shouldn't have decided to
5170 * inject a projection step, but let's just make sure.
5171 */
5173 goto fail;
5174
5175 /* Now we can grab the tlist expression */
5176 newexpr = (Node *) ((TargetEntry *) linitial(querytree->targetList))->expr;
5177
5178 /*
5179 * If the SQL function returns VOID, we can only inline it if it is a
5180 * SELECT of an expression returning VOID (ie, it's just a redirection to
5181 * another VOID-returning function). In all non-VOID-returning cases,
5182 * check_sql_fn_retval should ensure that newexpr returns the function's
5183 * declared result type, so this test shouldn't fail otherwise; but we may
5184 * as well cope gracefully if it does.
5185 */
5186 if (exprType(newexpr) != result_type)
5187 goto fail;
5188
5189 /*
5190 * Additional validity checks on the expression. It mustn't be more
5191 * volatile than the surrounding function (this is to avoid breaking hacks
5192 * that involve pretending a function is immutable when it really ain't).
5193 * If the surrounding function is declared strict, then the expression
5194 * must contain only strict constructs and must use all of the function
5195 * parameters (this is overkill, but an exact analysis is hard).
5196 */
5197 if (funcform->provolatile == PROVOLATILE_IMMUTABLE &&
5199 goto fail;
5200 else if (funcform->provolatile == PROVOLATILE_STABLE &&
5202 goto fail;
5203
5204 if (funcform->proisstrict &&
5206 goto fail;
5207
5208 /*
5209 * If any parameter expression contains a context-dependent node, we can't
5210 * inline, for fear of putting such a node into the wrong context.
5211 */
5213 goto fail;
5214
5215 /*
5216 * We may be able to do it; there are still checks on parameter usage to
5217 * make, but those are most easily done in combination with the actual
5218 * substitution of the inputs. So start building expression with inputs
5219 * substituted.
5220 */
5221 usecounts = (int *) palloc0(funcform->pronargs * sizeof(int));
5223 args, usecounts);
5224
5225 /* Now check for parameter usage */
5226 i = 0;
5227 foreach(arg, args)
5228 {
5229 Node *param = lfirst(arg);
5230
5231 if (usecounts[i] == 0)
5232 {
5233 /* Param not used at all: uncool if func is strict */
5234 if (funcform->proisstrict)
5235 goto fail;
5236 }
5237 else if (usecounts[i] != 1)
5238 {
5239 /* Param used multiple times: uncool if expensive or volatile */
5241
5242 /*
5243 * We define "expensive" as "contains any subplan or more than 10
5244 * operators". Note that the subplan search has to be done
5245 * explicitly, since cost_qual_eval() will barf on unplanned
5246 * subselects.
5247 */
5248 if (contain_subplans(param))
5249 goto fail;
5251 if (eval_cost.startup + eval_cost.per_tuple >
5252 10 * cpu_operator_cost)
5253 goto fail;
5254
5255 /*
5256 * Check volatility last since this is more expensive than the
5257 * above tests
5258 */
5259 if (contain_volatile_functions(param))
5260 goto fail;
5261 }
5262 i++;
5263 }
5264
5265 /*
5266 * Whew --- we can make the substitution. Copy the modified expression
5267 * out of the temporary memory context, and clean up.
5268 */
5270
5272
5274
5275 /*
5276 * If the result is of a collatable type, force the result to expose the
5277 * correct collation. In most cases this does not matter, but it's
5278 * possible that the function result is used directly as a sort key or in
5279 * other places where we expect exprCollation() to tell the truth.
5280 */
5282 {
5284
5286 {
5288
5289 newnode->arg = (Expr *) newexpr;
5290 newnode->collOid = result_collid;
5291 newnode->location = -1;
5292
5293 newexpr = (Node *) newnode;
5294 }
5295 }
5296
5297 /*
5298 * Since there is now no trace of the function in the plan tree, we must
5299 * explicitly record the plan's dependency on the function.
5300 */
5301 if (context->root)
5302 record_plan_function_dependency(context->root, funcid);
5303
5304 /*
5305 * Recursively try to simplify the modified expression. Here we must add
5306 * the current function to the context list of active functions.
5307 */
5308 context->active_fns = lappend_oid(context->active_fns, funcid);
5310 context->active_fns = list_delete_last(context->active_fns);
5311
5313
5314 return (Expr *) newexpr;
5315
5316 /* Here if func is not inlinable: release temp memory and return NULL */
5317fail:
5321
5322 return NULL;
5323}
5324
5325/*
5326 * Replace Param nodes by appropriate actual parameters
5327 */
5328static Node *
5329substitute_actual_parameters(Node *expr, int nargs, List *args,
5330 int *usecounts)
5331{
5333
5334 context.nargs = nargs;
5335 context.args = args;
5336 context.usecounts = usecounts;
5337
5338 return substitute_actual_parameters_mutator(expr, &context);
5339}
5340
5341static Node *
5344{
5345 if (node == NULL)
5346 return NULL;
5347 if (IsA(node, Param))
5348 {
5349 Param *param = (Param *) node;
5350
5351 if (param->paramkind != PARAM_EXTERN)
5352 elog(ERROR, "unexpected paramkind: %d", (int) param->paramkind);
5353 if (param->paramid <= 0 || param->paramid > context->nargs)
5354 elog(ERROR, "invalid paramid: %d", param->paramid);
5355
5356 /* Count usage of parameter */
5357 context->usecounts[param->paramid - 1]++;
5358
5359 /* Select the appropriate actual arg and replace the Param with it */
5360 /* We don't need to copy at this time (it'll get done later) */
5361 return list_nth(context->args, param->paramid - 1);
5362 }
5364}
5365
5366/*
5367 * error context callback to let us supply a call-stack traceback
5368 */
5369static void
5371{
5374
5375 /* If it's a syntax error, convert to internal syntax error report */
5377 if (syntaxerrposition > 0)
5378 {
5379 errposition(0);
5381 internalerrquery(callback_arg->prosrc);
5382 }
5383
5384 errcontext("SQL function \"%s\" during inlining", callback_arg->proname);
5385}
5386
5387/*
5388 * evaluate_expr: pre-evaluate a constant expression
5389 *
5390 * We use the executor's routine ExecEvalExpr() to avoid duplication of
5391 * code and ensure we get the same result as the executor would get.
5392 */
5393Expr *
5394evaluate_expr(Expr *expr, Oid result_type, int32 result_typmod,
5396{
5397 EState *estate;
5398 ExprState *exprstate;
5399 MemoryContext oldcontext;
5401 bool const_is_null;
5403 bool resultTypByVal;
5404
5405 /*
5406 * To use the executor, we need an EState.
5407 */
5408 estate = CreateExecutorState();
5409
5410 /* We can use the estate's working context to avoid memory leaks. */
5411 oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
5412
5413 /* Make sure any opfuncids are filled in. */
5414 fix_opfuncids((Node *) expr);
5415
5416 /*
5417 * Prepare expr for execution. (Note: we can't use ExecPrepareExpr
5418 * because it'd result in recursively invoking eval_const_expressions.)
5419 */
5420 exprstate = ExecInitExpr(expr, NULL);
5421
5422 /*
5423 * And evaluate it.
5424 *
5425 * It is OK to use a default econtext because none of the ExecEvalExpr()
5426 * code used in this situation will use econtext. That might seem
5427 * fortuitous, but it's not so unreasonable --- a constant expression does
5428 * not depend on context, by definition, n'est ce pas?
5429 */
5431 GetPerTupleExprContext(estate),
5432 &const_is_null);
5433
5434 /* Get info needed about result datatype */
5436
5437 /* Get back to outer memory context */
5438 MemoryContextSwitchTo(oldcontext);
5439
5440 /*
5441 * Must copy result out of sub-context used by expression eval.
5442 *
5443 * Also, if it's varlena, forcibly detoast it. This protects us against
5444 * storing TOAST pointers into plans that might outlive the referenced
5445 * data. (makeConst would handle detoasting anyway, but it's worth a few
5446 * extra lines here so that we can do the copy and detoast in one step.)
5447 */
5448 if (!const_is_null)
5449 {
5450 if (resultTypLen == -1)
5452 else
5454 }
5455
5456 /* Release all the junk we just created */
5457 FreeExecutorState(estate);
5458
5459 /*
5460 * Make the constant result node.
5461 */
5462 return (Expr *) makeConst(result_type, result_typmod, result_collation,
5466}
5467
5468
5469/*
5470 * inline_function_in_from
5471 * Attempt to "inline" a function in the FROM clause.
5472 *
5473 * "rte" is an RTE_FUNCTION rangetable entry. If it represents a call of a
5474 * function that can be inlined, expand the function and return the
5475 * substitute Query structure. Otherwise, return NULL.
5476 *
5477 * We assume that the RTE's expression has already been put through
5478 * eval_const_expressions(), which among other things will take care of
5479 * default arguments and named-argument notation.
5480 *
5481 * This has a good deal of similarity to inline_function(), but that's
5482 * for the general-expression case, and there are enough differences to
5483 * justify separate functions.
5484 */
5485Query *
5487{
5488 RangeTblFunction *rtfunc;
5489 FuncExpr *fexpr;
5490 Oid func_oid;
5495 Datum tmp;
5496 char *src;
5497 inline_error_callback_arg callback_arg;
5499 Query *querytree = NULL;
5500
5501 Assert(rte->rtekind == RTE_FUNCTION);
5502
5503 /*
5504 * Guard against infinite recursion during expansion by checking for stack
5505 * overflow. (There's no need to do more.)
5506 */
5508
5509 /* Fail if the RTE has ORDINALITY - we don't implement that here. */
5510 if (rte->funcordinality)
5511 return NULL;
5512
5513 /* Fail if RTE isn't a single, simple FuncExpr */
5514 if (list_length(rte->functions) != 1)
5515 return NULL;
5516 rtfunc = (RangeTblFunction *) linitial(rte->functions);
5517
5518 if (!IsA(rtfunc->funcexpr, FuncExpr))
5519 return NULL;
5520 fexpr = (FuncExpr *) rtfunc->funcexpr;
5521
5522 func_oid = fexpr->funcid;
5523
5524 /*
5525 * Refuse to inline if the arguments contain any volatile functions or
5526 * sub-selects. Volatile functions are rejected because inlining may
5527 * result in the arguments being evaluated multiple times, risking a
5528 * change in behavior. Sub-selects are rejected partly for implementation
5529 * reasons (pushing them down another level might change their behavior)
5530 * and partly because they're likely to be expensive and so multiple
5531 * evaluation would be bad.
5532 */
5533 if (contain_volatile_functions((Node *) fexpr->args) ||
5534 contain_subplans((Node *) fexpr->args))
5535 return NULL;
5536
5537 /* Check permission to call function (fail later, if not) */
5539 return NULL;
5540
5541 /* Check whether a plugin wants to hook function entry/exit */
5543 return NULL;
5544
5545 /*
5546 * OK, let's take a look at the function's pg_proc entry.
5547 */
5550 elog(ERROR, "cache lookup failed for function %u", func_oid);
5552
5553 /*
5554 * If the function SETs any configuration parameters, inlining would cause
5555 * us to miss making those changes.
5556 */
5558 {
5560 return NULL;
5561 }
5562
5563 /*
5564 * Make a temporary memory context, so that we don't leak all the stuff
5565 * that parsing and rewriting might create. If we succeed, we'll copy
5566 * just the finished query tree back up to the caller's context.
5567 */
5569 "inline_function_in_from",
5572
5573 /* Fetch the function body */
5575 src = TextDatumGetCString(tmp);
5576
5577 /*
5578 * If the function has an attached support function that can handle
5579 * SupportRequestInlineInFrom, then attempt to inline with that.
5580 */
5581 if (funcform->prosupport)
5582 {
5584
5586 req.root = root;
5587 req.rtfunc = rtfunc;
5588 req.proc = func_tuple;
5589
5590 querytree = (Query *)
5592 PointerGetDatum(&req)));
5593 }
5594
5595 /*
5596 * Setup error traceback support for ereport(). This is so that we can
5597 * finger the function that bad information came from. We don't install
5598 * this while running the support function, since it'd be likely to do the
5599 * wrong thing: any parse errors reported during that are very likely not
5600 * against the raw function source text.
5601 */
5602 callback_arg.proname = NameStr(funcform->proname);
5603 callback_arg.prosrc = src;
5604
5606 sqlerrcontext.arg = &callback_arg;
5609
5610 /*
5611 * If SupportRequestInlineInFrom didn't work, try our built-in inlining
5612 * mechanism.
5613 */
5614 if (!querytree)
5616 func_tuple, funcform, src);
5617
5618 if (!querytree)
5619 goto fail; /* no luck there either, fail */
5620
5621 /*
5622 * The result had better be a SELECT Query.
5623 */
5625 Assert(querytree->commandType == CMD_SELECT);
5626
5627 /*
5628 * Looks good --- substitute parameters into the query.
5629 */
5631 funcform->pronargs,
5632 fexpr->args);
5633
5634 /*
5635 * Copy the modified query out of the temporary memory context, and clean
5636 * up.
5637 */
5639
5641
5645
5646 /*
5647 * We don't have to fix collations here because the upper query is already
5648 * parsed, ie, the collations in the RTE are what count.
5649 */
5650
5651 /*
5652 * Since there is now no trace of the function in the plan tree, we must
5653 * explicitly record the plan's dependency on the function.
5654 */
5656
5657 /*
5658 * We must also notice if the inserted query adds a dependency on the
5659 * calling role due to RLS quals.
5660 */
5661 if (querytree->hasRowSecurity)
5662 root->glob->dependsOnRole = true;
5663
5664 return querytree;
5665
5666 /* Here if func is not inlinable: release temp memory and return NULL */
5667fail:
5672
5673 return NULL;
5674}
5675
5676/*
5677 * inline_sql_function_in_from
5678 *
5679 * This implements inline_function_in_from for SQL-language functions.
5680 * Returns NULL if the function couldn't be inlined.
5681 *
5682 * The division of labor between here and inline_function_in_from is based
5683 * on the rule that inline_function_in_from should make all checks that are
5684 * certain to be required in both this case and the support-function case.
5685 * Support functions might also want to make checks analogous to the ones
5686 * made here, but then again they might not, or they might just assume that
5687 * the function they are attached to can validly be inlined.
5688 */
5689static Query *
5691 RangeTblFunction *rtfunc,
5692 FuncExpr *fexpr,
5695 const char *src)
5696{
5697 Datum sqlbody;
5698 bool isNull;
5702 TupleDesc rettupdesc;
5703
5704 /*
5705 * The function must be declared to return a set, else inlining would
5706 * change the results if the contained SELECT didn't return exactly one
5707 * row.
5708 */
5709 if (!fexpr->funcretset)
5710 return NULL;
5711
5712 /*
5713 * Forget it if the function is not SQL-language or has other showstopper
5714 * properties. In particular it mustn't be declared STRICT, since we
5715 * couldn't enforce that. It also mustn't be VOLATILE, because that is
5716 * supposed to cause it to be executed with its own snapshot, rather than
5717 * sharing the snapshot of the calling query. We also disallow returning
5718 * SETOF VOID, because inlining would result in exposing the actual result
5719 * of the function's last SELECT, which should not happen in that case.
5720 * (Rechecking prokind, proretset, and pronargs is just paranoia.)
5721 */
5722 if (funcform->prolang != SQLlanguageId ||
5723 funcform->prokind != PROKIND_FUNCTION ||
5724 funcform->proisstrict ||
5725 funcform->provolatile == PROVOLATILE_VOLATILE ||
5726 funcform->prorettype == VOIDOID ||
5727 funcform->prosecdef ||
5728 !funcform->proretset ||
5729 list_length(fexpr->args) != funcform->pronargs)
5730 return NULL;
5731
5732 /* If we have prosqlbody, pay attention to that not prosrc */
5734 func_tuple,
5736 &isNull);
5737 if (!isNull)
5738 {
5739 Node *n;
5740
5742 if (IsA(n, List))
5744 else
5746 if (list_length(querytree_list) != 1)
5747 return NULL;
5749
5750 /* Acquire necessary locks, then apply rewriter. */
5751 AcquireRewriteLocks(querytree, true, false);
5753 if (list_length(querytree_list) != 1)
5754 return NULL;
5756 }
5757 else
5758 {
5761
5762 /*
5763 * Set up to handle parameters while parsing the function body. We
5764 * can use the FuncExpr just created as the input for
5765 * prepare_sql_fn_parse_info.
5766 */
5768 (Node *) fexpr,
5769 fexpr->inputcollid);
5770
5771 /*
5772 * Parse, analyze, and rewrite (unlike inline_function(), we can't
5773 * skip rewriting here). We can fail as soon as we find more than one
5774 * query, though.
5775 */
5778 return NULL;
5779
5781 src,
5783 pinfo, NULL);
5784 if (list_length(querytree_list) != 1)
5785 return NULL;
5787 }
5788
5789 /*
5790 * Also resolve the actual function result tupdesc, if composite. If we
5791 * have a coldeflist, believe that; otherwise use get_expr_result_type.
5792 * (This logic should match ExecInitFunctionScan.)
5793 */
5794 if (rtfunc->funccolnames != NIL)
5795 {
5797 rettupdesc = BuildDescFromLists(rtfunc->funccolnames,
5798 rtfunc->funccoltypes,
5799 rtfunc->funccoltypmods,
5800 rtfunc->funccolcollations);
5801 }
5802 else
5803 functypclass = get_expr_result_type((Node *) fexpr, NULL, &rettupdesc);
5804
5805 /*
5806 * The single command must be a plain SELECT.
5807 */
5808 if (!IsA(querytree, Query) ||
5809 querytree->commandType != CMD_SELECT)
5810 return NULL;
5811
5812 /*
5813 * Make sure the function (still) returns what it's declared to. This
5814 * will raise an error if wrong, but that's okay since the function would
5815 * fail at runtime anyway. Note that check_sql_fn_retval will also insert
5816 * coercions if needed to make the tlist expression(s) match the declared
5817 * type of the function. We also ask it to insert dummy NULL columns for
5818 * any dropped columns in rettupdesc, so that the elements of the modified
5819 * tlist match up to the attribute numbers.
5820 *
5821 * If the function returns a composite type, don't inline unless the check
5822 * shows it's returning a whole tuple result; otherwise what it's
5823 * returning is a single composite column which is not what we need.
5824 */
5826 fexpr->funcresulttype, rettupdesc,
5827 funcform->prokind,
5828 true) &&
5832 return NULL; /* reject not-whole-tuple-result cases */
5833
5834 /*
5835 * check_sql_fn_retval might've inserted a projection step, but that's
5836 * fine; just make sure we use the upper Query.
5837 */
5839
5840 return querytree;
5841}
5842
5843/*
5844 * Replace Param nodes by appropriate actual parameters
5845 *
5846 * This is just enough different from substitute_actual_parameters()
5847 * that it needs its own code.
5848 */
5849static Query *
5850substitute_actual_parameters_in_from(Query *expr, int nargs, List *args)
5851{
5853
5854 context.nargs = nargs;
5855 context.args = args;
5856 context.sublevels_up = 1;
5857
5858 return query_tree_mutator(expr,
5860 &context,
5861 0);
5862}
5863
5864static Node *
5867{
5868 Node *result;
5869
5870 if (node == NULL)
5871 return NULL;
5872 if (IsA(node, Query))
5873 {
5874 context->sublevels_up++;
5875 result = (Node *) query_tree_mutator((Query *) node,
5877 context,
5878 0);
5879 context->sublevels_up--;
5880 return result;
5881 }
5882 if (IsA(node, Param))
5883 {
5884 Param *param = (Param *) node;
5885
5886 if (param->paramkind == PARAM_EXTERN)
5887 {
5888 if (param->paramid <= 0 || param->paramid > context->nargs)
5889 elog(ERROR, "invalid paramid: %d", param->paramid);
5890
5891 /*
5892 * Since the parameter is being inserted into a subquery, we must
5893 * adjust levels.
5894 */
5895 result = copyObject(list_nth(context->args, param->paramid - 1));
5896 IncrementVarSublevelsUp(result, context->sublevels_up, 0);
5897 return result;
5898 }
5899 }
5900 return expression_tree_mutator(node,
5902 context);
5903}
5904
5905/*
5906 * pull_paramids
5907 * Returns a Bitmapset containing the paramids of all Params in 'expr'.
5908 */
5909Bitmapset *
5910pull_paramids(Expr *expr)
5911{
5912 Bitmapset *result = NULL;
5913
5914 (void) pull_paramids_walker((Node *) expr, &result);
5915
5916 return result;
5917}
5918
5919static bool
5920pull_paramids_walker(Node *node, Bitmapset **context)
5921{
5922 if (node == NULL)
5923 return false;
5924 if (IsA(node, Param))
5925 {
5926 Param *param = (Param *) node;
5927
5928 *context = bms_add_member(*context, param->paramid);
5929 return false;
5930 }
5931 return expression_tree_walker(node, pull_paramids_walker, context);
5932}
5933
5934/*
5935 * Build ScalarArrayOpExpr on top of 'exprs.' 'haveNonConst' indicates
5936 * whether at least one of the expressions is not Const. When it's false,
5937 * the array constant is built directly; otherwise, we have to build a child
5938 * ArrayExpr. The 'exprs' list gets freed if not directly used in the output
5939 * expression tree.
5940 */
5943 Oid inputcollid, List *exprs, bool haveNonConst)
5944{
5945 Node *arrayNode = NULL;
5947 Oid arraytype = get_array_type(coltype);
5948
5949 if (!OidIsValid(arraytype))
5950 return NULL;
5951
5952 /*
5953 * Assemble an array from the list of constants. It seems more profitable
5954 * to build a const array. But in the presence of other nodes, we don't
5955 * have a specific value here and must employ an ArrayExpr instead.
5956 */
5957 if (haveNonConst)
5958 {
5960
5961 /* array_collid will be set by parse_collate.c */
5962 arrayExpr->element_typeid = coltype;
5963 arrayExpr->array_typeid = arraytype;
5964 arrayExpr->multidims = false;
5965 arrayExpr->elements = exprs;
5966 arrayExpr->location = -1;
5967
5968 arrayNode = (Node *) arrayExpr;
5969 }
5970 else
5971 {
5972 int16 typlen;
5973 bool typbyval;
5974 char typalign;
5975 Datum *elems;
5976 bool *nulls;
5977 int i = 0;
5979 int dims[1] = {list_length(exprs)};
5980 int lbs[1] = {1};
5981
5982 get_typlenbyvalalign(coltype, &typlen, &typbyval, &typalign);
5983
5984 elems = palloc_array(Datum, list_length(exprs));
5985 nulls = palloc_array(bool, list_length(exprs));
5986 foreach_node(Const, value, exprs)
5987 {
5988 elems[i] = value->constvalue;
5989 nulls[i++] = value->constisnull;
5990 }
5991
5992 arrayConst = construct_md_array(elems, nulls, 1, dims, lbs,
5993 coltype, typlen, typbyval, typalign);
5996 false, false);
5997
5998 pfree(elems);
5999 pfree(nulls);
6000 list_free(exprs);
6001 }
6002
6003 /* Build the SAOP expression node */
6005 saopexpr->opno = oper;
6006 saopexpr->opfuncid = get_opcode(oper);
6007 saopexpr->hashfuncid = InvalidOid;
6008 saopexpr->negfuncid = InvalidOid;
6009 saopexpr->useOr = true;
6010 saopexpr->inputcollid = inputcollid;
6012 saopexpr->location = -1;
6013
6014 return saopexpr;
6015}
Datum querytree(PG_FUNCTION_ARGS)
Definition _int_bool.c:665
@ ACLCHECK_OK
Definition acl.h:183
AclResult object_aclcheck(Oid classid, Oid objectid, Oid roleid, AclMode mode)
Definition aclchk.c:3836
#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:814
#define bms_is_empty(a)
Definition bitmapset.h:118
#define TextDatumGetCString(d)
Definition builtins.h:99
#define NameStr(name)
Definition c.h:777
#define Assert(condition)
Definition c.h:885
int16_t int16
Definition c.h:553
int32_t int32
Definition c.h:554
#define OidIsValid(objectId)
Definition c.h:800
static List * simplify_or_arguments(List *args, eval_const_expressions_context *context, bool *haveNull, bool *forceTrue)
Definition clauses.c:3973
static bool rowtype_field_matches(Oid rowtypeid, int fieldnum, Oid expectedtype, int32 expectedtypmod, Oid expectedcollation)
Definition clauses.c:2198
Query * inline_function_in_from(PlannerInfo *root, RangeTblEntry *rte)
Definition clauses.c:5487
static List * add_function_defaults(List *args, int pronargs, HeapTuple func_tuple)
Definition clauses.c:4749
#define ece_all_arguments_const(node)
Definition clauses.c:2439
#define ece_evaluate_expr(node)
Definition clauses.c:2443
bool contain_mutable_functions(Node *clause)
Definition clauses.c:379
#define ece_generic_processing(node)
Definition clauses.c:2430
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:4848
static Node * substitute_actual_parameters_mutator(Node *node, substitute_actual_parameters_context *context)
Definition clauses.c:5343
static bool ece_function_is_safe(Oid funcid, eval_const_expressions_context *context)
Definition clauses.c:3935
static List * simplify_and_arguments(List *args, eval_const_expressions_context *context, bool *haveNull, bool *forceFalse)
Definition clauses.c:4079
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:4242
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:4974
static List * reorder_function_arguments(List *args, int pronargs, HeapTuple func_tuple)
Definition clauses.c:4679
static Node * simplify_aggref(Aggref *aggref, eval_const_expressions_context *context)
Definition clauses.c:4348
static Node * substitute_actual_parameters(Node *expr, int nargs, List *args, int *usecounts)
Definition clauses.c:5330
static Query * substitute_actual_parameters_in_from(Query *expr, int nargs, List *args)
Definition clauses.c:5851
static void sql_inline_error_callback(void *arg)
Definition clauses.c:5371
static bool contain_non_const_walker(Node *node, void *context)
Definition clauses.c:3919
static bool contain_context_dependent_node(Node *clause)
Definition clauses.c:1190
static void recheck_cast_function_args(List *args, Oid result_type, Oid *proargtypes, int pronargs, HeapTuple func_tuple)
Definition clauses.c:4803
List * expand_function_arguments(List *args, bool include_out_arguments, Oid result_type, HeapTuple func_tuple)
Definition clauses.c:4598
bool contain_nonstrict_functions(Node *clause)
Definition clauses.c:1002
static Node * substitute_actual_parameters_in_from_mutator(Node *node, substitute_actual_parameters_in_from_context *context)
Definition clauses.c:5866
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:5691
bool contain_subplans(Node *clause)
Definition clauses.c:339
static Node * simplify_boolean_equality(Oid opno, List *args)
Definition clauses.c:4173
Bitmapset * pull_paramids(Expr *expr)
Definition clauses.c:5911
ScalarArrayOpExpr * make_SAOP_expr(Oid oper, Node *leftexpr, Oid coltype, Oid arraycollid, Oid inputcollid, List *exprs, bool haveNonConst)
Definition clauses.c:5943
static Node * eval_const_expressions_mutator(Node *node, eval_const_expressions_context *context)
Definition clauses.c:2453
static bool pull_paramids_walker(Node *node, Bitmapset **context)
Definition clauses.c:5921
Expr * evaluate_expr(Expr *expr, Oid result_type, int32 result_typmod, Oid result_collation)
Definition clauses.c:5395
bool expr_is_nonnullable(PlannerInfo *root, Expr *expr, bool use_rel_info)
Definition clauses.c:4456
static List * fetch_function_defaults(HeapTuple func_tuple)
Definition clauses.c:4773
bool contain_volatile_functions(Node *clause)
Definition clauses.c:547
bool var_is_nonnullable(PlannerInfo *root, Var *var, bool use_rel_info)
Definition clauses.c:4391
double cpu_operator_cost
Definition costsize.c:134
void cost_qual_eval(QualCost *cost, List *quals, PlannerInfo *root)
Definition costsize.c:4898
Datum datumCopy(Datum value, bool typByVal, int typLen)
Definition datum.c:132
int internalerrquery(const char *query)
Definition elog.c:1517
int internalerrposition(int cursorpos)
Definition elog.c:1497
ErrorContextCallback * error_context_stack
Definition elog.c:95
int geterrposition(void)
Definition elog.c:1613
int errposition(int cursorpos)
Definition elog.c:1481
#define errcontext
Definition elog.h:198
#define ERROR
Definition elog.h:39
#define elog(elevel,...)
Definition elog.h:226
ExprState * ExecInitExpr(Expr *node, PlanState *parent)
Definition execExpr.c:143
void FreeExecutorState(EState *estate)
Definition execUtils.c:192
EState * CreateExecutorState(void)
Definition execUtils.c:88
#define GetPerTupleExprContext(estate)
Definition executor.h:656
static Datum ExecEvalExprSwitchContext(ExprState *state, ExprContext *econtext, bool *isNull)
Definition executor.h:436
#define palloc_array(type, count)
Definition fe_memutils.h:76
#define OidFunctionCall1(functionId, arg1)
Definition fmgr.h:722
#define PG_DETOAST_DATUM_COPY(datum)
Definition fmgr.h:242
#define FmgrHookIsNeeded(fn_oid)
Definition fmgr.h:850
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:2116
void sql_fn_parser_setup(struct ParseState *pstate, SQLFunctionParseInfoPtr pinfo)
Definition functions.c:340
SQLFunctionParseInfoPtr prepare_sql_fn_parse_info(HeapTuple procedureTuple, Node *call_expr, Oid inputCollation)
Definition functions.c:251
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 @174 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
RegProcedure get_func_support(Oid funcid)
Definition lsyscache.c:2008
void getTypeOutputInfo(Oid type, Oid *typOutput, bool *typIsVarlena)
Definition lsyscache.c:3059
void get_typlenbyvalalign(Oid typid, int16 *typlen, bool *typbyval, char *typalign)
Definition lsyscache.c:2421
void get_typlenbyval(Oid typid, int16 *typlen, bool *typbyval)
Definition lsyscache.c:2401
RegProcedure get_opcode(Oid opno)
Definition lsyscache.c:1435
void getTypeInputInfo(Oid type, Oid *typInput, Oid *typIOParam)
Definition lsyscache.c:3026
char func_volatile(Oid funcid)
Definition lsyscache.c:1930
Oid get_array_type(Oid typid)
Definition lsyscache.c:2939
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:1616
void * palloc0(Size size)
Definition mcxt.c:1417
MemoryContext CurrentMemoryContext
Definition mcxt.c:160
void MemoryContextDelete(MemoryContext context)
Definition mcxt.c:472
#define AllocSetContextCreate
Definition memutils.h:129
#define ALLOCSET_DEFAULT_SIZES
Definition memutils.h:160
Oid GetUserId(void)
Definition miscinit.c:469
Oid exprType(const Node *expr)
Definition nodeFuncs.c:42
int32 exprTypmod(const Node *expr)
Definition nodeFuncs.c:301
Oid exprCollation(const Node *expr)
Definition nodeFuncs.c:821
Node * applyRelabelType(Node *arg, Oid rtype, int32 rtypmod, Oid rcollid, CoercionForm rformat, int rlocation, bool overwrite_ok)
Definition nodeFuncs.c:636
void fix_opfuncids(Node *node)
Definition nodeFuncs.c:1840
void set_sa_opfuncid(ScalarArrayOpExpr *opexpr)
Definition nodeFuncs.c:1882
void set_opfuncid(OpExpr *opexpr)
Definition nodeFuncs.c:1871
#define expression_tree_mutator(n, m, c)
Definition nodeFuncs.h:155
static bool is_andclause(const void *clause)
Definition nodeFuncs.h:107
static bool is_orclause(const void *clause)
Definition nodeFuncs.h:116
#define expression_tree_walker(n, w, c)
Definition nodeFuncs.h:153
#define query_tree_mutator(q, m, c, f)
Definition nodeFuncs.h:160
#define IsA(nodeptr, _type_)
Definition nodes.h:164
#define copyObject(obj)
Definition nodes.h:232
#define nodeTag(nodeptr)
Definition nodes.h:139
@ CMD_SELECT
Definition nodes.h:275
#define makeNode(_type_)
Definition nodes.h:161
#define castNode(_type_, nodeptr)
Definition nodes.h:182
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition palloc.h:124
#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:372
@ RTE_FUNCTION
#define ACL_EXECUTE
Definition parsenodes.h:83
Query * transformTopLevelStmt(ParseState *pstate, RawStmt *parseTree)
Definition analyze.c:261
#define planner_rt_fetch(rti, root)
Definition pathnodes.h:692
void * arg
#define FUNC_MAX_ARGS
#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:212
#define foreach_ptr(type, var, lst)
Definition pg_list.h:469
static void * list_nth(const List *list, int n)
Definition pg_list.h:299
#define linitial(l)
Definition pg_list.h:178
#define list_make3(x1, x2, x3)
Definition pg_list.h:216
#define lsecond(l)
Definition pg_list.h:183
#define foreach_node(type, var, lst)
Definition pg_list.h:496
#define list_make2(x1, x2)
Definition pg_list.h:214
FormData_pg_proc * Form_pg_proc
Definition pg_proc.h:136
int16 pronargs
Definition pg_proc.h:81
char typalign
Definition pg_type.h:176
Bitmapset * find_relation_notnullatts(PlannerInfo *root, Oid relid)
Definition plancat.c:777
List * pg_analyze_and_rewrite_withcb(RawStmt *parsetree, const char *query_string, ParserSetupHook parserSetup, void *parserSetupArg, QueryEnvironment *queryEnv)
Definition postgres.c:762
List * pg_parse_query(const char *query_string)
Definition postgres.c:603
List * pg_rewrite_query(Query *query)
Definition postgres.c:802
static bool DatumGetBool(Datum X)
Definition postgres.h:100
static Datum PointerGetDatum(const void *X)
Definition postgres.h:352
static Datum BoolGetDatum(bool X)
Definition postgres.h:112
static Datum ObjectIdGetDatum(Oid X)
Definition postgres.h:262
uint64_t Datum
Definition postgres.h:70
static Pointer DatumGetPointer(Datum X)
Definition postgres.h:342
static Datum Int32GetDatum(int32 X)
Definition postgres.h:222
#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:2002
@ IS_NOT_FALSE
Definition primnodes.h:2002
@ IS_NOT_UNKNOWN
Definition primnodes.h:2002
@ IS_TRUE
Definition primnodes.h:2002
@ IS_UNKNOWN
Definition primnodes.h:2002
@ IS_FALSE
Definition primnodes.h:2002
@ AND_EXPR
Definition primnodes.h:964
@ OR_EXPR
Definition primnodes.h:964
@ NOT_EXPR
Definition primnodes.h:964
@ PARAM_EXTERN
Definition primnodes.h:385
@ COERCE_IMPLICIT_CAST
Definition primnodes.h:769
@ COERCE_EXPLICIT_CALL
Definition primnodes.h:767
@ IS_NULL
Definition primnodes.h:1978
@ IS_NOT_NULL
Definition primnodes.h:1978
tree ctl root
Definition radixtree.h:1857
void * stringToNode(const char *str)
Definition read.c:90
RelOptInfo * find_base_rel(PlannerInfo *root, int relid)
Definition relnode.c:533
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:3666
void record_plan_function_dependency(PlannerInfo *root, Oid funcid)
Definition setrefs.c:3626
void check_stack_depth(void)
Definition stack_depth.c:95
Oid aggfnoid
Definition primnodes.h:464
BoolExprType boolop
Definition primnodes.h:972
List * args
Definition primnodes.h:973
ParseLoc location
Definition primnodes.h:1248
ParseLoc location
Definition primnodes.h:1315
Oid consttype
Definition primnodes.h:330
MemoryContext es_query_cxt
Definition execnodes.h:713
struct ErrorContextCallback * previous
Definition elog.h:297
Expr xpr
Definition primnodes.h:781
ParseLoc location
Definition primnodes.h:803
Oid funcid
Definition primnodes.h:783
List * args
Definition primnodes.h:801
Definition pg_list.h:54
Definition nodes.h:135
NodeTag type
Definition nodes.h:136
Oid opno
Definition primnodes.h:851
List * args
Definition primnodes.h:869
ParseLoc location
Definition primnodes.h:872
ParamExternData params[FLEXIBLE_ARRAY_MEMBER]
Definition params.h:124
ParamFetchHook paramFetch
Definition params.h:111
ParseLoc location
Definition primnodes.h:404
int32 paramtypmod
Definition primnodes.h:400
int paramid
Definition primnodes.h:397
Oid paramtype
Definition primnodes.h:398
ParamKind paramkind
Definition primnodes.h:396
Oid paramcollid
Definition primnodes.h:402
const char * p_sourcetext
Definition parse_node.h:191
Bitmapset * notnullattnums
Definition pathnodes.h:1071
List * args
Definition primnodes.h:1449
AttrNumber varattno
Definition primnodes.h:275
int varno
Definition primnodes.h:270
Index varlevelsup
Definition primnodes.h:295
List * args
Definition primnodes.h:606
Index winref
Definition primnodes.h:612
Expr * aggfilter
Definition primnodes.h:608
ParseLoc location
Definition primnodes.h:620
int ignore_nulls
Definition primnodes.h:618
void ReleaseSysCache(HeapTuple tuple)
Definition syscache.c:264
Datum SysCacheGetAttrNotNull(SysCacheIdentifier cacheId, HeapTuple tup, AttrNumber attributeNumber)
Definition syscache.c:625
HeapTuple SearchSysCache1(SysCacheIdentifier cacheId, Datum key1)
Definition syscache.c:220
Datum SysCacheGetAttr(SysCacheIdentifier cacheId, HeapTuple tup, AttrNumber attributeNumber, bool *isNull)
Definition syscache.c:595
TupleDesc BuildDescFromLists(const List *names, const List *types, const List *typmods, const List *collations)
Definition tupdesc.c:1034
bool DomainHasConstraints(Oid type_id)
Definition typcache.c:1491

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

◆ ece_generic_processing

#define ece_generic_processing (   node)
Value:

Definition at line 2430 of file clauses.c.

◆ MIN_ARRAY_SIZE_FOR_HASHED_SAOP

#define MIN_ARRAY_SIZE_FOR_HASHED_SAOP   9

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

4750{
4751 int nargsprovided = list_length(args);
4752 List *defaults;
4753 int ndelete;
4754
4755 /* Get all the default expressions from the pg_proc tuple */
4757
4758 /* Delete any unused defaults from the list */
4759 ndelete = nargsprovided + list_length(defaults) - pronargs;
4760 if (ndelete < 0)
4761 elog(ERROR, "not enough default arguments");
4762 if (ndelete > 0)
4763 defaults = list_delete_first_n(defaults, ndelete);
4764
4765 /* And form the combined argument list, not modifying the input list */
4766 return list_concat_copy(args, defaults);
4767}

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

2160{
2161 Oid opoid;
2162 Node *temp;
2163
2164 /* Sanity checks: caller is at fault if these fail */
2165 if (!is_opclause(clause) ||
2166 list_length(clause->args) != 2)
2167 elog(ERROR, "cannot commute non-binary-operator clause");
2168
2169 opoid = get_commutator(clause->opno);
2170
2171 if (!OidIsValid(opoid))
2172 elog(ERROR, "could not find commutator for operator %u",
2173 clause->opno);
2174
2175 /*
2176 * modify the clause in-place!
2177 */
2178 clause->opno = opoid;
2179 clause->opfuncid = InvalidOid;
2180 /* opresulttype, opretset, opcollid, inputcollid need not change */
2181
2182 temp = linitial(clause->args);
2183 linitial(clause->args) = lsecond(clause->args);
2184 lsecond(clause->args) = temp;
2185}
Oid get_commutator(Oid opno)
Definition lsyscache.c:1659
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 190 of file clauses.c.

191{
192 return contain_agg_clause_walker(clause, NULL);
193}
static bool contain_agg_clause_walker(Node *node, void *context)
Definition clauses.c:196

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

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

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

1191{
1192 int flags = 0;
1193
1194 return contain_context_dependent_node_walker(clause, &flags);
1195}
static bool contain_context_dependent_node_walker(Node *node, int *flags)
Definition clauses.c:1200

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

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

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

1149{
1150 return contain_exec_param_walker(clause, param_ids);
1151}
static bool contain_exec_param_walker(Node *node, List *param_ids)
Definition clauses.c:1154

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

1155{
1156 if (node == NULL)
1157 return false;
1158 if (IsA(node, Param))
1159 {
1160 Param *p = (Param *) node;
1161
1162 if (p->paramkind == PARAM_EXEC &&
1164 return true;
1165 }
1167}
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 1274 of file clauses.c.

1275{
1276 return contain_leaked_vars_walker(clause, NULL);
1277}
static bool contain_leaked_vars_walker(Node *node, void *context)
Definition clauses.c:1286

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

1281{
1282 return !get_func_leakproof(func_id);
1283}
bool get_func_leakproof(Oid funcid)
Definition lsyscache.c:1987

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

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

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

Referenced by contain_leaked_vars(), and contain_leaked_vars_walker().

◆ contain_mutable_functions()

◆ contain_mutable_functions_after_planning()

bool contain_mutable_functions_after_planning ( Expr expr)

Definition at line 499 of file clauses.c.

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

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

386{
388}

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

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

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

3920{
3921 if (node == NULL)
3922 return false;
3923 if (IsA(node, Const))
3924 return false;
3925 if (IsA(node, List))
3926 return expression_tree_walker(node, contain_non_const_walker, context);
3927 /* Otherwise, abort the tree traversal and return true */
3928 return true;
3929}

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

1003{
1005}
static bool contain_nonstrict_functions_walker(Node *node, void *context)
Definition clauses.c:1014

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

1009{
1010 return !func_strict(func_id);
1011}
bool func_strict(Oid funcid)
Definition lsyscache.c:1911

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

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

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

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

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

548{
550}
static bool contain_volatile_functions_walker(Node *node, void *context)
Definition clauses.c:559

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(), distribute_qual_to_rels(), estimate_num_groups(), ExecInitWindowAgg(), expand_indexqual_rowcompare(), find_compatible_agg(), find_simplified_clause(), get_eclass_for_sort_expr(), get_memoize_path(), group_similar_or_args(), initialize_peragg(), inline_function(), inline_function_in_from(), is_pseudo_constant_clause(), is_pseudo_constant_clause_relids(), is_pseudo_constant_for_index(), is_safe_restriction_clause_for(), is_simple_subquery(), is_simple_values(), IsBinaryTidClause(), IsTidEqualAnyClause(), make_sort_input_target(), mark_nullable_by_grouping(), match_clause_to_ordering_op(), match_clause_to_partition_key(), match_opclause_to_indexcol(), match_orclause_to_indexcol(), match_rowcompare_to_indexcol(), match_saopclause_to_indexcol(), paraminfo_get_equal_hashops(), qual_is_pushdown_safe(), remove_unused_subquery_outputs(), SS_process_ctes(), and subquery_planner().

◆ contain_volatile_functions_after_planning()

bool contain_volatile_functions_after_planning ( Expr expr)

Definition at line 668 of file clauses.c.

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

References contain_volatile_functions(), and expression_planner().

◆ contain_volatile_functions_checker()

static bool contain_volatile_functions_checker ( Oid  func_id,
void context 
)
static

Definition at line 553 of file clauses.c.

554{
556}

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

683{
685}
static bool contain_volatile_functions_not_nextval_walker(Node *node, void *context)
Definition clauses.c:695

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

689{
690 return (func_id != F_NEXTVAL &&
692}

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

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

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

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

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

228{
229 return contain_windowfuncs(clause);
230}
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 2300 of file clauses.c.

2301{
2303}
static bool convert_saop_to_hashed_saop_walker(Node *node, void *context)
Definition clauses.c:2306

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

2307{
2308 if (node == NULL)
2309 return false;
2310
2311 if (IsA(node, ScalarArrayOpExpr))
2312 {
2313 ScalarArrayOpExpr *saop = (ScalarArrayOpExpr *) node;
2314 Expr *arrayarg = (Expr *) lsecond(saop->args);
2317
2318 if (arrayarg && IsA(arrayarg, Const) &&
2319 !((Const *) arrayarg)->constisnull)
2320 {
2321 if (saop->useOr)
2322 {
2325 {
2326 Datum arrdatum = ((Const *) arrayarg)->constvalue;
2328 int nitems;
2329
2330 /*
2331 * Only fill in the hash functions if the array looks
2332 * large enough for it to be worth hashing instead of
2333 * doing a linear search.
2334 */
2335 nitems = ArrayGetNItems(ARR_NDIM(arr), ARR_DIMS(arr));
2336
2338 {
2339 /* Looks good. Fill in the hash functions */
2340 saop->hashfuncid = lefthashfunc;
2341 }
2342 return false;
2343 }
2344 }
2345 else /* !saop->useOr */
2346 {
2347 Oid negator = get_negator(saop->opno);
2348
2349 /*
2350 * Check if this is a NOT IN using an operator whose negator
2351 * is hashable. If so we can still build a hash table and
2352 * just ensure the lookup items are not in the hash table.
2353 */
2354 if (OidIsValid(negator) &&
2357 {
2358 Datum arrdatum = ((Const *) arrayarg)->constvalue;
2360 int nitems;
2361
2362 /*
2363 * Only fill in the hash functions if the array looks
2364 * large enough for it to be worth hashing instead of
2365 * doing a linear search.
2366 */
2367 nitems = ArrayGetNItems(ARR_NDIM(arr), ARR_DIMS(arr));
2368
2370 {
2371 /* Looks good. Fill in the hash functions */
2372 saop->hashfuncid = lefthashfunc;
2373
2374 /*
2375 * Also set the negfuncid. The executor will need
2376 * that to perform hashtable lookups.
2377 */
2378 saop->negfuncid = get_opcode(negator);
2379 }
2380 return false;
2381 }
2382 }
2383 }
2384 }
2385
2387}
int ArrayGetNItems(int ndim, const int *dims)
Definition arrayutils.c:57
#define MIN_ARRAY_SIZE_FOR_HASHED_SAOP
Definition clauses.c:2282
#define nitems(x)
Definition indent.h:31
bool get_op_hash_functions(Oid opno, RegProcedure *lhs_procno, RegProcedure *rhs_procno)
Definition lsyscache.c:575
Oid get_negator(Oid opno)
Definition lsyscache.c:1683

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

Referenced by convert_saop_to_hashed_saop(), and convert_saop_to_hashed_saop_walker().

◆ ece_function_is_safe()

static bool ece_function_is_safe ( Oid  funcid,
eval_const_expressions_context context 
)
static

Definition at line 3935 of file clauses.c.

3936{
3937 char provolatile = func_volatile(funcid);
3938
3939 /*
3940 * Ordinarily we are only allowed to simplify immutable functions. But for
3941 * purposes of estimation, we consider it okay to simplify functions that
3942 * are merely stable; the risk that the result might change from planning
3943 * time to execution time is worth taking in preference to not being able
3944 * to estimate the value at all.
3945 */
3947 return true;
3948 if (context->estimate && provolatile == PROVOLATILE_STABLE)
3949 return true;
3950 return false;
3951}

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

2268{
2270
2271 if (root)
2272 context.boundParams = root->glob->boundParams; /* bound Params */
2273 else
2274 context.boundParams = NULL;
2275 context.root = root; /* for inlined-function dependencies */
2276 context.active_fns = NIL; /* nothing being recursively simplified */
2277 context.case_val = NULL; /* no CASE being examined */
2278 context.estimate = false; /* safe transformations only */
2279 return eval_const_expressions_mutator(node, &context);
2280}

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

2455{
2456
2457 /* since this function recurses, it could be driven to stack overflow */
2459
2460 if (node == NULL)
2461 return NULL;
2462 switch (nodeTag(node))
2463 {
2464 case T_Param:
2465 {
2466 Param *param = (Param *) node;
2467 ParamListInfo paramLI = context->boundParams;
2468
2469 /* Look to see if we've been given a value for this Param */
2470 if (param->paramkind == PARAM_EXTERN &&
2471 paramLI != NULL &&
2472 param->paramid > 0 &&
2473 param->paramid <= paramLI->numParams)
2474 {
2477
2478 /*
2479 * Give hook a chance in case parameter is dynamic. Tell
2480 * it that this fetch is speculative, so it should avoid
2481 * erroring out if parameter is unavailable.
2482 */
2483 if (paramLI->paramFetch != NULL)
2484 prm = paramLI->paramFetch(paramLI, param->paramid,
2485 true, &prmdata);
2486 else
2487 prm = &paramLI->params[param->paramid - 1];
2488
2489 /*
2490 * We don't just check OidIsValid, but insist that the
2491 * fetched type match the Param, just in case the hook did
2492 * something unexpected. No need to throw an error here
2493 * though; leave that for runtime.
2494 */
2495 if (OidIsValid(prm->ptype) &&
2496 prm->ptype == param->paramtype)
2497 {
2498 /* OK to substitute parameter value? */
2499 if (context->estimate ||
2500 (prm->pflags & PARAM_FLAG_CONST))
2501 {
2502 /*
2503 * Return a Const representing the param value.
2504 * Must copy pass-by-ref datatypes, since the
2505 * Param might be in a memory context
2506 * shorter-lived than our output plan should be.
2507 */
2508 int16 typLen;
2509 bool typByVal;
2510 Datum pval;
2511 Const *con;
2512
2514 &typLen, &typByVal);
2515 if (prm->isnull || typByVal)
2516 pval = prm->value;
2517 else
2518 pval = datumCopy(prm->value, typByVal, typLen);
2519 con = makeConst(param->paramtype,
2520 param->paramtypmod,
2521 param->paramcollid,
2522 (int) typLen,
2523 pval,
2524 prm->isnull,
2525 typByVal);
2526 con->location = param->location;
2527 return (Node *) con;
2528 }
2529 }
2530 }
2531
2532 /*
2533 * Not replaceable, so just copy the Param (no need to
2534 * recurse)
2535 */
2536 return (Node *) copyObject(param);
2537 }
2538 case T_WindowFunc:
2539 {
2540 WindowFunc *expr = (WindowFunc *) node;
2541 Oid funcid = expr->winfnoid;
2542 List *args;
2543 Expr *aggfilter;
2546
2547 /*
2548 * We can't really simplify a WindowFunc node, but we mustn't
2549 * just fall through to the default processing, because we
2550 * have to apply expand_function_arguments to its argument
2551 * list. That takes care of inserting default arguments and
2552 * expanding named-argument notation.
2553 */
2556 elog(ERROR, "cache lookup failed for function %u", funcid);
2557
2559 false, expr->wintype,
2560 func_tuple);
2561
2563
2564 /* Now, recursively simplify the args (which are a List) */
2565 args = (List *)
2568 context);
2569 /* ... and the filter expression, which isn't */
2570 aggfilter = (Expr *)
2572 context);
2573
2574 /* And build the replacement WindowFunc node */
2576 newexpr->winfnoid = expr->winfnoid;
2577 newexpr->wintype = expr->wintype;
2578 newexpr->wincollid = expr->wincollid;
2579 newexpr->inputcollid = expr->inputcollid;
2580 newexpr->args = args;
2581 newexpr->aggfilter = aggfilter;
2582 newexpr->runCondition = expr->runCondition;
2583 newexpr->winref = expr->winref;
2584 newexpr->winstar = expr->winstar;
2585 newexpr->winagg = expr->winagg;
2587 newexpr->location = expr->location;
2588
2589 return (Node *) newexpr;
2590 }
2591 case T_FuncExpr:
2592 {
2593 FuncExpr *expr = (FuncExpr *) node;
2594 List *args = expr->args;
2595 Expr *simple;
2597
2598 /*
2599 * Code for op/func reduction is pretty bulky, so split it out
2600 * as a separate function. Note: exprTypmod normally returns
2601 * -1 for a FuncExpr, but not when the node is recognizably a
2602 * length coercion; we want to preserve the typmod in the
2603 * eventual Const if so.
2604 */
2605 simple = simplify_function(expr->funcid,
2606 expr->funcresulttype,
2607 exprTypmod(node),
2608 expr->funccollid,
2609 expr->inputcollid,
2610 &args,
2611 expr->funcvariadic,
2612 true,
2613 true,
2614 context);
2615 if (simple) /* successfully simplified it */
2616 return (Node *) simple;
2617
2618 /*
2619 * The expression cannot be simplified any further, so build
2620 * and return a replacement FuncExpr node using the
2621 * possibly-simplified arguments. Note that we have also
2622 * converted the argument list to positional notation.
2623 */
2625 newexpr->funcid = expr->funcid;
2626 newexpr->funcresulttype = expr->funcresulttype;
2627 newexpr->funcretset = expr->funcretset;
2628 newexpr->funcvariadic = expr->funcvariadic;
2629 newexpr->funcformat = expr->funcformat;
2630 newexpr->funccollid = expr->funccollid;
2631 newexpr->inputcollid = expr->inputcollid;
2632 newexpr->args = args;
2633 newexpr->location = expr->location;
2634 return (Node *) newexpr;
2635 }
2636 case T_Aggref:
2637 node = ece_generic_processing(node);
2638 if (context->root != NULL)
2639 return simplify_aggref((Aggref *) node, context);
2640 return node;
2641 case T_OpExpr:
2642 {
2643 OpExpr *expr = (OpExpr *) node;
2644 List *args = expr->args;
2645 Expr *simple;
2646 OpExpr *newexpr;
2647
2648 /*
2649 * Need to get OID of underlying function. Okay to scribble
2650 * on input to this extent.
2651 */
2652 set_opfuncid(expr);
2653
2654 /*
2655 * Code for op/func reduction is pretty bulky, so split it out
2656 * as a separate function.
2657 */
2658 simple = simplify_function(expr->opfuncid,
2659 expr->opresulttype, -1,
2660 expr->opcollid,
2661 expr->inputcollid,
2662 &args,
2663 false,
2664 true,
2665 true,
2666 context);
2667 if (simple) /* successfully simplified it */
2668 return (Node *) simple;
2669
2670 /*
2671 * If the operator is boolean equality or inequality, we know
2672 * how to simplify cases involving one constant and one
2673 * non-constant argument.
2674 */
2675 if (expr->opno == BooleanEqualOperator ||
2677 {
2678 simple = (Expr *) simplify_boolean_equality(expr->opno,
2679 args);
2680 if (simple) /* successfully simplified it */
2681 return (Node *) simple;
2682 }
2683
2684 /*
2685 * The expression cannot be simplified any further, so build
2686 * and return a replacement OpExpr node using the
2687 * possibly-simplified arguments.
2688 */
2690 newexpr->opno = expr->opno;
2691 newexpr->opfuncid = expr->opfuncid;
2692 newexpr->opresulttype = expr->opresulttype;
2693 newexpr->opretset = expr->opretset;
2694 newexpr->opcollid = expr->opcollid;
2695 newexpr->inputcollid = expr->inputcollid;
2696 newexpr->args = args;
2697 newexpr->location = expr->location;
2698 return (Node *) newexpr;
2699 }
2700 case T_DistinctExpr:
2701 {
2702 DistinctExpr *expr = (DistinctExpr *) node;
2703 List *args;
2704 ListCell *arg;
2705 bool has_null_input = false;
2706 bool all_null_input = true;
2707 bool has_nonconst_input = false;
2708 bool has_nullable_nonconst = false;
2709 Expr *simple;
2711
2712 /*
2713 * Reduce constants in the DistinctExpr's arguments. We know
2714 * args is either NIL or a List node, so we can call
2715 * expression_tree_mutator directly rather than recursing to
2716 * self.
2717 */
2718 args = (List *) expression_tree_mutator((Node *) expr->args,
2720 context);
2721
2722 /*
2723 * We must do our own check for NULLs because DistinctExpr has
2724 * different results for NULL input than the underlying
2725 * operator does. We also check if any non-constant input is
2726 * potentially nullable.
2727 */
2728 foreach(arg, args)
2729 {
2730 if (IsA(lfirst(arg), Const))
2731 {
2734 }
2735 else
2736 {
2737 has_nonconst_input = true;
2738 all_null_input = false;
2739
2740 if (!has_nullable_nonconst &&
2741 !expr_is_nonnullable(context->root,
2742 (Expr *) lfirst(arg), false))
2743 has_nullable_nonconst = true;
2744 }
2745 }
2746
2747 if (!has_nonconst_input)
2748 {
2749 /*
2750 * All inputs are constants. We can optimize this out
2751 * completely.
2752 */
2753
2754 /* all nulls? then not distinct */
2755 if (all_null_input)
2756 return makeBoolConst(false, false);
2757
2758 /* one null? then distinct */
2759 if (has_null_input)
2760 return makeBoolConst(true, false);
2761
2762 /* otherwise try to evaluate the '=' operator */
2763 /* (NOT okay to try to inline it, though!) */
2764
2765 /*
2766 * Need to get OID of underlying function. Okay to
2767 * scribble on input to this extent.
2768 */
2769 set_opfuncid((OpExpr *) expr); /* rely on struct
2770 * equivalence */
2771
2772 /*
2773 * Code for op/func reduction is pretty bulky, so split it
2774 * out as a separate function.
2775 */
2776 simple = simplify_function(expr->opfuncid,
2777 expr->opresulttype, -1,
2778 expr->opcollid,
2779 expr->inputcollid,
2780 &args,
2781 false,
2782 false,
2783 false,
2784 context);
2785 if (simple) /* successfully simplified it */
2786 {
2787 /*
2788 * Since the underlying operator is "=", must negate
2789 * its result
2790 */
2791 Const *csimple = castNode(Const, simple);
2792
2793 csimple->constvalue =
2794 BoolGetDatum(!DatumGetBool(csimple->constvalue));
2795 return (Node *) csimple;
2796 }
2797 }
2798 else if (!has_nullable_nonconst)
2799 {
2800 /*
2801 * There are non-constant inputs, but since all of them
2802 * are proven non-nullable, "IS DISTINCT FROM" semantics
2803 * are much simpler.
2804 */
2805
2806 OpExpr *eqexpr;
2807
2808 /*
2809 * If one input is an explicit NULL constant, and the
2810 * other is a non-nullable expression, the result is
2811 * always TRUE.
2812 */
2813 if (has_null_input)
2814 return makeBoolConst(true, false);
2815
2816 /*
2817 * Otherwise, both inputs are known non-nullable. In this
2818 * case, "IS DISTINCT FROM" is equivalent to the standard
2819 * inequality operator (usually "<>"). We convert this to
2820 * an OpExpr, which is a more efficient representation for
2821 * the planner. It can enable the use of partial indexes
2822 * and constraint exclusion. Furthermore, if the clause
2823 * is negated (ie, "IS NOT DISTINCT FROM"), the resulting
2824 * "=" operator can allow the planner to use index scans,
2825 * merge joins, hash joins, and EC-based qual deductions.
2826 */
2828 eqexpr->opno = expr->opno;
2829 eqexpr->opfuncid = expr->opfuncid;
2830 eqexpr->opresulttype = BOOLOID;
2831 eqexpr->opretset = expr->opretset;
2832 eqexpr->opcollid = expr->opcollid;
2833 eqexpr->inputcollid = expr->inputcollid;
2834 eqexpr->args = args;
2835 eqexpr->location = expr->location;
2836
2838 context);
2839 }
2840 else if (has_null_input)
2841 {
2842 /*
2843 * One input is a nullable non-constant expression, and
2844 * the other is an explicit NULL constant. We can
2845 * transform this to a NullTest with !argisrow, which is
2846 * much more amenable to optimization.
2847 */
2848
2850
2851 nt->arg = (Expr *) (IsA(linitial(args), Const) ?
2852 lsecond(args) : linitial(args));
2853 nt->nulltesttype = IS_NOT_NULL;
2854
2855 /*
2856 * argisrow = false is correct whether or not arg is
2857 * composite
2858 */
2859 nt->argisrow = false;
2860 nt->location = expr->location;
2861
2862 return eval_const_expressions_mutator((Node *) nt, context);
2863 }
2864
2865 /*
2866 * The expression cannot be simplified any further, so build
2867 * and return a replacement DistinctExpr node using the
2868 * possibly-simplified arguments.
2869 */
2871 newexpr->opno = expr->opno;
2872 newexpr->opfuncid = expr->opfuncid;
2873 newexpr->opresulttype = expr->opresulttype;
2874 newexpr->opretset = expr->opretset;
2875 newexpr->opcollid = expr->opcollid;
2876 newexpr->inputcollid = expr->inputcollid;
2877 newexpr->args = args;
2878 newexpr->location = expr->location;
2879 return (Node *) newexpr;
2880 }
2881 case T_NullIfExpr:
2882 {
2883 NullIfExpr *expr;
2884 ListCell *arg;
2885 bool has_nonconst_input = false;
2886
2887 /* Copy the node and const-simplify its arguments */
2888 expr = (NullIfExpr *) ece_generic_processing(node);
2889
2890 /* If either argument is NULL they can't be equal */
2891 foreach(arg, expr->args)
2892 {
2893 if (!IsA(lfirst(arg), Const))
2894 has_nonconst_input = true;
2895 else if (((Const *) lfirst(arg))->constisnull)
2896 return (Node *) linitial(expr->args);
2897 }
2898
2899 /*
2900 * Need to get OID of underlying function before checking if
2901 * the function is OK to evaluate.
2902 */
2903 set_opfuncid((OpExpr *) expr);
2904
2905 if (!has_nonconst_input &&
2906 ece_function_is_safe(expr->opfuncid, context))
2907 return ece_evaluate_expr(expr);
2908
2909 return (Node *) expr;
2910 }
2912 {
2913 ScalarArrayOpExpr *saop;
2914
2915 /* Copy the node and const-simplify its arguments */
2917
2918 /* Make sure we know underlying function */
2919 set_sa_opfuncid(saop);
2920
2921 /*
2922 * If all arguments are Consts, and it's a safe function, we
2923 * can fold to a constant
2924 */
2925 if (ece_all_arguments_const(saop) &&
2926 ece_function_is_safe(saop->opfuncid, context))
2927 return ece_evaluate_expr(saop);
2928 return (Node *) saop;
2929 }
2930 case T_BoolExpr:
2931 {
2932 BoolExpr *expr = (BoolExpr *) node;
2933
2934 switch (expr->boolop)
2935 {
2936 case OR_EXPR:
2937 {
2938 List *newargs;
2939 bool haveNull = false;
2940 bool forceTrue = false;
2941
2943 context,
2944 &haveNull,
2945 &forceTrue);
2946 if (forceTrue)
2947 return makeBoolConst(true, false);
2948 if (haveNull)
2950 makeBoolConst(false, true));
2951 /* If all the inputs are FALSE, result is FALSE */
2952 if (newargs == NIL)
2953 return makeBoolConst(false, false);
2954
2955 /*
2956 * If only one nonconst-or-NULL input, it's the
2957 * result
2958 */
2959 if (list_length(newargs) == 1)
2960 return (Node *) linitial(newargs);
2961 /* Else we still need an OR node */
2962 return (Node *) make_orclause(newargs);
2963 }
2964 case AND_EXPR:
2965 {
2966 List *newargs;
2967 bool haveNull = false;
2968 bool forceFalse = false;
2969
2971 context,
2972 &haveNull,
2973 &forceFalse);
2974 if (forceFalse)
2975 return makeBoolConst(false, false);
2976 if (haveNull)
2978 makeBoolConst(false, true));
2979 /* If all the inputs are TRUE, result is TRUE */
2980 if (newargs == NIL)
2981 return makeBoolConst(true, false);
2982
2983 /*
2984 * If only one nonconst-or-NULL input, it's the
2985 * result
2986 */
2987 if (list_length(newargs) == 1)
2988 return (Node *) linitial(newargs);
2989 /* Else we still need an AND node */
2990 return (Node *) make_andclause(newargs);
2991 }
2992 case NOT_EXPR:
2993 {
2994 Node *arg;
2995
2996 Assert(list_length(expr->args) == 1);
2998 context);
2999
3000 /*
3001 * Use negate_clause() to see if we can simplify
3002 * away the NOT.
3003 */
3004 return negate_clause(arg);
3005 }
3006 default:
3007 elog(ERROR, "unrecognized boolop: %d",
3008 (int) expr->boolop);
3009 break;
3010 }
3011 break;
3012 }
3013
3014 case T_JsonValueExpr:
3015 {
3016 JsonValueExpr *jve = (JsonValueExpr *) node;
3017 Node *raw_expr = (Node *) jve->raw_expr;
3018 Node *formatted_expr = (Node *) jve->formatted_expr;
3019
3020 /*
3021 * If we can fold formatted_expr to a constant, we can elide
3022 * the JsonValueExpr altogether. Otherwise we must process
3023 * raw_expr too. But JsonFormat is a flat node and requires
3024 * no simplification, only copying.
3025 */
3026 formatted_expr = eval_const_expressions_mutator(formatted_expr,
3027 context);
3028 if (formatted_expr && IsA(formatted_expr, Const))
3029 return formatted_expr;
3030
3031 raw_expr = eval_const_expressions_mutator(raw_expr, context);
3032
3033 return (Node *) makeJsonValueExpr((Expr *) raw_expr,
3034 (Expr *) formatted_expr,
3035 copyObject(jve->format));
3036 }
3037
3038 case T_SubPlan:
3040
3041 /*
3042 * Return a SubPlan unchanged --- too late to do anything with it.
3043 *
3044 * XXX should we ereport() here instead? Probably this routine
3045 * should never be invoked after SubPlan creation.
3046 */
3047 return node;
3048 case T_RelabelType:
3049 {
3050 RelabelType *relabel = (RelabelType *) node;
3051 Node *arg;
3052
3053 /* Simplify the input ... */
3055 context);
3056 /* ... and attach a new RelabelType node, if needed */
3057 return applyRelabelType(arg,
3058 relabel->resulttype,
3059 relabel->resulttypmod,
3060 relabel->resultcollid,
3061 relabel->relabelformat,
3062 relabel->location,
3063 true);
3064 }
3065 case T_CoerceViaIO:
3066 {
3067 CoerceViaIO *expr = (CoerceViaIO *) node;
3068 List *args;
3069 Oid outfunc;
3070 bool outtypisvarlena;
3071 Oid infunc;
3073 Expr *simple;
3075
3076 /* Make a List so we can use simplify_function */
3077 args = list_make1(expr->arg);
3078
3079 /*
3080 * CoerceViaIO represents calling the source type's output
3081 * function then the result type's input function. So, try to
3082 * simplify it as though it were a stack of two such function
3083 * calls. First we need to know what the functions are.
3084 *
3085 * Note that the coercion functions are assumed not to care
3086 * about input collation, so we just pass InvalidOid for that.
3087 */
3091 &infunc, &intypioparam);
3092
3093 simple = simplify_function(outfunc,
3094 CSTRINGOID, -1,
3095 InvalidOid,
3096 InvalidOid,
3097 &args,
3098 false,
3099 true,
3100 true,
3101 context);
3102 if (simple) /* successfully simplified output fn */
3103 {
3104 /*
3105 * Input functions may want 1 to 3 arguments. We always
3106 * supply all three, trusting that nothing downstream will
3107 * complain.
3108 */
3109 args = list_make3(simple,
3111 -1,
3112 InvalidOid,
3113 sizeof(Oid),
3115 false,
3116 true),
3118 -1,
3119 InvalidOid,
3120 sizeof(int32),
3121 Int32GetDatum(-1),
3122 false,
3123 true));
3124
3125 simple = simplify_function(infunc,
3126 expr->resulttype, -1,
3127 expr->resultcollid,
3128 InvalidOid,
3129 &args,
3130 false,
3131 false,
3132 true,
3133 context);
3134 if (simple) /* successfully simplified input fn */
3135 return (Node *) simple;
3136 }
3137
3138 /*
3139 * The expression cannot be simplified any further, so build
3140 * and return a replacement CoerceViaIO node using the
3141 * possibly-simplified argument.
3142 */
3144 newexpr->arg = (Expr *) linitial(args);
3145 newexpr->resulttype = expr->resulttype;
3146 newexpr->resultcollid = expr->resultcollid;
3147 newexpr->coerceformat = expr->coerceformat;
3148 newexpr->location = expr->location;
3149 return (Node *) newexpr;
3150 }
3151 case T_ArrayCoerceExpr:
3152 {
3155
3156 /*
3157 * Copy the node and const-simplify its arguments. We can't
3158 * use ece_generic_processing() here because we need to mess
3159 * with case_val only while processing the elemexpr.
3160 */
3161 memcpy(ac, node, sizeof(ArrayCoerceExpr));
3162 ac->arg = (Expr *)
3164 context);
3165
3166 /*
3167 * Set up for the CaseTestExpr node contained in the elemexpr.
3168 * We must prevent it from absorbing any outer CASE value.
3169 */
3170 save_case_val = context->case_val;
3171 context->case_val = NULL;
3172
3173 ac->elemexpr = (Expr *)
3175 context);
3176
3177 context->case_val = save_case_val;
3178
3179 /*
3180 * If constant argument and the per-element expression is
3181 * immutable, we can simplify the whole thing to a constant.
3182 * Exception: although contain_mutable_functions considers
3183 * CoerceToDomain immutable for historical reasons, let's not
3184 * do so here; this ensures coercion to an array-over-domain
3185 * does not apply the domain's constraints until runtime.
3186 */
3187 if (ac->arg && IsA(ac->arg, Const) &&
3188 ac->elemexpr && !IsA(ac->elemexpr, CoerceToDomain) &&
3189 !contain_mutable_functions((Node *) ac->elemexpr))
3190 return ece_evaluate_expr(ac);
3191
3192 return (Node *) ac;
3193 }
3194 case T_CollateExpr:
3195 {
3196 /*
3197 * We replace CollateExpr with RelabelType, so as to improve
3198 * uniformity of expression representation and thus simplify
3199 * comparison of expressions. Hence this looks very nearly
3200 * the same as the RelabelType case, and we can apply the same
3201 * optimizations to avoid unnecessary RelabelTypes.
3202 */
3203 CollateExpr *collate = (CollateExpr *) node;
3204 Node *arg;
3205
3206 /* Simplify the input ... */
3208 context);
3209 /* ... and attach a new RelabelType node, if needed */
3210 return applyRelabelType(arg,
3211 exprType(arg),
3212 exprTypmod(arg),
3213 collate->collOid,
3215 collate->location,
3216 true);
3217 }
3218 case T_CaseExpr:
3219 {
3220 /*----------
3221 * CASE expressions can be simplified if there are constant
3222 * condition clauses:
3223 * FALSE (or NULL): drop the alternative
3224 * TRUE: drop all remaining alternatives
3225 * If the first non-FALSE alternative is a constant TRUE,
3226 * we can simplify the entire CASE to that alternative's
3227 * expression. If there are no non-FALSE alternatives,
3228 * we simplify the entire CASE to the default result (ELSE).
3229 *
3230 * If we have a simple-form CASE with constant test
3231 * expression, we substitute the constant value for contained
3232 * CaseTestExpr placeholder nodes, so that we have the
3233 * opportunity to reduce constant test conditions. For
3234 * example this allows
3235 * CASE 0 WHEN 0 THEN 1 ELSE 1/0 END
3236 * to reduce to 1 rather than drawing a divide-by-0 error.
3237 * Note that when the test expression is constant, we don't
3238 * have to include it in the resulting CASE; for example
3239 * CASE 0 WHEN x THEN y ELSE z END
3240 * is transformed by the parser to
3241 * CASE 0 WHEN CaseTestExpr = x THEN y ELSE z END
3242 * which we can simplify to
3243 * CASE WHEN 0 = x THEN y ELSE z END
3244 * It is not necessary for the executor to evaluate the "arg"
3245 * expression when executing the CASE, since any contained
3246 * CaseTestExprs that might have referred to it will have been
3247 * replaced by the constant.
3248 *----------
3249 */
3250 CaseExpr *caseexpr = (CaseExpr *) node;
3253 Node *newarg;
3254 List *newargs;
3255 bool const_true_cond;
3256 Node *defresult = NULL;
3257 ListCell *arg;
3258
3259 /* Simplify the test expression, if any */
3261 context);
3262
3263 /* Set up for contained CaseTestExpr nodes */
3264 save_case_val = context->case_val;
3265 if (newarg && IsA(newarg, Const))
3266 {
3267 context->case_val = newarg;
3268 newarg = NULL; /* not needed anymore, see above */
3269 }
3270 else
3271 context->case_val = NULL;
3272
3273 /* Simplify the WHEN clauses */
3274 newargs = NIL;
3275 const_true_cond = false;
3276 foreach(arg, caseexpr->args)
3277 {
3279 Node *casecond;
3281
3282 /* Simplify this alternative's test condition */
3284 context);
3285
3286 /*
3287 * If the test condition is constant FALSE (or NULL), then
3288 * drop this WHEN clause completely, without processing
3289 * the result.
3290 */
3291 if (casecond && IsA(casecond, Const))
3292 {
3294
3295 if (const_input->constisnull ||
3296 !DatumGetBool(const_input->constvalue))
3297 continue; /* drop alternative with FALSE cond */
3298 /* Else it's constant TRUE */
3299 const_true_cond = true;
3300 }
3301
3302 /* Simplify this alternative's result value */
3304 context);
3305
3306 /* If non-constant test condition, emit a new WHEN node */
3307 if (!const_true_cond)
3308 {
3310
3311 newcasewhen->expr = (Expr *) casecond;
3312 newcasewhen->result = (Expr *) caseresult;
3313 newcasewhen->location = oldcasewhen->location;
3315 continue;
3316 }
3317
3318 /*
3319 * Found a TRUE condition, so none of the remaining
3320 * alternatives can be reached. We treat the result as
3321 * the default result.
3322 */
3323 defresult = caseresult;
3324 break;
3325 }
3326
3327 /* Simplify the default result, unless we replaced it above */
3328 if (!const_true_cond)
3329 defresult = eval_const_expressions_mutator((Node *) caseexpr->defresult,
3330 context);
3331
3332 context->case_val = save_case_val;
3333
3334 /*
3335 * If no non-FALSE alternatives, CASE reduces to the default
3336 * result
3337 */
3338 if (newargs == NIL)
3339 return defresult;
3340 /* Otherwise we need a new CASE node */
3342 newcase->casetype = caseexpr->casetype;
3343 newcase->casecollid = caseexpr->casecollid;
3344 newcase->arg = (Expr *) newarg;
3345 newcase->args = newargs;
3346 newcase->defresult = (Expr *) defresult;
3347 newcase->location = caseexpr->location;
3348 return (Node *) newcase;
3349 }
3350 case T_CaseTestExpr:
3351 {
3352 /*
3353 * If we know a constant test value for the current CASE
3354 * construct, substitute it for the placeholder. Else just
3355 * return the placeholder as-is.
3356 */
3357 if (context->case_val)
3358 return copyObject(context->case_val);
3359 else
3360 return copyObject(node);
3361 }
3362 case T_SubscriptingRef:
3363 case T_ArrayExpr:
3364 case T_RowExpr:
3365 case T_MinMaxExpr:
3366 {
3367 /*
3368 * Generic handling for node types whose own processing is
3369 * known to be immutable, and for which we need no smarts
3370 * beyond "simplify if all inputs are constants".
3371 *
3372 * Treating SubscriptingRef this way assumes that subscripting
3373 * fetch and assignment are both immutable. This constrains
3374 * type-specific subscripting implementations; maybe we should
3375 * relax it someday.
3376 *
3377 * Treating MinMaxExpr this way amounts to assuming that the
3378 * btree comparison function it calls is immutable; see the
3379 * reasoning in contain_mutable_functions_walker.
3380 */
3381
3382 /* Copy the node and const-simplify its arguments */
3383 node = ece_generic_processing(node);
3384 /* If all arguments are Consts, we can fold to a constant */
3385 if (ece_all_arguments_const(node))
3386 return ece_evaluate_expr(node);
3387 return node;
3388 }
3389 case T_CoalesceExpr:
3390 {
3393 List *newargs;
3394 ListCell *arg;
3395
3396 newargs = NIL;
3397 foreach(arg, coalesceexpr->args)
3398 {
3399 Node *e;
3400
3402 context);
3403
3404 /*
3405 * We can remove null constants from the list. For a
3406 * nonnullable expression, if it has not been preceded by
3407 * any non-null-constant expressions then it is the
3408 * result. Otherwise, it's the next argument, but we can
3409 * drop following arguments since they will never be
3410 * reached.
3411 */
3412 if (IsA(e, Const))
3413 {
3414 if (((Const *) e)->constisnull)
3415 continue; /* drop null constant */
3416 if (newargs == NIL)
3417 return e; /* first expr */
3419 break;
3420 }
3421 if (expr_is_nonnullable(context->root, (Expr *) e, false))
3422 {
3423 if (newargs == NIL)
3424 return e; /* first expr */
3426 break;
3427 }
3428
3430 }
3431
3432 /*
3433 * If all the arguments were constant null, the result is just
3434 * null
3435 */
3436 if (newargs == NIL)
3437 return (Node *) makeNullConst(coalesceexpr->coalescetype,
3438 -1,
3439 coalesceexpr->coalescecollid);
3440
3441 /*
3442 * If there's exactly one surviving argument, we no longer
3443 * need COALESCE at all: the result is that argument
3444 */
3445 if (list_length(newargs) == 1)
3446 return (Node *) linitial(newargs);
3447
3449 newcoalesce->coalescetype = coalesceexpr->coalescetype;
3450 newcoalesce->coalescecollid = coalesceexpr->coalescecollid;
3451 newcoalesce->args = newargs;
3452 newcoalesce->location = coalesceexpr->location;
3453 return (Node *) newcoalesce;
3454 }
3455 case T_SQLValueFunction:
3456 {
3457 /*
3458 * All variants of SQLValueFunction are stable, so if we are
3459 * estimating the expression's value, we should evaluate the
3460 * current function value. Otherwise just copy.
3461 */
3462 SQLValueFunction *svf = (SQLValueFunction *) node;
3463
3464 if (context->estimate)
3465 return (Node *) evaluate_expr((Expr *) svf,
3466 svf->type,
3467 svf->typmod,
3468 InvalidOid);
3469 else
3470 return copyObject((Node *) svf);
3471 }
3472 case T_FieldSelect:
3473 {
3474 /*
3475 * We can optimize field selection from a whole-row Var into a
3476 * simple Var. (This case won't be generated directly by the
3477 * parser, because ParseComplexProjection short-circuits it.
3478 * But it can arise while simplifying functions.) Also, we
3479 * can optimize field selection from a RowExpr construct, or
3480 * of course from a constant.
3481 *
3482 * However, replacing a whole-row Var in this way has a
3483 * pitfall: if we've already built the rel targetlist for the
3484 * source relation, then the whole-row Var is scheduled to be
3485 * produced by the relation scan, but the simple Var probably
3486 * isn't, which will lead to a failure in setrefs.c. This is
3487 * not a problem when handling simple single-level queries, in
3488 * which expression simplification always happens first. It
3489 * is a risk for lateral references from subqueries, though.
3490 * To avoid such failures, don't optimize uplevel references.
3491 *
3492 * We must also check that the declared type of the field is
3493 * still the same as when the FieldSelect was created --- this
3494 * can change if someone did ALTER COLUMN TYPE on the rowtype.
3495 * If it isn't, we skip the optimization; the case will
3496 * probably fail at runtime, but that's not our problem here.
3497 */
3498 FieldSelect *fselect = (FieldSelect *) node;
3500 Node *arg;
3501
3503 context);
3504 if (arg && IsA(arg, Var) &&
3505 ((Var *) arg)->varattno == InvalidAttrNumber &&
3506 ((Var *) arg)->varlevelsup == 0)
3507 {
3508 if (rowtype_field_matches(((Var *) arg)->vartype,
3509 fselect->fieldnum,
3510 fselect->resulttype,
3511 fselect->resulttypmod,
3512 fselect->resultcollid))
3513 {
3514 Var *newvar;
3515
3516 newvar = makeVar(((Var *) arg)->varno,
3517 fselect->fieldnum,
3518 fselect->resulttype,
3519 fselect->resulttypmod,
3520 fselect->resultcollid,
3521 ((Var *) arg)->varlevelsup);
3522 /* New Var has same OLD/NEW returning as old one */
3523 newvar->varreturningtype = ((Var *) arg)->varreturningtype;
3524 /* New Var is nullable by same rels as the old one */
3525 newvar->varnullingrels = ((Var *) arg)->varnullingrels;
3526 return (Node *) newvar;
3527 }
3528 }
3529 if (arg && IsA(arg, RowExpr))
3530 {
3531 RowExpr *rowexpr = (RowExpr *) arg;
3532
3533 if (fselect->fieldnum > 0 &&
3534 fselect->fieldnum <= list_length(rowexpr->args))
3535 {
3536 Node *fld = (Node *) list_nth(rowexpr->args,
3537 fselect->fieldnum - 1);
3538
3539 if (rowtype_field_matches(rowexpr->row_typeid,
3540 fselect->fieldnum,
3541 fselect->resulttype,
3542 fselect->resulttypmod,
3543 fselect->resultcollid) &&
3544 fselect->resulttype == exprType(fld) &&
3545 fselect->resulttypmod == exprTypmod(fld) &&
3546 fselect->resultcollid == exprCollation(fld))
3547 return fld;
3548 }
3549 }
3551 newfselect->arg = (Expr *) arg;
3552 newfselect->fieldnum = fselect->fieldnum;
3553 newfselect->resulttype = fselect->resulttype;
3554 newfselect->resulttypmod = fselect->resulttypmod;
3555 newfselect->resultcollid = fselect->resultcollid;
3556 if (arg && IsA(arg, Const))
3557 {
3558 Const *con = (Const *) arg;
3559
3561 newfselect->fieldnum,
3562 newfselect->resulttype,
3563 newfselect->resulttypmod,
3564 newfselect->resultcollid))
3566 }
3567 return (Node *) newfselect;
3568 }
3569 case T_NullTest:
3570 {
3571 NullTest *ntest = (NullTest *) node;
3573 Node *arg;
3574
3576 context);
3577 if (ntest->argisrow && arg && IsA(arg, RowExpr))
3578 {
3579 /*
3580 * We break ROW(...) IS [NOT] NULL into separate tests on
3581 * its component fields. This form is usually more
3582 * efficient to evaluate, as well as being more amenable
3583 * to optimization.
3584 */
3585 RowExpr *rarg = (RowExpr *) arg;
3586 List *newargs = NIL;
3587 ListCell *l;
3588
3589 foreach(l, rarg->args)
3590 {
3591 Node *relem = (Node *) lfirst(l);
3592
3593 /*
3594 * A constant field refutes the whole NullTest if it's
3595 * of the wrong nullness; else we can discard it.
3596 */
3597 if (relem && IsA(relem, Const))
3598 {
3599 Const *carg = (Const *) relem;
3600
3601 if (carg->constisnull ?
3602 (ntest->nulltesttype == IS_NOT_NULL) :
3603 (ntest->nulltesttype == IS_NULL))
3604 return makeBoolConst(false, false);
3605 continue;
3606 }
3607
3608 /*
3609 * A proven non-nullable field refutes the whole
3610 * NullTest if the test is IS NULL; else we can
3611 * discard it.
3612 */
3613 if (relem &&
3614 expr_is_nonnullable(context->root, (Expr *) relem,
3615 false))
3616 {
3617 if (ntest->nulltesttype == IS_NULL)
3618 return makeBoolConst(false, false);
3619 continue;
3620 }
3621
3622 /*
3623 * Else, make a scalar (argisrow == false) NullTest
3624 * for this field. Scalar semantics are required
3625 * because IS [NOT] NULL doesn't recurse; see comments
3626 * in ExecEvalRowNullInt().
3627 */
3629 newntest->arg = (Expr *) relem;
3630 newntest->nulltesttype = ntest->nulltesttype;
3631 newntest->argisrow = false;
3632 newntest->location = ntest->location;
3634 }
3635 /* If all the inputs were constants, result is TRUE */
3636 if (newargs == NIL)
3637 return makeBoolConst(true, false);
3638 /* If only one nonconst input, it's the result */
3639 if (list_length(newargs) == 1)
3640 return (Node *) linitial(newargs);
3641 /* Else we need an AND node */
3642 return (Node *) make_andclause(newargs);
3643 }
3644 if (!ntest->argisrow && arg && IsA(arg, Const))
3645 {
3646 Const *carg = (Const *) arg;
3647 bool result;
3648
3649 switch (ntest->nulltesttype)
3650 {
3651 case IS_NULL:
3652 result = carg->constisnull;
3653 break;
3654 case IS_NOT_NULL:
3655 result = !carg->constisnull;
3656 break;
3657 default:
3658 elog(ERROR, "unrecognized nulltesttype: %d",
3659 (int) ntest->nulltesttype);
3660 result = false; /* keep compiler quiet */
3661 break;
3662 }
3663
3664 return makeBoolConst(result, false);
3665 }
3666 if (!ntest->argisrow && arg &&
3667 expr_is_nonnullable(context->root, (Expr *) arg, false))
3668 {
3669 bool result;
3670
3671 switch (ntest->nulltesttype)
3672 {
3673 case IS_NULL:
3674 result = false;
3675 break;
3676 case IS_NOT_NULL:
3677 result = true;
3678 break;
3679 default:
3680 elog(ERROR, "unrecognized nulltesttype: %d",
3681 (int) ntest->nulltesttype);
3682 result = false; /* keep compiler quiet */
3683 break;
3684 }
3685
3686 return makeBoolConst(result, false);
3687 }
3688
3690 newntest->arg = (Expr *) arg;
3691 newntest->nulltesttype = ntest->nulltesttype;
3692 newntest->argisrow = ntest->argisrow;
3693 newntest->location = ntest->location;
3694 return (Node *) newntest;
3695 }
3696 case T_BooleanTest:
3697 {
3698 /*
3699 * This case could be folded into the generic handling used
3700 * for ArrayExpr etc. But because the simplification logic is
3701 * so trivial, applying evaluate_expr() to perform it would be
3702 * a heavy overhead. BooleanTest is probably common enough to
3703 * justify keeping this bespoke implementation.
3704 */
3705 BooleanTest *btest = (BooleanTest *) node;
3707 Node *arg;
3708
3710 context);
3711 if (arg && IsA(arg, Const))
3712 {
3713 /*
3714 * If arg is Const, simplify to constant.
3715 */
3716 Const *carg = (Const *) arg;
3717 bool result;
3718
3719 switch (btest->booltesttype)
3720 {
3721 case IS_TRUE:
3722 result = (!carg->constisnull &&
3723 DatumGetBool(carg->constvalue));
3724 break;
3725 case IS_NOT_TRUE:
3726 result = (carg->constisnull ||
3727 !DatumGetBool(carg->constvalue));
3728 break;
3729 case IS_FALSE:
3730 result = (!carg->constisnull &&
3731 !DatumGetBool(carg->constvalue));
3732 break;
3733 case IS_NOT_FALSE:
3734 result = (carg->constisnull ||
3735 DatumGetBool(carg->constvalue));
3736 break;
3737 case IS_UNKNOWN:
3738 result = carg->constisnull;
3739 break;
3740 case IS_NOT_UNKNOWN:
3741 result = !carg->constisnull;
3742 break;
3743 default:
3744 elog(ERROR, "unrecognized booltesttype: %d",
3745 (int) btest->booltesttype);
3746 result = false; /* keep compiler quiet */
3747 break;
3748 }
3749
3750 return makeBoolConst(result, false);
3751 }
3752 if (arg && expr_is_nonnullable(context->root, (Expr *) arg, false))
3753 {
3754 /*
3755 * If arg is proven non-nullable, simplify to boolean
3756 * expression or constant.
3757 */
3758 switch (btest->booltesttype)
3759 {
3760 case IS_TRUE:
3761 case IS_NOT_FALSE:
3762 return arg;
3763
3764 case IS_FALSE:
3765 case IS_NOT_TRUE:
3766 return (Node *) make_notclause((Expr *) arg);
3767
3768 case IS_UNKNOWN:
3769 return makeBoolConst(false, false);
3770
3771 case IS_NOT_UNKNOWN:
3772 return makeBoolConst(true, false);
3773
3774 default:
3775 elog(ERROR, "unrecognized booltesttype: %d",
3776 (int) btest->booltesttype);
3777 break;
3778 }
3779 }
3780
3782 newbtest->arg = (Expr *) arg;
3783 newbtest->booltesttype = btest->booltesttype;
3784 newbtest->location = btest->location;
3785 return (Node *) newbtest;
3786 }
3787 case T_CoerceToDomain:
3788 {
3789 /*
3790 * If the domain currently has no constraints, we replace the
3791 * CoerceToDomain node with a simple RelabelType, which is
3792 * both far faster to execute and more amenable to later
3793 * optimization. We must then mark the plan as needing to be
3794 * rebuilt if the domain's constraints change.
3795 *
3796 * Also, in estimation mode, always replace CoerceToDomain
3797 * nodes, effectively assuming that the coercion will succeed.
3798 */
3801 Node *arg;
3802
3804 context);
3805 if (context->estimate ||
3806 !DomainHasConstraints(cdomain->resulttype))
3807 {
3808 /* Record dependency, if this isn't estimation mode */
3809 if (context->root && !context->estimate)
3811 cdomain->resulttype);
3812
3813 /* Generate RelabelType to substitute for CoerceToDomain */
3814 return applyRelabelType(arg,
3815 cdomain->resulttype,
3816 cdomain->resulttypmod,
3817 cdomain->resultcollid,
3818 cdomain->coercionformat,
3819 cdomain->location,
3820 true);
3821 }
3822
3824 newcdomain->arg = (Expr *) arg;
3825 newcdomain->resulttype = cdomain->resulttype;
3826 newcdomain->resulttypmod = cdomain->resulttypmod;
3827 newcdomain->resultcollid = cdomain->resultcollid;
3828 newcdomain->coercionformat = cdomain->coercionformat;
3829 newcdomain->location = cdomain->location;
3830 return (Node *) newcdomain;
3831 }
3832 case T_PlaceHolderVar:
3833
3834 /*
3835 * In estimation mode, just strip the PlaceHolderVar node
3836 * altogether; this amounts to estimating that the contained value
3837 * won't be forced to null by an outer join. In regular mode we
3838 * just use the default behavior (ie, simplify the expression but
3839 * leave the PlaceHolderVar node intact).
3840 */
3841 if (context->estimate)
3842 {
3843 PlaceHolderVar *phv = (PlaceHolderVar *) node;
3844
3845 return eval_const_expressions_mutator((Node *) phv->phexpr,
3846 context);
3847 }
3848 break;
3850 {
3852 Node *arg;
3854
3856 context);
3857
3859 newcre->resulttype = cre->resulttype;
3860 newcre->convertformat = cre->convertformat;
3861 newcre->location = cre->location;
3862
3863 /*
3864 * In case of a nested ConvertRowtypeExpr, we can convert the
3865 * leaf row directly to the topmost row format without any
3866 * intermediate conversions. (This works because
3867 * ConvertRowtypeExpr is used only for child->parent
3868 * conversion in inheritance trees, which works by exact match
3869 * of column name, and a column absent in an intermediate
3870 * result can't be present in the final result.)
3871 *
3872 * No need to check more than one level deep, because the
3873 * above recursion will have flattened anything else.
3874 */
3875 if (arg != NULL && IsA(arg, ConvertRowtypeExpr))
3876 {
3878
3879 arg = (Node *) argcre->arg;
3880
3881 /*
3882 * Make sure an outer implicit conversion can't hide an
3883 * inner explicit one.
3884 */
3885 if (newcre->convertformat == COERCE_IMPLICIT_CAST)
3886 newcre->convertformat = argcre->convertformat;
3887 }
3888
3889 newcre->arg = (Expr *) arg;
3890
3891 if (arg != NULL && IsA(arg, Const))
3892 return ece_evaluate_expr((Node *) newcre);
3893 return (Node *) newcre;
3894 }
3895 default:
3896 break;
3897 }
3898
3899 /*
3900 * For any node type not handled above, copy the node unchanged but
3901 * const-simplify its subexpressions. This is the correct thing for node
3902 * types whose behavior might change between planning and execution, such
3903 * as CurrentOfExpr. It's also a safe default for new node types not
3904 * known to this routine.
3905 */
3906 return ece_generic_processing(node);
3907}

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, 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(), negate_clause(), NIL, nodeTag, NOT_EXPR, 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(), 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 5395 of file clauses.c.

5397{
5398 EState *estate;
5399 ExprState *exprstate;
5400 MemoryContext oldcontext;
5402 bool const_is_null;
5404 bool resultTypByVal;
5405
5406 /*
5407 * To use the executor, we need an EState.
5408 */
5409 estate = CreateExecutorState();
5410
5411 /* We can use the estate's working context to avoid memory leaks. */
5412 oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
5413
5414 /* Make sure any opfuncids are filled in. */
5415 fix_opfuncids((Node *) expr);
5416
5417 /*
5418 * Prepare expr for execution. (Note: we can't use ExecPrepareExpr
5419 * because it'd result in recursively invoking eval_const_expressions.)
5420 */
5421 exprstate = ExecInitExpr(expr, NULL);
5422
5423 /*
5424 * And evaluate it.
5425 *
5426 * It is OK to use a default econtext because none of the ExecEvalExpr()
5427 * code used in this situation will use econtext. That might seem
5428 * fortuitous, but it's not so unreasonable --- a constant expression does
5429 * not depend on context, by definition, n'est ce pas?
5430 */
5432 GetPerTupleExprContext(estate),
5433 &const_is_null);
5434
5435 /* Get info needed about result datatype */
5437
5438 /* Get back to outer memory context */
5439 MemoryContextSwitchTo(oldcontext);
5440
5441 /*
5442 * Must copy result out of sub-context used by expression eval.
5443 *
5444 * Also, if it's varlena, forcibly detoast it. This protects us against
5445 * storing TOAST pointers into plans that might outlive the referenced
5446 * data. (makeConst would handle detoasting anyway, but it's worth a few
5447 * extra lines here so that we can do the copy and detoast in one step.)
5448 */
5449 if (!const_is_null)
5450 {
5451 if (resultTypLen == -1)
5453 else
5455 }
5456
5457 /* Release all the junk we just created */
5458 FreeExecutorState(estate);
5459
5460 /*
5461 * Make the constant result node.
5462 */
5463 return (Expr *) makeConst(result_type, result_typmod, result_collation,
5467}

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

4853{
4855 bool has_nonconst_input = false;
4856 bool has_null_input = false;
4857 ListCell *arg;
4859
4860 /*
4861 * Can't simplify if it returns a set.
4862 */
4863 if (funcform->proretset)
4864 return NULL;
4865
4866 /*
4867 * Can't simplify if it returns RECORD. The immediate problem is that it
4868 * will be needing an expected tupdesc which we can't supply here.
4869 *
4870 * In the case where it has OUT parameters, we could build an expected
4871 * tupdesc from those, but there may be other gotchas lurking. In
4872 * particular, if the function were to return NULL, we would produce a
4873 * null constant with no remaining indication of which concrete record
4874 * type it is. For now, seems best to leave the function call unreduced.
4875 */
4876 if (funcform->prorettype == RECORDOID)
4877 return NULL;
4878
4879 /*
4880 * Check for constant inputs and especially constant-NULL inputs.
4881 */
4882 foreach(arg, args)
4883 {
4884 if (IsA(lfirst(arg), Const))
4886 else
4887 has_nonconst_input = true;
4888 }
4889
4890 /*
4891 * If the function is strict and has a constant-NULL input, it will never
4892 * be called at all, so we can replace the call by a NULL constant, even
4893 * if there are other inputs that aren't constant, and even if the
4894 * function is not otherwise immutable.
4895 */
4896 if (funcform->proisstrict && has_null_input)
4897 return (Expr *) makeNullConst(result_type, result_typmod,
4899
4900 /*
4901 * Otherwise, can simplify only if all inputs are constants. (For a
4902 * non-strict function, constant NULL inputs are treated the same as
4903 * constant non-NULL inputs.)
4904 */
4906 return NULL;
4907
4908 /*
4909 * Ordinarily we are only allowed to simplify immutable functions. But for
4910 * purposes of estimation, we consider it okay to simplify functions that
4911 * are merely stable; the risk that the result might change from planning
4912 * time to execution time is worth taking in preference to not being able
4913 * to estimate the value at all.
4914 */
4915 if (funcform->provolatile == PROVOLATILE_IMMUTABLE)
4916 /* okay */ ;
4917 else if (context->estimate && funcform->provolatile == PROVOLATILE_STABLE)
4918 /* okay */ ;
4919 else
4920 return NULL;
4921
4922 /*
4923 * OK, looks like we can simplify this operator/function.
4924 *
4925 * Build a new FuncExpr node containing the already-simplified arguments.
4926 */
4928 newexpr->funcid = funcid;
4929 newexpr->funcresulttype = result_type;
4930 newexpr->funcretset = false;
4931 newexpr->funcvariadic = funcvariadic;
4932 newexpr->funcformat = COERCE_EXPLICIT_CALL; /* doesn't matter */
4933 newexpr->funccollid = result_collid; /* doesn't matter */
4934 newexpr->inputcollid = input_collid;
4935 newexpr->args = args;
4936 newexpr->location = -1;
4937
4938 return evaluate_expr((Expr *) newexpr, result_type, result_typmod,
4940}

References arg, COERCE_EXPLICIT_CALL, eval_const_expressions_context::estimate, evaluate_expr(), fb(), 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 4598 of file clauses.c.

4600{
4602 Oid *proargtypes = funcform->proargtypes.values;
4603 int pronargs = funcform->pronargs;
4604 bool has_named_args = false;
4605 ListCell *lc;
4606
4607 /*
4608 * If we are asked to match to OUT arguments, then use the proallargtypes
4609 * array (which includes those); otherwise use proargtypes (which
4610 * doesn't). Of course, if proallargtypes is null, we always use
4611 * proargtypes. (Fetching proallargtypes is annoyingly expensive
4612 * considering that we may have nothing to do here, but fortunately the
4613 * common case is include_out_arguments == false.)
4614 */
4616 {
4618 bool isNull;
4619
4622 &isNull);
4623 if (!isNull)
4624 {
4626
4627 pronargs = ARR_DIMS(arr)[0];
4628 if (ARR_NDIM(arr) != 1 ||
4629 pronargs < 0 ||
4630 ARR_HASNULL(arr) ||
4631 ARR_ELEMTYPE(arr) != OIDOID)
4632 elog(ERROR, "proallargtypes is not a 1-D Oid array or it contains nulls");
4633 Assert(pronargs >= funcform->pronargs);
4634 proargtypes = (Oid *) ARR_DATA_PTR(arr);
4635 }
4636 }
4637
4638 /* Do we have any named arguments? */
4639 foreach(lc, args)
4640 {
4641 Node *arg = (Node *) lfirst(lc);
4642
4643 if (IsA(arg, NamedArgExpr))
4644 {
4645 has_named_args = true;
4646 break;
4647 }
4648 }
4649
4650 /* If so, we must apply reorder_function_arguments */
4651 if (has_named_args)
4652 {
4654 /* Recheck argument types and add casts if needed */
4655 recheck_cast_function_args(args, result_type,
4657 func_tuple);
4658 }
4659 else if (list_length(args) < pronargs)
4660 {
4661 /* No named args, but we seem to be short some defaults */
4663 /* Recheck argument types and add casts if needed */
4664 recheck_cast_function_args(args, result_type,
4666 func_tuple);
4667 }
4668
4669 return args;
4670}

References add_function_defaults(), arg, ARR_DATA_PTR, ARR_DIMS, ARR_ELEMTYPE, ARR_HASNULL, ARR_NDIM, Assert, DatumGetArrayTypeP, elog, ERROR, fb(), 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,
bool  use_rel_info 
)

Definition at line 4456 of file clauses.c.

4457{
4458 /* since this function recurses, it could be driven to stack overflow */
4460
4461 switch (nodeTag(expr))
4462 {
4463 case T_Var:
4464 {
4465 if (root)
4466 return var_is_nonnullable(root, (Var *) expr, use_rel_info);
4467 }
4468 break;
4469 case T_Const:
4470 return !((Const *) expr)->constisnull;
4471 case T_CoalesceExpr:
4472 {
4473 /*
4474 * A CoalesceExpr returns NULL if and only if all its
4475 * arguments are NULL. Therefore, we can determine that a
4476 * CoalesceExpr cannot be NULL if at least one of its
4477 * arguments can be proven non-nullable.
4478 */
4480
4482 {
4484 return true;
4485 }
4486 }
4487 break;
4488 case T_MinMaxExpr:
4489 {
4490 /*
4491 * Like CoalesceExpr, a MinMaxExpr returns NULL only if all
4492 * its arguments evaluate to NULL.
4493 */
4494 MinMaxExpr *minmaxexpr = (MinMaxExpr *) expr;
4495
4497 {
4499 return true;
4500 }
4501 }
4502 break;
4503 case T_CaseExpr:
4504 {
4505 /*
4506 * A CASE expression is non-nullable if all branch results are
4507 * non-nullable. We must also verify that the default result
4508 * (ELSE) exists and is non-nullable.
4509 */
4510 CaseExpr *caseexpr = (CaseExpr *) expr;
4511
4512 /* The default result must be present and non-nullable */
4513 if (caseexpr->defresult == NULL ||
4515 return false;
4516
4517 /* All branch results must be non-nullable */
4519 {
4521 return false;
4522 }
4523
4524 return true;
4525 }
4526 break;
4527 case T_ArrayExpr:
4528 {
4529 /*
4530 * An ARRAY[] expression always returns a valid Array object,
4531 * even if it is empty (ARRAY[]) or contains NULLs
4532 * (ARRAY[NULL]). It never evaluates to a SQL NULL.
4533 */
4534 return true;
4535 }
4536 case T_NullTest:
4537 {
4538 /*
4539 * An IS NULL / IS NOT NULL expression always returns a
4540 * boolean value. It never returns SQL NULL.
4541 */
4542 return true;
4543 }
4544 case T_BooleanTest:
4545 {
4546 /*
4547 * A BooleanTest expression always evaluates to a boolean
4548 * value. It never returns SQL NULL.
4549 */
4550 return true;
4551 }
4552 case T_DistinctExpr:
4553 {
4554 /*
4555 * IS DISTINCT FROM never returns NULL, effectively acting as
4556 * though NULL were a normal data value.
4557 */
4558 return true;
4559 }
4560 case T_RelabelType:
4561 {
4562 /*
4563 * RelabelType does not change the nullability of the data.
4564 * The result is non-nullable if and only if the argument is
4565 * non-nullable.
4566 */
4567 return expr_is_nonnullable(root, ((RelabelType *) expr)->arg,
4568 use_rel_info);
4569 }
4570 default:
4571 break;
4572 }
4573
4574 return false;
4575}

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

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

◆ expression_returns_set_rows()

double expression_returns_set_rows ( PlannerInfo root,
Node clause 
)

Definition at line 298 of file clauses.c.

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

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

4774{
4775 List *defaults;
4777 char *str;
4778
4782 defaults = castNode(List, stringToNode(str));
4783 pfree(str);
4784 return defaults;
4785}

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

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

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

1929{
1930 List *result = NIL;
1931 Var *var;
1932 ListCell *l;
1933
1934 if (node == NULL)
1935 return NIL;
1936 /* Check single-clause cases using subroutine */
1937 var = find_forced_null_var(node);
1938 if (var)
1939 {
1940 result = mbms_add_member(result,
1941 var->varno,
1943 }
1944 /* Otherwise, handle AND-conditions */
1945 else if (IsA(node, List))
1946 {
1947 /*
1948 * At top level, we are examining an implicit-AND list: if any of the
1949 * arms produces FALSE-or-NULL then the result is FALSE-or-NULL.
1950 */
1951 foreach(l, (List *) node)
1952 {
1953 result = mbms_add_members(result,
1955 }
1956 }
1957 else if (IsA(node, BoolExpr))
1958 {
1959 BoolExpr *expr = (BoolExpr *) node;
1960
1961 /*
1962 * We don't bother considering the OR case, because it's fairly
1963 * unlikely anyone would write "v1 IS NULL OR v1 IS NULL". Likewise,
1964 * the NOT case isn't worth expending code on.
1965 */
1966 if (expr->boolop == AND_EXPR)
1967 {
1968 /* At top level we can just recurse (to the List case) */
1969 result = find_forced_null_vars((Node *) expr->args);
1970 }
1971 }
1972 return result;
1973}
List * find_forced_null_vars(Node *node)
Definition clauses.c:1928
Var * find_forced_null_var(Node *node)
Definition clauses.c:1989
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, 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 1468 of file clauses.c.

1469{
1470 return find_nonnullable_rels_walker(clause, true);
1471}
static Relids find_nonnullable_rels_walker(Node *node, bool top_level)
Definition clauses.c:1474

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

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

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

Referenced by find_nonnullable_rels(), and find_nonnullable_rels_walker().

◆ find_nonnullable_vars()

List * find_nonnullable_vars ( Node clause)

Definition at line 1719 of file clauses.c.

1720{
1721 return find_nonnullable_vars_walker(clause, true);
1722}
static List * find_nonnullable_vars_walker(Node *node, bool top_level)
Definition clauses.c:1725

References find_nonnullable_vars_walker().

Referenced by reduce_outer_joins_pass2().

◆ find_nonnullable_vars_walker()

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

Definition at line 1725 of file clauses.c.

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

Referenced by find_nonnullable_vars(), and find_nonnullable_vars_walker().

◆ find_window_functions()

WindowFuncLists * find_window_functions ( Node clause,
Index  maxWinRef 
)

Definition at line 240 of file clauses.c.

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

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

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

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

4979{
4981 char *src;
4982 Datum tmp;
4983 bool isNull;
4986 inline_error_callback_arg callback_arg;
4988 FuncExpr *fexpr;
4990 TupleDesc rettupdesc;
4991 ParseState *pstate;
4995 Node *newexpr;
4996 int *usecounts;
4997 ListCell *arg;
4998 int i;
4999
5000 /*
5001 * Forget it if the function is not SQL-language or has other showstopper
5002 * properties. (The prokind and nargs checks are just paranoia.)
5003 */
5004 if (funcform->prolang != SQLlanguageId ||
5005 funcform->prokind != PROKIND_FUNCTION ||
5006 funcform->prosecdef ||
5007 funcform->proretset ||
5008 funcform->prorettype == RECORDOID ||
5010 funcform->pronargs != list_length(args))
5011 return NULL;
5012
5013 /* Check for recursive function, and give up trying to expand if so */
5014 if (list_member_oid(context->active_fns, funcid))
5015 return NULL;
5016
5017 /* Check permission to call function (fail later, if not) */
5019 return NULL;
5020
5021 /* Check whether a plugin wants to hook function entry/exit */
5022 if (FmgrHookIsNeeded(funcid))
5023 return NULL;
5024
5025 /*
5026 * Make a temporary memory context, so that we don't leak all the stuff
5027 * that parsing might create.
5028 */
5030 "inline_function",
5033
5034 /*
5035 * We need a dummy FuncExpr node containing the already-simplified
5036 * arguments. (In some cases we don't really need it, but building it is
5037 * cheap enough that it's not worth contortions to avoid.)
5038 */
5040 fexpr->funcid = funcid;
5041 fexpr->funcresulttype = result_type;
5042 fexpr->funcretset = false;
5043 fexpr->funcvariadic = funcvariadic;
5044 fexpr->funcformat = COERCE_EXPLICIT_CALL; /* doesn't matter */
5045 fexpr->funccollid = result_collid; /* doesn't matter */
5046 fexpr->inputcollid = input_collid;
5047 fexpr->args = args;
5048 fexpr->location = -1;
5049
5050 /* Fetch the function body */
5052 src = TextDatumGetCString(tmp);
5053
5054 /*
5055 * Setup error traceback support for ereport(). This is so that we can
5056 * finger the function that bad information came from.
5057 */
5058 callback_arg.proname = NameStr(funcform->proname);
5059 callback_arg.prosrc = src;
5060
5062 sqlerrcontext.arg = &callback_arg;
5065
5066 /* If we have prosqlbody, pay attention to that not prosrc */
5068 func_tuple,
5070 &isNull);
5071 if (!isNull)
5072 {
5073 Node *n;
5074 List *query_list;
5075
5077 if (IsA(n, List))
5078 query_list = linitial_node(List, castNode(List, n));
5079 else
5080 query_list = list_make1(n);
5081 if (list_length(query_list) != 1)
5082 goto fail;
5083 querytree = linitial(query_list);
5084
5085 /*
5086 * Because we'll insist below that the querytree have an empty rtable
5087 * and no sublinks, it cannot have any relation references that need
5088 * to be locked or rewritten. So we can omit those steps.
5089 */
5090 }
5091 else
5092 {
5093 /* Set up to handle parameters while parsing the function body. */
5095 (Node *) fexpr,
5096 input_collid);
5097
5098 /*
5099 * We just do parsing and parse analysis, not rewriting, because
5100 * rewriting will not affect table-free-SELECT-only queries, which is
5101 * all that we care about. Also, we can punt as soon as we detect
5102 * more than one command in the function body.
5103 */
5106 goto fail;
5107
5108 pstate = make_parsestate(NULL);
5109 pstate->p_sourcetext = src;
5110 sql_fn_parser_setup(pstate, pinfo);
5111
5113
5114 free_parsestate(pstate);
5115 }
5116
5117 /*
5118 * The single command must be a simple "SELECT expression".
5119 *
5120 * Note: if you change the tests involved in this, see also plpgsql's
5121 * exec_simple_check_plan(). That generally needs to have the same idea
5122 * of what's a "simple expression", so that inlining a function that
5123 * previously wasn't inlined won't change plpgsql's conclusion.
5124 */
5125 if (!IsA(querytree, Query) ||
5126 querytree->commandType != CMD_SELECT ||
5127 querytree->hasAggs ||
5128 querytree->hasWindowFuncs ||
5129 querytree->hasTargetSRFs ||
5130 querytree->hasSubLinks ||
5131 querytree->cteList ||
5132 querytree->rtable ||
5133 querytree->jointree->fromlist ||
5134 querytree->jointree->quals ||
5135 querytree->groupClause ||
5136 querytree->groupingSets ||
5137 querytree->havingQual ||
5138 querytree->windowClause ||
5139 querytree->distinctClause ||
5140 querytree->sortClause ||
5141 querytree->limitOffset ||
5142 querytree->limitCount ||
5143 querytree->setOperations ||
5144 list_length(querytree->targetList) != 1)
5145 goto fail;
5146
5147 /* If the function result is composite, resolve it */
5149 NULL,
5150 &rettupdesc);
5151
5152 /*
5153 * Make sure the function (still) returns what it's declared to. This
5154 * will raise an error if wrong, but that's okay since the function would
5155 * fail at runtime anyway. Note that check_sql_fn_retval will also insert
5156 * a coercion if needed to make the tlist expression match the declared
5157 * type of the function.
5158 *
5159 * Note: we do not try this until we have verified that no rewriting was
5160 * needed; that's probably not important, but let's be careful.
5161 */
5164 result_type, rettupdesc,
5165 funcform->prokind,
5166 false))
5167 goto fail; /* reject whole-tuple-result cases */
5168
5169 /*
5170 * Given the tests above, check_sql_fn_retval shouldn't have decided to
5171 * inject a projection step, but let's just make sure.
5172 */
5174 goto fail;
5175
5176 /* Now we can grab the tlist expression */
5177 newexpr = (Node *) ((TargetEntry *) linitial(querytree->targetList))->expr;
5178
5179 /*
5180 * If the SQL function returns VOID, we can only inline it if it is a
5181 * SELECT of an expression returning VOID (ie, it's just a redirection to
5182 * another VOID-returning function). In all non-VOID-returning cases,
5183 * check_sql_fn_retval should ensure that newexpr returns the function's
5184 * declared result type, so this test shouldn't fail otherwise; but we may
5185 * as well cope gracefully if it does.
5186 */
5187 if (exprType(newexpr) != result_type)
5188 goto fail;
5189
5190 /*
5191 * Additional validity checks on the expression. It mustn't be more
5192 * volatile than the surrounding function (this is to avoid breaking hacks
5193 * that involve pretending a function is immutable when it really ain't).
5194 * If the surrounding function is declared strict, then the expression
5195 * must contain only strict constructs and must use all of the function
5196 * parameters (this is overkill, but an exact analysis is hard).
5197 */
5198 if (funcform->provolatile == PROVOLATILE_IMMUTABLE &&
5200 goto fail;
5201 else if (funcform->provolatile == PROVOLATILE_STABLE &&
5203 goto fail;
5204
5205 if (funcform->proisstrict &&
5207 goto fail;
5208
5209 /*
5210 * If any parameter expression contains a context-dependent node, we can't
5211 * inline, for fear of putting such a node into the wrong context.
5212 */
5214 goto fail;
5215
5216 /*
5217 * We may be able to do it; there are still checks on parameter usage to
5218 * make, but those are most easily done in combination with the actual
5219 * substitution of the inputs. So start building expression with inputs
5220 * substituted.
5221 */
5222 usecounts = (int *) palloc0(funcform->pronargs * sizeof(int));
5224 args, usecounts);
5225
5226 /* Now check for parameter usage */
5227 i = 0;
5228 foreach(arg, args)
5229 {
5230 Node *param = lfirst(arg);
5231
5232 if (usecounts[i] == 0)
5233 {
5234 /* Param not used at all: uncool if func is strict */
5235 if (funcform->proisstrict)
5236 goto fail;
5237 }
5238 else if (usecounts[i] != 1)
5239 {
5240 /* Param used multiple times: uncool if expensive or volatile */
5242
5243 /*
5244 * We define "expensive" as "contains any subplan or more than 10
5245 * operators". Note that the subplan search has to be done
5246 * explicitly, since cost_qual_eval() will barf on unplanned
5247 * subselects.
5248 */
5249 if (contain_subplans(param))
5250 goto fail;
5252 if (eval_cost.startup + eval_cost.per_tuple >
5253 10 * cpu_operator_cost)
5254 goto fail;
5255
5256 /*
5257 * Check volatility last since this is more expensive than the
5258 * above tests
5259 */
5260 if (contain_volatile_functions(param))
5261 goto fail;
5262 }
5263 i++;
5264 }
5265
5266 /*
5267 * Whew --- we can make the substitution. Copy the modified expression
5268 * out of the temporary memory context, and clean up.
5269 */
5271
5273
5275
5276 /*
5277 * If the result is of a collatable type, force the result to expose the
5278 * correct collation. In most cases this does not matter, but it's
5279 * possible that the function result is used directly as a sort key or in
5280 * other places where we expect exprCollation() to tell the truth.
5281 */
5283 {
5285
5287 {
5289
5290 newnode->arg = (Expr *) newexpr;
5291 newnode->collOid = result_collid;
5292 newnode->location = -1;
5293
5294 newexpr = (Node *) newnode;
5295 }
5296 }
5297
5298 /*
5299 * Since there is now no trace of the function in the plan tree, we must
5300 * explicitly record the plan's dependency on the function.
5301 */
5302 if (context->root)
5303 record_plan_function_dependency(context->root, funcid);
5304
5305 /*
5306 * Recursively try to simplify the modified expression. Here we must add
5307 * the current function to the context list of active functions.
5308 */
5309 context->active_fns = lappend_oid(context->active_fns, funcid);
5311 context->active_fns = list_delete_last(context->active_fns);
5312
5314
5315 return (Expr *) newexpr;
5316
5317 /* Here if func is not inlinable: release temp memory and return NULL */
5318fail:
5322
5323 return NULL;
5324}

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

5488{
5489 RangeTblFunction *rtfunc;
5490 FuncExpr *fexpr;
5491 Oid func_oid;
5496 Datum tmp;
5497 char *src;
5498 inline_error_callback_arg callback_arg;
5500 Query *querytree = NULL;
5501
5502 Assert(rte->rtekind == RTE_FUNCTION);
5503
5504 /*
5505 * Guard against infinite recursion during expansion by checking for stack
5506 * overflow. (There's no need to do more.)
5507 */
5509
5510 /* Fail if the RTE has ORDINALITY - we don't implement that here. */
5511 if (rte->funcordinality)
5512 return NULL;
5513
5514 /* Fail if RTE isn't a single, simple FuncExpr */
5515 if (list_length(rte->functions) != 1)
5516 return NULL;
5517 rtfunc = (RangeTblFunction *) linitial(rte->functions);
5518
5519 if (!IsA(rtfunc->funcexpr, FuncExpr))
5520 return NULL;
5521 fexpr = (FuncExpr *) rtfunc->funcexpr;
5522
5523 func_oid = fexpr->funcid;
5524
5525 /*
5526 * Refuse to inline if the arguments contain any volatile functions or
5527 * sub-selects. Volatile functions are rejected because inlining may
5528 * result in the arguments being evaluated multiple times, risking a
5529 * change in behavior. Sub-selects are rejected partly for implementation
5530 * reasons (pushing them down another level might change their behavior)
5531 * and partly because they're likely to be expensive and so multiple
5532 * evaluation would be bad.
5533 */
5534 if (contain_volatile_functions((Node *) fexpr->args) ||
5535 contain_subplans((Node *) fexpr->args))
5536 return NULL;
5537
5538 /* Check permission to call function (fail later, if not) */
5540 return NULL;
5541
5542 /* Check whether a plugin wants to hook function entry/exit */
5544 return NULL;
5545
5546 /*
5547 * OK, let's take a look at the function's pg_proc entry.
5548 */
5551 elog(ERROR, "cache lookup failed for function %u", func_oid);
5553
5554 /*
5555 * If the function SETs any configuration parameters, inlining would cause
5556 * us to miss making those changes.
5557 */
5559 {
5561 return NULL;
5562 }
5563
5564 /*
5565 * Make a temporary memory context, so that we don't leak all the stuff
5566 * that parsing and rewriting might create. If we succeed, we'll copy
5567 * just the finished query tree back up to the caller's context.
5568 */
5570 "inline_function_in_from",
5573
5574 /* Fetch the function body */
5576 src = TextDatumGetCString(tmp);
5577
5578 /*
5579 * If the function has an attached support function that can handle
5580 * SupportRequestInlineInFrom, then attempt to inline with that.
5581 */
5582 if (funcform->prosupport)
5583 {
5585
5587 req.root = root;
5588 req.rtfunc = rtfunc;
5589 req.proc = func_tuple;
5590
5591 querytree = (Query *)
5593 PointerGetDatum(&req)));
5594 }
5595
5596 /*
5597 * Setup error traceback support for ereport(). This is so that we can
5598 * finger the function that bad information came from. We don't install
5599 * this while running the support function, since it'd be likely to do the
5600 * wrong thing: any parse errors reported during that are very likely not
5601 * against the raw function source text.
5602 */
5603 callback_arg.proname = NameStr(funcform->proname);
5604 callback_arg.prosrc = src;
5605
5607 sqlerrcontext.arg = &callback_arg;
5610
5611 /*
5612 * If SupportRequestInlineInFrom didn't work, try our built-in inlining
5613 * mechanism.
5614 */
5615 if (!querytree)
5617 func_tuple, funcform, src);
5618
5619 if (!querytree)
5620 goto fail; /* no luck there either, fail */
5621
5622 /*
5623 * The result had better be a SELECT Query.
5624 */
5626 Assert(querytree->commandType == CMD_SELECT);
5627
5628 /*
5629 * Looks good --- substitute parameters into the query.
5630 */
5632 funcform->pronargs,
5633 fexpr->args);
5634
5635 /*
5636 * Copy the modified query out of the temporary memory context, and clean
5637 * up.
5638 */
5640
5642
5646
5647 /*
5648 * We don't have to fix collations here because the upper query is already
5649 * parsed, ie, the collations in the RTE are what count.
5650 */
5651
5652 /*
5653 * Since there is now no trace of the function in the plan tree, we must
5654 * explicitly record the plan's dependency on the function.
5655 */
5657
5658 /*
5659 * We must also notice if the inserted query adds a dependency on the
5660 * calling role due to RLS quals.
5661 */
5662 if (querytree->hasRowSecurity)
5663 root->glob->dependsOnRole = true;
5664
5665 return querytree;
5666
5667 /* Here if func is not inlinable: release temp memory and return NULL */
5668fail:
5673
5674 return NULL;
5675}

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

5697{
5698 Datum sqlbody;
5699 bool isNull;
5703 TupleDesc rettupdesc;
5704
5705 /*
5706 * The function must be declared to return a set, else inlining would
5707 * change the results if the contained SELECT didn't return exactly one
5708 * row.
5709 */
5710 if (!fexpr->funcretset)
5711 return NULL;
5712
5713 /*
5714 * Forget it if the function is not SQL-language or has other showstopper
5715 * properties. In particular it mustn't be declared STRICT, since we
5716 * couldn't enforce that. It also mustn't be VOLATILE, because that is
5717 * supposed to cause it to be executed with its own snapshot, rather than
5718 * sharing the snapshot of the calling query. We also disallow returning
5719 * SETOF VOID, because inlining would result in exposing the actual result
5720 * of the function's last SELECT, which should not happen in that case.
5721 * (Rechecking prokind, proretset, and pronargs is just paranoia.)
5722 */
5723 if (funcform->prolang != SQLlanguageId ||
5724 funcform->prokind != PROKIND_FUNCTION ||
5725 funcform->proisstrict ||
5726 funcform->provolatile == PROVOLATILE_VOLATILE ||
5727 funcform->prorettype == VOIDOID ||
5728 funcform->prosecdef ||
5729 !funcform->proretset ||
5730 list_length(fexpr->args) != funcform->pronargs)
5731 return NULL;
5732
5733 /* If we have prosqlbody, pay attention to that not prosrc */
5735 func_tuple,
5737 &isNull);
5738 if (!isNull)
5739 {
5740 Node *n;
5741
5743 if (IsA(n, List))
5745 else
5747 if (list_length(querytree_list) != 1)
5748 return NULL;
5750
5751 /* Acquire necessary locks, then apply rewriter. */
5752 AcquireRewriteLocks(querytree, true, false);
5754 if (list_length(querytree_list) != 1)
5755 return NULL;
5757 }
5758 else
5759 {
5762
5763 /*
5764 * Set up to handle parameters while parsing the function body. We
5765 * can use the FuncExpr just created as the input for
5766 * prepare_sql_fn_parse_info.
5767 */
5769 (Node *) fexpr,
5770 fexpr->inputcollid);
5771
5772 /*
5773 * Parse, analyze, and rewrite (unlike inline_function(), we can't
5774 * skip rewriting here). We can fail as soon as we find more than one
5775 * query, though.
5776 */
5779 return NULL;
5780
5782 src,
5784 pinfo, NULL);
5785 if (list_length(querytree_list) != 1)
5786 return NULL;
5788 }
5789
5790 /*
5791 * Also resolve the actual function result tupdesc, if composite. If we
5792 * have a coldeflist, believe that; otherwise use get_expr_result_type.
5793 * (This logic should match ExecInitFunctionScan.)
5794 */
5795 if (rtfunc->funccolnames != NIL)
5796 {
5798 rettupdesc = BuildDescFromLists(rtfunc->funccolnames,
5799 rtfunc->funccoltypes,
5800 rtfunc->funccoltypmods,
5801 rtfunc->funccolcollations);
5802 }
5803 else
5804 functypclass = get_expr_result_type((Node *) fexpr, NULL, &rettupdesc);
5805
5806 /*
5807 * The single command must be a plain SELECT.
5808 */
5809 if (!IsA(querytree, Query) ||
5810 querytree->commandType != CMD_SELECT)
5811 return NULL;
5812
5813 /*
5814 * Make sure the function (still) returns what it's declared to. This
5815 * will raise an error if wrong, but that's okay since the function would
5816 * fail at runtime anyway. Note that check_sql_fn_retval will also insert
5817 * coercions if needed to make the tlist expression(s) match the declared
5818 * type of the function. We also ask it to insert dummy NULL columns for
5819 * any dropped columns in rettupdesc, so that the elements of the modified
5820 * tlist match up to the attribute numbers.
5821 *
5822 * If the function returns a composite type, don't inline unless the check
5823 * shows it's returning a whole tuple result; otherwise what it's
5824 * returning is a single composite column which is not what we need.
5825 */
5827 fexpr->funcresulttype, rettupdesc,
5828 funcform->prokind,
5829 true) &&
5833 return NULL; /* reject not-whole-tuple-result cases */
5834
5835 /*
5836 * check_sql_fn_retval might've inserted a projection step, but that's
5837 * fine; just make sure we use the upper Query.
5838 */
5840
5841 return querytree;
5842}

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

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

2101{
2102 /*
2103 * We could implement this check in one recursive scan. But since the
2104 * check for volatile functions is both moderately expensive and unlikely
2105 * to fail, it seems better to look for Vars first and only check for
2106 * volatile functions if we find no Vars.
2107 */
2108 if (!contain_var_clause(clause) &&
2110 return true;
2111 return false;
2112}

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

2121{
2122 if (bms_is_empty(relids) &&
2124 return true;
2125 return false;
2126}

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

2039{
2040 Node *rightop;
2041
2042 /* The contained operator must be strict. */
2043 set_sa_opfuncid(expr);
2044 if (!func_strict(expr->opfuncid))
2045 return false;
2046 /* If ANY and falseOK, that's all we need to check. */
2047 if (expr->useOr && falseOK)
2048 return true;
2049 /* Else, we have to see if the array is provably non-empty. */
2050 Assert(list_length(expr->args) == 2);
2051 rightop = (Node *) lsecond(expr->args);
2052 if (rightop && IsA(rightop, Const))
2053 {
2054 Datum arraydatum = ((Const *) rightop)->constvalue;
2055 bool arrayisnull = ((Const *) rightop)->constisnull;
2057 int nitems;
2058
2059 if (arrayisnull)
2060 return false;
2063 if (nitems > 0)
2064 return true;
2065 }
2066 else if (rightop && IsA(rightop, ArrayExpr))
2067 {
2068 ArrayExpr *arrayexpr = (ArrayExpr *) rightop;
2069
2070 if (arrayexpr->elements != NIL && !arrayexpr->multidims)
2071 return true;
2072 }
2073 return false;
2074}

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

5945{
5946 Node *arrayNode = NULL;
5948 Oid arraytype = get_array_type(coltype);
5949
5950 if (!OidIsValid(arraytype))
5951 return NULL;
5952
5953 /*
5954 * Assemble an array from the list of constants. It seems more profitable
5955 * to build a const array. But in the presence of other nodes, we don't
5956 * have a specific value here and must employ an ArrayExpr instead.
5957 */
5958 if (haveNonConst)
5959 {
5961
5962 /* array_collid will be set by parse_collate.c */
5963 arrayExpr->element_typeid = coltype;
5964 arrayExpr->array_typeid = arraytype;
5965 arrayExpr->multidims = false;
5966 arrayExpr->elements = exprs;
5967 arrayExpr->location = -1;
5968
5969 arrayNode = (Node *) arrayExpr;
5970 }
5971 else
5972 {
5973 int16 typlen;
5974 bool typbyval;
5975 char typalign;
5976 Datum *elems;
5977 bool *nulls;
5978 int i = 0;
5980 int dims[1] = {list_length(exprs)};
5981 int lbs[1] = {1};
5982
5983 get_typlenbyvalalign(coltype, &typlen, &typbyval, &typalign);
5984
5985 elems = palloc_array(Datum, list_length(exprs));
5986 nulls = palloc_array(bool, list_length(exprs));
5987 foreach_node(Const, value, exprs)
5988 {
5989 elems[i] = value->constvalue;
5990 nulls[i++] = value->constisnull;
5991 }
5992
5993 arrayConst = construct_md_array(elems, nulls, 1, dims, lbs,
5994 coltype, typlen, typbyval, typalign);
5997 false, false);
5998
5999 pfree(elems);
6000 pfree(nulls);
6001 list_free(exprs);
6002 }
6003
6004 /* Build the SAOP expression node */
6006 saopexpr->opno = oper;
6007 saopexpr->opfuncid = get_opcode(oper);
6008 saopexpr->hashfuncid = InvalidOid;
6009 saopexpr->negfuncid = InvalidOid;
6010 saopexpr->useOr = true;
6011 saopexpr->inputcollid = inputcollid;
6013 saopexpr->location = -1;
6014
6015 return saopexpr;
6016}

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

832{
834 (max_parallel_hazard_context *) context);
835}
static bool max_parallel_hazard_test(char proparallel, max_parallel_hazard_context *context)
Definition clauses.c:803
char func_parallel(Oid funcid)
Definition lsyscache.c:1949

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

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

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

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

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

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

◆ NumRelids()

int NumRelids ( PlannerInfo root,
Node clause 
)

Definition at line 2142 of file clauses.c.

2143{
2144 int result;
2145 Relids varnos = pull_varnos(root, clause);
2146
2147 varnos = bms_del_members(varnos, root->outer_join_rels);
2148 result = bms_num_members(varnos);
2149 bms_free(varnos);
2150 return result;
2151}
Bitmapset * bms_del_members(Bitmapset *a, const Bitmapset *b)
Definition bitmapset.c:1160
void bms_free(Bitmapset *a)
Definition bitmapset.c:239
int bms_num_members(const Bitmapset *a)
Definition bitmapset.c:750
Relids pull_varnos(PlannerInfo *root, Node *node)
Definition var.c:114

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

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

◆ pull_paramids()

Bitmapset * pull_paramids ( Expr expr)

Definition at line 5911 of file clauses.c.

5912{
5913 Bitmapset *result = NULL;
5914
5915 (void) pull_paramids_walker((Node *) expr, &result);
5916
5917 return result;
5918}

References fb(), and pull_paramids_walker().

Referenced by create_memoize_plan().

◆ pull_paramids_walker()

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

Definition at line 5921 of file clauses.c.

5922{
5923 if (node == NULL)
5924 return false;
5925 if (IsA(node, Param))
5926 {
5927 Param *param = (Param *) node;
5928
5929 *context = bms_add_member(*context, param->paramid);
5930 return false;
5931 }
5932 return expression_tree_walker(node, pull_paramids_walker, context);
5933}

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

Referenced by pull_paramids(), and pull_paramids_walker().

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

4806{
4808 int nargs;
4811 Oid rettype;
4812 ListCell *lc;
4813
4814 if (list_length(args) > FUNC_MAX_ARGS)
4815 elog(ERROR, "too many function arguments");
4816 nargs = 0;
4817 foreach(lc, args)
4818 {
4819 actual_arg_types[nargs++] = exprType((Node *) lfirst(lc));
4820 }
4821 Assert(nargs == pronargs);
4825 nargs,
4826 funcform->prorettype,
4827 false);
4828 /* let's just check we got the same answer as the parser did ... */
4829 if (rettype != result_type)
4830 elog(ERROR, "function's resolved result type changed during planning");
4831
4832 /* perform any necessary typecasting of arguments */
4834}

References Assert, elog, enforce_generic_type_consistency(), ERROR, exprType(), fb(), FUNC_MAX_ARGS, GETSTRUCT(), lfirst, list_length(), make_fn_arguments(), 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 4679 of file clauses.c.

4680{
4682 int nargsprovided = list_length(args);
4684 ListCell *lc;
4685 int i;
4686
4689 elog(ERROR, "too many function arguments");
4690 memset(argarray, 0, pronargs * sizeof(Node *));
4691
4692 /* Deconstruct the argument list into an array indexed by argnumber */
4693 i = 0;
4694 foreach(lc, args)
4695 {
4696 Node *arg = (Node *) lfirst(lc);
4697
4698 if (!IsA(arg, NamedArgExpr))
4699 {
4700 /* positional argument, assumed to precede all named args */
4701 Assert(argarray[i] == NULL);
4702 argarray[i++] = arg;
4703 }
4704 else
4705 {
4707
4708 Assert(na->argnumber >= 0 && na->argnumber < pronargs);
4709 Assert(argarray[na->argnumber] == NULL);
4710 argarray[na->argnumber] = (Node *) na->arg;
4711 }
4712 }
4713
4714 /*
4715 * Fetch default expressions, if needed, and insert into array at proper
4716 * locations (they aren't necessarily consecutive or all used)
4717 */
4718 if (nargsprovided < pronargs)
4719 {
4721
4722 i = pronargs - funcform->pronargdefaults;
4723 foreach(lc, defaults)
4724 {
4725 if (argarray[i] == NULL)
4726 argarray[i] = (Node *) lfirst(lc);
4727 i++;
4728 }
4729 }
4730
4731 /* Now reconstruct the args list in proper order */
4732 args = NIL;
4733 for (i = 0; i < pronargs; i++)
4734 {
4735 Assert(argarray[i] != NULL);
4736 args = lappend(args, argarray[i]);
4737 }
4738
4739 return args;
4740}

References arg, Assert, elog, ERROR, fb(), fetch_function_defaults(), 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 2198 of file clauses.c.

2201{
2202 TupleDesc tupdesc;
2203 Form_pg_attribute attr;
2204
2205 /* No issue for RECORD, since there is no way to ALTER such a type */
2206 if (rowtypeid == RECORDOID)
2207 return true;
2208 tupdesc = lookup_rowtype_tupdesc_domain(rowtypeid, -1, false);
2210 {
2211 ReleaseTupleDesc(tupdesc);
2212 return false;
2213 }
2214 attr = TupleDescAttr(tupdesc, fieldnum - 1);
2215 if (attr->attisdropped ||
2216 attr->atttypid != expectedtype ||
2217 attr->atttypmod != expectedtypmod ||
2218 attr->attcollation != expectedcollation)
2219 {
2220 ReleaseTupleDesc(tupdesc);
2221 return false;
2222 }
2223 ReleaseTupleDesc(tupdesc);
2224 return true;
2225}
FormData_pg_attribute * Form_pg_attribute
#define ReleaseTupleDesc(tupdesc)
Definition tupdesc.h:219
static FormData_pg_attribute * TupleDescAttr(TupleDesc tupdesc, int i)
Definition tupdesc.h:160
TupleDesc lookup_rowtype_tupdesc_domain(Oid type_id, int32 typmod, bool noError)
Definition typcache.c:1980

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

4349{
4351
4353 {
4355 Node *newnode;
4356
4357 /*
4358 * Build a SupportRequestSimplifyAggref node to pass to the support
4359 * function.
4360 */
4362 req.root = context->root;
4363 req.aggref = aggref;
4364
4366 PointerGetDatum(&req)));
4367
4368 /*
4369 * We expect the support function to return either a new Node or NULL
4370 * (when simplification isn't possible).
4371 */
4372 Assert(newnode != (Node *) aggref || newnode == NULL);
4373
4374 if (newnode != NULL)
4375 return newnode;
4376 }
4377
4378 return (Node *) aggref;
4379}

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

4082{
4083 List *newargs = NIL;
4085
4086 /* See comments in simplify_or_arguments */
4088 while (unprocessed_args)
4089 {
4091
4093
4094 /* flatten nested ANDs as per above comment */
4095 if (is_andclause(arg))
4096 {
4097 List *subargs = ((BoolExpr *) arg)->args;
4099
4101 /* perhaps-overly-tense code to avoid leaking old lists */
4103 continue;
4104 }
4105
4106 /* If it's not an AND, simplify it */
4108
4109 /*
4110 * It is unlikely but not impossible for simplification of a non-AND
4111 * clause to produce an AND. Recheck, but don't be too tense about it
4112 * since it's not a mainstream case. In particular we don't worry
4113 * about const-simplifying the input twice, nor about list leakage.
4114 */
4115 if (is_andclause(arg))
4116 {
4117 List *subargs = ((BoolExpr *) arg)->args;
4118
4120 continue;
4121 }
4122
4123 /*
4124 * OK, we have a const-simplified non-AND argument. Process it per
4125 * comments above.
4126 */
4127 if (IsA(arg, Const))
4128 {
4129 Const *const_input = (Const *) arg;
4130
4131 if (const_input->constisnull)
4132 *haveNull = true;
4133 else if (!DatumGetBool(const_input->constvalue))
4134 {
4135 *forceFalse = true;
4136
4137 /*
4138 * Once we detect a FALSE result we can just exit the loop
4139 * immediately. However, if we ever add a notion of
4140 * non-removable functions, we'd need to keep scanning.
4141 */
4142 return NIL;
4143 }
4144 /* otherwise, we can drop the constant-true input */
4145 continue;
4146 }
4147
4148 /* else emit the simplified arg into the result list */
4150 }
4151
4152 return newargs;
4153}

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

4174{
4175 Node *leftop;
4176 Node *rightop;
4177
4178 Assert(list_length(args) == 2);
4179 leftop = linitial(args);
4180 rightop = lsecond(args);
4181 if (leftop && IsA(leftop, Const))
4182 {
4183 Assert(!((Const *) leftop)->constisnull);
4184 if (opno == BooleanEqualOperator)
4185 {
4186 if (DatumGetBool(((Const *) leftop)->constvalue))
4187 return rightop; /* true = foo */
4188 else
4189 return negate_clause(rightop); /* false = foo */
4190 }
4191 else
4192 {
4193 if (DatumGetBool(((Const *) leftop)->constvalue))
4194 return negate_clause(rightop); /* true <> foo */
4195 else
4196 return rightop; /* false <> foo */
4197 }
4198 }
4199 if (rightop && IsA(rightop, Const))
4200 {
4202 if (opno == BooleanEqualOperator)
4203 {
4205 return leftop; /* foo = true */
4206 else
4207 return negate_clause(leftop); /* foo = false */
4208 }
4209 else
4210 {
4212 return negate_clause(leftop); /* foo <> true */
4213 else
4214 return leftop; /* foo <> false */
4215 }
4216 }
4217 return NULL;
4218}

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

4246{
4247 List *args = *args_p;
4250 Expr *newexpr;
4251
4252 /*
4253 * We have three strategies for simplification: execute the function to
4254 * deliver a constant result, use a transform function to generate a
4255 * substitute node tree, or expand in-line the body of the function
4256 * definition (which only works for simple SQL-language functions, but
4257 * that is a common case). Each case needs access to the function's
4258 * pg_proc tuple, so fetch it just once.
4259 *
4260 * Note: the allow_non_const flag suppresses both the second and third
4261 * strategies; so if !allow_non_const, simplify_function can only return a
4262 * Const or NULL. Argument-list rewriting happens anyway, though.
4263 */
4266 elog(ERROR, "cache lookup failed for function %u", funcid);
4268
4269 /*
4270 * Process the function arguments, unless the caller did it already.
4271 *
4272 * Here we must deal with named or defaulted arguments, and then
4273 * recursively apply eval_const_expressions to the whole argument list.
4274 */
4275 if (process_args)
4276 {
4277 args = expand_function_arguments(args, false, result_type, func_tuple);
4280 context);
4281 /* Argument processing done, give it back to the caller */
4282 *args_p = args;
4283 }
4284
4285 /* Now attempt simplification of the function call proper. */
4286
4287 newexpr = evaluate_function(funcid, result_type, result_typmod,
4289 args, funcvariadic,
4290 func_tuple, context);
4291
4292 if (!newexpr && allow_non_const && OidIsValid(func_form->prosupport))
4293 {
4294 /*
4295 * Build a SupportRequestSimplify node to pass to the support
4296 * function, pointing to a dummy FuncExpr node containing the
4297 * simplified arg list. We use this approach to present a uniform
4298 * interface to the support function regardless of how the target
4299 * function is actually being invoked.
4300 */
4303
4304 fexpr.xpr.type = T_FuncExpr;
4305 fexpr.funcid = funcid;
4306 fexpr.funcresulttype = result_type;
4307 fexpr.funcretset = func_form->proretset;
4308 fexpr.funcvariadic = funcvariadic;
4309 fexpr.funcformat = COERCE_EXPLICIT_CALL;
4310 fexpr.funccollid = result_collid;
4311 fexpr.inputcollid = input_collid;
4312 fexpr.args = args;
4313 fexpr.location = -1;
4314
4316 req.root = context->root;
4317 req.fcall = &fexpr;
4318
4319 newexpr = (Expr *)
4321 PointerGetDatum(&req)));
4322
4323 /* catch a possible API misunderstanding */
4324 Assert(newexpr != (Expr *) &fexpr);
4325 }
4326
4327 if (!newexpr && allow_non_const)
4328 newexpr = inline_function(funcid, result_type, result_collid,
4330 func_tuple, context);
4331
4333
4334 return newexpr;
4335}

References Assert, COERCE_EXPLICIT_CALL, DatumGetPointer(), elog, ERROR, eval_const_expressions_mutator(), evaluate_function(), expand_function_arguments(), expression_tree_mutator, fb(), 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 3973 of file clauses.c.

3976{
3977 List *newargs = NIL;
3979
3980 /*
3981 * We want to ensure that any OR immediately beneath another OR gets
3982 * flattened into a single OR-list, so as to simplify later reasoning.
3983 *
3984 * To avoid stack overflow from recursion of eval_const_expressions, we
3985 * resort to some tenseness here: we keep a list of not-yet-processed
3986 * inputs, and handle flattening of nested ORs by prepending to the to-do
3987 * list instead of recursing. Now that the parser generates N-argument
3988 * ORs from simple lists, this complexity is probably less necessary than
3989 * it once was, but we might as well keep the logic.
3990 */
3992 while (unprocessed_args)
3993 {
3995
3997
3998 /* flatten nested ORs as per above comment */
3999 if (is_orclause(arg))
4000 {
4001 List *subargs = ((BoolExpr *) arg)->args;
4003
4005 /* perhaps-overly-tense code to avoid leaking old lists */
4007 continue;
4008 }
4009
4010 /* If it's not an OR, simplify it */
4012
4013 /*
4014 * It is unlikely but not impossible for simplification of a non-OR
4015 * clause to produce an OR. Recheck, but don't be too tense about it
4016 * since it's not a mainstream case. In particular we don't worry
4017 * about const-simplifying the input twice, nor about list leakage.
4018 */
4019 if (is_orclause(arg))
4020 {
4021 List *subargs = ((BoolExpr *) arg)->args;
4022
4024 continue;
4025 }
4026
4027 /*
4028 * OK, we have a const-simplified non-OR argument. Process it per
4029 * comments above.
4030 */
4031 if (IsA(arg, Const))
4032 {
4033 Const *const_input = (Const *) arg;
4034
4035 if (const_input->constisnull)
4036 *haveNull = true;
4037 else if (DatumGetBool(const_input->constvalue))
4038 {
4039 *forceTrue = true;
4040
4041 /*
4042 * Once we detect a TRUE result we can just exit the loop
4043 * immediately. However, if we ever add a notion of
4044 * non-removable functions, we'd need to keep scanning.
4045 */
4046 return NIL;
4047 }
4048 /* otherwise, we can drop the constant-false input */
4049 continue;
4050 }
4051
4052 /* else emit the simplified arg into the result list */
4054 }
4055
4056 return newargs;
4057}

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

5372{
5375
5376 /* If it's a syntax error, convert to internal syntax error report */
5378 if (syntaxerrposition > 0)
5379 {
5380 errposition(0);
5382 internalerrquery(callback_arg->prosrc);
5383 }
5384
5385 errcontext("SQL function \"%s\" during inlining", callback_arg->proname);
5386}

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

5332{
5334
5335 context.nargs = nargs;
5336 context.args = args;
5337 context.usecounts = usecounts;
5338
5339 return substitute_actual_parameters_mutator(expr, &context);
5340}

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

5868{
5869 Node *result;
5870
5871 if (node == NULL)
5872 return NULL;
5873 if (IsA(node, Query))
5874 {
5875 context->sublevels_up++;
5876 result = (Node *) query_tree_mutator((Query *) node,
5878 context,
5879 0);
5880 context->sublevels_up--;
5881 return result;
5882 }
5883 if (IsA(node, Param))
5884 {
5885 Param *param = (Param *) node;
5886
5887 if (param->paramkind == PARAM_EXTERN)
5888 {
5889 if (param->paramid <= 0 || param->paramid > context->nargs)
5890 elog(ERROR, "invalid paramid: %d", param->paramid);
5891
5892 /*
5893 * Since the parameter is being inserted into a subquery, we must
5894 * adjust levels.
5895 */
5896 result = copyObject(list_nth(context->args, param->paramid - 1));
5897 IncrementVarSublevelsUp(result, context->sublevels_up, 0);
5898 return result;
5899 }
5900 }
5901 return expression_tree_mutator(node,
5903 context);
5904}

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

5345{
5346 if (node == NULL)
5347 return NULL;
5348 if (IsA(node, Param))
5349 {
5350 Param *param = (Param *) node;
5351
5352 if (param->paramkind != PARAM_EXTERN)
5353 elog(ERROR, "unexpected paramkind: %d", (int) param->paramkind);
5354 if (param->paramid <= 0 || param->paramid > context->nargs)
5355 elog(ERROR, "invalid paramid: %d", param->paramid);
5356
5357 /* Count usage of parameter */
5358 context->usecounts[param->paramid - 1]++;
5359
5360 /* Select the appropriate actual arg and replace the Param with it */
5361 /* We don't need to copy at this time (it'll get done later) */
5362 return list_nth(context->args, param->paramid - 1);
5363 }
5365}

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,
bool  use_rel_info 
)

Definition at line 4391 of file clauses.c.

4392{
4393 Bitmapset *notnullattnums = NULL;
4394
4395 Assert(IsA(var, Var));
4396
4397 /* skip upper-level Vars */
4398 if (var->varlevelsup != 0)
4399 return false;
4400
4401 /* could the Var be nulled by any outer joins or grouping sets? */
4402 if (!bms_is_empty(var->varnullingrels))
4403 return false;
4404
4405 /* system columns cannot be NULL */
4406 if (var->varattno < 0)
4407 return true;
4408
4409 /*
4410 * Check if the Var is defined as NOT NULL. We retrieve the column NOT
4411 * NULL constraint information from the corresponding RelOptInfo if it is
4412 * available; otherwise, we search the hash table for this information.
4413 */
4414 if (use_rel_info)
4415 {
4416 RelOptInfo *rel = find_base_rel(root, var->varno);
4417
4418 notnullattnums = rel->notnullattnums;
4419 }
4420 else
4421 {
4423
4424 /*
4425 * We must skip inheritance parent tables, as some child tables may
4426 * have a NOT NULL constraint for a column while others may not. This
4427 * cannot happen with partitioned tables, though.
4428 */
4429 if (rte->inh && rte->relkind != RELKIND_PARTITIONED_TABLE)
4430 return false;
4431
4432 notnullattnums = find_relation_notnullatts(root, rte->relid);
4433 }
4434
4435 if (var->varattno > 0 &&
4436 bms_is_member(var->varattno, notnullattnums))
4437 return true;
4438
4439 return false;
4440}

References Assert, bms_is_empty, bms_is_member(), fb(), find_base_rel(), find_relation_notnullatts(), IsA, RelOptInfo::notnullattnums, planner_rt_fetch, root, Var::varattno, Var::varlevelsup, and Var::varno.

Referenced by expr_is_nonnullable().