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 Expr *simple;
2709
2710 /*
2711 * Reduce constants in the DistinctExpr's arguments. We know
2712 * args is either NIL or a List node, so we can call
2713 * expression_tree_mutator directly rather than recursing to
2714 * self.
2715 */
2716 args = (List *) expression_tree_mutator((Node *) expr->args,
2718 context);
2719
2720 /*
2721 * We must do our own check for NULLs because DistinctExpr has
2722 * different results for NULL input than the underlying
2723 * operator does.
2724 */
2725 foreach(arg, args)
2726 {
2727 if (IsA(lfirst(arg), Const))
2728 {
2731 }
2732 else
2733 has_nonconst_input = true;
2734 }
2735
2736 /* all constants? then can optimize this out */
2737 if (!has_nonconst_input)
2738 {
2739 /* all nulls? then not distinct */
2740 if (all_null_input)
2741 return makeBoolConst(false, false);
2742
2743 /* one null? then distinct */
2744 if (has_null_input)
2745 return makeBoolConst(true, false);
2746
2747 /* otherwise try to evaluate the '=' operator */
2748 /* (NOT okay to try to inline it, though!) */
2749
2750 /*
2751 * Need to get OID of underlying function. Okay to
2752 * scribble on input to this extent.
2753 */
2754 set_opfuncid((OpExpr *) expr); /* rely on struct
2755 * equivalence */
2756
2757 /*
2758 * Code for op/func reduction is pretty bulky, so split it
2759 * out as a separate function.
2760 */
2761 simple = simplify_function(expr->opfuncid,
2762 expr->opresulttype, -1,
2763 expr->opcollid,
2764 expr->inputcollid,
2765 &args,
2766 false,
2767 false,
2768 false,
2769 context);
2770 if (simple) /* successfully simplified it */
2771 {
2772 /*
2773 * Since the underlying operator is "=", must negate
2774 * its result
2775 */
2776 Const *csimple = castNode(Const, simple);
2777
2778 csimple->constvalue =
2779 BoolGetDatum(!DatumGetBool(csimple->constvalue));
2780 return (Node *) csimple;
2781 }
2782 }
2783
2784 /*
2785 * The expression cannot be simplified any further, so build
2786 * and return a replacement DistinctExpr node using the
2787 * possibly-simplified arguments.
2788 */
2790 newexpr->opno = expr->opno;
2791 newexpr->opfuncid = expr->opfuncid;
2792 newexpr->opresulttype = expr->opresulttype;
2793 newexpr->opretset = expr->opretset;
2794 newexpr->opcollid = expr->opcollid;
2795 newexpr->inputcollid = expr->inputcollid;
2796 newexpr->args = args;
2797 newexpr->location = expr->location;
2798 return (Node *) newexpr;
2799 }
2800 case T_NullIfExpr:
2801 {
2802 NullIfExpr *expr;
2803 ListCell *arg;
2804 bool has_nonconst_input = false;
2805
2806 /* Copy the node and const-simplify its arguments */
2807 expr = (NullIfExpr *) ece_generic_processing(node);
2808
2809 /* If either argument is NULL they can't be equal */
2810 foreach(arg, expr->args)
2811 {
2812 if (!IsA(lfirst(arg), Const))
2813 has_nonconst_input = true;
2814 else if (((Const *) lfirst(arg))->constisnull)
2815 return (Node *) linitial(expr->args);
2816 }
2817
2818 /*
2819 * Need to get OID of underlying function before checking if
2820 * the function is OK to evaluate.
2821 */
2822 set_opfuncid((OpExpr *) expr);
2823
2824 if (!has_nonconst_input &&
2825 ece_function_is_safe(expr->opfuncid, context))
2826 return ece_evaluate_expr(expr);
2827
2828 return (Node *) expr;
2829 }
2831 {
2832 ScalarArrayOpExpr *saop;
2833
2834 /* Copy the node and const-simplify its arguments */
2836
2837 /* Make sure we know underlying function */
2838 set_sa_opfuncid(saop);
2839
2840 /*
2841 * If all arguments are Consts, and it's a safe function, we
2842 * can fold to a constant
2843 */
2844 if (ece_all_arguments_const(saop) &&
2845 ece_function_is_safe(saop->opfuncid, context))
2846 return ece_evaluate_expr(saop);
2847 return (Node *) saop;
2848 }
2849 case T_BoolExpr:
2850 {
2851 BoolExpr *expr = (BoolExpr *) node;
2852
2853 switch (expr->boolop)
2854 {
2855 case OR_EXPR:
2856 {
2857 List *newargs;
2858 bool haveNull = false;
2859 bool forceTrue = false;
2860
2862 context,
2863 &haveNull,
2864 &forceTrue);
2865 if (forceTrue)
2866 return makeBoolConst(true, false);
2867 if (haveNull)
2869 makeBoolConst(false, true));
2870 /* If all the inputs are FALSE, result is FALSE */
2871 if (newargs == NIL)
2872 return makeBoolConst(false, false);
2873
2874 /*
2875 * If only one nonconst-or-NULL input, it's the
2876 * result
2877 */
2878 if (list_length(newargs) == 1)
2879 return (Node *) linitial(newargs);
2880 /* Else we still need an OR node */
2881 return (Node *) make_orclause(newargs);
2882 }
2883 case AND_EXPR:
2884 {
2885 List *newargs;
2886 bool haveNull = false;
2887 bool forceFalse = false;
2888
2890 context,
2891 &haveNull,
2892 &forceFalse);
2893 if (forceFalse)
2894 return makeBoolConst(false, false);
2895 if (haveNull)
2897 makeBoolConst(false, true));
2898 /* If all the inputs are TRUE, result is TRUE */
2899 if (newargs == NIL)
2900 return makeBoolConst(true, false);
2901
2902 /*
2903 * If only one nonconst-or-NULL input, it's the
2904 * result
2905 */
2906 if (list_length(newargs) == 1)
2907 return (Node *) linitial(newargs);
2908 /* Else we still need an AND node */
2909 return (Node *) make_andclause(newargs);
2910 }
2911 case NOT_EXPR:
2912 {
2913 Node *arg;
2914
2915 Assert(list_length(expr->args) == 1);
2917 context);
2918
2919 /*
2920 * Use negate_clause() to see if we can simplify
2921 * away the NOT.
2922 */
2923 return negate_clause(arg);
2924 }
2925 default:
2926 elog(ERROR, "unrecognized boolop: %d",
2927 (int) expr->boolop);
2928 break;
2929 }
2930 break;
2931 }
2932
2933 case T_JsonValueExpr:
2934 {
2935 JsonValueExpr *jve = (JsonValueExpr *) node;
2936 Node *raw_expr = (Node *) jve->raw_expr;
2937 Node *formatted_expr = (Node *) jve->formatted_expr;
2938
2939 /*
2940 * If we can fold formatted_expr to a constant, we can elide
2941 * the JsonValueExpr altogether. Otherwise we must process
2942 * raw_expr too. But JsonFormat is a flat node and requires
2943 * no simplification, only copying.
2944 */
2945 formatted_expr = eval_const_expressions_mutator(formatted_expr,
2946 context);
2947 if (formatted_expr && IsA(formatted_expr, Const))
2948 return formatted_expr;
2949
2950 raw_expr = eval_const_expressions_mutator(raw_expr, context);
2951
2952 return (Node *) makeJsonValueExpr((Expr *) raw_expr,
2953 (Expr *) formatted_expr,
2954 copyObject(jve->format));
2955 }
2956
2957 case T_SubPlan:
2959
2960 /*
2961 * Return a SubPlan unchanged --- too late to do anything with it.
2962 *
2963 * XXX should we ereport() here instead? Probably this routine
2964 * should never be invoked after SubPlan creation.
2965 */
2966 return node;
2967 case T_RelabelType:
2968 {
2969 RelabelType *relabel = (RelabelType *) node;
2970 Node *arg;
2971
2972 /* Simplify the input ... */
2974 context);
2975 /* ... and attach a new RelabelType node, if needed */
2976 return applyRelabelType(arg,
2977 relabel->resulttype,
2978 relabel->resulttypmod,
2979 relabel->resultcollid,
2980 relabel->relabelformat,
2981 relabel->location,
2982 true);
2983 }
2984 case T_CoerceViaIO:
2985 {
2986 CoerceViaIO *expr = (CoerceViaIO *) node;
2987 List *args;
2988 Oid outfunc;
2989 bool outtypisvarlena;
2990 Oid infunc;
2992 Expr *simple;
2994
2995 /* Make a List so we can use simplify_function */
2996 args = list_make1(expr->arg);
2997
2998 /*
2999 * CoerceViaIO represents calling the source type's output
3000 * function then the result type's input function. So, try to
3001 * simplify it as though it were a stack of two such function
3002 * calls. First we need to know what the functions are.
3003 *
3004 * Note that the coercion functions are assumed not to care
3005 * about input collation, so we just pass InvalidOid for that.
3006 */
3010 &infunc, &intypioparam);
3011
3012 simple = simplify_function(outfunc,
3013 CSTRINGOID, -1,
3014 InvalidOid,
3015 InvalidOid,
3016 &args,
3017 false,
3018 true,
3019 true,
3020 context);
3021 if (simple) /* successfully simplified output fn */
3022 {
3023 /*
3024 * Input functions may want 1 to 3 arguments. We always
3025 * supply all three, trusting that nothing downstream will
3026 * complain.
3027 */
3028 args = list_make3(simple,
3030 -1,
3031 InvalidOid,
3032 sizeof(Oid),
3034 false,
3035 true),
3037 -1,
3038 InvalidOid,
3039 sizeof(int32),
3040 Int32GetDatum(-1),
3041 false,
3042 true));
3043
3044 simple = simplify_function(infunc,
3045 expr->resulttype, -1,
3046 expr->resultcollid,
3047 InvalidOid,
3048 &args,
3049 false,
3050 false,
3051 true,
3052 context);
3053 if (simple) /* successfully simplified input fn */
3054 return (Node *) simple;
3055 }
3056
3057 /*
3058 * The expression cannot be simplified any further, so build
3059 * and return a replacement CoerceViaIO node using the
3060 * possibly-simplified argument.
3061 */
3063 newexpr->arg = (Expr *) linitial(args);
3064 newexpr->resulttype = expr->resulttype;
3065 newexpr->resultcollid = expr->resultcollid;
3066 newexpr->coerceformat = expr->coerceformat;
3067 newexpr->location = expr->location;
3068 return (Node *) newexpr;
3069 }
3070 case T_ArrayCoerceExpr:
3071 {
3074
3075 /*
3076 * Copy the node and const-simplify its arguments. We can't
3077 * use ece_generic_processing() here because we need to mess
3078 * with case_val only while processing the elemexpr.
3079 */
3080 memcpy(ac, node, sizeof(ArrayCoerceExpr));
3081 ac->arg = (Expr *)
3083 context);
3084
3085 /*
3086 * Set up for the CaseTestExpr node contained in the elemexpr.
3087 * We must prevent it from absorbing any outer CASE value.
3088 */
3089 save_case_val = context->case_val;
3090 context->case_val = NULL;
3091
3092 ac->elemexpr = (Expr *)
3094 context);
3095
3096 context->case_val = save_case_val;
3097
3098 /*
3099 * If constant argument and the per-element expression is
3100 * immutable, we can simplify the whole thing to a constant.
3101 * Exception: although contain_mutable_functions considers
3102 * CoerceToDomain immutable for historical reasons, let's not
3103 * do so here; this ensures coercion to an array-over-domain
3104 * does not apply the domain's constraints until runtime.
3105 */
3106 if (ac->arg && IsA(ac->arg, Const) &&
3107 ac->elemexpr && !IsA(ac->elemexpr, CoerceToDomain) &&
3108 !contain_mutable_functions((Node *) ac->elemexpr))
3109 return ece_evaluate_expr(ac);
3110
3111 return (Node *) ac;
3112 }
3113 case T_CollateExpr:
3114 {
3115 /*
3116 * We replace CollateExpr with RelabelType, so as to improve
3117 * uniformity of expression representation and thus simplify
3118 * comparison of expressions. Hence this looks very nearly
3119 * the same as the RelabelType case, and we can apply the same
3120 * optimizations to avoid unnecessary RelabelTypes.
3121 */
3122 CollateExpr *collate = (CollateExpr *) node;
3123 Node *arg;
3124
3125 /* Simplify the input ... */
3127 context);
3128 /* ... and attach a new RelabelType node, if needed */
3129 return applyRelabelType(arg,
3130 exprType(arg),
3131 exprTypmod(arg),
3132 collate->collOid,
3134 collate->location,
3135 true);
3136 }
3137 case T_CaseExpr:
3138 {
3139 /*----------
3140 * CASE expressions can be simplified if there are constant
3141 * condition clauses:
3142 * FALSE (or NULL): drop the alternative
3143 * TRUE: drop all remaining alternatives
3144 * If the first non-FALSE alternative is a constant TRUE,
3145 * we can simplify the entire CASE to that alternative's
3146 * expression. If there are no non-FALSE alternatives,
3147 * we simplify the entire CASE to the default result (ELSE).
3148 *
3149 * If we have a simple-form CASE with constant test
3150 * expression, we substitute the constant value for contained
3151 * CaseTestExpr placeholder nodes, so that we have the
3152 * opportunity to reduce constant test conditions. For
3153 * example this allows
3154 * CASE 0 WHEN 0 THEN 1 ELSE 1/0 END
3155 * to reduce to 1 rather than drawing a divide-by-0 error.
3156 * Note that when the test expression is constant, we don't
3157 * have to include it in the resulting CASE; for example
3158 * CASE 0 WHEN x THEN y ELSE z END
3159 * is transformed by the parser to
3160 * CASE 0 WHEN CaseTestExpr = x THEN y ELSE z END
3161 * which we can simplify to
3162 * CASE WHEN 0 = x THEN y ELSE z END
3163 * It is not necessary for the executor to evaluate the "arg"
3164 * expression when executing the CASE, since any contained
3165 * CaseTestExprs that might have referred to it will have been
3166 * replaced by the constant.
3167 *----------
3168 */
3169 CaseExpr *caseexpr = (CaseExpr *) node;
3172 Node *newarg;
3173 List *newargs;
3174 bool const_true_cond;
3175 Node *defresult = NULL;
3176 ListCell *arg;
3177
3178 /* Simplify the test expression, if any */
3180 context);
3181
3182 /* Set up for contained CaseTestExpr nodes */
3183 save_case_val = context->case_val;
3184 if (newarg && IsA(newarg, Const))
3185 {
3186 context->case_val = newarg;
3187 newarg = NULL; /* not needed anymore, see above */
3188 }
3189 else
3190 context->case_val = NULL;
3191
3192 /* Simplify the WHEN clauses */
3193 newargs = NIL;
3194 const_true_cond = false;
3195 foreach(arg, caseexpr->args)
3196 {
3198 Node *casecond;
3200
3201 /* Simplify this alternative's test condition */
3203 context);
3204
3205 /*
3206 * If the test condition is constant FALSE (or NULL), then
3207 * drop this WHEN clause completely, without processing
3208 * the result.
3209 */
3210 if (casecond && IsA(casecond, Const))
3211 {
3213
3214 if (const_input->constisnull ||
3215 !DatumGetBool(const_input->constvalue))
3216 continue; /* drop alternative with FALSE cond */
3217 /* Else it's constant TRUE */
3218 const_true_cond = true;
3219 }
3220
3221 /* Simplify this alternative's result value */
3223 context);
3224
3225 /* If non-constant test condition, emit a new WHEN node */
3226 if (!const_true_cond)
3227 {
3229
3230 newcasewhen->expr = (Expr *) casecond;
3231 newcasewhen->result = (Expr *) caseresult;
3232 newcasewhen->location = oldcasewhen->location;
3234 continue;
3235 }
3236
3237 /*
3238 * Found a TRUE condition, so none of the remaining
3239 * alternatives can be reached. We treat the result as
3240 * the default result.
3241 */
3242 defresult = caseresult;
3243 break;
3244 }
3245
3246 /* Simplify the default result, unless we replaced it above */
3247 if (!const_true_cond)
3248 defresult = eval_const_expressions_mutator((Node *) caseexpr->defresult,
3249 context);
3250
3251 context->case_val = save_case_val;
3252
3253 /*
3254 * If no non-FALSE alternatives, CASE reduces to the default
3255 * result
3256 */
3257 if (newargs == NIL)
3258 return defresult;
3259 /* Otherwise we need a new CASE node */
3261 newcase->casetype = caseexpr->casetype;
3262 newcase->casecollid = caseexpr->casecollid;
3263 newcase->arg = (Expr *) newarg;
3264 newcase->args = newargs;
3265 newcase->defresult = (Expr *) defresult;
3266 newcase->location = caseexpr->location;
3267 return (Node *) newcase;
3268 }
3269 case T_CaseTestExpr:
3270 {
3271 /*
3272 * If we know a constant test value for the current CASE
3273 * construct, substitute it for the placeholder. Else just
3274 * return the placeholder as-is.
3275 */
3276 if (context->case_val)
3277 return copyObject(context->case_val);
3278 else
3279 return copyObject(node);
3280 }
3281 case T_SubscriptingRef:
3282 case T_ArrayExpr:
3283 case T_RowExpr:
3284 case T_MinMaxExpr:
3285 {
3286 /*
3287 * Generic handling for node types whose own processing is
3288 * known to be immutable, and for which we need no smarts
3289 * beyond "simplify if all inputs are constants".
3290 *
3291 * Treating SubscriptingRef this way assumes that subscripting
3292 * fetch and assignment are both immutable. This constrains
3293 * type-specific subscripting implementations; maybe we should
3294 * relax it someday.
3295 *
3296 * Treating MinMaxExpr this way amounts to assuming that the
3297 * btree comparison function it calls is immutable; see the
3298 * reasoning in contain_mutable_functions_walker.
3299 */
3300
3301 /* Copy the node and const-simplify its arguments */
3302 node = ece_generic_processing(node);
3303 /* If all arguments are Consts, we can fold to a constant */
3304 if (ece_all_arguments_const(node))
3305 return ece_evaluate_expr(node);
3306 return node;
3307 }
3308 case T_CoalesceExpr:
3309 {
3312 List *newargs;
3313 ListCell *arg;
3314
3315 newargs = NIL;
3316 foreach(arg, coalesceexpr->args)
3317 {
3318 Node *e;
3319
3321 context);
3322
3323 /*
3324 * We can remove null constants from the list. For a
3325 * nonnullable expression, if it has not been preceded by
3326 * any non-null-constant expressions then it is the
3327 * result. Otherwise, it's the next argument, but we can
3328 * drop following arguments since they will never be
3329 * reached.
3330 */
3331 if (IsA(e, Const))
3332 {
3333 if (((Const *) e)->constisnull)
3334 continue; /* drop null constant */
3335 if (newargs == NIL)
3336 return e; /* first expr */
3338 break;
3339 }
3340 if (expr_is_nonnullable(context->root, (Expr *) e, false))
3341 {
3342 if (newargs == NIL)
3343 return e; /* first expr */
3345 break;
3346 }
3347
3349 }
3350
3351 /*
3352 * If all the arguments were constant null, the result is just
3353 * null
3354 */
3355 if (newargs == NIL)
3356 return (Node *) makeNullConst(coalesceexpr->coalescetype,
3357 -1,
3358 coalesceexpr->coalescecollid);
3359
3360 /*
3361 * If there's exactly one surviving argument, we no longer
3362 * need COALESCE at all: the result is that argument
3363 */
3364 if (list_length(newargs) == 1)
3365 return (Node *) linitial(newargs);
3366
3368 newcoalesce->coalescetype = coalesceexpr->coalescetype;
3369 newcoalesce->coalescecollid = coalesceexpr->coalescecollid;
3370 newcoalesce->args = newargs;
3371 newcoalesce->location = coalesceexpr->location;
3372 return (Node *) newcoalesce;
3373 }
3374 case T_SQLValueFunction:
3375 {
3376 /*
3377 * All variants of SQLValueFunction are stable, so if we are
3378 * estimating the expression's value, we should evaluate the
3379 * current function value. Otherwise just copy.
3380 */
3381 SQLValueFunction *svf = (SQLValueFunction *) node;
3382
3383 if (context->estimate)
3384 return (Node *) evaluate_expr((Expr *) svf,
3385 svf->type,
3386 svf->typmod,
3387 InvalidOid);
3388 else
3389 return copyObject((Node *) svf);
3390 }
3391 case T_FieldSelect:
3392 {
3393 /*
3394 * We can optimize field selection from a whole-row Var into a
3395 * simple Var. (This case won't be generated directly by the
3396 * parser, because ParseComplexProjection short-circuits it.
3397 * But it can arise while simplifying functions.) Also, we
3398 * can optimize field selection from a RowExpr construct, or
3399 * of course from a constant.
3400 *
3401 * However, replacing a whole-row Var in this way has a
3402 * pitfall: if we've already built the rel targetlist for the
3403 * source relation, then the whole-row Var is scheduled to be
3404 * produced by the relation scan, but the simple Var probably
3405 * isn't, which will lead to a failure in setrefs.c. This is
3406 * not a problem when handling simple single-level queries, in
3407 * which expression simplification always happens first. It
3408 * is a risk for lateral references from subqueries, though.
3409 * To avoid such failures, don't optimize uplevel references.
3410 *
3411 * We must also check that the declared type of the field is
3412 * still the same as when the FieldSelect was created --- this
3413 * can change if someone did ALTER COLUMN TYPE on the rowtype.
3414 * If it isn't, we skip the optimization; the case will
3415 * probably fail at runtime, but that's not our problem here.
3416 */
3417 FieldSelect *fselect = (FieldSelect *) node;
3419 Node *arg;
3420
3422 context);
3423 if (arg && IsA(arg, Var) &&
3424 ((Var *) arg)->varattno == InvalidAttrNumber &&
3425 ((Var *) arg)->varlevelsup == 0)
3426 {
3427 if (rowtype_field_matches(((Var *) arg)->vartype,
3428 fselect->fieldnum,
3429 fselect->resulttype,
3430 fselect->resulttypmod,
3431 fselect->resultcollid))
3432 {
3433 Var *newvar;
3434
3435 newvar = makeVar(((Var *) arg)->varno,
3436 fselect->fieldnum,
3437 fselect->resulttype,
3438 fselect->resulttypmod,
3439 fselect->resultcollid,
3440 ((Var *) arg)->varlevelsup);
3441 /* New Var has same OLD/NEW returning as old one */
3442 newvar->varreturningtype = ((Var *) arg)->varreturningtype;
3443 /* New Var is nullable by same rels as the old one */
3444 newvar->varnullingrels = ((Var *) arg)->varnullingrels;
3445 return (Node *) newvar;
3446 }
3447 }
3448 if (arg && IsA(arg, RowExpr))
3449 {
3450 RowExpr *rowexpr = (RowExpr *) arg;
3451
3452 if (fselect->fieldnum > 0 &&
3453 fselect->fieldnum <= list_length(rowexpr->args))
3454 {
3455 Node *fld = (Node *) list_nth(rowexpr->args,
3456 fselect->fieldnum - 1);
3457
3458 if (rowtype_field_matches(rowexpr->row_typeid,
3459 fselect->fieldnum,
3460 fselect->resulttype,
3461 fselect->resulttypmod,
3462 fselect->resultcollid) &&
3463 fselect->resulttype == exprType(fld) &&
3464 fselect->resulttypmod == exprTypmod(fld) &&
3465 fselect->resultcollid == exprCollation(fld))
3466 return fld;
3467 }
3468 }
3470 newfselect->arg = (Expr *) arg;
3471 newfselect->fieldnum = fselect->fieldnum;
3472 newfselect->resulttype = fselect->resulttype;
3473 newfselect->resulttypmod = fselect->resulttypmod;
3474 newfselect->resultcollid = fselect->resultcollid;
3475 if (arg && IsA(arg, Const))
3476 {
3477 Const *con = (Const *) arg;
3478
3480 newfselect->fieldnum,
3481 newfselect->resulttype,
3482 newfselect->resulttypmod,
3483 newfselect->resultcollid))
3485 }
3486 return (Node *) newfselect;
3487 }
3488 case T_NullTest:
3489 {
3490 NullTest *ntest = (NullTest *) node;
3492 Node *arg;
3493
3495 context);
3496 if (ntest->argisrow && arg && IsA(arg, RowExpr))
3497 {
3498 /*
3499 * We break ROW(...) IS [NOT] NULL into separate tests on
3500 * its component fields. This form is usually more
3501 * efficient to evaluate, as well as being more amenable
3502 * to optimization.
3503 */
3504 RowExpr *rarg = (RowExpr *) arg;
3505 List *newargs = NIL;
3506 ListCell *l;
3507
3508 foreach(l, rarg->args)
3509 {
3510 Node *relem = (Node *) lfirst(l);
3511
3512 /*
3513 * A constant field refutes the whole NullTest if it's
3514 * of the wrong nullness; else we can discard it.
3515 */
3516 if (relem && IsA(relem, Const))
3517 {
3518 Const *carg = (Const *) relem;
3519
3520 if (carg->constisnull ?
3521 (ntest->nulltesttype == IS_NOT_NULL) :
3522 (ntest->nulltesttype == IS_NULL))
3523 return makeBoolConst(false, false);
3524 continue;
3525 }
3526
3527 /*
3528 * A proven non-nullable field refutes the whole
3529 * NullTest if the test is IS NULL; else we can
3530 * discard it.
3531 */
3532 if (relem &&
3533 expr_is_nonnullable(context->root, (Expr *) relem,
3534 false))
3535 {
3536 if (ntest->nulltesttype == IS_NULL)
3537 return makeBoolConst(false, false);
3538 continue;
3539 }
3540
3541 /*
3542 * Else, make a scalar (argisrow == false) NullTest
3543 * for this field. Scalar semantics are required
3544 * because IS [NOT] NULL doesn't recurse; see comments
3545 * in ExecEvalRowNullInt().
3546 */
3548 newntest->arg = (Expr *) relem;
3549 newntest->nulltesttype = ntest->nulltesttype;
3550 newntest->argisrow = false;
3551 newntest->location = ntest->location;
3553 }
3554 /* If all the inputs were constants, result is TRUE */
3555 if (newargs == NIL)
3556 return makeBoolConst(true, false);
3557 /* If only one nonconst input, it's the result */
3558 if (list_length(newargs) == 1)
3559 return (Node *) linitial(newargs);
3560 /* Else we need an AND node */
3561 return (Node *) make_andclause(newargs);
3562 }
3563 if (!ntest->argisrow && arg && IsA(arg, Const))
3564 {
3565 Const *carg = (Const *) arg;
3566 bool result;
3567
3568 switch (ntest->nulltesttype)
3569 {
3570 case IS_NULL:
3571 result = carg->constisnull;
3572 break;
3573 case IS_NOT_NULL:
3574 result = !carg->constisnull;
3575 break;
3576 default:
3577 elog(ERROR, "unrecognized nulltesttype: %d",
3578 (int) ntest->nulltesttype);
3579 result = false; /* keep compiler quiet */
3580 break;
3581 }
3582
3583 return makeBoolConst(result, false);
3584 }
3585 if (!ntest->argisrow && arg &&
3586 expr_is_nonnullable(context->root, (Expr *) arg, false))
3587 {
3588 bool result;
3589
3590 switch (ntest->nulltesttype)
3591 {
3592 case IS_NULL:
3593 result = false;
3594 break;
3595 case IS_NOT_NULL:
3596 result = true;
3597 break;
3598 default:
3599 elog(ERROR, "unrecognized nulltesttype: %d",
3600 (int) ntest->nulltesttype);
3601 result = false; /* keep compiler quiet */
3602 break;
3603 }
3604
3605 return makeBoolConst(result, false);
3606 }
3607
3609 newntest->arg = (Expr *) arg;
3610 newntest->nulltesttype = ntest->nulltesttype;
3611 newntest->argisrow = ntest->argisrow;
3612 newntest->location = ntest->location;
3613 return (Node *) newntest;
3614 }
3615 case T_BooleanTest:
3616 {
3617 /*
3618 * This case could be folded into the generic handling used
3619 * for ArrayExpr etc. But because the simplification logic is
3620 * so trivial, applying evaluate_expr() to perform it would be
3621 * a heavy overhead. BooleanTest is probably common enough to
3622 * justify keeping this bespoke implementation.
3623 */
3624 BooleanTest *btest = (BooleanTest *) node;
3626 Node *arg;
3627
3629 context);
3630 if (arg && IsA(arg, Const))
3631 {
3632 Const *carg = (Const *) arg;
3633 bool result;
3634
3635 switch (btest->booltesttype)
3636 {
3637 case IS_TRUE:
3638 result = (!carg->constisnull &&
3639 DatumGetBool(carg->constvalue));
3640 break;
3641 case IS_NOT_TRUE:
3642 result = (carg->constisnull ||
3643 !DatumGetBool(carg->constvalue));
3644 break;
3645 case IS_FALSE:
3646 result = (!carg->constisnull &&
3647 !DatumGetBool(carg->constvalue));
3648 break;
3649 case IS_NOT_FALSE:
3650 result = (carg->constisnull ||
3651 DatumGetBool(carg->constvalue));
3652 break;
3653 case IS_UNKNOWN:
3654 result = carg->constisnull;
3655 break;
3656 case IS_NOT_UNKNOWN:
3657 result = !carg->constisnull;
3658 break;
3659 default:
3660 elog(ERROR, "unrecognized booltesttype: %d",
3661 (int) btest->booltesttype);
3662 result = false; /* keep compiler quiet */
3663 break;
3664 }
3665
3666 return makeBoolConst(result, false);
3667 }
3668
3670 newbtest->arg = (Expr *) arg;
3671 newbtest->booltesttype = btest->booltesttype;
3672 newbtest->location = btest->location;
3673 return (Node *) newbtest;
3674 }
3675 case T_CoerceToDomain:
3676 {
3677 /*
3678 * If the domain currently has no constraints, we replace the
3679 * CoerceToDomain node with a simple RelabelType, which is
3680 * both far faster to execute and more amenable to later
3681 * optimization. We must then mark the plan as needing to be
3682 * rebuilt if the domain's constraints change.
3683 *
3684 * Also, in estimation mode, always replace CoerceToDomain
3685 * nodes, effectively assuming that the coercion will succeed.
3686 */
3689 Node *arg;
3690
3692 context);
3693 if (context->estimate ||
3694 !DomainHasConstraints(cdomain->resulttype))
3695 {
3696 /* Record dependency, if this isn't estimation mode */
3697 if (context->root && !context->estimate)
3698 record_plan_type_dependency(context->root,
3699 cdomain->resulttype);
3700
3701 /* Generate RelabelType to substitute for CoerceToDomain */
3702 return applyRelabelType(arg,
3703 cdomain->resulttype,
3704 cdomain->resulttypmod,
3705 cdomain->resultcollid,
3706 cdomain->coercionformat,
3707 cdomain->location,
3708 true);
3709 }
3710
3712 newcdomain->arg = (Expr *) arg;
3713 newcdomain->resulttype = cdomain->resulttype;
3714 newcdomain->resulttypmod = cdomain->resulttypmod;
3715 newcdomain->resultcollid = cdomain->resultcollid;
3716 newcdomain->coercionformat = cdomain->coercionformat;
3717 newcdomain->location = cdomain->location;
3718 return (Node *) newcdomain;
3719 }
3720 case T_PlaceHolderVar:
3721
3722 /*
3723 * In estimation mode, just strip the PlaceHolderVar node
3724 * altogether; this amounts to estimating that the contained value
3725 * won't be forced to null by an outer join. In regular mode we
3726 * just use the default behavior (ie, simplify the expression but
3727 * leave the PlaceHolderVar node intact).
3728 */
3729 if (context->estimate)
3730 {
3731 PlaceHolderVar *phv = (PlaceHolderVar *) node;
3732
3733 return eval_const_expressions_mutator((Node *) phv->phexpr,
3734 context);
3735 }
3736 break;
3738 {
3740 Node *arg;
3742
3744 context);
3745
3747 newcre->resulttype = cre->resulttype;
3748 newcre->convertformat = cre->convertformat;
3749 newcre->location = cre->location;
3750
3751 /*
3752 * In case of a nested ConvertRowtypeExpr, we can convert the
3753 * leaf row directly to the topmost row format without any
3754 * intermediate conversions. (This works because
3755 * ConvertRowtypeExpr is used only for child->parent
3756 * conversion in inheritance trees, which works by exact match
3757 * of column name, and a column absent in an intermediate
3758 * result can't be present in the final result.)
3759 *
3760 * No need to check more than one level deep, because the
3761 * above recursion will have flattened anything else.
3762 */
3763 if (arg != NULL && IsA(arg, ConvertRowtypeExpr))
3764 {
3766
3767 arg = (Node *) argcre->arg;
3768
3769 /*
3770 * Make sure an outer implicit conversion can't hide an
3771 * inner explicit one.
3772 */
3773 if (newcre->convertformat == COERCE_IMPLICIT_CAST)
3774 newcre->convertformat = argcre->convertformat;
3775 }
3776
3777 newcre->arg = (Expr *) arg;
3778
3779 if (arg != NULL && IsA(arg, Const))
3780 return ece_evaluate_expr((Node *) newcre);
3781 return (Node *) newcre;
3782 }
3783 default:
3784 break;
3785 }
3786
3787 /*
3788 * For any node type not handled above, copy the node unchanged but
3789 * const-simplify its subexpressions. This is the correct thing for node
3790 * types whose behavior might change between planning and execution, such
3791 * as CurrentOfExpr. It's also a safe default for new node types not
3792 * known to this routine.
3793 */
3794 return ece_generic_processing(node);
3795}
3796
3797/*
3798 * Subroutine for eval_const_expressions: check for non-Const nodes.
3799 *
3800 * We can abort recursion immediately on finding a non-Const node. This is
3801 * critical for performance, else eval_const_expressions_mutator would take
3802 * O(N^2) time on non-simplifiable trees. However, we do need to descend
3803 * into List nodes since expression_tree_walker sometimes invokes the walker
3804 * function directly on List subtrees.
3805 */
3806static bool
3807contain_non_const_walker(Node *node, void *context)
3808{
3809 if (node == NULL)
3810 return false;
3811 if (IsA(node, Const))
3812 return false;
3813 if (IsA(node, List))
3814 return expression_tree_walker(node, contain_non_const_walker, context);
3815 /* Otherwise, abort the tree traversal and return true */
3816 return true;
3817}
3818
3819/*
3820 * Subroutine for eval_const_expressions: check if a function is OK to evaluate
3821 */
3822static bool
3824{
3825 char provolatile = func_volatile(funcid);
3826
3827 /*
3828 * Ordinarily we are only allowed to simplify immutable functions. But for
3829 * purposes of estimation, we consider it okay to simplify functions that
3830 * are merely stable; the risk that the result might change from planning
3831 * time to execution time is worth taking in preference to not being able
3832 * to estimate the value at all.
3833 */
3835 return true;
3836 if (context->estimate && provolatile == PROVOLATILE_STABLE)
3837 return true;
3838 return false;
3839}
3840
3841/*
3842 * Subroutine for eval_const_expressions: process arguments of an OR clause
3843 *
3844 * This includes flattening of nested ORs as well as recursion to
3845 * eval_const_expressions to simplify the OR arguments.
3846 *
3847 * After simplification, OR arguments are handled as follows:
3848 * non constant: keep
3849 * FALSE: drop (does not affect result)
3850 * TRUE: force result to TRUE
3851 * NULL: keep only one
3852 * We must keep one NULL input because OR expressions evaluate to NULL when no
3853 * input is TRUE and at least one is NULL. We don't actually include the NULL
3854 * here, that's supposed to be done by the caller.
3855 *
3856 * The output arguments *haveNull and *forceTrue must be initialized false
3857 * by the caller. They will be set true if a NULL constant or TRUE constant,
3858 * respectively, is detected anywhere in the argument list.
3859 */
3860static List *
3863 bool *haveNull, bool *forceTrue)
3864{
3865 List *newargs = NIL;
3867
3868 /*
3869 * We want to ensure that any OR immediately beneath another OR gets
3870 * flattened into a single OR-list, so as to simplify later reasoning.
3871 *
3872 * To avoid stack overflow from recursion of eval_const_expressions, we
3873 * resort to some tenseness here: we keep a list of not-yet-processed
3874 * inputs, and handle flattening of nested ORs by prepending to the to-do
3875 * list instead of recursing. Now that the parser generates N-argument
3876 * ORs from simple lists, this complexity is probably less necessary than
3877 * it once was, but we might as well keep the logic.
3878 */
3880 while (unprocessed_args)
3881 {
3883
3885
3886 /* flatten nested ORs as per above comment */
3887 if (is_orclause(arg))
3888 {
3889 List *subargs = ((BoolExpr *) arg)->args;
3891
3893 /* perhaps-overly-tense code to avoid leaking old lists */
3895 continue;
3896 }
3897
3898 /* If it's not an OR, simplify it */
3900
3901 /*
3902 * It is unlikely but not impossible for simplification of a non-OR
3903 * clause to produce an OR. Recheck, but don't be too tense about it
3904 * since it's not a mainstream case. In particular we don't worry
3905 * about const-simplifying the input twice, nor about list leakage.
3906 */
3907 if (is_orclause(arg))
3908 {
3909 List *subargs = ((BoolExpr *) arg)->args;
3910
3912 continue;
3913 }
3914
3915 /*
3916 * OK, we have a const-simplified non-OR argument. Process it per
3917 * comments above.
3918 */
3919 if (IsA(arg, Const))
3920 {
3921 Const *const_input = (Const *) arg;
3922
3923 if (const_input->constisnull)
3924 *haveNull = true;
3925 else if (DatumGetBool(const_input->constvalue))
3926 {
3927 *forceTrue = true;
3928
3929 /*
3930 * Once we detect a TRUE result we can just exit the loop
3931 * immediately. However, if we ever add a notion of
3932 * non-removable functions, we'd need to keep scanning.
3933 */
3934 return NIL;
3935 }
3936 /* otherwise, we can drop the constant-false input */
3937 continue;
3938 }
3939
3940 /* else emit the simplified arg into the result list */
3942 }
3943
3944 return newargs;
3945}
3946
3947/*
3948 * Subroutine for eval_const_expressions: process arguments of an AND clause
3949 *
3950 * This includes flattening of nested ANDs as well as recursion to
3951 * eval_const_expressions to simplify the AND arguments.
3952 *
3953 * After simplification, AND arguments are handled as follows:
3954 * non constant: keep
3955 * TRUE: drop (does not affect result)
3956 * FALSE: force result to FALSE
3957 * NULL: keep only one
3958 * We must keep one NULL input because AND expressions evaluate to NULL when
3959 * no input is FALSE and at least one is NULL. We don't actually include the
3960 * NULL here, that's supposed to be done by the caller.
3961 *
3962 * The output arguments *haveNull and *forceFalse must be initialized false
3963 * by the caller. They will be set true if a null constant or false constant,
3964 * respectively, is detected anywhere in the argument list.
3965 */
3966static List *
3969 bool *haveNull, bool *forceFalse)
3970{
3971 List *newargs = NIL;
3973
3974 /* See comments in simplify_or_arguments */
3976 while (unprocessed_args)
3977 {
3979
3981
3982 /* flatten nested ANDs as per above comment */
3983 if (is_andclause(arg))
3984 {
3985 List *subargs = ((BoolExpr *) arg)->args;
3987
3989 /* perhaps-overly-tense code to avoid leaking old lists */
3991 continue;
3992 }
3993
3994 /* If it's not an AND, simplify it */
3996
3997 /*
3998 * It is unlikely but not impossible for simplification of a non-AND
3999 * clause to produce an AND. Recheck, but don't be too tense about it
4000 * since it's not a mainstream case. In particular we don't worry
4001 * about const-simplifying the input twice, nor about list leakage.
4002 */
4003 if (is_andclause(arg))
4004 {
4005 List *subargs = ((BoolExpr *) arg)->args;
4006
4008 continue;
4009 }
4010
4011 /*
4012 * OK, we have a const-simplified non-AND argument. Process it per
4013 * comments above.
4014 */
4015 if (IsA(arg, Const))
4016 {
4017 Const *const_input = (Const *) arg;
4018
4019 if (const_input->constisnull)
4020 *haveNull = true;
4021 else if (!DatumGetBool(const_input->constvalue))
4022 {
4023 *forceFalse = true;
4024
4025 /*
4026 * Once we detect a FALSE result we can just exit the loop
4027 * immediately. However, if we ever add a notion of
4028 * non-removable functions, we'd need to keep scanning.
4029 */
4030 return NIL;
4031 }
4032 /* otherwise, we can drop the constant-true input */
4033 continue;
4034 }
4035
4036 /* else emit the simplified arg into the result list */
4038 }
4039
4040 return newargs;
4041}
4042
4043/*
4044 * Subroutine for eval_const_expressions: try to simplify boolean equality
4045 * or inequality condition
4046 *
4047 * Inputs are the operator OID and the simplified arguments to the operator.
4048 * Returns a simplified expression if successful, or NULL if cannot
4049 * simplify the expression.
4050 *
4051 * The idea here is to reduce "x = true" to "x" and "x = false" to "NOT x",
4052 * or similarly "x <> true" to "NOT x" and "x <> false" to "x".
4053 * This is only marginally useful in itself, but doing it in constant folding
4054 * ensures that we will recognize these forms as being equivalent in, for
4055 * example, partial index matching.
4056 *
4057 * We come here only if simplify_function has failed; therefore we cannot
4058 * see two constant inputs, nor a constant-NULL input.
4059 */
4060static Node *
4062{
4063 Node *leftop;
4064 Node *rightop;
4065
4066 Assert(list_length(args) == 2);
4067 leftop = linitial(args);
4068 rightop = lsecond(args);
4069 if (leftop && IsA(leftop, Const))
4070 {
4071 Assert(!((Const *) leftop)->constisnull);
4072 if (opno == BooleanEqualOperator)
4073 {
4074 if (DatumGetBool(((Const *) leftop)->constvalue))
4075 return rightop; /* true = foo */
4076 else
4077 return negate_clause(rightop); /* false = foo */
4078 }
4079 else
4080 {
4081 if (DatumGetBool(((Const *) leftop)->constvalue))
4082 return negate_clause(rightop); /* true <> foo */
4083 else
4084 return rightop; /* false <> foo */
4085 }
4086 }
4087 if (rightop && IsA(rightop, Const))
4088 {
4090 if (opno == BooleanEqualOperator)
4091 {
4093 return leftop; /* foo = true */
4094 else
4095 return negate_clause(leftop); /* foo = false */
4096 }
4097 else
4098 {
4100 return negate_clause(leftop); /* foo <> true */
4101 else
4102 return leftop; /* foo <> false */
4103 }
4104 }
4105 return NULL;
4106}
4107
4108/*
4109 * Subroutine for eval_const_expressions: try to simplify a function call
4110 * (which might originally have been an operator; we don't care)
4111 *
4112 * Inputs are the function OID, actual result type OID (which is needed for
4113 * polymorphic functions), result typmod, result collation, the input
4114 * collation to use for the function, the original argument list (not
4115 * const-simplified yet, unless process_args is false), and some flags;
4116 * also the context data for eval_const_expressions.
4117 *
4118 * Returns a simplified expression if successful, or NULL if cannot
4119 * simplify the function call.
4120 *
4121 * This function is also responsible for converting named-notation argument
4122 * lists into positional notation and/or adding any needed default argument
4123 * expressions; which is a bit grotty, but it avoids extra fetches of the
4124 * function's pg_proc tuple. For this reason, the args list is
4125 * pass-by-reference. Conversion and const-simplification of the args list
4126 * will be done even if simplification of the function call itself is not
4127 * possible.
4128 */
4129static Expr *
4130simplify_function(Oid funcid, Oid result_type, int32 result_typmod,
4132 bool funcvariadic, bool process_args, bool allow_non_const,
4134{
4135 List *args = *args_p;
4138 Expr *newexpr;
4139
4140 /*
4141 * We have three strategies for simplification: execute the function to
4142 * deliver a constant result, use a transform function to generate a
4143 * substitute node tree, or expand in-line the body of the function
4144 * definition (which only works for simple SQL-language functions, but
4145 * that is a common case). Each case needs access to the function's
4146 * pg_proc tuple, so fetch it just once.
4147 *
4148 * Note: the allow_non_const flag suppresses both the second and third
4149 * strategies; so if !allow_non_const, simplify_function can only return a
4150 * Const or NULL. Argument-list rewriting happens anyway, though.
4151 */
4154 elog(ERROR, "cache lookup failed for function %u", funcid);
4156
4157 /*
4158 * Process the function arguments, unless the caller did it already.
4159 *
4160 * Here we must deal with named or defaulted arguments, and then
4161 * recursively apply eval_const_expressions to the whole argument list.
4162 */
4163 if (process_args)
4164 {
4165 args = expand_function_arguments(args, false, result_type, func_tuple);
4168 context);
4169 /* Argument processing done, give it back to the caller */
4170 *args_p = args;
4171 }
4172
4173 /* Now attempt simplification of the function call proper. */
4174
4175 newexpr = evaluate_function(funcid, result_type, result_typmod,
4177 args, funcvariadic,
4178 func_tuple, context);
4179
4180 if (!newexpr && allow_non_const && OidIsValid(func_form->prosupport))
4181 {
4182 /*
4183 * Build a SupportRequestSimplify node to pass to the support
4184 * function, pointing to a dummy FuncExpr node containing the
4185 * simplified arg list. We use this approach to present a uniform
4186 * interface to the support function regardless of how the target
4187 * function is actually being invoked.
4188 */
4191
4192 fexpr.xpr.type = T_FuncExpr;
4193 fexpr.funcid = funcid;
4194 fexpr.funcresulttype = result_type;
4195 fexpr.funcretset = func_form->proretset;
4196 fexpr.funcvariadic = funcvariadic;
4197 fexpr.funcformat = COERCE_EXPLICIT_CALL;
4198 fexpr.funccollid = result_collid;
4199 fexpr.inputcollid = input_collid;
4200 fexpr.args = args;
4201 fexpr.location = -1;
4202
4204 req.root = context->root;
4205 req.fcall = &fexpr;
4206
4207 newexpr = (Expr *)
4209 PointerGetDatum(&req)));
4210
4211 /* catch a possible API misunderstanding */
4212 Assert(newexpr != (Expr *) &fexpr);
4213 }
4214
4215 if (!newexpr && allow_non_const)
4216 newexpr = inline_function(funcid, result_type, result_collid,
4218 func_tuple, context);
4219
4221
4222 return newexpr;
4223}
4224
4225/*
4226 * simplify_aggref
4227 * Call the Aggref.aggfnoid's prosupport function to allow it to
4228 * determine if simplification of the Aggref is possible. Returns the
4229 * newly simplified node if conversion took place; otherwise, returns the
4230 * original Aggref.
4231 *
4232 * See SupportRequestSimplifyAggref comments in supportnodes.h for further
4233 * details.
4234 */
4235static Node *
4237{
4239
4241 {
4243 Node *newnode;
4244
4245 /*
4246 * Build a SupportRequestSimplifyAggref node to pass to the support
4247 * function.
4248 */
4250 req.root = context->root;
4251 req.aggref = aggref;
4252
4254 PointerGetDatum(&req)));
4255
4256 /*
4257 * We expect the support function to return either a new Node or NULL
4258 * (when simplification isn't possible).
4259 */
4260 Assert(newnode != (Node *) aggref || newnode == NULL);
4261
4262 if (newnode != NULL)
4263 return newnode;
4264 }
4265
4266 return (Node *) aggref;
4267}
4268
4269/*
4270 * var_is_nonnullable: check to see if the Var cannot be NULL
4271 *
4272 * If the Var is defined NOT NULL and meanwhile is not nulled by any outer
4273 * joins or grouping sets, then we can know that it cannot be NULL.
4274 *
4275 * use_rel_info indicates whether the corresponding RelOptInfo is available for
4276 * use.
4277 */
4278bool
4280{
4281 Bitmapset *notnullattnums = NULL;
4282
4283 Assert(IsA(var, Var));
4284
4285 /* skip upper-level Vars */
4286 if (var->varlevelsup != 0)
4287 return false;
4288
4289 /* could the Var be nulled by any outer joins or grouping sets? */
4290 if (!bms_is_empty(var->varnullingrels))
4291 return false;
4292
4293 /* system columns cannot be NULL */
4294 if (var->varattno < 0)
4295 return true;
4296
4297 /*
4298 * Check if the Var is defined as NOT NULL. We retrieve the column NOT
4299 * NULL constraint information from the corresponding RelOptInfo if it is
4300 * available; otherwise, we search the hash table for this information.
4301 */
4302 if (use_rel_info)
4303 {
4304 RelOptInfo *rel = find_base_rel(root, var->varno);
4305
4306 notnullattnums = rel->notnullattnums;
4307 }
4308 else
4309 {
4311
4312 /*
4313 * We must skip inheritance parent tables, as some child tables may
4314 * have a NOT NULL constraint for a column while others may not. This
4315 * cannot happen with partitioned tables, though.
4316 */
4317 if (rte->inh && rte->relkind != RELKIND_PARTITIONED_TABLE)
4318 return false;
4319
4320 notnullattnums = find_relation_notnullatts(root, rte->relid);
4321 }
4322
4323 if (var->varattno > 0 &&
4324 bms_is_member(var->varattno, notnullattnums))
4325 return true;
4326
4327 return false;
4328}
4329
4330/*
4331 * expr_is_nonnullable: check to see if the Expr cannot be NULL
4332 *
4333 * Returns true iff the given 'expr' cannot produce SQL NULLs.
4334 *
4335 * If 'use_rel_info' is true, nullability of Vars is checked via the
4336 * corresponding RelOptInfo for the given Var. Some callers require
4337 * nullability information before RelOptInfos are generated. These should
4338 * pass 'use_rel_info' as false.
4339 *
4340 * For now, we support only a limited set of expression types. Support for
4341 * additional node types can be added in the future.
4342 */
4343bool
4345{
4346 /* since this function recurses, it could be driven to stack overflow */
4348
4349 switch (nodeTag(expr))
4350 {
4351 case T_Var:
4352 {
4353 if (root)
4354 return var_is_nonnullable(root, (Var *) expr, use_rel_info);
4355 }
4356 break;
4357 case T_Const:
4358 return !((Const *) expr)->constisnull;
4359 case T_CoalesceExpr:
4360 {
4361 /*
4362 * A CoalesceExpr returns NULL if and only if all its
4363 * arguments are NULL. Therefore, we can determine that a
4364 * CoalesceExpr cannot be NULL if at least one of its
4365 * arguments can be proven non-nullable.
4366 */
4368
4370 {
4372 return true;
4373 }
4374 }
4375 break;
4376 case T_MinMaxExpr:
4377 {
4378 /*
4379 * Like CoalesceExpr, a MinMaxExpr returns NULL only if all
4380 * its arguments evaluate to NULL.
4381 */
4382 MinMaxExpr *minmaxexpr = (MinMaxExpr *) expr;
4383
4385 {
4387 return true;
4388 }
4389 }
4390 break;
4391 case T_CaseExpr:
4392 {
4393 /*
4394 * A CASE expression is non-nullable if all branch results are
4395 * non-nullable. We must also verify that the default result
4396 * (ELSE) exists and is non-nullable.
4397 */
4398 CaseExpr *caseexpr = (CaseExpr *) expr;
4399
4400 /* The default result must be present and non-nullable */
4401 if (caseexpr->defresult == NULL ||
4403 return false;
4404
4405 /* All branch results must be non-nullable */
4407 {
4409 return false;
4410 }
4411
4412 return true;
4413 }
4414 break;
4415 case T_ArrayExpr:
4416 {
4417 /*
4418 * An ARRAY[] expression always returns a valid Array object,
4419 * even if it is empty (ARRAY[]) or contains NULLs
4420 * (ARRAY[NULL]). It never evaluates to a SQL NULL.
4421 */
4422 return true;
4423 }
4424 case T_NullTest:
4425 {
4426 /*
4427 * An IS NULL / IS NOT NULL expression always returns a
4428 * boolean value. It never returns SQL NULL.
4429 */
4430 return true;
4431 }
4432 case T_BooleanTest:
4433 {
4434 /*
4435 * A BooleanTest expression always evaluates to a boolean
4436 * value. It never returns SQL NULL.
4437 */
4438 return true;
4439 }
4440 case T_DistinctExpr:
4441 {
4442 /*
4443 * IS DISTINCT FROM never returns NULL, effectively acting as
4444 * though NULL were a normal data value.
4445 */
4446 return true;
4447 }
4448 case T_RelabelType:
4449 {
4450 /*
4451 * RelabelType does not change the nullability of the data.
4452 * The result is non-nullable if and only if the argument is
4453 * non-nullable.
4454 */
4455 return expr_is_nonnullable(root, ((RelabelType *) expr)->arg,
4456 use_rel_info);
4457 }
4458 default:
4459 break;
4460 }
4461
4462 return false;
4463}
4464
4465/*
4466 * expand_function_arguments: convert named-notation args to positional args
4467 * and/or insert default args, as needed
4468 *
4469 * Returns a possibly-transformed version of the args list.
4470 *
4471 * If include_out_arguments is true, then the args list and the result
4472 * include OUT arguments.
4473 *
4474 * The expected result type of the call must be given, for sanity-checking
4475 * purposes. Also, we ask the caller to provide the function's actual
4476 * pg_proc tuple, not just its OID.
4477 *
4478 * If we need to change anything, the input argument list is copied, not
4479 * modified.
4480 *
4481 * Note: this gets applied to operator argument lists too, even though the
4482 * cases it handles should never occur there. This should be OK since it
4483 * will fall through very quickly if there's nothing to do.
4484 */
4485List *
4487 Oid result_type, HeapTuple func_tuple)
4488{
4490 Oid *proargtypes = funcform->proargtypes.values;
4491 int pronargs = funcform->pronargs;
4492 bool has_named_args = false;
4493 ListCell *lc;
4494
4495 /*
4496 * If we are asked to match to OUT arguments, then use the proallargtypes
4497 * array (which includes those); otherwise use proargtypes (which
4498 * doesn't). Of course, if proallargtypes is null, we always use
4499 * proargtypes. (Fetching proallargtypes is annoyingly expensive
4500 * considering that we may have nothing to do here, but fortunately the
4501 * common case is include_out_arguments == false.)
4502 */
4504 {
4506 bool isNull;
4507
4510 &isNull);
4511 if (!isNull)
4512 {
4514
4515 pronargs = ARR_DIMS(arr)[0];
4516 if (ARR_NDIM(arr) != 1 ||
4517 pronargs < 0 ||
4518 ARR_HASNULL(arr) ||
4519 ARR_ELEMTYPE(arr) != OIDOID)
4520 elog(ERROR, "proallargtypes is not a 1-D Oid array or it contains nulls");
4521 Assert(pronargs >= funcform->pronargs);
4522 proargtypes = (Oid *) ARR_DATA_PTR(arr);
4523 }
4524 }
4525
4526 /* Do we have any named arguments? */
4527 foreach(lc, args)
4528 {
4529 Node *arg = (Node *) lfirst(lc);
4530
4531 if (IsA(arg, NamedArgExpr))
4532 {
4533 has_named_args = true;
4534 break;
4535 }
4536 }
4537
4538 /* If so, we must apply reorder_function_arguments */
4539 if (has_named_args)
4540 {
4542 /* Recheck argument types and add casts if needed */
4543 recheck_cast_function_args(args, result_type,
4545 func_tuple);
4546 }
4547 else if (list_length(args) < pronargs)
4548 {
4549 /* No named args, but we seem to be short some defaults */
4551 /* Recheck argument types and add casts if needed */
4552 recheck_cast_function_args(args, result_type,
4554 func_tuple);
4555 }
4556
4557 return args;
4558}
4559
4560/*
4561 * reorder_function_arguments: convert named-notation args to positional args
4562 *
4563 * This function also inserts default argument values as needed, since it's
4564 * impossible to form a truly valid positional call without that.
4565 */
4566static List *
4568{
4570 int nargsprovided = list_length(args);
4572 ListCell *lc;
4573 int i;
4574
4577 elog(ERROR, "too many function arguments");
4578 memset(argarray, 0, pronargs * sizeof(Node *));
4579
4580 /* Deconstruct the argument list into an array indexed by argnumber */
4581 i = 0;
4582 foreach(lc, args)
4583 {
4584 Node *arg = (Node *) lfirst(lc);
4585
4586 if (!IsA(arg, NamedArgExpr))
4587 {
4588 /* positional argument, assumed to precede all named args */
4589 Assert(argarray[i] == NULL);
4590 argarray[i++] = arg;
4591 }
4592 else
4593 {
4595
4596 Assert(na->argnumber >= 0 && na->argnumber < pronargs);
4597 Assert(argarray[na->argnumber] == NULL);
4598 argarray[na->argnumber] = (Node *) na->arg;
4599 }
4600 }
4601
4602 /*
4603 * Fetch default expressions, if needed, and insert into array at proper
4604 * locations (they aren't necessarily consecutive or all used)
4605 */
4606 if (nargsprovided < pronargs)
4607 {
4609
4610 i = pronargs - funcform->pronargdefaults;
4611 foreach(lc, defaults)
4612 {
4613 if (argarray[i] == NULL)
4614 argarray[i] = (Node *) lfirst(lc);
4615 i++;
4616 }
4617 }
4618
4619 /* Now reconstruct the args list in proper order */
4620 args = NIL;
4621 for (i = 0; i < pronargs; i++)
4622 {
4623 Assert(argarray[i] != NULL);
4624 args = lappend(args, argarray[i]);
4625 }
4626
4627 return args;
4628}
4629
4630/*
4631 * add_function_defaults: add missing function arguments from its defaults
4632 *
4633 * This is used only when the argument list was positional to begin with,
4634 * and so we know we just need to add defaults at the end.
4635 */
4636static List *
4638{
4639 int nargsprovided = list_length(args);
4640 List *defaults;
4641 int ndelete;
4642
4643 /* Get all the default expressions from the pg_proc tuple */
4645
4646 /* Delete any unused defaults from the list */
4647 ndelete = nargsprovided + list_length(defaults) - pronargs;
4648 if (ndelete < 0)
4649 elog(ERROR, "not enough default arguments");
4650 if (ndelete > 0)
4651 defaults = list_delete_first_n(defaults, ndelete);
4652
4653 /* And form the combined argument list, not modifying the input list */
4654 return list_concat_copy(args, defaults);
4655}
4656
4657/*
4658 * fetch_function_defaults: get function's default arguments as expression list
4659 */
4660static List *
4662{
4663 List *defaults;
4665 char *str;
4666
4670 defaults = castNode(List, stringToNode(str));
4671 pfree(str);
4672 return defaults;
4673}
4674
4675/*
4676 * recheck_cast_function_args: recheck function args and typecast as needed
4677 * after adding defaults.
4678 *
4679 * It is possible for some of the defaulted arguments to be polymorphic;
4680 * therefore we can't assume that the default expressions have the correct
4681 * data types already. We have to re-resolve polymorphics and do coercion
4682 * just like the parser did.
4683 *
4684 * This should be a no-op if there are no polymorphic arguments,
4685 * but we do it anyway to be sure.
4686 *
4687 * Note: if any casts are needed, the args list is modified in-place;
4688 * caller should have already copied the list structure.
4689 */
4690static void
4691recheck_cast_function_args(List *args, Oid result_type,
4692 Oid *proargtypes, int pronargs,
4694{
4696 int nargs;
4699 Oid rettype;
4700 ListCell *lc;
4701
4702 if (list_length(args) > FUNC_MAX_ARGS)
4703 elog(ERROR, "too many function arguments");
4704 nargs = 0;
4705 foreach(lc, args)
4706 {
4707 actual_arg_types[nargs++] = exprType((Node *) lfirst(lc));
4708 }
4709 Assert(nargs == pronargs);
4713 nargs,
4714 funcform->prorettype,
4715 false);
4716 /* let's just check we got the same answer as the parser did ... */
4717 if (rettype != result_type)
4718 elog(ERROR, "function's resolved result type changed during planning");
4719
4720 /* perform any necessary typecasting of arguments */
4722}
4723
4724/*
4725 * evaluate_function: try to pre-evaluate a function call
4726 *
4727 * We can do this if the function is strict and has any constant-null inputs
4728 * (just return a null constant), or if the function is immutable and has all
4729 * constant inputs (call it and return the result as a Const node). In
4730 * estimation mode we are willing to pre-evaluate stable functions too.
4731 *
4732 * Returns a simplified expression if successful, or NULL if cannot
4733 * simplify the function.
4734 */
4735static Expr *
4736evaluate_function(Oid funcid, Oid result_type, int32 result_typmod,
4738 bool funcvariadic,
4741{
4743 bool has_nonconst_input = false;
4744 bool has_null_input = false;
4745 ListCell *arg;
4747
4748 /*
4749 * Can't simplify if it returns a set.
4750 */
4751 if (funcform->proretset)
4752 return NULL;
4753
4754 /*
4755 * Can't simplify if it returns RECORD. The immediate problem is that it
4756 * will be needing an expected tupdesc which we can't supply here.
4757 *
4758 * In the case where it has OUT parameters, we could build an expected
4759 * tupdesc from those, but there may be other gotchas lurking. In
4760 * particular, if the function were to return NULL, we would produce a
4761 * null constant with no remaining indication of which concrete record
4762 * type it is. For now, seems best to leave the function call unreduced.
4763 */
4764 if (funcform->prorettype == RECORDOID)
4765 return NULL;
4766
4767 /*
4768 * Check for constant inputs and especially constant-NULL inputs.
4769 */
4770 foreach(arg, args)
4771 {
4772 if (IsA(lfirst(arg), Const))
4774 else
4775 has_nonconst_input = true;
4776 }
4777
4778 /*
4779 * If the function is strict and has a constant-NULL input, it will never
4780 * be called at all, so we can replace the call by a NULL constant, even
4781 * if there are other inputs that aren't constant, and even if the
4782 * function is not otherwise immutable.
4783 */
4784 if (funcform->proisstrict && has_null_input)
4785 return (Expr *) makeNullConst(result_type, result_typmod,
4787
4788 /*
4789 * Otherwise, can simplify only if all inputs are constants. (For a
4790 * non-strict function, constant NULL inputs are treated the same as
4791 * constant non-NULL inputs.)
4792 */
4794 return NULL;
4795
4796 /*
4797 * Ordinarily we are only allowed to simplify immutable functions. But for
4798 * purposes of estimation, we consider it okay to simplify functions that
4799 * are merely stable; the risk that the result might change from planning
4800 * time to execution time is worth taking in preference to not being able
4801 * to estimate the value at all.
4802 */
4803 if (funcform->provolatile == PROVOLATILE_IMMUTABLE)
4804 /* okay */ ;
4805 else if (context->estimate && funcform->provolatile == PROVOLATILE_STABLE)
4806 /* okay */ ;
4807 else
4808 return NULL;
4809
4810 /*
4811 * OK, looks like we can simplify this operator/function.
4812 *
4813 * Build a new FuncExpr node containing the already-simplified arguments.
4814 */
4816 newexpr->funcid = funcid;
4817 newexpr->funcresulttype = result_type;
4818 newexpr->funcretset = false;
4819 newexpr->funcvariadic = funcvariadic;
4820 newexpr->funcformat = COERCE_EXPLICIT_CALL; /* doesn't matter */
4821 newexpr->funccollid = result_collid; /* doesn't matter */
4822 newexpr->inputcollid = input_collid;
4823 newexpr->args = args;
4824 newexpr->location = -1;
4825
4826 return evaluate_expr((Expr *) newexpr, result_type, result_typmod,
4828}
4829
4830/*
4831 * inline_function: try to expand a function call inline
4832 *
4833 * If the function is a sufficiently simple SQL-language function
4834 * (just "SELECT expression"), then we can inline it and avoid the rather
4835 * high per-call overhead of SQL functions. Furthermore, this can expose
4836 * opportunities for constant-folding within the function expression.
4837 *
4838 * We have to beware of some special cases however. A directly or
4839 * indirectly recursive function would cause us to recurse forever,
4840 * so we keep track of which functions we are already expanding and
4841 * do not re-expand them. Also, if a parameter is used more than once
4842 * in the SQL-function body, we require it not to contain any volatile
4843 * functions (volatiles might deliver inconsistent answers) nor to be
4844 * unreasonably expensive to evaluate. The expensiveness check not only
4845 * prevents us from doing multiple evaluations of an expensive parameter
4846 * at runtime, but is a safety value to limit growth of an expression due
4847 * to repeated inlining.
4848 *
4849 * We must also beware of changing the volatility or strictness status of
4850 * functions by inlining them.
4851 *
4852 * Also, at the moment we can't inline functions returning RECORD. This
4853 * doesn't work in the general case because it discards information such
4854 * as OUT-parameter declarations.
4855 *
4856 * Also, context-dependent expression nodes in the argument list are trouble.
4857 *
4858 * Returns a simplified expression if successful, or NULL if cannot
4859 * simplify the function.
4860 */
4861static Expr *
4862inline_function(Oid funcid, Oid result_type, Oid result_collid,
4863 Oid input_collid, List *args,
4864 bool funcvariadic,
4867{
4869 char *src;
4870 Datum tmp;
4871 bool isNull;
4874 inline_error_callback_arg callback_arg;
4876 FuncExpr *fexpr;
4878 TupleDesc rettupdesc;
4879 ParseState *pstate;
4883 Node *newexpr;
4884 int *usecounts;
4885 ListCell *arg;
4886 int i;
4887
4888 /*
4889 * Forget it if the function is not SQL-language or has other showstopper
4890 * properties. (The prokind and nargs checks are just paranoia.)
4891 */
4892 if (funcform->prolang != SQLlanguageId ||
4893 funcform->prokind != PROKIND_FUNCTION ||
4894 funcform->prosecdef ||
4895 funcform->proretset ||
4896 funcform->prorettype == RECORDOID ||
4898 funcform->pronargs != list_length(args))
4899 return NULL;
4900
4901 /* Check for recursive function, and give up trying to expand if so */
4902 if (list_member_oid(context->active_fns, funcid))
4903 return NULL;
4904
4905 /* Check permission to call function (fail later, if not) */
4907 return NULL;
4908
4909 /* Check whether a plugin wants to hook function entry/exit */
4910 if (FmgrHookIsNeeded(funcid))
4911 return NULL;
4912
4913 /*
4914 * Make a temporary memory context, so that we don't leak all the stuff
4915 * that parsing might create.
4916 */
4918 "inline_function",
4921
4922 /*
4923 * We need a dummy FuncExpr node containing the already-simplified
4924 * arguments. (In some cases we don't really need it, but building it is
4925 * cheap enough that it's not worth contortions to avoid.)
4926 */
4928 fexpr->funcid = funcid;
4929 fexpr->funcresulttype = result_type;
4930 fexpr->funcretset = false;
4931 fexpr->funcvariadic = funcvariadic;
4932 fexpr->funcformat = COERCE_EXPLICIT_CALL; /* doesn't matter */
4933 fexpr->funccollid = result_collid; /* doesn't matter */
4934 fexpr->inputcollid = input_collid;
4935 fexpr->args = args;
4936 fexpr->location = -1;
4937
4938 /* Fetch the function body */
4940 src = TextDatumGetCString(tmp);
4941
4942 /*
4943 * Setup error traceback support for ereport(). This is so that we can
4944 * finger the function that bad information came from.
4945 */
4946 callback_arg.proname = NameStr(funcform->proname);
4947 callback_arg.prosrc = src;
4948
4950 sqlerrcontext.arg = &callback_arg;
4953
4954 /* If we have prosqlbody, pay attention to that not prosrc */
4956 func_tuple,
4958 &isNull);
4959 if (!isNull)
4960 {
4961 Node *n;
4962 List *query_list;
4963
4965 if (IsA(n, List))
4966 query_list = linitial_node(List, castNode(List, n));
4967 else
4968 query_list = list_make1(n);
4969 if (list_length(query_list) != 1)
4970 goto fail;
4971 querytree = linitial(query_list);
4972
4973 /*
4974 * Because we'll insist below that the querytree have an empty rtable
4975 * and no sublinks, it cannot have any relation references that need
4976 * to be locked or rewritten. So we can omit those steps.
4977 */
4978 }
4979 else
4980 {
4981 /* Set up to handle parameters while parsing the function body. */
4983 (Node *) fexpr,
4984 input_collid);
4985
4986 /*
4987 * We just do parsing and parse analysis, not rewriting, because
4988 * rewriting will not affect table-free-SELECT-only queries, which is
4989 * all that we care about. Also, we can punt as soon as we detect
4990 * more than one command in the function body.
4991 */
4994 goto fail;
4995
4996 pstate = make_parsestate(NULL);
4997 pstate->p_sourcetext = src;
4998 sql_fn_parser_setup(pstate, pinfo);
4999
5001
5002 free_parsestate(pstate);
5003 }
5004
5005 /*
5006 * The single command must be a simple "SELECT expression".
5007 *
5008 * Note: if you change the tests involved in this, see also plpgsql's
5009 * exec_simple_check_plan(). That generally needs to have the same idea
5010 * of what's a "simple expression", so that inlining a function that
5011 * previously wasn't inlined won't change plpgsql's conclusion.
5012 */
5013 if (!IsA(querytree, Query) ||
5014 querytree->commandType != CMD_SELECT ||
5015 querytree->hasAggs ||
5016 querytree->hasWindowFuncs ||
5017 querytree->hasTargetSRFs ||
5018 querytree->hasSubLinks ||
5019 querytree->cteList ||
5020 querytree->rtable ||
5021 querytree->jointree->fromlist ||
5022 querytree->jointree->quals ||
5023 querytree->groupClause ||
5024 querytree->groupingSets ||
5025 querytree->havingQual ||
5026 querytree->windowClause ||
5027 querytree->distinctClause ||
5028 querytree->sortClause ||
5029 querytree->limitOffset ||
5030 querytree->limitCount ||
5031 querytree->setOperations ||
5032 list_length(querytree->targetList) != 1)
5033 goto fail;
5034
5035 /* If the function result is composite, resolve it */
5037 NULL,
5038 &rettupdesc);
5039
5040 /*
5041 * Make sure the function (still) returns what it's declared to. This
5042 * will raise an error if wrong, but that's okay since the function would
5043 * fail at runtime anyway. Note that check_sql_fn_retval will also insert
5044 * a coercion if needed to make the tlist expression match the declared
5045 * type of the function.
5046 *
5047 * Note: we do not try this until we have verified that no rewriting was
5048 * needed; that's probably not important, but let's be careful.
5049 */
5052 result_type, rettupdesc,
5053 funcform->prokind,
5054 false))
5055 goto fail; /* reject whole-tuple-result cases */
5056
5057 /*
5058 * Given the tests above, check_sql_fn_retval shouldn't have decided to
5059 * inject a projection step, but let's just make sure.
5060 */
5062 goto fail;
5063
5064 /* Now we can grab the tlist expression */
5065 newexpr = (Node *) ((TargetEntry *) linitial(querytree->targetList))->expr;
5066
5067 /*
5068 * If the SQL function returns VOID, we can only inline it if it is a
5069 * SELECT of an expression returning VOID (ie, it's just a redirection to
5070 * another VOID-returning function). In all non-VOID-returning cases,
5071 * check_sql_fn_retval should ensure that newexpr returns the function's
5072 * declared result type, so this test shouldn't fail otherwise; but we may
5073 * as well cope gracefully if it does.
5074 */
5075 if (exprType(newexpr) != result_type)
5076 goto fail;
5077
5078 /*
5079 * Additional validity checks on the expression. It mustn't be more
5080 * volatile than the surrounding function (this is to avoid breaking hacks
5081 * that involve pretending a function is immutable when it really ain't).
5082 * If the surrounding function is declared strict, then the expression
5083 * must contain only strict constructs and must use all of the function
5084 * parameters (this is overkill, but an exact analysis is hard).
5085 */
5086 if (funcform->provolatile == PROVOLATILE_IMMUTABLE &&
5088 goto fail;
5089 else if (funcform->provolatile == PROVOLATILE_STABLE &&
5091 goto fail;
5092
5093 if (funcform->proisstrict &&
5095 goto fail;
5096
5097 /*
5098 * If any parameter expression contains a context-dependent node, we can't
5099 * inline, for fear of putting such a node into the wrong context.
5100 */
5102 goto fail;
5103
5104 /*
5105 * We may be able to do it; there are still checks on parameter usage to
5106 * make, but those are most easily done in combination with the actual
5107 * substitution of the inputs. So start building expression with inputs
5108 * substituted.
5109 */
5110 usecounts = (int *) palloc0(funcform->pronargs * sizeof(int));
5112 args, usecounts);
5113
5114 /* Now check for parameter usage */
5115 i = 0;
5116 foreach(arg, args)
5117 {
5118 Node *param = lfirst(arg);
5119
5120 if (usecounts[i] == 0)
5121 {
5122 /* Param not used at all: uncool if func is strict */
5123 if (funcform->proisstrict)
5124 goto fail;
5125 }
5126 else if (usecounts[i] != 1)
5127 {
5128 /* Param used multiple times: uncool if expensive or volatile */
5130
5131 /*
5132 * We define "expensive" as "contains any subplan or more than 10
5133 * operators". Note that the subplan search has to be done
5134 * explicitly, since cost_qual_eval() will barf on unplanned
5135 * subselects.
5136 */
5137 if (contain_subplans(param))
5138 goto fail;
5140 if (eval_cost.startup + eval_cost.per_tuple >
5141 10 * cpu_operator_cost)
5142 goto fail;
5143
5144 /*
5145 * Check volatility last since this is more expensive than the
5146 * above tests
5147 */
5148 if (contain_volatile_functions(param))
5149 goto fail;
5150 }
5151 i++;
5152 }
5153
5154 /*
5155 * Whew --- we can make the substitution. Copy the modified expression
5156 * out of the temporary memory context, and clean up.
5157 */
5159
5161
5163
5164 /*
5165 * If the result is of a collatable type, force the result to expose the
5166 * correct collation. In most cases this does not matter, but it's
5167 * possible that the function result is used directly as a sort key or in
5168 * other places where we expect exprCollation() to tell the truth.
5169 */
5171 {
5173
5175 {
5177
5178 newnode->arg = (Expr *) newexpr;
5179 newnode->collOid = result_collid;
5180 newnode->location = -1;
5181
5182 newexpr = (Node *) newnode;
5183 }
5184 }
5185
5186 /*
5187 * Since there is now no trace of the function in the plan tree, we must
5188 * explicitly record the plan's dependency on the function.
5189 */
5190 if (context->root)
5191 record_plan_function_dependency(context->root, funcid);
5192
5193 /*
5194 * Recursively try to simplify the modified expression. Here we must add
5195 * the current function to the context list of active functions.
5196 */
5197 context->active_fns = lappend_oid(context->active_fns, funcid);
5199 context->active_fns = list_delete_last(context->active_fns);
5200
5202
5203 return (Expr *) newexpr;
5204
5205 /* Here if func is not inlinable: release temp memory and return NULL */
5206fail:
5210
5211 return NULL;
5212}
5213
5214/*
5215 * Replace Param nodes by appropriate actual parameters
5216 */
5217static Node *
5218substitute_actual_parameters(Node *expr, int nargs, List *args,
5219 int *usecounts)
5220{
5222
5223 context.nargs = nargs;
5224 context.args = args;
5225 context.usecounts = usecounts;
5226
5227 return substitute_actual_parameters_mutator(expr, &context);
5228}
5229
5230static Node *
5233{
5234 if (node == NULL)
5235 return NULL;
5236 if (IsA(node, Param))
5237 {
5238 Param *param = (Param *) node;
5239
5240 if (param->paramkind != PARAM_EXTERN)
5241 elog(ERROR, "unexpected paramkind: %d", (int) param->paramkind);
5242 if (param->paramid <= 0 || param->paramid > context->nargs)
5243 elog(ERROR, "invalid paramid: %d", param->paramid);
5244
5245 /* Count usage of parameter */
5246 context->usecounts[param->paramid - 1]++;
5247
5248 /* Select the appropriate actual arg and replace the Param with it */
5249 /* We don't need to copy at this time (it'll get done later) */
5250 return list_nth(context->args, param->paramid - 1);
5251 }
5253}
5254
5255/*
5256 * error context callback to let us supply a call-stack traceback
5257 */
5258static void
5260{
5263
5264 /* If it's a syntax error, convert to internal syntax error report */
5266 if (syntaxerrposition > 0)
5267 {
5268 errposition(0);
5270 internalerrquery(callback_arg->prosrc);
5271 }
5272
5273 errcontext("SQL function \"%s\" during inlining", callback_arg->proname);
5274}
5275
5276/*
5277 * evaluate_expr: pre-evaluate a constant expression
5278 *
5279 * We use the executor's routine ExecEvalExpr() to avoid duplication of
5280 * code and ensure we get the same result as the executor would get.
5281 */
5282Expr *
5283evaluate_expr(Expr *expr, Oid result_type, int32 result_typmod,
5285{
5286 EState *estate;
5287 ExprState *exprstate;
5288 MemoryContext oldcontext;
5290 bool const_is_null;
5292 bool resultTypByVal;
5293
5294 /*
5295 * To use the executor, we need an EState.
5296 */
5297 estate = CreateExecutorState();
5298
5299 /* We can use the estate's working context to avoid memory leaks. */
5300 oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
5301
5302 /* Make sure any opfuncids are filled in. */
5303 fix_opfuncids((Node *) expr);
5304
5305 /*
5306 * Prepare expr for execution. (Note: we can't use ExecPrepareExpr
5307 * because it'd result in recursively invoking eval_const_expressions.)
5308 */
5309 exprstate = ExecInitExpr(expr, NULL);
5310
5311 /*
5312 * And evaluate it.
5313 *
5314 * It is OK to use a default econtext because none of the ExecEvalExpr()
5315 * code used in this situation will use econtext. That might seem
5316 * fortuitous, but it's not so unreasonable --- a constant expression does
5317 * not depend on context, by definition, n'est ce pas?
5318 */
5320 GetPerTupleExprContext(estate),
5321 &const_is_null);
5322
5323 /* Get info needed about result datatype */
5325
5326 /* Get back to outer memory context */
5327 MemoryContextSwitchTo(oldcontext);
5328
5329 /*
5330 * Must copy result out of sub-context used by expression eval.
5331 *
5332 * Also, if it's varlena, forcibly detoast it. This protects us against
5333 * storing TOAST pointers into plans that might outlive the referenced
5334 * data. (makeConst would handle detoasting anyway, but it's worth a few
5335 * extra lines here so that we can do the copy and detoast in one step.)
5336 */
5337 if (!const_is_null)
5338 {
5339 if (resultTypLen == -1)
5341 else
5343 }
5344
5345 /* Release all the junk we just created */
5346 FreeExecutorState(estate);
5347
5348 /*
5349 * Make the constant result node.
5350 */
5351 return (Expr *) makeConst(result_type, result_typmod, result_collation,
5355}
5356
5357
5358/*
5359 * inline_function_in_from
5360 * Attempt to "inline" a function in the FROM clause.
5361 *
5362 * "rte" is an RTE_FUNCTION rangetable entry. If it represents a call of a
5363 * function that can be inlined, expand the function and return the
5364 * substitute Query structure. Otherwise, return NULL.
5365 *
5366 * We assume that the RTE's expression has already been put through
5367 * eval_const_expressions(), which among other things will take care of
5368 * default arguments and named-argument notation.
5369 *
5370 * This has a good deal of similarity to inline_function(), but that's
5371 * for the general-expression case, and there are enough differences to
5372 * justify separate functions.
5373 */
5374Query *
5376{
5377 RangeTblFunction *rtfunc;
5378 FuncExpr *fexpr;
5379 Oid func_oid;
5384 Datum tmp;
5385 char *src;
5386 inline_error_callback_arg callback_arg;
5388 Query *querytree = NULL;
5389
5390 Assert(rte->rtekind == RTE_FUNCTION);
5391
5392 /*
5393 * Guard against infinite recursion during expansion by checking for stack
5394 * overflow. (There's no need to do more.)
5395 */
5397
5398 /* Fail if the RTE has ORDINALITY - we don't implement that here. */
5399 if (rte->funcordinality)
5400 return NULL;
5401
5402 /* Fail if RTE isn't a single, simple FuncExpr */
5403 if (list_length(rte->functions) != 1)
5404 return NULL;
5405 rtfunc = (RangeTblFunction *) linitial(rte->functions);
5406
5407 if (!IsA(rtfunc->funcexpr, FuncExpr))
5408 return NULL;
5409 fexpr = (FuncExpr *) rtfunc->funcexpr;
5410
5411 func_oid = fexpr->funcid;
5412
5413 /*
5414 * Refuse to inline if the arguments contain any volatile functions or
5415 * sub-selects. Volatile functions are rejected because inlining may
5416 * result in the arguments being evaluated multiple times, risking a
5417 * change in behavior. Sub-selects are rejected partly for implementation
5418 * reasons (pushing them down another level might change their behavior)
5419 * and partly because they're likely to be expensive and so multiple
5420 * evaluation would be bad.
5421 */
5422 if (contain_volatile_functions((Node *) fexpr->args) ||
5423 contain_subplans((Node *) fexpr->args))
5424 return NULL;
5425
5426 /* Check permission to call function (fail later, if not) */
5428 return NULL;
5429
5430 /* Check whether a plugin wants to hook function entry/exit */
5432 return NULL;
5433
5434 /*
5435 * OK, let's take a look at the function's pg_proc entry.
5436 */
5439 elog(ERROR, "cache lookup failed for function %u", func_oid);
5441
5442 /*
5443 * If the function SETs any configuration parameters, inlining would cause
5444 * us to miss making those changes.
5445 */
5447 {
5449 return NULL;
5450 }
5451
5452 /*
5453 * Make a temporary memory context, so that we don't leak all the stuff
5454 * that parsing and rewriting might create. If we succeed, we'll copy
5455 * just the finished query tree back up to the caller's context.
5456 */
5458 "inline_function_in_from",
5461
5462 /* Fetch the function body */
5464 src = TextDatumGetCString(tmp);
5465
5466 /*
5467 * If the function has an attached support function that can handle
5468 * SupportRequestInlineInFrom, then attempt to inline with that.
5469 */
5470 if (funcform->prosupport)
5471 {
5473
5475 req.root = root;
5476 req.rtfunc = rtfunc;
5477 req.proc = func_tuple;
5478
5479 querytree = (Query *)
5481 PointerGetDatum(&req)));
5482 }
5483
5484 /*
5485 * Setup error traceback support for ereport(). This is so that we can
5486 * finger the function that bad information came from. We don't install
5487 * this while running the support function, since it'd be likely to do the
5488 * wrong thing: any parse errors reported during that are very likely not
5489 * against the raw function source text.
5490 */
5491 callback_arg.proname = NameStr(funcform->proname);
5492 callback_arg.prosrc = src;
5493
5495 sqlerrcontext.arg = &callback_arg;
5498
5499 /*
5500 * If SupportRequestInlineInFrom didn't work, try our built-in inlining
5501 * mechanism.
5502 */
5503 if (!querytree)
5505 func_tuple, funcform, src);
5506
5507 if (!querytree)
5508 goto fail; /* no luck there either, fail */
5509
5510 /*
5511 * The result had better be a SELECT Query.
5512 */
5514 Assert(querytree->commandType == CMD_SELECT);
5515
5516 /*
5517 * Looks good --- substitute parameters into the query.
5518 */
5520 funcform->pronargs,
5521 fexpr->args);
5522
5523 /*
5524 * Copy the modified query out of the temporary memory context, and clean
5525 * up.
5526 */
5528
5530
5534
5535 /*
5536 * We don't have to fix collations here because the upper query is already
5537 * parsed, ie, the collations in the RTE are what count.
5538 */
5539
5540 /*
5541 * Since there is now no trace of the function in the plan tree, we must
5542 * explicitly record the plan's dependency on the function.
5543 */
5545
5546 /*
5547 * We must also notice if the inserted query adds a dependency on the
5548 * calling role due to RLS quals.
5549 */
5550 if (querytree->hasRowSecurity)
5551 root->glob->dependsOnRole = true;
5552
5553 return querytree;
5554
5555 /* Here if func is not inlinable: release temp memory and return NULL */
5556fail:
5561
5562 return NULL;
5563}
5564
5565/*
5566 * inline_sql_function_in_from
5567 *
5568 * This implements inline_function_in_from for SQL-language functions.
5569 * Returns NULL if the function couldn't be inlined.
5570 *
5571 * The division of labor between here and inline_function_in_from is based
5572 * on the rule that inline_function_in_from should make all checks that are
5573 * certain to be required in both this case and the support-function case.
5574 * Support functions might also want to make checks analogous to the ones
5575 * made here, but then again they might not, or they might just assume that
5576 * the function they are attached to can validly be inlined.
5577 */
5578static Query *
5580 RangeTblFunction *rtfunc,
5581 FuncExpr *fexpr,
5584 const char *src)
5585{
5586 Datum sqlbody;
5587 bool isNull;
5591 TupleDesc rettupdesc;
5592
5593 /*
5594 * The function must be declared to return a set, else inlining would
5595 * change the results if the contained SELECT didn't return exactly one
5596 * row.
5597 */
5598 if (!fexpr->funcretset)
5599 return NULL;
5600
5601 /*
5602 * Forget it if the function is not SQL-language or has other showstopper
5603 * properties. In particular it mustn't be declared STRICT, since we
5604 * couldn't enforce that. It also mustn't be VOLATILE, because that is
5605 * supposed to cause it to be executed with its own snapshot, rather than
5606 * sharing the snapshot of the calling query. We also disallow returning
5607 * SETOF VOID, because inlining would result in exposing the actual result
5608 * of the function's last SELECT, which should not happen in that case.
5609 * (Rechecking prokind, proretset, and pronargs is just paranoia.)
5610 */
5611 if (funcform->prolang != SQLlanguageId ||
5612 funcform->prokind != PROKIND_FUNCTION ||
5613 funcform->proisstrict ||
5614 funcform->provolatile == PROVOLATILE_VOLATILE ||
5615 funcform->prorettype == VOIDOID ||
5616 funcform->prosecdef ||
5617 !funcform->proretset ||
5618 list_length(fexpr->args) != funcform->pronargs)
5619 return NULL;
5620
5621 /* If we have prosqlbody, pay attention to that not prosrc */
5623 func_tuple,
5625 &isNull);
5626 if (!isNull)
5627 {
5628 Node *n;
5629
5631 if (IsA(n, List))
5633 else
5635 if (list_length(querytree_list) != 1)
5636 return NULL;
5638
5639 /* Acquire necessary locks, then apply rewriter. */
5640 AcquireRewriteLocks(querytree, true, false);
5642 if (list_length(querytree_list) != 1)
5643 return NULL;
5645 }
5646 else
5647 {
5650
5651 /*
5652 * Set up to handle parameters while parsing the function body. We
5653 * can use the FuncExpr just created as the input for
5654 * prepare_sql_fn_parse_info.
5655 */
5657 (Node *) fexpr,
5658 fexpr->inputcollid);
5659
5660 /*
5661 * Parse, analyze, and rewrite (unlike inline_function(), we can't
5662 * skip rewriting here). We can fail as soon as we find more than one
5663 * query, though.
5664 */
5667 return NULL;
5668
5670 src,
5672 pinfo, NULL);
5673 if (list_length(querytree_list) != 1)
5674 return NULL;
5676 }
5677
5678 /*
5679 * Also resolve the actual function result tupdesc, if composite. If we
5680 * have a coldeflist, believe that; otherwise use get_expr_result_type.
5681 * (This logic should match ExecInitFunctionScan.)
5682 */
5683 if (rtfunc->funccolnames != NIL)
5684 {
5686 rettupdesc = BuildDescFromLists(rtfunc->funccolnames,
5687 rtfunc->funccoltypes,
5688 rtfunc->funccoltypmods,
5689 rtfunc->funccolcollations);
5690 }
5691 else
5692 functypclass = get_expr_result_type((Node *) fexpr, NULL, &rettupdesc);
5693
5694 /*
5695 * The single command must be a plain SELECT.
5696 */
5697 if (!IsA(querytree, Query) ||
5698 querytree->commandType != CMD_SELECT)
5699 return NULL;
5700
5701 /*
5702 * Make sure the function (still) returns what it's declared to. This
5703 * will raise an error if wrong, but that's okay since the function would
5704 * fail at runtime anyway. Note that check_sql_fn_retval will also insert
5705 * coercions if needed to make the tlist expression(s) match the declared
5706 * type of the function. We also ask it to insert dummy NULL columns for
5707 * any dropped columns in rettupdesc, so that the elements of the modified
5708 * tlist match up to the attribute numbers.
5709 *
5710 * If the function returns a composite type, don't inline unless the check
5711 * shows it's returning a whole tuple result; otherwise what it's
5712 * returning is a single composite column which is not what we need.
5713 */
5715 fexpr->funcresulttype, rettupdesc,
5716 funcform->prokind,
5717 true) &&
5721 return NULL; /* reject not-whole-tuple-result cases */
5722
5723 /*
5724 * check_sql_fn_retval might've inserted a projection step, but that's
5725 * fine; just make sure we use the upper Query.
5726 */
5728
5729 return querytree;
5730}
5731
5732/*
5733 * Replace Param nodes by appropriate actual parameters
5734 *
5735 * This is just enough different from substitute_actual_parameters()
5736 * that it needs its own code.
5737 */
5738static Query *
5739substitute_actual_parameters_in_from(Query *expr, int nargs, List *args)
5740{
5742
5743 context.nargs = nargs;
5744 context.args = args;
5745 context.sublevels_up = 1;
5746
5747 return query_tree_mutator(expr,
5749 &context,
5750 0);
5751}
5752
5753static Node *
5756{
5757 Node *result;
5758
5759 if (node == NULL)
5760 return NULL;
5761 if (IsA(node, Query))
5762 {
5763 context->sublevels_up++;
5764 result = (Node *) query_tree_mutator((Query *) node,
5766 context,
5767 0);
5768 context->sublevels_up--;
5769 return result;
5770 }
5771 if (IsA(node, Param))
5772 {
5773 Param *param = (Param *) node;
5774
5775 if (param->paramkind == PARAM_EXTERN)
5776 {
5777 if (param->paramid <= 0 || param->paramid > context->nargs)
5778 elog(ERROR, "invalid paramid: %d", param->paramid);
5779
5780 /*
5781 * Since the parameter is being inserted into a subquery, we must
5782 * adjust levels.
5783 */
5784 result = copyObject(list_nth(context->args, param->paramid - 1));
5785 IncrementVarSublevelsUp(result, context->sublevels_up, 0);
5786 return result;
5787 }
5788 }
5789 return expression_tree_mutator(node,
5791 context);
5792}
5793
5794/*
5795 * pull_paramids
5796 * Returns a Bitmapset containing the paramids of all Params in 'expr'.
5797 */
5798Bitmapset *
5799pull_paramids(Expr *expr)
5800{
5801 Bitmapset *result = NULL;
5802
5803 (void) pull_paramids_walker((Node *) expr, &result);
5804
5805 return result;
5806}
5807
5808static bool
5809pull_paramids_walker(Node *node, Bitmapset **context)
5810{
5811 if (node == NULL)
5812 return false;
5813 if (IsA(node, Param))
5814 {
5815 Param *param = (Param *) node;
5816
5817 *context = bms_add_member(*context, param->paramid);
5818 return false;
5819 }
5820 return expression_tree_walker(node, pull_paramids_walker, context);
5821}
5822
5823/*
5824 * Build ScalarArrayOpExpr on top of 'exprs.' 'haveNonConst' indicates
5825 * whether at least one of the expressions is not Const. When it's false,
5826 * the array constant is built directly; otherwise, we have to build a child
5827 * ArrayExpr. The 'exprs' list gets freed if not directly used in the output
5828 * expression tree.
5829 */
5832 Oid inputcollid, List *exprs, bool haveNonConst)
5833{
5834 Node *arrayNode = NULL;
5836 Oid arraytype = get_array_type(coltype);
5837
5838 if (!OidIsValid(arraytype))
5839 return NULL;
5840
5841 /*
5842 * Assemble an array from the list of constants. It seems more profitable
5843 * to build a const array. But in the presence of other nodes, we don't
5844 * have a specific value here and must employ an ArrayExpr instead.
5845 */
5846 if (haveNonConst)
5847 {
5849
5850 /* array_collid will be set by parse_collate.c */
5851 arrayExpr->element_typeid = coltype;
5852 arrayExpr->array_typeid = arraytype;
5853 arrayExpr->multidims = false;
5854 arrayExpr->elements = exprs;
5855 arrayExpr->location = -1;
5856
5857 arrayNode = (Node *) arrayExpr;
5858 }
5859 else
5860 {
5861 int16 typlen;
5862 bool typbyval;
5863 char typalign;
5864 Datum *elems;
5865 bool *nulls;
5866 int i = 0;
5868 int dims[1] = {list_length(exprs)};
5869 int lbs[1] = {1};
5870
5871 get_typlenbyvalalign(coltype, &typlen, &typbyval, &typalign);
5872
5873 elems = palloc_array(Datum, list_length(exprs));
5874 nulls = palloc_array(bool, list_length(exprs));
5875 foreach_node(Const, value, exprs)
5876 {
5877 elems[i] = value->constvalue;
5878 nulls[i++] = value->constisnull;
5879 }
5880
5881 arrayConst = construct_md_array(elems, nulls, 1, dims, lbs,
5882 coltype, typlen, typbyval, typalign);
5885 false, false);
5886
5887 pfree(elems);
5888 pfree(nulls);
5889 list_free(exprs);
5890 }
5891
5892 /* Build the SAOP expression node */
5894 saopexpr->opno = oper;
5895 saopexpr->opfuncid = get_opcode(oper);
5896 saopexpr->hashfuncid = InvalidOid;
5897 saopexpr->negfuncid = InvalidOid;
5898 saopexpr->useOr = true;
5899 saopexpr->inputcollid = inputcollid;
5901 saopexpr->location = -1;
5902
5903 return saopexpr;
5904}
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:98
#define NameStr(name)
Definition c.h:765
#define Assert(condition)
Definition c.h:873
int16_t int16
Definition c.h:541
int32_t int32
Definition c.h:542
#define OidIsValid(objectId)
Definition c.h:788
static List * simplify_or_arguments(List *args, eval_const_expressions_context *context, bool *haveNull, bool *forceTrue)
Definition clauses.c:3862
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:5376
static List * add_function_defaults(List *args, int pronargs, HeapTuple func_tuple)
Definition clauses.c:4638
#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:4737
static Node * substitute_actual_parameters_mutator(Node *node, substitute_actual_parameters_context *context)
Definition clauses.c:5232
static bool ece_function_is_safe(Oid funcid, eval_const_expressions_context *context)
Definition clauses.c:3824
static List * simplify_and_arguments(List *args, eval_const_expressions_context *context, bool *haveNull, bool *forceFalse)
Definition clauses.c:3968
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:4131
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:4863
static List * reorder_function_arguments(List *args, int pronargs, HeapTuple func_tuple)
Definition clauses.c:4568
static Node * simplify_aggref(Aggref *aggref, eval_const_expressions_context *context)
Definition clauses.c:4237
static Node * substitute_actual_parameters(Node *expr, int nargs, List *args, int *usecounts)
Definition clauses.c:5219
static Query * substitute_actual_parameters_in_from(Query *expr, int nargs, List *args)
Definition clauses.c:5740
static void sql_inline_error_callback(void *arg)
Definition clauses.c:5260
static bool contain_non_const_walker(Node *node, void *context)
Definition clauses.c:3808
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:4692
List * expand_function_arguments(List *args, bool include_out_arguments, Oid result_type, HeapTuple func_tuple)
Definition clauses.c:4487
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:5755
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:5580
bool contain_subplans(Node *clause)
Definition clauses.c:339
static Node * simplify_boolean_equality(Oid opno, List *args)
Definition clauses.c:4062
Bitmapset * pull_paramids(Expr *expr)
Definition clauses.c:5800
ScalarArrayOpExpr * make_SAOP_expr(Oid oper, Node *leftexpr, Oid coltype, Oid arraycollid, Oid inputcollid, List *exprs, bool haveNonConst)
Definition clauses.c:5832
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:5810
Expr * evaluate_expr(Expr *expr, Oid result_type, int32 result_typmod, Oid result_collation)
Definition clauses.c:5284
bool expr_is_nonnullable(PlannerInfo *root, Expr *expr, bool use_rel_info)
Definition clauses.c:4345
static List * fetch_function_defaults(HeapTuple func_tuple)
Definition clauses.c:4662
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:4280
double cpu_operator_cost
Definition costsize.c:134
void cost_qual_eval(QualCost *cost, List *quals, PlannerInfo *root)
Definition costsize.c:4904
Datum datumCopy(Datum value, bool typByVal, int typLen)
Definition datum.c:132
int internalerrquery(const char *query)
Definition elog.c:1516
int internalerrposition(int cursorpos)
Definition elog.c:1496
ErrorContextCallback * error_context_stack
Definition elog.c:95
int geterrposition(void)
Definition elog.c:1612
int errposition(int cursorpos)
Definition elog.c:1480
#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 @172 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:3057
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:3024
char func_volatile(Oid funcid)
Definition lsyscache.c:1930
Oid get_array_type(Oid typid)
Definition lsyscache.c:2937
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
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:371
@ 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:686
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:763
List * pg_parse_query(const char *query_string)
Definition postgres.c:604
List * pg_rewrite_query(Query *query)
Definition postgres.c:803
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:2001
@ IS_NOT_FALSE
Definition primnodes.h:2001
@ IS_NOT_UNKNOWN
Definition primnodes.h:2001
@ IS_TRUE
Definition primnodes.h:2001
@ IS_UNKNOWN
Definition primnodes.h:2001
@ IS_FALSE
Definition primnodes.h:2001
@ AND_EXPR
Definition primnodes.h:963
@ OR_EXPR
Definition primnodes.h:963
@ NOT_EXPR
Definition primnodes.h:963
@ PARAM_EXTERN
Definition primnodes.h:384
@ COERCE_IMPLICIT_CAST
Definition primnodes.h:768
@ COERCE_EXPLICIT_CALL
Definition primnodes.h:766
@ IS_NULL
Definition primnodes.h:1977
@ IS_NOT_NULL
Definition primnodes.h:1977
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:3615
void record_plan_function_dependency(PlannerInfo *root, Oid funcid)
Definition setrefs.c:3575
void check_stack_depth(void)
Definition stack_depth.c:95
Oid aggfnoid
Definition primnodes.h:463
BoolExprType boolop
Definition primnodes.h:971
List * args
Definition primnodes.h:972
ParseLoc location
Definition primnodes.h:1247
ParseLoc location
Definition primnodes.h:1314
Oid consttype
Definition primnodes.h:329
MemoryContext es_query_cxt
Definition execnodes.h:712
struct ErrorContextCallback * previous
Definition elog.h:297
Expr xpr
Definition primnodes.h:780
ParseLoc location
Definition primnodes.h:802
Oid funcid
Definition primnodes.h:782
List * args
Definition primnodes.h:800
Definition pg_list.h:54
Definition nodes.h:135
NodeTag type
Definition nodes.h:136
Oid opno
Definition primnodes.h:850
List * args
Definition primnodes.h:868
ParseLoc location
Definition primnodes.h:871
ParamExternData params[FLEXIBLE_ARRAY_MEMBER]
Definition params.h:124
ParamFetchHook paramFetch
Definition params.h:111
ParseLoc location
Definition primnodes.h:403
int32 paramtypmod
Definition primnodes.h:399
int paramid
Definition primnodes.h:396
Oid paramtype
Definition primnodes.h:397
ParamKind paramkind
Definition primnodes.h:395
Oid paramcollid
Definition primnodes.h:401
const char * p_sourcetext
Definition parse_node.h:195
Bitmapset * notnullattnums
Definition pathnodes.h:1065
List * args
Definition primnodes.h:1448
AttrNumber varattno
Definition primnodes.h:274
int varno
Definition primnodes.h:269
Index varlevelsup
Definition primnodes.h:294
List * args
Definition primnodes.h:605
Index winref
Definition primnodes.h:611
Expr * aggfilter
Definition primnodes.h:607
ParseLoc location
Definition primnodes.h:619
int ignore_nulls
Definition primnodes.h:617
void ReleaseSysCache(HeapTuple tuple)
Definition syscache.c:264
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition syscache.c:220
Datum SysCacheGetAttr(int cacheId, HeapTuple tup, AttrNumber attributeNumber, bool *isNull)
Definition syscache.c:595
Datum SysCacheGetAttrNotNull(int cacheId, HeapTuple tup, AttrNumber attributeNumber)
Definition syscache.c:625
TupleDesc BuildDescFromLists(const List *names, const List *types, const List *typmods, const List *collations)
Definition tupdesc.c:1051
bool DomainHasConstraints(Oid type_id)
Definition typcache.c:1488

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

