1 /*-------------------------------------------------------------------------
4 * routines to manipulate qualification clauses
6 * Portions Copyright (c) 1996-2012, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
11 * src/backend/optimizer/util/clauses.c
14 * AUTHOR DATE MAJOR EVENT
15 * Andrew Yu Nov 3, 1994 clause.c and clauses.c combined
17 *-------------------------------------------------------------------------
22 #include "catalog/pg_aggregate.h"
23 #include "catalog/pg_language.h"
24 #include "catalog/pg_operator.h"
25 #include "catalog/pg_proc.h"
26 #include "catalog/pg_type.h"
27 #include "executor/executor.h"
28 #include "executor/functions.h"
30 #include "miscadmin.h"
31 #include "nodes/makefuncs.h"
32 #include "nodes/nodeFuncs.h"
33 #include "optimizer/clauses.h"
34 #include "optimizer/cost.h"
35 #include "optimizer/planmain.h"
36 #include "optimizer/prep.h"
37 #include "optimizer/var.h"
38 #include "parser/analyze.h"
39 #include "parser/parse_coerce.h"
40 #include "parser/parse_func.h"
41 #include "rewrite/rewriteManip.h"
42 #include "tcop/tcopprot.h"
43 #include "utils/acl.h"
44 #include "utils/builtins.h"
45 #include "utils/datum.h"
46 #include "utils/lsyscache.h"
47 #include "utils/memutils.h"
48 #include "utils/syscache.h"
49 #include "utils/typcache.h"
55 AggClauseCosts *costs;
56 } count_agg_clauses_context;
60 ParamListInfo boundParams;
65 } eval_const_expressions_context;
72 } substitute_actual_parameters_context;
79 } substitute_actual_srf_parameters_context;
85 } inline_error_callback_arg;
87 static bool contain_agg_clause_walker(Node *node, void *context);
88 static bool count_agg_clauses_walker(Node *node,
89 count_agg_clauses_context *context);
90 static bool find_window_functions_walker(Node *node, WindowFuncLists *lists);
91 static bool expression_returns_set_rows_walker(Node *node, double *count);
92 static bool contain_subplans_walker(Node *node, void *context);
93 static bool contain_mutable_functions_walker(Node *node, void *context);
94 static bool contain_volatile_functions_walker(Node *node, void *context);
95 static bool contain_nonstrict_functions_walker(Node *node, void *context);
96 static bool contain_leaky_functions_walker(Node *node, void *context);
97 static Relids find_nonnullable_rels_walker(Node *node, bool top_level);
98 static List *find_nonnullable_vars_walker(Node *node, bool top_level);
99 static bool is_strict_saop(ScalarArrayOpExpr *expr, bool falseOK);
100 static bool set_coercionform_dontcare_walker(Node *node, void *context);
101 static Node *eval_const_expressions_mutator(Node *node,
102 eval_const_expressions_context *context);
103 static List *simplify_or_arguments(List *args,
104 eval_const_expressions_context *context,
105 bool *haveNull, bool *forceTrue);
106 static List *simplify_and_arguments(List *args,
107 eval_const_expressions_context *context,
108 bool *haveNull, bool *forceFalse);
109 static Node *simplify_boolean_equality(Oid opno, List *args);
110 static Expr *simplify_function(Oid funcid,
111 Oid result_type, int32 result_typmod,
112 Oid result_collid, Oid input_collid, List **args_p,
113 bool process_args, bool allow_non_const,
114 eval_const_expressions_context *context);
115 static List *expand_function_arguments(List *args, Oid result_type,
116 HeapTuple func_tuple);
117 static List *reorder_function_arguments(List *args, HeapTuple func_tuple);
118 static List *add_function_defaults(List *args, HeapTuple func_tuple);
119 static List *fetch_function_defaults(HeapTuple func_tuple);
120 static void recheck_cast_function_args(List *args, Oid result_type,
121 HeapTuple func_tuple);
122 static Expr *evaluate_function(Oid funcid, Oid result_type, int32 result_typmod,
123 Oid result_collid, Oid input_collid, List *args,
124 HeapTuple func_tuple,
125 eval_const_expressions_context *context);
126 static Expr *inline_function(Oid funcid, Oid result_type, Oid result_collid,
127 Oid input_collid, List *args,
128 HeapTuple func_tuple,
129 eval_const_expressions_context *context);
130 static Node *substitute_actual_parameters(Node *expr, int nargs, List *args,
132 static Node *substitute_actual_parameters_mutator(Node *node,
133 substitute_actual_parameters_context *context);
134 static void sql_inline_error_callback(void *arg);
135 static Expr *evaluate_expr(Expr *expr, Oid result_type, int32 result_typmod,
136 Oid result_collation);
137 static Query *substitute_actual_srf_parameters(Query *expr,
138 int nargs, List *args);
139 static Node *substitute_actual_srf_parameters_mutator(Node *node,
140 substitute_actual_srf_parameters_context *context);
141 static bool tlist_matches_coltypelist(List *tlist, List *coltypelist);
144 /*****************************************************************************
145 * OPERATOR clause functions
146 *****************************************************************************/
150 * Creates an operator clause given its operator info, left operand
151 * and right operand (pass NULL to create single-operand clause),
152 * and collation info.
155 make_opclause(Oid opno, Oid opresulttype, bool opretset,
156 Expr *leftop, Expr *rightop,
157 Oid opcollid, Oid inputcollid)
159 OpExpr *expr = makeNode(OpExpr);
162 expr->opfuncid = InvalidOid;
163 expr->opresulttype = opresulttype;
164 expr->opretset = opretset;
165 expr->opcollid = opcollid;
166 expr->inputcollid = inputcollid;
168 expr->args = list_make2(leftop, rightop);
170 expr->args = list_make1(leftop);
172 return (Expr *) expr;
178 * Returns the left operand of a clause of the form (op expr expr)
182 get_leftop(const Expr *clause)
184 const OpExpr *expr = (const OpExpr *) clause;
186 if (expr->args != NIL)
187 return linitial(expr->args);
195 * Returns the right operand in a clause of the form (op expr expr).
196 * NB: result will be NULL if applied to a unary op clause.
199 get_rightop(const Expr *clause)
201 const OpExpr *expr = (const OpExpr *) clause;
203 if (list_length(expr->args) >= 2)
204 return lsecond(expr->args);
209 /*****************************************************************************
210 * NOT clause functions
211 *****************************************************************************/
216 * Returns t iff this is a 'not' clause: (NOT expr).
219 not_clause(Node *clause)
221 return (clause != NULL &&
222 IsA(clause, BoolExpr) &&
223 ((BoolExpr *) clause)->boolop == NOT_EXPR);
229 * Create a 'not' clause given the expression to be negated.
232 make_notclause(Expr *notclause)
234 BoolExpr *expr = makeNode(BoolExpr);
236 expr->boolop = NOT_EXPR;
237 expr->args = list_make1(notclause);
239 return (Expr *) expr;
245 * Retrieve the clause within a 'not' clause
248 get_notclausearg(Expr *notclause)
250 return linitial(((BoolExpr *) notclause)->args);
253 /*****************************************************************************
254 * OR clause functions
255 *****************************************************************************/
260 * Returns t iff the clause is an 'or' clause: (OR { expr }).
263 or_clause(Node *clause)
265 return (clause != NULL &&
266 IsA(clause, BoolExpr) &&
267 ((BoolExpr *) clause)->boolop == OR_EXPR);
273 * Creates an 'or' clause given a list of its subclauses.
276 make_orclause(List *orclauses)
278 BoolExpr *expr = makeNode(BoolExpr);
280 expr->boolop = OR_EXPR;
281 expr->args = orclauses;
283 return (Expr *) expr;
286 /*****************************************************************************
287 * AND clause functions
288 *****************************************************************************/
294 * Returns t iff its argument is an 'and' clause: (AND { expr }).
297 and_clause(Node *clause)
299 return (clause != NULL &&
300 IsA(clause, BoolExpr) &&
301 ((BoolExpr *) clause)->boolop == AND_EXPR);
307 * Creates an 'and' clause given a list of its subclauses.
310 make_andclause(List *andclauses)
312 BoolExpr *expr = makeNode(BoolExpr);
314 expr->boolop = AND_EXPR;
315 expr->args = andclauses;
317 return (Expr *) expr;
323 * Variant of make_andclause for ANDing two qual conditions together.
324 * Qual conditions have the property that a NULL nodetree is interpreted
327 * NB: this makes no attempt to preserve AND/OR flatness; so it should not
328 * be used on a qual that has already been run through prepqual.c.
331 make_and_qual(Node *qual1, Node *qual2)
337 return (Node *) make_andclause(list_make2(qual1, qual2));
341 * Sometimes (such as in the input of ExecQual), we use lists of expression
342 * nodes with implicit AND semantics.
344 * These functions convert between an AND-semantics expression list and the
345 * ordinary representation of a boolean expression.
347 * Note that an empty list is considered equivalent to TRUE.
350 make_ands_explicit(List *andclauses)
352 if (andclauses == NIL)
353 return (Expr *) makeBoolConst(true, false);
354 else if (list_length(andclauses) == 1)
355 return (Expr *) linitial(andclauses);
357 return make_andclause(andclauses);
361 make_ands_implicit(Expr *clause)
364 * NB: because the parser sets the qual field to NULL in a query that has
365 * no WHERE clause, we must consider a NULL input clause as TRUE, even
366 * though one might more reasonably think it FALSE. Grumble. If this
367 * causes trouble, consider changing the parser's behavior.
370 return NIL; /* NULL -> NIL list == TRUE */
371 else if (and_clause((Node *) clause))
372 return ((BoolExpr *) clause)->args;
373 else if (IsA(clause, Const) &&
374 !((Const *) clause)->constisnull &&
375 DatumGetBool(((Const *) clause)->constvalue))
376 return NIL; /* constant TRUE input -> NIL list */
378 return list_make1(clause);
382 /*****************************************************************************
383 * Aggregate-function clause manipulation
384 *****************************************************************************/
388 * Recursively search for Aggref nodes within a clause.
390 * Returns true if any aggregate found.
392 * This does not descend into subqueries, and so should be used only after
393 * reduction of sublinks to subplans, or in contexts where it's known there
394 * are no subqueries. There mustn't be outer-aggregate references either.
396 * (If you want something like this but able to deal with subqueries,
397 * see rewriteManip.c's contain_aggs_of_level().)
400 contain_agg_clause(Node *clause)
402 return contain_agg_clause_walker(clause, NULL);
406 contain_agg_clause_walker(Node *node, void *context)
410 if (IsA(node, Aggref))
412 Assert(((Aggref *) node)->agglevelsup == 0);
413 return true; /* abort the tree traversal and return true */
415 Assert(!IsA(node, SubLink));
416 return expression_tree_walker(node, contain_agg_clause_walker, context);
421 * Recursively count the Aggref nodes in an expression tree, and
422 * accumulate other cost information about them too.
424 * Note: this also checks for nested aggregates, which are an error.
426 * We not only count the nodes, but estimate their execution costs, and
427 * attempt to estimate the total space needed for their transition state
428 * values if all are evaluated in parallel (as would be done in a HashAgg
429 * plan). See AggClauseCosts for the exact set of statistics collected.
431 * NOTE that the counts/costs are ADDED to those already in *costs ... so
432 * the caller is responsible for zeroing the struct initially.
434 * This does not descend into subqueries, and so should be used only after
435 * reduction of sublinks to subplans, or in contexts where it's known there
436 * are no subqueries. There mustn't be outer-aggregate references either.
439 count_agg_clauses(PlannerInfo *root, Node *clause, AggClauseCosts *costs)
441 count_agg_clauses_context context;
444 context.costs = costs;
445 (void) count_agg_clauses_walker(clause, &context);
449 count_agg_clauses_walker(Node *node, count_agg_clauses_context *context)
453 if (IsA(node, Aggref))
455 Aggref *aggref = (Aggref *) node;
456 AggClauseCosts *costs = context->costs;
458 Form_pg_aggregate aggform;
467 Assert(aggref->agglevelsup == 0);
469 /* fetch info about aggregate from pg_aggregate */
470 aggTuple = SearchSysCache1(AGGFNOID,
471 ObjectIdGetDatum(aggref->aggfnoid));
472 if (!HeapTupleIsValid(aggTuple))
473 elog(ERROR, "cache lookup failed for aggregate %u",
475 aggform = (Form_pg_aggregate) GETSTRUCT(aggTuple);
476 aggtransfn = aggform->aggtransfn;
477 aggfinalfn = aggform->aggfinalfn;
478 aggtranstype = aggform->aggtranstype;
479 ReleaseSysCache(aggTuple);
483 if (aggref->aggorder != NIL || aggref->aggdistinct != NIL)
484 costs->numOrderedAggs++;
486 /* add component function execution costs to appropriate totals */
487 costs->transCost.per_tuple += get_func_cost(aggtransfn) * cpu_operator_cost;
488 if (OidIsValid(aggfinalfn))
489 costs->finalCost += get_func_cost(aggfinalfn) * cpu_operator_cost;
491 /* also add the input expressions' cost to per-input-row costs */
492 cost_qual_eval_node(&argcosts, (Node *) aggref->args, context->root);
493 costs->transCost.startup += argcosts.startup;
494 costs->transCost.per_tuple += argcosts.per_tuple;
496 /* extract argument types (ignoring any ORDER BY expressions) */
497 inputTypes = (Oid *) palloc(sizeof(Oid) * list_length(aggref->args));
499 foreach(l, aggref->args)
501 TargetEntry *tle = (TargetEntry *) lfirst(l);
504 inputTypes[numArguments++] = exprType((Node *) tle->expr);
507 /* resolve actual type of transition state, if polymorphic */
508 if (IsPolymorphicType(aggtranstype))
510 /* have to fetch the agg's declared input types... */
511 Oid *declaredArgTypes;
514 (void) get_func_signature(aggref->aggfnoid,
515 &declaredArgTypes, &agg_nargs);
516 Assert(agg_nargs == numArguments);
517 aggtranstype = enforce_generic_type_consistency(inputTypes,
522 pfree(declaredArgTypes);
526 * If the transition type is pass-by-value then it doesn't add
527 * anything to the required size of the hashtable. If it is
528 * pass-by-reference then we have to add the estimated size of the
529 * value itself, plus palloc overhead.
531 if (!get_typbyval(aggtranstype))
533 int32 aggtranstypmod;
537 * If transition state is of same type as first input, assume it's
538 * the same typmod (same width) as well. This works for cases
539 * like MAX/MIN and is probably somewhat reasonable otherwise.
541 if (numArguments > 0 && aggtranstype == inputTypes[0])
542 aggtranstypmod = exprTypmod((Node *) linitial(aggref->args));
546 avgwidth = get_typavgwidth(aggtranstype, aggtranstypmod);
547 avgwidth = MAXALIGN(avgwidth);
549 costs->transitionSpace += avgwidth + 2 * sizeof(void *);
551 else if (aggtranstype == INTERNALOID)
554 * INTERNAL transition type is a special case: although INTERNAL
555 * is pass-by-value, it's almost certainly being used as a pointer
556 * to some large data structure. We assume usage of
557 * ALLOCSET_DEFAULT_INITSIZE, which is a good guess if the data is
558 * being kept in a private memory context, as is done by
559 * array_agg() for instance.
561 costs->transitionSpace += ALLOCSET_DEFAULT_INITSIZE;
565 * Complain if the aggregate's arguments contain any aggregates;
566 * nested agg functions are semantically nonsensical.
568 if (contain_agg_clause((Node *) aggref->args))
570 (errcode(ERRCODE_GROUPING_ERROR),
571 errmsg("aggregate function calls cannot be nested")));
574 * Having checked that, we need not recurse into the argument.
578 Assert(!IsA(node, SubLink));
579 return expression_tree_walker(node, count_agg_clauses_walker,
584 /*****************************************************************************
585 * Window-function clause manipulation
586 *****************************************************************************/
589 * contain_window_function
590 * Recursively search for WindowFunc nodes within a clause.
592 * Since window functions don't have level fields, but are hard-wired to
593 * be associated with the current query level, this is just the same as
594 * rewriteManip.c's function.
597 contain_window_function(Node *clause)
599 return checkExprHasWindowFuncs(clause);
603 * find_window_functions
604 * Locate all the WindowFunc nodes in an expression tree, and organize
605 * them by winref ID number.
607 * Caller must provide an upper bound on the winref IDs expected in the tree.
610 find_window_functions(Node *clause, Index maxWinRef)
612 WindowFuncLists *lists = palloc(sizeof(WindowFuncLists));
614 lists->numWindowFuncs = 0;
615 lists->maxWinRef = maxWinRef;
616 lists->windowFuncs = (List **) palloc0((maxWinRef + 1) * sizeof(List *));
617 (void) find_window_functions_walker(clause, lists);
622 find_window_functions_walker(Node *node, WindowFuncLists *lists)
626 if (IsA(node, WindowFunc))
628 WindowFunc *wfunc = (WindowFunc *) node;
630 /* winref is unsigned, so one-sided test is OK */
631 if (wfunc->winref > lists->maxWinRef)
632 elog(ERROR, "WindowFunc contains out-of-range winref %u",
634 lists->windowFuncs[wfunc->winref] =
635 lappend(lists->windowFuncs[wfunc->winref], wfunc);
636 lists->numWindowFuncs++;
639 * Complain if the window function's arguments contain window
642 if (contain_window_function((Node *) wfunc->args))
644 (errcode(ERRCODE_WINDOWING_ERROR),
645 errmsg("window function calls cannot be nested")));
648 * Having checked that, we need not recurse into the argument.
652 Assert(!IsA(node, SubLink));
653 return expression_tree_walker(node, find_window_functions_walker,
658 /*****************************************************************************
659 * Support for expressions returning sets
660 *****************************************************************************/
663 * expression_returns_set_rows
664 * Estimate the number of rows returned by a set-returning expression.
665 * The result is 1 if there are no set-returning functions.
667 * We use the product of the rowcount estimates of all the functions in
668 * the given tree (this corresponds to the behavior of ExecMakeFunctionResult
669 * for nested set-returning functions).
671 * Note: keep this in sync with expression_returns_set() in nodes/nodeFuncs.c.
674 expression_returns_set_rows(Node *clause)
678 (void) expression_returns_set_rows_walker(clause, &result);
679 return clamp_row_est(result);
683 expression_returns_set_rows_walker(Node *node, double *count)
687 if (IsA(node, FuncExpr))
689 FuncExpr *expr = (FuncExpr *) node;
691 if (expr->funcretset)
692 *count *= get_func_rows(expr->funcid);
694 if (IsA(node, OpExpr))
696 OpExpr *expr = (OpExpr *) node;
701 *count *= get_func_rows(expr->opfuncid);
705 /* Avoid recursion for some cases that can't return a set */
706 if (IsA(node, Aggref))
708 if (IsA(node, WindowFunc))
710 if (IsA(node, DistinctExpr))
712 if (IsA(node, NullIfExpr))
714 if (IsA(node, ScalarArrayOpExpr))
716 if (IsA(node, BoolExpr))
718 if (IsA(node, SubLink))
720 if (IsA(node, SubPlan))
722 if (IsA(node, AlternativeSubPlan))
724 if (IsA(node, ArrayExpr))
726 if (IsA(node, RowExpr))
728 if (IsA(node, RowCompareExpr))
730 if (IsA(node, CoalesceExpr))
732 if (IsA(node, MinMaxExpr))
734 if (IsA(node, XmlExpr))
737 return expression_tree_walker(node, expression_returns_set_rows_walker,
742 * tlist_returns_set_rows
743 * Estimate the number of rows returned by a set-returning targetlist.
744 * The result is 1 if there are no set-returning functions.
746 * Here, the result is the largest rowcount estimate of any of the tlist's
747 * expressions, not the product as you would get from naively applying
748 * expression_returns_set_rows() to the whole tlist. The behavior actually
749 * implemented by ExecTargetList produces a number of rows equal to the least
750 * common multiple of the expression rowcounts, so that the product would be
751 * a worst-case estimate that is typically not realistic. Taking the max as
752 * we do here is a best-case estimate that might not be realistic either,
753 * but it's probably closer for typical usages. We don't try to compute the
754 * actual LCM because we're working with very approximate estimates, so their
755 * LCM would be unduly noisy.
758 tlist_returns_set_rows(List *tlist)
765 TargetEntry *tle = (TargetEntry *) lfirst(lc);
768 colresult = expression_returns_set_rows((Node *) tle->expr);
769 if (result < colresult)
776 /*****************************************************************************
777 * Subplan clause manipulation
778 *****************************************************************************/
782 * Recursively search for subplan nodes within a clause.
784 * If we see a SubLink node, we will return TRUE. This is only possible if
785 * the expression tree hasn't yet been transformed by subselect.c. We do not
786 * know whether the node will produce a true subplan or just an initplan,
787 * but we make the conservative assumption that it will be a subplan.
789 * Returns true if any subplan found.
792 contain_subplans(Node *clause)
794 return contain_subplans_walker(clause, NULL);
798 contain_subplans_walker(Node *node, void *context)
802 if (IsA(node, SubPlan) ||
803 IsA(node, AlternativeSubPlan) ||
805 return true; /* abort the tree traversal and return true */
806 return expression_tree_walker(node, contain_subplans_walker, context);
810 /*****************************************************************************
811 * Check clauses for mutable functions
812 *****************************************************************************/
815 * contain_mutable_functions
816 * Recursively search for mutable functions within a clause.
818 * Returns true if any mutable function (or operator implemented by a
819 * mutable function) is found. This test is needed so that we don't
820 * mistakenly think that something like "WHERE random() < 0.5" can be treated
821 * as a constant qualification.
823 * XXX we do not examine sub-selects to see if they contain uses of
824 * mutable functions. It's not real clear if that is correct or not...
827 contain_mutable_functions(Node *clause)
829 return contain_mutable_functions_walker(clause, NULL);
833 contain_mutable_functions_walker(Node *node, void *context)
837 if (IsA(node, FuncExpr))
839 FuncExpr *expr = (FuncExpr *) node;
841 if (func_volatile(expr->funcid) != PROVOLATILE_IMMUTABLE)
843 /* else fall through to check args */
845 else if (IsA(node, OpExpr))
847 OpExpr *expr = (OpExpr *) node;
850 if (func_volatile(expr->opfuncid) != PROVOLATILE_IMMUTABLE)
852 /* else fall through to check args */
854 else if (IsA(node, DistinctExpr))
856 DistinctExpr *expr = (DistinctExpr *) node;
858 set_opfuncid((OpExpr *) expr); /* rely on struct equivalence */
859 if (func_volatile(expr->opfuncid) != PROVOLATILE_IMMUTABLE)
861 /* else fall through to check args */
863 else if (IsA(node, NullIfExpr))
865 NullIfExpr *expr = (NullIfExpr *) node;
867 set_opfuncid((OpExpr *) expr); /* rely on struct equivalence */
868 if (func_volatile(expr->opfuncid) != PROVOLATILE_IMMUTABLE)
870 /* else fall through to check args */
872 else if (IsA(node, ScalarArrayOpExpr))
874 ScalarArrayOpExpr *expr = (ScalarArrayOpExpr *) node;
876 set_sa_opfuncid(expr);
877 if (func_volatile(expr->opfuncid) != PROVOLATILE_IMMUTABLE)
879 /* else fall through to check args */
881 else if (IsA(node, CoerceViaIO))
883 CoerceViaIO *expr = (CoerceViaIO *) node;
888 /* check the result type's input function */
889 getTypeInputInfo(expr->resulttype,
890 &iofunc, &typioparam);
891 if (func_volatile(iofunc) != PROVOLATILE_IMMUTABLE)
893 /* check the input type's output function */
894 getTypeOutputInfo(exprType((Node *) expr->arg),
895 &iofunc, &typisvarlena);
896 if (func_volatile(iofunc) != PROVOLATILE_IMMUTABLE)
898 /* else fall through to check args */
900 else if (IsA(node, ArrayCoerceExpr))
902 ArrayCoerceExpr *expr = (ArrayCoerceExpr *) node;
904 if (OidIsValid(expr->elemfuncid) &&
905 func_volatile(expr->elemfuncid) != PROVOLATILE_IMMUTABLE)
907 /* else fall through to check args */
909 else if (IsA(node, RowCompareExpr))
911 RowCompareExpr *rcexpr = (RowCompareExpr *) node;
914 foreach(opid, rcexpr->opnos)
916 if (op_volatile(lfirst_oid(opid)) != PROVOLATILE_IMMUTABLE)
919 /* else fall through to check args */
921 return expression_tree_walker(node, contain_mutable_functions_walker,
926 /*****************************************************************************
927 * Check clauses for volatile functions
928 *****************************************************************************/
931 * contain_volatile_functions
932 * Recursively search for volatile functions within a clause.
934 * Returns true if any volatile function (or operator implemented by a
935 * volatile function) is found. This test prevents invalid conversions
936 * of volatile expressions into indexscan quals.
938 * XXX we do not examine sub-selects to see if they contain uses of
939 * volatile functions. It's not real clear if that is correct or not...
942 contain_volatile_functions(Node *clause)
944 return contain_volatile_functions_walker(clause, NULL);
948 contain_volatile_functions_walker(Node *node, void *context)
952 if (IsA(node, FuncExpr))
954 FuncExpr *expr = (FuncExpr *) node;
956 if (func_volatile(expr->funcid) == PROVOLATILE_VOLATILE)
958 /* else fall through to check args */
960 else if (IsA(node, OpExpr))
962 OpExpr *expr = (OpExpr *) node;
965 if (func_volatile(expr->opfuncid) == PROVOLATILE_VOLATILE)
967 /* else fall through to check args */
969 else if (IsA(node, DistinctExpr))
971 DistinctExpr *expr = (DistinctExpr *) node;
973 set_opfuncid((OpExpr *) expr); /* rely on struct equivalence */
974 if (func_volatile(expr->opfuncid) == PROVOLATILE_VOLATILE)
976 /* else fall through to check args */
978 else if (IsA(node, NullIfExpr))
980 NullIfExpr *expr = (NullIfExpr *) node;
982 set_opfuncid((OpExpr *) expr); /* rely on struct equivalence */
983 if (func_volatile(expr->opfuncid) == PROVOLATILE_VOLATILE)
985 /* else fall through to check args */
987 else if (IsA(node, ScalarArrayOpExpr))
989 ScalarArrayOpExpr *expr = (ScalarArrayOpExpr *) node;
991 set_sa_opfuncid(expr);
992 if (func_volatile(expr->opfuncid) == PROVOLATILE_VOLATILE)
994 /* else fall through to check args */
996 else if (IsA(node, CoerceViaIO))
998 CoerceViaIO *expr = (CoerceViaIO *) node;
1003 /* check the result type's input function */
1004 getTypeInputInfo(expr->resulttype,
1005 &iofunc, &typioparam);
1006 if (func_volatile(iofunc) == PROVOLATILE_VOLATILE)
1008 /* check the input type's output function */
1009 getTypeOutputInfo(exprType((Node *) expr->arg),
1010 &iofunc, &typisvarlena);
1011 if (func_volatile(iofunc) == PROVOLATILE_VOLATILE)
1013 /* else fall through to check args */
1015 else if (IsA(node, ArrayCoerceExpr))
1017 ArrayCoerceExpr *expr = (ArrayCoerceExpr *) node;
1019 if (OidIsValid(expr->elemfuncid) &&
1020 func_volatile(expr->elemfuncid) == PROVOLATILE_VOLATILE)
1022 /* else fall through to check args */
1024 else if (IsA(node, RowCompareExpr))
1026 /* RowCompare probably can't have volatile ops, but check anyway */
1027 RowCompareExpr *rcexpr = (RowCompareExpr *) node;
1030 foreach(opid, rcexpr->opnos)
1032 if (op_volatile(lfirst_oid(opid)) == PROVOLATILE_VOLATILE)
1035 /* else fall through to check args */
1037 return expression_tree_walker(node, contain_volatile_functions_walker,
1042 /*****************************************************************************
1043 * Check clauses for nonstrict functions
1044 *****************************************************************************/
1047 * contain_nonstrict_functions
1048 * Recursively search for nonstrict functions within a clause.
1050 * Returns true if any nonstrict construct is found --- ie, anything that
1051 * could produce non-NULL output with a NULL input.
1053 * The idea here is that the caller has verified that the expression contains
1054 * one or more Var or Param nodes (as appropriate for the caller's need), and
1055 * now wishes to prove that the expression result will be NULL if any of these
1056 * inputs is NULL. If we return false, then the proof succeeded.
1059 contain_nonstrict_functions(Node *clause)
1061 return contain_nonstrict_functions_walker(clause, NULL);
1065 contain_nonstrict_functions_walker(Node *node, void *context)
1069 if (IsA(node, Aggref))
1071 /* an aggregate could return non-null with null input */
1074 if (IsA(node, WindowFunc))
1076 /* a window function could return non-null with null input */
1079 if (IsA(node, ArrayRef))
1081 /* array assignment is nonstrict, but subscripting is strict */
1082 if (((ArrayRef *) node)->refassgnexpr != NULL)
1084 /* else fall through to check args */
1086 if (IsA(node, FuncExpr))
1088 FuncExpr *expr = (FuncExpr *) node;
1090 if (!func_strict(expr->funcid))
1092 /* else fall through to check args */
1094 if (IsA(node, OpExpr))
1096 OpExpr *expr = (OpExpr *) node;
1099 if (!func_strict(expr->opfuncid))
1101 /* else fall through to check args */
1103 if (IsA(node, DistinctExpr))
1105 /* IS DISTINCT FROM is inherently non-strict */
1108 if (IsA(node, NullIfExpr))
1110 if (IsA(node, ScalarArrayOpExpr))
1112 ScalarArrayOpExpr *expr = (ScalarArrayOpExpr *) node;
1114 if (!is_strict_saop(expr, false))
1116 /* else fall through to check args */
1118 if (IsA(node, BoolExpr))
1120 BoolExpr *expr = (BoolExpr *) node;
1122 switch (expr->boolop)
1126 /* AND, OR are inherently non-strict */
1132 if (IsA(node, SubLink))
1134 /* In some cases a sublink might be strict, but in general not */
1137 if (IsA(node, SubPlan))
1139 if (IsA(node, AlternativeSubPlan))
1141 /* ArrayCoerceExpr is strict at the array level, regardless of elemfunc */
1142 if (IsA(node, FieldStore))
1144 if (IsA(node, CaseExpr))
1146 if (IsA(node, ArrayExpr))
1148 if (IsA(node, RowExpr))
1150 if (IsA(node, RowCompareExpr))
1152 if (IsA(node, CoalesceExpr))
1154 if (IsA(node, MinMaxExpr))
1156 if (IsA(node, XmlExpr))
1158 if (IsA(node, NullTest))
1160 if (IsA(node, BooleanTest))
1162 return expression_tree_walker(node, contain_nonstrict_functions_walker,
1166 /*****************************************************************************
1167 * Check clauses for non-leakproof functions
1168 *****************************************************************************/
1171 * contain_leaky_functions
1172 * Recursively search for leaky functions within a clause.
1174 * Returns true if any function call with side-effect may be present in the
1175 * clause. Qualifiers from outside the a security_barrier view should not
1176 * be pushed down into the view, lest the contents of tuples intended to be
1177 * filtered out be revealed via side effects.
1180 contain_leaky_functions(Node *clause)
1182 return contain_leaky_functions_walker(clause, NULL);
1186 contain_leaky_functions_walker(Node *node, void *context)
1191 switch (nodeTag(node))
1197 case T_NamedArgExpr:
1201 case T_CaseTestExpr:
1209 * We know these node types don't contain function calls; but
1210 * something further down in the node tree might.
1216 FuncExpr *expr = (FuncExpr *) node;
1218 if (!get_func_leakproof(expr->funcid))
1224 case T_DistinctExpr: /* struct-equivalent to OpExpr */
1225 case T_NullIfExpr: /* struct-equivalent to OpExpr */
1227 OpExpr *expr = (OpExpr *) node;
1230 if (!get_func_leakproof(expr->opfuncid))
1235 case T_ScalarArrayOpExpr:
1237 ScalarArrayOpExpr *expr = (ScalarArrayOpExpr *) node;
1239 set_sa_opfuncid(expr);
1240 if (!get_func_leakproof(expr->opfuncid))
1247 CoerceViaIO *expr = (CoerceViaIO *) node;
1252 getTypeInputInfo(exprType((Node *) expr->arg),
1254 if (!get_func_leakproof(funcid))
1257 getTypeOutputInfo(expr->resulttype, &funcid, &varlena);
1258 if (!get_func_leakproof(funcid))
1263 case T_ArrayCoerceExpr:
1265 ArrayCoerceExpr *expr = (ArrayCoerceExpr *) node;
1270 getTypeInputInfo(exprType((Node *) expr->arg),
1272 if (!get_func_leakproof(funcid))
1274 getTypeOutputInfo(expr->resulttype, &funcid, &varlena);
1275 if (!get_func_leakproof(funcid))
1280 case T_RowCompareExpr:
1282 RowCompareExpr *rcexpr = (RowCompareExpr *) node;
1285 foreach(opid, rcexpr->opnos)
1287 Oid funcid = get_opcode(lfirst_oid(opid));
1289 if (!get_func_leakproof(funcid))
1298 * If we don't recognize the node tag, assume it might be leaky.
1299 * This prevents an unexpected security hole if someone adds a new
1300 * node type that can call a function.
1304 return expression_tree_walker(node, contain_leaky_functions_walker,
1309 * find_nonnullable_rels
1310 * Determine which base rels are forced nonnullable by given clause.
1312 * Returns the set of all Relids that are referenced in the clause in such
1313 * a way that the clause cannot possibly return TRUE if any of these Relids
1314 * is an all-NULL row. (It is OK to err on the side of conservatism; hence
1315 * the analysis here is simplistic.)
1317 * The semantics here are subtly different from contain_nonstrict_functions:
1318 * that function is concerned with NULL results from arbitrary expressions,
1319 * but here we assume that the input is a Boolean expression, and wish to
1320 * see if NULL inputs will provably cause a FALSE-or-NULL result. We expect
1321 * the expression to have been AND/OR flattened and converted to implicit-AND
1324 * Note: this function is largely duplicative of find_nonnullable_vars().
1325 * The reason not to simplify this function into a thin wrapper around
1326 * find_nonnullable_vars() is that the tested conditions really are different:
1327 * a clause like "t1.v1 IS NOT NULL OR t1.v2 IS NOT NULL" does not prove
1328 * that either v1 or v2 can't be NULL, but it does prove that the t1 row
1329 * as a whole can't be all-NULL.
1331 * top_level is TRUE while scanning top-level AND/OR structure; here, showing
1332 * the result is either FALSE or NULL is good enough. top_level is FALSE when
1333 * we have descended below a NOT or a strict function: now we must be able to
1334 * prove that the subexpression goes to NULL.
1336 * We don't use expression_tree_walker here because we don't want to descend
1337 * through very many kinds of nodes; only the ones we can be sure are strict.
1340 find_nonnullable_rels(Node *clause)
1342 return find_nonnullable_rels_walker(clause, true);
1346 find_nonnullable_rels_walker(Node *node, bool top_level)
1348 Relids result = NULL;
1355 Var *var = (Var *) node;
1357 if (var->varlevelsup == 0)
1358 result = bms_make_singleton(var->varno);
1360 else if (IsA(node, List))
1363 * At top level, we are examining an implicit-AND list: if any of the
1364 * arms produces FALSE-or-NULL then the result is FALSE-or-NULL. If
1365 * not at top level, we are examining the arguments of a strict
1366 * function: if any of them produce NULL then the result of the
1367 * function must be NULL. So in both cases, the set of nonnullable
1368 * rels is the union of those found in the arms, and we pass down the
1369 * top_level flag unmodified.
1371 foreach(l, (List *) node)
1373 result = bms_join(result,
1374 find_nonnullable_rels_walker(lfirst(l),
1378 else if (IsA(node, FuncExpr))
1380 FuncExpr *expr = (FuncExpr *) node;
1382 if (func_strict(expr->funcid))
1383 result = find_nonnullable_rels_walker((Node *) expr->args, false);
1385 else if (IsA(node, OpExpr))
1387 OpExpr *expr = (OpExpr *) node;
1390 if (func_strict(expr->opfuncid))
1391 result = find_nonnullable_rels_walker((Node *) expr->args, false);
1393 else if (IsA(node, ScalarArrayOpExpr))
1395 ScalarArrayOpExpr *expr = (ScalarArrayOpExpr *) node;
1397 if (is_strict_saop(expr, true))
1398 result = find_nonnullable_rels_walker((Node *) expr->args, false);
1400 else if (IsA(node, BoolExpr))
1402 BoolExpr *expr = (BoolExpr *) node;
1404 switch (expr->boolop)
1407 /* At top level we can just recurse (to the List case) */
1410 result = find_nonnullable_rels_walker((Node *) expr->args,
1416 * Below top level, even if one arm produces NULL, the result
1417 * could be FALSE (hence not NULL). However, if *all* the
1418 * arms produce NULL then the result is NULL, so we can take
1419 * the intersection of the sets of nonnullable rels, just as
1420 * for OR. Fall through to share code.
1426 * OR is strict if all of its arms are, so we can take the
1427 * intersection of the sets of nonnullable rels for each arm.
1428 * This works for both values of top_level.
1430 foreach(l, expr->args)
1434 subresult = find_nonnullable_rels_walker(lfirst(l),
1436 if (result == NULL) /* first subresult? */
1439 result = bms_int_members(result, subresult);
1442 * If the intersection is empty, we can stop looking. This
1443 * also justifies the test for first-subresult above.
1445 if (bms_is_empty(result))
1450 /* NOT will return null if its arg is null */
1451 result = find_nonnullable_rels_walker((Node *) expr->args,
1455 elog(ERROR, "unrecognized boolop: %d", (int) expr->boolop);
1459 else if (IsA(node, RelabelType))
1461 RelabelType *expr = (RelabelType *) node;
1463 result = find_nonnullable_rels_walker((Node *) expr->arg, top_level);
1465 else if (IsA(node, CoerceViaIO))
1467 /* not clear this is useful, but it can't hurt */
1468 CoerceViaIO *expr = (CoerceViaIO *) node;
1470 result = find_nonnullable_rels_walker((Node *) expr->arg, top_level);
1472 else if (IsA(node, ArrayCoerceExpr))
1474 /* ArrayCoerceExpr is strict at the array level */
1475 ArrayCoerceExpr *expr = (ArrayCoerceExpr *) node;
1477 result = find_nonnullable_rels_walker((Node *) expr->arg, top_level);
1479 else if (IsA(node, ConvertRowtypeExpr))
1481 /* not clear this is useful, but it can't hurt */
1482 ConvertRowtypeExpr *expr = (ConvertRowtypeExpr *) node;
1484 result = find_nonnullable_rels_walker((Node *) expr->arg, top_level);
1486 else if (IsA(node, CollateExpr))
1488 CollateExpr *expr = (CollateExpr *) node;
1490 result = find_nonnullable_rels_walker((Node *) expr->arg, top_level);
1492 else if (IsA(node, NullTest))
1494 /* IS NOT NULL can be considered strict, but only at top level */
1495 NullTest *expr = (NullTest *) node;
1497 if (top_level && expr->nulltesttype == IS_NOT_NULL && !expr->argisrow)
1498 result = find_nonnullable_rels_walker((Node *) expr->arg, false);
1500 else if (IsA(node, BooleanTest))
1502 /* Boolean tests that reject NULL are strict at top level */
1503 BooleanTest *expr = (BooleanTest *) node;
1506 (expr->booltesttype == IS_TRUE ||
1507 expr->booltesttype == IS_FALSE ||
1508 expr->booltesttype == IS_NOT_UNKNOWN))
1509 result = find_nonnullable_rels_walker((Node *) expr->arg, false);
1511 else if (IsA(node, PlaceHolderVar))
1513 PlaceHolderVar *phv = (PlaceHolderVar *) node;
1515 result = find_nonnullable_rels_walker((Node *) phv->phexpr, top_level);
1521 * find_nonnullable_vars
1522 * Determine which Vars are forced nonnullable by given clause.
1524 * Returns a list of all level-zero Vars that are referenced in the clause in
1525 * such a way that the clause cannot possibly return TRUE if any of these Vars
1526 * is NULL. (It is OK to err on the side of conservatism; hence the analysis
1527 * here is simplistic.)
1529 * The semantics here are subtly different from contain_nonstrict_functions:
1530 * that function is concerned with NULL results from arbitrary expressions,
1531 * but here we assume that the input is a Boolean expression, and wish to
1532 * see if NULL inputs will provably cause a FALSE-or-NULL result. We expect
1533 * the expression to have been AND/OR flattened and converted to implicit-AND
1536 * The result is a palloc'd List, but we have not copied the member Var nodes.
1537 * Also, we don't bother trying to eliminate duplicate entries.
1539 * top_level is TRUE while scanning top-level AND/OR structure; here, showing
1540 * the result is either FALSE or NULL is good enough. top_level is FALSE when
1541 * we have descended below a NOT or a strict function: now we must be able to
1542 * prove that the subexpression goes to NULL.
1544 * We don't use expression_tree_walker here because we don't want to descend
1545 * through very many kinds of nodes; only the ones we can be sure are strict.
1548 find_nonnullable_vars(Node *clause)
1550 return find_nonnullable_vars_walker(clause, true);
1554 find_nonnullable_vars_walker(Node *node, bool top_level)
1563 Var *var = (Var *) node;
1565 if (var->varlevelsup == 0)
1566 result = list_make1(var);
1568 else if (IsA(node, List))
1571 * At top level, we are examining an implicit-AND list: if any of the
1572 * arms produces FALSE-or-NULL then the result is FALSE-or-NULL. If
1573 * not at top level, we are examining the arguments of a strict
1574 * function: if any of them produce NULL then the result of the
1575 * function must be NULL. So in both cases, the set of nonnullable
1576 * vars is the union of those found in the arms, and we pass down the
1577 * top_level flag unmodified.
1579 foreach(l, (List *) node)
1581 result = list_concat(result,
1582 find_nonnullable_vars_walker(lfirst(l),
1586 else if (IsA(node, FuncExpr))
1588 FuncExpr *expr = (FuncExpr *) node;
1590 if (func_strict(expr->funcid))
1591 result = find_nonnullable_vars_walker((Node *) expr->args, false);
1593 else if (IsA(node, OpExpr))
1595 OpExpr *expr = (OpExpr *) node;
1598 if (func_strict(expr->opfuncid))
1599 result = find_nonnullable_vars_walker((Node *) expr->args, false);
1601 else if (IsA(node, ScalarArrayOpExpr))
1603 ScalarArrayOpExpr *expr = (ScalarArrayOpExpr *) node;
1605 if (is_strict_saop(expr, true))
1606 result = find_nonnullable_vars_walker((Node *) expr->args, false);
1608 else if (IsA(node, BoolExpr))
1610 BoolExpr *expr = (BoolExpr *) node;
1612 switch (expr->boolop)
1615 /* At top level we can just recurse (to the List case) */
1618 result = find_nonnullable_vars_walker((Node *) expr->args,
1624 * Below top level, even if one arm produces NULL, the result
1625 * could be FALSE (hence not NULL). However, if *all* the
1626 * arms produce NULL then the result is NULL, so we can take
1627 * the intersection of the sets of nonnullable vars, just as
1628 * for OR. Fall through to share code.
1634 * OR is strict if all of its arms are, so we can take the
1635 * intersection of the sets of nonnullable vars for each arm.
1636 * This works for both values of top_level.
1638 foreach(l, expr->args)
1642 subresult = find_nonnullable_vars_walker(lfirst(l),
1644 if (result == NIL) /* first subresult? */
1647 result = list_intersection(result, subresult);
1650 * If the intersection is empty, we can stop looking. This
1651 * also justifies the test for first-subresult above.
1658 /* NOT will return null if its arg is null */
1659 result = find_nonnullable_vars_walker((Node *) expr->args,
1663 elog(ERROR, "unrecognized boolop: %d", (int) expr->boolop);
1667 else if (IsA(node, RelabelType))
1669 RelabelType *expr = (RelabelType *) node;
1671 result = find_nonnullable_vars_walker((Node *) expr->arg, top_level);
1673 else if (IsA(node, CoerceViaIO))
1675 /* not clear this is useful, but it can't hurt */
1676 CoerceViaIO *expr = (CoerceViaIO *) node;
1678 result = find_nonnullable_vars_walker((Node *) expr->arg, false);
1680 else if (IsA(node, ArrayCoerceExpr))
1682 /* ArrayCoerceExpr is strict at the array level */
1683 ArrayCoerceExpr *expr = (ArrayCoerceExpr *) node;
1685 result = find_nonnullable_vars_walker((Node *) expr->arg, top_level);
1687 else if (IsA(node, ConvertRowtypeExpr))
1689 /* not clear this is useful, but it can't hurt */
1690 ConvertRowtypeExpr *expr = (ConvertRowtypeExpr *) node;
1692 result = find_nonnullable_vars_walker((Node *) expr->arg, top_level);
1694 else if (IsA(node, CollateExpr))
1696 CollateExpr *expr = (CollateExpr *) node;
1698 result = find_nonnullable_vars_walker((Node *) expr->arg, top_level);
1700 else if (IsA(node, NullTest))
1702 /* IS NOT NULL can be considered strict, but only at top level */
1703 NullTest *expr = (NullTest *) node;
1705 if (top_level && expr->nulltesttype == IS_NOT_NULL && !expr->argisrow)
1706 result = find_nonnullable_vars_walker((Node *) expr->arg, false);
1708 else if (IsA(node, BooleanTest))
1710 /* Boolean tests that reject NULL are strict at top level */
1711 BooleanTest *expr = (BooleanTest *) node;
1714 (expr->booltesttype == IS_TRUE ||
1715 expr->booltesttype == IS_FALSE ||
1716 expr->booltesttype == IS_NOT_UNKNOWN))
1717 result = find_nonnullable_vars_walker((Node *) expr->arg, false);
1719 else if (IsA(node, PlaceHolderVar))
1721 PlaceHolderVar *phv = (PlaceHolderVar *) node;
1723 result = find_nonnullable_vars_walker((Node *) phv->phexpr, top_level);
1729 * find_forced_null_vars
1730 * Determine which Vars must be NULL for the given clause to return TRUE.
1732 * This is the complement of find_nonnullable_vars: find the level-zero Vars
1733 * that must be NULL for the clause to return TRUE. (It is OK to err on the
1734 * side of conservatism; hence the analysis here is simplistic. In fact,
1735 * we only detect simple "var IS NULL" tests at the top level.)
1737 * The result is a palloc'd List, but we have not copied the member Var nodes.
1738 * Also, we don't bother trying to eliminate duplicate entries.
1741 find_forced_null_vars(Node *node)
1749 /* Check single-clause cases using subroutine */
1750 var = find_forced_null_var(node);
1753 result = list_make1(var);
1755 /* Otherwise, handle AND-conditions */
1756 else if (IsA(node, List))
1759 * At top level, we are examining an implicit-AND list: if any of the
1760 * arms produces FALSE-or-NULL then the result is FALSE-or-NULL.
1762 foreach(l, (List *) node)
1764 result = list_concat(result,
1765 find_forced_null_vars(lfirst(l)));
1768 else if (IsA(node, BoolExpr))
1770 BoolExpr *expr = (BoolExpr *) node;
1773 * We don't bother considering the OR case, because it's fairly
1774 * unlikely anyone would write "v1 IS NULL OR v1 IS NULL". Likewise,
1775 * the NOT case isn't worth expending code on.
1777 if (expr->boolop == AND_EXPR)
1779 /* At top level we can just recurse (to the List case) */
1780 result = find_forced_null_vars((Node *) expr->args);
1787 * find_forced_null_var
1788 * Return the Var forced null by the given clause, or NULL if it's
1789 * not an IS NULL-type clause. For success, the clause must enforce
1790 * *only* nullness of the particular Var, not any other conditions.
1792 * This is just the single-clause case of find_forced_null_vars(), without
1793 * any allowance for AND conditions. It's used by initsplan.c on individual
1794 * qual clauses. The reason for not just applying find_forced_null_vars()
1795 * is that if an AND of an IS NULL clause with something else were to somehow
1796 * survive AND/OR flattening, initsplan.c might get fooled into discarding
1797 * the whole clause when only the IS NULL part of it had been proved redundant.
1800 find_forced_null_var(Node *node)
1804 if (IsA(node, NullTest))
1806 /* check for var IS NULL */
1807 NullTest *expr = (NullTest *) node;
1809 if (expr->nulltesttype == IS_NULL && !expr->argisrow)
1811 Var *var = (Var *) expr->arg;
1813 if (var && IsA(var, Var) &&
1814 var->varlevelsup == 0)
1818 else if (IsA(node, BooleanTest))
1820 /* var IS UNKNOWN is equivalent to var IS NULL */
1821 BooleanTest *expr = (BooleanTest *) node;
1823 if (expr->booltesttype == IS_UNKNOWN)
1825 Var *var = (Var *) expr->arg;
1827 if (var && IsA(var, Var) &&
1828 var->varlevelsup == 0)
1836 * Can we treat a ScalarArrayOpExpr as strict?
1838 * If "falseOK" is true, then a "false" result can be considered strict,
1839 * else we need to guarantee an actual NULL result for NULL input.
1841 * "foo op ALL array" is strict if the op is strict *and* we can prove
1842 * that the array input isn't an empty array. We can check that
1843 * for the cases of an array constant and an ARRAY[] construct.
1845 * "foo op ANY array" is strict in the falseOK sense if the op is strict.
1846 * If not falseOK, the test is the same as for "foo op ALL array".
1849 is_strict_saop(ScalarArrayOpExpr *expr, bool falseOK)
1853 /* The contained operator must be strict. */
1854 set_sa_opfuncid(expr);
1855 if (!func_strict(expr->opfuncid))
1857 /* If ANY and falseOK, that's all we need to check. */
1858 if (expr->useOr && falseOK)
1860 /* Else, we have to see if the array is provably non-empty. */
1861 Assert(list_length(expr->args) == 2);
1862 rightop = (Node *) lsecond(expr->args);
1863 if (rightop && IsA(rightop, Const))
1865 Datum arraydatum = ((Const *) rightop)->constvalue;
1866 bool arrayisnull = ((Const *) rightop)->constisnull;
1867 ArrayType *arrayval;
1872 arrayval = DatumGetArrayTypeP(arraydatum);
1873 nitems = ArrayGetNItems(ARR_NDIM(arrayval), ARR_DIMS(arrayval));
1877 else if (rightop && IsA(rightop, ArrayExpr))
1879 ArrayExpr *arrayexpr = (ArrayExpr *) rightop;
1881 if (arrayexpr->elements != NIL && !arrayexpr->multidims)
1888 /*****************************************************************************
1889 * Check for "pseudo-constant" clauses
1890 *****************************************************************************/
1893 * is_pseudo_constant_clause
1894 * Detect whether an expression is "pseudo constant", ie, it contains no
1895 * variables of the current query level and no uses of volatile functions.
1896 * Such an expr is not necessarily a true constant: it can still contain
1897 * Params and outer-level Vars, not to mention functions whose results
1898 * may vary from one statement to the next. However, the expr's value
1899 * will be constant over any one scan of the current query, so it can be
1900 * used as, eg, an indexscan key.
1902 * CAUTION: this function omits to test for one very important class of
1903 * not-constant expressions, namely aggregates (Aggrefs). In current usage
1904 * this is only applied to WHERE clauses and so a check for Aggrefs would be
1905 * a waste of cycles; but be sure to also check contain_agg_clause() if you
1906 * want to know about pseudo-constness in other contexts. The same goes
1907 * for window functions (WindowFuncs).
1910 is_pseudo_constant_clause(Node *clause)
1913 * We could implement this check in one recursive scan. But since the
1914 * check for volatile functions is both moderately expensive and unlikely
1915 * to fail, it seems better to look for Vars first and only check for
1916 * volatile functions if we find no Vars.
1918 if (!contain_var_clause(clause) &&
1919 !contain_volatile_functions(clause))
1925 * is_pseudo_constant_clause_relids
1926 * Same as above, except caller already has available the var membership
1927 * of the expression; this lets us avoid the contain_var_clause() scan.
1930 is_pseudo_constant_clause_relids(Node *clause, Relids relids)
1932 if (bms_is_empty(relids) &&
1933 !contain_volatile_functions(clause))
1939 /*****************************************************************************
1941 * General clause-manipulating routines *
1943 *****************************************************************************/
1947 * (formerly clause_relids)
1949 * Returns the number of different relations referenced in 'clause'.
1952 NumRelids(Node *clause)
1954 Relids varnos = pull_varnos(clause);
1955 int result = bms_num_members(varnos);
1962 * CommuteOpExpr: commute a binary operator clause
1964 * XXX the clause is destructively modified!
1967 CommuteOpExpr(OpExpr *clause)
1972 /* Sanity checks: caller is at fault if these fail */
1973 if (!is_opclause(clause) ||
1974 list_length(clause->args) != 2)
1975 elog(ERROR, "cannot commute non-binary-operator clause");
1977 opoid = get_commutator(clause->opno);
1979 if (!OidIsValid(opoid))
1980 elog(ERROR, "could not find commutator for operator %u",
1984 * modify the clause in-place!
1986 clause->opno = opoid;
1987 clause->opfuncid = InvalidOid;
1988 /* opresulttype, opretset, opcollid, inputcollid need not change */
1990 temp = linitial(clause->args);
1991 linitial(clause->args) = lsecond(clause->args);
1992 lsecond(clause->args) = temp;
1996 * CommuteRowCompareExpr: commute a RowCompareExpr clause
1998 * XXX the clause is destructively modified!
2001 CommuteRowCompareExpr(RowCompareExpr *clause)
2007 /* Sanity checks: caller is at fault if these fail */
2008 if (!IsA(clause, RowCompareExpr))
2009 elog(ERROR, "expected a RowCompareExpr");
2011 /* Build list of commuted operators */
2013 foreach(l, clause->opnos)
2015 Oid opoid = lfirst_oid(l);
2017 opoid = get_commutator(opoid);
2018 if (!OidIsValid(opoid))
2019 elog(ERROR, "could not find commutator for operator %u",
2021 newops = lappend_oid(newops, opoid);
2025 * modify the clause in-place!
2027 switch (clause->rctype)
2030 clause->rctype = ROWCOMPARE_GT;
2033 clause->rctype = ROWCOMPARE_GE;
2036 clause->rctype = ROWCOMPARE_LE;
2039 clause->rctype = ROWCOMPARE_LT;
2042 elog(ERROR, "unexpected RowCompare type: %d",
2043 (int) clause->rctype);
2047 clause->opnos = newops;
2050 * Note: we need not change the opfamilies list; we assume any btree
2051 * opfamily containing an operator will also contain its commutator.
2052 * Collations don't change either.
2055 temp = clause->largs;
2056 clause->largs = clause->rargs;
2057 clause->rargs = temp;
2061 * strip_implicit_coercions: remove implicit coercions at top level of tree
2063 * Note: there isn't any useful thing we can do with a RowExpr here, so
2064 * just return it unchanged, even if it's marked as an implicit coercion.
2067 strip_implicit_coercions(Node *node)
2071 if (IsA(node, FuncExpr))
2073 FuncExpr *f = (FuncExpr *) node;
2075 if (f->funcformat == COERCE_IMPLICIT_CAST)
2076 return strip_implicit_coercions(linitial(f->args));
2078 else if (IsA(node, RelabelType))
2080 RelabelType *r = (RelabelType *) node;
2082 if (r->relabelformat == COERCE_IMPLICIT_CAST)
2083 return strip_implicit_coercions((Node *) r->arg);
2085 else if (IsA(node, CoerceViaIO))
2087 CoerceViaIO *c = (CoerceViaIO *) node;
2089 if (c->coerceformat == COERCE_IMPLICIT_CAST)
2090 return strip_implicit_coercions((Node *) c->arg);
2092 else if (IsA(node, ArrayCoerceExpr))
2094 ArrayCoerceExpr *c = (ArrayCoerceExpr *) node;
2096 if (c->coerceformat == COERCE_IMPLICIT_CAST)
2097 return strip_implicit_coercions((Node *) c->arg);
2099 else if (IsA(node, ConvertRowtypeExpr))
2101 ConvertRowtypeExpr *c = (ConvertRowtypeExpr *) node;
2103 if (c->convertformat == COERCE_IMPLICIT_CAST)
2104 return strip_implicit_coercions((Node *) c->arg);
2106 else if (IsA(node, CoerceToDomain))
2108 CoerceToDomain *c = (CoerceToDomain *) node;
2110 if (c->coercionformat == COERCE_IMPLICIT_CAST)
2111 return strip_implicit_coercions((Node *) c->arg);
2117 * set_coercionform_dontcare: set all CoercionForm fields to COERCE_DONTCARE
2119 * This is used to make index expressions and index predicates more easily
2120 * comparable to clauses of queries. CoercionForm is not semantically
2121 * significant (for cases where it does matter, the significant info is
2122 * coded into the coercion function arguments) so we can ignore it during
2123 * comparisons. Thus, for example, an index on "foo::int4" can match an
2124 * implicit coercion to int4.
2126 * Caution: the passed expression tree is modified in-place.
2129 set_coercionform_dontcare(Node *node)
2131 (void) set_coercionform_dontcare_walker(node, NULL);
2135 set_coercionform_dontcare_walker(Node *node, void *context)
2139 if (IsA(node, FuncExpr))
2140 ((FuncExpr *) node)->funcformat = COERCE_DONTCARE;
2141 else if (IsA(node, RelabelType))
2142 ((RelabelType *) node)->relabelformat = COERCE_DONTCARE;
2143 else if (IsA(node, CoerceViaIO))
2144 ((CoerceViaIO *) node)->coerceformat = COERCE_DONTCARE;
2145 else if (IsA(node, ArrayCoerceExpr))
2146 ((ArrayCoerceExpr *) node)->coerceformat = COERCE_DONTCARE;
2147 else if (IsA(node, ConvertRowtypeExpr))
2148 ((ConvertRowtypeExpr *) node)->convertformat = COERCE_DONTCARE;
2149 else if (IsA(node, RowExpr))
2150 ((RowExpr *) node)->row_format = COERCE_DONTCARE;
2151 else if (IsA(node, CoerceToDomain))
2152 ((CoerceToDomain *) node)->coercionformat = COERCE_DONTCARE;
2153 return expression_tree_walker(node, set_coercionform_dontcare_walker,
2158 * Helper for eval_const_expressions: check that datatype of an attribute
2159 * is still what it was when the expression was parsed. This is needed to
2160 * guard against improper simplification after ALTER COLUMN TYPE. (XXX we
2161 * may well need to make similar checks elsewhere?)
2164 rowtype_field_matches(Oid rowtypeid, int fieldnum,
2165 Oid expectedtype, int32 expectedtypmod,
2166 Oid expectedcollation)
2169 Form_pg_attribute attr;
2171 /* No issue for RECORD, since there is no way to ALTER such a type */
2172 if (rowtypeid == RECORDOID)
2174 tupdesc = lookup_rowtype_tupdesc(rowtypeid, -1);
2175 if (fieldnum <= 0 || fieldnum > tupdesc->natts)
2177 ReleaseTupleDesc(tupdesc);
2180 attr = tupdesc->attrs[fieldnum - 1];
2181 if (attr->attisdropped ||
2182 attr->atttypid != expectedtype ||
2183 attr->atttypmod != expectedtypmod ||
2184 attr->attcollation != expectedcollation)
2186 ReleaseTupleDesc(tupdesc);
2189 ReleaseTupleDesc(tupdesc);
2194 /*--------------------
2195 * eval_const_expressions
2197 * Reduce any recognizably constant subexpressions of the given
2198 * expression tree, for example "2 + 2" => "4". More interestingly,
2199 * we can reduce certain boolean expressions even when they contain
2200 * non-constant subexpressions: "x OR true" => "true" no matter what
2201 * the subexpression x is. (XXX We assume that no such subexpression
2202 * will have important side-effects, which is not necessarily a good
2203 * assumption in the presence of user-defined functions; do we need a
2204 * pg_proc flag that prevents discarding the execution of a function?)
2206 * We do understand that certain functions may deliver non-constant
2207 * results even with constant inputs, "nextval()" being the classic
2208 * example. Functions that are not marked "immutable" in pg_proc
2209 * will not be pre-evaluated here, although we will reduce their
2210 * arguments as far as possible.
2212 * Whenever a function is eliminated from the expression by means of
2213 * constant-expression evaluation or inlining, we add the function to
2214 * root->glob->invalItems. This ensures the plan is known to depend on
2215 * such functions, even though they aren't referenced anymore.
2217 * We assume that the tree has already been type-checked and contains
2218 * only operators and functions that are reasonable to try to execute.
2220 * NOTE: "root" can be passed as NULL if the caller never wants to do any
2221 * Param substitutions nor receive info about inlined functions.
2223 * NOTE: the planner assumes that this will always flatten nested AND and
2224 * OR clauses into N-argument form. See comments in prepqual.c.
2226 * NOTE: another critical effect is that any function calls that require
2227 * default arguments will be expanded, and named-argument calls will be
2228 * converted to positional notation. The executor won't handle either.
2229 *--------------------
2232 eval_const_expressions(PlannerInfo *root, Node *node)
2234 eval_const_expressions_context context;
2237 context.boundParams = root->glob->boundParams; /* bound Params */
2239 context.boundParams = NULL;
2240 context.root = root; /* for inlined-function dependencies */
2241 context.active_fns = NIL; /* nothing being recursively simplified */
2242 context.case_val = NULL; /* no CASE being examined */
2243 context.estimate = false; /* safe transformations only */
2244 return eval_const_expressions_mutator(node, &context);
2247 /*--------------------
2248 * estimate_expression_value
2250 * This function attempts to estimate the value of an expression for
2251 * planning purposes. It is in essence a more aggressive version of
2252 * eval_const_expressions(): we will perform constant reductions that are
2253 * not necessarily 100% safe, but are reasonable for estimation purposes.
2255 * Currently the extra steps that are taken in this mode are:
2256 * 1. Substitute values for Params, where a bound Param value has been made
2257 * available by the caller of planner(), even if the Param isn't marked
2258 * constant. This effectively means that we plan using the first supplied
2259 * value of the Param.
2260 * 2. Fold stable, as well as immutable, functions to constants.
2261 * 3. Reduce PlaceHolderVar nodes to their contained expressions.
2262 *--------------------
2265 estimate_expression_value(PlannerInfo *root, Node *node)
2267 eval_const_expressions_context context;
2269 context.boundParams = root->glob->boundParams; /* bound Params */
2270 /* we do not need to mark the plan as depending on inlined functions */
2271 context.root = NULL;
2272 context.active_fns = NIL; /* nothing being recursively simplified */
2273 context.case_val = NULL; /* no CASE being examined */
2274 context.estimate = true; /* unsafe transformations OK */
2275 return eval_const_expressions_mutator(node, &context);
2279 eval_const_expressions_mutator(Node *node,
2280 eval_const_expressions_context *context)
2284 switch (nodeTag(node))
2288 Param *param = (Param *) node;
2290 /* Look to see if we've been given a value for this Param */
2291 if (param->paramkind == PARAM_EXTERN &&
2292 context->boundParams != NULL &&
2293 param->paramid > 0 &&
2294 param->paramid <= context->boundParams->numParams)
2296 ParamExternData *prm = &context->boundParams->params[param->paramid - 1];
2298 if (OidIsValid(prm->ptype))
2300 /* OK to substitute parameter value? */
2301 if (context->estimate ||
2302 (prm->pflags & PARAM_FLAG_CONST))
2305 * Return a Const representing the param value.
2306 * Must copy pass-by-ref datatypes, since the
2307 * Param might be in a memory context
2308 * shorter-lived than our output plan should be.
2314 Assert(prm->ptype == param->paramtype);
2315 get_typlenbyval(param->paramtype,
2316 &typLen, &typByVal);
2317 if (prm->isnull || typByVal)
2320 pval = datumCopy(prm->value, typByVal, typLen);
2321 return (Node *) makeConst(param->paramtype,
2333 * Not replaceable, so just copy the Param (no need to
2336 return (Node *) copyObject(param);
2340 FuncExpr *expr = (FuncExpr *) node;
2341 List *args = expr->args;
2346 * Code for op/func reduction is pretty bulky, so split it out
2347 * as a separate function. Note: exprTypmod normally returns
2348 * -1 for a FuncExpr, but not when the node is recognizably a
2349 * length coercion; we want to preserve the typmod in the
2350 * eventual Const if so.
2352 simple = simplify_function(expr->funcid,
2353 expr->funcresulttype,
2361 if (simple) /* successfully simplified it */
2362 return (Node *) simple;
2365 * The expression cannot be simplified any further, so build
2366 * and return a replacement FuncExpr node using the
2367 * possibly-simplified arguments. Note that we have also
2368 * converted the argument list to positional notation.
2370 newexpr = makeNode(FuncExpr);
2371 newexpr->funcid = expr->funcid;
2372 newexpr->funcresulttype = expr->funcresulttype;
2373 newexpr->funcretset = expr->funcretset;
2374 newexpr->funcformat = expr->funcformat;
2375 newexpr->funccollid = expr->funccollid;
2376 newexpr->inputcollid = expr->inputcollid;
2377 newexpr->args = args;
2378 newexpr->location = expr->location;
2379 return (Node *) newexpr;
2383 OpExpr *expr = (OpExpr *) node;
2384 List *args = expr->args;
2389 * Need to get OID of underlying function. Okay to scribble
2390 * on input to this extent.
2395 * Code for op/func reduction is pretty bulky, so split it out
2396 * as a separate function.
2398 simple = simplify_function(expr->opfuncid,
2399 expr->opresulttype, -1,
2406 if (simple) /* successfully simplified it */
2407 return (Node *) simple;
2410 * If the operator is boolean equality or inequality, we know
2411 * how to simplify cases involving one constant and one
2412 * non-constant argument.
2414 if (expr->opno == BooleanEqualOperator ||
2415 expr->opno == BooleanNotEqualOperator)
2417 simple = (Expr *) simplify_boolean_equality(expr->opno,
2419 if (simple) /* successfully simplified it */
2420 return (Node *) simple;
2424 * The expression cannot be simplified any further, so build
2425 * and return a replacement OpExpr node using the
2426 * possibly-simplified arguments.
2428 newexpr = makeNode(OpExpr);
2429 newexpr->opno = expr->opno;
2430 newexpr->opfuncid = expr->opfuncid;
2431 newexpr->opresulttype = expr->opresulttype;
2432 newexpr->opretset = expr->opretset;
2433 newexpr->opcollid = expr->opcollid;
2434 newexpr->inputcollid = expr->inputcollid;
2435 newexpr->args = args;
2436 newexpr->location = expr->location;
2437 return (Node *) newexpr;
2439 case T_DistinctExpr:
2441 DistinctExpr *expr = (DistinctExpr *) node;
2444 bool has_null_input = false;
2445 bool all_null_input = true;
2446 bool has_nonconst_input = false;
2448 DistinctExpr *newexpr;
2451 * Reduce constants in the DistinctExpr's arguments. We know
2452 * args is either NIL or a List node, so we can call
2453 * expression_tree_mutator directly rather than recursing to
2456 args = (List *) expression_tree_mutator((Node *) expr->args,
2457 eval_const_expressions_mutator,
2461 * We must do our own check for NULLs because DistinctExpr has
2462 * different results for NULL input than the underlying
2467 if (IsA(lfirst(arg), Const))
2469 has_null_input |= ((Const *) lfirst(arg))->constisnull;
2470 all_null_input &= ((Const *) lfirst(arg))->constisnull;
2473 has_nonconst_input = true;
2476 /* all constants? then can optimize this out */
2477 if (!has_nonconst_input)
2479 /* all nulls? then not distinct */
2481 return makeBoolConst(false, false);
2483 /* one null? then distinct */
2485 return makeBoolConst(true, false);
2487 /* otherwise try to evaluate the '=' operator */
2488 /* (NOT okay to try to inline it, though!) */
2491 * Need to get OID of underlying function. Okay to
2492 * scribble on input to this extent.
2494 set_opfuncid((OpExpr *) expr); /* rely on struct
2498 * Code for op/func reduction is pretty bulky, so split it
2499 * out as a separate function.
2501 simple = simplify_function(expr->opfuncid,
2502 expr->opresulttype, -1,
2509 if (simple) /* successfully simplified it */
2512 * Since the underlying operator is "=", must negate
2515 Const *csimple = (Const *) simple;
2517 Assert(IsA(csimple, Const));
2518 csimple->constvalue =
2519 BoolGetDatum(!DatumGetBool(csimple->constvalue));
2520 return (Node *) csimple;
2525 * The expression cannot be simplified any further, so build
2526 * and return a replacement DistinctExpr node using the
2527 * possibly-simplified arguments.
2529 newexpr = makeNode(DistinctExpr);
2530 newexpr->opno = expr->opno;
2531 newexpr->opfuncid = expr->opfuncid;
2532 newexpr->opresulttype = expr->opresulttype;
2533 newexpr->opretset = expr->opretset;
2534 newexpr->opcollid = expr->opcollid;
2535 newexpr->inputcollid = expr->inputcollid;
2536 newexpr->args = args;
2537 newexpr->location = expr->location;
2538 return (Node *) newexpr;
2542 BoolExpr *expr = (BoolExpr *) node;
2544 switch (expr->boolop)
2549 bool haveNull = false;
2550 bool forceTrue = false;
2552 newargs = simplify_or_arguments(expr->args,
2557 return makeBoolConst(true, false);
2559 newargs = lappend(newargs,
2560 makeBoolConst(false, true));
2561 /* If all the inputs are FALSE, result is FALSE */
2563 return makeBoolConst(false, false);
2566 * If only one nonconst-or-NULL input, it's the
2569 if (list_length(newargs) == 1)
2570 return (Node *) linitial(newargs);
2571 /* Else we still need an OR node */
2572 return (Node *) make_orclause(newargs);
2577 bool haveNull = false;
2578 bool forceFalse = false;
2580 newargs = simplify_and_arguments(expr->args,
2585 return makeBoolConst(false, false);
2587 newargs = lappend(newargs,
2588 makeBoolConst(false, true));
2589 /* If all the inputs are TRUE, result is TRUE */
2591 return makeBoolConst(true, false);
2594 * If only one nonconst-or-NULL input, it's the
2597 if (list_length(newargs) == 1)
2598 return (Node *) linitial(newargs);
2599 /* Else we still need an AND node */
2600 return (Node *) make_andclause(newargs);
2606 Assert(list_length(expr->args) == 1);
2607 arg = eval_const_expressions_mutator(linitial(expr->args),
2611 * Use negate_clause() to see if we can simplify
2614 return negate_clause(arg);
2617 elog(ERROR, "unrecognized boolop: %d",
2618 (int) expr->boolop);
2624 case T_AlternativeSubPlan:
2627 * Return a SubPlan unchanged --- too late to do anything with it.
2629 * XXX should we ereport() here instead? Probably this routine
2630 * should never be invoked after SubPlan creation.
2636 * If we can simplify the input to a constant, then we don't
2637 * need the RelabelType node anymore: just change the type
2638 * field of the Const node. Otherwise, must copy the
2641 RelabelType *relabel = (RelabelType *) node;
2644 arg = eval_const_expressions_mutator((Node *) relabel->arg,
2648 * If we find stacked RelabelTypes (eg, from foo :: int ::
2649 * oid) we can discard all but the top one.
2651 while (arg && IsA(arg, RelabelType))
2652 arg = (Node *) ((RelabelType *) arg)->arg;
2654 if (arg && IsA(arg, Const))
2656 Const *con = (Const *) arg;
2658 con->consttype = relabel->resulttype;
2659 con->consttypmod = relabel->resulttypmod;
2660 con->constcollid = relabel->resultcollid;
2661 return (Node *) con;
2665 RelabelType *newrelabel = makeNode(RelabelType);
2667 newrelabel->arg = (Expr *) arg;
2668 newrelabel->resulttype = relabel->resulttype;
2669 newrelabel->resulttypmod = relabel->resulttypmod;
2670 newrelabel->resultcollid = relabel->resultcollid;
2671 newrelabel->relabelformat = relabel->relabelformat;
2672 newrelabel->location = relabel->location;
2673 return (Node *) newrelabel;
2678 CoerceViaIO *expr = (CoerceViaIO *) node;
2681 bool outtypisvarlena;
2685 CoerceViaIO *newexpr;
2687 /* Make a List so we can use simplify_function */
2688 args = list_make1(expr->arg);
2691 * CoerceViaIO represents calling the source type's output
2692 * function then the result type's input function. So, try to
2693 * simplify it as though it were a stack of two such function
2694 * calls. First we need to know what the functions are.
2696 * Note that the coercion functions are assumed not to care
2697 * about input collation, so we just pass InvalidOid for that.
2699 getTypeOutputInfo(exprType((Node *) expr->arg),
2700 &outfunc, &outtypisvarlena);
2701 getTypeInputInfo(expr->resulttype,
2702 &infunc, &intypioparam);
2704 simple = simplify_function(outfunc,
2712 if (simple) /* successfully simplified output fn */
2715 * Input functions may want 1 to 3 arguments. We always
2716 * supply all three, trusting that nothing downstream will
2719 args = list_make3(simple,
2724 ObjectIdGetDatum(intypioparam),
2735 simple = simplify_function(infunc,
2736 expr->resulttype, -1,
2743 if (simple) /* successfully simplified input fn */
2744 return (Node *) simple;
2748 * The expression cannot be simplified any further, so build
2749 * and return a replacement CoerceViaIO node using the
2750 * possibly-simplified argument.
2752 newexpr = makeNode(CoerceViaIO);
2753 newexpr->arg = (Expr *) linitial(args);
2754 newexpr->resulttype = expr->resulttype;
2755 newexpr->resultcollid = expr->resultcollid;
2756 newexpr->coerceformat = expr->coerceformat;
2757 newexpr->location = expr->location;
2758 return (Node *) newexpr;
2760 case T_ArrayCoerceExpr:
2762 ArrayCoerceExpr *expr = (ArrayCoerceExpr *) node;
2764 ArrayCoerceExpr *newexpr;
2767 * Reduce constants in the ArrayCoerceExpr's argument, then
2768 * build a new ArrayCoerceExpr.
2770 arg = (Expr *) eval_const_expressions_mutator((Node *) expr->arg,
2773 newexpr = makeNode(ArrayCoerceExpr);
2775 newexpr->elemfuncid = expr->elemfuncid;
2776 newexpr->resulttype = expr->resulttype;
2777 newexpr->resulttypmod = expr->resulttypmod;
2778 newexpr->resultcollid = expr->resultcollid;
2779 newexpr->isExplicit = expr->isExplicit;
2780 newexpr->coerceformat = expr->coerceformat;
2781 newexpr->location = expr->location;
2784 * If constant argument and it's a binary-coercible or
2785 * immutable conversion, we can simplify it to a constant.
2787 if (arg && IsA(arg, Const) &&
2788 (!OidIsValid(newexpr->elemfuncid) ||
2789 func_volatile(newexpr->elemfuncid) == PROVOLATILE_IMMUTABLE))
2790 return (Node *) evaluate_expr((Expr *) newexpr,
2791 newexpr->resulttype,
2792 newexpr->resulttypmod,
2793 newexpr->resultcollid);
2795 /* Else we must return the partially-simplified node */
2796 return (Node *) newexpr;
2801 * If we can simplify the input to a constant, then we don't
2802 * need the CollateExpr node at all: just change the
2803 * constcollid field of the Const node. Otherwise, replace
2804 * the CollateExpr with a RelabelType. (We do that so as to
2805 * improve uniformity of expression representation and thus
2806 * simplify comparison of expressions.)
2808 CollateExpr *collate = (CollateExpr *) node;
2811 arg = eval_const_expressions_mutator((Node *) collate->arg,
2814 if (arg && IsA(arg, Const))
2816 Const *con = (Const *) arg;
2818 con->constcollid = collate->collOid;
2819 return (Node *) con;
2821 else if (collate->collOid == exprCollation(arg))
2823 /* Don't need a RelabelType either... */
2828 RelabelType *relabel = makeNode(RelabelType);
2830 relabel->resulttype = exprType(arg);
2831 relabel->resulttypmod = exprTypmod(arg);
2832 relabel->resultcollid = collate->collOid;
2833 relabel->relabelformat = COERCE_DONTCARE;
2834 relabel->location = collate->location;
2836 /* Don't create stacked RelabelTypes */
2837 while (arg && IsA(arg, RelabelType))
2838 arg = (Node *) ((RelabelType *) arg)->arg;
2839 relabel->arg = (Expr *) arg;
2841 return (Node *) relabel;
2847 * CASE expressions can be simplified if there are constant
2848 * condition clauses:
2849 * FALSE (or NULL): drop the alternative
2850 * TRUE: drop all remaining alternatives
2851 * If the first non-FALSE alternative is a constant TRUE,
2852 * we can simplify the entire CASE to that alternative's
2853 * expression. If there are no non-FALSE alternatives,
2854 * we simplify the entire CASE to the default result (ELSE).
2856 * If we have a simple-form CASE with constant test
2857 * expression, we substitute the constant value for contained
2858 * CaseTestExpr placeholder nodes, so that we have the
2859 * opportunity to reduce constant test conditions. For
2860 * example this allows
2861 * CASE 0 WHEN 0 THEN 1 ELSE 1/0 END
2862 * to reduce to 1 rather than drawing a divide-by-0 error.
2863 * Note that when the test expression is constant, we don't
2864 * have to include it in the resulting CASE; for example
2865 * CASE 0 WHEN x THEN y ELSE z END
2866 * is transformed by the parser to
2867 * CASE 0 WHEN CaseTestExpr = x THEN y ELSE z END
2868 * which we can simplify to
2869 * CASE WHEN 0 = x THEN y ELSE z END
2870 * It is not necessary for the executor to evaluate the "arg"
2871 * expression when executing the CASE, since any contained
2872 * CaseTestExprs that might have referred to it will have been
2873 * replaced by the constant.
2876 CaseExpr *caseexpr = (CaseExpr *) node;
2878 Node *save_case_val;
2881 bool const_true_cond;
2882 Node *defresult = NULL;
2885 /* Simplify the test expression, if any */
2886 newarg = eval_const_expressions_mutator((Node *) caseexpr->arg,
2889 /* Set up for contained CaseTestExpr nodes */
2890 save_case_val = context->case_val;
2891 if (newarg && IsA(newarg, Const))
2893 context->case_val = newarg;
2894 newarg = NULL; /* not needed anymore, see above */
2897 context->case_val = NULL;
2899 /* Simplify the WHEN clauses */
2901 const_true_cond = false;
2902 foreach(arg, caseexpr->args)
2904 CaseWhen *oldcasewhen = (CaseWhen *) lfirst(arg);
2908 Assert(IsA(oldcasewhen, CaseWhen));
2910 /* Simplify this alternative's test condition */
2911 casecond = eval_const_expressions_mutator((Node *) oldcasewhen->expr,
2915 * If the test condition is constant FALSE (or NULL), then
2916 * drop this WHEN clause completely, without processing
2919 if (casecond && IsA(casecond, Const))
2921 Const *const_input = (Const *) casecond;
2923 if (const_input->constisnull ||
2924 !DatumGetBool(const_input->constvalue))
2925 continue; /* drop alternative with FALSE cond */
2926 /* Else it's constant TRUE */
2927 const_true_cond = true;
2930 /* Simplify this alternative's result value */
2931 caseresult = eval_const_expressions_mutator((Node *) oldcasewhen->result,
2934 /* If non-constant test condition, emit a new WHEN node */
2935 if (!const_true_cond)
2937 CaseWhen *newcasewhen = makeNode(CaseWhen);
2939 newcasewhen->expr = (Expr *) casecond;
2940 newcasewhen->result = (Expr *) caseresult;
2941 newcasewhen->location = oldcasewhen->location;
2942 newargs = lappend(newargs, newcasewhen);
2947 * Found a TRUE condition, so none of the remaining
2948 * alternatives can be reached. We treat the result as
2949 * the default result.
2951 defresult = caseresult;
2955 /* Simplify the default result, unless we replaced it above */
2956 if (!const_true_cond)
2957 defresult = eval_const_expressions_mutator((Node *) caseexpr->defresult,
2960 context->case_val = save_case_val;
2963 * If no non-FALSE alternatives, CASE reduces to the default
2968 /* Otherwise we need a new CASE node */
2969 newcase = makeNode(CaseExpr);
2970 newcase->casetype = caseexpr->casetype;
2971 newcase->casecollid = caseexpr->casecollid;
2972 newcase->arg = (Expr *) newarg;
2973 newcase->args = newargs;
2974 newcase->defresult = (Expr *) defresult;
2975 newcase->location = caseexpr->location;
2976 return (Node *) newcase;
2978 case T_CaseTestExpr:
2981 * If we know a constant test value for the current CASE
2982 * construct, substitute it for the placeholder. Else just
2983 * return the placeholder as-is.
2985 if (context->case_val)
2986 return copyObject(context->case_val);
2988 return copyObject(node);
2992 ArrayExpr *arrayexpr = (ArrayExpr *) node;
2993 ArrayExpr *newarray;
2994 bool all_const = true;
2999 foreach(element, arrayexpr->elements)
3003 e = eval_const_expressions_mutator((Node *) lfirst(element),
3007 newelems = lappend(newelems, e);
3010 newarray = makeNode(ArrayExpr);
3011 newarray->array_typeid = arrayexpr->array_typeid;
3012 newarray->array_collid = arrayexpr->array_collid;
3013 newarray->element_typeid = arrayexpr->element_typeid;
3014 newarray->elements = newelems;
3015 newarray->multidims = arrayexpr->multidims;
3016 newarray->location = arrayexpr->location;
3019 return (Node *) evaluate_expr((Expr *) newarray,
3020 newarray->array_typeid,
3022 newarray->array_collid);
3024 return (Node *) newarray;
3026 case T_CoalesceExpr:
3028 CoalesceExpr *coalesceexpr = (CoalesceExpr *) node;
3029 CoalesceExpr *newcoalesce;
3034 foreach(arg, coalesceexpr->args)
3038 e = eval_const_expressions_mutator((Node *) lfirst(arg),
3042 * We can remove null constants from the list. For a
3043 * non-null constant, if it has not been preceded by any
3044 * other non-null-constant expressions then it is the
3045 * result. Otherwise, it's the next argument, but we can
3046 * drop following arguments since they will never be
3051 if (((Const *) e)->constisnull)
3052 continue; /* drop null constant */
3054 return e; /* first expr */
3055 newargs = lappend(newargs, e);
3058 newargs = lappend(newargs, e);
3062 * If all the arguments were constant null, the result is just
3066 return (Node *) makeNullConst(coalesceexpr->coalescetype,
3068 coalesceexpr->coalescecollid);
3070 newcoalesce = makeNode(CoalesceExpr);
3071 newcoalesce->coalescetype = coalesceexpr->coalescetype;
3072 newcoalesce->coalescecollid = coalesceexpr->coalescecollid;
3073 newcoalesce->args = newargs;
3074 newcoalesce->location = coalesceexpr->location;
3075 return (Node *) newcoalesce;
3080 * We can optimize field selection from a whole-row Var into a
3081 * simple Var. (This case won't be generated directly by the
3082 * parser, because ParseComplexProjection short-circuits it.
3083 * But it can arise while simplifying functions.) Also, we
3084 * can optimize field selection from a RowExpr construct.
3086 * We must however check that the declared type of the field
3087 * is still the same as when the FieldSelect was created ---
3088 * this can change if someone did ALTER COLUMN TYPE on the
3091 FieldSelect *fselect = (FieldSelect *) node;
3092 FieldSelect *newfselect;
3095 arg = eval_const_expressions_mutator((Node *) fselect->arg,
3097 if (arg && IsA(arg, Var) &&
3098 ((Var *) arg)->varattno == InvalidAttrNumber)
3100 if (rowtype_field_matches(((Var *) arg)->vartype,
3102 fselect->resulttype,
3103 fselect->resulttypmod,
3104 fselect->resultcollid))
3105 return (Node *) makeVar(((Var *) arg)->varno,
3107 fselect->resulttype,
3108 fselect->resulttypmod,
3109 fselect->resultcollid,
3110 ((Var *) arg)->varlevelsup);
3112 if (arg && IsA(arg, RowExpr))
3114 RowExpr *rowexpr = (RowExpr *) arg;
3116 if (fselect->fieldnum > 0 &&
3117 fselect->fieldnum <= list_length(rowexpr->args))
3119 Node *fld = (Node *) list_nth(rowexpr->args,
3120 fselect->fieldnum - 1);
3122 if (rowtype_field_matches(rowexpr->row_typeid,
3124 fselect->resulttype,
3125 fselect->resulttypmod,
3126 fselect->resultcollid) &&
3127 fselect->resulttype == exprType(fld) &&
3128 fselect->resulttypmod == exprTypmod(fld) &&
3129 fselect->resultcollid == exprCollation(fld))
3133 newfselect = makeNode(FieldSelect);
3134 newfselect->arg = (Expr *) arg;
3135 newfselect->fieldnum = fselect->fieldnum;
3136 newfselect->resulttype = fselect->resulttype;
3137 newfselect->resulttypmod = fselect->resulttypmod;
3138 newfselect->resultcollid = fselect->resultcollid;
3139 return (Node *) newfselect;
3143 NullTest *ntest = (NullTest *) node;
3147 arg = eval_const_expressions_mutator((Node *) ntest->arg,
3149 if (arg && IsA(arg, RowExpr))
3152 * We break ROW(...) IS [NOT] NULL into separate tests on
3153 * its component fields. This form is usually more
3154 * efficient to evaluate, as well as being more amenable
3157 RowExpr *rarg = (RowExpr *) arg;
3158 List *newargs = NIL;
3161 Assert(ntest->argisrow);
3163 foreach(l, rarg->args)
3165 Node *relem = (Node *) lfirst(l);
3168 * A constant field refutes the whole NullTest if it's
3169 * of the wrong nullness; else we can discard it.
3171 if (relem && IsA(relem, Const))
3173 Const *carg = (Const *) relem;
3175 if (carg->constisnull ?
3176 (ntest->nulltesttype == IS_NOT_NULL) :
3177 (ntest->nulltesttype == IS_NULL))
3178 return makeBoolConst(false, false);
3181 newntest = makeNode(NullTest);
3182 newntest->arg = (Expr *) relem;
3183 newntest->nulltesttype = ntest->nulltesttype;
3184 newntest->argisrow = type_is_rowtype(exprType(relem));
3185 newargs = lappend(newargs, newntest);
3187 /* If all the inputs were constants, result is TRUE */
3189 return makeBoolConst(true, false);
3190 /* If only one nonconst input, it's the result */
3191 if (list_length(newargs) == 1)
3192 return (Node *) linitial(newargs);
3193 /* Else we need an AND node */
3194 return (Node *) make_andclause(newargs);
3196 if (!ntest->argisrow && arg && IsA(arg, Const))
3198 Const *carg = (Const *) arg;
3201 switch (ntest->nulltesttype)
3204 result = carg->constisnull;
3207 result = !carg->constisnull;
3210 elog(ERROR, "unrecognized nulltesttype: %d",
3211 (int) ntest->nulltesttype);
3212 result = false; /* keep compiler quiet */
3216 return makeBoolConst(result, false);
3219 newntest = makeNode(NullTest);
3220 newntest->arg = (Expr *) arg;
3221 newntest->nulltesttype = ntest->nulltesttype;
3222 newntest->argisrow = ntest->argisrow;
3223 return (Node *) newntest;
3227 BooleanTest *btest = (BooleanTest *) node;
3228 BooleanTest *newbtest;
3231 arg = eval_const_expressions_mutator((Node *) btest->arg,
3233 if (arg && IsA(arg, Const))
3235 Const *carg = (Const *) arg;
3238 switch (btest->booltesttype)
3241 result = (!carg->constisnull &&
3242 DatumGetBool(carg->constvalue));
3245 result = (carg->constisnull ||
3246 !DatumGetBool(carg->constvalue));
3249 result = (!carg->constisnull &&
3250 !DatumGetBool(carg->constvalue));
3253 result = (carg->constisnull ||
3254 DatumGetBool(carg->constvalue));
3257 result = carg->constisnull;
3259 case IS_NOT_UNKNOWN:
3260 result = !carg->constisnull;
3263 elog(ERROR, "unrecognized booltesttype: %d",
3264 (int) btest->booltesttype);
3265 result = false; /* keep compiler quiet */
3269 return makeBoolConst(result, false);
3272 newbtest = makeNode(BooleanTest);
3273 newbtest->arg = (Expr *) arg;
3274 newbtest->booltesttype = btest->booltesttype;
3275 return (Node *) newbtest;
3277 case T_PlaceHolderVar:
3280 * In estimation mode, just strip the PlaceHolderVar node
3281 * altogether; this amounts to estimating that the contained value
3282 * won't be forced to null by an outer join. In regular mode we
3283 * just use the default behavior (ie, simplify the expression but
3284 * leave the PlaceHolderVar node intact).
3286 if (context->estimate)
3288 PlaceHolderVar *phv = (PlaceHolderVar *) node;
3290 return eval_const_expressions_mutator((Node *) phv->phexpr,
3299 * For any node type not handled above, we recurse using
3300 * expression_tree_mutator, which will copy the node unchanged but try to
3301 * simplify its arguments (if any) using this routine. For example: we
3302 * cannot eliminate an ArrayRef node, but we might be able to simplify
3303 * constant expressions in its subscripts.
3305 return expression_tree_mutator(node, eval_const_expressions_mutator,
3310 * Subroutine for eval_const_expressions: process arguments of an OR clause
3312 * This includes flattening of nested ORs as well as recursion to
3313 * eval_const_expressions to simplify the OR arguments.
3315 * After simplification, OR arguments are handled as follows:
3316 * non constant: keep
3317 * FALSE: drop (does not affect result)
3318 * TRUE: force result to TRUE
3319 * NULL: keep only one
3320 * We must keep one NULL input because ExecEvalOr returns NULL when no input
3321 * is TRUE and at least one is NULL. We don't actually include the NULL
3322 * here, that's supposed to be done by the caller.
3324 * The output arguments *haveNull and *forceTrue must be initialized FALSE
3325 * by the caller. They will be set TRUE if a null constant or true constant,
3326 * respectively, is detected anywhere in the argument list.
3329 simplify_or_arguments(List *args,
3330 eval_const_expressions_context *context,
3331 bool *haveNull, bool *forceTrue)
3333 List *newargs = NIL;
3334 List *unprocessed_args;
3337 * Since the parser considers OR to be a binary operator, long OR lists
3338 * become deeply nested expressions. We must flatten these into long
3339 * argument lists of a single OR operator. To avoid blowing out the stack
3340 * with recursion of eval_const_expressions, we resort to some tenseness
3341 * here: we keep a list of not-yet-processed inputs, and handle flattening
3342 * of nested ORs by prepending to the to-do list instead of recursing.
3344 unprocessed_args = list_copy(args);
3345 while (unprocessed_args)
3347 Node *arg = (Node *) linitial(unprocessed_args);
3349 unprocessed_args = list_delete_first(unprocessed_args);
3351 /* flatten nested ORs as per above comment */
3354 List *subargs = list_copy(((BoolExpr *) arg)->args);
3356 /* overly tense code to avoid leaking unused list header */
3357 if (!unprocessed_args)
3358 unprocessed_args = subargs;
3361 List *oldhdr = unprocessed_args;
3363 unprocessed_args = list_concat(subargs, unprocessed_args);
3369 /* If it's not an OR, simplify it */
3370 arg = eval_const_expressions_mutator(arg, context);
3373 * It is unlikely but not impossible for simplification of a non-OR
3374 * clause to produce an OR. Recheck, but don't be too tense about it
3375 * since it's not a mainstream case. In particular we don't worry
3376 * about const-simplifying the input twice.
3380 List *subargs = list_copy(((BoolExpr *) arg)->args);
3382 unprocessed_args = list_concat(subargs, unprocessed_args);
3387 * OK, we have a const-simplified non-OR argument. Process it per
3390 if (IsA(arg, Const))
3392 Const *const_input = (Const *) arg;
3394 if (const_input->constisnull)
3396 else if (DatumGetBool(const_input->constvalue))
3401 * Once we detect a TRUE result we can just exit the loop
3402 * immediately. However, if we ever add a notion of
3403 * non-removable functions, we'd need to keep scanning.
3407 /* otherwise, we can drop the constant-false input */
3411 /* else emit the simplified arg into the result list */
3412 newargs = lappend(newargs, arg);
3419 * Subroutine for eval_const_expressions: process arguments of an AND clause
3421 * This includes flattening of nested ANDs as well as recursion to
3422 * eval_const_expressions to simplify the AND arguments.
3424 * After simplification, AND arguments are handled as follows:
3425 * non constant: keep
3426 * TRUE: drop (does not affect result)
3427 * FALSE: force result to FALSE
3428 * NULL: keep only one
3429 * We must keep one NULL input because ExecEvalAnd returns NULL when no input
3430 * is FALSE and at least one is NULL. We don't actually include the NULL
3431 * here, that's supposed to be done by the caller.
3433 * The output arguments *haveNull and *forceFalse must be initialized FALSE
3434 * by the caller. They will be set TRUE if a null constant or false constant,
3435 * respectively, is detected anywhere in the argument list.
3438 simplify_and_arguments(List *args,
3439 eval_const_expressions_context *context,
3440 bool *haveNull, bool *forceFalse)
3442 List *newargs = NIL;
3443 List *unprocessed_args;
3445 /* See comments in simplify_or_arguments */
3446 unprocessed_args = list_copy(args);
3447 while (unprocessed_args)
3449 Node *arg = (Node *) linitial(unprocessed_args);
3451 unprocessed_args = list_delete_first(unprocessed_args);
3453 /* flatten nested ANDs as per above comment */
3454 if (and_clause(arg))
3456 List *subargs = list_copy(((BoolExpr *) arg)->args);
3458 /* overly tense code to avoid leaking unused list header */
3459 if (!unprocessed_args)
3460 unprocessed_args = subargs;
3463 List *oldhdr = unprocessed_args;
3465 unprocessed_args = list_concat(subargs, unprocessed_args);
3471 /* If it's not an AND, simplify it */
3472 arg = eval_const_expressions_mutator(arg, context);
3475 * It is unlikely but not impossible for simplification of a non-AND
3476 * clause to produce an AND. Recheck, but don't be too tense about it
3477 * since it's not a mainstream case. In particular we don't worry
3478 * about const-simplifying the input twice.
3480 if (and_clause(arg))
3482 List *subargs = list_copy(((BoolExpr *) arg)->args);
3484 unprocessed_args = list_concat(subargs, unprocessed_args);
3489 * OK, we have a const-simplified non-AND argument. Process it per
3492 if (IsA(arg, Const))
3494 Const *const_input = (Const *) arg;
3496 if (const_input->constisnull)
3498 else if (!DatumGetBool(const_input->constvalue))
3503 * Once we detect a FALSE result we can just exit the loop
3504 * immediately. However, if we ever add a notion of
3505 * non-removable functions, we'd need to keep scanning.
3509 /* otherwise, we can drop the constant-true input */
3513 /* else emit the simplified arg into the result list */
3514 newargs = lappend(newargs, arg);
3521 * Subroutine for eval_const_expressions: try to simplify boolean equality
3522 * or inequality condition
3524 * Inputs are the operator OID and the simplified arguments to the operator.
3525 * Returns a simplified expression if successful, or NULL if cannot
3526 * simplify the expression.
3528 * The idea here is to reduce "x = true" to "x" and "x = false" to "NOT x",
3529 * or similarly "x <> true" to "NOT x" and "x <> false" to "x".
3530 * This is only marginally useful in itself, but doing it in constant folding
3531 * ensures that we will recognize these forms as being equivalent in, for
3532 * example, partial index matching.
3534 * We come here only if simplify_function has failed; therefore we cannot
3535 * see two constant inputs, nor a constant-NULL input.
3538 simplify_boolean_equality(Oid opno, List *args)
3543 Assert(list_length(args) == 2);
3544 leftop = linitial(args);
3545 rightop = lsecond(args);
3546 if (leftop && IsA(leftop, Const))
3548 Assert(!((Const *) leftop)->constisnull);
3549 if (opno == BooleanEqualOperator)
3551 if (DatumGetBool(((Const *) leftop)->constvalue))
3552 return rightop; /* true = foo */
3554 return negate_clause(rightop); /* false = foo */
3558 if (DatumGetBool(((Const *) leftop)->constvalue))
3559 return negate_clause(rightop); /* true <> foo */
3561 return rightop; /* false <> foo */
3564 if (rightop && IsA(rightop, Const))
3566 Assert(!((Const *) rightop)->constisnull);
3567 if (opno == BooleanEqualOperator)
3569 if (DatumGetBool(((Const *) rightop)->constvalue))
3570 return leftop; /* foo = true */
3572 return negate_clause(leftop); /* foo = false */
3576 if (DatumGetBool(((Const *) rightop)->constvalue))
3577 return negate_clause(leftop); /* foo <> true */
3579 return leftop; /* foo <> false */
3586 * Subroutine for eval_const_expressions: try to simplify a function call
3587 * (which might originally have been an operator; we don't care)
3589 * Inputs are the function OID, actual result type OID (which is needed for
3590 * polymorphic functions), result typmod, result collation, the input
3591 * collation to use for the function, the original argument list (not
3592 * const-simplified yet, unless process_args is false), and some flags;
3593 * also the context data for eval_const_expressions.
3595 * Returns a simplified expression if successful, or NULL if cannot
3596 * simplify the function call.
3598 * This function is also responsible for converting named-notation argument
3599 * lists into positional notation and/or adding any needed default argument
3600 * expressions; which is a bit grotty, but it avoids extra fetches of the
3601 * function's pg_proc tuple. For this reason, the args list is
3602 * pass-by-reference. Conversion and const-simplification of the args list
3603 * will be done even if simplification of the function call itself is not
3607 simplify_function(Oid funcid, Oid result_type, int32 result_typmod,
3608 Oid result_collid, Oid input_collid, List **args_p,
3609 bool process_args, bool allow_non_const,
3610 eval_const_expressions_context *context)
3612 List *args = *args_p;
3613 HeapTuple func_tuple;
3614 Form_pg_proc func_form;
3618 * We have three strategies for simplification: execute the function to
3619 * deliver a constant result, use a transform function to generate a
3620 * substitute node tree, or expand in-line the body of the function
3621 * definition (which only works for simple SQL-language functions, but
3622 * that is a common case). Each case needs access to the function's
3623 * pg_proc tuple, so fetch it just once.
3625 * Note: the allow_non_const flag suppresses both the second and third
3626 * strategies; so if !allow_non_const, simplify_function can only return a
3627 * Const or NULL. Argument-list rewriting happens anyway, though.
3629 func_tuple = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcid));
3630 if (!HeapTupleIsValid(func_tuple))
3631 elog(ERROR, "cache lookup failed for function %u", funcid);
3632 func_form = (Form_pg_proc) GETSTRUCT(func_tuple);
3635 * Process the function arguments, unless the caller did it already.
3637 * Here we must deal with named or defaulted arguments, and then
3638 * recursively apply eval_const_expressions to the whole argument list.
3642 args = expand_function_arguments(args, result_type, func_tuple);
3643 args = (List *) expression_tree_mutator((Node *) args,
3644 eval_const_expressions_mutator,
3646 /* Argument processing done, give it back to the caller */
3650 /* Now attempt simplification of the function call proper. */
3652 newexpr = evaluate_function(funcid, result_type, result_typmod,
3653 result_collid, input_collid, args,
3654 func_tuple, context);
3656 if (!newexpr && allow_non_const && OidIsValid(func_form->protransform))
3659 * Build a dummy FuncExpr node containing the simplified arg list. We
3660 * use this approach to present a uniform interface to the transform
3661 * function regardless of how the function is actually being invoked.
3665 fexpr.xpr.type = T_FuncExpr;
3666 fexpr.funcid = funcid;
3667 fexpr.funcresulttype = result_type;
3668 fexpr.funcretset = func_form->proretset;
3669 fexpr.funcformat = COERCE_DONTCARE;
3670 fexpr.funccollid = result_collid;
3671 fexpr.inputcollid = input_collid;
3673 fexpr.location = -1;
3676 DatumGetPointer(OidFunctionCall1(func_form->protransform,
3677 PointerGetDatum(&fexpr)));
3680 if (!newexpr && allow_non_const)
3681 newexpr = inline_function(funcid, result_type, result_collid,
3683 func_tuple, context);
3685 ReleaseSysCache(func_tuple);
3691 * expand_function_arguments: convert named-notation args to positional args
3692 * and/or insert default args, as needed
3694 * If we need to change anything, the input argument list is copied, not
3697 * Note: this gets applied to operator argument lists too, even though the
3698 * cases it handles should never occur there. This should be OK since it
3699 * will fall through very quickly if there's nothing to do.
3702 expand_function_arguments(List *args, Oid result_type, HeapTuple func_tuple)
3704 Form_pg_proc funcform = (Form_pg_proc) GETSTRUCT(func_tuple);
3705 bool has_named_args = false;
3708 /* Do we have any named arguments? */
3711 Node *arg = (Node *) lfirst(lc);
3713 if (IsA(arg, NamedArgExpr))
3715 has_named_args = true;
3720 /* If so, we must apply reorder_function_arguments */
3723 args = reorder_function_arguments(args, func_tuple);
3724 /* Recheck argument types and add casts if needed */
3725 recheck_cast_function_args(args, result_type, func_tuple);
3727 else if (list_length(args) < funcform->pronargs)
3729 /* No named args, but we seem to be short some defaults */
3730 args = add_function_defaults(args, func_tuple);
3731 /* Recheck argument types and add casts if needed */
3732 recheck_cast_function_args(args, result_type, func_tuple);
3739 * reorder_function_arguments: convert named-notation args to positional args
3741 * This function also inserts default argument values as needed, since it's
3742 * impossible to form a truly valid positional call without that.
3745 reorder_function_arguments(List *args, HeapTuple func_tuple)
3747 Form_pg_proc funcform = (Form_pg_proc) GETSTRUCT(func_tuple);
3748 int pronargs = funcform->pronargs;
3749 int nargsprovided = list_length(args);
3750 Node *argarray[FUNC_MAX_ARGS];
3754 Assert(nargsprovided <= pronargs);
3755 if (pronargs > FUNC_MAX_ARGS)
3756 elog(ERROR, "too many function arguments");
3757 MemSet(argarray, 0, pronargs * sizeof(Node *));
3759 /* Deconstruct the argument list into an array indexed by argnumber */
3763 Node *arg = (Node *) lfirst(lc);
3765 if (!IsA(arg, NamedArgExpr))
3767 /* positional argument, assumed to precede all named args */
3768 Assert(argarray[i] == NULL);
3769 argarray[i++] = arg;
3773 NamedArgExpr *na = (NamedArgExpr *) arg;
3775 Assert(argarray[na->argnumber] == NULL);
3776 argarray[na->argnumber] = (Node *) na->arg;
3781 * Fetch default expressions, if needed, and insert into array at proper
3782 * locations (they aren't necessarily consecutive or all used)
3784 if (nargsprovided < pronargs)
3786 List *defaults = fetch_function_defaults(func_tuple);
3788 i = pronargs - funcform->pronargdefaults;
3789 foreach(lc, defaults)
3791 if (argarray[i] == NULL)
3792 argarray[i] = (Node *) lfirst(lc);
3797 /* Now reconstruct the args list in proper order */
3799 for (i = 0; i < pronargs; i++)
3801 Assert(argarray[i] != NULL);
3802 args = lappend(args, argarray[i]);
3809 * add_function_defaults: add missing function arguments from its defaults
3811 * This is used only when the argument list was positional to begin with,
3812 * and so we know we just need to add defaults at the end.
3815 add_function_defaults(List *args, HeapTuple func_tuple)
3817 Form_pg_proc funcform = (Form_pg_proc) GETSTRUCT(func_tuple);
3818 int nargsprovided = list_length(args);
3822 /* Get all the default expressions from the pg_proc tuple */
3823 defaults = fetch_function_defaults(func_tuple);
3825 /* Delete any unused defaults from the list */
3826 ndelete = nargsprovided + list_length(defaults) - funcform->pronargs;
3828 elog(ERROR, "not enough default arguments");
3829 while (ndelete-- > 0)
3830 defaults = list_delete_first(defaults);
3832 /* And form the combined argument list, not modifying the input list */
3833 return list_concat(list_copy(args), defaults);
3837 * fetch_function_defaults: get function's default arguments as expression list
3840 fetch_function_defaults(HeapTuple func_tuple)
3843 Datum proargdefaults;
3847 /* The error cases here shouldn't happen, but check anyway */
3848 proargdefaults = SysCacheGetAttr(PROCOID, func_tuple,
3849 Anum_pg_proc_proargdefaults,
3852 elog(ERROR, "not enough default arguments");
3853 str = TextDatumGetCString(proargdefaults);
3854 defaults = (List *) stringToNode(str);
3855 Assert(IsA(defaults, List));
3861 * recheck_cast_function_args: recheck function args and typecast as needed
3862 * after adding defaults.
3864 * It is possible for some of the defaulted arguments to be polymorphic;
3865 * therefore we can't assume that the default expressions have the correct
3866 * data types already. We have to re-resolve polymorphics and do coercion
3867 * just like the parser did.
3869 * This should be a no-op if there are no polymorphic arguments,
3870 * but we do it anyway to be sure.
3872 * Note: if any casts are needed, the args list is modified in-place;
3873 * caller should have already copied the list structure.
3876 recheck_cast_function_args(List *args, Oid result_type, HeapTuple func_tuple)
3878 Form_pg_proc funcform = (Form_pg_proc) GETSTRUCT(func_tuple);
3880 Oid actual_arg_types[FUNC_MAX_ARGS];
3881 Oid declared_arg_types[FUNC_MAX_ARGS];
3885 if (list_length(args) > FUNC_MAX_ARGS)
3886 elog(ERROR, "too many function arguments");
3890 actual_arg_types[nargs++] = exprType((Node *) lfirst(lc));
3892 Assert(nargs == funcform->pronargs);
3893 memcpy(declared_arg_types, funcform->proargtypes.values,
3894 funcform->pronargs * sizeof(Oid));
3895 rettype = enforce_generic_type_consistency(actual_arg_types,
3898 funcform->prorettype,
3900 /* let's just check we got the same answer as the parser did ... */
3901 if (rettype != result_type)
3902 elog(ERROR, "function's resolved result type changed during planning");
3904 /* perform any necessary typecasting of arguments */
3905 make_fn_arguments(NULL, args, actual_arg_types, declared_arg_types);
3909 * evaluate_function: try to pre-evaluate a function call
3911 * We can do this if the function is strict and has any constant-null inputs
3912 * (just return a null constant), or if the function is immutable and has all
3913 * constant inputs (call it and return the result as a Const node). In
3914 * estimation mode we are willing to pre-evaluate stable functions too.
3916 * Returns a simplified expression if successful, or NULL if cannot
3917 * simplify the function.
3920 evaluate_function(Oid funcid, Oid result_type, int32 result_typmod,
3921 Oid result_collid, Oid input_collid, List *args,
3922 HeapTuple func_tuple,
3923 eval_const_expressions_context *context)
3925 Form_pg_proc funcform = (Form_pg_proc) GETSTRUCT(func_tuple);
3926 bool has_nonconst_input = false;
3927 bool has_null_input = false;
3932 * Can't simplify if it returns a set.
3934 if (funcform->proretset)
3938 * Can't simplify if it returns RECORD. The immediate problem is that it
3939 * will be needing an expected tupdesc which we can't supply here.
3941 * In the case where it has OUT parameters, it could get by without an
3942 * expected tupdesc, but we still have issues: get_expr_result_type()
3943 * doesn't know how to extract type info from a RECORD constant, and in
3944 * the case of a NULL function result there doesn't seem to be any clean
3945 * way to fix that. In view of the likelihood of there being still other
3946 * gotchas, seems best to leave the function call unreduced.
3948 if (funcform->prorettype == RECORDOID)
3952 * Check for constant inputs and especially constant-NULL inputs.
3956 if (IsA(lfirst(arg), Const))
3957 has_null_input |= ((Const *) lfirst(arg))->constisnull;
3959 has_nonconst_input = true;
3963 * If the function is strict and has a constant-NULL input, it will never
3964 * be called at all, so we can replace the call by a NULL constant, even
3965 * if there are other inputs that aren't constant, and even if the
3966 * function is not otherwise immutable.
3968 if (funcform->proisstrict && has_null_input)
3969 return (Expr *) makeNullConst(result_type, result_typmod,
3973 * Otherwise, can simplify only if all inputs are constants. (For a
3974 * non-strict function, constant NULL inputs are treated the same as
3975 * constant non-NULL inputs.)
3977 if (has_nonconst_input)
3981 * Ordinarily we are only allowed to simplify immutable functions. But for
3982 * purposes of estimation, we consider it okay to simplify functions that
3983 * are merely stable; the risk that the result might change from planning
3984 * time to execution time is worth taking in preference to not being able
3985 * to estimate the value at all.
3987 if (funcform->provolatile == PROVOLATILE_IMMUTABLE)
3989 else if (context->estimate && funcform->provolatile == PROVOLATILE_STABLE)
3995 * OK, looks like we can simplify this operator/function.
3997 * Build a new FuncExpr node containing the already-simplified arguments.
3999 newexpr = makeNode(FuncExpr);
4000 newexpr->funcid = funcid;
4001 newexpr->funcresulttype = result_type;
4002 newexpr->funcretset = false;
4003 newexpr->funcformat = COERCE_DONTCARE; /* doesn't matter */
4004 newexpr->funccollid = result_collid; /* doesn't matter */
4005 newexpr->inputcollid = input_collid;
4006 newexpr->args = args;
4007 newexpr->location = -1;
4009 return evaluate_expr((Expr *) newexpr, result_type, result_typmod,
4014 * inline_function: try to expand a function call inline
4016 * If the function is a sufficiently simple SQL-language function
4017 * (just "SELECT expression"), then we can inline it and avoid the rather
4018 * high per-call overhead of SQL functions. Furthermore, this can expose
4019 * opportunities for constant-folding within the function expression.
4021 * We have to beware of some special cases however. A directly or
4022 * indirectly recursive function would cause us to recurse forever,
4023 * so we keep track of which functions we are already expanding and
4024 * do not re-expand them. Also, if a parameter is used more than once
4025 * in the SQL-function body, we require it not to contain any volatile
4026 * functions (volatiles might deliver inconsistent answers) nor to be
4027 * unreasonably expensive to evaluate. The expensiveness check not only
4028 * prevents us from doing multiple evaluations of an expensive parameter
4029 * at runtime, but is a safety value to limit growth of an expression due
4030 * to repeated inlining.
4032 * We must also beware of changing the volatility or strictness status of
4033 * functions by inlining them.
4035 * Also, at the moment we can't inline functions returning RECORD. This
4036 * doesn't work in the general case because it discards information such
4037 * as OUT-parameter declarations.
4039 * Returns a simplified expression if successful, or NULL if cannot
4040 * simplify the function.
4043 inline_function(Oid funcid, Oid result_type, Oid result_collid,
4044 Oid input_collid, List *args,
4045 HeapTuple func_tuple,
4046 eval_const_expressions_context *context)
4048 Form_pg_proc funcform = (Form_pg_proc) GETSTRUCT(func_tuple);
4052 bool modifyTargetList;
4053 MemoryContext oldcxt;
4054 MemoryContext mycxt;
4055 inline_error_callback_arg callback_arg;
4056 ErrorContextCallback sqlerrcontext;
4058 SQLFunctionParseInfoPtr pinfo;
4060 List *raw_parsetree_list;
4068 * Forget it if the function is not SQL-language or has other showstopper
4069 * properties. (The nargs check is just paranoia.)
4071 if (funcform->prolang != SQLlanguageId ||
4072 funcform->prosecdef ||
4073 funcform->proretset ||
4074 funcform->prorettype == RECORDOID ||
4075 !heap_attisnull(func_tuple, Anum_pg_proc_proconfig) ||
4076 funcform->pronargs != list_length(args))
4079 /* Check for recursive function, and give up trying to expand if so */
4080 if (list_member_oid(context->active_fns, funcid))
4083 /* Check permission to call function (fail later, if not) */
4084 if (pg_proc_aclcheck(funcid, GetUserId(), ACL_EXECUTE) != ACLCHECK_OK)
4087 /* Check whether a plugin wants to hook function entry/exit */
4088 if (FmgrHookIsNeeded(funcid))
4092 * Make a temporary memory context, so that we don't leak all the stuff
4093 * that parsing might create.
4095 mycxt = AllocSetContextCreate(CurrentMemoryContext,
4097 ALLOCSET_DEFAULT_MINSIZE,
4098 ALLOCSET_DEFAULT_INITSIZE,
4099 ALLOCSET_DEFAULT_MAXSIZE);
4100 oldcxt = MemoryContextSwitchTo(mycxt);
4102 /* Fetch the function body */
4103 tmp = SysCacheGetAttr(PROCOID,
4105 Anum_pg_proc_prosrc,
4108 elog(ERROR, "null prosrc for function %u", funcid);
4109 src = TextDatumGetCString(tmp);
4112 * Setup error traceback support for ereport(). This is so that we can
4113 * finger the function that bad information came from.
4115 callback_arg.proname = NameStr(funcform->proname);
4116 callback_arg.prosrc = src;
4118 sqlerrcontext.callback = sql_inline_error_callback;
4119 sqlerrcontext.arg = (void *) &callback_arg;
4120 sqlerrcontext.previous = error_context_stack;
4121 error_context_stack = &sqlerrcontext;
4124 * Set up to handle parameters while parsing the function body. We need a
4125 * dummy FuncExpr node containing the already-simplified arguments to pass
4126 * to prepare_sql_fn_parse_info. (It is really only needed if there are
4127 * some polymorphic arguments, but for simplicity we always build it.)
4129 fexpr = makeNode(FuncExpr);
4130 fexpr->funcid = funcid;
4131 fexpr->funcresulttype = result_type;
4132 fexpr->funcretset = false;
4133 fexpr->funcformat = COERCE_DONTCARE; /* doesn't matter */
4134 fexpr->funccollid = result_collid; /* doesn't matter */
4135 fexpr->inputcollid = input_collid;
4137 fexpr->location = -1;
4139 pinfo = prepare_sql_fn_parse_info(func_tuple,
4144 * We just do parsing and parse analysis, not rewriting, because rewriting
4145 * will not affect table-free-SELECT-only queries, which is all that we
4146 * care about. Also, we can punt as soon as we detect more than one
4147 * command in the function body.
4149 raw_parsetree_list = pg_parse_query(src);
4150 if (list_length(raw_parsetree_list) != 1)
4153 pstate = make_parsestate(NULL);
4154 pstate->p_sourcetext = src;
4155 sql_fn_parser_setup(pstate, pinfo);
4157 querytree = transformTopLevelStmt(pstate, linitial(raw_parsetree_list));
4159 free_parsestate(pstate);
4162 * The single command must be a simple "SELECT expression".
4164 if (!IsA(querytree, Query) ||
4165 querytree->commandType != CMD_SELECT ||
4166 querytree->utilityStmt ||
4167 querytree->hasAggs ||
4168 querytree->hasWindowFuncs ||
4169 querytree->hasSubLinks ||
4170 querytree->cteList ||
4171 querytree->rtable ||
4172 querytree->jointree->fromlist ||
4173 querytree->jointree->quals ||
4174 querytree->groupClause ||
4175 querytree->havingQual ||
4176 querytree->windowClause ||
4177 querytree->distinctClause ||
4178 querytree->sortClause ||
4179 querytree->limitOffset ||
4180 querytree->limitCount ||
4181 querytree->setOperations ||
4182 list_length(querytree->targetList) != 1)
4186 * Make sure the function (still) returns what it's declared to. This
4187 * will raise an error if wrong, but that's okay since the function would
4188 * fail at runtime anyway. Note that check_sql_fn_retval will also insert
4189 * a RelabelType if needed to make the tlist expression match the declared
4190 * type of the function.
4192 * Note: we do not try this until we have verified that no rewriting was
4193 * needed; that's probably not important, but let's be careful.
4195 if (check_sql_fn_retval(funcid, result_type, list_make1(querytree),
4196 &modifyTargetList, NULL))
4197 goto fail; /* reject whole-tuple-result cases */
4199 /* Now we can grab the tlist expression */
4200 newexpr = (Node *) ((TargetEntry *) linitial(querytree->targetList))->expr;
4202 /* Assert that check_sql_fn_retval did the right thing */
4203 Assert(exprType(newexpr) == result_type);
4204 /* It couldn't have made any dangerous tlist changes, either */
4205 Assert(!modifyTargetList);
4208 * Additional validity checks on the expression. It mustn't return a set,
4209 * and it mustn't be more volatile than the surrounding function (this is
4210 * to avoid breaking hacks that involve pretending a function is immutable
4211 * when it really ain't). If the surrounding function is declared strict,
4212 * then the expression must contain only strict constructs and must use
4213 * all of the function parameters (this is overkill, but an exact analysis
4216 if (expression_returns_set(newexpr))
4219 if (funcform->provolatile == PROVOLATILE_IMMUTABLE &&
4220 contain_mutable_functions(newexpr))
4222 else if (funcform->provolatile == PROVOLATILE_STABLE &&
4223 contain_volatile_functions(newexpr))
4226 if (funcform->proisstrict &&
4227 contain_nonstrict_functions(newexpr))
4231 * We may be able to do it; there are still checks on parameter usage to
4232 * make, but those are most easily done in combination with the actual
4233 * substitution of the inputs. So start building expression with inputs
4236 usecounts = (int *) palloc0(funcform->pronargs * sizeof(int));
4237 newexpr = substitute_actual_parameters(newexpr, funcform->pronargs,
4240 /* Now check for parameter usage */
4244 Node *param = lfirst(arg);
4246 if (usecounts[i] == 0)
4248 /* Param not used at all: uncool if func is strict */
4249 if (funcform->proisstrict)
4252 else if (usecounts[i] != 1)
4254 /* Param used multiple times: uncool if expensive or volatile */
4258 * We define "expensive" as "contains any subplan or more than 10
4259 * operators". Note that the subplan search has to be done
4260 * explicitly, since cost_qual_eval() will barf on unplanned
4263 if (contain_subplans(param))
4265 cost_qual_eval(&eval_cost, list_make1(param), NULL);
4266 if (eval_cost.startup + eval_cost.per_tuple >
4267 10 * cpu_operator_cost)
4271 * Check volatility last since this is more expensive than the
4274 if (contain_volatile_functions(param))
4281 * Whew --- we can make the substitution. Copy the modified expression
4282 * out of the temporary memory context, and clean up.
4284 MemoryContextSwitchTo(oldcxt);
4286 newexpr = copyObject(newexpr);
4288 MemoryContextDelete(mycxt);
4291 * If the result is of a collatable type, force the result to expose the
4292 * correct collation. In most cases this does not matter, but it's
4293 * possible that the function result is used directly as a sort key or in
4294 * other places where we expect exprCollation() to tell the truth.
4296 if (OidIsValid(result_collid))
4298 Oid exprcoll = exprCollation(newexpr);
4300 if (OidIsValid(exprcoll) && exprcoll != result_collid)
4302 CollateExpr *newnode = makeNode(CollateExpr);
4304 newnode->arg = (Expr *) newexpr;
4305 newnode->collOid = result_collid;
4306 newnode->location = -1;
4308 newexpr = (Node *) newnode;
4313 * Since there is now no trace of the function in the plan tree, we must
4314 * explicitly record the plan's dependency on the function.
4317 record_plan_function_dependency(context->root, funcid);
4320 * Recursively try to simplify the modified expression. Here we must add
4321 * the current function to the context list of active functions.
4323 context->active_fns = lcons_oid(funcid, context->active_fns);
4324 newexpr = eval_const_expressions_mutator(newexpr, context);
4325 context->active_fns = list_delete_first(context->active_fns);
4327 error_context_stack = sqlerrcontext.previous;
4329 return (Expr *) newexpr;
4331 /* Here if func is not inlinable: release temp memory and return NULL */
4333 MemoryContextSwitchTo(oldcxt);
4334 MemoryContextDelete(mycxt);
4335 error_context_stack = sqlerrcontext.previous;
4341 * Replace Param nodes by appropriate actual parameters
4344 substitute_actual_parameters(Node *expr, int nargs, List *args,
4347 substitute_actual_parameters_context context;
4349 context.nargs = nargs;
4350 context.args = args;
4351 context.usecounts = usecounts;
4353 return substitute_actual_parameters_mutator(expr, &context);
4357 substitute_actual_parameters_mutator(Node *node,
4358 substitute_actual_parameters_context *context)
4362 if (IsA(node, Param))
4364 Param *param = (Param *) node;
4366 if (param->paramkind != PARAM_EXTERN)
4367 elog(ERROR, "unexpected paramkind: %d", (int) param->paramkind);
4368 if (param->paramid <= 0 || param->paramid > context->nargs)
4369 elog(ERROR, "invalid paramid: %d", param->paramid);
4371 /* Count usage of parameter */
4372 context->usecounts[param->paramid - 1]++;
4374 /* Select the appropriate actual arg and replace the Param with it */
4375 /* We don't need to copy at this time (it'll get done later) */
4376 return list_nth(context->args, param->paramid - 1);
4378 return expression_tree_mutator(node, substitute_actual_parameters_mutator,
4383 * error context callback to let us supply a call-stack traceback
4386 sql_inline_error_callback(void *arg)
4388 inline_error_callback_arg *callback_arg = (inline_error_callback_arg *) arg;
4389 int syntaxerrposition;
4391 /* If it's a syntax error, convert to internal syntax error report */
4392 syntaxerrposition = geterrposition();
4393 if (syntaxerrposition > 0)
4396 internalerrposition(syntaxerrposition);
4397 internalerrquery(callback_arg->prosrc);
4400 errcontext("SQL function \"%s\" during inlining", callback_arg->proname);
4404 * evaluate_expr: pre-evaluate a constant expression
4406 * We use the executor's routine ExecEvalExpr() to avoid duplication of
4407 * code and ensure we get the same result as the executor would get.
4410 evaluate_expr(Expr *expr, Oid result_type, int32 result_typmod,
4411 Oid result_collation)
4414 ExprState *exprstate;
4415 MemoryContext oldcontext;
4419 bool resultTypByVal;
4422 * To use the executor, we need an EState.
4424 estate = CreateExecutorState();
4426 /* We can use the estate's working context to avoid memory leaks. */
4427 oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
4429 /* Make sure any opfuncids are filled in. */
4430 fix_opfuncids((Node *) expr);
4433 * Prepare expr for execution. (Note: we can't use ExecPrepareExpr
4434 * because it'd result in recursively invoking eval_const_expressions.)
4436 exprstate = ExecInitExpr(expr, NULL);
4441 * It is OK to use a default econtext because none of the ExecEvalExpr()
4442 * code used in this situation will use econtext. That might seem
4443 * fortuitous, but it's not so unreasonable --- a constant expression does
4444 * not depend on context, by definition, n'est ce pas?
4446 const_val = ExecEvalExprSwitchContext(exprstate,
4447 GetPerTupleExprContext(estate),
4448 &const_is_null, NULL);
4450 /* Get info needed about result datatype */
4451 get_typlenbyval(result_type, &resultTypLen, &resultTypByVal);
4453 /* Get back to outer memory context */
4454 MemoryContextSwitchTo(oldcontext);
4457 * Must copy result out of sub-context used by expression eval.
4459 * Also, if it's varlena, forcibly detoast it. This protects us against
4460 * storing TOAST pointers into plans that might outlive the referenced
4465 if (resultTypLen == -1)
4466 const_val = PointerGetDatum(PG_DETOAST_DATUM_COPY(const_val));
4468 const_val = datumCopy(const_val, resultTypByVal, resultTypLen);
4471 /* Release all the junk we just created */
4472 FreeExecutorState(estate);
4475 * Make the constant result node.
4477 return (Expr *) makeConst(result_type, result_typmod, result_collation,
4479 const_val, const_is_null,
4485 * inline_set_returning_function
4486 * Attempt to "inline" a set-returning function in the FROM clause.
4488 * "rte" is an RTE_FUNCTION rangetable entry. If it represents a call of a
4489 * set-returning SQL function that can safely be inlined, expand the function
4490 * and return the substitute Query structure. Otherwise, return NULL.
4492 * This has a good deal of similarity to inline_function(), but that's
4493 * for the non-set-returning case, and there are enough differences to
4494 * justify separate functions.
4497 inline_set_returning_function(PlannerInfo *root, RangeTblEntry *rte)
4501 HeapTuple func_tuple;
4502 Form_pg_proc funcform;
4506 bool modifyTargetList;
4507 MemoryContext oldcxt;
4508 MemoryContext mycxt;
4509 List *saveInvalItems;
4510 inline_error_callback_arg callback_arg;
4511 ErrorContextCallback sqlerrcontext;
4512 SQLFunctionParseInfoPtr pinfo;
4513 List *raw_parsetree_list;
4514 List *querytree_list;
4517 Assert(rte->rtekind == RTE_FUNCTION);
4520 * It doesn't make a lot of sense for a SQL SRF to refer to itself in its
4521 * own FROM clause, since that must cause infinite recursion at runtime.
4522 * It will cause this code to recurse too, so check for stack overflow.
4523 * (There's no need to do more.)
4525 check_stack_depth();
4527 /* Fail if FROM item isn't a simple FuncExpr */
4528 fexpr = (FuncExpr *) rte->funcexpr;
4529 if (fexpr == NULL || !IsA(fexpr, FuncExpr))
4531 func_oid = fexpr->funcid;
4534 * The function must be declared to return a set, else inlining would
4535 * change the results if the contained SELECT didn't return exactly one
4538 if (!fexpr->funcretset)
4542 * Refuse to inline if the arguments contain any volatile functions or
4543 * sub-selects. Volatile functions are rejected because inlining may
4544 * result in the arguments being evaluated multiple times, risking a
4545 * change in behavior. Sub-selects are rejected partly for implementation
4546 * reasons (pushing them down another level might change their behavior)
4547 * and partly because they're likely to be expensive and so multiple
4548 * evaluation would be bad.
4550 if (contain_volatile_functions((Node *) fexpr->args) ||
4551 contain_subplans((Node *) fexpr->args))
4554 /* Check permission to call function (fail later, if not) */
4555 if (pg_proc_aclcheck(func_oid, GetUserId(), ACL_EXECUTE) != ACLCHECK_OK)
4558 /* Check whether a plugin wants to hook function entry/exit */
4559 if (FmgrHookIsNeeded(func_oid))
4563 * OK, let's take a look at the function's pg_proc entry.
4565 func_tuple = SearchSysCache1(PROCOID, ObjectIdGetDatum(func_oid));
4566 if (!HeapTupleIsValid(func_tuple))
4567 elog(ERROR, "cache lookup failed for function %u", func_oid);
4568 funcform = (Form_pg_proc) GETSTRUCT(func_tuple);
4571 * Forget it if the function is not SQL-language or has other showstopper
4572 * properties. In particular it mustn't be declared STRICT, since we
4573 * couldn't enforce that. It also mustn't be VOLATILE, because that is
4574 * supposed to cause it to be executed with its own snapshot, rather than
4575 * sharing the snapshot of the calling query. (Rechecking proretset is
4578 if (funcform->prolang != SQLlanguageId ||
4579 funcform->proisstrict ||
4580 funcform->provolatile == PROVOLATILE_VOLATILE ||
4581 funcform->prosecdef ||
4582 !funcform->proretset ||
4583 !heap_attisnull(func_tuple, Anum_pg_proc_proconfig))
4585 ReleaseSysCache(func_tuple);
4590 * Make a temporary memory context, so that we don't leak all the stuff
4591 * that parsing might create.
4593 mycxt = AllocSetContextCreate(CurrentMemoryContext,
4594 "inline_set_returning_function",
4595 ALLOCSET_DEFAULT_MINSIZE,
4596 ALLOCSET_DEFAULT_INITSIZE,
4597 ALLOCSET_DEFAULT_MAXSIZE);
4598 oldcxt = MemoryContextSwitchTo(mycxt);
4601 * When we call eval_const_expressions below, it might try to add items to
4602 * root->glob->invalItems. Since it is running in the temp context, those
4603 * items will be in that context, and will need to be copied out if we're
4604 * successful. Temporarily reset the list so that we can keep those items
4605 * separate from the pre-existing list contents.
4607 saveInvalItems = root->glob->invalItems;
4608 root->glob->invalItems = NIL;
4610 /* Fetch the function body */
4611 tmp = SysCacheGetAttr(PROCOID,
4613 Anum_pg_proc_prosrc,
4616 elog(ERROR, "null prosrc for function %u", func_oid);
4617 src = TextDatumGetCString(tmp);
4620 * Setup error traceback support for ereport(). This is so that we can
4621 * finger the function that bad information came from.
4623 callback_arg.proname = NameStr(funcform->proname);
4624 callback_arg.prosrc = src;
4626 sqlerrcontext.callback = sql_inline_error_callback;
4627 sqlerrcontext.arg = (void *) &callback_arg;
4628 sqlerrcontext.previous = error_context_stack;
4629 error_context_stack = &sqlerrcontext;
4632 * Run eval_const_expressions on the function call. This is necessary to
4633 * ensure that named-argument notation is converted to positional notation
4634 * and any default arguments are inserted. It's a bit of overkill for the
4635 * arguments, since they'll get processed again later, but no harm will be
4638 fexpr = (FuncExpr *) eval_const_expressions(root, (Node *) fexpr);
4640 /* It should still be a call of the same function, but let's check */
4641 if (!IsA(fexpr, FuncExpr) ||
4642 fexpr->funcid != func_oid)
4645 /* Arg list length should now match the function */
4646 if (list_length(fexpr->args) != funcform->pronargs)
4650 * Set up to handle parameters while parsing the function body. We can
4651 * use the FuncExpr just created as the input for
4652 * prepare_sql_fn_parse_info.
4654 pinfo = prepare_sql_fn_parse_info(func_tuple,
4656 fexpr->inputcollid);
4659 * Parse, analyze, and rewrite (unlike inline_function(), we can't skip
4660 * rewriting here). We can fail as soon as we find more than one query,
4663 raw_parsetree_list = pg_parse_query(src);
4664 if (list_length(raw_parsetree_list) != 1)
4667 querytree_list = pg_analyze_and_rewrite_params(linitial(raw_parsetree_list),
4669 (ParserSetupHook) sql_fn_parser_setup,
4671 if (list_length(querytree_list) != 1)
4673 querytree = linitial(querytree_list);
4676 * The single command must be a plain SELECT.
4678 if (!IsA(querytree, Query) ||
4679 querytree->commandType != CMD_SELECT ||
4680 querytree->utilityStmt)
4684 * Make sure the function (still) returns what it's declared to. This
4685 * will raise an error if wrong, but that's okay since the function would
4686 * fail at runtime anyway. Note that check_sql_fn_retval will also insert
4687 * RelabelType(s) and/or NULL columns if needed to make the tlist
4688 * expression(s) match the declared type of the function.
4690 * If the function returns a composite type, don't inline unless the check
4691 * shows it's returning a whole tuple result; otherwise what it's
4692 * returning is a single composite column which is not what we need.
4694 if (!check_sql_fn_retval(func_oid, fexpr->funcresulttype,
4696 &modifyTargetList, NULL) &&
4697 (get_typtype(fexpr->funcresulttype) == TYPTYPE_COMPOSITE ||
4698 fexpr->funcresulttype == RECORDOID))
4699 goto fail; /* reject not-whole-tuple-result cases */
4702 * If we had to modify the tlist to make it match, and the statement is
4703 * one in which changing the tlist contents could change semantics, we
4704 * have to punt and not inline.
4706 if (modifyTargetList)
4710 * If it returns RECORD, we have to check against the column type list
4711 * provided in the RTE; check_sql_fn_retval can't do that. (If no match,
4712 * we just fail to inline, rather than complaining; see notes for
4713 * tlist_matches_coltypelist.) We don't have to do this for functions
4714 * with declared OUT parameters, even though their funcresulttype is
4715 * RECORDOID, so check get_func_result_type too.
4717 if (fexpr->funcresulttype == RECORDOID &&
4718 get_func_result_type(func_oid, NULL, NULL) == TYPEFUNC_RECORD &&
4719 !tlist_matches_coltypelist(querytree->targetList, rte->funccoltypes))
4723 * Looks good --- substitute parameters into the query.
4725 querytree = substitute_actual_srf_parameters(querytree,
4730 * Copy the modified query out of the temporary memory context, and clean
4733 MemoryContextSwitchTo(oldcxt);
4735 querytree = copyObject(querytree);
4737 /* copy up any new invalItems, too */
4738 root->glob->invalItems = list_concat(saveInvalItems,
4739 copyObject(root->glob->invalItems));
4741 MemoryContextDelete(mycxt);
4742 error_context_stack = sqlerrcontext.previous;
4743 ReleaseSysCache(func_tuple);
4746 * We don't have to fix collations here because the upper query is already
4747 * parsed, ie, the collations in the RTE are what count.
4751 * Since there is now no trace of the function in the plan tree, we must
4752 * explicitly record the plan's dependency on the function.
4754 record_plan_function_dependency(root, func_oid);
4758 /* Here if func is not inlinable: release temp memory and return NULL */
4760 MemoryContextSwitchTo(oldcxt);
4761 root->glob->invalItems = saveInvalItems;
4762 MemoryContextDelete(mycxt);
4763 error_context_stack = sqlerrcontext.previous;
4764 ReleaseSysCache(func_tuple);
4770 * Replace Param nodes by appropriate actual parameters
4772 * This is just enough different from substitute_actual_parameters()
4773 * that it needs its own code.
4776 substitute_actual_srf_parameters(Query *expr, int nargs, List *args)
4778 substitute_actual_srf_parameters_context context;
4780 context.nargs = nargs;
4781 context.args = args;
4782 context.sublevels_up = 1;
4784 return query_tree_mutator(expr,
4785 substitute_actual_srf_parameters_mutator,
4791 substitute_actual_srf_parameters_mutator(Node *node,
4792 substitute_actual_srf_parameters_context *context)
4798 if (IsA(node, Query))
4800 context->sublevels_up++;
4801 result = (Node *) query_tree_mutator((Query *) node,
4802 substitute_actual_srf_parameters_mutator,
4805 context->sublevels_up--;
4808 if (IsA(node, Param))
4810 Param *param = (Param *) node;
4812 if (param->paramkind == PARAM_EXTERN)
4814 if (param->paramid <= 0 || param->paramid > context->nargs)
4815 elog(ERROR, "invalid paramid: %d", param->paramid);
4818 * Since the parameter is being inserted into a subquery, we must
4821 result = copyObject(list_nth(context->args, param->paramid - 1));
4822 IncrementVarSublevelsUp(result, context->sublevels_up, 0);
4826 return expression_tree_mutator(node,
4827 substitute_actual_srf_parameters_mutator,
4832 * Check whether a SELECT targetlist emits the specified column types,
4833 * to see if it's safe to inline a function returning record.
4835 * We insist on exact match here. The executor allows binary-coercible
4836 * cases too, but we don't have a way to preserve the correct column types
4837 * in the correct places if we inline the function in such a case.
4839 * Note that we only check type OIDs not typmods; this agrees with what the
4840 * executor would do at runtime, and attributing a specific typmod to a
4841 * function result is largely wishful thinking anyway.
4844 tlist_matches_coltypelist(List *tlist, List *coltypelist)
4846 ListCell *tlistitem;
4847 ListCell *clistitem;
4849 clistitem = list_head(coltypelist);
4850 foreach(tlistitem, tlist)
4852 TargetEntry *tle = (TargetEntry *) lfirst(tlistitem);
4856 continue; /* ignore junk columns */
4858 if (clistitem == NULL)
4859 return false; /* too many tlist items */
4861 coltype = lfirst_oid(clistitem);
4862 clistitem = lnext(clistitem);
4864 if (exprType((Node *) tle->expr) != coltype)
4865 return false; /* column type mismatch */
4868 if (clistitem != NULL)
4869 return false; /* too few tlist items */