]> granicus.if.org Git - postgresql/blob - src/backend/optimizer/util/clauses.c
Improve has_nullable_targetlist() to allow strict functions of simple
[postgresql] / src / backend / optimizer / util / clauses.c
1 /*-------------------------------------------------------------------------
2  *
3  * clauses.c
4  *        routines to manipulate qualification clauses
5  *
6  * Portions Copyright (c) 1996-2003, PostgreSQL Global Development Group
7  * Portions Copyright (c) 1994, Regents of the University of California
8  *
9  *
10  * IDENTIFICATION
11  *        $PostgreSQL: pgsql/src/backend/optimizer/util/clauses.c,v 1.161 2004/01/10 18:13:53 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_language.h"
23 #include "catalog/pg_proc.h"
24 #include "catalog/pg_type.h"
25 #include "executor/executor.h"
26 #include "miscadmin.h"
27 #include "nodes/makefuncs.h"
28 #include "optimizer/clauses.h"
29 #include "optimizer/cost.h"
30 #include "optimizer/planmain.h"
31 #include "optimizer/var.h"
32 #include "parser/analyze.h"
33 #include "parser/parse_clause.h"
34 #include "parser/parse_expr.h"
35 #include "tcop/tcopprot.h"
36 #include "utils/acl.h"
37 #include "utils/builtins.h"
38 #include "utils/datum.h"
39 #include "utils/lsyscache.h"
40 #include "utils/memutils.h"
41 #include "utils/syscache.h"
42
43
44 /* note that pg_type.h hardwires size of bool as 1 ... duplicate it */
45 #define MAKEBOOLCONST(val,isnull) \
46         ((Node *) makeConst(BOOLOID, 1, (Datum) (val), (isnull), true))
47
48 typedef struct
49 {
50         int                     nargs;
51         List       *args;
52         int                *usecounts;
53 } substitute_actual_parameters_context;
54
55 static bool contain_agg_clause_walker(Node *node, void *context);
56 static bool contain_distinct_agg_clause_walker(Node *node, void *context);
57 static bool count_agg_clause_walker(Node *node, int *count);
58 static bool expression_returns_set_walker(Node *node, void *context);
59 static bool contain_subplans_walker(Node *node, void *context);
60 static bool contain_mutable_functions_walker(Node *node, void *context);
61 static bool contain_volatile_functions_walker(Node *node, void *context);
62 static bool contain_nonstrict_functions_walker(Node *node, void *context);
63 static Node *eval_const_expressions_mutator(Node *node, List *active_fns);
64 static Expr *simplify_function(Oid funcid, Oid result_type, List *args,
65                                   bool allow_inline, List *active_fns);
66 static Expr *evaluate_function(Oid funcid, Oid result_type, List *args,
67                                   HeapTuple func_tuple);
68 static Expr *inline_function(Oid funcid, Oid result_type, List *args,
69                                 HeapTuple func_tuple, List *active_fns);
70 static Node *substitute_actual_parameters(Node *expr, int nargs, List *args,
71                                                          int *usecounts);
72 static Node *substitute_actual_parameters_mutator(Node *node,
73                                                   substitute_actual_parameters_context *context);
74 static void sql_inline_error_callback(void *arg);
75 static Expr *evaluate_expr(Expr *expr, Oid result_type);
76
77
78 /*****************************************************************************
79  *              OPERATOR clause functions
80  *****************************************************************************/
81
82 /*
83  * make_opclause
84  *        Creates an operator clause given its operator info, left operand,
85  *        and right operand (pass NULL to create single-operand clause).
86  */
87 Expr *
88 make_opclause(Oid opno, Oid opresulttype, bool opretset,
89                           Expr *leftop, Expr *rightop)
90 {
91         OpExpr     *expr = makeNode(OpExpr);
92
93         expr->opno = opno;
94         expr->opfuncid = InvalidOid;
95         expr->opresulttype = opresulttype;
96         expr->opretset = opretset;
97         if (rightop)
98                 expr->args = makeList2(leftop, rightop);
99         else
100                 expr->args = makeList1(leftop);
101         return (Expr *) expr;
102 }
103
104 /*
105  * get_leftop
106  *
107  * Returns the left operand of a clause of the form (op expr expr)
108  *              or (op expr)
109  */
110 Node *
111 get_leftop(Expr *clause)
112 {
113         OpExpr     *expr = (OpExpr *) clause;
114
115         if (expr->args != NIL)
116                 return lfirst(expr->args);
117         else
118                 return NULL;
119 }
120
121 /*
122  * get_rightop
123  *
124  * Returns the right operand in a clause of the form (op expr expr).
125  * NB: result will be NULL if applied to a unary op clause.
126  */
127 Node *
128 get_rightop(Expr *clause)
129 {
130         OpExpr     *expr = (OpExpr *) clause;
131
132         if (expr->args != NIL && lnext(expr->args) != NIL)
133                 return lfirst(lnext(expr->args));
134         else
135                 return NULL;
136 }
137
138 /*****************************************************************************
139  *              NOT clause functions
140  *****************************************************************************/
141
142 /*
143  * not_clause
144  *
145  * Returns t iff this is a 'not' clause: (NOT expr).
146  */
147 bool
148 not_clause(Node *clause)
149 {
150         return (clause != NULL &&
151                         IsA(clause, BoolExpr) &&
152                         ((BoolExpr *) clause)->boolop == NOT_EXPR);
153 }
154
155 /*
156  * make_notclause
157  *
158  * Create a 'not' clause given the expression to be negated.
159  */
160 Expr *
161 make_notclause(Expr *notclause)
162 {
163         BoolExpr   *expr = makeNode(BoolExpr);
164
165         expr->boolop = NOT_EXPR;
166         expr->args = makeList1(notclause);
167         return (Expr *) expr;
168 }
169
170 /*
171  * get_notclausearg
172  *
173  * Retrieve the clause within a 'not' clause
174  */
175 Expr *
176 get_notclausearg(Expr *notclause)
177 {
178         return lfirst(((BoolExpr *) notclause)->args);
179 }
180
181 /*****************************************************************************
182  *              OR clause functions
183  *****************************************************************************/
184
185 /*
186  * or_clause
187  *
188  * Returns t iff the clause is an 'or' clause: (OR { expr }).
189  */
190 bool
191 or_clause(Node *clause)
192 {
193         return (clause != NULL &&
194                         IsA(clause, BoolExpr) &&
195                         ((BoolExpr *) clause)->boolop == OR_EXPR);
196 }
197
198 /*
199  * make_orclause
200  *
201  * Creates an 'or' clause given a list of its subclauses.
202  */
203 Expr *
204 make_orclause(List *orclauses)
205 {
206         BoolExpr   *expr = makeNode(BoolExpr);
207
208         expr->boolop = OR_EXPR;
209         expr->args = orclauses;
210         return (Expr *) expr;
211 }
212
213 /*****************************************************************************
214  *              AND clause functions
215  *****************************************************************************/
216
217
218 /*
219  * and_clause
220  *
221  * Returns t iff its argument is an 'and' clause: (AND { expr }).
222  */
223 bool
224 and_clause(Node *clause)
225 {
226         return (clause != NULL &&
227                         IsA(clause, BoolExpr) &&
228                         ((BoolExpr *) clause)->boolop == AND_EXPR);
229 }
230
231 /*
232  * make_andclause
233  *
234  * Creates an 'and' clause given a list of its subclauses.
235  */
236 Expr *
237 make_andclause(List *andclauses)
238 {
239         BoolExpr   *expr = makeNode(BoolExpr);
240
241         expr->boolop = AND_EXPR;
242         expr->args = andclauses;
243         return (Expr *) expr;
244 }
245
246 /*
247  * make_and_qual
248  *
249  * Variant of make_andclause for ANDing two qual conditions together.
250  * Qual conditions have the property that a NULL nodetree is interpreted
251  * as 'true'.
252  */
253 Node *
254 make_and_qual(Node *qual1, Node *qual2)
255 {
256         if (qual1 == NULL)
257                 return qual2;
258         if (qual2 == NULL)
259                 return qual1;
260         return (Node *) make_andclause(makeList2(qual1, qual2));
261 }
262
263 /*
264  * Sometimes (such as in the input of ExecQual), we use lists of expression
265  * nodes with implicit AND semantics.
266  *
267  * These functions convert between an AND-semantics expression list and the
268  * ordinary representation of a boolean expression.
269  *
270  * Note that an empty list is considered equivalent to TRUE.
271  */
272 Expr *
273 make_ands_explicit(List *andclauses)
274 {
275         if (andclauses == NIL)
276                 return (Expr *) MAKEBOOLCONST(true, false);
277         else if (lnext(andclauses) == NIL)
278                 return (Expr *) lfirst(andclauses);
279         else
280                 return make_andclause(andclauses);
281 }
282
283 List *
284 make_ands_implicit(Expr *clause)
285 {
286         /*
287          * NB: because the parser sets the qual field to NULL in a query that
288          * has no WHERE clause, we must consider a NULL input clause as TRUE,
289          * even though one might more reasonably think it FALSE.  Grumble. If
290          * this causes trouble, consider changing the parser's behavior.
291          */
292         if (clause == NULL)
293                 return NIL;                             /* NULL -> NIL list == TRUE */
294         else if (and_clause((Node *) clause))
295                 return ((BoolExpr *) clause)->args;
296         else if (IsA(clause, Const) &&
297                          !((Const *) clause)->constisnull &&
298                          DatumGetBool(((Const *) clause)->constvalue))
299                 return NIL;                             /* constant TRUE input -> NIL list */
300         else
301                 return makeList1(clause);
302 }
303
304
305 /*****************************************************************************
306  *              Aggregate-function clause manipulation
307  *****************************************************************************/
308
309 /*
310  * contain_agg_clause
311  *        Recursively search for Aggref nodes within a clause.
312  *
313  *        Returns true if any aggregate found.
314  *
315  * This does not descend into subqueries, and so should be used only after
316  * reduction of sublinks to subplans, or in contexts where it's known there
317  * are no subqueries.  There mustn't be outer-aggregate references either.
318  *
319  * (If you want something like this but able to deal with subqueries,
320  * see rewriteManip.c's checkExprHasAggs().)
321  */
322 bool
323 contain_agg_clause(Node *clause)
324 {
325         return contain_agg_clause_walker(clause, NULL);
326 }
327
328 static bool
329 contain_agg_clause_walker(Node *node, void *context)
330 {
331         if (node == NULL)
332                 return false;
333         if (IsA(node, Aggref))
334         {
335                 Assert(((Aggref *) node)->agglevelsup == 0);
336                 return true;                    /* abort the tree traversal and return
337                                                                  * true */
338         }
339         Assert(!IsA(node, SubLink));
340         return expression_tree_walker(node, contain_agg_clause_walker, context);
341 }
342
343 /*
344  * contain_distinct_agg_clause
345  *        Recursively search for DISTINCT Aggref nodes within a clause.
346  *
347  *        Returns true if any DISTINCT aggregate found.
348  *
349  * This does not descend into subqueries, and so should be used only after
350  * reduction of sublinks to subplans, or in contexts where it's known there
351  * are no subqueries.  There mustn't be outer-aggregate references either.
352  */
353 bool
354 contain_distinct_agg_clause(Node *clause)
355 {
356         return contain_distinct_agg_clause_walker(clause, NULL);
357 }
358
359 static bool
360 contain_distinct_agg_clause_walker(Node *node, void *context)
361 {
362         if (node == NULL)
363                 return false;
364         if (IsA(node, Aggref))
365         {
366                 Assert(((Aggref *) node)->agglevelsup == 0);
367                 if (((Aggref *) node)->aggdistinct)
368                         return true;            /* abort the tree traversal and return
369                                                                  * true */
370         }
371         Assert(!IsA(node, SubLink));
372         return expression_tree_walker(node, contain_distinct_agg_clause_walker, context);
373 }
374
375 /*
376  * count_agg_clause
377  *        Recursively count the Aggref nodes in an expression tree.
378  *
379  *        Note: this also checks for nested aggregates, which are an error.
380  *
381  * This does not descend into subqueries, and so should be used only after
382  * reduction of sublinks to subplans, or in contexts where it's known there
383  * are no subqueries.  There mustn't be outer-aggregate references either.
384  */
385 int
386 count_agg_clause(Node *clause)
387 {
388         int                     result = 0;
389
390         count_agg_clause_walker(clause, &result);
391         return result;
392 }
393
394 static bool
395 count_agg_clause_walker(Node *node, int *count)
396 {
397         if (node == NULL)
398                 return false;
399         if (IsA(node, Aggref))
400         {
401                 Assert(((Aggref *) node)->agglevelsup == 0);
402                 (*count)++;
403
404                 /*
405                  * Complain if the aggregate's argument contains any aggregates;
406                  * nested agg functions are semantically nonsensical.
407                  */
408                 if (contain_agg_clause((Node *) ((Aggref *) node)->target))
409                         ereport(ERROR,
410                                         (errcode(ERRCODE_GROUPING_ERROR),
411                                   errmsg("aggregate function calls may not be nested")));
412
413                 /*
414                  * Having checked that, we need not recurse into the argument.
415                  */
416                 return false;
417         }
418         Assert(!IsA(node, SubLink));
419         return expression_tree_walker(node, count_agg_clause_walker,
420                                                                   (void *) count);
421 }
422
423
424 /*****************************************************************************
425  *              Support for expressions returning sets
426  *****************************************************************************/
427
428 /*
429  * expression_returns_set
430  *        Test whether an expression returns a set result.
431  *
432  * Because we use expression_tree_walker(), this can also be applied to
433  * whole targetlists; it'll produce TRUE if any one of the tlist items
434  * returns a set.
435  */
436 bool
437 expression_returns_set(Node *clause)
438 {
439         return expression_returns_set_walker(clause, NULL);
440 }
441
442 static bool
443 expression_returns_set_walker(Node *node, void *context)
444 {
445         if (node == NULL)
446                 return false;
447         if (IsA(node, FuncExpr))
448         {
449                 FuncExpr   *expr = (FuncExpr *) node;
450
451                 if (expr->funcretset)
452                         return true;
453                 /* else fall through to check args */
454         }
455         if (IsA(node, OpExpr))
456         {
457                 OpExpr     *expr = (OpExpr *) node;
458
459                 if (expr->opretset)
460                         return true;
461                 /* else fall through to check args */
462         }
463
464         /* Avoid recursion for some cases that can't return a set */
465         if (IsA(node, Aggref))
466                 return false;
467         if (IsA(node, DistinctExpr))
468                 return false;
469         if (IsA(node, ScalarArrayOpExpr))
470                 return false;
471         if (IsA(node, BoolExpr))
472                 return false;
473         if (IsA(node, SubLink))
474                 return false;
475         if (IsA(node, SubPlan))
476                 return false;
477         if (IsA(node, ArrayExpr))
478                 return false;
479         if (IsA(node, CoalesceExpr))
480                 return false;
481         if (IsA(node, NullIfExpr))
482                 return false;
483
484         return expression_tree_walker(node, expression_returns_set_walker,
485                                                                   context);
486 }
487
488 /*****************************************************************************
489  *              Subplan clause manipulation
490  *****************************************************************************/
491
492 /*
493  * contain_subplans
494  *        Recursively search for subplan nodes within a clause.
495  *
496  * If we see a SubLink node, we will return TRUE.  This is only possible if
497  * the expression tree hasn't yet been transformed by subselect.c.  We do not
498  * know whether the node will produce a true subplan or just an initplan,
499  * but we make the conservative assumption that it will be a subplan.
500  *
501  * Returns true if any subplan found.
502  */
503 bool
504 contain_subplans(Node *clause)
505 {
506         return contain_subplans_walker(clause, NULL);
507 }
508
509 static bool
510 contain_subplans_walker(Node *node, void *context)
511 {
512         if (node == NULL)
513                 return false;
514         if (IsA(node, SubPlan) ||
515                 IsA(node, SubLink))
516                 return true;                    /* abort the tree traversal and return
517                                                                  * true */
518         return expression_tree_walker(node, contain_subplans_walker, context);
519 }
520
521
522 /*****************************************************************************
523  *              Check clauses for mutable functions
524  *****************************************************************************/
525
526 /*
527  * contain_mutable_functions
528  *        Recursively search for mutable functions within a clause.
529  *
530  * Returns true if any mutable function (or operator implemented by a
531  * mutable function) is found.  This test is needed so that we don't
532  * mistakenly think that something like "WHERE random() < 0.5" can be treated
533  * as a constant qualification.
534  *
535  * XXX we do not examine sub-selects to see if they contain uses of
536  * mutable functions.  It's not real clear if that is correct or not...
537  */
538 bool
539 contain_mutable_functions(Node *clause)
540 {
541         return contain_mutable_functions_walker(clause, NULL);
542 }
543
544 static bool
545 contain_mutable_functions_walker(Node *node, void *context)
546 {
547         if (node == NULL)
548                 return false;
549         if (IsA(node, FuncExpr))
550         {
551                 FuncExpr   *expr = (FuncExpr *) node;
552
553                 if (func_volatile(expr->funcid) != PROVOLATILE_IMMUTABLE)
554                         return true;
555                 /* else fall through to check args */
556         }
557         if (IsA(node, OpExpr))
558         {
559                 OpExpr     *expr = (OpExpr *) node;
560
561                 if (op_volatile(expr->opno) != PROVOLATILE_IMMUTABLE)
562                         return true;
563                 /* else fall through to check args */
564         }
565         if (IsA(node, DistinctExpr))
566         {
567                 DistinctExpr *expr = (DistinctExpr *) node;
568
569                 if (op_volatile(expr->opno) != PROVOLATILE_IMMUTABLE)
570                         return true;
571                 /* else fall through to check args */
572         }
573         if (IsA(node, ScalarArrayOpExpr))
574         {
575                 ScalarArrayOpExpr *expr = (ScalarArrayOpExpr *) node;
576
577                 if (op_volatile(expr->opno) != PROVOLATILE_IMMUTABLE)
578                         return true;
579                 /* else fall through to check args */
580         }
581         if (IsA(node, NullIfExpr))
582         {
583                 NullIfExpr *expr = (NullIfExpr *) node;
584
585                 if (op_volatile(expr->opno) != PROVOLATILE_IMMUTABLE)
586                         return true;
587                 /* else fall through to check args */
588         }
589         if (IsA(node, SubLink))
590         {
591                 SubLink    *sublink = (SubLink *) node;
592                 List       *opid;
593
594                 foreach(opid, sublink->operOids)
595                 {
596                         if (op_volatile(lfirsto(opid)) != PROVOLATILE_IMMUTABLE)
597                                 return true;
598                 }
599                 /* else fall through to check args */
600         }
601         return expression_tree_walker(node, contain_mutable_functions_walker,
602                                                                   context);
603 }
604
605
606 /*****************************************************************************
607  *              Check clauses for volatile functions
608  *****************************************************************************/
609
610 /*
611  * contain_volatile_functions
612  *        Recursively search for volatile functions within a clause.
613  *
614  * Returns true if any volatile function (or operator implemented by a
615  * volatile function) is found. This test prevents invalid conversions
616  * of volatile expressions into indexscan quals.
617  *
618  * XXX we do not examine sub-selects to see if they contain uses of
619  * volatile functions.  It's not real clear if that is correct or not...
620  */
621 bool
622 contain_volatile_functions(Node *clause)
623 {
624         return contain_volatile_functions_walker(clause, NULL);
625 }
626
627 static bool
628 contain_volatile_functions_walker(Node *node, void *context)
629 {
630         if (node == NULL)
631                 return false;
632         if (IsA(node, FuncExpr))
633         {
634                 FuncExpr   *expr = (FuncExpr *) node;
635
636                 if (func_volatile(expr->funcid) == PROVOLATILE_VOLATILE)
637                         return true;
638                 /* else fall through to check args */
639         }
640         if (IsA(node, OpExpr))
641         {
642                 OpExpr     *expr = (OpExpr *) node;
643
644                 if (op_volatile(expr->opno) == PROVOLATILE_VOLATILE)
645                         return true;
646                 /* else fall through to check args */
647         }
648         if (IsA(node, DistinctExpr))
649         {
650                 DistinctExpr *expr = (DistinctExpr *) node;
651
652                 if (op_volatile(expr->opno) == PROVOLATILE_VOLATILE)
653                         return true;
654                 /* else fall through to check args */
655         }
656         if (IsA(node, ScalarArrayOpExpr))
657         {
658                 ScalarArrayOpExpr *expr = (ScalarArrayOpExpr *) node;
659
660                 if (op_volatile(expr->opno) == PROVOLATILE_VOLATILE)
661                         return true;
662                 /* else fall through to check args */
663         }
664         if (IsA(node, NullIfExpr))
665         {
666                 NullIfExpr *expr = (NullIfExpr *) node;
667
668                 if (op_volatile(expr->opno) == PROVOLATILE_VOLATILE)
669                         return true;
670                 /* else fall through to check args */
671         }
672         if (IsA(node, SubLink))
673         {
674                 SubLink    *sublink = (SubLink *) node;
675                 List       *opid;
676
677                 foreach(opid, sublink->operOids)
678                 {
679                         if (op_volatile(lfirsto(opid)) == PROVOLATILE_VOLATILE)
680                                 return true;
681                 }
682                 /* else fall through to check args */
683         }
684         return expression_tree_walker(node, contain_volatile_functions_walker,
685                                                                   context);
686 }
687
688
689 /*****************************************************************************
690  *              Check clauses for nonstrict functions
691  *****************************************************************************/
692
693 /*
694  * contain_nonstrict_functions
695  *        Recursively search for nonstrict functions within a clause.
696  *
697  * Returns true if any nonstrict construct is found --- ie, anything that
698  * could produce non-NULL output with a NULL input.
699  *
700  * The idea here is that the caller has verified that the expression contains
701  * one or more Var or Param nodes (as appropriate for the caller's need), and
702  * now wishes to prove that the expression result will be NULL if any of these
703  * inputs is NULL.  If we return false, then the proof succeeded.
704  */
705 bool
706 contain_nonstrict_functions(Node *clause)
707 {
708         return contain_nonstrict_functions_walker(clause, NULL);
709 }
710
711 static bool
712 contain_nonstrict_functions_walker(Node *node, void *context)
713 {
714         if (node == NULL)
715                 return false;
716         if (IsA(node, Aggref))
717         {
718                 /* an aggregate could return non-null with null input */
719                 return true;
720         }
721         if (IsA(node, FuncExpr))
722         {
723                 FuncExpr   *expr = (FuncExpr *) node;
724
725                 if (!func_strict(expr->funcid))
726                         return true;
727                 /* else fall through to check args */
728         }
729         if (IsA(node, OpExpr))
730         {
731                 OpExpr     *expr = (OpExpr *) node;
732
733                 if (!op_strict(expr->opno))
734                         return true;
735                 /* else fall through to check args */
736         }
737         if (IsA(node, DistinctExpr))
738         {
739                 /* IS DISTINCT FROM is inherently non-strict */
740                 return true;
741         }
742         if (IsA(node, ScalarArrayOpExpr))
743         {
744                 /* inherently non-strict, consider null scalar and empty array */
745                 return true;
746         }
747         if (IsA(node, BoolExpr))
748         {
749                 BoolExpr   *expr = (BoolExpr *) node;
750
751                 switch (expr->boolop)
752                 {
753                         case AND_EXPR:
754                         case OR_EXPR:
755                                 /* AND, OR are inherently non-strict */
756                                 return true;
757                         default:
758                                 break;
759                 }
760         }
761         if (IsA(node, SubLink))
762         {
763                 /* In some cases a sublink might be strict, but in general not */
764                 return true;
765         }
766         if (IsA(node, SubPlan))
767                 return true;
768         if (IsA(node, CaseExpr))
769                 return true;
770         if (IsA(node, CaseWhen))
771                 return true;
772         /* NB: ArrayExpr might someday be nonstrict */
773         if (IsA(node, CoalesceExpr))
774                 return true;
775         if (IsA(node, NullIfExpr))
776                 return true;
777         if (IsA(node, NullTest))
778                 return true;
779         if (IsA(node, BooleanTest))
780                 return true;
781         return expression_tree_walker(node, contain_nonstrict_functions_walker,
782                                                                   context);
783 }
784
785
786 /*****************************************************************************
787  *              Check for "pseudo-constant" clauses
788  *****************************************************************************/
789
790 /*
791  * is_pseudo_constant_clause
792  *        Detect whether a clause is "constant", ie, it contains no variables
793  *        of the current query level and no uses of volatile functions.
794  *        Such a clause is not necessarily a true constant: it can still contain
795  *        Params and outer-level Vars, not to mention functions whose results
796  *        may vary from one statement to the next.      However, the clause's value
797  *        will be constant over any one scan of the current query, so it can be
798  *        used as an indexscan key or (if a top-level qual) can be pushed up to
799  *        become a gating qual.
800  */
801 bool
802 is_pseudo_constant_clause(Node *clause)
803 {
804         /*
805          * We could implement this check in one recursive scan.  But since the
806          * check for volatile functions is both moderately expensive and
807          * unlikely to fail, it seems better to look for Vars first and only
808          * check for volatile functions if we find no Vars.
809          */
810         if (!contain_var_clause(clause) &&
811                 !contain_volatile_functions(clause))
812                 return true;
813         return false;
814 }
815
816 /*
817  * is_pseudo_constant_clause_relids
818  *        Same as above, except caller already has available the var membership
819  *        of the clause; this lets us avoid the contain_var_clause() scan.
820  */
821 bool
822 is_pseudo_constant_clause_relids(Node *clause, Relids relids)
823 {
824         if (bms_is_empty(relids) &&
825                 !contain_volatile_functions(clause))
826                 return true;
827         return false;
828 }
829
830 /*
831  * pull_constant_clauses
832  *              Scan through a list of qualifications and separate "constant" quals
833  *              from those that are not.
834  *
835  * Returns a list of the pseudo-constant clauses in constantQual and the
836  * remaining quals as the return value.
837  */
838 List *
839 pull_constant_clauses(List *quals, List **constantQual)
840 {
841         FastList        constqual,
842                                 restqual;
843         List       *q;
844
845         FastListInit(&constqual);
846         FastListInit(&restqual);
847
848         foreach(q, quals)
849         {
850                 Node       *qual = (Node *) lfirst(q);
851
852                 if (is_pseudo_constant_clause(qual))
853                         FastAppend(&constqual, qual);
854                 else
855                         FastAppend(&restqual, qual);
856         }
857         *constantQual = FastListValue(&constqual);
858         return FastListValue(&restqual);
859 }
860
861
862 /*****************************************************************************
863  *              Tests on clauses of queries
864  *
865  * Possibly this code should go someplace else, since this isn't quite the
866  * same meaning of "clause" as is used elsewhere in this module.  But I can't
867  * think of a better place for it...
868  *****************************************************************************/
869
870 /*
871  * Test whether a query uses DISTINCT ON, ie, has a distinct-list that is
872  * not the same as the set of output columns.
873  */
874 bool
875 has_distinct_on_clause(Query *query)
876 {
877         List       *targetList;
878
879         /* Is there a DISTINCT clause at all? */
880         if (query->distinctClause == NIL)
881                 return false;
882
883         /*
884          * If the DISTINCT list contains all the nonjunk targetlist items, and
885          * nothing else (ie, no junk tlist items), then it's a simple
886          * DISTINCT, else it's DISTINCT ON.  We do not require the lists to be
887          * in the same order (since the parser may have adjusted the DISTINCT
888          * clause ordering to agree with ORDER BY).  Furthermore, a
889          * non-DISTINCT junk tlist item that is in the sortClause is also
890          * evidence of DISTINCT ON, since we don't allow ORDER BY on junk
891          * tlist items when plain DISTINCT is used.
892          *
893          * This code assumes that the DISTINCT list is valid, ie, all its entries
894          * match some entry of the tlist.
895          */
896         foreach(targetList, query->targetList)
897         {
898                 TargetEntry *tle = (TargetEntry *) lfirst(targetList);
899
900                 if (tle->resdom->ressortgroupref == 0)
901                 {
902                         if (tle->resdom->resjunk)
903                                 continue;               /* we can ignore unsorted junk cols */
904                         return true;            /* definitely not in DISTINCT list */
905                 }
906                 if (targetIsInSortList(tle, query->distinctClause))
907                 {
908                         if (tle->resdom->resjunk)
909                                 return true;    /* junk TLE in DISTINCT means DISTINCT ON */
910                         /* else this TLE is okay, keep looking */
911                 }
912                 else
913                 {
914                         /* This TLE is not in DISTINCT list */
915                         if (!tle->resdom->resjunk)
916                                 return true;    /* non-junk, non-DISTINCT, so DISTINCT ON */
917                         if (targetIsInSortList(tle, query->sortClause))
918                                 return true;    /* sorted, non-distinct junk */
919                         /* unsorted junk is okay, keep looking */
920                 }
921         }
922         /* It's a simple DISTINCT */
923         return false;
924 }
925
926 /*
927  * Test whether a query uses simple DISTINCT, ie, has a distinct-list that
928  * is the same as the set of output columns.
929  */
930 bool
931 has_distinct_clause(Query *query)
932 {
933         /* Is there a DISTINCT clause at all? */
934         if (query->distinctClause == NIL)
935                 return false;
936
937         /* It's DISTINCT if it's not DISTINCT ON */
938         return !has_distinct_on_clause(query);
939 }
940
941
942 /*****************************************************************************
943  *                                                                                                                                                       *
944  *              General clause-manipulating routines                                                             *
945  *                                                                                                                                                       *
946  *****************************************************************************/
947
948 /*
949  * NumRelids
950  *              (formerly clause_relids)
951  *
952  * Returns the number of different relations referenced in 'clause'.
953  */
954 int
955 NumRelids(Node *clause)
956 {
957         Relids          varnos = pull_varnos(clause);
958         int                     result = bms_num_members(varnos);
959
960         bms_free(varnos);
961         return result;
962 }
963
964 /*
965  * CommuteClause: commute a binary operator clause
966  *
967  * XXX the clause is destructively modified!
968  */
969 void
970 CommuteClause(OpExpr *clause)
971 {
972         Oid                     opoid;
973         Node       *temp;
974
975         /* Sanity checks: caller is at fault if these fail */
976         if (!is_opclause(clause) ||
977                 length(clause->args) != 2)
978                 elog(ERROR, "cannot commute non-binary-operator clause");
979
980         opoid = get_commutator(clause->opno);
981
982         if (!OidIsValid(opoid))
983                 elog(ERROR, "could not find commutator for operator %u",
984                          clause->opno);
985
986         /*
987          * modify the clause in-place!
988          */
989         clause->opno = opoid;
990         clause->opfuncid = InvalidOid;
991         /* opresulttype and opretset are assumed not to change */
992
993         temp = lfirst(clause->args);
994         lfirst(clause->args) = lsecond(clause->args);
995         lsecond(clause->args) = temp;
996 }
997
998
999 /*--------------------
1000  * eval_const_expressions
1001  *
1002  * Reduce any recognizably constant subexpressions of the given
1003  * expression tree, for example "2 + 2" => "4".  More interestingly,
1004  * we can reduce certain boolean expressions even when they contain
1005  * non-constant subexpressions: "x OR true" => "true" no matter what
1006  * the subexpression x is.      (XXX We assume that no such subexpression
1007  * will have important side-effects, which is not necessarily a good
1008  * assumption in the presence of user-defined functions; do we need a
1009  * pg_proc flag that prevents discarding the execution of a function?)
1010  *
1011  * We do understand that certain functions may deliver non-constant
1012  * results even with constant inputs, "nextval()" being the classic
1013  * example.  Functions that are not marked "immutable" in pg_proc
1014  * will not be pre-evaluated here, although we will reduce their
1015  * arguments as far as possible.
1016  *
1017  * We assume that the tree has already been type-checked and contains
1018  * only operators and functions that are reasonable to try to execute.
1019  *--------------------
1020  */
1021 Node *
1022 eval_const_expressions(Node *node)
1023 {
1024         /*
1025          * The context for the mutator is a list of SQL functions being
1026          * recursively simplified, so we start with an empty list.
1027          */
1028         return eval_const_expressions_mutator(node, NIL);
1029 }
1030
1031 static Node *
1032 eval_const_expressions_mutator(Node *node, List *active_fns)
1033 {
1034         if (node == NULL)
1035                 return NULL;
1036         if (IsA(node, FuncExpr))
1037         {
1038                 FuncExpr   *expr = (FuncExpr *) node;
1039                 List       *args;
1040                 Expr       *simple;
1041                 FuncExpr   *newexpr;
1042
1043                 /*
1044                  * Reduce constants in the FuncExpr's arguments.  We know args is
1045                  * either NIL or a List node, so we can call
1046                  * expression_tree_mutator directly rather than recursing to self.
1047                  */
1048                 args = (List *) expression_tree_mutator((Node *) expr->args,
1049                                                                                   eval_const_expressions_mutator,
1050                                                                                                 (void *) active_fns);
1051
1052                 /*
1053                  * Code for op/func reduction is pretty bulky, so split it out as
1054                  * a separate function.
1055                  */
1056                 simple = simplify_function(expr->funcid, expr->funcresulttype, args,
1057                                                                    true, active_fns);
1058                 if (simple)                             /* successfully simplified it */
1059                         return (Node *) simple;
1060
1061                 /*
1062                  * The expression cannot be simplified any further, so build and
1063                  * return a replacement FuncExpr node using the
1064                  * possibly-simplified arguments.
1065                  */
1066                 newexpr = makeNode(FuncExpr);
1067                 newexpr->funcid = expr->funcid;
1068                 newexpr->funcresulttype = expr->funcresulttype;
1069                 newexpr->funcretset = expr->funcretset;
1070                 newexpr->funcformat = expr->funcformat;
1071                 newexpr->args = args;
1072                 return (Node *) newexpr;
1073         }
1074         if (IsA(node, OpExpr))
1075         {
1076                 OpExpr     *expr = (OpExpr *) node;
1077                 List       *args;
1078                 Expr       *simple;
1079                 OpExpr     *newexpr;
1080
1081                 /*
1082                  * Reduce constants in the OpExpr's arguments.  We know args is
1083                  * either NIL or a List node, so we can call
1084                  * expression_tree_mutator directly rather than recursing to self.
1085                  */
1086                 args = (List *) expression_tree_mutator((Node *) expr->args,
1087                                                                                   eval_const_expressions_mutator,
1088                                                                                                 (void *) active_fns);
1089
1090                 /*
1091                  * Need to get OID of underlying function.      Okay to scribble on
1092                  * input to this extent.
1093                  */
1094                 set_opfuncid(expr);
1095
1096                 /*
1097                  * Code for op/func reduction is pretty bulky, so split it out as
1098                  * a separate function.
1099                  */
1100                 simple = simplify_function(expr->opfuncid, expr->opresulttype, args,
1101                                                                    true, active_fns);
1102                 if (simple)                             /* successfully simplified it */
1103                         return (Node *) simple;
1104
1105                 /*
1106                  * The expression cannot be simplified any further, so build and
1107                  * return a replacement OpExpr node using the possibly-simplified
1108                  * arguments.
1109                  */
1110                 newexpr = makeNode(OpExpr);
1111                 newexpr->opno = expr->opno;
1112                 newexpr->opfuncid = expr->opfuncid;
1113                 newexpr->opresulttype = expr->opresulttype;
1114                 newexpr->opretset = expr->opretset;
1115                 newexpr->args = args;
1116                 return (Node *) newexpr;
1117         }
1118         if (IsA(node, DistinctExpr))
1119         {
1120                 DistinctExpr *expr = (DistinctExpr *) node;
1121                 List       *args;
1122                 List       *arg;
1123                 bool            has_null_input = false;
1124                 bool            all_null_input = true;
1125                 bool            has_nonconst_input = false;
1126                 Expr       *simple;
1127                 DistinctExpr *newexpr;
1128
1129                 /*
1130                  * Reduce constants in the DistinctExpr's arguments.  We know args
1131                  * is either NIL or a List node, so we can call
1132                  * expression_tree_mutator directly rather than recursing to self.
1133                  */
1134                 args = (List *) expression_tree_mutator((Node *) expr->args,
1135                                                                                   eval_const_expressions_mutator,
1136                                                                                                 (void *) active_fns);
1137
1138                 /*
1139                  * We must do our own check for NULLs because DistinctExpr has
1140                  * different results for NULL input than the underlying operator
1141                  * does.
1142                  */
1143                 foreach(arg, args)
1144                 {
1145                         if (IsA(lfirst(arg), Const))
1146                         {
1147                                 has_null_input |= ((Const *) lfirst(arg))->constisnull;
1148                                 all_null_input &= ((Const *) lfirst(arg))->constisnull;
1149                         }
1150                         else
1151                                 has_nonconst_input = true;
1152                 }
1153
1154                 /* all constants? then can optimize this out */
1155                 if (!has_nonconst_input)
1156                 {
1157                         /* all nulls? then not distinct */
1158                         if (all_null_input)
1159                                 return MAKEBOOLCONST(false, false);
1160
1161                         /* one null? then distinct */
1162                         if (has_null_input)
1163                                 return MAKEBOOLCONST(true, false);
1164
1165                         /* otherwise try to evaluate the '=' operator */
1166                         /* (NOT okay to try to inline it, though!) */
1167
1168                         /*
1169                          * Need to get OID of underlying function.      Okay to scribble
1170                          * on input to this extent.
1171                          */
1172                         set_opfuncid((OpExpr *) expr);          /* rely on struct
1173                                                                                                  * equivalence */
1174
1175                         /*
1176                          * Code for op/func reduction is pretty bulky, so split it out
1177                          * as a separate function.
1178                          */
1179                         simple = simplify_function(expr->opfuncid, expr->opresulttype,
1180                                                                            args, false, active_fns);
1181                         if (simple)                     /* successfully simplified it */
1182                         {
1183                                 /*
1184                                  * Since the underlying operator is "=", must negate its
1185                                  * result
1186                                  */
1187                                 Const      *csimple = (Const *) simple;
1188
1189                                 Assert(IsA(csimple, Const));
1190                                 csimple->constvalue =
1191                                         BoolGetDatum(!DatumGetBool(csimple->constvalue));
1192                                 return (Node *) csimple;
1193                         }
1194                 }
1195
1196                 /*
1197                  * The expression cannot be simplified any further, so build and
1198                  * return a replacement DistinctExpr node using the
1199                  * possibly-simplified arguments.
1200                  */
1201                 newexpr = makeNode(DistinctExpr);
1202                 newexpr->opno = expr->opno;
1203                 newexpr->opfuncid = expr->opfuncid;
1204                 newexpr->opresulttype = expr->opresulttype;
1205                 newexpr->opretset = expr->opretset;
1206                 newexpr->args = args;
1207                 return (Node *) newexpr;
1208         }
1209         if (IsA(node, BoolExpr))
1210         {
1211                 BoolExpr   *expr = (BoolExpr *) node;
1212                 List       *args;
1213                 Const      *const_input;
1214
1215                 /*
1216                  * Reduce constants in the BoolExpr's arguments.  We know args is
1217                  * either NIL or a List node, so we can call
1218                  * expression_tree_mutator directly rather than recursing to self.
1219                  */
1220                 args = (List *) expression_tree_mutator((Node *) expr->args,
1221                                                                                   eval_const_expressions_mutator,
1222                                                                                                 (void *) active_fns);
1223
1224                 switch (expr->boolop)
1225                 {
1226                         case OR_EXPR:
1227                                 {
1228                                         /*----------
1229                                          * OR arguments are handled as follows:
1230                                          *      non constant: keep
1231                                          *      FALSE: drop (does not affect result)
1232                                          *      TRUE: force result to TRUE
1233                                          *      NULL: keep only one
1234                                          * We keep one NULL input because ExecEvalOr returns NULL
1235                                          * when no input is TRUE and at least one is NULL.
1236                                          *----------
1237                                          */
1238                                         FastList        newargs;
1239                                         List       *arg;
1240                                         bool            haveNull = false;
1241                                         bool            forceTrue = false;
1242
1243                                         FastListInit(&newargs);
1244                                         foreach(arg, args)
1245                                         {
1246                                                 if (!IsA(lfirst(arg), Const))
1247                                                 {
1248                                                         FastAppend(&newargs, lfirst(arg));
1249                                                         continue;
1250                                                 }
1251                                                 const_input = (Const *) lfirst(arg);
1252                                                 if (const_input->constisnull)
1253                                                         haveNull = true;
1254                                                 else if (DatumGetBool(const_input->constvalue))
1255                                                         forceTrue = true;
1256                                                 /* otherwise, we can drop the constant-false input */
1257                                         }
1258
1259                                         /*
1260                                          * We could return TRUE before falling out of the
1261                                          * loop, but this coding method will be easier to
1262                                          * adapt if we ever add a notion of non-removable
1263                                          * functions. We'd need to check all the inputs for
1264                                          * non-removability.
1265                                          */
1266                                         if (forceTrue)
1267                                                 return MAKEBOOLCONST(true, false);
1268                                         if (haveNull)
1269                                                 FastAppend(&newargs, MAKEBOOLCONST(false, true));
1270                                         /* If all the inputs are FALSE, result is FALSE */
1271                                         if (FastListValue(&newargs) == NIL)
1272                                                 return MAKEBOOLCONST(false, false);
1273                                         /* If only one nonconst-or-NULL input, it's the result */
1274                                         if (lnext(FastListValue(&newargs)) == NIL)
1275                                                 return (Node *) lfirst(FastListValue(&newargs));
1276                                         /* Else we still need an OR node */
1277                                         return (Node *) make_orclause(FastListValue(&newargs));
1278                                 }
1279                         case AND_EXPR:
1280                                 {
1281                                         /*----------
1282                                          * AND arguments are handled as follows:
1283                                          *      non constant: keep
1284                                          *      TRUE: drop (does not affect result)
1285                                          *      FALSE: force result to FALSE
1286                                          *      NULL: keep only one
1287                                          * We keep one NULL input because ExecEvalAnd returns NULL
1288                                          * when no input is FALSE and at least one is NULL.
1289                                          *----------
1290                                          */
1291                                         FastList        newargs;
1292                                         List       *arg;
1293                                         bool            haveNull = false;
1294                                         bool            forceFalse = false;
1295
1296                                         FastListInit(&newargs);
1297                                         foreach(arg, args)
1298                                         {
1299                                                 if (!IsA(lfirst(arg), Const))
1300                                                 {
1301                                                         FastAppend(&newargs, lfirst(arg));
1302                                                         continue;
1303                                                 }
1304                                                 const_input = (Const *) lfirst(arg);
1305                                                 if (const_input->constisnull)
1306                                                         haveNull = true;
1307                                                 else if (!DatumGetBool(const_input->constvalue))
1308                                                         forceFalse = true;
1309                                                 /* otherwise, we can drop the constant-true input */
1310                                         }
1311
1312                                         /*
1313                                          * We could return FALSE before falling out of the
1314                                          * loop, but this coding method will be easier to
1315                                          * adapt if we ever add a notion of non-removable
1316                                          * functions. We'd need to check all the inputs for
1317                                          * non-removability.
1318                                          */
1319                                         if (forceFalse)
1320                                                 return MAKEBOOLCONST(false, false);
1321                                         if (haveNull)
1322                                                 FastAppend(&newargs, MAKEBOOLCONST(false, true));
1323                                         /* If all the inputs are TRUE, result is TRUE */
1324                                         if (FastListValue(&newargs) == NIL)
1325                                                 return MAKEBOOLCONST(true, false);
1326                                         /* If only one nonconst-or-NULL input, it's the result */
1327                                         if (lnext(FastListValue(&newargs)) == NIL)
1328                                                 return (Node *) lfirst(FastListValue(&newargs));
1329                                         /* Else we still need an AND node */
1330                                         return (Node *) make_andclause(FastListValue(&newargs));
1331                                 }
1332                         case NOT_EXPR:
1333                                 Assert(length(args) == 1);
1334                                 if (IsA(lfirst(args), Const))
1335                                 {
1336                                         const_input = (Const *) lfirst(args);
1337                                         /* NOT NULL => NULL */
1338                                         if (const_input->constisnull)
1339                                                 return MAKEBOOLCONST(false, true);
1340                                         /* otherwise pretty easy */
1341                                         return MAKEBOOLCONST(!DatumGetBool(const_input->constvalue),
1342                                                                                  false);
1343                                 }
1344                                 /* Else we still need a NOT node */
1345                                 return (Node *) make_notclause(lfirst(args));
1346                         default:
1347                                 elog(ERROR, "unrecognized boolop: %d",
1348                                          (int) expr->boolop);
1349                                 break;
1350                 }
1351         }
1352         if (IsA(node, SubPlan))
1353         {
1354                 /*
1355                  * Return a SubPlan unchanged --- too late to do anything with it.
1356                  *
1357                  * XXX should we ereport() here instead?  Probably this routine
1358                  * should never be invoked after SubPlan creation.
1359                  */
1360                 return node;
1361         }
1362         if (IsA(node, RelabelType))
1363         {
1364                 /*
1365                  * If we can simplify the input to a constant, then we don't need
1366                  * the RelabelType node anymore: just change the type field of the
1367                  * Const node.  Otherwise, must copy the RelabelType node.
1368                  */
1369                 RelabelType *relabel = (RelabelType *) node;
1370                 Node       *arg;
1371
1372                 arg = eval_const_expressions_mutator((Node *) relabel->arg,
1373                                                                                          active_fns);
1374
1375                 /*
1376                  * If we find stacked RelabelTypes (eg, from foo :: int :: oid) we
1377                  * can discard all but the top one.
1378                  */
1379                 while (arg && IsA(arg, RelabelType))
1380                         arg = (Node *) ((RelabelType *) arg)->arg;
1381
1382                 if (arg && IsA(arg, Const))
1383                 {
1384                         Const      *con = (Const *) arg;
1385
1386                         con->consttype = relabel->resulttype;
1387
1388                         /*
1389                          * relabel's resulttypmod is discarded, which is OK for now;
1390                          * if the type actually needs a runtime length coercion then
1391                          * there should be a function call to do it just above this
1392                          * node.
1393                          */
1394                         return (Node *) con;
1395                 }
1396                 else
1397                 {
1398                         RelabelType *newrelabel = makeNode(RelabelType);
1399
1400                         newrelabel->arg = (Expr *) arg;
1401                         newrelabel->resulttype = relabel->resulttype;
1402                         newrelabel->resulttypmod = relabel->resulttypmod;
1403                         return (Node *) newrelabel;
1404                 }
1405         }
1406         if (IsA(node, CaseExpr))
1407         {
1408
1409                 /*----------
1410                  * CASE expressions can be simplified if there are constant
1411                  * condition clauses:
1412                  *              FALSE (or NULL): drop the alternative
1413                  *              TRUE: drop all remaining alternatives
1414                  * If the first non-FALSE alternative is a constant TRUE, we can
1415                  * simplify the entire CASE to that alternative's expression.
1416                  * If there are no non-FALSE alternatives, we simplify the entire
1417                  * CASE to the default result (ELSE result).
1418                  *----------
1419                  */
1420                 CaseExpr   *caseexpr = (CaseExpr *) node;
1421                 CaseExpr   *newcase;
1422                 FastList        newargs;
1423                 Node       *defresult;
1424                 Const      *const_input;
1425                 List       *arg;
1426
1427                 FastListInit(&newargs);
1428                 foreach(arg, caseexpr->args)
1429                 {
1430                         /* Simplify this alternative's condition and result */
1431                         CaseWhen   *casewhen = (CaseWhen *)
1432                         expression_tree_mutator((Node *) lfirst(arg),
1433                                                                         eval_const_expressions_mutator,
1434                                                                         (void *) active_fns);
1435
1436                         Assert(IsA(casewhen, CaseWhen));
1437                         if (casewhen->expr == NULL ||
1438                                 !IsA(casewhen->expr, Const))
1439                         {
1440                                 FastAppend(&newargs, casewhen);
1441                                 continue;
1442                         }
1443                         const_input = (Const *) casewhen->expr;
1444                         if (const_input->constisnull ||
1445                                 !DatumGetBool(const_input->constvalue))
1446                                 continue;               /* drop alternative with FALSE condition */
1447
1448                         /*
1449                          * Found a TRUE condition.      If it's the first (un-dropped)
1450                          * alternative, the CASE reduces to just this alternative.
1451                          */
1452                         if (FastListValue(&newargs) == NIL)
1453                                 return (Node *) casewhen->result;
1454
1455                         /*
1456                          * Otherwise, add it to the list, and drop all the rest.
1457                          */
1458                         FastAppend(&newargs, casewhen);
1459                         break;
1460                 }
1461
1462                 /* Simplify the default result */
1463                 defresult = eval_const_expressions_mutator((Node *) caseexpr->defresult,
1464                                                                                                    active_fns);
1465
1466                 /*
1467                  * If no non-FALSE alternatives, CASE reduces to the default
1468                  * result
1469                  */
1470                 if (FastListValue(&newargs) == NIL)
1471                         return defresult;
1472                 /* Otherwise we need a new CASE node */
1473                 newcase = makeNode(CaseExpr);
1474                 newcase->casetype = caseexpr->casetype;
1475                 newcase->arg = NULL;
1476                 newcase->args = FastListValue(&newargs);
1477                 newcase->defresult = (Expr *) defresult;
1478                 return (Node *) newcase;
1479         }
1480         if (IsA(node, ArrayExpr))
1481         {
1482                 ArrayExpr  *arrayexpr = (ArrayExpr *) node;
1483                 ArrayExpr  *newarray;
1484                 bool            all_const = true;
1485                 FastList        newelems;
1486                 List       *element;
1487
1488                 FastListInit(&newelems);
1489                 foreach(element, arrayexpr->elements)
1490                 {
1491                         Node       *e;
1492
1493                         e = eval_const_expressions_mutator((Node *) lfirst(element),
1494                                                                                            active_fns);
1495                         if (!IsA(e, Const))
1496                                 all_const = false;
1497                         FastAppend(&newelems, e);
1498                 }
1499
1500                 newarray = makeNode(ArrayExpr);
1501                 newarray->array_typeid = arrayexpr->array_typeid;
1502                 newarray->element_typeid = arrayexpr->element_typeid;
1503                 newarray->elements = FastListValue(&newelems);
1504                 newarray->multidims = arrayexpr->multidims;
1505
1506                 if (all_const)
1507                         return (Node *) evaluate_expr((Expr *) newarray,
1508                                                                                   newarray->array_typeid);
1509
1510                 return (Node *) newarray;
1511         }
1512         if (IsA(node, CoalesceExpr))
1513         {
1514                 CoalesceExpr *coalesceexpr = (CoalesceExpr *) node;
1515                 CoalesceExpr *newcoalesce;
1516                 FastList        newargs;
1517                 List       *arg;
1518
1519                 FastListInit(&newargs);
1520                 foreach(arg, coalesceexpr->args)
1521                 {
1522                         Node       *e;
1523
1524                         e = eval_const_expressions_mutator((Node *) lfirst(arg),
1525                                                                                            active_fns);
1526
1527                         /*
1528                          * We can remove null constants from the list. For a non-null
1529                          * constant, if it has not been preceded by any other
1530                          * non-null-constant expressions then that is the result.
1531                          */
1532                         if (IsA(e, Const))
1533                         {
1534                                 if (((Const *) e)->constisnull)
1535                                         continue;       /* drop null constant */
1536                                 if (FastListValue(&newargs) == NIL)
1537                                         return e;       /* first expr */
1538                         }
1539                         FastAppend(&newargs, e);
1540                 }
1541
1542                 newcoalesce = makeNode(CoalesceExpr);
1543                 newcoalesce->coalescetype = coalesceexpr->coalescetype;
1544                 newcoalesce->args = FastListValue(&newargs);
1545                 return (Node *) newcoalesce;
1546         }
1547         if (IsA(node, FieldSelect))
1548         {
1549                 /*
1550                  * We can optimize field selection from a whole-row Var into a
1551                  * simple Var.  (This case won't be generated directly by the
1552                  * parser, because ParseComplexProjection short-circuits it. But
1553                  * it can arise while simplifying functions.)  If the argument
1554                  * isn't a whole-row Var, just fall through to do generic
1555                  * processing.
1556                  */
1557                 FieldSelect *fselect = (FieldSelect *) node;
1558                 Var                *argvar = (Var *) fselect->arg;
1559
1560                 if (argvar && IsA(argvar, Var) &&
1561                         argvar->varattno == InvalidAttrNumber)
1562                 {
1563                         return (Node *) makeVar(argvar->varno,
1564                                                                         fselect->fieldnum,
1565                                                                         fselect->resulttype,
1566                                                                         fselect->resulttypmod,
1567                                                                         argvar->varlevelsup);
1568                 }
1569         }
1570
1571         /*
1572          * For any node type not handled above, we recurse using
1573          * expression_tree_mutator, which will copy the node unchanged but try
1574          * to simplify its arguments (if any) using this routine. For example:
1575          * we cannot eliminate an ArrayRef node, but we might be able to
1576          * simplify constant expressions in its subscripts.
1577          */
1578         return expression_tree_mutator(node, eval_const_expressions_mutator,
1579                                                                    (void *) active_fns);
1580 }
1581
1582 /*
1583  * Subroutine for eval_const_expressions: try to simplify a function call
1584  * (which might originally have been an operator; we don't care)
1585  *
1586  * Inputs are the function OID, actual result type OID (which is needed for
1587  * polymorphic functions), and the pre-simplified argument list;
1588  * also a list of already-active inline function expansions.
1589  *
1590  * Returns a simplified expression if successful, or NULL if cannot
1591  * simplify the function call.
1592  */
1593 static Expr *
1594 simplify_function(Oid funcid, Oid result_type, List *args,
1595                                   bool allow_inline, List *active_fns)
1596 {
1597         HeapTuple       func_tuple;
1598         Expr       *newexpr;
1599
1600         /*
1601          * We have two strategies for simplification: either execute the
1602          * function to deliver a constant result, or expand in-line the body
1603          * of the function definition (which only works for simple
1604          * SQL-language functions, but that is a common case).  In either case
1605          * we need access to the function's pg_proc tuple, so fetch it just
1606          * once to use in both attempts.
1607          */
1608         func_tuple = SearchSysCache(PROCOID,
1609                                                                 ObjectIdGetDatum(funcid),
1610                                                                 0, 0, 0);
1611         if (!HeapTupleIsValid(func_tuple))
1612                 elog(ERROR, "cache lookup failed for function %u", funcid);
1613
1614         newexpr = evaluate_function(funcid, result_type, args, func_tuple);
1615
1616         if (!newexpr && allow_inline)
1617                 newexpr = inline_function(funcid, result_type, args,
1618                                                                   func_tuple, active_fns);
1619
1620         ReleaseSysCache(func_tuple);
1621
1622         return newexpr;
1623 }
1624
1625 /*
1626  * evaluate_function: try to pre-evaluate a function call
1627  *
1628  * We can do this if the function is strict and has any constant-null inputs
1629  * (just return a null constant), or if the function is immutable and has all
1630  * constant inputs (call it and return the result as a Const node).
1631  *
1632  * Returns a simplified expression if successful, or NULL if cannot
1633  * simplify the function.
1634  */
1635 static Expr *
1636 evaluate_function(Oid funcid, Oid result_type, List *args,
1637                                   HeapTuple func_tuple)
1638 {
1639         Form_pg_proc funcform = (Form_pg_proc) GETSTRUCT(func_tuple);
1640         bool            has_nonconst_input = false;
1641         bool            has_null_input = false;
1642         List       *arg;
1643         FuncExpr   *newexpr;
1644
1645         /*
1646          * Can't simplify if it returns a set.
1647          */
1648         if (funcform->proretset)
1649                 return NULL;
1650
1651         /*
1652          * Check for constant inputs and especially constant-NULL inputs.
1653          */
1654         foreach(arg, args)
1655         {
1656                 if (IsA(lfirst(arg), Const))
1657                         has_null_input |= ((Const *) lfirst(arg))->constisnull;
1658                 else
1659                         has_nonconst_input = true;
1660         }
1661
1662         /*
1663          * If the function is strict and has a constant-NULL input, it will
1664          * never be called at all, so we can replace the call by a NULL
1665          * constant, even if there are other inputs that aren't constant, and
1666          * even if the function is not otherwise immutable.
1667          */
1668         if (funcform->proisstrict && has_null_input)
1669                 return (Expr *) makeNullConst(result_type);
1670
1671         /*
1672          * Otherwise, can simplify only if the function is immutable and all
1673          * inputs are constants. (For a non-strict function, constant NULL
1674          * inputs are treated the same as constant non-NULL inputs.)
1675          */
1676         if (funcform->provolatile != PROVOLATILE_IMMUTABLE ||
1677                 has_nonconst_input)
1678                 return NULL;
1679
1680         /*
1681          * OK, looks like we can simplify this operator/function.
1682          *
1683          * Build a new FuncExpr node containing the already-simplified arguments.
1684          */
1685         newexpr = makeNode(FuncExpr);
1686         newexpr->funcid = funcid;
1687         newexpr->funcresulttype = result_type;
1688         newexpr->funcretset = false;
1689         newexpr->funcformat = COERCE_EXPLICIT_CALL; /* doesn't matter */
1690         newexpr->args = args;
1691
1692         return evaluate_expr((Expr *) newexpr, result_type);
1693 }
1694
1695 /*
1696  * inline_function: try to expand a function call inline
1697  *
1698  * If the function is a sufficiently simple SQL-language function
1699  * (just "SELECT expression"), then we can inline it and avoid the rather
1700  * high per-call overhead of SQL functions.  Furthermore, this can expose
1701  * opportunities for constant-folding within the function expression.
1702  *
1703  * We have to beware of some special cases however.  A directly or
1704  * indirectly recursive function would cause us to recurse forever,
1705  * so we keep track of which functions we are already expanding and
1706  * do not re-expand them.  Also, if a parameter is used more than once
1707  * in the SQL-function body, we require it not to contain any volatile
1708  * functions (volatiles might deliver inconsistent answers) nor to be
1709  * unreasonably expensive to evaluate.  The expensiveness check not only
1710  * prevents us from doing multiple evaluations of an expensive parameter
1711  * at runtime, but is a safety value to limit growth of an expression due
1712  * to repeated inlining.
1713  *
1714  * We must also beware of changing the volatility or strictness status of
1715  * functions by inlining them.
1716  *
1717  * Returns a simplified expression if successful, or NULL if cannot
1718  * simplify the function.
1719  */
1720 static Expr *
1721 inline_function(Oid funcid, Oid result_type, List *args,
1722                                 HeapTuple func_tuple, List *active_fns)
1723 {
1724         Form_pg_proc funcform = (Form_pg_proc) GETSTRUCT(func_tuple);
1725         char            result_typtype;
1726         bool            polymorphic = false;
1727         Oid                     argtypes[FUNC_MAX_ARGS];
1728         char       *src;
1729         Datum           tmp;
1730         bool            isNull;
1731         MemoryContext oldcxt;
1732         MemoryContext mycxt;
1733         ErrorContextCallback sqlerrcontext;
1734         List       *raw_parsetree_list;
1735         List       *querytree_list;
1736         Query      *querytree;
1737         Node       *newexpr;
1738         int                *usecounts;
1739         List       *arg;
1740         int                     i;
1741
1742         /*
1743          * Forget it if the function is not SQL-language or has other
1744          * showstopper properties.      (The nargs check is just paranoia.)
1745          */
1746         if (funcform->prolang != SQLlanguageId ||
1747                 funcform->prosecdef ||
1748                 funcform->proretset ||
1749                 funcform->pronargs != length(args))
1750                 return NULL;
1751
1752         /*
1753          * Forget it if declared return type is not base, domain, or
1754          * polymorphic
1755          */
1756         result_typtype = get_typtype(funcform->prorettype);
1757         if (result_typtype != 'b' &&
1758                 result_typtype != 'd')
1759         {
1760                 if (funcform->prorettype == ANYARRAYOID ||
1761                         funcform->prorettype == ANYELEMENTOID)
1762                         polymorphic = true;
1763                 else
1764                         return NULL;
1765         }
1766
1767         /* Check for recursive function, and give up trying to expand if so */
1768         if (oidMember(funcid, active_fns))
1769                 return NULL;
1770
1771         /* Check permission to call function (fail later, if not) */
1772         if (pg_proc_aclcheck(funcid, GetUserId(), ACL_EXECUTE) != ACLCHECK_OK)
1773                 return NULL;
1774
1775         /* Check for polymorphic arguments, and substitute actual arg types */
1776         memcpy(argtypes, funcform->proargtypes, FUNC_MAX_ARGS * sizeof(Oid));
1777         for (i = 0; i < funcform->pronargs; i++)
1778         {
1779                 if (argtypes[i] == ANYARRAYOID ||
1780                         argtypes[i] == ANYELEMENTOID)
1781                 {
1782                         polymorphic = true;
1783                         argtypes[i] = exprType((Node *) nth(i, args));
1784                 }
1785         }
1786
1787         /*
1788          * Setup error traceback support for ereport().  This is so that we
1789          * can finger the function that bad information came from.
1790          */
1791         sqlerrcontext.callback = sql_inline_error_callback;
1792         sqlerrcontext.arg = funcform;
1793         sqlerrcontext.previous = error_context_stack;
1794         error_context_stack = &sqlerrcontext;
1795
1796         /*
1797          * Make a temporary memory context, so that we don't leak all the
1798          * stuff that parsing might create.
1799          */
1800         mycxt = AllocSetContextCreate(CurrentMemoryContext,
1801                                                                   "inline_function",
1802                                                                   ALLOCSET_DEFAULT_MINSIZE,
1803                                                                   ALLOCSET_DEFAULT_INITSIZE,
1804                                                                   ALLOCSET_DEFAULT_MAXSIZE);
1805         oldcxt = MemoryContextSwitchTo(mycxt);
1806
1807         /* Fetch and parse the function body */
1808         tmp = SysCacheGetAttr(PROCOID,
1809                                                   func_tuple,
1810                                                   Anum_pg_proc_prosrc,
1811                                                   &isNull);
1812         if (isNull)
1813                 elog(ERROR, "null prosrc for function %u", funcid);
1814         src = DatumGetCString(DirectFunctionCall1(textout, tmp));
1815
1816         /*
1817          * We just do parsing and parse analysis, not rewriting, because
1818          * rewriting will not affect table-free-SELECT-only queries, which is
1819          * all that we care about.      Also, we can punt as soon as we detect
1820          * more than one command in the function body.
1821          */
1822         raw_parsetree_list = pg_parse_query(src);
1823         if (length(raw_parsetree_list) != 1)
1824                 goto fail;
1825
1826         querytree_list = parse_analyze(lfirst(raw_parsetree_list),
1827                                                                    argtypes, funcform->pronargs);
1828
1829         if (length(querytree_list) != 1)
1830                 goto fail;
1831
1832         querytree = (Query *) lfirst(querytree_list);
1833
1834         /*
1835          * The single command must be a simple "SELECT expression".
1836          */
1837         if (!IsA(querytree, Query) ||
1838                 querytree->commandType != CMD_SELECT ||
1839                 querytree->resultRelation != 0 ||
1840                 querytree->into ||
1841                 querytree->hasAggs ||
1842                 querytree->hasSubLinks ||
1843                 querytree->rtable ||
1844                 querytree->jointree->fromlist ||
1845                 querytree->jointree->quals ||
1846                 querytree->groupClause ||
1847                 querytree->havingQual ||
1848                 querytree->distinctClause ||
1849                 querytree->sortClause ||
1850                 querytree->limitOffset ||
1851                 querytree->limitCount ||
1852                 querytree->setOperations ||
1853                 length(querytree->targetList) != 1)
1854                 goto fail;
1855
1856         newexpr = (Node *) ((TargetEntry *) lfirst(querytree->targetList))->expr;
1857
1858         /*
1859          * If the function has any arguments declared as polymorphic types,
1860          * then it wasn't type-checked at definition time; must do so now.
1861          * (This will raise an error if wrong, but that's okay since the
1862          * function would fail at runtime anyway.  Note we do not try this
1863          * until we have verified that no rewriting was needed; that's
1864          * probably not important, but let's be careful.)
1865          */
1866         if (polymorphic)
1867                 check_sql_fn_retval(result_type, get_typtype(result_type),
1868                                                         querytree_list);
1869
1870         /*
1871          * Additional validity checks on the expression.  It mustn't return a
1872          * set, and it mustn't be more volatile than the surrounding function
1873          * (this is to avoid breaking hacks that involve pretending a function
1874          * is immutable when it really ain't).  If the surrounding function is
1875          * declared strict, then the expression must contain only strict
1876          * constructs and must use all of the function parameters (this is
1877          * overkill, but an exact analysis is hard).
1878          */
1879         if (expression_returns_set(newexpr))
1880                 goto fail;
1881
1882         if (funcform->provolatile == PROVOLATILE_IMMUTABLE &&
1883                 contain_mutable_functions(newexpr))
1884                 goto fail;
1885         else if (funcform->provolatile == PROVOLATILE_STABLE &&
1886                          contain_volatile_functions(newexpr))
1887                 goto fail;
1888
1889         if (funcform->proisstrict &&
1890                 contain_nonstrict_functions(newexpr))
1891                 goto fail;
1892
1893         /*
1894          * We may be able to do it; there are still checks on parameter usage
1895          * to make, but those are most easily done in combination with the
1896          * actual substitution of the inputs.  So start building expression
1897          * with inputs substituted.
1898          */
1899         usecounts = (int *) palloc0((funcform->pronargs + 1) * sizeof(int));
1900         newexpr = substitute_actual_parameters(newexpr, funcform->pronargs,
1901                                                                                    args, usecounts);
1902
1903         /* Now check for parameter usage */
1904         i = 0;
1905         foreach(arg, args)
1906         {
1907                 Node       *param = lfirst(arg);
1908
1909                 if (usecounts[i] == 0)
1910                 {
1911                         /* Param not used at all: uncool if func is strict */
1912                         if (funcform->proisstrict)
1913                                 goto fail;
1914                 }
1915                 else if (usecounts[i] != 1)
1916                 {
1917                         /* Param used multiple times: uncool if expensive or volatile */
1918                         QualCost        eval_cost;
1919
1920                         /*
1921                          * We define "expensive" as "contains any subplan or more than
1922                          * 10 operators".  Note that the subplan search has to be done
1923                          * explicitly, since cost_qual_eval() will barf on unplanned
1924                          * subselects.
1925                          */
1926                         if (contain_subplans(param))
1927                                 goto fail;
1928                         cost_qual_eval(&eval_cost, makeList1(param));
1929                         if (eval_cost.startup + eval_cost.per_tuple >
1930                                 10 * cpu_operator_cost)
1931                                 goto fail;
1932
1933                         /*
1934                          * Check volatility last since this is more expensive than the
1935                          * above tests
1936                          */
1937                         if (contain_volatile_functions(param))
1938                                 goto fail;
1939                 }
1940                 i++;
1941         }
1942
1943         /*
1944          * Whew --- we can make the substitution.  Copy the modified
1945          * expression out of the temporary memory context, and clean up.
1946          */
1947         MemoryContextSwitchTo(oldcxt);
1948
1949         newexpr = copyObject(newexpr);
1950
1951         MemoryContextDelete(mycxt);
1952
1953         /*
1954          * Recursively try to simplify the modified expression.  Here we must
1955          * add the current function to the context list of active functions.
1956          */
1957         newexpr = eval_const_expressions_mutator(newexpr,
1958                                                                                          lconso(funcid, active_fns));
1959
1960         error_context_stack = sqlerrcontext.previous;
1961
1962         return (Expr *) newexpr;
1963
1964         /* Here if func is not inlinable: release temp memory and return NULL */
1965 fail:
1966         MemoryContextSwitchTo(oldcxt);
1967         MemoryContextDelete(mycxt);
1968         error_context_stack = sqlerrcontext.previous;
1969
1970         return NULL;
1971 }
1972
1973 /*
1974  * Replace Param nodes by appropriate actual parameters
1975  */
1976 static Node *
1977 substitute_actual_parameters(Node *expr, int nargs, List *args,
1978                                                          int *usecounts)
1979 {
1980         substitute_actual_parameters_context context;
1981
1982         context.nargs = nargs;
1983         context.args = args;
1984         context.usecounts = usecounts;
1985
1986         return substitute_actual_parameters_mutator(expr, &context);
1987 }
1988
1989 static Node *
1990 substitute_actual_parameters_mutator(Node *node,
1991                                                    substitute_actual_parameters_context *context)
1992 {
1993         if (node == NULL)
1994                 return NULL;
1995         if (IsA(node, Param))
1996         {
1997                 Param      *param = (Param *) node;
1998
1999                 if (param->paramkind != PARAM_NUM)
2000                         elog(ERROR, "unexpected paramkind: %d", param->paramkind);
2001                 if (param->paramid <= 0 || param->paramid > context->nargs)
2002                         elog(ERROR, "invalid paramid: %d", param->paramid);
2003
2004                 /* Count usage of parameter */
2005                 context->usecounts[param->paramid - 1]++;
2006
2007                 /* Select the appropriate actual arg and replace the Param with it */
2008                 /* We don't need to copy at this time (it'll get done later) */
2009                 return nth(param->paramid - 1, context->args);
2010         }
2011         return expression_tree_mutator(node, substitute_actual_parameters_mutator,
2012                                                                    (void *) context);
2013 }
2014
2015 /*
2016  * error context callback to let us supply a call-stack traceback
2017  */
2018 static void
2019 sql_inline_error_callback(void *arg)
2020 {
2021         Form_pg_proc funcform = (Form_pg_proc) arg;
2022
2023         errcontext("SQL function \"%s\" during inlining",
2024                            NameStr(funcform->proname));
2025 }
2026
2027 /*
2028  * evaluate_expr: pre-evaluate a constant expression
2029  *
2030  * We use the executor's routine ExecEvalExpr() to avoid duplication of
2031  * code and ensure we get the same result as the executor would get.
2032  */
2033 static Expr *
2034 evaluate_expr(Expr *expr, Oid result_type)
2035 {
2036         EState     *estate;
2037         ExprState  *exprstate;
2038         MemoryContext oldcontext;
2039         Datum           const_val;
2040         bool            const_is_null;
2041         int16           resultTypLen;
2042         bool            resultTypByVal;
2043
2044         /*
2045          * To use the executor, we need an EState.
2046          */
2047         estate = CreateExecutorState();
2048
2049         /* We can use the estate's working context to avoid memory leaks. */
2050         oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);
2051
2052         /*
2053          * Prepare expr for execution.
2054          */
2055         exprstate = ExecPrepareExpr(expr, estate);
2056
2057         /*
2058          * And evaluate it.
2059          *
2060          * It is OK to use a default econtext because none of the ExecEvalExpr()
2061          * code used in this situation will use econtext.  That might seem
2062          * fortuitous, but it's not so unreasonable --- a constant expression
2063          * does not depend on context, by definition, n'est ce pas?
2064          */
2065         const_val = ExecEvalExprSwitchContext(exprstate,
2066                                                                                   GetPerTupleExprContext(estate),
2067                                                                                   &const_is_null, NULL);
2068
2069         /* Get info needed about result datatype */
2070         get_typlenbyval(result_type, &resultTypLen, &resultTypByVal);
2071
2072         /* Get back to outer memory context */
2073         MemoryContextSwitchTo(oldcontext);
2074
2075         /* Must copy result out of sub-context used by expression eval */
2076         if (!const_is_null)
2077                 const_val = datumCopy(const_val, resultTypByVal, resultTypLen);
2078
2079         /* Release all the junk we just created */
2080         FreeExecutorState(estate);
2081
2082         /*
2083          * Make the constant result node.
2084          */
2085         return (Expr *) makeConst(result_type, resultTypLen,
2086                                                           const_val, const_is_null,
2087                                                           resultTypByVal);
2088 }
2089
2090
2091 /*
2092  * Standard expression-tree walking support
2093  *
2094  * We used to have near-duplicate code in many different routines that
2095  * understood how to recurse through an expression node tree.  That was
2096  * a pain to maintain, and we frequently had bugs due to some particular
2097  * routine neglecting to support a particular node type.  In most cases,
2098  * these routines only actually care about certain node types, and don't
2099  * care about other types except insofar as they have to recurse through
2100  * non-primitive node types.  Therefore, we now provide generic tree-walking
2101  * logic to consolidate the redundant "boilerplate" code.  There are
2102  * two versions: expression_tree_walker() and expression_tree_mutator().
2103  */
2104
2105 /*--------------------
2106  * expression_tree_walker() is designed to support routines that traverse
2107  * a tree in a read-only fashion (although it will also work for routines
2108  * that modify nodes in-place but never add/delete/replace nodes).
2109  * A walker routine should look like this:
2110  *
2111  * bool my_walker (Node *node, my_struct *context)
2112  * {
2113  *              if (node == NULL)
2114  *                      return false;
2115  *              // check for nodes that special work is required for, eg:
2116  *              if (IsA(node, Var))
2117  *              {
2118  *                      ... do special actions for Var nodes
2119  *              }
2120  *              else if (IsA(node, ...))
2121  *              {
2122  *                      ... do special actions for other node types
2123  *              }
2124  *              // for any node type not specially processed, do:
2125  *              return expression_tree_walker(node, my_walker, (void *) context);
2126  * }
2127  *
2128  * The "context" argument points to a struct that holds whatever context
2129  * information the walker routine needs --- it can be used to return data
2130  * gathered by the walker, too.  This argument is not touched by
2131  * expression_tree_walker, but it is passed down to recursive sub-invocations
2132  * of my_walker.  The tree walk is started from a setup routine that
2133  * fills in the appropriate context struct, calls my_walker with the top-level
2134  * node of the tree, and then examines the results.
2135  *
2136  * The walker routine should return "false" to continue the tree walk, or
2137  * "true" to abort the walk and immediately return "true" to the top-level
2138  * caller.      This can be used to short-circuit the traversal if the walker
2139  * has found what it came for.  "false" is returned to the top-level caller
2140  * iff no invocation of the walker returned "true".
2141  *
2142  * The node types handled by expression_tree_walker include all those
2143  * normally found in target lists and qualifier clauses during the planning
2144  * stage.  In particular, it handles List nodes since a cnf-ified qual clause
2145  * will have List structure at the top level, and it handles TargetEntry nodes
2146  * so that a scan of a target list can be handled without additional code.
2147  * (But only the "expr" part of a TargetEntry is examined, unless the walker
2148  * chooses to process TargetEntry nodes specially.)  Also, RangeTblRef,
2149  * FromExpr, JoinExpr, and SetOperationStmt nodes are handled, so that query
2150  * jointrees and setOperation trees can be processed without additional code.
2151  *
2152  * expression_tree_walker will handle SubLink nodes by recursing normally into
2153  * the "lefthand" arguments (which are expressions belonging to the outer
2154  * plan).  It will also call the walker on the sub-Query node; however, when
2155  * expression_tree_walker itself is called on a Query node, it does nothing
2156  * and returns "false".  The net effect is that unless the walker does
2157  * something special at a Query node, sub-selects will not be visited during
2158  * an expression tree walk. This is exactly the behavior wanted in many cases
2159  * --- and for those walkers that do want to recurse into sub-selects, special
2160  * behavior is typically needed anyway at the entry to a sub-select (such as
2161  * incrementing a depth counter). A walker that wants to examine sub-selects
2162  * should include code along the lines of:
2163  *
2164  *              if (IsA(node, Query))
2165  *              {
2166  *                      adjust context for subquery;
2167  *                      result = query_tree_walker((Query *) node, my_walker, context,
2168  *                                                                         0); // adjust flags as needed
2169  *                      restore context if needed;
2170  *                      return result;
2171  *              }
2172  *
2173  * query_tree_walker is a convenience routine (see below) that calls the
2174  * walker on all the expression subtrees of the given Query node.
2175  *
2176  * expression_tree_walker will handle SubPlan nodes by recursing normally
2177  * into the "exprs" and "args" lists (which are expressions belonging to
2178  * the outer plan).  It will not touch the completed subplan, however.  Since
2179  * there is no link to the original Query, it is not possible to recurse into
2180  * subselects of an already-planned expression tree.  This is OK for current
2181  * uses, but may need to be revisited in future.
2182  *--------------------
2183  */
2184
2185 bool
2186 expression_tree_walker(Node *node,
2187                                            bool (*walker) (),
2188                                            void *context)
2189 {
2190         List       *temp;
2191
2192         /*
2193          * The walker has already visited the current node, and so we need
2194          * only recurse into any sub-nodes it has.
2195          *
2196          * We assume that the walker is not interested in List nodes per se, so
2197          * when we expect a List we just recurse directly to self without
2198          * bothering to call the walker.
2199          */
2200         if (node == NULL)
2201                 return false;
2202         switch (nodeTag(node))
2203         {
2204                 case T_Var:
2205                 case T_Const:
2206                 case T_Param:
2207                 case T_CoerceToDomainValue:
2208                 case T_SetToDefault:
2209                 case T_RangeTblRef:
2210                         /* primitive node types with no subnodes */
2211                         break;
2212                 case T_Aggref:
2213                         return walker(((Aggref *) node)->target, context);
2214                 case T_ArrayRef:
2215                         {
2216                                 ArrayRef   *aref = (ArrayRef *) node;
2217
2218                                 /* recurse directly for upper/lower array index lists */
2219                                 if (expression_tree_walker((Node *) aref->refupperindexpr,
2220                                                                                    walker, context))
2221                                         return true;
2222                                 if (expression_tree_walker((Node *) aref->reflowerindexpr,
2223                                                                                    walker, context))
2224                                         return true;
2225                                 /* walker must see the refexpr and refassgnexpr, however */
2226                                 if (walker(aref->refexpr, context))
2227                                         return true;
2228                                 if (walker(aref->refassgnexpr, context))
2229                                         return true;
2230                         }
2231                         break;
2232                 case T_FuncExpr:
2233                         {
2234                                 FuncExpr   *expr = (FuncExpr *) node;
2235
2236                                 if (expression_tree_walker((Node *) expr->args,
2237                                                                                    walker, context))
2238                                         return true;
2239                         }
2240                         break;
2241                 case T_OpExpr:
2242                         {
2243                                 OpExpr     *expr = (OpExpr *) node;
2244
2245                                 if (expression_tree_walker((Node *) expr->args,
2246                                                                                    walker, context))
2247                                         return true;
2248                         }
2249                         break;
2250                 case T_DistinctExpr:
2251                         {
2252                                 DistinctExpr *expr = (DistinctExpr *) node;
2253
2254                                 if (expression_tree_walker((Node *) expr->args,
2255                                                                                    walker, context))
2256                                         return true;
2257                         }
2258                         break;
2259                 case T_ScalarArrayOpExpr:
2260                         {
2261                                 ScalarArrayOpExpr *expr = (ScalarArrayOpExpr *) node;
2262
2263                                 if (expression_tree_walker((Node *) expr->args,
2264                                                                                    walker, context))
2265                                         return true;
2266                         }
2267                         break;
2268                 case T_BoolExpr:
2269                         {
2270                                 BoolExpr   *expr = (BoolExpr *) node;
2271
2272                                 if (expression_tree_walker((Node *) expr->args,
2273                                                                                    walker, context))
2274                                         return true;
2275                         }
2276                         break;
2277                 case T_SubLink:
2278                         {
2279                                 SubLink    *sublink = (SubLink *) node;
2280
2281                                 if (expression_tree_walker((Node *) sublink->lefthand,
2282                                                                                    walker, context))
2283                                         return true;
2284
2285                                 /*
2286                                  * Also invoke the walker on the sublink's Query node, so
2287                                  * it can recurse into the sub-query if it wants to.
2288                                  */
2289                                 return walker(sublink->subselect, context);
2290                         }
2291                         break;
2292                 case T_SubPlan:
2293                         {
2294                                 SubPlan    *subplan = (SubPlan *) node;
2295
2296                                 /* recurse into the exprs list, but not into the Plan */
2297                                 if (expression_tree_walker((Node *) subplan->exprs,
2298                                                                                    walker, context))
2299                                         return true;
2300                                 /* also examine args list */
2301                                 if (expression_tree_walker((Node *) subplan->args,
2302                                                                                    walker, context))
2303                                         return true;
2304                         }
2305                         break;
2306                 case T_FieldSelect:
2307                         return walker(((FieldSelect *) node)->arg, context);
2308                 case T_RelabelType:
2309                         return walker(((RelabelType *) node)->arg, context);
2310                 case T_CaseExpr:
2311                         {
2312                                 CaseExpr   *caseexpr = (CaseExpr *) node;
2313
2314                                 /* we assume walker doesn't care about CaseWhens, either */
2315                                 foreach(temp, caseexpr->args)
2316                                 {
2317                                         CaseWhen   *when = (CaseWhen *) lfirst(temp);
2318
2319                                         Assert(IsA(when, CaseWhen));
2320                                         if (walker(when->expr, context))
2321                                                 return true;
2322                                         if (walker(when->result, context))
2323                                                 return true;
2324                                 }
2325                                 /* caseexpr->arg should be null, but we'll check it anyway */
2326                                 if (walker(caseexpr->arg, context))
2327                                         return true;
2328                                 if (walker(caseexpr->defresult, context))
2329                                         return true;
2330                         }
2331                         break;
2332                 case T_ArrayExpr:
2333                         return walker(((ArrayExpr *) node)->elements, context);
2334                 case T_CoalesceExpr:
2335                         return walker(((CoalesceExpr *) node)->args, context);
2336                 case T_NullIfExpr:
2337                         return walker(((NullIfExpr *) node)->args, context);
2338                 case T_NullTest:
2339                         return walker(((NullTest *) node)->arg, context);
2340                 case T_BooleanTest:
2341                         return walker(((BooleanTest *) node)->arg, context);
2342                 case T_CoerceToDomain:
2343                         return walker(((CoerceToDomain *) node)->arg, context);
2344                 case T_TargetEntry:
2345                         return walker(((TargetEntry *) node)->expr, context);
2346                 case T_Query:
2347                         /* Do nothing with a sub-Query, per discussion above */
2348                         break;
2349                 case T_List:
2350                         foreach(temp, (List *) node)
2351                         {
2352                                 if (walker((Node *) lfirst(temp), context))
2353                                         return true;
2354                         }
2355                         break;
2356                 case T_FromExpr:
2357                         {
2358                                 FromExpr   *from = (FromExpr *) node;
2359
2360                                 if (walker(from->fromlist, context))
2361                                         return true;
2362                                 if (walker(from->quals, context))
2363                                         return true;
2364                         }
2365                         break;
2366                 case T_JoinExpr:
2367                         {
2368                                 JoinExpr   *join = (JoinExpr *) node;
2369
2370                                 if (walker(join->larg, context))
2371                                         return true;
2372                                 if (walker(join->rarg, context))
2373                                         return true;
2374                                 if (walker(join->quals, context))
2375                                         return true;
2376
2377                                 /*
2378                                  * alias clause, using list are deemed uninteresting.
2379                                  */
2380                         }
2381                         break;
2382                 case T_SetOperationStmt:
2383                         {
2384                                 SetOperationStmt *setop = (SetOperationStmt *) node;
2385
2386                                 if (walker(setop->larg, context))
2387                                         return true;
2388                                 if (walker(setop->rarg, context))
2389                                         return true;
2390                         }
2391                         break;
2392                 case T_InClauseInfo:
2393                         {
2394                                 InClauseInfo *ininfo = (InClauseInfo *) node;
2395
2396                                 if (expression_tree_walker((Node *) ininfo->sub_targetlist,
2397                                                                                    walker, context))
2398                                         return true;
2399                         }
2400                         break;
2401                 case T_RangeVar:
2402                         /*
2403                          * Give a useful complaint if someone uses a bare relation name
2404                          * in an expression (see comments in transformColumnRef()).
2405                          */
2406                         ereport(ERROR,
2407                                         (errcode(ERRCODE_SYNTAX_ERROR),
2408                                          errmsg("relation reference \"%s\" cannot be used in an expression",
2409                                                         ((RangeVar *) node)->relname)));
2410                         break;
2411                 default:
2412                         elog(ERROR, "unrecognized node type: %d",
2413                                  (int) nodeTag(node));
2414                         break;
2415         }
2416         return false;
2417 }
2418
2419 /*
2420  * query_tree_walker --- initiate a walk of a Query's expressions
2421  *
2422  * This routine exists just to reduce the number of places that need to know
2423  * where all the expression subtrees of a Query are.  Note it can be used
2424  * for starting a walk at top level of a Query regardless of whether the
2425  * walker intends to descend into subqueries.  It is also useful for
2426  * descending into subqueries within a walker.
2427  *
2428  * Some callers want to suppress visitation of certain items in the sub-Query,
2429  * typically because they need to process them specially, or don't actually
2430  * want to recurse into subqueries.  This is supported by the flags argument,
2431  * which is the bitwise OR of flag values to suppress visitation of
2432  * indicated items.  (More flag bits may be added as needed.)
2433  */
2434 bool
2435 query_tree_walker(Query *query,
2436                                   bool (*walker) (),
2437                                   void *context,
2438                                   int flags)
2439 {
2440         List       *rt;
2441
2442         Assert(query != NULL && IsA(query, Query));
2443
2444         if (walker((Node *) query->targetList, context))
2445                 return true;
2446         if (walker((Node *) query->jointree, context))
2447                 return true;
2448         if (walker(query->setOperations, context))
2449                 return true;
2450         if (walker(query->havingQual, context))
2451                 return true;
2452         if (walker(query->limitOffset, context))
2453                 return true;
2454         if (walker(query->limitCount, context))
2455                 return true;
2456         if (walker(query->in_info_list, context))
2457                 return true;
2458         foreach(rt, query->rtable)
2459         {
2460                 RangeTblEntry *rte = (RangeTblEntry *) lfirst(rt);
2461
2462                 switch (rte->rtekind)
2463                 {
2464                         case RTE_RELATION:
2465                         case RTE_SPECIAL:
2466                                 /* nothing to do */
2467                                 break;
2468                         case RTE_SUBQUERY:
2469                                 if (!(flags & QTW_IGNORE_RT_SUBQUERIES))
2470                                         if (walker(rte->subquery, context))
2471                                                 return true;
2472                                 break;
2473                         case RTE_JOIN:
2474                                 if (!(flags & QTW_IGNORE_JOINALIASES))
2475                                         if (walker(rte->joinaliasvars, context))
2476                                                 return true;
2477                                 break;
2478                         case RTE_FUNCTION:
2479                                 if (walker(rte->funcexpr, context))
2480                                         return true;
2481                                 break;
2482                 }
2483         }
2484         return false;
2485 }
2486
2487
2488 /*--------------------
2489  * expression_tree_mutator() is designed to support routines that make a
2490  * modified copy of an expression tree, with some nodes being added,
2491  * removed, or replaced by new subtrees.  The original tree is (normally)
2492  * not changed.  Each recursion level is responsible for returning a copy of
2493  * (or appropriately modified substitute for) the subtree it is handed.
2494  * A mutator routine should look like this:
2495  *
2496  * Node * my_mutator (Node *node, my_struct *context)
2497  * {
2498  *              if (node == NULL)
2499  *                      return NULL;
2500  *              // check for nodes that special work is required for, eg:
2501  *              if (IsA(node, Var))
2502  *              {
2503  *                      ... create and return modified copy of Var node
2504  *              }
2505  *              else if (IsA(node, ...))
2506  *              {
2507  *                      ... do special transformations of other node types
2508  *              }
2509  *              // for any node type not specially processed, do:
2510  *              return expression_tree_mutator(node, my_mutator, (void *) context);
2511  * }
2512  *
2513  * The "context" argument points to a struct that holds whatever context
2514  * information the mutator routine needs --- it can be used to return extra
2515  * data gathered by the mutator, too.  This argument is not touched by
2516  * expression_tree_mutator, but it is passed down to recursive sub-invocations
2517  * of my_mutator.  The tree walk is started from a setup routine that
2518  * fills in the appropriate context struct, calls my_mutator with the
2519  * top-level node of the tree, and does any required post-processing.
2520  *
2521  * Each level of recursion must return an appropriately modified Node.
2522  * If expression_tree_mutator() is called, it will make an exact copy
2523  * of the given Node, but invoke my_mutator() to copy the sub-node(s)
2524  * of that Node.  In this way, my_mutator() has full control over the
2525  * copying process but need not directly deal with expression trees
2526  * that it has no interest in.
2527  *
2528  * Just as for expression_tree_walker, the node types handled by
2529  * expression_tree_mutator include all those normally found in target lists
2530  * and qualifier clauses during the planning stage.
2531  *
2532  * expression_tree_mutator will handle SubLink nodes by recursing normally
2533  * into the "lefthand" arguments (which are expressions belonging to the outer
2534  * plan).  It will also call the mutator on the sub-Query node; however, when
2535  * expression_tree_mutator itself is called on a Query node, it does nothing
2536  * and returns the unmodified Query node.  The net effect is that unless the
2537  * mutator does something special at a Query node, sub-selects will not be
2538  * visited or modified; the original sub-select will be linked to by the new
2539  * SubLink node.  Mutators that want to descend into sub-selects will usually
2540  * do so by recognizing Query nodes and calling query_tree_mutator (below).
2541  *
2542  * expression_tree_mutator will handle a SubPlan node by recursing into
2543  * the "exprs" and "args" lists (which belong to the outer plan), but it
2544  * will simply copy the link to the inner plan, since that's typically what
2545  * expression tree mutators want.  A mutator that wants to modify the subplan
2546  * can force appropriate behavior by recognizing SubPlan expression nodes
2547  * and doing the right thing.
2548  *--------------------
2549  */
2550
2551 Node *
2552 expression_tree_mutator(Node *node,
2553                                                 Node *(*mutator) (),
2554                                                 void *context)
2555 {
2556         /*
2557          * The mutator has already decided not to modify the current node, but
2558          * we must call the mutator for any sub-nodes.
2559          */
2560
2561 #define FLATCOPY(newnode, node, nodetype)  \
2562         ( (newnode) = makeNode(nodetype), \
2563           memcpy((newnode), (node), sizeof(nodetype)) )
2564
2565 #define CHECKFLATCOPY(newnode, node, nodetype)  \
2566         ( AssertMacro(IsA((node), nodetype)), \
2567           (newnode) = makeNode(nodetype), \
2568           memcpy((newnode), (node), sizeof(nodetype)) )
2569
2570 #define MUTATE(newfield, oldfield, fieldtype)  \
2571                 ( (newfield) = (fieldtype) mutator((Node *) (oldfield), context) )
2572
2573         if (node == NULL)
2574                 return NULL;
2575         switch (nodeTag(node))
2576         {
2577                 case T_Var:
2578                 case T_Const:
2579                 case T_Param:
2580                 case T_CoerceToDomainValue:
2581                 case T_SetToDefault:
2582                 case T_RangeTblRef:
2583                         /* primitive node types with no subnodes */
2584                         return (Node *) copyObject(node);
2585                 case T_Aggref:
2586                         {
2587                                 Aggref     *aggref = (Aggref *) node;
2588                                 Aggref     *newnode;
2589
2590                                 FLATCOPY(newnode, aggref, Aggref);
2591                                 MUTATE(newnode->target, aggref->target, Expr *);
2592                                 return (Node *) newnode;
2593                         }
2594                         break;
2595                 case T_ArrayRef:
2596                         {
2597                                 ArrayRef   *arrayref = (ArrayRef *) node;
2598                                 ArrayRef   *newnode;
2599
2600                                 FLATCOPY(newnode, arrayref, ArrayRef);
2601                                 MUTATE(newnode->refupperindexpr, arrayref->refupperindexpr,
2602                                            List *);
2603                                 MUTATE(newnode->reflowerindexpr, arrayref->reflowerindexpr,
2604                                            List *);
2605                                 MUTATE(newnode->refexpr, arrayref->refexpr,
2606                                            Expr *);
2607                                 MUTATE(newnode->refassgnexpr, arrayref->refassgnexpr,
2608                                            Expr *);
2609                                 return (Node *) newnode;
2610                         }
2611                         break;
2612                 case T_FuncExpr:
2613                         {
2614                                 FuncExpr   *expr = (FuncExpr *) node;
2615                                 FuncExpr   *newnode;
2616
2617                                 FLATCOPY(newnode, expr, FuncExpr);
2618                                 MUTATE(newnode->args, expr->args, List *);
2619                                 return (Node *) newnode;
2620                         }
2621                         break;
2622                 case T_OpExpr:
2623                         {
2624                                 OpExpr     *expr = (OpExpr *) node;
2625                                 OpExpr     *newnode;
2626
2627                                 FLATCOPY(newnode, expr, OpExpr);
2628                                 MUTATE(newnode->args, expr->args, List *);
2629                                 return (Node *) newnode;
2630                         }
2631                         break;
2632                 case T_DistinctExpr:
2633                         {
2634                                 DistinctExpr *expr = (DistinctExpr *) node;
2635                                 DistinctExpr *newnode;
2636
2637                                 FLATCOPY(newnode, expr, DistinctExpr);
2638                                 MUTATE(newnode->args, expr->args, List *);
2639                                 return (Node *) newnode;
2640                         }
2641                         break;
2642                 case T_ScalarArrayOpExpr:
2643                         {
2644                                 ScalarArrayOpExpr *expr = (ScalarArrayOpExpr *) node;
2645                                 ScalarArrayOpExpr *newnode;
2646
2647                                 FLATCOPY(newnode, expr, ScalarArrayOpExpr);
2648                                 MUTATE(newnode->args, expr->args, List *);
2649                                 return (Node *) newnode;
2650                         }
2651                         break;
2652                 case T_BoolExpr:
2653                         {
2654                                 BoolExpr   *expr = (BoolExpr *) node;
2655                                 BoolExpr   *newnode;
2656
2657                                 FLATCOPY(newnode, expr, BoolExpr);
2658                                 MUTATE(newnode->args, expr->args, List *);
2659                                 return (Node *) newnode;
2660                         }
2661                         break;
2662                 case T_SubLink:
2663                         {
2664                                 SubLink    *sublink = (SubLink *) node;
2665                                 SubLink    *newnode;
2666
2667                                 FLATCOPY(newnode, sublink, SubLink);
2668                                 MUTATE(newnode->lefthand, sublink->lefthand, List *);
2669
2670                                 /*
2671                                  * Also invoke the mutator on the sublink's Query node, so
2672                                  * it can recurse into the sub-query if it wants to.
2673                                  */
2674                                 MUTATE(newnode->subselect, sublink->subselect, Node *);
2675                                 return (Node *) newnode;
2676                         }
2677                         break;
2678                 case T_SubPlan:
2679                         {
2680                                 SubPlan    *subplan = (SubPlan *) node;
2681                                 SubPlan    *newnode;
2682
2683                                 FLATCOPY(newnode, subplan, SubPlan);
2684                                 /* transform exprs list */
2685                                 MUTATE(newnode->exprs, subplan->exprs, List *);
2686                                 /* transform args list (params to be passed to subplan) */
2687                                 MUTATE(newnode->args, subplan->args, List *);
2688                                 /* but not the sub-Plan itself, which is referenced as-is */
2689                                 return (Node *) newnode;
2690                         }
2691                         break;
2692                 case T_FieldSelect:
2693                         {
2694                                 FieldSelect *fselect = (FieldSelect *) node;
2695                                 FieldSelect *newnode;
2696
2697                                 FLATCOPY(newnode, fselect, FieldSelect);
2698                                 MUTATE(newnode->arg, fselect->arg, Expr *);
2699                                 return (Node *) newnode;
2700                         }
2701                         break;
2702                 case T_RelabelType:
2703                         {
2704                                 RelabelType *relabel = (RelabelType *) node;
2705                                 RelabelType *newnode;
2706
2707                                 FLATCOPY(newnode, relabel, RelabelType);
2708                                 MUTATE(newnode->arg, relabel->arg, Expr *);
2709                                 return (Node *) newnode;
2710                         }
2711                         break;
2712                 case T_CaseExpr:
2713                         {
2714                                 CaseExpr   *caseexpr = (CaseExpr *) node;
2715                                 CaseExpr   *newnode;
2716
2717                                 FLATCOPY(newnode, caseexpr, CaseExpr);
2718                                 MUTATE(newnode->args, caseexpr->args, List *);
2719                                 /* caseexpr->arg should be null, but we'll check it anyway */
2720                                 MUTATE(newnode->arg, caseexpr->arg, Expr *);
2721                                 MUTATE(newnode->defresult, caseexpr->defresult, Expr *);
2722                                 return (Node *) newnode;
2723                         }
2724                         break;
2725                 case T_CaseWhen:
2726                         {
2727                                 CaseWhen   *casewhen = (CaseWhen *) node;
2728                                 CaseWhen   *newnode;
2729
2730                                 FLATCOPY(newnode, casewhen, CaseWhen);
2731                                 MUTATE(newnode->expr, casewhen->expr, Expr *);
2732                                 MUTATE(newnode->result, casewhen->result, Expr *);
2733                                 return (Node *) newnode;
2734                         }
2735                         break;
2736                 case T_ArrayExpr:
2737                         {
2738                                 ArrayExpr  *arrayexpr = (ArrayExpr *) node;
2739                                 ArrayExpr  *newnode;
2740
2741                                 FLATCOPY(newnode, arrayexpr, ArrayExpr);
2742                                 MUTATE(newnode->elements, arrayexpr->elements, List *);
2743                                 return (Node *) newnode;
2744                         }
2745                         break;
2746                 case T_CoalesceExpr:
2747                         {
2748                                 CoalesceExpr *coalesceexpr = (CoalesceExpr *) node;
2749                                 CoalesceExpr *newnode;
2750
2751                                 FLATCOPY(newnode, coalesceexpr, CoalesceExpr);
2752                                 MUTATE(newnode->args, coalesceexpr->args, List *);
2753                                 return (Node *) newnode;
2754                         }
2755                         break;
2756                 case T_NullIfExpr:
2757                         {
2758                                 NullIfExpr *expr = (NullIfExpr *) node;
2759                                 NullIfExpr *newnode;
2760
2761                                 FLATCOPY(newnode, expr, NullIfExpr);
2762                                 MUTATE(newnode->args, expr->args, List *);
2763                                 return (Node *) newnode;
2764                         }
2765                         break;
2766                 case T_NullTest:
2767                         {
2768                                 NullTest   *ntest = (NullTest *) node;
2769                                 NullTest   *newnode;
2770
2771                                 FLATCOPY(newnode, ntest, NullTest);
2772                                 MUTATE(newnode->arg, ntest->arg, Expr *);
2773                                 return (Node *) newnode;
2774                         }
2775                         break;
2776                 case T_BooleanTest:
2777                         {
2778                                 BooleanTest *btest = (BooleanTest *) node;
2779                                 BooleanTest *newnode;
2780
2781                                 FLATCOPY(newnode, btest, BooleanTest);
2782                                 MUTATE(newnode->arg, btest->arg, Expr *);
2783                                 return (Node *) newnode;
2784                         }
2785                         break;
2786                 case T_CoerceToDomain:
2787                         {
2788                                 CoerceToDomain *ctest = (CoerceToDomain *) node;
2789                                 CoerceToDomain *newnode;
2790
2791                                 FLATCOPY(newnode, ctest, CoerceToDomain);
2792                                 MUTATE(newnode->arg, ctest->arg, Expr *);
2793                                 return (Node *) newnode;
2794                         }
2795                         break;
2796                 case T_TargetEntry:
2797                         {
2798                                 /*
2799                                  * We mutate the expression, but not the resdom, by
2800                                  * default.
2801                                  */
2802                                 TargetEntry *targetentry = (TargetEntry *) node;
2803                                 TargetEntry *newnode;
2804
2805                                 FLATCOPY(newnode, targetentry, TargetEntry);
2806                                 MUTATE(newnode->expr, targetentry->expr, Expr *);
2807                                 return (Node *) newnode;
2808                         }
2809                         break;
2810                 case T_Query:
2811                         /* Do nothing with a sub-Query, per discussion above */
2812                         return node;
2813                 case T_List:
2814                         {
2815                                 /*
2816                                  * We assume the mutator isn't interested in the list
2817                                  * nodes per se, so just invoke it on each list element.
2818                                  * NOTE: this would fail badly on a list with integer
2819                                  * elements!
2820                                  */
2821                                 FastList        resultlist;
2822                                 List       *temp;
2823
2824                                 FastListInit(&resultlist);
2825                                 foreach(temp, (List *) node)
2826                                 {
2827                                         FastAppend(&resultlist,
2828                                                            mutator((Node *) lfirst(temp), context));
2829                                 }
2830                                 return (Node *) FastListValue(&resultlist);
2831                         }
2832                         break;
2833                 case T_FromExpr:
2834                         {
2835                                 FromExpr   *from = (FromExpr *) node;
2836                                 FromExpr   *newnode;
2837
2838                                 FLATCOPY(newnode, from, FromExpr);
2839                                 MUTATE(newnode->fromlist, from->fromlist, List *);
2840                                 MUTATE(newnode->quals, from->quals, Node *);
2841                                 return (Node *) newnode;
2842                         }
2843                         break;
2844                 case T_JoinExpr:
2845                         {
2846                                 JoinExpr   *join = (JoinExpr *) node;
2847                                 JoinExpr   *newnode;
2848
2849                                 FLATCOPY(newnode, join, JoinExpr);
2850                                 MUTATE(newnode->larg, join->larg, Node *);
2851                                 MUTATE(newnode->rarg, join->rarg, Node *);
2852                                 MUTATE(newnode->quals, join->quals, Node *);
2853                                 /* We do not mutate alias or using by default */
2854                                 return (Node *) newnode;
2855                         }
2856                         break;
2857                 case T_SetOperationStmt:
2858                         {
2859                                 SetOperationStmt *setop = (SetOperationStmt *) node;
2860                                 SetOperationStmt *newnode;
2861
2862                                 FLATCOPY(newnode, setop, SetOperationStmt);
2863                                 MUTATE(newnode->larg, setop->larg, Node *);
2864                                 MUTATE(newnode->rarg, setop->rarg, Node *);
2865                                 return (Node *) newnode;
2866                         }
2867                         break;
2868                 case T_InClauseInfo:
2869                         {
2870                                 InClauseInfo *ininfo = (InClauseInfo *) node;
2871                                 InClauseInfo *newnode;
2872
2873                                 FLATCOPY(newnode, ininfo, InClauseInfo);
2874                                 MUTATE(newnode->sub_targetlist, ininfo->sub_targetlist, List *);
2875                                 return (Node *) newnode;
2876                         }
2877                         break;
2878                 case T_RangeVar:
2879                         /*
2880                          * Give a useful complaint if someone uses a bare relation name
2881                          * in an expression (see comments in transformColumnRef()).
2882                          */
2883                         ereport(ERROR,
2884                                         (errcode(ERRCODE_SYNTAX_ERROR),
2885                                          errmsg("relation reference \"%s\" cannot be used in an expression",
2886                                                         ((RangeVar *) node)->relname)));
2887                         break;
2888                 default:
2889                         elog(ERROR, "unrecognized node type: %d",
2890                                  (int) nodeTag(node));
2891                         break;
2892         }
2893         /* can't get here, but keep compiler happy */
2894         return NULL;
2895 }
2896
2897
2898 /*
2899  * query_tree_mutator --- initiate modification of a Query's expressions
2900  *
2901  * This routine exists just to reduce the number of places that need to know
2902  * where all the expression subtrees of a Query are.  Note it can be used
2903  * for starting a walk at top level of a Query regardless of whether the
2904  * mutator intends to descend into subqueries.  It is also useful for
2905  * descending into subqueries within a mutator.
2906  *
2907  * Some callers want to suppress mutating of certain items in the Query,
2908  * typically because they need to process them specially, or don't actually
2909  * want to recurse into subqueries.  This is supported by the flags argument,
2910  * which is the bitwise OR of flag values to suppress mutating of
2911  * indicated items.  (More flag bits may be added as needed.)
2912  *
2913  * Normally the Query node itself is copied, but some callers want it to be
2914  * modified in-place; they must pass QTW_DONT_COPY_QUERY in flags.      All
2915  * modified substructure is safely copied in any case.
2916  */
2917 Query *
2918 query_tree_mutator(Query *query,
2919                                    Node *(*mutator) (),
2920                                    void *context,
2921                                    int flags)
2922 {
2923         FastList        newrt;
2924         List       *rt;
2925
2926         Assert(query != NULL && IsA(query, Query));
2927
2928         if (!(flags & QTW_DONT_COPY_QUERY))
2929         {
2930                 Query      *newquery;
2931
2932                 FLATCOPY(newquery, query, Query);
2933                 query = newquery;
2934         }
2935
2936         MUTATE(query->targetList, query->targetList, List *);
2937         MUTATE(query->jointree, query->jointree, FromExpr *);
2938         MUTATE(query->setOperations, query->setOperations, Node *);
2939         MUTATE(query->havingQual, query->havingQual, Node *);
2940         MUTATE(query->limitOffset, query->limitOffset, Node *);
2941         MUTATE(query->limitCount, query->limitCount, Node *);
2942         MUTATE(query->in_info_list, query->in_info_list, List *);
2943         FastListInit(&newrt);
2944         foreach(rt, query->rtable)
2945         {
2946                 RangeTblEntry *rte = (RangeTblEntry *) lfirst(rt);
2947                 RangeTblEntry *newrte;
2948
2949                 FLATCOPY(newrte, rte, RangeTblEntry);
2950                 switch (rte->rtekind)
2951                 {
2952                         case RTE_RELATION:
2953                         case RTE_SPECIAL:
2954                                 /* we don't bother to copy eref, aliases, etc; OK? */
2955                                 break;
2956                         case RTE_SUBQUERY:
2957                                 if (!(flags & QTW_IGNORE_RT_SUBQUERIES))
2958                                 {
2959                                         CHECKFLATCOPY(newrte->subquery, rte->subquery, Query);
2960                                         MUTATE(newrte->subquery, newrte->subquery, Query *);
2961                                 }
2962                                 break;
2963                         case RTE_JOIN:
2964                                 if (!(flags & QTW_IGNORE_JOINALIASES))
2965                                 {
2966                                         MUTATE(newrte->joinaliasvars, rte->joinaliasvars, List *);
2967                                 }
2968                                 break;
2969                         case RTE_FUNCTION:
2970                                 MUTATE(newrte->funcexpr, rte->funcexpr, Node *);
2971                                 break;
2972                 }
2973                 FastAppend(&newrt, newrte);
2974         }
2975         query->rtable = FastListValue(&newrt);
2976         return query;
2977 }
2978
2979 /*
2980  * query_or_expression_tree_walker --- hybrid form
2981  *
2982  * This routine will invoke query_tree_walker if called on a Query node,
2983  * else will invoke the walker directly.  This is a useful way of starting
2984  * the recursion when the walker's normal change of state is not appropriate
2985  * for the outermost Query node.
2986  */
2987 bool
2988 query_or_expression_tree_walker(Node *node,
2989                                                                 bool (*walker) (),
2990                                                                 void *context,
2991                                                                 int flags)
2992 {
2993         if (node && IsA(node, Query))
2994                 return query_tree_walker((Query *) node,
2995                                                                  walker,
2996                                                                  context,
2997                                                                  flags);
2998         else
2999                 return walker(node, context);
3000 }
3001
3002 /*
3003  * query_or_expression_tree_mutator --- hybrid form
3004  *
3005  * This routine will invoke query_tree_mutator if called on a Query node,
3006  * else will invoke the mutator directly.  This is a useful way of starting
3007  * the recursion when the mutator's normal change of state is not appropriate
3008  * for the outermost Query node.
3009  */
3010 Node *
3011 query_or_expression_tree_mutator(Node *node,
3012                                                                  Node *(*mutator) (),
3013                                                                  void *context,
3014                                                                  int flags)
3015 {
3016         if (node && IsA(node, Query))
3017                 return (Node *) query_tree_mutator((Query *) node,
3018                                                                                    mutator,
3019                                                                                    context,
3020                                                                                    flags);
3021         else
3022                 return mutator(node, context);
3023 }