1 /*-------------------------------------------------------------------------
4 * routines to manipulate qualification clauses
6 * Portions Copyright (c) 1996-2004, 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.179 2004/08/29 04:12:34 momjian Exp $
14 * AUTHOR DATE MAJOR EVENT
15 * Andrew Yu Nov 3, 1994 clause.c and clauses.c combined
17 *-------------------------------------------------------------------------
22 #include "catalog/pg_language.h"
23 #include "catalog/pg_proc.h"
24 #include "catalog/pg_type.h"
25 #include "executor/executor.h"
26 #include "miscadmin.h"
27 #include "nodes/makefuncs.h"
28 #include "optimizer/clauses.h"
29 #include "optimizer/cost.h"
30 #include "optimizer/planmain.h"
31 #include "optimizer/planner.h"
32 #include "optimizer/var.h"
33 #include "parser/analyze.h"
34 #include "parser/parse_clause.h"
35 #include "parser/parse_expr.h"
36 #include "tcop/tcopprot.h"
37 #include "utils/acl.h"
38 #include "utils/builtins.h"
39 #include "utils/datum.h"
40 #include "utils/lsyscache.h"
41 #include "utils/memutils.h"
42 #include "utils/syscache.h"
43 #include "utils/typcache.h"
50 } eval_const_expressions_context;
57 } substitute_actual_parameters_context;
59 static bool contain_agg_clause_walker(Node *node, void *context);
60 static bool contain_distinct_agg_clause_walker(Node *node, void *context);
61 static bool count_agg_clause_walker(Node *node, int *count);
62 static bool expression_returns_set_walker(Node *node, void *context);
63 static bool contain_subplans_walker(Node *node, void *context);
64 static bool contain_mutable_functions_walker(Node *node, void *context);
65 static bool contain_volatile_functions_walker(Node *node, void *context);
66 static bool contain_nonstrict_functions_walker(Node *node, void *context);
67 static bool set_coercionform_dontcare_walker(Node *node, void *context);
68 static Node *eval_const_expressions_mutator(Node *node,
69 eval_const_expressions_context *context);
70 static List *simplify_or_arguments(List *args,
71 bool *haveNull, bool *forceTrue);
72 static List *simplify_and_arguments(List *args,
73 bool *haveNull, bool *forceFalse);
74 static Expr *simplify_function(Oid funcid, Oid result_type, List *args,
76 eval_const_expressions_context *context);
77 static Expr *evaluate_function(Oid funcid, Oid result_type, List *args,
78 HeapTuple func_tuple);
79 static Expr *inline_function(Oid funcid, Oid result_type, List *args,
81 eval_const_expressions_context *context);
82 static Node *substitute_actual_parameters(Node *expr, int nargs, List *args,
84 static Node *substitute_actual_parameters_mutator(Node *node,
85 substitute_actual_parameters_context *context);
86 static void sql_inline_error_callback(void *arg);
87 static Expr *evaluate_expr(Expr *expr, Oid result_type);
90 /*****************************************************************************
91 * OPERATOR clause functions
92 *****************************************************************************/
96 * Creates an operator clause given its operator info, left operand,
97 * and right operand (pass NULL to create single-operand clause).
100 make_opclause(Oid opno, Oid opresulttype, bool opretset,
101 Expr *leftop, Expr *rightop)
103 OpExpr *expr = makeNode(OpExpr);
106 expr->opfuncid = InvalidOid;
107 expr->opresulttype = opresulttype;
108 expr->opretset = opretset;
110 expr->args = list_make2(leftop, rightop);
112 expr->args = list_make1(leftop);
113 return (Expr *) expr;
119 * Returns the left operand of a clause of the form (op expr expr)
123 get_leftop(Expr *clause)
125 OpExpr *expr = (OpExpr *) clause;
127 if (expr->args != NIL)
128 return linitial(expr->args);
136 * Returns the right operand in a clause of the form (op expr expr).
137 * NB: result will be NULL if applied to a unary op clause.
140 get_rightop(Expr *clause)
142 OpExpr *expr = (OpExpr *) clause;
144 if (list_length(expr->args) >= 2)
145 return lsecond(expr->args);
150 /*****************************************************************************
151 * NOT clause functions
152 *****************************************************************************/
157 * Returns t iff this is a 'not' clause: (NOT expr).
160 not_clause(Node *clause)
162 return (clause != NULL &&
163 IsA(clause, BoolExpr) &&
164 ((BoolExpr *) clause)->boolop == NOT_EXPR);
170 * Create a 'not' clause given the expression to be negated.
173 make_notclause(Expr *notclause)
175 BoolExpr *expr = makeNode(BoolExpr);
177 expr->boolop = NOT_EXPR;
178 expr->args = list_make1(notclause);
179 return (Expr *) expr;
185 * Retrieve the clause within a 'not' clause
188 get_notclausearg(Expr *notclause)
190 return linitial(((BoolExpr *) notclause)->args);
193 /*****************************************************************************
194 * OR clause functions
195 *****************************************************************************/
200 * Returns t iff the clause is an 'or' clause: (OR { expr }).
203 or_clause(Node *clause)
205 return (clause != NULL &&
206 IsA(clause, BoolExpr) &&
207 ((BoolExpr *) clause)->boolop == OR_EXPR);
213 * Creates an 'or' clause given a list of its subclauses.
216 make_orclause(List *orclauses)
218 BoolExpr *expr = makeNode(BoolExpr);
220 expr->boolop = OR_EXPR;
221 expr->args = orclauses;
222 return (Expr *) expr;
225 /*****************************************************************************
226 * AND clause functions
227 *****************************************************************************/
233 * Returns t iff its argument is an 'and' clause: (AND { expr }).
236 and_clause(Node *clause)
238 return (clause != NULL &&
239 IsA(clause, BoolExpr) &&
240 ((BoolExpr *) clause)->boolop == AND_EXPR);
246 * Creates an 'and' clause given a list of its subclauses.
249 make_andclause(List *andclauses)
251 BoolExpr *expr = makeNode(BoolExpr);
253 expr->boolop = AND_EXPR;
254 expr->args = andclauses;
255 return (Expr *) expr;
261 * Variant of make_andclause for ANDing two qual conditions together.
262 * Qual conditions have the property that a NULL nodetree is interpreted
265 * NB: this makes no attempt to preserve AND/OR flatness; so it should not
266 * be used on a qual that has already been run through prepqual.c.
269 make_and_qual(Node *qual1, Node *qual2)
275 return (Node *) make_andclause(list_make2(qual1, qual2));
279 * Sometimes (such as in the input of ExecQual), we use lists of expression
280 * nodes with implicit AND semantics.
282 * These functions convert between an AND-semantics expression list and the
283 * ordinary representation of a boolean expression.
285 * Note that an empty list is considered equivalent to TRUE.
288 make_ands_explicit(List *andclauses)
290 if (andclauses == NIL)
291 return (Expr *) makeBoolConst(true, false);
292 else if (list_length(andclauses) == 1)
293 return (Expr *) linitial(andclauses);
295 return make_andclause(andclauses);
299 make_ands_implicit(Expr *clause)
302 * NB: because the parser sets the qual field to NULL in a query that
303 * has no WHERE clause, we must consider a NULL input clause as TRUE,
304 * even though one might more reasonably think it FALSE. Grumble. If
305 * this causes trouble, consider changing the parser's behavior.
308 return NIL; /* NULL -> NIL list == TRUE */
309 else if (and_clause((Node *) clause))
310 return ((BoolExpr *) clause)->args;
311 else if (IsA(clause, Const) &&
312 !((Const *) clause)->constisnull &&
313 DatumGetBool(((Const *) clause)->constvalue))
314 return NIL; /* constant TRUE input -> NIL list */
316 return list_make1(clause);
320 /*****************************************************************************
321 * Aggregate-function clause manipulation
322 *****************************************************************************/
326 * Recursively search for Aggref nodes within a clause.
328 * Returns true if any aggregate found.
330 * This does not descend into subqueries, and so should be used only after
331 * reduction of sublinks to subplans, or in contexts where it's known there
332 * are no subqueries. There mustn't be outer-aggregate references either.
334 * (If you want something like this but able to deal with subqueries,
335 * see rewriteManip.c's checkExprHasAggs().)
338 contain_agg_clause(Node *clause)
340 return contain_agg_clause_walker(clause, NULL);
344 contain_agg_clause_walker(Node *node, void *context)
348 if (IsA(node, Aggref))
350 Assert(((Aggref *) node)->agglevelsup == 0);
351 return true; /* abort the tree traversal and return
354 Assert(!IsA(node, SubLink));
355 return expression_tree_walker(node, contain_agg_clause_walker, context);
359 * contain_distinct_agg_clause
360 * Recursively search for DISTINCT Aggref nodes within a clause.
362 * Returns true if any DISTINCT aggregate found.
364 * This does not descend into subqueries, and so should be used only after
365 * reduction of sublinks to subplans, or in contexts where it's known there
366 * are no subqueries. There mustn't be outer-aggregate references either.
369 contain_distinct_agg_clause(Node *clause)
371 return contain_distinct_agg_clause_walker(clause, NULL);
375 contain_distinct_agg_clause_walker(Node *node, void *context)
379 if (IsA(node, Aggref))
381 Assert(((Aggref *) node)->agglevelsup == 0);
382 if (((Aggref *) node)->aggdistinct)
383 return true; /* abort the tree traversal and return
386 Assert(!IsA(node, SubLink));
387 return expression_tree_walker(node, contain_distinct_agg_clause_walker, context);
392 * Recursively count the Aggref nodes in an expression tree.
394 * Note: this also checks for nested aggregates, which are an error.
396 * This does not descend into subqueries, and so should be used only after
397 * reduction of sublinks to subplans, or in contexts where it's known there
398 * are no subqueries. There mustn't be outer-aggregate references either.
401 count_agg_clause(Node *clause)
405 count_agg_clause_walker(clause, &result);
410 count_agg_clause_walker(Node *node, int *count)
414 if (IsA(node, Aggref))
416 Assert(((Aggref *) node)->agglevelsup == 0);
420 * Complain if the aggregate's argument contains any aggregates;
421 * nested agg functions are semantically nonsensical.
423 if (contain_agg_clause((Node *) ((Aggref *) node)->target))
425 (errcode(ERRCODE_GROUPING_ERROR),
426 errmsg("aggregate function calls may not be nested")));
429 * Having checked that, we need not recurse into the argument.
433 Assert(!IsA(node, SubLink));
434 return expression_tree_walker(node, count_agg_clause_walker,
439 /*****************************************************************************
440 * Support for expressions returning sets
441 *****************************************************************************/
444 * expression_returns_set
445 * Test whether an expression returns a set result.
447 * Because we use expression_tree_walker(), this can also be applied to
448 * whole targetlists; it'll produce TRUE if any one of the tlist items
452 expression_returns_set(Node *clause)
454 return expression_returns_set_walker(clause, NULL);
458 expression_returns_set_walker(Node *node, void *context)
462 if (IsA(node, FuncExpr))
464 FuncExpr *expr = (FuncExpr *) node;
466 if (expr->funcretset)
468 /* else fall through to check args */
470 if (IsA(node, OpExpr))
472 OpExpr *expr = (OpExpr *) node;
476 /* else fall through to check args */
479 /* Avoid recursion for some cases that can't return a set */
480 if (IsA(node, Aggref))
482 if (IsA(node, DistinctExpr))
484 if (IsA(node, ScalarArrayOpExpr))
486 if (IsA(node, BoolExpr))
488 if (IsA(node, SubLink))
490 if (IsA(node, SubPlan))
492 if (IsA(node, ArrayExpr))
494 if (IsA(node, RowExpr))
496 if (IsA(node, CoalesceExpr))
498 if (IsA(node, NullIfExpr))
501 return expression_tree_walker(node, expression_returns_set_walker,
505 /*****************************************************************************
506 * Subplan clause manipulation
507 *****************************************************************************/
511 * Recursively search for subplan nodes within a clause.
513 * If we see a SubLink node, we will return TRUE. This is only possible if
514 * the expression tree hasn't yet been transformed by subselect.c. We do not
515 * know whether the node will produce a true subplan or just an initplan,
516 * but we make the conservative assumption that it will be a subplan.
518 * Returns true if any subplan found.
521 contain_subplans(Node *clause)
523 return contain_subplans_walker(clause, NULL);
527 contain_subplans_walker(Node *node, void *context)
531 if (IsA(node, SubPlan) ||
533 return true; /* abort the tree traversal and return
535 return expression_tree_walker(node, contain_subplans_walker, context);
539 /*****************************************************************************
540 * Check clauses for mutable functions
541 *****************************************************************************/
544 * contain_mutable_functions
545 * Recursively search for mutable functions within a clause.
547 * Returns true if any mutable function (or operator implemented by a
548 * mutable function) is found. This test is needed so that we don't
549 * mistakenly think that something like "WHERE random() < 0.5" can be treated
550 * as a constant qualification.
552 * XXX we do not examine sub-selects to see if they contain uses of
553 * mutable functions. It's not real clear if that is correct or not...
556 contain_mutable_functions(Node *clause)
558 return contain_mutable_functions_walker(clause, NULL);
562 contain_mutable_functions_walker(Node *node, void *context)
566 if (IsA(node, FuncExpr))
568 FuncExpr *expr = (FuncExpr *) node;
570 if (func_volatile(expr->funcid) != PROVOLATILE_IMMUTABLE)
572 /* else fall through to check args */
574 if (IsA(node, OpExpr))
576 OpExpr *expr = (OpExpr *) node;
578 if (op_volatile(expr->opno) != PROVOLATILE_IMMUTABLE)
580 /* else fall through to check args */
582 if (IsA(node, DistinctExpr))
584 DistinctExpr *expr = (DistinctExpr *) node;
586 if (op_volatile(expr->opno) != PROVOLATILE_IMMUTABLE)
588 /* else fall through to check args */
590 if (IsA(node, ScalarArrayOpExpr))
592 ScalarArrayOpExpr *expr = (ScalarArrayOpExpr *) node;
594 if (op_volatile(expr->opno) != PROVOLATILE_IMMUTABLE)
596 /* else fall through to check args */
598 if (IsA(node, NullIfExpr))
600 NullIfExpr *expr = (NullIfExpr *) node;
602 if (op_volatile(expr->opno) != PROVOLATILE_IMMUTABLE)
604 /* else fall through to check args */
606 if (IsA(node, SubLink))
608 SubLink *sublink = (SubLink *) node;
611 foreach(opid, sublink->operOids)
613 if (op_volatile(lfirst_oid(opid)) != PROVOLATILE_IMMUTABLE)
616 /* else fall through to check args */
618 return expression_tree_walker(node, contain_mutable_functions_walker,
623 /*****************************************************************************
624 * Check clauses for volatile functions
625 *****************************************************************************/
628 * contain_volatile_functions
629 * Recursively search for volatile functions within a clause.
631 * Returns true if any volatile function (or operator implemented by a
632 * volatile function) is found. This test prevents invalid conversions
633 * of volatile expressions into indexscan quals.
635 * XXX we do not examine sub-selects to see if they contain uses of
636 * volatile functions. It's not real clear if that is correct or not...
639 contain_volatile_functions(Node *clause)
641 return contain_volatile_functions_walker(clause, NULL);
645 contain_volatile_functions_walker(Node *node, void *context)
649 if (IsA(node, FuncExpr))
651 FuncExpr *expr = (FuncExpr *) node;
653 if (func_volatile(expr->funcid) == PROVOLATILE_VOLATILE)
655 /* else fall through to check args */
657 if (IsA(node, OpExpr))
659 OpExpr *expr = (OpExpr *) node;
661 if (op_volatile(expr->opno) == PROVOLATILE_VOLATILE)
663 /* else fall through to check args */
665 if (IsA(node, DistinctExpr))
667 DistinctExpr *expr = (DistinctExpr *) node;
669 if (op_volatile(expr->opno) == PROVOLATILE_VOLATILE)
671 /* else fall through to check args */
673 if (IsA(node, ScalarArrayOpExpr))
675 ScalarArrayOpExpr *expr = (ScalarArrayOpExpr *) node;
677 if (op_volatile(expr->opno) == PROVOLATILE_VOLATILE)
679 /* else fall through to check args */
681 if (IsA(node, NullIfExpr))
683 NullIfExpr *expr = (NullIfExpr *) node;
685 if (op_volatile(expr->opno) == PROVOLATILE_VOLATILE)
687 /* else fall through to check args */
689 if (IsA(node, SubLink))
691 SubLink *sublink = (SubLink *) node;
694 foreach(opid, sublink->operOids)
696 if (op_volatile(lfirst_oid(opid)) == PROVOLATILE_VOLATILE)
699 /* else fall through to check args */
701 return expression_tree_walker(node, contain_volatile_functions_walker,
706 /*****************************************************************************
707 * Check clauses for nonstrict functions
708 *****************************************************************************/
711 * contain_nonstrict_functions
712 * Recursively search for nonstrict functions within a clause.
714 * Returns true if any nonstrict construct is found --- ie, anything that
715 * could produce non-NULL output with a NULL input.
717 * The idea here is that the caller has verified that the expression contains
718 * one or more Var or Param nodes (as appropriate for the caller's need), and
719 * now wishes to prove that the expression result will be NULL if any of these
720 * inputs is NULL. If we return false, then the proof succeeded.
723 contain_nonstrict_functions(Node *clause)
725 return contain_nonstrict_functions_walker(clause, NULL);
729 contain_nonstrict_functions_walker(Node *node, void *context)
733 if (IsA(node, Aggref))
735 /* an aggregate could return non-null with null input */
738 if (IsA(node, ArrayRef))
740 /* array assignment is nonstrict */
741 if (((ArrayRef *) node)->refassgnexpr != NULL)
743 /* else fall through to check args */
745 if (IsA(node, FuncExpr))
747 FuncExpr *expr = (FuncExpr *) node;
749 if (!func_strict(expr->funcid))
751 /* else fall through to check args */
753 if (IsA(node, OpExpr))
755 OpExpr *expr = (OpExpr *) node;
757 if (!op_strict(expr->opno))
759 /* else fall through to check args */
761 if (IsA(node, DistinctExpr))
763 /* IS DISTINCT FROM is inherently non-strict */
766 if (IsA(node, ScalarArrayOpExpr))
768 /* inherently non-strict, consider null scalar and empty array */
771 if (IsA(node, BoolExpr))
773 BoolExpr *expr = (BoolExpr *) node;
775 switch (expr->boolop)
779 /* AND, OR are inherently non-strict */
785 if (IsA(node, SubLink))
787 /* In some cases a sublink might be strict, but in general not */
790 if (IsA(node, SubPlan))
792 if (IsA(node, FieldStore))
794 if (IsA(node, CaseExpr))
796 if (IsA(node, CaseWhen))
798 /* NB: ArrayExpr might someday be nonstrict */
799 if (IsA(node, RowExpr))
801 if (IsA(node, CoalesceExpr))
803 if (IsA(node, NullIfExpr))
805 if (IsA(node, NullTest))
807 if (IsA(node, BooleanTest))
809 return expression_tree_walker(node, contain_nonstrict_functions_walker,
814 /*****************************************************************************
815 * Check for "pseudo-constant" clauses
816 *****************************************************************************/
819 * is_pseudo_constant_clause
820 * Detect whether a clause is "constant", ie, it contains no variables
821 * of the current query level and no uses of volatile functions.
822 * Such a clause is not necessarily a true constant: it can still contain
823 * Params and outer-level Vars, not to mention functions whose results
824 * may vary from one statement to the next. However, the clause's value
825 * will be constant over any one scan of the current query, so it can be
826 * used as an indexscan key or (if a top-level qual) can be pushed up to
827 * become a gating qual.
830 is_pseudo_constant_clause(Node *clause)
833 * We could implement this check in one recursive scan. But since the
834 * check for volatile functions is both moderately expensive and
835 * unlikely to fail, it seems better to look for Vars first and only
836 * check for volatile functions if we find no Vars.
838 if (!contain_var_clause(clause) &&
839 !contain_volatile_functions(clause))
845 * is_pseudo_constant_clause_relids
846 * Same as above, except caller already has available the var membership
847 * of the clause; this lets us avoid the contain_var_clause() scan.
850 is_pseudo_constant_clause_relids(Node *clause, Relids relids)
852 if (bms_is_empty(relids) &&
853 !contain_volatile_functions(clause))
859 * pull_constant_clauses
860 * Scan through a list of qualifications and separate "constant" quals
861 * from those that are not.
863 * Returns a list of the pseudo-constant clauses in constantQual and the
864 * remaining quals as the return value.
867 pull_constant_clauses(List *quals, List **constantQual)
869 List *constqual = NIL,
875 Node *qual = (Node *) lfirst(q);
877 if (is_pseudo_constant_clause(qual))
878 constqual = lappend(constqual, qual);
880 restqual = lappend(restqual, qual);
882 *constantQual = constqual;
887 /*****************************************************************************
888 * Tests on clauses of queries
890 * Possibly this code should go someplace else, since this isn't quite the
891 * same meaning of "clause" as is used elsewhere in this module. But I can't
892 * think of a better place for it...
893 *****************************************************************************/
896 * Test whether a query uses DISTINCT ON, ie, has a distinct-list that is
897 * not the same as the set of output columns.
900 has_distinct_on_clause(Query *query)
904 /* Is there a DISTINCT clause at all? */
905 if (query->distinctClause == NIL)
909 * If the DISTINCT list contains all the nonjunk targetlist items, and
910 * nothing else (ie, no junk tlist items), then it's a simple
911 * DISTINCT, else it's DISTINCT ON. We do not require the lists to be
912 * in the same order (since the parser may have adjusted the DISTINCT
913 * clause ordering to agree with ORDER BY). Furthermore, a
914 * non-DISTINCT junk tlist item that is in the sortClause is also
915 * evidence of DISTINCT ON, since we don't allow ORDER BY on junk
916 * tlist items when plain DISTINCT is used.
918 * This code assumes that the DISTINCT list is valid, ie, all its entries
919 * match some entry of the tlist.
921 foreach(l, query->targetList)
923 TargetEntry *tle = (TargetEntry *) lfirst(l);
925 if (tle->resdom->ressortgroupref == 0)
927 if (tle->resdom->resjunk)
928 continue; /* we can ignore unsorted junk cols */
929 return true; /* definitely not in DISTINCT list */
931 if (targetIsInSortList(tle, query->distinctClause))
933 if (tle->resdom->resjunk)
934 return true; /* junk TLE in DISTINCT means DISTINCT ON */
935 /* else this TLE is okay, keep looking */
939 /* This TLE is not in DISTINCT list */
940 if (!tle->resdom->resjunk)
941 return true; /* non-junk, non-DISTINCT, so DISTINCT ON */
942 if (targetIsInSortList(tle, query->sortClause))
943 return true; /* sorted, non-distinct junk */
944 /* unsorted junk is okay, keep looking */
947 /* It's a simple DISTINCT */
952 * Test whether a query uses simple DISTINCT, ie, has a distinct-list that
953 * is the same as the set of output columns.
956 has_distinct_clause(Query *query)
958 /* Is there a DISTINCT clause at all? */
959 if (query->distinctClause == NIL)
962 /* It's DISTINCT if it's not DISTINCT ON */
963 return !has_distinct_on_clause(query);
967 /*****************************************************************************
969 * General clause-manipulating routines *
971 *****************************************************************************/
975 * (formerly clause_relids)
977 * Returns the number of different relations referenced in 'clause'.
980 NumRelids(Node *clause)
982 Relids varnos = pull_varnos(clause);
983 int result = bms_num_members(varnos);
990 * CommuteClause: commute a binary operator clause
992 * XXX the clause is destructively modified!
995 CommuteClause(OpExpr *clause)
1000 /* Sanity checks: caller is at fault if these fail */
1001 if (!is_opclause(clause) ||
1002 list_length(clause->args) != 2)
1003 elog(ERROR, "cannot commute non-binary-operator clause");
1005 opoid = get_commutator(clause->opno);
1007 if (!OidIsValid(opoid))
1008 elog(ERROR, "could not find commutator for operator %u",
1012 * modify the clause in-place!
1014 clause->opno = opoid;
1015 clause->opfuncid = InvalidOid;
1016 /* opresulttype and opretset are assumed not to change */
1018 temp = linitial(clause->args);
1019 linitial(clause->args) = lsecond(clause->args);
1020 lsecond(clause->args) = temp;
1024 * set_coercionform_dontcare: set all CoercionForm fields to COERCE_DONTCARE
1026 * This is used to make index expressions and index predicates more easily
1027 * comparable to clauses of queries. CoercionForm is not semantically
1028 * significant (for cases where it does matter, the significant info is
1029 * coded into the coercion function arguments) so we can ignore it during
1030 * comparisons. Thus, for example, an index on "foo::int4" can match an
1031 * implicit coercion to int4.
1033 * Caution: the passed expression tree is modified in-place.
1036 set_coercionform_dontcare(Node *node)
1038 (void) set_coercionform_dontcare_walker(node, NULL);
1042 set_coercionform_dontcare_walker(Node *node, void *context)
1046 if (IsA(node, FuncExpr))
1047 ((FuncExpr *) node)->funcformat = COERCE_DONTCARE;
1048 if (IsA(node, RelabelType))
1049 ((RelabelType *) node)->relabelformat = COERCE_DONTCARE;
1050 if (IsA(node, RowExpr))
1051 ((RowExpr *) node)->row_format = COERCE_DONTCARE;
1052 if (IsA(node, CoerceToDomain))
1053 ((CoerceToDomain *) node)->coercionformat = COERCE_DONTCARE;
1054 return expression_tree_walker(node, set_coercionform_dontcare_walker,
1059 * Helper for eval_const_expressions: check that datatype of an attribute
1060 * is still what it was when the expression was parsed. This is needed to
1061 * guard against improper simplification after ALTER COLUMN TYPE. (XXX we
1062 * may well need to make similar checks elsewhere?)
1065 rowtype_field_matches(Oid rowtypeid, int fieldnum,
1066 Oid expectedtype, int32 expectedtypmod)
1069 Form_pg_attribute attr;
1071 /* No issue for RECORD, since there is no way to ALTER such a type */
1072 if (rowtypeid == RECORDOID)
1074 tupdesc = lookup_rowtype_tupdesc(rowtypeid, -1);
1075 if (fieldnum <= 0 || fieldnum > tupdesc->natts)
1077 attr = tupdesc->attrs[fieldnum - 1];
1078 if (attr->attisdropped ||
1079 attr->atttypid != expectedtype ||
1080 attr->atttypmod != expectedtypmod)
1086 /*--------------------
1087 * eval_const_expressions
1089 * Reduce any recognizably constant subexpressions of the given
1090 * expression tree, for example "2 + 2" => "4". More interestingly,
1091 * we can reduce certain boolean expressions even when they contain
1092 * non-constant subexpressions: "x OR true" => "true" no matter what
1093 * the subexpression x is. (XXX We assume that no such subexpression
1094 * will have important side-effects, which is not necessarily a good
1095 * assumption in the presence of user-defined functions; do we need a
1096 * pg_proc flag that prevents discarding the execution of a function?)
1098 * We do understand that certain functions may deliver non-constant
1099 * results even with constant inputs, "nextval()" being the classic
1100 * example. Functions that are not marked "immutable" in pg_proc
1101 * will not be pre-evaluated here, although we will reduce their
1102 * arguments as far as possible.
1104 * We assume that the tree has already been type-checked and contains
1105 * only operators and functions that are reasonable to try to execute.
1106 *--------------------
1109 eval_const_expressions(Node *node)
1111 eval_const_expressions_context context;
1113 context.active_fns = NIL; /* nothing being recursively simplified */
1114 context.estimate = false; /* safe transformations only */
1115 return eval_const_expressions_mutator(node, &context);
1119 * estimate_expression_value
1121 * This function attempts to estimate the value of an expression for
1122 * planning purposes. It is in essence a more aggressive version of
1123 * eval_const_expressions(): we will perform constant reductions that are
1124 * not necessarily 100% safe, but are reasonable for estimation purposes.
1126 * Currently the only such transform is to substitute values for Params,
1127 * when a bound Param value has been made available by the caller of planner().
1128 * In future we might consider other things, such as reducing now() to current
1129 * time. (XXX seems like there could be a lot of scope for ideas here...
1130 * but we might need more volatility classifications ...)
1133 estimate_expression_value(Node *node)
1135 eval_const_expressions_context context;
1137 context.active_fns = NIL; /* nothing being recursively simplified */
1138 context.estimate = true; /* unsafe transformations OK */
1139 return eval_const_expressions_mutator(node, &context);
1143 eval_const_expressions_mutator(Node *node,
1144 eval_const_expressions_context *context)
1148 if (IsA(node, Param))
1150 Param *param = (Param *) node;
1152 /* OK to try to substitute value? */
1153 if (context->estimate && param->paramkind != PARAM_EXEC &&
1154 PlannerBoundParamList != NULL)
1156 ParamListInfo paramInfo;
1158 /* Search to see if we've been given a value for this Param */
1159 paramInfo = lookupParam(PlannerBoundParamList,
1167 * Found it, so return a Const representing the param value.
1168 * Note that we don't copy pass-by-ref datatypes, so the
1169 * Const will only be valid as long as the bound parameter
1170 * list exists. This is okay for intended uses of
1171 * estimate_expression_value().
1176 Assert(paramInfo->ptype == param->paramtype);
1177 get_typlenbyval(param->paramtype, &typLen, &typByVal);
1178 return (Node *) makeConst(param->paramtype,
1185 /* Not replaceable, so just copy the Param (no need to recurse) */
1186 return (Node *) copyObject(param);
1188 if (IsA(node, FuncExpr))
1190 FuncExpr *expr = (FuncExpr *) node;
1196 * Reduce constants in the FuncExpr's arguments. We know args is
1197 * either NIL or a List node, so we can call
1198 * expression_tree_mutator directly rather than recursing to self.
1200 args = (List *) expression_tree_mutator((Node *) expr->args,
1201 eval_const_expressions_mutator,
1205 * Code for op/func reduction is pretty bulky, so split it out as
1206 * a separate function.
1208 simple = simplify_function(expr->funcid, expr->funcresulttype, args,
1210 if (simple) /* successfully simplified it */
1211 return (Node *) simple;
1214 * The expression cannot be simplified any further, so build and
1215 * return a replacement FuncExpr node using the
1216 * possibly-simplified arguments.
1218 newexpr = makeNode(FuncExpr);
1219 newexpr->funcid = expr->funcid;
1220 newexpr->funcresulttype = expr->funcresulttype;
1221 newexpr->funcretset = expr->funcretset;
1222 newexpr->funcformat = expr->funcformat;
1223 newexpr->args = args;
1224 return (Node *) newexpr;
1226 if (IsA(node, OpExpr))
1228 OpExpr *expr = (OpExpr *) node;
1234 * Reduce constants in the OpExpr's arguments. We know args is
1235 * either NIL or a List node, so we can call
1236 * expression_tree_mutator directly rather than recursing to self.
1238 args = (List *) expression_tree_mutator((Node *) expr->args,
1239 eval_const_expressions_mutator,
1243 * Need to get OID of underlying function. Okay to scribble on
1244 * input to this extent.
1249 * Code for op/func reduction is pretty bulky, so split it out as
1250 * a separate function.
1252 simple = simplify_function(expr->opfuncid, expr->opresulttype, args,
1254 if (simple) /* successfully simplified it */
1255 return (Node *) simple;
1258 * The expression cannot be simplified any further, so build and
1259 * return a replacement OpExpr node using the possibly-simplified
1262 newexpr = makeNode(OpExpr);
1263 newexpr->opno = expr->opno;
1264 newexpr->opfuncid = expr->opfuncid;
1265 newexpr->opresulttype = expr->opresulttype;
1266 newexpr->opretset = expr->opretset;
1267 newexpr->args = args;
1268 return (Node *) newexpr;
1270 if (IsA(node, DistinctExpr))
1272 DistinctExpr *expr = (DistinctExpr *) node;
1275 bool has_null_input = false;
1276 bool all_null_input = true;
1277 bool has_nonconst_input = false;
1279 DistinctExpr *newexpr;
1282 * Reduce constants in the DistinctExpr's arguments. We know args
1283 * is either NIL or a List node, so we can call
1284 * expression_tree_mutator directly rather than recursing to self.
1286 args = (List *) expression_tree_mutator((Node *) expr->args,
1287 eval_const_expressions_mutator,
1291 * We must do our own check for NULLs because DistinctExpr has
1292 * different results for NULL input than the underlying operator
1297 if (IsA(lfirst(arg), Const))
1299 has_null_input |= ((Const *) lfirst(arg))->constisnull;
1300 all_null_input &= ((Const *) lfirst(arg))->constisnull;
1303 has_nonconst_input = true;
1306 /* all constants? then can optimize this out */
1307 if (!has_nonconst_input)
1309 /* all nulls? then not distinct */
1311 return makeBoolConst(false, false);
1313 /* one null? then distinct */
1315 return makeBoolConst(true, false);
1317 /* otherwise try to evaluate the '=' operator */
1318 /* (NOT okay to try to inline it, though!) */
1321 * Need to get OID of underlying function. Okay to scribble
1322 * on input to this extent.
1324 set_opfuncid((OpExpr *) expr); /* rely on struct
1328 * Code for op/func reduction is pretty bulky, so split it out
1329 * as a separate function.
1331 simple = simplify_function(expr->opfuncid, expr->opresulttype,
1332 args, false, context);
1333 if (simple) /* successfully simplified it */
1336 * Since the underlying operator is "=", must negate its
1339 Const *csimple = (Const *) simple;
1341 Assert(IsA(csimple, Const));
1342 csimple->constvalue =
1343 BoolGetDatum(!DatumGetBool(csimple->constvalue));
1344 return (Node *) csimple;
1349 * The expression cannot be simplified any further, so build and
1350 * return a replacement DistinctExpr node using the
1351 * possibly-simplified arguments.
1353 newexpr = makeNode(DistinctExpr);
1354 newexpr->opno = expr->opno;
1355 newexpr->opfuncid = expr->opfuncid;
1356 newexpr->opresulttype = expr->opresulttype;
1357 newexpr->opretset = expr->opretset;
1358 newexpr->args = args;
1359 return (Node *) newexpr;
1361 if (IsA(node, BoolExpr))
1363 BoolExpr *expr = (BoolExpr *) node;
1367 * Reduce constants in the BoolExpr's arguments. We know args is
1368 * either NIL or a List node, so we can call
1369 * expression_tree_mutator directly rather than recursing to self.
1371 args = (List *) expression_tree_mutator((Node *) expr->args,
1372 eval_const_expressions_mutator,
1375 switch (expr->boolop)
1380 bool haveNull = false;
1381 bool forceTrue = false;
1383 newargs = simplify_or_arguments(args,
1384 &haveNull, &forceTrue);
1386 return makeBoolConst(true, false);
1388 newargs = lappend(newargs, makeBoolConst(false, true));
1389 /* If all the inputs are FALSE, result is FALSE */
1391 return makeBoolConst(false, false);
1392 /* If only one nonconst-or-NULL input, it's the result */
1393 if (list_length(newargs) == 1)
1394 return (Node *) linitial(newargs);
1395 /* Else we still need an OR node */
1396 return (Node *) make_orclause(newargs);
1401 bool haveNull = false;
1402 bool forceFalse = false;
1404 newargs = simplify_and_arguments(args,
1405 &haveNull, &forceFalse);
1407 return makeBoolConst(false, false);
1409 newargs = lappend(newargs, makeBoolConst(false, true));
1410 /* If all the inputs are TRUE, result is TRUE */
1412 return makeBoolConst(true, false);
1413 /* If only one nonconst-or-NULL input, it's the result */
1414 if (list_length(newargs) == 1)
1415 return (Node *) linitial(newargs);
1416 /* Else we still need an AND node */
1417 return (Node *) make_andclause(newargs);
1420 Assert(list_length(args) == 1);
1421 if (IsA(linitial(args), Const))
1423 Const *const_input = (Const *) linitial(args);
1425 /* NOT NULL => NULL */
1426 if (const_input->constisnull)
1427 return makeBoolConst(false, true);
1428 /* otherwise pretty easy */
1429 return makeBoolConst(!DatumGetBool(const_input->constvalue),
1432 else if (not_clause((Node *) linitial(args)))
1434 /* Cancel NOT/NOT */
1435 return (Node *) get_notclausearg((Expr *) linitial(args));
1437 /* Else we still need a NOT node */
1438 return (Node *) make_notclause((Expr *) linitial(args));
1440 elog(ERROR, "unrecognized boolop: %d",
1441 (int) expr->boolop);
1445 if (IsA(node, SubPlan))
1448 * Return a SubPlan unchanged --- too late to do anything with it.
1450 * XXX should we ereport() here instead? Probably this routine
1451 * should never be invoked after SubPlan creation.
1455 if (IsA(node, RelabelType))
1458 * If we can simplify the input to a constant, then we don't need
1459 * the RelabelType node anymore: just change the type field of the
1460 * Const node. Otherwise, must copy the RelabelType node.
1462 RelabelType *relabel = (RelabelType *) node;
1465 arg = eval_const_expressions_mutator((Node *) relabel->arg,
1469 * If we find stacked RelabelTypes (eg, from foo :: int :: oid) we
1470 * can discard all but the top one.
1472 while (arg && IsA(arg, RelabelType))
1473 arg = (Node *) ((RelabelType *) arg)->arg;
1475 if (arg && IsA(arg, Const))
1477 Const *con = (Const *) arg;
1479 con->consttype = relabel->resulttype;
1482 * relabel's resulttypmod is discarded, which is OK for now;
1483 * if the type actually needs a runtime length coercion then
1484 * there should be a function call to do it just above this
1487 return (Node *) con;
1491 RelabelType *newrelabel = makeNode(RelabelType);
1493 newrelabel->arg = (Expr *) arg;
1494 newrelabel->resulttype = relabel->resulttype;
1495 newrelabel->resulttypmod = relabel->resulttypmod;
1496 return (Node *) newrelabel;
1499 if (IsA(node, CaseExpr))
1502 * CASE expressions can be simplified if there are constant
1503 * condition clauses:
1504 * FALSE (or NULL): drop the alternative
1505 * TRUE: drop all remaining alternatives
1506 * If the first non-FALSE alternative is a constant TRUE, we can
1507 * simplify the entire CASE to that alternative's expression.
1508 * If there are no non-FALSE alternatives, we simplify the entire
1509 * CASE to the default result (ELSE result).
1511 * If we have a simple-form CASE with constant test expression and
1512 * one or more constant comparison expressions, we could run the
1513 * implied comparisons and potentially reduce those arms to constants.
1514 * This is not yet implemented, however. At present, the
1515 * CaseTestExpr placeholder will always act as a non-constant node
1516 * and prevent the comparison boolean expressions from being reduced
1520 CaseExpr *caseexpr = (CaseExpr *) node;
1528 /* Simplify the test expression, if any */
1529 newarg = eval_const_expressions_mutator((Node *) caseexpr->arg,
1532 /* Simplify the WHEN clauses */
1534 foreach(arg, caseexpr->args)
1536 /* Simplify this alternative's condition and result */
1537 CaseWhen *casewhen = (CaseWhen *)
1538 expression_tree_mutator((Node *) lfirst(arg),
1539 eval_const_expressions_mutator,
1542 Assert(IsA(casewhen, CaseWhen));
1543 if (casewhen->expr == NULL ||
1544 !IsA(casewhen->expr, Const))
1546 newargs = lappend(newargs, casewhen);
1549 const_input = (Const *) casewhen->expr;
1550 if (const_input->constisnull ||
1551 !DatumGetBool(const_input->constvalue))
1552 continue; /* drop alternative with FALSE condition */
1555 * Found a TRUE condition. If it's the first (un-dropped)
1556 * alternative, the CASE reduces to just this alternative.
1559 return (Node *) casewhen->result;
1562 * Otherwise, add it to the list, and drop all the rest.
1564 newargs = lappend(newargs, casewhen);
1568 /* Simplify the default result */
1569 defresult = eval_const_expressions_mutator((Node *) caseexpr->defresult,
1573 * If no non-FALSE alternatives, CASE reduces to the default
1578 /* Otherwise we need a new CASE node */
1579 newcase = makeNode(CaseExpr);
1580 newcase->casetype = caseexpr->casetype;
1581 newcase->arg = (Expr *) newarg;
1582 newcase->args = newargs;
1583 newcase->defresult = (Expr *) defresult;
1584 return (Node *) newcase;
1586 if (IsA(node, ArrayExpr))
1588 ArrayExpr *arrayexpr = (ArrayExpr *) node;
1589 ArrayExpr *newarray;
1590 bool all_const = true;
1595 foreach(element, arrayexpr->elements)
1599 e = eval_const_expressions_mutator((Node *) lfirst(element),
1603 newelems = lappend(newelems, e);
1606 newarray = makeNode(ArrayExpr);
1607 newarray->array_typeid = arrayexpr->array_typeid;
1608 newarray->element_typeid = arrayexpr->element_typeid;
1609 newarray->elements = newelems;
1610 newarray->multidims = arrayexpr->multidims;
1613 return (Node *) evaluate_expr((Expr *) newarray,
1614 newarray->array_typeid);
1616 return (Node *) newarray;
1618 if (IsA(node, CoalesceExpr))
1620 CoalesceExpr *coalesceexpr = (CoalesceExpr *) node;
1621 CoalesceExpr *newcoalesce;
1626 foreach(arg, coalesceexpr->args)
1630 e = eval_const_expressions_mutator((Node *) lfirst(arg),
1634 * We can remove null constants from the list. For a non-null
1635 * constant, if it has not been preceded by any other
1636 * non-null-constant expressions then that is the result.
1640 if (((Const *) e)->constisnull)
1641 continue; /* drop null constant */
1643 return e; /* first expr */
1645 newargs = lappend(newargs, e);
1648 newcoalesce = makeNode(CoalesceExpr);
1649 newcoalesce->coalescetype = coalesceexpr->coalescetype;
1650 newcoalesce->args = newargs;
1651 return (Node *) newcoalesce;
1653 if (IsA(node, FieldSelect))
1656 * We can optimize field selection from a whole-row Var into a
1657 * simple Var. (This case won't be generated directly by the
1658 * parser, because ParseComplexProjection short-circuits it. But
1659 * it can arise while simplifying functions.) Also, we can
1660 * optimize field selection from a RowExpr construct.
1662 * We must however check that the declared type of the field is
1663 * still the same as when the FieldSelect was created --- this
1664 * can change if someone did ALTER COLUMN TYPE on the rowtype.
1666 FieldSelect *fselect = (FieldSelect *) node;
1667 FieldSelect *newfselect;
1670 arg = eval_const_expressions_mutator((Node *) fselect->arg,
1672 if (arg && IsA(arg, Var) &&
1673 ((Var *) arg)->varattno == InvalidAttrNumber)
1675 if (rowtype_field_matches(((Var *) arg)->vartype,
1677 fselect->resulttype,
1678 fselect->resulttypmod))
1679 return (Node *) makeVar(((Var *) arg)->varno,
1681 fselect->resulttype,
1682 fselect->resulttypmod,
1683 ((Var *) arg)->varlevelsup);
1685 if (arg && IsA(arg, RowExpr))
1687 RowExpr *rowexpr = (RowExpr *) arg;
1689 if (fselect->fieldnum > 0 &&
1690 fselect->fieldnum <= list_length(rowexpr->args))
1692 Node *fld = (Node *) list_nth(rowexpr->args,
1693 fselect->fieldnum - 1);
1695 if (rowtype_field_matches(rowexpr->row_typeid,
1697 fselect->resulttype,
1698 fselect->resulttypmod) &&
1699 fselect->resulttype == exprType(fld) &&
1700 fselect->resulttypmod == exprTypmod(fld))
1704 newfselect = makeNode(FieldSelect);
1705 newfselect->arg = (Expr *) arg;
1706 newfselect->fieldnum = fselect->fieldnum;
1707 newfselect->resulttype = fselect->resulttype;
1708 newfselect->resulttypmod = fselect->resulttypmod;
1709 return (Node *) newfselect;
1713 * For any node type not handled above, we recurse using
1714 * expression_tree_mutator, which will copy the node unchanged but try
1715 * to simplify its arguments (if any) using this routine. For example:
1716 * we cannot eliminate an ArrayRef node, but we might be able to
1717 * simplify constant expressions in its subscripts.
1719 return expression_tree_mutator(node, eval_const_expressions_mutator,
1724 * Subroutine for eval_const_expressions: scan the arguments of an OR clause
1726 * OR arguments are handled as follows:
1727 * non constant: keep
1728 * FALSE: drop (does not affect result)
1729 * TRUE: force result to TRUE
1730 * NULL: keep only one
1731 * We must keep one NULL input because ExecEvalOr returns NULL when no input
1732 * is TRUE and at least one is NULL.
1734 * This is split out as a subroutine so that we can recurse to fold sub-ORs
1735 * into the upper OR clause, thereby preserving AND/OR flatness.
1737 * The output arguments *haveNull and *forceTrue must be initialized FALSE
1738 * by the caller. They will be set TRUE if a null constant or true constant,
1739 * respectively, is detected anywhere in the argument list.
1742 simplify_or_arguments(List *args, bool *haveNull, bool *forceTrue)
1744 List *newargs = NIL;
1749 Node *arg = (Node *) lfirst(larg);
1751 if (IsA(arg, Const))
1753 Const *const_input = (Const *) arg;
1755 if (const_input->constisnull)
1757 else if (DatumGetBool(const_input->constvalue))
1761 * Once we detect a TRUE result we can just exit the loop
1762 * immediately. However, if we ever add a notion of
1763 * non-removable functions, we'd need to keep scanning.
1767 /* otherwise, we can drop the constant-false input */
1769 else if (or_clause(arg))
1771 newargs = list_concat(newargs,
1772 simplify_or_arguments(((BoolExpr *) arg)->args,
1773 haveNull, forceTrue));
1777 newargs = lappend(newargs, arg);
1785 * Subroutine for eval_const_expressions: scan the arguments of an AND clause
1787 * AND arguments are handled as follows:
1788 * non constant: keep
1789 * TRUE: drop (does not affect result)
1790 * FALSE: force result to FALSE
1791 * NULL: keep only one
1792 * We must keep one NULL input because ExecEvalAnd returns NULL when no input
1793 * is FALSE and at least one is NULL.
1795 * This is split out as a subroutine so that we can recurse to fold sub-ANDs
1796 * into the upper AND clause, thereby preserving AND/OR flatness.
1798 * The output arguments *haveNull and *forceFalse must be initialized FALSE
1799 * by the caller. They will be set TRUE if a null constant or false constant,
1800 * respectively, is detected anywhere in the argument list.
1803 simplify_and_arguments(List *args, bool *haveNull, bool *forceFalse)
1805 List *newargs = NIL;
1810 Node *arg = (Node *) lfirst(larg);
1812 if (IsA(arg, Const))
1814 Const *const_input = (Const *) arg;
1816 if (const_input->constisnull)
1818 else if (!DatumGetBool(const_input->constvalue))
1822 * Once we detect a FALSE result we can just exit the loop
1823 * immediately. However, if we ever add a notion of
1824 * non-removable functions, we'd need to keep scanning.
1828 /* otherwise, we can drop the constant-true input */
1830 else if (and_clause(arg))
1832 newargs = list_concat(newargs,
1833 simplify_and_arguments(((BoolExpr *) arg)->args,
1834 haveNull, forceFalse));
1838 newargs = lappend(newargs, arg);
1846 * Subroutine for eval_const_expressions: try to simplify a function call
1847 * (which might originally have been an operator; we don't care)
1849 * Inputs are the function OID, actual result type OID (which is needed for
1850 * polymorphic functions), and the pre-simplified argument list;
1851 * also the context data for eval_const_expressions.
1853 * Returns a simplified expression if successful, or NULL if cannot
1854 * simplify the function call.
1857 simplify_function(Oid funcid, Oid result_type, List *args,
1859 eval_const_expressions_context *context)
1861 HeapTuple func_tuple;
1865 * We have two strategies for simplification: either execute the
1866 * function to deliver a constant result, or expand in-line the body
1867 * of the function definition (which only works for simple
1868 * SQL-language functions, but that is a common case). In either case
1869 * we need access to the function's pg_proc tuple, so fetch it just
1870 * once to use in both attempts.
1872 func_tuple = SearchSysCache(PROCOID,
1873 ObjectIdGetDatum(funcid),
1875 if (!HeapTupleIsValid(func_tuple))
1876 elog(ERROR, "cache lookup failed for function %u", funcid);
1878 newexpr = evaluate_function(funcid, result_type, args, func_tuple);
1880 if (!newexpr && allow_inline)
1881 newexpr = inline_function(funcid, result_type, args,
1882 func_tuple, context);
1884 ReleaseSysCache(func_tuple);
1890 * evaluate_function: try to pre-evaluate a function call
1892 * We can do this if the function is strict and has any constant-null inputs
1893 * (just return a null constant), or if the function is immutable and has all
1894 * constant inputs (call it and return the result as a Const node).
1896 * Returns a simplified expression if successful, or NULL if cannot
1897 * simplify the function.
1900 evaluate_function(Oid funcid, Oid result_type, List *args,
1901 HeapTuple func_tuple)
1903 Form_pg_proc funcform = (Form_pg_proc) GETSTRUCT(func_tuple);
1904 bool has_nonconst_input = false;
1905 bool has_null_input = false;
1910 * Can't simplify if it returns a set.
1912 if (funcform->proretset)
1916 * Check for constant inputs and especially constant-NULL inputs.
1920 if (IsA(lfirst(arg), Const))
1921 has_null_input |= ((Const *) lfirst(arg))->constisnull;
1923 has_nonconst_input = true;
1927 * If the function is strict and has a constant-NULL input, it will
1928 * never be called at all, so we can replace the call by a NULL
1929 * constant, even if there are other inputs that aren't constant, and
1930 * even if the function is not otherwise immutable.
1932 if (funcform->proisstrict && has_null_input)
1933 return (Expr *) makeNullConst(result_type);
1936 * Otherwise, can simplify only if the function is immutable and all
1937 * inputs are constants. (For a non-strict function, constant NULL
1938 * inputs are treated the same as constant non-NULL inputs.)
1940 if (funcform->provolatile != PROVOLATILE_IMMUTABLE ||
1945 * OK, looks like we can simplify this operator/function.
1947 * Build a new FuncExpr node containing the already-simplified arguments.
1949 newexpr = makeNode(FuncExpr);
1950 newexpr->funcid = funcid;
1951 newexpr->funcresulttype = result_type;
1952 newexpr->funcretset = false;
1953 newexpr->funcformat = COERCE_DONTCARE; /* doesn't matter */
1954 newexpr->args = args;
1956 return evaluate_expr((Expr *) newexpr, result_type);
1960 * inline_function: try to expand a function call inline
1962 * If the function is a sufficiently simple SQL-language function
1963 * (just "SELECT expression"), then we can inline it and avoid the rather
1964 * high per-call overhead of SQL functions. Furthermore, this can expose
1965 * opportunities for constant-folding within the function expression.
1967 * We have to beware of some special cases however. A directly or
1968 * indirectly recursive function would cause us to recurse forever,
1969 * so we keep track of which functions we are already expanding and
1970 * do not re-expand them. Also, if a parameter is used more than once
1971 * in the SQL-function body, we require it not to contain any volatile
1972 * functions (volatiles might deliver inconsistent answers) nor to be
1973 * unreasonably expensive to evaluate. The expensiveness check not only
1974 * prevents us from doing multiple evaluations of an expensive parameter
1975 * at runtime, but is a safety value to limit growth of an expression due
1976 * to repeated inlining.
1978 * We must also beware of changing the volatility or strictness status of
1979 * functions by inlining them.
1981 * Returns a simplified expression if successful, or NULL if cannot
1982 * simplify the function.
1985 inline_function(Oid funcid, Oid result_type, List *args,
1986 HeapTuple func_tuple,
1987 eval_const_expressions_context *context)
1989 Form_pg_proc funcform = (Form_pg_proc) GETSTRUCT(func_tuple);
1990 bool polymorphic = false;
1991 Oid argtypes[FUNC_MAX_ARGS];
1995 MemoryContext oldcxt;
1996 MemoryContext mycxt;
1997 ErrorContextCallback sqlerrcontext;
1998 List *raw_parsetree_list;
1999 List *querytree_list;
2007 * Forget it if the function is not SQL-language or has other
2008 * showstopper properties. (The nargs check is just paranoia.)
2010 if (funcform->prolang != SQLlanguageId ||
2011 funcform->prosecdef ||
2012 funcform->proretset ||
2013 funcform->pronargs != list_length(args))
2016 /* Check for recursive function, and give up trying to expand if so */
2017 if (list_member_oid(context->active_fns, funcid))
2020 /* Check permission to call function (fail later, if not) */
2021 if (pg_proc_aclcheck(funcid, GetUserId(), ACL_EXECUTE) != ACLCHECK_OK)
2024 /* Check for polymorphic arguments, and substitute actual arg types */
2025 memcpy(argtypes, funcform->proargtypes, FUNC_MAX_ARGS * sizeof(Oid));
2026 for (i = 0; i < funcform->pronargs; i++)
2028 if (argtypes[i] == ANYARRAYOID ||
2029 argtypes[i] == ANYELEMENTOID)
2032 argtypes[i] = exprType((Node *) list_nth(args, i));
2036 if (funcform->prorettype == ANYARRAYOID ||
2037 funcform->prorettype == ANYELEMENTOID)
2041 * Setup error traceback support for ereport(). This is so that we
2042 * can finger the function that bad information came from.
2044 sqlerrcontext.callback = sql_inline_error_callback;
2045 sqlerrcontext.arg = func_tuple;
2046 sqlerrcontext.previous = error_context_stack;
2047 error_context_stack = &sqlerrcontext;
2050 * Make a temporary memory context, so that we don't leak all the
2051 * stuff that parsing might create.
2053 mycxt = AllocSetContextCreate(CurrentMemoryContext,
2055 ALLOCSET_DEFAULT_MINSIZE,
2056 ALLOCSET_DEFAULT_INITSIZE,
2057 ALLOCSET_DEFAULT_MAXSIZE);
2058 oldcxt = MemoryContextSwitchTo(mycxt);
2060 /* Fetch and parse the function body */
2061 tmp = SysCacheGetAttr(PROCOID,
2063 Anum_pg_proc_prosrc,
2066 elog(ERROR, "null prosrc for function %u", funcid);
2067 src = DatumGetCString(DirectFunctionCall1(textout, tmp));
2070 * We just do parsing and parse analysis, not rewriting, because
2071 * rewriting will not affect table-free-SELECT-only queries, which is
2072 * all that we care about. Also, we can punt as soon as we detect
2073 * more than one command in the function body.
2075 raw_parsetree_list = pg_parse_query(src);
2076 if (list_length(raw_parsetree_list) != 1)
2079 querytree_list = parse_analyze(linitial(raw_parsetree_list),
2080 argtypes, funcform->pronargs);
2082 if (list_length(querytree_list) != 1)
2085 querytree = (Query *) linitial(querytree_list);
2088 * The single command must be a simple "SELECT expression".
2090 if (!IsA(querytree, Query) ||
2091 querytree->commandType != CMD_SELECT ||
2092 querytree->resultRelation != 0 ||
2094 querytree->hasAggs ||
2095 querytree->hasSubLinks ||
2096 querytree->rtable ||
2097 querytree->jointree->fromlist ||
2098 querytree->jointree->quals ||
2099 querytree->groupClause ||
2100 querytree->havingQual ||
2101 querytree->distinctClause ||
2102 querytree->sortClause ||
2103 querytree->limitOffset ||
2104 querytree->limitCount ||
2105 querytree->setOperations ||
2106 list_length(querytree->targetList) != 1)
2109 newexpr = (Node *) ((TargetEntry *) linitial(querytree->targetList))->expr;
2112 * If the function has any arguments declared as polymorphic types,
2113 * then it wasn't type-checked at definition time; must do so now.
2114 * (This will raise an error if wrong, but that's okay since the
2115 * function would fail at runtime anyway. Note we do not try this
2116 * until we have verified that no rewriting was needed; that's
2117 * probably not important, but let's be careful.)
2120 (void) check_sql_fn_retval(result_type, get_typtype(result_type),
2124 * Additional validity checks on the expression. It mustn't return a
2125 * set, and it mustn't be more volatile than the surrounding function
2126 * (this is to avoid breaking hacks that involve pretending a function
2127 * is immutable when it really ain't). If the surrounding function is
2128 * declared strict, then the expression must contain only strict
2129 * constructs and must use all of the function parameters (this is
2130 * overkill, but an exact analysis is hard).
2132 if (expression_returns_set(newexpr))
2135 if (funcform->provolatile == PROVOLATILE_IMMUTABLE &&
2136 contain_mutable_functions(newexpr))
2138 else if (funcform->provolatile == PROVOLATILE_STABLE &&
2139 contain_volatile_functions(newexpr))
2142 if (funcform->proisstrict &&
2143 contain_nonstrict_functions(newexpr))
2147 * We may be able to do it; there are still checks on parameter usage
2148 * to make, but those are most easily done in combination with the
2149 * actual substitution of the inputs. So start building expression
2150 * with inputs substituted.
2152 usecounts = (int *) palloc0(funcform->pronargs * sizeof(int));
2153 newexpr = substitute_actual_parameters(newexpr, funcform->pronargs,
2156 /* Now check for parameter usage */
2160 Node *param = lfirst(arg);
2162 if (usecounts[i] == 0)
2164 /* Param not used at all: uncool if func is strict */
2165 if (funcform->proisstrict)
2168 else if (usecounts[i] != 1)
2170 /* Param used multiple times: uncool if expensive or volatile */
2174 * We define "expensive" as "contains any subplan or more than
2175 * 10 operators". Note that the subplan search has to be done
2176 * explicitly, since cost_qual_eval() will barf on unplanned
2179 if (contain_subplans(param))
2181 cost_qual_eval(&eval_cost, list_make1(param));
2182 if (eval_cost.startup + eval_cost.per_tuple >
2183 10 * cpu_operator_cost)
2187 * Check volatility last since this is more expensive than the
2190 if (contain_volatile_functions(param))
2197 * Whew --- we can make the substitution. Copy the modified
2198 * expression out of the temporary memory context, and clean up.
2200 MemoryContextSwitchTo(oldcxt);
2202 newexpr = copyObject(newexpr);
2204 MemoryContextDelete(mycxt);
2207 * Recursively try to simplify the modified expression. Here we must
2208 * add the current function to the context list of active functions.
2210 context->active_fns = lcons_oid(funcid, context->active_fns);
2211 newexpr = eval_const_expressions_mutator(newexpr, context);
2212 context->active_fns = list_delete_first(context->active_fns);
2214 error_context_stack = sqlerrcontext.previous;
2216 return (Expr *) newexpr;
2218 /* Here if func is not inlinable: release temp memory and return NULL */
2220 MemoryContextSwitchTo(oldcxt);
2221 MemoryContextDelete(mycxt);
2222 error_context_stack = sqlerrcontext.previous;
2228 * Replace Param nodes by appropriate actual parameters
2231 substitute_actual_parameters(Node *expr, int nargs, List *args,
2234 substitute_actual_parameters_context context;
2236 context.nargs = nargs;
2237 context.args = args;
2238 context.usecounts = usecounts;
2240 return substitute_actual_parameters_mutator(expr, &context);
2244 substitute_actual_parameters_mutator(Node *node,
2245 substitute_actual_parameters_context *context)
2249 if (IsA(node, Param))
2251 Param *param = (Param *) node;
2253 if (param->paramkind != PARAM_NUM)
2254 elog(ERROR, "unexpected paramkind: %d", param->paramkind);
2255 if (param->paramid <= 0 || param->paramid > context->nargs)
2256 elog(ERROR, "invalid paramid: %d", param->paramid);
2258 /* Count usage of parameter */
2259 context->usecounts[param->paramid - 1]++;
2261 /* Select the appropriate actual arg and replace the Param with it */
2262 /* We don't need to copy at this time (it'll get done later) */
2263 return list_nth(context->args, param->paramid - 1);
2265 return expression_tree_mutator(node, substitute_actual_parameters_mutator,
2270 * error context callback to let us supply a call-stack traceback
2273 sql_inline_error_callback(void *arg)
2275 HeapTuple func_tuple = (HeapTuple) arg;
2276 Form_pg_proc funcform = (Form_pg_proc) GETSTRUCT(func_tuple);
2277 int syntaxerrposition;
2279 /* If it's a syntax error, convert to internal syntax error report */
2280 syntaxerrposition = geterrposition();
2281 if (syntaxerrposition > 0)
2287 tmp = SysCacheGetAttr(PROCOID, func_tuple, Anum_pg_proc_prosrc,
2290 elog(ERROR, "null prosrc");
2291 prosrc = DatumGetCString(DirectFunctionCall1(textout, tmp));
2293 internalerrposition(syntaxerrposition);
2294 internalerrquery(prosrc);
2297 errcontext("SQL function \"%s\" during inlining",
2298 NameStr(funcform->proname));
2302 * evaluate_expr: pre-evaluate a constant expression
2304 * We use the executor's routine ExecEvalExpr() to avoid duplication of
2305 * code and ensure we get the same result as the executor would get.
2308 evaluate_expr(Expr *expr, Oid result_type)
2311 ExprState *exprstate;
2312 MemoryContext oldcontext;
2316 bool resultTypByVal;
2319 * To use the executor, we need an EState.
2321 estate = CreateExecutorState();
2323 /* We can use the estate's working context to avoid memory leaks. */
2324 oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
2327 * Prepare expr for execution.
2329 exprstate = ExecPrepareExpr(expr, estate);
2334 * It is OK to use a default econtext because none of the ExecEvalExpr()
2335 * code used in this situation will use econtext. That might seem
2336 * fortuitous, but it's not so unreasonable --- a constant expression
2337 * does not depend on context, by definition, n'est ce pas?
2339 const_val = ExecEvalExprSwitchContext(exprstate,
2340 GetPerTupleExprContext(estate),
2341 &const_is_null, NULL);
2343 /* Get info needed about result datatype */
2344 get_typlenbyval(result_type, &resultTypLen, &resultTypByVal);
2346 /* Get back to outer memory context */
2347 MemoryContextSwitchTo(oldcontext);
2349 /* Must copy result out of sub-context used by expression eval */
2351 const_val = datumCopy(const_val, resultTypByVal, resultTypLen);
2353 /* Release all the junk we just created */
2354 FreeExecutorState(estate);
2357 * Make the constant result node.
2359 return (Expr *) makeConst(result_type, resultTypLen,
2360 const_val, const_is_null,
2366 * Standard expression-tree walking support
2368 * We used to have near-duplicate code in many different routines that
2369 * understood how to recurse through an expression node tree. That was
2370 * a pain to maintain, and we frequently had bugs due to some particular
2371 * routine neglecting to support a particular node type. In most cases,
2372 * these routines only actually care about certain node types, and don't
2373 * care about other types except insofar as they have to recurse through
2374 * non-primitive node types. Therefore, we now provide generic tree-walking
2375 * logic to consolidate the redundant "boilerplate" code. There are
2376 * two versions: expression_tree_walker() and expression_tree_mutator().
2379 /*--------------------
2380 * expression_tree_walker() is designed to support routines that traverse
2381 * a tree in a read-only fashion (although it will also work for routines
2382 * that modify nodes in-place but never add/delete/replace nodes).
2383 * A walker routine should look like this:
2385 * bool my_walker (Node *node, my_struct *context)
2389 * // check for nodes that special work is required for, eg:
2390 * if (IsA(node, Var))
2392 * ... do special actions for Var nodes
2394 * else if (IsA(node, ...))
2396 * ... do special actions for other node types
2398 * // for any node type not specially processed, do:
2399 * return expression_tree_walker(node, my_walker, (void *) context);
2402 * The "context" argument points to a struct that holds whatever context
2403 * information the walker routine needs --- it can be used to return data
2404 * gathered by the walker, too. This argument is not touched by
2405 * expression_tree_walker, but it is passed down to recursive sub-invocations
2406 * of my_walker. The tree walk is started from a setup routine that
2407 * fills in the appropriate context struct, calls my_walker with the top-level
2408 * node of the tree, and then examines the results.
2410 * The walker routine should return "false" to continue the tree walk, or
2411 * "true" to abort the walk and immediately return "true" to the top-level
2412 * caller. This can be used to short-circuit the traversal if the walker
2413 * has found what it came for. "false" is returned to the top-level caller
2414 * iff no invocation of the walker returned "true".
2416 * The node types handled by expression_tree_walker include all those
2417 * normally found in target lists and qualifier clauses during the planning
2418 * stage. In particular, it handles List nodes since a cnf-ified qual clause
2419 * will have List structure at the top level, and it handles TargetEntry nodes
2420 * so that a scan of a target list can be handled without additional code.
2421 * (But only the "expr" part of a TargetEntry is examined, unless the walker
2422 * chooses to process TargetEntry nodes specially.) Also, RangeTblRef,
2423 * FromExpr, JoinExpr, and SetOperationStmt nodes are handled, so that query
2424 * jointrees and setOperation trees can be processed without additional code.
2426 * expression_tree_walker will handle SubLink nodes by recursing normally into
2427 * the "lefthand" arguments (which are expressions belonging to the outer
2428 * plan). It will also call the walker on the sub-Query node; however, when
2429 * expression_tree_walker itself is called on a Query node, it does nothing
2430 * and returns "false". The net effect is that unless the walker does
2431 * something special at a Query node, sub-selects will not be visited during
2432 * an expression tree walk. This is exactly the behavior wanted in many cases
2433 * --- and for those walkers that do want to recurse into sub-selects, special
2434 * behavior is typically needed anyway at the entry to a sub-select (such as
2435 * incrementing a depth counter). A walker that wants to examine sub-selects
2436 * should include code along the lines of:
2438 * if (IsA(node, Query))
2440 * adjust context for subquery;
2441 * result = query_tree_walker((Query *) node, my_walker, context,
2442 * 0); // adjust flags as needed
2443 * restore context if needed;
2447 * query_tree_walker is a convenience routine (see below) that calls the
2448 * walker on all the expression subtrees of the given Query node.
2450 * expression_tree_walker will handle SubPlan nodes by recursing normally
2451 * into the "exprs" and "args" lists (which are expressions belonging to
2452 * the outer plan). It will not touch the completed subplan, however. Since
2453 * there is no link to the original Query, it is not possible to recurse into
2454 * subselects of an already-planned expression tree. This is OK for current
2455 * uses, but may need to be revisited in future.
2456 *--------------------
2460 expression_tree_walker(Node *node,
2467 * The walker has already visited the current node, and so we need
2468 * only recurse into any sub-nodes it has.
2470 * We assume that the walker is not interested in List nodes per se, so
2471 * when we expect a List we just recurse directly to self without
2472 * bothering to call the walker.
2477 /* Guard against stack overflow due to overly complex expressions */
2478 check_stack_depth();
2480 switch (nodeTag(node))
2485 case T_CoerceToDomainValue:
2486 case T_CaseTestExpr:
2487 case T_SetToDefault:
2489 /* primitive node types with no subnodes */
2492 return walker(((Aggref *) node)->target, context);
2495 ArrayRef *aref = (ArrayRef *) node;
2497 /* recurse directly for upper/lower array index lists */
2498 if (expression_tree_walker((Node *) aref->refupperindexpr,
2501 if (expression_tree_walker((Node *) aref->reflowerindexpr,
2504 /* walker must see the refexpr and refassgnexpr, however */
2505 if (walker(aref->refexpr, context))
2507 if (walker(aref->refassgnexpr, context))
2513 FuncExpr *expr = (FuncExpr *) node;
2515 if (expression_tree_walker((Node *) expr->args,
2522 OpExpr *expr = (OpExpr *) node;
2524 if (expression_tree_walker((Node *) expr->args,
2529 case T_DistinctExpr:
2531 DistinctExpr *expr = (DistinctExpr *) node;
2533 if (expression_tree_walker((Node *) expr->args,
2538 case T_ScalarArrayOpExpr:
2540 ScalarArrayOpExpr *expr = (ScalarArrayOpExpr *) node;
2542 if (expression_tree_walker((Node *) expr->args,
2549 BoolExpr *expr = (BoolExpr *) node;
2551 if (expression_tree_walker((Node *) expr->args,
2558 SubLink *sublink = (SubLink *) node;
2560 if (expression_tree_walker((Node *) sublink->lefthand,
2565 * Also invoke the walker on the sublink's Query node, so
2566 * it can recurse into the sub-query if it wants to.
2568 return walker(sublink->subselect, context);
2573 SubPlan *subplan = (SubPlan *) node;
2575 /* recurse into the exprs list, but not into the Plan */
2576 if (expression_tree_walker((Node *) subplan->exprs,
2579 /* also examine args list */
2580 if (expression_tree_walker((Node *) subplan->args,
2586 return walker(((FieldSelect *) node)->arg, context);
2589 FieldStore *fstore = (FieldStore *) node;
2591 if (walker(fstore->arg, context))
2593 if (walker(fstore->newvals, context))
2598 return walker(((RelabelType *) node)->arg, context);
2601 CaseExpr *caseexpr = (CaseExpr *) node;
2603 if (walker(caseexpr->arg, context))
2605 /* we assume walker doesn't care about CaseWhens, either */
2606 foreach(temp, caseexpr->args)
2608 CaseWhen *when = (CaseWhen *) lfirst(temp);
2610 Assert(IsA(when, CaseWhen));
2611 if (walker(when->expr, context))
2613 if (walker(when->result, context))
2616 if (walker(caseexpr->defresult, context))
2621 return walker(((ArrayExpr *) node)->elements, context);
2623 return walker(((RowExpr *) node)->args, context);
2624 case T_CoalesceExpr:
2625 return walker(((CoalesceExpr *) node)->args, context);
2627 return walker(((NullIfExpr *) node)->args, context);
2629 return walker(((NullTest *) node)->arg, context);
2631 return walker(((BooleanTest *) node)->arg, context);
2632 case T_CoerceToDomain:
2633 return walker(((CoerceToDomain *) node)->arg, context);
2635 return walker(((TargetEntry *) node)->expr, context);
2637 /* Do nothing with a sub-Query, per discussion above */
2640 foreach(temp, (List *) node)
2642 if (walker((Node *) lfirst(temp), context))
2648 FromExpr *from = (FromExpr *) node;
2650 if (walker(from->fromlist, context))
2652 if (walker(from->quals, context))
2658 JoinExpr *join = (JoinExpr *) node;
2660 if (walker(join->larg, context))
2662 if (walker(join->rarg, context))
2664 if (walker(join->quals, context))
2668 * alias clause, using list are deemed uninteresting.
2672 case T_SetOperationStmt:
2674 SetOperationStmt *setop = (SetOperationStmt *) node;
2676 if (walker(setop->larg, context))
2678 if (walker(setop->rarg, context))
2682 case T_InClauseInfo:
2684 InClauseInfo *ininfo = (InClauseInfo *) node;
2686 if (expression_tree_walker((Node *) ininfo->sub_targetlist,
2692 elog(ERROR, "unrecognized node type: %d",
2693 (int) nodeTag(node));
2700 * query_tree_walker --- initiate a walk of a Query's expressions
2702 * This routine exists just to reduce the number of places that need to know
2703 * where all the expression subtrees of a Query are. Note it can be used
2704 * for starting a walk at top level of a Query regardless of whether the
2705 * walker intends to descend into subqueries. It is also useful for
2706 * descending into subqueries within a walker.
2708 * Some callers want to suppress visitation of certain items in the sub-Query,
2709 * typically because they need to process them specially, or don't actually
2710 * want to recurse into subqueries. This is supported by the flags argument,
2711 * which is the bitwise OR of flag values to suppress visitation of
2712 * indicated items. (More flag bits may be added as needed.)
2715 query_tree_walker(Query *query,
2722 Assert(query != NULL && IsA(query, Query));
2724 if (walker((Node *) query->targetList, context))
2726 if (walker((Node *) query->jointree, context))
2728 if (walker(query->setOperations, context))
2730 if (walker(query->havingQual, context))
2732 if (walker(query->limitOffset, context))
2734 if (walker(query->limitCount, context))
2736 if (walker(query->in_info_list, context))
2738 foreach(rt, query->rtable)
2740 RangeTblEntry *rte = (RangeTblEntry *) lfirst(rt);
2742 switch (rte->rtekind)
2749 if (!(flags & QTW_IGNORE_RT_SUBQUERIES))
2750 if (walker(rte->subquery, context))
2754 if (!(flags & QTW_IGNORE_JOINALIASES))
2755 if (walker(rte->joinaliasvars, context))
2759 if (walker(rte->funcexpr, context))
2768 /*--------------------
2769 * expression_tree_mutator() is designed to support routines that make a
2770 * modified copy of an expression tree, with some nodes being added,
2771 * removed, or replaced by new subtrees. The original tree is (normally)
2772 * not changed. Each recursion level is responsible for returning a copy of
2773 * (or appropriately modified substitute for) the subtree it is handed.
2774 * A mutator routine should look like this:
2776 * Node * my_mutator (Node *node, my_struct *context)
2780 * // check for nodes that special work is required for, eg:
2781 * if (IsA(node, Var))
2783 * ... create and return modified copy of Var node
2785 * else if (IsA(node, ...))
2787 * ... do special transformations of other node types
2789 * // for any node type not specially processed, do:
2790 * return expression_tree_mutator(node, my_mutator, (void *) context);
2793 * The "context" argument points to a struct that holds whatever context
2794 * information the mutator routine needs --- it can be used to return extra
2795 * data gathered by the mutator, too. This argument is not touched by
2796 * expression_tree_mutator, but it is passed down to recursive sub-invocations
2797 * of my_mutator. The tree walk is started from a setup routine that
2798 * fills in the appropriate context struct, calls my_mutator with the
2799 * top-level node of the tree, and does any required post-processing.
2801 * Each level of recursion must return an appropriately modified Node.
2802 * If expression_tree_mutator() is called, it will make an exact copy
2803 * of the given Node, but invoke my_mutator() to copy the sub-node(s)
2804 * of that Node. In this way, my_mutator() has full control over the
2805 * copying process but need not directly deal with expression trees
2806 * that it has no interest in.
2808 * Just as for expression_tree_walker, the node types handled by
2809 * expression_tree_mutator include all those normally found in target lists
2810 * and qualifier clauses during the planning stage.
2812 * expression_tree_mutator will handle SubLink nodes by recursing normally
2813 * into the "lefthand" arguments (which are expressions belonging to the outer
2814 * plan). It will also call the mutator on the sub-Query node; however, when
2815 * expression_tree_mutator itself is called on a Query node, it does nothing
2816 * and returns the unmodified Query node. The net effect is that unless the
2817 * mutator does something special at a Query node, sub-selects will not be
2818 * visited or modified; the original sub-select will be linked to by the new
2819 * SubLink node. Mutators that want to descend into sub-selects will usually
2820 * do so by recognizing Query nodes and calling query_tree_mutator (below).
2822 * expression_tree_mutator will handle a SubPlan node by recursing into
2823 * the "exprs" and "args" lists (which belong to the outer plan), but it
2824 * will simply copy the link to the inner plan, since that's typically what
2825 * expression tree mutators want. A mutator that wants to modify the subplan
2826 * can force appropriate behavior by recognizing SubPlan expression nodes
2827 * and doing the right thing.
2828 *--------------------
2832 expression_tree_mutator(Node *node,
2833 Node *(*mutator) (),
2837 * The mutator has already decided not to modify the current node, but
2838 * we must call the mutator for any sub-nodes.
2841 #define FLATCOPY(newnode, node, nodetype) \
2842 ( (newnode) = makeNode(nodetype), \
2843 memcpy((newnode), (node), sizeof(nodetype)) )
2845 #define CHECKFLATCOPY(newnode, node, nodetype) \
2846 ( AssertMacro(IsA((node), nodetype)), \
2847 (newnode) = makeNode(nodetype), \
2848 memcpy((newnode), (node), sizeof(nodetype)) )
2850 #define MUTATE(newfield, oldfield, fieldtype) \
2851 ( (newfield) = (fieldtype) mutator((Node *) (oldfield), context) )
2856 /* Guard against stack overflow due to overly complex expressions */
2857 check_stack_depth();
2859 switch (nodeTag(node))
2864 case T_CoerceToDomainValue:
2865 case T_CaseTestExpr:
2866 case T_SetToDefault:
2868 /* primitive node types with no subnodes */
2869 return (Node *) copyObject(node);
2872 Aggref *aggref = (Aggref *) node;
2875 FLATCOPY(newnode, aggref, Aggref);
2876 MUTATE(newnode->target, aggref->target, Expr *);
2877 return (Node *) newnode;
2882 ArrayRef *arrayref = (ArrayRef *) node;
2885 FLATCOPY(newnode, arrayref, ArrayRef);
2886 MUTATE(newnode->refupperindexpr, arrayref->refupperindexpr,
2888 MUTATE(newnode->reflowerindexpr, arrayref->reflowerindexpr,
2890 MUTATE(newnode->refexpr, arrayref->refexpr,
2892 MUTATE(newnode->refassgnexpr, arrayref->refassgnexpr,
2894 return (Node *) newnode;
2899 FuncExpr *expr = (FuncExpr *) node;
2902 FLATCOPY(newnode, expr, FuncExpr);
2903 MUTATE(newnode->args, expr->args, List *);
2904 return (Node *) newnode;
2909 OpExpr *expr = (OpExpr *) node;
2912 FLATCOPY(newnode, expr, OpExpr);
2913 MUTATE(newnode->args, expr->args, List *);
2914 return (Node *) newnode;
2917 case T_DistinctExpr:
2919 DistinctExpr *expr = (DistinctExpr *) node;
2920 DistinctExpr *newnode;
2922 FLATCOPY(newnode, expr, DistinctExpr);
2923 MUTATE(newnode->args, expr->args, List *);
2924 return (Node *) newnode;
2927 case T_ScalarArrayOpExpr:
2929 ScalarArrayOpExpr *expr = (ScalarArrayOpExpr *) node;
2930 ScalarArrayOpExpr *newnode;
2932 FLATCOPY(newnode, expr, ScalarArrayOpExpr);
2933 MUTATE(newnode->args, expr->args, List *);
2934 return (Node *) newnode;
2939 BoolExpr *expr = (BoolExpr *) node;
2942 FLATCOPY(newnode, expr, BoolExpr);
2943 MUTATE(newnode->args, expr->args, List *);
2944 return (Node *) newnode;
2949 SubLink *sublink = (SubLink *) node;
2952 FLATCOPY(newnode, sublink, SubLink);
2953 MUTATE(newnode->lefthand, sublink->lefthand, List *);
2956 * Also invoke the mutator on the sublink's Query node, so
2957 * it can recurse into the sub-query if it wants to.
2959 MUTATE(newnode->subselect, sublink->subselect, Node *);
2960 return (Node *) newnode;
2965 SubPlan *subplan = (SubPlan *) node;
2968 FLATCOPY(newnode, subplan, SubPlan);
2969 /* transform exprs list */
2970 MUTATE(newnode->exprs, subplan->exprs, List *);
2971 /* transform args list (params to be passed to subplan) */
2972 MUTATE(newnode->args, subplan->args, List *);
2973 /* but not the sub-Plan itself, which is referenced as-is */
2974 return (Node *) newnode;
2979 FieldSelect *fselect = (FieldSelect *) node;
2980 FieldSelect *newnode;
2982 FLATCOPY(newnode, fselect, FieldSelect);
2983 MUTATE(newnode->arg, fselect->arg, Expr *);
2984 return (Node *) newnode;
2989 FieldStore *fstore = (FieldStore *) node;
2990 FieldStore *newnode;
2992 FLATCOPY(newnode, fstore, FieldStore);
2993 MUTATE(newnode->arg, fstore->arg, Expr *);
2994 MUTATE(newnode->newvals, fstore->newvals, List *);
2995 newnode->fieldnums = list_copy(fstore->fieldnums);
2996 return (Node *) newnode;
3001 RelabelType *relabel = (RelabelType *) node;
3002 RelabelType *newnode;
3004 FLATCOPY(newnode, relabel, RelabelType);
3005 MUTATE(newnode->arg, relabel->arg, Expr *);
3006 return (Node *) newnode;
3011 CaseExpr *caseexpr = (CaseExpr *) node;
3014 FLATCOPY(newnode, caseexpr, CaseExpr);
3015 MUTATE(newnode->arg, caseexpr->arg, Expr *);
3016 MUTATE(newnode->args, caseexpr->args, List *);
3017 MUTATE(newnode->defresult, caseexpr->defresult, Expr *);
3018 return (Node *) newnode;
3023 CaseWhen *casewhen = (CaseWhen *) node;
3026 FLATCOPY(newnode, casewhen, CaseWhen);
3027 MUTATE(newnode->expr, casewhen->expr, Expr *);
3028 MUTATE(newnode->result, casewhen->result, Expr *);
3029 return (Node *) newnode;
3034 ArrayExpr *arrayexpr = (ArrayExpr *) node;
3037 FLATCOPY(newnode, arrayexpr, ArrayExpr);
3038 MUTATE(newnode->elements, arrayexpr->elements, List *);
3039 return (Node *) newnode;
3044 RowExpr *rowexpr = (RowExpr *) node;
3047 FLATCOPY(newnode, rowexpr, RowExpr);
3048 MUTATE(newnode->args, rowexpr->args, List *);
3049 return (Node *) newnode;
3052 case T_CoalesceExpr:
3054 CoalesceExpr *coalesceexpr = (CoalesceExpr *) node;
3055 CoalesceExpr *newnode;
3057 FLATCOPY(newnode, coalesceexpr, CoalesceExpr);
3058 MUTATE(newnode->args, coalesceexpr->args, List *);
3059 return (Node *) newnode;
3064 NullIfExpr *expr = (NullIfExpr *) node;
3065 NullIfExpr *newnode;
3067 FLATCOPY(newnode, expr, NullIfExpr);
3068 MUTATE(newnode->args, expr->args, List *);
3069 return (Node *) newnode;
3074 NullTest *ntest = (NullTest *) node;
3077 FLATCOPY(newnode, ntest, NullTest);
3078 MUTATE(newnode->arg, ntest->arg, Expr *);
3079 return (Node *) newnode;
3084 BooleanTest *btest = (BooleanTest *) node;
3085 BooleanTest *newnode;
3087 FLATCOPY(newnode, btest, BooleanTest);
3088 MUTATE(newnode->arg, btest->arg, Expr *);
3089 return (Node *) newnode;
3092 case T_CoerceToDomain:
3094 CoerceToDomain *ctest = (CoerceToDomain *) node;
3095 CoerceToDomain *newnode;
3097 FLATCOPY(newnode, ctest, CoerceToDomain);
3098 MUTATE(newnode->arg, ctest->arg, Expr *);
3099 return (Node *) newnode;
3105 * We mutate the expression, but not the resdom, by
3108 TargetEntry *targetentry = (TargetEntry *) node;
3109 TargetEntry *newnode;
3111 FLATCOPY(newnode, targetentry, TargetEntry);
3112 MUTATE(newnode->expr, targetentry->expr, Expr *);
3113 return (Node *) newnode;
3117 /* Do nothing with a sub-Query, per discussion above */
3122 * We assume the mutator isn't interested in the list
3123 * nodes per se, so just invoke it on each list element.
3124 * NOTE: this would fail badly on a list with integer
3131 foreach(temp, (List *) node)
3133 resultlist = lappend(resultlist,
3134 mutator((Node *) lfirst(temp),
3137 return (Node *) resultlist;
3142 FromExpr *from = (FromExpr *) node;
3145 FLATCOPY(newnode, from, FromExpr);
3146 MUTATE(newnode->fromlist, from->fromlist, List *);
3147 MUTATE(newnode->quals, from->quals, Node *);
3148 return (Node *) newnode;
3153 JoinExpr *join = (JoinExpr *) node;
3156 FLATCOPY(newnode, join, JoinExpr);
3157 MUTATE(newnode->larg, join->larg, Node *);
3158 MUTATE(newnode->rarg, join->rarg, Node *);
3159 MUTATE(newnode->quals, join->quals, Node *);
3160 /* We do not mutate alias or using by default */
3161 return (Node *) newnode;
3164 case T_SetOperationStmt:
3166 SetOperationStmt *setop = (SetOperationStmt *) node;
3167 SetOperationStmt *newnode;
3169 FLATCOPY(newnode, setop, SetOperationStmt);
3170 MUTATE(newnode->larg, setop->larg, Node *);
3171 MUTATE(newnode->rarg, setop->rarg, Node *);
3172 return (Node *) newnode;
3175 case T_InClauseInfo:
3177 InClauseInfo *ininfo = (InClauseInfo *) node;
3178 InClauseInfo *newnode;
3180 FLATCOPY(newnode, ininfo, InClauseInfo);
3181 MUTATE(newnode->sub_targetlist, ininfo->sub_targetlist, List *);
3182 return (Node *) newnode;
3186 elog(ERROR, "unrecognized node type: %d",
3187 (int) nodeTag(node));
3190 /* can't get here, but keep compiler happy */
3196 * query_tree_mutator --- initiate modification of a Query's expressions
3198 * This routine exists just to reduce the number of places that need to know
3199 * where all the expression subtrees of a Query are. Note it can be used
3200 * for starting a walk at top level of a Query regardless of whether the
3201 * mutator intends to descend into subqueries. It is also useful for
3202 * descending into subqueries within a mutator.
3204 * Some callers want to suppress mutating of certain items in the Query,
3205 * typically because they need to process them specially, or don't actually
3206 * want to recurse into subqueries. This is supported by the flags argument,
3207 * which is the bitwise OR of flag values to suppress mutating of
3208 * indicated items. (More flag bits may be added as needed.)
3210 * Normally the Query node itself is copied, but some callers want it to be
3211 * modified in-place; they must pass QTW_DONT_COPY_QUERY in flags. All
3212 * modified substructure is safely copied in any case.
3215 query_tree_mutator(Query *query,
3216 Node *(*mutator) (),
3223 Assert(query != NULL && IsA(query, Query));
3225 if (!(flags & QTW_DONT_COPY_QUERY))
3229 FLATCOPY(newquery, query, Query);
3233 MUTATE(query->targetList, query->targetList, List *);
3234 MUTATE(query->jointree, query->jointree, FromExpr *);
3235 MUTATE(query->setOperations, query->setOperations, Node *);
3236 MUTATE(query->havingQual, query->havingQual, Node *);
3237 MUTATE(query->limitOffset, query->limitOffset, Node *);
3238 MUTATE(query->limitCount, query->limitCount, Node *);
3239 MUTATE(query->in_info_list, query->in_info_list, List *);
3241 foreach(rt, query->rtable)
3243 RangeTblEntry *rte = (RangeTblEntry *) lfirst(rt);
3244 RangeTblEntry *newrte;
3246 FLATCOPY(newrte, rte, RangeTblEntry);
3247 switch (rte->rtekind)
3251 /* we don't bother to copy eref, aliases, etc; OK? */
3254 if (!(flags & QTW_IGNORE_RT_SUBQUERIES))
3256 CHECKFLATCOPY(newrte->subquery, rte->subquery, Query);
3257 MUTATE(newrte->subquery, newrte->subquery, Query *);
3261 if (!(flags & QTW_IGNORE_JOINALIASES))
3263 MUTATE(newrte->joinaliasvars, rte->joinaliasvars, List *);
3267 MUTATE(newrte->funcexpr, rte->funcexpr, Node *);
3270 newrt = lappend(newrt, newrte);
3272 query->rtable = newrt;
3277 * query_or_expression_tree_walker --- hybrid form
3279 * This routine will invoke query_tree_walker if called on a Query node,
3280 * else will invoke the walker directly. This is a useful way of starting
3281 * the recursion when the walker's normal change of state is not appropriate
3282 * for the outermost Query node.
3285 query_or_expression_tree_walker(Node *node,
3290 if (node && IsA(node, Query))
3291 return query_tree_walker((Query *) node,
3296 return walker(node, context);
3300 * query_or_expression_tree_mutator --- hybrid form
3302 * This routine will invoke query_tree_mutator if called on a Query node,
3303 * else will invoke the mutator directly. This is a useful way of starting
3304 * the recursion when the mutator's normal change of state is not appropriate
3305 * for the outermost Query node.
3308 query_or_expression_tree_mutator(Node *node,
3309 Node *(*mutator) (),
3313 if (node && IsA(node, Query))
3314 return (Node *) query_tree_mutator((Query *) node,
3319 return mutator(node, context);