OSDN Git Service

First phase of SCHEMA changes, concentrating on fixing the grammar and
[pg-rex/syncrep.git] / src / backend / optimizer / util / clauses.c
1 /*-------------------------------------------------------------------------
2  *
3  * clauses.c
4  *        routines to manipulate qualification clauses
5  *
6  * Portions Copyright (c) 1996-2001, PostgreSQL Global Development Group
7  * Portions Copyright (c) 1994, Regents of the University of California
8  *
9  *
10  * IDENTIFICATION
11  *        $Header: /cvsroot/pgsql/src/backend/optimizer/util/clauses.c,v 1.95 2002/03/21 16:00:44 tgl Exp $
12  *
13  * HISTORY
14  *        AUTHOR                        DATE                    MAJOR EVENT
15  *        Andrew Yu                     Nov 3, 1994             clause.c and clauses.c combined
16  *
17  *-------------------------------------------------------------------------
18  */
19
20 #include "postgres.h"
21
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"
35
36
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))
41
42 typedef struct
43 {
44         Query      *query;
45         List       *groupClauses;
46 }       check_subplans_for_ungrouped_vars_context;
47
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);
58
59
60 Expr *
61 make_clause(int type, Node *oper, List *args)
62 {
63         Expr       *expr = makeNode(Expr);
64
65         switch (type)
66         {
67                 case AND_EXPR:
68                 case OR_EXPR:
69                 case NOT_EXPR:
70                         expr->typeOid = BOOLOID;
71                         break;
72                 case OP_EXPR:
73                         expr->typeOid = ((Oper *) oper)->opresulttype;
74                         break;
75                 case FUNC_EXPR:
76                         expr->typeOid = ((Func *) oper)->functype;
77                         break;
78                 default:
79                         elog(ERROR, "make_clause: unsupported type %d", type);
80                         break;
81         }
82         expr->opType = type;
83         expr->oper = oper;                      /* ignored for AND, OR, NOT */
84         expr->args = args;
85         return expr;
86 }
87
88
89 /*****************************************************************************
90  *              OPERATOR clause functions
91  *****************************************************************************/
92
93
94 /*
95  * is_opclause
96  *
97  * Returns t iff the clause is an operator clause:
98  *                              (op expr expr) or (op expr).
99  *
100  * [historical note: is_clause has the exact functionality and is used
101  *              throughout the code. They're renamed to is_opclause for clarity.
102  *                                                                                              - ay 10/94.]
103  */
104 bool
105 is_opclause(Node *clause)
106 {
107         return (clause != NULL &&
108                         IsA(clause, Expr) &&
109                         ((Expr *) clause)->opType == OP_EXPR);
110 }
111
112 /*
113  * make_opclause
114  *        Creates a clause given its operator left operand and right
115  *        operand (if it is non-null).
116  *
117  */
118 Expr *
119 make_opclause(Oper *op, Var *leftop, Var *rightop)
120 {
121         Expr       *expr = makeNode(Expr);
122
123         expr->typeOid = op->opresulttype;
124         expr->opType = OP_EXPR;
125         expr->oper = (Node *) op;
126         if (rightop)
127                 expr->args = makeList2(leftop, rightop);
128         else
129                 expr->args = makeList1(leftop);
130         return expr;
131 }
132
133 /*
134  * get_leftop
135  *
136  * Returns the left operand of a clause of the form (op expr expr)
137  *              or (op expr)
138  *
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 *.
142  */
143 Var *
144 get_leftop(Expr *clause)
145 {
146         if (clause->args != NULL)
147                 return lfirst(clause->args);
148         else
149                 return NULL;
150 }
151
152 /*
153  * get_rightop
154  *
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.
157  */
158 Var *
159 get_rightop(Expr *clause)
160 {
161         if (clause->args != NULL && lnext(clause->args) != NULL)
162                 return lfirst(lnext(clause->args));
163         else
164                 return NULL;
165 }
166
167 /*****************************************************************************
168  *              FUNC clause functions
169  *****************************************************************************/
170
171 /*
172  * is_funcclause
173  *
174  * Returns t iff the clause is a function clause: (func { expr }).
175  *
176  */
177 bool
178 is_funcclause(Node *clause)
179 {
180         return (clause != NULL &&
181                         IsA(clause, Expr) &&
182                         ((Expr *) clause)->opType == FUNC_EXPR);
183 }
184
185 /*
186  * make_funcclause
187  *
188  * Creates a function clause given the FUNC node and the functional
189  * arguments.
190  *
191  */
192 Expr *
193 make_funcclause(Func *func, List *funcargs)
194 {
195         Expr       *expr = makeNode(Expr);
196
197         expr->typeOid = func->functype;
198         expr->opType = FUNC_EXPR;
199         expr->oper = (Node *) func;
200         expr->args = funcargs;
201         return expr;
202 }
203
204 /*****************************************************************************
205  *              OR clause functions
206  *****************************************************************************/
207
208 /*
209  * or_clause
210  *
211  * Returns t iff the clause is an 'or' clause: (OR { expr }).
212  *
213  */
214 bool
215 or_clause(Node *clause)
216 {
217         return (clause != NULL &&
218                         IsA(clause, Expr) &&
219                         ((Expr *) clause)->opType == OR_EXPR);
220 }
221
222 /*
223  * make_orclause
224  *
225  * Creates an 'or' clause given a list of its subclauses.
226  *
227  */
228 Expr *
229 make_orclause(List *orclauses)
230 {
231         Expr       *expr = makeNode(Expr);
232
233         expr->typeOid = BOOLOID;
234         expr->opType = OR_EXPR;
235         expr->oper = NULL;
236         expr->args = orclauses;
237         return expr;
238 }
239
240 /*****************************************************************************
241  *              NOT clause functions
242  *****************************************************************************/
243
244 /*
245  * not_clause
246  *
247  * Returns t iff this is a 'not' clause: (NOT expr).
248  *
249  */
250 bool
251 not_clause(Node *clause)
252 {
253         return (clause != NULL &&
254                         IsA(clause, Expr) &&
255                         ((Expr *) clause)->opType == NOT_EXPR);
256 }
257
258 /*
259  * make_notclause
260  *
261  * Create a 'not' clause given the expression to be negated.
262  *
263  */
264 Expr *
265 make_notclause(Expr *notclause)
266 {
267         Expr       *expr = makeNode(Expr);
268
269         expr->typeOid = BOOLOID;
270         expr->opType = NOT_EXPR;
271         expr->oper = NULL;
272         expr->args = makeList1(notclause);
273         return expr;
274 }
275
276 /*
277  * get_notclausearg
278  *
279  * Retrieve the clause within a 'not' clause
280  *
281  */
282 Expr *
283 get_notclausearg(Expr *notclause)
284 {
285         return lfirst(notclause->args);
286 }
287
288 /*****************************************************************************
289  *              AND clause functions
290  *****************************************************************************/
291
292
293 /*
294  * and_clause
295  *
296  * Returns t iff its argument is an 'and' clause: (AND { expr }).
297  *
298  */
299 bool
300 and_clause(Node *clause)
301 {
302         return (clause != NULL &&
303                         IsA(clause, Expr) &&
304                         ((Expr *) clause)->opType == AND_EXPR);
305 }
306
307 /*
308  * make_andclause
309  *
310  * Create an 'and' clause given its arguments in a list.
311  */
312 Expr *
313 make_andclause(List *andclauses)
314 {
315         Expr       *expr = makeNode(Expr);
316
317         expr->typeOid = BOOLOID;
318         expr->opType = AND_EXPR;
319         expr->oper = NULL;
320         expr->args = andclauses;
321         return expr;
322 }
323
324 /*
325  * make_and_qual
326  *
327  * Variant of make_andclause for ANDing two qual conditions together.
328  * Qual conditions have the property that a NULL nodetree is interpreted
329  * as 'true'.
330  */
331 Node *
332 make_and_qual(Node *qual1, Node *qual2)
333 {
334         if (qual1 == NULL)
335                 return qual2;
336         if (qual2 == NULL)
337                 return qual1;
338         return (Node *) make_andclause(makeList2(qual1, qual2));
339 }
340
341 /*
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.
344  *
345  * These functions convert between an AND-semantics expression list and the
346  * ordinary representation of a boolean expression.
347  *
348  * Note that an empty list is considered equivalent to TRUE.
349  */
350 Expr *
351 make_ands_explicit(List *andclauses)
352 {
353         if (andclauses == NIL)
354                 return (Expr *) MAKEBOOLCONST(true, false);
355         else if (lnext(andclauses) == NIL)
356                 return (Expr *) lfirst(andclauses);
357         else
358                 return make_andclause(andclauses);
359 }
360
361 List *
362 make_ands_implicit(Expr *clause)
363 {
364         /*
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.
369          */
370         if (clause == NULL)
371                 return NIL;                             /* NULL -> NIL list == TRUE */
372         else if (and_clause((Node *) clause))
373                 return clause->args;
374         else if (IsA(clause, Const) &&
375                          !((Const *) clause)->constisnull &&
376                          DatumGetBool(((Const *) clause)->constvalue))
377                 return NIL;                             /* constant TRUE input -> NIL list */
378         else
379                 return makeList1(clause);
380 }
381
382
383 /*****************************************************************************
384  *              Aggregate-function clause manipulation
385  *****************************************************************************/
386
387 /*
388  * contain_agg_clause
389  *        Recursively search for Aggref nodes within a clause.
390  *
391  *        Returns true if any aggregate found.
392  */
393 bool
394 contain_agg_clause(Node *clause)
395 {
396         return contain_agg_clause_walker(clause, NULL);
397 }
398
399 static bool
400 contain_agg_clause_walker(Node *node, void *context)
401 {
402         if (node == NULL)
403                 return false;
404         if (IsA(node, Aggref))
405                 return true;                    /* abort the tree traversal and return
406                                                                  * true */
407         return expression_tree_walker(node, contain_agg_clause_walker, context);
408 }
409
410 /*
411  * pull_agg_clause
412  *        Recursively pulls all Aggref nodes from an expression tree.
413  *
414  *        Returns list of Aggref nodes found.  Note the nodes themselves are not
415  *        copied, only referenced.
416  *
417  *        Note: this also checks for nested aggregates, which are an error.
418  */
419 List *
420 pull_agg_clause(Node *clause)
421 {
422         List       *result = NIL;
423
424         pull_agg_clause_walker(clause, &result);
425         return result;
426 }
427
428 static bool
429 pull_agg_clause_walker(Node *node, List **listptr)
430 {
431         if (node == NULL)
432                 return false;
433         if (IsA(node, Aggref))
434         {
435                 *listptr = lappend(*listptr, node);
436
437                 /*
438                  * Complain if the aggregate's argument contains any aggregates;
439                  * nested agg functions are semantically nonsensical.
440                  */
441                 if (contain_agg_clause(((Aggref *) node)->target))
442                         elog(ERROR, "Aggregate function calls may not be nested");
443
444                 /*
445                  * Having checked that, we need not recurse into the argument.
446                  */
447                 return false;
448         }
449         return expression_tree_walker(node, pull_agg_clause_walker,
450                                                                   (void *) listptr);
451 }
452
453
454 /*****************************************************************************
455  *              Iter clause manipulation
456  *****************************************************************************/
457
458 /*
459  * contain_iter_clause
460  *        Recursively search for Iter nodes within a clause.
461  *
462  *        Returns true if any Iter found.
463  *
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.
469  */
470 bool
471 contain_iter_clause(Node *clause)
472 {
473         return contain_iter_clause_walker(clause, NULL);
474 }
475
476 static bool
477 contain_iter_clause_walker(Node *node, void *context)
478 {
479         if (node == NULL)
480                 return false;
481         if (IsA(node, Iter))
482                 return true;                    /* abort the tree traversal and return
483                                                                  * true */
484         return expression_tree_walker(node, contain_iter_clause_walker, context);
485 }
486
487 /*****************************************************************************
488  *              Subplan clause manipulation
489  *****************************************************************************/
490
491 /*
492  * contain_subplans
493  *        Recursively search for subplan nodes within a clause.
494  *
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.
499  *
500  * Returns true if any subplan found.
501  */
502 bool
503 contain_subplans(Node *clause)
504 {
505         return contain_subplans_walker(clause, NULL);
506 }
507
508 static bool
509 contain_subplans_walker(Node *node, void *context)
510 {
511         if (node == NULL)
512                 return false;
513         if (is_subplan(node) || IsA(node, SubLink))
514                 return true;                    /* abort the tree traversal and return
515                                                                  * true */
516         return expression_tree_walker(node, contain_subplans_walker, context);
517 }
518
519 /*
520  * pull_subplans
521  *        Recursively pulls all subplans from an expression tree.
522  *
523  *        Returns list of subplan nodes found.  Note the nodes themselves are not
524  *        copied, only referenced.
525  */
526 List *
527 pull_subplans(Node *clause)
528 {
529         List       *result = NIL;
530
531         pull_subplans_walker(clause, &result);
532         return result;
533 }
534
535 static bool
536 pull_subplans_walker(Node *node, List **listptr)
537 {
538         if (node == NULL)
539                 return false;
540         if (is_subplan(node))
541         {
542                 *listptr = lappend(*listptr, ((Expr *) node)->oper);
543                 /* fall through to check args to subplan */
544         }
545         return expression_tree_walker(node, pull_subplans_walker,
546                                                                   (void *) listptr);
547 }
548
549 /*
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.
553  *
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.
559  *
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
563  *              SELECT
564  *                      (SELECT x FROM bar where y = (foo.a + foo.b))
565  *              FROM foo
566  *              GROUP BY a + b;
567  * This query will be rejected although it could be allowed.
568  */
569 void
570 check_subplans_for_ungrouped_vars(Query *query)
571 {
572         check_subplans_for_ungrouped_vars_context context;
573         List       *gl;
574
575         context.query = query;
576
577         /*
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).
581          */
582         context.groupClauses = NIL;
583         foreach(gl, query->groupClause)
584         {
585                 GroupClause *grpcl = lfirst(gl);
586                 Node       *expr;
587
588                 expr = get_sortgroupclause_expr(grpcl, query->targetList);
589                 context.groupClauses = lcons(expr, context.groupClauses);
590         }
591
592         /*
593          * Recursively scan the targetlist and the HAVING clause. WHERE and
594          * JOIN/ON conditions are not examined, since they are evaluated
595          * before grouping.
596          */
597         check_subplans_for_ungrouped_vars_walker((Node *) query->targetList,
598                                                                                          &context);
599         check_subplans_for_ungrouped_vars_walker(query->havingQual,
600                                                                                          &context);
601
602         freeList(context.groupClauses);
603 }
604
605 static bool
606 check_subplans_for_ungrouped_vars_walker(Node *node,
607                                          check_subplans_for_ungrouped_vars_context * context)
608 {
609         List       *gl;
610
611         if (node == NULL)
612                 return false;
613         if (IsA(node, Const) ||IsA(node, Param))
614                 return false;                   /* constants are always acceptable */
615
616         /*
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().)
621          */
622         if (IsA(node, Aggref))
623                 return false;
624
625         /*
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.
629          */
630         foreach(gl, context->groupClauses)
631         {
632                 if (equal(node, lfirst(gl)))
633                         return false;           /* acceptable, do not descend more */
634         }
635
636         /*
637          * We can ignore Vars other than in subplan args lists, since the
638          * parser already checked 'em.
639          */
640         if (is_subplan(node))
641         {
642                 /*
643                  * The args list of the subplan node represents attributes from
644                  * outside passed into the sublink.
645                  */
646                 List       *t;
647
648                 foreach(t, ((Expr *) node)->args)
649                 {
650                         Node       *thisarg = lfirst(t);
651                         Var                *var;
652                         bool            contained_in_group_clause;
653
654                         /*
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
658                          * worry, instead.)
659                          */
660                         if (!IsA(thisarg, Var))
661                                 continue;
662                         var = (Var *) thisarg;
663                         if (var->varlevelsup > 0)
664                                 continue;
665
666                         /*
667                          * Else, see if it is a grouping column.
668                          */
669                         contained_in_group_clause = false;
670                         foreach(gl, context->groupClauses)
671                         {
672                                 if (equal(thisarg, lfirst(gl)))
673                                 {
674                                         contained_in_group_clause = true;
675                                         break;
676                                 }
677                         }
678
679                         if (!contained_in_group_clause)
680                         {
681                                 /* Found an ungrouped argument.  Complain. */
682                                 RangeTblEntry *rte;
683                                 char       *attname;
684
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);
691                         }
692                 }
693         }
694         return expression_tree_walker(node,
695                                                                 check_subplans_for_ungrouped_vars_walker,
696                                                                   (void *) context);
697 }
698
699
700 /*****************************************************************************
701  *              Check clauses for noncachable functions
702  *****************************************************************************/
703
704 /*
705  * contain_noncachable_functions
706  *        Recursively search for noncachable functions within a clause.
707  *
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.
712  *
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...
715  */
716 bool
717 contain_noncachable_functions(Node *clause)
718 {
719         return contain_noncachable_functions_walker(clause, NULL);
720 }
721
722 static bool
723 contain_noncachable_functions_walker(Node *node, void *context)
724 {
725         if (node == NULL)
726                 return false;
727         if (IsA(node, Expr))
728         {
729                 Expr       *expr = (Expr *) node;
730
731                 switch (expr->opType)
732                 {
733                         case OP_EXPR:
734                                 if (!op_iscachable(((Oper *) expr->oper)->opno))
735                                         return true;
736                                 break;
737                         case FUNC_EXPR:
738                                 if (!func_iscachable(((Func *) expr->oper)->funcid))
739                                         return true;
740                                 break;
741                         default:
742                                 break;
743                 }
744         }
745         return expression_tree_walker(node, contain_noncachable_functions_walker,
746                                                                   context);
747 }
748
749
750 /*****************************************************************************
751  *              Check for "pseudo-constant" clauses
752  *****************************************************************************/
753
754 /*
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.
762  */
763 bool
764 is_pseudo_constant_clause(Node *clause)
765 {
766         /*
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.
771          */
772         if (!contain_var_clause(clause) &&
773                 !contain_noncachable_functions(clause))
774                 return true;
775         return false;
776 }
777
778 /*
779  * pull_constant_clauses
780  *              Scan through a list of qualifications and separate "constant" quals
781  *              from those that are not.
782  *
783  * Returns a list of the pseudo-constant clauses in constantQual and the
784  * remaining quals as the return value.
785  */
786 List *
787 pull_constant_clauses(List *quals, List **constantQual)
788 {
789         List       *constqual = NIL;
790         List       *restqual = NIL;
791         List       *q;
792
793         foreach(q, quals)
794         {
795                 Node       *qual = (Node *) lfirst(q);
796
797                 if (is_pseudo_constant_clause(qual))
798                         constqual = lappend(constqual, qual);
799                 else
800                         restqual = lappend(restqual, qual);
801         }
802         *constantQual = constqual;
803         return restqual;
804 }
805
806
807 /*****************************************************************************
808  *              Tests on clauses of queries
809  *
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  *****************************************************************************/
814
815 /*
816  * Test whether a sort/group reference value appears in the given list of
817  * SortClause (or GroupClause) nodes.
818  *
819  * Because GroupClause is typedef'd as SortClause, either kind of
820  * node list can be passed without casting.
821  */
822 static bool
823 sortgroupref_is_present(Index sortgroupref, List *clauselist)
824 {
825         List       *clause;
826
827         foreach(clause, clauselist)
828         {
829                 SortClause *scl = (SortClause *) lfirst(clause);
830
831                 if (scl->tleSortGroupRef == sortgroupref)
832                         return true;
833         }
834         return false;
835 }
836
837 /*
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.
840  */
841 bool
842 has_distinct_on_clause(Query *query)
843 {
844         List       *targetList;
845
846         /* Is there a DISTINCT clause at all? */
847         if (query->distinctClause == NIL)
848                 return false;
849
850         /*
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.
859          *
860          * This code assumes that the DISTINCT list is valid, ie, all its entries
861          * match some entry of the tlist.
862          */
863         foreach(targetList, query->targetList)
864         {
865                 TargetEntry *tle = (TargetEntry *) lfirst(targetList);
866                 Index           ressortgroupref = tle->resdom->ressortgroupref;
867
868                 if (ressortgroupref == 0)
869                 {
870                         if (tle->resdom->resjunk)
871                                 continue;               /* we can ignore unsorted junk cols */
872                         return true;            /* definitely not in DISTINCT list */
873                 }
874                 if (sortgroupref_is_present(ressortgroupref, query->distinctClause))
875                 {
876                         if (tle->resdom->resjunk)
877                                 return true;    /* junk TLE in DISTINCT means DISTINCT ON */
878                         /* else this TLE is okay, keep looking */
879                 }
880                 else
881                 {
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 */
888                 }
889         }
890         /* It's a simple DISTINCT */
891         return false;
892 }
893
894
895 /*****************************************************************************
896  *                                                                                                                                                       *
897  *              General clause-manipulating routines                                                             *
898  *                                                                                                                                                       *
899  *****************************************************************************/
900
901 /*
902  * clause_get_relids_vars
903  *        Retrieves distinct relids and vars appearing within a clause.
904  *
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...
911  *
912  * Note that upper-level vars are ignored, since they normally will
913  * become Params with respect to this query level.
914  */
915 void
916 clause_get_relids_vars(Node *clause, Relids *relids, List **vars)
917 {
918         List       *clvars = pull_var_clause(clause, false);
919         List       *varno_list = NIL;
920         List       *var_list = NIL;
921         List       *i;
922
923         foreach(i, clvars)
924         {
925                 Var                *var = (Var *) lfirst(i);
926                 List       *vi;
927
928                 if (!intMember(var->varno, varno_list))
929                         varno_list = lconsi(var->varno, varno_list);
930                 foreach(vi, var_list)
931                 {
932                         Var                *in_list = (Var *) lfirst(vi);
933
934                         if (in_list->varno == var->varno &&
935                                 in_list->varattno == var->varattno)
936                                 break;
937                 }
938                 if (vi == NIL)
939                         var_list = lcons(var, var_list);
940         }
941         freeList(clvars);
942
943         *relids = varno_list;
944         *vars = var_list;
945 }
946
947 /*
948  * NumRelids
949  *              (formerly clause_relids)
950  *
951  * Returns the number of different relations referenced in 'clause'.
952  */
953 int
954 NumRelids(Node *clause)
955 {
956         List       *varno_list = pull_varnos(clause);
957         int                     result = length(varno_list);
958
959         freeList(varno_list);
960         return result;
961 }
962
963 /*--------------------
964  * CommuteClause: commute a binary operator clause
965  *
966  * XXX the clause is destructively modified!
967  *--------------------
968  */
969 void
970 CommuteClause(Expr *clause)
971 {
972         Oid                     opoid;
973         HeapTuple       optup;
974         Form_pg_operator commuTup;
975         Oper       *commu;
976         Node       *temp;
977
978         if (!is_opclause((Node *) clause) ||
979                 length(clause->args) != 2)
980                 elog(ERROR, "CommuteClause: applied to non-binary-operator clause");
981
982         opoid = ((Oper *) clause->oper)->opno;
983
984         optup = SearchSysCache(OPEROID,
985                                                    ObjectIdGetDatum(get_commutator(opoid)),
986                                                    0, 0, 0);
987         if (!HeapTupleIsValid(optup))
988                 elog(ERROR, "CommuteClause: no commutator for operator %u", opoid);
989
990         commuTup = (Form_pg_operator) GETSTRUCT(optup);
991
992         commu = makeOper(optup->t_data->t_oid,
993                                          commuTup->oprcode,
994                                          commuTup->oprresult);
995
996         ReleaseSysCache(optup);
997
998         /*
999          * re-form the clause in-place!
1000          */
1001         clause->oper = (Node *) commu;
1002         temp = lfirst(clause->args);
1003         lfirst(clause->args) = lsecond(clause->args);
1004         lsecond(clause->args) = temp;
1005 }
1006
1007
1008 /*--------------------
1009  * eval_const_expressions
1010  *
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?)
1019  *
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.
1026  *
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.
1029  *
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  *--------------------
1038  */
1039 Node *
1040 eval_const_expressions(Node *node)
1041 {
1042         /* no context or special setup needed, so away we go... */
1043         return eval_const_expressions_mutator(node, NULL);
1044 }
1045
1046 static Node *
1047 eval_const_expressions_mutator(Node *node, void *context)
1048 {
1049         if (node == NULL)
1050                 return NULL;
1051         if (IsA(node, Expr))
1052         {
1053                 Expr       *expr = (Expr *) node;
1054                 List       *args;
1055                 Const      *const_input;
1056                 Expr       *newexpr;
1057
1058                 /*
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.
1062                  */
1063                 args = (List *) expression_tree_mutator((Node *) expr->args,
1064                                                                                   eval_const_expressions_mutator,
1065                                                                                                 (void *) context);
1066
1067                 switch (expr->opType)
1068                 {
1069                         case OP_EXPR:
1070                         case FUNC_EXPR:
1071
1072                                 /*
1073                                  * Code for op/func case is pretty bulky, so split it out
1074                                  * as a separate function.
1075                                  */
1076                                 newexpr = simplify_op_or_func(expr, args);
1077                                 if (newexpr)    /* successfully simplified it */
1078                                         return (Node *) newexpr;
1079
1080                                 /*
1081                                  * else fall out to build new Expr node with simplified
1082                                  * args
1083                                  */
1084                                 break;
1085                         case OR_EXPR:
1086                                 {
1087
1088                                         /*----------
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.
1096                                          *----------
1097                                          */
1098                                         List       *newargs = NIL;
1099                                         List       *arg;
1100                                         bool            haveNull = false;
1101                                         bool            forceTrue = false;
1102
1103                                         foreach(arg, args)
1104                                         {
1105                                                 if (!IsA(lfirst(arg), Const))
1106                                                 {
1107                                                         newargs = lappend(newargs, lfirst(arg));
1108                                                         continue;
1109                                                 }
1110                                                 const_input = (Const *) lfirst(arg);
1111                                                 if (const_input->constisnull)
1112                                                         haveNull = true;
1113                                                 else if (DatumGetBool(const_input->constvalue))
1114                                                         forceTrue = true;
1115                                                 /* otherwise, we can drop the constant-false input */
1116                                         }
1117
1118                                         /*
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
1123                                          * non-removability.
1124                                          */
1125                                         if (forceTrue)
1126                                                 return MAKEBOOLCONST(true, false);
1127                                         if (haveNull)
1128                                                 newargs = lappend(newargs, MAKEBOOLCONST(false, true));
1129                                         /* If all the inputs are FALSE, result is FALSE */
1130                                         if (newargs == NIL)
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);
1137                                 }
1138                         case AND_EXPR:
1139                                 {
1140
1141                                         /*----------
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.
1149                                          *----------
1150                                          */
1151                                         List       *newargs = NIL;
1152                                         List       *arg;
1153                                         bool            haveNull = false;
1154                                         bool            forceFalse = false;
1155
1156                                         foreach(arg, args)
1157                                         {
1158                                                 if (!IsA(lfirst(arg), Const))
1159                                                 {
1160                                                         newargs = lappend(newargs, lfirst(arg));
1161                                                         continue;
1162                                                 }
1163                                                 const_input = (Const *) lfirst(arg);
1164                                                 if (const_input->constisnull)
1165                                                         haveNull = true;
1166                                                 else if (!DatumGetBool(const_input->constvalue))
1167                                                         forceFalse = true;
1168                                                 /* otherwise, we can drop the constant-true input */
1169                                         }
1170
1171                                         /*
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
1176                                          * non-removability.
1177                                          */
1178                                         if (forceFalse)
1179                                                 return MAKEBOOLCONST(false, false);
1180                                         if (haveNull)
1181                                                 newargs = lappend(newargs, MAKEBOOLCONST(false, true));
1182                                         /* If all the inputs are TRUE, result is TRUE */
1183                                         if (newargs == NIL)
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);
1190                                 }
1191                         case NOT_EXPR:
1192                                 Assert(length(args) == 1);
1193                                 if (!IsA(lfirst(args), Const))
1194                                         break;
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),
1201                                                                          false);
1202                         case SUBPLAN_EXPR:
1203
1204                                 /*
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
1209                                  * anyway).
1210                                  */
1211                                 return (Node *) expr;
1212                         default:
1213                                 elog(ERROR, "eval_const_expressions: unexpected opType %d",
1214                                          (int) expr->opType);
1215                                 break;
1216                 }
1217
1218                 /*
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
1224                  * preserved...
1225                  */
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;
1232         }
1233         if (IsA(node, RelabelType))
1234         {
1235                 /*
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.
1239                  */
1240                 RelabelType *relabel = (RelabelType *) node;
1241                 Node       *arg;
1242
1243                 arg = eval_const_expressions_mutator(relabel->arg, context);
1244
1245                 /*
1246                  * If we find stacked RelabelTypes (eg, from foo :: int :: oid) we
1247                  * can discard all but the top one.
1248                  */
1249                 while (arg && IsA(arg, RelabelType))
1250                         arg = ((RelabelType *) arg)->arg;
1251
1252                 if (arg && IsA(arg, Const))
1253                 {
1254                         Const      *con = (Const *) arg;
1255
1256                         con->consttype = relabel->resulttype;
1257
1258                         /*
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
1262                          * node.
1263                          */
1264                         return (Node *) con;
1265                 }
1266                 else
1267                 {
1268                         RelabelType *newrelabel = makeNode(RelabelType);
1269
1270                         newrelabel->arg = arg;
1271                         newrelabel->resulttype = relabel->resulttype;
1272                         newrelabel->resulttypmod = relabel->resulttypmod;
1273                         return (Node *) newrelabel;
1274                 }
1275         }
1276         if (IsA(node, CaseExpr))
1277         {
1278
1279                 /*----------
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).
1288                  *----------
1289                  */
1290                 CaseExpr   *caseexpr = (CaseExpr *) node;
1291                 CaseExpr   *newcase;
1292                 List       *newargs = NIL;
1293                 Node       *defresult;
1294                 Const      *const_input;
1295                 List       *arg;
1296
1297                 foreach(arg, caseexpr->args)
1298                 {
1299                         /* Simplify this alternative's condition and result */
1300                         CaseWhen   *casewhen = (CaseWhen *)
1301                         expression_tree_mutator((Node *) lfirst(arg),
1302                                                                         eval_const_expressions_mutator,
1303                                                                         (void *) context);
1304
1305                         Assert(IsA(casewhen, CaseWhen));
1306                         if (casewhen->expr == NULL ||
1307                                 !IsA(casewhen->expr, Const))
1308                         {
1309                                 newargs = lappend(newargs, casewhen);
1310                                 continue;
1311                         }
1312                         const_input = (Const *) casewhen->expr;
1313                         if (const_input->constisnull ||
1314                                 !DatumGetBool(const_input->constvalue))
1315                                 continue;               /* drop alternative with FALSE condition */
1316
1317                         /*
1318                          * Found a TRUE condition.      If it's the first (un-dropped)
1319                          * alternative, the CASE reduces to just this alternative.
1320                          */
1321                         if (newargs == NIL)
1322                                 return casewhen->result;
1323
1324                         /*
1325                          * Otherwise, add it to the list, and drop all the rest.
1326                          */
1327                         newargs = lappend(newargs, casewhen);
1328                         break;
1329                 }
1330
1331                 /* Simplify the default result */
1332                 defresult = eval_const_expressions_mutator(caseexpr->defresult,
1333                                                                                                    context);
1334
1335                 /*
1336                  * If no non-FALSE alternatives, CASE reduces to the default
1337                  * result
1338                  */
1339                 if (newargs == NIL)
1340                         return defresult;
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;
1348         }
1349         if (IsA(node, Iter))
1350         {
1351                 /*
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?
1357                  */
1358                 Iter       *iter = (Iter *) node;
1359
1360                 if (is_funcclause(iter->iterexpr))
1361                 {
1362                         Expr       *func = (Expr *) iter->iterexpr;
1363                         Expr       *newfunc;
1364                         Iter       *newiter;
1365
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,
1373                                                                                 (void *) context);
1374                         newiter = makeNode(Iter);
1375                         newiter->iterexpr = (Node *) newfunc;
1376                         newiter->itertype = iter->itertype;
1377                         return (Node *) newiter;
1378                 }
1379         }
1380
1381         /*
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.
1387          */
1388         return expression_tree_mutator(node, eval_const_expressions_mutator,
1389                                                                    (void *) context);
1390 }
1391
1392 /*
1393  * Subroutine for eval_const_expressions: try to evaluate an op or func
1394  *
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.
1398  *
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.
1406  */
1407 static Expr *
1408 simplify_op_or_func(Expr *expr, List *args)
1409 {
1410         List       *arg;
1411         Oid                     funcid;
1412         Oid                     result_typeid;
1413         HeapTuple       func_tuple;
1414         Form_pg_proc funcform;
1415         bool            proiscachable;
1416         bool            proisstrict;
1417         bool            proretset;
1418         int16           resultTypLen;
1419         bool            resultTypByVal;
1420         Expr       *newexpr;
1421         ExprContext *econtext;
1422         Datum           const_val;
1423         bool            has_nonconst_input = false;
1424         bool            has_null_input = false;
1425         bool            const_is_null;
1426
1427         /*
1428          * Check for constant inputs and especially constant-NULL inputs.
1429          */
1430         foreach(arg, args)
1431         {
1432                 if (IsA(lfirst(arg), Const))
1433                         has_null_input |= ((Const *) lfirst(arg))->constisnull;
1434                 else
1435                         has_nonconst_input = true;
1436         }
1437
1438         /*
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.
1444          */
1445         if (has_nonconst_input && !has_null_input)
1446                 return NULL;
1447
1448         /*
1449          * Get the function procedure's OID and look to see whether it is
1450          * marked proiscachable.
1451          *
1452          * XXX would it be better to take the result type from the pg_proc tuple,
1453          * rather than the Oper or Func node?
1454          */
1455         if (expr->opType == OP_EXPR)
1456         {
1457                 Oper       *oper = (Oper *) expr->oper;
1458
1459                 replace_opid(oper);             /* OK to scribble on input to this extent */
1460                 funcid = oper->opid;
1461                 result_typeid = oper->opresulttype;
1462         }
1463         else
1464         {
1465                 Func       *func = (Func *) expr->oper;
1466
1467                 funcid = func->funcid;
1468                 result_typeid = func->functype;
1469         }
1470
1471         /*
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.
1474          */
1475         func_tuple = SearchSysCache(PROCOID,
1476                                                                 ObjectIdGetDatum(funcid),
1477                                                                 0, 0, 0);
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);
1485
1486         if (!proiscachable)
1487                 return NULL;
1488
1489         /*
1490          * Also check to make sure it doesn't return a set.
1491          */
1492         if (proretset)
1493                 return NULL;
1494
1495         /*
1496          * Now that we know if the function is strict, we can finish the
1497          * checks for simplifiable inputs that we started above.
1498          */
1499         if (proisstrict && has_null_input)
1500         {
1501                 /*
1502                  * It's strict and has NULL input, so must produce NULL output.
1503                  * Return a NULL constant of the right type.
1504                  */
1505                 return (Expr *) makeNullConst(result_typeid);
1506         }
1507
1508         /*
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.)
1512          */
1513         if (has_nonconst_input)
1514                 return NULL;
1515
1516         /*
1517          * OK, looks like we can simplify this operator/function.
1518          *
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.
1521          *
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.
1525          */
1526         newexpr = makeNode(Expr);
1527         newexpr->typeOid = expr->typeOid;
1528         newexpr->opType = expr->opType;
1529         newexpr->oper = expr->oper;
1530         newexpr->args = args;
1531
1532         /* Get info needed about result datatype */
1533         get_typlenbyval(result_typeid, &resultTypLen, &resultTypByVal);
1534
1535         /*
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?
1540          */
1541         econtext = MakeExprContext(NULL, CurrentMemoryContext);
1542
1543         const_val = ExecEvalExprSwitchContext((Node *) newexpr, econtext,
1544                                                                                   &const_is_null, NULL);
1545
1546         /* Must copy result out of sub-context used by expression eval */
1547         if (!const_is_null)
1548                 const_val = datumCopy(const_val, resultTypByVal, resultTypLen);
1549
1550         FreeExprContext(econtext);
1551         pfree(newexpr);
1552
1553         /*
1554          * Make the constant result node.
1555          */
1556         return (Expr *) makeConst(result_typeid, resultTypLen,
1557                                                           const_val, const_is_null,
1558                                                           resultTypByVal, false, false);
1559 }
1560
1561
1562 /*
1563  * Standard expression-tree walking support
1564  *
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().
1574  */
1575
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:
1581  *
1582  * bool my_walker (Node *node, my_struct *context)
1583  * {
1584  *              if (node == NULL)
1585  *                      return false;
1586  *              // check for nodes that special work is required for, eg:
1587  *              if (IsA(node, Var))
1588  *              {
1589  *                      ... do special actions for Var nodes
1590  *              }
1591  *              else if (IsA(node, ...))
1592  *              {
1593  *                      ... do special actions for other node types
1594  *              }
1595  *              // for any node type not specially processed, do:
1596  *              return expression_tree_walker(node, my_walker, (void *) context);
1597  * }
1598  *
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.
1606  *
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".
1612  *
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.
1622  *
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:
1634  *
1635  *              if (IsA(node, Query))
1636  *              {
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;
1641  *                      return result;
1642  *              }
1643  *
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.
1646  *
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  *--------------------
1652  */
1653
1654 bool
1655 expression_tree_walker(Node *node,
1656                                            bool (*walker) (),
1657                                            void *context)
1658 {
1659         List       *temp;
1660
1661         /*
1662          * The walker has already visited the current node, and so we need
1663          * only recurse into any sub-nodes it has.
1664          *
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.
1668          */
1669         if (node == NULL)
1670                 return false;
1671         switch (nodeTag(node))
1672         {
1673                 case T_Const:
1674                 case T_Var:
1675                 case T_Param:
1676                 case T_RangeTblRef:
1677                         /* primitive node types with no subnodes */
1678                         break;
1679                 case T_Expr:
1680                         {
1681                                 Expr       *expr = (Expr *) node;
1682
1683                                 if (expr->opType == SUBPLAN_EXPR)
1684                                 {
1685                                         /* recurse to the SubLink node (skipping SubPlan!) */
1686                                         if (walker((Node *) ((SubPlan *) expr->oper)->sublink,
1687                                                            context))
1688                                                 return true;
1689                                 }
1690                                 /* for all Expr node types, examine args list */
1691                                 if (expression_tree_walker((Node *) expr->args,
1692                                                                                    walker, context))
1693                                         return true;
1694                         }
1695                         break;
1696                 case T_Aggref:
1697                         return walker(((Aggref *) node)->target, context);
1698                 case T_Iter:
1699                         return walker(((Iter *) node)->iterexpr, context);
1700                 case T_ArrayRef:
1701                         {
1702                                 ArrayRef   *aref = (ArrayRef *) node;
1703
1704                                 /* recurse directly for upper/lower array index lists */
1705                                 if (expression_tree_walker((Node *) aref->refupperindexpr,
1706                                                                                    walker, context))
1707                                         return true;
1708                                 if (expression_tree_walker((Node *) aref->reflowerindexpr,
1709                                                                                    walker, context))
1710                                         return true;
1711                                 /* walker must see the refexpr and refassgnexpr, however */
1712                                 if (walker(aref->refexpr, context))
1713                                         return true;
1714                                 if (walker(aref->refassgnexpr, context))
1715                                         return true;
1716                         }
1717                         break;
1718                 case T_FieldSelect:
1719                         return walker(((FieldSelect *) node)->arg, context);
1720                 case T_RelabelType:
1721                         return walker(((RelabelType *) node)->arg, context);
1722                 case T_CaseExpr:
1723                         {
1724                                 CaseExpr   *caseexpr = (CaseExpr *) node;
1725
1726                                 /* we assume walker doesn't care about CaseWhens, either */
1727                                 foreach(temp, caseexpr->args)
1728                                 {
1729                                         CaseWhen   *when = (CaseWhen *) lfirst(temp);
1730
1731                                         Assert(IsA(when, CaseWhen));
1732                                         if (walker(when->expr, context))
1733                                                 return true;
1734                                         if (walker(when->result, context))
1735                                                 return true;
1736                                 }
1737                                 /* caseexpr->arg should be null, but we'll check it anyway */
1738                                 if (walker(caseexpr->arg, context))
1739                                         return true;
1740                                 if (walker(caseexpr->defresult, context))
1741                                         return true;
1742                         }
1743                         break;
1744                 case T_NullTest:
1745                         return walker(((NullTest *) node)->arg, context);
1746                 case T_BooleanTest:
1747                         return walker(((BooleanTest *) node)->arg, context);
1748                 case T_SubLink:
1749                         {
1750                                 SubLink    *sublink = (SubLink *) node;
1751
1752                                 /*
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
1758                                  * confusing).
1759                                  */
1760                                 if (sublink->lefthand)
1761                                 {
1762                                         if (walker((Node *) sublink->lefthand, context))
1763                                                 return true;
1764                                 }
1765                                 else
1766                                 {
1767                                         if (walker((Node *) sublink->oper, context))
1768                                                 return true;
1769                                 }
1770
1771                                 /*
1772                                  * Also invoke the walker on the sublink's Query node, so
1773                                  * it can recurse into the sub-query if it wants to.
1774                                  */
1775                                 return walker(sublink->subselect, context);
1776                         }
1777                         break;
1778                 case T_Query:
1779                         /* Do nothing with a sub-Query, per discussion above */
1780                         break;
1781                 case T_List:
1782                         foreach(temp, (List *) node)
1783                         {
1784                                 if (walker((Node *) lfirst(temp), context))
1785                                         return true;
1786                         }
1787                         break;
1788                 case T_TargetEntry:
1789                         return walker(((TargetEntry *) node)->expr, context);
1790                 case T_FromExpr:
1791                         {
1792                                 FromExpr   *from = (FromExpr *) node;
1793
1794                                 if (walker(from->fromlist, context))
1795                                         return true;
1796                                 if (walker(from->quals, context))
1797                                         return true;
1798                         }
1799                         break;
1800                 case T_JoinExpr:
1801                         {
1802                                 JoinExpr   *join = (JoinExpr *) node;
1803
1804                                 if (walker(join->larg, context))
1805                                         return true;
1806                                 if (walker(join->rarg, context))
1807                                         return true;
1808                                 if (walker(join->quals, context))
1809                                         return true;
1810                                 /*
1811                                  * alias clause, using list are deemed uninteresting.
1812                                  */
1813                         }
1814                         break;
1815                 case T_SetOperationStmt:
1816                         {
1817                                 SetOperationStmt *setop = (SetOperationStmt *) node;
1818
1819                                 if (walker(setop->larg, context))
1820                                         return true;
1821                                 if (walker(setop->rarg, context))
1822                                         return true;
1823                         }
1824                         break;
1825                 default:
1826                         elog(ERROR, "expression_tree_walker: Unexpected node type %d",
1827                                  nodeTag(node));
1828                         break;
1829         }
1830         return false;
1831 }
1832
1833 /*
1834  * query_tree_walker --- initiate a walk of a Query's expressions
1835  *
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.
1841  *
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.
1846  */
1847 bool
1848 query_tree_walker(Query *query,
1849                                   bool (*walker) (),
1850                                   void *context,
1851                                   bool visitQueryRTEs)
1852 {
1853         Assert(query != NULL && IsA(query, Query));
1854
1855         if (walker((Node *) query->targetList, context))
1856                 return true;
1857         if (walker((Node *) query->jointree, context))
1858                 return true;
1859         if (walker(query->setOperations, context))
1860                 return true;
1861         if (walker(query->havingQual, context))
1862                 return true;
1863         if (visitQueryRTEs)
1864         {
1865                 List       *rt;
1866
1867                 foreach(rt, query->rtable)
1868                 {
1869                         RangeTblEntry *rte = (RangeTblEntry *) lfirst(rt);
1870
1871                         if (rte->subquery)
1872                                 if (walker(rte->subquery, context))
1873                                         return true;
1874                 }
1875         }
1876         return false;
1877 }
1878
1879
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:
1887  *
1888  * Node * my_mutator (Node *node, my_struct *context)
1889  * {
1890  *              if (node == NULL)
1891  *                      return NULL;
1892  *              // check for nodes that special work is required for, eg:
1893  *              if (IsA(node, Var))
1894  *              {
1895  *                      ... create and return modified copy of Var node
1896  *              }
1897  *              else if (IsA(node, ...))
1898  *              {
1899  *                      ... do special transformations of other node types
1900  *              }
1901  *              // for any node type not specially processed, do:
1902  *              return expression_tree_mutator(node, my_mutator, (void *) context);
1903  * }
1904  *
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.
1912  *
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.
1919  *
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.
1923  *
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.
1930  *
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
1935  * behavior.
1936  *--------------------
1937  */
1938
1939 Node *
1940 expression_tree_mutator(Node *node,
1941                                                 Node *(*mutator) (),
1942                                                 void *context)
1943 {
1944         /*
1945          * The mutator has already decided not to modify the current node, but
1946          * we must call the mutator for any sub-nodes.
1947          */
1948
1949 #define FLATCOPY(newnode, node, nodetype)  \
1950         ( (newnode) = makeNode(nodetype), \
1951           memcpy((newnode), (node), sizeof(nodetype)) )
1952
1953 #define CHECKFLATCOPY(newnode, node, nodetype)  \
1954         ( AssertMacro(IsA((node), nodetype)), \
1955           (newnode) = makeNode(nodetype), \
1956           memcpy((newnode), (node), sizeof(nodetype)) )
1957
1958 #define MUTATE(newfield, oldfield, fieldtype)  \
1959                 ( (newfield) = (fieldtype) mutator((Node *) (oldfield), context) )
1960
1961         if (node == NULL)
1962                 return NULL;
1963         switch (nodeTag(node))
1964         {
1965                 case T_Const:
1966                 case T_Var:
1967                 case T_Param:
1968                 case T_RangeTblRef:
1969                         /* primitive node types with no subnodes */
1970                         return (Node *) copyObject(node);
1971                 case T_Expr:
1972                         {
1973                                 Expr       *expr = (Expr *) node;
1974                                 Expr       *newnode;
1975
1976                                 FLATCOPY(newnode, expr, Expr);
1977
1978                                 if (expr->opType == SUBPLAN_EXPR)
1979                                 {
1980                                         SubLink    *oldsublink = ((SubPlan *) expr->oper)->sublink;
1981                                         SubPlan    *newsubplan;
1982
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);
1988
1989                                         /*
1990                                          * transform args list (params to be passed to
1991                                          * subplan)
1992                                          */
1993                                         MUTATE(newnode->args, expr->args, List *);
1994                                         /* transform sublink's oper list as well */
1995                                         MUTATE(newsubplan->sublink->oper, oldsublink->oper, List *);
1996
1997                                         /*
1998                                          * but not the subplan itself, which is referenced
1999                                          * as-is
2000                                          */
2001                                 }
2002                                 else
2003                                 {
2004                                         /*
2005                                          * for other Expr node types, just transform args
2006                                          * list, linking to original oper node (OK?)
2007                                          */
2008                                         MUTATE(newnode->args, expr->args, List *);
2009                                 }
2010                                 return (Node *) newnode;
2011                         }
2012                         break;
2013                 case T_Aggref:
2014                         {
2015                                 Aggref     *aggref = (Aggref *) node;
2016                                 Aggref     *newnode;
2017
2018                                 FLATCOPY(newnode, aggref, Aggref);
2019                                 MUTATE(newnode->target, aggref->target, Node *);
2020                                 return (Node *) newnode;
2021                         }
2022                         break;
2023                 case T_Iter:
2024                         {
2025                                 Iter       *iter = (Iter *) node;
2026                                 Iter       *newnode;
2027
2028                                 FLATCOPY(newnode, iter, Iter);
2029                                 MUTATE(newnode->iterexpr, iter->iterexpr, Node *);
2030                                 return (Node *) newnode;
2031                         }
2032                         break;
2033                 case T_ArrayRef:
2034                         {
2035                                 ArrayRef   *arrayref = (ArrayRef *) node;
2036                                 ArrayRef   *newnode;
2037
2038                                 FLATCOPY(newnode, arrayref, ArrayRef);
2039                                 MUTATE(newnode->refupperindexpr, arrayref->refupperindexpr,
2040                                            List *);
2041                                 MUTATE(newnode->reflowerindexpr, arrayref->reflowerindexpr,
2042                                            List *);
2043                                 MUTATE(newnode->refexpr, arrayref->refexpr,
2044                                            Node *);
2045                                 MUTATE(newnode->refassgnexpr, arrayref->refassgnexpr,
2046                                            Node *);
2047                                 return (Node *) newnode;
2048                         }
2049                         break;
2050                 case T_FieldSelect:
2051                         {
2052                                 FieldSelect *fselect = (FieldSelect *) node;
2053                                 FieldSelect *newnode;
2054
2055                                 FLATCOPY(newnode, fselect, FieldSelect);
2056                                 MUTATE(newnode->arg, fselect->arg, Node *);
2057                                 return (Node *) newnode;
2058                         }
2059                         break;
2060                 case T_RelabelType:
2061                         {
2062                                 RelabelType *relabel = (RelabelType *) node;
2063                                 RelabelType *newnode;
2064
2065                                 FLATCOPY(newnode, relabel, RelabelType);
2066                                 MUTATE(newnode->arg, relabel->arg, Node *);
2067                                 return (Node *) newnode;
2068                         }
2069                         break;
2070                 case T_CaseExpr:
2071                         {
2072                                 CaseExpr   *caseexpr = (CaseExpr *) node;
2073                                 CaseExpr   *newnode;
2074
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;
2081                         }
2082                         break;
2083                 case T_CaseWhen:
2084                         {
2085                                 CaseWhen   *casewhen = (CaseWhen *) node;
2086                                 CaseWhen   *newnode;
2087
2088                                 FLATCOPY(newnode, casewhen, CaseWhen);
2089                                 MUTATE(newnode->expr, casewhen->expr, Node *);
2090                                 MUTATE(newnode->result, casewhen->result, Node *);
2091                                 return (Node *) newnode;
2092                         }
2093                         break;
2094                 case T_NullTest:
2095                         {
2096                                 NullTest   *ntest = (NullTest *) node;
2097                                 NullTest   *newnode;
2098
2099                                 FLATCOPY(newnode, ntest, NullTest);
2100                                 MUTATE(newnode->arg, ntest->arg, Node *);
2101                                 return (Node *) newnode;
2102                         }
2103                         break;
2104                 case T_BooleanTest:
2105                         {
2106                                 BooleanTest *btest = (BooleanTest *) node;
2107                                 BooleanTest *newnode;
2108
2109                                 FLATCOPY(newnode, btest, BooleanTest);
2110                                 MUTATE(newnode->arg, btest->arg, Node *);
2111                                 return (Node *) newnode;
2112                         }
2113                         break;
2114                 case T_SubLink:
2115                         {
2116                                 /*
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.
2120                                  */
2121                                 SubLink    *sublink = (SubLink *) node;
2122                                 SubLink    *newnode;
2123
2124                                 FLATCOPY(newnode, sublink, SubLink);
2125                                 MUTATE(newnode->lefthand, sublink->lefthand, List *);
2126                                 return (Node *) newnode;
2127                         }
2128                         break;
2129                 case T_List:
2130                         {
2131                                 /*
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
2135                                  * elements!
2136                                  */
2137                                 List       *resultlist = NIL;
2138                                 List       *temp;
2139
2140                                 foreach(temp, (List *) node)
2141                                 {
2142                                         resultlist = lappend(resultlist,
2143                                                                                  mutator((Node *) lfirst(temp),
2144                                                                                                  context));
2145                                 }
2146                                 return (Node *) resultlist;
2147                         }
2148                         break;
2149                 case T_TargetEntry:
2150                         {
2151                                 /*
2152                                  * We mutate the expression, but not the resdom, by
2153                                  * default.
2154                                  */
2155                                 TargetEntry *targetentry = (TargetEntry *) node;
2156                                 TargetEntry *newnode;
2157
2158                                 FLATCOPY(newnode, targetentry, TargetEntry);
2159                                 MUTATE(newnode->expr, targetentry->expr, Node *);
2160                                 return (Node *) newnode;
2161                         }
2162                         break;
2163                 case T_FromExpr:
2164                         {
2165                                 FromExpr   *from = (FromExpr *) node;
2166                                 FromExpr   *newnode;
2167
2168                                 FLATCOPY(newnode, from, FromExpr);
2169                                 MUTATE(newnode->fromlist, from->fromlist, List *);
2170                                 MUTATE(newnode->quals, from->quals, Node *);
2171                                 return (Node *) newnode;
2172                         }
2173                         break;
2174                 case T_JoinExpr:
2175                         {
2176                                 JoinExpr   *join = (JoinExpr *) node;
2177                                 JoinExpr   *newnode;
2178
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;
2185                         }
2186                         break;
2187                 case T_SetOperationStmt:
2188                         {
2189                                 SetOperationStmt *setop = (SetOperationStmt *) node;
2190                                 SetOperationStmt *newnode;
2191
2192                                 FLATCOPY(newnode, setop, SetOperationStmt);
2193                                 MUTATE(newnode->larg, setop->larg, Node *);
2194                                 MUTATE(newnode->rarg, setop->rarg, Node *);
2195                                 return (Node *) newnode;
2196                         }
2197                         break;
2198                 default:
2199                         elog(ERROR, "expression_tree_mutator: Unexpected node type %d",
2200                                  nodeTag(node));
2201                         break;
2202         }
2203         /* can't get here, but keep compiler happy */
2204         return NULL;
2205 }
2206
2207
2208 /*
2209  * query_tree_mutator --- initiate modification of a Query's expressions
2210  *
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.
2216  *
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
2219  * copied, however.
2220  *
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.
2225  */
2226 void
2227 query_tree_mutator(Query *query,
2228                                    Node *(*mutator) (),
2229                                    void *context,
2230                                    bool visitQueryRTEs)
2231 {
2232         Assert(query != NULL && IsA(query, Query));
2233
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 *);
2238         if (visitQueryRTEs)
2239         {
2240                 List       *newrt = NIL;
2241                 List       *rt;
2242
2243                 foreach(rt, query->rtable)
2244                 {
2245                         RangeTblEntry *rte = (RangeTblEntry *) lfirst(rt);
2246
2247                         if (rte->subquery)
2248                         {
2249                                 RangeTblEntry *newrte;
2250
2251                                 FLATCOPY(newrte, rte, RangeTblEntry);
2252                                 CHECKFLATCOPY(newrte->subquery, rte->subquery, Query);
2253                                 MUTATE(newrte->subquery, newrte->subquery, Query *);
2254                                 rte = newrte;
2255                         }
2256                         newrt = lappend(newrt, rte);
2257                 }
2258                 query->rtable = newrt;
2259         }
2260 }