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