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.116 2002/12/12 15:49:32 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_operator.h"
24 #include "catalog/pg_proc.h"
25 #include "catalog/pg_type.h"
26 #include "executor/executor.h"
27 #include "miscadmin.h"
28 #include "nodes/makefuncs.h"
29 #include "nodes/nodeFuncs.h"
30 #include "optimizer/clauses.h"
31 #include "optimizer/tlist.h"
32 #include "optimizer/var.h"
33 #include "parser/analyze.h"
34 #include "parser/parsetree.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))
52 } check_subplans_for_ungrouped_vars_context;
59 } substitute_actual_parameters_context;
61 static bool contain_agg_clause_walker(Node *node, void *context);
62 static bool contain_distinct_agg_clause_walker(Node *node, void *context);
63 static bool pull_agg_clause_walker(Node *node, List **listptr);
64 static bool expression_returns_set_walker(Node *node, void *context);
65 static bool contain_subplans_walker(Node *node, void *context);
66 static bool pull_subplans_walker(Node *node, List **listptr);
67 static bool check_subplans_for_ungrouped_vars_walker(Node *node,
68 check_subplans_for_ungrouped_vars_context *context);
69 static bool contain_mutable_functions_walker(Node *node, void *context);
70 static bool contain_volatile_functions_walker(Node *node, void *context);
71 static bool contain_nonstrict_functions_walker(Node *node, void *context);
72 static Node *eval_const_expressions_mutator(Node *node, List *active_fns);
73 static Expr *simplify_function(Oid funcid, List *args, bool allow_inline,
75 static Expr *evaluate_function(Oid funcid, List *args, HeapTuple func_tuple);
76 static Expr *inline_function(Oid funcid, List *args, HeapTuple func_tuple,
78 static Node *substitute_actual_parameters(Node *expr, int nargs, List *args,
80 static Node *substitute_actual_parameters_mutator(Node *node,
81 substitute_actual_parameters_context *context);
84 /*****************************************************************************
85 * OPERATOR clause functions
86 *****************************************************************************/
90 * Creates an operator clause given its operator info, left operand,
91 * and right operand (pass NULL to create single-operand clause).
94 make_opclause(Oid opno, Oid opresulttype, bool opretset,
95 Expr *leftop, Expr *rightop)
97 OpExpr *expr = makeNode(OpExpr);
100 expr->opfuncid = InvalidOid;
101 expr->opresulttype = opresulttype;
102 expr->opretset = opretset;
104 expr->args = makeList2(leftop, rightop);
106 expr->args = makeList1(leftop);
107 return (Expr *) expr;
113 * Returns the left operand of a clause of the form (op expr expr)
116 * NB: for historical reasons, the result is declared Var *, even
117 * though many callers can cope with results that are not Vars.
118 * The result really ought to be declared Expr * or Node *.
121 get_leftop(Expr *clause)
123 OpExpr *expr = (OpExpr *) clause;
125 if (expr->args != NULL)
126 return lfirst(expr->args);
134 * Returns the right operand in a clause of the form (op expr expr).
135 * NB: result will be NULL if applied to a unary op clause.
138 get_rightop(Expr *clause)
140 OpExpr *expr = (OpExpr *) clause;
142 if (expr->args != NULL && lnext(expr->args) != NULL)
143 return lfirst(lnext(expr->args));
148 /*****************************************************************************
149 * FUNCTION clause functions
150 *****************************************************************************/
154 * Creates a function clause given its function info and argument list.
157 make_funcclause(Oid funcid, Oid funcresulttype, bool funcretset,
158 CoercionForm funcformat, List *funcargs)
160 FuncExpr *expr = makeNode(FuncExpr);
162 expr->funcid = funcid;
163 expr->funcresulttype = funcresulttype;
164 expr->funcretset = funcretset;
165 expr->funcformat = funcformat;
166 expr->args = funcargs;
167 return (Expr *) expr;
170 /*****************************************************************************
171 * NOT clause functions
172 *****************************************************************************/
177 * Returns t iff this is a 'not' clause: (NOT expr).
180 not_clause(Node *clause)
182 return (clause != NULL &&
183 IsA(clause, BoolExpr) &&
184 ((BoolExpr *) clause)->boolop == NOT_EXPR);
190 * Create a 'not' clause given the expression to be negated.
193 make_notclause(Expr *notclause)
195 BoolExpr *expr = makeNode(BoolExpr);
197 expr->boolop = NOT_EXPR;
198 expr->args = makeList1(notclause);
199 return (Expr *) expr;
205 * Retrieve the clause within a 'not' clause
208 get_notclausearg(Expr *notclause)
210 return lfirst(((BoolExpr *) notclause)->args);
213 /*****************************************************************************
214 * OR clause functions
215 *****************************************************************************/
220 * Returns t iff the clause is an 'or' clause: (OR { expr }).
223 or_clause(Node *clause)
225 return (clause != NULL &&
226 IsA(clause, BoolExpr) &&
227 ((BoolExpr *) clause)->boolop == OR_EXPR);
233 * Creates an 'or' clause given a list of its subclauses.
236 make_orclause(List *orclauses)
238 BoolExpr *expr = makeNode(BoolExpr);
240 expr->boolop = OR_EXPR;
241 expr->args = orclauses;
242 return (Expr *) expr;
245 /*****************************************************************************
246 * AND clause functions
247 *****************************************************************************/
253 * Returns t iff its argument is an 'and' clause: (AND { expr }).
256 and_clause(Node *clause)
258 return (clause != NULL &&
259 IsA(clause, BoolExpr) &&
260 ((BoolExpr *) clause)->boolop == AND_EXPR);
266 * Creates an 'and' clause given a list of its subclauses.
269 make_andclause(List *andclauses)
271 BoolExpr *expr = makeNode(BoolExpr);
273 expr->boolop = AND_EXPR;
274 expr->args = andclauses;
275 return (Expr *) expr;
281 * Variant of make_andclause for ANDing two qual conditions together.
282 * Qual conditions have the property that a NULL nodetree is interpreted
286 make_and_qual(Node *qual1, Node *qual2)
292 return (Node *) make_andclause(makeList2(qual1, qual2));
296 * Sometimes (such as in the result of canonicalize_qual or the input of
297 * ExecQual), we use lists of expression nodes with implicit AND semantics.
299 * These functions convert between an AND-semantics expression list and the
300 * ordinary representation of a boolean expression.
302 * Note that an empty list is considered equivalent to TRUE.
305 make_ands_explicit(List *andclauses)
307 if (andclauses == NIL)
308 return (Expr *) MAKEBOOLCONST(true, false);
309 else if (lnext(andclauses) == NIL)
310 return (Expr *) lfirst(andclauses);
312 return make_andclause(andclauses);
316 make_ands_implicit(Expr *clause)
319 * NB: because the parser sets the qual field to NULL in a query that
320 * has no WHERE clause, we must consider a NULL input clause as TRUE,
321 * even though one might more reasonably think it FALSE. Grumble. If
322 * this causes trouble, consider changing the parser's behavior.
325 return NIL; /* NULL -> NIL list == TRUE */
326 else if (and_clause((Node *) clause))
327 return ((BoolExpr *) clause)->args;
328 else if (IsA(clause, Const) &&
329 !((Const *) clause)->constisnull &&
330 DatumGetBool(((Const *) clause)->constvalue))
331 return NIL; /* constant TRUE input -> NIL list */
333 return makeList1(clause);
337 /*****************************************************************************
338 * Aggregate-function clause manipulation
339 *****************************************************************************/
343 * Recursively search for Aggref nodes within a clause.
345 * Returns true if any aggregate found.
348 contain_agg_clause(Node *clause)
350 return contain_agg_clause_walker(clause, NULL);
354 contain_agg_clause_walker(Node *node, void *context)
358 if (IsA(node, Aggref))
359 return true; /* abort the tree traversal and return
361 return expression_tree_walker(node, contain_agg_clause_walker, context);
365 * contain_distinct_agg_clause
366 * Recursively search for DISTINCT Aggref nodes within a clause.
368 * Returns true if any DISTINCT aggregate found.
371 contain_distinct_agg_clause(Node *clause)
373 return contain_distinct_agg_clause_walker(clause, NULL);
377 contain_distinct_agg_clause_walker(Node *node, void *context)
381 if (IsA(node, Aggref))
383 if (((Aggref *) node)->aggdistinct)
384 return true; /* abort the tree traversal and return
387 return expression_tree_walker(node, contain_distinct_agg_clause_walker, context);
392 * Recursively pulls all Aggref nodes from an expression tree.
394 * Returns list of Aggref nodes found. Note the nodes themselves are not
395 * copied, only referenced.
397 * Note: this also checks for nested aggregates, which are an error.
400 pull_agg_clause(Node *clause)
404 pull_agg_clause_walker(clause, &result);
409 pull_agg_clause_walker(Node *node, List **listptr)
413 if (IsA(node, Aggref))
415 *listptr = lappend(*listptr, node);
418 * Complain if the aggregate's argument contains any aggregates;
419 * nested agg functions are semantically nonsensical.
421 if (contain_agg_clause((Node *) ((Aggref *) node)->target))
422 elog(ERROR, "Aggregate function calls may not be nested");
425 * Having checked that, we need not recurse into the argument.
429 return expression_tree_walker(node, pull_agg_clause_walker,
434 /*****************************************************************************
435 * Support for expressions returning sets
436 *****************************************************************************/
439 * expression_returns_set
440 * Test whether an expression returns a set result.
442 * Because we use expression_tree_walker(), this can also be applied to
443 * whole targetlists; it'll produce TRUE if any one of the tlist items
447 expression_returns_set(Node *clause)
449 return expression_returns_set_walker(clause, NULL);
453 expression_returns_set_walker(Node *node, void *context)
457 if (IsA(node, FuncExpr))
459 FuncExpr *expr = (FuncExpr *) node;
461 if (expr->funcretset)
463 /* else fall through to check args */
465 if (IsA(node, OpExpr))
467 OpExpr *expr = (OpExpr *) node;
471 /* else fall through to check args */
473 if (IsA(node, DistinctExpr))
475 DistinctExpr *expr = (DistinctExpr *) node;
479 /* else fall through to check args */
482 /* Avoid recursion for some cases that can't return a set */
483 if (IsA(node, BoolExpr))
485 if (IsA(node, Aggref))
487 if (IsA(node, SubLink))
489 if (IsA(node, SubPlanExpr))
492 return expression_tree_walker(node, expression_returns_set_walker,
496 /*****************************************************************************
497 * Subplan clause manipulation
498 *****************************************************************************/
502 * Recursively search for subplan nodes within a clause.
504 * If we see a SubLink node, we will return TRUE. This is only possible if
505 * the expression tree hasn't yet been transformed by subselect.c. We do not
506 * know whether the node will produce a true subplan or just an initplan,
507 * but we make the conservative assumption that it will be a subplan.
509 * Returns true if any subplan found.
512 contain_subplans(Node *clause)
514 return contain_subplans_walker(clause, NULL);
518 contain_subplans_walker(Node *node, void *context)
522 if (IsA(node, SubPlanExpr) ||
524 return true; /* abort the tree traversal and return
526 return expression_tree_walker(node, contain_subplans_walker, context);
531 * Recursively pulls all subplans from an expression tree.
533 * Returns list of SubPlanExpr nodes found. Note the nodes themselves
534 * are not copied, only referenced.
537 pull_subplans(Node *clause)
541 pull_subplans_walker(clause, &result);
546 pull_subplans_walker(Node *node, List **listptr)
550 if (is_subplan(node))
552 *listptr = lappend(*listptr, node);
553 /* fall through to check args to subplan */
555 return expression_tree_walker(node, pull_subplans_walker,
560 * check_subplans_for_ungrouped_vars
561 * Check for subplans that are being passed ungrouped variables as
562 * parameters; generate an error message if any are found.
564 * In most contexts, ungrouped variables will be detected by the parser (see
565 * parse_agg.c, check_ungrouped_columns()). But that routine currently does
566 * not check subplans, because the necessary info is not computed until the
567 * planner runs. So we do it here, after we have processed sublinks into
568 * subplans. This ought to be cleaned up someday.
570 * A deficiency in this scheme is that any outer reference var must be
571 * grouped by itself; we don't recognize groupable expressions within
572 * subselects. For example, consider
574 * (SELECT x FROM bar where y = (foo.a + foo.b))
577 * This query will be rejected although it could be allowed.
580 check_subplans_for_ungrouped_vars(Query *query)
582 check_subplans_for_ungrouped_vars_context context;
585 context.query = query;
588 * Build a list of the acceptable GROUP BY expressions for use in the
589 * walker (to avoid repeated scans of the targetlist within the
590 * recursive routine).
592 context.groupClauses = NIL;
593 foreach(gl, query->groupClause)
595 GroupClause *grpcl = lfirst(gl);
598 expr = get_sortgroupclause_expr(grpcl, query->targetList);
599 context.groupClauses = lcons(expr, context.groupClauses);
603 * Recursively scan the targetlist and the HAVING clause. WHERE and
604 * JOIN/ON conditions are not examined, since they are evaluated
607 check_subplans_for_ungrouped_vars_walker((Node *) query->targetList,
609 check_subplans_for_ungrouped_vars_walker(query->havingQual,
612 freeList(context.groupClauses);
616 check_subplans_for_ungrouped_vars_walker(Node *node,
617 check_subplans_for_ungrouped_vars_context *context)
623 if (IsA(node, Const) ||
625 return false; /* constants are always acceptable */
628 * If we find an aggregate function, do not recurse into its
629 * arguments. Subplans invoked within aggregate calls are allowed to
630 * receive ungrouped variables. (This test and the next one should
631 * match the logic in parse_agg.c's check_ungrouped_columns().)
633 if (IsA(node, Aggref))
637 * Check to see if subexpression as a whole matches any GROUP BY item.
638 * We need to do this at every recursion level so that we recognize
639 * GROUPed-BY expressions before reaching variables within them.
641 foreach(gl, context->groupClauses)
643 if (equal(node, lfirst(gl)))
644 return false; /* acceptable, do not descend more */
648 * We can ignore Vars other than in subplan args lists, since the
649 * parser already checked 'em.
651 if (is_subplan(node))
654 * The args list of the subplan node represents attributes from
655 * outside passed into the sublink.
659 foreach(t, ((SubPlanExpr *) node)->args)
661 Node *thisarg = lfirst(t);
663 bool contained_in_group_clause;
666 * We do not care about args that are not local variables;
667 * params or outer-level vars are not our responsibility to
668 * check. (The outer-level query passing them to us needs to
671 if (!IsA(thisarg, Var))
673 var = (Var *) thisarg;
674 if (var->varlevelsup > 0)
678 * Else, see if it is a grouping column.
680 contained_in_group_clause = false;
681 foreach(gl, context->groupClauses)
683 if (equal(thisarg, lfirst(gl)))
685 contained_in_group_clause = true;
690 if (!contained_in_group_clause)
692 /* Found an ungrouped argument. Complain. */
696 Assert(var->varno > 0 &&
697 (int) var->varno <= length(context->query->rtable));
698 rte = rt_fetch(var->varno, context->query->rtable);
699 attname = get_rte_attribute_name(rte, var->varattno);
700 elog(ERROR, "Sub-SELECT uses un-GROUPed attribute %s.%s from outer query",
701 rte->eref->aliasname, attname);
705 return expression_tree_walker(node,
706 check_subplans_for_ungrouped_vars_walker,
711 /*****************************************************************************
712 * Check clauses for mutable functions
713 *****************************************************************************/
716 * contain_mutable_functions
717 * Recursively search for mutable functions within a clause.
719 * Returns true if any mutable function (or operator implemented by a
720 * mutable function) is found. This test is needed so that we don't
721 * mistakenly think that something like "WHERE random() < 0.5" can be treated
722 * as a constant qualification.
724 * XXX we do not examine sublinks/subplans to see if they contain uses of
725 * mutable functions. It's not real clear if that is correct or not...
728 contain_mutable_functions(Node *clause)
730 return contain_mutable_functions_walker(clause, NULL);
734 contain_mutable_functions_walker(Node *node, void *context)
738 if (IsA(node, FuncExpr))
740 FuncExpr *expr = (FuncExpr *) node;
742 if (func_volatile(expr->funcid) != PROVOLATILE_IMMUTABLE)
744 /* else fall through to check args */
746 if (IsA(node, OpExpr))
748 OpExpr *expr = (OpExpr *) node;
750 if (op_volatile(expr->opno) != PROVOLATILE_IMMUTABLE)
752 /* else fall through to check args */
754 if (IsA(node, DistinctExpr))
756 DistinctExpr *expr = (DistinctExpr *) node;
758 if (op_volatile(expr->opno) != PROVOLATILE_IMMUTABLE)
760 /* else fall through to check args */
762 return expression_tree_walker(node, contain_mutable_functions_walker,
767 /*****************************************************************************
768 * Check clauses for volatile functions
769 *****************************************************************************/
772 * contain_volatile_functions
773 * Recursively search for volatile functions within a clause.
775 * Returns true if any volatile function (or operator implemented by a
776 * volatile function) is found. This test prevents invalid conversions
777 * of volatile expressions into indexscan quals.
779 * XXX we do not examine sublinks/subplans to see if they contain uses of
780 * volatile functions. It's not real clear if that is correct or not...
783 contain_volatile_functions(Node *clause)
785 return contain_volatile_functions_walker(clause, NULL);
789 contain_volatile_functions_walker(Node *node, void *context)
793 if (IsA(node, FuncExpr))
795 FuncExpr *expr = (FuncExpr *) node;
797 if (func_volatile(expr->funcid) == PROVOLATILE_VOLATILE)
799 /* else fall through to check args */
801 if (IsA(node, OpExpr))
803 OpExpr *expr = (OpExpr *) node;
805 if (op_volatile(expr->opno) == PROVOLATILE_VOLATILE)
807 /* else fall through to check args */
809 if (IsA(node, DistinctExpr))
811 DistinctExpr *expr = (DistinctExpr *) node;
813 if (op_volatile(expr->opno) == PROVOLATILE_VOLATILE)
815 /* else fall through to check args */
817 return expression_tree_walker(node, contain_volatile_functions_walker,
822 /*****************************************************************************
823 * Check clauses for nonstrict functions
824 *****************************************************************************/
827 * contain_nonstrict_functions
828 * Recursively search for nonstrict functions within a clause.
830 * Returns true if any nonstrict construct is found --- ie, anything that
831 * could produce non-NULL output with a NULL input.
833 * XXX we do not examine sublinks/subplans to see if they contain uses of
834 * nonstrict functions. It's not real clear if that is correct or not...
835 * for the current usage it does not matter, since inline_function()
836 * rejects cases with sublinks.
839 contain_nonstrict_functions(Node *clause)
841 return contain_nonstrict_functions_walker(clause, NULL);
845 contain_nonstrict_functions_walker(Node *node, void *context)
849 if (IsA(node, FuncExpr))
851 FuncExpr *expr = (FuncExpr *) node;
853 if (!func_strict(expr->funcid))
855 /* else fall through to check args */
857 if (IsA(node, OpExpr))
859 OpExpr *expr = (OpExpr *) node;
861 if (!op_strict(expr->opno))
863 /* else fall through to check args */
865 if (IsA(node, DistinctExpr))
867 /* IS DISTINCT FROM is inherently non-strict */
870 if (IsA(node, BoolExpr))
872 BoolExpr *expr = (BoolExpr *) node;
874 switch (expr->boolop)
878 /* OR, AND are inherently non-strict */
884 if (IsA(node, CaseExpr))
886 if (IsA(node, NullTest))
888 if (IsA(node, BooleanTest))
890 return expression_tree_walker(node, contain_nonstrict_functions_walker,
895 /*****************************************************************************
896 * Check for "pseudo-constant" clauses
897 *****************************************************************************/
900 * is_pseudo_constant_clause
901 * Detect whether a clause is "constant", ie, it contains no variables
902 * of the current query level and no uses of volatile functions.
903 * Such a clause is not necessarily a true constant: it can still contain
904 * Params and outer-level Vars, not to mention functions whose results
905 * may vary from one statement to the next. However, the clause's value
906 * will be constant over any one scan of the current query, so it can be
907 * used as an indexscan key or (if a top-level qual) can be pushed up to
908 * become a gating qual.
911 is_pseudo_constant_clause(Node *clause)
914 * We could implement this check in one recursive scan. But since the
915 * check for volatile functions is both moderately expensive and
916 * unlikely to fail, it seems better to look for Vars first and only
917 * check for volatile functions if we find no Vars.
919 if (!contain_var_clause(clause) &&
920 !contain_volatile_functions(clause))
926 * pull_constant_clauses
927 * Scan through a list of qualifications and separate "constant" quals
928 * from those that are not.
930 * Returns a list of the pseudo-constant clauses in constantQual and the
931 * remaining quals as the return value.
934 pull_constant_clauses(List *quals, List **constantQual)
936 List *constqual = NIL;
937 List *restqual = NIL;
942 Node *qual = (Node *) lfirst(q);
944 if (is_pseudo_constant_clause(qual))
945 constqual = lappend(constqual, qual);
947 restqual = lappend(restqual, qual);
949 *constantQual = constqual;
954 /*****************************************************************************
955 * Tests on clauses of queries
957 * Possibly this code should go someplace else, since this isn't quite the
958 * same meaning of "clause" as is used elsewhere in this module. But I can't
959 * think of a better place for it...
960 *****************************************************************************/
963 * Test whether a sort/group reference value appears in the given list of
964 * SortClause (or GroupClause) nodes.
966 * Because GroupClause is typedef'd as SortClause, either kind of
967 * node list can be passed without casting.
970 sortgroupref_is_present(Index sortgroupref, List *clauselist)
974 foreach(clause, clauselist)
976 SortClause *scl = (SortClause *) lfirst(clause);
978 if (scl->tleSortGroupRef == sortgroupref)
985 * Test whether a query uses DISTINCT ON, ie, has a distinct-list that is
986 * not the same as the set of output columns.
989 has_distinct_on_clause(Query *query)
993 /* Is there a DISTINCT clause at all? */
994 if (query->distinctClause == NIL)
998 * If the DISTINCT list contains all the nonjunk targetlist items, and
999 * nothing else (ie, no junk tlist items), then it's a simple
1000 * DISTINCT, else it's DISTINCT ON. We do not require the lists to be
1001 * in the same order (since the parser may have adjusted the DISTINCT
1002 * clause ordering to agree with ORDER BY). Furthermore, a
1003 * non-DISTINCT junk tlist item that is in the sortClause is also
1004 * evidence of DISTINCT ON, since we don't allow ORDER BY on junk
1005 * tlist items when plain DISTINCT is used.
1007 * This code assumes that the DISTINCT list is valid, ie, all its entries
1008 * match some entry of the tlist.
1010 foreach(targetList, query->targetList)
1012 TargetEntry *tle = (TargetEntry *) lfirst(targetList);
1013 Index ressortgroupref = tle->resdom->ressortgroupref;
1015 if (ressortgroupref == 0)
1017 if (tle->resdom->resjunk)
1018 continue; /* we can ignore unsorted junk cols */
1019 return true; /* definitely not in DISTINCT list */
1021 if (sortgroupref_is_present(ressortgroupref, query->distinctClause))
1023 if (tle->resdom->resjunk)
1024 return true; /* junk TLE in DISTINCT means DISTINCT ON */
1025 /* else this TLE is okay, keep looking */
1029 /* This TLE is not in DISTINCT list */
1030 if (!tle->resdom->resjunk)
1031 return true; /* non-junk, non-DISTINCT, so DISTINCT ON */
1032 if (sortgroupref_is_present(ressortgroupref, query->sortClause))
1033 return true; /* sorted, non-distinct junk */
1034 /* unsorted junk is okay, keep looking */
1037 /* It's a simple DISTINCT */
1042 /*****************************************************************************
1044 * General clause-manipulating routines *
1046 *****************************************************************************/
1049 * clause_get_relids_vars
1050 * Retrieves distinct relids and vars appearing within a clause.
1052 * '*relids' is set to an integer list of all distinct "varno"s appearing
1053 * in Vars within the clause.
1054 * '*vars' is set to a list of all distinct Vars appearing within the clause.
1055 * Var nodes are considered distinct if they have different varno
1056 * or varattno values. If there are several occurrences of the same
1057 * varno/varattno, you get a randomly chosen one...
1059 * Note that upper-level vars are ignored, since they normally will
1060 * become Params with respect to this query level.
1063 clause_get_relids_vars(Node *clause, Relids *relids, List **vars)
1065 List *clvars = pull_var_clause(clause, false);
1066 List *varno_list = NIL;
1067 List *var_list = NIL;
1072 Var *var = (Var *) lfirst(i);
1075 if (!intMember(var->varno, varno_list))
1076 varno_list = lconsi(var->varno, varno_list);
1077 foreach(vi, var_list)
1079 Var *in_list = (Var *) lfirst(vi);
1081 if (in_list->varno == var->varno &&
1082 in_list->varattno == var->varattno)
1086 var_list = lcons(var, var_list);
1090 *relids = varno_list;
1096 * (formerly clause_relids)
1098 * Returns the number of different relations referenced in 'clause'.
1101 NumRelids(Node *clause)
1103 List *varno_list = pull_varnos(clause);
1104 int result = length(varno_list);
1106 freeList(varno_list);
1111 * CommuteClause: commute a binary operator clause
1113 * XXX the clause is destructively modified!
1116 CommuteClause(OpExpr *clause)
1121 if (!is_opclause(clause) ||
1122 length(clause->args) != 2)
1123 elog(ERROR, "CommuteClause: applied to non-binary-operator clause");
1125 opoid = get_commutator(clause->opno);
1127 if (!OidIsValid(opoid))
1128 elog(ERROR, "CommuteClause: no commutator for operator %u",
1132 * modify the clause in-place!
1134 clause->opno = opoid;
1135 clause->opfuncid = InvalidOid;
1136 /* opresulttype and opretset are assumed not to change */
1138 temp = lfirst(clause->args);
1139 lfirst(clause->args) = lsecond(clause->args);
1140 lsecond(clause->args) = temp;
1144 /*--------------------
1145 * eval_const_expressions
1147 * Reduce any recognizably constant subexpressions of the given
1148 * expression tree, for example "2 + 2" => "4". More interestingly,
1149 * we can reduce certain boolean expressions even when they contain
1150 * non-constant subexpressions: "x OR true" => "true" no matter what
1151 * the subexpression x is. (XXX We assume that no such subexpression
1152 * will have important side-effects, which is not necessarily a good
1153 * assumption in the presence of user-defined functions; do we need a
1154 * pg_proc flag that prevents discarding the execution of a function?)
1156 * We do understand that certain functions may deliver non-constant
1157 * results even with constant inputs, "nextval()" being the classic
1158 * example. Functions that are not marked "immutable" in pg_proc
1159 * will not be pre-evaluated here, although we will reduce their
1160 * arguments as far as possible.
1162 * We assume that the tree has already been type-checked and contains
1163 * only operators and functions that are reasonable to try to execute.
1164 *--------------------
1167 eval_const_expressions(Node *node)
1170 * The context for the mutator is a list of SQL functions being
1171 * recursively simplified, so we start with an empty list.
1173 return eval_const_expressions_mutator(node, NIL);
1177 eval_const_expressions_mutator(Node *node, List *active_fns)
1181 if (IsA(node, FuncExpr))
1183 FuncExpr *expr = (FuncExpr *) node;
1189 * Reduce constants in the FuncExpr's arguments. We know args is
1190 * either NIL or a List node, so we can call
1191 * expression_tree_mutator directly rather than recursing to self.
1193 args = (List *) expression_tree_mutator((Node *) expr->args,
1194 eval_const_expressions_mutator,
1195 (void *) active_fns);
1197 * Code for op/func reduction is pretty bulky, so split it out
1198 * as a separate function.
1200 simple = simplify_function(expr->funcid, args, true, active_fns);
1201 if (simple) /* successfully simplified it */
1202 return (Node *) simple;
1204 * The expression cannot be simplified any further, so build and
1205 * return a replacement FuncExpr node using the possibly-simplified
1208 newexpr = makeNode(FuncExpr);
1209 newexpr->funcid = expr->funcid;
1210 newexpr->funcresulttype = expr->funcresulttype;
1211 newexpr->funcretset = expr->funcretset;
1212 newexpr->funcformat = expr->funcformat;
1213 newexpr->args = args;
1214 return (Node *) newexpr;
1216 if (IsA(node, OpExpr))
1218 OpExpr *expr = (OpExpr *) node;
1224 * Reduce constants in the OpExpr's arguments. We know args is
1225 * either NIL or a List node, so we can call
1226 * expression_tree_mutator directly rather than recursing to self.
1228 args = (List *) expression_tree_mutator((Node *) expr->args,
1229 eval_const_expressions_mutator,
1230 (void *) active_fns);
1232 * Need to get OID of underlying function. Okay to scribble on
1233 * input to this extent.
1237 * Code for op/func reduction is pretty bulky, so split it out
1238 * as a separate function.
1240 simple = simplify_function(expr->opfuncid, args, true, active_fns);
1241 if (simple) /* successfully simplified it */
1242 return (Node *) simple;
1244 * The expression cannot be simplified any further, so build and
1245 * return a replacement OpExpr node using the possibly-simplified
1248 newexpr = makeNode(OpExpr);
1249 newexpr->opno = expr->opno;
1250 newexpr->opfuncid = expr->opfuncid;
1251 newexpr->opresulttype = expr->opresulttype;
1252 newexpr->opretset = expr->opretset;
1253 newexpr->args = args;
1254 return (Node *) newexpr;
1256 if (IsA(node, DistinctExpr))
1258 DistinctExpr *expr = (DistinctExpr *) node;
1261 bool has_null_input = false;
1262 bool all_null_input = true;
1263 bool has_nonconst_input = false;
1265 DistinctExpr *newexpr;
1268 * Reduce constants in the DistinctExpr's arguments. We know args is
1269 * either NIL or a List node, so we can call
1270 * expression_tree_mutator directly rather than recursing to self.
1272 args = (List *) expression_tree_mutator((Node *) expr->args,
1273 eval_const_expressions_mutator,
1274 (void *) active_fns);
1277 * We must do our own check for NULLs because
1278 * DistinctExpr has different results for NULL input
1279 * than the underlying operator does.
1283 if (IsA(lfirst(arg), Const))
1285 has_null_input |= ((Const *) lfirst(arg))->constisnull;
1286 all_null_input &= ((Const *) lfirst(arg))->constisnull;
1289 has_nonconst_input = true;
1292 /* all constants? then can optimize this out */
1293 if (!has_nonconst_input)
1295 /* all nulls? then not distinct */
1297 return MAKEBOOLCONST(false, false);
1299 /* one null? then distinct */
1301 return MAKEBOOLCONST(true, false);
1303 /* otherwise try to evaluate the '=' operator */
1304 /* (NOT okay to try to inline it, though!) */
1307 * Need to get OID of underlying function. Okay to scribble on
1308 * input to this extent.
1310 set_opfuncid((OpExpr *) expr); /* rely on struct equivalence */
1312 * Code for op/func reduction is pretty bulky, so split it out
1313 * as a separate function.
1315 simple = simplify_function(expr->opfuncid, args,
1317 if (simple) /* successfully simplified it */
1318 return (Node *) simple;
1322 * The expression cannot be simplified any further, so build and
1323 * return a replacement DistinctExpr node using the
1324 * possibly-simplified arguments.
1326 newexpr = makeNode(DistinctExpr);
1327 newexpr->opno = expr->opno;
1328 newexpr->opfuncid = expr->opfuncid;
1329 newexpr->opresulttype = expr->opresulttype;
1330 newexpr->opretset = expr->opretset;
1331 newexpr->args = args;
1332 return (Node *) newexpr;
1334 if (IsA(node, BoolExpr))
1336 BoolExpr *expr = (BoolExpr *) node;
1341 * Reduce constants in the BoolExpr's arguments. We know args is
1342 * either NIL or a List node, so we can call
1343 * expression_tree_mutator directly rather than recursing to self.
1345 args = (List *) expression_tree_mutator((Node *) expr->args,
1346 eval_const_expressions_mutator,
1347 (void *) active_fns);
1349 switch (expr->boolop)
1354 * OR arguments are handled as follows:
1355 * non constant: keep
1356 * FALSE: drop (does not affect result)
1357 * TRUE: force result to TRUE
1358 * NULL: keep only one
1359 * We keep one NULL input because ExecEvalOr returns NULL
1360 * when no input is TRUE and at least one is NULL.
1363 List *newargs = NIL;
1365 bool haveNull = false;
1366 bool forceTrue = false;
1370 if (!IsA(lfirst(arg), Const))
1372 newargs = lappend(newargs, lfirst(arg));
1375 const_input = (Const *) lfirst(arg);
1376 if (const_input->constisnull)
1378 else if (DatumGetBool(const_input->constvalue))
1380 /* otherwise, we can drop the constant-false input */
1384 * We could return TRUE before falling out of the
1385 * loop, but this coding method will be easier to
1386 * adapt if we ever add a notion of non-removable
1387 * functions. We'd need to check all the inputs for
1391 return MAKEBOOLCONST(true, false);
1393 newargs = lappend(newargs, MAKEBOOLCONST(false, true));
1394 /* If all the inputs are FALSE, result is FALSE */
1396 return MAKEBOOLCONST(false, false);
1397 /* If only one nonconst-or-NULL input, it's the result */
1398 if (lnext(newargs) == NIL)
1399 return (Node *) lfirst(newargs);
1400 /* Else we still need an OR node */
1401 return (Node *) make_orclause(newargs);
1406 * AND arguments are handled as follows:
1407 * non constant: keep
1408 * TRUE: drop (does not affect result)
1409 * FALSE: force result to FALSE
1410 * NULL: keep only one
1411 * We keep one NULL input because ExecEvalAnd returns NULL
1412 * when no input is FALSE and at least one is NULL.
1415 List *newargs = NIL;
1417 bool haveNull = false;
1418 bool forceFalse = false;
1422 if (!IsA(lfirst(arg), Const))
1424 newargs = lappend(newargs, lfirst(arg));
1427 const_input = (Const *) lfirst(arg);
1428 if (const_input->constisnull)
1430 else if (!DatumGetBool(const_input->constvalue))
1432 /* otherwise, we can drop the constant-true input */
1436 * We could return FALSE before falling out of the
1437 * loop, but this coding method will be easier to
1438 * adapt if we ever add a notion of non-removable
1439 * functions. We'd need to check all the inputs for
1443 return MAKEBOOLCONST(false, false);
1445 newargs = lappend(newargs, MAKEBOOLCONST(false, true));
1446 /* If all the inputs are TRUE, result is TRUE */
1448 return MAKEBOOLCONST(true, false);
1449 /* If only one nonconst-or-NULL input, it's the result */
1450 if (lnext(newargs) == NIL)
1451 return (Node *) lfirst(newargs);
1452 /* Else we still need an AND node */
1453 return (Node *) make_andclause(newargs);
1456 Assert(length(args) == 1);
1457 if (IsA(lfirst(args), Const))
1459 const_input = (Const *) lfirst(args);
1460 /* NOT NULL => NULL */
1461 if (const_input->constisnull)
1462 return MAKEBOOLCONST(false, true);
1463 /* otherwise pretty easy */
1464 return MAKEBOOLCONST(!DatumGetBool(const_input->constvalue),
1467 /* Else we still need a NOT node */
1468 return (Node *) make_notclause(lfirst(args));
1470 elog(ERROR, "eval_const_expressions: unexpected boolop %d",
1471 (int) expr->boolop);
1475 if (IsA(node, SubPlanExpr))
1478 * Return a SubPlanExpr unchanged --- too late to do anything
1481 * XXX should we elog() here instead? Probably this routine
1482 * should never be invoked after SubPlanExpr creation.
1486 if (IsA(node, RelabelType))
1489 * If we can simplify the input to a constant, then we don't need
1490 * the RelabelType node anymore: just change the type field of the
1491 * Const node. Otherwise, must copy the RelabelType node.
1493 RelabelType *relabel = (RelabelType *) node;
1496 arg = eval_const_expressions_mutator((Node *) relabel->arg,
1500 * If we find stacked RelabelTypes (eg, from foo :: int :: oid) we
1501 * can discard all but the top one.
1503 while (arg && IsA(arg, RelabelType))
1504 arg = (Node *) ((RelabelType *) arg)->arg;
1506 if (arg && IsA(arg, Const))
1508 Const *con = (Const *) arg;
1510 con->consttype = relabel->resulttype;
1513 * relabel's resulttypmod is discarded, which is OK for now;
1514 * if the type actually needs a runtime length coercion then
1515 * there should be a function call to do it just above this
1518 return (Node *) con;
1522 RelabelType *newrelabel = makeNode(RelabelType);
1524 newrelabel->arg = (Expr *) arg;
1525 newrelabel->resulttype = relabel->resulttype;
1526 newrelabel->resulttypmod = relabel->resulttypmod;
1527 return (Node *) newrelabel;
1530 if (IsA(node, CaseExpr))
1534 * CASE expressions can be simplified if there are constant
1535 * condition clauses:
1536 * FALSE (or NULL): drop the alternative
1537 * TRUE: drop all remaining alternatives
1538 * If the first non-FALSE alternative is a constant TRUE, we can
1539 * simplify the entire CASE to that alternative's expression.
1540 * If there are no non-FALSE alternatives, we simplify the entire
1541 * CASE to the default result (ELSE result).
1544 CaseExpr *caseexpr = (CaseExpr *) node;
1546 List *newargs = NIL;
1551 foreach(arg, caseexpr->args)
1553 /* Simplify this alternative's condition and result */
1554 CaseWhen *casewhen = (CaseWhen *)
1555 expression_tree_mutator((Node *) lfirst(arg),
1556 eval_const_expressions_mutator,
1557 (void *) active_fns);
1559 Assert(IsA(casewhen, CaseWhen));
1560 if (casewhen->expr == NULL ||
1561 !IsA(casewhen->expr, Const))
1563 newargs = lappend(newargs, casewhen);
1566 const_input = (Const *) casewhen->expr;
1567 if (const_input->constisnull ||
1568 !DatumGetBool(const_input->constvalue))
1569 continue; /* drop alternative with FALSE condition */
1572 * Found a TRUE condition. If it's the first (un-dropped)
1573 * alternative, the CASE reduces to just this alternative.
1576 return (Node *) casewhen->result;
1579 * Otherwise, add it to the list, and drop all the rest.
1581 newargs = lappend(newargs, casewhen);
1585 /* Simplify the default result */
1586 defresult = eval_const_expressions_mutator((Node *) caseexpr->defresult,
1590 * If no non-FALSE alternatives, CASE reduces to the default
1595 /* Otherwise we need a new CASE node */
1596 newcase = makeNode(CaseExpr);
1597 newcase->casetype = caseexpr->casetype;
1598 newcase->arg = NULL;
1599 newcase->args = newargs;
1600 newcase->defresult = (Expr *) defresult;
1601 return (Node *) newcase;
1605 * For any node type not handled above, we recurse using
1606 * expression_tree_mutator, which will copy the node unchanged but try
1607 * to simplify its arguments (if any) using this routine. For example:
1608 * we cannot eliminate an ArrayRef node, but we might be able to
1609 * simplify constant expressions in its subscripts.
1611 return expression_tree_mutator(node, eval_const_expressions_mutator,
1612 (void *) active_fns);
1616 * Subroutine for eval_const_expressions: try to simplify a function call
1617 * (which might originally have been an operator; we don't care)
1619 * Inputs are the function OID and the pre-simplified argument list;
1620 * also a list of already-active inline function expansions.
1622 * Returns a simplified expression if successful, or NULL if cannot
1623 * simplify the function call.
1626 simplify_function(Oid funcid, List *args, bool allow_inline, List *active_fns)
1628 HeapTuple func_tuple;
1632 * We have two strategies for simplification: either execute the function
1633 * to deliver a constant result, or expand in-line the body of the
1634 * function definition (which only works for simple SQL-language
1635 * functions, but that is a common case). In either case we need access
1636 * to the function's pg_proc tuple, so fetch it just once to use in both
1639 func_tuple = SearchSysCache(PROCOID,
1640 ObjectIdGetDatum(funcid),
1642 if (!HeapTupleIsValid(func_tuple))
1643 elog(ERROR, "Function OID %u does not exist", funcid);
1645 newexpr = evaluate_function(funcid, args, func_tuple);
1647 if (!newexpr && allow_inline)
1648 newexpr = inline_function(funcid, args, func_tuple, active_fns);
1650 ReleaseSysCache(func_tuple);
1656 * evaluate_function: try to pre-evaluate a function call
1658 * We can do this if the function is strict and has any constant-null inputs
1659 * (just return a null constant), or if the function is immutable and has all
1660 * constant inputs (call it and return the result as a Const node).
1662 * Returns a simplified expression if successful, or NULL if cannot
1663 * simplify the function.
1666 evaluate_function(Oid funcid, List *args, HeapTuple func_tuple)
1668 Form_pg_proc funcform = (Form_pg_proc) GETSTRUCT(func_tuple);
1669 Oid result_typeid = funcform->prorettype;
1671 bool resultTypByVal;
1672 bool has_nonconst_input = false;
1673 bool has_null_input = false;
1675 ExprContext *econtext;
1681 * Can't simplify if it returns a set.
1683 if (funcform->proretset)
1687 * Check for constant inputs and especially constant-NULL inputs.
1691 if (IsA(lfirst(arg), Const))
1692 has_null_input |= ((Const *) lfirst(arg))->constisnull;
1694 has_nonconst_input = true;
1698 * If the function is strict and has a constant-NULL input, it will
1699 * never be called at all, so we can replace the call by a NULL
1700 * constant, even if there are other inputs that aren't constant,
1701 * and even if the function is not otherwise immutable.
1703 if (funcform->proisstrict && has_null_input)
1704 return (Expr *) makeNullConst(result_typeid);
1707 * Otherwise, can simplify only if the function is immutable and
1708 * all inputs are constants. (For a non-strict function, constant NULL
1709 * inputs are treated the same as constant non-NULL inputs.)
1711 if (funcform->provolatile != PROVOLATILE_IMMUTABLE ||
1716 * OK, looks like we can simplify this operator/function.
1718 * We use the executor's routine ExecEvalExpr() to avoid duplication of
1719 * code and ensure we get the same result as the executor would get.
1721 * Build a new FuncExpr node containing the already-simplified arguments.
1723 newexpr = makeNode(FuncExpr);
1724 newexpr->funcid = funcid;
1725 newexpr->funcresulttype = result_typeid;
1726 newexpr->funcretset = false;
1727 newexpr->funcformat = COERCE_EXPLICIT_CALL; /* doesn't matter */
1728 newexpr->args = args;
1730 /* Get info needed about result datatype */
1731 get_typlenbyval(result_typeid, &resultTypLen, &resultTypByVal);
1734 * It is OK to use a dummy econtext because none of the
1735 * ExecEvalExpr() code used in this situation will use econtext. That
1736 * might seem fortuitous, but it's not so unreasonable --- a constant
1737 * expression does not depend on context, by definition, n'est ce pas?
1739 econtext = MakeExprContext(NULL, CurrentMemoryContext);
1741 const_val = ExecEvalExprSwitchContext((Node *) newexpr, econtext,
1742 &const_is_null, NULL);
1744 /* Must copy result out of sub-context used by expression eval */
1746 const_val = datumCopy(const_val, resultTypByVal, resultTypLen);
1748 FreeExprContext(econtext);
1752 * Make the constant result node.
1754 return (Expr *) makeConst(result_typeid, resultTypLen,
1755 const_val, const_is_null,
1760 * inline_function: try to expand a function call inline
1762 * If the function is a sufficiently simple SQL-language function
1763 * (just "SELECT expression"), then we can inline it and avoid the rather
1764 * high per-call overhead of SQL functions. Furthermore, this can expose
1765 * opportunities for constant-folding within the function expression.
1767 * We have to beware of some special cases however. A directly or
1768 * indirectly recursive function would cause us to recurse forever,
1769 * so we keep track of which functions we are already expanding and
1770 * do not re-expand them. Also, if a parameter is used more than once
1771 * in the SQL-function body, we require it not to contain any volatile
1772 * functions or sublinks --- volatiles might deliver inconsistent answers,
1773 * and subplans might be unreasonably expensive to evaluate multiple times.
1774 * We must also beware of changing the volatility or strictness status of
1775 * functions by inlining them.
1777 * Returns a simplified expression if successful, or NULL if cannot
1778 * simplify the function.
1781 inline_function(Oid funcid, List *args, HeapTuple func_tuple,
1784 Form_pg_proc funcform = (Form_pg_proc) GETSTRUCT(func_tuple);
1785 Oid result_typeid = funcform->prorettype;
1786 char result_typtype;
1790 MemoryContext oldcxt;
1791 MemoryContext mycxt;
1792 StringInfoData stri;
1793 List *raw_parsetree_list;
1794 List *querytree_list;
1802 * Forget it if the function is not SQL-language or has other
1803 * showstopper properties. (The nargs check is just paranoia.)
1805 if (funcform->prolang != SQLlanguageId ||
1806 funcform->prosecdef ||
1807 funcform->proretset ||
1808 funcform->pronargs != length(args))
1811 /* Forget it if return type is tuple or void */
1812 result_typtype = get_typtype(result_typeid);
1813 if (result_typtype != 'b' &&
1814 result_typtype != 'd')
1817 /* Check for recursive function, and give up trying to expand if so */
1818 if (intMember(funcid, active_fns))
1821 /* Check permission to call function (fail later, if not) */
1822 if (pg_proc_aclcheck(funcid, GetUserId(), ACL_EXECUTE) != ACLCHECK_OK)
1826 * Make a temporary memory context, so that we don't leak all the
1827 * stuff that parsing might create.
1829 mycxt = AllocSetContextCreate(CurrentMemoryContext,
1831 ALLOCSET_DEFAULT_MINSIZE,
1832 ALLOCSET_DEFAULT_INITSIZE,
1833 ALLOCSET_DEFAULT_MAXSIZE);
1834 oldcxt = MemoryContextSwitchTo(mycxt);
1836 /* Fetch and parse the function body */
1837 tmp = SysCacheGetAttr(PROCOID,
1839 Anum_pg_proc_prosrc,
1842 elog(ERROR, "inline_function: null prosrc for procedure %u",
1844 src = DatumGetCString(DirectFunctionCall1(textout, tmp));
1847 * We just do parsing and parse analysis, not rewriting, because
1848 * rewriting will not affect SELECT-only queries, which is all that
1849 * we care about. Also, we can punt as soon as we detect more than
1850 * one command in the function body.
1852 initStringInfo(&stri);
1853 appendStringInfo(&stri, "%s", src);
1855 raw_parsetree_list = pg_parse_query(&stri,
1856 funcform->proargtypes,
1857 funcform->pronargs);
1858 if (length(raw_parsetree_list) != 1)
1861 querytree_list = parse_analyze(lfirst(raw_parsetree_list), NULL);
1863 if (length(querytree_list) != 1)
1866 querytree = (Query *) lfirst(querytree_list);
1869 * The single command must be a simple "SELECT expression".
1871 if (!IsA(querytree, Query) ||
1872 querytree->commandType != CMD_SELECT ||
1873 querytree->resultRelation != 0 ||
1875 querytree->isPortal ||
1876 querytree->hasAggs ||
1877 querytree->hasSubLinks ||
1878 querytree->rtable ||
1879 querytree->jointree->fromlist ||
1880 querytree->jointree->quals ||
1881 querytree->groupClause ||
1882 querytree->havingQual ||
1883 querytree->distinctClause ||
1884 querytree->sortClause ||
1885 querytree->limitOffset ||
1886 querytree->limitCount ||
1887 querytree->setOperations ||
1888 length(querytree->targetList) != 1)
1891 newexpr = (Node *) ((TargetEntry *) lfirst(querytree->targetList))->expr;
1894 * Additional validity checks on the expression. It mustn't return a
1895 * set, and it mustn't be more volatile than the surrounding function
1896 * (this is to avoid breaking hacks that involve pretending a function
1897 * is immutable when it really ain't). If the surrounding function is
1898 * declared strict, then the expression must contain only strict constructs
1899 * and must use all of the function parameters (this is overkill, but
1900 * an exact analysis is hard).
1902 if (expression_returns_set(newexpr))
1905 if (funcform->provolatile == PROVOLATILE_IMMUTABLE &&
1906 contain_mutable_functions(newexpr))
1908 else if (funcform->provolatile == PROVOLATILE_STABLE &&
1909 contain_volatile_functions(newexpr))
1912 if (funcform->proisstrict &&
1913 contain_nonstrict_functions(newexpr))
1917 * We may be able to do it; there are still checks on parameter usage
1918 * to make, but those are most easily done in combination with the
1919 * actual substitution of the inputs. So start building expression
1920 * with inputs substituted.
1922 usecounts = (int *) palloc0((funcform->pronargs + 1) * sizeof(int));
1923 newexpr = substitute_actual_parameters(newexpr, funcform->pronargs,
1926 /* Now check for parameter usage */
1930 Node *param = lfirst(arg);
1932 if (usecounts[i] == 0)
1934 /* Param not used at all: uncool if func is strict */
1935 if (funcform->proisstrict)
1938 else if (usecounts[i] != 1)
1940 /* Param used multiple times: uncool if volatile or expensive */
1941 if (contain_volatile_functions(param) ||
1942 contain_subplans(param))
1949 * Whew --- we can make the substitution. Copy the modified expression
1950 * out of the temporary memory context, and clean up.
1952 MemoryContextSwitchTo(oldcxt);
1954 newexpr = copyObject(newexpr);
1956 MemoryContextDelete(mycxt);
1959 * Recursively try to simplify the modified expression. Here we must
1960 * add the current function to the context list of active functions.
1962 newexpr = eval_const_expressions_mutator(newexpr,
1963 lconsi(funcid, active_fns));
1965 return (Expr *) newexpr;
1967 /* Here if func is not inlinable: release temp memory and return NULL */
1969 MemoryContextSwitchTo(oldcxt);
1970 MemoryContextDelete(mycxt);
1976 * Replace Param nodes by appropriate actual parameters
1979 substitute_actual_parameters(Node *expr, int nargs, List *args,
1982 substitute_actual_parameters_context context;
1984 context.nargs = nargs;
1985 context.args = args;
1986 context.usecounts = usecounts;
1988 return substitute_actual_parameters_mutator(expr, &context);
1992 substitute_actual_parameters_mutator(Node *node,
1993 substitute_actual_parameters_context *context)
1997 if (IsA(node, Param))
1999 Param *param = (Param *) node;
2001 if (param->paramkind != PARAM_NUM)
2002 elog(ERROR, "substitute_actual_parameters_mutator: unexpected paramkind");
2003 if (param->paramid <= 0 || param->paramid > context->nargs)
2004 elog(ERROR, "substitute_actual_parameters_mutator: unexpected paramid");
2006 /* Count usage of parameter */
2007 context->usecounts[param->paramid - 1]++;
2009 /* Select the appropriate actual arg and replace the Param with it */
2010 /* We don't need to copy at this time (it'll get done later) */
2011 return nth(param->paramid - 1, context->args);
2013 return expression_tree_mutator(node, substitute_actual_parameters_mutator,
2019 * Standard expression-tree walking support
2021 * We used to have near-duplicate code in many different routines that
2022 * understood how to recurse through an expression node tree. That was
2023 * a pain to maintain, and we frequently had bugs due to some particular
2024 * routine neglecting to support a particular node type. In most cases,
2025 * these routines only actually care about certain node types, and don't
2026 * care about other types except insofar as they have to recurse through
2027 * non-primitive node types. Therefore, we now provide generic tree-walking
2028 * logic to consolidate the redundant "boilerplate" code. There are
2029 * two versions: expression_tree_walker() and expression_tree_mutator().
2032 /*--------------------
2033 * expression_tree_walker() is designed to support routines that traverse
2034 * a tree in a read-only fashion (although it will also work for routines
2035 * that modify nodes in-place but never add/delete/replace nodes).
2036 * A walker routine should look like this:
2038 * bool my_walker (Node *node, my_struct *context)
2042 * // check for nodes that special work is required for, eg:
2043 * if (IsA(node, Var))
2045 * ... do special actions for Var nodes
2047 * else if (IsA(node, ...))
2049 * ... do special actions for other node types
2051 * // for any node type not specially processed, do:
2052 * return expression_tree_walker(node, my_walker, (void *) context);
2055 * The "context" argument points to a struct that holds whatever context
2056 * information the walker routine needs --- it can be used to return data
2057 * gathered by the walker, too. This argument is not touched by
2058 * expression_tree_walker, but it is passed down to recursive sub-invocations
2059 * of my_walker. The tree walk is started from a setup routine that
2060 * fills in the appropriate context struct, calls my_walker with the top-level
2061 * node of the tree, and then examines the results.
2063 * The walker routine should return "false" to continue the tree walk, or
2064 * "true" to abort the walk and immediately return "true" to the top-level
2065 * caller. This can be used to short-circuit the traversal if the walker
2066 * has found what it came for. "false" is returned to the top-level caller
2067 * iff no invocation of the walker returned "true".
2069 * The node types handled by expression_tree_walker include all those
2070 * normally found in target lists and qualifier clauses during the planning
2071 * stage. In particular, it handles List nodes since a cnf-ified qual clause
2072 * will have List structure at the top level, and it handles TargetEntry nodes
2073 * so that a scan of a target list can be handled without additional code.
2074 * (But only the "expr" part of a TargetEntry is examined, unless the walker
2075 * chooses to process TargetEntry nodes specially.) Also, RangeTblRef,
2076 * FromExpr, JoinExpr, and SetOperationStmt nodes are handled, so that query
2077 * jointrees and setOperation trees can be processed without additional code.
2079 * expression_tree_walker will handle SubLink and SubPlanExpr nodes by
2080 * recursing normally into the "lefthand" arguments (which are expressions
2081 * belonging to the outer plan). It will also call the walker on the
2082 * sub-Query node; however, when expression_tree_walker itself is called on a
2083 * Query node, it does nothing and returns "false". The net effect is that
2084 * unless the walker does something special at a Query node, sub-selects will
2085 * not be visited during an expression tree walk. This is exactly the behavior
2086 * wanted in many cases --- and for those walkers that do want to recurse into
2087 * sub-selects, special behavior is typically needed anyway at the entry to a
2088 * sub-select (such as incrementing a depth counter). A walker that wants to
2089 * examine sub-selects should include code along the lines of:
2091 * if (IsA(node, Query))
2093 * adjust context for subquery;
2094 * result = query_tree_walker((Query *) node, my_walker, context,
2095 * 0); // to visit rtable items too
2096 * restore context if needed;
2100 * query_tree_walker is a convenience routine (see below) that calls the
2101 * walker on all the expression subtrees of the given Query node.
2103 * NOTE: currently, because make_subplan() clears the subselect link in
2104 * a SubLink node, it is not actually possible to recurse into subselects
2105 * of an already-planned expression tree. This is OK for current uses,
2106 * but ought to be cleaned up when we redesign querytree processing.
2107 *--------------------
2111 expression_tree_walker(Node *node,
2118 * The walker has already visited the current node, and so we need
2119 * only recurse into any sub-nodes it has.
2121 * We assume that the walker is not interested in List nodes per se, so
2122 * when we expect a List we just recurse directly to self without
2123 * bothering to call the walker.
2127 switch (nodeTag(node))
2133 /* primitive node types with no subnodes */
2136 return walker(((Aggref *) node)->target, context);
2139 ArrayRef *aref = (ArrayRef *) node;
2141 /* recurse directly for upper/lower array index lists */
2142 if (expression_tree_walker((Node *) aref->refupperindexpr,
2145 if (expression_tree_walker((Node *) aref->reflowerindexpr,
2148 /* walker must see the refexpr and refassgnexpr, however */
2149 if (walker(aref->refexpr, context))
2151 if (walker(aref->refassgnexpr, context))
2157 FuncExpr *expr = (FuncExpr *) node;
2159 if (expression_tree_walker((Node *) expr->args,
2166 OpExpr *expr = (OpExpr *) node;
2168 if (expression_tree_walker((Node *) expr->args,
2173 case T_DistinctExpr:
2175 DistinctExpr *expr = (DistinctExpr *) node;
2177 if (expression_tree_walker((Node *) expr->args,
2184 BoolExpr *expr = (BoolExpr *) node;
2186 if (expression_tree_walker((Node *) expr->args,
2193 SubLink *sublink = (SubLink *) node;
2196 * If the SubLink has already been processed by
2197 * subselect.c, it will have lefthand=NIL, and we need to
2198 * scan the oper list. Otherwise we only need to look at
2199 * the lefthand list (the incomplete OpExpr nodes in the
2200 * oper list are deemed uninteresting, perhaps even
2203 if (sublink->lefthand)
2205 if (walker((Node *) sublink->lefthand, context))
2210 if (walker((Node *) sublink->oper, context))
2215 * Also invoke the walker on the sublink's Query node, so
2216 * it can recurse into the sub-query if it wants to.
2218 return walker(sublink->subselect, context);
2223 SubPlanExpr *expr = (SubPlanExpr *) node;
2225 /* recurse to the SubLink node, but not into the Plan */
2226 if (walker((Node *) expr->sublink, context))
2228 /* also examine args list */
2229 if (expression_tree_walker((Node *) expr->args,
2235 return walker(((FieldSelect *) node)->arg, context);
2237 return walker(((RelabelType *) node)->arg, context);
2240 CaseExpr *caseexpr = (CaseExpr *) node;
2242 /* we assume walker doesn't care about CaseWhens, either */
2243 foreach(temp, caseexpr->args)
2245 CaseWhen *when = (CaseWhen *) lfirst(temp);
2247 Assert(IsA(when, CaseWhen));
2248 if (walker(when->expr, context))
2250 if (walker(when->result, context))
2253 /* caseexpr->arg should be null, but we'll check it anyway */
2254 if (walker(caseexpr->arg, context))
2256 if (walker(caseexpr->defresult, context))
2261 return walker(((NullTest *) node)->arg, context);
2263 return walker(((BooleanTest *) node)->arg, context);
2264 case T_ConstraintTest:
2265 if (walker(((ConstraintTest *) node)->arg, context))
2267 return walker(((ConstraintTest *) node)->check_expr, context);
2268 case T_ConstraintTestValue:
2271 return walker(((TargetEntry *) node)->expr, context);
2273 /* Do nothing with a sub-Query, per discussion above */
2276 foreach(temp, (List *) node)
2278 if (walker((Node *) lfirst(temp), context))
2284 FromExpr *from = (FromExpr *) node;
2286 if (walker(from->fromlist, context))
2288 if (walker(from->quals, context))
2294 JoinExpr *join = (JoinExpr *) node;
2296 if (walker(join->larg, context))
2298 if (walker(join->rarg, context))
2300 if (walker(join->quals, context))
2304 * alias clause, using list are deemed uninteresting.
2308 case T_SetOperationStmt:
2310 SetOperationStmt *setop = (SetOperationStmt *) node;
2312 if (walker(setop->larg, context))
2314 if (walker(setop->rarg, context))
2319 elog(ERROR, "expression_tree_walker: Unexpected node type %d",
2327 * query_tree_walker --- initiate a walk of a Query's expressions
2329 * This routine exists just to reduce the number of places that need to know
2330 * where all the expression subtrees of a Query are. Note it can be used
2331 * for starting a walk at top level of a Query regardless of whether the
2332 * walker intends to descend into subqueries. It is also useful for
2333 * descending into subqueries within a walker.
2335 * Some callers want to suppress visitation of certain items in the sub-Query,
2336 * typically because they need to process them specially, or don't actually
2337 * want to recurse into subqueries. This is supported by the flags argument,
2338 * which is the bitwise OR of flag values to suppress visitation of
2339 * indicated items. (More flag bits may be added as needed.)
2342 query_tree_walker(Query *query,
2349 Assert(query != NULL && IsA(query, Query));
2351 if (walker((Node *) query->targetList, context))
2353 if (walker((Node *) query->jointree, context))
2355 if (walker(query->setOperations, context))
2357 if (walker(query->havingQual, context))
2359 foreach(rt, query->rtable)
2361 RangeTblEntry *rte = (RangeTblEntry *) lfirst(rt);
2363 switch (rte->rtekind)
2370 if (! (flags & QTW_IGNORE_SUBQUERIES))
2371 if (walker(rte->subquery, context))
2375 if (! (flags & QTW_IGNORE_JOINALIASES))
2376 if (walker(rte->joinaliasvars, context))
2380 if (walker(rte->funcexpr, context))
2389 /*--------------------
2390 * expression_tree_mutator() is designed to support routines that make a
2391 * modified copy of an expression tree, with some nodes being added,
2392 * removed, or replaced by new subtrees. The original tree is (normally)
2393 * not changed. Each recursion level is responsible for returning a copy of
2394 * (or appropriately modified substitute for) the subtree it is handed.
2395 * A mutator routine should look like this:
2397 * Node * my_mutator (Node *node, my_struct *context)
2401 * // check for nodes that special work is required for, eg:
2402 * if (IsA(node, Var))
2404 * ... create and return modified copy of Var node
2406 * else if (IsA(node, ...))
2408 * ... do special transformations of other node types
2410 * // for any node type not specially processed, do:
2411 * return expression_tree_mutator(node, my_mutator, (void *) context);
2414 * The "context" argument points to a struct that holds whatever context
2415 * information the mutator routine needs --- it can be used to return extra
2416 * data gathered by the mutator, too. This argument is not touched by
2417 * expression_tree_mutator, but it is passed down to recursive sub-invocations
2418 * of my_mutator. The tree walk is started from a setup routine that
2419 * fills in the appropriate context struct, calls my_mutator with the
2420 * top-level node of the tree, and does any required post-processing.
2422 * Each level of recursion must return an appropriately modified Node.
2423 * If expression_tree_mutator() is called, it will make an exact copy
2424 * of the given Node, but invoke my_mutator() to copy the sub-node(s)
2425 * of that Node. In this way, my_mutator() has full control over the
2426 * copying process but need not directly deal with expression trees
2427 * that it has no interest in.
2429 * Just as for expression_tree_walker, the node types handled by
2430 * expression_tree_mutator include all those normally found in target lists
2431 * and qualifier clauses during the planning stage.
2433 * expression_tree_mutator will handle a SubPlanExpr node by recursing into
2434 * the args and sublink->oper lists (which belong to the outer plan), but it
2435 * will simply copy the link to the inner plan, since that's typically what
2436 * expression tree mutators want. A mutator that wants to modify the subplan
2437 * can force appropriate behavior by recognizing subplan expression nodes
2438 * and doing the right thing.
2440 * Bare SubLink nodes (without a SubPlanExpr) are handled by recursing into
2441 * the "lefthand" argument list only. (A bare SubLink should be seen only if
2442 * the tree has not yet been processed by subselect.c.) Again, this can be
2443 * overridden by the mutator, but it seems to be the most useful default
2445 *--------------------
2449 expression_tree_mutator(Node *node,
2450 Node *(*mutator) (),
2454 * The mutator has already decided not to modify the current node, but
2455 * we must call the mutator for any sub-nodes.
2458 #define FLATCOPY(newnode, node, nodetype) \
2459 ( (newnode) = makeNode(nodetype), \
2460 memcpy((newnode), (node), sizeof(nodetype)) )
2462 #define CHECKFLATCOPY(newnode, node, nodetype) \
2463 ( AssertMacro(IsA((node), nodetype)), \
2464 (newnode) = makeNode(nodetype), \
2465 memcpy((newnode), (node), sizeof(nodetype)) )
2467 #define MUTATE(newfield, oldfield, fieldtype) \
2468 ( (newfield) = (fieldtype) mutator((Node *) (oldfield), context) )
2472 switch (nodeTag(node))
2478 /* primitive node types with no subnodes */
2479 return (Node *) copyObject(node);
2482 Aggref *aggref = (Aggref *) node;
2485 FLATCOPY(newnode, aggref, Aggref);
2486 MUTATE(newnode->target, aggref->target, Expr *);
2487 return (Node *) newnode;
2492 ArrayRef *arrayref = (ArrayRef *) node;
2495 FLATCOPY(newnode, arrayref, ArrayRef);
2496 MUTATE(newnode->refupperindexpr, arrayref->refupperindexpr,
2498 MUTATE(newnode->reflowerindexpr, arrayref->reflowerindexpr,
2500 MUTATE(newnode->refexpr, arrayref->refexpr,
2502 MUTATE(newnode->refassgnexpr, arrayref->refassgnexpr,
2504 return (Node *) newnode;
2509 FuncExpr *expr = (FuncExpr *) node;
2512 FLATCOPY(newnode, expr, FuncExpr);
2513 MUTATE(newnode->args, expr->args, List *);
2514 return (Node *) newnode;
2519 OpExpr *expr = (OpExpr *) node;
2522 FLATCOPY(newnode, expr, OpExpr);
2523 MUTATE(newnode->args, expr->args, List *);
2524 return (Node *) newnode;
2527 case T_DistinctExpr:
2529 DistinctExpr *expr = (DistinctExpr *) node;
2530 DistinctExpr *newnode;
2532 FLATCOPY(newnode, expr, DistinctExpr);
2533 MUTATE(newnode->args, expr->args, List *);
2534 return (Node *) newnode;
2539 BoolExpr *expr = (BoolExpr *) node;
2542 FLATCOPY(newnode, expr, BoolExpr);
2543 MUTATE(newnode->args, expr->args, List *);
2544 return (Node *) newnode;
2550 * A "bare" SubLink (note we will not come here if we
2551 * found a SubPlanExpr node above it). Transform the
2552 * lefthand side, but not the oper list nor the subquery.
2554 SubLink *sublink = (SubLink *) node;
2557 FLATCOPY(newnode, sublink, SubLink);
2558 MUTATE(newnode->lefthand, sublink->lefthand, List *);
2559 return (Node *) newnode;
2564 SubPlanExpr *expr = (SubPlanExpr *) node;
2565 SubLink *oldsublink = expr->sublink;
2566 SubPlanExpr *newnode;
2568 FLATCOPY(newnode, expr, SubPlanExpr);
2569 /* flat-copy the SubLink node */
2570 CHECKFLATCOPY(newnode->sublink, oldsublink, SubLink);
2571 /* transform args list (params to be passed to subplan) */
2572 MUTATE(newnode->args, expr->args, List *);
2573 /* transform sublink's oper list as well */
2574 MUTATE(newnode->sublink->oper, oldsublink->oper, List *);
2575 /* but not the subplan itself, which is referenced as-is */
2576 return (Node *) newnode;
2581 FieldSelect *fselect = (FieldSelect *) node;
2582 FieldSelect *newnode;
2584 FLATCOPY(newnode, fselect, FieldSelect);
2585 MUTATE(newnode->arg, fselect->arg, Expr *);
2586 return (Node *) newnode;
2591 RelabelType *relabel = (RelabelType *) node;
2592 RelabelType *newnode;
2594 FLATCOPY(newnode, relabel, RelabelType);
2595 MUTATE(newnode->arg, relabel->arg, Expr *);
2596 return (Node *) newnode;
2601 CaseExpr *caseexpr = (CaseExpr *) node;
2604 FLATCOPY(newnode, caseexpr, CaseExpr);
2605 MUTATE(newnode->args, caseexpr->args, List *);
2606 /* caseexpr->arg should be null, but we'll check it anyway */
2607 MUTATE(newnode->arg, caseexpr->arg, Expr *);
2608 MUTATE(newnode->defresult, caseexpr->defresult, Expr *);
2609 return (Node *) newnode;
2614 CaseWhen *casewhen = (CaseWhen *) node;
2617 FLATCOPY(newnode, casewhen, CaseWhen);
2618 MUTATE(newnode->expr, casewhen->expr, Expr *);
2619 MUTATE(newnode->result, casewhen->result, Expr *);
2620 return (Node *) newnode;
2625 NullTest *ntest = (NullTest *) node;
2628 FLATCOPY(newnode, ntest, NullTest);
2629 MUTATE(newnode->arg, ntest->arg, Expr *);
2630 return (Node *) newnode;
2635 BooleanTest *btest = (BooleanTest *) node;
2636 BooleanTest *newnode;
2638 FLATCOPY(newnode, btest, BooleanTest);
2639 MUTATE(newnode->arg, btest->arg, Expr *);
2640 return (Node *) newnode;
2643 case T_ConstraintTest:
2645 ConstraintTest *ctest = (ConstraintTest *) node;
2646 ConstraintTest *newnode;
2648 FLATCOPY(newnode, ctest, ConstraintTest);
2649 MUTATE(newnode->arg, ctest->arg, Expr *);
2650 MUTATE(newnode->check_expr, ctest->check_expr, Expr *);
2651 return (Node *) newnode;
2654 case T_ConstraintTestValue:
2656 ConstraintTestValue *ctest = (ConstraintTestValue *) node;
2657 ConstraintTestValue *newnode;
2659 FLATCOPY(newnode, ctest, ConstraintTestValue);
2660 return (Node *) newnode;
2666 * We mutate the expression, but not the resdom, by
2669 TargetEntry *targetentry = (TargetEntry *) node;
2670 TargetEntry *newnode;
2672 FLATCOPY(newnode, targetentry, TargetEntry);
2673 MUTATE(newnode->expr, targetentry->expr, Expr *);
2674 return (Node *) newnode;
2680 * We assume the mutator isn't interested in the list
2681 * nodes per se, so just invoke it on each list element.
2682 * NOTE: this would fail badly on a list with integer
2685 List *resultlist = NIL;
2688 foreach(temp, (List *) node)
2690 resultlist = lappend(resultlist,
2691 mutator((Node *) lfirst(temp),
2694 return (Node *) resultlist;
2699 FromExpr *from = (FromExpr *) node;
2702 FLATCOPY(newnode, from, FromExpr);
2703 MUTATE(newnode->fromlist, from->fromlist, List *);
2704 MUTATE(newnode->quals, from->quals, Node *);
2705 return (Node *) newnode;
2710 JoinExpr *join = (JoinExpr *) node;
2713 FLATCOPY(newnode, join, JoinExpr);
2714 MUTATE(newnode->larg, join->larg, Node *);
2715 MUTATE(newnode->rarg, join->rarg, Node *);
2716 MUTATE(newnode->quals, join->quals, Node *);
2717 /* We do not mutate alias or using by default */
2718 return (Node *) newnode;
2721 case T_SetOperationStmt:
2723 SetOperationStmt *setop = (SetOperationStmt *) node;
2724 SetOperationStmt *newnode;
2726 FLATCOPY(newnode, setop, SetOperationStmt);
2727 MUTATE(newnode->larg, setop->larg, Node *);
2728 MUTATE(newnode->rarg, setop->rarg, Node *);
2729 return (Node *) newnode;
2733 elog(ERROR, "expression_tree_mutator: Unexpected node type %d",
2737 /* can't get here, but keep compiler happy */
2743 * query_tree_mutator --- initiate modification of a Query's expressions
2745 * This routine exists just to reduce the number of places that need to know
2746 * where all the expression subtrees of a Query are. Note it can be used
2747 * for starting a walk at top level of a Query regardless of whether the
2748 * mutator intends to descend into subqueries. It is also useful for
2749 * descending into subqueries within a mutator.
2751 * The specified Query node is modified-in-place; do a FLATCOPY() beforehand
2752 * if you don't want to change the original. All substructure is safely
2755 * Some callers want to suppress mutating of certain items in the sub-Query,
2756 * typically because they need to process them specially, or don't actually
2757 * want to recurse into subqueries. This is supported by the flags argument,
2758 * which is the bitwise OR of flag values to suppress mutating of
2759 * indicated items. (More flag bits may be added as needed.)
2762 query_tree_mutator(Query *query,
2763 Node *(*mutator) (),
2770 Assert(query != NULL && IsA(query, Query));
2772 MUTATE(query->targetList, query->targetList, List *);
2773 MUTATE(query->jointree, query->jointree, FromExpr *);
2774 MUTATE(query->setOperations, query->setOperations, Node *);
2775 MUTATE(query->havingQual, query->havingQual, Node *);
2776 foreach(rt, query->rtable)
2778 RangeTblEntry *rte = (RangeTblEntry *) lfirst(rt);
2779 RangeTblEntry *newrte;
2781 switch (rte->rtekind)
2785 /* nothing to do, don't bother to make a copy */
2788 if (! (flags & QTW_IGNORE_SUBQUERIES))
2790 FLATCOPY(newrte, rte, RangeTblEntry);
2791 CHECKFLATCOPY(newrte->subquery, rte->subquery, Query);
2792 MUTATE(newrte->subquery, newrte->subquery, Query *);
2797 if (! (flags & QTW_IGNORE_JOINALIASES))
2799 FLATCOPY(newrte, rte, RangeTblEntry);
2800 MUTATE(newrte->joinaliasvars, rte->joinaliasvars, List *);
2805 FLATCOPY(newrte, rte, RangeTblEntry);
2806 MUTATE(newrte->funcexpr, rte->funcexpr, Node *);
2810 newrt = lappend(newrt, rte);
2812 query->rtable = newrt;