4639{
4640 int nargsprovided = list_length(args);
4641 List *defaults;
4642 int ndelete;
4643
4644 /* Get all the default expressions from the pg_proc tuple */
4646
4647 /* Delete any unused defaults from the list */
4648 ndelete = nargsprovided + list_length(defaults) - pronargs;
4649 if (ndelete < 0)
4650 elog(ERROR, "not enough default arguments");
4651 if (ndelete > 0)
4652 defaults = list_delete_first_n(defaults, ndelete);
4653
4654 /* And form the combined argument list, not modifying the input list */
4655 return list_concat_copy(args, defaults);
4656}

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

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:3280
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:735
TypeCacheEntry * lookup_type_cache(Oid type_id, int flags)
Definition typcache.c:386
#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:6817

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

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

3809{
3810 if (node == NULL)
3811 return false;
3812 if (IsA(node, Const))
3813 return false;
3814 if (IsA(node, List))
3815 return expression_tree_walker(node, contain_non_const_walker, context);
3816 /* Otherwise, abort the tree traversal and return true */
3817 return true;
3818}

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:1825
@ VOLATILITY_VOLATILE
Definition pathnodes.h:1824
VolatileFunctionStatus has_volatile_expr
Definition pathnodes.h:1870
List * exprs
Definition pathnodes.h:1858
Expr * clause
Definition pathnodes.h:2870

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

