1 /*-------------------------------------------------------------------------
4 * routines to manipulate qualification clauses
6 * Portions Copyright (c) 1996-2010, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
11 * src/backend/optimizer/util/clauses.c
14 * AUTHOR DATE MAJOR EVENT
15 * Andrew Yu Nov 3, 1994 clause.c and clauses.c combined
17 *-------------------------------------------------------------------------
22 #include "catalog/pg_aggregate.h"
23 #include "catalog/pg_language.h"
24 #include "catalog/pg_operator.h"
25 #include "catalog/pg_proc.h"
26 #include "catalog/pg_type.h"
27 #include "executor/executor.h"
28 #include "executor/functions.h"
29 #include "miscadmin.h"
30 #include "nodes/makefuncs.h"
31 #include "nodes/nodeFuncs.h"
32 #include "optimizer/clauses.h"
33 #include "optimizer/cost.h"
34 #include "optimizer/planmain.h"
35 #include "optimizer/prep.h"
36 #include "optimizer/var.h"
37 #include "parser/analyze.h"
38 #include "parser/parse_coerce.h"
39 #include "parser/parse_func.h"
40 #include "rewrite/rewriteManip.h"
41 #include "tcop/tcopprot.h"
42 #include "utils/acl.h"
43 #include "utils/builtins.h"
44 #include "utils/datum.h"
45 #include "utils/lsyscache.h"
46 #include "utils/memutils.h"
47 #include "utils/syscache.h"
48 #include "utils/typcache.h"
53 ParamListInfo boundParams;
58 } eval_const_expressions_context;
65 } substitute_actual_parameters_context;
72 } substitute_actual_srf_parameters_context;
78 } inline_error_callback_arg;
80 static bool contain_agg_clause_walker(Node *node, void *context);
81 static bool pull_agg_clause_walker(Node *node, List **context);
82 static bool count_agg_clauses_walker(Node *node, AggClauseCounts *counts);
83 static bool find_window_functions_walker(Node *node, WindowFuncLists *lists);
84 static bool expression_returns_set_rows_walker(Node *node, double *count);
85 static bool contain_subplans_walker(Node *node, void *context);
86 static bool contain_mutable_functions_walker(Node *node, void *context);
87 static bool contain_volatile_functions_walker(Node *node, void *context);
88 static bool contain_nonstrict_functions_walker(Node *node, void *context);
89 static Relids find_nonnullable_rels_walker(Node *node, bool top_level);
90 static List *find_nonnullable_vars_walker(Node *node, bool top_level);
91 static bool is_strict_saop(ScalarArrayOpExpr *expr, bool falseOK);
92 static bool set_coercionform_dontcare_walker(Node *node, void *context);
93 static Node *eval_const_expressions_mutator(Node *node,
94 eval_const_expressions_context *context);
95 static List *simplify_or_arguments(List *args,
96 eval_const_expressions_context *context,
97 bool *haveNull, bool *forceTrue);
98 static List *simplify_and_arguments(List *args,
99 eval_const_expressions_context *context,
100 bool *haveNull, bool *forceFalse);
101 static Node *simplify_boolean_equality(Oid opno, List *args);
102 static Expr *simplify_function(Oid funcid,
103 Oid result_type, int32 result_typmod, List **args,
106 eval_const_expressions_context *context);
107 static List *reorder_function_arguments(List *args, Oid result_type,
108 HeapTuple func_tuple,
109 eval_const_expressions_context *context);
110 static List *add_function_defaults(List *args, Oid result_type,
111 HeapTuple func_tuple,
112 eval_const_expressions_context *context);
113 static List *fetch_function_defaults(HeapTuple func_tuple);
114 static void recheck_cast_function_args(List *args, Oid result_type,
115 HeapTuple func_tuple);
116 static Expr *evaluate_function(Oid funcid,
117 Oid result_type, int32 result_typmod, List *args,
118 HeapTuple func_tuple,
119 eval_const_expressions_context *context);
120 static Expr *inline_function(Oid funcid, Oid result_type, List *args,
121 HeapTuple func_tuple,
122 eval_const_expressions_context *context);
123 static Node *substitute_actual_parameters(Node *expr, int nargs, List *args,
125 static Node *substitute_actual_parameters_mutator(Node *node,
126 substitute_actual_parameters_context *context);
127 static void sql_inline_error_callback(void *arg);
128 static Expr *evaluate_expr(Expr *expr, Oid result_type, int32 result_typmod);
129 static Query *substitute_actual_srf_parameters(Query *expr,
130 int nargs, List *args);
131 static Node *substitute_actual_srf_parameters_mutator(Node *node,
132 substitute_actual_srf_parameters_context *context);
133 static bool tlist_matches_coltypelist(List *tlist, List *coltypelist);
136 /*****************************************************************************
137 * OPERATOR clause functions
138 *****************************************************************************/
142 * Creates an operator clause given its operator info, left operand,
143 * and right operand (pass NULL to create single-operand clause).
146 make_opclause(Oid opno, Oid opresulttype, bool opretset,
147 Expr *leftop, Expr *rightop)
149 OpExpr *expr = makeNode(OpExpr);
152 expr->opfuncid = InvalidOid;
153 expr->opresulttype = opresulttype;
154 expr->opretset = opretset;
156 expr->args = list_make2(leftop, rightop);
158 expr->args = list_make1(leftop);
160 return (Expr *) expr;
166 * Returns the left operand of a clause of the form (op expr expr)
170 get_leftop(Expr *clause)
172 OpExpr *expr = (OpExpr *) clause;
174 if (expr->args != NIL)
175 return linitial(expr->args);
183 * Returns the right operand in a clause of the form (op expr expr).
184 * NB: result will be NULL if applied to a unary op clause.
187 get_rightop(Expr *clause)
189 OpExpr *expr = (OpExpr *) clause;
191 if (list_length(expr->args) >= 2)
192 return lsecond(expr->args);
197 /*****************************************************************************
198 * NOT clause functions
199 *****************************************************************************/
204 * Returns t iff this is a 'not' clause: (NOT expr).
207 not_clause(Node *clause)
209 return (clause != NULL &&
210 IsA(clause, BoolExpr) &&
211 ((BoolExpr *) clause)->boolop == NOT_EXPR);
217 * Create a 'not' clause given the expression to be negated.
220 make_notclause(Expr *notclause)
222 BoolExpr *expr = makeNode(BoolExpr);
224 expr->boolop = NOT_EXPR;
225 expr->args = list_make1(notclause);
227 return (Expr *) expr;
233 * Retrieve the clause within a 'not' clause
236 get_notclausearg(Expr *notclause)
238 return linitial(((BoolExpr *) notclause)->args);
241 /*****************************************************************************
242 * OR clause functions
243 *****************************************************************************/
248 * Returns t iff the clause is an 'or' clause: (OR { expr }).
251 or_clause(Node *clause)
253 return (clause != NULL &&
254 IsA(clause, BoolExpr) &&
255 ((BoolExpr *) clause)->boolop == OR_EXPR);
261 * Creates an 'or' clause given a list of its subclauses.
264 make_orclause(List *orclauses)
266 BoolExpr *expr = makeNode(BoolExpr);
268 expr->boolop = OR_EXPR;
269 expr->args = orclauses;
271 return (Expr *) expr;
274 /*****************************************************************************
275 * AND clause functions
276 *****************************************************************************/
282 * Returns t iff its argument is an 'and' clause: (AND { expr }).
285 and_clause(Node *clause)
287 return (clause != NULL &&
288 IsA(clause, BoolExpr) &&
289 ((BoolExpr *) clause)->boolop == AND_EXPR);
295 * Creates an 'and' clause given a list of its subclauses.
298 make_andclause(List *andclauses)
300 BoolExpr *expr = makeNode(BoolExpr);
302 expr->boolop = AND_EXPR;
303 expr->args = andclauses;
305 return (Expr *) expr;
311 * Variant of make_andclause for ANDing two qual conditions together.
312 * Qual conditions have the property that a NULL nodetree is interpreted
315 * NB: this makes no attempt to preserve AND/OR flatness; so it should not
316 * be used on a qual that has already been run through prepqual.c.
319 make_and_qual(Node *qual1, Node *qual2)
325 return (Node *) make_andclause(list_make2(qual1, qual2));
329 * Sometimes (such as in the input of ExecQual), we use lists of expression
330 * nodes with implicit AND semantics.
332 * These functions convert between an AND-semantics expression list and the
333 * ordinary representation of a boolean expression.
335 * Note that an empty list is considered equivalent to TRUE.
338 make_ands_explicit(List *andclauses)
340 if (andclauses == NIL)
341 return (Expr *) makeBoolConst(true, false);
342 else if (list_length(andclauses) == 1)
343 return (Expr *) linitial(andclauses);
345 return make_andclause(andclauses);
349 make_ands_implicit(Expr *clause)
352 * NB: because the parser sets the qual field to NULL in a query that has
353 * no WHERE clause, we must consider a NULL input clause as TRUE, even
354 * though one might more reasonably think it FALSE. Grumble. If this
355 * causes trouble, consider changing the parser's behavior.
358 return NIL; /* NULL -> NIL list == TRUE */
359 else if (and_clause((Node *) clause))
360 return ((BoolExpr *) clause)->args;
361 else if (IsA(clause, Const) &&
362 !((Const *) clause)->constisnull &&
363 DatumGetBool(((Const *) clause)->constvalue))
364 return NIL; /* constant TRUE input -> NIL list */
366 return list_make1(clause);
370 /*****************************************************************************
371 * Aggregate-function clause manipulation
372 *****************************************************************************/
376 * Recursively search for Aggref nodes within a clause.
378 * Returns true if any aggregate found.
380 * This does not descend into subqueries, and so should be used only after
381 * reduction of sublinks to subplans, or in contexts where it's known there
382 * are no subqueries. There mustn't be outer-aggregate references either.
384 * (If you want something like this but able to deal with subqueries,
385 * see rewriteManip.c's contain_aggs_of_level().)
388 contain_agg_clause(Node *clause)
390 return contain_agg_clause_walker(clause, NULL);
394 contain_agg_clause_walker(Node *node, void *context)
398 if (IsA(node, Aggref))
400 Assert(((Aggref *) node)->agglevelsup == 0);
401 return true; /* abort the tree traversal and return true */
403 Assert(!IsA(node, SubLink));
404 return expression_tree_walker(node, contain_agg_clause_walker, context);
409 * Recursively search for Aggref nodes within a clause.
411 * Returns a List of all Aggrefs found.
413 * This does not descend into subqueries, and so should be used only after
414 * reduction of sublinks to subplans, or in contexts where it's known there
415 * are no subqueries. There mustn't be outer-aggregate references either.
418 pull_agg_clause(Node *clause)
422 (void) pull_agg_clause_walker(clause, &result);
427 pull_agg_clause_walker(Node *node, List **context)
431 if (IsA(node, Aggref))
433 Assert(((Aggref *) node)->agglevelsup == 0);
434 *context = lappend(*context, node);
435 return false; /* no need to descend into arguments */
437 Assert(!IsA(node, SubLink));
438 return expression_tree_walker(node, pull_agg_clause_walker,
444 * Recursively count the Aggref nodes in an expression tree.
446 * Note: this also checks for nested aggregates, which are an error.
448 * We not only count the nodes, but attempt to estimate the total space
449 * needed for their transition state values if all are evaluated in parallel
450 * (as would be done in a HashAgg plan). See AggClauseCounts for the exact
451 * set of statistics returned.
453 * NOTE that the counts are ADDED to those already in *counts ... so the
454 * caller is responsible for zeroing the struct initially.
456 * This does not descend into subqueries, and so should be used only after
457 * reduction of sublinks to subplans, or in contexts where it's known there
458 * are no subqueries. There mustn't be outer-aggregate references either.
461 count_agg_clauses(Node *clause, AggClauseCounts *counts)
463 /* no setup needed */
464 count_agg_clauses_walker(clause, counts);
468 count_agg_clauses_walker(Node *node, AggClauseCounts *counts)
472 if (IsA(node, Aggref))
474 Aggref *aggref = (Aggref *) node;
478 Form_pg_aggregate aggform;
482 Assert(aggref->agglevelsup == 0);
484 if (aggref->aggorder != NIL || aggref->aggdistinct != NIL)
485 counts->numOrderedAggs++;
487 /* extract argument types (ignoring any ORDER BY expressions) */
488 inputTypes = (Oid *) palloc(sizeof(Oid) * list_length(aggref->args));
490 foreach(l, aggref->args)
492 TargetEntry *tle = (TargetEntry *) lfirst(l);
495 inputTypes[numArguments++] = exprType((Node *) tle->expr);
498 /* fetch aggregate transition datatype from pg_aggregate */
499 aggTuple = SearchSysCache1(AGGFNOID,
500 ObjectIdGetDatum(aggref->aggfnoid));
501 if (!HeapTupleIsValid(aggTuple))
502 elog(ERROR, "cache lookup failed for aggregate %u",
504 aggform = (Form_pg_aggregate) GETSTRUCT(aggTuple);
505 aggtranstype = aggform->aggtranstype;
506 ReleaseSysCache(aggTuple);
508 /* resolve actual type of transition state, if polymorphic */
509 if (IsPolymorphicType(aggtranstype))
511 /* have to fetch the agg's declared input types... */
512 Oid *declaredArgTypes;
515 (void) get_func_signature(aggref->aggfnoid,
516 &declaredArgTypes, &agg_nargs);
517 Assert(agg_nargs == numArguments);
518 aggtranstype = enforce_generic_type_consistency(inputTypes,
523 pfree(declaredArgTypes);
527 * If the transition type is pass-by-value then it doesn't add
528 * anything to the required size of the hashtable. If it is
529 * pass-by-reference then we have to add the estimated size of the
530 * value itself, plus palloc overhead.
532 if (!get_typbyval(aggtranstype))
534 int32 aggtranstypmod;
538 * If transition state is of same type as first input, assume it's
539 * the same typmod (same width) as well. This works for cases
540 * like MAX/MIN and is probably somewhat reasonable otherwise.
542 if (numArguments > 0 && aggtranstype == inputTypes[0])
543 aggtranstypmod = exprTypmod((Node *) linitial(aggref->args));
547 avgwidth = get_typavgwidth(aggtranstype, aggtranstypmod);
548 avgwidth = MAXALIGN(avgwidth);
550 counts->transitionSpace += avgwidth + 2 * sizeof(void *);
552 else if (aggtranstype == INTERNALOID)
555 * INTERNAL transition type is a special case: although INTERNAL
556 * is pass-by-value, it's almost certainly being used as a pointer
557 * to some large data structure. We assume usage of
558 * ALLOCSET_DEFAULT_INITSIZE, which is a good guess if the data is
559 * being kept in a private memory context, as is done by
560 * array_agg() for instance.
562 counts->transitionSpace += ALLOCSET_DEFAULT_INITSIZE;
566 * Complain if the aggregate's arguments contain any aggregates;
567 * nested agg functions are semantically nonsensical.
569 if (contain_agg_clause((Node *) aggref->args))
571 (errcode(ERRCODE_GROUPING_ERROR),
572 errmsg("aggregate function calls cannot be nested")));
575 * Having checked that, we need not recurse into the argument.
579 Assert(!IsA(node, SubLink));
580 return expression_tree_walker(node, count_agg_clauses_walker,
585 /*****************************************************************************
586 * Window-function clause manipulation
587 *****************************************************************************/
590 * contain_window_function
591 * Recursively search for WindowFunc nodes within a clause.
593 * Since window functions don't have level fields, but are hard-wired to
594 * be associated with the current query level, this is just the same as
595 * rewriteManip.c's function.
598 contain_window_function(Node *clause)
600 return checkExprHasWindowFuncs(clause);
604 * find_window_functions
605 * Locate all the WindowFunc nodes in an expression tree, and organize
606 * them by winref ID number.
608 * Caller must provide an upper bound on the winref IDs expected in the tree.
611 find_window_functions(Node *clause, Index maxWinRef)
613 WindowFuncLists *lists = palloc(sizeof(WindowFuncLists));
615 lists->numWindowFuncs = 0;
616 lists->maxWinRef = maxWinRef;
617 lists->windowFuncs = (List **) palloc0((maxWinRef + 1) * sizeof(List *));
618 (void) find_window_functions_walker(clause, lists);
623 find_window_functions_walker(Node *node, WindowFuncLists *lists)
627 if (IsA(node, WindowFunc))
629 WindowFunc *wfunc = (WindowFunc *) node;
631 /* winref is unsigned, so one-sided test is OK */
632 if (wfunc->winref > lists->maxWinRef)
633 elog(ERROR, "WindowFunc contains out-of-range winref %u",
635 lists->windowFuncs[wfunc->winref] =
636 lappend(lists->windowFuncs[wfunc->winref], wfunc);
637 lists->numWindowFuncs++;
640 * Complain if the window function's arguments contain window
643 if (contain_window_function((Node *) wfunc->args))
645 (errcode(ERRCODE_WINDOWING_ERROR),
646 errmsg("window function calls cannot be nested")));
649 * Having checked that, we need not recurse into the argument.
653 Assert(!IsA(node, SubLink));
654 return expression_tree_walker(node, find_window_functions_walker,
659 /*****************************************************************************
660 * Support for expressions returning sets
661 *****************************************************************************/
664 * expression_returns_set_rows
665 * Estimate the number of rows in a set result.
667 * We use the product of the rowcount estimates of all the functions in
668 * the given tree. The result is 1 if there are no set-returning functions.
670 * Note: keep this in sync with expression_returns_set() in nodes/nodeFuncs.c.
673 expression_returns_set_rows(Node *clause)
677 (void) expression_returns_set_rows_walker(clause, &result);
682 expression_returns_set_rows_walker(Node *node, double *count)
686 if (IsA(node, FuncExpr))
688 FuncExpr *expr = (FuncExpr *) node;
690 if (expr->funcretset)
691 *count *= get_func_rows(expr->funcid);
693 if (IsA(node, OpExpr))
695 OpExpr *expr = (OpExpr *) node;
700 *count *= get_func_rows(expr->opfuncid);
704 /* Avoid recursion for some cases that can't return a set */
705 if (IsA(node, Aggref))
707 if (IsA(node, WindowFunc))
709 if (IsA(node, DistinctExpr))
711 if (IsA(node, ScalarArrayOpExpr))
713 if (IsA(node, BoolExpr))
715 if (IsA(node, SubLink))
717 if (IsA(node, SubPlan))
719 if (IsA(node, AlternativeSubPlan))
721 if (IsA(node, ArrayExpr))
723 if (IsA(node, RowExpr))
725 if (IsA(node, RowCompareExpr))
727 if (IsA(node, CoalesceExpr))
729 if (IsA(node, MinMaxExpr))
731 if (IsA(node, XmlExpr))
733 if (IsA(node, NullIfExpr))
736 return expression_tree_walker(node, expression_returns_set_rows_walker,
741 /*****************************************************************************
742 * Subplan clause manipulation
743 *****************************************************************************/
747 * Recursively search for subplan nodes within a clause.
749 * If we see a SubLink node, we will return TRUE. This is only possible if
750 * the expression tree hasn't yet been transformed by subselect.c. We do not
751 * know whether the node will produce a true subplan or just an initplan,
752 * but we make the conservative assumption that it will be a subplan.
754 * Returns true if any subplan found.
757 contain_subplans(Node *clause)
759 return contain_subplans_walker(clause, NULL);
763 contain_subplans_walker(Node *node, void *context)
767 if (IsA(node, SubPlan) ||
768 IsA(node, AlternativeSubPlan) ||
770 return true; /* abort the tree traversal and return true */
771 return expression_tree_walker(node, contain_subplans_walker, context);
775 /*****************************************************************************
776 * Check clauses for mutable functions
777 *****************************************************************************/
780 * contain_mutable_functions
781 * Recursively search for mutable functions within a clause.
783 * Returns true if any mutable function (or operator implemented by a
784 * mutable function) is found. This test is needed so that we don't
785 * mistakenly think that something like "WHERE random() < 0.5" can be treated
786 * as a constant qualification.
788 * XXX we do not examine sub-selects to see if they contain uses of
789 * mutable functions. It's not real clear if that is correct or not...
792 contain_mutable_functions(Node *clause)
794 return contain_mutable_functions_walker(clause, NULL);
798 contain_mutable_functions_walker(Node *node, void *context)
802 if (IsA(node, FuncExpr))
804 FuncExpr *expr = (FuncExpr *) node;
806 if (func_volatile(expr->funcid) != PROVOLATILE_IMMUTABLE)
808 /* else fall through to check args */
810 else if (IsA(node, OpExpr))
812 OpExpr *expr = (OpExpr *) node;
815 if (func_volatile(expr->opfuncid) != PROVOLATILE_IMMUTABLE)
817 /* else fall through to check args */
819 else if (IsA(node, DistinctExpr))
821 DistinctExpr *expr = (DistinctExpr *) node;
823 set_opfuncid((OpExpr *) expr); /* rely on struct equivalence */
824 if (func_volatile(expr->opfuncid) != PROVOLATILE_IMMUTABLE)
826 /* else fall through to check args */
828 else if (IsA(node, ScalarArrayOpExpr))
830 ScalarArrayOpExpr *expr = (ScalarArrayOpExpr *) node;
832 set_sa_opfuncid(expr);
833 if (func_volatile(expr->opfuncid) != PROVOLATILE_IMMUTABLE)
835 /* else fall through to check args */
837 else if (IsA(node, CoerceViaIO))
839 CoerceViaIO *expr = (CoerceViaIO *) node;
844 /* check the result type's input function */
845 getTypeInputInfo(expr->resulttype,
846 &iofunc, &typioparam);
847 if (func_volatile(iofunc) != PROVOLATILE_IMMUTABLE)
849 /* check the input type's output function */
850 getTypeOutputInfo(exprType((Node *) expr->arg),
851 &iofunc, &typisvarlena);
852 if (func_volatile(iofunc) != PROVOLATILE_IMMUTABLE)
854 /* else fall through to check args */
856 else if (IsA(node, ArrayCoerceExpr))
858 ArrayCoerceExpr *expr = (ArrayCoerceExpr *) node;
860 if (OidIsValid(expr->elemfuncid) &&
861 func_volatile(expr->elemfuncid) != PROVOLATILE_IMMUTABLE)
863 /* else fall through to check args */
865 else if (IsA(node, NullIfExpr))
867 NullIfExpr *expr = (NullIfExpr *) node;
869 set_opfuncid((OpExpr *) expr); /* rely on struct equivalence */
870 if (func_volatile(expr->opfuncid) != PROVOLATILE_IMMUTABLE)
872 /* else fall through to check args */
874 else if (IsA(node, RowCompareExpr))
876 RowCompareExpr *rcexpr = (RowCompareExpr *) node;
879 foreach(opid, rcexpr->opnos)
881 if (op_volatile(lfirst_oid(opid)) != PROVOLATILE_IMMUTABLE)
884 /* else fall through to check args */
886 return expression_tree_walker(node, contain_mutable_functions_walker,
891 /*****************************************************************************
892 * Check clauses for volatile functions
893 *****************************************************************************/
896 * contain_volatile_functions
897 * Recursively search for volatile functions within a clause.
899 * Returns true if any volatile function (or operator implemented by a
900 * volatile function) is found. This test prevents invalid conversions
901 * of volatile expressions into indexscan quals.
903 * XXX we do not examine sub-selects to see if they contain uses of
904 * volatile functions. It's not real clear if that is correct or not...
907 contain_volatile_functions(Node *clause)
909 return contain_volatile_functions_walker(clause, NULL);
913 contain_volatile_functions_walker(Node *node, void *context)
917 if (IsA(node, FuncExpr))
919 FuncExpr *expr = (FuncExpr *) node;
921 if (func_volatile(expr->funcid) == PROVOLATILE_VOLATILE)
923 /* else fall through to check args */
925 else if (IsA(node, OpExpr))
927 OpExpr *expr = (OpExpr *) node;
930 if (func_volatile(expr->opfuncid) == PROVOLATILE_VOLATILE)
932 /* else fall through to check args */
934 else if (IsA(node, DistinctExpr))
936 DistinctExpr *expr = (DistinctExpr *) node;
938 set_opfuncid((OpExpr *) expr); /* rely on struct equivalence */
939 if (func_volatile(expr->opfuncid) == PROVOLATILE_VOLATILE)
941 /* else fall through to check args */
943 else if (IsA(node, ScalarArrayOpExpr))
945 ScalarArrayOpExpr *expr = (ScalarArrayOpExpr *) node;
947 set_sa_opfuncid(expr);
948 if (func_volatile(expr->opfuncid) == PROVOLATILE_VOLATILE)
950 /* else fall through to check args */
952 else if (IsA(node, CoerceViaIO))
954 CoerceViaIO *expr = (CoerceViaIO *) node;
959 /* check the result type's input function */
960 getTypeInputInfo(expr->resulttype,
961 &iofunc, &typioparam);
962 if (func_volatile(iofunc) == PROVOLATILE_VOLATILE)
964 /* check the input type's output function */
965 getTypeOutputInfo(exprType((Node *) expr->arg),
966 &iofunc, &typisvarlena);
967 if (func_volatile(iofunc) == PROVOLATILE_VOLATILE)
969 /* else fall through to check args */
971 else if (IsA(node, ArrayCoerceExpr))
973 ArrayCoerceExpr *expr = (ArrayCoerceExpr *) node;
975 if (OidIsValid(expr->elemfuncid) &&
976 func_volatile(expr->elemfuncid) == PROVOLATILE_VOLATILE)
978 /* else fall through to check args */
980 else if (IsA(node, NullIfExpr))
982 NullIfExpr *expr = (NullIfExpr *) node;
984 set_opfuncid((OpExpr *) expr); /* rely on struct equivalence */
985 if (func_volatile(expr->opfuncid) == PROVOLATILE_VOLATILE)
987 /* else fall through to check args */
989 else if (IsA(node, RowCompareExpr))
991 /* RowCompare probably can't have volatile ops, but check anyway */
992 RowCompareExpr *rcexpr = (RowCompareExpr *) node;
995 foreach(opid, rcexpr->opnos)
997 if (op_volatile(lfirst_oid(opid)) == PROVOLATILE_VOLATILE)
1000 /* else fall through to check args */
1002 return expression_tree_walker(node, contain_volatile_functions_walker,
1007 /*****************************************************************************
1008 * Check clauses for nonstrict functions
1009 *****************************************************************************/
1012 * contain_nonstrict_functions
1013 * Recursively search for nonstrict functions within a clause.
1015 * Returns true if any nonstrict construct is found --- ie, anything that
1016 * could produce non-NULL output with a NULL input.
1018 * The idea here is that the caller has verified that the expression contains
1019 * one or more Var or Param nodes (as appropriate for the caller's need), and
1020 * now wishes to prove that the expression result will be NULL if any of these
1021 * inputs is NULL. If we return false, then the proof succeeded.
1024 contain_nonstrict_functions(Node *clause)
1026 return contain_nonstrict_functions_walker(clause, NULL);
1030 contain_nonstrict_functions_walker(Node *node, void *context)
1034 if (IsA(node, Aggref))
1036 /* an aggregate could return non-null with null input */
1039 if (IsA(node, WindowFunc))
1041 /* a window function could return non-null with null input */
1044 if (IsA(node, ArrayRef))
1046 /* array assignment is nonstrict, but subscripting is strict */
1047 if (((ArrayRef *) node)->refassgnexpr != NULL)
1049 /* else fall through to check args */
1051 if (IsA(node, FuncExpr))
1053 FuncExpr *expr = (FuncExpr *) node;
1055 if (!func_strict(expr->funcid))
1057 /* else fall through to check args */
1059 if (IsA(node, OpExpr))
1061 OpExpr *expr = (OpExpr *) node;
1064 if (!func_strict(expr->opfuncid))
1066 /* else fall through to check args */
1068 if (IsA(node, DistinctExpr))
1070 /* IS DISTINCT FROM is inherently non-strict */
1073 if (IsA(node, ScalarArrayOpExpr))
1075 ScalarArrayOpExpr *expr = (ScalarArrayOpExpr *) node;
1077 if (!is_strict_saop(expr, false))
1079 /* else fall through to check args */
1081 if (IsA(node, BoolExpr))
1083 BoolExpr *expr = (BoolExpr *) node;
1085 switch (expr->boolop)
1089 /* AND, OR are inherently non-strict */
1095 if (IsA(node, SubLink))
1097 /* In some cases a sublink might be strict, but in general not */
1100 if (IsA(node, SubPlan))
1102 if (IsA(node, AlternativeSubPlan))
1104 /* ArrayCoerceExpr is strict at the array level, regardless of elemfunc */
1105 if (IsA(node, FieldStore))
1107 if (IsA(node, CaseExpr))
1109 if (IsA(node, ArrayExpr))
1111 if (IsA(node, RowExpr))
1113 if (IsA(node, RowCompareExpr))
1115 if (IsA(node, CoalesceExpr))
1117 if (IsA(node, MinMaxExpr))
1119 if (IsA(node, XmlExpr))
1121 if (IsA(node, NullIfExpr))
1123 if (IsA(node, NullTest))
1125 if (IsA(node, BooleanTest))
1127 return expression_tree_walker(node, contain_nonstrict_functions_walker,
1133 * find_nonnullable_rels
1134 * Determine which base rels are forced nonnullable by given clause.
1136 * Returns the set of all Relids that are referenced in the clause in such
1137 * a way that the clause cannot possibly return TRUE if any of these Relids
1138 * is an all-NULL row. (It is OK to err on the side of conservatism; hence
1139 * the analysis here is simplistic.)
1141 * The semantics here are subtly different from contain_nonstrict_functions:
1142 * that function is concerned with NULL results from arbitrary expressions,
1143 * but here we assume that the input is a Boolean expression, and wish to
1144 * see if NULL inputs will provably cause a FALSE-or-NULL result. We expect
1145 * the expression to have been AND/OR flattened and converted to implicit-AND
1148 * Note: this function is largely duplicative of find_nonnullable_vars().
1149 * The reason not to simplify this function into a thin wrapper around
1150 * find_nonnullable_vars() is that the tested conditions really are different:
1151 * a clause like "t1.v1 IS NOT NULL OR t1.v2 IS NOT NULL" does not prove
1152 * that either v1 or v2 can't be NULL, but it does prove that the t1 row
1153 * as a whole can't be all-NULL.
1155 * top_level is TRUE while scanning top-level AND/OR structure; here, showing
1156 * the result is either FALSE or NULL is good enough. top_level is FALSE when
1157 * we have descended below a NOT or a strict function: now we must be able to
1158 * prove that the subexpression goes to NULL.
1160 * We don't use expression_tree_walker here because we don't want to descend
1161 * through very many kinds of nodes; only the ones we can be sure are strict.
1164 find_nonnullable_rels(Node *clause)
1166 return find_nonnullable_rels_walker(clause, true);
1170 find_nonnullable_rels_walker(Node *node, bool top_level)
1172 Relids result = NULL;
1179 Var *var = (Var *) node;
1181 if (var->varlevelsup == 0)
1182 result = bms_make_singleton(var->varno);
1184 else if (IsA(node, List))
1187 * At top level, we are examining an implicit-AND list: if any of the
1188 * arms produces FALSE-or-NULL then the result is FALSE-or-NULL. If
1189 * not at top level, we are examining the arguments of a strict
1190 * function: if any of them produce NULL then the result of the
1191 * function must be NULL. So in both cases, the set of nonnullable
1192 * rels is the union of those found in the arms, and we pass down the
1193 * top_level flag unmodified.
1195 foreach(l, (List *) node)
1197 result = bms_join(result,
1198 find_nonnullable_rels_walker(lfirst(l),
1202 else if (IsA(node, FuncExpr))
1204 FuncExpr *expr = (FuncExpr *) node;
1206 if (func_strict(expr->funcid))
1207 result = find_nonnullable_rels_walker((Node *) expr->args, false);
1209 else if (IsA(node, OpExpr))
1211 OpExpr *expr = (OpExpr *) node;
1214 if (func_strict(expr->opfuncid))
1215 result = find_nonnullable_rels_walker((Node *) expr->args, false);
1217 else if (IsA(node, ScalarArrayOpExpr))
1219 ScalarArrayOpExpr *expr = (ScalarArrayOpExpr *) node;
1221 if (is_strict_saop(expr, true))
1222 result = find_nonnullable_rels_walker((Node *) expr->args, false);
1224 else if (IsA(node, BoolExpr))
1226 BoolExpr *expr = (BoolExpr *) node;
1228 switch (expr->boolop)
1231 /* At top level we can just recurse (to the List case) */
1234 result = find_nonnullable_rels_walker((Node *) expr->args,
1240 * Below top level, even if one arm produces NULL, the result
1241 * could be FALSE (hence not NULL). However, if *all* the
1242 * arms produce NULL then the result is NULL, so we can take
1243 * the intersection of the sets of nonnullable rels, just as
1244 * for OR. Fall through to share code.
1250 * OR is strict if all of its arms are, so we can take the
1251 * intersection of the sets of nonnullable rels for each arm.
1252 * This works for both values of top_level.
1254 foreach(l, expr->args)
1258 subresult = find_nonnullable_rels_walker(lfirst(l),
1260 if (result == NULL) /* first subresult? */
1263 result = bms_int_members(result, subresult);
1266 * If the intersection is empty, we can stop looking. This
1267 * also justifies the test for first-subresult above.
1269 if (bms_is_empty(result))
1274 /* NOT will return null if its arg is null */
1275 result = find_nonnullable_rels_walker((Node *) expr->args,
1279 elog(ERROR, "unrecognized boolop: %d", (int) expr->boolop);
1283 else if (IsA(node, RelabelType))
1285 RelabelType *expr = (RelabelType *) node;
1287 result = find_nonnullable_rels_walker((Node *) expr->arg, top_level);
1289 else if (IsA(node, CoerceViaIO))
1291 /* not clear this is useful, but it can't hurt */
1292 CoerceViaIO *expr = (CoerceViaIO *) node;
1294 result = find_nonnullable_rels_walker((Node *) expr->arg, top_level);
1296 else if (IsA(node, ArrayCoerceExpr))
1298 /* ArrayCoerceExpr is strict at the array level */
1299 ArrayCoerceExpr *expr = (ArrayCoerceExpr *) node;
1301 result = find_nonnullable_rels_walker((Node *) expr->arg, top_level);
1303 else if (IsA(node, ConvertRowtypeExpr))
1305 /* not clear this is useful, but it can't hurt */
1306 ConvertRowtypeExpr *expr = (ConvertRowtypeExpr *) node;
1308 result = find_nonnullable_rels_walker((Node *) expr->arg, top_level);
1310 else if (IsA(node, NullTest))
1312 /* IS NOT NULL can be considered strict, but only at top level */
1313 NullTest *expr = (NullTest *) node;
1315 if (top_level && expr->nulltesttype == IS_NOT_NULL && !expr->argisrow)
1316 result = find_nonnullable_rels_walker((Node *) expr->arg, false);
1318 else if (IsA(node, BooleanTest))
1320 /* Boolean tests that reject NULL are strict at top level */
1321 BooleanTest *expr = (BooleanTest *) node;
1324 (expr->booltesttype == IS_TRUE ||
1325 expr->booltesttype == IS_FALSE ||
1326 expr->booltesttype == IS_NOT_UNKNOWN))
1327 result = find_nonnullable_rels_walker((Node *) expr->arg, false);
1329 else if (IsA(node, PlaceHolderVar))
1331 PlaceHolderVar *phv = (PlaceHolderVar *) node;
1333 result = find_nonnullable_rels_walker((Node *) phv->phexpr, top_level);
1339 * find_nonnullable_vars
1340 * Determine which Vars are forced nonnullable by given clause.
1342 * Returns a list of all level-zero Vars that are referenced in the clause in
1343 * such a way that the clause cannot possibly return TRUE if any of these Vars
1344 * is NULL. (It is OK to err on the side of conservatism; hence the analysis
1345 * here is simplistic.)
1347 * The semantics here are subtly different from contain_nonstrict_functions:
1348 * that function is concerned with NULL results from arbitrary expressions,
1349 * but here we assume that the input is a Boolean expression, and wish to
1350 * see if NULL inputs will provably cause a FALSE-or-NULL result. We expect
1351 * the expression to have been AND/OR flattened and converted to implicit-AND
1354 * The result is a palloc'd List, but we have not copied the member Var nodes.
1355 * Also, we don't bother trying to eliminate duplicate entries.
1357 * top_level is TRUE while scanning top-level AND/OR structure; here, showing
1358 * the result is either FALSE or NULL is good enough. top_level is FALSE when
1359 * we have descended below a NOT or a strict function: now we must be able to
1360 * prove that the subexpression goes to NULL.
1362 * We don't use expression_tree_walker here because we don't want to descend
1363 * through very many kinds of nodes; only the ones we can be sure are strict.
1366 find_nonnullable_vars(Node *clause)
1368 return find_nonnullable_vars_walker(clause, true);
1372 find_nonnullable_vars_walker(Node *node, bool top_level)
1381 Var *var = (Var *) node;
1383 if (var->varlevelsup == 0)
1384 result = list_make1(var);
1386 else if (IsA(node, List))
1389 * At top level, we are examining an implicit-AND list: if any of the
1390 * arms produces FALSE-or-NULL then the result is FALSE-or-NULL. If
1391 * not at top level, we are examining the arguments of a strict
1392 * function: if any of them produce NULL then the result of the
1393 * function must be NULL. So in both cases, the set of nonnullable
1394 * vars is the union of those found in the arms, and we pass down the
1395 * top_level flag unmodified.
1397 foreach(l, (List *) node)
1399 result = list_concat(result,
1400 find_nonnullable_vars_walker(lfirst(l),
1404 else if (IsA(node, FuncExpr))
1406 FuncExpr *expr = (FuncExpr *) node;
1408 if (func_strict(expr->funcid))
1409 result = find_nonnullable_vars_walker((Node *) expr->args, false);
1411 else if (IsA(node, OpExpr))
1413 OpExpr *expr = (OpExpr *) node;
1416 if (func_strict(expr->opfuncid))
1417 result = find_nonnullable_vars_walker((Node *) expr->args, false);
1419 else if (IsA(node, ScalarArrayOpExpr))
1421 ScalarArrayOpExpr *expr = (ScalarArrayOpExpr *) node;
1423 if (is_strict_saop(expr, true))
1424 result = find_nonnullable_vars_walker((Node *) expr->args, false);
1426 else if (IsA(node, BoolExpr))
1428 BoolExpr *expr = (BoolExpr *) node;
1430 switch (expr->boolop)
1433 /* At top level we can just recurse (to the List case) */
1436 result = find_nonnullable_vars_walker((Node *) expr->args,
1442 * Below top level, even if one arm produces NULL, the result
1443 * could be FALSE (hence not NULL). However, if *all* the
1444 * arms produce NULL then the result is NULL, so we can take
1445 * the intersection of the sets of nonnullable vars, just as
1446 * for OR. Fall through to share code.
1452 * OR is strict if all of its arms are, so we can take the
1453 * intersection of the sets of nonnullable vars for each arm.
1454 * This works for both values of top_level.
1456 foreach(l, expr->args)
1460 subresult = find_nonnullable_vars_walker(lfirst(l),
1462 if (result == NIL) /* first subresult? */
1465 result = list_intersection(result, subresult);
1468 * If the intersection is empty, we can stop looking. This
1469 * also justifies the test for first-subresult above.
1476 /* NOT will return null if its arg is null */
1477 result = find_nonnullable_vars_walker((Node *) expr->args,
1481 elog(ERROR, "unrecognized boolop: %d", (int) expr->boolop);
1485 else if (IsA(node, RelabelType))
1487 RelabelType *expr = (RelabelType *) node;
1489 result = find_nonnullable_vars_walker((Node *) expr->arg, top_level);
1491 else if (IsA(node, CoerceViaIO))
1493 /* not clear this is useful, but it can't hurt */
1494 CoerceViaIO *expr = (CoerceViaIO *) node;
1496 result = find_nonnullable_vars_walker((Node *) expr->arg, false);
1498 else if (IsA(node, ArrayCoerceExpr))
1500 /* ArrayCoerceExpr is strict at the array level */
1501 ArrayCoerceExpr *expr = (ArrayCoerceExpr *) node;
1503 result = find_nonnullable_vars_walker((Node *) expr->arg, top_level);
1505 else if (IsA(node, ConvertRowtypeExpr))
1507 /* not clear this is useful, but it can't hurt */
1508 ConvertRowtypeExpr *expr = (ConvertRowtypeExpr *) node;
1510 result = find_nonnullable_vars_walker((Node *) expr->arg, top_level);
1512 else if (IsA(node, NullTest))
1514 /* IS NOT NULL can be considered strict, but only at top level */
1515 NullTest *expr = (NullTest *) node;
1517 if (top_level && expr->nulltesttype == IS_NOT_NULL && !expr->argisrow)
1518 result = find_nonnullable_vars_walker((Node *) expr->arg, false);
1520 else if (IsA(node, BooleanTest))
1522 /* Boolean tests that reject NULL are strict at top level */
1523 BooleanTest *expr = (BooleanTest *) node;
1526 (expr->booltesttype == IS_TRUE ||
1527 expr->booltesttype == IS_FALSE ||
1528 expr->booltesttype == IS_NOT_UNKNOWN))
1529 result = find_nonnullable_vars_walker((Node *) expr->arg, false);
1531 else if (IsA(node, PlaceHolderVar))
1533 PlaceHolderVar *phv = (PlaceHolderVar *) node;
1535 result = find_nonnullable_vars_walker((Node *) phv->phexpr, top_level);
1541 * find_forced_null_vars
1542 * Determine which Vars must be NULL for the given clause to return TRUE.
1544 * This is the complement of find_nonnullable_vars: find the level-zero Vars
1545 * that must be NULL for the clause to return TRUE. (It is OK to err on the
1546 * side of conservatism; hence the analysis here is simplistic. In fact,
1547 * we only detect simple "var IS NULL" tests at the top level.)
1549 * The result is a palloc'd List, but we have not copied the member Var nodes.
1550 * Also, we don't bother trying to eliminate duplicate entries.
1553 find_forced_null_vars(Node *node)
1561 /* Check single-clause cases using subroutine */
1562 var = find_forced_null_var(node);
1565 result = list_make1(var);
1567 /* Otherwise, handle AND-conditions */
1568 else if (IsA(node, List))
1571 * At top level, we are examining an implicit-AND list: if any of the
1572 * arms produces FALSE-or-NULL then the result is FALSE-or-NULL.
1574 foreach(l, (List *) node)
1576 result = list_concat(result,
1577 find_forced_null_vars(lfirst(l)));
1580 else if (IsA(node, BoolExpr))
1582 BoolExpr *expr = (BoolExpr *) node;
1585 * We don't bother considering the OR case, because it's fairly
1586 * unlikely anyone would write "v1 IS NULL OR v1 IS NULL". Likewise,
1587 * the NOT case isn't worth expending code on.
1589 if (expr->boolop == AND_EXPR)
1591 /* At top level we can just recurse (to the List case) */
1592 result = find_forced_null_vars((Node *) expr->args);
1599 * find_forced_null_var
1600 * Return the Var forced null by the given clause, or NULL if it's
1601 * not an IS NULL-type clause. For success, the clause must enforce
1602 * *only* nullness of the particular Var, not any other conditions.
1604 * This is just the single-clause case of find_forced_null_vars(), without
1605 * any allowance for AND conditions. It's used by initsplan.c on individual
1606 * qual clauses. The reason for not just applying find_forced_null_vars()
1607 * is that if an AND of an IS NULL clause with something else were to somehow
1608 * survive AND/OR flattening, initsplan.c might get fooled into discarding
1609 * the whole clause when only the IS NULL part of it had been proved redundant.
1612 find_forced_null_var(Node *node)
1616 if (IsA(node, NullTest))
1618 /* check for var IS NULL */
1619 NullTest *expr = (NullTest *) node;
1621 if (expr->nulltesttype == IS_NULL && !expr->argisrow)
1623 Var *var = (Var *) expr->arg;
1625 if (var && IsA(var, Var) &&
1626 var->varlevelsup == 0)
1630 else if (IsA(node, BooleanTest))
1632 /* var IS UNKNOWN is equivalent to var IS NULL */
1633 BooleanTest *expr = (BooleanTest *) node;
1635 if (expr->booltesttype == IS_UNKNOWN)
1637 Var *var = (Var *) expr->arg;
1639 if (var && IsA(var, Var) &&
1640 var->varlevelsup == 0)
1648 * Can we treat a ScalarArrayOpExpr as strict?
1650 * If "falseOK" is true, then a "false" result can be considered strict,
1651 * else we need to guarantee an actual NULL result for NULL input.
1653 * "foo op ALL array" is strict if the op is strict *and* we can prove
1654 * that the array input isn't an empty array. We can check that
1655 * for the cases of an array constant and an ARRAY[] construct.
1657 * "foo op ANY array" is strict in the falseOK sense if the op is strict.
1658 * If not falseOK, the test is the same as for "foo op ALL array".
1661 is_strict_saop(ScalarArrayOpExpr *expr, bool falseOK)
1665 /* The contained operator must be strict. */
1666 set_sa_opfuncid(expr);
1667 if (!func_strict(expr->opfuncid))
1669 /* If ANY and falseOK, that's all we need to check. */
1670 if (expr->useOr && falseOK)
1672 /* Else, we have to see if the array is provably non-empty. */
1673 Assert(list_length(expr->args) == 2);
1674 rightop = (Node *) lsecond(expr->args);
1675 if (rightop && IsA(rightop, Const))
1677 Datum arraydatum = ((Const *) rightop)->constvalue;
1678 bool arrayisnull = ((Const *) rightop)->constisnull;
1679 ArrayType *arrayval;
1684 arrayval = DatumGetArrayTypeP(arraydatum);
1685 nitems = ArrayGetNItems(ARR_NDIM(arrayval), ARR_DIMS(arrayval));
1689 else if (rightop && IsA(rightop, ArrayExpr))
1691 ArrayExpr *arrayexpr = (ArrayExpr *) rightop;
1693 if (arrayexpr->elements != NIL && !arrayexpr->multidims)
1700 /*****************************************************************************
1701 * Check for "pseudo-constant" clauses
1702 *****************************************************************************/
1705 * is_pseudo_constant_clause
1706 * Detect whether an expression is "pseudo constant", ie, it contains no
1707 * variables of the current query level and no uses of volatile functions.
1708 * Such an expr is not necessarily a true constant: it can still contain
1709 * Params and outer-level Vars, not to mention functions whose results
1710 * may vary from one statement to the next. However, the expr's value
1711 * will be constant over any one scan of the current query, so it can be
1712 * used as, eg, an indexscan key.
1714 * CAUTION: this function omits to test for one very important class of
1715 * not-constant expressions, namely aggregates (Aggrefs). In current usage
1716 * this is only applied to WHERE clauses and so a check for Aggrefs would be
1717 * a waste of cycles; but be sure to also check contain_agg_clause() if you
1718 * want to know about pseudo-constness in other contexts. The same goes
1719 * for window functions (WindowFuncs).
1722 is_pseudo_constant_clause(Node *clause)
1725 * We could implement this check in one recursive scan. But since the
1726 * check for volatile functions is both moderately expensive and unlikely
1727 * to fail, it seems better to look for Vars first and only check for
1728 * volatile functions if we find no Vars.
1730 if (!contain_var_clause(clause) &&
1731 !contain_volatile_functions(clause))
1737 * is_pseudo_constant_clause_relids
1738 * Same as above, except caller already has available the var membership
1739 * of the expression; this lets us avoid the contain_var_clause() scan.
1742 is_pseudo_constant_clause_relids(Node *clause, Relids relids)
1744 if (bms_is_empty(relids) &&
1745 !contain_volatile_functions(clause))
1751 /*****************************************************************************
1753 * General clause-manipulating routines *
1755 *****************************************************************************/
1759 * (formerly clause_relids)
1761 * Returns the number of different relations referenced in 'clause'.
1764 NumRelids(Node *clause)
1766 Relids varnos = pull_varnos(clause);
1767 int result = bms_num_members(varnos);
1774 * CommuteOpExpr: commute a binary operator clause
1776 * XXX the clause is destructively modified!
1779 CommuteOpExpr(OpExpr *clause)
1784 /* Sanity checks: caller is at fault if these fail */
1785 if (!is_opclause(clause) ||
1786 list_length(clause->args) != 2)
1787 elog(ERROR, "cannot commute non-binary-operator clause");
1789 opoid = get_commutator(clause->opno);
1791 if (!OidIsValid(opoid))
1792 elog(ERROR, "could not find commutator for operator %u",
1796 * modify the clause in-place!
1798 clause->opno = opoid;
1799 clause->opfuncid = InvalidOid;
1800 /* opresulttype and opretset are assumed not to change */
1802 temp = linitial(clause->args);
1803 linitial(clause->args) = lsecond(clause->args);
1804 lsecond(clause->args) = temp;
1808 * CommuteRowCompareExpr: commute a RowCompareExpr clause
1810 * XXX the clause is destructively modified!
1813 CommuteRowCompareExpr(RowCompareExpr *clause)
1819 /* Sanity checks: caller is at fault if these fail */
1820 if (!IsA(clause, RowCompareExpr))
1821 elog(ERROR, "expected a RowCompareExpr");
1823 /* Build list of commuted operators */
1825 foreach(l, clause->opnos)
1827 Oid opoid = lfirst_oid(l);
1829 opoid = get_commutator(opoid);
1830 if (!OidIsValid(opoid))
1831 elog(ERROR, "could not find commutator for operator %u",
1833 newops = lappend_oid(newops, opoid);
1837 * modify the clause in-place!
1839 switch (clause->rctype)
1842 clause->rctype = ROWCOMPARE_GT;
1845 clause->rctype = ROWCOMPARE_GE;
1848 clause->rctype = ROWCOMPARE_LE;
1851 clause->rctype = ROWCOMPARE_LT;
1854 elog(ERROR, "unexpected RowCompare type: %d",
1855 (int) clause->rctype);
1859 clause->opnos = newops;
1862 * Note: we need not change the opfamilies list; we assume any btree
1863 * opfamily containing an operator will also contain its commutator.
1866 temp = clause->largs;
1867 clause->largs = clause->rargs;
1868 clause->rargs = temp;
1872 * strip_implicit_coercions: remove implicit coercions at top level of tree
1874 * Note: there isn't any useful thing we can do with a RowExpr here, so
1875 * just return it unchanged, even if it's marked as an implicit coercion.
1878 strip_implicit_coercions(Node *node)
1882 if (IsA(node, FuncExpr))
1884 FuncExpr *f = (FuncExpr *) node;
1886 if (f->funcformat == COERCE_IMPLICIT_CAST)
1887 return strip_implicit_coercions(linitial(f->args));
1889 else if (IsA(node, RelabelType))
1891 RelabelType *r = (RelabelType *) node;
1893 if (r->relabelformat == COERCE_IMPLICIT_CAST)
1894 return strip_implicit_coercions((Node *) r->arg);
1896 else if (IsA(node, CoerceViaIO))
1898 CoerceViaIO *c = (CoerceViaIO *) node;
1900 if (c->coerceformat == COERCE_IMPLICIT_CAST)
1901 return strip_implicit_coercions((Node *) c->arg);
1903 else if (IsA(node, ArrayCoerceExpr))
1905 ArrayCoerceExpr *c = (ArrayCoerceExpr *) node;
1907 if (c->coerceformat == COERCE_IMPLICIT_CAST)
1908 return strip_implicit_coercions((Node *) c->arg);
1910 else if (IsA(node, ConvertRowtypeExpr))
1912 ConvertRowtypeExpr *c = (ConvertRowtypeExpr *) node;
1914 if (c->convertformat == COERCE_IMPLICIT_CAST)
1915 return strip_implicit_coercions((Node *) c->arg);
1917 else if (IsA(node, CoerceToDomain))
1919 CoerceToDomain *c = (CoerceToDomain *) node;
1921 if (c->coercionformat == COERCE_IMPLICIT_CAST)
1922 return strip_implicit_coercions((Node *) c->arg);
1928 * set_coercionform_dontcare: set all CoercionForm fields to COERCE_DONTCARE
1930 * This is used to make index expressions and index predicates more easily
1931 * comparable to clauses of queries. CoercionForm is not semantically
1932 * significant (for cases where it does matter, the significant info is
1933 * coded into the coercion function arguments) so we can ignore it during
1934 * comparisons. Thus, for example, an index on "foo::int4" can match an
1935 * implicit coercion to int4.
1937 * Caution: the passed expression tree is modified in-place.
1940 set_coercionform_dontcare(Node *node)
1942 (void) set_coercionform_dontcare_walker(node, NULL);
1946 set_coercionform_dontcare_walker(Node *node, void *context)
1950 if (IsA(node, FuncExpr))
1951 ((FuncExpr *) node)->funcformat = COERCE_DONTCARE;
1952 else if (IsA(node, RelabelType))
1953 ((RelabelType *) node)->relabelformat = COERCE_DONTCARE;
1954 else if (IsA(node, CoerceViaIO))
1955 ((CoerceViaIO *) node)->coerceformat = COERCE_DONTCARE;
1956 else if (IsA(node, ArrayCoerceExpr))
1957 ((ArrayCoerceExpr *) node)->coerceformat = COERCE_DONTCARE;
1958 else if (IsA(node, ConvertRowtypeExpr))
1959 ((ConvertRowtypeExpr *) node)->convertformat = COERCE_DONTCARE;
1960 else if (IsA(node, RowExpr))
1961 ((RowExpr *) node)->row_format = COERCE_DONTCARE;
1962 else if (IsA(node, CoerceToDomain))
1963 ((CoerceToDomain *) node)->coercionformat = COERCE_DONTCARE;
1964 return expression_tree_walker(node, set_coercionform_dontcare_walker,
1969 * Helper for eval_const_expressions: check that datatype of an attribute
1970 * is still what it was when the expression was parsed. This is needed to
1971 * guard against improper simplification after ALTER COLUMN TYPE. (XXX we
1972 * may well need to make similar checks elsewhere?)
1975 rowtype_field_matches(Oid rowtypeid, int fieldnum,
1976 Oid expectedtype, int32 expectedtypmod)
1979 Form_pg_attribute attr;
1981 /* No issue for RECORD, since there is no way to ALTER such a type */
1982 if (rowtypeid == RECORDOID)
1984 tupdesc = lookup_rowtype_tupdesc(rowtypeid, -1);
1985 if (fieldnum <= 0 || fieldnum > tupdesc->natts)
1987 ReleaseTupleDesc(tupdesc);
1990 attr = tupdesc->attrs[fieldnum - 1];
1991 if (attr->attisdropped ||
1992 attr->atttypid != expectedtype ||
1993 attr->atttypmod != expectedtypmod)
1995 ReleaseTupleDesc(tupdesc);
1998 ReleaseTupleDesc(tupdesc);
2003 /*--------------------
2004 * eval_const_expressions
2006 * Reduce any recognizably constant subexpressions of the given
2007 * expression tree, for example "2 + 2" => "4". More interestingly,
2008 * we can reduce certain boolean expressions even when they contain
2009 * non-constant subexpressions: "x OR true" => "true" no matter what
2010 * the subexpression x is. (XXX We assume that no such subexpression
2011 * will have important side-effects, which is not necessarily a good
2012 * assumption in the presence of user-defined functions; do we need a
2013 * pg_proc flag that prevents discarding the execution of a function?)
2015 * We do understand that certain functions may deliver non-constant
2016 * results even with constant inputs, "nextval()" being the classic
2017 * example. Functions that are not marked "immutable" in pg_proc
2018 * will not be pre-evaluated here, although we will reduce their
2019 * arguments as far as possible.
2021 * Whenever a function is eliminated from the expression by means of
2022 * constant-expression evaluation or inlining, we add the function to
2023 * root->glob->invalItems. This ensures the plan is known to depend on
2024 * such functions, even though they aren't referenced anymore.
2026 * We assume that the tree has already been type-checked and contains
2027 * only operators and functions that are reasonable to try to execute.
2029 * NOTE: "root" can be passed as NULL if the caller never wants to do any
2030 * Param substitutions nor receive info about inlined functions.
2032 * NOTE: the planner assumes that this will always flatten nested AND and
2033 * OR clauses into N-argument form. See comments in prepqual.c.
2035 * NOTE: another critical effect is that any function calls that require
2036 * default arguments will be expanded, and named-argument calls will be
2037 * converted to positional notation. The executor won't handle either.
2038 *--------------------
2041 eval_const_expressions(PlannerInfo *root, Node *node)
2043 eval_const_expressions_context context;
2047 context.boundParams = root->glob->boundParams; /* bound Params */
2048 context.glob = root->glob; /* for inlined-function dependencies */
2052 context.boundParams = NULL;
2053 context.glob = NULL;
2055 context.active_fns = NIL; /* nothing being recursively simplified */
2056 context.case_val = NULL; /* no CASE being examined */
2057 context.estimate = false; /* safe transformations only */
2058 return eval_const_expressions_mutator(node, &context);
2061 /*--------------------
2062 * estimate_expression_value
2064 * This function attempts to estimate the value of an expression for
2065 * planning purposes. It is in essence a more aggressive version of
2066 * eval_const_expressions(): we will perform constant reductions that are
2067 * not necessarily 100% safe, but are reasonable for estimation purposes.
2069 * Currently the extra steps that are taken in this mode are:
2070 * 1. Substitute values for Params, where a bound Param value has been made
2071 * available by the caller of planner(), even if the Param isn't marked
2072 * constant. This effectively means that we plan using the first supplied
2073 * value of the Param.
2074 * 2. Fold stable, as well as immutable, functions to constants.
2075 * 3. Reduce PlaceHolderVar nodes to their contained expressions.
2076 *--------------------
2079 estimate_expression_value(PlannerInfo *root, Node *node)
2081 eval_const_expressions_context context;
2083 context.boundParams = root->glob->boundParams; /* bound Params */
2084 /* we do not need to mark the plan as depending on inlined functions */
2085 context.glob = NULL;
2086 context.active_fns = NIL; /* nothing being recursively simplified */
2087 context.case_val = NULL; /* no CASE being examined */
2088 context.estimate = true; /* unsafe transformations OK */
2089 return eval_const_expressions_mutator(node, &context);
2093 eval_const_expressions_mutator(Node *node,
2094 eval_const_expressions_context *context)
2098 if (IsA(node, Param))
2100 Param *param = (Param *) node;
2102 /* Look to see if we've been given a value for this Param */
2103 if (param->paramkind == PARAM_EXTERN &&
2104 context->boundParams != NULL &&
2105 param->paramid > 0 &&
2106 param->paramid <= context->boundParams->numParams)
2108 ParamExternData *prm = &context->boundParams->params[param->paramid - 1];
2110 if (OidIsValid(prm->ptype))
2112 /* OK to substitute parameter value? */
2113 if (context->estimate || (prm->pflags & PARAM_FLAG_CONST))
2116 * Return a Const representing the param value. Must copy
2117 * pass-by-ref datatypes, since the Param might be in a
2118 * memory context shorter-lived than our output plan
2125 Assert(prm->ptype == param->paramtype);
2126 get_typlenbyval(param->paramtype, &typLen, &typByVal);
2127 if (prm->isnull || typByVal)
2130 pval = datumCopy(prm->value, typByVal, typLen);
2131 return (Node *) makeConst(param->paramtype,
2140 /* Not replaceable, so just copy the Param (no need to recurse) */
2141 return (Node *) copyObject(param);
2143 if (IsA(node, FuncExpr))
2145 FuncExpr *expr = (FuncExpr *) node;
2147 bool has_named_args;
2153 * Reduce constants in the FuncExpr's arguments, and check to see if
2154 * there are any named args.
2157 has_named_args = false;
2158 foreach(lc, expr->args)
2160 Node *arg = (Node *) lfirst(lc);
2162 arg = eval_const_expressions_mutator(arg, context);
2163 if (IsA(arg, NamedArgExpr))
2164 has_named_args = true;
2165 args = lappend(args, arg);
2169 * Code for op/func reduction is pretty bulky, so split it out as a
2170 * separate function. Note: exprTypmod normally returns -1 for a
2171 * FuncExpr, but not when the node is recognizably a length coercion;
2172 * we want to preserve the typmod in the eventual Const if so.
2174 simple = simplify_function(expr->funcid,
2175 expr->funcresulttype, exprTypmod(node),
2177 has_named_args, true, context);
2178 if (simple) /* successfully simplified it */
2179 return (Node *) simple;
2182 * The expression cannot be simplified any further, so build and
2183 * return a replacement FuncExpr node using the possibly-simplified
2184 * arguments. Note that we have also converted the argument list to
2185 * positional notation.
2187 newexpr = makeNode(FuncExpr);
2188 newexpr->funcid = expr->funcid;
2189 newexpr->funcresulttype = expr->funcresulttype;
2190 newexpr->funcretset = expr->funcretset;
2191 newexpr->funcformat = expr->funcformat;
2192 newexpr->args = args;
2193 newexpr->location = expr->location;
2194 return (Node *) newexpr;
2196 if (IsA(node, OpExpr))
2198 OpExpr *expr = (OpExpr *) node;
2204 * Reduce constants in the OpExpr's arguments. We know args is either
2205 * NIL or a List node, so we can call expression_tree_mutator directly
2206 * rather than recursing to self.
2208 args = (List *) expression_tree_mutator((Node *) expr->args,
2209 eval_const_expressions_mutator,
2213 * Need to get OID of underlying function. Okay to scribble on input
2219 * Code for op/func reduction is pretty bulky, so split it out as a
2220 * separate function.
2222 simple = simplify_function(expr->opfuncid,
2223 expr->opresulttype, -1,
2225 false, true, context);
2226 if (simple) /* successfully simplified it */
2227 return (Node *) simple;
2230 * If the operator is boolean equality or inequality, we know how to
2231 * simplify cases involving one constant and one non-constant
2234 if (expr->opno == BooleanEqualOperator ||
2235 expr->opno == BooleanNotEqualOperator)
2237 simple = (Expr *) simplify_boolean_equality(expr->opno, args);
2238 if (simple) /* successfully simplified it */
2239 return (Node *) simple;
2243 * The expression cannot be simplified any further, so build and
2244 * return a replacement OpExpr node using the possibly-simplified
2247 newexpr = makeNode(OpExpr);
2248 newexpr->opno = expr->opno;
2249 newexpr->opfuncid = expr->opfuncid;
2250 newexpr->opresulttype = expr->opresulttype;
2251 newexpr->opretset = expr->opretset;
2252 newexpr->args = args;
2253 newexpr->location = expr->location;
2254 return (Node *) newexpr;
2256 if (IsA(node, DistinctExpr))
2258 DistinctExpr *expr = (DistinctExpr *) node;
2261 bool has_null_input = false;
2262 bool all_null_input = true;
2263 bool has_nonconst_input = false;
2265 DistinctExpr *newexpr;
2268 * Reduce constants in the DistinctExpr's arguments. We know args is
2269 * either NIL or a List node, so we can call expression_tree_mutator
2270 * directly rather than recursing to self.
2272 args = (List *) expression_tree_mutator((Node *) expr->args,
2273 eval_const_expressions_mutator,
2277 * We must do our own check for NULLs because DistinctExpr has
2278 * different results for NULL input than the underlying operator does.
2282 if (IsA(lfirst(arg), Const))
2284 has_null_input |= ((Const *) lfirst(arg))->constisnull;
2285 all_null_input &= ((Const *) lfirst(arg))->constisnull;
2288 has_nonconst_input = true;
2291 /* all constants? then can optimize this out */
2292 if (!has_nonconst_input)
2294 /* all nulls? then not distinct */
2296 return makeBoolConst(false, false);
2298 /* one null? then distinct */
2300 return makeBoolConst(true, false);
2302 /* otherwise try to evaluate the '=' operator */
2303 /* (NOT okay to try to inline it, though!) */
2306 * Need to get OID of underlying function. Okay to scribble on
2307 * input to this extent.
2309 set_opfuncid((OpExpr *) expr); /* rely on struct equivalence */
2312 * Code for op/func reduction is pretty bulky, so split it out as
2313 * a separate function.
2315 simple = simplify_function(expr->opfuncid,
2316 expr->opresulttype, -1,
2318 false, false, context);
2319 if (simple) /* successfully simplified it */
2322 * Since the underlying operator is "=", must negate its
2325 Const *csimple = (Const *) simple;
2327 Assert(IsA(csimple, Const));
2328 csimple->constvalue =
2329 BoolGetDatum(!DatumGetBool(csimple->constvalue));
2330 return (Node *) csimple;
2335 * The expression cannot be simplified any further, so build and
2336 * return a replacement DistinctExpr node using the
2337 * possibly-simplified arguments.
2339 newexpr = makeNode(DistinctExpr);
2340 newexpr->opno = expr->opno;
2341 newexpr->opfuncid = expr->opfuncid;
2342 newexpr->opresulttype = expr->opresulttype;
2343 newexpr->opretset = expr->opretset;
2344 newexpr->args = args;
2345 newexpr->location = expr->location;
2346 return (Node *) newexpr;
2348 if (IsA(node, BoolExpr))
2350 BoolExpr *expr = (BoolExpr *) node;
2352 switch (expr->boolop)
2357 bool haveNull = false;
2358 bool forceTrue = false;
2360 newargs = simplify_or_arguments(expr->args, context,
2361 &haveNull, &forceTrue);
2363 return makeBoolConst(true, false);
2365 newargs = lappend(newargs, makeBoolConst(false, true));
2366 /* If all the inputs are FALSE, result is FALSE */
2368 return makeBoolConst(false, false);
2369 /* If only one nonconst-or-NULL input, it's the result */
2370 if (list_length(newargs) == 1)
2371 return (Node *) linitial(newargs);
2372 /* Else we still need an OR node */
2373 return (Node *) make_orclause(newargs);
2378 bool haveNull = false;
2379 bool forceFalse = false;
2381 newargs = simplify_and_arguments(expr->args, context,
2382 &haveNull, &forceFalse);
2384 return makeBoolConst(false, false);
2386 newargs = lappend(newargs, makeBoolConst(false, true));
2387 /* If all the inputs are TRUE, result is TRUE */
2389 return makeBoolConst(true, false);
2390 /* If only one nonconst-or-NULL input, it's the result */
2391 if (list_length(newargs) == 1)
2392 return (Node *) linitial(newargs);
2393 /* Else we still need an AND node */
2394 return (Node *) make_andclause(newargs);
2400 Assert(list_length(expr->args) == 1);
2401 arg = eval_const_expressions_mutator(linitial(expr->args),
2405 * Use negate_clause() to see if we can simplify away
2408 return negate_clause(arg);
2411 elog(ERROR, "unrecognized boolop: %d",
2412 (int) expr->boolop);
2416 if (IsA(node, SubPlan) ||
2417 IsA(node, AlternativeSubPlan))
2420 * Return a SubPlan unchanged --- too late to do anything with it.
2422 * XXX should we ereport() here instead? Probably this routine should
2423 * never be invoked after SubPlan creation.
2427 if (IsA(node, RelabelType))
2430 * If we can simplify the input to a constant, then we don't need the
2431 * RelabelType node anymore: just change the type field of the Const
2432 * node. Otherwise, must copy the RelabelType node.
2434 RelabelType *relabel = (RelabelType *) node;
2437 arg = eval_const_expressions_mutator((Node *) relabel->arg,
2441 * If we find stacked RelabelTypes (eg, from foo :: int :: oid) we can
2442 * discard all but the top one.
2444 while (arg && IsA(arg, RelabelType))
2445 arg = (Node *) ((RelabelType *) arg)->arg;
2447 if (arg && IsA(arg, Const))
2449 Const *con = (Const *) arg;
2451 con->consttype = relabel->resulttype;
2452 con->consttypmod = relabel->resulttypmod;
2453 return (Node *) con;
2457 RelabelType *newrelabel = makeNode(RelabelType);
2459 newrelabel->arg = (Expr *) arg;
2460 newrelabel->resulttype = relabel->resulttype;
2461 newrelabel->resulttypmod = relabel->resulttypmod;
2462 newrelabel->relabelformat = relabel->relabelformat;
2463 newrelabel->location = relabel->location;
2464 return (Node *) newrelabel;
2467 if (IsA(node, CoerceViaIO))
2469 CoerceViaIO *expr = (CoerceViaIO *) node;
2473 bool outtypisvarlena;
2477 CoerceViaIO *newexpr;
2480 * Reduce constants in the CoerceViaIO's argument.
2482 arg = (Expr *) eval_const_expressions_mutator((Node *) expr->arg,
2484 args = list_make1(arg);
2487 * CoerceViaIO represents calling the source type's output function
2488 * then the result type's input function. So, try to simplify it as
2489 * though it were a stack of two such function calls. First we need
2490 * to know what the functions are.
2492 getTypeOutputInfo(exprType((Node *) arg), &outfunc, &outtypisvarlena);
2493 getTypeInputInfo(expr->resulttype, &infunc, &intypioparam);
2495 simple = simplify_function(outfunc,
2498 false, true, context);
2499 if (simple) /* successfully simplified output fn */
2502 * Input functions may want 1 to 3 arguments. We always supply
2503 * all three, trusting that nothing downstream will complain.
2505 args = list_make3(simple,
2506 makeConst(OIDOID, -1, sizeof(Oid),
2507 ObjectIdGetDatum(intypioparam),
2509 makeConst(INT4OID, -1, sizeof(int32),
2513 simple = simplify_function(infunc,
2514 expr->resulttype, -1,
2516 false, true, context);
2517 if (simple) /* successfully simplified input fn */
2518 return (Node *) simple;
2522 * The expression cannot be simplified any further, so build and
2523 * return a replacement CoerceViaIO node using the possibly-simplified
2526 newexpr = makeNode(CoerceViaIO);
2528 newexpr->resulttype = expr->resulttype;
2529 newexpr->coerceformat = expr->coerceformat;
2530 newexpr->location = expr->location;
2531 return (Node *) newexpr;
2533 if (IsA(node, ArrayCoerceExpr))
2535 ArrayCoerceExpr *expr = (ArrayCoerceExpr *) node;
2537 ArrayCoerceExpr *newexpr;
2540 * Reduce constants in the ArrayCoerceExpr's argument, then build a
2541 * new ArrayCoerceExpr.
2543 arg = (Expr *) eval_const_expressions_mutator((Node *) expr->arg,
2546 newexpr = makeNode(ArrayCoerceExpr);
2548 newexpr->elemfuncid = expr->elemfuncid;
2549 newexpr->resulttype = expr->resulttype;
2550 newexpr->resulttypmod = expr->resulttypmod;
2551 newexpr->isExplicit = expr->isExplicit;
2552 newexpr->coerceformat = expr->coerceformat;
2553 newexpr->location = expr->location;
2556 * If constant argument and it's a binary-coercible or immutable
2557 * conversion, we can simplify it to a constant.
2559 if (arg && IsA(arg, Const) &&
2560 (!OidIsValid(newexpr->elemfuncid) ||
2561 func_volatile(newexpr->elemfuncid) == PROVOLATILE_IMMUTABLE))
2562 return (Node *) evaluate_expr((Expr *) newexpr,
2563 newexpr->resulttype,
2564 newexpr->resulttypmod);
2566 /* Else we must return the partially-simplified node */
2567 return (Node *) newexpr;
2569 if (IsA(node, CaseExpr))
2572 * CASE expressions can be simplified if there are constant
2573 * condition clauses:
2574 * FALSE (or NULL): drop the alternative
2575 * TRUE: drop all remaining alternatives
2576 * If the first non-FALSE alternative is a constant TRUE, we can
2577 * simplify the entire CASE to that alternative's expression.
2578 * If there are no non-FALSE alternatives, we simplify the entire
2579 * CASE to the default result (ELSE result).
2581 * If we have a simple-form CASE with constant test expression,
2582 * we substitute the constant value for contained CaseTestExpr
2583 * placeholder nodes, so that we have the opportunity to reduce
2584 * constant test conditions. For example this allows
2585 * CASE 0 WHEN 0 THEN 1 ELSE 1/0 END
2586 * to reduce to 1 rather than drawing a divide-by-0 error.
2589 CaseExpr *caseexpr = (CaseExpr *) node;
2591 Node *save_case_val;
2594 bool const_true_cond;
2595 Node *defresult = NULL;
2598 /* Simplify the test expression, if any */
2599 newarg = eval_const_expressions_mutator((Node *) caseexpr->arg,
2602 /* Set up for contained CaseTestExpr nodes */
2603 save_case_val = context->case_val;
2604 if (newarg && IsA(newarg, Const))
2605 context->case_val = newarg;
2607 context->case_val = NULL;
2609 /* Simplify the WHEN clauses */
2611 const_true_cond = false;
2612 foreach(arg, caseexpr->args)
2614 CaseWhen *oldcasewhen = (CaseWhen *) lfirst(arg);
2618 Assert(IsA(oldcasewhen, CaseWhen));
2620 /* Simplify this alternative's test condition */
2622 eval_const_expressions_mutator((Node *) oldcasewhen->expr,
2626 * If the test condition is constant FALSE (or NULL), then drop
2627 * this WHEN clause completely, without processing the result.
2629 if (casecond && IsA(casecond, Const))
2631 Const *const_input = (Const *) casecond;
2633 if (const_input->constisnull ||
2634 !DatumGetBool(const_input->constvalue))
2635 continue; /* drop alternative with FALSE condition */
2636 /* Else it's constant TRUE */
2637 const_true_cond = true;
2640 /* Simplify this alternative's result value */
2642 eval_const_expressions_mutator((Node *) oldcasewhen->result,
2645 /* If non-constant test condition, emit a new WHEN node */
2646 if (!const_true_cond)
2648 CaseWhen *newcasewhen = makeNode(CaseWhen);
2650 newcasewhen->expr = (Expr *) casecond;
2651 newcasewhen->result = (Expr *) caseresult;
2652 newcasewhen->location = oldcasewhen->location;
2653 newargs = lappend(newargs, newcasewhen);
2658 * Found a TRUE condition, so none of the remaining alternatives
2659 * can be reached. We treat the result as the default result.
2661 defresult = caseresult;
2665 /* Simplify the default result, unless we replaced it above */
2666 if (!const_true_cond)
2668 eval_const_expressions_mutator((Node *) caseexpr->defresult,
2671 context->case_val = save_case_val;
2673 /* If no non-FALSE alternatives, CASE reduces to the default result */
2676 /* Otherwise we need a new CASE node */
2677 newcase = makeNode(CaseExpr);
2678 newcase->casetype = caseexpr->casetype;
2679 newcase->arg = (Expr *) newarg;
2680 newcase->args = newargs;
2681 newcase->defresult = (Expr *) defresult;
2682 newcase->location = caseexpr->location;
2683 return (Node *) newcase;
2685 if (IsA(node, CaseTestExpr))
2688 * If we know a constant test value for the current CASE construct,
2689 * substitute it for the placeholder. Else just return the
2690 * placeholder as-is.
2692 if (context->case_val)
2693 return copyObject(context->case_val);
2695 return copyObject(node);
2697 if (IsA(node, ArrayExpr))
2699 ArrayExpr *arrayexpr = (ArrayExpr *) node;
2700 ArrayExpr *newarray;
2701 bool all_const = true;
2706 foreach(element, arrayexpr->elements)
2710 e = eval_const_expressions_mutator((Node *) lfirst(element),
2714 newelems = lappend(newelems, e);
2717 newarray = makeNode(ArrayExpr);
2718 newarray->array_typeid = arrayexpr->array_typeid;
2719 newarray->element_typeid = arrayexpr->element_typeid;
2720 newarray->elements = newelems;
2721 newarray->multidims = arrayexpr->multidims;
2722 newarray->location = arrayexpr->location;
2725 return (Node *) evaluate_expr((Expr *) newarray,
2726 newarray->array_typeid,
2729 return (Node *) newarray;
2731 if (IsA(node, CoalesceExpr))
2733 CoalesceExpr *coalesceexpr = (CoalesceExpr *) node;
2734 CoalesceExpr *newcoalesce;
2739 foreach(arg, coalesceexpr->args)
2743 e = eval_const_expressions_mutator((Node *) lfirst(arg),
2747 * We can remove null constants from the list. For a non-null
2748 * constant, if it has not been preceded by any other
2749 * non-null-constant expressions then it is the result. Otherwise,
2750 * it's the next argument, but we can drop following arguments
2751 * since they will never be reached.
2755 if (((Const *) e)->constisnull)
2756 continue; /* drop null constant */
2758 return e; /* first expr */
2759 newargs = lappend(newargs, e);
2762 newargs = lappend(newargs, e);
2765 /* If all the arguments were constant null, the result is just null */
2767 return (Node *) makeNullConst(coalesceexpr->coalescetype, -1);
2769 newcoalesce = makeNode(CoalesceExpr);
2770 newcoalesce->coalescetype = coalesceexpr->coalescetype;
2771 newcoalesce->args = newargs;
2772 newcoalesce->location = coalesceexpr->location;
2773 return (Node *) newcoalesce;
2775 if (IsA(node, FieldSelect))
2778 * We can optimize field selection from a whole-row Var into a simple
2779 * Var. (This case won't be generated directly by the parser, because
2780 * ParseComplexProjection short-circuits it. But it can arise while
2781 * simplifying functions.) Also, we can optimize field selection from
2782 * a RowExpr construct.
2784 * We must however check that the declared type of the field is still
2785 * the same as when the FieldSelect was created --- this can change if
2786 * someone did ALTER COLUMN TYPE on the rowtype.
2788 FieldSelect *fselect = (FieldSelect *) node;
2789 FieldSelect *newfselect;
2792 arg = eval_const_expressions_mutator((Node *) fselect->arg,
2794 if (arg && IsA(arg, Var) &&
2795 ((Var *) arg)->varattno == InvalidAttrNumber)
2797 if (rowtype_field_matches(((Var *) arg)->vartype,
2799 fselect->resulttype,
2800 fselect->resulttypmod))
2801 return (Node *) makeVar(((Var *) arg)->varno,
2803 fselect->resulttype,
2804 fselect->resulttypmod,
2805 ((Var *) arg)->varlevelsup);
2807 if (arg && IsA(arg, RowExpr))
2809 RowExpr *rowexpr = (RowExpr *) arg;
2811 if (fselect->fieldnum > 0 &&
2812 fselect->fieldnum <= list_length(rowexpr->args))
2814 Node *fld = (Node *) list_nth(rowexpr->args,
2815 fselect->fieldnum - 1);
2817 if (rowtype_field_matches(rowexpr->row_typeid,
2819 fselect->resulttype,
2820 fselect->resulttypmod) &&
2821 fselect->resulttype == exprType(fld) &&
2822 fselect->resulttypmod == exprTypmod(fld))
2826 newfselect = makeNode(FieldSelect);
2827 newfselect->arg = (Expr *) arg;
2828 newfselect->fieldnum = fselect->fieldnum;
2829 newfselect->resulttype = fselect->resulttype;
2830 newfselect->resulttypmod = fselect->resulttypmod;
2831 return (Node *) newfselect;
2833 if (IsA(node, NullTest))
2835 NullTest *ntest = (NullTest *) node;
2839 arg = eval_const_expressions_mutator((Node *) ntest->arg,
2841 if (arg && IsA(arg, RowExpr))
2844 * We break ROW(...) IS [NOT] NULL into separate tests on its
2845 * component fields. This form is usually more efficient to
2846 * evaluate, as well as being more amenable to optimization.
2848 RowExpr *rarg = (RowExpr *) arg;
2849 List *newargs = NIL;
2852 Assert(ntest->argisrow);
2854 foreach(l, rarg->args)
2856 Node *relem = (Node *) lfirst(l);
2859 * A constant field refutes the whole NullTest if it's of the
2860 * wrong nullness; else we can discard it.
2862 if (relem && IsA(relem, Const))
2864 Const *carg = (Const *) relem;
2866 if (carg->constisnull ?
2867 (ntest->nulltesttype == IS_NOT_NULL) :
2868 (ntest->nulltesttype == IS_NULL))
2869 return makeBoolConst(false, false);
2872 newntest = makeNode(NullTest);
2873 newntest->arg = (Expr *) relem;
2874 newntest->nulltesttype = ntest->nulltesttype;
2875 newntest->argisrow = type_is_rowtype(exprType(relem));
2876 newargs = lappend(newargs, newntest);
2878 /* If all the inputs were constants, result is TRUE */
2880 return makeBoolConst(true, false);
2881 /* If only one nonconst input, it's the result */
2882 if (list_length(newargs) == 1)
2883 return (Node *) linitial(newargs);
2884 /* Else we need an AND node */
2885 return (Node *) make_andclause(newargs);
2887 if (!ntest->argisrow && arg && IsA(arg, Const))
2889 Const *carg = (Const *) arg;
2892 switch (ntest->nulltesttype)
2895 result = carg->constisnull;
2898 result = !carg->constisnull;
2901 elog(ERROR, "unrecognized nulltesttype: %d",
2902 (int) ntest->nulltesttype);
2903 result = false; /* keep compiler quiet */
2907 return makeBoolConst(result, false);
2910 newntest = makeNode(NullTest);
2911 newntest->arg = (Expr *) arg;
2912 newntest->nulltesttype = ntest->nulltesttype;
2913 newntest->argisrow = ntest->argisrow;
2914 return (Node *) newntest;
2916 if (IsA(node, BooleanTest))
2918 BooleanTest *btest = (BooleanTest *) node;
2919 BooleanTest *newbtest;
2922 arg = eval_const_expressions_mutator((Node *) btest->arg,
2924 if (arg && IsA(arg, Const))
2926 Const *carg = (Const *) arg;
2929 switch (btest->booltesttype)
2932 result = (!carg->constisnull &&
2933 DatumGetBool(carg->constvalue));
2936 result = (carg->constisnull ||
2937 !DatumGetBool(carg->constvalue));
2940 result = (!carg->constisnull &&
2941 !DatumGetBool(carg->constvalue));
2944 result = (carg->constisnull ||
2945 DatumGetBool(carg->constvalue));
2948 result = carg->constisnull;
2950 case IS_NOT_UNKNOWN:
2951 result = !carg->constisnull;
2954 elog(ERROR, "unrecognized booltesttype: %d",
2955 (int) btest->booltesttype);
2956 result = false; /* keep compiler quiet */
2960 return makeBoolConst(result, false);
2963 newbtest = makeNode(BooleanTest);
2964 newbtest->arg = (Expr *) arg;
2965 newbtest->booltesttype = btest->booltesttype;
2966 return (Node *) newbtest;
2968 if (IsA(node, PlaceHolderVar) &&context->estimate)
2971 * In estimation mode, just strip the PlaceHolderVar node altogether;
2972 * this amounts to estimating that the contained value won't be forced
2973 * to null by an outer join. In regular mode we just use the default
2974 * behavior (ie, simplify the expression but leave the PlaceHolderVar
2977 PlaceHolderVar *phv = (PlaceHolderVar *) node;
2979 return eval_const_expressions_mutator((Node *) phv->phexpr,
2984 * For any node type not handled above, we recurse using
2985 * expression_tree_mutator, which will copy the node unchanged but try to
2986 * simplify its arguments (if any) using this routine. For example: we
2987 * cannot eliminate an ArrayRef node, but we might be able to simplify
2988 * constant expressions in its subscripts.
2990 return expression_tree_mutator(node, eval_const_expressions_mutator,
2995 * Subroutine for eval_const_expressions: process arguments of an OR clause
2997 * This includes flattening of nested ORs as well as recursion to
2998 * eval_const_expressions to simplify the OR arguments.
3000 * After simplification, OR arguments are handled as follows:
3001 * non constant: keep
3002 * FALSE: drop (does not affect result)
3003 * TRUE: force result to TRUE
3004 * NULL: keep only one
3005 * We must keep one NULL input because ExecEvalOr returns NULL when no input
3006 * is TRUE and at least one is NULL. We don't actually include the NULL
3007 * here, that's supposed to be done by the caller.
3009 * The output arguments *haveNull and *forceTrue must be initialized FALSE
3010 * by the caller. They will be set TRUE if a null constant or true constant,
3011 * respectively, is detected anywhere in the argument list.
3014 simplify_or_arguments(List *args,
3015 eval_const_expressions_context *context,
3016 bool *haveNull, bool *forceTrue)
3018 List *newargs = NIL;
3019 List *unprocessed_args;
3022 * Since the parser considers OR to be a binary operator, long OR lists
3023 * become deeply nested expressions. We must flatten these into long
3024 * argument lists of a single OR operator. To avoid blowing out the stack
3025 * with recursion of eval_const_expressions, we resort to some tenseness
3026 * here: we keep a list of not-yet-processed inputs, and handle flattening
3027 * of nested ORs by prepending to the to-do list instead of recursing.
3029 unprocessed_args = list_copy(args);
3030 while (unprocessed_args)
3032 Node *arg = (Node *) linitial(unprocessed_args);
3034 unprocessed_args = list_delete_first(unprocessed_args);
3036 /* flatten nested ORs as per above comment */
3039 List *subargs = list_copy(((BoolExpr *) arg)->args);
3041 /* overly tense code to avoid leaking unused list header */
3042 if (!unprocessed_args)
3043 unprocessed_args = subargs;
3046 List *oldhdr = unprocessed_args;
3048 unprocessed_args = list_concat(subargs, unprocessed_args);
3054 /* If it's not an OR, simplify it */
3055 arg = eval_const_expressions_mutator(arg, context);
3058 * It is unlikely but not impossible for simplification of a non-OR
3059 * clause to produce an OR. Recheck, but don't be too tense about it
3060 * since it's not a mainstream case. In particular we don't worry
3061 * about const-simplifying the input twice.
3065 List *subargs = list_copy(((BoolExpr *) arg)->args);
3067 unprocessed_args = list_concat(subargs, unprocessed_args);
3072 * OK, we have a const-simplified non-OR argument. Process it per
3075 if (IsA(arg, Const))
3077 Const *const_input = (Const *) arg;
3079 if (const_input->constisnull)
3081 else if (DatumGetBool(const_input->constvalue))
3086 * Once we detect a TRUE result we can just exit the loop
3087 * immediately. However, if we ever add a notion of
3088 * non-removable functions, we'd need to keep scanning.
3092 /* otherwise, we can drop the constant-false input */
3096 /* else emit the simplified arg into the result list */
3097 newargs = lappend(newargs, arg);
3104 * Subroutine for eval_const_expressions: process arguments of an AND clause
3106 * This includes flattening of nested ANDs as well as recursion to
3107 * eval_const_expressions to simplify the AND arguments.
3109 * After simplification, AND arguments are handled as follows:
3110 * non constant: keep
3111 * TRUE: drop (does not affect result)
3112 * FALSE: force result to FALSE
3113 * NULL: keep only one
3114 * We must keep one NULL input because ExecEvalAnd returns NULL when no input
3115 * is FALSE and at least one is NULL. We don't actually include the NULL
3116 * here, that's supposed to be done by the caller.
3118 * The output arguments *haveNull and *forceFalse must be initialized FALSE
3119 * by the caller. They will be set TRUE if a null constant or false constant,
3120 * respectively, is detected anywhere in the argument list.
3123 simplify_and_arguments(List *args,
3124 eval_const_expressions_context *context,
3125 bool *haveNull, bool *forceFalse)
3127 List *newargs = NIL;
3128 List *unprocessed_args;
3130 /* See comments in simplify_or_arguments */
3131 unprocessed_args = list_copy(args);
3132 while (unprocessed_args)
3134 Node *arg = (Node *) linitial(unprocessed_args);
3136 unprocessed_args = list_delete_first(unprocessed_args);
3138 /* flatten nested ANDs as per above comment */
3139 if (and_clause(arg))
3141 List *subargs = list_copy(((BoolExpr *) arg)->args);
3143 /* overly tense code to avoid leaking unused list header */
3144 if (!unprocessed_args)
3145 unprocessed_args = subargs;
3148 List *oldhdr = unprocessed_args;
3150 unprocessed_args = list_concat(subargs, unprocessed_args);
3156 /* If it's not an AND, simplify it */
3157 arg = eval_const_expressions_mutator(arg, context);
3160 * It is unlikely but not impossible for simplification of a non-AND
3161 * clause to produce an AND. Recheck, but don't be too tense about it
3162 * since it's not a mainstream case. In particular we don't worry
3163 * about const-simplifying the input twice.
3165 if (and_clause(arg))
3167 List *subargs = list_copy(((BoolExpr *) arg)->args);
3169 unprocessed_args = list_concat(subargs, unprocessed_args);
3174 * OK, we have a const-simplified non-AND argument. Process it per
3177 if (IsA(arg, Const))
3179 Const *const_input = (Const *) arg;
3181 if (const_input->constisnull)
3183 else if (!DatumGetBool(const_input->constvalue))
3188 * Once we detect a FALSE result we can just exit the loop
3189 * immediately. However, if we ever add a notion of
3190 * non-removable functions, we'd need to keep scanning.
3194 /* otherwise, we can drop the constant-true input */
3198 /* else emit the simplified arg into the result list */
3199 newargs = lappend(newargs, arg);
3206 * Subroutine for eval_const_expressions: try to simplify boolean equality
3207 * or inequality condition
3209 * Inputs are the operator OID and the simplified arguments to the operator.
3210 * Returns a simplified expression if successful, or NULL if cannot
3211 * simplify the expression.
3213 * The idea here is to reduce "x = true" to "x" and "x = false" to "NOT x",
3214 * or similarly "x <> true" to "NOT x" and "x <> false" to "x".
3215 * This is only marginally useful in itself, but doing it in constant folding
3216 * ensures that we will recognize these forms as being equivalent in, for
3217 * example, partial index matching.
3219 * We come here only if simplify_function has failed; therefore we cannot
3220 * see two constant inputs, nor a constant-NULL input.
3223 simplify_boolean_equality(Oid opno, List *args)
3228 Assert(list_length(args) == 2);
3229 leftop = linitial(args);
3230 rightop = lsecond(args);
3231 if (leftop && IsA(leftop, Const))
3233 Assert(!((Const *) leftop)->constisnull);
3234 if (opno == BooleanEqualOperator)
3236 if (DatumGetBool(((Const *) leftop)->constvalue))
3237 return rightop; /* true = foo */
3239 return negate_clause(rightop); /* false = foo */
3243 if (DatumGetBool(((Const *) leftop)->constvalue))
3244 return negate_clause(rightop); /* true <> foo */
3246 return rightop; /* false <> foo */
3249 if (rightop && IsA(rightop, Const))
3251 Assert(!((Const *) rightop)->constisnull);
3252 if (opno == BooleanEqualOperator)
3254 if (DatumGetBool(((Const *) rightop)->constvalue))
3255 return leftop; /* foo = true */
3257 return negate_clause(leftop); /* foo = false */
3261 if (DatumGetBool(((Const *) rightop)->constvalue))
3262 return negate_clause(leftop); /* foo <> true */
3264 return leftop; /* foo <> false */
3271 * Subroutine for eval_const_expressions: try to simplify a function call
3272 * (which might originally have been an operator; we don't care)
3274 * Inputs are the function OID, actual result type OID (which is needed for
3275 * polymorphic functions) and typmod, and the pre-simplified argument list;
3276 * also the context data for eval_const_expressions.
3278 * Returns a simplified expression if successful, or NULL if cannot
3279 * simplify the function call.
3281 * This function is also responsible for converting named-notation argument
3282 * lists into positional notation and/or adding any needed default argument
3283 * expressions; which is a bit grotty, but it avoids an extra fetch of the
3284 * function's pg_proc tuple. For this reason, the args list is
3285 * pass-by-reference, and it may get modified even if simplification fails.
3288 simplify_function(Oid funcid, Oid result_type, int32 result_typmod,
3290 bool has_named_args,
3292 eval_const_expressions_context *context)
3294 HeapTuple func_tuple;
3298 * We have two strategies for simplification: either execute the function
3299 * to deliver a constant result, or expand in-line the body of the
3300 * function definition (which only works for simple SQL-language
3301 * functions, but that is a common case). In either case we need access
3302 * to the function's pg_proc tuple, so fetch it just once to use in both
3305 func_tuple = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcid));
3306 if (!HeapTupleIsValid(func_tuple))
3307 elog(ERROR, "cache lookup failed for function %u", funcid);
3310 * While we have the tuple, reorder named arguments and add default
3311 * arguments if needed.
3314 *args = reorder_function_arguments(*args, result_type, func_tuple,
3316 else if (((Form_pg_proc) GETSTRUCT(func_tuple))->pronargs > list_length(*args))
3317 *args = add_function_defaults(*args, result_type, func_tuple, context);
3319 newexpr = evaluate_function(funcid, result_type, result_typmod, *args,
3320 func_tuple, context);
3322 if (!newexpr && allow_inline)
3323 newexpr = inline_function(funcid, result_type, *args,
3324 func_tuple, context);
3326 ReleaseSysCache(func_tuple);
3332 * reorder_function_arguments: convert named-notation args to positional args
3334 * This function also inserts default argument values as needed, since it's
3335 * impossible to form a truly valid positional call without that.
3338 reorder_function_arguments(List *args, Oid result_type, HeapTuple func_tuple,
3339 eval_const_expressions_context *context)
3341 Form_pg_proc funcform = (Form_pg_proc) GETSTRUCT(func_tuple);
3342 int pronargs = funcform->pronargs;
3343 int nargsprovided = list_length(args);
3344 Node *argarray[FUNC_MAX_ARGS];
3345 Bitmapset *defargnumbers;
3349 Assert(nargsprovided <= pronargs);
3350 if (pronargs > FUNC_MAX_ARGS)
3351 elog(ERROR, "too many function arguments");
3352 MemSet(argarray, 0, pronargs * sizeof(Node *));
3354 /* Deconstruct the argument list into an array indexed by argnumber */
3358 Node *arg = (Node *) lfirst(lc);
3360 if (!IsA(arg, NamedArgExpr))
3362 /* positional argument, assumed to precede all named args */
3363 Assert(argarray[i] == NULL);
3364 argarray[i++] = arg;
3368 NamedArgExpr *na = (NamedArgExpr *) arg;
3370 Assert(argarray[na->argnumber] == NULL);
3371 argarray[na->argnumber] = (Node *) na->arg;
3376 * Fetch default expressions, if needed, and insert into array at proper
3377 * locations (they aren't necessarily consecutive or all used)
3379 defargnumbers = NULL;
3380 if (nargsprovided < pronargs)
3382 List *defaults = fetch_function_defaults(func_tuple);
3384 i = pronargs - funcform->pronargdefaults;
3385 foreach(lc, defaults)
3387 if (argarray[i] == NULL)
3389 argarray[i] = (Node *) lfirst(lc);
3390 defargnumbers = bms_add_member(defargnumbers, i);
3396 /* Now reconstruct the args list in proper order */
3398 for (i = 0; i < pronargs; i++)
3400 Assert(argarray[i] != NULL);
3401 args = lappend(args, argarray[i]);
3404 /* Recheck argument types and add casts if needed */
3405 recheck_cast_function_args(args, result_type, func_tuple);
3408 * Lastly, we have to recursively simplify the defaults we just added (but
3409 * don't recurse on the args passed in, as we already did those). This
3410 * isn't merely an optimization, it's *necessary* since there could be
3411 * functions with named or defaulted arguments down in there.
3413 * Note that we do this last in hopes of simplifying any typecasts that
3414 * were added by recheck_cast_function_args --- there shouldn't be any new
3415 * casts added to the explicit arguments, but casts on the defaults are
3418 if (defargnumbers != NULL)
3423 if (bms_is_member(i, defargnumbers))
3424 lfirst(lc) = eval_const_expressions_mutator((Node *) lfirst(lc),
3434 * add_function_defaults: add missing function arguments from its defaults
3436 * This is used only when the argument list was positional to begin with,
3437 * and so we know we just need to add defaults at the end.
3440 add_function_defaults(List *args, Oid result_type, HeapTuple func_tuple,
3441 eval_const_expressions_context *context)
3443 Form_pg_proc funcform = (Form_pg_proc) GETSTRUCT(func_tuple);
3444 int nargsprovided = list_length(args);
3449 /* Get all the default expressions from the pg_proc tuple */
3450 defaults = fetch_function_defaults(func_tuple);
3452 /* Delete any unused defaults from the list */
3453 ndelete = nargsprovided + list_length(defaults) - funcform->pronargs;
3455 elog(ERROR, "not enough default arguments");
3456 while (ndelete-- > 0)
3457 defaults = list_delete_first(defaults);
3459 /* And form the combined argument list */
3460 args = list_concat(args, defaults);
3462 /* Recheck argument types and add casts if needed */
3463 recheck_cast_function_args(args, result_type, func_tuple);
3466 * Lastly, we have to recursively simplify the defaults we just added (but
3467 * don't recurse on the args passed in, as we already did those). This
3468 * isn't merely an optimization, it's *necessary* since there could be
3469 * functions with named or defaulted arguments down in there.
3471 * Note that we do this last in hopes of simplifying any typecasts that
3472 * were added by recheck_cast_function_args --- there shouldn't be any new
3473 * casts added to the explicit arguments, but casts on the defaults are
3478 if (nargsprovided-- > 0)
3479 continue; /* skip original arg positions */
3480 lfirst(lc) = eval_const_expressions_mutator((Node *) lfirst(lc),
3488 * fetch_function_defaults: get function's default arguments as expression list
3491 fetch_function_defaults(HeapTuple func_tuple)
3494 Datum proargdefaults;
3498 /* The error cases here shouldn't happen, but check anyway */
3499 proargdefaults = SysCacheGetAttr(PROCOID, func_tuple,
3500 Anum_pg_proc_proargdefaults,
3503 elog(ERROR, "not enough default arguments");
3504 str = TextDatumGetCString(proargdefaults);
3505 defaults = (List *) stringToNode(str);
3506 Assert(IsA(defaults, List));
3512 * recheck_cast_function_args: recheck function args and typecast as needed
3513 * after adding defaults.
3515 * It is possible for some of the defaulted arguments to be polymorphic;
3516 * therefore we can't assume that the default expressions have the correct
3517 * data types already. We have to re-resolve polymorphics and do coercion
3518 * just like the parser did.
3520 * This should be a no-op if there are no polymorphic arguments,
3521 * but we do it anyway to be sure.
3523 * Note: if any casts are needed, the args list is modified in-place.
3526 recheck_cast_function_args(List *args, Oid result_type, HeapTuple func_tuple)
3528 Form_pg_proc funcform = (Form_pg_proc) GETSTRUCT(func_tuple);
3530 Oid actual_arg_types[FUNC_MAX_ARGS];
3531 Oid declared_arg_types[FUNC_MAX_ARGS];
3535 if (list_length(args) > FUNC_MAX_ARGS)
3536 elog(ERROR, "too many function arguments");
3540 actual_arg_types[nargs++] = exprType((Node *) lfirst(lc));
3542 Assert(nargs == funcform->pronargs);
3543 memcpy(declared_arg_types, funcform->proargtypes.values,
3544 funcform->pronargs * sizeof(Oid));
3545 rettype = enforce_generic_type_consistency(actual_arg_types,
3548 funcform->prorettype,
3550 /* let's just check we got the same answer as the parser did ... */
3551 if (rettype != result_type)
3552 elog(ERROR, "function's resolved result type changed during planning");
3554 /* perform any necessary typecasting of arguments */
3555 make_fn_arguments(NULL, args, actual_arg_types, declared_arg_types);
3559 * evaluate_function: try to pre-evaluate a function call
3561 * We can do this if the function is strict and has any constant-null inputs
3562 * (just return a null constant), or if the function is immutable and has all
3563 * constant inputs (call it and return the result as a Const node). In
3564 * estimation mode we are willing to pre-evaluate stable functions too.
3566 * Returns a simplified expression if successful, or NULL if cannot
3567 * simplify the function.
3570 evaluate_function(Oid funcid, Oid result_type, int32 result_typmod, List *args,
3571 HeapTuple func_tuple,
3572 eval_const_expressions_context *context)
3574 Form_pg_proc funcform = (Form_pg_proc) GETSTRUCT(func_tuple);
3575 bool has_nonconst_input = false;
3576 bool has_null_input = false;
3581 * Can't simplify if it returns a set.
3583 if (funcform->proretset)
3587 * Can't simplify if it returns RECORD. The immediate problem is that it
3588 * will be needing an expected tupdesc which we can't supply here.
3590 * In the case where it has OUT parameters, it could get by without an
3591 * expected tupdesc, but we still have issues: get_expr_result_type()
3592 * doesn't know how to extract type info from a RECORD constant, and in
3593 * the case of a NULL function result there doesn't seem to be any clean
3594 * way to fix that. In view of the likelihood of there being still other
3595 * gotchas, seems best to leave the function call unreduced.
3597 if (funcform->prorettype == RECORDOID)
3601 * Check for constant inputs and especially constant-NULL inputs.
3605 if (IsA(lfirst(arg), Const))
3606 has_null_input |= ((Const *) lfirst(arg))->constisnull;
3608 has_nonconst_input = true;
3612 * If the function is strict and has a constant-NULL input, it will never
3613 * be called at all, so we can replace the call by a NULL constant, even
3614 * if there are other inputs that aren't constant, and even if the
3615 * function is not otherwise immutable.
3617 if (funcform->proisstrict && has_null_input)
3618 return (Expr *) makeNullConst(result_type, result_typmod);
3621 * Otherwise, can simplify only if all inputs are constants. (For a
3622 * non-strict function, constant NULL inputs are treated the same as
3623 * constant non-NULL inputs.)
3625 if (has_nonconst_input)
3629 * Ordinarily we are only allowed to simplify immutable functions. But for
3630 * purposes of estimation, we consider it okay to simplify functions that
3631 * are merely stable; the risk that the result might change from planning
3632 * time to execution time is worth taking in preference to not being able
3633 * to estimate the value at all.
3635 if (funcform->provolatile == PROVOLATILE_IMMUTABLE)
3637 else if (context->estimate && funcform->provolatile == PROVOLATILE_STABLE)
3643 * OK, looks like we can simplify this operator/function.
3645 * Build a new FuncExpr node containing the already-simplified arguments.
3647 newexpr = makeNode(FuncExpr);
3648 newexpr->funcid = funcid;
3649 newexpr->funcresulttype = result_type;
3650 newexpr->funcretset = false;
3651 newexpr->funcformat = COERCE_DONTCARE; /* doesn't matter */
3652 newexpr->args = args;
3653 newexpr->location = -1;
3655 return evaluate_expr((Expr *) newexpr, result_type, result_typmod);
3659 * inline_function: try to expand a function call inline
3661 * If the function is a sufficiently simple SQL-language function
3662 * (just "SELECT expression"), then we can inline it and avoid the rather
3663 * high per-call overhead of SQL functions. Furthermore, this can expose
3664 * opportunities for constant-folding within the function expression.
3666 * We have to beware of some special cases however. A directly or
3667 * indirectly recursive function would cause us to recurse forever,
3668 * so we keep track of which functions we are already expanding and
3669 * do not re-expand them. Also, if a parameter is used more than once
3670 * in the SQL-function body, we require it not to contain any volatile
3671 * functions (volatiles might deliver inconsistent answers) nor to be
3672 * unreasonably expensive to evaluate. The expensiveness check not only
3673 * prevents us from doing multiple evaluations of an expensive parameter
3674 * at runtime, but is a safety value to limit growth of an expression due
3675 * to repeated inlining.
3677 * We must also beware of changing the volatility or strictness status of
3678 * functions by inlining them.
3680 * Returns a simplified expression if successful, or NULL if cannot
3681 * simplify the function.
3684 inline_function(Oid funcid, Oid result_type, List *args,
3685 HeapTuple func_tuple,
3686 eval_const_expressions_context *context)
3688 Form_pg_proc funcform = (Form_pg_proc) GETSTRUCT(func_tuple);
3693 bool modifyTargetList;
3694 MemoryContext oldcxt;
3695 MemoryContext mycxt;
3696 inline_error_callback_arg callback_arg;
3697 ErrorContextCallback sqlerrcontext;
3698 List *raw_parsetree_list;
3706 * Forget it if the function is not SQL-language or has other showstopper
3707 * properties. (The nargs check is just paranoia.)
3709 if (funcform->prolang != SQLlanguageId ||
3710 funcform->prosecdef ||
3711 funcform->proretset ||
3712 !heap_attisnull(func_tuple, Anum_pg_proc_proconfig) ||
3713 funcform->pronargs != list_length(args))
3716 /* Check for recursive function, and give up trying to expand if so */
3717 if (list_member_oid(context->active_fns, funcid))
3720 /* Check permission to call function (fail later, if not) */
3721 if (pg_proc_aclcheck(funcid, GetUserId(), ACL_EXECUTE) != ACLCHECK_OK)
3725 * Make a temporary memory context, so that we don't leak all the stuff
3726 * that parsing might create.
3728 mycxt = AllocSetContextCreate(CurrentMemoryContext,
3730 ALLOCSET_DEFAULT_MINSIZE,
3731 ALLOCSET_DEFAULT_INITSIZE,
3732 ALLOCSET_DEFAULT_MAXSIZE);
3733 oldcxt = MemoryContextSwitchTo(mycxt);
3735 /* Fetch the function body */
3736 tmp = SysCacheGetAttr(PROCOID,
3738 Anum_pg_proc_prosrc,
3741 elog(ERROR, "null prosrc for function %u", funcid);
3742 src = TextDatumGetCString(tmp);
3745 * Setup error traceback support for ereport(). This is so that we can
3746 * finger the function that bad information came from.
3748 callback_arg.proname = NameStr(funcform->proname);
3749 callback_arg.prosrc = src;
3751 sqlerrcontext.callback = sql_inline_error_callback;
3752 sqlerrcontext.arg = (void *) &callback_arg;
3753 sqlerrcontext.previous = error_context_stack;
3754 error_context_stack = &sqlerrcontext;
3756 /* Check for polymorphic arguments, and substitute actual arg types */
3757 argtypes = (Oid *) palloc(funcform->pronargs * sizeof(Oid));
3758 memcpy(argtypes, funcform->proargtypes.values,
3759 funcform->pronargs * sizeof(Oid));
3760 for (i = 0; i < funcform->pronargs; i++)
3762 if (IsPolymorphicType(argtypes[i]))
3764 argtypes[i] = exprType((Node *) list_nth(args, i));
3769 * We just do parsing and parse analysis, not rewriting, because rewriting
3770 * will not affect table-free-SELECT-only queries, which is all that we
3771 * care about. Also, we can punt as soon as we detect more than one
3772 * command in the function body.
3774 raw_parsetree_list = pg_parse_query(src);
3775 if (list_length(raw_parsetree_list) != 1)
3778 querytree = parse_analyze(linitial(raw_parsetree_list), src,
3779 argtypes, funcform->pronargs);
3782 * The single command must be a simple "SELECT expression".
3784 if (!IsA(querytree, Query) ||
3785 querytree->commandType != CMD_SELECT ||
3786 querytree->utilityStmt ||
3787 querytree->intoClause ||
3788 querytree->hasAggs ||
3789 querytree->hasWindowFuncs ||
3790 querytree->hasSubLinks ||
3791 querytree->cteList ||
3792 querytree->rtable ||
3793 querytree->jointree->fromlist ||
3794 querytree->jointree->quals ||
3795 querytree->groupClause ||
3796 querytree->havingQual ||
3797 querytree->windowClause ||
3798 querytree->distinctClause ||
3799 querytree->sortClause ||
3800 querytree->limitOffset ||
3801 querytree->limitCount ||
3802 querytree->setOperations ||
3803 list_length(querytree->targetList) != 1)
3807 * Make sure the function (still) returns what it's declared to. This
3808 * will raise an error if wrong, but that's okay since the function would
3809 * fail at runtime anyway. Note that check_sql_fn_retval will also insert
3810 * a RelabelType if needed to make the tlist expression match the declared
3811 * type of the function.
3813 * Note: we do not try this until we have verified that no rewriting was
3814 * needed; that's probably not important, but let's be careful.
3816 if (check_sql_fn_retval(funcid, result_type, list_make1(querytree),
3817 &modifyTargetList, NULL))
3818 goto fail; /* reject whole-tuple-result cases */
3820 /* Now we can grab the tlist expression */
3821 newexpr = (Node *) ((TargetEntry *) linitial(querytree->targetList))->expr;
3823 /* Assert that check_sql_fn_retval did the right thing */
3824 Assert(exprType(newexpr) == result_type);
3825 /* It couldn't have made any dangerous tlist changes, either */
3826 Assert(!modifyTargetList);
3829 * Additional validity checks on the expression. It mustn't return a set,
3830 * and it mustn't be more volatile than the surrounding function (this is
3831 * to avoid breaking hacks that involve pretending a function is immutable
3832 * when it really ain't). If the surrounding function is declared strict,
3833 * then the expression must contain only strict constructs and must use
3834 * all of the function parameters (this is overkill, but an exact analysis
3837 if (expression_returns_set(newexpr))
3840 if (funcform->provolatile == PROVOLATILE_IMMUTABLE &&
3841 contain_mutable_functions(newexpr))
3843 else if (funcform->provolatile == PROVOLATILE_STABLE &&
3844 contain_volatile_functions(newexpr))
3847 if (funcform->proisstrict &&
3848 contain_nonstrict_functions(newexpr))
3852 * We may be able to do it; there are still checks on parameter usage to
3853 * make, but those are most easily done in combination with the actual
3854 * substitution of the inputs. So start building expression with inputs
3857 usecounts = (int *) palloc0(funcform->pronargs * sizeof(int));
3858 newexpr = substitute_actual_parameters(newexpr, funcform->pronargs,
3861 /* Now check for parameter usage */
3865 Node *param = lfirst(arg);
3867 if (usecounts[i] == 0)
3869 /* Param not used at all: uncool if func is strict */
3870 if (funcform->proisstrict)
3873 else if (usecounts[i] != 1)
3875 /* Param used multiple times: uncool if expensive or volatile */
3879 * We define "expensive" as "contains any subplan or more than 10
3880 * operators". Note that the subplan search has to be done
3881 * explicitly, since cost_qual_eval() will barf on unplanned
3884 if (contain_subplans(param))
3886 cost_qual_eval(&eval_cost, list_make1(param), NULL);
3887 if (eval_cost.startup + eval_cost.per_tuple >
3888 10 * cpu_operator_cost)
3892 * Check volatility last since this is more expensive than the
3895 if (contain_volatile_functions(param))
3902 * Whew --- we can make the substitution. Copy the modified expression
3903 * out of the temporary memory context, and clean up.
3905 MemoryContextSwitchTo(oldcxt);
3907 newexpr = copyObject(newexpr);
3909 MemoryContextDelete(mycxt);
3912 * Since there is now no trace of the function in the plan tree, we must
3913 * explicitly record the plan's dependency on the function.
3916 record_plan_function_dependency(context->glob, funcid);
3919 * Recursively try to simplify the modified expression. Here we must add
3920 * the current function to the context list of active functions.
3922 context->active_fns = lcons_oid(funcid, context->active_fns);
3923 newexpr = eval_const_expressions_mutator(newexpr, context);
3924 context->active_fns = list_delete_first(context->active_fns);
3926 error_context_stack = sqlerrcontext.previous;
3928 return (Expr *) newexpr;
3930 /* Here if func is not inlinable: release temp memory and return NULL */
3932 MemoryContextSwitchTo(oldcxt);
3933 MemoryContextDelete(mycxt);
3934 error_context_stack = sqlerrcontext.previous;
3940 * Replace Param nodes by appropriate actual parameters
3943 substitute_actual_parameters(Node *expr, int nargs, List *args,
3946 substitute_actual_parameters_context context;
3948 context.nargs = nargs;
3949 context.args = args;
3950 context.usecounts = usecounts;
3952 return substitute_actual_parameters_mutator(expr, &context);
3956 substitute_actual_parameters_mutator(Node *node,
3957 substitute_actual_parameters_context *context)
3961 if (IsA(node, Param))
3963 Param *param = (Param *) node;
3965 if (param->paramkind != PARAM_EXTERN)
3966 elog(ERROR, "unexpected paramkind: %d", (int) param->paramkind);
3967 if (param->paramid <= 0 || param->paramid > context->nargs)
3968 elog(ERROR, "invalid paramid: %d", param->paramid);
3970 /* Count usage of parameter */
3971 context->usecounts[param->paramid - 1]++;
3973 /* Select the appropriate actual arg and replace the Param with it */
3974 /* We don't need to copy at this time (it'll get done later) */
3975 return list_nth(context->args, param->paramid - 1);
3977 return expression_tree_mutator(node, substitute_actual_parameters_mutator,
3982 * error context callback to let us supply a call-stack traceback
3985 sql_inline_error_callback(void *arg)
3987 inline_error_callback_arg *callback_arg = (inline_error_callback_arg *) arg;
3988 int syntaxerrposition;
3990 /* If it's a syntax error, convert to internal syntax error report */
3991 syntaxerrposition = geterrposition();
3992 if (syntaxerrposition > 0)
3995 internalerrposition(syntaxerrposition);
3996 internalerrquery(callback_arg->prosrc);
3999 errcontext("SQL function \"%s\" during inlining", callback_arg->proname);
4003 * evaluate_expr: pre-evaluate a constant expression
4005 * We use the executor's routine ExecEvalExpr() to avoid duplication of
4006 * code and ensure we get the same result as the executor would get.
4009 evaluate_expr(Expr *expr, Oid result_type, int32 result_typmod)
4012 ExprState *exprstate;
4013 MemoryContext oldcontext;
4017 bool resultTypByVal;
4020 * To use the executor, we need an EState.
4022 estate = CreateExecutorState();
4024 /* We can use the estate's working context to avoid memory leaks. */
4025 oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
4027 /* Make sure any opfuncids are filled in. */
4028 fix_opfuncids((Node *) expr);
4031 * Prepare expr for execution. (Note: we can't use ExecPrepareExpr
4032 * because it'd result in recursively invoking eval_const_expressions.)
4034 exprstate = ExecInitExpr(expr, NULL);
4039 * It is OK to use a default econtext because none of the ExecEvalExpr()
4040 * code used in this situation will use econtext. That might seem
4041 * fortuitous, but it's not so unreasonable --- a constant expression does
4042 * not depend on context, by definition, n'est ce pas?
4044 const_val = ExecEvalExprSwitchContext(exprstate,
4045 GetPerTupleExprContext(estate),
4046 &const_is_null, NULL);
4048 /* Get info needed about result datatype */
4049 get_typlenbyval(result_type, &resultTypLen, &resultTypByVal);
4051 /* Get back to outer memory context */
4052 MemoryContextSwitchTo(oldcontext);
4055 * Must copy result out of sub-context used by expression eval.
4057 * Also, if it's varlena, forcibly detoast it. This protects us against
4058 * storing TOAST pointers into plans that might outlive the referenced
4063 if (resultTypLen == -1)
4064 const_val = PointerGetDatum(PG_DETOAST_DATUM_COPY(const_val));
4066 const_val = datumCopy(const_val, resultTypByVal, resultTypLen);
4069 /* Release all the junk we just created */
4070 FreeExecutorState(estate);
4073 * Make the constant result node.
4075 return (Expr *) makeConst(result_type, result_typmod, resultTypLen,
4076 const_val, const_is_null,
4082 * inline_set_returning_function
4083 * Attempt to "inline" a set-returning function in the FROM clause.
4085 * "rte" is an RTE_FUNCTION rangetable entry. If it represents a call of a
4086 * set-returning SQL function that can safely be inlined, expand the function
4087 * and return the substitute Query structure. Otherwise, return NULL.
4089 * This has a good deal of similarity to inline_function(), but that's
4090 * for the non-set-returning case, and there are enough differences to
4091 * justify separate functions.
4094 inline_set_returning_function(PlannerInfo *root, RangeTblEntry *rte)
4098 HeapTuple func_tuple;
4099 Form_pg_proc funcform;
4104 bool modifyTargetList;
4105 MemoryContext oldcxt;
4106 MemoryContext mycxt;
4107 List *saveInvalItems;
4108 inline_error_callback_arg callback_arg;
4109 ErrorContextCallback sqlerrcontext;
4110 List *raw_parsetree_list;
4111 List *querytree_list;
4115 Assert(rte->rtekind == RTE_FUNCTION);
4118 * It doesn't make a lot of sense for a SQL SRF to refer to itself in its
4119 * own FROM clause, since that must cause infinite recursion at runtime.
4120 * It will cause this code to recurse too, so check for stack overflow.
4121 * (There's no need to do more.)
4123 check_stack_depth();
4125 /* Fail if FROM item isn't a simple FuncExpr */
4126 fexpr = (FuncExpr *) rte->funcexpr;
4127 if (fexpr == NULL || !IsA(fexpr, FuncExpr))
4129 func_oid = fexpr->funcid;
4132 * The function must be declared to return a set, else inlining would
4133 * change the results if the contained SELECT didn't return exactly one
4136 if (!fexpr->funcretset)
4140 * Refuse to inline if the arguments contain any volatile functions or
4141 * sub-selects. Volatile functions are rejected because inlining may
4142 * result in the arguments being evaluated multiple times, risking a
4143 * change in behavior. Sub-selects are rejected partly for implementation
4144 * reasons (pushing them down another level might change their behavior)
4145 * and partly because they're likely to be expensive and so multiple
4146 * evaluation would be bad.
4148 if (contain_volatile_functions((Node *) fexpr->args) ||
4149 contain_subplans((Node *) fexpr->args))
4152 /* Check permission to call function (fail later, if not) */
4153 if (pg_proc_aclcheck(func_oid, GetUserId(), ACL_EXECUTE) != ACLCHECK_OK)
4157 * OK, let's take a look at the function's pg_proc entry.
4159 func_tuple = SearchSysCache1(PROCOID, ObjectIdGetDatum(func_oid));
4160 if (!HeapTupleIsValid(func_tuple))
4161 elog(ERROR, "cache lookup failed for function %u", func_oid);
4162 funcform = (Form_pg_proc) GETSTRUCT(func_tuple);
4165 * Forget it if the function is not SQL-language or has other showstopper
4166 * properties. In particular it mustn't be declared STRICT, since we
4167 * couldn't enforce that. It also mustn't be VOLATILE, because that is
4168 * supposed to cause it to be executed with its own snapshot, rather than
4169 * sharing the snapshot of the calling query. (Rechecking proretset is
4172 if (funcform->prolang != SQLlanguageId ||
4173 funcform->proisstrict ||
4174 funcform->provolatile == PROVOLATILE_VOLATILE ||
4175 funcform->prosecdef ||
4176 !funcform->proretset ||
4177 !heap_attisnull(func_tuple, Anum_pg_proc_proconfig))
4179 ReleaseSysCache(func_tuple);
4184 * Make a temporary memory context, so that we don't leak all the stuff
4185 * that parsing might create.
4187 mycxt = AllocSetContextCreate(CurrentMemoryContext,
4188 "inline_set_returning_function",
4189 ALLOCSET_DEFAULT_MINSIZE,
4190 ALLOCSET_DEFAULT_INITSIZE,
4191 ALLOCSET_DEFAULT_MAXSIZE);
4192 oldcxt = MemoryContextSwitchTo(mycxt);
4195 * When we call eval_const_expressions below, it might try to add items
4196 * to root->glob->invalItems. Since it is running in the temp context,
4197 * those items will be in that context, and will need to be copied out
4198 * if we're successful. Temporarily reset the list so that we can keep
4199 * those items separate from the pre-existing list contents.
4201 saveInvalItems = root->glob->invalItems;
4202 root->glob->invalItems = NIL;
4204 /* Fetch the function body */
4205 tmp = SysCacheGetAttr(PROCOID,
4207 Anum_pg_proc_prosrc,
4210 elog(ERROR, "null prosrc for function %u", func_oid);
4211 src = TextDatumGetCString(tmp);
4214 * Setup error traceback support for ereport(). This is so that we can
4215 * finger the function that bad information came from.
4217 callback_arg.proname = NameStr(funcform->proname);
4218 callback_arg.prosrc = src;
4220 sqlerrcontext.callback = sql_inline_error_callback;
4221 sqlerrcontext.arg = (void *) &callback_arg;
4222 sqlerrcontext.previous = error_context_stack;
4223 error_context_stack = &sqlerrcontext;
4226 * Run eval_const_expressions on the function call. This is necessary to
4227 * ensure that named-argument notation is converted to positional notation
4228 * and any default arguments are inserted. It's a bit of overkill for the
4229 * arguments, since they'll get processed again later, but no harm will be
4232 fexpr = (FuncExpr *) eval_const_expressions(root, (Node *) fexpr);
4234 /* It should still be a call of the same function, but let's check */
4235 if (!IsA(fexpr, FuncExpr) ||
4236 fexpr->funcid != func_oid)
4239 /* Arg list length should now match the function */
4240 if (list_length(fexpr->args) != funcform->pronargs)
4243 /* Check for polymorphic arguments, and substitute actual arg types */
4244 argtypes = (Oid *) palloc(funcform->pronargs * sizeof(Oid));
4245 memcpy(argtypes, funcform->proargtypes.values,
4246 funcform->pronargs * sizeof(Oid));
4247 for (i = 0; i < funcform->pronargs; i++)
4249 if (IsPolymorphicType(argtypes[i]))
4251 argtypes[i] = exprType((Node *) list_nth(fexpr->args, i));
4256 * Parse, analyze, and rewrite (unlike inline_function(), we can't skip
4257 * rewriting here). We can fail as soon as we find more than one query,
4260 raw_parsetree_list = pg_parse_query(src);
4261 if (list_length(raw_parsetree_list) != 1)
4264 querytree_list = pg_analyze_and_rewrite(linitial(raw_parsetree_list), src,
4265 argtypes, funcform->pronargs);
4266 if (list_length(querytree_list) != 1)
4268 querytree = linitial(querytree_list);
4271 * The single command must be a regular results-returning SELECT.
4273 if (!IsA(querytree, Query) ||
4274 querytree->commandType != CMD_SELECT ||
4275 querytree->utilityStmt ||
4276 querytree->intoClause)
4280 * Make sure the function (still) returns what it's declared to. This
4281 * will raise an error if wrong, but that's okay since the function would
4282 * fail at runtime anyway. Note that check_sql_fn_retval will also insert
4283 * RelabelType(s) and/or NULL columns if needed to make the tlist
4284 * expression(s) match the declared type of the function.
4286 * If the function returns a composite type, don't inline unless the check
4287 * shows it's returning a whole tuple result; otherwise what it's
4288 * returning is a single composite column which is not what we need.
4290 if (!check_sql_fn_retval(func_oid, fexpr->funcresulttype,
4292 &modifyTargetList, NULL) &&
4293 (get_typtype(fexpr->funcresulttype) == TYPTYPE_COMPOSITE ||
4294 fexpr->funcresulttype == RECORDOID))
4295 goto fail; /* reject not-whole-tuple-result cases */
4298 * If we had to modify the tlist to make it match, and the statement is
4299 * one in which changing the tlist contents could change semantics, we
4300 * have to punt and not inline.
4302 if (modifyTargetList)
4306 * If it returns RECORD, we have to check against the column type list
4307 * provided in the RTE; check_sql_fn_retval can't do that. (If no match,
4308 * we just fail to inline, rather than complaining; see notes for
4309 * tlist_matches_coltypelist.)
4311 if (fexpr->funcresulttype == RECORDOID &&
4312 !tlist_matches_coltypelist(querytree->targetList, rte->funccoltypes))
4316 * Looks good --- substitute parameters into the query.
4318 querytree = substitute_actual_srf_parameters(querytree,
4323 * Copy the modified query out of the temporary memory context, and clean
4326 MemoryContextSwitchTo(oldcxt);
4328 querytree = copyObject(querytree);
4330 /* copy up any new invalItems, too */
4331 root->glob->invalItems = list_concat(saveInvalItems,
4332 copyObject(root->glob->invalItems));
4334 MemoryContextDelete(mycxt);
4335 error_context_stack = sqlerrcontext.previous;
4336 ReleaseSysCache(func_tuple);
4339 * Since there is now no trace of the function in the plan tree, we must
4340 * explicitly record the plan's dependency on the function.
4342 record_plan_function_dependency(root->glob, func_oid);
4346 /* Here if func is not inlinable: release temp memory and return NULL */
4348 MemoryContextSwitchTo(oldcxt);
4349 root->glob->invalItems = saveInvalItems;
4350 MemoryContextDelete(mycxt);
4351 error_context_stack = sqlerrcontext.previous;
4352 ReleaseSysCache(func_tuple);
4358 * Replace Param nodes by appropriate actual parameters
4360 * This is just enough different from substitute_actual_parameters()
4361 * that it needs its own code.
4364 substitute_actual_srf_parameters(Query *expr, int nargs, List *args)
4366 substitute_actual_srf_parameters_context context;
4368 context.nargs = nargs;
4369 context.args = args;
4370 context.sublevels_up = 1;
4372 return query_tree_mutator(expr,
4373 substitute_actual_srf_parameters_mutator,
4379 substitute_actual_srf_parameters_mutator(Node *node,
4380 substitute_actual_srf_parameters_context *context)
4386 if (IsA(node, Query))
4388 context->sublevels_up++;
4389 result = (Node *) query_tree_mutator((Query *) node,
4390 substitute_actual_srf_parameters_mutator,
4393 context->sublevels_up--;
4396 if (IsA(node, Param))
4398 Param *param = (Param *) node;
4400 if (param->paramkind == PARAM_EXTERN)
4402 if (param->paramid <= 0 || param->paramid > context->nargs)
4403 elog(ERROR, "invalid paramid: %d", param->paramid);
4406 * Since the parameter is being inserted into a subquery, we must
4409 result = copyObject(list_nth(context->args, param->paramid - 1));
4410 IncrementVarSublevelsUp(result, context->sublevels_up, 0);
4414 return expression_tree_mutator(node,
4415 substitute_actual_srf_parameters_mutator,
4420 * Check whether a SELECT targetlist emits the specified column types,
4421 * to see if it's safe to inline a function returning record.
4423 * We insist on exact match here. The executor allows binary-coercible
4424 * cases too, but we don't have a way to preserve the correct column types
4425 * in the correct places if we inline the function in such a case.
4427 * Note that we only check type OIDs not typmods; this agrees with what the
4428 * executor would do at runtime, and attributing a specific typmod to a
4429 * function result is largely wishful thinking anyway.
4432 tlist_matches_coltypelist(List *tlist, List *coltypelist)
4434 ListCell *tlistitem;
4435 ListCell *clistitem;
4437 clistitem = list_head(coltypelist);
4438 foreach(tlistitem, tlist)
4440 TargetEntry *tle = (TargetEntry *) lfirst(tlistitem);
4444 continue; /* ignore junk columns */
4446 if (clistitem == NULL)
4447 return false; /* too many tlist items */
4449 coltype = lfirst_oid(clistitem);
4450 clistitem = lnext(clistitem);
4452 if (exprType((Node *) tle->expr) != coltype)
4453 return false; /* column type mismatch */
4456 if (clistitem != NULL)
4457 return false; /* too few tlist items */