1 /*-------------------------------------------------------------------------
4 * routines to manipulate qualification clauses
6 * Portions Copyright (c) 1996-2003, 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.161 2004/01/10 18:13:53 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/cost.h"
30 #include "optimizer/planmain.h"
31 #include "optimizer/var.h"
32 #include "parser/analyze.h"
33 #include "parser/parse_clause.h"
34 #include "parser/parse_expr.h"
35 #include "tcop/tcopprot.h"
36 #include "utils/acl.h"
37 #include "utils/builtins.h"
38 #include "utils/datum.h"
39 #include "utils/lsyscache.h"
40 #include "utils/memutils.h"
41 #include "utils/syscache.h"
44 /* note that pg_type.h hardwires size of bool as 1 ... duplicate it */
45 #define MAKEBOOLCONST(val,isnull) \
46 ((Node *) makeConst(BOOLOID, 1, (Datum) (val), (isnull), true))
53 } substitute_actual_parameters_context;
55 static bool contain_agg_clause_walker(Node *node, void *context);
56 static bool contain_distinct_agg_clause_walker(Node *node, void *context);
57 static bool count_agg_clause_walker(Node *node, int *count);
58 static bool expression_returns_set_walker(Node *node, void *context);
59 static bool contain_subplans_walker(Node *node, void *context);
60 static bool contain_mutable_functions_walker(Node *node, void *context);
61 static bool contain_volatile_functions_walker(Node *node, void *context);
62 static bool contain_nonstrict_functions_walker(Node *node, void *context);
63 static Node *eval_const_expressions_mutator(Node *node, List *active_fns);
64 static Expr *simplify_function(Oid funcid, Oid result_type, List *args,
65 bool allow_inline, List *active_fns);
66 static Expr *evaluate_function(Oid funcid, Oid result_type, List *args,
67 HeapTuple func_tuple);
68 static Expr *inline_function(Oid funcid, Oid result_type, List *args,
69 HeapTuple func_tuple, List *active_fns);
70 static Node *substitute_actual_parameters(Node *expr, int nargs, List *args,
72 static Node *substitute_actual_parameters_mutator(Node *node,
73 substitute_actual_parameters_context *context);
74 static void sql_inline_error_callback(void *arg);
75 static Expr *evaluate_expr(Expr *expr, Oid result_type);
78 /*****************************************************************************
79 * OPERATOR clause functions
80 *****************************************************************************/
84 * Creates an operator clause given its operator info, left operand,
85 * and right operand (pass NULL to create single-operand clause).
88 make_opclause(Oid opno, Oid opresulttype, bool opretset,
89 Expr *leftop, Expr *rightop)
91 OpExpr *expr = makeNode(OpExpr);
94 expr->opfuncid = InvalidOid;
95 expr->opresulttype = opresulttype;
96 expr->opretset = opretset;
98 expr->args = makeList2(leftop, rightop);
100 expr->args = makeList1(leftop);
101 return (Expr *) expr;
107 * Returns the left operand of a clause of the form (op expr expr)
111 get_leftop(Expr *clause)
113 OpExpr *expr = (OpExpr *) clause;
115 if (expr->args != NIL)
116 return lfirst(expr->args);
124 * Returns the right operand in a clause of the form (op expr expr).
125 * NB: result will be NULL if applied to a unary op clause.
128 get_rightop(Expr *clause)
130 OpExpr *expr = (OpExpr *) clause;
132 if (expr->args != NIL && lnext(expr->args) != NIL)
133 return lfirst(lnext(expr->args));
138 /*****************************************************************************
139 * NOT clause functions
140 *****************************************************************************/
145 * Returns t iff this is a 'not' clause: (NOT expr).
148 not_clause(Node *clause)
150 return (clause != NULL &&
151 IsA(clause, BoolExpr) &&
152 ((BoolExpr *) clause)->boolop == NOT_EXPR);
158 * Create a 'not' clause given the expression to be negated.
161 make_notclause(Expr *notclause)
163 BoolExpr *expr = makeNode(BoolExpr);
165 expr->boolop = NOT_EXPR;
166 expr->args = makeList1(notclause);
167 return (Expr *) expr;
173 * Retrieve the clause within a 'not' clause
176 get_notclausearg(Expr *notclause)
178 return lfirst(((BoolExpr *) notclause)->args);
181 /*****************************************************************************
182 * OR clause functions
183 *****************************************************************************/
188 * Returns t iff the clause is an 'or' clause: (OR { expr }).
191 or_clause(Node *clause)
193 return (clause != NULL &&
194 IsA(clause, BoolExpr) &&
195 ((BoolExpr *) clause)->boolop == OR_EXPR);
201 * Creates an 'or' clause given a list of its subclauses.
204 make_orclause(List *orclauses)
206 BoolExpr *expr = makeNode(BoolExpr);
208 expr->boolop = OR_EXPR;
209 expr->args = orclauses;
210 return (Expr *) expr;
213 /*****************************************************************************
214 * AND clause functions
215 *****************************************************************************/
221 * Returns t iff its argument is an 'and' clause: (AND { expr }).
224 and_clause(Node *clause)
226 return (clause != NULL &&
227 IsA(clause, BoolExpr) &&
228 ((BoolExpr *) clause)->boolop == AND_EXPR);
234 * Creates an 'and' clause given a list of its subclauses.
237 make_andclause(List *andclauses)
239 BoolExpr *expr = makeNode(BoolExpr);
241 expr->boolop = AND_EXPR;
242 expr->args = andclauses;
243 return (Expr *) expr;
249 * Variant of make_andclause for ANDing two qual conditions together.
250 * Qual conditions have the property that a NULL nodetree is interpreted
254 make_and_qual(Node *qual1, Node *qual2)
260 return (Node *) make_andclause(makeList2(qual1, qual2));
264 * Sometimes (such as in the input of ExecQual), we use lists of expression
265 * nodes with implicit AND semantics.
267 * These functions convert between an AND-semantics expression list and the
268 * ordinary representation of a boolean expression.
270 * Note that an empty list is considered equivalent to TRUE.
273 make_ands_explicit(List *andclauses)
275 if (andclauses == NIL)
276 return (Expr *) MAKEBOOLCONST(true, false);
277 else if (lnext(andclauses) == NIL)
278 return (Expr *) lfirst(andclauses);
280 return make_andclause(andclauses);
284 make_ands_implicit(Expr *clause)
287 * NB: because the parser sets the qual field to NULL in a query that
288 * has no WHERE clause, we must consider a NULL input clause as TRUE,
289 * even though one might more reasonably think it FALSE. Grumble. If
290 * this causes trouble, consider changing the parser's behavior.
293 return NIL; /* NULL -> NIL list == TRUE */
294 else if (and_clause((Node *) clause))
295 return ((BoolExpr *) clause)->args;
296 else if (IsA(clause, Const) &&
297 !((Const *) clause)->constisnull &&
298 DatumGetBool(((Const *) clause)->constvalue))
299 return NIL; /* constant TRUE input -> NIL list */
301 return makeList1(clause);
305 /*****************************************************************************
306 * Aggregate-function clause manipulation
307 *****************************************************************************/
311 * Recursively search for Aggref nodes within a clause.
313 * Returns true if any aggregate found.
315 * This does not descend into subqueries, and so should be used only after
316 * reduction of sublinks to subplans, or in contexts where it's known there
317 * are no subqueries. There mustn't be outer-aggregate references either.
319 * (If you want something like this but able to deal with subqueries,
320 * see rewriteManip.c's checkExprHasAggs().)
323 contain_agg_clause(Node *clause)
325 return contain_agg_clause_walker(clause, NULL);
329 contain_agg_clause_walker(Node *node, void *context)
333 if (IsA(node, Aggref))
335 Assert(((Aggref *) node)->agglevelsup == 0);
336 return true; /* abort the tree traversal and return
339 Assert(!IsA(node, SubLink));
340 return expression_tree_walker(node, contain_agg_clause_walker, context);
344 * contain_distinct_agg_clause
345 * Recursively search for DISTINCT Aggref nodes within a clause.
347 * Returns true if any DISTINCT aggregate found.
349 * This does not descend into subqueries, and so should be used only after
350 * reduction of sublinks to subplans, or in contexts where it's known there
351 * are no subqueries. There mustn't be outer-aggregate references either.
354 contain_distinct_agg_clause(Node *clause)
356 return contain_distinct_agg_clause_walker(clause, NULL);
360 contain_distinct_agg_clause_walker(Node *node, void *context)
364 if (IsA(node, Aggref))
366 Assert(((Aggref *) node)->agglevelsup == 0);
367 if (((Aggref *) node)->aggdistinct)
368 return true; /* abort the tree traversal and return
371 Assert(!IsA(node, SubLink));
372 return expression_tree_walker(node, contain_distinct_agg_clause_walker, context);
377 * Recursively count the Aggref nodes in an expression tree.
379 * Note: this also checks for nested aggregates, which are an error.
381 * This does not descend into subqueries, and so should be used only after
382 * reduction of sublinks to subplans, or in contexts where it's known there
383 * are no subqueries. There mustn't be outer-aggregate references either.
386 count_agg_clause(Node *clause)
390 count_agg_clause_walker(clause, &result);
395 count_agg_clause_walker(Node *node, int *count)
399 if (IsA(node, Aggref))
401 Assert(((Aggref *) node)->agglevelsup == 0);
405 * Complain if the aggregate's argument contains any aggregates;
406 * nested agg functions are semantically nonsensical.
408 if (contain_agg_clause((Node *) ((Aggref *) node)->target))
410 (errcode(ERRCODE_GROUPING_ERROR),
411 errmsg("aggregate function calls may not be nested")));
414 * Having checked that, we need not recurse into the argument.
418 Assert(!IsA(node, SubLink));
419 return expression_tree_walker(node, count_agg_clause_walker,
424 /*****************************************************************************
425 * Support for expressions returning sets
426 *****************************************************************************/
429 * expression_returns_set
430 * Test whether an expression returns a set result.
432 * Because we use expression_tree_walker(), this can also be applied to
433 * whole targetlists; it'll produce TRUE if any one of the tlist items
437 expression_returns_set(Node *clause)
439 return expression_returns_set_walker(clause, NULL);
443 expression_returns_set_walker(Node *node, void *context)
447 if (IsA(node, FuncExpr))
449 FuncExpr *expr = (FuncExpr *) node;
451 if (expr->funcretset)
453 /* else fall through to check args */
455 if (IsA(node, OpExpr))
457 OpExpr *expr = (OpExpr *) node;
461 /* else fall through to check args */
464 /* Avoid recursion for some cases that can't return a set */
465 if (IsA(node, Aggref))
467 if (IsA(node, DistinctExpr))
469 if (IsA(node, ScalarArrayOpExpr))
471 if (IsA(node, BoolExpr))
473 if (IsA(node, SubLink))
475 if (IsA(node, SubPlan))
477 if (IsA(node, ArrayExpr))
479 if (IsA(node, CoalesceExpr))
481 if (IsA(node, NullIfExpr))
484 return expression_tree_walker(node, expression_returns_set_walker,
488 /*****************************************************************************
489 * Subplan clause manipulation
490 *****************************************************************************/
494 * Recursively search for subplan nodes within a clause.
496 * If we see a SubLink node, we will return TRUE. This is only possible if
497 * the expression tree hasn't yet been transformed by subselect.c. We do not
498 * know whether the node will produce a true subplan or just an initplan,
499 * but we make the conservative assumption that it will be a subplan.
501 * Returns true if any subplan found.
504 contain_subplans(Node *clause)
506 return contain_subplans_walker(clause, NULL);
510 contain_subplans_walker(Node *node, void *context)
514 if (IsA(node, SubPlan) ||
516 return true; /* abort the tree traversal and return
518 return expression_tree_walker(node, contain_subplans_walker, context);
522 /*****************************************************************************
523 * Check clauses for mutable functions
524 *****************************************************************************/
527 * contain_mutable_functions
528 * Recursively search for mutable functions within a clause.
530 * Returns true if any mutable function (or operator implemented by a
531 * mutable function) is found. This test is needed so that we don't
532 * mistakenly think that something like "WHERE random() < 0.5" can be treated
533 * as a constant qualification.
535 * XXX we do not examine sub-selects to see if they contain uses of
536 * mutable functions. It's not real clear if that is correct or not...
539 contain_mutable_functions(Node *clause)
541 return contain_mutable_functions_walker(clause, NULL);
545 contain_mutable_functions_walker(Node *node, void *context)
549 if (IsA(node, FuncExpr))
551 FuncExpr *expr = (FuncExpr *) node;
553 if (func_volatile(expr->funcid) != PROVOLATILE_IMMUTABLE)
555 /* else fall through to check args */
557 if (IsA(node, OpExpr))
559 OpExpr *expr = (OpExpr *) node;
561 if (op_volatile(expr->opno) != PROVOLATILE_IMMUTABLE)
563 /* else fall through to check args */
565 if (IsA(node, DistinctExpr))
567 DistinctExpr *expr = (DistinctExpr *) node;
569 if (op_volatile(expr->opno) != PROVOLATILE_IMMUTABLE)
571 /* else fall through to check args */
573 if (IsA(node, ScalarArrayOpExpr))
575 ScalarArrayOpExpr *expr = (ScalarArrayOpExpr *) node;
577 if (op_volatile(expr->opno) != PROVOLATILE_IMMUTABLE)
579 /* else fall through to check args */
581 if (IsA(node, NullIfExpr))
583 NullIfExpr *expr = (NullIfExpr *) node;
585 if (op_volatile(expr->opno) != PROVOLATILE_IMMUTABLE)
587 /* else fall through to check args */
589 if (IsA(node, SubLink))
591 SubLink *sublink = (SubLink *) node;
594 foreach(opid, sublink->operOids)
596 if (op_volatile(lfirsto(opid)) != PROVOLATILE_IMMUTABLE)
599 /* else fall through to check args */
601 return expression_tree_walker(node, contain_mutable_functions_walker,
606 /*****************************************************************************
607 * Check clauses for volatile functions
608 *****************************************************************************/
611 * contain_volatile_functions
612 * Recursively search for volatile functions within a clause.
614 * Returns true if any volatile function (or operator implemented by a
615 * volatile function) is found. This test prevents invalid conversions
616 * of volatile expressions into indexscan quals.
618 * XXX we do not examine sub-selects to see if they contain uses of
619 * volatile functions. It's not real clear if that is correct or not...
622 contain_volatile_functions(Node *clause)
624 return contain_volatile_functions_walker(clause, NULL);
628 contain_volatile_functions_walker(Node *node, void *context)
632 if (IsA(node, FuncExpr))
634 FuncExpr *expr = (FuncExpr *) node;
636 if (func_volatile(expr->funcid) == PROVOLATILE_VOLATILE)
638 /* else fall through to check args */
640 if (IsA(node, OpExpr))
642 OpExpr *expr = (OpExpr *) node;
644 if (op_volatile(expr->opno) == PROVOLATILE_VOLATILE)
646 /* else fall through to check args */
648 if (IsA(node, DistinctExpr))
650 DistinctExpr *expr = (DistinctExpr *) node;
652 if (op_volatile(expr->opno) == PROVOLATILE_VOLATILE)
654 /* else fall through to check args */
656 if (IsA(node, ScalarArrayOpExpr))
658 ScalarArrayOpExpr *expr = (ScalarArrayOpExpr *) node;
660 if (op_volatile(expr->opno) == PROVOLATILE_VOLATILE)
662 /* else fall through to check args */
664 if (IsA(node, NullIfExpr))
666 NullIfExpr *expr = (NullIfExpr *) node;
668 if (op_volatile(expr->opno) == PROVOLATILE_VOLATILE)
670 /* else fall through to check args */
672 if (IsA(node, SubLink))
674 SubLink *sublink = (SubLink *) node;
677 foreach(opid, sublink->operOids)
679 if (op_volatile(lfirsto(opid)) == PROVOLATILE_VOLATILE)
682 /* else fall through to check args */
684 return expression_tree_walker(node, contain_volatile_functions_walker,
689 /*****************************************************************************
690 * Check clauses for nonstrict functions
691 *****************************************************************************/
694 * contain_nonstrict_functions
695 * Recursively search for nonstrict functions within a clause.
697 * Returns true if any nonstrict construct is found --- ie, anything that
698 * could produce non-NULL output with a NULL input.
700 * The idea here is that the caller has verified that the expression contains
701 * one or more Var or Param nodes (as appropriate for the caller's need), and
702 * now wishes to prove that the expression result will be NULL if any of these
703 * inputs is NULL. If we return false, then the proof succeeded.
706 contain_nonstrict_functions(Node *clause)
708 return contain_nonstrict_functions_walker(clause, NULL);
712 contain_nonstrict_functions_walker(Node *node, void *context)
716 if (IsA(node, Aggref))
718 /* an aggregate could return non-null with null input */
721 if (IsA(node, FuncExpr))
723 FuncExpr *expr = (FuncExpr *) node;
725 if (!func_strict(expr->funcid))
727 /* else fall through to check args */
729 if (IsA(node, OpExpr))
731 OpExpr *expr = (OpExpr *) node;
733 if (!op_strict(expr->opno))
735 /* else fall through to check args */
737 if (IsA(node, DistinctExpr))
739 /* IS DISTINCT FROM is inherently non-strict */
742 if (IsA(node, ScalarArrayOpExpr))
744 /* inherently non-strict, consider null scalar and empty array */
747 if (IsA(node, BoolExpr))
749 BoolExpr *expr = (BoolExpr *) node;
751 switch (expr->boolop)
755 /* AND, OR are inherently non-strict */
761 if (IsA(node, SubLink))
763 /* In some cases a sublink might be strict, but in general not */
766 if (IsA(node, SubPlan))
768 if (IsA(node, CaseExpr))
770 if (IsA(node, CaseWhen))
772 /* NB: ArrayExpr might someday be nonstrict */
773 if (IsA(node, CoalesceExpr))
775 if (IsA(node, NullIfExpr))
777 if (IsA(node, NullTest))
779 if (IsA(node, BooleanTest))
781 return expression_tree_walker(node, contain_nonstrict_functions_walker,
786 /*****************************************************************************
787 * Check for "pseudo-constant" clauses
788 *****************************************************************************/
791 * is_pseudo_constant_clause
792 * Detect whether a clause is "constant", ie, it contains no variables
793 * of the current query level and no uses of volatile functions.
794 * Such a clause is not necessarily a true constant: it can still contain
795 * Params and outer-level Vars, not to mention functions whose results
796 * may vary from one statement to the next. However, the clause's value
797 * will be constant over any one scan of the current query, so it can be
798 * used as an indexscan key or (if a top-level qual) can be pushed up to
799 * become a gating qual.
802 is_pseudo_constant_clause(Node *clause)
805 * We could implement this check in one recursive scan. But since the
806 * check for volatile functions is both moderately expensive and
807 * unlikely to fail, it seems better to look for Vars first and only
808 * check for volatile functions if we find no Vars.
810 if (!contain_var_clause(clause) &&
811 !contain_volatile_functions(clause))
817 * is_pseudo_constant_clause_relids
818 * Same as above, except caller already has available the var membership
819 * of the clause; this lets us avoid the contain_var_clause() scan.
822 is_pseudo_constant_clause_relids(Node *clause, Relids relids)
824 if (bms_is_empty(relids) &&
825 !contain_volatile_functions(clause))
831 * pull_constant_clauses
832 * Scan through a list of qualifications and separate "constant" quals
833 * from those that are not.
835 * Returns a list of the pseudo-constant clauses in constantQual and the
836 * remaining quals as the return value.
839 pull_constant_clauses(List *quals, List **constantQual)
845 FastListInit(&constqual);
846 FastListInit(&restqual);
850 Node *qual = (Node *) lfirst(q);
852 if (is_pseudo_constant_clause(qual))
853 FastAppend(&constqual, qual);
855 FastAppend(&restqual, qual);
857 *constantQual = FastListValue(&constqual);
858 return FastListValue(&restqual);
862 /*****************************************************************************
863 * Tests on clauses of queries
865 * Possibly this code should go someplace else, since this isn't quite the
866 * same meaning of "clause" as is used elsewhere in this module. But I can't
867 * think of a better place for it...
868 *****************************************************************************/
871 * Test whether a query uses DISTINCT ON, ie, has a distinct-list that is
872 * not the same as the set of output columns.
875 has_distinct_on_clause(Query *query)
879 /* Is there a DISTINCT clause at all? */
880 if (query->distinctClause == NIL)
884 * If the DISTINCT list contains all the nonjunk targetlist items, and
885 * nothing else (ie, no junk tlist items), then it's a simple
886 * DISTINCT, else it's DISTINCT ON. We do not require the lists to be
887 * in the same order (since the parser may have adjusted the DISTINCT
888 * clause ordering to agree with ORDER BY). Furthermore, a
889 * non-DISTINCT junk tlist item that is in the sortClause is also
890 * evidence of DISTINCT ON, since we don't allow ORDER BY on junk
891 * tlist items when plain DISTINCT is used.
893 * This code assumes that the DISTINCT list is valid, ie, all its entries
894 * match some entry of the tlist.
896 foreach(targetList, query->targetList)
898 TargetEntry *tle = (TargetEntry *) lfirst(targetList);
900 if (tle->resdom->ressortgroupref == 0)
902 if (tle->resdom->resjunk)
903 continue; /* we can ignore unsorted junk cols */
904 return true; /* definitely not in DISTINCT list */
906 if (targetIsInSortList(tle, query->distinctClause))
908 if (tle->resdom->resjunk)
909 return true; /* junk TLE in DISTINCT means DISTINCT ON */
910 /* else this TLE is okay, keep looking */
914 /* This TLE is not in DISTINCT list */
915 if (!tle->resdom->resjunk)
916 return true; /* non-junk, non-DISTINCT, so DISTINCT ON */
917 if (targetIsInSortList(tle, query->sortClause))
918 return true; /* sorted, non-distinct junk */
919 /* unsorted junk is okay, keep looking */
922 /* It's a simple DISTINCT */
927 * Test whether a query uses simple DISTINCT, ie, has a distinct-list that
928 * is the same as the set of output columns.
931 has_distinct_clause(Query *query)
933 /* Is there a DISTINCT clause at all? */
934 if (query->distinctClause == NIL)
937 /* It's DISTINCT if it's not DISTINCT ON */
938 return !has_distinct_on_clause(query);
942 /*****************************************************************************
944 * General clause-manipulating routines *
946 *****************************************************************************/
950 * (formerly clause_relids)
952 * Returns the number of different relations referenced in 'clause'.
955 NumRelids(Node *clause)
957 Relids varnos = pull_varnos(clause);
958 int result = bms_num_members(varnos);
965 * CommuteClause: commute a binary operator clause
967 * XXX the clause is destructively modified!
970 CommuteClause(OpExpr *clause)
975 /* Sanity checks: caller is at fault if these fail */
976 if (!is_opclause(clause) ||
977 length(clause->args) != 2)
978 elog(ERROR, "cannot commute non-binary-operator clause");
980 opoid = get_commutator(clause->opno);
982 if (!OidIsValid(opoid))
983 elog(ERROR, "could not find commutator for operator %u",
987 * modify the clause in-place!
989 clause->opno = opoid;
990 clause->opfuncid = InvalidOid;
991 /* opresulttype and opretset are assumed not to change */
993 temp = lfirst(clause->args);
994 lfirst(clause->args) = lsecond(clause->args);
995 lsecond(clause->args) = temp;
999 /*--------------------
1000 * eval_const_expressions
1002 * Reduce any recognizably constant subexpressions of the given
1003 * expression tree, for example "2 + 2" => "4". More interestingly,
1004 * we can reduce certain boolean expressions even when they contain
1005 * non-constant subexpressions: "x OR true" => "true" no matter what
1006 * the subexpression x is. (XXX We assume that no such subexpression
1007 * will have important side-effects, which is not necessarily a good
1008 * assumption in the presence of user-defined functions; do we need a
1009 * pg_proc flag that prevents discarding the execution of a function?)
1011 * We do understand that certain functions may deliver non-constant
1012 * results even with constant inputs, "nextval()" being the classic
1013 * example. Functions that are not marked "immutable" in pg_proc
1014 * will not be pre-evaluated here, although we will reduce their
1015 * arguments as far as possible.
1017 * We assume that the tree has already been type-checked and contains
1018 * only operators and functions that are reasonable to try to execute.
1019 *--------------------
1022 eval_const_expressions(Node *node)
1025 * The context for the mutator is a list of SQL functions being
1026 * recursively simplified, so we start with an empty list.
1028 return eval_const_expressions_mutator(node, NIL);
1032 eval_const_expressions_mutator(Node *node, List *active_fns)
1036 if (IsA(node, FuncExpr))
1038 FuncExpr *expr = (FuncExpr *) node;
1044 * Reduce constants in the FuncExpr's arguments. We know args is
1045 * either NIL or a List node, so we can call
1046 * expression_tree_mutator directly rather than recursing to self.
1048 args = (List *) expression_tree_mutator((Node *) expr->args,
1049 eval_const_expressions_mutator,
1050 (void *) active_fns);
1053 * Code for op/func reduction is pretty bulky, so split it out as
1054 * a separate function.
1056 simple = simplify_function(expr->funcid, expr->funcresulttype, args,
1058 if (simple) /* successfully simplified it */
1059 return (Node *) simple;
1062 * The expression cannot be simplified any further, so build and
1063 * return a replacement FuncExpr node using the
1064 * possibly-simplified arguments.
1066 newexpr = makeNode(FuncExpr);
1067 newexpr->funcid = expr->funcid;
1068 newexpr->funcresulttype = expr->funcresulttype;
1069 newexpr->funcretset = expr->funcretset;
1070 newexpr->funcformat = expr->funcformat;
1071 newexpr->args = args;
1072 return (Node *) newexpr;
1074 if (IsA(node, OpExpr))
1076 OpExpr *expr = (OpExpr *) node;
1082 * Reduce constants in the OpExpr's arguments. We know args is
1083 * either NIL or a List node, so we can call
1084 * expression_tree_mutator directly rather than recursing to self.
1086 args = (List *) expression_tree_mutator((Node *) expr->args,
1087 eval_const_expressions_mutator,
1088 (void *) active_fns);
1091 * Need to get OID of underlying function. Okay to scribble on
1092 * input to this extent.
1097 * Code for op/func reduction is pretty bulky, so split it out as
1098 * a separate function.
1100 simple = simplify_function(expr->opfuncid, expr->opresulttype, args,
1102 if (simple) /* successfully simplified it */
1103 return (Node *) simple;
1106 * The expression cannot be simplified any further, so build and
1107 * return a replacement OpExpr node using the possibly-simplified
1110 newexpr = makeNode(OpExpr);
1111 newexpr->opno = expr->opno;
1112 newexpr->opfuncid = expr->opfuncid;
1113 newexpr->opresulttype = expr->opresulttype;
1114 newexpr->opretset = expr->opretset;
1115 newexpr->args = args;
1116 return (Node *) newexpr;
1118 if (IsA(node, DistinctExpr))
1120 DistinctExpr *expr = (DistinctExpr *) node;
1123 bool has_null_input = false;
1124 bool all_null_input = true;
1125 bool has_nonconst_input = false;
1127 DistinctExpr *newexpr;
1130 * Reduce constants in the DistinctExpr's arguments. We know args
1131 * is either NIL or a List node, so we can call
1132 * expression_tree_mutator directly rather than recursing to self.
1134 args = (List *) expression_tree_mutator((Node *) expr->args,
1135 eval_const_expressions_mutator,
1136 (void *) active_fns);
1139 * We must do our own check for NULLs because DistinctExpr has
1140 * different results for NULL input than the underlying operator
1145 if (IsA(lfirst(arg), Const))
1147 has_null_input |= ((Const *) lfirst(arg))->constisnull;
1148 all_null_input &= ((Const *) lfirst(arg))->constisnull;
1151 has_nonconst_input = true;
1154 /* all constants? then can optimize this out */
1155 if (!has_nonconst_input)
1157 /* all nulls? then not distinct */
1159 return MAKEBOOLCONST(false, false);
1161 /* one null? then distinct */
1163 return MAKEBOOLCONST(true, false);
1165 /* otherwise try to evaluate the '=' operator */
1166 /* (NOT okay to try to inline it, though!) */
1169 * Need to get OID of underlying function. Okay to scribble
1170 * on input to this extent.
1172 set_opfuncid((OpExpr *) expr); /* rely on struct
1176 * Code for op/func reduction is pretty bulky, so split it out
1177 * as a separate function.
1179 simple = simplify_function(expr->opfuncid, expr->opresulttype,
1180 args, false, active_fns);
1181 if (simple) /* successfully simplified it */
1184 * Since the underlying operator is "=", must negate its
1187 Const *csimple = (Const *) simple;
1189 Assert(IsA(csimple, Const));
1190 csimple->constvalue =
1191 BoolGetDatum(!DatumGetBool(csimple->constvalue));
1192 return (Node *) csimple;
1197 * The expression cannot be simplified any further, so build and
1198 * return a replacement DistinctExpr node using the
1199 * possibly-simplified arguments.
1201 newexpr = makeNode(DistinctExpr);
1202 newexpr->opno = expr->opno;
1203 newexpr->opfuncid = expr->opfuncid;
1204 newexpr->opresulttype = expr->opresulttype;
1205 newexpr->opretset = expr->opretset;
1206 newexpr->args = args;
1207 return (Node *) newexpr;
1209 if (IsA(node, BoolExpr))
1211 BoolExpr *expr = (BoolExpr *) node;
1216 * Reduce constants in the BoolExpr's arguments. We know args is
1217 * either NIL or a List node, so we can call
1218 * expression_tree_mutator directly rather than recursing to self.
1220 args = (List *) expression_tree_mutator((Node *) expr->args,
1221 eval_const_expressions_mutator,
1222 (void *) active_fns);
1224 switch (expr->boolop)
1229 * OR arguments are handled as follows:
1230 * non constant: keep
1231 * FALSE: drop (does not affect result)
1232 * TRUE: force result to TRUE
1233 * NULL: keep only one
1234 * We keep one NULL input because ExecEvalOr returns NULL
1235 * when no input is TRUE and at least one is NULL.
1240 bool haveNull = false;
1241 bool forceTrue = false;
1243 FastListInit(&newargs);
1246 if (!IsA(lfirst(arg), Const))
1248 FastAppend(&newargs, lfirst(arg));
1251 const_input = (Const *) lfirst(arg);
1252 if (const_input->constisnull)
1254 else if (DatumGetBool(const_input->constvalue))
1256 /* otherwise, we can drop the constant-false input */
1260 * We could return TRUE before falling out of the
1261 * loop, but this coding method will be easier to
1262 * adapt if we ever add a notion of non-removable
1263 * functions. We'd need to check all the inputs for
1267 return MAKEBOOLCONST(true, false);
1269 FastAppend(&newargs, MAKEBOOLCONST(false, true));
1270 /* If all the inputs are FALSE, result is FALSE */
1271 if (FastListValue(&newargs) == NIL)
1272 return MAKEBOOLCONST(false, false);
1273 /* If only one nonconst-or-NULL input, it's the result */
1274 if (lnext(FastListValue(&newargs)) == NIL)
1275 return (Node *) lfirst(FastListValue(&newargs));
1276 /* Else we still need an OR node */
1277 return (Node *) make_orclause(FastListValue(&newargs));
1282 * AND arguments are handled as follows:
1283 * non constant: keep
1284 * TRUE: drop (does not affect result)
1285 * FALSE: force result to FALSE
1286 * NULL: keep only one
1287 * We keep one NULL input because ExecEvalAnd returns NULL
1288 * when no input is FALSE and at least one is NULL.
1293 bool haveNull = false;
1294 bool forceFalse = false;
1296 FastListInit(&newargs);
1299 if (!IsA(lfirst(arg), Const))
1301 FastAppend(&newargs, lfirst(arg));
1304 const_input = (Const *) lfirst(arg);
1305 if (const_input->constisnull)
1307 else if (!DatumGetBool(const_input->constvalue))
1309 /* otherwise, we can drop the constant-true input */
1313 * We could return FALSE before falling out of the
1314 * loop, but this coding method will be easier to
1315 * adapt if we ever add a notion of non-removable
1316 * functions. We'd need to check all the inputs for
1320 return MAKEBOOLCONST(false, false);
1322 FastAppend(&newargs, MAKEBOOLCONST(false, true));
1323 /* If all the inputs are TRUE, result is TRUE */
1324 if (FastListValue(&newargs) == NIL)
1325 return MAKEBOOLCONST(true, false);
1326 /* If only one nonconst-or-NULL input, it's the result */
1327 if (lnext(FastListValue(&newargs)) == NIL)
1328 return (Node *) lfirst(FastListValue(&newargs));
1329 /* Else we still need an AND node */
1330 return (Node *) make_andclause(FastListValue(&newargs));
1333 Assert(length(args) == 1);
1334 if (IsA(lfirst(args), Const))
1336 const_input = (Const *) lfirst(args);
1337 /* NOT NULL => NULL */
1338 if (const_input->constisnull)
1339 return MAKEBOOLCONST(false, true);
1340 /* otherwise pretty easy */
1341 return MAKEBOOLCONST(!DatumGetBool(const_input->constvalue),
1344 /* Else we still need a NOT node */
1345 return (Node *) make_notclause(lfirst(args));
1347 elog(ERROR, "unrecognized boolop: %d",
1348 (int) expr->boolop);
1352 if (IsA(node, SubPlan))
1355 * Return a SubPlan unchanged --- too late to do anything with it.
1357 * XXX should we ereport() here instead? Probably this routine
1358 * should never be invoked after SubPlan creation.
1362 if (IsA(node, RelabelType))
1365 * If we can simplify the input to a constant, then we don't need
1366 * the RelabelType node anymore: just change the type field of the
1367 * Const node. Otherwise, must copy the RelabelType node.
1369 RelabelType *relabel = (RelabelType *) node;
1372 arg = eval_const_expressions_mutator((Node *) relabel->arg,
1376 * If we find stacked RelabelTypes (eg, from foo :: int :: oid) we
1377 * can discard all but the top one.
1379 while (arg && IsA(arg, RelabelType))
1380 arg = (Node *) ((RelabelType *) arg)->arg;
1382 if (arg && IsA(arg, Const))
1384 Const *con = (Const *) arg;
1386 con->consttype = relabel->resulttype;
1389 * relabel's resulttypmod is discarded, which is OK for now;
1390 * if the type actually needs a runtime length coercion then
1391 * there should be a function call to do it just above this
1394 return (Node *) con;
1398 RelabelType *newrelabel = makeNode(RelabelType);
1400 newrelabel->arg = (Expr *) arg;
1401 newrelabel->resulttype = relabel->resulttype;
1402 newrelabel->resulttypmod = relabel->resulttypmod;
1403 return (Node *) newrelabel;
1406 if (IsA(node, CaseExpr))
1410 * CASE expressions can be simplified if there are constant
1411 * condition clauses:
1412 * FALSE (or NULL): drop the alternative
1413 * TRUE: drop all remaining alternatives
1414 * If the first non-FALSE alternative is a constant TRUE, we can
1415 * simplify the entire CASE to that alternative's expression.
1416 * If there are no non-FALSE alternatives, we simplify the entire
1417 * CASE to the default result (ELSE result).
1420 CaseExpr *caseexpr = (CaseExpr *) node;
1427 FastListInit(&newargs);
1428 foreach(arg, caseexpr->args)
1430 /* Simplify this alternative's condition and result */
1431 CaseWhen *casewhen = (CaseWhen *)
1432 expression_tree_mutator((Node *) lfirst(arg),
1433 eval_const_expressions_mutator,
1434 (void *) active_fns);
1436 Assert(IsA(casewhen, CaseWhen));
1437 if (casewhen->expr == NULL ||
1438 !IsA(casewhen->expr, Const))
1440 FastAppend(&newargs, casewhen);
1443 const_input = (Const *) casewhen->expr;
1444 if (const_input->constisnull ||
1445 !DatumGetBool(const_input->constvalue))
1446 continue; /* drop alternative with FALSE condition */
1449 * Found a TRUE condition. If it's the first (un-dropped)
1450 * alternative, the CASE reduces to just this alternative.
1452 if (FastListValue(&newargs) == NIL)
1453 return (Node *) casewhen->result;
1456 * Otherwise, add it to the list, and drop all the rest.
1458 FastAppend(&newargs, casewhen);
1462 /* Simplify the default result */
1463 defresult = eval_const_expressions_mutator((Node *) caseexpr->defresult,
1467 * If no non-FALSE alternatives, CASE reduces to the default
1470 if (FastListValue(&newargs) == NIL)
1472 /* Otherwise we need a new CASE node */
1473 newcase = makeNode(CaseExpr);
1474 newcase->casetype = caseexpr->casetype;
1475 newcase->arg = NULL;
1476 newcase->args = FastListValue(&newargs);
1477 newcase->defresult = (Expr *) defresult;
1478 return (Node *) newcase;
1480 if (IsA(node, ArrayExpr))
1482 ArrayExpr *arrayexpr = (ArrayExpr *) node;
1483 ArrayExpr *newarray;
1484 bool all_const = true;
1488 FastListInit(&newelems);
1489 foreach(element, arrayexpr->elements)
1493 e = eval_const_expressions_mutator((Node *) lfirst(element),
1497 FastAppend(&newelems, e);
1500 newarray = makeNode(ArrayExpr);
1501 newarray->array_typeid = arrayexpr->array_typeid;
1502 newarray->element_typeid = arrayexpr->element_typeid;
1503 newarray->elements = FastListValue(&newelems);
1504 newarray->multidims = arrayexpr->multidims;
1507 return (Node *) evaluate_expr((Expr *) newarray,
1508 newarray->array_typeid);
1510 return (Node *) newarray;
1512 if (IsA(node, CoalesceExpr))
1514 CoalesceExpr *coalesceexpr = (CoalesceExpr *) node;
1515 CoalesceExpr *newcoalesce;
1519 FastListInit(&newargs);
1520 foreach(arg, coalesceexpr->args)
1524 e = eval_const_expressions_mutator((Node *) lfirst(arg),
1528 * We can remove null constants from the list. For a non-null
1529 * constant, if it has not been preceded by any other
1530 * non-null-constant expressions then that is the result.
1534 if (((Const *) e)->constisnull)
1535 continue; /* drop null constant */
1536 if (FastListValue(&newargs) == NIL)
1537 return e; /* first expr */
1539 FastAppend(&newargs, e);
1542 newcoalesce = makeNode(CoalesceExpr);
1543 newcoalesce->coalescetype = coalesceexpr->coalescetype;
1544 newcoalesce->args = FastListValue(&newargs);
1545 return (Node *) newcoalesce;
1547 if (IsA(node, FieldSelect))
1550 * We can optimize field selection from a whole-row Var into a
1551 * simple Var. (This case won't be generated directly by the
1552 * parser, because ParseComplexProjection short-circuits it. But
1553 * it can arise while simplifying functions.) If the argument
1554 * isn't a whole-row Var, just fall through to do generic
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
1602 * function to deliver a constant result, or expand in-line the body
1603 * of the function definition (which only works for simple
1604 * SQL-language functions, but that is a common case). In either case
1605 * we need access to the function's pg_proc tuple, so fetch it just
1606 * once to use in both attempts.
1608 func_tuple = SearchSysCache(PROCOID,
1609 ObjectIdGetDatum(funcid),
1611 if (!HeapTupleIsValid(func_tuple))
1612 elog(ERROR, "cache lookup failed for function %u", 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, and
1666 * 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 all
1673 * 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 (volatiles might deliver inconsistent answers) nor to be
1709 * unreasonably expensive to evaluate. The expensiveness check not only
1710 * prevents us from doing multiple evaluations of an expensive parameter
1711 * at runtime, but is a safety value to limit growth of an expression due
1712 * to repeated inlining.
1714 * We must also beware of changing the volatility or strictness status of
1715 * functions by inlining them.
1717 * Returns a simplified expression if successful, or NULL if cannot
1718 * simplify the function.
1721 inline_function(Oid funcid, Oid result_type, List *args,
1722 HeapTuple func_tuple, List *active_fns)
1724 Form_pg_proc funcform = (Form_pg_proc) GETSTRUCT(func_tuple);
1725 char result_typtype;
1726 bool polymorphic = false;
1727 Oid argtypes[FUNC_MAX_ARGS];
1731 MemoryContext oldcxt;
1732 MemoryContext mycxt;
1733 ErrorContextCallback sqlerrcontext;
1734 List *raw_parsetree_list;
1735 List *querytree_list;
1743 * Forget it if the function is not SQL-language or has other
1744 * showstopper properties. (The nargs check is just paranoia.)
1746 if (funcform->prolang != SQLlanguageId ||
1747 funcform->prosecdef ||
1748 funcform->proretset ||
1749 funcform->pronargs != length(args))
1753 * Forget it if declared return type is not base, domain, or
1756 result_typtype = get_typtype(funcform->prorettype);
1757 if (result_typtype != 'b' &&
1758 result_typtype != 'd')
1760 if (funcform->prorettype == ANYARRAYOID ||
1761 funcform->prorettype == ANYELEMENTOID)
1767 /* Check for recursive function, and give up trying to expand if so */
1768 if (oidMember(funcid, active_fns))
1771 /* Check permission to call function (fail later, if not) */
1772 if (pg_proc_aclcheck(funcid, GetUserId(), ACL_EXECUTE) != ACLCHECK_OK)
1775 /* Check for polymorphic arguments, and substitute actual arg types */
1776 memcpy(argtypes, funcform->proargtypes, FUNC_MAX_ARGS * sizeof(Oid));
1777 for (i = 0; i < funcform->pronargs; i++)
1779 if (argtypes[i] == ANYARRAYOID ||
1780 argtypes[i] == ANYELEMENTOID)
1783 argtypes[i] = exprType((Node *) nth(i, args));
1788 * Setup error traceback support for ereport(). This is so that we
1789 * can finger the function that bad information came from.
1791 sqlerrcontext.callback = sql_inline_error_callback;
1792 sqlerrcontext.arg = funcform;
1793 sqlerrcontext.previous = error_context_stack;
1794 error_context_stack = &sqlerrcontext;
1797 * Make a temporary memory context, so that we don't leak all the
1798 * stuff that parsing might create.
1800 mycxt = AllocSetContextCreate(CurrentMemoryContext,
1802 ALLOCSET_DEFAULT_MINSIZE,
1803 ALLOCSET_DEFAULT_INITSIZE,
1804 ALLOCSET_DEFAULT_MAXSIZE);
1805 oldcxt = MemoryContextSwitchTo(mycxt);
1807 /* Fetch and parse the function body */
1808 tmp = SysCacheGetAttr(PROCOID,
1810 Anum_pg_proc_prosrc,
1813 elog(ERROR, "null prosrc for function %u", funcid);
1814 src = DatumGetCString(DirectFunctionCall1(textout, tmp));
1817 * We just do parsing and parse analysis, not rewriting, because
1818 * rewriting will not affect table-free-SELECT-only queries, which is
1819 * all that we care about. Also, we can punt as soon as we detect
1820 * more than one command in the function body.
1822 raw_parsetree_list = pg_parse_query(src);
1823 if (length(raw_parsetree_list) != 1)
1826 querytree_list = parse_analyze(lfirst(raw_parsetree_list),
1827 argtypes, funcform->pronargs);
1829 if (length(querytree_list) != 1)
1832 querytree = (Query *) lfirst(querytree_list);
1835 * The single command must be a simple "SELECT expression".
1837 if (!IsA(querytree, Query) ||
1838 querytree->commandType != CMD_SELECT ||
1839 querytree->resultRelation != 0 ||
1841 querytree->hasAggs ||
1842 querytree->hasSubLinks ||
1843 querytree->rtable ||
1844 querytree->jointree->fromlist ||
1845 querytree->jointree->quals ||
1846 querytree->groupClause ||
1847 querytree->havingQual ||
1848 querytree->distinctClause ||
1849 querytree->sortClause ||
1850 querytree->limitOffset ||
1851 querytree->limitCount ||
1852 querytree->setOperations ||
1853 length(querytree->targetList) != 1)
1856 newexpr = (Node *) ((TargetEntry *) lfirst(querytree->targetList))->expr;
1859 * If the function has any arguments declared as polymorphic types,
1860 * then it wasn't type-checked at definition time; must do so now.
1861 * (This will raise an error if wrong, but that's okay since the
1862 * function would fail at runtime anyway. Note we do not try this
1863 * until we have verified that no rewriting was needed; that's
1864 * probably not important, but let's be careful.)
1867 check_sql_fn_retval(result_type, get_typtype(result_type),
1871 * Additional validity checks on the expression. It mustn't return a
1872 * set, and it mustn't be more volatile than the surrounding function
1873 * (this is to avoid breaking hacks that involve pretending a function
1874 * is immutable when it really ain't). If the surrounding function is
1875 * declared strict, then the expression must contain only strict
1876 * constructs and must use all of the function parameters (this is
1877 * overkill, but an exact analysis is hard).
1879 if (expression_returns_set(newexpr))
1882 if (funcform->provolatile == PROVOLATILE_IMMUTABLE &&
1883 contain_mutable_functions(newexpr))
1885 else if (funcform->provolatile == PROVOLATILE_STABLE &&
1886 contain_volatile_functions(newexpr))
1889 if (funcform->proisstrict &&
1890 contain_nonstrict_functions(newexpr))
1894 * We may be able to do it; there are still checks on parameter usage
1895 * to make, but those are most easily done in combination with the
1896 * actual substitution of the inputs. So start building expression
1897 * with inputs substituted.
1899 usecounts = (int *) palloc0((funcform->pronargs + 1) * sizeof(int));
1900 newexpr = substitute_actual_parameters(newexpr, funcform->pronargs,
1903 /* Now check for parameter usage */
1907 Node *param = lfirst(arg);
1909 if (usecounts[i] == 0)
1911 /* Param not used at all: uncool if func is strict */
1912 if (funcform->proisstrict)
1915 else if (usecounts[i] != 1)
1917 /* Param used multiple times: uncool if expensive or volatile */
1921 * We define "expensive" as "contains any subplan or more than
1922 * 10 operators". Note that the subplan search has to be done
1923 * explicitly, since cost_qual_eval() will barf on unplanned
1926 if (contain_subplans(param))
1928 cost_qual_eval(&eval_cost, makeList1(param));
1929 if (eval_cost.startup + eval_cost.per_tuple >
1930 10 * cpu_operator_cost)
1934 * Check volatility last since this is more expensive than the
1937 if (contain_volatile_functions(param))
1944 * Whew --- we can make the substitution. Copy the modified
1945 * expression out of the temporary memory context, and clean up.
1947 MemoryContextSwitchTo(oldcxt);
1949 newexpr = copyObject(newexpr);
1951 MemoryContextDelete(mycxt);
1954 * Recursively try to simplify the modified expression. Here we must
1955 * add the current function to the context list of active functions.
1957 newexpr = eval_const_expressions_mutator(newexpr,
1958 lconso(funcid, active_fns));
1960 error_context_stack = sqlerrcontext.previous;
1962 return (Expr *) newexpr;
1964 /* Here if func is not inlinable: release temp memory and return NULL */
1966 MemoryContextSwitchTo(oldcxt);
1967 MemoryContextDelete(mycxt);
1968 error_context_stack = sqlerrcontext.previous;
1974 * Replace Param nodes by appropriate actual parameters
1977 substitute_actual_parameters(Node *expr, int nargs, List *args,
1980 substitute_actual_parameters_context context;
1982 context.nargs = nargs;
1983 context.args = args;
1984 context.usecounts = usecounts;
1986 return substitute_actual_parameters_mutator(expr, &context);
1990 substitute_actual_parameters_mutator(Node *node,
1991 substitute_actual_parameters_context *context)
1995 if (IsA(node, Param))
1997 Param *param = (Param *) node;
1999 if (param->paramkind != PARAM_NUM)
2000 elog(ERROR, "unexpected paramkind: %d", param->paramkind);
2001 if (param->paramid <= 0 || param->paramid > context->nargs)
2002 elog(ERROR, "invalid paramid: %d", param->paramid);
2004 /* Count usage of parameter */
2005 context->usecounts[param->paramid - 1]++;
2007 /* Select the appropriate actual arg and replace the Param with it */
2008 /* We don't need to copy at this time (it'll get done later) */
2009 return nth(param->paramid - 1, context->args);
2011 return expression_tree_mutator(node, substitute_actual_parameters_mutator,
2016 * error context callback to let us supply a call-stack traceback
2019 sql_inline_error_callback(void *arg)
2021 Form_pg_proc funcform = (Form_pg_proc) arg;
2023 errcontext("SQL function \"%s\" during inlining",
2024 NameStr(funcform->proname));
2028 * evaluate_expr: pre-evaluate a constant expression
2030 * We use the executor's routine ExecEvalExpr() to avoid duplication of
2031 * code and ensure we get the same result as the executor would get.
2034 evaluate_expr(Expr *expr, Oid result_type)
2037 ExprState *exprstate;
2038 MemoryContext oldcontext;
2042 bool resultTypByVal;
2045 * To use the executor, we need an EState.
2047 estate = CreateExecutorState();
2049 /* We can use the estate's working context to avoid memory leaks. */
2050 oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
2053 * Prepare expr for execution.
2055 exprstate = ExecPrepareExpr(expr, estate);
2060 * It is OK to use a default econtext because none of the ExecEvalExpr()
2061 * code used in this situation will use econtext. That might seem
2062 * fortuitous, but it's not so unreasonable --- a constant expression
2063 * does not depend on context, by definition, n'est ce pas?
2065 const_val = ExecEvalExprSwitchContext(exprstate,
2066 GetPerTupleExprContext(estate),
2067 &const_is_null, NULL);
2069 /* Get info needed about result datatype */
2070 get_typlenbyval(result_type, &resultTypLen, &resultTypByVal);
2072 /* Get back to outer memory context */
2073 MemoryContextSwitchTo(oldcontext);
2075 /* Must copy result out of sub-context used by expression eval */
2077 const_val = datumCopy(const_val, resultTypByVal, resultTypLen);
2079 /* Release all the junk we just created */
2080 FreeExecutorState(estate);
2083 * Make the constant result node.
2085 return (Expr *) makeConst(result_type, resultTypLen,
2086 const_val, const_is_null,
2092 * Standard expression-tree walking support
2094 * We used to have near-duplicate code in many different routines that
2095 * understood how to recurse through an expression node tree. That was
2096 * a pain to maintain, and we frequently had bugs due to some particular
2097 * routine neglecting to support a particular node type. In most cases,
2098 * these routines only actually care about certain node types, and don't
2099 * care about other types except insofar as they have to recurse through
2100 * non-primitive node types. Therefore, we now provide generic tree-walking
2101 * logic to consolidate the redundant "boilerplate" code. There are
2102 * two versions: expression_tree_walker() and expression_tree_mutator().
2105 /*--------------------
2106 * expression_tree_walker() is designed to support routines that traverse
2107 * a tree in a read-only fashion (although it will also work for routines
2108 * that modify nodes in-place but never add/delete/replace nodes).
2109 * A walker routine should look like this:
2111 * bool my_walker (Node *node, my_struct *context)
2115 * // check for nodes that special work is required for, eg:
2116 * if (IsA(node, Var))
2118 * ... do special actions for Var nodes
2120 * else if (IsA(node, ...))
2122 * ... do special actions for other node types
2124 * // for any node type not specially processed, do:
2125 * return expression_tree_walker(node, my_walker, (void *) context);
2128 * The "context" argument points to a struct that holds whatever context
2129 * information the walker routine needs --- it can be used to return data
2130 * gathered by the walker, too. This argument is not touched by
2131 * expression_tree_walker, but it is passed down to recursive sub-invocations
2132 * of my_walker. The tree walk is started from a setup routine that
2133 * fills in the appropriate context struct, calls my_walker with the top-level
2134 * node of the tree, and then examines the results.
2136 * The walker routine should return "false" to continue the tree walk, or
2137 * "true" to abort the walk and immediately return "true" to the top-level
2138 * caller. This can be used to short-circuit the traversal if the walker
2139 * has found what it came for. "false" is returned to the top-level caller
2140 * iff no invocation of the walker returned "true".
2142 * The node types handled by expression_tree_walker include all those
2143 * normally found in target lists and qualifier clauses during the planning
2144 * stage. In particular, it handles List nodes since a cnf-ified qual clause
2145 * will have List structure at the top level, and it handles TargetEntry nodes
2146 * so that a scan of a target list can be handled without additional code.
2147 * (But only the "expr" part of a TargetEntry is examined, unless the walker
2148 * chooses to process TargetEntry nodes specially.) Also, RangeTblRef,
2149 * FromExpr, JoinExpr, and SetOperationStmt nodes are handled, so that query
2150 * jointrees and setOperation trees can be processed without additional code.
2152 * expression_tree_walker will handle SubLink nodes by recursing normally into
2153 * the "lefthand" arguments (which are expressions belonging to the outer
2154 * plan). It will also call the walker on the sub-Query node; however, when
2155 * expression_tree_walker itself is called on a Query node, it does nothing
2156 * and returns "false". The net effect is that unless the walker does
2157 * something special at a Query node, sub-selects will not be visited during
2158 * an expression tree walk. This is exactly the behavior wanted in many cases
2159 * --- and for those walkers that do want to recurse into sub-selects, special
2160 * behavior is typically needed anyway at the entry to a sub-select (such as
2161 * incrementing a depth counter). A walker that wants to examine sub-selects
2162 * should include code along the lines of:
2164 * if (IsA(node, Query))
2166 * adjust context for subquery;
2167 * result = query_tree_walker((Query *) node, my_walker, context,
2168 * 0); // adjust flags as needed
2169 * restore context if needed;
2173 * query_tree_walker is a convenience routine (see below) that calls the
2174 * walker on all the expression subtrees of the given Query node.
2176 * expression_tree_walker will handle SubPlan nodes by recursing normally
2177 * into the "exprs" and "args" lists (which are expressions belonging to
2178 * the outer plan). It will not touch the completed subplan, however. Since
2179 * there is no link to the original Query, it is not possible to recurse into
2180 * subselects of an already-planned expression tree. This is OK for current
2181 * uses, but may need to be revisited in future.
2182 *--------------------
2186 expression_tree_walker(Node *node,
2193 * The walker has already visited the current node, and so we need
2194 * only recurse into any sub-nodes it has.
2196 * We assume that the walker is not interested in List nodes per se, so
2197 * when we expect a List we just recurse directly to self without
2198 * bothering to call the walker.
2202 switch (nodeTag(node))
2207 case T_CoerceToDomainValue:
2208 case T_SetToDefault:
2210 /* primitive node types with no subnodes */
2213 return walker(((Aggref *) node)->target, context);
2216 ArrayRef *aref = (ArrayRef *) node;
2218 /* recurse directly for upper/lower array index lists */
2219 if (expression_tree_walker((Node *) aref->refupperindexpr,
2222 if (expression_tree_walker((Node *) aref->reflowerindexpr,
2225 /* walker must see the refexpr and refassgnexpr, however */
2226 if (walker(aref->refexpr, context))
2228 if (walker(aref->refassgnexpr, context))
2234 FuncExpr *expr = (FuncExpr *) node;
2236 if (expression_tree_walker((Node *) expr->args,
2243 OpExpr *expr = (OpExpr *) node;
2245 if (expression_tree_walker((Node *) expr->args,
2250 case T_DistinctExpr:
2252 DistinctExpr *expr = (DistinctExpr *) node;
2254 if (expression_tree_walker((Node *) expr->args,
2259 case T_ScalarArrayOpExpr:
2261 ScalarArrayOpExpr *expr = (ScalarArrayOpExpr *) node;
2263 if (expression_tree_walker((Node *) expr->args,
2270 BoolExpr *expr = (BoolExpr *) node;
2272 if (expression_tree_walker((Node *) expr->args,
2279 SubLink *sublink = (SubLink *) node;
2281 if (expression_tree_walker((Node *) sublink->lefthand,
2286 * Also invoke the walker on the sublink's Query node, so
2287 * it can recurse into the sub-query if it wants to.
2289 return walker(sublink->subselect, context);
2294 SubPlan *subplan = (SubPlan *) node;
2296 /* recurse into the exprs list, but not into the Plan */
2297 if (expression_tree_walker((Node *) subplan->exprs,
2300 /* also examine args list */
2301 if (expression_tree_walker((Node *) subplan->args,
2307 return walker(((FieldSelect *) node)->arg, context);
2309 return walker(((RelabelType *) node)->arg, context);
2312 CaseExpr *caseexpr = (CaseExpr *) node;
2314 /* we assume walker doesn't care about CaseWhens, either */
2315 foreach(temp, caseexpr->args)
2317 CaseWhen *when = (CaseWhen *) lfirst(temp);
2319 Assert(IsA(when, CaseWhen));
2320 if (walker(when->expr, context))
2322 if (walker(when->result, context))
2325 /* caseexpr->arg should be null, but we'll check it anyway */
2326 if (walker(caseexpr->arg, context))
2328 if (walker(caseexpr->defresult, context))
2333 return walker(((ArrayExpr *) node)->elements, context);
2334 case T_CoalesceExpr:
2335 return walker(((CoalesceExpr *) node)->args, context);
2337 return walker(((NullIfExpr *) node)->args, context);
2339 return walker(((NullTest *) node)->arg, context);
2341 return walker(((BooleanTest *) node)->arg, context);
2342 case T_CoerceToDomain:
2343 return walker(((CoerceToDomain *) node)->arg, context);
2345 return walker(((TargetEntry *) node)->expr, context);
2347 /* Do nothing with a sub-Query, per discussion above */
2350 foreach(temp, (List *) node)
2352 if (walker((Node *) lfirst(temp), context))
2358 FromExpr *from = (FromExpr *) node;
2360 if (walker(from->fromlist, context))
2362 if (walker(from->quals, context))
2368 JoinExpr *join = (JoinExpr *) node;
2370 if (walker(join->larg, context))
2372 if (walker(join->rarg, context))
2374 if (walker(join->quals, context))
2378 * alias clause, using list are deemed uninteresting.
2382 case T_SetOperationStmt:
2384 SetOperationStmt *setop = (SetOperationStmt *) node;
2386 if (walker(setop->larg, context))
2388 if (walker(setop->rarg, context))
2392 case T_InClauseInfo:
2394 InClauseInfo *ininfo = (InClauseInfo *) node;
2396 if (expression_tree_walker((Node *) ininfo->sub_targetlist,
2403 * Give a useful complaint if someone uses a bare relation name
2404 * in an expression (see comments in transformColumnRef()).
2407 (errcode(ERRCODE_SYNTAX_ERROR),
2408 errmsg("relation reference \"%s\" cannot be used in an expression",
2409 ((RangeVar *) node)->relname)));
2412 elog(ERROR, "unrecognized node type: %d",
2413 (int) nodeTag(node));
2420 * query_tree_walker --- initiate a walk of a Query's expressions
2422 * This routine exists just to reduce the number of places that need to know
2423 * where all the expression subtrees of a Query are. Note it can be used
2424 * for starting a walk at top level of a Query regardless of whether the
2425 * walker intends to descend into subqueries. It is also useful for
2426 * descending into subqueries within a walker.
2428 * Some callers want to suppress visitation of certain items in the sub-Query,
2429 * typically because they need to process them specially, or don't actually
2430 * want to recurse into subqueries. This is supported by the flags argument,
2431 * which is the bitwise OR of flag values to suppress visitation of
2432 * indicated items. (More flag bits may be added as needed.)
2435 query_tree_walker(Query *query,
2442 Assert(query != NULL && IsA(query, Query));
2444 if (walker((Node *) query->targetList, context))
2446 if (walker((Node *) query->jointree, context))
2448 if (walker(query->setOperations, context))
2450 if (walker(query->havingQual, context))
2452 if (walker(query->limitOffset, context))
2454 if (walker(query->limitCount, context))
2456 if (walker(query->in_info_list, context))
2458 foreach(rt, query->rtable)
2460 RangeTblEntry *rte = (RangeTblEntry *) lfirst(rt);
2462 switch (rte->rtekind)
2469 if (!(flags & QTW_IGNORE_RT_SUBQUERIES))
2470 if (walker(rte->subquery, context))
2474 if (!(flags & QTW_IGNORE_JOINALIASES))
2475 if (walker(rte->joinaliasvars, context))
2479 if (walker(rte->funcexpr, context))
2488 /*--------------------
2489 * expression_tree_mutator() is designed to support routines that make a
2490 * modified copy of an expression tree, with some nodes being added,
2491 * removed, or replaced by new subtrees. The original tree is (normally)
2492 * not changed. Each recursion level is responsible for returning a copy of
2493 * (or appropriately modified substitute for) the subtree it is handed.
2494 * A mutator routine should look like this:
2496 * Node * my_mutator (Node *node, my_struct *context)
2500 * // check for nodes that special work is required for, eg:
2501 * if (IsA(node, Var))
2503 * ... create and return modified copy of Var node
2505 * else if (IsA(node, ...))
2507 * ... do special transformations of other node types
2509 * // for any node type not specially processed, do:
2510 * return expression_tree_mutator(node, my_mutator, (void *) context);
2513 * The "context" argument points to a struct that holds whatever context
2514 * information the mutator routine needs --- it can be used to return extra
2515 * data gathered by the mutator, too. This argument is not touched by
2516 * expression_tree_mutator, but it is passed down to recursive sub-invocations
2517 * of my_mutator. The tree walk is started from a setup routine that
2518 * fills in the appropriate context struct, calls my_mutator with the
2519 * top-level node of the tree, and does any required post-processing.
2521 * Each level of recursion must return an appropriately modified Node.
2522 * If expression_tree_mutator() is called, it will make an exact copy
2523 * of the given Node, but invoke my_mutator() to copy the sub-node(s)
2524 * of that Node. In this way, my_mutator() has full control over the
2525 * copying process but need not directly deal with expression trees
2526 * that it has no interest in.
2528 * Just as for expression_tree_walker, the node types handled by
2529 * expression_tree_mutator include all those normally found in target lists
2530 * and qualifier clauses during the planning stage.
2532 * expression_tree_mutator will handle SubLink nodes by recursing normally
2533 * into the "lefthand" arguments (which are expressions belonging to the outer
2534 * plan). It will also call the mutator on the sub-Query node; however, when
2535 * expression_tree_mutator itself is called on a Query node, it does nothing
2536 * and returns the unmodified Query node. The net effect is that unless the
2537 * mutator does something special at a Query node, sub-selects will not be
2538 * visited or modified; the original sub-select will be linked to by the new
2539 * SubLink node. Mutators that want to descend into sub-selects will usually
2540 * do so by recognizing Query nodes and calling query_tree_mutator (below).
2542 * expression_tree_mutator will handle a SubPlan node by recursing into
2543 * the "exprs" and "args" lists (which belong to the outer plan), but it
2544 * will simply copy the link to the inner plan, since that's typically what
2545 * expression tree mutators want. A mutator that wants to modify the subplan
2546 * can force appropriate behavior by recognizing SubPlan expression nodes
2547 * and doing the right thing.
2548 *--------------------
2552 expression_tree_mutator(Node *node,
2553 Node *(*mutator) (),
2557 * The mutator has already decided not to modify the current node, but
2558 * we must call the mutator for any sub-nodes.
2561 #define FLATCOPY(newnode, node, nodetype) \
2562 ( (newnode) = makeNode(nodetype), \
2563 memcpy((newnode), (node), sizeof(nodetype)) )
2565 #define CHECKFLATCOPY(newnode, node, nodetype) \
2566 ( AssertMacro(IsA((node), nodetype)), \
2567 (newnode) = makeNode(nodetype), \
2568 memcpy((newnode), (node), sizeof(nodetype)) )
2570 #define MUTATE(newfield, oldfield, fieldtype) \
2571 ( (newfield) = (fieldtype) mutator((Node *) (oldfield), context) )
2575 switch (nodeTag(node))
2580 case T_CoerceToDomainValue:
2581 case T_SetToDefault:
2583 /* primitive node types with no subnodes */
2584 return (Node *) copyObject(node);
2587 Aggref *aggref = (Aggref *) node;
2590 FLATCOPY(newnode, aggref, Aggref);
2591 MUTATE(newnode->target, aggref->target, Expr *);
2592 return (Node *) newnode;
2597 ArrayRef *arrayref = (ArrayRef *) node;
2600 FLATCOPY(newnode, arrayref, ArrayRef);
2601 MUTATE(newnode->refupperindexpr, arrayref->refupperindexpr,
2603 MUTATE(newnode->reflowerindexpr, arrayref->reflowerindexpr,
2605 MUTATE(newnode->refexpr, arrayref->refexpr,
2607 MUTATE(newnode->refassgnexpr, arrayref->refassgnexpr,
2609 return (Node *) newnode;
2614 FuncExpr *expr = (FuncExpr *) node;
2617 FLATCOPY(newnode, expr, FuncExpr);
2618 MUTATE(newnode->args, expr->args, List *);
2619 return (Node *) newnode;
2624 OpExpr *expr = (OpExpr *) node;
2627 FLATCOPY(newnode, expr, OpExpr);
2628 MUTATE(newnode->args, expr->args, List *);
2629 return (Node *) newnode;
2632 case T_DistinctExpr:
2634 DistinctExpr *expr = (DistinctExpr *) node;
2635 DistinctExpr *newnode;
2637 FLATCOPY(newnode, expr, DistinctExpr);
2638 MUTATE(newnode->args, expr->args, List *);
2639 return (Node *) newnode;
2642 case T_ScalarArrayOpExpr:
2644 ScalarArrayOpExpr *expr = (ScalarArrayOpExpr *) node;
2645 ScalarArrayOpExpr *newnode;
2647 FLATCOPY(newnode, expr, ScalarArrayOpExpr);
2648 MUTATE(newnode->args, expr->args, List *);
2649 return (Node *) newnode;
2654 BoolExpr *expr = (BoolExpr *) node;
2657 FLATCOPY(newnode, expr, BoolExpr);
2658 MUTATE(newnode->args, expr->args, List *);
2659 return (Node *) newnode;
2664 SubLink *sublink = (SubLink *) node;
2667 FLATCOPY(newnode, sublink, SubLink);
2668 MUTATE(newnode->lefthand, sublink->lefthand, List *);
2671 * Also invoke the mutator on the sublink's Query node, so
2672 * it can recurse into the sub-query if it wants to.
2674 MUTATE(newnode->subselect, sublink->subselect, Node *);
2675 return (Node *) newnode;
2680 SubPlan *subplan = (SubPlan *) node;
2683 FLATCOPY(newnode, subplan, SubPlan);
2684 /* transform exprs list */
2685 MUTATE(newnode->exprs, subplan->exprs, List *);
2686 /* transform args list (params to be passed to subplan) */
2687 MUTATE(newnode->args, subplan->args, List *);
2688 /* but not the sub-Plan itself, which is referenced as-is */
2689 return (Node *) newnode;
2694 FieldSelect *fselect = (FieldSelect *) node;
2695 FieldSelect *newnode;
2697 FLATCOPY(newnode, fselect, FieldSelect);
2698 MUTATE(newnode->arg, fselect->arg, Expr *);
2699 return (Node *) newnode;
2704 RelabelType *relabel = (RelabelType *) node;
2705 RelabelType *newnode;
2707 FLATCOPY(newnode, relabel, RelabelType);
2708 MUTATE(newnode->arg, relabel->arg, Expr *);
2709 return (Node *) newnode;
2714 CaseExpr *caseexpr = (CaseExpr *) node;
2717 FLATCOPY(newnode, caseexpr, CaseExpr);
2718 MUTATE(newnode->args, caseexpr->args, List *);
2719 /* caseexpr->arg should be null, but we'll check it anyway */
2720 MUTATE(newnode->arg, caseexpr->arg, Expr *);
2721 MUTATE(newnode->defresult, caseexpr->defresult, Expr *);
2722 return (Node *) newnode;
2727 CaseWhen *casewhen = (CaseWhen *) node;
2730 FLATCOPY(newnode, casewhen, CaseWhen);
2731 MUTATE(newnode->expr, casewhen->expr, Expr *);
2732 MUTATE(newnode->result, casewhen->result, Expr *);
2733 return (Node *) newnode;
2738 ArrayExpr *arrayexpr = (ArrayExpr *) node;
2741 FLATCOPY(newnode, arrayexpr, ArrayExpr);
2742 MUTATE(newnode->elements, arrayexpr->elements, List *);
2743 return (Node *) newnode;
2746 case T_CoalesceExpr:
2748 CoalesceExpr *coalesceexpr = (CoalesceExpr *) node;
2749 CoalesceExpr *newnode;
2751 FLATCOPY(newnode, coalesceexpr, CoalesceExpr);
2752 MUTATE(newnode->args, coalesceexpr->args, List *);
2753 return (Node *) newnode;
2758 NullIfExpr *expr = (NullIfExpr *) node;
2759 NullIfExpr *newnode;
2761 FLATCOPY(newnode, expr, NullIfExpr);
2762 MUTATE(newnode->args, expr->args, List *);
2763 return (Node *) newnode;
2768 NullTest *ntest = (NullTest *) node;
2771 FLATCOPY(newnode, ntest, NullTest);
2772 MUTATE(newnode->arg, ntest->arg, Expr *);
2773 return (Node *) newnode;
2778 BooleanTest *btest = (BooleanTest *) node;
2779 BooleanTest *newnode;
2781 FLATCOPY(newnode, btest, BooleanTest);
2782 MUTATE(newnode->arg, btest->arg, Expr *);
2783 return (Node *) newnode;
2786 case T_CoerceToDomain:
2788 CoerceToDomain *ctest = (CoerceToDomain *) node;
2789 CoerceToDomain *newnode;
2791 FLATCOPY(newnode, ctest, CoerceToDomain);
2792 MUTATE(newnode->arg, ctest->arg, Expr *);
2793 return (Node *) newnode;
2799 * We mutate the expression, but not the resdom, by
2802 TargetEntry *targetentry = (TargetEntry *) node;
2803 TargetEntry *newnode;
2805 FLATCOPY(newnode, targetentry, TargetEntry);
2806 MUTATE(newnode->expr, targetentry->expr, Expr *);
2807 return (Node *) newnode;
2811 /* Do nothing with a sub-Query, per discussion above */
2816 * We assume the mutator isn't interested in the list
2817 * nodes per se, so just invoke it on each list element.
2818 * NOTE: this would fail badly on a list with integer
2821 FastList resultlist;
2824 FastListInit(&resultlist);
2825 foreach(temp, (List *) node)
2827 FastAppend(&resultlist,
2828 mutator((Node *) lfirst(temp), context));
2830 return (Node *) FastListValue(&resultlist);
2835 FromExpr *from = (FromExpr *) node;
2838 FLATCOPY(newnode, from, FromExpr);
2839 MUTATE(newnode->fromlist, from->fromlist, List *);
2840 MUTATE(newnode->quals, from->quals, Node *);
2841 return (Node *) newnode;
2846 JoinExpr *join = (JoinExpr *) node;
2849 FLATCOPY(newnode, join, JoinExpr);
2850 MUTATE(newnode->larg, join->larg, Node *);
2851 MUTATE(newnode->rarg, join->rarg, Node *);
2852 MUTATE(newnode->quals, join->quals, Node *);
2853 /* We do not mutate alias or using by default */
2854 return (Node *) newnode;
2857 case T_SetOperationStmt:
2859 SetOperationStmt *setop = (SetOperationStmt *) node;
2860 SetOperationStmt *newnode;
2862 FLATCOPY(newnode, setop, SetOperationStmt);
2863 MUTATE(newnode->larg, setop->larg, Node *);
2864 MUTATE(newnode->rarg, setop->rarg, Node *);
2865 return (Node *) newnode;
2868 case T_InClauseInfo:
2870 InClauseInfo *ininfo = (InClauseInfo *) node;
2871 InClauseInfo *newnode;
2873 FLATCOPY(newnode, ininfo, InClauseInfo);
2874 MUTATE(newnode->sub_targetlist, ininfo->sub_targetlist, List *);
2875 return (Node *) newnode;
2880 * Give a useful complaint if someone uses a bare relation name
2881 * in an expression (see comments in transformColumnRef()).
2884 (errcode(ERRCODE_SYNTAX_ERROR),
2885 errmsg("relation reference \"%s\" cannot be used in an expression",
2886 ((RangeVar *) node)->relname)));
2889 elog(ERROR, "unrecognized node type: %d",
2890 (int) nodeTag(node));
2893 /* can't get here, but keep compiler happy */
2899 * query_tree_mutator --- initiate modification of a Query's expressions
2901 * This routine exists just to reduce the number of places that need to know
2902 * where all the expression subtrees of a Query are. Note it can be used
2903 * for starting a walk at top level of a Query regardless of whether the
2904 * mutator intends to descend into subqueries. It is also useful for
2905 * descending into subqueries within a mutator.
2907 * Some callers want to suppress mutating of certain items in the Query,
2908 * typically because they need to process them specially, or don't actually
2909 * want to recurse into subqueries. This is supported by the flags argument,
2910 * which is the bitwise OR of flag values to suppress mutating of
2911 * indicated items. (More flag bits may be added as needed.)
2913 * Normally the Query node itself is copied, but some callers want it to be
2914 * modified in-place; they must pass QTW_DONT_COPY_QUERY in flags. All
2915 * modified substructure is safely copied in any case.
2918 query_tree_mutator(Query *query,
2919 Node *(*mutator) (),
2926 Assert(query != NULL && IsA(query, Query));
2928 if (!(flags & QTW_DONT_COPY_QUERY))
2932 FLATCOPY(newquery, query, Query);
2936 MUTATE(query->targetList, query->targetList, List *);
2937 MUTATE(query->jointree, query->jointree, FromExpr *);
2938 MUTATE(query->setOperations, query->setOperations, Node *);
2939 MUTATE(query->havingQual, query->havingQual, Node *);
2940 MUTATE(query->limitOffset, query->limitOffset, Node *);
2941 MUTATE(query->limitCount, query->limitCount, Node *);
2942 MUTATE(query->in_info_list, query->in_info_list, List *);
2943 FastListInit(&newrt);
2944 foreach(rt, query->rtable)
2946 RangeTblEntry *rte = (RangeTblEntry *) lfirst(rt);
2947 RangeTblEntry *newrte;
2949 FLATCOPY(newrte, rte, RangeTblEntry);
2950 switch (rte->rtekind)
2954 /* we don't bother to copy eref, aliases, etc; OK? */
2957 if (!(flags & QTW_IGNORE_RT_SUBQUERIES))
2959 CHECKFLATCOPY(newrte->subquery, rte->subquery, Query);
2960 MUTATE(newrte->subquery, newrte->subquery, Query *);
2964 if (!(flags & QTW_IGNORE_JOINALIASES))
2966 MUTATE(newrte->joinaliasvars, rte->joinaliasvars, List *);
2970 MUTATE(newrte->funcexpr, rte->funcexpr, Node *);
2973 FastAppend(&newrt, newrte);
2975 query->rtable = FastListValue(&newrt);
2980 * query_or_expression_tree_walker --- hybrid form
2982 * This routine will invoke query_tree_walker if called on a Query node,
2983 * else will invoke the walker directly. This is a useful way of starting
2984 * the recursion when the walker's normal change of state is not appropriate
2985 * for the outermost Query node.
2988 query_or_expression_tree_walker(Node *node,
2993 if (node && IsA(node, Query))
2994 return query_tree_walker((Query *) node,
2999 return walker(node, context);
3003 * query_or_expression_tree_mutator --- hybrid form
3005 * This routine will invoke query_tree_mutator if called on a Query node,
3006 * else will invoke the mutator directly. This is a useful way of starting
3007 * the recursion when the mutator's normal change of state is not appropriate
3008 * for the outermost Query node.
3011 query_or_expression_tree_mutator(Node *node,
3012 Node *(*mutator) (),
3016 if (node && IsA(node, Query))
3017 return (Node *) query_tree_mutator((Query *) node,
3022 return mutator(node, context);