1 /*-------------------------------------------------------------------------
4 * Various general-purpose manipulations of Node trees
6 * Portions Copyright (c) 1996-2011, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
11 * src/backend/nodes/nodeFuncs.c
13 *-------------------------------------------------------------------------
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"
26 static bool expression_returns_set_walker(Node *node, void *context);
27 static int leftmostLoc(int loc1, int loc2);
32 * returns the Oid of the type of the expression's result.
42 switch (nodeTag(expr))
45 type = ((Var *) expr)->vartype;
48 type = ((Const *) expr)->consttype;
51 type = ((Param *) expr)->paramtype;
54 type = ((Aggref *) expr)->aggtype;
57 type = ((WindowFunc *) expr)->wintype;
61 ArrayRef *arrayref = (ArrayRef *) expr;
63 /* slice and/or store operations yield the array type */
64 if (arrayref->reflowerindexpr || arrayref->refassgnexpr)
65 type = arrayref->refarraytype;
67 type = arrayref->refelemtype;
71 type = ((FuncExpr *) expr)->funcresulttype;
74 type = exprType((Node *) ((NamedArgExpr *) expr)->arg);
77 type = ((OpExpr *) expr)->opresulttype;
80 type = ((DistinctExpr *) expr)->opresulttype;
82 case T_ScalarArrayOpExpr:
90 SubLink *sublink = (SubLink *) expr;
92 if (sublink->subLinkType == EXPR_SUBLINK ||
93 sublink->subLinkType == ARRAY_SUBLINK)
95 /* get the type of the subselect's first target column */
96 Query *qtree = (Query *) sublink->subselect;
99 if (!qtree || !IsA(qtree, Query))
100 elog(ERROR, "cannot get type for untransformed sublink");
101 tent = (TargetEntry *) linitial(qtree->targetList);
102 Assert(IsA(tent, TargetEntry));
103 Assert(!tent->resjunk);
104 type = exprType((Node *) tent->expr);
105 if (sublink->subLinkType == ARRAY_SUBLINK)
107 type = get_array_type(type);
108 if (!OidIsValid(type))
110 (errcode(ERRCODE_UNDEFINED_OBJECT),
111 errmsg("could not find array type for data type %s",
112 format_type_be(exprType((Node *) tent->expr)))));
117 /* for all other sublink types, result is boolean */
124 SubPlan *subplan = (SubPlan *) expr;
126 if (subplan->subLinkType == EXPR_SUBLINK ||
127 subplan->subLinkType == ARRAY_SUBLINK)
129 /* get the type of the subselect's first target column */
130 type = subplan->firstColType;
131 if (subplan->subLinkType == ARRAY_SUBLINK)
133 type = get_array_type(type);
134 if (!OidIsValid(type))
136 (errcode(ERRCODE_UNDEFINED_OBJECT),
137 errmsg("could not find array type for data type %s",
138 format_type_be(subplan->firstColType))));
143 /* for all other subplan types, result is boolean */
148 case T_AlternativeSubPlan:
150 AlternativeSubPlan *asplan = (AlternativeSubPlan *) expr;
152 /* subplans should all return the same thing */
153 type = exprType((Node *) linitial(asplan->subplans));
157 type = ((FieldSelect *) expr)->resulttype;
160 type = ((FieldStore *) expr)->resulttype;
163 type = ((RelabelType *) expr)->resulttype;
165 case T_CollateClause:
166 type = exprType((Node *) ((CollateClause *) expr)->arg);
169 type = ((CoerceViaIO *) expr)->resulttype;
171 case T_ArrayCoerceExpr:
172 type = ((ArrayCoerceExpr *) expr)->resulttype;
174 case T_ConvertRowtypeExpr:
175 type = ((ConvertRowtypeExpr *) expr)->resulttype;
178 type = ((CaseExpr *) expr)->casetype;
181 type = ((CaseTestExpr *) expr)->typeId;
184 type = ((ArrayExpr *) expr)->array_typeid;
187 type = ((RowExpr *) expr)->row_typeid;
189 case T_RowCompareExpr:
193 type = ((CoalesceExpr *) expr)->coalescetype;
196 type = ((MinMaxExpr *) expr)->minmaxtype;
199 if (((XmlExpr *) expr)->op == IS_DOCUMENT)
201 else if (((XmlExpr *) expr)->op == IS_XMLSERIALIZE)
207 type = exprType((Node *) linitial(((NullIfExpr *) expr)->args));
215 case T_CoerceToDomain:
216 type = ((CoerceToDomain *) expr)->resulttype;
218 case T_CoerceToDomainValue:
219 type = ((CoerceToDomainValue *) expr)->typeId;
222 type = ((SetToDefault *) expr)->typeId;
224 case T_CurrentOfExpr:
227 case T_PlaceHolderVar:
228 type = exprType((Node *) ((PlaceHolderVar *) expr)->phexpr);
231 elog(ERROR, "unrecognized node type: %d", (int) nodeTag(expr));
232 type = InvalidOid; /* keep compiler quiet */
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.
244 exprTypmod(Node *expr)
249 switch (nodeTag(expr))
252 return ((Var *) expr)->vartypmod;
254 return ((Const *) expr)->consttypmod;
256 return ((Param *) expr)->paramtypmod;
258 /* typmod is the same for array or element */
259 return ((ArrayRef *) expr)->reftypmod;
264 /* Be smart about length-coercion functions... */
265 if (exprIsLengthCoercion(expr, &coercedTypmod))
266 return coercedTypmod;
270 return exprTypmod((Node *) ((NamedArgExpr *) expr)->arg);
273 SubLink *sublink = (SubLink *) expr;
275 if (sublink->subLinkType == EXPR_SUBLINK ||
276 sublink->subLinkType == ARRAY_SUBLINK)
278 /* get the typmod of the subselect's first target column */
279 Query *qtree = (Query *) sublink->subselect;
282 if (!qtree || !IsA(qtree, Query))
283 elog(ERROR, "cannot get type for untransformed sublink");
284 tent = (TargetEntry *) linitial(qtree->targetList);
285 Assert(IsA(tent, TargetEntry));
286 Assert(!tent->resjunk);
287 return exprTypmod((Node *) tent->expr);
288 /* note we don't need to care if it's an array */
294 SubPlan *subplan = (SubPlan *) expr;
296 if (subplan->subLinkType == EXPR_SUBLINK ||
297 subplan->subLinkType == ARRAY_SUBLINK)
299 /* get the typmod of the subselect's first target column */
300 /* note we don't need to care if it's an array */
301 return subplan->firstColTypmod;
305 /* for all other subplan types, result is boolean */
310 case T_AlternativeSubPlan:
312 AlternativeSubPlan *asplan = (AlternativeSubPlan *) expr;
314 /* subplans should all return the same thing */
315 return exprTypmod((Node *) linitial(asplan->subplans));
319 return ((FieldSelect *) expr)->resulttypmod;
321 return ((RelabelType *) expr)->resulttypmod;
322 case T_ArrayCoerceExpr:
323 return ((ArrayCoerceExpr *) expr)->resulttypmod;
327 * If all the alternatives agree on type/typmod, return that
328 * typmod, else use -1
330 CaseExpr *cexpr = (CaseExpr *) expr;
331 Oid casetype = cexpr->casetype;
335 if (!cexpr->defresult)
337 if (exprType((Node *) cexpr->defresult) != casetype)
339 typmod = exprTypmod((Node *) cexpr->defresult);
341 return -1; /* no point in trying harder */
342 foreach(arg, cexpr->args)
344 CaseWhen *w = (CaseWhen *) lfirst(arg);
346 Assert(IsA(w, CaseWhen));
347 if (exprType((Node *) w->result) != casetype)
349 if (exprTypmod((Node *) w->result) != typmod)
356 return ((CaseTestExpr *) expr)->typeMod;
360 * If all the elements agree on type/typmod, return that
361 * typmod, else use -1
363 ArrayExpr *arrayexpr = (ArrayExpr *) expr;
368 if (arrayexpr->elements == NIL)
370 typmod = exprTypmod((Node *) linitial(arrayexpr->elements));
372 return -1; /* no point in trying harder */
373 if (arrayexpr->multidims)
374 commontype = arrayexpr->array_typeid;
376 commontype = arrayexpr->element_typeid;
377 foreach(elem, arrayexpr->elements)
379 Node *e = (Node *) lfirst(elem);
381 if (exprType(e) != commontype)
383 if (exprTypmod(e) != typmod)
392 * If all the alternatives agree on type/typmod, return that
393 * typmod, else use -1
395 CoalesceExpr *cexpr = (CoalesceExpr *) expr;
396 Oid coalescetype = cexpr->coalescetype;
400 if (exprType((Node *) linitial(cexpr->args)) != coalescetype)
402 typmod = exprTypmod((Node *) linitial(cexpr->args));
404 return -1; /* no point in trying harder */
405 for_each_cell(arg, lnext(list_head(cexpr->args)))
407 Node *e = (Node *) lfirst(arg);
409 if (exprType(e) != coalescetype)
411 if (exprTypmod(e) != typmod)
420 * If all the alternatives agree on type/typmod, return that
421 * typmod, else use -1
423 MinMaxExpr *mexpr = (MinMaxExpr *) expr;
424 Oid minmaxtype = mexpr->minmaxtype;
428 if (exprType((Node *) linitial(mexpr->args)) != minmaxtype)
430 typmod = exprTypmod((Node *) linitial(mexpr->args));
432 return -1; /* no point in trying harder */
433 for_each_cell(arg, lnext(list_head(mexpr->args)))
435 Node *e = (Node *) lfirst(arg);
437 if (exprType(e) != minmaxtype)
439 if (exprTypmod(e) != typmod)
447 NullIfExpr *nexpr = (NullIfExpr *) expr;
449 return exprTypmod((Node *) linitial(nexpr->args));
452 case T_CoerceToDomain:
453 return ((CoerceToDomain *) expr)->resulttypmod;
454 case T_CoerceToDomainValue:
455 return ((CoerceToDomainValue *) expr)->typeMod;
457 return ((SetToDefault *) expr)->typeMod;
458 case T_PlaceHolderVar:
459 return exprTypmod((Node *) ((PlaceHolderVar *) expr)->phexpr);
468 * returns the Oid of the collation of the expression's result.
471 exprCollation(Node *expr)
478 switch (nodeTag(expr))
481 coll = ((Var *) expr)->varcollid;
484 coll = ((Const *) expr)->constcollid;
487 coll = ((Param *) expr)->paramcollation;
490 coll = ((Aggref *) expr)->collid;
493 coll = ((WindowFunc *) expr)->collid;
496 coll = ((ArrayRef *) expr)->refcollid;
499 coll = ((FuncExpr *) expr)->collid;
502 coll = exprCollation((Node *) ((NamedArgExpr *) expr)->arg);
505 coll = ((OpExpr *) expr)->collid;
508 coll = ((DistinctExpr *) expr)->collid;
510 case T_ScalarArrayOpExpr:
511 coll = ((ScalarArrayOpExpr *) expr)->collid;
514 coll = InvalidOid; /* not applicable */
518 SubLink *sublink = (SubLink *) expr;
520 if (sublink->subLinkType == EXPR_SUBLINK ||
521 sublink->subLinkType == ARRAY_SUBLINK)
523 /* get the collation of the subselect's first target column */
524 Query *qtree = (Query *) sublink->subselect;
527 if (!qtree || !IsA(qtree, Query))
528 elog(ERROR, "cannot get collation for untransformed sublink");
529 tent = (TargetEntry *) linitial(qtree->targetList);
530 Assert(IsA(tent, TargetEntry));
531 Assert(!tent->resjunk);
532 coll = exprCollation((Node *) tent->expr);
533 /* note we don't need to care if it's an array */
541 SubPlan *subplan = (SubPlan *) expr;
543 if (subplan->subLinkType == EXPR_SUBLINK ||
544 subplan->subLinkType == ARRAY_SUBLINK)
546 /* get the collation of the subselect's first target column */
547 /* note we don't need to care if it's an array */
548 coll = subplan->firstColCollation;
552 /* for all other subplan types, result is boolean */
557 case T_AlternativeSubPlan:
559 AlternativeSubPlan *asplan = (AlternativeSubPlan *) expr;
561 /* subplans should all return the same thing */
562 coll = exprCollation((Node *) linitial(asplan->subplans));
566 coll = ((FieldSelect *) expr)->resultcollation;
569 coll = InvalidOid; /* not applicable */
572 coll = exprCollation((Node *) ((RelabelType *) expr)->arg);
574 case T_CollateClause:
575 coll = ((CollateClause *) expr)->collOid;
579 CoerceViaIO *cvio = (CoerceViaIO *) expr;
580 coll = coercion_expression_result_collation(cvio->resulttype, (Node *) cvio->arg);
583 case T_ArrayCoerceExpr:
585 ArrayCoerceExpr *ace = (ArrayCoerceExpr *) expr;
586 coll = coercion_expression_result_collation(ace->resulttype, (Node *) ace->arg);
589 case T_ConvertRowtypeExpr:
591 ConvertRowtypeExpr *cre = (ConvertRowtypeExpr *) expr;
592 coll = coercion_expression_result_collation(cre->resulttype, (Node *) cre->arg);
596 coll = ((CaseExpr *) expr)->casecollation;
599 coll = ((CaseTestExpr *) expr)->collation;
602 coll = get_typcollation(((ArrayExpr *) expr)->array_typeid);
605 coll = InvalidOid; /* not applicable */
607 case T_RowCompareExpr:
608 coll = InvalidOid; /* not applicable */
611 coll = ((CoalesceExpr *) expr)->coalescecollation;
614 coll = ((MinMaxExpr *) expr)->collid;
617 if (((XmlExpr *) expr)->op == IS_XMLSERIALIZE)
618 coll = DEFAULT_COLLATION_OID;
623 coll = exprCollation((Node *) linitial(((NullIfExpr *) expr)->args));
626 coll = InvalidOid; /* not applicable */
629 coll = InvalidOid; /* not applicable */
631 case T_CoerceToDomain:
632 coll = get_typcollation(((CoerceToDomain *) expr)->resulttype);
633 if (coll == DEFAULT_COLLATION_OID)
634 coll = exprCollation((Node *) ((CoerceToDomain *) expr)->arg);
636 case T_CoerceToDomainValue:
637 coll = get_typcollation(((CoerceToDomainValue *) expr)->typeId);
640 coll = ((SetToDefault *) expr)->collid;
642 case T_CurrentOfExpr:
643 coll = InvalidOid; /* not applicable */
645 case T_PlaceHolderVar:
646 coll = exprCollation((Node *) ((PlaceHolderVar *) expr)->phexpr);
649 elog(ERROR, "unrecognized node type: %d", (int) nodeTag(expr));
650 coll = InvalidOid; /* keep compiler quiet */
658 * Compute the result collation of a coercion-like expression that
659 * converts arg to resulttype.
662 coercion_expression_result_collation(Oid resulttype, Node *arg)
664 if (type_is_collatable(resulttype))
666 if (type_is_collatable(exprType(arg)))
667 return exprCollation(arg);
669 return DEFAULT_COLLATION_OID;
676 * exprIsLengthCoercion
677 * Detect whether an expression tree is an application of a datatype's
678 * typmod-coercion function. Optionally extract the result's typmod.
680 * If coercedTypmod is not NULL, the typmod is stored there if the expression
681 * is a length-coercion function, else -1 is stored there.
683 * Note that a combined type-and-length coercion will be treated as a
684 * length coercion by this routine.
687 exprIsLengthCoercion(Node *expr, int32 *coercedTypmod)
689 if (coercedTypmod != NULL)
690 *coercedTypmod = -1; /* default result on failure */
693 * Scalar-type length coercions are FuncExprs, array-type length coercions
694 * are ArrayCoerceExprs
696 if (expr && IsA(expr, FuncExpr))
698 FuncExpr *func = (FuncExpr *) expr;
703 * If it didn't come from a coercion context, reject.
705 if (func->funcformat != COERCE_EXPLICIT_CAST &&
706 func->funcformat != COERCE_IMPLICIT_CAST)
710 * If it's not a two-argument or three-argument function with the
711 * second argument being an int4 constant, it can't have been created
712 * from a length coercion (it must be a type coercion, instead).
714 nargs = list_length(func->args);
715 if (nargs < 2 || nargs > 3)
718 second_arg = (Const *) lsecond(func->args);
719 if (!IsA(second_arg, Const) ||
720 second_arg->consttype != INT4OID ||
721 second_arg->constisnull)
725 * OK, it is indeed a length-coercion function.
727 if (coercedTypmod != NULL)
728 *coercedTypmod = DatumGetInt32(second_arg->constvalue);
733 if (expr && IsA(expr, ArrayCoerceExpr))
735 ArrayCoerceExpr *acoerce = (ArrayCoerceExpr *) expr;
737 /* It's not a length coercion unless there's a nondefault typmod */
738 if (acoerce->resulttypmod < 0)
742 * OK, it is indeed a length-coercion expression.
744 if (coercedTypmod != NULL)
745 *coercedTypmod = acoerce->resulttypmod;
754 * expression_returns_set
755 * Test whether an expression returns a set result.
757 * Because we use expression_tree_walker(), this can also be applied to
758 * whole targetlists; it'll produce TRUE if any one of the tlist items
762 expression_returns_set(Node *clause)
764 return expression_returns_set_walker(clause, NULL);
768 expression_returns_set_walker(Node *node, void *context)
772 if (IsA(node, FuncExpr))
774 FuncExpr *expr = (FuncExpr *) node;
776 if (expr->funcretset)
778 /* else fall through to check args */
780 if (IsA(node, OpExpr))
782 OpExpr *expr = (OpExpr *) node;
786 /* else fall through to check args */
789 /* Avoid recursion for some cases that can't return a set */
790 if (IsA(node, Aggref))
792 if (IsA(node, WindowFunc))
794 if (IsA(node, DistinctExpr))
796 if (IsA(node, ScalarArrayOpExpr))
798 if (IsA(node, BoolExpr))
800 if (IsA(node, SubLink))
802 if (IsA(node, SubPlan))
804 if (IsA(node, AlternativeSubPlan))
806 if (IsA(node, ArrayExpr))
808 if (IsA(node, RowExpr))
810 if (IsA(node, RowCompareExpr))
812 if (IsA(node, CoalesceExpr))
814 if (IsA(node, MinMaxExpr))
816 if (IsA(node, XmlExpr))
818 if (IsA(node, NullIfExpr))
821 return expression_tree_walker(node, expression_returns_set_walker,
828 * returns the parse location of an expression tree, for error reports
830 * -1 is returned if the location can't be determined.
832 * For expressions larger than a single token, the intent here is to
833 * return the location of the expression's leftmost token, not necessarily
834 * the topmost Node's location field. For example, an OpExpr's location
835 * field will point at the operator name, but if it is not a prefix operator
836 * then we should return the location of the left-hand operand instead.
837 * The reason is that we want to reference the entire expression not just
838 * that operator, and pointing to its start seems to be the most natural way.
840 * The location is not perfect --- for example, since the grammar doesn't
841 * explicitly represent parentheses in the parsetree, given something that
842 * had been written "(a + b) * c" we are going to point at "a" not "(".
843 * But it should be plenty good enough for error reporting purposes.
845 * You might think that this code is overly general, for instance why check
846 * the operands of a FuncExpr node, when the function name can be expected
847 * to be to the left of them? There are a couple of reasons. The grammar
848 * sometimes builds expressions that aren't quite what the user wrote;
849 * for instance x IS NOT BETWEEN ... becomes a NOT-expression whose keyword
850 * pointer is to the right of its leftmost argument. Also, nodes that were
851 * inserted implicitly by parse analysis (such as FuncExprs for implicit
852 * coercions) will have location -1, and so we can have odd combinations of
853 * known and unknown locations in a tree.
856 exprLocation(Node *expr)
862 switch (nodeTag(expr))
865 loc = ((RangeVar *) expr)->location;
868 loc = ((Var *) expr)->location;
871 loc = ((Const *) expr)->location;
874 loc = ((Param *) expr)->location;
877 /* function name should always be the first thing */
878 loc = ((Aggref *) expr)->location;
881 /* function name should always be the first thing */
882 loc = ((WindowFunc *) expr)->location;
885 /* just use array argument's location */
886 loc = exprLocation((Node *) ((ArrayRef *) expr)->refexpr);
890 FuncExpr *fexpr = (FuncExpr *) expr;
892 /* consider both function name and leftmost arg */
893 loc = leftmostLoc(fexpr->location,
894 exprLocation((Node *) fexpr->args));
899 NamedArgExpr *na = (NamedArgExpr *) expr;
901 /* consider both argument name and value */
902 loc = leftmostLoc(na->location,
903 exprLocation((Node *) na->arg));
907 case T_DistinctExpr: /* struct-equivalent to OpExpr */
908 case T_NullIfExpr: /* struct-equivalent to OpExpr */
910 OpExpr *opexpr = (OpExpr *) expr;
912 /* consider both operator name and leftmost arg */
913 loc = leftmostLoc(opexpr->location,
914 exprLocation((Node *) opexpr->args));
917 case T_ScalarArrayOpExpr:
919 ScalarArrayOpExpr *saopexpr = (ScalarArrayOpExpr *) expr;
921 /* consider both operator name and leftmost arg */
922 loc = leftmostLoc(saopexpr->location,
923 exprLocation((Node *) saopexpr->args));
928 BoolExpr *bexpr = (BoolExpr *) expr;
931 * Same as above, to handle either NOT or AND/OR. We can't
932 * special-case NOT because of the way that it's used for
933 * things like IS NOT BETWEEN.
935 loc = leftmostLoc(bexpr->location,
936 exprLocation((Node *) bexpr->args));
941 SubLink *sublink = (SubLink *) expr;
943 /* check the testexpr, if any, and the operator/keyword */
944 loc = leftmostLoc(exprLocation(sublink->testexpr),
949 /* just use argument's location */
950 loc = exprLocation((Node *) ((FieldSelect *) expr)->arg);
953 /* just use argument's location */
954 loc = exprLocation((Node *) ((FieldStore *) expr)->arg);
958 RelabelType *rexpr = (RelabelType *) expr;
961 loc = leftmostLoc(rexpr->location,
962 exprLocation((Node *) rexpr->arg));
967 CoerceViaIO *cexpr = (CoerceViaIO *) expr;
970 loc = leftmostLoc(cexpr->location,
971 exprLocation((Node *) cexpr->arg));
974 case T_ArrayCoerceExpr:
976 ArrayCoerceExpr *cexpr = (ArrayCoerceExpr *) expr;
979 loc = leftmostLoc(cexpr->location,
980 exprLocation((Node *) cexpr->arg));
983 case T_ConvertRowtypeExpr:
985 ConvertRowtypeExpr *cexpr = (ConvertRowtypeExpr *) expr;
988 loc = leftmostLoc(cexpr->location,
989 exprLocation((Node *) cexpr->arg));
993 /* CASE keyword should always be the first thing */
994 loc = ((CaseExpr *) expr)->location;
997 /* WHEN keyword should always be the first thing */
998 loc = ((CaseWhen *) expr)->location;
1001 /* the location points at ARRAY or [, which must be leftmost */
1002 loc = ((ArrayExpr *) expr)->location;
1005 /* the location points at ROW or (, which must be leftmost */
1006 loc = ((RowExpr *) expr)->location;
1008 case T_RowCompareExpr:
1009 /* just use leftmost argument's location */
1010 loc = exprLocation((Node *) ((RowCompareExpr *) expr)->largs);
1012 case T_CoalesceExpr:
1013 /* COALESCE keyword should always be the first thing */
1014 loc = ((CoalesceExpr *) expr)->location;
1017 /* GREATEST/LEAST keyword should always be the first thing */
1018 loc = ((MinMaxExpr *) expr)->location;
1022 XmlExpr *xexpr = (XmlExpr *) expr;
1024 /* consider both function name and leftmost arg */
1025 loc = leftmostLoc(xexpr->location,
1026 exprLocation((Node *) xexpr->args));
1030 /* just use argument's location */
1031 loc = exprLocation((Node *) ((NullTest *) expr)->arg);
1034 /* just use argument's location */
1035 loc = exprLocation((Node *) ((BooleanTest *) expr)->arg);
1037 case T_CoerceToDomain:
1039 CoerceToDomain *cexpr = (CoerceToDomain *) expr;
1042 loc = leftmostLoc(cexpr->location,
1043 exprLocation((Node *) cexpr->arg));
1046 case T_CoerceToDomainValue:
1047 loc = ((CoerceToDomainValue *) expr)->location;
1049 case T_SetToDefault:
1050 loc = ((SetToDefault *) expr)->location;
1053 /* just use argument's location */
1054 loc = exprLocation((Node *) ((TargetEntry *) expr)->expr);
1057 /* use the contained RangeVar's location --- close enough */
1058 loc = exprLocation((Node *) ((IntoClause *) expr)->rel);
1062 /* report location of first list member that has a location */
1065 loc = -1; /* just to suppress compiler warning */
1066 foreach(lc, (List *) expr)
1068 loc = exprLocation((Node *) lfirst(lc));
1076 A_Expr *aexpr = (A_Expr *) expr;
1078 /* use leftmost of operator or left operand (if any) */
1079 /* we assume right operand can't be to left of operator */
1080 loc = leftmostLoc(aexpr->location,
1081 exprLocation(aexpr->lexpr));
1085 loc = ((ColumnRef *) expr)->location;
1088 loc = ((ParamRef *) expr)->location;
1091 loc = ((A_Const *) expr)->location;
1095 FuncCall *fc = (FuncCall *) expr;
1097 /* consider both function name and leftmost arg */
1098 /* (we assume any ORDER BY nodes must be to right of name) */
1099 loc = leftmostLoc(fc->location,
1100 exprLocation((Node *) fc->args));
1104 /* the location points at ARRAY or [, which must be leftmost */
1105 loc = ((A_ArrayExpr *) expr)->location;
1108 /* we need not examine the contained expression (if any) */
1109 loc = ((ResTarget *) expr)->location;
1113 TypeCast *tc = (TypeCast *) expr;
1116 * This could represent CAST(), ::, or TypeName 'literal', so
1117 * any of the components might be leftmost.
1119 loc = exprLocation(tc->arg);
1120 loc = leftmostLoc(loc, tc->typeName->location);
1121 loc = leftmostLoc(loc, tc->location);
1124 case T_CollateClause:
1125 loc = ((CollateClause *) expr)->location;
1128 /* just use argument's location (ignore operator, if any) */
1129 loc = exprLocation(((SortBy *) expr)->node);
1132 loc = ((WindowDef *) expr)->location;
1135 loc = ((TypeName *) expr)->location;
1138 loc = ((Constraint *) expr)->location;
1140 case T_XmlSerialize:
1141 /* XMLSERIALIZE keyword should always be the first thing */
1142 loc = ((XmlSerialize *) expr)->location;
1145 loc = ((WithClause *) expr)->location;
1147 case T_CommonTableExpr:
1148 loc = ((CommonTableExpr *) expr)->location;
1150 case T_PlaceHolderVar:
1151 /* just use argument's location */
1152 loc = exprLocation((Node *) ((PlaceHolderVar *) expr)->phexpr);
1155 /* for any other node type it's just unknown... */
1163 * leftmostLoc - support for exprLocation
1165 * Take the minimum of two parse location values, but ignore unknowns
1168 leftmostLoc(int loc1, int loc2)
1175 return Min(loc1, loc2);
1180 * Standard expression-tree walking support
1182 * We used to have near-duplicate code in many different routines that
1183 * understood how to recurse through an expression node tree. That was
1184 * a pain to maintain, and we frequently had bugs due to some particular
1185 * routine neglecting to support a particular node type. In most cases,
1186 * these routines only actually care about certain node types, and don't
1187 * care about other types except insofar as they have to recurse through
1188 * non-primitive node types. Therefore, we now provide generic tree-walking
1189 * logic to consolidate the redundant "boilerplate" code. There are
1190 * two versions: expression_tree_walker() and expression_tree_mutator().
1194 * expression_tree_walker() is designed to support routines that traverse
1195 * a tree in a read-only fashion (although it will also work for routines
1196 * that modify nodes in-place but never add/delete/replace nodes).
1197 * A walker routine should look like this:
1199 * bool my_walker (Node *node, my_struct *context)
1203 * // check for nodes that special work is required for, eg:
1204 * if (IsA(node, Var))
1206 * ... do special actions for Var nodes
1208 * else if (IsA(node, ...))
1210 * ... do special actions for other node types
1212 * // for any node type not specially processed, do:
1213 * return expression_tree_walker(node, my_walker, (void *) context);
1216 * The "context" argument points to a struct that holds whatever context
1217 * information the walker routine needs --- it can be used to return data
1218 * gathered by the walker, too. This argument is not touched by
1219 * expression_tree_walker, but it is passed down to recursive sub-invocations
1220 * of my_walker. The tree walk is started from a setup routine that
1221 * fills in the appropriate context struct, calls my_walker with the top-level
1222 * node of the tree, and then examines the results.
1224 * The walker routine should return "false" to continue the tree walk, or
1225 * "true" to abort the walk and immediately return "true" to the top-level
1226 * caller. This can be used to short-circuit the traversal if the walker
1227 * has found what it came for. "false" is returned to the top-level caller
1228 * iff no invocation of the walker returned "true".
1230 * The node types handled by expression_tree_walker include all those
1231 * normally found in target lists and qualifier clauses during the planning
1232 * stage. In particular, it handles List nodes since a cnf-ified qual clause
1233 * will have List structure at the top level, and it handles TargetEntry nodes
1234 * so that a scan of a target list can be handled without additional code.
1235 * Also, RangeTblRef, FromExpr, JoinExpr, and SetOperationStmt nodes are
1236 * handled, so that query jointrees and setOperation trees can be processed
1237 * without additional code.
1239 * expression_tree_walker will handle SubLink nodes by recursing normally
1240 * into the "testexpr" subtree (which is an expression belonging to the outer
1241 * plan). It will also call the walker on the sub-Query node; however, when
1242 * expression_tree_walker itself is called on a Query node, it does nothing
1243 * and returns "false". The net effect is that unless the walker does
1244 * something special at a Query node, sub-selects will not be visited during
1245 * an expression tree walk. This is exactly the behavior wanted in many cases
1246 * --- and for those walkers that do want to recurse into sub-selects, special
1247 * behavior is typically needed anyway at the entry to a sub-select (such as
1248 * incrementing a depth counter). A walker that wants to examine sub-selects
1249 * should include code along the lines of:
1251 * if (IsA(node, Query))
1253 * adjust context for subquery;
1254 * result = query_tree_walker((Query *) node, my_walker, context,
1255 * 0); // adjust flags as needed
1256 * restore context if needed;
1260 * query_tree_walker is a convenience routine (see below) that calls the
1261 * walker on all the expression subtrees of the given Query node.
1263 * expression_tree_walker will handle SubPlan nodes by recursing normally
1264 * into the "testexpr" and the "args" list (which are expressions belonging to
1265 * the outer plan). It will not touch the completed subplan, however. Since
1266 * there is no link to the original Query, it is not possible to recurse into
1267 * subselects of an already-planned expression tree. This is OK for current
1268 * uses, but may need to be revisited in future.
1272 expression_tree_walker(Node *node,
1279 * The walker has already visited the current node, and so we need only
1280 * recurse into any sub-nodes it has.
1282 * We assume that the walker is not interested in List nodes per se, so
1283 * when we expect a List we just recurse directly to self without
1284 * bothering to call the walker.
1289 /* Guard against stack overflow due to overly complex expressions */
1290 check_stack_depth();
1292 switch (nodeTag(node))
1297 case T_CoerceToDomainValue:
1298 case T_CaseTestExpr:
1299 case T_SetToDefault:
1300 case T_CurrentOfExpr:
1302 case T_SortGroupClause:
1303 /* primitive node types with no expression subnodes */
1307 Aggref *expr = (Aggref *) node;
1309 /* recurse directly on List */
1310 if (expression_tree_walker((Node *) expr->args,
1313 if (expression_tree_walker((Node *) expr->aggorder,
1316 if (expression_tree_walker((Node *) expr->aggdistinct,
1323 WindowFunc *expr = (WindowFunc *) node;
1325 /* recurse directly on List */
1326 if (expression_tree_walker((Node *) expr->args,
1333 ArrayRef *aref = (ArrayRef *) node;
1335 /* recurse directly for upper/lower array index lists */
1336 if (expression_tree_walker((Node *) aref->refupperindexpr,
1339 if (expression_tree_walker((Node *) aref->reflowerindexpr,
1342 /* walker must see the refexpr and refassgnexpr, however */
1343 if (walker(aref->refexpr, context))
1345 if (walker(aref->refassgnexpr, context))
1351 FuncExpr *expr = (FuncExpr *) node;
1353 if (expression_tree_walker((Node *) expr->args,
1358 case T_NamedArgExpr:
1359 return walker(((NamedArgExpr *) node)->arg, context);
1362 OpExpr *expr = (OpExpr *) node;
1364 if (expression_tree_walker((Node *) expr->args,
1369 case T_DistinctExpr:
1371 DistinctExpr *expr = (DistinctExpr *) node;
1373 if (expression_tree_walker((Node *) expr->args,
1378 case T_ScalarArrayOpExpr:
1380 ScalarArrayOpExpr *expr = (ScalarArrayOpExpr *) node;
1382 if (expression_tree_walker((Node *) expr->args,
1389 BoolExpr *expr = (BoolExpr *) node;
1391 if (expression_tree_walker((Node *) expr->args,
1398 SubLink *sublink = (SubLink *) node;
1400 if (walker(sublink->testexpr, context))
1404 * Also invoke the walker on the sublink's Query node, so it
1405 * can recurse into the sub-query if it wants to.
1407 return walker(sublink->subselect, context);
1412 SubPlan *subplan = (SubPlan *) node;
1414 /* recurse into the testexpr, but not into the Plan */
1415 if (walker(subplan->testexpr, context))
1417 /* also examine args list */
1418 if (expression_tree_walker((Node *) subplan->args,
1423 case T_AlternativeSubPlan:
1424 return walker(((AlternativeSubPlan *) node)->subplans, context);
1426 return walker(((FieldSelect *) node)->arg, context);
1429 FieldStore *fstore = (FieldStore *) node;
1431 if (walker(fstore->arg, context))
1433 if (walker(fstore->newvals, context))
1438 return walker(((RelabelType *) node)->arg, context);
1439 case T_CollateClause:
1440 return walker(((CollateClause *) node)->arg, context);
1442 return walker(((CoerceViaIO *) node)->arg, context);
1443 case T_ArrayCoerceExpr:
1444 return walker(((ArrayCoerceExpr *) node)->arg, context);
1445 case T_ConvertRowtypeExpr:
1446 return walker(((ConvertRowtypeExpr *) node)->arg, context);
1449 CaseExpr *caseexpr = (CaseExpr *) node;
1451 if (walker(caseexpr->arg, context))
1453 /* we assume walker doesn't care about CaseWhens, either */
1454 foreach(temp, caseexpr->args)
1456 CaseWhen *when = (CaseWhen *) lfirst(temp);
1458 Assert(IsA(when, CaseWhen));
1459 if (walker(when->expr, context))
1461 if (walker(when->result, context))
1464 if (walker(caseexpr->defresult, context))
1469 return walker(((ArrayExpr *) node)->elements, context);
1471 /* Assume colnames isn't interesting */
1472 return walker(((RowExpr *) node)->args, context);
1473 case T_RowCompareExpr:
1475 RowCompareExpr *rcexpr = (RowCompareExpr *) node;
1477 if (walker(rcexpr->largs, context))
1479 if (walker(rcexpr->rargs, context))
1483 case T_CoalesceExpr:
1484 return walker(((CoalesceExpr *) node)->args, context);
1486 return walker(((MinMaxExpr *) node)->args, context);
1489 XmlExpr *xexpr = (XmlExpr *) node;
1491 if (walker(xexpr->named_args, context))
1493 /* we assume walker doesn't care about arg_names */
1494 if (walker(xexpr->args, context))
1499 return walker(((NullIfExpr *) node)->args, context);
1501 return walker(((NullTest *) node)->arg, context);
1503 return walker(((BooleanTest *) node)->arg, context);
1504 case T_CoerceToDomain:
1505 return walker(((CoerceToDomain *) node)->arg, context);
1507 return walker(((TargetEntry *) node)->expr, context);
1509 /* Do nothing with a sub-Query, per discussion above */
1511 case T_WindowClause:
1513 WindowClause *wc = (WindowClause *) node;
1515 if (walker(wc->partitionClause, context))
1517 if (walker(wc->orderClause, context))
1519 if (walker(wc->startOffset, context))
1521 if (walker(wc->endOffset, context))
1525 case T_CommonTableExpr:
1527 CommonTableExpr *cte = (CommonTableExpr *) node;
1530 * Invoke the walker on the CTE's Query node, so it can
1531 * recurse into the sub-query if it wants to.
1533 return walker(cte->ctequery, context);
1537 foreach(temp, (List *) node)
1539 if (walker((Node *) lfirst(temp), context))
1545 FromExpr *from = (FromExpr *) node;
1547 if (walker(from->fromlist, context))
1549 if (walker(from->quals, context))
1555 JoinExpr *join = (JoinExpr *) node;
1557 if (walker(join->larg, context))
1559 if (walker(join->rarg, context))
1561 if (walker(join->quals, context))
1565 * alias clause, using list are deemed uninteresting.
1569 case T_SetOperationStmt:
1571 SetOperationStmt *setop = (SetOperationStmt *) node;
1573 if (walker(setop->larg, context))
1575 if (walker(setop->rarg, context))
1578 /* groupClauses are deemed uninteresting */
1581 case T_PlaceHolderVar:
1582 return walker(((PlaceHolderVar *) node)->phexpr, context);
1583 case T_AppendRelInfo:
1585 AppendRelInfo *appinfo = (AppendRelInfo *) node;
1587 if (expression_tree_walker((Node *) appinfo->translated_vars,
1592 case T_PlaceHolderInfo:
1593 return walker(((PlaceHolderInfo *) node)->ph_var, context);
1595 elog(ERROR, "unrecognized node type: %d",
1596 (int) nodeTag(node));
1603 * query_tree_walker --- initiate a walk of a Query's expressions
1605 * This routine exists just to reduce the number of places that need to know
1606 * where all the expression subtrees of a Query are. Note it can be used
1607 * for starting a walk at top level of a Query regardless of whether the
1608 * walker intends to descend into subqueries. It is also useful for
1609 * descending into subqueries within a walker.
1611 * Some callers want to suppress visitation of certain items in the sub-Query,
1612 * typically because they need to process them specially, or don't actually
1613 * want to recurse into subqueries. This is supported by the flags argument,
1614 * which is the bitwise OR of flag values to suppress visitation of
1615 * indicated items. (More flag bits may be added as needed.)
1618 query_tree_walker(Query *query,
1623 Assert(query != NULL && IsA(query, Query));
1625 if (walker((Node *) query->targetList, context))
1627 if (walker((Node *) query->returningList, context))
1629 if (walker((Node *) query->jointree, context))
1631 if (walker(query->setOperations, context))
1633 if (walker(query->havingQual, context))
1635 if (walker(query->limitOffset, context))
1637 if (walker(query->limitCount, context))
1639 if (!(flags & QTW_IGNORE_CTE_SUBQUERIES))
1641 if (walker((Node *) query->cteList, context))
1644 if (range_table_walker(query->rtable, walker, context, flags))
1650 * range_table_walker is just the part of query_tree_walker that scans
1651 * a query's rangetable. This is split out since it can be useful on
1655 range_table_walker(List *rtable,
1664 RangeTblEntry *rte = (RangeTblEntry *) lfirst(rt);
1666 /* For historical reasons, visiting RTEs is not the default */
1667 if (flags & QTW_EXAMINE_RTES)
1668 if (walker(rte, context))
1671 switch (rte->rtekind)
1679 if (!(flags & QTW_IGNORE_RT_SUBQUERIES))
1680 if (walker(rte->subquery, context))
1684 if (!(flags & QTW_IGNORE_JOINALIASES))
1685 if (walker(rte->joinaliasvars, context))
1689 if (walker(rte->funcexpr, context))
1693 if (walker(rte->values_lists, context))
1703 * expression_tree_mutator() is designed to support routines that make a
1704 * modified copy of an expression tree, with some nodes being added,
1705 * removed, or replaced by new subtrees. The original tree is (normally)
1706 * not changed. Each recursion level is responsible for returning a copy of
1707 * (or appropriately modified substitute for) the subtree it is handed.
1708 * A mutator routine should look like this:
1710 * Node * my_mutator (Node *node, my_struct *context)
1714 * // check for nodes that special work is required for, eg:
1715 * if (IsA(node, Var))
1717 * ... create and return modified copy of Var node
1719 * else if (IsA(node, ...))
1721 * ... do special transformations of other node types
1723 * // for any node type not specially processed, do:
1724 * return expression_tree_mutator(node, my_mutator, (void *) context);
1727 * The "context" argument points to a struct that holds whatever context
1728 * information the mutator routine needs --- it can be used to return extra
1729 * data gathered by the mutator, too. This argument is not touched by
1730 * expression_tree_mutator, but it is passed down to recursive sub-invocations
1731 * of my_mutator. The tree walk is started from a setup routine that
1732 * fills in the appropriate context struct, calls my_mutator with the
1733 * top-level node of the tree, and does any required post-processing.
1735 * Each level of recursion must return an appropriately modified Node.
1736 * If expression_tree_mutator() is called, it will make an exact copy
1737 * of the given Node, but invoke my_mutator() to copy the sub-node(s)
1738 * of that Node. In this way, my_mutator() has full control over the
1739 * copying process but need not directly deal with expression trees
1740 * that it has no interest in.
1742 * Just as for expression_tree_walker, the node types handled by
1743 * expression_tree_mutator include all those normally found in target lists
1744 * and qualifier clauses during the planning stage.
1746 * expression_tree_mutator will handle SubLink nodes by recursing normally
1747 * into the "testexpr" subtree (which is an expression belonging to the outer
1748 * plan). It will also call the mutator on the sub-Query node; however, when
1749 * expression_tree_mutator itself is called on a Query node, it does nothing
1750 * and returns the unmodified Query node. The net effect is that unless the
1751 * mutator does something special at a Query node, sub-selects will not be
1752 * visited or modified; the original sub-select will be linked to by the new
1753 * SubLink node. Mutators that want to descend into sub-selects will usually
1754 * do so by recognizing Query nodes and calling query_tree_mutator (below).
1756 * expression_tree_mutator will handle a SubPlan node by recursing into the
1757 * "testexpr" and the "args" list (which belong to the outer plan), but it
1758 * will simply copy the link to the inner plan, since that's typically what
1759 * expression tree mutators want. A mutator that wants to modify the subplan
1760 * can force appropriate behavior by recognizing SubPlan expression nodes
1761 * and doing the right thing.
1765 expression_tree_mutator(Node *node,
1766 Node *(*mutator) (),
1770 * The mutator has already decided not to modify the current node, but we
1771 * must call the mutator for any sub-nodes.
1774 #define FLATCOPY(newnode, node, nodetype) \
1775 ( (newnode) = (nodetype *) palloc(sizeof(nodetype)), \
1776 memcpy((newnode), (node), sizeof(nodetype)) )
1778 #define CHECKFLATCOPY(newnode, node, nodetype) \
1779 ( AssertMacro(IsA((node), nodetype)), \
1780 (newnode) = (nodetype *) palloc(sizeof(nodetype)), \
1781 memcpy((newnode), (node), sizeof(nodetype)) )
1783 #define MUTATE(newfield, oldfield, fieldtype) \
1784 ( (newfield) = (fieldtype) mutator((Node *) (oldfield), context) )
1789 /* Guard against stack overflow due to overly complex expressions */
1790 check_stack_depth();
1792 switch (nodeTag(node))
1795 * Primitive node types with no expression subnodes. Var and
1796 * Const are frequent enough to deserve special cases, the others
1797 * we just use copyObject for.
1801 Var *var = (Var *) node;
1804 FLATCOPY(newnode, var, Var);
1805 return (Node *) newnode;
1810 Const *oldnode = (Const *) node;
1813 FLATCOPY(newnode, oldnode, Const);
1814 /* XXX we don't bother with datumCopy; should we? */
1815 return (Node *) newnode;
1819 case T_CoerceToDomainValue:
1820 case T_CaseTestExpr:
1821 case T_SetToDefault:
1822 case T_CurrentOfExpr:
1824 case T_SortGroupClause:
1825 return (Node *) copyObject(node);
1828 Aggref *aggref = (Aggref *) node;
1831 FLATCOPY(newnode, aggref, Aggref);
1832 MUTATE(newnode->args, aggref->args, List *);
1833 MUTATE(newnode->aggorder, aggref->aggorder, List *);
1834 MUTATE(newnode->aggdistinct, aggref->aggdistinct, List *);
1835 return (Node *) newnode;
1840 WindowFunc *wfunc = (WindowFunc *) node;
1841 WindowFunc *newnode;
1843 FLATCOPY(newnode, wfunc, WindowFunc);
1844 MUTATE(newnode->args, wfunc->args, List *);
1845 return (Node *) newnode;
1850 ArrayRef *arrayref = (ArrayRef *) node;
1853 FLATCOPY(newnode, arrayref, ArrayRef);
1854 MUTATE(newnode->refupperindexpr, arrayref->refupperindexpr,
1856 MUTATE(newnode->reflowerindexpr, arrayref->reflowerindexpr,
1858 MUTATE(newnode->refexpr, arrayref->refexpr,
1860 MUTATE(newnode->refassgnexpr, arrayref->refassgnexpr,
1862 return (Node *) newnode;
1867 FuncExpr *expr = (FuncExpr *) node;
1870 FLATCOPY(newnode, expr, FuncExpr);
1871 MUTATE(newnode->args, expr->args, List *);
1872 return (Node *) newnode;
1875 case T_NamedArgExpr:
1877 NamedArgExpr *nexpr = (NamedArgExpr *) node;
1878 NamedArgExpr *newnode;
1880 FLATCOPY(newnode, nexpr, NamedArgExpr);
1881 MUTATE(newnode->arg, nexpr->arg, Expr *);
1882 return (Node *) newnode;
1887 OpExpr *expr = (OpExpr *) node;
1890 FLATCOPY(newnode, expr, OpExpr);
1891 MUTATE(newnode->args, expr->args, List *);
1892 return (Node *) newnode;
1895 case T_DistinctExpr:
1897 DistinctExpr *expr = (DistinctExpr *) node;
1898 DistinctExpr *newnode;
1900 FLATCOPY(newnode, expr, DistinctExpr);
1901 MUTATE(newnode->args, expr->args, List *);
1902 return (Node *) newnode;
1905 case T_ScalarArrayOpExpr:
1907 ScalarArrayOpExpr *expr = (ScalarArrayOpExpr *) node;
1908 ScalarArrayOpExpr *newnode;
1910 FLATCOPY(newnode, expr, ScalarArrayOpExpr);
1911 MUTATE(newnode->args, expr->args, List *);
1912 return (Node *) newnode;
1917 BoolExpr *expr = (BoolExpr *) node;
1920 FLATCOPY(newnode, expr, BoolExpr);
1921 MUTATE(newnode->args, expr->args, List *);
1922 return (Node *) newnode;
1927 SubLink *sublink = (SubLink *) node;
1930 FLATCOPY(newnode, sublink, SubLink);
1931 MUTATE(newnode->testexpr, sublink->testexpr, Node *);
1934 * Also invoke the mutator on the sublink's Query node, so it
1935 * can recurse into the sub-query if it wants to.
1937 MUTATE(newnode->subselect, sublink->subselect, Node *);
1938 return (Node *) newnode;
1943 SubPlan *subplan = (SubPlan *) node;
1946 FLATCOPY(newnode, subplan, SubPlan);
1947 /* transform testexpr */
1948 MUTATE(newnode->testexpr, subplan->testexpr, Node *);
1949 /* transform args list (params to be passed to subplan) */
1950 MUTATE(newnode->args, subplan->args, List *);
1951 /* but not the sub-Plan itself, which is referenced as-is */
1952 return (Node *) newnode;
1955 case T_AlternativeSubPlan:
1957 AlternativeSubPlan *asplan = (AlternativeSubPlan *) node;
1958 AlternativeSubPlan *newnode;
1960 FLATCOPY(newnode, asplan, AlternativeSubPlan);
1961 MUTATE(newnode->subplans, asplan->subplans, List *);
1962 return (Node *) newnode;
1967 FieldSelect *fselect = (FieldSelect *) node;
1968 FieldSelect *newnode;
1970 FLATCOPY(newnode, fselect, FieldSelect);
1971 MUTATE(newnode->arg, fselect->arg, Expr *);
1972 return (Node *) newnode;
1977 FieldStore *fstore = (FieldStore *) node;
1978 FieldStore *newnode;
1980 FLATCOPY(newnode, fstore, FieldStore);
1981 MUTATE(newnode->arg, fstore->arg, Expr *);
1982 MUTATE(newnode->newvals, fstore->newvals, List *);
1983 newnode->fieldnums = list_copy(fstore->fieldnums);
1984 return (Node *) newnode;
1989 RelabelType *relabel = (RelabelType *) node;
1990 RelabelType *newnode;
1992 FLATCOPY(newnode, relabel, RelabelType);
1993 MUTATE(newnode->arg, relabel->arg, Expr *);
1994 return (Node *) newnode;
1997 case T_CollateClause:
1999 CollateClause *collate = (CollateClause *) node;
2000 CollateClause *newnode;
2002 FLATCOPY(newnode, collate, CollateClause);
2003 MUTATE(newnode->arg, collate->arg, Expr *);
2004 return (Node *) newnode;
2009 CoerceViaIO *iocoerce = (CoerceViaIO *) node;
2010 CoerceViaIO *newnode;
2012 FLATCOPY(newnode, iocoerce, CoerceViaIO);
2013 MUTATE(newnode->arg, iocoerce->arg, Expr *);
2014 return (Node *) newnode;
2017 case T_ArrayCoerceExpr:
2019 ArrayCoerceExpr *acoerce = (ArrayCoerceExpr *) node;
2020 ArrayCoerceExpr *newnode;
2022 FLATCOPY(newnode, acoerce, ArrayCoerceExpr);
2023 MUTATE(newnode->arg, acoerce->arg, Expr *);
2024 return (Node *) newnode;
2027 case T_ConvertRowtypeExpr:
2029 ConvertRowtypeExpr *convexpr = (ConvertRowtypeExpr *) node;
2030 ConvertRowtypeExpr *newnode;
2032 FLATCOPY(newnode, convexpr, ConvertRowtypeExpr);
2033 MUTATE(newnode->arg, convexpr->arg, Expr *);
2034 return (Node *) newnode;
2039 CaseExpr *caseexpr = (CaseExpr *) node;
2042 FLATCOPY(newnode, caseexpr, CaseExpr);
2043 MUTATE(newnode->arg, caseexpr->arg, Expr *);
2044 MUTATE(newnode->args, caseexpr->args, List *);
2045 MUTATE(newnode->defresult, caseexpr->defresult, Expr *);
2046 return (Node *) newnode;
2051 CaseWhen *casewhen = (CaseWhen *) node;
2054 FLATCOPY(newnode, casewhen, CaseWhen);
2055 MUTATE(newnode->expr, casewhen->expr, Expr *);
2056 MUTATE(newnode->result, casewhen->result, Expr *);
2057 return (Node *) newnode;
2062 ArrayExpr *arrayexpr = (ArrayExpr *) node;
2065 FLATCOPY(newnode, arrayexpr, ArrayExpr);
2066 MUTATE(newnode->elements, arrayexpr->elements, List *);
2067 return (Node *) newnode;
2072 RowExpr *rowexpr = (RowExpr *) node;
2075 FLATCOPY(newnode, rowexpr, RowExpr);
2076 MUTATE(newnode->args, rowexpr->args, List *);
2077 /* Assume colnames needn't be duplicated */
2078 return (Node *) newnode;
2081 case T_RowCompareExpr:
2083 RowCompareExpr *rcexpr = (RowCompareExpr *) node;
2084 RowCompareExpr *newnode;
2086 FLATCOPY(newnode, rcexpr, RowCompareExpr);
2087 MUTATE(newnode->largs, rcexpr->largs, List *);
2088 MUTATE(newnode->rargs, rcexpr->rargs, List *);
2089 return (Node *) newnode;
2092 case T_CoalesceExpr:
2094 CoalesceExpr *coalesceexpr = (CoalesceExpr *) node;
2095 CoalesceExpr *newnode;
2097 FLATCOPY(newnode, coalesceexpr, CoalesceExpr);
2098 MUTATE(newnode->args, coalesceexpr->args, List *);
2099 return (Node *) newnode;
2104 MinMaxExpr *minmaxexpr = (MinMaxExpr *) node;
2105 MinMaxExpr *newnode;
2107 FLATCOPY(newnode, minmaxexpr, MinMaxExpr);
2108 MUTATE(newnode->args, minmaxexpr->args, List *);
2109 return (Node *) newnode;
2114 XmlExpr *xexpr = (XmlExpr *) node;
2117 FLATCOPY(newnode, xexpr, XmlExpr);
2118 MUTATE(newnode->named_args, xexpr->named_args, List *);
2119 /* assume mutator does not care about arg_names */
2120 MUTATE(newnode->args, xexpr->args, List *);
2121 return (Node *) newnode;
2126 NullIfExpr *expr = (NullIfExpr *) node;
2127 NullIfExpr *newnode;
2129 FLATCOPY(newnode, expr, NullIfExpr);
2130 MUTATE(newnode->args, expr->args, List *);
2131 return (Node *) newnode;
2136 NullTest *ntest = (NullTest *) node;
2139 FLATCOPY(newnode, ntest, NullTest);
2140 MUTATE(newnode->arg, ntest->arg, Expr *);
2141 return (Node *) newnode;
2146 BooleanTest *btest = (BooleanTest *) node;
2147 BooleanTest *newnode;
2149 FLATCOPY(newnode, btest, BooleanTest);
2150 MUTATE(newnode->arg, btest->arg, Expr *);
2151 return (Node *) newnode;
2154 case T_CoerceToDomain:
2156 CoerceToDomain *ctest = (CoerceToDomain *) node;
2157 CoerceToDomain *newnode;
2159 FLATCOPY(newnode, ctest, CoerceToDomain);
2160 MUTATE(newnode->arg, ctest->arg, Expr *);
2161 return (Node *) newnode;
2166 TargetEntry *targetentry = (TargetEntry *) node;
2167 TargetEntry *newnode;
2169 FLATCOPY(newnode, targetentry, TargetEntry);
2170 MUTATE(newnode->expr, targetentry->expr, Expr *);
2171 return (Node *) newnode;
2175 /* Do nothing with a sub-Query, per discussion above */
2177 case T_WindowClause:
2179 WindowClause *wc = (WindowClause *) node;
2180 WindowClause *newnode;
2182 FLATCOPY(newnode, wc, WindowClause);
2183 MUTATE(newnode->partitionClause, wc->partitionClause, List *);
2184 MUTATE(newnode->orderClause, wc->orderClause, List *);
2185 MUTATE(newnode->startOffset, wc->startOffset, Node *);
2186 MUTATE(newnode->endOffset, wc->endOffset, Node *);
2187 return (Node *) newnode;
2190 case T_CommonTableExpr:
2192 CommonTableExpr *cte = (CommonTableExpr *) node;
2193 CommonTableExpr *newnode;
2195 FLATCOPY(newnode, cte, CommonTableExpr);
2198 * Also invoke the mutator on the CTE's Query node, so it can
2199 * recurse into the sub-query if it wants to.
2201 MUTATE(newnode->ctequery, cte->ctequery, Node *);
2202 return (Node *) newnode;
2208 * We assume the mutator isn't interested in the list nodes
2209 * per se, so just invoke it on each list element. NOTE: this
2210 * would fail badly on a list with integer elements!
2216 foreach(temp, (List *) node)
2218 resultlist = lappend(resultlist,
2219 mutator((Node *) lfirst(temp),
2222 return (Node *) resultlist;
2227 FromExpr *from = (FromExpr *) node;
2230 FLATCOPY(newnode, from, FromExpr);
2231 MUTATE(newnode->fromlist, from->fromlist, List *);
2232 MUTATE(newnode->quals, from->quals, Node *);
2233 return (Node *) newnode;
2238 JoinExpr *join = (JoinExpr *) node;
2241 FLATCOPY(newnode, join, JoinExpr);
2242 MUTATE(newnode->larg, join->larg, Node *);
2243 MUTATE(newnode->rarg, join->rarg, Node *);
2244 MUTATE(newnode->quals, join->quals, Node *);
2245 /* We do not mutate alias or using by default */
2246 return (Node *) newnode;
2249 case T_SetOperationStmt:
2251 SetOperationStmt *setop = (SetOperationStmt *) node;
2252 SetOperationStmt *newnode;
2254 FLATCOPY(newnode, setop, SetOperationStmt);
2255 MUTATE(newnode->larg, setop->larg, Node *);
2256 MUTATE(newnode->rarg, setop->rarg, Node *);
2257 /* We do not mutate groupClauses by default */
2258 return (Node *) newnode;
2261 case T_PlaceHolderVar:
2263 PlaceHolderVar *phv = (PlaceHolderVar *) node;
2264 PlaceHolderVar *newnode;
2266 FLATCOPY(newnode, phv, PlaceHolderVar);
2267 MUTATE(newnode->phexpr, phv->phexpr, Expr *);
2268 /* Assume we need not copy the relids bitmapset */
2269 return (Node *) newnode;
2272 case T_AppendRelInfo:
2274 AppendRelInfo *appinfo = (AppendRelInfo *) node;
2275 AppendRelInfo *newnode;
2277 FLATCOPY(newnode, appinfo, AppendRelInfo);
2278 MUTATE(newnode->translated_vars, appinfo->translated_vars, List *);
2279 return (Node *) newnode;
2282 case T_PlaceHolderInfo:
2284 PlaceHolderInfo *phinfo = (PlaceHolderInfo *) node;
2285 PlaceHolderInfo *newnode;
2287 FLATCOPY(newnode, phinfo, PlaceHolderInfo);
2288 MUTATE(newnode->ph_var, phinfo->ph_var, PlaceHolderVar *);
2289 /* Assume we need not copy the relids bitmapsets */
2290 return (Node *) newnode;
2294 elog(ERROR, "unrecognized node type: %d",
2295 (int) nodeTag(node));
2298 /* can't get here, but keep compiler happy */
2304 * query_tree_mutator --- initiate modification of a Query's expressions
2306 * This routine exists just to reduce the number of places that need to know
2307 * where all the expression subtrees of a Query are. Note it can be used
2308 * for starting a walk at top level of a Query regardless of whether the
2309 * mutator intends to descend into subqueries. It is also useful for
2310 * descending into subqueries within a mutator.
2312 * Some callers want to suppress mutating of certain items in the Query,
2313 * typically because they need to process them specially, or don't actually
2314 * want to recurse into subqueries. This is supported by the flags argument,
2315 * which is the bitwise OR of flag values to suppress mutating of
2316 * indicated items. (More flag bits may be added as needed.)
2318 * Normally the Query node itself is copied, but some callers want it to be
2319 * modified in-place; they must pass QTW_DONT_COPY_QUERY in flags. All
2320 * modified substructure is safely copied in any case.
2323 query_tree_mutator(Query *query,
2324 Node *(*mutator) (),
2328 Assert(query != NULL && IsA(query, Query));
2330 if (!(flags & QTW_DONT_COPY_QUERY))
2334 FLATCOPY(newquery, query, Query);
2338 MUTATE(query->targetList, query->targetList, List *);
2339 MUTATE(query->returningList, query->returningList, List *);
2340 MUTATE(query->jointree, query->jointree, FromExpr *);
2341 MUTATE(query->setOperations, query->setOperations, Node *);
2342 MUTATE(query->havingQual, query->havingQual, Node *);
2343 MUTATE(query->limitOffset, query->limitOffset, Node *);
2344 MUTATE(query->limitCount, query->limitCount, Node *);
2345 if (!(flags & QTW_IGNORE_CTE_SUBQUERIES))
2346 MUTATE(query->cteList, query->cteList, List *);
2347 else /* else copy CTE list as-is */
2348 query->cteList = copyObject(query->cteList);
2349 query->rtable = range_table_mutator(query->rtable,
2350 mutator, context, flags);
2355 * range_table_mutator is just the part of query_tree_mutator that processes
2356 * a query's rangetable. This is split out since it can be useful on
2360 range_table_mutator(List *rtable,
2361 Node *(*mutator) (),
2370 RangeTblEntry *rte = (RangeTblEntry *) lfirst(rt);
2371 RangeTblEntry *newrte;
2373 FLATCOPY(newrte, rte, RangeTblEntry);
2374 switch (rte->rtekind)
2379 /* we don't bother to copy eref, aliases, etc; OK? */
2382 if (!(flags & QTW_IGNORE_RT_SUBQUERIES))
2384 CHECKFLATCOPY(newrte->subquery, rte->subquery, Query);
2385 MUTATE(newrte->subquery, newrte->subquery, Query *);
2389 /* else, copy RT subqueries as-is */
2390 newrte->subquery = copyObject(rte->subquery);
2394 if (!(flags & QTW_IGNORE_JOINALIASES))
2395 MUTATE(newrte->joinaliasvars, rte->joinaliasvars, List *);
2398 /* else, copy join aliases as-is */
2399 newrte->joinaliasvars = copyObject(rte->joinaliasvars);
2403 MUTATE(newrte->funcexpr, rte->funcexpr, Node *);
2406 MUTATE(newrte->values_lists, rte->values_lists, List *);
2409 newrt = lappend(newrt, newrte);
2415 * query_or_expression_tree_walker --- hybrid form
2417 * This routine will invoke query_tree_walker if called on a Query node,
2418 * else will invoke the walker directly. This is a useful way of starting
2419 * the recursion when the walker's normal change of state is not appropriate
2420 * for the outermost Query node.
2423 query_or_expression_tree_walker(Node *node,
2428 if (node && IsA(node, Query))
2429 return query_tree_walker((Query *) node,
2434 return walker(node, context);
2438 * query_or_expression_tree_mutator --- hybrid form
2440 * This routine will invoke query_tree_mutator if called on a Query node,
2441 * else will invoke the mutator directly. This is a useful way of starting
2442 * the recursion when the mutator's normal change of state is not appropriate
2443 * for the outermost Query node.
2446 query_or_expression_tree_mutator(Node *node,
2447 Node *(*mutator) (),
2451 if (node && IsA(node, Query))
2452 return (Node *) query_tree_mutator((Query *) node,
2457 return mutator(node, context);
2462 * raw_expression_tree_walker --- walk raw parse trees
2464 * This has exactly the same API as expression_tree_walker, but instead of
2465 * walking post-analysis parse trees, it knows how to walk the node types
2466 * found in raw grammar output. (There is not currently any need for a
2467 * combined walker, so we keep them separate in the name of efficiency.)
2468 * Unlike expression_tree_walker, there is no special rule about query
2469 * boundaries: we descend to everything that's possibly interesting.
2471 * Currently, the node type coverage extends to SelectStmt and everything
2472 * that could appear under it, but not other statement types.
2475 raw_expression_tree_walker(Node *node, bool (*walker) (), void *context)
2480 * The walker has already visited the current node, and so we need only
2481 * recurse into any sub-nodes it has.
2486 /* Guard against stack overflow due to overly complex expressions */
2487 check_stack_depth();
2489 switch (nodeTag(node))
2491 case T_SetToDefault:
2492 case T_CurrentOfExpr:
2501 /* primitive node types with no subnodes */
2504 /* we assume the colnames list isn't interesting */
2507 return walker(((RangeVar *) node)->alias, context);
2510 SubLink *sublink = (SubLink *) node;
2512 if (walker(sublink->testexpr, context))
2514 /* we assume the operName is not interesting */
2515 if (walker(sublink->subselect, context))
2521 CaseExpr *caseexpr = (CaseExpr *) node;
2523 if (walker(caseexpr->arg, context))
2525 /* we assume walker doesn't care about CaseWhens, either */
2526 foreach(temp, caseexpr->args)
2528 CaseWhen *when = (CaseWhen *) lfirst(temp);
2530 Assert(IsA(when, CaseWhen));
2531 if (walker(when->expr, context))
2533 if (walker(when->result, context))
2536 if (walker(caseexpr->defresult, context))
2541 /* Assume colnames isn't interesting */
2542 return walker(((RowExpr *) node)->args, context);
2543 case T_CoalesceExpr:
2544 return walker(((CoalesceExpr *) node)->args, context);
2546 return walker(((MinMaxExpr *) node)->args, context);
2549 XmlExpr *xexpr = (XmlExpr *) node;
2551 if (walker(xexpr->named_args, context))
2553 /* we assume walker doesn't care about arg_names */
2554 if (walker(xexpr->args, context))
2559 return walker(((NullTest *) node)->arg, context);
2561 return walker(((BooleanTest *) node)->arg, context);
2564 JoinExpr *join = (JoinExpr *) node;
2566 if (walker(join->larg, context))
2568 if (walker(join->rarg, context))
2570 if (walker(join->quals, context))
2572 if (walker(join->alias, context))
2574 /* using list is deemed uninteresting */
2579 IntoClause *into = (IntoClause *) node;
2581 if (walker(into->rel, context))
2583 /* colNames, options are deemed uninteresting */
2587 foreach(temp, (List *) node)
2589 if (walker((Node *) lfirst(temp), context))
2595 SelectStmt *stmt = (SelectStmt *) node;
2597 if (walker(stmt->distinctClause, context))
2599 if (walker(stmt->intoClause, context))
2601 if (walker(stmt->targetList, context))
2603 if (walker(stmt->fromClause, context))
2605 if (walker(stmt->whereClause, context))
2607 if (walker(stmt->groupClause, context))
2609 if (walker(stmt->havingClause, context))
2611 if (walker(stmt->windowClause, context))
2613 if (walker(stmt->withClause, context))
2615 if (walker(stmt->valuesLists, context))
2617 if (walker(stmt->sortClause, context))
2619 if (walker(stmt->limitOffset, context))
2621 if (walker(stmt->limitCount, context))
2623 if (walker(stmt->lockingClause, context))
2625 if (walker(stmt->larg, context))
2627 if (walker(stmt->rarg, context))
2633 A_Expr *expr = (A_Expr *) node;
2635 if (walker(expr->lexpr, context))
2637 if (walker(expr->rexpr, context))
2639 /* operator name is deemed uninteresting */
2643 /* we assume the fields contain nothing interesting */
2647 FuncCall *fcall = (FuncCall *) node;
2649 if (walker(fcall->args, context))
2651 if (walker(fcall->agg_order, context))
2653 if (walker(fcall->over, context))
2655 /* function name is deemed uninteresting */
2658 case T_NamedArgExpr:
2659 return walker(((NamedArgExpr *) node)->arg, context);
2662 A_Indices *indices = (A_Indices *) node;
2664 if (walker(indices->lidx, context))
2666 if (walker(indices->uidx, context))
2670 case T_A_Indirection:
2672 A_Indirection *indir = (A_Indirection *) node;
2674 if (walker(indir->arg, context))
2676 if (walker(indir->indirection, context))
2681 return walker(((A_ArrayExpr *) node)->elements, context);
2684 ResTarget *rt = (ResTarget *) node;
2686 if (walker(rt->indirection, context))
2688 if (walker(rt->val, context))
2694 TypeCast *tc = (TypeCast *) node;
2696 if (walker(tc->arg, context))
2698 if (walker(tc->typeName, context))
2702 case T_CollateClause:
2703 return walker(((CollateClause *) node)->arg, context);
2705 return walker(((SortBy *) node)->node, context);
2708 WindowDef *wd = (WindowDef *) node;
2710 if (walker(wd->partitionClause, context))
2712 if (walker(wd->orderClause, context))
2714 if (walker(wd->startOffset, context))
2716 if (walker(wd->endOffset, context))
2720 case T_RangeSubselect:
2722 RangeSubselect *rs = (RangeSubselect *) node;
2724 if (walker(rs->subquery, context))
2726 if (walker(rs->alias, context))
2730 case T_RangeFunction:
2732 RangeFunction *rf = (RangeFunction *) node;
2734 if (walker(rf->funccallnode, context))
2736 if (walker(rf->alias, context))
2742 TypeName *tn = (TypeName *) node;
2744 if (walker(tn->typmods, context))
2746 if (walker(tn->arrayBounds, context))
2748 /* type name itself is deemed uninteresting */
2753 ColumnDef *coldef = (ColumnDef *) node;
2755 if (walker(coldef->typeName, context))
2757 if (walker(coldef->raw_default, context))
2759 /* for now, constraints are ignored */
2762 case T_LockingClause:
2763 return walker(((LockingClause *) node)->lockedRels, context);
2764 case T_XmlSerialize:
2766 XmlSerialize *xs = (XmlSerialize *) node;
2768 if (walker(xs->expr, context))
2770 if (walker(xs->typeName, context))
2775 return walker(((WithClause *) node)->ctes, context);
2776 case T_CommonTableExpr:
2777 return walker(((CommonTableExpr *) node)->ctequery, context);
2779 elog(ERROR, "unrecognized node type: %d",
2780 (int) nodeTag(node));