3825{
3826 char provolatile = func_volatile(funcid);
3827
3828 /*
3829 * Ordinarily we are only allowed to simplify immutable functions. But for
3830 * purposes of estimation, we consider it okay to simplify functions that
3831 * are merely stable; the risk that the result might change from planning
3832 * time to execution time is worth taking in preference to not being able
3833 * to estimate the value at all.
3834 */
3836 return true;
3837 if (context->estimate && provolatile == PROVOLATILE_STABLE)
3838 return true;
3839 return false;
3840}

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 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.
2725 */
2726 foreach(arg, args)
2727 {
2728 if (IsA(lfirst(arg), Const))
2729 {
2732 }
2733 else
2734 has_nonconst_input = true;
2735 }
2736
2737 /* all constants? then can optimize this out */
2738 if (!has_nonconst_input)
2739 {
2740 /* all nulls? then not distinct */
2741 if (all_null_input)
2742 return makeBoolConst(false, false);
2743
2744 /* one null? then distinct */
2745 if (has_null_input)
2746 return makeBoolConst(true, false);
2747
2748 /* otherwise try to evaluate the '=' operator */
2749 /* (NOT okay to try to inline it, though!) */
2750
2751 /*
2752 * Need to get OID of underlying function. Okay to
2753 * scribble on input to this extent.
2754 */
2755 set_opfuncid((OpExpr *) expr); /* rely on struct
2756 * equivalence */
2757
2758 /*
2759 * Code for op/func reduction is pretty bulky, so split it
2760 * out as a separate function.
2761 */
2762 simple = simplify_function(expr->opfuncid,
2763 expr->opresulttype, -1,
2764 expr->opcollid,
2765 expr->inputcollid,
2766 &args,
2767 false,
2768 false,
2769 false,
2770 context);
2771 if (simple) /* successfully simplified it */
2772 {
2773 /*
2774 * Since the underlying operator is "=", must negate
2775 * its result
2776 */
2777 Const *csimple = castNode(Const, simple);
2778
2779 csimple->constvalue =
2780 BoolGetDatum(!DatumGetBool(csimple->constvalue));
2781 return (Node *) csimple;
2782 }
2783 }
2784
2785 /*
2786 * The expression cannot be simplified any further, so build
2787 * and return a replacement DistinctExpr node using the
2788 * possibly-simplified arguments.
2789 */
2791 newexpr->opno = expr->opno;
2792 newexpr->opfuncid = expr->opfuncid;
2793 newexpr->opresulttype = expr->opresulttype;
2794 newexpr->opretset = expr->opretset;
2795 newexpr->opcollid = expr->opcollid;
2796 newexpr->inputcollid = expr->inputcollid;
2797 newexpr->args = args;
2798 newexpr->location = expr->location;
2799 return (Node *) newexpr;
2800 }
2801 case T_NullIfExpr:
2802 {
2803 NullIfExpr *expr;
2804 ListCell *arg;
2805 bool has_nonconst_input = false;
2806
2807 /* Copy the node and const-simplify its arguments */
2808 expr = (NullIfExpr *) ece_generic_processing(node);
2809
2810 /* If either argument is NULL they can't be equal */
2811 foreach(arg, expr->args)
2812 {
2813 if (!IsA(lfirst(arg), Const))
2814 has_nonconst_input = true;
2815 else if (((Const *) lfirst(arg))->constisnull)
2816 return (Node *) linitial(expr->args);
2817 }
2818
2819 /*
2820 * Need to get OID of underlying function before checking if
2821 * the function is OK to evaluate.
2822 */
2823 set_opfuncid((OpExpr *) expr);
2824
2825 if (!has_nonconst_input &&
2826 ece_function_is_safe(expr->opfuncid, context))
2827 return ece_evaluate_expr(expr);
2828
2829 return (Node *) expr;
2830 }
2832 {
2833 ScalarArrayOpExpr *saop;
2834
2835 /* Copy the node and const-simplify its arguments */
2837
2838 /* Make sure we know underlying function */
2839 set_sa_opfuncid(saop);
2840
2841 /*
2842 * If all arguments are Consts, and it's a safe function, we
2843 * can fold to a constant
2844 */
2845 if (ece_all_arguments_const(saop) &&
2846 ece_function_is_safe(saop->opfuncid, context))
2847 return ece_evaluate_expr(saop);
2848 return (Node *) saop;
2849 }
2850 case T_BoolExpr:
2851 {
2852 BoolExpr *expr = (BoolExpr *) node;
2853
2854 switch (expr->boolop)
2855 {
2856 case OR_EXPR:
2857 {
2858 List *newargs;
2859 bool haveNull = false;
2860 bool forceTrue = false;
2861
2863 context,
2864 &haveNull,
2865 &forceTrue);
2866 if (forceTrue)
2867 return makeBoolConst(true, false);
2868 if (haveNull)
2870 makeBoolConst(false, true));
2871 /* If all the inputs are FALSE, result is FALSE */
2872 if (newargs == NIL)
2873 return makeBoolConst(false, false);
2874
2875 /*
2876 * If only one nonconst-or-NULL input, it's the
2877 * result
2878 */
2879 if (list_length(newargs) == 1)
2880 return (Node *) linitial(newargs);
2881 /* Else we still need an OR node */
2882 return (Node *) make_orclause(newargs);
2883 }
2884 case AND_EXPR:
2885 {
2886 List *newargs;
2887 bool haveNull = false;
2888 bool forceFalse = false;
2889
2891 context,
2892 &haveNull,
2893 &forceFalse);
2894 if (forceFalse)
2895 return makeBoolConst(false, false);
2896 if (haveNull)
2898 makeBoolConst(false, true));
2899 /* If all the inputs are TRUE, result is TRUE */
2900 if (newargs == NIL)
2901 return makeBoolConst(true, false);
2902
2903 /*
2904 * If only one nonconst-or-NULL input, it's the
2905 * result
2906 */
2907 if (list_length(newargs) == 1)
2908 return (Node *) linitial(newargs);
2909 /* Else we still need an AND node */
2910 return (Node *) make_andclause(newargs);
2911 }
2912 case NOT_EXPR:
2913 {
2914 Node *arg;
2915
2916 Assert(list_length(expr->args) == 1);
2918 context);
2919
2920 /*
2921 * Use negate_clause() to see if we can simplify
2922 * away the NOT.
2923 */
2924 return negate_clause(arg);
2925 }
2926 default:
2927 elog(ERROR, "unrecognized boolop: %d",
2928 (int) expr->boolop);
2929 break;
2930 }
2931 break;
2932 }
2933
2934 case T_JsonValueExpr:
2935 {
2936 JsonValueExpr *jve = (JsonValueExpr *) node;
2937 Node *raw_expr = (Node *) jve->raw_expr;
2938 Node *formatted_expr = (Node *) jve->formatted_expr;
2939
2940 /*
2941 * If we can fold formatted_expr to a constant, we can elide
2942 * the JsonValueExpr altogether. Otherwise we must process
2943 * raw_expr too. But JsonFormat is a flat node and requires
2944 * no simplification, only copying.
2945 */
2946 formatted_expr = eval_const_expressions_mutator(formatted_expr,
2947 context);
2948 if (formatted_expr && IsA(formatted_expr, Const))
2949 return formatted_expr;
2950
2951 raw_expr = eval_const_expressions_mutator(raw_expr, context);
2952
2953 return (Node *) makeJsonValueExpr((Expr *) raw_expr,
2954 (Expr *) formatted_expr,
2955 copyObject(jve->format));
2956 }
2957
2958 case T_SubPlan:
2960
2961 /*
2962 * Return a SubPlan unchanged --- too late to do anything with it.
2963 *
2964 * XXX should we ereport() here instead? Probably this routine
2965 * should never be invoked after SubPlan creation.
2966 */
2967 return node;
2968 case T_RelabelType:
2969 {
2970 RelabelType *relabel = (RelabelType *) node;
2971 Node *arg;
2972
2973 /* Simplify the input ... */
2975 context);
2976 /* ... and attach a new RelabelType node, if needed */
2977 return applyRelabelType(arg,
2978 relabel->resulttype,
2979 relabel->resulttypmod,
2980 relabel->resultcollid,
2981 relabel->relabelformat,
2982 relabel->location,
2983 true);
2984 }
2985 case T_CoerceViaIO:
2986 {
2987 CoerceViaIO *expr = (CoerceViaIO *) node;
2988 List *args;
2989 Oid outfunc;
2990 bool outtypisvarlena;
2991 Oid infunc;
2993 Expr *simple;
2995
2996 /* Make a List so we can use simplify_function */
2997 args = list_make1(expr->arg);
2998
2999 /*
3000 * CoerceViaIO represents calling the source type's output
3001 * function then the result type's input function. So, try to
3002 * simplify it as though it were a stack of two such function
3003 * calls. First we need to know what the functions are.
3004 *
3005 * Note that the coercion functions are assumed not to care
3006 * about input collation, so we just pass InvalidOid for that.
3007 */
3011 &infunc, &intypioparam);
3012
3013 simple = simplify_function(outfunc,
3014 CSTRINGOID, -1,
3015 InvalidOid,
3016 InvalidOid,
3017 &args,
3018 false,
3019 true,
3020 true,
3021 context);
3022 if (simple) /* successfully simplified output fn */
3023 {
3024 /*
3025 * Input functions may want 1 to 3 arguments. We always
3026 * supply all three, trusting that nothing downstream will
3027 * complain.
3028 */
3029 args = list_make3(simple,
3031 -1,
3032 InvalidOid,
3033 sizeof(Oid),
3035 false,
3036 true),
3038 -1,
3039 InvalidOid,
3040 sizeof(int32),
3041 Int32GetDatum(-1),
3042 false,
3043 true));
3044
3045 simple = simplify_function(infunc,
3046 expr->resulttype, -1,
3047 expr->resultcollid,
3048 InvalidOid,
3049 &args,
3050 false,
3051 false,
3052 true,
3053 context);
3054 if (simple) /* successfully simplified input fn */
3055 return (Node *) simple;
3056 }
3057
3058 /*
3059 * The expression cannot be simplified any further, so build
3060 * and return a replacement CoerceViaIO node using the
3061 * possibly-simplified argument.
3062 */
3064 newexpr->arg = (Expr *) linitial(args);
3065 newexpr->resulttype = expr->resulttype;
3066 newexpr->resultcollid = expr->resultcollid;
3067 newexpr->coerceformat = expr->coerceformat;
3068 newexpr->location = expr->location;
3069 return (Node *) newexpr;
3070 }
3071 case T_ArrayCoerceExpr:
3072 {
3075
3076 /*
3077 * Copy the node and const-simplify its arguments. We can't
3078 * use ece_generic_processing() here because we need to mess
3079 * with case_val only while processing the elemexpr.
3080 */
3081 memcpy(ac, node, sizeof(ArrayCoerceExpr));
3082 ac->arg = (Expr *)
3084 context);
3085
3086 /*
3087 * Set up for the CaseTestExpr node contained in the elemexpr.
3088 * We must prevent it from absorbing any outer CASE value.
3089 */
3090 save_case_val = context->case_val;
3091 context->case_val = NULL;
3092
3093 ac->elemexpr = (Expr *)
3095 context);
3096
3097 context->case_val = save_case_val;
3098
3099 /*
3100 * If constant argument and the per-element expression is
3101 * immutable, we can simplify the whole thing to a constant.
3102 * Exception: although contain_mutable_functions considers
3103 * CoerceToDomain immutable for historical reasons, let's not
3104 * do so here; this ensures coercion to an array-over-domain
3105 * does not apply the domain's constraints until runtime.
3106 */
3107 if (ac->arg && IsA(ac->arg, Const) &&
3108 ac->elemexpr && !IsA(ac->elemexpr, CoerceToDomain) &&
3109 !contain_mutable_functions((Node *) ac->elemexpr))
3110 return ece_evaluate_expr(ac);
3111
3112 return (Node *) ac;
3113 }
3114 case T_CollateExpr:
3115 {
3116 /*
3117 * We replace CollateExpr with RelabelType, so as to improve
3118 * uniformity of expression representation and thus simplify
3119 * comparison of expressions. Hence this looks very nearly
3120 * the same as the RelabelType case, and we can apply the same
3121 * optimizations to avoid unnecessary RelabelTypes.
3122 */
3123 CollateExpr *collate = (CollateExpr *) node;
3124 Node *arg;
3125
3126 /* Simplify the input ... */
3128 context);
3129 /* ... and attach a new RelabelType node, if needed */
3130 return applyRelabelType(arg,
3131 exprType(arg),
3132 exprTypmod(arg),
3133 collate->collOid,
3135 collate->location,
3136 true);
3137 }
3138 case T_CaseExpr:
3139 {
3140 /*----------
3141 * CASE expressions can be simplified if there are constant
3142 * condition clauses:
3143 * FALSE (or NULL): drop the alternative
3144 * TRUE: drop all remaining alternatives
3145 * If the first non-FALSE alternative is a constant TRUE,
3146 * we can simplify the entire CASE to that alternative's
3147 * expression. If there are no non-FALSE alternatives,
3148 * we simplify the entire CASE to the default result (ELSE).
3149 *
3150 * If we have a simple-form CASE with constant test
3151 * expression, we substitute the constant value for contained
3152 * CaseTestExpr placeholder nodes, so that we have the
3153 * opportunity to reduce constant test conditions. For
3154 * example this allows
3155 * CASE 0 WHEN 0 THEN 1 ELSE 1/0 END
3156 * to reduce to 1 rather than drawing a divide-by-0 error.
3157 * Note that when the test expression is constant, we don't
3158 * have to include it in the resulting CASE; for example
3159 * CASE 0 WHEN x THEN y ELSE z END
3160 * is transformed by the parser to
3161 * CASE 0 WHEN CaseTestExpr = x THEN y ELSE z END
3162 * which we can simplify to
3163 * CASE WHEN 0 = x THEN y ELSE z END
3164 * It is not necessary for the executor to evaluate the "arg"
3165 * expression when executing the CASE, since any contained
3166 * CaseTestExprs that might have referred to it will have been
3167 * replaced by the constant.
3168 *----------
3169 */
3170 CaseExpr *caseexpr = (CaseExpr *) node;
3173 Node *newarg;
3174 List *newargs;
3175 bool const_true_cond;
3176 Node *defresult = NULL;
3177 ListCell *arg;
3178
3179 /* Simplify the test expression, if any */
3181 context);
3182
3183 /* Set up for contained CaseTestExpr nodes */
3184 save_case_val = context->case_val;
3185 if (newarg && IsA(newarg, Const))
3186 {
3187 context->case_val = newarg;
3188 newarg = NULL; /* not needed anymore, see above */
3189 }
3190 else
3191 context->case_val = NULL;
3192
3193 /* Simplify the WHEN clauses */
3194 newargs = NIL;
3195 const_true_cond = false;
3196 foreach(arg, caseexpr->args)
3197 {
3199 Node *casecond;
3201
3202 /* Simplify this alternative's test condition */
3204 context);
3205
3206 /*
3207 * If the test condition is constant FALSE (or NULL), then
3208 * drop this WHEN clause completely, without processing
3209 * the result.
3210 */
3211 if (casecond && IsA(casecond, Const))
3212 {
3214
3215 if (const_input->constisnull ||
3216 !DatumGetBool(const_input->constvalue))
3217 continue; /* drop alternative with FALSE cond */
3218 /* Else it's constant TRUE */
3219 const_true_cond = true;
3220 }
3221
3222 /* Simplify this alternative's result value */
3224 context);
3225
3226 /* If non-constant test condition, emit a new WHEN node */
3227 if (!const_true_cond)
3228 {
3230
3231 newcasewhen->expr = (Expr *) casecond;
3232 newcasewhen->result = (Expr *) caseresult;
3233 newcasewhen->location = oldcasewhen->location;
3235 continue;
3236 }
3237
3238 /*
3239 * Found a TRUE condition, so none of the remaining
3240 * alternatives can be reached. We treat the result as
3241 * the default result.
3242 */
3243 defresult = caseresult;
3244 break;
3245 }
3246
3247 /* Simplify the default result, unless we replaced it above */
3248 if (!const_true_cond)
3249 defresult = eval_const_expressions_mutator((Node *) caseexpr->defresult,
3250 context);
3251
3252 context->case_val = save_case_val;
3253
3254 /*
3255 * If no non-FALSE alternatives, CASE reduces to the default
3256 * result
3257 */
3258 if (newargs == NIL)
3259 return defresult;
3260 /* Otherwise we need a new CASE node */
3262 newcase->casetype = caseexpr->casetype;
3263 newcase->casecollid = caseexpr->casecollid;
3264 newcase->arg = (Expr *) newarg;
3265 newcase->args = newargs;
3266 newcase->defresult = (Expr *) defresult;
3267 newcase->location = caseexpr->location;
3268 return (Node *) newcase;
3269 }
3270 case T_CaseTestExpr:
3271 {
3272 /*
3273 * If we know a constant test value for the current CASE
3274 * construct, substitute it for the placeholder. Else just
3275 * return the placeholder as-is.
3276 */
3277 if (context->case_val)
3278 return copyObject(context->case_val);
3279 else
3280 return copyObject(node);
3281 }
3282 case T_SubscriptingRef:
3283 case T_ArrayExpr:
3284 case T_RowExpr:
3285 case T_MinMaxExpr:
3286 {
3287 /*
3288 * Generic handling for node types whose own processing is
3289 * known to be immutable, and for which we need no smarts
3290 * beyond "simplify if all inputs are constants".
3291 *
3292 * Treating SubscriptingRef this way assumes that subscripting
3293 * fetch and assignment are both immutable. This constrains
3294 * type-specific subscripting implementations; maybe we should
3295 * relax it someday.
3296 *
3297 * Treating MinMaxExpr this way amounts to assuming that the
3298 * btree comparison function it calls is immutable; see the
3299 * reasoning in contain_mutable_functions_walker.
3300 */
3301
3302 /* Copy the node and const-simplify its arguments */
3303 node = ece_generic_processing(node);
3304 /* If all arguments are Consts, we can fold to a constant */
3305 if (ece_all_arguments_const(node))
3306 return ece_evaluate_expr(node);
3307 return node;
3308 }
3309 case T_CoalesceExpr:
3310 {
3313 List *newargs;
3314 ListCell *arg;
3315
3316 newargs = NIL;
3317 foreach(arg, coalesceexpr->args)
3318 {
3319 Node *e;
3320
3322 context);
3323
3324 /*
3325 * We can remove null constants from the list. For a
3326 * nonnullable expression, if it has not been preceded by
3327 * any non-null-constant expressions then it is the
3328 * result. Otherwise, it's the next argument, but we can
3329 * drop following arguments since they will never be
3330 * reached.
3331 */
3332 if (IsA(e, Const))
3333 {
3334 if (((Const *) e)->constisnull)
3335 continue; /* drop null constant */
3336 if (newargs == NIL)
3337 return e; /* first expr */
3339 break;
3340 }
3341 if (expr_is_nonnullable(context->root, (Expr *) e, false))
3342 {
3343 if (newargs == NIL)
3344 return e; /* first expr */
3346 break;
3347 }
3348
3350 }
3351
3352 /*
3353 * If all the arguments were constant null, the result is just
3354 * null
3355 */
3356 if (newargs == NIL)
3357 return (Node *) makeNullConst(coalesceexpr->coalescetype,
3358 -1,
3359 coalesceexpr->coalescecollid);
3360
3361 /*
3362 * If there's exactly one surviving argument, we no longer
3363 * need COALESCE at all: the result is that argument
3364 */
3365 if (list_length(newargs) == 1)
3366 return (Node *) linitial(newargs);
3367
3369 newcoalesce->coalescetype = coalesceexpr->coalescetype;
3370 newcoalesce->coalescecollid = coalesceexpr->coalescecollid;
3371 newcoalesce->args = newargs;
3372 newcoalesce->location = coalesceexpr->location;
3373 return (Node *) newcoalesce;
3374 }
3375 case T_SQLValueFunction:
3376 {
3377 /*
3378 * All variants of SQLValueFunction are stable, so if we are
3379 * estimating the expression's value, we should evaluate the
3380 * current function value. Otherwise just copy.
3381 */
3382 SQLValueFunction *svf = (SQLValueFunction *) node;
3383
3384 if (context->estimate)
3385 return (Node *) evaluate_expr((Expr *) svf,
3386 svf->type,
3387 svf->typmod,
3388 InvalidOid);
3389 else
3390 return copyObject((Node *) svf);
3391 }
3392 case T_FieldSelect:
3393 {
3394 /*
3395 * We can optimize field selection from a whole-row Var into a
3396 * simple Var. (This case won't be generated directly by the
3397 * parser, because ParseComplexProjection short-circuits it.
3398 * But it can arise while simplifying functions.) Also, we
3399 * can optimize field selection from a RowExpr construct, or
3400 * of course from a constant.
3401 *
3402 * However, replacing a whole-row Var in this way has a
3403 * pitfall: if we've already built the rel targetlist for the
3404 * source relation, then the whole-row Var is scheduled to be
3405 * produced by the relation scan, but the simple Var probably
3406 * isn't, which will lead to a failure in setrefs.c. This is
3407 * not a problem when handling simple single-level queries, in
3408 * which expression simplification always happens first. It
3409 * is a risk for lateral references from subqueries, though.
3410 * To avoid such failures, don't optimize uplevel references.
3411 *
3412 * We must also check that the declared type of the field is
3413 * still the same as when the FieldSelect was created --- this
3414 * can change if someone did ALTER COLUMN TYPE on the rowtype.
3415 * If it isn't, we skip the optimization; the case will
3416 * probably fail at runtime, but that's not our problem here.
3417 */
3418 FieldSelect *fselect = (FieldSelect *) node;
3420 Node *arg;
3421
3423 context);
3424 if (arg && IsA(arg, Var) &&
3425 ((Var *) arg)->varattno == InvalidAttrNumber &&
3426 ((Var *) arg)->varlevelsup == 0)
3427 {
3428 if (rowtype_field_matches(((Var *) arg)->vartype,
3429 fselect->fieldnum,
3430 fselect->resulttype,
3431 fselect->resulttypmod,
3432 fselect->resultcollid))
3433 {
3434 Var *newvar;
3435
3436 newvar = makeVar(((Var *) arg)->varno,
3437 fselect->fieldnum,
3438 fselect->resulttype,
3439 fselect->resulttypmod,
3440 fselect->resultcollid,
3441 ((Var *) arg)->varlevelsup);
3442 /* New Var has same OLD/NEW returning as old one */
3443 newvar->varreturningtype = ((Var *) arg)->varreturningtype;
3444 /* New Var is nullable by same rels as the old one */
3445 newvar->varnullingrels = ((Var *) arg)->varnullingrels;
3446 return (Node *) newvar;
3447 }
3448 }
3449 if (arg && IsA(arg, RowExpr))
3450 {
3451 RowExpr *rowexpr = (RowExpr *) arg;
3452
3453 if (fselect->fieldnum > 0 &&
3454 fselect->fieldnum <= list_length(rowexpr->args))
3455 {
3456 Node *fld = (Node *) list_nth(rowexpr->args,
3457 fselect->fieldnum - 1);
3458
3459 if (rowtype_field_matches(rowexpr->row_typeid,
3460 fselect->fieldnum,
3461 fselect->resulttype,
3462 fselect->resulttypmod,
3463 fselect->resultcollid) &&
3464 fselect->resulttype == exprType(fld) &&
3465 fselect->resulttypmod == exprTypmod(fld) &&
3466 fselect->resultcollid == exprCollation(fld))
3467 return fld;
3468 }
3469 }
3471 newfselect->arg = (Expr *) arg;
3472 newfselect->fieldnum = fselect->fieldnum;
3473 newfselect->resulttype = fselect->resulttype;
3474 newfselect->resulttypmod = fselect->resulttypmod;
3475 newfselect->resultcollid = fselect->resultcollid;
3476 if (arg && IsA(arg, Const))
3477 {
3478 Const *con = (Const *) arg;
3479
3481 newfselect->fieldnum,
3482 newfselect->resulttype,
3483 newfselect->resulttypmod,
3484 newfselect->resultcollid))
3486 }
3487 return (Node *) newfselect;
3488 }
3489 case T_NullTest:
3490 {
3491 NullTest *ntest = (NullTest *) node;
3493 Node *arg;
3494
3496 context);
3497 if (ntest->argisrow && arg && IsA(arg, RowExpr))
3498 {
3499 /*
3500 * We break ROW(...) IS [NOT] NULL into separate tests on
3501 * its component fields. This form is usually more
3502 * efficient to evaluate, as well as being more amenable
3503 * to optimization.
3504 */
3505 RowExpr *rarg = (RowExpr *) arg;
3506 List *newargs = NIL;
3507 ListCell *l;
3508
3509 foreach(l, rarg->args)
3510 {
3511 Node *relem = (Node *) lfirst(l);
3512
3513 /*
3514 * A constant field refutes the whole NullTest if it's
3515 * of the wrong nullness; else we can discard it.
3516 */
3517 if (relem && IsA(relem, Const))
3518 {
3519 Const *carg = (Const *) relem;
3520
3521 if (carg->constisnull ?
3522 (ntest->nulltesttype == IS_NOT_NULL) :
3523 (ntest->nulltesttype == IS_NULL))
3524 return makeBoolConst(false, false);
3525 continue;
3526 }
3527
3528 /*
3529 * A proven non-nullable field refutes the whole
3530 * NullTest if the test is IS NULL; else we can
3531 * discard it.
3532 */
3533 if (relem &&
3534 expr_is_nonnullable(context->root, (Expr *) relem,
3535 false))
3536 {
3537 if (ntest->nulltesttype == IS_NULL)
3538 return makeBoolConst(false, false);
3539 continue;
3540 }
3541
3542 /*
3543 * Else, make a scalar (argisrow == false) NullTest
3544 * for this field. Scalar semantics are required
3545 * because IS [NOT] NULL doesn't recurse; see comments
3546 * in ExecEvalRowNullInt().
3547 */
3549 newntest->arg = (Expr *) relem;
3550 newntest->nulltesttype = ntest->nulltesttype;
3551 newntest->argisrow = false;
3552 newntest->location = ntest->location;
3554 }
3555 /* If all the inputs were constants, result is TRUE */
3556 if (newargs == NIL)
3557 return makeBoolConst(true, false);
3558 /* If only one nonconst input, it's the result */
3559 if (list_length(newargs) == 1)
3560 return (Node *) linitial(newargs);
3561 /* Else we need an AND node */
3562 return (Node *) make_andclause(newargs);
3563 }
3564 if (!ntest->argisrow && arg && IsA(arg, Const))
3565 {
3566 Const *carg = (Const *) arg;
3567 bool result;
3568
3569 switch (ntest->nulltesttype)
3570 {
3571 case IS_NULL:
3572 result = carg->constisnull;
3573 break;
3574 case IS_NOT_NULL:
3575 result = !carg->constisnull;
3576 break;
3577 default:
3578 elog(ERROR, "unrecognized nulltesttype: %d",
3579 (int) ntest->nulltesttype);
3580 result = false; /* keep compiler quiet */
3581 break;
3582 }
3583
3584 return makeBoolConst(result, false);
3585 }
3586 if (!ntest->argisrow && arg &&
3587 expr_is_nonnullable(context->root, (Expr *) arg, false))
3588 {
3589 bool result;
3590
3591 switch (ntest->nulltesttype)
3592 {
3593 case IS_NULL:
3594 result = false;
3595 break;
3596 case IS_NOT_NULL:
3597 result = true;
3598 break;
3599 default:
3600 elog(ERROR, "unrecognized nulltesttype: %d",
3601 (int) ntest->nulltesttype);
3602 result = false; /* keep compiler quiet */
3603 break;
3604 }
3605
3606 return makeBoolConst(result, false);
3607 }
3608
3610 newntest->arg = (Expr *) arg;
3611 newntest->nulltesttype = ntest->nulltesttype;
3612 newntest->argisrow = ntest->argisrow;
3613 newntest->location = ntest->location;
3614 return (Node *) newntest;
3615 }
3616 case T_BooleanTest:
3617 {
3618 /*
3619 * This case could be folded into the generic handling used
3620 * for ArrayExpr etc. But because the simplification logic is
3621 * so trivial, applying evaluate_expr() to perform it would be
3622 * a heavy overhead. BooleanTest is probably common enough to
3623 * justify keeping this bespoke implementation.
3624 */
3625 BooleanTest *btest = (BooleanTest *) node;
3627 Node *arg;
3628
3630 context);
3631 if (arg && IsA(arg, Const))
3632 {
3633 Const *carg = (Const *) arg;
3634 bool result;
3635
3636 switch (btest->booltesttype)
3637 {
3638 case IS_TRUE:
3639 result = (!carg->constisnull &&
3640 DatumGetBool(carg->constvalue));
3641 break;
3642 case IS_NOT_TRUE:
3643 result = (carg->constisnull ||
3644 !DatumGetBool(carg->constvalue));
3645 break;
3646 case IS_FALSE:
3647 result = (!carg->constisnull &&
3648 !DatumGetBool(carg->constvalue));
3649 break;
3650 case IS_NOT_FALSE:
3651 result = (carg->constisnull ||
3652 DatumGetBool(carg->constvalue));
3653 break;
3654 case IS_UNKNOWN:
3655 result = carg->constisnull;
3656 break;
3657 case IS_NOT_UNKNOWN:
3658 result = !carg->constisnull;
3659 break;
3660 default:
3661 elog(ERROR, "unrecognized booltesttype: %d",
3662 (int) btest->booltesttype);
3663 result = false; /* keep compiler quiet */
3664 break;
3665 }
3666
3667 return makeBoolConst(result, false);
3668 }
3669
3671 newbtest->arg = (Expr *) arg;
3672 newbtest->booltesttype = btest->booltesttype;
3673 newbtest->location = btest->location;
3674 return (Node *) newbtest;
3675 }
3676 case T_CoerceToDomain:
3677 {
3678 /*
3679 * If the domain currently has no constraints, we replace the
3680 * CoerceToDomain node with a simple RelabelType, which is
3681 * both far faster to execute and more amenable to later
3682 * optimization. We must then mark the plan as needing to be
3683 * rebuilt if the domain's constraints change.
3684 *
3685 * Also, in estimation mode, always replace CoerceToDomain
3686 * nodes, effectively assuming that the coercion will succeed.
3687 */
3690 Node *arg;
3691
3693 context);
3694 if (context->estimate ||
3695 !DomainHasConstraints(cdomain->resulttype))
3696 {
3697 /* Record dependency, if this isn't estimation mode */
3698 if (context->root && !context->estimate)
3700 cdomain->resulttype);
3701
3702 /* Generate RelabelType to substitute for CoerceToDomain */
3703 return applyRelabelType(arg,
3704 cdomain->resulttype,
3705 cdomain->resulttypmod,
3706 cdomain->resultcollid,
3707 cdomain->coercionformat,
3708 cdomain->location,
3709 true);
3710 }
3711
3713 newcdomain->arg = (Expr *) arg;
3714 newcdomain->resulttype = cdomain->resulttype;
3715 newcdomain->resulttypmod = cdomain->resulttypmod;
3716 newcdomain->resultcollid = cdomain->resultcollid;
3717 newcdomain->coercionformat = cdomain->coercionformat;
3718 newcdomain->location = cdomain->location;
3719 return (Node *) newcdomain;
3720 }
3721 case T_PlaceHolderVar:
3722
3723 /*
3724 * In estimation mode, just strip the PlaceHolderVar node
3725 * altogether; this amounts to estimating that the contained value
3726 * won't be forced to null by an outer join. In regular mode we
3727 * just use the default behavior (ie, simplify the expression but
3728 * leave the PlaceHolderVar node intact).
3729 */
3730 if (context->estimate)
3731 {
3732 PlaceHolderVar *phv = (PlaceHolderVar *) node;
3733
3734 return eval_const_expressions_mutator((Node *) phv->phexpr,
3735 context);
3736 }
3737 break;
3739 {
3741 Node *arg;
3743
3745 context);
3746
3748 newcre->resulttype = cre->resulttype;
3749 newcre->convertformat = cre->convertformat;
3750 newcre->location = cre->location;
3751
3752 /*
3753 * In case of a nested ConvertRowtypeExpr, we can convert the
3754 * leaf row directly to the topmost row format without any
3755 * intermediate conversions. (This works because
3756 * ConvertRowtypeExpr is used only for child->parent
3757 * conversion in inheritance trees, which works by exact match
3758 * of column name, and a column absent in an intermediate
3759 * result can't be present in the final result.)
3760 *
3761 * No need to check more than one level deep, because the
3762 * above recursion will have flattened anything else.
3763 */
3764 if (arg != NULL && IsA(arg, ConvertRowtypeExpr))
3765 {
3767
3768 arg = (Node *) argcre->arg;
3769
3770 /*
3771 * Make sure an outer implicit conversion can't hide an
3772 * inner explicit one.
3773 */
3774 if (newcre->convertformat == COERCE_IMPLICIT_CAST)
3775 newcre->convertformat = argcre->convertformat;
3776 }
3777
3778 newcre->arg = (Expr *) arg;
3779
3780 if (arg != NULL && IsA(arg, Const))
3781 return ece_evaluate_expr((Node *) newcre);
3782 return (Node *) newcre;
3783 }
3784 default:
3785 break;
3786 }
3787
3788 /*
3789 * For any node type not handled above, copy the node unchanged but
3790 * const-simplify its subexpressions. This is the correct thing for node
3791 * types whose behavior might change between planning and execution, such
3792 * as CurrentOfExpr. It's also a safe default for new node types not
3793 * known to this routine.
3794 */
3795 return ece_generic_processing(node);
3796}

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, make_andclause(), 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 5284 of file clauses.c.

