1 /*-------------------------------------------------------------------------
4 * routines to manipulate qualification clauses
6 * Portions Copyright (c) 1996-2006, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
11 * $PostgreSQL: pgsql/src/backend/optimizer/util/clauses.c,v 1.218 2006/08/12 02:52:05 tgl Exp $
14 * AUTHOR DATE MAJOR EVENT
15 * Andrew Yu Nov 3, 1994 clause.c and clauses.c combined
17 *-------------------------------------------------------------------------
22 #include "catalog/pg_aggregate.h"
23 #include "catalog/pg_language.h"
24 #include "catalog/pg_operator.h"
25 #include "catalog/pg_proc.h"
26 #include "catalog/pg_type.h"
27 #include "executor/executor.h"
28 #include "executor/functions.h"
29 #include "miscadmin.h"
30 #include "nodes/makefuncs.h"
31 #include "optimizer/clauses.h"
32 #include "optimizer/cost.h"
33 #include "optimizer/planmain.h"
34 #include "optimizer/planner.h"
35 #include "optimizer/var.h"
36 #include "parser/analyze.h"
37 #include "parser/parse_clause.h"
38 #include "parser/parse_coerce.h"
39 #include "parser/parse_expr.h"
40 #include "tcop/tcopprot.h"
41 #include "utils/acl.h"
42 #include "utils/builtins.h"
43 #include "utils/datum.h"
44 #include "utils/lsyscache.h"
45 #include "utils/memutils.h"
46 #include "utils/syscache.h"
47 #include "utils/typcache.h"
55 } eval_const_expressions_context;
62 } substitute_actual_parameters_context;
64 static bool contain_agg_clause_walker(Node *node, void *context);
65 static bool count_agg_clauses_walker(Node *node, AggClauseCounts *counts);
66 static bool expression_returns_set_walker(Node *node, void *context);
67 static bool contain_subplans_walker(Node *node, void *context);
68 static bool contain_mutable_functions_walker(Node *node, void *context);
69 static bool contain_volatile_functions_walker(Node *node, void *context);
70 static bool contain_nonstrict_functions_walker(Node *node, void *context);
71 static Relids find_nonnullable_rels_walker(Node *node, bool top_level);
72 static bool is_strict_saop(ScalarArrayOpExpr *expr, bool falseOK);
73 static bool set_coercionform_dontcare_walker(Node *node, void *context);
74 static Node *eval_const_expressions_mutator(Node *node,
75 eval_const_expressions_context *context);
76 static List *simplify_or_arguments(List *args,
77 eval_const_expressions_context *context,
78 bool *haveNull, bool *forceTrue);
79 static List *simplify_and_arguments(List *args,
80 eval_const_expressions_context *context,
81 bool *haveNull, bool *forceFalse);
82 static Expr *simplify_boolean_equality(List *args);
83 static Expr *simplify_function(Oid funcid, Oid result_type, List *args,
85 eval_const_expressions_context *context);
86 static Expr *evaluate_function(Oid funcid, Oid result_type, List *args,
88 eval_const_expressions_context *context);
89 static Expr *inline_function(Oid funcid, Oid result_type, List *args,
91 eval_const_expressions_context *context);
92 static Node *substitute_actual_parameters(Node *expr, int nargs, List *args,
94 static Node *substitute_actual_parameters_mutator(Node *node,
95 substitute_actual_parameters_context *context);
96 static void sql_inline_error_callback(void *arg);
97 static Expr *evaluate_expr(Expr *expr, Oid result_type);
100 /*****************************************************************************
101 * OPERATOR clause functions
102 *****************************************************************************/
106 * Creates an operator clause given its operator info, left operand,
107 * and right operand (pass NULL to create single-operand clause).
110 make_opclause(Oid opno, Oid opresulttype, bool opretset,
111 Expr *leftop, Expr *rightop)
113 OpExpr *expr = makeNode(OpExpr);
116 expr->opfuncid = InvalidOid;
117 expr->opresulttype = opresulttype;
118 expr->opretset = opretset;
120 expr->args = list_make2(leftop, rightop);
122 expr->args = list_make1(leftop);
123 return (Expr *) expr;
129 * Returns the left operand of a clause of the form (op expr expr)
133 get_leftop(Expr *clause)
135 OpExpr *expr = (OpExpr *) clause;
137 if (expr->args != NIL)
138 return linitial(expr->args);
146 * Returns the right operand in a clause of the form (op expr expr).
147 * NB: result will be NULL if applied to a unary op clause.
150 get_rightop(Expr *clause)
152 OpExpr *expr = (OpExpr *) clause;
154 if (list_length(expr->args) >= 2)
155 return lsecond(expr->args);
160 /*****************************************************************************
161 * NOT clause functions
162 *****************************************************************************/
167 * Returns t iff this is a 'not' clause: (NOT expr).
170 not_clause(Node *clause)
172 return (clause != NULL &&
173 IsA(clause, BoolExpr) &&
174 ((BoolExpr *) clause)->boolop == NOT_EXPR);
180 * Create a 'not' clause given the expression to be negated.
183 make_notclause(Expr *notclause)
185 BoolExpr *expr = makeNode(BoolExpr);
187 expr->boolop = NOT_EXPR;
188 expr->args = list_make1(notclause);
189 return (Expr *) expr;
195 * Retrieve the clause within a 'not' clause
198 get_notclausearg(Expr *notclause)
200 return linitial(((BoolExpr *) notclause)->args);
203 /*****************************************************************************
204 * OR clause functions
205 *****************************************************************************/
210 * Returns t iff the clause is an 'or' clause: (OR { expr }).
213 or_clause(Node *clause)
215 return (clause != NULL &&
216 IsA(clause, BoolExpr) &&
217 ((BoolExpr *) clause)->boolop == OR_EXPR);
223 * Creates an 'or' clause given a list of its subclauses.
226 make_orclause(List *orclauses)
228 BoolExpr *expr = makeNode(BoolExpr);
230 expr->boolop = OR_EXPR;
231 expr->args = orclauses;
232 return (Expr *) expr;
235 /*****************************************************************************
236 * AND clause functions
237 *****************************************************************************/
243 * Returns t iff its argument is an 'and' clause: (AND { expr }).
246 and_clause(Node *clause)
248 return (clause != NULL &&
249 IsA(clause, BoolExpr) &&
250 ((BoolExpr *) clause)->boolop == AND_EXPR);
256 * Creates an 'and' clause given a list of its subclauses.
259 make_andclause(List *andclauses)
261 BoolExpr *expr = makeNode(BoolExpr);
263 expr->boolop = AND_EXPR;
264 expr->args = andclauses;
265 return (Expr *) expr;
271 * Variant of make_andclause for ANDing two qual conditions together.
272 * Qual conditions have the property that a NULL nodetree is interpreted
275 * NB: this makes no attempt to preserve AND/OR flatness; so it should not
276 * be used on a qual that has already been run through prepqual.c.
279 make_and_qual(Node *qual1, Node *qual2)
285 return (Node *) make_andclause(list_make2(qual1, qual2));
289 * Sometimes (such as in the input of ExecQual), we use lists of expression
290 * nodes with implicit AND semantics.
292 * These functions convert between an AND-semantics expression list and the
293 * ordinary representation of a boolean expression.
295 * Note that an empty list is considered equivalent to TRUE.
298 make_ands_explicit(List *andclauses)
300 if (andclauses == NIL)
301 return (Expr *) makeBoolConst(true, false);
302 else if (list_length(andclauses) == 1)
303 return (Expr *) linitial(andclauses);
305 return make_andclause(andclauses);
309 make_ands_implicit(Expr *clause)
312 * NB: because the parser sets the qual field to NULL in a query that has
313 * no WHERE clause, we must consider a NULL input clause as TRUE, even
314 * though one might more reasonably think it FALSE. Grumble. If this
315 * causes trouble, consider changing the parser's behavior.
318 return NIL; /* NULL -> NIL list == TRUE */
319 else if (and_clause((Node *) clause))
320 return ((BoolExpr *) clause)->args;
321 else if (IsA(clause, Const) &&
322 !((Const *) clause)->constisnull &&
323 DatumGetBool(((Const *) clause)->constvalue))
324 return NIL; /* constant TRUE input -> NIL list */
326 return list_make1(clause);
330 /*****************************************************************************
331 * Aggregate-function clause manipulation
332 *****************************************************************************/
336 * Recursively search for Aggref nodes within a clause.
338 * Returns true if any aggregate found.
340 * This does not descend into subqueries, and so should be used only after
341 * reduction of sublinks to subplans, or in contexts where it's known there
342 * are no subqueries. There mustn't be outer-aggregate references either.
344 * (If you want something like this but able to deal with subqueries,
345 * see rewriteManip.c's checkExprHasAggs().)
348 contain_agg_clause(Node *clause)
350 return contain_agg_clause_walker(clause, NULL);
354 contain_agg_clause_walker(Node *node, void *context)
358 if (IsA(node, Aggref))
360 Assert(((Aggref *) node)->agglevelsup == 0);
361 return true; /* abort the tree traversal and return true */
363 Assert(!IsA(node, SubLink));
364 return expression_tree_walker(node, contain_agg_clause_walker, context);
369 * Recursively count the Aggref nodes in an expression tree.
371 * Note: this also checks for nested aggregates, which are an error.
373 * We not only count the nodes, but attempt to estimate the total space
374 * needed for their transition state values if all are evaluated in parallel
375 * (as would be done in a HashAgg plan). See AggClauseCounts for the exact
376 * set of statistics returned.
378 * NOTE that the counts are ADDED to those already in *counts ... so the
379 * caller is responsible for zeroing the struct initially.
381 * This does not descend into subqueries, and so should be used only after
382 * reduction of sublinks to subplans, or in contexts where it's known there
383 * are no subqueries. There mustn't be outer-aggregate references either.
386 count_agg_clauses(Node *clause, AggClauseCounts *counts)
388 /* no setup needed */
389 count_agg_clauses_walker(clause, counts);
393 count_agg_clauses_walker(Node *node, AggClauseCounts *counts)
397 if (IsA(node, Aggref))
399 Aggref *aggref = (Aggref *) node;
403 Form_pg_aggregate aggform;
408 Assert(aggref->agglevelsup == 0);
410 if (aggref->aggdistinct)
411 counts->numDistinctAggs++;
413 /* extract argument types */
414 numArguments = list_length(aggref->args);
415 inputTypes = (Oid *) palloc(sizeof(Oid) * numArguments);
417 foreach(l, aggref->args)
419 inputTypes[i++] = exprType((Node *) lfirst(l));
422 /* fetch aggregate transition datatype from pg_aggregate */
423 aggTuple = SearchSysCache(AGGFNOID,
424 ObjectIdGetDatum(aggref->aggfnoid),
426 if (!HeapTupleIsValid(aggTuple))
427 elog(ERROR, "cache lookup failed for aggregate %u",
429 aggform = (Form_pg_aggregate) GETSTRUCT(aggTuple);
430 aggtranstype = aggform->aggtranstype;
431 ReleaseSysCache(aggTuple);
433 /* resolve actual type of transition state, if polymorphic */
434 if (aggtranstype == ANYARRAYOID || aggtranstype == ANYELEMENTOID)
436 /* have to fetch the agg's declared input types... */
437 Oid *declaredArgTypes;
440 (void) get_func_signature(aggref->aggfnoid,
441 &declaredArgTypes, &agg_nargs);
442 Assert(agg_nargs == numArguments);
443 aggtranstype = enforce_generic_type_consistency(inputTypes,
447 pfree(declaredArgTypes);
451 * If the transition type is pass-by-value then it doesn't add
452 * anything to the required size of the hashtable. If it is
453 * pass-by-reference then we have to add the estimated size of the
454 * value itself, plus palloc overhead.
456 if (!get_typbyval(aggtranstype))
458 int32 aggtranstypmod;
462 * If transition state is of same type as first input, assume it's
463 * the same typmod (same width) as well. This works for cases
464 * like MAX/MIN and is probably somewhat reasonable otherwise.
466 if (numArguments > 0 && aggtranstype == inputTypes[0])
467 aggtranstypmod = exprTypmod((Node *) linitial(aggref->args));
471 avgwidth = get_typavgwidth(aggtranstype, aggtranstypmod);
472 avgwidth = MAXALIGN(avgwidth);
474 counts->transitionSpace += avgwidth + 2 * sizeof(void *);
478 * Complain if the aggregate's arguments contain any aggregates;
479 * nested agg functions are semantically nonsensical.
481 if (contain_agg_clause((Node *) aggref->args))
483 (errcode(ERRCODE_GROUPING_ERROR),
484 errmsg("aggregate function calls may not be nested")));
487 * Having checked that, we need not recurse into the argument.
491 Assert(!IsA(node, SubLink));
492 return expression_tree_walker(node, count_agg_clauses_walker,
497 /*****************************************************************************
498 * Support for expressions returning sets
499 *****************************************************************************/
502 * expression_returns_set
503 * Test whether an expression returns a set result.
505 * Because we use expression_tree_walker(), this can also be applied to
506 * whole targetlists; it'll produce TRUE if any one of the tlist items
510 expression_returns_set(Node *clause)
512 return expression_returns_set_walker(clause, NULL);
516 expression_returns_set_walker(Node *node, void *context)
520 if (IsA(node, FuncExpr))
522 FuncExpr *expr = (FuncExpr *) node;
524 if (expr->funcretset)
526 /* else fall through to check args */
528 if (IsA(node, OpExpr))
530 OpExpr *expr = (OpExpr *) node;
534 /* else fall through to check args */
537 /* Avoid recursion for some cases that can't return a set */
538 if (IsA(node, Aggref))
540 if (IsA(node, DistinctExpr))
542 if (IsA(node, ScalarArrayOpExpr))
544 if (IsA(node, BoolExpr))
546 if (IsA(node, SubLink))
548 if (IsA(node, SubPlan))
550 if (IsA(node, ArrayExpr))
552 if (IsA(node, RowExpr))
554 if (IsA(node, RowCompareExpr))
556 if (IsA(node, CoalesceExpr))
558 if (IsA(node, MinMaxExpr))
560 if (IsA(node, NullIfExpr))
563 return expression_tree_walker(node, expression_returns_set_walker,
567 /*****************************************************************************
568 * Subplan clause manipulation
569 *****************************************************************************/
573 * Recursively search for subplan nodes within a clause.
575 * If we see a SubLink node, we will return TRUE. This is only possible if
576 * the expression tree hasn't yet been transformed by subselect.c. We do not
577 * know whether the node will produce a true subplan or just an initplan,
578 * but we make the conservative assumption that it will be a subplan.
580 * Returns true if any subplan found.
583 contain_subplans(Node *clause)
585 return contain_subplans_walker(clause, NULL);
589 contain_subplans_walker(Node *node, void *context)
593 if (IsA(node, SubPlan) ||
595 return true; /* abort the tree traversal and return true */
596 return expression_tree_walker(node, contain_subplans_walker, context);
600 /*****************************************************************************
601 * Check clauses for mutable functions
602 *****************************************************************************/
605 * contain_mutable_functions
606 * Recursively search for mutable functions within a clause.
608 * Returns true if any mutable function (or operator implemented by a
609 * mutable function) is found. This test is needed so that we don't
610 * mistakenly think that something like "WHERE random() < 0.5" can be treated
611 * as a constant qualification.
613 * XXX we do not examine sub-selects to see if they contain uses of
614 * mutable functions. It's not real clear if that is correct or not...
617 contain_mutable_functions(Node *clause)
619 return contain_mutable_functions_walker(clause, NULL);
623 contain_mutable_functions_walker(Node *node, void *context)
627 if (IsA(node, FuncExpr))
629 FuncExpr *expr = (FuncExpr *) node;
631 if (func_volatile(expr->funcid) != PROVOLATILE_IMMUTABLE)
633 /* else fall through to check args */
635 if (IsA(node, OpExpr))
637 OpExpr *expr = (OpExpr *) node;
639 if (op_volatile(expr->opno) != PROVOLATILE_IMMUTABLE)
641 /* else fall through to check args */
643 if (IsA(node, DistinctExpr))
645 DistinctExpr *expr = (DistinctExpr *) node;
647 if (op_volatile(expr->opno) != PROVOLATILE_IMMUTABLE)
649 /* else fall through to check args */
651 if (IsA(node, ScalarArrayOpExpr))
653 ScalarArrayOpExpr *expr = (ScalarArrayOpExpr *) node;
655 if (op_volatile(expr->opno) != PROVOLATILE_IMMUTABLE)
657 /* else fall through to check args */
659 if (IsA(node, NullIfExpr))
661 NullIfExpr *expr = (NullIfExpr *) node;
663 if (op_volatile(expr->opno) != PROVOLATILE_IMMUTABLE)
665 /* else fall through to check args */
667 if (IsA(node, RowCompareExpr))
669 RowCompareExpr *rcexpr = (RowCompareExpr *) node;
672 foreach(opid, rcexpr->opnos)
674 if (op_volatile(lfirst_oid(opid)) != PROVOLATILE_IMMUTABLE)
677 /* else fall through to check args */
679 return expression_tree_walker(node, contain_mutable_functions_walker,
684 /*****************************************************************************
685 * Check clauses for volatile functions
686 *****************************************************************************/
689 * contain_volatile_functions
690 * Recursively search for volatile functions within a clause.
692 * Returns true if any volatile function (or operator implemented by a
693 * volatile function) is found. This test prevents invalid conversions
694 * of volatile expressions into indexscan quals.
696 * XXX we do not examine sub-selects to see if they contain uses of
697 * volatile functions. It's not real clear if that is correct or not...
700 contain_volatile_functions(Node *clause)
702 return contain_volatile_functions_walker(clause, NULL);
706 contain_volatile_functions_walker(Node *node, void *context)
710 if (IsA(node, FuncExpr))
712 FuncExpr *expr = (FuncExpr *) node;
714 if (func_volatile(expr->funcid) == PROVOLATILE_VOLATILE)
716 /* else fall through to check args */
718 if (IsA(node, OpExpr))
720 OpExpr *expr = (OpExpr *) node;
722 if (op_volatile(expr->opno) == PROVOLATILE_VOLATILE)
724 /* else fall through to check args */
726 if (IsA(node, DistinctExpr))
728 DistinctExpr *expr = (DistinctExpr *) node;
730 if (op_volatile(expr->opno) == PROVOLATILE_VOLATILE)
732 /* else fall through to check args */
734 if (IsA(node, ScalarArrayOpExpr))
736 ScalarArrayOpExpr *expr = (ScalarArrayOpExpr *) node;
738 if (op_volatile(expr->opno) == PROVOLATILE_VOLATILE)
740 /* else fall through to check args */
742 if (IsA(node, NullIfExpr))
744 NullIfExpr *expr = (NullIfExpr *) node;
746 if (op_volatile(expr->opno) == PROVOLATILE_VOLATILE)
748 /* else fall through to check args */
750 if (IsA(node, RowCompareExpr))
752 /* RowCompare probably can't have volatile ops, but check anyway */
753 RowCompareExpr *rcexpr = (RowCompareExpr *) node;
756 foreach(opid, rcexpr->opnos)
758 if (op_volatile(lfirst_oid(opid)) == PROVOLATILE_VOLATILE)
761 /* else fall through to check args */
763 return expression_tree_walker(node, contain_volatile_functions_walker,
768 /*****************************************************************************
769 * Check clauses for nonstrict functions
770 *****************************************************************************/
773 * contain_nonstrict_functions
774 * Recursively search for nonstrict functions within a clause.
776 * Returns true if any nonstrict construct is found --- ie, anything that
777 * could produce non-NULL output with a NULL input.
779 * The idea here is that the caller has verified that the expression contains
780 * one or more Var or Param nodes (as appropriate for the caller's need), and
781 * now wishes to prove that the expression result will be NULL if any of these
782 * inputs is NULL. If we return false, then the proof succeeded.
785 contain_nonstrict_functions(Node *clause)
787 return contain_nonstrict_functions_walker(clause, NULL);
791 contain_nonstrict_functions_walker(Node *node, void *context)
795 if (IsA(node, Aggref))
797 /* an aggregate could return non-null with null input */
800 if (IsA(node, ArrayRef))
802 /* array assignment is nonstrict, but subscripting is strict */
803 if (((ArrayRef *) node)->refassgnexpr != NULL)
805 /* else fall through to check args */
807 if (IsA(node, FuncExpr))
809 FuncExpr *expr = (FuncExpr *) node;
811 if (!func_strict(expr->funcid))
813 /* else fall through to check args */
815 if (IsA(node, OpExpr))
817 OpExpr *expr = (OpExpr *) node;
819 if (!op_strict(expr->opno))
821 /* else fall through to check args */
823 if (IsA(node, DistinctExpr))
825 /* IS DISTINCT FROM is inherently non-strict */
828 if (IsA(node, ScalarArrayOpExpr))
830 ScalarArrayOpExpr *expr = (ScalarArrayOpExpr *) node;
832 if (!is_strict_saop(expr, false))
834 /* else fall through to check args */
836 if (IsA(node, BoolExpr))
838 BoolExpr *expr = (BoolExpr *) node;
840 switch (expr->boolop)
844 /* AND, OR are inherently non-strict */
850 if (IsA(node, SubLink))
852 /* In some cases a sublink might be strict, but in general not */
855 if (IsA(node, SubPlan))
857 if (IsA(node, FieldStore))
859 if (IsA(node, CaseExpr))
861 if (IsA(node, CaseWhen))
863 if (IsA(node, ArrayExpr))
865 if (IsA(node, RowExpr))
867 if (IsA(node, RowCompareExpr))
869 if (IsA(node, CoalesceExpr))
871 if (IsA(node, MinMaxExpr))
873 if (IsA(node, NullIfExpr))
875 if (IsA(node, NullTest))
877 if (IsA(node, BooleanTest))
879 return expression_tree_walker(node, contain_nonstrict_functions_walker,
885 * find_nonnullable_rels
886 * Determine which base rels are forced nonnullable by given clause.
888 * Returns the set of all Relids that are referenced in the clause in such
889 * a way that the clause cannot possibly return TRUE if any of these Relids
890 * is an all-NULL row. (It is OK to err on the side of conservatism; hence
891 * the analysis here is simplistic.)
893 * The semantics here are subtly different from contain_nonstrict_functions:
894 * that function is concerned with NULL results from arbitrary expressions,
895 * but here we assume that the input is a Boolean expression, and wish to
896 * see if NULL inputs will provably cause a FALSE-or-NULL result. We expect
897 * the expression to have been AND/OR flattened and converted to implicit-AND
900 * We don't use expression_tree_walker here because we don't want to
901 * descend through very many kinds of nodes; only the ones we can be sure
902 * are strict. We can descend through the top level of implicit AND'ing,
903 * but not through any explicit ANDs (or ORs) below that, since those are not
904 * strict constructs. The List case handles the top-level implicit AND list
905 * as well as lists of arguments to strict operators/functions.
908 find_nonnullable_rels(Node *clause)
910 return find_nonnullable_rels_walker(clause, true);
914 find_nonnullable_rels_walker(Node *node, bool top_level)
916 Relids result = NULL;
922 Var *var = (Var *) node;
924 if (var->varlevelsup == 0)
925 result = bms_make_singleton(var->varno);
927 else if (IsA(node, List))
931 foreach(l, (List *) node)
933 result = bms_join(result,
934 find_nonnullable_rels_walker(lfirst(l),
938 else if (IsA(node, FuncExpr))
940 FuncExpr *expr = (FuncExpr *) node;
942 if (func_strict(expr->funcid))
943 result = find_nonnullable_rels_walker((Node *) expr->args, false);
945 else if (IsA(node, OpExpr))
947 OpExpr *expr = (OpExpr *) node;
949 if (op_strict(expr->opno))
950 result = find_nonnullable_rels_walker((Node *) expr->args, false);
952 else if (IsA(node, ScalarArrayOpExpr))
954 ScalarArrayOpExpr *expr = (ScalarArrayOpExpr *) node;
956 if (is_strict_saop(expr, true))
957 result = find_nonnullable_rels_walker((Node *) expr->args, false);
959 else if (IsA(node, BoolExpr))
961 BoolExpr *expr = (BoolExpr *) node;
963 /* NOT is strict, others are not */
964 if (expr->boolop == NOT_EXPR)
965 result = find_nonnullable_rels_walker((Node *) expr->args, false);
967 else if (IsA(node, RelabelType))
969 RelabelType *expr = (RelabelType *) node;
971 result = find_nonnullable_rels_walker((Node *) expr->arg, top_level);
973 else if (IsA(node, ConvertRowtypeExpr))
975 /* not clear this is useful, but it can't hurt */
976 ConvertRowtypeExpr *expr = (ConvertRowtypeExpr *) node;
978 result = find_nonnullable_rels_walker((Node *) expr->arg, top_level);
980 else if (IsA(node, NullTest))
982 NullTest *expr = (NullTest *) node;
985 * IS NOT NULL can be considered strict, but only at top level; else
986 * we might have something like NOT (x IS NOT NULL).
988 if (top_level && expr->nulltesttype == IS_NOT_NULL)
989 result = find_nonnullable_rels_walker((Node *) expr->arg, false);
991 else if (IsA(node, BooleanTest))
993 BooleanTest *expr = (BooleanTest *) node;
996 * Appropriate boolean tests are strict at top level.
999 (expr->booltesttype == IS_TRUE ||
1000 expr->booltesttype == IS_FALSE ||
1001 expr->booltesttype == IS_NOT_UNKNOWN))
1002 result = find_nonnullable_rels_walker((Node *) expr->arg, false);
1008 * Can we treat a ScalarArrayOpExpr as strict?
1010 * If "falseOK" is true, then a "false" result can be considered strict,
1011 * else we need to guarantee an actual NULL result for NULL input.
1013 * "foo op ALL array" is strict if the op is strict *and* we can prove
1014 * that the array input isn't an empty array. We can check that
1015 * for the cases of an array constant and an ARRAY[] construct.
1017 * "foo op ANY array" is strict in the falseOK sense if the op is strict.
1018 * If not falseOK, the test is the same as for "foo op ALL array".
1021 is_strict_saop(ScalarArrayOpExpr *expr, bool falseOK)
1025 /* The contained operator must be strict. */
1026 if (!op_strict(expr->opno))
1028 /* If ANY and falseOK, that's all we need to check. */
1029 if (expr->useOr && falseOK)
1031 /* Else, we have to see if the array is provably non-empty. */
1032 Assert(list_length(expr->args) == 2);
1033 rightop = (Node *) lsecond(expr->args);
1034 if (rightop && IsA(rightop, Const))
1036 Datum arraydatum = ((Const *) rightop)->constvalue;
1037 bool arrayisnull = ((Const *) rightop)->constisnull;
1038 ArrayType *arrayval;
1043 arrayval = DatumGetArrayTypeP(arraydatum);
1044 nitems = ArrayGetNItems(ARR_NDIM(arrayval), ARR_DIMS(arrayval));
1048 else if (rightop && IsA(rightop, ArrayExpr))
1050 ArrayExpr *arrayexpr = (ArrayExpr *) rightop;
1052 if (arrayexpr->elements != NIL && !arrayexpr->multidims)
1059 /*****************************************************************************
1060 * Check for "pseudo-constant" clauses
1061 *****************************************************************************/
1064 * is_pseudo_constant_clause
1065 * Detect whether an expression is "pseudo constant", ie, it contains no
1066 * variables of the current query level and no uses of volatile functions.
1067 * Such an expr is not necessarily a true constant: it can still contain
1068 * Params and outer-level Vars, not to mention functions whose results
1069 * may vary from one statement to the next. However, the expr's value
1070 * will be constant over any one scan of the current query, so it can be
1071 * used as, eg, an indexscan key.
1074 is_pseudo_constant_clause(Node *clause)
1077 * We could implement this check in one recursive scan. But since the
1078 * check for volatile functions is both moderately expensive and unlikely
1079 * to fail, it seems better to look for Vars first and only check for
1080 * volatile functions if we find no Vars.
1082 if (!contain_var_clause(clause) &&
1083 !contain_volatile_functions(clause))
1089 * is_pseudo_constant_clause_relids
1090 * Same as above, except caller already has available the var membership
1091 * of the expression; this lets us avoid the contain_var_clause() scan.
1094 is_pseudo_constant_clause_relids(Node *clause, Relids relids)
1096 if (bms_is_empty(relids) &&
1097 !contain_volatile_functions(clause))
1103 /*****************************************************************************
1104 * Tests on clauses of queries
1106 * Possibly this code should go someplace else, since this isn't quite the
1107 * same meaning of "clause" as is used elsewhere in this module. But I can't
1108 * think of a better place for it...
1109 *****************************************************************************/
1112 * Test whether a query uses DISTINCT ON, ie, has a distinct-list that is
1113 * not the same as the set of output columns.
1116 has_distinct_on_clause(Query *query)
1120 /* Is there a DISTINCT clause at all? */
1121 if (query->distinctClause == NIL)
1125 * If the DISTINCT list contains all the nonjunk targetlist items, and
1126 * nothing else (ie, no junk tlist items), then it's a simple DISTINCT,
1127 * else it's DISTINCT ON. We do not require the lists to be in the same
1128 * order (since the parser may have adjusted the DISTINCT clause ordering
1129 * to agree with ORDER BY). Furthermore, a non-DISTINCT junk tlist item
1130 * that is in the sortClause is also evidence of DISTINCT ON, since we
1131 * don't allow ORDER BY on junk tlist items when plain DISTINCT is used.
1133 * This code assumes that the DISTINCT list is valid, ie, all its entries
1134 * match some entry of the tlist.
1136 foreach(l, query->targetList)
1138 TargetEntry *tle = (TargetEntry *) lfirst(l);
1140 if (tle->ressortgroupref == 0)
1143 continue; /* we can ignore unsorted junk cols */
1144 return true; /* definitely not in DISTINCT list */
1146 if (targetIsInSortList(tle, query->distinctClause))
1149 return true; /* junk TLE in DISTINCT means DISTINCT ON */
1150 /* else this TLE is okay, keep looking */
1154 /* This TLE is not in DISTINCT list */
1156 return true; /* non-junk, non-DISTINCT, so DISTINCT ON */
1157 if (targetIsInSortList(tle, query->sortClause))
1158 return true; /* sorted, non-distinct junk */
1159 /* unsorted junk is okay, keep looking */
1162 /* It's a simple DISTINCT */
1167 * Test whether a query uses simple DISTINCT, ie, has a distinct-list that
1168 * is the same as the set of output columns.
1171 has_distinct_clause(Query *query)
1173 /* Is there a DISTINCT clause at all? */
1174 if (query->distinctClause == NIL)
1177 /* It's DISTINCT if it's not DISTINCT ON */
1178 return !has_distinct_on_clause(query);
1182 /*****************************************************************************
1184 * General clause-manipulating routines *
1186 *****************************************************************************/
1190 * (formerly clause_relids)
1192 * Returns the number of different relations referenced in 'clause'.
1195 NumRelids(Node *clause)
1197 Relids varnos = pull_varnos(clause);
1198 int result = bms_num_members(varnos);
1205 * CommuteOpExpr: commute a binary operator clause
1207 * XXX the clause is destructively modified!
1210 CommuteOpExpr(OpExpr *clause)
1215 /* Sanity checks: caller is at fault if these fail */
1216 if (!is_opclause(clause) ||
1217 list_length(clause->args) != 2)
1218 elog(ERROR, "cannot commute non-binary-operator clause");
1220 opoid = get_commutator(clause->opno);
1222 if (!OidIsValid(opoid))
1223 elog(ERROR, "could not find commutator for operator %u",
1227 * modify the clause in-place!
1229 clause->opno = opoid;
1230 clause->opfuncid = InvalidOid;
1231 /* opresulttype and opretset are assumed not to change */
1233 temp = linitial(clause->args);
1234 linitial(clause->args) = lsecond(clause->args);
1235 lsecond(clause->args) = temp;
1239 * CommuteRowCompareExpr: commute a RowCompareExpr clause
1241 * XXX the clause is destructively modified!
1244 CommuteRowCompareExpr(RowCompareExpr *clause)
1250 /* Sanity checks: caller is at fault if these fail */
1251 if (!IsA(clause, RowCompareExpr))
1252 elog(ERROR, "expected a RowCompareExpr");
1254 /* Build list of commuted operators */
1256 foreach(l, clause->opnos)
1258 Oid opoid = lfirst_oid(l);
1260 opoid = get_commutator(opoid);
1261 if (!OidIsValid(opoid))
1262 elog(ERROR, "could not find commutator for operator %u",
1264 newops = lappend_oid(newops, opoid);
1268 * modify the clause in-place!
1270 switch (clause->rctype)
1273 clause->rctype = ROWCOMPARE_GT;
1276 clause->rctype = ROWCOMPARE_GE;
1279 clause->rctype = ROWCOMPARE_LE;
1282 clause->rctype = ROWCOMPARE_LT;
1285 elog(ERROR, "unexpected RowCompare type: %d",
1286 (int) clause->rctype);
1290 clause->opnos = newops;
1292 * Note: we don't bother to update the opclasses list, but just set
1293 * it to empty. This is OK since this routine is currently only used
1294 * for index quals, and the index machinery won't use the opclass
1295 * information. The original opclass list is NOT valid if we have
1296 * commuted any cross-type comparisons, so don't leave it in place.
1298 clause->opclasses = NIL; /* XXX */
1300 temp = clause->largs;
1301 clause->largs = clause->rargs;
1302 clause->rargs = temp;
1306 * strip_implicit_coercions: remove implicit coercions at top level of tree
1308 * Note: there isn't any useful thing we can do with a RowExpr here, so
1309 * just return it unchanged, even if it's marked as an implicit coercion.
1312 strip_implicit_coercions(Node *node)
1316 if (IsA(node, FuncExpr))
1318 FuncExpr *f = (FuncExpr *) node;
1320 if (f->funcformat == COERCE_IMPLICIT_CAST)
1321 return strip_implicit_coercions(linitial(f->args));
1323 else if (IsA(node, RelabelType))
1325 RelabelType *r = (RelabelType *) node;
1327 if (r->relabelformat == COERCE_IMPLICIT_CAST)
1328 return strip_implicit_coercions((Node *) r->arg);
1330 else if (IsA(node, ConvertRowtypeExpr))
1332 ConvertRowtypeExpr *c = (ConvertRowtypeExpr *) node;
1334 if (c->convertformat == COERCE_IMPLICIT_CAST)
1335 return strip_implicit_coercions((Node *) c->arg);
1337 else if (IsA(node, CoerceToDomain))
1339 CoerceToDomain *c = (CoerceToDomain *) node;
1341 if (c->coercionformat == COERCE_IMPLICIT_CAST)
1342 return strip_implicit_coercions((Node *) c->arg);
1348 * set_coercionform_dontcare: set all CoercionForm fields to COERCE_DONTCARE
1350 * This is used to make index expressions and index predicates more easily
1351 * comparable to clauses of queries. CoercionForm is not semantically
1352 * significant (for cases where it does matter, the significant info is
1353 * coded into the coercion function arguments) so we can ignore it during
1354 * comparisons. Thus, for example, an index on "foo::int4" can match an
1355 * implicit coercion to int4.
1357 * Caution: the passed expression tree is modified in-place.
1360 set_coercionform_dontcare(Node *node)
1362 (void) set_coercionform_dontcare_walker(node, NULL);
1366 set_coercionform_dontcare_walker(Node *node, void *context)
1370 if (IsA(node, FuncExpr))
1371 ((FuncExpr *) node)->funcformat = COERCE_DONTCARE;
1372 else if (IsA(node, RelabelType))
1373 ((RelabelType *) node)->relabelformat = COERCE_DONTCARE;
1374 else if (IsA(node, ConvertRowtypeExpr))
1375 ((ConvertRowtypeExpr *) node)->convertformat = COERCE_DONTCARE;
1376 else if (IsA(node, RowExpr))
1377 ((RowExpr *) node)->row_format = COERCE_DONTCARE;
1378 else if (IsA(node, CoerceToDomain))
1379 ((CoerceToDomain *) node)->coercionformat = COERCE_DONTCARE;
1380 return expression_tree_walker(node, set_coercionform_dontcare_walker,
1385 * Helper for eval_const_expressions: check that datatype of an attribute
1386 * is still what it was when the expression was parsed. This is needed to
1387 * guard against improper simplification after ALTER COLUMN TYPE. (XXX we
1388 * may well need to make similar checks elsewhere?)
1391 rowtype_field_matches(Oid rowtypeid, int fieldnum,
1392 Oid expectedtype, int32 expectedtypmod)
1395 Form_pg_attribute attr;
1397 /* No issue for RECORD, since there is no way to ALTER such a type */
1398 if (rowtypeid == RECORDOID)
1400 tupdesc = lookup_rowtype_tupdesc(rowtypeid, -1);
1401 if (fieldnum <= 0 || fieldnum > tupdesc->natts)
1403 ReleaseTupleDesc(tupdesc);
1406 attr = tupdesc->attrs[fieldnum - 1];
1407 if (attr->attisdropped ||
1408 attr->atttypid != expectedtype ||
1409 attr->atttypmod != expectedtypmod)
1411 ReleaseTupleDesc(tupdesc);
1414 ReleaseTupleDesc(tupdesc);
1419 /*--------------------
1420 * eval_const_expressions
1422 * Reduce any recognizably constant subexpressions of the given
1423 * expression tree, for example "2 + 2" => "4". More interestingly,
1424 * we can reduce certain boolean expressions even when they contain
1425 * non-constant subexpressions: "x OR true" => "true" no matter what
1426 * the subexpression x is. (XXX We assume that no such subexpression
1427 * will have important side-effects, which is not necessarily a good
1428 * assumption in the presence of user-defined functions; do we need a
1429 * pg_proc flag that prevents discarding the execution of a function?)
1431 * We do understand that certain functions may deliver non-constant
1432 * results even with constant inputs, "nextval()" being the classic
1433 * example. Functions that are not marked "immutable" in pg_proc
1434 * will not be pre-evaluated here, although we will reduce their
1435 * arguments as far as possible.
1437 * We assume that the tree has already been type-checked and contains
1438 * only operators and functions that are reasonable to try to execute.
1440 * NOTE: the planner assumes that this will always flatten nested AND and
1441 * OR clauses into N-argument form. See comments in prepqual.c.
1442 *--------------------
1445 eval_const_expressions(Node *node)
1447 eval_const_expressions_context context;
1449 context.active_fns = NIL; /* nothing being recursively simplified */
1450 context.case_val = NULL; /* no CASE being examined */
1451 context.estimate = false; /* safe transformations only */
1452 return eval_const_expressions_mutator(node, &context);
1455 /*--------------------
1456 * estimate_expression_value
1458 * This function attempts to estimate the value of an expression for
1459 * planning purposes. It is in essence a more aggressive version of
1460 * eval_const_expressions(): we will perform constant reductions that are
1461 * not necessarily 100% safe, but are reasonable for estimation purposes.
1463 * Currently the extra steps that are taken in this mode are:
1464 * 1. Substitute values for Params, where a bound Param value has been made
1465 * available by the caller of planner().
1466 * 2. Fold stable, as well as immutable, functions to constants.
1467 *--------------------
1470 estimate_expression_value(Node *node)
1472 eval_const_expressions_context context;
1474 context.active_fns = NIL; /* nothing being recursively simplified */
1475 context.case_val = NULL; /* no CASE being examined */
1476 context.estimate = true; /* unsafe transformations OK */
1477 return eval_const_expressions_mutator(node, &context);
1481 eval_const_expressions_mutator(Node *node,
1482 eval_const_expressions_context *context)
1486 if (IsA(node, Param))
1488 Param *param = (Param *) node;
1490 /* OK to try to substitute value? */
1491 if (context->estimate && param->paramkind == PARAM_EXTERN &&
1492 PlannerBoundParamList != NULL)
1494 /* Look to see if we've been given a value for this Param */
1495 if (param->paramid > 0 &&
1496 param->paramid <= PlannerBoundParamList->numParams)
1498 ParamExternData *prm = &PlannerBoundParamList->params[param->paramid - 1];
1500 if (OidIsValid(prm->ptype))
1503 * Found it, so return a Const representing the param
1504 * value. Note that we don't copy pass-by-ref datatypes,
1505 * so the Const will only be valid as long as the bound
1506 * parameter list exists. This is okay for intended uses
1507 * of estimate_expression_value().
1512 Assert(prm->ptype == param->paramtype);
1513 get_typlenbyval(param->paramtype, &typLen, &typByVal);
1514 return (Node *) makeConst(param->paramtype,
1522 /* Not replaceable, so just copy the Param (no need to recurse) */
1523 return (Node *) copyObject(param);
1525 if (IsA(node, FuncExpr))
1527 FuncExpr *expr = (FuncExpr *) node;
1533 * Reduce constants in the FuncExpr's arguments. We know args is
1534 * either NIL or a List node, so we can call expression_tree_mutator
1535 * directly rather than recursing to self.
1537 args = (List *) expression_tree_mutator((Node *) expr->args,
1538 eval_const_expressions_mutator,
1542 * Code for op/func reduction is pretty bulky, so split it out as a
1543 * separate function.
1545 simple = simplify_function(expr->funcid, expr->funcresulttype, args,
1547 if (simple) /* successfully simplified it */
1548 return (Node *) simple;
1551 * The expression cannot be simplified any further, so build and
1552 * return a replacement FuncExpr node using the possibly-simplified
1555 newexpr = makeNode(FuncExpr);
1556 newexpr->funcid = expr->funcid;
1557 newexpr->funcresulttype = expr->funcresulttype;
1558 newexpr->funcretset = expr->funcretset;
1559 newexpr->funcformat = expr->funcformat;
1560 newexpr->args = args;
1561 return (Node *) newexpr;
1563 if (IsA(node, OpExpr))
1565 OpExpr *expr = (OpExpr *) node;
1571 * Reduce constants in the OpExpr's arguments. We know args is either
1572 * NIL or a List node, so we can call expression_tree_mutator directly
1573 * rather than recursing to self.
1575 args = (List *) expression_tree_mutator((Node *) expr->args,
1576 eval_const_expressions_mutator,
1580 * Need to get OID of underlying function. Okay to scribble on input
1586 * Code for op/func reduction is pretty bulky, so split it out as a
1587 * separate function.
1589 simple = simplify_function(expr->opfuncid, expr->opresulttype, args,
1591 if (simple) /* successfully simplified it */
1592 return (Node *) simple;
1595 * If the operator is boolean equality, we know how to simplify cases
1596 * involving one constant and one non-constant argument.
1598 if (expr->opno == BooleanEqualOperator)
1600 simple = simplify_boolean_equality(args);
1601 if (simple) /* successfully simplified it */
1602 return (Node *) simple;
1606 * The expression cannot be simplified any further, so build and
1607 * return a replacement OpExpr node using the possibly-simplified
1610 newexpr = makeNode(OpExpr);
1611 newexpr->opno = expr->opno;
1612 newexpr->opfuncid = expr->opfuncid;
1613 newexpr->opresulttype = expr->opresulttype;
1614 newexpr->opretset = expr->opretset;
1615 newexpr->args = args;
1616 return (Node *) newexpr;
1618 if (IsA(node, DistinctExpr))
1620 DistinctExpr *expr = (DistinctExpr *) node;
1623 bool has_null_input = false;
1624 bool all_null_input = true;
1625 bool has_nonconst_input = false;
1627 DistinctExpr *newexpr;
1630 * Reduce constants in the DistinctExpr's arguments. We know args is
1631 * either NIL or a List node, so we can call expression_tree_mutator
1632 * directly rather than recursing to self.
1634 args = (List *) expression_tree_mutator((Node *) expr->args,
1635 eval_const_expressions_mutator,
1639 * We must do our own check for NULLs because DistinctExpr has
1640 * different results for NULL input than the underlying operator does.
1644 if (IsA(lfirst(arg), Const))
1646 has_null_input |= ((Const *) lfirst(arg))->constisnull;
1647 all_null_input &= ((Const *) lfirst(arg))->constisnull;
1650 has_nonconst_input = true;
1653 /* all constants? then can optimize this out */
1654 if (!has_nonconst_input)
1656 /* all nulls? then not distinct */
1658 return makeBoolConst(false, false);
1660 /* one null? then distinct */
1662 return makeBoolConst(true, false);
1664 /* otherwise try to evaluate the '=' operator */
1665 /* (NOT okay to try to inline it, though!) */
1668 * Need to get OID of underlying function. Okay to scribble on
1669 * input to this extent.
1671 set_opfuncid((OpExpr *) expr); /* rely on struct equivalence */
1674 * Code for op/func reduction is pretty bulky, so split it out as
1675 * a separate function.
1677 simple = simplify_function(expr->opfuncid, expr->opresulttype,
1678 args, false, context);
1679 if (simple) /* successfully simplified it */
1682 * Since the underlying operator is "=", must negate its
1685 Const *csimple = (Const *) simple;
1687 Assert(IsA(csimple, Const));
1688 csimple->constvalue =
1689 BoolGetDatum(!DatumGetBool(csimple->constvalue));
1690 return (Node *) csimple;
1695 * The expression cannot be simplified any further, so build and
1696 * return a replacement DistinctExpr node using the
1697 * possibly-simplified arguments.
1699 newexpr = makeNode(DistinctExpr);
1700 newexpr->opno = expr->opno;
1701 newexpr->opfuncid = expr->opfuncid;
1702 newexpr->opresulttype = expr->opresulttype;
1703 newexpr->opretset = expr->opretset;
1704 newexpr->args = args;
1705 return (Node *) newexpr;
1707 if (IsA(node, BoolExpr))
1709 BoolExpr *expr = (BoolExpr *) node;
1711 switch (expr->boolop)
1716 bool haveNull = false;
1717 bool forceTrue = false;
1719 newargs = simplify_or_arguments(expr->args, context,
1720 &haveNull, &forceTrue);
1722 return makeBoolConst(true, false);
1724 newargs = lappend(newargs, makeBoolConst(false, true));
1725 /* If all the inputs are FALSE, result is FALSE */
1727 return makeBoolConst(false, false);
1728 /* If only one nonconst-or-NULL input, it's the result */
1729 if (list_length(newargs) == 1)
1730 return (Node *) linitial(newargs);
1731 /* Else we still need an OR node */
1732 return (Node *) make_orclause(newargs);
1737 bool haveNull = false;
1738 bool forceFalse = false;
1740 newargs = simplify_and_arguments(expr->args, context,
1741 &haveNull, &forceFalse);
1743 return makeBoolConst(false, false);
1745 newargs = lappend(newargs, makeBoolConst(false, true));
1746 /* If all the inputs are TRUE, result is TRUE */
1748 return makeBoolConst(true, false);
1749 /* If only one nonconst-or-NULL input, it's the result */
1750 if (list_length(newargs) == 1)
1751 return (Node *) linitial(newargs);
1752 /* Else we still need an AND node */
1753 return (Node *) make_andclause(newargs);
1759 Assert(list_length(expr->args) == 1);
1760 arg = eval_const_expressions_mutator(linitial(expr->args),
1762 if (IsA(arg, Const))
1764 Const *const_input = (Const *) arg;
1766 /* NOT NULL => NULL */
1767 if (const_input->constisnull)
1768 return makeBoolConst(false, true);
1769 /* otherwise pretty easy */
1770 return makeBoolConst(!DatumGetBool(const_input->constvalue),
1773 else if (not_clause(arg))
1775 /* Cancel NOT/NOT */
1776 return (Node *) get_notclausearg((Expr *) arg);
1778 /* Else we still need a NOT node */
1779 return (Node *) make_notclause((Expr *) arg);
1782 elog(ERROR, "unrecognized boolop: %d",
1783 (int) expr->boolop);
1787 if (IsA(node, SubPlan))
1790 * Return a SubPlan unchanged --- too late to do anything with it.
1792 * XXX should we ereport() here instead? Probably this routine should
1793 * never be invoked after SubPlan creation.
1797 if (IsA(node, RelabelType))
1800 * If we can simplify the input to a constant, then we don't need the
1801 * RelabelType node anymore: just change the type field of the Const
1802 * node. Otherwise, must copy the RelabelType node.
1804 RelabelType *relabel = (RelabelType *) node;
1807 arg = eval_const_expressions_mutator((Node *) relabel->arg,
1811 * If we find stacked RelabelTypes (eg, from foo :: int :: oid) we can
1812 * discard all but the top one.
1814 while (arg && IsA(arg, RelabelType))
1815 arg = (Node *) ((RelabelType *) arg)->arg;
1817 if (arg && IsA(arg, Const))
1819 Const *con = (Const *) arg;
1821 con->consttype = relabel->resulttype;
1824 * relabel's resulttypmod is discarded, which is OK for now; if
1825 * the type actually needs a runtime length coercion then there
1826 * should be a function call to do it just above this node.
1828 return (Node *) con;
1832 RelabelType *newrelabel = makeNode(RelabelType);
1834 newrelabel->arg = (Expr *) arg;
1835 newrelabel->resulttype = relabel->resulttype;
1836 newrelabel->resulttypmod = relabel->resulttypmod;
1837 return (Node *) newrelabel;
1840 if (IsA(node, CaseExpr))
1843 * CASE expressions can be simplified if there are constant
1844 * condition clauses:
1845 * FALSE (or NULL): drop the alternative
1846 * TRUE: drop all remaining alternatives
1847 * If the first non-FALSE alternative is a constant TRUE, we can
1848 * simplify the entire CASE to that alternative's expression.
1849 * If there are no non-FALSE alternatives, we simplify the entire
1850 * CASE to the default result (ELSE result).
1852 * If we have a simple-form CASE with constant test expression,
1853 * we substitute the constant value for contained CaseTestExpr
1854 * placeholder nodes, so that we have the opportunity to reduce
1855 * constant test conditions. For example this allows
1856 * CASE 0 WHEN 0 THEN 1 ELSE 1/0 END
1857 * to reduce to 1 rather than drawing a divide-by-0 error.
1860 CaseExpr *caseexpr = (CaseExpr *) node;
1862 Node *save_case_val;
1865 bool const_true_cond;
1866 Node *defresult = NULL;
1869 /* Simplify the test expression, if any */
1870 newarg = eval_const_expressions_mutator((Node *) caseexpr->arg,
1873 /* Set up for contained CaseTestExpr nodes */
1874 save_case_val = context->case_val;
1875 if (newarg && IsA(newarg, Const))
1876 context->case_val = newarg;
1878 context->case_val = NULL;
1880 /* Simplify the WHEN clauses */
1882 const_true_cond = false;
1883 foreach(arg, caseexpr->args)
1885 CaseWhen *oldcasewhen = (CaseWhen *) lfirst(arg);
1889 Assert(IsA(oldcasewhen, CaseWhen));
1891 /* Simplify this alternative's test condition */
1893 eval_const_expressions_mutator((Node *) oldcasewhen->expr,
1897 * If the test condition is constant FALSE (or NULL), then drop
1898 * this WHEN clause completely, without processing the result.
1900 if (casecond && IsA(casecond, Const))
1902 Const *const_input = (Const *) casecond;
1904 if (const_input->constisnull ||
1905 !DatumGetBool(const_input->constvalue))
1906 continue; /* drop alternative with FALSE condition */
1907 /* Else it's constant TRUE */
1908 const_true_cond = true;
1911 /* Simplify this alternative's result value */
1913 eval_const_expressions_mutator((Node *) oldcasewhen->result,
1916 /* If non-constant test condition, emit a new WHEN node */
1917 if (!const_true_cond)
1919 CaseWhen *newcasewhen = makeNode(CaseWhen);
1921 newcasewhen->expr = (Expr *) casecond;
1922 newcasewhen->result = (Expr *) caseresult;
1923 newargs = lappend(newargs, newcasewhen);
1928 * Found a TRUE condition, so none of the remaining alternatives
1929 * can be reached. We treat the result as the default result.
1931 defresult = caseresult;
1935 /* Simplify the default result, unless we replaced it above */
1936 if (!const_true_cond)
1938 eval_const_expressions_mutator((Node *) caseexpr->defresult,
1941 context->case_val = save_case_val;
1943 /* If no non-FALSE alternatives, CASE reduces to the default result */
1946 /* Otherwise we need a new CASE node */
1947 newcase = makeNode(CaseExpr);
1948 newcase->casetype = caseexpr->casetype;
1949 newcase->arg = (Expr *) newarg;
1950 newcase->args = newargs;
1951 newcase->defresult = (Expr *) defresult;
1952 return (Node *) newcase;
1954 if (IsA(node, CaseTestExpr))
1957 * If we know a constant test value for the current CASE construct,
1958 * substitute it for the placeholder. Else just return the
1959 * placeholder as-is.
1961 if (context->case_val)
1962 return copyObject(context->case_val);
1964 return copyObject(node);
1966 if (IsA(node, ArrayExpr))
1968 ArrayExpr *arrayexpr = (ArrayExpr *) node;
1969 ArrayExpr *newarray;
1970 bool all_const = true;
1975 foreach(element, arrayexpr->elements)
1979 e = eval_const_expressions_mutator((Node *) lfirst(element),
1983 newelems = lappend(newelems, e);
1986 newarray = makeNode(ArrayExpr);
1987 newarray->array_typeid = arrayexpr->array_typeid;
1988 newarray->element_typeid = arrayexpr->element_typeid;
1989 newarray->elements = newelems;
1990 newarray->multidims = arrayexpr->multidims;
1993 return (Node *) evaluate_expr((Expr *) newarray,
1994 newarray->array_typeid);
1996 return (Node *) newarray;
1998 if (IsA(node, CoalesceExpr))
2000 CoalesceExpr *coalesceexpr = (CoalesceExpr *) node;
2001 CoalesceExpr *newcoalesce;
2006 foreach(arg, coalesceexpr->args)
2010 e = eval_const_expressions_mutator((Node *) lfirst(arg),
2014 * We can remove null constants from the list. For a non-null
2015 * constant, if it has not been preceded by any other
2016 * non-null-constant expressions then that is the result.
2020 if (((Const *) e)->constisnull)
2021 continue; /* drop null constant */
2023 return e; /* first expr */
2025 newargs = lappend(newargs, e);
2028 /* If all the arguments were constant null, the result is just null */
2030 return (Node *) makeNullConst(coalesceexpr->coalescetype);
2032 newcoalesce = makeNode(CoalesceExpr);
2033 newcoalesce->coalescetype = coalesceexpr->coalescetype;
2034 newcoalesce->args = newargs;
2035 return (Node *) newcoalesce;
2037 if (IsA(node, FieldSelect))
2040 * We can optimize field selection from a whole-row Var into a simple
2041 * Var. (This case won't be generated directly by the parser, because
2042 * ParseComplexProjection short-circuits it. But it can arise while
2043 * simplifying functions.) Also, we can optimize field selection from
2044 * a RowExpr construct.
2046 * We must however check that the declared type of the field is still
2047 * the same as when the FieldSelect was created --- this can change if
2048 * someone did ALTER COLUMN TYPE on the rowtype.
2050 FieldSelect *fselect = (FieldSelect *) node;
2051 FieldSelect *newfselect;
2054 arg = eval_const_expressions_mutator((Node *) fselect->arg,
2056 if (arg && IsA(arg, Var) &&
2057 ((Var *) arg)->varattno == InvalidAttrNumber)
2059 if (rowtype_field_matches(((Var *) arg)->vartype,
2061 fselect->resulttype,
2062 fselect->resulttypmod))
2063 return (Node *) makeVar(((Var *) arg)->varno,
2065 fselect->resulttype,
2066 fselect->resulttypmod,
2067 ((Var *) arg)->varlevelsup);
2069 if (arg && IsA(arg, RowExpr))
2071 RowExpr *rowexpr = (RowExpr *) arg;
2073 if (fselect->fieldnum > 0 &&
2074 fselect->fieldnum <= list_length(rowexpr->args))
2076 Node *fld = (Node *) list_nth(rowexpr->args,
2077 fselect->fieldnum - 1);
2079 if (rowtype_field_matches(rowexpr->row_typeid,
2081 fselect->resulttype,
2082 fselect->resulttypmod) &&
2083 fselect->resulttype == exprType(fld) &&
2084 fselect->resulttypmod == exprTypmod(fld))
2088 newfselect = makeNode(FieldSelect);
2089 newfselect->arg = (Expr *) arg;
2090 newfselect->fieldnum = fselect->fieldnum;
2091 newfselect->resulttype = fselect->resulttype;
2092 newfselect->resulttypmod = fselect->resulttypmod;
2093 return (Node *) newfselect;
2095 if (IsA(node, BooleanTest))
2097 BooleanTest *btest = (BooleanTest *) node;
2098 BooleanTest *newbtest;
2101 arg = eval_const_expressions_mutator((Node *) btest->arg,
2103 if (arg && IsA(arg, Const))
2105 Const *carg = (Const *) arg;
2108 switch (btest->booltesttype)
2111 result = (!carg->constisnull &&
2112 DatumGetBool(carg->constvalue));
2115 result = (carg->constisnull ||
2116 !DatumGetBool(carg->constvalue));
2119 result = (!carg->constisnull &&
2120 !DatumGetBool(carg->constvalue));
2123 result = (carg->constisnull ||
2124 DatumGetBool(carg->constvalue));
2127 result = carg->constisnull;
2129 case IS_NOT_UNKNOWN:
2130 result = !carg->constisnull;
2133 elog(ERROR, "unrecognized booltesttype: %d",
2134 (int) btest->booltesttype);
2135 result = false; /* keep compiler quiet */
2139 return makeBoolConst(result, false);
2142 newbtest = makeNode(BooleanTest);
2143 newbtest->arg = (Expr *) arg;
2144 newbtest->booltesttype = btest->booltesttype;
2145 return (Node *) newbtest;
2149 * For any node type not handled above, we recurse using
2150 * expression_tree_mutator, which will copy the node unchanged but try to
2151 * simplify its arguments (if any) using this routine. For example: we
2152 * cannot eliminate an ArrayRef node, but we might be able to simplify
2153 * constant expressions in its subscripts.
2155 return expression_tree_mutator(node, eval_const_expressions_mutator,
2160 * Subroutine for eval_const_expressions: process arguments of an OR clause
2162 * This includes flattening of nested ORs as well as recursion to
2163 * eval_const_expressions to simplify the OR arguments.
2165 * After simplification, OR arguments are handled as follows:
2166 * non constant: keep
2167 * FALSE: drop (does not affect result)
2168 * TRUE: force result to TRUE
2169 * NULL: keep only one
2170 * We must keep one NULL input because ExecEvalOr returns NULL when no input
2171 * is TRUE and at least one is NULL. We don't actually include the NULL
2172 * here, that's supposed to be done by the caller.
2174 * The output arguments *haveNull and *forceTrue must be initialized FALSE
2175 * by the caller. They will be set TRUE if a null constant or true constant,
2176 * respectively, is detected anywhere in the argument list.
2179 simplify_or_arguments(List *args,
2180 eval_const_expressions_context *context,
2181 bool *haveNull, bool *forceTrue)
2183 List *newargs = NIL;
2184 List *unprocessed_args;
2187 * Since the parser considers OR to be a binary operator, long OR lists
2188 * become deeply nested expressions. We must flatten these into long
2189 * argument lists of a single OR operator. To avoid blowing out the stack
2190 * with recursion of eval_const_expressions, we resort to some tenseness
2191 * here: we keep a list of not-yet-processed inputs, and handle flattening
2192 * of nested ORs by prepending to the to-do list instead of recursing.
2194 unprocessed_args = list_copy(args);
2195 while (unprocessed_args)
2197 Node *arg = (Node *) linitial(unprocessed_args);
2199 unprocessed_args = list_delete_first(unprocessed_args);
2201 /* flatten nested ORs as per above comment */
2204 List *subargs = list_copy(((BoolExpr *) arg)->args);
2206 /* overly tense code to avoid leaking unused list header */
2207 if (!unprocessed_args)
2208 unprocessed_args = subargs;
2211 List *oldhdr = unprocessed_args;
2213 unprocessed_args = list_concat(subargs, unprocessed_args);
2219 /* If it's not an OR, simplify it */
2220 arg = eval_const_expressions_mutator(arg, context);
2223 * It is unlikely but not impossible for simplification of a non-OR
2224 * clause to produce an OR. Recheck, but don't be too tense about it
2225 * since it's not a mainstream case. In particular we don't worry
2226 * about const-simplifying the input twice.
2230 List *subargs = list_copy(((BoolExpr *) arg)->args);
2232 unprocessed_args = list_concat(subargs, unprocessed_args);
2237 * OK, we have a const-simplified non-OR argument. Process it per
2240 if (IsA(arg, Const))
2242 Const *const_input = (Const *) arg;
2244 if (const_input->constisnull)
2246 else if (DatumGetBool(const_input->constvalue))
2251 * Once we detect a TRUE result we can just exit the loop
2252 * immediately. However, if we ever add a notion of
2253 * non-removable functions, we'd need to keep scanning.
2257 /* otherwise, we can drop the constant-false input */
2261 /* else emit the simplified arg into the result list */
2262 newargs = lappend(newargs, arg);
2269 * Subroutine for eval_const_expressions: process arguments of an AND clause
2271 * This includes flattening of nested ANDs as well as recursion to
2272 * eval_const_expressions to simplify the AND arguments.
2274 * After simplification, AND arguments are handled as follows:
2275 * non constant: keep
2276 * TRUE: drop (does not affect result)
2277 * FALSE: force result to FALSE
2278 * NULL: keep only one
2279 * We must keep one NULL input because ExecEvalAnd returns NULL when no input
2280 * is FALSE and at least one is NULL. We don't actually include the NULL
2281 * here, that's supposed to be done by the caller.
2283 * The output arguments *haveNull and *forceFalse must be initialized FALSE
2284 * by the caller. They will be set TRUE if a null constant or false constant,
2285 * respectively, is detected anywhere in the argument list.
2288 simplify_and_arguments(List *args,
2289 eval_const_expressions_context *context,
2290 bool *haveNull, bool *forceFalse)
2292 List *newargs = NIL;
2293 List *unprocessed_args;
2295 /* See comments in simplify_or_arguments */
2296 unprocessed_args = list_copy(args);
2297 while (unprocessed_args)
2299 Node *arg = (Node *) linitial(unprocessed_args);
2301 unprocessed_args = list_delete_first(unprocessed_args);
2303 /* flatten nested ANDs as per above comment */
2304 if (and_clause(arg))
2306 List *subargs = list_copy(((BoolExpr *) arg)->args);
2308 /* overly tense code to avoid leaking unused list header */
2309 if (!unprocessed_args)
2310 unprocessed_args = subargs;
2313 List *oldhdr = unprocessed_args;
2315 unprocessed_args = list_concat(subargs, unprocessed_args);
2321 /* If it's not an AND, simplify it */
2322 arg = eval_const_expressions_mutator(arg, context);
2325 * It is unlikely but not impossible for simplification of a non-AND
2326 * clause to produce an AND. Recheck, but don't be too tense about it
2327 * since it's not a mainstream case. In particular we don't worry
2328 * about const-simplifying the input twice.
2330 if (and_clause(arg))
2332 List *subargs = list_copy(((BoolExpr *) arg)->args);
2334 unprocessed_args = list_concat(subargs, unprocessed_args);
2339 * OK, we have a const-simplified non-AND argument. Process it per
2342 if (IsA(arg, Const))
2344 Const *const_input = (Const *) arg;
2346 if (const_input->constisnull)
2348 else if (!DatumGetBool(const_input->constvalue))
2353 * Once we detect a FALSE result we can just exit the loop
2354 * immediately. However, if we ever add a notion of
2355 * non-removable functions, we'd need to keep scanning.
2359 /* otherwise, we can drop the constant-true input */
2363 /* else emit the simplified arg into the result list */
2364 newargs = lappend(newargs, arg);
2371 * Subroutine for eval_const_expressions: try to simplify boolean equality
2373 * Input is the list of simplified arguments to the operator.
2374 * Returns a simplified expression if successful, or NULL if cannot
2375 * simplify the expression.
2377 * The idea here is to reduce "x = true" to "x" and "x = false" to "NOT x".
2378 * This is only marginally useful in itself, but doing it in constant folding
2379 * ensures that we will recognize the two forms as being equivalent in, for
2380 * example, partial index matching.
2382 * We come here only if simplify_function has failed; therefore we cannot
2383 * see two constant inputs, nor a constant-NULL input.
2386 simplify_boolean_equality(List *args)
2391 Assert(list_length(args) == 2);
2392 leftop = linitial(args);
2393 rightop = lsecond(args);
2394 if (leftop && IsA(leftop, Const))
2396 Assert(!((Const *) leftop)->constisnull);
2397 if (DatumGetBool(((Const *) leftop)->constvalue))
2398 return rightop; /* true = foo */
2400 return make_notclause(rightop); /* false = foo */
2402 if (rightop && IsA(rightop, Const))
2404 Assert(!((Const *) rightop)->constisnull);
2405 if (DatumGetBool(((Const *) rightop)->constvalue))
2406 return leftop; /* foo = true */
2408 return make_notclause(leftop); /* foo = false */
2414 * Subroutine for eval_const_expressions: try to simplify a function call
2415 * (which might originally have been an operator; we don't care)
2417 * Inputs are the function OID, actual result type OID (which is needed for
2418 * polymorphic functions), and the pre-simplified argument list;
2419 * also the context data for eval_const_expressions.
2421 * Returns a simplified expression if successful, or NULL if cannot
2422 * simplify the function call.
2425 simplify_function(Oid funcid, Oid result_type, List *args,
2427 eval_const_expressions_context *context)
2429 HeapTuple func_tuple;
2433 * We have two strategies for simplification: either execute the function
2434 * to deliver a constant result, or expand in-line the body of the
2435 * function definition (which only works for simple SQL-language
2436 * functions, but that is a common case). In either case we need access
2437 * to the function's pg_proc tuple, so fetch it just once to use in both
2440 func_tuple = SearchSysCache(PROCOID,
2441 ObjectIdGetDatum(funcid),
2443 if (!HeapTupleIsValid(func_tuple))
2444 elog(ERROR, "cache lookup failed for function %u", funcid);
2446 newexpr = evaluate_function(funcid, result_type, args,
2447 func_tuple, context);
2449 if (!newexpr && allow_inline)
2450 newexpr = inline_function(funcid, result_type, args,
2451 func_tuple, context);
2453 ReleaseSysCache(func_tuple);
2459 * evaluate_function: try to pre-evaluate a function call
2461 * We can do this if the function is strict and has any constant-null inputs
2462 * (just return a null constant), or if the function is immutable and has all
2463 * constant inputs (call it and return the result as a Const node). In
2464 * estimation mode we are willing to pre-evaluate stable functions too.
2466 * Returns a simplified expression if successful, or NULL if cannot
2467 * simplify the function.
2470 evaluate_function(Oid funcid, Oid result_type, List *args,
2471 HeapTuple func_tuple,
2472 eval_const_expressions_context *context)
2474 Form_pg_proc funcform = (Form_pg_proc) GETSTRUCT(func_tuple);
2475 bool has_nonconst_input = false;
2476 bool has_null_input = false;
2481 * Can't simplify if it returns a set.
2483 if (funcform->proretset)
2487 * Can't simplify if it returns RECORD. The immediate problem is that it
2488 * will be needing an expected tupdesc which we can't supply here.
2490 * In the case where it has OUT parameters, it could get by without an
2491 * expected tupdesc, but we still have issues: get_expr_result_type()
2492 * doesn't know how to extract type info from a RECORD constant, and in
2493 * the case of a NULL function result there doesn't seem to be any clean
2494 * way to fix that. In view of the likelihood of there being still other
2495 * gotchas, seems best to leave the function call unreduced.
2497 if (funcform->prorettype == RECORDOID)
2501 * Check for constant inputs and especially constant-NULL inputs.
2505 if (IsA(lfirst(arg), Const))
2506 has_null_input |= ((Const *) lfirst(arg))->constisnull;
2508 has_nonconst_input = true;
2512 * If the function is strict and has a constant-NULL input, it will never
2513 * be called at all, so we can replace the call by a NULL constant, even
2514 * if there are other inputs that aren't constant, and even if the
2515 * function is not otherwise immutable.
2517 if (funcform->proisstrict && has_null_input)
2518 return (Expr *) makeNullConst(result_type);
2521 * Otherwise, can simplify only if all inputs are constants. (For a
2522 * non-strict function, constant NULL inputs are treated the same as
2523 * constant non-NULL inputs.)
2525 if (has_nonconst_input)
2529 * Ordinarily we are only allowed to simplify immutable functions. But for
2530 * purposes of estimation, we consider it okay to simplify functions that
2531 * are merely stable; the risk that the result might change from planning
2532 * time to execution time is worth taking in preference to not being able
2533 * to estimate the value at all.
2535 if (funcform->provolatile == PROVOLATILE_IMMUTABLE)
2537 else if (context->estimate && funcform->provolatile == PROVOLATILE_STABLE)
2543 * OK, looks like we can simplify this operator/function.
2545 * Build a new FuncExpr node containing the already-simplified arguments.
2547 newexpr = makeNode(FuncExpr);
2548 newexpr->funcid = funcid;
2549 newexpr->funcresulttype = result_type;
2550 newexpr->funcretset = false;
2551 newexpr->funcformat = COERCE_DONTCARE; /* doesn't matter */
2552 newexpr->args = args;
2554 return evaluate_expr((Expr *) newexpr, result_type);
2558 * inline_function: try to expand a function call inline
2560 * If the function is a sufficiently simple SQL-language function
2561 * (just "SELECT expression"), then we can inline it and avoid the rather
2562 * high per-call overhead of SQL functions. Furthermore, this can expose
2563 * opportunities for constant-folding within the function expression.
2565 * We have to beware of some special cases however. A directly or
2566 * indirectly recursive function would cause us to recurse forever,
2567 * so we keep track of which functions we are already expanding and
2568 * do not re-expand them. Also, if a parameter is used more than once
2569 * in the SQL-function body, we require it not to contain any volatile
2570 * functions (volatiles might deliver inconsistent answers) nor to be
2571 * unreasonably expensive to evaluate. The expensiveness check not only
2572 * prevents us from doing multiple evaluations of an expensive parameter
2573 * at runtime, but is a safety value to limit growth of an expression due
2574 * to repeated inlining.
2576 * We must also beware of changing the volatility or strictness status of
2577 * functions by inlining them.
2579 * Returns a simplified expression if successful, or NULL if cannot
2580 * simplify the function.
2583 inline_function(Oid funcid, Oid result_type, List *args,
2584 HeapTuple func_tuple,
2585 eval_const_expressions_context *context)
2587 Form_pg_proc funcform = (Form_pg_proc) GETSTRUCT(func_tuple);
2588 bool polymorphic = false;
2593 MemoryContext oldcxt;
2594 MemoryContext mycxt;
2595 ErrorContextCallback sqlerrcontext;
2596 List *raw_parsetree_list;
2597 List *querytree_list;
2605 * Forget it if the function is not SQL-language or has other showstopper
2606 * properties. (The nargs check is just paranoia.)
2608 if (funcform->prolang != SQLlanguageId ||
2609 funcform->prosecdef ||
2610 funcform->proretset ||
2611 funcform->pronargs != list_length(args))
2614 /* Check for recursive function, and give up trying to expand if so */
2615 if (list_member_oid(context->active_fns, funcid))
2618 /* Check permission to call function (fail later, if not) */
2619 if (pg_proc_aclcheck(funcid, GetUserId(), ACL_EXECUTE) != ACLCHECK_OK)
2623 * Setup error traceback support for ereport(). This is so that we can
2624 * finger the function that bad information came from.
2626 sqlerrcontext.callback = sql_inline_error_callback;
2627 sqlerrcontext.arg = func_tuple;
2628 sqlerrcontext.previous = error_context_stack;
2629 error_context_stack = &sqlerrcontext;
2632 * Make a temporary memory context, so that we don't leak all the stuff
2633 * that parsing might create.
2635 mycxt = AllocSetContextCreate(CurrentMemoryContext,
2637 ALLOCSET_DEFAULT_MINSIZE,
2638 ALLOCSET_DEFAULT_INITSIZE,
2639 ALLOCSET_DEFAULT_MAXSIZE);
2640 oldcxt = MemoryContextSwitchTo(mycxt);
2642 /* Check for polymorphic arguments, and substitute actual arg types */
2643 argtypes = (Oid *) palloc(funcform->pronargs * sizeof(Oid));
2644 memcpy(argtypes, funcform->proargtypes.values,
2645 funcform->pronargs * sizeof(Oid));
2646 for (i = 0; i < funcform->pronargs; i++)
2648 if (argtypes[i] == ANYARRAYOID ||
2649 argtypes[i] == ANYELEMENTOID)
2652 argtypes[i] = exprType((Node *) list_nth(args, i));
2656 if (funcform->prorettype == ANYARRAYOID ||
2657 funcform->prorettype == ANYELEMENTOID)
2660 /* Fetch and parse the function body */
2661 tmp = SysCacheGetAttr(PROCOID,
2663 Anum_pg_proc_prosrc,
2666 elog(ERROR, "null prosrc for function %u", funcid);
2667 src = DatumGetCString(DirectFunctionCall1(textout, tmp));
2670 * We just do parsing and parse analysis, not rewriting, because rewriting
2671 * will not affect table-free-SELECT-only queries, which is all that we
2672 * care about. Also, we can punt as soon as we detect more than one
2673 * command in the function body.
2675 raw_parsetree_list = pg_parse_query(src);
2676 if (list_length(raw_parsetree_list) != 1)
2679 querytree_list = parse_analyze(linitial(raw_parsetree_list), src,
2680 argtypes, funcform->pronargs);
2682 if (list_length(querytree_list) != 1)
2685 querytree = (Query *) linitial(querytree_list);
2688 * The single command must be a simple "SELECT expression".
2690 if (!IsA(querytree, Query) ||
2691 querytree->commandType != CMD_SELECT ||
2692 querytree->resultRelation != 0 ||
2694 querytree->hasAggs ||
2695 querytree->hasSubLinks ||
2696 querytree->rtable ||
2697 querytree->jointree->fromlist ||
2698 querytree->jointree->quals ||
2699 querytree->groupClause ||
2700 querytree->havingQual ||
2701 querytree->distinctClause ||
2702 querytree->sortClause ||
2703 querytree->limitOffset ||
2704 querytree->limitCount ||
2705 querytree->setOperations ||
2706 list_length(querytree->targetList) != 1)
2709 newexpr = (Node *) ((TargetEntry *) linitial(querytree->targetList))->expr;
2712 * If the function has any arguments declared as polymorphic types, then
2713 * it wasn't type-checked at definition time; must do so now. (This will
2714 * raise an error if wrong, but that's okay since the function would fail
2715 * at runtime anyway. Note we do not try this until we have verified that
2716 * no rewriting was needed; that's probably not important, but let's be
2720 (void) check_sql_fn_retval(funcid, result_type, querytree_list, NULL);
2723 * Additional validity checks on the expression. It mustn't return a set,
2724 * and it mustn't be more volatile than the surrounding function (this is
2725 * to avoid breaking hacks that involve pretending a function is immutable
2726 * when it really ain't). If the surrounding function is declared strict,
2727 * then the expression must contain only strict constructs and must use
2728 * all of the function parameters (this is overkill, but an exact analysis
2731 if (expression_returns_set(newexpr))
2734 if (funcform->provolatile == PROVOLATILE_IMMUTABLE &&
2735 contain_mutable_functions(newexpr))
2737 else if (funcform->provolatile == PROVOLATILE_STABLE &&
2738 contain_volatile_functions(newexpr))
2741 if (funcform->proisstrict &&
2742 contain_nonstrict_functions(newexpr))
2746 * We may be able to do it; there are still checks on parameter usage to
2747 * make, but those are most easily done in combination with the actual
2748 * substitution of the inputs. So start building expression with inputs
2751 usecounts = (int *) palloc0(funcform->pronargs * sizeof(int));
2752 newexpr = substitute_actual_parameters(newexpr, funcform->pronargs,
2755 /* Now check for parameter usage */
2759 Node *param = lfirst(arg);
2761 if (usecounts[i] == 0)
2763 /* Param not used at all: uncool if func is strict */
2764 if (funcform->proisstrict)
2767 else if (usecounts[i] != 1)
2769 /* Param used multiple times: uncool if expensive or volatile */
2773 * We define "expensive" as "contains any subplan or more than 10
2774 * operators". Note that the subplan search has to be done
2775 * explicitly, since cost_qual_eval() will barf on unplanned
2778 if (contain_subplans(param))
2780 cost_qual_eval(&eval_cost, list_make1(param));
2781 if (eval_cost.startup + eval_cost.per_tuple >
2782 10 * cpu_operator_cost)
2786 * Check volatility last since this is more expensive than the
2789 if (contain_volatile_functions(param))
2796 * Whew --- we can make the substitution. Copy the modified expression
2797 * out of the temporary memory context, and clean up.
2799 MemoryContextSwitchTo(oldcxt);
2801 newexpr = copyObject(newexpr);
2803 MemoryContextDelete(mycxt);
2806 * Recursively try to simplify the modified expression. Here we must add
2807 * the current function to the context list of active functions.
2809 context->active_fns = lcons_oid(funcid, context->active_fns);
2810 newexpr = eval_const_expressions_mutator(newexpr, context);
2811 context->active_fns = list_delete_first(context->active_fns);
2813 error_context_stack = sqlerrcontext.previous;
2815 return (Expr *) newexpr;
2817 /* Here if func is not inlinable: release temp memory and return NULL */
2819 MemoryContextSwitchTo(oldcxt);
2820 MemoryContextDelete(mycxt);
2821 error_context_stack = sqlerrcontext.previous;
2827 * Replace Param nodes by appropriate actual parameters
2830 substitute_actual_parameters(Node *expr, int nargs, List *args,
2833 substitute_actual_parameters_context context;
2835 context.nargs = nargs;
2836 context.args = args;
2837 context.usecounts = usecounts;
2839 return substitute_actual_parameters_mutator(expr, &context);
2843 substitute_actual_parameters_mutator(Node *node,
2844 substitute_actual_parameters_context *context)
2848 if (IsA(node, Param))
2850 Param *param = (Param *) node;
2852 if (param->paramkind != PARAM_EXTERN)
2853 elog(ERROR, "unexpected paramkind: %d", (int) param->paramkind);
2854 if (param->paramid <= 0 || param->paramid > context->nargs)
2855 elog(ERROR, "invalid paramid: %d", param->paramid);
2857 /* Count usage of parameter */
2858 context->usecounts[param->paramid - 1]++;
2860 /* Select the appropriate actual arg and replace the Param with it */
2861 /* We don't need to copy at this time (it'll get done later) */
2862 return list_nth(context->args, param->paramid - 1);
2864 return expression_tree_mutator(node, substitute_actual_parameters_mutator,
2869 * error context callback to let us supply a call-stack traceback
2872 sql_inline_error_callback(void *arg)
2874 HeapTuple func_tuple = (HeapTuple) arg;
2875 Form_pg_proc funcform = (Form_pg_proc) GETSTRUCT(func_tuple);
2876 int syntaxerrposition;
2878 /* If it's a syntax error, convert to internal syntax error report */
2879 syntaxerrposition = geterrposition();
2880 if (syntaxerrposition > 0)
2886 tmp = SysCacheGetAttr(PROCOID, func_tuple, Anum_pg_proc_prosrc,
2889 elog(ERROR, "null prosrc");
2890 prosrc = DatumGetCString(DirectFunctionCall1(textout, tmp));
2892 internalerrposition(syntaxerrposition);
2893 internalerrquery(prosrc);
2896 errcontext("SQL function \"%s\" during inlining",
2897 NameStr(funcform->proname));
2901 * evaluate_expr: pre-evaluate a constant expression
2903 * We use the executor's routine ExecEvalExpr() to avoid duplication of
2904 * code and ensure we get the same result as the executor would get.
2907 evaluate_expr(Expr *expr, Oid result_type)
2910 ExprState *exprstate;
2911 MemoryContext oldcontext;
2915 bool resultTypByVal;
2918 * To use the executor, we need an EState.
2920 estate = CreateExecutorState();
2922 /* We can use the estate's working context to avoid memory leaks. */
2923 oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
2926 * Prepare expr for execution.
2928 exprstate = ExecPrepareExpr(expr, estate);
2933 * It is OK to use a default econtext because none of the ExecEvalExpr()
2934 * code used in this situation will use econtext. That might seem
2935 * fortuitous, but it's not so unreasonable --- a constant expression does
2936 * not depend on context, by definition, n'est ce pas?
2938 const_val = ExecEvalExprSwitchContext(exprstate,
2939 GetPerTupleExprContext(estate),
2940 &const_is_null, NULL);
2942 /* Get info needed about result datatype */
2943 get_typlenbyval(result_type, &resultTypLen, &resultTypByVal);
2945 /* Get back to outer memory context */
2946 MemoryContextSwitchTo(oldcontext);
2948 /* Must copy result out of sub-context used by expression eval */
2950 const_val = datumCopy(const_val, resultTypByVal, resultTypLen);
2952 /* Release all the junk we just created */
2953 FreeExecutorState(estate);
2956 * Make the constant result node.
2958 return (Expr *) makeConst(result_type, resultTypLen,
2959 const_val, const_is_null,
2965 * Standard expression-tree walking support
2967 * We used to have near-duplicate code in many different routines that
2968 * understood how to recurse through an expression node tree. That was
2969 * a pain to maintain, and we frequently had bugs due to some particular
2970 * routine neglecting to support a particular node type. In most cases,
2971 * these routines only actually care about certain node types, and don't
2972 * care about other types except insofar as they have to recurse through
2973 * non-primitive node types. Therefore, we now provide generic tree-walking
2974 * logic to consolidate the redundant "boilerplate" code. There are
2975 * two versions: expression_tree_walker() and expression_tree_mutator().
2978 /*--------------------
2979 * expression_tree_walker() is designed to support routines that traverse
2980 * a tree in a read-only fashion (although it will also work for routines
2981 * that modify nodes in-place but never add/delete/replace nodes).
2982 * A walker routine should look like this:
2984 * bool my_walker (Node *node, my_struct *context)
2988 * // check for nodes that special work is required for, eg:
2989 * if (IsA(node, Var))
2991 * ... do special actions for Var nodes
2993 * else if (IsA(node, ...))
2995 * ... do special actions for other node types
2997 * // for any node type not specially processed, do:
2998 * return expression_tree_walker(node, my_walker, (void *) context);
3001 * The "context" argument points to a struct that holds whatever context
3002 * information the walker routine needs --- it can be used to return data
3003 * gathered by the walker, too. This argument is not touched by
3004 * expression_tree_walker, but it is passed down to recursive sub-invocations
3005 * of my_walker. The tree walk is started from a setup routine that
3006 * fills in the appropriate context struct, calls my_walker with the top-level
3007 * node of the tree, and then examines the results.
3009 * The walker routine should return "false" to continue the tree walk, or
3010 * "true" to abort the walk and immediately return "true" to the top-level
3011 * caller. This can be used to short-circuit the traversal if the walker
3012 * has found what it came for. "false" is returned to the top-level caller
3013 * iff no invocation of the walker returned "true".
3015 * The node types handled by expression_tree_walker include all those
3016 * normally found in target lists and qualifier clauses during the planning
3017 * stage. In particular, it handles List nodes since a cnf-ified qual clause
3018 * will have List structure at the top level, and it handles TargetEntry nodes
3019 * so that a scan of a target list can be handled without additional code.
3020 * (But only the "expr" part of a TargetEntry is examined, unless the walker
3021 * chooses to process TargetEntry nodes specially.) Also, RangeTblRef,
3022 * FromExpr, JoinExpr, and SetOperationStmt nodes are handled, so that query
3023 * jointrees and setOperation trees can be processed without additional code.
3025 * expression_tree_walker will handle SubLink nodes by recursing normally
3026 * into the "testexpr" subtree (which is an expression belonging to the outer
3027 * plan). It will also call the walker on the sub-Query node; however, when
3028 * expression_tree_walker itself is called on a Query node, it does nothing
3029 * and returns "false". The net effect is that unless the walker does
3030 * something special at a Query node, sub-selects will not be visited during
3031 * an expression tree walk. This is exactly the behavior wanted in many cases
3032 * --- and for those walkers that do want to recurse into sub-selects, special
3033 * behavior is typically needed anyway at the entry to a sub-select (such as
3034 * incrementing a depth counter). A walker that wants to examine sub-selects
3035 * should include code along the lines of:
3037 * if (IsA(node, Query))
3039 * adjust context for subquery;
3040 * result = query_tree_walker((Query *) node, my_walker, context,
3041 * 0); // adjust flags as needed
3042 * restore context if needed;
3046 * query_tree_walker is a convenience routine (see below) that calls the
3047 * walker on all the expression subtrees of the given Query node.
3049 * expression_tree_walker will handle SubPlan nodes by recursing normally
3050 * into the "testexpr" and the "args" list (which are expressions belonging to
3051 * the outer plan). It will not touch the completed subplan, however. Since
3052 * there is no link to the original Query, it is not possible to recurse into
3053 * subselects of an already-planned expression tree. This is OK for current
3054 * uses, but may need to be revisited in future.
3055 *--------------------
3059 expression_tree_walker(Node *node,
3066 * The walker has already visited the current node, and so we need only
3067 * recurse into any sub-nodes it has.
3069 * We assume that the walker is not interested in List nodes per se, so
3070 * when we expect a List we just recurse directly to self without
3071 * bothering to call the walker.
3076 /* Guard against stack overflow due to overly complex expressions */
3077 check_stack_depth();
3079 switch (nodeTag(node))
3084 case T_CoerceToDomainValue:
3085 case T_CaseTestExpr:
3086 case T_SetToDefault:
3088 case T_OuterJoinInfo:
3089 /* primitive node types with no expression subnodes */
3093 Aggref *expr = (Aggref *) node;
3095 if (expression_tree_walker((Node *) expr->args,
3102 ArrayRef *aref = (ArrayRef *) node;
3104 /* recurse directly for upper/lower array index lists */
3105 if (expression_tree_walker((Node *) aref->refupperindexpr,
3108 if (expression_tree_walker((Node *) aref->reflowerindexpr,
3111 /* walker must see the refexpr and refassgnexpr, however */
3112 if (walker(aref->refexpr, context))
3114 if (walker(aref->refassgnexpr, context))
3120 FuncExpr *expr = (FuncExpr *) node;
3122 if (expression_tree_walker((Node *) expr->args,
3129 OpExpr *expr = (OpExpr *) node;
3131 if (expression_tree_walker((Node *) expr->args,
3136 case T_DistinctExpr:
3138 DistinctExpr *expr = (DistinctExpr *) node;
3140 if (expression_tree_walker((Node *) expr->args,
3145 case T_ScalarArrayOpExpr:
3147 ScalarArrayOpExpr *expr = (ScalarArrayOpExpr *) node;
3149 if (expression_tree_walker((Node *) expr->args,
3156 BoolExpr *expr = (BoolExpr *) node;
3158 if (expression_tree_walker((Node *) expr->args,
3165 SubLink *sublink = (SubLink *) node;
3167 if (expression_tree_walker(sublink->testexpr,
3172 * Also invoke the walker on the sublink's Query node, so it
3173 * can recurse into the sub-query if it wants to.
3175 return walker(sublink->subselect, context);
3180 SubPlan *subplan = (SubPlan *) node;
3182 /* recurse into the testexpr, but not into the Plan */
3183 if (expression_tree_walker(subplan->testexpr,
3186 /* also examine args list */
3187 if (expression_tree_walker((Node *) subplan->args,
3193 return walker(((FieldSelect *) node)->arg, context);
3196 FieldStore *fstore = (FieldStore *) node;
3198 if (walker(fstore->arg, context))
3200 if (walker(fstore->newvals, context))
3205 return walker(((RelabelType *) node)->arg, context);
3206 case T_ConvertRowtypeExpr:
3207 return walker(((ConvertRowtypeExpr *) node)->arg, context);
3210 CaseExpr *caseexpr = (CaseExpr *) node;
3212 if (walker(caseexpr->arg, context))
3214 /* we assume walker doesn't care about CaseWhens, either */
3215 foreach(temp, caseexpr->args)
3217 CaseWhen *when = (CaseWhen *) lfirst(temp);
3219 Assert(IsA(when, CaseWhen));
3220 if (walker(when->expr, context))
3222 if (walker(when->result, context))
3225 if (walker(caseexpr->defresult, context))
3230 return walker(((ArrayExpr *) node)->elements, context);
3232 return walker(((RowExpr *) node)->args, context);
3233 case T_RowCompareExpr:
3235 RowCompareExpr *rcexpr = (RowCompareExpr *) node;
3237 if (walker(rcexpr->largs, context))
3239 if (walker(rcexpr->rargs, context))
3243 case T_CoalesceExpr:
3244 return walker(((CoalesceExpr *) node)->args, context);
3246 return walker(((MinMaxExpr *) node)->args, context);
3248 return walker(((NullIfExpr *) node)->args, context);
3250 return walker(((NullTest *) node)->arg, context);
3252 return walker(((BooleanTest *) node)->arg, context);
3253 case T_CoerceToDomain:
3254 return walker(((CoerceToDomain *) node)->arg, context);
3256 return walker(((TargetEntry *) node)->expr, context);
3258 /* Do nothing with a sub-Query, per discussion above */
3261 foreach(temp, (List *) node)
3263 if (walker((Node *) lfirst(temp), context))
3269 FromExpr *from = (FromExpr *) node;
3271 if (walker(from->fromlist, context))
3273 if (walker(from->quals, context))
3279 JoinExpr *join = (JoinExpr *) node;
3281 if (walker(join->larg, context))
3283 if (walker(join->rarg, context))
3285 if (walker(join->quals, context))
3289 * alias clause, using list are deemed uninteresting.
3293 case T_SetOperationStmt:
3295 SetOperationStmt *setop = (SetOperationStmt *) node;
3297 if (walker(setop->larg, context))
3299 if (walker(setop->rarg, context))
3303 case T_InClauseInfo:
3305 InClauseInfo *ininfo = (InClauseInfo *) node;
3307 if (expression_tree_walker((Node *) ininfo->sub_targetlist,
3312 case T_AppendRelInfo:
3314 AppendRelInfo *appinfo = (AppendRelInfo *) node;
3316 if (expression_tree_walker((Node *) appinfo->translated_vars,
3322 elog(ERROR, "unrecognized node type: %d",
3323 (int) nodeTag(node));
3330 * query_tree_walker --- initiate a walk of a Query's expressions
3332 * This routine exists just to reduce the number of places that need to know
3333 * where all the expression subtrees of a Query are. Note it can be used
3334 * for starting a walk at top level of a Query regardless of whether the
3335 * walker intends to descend into subqueries. It is also useful for
3336 * descending into subqueries within a walker.
3338 * Some callers want to suppress visitation of certain items in the sub-Query,
3339 * typically because they need to process them specially, or don't actually
3340 * want to recurse into subqueries. This is supported by the flags argument,
3341 * which is the bitwise OR of flag values to suppress visitation of
3342 * indicated items. (More flag bits may be added as needed.)
3345 query_tree_walker(Query *query,
3350 Assert(query != NULL && IsA(query, Query));
3352 if (walker((Node *) query->targetList, context))
3354 if (walker((Node *) query->returningList, context))
3356 if (walker((Node *) query->jointree, context))
3358 if (walker(query->setOperations, context))
3360 if (walker(query->havingQual, context))
3362 if (walker(query->limitOffset, context))
3364 if (walker(query->limitCount, context))
3366 if (range_table_walker(query->rtable, walker, context, flags))
3372 * range_table_walker is just the part of query_tree_walker that scans
3373 * a query's rangetable. This is split out since it can be useful on
3377 range_table_walker(List *rtable,
3386 RangeTblEntry *rte = (RangeTblEntry *) lfirst(rt);
3388 switch (rte->rtekind)
3395 if (!(flags & QTW_IGNORE_RT_SUBQUERIES))
3396 if (walker(rte->subquery, context))
3400 if (!(flags & QTW_IGNORE_JOINALIASES))
3401 if (walker(rte->joinaliasvars, context))
3405 if (walker(rte->funcexpr, context))
3409 if (walker(rte->values_lists, context))
3418 /*--------------------
3419 * expression_tree_mutator() is designed to support routines that make a
3420 * modified copy of an expression tree, with some nodes being added,
3421 * removed, or replaced by new subtrees. The original tree is (normally)
3422 * not changed. Each recursion level is responsible for returning a copy of
3423 * (or appropriately modified substitute for) the subtree it is handed.
3424 * A mutator routine should look like this:
3426 * Node * my_mutator (Node *node, my_struct *context)
3430 * // check for nodes that special work is required for, eg:
3431 * if (IsA(node, Var))
3433 * ... create and return modified copy of Var node
3435 * else if (IsA(node, ...))
3437 * ... do special transformations of other node types
3439 * // for any node type not specially processed, do:
3440 * return expression_tree_mutator(node, my_mutator, (void *) context);
3443 * The "context" argument points to a struct that holds whatever context
3444 * information the mutator routine needs --- it can be used to return extra
3445 * data gathered by the mutator, too. This argument is not touched by
3446 * expression_tree_mutator, but it is passed down to recursive sub-invocations
3447 * of my_mutator. The tree walk is started from a setup routine that
3448 * fills in the appropriate context struct, calls my_mutator with the
3449 * top-level node of the tree, and does any required post-processing.
3451 * Each level of recursion must return an appropriately modified Node.
3452 * If expression_tree_mutator() is called, it will make an exact copy
3453 * of the given Node, but invoke my_mutator() to copy the sub-node(s)
3454 * of that Node. In this way, my_mutator() has full control over the
3455 * copying process but need not directly deal with expression trees
3456 * that it has no interest in.
3458 * Just as for expression_tree_walker, the node types handled by
3459 * expression_tree_mutator include all those normally found in target lists
3460 * and qualifier clauses during the planning stage.
3462 * expression_tree_mutator will handle SubLink nodes by recursing normally
3463 * into the "testexpr" subtree (which is an expression belonging to the outer
3464 * plan). It will also call the mutator on the sub-Query node; however, when
3465 * expression_tree_mutator itself is called on a Query node, it does nothing
3466 * and returns the unmodified Query node. The net effect is that unless the
3467 * mutator does something special at a Query node, sub-selects will not be
3468 * visited or modified; the original sub-select will be linked to by the new
3469 * SubLink node. Mutators that want to descend into sub-selects will usually
3470 * do so by recognizing Query nodes and calling query_tree_mutator (below).
3472 * expression_tree_mutator will handle a SubPlan node by recursing into the
3473 * "testexpr" and the "args" list (which belong to the outer plan), but it
3474 * will simply copy the link to the inner plan, since that's typically what
3475 * expression tree mutators want. A mutator that wants to modify the subplan
3476 * can force appropriate behavior by recognizing SubPlan expression nodes
3477 * and doing the right thing.
3478 *--------------------
3482 expression_tree_mutator(Node *node,
3483 Node *(*mutator) (),
3487 * The mutator has already decided not to modify the current node, but we
3488 * must call the mutator for any sub-nodes.
3491 #define FLATCOPY(newnode, node, nodetype) \
3492 ( (newnode) = makeNode(nodetype), \
3493 memcpy((newnode), (node), sizeof(nodetype)) )
3495 #define CHECKFLATCOPY(newnode, node, nodetype) \
3496 ( AssertMacro(IsA((node), nodetype)), \
3497 (newnode) = makeNode(nodetype), \
3498 memcpy((newnode), (node), sizeof(nodetype)) )
3500 #define MUTATE(newfield, oldfield, fieldtype) \
3501 ( (newfield) = (fieldtype) mutator((Node *) (oldfield), context) )
3506 /* Guard against stack overflow due to overly complex expressions */
3507 check_stack_depth();
3509 switch (nodeTag(node))
3514 case T_CoerceToDomainValue:
3515 case T_CaseTestExpr:
3516 case T_SetToDefault:
3518 case T_OuterJoinInfo:
3519 /* primitive node types with no expression subnodes */
3520 return (Node *) copyObject(node);
3523 Aggref *aggref = (Aggref *) node;
3526 FLATCOPY(newnode, aggref, Aggref);
3527 MUTATE(newnode->args, aggref->args, List *);
3528 return (Node *) newnode;
3533 ArrayRef *arrayref = (ArrayRef *) node;
3536 FLATCOPY(newnode, arrayref, ArrayRef);
3537 MUTATE(newnode->refupperindexpr, arrayref->refupperindexpr,
3539 MUTATE(newnode->reflowerindexpr, arrayref->reflowerindexpr,
3541 MUTATE(newnode->refexpr, arrayref->refexpr,
3543 MUTATE(newnode->refassgnexpr, arrayref->refassgnexpr,
3545 return (Node *) newnode;
3550 FuncExpr *expr = (FuncExpr *) node;
3553 FLATCOPY(newnode, expr, FuncExpr);
3554 MUTATE(newnode->args, expr->args, List *);
3555 return (Node *) newnode;
3560 OpExpr *expr = (OpExpr *) node;
3563 FLATCOPY(newnode, expr, OpExpr);
3564 MUTATE(newnode->args, expr->args, List *);
3565 return (Node *) newnode;
3568 case T_DistinctExpr:
3570 DistinctExpr *expr = (DistinctExpr *) node;
3571 DistinctExpr *newnode;
3573 FLATCOPY(newnode, expr, DistinctExpr);
3574 MUTATE(newnode->args, expr->args, List *);
3575 return (Node *) newnode;
3578 case T_ScalarArrayOpExpr:
3580 ScalarArrayOpExpr *expr = (ScalarArrayOpExpr *) node;
3581 ScalarArrayOpExpr *newnode;
3583 FLATCOPY(newnode, expr, ScalarArrayOpExpr);
3584 MUTATE(newnode->args, expr->args, List *);
3585 return (Node *) newnode;
3590 BoolExpr *expr = (BoolExpr *) node;
3593 FLATCOPY(newnode, expr, BoolExpr);
3594 MUTATE(newnode->args, expr->args, List *);
3595 return (Node *) newnode;
3600 SubLink *sublink = (SubLink *) node;
3603 FLATCOPY(newnode, sublink, SubLink);
3604 MUTATE(newnode->testexpr, sublink->testexpr, Node *);
3607 * Also invoke the mutator on the sublink's Query node, so it
3608 * can recurse into the sub-query if it wants to.
3610 MUTATE(newnode->subselect, sublink->subselect, Node *);
3611 return (Node *) newnode;
3616 SubPlan *subplan = (SubPlan *) node;
3619 FLATCOPY(newnode, subplan, SubPlan);
3620 /* transform testexpr */
3621 MUTATE(newnode->testexpr, subplan->testexpr, Node *);
3622 /* transform args list (params to be passed to subplan) */
3623 MUTATE(newnode->args, subplan->args, List *);
3624 /* but not the sub-Plan itself, which is referenced as-is */
3625 return (Node *) newnode;
3630 FieldSelect *fselect = (FieldSelect *) node;
3631 FieldSelect *newnode;
3633 FLATCOPY(newnode, fselect, FieldSelect);
3634 MUTATE(newnode->arg, fselect->arg, Expr *);
3635 return (Node *) newnode;
3640 FieldStore *fstore = (FieldStore *) node;
3641 FieldStore *newnode;
3643 FLATCOPY(newnode, fstore, FieldStore);
3644 MUTATE(newnode->arg, fstore->arg, Expr *);
3645 MUTATE(newnode->newvals, fstore->newvals, List *);
3646 newnode->fieldnums = list_copy(fstore->fieldnums);
3647 return (Node *) newnode;
3652 RelabelType *relabel = (RelabelType *) node;
3653 RelabelType *newnode;
3655 FLATCOPY(newnode, relabel, RelabelType);
3656 MUTATE(newnode->arg, relabel->arg, Expr *);
3657 return (Node *) newnode;
3660 case T_ConvertRowtypeExpr:
3662 ConvertRowtypeExpr *convexpr = (ConvertRowtypeExpr *) node;
3663 ConvertRowtypeExpr *newnode;
3665 FLATCOPY(newnode, convexpr, ConvertRowtypeExpr);
3666 MUTATE(newnode->arg, convexpr->arg, Expr *);
3667 return (Node *) newnode;
3672 CaseExpr *caseexpr = (CaseExpr *) node;
3675 FLATCOPY(newnode, caseexpr, CaseExpr);
3676 MUTATE(newnode->arg, caseexpr->arg, Expr *);
3677 MUTATE(newnode->args, caseexpr->args, List *);
3678 MUTATE(newnode->defresult, caseexpr->defresult, Expr *);
3679 return (Node *) newnode;
3684 CaseWhen *casewhen = (CaseWhen *) node;
3687 FLATCOPY(newnode, casewhen, CaseWhen);
3688 MUTATE(newnode->expr, casewhen->expr, Expr *);
3689 MUTATE(newnode->result, casewhen->result, Expr *);
3690 return (Node *) newnode;
3695 ArrayExpr *arrayexpr = (ArrayExpr *) node;
3698 FLATCOPY(newnode, arrayexpr, ArrayExpr);
3699 MUTATE(newnode->elements, arrayexpr->elements, List *);
3700 return (Node *) newnode;
3705 RowExpr *rowexpr = (RowExpr *) node;
3708 FLATCOPY(newnode, rowexpr, RowExpr);
3709 MUTATE(newnode->args, rowexpr->args, List *);
3710 return (Node *) newnode;
3713 case T_RowCompareExpr:
3715 RowCompareExpr *rcexpr = (RowCompareExpr *) node;
3716 RowCompareExpr *newnode;
3718 FLATCOPY(newnode, rcexpr, RowCompareExpr);
3719 MUTATE(newnode->largs, rcexpr->largs, List *);
3720 MUTATE(newnode->rargs, rcexpr->rargs, List *);
3721 return (Node *) newnode;
3724 case T_CoalesceExpr:
3726 CoalesceExpr *coalesceexpr = (CoalesceExpr *) node;
3727 CoalesceExpr *newnode;
3729 FLATCOPY(newnode, coalesceexpr, CoalesceExpr);
3730 MUTATE(newnode->args, coalesceexpr->args, List *);
3731 return (Node *) newnode;
3736 MinMaxExpr *minmaxexpr = (MinMaxExpr *) node;
3737 MinMaxExpr *newnode;
3739 FLATCOPY(newnode, minmaxexpr, MinMaxExpr);
3740 MUTATE(newnode->args, minmaxexpr->args, List *);
3741 return (Node *) newnode;
3746 NullIfExpr *expr = (NullIfExpr *) node;
3747 NullIfExpr *newnode;
3749 FLATCOPY(newnode, expr, NullIfExpr);
3750 MUTATE(newnode->args, expr->args, List *);
3751 return (Node *) newnode;
3756 NullTest *ntest = (NullTest *) node;
3759 FLATCOPY(newnode, ntest, NullTest);
3760 MUTATE(newnode->arg, ntest->arg, Expr *);
3761 return (Node *) newnode;
3766 BooleanTest *btest = (BooleanTest *) node;
3767 BooleanTest *newnode;
3769 FLATCOPY(newnode, btest, BooleanTest);
3770 MUTATE(newnode->arg, btest->arg, Expr *);
3771 return (Node *) newnode;
3774 case T_CoerceToDomain:
3776 CoerceToDomain *ctest = (CoerceToDomain *) node;
3777 CoerceToDomain *newnode;
3779 FLATCOPY(newnode, ctest, CoerceToDomain);
3780 MUTATE(newnode->arg, ctest->arg, Expr *);
3781 return (Node *) newnode;
3786 TargetEntry *targetentry = (TargetEntry *) node;
3787 TargetEntry *newnode;
3789 FLATCOPY(newnode, targetentry, TargetEntry);
3790 MUTATE(newnode->expr, targetentry->expr, Expr *);
3791 return (Node *) newnode;
3795 /* Do nothing with a sub-Query, per discussion above */
3800 * We assume the mutator isn't interested in the list nodes
3801 * per se, so just invoke it on each list element. NOTE: this
3802 * would fail badly on a list with integer elements!
3808 foreach(temp, (List *) node)
3810 resultlist = lappend(resultlist,
3811 mutator((Node *) lfirst(temp),
3814 return (Node *) resultlist;
3819 FromExpr *from = (FromExpr *) node;
3822 FLATCOPY(newnode, from, FromExpr);
3823 MUTATE(newnode->fromlist, from->fromlist, List *);
3824 MUTATE(newnode->quals, from->quals, Node *);
3825 return (Node *) newnode;
3830 JoinExpr *join = (JoinExpr *) node;
3833 FLATCOPY(newnode, join, JoinExpr);
3834 MUTATE(newnode->larg, join->larg, Node *);
3835 MUTATE(newnode->rarg, join->rarg, Node *);
3836 MUTATE(newnode->quals, join->quals, Node *);
3837 /* We do not mutate alias or using by default */
3838 return (Node *) newnode;
3841 case T_SetOperationStmt:
3843 SetOperationStmt *setop = (SetOperationStmt *) node;
3844 SetOperationStmt *newnode;
3846 FLATCOPY(newnode, setop, SetOperationStmt);
3847 MUTATE(newnode->larg, setop->larg, Node *);
3848 MUTATE(newnode->rarg, setop->rarg, Node *);
3849 return (Node *) newnode;
3852 case T_InClauseInfo:
3854 InClauseInfo *ininfo = (InClauseInfo *) node;
3855 InClauseInfo *newnode;
3857 FLATCOPY(newnode, ininfo, InClauseInfo);
3858 MUTATE(newnode->sub_targetlist, ininfo->sub_targetlist, List *);
3859 return (Node *) newnode;
3862 case T_AppendRelInfo:
3864 AppendRelInfo *appinfo = (AppendRelInfo *) node;
3865 AppendRelInfo *newnode;
3867 FLATCOPY(newnode, appinfo, AppendRelInfo);
3868 MUTATE(newnode->translated_vars, appinfo->translated_vars, List *);
3869 return (Node *) newnode;
3873 elog(ERROR, "unrecognized node type: %d",
3874 (int) nodeTag(node));
3877 /* can't get here, but keep compiler happy */
3883 * query_tree_mutator --- initiate modification of a Query's expressions
3885 * This routine exists just to reduce the number of places that need to know
3886 * where all the expression subtrees of a Query are. Note it can be used
3887 * for starting a walk at top level of a Query regardless of whether the
3888 * mutator intends to descend into subqueries. It is also useful for
3889 * descending into subqueries within a mutator.
3891 * Some callers want to suppress mutating of certain items in the Query,
3892 * typically because they need to process them specially, or don't actually
3893 * want to recurse into subqueries. This is supported by the flags argument,
3894 * which is the bitwise OR of flag values to suppress mutating of
3895 * indicated items. (More flag bits may be added as needed.)
3897 * Normally the Query node itself is copied, but some callers want it to be
3898 * modified in-place; they must pass QTW_DONT_COPY_QUERY in flags. All
3899 * modified substructure is safely copied in any case.
3902 query_tree_mutator(Query *query,
3903 Node *(*mutator) (),
3907 Assert(query != NULL && IsA(query, Query));
3909 if (!(flags & QTW_DONT_COPY_QUERY))
3913 FLATCOPY(newquery, query, Query);
3917 MUTATE(query->targetList, query->targetList, List *);
3918 MUTATE(query->returningList, query->returningList, List *);
3919 MUTATE(query->jointree, query->jointree, FromExpr *);
3920 MUTATE(query->setOperations, query->setOperations, Node *);
3921 MUTATE(query->havingQual, query->havingQual, Node *);
3922 MUTATE(query->limitOffset, query->limitOffset, Node *);
3923 MUTATE(query->limitCount, query->limitCount, Node *);
3924 query->rtable = range_table_mutator(query->rtable,
3925 mutator, context, flags);
3930 * range_table_mutator is just the part of query_tree_mutator that processes
3931 * a query's rangetable. This is split out since it can be useful on
3935 range_table_mutator(List *rtable,
3936 Node *(*mutator) (),
3945 RangeTblEntry *rte = (RangeTblEntry *) lfirst(rt);
3946 RangeTblEntry *newrte;
3948 FLATCOPY(newrte, rte, RangeTblEntry);
3949 switch (rte->rtekind)
3953 /* we don't bother to copy eref, aliases, etc; OK? */
3956 if (!(flags & QTW_IGNORE_RT_SUBQUERIES))
3958 CHECKFLATCOPY(newrte->subquery, rte->subquery, Query);
3959 MUTATE(newrte->subquery, newrte->subquery, Query *);
3963 /* else, copy RT subqueries as-is */
3964 newrte->subquery = copyObject(rte->subquery);
3968 if (!(flags & QTW_IGNORE_JOINALIASES))
3969 MUTATE(newrte->joinaliasvars, rte->joinaliasvars, List *);
3972 /* else, copy join aliases as-is */
3973 newrte->joinaliasvars = copyObject(rte->joinaliasvars);
3977 MUTATE(newrte->funcexpr, rte->funcexpr, Node *);
3980 MUTATE(newrte->values_lists, rte->values_lists, List *);
3983 newrt = lappend(newrt, newrte);
3989 * query_or_expression_tree_walker --- hybrid form
3991 * This routine will invoke query_tree_walker if called on a Query node,
3992 * else will invoke the walker directly. This is a useful way of starting
3993 * the recursion when the walker's normal change of state is not appropriate
3994 * for the outermost Query node.
3997 query_or_expression_tree_walker(Node *node,
4002 if (node && IsA(node, Query))
4003 return query_tree_walker((Query *) node,
4008 return walker(node, context);
4012 * query_or_expression_tree_mutator --- hybrid form
4014 * This routine will invoke query_tree_mutator if called on a Query node,
4015 * else will invoke the mutator directly. This is a useful way of starting
4016 * the recursion when the mutator's normal change of state is not appropriate
4017 * for the outermost Query node.
4020 query_or_expression_tree_mutator(Node *node,
4021 Node *(*mutator) (),
4025 if (node && IsA(node, Query))
4026 return (Node *) query_tree_mutator((Query *) node,
4031 return mutator(node, context);