]> granicus.if.org Git - postgresql/blob - src/backend/nodes/nodeFuncs.c
Reduce hash size for compute_array_stats, compute_tsvector_stats.
[postgresql] / src / backend / nodes / nodeFuncs.c
1 /*-------------------------------------------------------------------------
2  *
3  * nodeFuncs.c
4  *              Various general-purpose manipulations of Node trees
5  *
6  * Portions Copyright (c) 1996-2012, PostgreSQL Global Development Group
7  * Portions Copyright (c) 1994, Regents of the University of California
8  *
9  *
10  * IDENTIFICATION
11  *        src/backend/nodes/nodeFuncs.c
12  *
13  *-------------------------------------------------------------------------
14  */
15 #include "postgres.h"
16
17 #include "catalog/pg_collation.h"
18 #include "catalog/pg_type.h"
19 #include "miscadmin.h"
20 #include "nodes/makefuncs.h"
21 #include "nodes/nodeFuncs.h"
22 #include "nodes/relation.h"
23 #include "utils/builtins.h"
24 #include "utils/lsyscache.h"
25
26
27 static bool expression_returns_set_walker(Node *node, void *context);
28 static int      leftmostLoc(int loc1, int loc2);
29
30
31 /*
32  *      exprType -
33  *        returns the Oid of the type of the expression's result.
34  */
35 Oid
36 exprType(const Node *expr)
37 {
38         Oid                     type;
39
40         if (!expr)
41                 return InvalidOid;
42
43         switch (nodeTag(expr))
44         {
45                 case T_Var:
46                         type = ((const Var *) expr)->vartype;
47                         break;
48                 case T_Const:
49                         type = ((const Const *) expr)->consttype;
50                         break;
51                 case T_Param:
52                         type = ((const Param *) expr)->paramtype;
53                         break;
54                 case T_Aggref:
55                         type = ((const Aggref *) expr)->aggtype;
56                         break;
57                 case T_WindowFunc:
58                         type = ((const WindowFunc *) expr)->wintype;
59                         break;
60                 case T_ArrayRef:
61                         {
62                                 const ArrayRef   *arrayref = (const ArrayRef *) expr;
63
64                                 /* slice and/or store operations yield the array type */
65                                 if (arrayref->reflowerindexpr || arrayref->refassgnexpr)
66                                         type = arrayref->refarraytype;
67                                 else
68                                         type = arrayref->refelemtype;
69                         }
70                         break;
71                 case T_FuncExpr:
72                         type = ((const FuncExpr *) expr)->funcresulttype;
73                         break;
74                 case T_NamedArgExpr:
75                         type = exprType((Node *) ((const NamedArgExpr *) expr)->arg);
76                         break;
77                 case T_OpExpr:
78                         type = ((const OpExpr *) expr)->opresulttype;
79                         break;
80                 case T_DistinctExpr:
81                         type = ((const DistinctExpr *) expr)->opresulttype;
82                         break;
83                 case T_NullIfExpr:
84                         type = ((const NullIfExpr *) expr)->opresulttype;
85                         break;
86                 case T_ScalarArrayOpExpr:
87                         type = BOOLOID;
88                         break;
89                 case T_BoolExpr:
90                         type = BOOLOID;
91                         break;
92                 case T_SubLink:
93                         {
94                                 const SubLink    *sublink = (const SubLink *) expr;
95
96                                 if (sublink->subLinkType == EXPR_SUBLINK ||
97                                         sublink->subLinkType == ARRAY_SUBLINK)
98                                 {
99                                         /* get the type of the subselect's first target column */
100                                         Query      *qtree = (Query *) sublink->subselect;
101                                         TargetEntry *tent;
102
103                                         if (!qtree || !IsA(qtree, Query))
104                                                 elog(ERROR, "cannot get type for untransformed sublink");
105                                         tent = (TargetEntry *) linitial(qtree->targetList);
106                                         Assert(IsA(tent, TargetEntry));
107                                         Assert(!tent->resjunk);
108                                         type = exprType((Node *) tent->expr);
109                                         if (sublink->subLinkType == ARRAY_SUBLINK)
110                                         {
111                                                 type = get_array_type(type);
112                                                 if (!OidIsValid(type))
113                                                         ereport(ERROR,
114                                                                         (errcode(ERRCODE_UNDEFINED_OBJECT),
115                                                                          errmsg("could not find array type for data type %s",
116                                                         format_type_be(exprType((Node *) tent->expr)))));
117                                         }
118                                 }
119                                 else
120                                 {
121                                         /* for all other sublink types, result is boolean */
122                                         type = BOOLOID;
123                                 }
124                         }
125                         break;
126                 case T_SubPlan:
127                         {
128                                 const SubPlan    *subplan = (const SubPlan *) expr;
129
130                                 if (subplan->subLinkType == EXPR_SUBLINK ||
131                                         subplan->subLinkType == ARRAY_SUBLINK)
132                                 {
133                                         /* get the type of the subselect's first target column */
134                                         type = subplan->firstColType;
135                                         if (subplan->subLinkType == ARRAY_SUBLINK)
136                                         {
137                                                 type = get_array_type(type);
138                                                 if (!OidIsValid(type))
139                                                         ereport(ERROR,
140                                                                         (errcode(ERRCODE_UNDEFINED_OBJECT),
141                                                                          errmsg("could not find array type for data type %s",
142                                                                         format_type_be(subplan->firstColType))));
143                                         }
144                                 }
145                                 else
146                                 {
147                                         /* for all other subplan types, result is boolean */
148                                         type = BOOLOID;
149                                 }
150                         }
151                         break;
152                 case T_AlternativeSubPlan:
153                         {
154                                 const AlternativeSubPlan *asplan = (const AlternativeSubPlan *) expr;
155
156                                 /* subplans should all return the same thing */
157                                 type = exprType((Node *) linitial(asplan->subplans));
158                         }
159                         break;
160                 case T_FieldSelect:
161                         type = ((const FieldSelect *) expr)->resulttype;
162                         break;
163                 case T_FieldStore:
164                         type = ((const FieldStore *) expr)->resulttype;
165                         break;
166                 case T_RelabelType:
167                         type = ((const RelabelType *) expr)->resulttype;
168                         break;
169                 case T_CoerceViaIO:
170                         type = ((const CoerceViaIO *) expr)->resulttype;
171                         break;
172                 case T_ArrayCoerceExpr:
173                         type = ((const ArrayCoerceExpr *) expr)->resulttype;
174                         break;
175                 case T_ConvertRowtypeExpr:
176                         type = ((const ConvertRowtypeExpr *) expr)->resulttype;
177                         break;
178                 case T_CollateExpr:
179                         type = exprType((Node *) ((const CollateExpr *) expr)->arg);
180                         break;
181                 case T_CaseExpr:
182                         type = ((const CaseExpr *) expr)->casetype;
183                         break;
184                 case T_CaseTestExpr:
185                         type = ((const CaseTestExpr *) expr)->typeId;
186                         break;
187                 case T_ArrayExpr:
188                         type = ((const ArrayExpr *) expr)->array_typeid;
189                         break;
190                 case T_RowExpr:
191                         type = ((const RowExpr *) expr)->row_typeid;
192                         break;
193                 case T_RowCompareExpr:
194                         type = BOOLOID;
195                         break;
196                 case T_CoalesceExpr:
197                         type = ((const CoalesceExpr *) expr)->coalescetype;
198                         break;
199                 case T_MinMaxExpr:
200                         type = ((const MinMaxExpr *) expr)->minmaxtype;
201                         break;
202                 case T_XmlExpr:
203                         if (((const XmlExpr *) expr)->op == IS_DOCUMENT)
204                                 type = BOOLOID;
205                         else if (((const XmlExpr *) expr)->op == IS_XMLSERIALIZE)
206                                 type = TEXTOID;
207                         else
208                                 type = XMLOID;
209                         break;
210                 case T_NullTest:
211                         type = BOOLOID;
212                         break;
213                 case T_BooleanTest:
214                         type = BOOLOID;
215                         break;
216                 case T_CoerceToDomain:
217                         type = ((const CoerceToDomain *) expr)->resulttype;
218                         break;
219                 case T_CoerceToDomainValue:
220                         type = ((const CoerceToDomainValue *) expr)->typeId;
221                         break;
222                 case T_SetToDefault:
223                         type = ((const SetToDefault *) expr)->typeId;
224                         break;
225                 case T_CurrentOfExpr:
226                         type = BOOLOID;
227                         break;
228                 case T_PlaceHolderVar:
229                         type = exprType((Node *) ((const PlaceHolderVar *) expr)->phexpr);
230                         break;
231                 default:
232                         elog(ERROR, "unrecognized node type: %d", (int) nodeTag(expr));
233                         type = InvalidOid;      /* keep compiler quiet */
234                         break;
235         }
236         return type;
237 }
238
239 /*
240  *      exprTypmod -
241  *        returns the type-specific modifier of the expression's result type,
242  *        if it can be determined.      In many cases, it can't and we return -1.
243  */
244 int32
245 exprTypmod(const Node *expr)
246 {
247         if (!expr)
248                 return -1;
249
250         switch (nodeTag(expr))
251         {
252                 case T_Var:
253                         return ((const Var *) expr)->vartypmod;
254                 case T_Const:
255                         return ((const Const *) expr)->consttypmod;
256                 case T_Param:
257                         return ((const Param *) expr)->paramtypmod;
258                 case T_ArrayRef:
259                         /* typmod is the same for array or element */
260                         return ((const ArrayRef *) expr)->reftypmod;
261                 case T_FuncExpr:
262                         {
263                                 int32           coercedTypmod;
264
265                                 /* Be smart about length-coercion functions... */
266                                 if (exprIsLengthCoercion(expr, &coercedTypmod))
267                                         return coercedTypmod;
268                         }
269                         break;
270                 case T_NamedArgExpr:
271                         return exprTypmod((Node *) ((const NamedArgExpr *) expr)->arg);
272                 case T_NullIfExpr:
273                         {
274                                 /*
275                                  * Result is either first argument or NULL, so we can report
276                                  * first argument's typmod if known.
277                                  */
278                                 const NullIfExpr *nexpr = (const NullIfExpr *) expr;
279
280                                 return exprTypmod((Node *) linitial(nexpr->args));
281                         }
282                         break;
283                 case T_SubLink:
284                         {
285                                 const SubLink    *sublink = (const SubLink *) expr;
286
287                                 if (sublink->subLinkType == EXPR_SUBLINK ||
288                                         sublink->subLinkType == ARRAY_SUBLINK)
289                                 {
290                                         /* get the typmod of the subselect's first target column */
291                                         Query      *qtree = (Query *) sublink->subselect;
292                                         TargetEntry *tent;
293
294                                         if (!qtree || !IsA(qtree, Query))
295                                                 elog(ERROR, "cannot get type for untransformed sublink");
296                                         tent = (TargetEntry *) linitial(qtree->targetList);
297                                         Assert(IsA(tent, TargetEntry));
298                                         Assert(!tent->resjunk);
299                                         return exprTypmod((Node *) tent->expr);
300                                         /* note we don't need to care if it's an array */
301                                 }
302                         }
303                         break;
304                 case T_SubPlan:
305                         {
306                                 const SubPlan    *subplan = (const SubPlan *) expr;
307
308                                 if (subplan->subLinkType == EXPR_SUBLINK ||
309                                         subplan->subLinkType == ARRAY_SUBLINK)
310                                 {
311                                         /* get the typmod of the subselect's first target column */
312                                         /* note we don't need to care if it's an array */
313                                         return subplan->firstColTypmod;
314                                 }
315                                 else
316                                 {
317                                         /* for all other subplan types, result is boolean */
318                                         return -1;
319                                 }
320                         }
321                         break;
322                 case T_AlternativeSubPlan:
323                         {
324                                 const AlternativeSubPlan *asplan = (const AlternativeSubPlan *) expr;
325
326                                 /* subplans should all return the same thing */
327                                 return exprTypmod((Node *) linitial(asplan->subplans));
328                         }
329                         break;
330                 case T_FieldSelect:
331                         return ((const FieldSelect *) expr)->resulttypmod;
332                 case T_RelabelType:
333                         return ((const RelabelType *) expr)->resulttypmod;
334                 case T_ArrayCoerceExpr:
335                         return ((const ArrayCoerceExpr *) expr)->resulttypmod;
336                 case T_CollateExpr:
337                         return exprTypmod((Node *) ((const CollateExpr *) expr)->arg);
338                 case T_CaseExpr:
339                         {
340                                 /*
341                                  * If all the alternatives agree on type/typmod, return that
342                                  * typmod, else use -1
343                                  */
344                                 const CaseExpr   *cexpr = (const CaseExpr *) expr;
345                                 Oid                     casetype = cexpr->casetype;
346                                 int32           typmod;
347                                 ListCell   *arg;
348
349                                 if (!cexpr->defresult)
350                                         return -1;
351                                 if (exprType((Node *) cexpr->defresult) != casetype)
352                                         return -1;
353                                 typmod = exprTypmod((Node *) cexpr->defresult);
354                                 if (typmod < 0)
355                                         return -1;      /* no point in trying harder */
356                                 foreach(arg, cexpr->args)
357                                 {
358                                         CaseWhen   *w = (CaseWhen *) lfirst(arg);
359
360                                         Assert(IsA(w, CaseWhen));
361                                         if (exprType((Node *) w->result) != casetype)
362                                                 return -1;
363                                         if (exprTypmod((Node *) w->result) != typmod)
364                                                 return -1;
365                                 }
366                                 return typmod;
367                         }
368                         break;
369                 case T_CaseTestExpr:
370                         return ((const CaseTestExpr *) expr)->typeMod;
371                 case T_ArrayExpr:
372                         {
373                                 /*
374                                  * If all the elements agree on type/typmod, return that
375                                  * typmod, else use -1
376                                  */
377                                 const ArrayExpr  *arrayexpr = (const ArrayExpr *) expr;
378                                 Oid                     commontype;
379                                 int32           typmod;
380                                 ListCell   *elem;
381
382                                 if (arrayexpr->elements == NIL)
383                                         return -1;
384                                 typmod = exprTypmod((Node *) linitial(arrayexpr->elements));
385                                 if (typmod < 0)
386                                         return -1;      /* no point in trying harder */
387                                 if (arrayexpr->multidims)
388                                         commontype = arrayexpr->array_typeid;
389                                 else
390                                         commontype = arrayexpr->element_typeid;
391                                 foreach(elem, arrayexpr->elements)
392                                 {
393                                         Node       *e = (Node *) lfirst(elem);
394
395                                         if (exprType(e) != commontype)
396                                                 return -1;
397                                         if (exprTypmod(e) != typmod)
398                                                 return -1;
399                                 }
400                                 return typmod;
401                         }
402                         break;
403                 case T_CoalesceExpr:
404                         {
405                                 /*
406                                  * If all the alternatives agree on type/typmod, return that
407                                  * typmod, else use -1
408                                  */
409                                 const CoalesceExpr *cexpr = (const CoalesceExpr *) expr;
410                                 Oid                     coalescetype = cexpr->coalescetype;
411                                 int32           typmod;
412                                 ListCell   *arg;
413
414                                 if (exprType((Node *) linitial(cexpr->args)) != coalescetype)
415                                         return -1;
416                                 typmod = exprTypmod((Node *) linitial(cexpr->args));
417                                 if (typmod < 0)
418                                         return -1;      /* no point in trying harder */
419                                 for_each_cell(arg, lnext(list_head(cexpr->args)))
420                                 {
421                                         Node       *e = (Node *) lfirst(arg);
422
423                                         if (exprType(e) != coalescetype)
424                                                 return -1;
425                                         if (exprTypmod(e) != typmod)
426                                                 return -1;
427                                 }
428                                 return typmod;
429                         }
430                         break;
431                 case T_MinMaxExpr:
432                         {
433                                 /*
434                                  * If all the alternatives agree on type/typmod, return that
435                                  * typmod, else use -1
436                                  */
437                                 const MinMaxExpr *mexpr = (const MinMaxExpr *) expr;
438                                 Oid                     minmaxtype = mexpr->minmaxtype;
439                                 int32           typmod;
440                                 ListCell   *arg;
441
442                                 if (exprType((Node *) linitial(mexpr->args)) != minmaxtype)
443                                         return -1;
444                                 typmod = exprTypmod((Node *) linitial(mexpr->args));
445                                 if (typmod < 0)
446                                         return -1;      /* no point in trying harder */
447                                 for_each_cell(arg, lnext(list_head(mexpr->args)))
448                                 {
449                                         Node       *e = (Node *) lfirst(arg);
450
451                                         if (exprType(e) != minmaxtype)
452                                                 return -1;
453                                         if (exprTypmod(e) != typmod)
454                                                 return -1;
455                                 }
456                                 return typmod;
457                         }
458                         break;
459                 case T_CoerceToDomain:
460                         return ((const CoerceToDomain *) expr)->resulttypmod;
461                 case T_CoerceToDomainValue:
462                         return ((const CoerceToDomainValue *) expr)->typeMod;
463                 case T_SetToDefault:
464                         return ((const SetToDefault *) expr)->typeMod;
465                 case T_PlaceHolderVar:
466                         return exprTypmod((Node *) ((const PlaceHolderVar *) expr)->phexpr);
467                 default:
468                         break;
469         }
470         return -1;
471 }
472
473 /*
474  * exprIsLengthCoercion
475  *              Detect whether an expression tree is an application of a datatype's
476  *              typmod-coercion function.  Optionally extract the result's typmod.
477  *
478  * If coercedTypmod is not NULL, the typmod is stored there if the expression
479  * is a length-coercion function, else -1 is stored there.
480  *
481  * Note that a combined type-and-length coercion will be treated as a
482  * length coercion by this routine.
483  */
484 bool
485 exprIsLengthCoercion(const Node *expr, int32 *coercedTypmod)
486 {
487         if (coercedTypmod != NULL)
488                 *coercedTypmod = -1;    /* default result on failure */
489
490         /*
491          * Scalar-type length coercions are FuncExprs, array-type length coercions
492          * are ArrayCoerceExprs
493          */
494         if (expr && IsA(expr, FuncExpr))
495         {
496                 const FuncExpr   *func = (const FuncExpr *) expr;
497                 int                     nargs;
498                 Const      *second_arg;
499
500                 /*
501                  * If it didn't come from a coercion context, reject.
502                  */
503                 if (func->funcformat != COERCE_EXPLICIT_CAST &&
504                         func->funcformat != COERCE_IMPLICIT_CAST)
505                         return false;
506
507                 /*
508                  * If it's not a two-argument or three-argument function with the
509                  * second argument being an int4 constant, it can't have been created
510                  * from a length coercion (it must be a type coercion, instead).
511                  */
512                 nargs = list_length(func->args);
513                 if (nargs < 2 || nargs > 3)
514                         return false;
515
516                 second_arg = (Const *) lsecond(func->args);
517                 if (!IsA(second_arg, Const) ||
518                         second_arg->consttype != INT4OID ||
519                         second_arg->constisnull)
520                         return false;
521
522                 /*
523                  * OK, it is indeed a length-coercion function.
524                  */
525                 if (coercedTypmod != NULL)
526                         *coercedTypmod = DatumGetInt32(second_arg->constvalue);
527
528                 return true;
529         }
530
531         if (expr && IsA(expr, ArrayCoerceExpr))
532         {
533                 const ArrayCoerceExpr *acoerce = (const ArrayCoerceExpr *) expr;
534
535                 /* It's not a length coercion unless there's a nondefault typmod */
536                 if (acoerce->resulttypmod < 0)
537                         return false;
538
539                 /*
540                  * OK, it is indeed a length-coercion expression.
541                  */
542                 if (coercedTypmod != NULL)
543                         *coercedTypmod = acoerce->resulttypmod;
544
545                 return true;
546         }
547
548         return false;
549 }
550
551 /*
552  * relabel_to_typmod
553  *              Add a RelabelType node that changes just the typmod of the expression.
554  *
555  * This is primarily intended to be used during planning.  Therefore, it
556  * strips any existing RelabelType nodes to maintain the planner's invariant
557  * that there are not adjacent RelabelTypes, and it uses COERCE_DONTCARE
558  * which would typically be inappropriate earlier.
559  */
560 Node *
561 relabel_to_typmod(Node *expr, int32 typmod)
562 {
563         Oid                     type = exprType(expr);
564         Oid                     coll = exprCollation(expr);
565
566         /* Strip any existing RelabelType node(s) */
567         while (expr && IsA(expr, RelabelType))
568                 expr = (Node *) ((RelabelType *) expr)->arg;
569
570         /* Apply new typmod, preserving the previous exposed type and collation */
571         return (Node *) makeRelabelType((Expr *) expr, type, typmod, coll,
572                                                                         COERCE_DONTCARE);
573 }
574
575 /*
576  * expression_returns_set
577  *        Test whether an expression returns a set result.
578  *
579  * Because we use expression_tree_walker(), this can also be applied to
580  * whole targetlists; it'll produce TRUE if any one of the tlist items
581  * returns a set.
582  */
583 bool
584 expression_returns_set(Node *clause)
585 {
586         return expression_returns_set_walker(clause, NULL);
587 }
588
589 static bool
590 expression_returns_set_walker(Node *node, void *context)
591 {
592         if (node == NULL)
593                 return false;
594         if (IsA(node, FuncExpr))
595         {
596                 FuncExpr   *expr = (FuncExpr *) node;
597
598                 if (expr->funcretset)
599                         return true;
600                 /* else fall through to check args */
601         }
602         if (IsA(node, OpExpr))
603         {
604                 OpExpr     *expr = (OpExpr *) node;
605
606                 if (expr->opretset)
607                         return true;
608                 /* else fall through to check args */
609         }
610
611         /* Avoid recursion for some cases that can't return a set */
612         if (IsA(node, Aggref))
613                 return false;
614         if (IsA(node, WindowFunc))
615                 return false;
616         if (IsA(node, DistinctExpr))
617                 return false;
618         if (IsA(node, NullIfExpr))
619                 return false;
620         if (IsA(node, ScalarArrayOpExpr))
621                 return false;
622         if (IsA(node, BoolExpr))
623                 return false;
624         if (IsA(node, SubLink))
625                 return false;
626         if (IsA(node, SubPlan))
627                 return false;
628         if (IsA(node, AlternativeSubPlan))
629                 return false;
630         if (IsA(node, ArrayExpr))
631                 return false;
632         if (IsA(node, RowExpr))
633                 return false;
634         if (IsA(node, RowCompareExpr))
635                 return false;
636         if (IsA(node, CoalesceExpr))
637                 return false;
638         if (IsA(node, MinMaxExpr))
639                 return false;
640         if (IsA(node, XmlExpr))
641                 return false;
642
643         return expression_tree_walker(node, expression_returns_set_walker,
644                                                                   context);
645 }
646
647
648 /*
649  *      exprCollation -
650  *        returns the Oid of the collation of the expression's result.
651  *
652  * Note: expression nodes that can invoke functions generally have an
653  * "inputcollid" field, which is what the function should use as collation.
654  * That is the resolved common collation of the node's inputs.  It is often
655  * but not always the same as the result collation; in particular, if the
656  * function produces a non-collatable result type from collatable inputs
657  * or vice versa, the two are different.
658  */
659 Oid
660 exprCollation(const Node *expr)
661 {
662         Oid                     coll;
663
664         if (!expr)
665                 return InvalidOid;
666
667         switch (nodeTag(expr))
668         {
669                 case T_Var:
670                         coll = ((const Var *) expr)->varcollid;
671                         break;
672                 case T_Const:
673                         coll = ((const Const *) expr)->constcollid;
674                         break;
675                 case T_Param:
676                         coll = ((const Param *) expr)->paramcollid;
677                         break;
678                 case T_Aggref:
679                         coll = ((const Aggref *) expr)->aggcollid;
680                         break;
681                 case T_WindowFunc:
682                         coll = ((const WindowFunc *) expr)->wincollid;
683                         break;
684                 case T_ArrayRef:
685                         coll = ((const ArrayRef *) expr)->refcollid;
686                         break;
687                 case T_FuncExpr:
688                         coll = ((const FuncExpr *) expr)->funccollid;
689                         break;
690                 case T_NamedArgExpr:
691                         coll = exprCollation((Node *) ((const NamedArgExpr *) expr)->arg);
692                         break;
693                 case T_OpExpr:
694                         coll = ((const OpExpr *) expr)->opcollid;
695                         break;
696                 case T_DistinctExpr:
697                         coll = ((const DistinctExpr *) expr)->opcollid;
698                         break;
699                 case T_NullIfExpr:
700                         coll = ((const NullIfExpr *) expr)->opcollid;
701                         break;
702                 case T_ScalarArrayOpExpr:
703                         coll = InvalidOid;      /* result is always boolean */
704                         break;
705                 case T_BoolExpr:
706                         coll = InvalidOid;      /* result is always boolean */
707                         break;
708                 case T_SubLink:
709                         {
710                                 const SubLink    *sublink = (const SubLink *) expr;
711
712                                 if (sublink->subLinkType == EXPR_SUBLINK ||
713                                         sublink->subLinkType == ARRAY_SUBLINK)
714                                 {
715                                         /* get the collation of subselect's first target column */
716                                         Query      *qtree = (Query *) sublink->subselect;
717                                         TargetEntry *tent;
718
719                                         if (!qtree || !IsA(qtree, Query))
720                                                 elog(ERROR, "cannot get collation for untransformed sublink");
721                                         tent = (TargetEntry *) linitial(qtree->targetList);
722                                         Assert(IsA(tent, TargetEntry));
723                                         Assert(!tent->resjunk);
724                                         coll = exprCollation((Node *) tent->expr);
725                                         /* collation doesn't change if it's converted to array */
726                                 }
727                                 else
728                                 {
729                                         /* for all other sublink types, result is boolean */
730                                         coll = InvalidOid;
731                                 }
732                         }
733                         break;
734                 case T_SubPlan:
735                         {
736                                 const SubPlan    *subplan = (const SubPlan *) expr;
737
738                                 if (subplan->subLinkType == EXPR_SUBLINK ||
739                                         subplan->subLinkType == ARRAY_SUBLINK)
740                                 {
741                                         /* get the collation of subselect's first target column */
742                                         coll = subplan->firstColCollation;
743                                         /* collation doesn't change if it's converted to array */
744                                 }
745                                 else
746                                 {
747                                         /* for all other subplan types, result is boolean */
748                                         coll = InvalidOid;
749                                 }
750                         }
751                         break;
752                 case T_AlternativeSubPlan:
753                         {
754                                 const AlternativeSubPlan *asplan = (const AlternativeSubPlan *) expr;
755
756                                 /* subplans should all return the same thing */
757                                 coll = exprCollation((Node *) linitial(asplan->subplans));
758                         }
759                         break;
760                 case T_FieldSelect:
761                         coll = ((const FieldSelect *) expr)->resultcollid;
762                         break;
763                 case T_FieldStore:
764                         coll = InvalidOid;      /* result is always composite */
765                         break;
766                 case T_RelabelType:
767                         coll = ((const RelabelType *) expr)->resultcollid;
768                         break;
769                 case T_CoerceViaIO:
770                         coll = ((const CoerceViaIO *) expr)->resultcollid;
771                         break;
772                 case T_ArrayCoerceExpr:
773                         coll = ((const ArrayCoerceExpr *) expr)->resultcollid;
774                         break;
775                 case T_ConvertRowtypeExpr:
776                         coll = InvalidOid;      /* result is always composite */
777                         break;
778                 case T_CollateExpr:
779                         coll = ((const CollateExpr *) expr)->collOid;
780                         break;
781                 case T_CaseExpr:
782                         coll = ((const CaseExpr *) expr)->casecollid;
783                         break;
784                 case T_CaseTestExpr:
785                         coll = ((const CaseTestExpr *) expr)->collation;
786                         break;
787                 case T_ArrayExpr:
788                         coll = ((const ArrayExpr *) expr)->array_collid;
789                         break;
790                 case T_RowExpr:
791                         coll = InvalidOid;      /* result is always composite */
792                         break;
793                 case T_RowCompareExpr:
794                         coll = InvalidOid;      /* result is always boolean */
795                         break;
796                 case T_CoalesceExpr:
797                         coll = ((const CoalesceExpr *) expr)->coalescecollid;
798                         break;
799                 case T_MinMaxExpr:
800                         coll = ((const MinMaxExpr *) expr)->minmaxcollid;
801                         break;
802                 case T_XmlExpr:
803
804                         /*
805                          * XMLSERIALIZE returns text from non-collatable inputs, so its
806                          * collation is always default.  The other cases return boolean or
807                          * XML, which are non-collatable.
808                          */
809                         if (((const XmlExpr *) expr)->op == IS_XMLSERIALIZE)
810                                 coll = DEFAULT_COLLATION_OID;
811                         else
812                                 coll = InvalidOid;
813                         break;
814                 case T_NullTest:
815                         coll = InvalidOid;      /* result is always boolean */
816                         break;
817                 case T_BooleanTest:
818                         coll = InvalidOid;      /* result is always boolean */
819                         break;
820                 case T_CoerceToDomain:
821                         coll = ((const CoerceToDomain *) expr)->resultcollid;
822                         break;
823                 case T_CoerceToDomainValue:
824                         coll = ((const CoerceToDomainValue *) expr)->collation;
825                         break;
826                 case T_SetToDefault:
827                         coll = ((const SetToDefault *) expr)->collation;
828                         break;
829                 case T_CurrentOfExpr:
830                         coll = InvalidOid;      /* result is always boolean */
831                         break;
832                 case T_PlaceHolderVar:
833                         coll = exprCollation((Node *) ((const PlaceHolderVar *) expr)->phexpr);
834                         break;
835                 default:
836                         elog(ERROR, "unrecognized node type: %d", (int) nodeTag(expr));
837                         coll = InvalidOid;      /* keep compiler quiet */
838                         break;
839         }
840         return coll;
841 }
842
843 /*
844  *      exprInputCollation -
845  *        returns the Oid of the collation a function should use, if available.
846  *
847  * Result is InvalidOid if the node type doesn't store this information.
848  */
849 Oid
850 exprInputCollation(const Node *expr)
851 {
852         Oid                     coll;
853
854         if (!expr)
855                 return InvalidOid;
856
857         switch (nodeTag(expr))
858         {
859                 case T_Aggref:
860                         coll = ((const Aggref *) expr)->inputcollid;
861                         break;
862                 case T_WindowFunc:
863                         coll = ((const WindowFunc *) expr)->inputcollid;
864                         break;
865                 case T_FuncExpr:
866                         coll = ((const FuncExpr *) expr)->inputcollid;
867                         break;
868                 case T_OpExpr:
869                         coll = ((const OpExpr *) expr)->inputcollid;
870                         break;
871                 case T_DistinctExpr:
872                         coll = ((const DistinctExpr *) expr)->inputcollid;
873                         break;
874                 case T_NullIfExpr:
875                         coll = ((const NullIfExpr *) expr)->inputcollid;
876                         break;
877                 case T_ScalarArrayOpExpr:
878                         coll = ((const ScalarArrayOpExpr *) expr)->inputcollid;
879                         break;
880                 case T_MinMaxExpr:
881                         coll = ((const MinMaxExpr *) expr)->inputcollid;
882                         break;
883                 default:
884                         coll = InvalidOid;
885                         break;
886         }
887         return coll;
888 }
889
890 /*
891  *      exprSetCollation -
892  *        Assign collation information to an expression tree node.
893  *
894  * Note: since this is only used during parse analysis, we don't need to
895  * worry about subplans or PlaceHolderVars.
896  */
897 void
898 exprSetCollation(Node *expr, Oid collation)
899 {
900         switch (nodeTag(expr))
901         {
902                 case T_Var:
903                         ((Var *) expr)->varcollid = collation;
904                         break;
905                 case T_Const:
906                         ((Const *) expr)->constcollid = collation;
907                         break;
908                 case T_Param:
909                         ((Param *) expr)->paramcollid = collation;
910                         break;
911                 case T_Aggref:
912                         ((Aggref *) expr)->aggcollid = collation;
913                         break;
914                 case T_WindowFunc:
915                         ((WindowFunc *) expr)->wincollid = collation;
916                         break;
917                 case T_ArrayRef:
918                         ((ArrayRef *) expr)->refcollid = collation;
919                         break;
920                 case T_FuncExpr:
921                         ((FuncExpr *) expr)->funccollid = collation;
922                         break;
923                 case T_NamedArgExpr:
924                         Assert(collation == exprCollation((Node *) ((NamedArgExpr *) expr)->arg));
925                         break;
926                 case T_OpExpr:
927                         ((OpExpr *) expr)->opcollid = collation;
928                         break;
929                 case T_DistinctExpr:
930                         ((DistinctExpr *) expr)->opcollid = collation;
931                         break;
932                 case T_NullIfExpr:
933                         ((NullIfExpr *) expr)->opcollid = collation;
934                         break;
935                 case T_ScalarArrayOpExpr:
936                         Assert(!OidIsValid(collation));         /* result is always boolean */
937                         break;
938                 case T_BoolExpr:
939                         Assert(!OidIsValid(collation));         /* result is always boolean */
940                         break;
941                 case T_SubLink:
942 #ifdef USE_ASSERT_CHECKING
943                         {
944                                 SubLink    *sublink = (SubLink *) expr;
945
946                                 if (sublink->subLinkType == EXPR_SUBLINK ||
947                                         sublink->subLinkType == ARRAY_SUBLINK)
948                                 {
949                                         /* get the collation of subselect's first target column */
950                                         Query      *qtree = (Query *) sublink->subselect;
951                                         TargetEntry *tent;
952
953                                         if (!qtree || !IsA(qtree, Query))
954                                                 elog(ERROR, "cannot set collation for untransformed sublink");
955                                         tent = (TargetEntry *) linitial(qtree->targetList);
956                                         Assert(IsA(tent, TargetEntry));
957                                         Assert(!tent->resjunk);
958                                         Assert(collation == exprCollation((Node *) tent->expr));
959                                 }
960                                 else
961                                 {
962                                         /* for all other sublink types, result is boolean */
963                                         Assert(!OidIsValid(collation));
964                                 }
965                         }
966 #endif   /* USE_ASSERT_CHECKING */
967                         break;
968                 case T_FieldSelect:
969                         ((FieldSelect *) expr)->resultcollid = collation;
970                         break;
971                 case T_FieldStore:
972                         Assert(!OidIsValid(collation));         /* result is always composite */
973                         break;
974                 case T_RelabelType:
975                         ((RelabelType *) expr)->resultcollid = collation;
976                         break;
977                 case T_CoerceViaIO:
978                         ((CoerceViaIO *) expr)->resultcollid = collation;
979                         break;
980                 case T_ArrayCoerceExpr:
981                         ((ArrayCoerceExpr *) expr)->resultcollid = collation;
982                         break;
983                 case T_ConvertRowtypeExpr:
984                         Assert(!OidIsValid(collation));         /* result is always composite */
985                         break;
986                 case T_CaseExpr:
987                         ((CaseExpr *) expr)->casecollid = collation;
988                         break;
989                 case T_ArrayExpr:
990                         ((ArrayExpr *) expr)->array_collid = collation;
991                         break;
992                 case T_RowExpr:
993                         Assert(!OidIsValid(collation));         /* result is always composite */
994                         break;
995                 case T_RowCompareExpr:
996                         Assert(!OidIsValid(collation));         /* result is always boolean */
997                         break;
998                 case T_CoalesceExpr:
999                         ((CoalesceExpr *) expr)->coalescecollid = collation;
1000                         break;
1001                 case T_MinMaxExpr:
1002                         ((MinMaxExpr *) expr)->minmaxcollid = collation;
1003                         break;
1004                 case T_XmlExpr:
1005                         Assert((((XmlExpr *) expr)->op == IS_XMLSERIALIZE) ?
1006                                    (collation == DEFAULT_COLLATION_OID) :
1007                                    (collation == InvalidOid));
1008                         break;
1009                 case T_NullTest:
1010                         Assert(!OidIsValid(collation));         /* result is always boolean */
1011                         break;
1012                 case T_BooleanTest:
1013                         Assert(!OidIsValid(collation));         /* result is always boolean */
1014                         break;
1015                 case T_CoerceToDomain:
1016                         ((CoerceToDomain *) expr)->resultcollid = collation;
1017                         break;
1018                 case T_CoerceToDomainValue:
1019                         ((CoerceToDomainValue *) expr)->collation = collation;
1020                         break;
1021                 case T_SetToDefault:
1022                         ((SetToDefault *) expr)->collation = collation;
1023                         break;
1024                 case T_CurrentOfExpr:
1025                         Assert(!OidIsValid(collation));         /* result is always boolean */
1026                         break;
1027                 default:
1028                         elog(ERROR, "unrecognized node type: %d", (int) nodeTag(expr));
1029                         break;
1030         }
1031 }
1032
1033 /*
1034  *      exprSetInputCollation -
1035  *        Assign input-collation information to an expression tree node.
1036  *
1037  * This is a no-op for node types that don't store their input collation.
1038  * Note we omit RowCompareExpr, which needs special treatment since it
1039  * contains multiple input collation OIDs.
1040  */
1041 void
1042 exprSetInputCollation(Node *expr, Oid inputcollation)
1043 {
1044         switch (nodeTag(expr))
1045         {
1046                 case T_Aggref:
1047                         ((Aggref *) expr)->inputcollid = inputcollation;
1048                         break;
1049                 case T_WindowFunc:
1050                         ((WindowFunc *) expr)->inputcollid = inputcollation;
1051                         break;
1052                 case T_FuncExpr:
1053                         ((FuncExpr *) expr)->inputcollid = inputcollation;
1054                         break;
1055                 case T_OpExpr:
1056                         ((OpExpr *) expr)->inputcollid = inputcollation;
1057                         break;
1058                 case T_DistinctExpr:
1059                         ((DistinctExpr *) expr)->inputcollid = inputcollation;
1060                         break;
1061                 case T_NullIfExpr:
1062                         ((NullIfExpr *) expr)->inputcollid = inputcollation;
1063                         break;
1064                 case T_ScalarArrayOpExpr:
1065                         ((ScalarArrayOpExpr *) expr)->inputcollid = inputcollation;
1066                         break;
1067                 case T_MinMaxExpr:
1068                         ((MinMaxExpr *) expr)->inputcollid = inputcollation;
1069                         break;
1070                 default:
1071                         break;
1072         }
1073 }
1074
1075
1076 /*
1077  *      exprLocation -
1078  *        returns the parse location of an expression tree, for error reports
1079  *
1080  * -1 is returned if the location can't be determined.
1081  *
1082  * For expressions larger than a single token, the intent here is to
1083  * return the location of the expression's leftmost token, not necessarily
1084  * the topmost Node's location field.  For example, an OpExpr's location
1085  * field will point at the operator name, but if it is not a prefix operator
1086  * then we should return the location of the left-hand operand instead.
1087  * The reason is that we want to reference the entire expression not just
1088  * that operator, and pointing to its start seems to be the most natural way.
1089  *
1090  * The location is not perfect --- for example, since the grammar doesn't
1091  * explicitly represent parentheses in the parsetree, given something that
1092  * had been written "(a + b) * c" we are going to point at "a" not "(".
1093  * But it should be plenty good enough for error reporting purposes.
1094  *
1095  * You might think that this code is overly general, for instance why check
1096  * the operands of a FuncExpr node, when the function name can be expected
1097  * to be to the left of them?  There are a couple of reasons.  The grammar
1098  * sometimes builds expressions that aren't quite what the user wrote;
1099  * for instance x IS NOT BETWEEN ... becomes a NOT-expression whose keyword
1100  * pointer is to the right of its leftmost argument.  Also, nodes that were
1101  * inserted implicitly by parse analysis (such as FuncExprs for implicit
1102  * coercions) will have location -1, and so we can have odd combinations of
1103  * known and unknown locations in a tree.
1104  */
1105 int
1106 exprLocation(const Node *expr)
1107 {
1108         int                     loc;
1109
1110         if (expr == NULL)
1111                 return -1;
1112         switch (nodeTag(expr))
1113         {
1114                 case T_RangeVar:
1115                         loc = ((const RangeVar *) expr)->location;
1116                         break;
1117                 case T_Var:
1118                         loc = ((const Var *) expr)->location;
1119                         break;
1120                 case T_Const:
1121                         loc = ((const Const *) expr)->location;
1122                         break;
1123                 case T_Param:
1124                         loc = ((const Param *) expr)->location;
1125                         break;
1126                 case T_Aggref:
1127                         /* function name should always be the first thing */
1128                         loc = ((const Aggref *) expr)->location;
1129                         break;
1130                 case T_WindowFunc:
1131                         /* function name should always be the first thing */
1132                         loc = ((const WindowFunc *) expr)->location;
1133                         break;
1134                 case T_ArrayRef:
1135                         /* just use array argument's location */
1136                         loc = exprLocation((Node *) ((const ArrayRef *) expr)->refexpr);
1137                         break;
1138                 case T_FuncExpr:
1139                         {
1140                                 const FuncExpr   *fexpr = (const FuncExpr *) expr;
1141
1142                                 /* consider both function name and leftmost arg */
1143                                 loc = leftmostLoc(fexpr->location,
1144                                                                   exprLocation((Node *) fexpr->args));
1145                         }
1146                         break;
1147                 case T_NamedArgExpr:
1148                         {
1149                                 const NamedArgExpr *na = (const NamedArgExpr *) expr;
1150
1151                                 /* consider both argument name and value */
1152                                 loc = leftmostLoc(na->location,
1153                                                                   exprLocation((Node *) na->arg));
1154                         }
1155                         break;
1156                 case T_OpExpr:
1157                 case T_DistinctExpr:    /* struct-equivalent to OpExpr */
1158                 case T_NullIfExpr:              /* struct-equivalent to OpExpr */
1159                         {
1160                                 const OpExpr       *opexpr = (const OpExpr *) expr;
1161
1162                                 /* consider both operator name and leftmost arg */
1163                                 loc = leftmostLoc(opexpr->location,
1164                                                                   exprLocation((Node *) opexpr->args));
1165                         }
1166                         break;
1167                 case T_ScalarArrayOpExpr:
1168                         {
1169                                 const ScalarArrayOpExpr *saopexpr = (const ScalarArrayOpExpr *) expr;
1170
1171                                 /* consider both operator name and leftmost arg */
1172                                 loc = leftmostLoc(saopexpr->location,
1173                                                                   exprLocation((Node *) saopexpr->args));
1174                         }
1175                         break;
1176                 case T_BoolExpr:
1177                         {
1178                                 const BoolExpr   *bexpr = (const BoolExpr *) expr;
1179
1180                                 /*
1181                                  * Same as above, to handle either NOT or AND/OR.  We can't
1182                                  * special-case NOT because of the way that it's used for
1183                                  * things like IS NOT BETWEEN.
1184                                  */
1185                                 loc = leftmostLoc(bexpr->location,
1186                                                                   exprLocation((Node *) bexpr->args));
1187                         }
1188                         break;
1189                 case T_SubLink:
1190                         {
1191                                 const SubLink    *sublink = (const SubLink *) expr;
1192
1193                                 /* check the testexpr, if any, and the operator/keyword */
1194                                 loc = leftmostLoc(exprLocation(sublink->testexpr),
1195                                                                   sublink->location);
1196                         }
1197                         break;
1198                 case T_FieldSelect:
1199                         /* just use argument's location */
1200                         loc = exprLocation((Node *) ((const FieldSelect *) expr)->arg);
1201                         break;
1202                 case T_FieldStore:
1203                         /* just use argument's location */
1204                         loc = exprLocation((Node *) ((const FieldStore *) expr)->arg);
1205                         break;
1206                 case T_RelabelType:
1207                         {
1208                                 const RelabelType *rexpr = (const RelabelType *) expr;
1209
1210                                 /* Much as above */
1211                                 loc = leftmostLoc(rexpr->location,
1212                                                                   exprLocation((Node *) rexpr->arg));
1213                         }
1214                         break;
1215                 case T_CoerceViaIO:
1216                         {
1217                                 const CoerceViaIO *cexpr = (const CoerceViaIO *) expr;
1218
1219                                 /* Much as above */
1220                                 loc = leftmostLoc(cexpr->location,
1221                                                                   exprLocation((Node *) cexpr->arg));
1222                         }
1223                         break;
1224                 case T_ArrayCoerceExpr:
1225                         {
1226                                 const ArrayCoerceExpr *cexpr = (const ArrayCoerceExpr *) expr;
1227
1228                                 /* Much as above */
1229                                 loc = leftmostLoc(cexpr->location,
1230                                                                   exprLocation((Node *) cexpr->arg));
1231                         }
1232                         break;
1233                 case T_ConvertRowtypeExpr:
1234                         {
1235                                 const ConvertRowtypeExpr *cexpr = (const ConvertRowtypeExpr *) expr;
1236
1237                                 /* Much as above */
1238                                 loc = leftmostLoc(cexpr->location,
1239                                                                   exprLocation((Node *) cexpr->arg));
1240                         }
1241                         break;
1242                 case T_CollateExpr:
1243                         /* just use argument's location */
1244                         loc = exprLocation((Node *) ((const CollateExpr *) expr)->arg);
1245                         break;
1246                 case T_CaseExpr:
1247                         /* CASE keyword should always be the first thing */
1248                         loc = ((const CaseExpr *) expr)->location;
1249                         break;
1250                 case T_CaseWhen:
1251                         /* WHEN keyword should always be the first thing */
1252                         loc = ((const CaseWhen *) expr)->location;
1253                         break;
1254                 case T_ArrayExpr:
1255                         /* the location points at ARRAY or [, which must be leftmost */
1256                         loc = ((const ArrayExpr *) expr)->location;
1257                         break;
1258                 case T_RowExpr:
1259                         /* the location points at ROW or (, which must be leftmost */
1260                         loc = ((const RowExpr *) expr)->location;
1261                         break;
1262                 case T_RowCompareExpr:
1263                         /* just use leftmost argument's location */
1264                         loc = exprLocation((Node *) ((const RowCompareExpr *) expr)->largs);
1265                         break;
1266                 case T_CoalesceExpr:
1267                         /* COALESCE keyword should always be the first thing */
1268                         loc = ((const CoalesceExpr *) expr)->location;
1269                         break;
1270                 case T_MinMaxExpr:
1271                         /* GREATEST/LEAST keyword should always be the first thing */
1272                         loc = ((const MinMaxExpr *) expr)->location;
1273                         break;
1274                 case T_XmlExpr:
1275                         {
1276                                 const XmlExpr    *xexpr = (const XmlExpr *) expr;
1277
1278                                 /* consider both function name and leftmost arg */
1279                                 loc = leftmostLoc(xexpr->location,
1280                                                                   exprLocation((Node *) xexpr->args));
1281                         }
1282                         break;
1283                 case T_NullTest:
1284                         /* just use argument's location */
1285                         loc = exprLocation((Node *) ((const NullTest *) expr)->arg);
1286                         break;
1287                 case T_BooleanTest:
1288                         /* just use argument's location */
1289                         loc = exprLocation((Node *) ((const BooleanTest *) expr)->arg);
1290                         break;
1291                 case T_CoerceToDomain:
1292                         {
1293                                 const CoerceToDomain *cexpr = (const CoerceToDomain *) expr;
1294
1295                                 /* Much as above */
1296                                 loc = leftmostLoc(cexpr->location,
1297                                                                   exprLocation((Node *) cexpr->arg));
1298                         }
1299                         break;
1300                 case T_CoerceToDomainValue:
1301                         loc = ((const CoerceToDomainValue *) expr)->location;
1302                         break;
1303                 case T_SetToDefault:
1304                         loc = ((const SetToDefault *) expr)->location;
1305                         break;
1306                 case T_TargetEntry:
1307                         /* just use argument's location */
1308                         loc = exprLocation((Node *) ((const TargetEntry *) expr)->expr);
1309                         break;
1310                 case T_IntoClause:
1311                         /* use the contained RangeVar's location --- close enough */
1312                         loc = exprLocation((Node *) ((const IntoClause *) expr)->rel);
1313                         break;
1314                 case T_List:
1315                         {
1316                                 /* report location of first list member that has a location */
1317                                 ListCell   *lc;
1318
1319                                 loc = -1;               /* just to suppress compiler warning */
1320                                 foreach(lc, (const List *) expr)
1321                                 {
1322                                         loc = exprLocation((Node *) lfirst(lc));
1323                                         if (loc >= 0)
1324                                                 break;
1325                                 }
1326                         }
1327                         break;
1328                 case T_A_Expr:
1329                         {
1330                                 const A_Expr       *aexpr = (const A_Expr *) expr;
1331
1332                                 /* use leftmost of operator or left operand (if any) */
1333                                 /* we assume right operand can't be to left of operator */
1334                                 loc = leftmostLoc(aexpr->location,
1335                                                                   exprLocation(aexpr->lexpr));
1336                         }
1337                         break;
1338                 case T_ColumnRef:
1339                         loc = ((const ColumnRef *) expr)->location;
1340                         break;
1341                 case T_ParamRef:
1342                         loc = ((const ParamRef *) expr)->location;
1343                         break;
1344                 case T_A_Const:
1345                         loc = ((const A_Const *) expr)->location;
1346                         break;
1347                 case T_FuncCall:
1348                         {
1349                                 const FuncCall   *fc = (const FuncCall *) expr;
1350
1351                                 /* consider both function name and leftmost arg */
1352                                 /* (we assume any ORDER BY nodes must be to right of name) */
1353                                 loc = leftmostLoc(fc->location,
1354                                                                   exprLocation((Node *) fc->args));
1355                         }
1356                         break;
1357                 case T_A_ArrayExpr:
1358                         /* the location points at ARRAY or [, which must be leftmost */
1359                         loc = ((const A_ArrayExpr *) expr)->location;
1360                         break;
1361                 case T_ResTarget:
1362                         /* we need not examine the contained expression (if any) */
1363                         loc = ((const ResTarget *) expr)->location;
1364                         break;
1365                 case T_TypeCast:
1366                         {
1367                                 const TypeCast   *tc = (const TypeCast *) expr;
1368
1369                                 /*
1370                                  * This could represent CAST(), ::, or TypeName 'literal', so
1371                                  * any of the components might be leftmost.
1372                                  */
1373                                 loc = exprLocation(tc->arg);
1374                                 loc = leftmostLoc(loc, tc->typeName->location);
1375                                 loc = leftmostLoc(loc, tc->location);
1376                         }
1377                         break;
1378                 case T_CollateClause:
1379                         /* just use argument's location */
1380                         loc = exprLocation(((const CollateClause *) expr)->arg);
1381                         break;
1382                 case T_SortBy:
1383                         /* just use argument's location (ignore operator, if any) */
1384                         loc = exprLocation(((const SortBy *) expr)->node);
1385                         break;
1386                 case T_WindowDef:
1387                         loc = ((const WindowDef *) expr)->location;
1388                         break;
1389                 case T_TypeName:
1390                         loc = ((const TypeName *) expr)->location;
1391                         break;
1392                 case T_Constraint:
1393                         loc = ((const Constraint *) expr)->location;
1394                         break;
1395                 case T_XmlSerialize:
1396                         /* XMLSERIALIZE keyword should always be the first thing */
1397                         loc = ((const XmlSerialize *) expr)->location;
1398                         break;
1399                 case T_WithClause:
1400                         loc = ((const WithClause *) expr)->location;
1401                         break;
1402                 case T_CommonTableExpr:
1403                         loc = ((const CommonTableExpr *) expr)->location;
1404                         break;
1405                 case T_PlaceHolderVar:
1406                         /* just use argument's location */
1407                         loc = exprLocation((Node *) ((const PlaceHolderVar *) expr)->phexpr);
1408                         break;
1409                 default:
1410                         /* for any other node type it's just unknown... */
1411                         loc = -1;
1412                         break;
1413         }
1414         return loc;
1415 }
1416
1417 /*
1418  * leftmostLoc - support for exprLocation
1419  *
1420  * Take the minimum of two parse location values, but ignore unknowns
1421  */
1422 static int
1423 leftmostLoc(int loc1, int loc2)
1424 {
1425         if (loc1 < 0)
1426                 return loc2;
1427         else if (loc2 < 0)
1428                 return loc1;
1429         else
1430                 return Min(loc1, loc2);
1431 }
1432
1433
1434 /*
1435  * Standard expression-tree walking support
1436  *
1437  * We used to have near-duplicate code in many different routines that
1438  * understood how to recurse through an expression node tree.  That was
1439  * a pain to maintain, and we frequently had bugs due to some particular
1440  * routine neglecting to support a particular node type.  In most cases,
1441  * these routines only actually care about certain node types, and don't
1442  * care about other types except insofar as they have to recurse through
1443  * non-primitive node types.  Therefore, we now provide generic tree-walking
1444  * logic to consolidate the redundant "boilerplate" code.  There are
1445  * two versions: expression_tree_walker() and expression_tree_mutator().
1446  */
1447
1448 /*
1449  * expression_tree_walker() is designed to support routines that traverse
1450  * a tree in a read-only fashion (although it will also work for routines
1451  * that modify nodes in-place but never add/delete/replace nodes).
1452  * A walker routine should look like this:
1453  *
1454  * bool my_walker (Node *node, my_struct *context)
1455  * {
1456  *              if (node == NULL)
1457  *                      return false;
1458  *              // check for nodes that special work is required for, eg:
1459  *              if (IsA(node, Var))
1460  *              {
1461  *                      ... do special actions for Var nodes
1462  *              }
1463  *              else if (IsA(node, ...))
1464  *              {
1465  *                      ... do special actions for other node types
1466  *              }
1467  *              // for any node type not specially processed, do:
1468  *              return expression_tree_walker(node, my_walker, (void *) context);
1469  * }
1470  *
1471  * The "context" argument points to a struct that holds whatever context
1472  * information the walker routine needs --- it can be used to return data
1473  * gathered by the walker, too.  This argument is not touched by
1474  * expression_tree_walker, but it is passed down to recursive sub-invocations
1475  * of my_walker.  The tree walk is started from a setup routine that
1476  * fills in the appropriate context struct, calls my_walker with the top-level
1477  * node of the tree, and then examines the results.
1478  *
1479  * The walker routine should return "false" to continue the tree walk, or
1480  * "true" to abort the walk and immediately return "true" to the top-level
1481  * caller.      This can be used to short-circuit the traversal if the walker
1482  * has found what it came for.  "false" is returned to the top-level caller
1483  * iff no invocation of the walker returned "true".
1484  *
1485  * The node types handled by expression_tree_walker include all those
1486  * normally found in target lists and qualifier clauses during the planning
1487  * stage.  In particular, it handles List nodes since a cnf-ified qual clause
1488  * will have List structure at the top level, and it handles TargetEntry nodes
1489  * so that a scan of a target list can be handled without additional code.
1490  * Also, RangeTblRef, FromExpr, JoinExpr, and SetOperationStmt nodes are
1491  * handled, so that query jointrees and setOperation trees can be processed
1492  * without additional code.
1493  *
1494  * expression_tree_walker will handle SubLink nodes by recursing normally
1495  * into the "testexpr" subtree (which is an expression belonging to the outer
1496  * plan).  It will also call the walker on the sub-Query node; however, when
1497  * expression_tree_walker itself is called on a Query node, it does nothing
1498  * and returns "false".  The net effect is that unless the walker does
1499  * something special at a Query node, sub-selects will not be visited during
1500  * an expression tree walk. This is exactly the behavior wanted in many cases
1501  * --- and for those walkers that do want to recurse into sub-selects, special
1502  * behavior is typically needed anyway at the entry to a sub-select (such as
1503  * incrementing a depth counter). A walker that wants to examine sub-selects
1504  * should include code along the lines of:
1505  *
1506  *              if (IsA(node, Query))
1507  *              {
1508  *                      adjust context for subquery;
1509  *                      result = query_tree_walker((Query *) node, my_walker, context,
1510  *                                                                         0); // adjust flags as needed
1511  *                      restore context if needed;
1512  *                      return result;
1513  *              }
1514  *
1515  * query_tree_walker is a convenience routine (see below) that calls the
1516  * walker on all the expression subtrees of the given Query node.
1517  *
1518  * expression_tree_walker will handle SubPlan nodes by recursing normally
1519  * into the "testexpr" and the "args" list (which are expressions belonging to
1520  * the outer plan).  It will not touch the completed subplan, however.  Since
1521  * there is no link to the original Query, it is not possible to recurse into
1522  * subselects of an already-planned expression tree.  This is OK for current
1523  * uses, but may need to be revisited in future.
1524  */
1525
1526 bool
1527 expression_tree_walker(Node *node,
1528                                            bool (*walker) (),
1529                                            void *context)
1530 {
1531         ListCell   *temp;
1532
1533         /*
1534          * The walker has already visited the current node, and so we need only
1535          * recurse into any sub-nodes it has.
1536          *
1537          * We assume that the walker is not interested in List nodes per se, so
1538          * when we expect a List we just recurse directly to self without
1539          * bothering to call the walker.
1540          */
1541         if (node == NULL)
1542                 return false;
1543
1544         /* Guard against stack overflow due to overly complex expressions */
1545         check_stack_depth();
1546
1547         switch (nodeTag(node))
1548         {
1549                 case T_Var:
1550                 case T_Const:
1551                 case T_Param:
1552                 case T_CoerceToDomainValue:
1553                 case T_CaseTestExpr:
1554                 case T_SetToDefault:
1555                 case T_CurrentOfExpr:
1556                 case T_RangeTblRef:
1557                 case T_SortGroupClause:
1558                         /* primitive node types with no expression subnodes */
1559                         break;
1560                 case T_Aggref:
1561                         {
1562                                 Aggref     *expr = (Aggref *) node;
1563
1564                                 /* recurse directly on List */
1565                                 if (expression_tree_walker((Node *) expr->args,
1566                                                                                    walker, context))
1567                                         return true;
1568                                 if (expression_tree_walker((Node *) expr->aggorder,
1569                                                                                    walker, context))
1570                                         return true;
1571                                 if (expression_tree_walker((Node *) expr->aggdistinct,
1572                                                                                    walker, context))
1573                                         return true;
1574                         }
1575                         break;
1576                 case T_WindowFunc:
1577                         {
1578                                 WindowFunc *expr = (WindowFunc *) node;
1579
1580                                 /* recurse directly on List */
1581                                 if (expression_tree_walker((Node *) expr->args,
1582                                                                                    walker, context))
1583                                         return true;
1584                         }
1585                         break;
1586                 case T_ArrayRef:
1587                         {
1588                                 ArrayRef   *aref = (ArrayRef *) node;
1589
1590                                 /* recurse directly for upper/lower array index lists */
1591                                 if (expression_tree_walker((Node *) aref->refupperindexpr,
1592                                                                                    walker, context))
1593                                         return true;
1594                                 if (expression_tree_walker((Node *) aref->reflowerindexpr,
1595                                                                                    walker, context))
1596                                         return true;
1597                                 /* walker must see the refexpr and refassgnexpr, however */
1598                                 if (walker(aref->refexpr, context))
1599                                         return true;
1600                                 if (walker(aref->refassgnexpr, context))
1601                                         return true;
1602                         }
1603                         break;
1604                 case T_FuncExpr:
1605                         {
1606                                 FuncExpr   *expr = (FuncExpr *) node;
1607
1608                                 if (expression_tree_walker((Node *) expr->args,
1609                                                                                    walker, context))
1610                                         return true;
1611                         }
1612                         break;
1613                 case T_NamedArgExpr:
1614                         return walker(((NamedArgExpr *) node)->arg, context);
1615                 case T_OpExpr:
1616                 case T_DistinctExpr:    /* struct-equivalent to OpExpr */
1617                 case T_NullIfExpr:              /* struct-equivalent to OpExpr */
1618                         {
1619                                 OpExpr     *expr = (OpExpr *) node;
1620
1621                                 if (expression_tree_walker((Node *) expr->args,
1622                                                                                    walker, context))
1623                                         return true;
1624                         }
1625                         break;
1626                 case T_ScalarArrayOpExpr:
1627                         {
1628                                 ScalarArrayOpExpr *expr = (ScalarArrayOpExpr *) node;
1629
1630                                 if (expression_tree_walker((Node *) expr->args,
1631                                                                                    walker, context))
1632                                         return true;
1633                         }
1634                         break;
1635                 case T_BoolExpr:
1636                         {
1637                                 BoolExpr   *expr = (BoolExpr *) node;
1638
1639                                 if (expression_tree_walker((Node *) expr->args,
1640                                                                                    walker, context))
1641                                         return true;
1642                         }
1643                         break;
1644                 case T_SubLink:
1645                         {
1646                                 SubLink    *sublink = (SubLink *) node;
1647
1648                                 if (walker(sublink->testexpr, context))
1649                                         return true;
1650
1651                                 /*
1652                                  * Also invoke the walker on the sublink's Query node, so it
1653                                  * can recurse into the sub-query if it wants to.
1654                                  */
1655                                 return walker(sublink->subselect, context);
1656                         }
1657                         break;
1658                 case T_SubPlan:
1659                         {
1660                                 SubPlan    *subplan = (SubPlan *) node;
1661
1662                                 /* recurse into the testexpr, but not into the Plan */
1663                                 if (walker(subplan->testexpr, context))
1664                                         return true;
1665                                 /* also examine args list */
1666                                 if (expression_tree_walker((Node *) subplan->args,
1667                                                                                    walker, context))
1668                                         return true;
1669                         }
1670                         break;
1671                 case T_AlternativeSubPlan:
1672                         return walker(((AlternativeSubPlan *) node)->subplans, context);
1673                 case T_FieldSelect:
1674                         return walker(((FieldSelect *) node)->arg, context);
1675                 case T_FieldStore:
1676                         {
1677                                 FieldStore *fstore = (FieldStore *) node;
1678
1679                                 if (walker(fstore->arg, context))
1680                                         return true;
1681                                 if (walker(fstore->newvals, context))
1682                                         return true;
1683                         }
1684                         break;
1685                 case T_RelabelType:
1686                         return walker(((RelabelType *) node)->arg, context);
1687                 case T_CoerceViaIO:
1688                         return walker(((CoerceViaIO *) node)->arg, context);
1689                 case T_ArrayCoerceExpr:
1690                         return walker(((ArrayCoerceExpr *) node)->arg, context);
1691                 case T_ConvertRowtypeExpr:
1692                         return walker(((ConvertRowtypeExpr *) node)->arg, context);
1693                 case T_CollateExpr:
1694                         return walker(((CollateExpr *) node)->arg, context);
1695                 case T_CaseExpr:
1696                         {
1697                                 CaseExpr   *caseexpr = (CaseExpr *) node;
1698
1699                                 if (walker(caseexpr->arg, context))
1700                                         return true;
1701                                 /* we assume walker doesn't care about CaseWhens, either */
1702                                 foreach(temp, caseexpr->args)
1703                                 {
1704                                         CaseWhen   *when = (CaseWhen *) lfirst(temp);
1705
1706                                         Assert(IsA(when, CaseWhen));
1707                                         if (walker(when->expr, context))
1708                                                 return true;
1709                                         if (walker(when->result, context))
1710                                                 return true;
1711                                 }
1712                                 if (walker(caseexpr->defresult, context))
1713                                         return true;
1714                         }
1715                         break;
1716                 case T_ArrayExpr:
1717                         return walker(((ArrayExpr *) node)->elements, context);
1718                 case T_RowExpr:
1719                         /* Assume colnames isn't interesting */
1720                         return walker(((RowExpr *) node)->args, context);
1721                 case T_RowCompareExpr:
1722                         {
1723                                 RowCompareExpr *rcexpr = (RowCompareExpr *) node;
1724
1725                                 if (walker(rcexpr->largs, context))
1726                                         return true;
1727                                 if (walker(rcexpr->rargs, context))
1728                                         return true;
1729                         }
1730                         break;
1731                 case T_CoalesceExpr:
1732                         return walker(((CoalesceExpr *) node)->args, context);
1733                 case T_MinMaxExpr:
1734                         return walker(((MinMaxExpr *) node)->args, context);
1735                 case T_XmlExpr:
1736                         {
1737                                 XmlExpr    *xexpr = (XmlExpr *) node;
1738
1739                                 if (walker(xexpr->named_args, context))
1740                                         return true;
1741                                 /* we assume walker doesn't care about arg_names */
1742                                 if (walker(xexpr->args, context))
1743                                         return true;
1744                         }
1745                         break;
1746                 case T_NullTest:
1747                         return walker(((NullTest *) node)->arg, context);
1748                 case T_BooleanTest:
1749                         return walker(((BooleanTest *) node)->arg, context);
1750                 case T_CoerceToDomain:
1751                         return walker(((CoerceToDomain *) node)->arg, context);
1752                 case T_TargetEntry:
1753                         return walker(((TargetEntry *) node)->expr, context);
1754                 case T_Query:
1755                         /* Do nothing with a sub-Query, per discussion above */
1756                         break;
1757                 case T_WindowClause:
1758                         {
1759                                 WindowClause *wc = (WindowClause *) node;
1760
1761                                 if (walker(wc->partitionClause, context))
1762                                         return true;
1763                                 if (walker(wc->orderClause, context))
1764                                         return true;
1765                                 if (walker(wc->startOffset, context))
1766                                         return true;
1767                                 if (walker(wc->endOffset, context))
1768                                         return true;
1769                         }
1770                         break;
1771                 case T_CommonTableExpr:
1772                         {
1773                                 CommonTableExpr *cte = (CommonTableExpr *) node;
1774
1775                                 /*
1776                                  * Invoke the walker on the CTE's Query node, so it can
1777                                  * recurse into the sub-query if it wants to.
1778                                  */
1779                                 return walker(cte->ctequery, context);
1780                         }
1781                         break;
1782                 case T_List:
1783                         foreach(temp, (List *) node)
1784                         {
1785                                 if (walker((Node *) lfirst(temp), context))
1786                                         return true;
1787                         }
1788                         break;
1789                 case T_FromExpr:
1790                         {
1791                                 FromExpr   *from = (FromExpr *) node;
1792
1793                                 if (walker(from->fromlist, context))
1794                                         return true;
1795                                 if (walker(from->quals, context))
1796                                         return true;
1797                         }
1798                         break;
1799                 case T_JoinExpr:
1800                         {
1801                                 JoinExpr   *join = (JoinExpr *) node;
1802
1803                                 if (walker(join->larg, context))
1804                                         return true;
1805                                 if (walker(join->rarg, context))
1806                                         return true;
1807                                 if (walker(join->quals, context))
1808                                         return true;
1809
1810                                 /*
1811                                  * alias clause, using list are deemed uninteresting.
1812                                  */
1813                         }
1814                         break;
1815                 case T_SetOperationStmt:
1816                         {
1817                                 SetOperationStmt *setop = (SetOperationStmt *) node;
1818
1819                                 if (walker(setop->larg, context))
1820                                         return true;
1821                                 if (walker(setop->rarg, context))
1822                                         return true;
1823
1824                                 /* groupClauses are deemed uninteresting */
1825                         }
1826                         break;
1827                 case T_PlaceHolderVar:
1828                         return walker(((PlaceHolderVar *) node)->phexpr, context);
1829                 case T_AppendRelInfo:
1830                         {
1831                                 AppendRelInfo *appinfo = (AppendRelInfo *) node;
1832
1833                                 if (expression_tree_walker((Node *) appinfo->translated_vars,
1834                                                                                    walker, context))
1835                                         return true;
1836                         }
1837                         break;
1838                 case T_PlaceHolderInfo:
1839                         return walker(((PlaceHolderInfo *) node)->ph_var, context);
1840                 default:
1841                         elog(ERROR, "unrecognized node type: %d",
1842                                  (int) nodeTag(node));
1843                         break;
1844         }
1845         return false;
1846 }
1847
1848 /*
1849  * query_tree_walker --- initiate a walk of a Query's expressions
1850  *
1851  * This routine exists just to reduce the number of places that need to know
1852  * where all the expression subtrees of a Query are.  Note it can be used
1853  * for starting a walk at top level of a Query regardless of whether the
1854  * walker intends to descend into subqueries.  It is also useful for
1855  * descending into subqueries within a walker.
1856  *
1857  * Some callers want to suppress visitation of certain items in the sub-Query,
1858  * typically because they need to process them specially, or don't actually
1859  * want to recurse into subqueries.  This is supported by the flags argument,
1860  * which is the bitwise OR of flag values to suppress visitation of
1861  * indicated items.  (More flag bits may be added as needed.)
1862  */
1863 bool
1864 query_tree_walker(Query *query,
1865                                   bool (*walker) (),
1866                                   void *context,
1867                                   int flags)
1868 {
1869         Assert(query != NULL && IsA(query, Query));
1870
1871         if (walker((Node *) query->targetList, context))
1872                 return true;
1873         if (walker((Node *) query->returningList, context))
1874                 return true;
1875         if (walker((Node *) query->jointree, context))
1876                 return true;
1877         if (walker(query->setOperations, context))
1878                 return true;
1879         if (walker(query->havingQual, context))
1880                 return true;
1881         if (walker(query->limitOffset, context))
1882                 return true;
1883         if (walker(query->limitCount, context))
1884                 return true;
1885         if (!(flags & QTW_IGNORE_CTE_SUBQUERIES))
1886         {
1887                 if (walker((Node *) query->cteList, context))
1888                         return true;
1889         }
1890         if (!(flags & QTW_IGNORE_RANGE_TABLE))
1891         {
1892                 if (range_table_walker(query->rtable, walker, context, flags))
1893                         return true;
1894         }
1895         return false;
1896 }
1897
1898 /*
1899  * range_table_walker is just the part of query_tree_walker that scans
1900  * a query's rangetable.  This is split out since it can be useful on
1901  * its own.
1902  */
1903 bool
1904 range_table_walker(List *rtable,
1905                                    bool (*walker) (),
1906                                    void *context,
1907                                    int flags)
1908 {
1909         ListCell   *rt;
1910
1911         foreach(rt, rtable)
1912         {
1913                 RangeTblEntry *rte = (RangeTblEntry *) lfirst(rt);
1914
1915                 /* For historical reasons, visiting RTEs is not the default */
1916                 if (flags & QTW_EXAMINE_RTES)
1917                         if (walker(rte, context))
1918                                 return true;
1919
1920                 switch (rte->rtekind)
1921                 {
1922                         case RTE_RELATION:
1923                         case RTE_CTE:
1924                                 /* nothing to do */
1925                                 break;
1926                         case RTE_SUBQUERY:
1927                                 if (!(flags & QTW_IGNORE_RT_SUBQUERIES))
1928                                         if (walker(rte->subquery, context))
1929                                                 return true;
1930                                 break;
1931                         case RTE_JOIN:
1932                                 if (!(flags & QTW_IGNORE_JOINALIASES))
1933                                         if (walker(rte->joinaliasvars, context))
1934                                                 return true;
1935                                 break;
1936                         case RTE_FUNCTION:
1937                                 if (walker(rte->funcexpr, context))
1938                                         return true;
1939                                 break;
1940                         case RTE_VALUES:
1941                                 if (walker(rte->values_lists, context))
1942                                         return true;
1943                                 break;
1944                 }
1945         }
1946         return false;
1947 }
1948
1949
1950 /*
1951  * expression_tree_mutator() is designed to support routines that make a
1952  * modified copy of an expression tree, with some nodes being added,
1953  * removed, or replaced by new subtrees.  The original tree is (normally)
1954  * not changed.  Each recursion level is responsible for returning a copy of
1955  * (or appropriately modified substitute for) the subtree it is handed.
1956  * A mutator routine should look like this:
1957  *
1958  * Node * my_mutator (Node *node, my_struct *context)
1959  * {
1960  *              if (node == NULL)
1961  *                      return NULL;
1962  *              // check for nodes that special work is required for, eg:
1963  *              if (IsA(node, Var))
1964  *              {
1965  *                      ... create and return modified copy of Var node
1966  *              }
1967  *              else if (IsA(node, ...))
1968  *              {
1969  *                      ... do special transformations of other node types
1970  *              }
1971  *              // for any node type not specially processed, do:
1972  *              return expression_tree_mutator(node, my_mutator, (void *) context);
1973  * }
1974  *
1975  * The "context" argument points to a struct that holds whatever context
1976  * information the mutator routine needs --- it can be used to return extra
1977  * data gathered by the mutator, too.  This argument is not touched by
1978  * expression_tree_mutator, but it is passed down to recursive sub-invocations
1979  * of my_mutator.  The tree walk is started from a setup routine that
1980  * fills in the appropriate context struct, calls my_mutator with the
1981  * top-level node of the tree, and does any required post-processing.
1982  *
1983  * Each level of recursion must return an appropriately modified Node.
1984  * If expression_tree_mutator() is called, it will make an exact copy
1985  * of the given Node, but invoke my_mutator() to copy the sub-node(s)
1986  * of that Node.  In this way, my_mutator() has full control over the
1987  * copying process but need not directly deal with expression trees
1988  * that it has no interest in.
1989  *
1990  * Just as for expression_tree_walker, the node types handled by
1991  * expression_tree_mutator include all those normally found in target lists
1992  * and qualifier clauses during the planning stage.
1993  *
1994  * expression_tree_mutator will handle SubLink nodes by recursing normally
1995  * into the "testexpr" subtree (which is an expression belonging to the outer
1996  * plan).  It will also call the mutator on the sub-Query node; however, when
1997  * expression_tree_mutator itself is called on a Query node, it does nothing
1998  * and returns the unmodified Query node.  The net effect is that unless the
1999  * mutator does something special at a Query node, sub-selects will not be
2000  * visited or modified; the original sub-select will be linked to by the new
2001  * SubLink node.  Mutators that want to descend into sub-selects will usually
2002  * do so by recognizing Query nodes and calling query_tree_mutator (below).
2003  *
2004  * expression_tree_mutator will handle a SubPlan node by recursing into the
2005  * "testexpr" and the "args" list (which belong to the outer plan), but it
2006  * will simply copy the link to the inner plan, since that's typically what
2007  * expression tree mutators want.  A mutator that wants to modify the subplan
2008  * can force appropriate behavior by recognizing SubPlan expression nodes
2009  * and doing the right thing.
2010  */
2011
2012 Node *
2013 expression_tree_mutator(Node *node,
2014                                                 Node *(*mutator) (),
2015                                                 void *context)
2016 {
2017         /*
2018          * The mutator has already decided not to modify the current node, but we
2019          * must call the mutator for any sub-nodes.
2020          */
2021
2022 #define FLATCOPY(newnode, node, nodetype)  \
2023         ( (newnode) = (nodetype *) palloc(sizeof(nodetype)), \
2024           memcpy((newnode), (node), sizeof(nodetype)) )
2025
2026 #define CHECKFLATCOPY(newnode, node, nodetype)  \
2027         ( AssertMacro(IsA((node), nodetype)), \
2028           (newnode) = (nodetype *) palloc(sizeof(nodetype)), \
2029           memcpy((newnode), (node), sizeof(nodetype)) )
2030
2031 #define MUTATE(newfield, oldfield, fieldtype)  \
2032                 ( (newfield) = (fieldtype) mutator((Node *) (oldfield), context) )
2033
2034         if (node == NULL)
2035                 return NULL;
2036
2037         /* Guard against stack overflow due to overly complex expressions */
2038         check_stack_depth();
2039
2040         switch (nodeTag(node))
2041         {
2042                         /*
2043                          * Primitive node types with no expression subnodes.  Var and
2044                          * Const are frequent enough to deserve special cases, the others
2045                          * we just use copyObject for.
2046                          */
2047                 case T_Var:
2048                         {
2049                                 Var                *var = (Var *) node;
2050                                 Var                *newnode;
2051
2052                                 FLATCOPY(newnode, var, Var);
2053                                 return (Node *) newnode;
2054                         }
2055                         break;
2056                 case T_Const:
2057                         {
2058                                 Const      *oldnode = (Const *) node;
2059                                 Const      *newnode;
2060
2061                                 FLATCOPY(newnode, oldnode, Const);
2062                                 /* XXX we don't bother with datumCopy; should we? */
2063                                 return (Node *) newnode;
2064                         }
2065                         break;
2066                 case T_Param:
2067                 case T_CoerceToDomainValue:
2068                 case T_CaseTestExpr:
2069                 case T_SetToDefault:
2070                 case T_CurrentOfExpr:
2071                 case T_RangeTblRef:
2072                 case T_SortGroupClause:
2073                         return (Node *) copyObject(node);
2074                 case T_Aggref:
2075                         {
2076                                 Aggref     *aggref = (Aggref *) node;
2077                                 Aggref     *newnode;
2078
2079                                 FLATCOPY(newnode, aggref, Aggref);
2080                                 MUTATE(newnode->args, aggref->args, List *);
2081                                 MUTATE(newnode->aggorder, aggref->aggorder, List *);
2082                                 MUTATE(newnode->aggdistinct, aggref->aggdistinct, List *);
2083                                 return (Node *) newnode;
2084                         }
2085                         break;
2086                 case T_WindowFunc:
2087                         {
2088                                 WindowFunc *wfunc = (WindowFunc *) node;
2089                                 WindowFunc *newnode;
2090
2091                                 FLATCOPY(newnode, wfunc, WindowFunc);
2092                                 MUTATE(newnode->args, wfunc->args, List *);
2093                                 return (Node *) newnode;
2094                         }
2095                         break;
2096                 case T_ArrayRef:
2097                         {
2098                                 ArrayRef   *arrayref = (ArrayRef *) node;
2099                                 ArrayRef   *newnode;
2100
2101                                 FLATCOPY(newnode, arrayref, ArrayRef);
2102                                 MUTATE(newnode->refupperindexpr, arrayref->refupperindexpr,
2103                                            List *);
2104                                 MUTATE(newnode->reflowerindexpr, arrayref->reflowerindexpr,
2105                                            List *);
2106                                 MUTATE(newnode->refexpr, arrayref->refexpr,
2107                                            Expr *);
2108                                 MUTATE(newnode->refassgnexpr, arrayref->refassgnexpr,
2109                                            Expr *);
2110                                 return (Node *) newnode;
2111                         }
2112                         break;
2113                 case T_FuncExpr:
2114                         {
2115                                 FuncExpr   *expr = (FuncExpr *) node;
2116                                 FuncExpr   *newnode;
2117
2118                                 FLATCOPY(newnode, expr, FuncExpr);
2119                                 MUTATE(newnode->args, expr->args, List *);
2120                                 return (Node *) newnode;
2121                         }
2122                         break;
2123                 case T_NamedArgExpr:
2124                         {
2125                                 NamedArgExpr *nexpr = (NamedArgExpr *) node;
2126                                 NamedArgExpr *newnode;
2127
2128                                 FLATCOPY(newnode, nexpr, NamedArgExpr);
2129                                 MUTATE(newnode->arg, nexpr->arg, Expr *);
2130                                 return (Node *) newnode;
2131                         }
2132                         break;
2133                 case T_OpExpr:
2134                         {
2135                                 OpExpr     *expr = (OpExpr *) node;
2136                                 OpExpr     *newnode;
2137
2138                                 FLATCOPY(newnode, expr, OpExpr);
2139                                 MUTATE(newnode->args, expr->args, List *);
2140                                 return (Node *) newnode;
2141                         }
2142                         break;
2143                 case T_DistinctExpr:
2144                         {
2145                                 DistinctExpr *expr = (DistinctExpr *) node;
2146                                 DistinctExpr *newnode;
2147
2148                                 FLATCOPY(newnode, expr, DistinctExpr);
2149                                 MUTATE(newnode->args, expr->args, List *);
2150                                 return (Node *) newnode;
2151                         }
2152                         break;
2153                 case T_NullIfExpr:
2154                         {
2155                                 NullIfExpr *expr = (NullIfExpr *) node;
2156                                 NullIfExpr *newnode;
2157
2158                                 FLATCOPY(newnode, expr, NullIfExpr);
2159                                 MUTATE(newnode->args, expr->args, List *);
2160                                 return (Node *) newnode;
2161                         }
2162                         break;
2163                 case T_ScalarArrayOpExpr:
2164                         {
2165                                 ScalarArrayOpExpr *expr = (ScalarArrayOpExpr *) node;
2166                                 ScalarArrayOpExpr *newnode;
2167
2168                                 FLATCOPY(newnode, expr, ScalarArrayOpExpr);
2169                                 MUTATE(newnode->args, expr->args, List *);
2170                                 return (Node *) newnode;
2171                         }
2172                         break;
2173                 case T_BoolExpr:
2174                         {
2175                                 BoolExpr   *expr = (BoolExpr *) node;
2176                                 BoolExpr   *newnode;
2177
2178                                 FLATCOPY(newnode, expr, BoolExpr);
2179                                 MUTATE(newnode->args, expr->args, List *);
2180                                 return (Node *) newnode;
2181                         }
2182                         break;
2183                 case T_SubLink:
2184                         {
2185                                 SubLink    *sublink = (SubLink *) node;
2186                                 SubLink    *newnode;
2187
2188                                 FLATCOPY(newnode, sublink, SubLink);
2189                                 MUTATE(newnode->testexpr, sublink->testexpr, Node *);
2190
2191                                 /*
2192                                  * Also invoke the mutator on the sublink's Query node, so it
2193                                  * can recurse into the sub-query if it wants to.
2194                                  */
2195                                 MUTATE(newnode->subselect, sublink->subselect, Node *);
2196                                 return (Node *) newnode;
2197                         }
2198                         break;
2199                 case T_SubPlan:
2200                         {
2201                                 SubPlan    *subplan = (SubPlan *) node;
2202                                 SubPlan    *newnode;
2203
2204                                 FLATCOPY(newnode, subplan, SubPlan);
2205                                 /* transform testexpr */
2206                                 MUTATE(newnode->testexpr, subplan->testexpr, Node *);
2207                                 /* transform args list (params to be passed to subplan) */
2208                                 MUTATE(newnode->args, subplan->args, List *);
2209                                 /* but not the sub-Plan itself, which is referenced as-is */
2210                                 return (Node *) newnode;
2211                         }
2212                         break;
2213                 case T_AlternativeSubPlan:
2214                         {
2215                                 AlternativeSubPlan *asplan = (AlternativeSubPlan *) node;
2216                                 AlternativeSubPlan *newnode;
2217
2218                                 FLATCOPY(newnode, asplan, AlternativeSubPlan);
2219                                 MUTATE(newnode->subplans, asplan->subplans, List *);
2220                                 return (Node *) newnode;
2221                         }
2222                         break;
2223                 case T_FieldSelect:
2224                         {
2225                                 FieldSelect *fselect = (FieldSelect *) node;
2226                                 FieldSelect *newnode;
2227
2228                                 FLATCOPY(newnode, fselect, FieldSelect);
2229                                 MUTATE(newnode->arg, fselect->arg, Expr *);
2230                                 return (Node *) newnode;
2231                         }
2232                         break;
2233                 case T_FieldStore:
2234                         {
2235                                 FieldStore *fstore = (FieldStore *) node;
2236                                 FieldStore *newnode;
2237
2238                                 FLATCOPY(newnode, fstore, FieldStore);
2239                                 MUTATE(newnode->arg, fstore->arg, Expr *);
2240                                 MUTATE(newnode->newvals, fstore->newvals, List *);
2241                                 newnode->fieldnums = list_copy(fstore->fieldnums);
2242                                 return (Node *) newnode;
2243                         }
2244                         break;
2245                 case T_RelabelType:
2246                         {
2247                                 RelabelType *relabel = (RelabelType *) node;
2248                                 RelabelType *newnode;
2249
2250                                 FLATCOPY(newnode, relabel, RelabelType);
2251                                 MUTATE(newnode->arg, relabel->arg, Expr *);
2252                                 return (Node *) newnode;
2253                         }
2254                         break;
2255                 case T_CoerceViaIO:
2256                         {
2257                                 CoerceViaIO *iocoerce = (CoerceViaIO *) node;
2258                                 CoerceViaIO *newnode;
2259
2260                                 FLATCOPY(newnode, iocoerce, CoerceViaIO);
2261                                 MUTATE(newnode->arg, iocoerce->arg, Expr *);
2262                                 return (Node *) newnode;
2263                         }
2264                         break;
2265                 case T_ArrayCoerceExpr:
2266                         {
2267                                 ArrayCoerceExpr *acoerce = (ArrayCoerceExpr *) node;
2268                                 ArrayCoerceExpr *newnode;
2269
2270                                 FLATCOPY(newnode, acoerce, ArrayCoerceExpr);
2271                                 MUTATE(newnode->arg, acoerce->arg, Expr *);
2272                                 return (Node *) newnode;
2273                         }
2274                         break;
2275                 case T_ConvertRowtypeExpr:
2276                         {
2277                                 ConvertRowtypeExpr *convexpr = (ConvertRowtypeExpr *) node;
2278                                 ConvertRowtypeExpr *newnode;
2279
2280                                 FLATCOPY(newnode, convexpr, ConvertRowtypeExpr);
2281                                 MUTATE(newnode->arg, convexpr->arg, Expr *);
2282                                 return (Node *) newnode;
2283                         }
2284                         break;
2285                 case T_CollateExpr:
2286                         {
2287                                 CollateExpr *collate = (CollateExpr *) node;
2288                                 CollateExpr *newnode;
2289
2290                                 FLATCOPY(newnode, collate, CollateExpr);
2291                                 MUTATE(newnode->arg, collate->arg, Expr *);
2292                                 return (Node *) newnode;
2293                         }
2294                         break;
2295                 case T_CaseExpr:
2296                         {
2297                                 CaseExpr   *caseexpr = (CaseExpr *) node;
2298                                 CaseExpr   *newnode;
2299
2300                                 FLATCOPY(newnode, caseexpr, CaseExpr);
2301                                 MUTATE(newnode->arg, caseexpr->arg, Expr *);
2302                                 MUTATE(newnode->args, caseexpr->args, List *);
2303                                 MUTATE(newnode->defresult, caseexpr->defresult, Expr *);
2304                                 return (Node *) newnode;
2305                         }
2306                         break;
2307                 case T_CaseWhen:
2308                         {
2309                                 CaseWhen   *casewhen = (CaseWhen *) node;
2310                                 CaseWhen   *newnode;
2311
2312                                 FLATCOPY(newnode, casewhen, CaseWhen);
2313                                 MUTATE(newnode->expr, casewhen->expr, Expr *);
2314                                 MUTATE(newnode->result, casewhen->result, Expr *);
2315                                 return (Node *) newnode;
2316                         }
2317                         break;
2318                 case T_ArrayExpr:
2319                         {
2320                                 ArrayExpr  *arrayexpr = (ArrayExpr *) node;
2321                                 ArrayExpr  *newnode;
2322
2323                                 FLATCOPY(newnode, arrayexpr, ArrayExpr);
2324                                 MUTATE(newnode->elements, arrayexpr->elements, List *);
2325                                 return (Node *) newnode;
2326                         }
2327                         break;
2328                 case T_RowExpr:
2329                         {
2330                                 RowExpr    *rowexpr = (RowExpr *) node;
2331                                 RowExpr    *newnode;
2332
2333                                 FLATCOPY(newnode, rowexpr, RowExpr);
2334                                 MUTATE(newnode->args, rowexpr->args, List *);
2335                                 /* Assume colnames needn't be duplicated */
2336                                 return (Node *) newnode;
2337                         }
2338                         break;
2339                 case T_RowCompareExpr:
2340                         {
2341                                 RowCompareExpr *rcexpr = (RowCompareExpr *) node;
2342                                 RowCompareExpr *newnode;
2343
2344                                 FLATCOPY(newnode, rcexpr, RowCompareExpr);
2345                                 MUTATE(newnode->largs, rcexpr->largs, List *);
2346                                 MUTATE(newnode->rargs, rcexpr->rargs, List *);
2347                                 return (Node *) newnode;
2348                         }
2349                         break;
2350                 case T_CoalesceExpr:
2351                         {
2352                                 CoalesceExpr *coalesceexpr = (CoalesceExpr *) node;
2353                                 CoalesceExpr *newnode;
2354
2355                                 FLATCOPY(newnode, coalesceexpr, CoalesceExpr);
2356                                 MUTATE(newnode->args, coalesceexpr->args, List *);
2357                                 return (Node *) newnode;
2358                         }
2359                         break;
2360                 case T_MinMaxExpr:
2361                         {
2362                                 MinMaxExpr *minmaxexpr = (MinMaxExpr *) node;
2363                                 MinMaxExpr *newnode;
2364
2365                                 FLATCOPY(newnode, minmaxexpr, MinMaxExpr);
2366                                 MUTATE(newnode->args, minmaxexpr->args, List *);
2367                                 return (Node *) newnode;
2368                         }
2369                         break;
2370                 case T_XmlExpr:
2371                         {
2372                                 XmlExpr    *xexpr = (XmlExpr *) node;
2373                                 XmlExpr    *newnode;
2374
2375                                 FLATCOPY(newnode, xexpr, XmlExpr);
2376                                 MUTATE(newnode->named_args, xexpr->named_args, List *);
2377                                 /* assume mutator does not care about arg_names */
2378                                 MUTATE(newnode->args, xexpr->args, List *);
2379                                 return (Node *) newnode;
2380                         }
2381                         break;
2382                 case T_NullTest:
2383                         {
2384                                 NullTest   *ntest = (NullTest *) node;
2385                                 NullTest   *newnode;
2386
2387                                 FLATCOPY(newnode, ntest, NullTest);
2388                                 MUTATE(newnode->arg, ntest->arg, Expr *);
2389                                 return (Node *) newnode;
2390                         }
2391                         break;
2392                 case T_BooleanTest:
2393                         {
2394                                 BooleanTest *btest = (BooleanTest *) node;
2395                                 BooleanTest *newnode;
2396
2397                                 FLATCOPY(newnode, btest, BooleanTest);
2398                                 MUTATE(newnode->arg, btest->arg, Expr *);
2399                                 return (Node *) newnode;
2400                         }
2401                         break;
2402                 case T_CoerceToDomain:
2403                         {
2404                                 CoerceToDomain *ctest = (CoerceToDomain *) node;
2405                                 CoerceToDomain *newnode;
2406
2407                                 FLATCOPY(newnode, ctest, CoerceToDomain);
2408                                 MUTATE(newnode->arg, ctest->arg, Expr *);
2409                                 return (Node *) newnode;
2410                         }
2411                         break;
2412                 case T_TargetEntry:
2413                         {
2414                                 TargetEntry *targetentry = (TargetEntry *) node;
2415                                 TargetEntry *newnode;
2416
2417                                 FLATCOPY(newnode, targetentry, TargetEntry);
2418                                 MUTATE(newnode->expr, targetentry->expr, Expr *);
2419                                 return (Node *) newnode;
2420                         }
2421                         break;
2422                 case T_Query:
2423                         /* Do nothing with a sub-Query, per discussion above */
2424                         return node;
2425                 case T_WindowClause:
2426                         {
2427                                 WindowClause *wc = (WindowClause *) node;
2428                                 WindowClause *newnode;
2429
2430                                 FLATCOPY(newnode, wc, WindowClause);
2431                                 MUTATE(newnode->partitionClause, wc->partitionClause, List *);
2432                                 MUTATE(newnode->orderClause, wc->orderClause, List *);
2433                                 MUTATE(newnode->startOffset, wc->startOffset, Node *);
2434                                 MUTATE(newnode->endOffset, wc->endOffset, Node *);
2435                                 return (Node *) newnode;
2436                         }
2437                         break;
2438                 case T_CommonTableExpr:
2439                         {
2440                                 CommonTableExpr *cte = (CommonTableExpr *) node;
2441                                 CommonTableExpr *newnode;
2442
2443                                 FLATCOPY(newnode, cte, CommonTableExpr);
2444
2445                                 /*
2446                                  * Also invoke the mutator on the CTE's Query node, so it can
2447                                  * recurse into the sub-query if it wants to.
2448                                  */
2449                                 MUTATE(newnode->ctequery, cte->ctequery, Node *);
2450                                 return (Node *) newnode;
2451                         }
2452                         break;
2453                 case T_List:
2454                         {
2455                                 /*
2456                                  * We assume the mutator isn't interested in the list nodes
2457                                  * per se, so just invoke it on each list element. NOTE: this
2458                                  * would fail badly on a list with integer elements!
2459                                  */
2460                                 List       *resultlist;
2461                                 ListCell   *temp;
2462
2463                                 resultlist = NIL;
2464                                 foreach(temp, (List *) node)
2465                                 {
2466                                         resultlist = lappend(resultlist,
2467                                                                                  mutator((Node *) lfirst(temp),
2468                                                                                                  context));
2469                                 }
2470                                 return (Node *) resultlist;
2471                         }
2472                         break;
2473                 case T_FromExpr:
2474                         {
2475                                 FromExpr   *from = (FromExpr *) node;
2476                                 FromExpr   *newnode;
2477
2478                                 FLATCOPY(newnode, from, FromExpr);
2479                                 MUTATE(newnode->fromlist, from->fromlist, List *);
2480                                 MUTATE(newnode->quals, from->quals, Node *);
2481                                 return (Node *) newnode;
2482                         }
2483                         break;
2484                 case T_JoinExpr:
2485                         {
2486                                 JoinExpr   *join = (JoinExpr *) node;
2487                                 JoinExpr   *newnode;
2488
2489                                 FLATCOPY(newnode, join, JoinExpr);
2490                                 MUTATE(newnode->larg, join->larg, Node *);
2491                                 MUTATE(newnode->rarg, join->rarg, Node *);
2492                                 MUTATE(newnode->quals, join->quals, Node *);
2493                                 /* We do not mutate alias or using by default */
2494                                 return (Node *) newnode;
2495                         }
2496                         break;
2497                 case T_SetOperationStmt:
2498                         {
2499                                 SetOperationStmt *setop = (SetOperationStmt *) node;
2500                                 SetOperationStmt *newnode;
2501
2502                                 FLATCOPY(newnode, setop, SetOperationStmt);
2503                                 MUTATE(newnode->larg, setop->larg, Node *);
2504                                 MUTATE(newnode->rarg, setop->rarg, Node *);
2505                                 /* We do not mutate groupClauses by default */
2506                                 return (Node *) newnode;
2507                         }
2508                         break;
2509                 case T_PlaceHolderVar:
2510                         {
2511                                 PlaceHolderVar *phv = (PlaceHolderVar *) node;
2512                                 PlaceHolderVar *newnode;
2513
2514                                 FLATCOPY(newnode, phv, PlaceHolderVar);
2515                                 MUTATE(newnode->phexpr, phv->phexpr, Expr *);
2516                                 /* Assume we need not copy the relids bitmapset */
2517                                 return (Node *) newnode;
2518                         }
2519                         break;
2520                 case T_AppendRelInfo:
2521                         {
2522                                 AppendRelInfo *appinfo = (AppendRelInfo *) node;
2523                                 AppendRelInfo *newnode;
2524
2525                                 FLATCOPY(newnode, appinfo, AppendRelInfo);
2526                                 MUTATE(newnode->translated_vars, appinfo->translated_vars, List *);
2527                                 return (Node *) newnode;
2528                         }
2529                         break;
2530                 case T_PlaceHolderInfo:
2531                         {
2532                                 PlaceHolderInfo *phinfo = (PlaceHolderInfo *) node;
2533                                 PlaceHolderInfo *newnode;
2534
2535                                 FLATCOPY(newnode, phinfo, PlaceHolderInfo);
2536                                 MUTATE(newnode->ph_var, phinfo->ph_var, PlaceHolderVar *);
2537                                 /* Assume we need not copy the relids bitmapsets */
2538                                 return (Node *) newnode;
2539                         }
2540                         break;
2541                 default:
2542                         elog(ERROR, "unrecognized node type: %d",
2543                                  (int) nodeTag(node));
2544                         break;
2545         }
2546         /* can't get here, but keep compiler happy */
2547         return NULL;
2548 }
2549
2550
2551 /*
2552  * query_tree_mutator --- initiate modification of a Query's expressions
2553  *
2554  * This routine exists just to reduce the number of places that need to know
2555  * where all the expression subtrees of a Query are.  Note it can be used
2556  * for starting a walk at top level of a Query regardless of whether the
2557  * mutator intends to descend into subqueries.  It is also useful for
2558  * descending into subqueries within a mutator.
2559  *
2560  * Some callers want to suppress mutating of certain items in the Query,
2561  * typically because they need to process them specially, or don't actually
2562  * want to recurse into subqueries.  This is supported by the flags argument,
2563  * which is the bitwise OR of flag values to suppress mutating of
2564  * indicated items.  (More flag bits may be added as needed.)
2565  *
2566  * Normally the Query node itself is copied, but some callers want it to be
2567  * modified in-place; they must pass QTW_DONT_COPY_QUERY in flags.      All
2568  * modified substructure is safely copied in any case.
2569  */
2570 Query *
2571 query_tree_mutator(Query *query,
2572                                    Node *(*mutator) (),
2573                                    void *context,
2574                                    int flags)
2575 {
2576         Assert(query != NULL && IsA(query, Query));
2577
2578         if (!(flags & QTW_DONT_COPY_QUERY))
2579         {
2580                 Query      *newquery;
2581
2582                 FLATCOPY(newquery, query, Query);
2583                 query = newquery;
2584         }
2585
2586         MUTATE(query->targetList, query->targetList, List *);
2587         MUTATE(query->returningList, query->returningList, List *);
2588         MUTATE(query->jointree, query->jointree, FromExpr *);
2589         MUTATE(query->setOperations, query->setOperations, Node *);
2590         MUTATE(query->havingQual, query->havingQual, Node *);
2591         MUTATE(query->limitOffset, query->limitOffset, Node *);
2592         MUTATE(query->limitCount, query->limitCount, Node *);
2593         if (!(flags & QTW_IGNORE_CTE_SUBQUERIES))
2594                 MUTATE(query->cteList, query->cteList, List *);
2595         else    /* else copy CTE list as-is */
2596                 query->cteList = copyObject(query->cteList);
2597         query->rtable = range_table_mutator(query->rtable,
2598                                                                                 mutator, context, flags);
2599         return query;
2600 }
2601
2602 /*
2603  * range_table_mutator is just the part of query_tree_mutator that processes
2604  * a query's rangetable.  This is split out since it can be useful on
2605  * its own.
2606  */
2607 List *
2608 range_table_mutator(List *rtable,
2609                                         Node *(*mutator) (),
2610                                         void *context,
2611                                         int flags)
2612 {
2613         List       *newrt = NIL;
2614         ListCell   *rt;
2615
2616         foreach(rt, rtable)
2617         {
2618                 RangeTblEntry *rte = (RangeTblEntry *) lfirst(rt);
2619                 RangeTblEntry *newrte;
2620
2621                 FLATCOPY(newrte, rte, RangeTblEntry);
2622                 switch (rte->rtekind)
2623                 {
2624                         case RTE_RELATION:
2625                         case RTE_CTE:
2626                                 /* we don't bother to copy eref, aliases, etc; OK? */
2627                                 break;
2628                         case RTE_SUBQUERY:
2629                                 if (!(flags & QTW_IGNORE_RT_SUBQUERIES))
2630                                 {
2631                                         CHECKFLATCOPY(newrte->subquery, rte->subquery, Query);
2632                                         MUTATE(newrte->subquery, newrte->subquery, Query *);
2633                                 }
2634                                 else
2635                                 {
2636                                         /* else, copy RT subqueries as-is */
2637                                         newrte->subquery = copyObject(rte->subquery);
2638                                 }
2639                                 break;
2640                         case RTE_JOIN:
2641                                 if (!(flags & QTW_IGNORE_JOINALIASES))
2642                                         MUTATE(newrte->joinaliasvars, rte->joinaliasvars, List *);
2643                                 else
2644                                 {
2645                                         /* else, copy join aliases as-is */
2646                                         newrte->joinaliasvars = copyObject(rte->joinaliasvars);
2647                                 }
2648                                 break;
2649                         case RTE_FUNCTION:
2650                                 MUTATE(newrte->funcexpr, rte->funcexpr, Node *);
2651                                 break;
2652                         case RTE_VALUES:
2653                                 MUTATE(newrte->values_lists, rte->values_lists, List *);
2654                                 break;
2655                 }
2656                 newrt = lappend(newrt, newrte);
2657         }
2658         return newrt;
2659 }
2660
2661 /*
2662  * query_or_expression_tree_walker --- hybrid form
2663  *
2664  * This routine will invoke query_tree_walker if called on a Query node,
2665  * else will invoke the walker directly.  This is a useful way of starting
2666  * the recursion when the walker's normal change of state is not appropriate
2667  * for the outermost Query node.
2668  */
2669 bool
2670 query_or_expression_tree_walker(Node *node,
2671                                                                 bool (*walker) (),
2672                                                                 void *context,
2673                                                                 int flags)
2674 {
2675         if (node && IsA(node, Query))
2676                 return query_tree_walker((Query *) node,
2677                                                                  walker,
2678                                                                  context,
2679                                                                  flags);
2680         else
2681                 return walker(node, context);
2682 }
2683
2684 /*
2685  * query_or_expression_tree_mutator --- hybrid form
2686  *
2687  * This routine will invoke query_tree_mutator if called on a Query node,
2688  * else will invoke the mutator directly.  This is a useful way of starting
2689  * the recursion when the mutator's normal change of state is not appropriate
2690  * for the outermost Query node.
2691  */
2692 Node *
2693 query_or_expression_tree_mutator(Node *node,
2694                                                                  Node *(*mutator) (),
2695                                                                  void *context,
2696                                                                  int flags)
2697 {
2698         if (node && IsA(node, Query))
2699                 return (Node *) query_tree_mutator((Query *) node,
2700                                                                                    mutator,
2701                                                                                    context,
2702                                                                                    flags);
2703         else
2704                 return mutator(node, context);
2705 }
2706
2707
2708 /*
2709  * raw_expression_tree_walker --- walk raw parse trees
2710  *
2711  * This has exactly the same API as expression_tree_walker, but instead of
2712  * walking post-analysis parse trees, it knows how to walk the node types
2713  * found in raw grammar output.  (There is not currently any need for a
2714  * combined walker, so we keep them separate in the name of efficiency.)
2715  * Unlike expression_tree_walker, there is no special rule about query
2716  * boundaries: we descend to everything that's possibly interesting.
2717  *
2718  * Currently, the node type coverage extends to SelectStmt and everything
2719  * that could appear under it, but not other statement types.
2720  */
2721 bool
2722 raw_expression_tree_walker(Node *node,
2723                                                    bool (*walker) (),
2724                                                    void *context)
2725 {
2726         ListCell   *temp;
2727
2728         /*
2729          * The walker has already visited the current node, and so we need only
2730          * recurse into any sub-nodes it has.
2731          */
2732         if (node == NULL)
2733                 return false;
2734
2735         /* Guard against stack overflow due to overly complex expressions */
2736         check_stack_depth();
2737
2738         switch (nodeTag(node))
2739         {
2740                 case T_SetToDefault:
2741                 case T_CurrentOfExpr:
2742                 case T_Integer:
2743                 case T_Float:
2744                 case T_String:
2745                 case T_BitString:
2746                 case T_Null:
2747                 case T_ParamRef:
2748                 case T_A_Const:
2749                 case T_A_Star:
2750                         /* primitive node types with no subnodes */
2751                         break;
2752                 case T_Alias:
2753                         /* we assume the colnames list isn't interesting */
2754                         break;
2755                 case T_RangeVar:
2756                         return walker(((RangeVar *) node)->alias, context);
2757                 case T_SubLink:
2758                         {
2759                                 SubLink    *sublink = (SubLink *) node;
2760
2761                                 if (walker(sublink->testexpr, context))
2762                                         return true;
2763                                 /* we assume the operName is not interesting */
2764                                 if (walker(sublink->subselect, context))
2765                                         return true;
2766                         }
2767                         break;
2768                 case T_CaseExpr:
2769                         {
2770                                 CaseExpr   *caseexpr = (CaseExpr *) node;
2771
2772                                 if (walker(caseexpr->arg, context))
2773                                         return true;
2774                                 /* we assume walker doesn't care about CaseWhens, either */
2775                                 foreach(temp, caseexpr->args)
2776                                 {
2777                                         CaseWhen   *when = (CaseWhen *) lfirst(temp);
2778
2779                                         Assert(IsA(when, CaseWhen));
2780                                         if (walker(when->expr, context))
2781                                                 return true;
2782                                         if (walker(when->result, context))
2783                                                 return true;
2784                                 }
2785                                 if (walker(caseexpr->defresult, context))
2786                                         return true;
2787                         }
2788                         break;
2789                 case T_RowExpr:
2790                         /* Assume colnames isn't interesting */
2791                         return walker(((RowExpr *) node)->args, context);
2792                 case T_CoalesceExpr:
2793                         return walker(((CoalesceExpr *) node)->args, context);
2794                 case T_MinMaxExpr:
2795                         return walker(((MinMaxExpr *) node)->args, context);
2796                 case T_XmlExpr:
2797                         {
2798                                 XmlExpr    *xexpr = (XmlExpr *) node;
2799
2800                                 if (walker(xexpr->named_args, context))
2801                                         return true;
2802                                 /* we assume walker doesn't care about arg_names */
2803                                 if (walker(xexpr->args, context))
2804                                         return true;
2805                         }
2806                         break;
2807                 case T_NullTest:
2808                         return walker(((NullTest *) node)->arg, context);
2809                 case T_BooleanTest:
2810                         return walker(((BooleanTest *) node)->arg, context);
2811                 case T_JoinExpr:
2812                         {
2813                                 JoinExpr   *join = (JoinExpr *) node;
2814
2815                                 if (walker(join->larg, context))
2816                                         return true;
2817                                 if (walker(join->rarg, context))
2818                                         return true;
2819                                 if (walker(join->quals, context))
2820                                         return true;
2821                                 if (walker(join->alias, context))
2822                                         return true;
2823                                 /* using list is deemed uninteresting */
2824                         }
2825                         break;
2826                 case T_IntoClause:
2827                         {
2828                                 IntoClause *into = (IntoClause *) node;
2829
2830                                 if (walker(into->rel, context))
2831                                         return true;
2832                                 /* colNames, options are deemed uninteresting */
2833                         }
2834                         break;
2835                 case T_List:
2836                         foreach(temp, (List *) node)
2837                         {
2838                                 if (walker((Node *) lfirst(temp), context))
2839                                         return true;
2840                         }
2841                         break;
2842                 case T_InsertStmt:
2843                         {
2844                                 InsertStmt *stmt = (InsertStmt *) node;
2845
2846                                 if (walker(stmt->relation, context))
2847                                         return true;
2848                                 if (walker(stmt->cols, context))
2849                                         return true;
2850                                 if (walker(stmt->selectStmt, context))
2851                                         return true;
2852                                 if (walker(stmt->returningList, context))
2853                                         return true;
2854                                 if (walker(stmt->withClause, context))
2855                                         return true;
2856                         }
2857                         break;
2858                 case T_DeleteStmt:
2859                         {
2860                                 DeleteStmt *stmt = (DeleteStmt *) node;
2861
2862                                 if (walker(stmt->relation, context))
2863                                         return true;
2864                                 if (walker(stmt->usingClause, context))
2865                                         return true;
2866                                 if (walker(stmt->whereClause, context))
2867                                         return true;
2868                                 if (walker(stmt->returningList, context))
2869                                         return true;
2870                                 if (walker(stmt->withClause, context))
2871                                         return true;
2872                         }
2873                         break;
2874                 case T_UpdateStmt:
2875                         {
2876                                 UpdateStmt *stmt = (UpdateStmt *) node;
2877
2878                                 if (walker(stmt->relation, context))
2879                                         return true;
2880                                 if (walker(stmt->targetList, context))
2881                                         return true;
2882                                 if (walker(stmt->whereClause, context))
2883                                         return true;
2884                                 if (walker(stmt->fromClause, context))
2885                                         return true;
2886                                 if (walker(stmt->returningList, context))
2887                                         return true;
2888                                 if (walker(stmt->withClause, context))
2889                                         return true;
2890                         }
2891                         break;
2892                 case T_SelectStmt:
2893                         {
2894                                 SelectStmt *stmt = (SelectStmt *) node;
2895
2896                                 if (walker(stmt->distinctClause, context))
2897                                         return true;
2898                                 if (walker(stmt->intoClause, context))
2899                                         return true;
2900                                 if (walker(stmt->targetList, context))
2901                                         return true;
2902                                 if (walker(stmt->fromClause, context))
2903                                         return true;
2904                                 if (walker(stmt->whereClause, context))
2905                                         return true;
2906                                 if (walker(stmt->groupClause, context))
2907                                         return true;
2908                                 if (walker(stmt->havingClause, context))
2909                                         return true;
2910                                 if (walker(stmt->windowClause, context))
2911                                         return true;
2912                                 if (walker(stmt->withClause, context))
2913                                         return true;
2914                                 if (walker(stmt->valuesLists, context))
2915                                         return true;
2916                                 if (walker(stmt->sortClause, context))
2917                                         return true;
2918                                 if (walker(stmt->limitOffset, context))
2919                                         return true;
2920                                 if (walker(stmt->limitCount, context))
2921                                         return true;
2922                                 if (walker(stmt->lockingClause, context))
2923                                         return true;
2924                                 if (walker(stmt->larg, context))
2925                                         return true;
2926                                 if (walker(stmt->rarg, context))
2927                                         return true;
2928                         }
2929                         break;
2930                 case T_A_Expr:
2931                         {
2932                                 A_Expr     *expr = (A_Expr *) node;
2933
2934                                 if (walker(expr->lexpr, context))
2935                                         return true;
2936                                 if (walker(expr->rexpr, context))
2937                                         return true;
2938                                 /* operator name is deemed uninteresting */
2939                         }
2940                         break;
2941                 case T_ColumnRef:
2942                         /* we assume the fields contain nothing interesting */
2943                         break;
2944                 case T_FuncCall:
2945                         {
2946                                 FuncCall   *fcall = (FuncCall *) node;
2947
2948                                 if (walker(fcall->args, context))
2949                                         return true;
2950                                 if (walker(fcall->agg_order, context))
2951                                         return true;
2952                                 if (walker(fcall->over, context))
2953                                         return true;
2954                                 /* function name is deemed uninteresting */
2955                         }
2956                         break;
2957                 case T_NamedArgExpr:
2958                         return walker(((NamedArgExpr *) node)->arg, context);
2959                 case T_A_Indices:
2960                         {
2961                                 A_Indices  *indices = (A_Indices *) node;
2962
2963                                 if (walker(indices->lidx, context))
2964                                         return true;
2965                                 if (walker(indices->uidx, context))
2966                                         return true;
2967                         }
2968                         break;
2969                 case T_A_Indirection:
2970                         {
2971                                 A_Indirection *indir = (A_Indirection *) node;
2972
2973                                 if (walker(indir->arg, context))
2974                                         return true;
2975                                 if (walker(indir->indirection, context))
2976                                         return true;
2977                         }
2978                         break;
2979                 case T_A_ArrayExpr:
2980                         return walker(((A_ArrayExpr *) node)->elements, context);
2981                 case T_ResTarget:
2982                         {
2983                                 ResTarget  *rt = (ResTarget *) node;
2984
2985                                 if (walker(rt->indirection, context))
2986                                         return true;
2987                                 if (walker(rt->val, context))
2988                                         return true;
2989                         }
2990                         break;
2991                 case T_TypeCast:
2992                         {
2993                                 TypeCast   *tc = (TypeCast *) node;
2994
2995                                 if (walker(tc->arg, context))
2996                                         return true;
2997                                 if (walker(tc->typeName, context))
2998                                         return true;
2999                         }
3000                         break;
3001                 case T_CollateClause:
3002                         return walker(((CollateClause *) node)->arg, context);
3003                 case T_SortBy:
3004                         return walker(((SortBy *) node)->node, context);
3005                 case T_WindowDef:
3006                         {
3007                                 WindowDef  *wd = (WindowDef *) node;
3008
3009                                 if (walker(wd->partitionClause, context))
3010                                         return true;
3011                                 if (walker(wd->orderClause, context))
3012                                         return true;
3013                                 if (walker(wd->startOffset, context))
3014                                         return true;
3015                                 if (walker(wd->endOffset, context))
3016                                         return true;
3017                         }
3018                         break;
3019                 case T_RangeSubselect:
3020                         {
3021                                 RangeSubselect *rs = (RangeSubselect *) node;
3022
3023                                 if (walker(rs->subquery, context))
3024                                         return true;
3025                                 if (walker(rs->alias, context))
3026                                         return true;
3027                         }
3028                         break;
3029                 case T_RangeFunction:
3030                         {
3031                                 RangeFunction *rf = (RangeFunction *) node;
3032
3033                                 if (walker(rf->funccallnode, context))
3034                                         return true;
3035                                 if (walker(rf->alias, context))
3036                                         return true;
3037                         }
3038                         break;
3039                 case T_TypeName:
3040                         {
3041                                 TypeName   *tn = (TypeName *) node;
3042
3043                                 if (walker(tn->typmods, context))
3044                                         return true;
3045                                 if (walker(tn->arrayBounds, context))
3046                                         return true;
3047                                 /* type name itself is deemed uninteresting */
3048                         }
3049                         break;
3050                 case T_ColumnDef:
3051                         {
3052                                 ColumnDef  *coldef = (ColumnDef *) node;
3053
3054                                 if (walker(coldef->typeName, context))
3055                                         return true;
3056                                 if (walker(coldef->raw_default, context))
3057                                         return true;
3058                                 if (walker(coldef->collClause, context))
3059                                         return true;
3060                                 /* for now, constraints are ignored */
3061                         }
3062                         break;
3063                 case T_LockingClause:
3064                         return walker(((LockingClause *) node)->lockedRels, context);
3065                 case T_XmlSerialize:
3066                         {
3067                                 XmlSerialize *xs = (XmlSerialize *) node;
3068
3069                                 if (walker(xs->expr, context))
3070                                         return true;
3071                                 if (walker(xs->typeName, context))
3072                                         return true;
3073                         }
3074                         break;
3075                 case T_WithClause:
3076                         return walker(((WithClause *) node)->ctes, context);
3077                 case T_CommonTableExpr:
3078                         return walker(((CommonTableExpr *) node)->ctequery, context);
3079                 default:
3080                         elog(ERROR, "unrecognized node type: %d",
3081                                  (int) nodeTag(node));
3082                         break;
3083         }
3084         return false;
3085 }