5286{
5287 EState *estate;
5288 ExprState *exprstate;
5289 MemoryContext oldcontext;
5291 bool const_is_null;
5293 bool resultTypByVal;
5294
5295 /*
5296 * To use the executor, we need an EState.
5297 */
5298 estate = CreateExecutorState();
5299
5300 /* We can use the estate's working context to avoid memory leaks. */
5301 oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
5302
5303 /* Make sure any opfuncids are filled in. */
5304 fix_opfuncids((Node *) expr);
5305
5306 /*
5307 * Prepare expr for execution. (Note: we can't use ExecPrepareExpr
5308 * because it'd result in recursively invoking eval_const_expressions.)
5309 */
5310 exprstate = ExecInitExpr(expr, NULL);
5311
5312 /*
5313 * And evaluate it.
5314 *
5315 * It is OK to use a default econtext because none of the ExecEvalExpr()
5316 * code used in this situation will use econtext. That might seem
5317 * fortuitous, but it's not so unreasonable --- a constant expression does
5318 * not depend on context, by definition, n'est ce pas?
5319 */
5321 GetPerTupleExprContext(estate),
5322 &const_is_null);
5323
5324 /* Get info needed about result datatype */
5326
5327 /* Get back to outer memory context */
5328 MemoryContextSwitchTo(oldcontext);
5329
5330 /*
5331 * Must copy result out of sub-context used by expression eval.
5332 *
5333 * Also, if it's varlena, forcibly detoast it. This protects us against
5334 * storing TOAST pointers into plans that might outlive the referenced
5335 * data. (makeConst would handle detoasting anyway, but it's worth a few
5336 * extra lines here so that we can do the copy and detoast in one step.)
5337 */
5338 if (!const_is_null)
5339 {
5340 if (resultTypLen == -1)
5342 else
5344 }
5345
5346 /* Release all the junk we just created */
5347 FreeExecutorState(estate);
5348
5349 /*
5350 * Make the constant result node.
5351 */
5352 return (Expr *) makeConst(result_type, result_typmod, result_collation,
5356}

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

