1 /*-------------------------------------------------------------------------
4 * routines to manipulate qualification clauses
6 * Portions Copyright (c) 1996-2002, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
11 * $Header: /cvsroot/pgsql/src/backend/optimizer/util/clauses.c,v 1.143 2003/07/01 00:04:37 tgl 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/planmain.h"
30 #include "optimizer/var.h"
31 #include "parser/analyze.h"
32 #include "parser/parse_clause.h"
33 #include "tcop/tcopprot.h"
34 #include "utils/acl.h"
35 #include "utils/builtins.h"
36 #include "utils/datum.h"
37 #include "utils/lsyscache.h"
38 #include "utils/memutils.h"
39 #include "utils/syscache.h"
42 /* note that pg_type.h hardwires size of bool as 1 ... duplicate it */
43 #define MAKEBOOLCONST(val,isnull) \
44 ((Node *) makeConst(BOOLOID, 1, (Datum) (val), (isnull), true))
51 } substitute_actual_parameters_context;
53 static bool contain_agg_clause_walker(Node *node, void *context);
54 static bool contain_distinct_agg_clause_walker(Node *node, void *context);
55 static bool count_agg_clause_walker(Node *node, int *count);
56 static bool expression_returns_set_walker(Node *node, void *context);
57 static bool contain_subplans_walker(Node *node, void *context);
58 static bool contain_mutable_functions_walker(Node *node, void *context);
59 static bool contain_volatile_functions_walker(Node *node, void *context);
60 static bool contain_nonstrict_functions_walker(Node *node, void *context);
61 static Node *eval_const_expressions_mutator(Node *node, List *active_fns);
62 static Expr *simplify_function(Oid funcid, Oid result_type, List *args,
63 bool allow_inline, List *active_fns);
64 static Expr *evaluate_function(Oid funcid, Oid result_type, List *args,
65 HeapTuple func_tuple);
66 static Expr *inline_function(Oid funcid, Oid result_type, List *args,
67 HeapTuple func_tuple, List *active_fns);
68 static Node *substitute_actual_parameters(Node *expr, int nargs, List *args,
70 static Node *substitute_actual_parameters_mutator(Node *node,
71 substitute_actual_parameters_context *context);
72 static Expr *evaluate_expr(Expr *expr, Oid result_type);
75 /*****************************************************************************
76 * OPERATOR clause functions
77 *****************************************************************************/
81 * Creates an operator clause given its operator info, left operand,
82 * and right operand (pass NULL to create single-operand clause).
85 make_opclause(Oid opno, Oid opresulttype, bool opretset,
86 Expr *leftop, Expr *rightop)
88 OpExpr *expr = makeNode(OpExpr);
91 expr->opfuncid = InvalidOid;
92 expr->opresulttype = opresulttype;
93 expr->opretset = opretset;
95 expr->args = makeList2(leftop, rightop);
97 expr->args = makeList1(leftop);
104 * Returns the left operand of a clause of the form (op expr expr)
108 get_leftop(Expr *clause)
110 OpExpr *expr = (OpExpr *) clause;
112 if (expr->args != NIL)
113 return lfirst(expr->args);
121 * Returns the right operand in a clause of the form (op expr expr).
122 * NB: result will be NULL if applied to a unary op clause.
125 get_rightop(Expr *clause)
127 OpExpr *expr = (OpExpr *) clause;
129 if (expr->args != NIL && lnext(expr->args) != NIL)
130 return lfirst(lnext(expr->args));
135 /*****************************************************************************
136 * NOT clause functions
137 *****************************************************************************/
142 * Returns t iff this is a 'not' clause: (NOT expr).
145 not_clause(Node *clause)
147 return (clause != NULL &&
148 IsA(clause, BoolExpr) &&
149 ((BoolExpr *) clause)->boolop == NOT_EXPR);
155 * Create a 'not' clause given the expression to be negated.
158 make_notclause(Expr *notclause)
160 BoolExpr *expr = makeNode(BoolExpr);
162 expr->boolop = NOT_EXPR;
163 expr->args = makeList1(notclause);
164 return (Expr *) expr;
170 * Retrieve the clause within a 'not' clause
173 get_notclausearg(Expr *notclause)
175 return lfirst(((BoolExpr *) notclause)->args);
178 /*****************************************************************************
179 * OR clause functions
180 *****************************************************************************/
185 * Returns t iff the clause is an 'or' clause: (OR { expr }).
188 or_clause(Node *clause)
190 return (clause != NULL &&
191 IsA(clause, BoolExpr) &&
192 ((BoolExpr *) clause)->boolop == OR_EXPR);
198 * Creates an 'or' clause given a list of its subclauses.
201 make_orclause(List *orclauses)
203 BoolExpr *expr = makeNode(BoolExpr);
205 expr->boolop = OR_EXPR;
206 expr->args = orclauses;
207 return (Expr *) expr;
210 /*****************************************************************************
211 * AND clause functions
212 *****************************************************************************/
218 * Returns t iff its argument is an 'and' clause: (AND { expr }).
221 and_clause(Node *clause)
223 return (clause != NULL &&
224 IsA(clause, BoolExpr) &&
225 ((BoolExpr *) clause)->boolop == AND_EXPR);
231 * Creates an 'and' clause given a list of its subclauses.
234 make_andclause(List *andclauses)
236 BoolExpr *expr = makeNode(BoolExpr);
238 expr->boolop = AND_EXPR;
239 expr->args = andclauses;
240 return (Expr *) expr;
246 * Variant of make_andclause for ANDing two qual conditions together.
247 * Qual conditions have the property that a NULL nodetree is interpreted
251 make_and_qual(Node *qual1, Node *qual2)
257 return (Node *) make_andclause(makeList2(qual1, qual2));
261 * Sometimes (such as in the result of canonicalize_qual or the input of
262 * ExecQual), we use lists of expression nodes with implicit AND semantics.
264 * These functions convert between an AND-semantics expression list and the
265 * ordinary representation of a boolean expression.
267 * Note that an empty list is considered equivalent to TRUE.
270 make_ands_explicit(List *andclauses)
272 if (andclauses == NIL)
273 return (Expr *) MAKEBOOLCONST(true, false);
274 else if (lnext(andclauses) == NIL)
275 return (Expr *) lfirst(andclauses);
277 return make_andclause(andclauses);
281 make_ands_implicit(Expr *clause)
284 * NB: because the parser sets the qual field to NULL in a query that
285 * has no WHERE clause, we must consider a NULL input clause as TRUE,
286 * even though one might more reasonably think it FALSE. Grumble. If
287 * this causes trouble, consider changing the parser's behavior.
290 return NIL; /* NULL -> NIL list == TRUE */
291 else if (and_clause((Node *) clause))
292 return ((BoolExpr *) clause)->args;
293 else if (IsA(clause, Const) &&
294 !((Const *) clause)->constisnull &&
295 DatumGetBool(((Const *) clause)->constvalue))
296 return NIL; /* constant TRUE input -> NIL list */
298 return makeList1(clause);
302 /*****************************************************************************
303 * Aggregate-function clause manipulation
304 *****************************************************************************/
308 * Recursively search for Aggref nodes within a clause.
310 * Returns true if any aggregate found.
312 * This does not descend into subqueries, and so should be used only after
313 * reduction of sublinks to subplans, or in contexts where it's known there
314 * are no subqueries. There mustn't be outer-aggregate references either.
316 * (If you want something like this but able to deal with subqueries,
317 * see rewriteManip.c's checkExprHasAggs().)
320 contain_agg_clause(Node *clause)
322 return contain_agg_clause_walker(clause, NULL);
326 contain_agg_clause_walker(Node *node, void *context)
330 if (IsA(node, Aggref))
332 Assert(((Aggref *) node)->agglevelsup == 0);
333 return true; /* abort the tree traversal and return
336 Assert(!IsA(node, SubLink));
337 return expression_tree_walker(node, contain_agg_clause_walker, context);
341 * contain_distinct_agg_clause
342 * Recursively search for DISTINCT Aggref nodes within a clause.
344 * Returns true if any DISTINCT aggregate found.
346 * This does not descend into subqueries, and so should be used only after
347 * reduction of sublinks to subplans, or in contexts where it's known there
348 * are no subqueries. There mustn't be outer-aggregate references either.
351 contain_distinct_agg_clause(Node *clause)
353 return contain_distinct_agg_clause_walker(clause, NULL);
357 contain_distinct_agg_clause_walker(Node *node, void *context)
361 if (IsA(node, Aggref))
363 Assert(((Aggref *) node)->agglevelsup == 0);
364 if (((Aggref *) node)->aggdistinct)
365 return true; /* abort the tree traversal and return
368 Assert(!IsA(node, SubLink));
369 return expression_tree_walker(node, contain_distinct_agg_clause_walker, context);
374 * Recursively count the Aggref nodes in an expression tree.
376 * Note: this also checks for nested aggregates, which are an error.
378 * This does not descend into subqueries, and so should be used only after
379 * reduction of sublinks to subplans, or in contexts where it's known there
380 * are no subqueries. There mustn't be outer-aggregate references either.
383 count_agg_clause(Node *clause)
387 count_agg_clause_walker(clause, &result);
392 count_agg_clause_walker(Node *node, int *count)
396 if (IsA(node, Aggref))
398 Assert(((Aggref *) node)->agglevelsup == 0);
402 * Complain if the aggregate's argument contains any aggregates;
403 * nested agg functions are semantically nonsensical.
405 if (contain_agg_clause((Node *) ((Aggref *) node)->target))
406 elog(ERROR, "Aggregate function calls may not be nested");
409 * Having checked that, we need not recurse into the argument.
413 Assert(!IsA(node, SubLink));
414 return expression_tree_walker(node, count_agg_clause_walker,
419 /*****************************************************************************
420 * Support for expressions returning sets
421 *****************************************************************************/
424 * expression_returns_set
425 * Test whether an expression returns a set result.
427 * Because we use expression_tree_walker(), this can also be applied to
428 * whole targetlists; it'll produce TRUE if any one of the tlist items
432 expression_returns_set(Node *clause)
434 return expression_returns_set_walker(clause, NULL);
438 expression_returns_set_walker(Node *node, void *context)
442 if (IsA(node, FuncExpr))
444 FuncExpr *expr = (FuncExpr *) node;
446 if (expr->funcretset)
448 /* else fall through to check args */
450 if (IsA(node, OpExpr))
452 OpExpr *expr = (OpExpr *) node;
456 /* else fall through to check args */
459 /* Avoid recursion for some cases that can't return a set */
460 if (IsA(node, Aggref))
462 if (IsA(node, DistinctExpr))
464 if (IsA(node, ScalarArrayOpExpr))
466 if (IsA(node, BoolExpr))
468 if (IsA(node, SubLink))
470 if (IsA(node, SubPlan))
472 if (IsA(node, ArrayExpr))
474 if (IsA(node, CoalesceExpr))
476 if (IsA(node, NullIfExpr))
479 return expression_tree_walker(node, expression_returns_set_walker,
483 /*****************************************************************************
484 * Subplan clause manipulation
485 *****************************************************************************/
489 * Recursively search for subplan nodes within a clause.
491 * If we see a SubLink node, we will return TRUE. This is only possible if
492 * the expression tree hasn't yet been transformed by subselect.c. We do not
493 * know whether the node will produce a true subplan or just an initplan,
494 * but we make the conservative assumption that it will be a subplan.
496 * Returns true if any subplan found.
499 contain_subplans(Node *clause)
501 return contain_subplans_walker(clause, NULL);
505 contain_subplans_walker(Node *node, void *context)
509 if (IsA(node, SubPlan) ||
511 return true; /* abort the tree traversal and return
513 return expression_tree_walker(node, contain_subplans_walker, context);
517 /*****************************************************************************
518 * Check clauses for mutable functions
519 *****************************************************************************/
522 * contain_mutable_functions
523 * Recursively search for mutable functions within a clause.
525 * Returns true if any mutable function (or operator implemented by a
526 * mutable function) is found. This test is needed so that we don't
527 * mistakenly think that something like "WHERE random() < 0.5" can be treated
528 * as a constant qualification.
530 * XXX we do not examine sub-selects to see if they contain uses of
531 * mutable functions. It's not real clear if that is correct or not...
534 contain_mutable_functions(Node *clause)
536 return contain_mutable_functions_walker(clause, NULL);
540 contain_mutable_functions_walker(Node *node, void *context)
544 if (IsA(node, FuncExpr))
546 FuncExpr *expr = (FuncExpr *) node;
548 if (func_volatile(expr->funcid) != PROVOLATILE_IMMUTABLE)
550 /* else fall through to check args */
552 if (IsA(node, OpExpr))
554 OpExpr *expr = (OpExpr *) node;
556 if (op_volatile(expr->opno) != PROVOLATILE_IMMUTABLE)
558 /* else fall through to check args */
560 if (IsA(node, DistinctExpr))
562 DistinctExpr *expr = (DistinctExpr *) node;
564 if (op_volatile(expr->opno) != PROVOLATILE_IMMUTABLE)
566 /* else fall through to check args */
568 if (IsA(node, ScalarArrayOpExpr))
570 ScalarArrayOpExpr *expr = (ScalarArrayOpExpr *) node;
572 if (op_volatile(expr->opno) != PROVOLATILE_IMMUTABLE)
574 /* else fall through to check args */
576 if (IsA(node, NullIfExpr))
578 NullIfExpr *expr = (NullIfExpr *) node;
580 if (op_volatile(expr->opno) != PROVOLATILE_IMMUTABLE)
582 /* else fall through to check args */
584 if (IsA(node, SubLink))
586 SubLink *sublink = (SubLink *) node;
589 foreach(opid, sublink->operOids)
591 if (op_volatile(lfirsto(opid)) != PROVOLATILE_IMMUTABLE)
594 /* else fall through to check args */
596 return expression_tree_walker(node, contain_mutable_functions_walker,
601 /*****************************************************************************
602 * Check clauses for volatile functions
603 *****************************************************************************/
606 * contain_volatile_functions
607 * Recursively search for volatile functions within a clause.
609 * Returns true if any volatile function (or operator implemented by a
610 * volatile function) is found. This test prevents invalid conversions
611 * of volatile expressions into indexscan quals.
613 * XXX we do not examine sub-selects to see if they contain uses of
614 * volatile functions. It's not real clear if that is correct or not...
617 contain_volatile_functions(Node *clause)
619 return contain_volatile_functions_walker(clause, NULL);
623 contain_volatile_functions_walker(Node *node, void *context)
627 if (IsA(node, FuncExpr))
629 FuncExpr *expr = (FuncExpr *) node;
631 if (func_volatile(expr->funcid) == PROVOLATILE_VOLATILE)
633 /* else fall through to check args */
635 if (IsA(node, OpExpr))
637 OpExpr *expr = (OpExpr *) node;
639 if (op_volatile(expr->opno) == PROVOLATILE_VOLATILE)
641 /* else fall through to check args */
643 if (IsA(node, DistinctExpr))
645 DistinctExpr *expr = (DistinctExpr *) node;
647 if (op_volatile(expr->opno) == PROVOLATILE_VOLATILE)
649 /* else fall through to check args */
651 if (IsA(node, ScalarArrayOpExpr))
653 ScalarArrayOpExpr *expr = (ScalarArrayOpExpr *) node;
655 if (op_volatile(expr->opno) == PROVOLATILE_VOLATILE)
657 /* else fall through to check args */
659 if (IsA(node, NullIfExpr))
661 NullIfExpr *expr = (NullIfExpr *) node;
663 if (op_volatile(expr->opno) == PROVOLATILE_VOLATILE)
665 /* else fall through to check args */
667 if (IsA(node, SubLink))
669 SubLink *sublink = (SubLink *) node;
672 foreach(opid, sublink->operOids)
674 if (op_volatile(lfirsto(opid)) == PROVOLATILE_VOLATILE)
677 /* else fall through to check args */
679 return expression_tree_walker(node, contain_volatile_functions_walker,
684 /*****************************************************************************
685 * Check clauses for nonstrict functions
686 *****************************************************************************/
689 * contain_nonstrict_functions
690 * Recursively search for nonstrict functions within a clause.
692 * Returns true if any nonstrict construct is found --- ie, anything that
693 * could produce non-NULL output with a NULL input.
695 * XXX we do not examine sub-selects to see if they contain uses of
696 * nonstrict functions. It's not real clear if that is correct or not...
697 * for the current usage it does not matter, since inline_function()
698 * rejects cases with sublinks.
701 contain_nonstrict_functions(Node *clause)
703 return contain_nonstrict_functions_walker(clause, NULL);
707 contain_nonstrict_functions_walker(Node *node, void *context)
711 if (IsA(node, FuncExpr))
713 FuncExpr *expr = (FuncExpr *) node;
715 if (!func_strict(expr->funcid))
717 /* else fall through to check args */
719 if (IsA(node, OpExpr))
721 OpExpr *expr = (OpExpr *) node;
723 if (!op_strict(expr->opno))
725 /* else fall through to check args */
727 if (IsA(node, DistinctExpr))
729 /* IS DISTINCT FROM is inherently non-strict */
732 if (IsA(node, ScalarArrayOpExpr))
734 /* inherently non-strict, consider null scalar and empty array */
737 if (IsA(node, BoolExpr))
739 BoolExpr *expr = (BoolExpr *) node;
741 switch (expr->boolop)
745 /* OR, AND are inherently non-strict */
751 if (IsA(node, CaseExpr))
753 /* NB: ArrayExpr might someday be nonstrict */
754 if (IsA(node, CoalesceExpr))
756 if (IsA(node, NullIfExpr))
758 if (IsA(node, NullTest))
760 if (IsA(node, BooleanTest))
762 if (IsA(node, SubLink))
764 SubLink *sublink = (SubLink *) node;
767 foreach(opid, sublink->operOids)
769 if (!op_strict(lfirsto(opid)))
772 /* else fall through to check args */
774 return expression_tree_walker(node, contain_nonstrict_functions_walker,
779 /*****************************************************************************
780 * Check for "pseudo-constant" clauses
781 *****************************************************************************/
784 * is_pseudo_constant_clause
785 * Detect whether a clause is "constant", ie, it contains no variables
786 * of the current query level and no uses of volatile functions.
787 * Such a clause is not necessarily a true constant: it can still contain
788 * Params and outer-level Vars, not to mention functions whose results
789 * may vary from one statement to the next. However, the clause's value
790 * will be constant over any one scan of the current query, so it can be
791 * used as an indexscan key or (if a top-level qual) can be pushed up to
792 * become a gating qual.
795 is_pseudo_constant_clause(Node *clause)
798 * We could implement this check in one recursive scan. But since the
799 * check for volatile functions is both moderately expensive and
800 * unlikely to fail, it seems better to look for Vars first and only
801 * check for volatile functions if we find no Vars.
803 if (!contain_var_clause(clause) &&
804 !contain_volatile_functions(clause))
810 * pull_constant_clauses
811 * Scan through a list of qualifications and separate "constant" quals
812 * from those that are not.
814 * Returns a list of the pseudo-constant clauses in constantQual and the
815 * remaining quals as the return value.
818 pull_constant_clauses(List *quals, List **constantQual)
824 FastListInit(&constqual);
825 FastListInit(&restqual);
829 Node *qual = (Node *) lfirst(q);
831 if (is_pseudo_constant_clause(qual))
832 FastAppend(&constqual, qual);
834 FastAppend(&restqual, qual);
836 *constantQual = FastListValue(&constqual);
837 return FastListValue(&restqual);
841 /*****************************************************************************
842 * Tests on clauses of queries
844 * Possibly this code should go someplace else, since this isn't quite the
845 * same meaning of "clause" as is used elsewhere in this module. But I can't
846 * think of a better place for it...
847 *****************************************************************************/
850 * Test whether a query uses DISTINCT ON, ie, has a distinct-list that is
851 * not the same as the set of output columns.
854 has_distinct_on_clause(Query *query)
858 /* Is there a DISTINCT clause at all? */
859 if (query->distinctClause == NIL)
863 * If the DISTINCT list contains all the nonjunk targetlist items, and
864 * nothing else (ie, no junk tlist items), then it's a simple
865 * DISTINCT, else it's DISTINCT ON. We do not require the lists to be
866 * in the same order (since the parser may have adjusted the DISTINCT
867 * clause ordering to agree with ORDER BY). Furthermore, a
868 * non-DISTINCT junk tlist item that is in the sortClause is also
869 * evidence of DISTINCT ON, since we don't allow ORDER BY on junk
870 * tlist items when plain DISTINCT is used.
872 * This code assumes that the DISTINCT list is valid, ie, all its entries
873 * match some entry of the tlist.
875 foreach(targetList, query->targetList)
877 TargetEntry *tle = (TargetEntry *) lfirst(targetList);
879 if (tle->resdom->ressortgroupref == 0)
881 if (tle->resdom->resjunk)
882 continue; /* we can ignore unsorted junk cols */
883 return true; /* definitely not in DISTINCT list */
885 if (targetIsInSortList(tle, query->distinctClause))
887 if (tle->resdom->resjunk)
888 return true; /* junk TLE in DISTINCT means DISTINCT ON */
889 /* else this TLE is okay, keep looking */
893 /* This TLE is not in DISTINCT list */
894 if (!tle->resdom->resjunk)
895 return true; /* non-junk, non-DISTINCT, so DISTINCT ON */
896 if (targetIsInSortList(tle, query->sortClause))
897 return true; /* sorted, non-distinct junk */
898 /* unsorted junk is okay, keep looking */
901 /* It's a simple DISTINCT */
906 /*****************************************************************************
908 * General clause-manipulating routines *
910 *****************************************************************************/
913 * clause_get_relids_vars
914 * Retrieves distinct relids and vars appearing within a clause.
916 * '*relids' is set to the set of all distinct "varno"s appearing
917 * in Vars within the clause.
918 * '*vars' is set to a list of all distinct Vars appearing within the clause.
919 * Var nodes are considered distinct if they have different varno
920 * or varattno values. If there are several occurrences of the same
921 * varno/varattno, you get a randomly chosen one...
923 * Note that upper-level vars are ignored, since they normally will
924 * become Params with respect to this query level.
927 clause_get_relids_vars(Node *clause, Relids *relids, List **vars)
929 List *clvars = pull_var_clause(clause, false);
930 Relids varnos = NULL;
931 List *var_list = NIL;
936 Var *var = (Var *) lfirst(i);
939 varnos = bms_add_member(varnos, var->varno);
940 foreach(vi, var_list)
942 Var *in_list = (Var *) lfirst(vi);
944 if (in_list->varno == var->varno &&
945 in_list->varattno == var->varattno)
949 var_list = lcons(var, var_list);
959 * (formerly clause_relids)
961 * Returns the number of different relations referenced in 'clause'.
964 NumRelids(Node *clause)
966 Relids varnos = pull_varnos(clause);
967 int result = bms_num_members(varnos);
974 * CommuteClause: commute a binary operator clause
976 * XXX the clause is destructively modified!
979 CommuteClause(OpExpr *clause)
984 if (!is_opclause(clause) ||
985 length(clause->args) != 2)
986 elog(ERROR, "CommuteClause: applied to non-binary-operator clause");
988 opoid = get_commutator(clause->opno);
990 if (!OidIsValid(opoid))
991 elog(ERROR, "CommuteClause: no commutator for operator %u",
995 * modify the clause in-place!
997 clause->opno = opoid;
998 clause->opfuncid = InvalidOid;
999 /* opresulttype and opretset are assumed not to change */
1001 temp = lfirst(clause->args);
1002 lfirst(clause->args) = lsecond(clause->args);
1003 lsecond(clause->args) = temp;
1007 /*--------------------
1008 * eval_const_expressions
1010 * Reduce any recognizably constant subexpressions of the given
1011 * expression tree, for example "2 + 2" => "4". More interestingly,
1012 * we can reduce certain boolean expressions even when they contain
1013 * non-constant subexpressions: "x OR true" => "true" no matter what
1014 * the subexpression x is. (XXX We assume that no such subexpression
1015 * will have important side-effects, which is not necessarily a good
1016 * assumption in the presence of user-defined functions; do we need a
1017 * pg_proc flag that prevents discarding the execution of a function?)
1019 * We do understand that certain functions may deliver non-constant
1020 * results even with constant inputs, "nextval()" being the classic
1021 * example. Functions that are not marked "immutable" in pg_proc
1022 * will not be pre-evaluated here, although we will reduce their
1023 * arguments as far as possible.
1025 * We assume that the tree has already been type-checked and contains
1026 * only operators and functions that are reasonable to try to execute.
1027 *--------------------
1030 eval_const_expressions(Node *node)
1033 * The context for the mutator is a list of SQL functions being
1034 * recursively simplified, so we start with an empty list.
1036 return eval_const_expressions_mutator(node, NIL);
1040 eval_const_expressions_mutator(Node *node, List *active_fns)
1044 if (IsA(node, FuncExpr))
1046 FuncExpr *expr = (FuncExpr *) node;
1052 * Reduce constants in the FuncExpr's arguments. We know args is
1053 * either NIL or a List node, so we can call
1054 * expression_tree_mutator directly rather than recursing to self.
1056 args = (List *) expression_tree_mutator((Node *) expr->args,
1057 eval_const_expressions_mutator,
1058 (void *) active_fns);
1060 * Code for op/func reduction is pretty bulky, so split it out
1061 * as a separate function.
1063 simple = simplify_function(expr->funcid, expr->funcresulttype, args,
1065 if (simple) /* successfully simplified it */
1066 return (Node *) simple;
1068 * The expression cannot be simplified any further, so build and
1069 * return a replacement FuncExpr node using the possibly-simplified
1072 newexpr = makeNode(FuncExpr);
1073 newexpr->funcid = expr->funcid;
1074 newexpr->funcresulttype = expr->funcresulttype;
1075 newexpr->funcretset = expr->funcretset;
1076 newexpr->funcformat = expr->funcformat;
1077 newexpr->args = args;
1078 return (Node *) newexpr;
1080 if (IsA(node, OpExpr))
1082 OpExpr *expr = (OpExpr *) node;
1088 * Reduce constants in the OpExpr's arguments. We know args is
1089 * either NIL or a List node, so we can call
1090 * expression_tree_mutator directly rather than recursing to self.
1092 args = (List *) expression_tree_mutator((Node *) expr->args,
1093 eval_const_expressions_mutator,
1094 (void *) active_fns);
1096 * Need to get OID of underlying function. Okay to scribble on
1097 * input to this extent.
1101 * Code for op/func reduction is pretty bulky, so split it out
1102 * as a separate function.
1104 simple = simplify_function(expr->opfuncid, expr->opresulttype, args,
1106 if (simple) /* successfully simplified it */
1107 return (Node *) simple;
1109 * The expression cannot be simplified any further, so build and
1110 * return a replacement OpExpr node using the possibly-simplified
1113 newexpr = makeNode(OpExpr);
1114 newexpr->opno = expr->opno;
1115 newexpr->opfuncid = expr->opfuncid;
1116 newexpr->opresulttype = expr->opresulttype;
1117 newexpr->opretset = expr->opretset;
1118 newexpr->args = args;
1119 return (Node *) newexpr;
1121 if (IsA(node, DistinctExpr))
1123 DistinctExpr *expr = (DistinctExpr *) node;
1126 bool has_null_input = false;
1127 bool all_null_input = true;
1128 bool has_nonconst_input = false;
1130 DistinctExpr *newexpr;
1133 * Reduce constants in the DistinctExpr's arguments. We know args is
1134 * either NIL or a List node, so we can call
1135 * expression_tree_mutator directly rather than recursing to self.
1137 args = (List *) expression_tree_mutator((Node *) expr->args,
1138 eval_const_expressions_mutator,
1139 (void *) active_fns);
1142 * We must do our own check for NULLs because
1143 * DistinctExpr has different results for NULL input
1144 * than the underlying operator does.
1148 if (IsA(lfirst(arg), Const))
1150 has_null_input |= ((Const *) lfirst(arg))->constisnull;
1151 all_null_input &= ((Const *) lfirst(arg))->constisnull;
1154 has_nonconst_input = true;
1157 /* all constants? then can optimize this out */
1158 if (!has_nonconst_input)
1160 /* all nulls? then not distinct */
1162 return MAKEBOOLCONST(false, false);
1164 /* one null? then distinct */
1166 return MAKEBOOLCONST(true, false);
1168 /* otherwise try to evaluate the '=' operator */
1169 /* (NOT okay to try to inline it, though!) */
1172 * Need to get OID of underlying function. Okay to scribble on
1173 * input to this extent.
1175 set_opfuncid((OpExpr *) expr); /* rely on struct equivalence */
1177 * Code for op/func reduction is pretty bulky, so split it out
1178 * as a separate function.
1180 simple = simplify_function(expr->opfuncid, expr->opresulttype,
1181 args, false, active_fns);
1182 if (simple) /* successfully simplified it */
1185 * Since the underlying operator is "=", must negate its
1188 Const *csimple = (Const *) simple;
1190 Assert(IsA(csimple, Const));
1191 csimple->constvalue =
1192 BoolGetDatum(!DatumGetBool(csimple->constvalue));
1193 return (Node *) csimple;
1198 * The expression cannot be simplified any further, so build and
1199 * return a replacement DistinctExpr node using the
1200 * possibly-simplified arguments.
1202 newexpr = makeNode(DistinctExpr);
1203 newexpr->opno = expr->opno;
1204 newexpr->opfuncid = expr->opfuncid;
1205 newexpr->opresulttype = expr->opresulttype;
1206 newexpr->opretset = expr->opretset;
1207 newexpr->args = args;
1208 return (Node *) newexpr;
1210 if (IsA(node, BoolExpr))
1212 BoolExpr *expr = (BoolExpr *) node;
1217 * Reduce constants in the BoolExpr's arguments. We know args is
1218 * either NIL or a List node, so we can call
1219 * expression_tree_mutator directly rather than recursing to self.
1221 args = (List *) expression_tree_mutator((Node *) expr->args,
1222 eval_const_expressions_mutator,
1223 (void *) active_fns);
1225 switch (expr->boolop)
1230 * OR arguments are handled as follows:
1231 * non constant: keep
1232 * FALSE: drop (does not affect result)
1233 * TRUE: force result to TRUE
1234 * NULL: keep only one
1235 * We keep one NULL input because ExecEvalOr returns NULL
1236 * when no input is TRUE and at least one is NULL.
1241 bool haveNull = false;
1242 bool forceTrue = false;
1244 FastListInit(&newargs);
1247 if (!IsA(lfirst(arg), Const))
1249 FastAppend(&newargs, lfirst(arg));
1252 const_input = (Const *) lfirst(arg);
1253 if (const_input->constisnull)
1255 else if (DatumGetBool(const_input->constvalue))
1257 /* otherwise, we can drop the constant-false input */
1261 * We could return TRUE before falling out of the
1262 * loop, but this coding method will be easier to
1263 * adapt if we ever add a notion of non-removable
1264 * functions. We'd need to check all the inputs for
1268 return MAKEBOOLCONST(true, false);
1270 FastAppend(&newargs, MAKEBOOLCONST(false, true));
1271 /* If all the inputs are FALSE, result is FALSE */
1272 if (FastListValue(&newargs) == NIL)
1273 return MAKEBOOLCONST(false, false);
1274 /* If only one nonconst-or-NULL input, it's the result */
1275 if (lnext(FastListValue(&newargs)) == NIL)
1276 return (Node *) lfirst(FastListValue(&newargs));
1277 /* Else we still need an OR node */
1278 return (Node *) make_orclause(FastListValue(&newargs));
1283 * AND arguments are handled as follows:
1284 * non constant: keep
1285 * TRUE: drop (does not affect result)
1286 * FALSE: force result to FALSE
1287 * NULL: keep only one
1288 * We keep one NULL input because ExecEvalAnd returns NULL
1289 * when no input is FALSE and at least one is NULL.
1294 bool haveNull = false;
1295 bool forceFalse = false;
1297 FastListInit(&newargs);
1300 if (!IsA(lfirst(arg), Const))
1302 FastAppend(&newargs, lfirst(arg));
1305 const_input = (Const *) lfirst(arg);
1306 if (const_input->constisnull)
1308 else if (!DatumGetBool(const_input->constvalue))
1310 /* otherwise, we can drop the constant-true input */
1314 * We could return FALSE before falling out of the
1315 * loop, but this coding method will be easier to
1316 * adapt if we ever add a notion of non-removable
1317 * functions. We'd need to check all the inputs for
1321 return MAKEBOOLCONST(false, false);
1323 FastAppend(&newargs, MAKEBOOLCONST(false, true));
1324 /* If all the inputs are TRUE, result is TRUE */
1325 if (FastListValue(&newargs) == NIL)
1326 return MAKEBOOLCONST(true, false);
1327 /* If only one nonconst-or-NULL input, it's the result */
1328 if (lnext(FastListValue(&newargs)) == NIL)
1329 return (Node *) lfirst(FastListValue(&newargs));
1330 /* Else we still need an AND node */
1331 return (Node *) make_andclause(FastListValue(&newargs));
1334 Assert(length(args) == 1);
1335 if (IsA(lfirst(args), Const))
1337 const_input = (Const *) lfirst(args);
1338 /* NOT NULL => NULL */
1339 if (const_input->constisnull)
1340 return MAKEBOOLCONST(false, true);
1341 /* otherwise pretty easy */
1342 return MAKEBOOLCONST(!DatumGetBool(const_input->constvalue),
1345 /* Else we still need a NOT node */
1346 return (Node *) make_notclause(lfirst(args));
1348 elog(ERROR, "eval_const_expressions: unexpected boolop %d",
1349 (int) expr->boolop);
1353 if (IsA(node, SubPlan))
1356 * Return a SubPlan unchanged --- too late to do anything
1359 * XXX should we elog() here instead? Probably this routine
1360 * should never be invoked after SubPlan creation.
1364 if (IsA(node, RelabelType))
1367 * If we can simplify the input to a constant, then we don't need
1368 * the RelabelType node anymore: just change the type field of the
1369 * Const node. Otherwise, must copy the RelabelType node.
1371 RelabelType *relabel = (RelabelType *) node;
1374 arg = eval_const_expressions_mutator((Node *) relabel->arg,
1378 * If we find stacked RelabelTypes (eg, from foo :: int :: oid) we
1379 * can discard all but the top one.
1381 while (arg && IsA(arg, RelabelType))
1382 arg = (Node *) ((RelabelType *) arg)->arg;
1384 if (arg && IsA(arg, Const))
1386 Const *con = (Const *) arg;
1388 con->consttype = relabel->resulttype;
1391 * relabel's resulttypmod is discarded, which is OK for now;
1392 * if the type actually needs a runtime length coercion then
1393 * there should be a function call to do it just above this
1396 return (Node *) con;
1400 RelabelType *newrelabel = makeNode(RelabelType);
1402 newrelabel->arg = (Expr *) arg;
1403 newrelabel->resulttype = relabel->resulttype;
1404 newrelabel->resulttypmod = relabel->resulttypmod;
1405 return (Node *) newrelabel;
1408 if (IsA(node, CaseExpr))
1412 * CASE expressions can be simplified if there are constant
1413 * condition clauses:
1414 * FALSE (or NULL): drop the alternative
1415 * TRUE: drop all remaining alternatives
1416 * If the first non-FALSE alternative is a constant TRUE, we can
1417 * simplify the entire CASE to that alternative's expression.
1418 * If there are no non-FALSE alternatives, we simplify the entire
1419 * CASE to the default result (ELSE result).
1422 CaseExpr *caseexpr = (CaseExpr *) node;
1429 FastListInit(&newargs);
1430 foreach(arg, caseexpr->args)
1432 /* Simplify this alternative's condition and result */
1433 CaseWhen *casewhen = (CaseWhen *)
1434 expression_tree_mutator((Node *) lfirst(arg),
1435 eval_const_expressions_mutator,
1436 (void *) active_fns);
1438 Assert(IsA(casewhen, CaseWhen));
1439 if (casewhen->expr == NULL ||
1440 !IsA(casewhen->expr, Const))
1442 FastAppend(&newargs, casewhen);
1445 const_input = (Const *) casewhen->expr;
1446 if (const_input->constisnull ||
1447 !DatumGetBool(const_input->constvalue))
1448 continue; /* drop alternative with FALSE condition */
1451 * Found a TRUE condition. If it's the first (un-dropped)
1452 * alternative, the CASE reduces to just this alternative.
1454 if (FastListValue(&newargs) == NIL)
1455 return (Node *) casewhen->result;
1458 * Otherwise, add it to the list, and drop all the rest.
1460 FastAppend(&newargs, casewhen);
1464 /* Simplify the default result */
1465 defresult = eval_const_expressions_mutator((Node *) caseexpr->defresult,
1469 * If no non-FALSE alternatives, CASE reduces to the default
1472 if (FastListValue(&newargs) == NIL)
1474 /* Otherwise we need a new CASE node */
1475 newcase = makeNode(CaseExpr);
1476 newcase->casetype = caseexpr->casetype;
1477 newcase->arg = NULL;
1478 newcase->args = FastListValue(&newargs);
1479 newcase->defresult = (Expr *) defresult;
1480 return (Node *) newcase;
1482 if (IsA(node, ArrayExpr))
1484 ArrayExpr *arrayexpr = (ArrayExpr *) node;
1485 ArrayExpr *newarray;
1486 bool all_const = true;
1490 FastListInit(&newelems);
1491 foreach(element, arrayexpr->elements)
1495 e = eval_const_expressions_mutator((Node *) lfirst(element),
1499 FastAppend(&newelems, e);
1502 newarray = makeNode(ArrayExpr);
1503 newarray->array_typeid = arrayexpr->array_typeid;
1504 newarray->element_typeid = arrayexpr->element_typeid;
1505 newarray->elements = FastListValue(&newelems);
1506 newarray->ndims = arrayexpr->ndims;
1509 return (Node *) evaluate_expr((Expr *) newarray,
1510 newarray->array_typeid);
1512 return (Node *) newarray;
1514 if (IsA(node, CoalesceExpr))
1516 CoalesceExpr *coalesceexpr = (CoalesceExpr *) node;
1517 CoalesceExpr *newcoalesce;
1521 FastListInit(&newargs);
1522 foreach(arg, coalesceexpr->args)
1526 e = eval_const_expressions_mutator((Node *) lfirst(arg),
1529 * We can remove null constants from the list.
1530 * For a non-null constant, if it has not been preceded by any
1531 * other non-null-constant expressions then that is the result.
1535 if (((Const *) e)->constisnull)
1536 continue; /* drop null constant */
1537 if (FastListValue(&newargs) == NIL)
1538 return e; /* first expr */
1540 FastAppend(&newargs, e);
1543 newcoalesce = makeNode(CoalesceExpr);
1544 newcoalesce->coalescetype = coalesceexpr->coalescetype;
1545 newcoalesce->args = FastListValue(&newargs);
1546 return (Node *) newcoalesce;
1548 if (IsA(node, FieldSelect))
1551 * We can optimize field selection from a whole-row Var into a
1552 * simple Var. (This case won't be generated directly by the
1553 * parser, because ParseComplexProjection short-circuits it.
1554 * But it can arise while simplifying functions.) If the argument
1555 * isn't a whole-row Var, just fall through to do generic processing.
1557 FieldSelect *fselect = (FieldSelect *) node;
1558 Var *argvar = (Var *) fselect->arg;
1560 if (argvar && IsA(argvar, Var) &&
1561 argvar->varattno == InvalidAttrNumber)
1563 return (Node *) makeVar(argvar->varno,
1565 fselect->resulttype,
1566 fselect->resulttypmod,
1567 argvar->varlevelsup);
1572 * For any node type not handled above, we recurse using
1573 * expression_tree_mutator, which will copy the node unchanged but try
1574 * to simplify its arguments (if any) using this routine. For example:
1575 * we cannot eliminate an ArrayRef node, but we might be able to
1576 * simplify constant expressions in its subscripts.
1578 return expression_tree_mutator(node, eval_const_expressions_mutator,
1579 (void *) active_fns);
1583 * Subroutine for eval_const_expressions: try to simplify a function call
1584 * (which might originally have been an operator; we don't care)
1586 * Inputs are the function OID, actual result type OID (which is needed for
1587 * polymorphic functions), and the pre-simplified argument list;
1588 * also a list of already-active inline function expansions.
1590 * Returns a simplified expression if successful, or NULL if cannot
1591 * simplify the function call.
1594 simplify_function(Oid funcid, Oid result_type, List *args,
1595 bool allow_inline, List *active_fns)
1597 HeapTuple func_tuple;
1601 * We have two strategies for simplification: either execute the function
1602 * to deliver a constant result, or expand in-line the body of the
1603 * function definition (which only works for simple SQL-language
1604 * functions, but that is a common case). In either case we need access
1605 * to the function's pg_proc tuple, so fetch it just once to use in both
1608 func_tuple = SearchSysCache(PROCOID,
1609 ObjectIdGetDatum(funcid),
1611 if (!HeapTupleIsValid(func_tuple))
1612 elog(ERROR, "Function OID %u does not exist", funcid);
1614 newexpr = evaluate_function(funcid, result_type, args, func_tuple);
1616 if (!newexpr && allow_inline)
1617 newexpr = inline_function(funcid, result_type, args,
1618 func_tuple, active_fns);
1620 ReleaseSysCache(func_tuple);
1626 * evaluate_function: try to pre-evaluate a function call
1628 * We can do this if the function is strict and has any constant-null inputs
1629 * (just return a null constant), or if the function is immutable and has all
1630 * constant inputs (call it and return the result as a Const node).
1632 * Returns a simplified expression if successful, or NULL if cannot
1633 * simplify the function.
1636 evaluate_function(Oid funcid, Oid result_type, List *args,
1637 HeapTuple func_tuple)
1639 Form_pg_proc funcform = (Form_pg_proc) GETSTRUCT(func_tuple);
1640 bool has_nonconst_input = false;
1641 bool has_null_input = false;
1646 * Can't simplify if it returns a set.
1648 if (funcform->proretset)
1652 * Check for constant inputs and especially constant-NULL inputs.
1656 if (IsA(lfirst(arg), Const))
1657 has_null_input |= ((Const *) lfirst(arg))->constisnull;
1659 has_nonconst_input = true;
1663 * If the function is strict and has a constant-NULL input, it will
1664 * never be called at all, so we can replace the call by a NULL
1665 * constant, even if there are other inputs that aren't constant,
1666 * and even if the function is not otherwise immutable.
1668 if (funcform->proisstrict && has_null_input)
1669 return (Expr *) makeNullConst(result_type);
1672 * Otherwise, can simplify only if the function is immutable and
1673 * all inputs are constants. (For a non-strict function, constant NULL
1674 * inputs are treated the same as constant non-NULL inputs.)
1676 if (funcform->provolatile != PROVOLATILE_IMMUTABLE ||
1681 * OK, looks like we can simplify this operator/function.
1683 * Build a new FuncExpr node containing the already-simplified arguments.
1685 newexpr = makeNode(FuncExpr);
1686 newexpr->funcid = funcid;
1687 newexpr->funcresulttype = result_type;
1688 newexpr->funcretset = false;
1689 newexpr->funcformat = COERCE_EXPLICIT_CALL; /* doesn't matter */
1690 newexpr->args = args;
1692 return evaluate_expr((Expr *) newexpr, result_type);
1696 * inline_function: try to expand a function call inline
1698 * If the function is a sufficiently simple SQL-language function
1699 * (just "SELECT expression"), then we can inline it and avoid the rather
1700 * high per-call overhead of SQL functions. Furthermore, this can expose
1701 * opportunities for constant-folding within the function expression.
1703 * We have to beware of some special cases however. A directly or
1704 * indirectly recursive function would cause us to recurse forever,
1705 * so we keep track of which functions we are already expanding and
1706 * do not re-expand them. Also, if a parameter is used more than once
1707 * in the SQL-function body, we require it not to contain any volatile
1708 * functions or sublinks --- volatiles might deliver inconsistent answers,
1709 * and subplans might be unreasonably expensive to evaluate multiple times.
1710 * We must also beware of changing the volatility or strictness status of
1711 * functions by inlining them.
1713 * Returns a simplified expression if successful, or NULL if cannot
1714 * simplify the function.
1717 inline_function(Oid funcid, Oid result_type, List *args,
1718 HeapTuple func_tuple, List *active_fns)
1720 Form_pg_proc funcform = (Form_pg_proc) GETSTRUCT(func_tuple);
1721 char result_typtype;
1725 MemoryContext oldcxt;
1726 MemoryContext mycxt;
1727 List *raw_parsetree_list;
1728 List *querytree_list;
1737 * Forget it if the function is not SQL-language or has other
1738 * showstopper properties. (The nargs check is just paranoia.)
1740 if (funcform->prolang != SQLlanguageId ||
1741 funcform->prosecdef ||
1742 funcform->proretset ||
1743 funcform->pronargs != length(args))
1746 /* Forget it if declared return type is not base or domain */
1747 result_typtype = get_typtype(funcform->prorettype);
1748 if (result_typtype != 'b' &&
1749 result_typtype != 'd')
1752 /* Forget it if any declared argument type is polymorphic */
1753 for (j = 0; j < funcform->pronargs; j++)
1755 if (funcform->proargtypes[j] == ANYARRAYOID ||
1756 funcform->proargtypes[j] == ANYELEMENTOID)
1760 /* Check for recursive function, and give up trying to expand if so */
1761 if (oidMember(funcid, active_fns))
1764 /* Check permission to call function (fail later, if not) */
1765 if (pg_proc_aclcheck(funcid, GetUserId(), ACL_EXECUTE) != ACLCHECK_OK)
1769 * Make a temporary memory context, so that we don't leak all the
1770 * stuff that parsing might create.
1772 mycxt = AllocSetContextCreate(CurrentMemoryContext,
1774 ALLOCSET_DEFAULT_MINSIZE,
1775 ALLOCSET_DEFAULT_INITSIZE,
1776 ALLOCSET_DEFAULT_MAXSIZE);
1777 oldcxt = MemoryContextSwitchTo(mycxt);
1779 /* Fetch and parse the function body */
1780 tmp = SysCacheGetAttr(PROCOID,
1782 Anum_pg_proc_prosrc,
1785 elog(ERROR, "inline_function: null prosrc for procedure %u",
1787 src = DatumGetCString(DirectFunctionCall1(textout, tmp));
1790 * We just do parsing and parse analysis, not rewriting, because
1791 * rewriting will not affect table-free-SELECT-only queries, which is all
1792 * that we care about. Also, we can punt as soon as we detect more than
1793 * one command in the function body.
1795 raw_parsetree_list = pg_parse_query(src);
1796 if (length(raw_parsetree_list) != 1)
1799 querytree_list = parse_analyze(lfirst(raw_parsetree_list),
1800 funcform->proargtypes,
1801 funcform->pronargs);
1803 if (length(querytree_list) != 1)
1806 querytree = (Query *) lfirst(querytree_list);
1809 * The single command must be a simple "SELECT expression".
1811 if (!IsA(querytree, Query) ||
1812 querytree->commandType != CMD_SELECT ||
1813 querytree->resultRelation != 0 ||
1815 querytree->hasAggs ||
1816 querytree->hasSubLinks ||
1817 querytree->rtable ||
1818 querytree->jointree->fromlist ||
1819 querytree->jointree->quals ||
1820 querytree->groupClause ||
1821 querytree->havingQual ||
1822 querytree->distinctClause ||
1823 querytree->sortClause ||
1824 querytree->limitOffset ||
1825 querytree->limitCount ||
1826 querytree->setOperations ||
1827 length(querytree->targetList) != 1)
1830 newexpr = (Node *) ((TargetEntry *) lfirst(querytree->targetList))->expr;
1833 * Additional validity checks on the expression. It mustn't return a
1834 * set, and it mustn't be more volatile than the surrounding function
1835 * (this is to avoid breaking hacks that involve pretending a function
1836 * is immutable when it really ain't). If the surrounding function is
1837 * declared strict, then the expression must contain only strict constructs
1838 * and must use all of the function parameters (this is overkill, but
1839 * an exact analysis is hard).
1841 if (expression_returns_set(newexpr))
1844 if (funcform->provolatile == PROVOLATILE_IMMUTABLE &&
1845 contain_mutable_functions(newexpr))
1847 else if (funcform->provolatile == PROVOLATILE_STABLE &&
1848 contain_volatile_functions(newexpr))
1851 if (funcform->proisstrict &&
1852 contain_nonstrict_functions(newexpr))
1856 * We may be able to do it; there are still checks on parameter usage
1857 * to make, but those are most easily done in combination with the
1858 * actual substitution of the inputs. So start building expression
1859 * with inputs substituted.
1861 usecounts = (int *) palloc0((funcform->pronargs + 1) * sizeof(int));
1862 newexpr = substitute_actual_parameters(newexpr, funcform->pronargs,
1865 /* Now check for parameter usage */
1869 Node *param = lfirst(arg);
1871 if (usecounts[i] == 0)
1873 /* Param not used at all: uncool if func is strict */
1874 if (funcform->proisstrict)
1877 else if (usecounts[i] != 1)
1879 /* Param used multiple times: uncool if volatile or expensive */
1880 if (contain_volatile_functions(param) ||
1881 contain_subplans(param))
1888 * Whew --- we can make the substitution. Copy the modified expression
1889 * out of the temporary memory context, and clean up.
1891 MemoryContextSwitchTo(oldcxt);
1893 newexpr = copyObject(newexpr);
1895 MemoryContextDelete(mycxt);
1898 * Recursively try to simplify the modified expression. Here we must
1899 * add the current function to the context list of active functions.
1901 newexpr = eval_const_expressions_mutator(newexpr,
1902 lconso(funcid, active_fns));
1904 return (Expr *) newexpr;
1906 /* Here if func is not inlinable: release temp memory and return NULL */
1908 MemoryContextSwitchTo(oldcxt);
1909 MemoryContextDelete(mycxt);
1915 * Replace Param nodes by appropriate actual parameters
1918 substitute_actual_parameters(Node *expr, int nargs, List *args,
1921 substitute_actual_parameters_context context;
1923 context.nargs = nargs;
1924 context.args = args;
1925 context.usecounts = usecounts;
1927 return substitute_actual_parameters_mutator(expr, &context);
1931 substitute_actual_parameters_mutator(Node *node,
1932 substitute_actual_parameters_context *context)
1936 if (IsA(node, Param))
1938 Param *param = (Param *) node;
1940 if (param->paramkind != PARAM_NUM)
1941 elog(ERROR, "substitute_actual_parameters_mutator: unexpected paramkind");
1942 if (param->paramid <= 0 || param->paramid > context->nargs)
1943 elog(ERROR, "substitute_actual_parameters_mutator: unexpected paramid");
1945 /* Count usage of parameter */
1946 context->usecounts[param->paramid - 1]++;
1948 /* Select the appropriate actual arg and replace the Param with it */
1949 /* We don't need to copy at this time (it'll get done later) */
1950 return nth(param->paramid - 1, context->args);
1952 return expression_tree_mutator(node, substitute_actual_parameters_mutator,
1957 * evaluate_expr: pre-evaluate a constant expression
1959 * We use the executor's routine ExecEvalExpr() to avoid duplication of
1960 * code and ensure we get the same result as the executor would get.
1963 evaluate_expr(Expr *expr, Oid result_type)
1966 ExprState *exprstate;
1967 MemoryContext oldcontext;
1971 bool resultTypByVal;
1974 * To use the executor, we need an EState.
1976 estate = CreateExecutorState();
1978 /* We can use the estate's working context to avoid memory leaks. */
1979 oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
1982 * Prepare expr for execution.
1984 exprstate = ExecPrepareExpr(expr, estate);
1989 * It is OK to use a default econtext because none of the
1990 * ExecEvalExpr() code used in this situation will use econtext. That
1991 * might seem fortuitous, but it's not so unreasonable --- a constant
1992 * expression does not depend on context, by definition, n'est ce pas?
1994 const_val = ExecEvalExprSwitchContext(exprstate,
1995 GetPerTupleExprContext(estate),
1996 &const_is_null, NULL);
1998 /* Get info needed about result datatype */
1999 get_typlenbyval(result_type, &resultTypLen, &resultTypByVal);
2001 /* Get back to outer memory context */
2002 MemoryContextSwitchTo(oldcontext);
2004 /* Must copy result out of sub-context used by expression eval */
2006 const_val = datumCopy(const_val, resultTypByVal, resultTypLen);
2008 /* Release all the junk we just created */
2009 FreeExecutorState(estate);
2012 * Make the constant result node.
2014 return (Expr *) makeConst(result_type, resultTypLen,
2015 const_val, const_is_null,
2021 * Standard expression-tree walking support
2023 * We used to have near-duplicate code in many different routines that
2024 * understood how to recurse through an expression node tree. That was
2025 * a pain to maintain, and we frequently had bugs due to some particular
2026 * routine neglecting to support a particular node type. In most cases,
2027 * these routines only actually care about certain node types, and don't
2028 * care about other types except insofar as they have to recurse through
2029 * non-primitive node types. Therefore, we now provide generic tree-walking
2030 * logic to consolidate the redundant "boilerplate" code. There are
2031 * two versions: expression_tree_walker() and expression_tree_mutator().
2034 /*--------------------
2035 * expression_tree_walker() is designed to support routines that traverse
2036 * a tree in a read-only fashion (although it will also work for routines
2037 * that modify nodes in-place but never add/delete/replace nodes).
2038 * A walker routine should look like this:
2040 * bool my_walker (Node *node, my_struct *context)
2044 * // check for nodes that special work is required for, eg:
2045 * if (IsA(node, Var))
2047 * ... do special actions for Var nodes
2049 * else if (IsA(node, ...))
2051 * ... do special actions for other node types
2053 * // for any node type not specially processed, do:
2054 * return expression_tree_walker(node, my_walker, (void *) context);
2057 * The "context" argument points to a struct that holds whatever context
2058 * information the walker routine needs --- it can be used to return data
2059 * gathered by the walker, too. This argument is not touched by
2060 * expression_tree_walker, but it is passed down to recursive sub-invocations
2061 * of my_walker. The tree walk is started from a setup routine that
2062 * fills in the appropriate context struct, calls my_walker with the top-level
2063 * node of the tree, and then examines the results.
2065 * The walker routine should return "false" to continue the tree walk, or
2066 * "true" to abort the walk and immediately return "true" to the top-level
2067 * caller. This can be used to short-circuit the traversal if the walker
2068 * has found what it came for. "false" is returned to the top-level caller
2069 * iff no invocation of the walker returned "true".
2071 * The node types handled by expression_tree_walker include all those
2072 * normally found in target lists and qualifier clauses during the planning
2073 * stage. In particular, it handles List nodes since a cnf-ified qual clause
2074 * will have List structure at the top level, and it handles TargetEntry nodes
2075 * so that a scan of a target list can be handled without additional code.
2076 * (But only the "expr" part of a TargetEntry is examined, unless the walker
2077 * chooses to process TargetEntry nodes specially.) Also, RangeTblRef,
2078 * FromExpr, JoinExpr, and SetOperationStmt nodes are handled, so that query
2079 * jointrees and setOperation trees can be processed without additional code.
2081 * expression_tree_walker will handle SubLink nodes by recursing normally into
2082 * the "lefthand" arguments (which are expressions belonging to the outer
2083 * plan). It will also call the walker on the sub-Query node; however, when
2084 * expression_tree_walker itself is called on a Query node, it does nothing
2085 * and returns "false". The net effect is that unless the walker does
2086 * something special at a Query node, sub-selects will not be visited during
2087 * an expression tree walk. This is exactly the behavior wanted in many cases
2088 * --- and for those walkers that do want to recurse into sub-selects, special
2089 * behavior is typically needed anyway at the entry to a sub-select (such as
2090 * incrementing a depth counter). A walker that wants to examine sub-selects
2091 * should include code along the lines of:
2093 * if (IsA(node, Query))
2095 * adjust context for subquery;
2096 * result = query_tree_walker((Query *) node, my_walker, context,
2097 * 0); // adjust flags as needed
2098 * restore context if needed;
2102 * query_tree_walker is a convenience routine (see below) that calls the
2103 * walker on all the expression subtrees of the given Query node.
2105 * expression_tree_walker will handle SubPlan nodes by recursing normally
2106 * into the "exprs" and "args" lists (which are expressions belonging to
2107 * the outer plan). It will not touch the completed subplan, however. Since
2108 * there is no link to the original Query, it is not possible to recurse into
2109 * subselects of an already-planned expression tree. This is OK for current
2110 * uses, but may need to be revisited in future.
2111 *--------------------
2115 expression_tree_walker(Node *node,
2122 * The walker has already visited the current node, and so we need
2123 * only recurse into any sub-nodes it has.
2125 * We assume that the walker is not interested in List nodes per se, so
2126 * when we expect a List we just recurse directly to self without
2127 * bothering to call the walker.
2131 switch (nodeTag(node))
2136 case T_CoerceToDomainValue:
2138 /* primitive node types with no subnodes */
2141 return walker(((Aggref *) node)->target, context);
2144 ArrayRef *aref = (ArrayRef *) node;
2146 /* recurse directly for upper/lower array index lists */
2147 if (expression_tree_walker((Node *) aref->refupperindexpr,
2150 if (expression_tree_walker((Node *) aref->reflowerindexpr,
2153 /* walker must see the refexpr and refassgnexpr, however */
2154 if (walker(aref->refexpr, context))
2156 if (walker(aref->refassgnexpr, context))
2162 FuncExpr *expr = (FuncExpr *) node;
2164 if (expression_tree_walker((Node *) expr->args,
2171 OpExpr *expr = (OpExpr *) node;
2173 if (expression_tree_walker((Node *) expr->args,
2178 case T_DistinctExpr:
2180 DistinctExpr *expr = (DistinctExpr *) node;
2182 if (expression_tree_walker((Node *) expr->args,
2187 case T_ScalarArrayOpExpr:
2189 ScalarArrayOpExpr *expr = (ScalarArrayOpExpr *) node;
2191 if (expression_tree_walker((Node *) expr->args,
2198 BoolExpr *expr = (BoolExpr *) node;
2200 if (expression_tree_walker((Node *) expr->args,
2207 SubLink *sublink = (SubLink *) node;
2209 if (expression_tree_walker((Node *) sublink->lefthand,
2213 * Also invoke the walker on the sublink's Query node, so
2214 * it can recurse into the sub-query if it wants to.
2216 return walker(sublink->subselect, context);
2221 SubPlan *subplan = (SubPlan *) node;
2223 /* recurse into the exprs list, but not into the Plan */
2224 if (expression_tree_walker((Node *) subplan->exprs,
2227 /* also examine args list */
2228 if (expression_tree_walker((Node *) subplan->args,
2234 return walker(((FieldSelect *) node)->arg, context);
2236 return walker(((RelabelType *) node)->arg, context);
2239 CaseExpr *caseexpr = (CaseExpr *) node;
2241 /* we assume walker doesn't care about CaseWhens, either */
2242 foreach(temp, caseexpr->args)
2244 CaseWhen *when = (CaseWhen *) lfirst(temp);
2246 Assert(IsA(when, CaseWhen));
2247 if (walker(when->expr, context))
2249 if (walker(when->result, context))
2252 /* caseexpr->arg should be null, but we'll check it anyway */
2253 if (walker(caseexpr->arg, context))
2255 if (walker(caseexpr->defresult, context))
2260 return walker(((ArrayExpr *) node)->elements, context);
2261 case T_CoalesceExpr:
2262 return walker(((CoalesceExpr *) node)->args, context);
2264 return walker(((NullIfExpr *) node)->args, context);
2266 return walker(((NullTest *) node)->arg, context);
2268 return walker(((BooleanTest *) node)->arg, context);
2269 case T_CoerceToDomain:
2270 return walker(((CoerceToDomain *) node)->arg, context);
2272 return walker(((TargetEntry *) node)->expr, context);
2274 /* Do nothing with a sub-Query, per discussion above */
2277 foreach(temp, (List *) node)
2279 if (walker((Node *) lfirst(temp), context))
2285 FromExpr *from = (FromExpr *) node;
2287 if (walker(from->fromlist, context))
2289 if (walker(from->quals, context))
2295 JoinExpr *join = (JoinExpr *) node;
2297 if (walker(join->larg, context))
2299 if (walker(join->rarg, context))
2301 if (walker(join->quals, context))
2305 * alias clause, using list are deemed uninteresting.
2309 case T_SetOperationStmt:
2311 SetOperationStmt *setop = (SetOperationStmt *) node;
2313 if (walker(setop->larg, context))
2315 if (walker(setop->rarg, context))
2319 case T_InClauseInfo:
2321 InClauseInfo *ininfo = (InClauseInfo *) node;
2323 if (expression_tree_walker((Node *) ininfo->sub_targetlist,
2329 elog(ERROR, "expression_tree_walker: Unexpected node type %d",
2337 * query_tree_walker --- initiate a walk of a Query's expressions
2339 * This routine exists just to reduce the number of places that need to know
2340 * where all the expression subtrees of a Query are. Note it can be used
2341 * for starting a walk at top level of a Query regardless of whether the
2342 * walker intends to descend into subqueries. It is also useful for
2343 * descending into subqueries within a walker.
2345 * Some callers want to suppress visitation of certain items in the sub-Query,
2346 * typically because they need to process them specially, or don't actually
2347 * want to recurse into subqueries. This is supported by the flags argument,
2348 * which is the bitwise OR of flag values to suppress visitation of
2349 * indicated items. (More flag bits may be added as needed.)
2352 query_tree_walker(Query *query,
2359 Assert(query != NULL && IsA(query, Query));
2361 if (walker((Node *) query->targetList, context))
2363 if (walker((Node *) query->jointree, context))
2365 if (walker(query->setOperations, context))
2367 if (walker(query->havingQual, context))
2369 if (walker(query->in_info_list, context))
2371 foreach(rt, query->rtable)
2373 RangeTblEntry *rte = (RangeTblEntry *) lfirst(rt);
2375 switch (rte->rtekind)
2382 if (! (flags & QTW_IGNORE_RT_SUBQUERIES))
2383 if (walker(rte->subquery, context))
2387 if (! (flags & QTW_IGNORE_JOINALIASES))
2388 if (walker(rte->joinaliasvars, context))
2392 if (walker(rte->funcexpr, context))
2401 /*--------------------
2402 * expression_tree_mutator() is designed to support routines that make a
2403 * modified copy of an expression tree, with some nodes being added,
2404 * removed, or replaced by new subtrees. The original tree is (normally)
2405 * not changed. Each recursion level is responsible for returning a copy of
2406 * (or appropriately modified substitute for) the subtree it is handed.
2407 * A mutator routine should look like this:
2409 * Node * my_mutator (Node *node, my_struct *context)
2413 * // check for nodes that special work is required for, eg:
2414 * if (IsA(node, Var))
2416 * ... create and return modified copy of Var node
2418 * else if (IsA(node, ...))
2420 * ... do special transformations of other node types
2422 * // for any node type not specially processed, do:
2423 * return expression_tree_mutator(node, my_mutator, (void *) context);
2426 * The "context" argument points to a struct that holds whatever context
2427 * information the mutator routine needs --- it can be used to return extra
2428 * data gathered by the mutator, too. This argument is not touched by
2429 * expression_tree_mutator, but it is passed down to recursive sub-invocations
2430 * of my_mutator. The tree walk is started from a setup routine that
2431 * fills in the appropriate context struct, calls my_mutator with the
2432 * top-level node of the tree, and does any required post-processing.
2434 * Each level of recursion must return an appropriately modified Node.
2435 * If expression_tree_mutator() is called, it will make an exact copy
2436 * of the given Node, but invoke my_mutator() to copy the sub-node(s)
2437 * of that Node. In this way, my_mutator() has full control over the
2438 * copying process but need not directly deal with expression trees
2439 * that it has no interest in.
2441 * Just as for expression_tree_walker, the node types handled by
2442 * expression_tree_mutator include all those normally found in target lists
2443 * and qualifier clauses during the planning stage.
2445 * expression_tree_mutator will handle SubLink nodes by recursing normally
2446 * into the "lefthand" arguments (which are expressions belonging to the outer
2447 * plan). It will also call the mutator on the sub-Query node; however, when
2448 * expression_tree_mutator itself is called on a Query node, it does nothing
2449 * and returns the unmodified Query node. The net effect is that unless the
2450 * mutator does something special at a Query node, sub-selects will not be
2451 * visited or modified; the original sub-select will be linked to by the new
2452 * SubLink node. Mutators that want to descend into sub-selects will usually
2453 * do so by recognizing Query nodes and calling query_tree_mutator (below).
2455 * expression_tree_mutator will handle a SubPlan node by recursing into
2456 * the "exprs" and "args" lists (which belong to the outer plan), but it
2457 * will simply copy the link to the inner plan, since that's typically what
2458 * expression tree mutators want. A mutator that wants to modify the subplan
2459 * can force appropriate behavior by recognizing SubPlan expression nodes
2460 * and doing the right thing.
2461 *--------------------
2465 expression_tree_mutator(Node *node,
2466 Node *(*mutator) (),
2470 * The mutator has already decided not to modify the current node, but
2471 * we must call the mutator for any sub-nodes.
2474 #define FLATCOPY(newnode, node, nodetype) \
2475 ( (newnode) = makeNode(nodetype), \
2476 memcpy((newnode), (node), sizeof(nodetype)) )
2478 #define CHECKFLATCOPY(newnode, node, nodetype) \
2479 ( AssertMacro(IsA((node), nodetype)), \
2480 (newnode) = makeNode(nodetype), \
2481 memcpy((newnode), (node), sizeof(nodetype)) )
2483 #define MUTATE(newfield, oldfield, fieldtype) \
2484 ( (newfield) = (fieldtype) mutator((Node *) (oldfield), context) )
2488 switch (nodeTag(node))
2493 case T_CoerceToDomainValue:
2495 /* primitive node types with no subnodes */
2496 return (Node *) copyObject(node);
2499 Aggref *aggref = (Aggref *) node;
2502 FLATCOPY(newnode, aggref, Aggref);
2503 MUTATE(newnode->target, aggref->target, Expr *);
2504 return (Node *) newnode;
2509 ArrayRef *arrayref = (ArrayRef *) node;
2512 FLATCOPY(newnode, arrayref, ArrayRef);
2513 MUTATE(newnode->refupperindexpr, arrayref->refupperindexpr,
2515 MUTATE(newnode->reflowerindexpr, arrayref->reflowerindexpr,
2517 MUTATE(newnode->refexpr, arrayref->refexpr,
2519 MUTATE(newnode->refassgnexpr, arrayref->refassgnexpr,
2521 return (Node *) newnode;
2526 FuncExpr *expr = (FuncExpr *) node;
2529 FLATCOPY(newnode, expr, FuncExpr);
2530 MUTATE(newnode->args, expr->args, List *);
2531 return (Node *) newnode;
2536 OpExpr *expr = (OpExpr *) node;
2539 FLATCOPY(newnode, expr, OpExpr);
2540 MUTATE(newnode->args, expr->args, List *);
2541 return (Node *) newnode;
2544 case T_DistinctExpr:
2546 DistinctExpr *expr = (DistinctExpr *) node;
2547 DistinctExpr *newnode;
2549 FLATCOPY(newnode, expr, DistinctExpr);
2550 MUTATE(newnode->args, expr->args, List *);
2551 return (Node *) newnode;
2554 case T_ScalarArrayOpExpr:
2556 ScalarArrayOpExpr *expr = (ScalarArrayOpExpr *) node;
2557 ScalarArrayOpExpr *newnode;
2559 FLATCOPY(newnode, expr, ScalarArrayOpExpr);
2560 MUTATE(newnode->args, expr->args, List *);
2561 return (Node *) newnode;
2566 BoolExpr *expr = (BoolExpr *) node;
2569 FLATCOPY(newnode, expr, BoolExpr);
2570 MUTATE(newnode->args, expr->args, List *);
2571 return (Node *) newnode;
2576 SubLink *sublink = (SubLink *) node;
2579 FLATCOPY(newnode, sublink, SubLink);
2580 MUTATE(newnode->lefthand, sublink->lefthand, List *);
2582 * Also invoke the mutator on the sublink's Query node, so
2583 * it can recurse into the sub-query if it wants to.
2585 MUTATE(newnode->subselect, sublink->subselect, Node *);
2586 return (Node *) newnode;
2591 SubPlan *subplan = (SubPlan *) node;
2594 FLATCOPY(newnode, subplan, SubPlan);
2595 /* transform exprs list */
2596 MUTATE(newnode->exprs, subplan->exprs, List *);
2597 /* transform args list (params to be passed to subplan) */
2598 MUTATE(newnode->args, subplan->args, List *);
2599 /* but not the sub-Plan itself, which is referenced as-is */
2600 return (Node *) newnode;
2605 FieldSelect *fselect = (FieldSelect *) node;
2606 FieldSelect *newnode;
2608 FLATCOPY(newnode, fselect, FieldSelect);
2609 MUTATE(newnode->arg, fselect->arg, Expr *);
2610 return (Node *) newnode;
2615 RelabelType *relabel = (RelabelType *) node;
2616 RelabelType *newnode;
2618 FLATCOPY(newnode, relabel, RelabelType);
2619 MUTATE(newnode->arg, relabel->arg, Expr *);
2620 return (Node *) newnode;
2625 CaseExpr *caseexpr = (CaseExpr *) node;
2628 FLATCOPY(newnode, caseexpr, CaseExpr);
2629 MUTATE(newnode->args, caseexpr->args, List *);
2630 /* caseexpr->arg should be null, but we'll check it anyway */
2631 MUTATE(newnode->arg, caseexpr->arg, Expr *);
2632 MUTATE(newnode->defresult, caseexpr->defresult, Expr *);
2633 return (Node *) newnode;
2638 CaseWhen *casewhen = (CaseWhen *) node;
2641 FLATCOPY(newnode, casewhen, CaseWhen);
2642 MUTATE(newnode->expr, casewhen->expr, Expr *);
2643 MUTATE(newnode->result, casewhen->result, Expr *);
2644 return (Node *) newnode;
2649 ArrayExpr *arrayexpr = (ArrayExpr *) node;
2652 FLATCOPY(newnode, arrayexpr, ArrayExpr);
2653 MUTATE(newnode->elements, arrayexpr->elements, List *);
2654 return (Node *) newnode;
2657 case T_CoalesceExpr:
2659 CoalesceExpr *coalesceexpr = (CoalesceExpr *) node;
2660 CoalesceExpr *newnode;
2662 FLATCOPY(newnode, coalesceexpr, CoalesceExpr);
2663 MUTATE(newnode->args, coalesceexpr->args, List *);
2664 return (Node *) newnode;
2669 NullIfExpr *expr = (NullIfExpr *) node;
2670 NullIfExpr *newnode;
2672 FLATCOPY(newnode, expr, NullIfExpr);
2673 MUTATE(newnode->args, expr->args, List *);
2674 return (Node *) newnode;
2679 NullTest *ntest = (NullTest *) node;
2682 FLATCOPY(newnode, ntest, NullTest);
2683 MUTATE(newnode->arg, ntest->arg, Expr *);
2684 return (Node *) newnode;
2689 BooleanTest *btest = (BooleanTest *) node;
2690 BooleanTest *newnode;
2692 FLATCOPY(newnode, btest, BooleanTest);
2693 MUTATE(newnode->arg, btest->arg, Expr *);
2694 return (Node *) newnode;
2697 case T_CoerceToDomain:
2699 CoerceToDomain *ctest = (CoerceToDomain *) node;
2700 CoerceToDomain *newnode;
2702 FLATCOPY(newnode, ctest, CoerceToDomain);
2703 MUTATE(newnode->arg, ctest->arg, Expr *);
2704 return (Node *) newnode;
2710 * We mutate the expression, but not the resdom, by
2713 TargetEntry *targetentry = (TargetEntry *) node;
2714 TargetEntry *newnode;
2716 FLATCOPY(newnode, targetentry, TargetEntry);
2717 MUTATE(newnode->expr, targetentry->expr, Expr *);
2718 return (Node *) newnode;
2722 /* Do nothing with a sub-Query, per discussion above */
2727 * We assume the mutator isn't interested in the list
2728 * nodes per se, so just invoke it on each list element.
2729 * NOTE: this would fail badly on a list with integer
2732 FastList resultlist;
2735 FastListInit(&resultlist);
2736 foreach(temp, (List *) node)
2738 FastAppend(&resultlist,
2739 mutator((Node *) lfirst(temp), context));
2741 return (Node *) FastListValue(&resultlist);
2746 FromExpr *from = (FromExpr *) node;
2749 FLATCOPY(newnode, from, FromExpr);
2750 MUTATE(newnode->fromlist, from->fromlist, List *);
2751 MUTATE(newnode->quals, from->quals, Node *);
2752 return (Node *) newnode;
2757 JoinExpr *join = (JoinExpr *) node;
2760 FLATCOPY(newnode, join, JoinExpr);
2761 MUTATE(newnode->larg, join->larg, Node *);
2762 MUTATE(newnode->rarg, join->rarg, Node *);
2763 MUTATE(newnode->quals, join->quals, Node *);
2764 /* We do not mutate alias or using by default */
2765 return (Node *) newnode;
2768 case T_SetOperationStmt:
2770 SetOperationStmt *setop = (SetOperationStmt *) node;
2771 SetOperationStmt *newnode;
2773 FLATCOPY(newnode, setop, SetOperationStmt);
2774 MUTATE(newnode->larg, setop->larg, Node *);
2775 MUTATE(newnode->rarg, setop->rarg, Node *);
2776 return (Node *) newnode;
2779 case T_InClauseInfo:
2781 InClauseInfo *ininfo = (InClauseInfo *) node;
2782 InClauseInfo *newnode;
2784 FLATCOPY(newnode, ininfo, InClauseInfo);
2785 MUTATE(newnode->sub_targetlist, ininfo->sub_targetlist, List *);
2786 return (Node *) newnode;
2790 elog(ERROR, "expression_tree_mutator: Unexpected node type %d",
2794 /* can't get here, but keep compiler happy */
2800 * query_tree_mutator --- initiate modification of a Query's expressions
2802 * This routine exists just to reduce the number of places that need to know
2803 * where all the expression subtrees of a Query are. Note it can be used
2804 * for starting a walk at top level of a Query regardless of whether the
2805 * mutator intends to descend into subqueries. It is also useful for
2806 * descending into subqueries within a mutator.
2808 * Some callers want to suppress mutating of certain items in the Query,
2809 * typically because they need to process them specially, or don't actually
2810 * want to recurse into subqueries. This is supported by the flags argument,
2811 * which is the bitwise OR of flag values to suppress mutating of
2812 * indicated items. (More flag bits may be added as needed.)
2814 * Normally the Query node itself is copied, but some callers want it to be
2815 * modified in-place; they must pass QTW_DONT_COPY_QUERY in flags. All
2816 * modified substructure is safely copied in any case.
2819 query_tree_mutator(Query *query,
2820 Node *(*mutator) (),
2827 Assert(query != NULL && IsA(query, Query));
2829 if (! (flags & QTW_DONT_COPY_QUERY))
2833 FLATCOPY(newquery, query, Query);
2837 MUTATE(query->targetList, query->targetList, List *);
2838 MUTATE(query->jointree, query->jointree, FromExpr *);
2839 MUTATE(query->setOperations, query->setOperations, Node *);
2840 MUTATE(query->havingQual, query->havingQual, Node *);
2841 MUTATE(query->in_info_list, query->in_info_list, List *);
2842 FastListInit(&newrt);
2843 foreach(rt, query->rtable)
2845 RangeTblEntry *rte = (RangeTblEntry *) lfirst(rt);
2846 RangeTblEntry *newrte;
2848 switch (rte->rtekind)
2852 /* nothing to do, don't bother to make a copy */
2855 if (! (flags & QTW_IGNORE_RT_SUBQUERIES))
2857 FLATCOPY(newrte, rte, RangeTblEntry);
2858 CHECKFLATCOPY(newrte->subquery, rte->subquery, Query);
2859 MUTATE(newrte->subquery, newrte->subquery, Query *);
2864 if (! (flags & QTW_IGNORE_JOINALIASES))
2866 FLATCOPY(newrte, rte, RangeTblEntry);
2867 MUTATE(newrte->joinaliasvars, rte->joinaliasvars, List *);
2872 FLATCOPY(newrte, rte, RangeTblEntry);
2873 MUTATE(newrte->funcexpr, rte->funcexpr, Node *);
2877 FastAppend(&newrt, rte);
2879 query->rtable = FastListValue(&newrt);
2884 * query_or_expression_tree_walker --- hybrid form
2886 * This routine will invoke query_tree_walker if called on a Query node,
2887 * else will invoke the walker directly. This is a useful way of starting
2888 * the recursion when the walker's normal change of state is not appropriate
2889 * for the outermost Query node.
2892 query_or_expression_tree_walker(Node *node,
2897 if (node && IsA(node, Query))
2898 return query_tree_walker((Query *) node,
2903 return walker(node, context);
2907 * query_or_expression_tree_mutator --- hybrid form
2909 * This routine will invoke query_tree_mutator if called on a Query node,
2910 * else will invoke the mutator directly. This is a useful way of starting
2911 * the recursion when the mutator's normal change of state is not appropriate
2912 * for the outermost Query node.
2915 query_or_expression_tree_mutator(Node *node,
2916 Node *(*mutator) (),
2920 if (node && IsA(node, Query))
2921 return (Node *) query_tree_mutator((Query *) node,
2926 return mutator(node, context);