1 /*-------------------------------------------------------------------------
4 * routines to manipulate qualification clauses
6 * Portions Copyright (c) 1996-2001, 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.95 2002/03/21 16:00:44 tgl Exp $
14 * AUTHOR DATE MAJOR EVENT
15 * Andrew Yu Nov 3, 1994 clause.c and clauses.c combined
17 *-------------------------------------------------------------------------
22 #include "catalog/pg_operator.h"
23 #include "catalog/pg_proc.h"
24 #include "catalog/pg_type.h"
25 #include "executor/executor.h"
26 #include "nodes/makefuncs.h"
27 #include "nodes/nodeFuncs.h"
28 #include "optimizer/clauses.h"
29 #include "optimizer/tlist.h"
30 #include "optimizer/var.h"
31 #include "parser/parsetree.h"
32 #include "utils/datum.h"
33 #include "utils/lsyscache.h"
34 #include "utils/syscache.h"
37 /* note that pg_type.h hardwires size of bool as 1 ... duplicate it */
38 #define MAKEBOOLCONST(val,isnull) \
39 ((Node *) makeConst(BOOLOID, 1, (Datum) (val), \
40 (isnull), true, false, false))
46 } check_subplans_for_ungrouped_vars_context;
48 static bool contain_agg_clause_walker(Node *node, void *context);
49 static bool pull_agg_clause_walker(Node *node, List **listptr);
50 static bool contain_iter_clause_walker(Node *node, void *context);
51 static bool contain_subplans_walker(Node *node, void *context);
52 static bool pull_subplans_walker(Node *node, List **listptr);
53 static bool check_subplans_for_ungrouped_vars_walker(Node *node,
54 check_subplans_for_ungrouped_vars_context * context);
55 static bool contain_noncachable_functions_walker(Node *node, void *context);
56 static Node *eval_const_expressions_mutator(Node *node, void *context);
57 static Expr *simplify_op_or_func(Expr *expr, List *args);
61 make_clause(int type, Node *oper, List *args)
63 Expr *expr = makeNode(Expr);
70 expr->typeOid = BOOLOID;
73 expr->typeOid = ((Oper *) oper)->opresulttype;
76 expr->typeOid = ((Func *) oper)->functype;
79 elog(ERROR, "make_clause: unsupported type %d", type);
83 expr->oper = oper; /* ignored for AND, OR, NOT */
89 /*****************************************************************************
90 * OPERATOR clause functions
91 *****************************************************************************/
97 * Returns t iff the clause is an operator clause:
98 * (op expr expr) or (op expr).
100 * [historical note: is_clause has the exact functionality and is used
101 * throughout the code. They're renamed to is_opclause for clarity.
105 is_opclause(Node *clause)
107 return (clause != NULL &&
109 ((Expr *) clause)->opType == OP_EXPR);
114 * Creates a clause given its operator left operand and right
115 * operand (if it is non-null).
119 make_opclause(Oper *op, Var *leftop, Var *rightop)
121 Expr *expr = makeNode(Expr);
123 expr->typeOid = op->opresulttype;
124 expr->opType = OP_EXPR;
125 expr->oper = (Node *) op;
127 expr->args = makeList2(leftop, rightop);
129 expr->args = makeList1(leftop);
136 * Returns the left operand of a clause of the form (op expr expr)
139 * NB: for historical reasons, the result is declared Var *, even
140 * though many callers can cope with results that are not Vars.
141 * The result really ought to be declared Expr * or Node *.
144 get_leftop(Expr *clause)
146 if (clause->args != NULL)
147 return lfirst(clause->args);
155 * Returns the right operand in a clause of the form (op expr expr).
156 * NB: result will be NULL if applied to a unary op clause.
159 get_rightop(Expr *clause)
161 if (clause->args != NULL && lnext(clause->args) != NULL)
162 return lfirst(lnext(clause->args));
167 /*****************************************************************************
168 * FUNC clause functions
169 *****************************************************************************/
174 * Returns t iff the clause is a function clause: (func { expr }).
178 is_funcclause(Node *clause)
180 return (clause != NULL &&
182 ((Expr *) clause)->opType == FUNC_EXPR);
188 * Creates a function clause given the FUNC node and the functional
193 make_funcclause(Func *func, List *funcargs)
195 Expr *expr = makeNode(Expr);
197 expr->typeOid = func->functype;
198 expr->opType = FUNC_EXPR;
199 expr->oper = (Node *) func;
200 expr->args = funcargs;
204 /*****************************************************************************
205 * OR clause functions
206 *****************************************************************************/
211 * Returns t iff the clause is an 'or' clause: (OR { expr }).
215 or_clause(Node *clause)
217 return (clause != NULL &&
219 ((Expr *) clause)->opType == OR_EXPR);
225 * Creates an 'or' clause given a list of its subclauses.
229 make_orclause(List *orclauses)
231 Expr *expr = makeNode(Expr);
233 expr->typeOid = BOOLOID;
234 expr->opType = OR_EXPR;
236 expr->args = orclauses;
240 /*****************************************************************************
241 * NOT clause functions
242 *****************************************************************************/
247 * Returns t iff this is a 'not' clause: (NOT expr).
251 not_clause(Node *clause)
253 return (clause != NULL &&
255 ((Expr *) clause)->opType == NOT_EXPR);
261 * Create a 'not' clause given the expression to be negated.
265 make_notclause(Expr *notclause)
267 Expr *expr = makeNode(Expr);
269 expr->typeOid = BOOLOID;
270 expr->opType = NOT_EXPR;
272 expr->args = makeList1(notclause);
279 * Retrieve the clause within a 'not' clause
283 get_notclausearg(Expr *notclause)
285 return lfirst(notclause->args);
288 /*****************************************************************************
289 * AND clause functions
290 *****************************************************************************/
296 * Returns t iff its argument is an 'and' clause: (AND { expr }).
300 and_clause(Node *clause)
302 return (clause != NULL &&
304 ((Expr *) clause)->opType == AND_EXPR);
310 * Create an 'and' clause given its arguments in a list.
313 make_andclause(List *andclauses)
315 Expr *expr = makeNode(Expr);
317 expr->typeOid = BOOLOID;
318 expr->opType = AND_EXPR;
320 expr->args = andclauses;
327 * Variant of make_andclause for ANDing two qual conditions together.
328 * Qual conditions have the property that a NULL nodetree is interpreted
332 make_and_qual(Node *qual1, Node *qual2)
338 return (Node *) make_andclause(makeList2(qual1, qual2));
342 * Sometimes (such as in the result of canonicalize_qual or the input of
343 * ExecQual), we use lists of expression nodes with implicit AND semantics.
345 * These functions convert between an AND-semantics expression list and the
346 * ordinary representation of a boolean expression.
348 * Note that an empty list is considered equivalent to TRUE.
351 make_ands_explicit(List *andclauses)
353 if (andclauses == NIL)
354 return (Expr *) MAKEBOOLCONST(true, false);
355 else if (lnext(andclauses) == NIL)
356 return (Expr *) lfirst(andclauses);
358 return make_andclause(andclauses);
362 make_ands_implicit(Expr *clause)
365 * NB: because the parser sets the qual field to NULL in a query that
366 * has no WHERE clause, we must consider a NULL input clause as TRUE,
367 * even though one might more reasonably think it FALSE. Grumble. If
368 * this causes trouble, consider changing the parser's behavior.
371 return NIL; /* NULL -> NIL list == TRUE */
372 else if (and_clause((Node *) clause))
374 else if (IsA(clause, Const) &&
375 !((Const *) clause)->constisnull &&
376 DatumGetBool(((Const *) clause)->constvalue))
377 return NIL; /* constant TRUE input -> NIL list */
379 return makeList1(clause);
383 /*****************************************************************************
384 * Aggregate-function clause manipulation
385 *****************************************************************************/
389 * Recursively search for Aggref nodes within a clause.
391 * Returns true if any aggregate found.
394 contain_agg_clause(Node *clause)
396 return contain_agg_clause_walker(clause, NULL);
400 contain_agg_clause_walker(Node *node, void *context)
404 if (IsA(node, Aggref))
405 return true; /* abort the tree traversal and return
407 return expression_tree_walker(node, contain_agg_clause_walker, context);
412 * Recursively pulls all Aggref nodes from an expression tree.
414 * Returns list of Aggref nodes found. Note the nodes themselves are not
415 * copied, only referenced.
417 * Note: this also checks for nested aggregates, which are an error.
420 pull_agg_clause(Node *clause)
424 pull_agg_clause_walker(clause, &result);
429 pull_agg_clause_walker(Node *node, List **listptr)
433 if (IsA(node, Aggref))
435 *listptr = lappend(*listptr, node);
438 * Complain if the aggregate's argument contains any aggregates;
439 * nested agg functions are semantically nonsensical.
441 if (contain_agg_clause(((Aggref *) node)->target))
442 elog(ERROR, "Aggregate function calls may not be nested");
445 * Having checked that, we need not recurse into the argument.
449 return expression_tree_walker(node, pull_agg_clause_walker,
454 /*****************************************************************************
455 * Iter clause manipulation
456 *****************************************************************************/
459 * contain_iter_clause
460 * Recursively search for Iter nodes within a clause.
462 * Returns true if any Iter found.
464 * XXX Iter is a crock. It'd be better to look directly at each function
465 * or operator to see if it can return a set. However, that would require
466 * a lot of extra cycles as things presently stand. The return-type info
467 * for function and operator nodes should be extended to include whether
468 * the return is a set.
471 contain_iter_clause(Node *clause)
473 return contain_iter_clause_walker(clause, NULL);
477 contain_iter_clause_walker(Node *node, void *context)
482 return true; /* abort the tree traversal and return
484 return expression_tree_walker(node, contain_iter_clause_walker, context);
487 /*****************************************************************************
488 * Subplan clause manipulation
489 *****************************************************************************/
493 * Recursively search for subplan nodes within a clause.
495 * If we see a SubLink node, we will return TRUE. This is only possible if
496 * the expression tree hasn't yet been transformed by subselect.c. We do not
497 * know whether the node will produce a true subplan or just an initplan,
498 * but we make the conservative assumption that it will be a subplan.
500 * Returns true if any subplan found.
503 contain_subplans(Node *clause)
505 return contain_subplans_walker(clause, NULL);
509 contain_subplans_walker(Node *node, void *context)
513 if (is_subplan(node) || IsA(node, SubLink))
514 return true; /* abort the tree traversal and return
516 return expression_tree_walker(node, contain_subplans_walker, context);
521 * Recursively pulls all subplans from an expression tree.
523 * Returns list of subplan nodes found. Note the nodes themselves are not
524 * copied, only referenced.
527 pull_subplans(Node *clause)
531 pull_subplans_walker(clause, &result);
536 pull_subplans_walker(Node *node, List **listptr)
540 if (is_subplan(node))
542 *listptr = lappend(*listptr, ((Expr *) node)->oper);
543 /* fall through to check args to subplan */
545 return expression_tree_walker(node, pull_subplans_walker,
550 * check_subplans_for_ungrouped_vars
551 * Check for subplans that are being passed ungrouped variables as
552 * parameters; generate an error message if any are found.
554 * In most contexts, ungrouped variables will be detected by the parser (see
555 * parse_agg.c, check_ungrouped_columns()). But that routine currently does
556 * not check subplans, because the necessary info is not computed until the
557 * planner runs. So we do it here, after we have processed sublinks into
558 * subplans. This ought to be cleaned up someday.
560 * A deficiency in this scheme is that any outer reference var must be
561 * grouped by itself; we don't recognize groupable expressions within
562 * subselects. For example, consider
564 * (SELECT x FROM bar where y = (foo.a + foo.b))
567 * This query will be rejected although it could be allowed.
570 check_subplans_for_ungrouped_vars(Query *query)
572 check_subplans_for_ungrouped_vars_context context;
575 context.query = query;
578 * Build a list of the acceptable GROUP BY expressions for use in the
579 * walker (to avoid repeated scans of the targetlist within the
580 * recursive routine).
582 context.groupClauses = NIL;
583 foreach(gl, query->groupClause)
585 GroupClause *grpcl = lfirst(gl);
588 expr = get_sortgroupclause_expr(grpcl, query->targetList);
589 context.groupClauses = lcons(expr, context.groupClauses);
593 * Recursively scan the targetlist and the HAVING clause. WHERE and
594 * JOIN/ON conditions are not examined, since they are evaluated
597 check_subplans_for_ungrouped_vars_walker((Node *) query->targetList,
599 check_subplans_for_ungrouped_vars_walker(query->havingQual,
602 freeList(context.groupClauses);
606 check_subplans_for_ungrouped_vars_walker(Node *node,
607 check_subplans_for_ungrouped_vars_context * context)
613 if (IsA(node, Const) ||IsA(node, Param))
614 return false; /* constants are always acceptable */
617 * If we find an aggregate function, do not recurse into its
618 * arguments. Subplans invoked within aggregate calls are allowed to
619 * receive ungrouped variables. (This test and the next one should
620 * match the logic in parse_agg.c's check_ungrouped_columns().)
622 if (IsA(node, Aggref))
626 * Check to see if subexpression as a whole matches any GROUP BY item.
627 * We need to do this at every recursion level so that we recognize
628 * GROUPed-BY expressions before reaching variables within them.
630 foreach(gl, context->groupClauses)
632 if (equal(node, lfirst(gl)))
633 return false; /* acceptable, do not descend more */
637 * We can ignore Vars other than in subplan args lists, since the
638 * parser already checked 'em.
640 if (is_subplan(node))
643 * The args list of the subplan node represents attributes from
644 * outside passed into the sublink.
648 foreach(t, ((Expr *) node)->args)
650 Node *thisarg = lfirst(t);
652 bool contained_in_group_clause;
655 * We do not care about args that are not local variables;
656 * params or outer-level vars are not our responsibility to
657 * check. (The outer-level query passing them to us needs to
660 if (!IsA(thisarg, Var))
662 var = (Var *) thisarg;
663 if (var->varlevelsup > 0)
667 * Else, see if it is a grouping column.
669 contained_in_group_clause = false;
670 foreach(gl, context->groupClauses)
672 if (equal(thisarg, lfirst(gl)))
674 contained_in_group_clause = true;
679 if (!contained_in_group_clause)
681 /* Found an ungrouped argument. Complain. */
685 Assert(var->varno > 0 &&
686 (int) var->varno <= length(context->query->rtable));
687 rte = rt_fetch(var->varno, context->query->rtable);
688 attname = get_rte_attribute_name(rte, var->varattno);
689 elog(ERROR, "Sub-SELECT uses un-GROUPed attribute %s.%s from outer query",
690 rte->eref->aliasname, attname);
694 return expression_tree_walker(node,
695 check_subplans_for_ungrouped_vars_walker,
700 /*****************************************************************************
701 * Check clauses for noncachable functions
702 *****************************************************************************/
705 * contain_noncachable_functions
706 * Recursively search for noncachable functions within a clause.
708 * Returns true if any noncachable function (or operator implemented by a
709 * noncachable function) is found. This test is needed so that we don't
710 * mistakenly think that something like "WHERE random() < 0.5" can be treated
711 * as a constant qualification.
713 * XXX we do not examine sublinks/subplans to see if they contain uses of
714 * noncachable functions. It's not real clear if that is correct or not...
717 contain_noncachable_functions(Node *clause)
719 return contain_noncachable_functions_walker(clause, NULL);
723 contain_noncachable_functions_walker(Node *node, void *context)
729 Expr *expr = (Expr *) node;
731 switch (expr->opType)
734 if (!op_iscachable(((Oper *) expr->oper)->opno))
738 if (!func_iscachable(((Func *) expr->oper)->funcid))
745 return expression_tree_walker(node, contain_noncachable_functions_walker,
750 /*****************************************************************************
751 * Check for "pseudo-constant" clauses
752 *****************************************************************************/
755 * is_pseudo_constant_clause
756 * Detect whether a clause is "constant", ie, it contains no variables
757 * of the current query level and no uses of noncachable functions.
758 * Such a clause is not necessarily a true constant: it can still contain
759 * Params and outer-level Vars. However, its value will be constant over
760 * any one scan of the current query, so it can be used as an indexscan
761 * key or (if a top-level qual) can be pushed up to become a gating qual.
764 is_pseudo_constant_clause(Node *clause)
767 * We could implement this check in one recursive scan. But since the
768 * check for noncachable functions is both moderately expensive and
769 * unlikely to fail, it seems better to look for Vars first and only
770 * check for noncachable functions if we find no Vars.
772 if (!contain_var_clause(clause) &&
773 !contain_noncachable_functions(clause))
779 * pull_constant_clauses
780 * Scan through a list of qualifications and separate "constant" quals
781 * from those that are not.
783 * Returns a list of the pseudo-constant clauses in constantQual and the
784 * remaining quals as the return value.
787 pull_constant_clauses(List *quals, List **constantQual)
789 List *constqual = NIL;
790 List *restqual = NIL;
795 Node *qual = (Node *) lfirst(q);
797 if (is_pseudo_constant_clause(qual))
798 constqual = lappend(constqual, qual);
800 restqual = lappend(restqual, qual);
802 *constantQual = constqual;
807 /*****************************************************************************
808 * Tests on clauses of queries
810 * Possibly this code should go someplace else, since this isn't quite the
811 * same meaning of "clause" as is used elsewhere in this module. But I can't
812 * think of a better place for it...
813 *****************************************************************************/
816 * Test whether a sort/group reference value appears in the given list of
817 * SortClause (or GroupClause) nodes.
819 * Because GroupClause is typedef'd as SortClause, either kind of
820 * node list can be passed without casting.
823 sortgroupref_is_present(Index sortgroupref, List *clauselist)
827 foreach(clause, clauselist)
829 SortClause *scl = (SortClause *) lfirst(clause);
831 if (scl->tleSortGroupRef == sortgroupref)
838 * Test whether a query uses DISTINCT ON, ie, has a distinct-list that is
839 * not the same as the set of output columns.
842 has_distinct_on_clause(Query *query)
846 /* Is there a DISTINCT clause at all? */
847 if (query->distinctClause == NIL)
851 * If the DISTINCT list contains all the nonjunk targetlist items, and
852 * nothing else (ie, no junk tlist items), then it's a simple
853 * DISTINCT, else it's DISTINCT ON. We do not require the lists to be
854 * in the same order (since the parser may have adjusted the DISTINCT
855 * clause ordering to agree with ORDER BY). Furthermore, a
856 * non-DISTINCT junk tlist item that is in the sortClause is also
857 * evidence of DISTINCT ON, since we don't allow ORDER BY on junk
858 * tlist items when plain DISTINCT is used.
860 * This code assumes that the DISTINCT list is valid, ie, all its entries
861 * match some entry of the tlist.
863 foreach(targetList, query->targetList)
865 TargetEntry *tle = (TargetEntry *) lfirst(targetList);
866 Index ressortgroupref = tle->resdom->ressortgroupref;
868 if (ressortgroupref == 0)
870 if (tle->resdom->resjunk)
871 continue; /* we can ignore unsorted junk cols */
872 return true; /* definitely not in DISTINCT list */
874 if (sortgroupref_is_present(ressortgroupref, query->distinctClause))
876 if (tle->resdom->resjunk)
877 return true; /* junk TLE in DISTINCT means DISTINCT ON */
878 /* else this TLE is okay, keep looking */
882 /* This TLE is not in DISTINCT list */
883 if (!tle->resdom->resjunk)
884 return true; /* non-junk, non-DISTINCT, so DISTINCT ON */
885 if (sortgroupref_is_present(ressortgroupref, query->sortClause))
886 return true; /* sorted, non-distinct junk */
887 /* unsorted junk is okay, keep looking */
890 /* It's a simple DISTINCT */
895 /*****************************************************************************
897 * General clause-manipulating routines *
899 *****************************************************************************/
902 * clause_get_relids_vars
903 * Retrieves distinct relids and vars appearing within a clause.
905 * '*relids' is set to an integer list of all distinct "varno"s appearing
906 * in Vars within the clause.
907 * '*vars' is set to a list of all distinct Vars appearing within the clause.
908 * Var nodes are considered distinct if they have different varno
909 * or varattno values. If there are several occurrences of the same
910 * varno/varattno, you get a randomly chosen one...
912 * Note that upper-level vars are ignored, since they normally will
913 * become Params with respect to this query level.
916 clause_get_relids_vars(Node *clause, Relids *relids, List **vars)
918 List *clvars = pull_var_clause(clause, false);
919 List *varno_list = NIL;
920 List *var_list = NIL;
925 Var *var = (Var *) lfirst(i);
928 if (!intMember(var->varno, varno_list))
929 varno_list = lconsi(var->varno, varno_list);
930 foreach(vi, var_list)
932 Var *in_list = (Var *) lfirst(vi);
934 if (in_list->varno == var->varno &&
935 in_list->varattno == var->varattno)
939 var_list = lcons(var, var_list);
943 *relids = varno_list;
949 * (formerly clause_relids)
951 * Returns the number of different relations referenced in 'clause'.
954 NumRelids(Node *clause)
956 List *varno_list = pull_varnos(clause);
957 int result = length(varno_list);
959 freeList(varno_list);
963 /*--------------------
964 * CommuteClause: commute a binary operator clause
966 * XXX the clause is destructively modified!
967 *--------------------
970 CommuteClause(Expr *clause)
974 Form_pg_operator commuTup;
978 if (!is_opclause((Node *) clause) ||
979 length(clause->args) != 2)
980 elog(ERROR, "CommuteClause: applied to non-binary-operator clause");
982 opoid = ((Oper *) clause->oper)->opno;
984 optup = SearchSysCache(OPEROID,
985 ObjectIdGetDatum(get_commutator(opoid)),
987 if (!HeapTupleIsValid(optup))
988 elog(ERROR, "CommuteClause: no commutator for operator %u", opoid);
990 commuTup = (Form_pg_operator) GETSTRUCT(optup);
992 commu = makeOper(optup->t_data->t_oid,
994 commuTup->oprresult);
996 ReleaseSysCache(optup);
999 * re-form the clause in-place!
1001 clause->oper = (Node *) commu;
1002 temp = lfirst(clause->args);
1003 lfirst(clause->args) = lsecond(clause->args);
1004 lsecond(clause->args) = temp;
1008 /*--------------------
1009 * eval_const_expressions
1011 * Reduce any recognizably constant subexpressions of the given
1012 * expression tree, for example "2 + 2" => "4". More interestingly,
1013 * we can reduce certain boolean expressions even when they contain
1014 * non-constant subexpressions: "x OR true" => "true" no matter what
1015 * the subexpression x is. (XXX We assume that no such subexpression
1016 * will have important side-effects, which is not necessarily a good
1017 * assumption in the presence of user-defined functions; do we need a
1018 * pg_proc flag that prevents discarding the execution of a function?)
1020 * We do understand that certain functions may deliver non-constant
1021 * results even with constant inputs, "nextval()" being the classic
1022 * example. Functions that are not marked "proiscachable" in pg_proc
1023 * will not be pre-evaluated here, although we will reduce their
1024 * arguments as far as possible. Functions that are the arguments
1025 * of Iter nodes are also not evaluated.
1027 * We assume that the tree has already been type-checked and contains
1028 * only operators and functions that are reasonable to try to execute.
1030 * This routine should be invoked before converting sublinks to subplans
1031 * (subselect.c's SS_process_sublinks()). The converted form contains
1032 * bogus "Const" nodes that are actually placeholders where the executor
1033 * will insert values from the inner plan, and obviously we mustn't try
1034 * to reduce the expression as though these were really constants.
1035 * As a safeguard, if we happen to find an already-converted SubPlan node,
1036 * we will return it unchanged rather than recursing into it.
1037 *--------------------
1040 eval_const_expressions(Node *node)
1042 /* no context or special setup needed, so away we go... */
1043 return eval_const_expressions_mutator(node, NULL);
1047 eval_const_expressions_mutator(Node *node, void *context)
1051 if (IsA(node, Expr))
1053 Expr *expr = (Expr *) node;
1059 * Reduce constants in the Expr's arguments. We know args is
1060 * either NIL or a List node, so we can call
1061 * expression_tree_mutator directly rather than recursing to self.
1063 args = (List *) expression_tree_mutator((Node *) expr->args,
1064 eval_const_expressions_mutator,
1067 switch (expr->opType)
1073 * Code for op/func case is pretty bulky, so split it out
1074 * as a separate function.
1076 newexpr = simplify_op_or_func(expr, args);
1077 if (newexpr) /* successfully simplified it */
1078 return (Node *) newexpr;
1081 * else fall out to build new Expr node with simplified
1089 * OR arguments are handled as follows:
1090 * non constant: keep
1091 * FALSE: drop (does not affect result)
1092 * TRUE: force result to TRUE
1093 * NULL: keep only one
1094 * We keep one NULL input because ExecEvalOr returns NULL
1095 * when no input is TRUE and at least one is NULL.
1098 List *newargs = NIL;
1100 bool haveNull = false;
1101 bool forceTrue = false;
1105 if (!IsA(lfirst(arg), Const))
1107 newargs = lappend(newargs, lfirst(arg));
1110 const_input = (Const *) lfirst(arg);
1111 if (const_input->constisnull)
1113 else if (DatumGetBool(const_input->constvalue))
1115 /* otherwise, we can drop the constant-false input */
1119 * We could return TRUE before falling out of the
1120 * loop, but this coding method will be easier to
1121 * adapt if we ever add a notion of non-removable
1122 * functions. We'd need to check all the inputs for
1126 return MAKEBOOLCONST(true, false);
1128 newargs = lappend(newargs, MAKEBOOLCONST(false, true));
1129 /* If all the inputs are FALSE, result is FALSE */
1131 return MAKEBOOLCONST(false, false);
1132 /* If only one nonconst-or-NULL input, it's the result */
1133 if (lnext(newargs) == NIL)
1134 return (Node *) lfirst(newargs);
1135 /* Else we still need an OR node */
1136 return (Node *) make_orclause(newargs);
1142 * AND arguments are handled as follows:
1143 * non constant: keep
1144 * TRUE: drop (does not affect result)
1145 * FALSE: force result to FALSE
1146 * NULL: keep only one
1147 * We keep one NULL input because ExecEvalAnd returns NULL
1148 * when no input is FALSE and at least one is NULL.
1151 List *newargs = NIL;
1153 bool haveNull = false;
1154 bool forceFalse = false;
1158 if (!IsA(lfirst(arg), Const))
1160 newargs = lappend(newargs, lfirst(arg));
1163 const_input = (Const *) lfirst(arg);
1164 if (const_input->constisnull)
1166 else if (!DatumGetBool(const_input->constvalue))
1168 /* otherwise, we can drop the constant-true input */
1172 * We could return FALSE before falling out of the
1173 * loop, but this coding method will be easier to
1174 * adapt if we ever add a notion of non-removable
1175 * functions. We'd need to check all the inputs for
1179 return MAKEBOOLCONST(false, false);
1181 newargs = lappend(newargs, MAKEBOOLCONST(false, true));
1182 /* If all the inputs are TRUE, result is TRUE */
1184 return MAKEBOOLCONST(true, false);
1185 /* If only one nonconst-or-NULL input, it's the result */
1186 if (lnext(newargs) == NIL)
1187 return (Node *) lfirst(newargs);
1188 /* Else we still need an AND node */
1189 return (Node *) make_andclause(newargs);
1192 Assert(length(args) == 1);
1193 if (!IsA(lfirst(args), Const))
1195 const_input = (Const *) lfirst(args);
1196 /* NOT NULL => NULL */
1197 if (const_input->constisnull)
1198 return MAKEBOOLCONST(false, true);
1199 /* otherwise pretty easy */
1200 return MAKEBOOLCONST(!DatumGetBool(const_input->constvalue),
1205 * Safety measure per notes at head of this routine:
1206 * return a SubPlan unchanged. Too late to do anything
1207 * with it. The arglist simplification above was wasted
1208 * work (the list probably only contains Var nodes
1211 return (Node *) expr;
1213 elog(ERROR, "eval_const_expressions: unexpected opType %d",
1214 (int) expr->opType);
1219 * If we break out of the above switch on opType, then the
1220 * expression cannot be simplified any further, so build and
1221 * return a replacement Expr node using the possibly-simplified
1222 * arguments and the original oper node. Can't use make_clause()
1223 * here because we want to be sure the typeOid field is
1226 newexpr = makeNode(Expr);
1227 newexpr->typeOid = expr->typeOid;
1228 newexpr->opType = expr->opType;
1229 newexpr->oper = expr->oper;
1230 newexpr->args = args;
1231 return (Node *) newexpr;
1233 if (IsA(node, RelabelType))
1236 * If we can simplify the input to a constant, then we don't need
1237 * the RelabelType node anymore: just change the type field of the
1238 * Const node. Otherwise, must copy the RelabelType node.
1240 RelabelType *relabel = (RelabelType *) node;
1243 arg = eval_const_expressions_mutator(relabel->arg, context);
1246 * If we find stacked RelabelTypes (eg, from foo :: int :: oid) we
1247 * can discard all but the top one.
1249 while (arg && IsA(arg, RelabelType))
1250 arg = ((RelabelType *) arg)->arg;
1252 if (arg && IsA(arg, Const))
1254 Const *con = (Const *) arg;
1256 con->consttype = relabel->resulttype;
1259 * relabel's resulttypmod is discarded, which is OK for now;
1260 * if the type actually needs a runtime length coercion then
1261 * there should be a function call to do it just above this
1264 return (Node *) con;
1268 RelabelType *newrelabel = makeNode(RelabelType);
1270 newrelabel->arg = arg;
1271 newrelabel->resulttype = relabel->resulttype;
1272 newrelabel->resulttypmod = relabel->resulttypmod;
1273 return (Node *) newrelabel;
1276 if (IsA(node, CaseExpr))
1280 * CASE expressions can be simplified if there are constant
1281 * condition clauses:
1282 * FALSE (or NULL): drop the alternative
1283 * TRUE: drop all remaining alternatives
1284 * If the first non-FALSE alternative is a constant TRUE, we can
1285 * simplify the entire CASE to that alternative's expression.
1286 * If there are no non-FALSE alternatives, we simplify the entire
1287 * CASE to the default result (ELSE result).
1290 CaseExpr *caseexpr = (CaseExpr *) node;
1292 List *newargs = NIL;
1297 foreach(arg, caseexpr->args)
1299 /* Simplify this alternative's condition and result */
1300 CaseWhen *casewhen = (CaseWhen *)
1301 expression_tree_mutator((Node *) lfirst(arg),
1302 eval_const_expressions_mutator,
1305 Assert(IsA(casewhen, CaseWhen));
1306 if (casewhen->expr == NULL ||
1307 !IsA(casewhen->expr, Const))
1309 newargs = lappend(newargs, casewhen);
1312 const_input = (Const *) casewhen->expr;
1313 if (const_input->constisnull ||
1314 !DatumGetBool(const_input->constvalue))
1315 continue; /* drop alternative with FALSE condition */
1318 * Found a TRUE condition. If it's the first (un-dropped)
1319 * alternative, the CASE reduces to just this alternative.
1322 return casewhen->result;
1325 * Otherwise, add it to the list, and drop all the rest.
1327 newargs = lappend(newargs, casewhen);
1331 /* Simplify the default result */
1332 defresult = eval_const_expressions_mutator(caseexpr->defresult,
1336 * If no non-FALSE alternatives, CASE reduces to the default
1341 /* Otherwise we need a new CASE node */
1342 newcase = makeNode(CaseExpr);
1343 newcase->casetype = caseexpr->casetype;
1344 newcase->arg = NULL;
1345 newcase->args = newargs;
1346 newcase->defresult = defresult;
1347 return (Node *) newcase;
1349 if (IsA(node, Iter))
1352 * The argument of an Iter is normally a function call. We must
1353 * not try to eliminate the function, but we can try to simplify
1354 * its arguments. If, by chance, the arg is NOT a function then
1355 * we go ahead and try to simplify it (by falling into
1356 * expression_tree_mutator). Is that the right thing?
1358 Iter *iter = (Iter *) node;
1360 if (is_funcclause(iter->iterexpr))
1362 Expr *func = (Expr *) iter->iterexpr;
1366 newfunc = makeNode(Expr);
1367 newfunc->typeOid = func->typeOid;
1368 newfunc->opType = func->opType;
1369 newfunc->oper = func->oper;
1370 newfunc->args = (List *)
1371 expression_tree_mutator((Node *) func->args,
1372 eval_const_expressions_mutator,
1374 newiter = makeNode(Iter);
1375 newiter->iterexpr = (Node *) newfunc;
1376 newiter->itertype = iter->itertype;
1377 return (Node *) newiter;
1382 * For any node type not handled above, we recurse using
1383 * expression_tree_mutator, which will copy the node unchanged but try
1384 * to simplify its arguments (if any) using this routine. For example:
1385 * we cannot eliminate an ArrayRef node, but we might be able to
1386 * simplify constant expressions in its subscripts.
1388 return expression_tree_mutator(node, eval_const_expressions_mutator,
1393 * Subroutine for eval_const_expressions: try to evaluate an op or func
1395 * Inputs are the op or func Expr node, and the pre-simplified argument list.
1396 * Returns a simplified expression if successful, or NULL if cannot
1397 * simplify the op/func.
1399 * XXX Possible future improvement: if the func is SQL-language, and its
1400 * definition is simply "SELECT expression", we could parse and substitute
1401 * the expression here. This would avoid much runtime overhead, and perhaps
1402 * expose opportunities for constant-folding within the expression even if
1403 * not all the func's input args are constants. It'd be appropriate to do
1404 * that here, not in the parser, since we wouldn't want it to happen until
1405 * after rule substitution/rewriting.
1408 simplify_op_or_func(Expr *expr, List *args)
1413 HeapTuple func_tuple;
1414 Form_pg_proc funcform;
1419 bool resultTypByVal;
1421 ExprContext *econtext;
1423 bool has_nonconst_input = false;
1424 bool has_null_input = false;
1428 * Check for constant inputs and especially constant-NULL inputs.
1432 if (IsA(lfirst(arg), Const))
1433 has_null_input |= ((Const *) lfirst(arg))->constisnull;
1435 has_nonconst_input = true;
1439 * If the function is strict and has a constant-NULL input, it will
1440 * never be called at all, so we can replace the call by a NULL
1441 * constant even if there are other inputs that aren't constant.
1442 * Otherwise, we can only simplify if all inputs are constants. We can
1443 * skip the function lookup if neither case applies.
1445 if (has_nonconst_input && !has_null_input)
1449 * Get the function procedure's OID and look to see whether it is
1450 * marked proiscachable.
1452 * XXX would it be better to take the result type from the pg_proc tuple,
1453 * rather than the Oper or Func node?
1455 if (expr->opType == OP_EXPR)
1457 Oper *oper = (Oper *) expr->oper;
1459 replace_opid(oper); /* OK to scribble on input to this extent */
1460 funcid = oper->opid;
1461 result_typeid = oper->opresulttype;
1465 Func *func = (Func *) expr->oper;
1467 funcid = func->funcid;
1468 result_typeid = func->functype;
1472 * we could use func_iscachable() here, but we need several fields out
1473 * of the func tuple, so might as well just look it up once.
1475 func_tuple = SearchSysCache(PROCOID,
1476 ObjectIdGetDatum(funcid),
1478 if (!HeapTupleIsValid(func_tuple))
1479 elog(ERROR, "Function OID %u does not exist", funcid);
1480 funcform = (Form_pg_proc) GETSTRUCT(func_tuple);
1481 proiscachable = funcform->proiscachable;
1482 proisstrict = funcform->proisstrict;
1483 proretset = funcform->proretset;
1484 ReleaseSysCache(func_tuple);
1490 * Also check to make sure it doesn't return a set.
1496 * Now that we know if the function is strict, we can finish the
1497 * checks for simplifiable inputs that we started above.
1499 if (proisstrict && has_null_input)
1502 * It's strict and has NULL input, so must produce NULL output.
1503 * Return a NULL constant of the right type.
1505 return (Expr *) makeNullConst(result_typeid);
1509 * Otherwise, can simplify only if all inputs are constants. (For a
1510 * non-strict function, constant NULL inputs are treated the same as
1511 * constant non-NULL inputs.)
1513 if (has_nonconst_input)
1517 * OK, looks like we can simplify this operator/function.
1519 * We use the executor's routine ExecEvalExpr() to avoid duplication of
1520 * code and ensure we get the same result as the executor would get.
1522 * Build a new Expr node containing the already-simplified arguments. The
1523 * only other setup needed here is the replace_opid() that we already
1524 * did for the OP_EXPR case.
1526 newexpr = makeNode(Expr);
1527 newexpr->typeOid = expr->typeOid;
1528 newexpr->opType = expr->opType;
1529 newexpr->oper = expr->oper;
1530 newexpr->args = args;
1532 /* Get info needed about result datatype */
1533 get_typlenbyval(result_typeid, &resultTypLen, &resultTypByVal);
1536 * It is OK to pass a dummy econtext because none of the
1537 * ExecEvalExpr() code used in this situation will use econtext. That
1538 * might seem fortuitous, but it's not so unreasonable --- a constant
1539 * expression does not depend on context, by definition, n'est ce pas?
1541 econtext = MakeExprContext(NULL, CurrentMemoryContext);
1543 const_val = ExecEvalExprSwitchContext((Node *) newexpr, econtext,
1544 &const_is_null, NULL);
1546 /* Must copy result out of sub-context used by expression eval */
1548 const_val = datumCopy(const_val, resultTypByVal, resultTypLen);
1550 FreeExprContext(econtext);
1554 * Make the constant result node.
1556 return (Expr *) makeConst(result_typeid, resultTypLen,
1557 const_val, const_is_null,
1558 resultTypByVal, false, false);
1563 * Standard expression-tree walking support
1565 * We used to have near-duplicate code in many different routines that
1566 * understood how to recurse through an expression node tree. That was
1567 * a pain to maintain, and we frequently had bugs due to some particular
1568 * routine neglecting to support a particular node type. In most cases,
1569 * these routines only actually care about certain node types, and don't
1570 * care about other types except insofar as they have to recurse through
1571 * non-primitive node types. Therefore, we now provide generic tree-walking
1572 * logic to consolidate the redundant "boilerplate" code. There are
1573 * two versions: expression_tree_walker() and expression_tree_mutator().
1576 /*--------------------
1577 * expression_tree_walker() is designed to support routines that traverse
1578 * a tree in a read-only fashion (although it will also work for routines
1579 * that modify nodes in-place but never add/delete/replace nodes).
1580 * A walker routine should look like this:
1582 * bool my_walker (Node *node, my_struct *context)
1586 * // check for nodes that special work is required for, eg:
1587 * if (IsA(node, Var))
1589 * ... do special actions for Var nodes
1591 * else if (IsA(node, ...))
1593 * ... do special actions for other node types
1595 * // for any node type not specially processed, do:
1596 * return expression_tree_walker(node, my_walker, (void *) context);
1599 * The "context" argument points to a struct that holds whatever context
1600 * information the walker routine needs --- it can be used to return data
1601 * gathered by the walker, too. This argument is not touched by
1602 * expression_tree_walker, but it is passed down to recursive sub-invocations
1603 * of my_walker. The tree walk is started from a setup routine that
1604 * fills in the appropriate context struct, calls my_walker with the top-level
1605 * node of the tree, and then examines the results.
1607 * The walker routine should return "false" to continue the tree walk, or
1608 * "true" to abort the walk and immediately return "true" to the top-level
1609 * caller. This can be used to short-circuit the traversal if the walker
1610 * has found what it came for. "false" is returned to the top-level caller
1611 * iff no invocation of the walker returned "true".
1613 * The node types handled by expression_tree_walker include all those
1614 * normally found in target lists and qualifier clauses during the planning
1615 * stage. In particular, it handles List nodes since a cnf-ified qual clause
1616 * will have List structure at the top level, and it handles TargetEntry nodes
1617 * so that a scan of a target list can be handled without additional code.
1618 * (But only the "expr" part of a TargetEntry is examined, unless the walker
1619 * chooses to process TargetEntry nodes specially.) Also, RangeTblRef,
1620 * FromExpr, JoinExpr, and SetOperationStmt nodes are handled, so that query
1621 * jointrees and setOperation trees can be processed without additional code.
1623 * expression_tree_walker will handle SubLink and SubPlan nodes by recursing
1624 * normally into the "lefthand" arguments (which belong to the outer plan).
1625 * It will also call the walker on the sub-Query node; however, when
1626 * expression_tree_walker itself is called on a Query node, it does nothing
1627 * and returns "false". The net effect is that unless the walker does
1628 * something special at a Query node, sub-selects will not be visited
1629 * during an expression tree walk. This is exactly the behavior wanted
1630 * in many cases --- and for those walkers that do want to recurse into
1631 * sub-selects, special behavior is typically needed anyway at the entry
1632 * to a sub-select (such as incrementing a depth counter). A walker that
1633 * wants to examine sub-selects should include code along the lines of:
1635 * if (IsA(node, Query))
1637 * adjust context for subquery;
1638 * result = query_tree_walker((Query *) node, my_walker, context,
1639 * true); // to visit subquery RTEs too
1640 * restore context if needed;
1644 * query_tree_walker is a convenience routine (see below) that calls the
1645 * walker on all the expression subtrees of the given Query node.
1647 * NOTE: currently, because make_subplan() clears the subselect link in
1648 * a SubLink node, it is not actually possible to recurse into subselects
1649 * of an already-planned expression tree. This is OK for current uses,
1650 * but ought to be cleaned up when we redesign querytree processing.
1651 *--------------------
1655 expression_tree_walker(Node *node,
1662 * The walker has already visited the current node, and so we need
1663 * only recurse into any sub-nodes it has.
1665 * We assume that the walker is not interested in List nodes per se, so
1666 * when we expect a List we just recurse directly to self without
1667 * bothering to call the walker.
1671 switch (nodeTag(node))
1677 /* primitive node types with no subnodes */
1681 Expr *expr = (Expr *) node;
1683 if (expr->opType == SUBPLAN_EXPR)
1685 /* recurse to the SubLink node (skipping SubPlan!) */
1686 if (walker((Node *) ((SubPlan *) expr->oper)->sublink,
1690 /* for all Expr node types, examine args list */
1691 if (expression_tree_walker((Node *) expr->args,
1697 return walker(((Aggref *) node)->target, context);
1699 return walker(((Iter *) node)->iterexpr, context);
1702 ArrayRef *aref = (ArrayRef *) node;
1704 /* recurse directly for upper/lower array index lists */
1705 if (expression_tree_walker((Node *) aref->refupperindexpr,
1708 if (expression_tree_walker((Node *) aref->reflowerindexpr,
1711 /* walker must see the refexpr and refassgnexpr, however */
1712 if (walker(aref->refexpr, context))
1714 if (walker(aref->refassgnexpr, context))
1719 return walker(((FieldSelect *) node)->arg, context);
1721 return walker(((RelabelType *) node)->arg, context);
1724 CaseExpr *caseexpr = (CaseExpr *) node;
1726 /* we assume walker doesn't care about CaseWhens, either */
1727 foreach(temp, caseexpr->args)
1729 CaseWhen *when = (CaseWhen *) lfirst(temp);
1731 Assert(IsA(when, CaseWhen));
1732 if (walker(when->expr, context))
1734 if (walker(when->result, context))
1737 /* caseexpr->arg should be null, but we'll check it anyway */
1738 if (walker(caseexpr->arg, context))
1740 if (walker(caseexpr->defresult, context))
1745 return walker(((NullTest *) node)->arg, context);
1747 return walker(((BooleanTest *) node)->arg, context);
1750 SubLink *sublink = (SubLink *) node;
1753 * If the SubLink has already been processed by
1754 * subselect.c, it will have lefthand=NIL, and we need to
1755 * scan the oper list. Otherwise we only need to look at
1756 * the lefthand list (the incomplete Oper nodes in the
1757 * oper list are deemed uninteresting, perhaps even
1760 if (sublink->lefthand)
1762 if (walker((Node *) sublink->lefthand, context))
1767 if (walker((Node *) sublink->oper, context))
1772 * Also invoke the walker on the sublink's Query node, so
1773 * it can recurse into the sub-query if it wants to.
1775 return walker(sublink->subselect, context);
1779 /* Do nothing with a sub-Query, per discussion above */
1782 foreach(temp, (List *) node)
1784 if (walker((Node *) lfirst(temp), context))
1789 return walker(((TargetEntry *) node)->expr, context);
1792 FromExpr *from = (FromExpr *) node;
1794 if (walker(from->fromlist, context))
1796 if (walker(from->quals, context))
1802 JoinExpr *join = (JoinExpr *) node;
1804 if (walker(join->larg, context))
1806 if (walker(join->rarg, context))
1808 if (walker(join->quals, context))
1811 * alias clause, using list are deemed uninteresting.
1815 case T_SetOperationStmt:
1817 SetOperationStmt *setop = (SetOperationStmt *) node;
1819 if (walker(setop->larg, context))
1821 if (walker(setop->rarg, context))
1826 elog(ERROR, "expression_tree_walker: Unexpected node type %d",
1834 * query_tree_walker --- initiate a walk of a Query's expressions
1836 * This routine exists just to reduce the number of places that need to know
1837 * where all the expression subtrees of a Query are. Note it can be used
1838 * for starting a walk at top level of a Query regardless of whether the
1839 * walker intends to descend into subqueries. It is also useful for
1840 * descending into subqueries within a walker.
1842 * If visitQueryRTEs is true, the walker will also be called on sub-Query
1843 * nodes present in subquery rangetable entries of the given Query. This
1844 * is optional since some callers handle those sub-queries separately,
1845 * or don't really want to see subqueries anyway.
1848 query_tree_walker(Query *query,
1851 bool visitQueryRTEs)
1853 Assert(query != NULL && IsA(query, Query));
1855 if (walker((Node *) query->targetList, context))
1857 if (walker((Node *) query->jointree, context))
1859 if (walker(query->setOperations, context))
1861 if (walker(query->havingQual, context))
1867 foreach(rt, query->rtable)
1869 RangeTblEntry *rte = (RangeTblEntry *) lfirst(rt);
1872 if (walker(rte->subquery, context))
1880 /*--------------------
1881 * expression_tree_mutator() is designed to support routines that make a
1882 * modified copy of an expression tree, with some nodes being added,
1883 * removed, or replaced by new subtrees. The original tree is (normally)
1884 * not changed. Each recursion level is responsible for returning a copy of
1885 * (or appropriately modified substitute for) the subtree it is handed.
1886 * A mutator routine should look like this:
1888 * Node * my_mutator (Node *node, my_struct *context)
1892 * // check for nodes that special work is required for, eg:
1893 * if (IsA(node, Var))
1895 * ... create and return modified copy of Var node
1897 * else if (IsA(node, ...))
1899 * ... do special transformations of other node types
1901 * // for any node type not specially processed, do:
1902 * return expression_tree_mutator(node, my_mutator, (void *) context);
1905 * The "context" argument points to a struct that holds whatever context
1906 * information the mutator routine needs --- it can be used to return extra
1907 * data gathered by the mutator, too. This argument is not touched by
1908 * expression_tree_mutator, but it is passed down to recursive sub-invocations
1909 * of my_mutator. The tree walk is started from a setup routine that
1910 * fills in the appropriate context struct, calls my_mutator with the
1911 * top-level node of the tree, and does any required post-processing.
1913 * Each level of recursion must return an appropriately modified Node.
1914 * If expression_tree_mutator() is called, it will make an exact copy
1915 * of the given Node, but invoke my_mutator() to copy the sub-node(s)
1916 * of that Node. In this way, my_mutator() has full control over the
1917 * copying process but need not directly deal with expression trees
1918 * that it has no interest in.
1920 * Just as for expression_tree_walker, the node types handled by
1921 * expression_tree_mutator include all those normally found in target lists
1922 * and qualifier clauses during the planning stage.
1924 * expression_tree_mutator will handle a SUBPLAN_EXPR node by recursing into
1925 * the args and slink->oper lists (which belong to the outer plan), but it
1926 * will simply copy the link to the inner plan, since that's typically what
1927 * expression tree mutators want. A mutator that wants to modify the subplan
1928 * can force appropriate behavior by recognizing subplan expression nodes
1929 * and doing the right thing.
1931 * Bare SubLink nodes (without a SUBPLAN_EXPR) are handled by recursing into
1932 * the "lefthand" argument list only. (A bare SubLink should be seen only if
1933 * the tree has not yet been processed by subselect.c.) Again, this can be
1934 * overridden by the mutator, but it seems to be the most useful default
1936 *--------------------
1940 expression_tree_mutator(Node *node,
1941 Node *(*mutator) (),
1945 * The mutator has already decided not to modify the current node, but
1946 * we must call the mutator for any sub-nodes.
1949 #define FLATCOPY(newnode, node, nodetype) \
1950 ( (newnode) = makeNode(nodetype), \
1951 memcpy((newnode), (node), sizeof(nodetype)) )
1953 #define CHECKFLATCOPY(newnode, node, nodetype) \
1954 ( AssertMacro(IsA((node), nodetype)), \
1955 (newnode) = makeNode(nodetype), \
1956 memcpy((newnode), (node), sizeof(nodetype)) )
1958 #define MUTATE(newfield, oldfield, fieldtype) \
1959 ( (newfield) = (fieldtype) mutator((Node *) (oldfield), context) )
1963 switch (nodeTag(node))
1969 /* primitive node types with no subnodes */
1970 return (Node *) copyObject(node);
1973 Expr *expr = (Expr *) node;
1976 FLATCOPY(newnode, expr, Expr);
1978 if (expr->opType == SUBPLAN_EXPR)
1980 SubLink *oldsublink = ((SubPlan *) expr->oper)->sublink;
1981 SubPlan *newsubplan;
1983 /* flat-copy the oper node, which is a SubPlan */
1984 CHECKFLATCOPY(newsubplan, expr->oper, SubPlan);
1985 newnode->oper = (Node *) newsubplan;
1986 /* likewise its SubLink node */
1987 CHECKFLATCOPY(newsubplan->sublink, oldsublink, SubLink);
1990 * transform args list (params to be passed to
1993 MUTATE(newnode->args, expr->args, List *);
1994 /* transform sublink's oper list as well */
1995 MUTATE(newsubplan->sublink->oper, oldsublink->oper, List *);
1998 * but not the subplan itself, which is referenced
2005 * for other Expr node types, just transform args
2006 * list, linking to original oper node (OK?)
2008 MUTATE(newnode->args, expr->args, List *);
2010 return (Node *) newnode;
2015 Aggref *aggref = (Aggref *) node;
2018 FLATCOPY(newnode, aggref, Aggref);
2019 MUTATE(newnode->target, aggref->target, Node *);
2020 return (Node *) newnode;
2025 Iter *iter = (Iter *) node;
2028 FLATCOPY(newnode, iter, Iter);
2029 MUTATE(newnode->iterexpr, iter->iterexpr, Node *);
2030 return (Node *) newnode;
2035 ArrayRef *arrayref = (ArrayRef *) node;
2038 FLATCOPY(newnode, arrayref, ArrayRef);
2039 MUTATE(newnode->refupperindexpr, arrayref->refupperindexpr,
2041 MUTATE(newnode->reflowerindexpr, arrayref->reflowerindexpr,
2043 MUTATE(newnode->refexpr, arrayref->refexpr,
2045 MUTATE(newnode->refassgnexpr, arrayref->refassgnexpr,
2047 return (Node *) newnode;
2052 FieldSelect *fselect = (FieldSelect *) node;
2053 FieldSelect *newnode;
2055 FLATCOPY(newnode, fselect, FieldSelect);
2056 MUTATE(newnode->arg, fselect->arg, Node *);
2057 return (Node *) newnode;
2062 RelabelType *relabel = (RelabelType *) node;
2063 RelabelType *newnode;
2065 FLATCOPY(newnode, relabel, RelabelType);
2066 MUTATE(newnode->arg, relabel->arg, Node *);
2067 return (Node *) newnode;
2072 CaseExpr *caseexpr = (CaseExpr *) node;
2075 FLATCOPY(newnode, caseexpr, CaseExpr);
2076 MUTATE(newnode->args, caseexpr->args, List *);
2077 /* caseexpr->arg should be null, but we'll check it anyway */
2078 MUTATE(newnode->arg, caseexpr->arg, Node *);
2079 MUTATE(newnode->defresult, caseexpr->defresult, Node *);
2080 return (Node *) newnode;
2085 CaseWhen *casewhen = (CaseWhen *) node;
2088 FLATCOPY(newnode, casewhen, CaseWhen);
2089 MUTATE(newnode->expr, casewhen->expr, Node *);
2090 MUTATE(newnode->result, casewhen->result, Node *);
2091 return (Node *) newnode;
2096 NullTest *ntest = (NullTest *) node;
2099 FLATCOPY(newnode, ntest, NullTest);
2100 MUTATE(newnode->arg, ntest->arg, Node *);
2101 return (Node *) newnode;
2106 BooleanTest *btest = (BooleanTest *) node;
2107 BooleanTest *newnode;
2109 FLATCOPY(newnode, btest, BooleanTest);
2110 MUTATE(newnode->arg, btest->arg, Node *);
2111 return (Node *) newnode;
2117 * A "bare" SubLink (note we will not come here if we
2118 * found a SUBPLAN_EXPR node above it). Transform the
2119 * lefthand side, but not the oper list nor the subquery.
2121 SubLink *sublink = (SubLink *) node;
2124 FLATCOPY(newnode, sublink, SubLink);
2125 MUTATE(newnode->lefthand, sublink->lefthand, List *);
2126 return (Node *) newnode;
2132 * We assume the mutator isn't interested in the list
2133 * nodes per se, so just invoke it on each list element.
2134 * NOTE: this would fail badly on a list with integer
2137 List *resultlist = NIL;
2140 foreach(temp, (List *) node)
2142 resultlist = lappend(resultlist,
2143 mutator((Node *) lfirst(temp),
2146 return (Node *) resultlist;
2152 * We mutate the expression, but not the resdom, by
2155 TargetEntry *targetentry = (TargetEntry *) node;
2156 TargetEntry *newnode;
2158 FLATCOPY(newnode, targetentry, TargetEntry);
2159 MUTATE(newnode->expr, targetentry->expr, Node *);
2160 return (Node *) newnode;
2165 FromExpr *from = (FromExpr *) node;
2168 FLATCOPY(newnode, from, FromExpr);
2169 MUTATE(newnode->fromlist, from->fromlist, List *);
2170 MUTATE(newnode->quals, from->quals, Node *);
2171 return (Node *) newnode;
2176 JoinExpr *join = (JoinExpr *) node;
2179 FLATCOPY(newnode, join, JoinExpr);
2180 MUTATE(newnode->larg, join->larg, Node *);
2181 MUTATE(newnode->rarg, join->rarg, Node *);
2182 MUTATE(newnode->quals, join->quals, Node *);
2183 /* We do not mutate alias or using by default */
2184 return (Node *) newnode;
2187 case T_SetOperationStmt:
2189 SetOperationStmt *setop = (SetOperationStmt *) node;
2190 SetOperationStmt *newnode;
2192 FLATCOPY(newnode, setop, SetOperationStmt);
2193 MUTATE(newnode->larg, setop->larg, Node *);
2194 MUTATE(newnode->rarg, setop->rarg, Node *);
2195 return (Node *) newnode;
2199 elog(ERROR, "expression_tree_mutator: Unexpected node type %d",
2203 /* can't get here, but keep compiler happy */
2209 * query_tree_mutator --- initiate modification of a Query's expressions
2211 * This routine exists just to reduce the number of places that need to know
2212 * where all the expression subtrees of a Query are. Note it can be used
2213 * for starting a walk at top level of a Query regardless of whether the
2214 * mutator intends to descend into subqueries. It is also useful for
2215 * descending into subqueries within a mutator.
2217 * The specified Query node is modified-in-place; do a FLATCOPY() beforehand
2218 * if you don't want to change the original. All substructure is safely
2221 * If visitQueryRTEs is true, the mutator will also be called on sub-Query
2222 * nodes present in subquery rangetable entries of the given Query. This
2223 * is optional since some callers handle those sub-queries separately,
2224 * or don't really want to see subqueries anyway.
2227 query_tree_mutator(Query *query,
2228 Node *(*mutator) (),
2230 bool visitQueryRTEs)
2232 Assert(query != NULL && IsA(query, Query));
2234 MUTATE(query->targetList, query->targetList, List *);
2235 MUTATE(query->jointree, query->jointree, FromExpr *);
2236 MUTATE(query->setOperations, query->setOperations, Node *);
2237 MUTATE(query->havingQual, query->havingQual, Node *);
2243 foreach(rt, query->rtable)
2245 RangeTblEntry *rte = (RangeTblEntry *) lfirst(rt);
2249 RangeTblEntry *newrte;
2251 FLATCOPY(newrte, rte, RangeTblEntry);
2252 CHECKFLATCOPY(newrte->subquery, rte->subquery, Query);
2253 MUTATE(newrte->subquery, newrte->subquery, Query *);
2256 newrt = lappend(newrt, rte);
2258 query->rtable = newrt;