1 /*-------------------------------------------------------------------------
4 * routines to manipulate qualification clauses
6 * Portions Copyright (c) 1996-2008, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
11 * $PostgreSQL: pgsql/src/backend/optimizer/util/clauses.c,v 1.268 2008/10/04 21:56:53 tgl Exp $
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 "rewrite/rewriteManip.h"
40 #include "tcop/tcopprot.h"
41 #include "utils/acl.h"
42 #include "utils/builtins.h"
43 #include "utils/datum.h"
44 #include "utils/lsyscache.h"
45 #include "utils/memutils.h"
46 #include "utils/syscache.h"
47 #include "utils/typcache.h"
52 ParamListInfo boundParams;
57 } eval_const_expressions_context;
64 } substitute_actual_parameters_context;
71 } substitute_actual_srf_parameters_context;
73 static bool contain_agg_clause_walker(Node *node, void *context);
74 static bool count_agg_clauses_walker(Node *node, AggClauseCounts *counts);
75 static bool expression_returns_set_rows_walker(Node *node, double *count);
76 static bool contain_subplans_walker(Node *node, void *context);
77 static bool contain_mutable_functions_walker(Node *node, void *context);
78 static bool contain_volatile_functions_walker(Node *node, void *context);
79 static bool contain_nonstrict_functions_walker(Node *node, void *context);
80 static Relids find_nonnullable_rels_walker(Node *node, bool top_level);
81 static List *find_nonnullable_vars_walker(Node *node, bool top_level);
82 static bool is_strict_saop(ScalarArrayOpExpr *expr, bool falseOK);
83 static bool set_coercionform_dontcare_walker(Node *node, void *context);
84 static Node *eval_const_expressions_mutator(Node *node,
85 eval_const_expressions_context *context);
86 static List *simplify_or_arguments(List *args,
87 eval_const_expressions_context *context,
88 bool *haveNull, bool *forceTrue);
89 static List *simplify_and_arguments(List *args,
90 eval_const_expressions_context *context,
91 bool *haveNull, bool *forceFalse);
92 static Expr *simplify_boolean_equality(List *args);
93 static Expr *simplify_function(Oid funcid,
94 Oid result_type, int32 result_typmod, List *args,
96 eval_const_expressions_context *context);
97 static Expr *evaluate_function(Oid funcid,
98 Oid result_type, int32 result_typmod, List *args,
100 eval_const_expressions_context *context);
101 static Expr *inline_function(Oid funcid, Oid result_type, List *args,
102 HeapTuple func_tuple,
103 eval_const_expressions_context *context);
104 static Node *substitute_actual_parameters(Node *expr, int nargs, List *args,
106 static Node *substitute_actual_parameters_mutator(Node *node,
107 substitute_actual_parameters_context *context);
108 static void sql_inline_error_callback(void *arg);
109 static Expr *evaluate_expr(Expr *expr, Oid result_type, int32 result_typmod);
110 static Query *substitute_actual_srf_parameters(Query *expr,
111 int nargs, List *args);
112 static Node *substitute_actual_srf_parameters_mutator(Node *node,
113 substitute_actual_srf_parameters_context *context);
116 /*****************************************************************************
117 * OPERATOR clause functions
118 *****************************************************************************/
122 * Creates an operator clause given its operator info, left operand,
123 * and right operand (pass NULL to create single-operand clause).
126 make_opclause(Oid opno, Oid opresulttype, bool opretset,
127 Expr *leftop, Expr *rightop)
129 OpExpr *expr = makeNode(OpExpr);
132 expr->opfuncid = InvalidOid;
133 expr->opresulttype = opresulttype;
134 expr->opretset = opretset;
136 expr->args = list_make2(leftop, rightop);
138 expr->args = list_make1(leftop);
140 return (Expr *) expr;
146 * Returns the left operand of a clause of the form (op expr expr)
150 get_leftop(Expr *clause)
152 OpExpr *expr = (OpExpr *) clause;
154 if (expr->args != NIL)
155 return linitial(expr->args);
163 * Returns the right operand in a clause of the form (op expr expr).
164 * NB: result will be NULL if applied to a unary op clause.
167 get_rightop(Expr *clause)
169 OpExpr *expr = (OpExpr *) clause;
171 if (list_length(expr->args) >= 2)
172 return lsecond(expr->args);
177 /*****************************************************************************
178 * NOT clause functions
179 *****************************************************************************/
184 * Returns t iff this is a 'not' clause: (NOT expr).
187 not_clause(Node *clause)
189 return (clause != NULL &&
190 IsA(clause, BoolExpr) &&
191 ((BoolExpr *) clause)->boolop == NOT_EXPR);
197 * Create a 'not' clause given the expression to be negated.
200 make_notclause(Expr *notclause)
202 BoolExpr *expr = makeNode(BoolExpr);
204 expr->boolop = NOT_EXPR;
205 expr->args = list_make1(notclause);
207 return (Expr *) expr;
213 * Retrieve the clause within a 'not' clause
216 get_notclausearg(Expr *notclause)
218 return linitial(((BoolExpr *) notclause)->args);
221 /*****************************************************************************
222 * OR clause functions
223 *****************************************************************************/
228 * Returns t iff the clause is an 'or' clause: (OR { expr }).
231 or_clause(Node *clause)
233 return (clause != NULL &&
234 IsA(clause, BoolExpr) &&
235 ((BoolExpr *) clause)->boolop == OR_EXPR);
241 * Creates an 'or' clause given a list of its subclauses.
244 make_orclause(List *orclauses)
246 BoolExpr *expr = makeNode(BoolExpr);
248 expr->boolop = OR_EXPR;
249 expr->args = orclauses;
251 return (Expr *) expr;
254 /*****************************************************************************
255 * AND clause functions
256 *****************************************************************************/
262 * Returns t iff its argument is an 'and' clause: (AND { expr }).
265 and_clause(Node *clause)
267 return (clause != NULL &&
268 IsA(clause, BoolExpr) &&
269 ((BoolExpr *) clause)->boolop == AND_EXPR);
275 * Creates an 'and' clause given a list of its subclauses.
278 make_andclause(List *andclauses)
280 BoolExpr *expr = makeNode(BoolExpr);
282 expr->boolop = AND_EXPR;
283 expr->args = andclauses;
285 return (Expr *) expr;
291 * Variant of make_andclause for ANDing two qual conditions together.
292 * Qual conditions have the property that a NULL nodetree is interpreted
295 * NB: this makes no attempt to preserve AND/OR flatness; so it should not
296 * be used on a qual that has already been run through prepqual.c.
299 make_and_qual(Node *qual1, Node *qual2)
305 return (Node *) make_andclause(list_make2(qual1, qual2));
309 * Sometimes (such as in the input of ExecQual), we use lists of expression
310 * nodes with implicit AND semantics.
312 * These functions convert between an AND-semantics expression list and the
313 * ordinary representation of a boolean expression.
315 * Note that an empty list is considered equivalent to TRUE.
318 make_ands_explicit(List *andclauses)
320 if (andclauses == NIL)
321 return (Expr *) makeBoolConst(true, false);
322 else if (list_length(andclauses) == 1)
323 return (Expr *) linitial(andclauses);
325 return make_andclause(andclauses);
329 make_ands_implicit(Expr *clause)
332 * NB: because the parser sets the qual field to NULL in a query that has
333 * no WHERE clause, we must consider a NULL input clause as TRUE, even
334 * though one might more reasonably think it FALSE. Grumble. If this
335 * causes trouble, consider changing the parser's behavior.
338 return NIL; /* NULL -> NIL list == TRUE */
339 else if (and_clause((Node *) clause))
340 return ((BoolExpr *) clause)->args;
341 else if (IsA(clause, Const) &&
342 !((Const *) clause)->constisnull &&
343 DatumGetBool(((Const *) clause)->constvalue))
344 return NIL; /* constant TRUE input -> NIL list */
346 return list_make1(clause);
350 /*****************************************************************************
351 * Aggregate-function clause manipulation
352 *****************************************************************************/
356 * Recursively search for Aggref nodes within a clause.
358 * Returns true if any aggregate found.
360 * This does not descend into subqueries, and so should be used only after
361 * reduction of sublinks to subplans, or in contexts where it's known there
362 * are no subqueries. There mustn't be outer-aggregate references either.
364 * (If you want something like this but able to deal with subqueries,
365 * see rewriteManip.c's contain_aggs_of_level().)
368 contain_agg_clause(Node *clause)
370 return contain_agg_clause_walker(clause, NULL);
374 contain_agg_clause_walker(Node *node, void *context)
378 if (IsA(node, Aggref))
380 Assert(((Aggref *) node)->agglevelsup == 0);
381 return true; /* abort the tree traversal and return true */
383 Assert(!IsA(node, SubLink));
384 return expression_tree_walker(node, contain_agg_clause_walker, context);
389 * Recursively count the Aggref nodes in an expression tree.
391 * Note: this also checks for nested aggregates, which are an error.
393 * We not only count the nodes, but attempt to estimate the total space
394 * needed for their transition state values if all are evaluated in parallel
395 * (as would be done in a HashAgg plan). See AggClauseCounts for the exact
396 * set of statistics returned.
398 * NOTE that the counts are ADDED to those already in *counts ... so the
399 * caller is responsible for zeroing the struct initially.
401 * This does not descend into subqueries, and so should be used only after
402 * reduction of sublinks to subplans, or in contexts where it's known there
403 * are no subqueries. There mustn't be outer-aggregate references either.
406 count_agg_clauses(Node *clause, AggClauseCounts *counts)
408 /* no setup needed */
409 count_agg_clauses_walker(clause, counts);
413 count_agg_clauses_walker(Node *node, AggClauseCounts *counts)
417 if (IsA(node, Aggref))
419 Aggref *aggref = (Aggref *) node;
423 Form_pg_aggregate aggform;
428 Assert(aggref->agglevelsup == 0);
430 if (aggref->aggdistinct)
431 counts->numDistinctAggs++;
433 /* extract argument types */
434 numArguments = list_length(aggref->args);
435 inputTypes = (Oid *) palloc(sizeof(Oid) * numArguments);
437 foreach(l, aggref->args)
439 inputTypes[i++] = exprType((Node *) lfirst(l));
442 /* fetch aggregate transition datatype from pg_aggregate */
443 aggTuple = SearchSysCache(AGGFNOID,
444 ObjectIdGetDatum(aggref->aggfnoid),
446 if (!HeapTupleIsValid(aggTuple))
447 elog(ERROR, "cache lookup failed for aggregate %u",
449 aggform = (Form_pg_aggregate) GETSTRUCT(aggTuple);
450 aggtranstype = aggform->aggtranstype;
451 ReleaseSysCache(aggTuple);
453 /* resolve actual type of transition state, if polymorphic */
454 if (IsPolymorphicType(aggtranstype))
456 /* have to fetch the agg's declared input types... */
457 Oid *declaredArgTypes;
460 (void) get_func_signature(aggref->aggfnoid,
461 &declaredArgTypes, &agg_nargs);
462 Assert(agg_nargs == numArguments);
463 aggtranstype = enforce_generic_type_consistency(inputTypes,
468 pfree(declaredArgTypes);
472 * If the transition type is pass-by-value then it doesn't add
473 * anything to the required size of the hashtable. If it is
474 * pass-by-reference then we have to add the estimated size of the
475 * value itself, plus palloc overhead.
477 if (!get_typbyval(aggtranstype))
479 int32 aggtranstypmod;
483 * If transition state is of same type as first input, assume it's
484 * the same typmod (same width) as well. This works for cases
485 * like MAX/MIN and is probably somewhat reasonable otherwise.
487 if (numArguments > 0 && aggtranstype == inputTypes[0])
488 aggtranstypmod = exprTypmod((Node *) linitial(aggref->args));
492 avgwidth = get_typavgwidth(aggtranstype, aggtranstypmod);
493 avgwidth = MAXALIGN(avgwidth);
495 counts->transitionSpace += avgwidth + 2 * sizeof(void *);
499 * Complain if the aggregate's arguments contain any aggregates;
500 * nested agg functions are semantically nonsensical.
502 if (contain_agg_clause((Node *) aggref->args))
504 (errcode(ERRCODE_GROUPING_ERROR),
505 errmsg("aggregate function calls cannot be nested")));
508 * Having checked that, we need not recurse into the argument.
512 Assert(!IsA(node, SubLink));
513 return expression_tree_walker(node, count_agg_clauses_walker,
518 /*****************************************************************************
519 * Support for expressions returning sets
520 *****************************************************************************/
523 * expression_returns_set_rows
524 * Estimate the number of rows in a set result.
526 * We use the product of the rowcount estimates of all the functions in
527 * the given tree. The result is 1 if there are no set-returning functions.
529 * Note: keep this in sync with expression_returns_set() in nodes/nodeFuncs.c.
532 expression_returns_set_rows(Node *clause)
536 (void) expression_returns_set_rows_walker(clause, &result);
541 expression_returns_set_rows_walker(Node *node, double *count)
545 if (IsA(node, FuncExpr))
547 FuncExpr *expr = (FuncExpr *) node;
549 if (expr->funcretset)
550 *count *= get_func_rows(expr->funcid);
552 if (IsA(node, OpExpr))
554 OpExpr *expr = (OpExpr *) node;
559 *count *= get_func_rows(expr->opfuncid);
563 /* Avoid recursion for some cases that can't return a set */
564 if (IsA(node, Aggref))
566 if (IsA(node, DistinctExpr))
568 if (IsA(node, ScalarArrayOpExpr))
570 if (IsA(node, BoolExpr))
572 if (IsA(node, SubLink))
574 if (IsA(node, SubPlan))
576 if (IsA(node, AlternativeSubPlan))
578 if (IsA(node, ArrayExpr))
580 if (IsA(node, RowExpr))
582 if (IsA(node, RowCompareExpr))
584 if (IsA(node, CoalesceExpr))
586 if (IsA(node, MinMaxExpr))
588 if (IsA(node, XmlExpr))
590 if (IsA(node, NullIfExpr))
593 return expression_tree_walker(node, expression_returns_set_rows_walker,
598 /*****************************************************************************
599 * Subplan clause manipulation
600 *****************************************************************************/
604 * Recursively search for subplan nodes within a clause.
606 * If we see a SubLink node, we will return TRUE. This is only possible if
607 * the expression tree hasn't yet been transformed by subselect.c. We do not
608 * know whether the node will produce a true subplan or just an initplan,
609 * but we make the conservative assumption that it will be a subplan.
611 * Returns true if any subplan found.
614 contain_subplans(Node *clause)
616 return contain_subplans_walker(clause, NULL);
620 contain_subplans_walker(Node *node, void *context)
624 if (IsA(node, SubPlan) ||
625 IsA(node, AlternativeSubPlan) ||
627 return true; /* abort the tree traversal and return true */
628 return expression_tree_walker(node, contain_subplans_walker, context);
632 /*****************************************************************************
633 * Check clauses for mutable functions
634 *****************************************************************************/
637 * contain_mutable_functions
638 * Recursively search for mutable functions within a clause.
640 * Returns true if any mutable function (or operator implemented by a
641 * mutable function) is found. This test is needed so that we don't
642 * mistakenly think that something like "WHERE random() < 0.5" can be treated
643 * as a constant qualification.
645 * XXX we do not examine sub-selects to see if they contain uses of
646 * mutable functions. It's not real clear if that is correct or not...
649 contain_mutable_functions(Node *clause)
651 return contain_mutable_functions_walker(clause, NULL);
655 contain_mutable_functions_walker(Node *node, void *context)
659 if (IsA(node, FuncExpr))
661 FuncExpr *expr = (FuncExpr *) node;
663 if (func_volatile(expr->funcid) != PROVOLATILE_IMMUTABLE)
665 /* else fall through to check args */
667 else if (IsA(node, OpExpr))
669 OpExpr *expr = (OpExpr *) node;
672 if (func_volatile(expr->opfuncid) != PROVOLATILE_IMMUTABLE)
674 /* else fall through to check args */
676 else if (IsA(node, DistinctExpr))
678 DistinctExpr *expr = (DistinctExpr *) node;
680 set_opfuncid((OpExpr *) expr); /* rely on struct equivalence */
681 if (func_volatile(expr->opfuncid) != PROVOLATILE_IMMUTABLE)
683 /* else fall through to check args */
685 else if (IsA(node, ScalarArrayOpExpr))
687 ScalarArrayOpExpr *expr = (ScalarArrayOpExpr *) node;
689 set_sa_opfuncid(expr);
690 if (func_volatile(expr->opfuncid) != PROVOLATILE_IMMUTABLE)
692 /* else fall through to check args */
694 else if (IsA(node, CoerceViaIO))
696 CoerceViaIO *expr = (CoerceViaIO *) node;
701 /* check the result type's input function */
702 getTypeInputInfo(expr->resulttype,
703 &iofunc, &typioparam);
704 if (func_volatile(iofunc) != PROVOLATILE_IMMUTABLE)
706 /* check the input type's output function */
707 getTypeOutputInfo(exprType((Node *) expr->arg),
708 &iofunc, &typisvarlena);
709 if (func_volatile(iofunc) != PROVOLATILE_IMMUTABLE)
711 /* else fall through to check args */
713 else if (IsA(node, ArrayCoerceExpr))
715 ArrayCoerceExpr *expr = (ArrayCoerceExpr *) node;
717 if (OidIsValid(expr->elemfuncid) &&
718 func_volatile(expr->elemfuncid) != PROVOLATILE_IMMUTABLE)
720 /* else fall through to check args */
722 else if (IsA(node, NullIfExpr))
724 NullIfExpr *expr = (NullIfExpr *) node;
726 set_opfuncid((OpExpr *) expr); /* rely on struct equivalence */
727 if (func_volatile(expr->opfuncid) != PROVOLATILE_IMMUTABLE)
729 /* else fall through to check args */
731 else if (IsA(node, RowCompareExpr))
733 RowCompareExpr *rcexpr = (RowCompareExpr *) node;
736 foreach(opid, rcexpr->opnos)
738 if (op_volatile(lfirst_oid(opid)) != PROVOLATILE_IMMUTABLE)
741 /* else fall through to check args */
743 return expression_tree_walker(node, contain_mutable_functions_walker,
748 /*****************************************************************************
749 * Check clauses for volatile functions
750 *****************************************************************************/
753 * contain_volatile_functions
754 * Recursively search for volatile functions within a clause.
756 * Returns true if any volatile function (or operator implemented by a
757 * volatile function) is found. This test prevents invalid conversions
758 * of volatile expressions into indexscan quals.
760 * XXX we do not examine sub-selects to see if they contain uses of
761 * volatile functions. It's not real clear if that is correct or not...
764 contain_volatile_functions(Node *clause)
766 return contain_volatile_functions_walker(clause, NULL);
770 contain_volatile_functions_walker(Node *node, void *context)
774 if (IsA(node, FuncExpr))
776 FuncExpr *expr = (FuncExpr *) node;
778 if (func_volatile(expr->funcid) == PROVOLATILE_VOLATILE)
780 /* else fall through to check args */
782 else if (IsA(node, OpExpr))
784 OpExpr *expr = (OpExpr *) node;
787 if (func_volatile(expr->opfuncid) == PROVOLATILE_VOLATILE)
789 /* else fall through to check args */
791 else if (IsA(node, DistinctExpr))
793 DistinctExpr *expr = (DistinctExpr *) node;
795 set_opfuncid((OpExpr *) expr); /* rely on struct equivalence */
796 if (func_volatile(expr->opfuncid) == PROVOLATILE_VOLATILE)
798 /* else fall through to check args */
800 else if (IsA(node, ScalarArrayOpExpr))
802 ScalarArrayOpExpr *expr = (ScalarArrayOpExpr *) node;
804 set_sa_opfuncid(expr);
805 if (func_volatile(expr->opfuncid) == PROVOLATILE_VOLATILE)
807 /* else fall through to check args */
809 else if (IsA(node, CoerceViaIO))
811 CoerceViaIO *expr = (CoerceViaIO *) node;
816 /* check the result type's input function */
817 getTypeInputInfo(expr->resulttype,
818 &iofunc, &typioparam);
819 if (func_volatile(iofunc) == PROVOLATILE_VOLATILE)
821 /* check the input type's output function */
822 getTypeOutputInfo(exprType((Node *) expr->arg),
823 &iofunc, &typisvarlena);
824 if (func_volatile(iofunc) == PROVOLATILE_VOLATILE)
826 /* else fall through to check args */
828 else if (IsA(node, ArrayCoerceExpr))
830 ArrayCoerceExpr *expr = (ArrayCoerceExpr *) node;
832 if (OidIsValid(expr->elemfuncid) &&
833 func_volatile(expr->elemfuncid) == PROVOLATILE_VOLATILE)
835 /* else fall through to check args */
837 else if (IsA(node, NullIfExpr))
839 NullIfExpr *expr = (NullIfExpr *) node;
841 set_opfuncid((OpExpr *) expr); /* rely on struct equivalence */
842 if (func_volatile(expr->opfuncid) == PROVOLATILE_VOLATILE)
844 /* else fall through to check args */
846 else if (IsA(node, RowCompareExpr))
848 /* RowCompare probably can't have volatile ops, but check anyway */
849 RowCompareExpr *rcexpr = (RowCompareExpr *) node;
852 foreach(opid, rcexpr->opnos)
854 if (op_volatile(lfirst_oid(opid)) == PROVOLATILE_VOLATILE)
857 /* else fall through to check args */
859 return expression_tree_walker(node, contain_volatile_functions_walker,
864 /*****************************************************************************
865 * Check clauses for nonstrict functions
866 *****************************************************************************/
869 * contain_nonstrict_functions
870 * Recursively search for nonstrict functions within a clause.
872 * Returns true if any nonstrict construct is found --- ie, anything that
873 * could produce non-NULL output with a NULL input.
875 * The idea here is that the caller has verified that the expression contains
876 * one or more Var or Param nodes (as appropriate for the caller's need), and
877 * now wishes to prove that the expression result will be NULL if any of these
878 * inputs is NULL. If we return false, then the proof succeeded.
881 contain_nonstrict_functions(Node *clause)
883 return contain_nonstrict_functions_walker(clause, NULL);
887 contain_nonstrict_functions_walker(Node *node, void *context)
891 if (IsA(node, Aggref))
893 /* an aggregate could return non-null with null input */
896 if (IsA(node, ArrayRef))
898 /* array assignment is nonstrict, but subscripting is strict */
899 if (((ArrayRef *) node)->refassgnexpr != NULL)
901 /* else fall through to check args */
903 if (IsA(node, FuncExpr))
905 FuncExpr *expr = (FuncExpr *) node;
907 if (!func_strict(expr->funcid))
909 /* else fall through to check args */
911 if (IsA(node, OpExpr))
913 OpExpr *expr = (OpExpr *) node;
916 if (!func_strict(expr->opfuncid))
918 /* else fall through to check args */
920 if (IsA(node, DistinctExpr))
922 /* IS DISTINCT FROM is inherently non-strict */
925 if (IsA(node, ScalarArrayOpExpr))
927 ScalarArrayOpExpr *expr = (ScalarArrayOpExpr *) node;
929 if (!is_strict_saop(expr, false))
931 /* else fall through to check args */
933 if (IsA(node, BoolExpr))
935 BoolExpr *expr = (BoolExpr *) node;
937 switch (expr->boolop)
941 /* AND, OR are inherently non-strict */
947 if (IsA(node, SubLink))
949 /* In some cases a sublink might be strict, but in general not */
952 if (IsA(node, SubPlan))
954 if (IsA(node, AlternativeSubPlan))
956 /* ArrayCoerceExpr is strict at the array level, regardless of elemfunc */
957 if (IsA(node, FieldStore))
959 if (IsA(node, CaseExpr))
961 if (IsA(node, ArrayExpr))
963 if (IsA(node, RowExpr))
965 if (IsA(node, RowCompareExpr))
967 if (IsA(node, CoalesceExpr))
969 if (IsA(node, MinMaxExpr))
971 if (IsA(node, XmlExpr))
973 if (IsA(node, NullIfExpr))
975 if (IsA(node, NullTest))
977 if (IsA(node, BooleanTest))
979 return expression_tree_walker(node, contain_nonstrict_functions_walker,
985 * find_nonnullable_rels
986 * Determine which base rels are forced nonnullable by given clause.
988 * Returns the set of all Relids that are referenced in the clause in such
989 * a way that the clause cannot possibly return TRUE if any of these Relids
990 * is an all-NULL row. (It is OK to err on the side of conservatism; hence
991 * the analysis here is simplistic.)
993 * The semantics here are subtly different from contain_nonstrict_functions:
994 * that function is concerned with NULL results from arbitrary expressions,
995 * but here we assume that the input is a Boolean expression, and wish to
996 * see if NULL inputs will provably cause a FALSE-or-NULL result. We expect
997 * the expression to have been AND/OR flattened and converted to implicit-AND
1000 * Note: this function is largely duplicative of find_nonnullable_vars().
1001 * The reason not to simplify this function into a thin wrapper around
1002 * find_nonnullable_vars() is that the tested conditions really are different:
1003 * a clause like "t1.v1 IS NOT NULL OR t1.v2 IS NOT NULL" does not prove
1004 * that either v1 or v2 can't be NULL, but it does prove that the t1 row
1005 * as a whole can't be all-NULL.
1007 * top_level is TRUE while scanning top-level AND/OR structure; here, showing
1008 * the result is either FALSE or NULL is good enough. top_level is FALSE when
1009 * we have descended below a NOT or a strict function: now we must be able to
1010 * prove that the subexpression goes to NULL.
1012 * We don't use expression_tree_walker here because we don't want to descend
1013 * through very many kinds of nodes; only the ones we can be sure are strict.
1016 find_nonnullable_rels(Node *clause)
1018 return find_nonnullable_rels_walker(clause, true);
1022 find_nonnullable_rels_walker(Node *node, bool top_level)
1024 Relids result = NULL;
1031 Var *var = (Var *) node;
1033 if (var->varlevelsup == 0)
1034 result = bms_make_singleton(var->varno);
1036 else if (IsA(node, List))
1039 * At top level, we are examining an implicit-AND list: if any of the
1040 * arms produces FALSE-or-NULL then the result is FALSE-or-NULL. If
1041 * not at top level, we are examining the arguments of a strict
1042 * function: if any of them produce NULL then the result of the
1043 * function must be NULL. So in both cases, the set of nonnullable
1044 * rels is the union of those found in the arms, and we pass down the
1045 * top_level flag unmodified.
1047 foreach(l, (List *) node)
1049 result = bms_join(result,
1050 find_nonnullable_rels_walker(lfirst(l),
1054 else if (IsA(node, FuncExpr))
1056 FuncExpr *expr = (FuncExpr *) node;
1058 if (func_strict(expr->funcid))
1059 result = find_nonnullable_rels_walker((Node *) expr->args, false);
1061 else if (IsA(node, OpExpr))
1063 OpExpr *expr = (OpExpr *) node;
1066 if (func_strict(expr->opfuncid))
1067 result = find_nonnullable_rels_walker((Node *) expr->args, false);
1069 else if (IsA(node, ScalarArrayOpExpr))
1071 ScalarArrayOpExpr *expr = (ScalarArrayOpExpr *) node;
1073 if (is_strict_saop(expr, true))
1074 result = find_nonnullable_rels_walker((Node *) expr->args, false);
1076 else if (IsA(node, BoolExpr))
1078 BoolExpr *expr = (BoolExpr *) node;
1080 switch (expr->boolop)
1083 /* At top level we can just recurse (to the List case) */
1086 result = find_nonnullable_rels_walker((Node *) expr->args,
1092 * Below top level, even if one arm produces NULL, the result
1093 * could be FALSE (hence not NULL). However, if *all* the
1094 * arms produce NULL then the result is NULL, so we can take
1095 * the intersection of the sets of nonnullable rels, just as
1096 * for OR. Fall through to share code.
1102 * OR is strict if all of its arms are, so we can take the
1103 * intersection of the sets of nonnullable rels for each arm.
1104 * This works for both values of top_level.
1106 foreach(l, expr->args)
1110 subresult = find_nonnullable_rels_walker(lfirst(l),
1112 if (result == NULL) /* first subresult? */
1115 result = bms_int_members(result, subresult);
1118 * If the intersection is empty, we can stop looking. This
1119 * also justifies the test for first-subresult above.
1121 if (bms_is_empty(result))
1126 /* NOT will return null if its arg is null */
1127 result = find_nonnullable_rels_walker((Node *) expr->args,
1131 elog(ERROR, "unrecognized boolop: %d", (int) expr->boolop);
1135 else if (IsA(node, RelabelType))
1137 RelabelType *expr = (RelabelType *) node;
1139 result = find_nonnullable_rels_walker((Node *) expr->arg, top_level);
1141 else if (IsA(node, CoerceViaIO))
1143 /* not clear this is useful, but it can't hurt */
1144 CoerceViaIO *expr = (CoerceViaIO *) node;
1146 result = find_nonnullable_rels_walker((Node *) expr->arg, top_level);
1148 else if (IsA(node, ArrayCoerceExpr))
1150 /* ArrayCoerceExpr is strict at the array level */
1151 ArrayCoerceExpr *expr = (ArrayCoerceExpr *) node;
1153 result = find_nonnullable_rels_walker((Node *) expr->arg, top_level);
1155 else if (IsA(node, ConvertRowtypeExpr))
1157 /* not clear this is useful, but it can't hurt */
1158 ConvertRowtypeExpr *expr = (ConvertRowtypeExpr *) node;
1160 result = find_nonnullable_rels_walker((Node *) expr->arg, top_level);
1162 else if (IsA(node, NullTest))
1164 /* IS NOT NULL can be considered strict, but only at top level */
1165 NullTest *expr = (NullTest *) node;
1167 if (top_level && expr->nulltesttype == IS_NOT_NULL)
1168 result = find_nonnullable_rels_walker((Node *) expr->arg, false);
1170 else if (IsA(node, BooleanTest))
1172 /* Boolean tests that reject NULL are strict at top level */
1173 BooleanTest *expr = (BooleanTest *) node;
1176 (expr->booltesttype == IS_TRUE ||
1177 expr->booltesttype == IS_FALSE ||
1178 expr->booltesttype == IS_NOT_UNKNOWN))
1179 result = find_nonnullable_rels_walker((Node *) expr->arg, false);
1181 else if (IsA(node, FlattenedSubLink))
1183 /* JOIN_SEMI sublinks preserve strictness, but JOIN_ANTI ones don't */
1184 FlattenedSubLink *expr = (FlattenedSubLink *) node;
1186 if (expr->jointype == JOIN_SEMI)
1187 result = find_nonnullable_rels_walker((Node *) expr->quals,
1194 * find_nonnullable_vars
1195 * Determine which Vars are forced nonnullable by given clause.
1197 * Returns a list of all level-zero Vars that are referenced in the clause in
1198 * such a way that the clause cannot possibly return TRUE if any of these Vars
1199 * is NULL. (It is OK to err on the side of conservatism; hence the analysis
1200 * here is simplistic.)
1202 * The semantics here are subtly different from contain_nonstrict_functions:
1203 * that function is concerned with NULL results from arbitrary expressions,
1204 * but here we assume that the input is a Boolean expression, and wish to
1205 * see if NULL inputs will provably cause a FALSE-or-NULL result. We expect
1206 * the expression to have been AND/OR flattened and converted to implicit-AND
1209 * The result is a palloc'd List, but we have not copied the member Var nodes.
1210 * Also, we don't bother trying to eliminate duplicate entries.
1212 * top_level is TRUE while scanning top-level AND/OR structure; here, showing
1213 * the result is either FALSE or NULL is good enough. top_level is FALSE when
1214 * we have descended below a NOT or a strict function: now we must be able to
1215 * prove that the subexpression goes to NULL.
1217 * We don't use expression_tree_walker here because we don't want to descend
1218 * through very many kinds of nodes; only the ones we can be sure are strict.
1221 find_nonnullable_vars(Node *clause)
1223 return find_nonnullable_vars_walker(clause, true);
1227 find_nonnullable_vars_walker(Node *node, bool top_level)
1236 Var *var = (Var *) node;
1238 if (var->varlevelsup == 0)
1239 result = list_make1(var);
1241 else if (IsA(node, List))
1244 * At top level, we are examining an implicit-AND list: if any of the
1245 * arms produces FALSE-or-NULL then the result is FALSE-or-NULL. If
1246 * not at top level, we are examining the arguments of a strict
1247 * function: if any of them produce NULL then the result of the
1248 * function must be NULL. So in both cases, the set of nonnullable
1249 * vars is the union of those found in the arms, and we pass down the
1250 * top_level flag unmodified.
1252 foreach(l, (List *) node)
1254 result = list_concat(result,
1255 find_nonnullable_vars_walker(lfirst(l),
1259 else if (IsA(node, FuncExpr))
1261 FuncExpr *expr = (FuncExpr *) node;
1263 if (func_strict(expr->funcid))
1264 result = find_nonnullable_vars_walker((Node *) expr->args, false);
1266 else if (IsA(node, OpExpr))
1268 OpExpr *expr = (OpExpr *) node;
1271 if (func_strict(expr->opfuncid))
1272 result = find_nonnullable_vars_walker((Node *) expr->args, false);
1274 else if (IsA(node, ScalarArrayOpExpr))
1276 ScalarArrayOpExpr *expr = (ScalarArrayOpExpr *) node;
1278 if (is_strict_saop(expr, true))
1279 result = find_nonnullable_vars_walker((Node *) expr->args, false);
1281 else if (IsA(node, BoolExpr))
1283 BoolExpr *expr = (BoolExpr *) node;
1285 switch (expr->boolop)
1288 /* At top level we can just recurse (to the List case) */
1291 result = find_nonnullable_vars_walker((Node *) expr->args,
1297 * Below top level, even if one arm produces NULL, the result
1298 * could be FALSE (hence not NULL). However, if *all* the
1299 * arms produce NULL then the result is NULL, so we can take
1300 * the intersection of the sets of nonnullable vars, just as
1301 * for OR. Fall through to share code.
1307 * OR is strict if all of its arms are, so we can take the
1308 * intersection of the sets of nonnullable vars for each arm.
1309 * This works for both values of top_level.
1311 foreach(l, expr->args)
1315 subresult = find_nonnullable_vars_walker(lfirst(l),
1317 if (result == NIL) /* first subresult? */
1320 result = list_intersection(result, subresult);
1323 * If the intersection is empty, we can stop looking. This
1324 * also justifies the test for first-subresult above.
1331 /* NOT will return null if its arg is null */
1332 result = find_nonnullable_vars_walker((Node *) expr->args,
1336 elog(ERROR, "unrecognized boolop: %d", (int) expr->boolop);
1340 else if (IsA(node, RelabelType))
1342 RelabelType *expr = (RelabelType *) node;
1344 result = find_nonnullable_vars_walker((Node *) expr->arg, top_level);
1346 else if (IsA(node, CoerceViaIO))
1348 /* not clear this is useful, but it can't hurt */
1349 CoerceViaIO *expr = (CoerceViaIO *) node;
1351 result = find_nonnullable_vars_walker((Node *) expr->arg, false);
1353 else if (IsA(node, ArrayCoerceExpr))
1355 /* ArrayCoerceExpr is strict at the array level */
1356 ArrayCoerceExpr *expr = (ArrayCoerceExpr *) node;
1358 result = find_nonnullable_vars_walker((Node *) expr->arg, top_level);
1360 else if (IsA(node, ConvertRowtypeExpr))
1362 /* not clear this is useful, but it can't hurt */
1363 ConvertRowtypeExpr *expr = (ConvertRowtypeExpr *) node;
1365 result = find_nonnullable_vars_walker((Node *) expr->arg, top_level);
1367 else if (IsA(node, NullTest))
1369 /* IS NOT NULL can be considered strict, but only at top level */
1370 NullTest *expr = (NullTest *) node;
1372 if (top_level && expr->nulltesttype == IS_NOT_NULL)
1373 result = find_nonnullable_vars_walker((Node *) expr->arg, false);
1375 else if (IsA(node, BooleanTest))
1377 /* Boolean tests that reject NULL are strict at top level */
1378 BooleanTest *expr = (BooleanTest *) node;
1381 (expr->booltesttype == IS_TRUE ||
1382 expr->booltesttype == IS_FALSE ||
1383 expr->booltesttype == IS_NOT_UNKNOWN))
1384 result = find_nonnullable_vars_walker((Node *) expr->arg, false);
1386 else if (IsA(node, FlattenedSubLink))
1388 /* JOIN_SEMI sublinks preserve strictness, but JOIN_ANTI ones don't */
1389 FlattenedSubLink *expr = (FlattenedSubLink *) node;
1391 if (expr->jointype == JOIN_SEMI)
1392 result = find_nonnullable_vars_walker((Node *) expr->quals,
1399 * find_forced_null_vars
1400 * Determine which Vars must be NULL for the given clause to return TRUE.
1402 * This is the complement of find_nonnullable_vars: find the level-zero Vars
1403 * that must be NULL for the clause to return TRUE. (It is OK to err on the
1404 * side of conservatism; hence the analysis here is simplistic. In fact,
1405 * we only detect simple "var IS NULL" tests at the top level.)
1407 * The result is a palloc'd List, but we have not copied the member Var nodes.
1408 * Also, we don't bother trying to eliminate duplicate entries.
1411 find_forced_null_vars(Node *node)
1419 /* Check single-clause cases using subroutine */
1420 var = find_forced_null_var(node);
1423 result = list_make1(var);
1425 /* Otherwise, handle AND-conditions */
1426 else if (IsA(node, List))
1429 * At top level, we are examining an implicit-AND list: if any of the
1430 * arms produces FALSE-or-NULL then the result is FALSE-or-NULL.
1432 foreach(l, (List *) node)
1434 result = list_concat(result,
1435 find_forced_null_vars(lfirst(l)));
1438 else if (IsA(node, BoolExpr))
1440 BoolExpr *expr = (BoolExpr *) node;
1443 * We don't bother considering the OR case, because it's fairly
1444 * unlikely anyone would write "v1 IS NULL OR v1 IS NULL".
1445 * Likewise, the NOT case isn't worth expending code on.
1447 if (expr->boolop == AND_EXPR)
1449 /* At top level we can just recurse (to the List case) */
1450 result = find_forced_null_vars((Node *) expr->args);
1457 * find_forced_null_var
1458 * Return the Var forced null by the given clause, or NULL if it's
1459 * not an IS NULL-type clause. For success, the clause must enforce
1460 * *only* nullness of the particular Var, not any other conditions.
1462 * This is just the single-clause case of find_forced_null_vars(), without
1463 * any allowance for AND conditions. It's used by initsplan.c on individual
1464 * qual clauses. The reason for not just applying find_forced_null_vars()
1465 * is that if an AND of an IS NULL clause with something else were to somehow
1466 * survive AND/OR flattening, initsplan.c might get fooled into discarding
1467 * the whole clause when only the IS NULL part of it had been proved redundant.
1470 find_forced_null_var(Node *node)
1474 if (IsA(node, NullTest))
1476 /* check for var IS NULL */
1477 NullTest *expr = (NullTest *) node;
1479 if (expr->nulltesttype == IS_NULL)
1481 Var *var = (Var *) expr->arg;
1483 if (var && IsA(var, Var) &&
1484 var->varlevelsup == 0)
1488 else if (IsA(node, BooleanTest))
1490 /* var IS UNKNOWN is equivalent to var IS NULL */
1491 BooleanTest *expr = (BooleanTest *) node;
1493 if (expr->booltesttype == IS_UNKNOWN)
1495 Var *var = (Var *) expr->arg;
1497 if (var && IsA(var, Var) &&
1498 var->varlevelsup == 0)
1506 * Can we treat a ScalarArrayOpExpr as strict?
1508 * If "falseOK" is true, then a "false" result can be considered strict,
1509 * else we need to guarantee an actual NULL result for NULL input.
1511 * "foo op ALL array" is strict if the op is strict *and* we can prove
1512 * that the array input isn't an empty array. We can check that
1513 * for the cases of an array constant and an ARRAY[] construct.
1515 * "foo op ANY array" is strict in the falseOK sense if the op is strict.
1516 * If not falseOK, the test is the same as for "foo op ALL array".
1519 is_strict_saop(ScalarArrayOpExpr *expr, bool falseOK)
1523 /* The contained operator must be strict. */
1524 set_sa_opfuncid(expr);
1525 if (!func_strict(expr->opfuncid))
1527 /* If ANY and falseOK, that's all we need to check. */
1528 if (expr->useOr && falseOK)
1530 /* Else, we have to see if the array is provably non-empty. */
1531 Assert(list_length(expr->args) == 2);
1532 rightop = (Node *) lsecond(expr->args);
1533 if (rightop && IsA(rightop, Const))
1535 Datum arraydatum = ((Const *) rightop)->constvalue;
1536 bool arrayisnull = ((Const *) rightop)->constisnull;
1537 ArrayType *arrayval;
1542 arrayval = DatumGetArrayTypeP(arraydatum);
1543 nitems = ArrayGetNItems(ARR_NDIM(arrayval), ARR_DIMS(arrayval));
1547 else if (rightop && IsA(rightop, ArrayExpr))
1549 ArrayExpr *arrayexpr = (ArrayExpr *) rightop;
1551 if (arrayexpr->elements != NIL && !arrayexpr->multidims)
1558 /*****************************************************************************
1559 * Check for "pseudo-constant" clauses
1560 *****************************************************************************/
1563 * is_pseudo_constant_clause
1564 * Detect whether an expression is "pseudo constant", ie, it contains no
1565 * variables of the current query level and no uses of volatile functions.
1566 * Such an expr is not necessarily a true constant: it can still contain
1567 * Params and outer-level Vars, not to mention functions whose results
1568 * may vary from one statement to the next. However, the expr's value
1569 * will be constant over any one scan of the current query, so it can be
1570 * used as, eg, an indexscan key.
1572 * CAUTION: this function omits to test for one very important class of
1573 * not-constant expressions, namely aggregates (Aggrefs). In current usage
1574 * this is only applied to WHERE clauses and so a check for Aggrefs would be
1575 * a waste of cycles; but be sure to also check contain_agg_clause() if you
1576 * want to know about pseudo-constness in other contexts.
1579 is_pseudo_constant_clause(Node *clause)
1582 * We could implement this check in one recursive scan. But since the
1583 * check for volatile functions is both moderately expensive and unlikely
1584 * to fail, it seems better to look for Vars first and only check for
1585 * volatile functions if we find no Vars.
1587 if (!contain_var_clause(clause) &&
1588 !contain_volatile_functions(clause))
1594 * is_pseudo_constant_clause_relids
1595 * Same as above, except caller already has available the var membership
1596 * of the expression; this lets us avoid the contain_var_clause() scan.
1599 is_pseudo_constant_clause_relids(Node *clause, Relids relids)
1601 if (bms_is_empty(relids) &&
1602 !contain_volatile_functions(clause))
1608 /*****************************************************************************
1610 * General clause-manipulating routines *
1612 *****************************************************************************/
1616 * (formerly clause_relids)
1618 * Returns the number of different relations referenced in 'clause'.
1621 NumRelids(Node *clause)
1623 Relids varnos = pull_varnos(clause);
1624 int result = bms_num_members(varnos);
1631 * CommuteOpExpr: commute a binary operator clause
1633 * XXX the clause is destructively modified!
1636 CommuteOpExpr(OpExpr *clause)
1641 /* Sanity checks: caller is at fault if these fail */
1642 if (!is_opclause(clause) ||
1643 list_length(clause->args) != 2)
1644 elog(ERROR, "cannot commute non-binary-operator clause");
1646 opoid = get_commutator(clause->opno);
1648 if (!OidIsValid(opoid))
1649 elog(ERROR, "could not find commutator for operator %u",
1653 * modify the clause in-place!
1655 clause->opno = opoid;
1656 clause->opfuncid = InvalidOid;
1657 /* opresulttype and opretset are assumed not to change */
1659 temp = linitial(clause->args);
1660 linitial(clause->args) = lsecond(clause->args);
1661 lsecond(clause->args) = temp;
1665 * CommuteRowCompareExpr: commute a RowCompareExpr clause
1667 * XXX the clause is destructively modified!
1670 CommuteRowCompareExpr(RowCompareExpr *clause)
1676 /* Sanity checks: caller is at fault if these fail */
1677 if (!IsA(clause, RowCompareExpr))
1678 elog(ERROR, "expected a RowCompareExpr");
1680 /* Build list of commuted operators */
1682 foreach(l, clause->opnos)
1684 Oid opoid = lfirst_oid(l);
1686 opoid = get_commutator(opoid);
1687 if (!OidIsValid(opoid))
1688 elog(ERROR, "could not find commutator for operator %u",
1690 newops = lappend_oid(newops, opoid);
1694 * modify the clause in-place!
1696 switch (clause->rctype)
1699 clause->rctype = ROWCOMPARE_GT;
1702 clause->rctype = ROWCOMPARE_GE;
1705 clause->rctype = ROWCOMPARE_LE;
1708 clause->rctype = ROWCOMPARE_LT;
1711 elog(ERROR, "unexpected RowCompare type: %d",
1712 (int) clause->rctype);
1716 clause->opnos = newops;
1719 * Note: we need not change the opfamilies list; we assume any btree
1720 * opfamily containing an operator will also contain its commutator.
1723 temp = clause->largs;
1724 clause->largs = clause->rargs;
1725 clause->rargs = temp;
1729 * strip_implicit_coercions: remove implicit coercions at top level of tree
1731 * Note: there isn't any useful thing we can do with a RowExpr here, so
1732 * just return it unchanged, even if it's marked as an implicit coercion.
1735 strip_implicit_coercions(Node *node)
1739 if (IsA(node, FuncExpr))
1741 FuncExpr *f = (FuncExpr *) node;
1743 if (f->funcformat == COERCE_IMPLICIT_CAST)
1744 return strip_implicit_coercions(linitial(f->args));
1746 else if (IsA(node, RelabelType))
1748 RelabelType *r = (RelabelType *) node;
1750 if (r->relabelformat == COERCE_IMPLICIT_CAST)
1751 return strip_implicit_coercions((Node *) r->arg);
1753 else if (IsA(node, CoerceViaIO))
1755 CoerceViaIO *c = (CoerceViaIO *) node;
1757 if (c->coerceformat == COERCE_IMPLICIT_CAST)
1758 return strip_implicit_coercions((Node *) c->arg);
1760 else if (IsA(node, ArrayCoerceExpr))
1762 ArrayCoerceExpr *c = (ArrayCoerceExpr *) node;
1764 if (c->coerceformat == COERCE_IMPLICIT_CAST)
1765 return strip_implicit_coercions((Node *) c->arg);
1767 else if (IsA(node, ConvertRowtypeExpr))
1769 ConvertRowtypeExpr *c = (ConvertRowtypeExpr *) node;
1771 if (c->convertformat == COERCE_IMPLICIT_CAST)
1772 return strip_implicit_coercions((Node *) c->arg);
1774 else if (IsA(node, CoerceToDomain))
1776 CoerceToDomain *c = (CoerceToDomain *) node;
1778 if (c->coercionformat == COERCE_IMPLICIT_CAST)
1779 return strip_implicit_coercions((Node *) c->arg);
1785 * set_coercionform_dontcare: set all CoercionForm fields to COERCE_DONTCARE
1787 * This is used to make index expressions and index predicates more easily
1788 * comparable to clauses of queries. CoercionForm is not semantically
1789 * significant (for cases where it does matter, the significant info is
1790 * coded into the coercion function arguments) so we can ignore it during
1791 * comparisons. Thus, for example, an index on "foo::int4" can match an
1792 * implicit coercion to int4.
1794 * Caution: the passed expression tree is modified in-place.
1797 set_coercionform_dontcare(Node *node)
1799 (void) set_coercionform_dontcare_walker(node, NULL);
1803 set_coercionform_dontcare_walker(Node *node, void *context)
1807 if (IsA(node, FuncExpr))
1808 ((FuncExpr *) node)->funcformat = COERCE_DONTCARE;
1809 else if (IsA(node, RelabelType))
1810 ((RelabelType *) node)->relabelformat = COERCE_DONTCARE;
1811 else if (IsA(node, CoerceViaIO))
1812 ((CoerceViaIO *) node)->coerceformat = COERCE_DONTCARE;
1813 else if (IsA(node, ArrayCoerceExpr))
1814 ((ArrayCoerceExpr *) node)->coerceformat = COERCE_DONTCARE;
1815 else if (IsA(node, ConvertRowtypeExpr))
1816 ((ConvertRowtypeExpr *) node)->convertformat = COERCE_DONTCARE;
1817 else if (IsA(node, RowExpr))
1818 ((RowExpr *) node)->row_format = COERCE_DONTCARE;
1819 else if (IsA(node, CoerceToDomain))
1820 ((CoerceToDomain *) node)->coercionformat = COERCE_DONTCARE;
1821 return expression_tree_walker(node, set_coercionform_dontcare_walker,
1826 * Helper for eval_const_expressions: check that datatype of an attribute
1827 * is still what it was when the expression was parsed. This is needed to
1828 * guard against improper simplification after ALTER COLUMN TYPE. (XXX we
1829 * may well need to make similar checks elsewhere?)
1832 rowtype_field_matches(Oid rowtypeid, int fieldnum,
1833 Oid expectedtype, int32 expectedtypmod)
1836 Form_pg_attribute attr;
1838 /* No issue for RECORD, since there is no way to ALTER such a type */
1839 if (rowtypeid == RECORDOID)
1841 tupdesc = lookup_rowtype_tupdesc(rowtypeid, -1);
1842 if (fieldnum <= 0 || fieldnum > tupdesc->natts)
1844 ReleaseTupleDesc(tupdesc);
1847 attr = tupdesc->attrs[fieldnum - 1];
1848 if (attr->attisdropped ||
1849 attr->atttypid != expectedtype ||
1850 attr->atttypmod != expectedtypmod)
1852 ReleaseTupleDesc(tupdesc);
1855 ReleaseTupleDesc(tupdesc);
1860 /*--------------------
1861 * eval_const_expressions
1863 * Reduce any recognizably constant subexpressions of the given
1864 * expression tree, for example "2 + 2" => "4". More interestingly,
1865 * we can reduce certain boolean expressions even when they contain
1866 * non-constant subexpressions: "x OR true" => "true" no matter what
1867 * the subexpression x is. (XXX We assume that no such subexpression
1868 * will have important side-effects, which is not necessarily a good
1869 * assumption in the presence of user-defined functions; do we need a
1870 * pg_proc flag that prevents discarding the execution of a function?)
1872 * We do understand that certain functions may deliver non-constant
1873 * results even with constant inputs, "nextval()" being the classic
1874 * example. Functions that are not marked "immutable" in pg_proc
1875 * will not be pre-evaluated here, although we will reduce their
1876 * arguments as far as possible.
1878 * We assume that the tree has already been type-checked and contains
1879 * only operators and functions that are reasonable to try to execute.
1881 * NOTE: "root" can be passed as NULL if the caller never wants to do any
1882 * Param substitutions.
1884 * NOTE: the planner assumes that this will always flatten nested AND and
1885 * OR clauses into N-argument form. See comments in prepqual.c.
1886 *--------------------
1889 eval_const_expressions(PlannerInfo *root, Node *node)
1891 eval_const_expressions_context context;
1895 context.boundParams = root->glob->boundParams; /* bound Params */
1896 context.glob = root->glob; /* for inlined-function dependencies */
1900 context.boundParams = NULL;
1901 context.glob = NULL;
1903 context.active_fns = NIL; /* nothing being recursively simplified */
1904 context.case_val = NULL; /* no CASE being examined */
1905 context.estimate = false; /* safe transformations only */
1906 return eval_const_expressions_mutator(node, &context);
1909 /*--------------------
1910 * estimate_expression_value
1912 * This function attempts to estimate the value of an expression for
1913 * planning purposes. It is in essence a more aggressive version of
1914 * eval_const_expressions(): we will perform constant reductions that are
1915 * not necessarily 100% safe, but are reasonable for estimation purposes.
1917 * Currently the extra steps that are taken in this mode are:
1918 * 1. Substitute values for Params, where a bound Param value has been made
1919 * available by the caller of planner(), even if the Param isn't marked
1920 * constant. This effectively means that we plan using the first supplied
1921 * value of the Param.
1922 * 2. Fold stable, as well as immutable, functions to constants.
1923 *--------------------
1926 estimate_expression_value(PlannerInfo *root, Node *node)
1928 eval_const_expressions_context context;
1930 context.boundParams = root->glob->boundParams; /* bound Params */
1931 /* we do not need to mark the plan as depending on inlined functions */
1932 context.glob = NULL;
1933 context.active_fns = NIL; /* nothing being recursively simplified */
1934 context.case_val = NULL; /* no CASE being examined */
1935 context.estimate = true; /* unsafe transformations OK */
1936 return eval_const_expressions_mutator(node, &context);
1940 eval_const_expressions_mutator(Node *node,
1941 eval_const_expressions_context *context)
1945 if (IsA(node, Param))
1947 Param *param = (Param *) node;
1949 /* Look to see if we've been given a value for this Param */
1950 if (param->paramkind == PARAM_EXTERN &&
1951 context->boundParams != NULL &&
1952 param->paramid > 0 &&
1953 param->paramid <= context->boundParams->numParams)
1955 ParamExternData *prm = &context->boundParams->params[param->paramid - 1];
1957 if (OidIsValid(prm->ptype))
1959 /* OK to substitute parameter value? */
1960 if (context->estimate || (prm->pflags & PARAM_FLAG_CONST))
1963 * Return a Const representing the param value. Must copy
1964 * pass-by-ref datatypes, since the Param might be in a
1965 * memory context shorter-lived than our output plan
1972 Assert(prm->ptype == param->paramtype);
1973 get_typlenbyval(param->paramtype, &typLen, &typByVal);
1974 if (prm->isnull || typByVal)
1977 pval = datumCopy(prm->value, typByVal, typLen);
1978 return (Node *) makeConst(param->paramtype,
1987 /* Not replaceable, so just copy the Param (no need to recurse) */
1988 return (Node *) copyObject(param);
1990 if (IsA(node, FuncExpr))
1992 FuncExpr *expr = (FuncExpr *) node;
1998 * Reduce constants in the FuncExpr's arguments. We know args is
1999 * either NIL or a List node, so we can call expression_tree_mutator
2000 * directly rather than recursing to self.
2002 args = (List *) expression_tree_mutator((Node *) expr->args,
2003 eval_const_expressions_mutator,
2007 * Code for op/func reduction is pretty bulky, so split it out as a
2008 * separate function. Note: exprTypmod normally returns -1 for a
2009 * FuncExpr, but not when the node is recognizably a length coercion;
2010 * we want to preserve the typmod in the eventual Const if so.
2012 simple = simplify_function(expr->funcid,
2013 expr->funcresulttype, exprTypmod(node),
2016 if (simple) /* successfully simplified it */
2017 return (Node *) simple;
2020 * The expression cannot be simplified any further, so build and
2021 * return a replacement FuncExpr node using the possibly-simplified
2024 newexpr = makeNode(FuncExpr);
2025 newexpr->funcid = expr->funcid;
2026 newexpr->funcresulttype = expr->funcresulttype;
2027 newexpr->funcretset = expr->funcretset;
2028 newexpr->funcformat = expr->funcformat;
2029 newexpr->args = args;
2030 newexpr->location = expr->location;
2031 return (Node *) newexpr;
2033 if (IsA(node, OpExpr))
2035 OpExpr *expr = (OpExpr *) node;
2041 * Reduce constants in the OpExpr's arguments. We know args is either
2042 * NIL or a List node, so we can call expression_tree_mutator directly
2043 * rather than recursing to self.
2045 args = (List *) expression_tree_mutator((Node *) expr->args,
2046 eval_const_expressions_mutator,
2050 * Need to get OID of underlying function. Okay to scribble on input
2056 * Code for op/func reduction is pretty bulky, so split it out as a
2057 * separate function.
2059 simple = simplify_function(expr->opfuncid,
2060 expr->opresulttype, -1,
2063 if (simple) /* successfully simplified it */
2064 return (Node *) simple;
2067 * If the operator is boolean equality, we know how to simplify cases
2068 * involving one constant and one non-constant argument.
2070 if (expr->opno == BooleanEqualOperator)
2072 simple = simplify_boolean_equality(args);
2073 if (simple) /* successfully simplified it */
2074 return (Node *) simple;
2078 * The expression cannot be simplified any further, so build and
2079 * return a replacement OpExpr node using the possibly-simplified
2082 newexpr = makeNode(OpExpr);
2083 newexpr->opno = expr->opno;
2084 newexpr->opfuncid = expr->opfuncid;
2085 newexpr->opresulttype = expr->opresulttype;
2086 newexpr->opretset = expr->opretset;
2087 newexpr->args = args;
2088 newexpr->location = expr->location;
2089 return (Node *) newexpr;
2091 if (IsA(node, DistinctExpr))
2093 DistinctExpr *expr = (DistinctExpr *) node;
2096 bool has_null_input = false;
2097 bool all_null_input = true;
2098 bool has_nonconst_input = false;
2100 DistinctExpr *newexpr;
2103 * Reduce constants in the DistinctExpr's arguments. We know args is
2104 * either NIL or a List node, so we can call expression_tree_mutator
2105 * directly rather than recursing to self.
2107 args = (List *) expression_tree_mutator((Node *) expr->args,
2108 eval_const_expressions_mutator,
2112 * We must do our own check for NULLs because DistinctExpr has
2113 * different results for NULL input than the underlying operator does.
2117 if (IsA(lfirst(arg), Const))
2119 has_null_input |= ((Const *) lfirst(arg))->constisnull;
2120 all_null_input &= ((Const *) lfirst(arg))->constisnull;
2123 has_nonconst_input = true;
2126 /* all constants? then can optimize this out */
2127 if (!has_nonconst_input)
2129 /* all nulls? then not distinct */
2131 return makeBoolConst(false, false);
2133 /* one null? then distinct */
2135 return makeBoolConst(true, false);
2137 /* otherwise try to evaluate the '=' operator */
2138 /* (NOT okay to try to inline it, though!) */
2141 * Need to get OID of underlying function. Okay to scribble on
2142 * input to this extent.
2144 set_opfuncid((OpExpr *) expr); /* rely on struct equivalence */
2147 * Code for op/func reduction is pretty bulky, so split it out as
2148 * a separate function.
2150 simple = simplify_function(expr->opfuncid,
2151 expr->opresulttype, -1,
2154 if (simple) /* successfully simplified it */
2157 * Since the underlying operator is "=", must negate its
2160 Const *csimple = (Const *) simple;
2162 Assert(IsA(csimple, Const));
2163 csimple->constvalue =
2164 BoolGetDatum(!DatumGetBool(csimple->constvalue));
2165 return (Node *) csimple;
2170 * The expression cannot be simplified any further, so build and
2171 * return a replacement DistinctExpr node using the
2172 * possibly-simplified arguments.
2174 newexpr = makeNode(DistinctExpr);
2175 newexpr->opno = expr->opno;
2176 newexpr->opfuncid = expr->opfuncid;
2177 newexpr->opresulttype = expr->opresulttype;
2178 newexpr->opretset = expr->opretset;
2179 newexpr->args = args;
2180 newexpr->location = expr->location;
2181 return (Node *) newexpr;
2183 if (IsA(node, BoolExpr))
2185 BoolExpr *expr = (BoolExpr *) node;
2187 switch (expr->boolop)
2192 bool haveNull = false;
2193 bool forceTrue = false;
2195 newargs = simplify_or_arguments(expr->args, context,
2196 &haveNull, &forceTrue);
2198 return makeBoolConst(true, false);
2200 newargs = lappend(newargs, makeBoolConst(false, true));
2201 /* If all the inputs are FALSE, result is FALSE */
2203 return makeBoolConst(false, false);
2204 /* If only one nonconst-or-NULL input, it's the result */
2205 if (list_length(newargs) == 1)
2206 return (Node *) linitial(newargs);
2207 /* Else we still need an OR node */
2208 return (Node *) make_orclause(newargs);
2213 bool haveNull = false;
2214 bool forceFalse = false;
2216 newargs = simplify_and_arguments(expr->args, context,
2217 &haveNull, &forceFalse);
2219 return makeBoolConst(false, false);
2221 newargs = lappend(newargs, makeBoolConst(false, true));
2222 /* If all the inputs are TRUE, result is TRUE */
2224 return makeBoolConst(true, false);
2225 /* If only one nonconst-or-NULL input, it's the result */
2226 if (list_length(newargs) == 1)
2227 return (Node *) linitial(newargs);
2228 /* Else we still need an AND node */
2229 return (Node *) make_andclause(newargs);
2235 Assert(list_length(expr->args) == 1);
2236 arg = eval_const_expressions_mutator(linitial(expr->args),
2238 if (IsA(arg, Const))
2240 Const *const_input = (Const *) arg;
2242 /* NOT NULL => NULL */
2243 if (const_input->constisnull)
2244 return makeBoolConst(false, true);
2245 /* otherwise pretty easy */
2246 return makeBoolConst(!DatumGetBool(const_input->constvalue),
2249 else if (not_clause(arg))
2251 /* Cancel NOT/NOT */
2252 return (Node *) get_notclausearg((Expr *) arg);
2254 /* Else we still need a NOT node */
2255 return (Node *) make_notclause((Expr *) arg);
2258 elog(ERROR, "unrecognized boolop: %d",
2259 (int) expr->boolop);
2263 if (IsA(node, SubPlan) ||
2264 IsA(node, AlternativeSubPlan))
2267 * Return a SubPlan unchanged --- too late to do anything with it.
2269 * XXX should we ereport() here instead? Probably this routine should
2270 * never be invoked after SubPlan creation.
2274 if (IsA(node, RelabelType))
2277 * If we can simplify the input to a constant, then we don't need the
2278 * RelabelType node anymore: just change the type field of the Const
2279 * node. Otherwise, must copy the RelabelType node.
2281 RelabelType *relabel = (RelabelType *) node;
2284 arg = eval_const_expressions_mutator((Node *) relabel->arg,
2288 * If we find stacked RelabelTypes (eg, from foo :: int :: oid) we can
2289 * discard all but the top one.
2291 while (arg && IsA(arg, RelabelType))
2292 arg = (Node *) ((RelabelType *) arg)->arg;
2294 if (arg && IsA(arg, Const))
2296 Const *con = (Const *) arg;
2298 con->consttype = relabel->resulttype;
2299 con->consttypmod = relabel->resulttypmod;
2300 return (Node *) con;
2304 RelabelType *newrelabel = makeNode(RelabelType);
2306 newrelabel->arg = (Expr *) arg;
2307 newrelabel->resulttype = relabel->resulttype;
2308 newrelabel->resulttypmod = relabel->resulttypmod;
2309 newrelabel->relabelformat = relabel->relabelformat;
2310 newrelabel->location = relabel->location;
2311 return (Node *) newrelabel;
2314 if (IsA(node, CoerceViaIO))
2316 CoerceViaIO *expr = (CoerceViaIO *) node;
2319 bool outtypisvarlena;
2323 CoerceViaIO *newexpr;
2326 * Reduce constants in the CoerceViaIO's argument.
2328 arg = (Expr *) eval_const_expressions_mutator((Node *) expr->arg,
2332 * CoerceViaIO represents calling the source type's output function
2333 * then the result type's input function. So, try to simplify it
2334 * as though it were a stack of two such function calls. First we
2335 * need to know what the functions are.
2337 getTypeOutputInfo(exprType((Node *) arg), &outfunc, &outtypisvarlena);
2338 getTypeInputInfo(expr->resulttype, &infunc, &intypioparam);
2340 simple = simplify_function(outfunc,
2344 if (simple) /* successfully simplified output fn */
2347 * Input functions may want 1 to 3 arguments. We always supply
2348 * all three, trusting that nothing downstream will complain.
2352 args = list_make3(simple,
2353 makeConst(OIDOID, -1, sizeof(Oid),
2354 ObjectIdGetDatum(intypioparam),
2356 makeConst(INT4OID, -1, sizeof(int32),
2360 simple = simplify_function(infunc,
2361 expr->resulttype, -1,
2364 if (simple) /* successfully simplified input fn */
2365 return (Node *) simple;
2369 * The expression cannot be simplified any further, so build and
2370 * return a replacement CoerceViaIO node using the possibly-simplified
2373 newexpr = makeNode(CoerceViaIO);
2375 newexpr->resulttype = expr->resulttype;
2376 newexpr->coerceformat = expr->coerceformat;
2377 newexpr->location = expr->location;
2378 return (Node *) newexpr;
2380 if (IsA(node, ArrayCoerceExpr))
2382 ArrayCoerceExpr *expr = (ArrayCoerceExpr *) node;
2384 ArrayCoerceExpr *newexpr;
2387 * Reduce constants in the ArrayCoerceExpr's argument, then build
2388 * a new ArrayCoerceExpr.
2390 arg = (Expr *) eval_const_expressions_mutator((Node *) expr->arg,
2393 newexpr = makeNode(ArrayCoerceExpr);
2395 newexpr->elemfuncid = expr->elemfuncid;
2396 newexpr->resulttype = expr->resulttype;
2397 newexpr->resulttypmod = expr->resulttypmod;
2398 newexpr->isExplicit = expr->isExplicit;
2399 newexpr->coerceformat = expr->coerceformat;
2400 newexpr->location = expr->location;
2403 * If constant argument and it's a binary-coercible or immutable
2404 * conversion, we can simplify it to a constant.
2406 if (arg && IsA(arg, Const) &&
2407 (!OidIsValid(newexpr->elemfuncid) ||
2408 func_volatile(newexpr->elemfuncid) == PROVOLATILE_IMMUTABLE))
2409 return (Node *) evaluate_expr((Expr *) newexpr,
2410 newexpr->resulttype,
2411 newexpr->resulttypmod);
2413 /* Else we must return the partially-simplified node */
2414 return (Node *) newexpr;
2416 if (IsA(node, CaseExpr))
2419 * CASE expressions can be simplified if there are constant
2420 * condition clauses:
2421 * FALSE (or NULL): drop the alternative
2422 * TRUE: drop all remaining alternatives
2423 * If the first non-FALSE alternative is a constant TRUE, we can
2424 * simplify the entire CASE to that alternative's expression.
2425 * If there are no non-FALSE alternatives, we simplify the entire
2426 * CASE to the default result (ELSE result).
2428 * If we have a simple-form CASE with constant test expression,
2429 * we substitute the constant value for contained CaseTestExpr
2430 * placeholder nodes, so that we have the opportunity to reduce
2431 * constant test conditions. For example this allows
2432 * CASE 0 WHEN 0 THEN 1 ELSE 1/0 END
2433 * to reduce to 1 rather than drawing a divide-by-0 error.
2436 CaseExpr *caseexpr = (CaseExpr *) node;
2438 Node *save_case_val;
2441 bool const_true_cond;
2442 Node *defresult = NULL;
2445 /* Simplify the test expression, if any */
2446 newarg = eval_const_expressions_mutator((Node *) caseexpr->arg,
2449 /* Set up for contained CaseTestExpr nodes */
2450 save_case_val = context->case_val;
2451 if (newarg && IsA(newarg, Const))
2452 context->case_val = newarg;
2454 context->case_val = NULL;
2456 /* Simplify the WHEN clauses */
2458 const_true_cond = false;
2459 foreach(arg, caseexpr->args)
2461 CaseWhen *oldcasewhen = (CaseWhen *) lfirst(arg);
2465 Assert(IsA(oldcasewhen, CaseWhen));
2467 /* Simplify this alternative's test condition */
2469 eval_const_expressions_mutator((Node *) oldcasewhen->expr,
2473 * If the test condition is constant FALSE (or NULL), then drop
2474 * this WHEN clause completely, without processing the result.
2476 if (casecond && IsA(casecond, Const))
2478 Const *const_input = (Const *) casecond;
2480 if (const_input->constisnull ||
2481 !DatumGetBool(const_input->constvalue))
2482 continue; /* drop alternative with FALSE condition */
2483 /* Else it's constant TRUE */
2484 const_true_cond = true;
2487 /* Simplify this alternative's result value */
2489 eval_const_expressions_mutator((Node *) oldcasewhen->result,
2492 /* If non-constant test condition, emit a new WHEN node */
2493 if (!const_true_cond)
2495 CaseWhen *newcasewhen = makeNode(CaseWhen);
2497 newcasewhen->expr = (Expr *) casecond;
2498 newcasewhen->result = (Expr *) caseresult;
2499 newcasewhen->location = oldcasewhen->location;
2500 newargs = lappend(newargs, newcasewhen);
2505 * Found a TRUE condition, so none of the remaining alternatives
2506 * can be reached. We treat the result as the default result.
2508 defresult = caseresult;
2512 /* Simplify the default result, unless we replaced it above */
2513 if (!const_true_cond)
2515 eval_const_expressions_mutator((Node *) caseexpr->defresult,
2518 context->case_val = save_case_val;
2520 /* If no non-FALSE alternatives, CASE reduces to the default result */
2523 /* Otherwise we need a new CASE node */
2524 newcase = makeNode(CaseExpr);
2525 newcase->casetype = caseexpr->casetype;
2526 newcase->arg = (Expr *) newarg;
2527 newcase->args = newargs;
2528 newcase->defresult = (Expr *) defresult;
2529 newcase->location = caseexpr->location;
2530 return (Node *) newcase;
2532 if (IsA(node, CaseTestExpr))
2535 * If we know a constant test value for the current CASE construct,
2536 * substitute it for the placeholder. Else just return the
2537 * placeholder as-is.
2539 if (context->case_val)
2540 return copyObject(context->case_val);
2542 return copyObject(node);
2544 if (IsA(node, ArrayExpr))
2546 ArrayExpr *arrayexpr = (ArrayExpr *) node;
2547 ArrayExpr *newarray;
2548 bool all_const = true;
2553 foreach(element, arrayexpr->elements)
2557 e = eval_const_expressions_mutator((Node *) lfirst(element),
2561 newelems = lappend(newelems, e);
2564 newarray = makeNode(ArrayExpr);
2565 newarray->array_typeid = arrayexpr->array_typeid;
2566 newarray->element_typeid = arrayexpr->element_typeid;
2567 newarray->elements = newelems;
2568 newarray->multidims = arrayexpr->multidims;
2569 newarray->location = arrayexpr->location;
2572 return (Node *) evaluate_expr((Expr *) newarray,
2573 newarray->array_typeid,
2576 return (Node *) newarray;
2578 if (IsA(node, CoalesceExpr))
2580 CoalesceExpr *coalesceexpr = (CoalesceExpr *) node;
2581 CoalesceExpr *newcoalesce;
2586 foreach(arg, coalesceexpr->args)
2590 e = eval_const_expressions_mutator((Node *) lfirst(arg),
2594 * We can remove null constants from the list. For a non-null
2595 * constant, if it has not been preceded by any other
2596 * non-null-constant expressions then that is the result.
2600 if (((Const *) e)->constisnull)
2601 continue; /* drop null constant */
2603 return e; /* first expr */
2605 newargs = lappend(newargs, e);
2608 /* If all the arguments were constant null, the result is just null */
2610 return (Node *) makeNullConst(coalesceexpr->coalescetype, -1);
2612 newcoalesce = makeNode(CoalesceExpr);
2613 newcoalesce->coalescetype = coalesceexpr->coalescetype;
2614 newcoalesce->args = newargs;
2615 newcoalesce->location = coalesceexpr->location;
2616 return (Node *) newcoalesce;
2618 if (IsA(node, FieldSelect))
2621 * We can optimize field selection from a whole-row Var into a simple
2622 * Var. (This case won't be generated directly by the parser, because
2623 * ParseComplexProjection short-circuits it. But it can arise while
2624 * simplifying functions.) Also, we can optimize field selection from
2625 * a RowExpr construct.
2627 * We must however check that the declared type of the field is still
2628 * the same as when the FieldSelect was created --- this can change if
2629 * someone did ALTER COLUMN TYPE on the rowtype.
2631 FieldSelect *fselect = (FieldSelect *) node;
2632 FieldSelect *newfselect;
2635 arg = eval_const_expressions_mutator((Node *) fselect->arg,
2637 if (arg && IsA(arg, Var) &&
2638 ((Var *) arg)->varattno == InvalidAttrNumber)
2640 if (rowtype_field_matches(((Var *) arg)->vartype,
2642 fselect->resulttype,
2643 fselect->resulttypmod))
2644 return (Node *) makeVar(((Var *) arg)->varno,
2646 fselect->resulttype,
2647 fselect->resulttypmod,
2648 ((Var *) arg)->varlevelsup);
2650 if (arg && IsA(arg, RowExpr))
2652 RowExpr *rowexpr = (RowExpr *) arg;
2654 if (fselect->fieldnum > 0 &&
2655 fselect->fieldnum <= list_length(rowexpr->args))
2657 Node *fld = (Node *) list_nth(rowexpr->args,
2658 fselect->fieldnum - 1);
2660 if (rowtype_field_matches(rowexpr->row_typeid,
2662 fselect->resulttype,
2663 fselect->resulttypmod) &&
2664 fselect->resulttype == exprType(fld) &&
2665 fselect->resulttypmod == exprTypmod(fld))
2669 newfselect = makeNode(FieldSelect);
2670 newfselect->arg = (Expr *) arg;
2671 newfselect->fieldnum = fselect->fieldnum;
2672 newfselect->resulttype = fselect->resulttype;
2673 newfselect->resulttypmod = fselect->resulttypmod;
2674 return (Node *) newfselect;
2676 if (IsA(node, NullTest))
2678 NullTest *ntest = (NullTest *) node;
2682 arg = eval_const_expressions_mutator((Node *) ntest->arg,
2684 if (arg && IsA(arg, RowExpr))
2686 RowExpr *rarg = (RowExpr *) arg;
2687 List *newargs = NIL;
2691 * We break ROW(...) IS [NOT] NULL into separate tests on its
2692 * component fields. This form is usually more efficient to
2693 * evaluate, as well as being more amenable to optimization.
2695 foreach(l, rarg->args)
2697 Node *relem = (Node *) lfirst(l);
2700 * A constant field refutes the whole NullTest if it's of the
2701 * wrong nullness; else we can discard it.
2703 if (relem && IsA(relem, Const))
2705 Const *carg = (Const *) relem;
2707 if (carg->constisnull ?
2708 (ntest->nulltesttype == IS_NOT_NULL) :
2709 (ntest->nulltesttype == IS_NULL))
2710 return makeBoolConst(false, false);
2713 newntest = makeNode(NullTest);
2714 newntest->arg = (Expr *) relem;
2715 newntest->nulltesttype = ntest->nulltesttype;
2716 newargs = lappend(newargs, newntest);
2718 /* If all the inputs were constants, result is TRUE */
2720 return makeBoolConst(true, false);
2721 /* If only one nonconst input, it's the result */
2722 if (list_length(newargs) == 1)
2723 return (Node *) linitial(newargs);
2724 /* Else we need an AND node */
2725 return (Node *) make_andclause(newargs);
2727 if (arg && IsA(arg, Const))
2729 Const *carg = (Const *) arg;
2732 switch (ntest->nulltesttype)
2735 result = carg->constisnull;
2738 result = !carg->constisnull;
2741 elog(ERROR, "unrecognized nulltesttype: %d",
2742 (int) ntest->nulltesttype);
2743 result = false; /* keep compiler quiet */
2747 return makeBoolConst(result, false);
2750 newntest = makeNode(NullTest);
2751 newntest->arg = (Expr *) arg;
2752 newntest->nulltesttype = ntest->nulltesttype;
2753 return (Node *) newntest;
2755 if (IsA(node, BooleanTest))
2757 BooleanTest *btest = (BooleanTest *) node;
2758 BooleanTest *newbtest;
2761 arg = eval_const_expressions_mutator((Node *) btest->arg,
2763 if (arg && IsA(arg, Const))
2765 Const *carg = (Const *) arg;
2768 switch (btest->booltesttype)
2771 result = (!carg->constisnull &&
2772 DatumGetBool(carg->constvalue));
2775 result = (carg->constisnull ||
2776 !DatumGetBool(carg->constvalue));
2779 result = (!carg->constisnull &&
2780 !DatumGetBool(carg->constvalue));
2783 result = (carg->constisnull ||
2784 DatumGetBool(carg->constvalue));
2787 result = carg->constisnull;
2789 case IS_NOT_UNKNOWN:
2790 result = !carg->constisnull;
2793 elog(ERROR, "unrecognized booltesttype: %d",
2794 (int) btest->booltesttype);
2795 result = false; /* keep compiler quiet */
2799 return makeBoolConst(result, false);
2802 newbtest = makeNode(BooleanTest);
2803 newbtest->arg = (Expr *) arg;
2804 newbtest->booltesttype = btest->booltesttype;
2805 return (Node *) newbtest;
2807 if (IsA(node, FlattenedSubLink))
2809 FlattenedSubLink *fslink = (FlattenedSubLink *) node;
2810 FlattenedSubLink *newfslink;
2813 /* Simplify and also canonicalize the arguments */
2814 quals = (Expr *) eval_const_expressions_mutator((Node *) fslink->quals,
2816 quals = canonicalize_qual(quals);
2818 newfslink = makeNode(FlattenedSubLink);
2819 newfslink->jointype = fslink->jointype;
2820 newfslink->lefthand = fslink->lefthand;
2821 newfslink->righthand = fslink->righthand;
2822 newfslink->quals = quals;
2823 return (Node *) newfslink;
2827 * For any node type not handled above, we recurse using
2828 * expression_tree_mutator, which will copy the node unchanged but try to
2829 * simplify its arguments (if any) using this routine. For example: we
2830 * cannot eliminate an ArrayRef node, but we might be able to simplify
2831 * constant expressions in its subscripts.
2833 return expression_tree_mutator(node, eval_const_expressions_mutator,
2838 * Subroutine for eval_const_expressions: process arguments of an OR clause
2840 * This includes flattening of nested ORs as well as recursion to
2841 * eval_const_expressions to simplify the OR arguments.
2843 * After simplification, OR arguments are handled as follows:
2844 * non constant: keep
2845 * FALSE: drop (does not affect result)
2846 * TRUE: force result to TRUE
2847 * NULL: keep only one
2848 * We must keep one NULL input because ExecEvalOr returns NULL when no input
2849 * is TRUE and at least one is NULL. We don't actually include the NULL
2850 * here, that's supposed to be done by the caller.
2852 * The output arguments *haveNull and *forceTrue must be initialized FALSE
2853 * by the caller. They will be set TRUE if a null constant or true constant,
2854 * respectively, is detected anywhere in the argument list.
2857 simplify_or_arguments(List *args,
2858 eval_const_expressions_context *context,
2859 bool *haveNull, bool *forceTrue)
2861 List *newargs = NIL;
2862 List *unprocessed_args;
2865 * Since the parser considers OR to be a binary operator, long OR lists
2866 * become deeply nested expressions. We must flatten these into long
2867 * argument lists of a single OR operator. To avoid blowing out the stack
2868 * with recursion of eval_const_expressions, we resort to some tenseness
2869 * here: we keep a list of not-yet-processed inputs, and handle flattening
2870 * of nested ORs by prepending to the to-do list instead of recursing.
2872 unprocessed_args = list_copy(args);
2873 while (unprocessed_args)
2875 Node *arg = (Node *) linitial(unprocessed_args);
2877 unprocessed_args = list_delete_first(unprocessed_args);
2879 /* flatten nested ORs as per above comment */
2882 List *subargs = list_copy(((BoolExpr *) arg)->args);
2884 /* overly tense code to avoid leaking unused list header */
2885 if (!unprocessed_args)
2886 unprocessed_args = subargs;
2889 List *oldhdr = unprocessed_args;
2891 unprocessed_args = list_concat(subargs, unprocessed_args);
2897 /* If it's not an OR, simplify it */
2898 arg = eval_const_expressions_mutator(arg, context);
2901 * It is unlikely but not impossible for simplification of a non-OR
2902 * clause to produce an OR. Recheck, but don't be too tense about it
2903 * since it's not a mainstream case. In particular we don't worry
2904 * about const-simplifying the input twice.
2908 List *subargs = list_copy(((BoolExpr *) arg)->args);
2910 unprocessed_args = list_concat(subargs, unprocessed_args);
2915 * OK, we have a const-simplified non-OR argument. Process it per
2918 if (IsA(arg, Const))
2920 Const *const_input = (Const *) arg;
2922 if (const_input->constisnull)
2924 else if (DatumGetBool(const_input->constvalue))
2929 * Once we detect a TRUE result we can just exit the loop
2930 * immediately. However, if we ever add a notion of
2931 * non-removable functions, we'd need to keep scanning.
2935 /* otherwise, we can drop the constant-false input */
2939 /* else emit the simplified arg into the result list */
2940 newargs = lappend(newargs, arg);
2947 * Subroutine for eval_const_expressions: process arguments of an AND clause
2949 * This includes flattening of nested ANDs as well as recursion to
2950 * eval_const_expressions to simplify the AND arguments.
2952 * After simplification, AND arguments are handled as follows:
2953 * non constant: keep
2954 * TRUE: drop (does not affect result)
2955 * FALSE: force result to FALSE
2956 * NULL: keep only one
2957 * We must keep one NULL input because ExecEvalAnd returns NULL when no input
2958 * is FALSE and at least one is NULL. We don't actually include the NULL
2959 * here, that's supposed to be done by the caller.
2961 * The output arguments *haveNull and *forceFalse must be initialized FALSE
2962 * by the caller. They will be set TRUE if a null constant or false constant,
2963 * respectively, is detected anywhere in the argument list.
2966 simplify_and_arguments(List *args,
2967 eval_const_expressions_context *context,
2968 bool *haveNull, bool *forceFalse)
2970 List *newargs = NIL;
2971 List *unprocessed_args;
2973 /* See comments in simplify_or_arguments */
2974 unprocessed_args = list_copy(args);
2975 while (unprocessed_args)
2977 Node *arg = (Node *) linitial(unprocessed_args);
2979 unprocessed_args = list_delete_first(unprocessed_args);
2981 /* flatten nested ANDs as per above comment */
2982 if (and_clause(arg))
2984 List *subargs = list_copy(((BoolExpr *) arg)->args);
2986 /* overly tense code to avoid leaking unused list header */
2987 if (!unprocessed_args)
2988 unprocessed_args = subargs;
2991 List *oldhdr = unprocessed_args;
2993 unprocessed_args = list_concat(subargs, unprocessed_args);
2999 /* If it's not an AND, simplify it */
3000 arg = eval_const_expressions_mutator(arg, context);
3003 * It is unlikely but not impossible for simplification of a non-AND
3004 * clause to produce an AND. Recheck, but don't be too tense about it
3005 * since it's not a mainstream case. In particular we don't worry
3006 * about const-simplifying the input twice.
3008 if (and_clause(arg))
3010 List *subargs = list_copy(((BoolExpr *) arg)->args);
3012 unprocessed_args = list_concat(subargs, unprocessed_args);
3017 * OK, we have a const-simplified non-AND argument. Process it per
3020 if (IsA(arg, Const))
3022 Const *const_input = (Const *) arg;
3024 if (const_input->constisnull)
3026 else if (!DatumGetBool(const_input->constvalue))
3031 * Once we detect a FALSE result we can just exit the loop
3032 * immediately. However, if we ever add a notion of
3033 * non-removable functions, we'd need to keep scanning.
3037 /* otherwise, we can drop the constant-true input */
3041 /* else emit the simplified arg into the result list */
3042 newargs = lappend(newargs, arg);
3049 * Subroutine for eval_const_expressions: try to simplify boolean equality
3051 * Input is the list of simplified arguments to the operator.
3052 * Returns a simplified expression if successful, or NULL if cannot
3053 * simplify the expression.
3055 * The idea here is to reduce "x = true" to "x" and "x = false" to "NOT x".
3056 * This is only marginally useful in itself, but doing it in constant folding
3057 * ensures that we will recognize the two forms as being equivalent in, for
3058 * example, partial index matching.
3060 * We come here only if simplify_function has failed; therefore we cannot
3061 * see two constant inputs, nor a constant-NULL input.
3064 simplify_boolean_equality(List *args)
3069 Assert(list_length(args) == 2);
3070 leftop = linitial(args);
3071 rightop = lsecond(args);
3072 if (leftop && IsA(leftop, Const))
3074 Assert(!((Const *) leftop)->constisnull);
3075 if (DatumGetBool(((Const *) leftop)->constvalue))
3076 return rightop; /* true = foo */
3078 return make_notclause(rightop); /* false = foo */
3080 if (rightop && IsA(rightop, Const))
3082 Assert(!((Const *) rightop)->constisnull);
3083 if (DatumGetBool(((Const *) rightop)->constvalue))
3084 return leftop; /* foo = true */
3086 return make_notclause(leftop); /* foo = false */
3092 * Subroutine for eval_const_expressions: try to simplify a function call
3093 * (which might originally have been an operator; we don't care)
3095 * Inputs are the function OID, actual result type OID (which is needed for
3096 * polymorphic functions) and typmod, and the pre-simplified argument list;
3097 * also the context data for eval_const_expressions.
3099 * Returns a simplified expression if successful, or NULL if cannot
3100 * simplify the function call.
3103 simplify_function(Oid funcid, Oid result_type, int32 result_typmod,
3106 eval_const_expressions_context *context)
3108 HeapTuple func_tuple;
3112 * We have two strategies for simplification: either execute the function
3113 * to deliver a constant result, or expand in-line the body of the
3114 * function definition (which only works for simple SQL-language
3115 * functions, but that is a common case). In either case we need access
3116 * to the function's pg_proc tuple, so fetch it just once to use in both
3119 func_tuple = SearchSysCache(PROCOID,
3120 ObjectIdGetDatum(funcid),
3122 if (!HeapTupleIsValid(func_tuple))
3123 elog(ERROR, "cache lookup failed for function %u", funcid);
3125 newexpr = evaluate_function(funcid, result_type, result_typmod, args,
3126 func_tuple, context);
3128 if (!newexpr && allow_inline)
3129 newexpr = inline_function(funcid, result_type, args,
3130 func_tuple, context);
3132 ReleaseSysCache(func_tuple);
3138 * evaluate_function: try to pre-evaluate a function call
3140 * We can do this if the function is strict and has any constant-null inputs
3141 * (just return a null constant), or if the function is immutable and has all
3142 * constant inputs (call it and return the result as a Const node). In
3143 * estimation mode we are willing to pre-evaluate stable functions too.
3145 * Returns a simplified expression if successful, or NULL if cannot
3146 * simplify the function.
3149 evaluate_function(Oid funcid, Oid result_type, int32 result_typmod, List *args,
3150 HeapTuple func_tuple,
3151 eval_const_expressions_context *context)
3153 Form_pg_proc funcform = (Form_pg_proc) GETSTRUCT(func_tuple);
3154 bool has_nonconst_input = false;
3155 bool has_null_input = false;
3160 * Can't simplify if it returns a set.
3162 if (funcform->proretset)
3166 * Can't simplify if it returns RECORD. The immediate problem is that it
3167 * will be needing an expected tupdesc which we can't supply here.
3169 * In the case where it has OUT parameters, it could get by without an
3170 * expected tupdesc, but we still have issues: get_expr_result_type()
3171 * doesn't know how to extract type info from a RECORD constant, and in
3172 * the case of a NULL function result there doesn't seem to be any clean
3173 * way to fix that. In view of the likelihood of there being still other
3174 * gotchas, seems best to leave the function call unreduced.
3176 if (funcform->prorettype == RECORDOID)
3180 * Check for constant inputs and especially constant-NULL inputs.
3184 if (IsA(lfirst(arg), Const))
3185 has_null_input |= ((Const *) lfirst(arg))->constisnull;
3187 has_nonconst_input = true;
3191 * If the function is strict and has a constant-NULL input, it will never
3192 * be called at all, so we can replace the call by a NULL constant, even
3193 * if there are other inputs that aren't constant, and even if the
3194 * function is not otherwise immutable.
3196 if (funcform->proisstrict && has_null_input)
3197 return (Expr *) makeNullConst(result_type, result_typmod);
3200 * Otherwise, can simplify only if all inputs are constants. (For a
3201 * non-strict function, constant NULL inputs are treated the same as
3202 * constant non-NULL inputs.)
3204 if (has_nonconst_input)
3208 * Ordinarily we are only allowed to simplify immutable functions. But for
3209 * purposes of estimation, we consider it okay to simplify functions that
3210 * are merely stable; the risk that the result might change from planning
3211 * time to execution time is worth taking in preference to not being able
3212 * to estimate the value at all.
3214 if (funcform->provolatile == PROVOLATILE_IMMUTABLE)
3216 else if (context->estimate && funcform->provolatile == PROVOLATILE_STABLE)
3222 * OK, looks like we can simplify this operator/function.
3224 * Build a new FuncExpr node containing the already-simplified arguments.
3226 newexpr = makeNode(FuncExpr);
3227 newexpr->funcid = funcid;
3228 newexpr->funcresulttype = result_type;
3229 newexpr->funcretset = false;
3230 newexpr->funcformat = COERCE_DONTCARE; /* doesn't matter */
3231 newexpr->args = args;
3232 newexpr->location = -1;
3234 return evaluate_expr((Expr *) newexpr, result_type, result_typmod);
3238 * inline_function: try to expand a function call inline
3240 * If the function is a sufficiently simple SQL-language function
3241 * (just "SELECT expression"), then we can inline it and avoid the rather
3242 * high per-call overhead of SQL functions. Furthermore, this can expose
3243 * opportunities for constant-folding within the function expression.
3245 * We have to beware of some special cases however. A directly or
3246 * indirectly recursive function would cause us to recurse forever,
3247 * so we keep track of which functions we are already expanding and
3248 * do not re-expand them. Also, if a parameter is used more than once
3249 * in the SQL-function body, we require it not to contain any volatile
3250 * functions (volatiles might deliver inconsistent answers) nor to be
3251 * unreasonably expensive to evaluate. The expensiveness check not only
3252 * prevents us from doing multiple evaluations of an expensive parameter
3253 * at runtime, but is a safety value to limit growth of an expression due
3254 * to repeated inlining.
3256 * We must also beware of changing the volatility or strictness status of
3257 * functions by inlining them.
3259 * Returns a simplified expression if successful, or NULL if cannot
3260 * simplify the function.
3263 inline_function(Oid funcid, Oid result_type, List *args,
3264 HeapTuple func_tuple,
3265 eval_const_expressions_context *context)
3267 Form_pg_proc funcform = (Form_pg_proc) GETSTRUCT(func_tuple);
3272 MemoryContext oldcxt;
3273 MemoryContext mycxt;
3274 ErrorContextCallback sqlerrcontext;
3275 List *raw_parsetree_list;
3283 * Forget it if the function is not SQL-language or has other showstopper
3284 * properties. (The nargs check is just paranoia.)
3286 if (funcform->prolang != SQLlanguageId ||
3287 funcform->prosecdef ||
3288 funcform->proretset ||
3289 !heap_attisnull(func_tuple, Anum_pg_proc_proconfig) ||
3290 funcform->pronargs != list_length(args))
3293 /* Check for recursive function, and give up trying to expand if so */
3294 if (list_member_oid(context->active_fns, funcid))
3297 /* Check permission to call function (fail later, if not) */
3298 if (pg_proc_aclcheck(funcid, GetUserId(), ACL_EXECUTE) != ACLCHECK_OK)
3302 * Setup error traceback support for ereport(). This is so that we can
3303 * finger the function that bad information came from.
3305 sqlerrcontext.callback = sql_inline_error_callback;
3306 sqlerrcontext.arg = func_tuple;
3307 sqlerrcontext.previous = error_context_stack;
3308 error_context_stack = &sqlerrcontext;
3311 * Make a temporary memory context, so that we don't leak all the stuff
3312 * that parsing might create.
3314 mycxt = AllocSetContextCreate(CurrentMemoryContext,
3316 ALLOCSET_DEFAULT_MINSIZE,
3317 ALLOCSET_DEFAULT_INITSIZE,
3318 ALLOCSET_DEFAULT_MAXSIZE);
3319 oldcxt = MemoryContextSwitchTo(mycxt);
3321 /* Check for polymorphic arguments, and substitute actual arg types */
3322 argtypes = (Oid *) palloc(funcform->pronargs * sizeof(Oid));
3323 memcpy(argtypes, funcform->proargtypes.values,
3324 funcform->pronargs * sizeof(Oid));
3325 for (i = 0; i < funcform->pronargs; i++)
3327 if (IsPolymorphicType(argtypes[i]))
3329 argtypes[i] = exprType((Node *) list_nth(args, i));
3333 /* Fetch and parse the function body */
3334 tmp = SysCacheGetAttr(PROCOID,
3336 Anum_pg_proc_prosrc,
3339 elog(ERROR, "null prosrc for function %u", funcid);
3340 src = TextDatumGetCString(tmp);
3343 * We just do parsing and parse analysis, not rewriting, because rewriting
3344 * will not affect table-free-SELECT-only queries, which is all that we
3345 * care about. Also, we can punt as soon as we detect more than one
3346 * command in the function body.
3348 raw_parsetree_list = pg_parse_query(src);
3349 if (list_length(raw_parsetree_list) != 1)
3352 querytree = parse_analyze(linitial(raw_parsetree_list), src,
3353 argtypes, funcform->pronargs);
3356 * The single command must be a simple "SELECT expression".
3358 if (!IsA(querytree, Query) ||
3359 querytree->commandType != CMD_SELECT ||
3360 querytree->utilityStmt ||
3361 querytree->intoClause ||
3362 querytree->hasAggs ||
3363 querytree->hasSubLinks ||
3364 querytree->cteList ||
3365 querytree->rtable ||
3366 querytree->jointree->fromlist ||
3367 querytree->jointree->quals ||
3368 querytree->groupClause ||
3369 querytree->havingQual ||
3370 querytree->distinctClause ||
3371 querytree->sortClause ||
3372 querytree->limitOffset ||
3373 querytree->limitCount ||
3374 querytree->setOperations ||
3375 list_length(querytree->targetList) != 1)
3379 * Make sure the function (still) returns what it's declared to. This
3380 * will raise an error if wrong, but that's okay since the function would
3381 * fail at runtime anyway. Note that check_sql_fn_retval will also insert
3382 * a RelabelType if needed to make the tlist expression match the declared
3383 * type of the function.
3385 * Note: we do not try this until we have verified that no rewriting was
3386 * needed; that's probably not important, but let's be careful.
3388 if (check_sql_fn_retval(funcid, result_type, list_make1(querytree),
3390 goto fail; /* reject whole-tuple-result cases */
3392 /* Now we can grab the tlist expression */
3393 newexpr = (Node *) ((TargetEntry *) linitial(querytree->targetList))->expr;
3395 /* Assert that check_sql_fn_retval did the right thing */
3396 Assert(exprType(newexpr) == result_type);
3399 * Additional validity checks on the expression. It mustn't return a set,
3400 * and it mustn't be more volatile than the surrounding function (this is
3401 * to avoid breaking hacks that involve pretending a function is immutable
3402 * when it really ain't). If the surrounding function is declared strict,
3403 * then the expression must contain only strict constructs and must use
3404 * all of the function parameters (this is overkill, but an exact analysis
3407 if (expression_returns_set(newexpr))
3410 if (funcform->provolatile == PROVOLATILE_IMMUTABLE &&
3411 contain_mutable_functions(newexpr))
3413 else if (funcform->provolatile == PROVOLATILE_STABLE &&
3414 contain_volatile_functions(newexpr))
3417 if (funcform->proisstrict &&
3418 contain_nonstrict_functions(newexpr))
3422 * We may be able to do it; there are still checks on parameter usage to
3423 * make, but those are most easily done in combination with the actual
3424 * substitution of the inputs. So start building expression with inputs
3427 usecounts = (int *) palloc0(funcform->pronargs * sizeof(int));
3428 newexpr = substitute_actual_parameters(newexpr, funcform->pronargs,
3431 /* Now check for parameter usage */
3435 Node *param = lfirst(arg);
3437 if (usecounts[i] == 0)
3439 /* Param not used at all: uncool if func is strict */
3440 if (funcform->proisstrict)
3443 else if (usecounts[i] != 1)
3445 /* Param used multiple times: uncool if expensive or volatile */
3449 * We define "expensive" as "contains any subplan or more than 10
3450 * operators". Note that the subplan search has to be done
3451 * explicitly, since cost_qual_eval() will barf on unplanned
3454 if (contain_subplans(param))
3456 cost_qual_eval(&eval_cost, list_make1(param), NULL);
3457 if (eval_cost.startup + eval_cost.per_tuple >
3458 10 * cpu_operator_cost)
3462 * Check volatility last since this is more expensive than the
3465 if (contain_volatile_functions(param))
3472 * Whew --- we can make the substitution. Copy the modified expression
3473 * out of the temporary memory context, and clean up.
3475 MemoryContextSwitchTo(oldcxt);
3477 newexpr = copyObject(newexpr);
3479 MemoryContextDelete(mycxt);
3482 * Since there is now no trace of the function in the plan tree, we
3483 * must explicitly record the plan's dependency on the function.
3486 record_plan_function_dependency(context->glob, funcid);
3489 * Recursively try to simplify the modified expression. Here we must add
3490 * the current function to the context list of active functions.
3492 context->active_fns = lcons_oid(funcid, context->active_fns);
3493 newexpr = eval_const_expressions_mutator(newexpr, context);
3494 context->active_fns = list_delete_first(context->active_fns);
3496 error_context_stack = sqlerrcontext.previous;
3498 return (Expr *) newexpr;
3500 /* Here if func is not inlinable: release temp memory and return NULL */
3502 MemoryContextSwitchTo(oldcxt);
3503 MemoryContextDelete(mycxt);
3504 error_context_stack = sqlerrcontext.previous;
3510 * Replace Param nodes by appropriate actual parameters
3513 substitute_actual_parameters(Node *expr, int nargs, List *args,
3516 substitute_actual_parameters_context context;
3518 context.nargs = nargs;
3519 context.args = args;
3520 context.usecounts = usecounts;
3522 return substitute_actual_parameters_mutator(expr, &context);
3526 substitute_actual_parameters_mutator(Node *node,
3527 substitute_actual_parameters_context *context)
3531 if (IsA(node, Param))
3533 Param *param = (Param *) node;
3535 if (param->paramkind != PARAM_EXTERN)
3536 elog(ERROR, "unexpected paramkind: %d", (int) param->paramkind);
3537 if (param->paramid <= 0 || param->paramid > context->nargs)
3538 elog(ERROR, "invalid paramid: %d", param->paramid);
3540 /* Count usage of parameter */
3541 context->usecounts[param->paramid - 1]++;
3543 /* Select the appropriate actual arg and replace the Param with it */
3544 /* We don't need to copy at this time (it'll get done later) */
3545 return list_nth(context->args, param->paramid - 1);
3547 return expression_tree_mutator(node, substitute_actual_parameters_mutator,
3552 * error context callback to let us supply a call-stack traceback
3555 sql_inline_error_callback(void *arg)
3557 HeapTuple func_tuple = (HeapTuple) arg;
3558 Form_pg_proc funcform = (Form_pg_proc) GETSTRUCT(func_tuple);
3559 int syntaxerrposition;
3561 /* If it's a syntax error, convert to internal syntax error report */
3562 syntaxerrposition = geterrposition();
3563 if (syntaxerrposition > 0)
3569 tmp = SysCacheGetAttr(PROCOID, func_tuple, Anum_pg_proc_prosrc,
3572 elog(ERROR, "null prosrc");
3573 prosrc = TextDatumGetCString(tmp);
3575 internalerrposition(syntaxerrposition);
3576 internalerrquery(prosrc);
3579 errcontext("SQL function \"%s\" during inlining",
3580 NameStr(funcform->proname));
3584 * evaluate_expr: pre-evaluate a constant expression
3586 * We use the executor's routine ExecEvalExpr() to avoid duplication of
3587 * code and ensure we get the same result as the executor would get.
3590 evaluate_expr(Expr *expr, Oid result_type, int32 result_typmod)
3593 ExprState *exprstate;
3594 MemoryContext oldcontext;
3598 bool resultTypByVal;
3601 * To use the executor, we need an EState.
3603 estate = CreateExecutorState();
3605 /* We can use the estate's working context to avoid memory leaks. */
3606 oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
3609 * Prepare expr for execution.
3611 exprstate = ExecPrepareExpr(expr, estate);
3616 * It is OK to use a default econtext because none of the ExecEvalExpr()
3617 * code used in this situation will use econtext. That might seem
3618 * fortuitous, but it's not so unreasonable --- a constant expression does
3619 * not depend on context, by definition, n'est ce pas?
3621 const_val = ExecEvalExprSwitchContext(exprstate,
3622 GetPerTupleExprContext(estate),
3623 &const_is_null, NULL);
3625 /* Get info needed about result datatype */
3626 get_typlenbyval(result_type, &resultTypLen, &resultTypByVal);
3628 /* Get back to outer memory context */
3629 MemoryContextSwitchTo(oldcontext);
3632 * Must copy result out of sub-context used by expression eval.
3634 * Also, if it's varlena, forcibly detoast it. This protects us against
3635 * storing TOAST pointers into plans that might outlive the referenced
3640 if (resultTypLen == -1)
3641 const_val = PointerGetDatum(PG_DETOAST_DATUM_COPY(const_val));
3643 const_val = datumCopy(const_val, resultTypByVal, resultTypLen);
3646 /* Release all the junk we just created */
3647 FreeExecutorState(estate);
3650 * Make the constant result node.
3652 return (Expr *) makeConst(result_type, result_typmod, resultTypLen,
3653 const_val, const_is_null,
3659 * inline_set_returning_function
3660 * Attempt to "inline" a set-returning function in the FROM clause.
3662 * "node" is the expression from an RTE_FUNCTION rangetable entry. If it
3663 * represents a call of a set-returning SQL function that can safely be
3664 * inlined, expand the function and return the substitute Query structure.
3665 * Otherwise, return NULL.
3667 * This has a good deal of similarity to inline_function(), but that's
3668 * for the non-set-returning case, and there are enough differences to
3669 * justify separate functions.
3672 inline_set_returning_function(PlannerInfo *root, Node *node)
3675 HeapTuple func_tuple;
3676 Form_pg_proc funcform;
3681 MemoryContext oldcxt;
3682 MemoryContext mycxt;
3683 ErrorContextCallback sqlerrcontext;
3684 List *raw_parsetree_list;
3685 List *querytree_list;
3690 * It doesn't make a lot of sense for a SQL SRF to refer to itself
3691 * in its own FROM clause, since that must cause infinite recursion
3692 * at runtime. It will cause this code to recurse too, so check
3693 * for stack overflow. (There's no need to do more.)
3695 check_stack_depth();
3697 /* Fail if FROM item isn't a simple FuncExpr */
3698 if (node == NULL || !IsA(node, FuncExpr))
3700 fexpr = (FuncExpr *) node;
3703 * The function must be declared to return a set, else inlining would
3704 * change the results if the contained SELECT didn't return exactly
3707 if (!fexpr->funcretset)
3710 /* Fail if function returns RECORD ... we don't have enough context */
3711 if (fexpr->funcresulttype == RECORDOID)
3715 * Refuse to inline if the arguments contain any volatile functions or
3716 * sub-selects. Volatile functions are rejected because inlining may
3717 * result in the arguments being evaluated multiple times, risking a
3718 * change in behavior. Sub-selects are rejected partly for implementation
3719 * reasons (pushing them down another level might change their behavior)
3720 * and partly because they're likely to be expensive and so multiple
3721 * evaluation would be bad.
3723 if (contain_volatile_functions((Node *) fexpr->args) ||
3724 contain_subplans((Node *) fexpr->args))
3727 /* Check permission to call function (fail later, if not) */
3728 if (pg_proc_aclcheck(fexpr->funcid, GetUserId(), ACL_EXECUTE) != ACLCHECK_OK)
3732 * OK, let's take a look at the function's pg_proc entry.
3734 func_tuple = SearchSysCache(PROCOID,
3735 ObjectIdGetDatum(fexpr->funcid),
3737 if (!HeapTupleIsValid(func_tuple))
3738 elog(ERROR, "cache lookup failed for function %u", fexpr->funcid);
3739 funcform = (Form_pg_proc) GETSTRUCT(func_tuple);
3742 * Forget it if the function is not SQL-language or has other showstopper
3743 * properties. In particular it mustn't be declared STRICT, since we
3744 * couldn't enforce that. It also mustn't be VOLATILE, because that is
3745 * supposed to cause it to be executed with its own snapshot, rather than
3746 * sharing the snapshot of the calling query. (The nargs check is just
3747 * paranoia, ditto rechecking proretset.)
3749 if (funcform->prolang != SQLlanguageId ||
3750 funcform->proisstrict ||
3751 funcform->provolatile == PROVOLATILE_VOLATILE ||
3752 funcform->prosecdef ||
3753 !funcform->proretset ||
3754 !heap_attisnull(func_tuple, Anum_pg_proc_proconfig) ||
3755 funcform->pronargs != list_length(fexpr->args))
3757 ReleaseSysCache(func_tuple);
3762 * Setup error traceback support for ereport(). This is so that we can
3763 * finger the function that bad information came from.
3765 sqlerrcontext.callback = sql_inline_error_callback;
3766 sqlerrcontext.arg = func_tuple;
3767 sqlerrcontext.previous = error_context_stack;
3768 error_context_stack = &sqlerrcontext;
3771 * Make a temporary memory context, so that we don't leak all the stuff
3772 * that parsing might create.
3774 mycxt = AllocSetContextCreate(CurrentMemoryContext,
3775 "inline_set_returning_function",
3776 ALLOCSET_DEFAULT_MINSIZE,
3777 ALLOCSET_DEFAULT_INITSIZE,
3778 ALLOCSET_DEFAULT_MAXSIZE);
3779 oldcxt = MemoryContextSwitchTo(mycxt);
3781 /* Check for polymorphic arguments, and substitute actual arg types */
3782 argtypes = (Oid *) palloc(funcform->pronargs * sizeof(Oid));
3783 memcpy(argtypes, funcform->proargtypes.values,
3784 funcform->pronargs * sizeof(Oid));
3785 for (i = 0; i < funcform->pronargs; i++)
3787 if (IsPolymorphicType(argtypes[i]))
3789 argtypes[i] = exprType((Node *) list_nth(fexpr->args, i));
3793 /* Fetch and parse the function body */
3794 tmp = SysCacheGetAttr(PROCOID,
3796 Anum_pg_proc_prosrc,
3799 elog(ERROR, "null prosrc for function %u", fexpr->funcid);
3800 src = TextDatumGetCString(tmp);
3803 * Parse, analyze, and rewrite (unlike inline_function(), we can't
3804 * skip rewriting here). We can fail as soon as we find more than
3805 * one query, though.
3807 raw_parsetree_list = pg_parse_query(src);
3808 if (list_length(raw_parsetree_list) != 1)
3811 querytree_list = pg_analyze_and_rewrite(linitial(raw_parsetree_list), src,
3812 argtypes, funcform->pronargs);
3813 if (list_length(querytree_list) != 1)
3815 querytree = linitial(querytree_list);
3818 * The single command must be a regular results-returning SELECT.
3820 if (!IsA(querytree, Query) ||
3821 querytree->commandType != CMD_SELECT ||
3822 querytree->utilityStmt ||
3823 querytree->intoClause)
3827 * Make sure the function (still) returns what it's declared to. This
3828 * will raise an error if wrong, but that's okay since the function would
3829 * fail at runtime anyway. Note that check_sql_fn_retval will also insert
3830 * RelabelType(s) if needed to make the tlist expression(s) match the
3831 * declared type of the function.
3833 * If the function returns a composite type, don't inline unless the
3834 * check shows it's returning a whole tuple result; otherwise what
3835 * it's returning is a single composite column which is not what we need.
3837 if (!check_sql_fn_retval(fexpr->funcid, fexpr->funcresulttype,
3840 get_typtype(fexpr->funcresulttype) == TYPTYPE_COMPOSITE)
3841 goto fail; /* reject not-whole-tuple-result cases */
3844 * Looks good --- substitute parameters into the query.
3846 querytree = substitute_actual_srf_parameters(querytree,
3851 * Copy the modified query out of the temporary memory context,
3854 MemoryContextSwitchTo(oldcxt);
3856 querytree = copyObject(querytree);
3858 MemoryContextDelete(mycxt);
3859 error_context_stack = sqlerrcontext.previous;
3860 ReleaseSysCache(func_tuple);
3863 * Since there is now no trace of the function in the plan tree, we
3864 * must explicitly record the plan's dependency on the function.
3866 record_plan_function_dependency(root->glob, fexpr->funcid);
3870 /* Here if func is not inlinable: release temp memory and return NULL */
3872 MemoryContextSwitchTo(oldcxt);
3873 MemoryContextDelete(mycxt);
3874 error_context_stack = sqlerrcontext.previous;
3875 ReleaseSysCache(func_tuple);
3881 * Replace Param nodes by appropriate actual parameters
3883 * This is just enough different from substitute_actual_parameters()
3884 * that it needs its own code.
3887 substitute_actual_srf_parameters(Query *expr, int nargs, List *args)
3889 substitute_actual_srf_parameters_context context;
3891 context.nargs = nargs;
3892 context.args = args;
3893 context.sublevels_up = 1;
3895 return query_tree_mutator(expr,
3896 substitute_actual_srf_parameters_mutator,
3902 substitute_actual_srf_parameters_mutator(Node *node,
3903 substitute_actual_srf_parameters_context *context)
3909 if (IsA(node, Query))
3911 context->sublevels_up++;
3912 result = (Node *) query_tree_mutator((Query *) node,
3913 substitute_actual_srf_parameters_mutator,
3916 context->sublevels_up--;
3919 if (IsA(node, Param))
3921 Param *param = (Param *) node;
3923 if (param->paramkind == PARAM_EXTERN)
3925 if (param->paramid <= 0 || param->paramid > context->nargs)
3926 elog(ERROR, "invalid paramid: %d", param->paramid);
3929 * Since the parameter is being inserted into a subquery,
3930 * we must adjust levels.
3932 result = copyObject(list_nth(context->args, param->paramid - 1));
3933 IncrementVarSublevelsUp(result, context->sublevels_up, 0);
3937 return expression_tree_mutator(node,
3938 substitute_actual_srf_parameters_mutator,