4742{
4744 bool has_nonconst_input = false;
4745 bool has_null_input = false;
4746 ListCell *arg;
4748
4749 /*
4750 * Can't simplify if it returns a set.
4751 */
4752 if (funcform->proretset)
4753 return NULL;
4754
4755 /*
4756 * Can't simplify if it returns RECORD. The immediate problem is that it
4757 * will be needing an expected tupdesc which we can't supply here.
4758 *
4759 * In the case where it has OUT parameters, we could build an expected
4760 * tupdesc from those, but there may be other gotchas lurking. In
4761 * particular, if the function were to return NULL, we would produce a
4762 * null constant with no remaining indication of which concrete record
4763 * type it is. For now, seems best to leave the function call unreduced.
4764 */
4765 if (funcform->prorettype == RECORDOID)
4766 return NULL;
4767
4768 /*
4769 * Check for constant inputs and especially constant-NULL inputs.
4770 */
4771 foreach(arg, args)
4772 {
4773 if (IsA(lfirst(arg), Const))
4775 else
4776 has_nonconst_input = true;
4777 }
4778
4779 /*
4780 * If the function is strict and has a constant-NULL input, it will never
4781 * be called at all, so we can replace the call by a NULL constant, even
4782 * if there are other inputs that aren't constant, and even if the
4783 * function is not otherwise immutable.
4784 */
4785 if (funcform->proisstrict && has_null_input)
4786 return (Expr *) makeNullConst(result_type, result_typmod,
4788
4789 /*
4790 * Otherwise, can simplify only if all inputs are constants. (For a
4791 * non-strict function, constant NULL inputs are treated the same as
4792 * constant non-NULL inputs.)
4793 */
4795 return NULL;
4796
4797 /*
4798 * Ordinarily we are only allowed to simplify immutable functions. But for
4799 * purposes of estimation, we consider it okay to simplify functions that
4800 * are merely stable; the risk that the result might change from planning
4801 * time to execution time is worth taking in preference to not being able
4802 * to estimate the value at all.
4803 */
4804 if (funcform->provolatile == PROVOLATILE_IMMUTABLE)
4805 /* okay */ ;
4806 else if (context->estimate && funcform->provolatile == PROVOLATILE_STABLE)
4807 /* okay */ ;
4808 else
4809 return NULL;
4810
4811 /*
4812 * OK, looks like we can simplify this operator/function.
4813 *
4814 * Build a new FuncExpr node containing the already-simplified arguments.
4815 */
4817 newexpr->funcid = funcid;
4818 newexpr->funcresulttype = result_type;
4819 newexpr->funcretset = false;
4820 newexpr->funcvariadic = funcvariadic;
4821 newexpr->funcformat = COERCE_EXPLICIT_CALL; /* doesn't matter */
4822 newexpr->funccollid = result_collid; /* doesn't matter */
4823 newexpr->inputcollid = input_collid;
4824 newexpr->args = args;
4825 newexpr->location = -1;
4826
4827 return evaluate_expr((Expr *) newexpr, result_type, result_typmod,
4829}

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

4489{
4491 Oid *proargtypes = funcform->proargtypes.values;
4492 int pronargs = funcform->pronargs;
4493 bool has_named_args = false;
4494 ListCell *lc;
4495
4496 /*
4497 * If we are asked to match to OUT arguments, then use the proallargtypes
4498 * array (which includes those); otherwise use proargtypes (which
4499 * doesn't). Of course, if proallargtypes is null, we always use
4500 * proargtypes. (Fetching proallargtypes is annoyingly expensive
4501 * considering that we may have nothing to do here, but fortunately the
4502 * common case is include_out_arguments == false.)
4503 */
4505 {
4507 bool isNull;
4508
4511 &isNull);
4512 if (!isNull)
4513 {
4515
4516 pronargs = ARR_DIMS(arr)[0];
4517 if (ARR_NDIM(arr) != 1 ||
4518 pronargs < 0 ||
4519 ARR_HASNULL(arr) ||
4520 ARR_ELEMTYPE(arr) != OIDOID)
4521 elog(ERROR, "proallargtypes is not a 1-D Oid array or it contains nulls");
4522 Assert(pronargs >= funcform->pronargs);
4523 proargtypes = (Oid *) ARR_DATA_PTR(arr);
4524 }
4525 }
4526
4527 /* Do we have any named arguments? */
4528 foreach(lc, args)
4529 {
4530 Node *arg = (Node *) lfirst(lc);
4531
4532 if (IsA(arg, NamedArgExpr))
4533 {
4534 has_named_args = true;
4535 break;
4536 }
4537 }
4538
4539 /* If so, we must apply reorder_function_arguments */
4540 if (has_named_args)
4541 {
4543 /* Recheck argument types and add casts if needed */
4544 recheck_cast_function_args(args, result_type,
4546 func_tuple);
4547 }
4548 else if (list_length(args) < pronargs)
4549 {
4550 /* No named args, but we seem to be short some defaults */
4552 /* Recheck argument types and add casts if needed */
4553 recheck_cast_function_args(args, result_type,
4555 func_tuple);
4556 }
4557
4558 return args;
4559}

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

4346{
4347 /* since this function recurses, it could be driven to stack overflow */
4349
4350 switch (nodeTag(expr))
4351 {
4352 case T_Var:
4353 {
4354 if (root)
4355 return var_is_nonnullable(root, (Var *) expr, use_rel_info);
4356 }
4357 break;
4358 case T_Const:
4359 return !((Const *) expr)->constisnull;
4360 case T_CoalesceExpr:
4361 {
4362 /*
4363 * A CoalesceExpr returns NULL if and only if all its
4364 * arguments are NULL. Therefore, we can determine that a
4365 * CoalesceExpr cannot be NULL if at least one of its
4366 * arguments can be proven non-nullable.
4367 */
4369
4371 {
4373 return true;
4374 }
4375 }
4376 break;
4377 case T_MinMaxExpr:
4378 {
4379 /*
4380 * Like CoalesceExpr, a MinMaxExpr returns NULL only if all
4381 * its arguments evaluate to NULL.
4382 */
4383 MinMaxExpr *minmaxexpr = (MinMaxExpr *) expr;
4384
4386 {
4388 return true;
4389 }
4390 }
4391 break;
4392 case T_CaseExpr:
4393 {
4394 /*
4395 * A CASE expression is non-nullable if all branch results are
4396 * non-nullable. We must also verify that the default result
4397 * (ELSE) exists and is non-nullable.
4398 */
4399 CaseExpr *caseexpr = (CaseExpr *) expr;
4400
4401 /* The default result must be present and non-nullable */
4402 if (caseexpr->defresult == NULL ||
4404 return false;
4405
4406 /* All branch results must be non-nullable */
4408 {
4410 return false;
4411 }
4412
4413 return true;
4414 }
4415 break;
4416 case T_ArrayExpr:
4417 {
4418 /*
4419 * An ARRAY[] expression always returns a valid Array object,
4420 * even if it is empty (ARRAY[]) or contains NULLs
4421 * (ARRAY[NULL]). It never evaluates to a SQL NULL.
4422 */
4423 return true;
4424 }
4425 case T_NullTest:
4426 {
4427 /*
4428 * An IS NULL / IS NOT NULL expression always returns a
4429 * boolean value. It never returns SQL NULL.
4430 */
4431 return true;
4432 }
4433 case T_BooleanTest:
4434 {
4435 /*
4436 * A BooleanTest expression always evaluates to a boolean
4437 * value. It never returns SQL NULL.
4438 */
4439 return true;
4440 }
4441 case T_DistinctExpr:
4442 {
4443 /*
4444 * IS DISTINCT FROM never returns NULL, effectively acting as
4445 * though NULL were a normal data value.
4446 */
4447 return true;
4448 }
4449 case T_RelabelType:
4450 {
4451 /*
4452 * RelabelType does not change the nullability of the data.
4453 * The result is non-nullable if and only if the argument is
4454 * non-nullable.
4455 */
4456 return expr_is_nonnullable(root, ((RelabelType *) expr)->arg,
4457 use_rel_info);
4458 }
4459 default:
4460 break;
4461 }
4462
4463 return false;
4464}

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

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

4663{
4664 List *defaults;
4666 char *str;
4667
4671 defaults = castNode(List, stringToNode(str));
4672 pfree(str);
4673 return defaults;
4674}

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:2008
NullTestType nulltesttype
Definition primnodes.h:1984
Expr * arg
Definition primnodes.h:1983

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 */
1550 /* FALL THRU */
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
static bool is_strict_saop(ScalarArrayOpExpr *expr, bool falseOK)
Definition clauses.c:2038
@ ANY_SUBLINK
Definition primnodes.h:1031
@ ROWCOMPARE_SUBLINK
Definition primnodes.h:1032
Node * testexpr
Definition primnodes.h:1099
SubLinkType subLinkType
Definition primnodes.h:1097

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, 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 */
1808 /* FALL THRU */
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, 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 4863 of file clauses.c.

4868{
4870 char *src;
4871 Datum tmp;
4872 bool isNull;
4875 inline_error_callback_arg callback_arg;
4877 FuncExpr *fexpr;
4879 TupleDesc rettupdesc;
4880 ParseState *pstate;
4884 Node *newexpr;
4885 int *usecounts;
4886 ListCell *arg;
4887 int i;
4888
4889 /*
4890 * Forget it if the function is not SQL-language or has other showstopper
4891 * properties. (The prokind and nargs checks are just paranoia.)
4892 */
4893 if (funcform->prolang != SQLlanguageId ||
4894 funcform->prokind != PROKIND_FUNCTION ||
4895 funcform->prosecdef ||
4896 funcform->proretset ||
4897 funcform->prorettype == RECORDOID ||
4899 funcform->pronargs != list_length(args))
4900 return NULL;
4901
4902 /* Check for recursive function, and give up trying to expand if so */
4903 if (list_member_oid(context->active_fns, funcid))
4904 return NULL;
4905
4906 /* Check permission to call function (fail later, if not) */
4908 return NULL;
4909
4910 /* Check whether a plugin wants to hook function entry/exit */
4911 if (FmgrHookIsNeeded(funcid))
4912 return NULL;
4913
4914 /*
4915 * Make a temporary memory context, so that we don't leak all the stuff
4916 * that parsing might create.
4917 */
4919 "inline_function",
4922
4923 /*
4924 * We need a dummy FuncExpr node containing the already-simplified
4925 * arguments. (In some cases we don't really need it, but building it is
4926 * cheap enough that it's not worth contortions to avoid.)
4927 */
4929 fexpr->funcid = funcid;
4930 fexpr->funcresulttype = result_type;
4931 fexpr->funcretset = false;
4932 fexpr->funcvariadic = funcvariadic;
4933 fexpr->funcformat = COERCE_EXPLICIT_CALL; /* doesn't matter */
4934 fexpr->funccollid = result_collid; /* doesn't matter */
4935 fexpr->inputcollid = input_collid;
4936 fexpr->args = args;
4937 fexpr->location = -1;
4938
4939 /* Fetch the function body */
4941 src = TextDatumGetCString(tmp);
4942
4943 /*
4944 * Setup error traceback support for ereport(). This is so that we can
4945 * finger the function that bad information came from.
4946 */
4947 callback_arg.proname = NameStr(funcform->proname);
4948 callback_arg.prosrc = src;
4949
4951 sqlerrcontext.arg = &callback_arg;
4954
4955 /* If we have prosqlbody, pay attention to that not prosrc */
4957 func_tuple,
4959 &isNull);
4960 if (!isNull)
4961 {
4962 Node *n;
4963 List *query_list;
4964
4966 if (IsA(n, List))
4967 query_list = linitial_node(List, castNode(List, n));
4968 else
4969 query_list = list_make1(n);
4970 if (list_length(query_list) != 1)
4971 goto fail;
4972 querytree = linitial(query_list);
4973
4974 /*
4975 * Because we'll insist below that the querytree have an empty rtable
4976 * and no sublinks, it cannot have any relation references that need
4977 * to be locked or rewritten. So we can omit those steps.
4978 */
4979 }
4980 else
4981 {
4982 /* Set up to handle parameters while parsing the function body. */
4984 (Node *) fexpr,
4985 input_collid);
4986
4987 /*
4988 * We just do parsing and parse analysis, not rewriting, because
4989 * rewriting will not affect table-free-SELECT-only queries, which is
4990 * all that we care about. Also, we can punt as soon as we detect
4991 * more than one command in the function body.
4992 */
4995 goto fail;
4996
4997 pstate = make_parsestate(NULL);
4998 pstate->p_sourcetext = src;
4999 sql_fn_parser_setup(pstate, pinfo);
5000
5002
5003 free_parsestate(pstate);
5004 }
5005
5006 /*
5007 * The single command must be a simple "SELECT expression".
5008 *
5009 * Note: if you change the tests involved in this, see also plpgsql's
5010 * exec_simple_check_plan(). That generally needs to have the same idea
5011 * of what's a "simple expression", so that inlining a function that
5012 * previously wasn't inlined won't change plpgsql's conclusion.
5013 */
5014 if (!IsA(querytree, Query) ||
5015 querytree->commandType != CMD_SELECT ||
5016 querytree->hasAggs ||
5017 querytree->hasWindowFuncs ||
5018 querytree->hasTargetSRFs ||
5019 querytree->hasSubLinks ||
5020 querytree->cteList ||
5021 querytree->rtable ||
5022 querytree->jointree->fromlist ||
5023 querytree->jointree->quals ||
5024 querytree->groupClause ||
5025 querytree->groupingSets ||
5026 querytree->havingQual ||
5027 querytree->windowClause ||
5028 querytree->distinctClause ||
5029 querytree->sortClause ||
5030 querytree->limitOffset ||
5031 querytree->limitCount ||
5032 querytree->setOperations ||
5033 list_length(querytree->targetList) != 1)
5034 goto fail;
5035
5036 /* If the function result is composite, resolve it */
5038 NULL,
5039 &rettupdesc);
5040
5041 /*
5042 * Make sure the function (still) returns what it's declared to. This
5043 * will raise an error if wrong, but that's okay since the function would
5044 * fail at runtime anyway. Note that check_sql_fn_retval will also insert
5045 * a coercion if needed to make the tlist expression match the declared
5046 * type of the function.
5047 *
5048 * Note: we do not try this until we have verified that no rewriting was
5049 * needed; that's probably not important, but let's be careful.
5050 */
5053 result_type, rettupdesc,
5054 funcform->prokind,
5055 false))
5056 goto fail; /* reject whole-tuple-result cases */
5057
5058 /*
5059 * Given the tests above, check_sql_fn_retval shouldn't have decided to
5060 * inject a projection step, but let's just make sure.
5061 */
5063 goto fail;
5064
5065 /* Now we can grab the tlist expression */
5066 newexpr = (Node *) ((TargetEntry *) linitial(querytree->targetList))->expr;
5067
5068 /*
5069 * If the SQL function returns VOID, we can only inline it if it is a
5070 * SELECT of an expression returning VOID (ie, it's just a redirection to
5071 * another VOID-returning function). In all non-VOID-returning cases,
5072 * check_sql_fn_retval should ensure that newexpr returns the function's
5073 * declared result type, so this test shouldn't fail otherwise; but we may
5074 * as well cope gracefully if it does.
5075 */
5076 if (exprType(newexpr) != result_type)
5077 goto fail;
5078
5079 /*
5080 * Additional validity checks on the expression. It mustn't be more
5081 * volatile than the surrounding function (this is to avoid breaking hacks
5082 * that involve pretending a function is immutable when it really ain't).
5083 * If the surrounding function is declared strict, then the expression
5084 * must contain only strict constructs and must use all of the function
5085 * parameters (this is overkill, but an exact analysis is hard).
5086 */
5087 if (funcform->provolatile == PROVOLATILE_IMMUTABLE &&
5089 goto fail;
5090 else if (funcform->provolatile == PROVOLATILE_STABLE &&
5092 goto fail;
5093
5094 if (funcform->proisstrict &&
5096 goto fail;
5097
5098 /*
5099 * If any parameter expression contains a context-dependent node, we can't
5100 * inline, for fear of putting such a node into the wrong context.
5101 */
5103 goto fail;
5104
5105 /*
5106 * We may be able to do it; there are still checks on parameter usage to
5107 * make, but those are most easily done in combination with the actual
5108 * substitution of the inputs. So start building expression with inputs
5109 * substituted.
5110 */
5111 usecounts = (int *) palloc0(funcform->pronargs * sizeof(int));
5113 args, usecounts);
5114
5115 /* Now check for parameter usage */
5116 i = 0;
5117 foreach(arg, args)
5118 {
5119 Node *param = lfirst(arg);
5120
5121 if (usecounts[i] == 0)
5122 {
5123 /* Param not used at all: uncool if func is strict */
5124 if (funcform->proisstrict)
5125 goto fail;
5126 }
5127 else if (usecounts[i] != 1)
5128 {
5129 /* Param used multiple times: uncool if expensive or volatile */
5131
5132 /*
5133 * We define "expensive" as "contains any subplan or more than 10
5134 * operators". Note that the subplan search has to be done
5135 * explicitly, since cost_qual_eval() will barf on unplanned
5136 * subselects.
5137 */
5138 if (contain_subplans(param))
5139 goto fail;
5141 if (eval_cost.startup + eval_cost.per_tuple >
5142 10 * cpu_operator_cost)
5143 goto fail;
5144
5145 /*
5146 * Check volatility last since this is more expensive than the
5147 * above tests
5148 */
5149 if (contain_volatile_functions(param))
5150 goto fail;
5151 }
5152 i++;
5153 }
5154
5155 /*
5156 * Whew --- we can make the substitution. Copy the modified expression
5157 * out of the temporary memory context, and clean up.
5158 */
5160
5162
5164
5165 /*
5166 * If the result is of a collatable type, force the result to expose the
5167 * correct collation. In most cases this does not matter, but it's
5168 * possible that the function result is used directly as a sort key or in
5169 * other places where we expect exprCollation() to tell the truth.
5170 */
5172 {
5174
5176 {
5178
5179 newnode->arg = (Expr *) newexpr;
5180 newnode->collOid = result_collid;
5181 newnode->location = -1;
5182
5183 newexpr = (Node *) newnode;
5184 }
5185 }
5186
5187 /*
5188 * Since there is now no trace of the function in the plan tree, we must
5189 * explicitly record the plan's dependency on the function.
5190 */
5191 if (context->root)
5192 record_plan_function_dependency(context->root, funcid);
5193
5194 /*
5195 * Recursively try to simplify the modified expression. Here we must add
5196 * the current function to the context list of active functions.
5197 */
5198 context->active_fns = lappend_oid(context->active_fns, funcid);
5200 context->active_fns = list_delete_last(context->active_fns);
5201
5203
5204 return (Expr *) newexpr;
5205
5206 /* Here if func is not inlinable: release temp memory and return NULL */
5207fail:
5211
5212 return NULL;
5213}

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

5377{
5378 RangeTblFunction *rtfunc;
5379 FuncExpr *fexpr;
5380 Oid func_oid;
5385 Datum tmp;
5386 char *src;
5387 inline_error_callback_arg callback_arg;
5389 Query *querytree = NULL;
5390
5391 Assert(rte->rtekind == RTE_FUNCTION);
5392
5393 /*
5394 * Guard against infinite recursion during expansion by checking for stack
5395 * overflow. (There's no need to do more.)
5396 */
5398
5399 /* Fail if the RTE has ORDINALITY - we don't implement that here. */
5400 if (rte->funcordinality)
5401 return NULL;
5402
5403 /* Fail if RTE isn't a single, simple FuncExpr */
5404 if (list_length(rte->functions) != 1)
5405 return NULL;
5406 rtfunc = (RangeTblFunction *) linitial(rte->functions);
5407
5408 if (!IsA(rtfunc->funcexpr, FuncExpr))
5409 return NULL;
5410 fexpr = (FuncExpr *) rtfunc->funcexpr;
5411
5412 func_oid = fexpr->funcid;
5413
5414 /*
5415 * Refuse to inline if the arguments contain any volatile functions or
5416 * sub-selects. Volatile functions are rejected because inlining may
5417 * result in the arguments being evaluated multiple times, risking a
5418 * change in behavior. Sub-selects are rejected partly for implementation
5419 * reasons (pushing them down another level might change their behavior)
5420 * and partly because they're likely to be expensive and so multiple
5421 * evaluation would be bad.
5422 */
5423 if (contain_volatile_functions((Node *) fexpr->args) ||
5424 contain_subplans((Node *) fexpr->args))
5425 return NULL;
5426
5427 /* Check permission to call function (fail later, if not) */
5429 return NULL;
5430
5431 /* Check whether a plugin wants to hook function entry/exit */
5433 return NULL;
5434
5435 /*
5436 * OK, let's take a look at the function's pg_proc entry.
5437 */
5440 elog(ERROR, "cache lookup failed for function %u", func_oid);
5442
5443 /*
5444 * If the function SETs any configuration parameters, inlining would cause
5445 * us to miss making those changes.
5446 */
5448 {
5450 return NULL;
5451 }
5452
5453 /*
5454 * Make a temporary memory context, so that we don't leak all the stuff
5455 * that parsing and rewriting might create. If we succeed, we'll copy
5456 * just the finished query tree back up to the caller's context.
5457 */
5459 "inline_function_in_from",
5462
5463 /* Fetch the function body */
5465 src = TextDatumGetCString(tmp);
5466
5467 /*
5468 * If the function has an attached support function that can handle
5469 * SupportRequestInlineInFrom, then attempt to inline with that.
5470 */
5471 if (funcform->prosupport)
5472 {
5474
5476 req.root = root;
5477 req.rtfunc = rtfunc;
5478 req.proc = func_tuple;
5479
5480 querytree = (Query *)
5482 PointerGetDatum(&req)));
5483 }
5484
5485 /*
5486 * Setup error traceback support for ereport(). This is so that we can
5487 * finger the function that bad information came from. We don't install
5488 * this while running the support function, since it'd be likely to do the
5489 * wrong thing: any parse errors reported during that are very likely not
5490 * against the raw function source text.
5491 */
5492 callback_arg.proname = NameStr(funcform->proname);
5493 callback_arg.prosrc = src;
5494
5496 sqlerrcontext.arg = &callback_arg;
5499
5500 /*
5501 * If SupportRequestInlineInFrom didn't work, try our built-in inlining
5502 * mechanism.
5503 */
5504 if (!querytree)
5506 func_tuple, funcform, src);
5507
5508 if (!querytree)
5509 goto fail; /* no luck there either, fail */
5510
5511 /*
5512 * The result had better be a SELECT Query.
5513 */
5515 Assert(querytree->commandType == CMD_SELECT);
5516
5517 /*
5518 * Looks good --- substitute parameters into the query.
5519 */
5521 funcform->pronargs,
5522 fexpr->args);
5523
5524 /*
5525 * Copy the modified query out of the temporary memory context, and clean
5526 * up.
5527 */
5529
5531
5535
5536 /*
5537 * We don't have to fix collations here because the upper query is already
5538 * parsed, ie, the collations in the RTE are what count.
5539 */
5540
5541 /*
5542 * Since there is now no trace of the function in the plan tree, we must
5543 * explicitly record the plan's dependency on the function.
5544 */
5546
5547 /*
5548 * We must also notice if the inserted query adds a dependency on the
5549 * calling role due to RLS quals.
5550 */
5551 if (querytree->hasRowSecurity)
5552 root->glob->dependsOnRole = true;
5553
5554 return querytree;
5555
5556 /* Here if func is not inlinable: release temp memory and return NULL */
5557fail:
5562
5563 return NULL;
5564}

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

