1 /*-------------------------------------------------------------------------
4 * routines to manipulate qualification clauses
6 * Portions Copyright (c) 1996-2018, 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 "access/htup_details.h"
23 #include "catalog/pg_aggregate.h"
24 #include "catalog/pg_class.h"
25 #include "catalog/pg_language.h"
26 #include "catalog/pg_operator.h"
27 #include "catalog/pg_proc.h"
28 #include "catalog/pg_type.h"
29 #include "executor/executor.h"
30 #include "executor/functions.h"
32 #include "miscadmin.h"
33 #include "nodes/makefuncs.h"
34 #include "nodes/nodeFuncs.h"
35 #include "optimizer/clauses.h"
36 #include "optimizer/cost.h"
37 #include "optimizer/planmain.h"
38 #include "optimizer/prep.h"
39 #include "optimizer/var.h"
40 #include "parser/analyze.h"
41 #include "parser/parse_agg.h"
42 #include "parser/parse_coerce.h"
43 #include "parser/parse_func.h"
44 #include "rewrite/rewriteManip.h"
45 #include "tcop/tcopprot.h"
46 #include "utils/acl.h"
47 #include "utils/builtins.h"
48 #include "utils/datum.h"
49 #include "utils/fmgroids.h"
50 #include "utils/lsyscache.h"
51 #include "utils/memutils.h"
52 #include "utils/syscache.h"
53 #include "utils/typcache.h"
60 AggClauseCosts *costs;
61 } get_agg_clause_costs_context;
65 ParamListInfo boundParams;
70 } eval_const_expressions_context;
77 } substitute_actual_parameters_context;
84 } substitute_actual_srf_parameters_context;
90 } inline_error_callback_arg;
94 char max_hazard; /* worst proparallel hazard found so far */
95 char max_interesting; /* worst proparallel hazard of interest */
96 List *safe_param_ids; /* PARAM_EXEC Param IDs to treat as safe */
97 } max_parallel_hazard_context;
99 static bool contain_agg_clause_walker(Node *node, void *context);
100 static bool get_agg_clause_costs_walker(Node *node,
101 get_agg_clause_costs_context *context);
102 static bool find_window_functions_walker(Node *node, WindowFuncLists *lists);
103 static bool contain_subplans_walker(Node *node, void *context);
104 static bool contain_mutable_functions_walker(Node *node, void *context);
105 static bool contain_volatile_functions_walker(Node *node, void *context);
106 static bool contain_volatile_functions_not_nextval_walker(Node *node, void *context);
107 static bool max_parallel_hazard_walker(Node *node,
108 max_parallel_hazard_context *context);
109 static bool contain_nonstrict_functions_walker(Node *node, void *context);
110 static bool contain_context_dependent_node(Node *clause);
111 static bool contain_context_dependent_node_walker(Node *node, int *flags);
112 static bool contain_leaked_vars_walker(Node *node, void *context);
113 static Relids find_nonnullable_rels_walker(Node *node, bool top_level);
114 static List *find_nonnullable_vars_walker(Node *node, bool top_level);
115 static bool is_strict_saop(ScalarArrayOpExpr *expr, bool falseOK);
116 static Node *eval_const_expressions_mutator(Node *node,
117 eval_const_expressions_context *context);
118 static bool contain_non_const_walker(Node *node, void *context);
119 static bool ece_function_is_safe(Oid funcid,
120 eval_const_expressions_context *context);
121 static List *simplify_or_arguments(List *args,
122 eval_const_expressions_context *context,
123 bool *haveNull, bool *forceTrue);
124 static List *simplify_and_arguments(List *args,
125 eval_const_expressions_context *context,
126 bool *haveNull, bool *forceFalse);
127 static Node *simplify_boolean_equality(Oid opno, List *args);
128 static Expr *simplify_function(Oid funcid,
129 Oid result_type, int32 result_typmod,
130 Oid result_collid, Oid input_collid, List **args_p,
131 bool funcvariadic, bool process_args, bool allow_non_const,
132 eval_const_expressions_context *context);
133 static List *expand_function_arguments(List *args, Oid result_type,
134 HeapTuple func_tuple);
135 static List *reorder_function_arguments(List *args, HeapTuple func_tuple);
136 static List *add_function_defaults(List *args, HeapTuple func_tuple);
137 static List *fetch_function_defaults(HeapTuple func_tuple);
138 static void recheck_cast_function_args(List *args, Oid result_type,
139 HeapTuple func_tuple);
140 static Expr *evaluate_function(Oid funcid, Oid result_type, int32 result_typmod,
141 Oid result_collid, Oid input_collid, List *args,
143 HeapTuple func_tuple,
144 eval_const_expressions_context *context);
145 static Expr *inline_function(Oid funcid, Oid result_type, Oid result_collid,
146 Oid input_collid, List *args,
148 HeapTuple func_tuple,
149 eval_const_expressions_context *context);
150 static Node *substitute_actual_parameters(Node *expr, int nargs, List *args,
152 static Node *substitute_actual_parameters_mutator(Node *node,
153 substitute_actual_parameters_context *context);
154 static void sql_inline_error_callback(void *arg);
155 static Expr *evaluate_expr(Expr *expr, Oid result_type, int32 result_typmod,
156 Oid result_collation);
157 static Query *substitute_actual_srf_parameters(Query *expr,
158 int nargs, List *args);
159 static Node *substitute_actual_srf_parameters_mutator(Node *node,
160 substitute_actual_srf_parameters_context *context);
161 static bool tlist_matches_coltypelist(List *tlist, List *coltypelist);
164 /*****************************************************************************
165 * OPERATOR clause functions
166 *****************************************************************************/
170 * Creates an operator clause given its operator info, left operand
171 * and right operand (pass NULL to create single-operand clause),
172 * and collation info.
175 make_opclause(Oid opno, Oid opresulttype, bool opretset,
176 Expr *leftop, Expr *rightop,
177 Oid opcollid, Oid inputcollid)
179 OpExpr *expr = makeNode(OpExpr);
182 expr->opfuncid = InvalidOid;
183 expr->opresulttype = opresulttype;
184 expr->opretset = opretset;
185 expr->opcollid = opcollid;
186 expr->inputcollid = inputcollid;
188 expr->args = list_make2(leftop, rightop);
190 expr->args = list_make1(leftop);
192 return (Expr *) expr;
198 * Returns the left operand of a clause of the form (op expr expr)
202 get_leftop(const Expr *clause)
204 const OpExpr *expr = (const OpExpr *) clause;
206 if (expr->args != NIL)
207 return linitial(expr->args);
215 * Returns the right operand in a clause of the form (op expr expr).
216 * NB: result will be NULL if applied to a unary op clause.
219 get_rightop(const Expr *clause)
221 const OpExpr *expr = (const OpExpr *) clause;
223 if (list_length(expr->args) >= 2)
224 return lsecond(expr->args);
229 /*****************************************************************************
230 * NOT clause functions
231 *****************************************************************************/
236 * Returns t iff this is a 'not' clause: (NOT expr).
239 not_clause(Node *clause)
241 return (clause != NULL &&
242 IsA(clause, BoolExpr) &&
243 ((BoolExpr *) clause)->boolop == NOT_EXPR);
249 * Create a 'not' clause given the expression to be negated.
252 make_notclause(Expr *notclause)
254 BoolExpr *expr = makeNode(BoolExpr);
256 expr->boolop = NOT_EXPR;
257 expr->args = list_make1(notclause);
259 return (Expr *) expr;
265 * Retrieve the clause within a 'not' clause
268 get_notclausearg(Expr *notclause)
270 return linitial(((BoolExpr *) notclause)->args);
273 /*****************************************************************************
274 * OR clause functions
275 *****************************************************************************/
280 * Returns t iff the clause is an 'or' clause: (OR { expr }).
283 or_clause(Node *clause)
285 return (clause != NULL &&
286 IsA(clause, BoolExpr) &&
287 ((BoolExpr *) clause)->boolop == OR_EXPR);
293 * Creates an 'or' clause given a list of its subclauses.
296 make_orclause(List *orclauses)
298 BoolExpr *expr = makeNode(BoolExpr);
300 expr->boolop = OR_EXPR;
301 expr->args = orclauses;
303 return (Expr *) expr;
306 /*****************************************************************************
307 * AND clause functions
308 *****************************************************************************/
314 * Returns t iff its argument is an 'and' clause: (AND { expr }).
317 and_clause(Node *clause)
319 return (clause != NULL &&
320 IsA(clause, BoolExpr) &&
321 ((BoolExpr *) clause)->boolop == AND_EXPR);
327 * Creates an 'and' clause given a list of its subclauses.
330 make_andclause(List *andclauses)
332 BoolExpr *expr = makeNode(BoolExpr);
334 expr->boolop = AND_EXPR;
335 expr->args = andclauses;
337 return (Expr *) expr;
343 * Variant of make_andclause for ANDing two qual conditions together.
344 * Qual conditions have the property that a NULL nodetree is interpreted
347 * NB: this makes no attempt to preserve AND/OR flatness; so it should not
348 * be used on a qual that has already been run through prepqual.c.
351 make_and_qual(Node *qual1, Node *qual2)
357 return (Node *) make_andclause(list_make2(qual1, qual2));
361 * The planner frequently prefers to represent qualification expressions
362 * as lists of boolean expressions with implicit AND semantics.
364 * These functions convert between an AND-semantics expression list and the
365 * ordinary representation of a boolean expression.
367 * Note that an empty list is considered equivalent to TRUE.
370 make_ands_explicit(List *andclauses)
372 if (andclauses == NIL)
373 return (Expr *) makeBoolConst(true, false);
374 else if (list_length(andclauses) == 1)
375 return (Expr *) linitial(andclauses);
377 return make_andclause(andclauses);
381 make_ands_implicit(Expr *clause)
384 * NB: because the parser sets the qual field to NULL in a query that has
385 * no WHERE clause, we must consider a NULL input clause as TRUE, even
386 * though one might more reasonably think it FALSE. Grumble. If this
387 * causes trouble, consider changing the parser's behavior.
390 return NIL; /* NULL -> NIL list == TRUE */
391 else if (and_clause((Node *) clause))
392 return ((BoolExpr *) clause)->args;
393 else if (IsA(clause, Const) &&
394 !((Const *) clause)->constisnull &&
395 DatumGetBool(((Const *) clause)->constvalue))
396 return NIL; /* constant TRUE input -> NIL list */
398 return list_make1(clause);
402 /*****************************************************************************
403 * Aggregate-function clause manipulation
404 *****************************************************************************/
408 * Recursively search for Aggref/GroupingFunc nodes within a clause.
410 * Returns true if any aggregate found.
412 * This does not descend into subqueries, and so should be used only after
413 * reduction of sublinks to subplans, or in contexts where it's known there
414 * are no subqueries. There mustn't be outer-aggregate references either.
416 * (If you want something like this but able to deal with subqueries,
417 * see rewriteManip.c's contain_aggs_of_level().)
420 contain_agg_clause(Node *clause)
422 return contain_agg_clause_walker(clause, NULL);
426 contain_agg_clause_walker(Node *node, void *context)
430 if (IsA(node, Aggref))
432 Assert(((Aggref *) node)->agglevelsup == 0);
433 return true; /* abort the tree traversal and return true */
435 if (IsA(node, GroupingFunc))
437 Assert(((GroupingFunc *) node)->agglevelsup == 0);
438 return true; /* abort the tree traversal and return true */
440 Assert(!IsA(node, SubLink));
441 return expression_tree_walker(node, contain_agg_clause_walker, context);
445 * get_agg_clause_costs
446 * Recursively find the Aggref nodes in an expression tree, and
447 * accumulate cost information about them.
449 * 'aggsplit' tells us the expected partial-aggregation mode, which affects
450 * the cost estimates.
452 * NOTE that the counts/costs are ADDED to those already in *costs ... so
453 * the caller is responsible for zeroing the struct initially.
455 * We count the nodes, estimate their execution costs, and estimate the total
456 * space needed for their transition state values if all are evaluated in
457 * parallel (as would be done in a HashAgg plan). Also, we check whether
458 * partial aggregation is feasible. See AggClauseCosts for the exact set
459 * of statistics collected.
461 * In addition, we mark Aggref nodes with the correct aggtranstype, so
462 * that that doesn't need to be done repeatedly. (That makes this function's
463 * name a bit of a misnomer.)
465 * This does not descend into subqueries, and so should be used only after
466 * reduction of sublinks to subplans, or in contexts where it's known there
467 * are no subqueries. There mustn't be outer-aggregate references either.
470 get_agg_clause_costs(PlannerInfo *root, Node *clause, AggSplit aggsplit,
471 AggClauseCosts *costs)
473 get_agg_clause_costs_context context;
476 context.aggsplit = aggsplit;
477 context.costs = costs;
478 (void) get_agg_clause_costs_walker(clause, &context);
482 get_agg_clause_costs_walker(Node *node, get_agg_clause_costs_context *context)
486 if (IsA(node, Aggref))
488 Aggref *aggref = (Aggref *) node;
489 AggClauseCosts *costs = context->costs;
491 Form_pg_aggregate aggform;
501 Assert(aggref->agglevelsup == 0);
504 * Fetch info about aggregate from pg_aggregate. Note it's correct to
505 * ignore the moving-aggregate variant, since what we're concerned
506 * with here is aggregates not window functions.
508 aggTuple = SearchSysCache1(AGGFNOID,
509 ObjectIdGetDatum(aggref->aggfnoid));
510 if (!HeapTupleIsValid(aggTuple))
511 elog(ERROR, "cache lookup failed for aggregate %u",
513 aggform = (Form_pg_aggregate) GETSTRUCT(aggTuple);
514 aggtransfn = aggform->aggtransfn;
515 aggfinalfn = aggform->aggfinalfn;
516 aggcombinefn = aggform->aggcombinefn;
517 aggserialfn = aggform->aggserialfn;
518 aggdeserialfn = aggform->aggdeserialfn;
519 aggtranstype = aggform->aggtranstype;
520 aggtransspace = aggform->aggtransspace;
521 ReleaseSysCache(aggTuple);
524 * Resolve the possibly-polymorphic aggregate transition type, unless
525 * already done in a previous pass over the expression.
527 if (OidIsValid(aggref->aggtranstype))
528 aggtranstype = aggref->aggtranstype;
531 Oid inputTypes[FUNC_MAX_ARGS];
534 /* extract argument types (ignoring any ORDER BY expressions) */
535 numArguments = get_aggregate_argtypes(aggref, inputTypes);
537 /* resolve actual type of transition state, if polymorphic */
538 aggtranstype = resolve_aggregate_transtype(aggref->aggfnoid,
542 aggref->aggtranstype = aggtranstype;
546 * Count it, and check for cases requiring ordered input. Note that
547 * ordered-set aggs always have nonempty aggorder. Any ordered-input
548 * case also defeats partial aggregation.
551 if (aggref->aggorder != NIL || aggref->aggdistinct != NIL)
553 costs->numOrderedAggs++;
554 costs->hasNonPartial = true;
558 * Check whether partial aggregation is feasible, unless we already
559 * found out that we can't do it.
561 if (!costs->hasNonPartial)
564 * If there is no combine function, then partial aggregation is
567 if (!OidIsValid(aggcombinefn))
568 costs->hasNonPartial = true;
571 * If we have any aggs with transtype INTERNAL then we must check
572 * whether they have serialization/deserialization functions; if
573 * not, we can't serialize partial-aggregation results.
575 else if (aggtranstype == INTERNALOID &&
576 (!OidIsValid(aggserialfn) || !OidIsValid(aggdeserialfn)))
577 costs->hasNonSerial = true;
581 * Add the appropriate component function execution costs to
582 * appropriate totals.
584 if (DO_AGGSPLIT_COMBINE(context->aggsplit))
586 /* charge for combining previously aggregated states */
587 costs->transCost.per_tuple += get_func_cost(aggcombinefn) * cpu_operator_cost;
590 costs->transCost.per_tuple += get_func_cost(aggtransfn) * cpu_operator_cost;
591 if (DO_AGGSPLIT_DESERIALIZE(context->aggsplit) &&
592 OidIsValid(aggdeserialfn))
593 costs->transCost.per_tuple += get_func_cost(aggdeserialfn) * cpu_operator_cost;
594 if (DO_AGGSPLIT_SERIALIZE(context->aggsplit) &&
595 OidIsValid(aggserialfn))
596 costs->finalCost += get_func_cost(aggserialfn) * cpu_operator_cost;
597 if (!DO_AGGSPLIT_SKIPFINAL(context->aggsplit) &&
598 OidIsValid(aggfinalfn))
599 costs->finalCost += get_func_cost(aggfinalfn) * cpu_operator_cost;
602 * These costs are incurred only by the initial aggregate node, so we
603 * mustn't include them again at upper levels.
605 if (!DO_AGGSPLIT_COMBINE(context->aggsplit))
607 /* add the input expressions' cost to per-input-row costs */
608 cost_qual_eval_node(&argcosts, (Node *) aggref->args, context->root);
609 costs->transCost.startup += argcosts.startup;
610 costs->transCost.per_tuple += argcosts.per_tuple;
613 * Add any filter's cost to per-input-row costs.
615 * XXX Ideally we should reduce input expression costs according
616 * to filter selectivity, but it's not clear it's worth the
619 if (aggref->aggfilter)
621 cost_qual_eval_node(&argcosts, (Node *) aggref->aggfilter,
623 costs->transCost.startup += argcosts.startup;
624 costs->transCost.per_tuple += argcosts.per_tuple;
629 * If there are direct arguments, treat their evaluation cost like the
630 * cost of the finalfn.
632 if (aggref->aggdirectargs)
634 cost_qual_eval_node(&argcosts, (Node *) aggref->aggdirectargs,
636 costs->transCost.startup += argcosts.startup;
637 costs->finalCost += argcosts.per_tuple;
641 * If the transition type is pass-by-value then it doesn't add
642 * anything to the required size of the hashtable. If it is
643 * pass-by-reference then we have to add the estimated size of the
644 * value itself, plus palloc overhead.
646 if (!get_typbyval(aggtranstype))
650 /* Use average width if aggregate definition gave one */
651 if (aggtransspace > 0)
652 avgwidth = aggtransspace;
653 else if (aggtransfn == F_ARRAY_APPEND)
656 * If the transition function is array_append(), it'll use an
657 * expanded array as transvalue, which will occupy at least
658 * ALLOCSET_SMALL_INITSIZE and possibly more. Use that as the
659 * estimate for lack of a better idea.
661 avgwidth = ALLOCSET_SMALL_INITSIZE;
666 * If transition state is of same type as first aggregated
667 * input, assume it's the same typmod (same width) as well.
668 * This works for cases like MAX/MIN and is probably somewhat
669 * reasonable otherwise.
671 int32 aggtranstypmod = -1;
675 TargetEntry *tle = (TargetEntry *) linitial(aggref->args);
677 if (aggtranstype == exprType((Node *) tle->expr))
678 aggtranstypmod = exprTypmod((Node *) tle->expr);
681 avgwidth = get_typavgwidth(aggtranstype, aggtranstypmod);
684 avgwidth = MAXALIGN(avgwidth);
685 costs->transitionSpace += avgwidth + 2 * sizeof(void *);
687 else if (aggtranstype == INTERNALOID)
690 * INTERNAL transition type is a special case: although INTERNAL
691 * is pass-by-value, it's almost certainly being used as a pointer
692 * to some large data structure. The aggregate definition can
693 * provide an estimate of the size. If it doesn't, then we assume
694 * ALLOCSET_DEFAULT_INITSIZE, which is a good guess if the data is
695 * being kept in a private memory context, as is done by
696 * array_agg() for instance.
698 if (aggtransspace > 0)
699 costs->transitionSpace += aggtransspace;
701 costs->transitionSpace += ALLOCSET_DEFAULT_INITSIZE;
705 * We assume that the parser checked that there are no aggregates (of
706 * this level anyway) in the aggregated arguments, direct arguments,
707 * or filter clause. Hence, we need not recurse into any of them.
711 Assert(!IsA(node, SubLink));
712 return expression_tree_walker(node, get_agg_clause_costs_walker,
717 /*****************************************************************************
718 * Window-function clause manipulation
719 *****************************************************************************/
722 * contain_window_function
723 * Recursively search for WindowFunc nodes within a clause.
725 * Since window functions don't have level fields, but are hard-wired to
726 * be associated with the current query level, this is just the same as
727 * rewriteManip.c's function.
730 contain_window_function(Node *clause)
732 return contain_windowfuncs(clause);
736 * find_window_functions
737 * Locate all the WindowFunc nodes in an expression tree, and organize
738 * them by winref ID number.
740 * Caller must provide an upper bound on the winref IDs expected in the tree.
743 find_window_functions(Node *clause, Index maxWinRef)
745 WindowFuncLists *lists = palloc(sizeof(WindowFuncLists));
747 lists->numWindowFuncs = 0;
748 lists->maxWinRef = maxWinRef;
749 lists->windowFuncs = (List **) palloc0((maxWinRef + 1) * sizeof(List *));
750 (void) find_window_functions_walker(clause, lists);
755 find_window_functions_walker(Node *node, WindowFuncLists *lists)
759 if (IsA(node, WindowFunc))
761 WindowFunc *wfunc = (WindowFunc *) node;
763 /* winref is unsigned, so one-sided test is OK */
764 if (wfunc->winref > lists->maxWinRef)
765 elog(ERROR, "WindowFunc contains out-of-range winref %u",
767 /* eliminate duplicates, so that we avoid repeated computation */
768 if (!list_member(lists->windowFuncs[wfunc->winref], wfunc))
770 lists->windowFuncs[wfunc->winref] =
771 lappend(lists->windowFuncs[wfunc->winref], wfunc);
772 lists->numWindowFuncs++;
776 * We assume that the parser checked that there are no window
777 * functions in the arguments or filter clause. Hence, we need not
778 * recurse into them. (If either the parser or the planner screws up
779 * on this point, the executor will still catch it; see ExecInitExpr.)
783 Assert(!IsA(node, SubLink));
784 return expression_tree_walker(node, find_window_functions_walker,
789 /*****************************************************************************
790 * Support for expressions returning sets
791 *****************************************************************************/
794 * expression_returns_set_rows
795 * Estimate the number of rows returned by a set-returning expression.
796 * The result is 1 if it's not a set-returning expression.
798 * We should only examine the top-level function or operator; it used to be
799 * appropriate to recurse, but not anymore. (Even if there are more SRFs in
800 * the function's inputs, their multipliers are accounted for separately.)
802 * Note: keep this in sync with expression_returns_set() in nodes/nodeFuncs.c.
805 expression_returns_set_rows(Node *clause)
809 if (IsA(clause, FuncExpr))
811 FuncExpr *expr = (FuncExpr *) clause;
813 if (expr->funcretset)
814 return clamp_row_est(get_func_rows(expr->funcid));
816 if (IsA(clause, OpExpr))
818 OpExpr *expr = (OpExpr *) clause;
823 return clamp_row_est(get_func_rows(expr->opfuncid));
830 /*****************************************************************************
831 * Subplan clause manipulation
832 *****************************************************************************/
836 * Recursively search for subplan nodes within a clause.
838 * If we see a SubLink node, we will return true. This is only possible if
839 * the expression tree hasn't yet been transformed by subselect.c. We do not
840 * know whether the node will produce a true subplan or just an initplan,
841 * but we make the conservative assumption that it will be a subplan.
843 * Returns true if any subplan found.
846 contain_subplans(Node *clause)
848 return contain_subplans_walker(clause, NULL);
852 contain_subplans_walker(Node *node, void *context)
856 if (IsA(node, SubPlan) ||
857 IsA(node, AlternativeSubPlan) ||
859 return true; /* abort the tree traversal and return true */
860 return expression_tree_walker(node, contain_subplans_walker, context);
864 /*****************************************************************************
865 * Check clauses for mutable functions
866 *****************************************************************************/
869 * contain_mutable_functions
870 * Recursively search for mutable functions within a clause.
872 * Returns true if any mutable function (or operator implemented by a
873 * mutable function) is found. This test is needed so that we don't
874 * mistakenly think that something like "WHERE random() < 0.5" can be treated
875 * as a constant qualification.
877 * We will recursively look into Query nodes (i.e., SubLink sub-selects)
878 * but not into SubPlans. See comments for contain_volatile_functions().
881 contain_mutable_functions(Node *clause)
883 return contain_mutable_functions_walker(clause, NULL);
887 contain_mutable_functions_checker(Oid func_id, void *context)
889 return (func_volatile(func_id) != PROVOLATILE_IMMUTABLE);
893 contain_mutable_functions_walker(Node *node, void *context)
897 /* Check for mutable functions in node itself */
898 if (check_functions_in_node(node, contain_mutable_functions_checker,
902 if (IsA(node, SQLValueFunction))
904 /* all variants of SQLValueFunction are stable */
908 if (IsA(node, NextValueExpr))
910 /* NextValueExpr is volatile */
915 * It should be safe to treat MinMaxExpr as immutable, because it will
916 * depend on a non-cross-type btree comparison function, and those should
917 * always be immutable. Treating XmlExpr as immutable is more dubious,
918 * and treating CoerceToDomain as immutable is outright dangerous. But we
919 * have done so historically, and changing this would probably cause more
920 * problems than it would fix. In practice, if you have a non-immutable
921 * domain constraint you are in for pain anyhow.
924 /* Recurse to check arguments */
925 if (IsA(node, Query))
927 /* Recurse into subselects */
928 return query_tree_walker((Query *) node,
929 contain_mutable_functions_walker,
932 return expression_tree_walker(node, contain_mutable_functions_walker,
937 /*****************************************************************************
938 * Check clauses for volatile functions
939 *****************************************************************************/
942 * contain_volatile_functions
943 * Recursively search for volatile functions within a clause.
945 * Returns true if any volatile function (or operator implemented by a
946 * volatile function) is found. This test prevents, for example,
947 * invalid conversions of volatile expressions into indexscan quals.
949 * We will recursively look into Query nodes (i.e., SubLink sub-selects)
950 * but not into SubPlans. This is a bit odd, but intentional. If we are
951 * looking at a SubLink, we are probably deciding whether a query tree
952 * transformation is safe, and a contained sub-select should affect that;
953 * for example, duplicating a sub-select containing a volatile function
954 * would be bad. However, once we've got to the stage of having SubPlans,
955 * subsequent planning need not consider volatility within those, since
956 * the executor won't change its evaluation rules for a SubPlan based on
960 contain_volatile_functions(Node *clause)
962 return contain_volatile_functions_walker(clause, NULL);
966 contain_volatile_functions_checker(Oid func_id, void *context)
968 return (func_volatile(func_id) == PROVOLATILE_VOLATILE);
972 contain_volatile_functions_walker(Node *node, void *context)
976 /* Check for volatile functions in node itself */
977 if (check_functions_in_node(node, contain_volatile_functions_checker,
981 if (IsA(node, NextValueExpr))
983 /* NextValueExpr is volatile */
988 * See notes in contain_mutable_functions_walker about why we treat
989 * MinMaxExpr, XmlExpr, and CoerceToDomain as immutable, while
990 * SQLValueFunction is stable. Hence, none of them are of interest here.
993 /* Recurse to check arguments */
994 if (IsA(node, Query))
996 /* Recurse into subselects */
997 return query_tree_walker((Query *) node,
998 contain_volatile_functions_walker,
1001 return expression_tree_walker(node, contain_volatile_functions_walker,
1006 * Special purpose version of contain_volatile_functions() for use in COPY:
1007 * ignore nextval(), but treat all other functions normally.
1010 contain_volatile_functions_not_nextval(Node *clause)
1012 return contain_volatile_functions_not_nextval_walker(clause, NULL);
1016 contain_volatile_functions_not_nextval_checker(Oid func_id, void *context)
1018 return (func_id != F_NEXTVAL_OID &&
1019 func_volatile(func_id) == PROVOLATILE_VOLATILE);
1023 contain_volatile_functions_not_nextval_walker(Node *node, void *context)
1027 /* Check for volatile functions in node itself */
1028 if (check_functions_in_node(node,
1029 contain_volatile_functions_not_nextval_checker,
1034 * See notes in contain_mutable_functions_walker about why we treat
1035 * MinMaxExpr, XmlExpr, and CoerceToDomain as immutable, while
1036 * SQLValueFunction is stable. Hence, none of them are of interest here.
1037 * Also, since we're intentionally ignoring nextval(), presumably we
1038 * should ignore NextValueExpr.
1041 /* Recurse to check arguments */
1042 if (IsA(node, Query))
1044 /* Recurse into subselects */
1045 return query_tree_walker((Query *) node,
1046 contain_volatile_functions_not_nextval_walker,
1049 return expression_tree_walker(node,
1050 contain_volatile_functions_not_nextval_walker,
1055 /*****************************************************************************
1056 * Check queries for parallel unsafe and/or restricted constructs
1057 *****************************************************************************/
1060 * max_parallel_hazard
1061 * Find the worst parallel-hazard level in the given query
1063 * Returns the worst function hazard property (the earliest in this list:
1064 * PROPARALLEL_UNSAFE, PROPARALLEL_RESTRICTED, PROPARALLEL_SAFE) that can
1065 * be found in the given parsetree. We use this to find out whether the query
1066 * can be parallelized at all. The caller will also save the result in
1067 * PlannerGlobal so as to short-circuit checks of portions of the querytree
1068 * later, in the common case where everything is SAFE.
1071 max_parallel_hazard(Query *parse)
1073 max_parallel_hazard_context context;
1075 context.max_hazard = PROPARALLEL_SAFE;
1076 context.max_interesting = PROPARALLEL_UNSAFE;
1077 context.safe_param_ids = NIL;
1078 (void) max_parallel_hazard_walker((Node *) parse, &context);
1079 return context.max_hazard;
1084 * Detect whether the given expr contains only parallel-safe functions
1086 * root->glob->maxParallelHazard must previously have been set to the
1087 * result of max_parallel_hazard() on the whole query.
1090 is_parallel_safe(PlannerInfo *root, Node *node)
1092 max_parallel_hazard_context context;
1097 * Even if the original querytree contained nothing unsafe, we need to
1098 * search the expression if we have generated any PARAM_EXEC Params while
1099 * planning, because those are parallel-restricted and there might be one
1100 * in this expression. But otherwise we don't need to look.
1102 if (root->glob->maxParallelHazard == PROPARALLEL_SAFE &&
1103 root->glob->paramExecTypes == NIL)
1105 /* Else use max_parallel_hazard's search logic, but stop on RESTRICTED */
1106 context.max_hazard = PROPARALLEL_SAFE;
1107 context.max_interesting = PROPARALLEL_RESTRICTED;
1108 context.safe_param_ids = NIL;
1111 * The params that refer to the same or parent query level are considered
1112 * parallel-safe. The idea is that we compute such params at Gather or
1113 * Gather Merge node and pass their value to workers.
1115 for (proot = root; proot != NULL; proot = proot->parent_root)
1117 foreach(l, proot->init_plans)
1119 SubPlan *initsubplan = (SubPlan *) lfirst(l);
1122 foreach(l2, initsubplan->setParam)
1123 context.safe_param_ids = lcons_int(lfirst_int(l2),
1124 context.safe_param_ids);
1128 return !max_parallel_hazard_walker(node, &context);
1131 /* core logic for all parallel-hazard checks */
1133 max_parallel_hazard_test(char proparallel, max_parallel_hazard_context *context)
1135 switch (proparallel)
1137 case PROPARALLEL_SAFE:
1138 /* nothing to see here, move along */
1140 case PROPARALLEL_RESTRICTED:
1141 /* increase max_hazard to RESTRICTED */
1142 Assert(context->max_hazard != PROPARALLEL_UNSAFE);
1143 context->max_hazard = proparallel;
1144 /* done if we are not expecting any unsafe functions */
1145 if (context->max_interesting == proparallel)
1148 case PROPARALLEL_UNSAFE:
1149 context->max_hazard = proparallel;
1150 /* we're always done at the first unsafe construct */
1153 elog(ERROR, "unrecognized proparallel value \"%c\"", proparallel);
1159 /* check_functions_in_node callback */
1161 max_parallel_hazard_checker(Oid func_id, void *context)
1163 return max_parallel_hazard_test(func_parallel(func_id),
1164 (max_parallel_hazard_context *) context);
1168 max_parallel_hazard_walker(Node *node, max_parallel_hazard_context *context)
1173 /* Check for hazardous functions in node itself */
1174 if (check_functions_in_node(node, max_parallel_hazard_checker,
1179 * It should be OK to treat MinMaxExpr as parallel-safe, since btree
1180 * opclass support functions are generally parallel-safe. XmlExpr is a
1181 * bit more dubious but we can probably get away with it. We err on the
1182 * side of caution by treating CoerceToDomain as parallel-restricted.
1183 * (Note: in principle that's wrong because a domain constraint could
1184 * contain a parallel-unsafe function; but useful constraints probably
1185 * never would have such, and assuming they do would cripple use of
1186 * parallel query in the presence of domain types.) SQLValueFunction
1187 * should be safe in all cases. NextValueExpr is parallel-unsafe.
1189 if (IsA(node, CoerceToDomain))
1191 if (max_parallel_hazard_test(PROPARALLEL_RESTRICTED, context))
1195 if (IsA(node, NextValueExpr))
1197 if (max_parallel_hazard_test(PROPARALLEL_UNSAFE, context))
1202 * As a notational convenience for callers, look through RestrictInfo.
1204 else if (IsA(node, RestrictInfo))
1206 RestrictInfo *rinfo = (RestrictInfo *) node;
1208 return max_parallel_hazard_walker((Node *) rinfo->clause, context);
1212 * Really we should not see SubLink during a max_interesting == restricted
1213 * scan, but if we do, return true.
1215 else if (IsA(node, SubLink))
1217 if (max_parallel_hazard_test(PROPARALLEL_RESTRICTED, context))
1222 * Only parallel-safe SubPlans can be sent to workers. Within the
1223 * testexpr of the SubPlan, Params representing the output columns of the
1224 * subplan can be treated as parallel-safe, so temporarily add their IDs
1225 * to the safe_param_ids list while examining the testexpr.
1227 else if (IsA(node, SubPlan))
1229 SubPlan *subplan = (SubPlan *) node;
1230 List *save_safe_param_ids;
1232 if (!subplan->parallel_safe &&
1233 max_parallel_hazard_test(PROPARALLEL_RESTRICTED, context))
1235 save_safe_param_ids = context->safe_param_ids;
1236 context->safe_param_ids = list_concat(list_copy(subplan->paramIds),
1237 context->safe_param_ids);
1238 if (max_parallel_hazard_walker(subplan->testexpr, context))
1239 return true; /* no need to restore safe_param_ids */
1240 context->safe_param_ids = save_safe_param_ids;
1241 /* we must also check args, but no special Param treatment there */
1242 if (max_parallel_hazard_walker((Node *) subplan->args, context))
1244 /* don't want to recurse normally, so we're done */
1249 * We can't pass Params to workers at the moment either, so they are also
1250 * parallel-restricted, unless they are PARAM_EXTERN Params or are
1251 * PARAM_EXEC Params listed in safe_param_ids, meaning they could be
1252 * either generated within the worker or can be computed in master and
1253 * then their value can be passed to the worker.
1255 else if (IsA(node, Param))
1257 Param *param = (Param *) node;
1259 if (param->paramkind == PARAM_EXTERN)
1262 if (param->paramkind != PARAM_EXEC ||
1263 !list_member_int(context->safe_param_ids, param->paramid))
1265 if (max_parallel_hazard_test(PROPARALLEL_RESTRICTED, context))
1268 return false; /* nothing to recurse to */
1272 * When we're first invoked on a completely unplanned tree, we must
1273 * recurse into subqueries so to as to locate parallel-unsafe constructs
1274 * anywhere in the tree.
1276 else if (IsA(node, Query))
1278 Query *query = (Query *) node;
1280 /* SELECT FOR UPDATE/SHARE must be treated as unsafe */
1281 if (query->rowMarks != NULL)
1283 context->max_hazard = PROPARALLEL_UNSAFE;
1287 /* Recurse into subselects */
1288 return query_tree_walker(query,
1289 max_parallel_hazard_walker,
1293 /* Recurse to check arguments */
1294 return expression_tree_walker(node,
1295 max_parallel_hazard_walker,
1300 /*****************************************************************************
1301 * Check clauses for nonstrict functions
1302 *****************************************************************************/
1305 * contain_nonstrict_functions
1306 * Recursively search for nonstrict functions within a clause.
1308 * Returns true if any nonstrict construct is found --- ie, anything that
1309 * could produce non-NULL output with a NULL input.
1311 * The idea here is that the caller has verified that the expression contains
1312 * one or more Var or Param nodes (as appropriate for the caller's need), and
1313 * now wishes to prove that the expression result will be NULL if any of these
1314 * inputs is NULL. If we return false, then the proof succeeded.
1317 contain_nonstrict_functions(Node *clause)
1319 return contain_nonstrict_functions_walker(clause, NULL);
1323 contain_nonstrict_functions_checker(Oid func_id, void *context)
1325 return !func_strict(func_id);
1329 contain_nonstrict_functions_walker(Node *node, void *context)
1333 if (IsA(node, Aggref))
1335 /* an aggregate could return non-null with null input */
1338 if (IsA(node, GroupingFunc))
1341 * A GroupingFunc doesn't evaluate its arguments, and therefore must
1342 * be treated as nonstrict.
1346 if (IsA(node, WindowFunc))
1348 /* a window function could return non-null with null input */
1351 if (IsA(node, ArrayRef))
1353 /* array assignment is nonstrict, but subscripting is strict */
1354 if (((ArrayRef *) node)->refassgnexpr != NULL)
1356 /* else fall through to check args */
1358 if (IsA(node, DistinctExpr))
1360 /* IS DISTINCT FROM is inherently non-strict */
1363 if (IsA(node, NullIfExpr))
1365 /* NULLIF is inherently non-strict */
1368 if (IsA(node, BoolExpr))
1370 BoolExpr *expr = (BoolExpr *) node;
1372 switch (expr->boolop)
1376 /* AND, OR are inherently non-strict */
1382 if (IsA(node, SubLink))
1384 /* In some cases a sublink might be strict, but in general not */
1387 if (IsA(node, SubPlan))
1389 if (IsA(node, AlternativeSubPlan))
1391 if (IsA(node, FieldStore))
1393 if (IsA(node, ArrayCoerceExpr))
1396 * ArrayCoerceExpr is strict at the array level, regardless of what
1397 * the per-element expression is; so we should ignore elemexpr and
1398 * recurse only into the arg.
1400 return expression_tree_walker((Node *) ((ArrayCoerceExpr *) node)->arg,
1401 contain_nonstrict_functions_walker,
1404 if (IsA(node, CaseExpr))
1406 if (IsA(node, ArrayExpr))
1408 if (IsA(node, RowExpr))
1410 if (IsA(node, RowCompareExpr))
1412 if (IsA(node, CoalesceExpr))
1414 if (IsA(node, MinMaxExpr))
1416 if (IsA(node, XmlExpr))
1418 if (IsA(node, NullTest))
1420 if (IsA(node, BooleanTest))
1423 /* Check other function-containing nodes */
1424 if (check_functions_in_node(node, contain_nonstrict_functions_checker,
1428 return expression_tree_walker(node, contain_nonstrict_functions_walker,
1432 /*****************************************************************************
1433 * Check clauses for context-dependent nodes
1434 *****************************************************************************/
1437 * contain_context_dependent_node
1438 * Recursively search for context-dependent nodes within a clause.
1440 * CaseTestExpr nodes must appear directly within the corresponding CaseExpr,
1441 * not nested within another one, or they'll see the wrong test value. If one
1442 * appears "bare" in the arguments of a SQL function, then we can't inline the
1443 * SQL function for fear of creating such a situation.
1445 * CoerceToDomainValue would have the same issue if domain CHECK expressions
1446 * could get inlined into larger expressions, but presently that's impossible.
1447 * Still, it might be allowed in future, or other node types with similar
1448 * issues might get invented. So give this function a generic name, and set
1449 * up the recursion state to allow multiple flag bits.
1452 contain_context_dependent_node(Node *clause)
1456 return contain_context_dependent_node_walker(clause, &flags);
1459 #define CCDN_IN_CASEEXPR 0x0001 /* CaseTestExpr okay here? */
1462 contain_context_dependent_node_walker(Node *node, int *flags)
1466 if (IsA(node, CaseTestExpr))
1467 return !(*flags & CCDN_IN_CASEEXPR);
1468 if (IsA(node, CaseExpr))
1470 CaseExpr *caseexpr = (CaseExpr *) node;
1473 * If this CASE doesn't have a test expression, then it doesn't create
1474 * a context in which CaseTestExprs should appear, so just fall
1475 * through and treat it as a generic expression node.
1479 int save_flags = *flags;
1483 * Note: in principle, we could distinguish the various sub-parts
1484 * of a CASE construct and set the flag bit only for some of them,
1485 * since we are only expecting CaseTestExprs to appear in the
1486 * "expr" subtree of the CaseWhen nodes. But it doesn't really
1487 * seem worth any extra code. If there are any bare CaseTestExprs
1488 * elsewhere in the CASE, something's wrong already.
1490 *flags |= CCDN_IN_CASEEXPR;
1491 res = expression_tree_walker(node,
1492 contain_context_dependent_node_walker,
1494 *flags = save_flags;
1498 return expression_tree_walker(node, contain_context_dependent_node_walker,
1502 /*****************************************************************************
1503 * Check clauses for Vars passed to non-leakproof functions
1504 *****************************************************************************/
1507 * contain_leaked_vars
1508 * Recursively scan a clause to discover whether it contains any Var
1509 * nodes (of the current query level) that are passed as arguments to
1512 * Returns true if the clause contains any non-leakproof functions that are
1513 * passed Var nodes of the current query level, and which might therefore leak
1514 * data. Such clauses must be applied after any lower-level security barrier
1518 contain_leaked_vars(Node *clause)
1520 return contain_leaked_vars_walker(clause, NULL);
1524 contain_leaked_vars_checker(Oid func_id, void *context)
1526 return !get_func_leakproof(func_id);
1530 contain_leaked_vars_walker(Node *node, void *context)
1535 switch (nodeTag(node))
1544 case T_NamedArgExpr:
1549 case T_CaseTestExpr:
1552 case T_SQLValueFunction:
1555 case T_NextValueExpr:
1559 * We know these node types don't contain function calls; but
1560 * something further down in the node tree might.
1566 case T_DistinctExpr:
1568 case T_ScalarArrayOpExpr:
1570 case T_ArrayCoerceExpr:
1573 * If node contains a leaky function call, and there's any Var
1574 * underneath it, reject.
1576 if (check_functions_in_node(node, contain_leaked_vars_checker,
1578 contain_var_clause(node))
1582 case T_RowCompareExpr:
1585 * It's worth special-casing this because a leaky comparison
1586 * function only compromises one pair of row elements, which
1587 * might not contain Vars while others do.
1589 RowCompareExpr *rcexpr = (RowCompareExpr *) node;
1594 forthree(opid, rcexpr->opnos,
1595 larg, rcexpr->largs,
1596 rarg, rcexpr->rargs)
1598 Oid funcid = get_opcode(lfirst_oid(opid));
1600 if (!get_func_leakproof(funcid) &&
1601 (contain_var_clause((Node *) lfirst(larg)) ||
1602 contain_var_clause((Node *) lfirst(rarg))))
1608 case T_CurrentOfExpr:
1611 * WHERE CURRENT OF doesn't contain leaky function calls.
1612 * Moreover, it is essential that this is considered non-leaky,
1613 * since the planner must always generate a TID scan when CURRENT
1614 * OF is present -- cf. cost_tidscan.
1621 * If we don't recognize the node tag, assume it might be leaky.
1622 * This prevents an unexpected security hole if someone adds a new
1623 * node type that can call a function.
1627 return expression_tree_walker(node, contain_leaked_vars_walker,
1632 * find_nonnullable_rels
1633 * Determine which base rels are forced nonnullable by given clause.
1635 * Returns the set of all Relids that are referenced in the clause in such
1636 * a way that the clause cannot possibly return TRUE if any of these Relids
1637 * is an all-NULL row. (It is OK to err on the side of conservatism; hence
1638 * the analysis here is simplistic.)
1640 * The semantics here are subtly different from contain_nonstrict_functions:
1641 * that function is concerned with NULL results from arbitrary expressions,
1642 * but here we assume that the input is a Boolean expression, and wish to
1643 * see if NULL inputs will provably cause a FALSE-or-NULL result. We expect
1644 * the expression to have been AND/OR flattened and converted to implicit-AND
1647 * Note: this function is largely duplicative of find_nonnullable_vars().
1648 * The reason not to simplify this function into a thin wrapper around
1649 * find_nonnullable_vars() is that the tested conditions really are different:
1650 * a clause like "t1.v1 IS NOT NULL OR t1.v2 IS NOT NULL" does not prove
1651 * that either v1 or v2 can't be NULL, but it does prove that the t1 row
1652 * as a whole can't be all-NULL.
1654 * top_level is true while scanning top-level AND/OR structure; here, showing
1655 * the result is either FALSE or NULL is good enough. top_level is false when
1656 * we have descended below a NOT or a strict function: now we must be able to
1657 * prove that the subexpression goes to NULL.
1659 * We don't use expression_tree_walker here because we don't want to descend
1660 * through very many kinds of nodes; only the ones we can be sure are strict.
1663 find_nonnullable_rels(Node *clause)
1665 return find_nonnullable_rels_walker(clause, true);
1669 find_nonnullable_rels_walker(Node *node, bool top_level)
1671 Relids result = NULL;
1678 Var *var = (Var *) node;
1680 if (var->varlevelsup == 0)
1681 result = bms_make_singleton(var->varno);
1683 else if (IsA(node, List))
1686 * At top level, we are examining an implicit-AND list: if any of the
1687 * arms produces FALSE-or-NULL then the result is FALSE-or-NULL. If
1688 * not at top level, we are examining the arguments of a strict
1689 * function: if any of them produce NULL then the result of the
1690 * function must be NULL. So in both cases, the set of nonnullable
1691 * rels is the union of those found in the arms, and we pass down the
1692 * top_level flag unmodified.
1694 foreach(l, (List *) node)
1696 result = bms_join(result,
1697 find_nonnullable_rels_walker(lfirst(l),
1701 else if (IsA(node, FuncExpr))
1703 FuncExpr *expr = (FuncExpr *) node;
1705 if (func_strict(expr->funcid))
1706 result = find_nonnullable_rels_walker((Node *) expr->args, false);
1708 else if (IsA(node, OpExpr))
1710 OpExpr *expr = (OpExpr *) node;
1713 if (func_strict(expr->opfuncid))
1714 result = find_nonnullable_rels_walker((Node *) expr->args, false);
1716 else if (IsA(node, ScalarArrayOpExpr))
1718 ScalarArrayOpExpr *expr = (ScalarArrayOpExpr *) node;
1720 if (is_strict_saop(expr, true))
1721 result = find_nonnullable_rels_walker((Node *) expr->args, false);
1723 else if (IsA(node, BoolExpr))
1725 BoolExpr *expr = (BoolExpr *) node;
1727 switch (expr->boolop)
1730 /* At top level we can just recurse (to the List case) */
1733 result = find_nonnullable_rels_walker((Node *) expr->args,
1739 * Below top level, even if one arm produces NULL, the result
1740 * could be FALSE (hence not NULL). However, if *all* the
1741 * arms produce NULL then the result is NULL, so we can take
1742 * the intersection of the sets of nonnullable rels, just as
1743 * for OR. Fall through to share code.
1749 * OR is strict if all of its arms are, so we can take the
1750 * intersection of the sets of nonnullable rels for each arm.
1751 * This works for both values of top_level.
1753 foreach(l, expr->args)
1757 subresult = find_nonnullable_rels_walker(lfirst(l),
1759 if (result == NULL) /* first subresult? */
1762 result = bms_int_members(result, subresult);
1765 * If the intersection is empty, we can stop looking. This
1766 * also justifies the test for first-subresult above.
1768 if (bms_is_empty(result))
1773 /* NOT will return null if its arg is null */
1774 result = find_nonnullable_rels_walker((Node *) expr->args,
1778 elog(ERROR, "unrecognized boolop: %d", (int) expr->boolop);
1782 else if (IsA(node, RelabelType))
1784 RelabelType *expr = (RelabelType *) node;
1786 result = find_nonnullable_rels_walker((Node *) expr->arg, top_level);
1788 else if (IsA(node, CoerceViaIO))
1790 /* not clear this is useful, but it can't hurt */
1791 CoerceViaIO *expr = (CoerceViaIO *) node;
1793 result = find_nonnullable_rels_walker((Node *) expr->arg, top_level);
1795 else if (IsA(node, ArrayCoerceExpr))
1797 /* ArrayCoerceExpr is strict at the array level; ignore elemexpr */
1798 ArrayCoerceExpr *expr = (ArrayCoerceExpr *) node;
1800 result = find_nonnullable_rels_walker((Node *) expr->arg, top_level);
1802 else if (IsA(node, ConvertRowtypeExpr))
1804 /* not clear this is useful, but it can't hurt */
1805 ConvertRowtypeExpr *expr = (ConvertRowtypeExpr *) node;
1807 result = find_nonnullable_rels_walker((Node *) expr->arg, top_level);
1809 else if (IsA(node, CollateExpr))
1811 CollateExpr *expr = (CollateExpr *) node;
1813 result = find_nonnullable_rels_walker((Node *) expr->arg, top_level);
1815 else if (IsA(node, NullTest))
1817 /* IS NOT NULL can be considered strict, but only at top level */
1818 NullTest *expr = (NullTest *) node;
1820 if (top_level && expr->nulltesttype == IS_NOT_NULL && !expr->argisrow)
1821 result = find_nonnullable_rels_walker((Node *) expr->arg, false);
1823 else if (IsA(node, BooleanTest))
1825 /* Boolean tests that reject NULL are strict at top level */
1826 BooleanTest *expr = (BooleanTest *) node;
1829 (expr->booltesttype == IS_TRUE ||
1830 expr->booltesttype == IS_FALSE ||
1831 expr->booltesttype == IS_NOT_UNKNOWN))
1832 result = find_nonnullable_rels_walker((Node *) expr->arg, false);
1834 else if (IsA(node, PlaceHolderVar))
1836 PlaceHolderVar *phv = (PlaceHolderVar *) node;
1838 result = find_nonnullable_rels_walker((Node *) phv->phexpr, top_level);
1844 * find_nonnullable_vars
1845 * Determine which Vars are forced nonnullable by given clause.
1847 * Returns a list of all level-zero Vars that are referenced in the clause in
1848 * such a way that the clause cannot possibly return TRUE if any of these Vars
1849 * is NULL. (It is OK to err on the side of conservatism; hence the analysis
1850 * here is simplistic.)
1852 * The semantics here are subtly different from contain_nonstrict_functions:
1853 * that function is concerned with NULL results from arbitrary expressions,
1854 * but here we assume that the input is a Boolean expression, and wish to
1855 * see if NULL inputs will provably cause a FALSE-or-NULL result. We expect
1856 * the expression to have been AND/OR flattened and converted to implicit-AND
1859 * The result is a palloc'd List, but we have not copied the member Var nodes.
1860 * Also, we don't bother trying to eliminate duplicate entries.
1862 * top_level is true while scanning top-level AND/OR structure; here, showing
1863 * the result is either FALSE or NULL is good enough. top_level is false when
1864 * we have descended below a NOT or a strict function: now we must be able to
1865 * prove that the subexpression goes to NULL.
1867 * We don't use expression_tree_walker here because we don't want to descend
1868 * through very many kinds of nodes; only the ones we can be sure are strict.
1871 find_nonnullable_vars(Node *clause)
1873 return find_nonnullable_vars_walker(clause, true);
1877 find_nonnullable_vars_walker(Node *node, bool top_level)
1886 Var *var = (Var *) node;
1888 if (var->varlevelsup == 0)
1889 result = list_make1(var);
1891 else if (IsA(node, List))
1894 * At top level, we are examining an implicit-AND list: if any of the
1895 * arms produces FALSE-or-NULL then the result is FALSE-or-NULL. If
1896 * not at top level, we are examining the arguments of a strict
1897 * function: if any of them produce NULL then the result of the
1898 * function must be NULL. So in both cases, the set of nonnullable
1899 * vars is the union of those found in the arms, and we pass down the
1900 * top_level flag unmodified.
1902 foreach(l, (List *) node)
1904 result = list_concat(result,
1905 find_nonnullable_vars_walker(lfirst(l),
1909 else if (IsA(node, FuncExpr))
1911 FuncExpr *expr = (FuncExpr *) node;
1913 if (func_strict(expr->funcid))
1914 result = find_nonnullable_vars_walker((Node *) expr->args, false);
1916 else if (IsA(node, OpExpr))
1918 OpExpr *expr = (OpExpr *) node;
1921 if (func_strict(expr->opfuncid))
1922 result = find_nonnullable_vars_walker((Node *) expr->args, false);
1924 else if (IsA(node, ScalarArrayOpExpr))
1926 ScalarArrayOpExpr *expr = (ScalarArrayOpExpr *) node;
1928 if (is_strict_saop(expr, true))
1929 result = find_nonnullable_vars_walker((Node *) expr->args, false);
1931 else if (IsA(node, BoolExpr))
1933 BoolExpr *expr = (BoolExpr *) node;
1935 switch (expr->boolop)
1938 /* At top level we can just recurse (to the List case) */
1941 result = find_nonnullable_vars_walker((Node *) expr->args,
1947 * Below top level, even if one arm produces NULL, the result
1948 * could be FALSE (hence not NULL). However, if *all* the
1949 * arms produce NULL then the result is NULL, so we can take
1950 * the intersection of the sets of nonnullable vars, just as
1951 * for OR. Fall through to share code.
1957 * OR is strict if all of its arms are, so we can take the
1958 * intersection of the sets of nonnullable vars for each arm.
1959 * This works for both values of top_level.
1961 foreach(l, expr->args)
1965 subresult = find_nonnullable_vars_walker(lfirst(l),
1967 if (result == NIL) /* first subresult? */
1970 result = list_intersection(result, subresult);
1973 * If the intersection is empty, we can stop looking. This
1974 * also justifies the test for first-subresult above.
1981 /* NOT will return null if its arg is null */
1982 result = find_nonnullable_vars_walker((Node *) expr->args,
1986 elog(ERROR, "unrecognized boolop: %d", (int) expr->boolop);
1990 else if (IsA(node, RelabelType))
1992 RelabelType *expr = (RelabelType *) node;
1994 result = find_nonnullable_vars_walker((Node *) expr->arg, top_level);
1996 else if (IsA(node, CoerceViaIO))
1998 /* not clear this is useful, but it can't hurt */
1999 CoerceViaIO *expr = (CoerceViaIO *) node;
2001 result = find_nonnullable_vars_walker((Node *) expr->arg, false);
2003 else if (IsA(node, ArrayCoerceExpr))
2005 /* ArrayCoerceExpr is strict at the array level; ignore elemexpr */
2006 ArrayCoerceExpr *expr = (ArrayCoerceExpr *) node;
2008 result = find_nonnullable_vars_walker((Node *) expr->arg, top_level);
2010 else if (IsA(node, ConvertRowtypeExpr))
2012 /* not clear this is useful, but it can't hurt */
2013 ConvertRowtypeExpr *expr = (ConvertRowtypeExpr *) node;
2015 result = find_nonnullable_vars_walker((Node *) expr->arg, top_level);
2017 else if (IsA(node, CollateExpr))
2019 CollateExpr *expr = (CollateExpr *) node;
2021 result = find_nonnullable_vars_walker((Node *) expr->arg, top_level);
2023 else if (IsA(node, NullTest))
2025 /* IS NOT NULL can be considered strict, but only at top level */
2026 NullTest *expr = (NullTest *) node;
2028 if (top_level && expr->nulltesttype == IS_NOT_NULL && !expr->argisrow)
2029 result = find_nonnullable_vars_walker((Node *) expr->arg, false);
2031 else if (IsA(node, BooleanTest))
2033 /* Boolean tests that reject NULL are strict at top level */
2034 BooleanTest *expr = (BooleanTest *) node;
2037 (expr->booltesttype == IS_TRUE ||
2038 expr->booltesttype == IS_FALSE ||
2039 expr->booltesttype == IS_NOT_UNKNOWN))
2040 result = find_nonnullable_vars_walker((Node *) expr->arg, false);
2042 else if (IsA(node, PlaceHolderVar))
2044 PlaceHolderVar *phv = (PlaceHolderVar *) node;
2046 result = find_nonnullable_vars_walker((Node *) phv->phexpr, top_level);
2052 * find_forced_null_vars
2053 * Determine which Vars must be NULL for the given clause to return TRUE.
2055 * This is the complement of find_nonnullable_vars: find the level-zero Vars
2056 * that must be NULL for the clause to return TRUE. (It is OK to err on the
2057 * side of conservatism; hence the analysis here is simplistic. In fact,
2058 * we only detect simple "var IS NULL" tests at the top level.)
2060 * The result is a palloc'd List, but we have not copied the member Var nodes.
2061 * Also, we don't bother trying to eliminate duplicate entries.
2064 find_forced_null_vars(Node *node)
2072 /* Check single-clause cases using subroutine */
2073 var = find_forced_null_var(node);
2076 result = list_make1(var);
2078 /* Otherwise, handle AND-conditions */
2079 else if (IsA(node, List))
2082 * At top level, we are examining an implicit-AND list: if any of the
2083 * arms produces FALSE-or-NULL then the result is FALSE-or-NULL.
2085 foreach(l, (List *) node)
2087 result = list_concat(result,
2088 find_forced_null_vars(lfirst(l)));
2091 else if (IsA(node, BoolExpr))
2093 BoolExpr *expr = (BoolExpr *) node;
2096 * We don't bother considering the OR case, because it's fairly
2097 * unlikely anyone would write "v1 IS NULL OR v1 IS NULL". Likewise,
2098 * the NOT case isn't worth expending code on.
2100 if (expr->boolop == AND_EXPR)
2102 /* At top level we can just recurse (to the List case) */
2103 result = find_forced_null_vars((Node *) expr->args);
2110 * find_forced_null_var
2111 * Return the Var forced null by the given clause, or NULL if it's
2112 * not an IS NULL-type clause. For success, the clause must enforce
2113 * *only* nullness of the particular Var, not any other conditions.
2115 * This is just the single-clause case of find_forced_null_vars(), without
2116 * any allowance for AND conditions. It's used by initsplan.c on individual
2117 * qual clauses. The reason for not just applying find_forced_null_vars()
2118 * is that if an AND of an IS NULL clause with something else were to somehow
2119 * survive AND/OR flattening, initsplan.c might get fooled into discarding
2120 * the whole clause when only the IS NULL part of it had been proved redundant.
2123 find_forced_null_var(Node *node)
2127 if (IsA(node, NullTest))
2129 /* check for var IS NULL */
2130 NullTest *expr = (NullTest *) node;
2132 if (expr->nulltesttype == IS_NULL && !expr->argisrow)
2134 Var *var = (Var *) expr->arg;
2136 if (var && IsA(var, Var) &&
2137 var->varlevelsup == 0)
2141 else if (IsA(node, BooleanTest))
2143 /* var IS UNKNOWN is equivalent to var IS NULL */
2144 BooleanTest *expr = (BooleanTest *) node;
2146 if (expr->booltesttype == IS_UNKNOWN)
2148 Var *var = (Var *) expr->arg;
2150 if (var && IsA(var, Var) &&
2151 var->varlevelsup == 0)
2159 * Can we treat a ScalarArrayOpExpr as strict?
2161 * If "falseOK" is true, then a "false" result can be considered strict,
2162 * else we need to guarantee an actual NULL result for NULL input.
2164 * "foo op ALL array" is strict if the op is strict *and* we can prove
2165 * that the array input isn't an empty array. We can check that
2166 * for the cases of an array constant and an ARRAY[] construct.
2168 * "foo op ANY array" is strict in the falseOK sense if the op is strict.
2169 * If not falseOK, the test is the same as for "foo op ALL array".
2172 is_strict_saop(ScalarArrayOpExpr *expr, bool falseOK)
2176 /* The contained operator must be strict. */
2177 set_sa_opfuncid(expr);
2178 if (!func_strict(expr->opfuncid))
2180 /* If ANY and falseOK, that's all we need to check. */
2181 if (expr->useOr && falseOK)
2183 /* Else, we have to see if the array is provably non-empty. */
2184 Assert(list_length(expr->args) == 2);
2185 rightop = (Node *) lsecond(expr->args);
2186 if (rightop && IsA(rightop, Const))
2188 Datum arraydatum = ((Const *) rightop)->constvalue;
2189 bool arrayisnull = ((Const *) rightop)->constisnull;
2190 ArrayType *arrayval;
2195 arrayval = DatumGetArrayTypeP(arraydatum);
2196 nitems = ArrayGetNItems(ARR_NDIM(arrayval), ARR_DIMS(arrayval));
2200 else if (rightop && IsA(rightop, ArrayExpr))
2202 ArrayExpr *arrayexpr = (ArrayExpr *) rightop;
2204 if (arrayexpr->elements != NIL && !arrayexpr->multidims)
2211 /*****************************************************************************
2212 * Check for "pseudo-constant" clauses
2213 *****************************************************************************/
2216 * is_pseudo_constant_clause
2217 * Detect whether an expression is "pseudo constant", ie, it contains no
2218 * variables of the current query level and no uses of volatile functions.
2219 * Such an expr is not necessarily a true constant: it can still contain
2220 * Params and outer-level Vars, not to mention functions whose results
2221 * may vary from one statement to the next. However, the expr's value
2222 * will be constant over any one scan of the current query, so it can be
2223 * used as, eg, an indexscan key.
2225 * CAUTION: this function omits to test for one very important class of
2226 * not-constant expressions, namely aggregates (Aggrefs). In current usage
2227 * this is only applied to WHERE clauses and so a check for Aggrefs would be
2228 * a waste of cycles; but be sure to also check contain_agg_clause() if you
2229 * want to know about pseudo-constness in other contexts. The same goes
2230 * for window functions (WindowFuncs).
2233 is_pseudo_constant_clause(Node *clause)
2236 * We could implement this check in one recursive scan. But since the
2237 * check for volatile functions is both moderately expensive and unlikely
2238 * to fail, it seems better to look for Vars first and only check for
2239 * volatile functions if we find no Vars.
2241 if (!contain_var_clause(clause) &&
2242 !contain_volatile_functions(clause))
2248 * is_pseudo_constant_clause_relids
2249 * Same as above, except caller already has available the var membership
2250 * of the expression; this lets us avoid the contain_var_clause() scan.
2253 is_pseudo_constant_clause_relids(Node *clause, Relids relids)
2255 if (bms_is_empty(relids) &&
2256 !contain_volatile_functions(clause))
2262 /*****************************************************************************
2264 * General clause-manipulating routines *
2266 *****************************************************************************/
2270 * (formerly clause_relids)
2272 * Returns the number of different relations referenced in 'clause'.
2275 NumRelids(Node *clause)
2277 Relids varnos = pull_varnos(clause);
2278 int result = bms_num_members(varnos);
2285 * CommuteOpExpr: commute a binary operator clause
2287 * XXX the clause is destructively modified!
2290 CommuteOpExpr(OpExpr *clause)
2295 /* Sanity checks: caller is at fault if these fail */
2296 if (!is_opclause(clause) ||
2297 list_length(clause->args) != 2)
2298 elog(ERROR, "cannot commute non-binary-operator clause");
2300 opoid = get_commutator(clause->opno);
2302 if (!OidIsValid(opoid))
2303 elog(ERROR, "could not find commutator for operator %u",
2307 * modify the clause in-place!
2309 clause->opno = opoid;
2310 clause->opfuncid = InvalidOid;
2311 /* opresulttype, opretset, opcollid, inputcollid need not change */
2313 temp = linitial(clause->args);
2314 linitial(clause->args) = lsecond(clause->args);
2315 lsecond(clause->args) = temp;
2319 * CommuteRowCompareExpr: commute a RowCompareExpr clause
2321 * XXX the clause is destructively modified!
2324 CommuteRowCompareExpr(RowCompareExpr *clause)
2330 /* Sanity checks: caller is at fault if these fail */
2331 if (!IsA(clause, RowCompareExpr))
2332 elog(ERROR, "expected a RowCompareExpr");
2334 /* Build list of commuted operators */
2336 foreach(l, clause->opnos)
2338 Oid opoid = lfirst_oid(l);
2340 opoid = get_commutator(opoid);
2341 if (!OidIsValid(opoid))
2342 elog(ERROR, "could not find commutator for operator %u",
2344 newops = lappend_oid(newops, opoid);
2348 * modify the clause in-place!
2350 switch (clause->rctype)
2353 clause->rctype = ROWCOMPARE_GT;
2356 clause->rctype = ROWCOMPARE_GE;
2359 clause->rctype = ROWCOMPARE_LE;
2362 clause->rctype = ROWCOMPARE_LT;
2365 elog(ERROR, "unexpected RowCompare type: %d",
2366 (int) clause->rctype);
2370 clause->opnos = newops;
2373 * Note: we need not change the opfamilies list; we assume any btree
2374 * opfamily containing an operator will also contain its commutator.
2375 * Collations don't change either.
2378 temp = clause->largs;
2379 clause->largs = clause->rargs;
2380 clause->rargs = temp;
2384 * Helper for eval_const_expressions: check that datatype of an attribute
2385 * is still what it was when the expression was parsed. This is needed to
2386 * guard against improper simplification after ALTER COLUMN TYPE. (XXX we
2387 * may well need to make similar checks elsewhere?)
2389 * rowtypeid may come from a whole-row Var, and therefore it can be a domain
2390 * over composite, but for this purpose we only care about checking the type
2391 * of a contained field.
2394 rowtype_field_matches(Oid rowtypeid, int fieldnum,
2395 Oid expectedtype, int32 expectedtypmod,
2396 Oid expectedcollation)
2399 Form_pg_attribute attr;
2401 /* No issue for RECORD, since there is no way to ALTER such a type */
2402 if (rowtypeid == RECORDOID)
2404 tupdesc = lookup_rowtype_tupdesc_domain(rowtypeid, -1, false);
2405 if (fieldnum <= 0 || fieldnum > tupdesc->natts)
2407 ReleaseTupleDesc(tupdesc);
2410 attr = TupleDescAttr(tupdesc, fieldnum - 1);
2411 if (attr->attisdropped ||
2412 attr->atttypid != expectedtype ||
2413 attr->atttypmod != expectedtypmod ||
2414 attr->attcollation != expectedcollation)
2416 ReleaseTupleDesc(tupdesc);
2419 ReleaseTupleDesc(tupdesc);
2424 /*--------------------
2425 * eval_const_expressions
2427 * Reduce any recognizably constant subexpressions of the given
2428 * expression tree, for example "2 + 2" => "4". More interestingly,
2429 * we can reduce certain boolean expressions even when they contain
2430 * non-constant subexpressions: "x OR true" => "true" no matter what
2431 * the subexpression x is. (XXX We assume that no such subexpression
2432 * will have important side-effects, which is not necessarily a good
2433 * assumption in the presence of user-defined functions; do we need a
2434 * pg_proc flag that prevents discarding the execution of a function?)
2436 * We do understand that certain functions may deliver non-constant
2437 * results even with constant inputs, "nextval()" being the classic
2438 * example. Functions that are not marked "immutable" in pg_proc
2439 * will not be pre-evaluated here, although we will reduce their
2440 * arguments as far as possible.
2442 * Whenever a function is eliminated from the expression by means of
2443 * constant-expression evaluation or inlining, we add the function to
2444 * root->glob->invalItems. This ensures the plan is known to depend on
2445 * such functions, even though they aren't referenced anymore.
2447 * We assume that the tree has already been type-checked and contains
2448 * only operators and functions that are reasonable to try to execute.
2450 * NOTE: "root" can be passed as NULL if the caller never wants to do any
2451 * Param substitutions nor receive info about inlined functions.
2453 * NOTE: the planner assumes that this will always flatten nested AND and
2454 * OR clauses into N-argument form. See comments in prepqual.c.
2456 * NOTE: another critical effect is that any function calls that require
2457 * default arguments will be expanded, and named-argument calls will be
2458 * converted to positional notation. The executor won't handle either.
2459 *--------------------
2462 eval_const_expressions(PlannerInfo *root, Node *node)
2464 eval_const_expressions_context context;
2467 context.boundParams = root->glob->boundParams; /* bound Params */
2469 context.boundParams = NULL;
2470 context.root = root; /* for inlined-function dependencies */
2471 context.active_fns = NIL; /* nothing being recursively simplified */
2472 context.case_val = NULL; /* no CASE being examined */
2473 context.estimate = false; /* safe transformations only */
2474 return eval_const_expressions_mutator(node, &context);
2477 /*--------------------
2478 * estimate_expression_value
2480 * This function attempts to estimate the value of an expression for
2481 * planning purposes. It is in essence a more aggressive version of
2482 * eval_const_expressions(): we will perform constant reductions that are
2483 * not necessarily 100% safe, but are reasonable for estimation purposes.
2485 * Currently the extra steps that are taken in this mode are:
2486 * 1. Substitute values for Params, where a bound Param value has been made
2487 * available by the caller of planner(), even if the Param isn't marked
2488 * constant. This effectively means that we plan using the first supplied
2489 * value of the Param.
2490 * 2. Fold stable, as well as immutable, functions to constants.
2491 * 3. Reduce PlaceHolderVar nodes to their contained expressions.
2492 *--------------------
2495 estimate_expression_value(PlannerInfo *root, Node *node)
2497 eval_const_expressions_context context;
2499 context.boundParams = root->glob->boundParams; /* bound Params */
2500 /* we do not need to mark the plan as depending on inlined functions */
2501 context.root = NULL;
2502 context.active_fns = NIL; /* nothing being recursively simplified */
2503 context.case_val = NULL; /* no CASE being examined */
2504 context.estimate = true; /* unsafe transformations OK */
2505 return eval_const_expressions_mutator(node, &context);
2509 * The generic case in eval_const_expressions_mutator is to recurse using
2510 * expression_tree_mutator, which will copy the given node unchanged but
2511 * const-simplify its arguments (if any) as far as possible. If the node
2512 * itself does immutable processing, and each of its arguments were reduced
2513 * to a Const, we can then reduce it to a Const using evaluate_expr. (Some
2514 * node types need more complicated logic; for example, a CASE expression
2515 * might be reducible to a constant even if not all its subtrees are.)
2517 #define ece_generic_processing(node) \
2518 expression_tree_mutator((Node *) (node), eval_const_expressions_mutator, \
2522 * Check whether all arguments of the given node were reduced to Consts.
2523 * By going directly to expression_tree_walker, contain_non_const_walker
2524 * is not applied to the node itself, only to its children.
2526 #define ece_all_arguments_const(node) \
2527 (!expression_tree_walker((Node *) (node), contain_non_const_walker, NULL))
2529 /* Generic macro for applying evaluate_expr */
2530 #define ece_evaluate_expr(node) \
2531 ((Node *) evaluate_expr((Expr *) (node), \
2532 exprType((Node *) (node)), \
2533 exprTypmod((Node *) (node)), \
2534 exprCollation((Node *) (node))))
2537 * Recursive guts of eval_const_expressions/estimate_expression_value
2540 eval_const_expressions_mutator(Node *node,
2541 eval_const_expressions_context *context)
2545 switch (nodeTag(node))
2549 Param *param = (Param *) node;
2550 ParamListInfo paramLI = context->boundParams;
2552 /* Look to see if we've been given a value for this Param */
2553 if (param->paramkind == PARAM_EXTERN &&
2555 param->paramid > 0 &&
2556 param->paramid <= paramLI->numParams)
2558 ParamExternData *prm;
2559 ParamExternData prmdata;
2562 * Give hook a chance in case parameter is dynamic. Tell
2563 * it that this fetch is speculative, so it should avoid
2564 * erroring out if parameter is unavailable.
2566 if (paramLI->paramFetch != NULL)
2567 prm = paramLI->paramFetch(paramLI, param->paramid,
2570 prm = ¶mLI->params[param->paramid - 1];
2572 if (OidIsValid(prm->ptype))
2574 /* OK to substitute parameter value? */
2575 if (context->estimate ||
2576 (prm->pflags & PARAM_FLAG_CONST))
2579 * Return a Const representing the param value.
2580 * Must copy pass-by-ref datatypes, since the
2581 * Param might be in a memory context
2582 * shorter-lived than our output plan should be.
2588 Assert(prm->ptype == param->paramtype);
2589 get_typlenbyval(param->paramtype,
2590 &typLen, &typByVal);
2591 if (prm->isnull || typByVal)
2594 pval = datumCopy(prm->value, typByVal, typLen);
2595 return (Node *) makeConst(param->paramtype,
2607 * Not replaceable, so just copy the Param (no need to
2610 return (Node *) copyObject(param);
2614 WindowFunc *expr = (WindowFunc *) node;
2615 Oid funcid = expr->winfnoid;
2618 HeapTuple func_tuple;
2619 WindowFunc *newexpr;
2622 * We can't really simplify a WindowFunc node, but we mustn't
2623 * just fall through to the default processing, because we
2624 * have to apply expand_function_arguments to its argument
2625 * list. That takes care of inserting default arguments and
2626 * expanding named-argument notation.
2628 func_tuple = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcid));
2629 if (!HeapTupleIsValid(func_tuple))
2630 elog(ERROR, "cache lookup failed for function %u", funcid);
2632 args = expand_function_arguments(expr->args, expr->wintype,
2635 ReleaseSysCache(func_tuple);
2637 /* Now, recursively simplify the args (which are a List) */
2639 expression_tree_mutator((Node *) args,
2640 eval_const_expressions_mutator,
2642 /* ... and the filter expression, which isn't */
2643 aggfilter = (Expr *)
2644 eval_const_expressions_mutator((Node *) expr->aggfilter,
2647 /* And build the replacement WindowFunc node */
2648 newexpr = makeNode(WindowFunc);
2649 newexpr->winfnoid = expr->winfnoid;
2650 newexpr->wintype = expr->wintype;
2651 newexpr->wincollid = expr->wincollid;
2652 newexpr->inputcollid = expr->inputcollid;
2653 newexpr->args = args;
2654 newexpr->aggfilter = aggfilter;
2655 newexpr->winref = expr->winref;
2656 newexpr->winstar = expr->winstar;
2657 newexpr->winagg = expr->winagg;
2658 newexpr->location = expr->location;
2660 return (Node *) newexpr;
2664 FuncExpr *expr = (FuncExpr *) node;
2665 List *args = expr->args;
2670 * Code for op/func reduction is pretty bulky, so split it out
2671 * as a separate function. Note: exprTypmod normally returns
2672 * -1 for a FuncExpr, but not when the node is recognizably a
2673 * length coercion; we want to preserve the typmod in the
2674 * eventual Const if so.
2676 simple = simplify_function(expr->funcid,
2677 expr->funcresulttype,
2686 if (simple) /* successfully simplified it */
2687 return (Node *) simple;
2690 * The expression cannot be simplified any further, so build
2691 * and return a replacement FuncExpr node using the
2692 * possibly-simplified arguments. Note that we have also
2693 * converted the argument list to positional notation.
2695 newexpr = makeNode(FuncExpr);
2696 newexpr->funcid = expr->funcid;
2697 newexpr->funcresulttype = expr->funcresulttype;
2698 newexpr->funcretset = expr->funcretset;
2699 newexpr->funcvariadic = expr->funcvariadic;
2700 newexpr->funcformat = expr->funcformat;
2701 newexpr->funccollid = expr->funccollid;
2702 newexpr->inputcollid = expr->inputcollid;
2703 newexpr->args = args;
2704 newexpr->location = expr->location;
2705 return (Node *) newexpr;
2709 OpExpr *expr = (OpExpr *) node;
2710 List *args = expr->args;
2715 * Need to get OID of underlying function. Okay to scribble
2716 * on input to this extent.
2721 * Code for op/func reduction is pretty bulky, so split it out
2722 * as a separate function.
2724 simple = simplify_function(expr->opfuncid,
2725 expr->opresulttype, -1,
2733 if (simple) /* successfully simplified it */
2734 return (Node *) simple;
2737 * If the operator is boolean equality or inequality, we know
2738 * how to simplify cases involving one constant and one
2739 * non-constant argument.
2741 if (expr->opno == BooleanEqualOperator ||
2742 expr->opno == BooleanNotEqualOperator)
2744 simple = (Expr *) simplify_boolean_equality(expr->opno,
2746 if (simple) /* successfully simplified it */
2747 return (Node *) simple;
2751 * The expression cannot be simplified any further, so build
2752 * and return a replacement OpExpr node using the
2753 * possibly-simplified arguments.
2755 newexpr = makeNode(OpExpr);
2756 newexpr->opno = expr->opno;
2757 newexpr->opfuncid = expr->opfuncid;
2758 newexpr->opresulttype = expr->opresulttype;
2759 newexpr->opretset = expr->opretset;
2760 newexpr->opcollid = expr->opcollid;
2761 newexpr->inputcollid = expr->inputcollid;
2762 newexpr->args = args;
2763 newexpr->location = expr->location;
2764 return (Node *) newexpr;
2766 case T_DistinctExpr:
2768 DistinctExpr *expr = (DistinctExpr *) node;
2771 bool has_null_input = false;
2772 bool all_null_input = true;
2773 bool has_nonconst_input = false;
2775 DistinctExpr *newexpr;
2778 * Reduce constants in the DistinctExpr's arguments. We know
2779 * args is either NIL or a List node, so we can call
2780 * expression_tree_mutator directly rather than recursing to
2783 args = (List *) expression_tree_mutator((Node *) expr->args,
2784 eval_const_expressions_mutator,
2788 * We must do our own check for NULLs because DistinctExpr has
2789 * different results for NULL input than the underlying
2794 if (IsA(lfirst(arg), Const))
2796 has_null_input |= ((Const *) lfirst(arg))->constisnull;
2797 all_null_input &= ((Const *) lfirst(arg))->constisnull;
2800 has_nonconst_input = true;
2803 /* all constants? then can optimize this out */
2804 if (!has_nonconst_input)
2806 /* all nulls? then not distinct */
2808 return makeBoolConst(false, false);
2810 /* one null? then distinct */
2812 return makeBoolConst(true, false);
2814 /* otherwise try to evaluate the '=' operator */
2815 /* (NOT okay to try to inline it, though!) */
2818 * Need to get OID of underlying function. Okay to
2819 * scribble on input to this extent.
2821 set_opfuncid((OpExpr *) expr); /* rely on struct
2825 * Code for op/func reduction is pretty bulky, so split it
2826 * out as a separate function.
2828 simple = simplify_function(expr->opfuncid,
2829 expr->opresulttype, -1,
2837 if (simple) /* successfully simplified it */
2840 * Since the underlying operator is "=", must negate
2843 Const *csimple = castNode(Const, simple);
2845 csimple->constvalue =
2846 BoolGetDatum(!DatumGetBool(csimple->constvalue));
2847 return (Node *) csimple;
2852 * The expression cannot be simplified any further, so build
2853 * and return a replacement DistinctExpr node using the
2854 * possibly-simplified arguments.
2856 newexpr = makeNode(DistinctExpr);
2857 newexpr->opno = expr->opno;
2858 newexpr->opfuncid = expr->opfuncid;
2859 newexpr->opresulttype = expr->opresulttype;
2860 newexpr->opretset = expr->opretset;
2861 newexpr->opcollid = expr->opcollid;
2862 newexpr->inputcollid = expr->inputcollid;
2863 newexpr->args = args;
2864 newexpr->location = expr->location;
2865 return (Node *) newexpr;
2867 case T_ScalarArrayOpExpr:
2869 ScalarArrayOpExpr *saop;
2871 /* Copy the node and const-simplify its arguments */
2872 saop = (ScalarArrayOpExpr *) ece_generic_processing(node);
2874 /* Make sure we know underlying function */
2875 set_sa_opfuncid(saop);
2878 * If all arguments are Consts, and it's a safe function, we
2879 * can fold to a constant
2881 if (ece_all_arguments_const(saop) &&
2882 ece_function_is_safe(saop->opfuncid, context))
2883 return ece_evaluate_expr(saop);
2884 return (Node *) saop;
2888 BoolExpr *expr = (BoolExpr *) node;
2890 switch (expr->boolop)
2895 bool haveNull = false;
2896 bool forceTrue = false;
2898 newargs = simplify_or_arguments(expr->args,
2903 return makeBoolConst(true, false);
2905 newargs = lappend(newargs,
2906 makeBoolConst(false, true));
2907 /* If all the inputs are FALSE, result is FALSE */
2909 return makeBoolConst(false, false);
2912 * If only one nonconst-or-NULL input, it's the
2915 if (list_length(newargs) == 1)
2916 return (Node *) linitial(newargs);
2917 /* Else we still need an OR node */
2918 return (Node *) make_orclause(newargs);
2923 bool haveNull = false;
2924 bool forceFalse = false;
2926 newargs = simplify_and_arguments(expr->args,
2931 return makeBoolConst(false, false);
2933 newargs = lappend(newargs,
2934 makeBoolConst(false, true));
2935 /* If all the inputs are TRUE, result is TRUE */
2937 return makeBoolConst(true, false);
2940 * If only one nonconst-or-NULL input, it's the
2943 if (list_length(newargs) == 1)
2944 return (Node *) linitial(newargs);
2945 /* Else we still need an AND node */
2946 return (Node *) make_andclause(newargs);
2952 Assert(list_length(expr->args) == 1);
2953 arg = eval_const_expressions_mutator(linitial(expr->args),
2957 * Use negate_clause() to see if we can simplify
2960 return negate_clause(arg);
2963 elog(ERROR, "unrecognized boolop: %d",
2964 (int) expr->boolop);
2970 case T_AlternativeSubPlan:
2973 * Return a SubPlan unchanged --- too late to do anything with it.
2975 * XXX should we ereport() here instead? Probably this routine
2976 * should never be invoked after SubPlan creation.
2982 * If we can simplify the input to a constant, then we don't
2983 * need the RelabelType node anymore: just change the type
2984 * field of the Const node. Otherwise, must copy the
2987 RelabelType *relabel = (RelabelType *) node;
2990 arg = eval_const_expressions_mutator((Node *) relabel->arg,
2994 * If we find stacked RelabelTypes (eg, from foo :: int ::
2995 * oid) we can discard all but the top one.
2997 while (arg && IsA(arg, RelabelType))
2998 arg = (Node *) ((RelabelType *) arg)->arg;
3000 if (arg && IsA(arg, Const))
3002 Const *con = (Const *) arg;
3004 con->consttype = relabel->resulttype;
3005 con->consttypmod = relabel->resulttypmod;
3006 con->constcollid = relabel->resultcollid;
3007 return (Node *) con;
3011 RelabelType *newrelabel = makeNode(RelabelType);
3013 newrelabel->arg = (Expr *) arg;
3014 newrelabel->resulttype = relabel->resulttype;
3015 newrelabel->resulttypmod = relabel->resulttypmod;
3016 newrelabel->resultcollid = relabel->resultcollid;
3017 newrelabel->relabelformat = relabel->relabelformat;
3018 newrelabel->location = relabel->location;
3019 return (Node *) newrelabel;
3024 CoerceViaIO *expr = (CoerceViaIO *) node;
3027 bool outtypisvarlena;
3031 CoerceViaIO *newexpr;
3033 /* Make a List so we can use simplify_function */
3034 args = list_make1(expr->arg);
3037 * CoerceViaIO represents calling the source type's output
3038 * function then the result type's input function. So, try to
3039 * simplify it as though it were a stack of two such function
3040 * calls. First we need to know what the functions are.
3042 * Note that the coercion functions are assumed not to care
3043 * about input collation, so we just pass InvalidOid for that.
3045 getTypeOutputInfo(exprType((Node *) expr->arg),
3046 &outfunc, &outtypisvarlena);
3047 getTypeInputInfo(expr->resulttype,
3048 &infunc, &intypioparam);
3050 simple = simplify_function(outfunc,
3059 if (simple) /* successfully simplified output fn */
3062 * Input functions may want 1 to 3 arguments. We always
3063 * supply all three, trusting that nothing downstream will
3066 args = list_make3(simple,
3071 ObjectIdGetDatum(intypioparam),
3082 simple = simplify_function(infunc,
3083 expr->resulttype, -1,
3091 if (simple) /* successfully simplified input fn */
3092 return (Node *) simple;
3096 * The expression cannot be simplified any further, so build
3097 * and return a replacement CoerceViaIO node using the
3098 * possibly-simplified argument.
3100 newexpr = makeNode(CoerceViaIO);
3101 newexpr->arg = (Expr *) linitial(args);
3102 newexpr->resulttype = expr->resulttype;
3103 newexpr->resultcollid = expr->resultcollid;
3104 newexpr->coerceformat = expr->coerceformat;
3105 newexpr->location = expr->location;
3106 return (Node *) newexpr;
3108 case T_ArrayCoerceExpr:
3110 ArrayCoerceExpr *ac;
3112 /* Copy the node and const-simplify its arguments */
3113 ac = (ArrayCoerceExpr *) ece_generic_processing(node);
3116 * If constant argument and the per-element expression is
3117 * immutable, we can simplify the whole thing to a constant.
3118 * Exception: although contain_mutable_functions considers
3119 * CoerceToDomain immutable for historical reasons, let's not
3120 * do so here; this ensures coercion to an array-over-domain
3121 * does not apply the domain's constraints until runtime.
3123 if (ac->arg && IsA(ac->arg, Const) &&
3124 ac->elemexpr && !IsA(ac->elemexpr, CoerceToDomain) &&
3125 !contain_mutable_functions((Node *) ac->elemexpr))
3126 return ece_evaluate_expr(ac);
3132 * If we can simplify the input to a constant, then we don't
3133 * need the CollateExpr node at all: just change the
3134 * constcollid field of the Const node. Otherwise, replace
3135 * the CollateExpr with a RelabelType. (We do that so as to
3136 * improve uniformity of expression representation and thus
3137 * simplify comparison of expressions.)
3139 CollateExpr *collate = (CollateExpr *) node;
3142 arg = eval_const_expressions_mutator((Node *) collate->arg,
3145 if (arg && IsA(arg, Const))
3147 Const *con = (Const *) arg;
3149 con->constcollid = collate->collOid;
3150 return (Node *) con;
3152 else if (collate->collOid == exprCollation(arg))
3154 /* Don't need a RelabelType either... */
3159 RelabelType *relabel = makeNode(RelabelType);
3161 relabel->resulttype = exprType(arg);
3162 relabel->resulttypmod = exprTypmod(arg);
3163 relabel->resultcollid = collate->collOid;
3164 relabel->relabelformat = COERCE_IMPLICIT_CAST;
3165 relabel->location = collate->location;
3167 /* Don't create stacked RelabelTypes */
3168 while (arg && IsA(arg, RelabelType))
3169 arg = (Node *) ((RelabelType *) arg)->arg;
3170 relabel->arg = (Expr *) arg;
3172 return (Node *) relabel;
3178 * CASE expressions can be simplified if there are constant
3179 * condition clauses:
3180 * FALSE (or NULL): drop the alternative
3181 * TRUE: drop all remaining alternatives
3182 * If the first non-FALSE alternative is a constant TRUE,
3183 * we can simplify the entire CASE to that alternative's
3184 * expression. If there are no non-FALSE alternatives,
3185 * we simplify the entire CASE to the default result (ELSE).
3187 * If we have a simple-form CASE with constant test
3188 * expression, we substitute the constant value for contained
3189 * CaseTestExpr placeholder nodes, so that we have the
3190 * opportunity to reduce constant test conditions. For
3191 * example this allows
3192 * CASE 0 WHEN 0 THEN 1 ELSE 1/0 END
3193 * to reduce to 1 rather than drawing a divide-by-0 error.
3194 * Note that when the test expression is constant, we don't
3195 * have to include it in the resulting CASE; for example
3196 * CASE 0 WHEN x THEN y ELSE z END
3197 * is transformed by the parser to
3198 * CASE 0 WHEN CaseTestExpr = x THEN y ELSE z END
3199 * which we can simplify to
3200 * CASE WHEN 0 = x THEN y ELSE z END
3201 * It is not necessary for the executor to evaluate the "arg"
3202 * expression when executing the CASE, since any contained
3203 * CaseTestExprs that might have referred to it will have been
3204 * replaced by the constant.
3207 CaseExpr *caseexpr = (CaseExpr *) node;
3209 Node *save_case_val;
3212 bool const_true_cond;
3213 Node *defresult = NULL;
3216 /* Simplify the test expression, if any */
3217 newarg = eval_const_expressions_mutator((Node *) caseexpr->arg,
3220 /* Set up for contained CaseTestExpr nodes */
3221 save_case_val = context->case_val;
3222 if (newarg && IsA(newarg, Const))
3224 context->case_val = newarg;
3225 newarg = NULL; /* not needed anymore, see above */
3228 context->case_val = NULL;
3230 /* Simplify the WHEN clauses */
3232 const_true_cond = false;
3233 foreach(arg, caseexpr->args)
3235 CaseWhen *oldcasewhen = lfirst_node(CaseWhen, arg);
3239 /* Simplify this alternative's test condition */
3240 casecond = eval_const_expressions_mutator((Node *) oldcasewhen->expr,
3244 * If the test condition is constant FALSE (or NULL), then
3245 * drop this WHEN clause completely, without processing
3248 if (casecond && IsA(casecond, Const))
3250 Const *const_input = (Const *) casecond;
3252 if (const_input->constisnull ||
3253 !DatumGetBool(const_input->constvalue))
3254 continue; /* drop alternative with FALSE cond */
3255 /* Else it's constant TRUE */
3256 const_true_cond = true;
3259 /* Simplify this alternative's result value */
3260 caseresult = eval_const_expressions_mutator((Node *) oldcasewhen->result,
3263 /* If non-constant test condition, emit a new WHEN node */
3264 if (!const_true_cond)
3266 CaseWhen *newcasewhen = makeNode(CaseWhen);
3268 newcasewhen->expr = (Expr *) casecond;
3269 newcasewhen->result = (Expr *) caseresult;
3270 newcasewhen->location = oldcasewhen->location;
3271 newargs = lappend(newargs, newcasewhen);
3276 * Found a TRUE condition, so none of the remaining
3277 * alternatives can be reached. We treat the result as
3278 * the default result.
3280 defresult = caseresult;
3284 /* Simplify the default result, unless we replaced it above */
3285 if (!const_true_cond)
3286 defresult = eval_const_expressions_mutator((Node *) caseexpr->defresult,
3289 context->case_val = save_case_val;
3292 * If no non-FALSE alternatives, CASE reduces to the default
3297 /* Otherwise we need a new CASE node */
3298 newcase = makeNode(CaseExpr);
3299 newcase->casetype = caseexpr->casetype;
3300 newcase->casecollid = caseexpr->casecollid;
3301 newcase->arg = (Expr *) newarg;
3302 newcase->args = newargs;
3303 newcase->defresult = (Expr *) defresult;
3304 newcase->location = caseexpr->location;
3305 return (Node *) newcase;
3307 case T_CaseTestExpr:
3310 * If we know a constant test value for the current CASE
3311 * construct, substitute it for the placeholder. Else just
3312 * return the placeholder as-is.
3314 if (context->case_val)
3315 return copyObject(context->case_val);
3317 return copyObject(node);
3324 * Generic handling for node types whose own processing is
3325 * known to be immutable, and for which we need no smarts
3326 * beyond "simplify if all inputs are constants".
3329 /* Copy the node and const-simplify its arguments */
3330 node = ece_generic_processing(node);
3331 /* If all arguments are Consts, we can fold to a constant */
3332 if (ece_all_arguments_const(node))
3333 return ece_evaluate_expr(node);
3336 case T_CoalesceExpr:
3338 CoalesceExpr *coalesceexpr = (CoalesceExpr *) node;
3339 CoalesceExpr *newcoalesce;
3344 foreach(arg, coalesceexpr->args)
3348 e = eval_const_expressions_mutator((Node *) lfirst(arg),
3352 * We can remove null constants from the list. For a
3353 * non-null constant, if it has not been preceded by any
3354 * other non-null-constant expressions then it is the
3355 * result. Otherwise, it's the next argument, but we can
3356 * drop following arguments since they will never be
3361 if (((Const *) e)->constisnull)
3362 continue; /* drop null constant */
3364 return e; /* first expr */
3365 newargs = lappend(newargs, e);
3368 newargs = lappend(newargs, e);
3372 * If all the arguments were constant null, the result is just
3376 return (Node *) makeNullConst(coalesceexpr->coalescetype,
3378 coalesceexpr->coalescecollid);
3380 newcoalesce = makeNode(CoalesceExpr);
3381 newcoalesce->coalescetype = coalesceexpr->coalescetype;
3382 newcoalesce->coalescecollid = coalesceexpr->coalescecollid;
3383 newcoalesce->args = newargs;
3384 newcoalesce->location = coalesceexpr->location;
3385 return (Node *) newcoalesce;
3387 case T_SQLValueFunction:
3390 * All variants of SQLValueFunction are stable, so if we are
3391 * estimating the expression's value, we should evaluate the
3392 * current function value. Otherwise just copy.
3394 SQLValueFunction *svf = (SQLValueFunction *) node;
3396 if (context->estimate)
3397 return (Node *) evaluate_expr((Expr *) svf,
3402 return copyObject((Node *) svf);
3407 * We can optimize field selection from a whole-row Var into a
3408 * simple Var. (This case won't be generated directly by the
3409 * parser, because ParseComplexProjection short-circuits it.
3410 * But it can arise while simplifying functions.) Also, we
3411 * can optimize field selection from a RowExpr construct, or
3412 * of course from a constant.
3414 * However, replacing a whole-row Var in this way has a
3415 * pitfall: if we've already built the rel targetlist for the
3416 * source relation, then the whole-row Var is scheduled to be
3417 * produced by the relation scan, but the simple Var probably
3418 * isn't, which will lead to a failure in setrefs.c. This is
3419 * not a problem when handling simple single-level queries, in
3420 * which expression simplification always happens first. It
3421 * is a risk for lateral references from subqueries, though.
3422 * To avoid such failures, don't optimize uplevel references.
3424 * We must also check that the declared type of the field is
3425 * still the same as when the FieldSelect was created --- this
3426 * can change if someone did ALTER COLUMN TYPE on the rowtype.
3427 * If it isn't, we skip the optimization; the case will
3428 * probably fail at runtime, but that's not our problem here.
3430 FieldSelect *fselect = (FieldSelect *) node;
3431 FieldSelect *newfselect;
3434 arg = eval_const_expressions_mutator((Node *) fselect->arg,
3436 if (arg && IsA(arg, Var) &&
3437 ((Var *) arg)->varattno == InvalidAttrNumber &&
3438 ((Var *) arg)->varlevelsup == 0)
3440 if (rowtype_field_matches(((Var *) arg)->vartype,
3442 fselect->resulttype,
3443 fselect->resulttypmod,
3444 fselect->resultcollid))
3445 return (Node *) makeVar(((Var *) arg)->varno,
3447 fselect->resulttype,
3448 fselect->resulttypmod,
3449 fselect->resultcollid,
3450 ((Var *) arg)->varlevelsup);
3452 if (arg && IsA(arg, RowExpr))
3454 RowExpr *rowexpr = (RowExpr *) arg;
3456 if (fselect->fieldnum > 0 &&
3457 fselect->fieldnum <= list_length(rowexpr->args))
3459 Node *fld = (Node *) list_nth(rowexpr->args,
3460 fselect->fieldnum - 1);
3462 if (rowtype_field_matches(rowexpr->row_typeid,
3464 fselect->resulttype,
3465 fselect->resulttypmod,
3466 fselect->resultcollid) &&
3467 fselect->resulttype == exprType(fld) &&
3468 fselect->resulttypmod == exprTypmod(fld) &&
3469 fselect->resultcollid == exprCollation(fld))
3473 newfselect = makeNode(FieldSelect);
3474 newfselect->arg = (Expr *) arg;
3475 newfselect->fieldnum = fselect->fieldnum;
3476 newfselect->resulttype = fselect->resulttype;
3477 newfselect->resulttypmod = fselect->resulttypmod;
3478 newfselect->resultcollid = fselect->resultcollid;
3479 if (arg && IsA(arg, Const))
3481 Const *con = (Const *) arg;
3483 if (rowtype_field_matches(con->consttype,
3484 newfselect->fieldnum,
3485 newfselect->resulttype,
3486 newfselect->resulttypmod,
3487 newfselect->resultcollid))
3488 return ece_evaluate_expr(newfselect);
3490 return (Node *) newfselect;
3494 NullTest *ntest = (NullTest *) node;
3498 arg = eval_const_expressions_mutator((Node *) ntest->arg,
3500 if (ntest->argisrow && arg && IsA(arg, RowExpr))
3503 * We break ROW(...) IS [NOT] NULL into separate tests on
3504 * its component fields. This form is usually more
3505 * efficient to evaluate, as well as being more amenable
3508 RowExpr *rarg = (RowExpr *) arg;
3509 List *newargs = NIL;
3512 foreach(l, rarg->args)
3514 Node *relem = (Node *) lfirst(l);
3517 * A constant field refutes the whole NullTest if it's
3518 * of the wrong nullness; else we can discard it.
3520 if (relem && IsA(relem, Const))
3522 Const *carg = (Const *) relem;
3524 if (carg->constisnull ?
3525 (ntest->nulltesttype == IS_NOT_NULL) :
3526 (ntest->nulltesttype == IS_NULL))
3527 return makeBoolConst(false, false);
3532 * Else, make a scalar (argisrow == false) NullTest
3533 * for this field. Scalar semantics are required
3534 * because IS [NOT] NULL doesn't recurse; see comments
3535 * in ExecEvalRowNullInt().
3537 newntest = makeNode(NullTest);
3538 newntest->arg = (Expr *) relem;
3539 newntest->nulltesttype = ntest->nulltesttype;
3540 newntest->argisrow = false;
3541 newntest->location = ntest->location;
3542 newargs = lappend(newargs, newntest);
3544 /* If all the inputs were constants, result is TRUE */
3546 return makeBoolConst(true, false);
3547 /* If only one nonconst input, it's the result */
3548 if (list_length(newargs) == 1)
3549 return (Node *) linitial(newargs);
3550 /* Else we need an AND node */
3551 return (Node *) make_andclause(newargs);
3553 if (!ntest->argisrow && arg && IsA(arg, Const))
3555 Const *carg = (Const *) arg;
3558 switch (ntest->nulltesttype)
3561 result = carg->constisnull;
3564 result = !carg->constisnull;
3567 elog(ERROR, "unrecognized nulltesttype: %d",
3568 (int) ntest->nulltesttype);
3569 result = false; /* keep compiler quiet */
3573 return makeBoolConst(result, false);
3576 newntest = makeNode(NullTest);
3577 newntest->arg = (Expr *) arg;
3578 newntest->nulltesttype = ntest->nulltesttype;
3579 newntest->argisrow = ntest->argisrow;
3580 newntest->location = ntest->location;
3581 return (Node *) newntest;
3586 * This case could be folded into the generic handling used
3587 * for ArrayRef etc. But because the simplification logic is
3588 * so trivial, applying evaluate_expr() to perform it would be
3589 * a heavy overhead. BooleanTest is probably common enough to
3590 * justify keeping this bespoke implementation.
3592 BooleanTest *btest = (BooleanTest *) node;
3593 BooleanTest *newbtest;
3596 arg = eval_const_expressions_mutator((Node *) btest->arg,
3598 if (arg && IsA(arg, Const))
3600 Const *carg = (Const *) arg;
3603 switch (btest->booltesttype)
3606 result = (!carg->constisnull &&
3607 DatumGetBool(carg->constvalue));
3610 result = (carg->constisnull ||
3611 !DatumGetBool(carg->constvalue));
3614 result = (!carg->constisnull &&
3615 !DatumGetBool(carg->constvalue));
3618 result = (carg->constisnull ||
3619 DatumGetBool(carg->constvalue));
3622 result = carg->constisnull;
3624 case IS_NOT_UNKNOWN:
3625 result = !carg->constisnull;
3628 elog(ERROR, "unrecognized booltesttype: %d",
3629 (int) btest->booltesttype);
3630 result = false; /* keep compiler quiet */
3634 return makeBoolConst(result, false);
3637 newbtest = makeNode(BooleanTest);
3638 newbtest->arg = (Expr *) arg;
3639 newbtest->booltesttype = btest->booltesttype;
3640 newbtest->location = btest->location;
3641 return (Node *) newbtest;
3643 case T_PlaceHolderVar:
3646 * In estimation mode, just strip the PlaceHolderVar node
3647 * altogether; this amounts to estimating that the contained value
3648 * won't be forced to null by an outer join. In regular mode we
3649 * just use the default behavior (ie, simplify the expression but
3650 * leave the PlaceHolderVar node intact).
3652 if (context->estimate)
3654 PlaceHolderVar *phv = (PlaceHolderVar *) node;
3656 return eval_const_expressions_mutator((Node *) phv->phexpr,
3665 * For any node type not handled above, copy the node unchanged but
3666 * const-simplify its subexpressions. This is the correct thing for node
3667 * types whose behavior might change between planning and execution, such
3668 * as CoerceToDomain. It's also a safe default for new node types not
3669 * known to this routine.
3671 return ece_generic_processing(node);
3675 * Subroutine for eval_const_expressions: check for non-Const nodes.
3677 * We can abort recursion immediately on finding a non-Const node. This is
3678 * critical for performance, else eval_const_expressions_mutator would take
3679 * O(N^2) time on non-simplifiable trees. However, we do need to descend
3680 * into List nodes since expression_tree_walker sometimes invokes the walker
3681 * function directly on List subtrees.
3684 contain_non_const_walker(Node *node, void *context)
3688 if (IsA(node, Const))
3690 if (IsA(node, List))
3691 return expression_tree_walker(node, contain_non_const_walker, context);
3692 /* Otherwise, abort the tree traversal and return true */
3697 * Subroutine for eval_const_expressions: check if a function is OK to evaluate
3700 ece_function_is_safe(Oid funcid, eval_const_expressions_context *context)
3702 char provolatile = func_volatile(funcid);
3705 * Ordinarily we are only allowed to simplify immutable functions. But for
3706 * purposes of estimation, we consider it okay to simplify functions that
3707 * are merely stable; the risk that the result might change from planning
3708 * time to execution time is worth taking in preference to not being able
3709 * to estimate the value at all.
3711 if (provolatile == PROVOLATILE_IMMUTABLE)
3713 if (context->estimate && provolatile == PROVOLATILE_STABLE)
3719 * Subroutine for eval_const_expressions: process arguments of an OR clause
3721 * This includes flattening of nested ORs as well as recursion to
3722 * eval_const_expressions to simplify the OR arguments.
3724 * After simplification, OR arguments are handled as follows:
3725 * non constant: keep
3726 * FALSE: drop (does not affect result)
3727 * TRUE: force result to TRUE
3728 * NULL: keep only one
3729 * We must keep one NULL input because OR expressions evaluate to NULL when no
3730 * input is TRUE and at least one is NULL. We don't actually include the NULL
3731 * here, that's supposed to be done by the caller.
3733 * The output arguments *haveNull and *forceTrue must be initialized false
3734 * by the caller. They will be set true if a NULL constant or TRUE constant,
3735 * respectively, is detected anywhere in the argument list.
3738 simplify_or_arguments(List *args,
3739 eval_const_expressions_context *context,
3740 bool *haveNull, bool *forceTrue)
3742 List *newargs = NIL;
3743 List *unprocessed_args;
3746 * We want to ensure that any OR immediately beneath another OR gets
3747 * flattened into a single OR-list, so as to simplify later reasoning.
3749 * To avoid stack overflow from recursion of eval_const_expressions, we
3750 * resort to some tenseness here: we keep a list of not-yet-processed
3751 * inputs, and handle flattening of nested ORs by prepending to the to-do
3752 * list instead of recursing. Now that the parser generates N-argument
3753 * ORs from simple lists, this complexity is probably less necessary than
3754 * it once was, but we might as well keep the logic.
3756 unprocessed_args = list_copy(args);
3757 while (unprocessed_args)
3759 Node *arg = (Node *) linitial(unprocessed_args);
3761 unprocessed_args = list_delete_first(unprocessed_args);
3763 /* flatten nested ORs as per above comment */
3766 List *subargs = list_copy(((BoolExpr *) arg)->args);
3768 /* overly tense code to avoid leaking unused list header */
3769 if (!unprocessed_args)
3770 unprocessed_args = subargs;
3773 List *oldhdr = unprocessed_args;
3775 unprocessed_args = list_concat(subargs, unprocessed_args);
3781 /* If it's not an OR, simplify it */
3782 arg = eval_const_expressions_mutator(arg, context);
3785 * It is unlikely but not impossible for simplification of a non-OR
3786 * clause to produce an OR. Recheck, but don't be too tense about it
3787 * since it's not a mainstream case. In particular we don't worry
3788 * about const-simplifying the input twice.
3792 List *subargs = list_copy(((BoolExpr *) arg)->args);
3794 unprocessed_args = list_concat(subargs, unprocessed_args);
3799 * OK, we have a const-simplified non-OR argument. Process it per
3802 if (IsA(arg, Const))
3804 Const *const_input = (Const *) arg;
3806 if (const_input->constisnull)
3808 else if (DatumGetBool(const_input->constvalue))
3813 * Once we detect a TRUE result we can just exit the loop
3814 * immediately. However, if we ever add a notion of
3815 * non-removable functions, we'd need to keep scanning.
3819 /* otherwise, we can drop the constant-false input */
3823 /* else emit the simplified arg into the result list */
3824 newargs = lappend(newargs, arg);
3831 * Subroutine for eval_const_expressions: process arguments of an AND clause
3833 * This includes flattening of nested ANDs as well as recursion to
3834 * eval_const_expressions to simplify the AND arguments.
3836 * After simplification, AND arguments are handled as follows:
3837 * non constant: keep
3838 * TRUE: drop (does not affect result)
3839 * FALSE: force result to FALSE
3840 * NULL: keep only one
3841 * We must keep one NULL input because AND expressions evaluate to NULL when
3842 * no input is FALSE and at least one is NULL. We don't actually include the
3843 * NULL here, that's supposed to be done by the caller.
3845 * The output arguments *haveNull and *forceFalse must be initialized false
3846 * by the caller. They will be set true if a null constant or false constant,
3847 * respectively, is detected anywhere in the argument list.
3850 simplify_and_arguments(List *args,
3851 eval_const_expressions_context *context,
3852 bool *haveNull, bool *forceFalse)
3854 List *newargs = NIL;
3855 List *unprocessed_args;
3857 /* See comments in simplify_or_arguments */
3858 unprocessed_args = list_copy(args);
3859 while (unprocessed_args)
3861 Node *arg = (Node *) linitial(unprocessed_args);
3863 unprocessed_args = list_delete_first(unprocessed_args);
3865 /* flatten nested ANDs as per above comment */
3866 if (and_clause(arg))
3868 List *subargs = list_copy(((BoolExpr *) arg)->args);
3870 /* overly tense code to avoid leaking unused list header */
3871 if (!unprocessed_args)
3872 unprocessed_args = subargs;
3875 List *oldhdr = unprocessed_args;
3877 unprocessed_args = list_concat(subargs, unprocessed_args);
3883 /* If it's not an AND, simplify it */
3884 arg = eval_const_expressions_mutator(arg, context);
3887 * It is unlikely but not impossible for simplification of a non-AND
3888 * clause to produce an AND. Recheck, but don't be too tense about it
3889 * since it's not a mainstream case. In particular we don't worry
3890 * about const-simplifying the input twice.
3892 if (and_clause(arg))
3894 List *subargs = list_copy(((BoolExpr *) arg)->args);
3896 unprocessed_args = list_concat(subargs, unprocessed_args);
3901 * OK, we have a const-simplified non-AND argument. Process it per
3904 if (IsA(arg, Const))
3906 Const *const_input = (Const *) arg;
3908 if (const_input->constisnull)
3910 else if (!DatumGetBool(const_input->constvalue))
3915 * Once we detect a FALSE result we can just exit the loop
3916 * immediately. However, if we ever add a notion of
3917 * non-removable functions, we'd need to keep scanning.
3921 /* otherwise, we can drop the constant-true input */
3925 /* else emit the simplified arg into the result list */
3926 newargs = lappend(newargs, arg);
3933 * Subroutine for eval_const_expressions: try to simplify boolean equality
3934 * or inequality condition
3936 * Inputs are the operator OID and the simplified arguments to the operator.
3937 * Returns a simplified expression if successful, or NULL if cannot
3938 * simplify the expression.
3940 * The idea here is to reduce "x = true" to "x" and "x = false" to "NOT x",
3941 * or similarly "x <> true" to "NOT x" and "x <> false" to "x".
3942 * This is only marginally useful in itself, but doing it in constant folding
3943 * ensures that we will recognize these forms as being equivalent in, for
3944 * example, partial index matching.
3946 * We come here only if simplify_function has failed; therefore we cannot
3947 * see two constant inputs, nor a constant-NULL input.
3950 simplify_boolean_equality(Oid opno, List *args)
3955 Assert(list_length(args) == 2);
3956 leftop = linitial(args);
3957 rightop = lsecond(args);
3958 if (leftop && IsA(leftop, Const))
3960 Assert(!((Const *) leftop)->constisnull);
3961 if (opno == BooleanEqualOperator)
3963 if (DatumGetBool(((Const *) leftop)->constvalue))
3964 return rightop; /* true = foo */
3966 return negate_clause(rightop); /* false = foo */
3970 if (DatumGetBool(((Const *) leftop)->constvalue))
3971 return negate_clause(rightop); /* true <> foo */
3973 return rightop; /* false <> foo */
3976 if (rightop && IsA(rightop, Const))
3978 Assert(!((Const *) rightop)->constisnull);
3979 if (opno == BooleanEqualOperator)
3981 if (DatumGetBool(((Const *) rightop)->constvalue))
3982 return leftop; /* foo = true */
3984 return negate_clause(leftop); /* foo = false */
3988 if (DatumGetBool(((Const *) rightop)->constvalue))
3989 return negate_clause(leftop); /* foo <> true */
3991 return leftop; /* foo <> false */
3998 * Subroutine for eval_const_expressions: try to simplify a function call
3999 * (which might originally have been an operator; we don't care)
4001 * Inputs are the function OID, actual result type OID (which is needed for
4002 * polymorphic functions), result typmod, result collation, the input
4003 * collation to use for the function, the original argument list (not
4004 * const-simplified yet, unless process_args is false), and some flags;
4005 * also the context data for eval_const_expressions.
4007 * Returns a simplified expression if successful, or NULL if cannot
4008 * simplify the function call.
4010 * This function is also responsible for converting named-notation argument
4011 * lists into positional notation and/or adding any needed default argument
4012 * expressions; which is a bit grotty, but it avoids extra fetches of the
4013 * function's pg_proc tuple. For this reason, the args list is
4014 * pass-by-reference. Conversion and const-simplification of the args list
4015 * will be done even if simplification of the function call itself is not
4019 simplify_function(Oid funcid, Oid result_type, int32 result_typmod,
4020 Oid result_collid, Oid input_collid, List **args_p,
4021 bool funcvariadic, bool process_args, bool allow_non_const,
4022 eval_const_expressions_context *context)
4024 List *args = *args_p;
4025 HeapTuple func_tuple;
4026 Form_pg_proc func_form;
4030 * We have three strategies for simplification: execute the function to
4031 * deliver a constant result, use a transform function to generate a
4032 * substitute node tree, or expand in-line the body of the function
4033 * definition (which only works for simple SQL-language functions, but
4034 * that is a common case). Each case needs access to the function's
4035 * pg_proc tuple, so fetch it just once.
4037 * Note: the allow_non_const flag suppresses both the second and third
4038 * strategies; so if !allow_non_const, simplify_function can only return a
4039 * Const or NULL. Argument-list rewriting happens anyway, though.
4041 func_tuple = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcid));
4042 if (!HeapTupleIsValid(func_tuple))
4043 elog(ERROR, "cache lookup failed for function %u", funcid);
4044 func_form = (Form_pg_proc) GETSTRUCT(func_tuple);
4047 * Process the function arguments, unless the caller did it already.
4049 * Here we must deal with named or defaulted arguments, and then
4050 * recursively apply eval_const_expressions to the whole argument list.
4054 args = expand_function_arguments(args, result_type, func_tuple);
4055 args = (List *) expression_tree_mutator((Node *) args,
4056 eval_const_expressions_mutator,
4058 /* Argument processing done, give it back to the caller */
4062 /* Now attempt simplification of the function call proper. */
4064 newexpr = evaluate_function(funcid, result_type, result_typmod,
4065 result_collid, input_collid,
4067 func_tuple, context);
4069 if (!newexpr && allow_non_const && OidIsValid(func_form->protransform))
4072 * Build a dummy FuncExpr node containing the simplified arg list. We
4073 * use this approach to present a uniform interface to the transform
4074 * function regardless of how the function is actually being invoked.
4078 fexpr.xpr.type = T_FuncExpr;
4079 fexpr.funcid = funcid;
4080 fexpr.funcresulttype = result_type;
4081 fexpr.funcretset = func_form->proretset;
4082 fexpr.funcvariadic = funcvariadic;
4083 fexpr.funcformat = COERCE_EXPLICIT_CALL;
4084 fexpr.funccollid = result_collid;
4085 fexpr.inputcollid = input_collid;
4087 fexpr.location = -1;
4090 DatumGetPointer(OidFunctionCall1(func_form->protransform,
4091 PointerGetDatum(&fexpr)));
4094 if (!newexpr && allow_non_const)
4095 newexpr = inline_function(funcid, result_type, result_collid,
4096 input_collid, args, funcvariadic,
4097 func_tuple, context);
4099 ReleaseSysCache(func_tuple);
4105 * expand_function_arguments: convert named-notation args to positional args
4106 * and/or insert default args, as needed
4108 * If we need to change anything, the input argument list is copied, not
4111 * Note: this gets applied to operator argument lists too, even though the
4112 * cases it handles should never occur there. This should be OK since it
4113 * will fall through very quickly if there's nothing to do.
4116 expand_function_arguments(List *args, Oid result_type, HeapTuple func_tuple)
4118 Form_pg_proc funcform = (Form_pg_proc) GETSTRUCT(func_tuple);
4119 bool has_named_args = false;
4122 /* Do we have any named arguments? */
4125 Node *arg = (Node *) lfirst(lc);
4127 if (IsA(arg, NamedArgExpr))
4129 has_named_args = true;
4134 /* If so, we must apply reorder_function_arguments */
4137 args = reorder_function_arguments(args, func_tuple);
4138 /* Recheck argument types and add casts if needed */
4139 recheck_cast_function_args(args, result_type, func_tuple);
4141 else if (list_length(args) < funcform->pronargs)
4143 /* No named args, but we seem to be short some defaults */
4144 args = add_function_defaults(args, func_tuple);
4145 /* Recheck argument types and add casts if needed */
4146 recheck_cast_function_args(args, result_type, func_tuple);
4153 * reorder_function_arguments: convert named-notation args to positional args
4155 * This function also inserts default argument values as needed, since it's
4156 * impossible to form a truly valid positional call without that.
4159 reorder_function_arguments(List *args, HeapTuple func_tuple)
4161 Form_pg_proc funcform = (Form_pg_proc) GETSTRUCT(func_tuple);
4162 int pronargs = funcform->pronargs;
4163 int nargsprovided = list_length(args);
4164 Node *argarray[FUNC_MAX_ARGS];
4168 Assert(nargsprovided <= pronargs);
4169 if (pronargs > FUNC_MAX_ARGS)
4170 elog(ERROR, "too many function arguments");
4171 MemSet(argarray, 0, pronargs * sizeof(Node *));
4173 /* Deconstruct the argument list into an array indexed by argnumber */
4177 Node *arg = (Node *) lfirst(lc);
4179 if (!IsA(arg, NamedArgExpr))
4181 /* positional argument, assumed to precede all named args */
4182 Assert(argarray[i] == NULL);
4183 argarray[i++] = arg;
4187 NamedArgExpr *na = (NamedArgExpr *) arg;
4189 Assert(argarray[na->argnumber] == NULL);
4190 argarray[na->argnumber] = (Node *) na->arg;
4195 * Fetch default expressions, if needed, and insert into array at proper
4196 * locations (they aren't necessarily consecutive or all used)
4198 if (nargsprovided < pronargs)
4200 List *defaults = fetch_function_defaults(func_tuple);
4202 i = pronargs - funcform->pronargdefaults;
4203 foreach(lc, defaults)
4205 if (argarray[i] == NULL)
4206 argarray[i] = (Node *) lfirst(lc);
4211 /* Now reconstruct the args list in proper order */
4213 for (i = 0; i < pronargs; i++)
4215 Assert(argarray[i] != NULL);
4216 args = lappend(args, argarray[i]);
4223 * add_function_defaults: add missing function arguments from its defaults
4225 * This is used only when the argument list was positional to begin with,
4226 * and so we know we just need to add defaults at the end.
4229 add_function_defaults(List *args, HeapTuple func_tuple)
4231 Form_pg_proc funcform = (Form_pg_proc) GETSTRUCT(func_tuple);
4232 int nargsprovided = list_length(args);
4236 /* Get all the default expressions from the pg_proc tuple */
4237 defaults = fetch_function_defaults(func_tuple);
4239 /* Delete any unused defaults from the list */
4240 ndelete = nargsprovided + list_length(defaults) - funcform->pronargs;
4242 elog(ERROR, "not enough default arguments");
4243 while (ndelete-- > 0)
4244 defaults = list_delete_first(defaults);
4246 /* And form the combined argument list, not modifying the input list */
4247 return list_concat(list_copy(args), defaults);
4251 * fetch_function_defaults: get function's default arguments as expression list
4254 fetch_function_defaults(HeapTuple func_tuple)
4257 Datum proargdefaults;
4261 /* The error cases here shouldn't happen, but check anyway */
4262 proargdefaults = SysCacheGetAttr(PROCOID, func_tuple,
4263 Anum_pg_proc_proargdefaults,
4266 elog(ERROR, "not enough default arguments");
4267 str = TextDatumGetCString(proargdefaults);
4268 defaults = castNode(List, stringToNode(str));
4274 * recheck_cast_function_args: recheck function args and typecast as needed
4275 * after adding defaults.
4277 * It is possible for some of the defaulted arguments to be polymorphic;
4278 * therefore we can't assume that the default expressions have the correct
4279 * data types already. We have to re-resolve polymorphics and do coercion
4280 * just like the parser did.
4282 * This should be a no-op if there are no polymorphic arguments,
4283 * but we do it anyway to be sure.
4285 * Note: if any casts are needed, the args list is modified in-place;
4286 * caller should have already copied the list structure.
4289 recheck_cast_function_args(List *args, Oid result_type, HeapTuple func_tuple)
4291 Form_pg_proc funcform = (Form_pg_proc) GETSTRUCT(func_tuple);
4293 Oid actual_arg_types[FUNC_MAX_ARGS];
4294 Oid declared_arg_types[FUNC_MAX_ARGS];
4298 if (list_length(args) > FUNC_MAX_ARGS)
4299 elog(ERROR, "too many function arguments");
4303 actual_arg_types[nargs++] = exprType((Node *) lfirst(lc));
4305 Assert(nargs == funcform->pronargs);
4306 memcpy(declared_arg_types, funcform->proargtypes.values,
4307 funcform->pronargs * sizeof(Oid));
4308 rettype = enforce_generic_type_consistency(actual_arg_types,
4311 funcform->prorettype,
4313 /* let's just check we got the same answer as the parser did ... */
4314 if (rettype != result_type)
4315 elog(ERROR, "function's resolved result type changed during planning");
4317 /* perform any necessary typecasting of arguments */
4318 make_fn_arguments(NULL, args, actual_arg_types, declared_arg_types);
4322 * evaluate_function: try to pre-evaluate a function call
4324 * We can do this if the function is strict and has any constant-null inputs
4325 * (just return a null constant), or if the function is immutable and has all
4326 * constant inputs (call it and return the result as a Const node). In
4327 * estimation mode we are willing to pre-evaluate stable functions too.
4329 * Returns a simplified expression if successful, or NULL if cannot
4330 * simplify the function.
4333 evaluate_function(Oid funcid, Oid result_type, int32 result_typmod,
4334 Oid result_collid, Oid input_collid, List *args,
4336 HeapTuple func_tuple,
4337 eval_const_expressions_context *context)
4339 Form_pg_proc funcform = (Form_pg_proc) GETSTRUCT(func_tuple);
4340 bool has_nonconst_input = false;
4341 bool has_null_input = false;
4346 * Can't simplify if it returns a set.
4348 if (funcform->proretset)
4352 * Can't simplify if it returns RECORD. The immediate problem is that it
4353 * will be needing an expected tupdesc which we can't supply here.
4355 * In the case where it has OUT parameters, it could get by without an
4356 * expected tupdesc, but we still have issues: get_expr_result_type()
4357 * doesn't know how to extract type info from a RECORD constant, and in
4358 * the case of a NULL function result there doesn't seem to be any clean
4359 * way to fix that. In view of the likelihood of there being still other
4360 * gotchas, seems best to leave the function call unreduced.
4362 if (funcform->prorettype == RECORDOID)
4366 * Check for constant inputs and especially constant-NULL inputs.
4370 if (IsA(lfirst(arg), Const))
4371 has_null_input |= ((Const *) lfirst(arg))->constisnull;
4373 has_nonconst_input = true;
4377 * If the function is strict and has a constant-NULL input, it will never
4378 * be called at all, so we can replace the call by a NULL constant, even
4379 * if there are other inputs that aren't constant, and even if the
4380 * function is not otherwise immutable.
4382 if (funcform->proisstrict && has_null_input)
4383 return (Expr *) makeNullConst(result_type, result_typmod,
4387 * Otherwise, can simplify only if all inputs are constants. (For a
4388 * non-strict function, constant NULL inputs are treated the same as
4389 * constant non-NULL inputs.)
4391 if (has_nonconst_input)
4395 * Ordinarily we are only allowed to simplify immutable functions. But for
4396 * purposes of estimation, we consider it okay to simplify functions that
4397 * are merely stable; the risk that the result might change from planning
4398 * time to execution time is worth taking in preference to not being able
4399 * to estimate the value at all.
4401 if (funcform->provolatile == PROVOLATILE_IMMUTABLE)
4403 else if (context->estimate && funcform->provolatile == PROVOLATILE_STABLE)
4409 * OK, looks like we can simplify this operator/function.
4411 * Build a new FuncExpr node containing the already-simplified arguments.
4413 newexpr = makeNode(FuncExpr);
4414 newexpr->funcid = funcid;
4415 newexpr->funcresulttype = result_type;
4416 newexpr->funcretset = false;
4417 newexpr->funcvariadic = funcvariadic;
4418 newexpr->funcformat = COERCE_EXPLICIT_CALL; /* doesn't matter */
4419 newexpr->funccollid = result_collid; /* doesn't matter */
4420 newexpr->inputcollid = input_collid;
4421 newexpr->args = args;
4422 newexpr->location = -1;
4424 return evaluate_expr((Expr *) newexpr, result_type, result_typmod,
4429 * inline_function: try to expand a function call inline
4431 * If the function is a sufficiently simple SQL-language function
4432 * (just "SELECT expression"), then we can inline it and avoid the rather
4433 * high per-call overhead of SQL functions. Furthermore, this can expose
4434 * opportunities for constant-folding within the function expression.
4436 * We have to beware of some special cases however. A directly or
4437 * indirectly recursive function would cause us to recurse forever,
4438 * so we keep track of which functions we are already expanding and
4439 * do not re-expand them. Also, if a parameter is used more than once
4440 * in the SQL-function body, we require it not to contain any volatile
4441 * functions (volatiles might deliver inconsistent answers) nor to be
4442 * unreasonably expensive to evaluate. The expensiveness check not only
4443 * prevents us from doing multiple evaluations of an expensive parameter
4444 * at runtime, but is a safety value to limit growth of an expression due
4445 * to repeated inlining.
4447 * We must also beware of changing the volatility or strictness status of
4448 * functions by inlining them.
4450 * Also, at the moment we can't inline functions returning RECORD. This
4451 * doesn't work in the general case because it discards information such
4452 * as OUT-parameter declarations.
4454 * Also, context-dependent expression nodes in the argument list are trouble.
4456 * Returns a simplified expression if successful, or NULL if cannot
4457 * simplify the function.
4460 inline_function(Oid funcid, Oid result_type, Oid result_collid,
4461 Oid input_collid, List *args,
4463 HeapTuple func_tuple,
4464 eval_const_expressions_context *context)
4466 Form_pg_proc funcform = (Form_pg_proc) GETSTRUCT(func_tuple);
4470 bool modifyTargetList;
4471 MemoryContext oldcxt;
4472 MemoryContext mycxt;
4473 inline_error_callback_arg callback_arg;
4474 ErrorContextCallback sqlerrcontext;
4476 SQLFunctionParseInfoPtr pinfo;
4478 List *raw_parsetree_list;
4486 * Forget it if the function is not SQL-language or has other showstopper
4487 * properties. (The prokind and nargs checks are just paranoia.)
4489 if (funcform->prolang != SQLlanguageId ||
4490 funcform->prokind != PROKIND_FUNCTION ||
4491 funcform->prosecdef ||
4492 funcform->proretset ||
4493 funcform->prorettype == RECORDOID ||
4494 !heap_attisnull(func_tuple, Anum_pg_proc_proconfig, NULL) ||
4495 funcform->pronargs != list_length(args))
4498 /* Check for recursive function, and give up trying to expand if so */
4499 if (list_member_oid(context->active_fns, funcid))
4502 /* Check permission to call function (fail later, if not) */
4503 if (pg_proc_aclcheck(funcid, GetUserId(), ACL_EXECUTE) != ACLCHECK_OK)
4506 /* Check whether a plugin wants to hook function entry/exit */
4507 if (FmgrHookIsNeeded(funcid))
4511 * Make a temporary memory context, so that we don't leak all the stuff
4512 * that parsing might create.
4514 mycxt = AllocSetContextCreate(CurrentMemoryContext,
4516 ALLOCSET_DEFAULT_SIZES);
4517 oldcxt = MemoryContextSwitchTo(mycxt);
4519 /* Fetch the function body */
4520 tmp = SysCacheGetAttr(PROCOID,
4522 Anum_pg_proc_prosrc,
4525 elog(ERROR, "null prosrc for function %u", funcid);
4526 src = TextDatumGetCString(tmp);
4529 * Setup error traceback support for ereport(). This is so that we can
4530 * finger the function that bad information came from.
4532 callback_arg.proname = NameStr(funcform->proname);
4533 callback_arg.prosrc = src;
4535 sqlerrcontext.callback = sql_inline_error_callback;
4536 sqlerrcontext.arg = (void *) &callback_arg;
4537 sqlerrcontext.previous = error_context_stack;
4538 error_context_stack = &sqlerrcontext;
4541 * Set up to handle parameters while parsing the function body. We need a
4542 * dummy FuncExpr node containing the already-simplified arguments to pass
4543 * to prepare_sql_fn_parse_info. (It is really only needed if there are
4544 * some polymorphic arguments, but for simplicity we always build it.)
4546 fexpr = makeNode(FuncExpr);
4547 fexpr->funcid = funcid;
4548 fexpr->funcresulttype = result_type;
4549 fexpr->funcretset = false;
4550 fexpr->funcvariadic = funcvariadic;
4551 fexpr->funcformat = COERCE_EXPLICIT_CALL; /* doesn't matter */
4552 fexpr->funccollid = result_collid; /* doesn't matter */
4553 fexpr->inputcollid = input_collid;
4555 fexpr->location = -1;
4557 pinfo = prepare_sql_fn_parse_info(func_tuple,
4562 * We just do parsing and parse analysis, not rewriting, because rewriting
4563 * will not affect table-free-SELECT-only queries, which is all that we
4564 * care about. Also, we can punt as soon as we detect more than one
4565 * command in the function body.
4567 raw_parsetree_list = pg_parse_query(src);
4568 if (list_length(raw_parsetree_list) != 1)
4571 pstate = make_parsestate(NULL);
4572 pstate->p_sourcetext = src;
4573 sql_fn_parser_setup(pstate, pinfo);
4575 querytree = transformTopLevelStmt(pstate, linitial(raw_parsetree_list));
4577 free_parsestate(pstate);
4580 * The single command must be a simple "SELECT expression".
4582 * Note: if you change the tests involved in this, see also plpgsql's
4583 * exec_simple_check_plan(). That generally needs to have the same idea
4584 * of what's a "simple expression", so that inlining a function that
4585 * previously wasn't inlined won't change plpgsql's conclusion.
4587 if (!IsA(querytree, Query) ||
4588 querytree->commandType != CMD_SELECT ||
4589 querytree->hasAggs ||
4590 querytree->hasWindowFuncs ||
4591 querytree->hasTargetSRFs ||
4592 querytree->hasSubLinks ||
4593 querytree->cteList ||
4594 querytree->rtable ||
4595 querytree->jointree->fromlist ||
4596 querytree->jointree->quals ||
4597 querytree->groupClause ||
4598 querytree->groupingSets ||
4599 querytree->havingQual ||
4600 querytree->windowClause ||
4601 querytree->distinctClause ||
4602 querytree->sortClause ||
4603 querytree->limitOffset ||
4604 querytree->limitCount ||
4605 querytree->setOperations ||
4606 list_length(querytree->targetList) != 1)
4610 * Make sure the function (still) returns what it's declared to. This
4611 * will raise an error if wrong, but that's okay since the function would
4612 * fail at runtime anyway. Note that check_sql_fn_retval will also insert
4613 * a RelabelType if needed to make the tlist expression match the declared
4614 * type of the function.
4616 * Note: we do not try this until we have verified that no rewriting was
4617 * needed; that's probably not important, but let's be careful.
4619 if (check_sql_fn_retval(funcid, result_type, list_make1(querytree),
4620 &modifyTargetList, NULL))
4621 goto fail; /* reject whole-tuple-result cases */
4623 /* Now we can grab the tlist expression */
4624 newexpr = (Node *) ((TargetEntry *) linitial(querytree->targetList))->expr;
4627 * If the SQL function returns VOID, we can only inline it if it is a
4628 * SELECT of an expression returning VOID (ie, it's just a redirection to
4629 * another VOID-returning function). In all non-VOID-returning cases,
4630 * check_sql_fn_retval should ensure that newexpr returns the function's
4631 * declared result type, so this test shouldn't fail otherwise; but we may
4632 * as well cope gracefully if it does.
4634 if (exprType(newexpr) != result_type)
4637 /* check_sql_fn_retval couldn't have made any dangerous tlist changes */
4638 Assert(!modifyTargetList);
4641 * Additional validity checks on the expression. It mustn't be more
4642 * volatile than the surrounding function (this is to avoid breaking hacks
4643 * that involve pretending a function is immutable when it really ain't).
4644 * If the surrounding function is declared strict, then the expression
4645 * must contain only strict constructs and must use all of the function
4646 * parameters (this is overkill, but an exact analysis is hard).
4648 if (funcform->provolatile == PROVOLATILE_IMMUTABLE &&
4649 contain_mutable_functions(newexpr))
4651 else if (funcform->provolatile == PROVOLATILE_STABLE &&
4652 contain_volatile_functions(newexpr))
4655 if (funcform->proisstrict &&
4656 contain_nonstrict_functions(newexpr))
4660 * If any parameter expression contains a context-dependent node, we can't
4661 * inline, for fear of putting such a node into the wrong context.
4663 if (contain_context_dependent_node((Node *) args))
4667 * We may be able to do it; there are still checks on parameter usage to
4668 * make, but those are most easily done in combination with the actual
4669 * substitution of the inputs. So start building expression with inputs
4672 usecounts = (int *) palloc0(funcform->pronargs * sizeof(int));
4673 newexpr = substitute_actual_parameters(newexpr, funcform->pronargs,
4676 /* Now check for parameter usage */
4680 Node *param = lfirst(arg);
4682 if (usecounts[i] == 0)
4684 /* Param not used at all: uncool if func is strict */
4685 if (funcform->proisstrict)
4688 else if (usecounts[i] != 1)
4690 /* Param used multiple times: uncool if expensive or volatile */
4694 * We define "expensive" as "contains any subplan or more than 10
4695 * operators". Note that the subplan search has to be done
4696 * explicitly, since cost_qual_eval() will barf on unplanned
4699 if (contain_subplans(param))
4701 cost_qual_eval(&eval_cost, list_make1(param), NULL);
4702 if (eval_cost.startup + eval_cost.per_tuple >
4703 10 * cpu_operator_cost)
4707 * Check volatility last since this is more expensive than the
4710 if (contain_volatile_functions(param))
4717 * Whew --- we can make the substitution. Copy the modified expression
4718 * out of the temporary memory context, and clean up.
4720 MemoryContextSwitchTo(oldcxt);
4722 newexpr = copyObject(newexpr);
4724 MemoryContextDelete(mycxt);
4727 * If the result is of a collatable type, force the result to expose the
4728 * correct collation. In most cases this does not matter, but it's
4729 * possible that the function result is used directly as a sort key or in
4730 * other places where we expect exprCollation() to tell the truth.
4732 if (OidIsValid(result_collid))
4734 Oid exprcoll = exprCollation(newexpr);
4736 if (OidIsValid(exprcoll) && exprcoll != result_collid)
4738 CollateExpr *newnode = makeNode(CollateExpr);
4740 newnode->arg = (Expr *) newexpr;
4741 newnode->collOid = result_collid;
4742 newnode->location = -1;
4744 newexpr = (Node *) newnode;
4749 * Since there is now no trace of the function in the plan tree, we must
4750 * explicitly record the plan's dependency on the function.
4753 record_plan_function_dependency(context->root, funcid);
4756 * Recursively try to simplify the modified expression. Here we must add
4757 * the current function to the context list of active functions.
4759 context->active_fns = lcons_oid(funcid, context->active_fns);
4760 newexpr = eval_const_expressions_mutator(newexpr, context);
4761 context->active_fns = list_delete_first(context->active_fns);
4763 error_context_stack = sqlerrcontext.previous;
4765 return (Expr *) newexpr;
4767 /* Here if func is not inlinable: release temp memory and return NULL */
4769 MemoryContextSwitchTo(oldcxt);
4770 MemoryContextDelete(mycxt);
4771 error_context_stack = sqlerrcontext.previous;
4777 * Replace Param nodes by appropriate actual parameters
4780 substitute_actual_parameters(Node *expr, int nargs, List *args,
4783 substitute_actual_parameters_context context;
4785 context.nargs = nargs;
4786 context.args = args;
4787 context.usecounts = usecounts;
4789 return substitute_actual_parameters_mutator(expr, &context);
4793 substitute_actual_parameters_mutator(Node *node,
4794 substitute_actual_parameters_context *context)
4798 if (IsA(node, Param))
4800 Param *param = (Param *) node;
4802 if (param->paramkind != PARAM_EXTERN)
4803 elog(ERROR, "unexpected paramkind: %d", (int) param->paramkind);
4804 if (param->paramid <= 0 || param->paramid > context->nargs)
4805 elog(ERROR, "invalid paramid: %d", param->paramid);
4807 /* Count usage of parameter */
4808 context->usecounts[param->paramid - 1]++;
4810 /* Select the appropriate actual arg and replace the Param with it */
4811 /* We don't need to copy at this time (it'll get done later) */
4812 return list_nth(context->args, param->paramid - 1);
4814 return expression_tree_mutator(node, substitute_actual_parameters_mutator,
4819 * error context callback to let us supply a call-stack traceback
4822 sql_inline_error_callback(void *arg)
4824 inline_error_callback_arg *callback_arg = (inline_error_callback_arg *) arg;
4825 int syntaxerrposition;
4827 /* If it's a syntax error, convert to internal syntax error report */
4828 syntaxerrposition = geterrposition();
4829 if (syntaxerrposition > 0)
4832 internalerrposition(syntaxerrposition);
4833 internalerrquery(callback_arg->prosrc);
4836 errcontext("SQL function \"%s\" during inlining", callback_arg->proname);
4840 * evaluate_expr: pre-evaluate a constant expression
4842 * We use the executor's routine ExecEvalExpr() to avoid duplication of
4843 * code and ensure we get the same result as the executor would get.
4846 evaluate_expr(Expr *expr, Oid result_type, int32 result_typmod,
4847 Oid result_collation)
4850 ExprState *exprstate;
4851 MemoryContext oldcontext;
4855 bool resultTypByVal;
4858 * To use the executor, we need an EState.
4860 estate = CreateExecutorState();
4862 /* We can use the estate's working context to avoid memory leaks. */
4863 oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
4865 /* Make sure any opfuncids are filled in. */
4866 fix_opfuncids((Node *) expr);
4869 * Prepare expr for execution. (Note: we can't use ExecPrepareExpr
4870 * because it'd result in recursively invoking eval_const_expressions.)
4872 exprstate = ExecInitExpr(expr, NULL);
4877 * It is OK to use a default econtext because none of the ExecEvalExpr()
4878 * code used in this situation will use econtext. That might seem
4879 * fortuitous, but it's not so unreasonable --- a constant expression does
4880 * not depend on context, by definition, n'est ce pas?
4882 const_val = ExecEvalExprSwitchContext(exprstate,
4883 GetPerTupleExprContext(estate),
4886 /* Get info needed about result datatype */
4887 get_typlenbyval(result_type, &resultTypLen, &resultTypByVal);
4889 /* Get back to outer memory context */
4890 MemoryContextSwitchTo(oldcontext);
4893 * Must copy result out of sub-context used by expression eval.
4895 * Also, if it's varlena, forcibly detoast it. This protects us against
4896 * storing TOAST pointers into plans that might outlive the referenced
4897 * data. (makeConst would handle detoasting anyway, but it's worth a few
4898 * extra lines here so that we can do the copy and detoast in one step.)
4902 if (resultTypLen == -1)
4903 const_val = PointerGetDatum(PG_DETOAST_DATUM_COPY(const_val));
4905 const_val = datumCopy(const_val, resultTypByVal, resultTypLen);
4908 /* Release all the junk we just created */
4909 FreeExecutorState(estate);
4912 * Make the constant result node.
4914 return (Expr *) makeConst(result_type, result_typmod, result_collation,
4916 const_val, const_is_null,
4922 * inline_set_returning_function
4923 * Attempt to "inline" a set-returning function in the FROM clause.
4925 * "rte" is an RTE_FUNCTION rangetable entry. If it represents a call of a
4926 * set-returning SQL function that can safely be inlined, expand the function
4927 * and return the substitute Query structure. Otherwise, return NULL.
4929 * This has a good deal of similarity to inline_function(), but that's
4930 * for the non-set-returning case, and there are enough differences to
4931 * justify separate functions.
4934 inline_set_returning_function(PlannerInfo *root, RangeTblEntry *rte)
4936 RangeTblFunction *rtfunc;
4939 HeapTuple func_tuple;
4940 Form_pg_proc funcform;
4944 bool modifyTargetList;
4945 MemoryContext oldcxt;
4946 MemoryContext mycxt;
4947 List *saveInvalItems;
4948 inline_error_callback_arg callback_arg;
4949 ErrorContextCallback sqlerrcontext;
4950 SQLFunctionParseInfoPtr pinfo;
4951 List *raw_parsetree_list;
4952 List *querytree_list;
4955 Assert(rte->rtekind == RTE_FUNCTION);
4958 * It doesn't make a lot of sense for a SQL SRF to refer to itself in its
4959 * own FROM clause, since that must cause infinite recursion at runtime.
4960 * It will cause this code to recurse too, so check for stack overflow.
4961 * (There's no need to do more.)
4963 check_stack_depth();
4965 /* Fail if the RTE has ORDINALITY - we don't implement that here. */
4966 if (rte->funcordinality)
4969 /* Fail if RTE isn't a single, simple FuncExpr */
4970 if (list_length(rte->functions) != 1)
4972 rtfunc = (RangeTblFunction *) linitial(rte->functions);
4974 if (!IsA(rtfunc->funcexpr, FuncExpr))
4976 fexpr = (FuncExpr *) rtfunc->funcexpr;
4978 func_oid = fexpr->funcid;
4981 * The function must be declared to return a set, else inlining would
4982 * change the results if the contained SELECT didn't return exactly one
4985 if (!fexpr->funcretset)
4989 * Refuse to inline if the arguments contain any volatile functions or
4990 * sub-selects. Volatile functions are rejected because inlining may
4991 * result in the arguments being evaluated multiple times, risking a
4992 * change in behavior. Sub-selects are rejected partly for implementation
4993 * reasons (pushing them down another level might change their behavior)
4994 * and partly because they're likely to be expensive and so multiple
4995 * evaluation would be bad.
4997 if (contain_volatile_functions((Node *) fexpr->args) ||
4998 contain_subplans((Node *) fexpr->args))
5001 /* Check permission to call function (fail later, if not) */
5002 if (pg_proc_aclcheck(func_oid, GetUserId(), ACL_EXECUTE) != ACLCHECK_OK)
5005 /* Check whether a plugin wants to hook function entry/exit */
5006 if (FmgrHookIsNeeded(func_oid))
5010 * OK, let's take a look at the function's pg_proc entry.
5012 func_tuple = SearchSysCache1(PROCOID, ObjectIdGetDatum(func_oid));
5013 if (!HeapTupleIsValid(func_tuple))
5014 elog(ERROR, "cache lookup failed for function %u", func_oid);
5015 funcform = (Form_pg_proc) GETSTRUCT(func_tuple);
5018 * Forget it if the function is not SQL-language or has other showstopper
5019 * properties. In particular it mustn't be declared STRICT, since we
5020 * couldn't enforce that. It also mustn't be VOLATILE, because that is
5021 * supposed to cause it to be executed with its own snapshot, rather than
5022 * sharing the snapshot of the calling query. We also disallow returning
5023 * SETOF VOID, because inlining would result in exposing the actual result
5024 * of the function's last SELECT, which should not happen in that case.
5025 * (Rechecking prokind and proretset is just paranoia.)
5027 if (funcform->prolang != SQLlanguageId ||
5028 funcform->prokind != PROKIND_FUNCTION ||
5029 funcform->proisstrict ||
5030 funcform->provolatile == PROVOLATILE_VOLATILE ||
5031 funcform->prorettype == VOIDOID ||
5032 funcform->prosecdef ||
5033 !funcform->proretset ||
5034 !heap_attisnull(func_tuple, Anum_pg_proc_proconfig, NULL))
5036 ReleaseSysCache(func_tuple);
5041 * Make a temporary memory context, so that we don't leak all the stuff
5042 * that parsing might create.
5044 mycxt = AllocSetContextCreate(CurrentMemoryContext,
5045 "inline_set_returning_function",
5046 ALLOCSET_DEFAULT_SIZES);
5047 oldcxt = MemoryContextSwitchTo(mycxt);
5050 * When we call eval_const_expressions below, it might try to add items to
5051 * root->glob->invalItems. Since it is running in the temp context, those
5052 * items will be in that context, and will need to be copied out if we're
5053 * successful. Temporarily reset the list so that we can keep those items
5054 * separate from the pre-existing list contents.
5056 saveInvalItems = root->glob->invalItems;
5057 root->glob->invalItems = NIL;
5059 /* Fetch the function body */
5060 tmp = SysCacheGetAttr(PROCOID,
5062 Anum_pg_proc_prosrc,
5065 elog(ERROR, "null prosrc for function %u", func_oid);
5066 src = TextDatumGetCString(tmp);
5069 * Setup error traceback support for ereport(). This is so that we can
5070 * finger the function that bad information came from.
5072 callback_arg.proname = NameStr(funcform->proname);
5073 callback_arg.prosrc = src;
5075 sqlerrcontext.callback = sql_inline_error_callback;
5076 sqlerrcontext.arg = (void *) &callback_arg;
5077 sqlerrcontext.previous = error_context_stack;
5078 error_context_stack = &sqlerrcontext;
5081 * Run eval_const_expressions on the function call. This is necessary to
5082 * ensure that named-argument notation is converted to positional notation
5083 * and any default arguments are inserted. It's a bit of overkill for the
5084 * arguments, since they'll get processed again later, but no harm will be
5087 fexpr = (FuncExpr *) eval_const_expressions(root, (Node *) fexpr);
5089 /* It should still be a call of the same function, but let's check */
5090 if (!IsA(fexpr, FuncExpr) ||
5091 fexpr->funcid != func_oid)
5094 /* Arg list length should now match the function */
5095 if (list_length(fexpr->args) != funcform->pronargs)
5099 * Set up to handle parameters while parsing the function body. We can
5100 * use the FuncExpr just created as the input for
5101 * prepare_sql_fn_parse_info.
5103 pinfo = prepare_sql_fn_parse_info(func_tuple,
5105 fexpr->inputcollid);
5108 * Parse, analyze, and rewrite (unlike inline_function(), we can't skip
5109 * rewriting here). We can fail as soon as we find more than one query,
5112 raw_parsetree_list = pg_parse_query(src);
5113 if (list_length(raw_parsetree_list) != 1)
5116 querytree_list = pg_analyze_and_rewrite_params(linitial(raw_parsetree_list),
5118 (ParserSetupHook) sql_fn_parser_setup,
5120 if (list_length(querytree_list) != 1)
5122 querytree = linitial(querytree_list);
5125 * The single command must be a plain SELECT.
5127 if (!IsA(querytree, Query) ||
5128 querytree->commandType != CMD_SELECT)
5132 * Make sure the function (still) returns what it's declared to. This
5133 * will raise an error if wrong, but that's okay since the function would
5134 * fail at runtime anyway. Note that check_sql_fn_retval will also insert
5135 * RelabelType(s) and/or NULL columns if needed to make the tlist
5136 * expression(s) match the declared type of the function.
5138 * If the function returns a composite type, don't inline unless the check
5139 * shows it's returning a whole tuple result; otherwise what it's
5140 * returning is a single composite column which is not what we need. (Like
5141 * check_sql_fn_retval, we deliberately exclude domains over composite
5144 if (!check_sql_fn_retval(func_oid, fexpr->funcresulttype,
5146 &modifyTargetList, NULL) &&
5147 (get_typtype(fexpr->funcresulttype) == TYPTYPE_COMPOSITE ||
5148 fexpr->funcresulttype == RECORDOID))
5149 goto fail; /* reject not-whole-tuple-result cases */
5152 * If we had to modify the tlist to make it match, and the statement is
5153 * one in which changing the tlist contents could change semantics, we
5154 * have to punt and not inline.
5156 if (modifyTargetList)
5160 * If it returns RECORD, we have to check against the column type list
5161 * provided in the RTE; check_sql_fn_retval can't do that. (If no match,
5162 * we just fail to inline, rather than complaining; see notes for
5163 * tlist_matches_coltypelist.) We don't have to do this for functions
5164 * with declared OUT parameters, even though their funcresulttype is
5165 * RECORDOID, so check get_func_result_type too.
5167 if (fexpr->funcresulttype == RECORDOID &&
5168 get_func_result_type(func_oid, NULL, NULL) == TYPEFUNC_RECORD &&
5169 !tlist_matches_coltypelist(querytree->targetList,
5170 rtfunc->funccoltypes))
5174 * Looks good --- substitute parameters into the query.
5176 querytree = substitute_actual_srf_parameters(querytree,
5181 * Copy the modified query out of the temporary memory context, and clean
5184 MemoryContextSwitchTo(oldcxt);
5186 querytree = copyObject(querytree);
5188 /* copy up any new invalItems, too */
5189 root->glob->invalItems = list_concat(saveInvalItems,
5190 copyObject(root->glob->invalItems));
5192 MemoryContextDelete(mycxt);
5193 error_context_stack = sqlerrcontext.previous;
5194 ReleaseSysCache(func_tuple);
5197 * We don't have to fix collations here because the upper query is already
5198 * parsed, ie, the collations in the RTE are what count.
5202 * Since there is now no trace of the function in the plan tree, we must
5203 * explicitly record the plan's dependency on the function.
5205 record_plan_function_dependency(root, func_oid);
5209 /* Here if func is not inlinable: release temp memory and return NULL */
5211 MemoryContextSwitchTo(oldcxt);
5212 root->glob->invalItems = saveInvalItems;
5213 MemoryContextDelete(mycxt);
5214 error_context_stack = sqlerrcontext.previous;
5215 ReleaseSysCache(func_tuple);
5221 * Replace Param nodes by appropriate actual parameters
5223 * This is just enough different from substitute_actual_parameters()
5224 * that it needs its own code.
5227 substitute_actual_srf_parameters(Query *expr, int nargs, List *args)
5229 substitute_actual_srf_parameters_context context;
5231 context.nargs = nargs;
5232 context.args = args;
5233 context.sublevels_up = 1;
5235 return query_tree_mutator(expr,
5236 substitute_actual_srf_parameters_mutator,
5242 substitute_actual_srf_parameters_mutator(Node *node,
5243 substitute_actual_srf_parameters_context *context)
5249 if (IsA(node, Query))
5251 context->sublevels_up++;
5252 result = (Node *) query_tree_mutator((Query *) node,
5253 substitute_actual_srf_parameters_mutator,
5256 context->sublevels_up--;
5259 if (IsA(node, Param))
5261 Param *param = (Param *) node;
5263 if (param->paramkind == PARAM_EXTERN)
5265 if (param->paramid <= 0 || param->paramid > context->nargs)
5266 elog(ERROR, "invalid paramid: %d", param->paramid);
5269 * Since the parameter is being inserted into a subquery, we must
5272 result = copyObject(list_nth(context->args, param->paramid - 1));
5273 IncrementVarSublevelsUp(result, context->sublevels_up, 0);
5277 return expression_tree_mutator(node,
5278 substitute_actual_srf_parameters_mutator,
5283 * Check whether a SELECT targetlist emits the specified column types,
5284 * to see if it's safe to inline a function returning record.
5286 * We insist on exact match here. The executor allows binary-coercible
5287 * cases too, but we don't have a way to preserve the correct column types
5288 * in the correct places if we inline the function in such a case.
5290 * Note that we only check type OIDs not typmods; this agrees with what the
5291 * executor would do at runtime, and attributing a specific typmod to a
5292 * function result is largely wishful thinking anyway.
5295 tlist_matches_coltypelist(List *tlist, List *coltypelist)
5297 ListCell *tlistitem;
5298 ListCell *clistitem;
5300 clistitem = list_head(coltypelist);
5301 foreach(tlistitem, tlist)
5303 TargetEntry *tle = (TargetEntry *) lfirst(tlistitem);
5307 continue; /* ignore junk columns */
5309 if (clistitem == NULL)
5310 return false; /* too many tlist items */
5312 coltype = lfirst_oid(clistitem);
5313 clistitem = lnext(clistitem);
5315 if (exprType((Node *) tle->expr) != coltype)
5316 return false; /* column type mismatch */
5319 if (clistitem != NULL)
5320 return false; /* too few tlist items */