5586{
5587 Datum sqlbody;
5588 bool isNull;
5592 TupleDesc rettupdesc;
5593
5594 /*
5595 * The function must be declared to return a set, else inlining would
5596 * change the results if the contained SELECT didn't return exactly one
5597 * row.
5598 */
5599 if (!fexpr->funcretset)
5600 return NULL;
5601
5602 /*
5603 * Forget it if the function is not SQL-language or has other showstopper
5604 * properties. In particular it mustn't be declared STRICT, since we
5605 * couldn't enforce that. It also mustn't be VOLATILE, because that is
5606 * supposed to cause it to be executed with its own snapshot, rather than
5607 * sharing the snapshot of the calling query. We also disallow returning
5608 * SETOF VOID, because inlining would result in exposing the actual result
5609 * of the function's last SELECT, which should not happen in that case.
5610 * (Rechecking prokind, proretset, and pronargs is just paranoia.)
5611 */
5612 if (funcform->prolang != SQLlanguageId ||
5613 funcform->prokind != PROKIND_FUNCTION ||
5614 funcform->proisstrict ||
5615 funcform->provolatile == PROVOLATILE_VOLATILE ||
5616 funcform->prorettype == VOIDOID ||
5617 funcform->prosecdef ||
5618 !funcform->proretset ||
5619 list_length(fexpr->args) != funcform->pronargs)
5620 return NULL;
5621
5622 /* If we have prosqlbody, pay attention to that not prosrc */
5624 func_tuple,
5626 &isNull);
5627 if (!isNull)
5628 {
5629 Node *n;
5630
5632 if (IsA(n, List))
5634 else
5636 if (list_length(querytree_list) != 1)
5637 return NULL;
5639
5640 /* Acquire necessary locks, then apply rewriter. */
5641 AcquireRewriteLocks(querytree, true, false);
5643 if (list_length(querytree_list) != 1)
5644 return NULL;
5646 }
5647 else
5648 {
5651
5652 /*
5653 * Set up to handle parameters while parsing the function body. We
5654 * can use the FuncExpr just created as the input for
5655 * prepare_sql_fn_parse_info.
5656 */
5658 (Node *) fexpr,
5659 fexpr->inputcollid);
5660
5661 /*
5662 * Parse, analyze, and rewrite (unlike inline_function(), we can't
5663 * skip rewriting here). We can fail as soon as we find more than one
5664 * query, though.
5665 */
5668 return NULL;
5669
5671 src,
5673 pinfo, NULL);
5674 if (list_length(querytree_list) != 1)
5675 return NULL;
5677 }
5678
5679 /*
5680 * Also resolve the actual function result tupdesc, if composite. If we
5681 * have a coldeflist, believe that; otherwise use get_expr_result_type.
5682 * (This logic should match ExecInitFunctionScan.)
5683 */
5684 if (rtfunc->funccolnames != NIL)
5685 {
5687 rettupdesc = BuildDescFromLists(rtfunc->funccolnames,
5688 rtfunc->funccoltypes,
5689 rtfunc->funccoltypmods,
5690 rtfunc->funccolcollations);
5691 }
5692 else
5693 functypclass = get_expr_result_type((Node *) fexpr, NULL, &rettupdesc);
5694
5695 /*
5696 * The single command must be a plain SELECT.
5697 */
5698 if (!IsA(querytree, Query) ||
5699 querytree->commandType != CMD_SELECT)
5700 return NULL;
5701
5702 /*
5703 * Make sure the function (still) returns what it's declared to. This
5704 * will raise an error if wrong, but that's okay since the function would
5705 * fail at runtime anyway. Note that check_sql_fn_retval will also insert
5706 * coercions if needed to make the tlist expression(s) match the declared
5707 * type of the function. We also ask it to insert dummy NULL columns for
5708 * any dropped columns in rettupdesc, so that the elements of the modified
5709 * tlist match up to the attribute numbers.
5710 *
5711 * If the function returns a composite type, don't inline unless the check
5712 * shows it's returning a whole tuple result; otherwise what it's
5713 * returning is a single composite column which is not what we need.
5714 */
5716 fexpr->funcresulttype, rettupdesc,
5717 funcform->prokind,
5718 true) &&
5722 return NULL; /* reject not-whole-tuple-result cases */
5723
5724 /*
5725 * check_sql_fn_retval might've inserted a projection step, but that's
5726 * fine; just make sure we use the upper Query.
5727 */
5729
5730 return querytree;
5731}

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

5834{
5835 Node *arrayNode = NULL;
5837 Oid arraytype = get_array_type(coltype);
5838
5839 if (!OidIsValid(arraytype))
5840 return NULL;
5841
5842 /*
5843 * Assemble an array from the list of constants. It seems more profitable
5844 * to build a const array. But in the presence of other nodes, we don't
5845 * have a specific value here and must employ an ArrayExpr instead.
5846 */
5847 if (haveNonConst)
5848 {
5850
5851 /* array_collid will be set by parse_collate.c */
5852 arrayExpr->element_typeid = coltype;
5853 arrayExpr->array_typeid = arraytype;
5854 arrayExpr->multidims = false;
5855 arrayExpr->elements = exprs;
5856 arrayExpr->location = -1;
5857
5858 arrayNode = (Node *) arrayExpr;
5859 }
5860 else
5861 {
5862 int16 typlen;
5863 bool typbyval;
5864 char typalign;
5865 Datum *elems;
5866 bool *nulls;
5867 int i = 0;
5869 int dims[1] = {list_length(exprs)};
5870 int lbs[1] = {1};
5871
5872 get_typlenbyvalalign(coltype, &typlen, &typbyval, &typalign);
5873
5874 elems = palloc_array(Datum, list_length(exprs));
5875 nulls = palloc_array(bool, list_length(exprs));
5876 foreach_node(Const, value, exprs)
5877 {
5878 elems[i] = value->constvalue;
5879 nulls[i++] = value->constisnull;
5880 }
5881
5882 arrayConst = construct_md_array(elems, nulls, 1, dims, lbs,
5883 coltype, typlen, typbyval, typalign);
5886 false, false);
5887
5888 pfree(elems);
5889 pfree(nulls);
5890 list_free(exprs);
5891 }
5892
5893 /* Build the SAOP expression node */
5895 saopexpr->opno = oper;
5896 saopexpr->opfuncid = get_opcode(oper);
5897 saopexpr->hashfuncid = InvalidOid;
5898 saopexpr->negfuncid = InvalidOid;
5899 saopexpr->useOr = true;
5900 saopexpr->inputcollid = inputcollid;
5902 saopexpr->location = -1;
5903
5904 return saopexpr;
5905}

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:1124
List * paramIds
Definition primnodes.h:1100
bool parallel_safe
Definition primnodes.h:1117

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

5801{
5802 Bitmapset *result = NULL;
5803
5804 (void) pull_paramids_walker((Node *) expr, &result);
5805
5806 return result;
5807}

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

5811{
5812 if (node == NULL)
5813 return false;
5814 if (IsA(node, Param))
5815 {
5816 Param *param = (Param *) node;
5817
5818 *context = bms_add_member(*context, param->paramid);
5819 return false;
5820 }
5821 return expression_tree_walker(node, pull_paramids_walker, context);
5822}

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

4695{
4697 int nargs;
4700 Oid rettype;
4701 ListCell *lc;
4702
4703 if (list_length(args) > FUNC_MAX_ARGS)
4704 elog(ERROR, "too many function arguments");
4705 nargs = 0;
4706 foreach(lc, args)
4707 {
4708 actual_arg_types[nargs++] = exprType((Node *) lfirst(lc));
4709 }
4710 Assert(nargs == pronargs);
4714 nargs,
4715 funcform->prorettype,
4716 false);
4717 /* let's just check we got the same answer as the parser did ... */
4718 if (rettype != result_type)
4719 elog(ERROR, "function's resolved result type changed during planning");
4720
4721 /* perform any necessary typecasting of arguments */
4723}

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

4569{
4571 int nargsprovided = list_length(args);
4573 ListCell *lc;
4574 int i;
4575
4578 elog(ERROR, "too many function arguments");
4579 memset(argarray, 0, pronargs * sizeof(Node *));
4580
4581 /* Deconstruct the argument list into an array indexed by argnumber */
4582 i = 0;
4583 foreach(lc, args)
4584 {
4585 Node *arg = (Node *) lfirst(lc);
4586
4587 if (!IsA(arg, NamedArgExpr))
4588 {
4589 /* positional argument, assumed to precede all named args */
4590 Assert(argarray[i] == NULL);
4591 argarray[i++] = arg;
4592 }
4593 else
4594 {
4596
4597 Assert(na->argnumber >= 0 && na->argnumber < pronargs);
4598 Assert(argarray[na->argnumber] == NULL);
4599 argarray[na->argnumber] = (Node *) na->arg;
4600 }
4601 }
4602
4603 /*
4604 * Fetch default expressions, if needed, and insert into array at proper
4605 * locations (they aren't necessarily consecutive or all used)
4606 */
4607 if (nargsprovided < pronargs)
4608 {
4610
4611 i = pronargs - funcform->pronargdefaults;
4612 foreach(lc, defaults)
4613 {
4614 if (argarray[i] == NULL)
4615 argarray[i] = (Node *) lfirst(lc);
4616 i++;
4617 }
4618 }
4619
4620 /* Now reconstruct the args list in proper order */
4621 args = NIL;
4622 for (i = 0; i < pronargs; i++)
4623 {
4624 Assert(argarray[i] != NULL);
4625 args = lappend(args, argarray[i]);
4626 }
4627
4628 return args;
4629}

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

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

4238{
4240
4242 {
4244 Node *newnode;
4245
4246 /*
4247 * Build a SupportRequestSimplifyAggref node to pass to the support
4248 * function.
4249 */
4251 req.root = context->root;
4252 req.aggref = aggref;
4253
4255 PointerGetDatum(&req)));
4256
4257 /*
4258 * We expect the support function to return either a new Node or NULL
4259 * (when simplification isn't possible).
4260 */
4261 Assert(newnode != (Node *) aggref || newnode == NULL);
4262
4263 if (newnode != NULL)
4264 return newnode;
4265 }
4266
4267 return (Node *) aggref;
4268}

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

3971{
3972 List *newargs = NIL;
3974
3975 /* See comments in simplify_or_arguments */
3977 while (unprocessed_args)
3978 {
3980
3982
3983 /* flatten nested ANDs as per above comment */
3984 if (is_andclause(arg))
3985 {
3986 List *subargs = ((BoolExpr *) arg)->args;
3988
3990 /* perhaps-overly-tense code to avoid leaking old lists */
3992 continue;
3993 }
3994
3995 /* If it's not an AND, simplify it */
3997
3998 /*
3999 * It is unlikely but not impossible for simplification of a non-AND
4000 * clause to produce an AND. Recheck, but don't be too tense about it
4001 * since it's not a mainstream case. In particular we don't worry
4002 * about const-simplifying the input twice, nor about list leakage.
4003 */
4004 if (is_andclause(arg))
4005 {
4006 List *subargs = ((BoolExpr *) arg)->args;
4007
4009 continue;
4010 }
4011
4012 /*
4013 * OK, we have a const-simplified non-AND argument. Process it per
4014 * comments above.
4015 */
4016 if (IsA(arg, Const))
4017 {
4018 Const *const_input = (Const *) arg;
4019
4020 if (const_input->constisnull)
4021 *haveNull = true;
4022 else if (!DatumGetBool(const_input->constvalue))
4023 {
4024 *forceFalse = true;
4025
4026 /*
4027 * Once we detect a FALSE result we can just exit the loop
4028 * immediately. However, if we ever add a notion of
4029 * non-removable functions, we'd need to keep scanning.
4030 */
4031 return NIL;
4032 }
4033 /* otherwise, we can drop the constant-true input */
4034 continue;
4035 }
4036
4037 /* else emit the simplified arg into the result list */
4039 }
4040
4041 return newargs;
4042}

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

4063{
4064 Node *leftop;
4065 Node *rightop;
4066
4067 Assert(list_length(args) == 2);
4068 leftop = linitial(args);
4069 rightop = lsecond(args);
4070 if (leftop && IsA(leftop, Const))
4071 {
4072 Assert(!((Const *) leftop)->constisnull);
4073 if (opno == BooleanEqualOperator)
4074 {
4075 if (DatumGetBool(((Const *) leftop)->constvalue))
4076 return rightop; /* true = foo */
4077 else
4078 return negate_clause(rightop); /* false = foo */
4079 }
4080 else
4081 {
4082 if (DatumGetBool(((Const *) leftop)->constvalue))
4083 return negate_clause(rightop); /* true <> foo */
4084 else
4085 return rightop; /* false <> foo */
4086 }
4087 }
4088 if (rightop && IsA(rightop, Const))
4089 {
4091 if (opno == BooleanEqualOperator)
4092 {
4094 return leftop; /* foo = true */
4095 else
4096 return negate_clause(leftop); /* foo = false */
4097 }
4098 else
4099 {
4101 return negate_clause(leftop); /* foo <> true */
4102 else
4103 return leftop; /* foo <> false */
4104 }
4105 }
4106 return NULL;
4107}

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

4135{
4136 List *args = *args_p;
4139 Expr *newexpr;
4140
4141 /*
4142 * We have three strategies for simplification: execute the function to
4143 * deliver a constant result, use a transform function to generate a
4144 * substitute node tree, or expand in-line the body of the function
4145 * definition (which only works for simple SQL-language functions, but
4146 * that is a common case). Each case needs access to the function's
4147 * pg_proc tuple, so fetch it just once.
4148 *
4149 * Note: the allow_non_const flag suppresses both the second and third
4150 * strategies; so if !allow_non_const, simplify_function can only return a
4151 * Const or NULL. Argument-list rewriting happens anyway, though.
4152 */
4155 elog(ERROR, "cache lookup failed for function %u", funcid);
4157
4158 /*
4159 * Process the function arguments, unless the caller did it already.
4160 *
4161 * Here we must deal with named or defaulted arguments, and then
4162 * recursively apply eval_const_expressions to the whole argument list.
4163 */
4164 if (process_args)
4165 {
4166 args = expand_function_arguments(args, false, result_type, func_tuple);
4169 context);
4170 /* Argument processing done, give it back to the caller */
4171 *args_p = args;
4172 }
4173
4174 /* Now attempt simplification of the function call proper. */
4175
4176 newexpr = evaluate_function(funcid, result_type, result_typmod,
4178 args, funcvariadic,
4179 func_tuple, context);
4180
4181 if (!newexpr && allow_non_const && OidIsValid(func_form->prosupport))
4182 {
4183 /*
4184 * Build a SupportRequestSimplify node to pass to the support
4185 * function, pointing to a dummy FuncExpr node containing the
4186 * simplified arg list. We use this approach to present a uniform
4187 * interface to the support function regardless of how the target
4188 * function is actually being invoked.
4189 */
4192
4193 fexpr.xpr.type = T_FuncExpr;
4194 fexpr.funcid = funcid;
4195 fexpr.funcresulttype = result_type;
4196 fexpr.funcretset = func_form->proretset;
4197 fexpr.funcvariadic = funcvariadic;
4198 fexpr.funcformat = COERCE_EXPLICIT_CALL;
4199 fexpr.funccollid = result_collid;
4200 fexpr.inputcollid = input_collid;
4201 fexpr.args = args;
4202 fexpr.location = -1;
4203
4205 req.root = context->root;
4206 req.fcall = &fexpr;
4207
4208 newexpr = (Expr *)
4210 PointerGetDatum(&req)));
4211
4212 /* catch a possible API misunderstanding */
4213 Assert(newexpr != (Expr *) &fexpr);
4214 }
4215
4216 if (!newexpr && allow_non_const)
4217 newexpr = inline_function(funcid, result_type, result_collid,
4219 func_tuple, context);
4220
4222
4223 return newexpr;
4224}

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

3865{
3866 List *newargs = NIL;
3868
3869 /*
3870 * We want to ensure that any OR immediately beneath another OR gets
3871 * flattened into a single OR-list, so as to simplify later reasoning.
3872 *
3873 * To avoid stack overflow from recursion of eval_const_expressions, we
3874 * resort to some tenseness here: we keep a list of not-yet-processed
3875 * inputs, and handle flattening of nested ORs by prepending to the to-do
3876 * list instead of recursing. Now that the parser generates N-argument
3877 * ORs from simple lists, this complexity is probably less necessary than
3878 * it once was, but we might as well keep the logic.
3879 */
3881 while (unprocessed_args)
3882 {
3884
3886
3887 /* flatten nested ORs as per above comment */
3888 if (is_orclause(arg))
3889 {
3890 List *subargs = ((BoolExpr *) arg)->args;
3892
3894 /* perhaps-overly-tense code to avoid leaking old lists */
3896 continue;
3897 }
3898
3899 /* If it's not an OR, simplify it */
3901
3902 /*
3903 * It is unlikely but not impossible for simplification of a non-OR
3904 * clause to produce an OR. Recheck, but don't be too tense about it
3905 * since it's not a mainstream case. In particular we don't worry
3906 * about const-simplifying the input twice, nor about list leakage.
3907 */
3908 if (is_orclause(arg))
3909 {
3910 List *subargs = ((BoolExpr *) arg)->args;
3911
3913 continue;
3914 }
3915
3916 /*
3917 * OK, we have a const-simplified non-OR argument. Process it per
3918 * comments above.
3919 */
3920 if (IsA(arg, Const))
3921 {
3922 Const *const_input = (Const *) arg;
3923
3924 if (const_input->constisnull)
3925 *haveNull = true;
3926 else if (DatumGetBool(const_input->constvalue))
3927 {
3928 *forceTrue = true;
3929
3930 /*
3931 * Once we detect a TRUE result we can just exit the loop
3932 * immediately. However, if we ever add a notion of
3933 * non-removable functions, we'd need to keep scanning.
3934 */
3935 return NIL;
3936 }
3937 /* otherwise, we can drop the constant-false input */
3938 continue;
3939 }
3940
3941 /* else emit the simplified arg into the result list */
3943 }
3944
3945 return newargs;
3946}

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

5261{
5264
5265 /* If it's a syntax error, convert to internal syntax error report */
5267 if (syntaxerrposition > 0)
5268 {
5269 errposition(0);
5271 internalerrquery(callback_arg->prosrc);
5272 }
5273
5274 errcontext("SQL function \"%s\" during inlining", callback_arg->proname);
5275}

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

5221{
5223
5224 context.nargs = nargs;
5225 context.args = args;
5226 context.usecounts = usecounts;
5227
5228 return substitute_actual_parameters_mutator(expr, &context);
5229}

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

5757{
5758 Node *result;
5759
5760 if (node == NULL)
5761 return NULL;
5762 if (IsA(node, Query))
5763 {
5764 context->sublevels_up++;
5765 result = (Node *) query_tree_mutator((Query *) node,
5767 context,
5768 0);
5769 context->sublevels_up--;
5770 return result;
5771 }
5772 if (IsA(node, Param))
5773 {
5774 Param *param = (Param *) node;
5775
5776 if (param->paramkind == PARAM_EXTERN)
5777 {
5778 if (param->paramid <= 0 || param->paramid > context->nargs)
5779 elog(ERROR, "invalid paramid: %d", param->paramid);
5780
5781 /*
5782 * Since the parameter is being inserted into a subquery, we must
5783 * adjust levels.
5784 */
5785 result = copyObject(list_nth(context->args, param->paramid - 1));
5786 IncrementVarSublevelsUp(result, context->sublevels_up, 0);
5787 return result;
5788 }
5789 }
5790 return expression_tree_mutator(node,
5792 context);
5793}

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

5234{
5235 if (node == NULL)
5236 return NULL;
5237 if (IsA(node, Param))
5238 {
5239 Param *param = (Param *) node;
5240
5241 if (param->paramkind != PARAM_EXTERN)
5242 elog(ERROR, "unexpected paramkind: %d", (int) param->paramkind);
5243 if (param->paramid <= 0 || param->paramid > context->nargs)
5244 elog(ERROR, "invalid paramid: %d", param->paramid);
5245
5246 /* Count usage of parameter */
5247 context->usecounts[param->paramid - 1]++;
5248
5249 /* Select the appropriate actual arg and replace the Param with it */
5250 /* We don't need to copy at this time (it'll get done later) */
5251 return list_nth(context->args, param->paramid - 1);
5252 }
5254}

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

4281{
4282 Bitmapset *notnullattnums = NULL;
4283
4284 Assert(IsA(var, Var));
4285
4286 /* skip upper-level Vars */
4287 if (var->varlevelsup != 0)
4288 return false;
4289
4290 /* could the Var be nulled by any outer joins or grouping sets? */
4291 if (!bms_is_empty(var->varnullingrels))
4292 return false;
4293
4294 /* system columns cannot be NULL */
4295 if (var->varattno < 0)
4296 return true;
4297
4298 /*
4299 * Check if the Var is defined as NOT NULL. We retrieve the column NOT
4300 * NULL constraint information from the corresponding RelOptInfo if it is
4301 * available; otherwise, we search the hash table for this information.
4302 */
4303 if (use_rel_info)
4304 {
4305 RelOptInfo *rel = find_base_rel(root, var->varno);
4306
4307 notnullattnums = rel->notnullattnums;
4308 }
4309 else
4310 {
4312
4313 /*
4314 * We must skip inheritance parent tables, as some child tables may
4315 * have a NOT NULL constraint for a column while others may not. This
4316 * cannot happen with partitioned tables, though.
4317 */
4318 if (rte->inh && rte->relkind != RELKIND_PARTITIONED_TABLE)
4319 return false;
4320
4321 notnullattnums = find_relation_notnullatts(root, rte->relid);
4322 }
4323
4324 if (var->varattno > 0 &&
4325 bms_is_member(var->varattno, notnullattnums))
4326 return true;
4327
4328 return false;
4329}

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