1 /*-------------------------------------------------------------------------
4 * Various general-purpose manipulations of Node trees
6 * Portions Copyright (c) 1996-2009, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
13 *-------------------------------------------------------------------------
17 #include "catalog/pg_type.h"
18 #include "miscadmin.h"
19 #include "nodes/nodeFuncs.h"
20 #include "nodes/relation.h"
21 #include "utils/builtins.h"
22 #include "utils/lsyscache.h"
25 static bool expression_returns_set_walker(Node
*node
, void *context
);
26 static int leftmostLoc(int loc1
, int loc2
);
31 * returns the Oid of the type of the expression. (Used for typechecking.)
41 switch (nodeTag(expr
))
44 type
= ((Var
*) expr
)->vartype
;
47 type
= ((Const
*) expr
)->consttype
;
50 type
= ((Param
*) expr
)->paramtype
;
53 type
= ((Aggref
*) expr
)->aggtype
;
56 type
= ((WindowFunc
*) expr
)->wintype
;
60 ArrayRef
*arrayref
= (ArrayRef
*) expr
;
62 /* slice and/or store operations yield the array type */
63 if (arrayref
->reflowerindexpr
|| arrayref
->refassgnexpr
)
64 type
= arrayref
->refarraytype
;
66 type
= arrayref
->refelemtype
;
70 type
= ((FuncExpr
*) expr
)->funcresulttype
;
73 type
= ((OpExpr
*) expr
)->opresulttype
;
76 type
= ((DistinctExpr
*) expr
)->opresulttype
;
78 case T_ScalarArrayOpExpr
:
86 SubLink
*sublink
= (SubLink
*) expr
;
88 if (sublink
->subLinkType
== EXPR_SUBLINK
||
89 sublink
->subLinkType
== ARRAY_SUBLINK
)
91 /* get the type of the subselect's first target column */
92 Query
*qtree
= (Query
*) sublink
->subselect
;
95 if (!qtree
|| !IsA(qtree
, Query
))
96 elog(ERROR
, "cannot get type for untransformed sublink");
97 tent
= (TargetEntry
*) linitial(qtree
->targetList
);
98 Assert(IsA(tent
, TargetEntry
));
99 Assert(!tent
->resjunk
);
100 type
= exprType((Node
*) tent
->expr
);
101 if (sublink
->subLinkType
== ARRAY_SUBLINK
)
103 type
= get_array_type(type
);
104 if (!OidIsValid(type
))
106 (errcode(ERRCODE_UNDEFINED_OBJECT
),
107 errmsg("could not find array type for data type %s",
108 format_type_be(exprType((Node
*) tent
->expr
)))));
113 /* for all other sublink types, result is boolean */
121 * Although the parser does not ever deal with already-planned
122 * expression trees, we support SubPlan nodes in this routine
123 * for the convenience of ruleutils.c.
125 SubPlan
*subplan
= (SubPlan
*) expr
;
127 if (subplan
->subLinkType
== EXPR_SUBLINK
||
128 subplan
->subLinkType
== ARRAY_SUBLINK
)
130 /* get the type of the subselect's first target column */
131 type
= subplan
->firstColType
;
132 if (subplan
->subLinkType
== ARRAY_SUBLINK
)
134 type
= get_array_type(type
);
135 if (!OidIsValid(type
))
137 (errcode(ERRCODE_UNDEFINED_OBJECT
),
138 errmsg("could not find array type for data type %s",
139 format_type_be(subplan
->firstColType
))));
144 /* for all other subplan types, result is boolean */
149 case T_AlternativeSubPlan
:
151 /* As above, supported for the convenience of ruleutils.c */
152 AlternativeSubPlan
*asplan
= (AlternativeSubPlan
*) expr
;
154 /* subplans should all return the same thing */
155 type
= exprType((Node
*) linitial(asplan
->subplans
));
159 type
= ((FieldSelect
*) expr
)->resulttype
;
162 type
= ((FieldStore
*) expr
)->resulttype
;
165 type
= ((RelabelType
*) expr
)->resulttype
;
168 type
= ((CoerceViaIO
*) expr
)->resulttype
;
170 case T_ArrayCoerceExpr
:
171 type
= ((ArrayCoerceExpr
*) expr
)->resulttype
;
173 case T_ConvertRowtypeExpr
:
174 type
= ((ConvertRowtypeExpr
*) expr
)->resulttype
;
177 type
= ((CaseExpr
*) expr
)->casetype
;
180 type
= ((CaseTestExpr
*) expr
)->typeId
;
183 type
= ((ArrayExpr
*) expr
)->array_typeid
;
186 type
= ((RowExpr
*) expr
)->row_typeid
;
188 case T_RowCompareExpr
:
192 type
= ((CoalesceExpr
*) expr
)->coalescetype
;
195 type
= ((MinMaxExpr
*) expr
)->minmaxtype
;
198 if (((XmlExpr
*) expr
)->op
== IS_DOCUMENT
)
200 else if (((XmlExpr
*) expr
)->op
== IS_XMLSERIALIZE
)
206 type
= exprType((Node
*) linitial(((NullIfExpr
*) expr
)->args
));
214 case T_CoerceToDomain
:
215 type
= ((CoerceToDomain
*) expr
)->resulttype
;
217 case T_CoerceToDomainValue
:
218 type
= ((CoerceToDomainValue
*) expr
)->typeId
;
221 type
= ((SetToDefault
*) expr
)->typeId
;
223 case T_CurrentOfExpr
:
226 case T_PlaceHolderVar
:
227 type
= exprType((Node
*) ((PlaceHolderVar
*) expr
)->phexpr
);
230 elog(ERROR
, "unrecognized node type: %d", (int) nodeTag(expr
));
231 type
= InvalidOid
; /* keep compiler quiet */
239 * returns the type-specific attrmod of the expression, if it can be
240 * determined. In most cases, it can't and we return -1.
243 exprTypmod(Node
*expr
)
248 switch (nodeTag(expr
))
251 return ((Var
*) expr
)->vartypmod
;
253 return ((Const
*) expr
)->consttypmod
;
255 return ((Param
*) expr
)->paramtypmod
;
257 /* typmod is the same for array or element */
258 return ((ArrayRef
*) expr
)->reftypmod
;
263 /* Be smart about length-coercion functions... */
264 if (exprIsLengthCoercion(expr
, &coercedTypmod
))
265 return coercedTypmod
;
270 SubLink
*sublink
= (SubLink
*) expr
;
272 if (sublink
->subLinkType
== EXPR_SUBLINK
||
273 sublink
->subLinkType
== ARRAY_SUBLINK
)
275 /* get the typmod of the subselect's first target column */
276 Query
*qtree
= (Query
*) sublink
->subselect
;
279 if (!qtree
|| !IsA(qtree
, Query
))
280 elog(ERROR
, "cannot get type for untransformed sublink");
281 tent
= (TargetEntry
*) linitial(qtree
->targetList
);
282 Assert(IsA(tent
, TargetEntry
));
283 Assert(!tent
->resjunk
);
284 return exprTypmod((Node
*) tent
->expr
);
285 /* note we don't need to care if it's an array */
290 return ((FieldSelect
*) expr
)->resulttypmod
;
292 return ((RelabelType
*) expr
)->resulttypmod
;
293 case T_ArrayCoerceExpr
:
294 return ((ArrayCoerceExpr
*) expr
)->resulttypmod
;
298 * If all the alternatives agree on type/typmod, return that
299 * typmod, else use -1
301 CaseExpr
*cexpr
= (CaseExpr
*) expr
;
302 Oid casetype
= cexpr
->casetype
;
306 if (!cexpr
->defresult
)
308 if (exprType((Node
*) cexpr
->defresult
) != casetype
)
310 typmod
= exprTypmod((Node
*) cexpr
->defresult
);
312 return -1; /* no point in trying harder */
313 foreach(arg
, cexpr
->args
)
315 CaseWhen
*w
= (CaseWhen
*) lfirst(arg
);
317 Assert(IsA(w
, CaseWhen
));
318 if (exprType((Node
*) w
->result
) != casetype
)
320 if (exprTypmod((Node
*) w
->result
) != typmod
)
327 return ((CaseTestExpr
*) expr
)->typeMod
;
331 * If all the elements agree on type/typmod, return that
332 * typmod, else use -1
334 ArrayExpr
*arrayexpr
= (ArrayExpr
*) expr
;
339 if (arrayexpr
->elements
== NIL
)
341 typmod
= exprTypmod((Node
*) linitial(arrayexpr
->elements
));
343 return -1; /* no point in trying harder */
344 if (arrayexpr
->multidims
)
345 commontype
= arrayexpr
->array_typeid
;
347 commontype
= arrayexpr
->element_typeid
;
348 foreach(elem
, arrayexpr
->elements
)
350 Node
*e
= (Node
*) lfirst(elem
);
352 if (exprType(e
) != commontype
)
354 if (exprTypmod(e
) != typmod
)
363 * If all the alternatives agree on type/typmod, return that
364 * typmod, else use -1
366 CoalesceExpr
*cexpr
= (CoalesceExpr
*) expr
;
367 Oid coalescetype
= cexpr
->coalescetype
;
371 if (exprType((Node
*) linitial(cexpr
->args
)) != coalescetype
)
373 typmod
= exprTypmod((Node
*) linitial(cexpr
->args
));
375 return -1; /* no point in trying harder */
376 for_each_cell(arg
, lnext(list_head(cexpr
->args
)))
378 Node
*e
= (Node
*) lfirst(arg
);
380 if (exprType(e
) != coalescetype
)
382 if (exprTypmod(e
) != typmod
)
391 * If all the alternatives agree on type/typmod, return that
392 * typmod, else use -1
394 MinMaxExpr
*mexpr
= (MinMaxExpr
*) expr
;
395 Oid minmaxtype
= mexpr
->minmaxtype
;
399 if (exprType((Node
*) linitial(mexpr
->args
)) != minmaxtype
)
401 typmod
= exprTypmod((Node
*) linitial(mexpr
->args
));
403 return -1; /* no point in trying harder */
404 for_each_cell(arg
, lnext(list_head(mexpr
->args
)))
406 Node
*e
= (Node
*) lfirst(arg
);
408 if (exprType(e
) != minmaxtype
)
410 if (exprTypmod(e
) != typmod
)
418 NullIfExpr
*nexpr
= (NullIfExpr
*) expr
;
420 return exprTypmod((Node
*) linitial(nexpr
->args
));
423 case T_CoerceToDomain
:
424 return ((CoerceToDomain
*) expr
)->resulttypmod
;
425 case T_CoerceToDomainValue
:
426 return ((CoerceToDomainValue
*) expr
)->typeMod
;
428 return ((SetToDefault
*) expr
)->typeMod
;
429 case T_PlaceHolderVar
:
430 return exprTypmod((Node
*) ((PlaceHolderVar
*) expr
)->phexpr
);
438 * exprIsLengthCoercion
439 * Detect whether an expression tree is an application of a datatype's
440 * typmod-coercion function. Optionally extract the result's typmod.
442 * If coercedTypmod is not NULL, the typmod is stored there if the expression
443 * is a length-coercion function, else -1 is stored there.
445 * Note that a combined type-and-length coercion will be treated as a
446 * length coercion by this routine.
449 exprIsLengthCoercion(Node
*expr
, int32
*coercedTypmod
)
451 if (coercedTypmod
!= NULL
)
452 *coercedTypmod
= -1; /* default result on failure */
455 * Scalar-type length coercions are FuncExprs, array-type length coercions
456 * are ArrayCoerceExprs
458 if (expr
&& IsA(expr
, FuncExpr
))
460 FuncExpr
*func
= (FuncExpr
*) expr
;
465 * If it didn't come from a coercion context, reject.
467 if (func
->funcformat
!= COERCE_EXPLICIT_CAST
&&
468 func
->funcformat
!= COERCE_IMPLICIT_CAST
)
472 * If it's not a two-argument or three-argument function with the
473 * second argument being an int4 constant, it can't have been created
474 * from a length coercion (it must be a type coercion, instead).
476 nargs
= list_length(func
->args
);
477 if (nargs
< 2 || nargs
> 3)
480 second_arg
= (Const
*) lsecond(func
->args
);
481 if (!IsA(second_arg
, Const
) ||
482 second_arg
->consttype
!= INT4OID
||
483 second_arg
->constisnull
)
487 * OK, it is indeed a length-coercion function.
489 if (coercedTypmod
!= NULL
)
490 *coercedTypmod
= DatumGetInt32(second_arg
->constvalue
);
495 if (expr
&& IsA(expr
, ArrayCoerceExpr
))
497 ArrayCoerceExpr
*acoerce
= (ArrayCoerceExpr
*) expr
;
499 /* It's not a length coercion unless there's a nondefault typmod */
500 if (acoerce
->resulttypmod
< 0)
504 * OK, it is indeed a length-coercion expression.
506 if (coercedTypmod
!= NULL
)
507 *coercedTypmod
= acoerce
->resulttypmod
;
516 * expression_returns_set
517 * Test whether an expression returns a set result.
519 * Because we use expression_tree_walker(), this can also be applied to
520 * whole targetlists; it'll produce TRUE if any one of the tlist items
524 expression_returns_set(Node
*clause
)
526 return expression_returns_set_walker(clause
, NULL
);
530 expression_returns_set_walker(Node
*node
, void *context
)
534 if (IsA(node
, FuncExpr
))
536 FuncExpr
*expr
= (FuncExpr
*) node
;
538 if (expr
->funcretset
)
540 /* else fall through to check args */
542 if (IsA(node
, OpExpr
))
544 OpExpr
*expr
= (OpExpr
*) node
;
548 /* else fall through to check args */
551 /* Avoid recursion for some cases that can't return a set */
552 if (IsA(node
, Aggref
))
554 if (IsA(node
, WindowFunc
))
556 if (IsA(node
, DistinctExpr
))
558 if (IsA(node
, ScalarArrayOpExpr
))
560 if (IsA(node
, BoolExpr
))
562 if (IsA(node
, SubLink
))
564 if (IsA(node
, SubPlan
))
566 if (IsA(node
, AlternativeSubPlan
))
568 if (IsA(node
, ArrayExpr
))
570 if (IsA(node
, RowExpr
))
572 if (IsA(node
, RowCompareExpr
))
574 if (IsA(node
, CoalesceExpr
))
576 if (IsA(node
, MinMaxExpr
))
578 if (IsA(node
, XmlExpr
))
580 if (IsA(node
, NullIfExpr
))
583 return expression_tree_walker(node
, expression_returns_set_walker
,
590 * returns the parse location of an expression tree, for error reports
592 * -1 is returned if the location can't be determined.
594 * For expressions larger than a single token, the intent here is to
595 * return the location of the expression's leftmost token, not necessarily
596 * the topmost Node's location field. For example, an OpExpr's location
597 * field will point at the operator name, but if it is not a prefix operator
598 * then we should return the location of the left-hand operand instead.
599 * The reason is that we want to reference the entire expression not just
600 * that operator, and pointing to its start seems to be the most natural way.
602 * The location is not perfect --- for example, since the grammar doesn't
603 * explicitly represent parentheses in the parsetree, given something that
604 * had been written "(a + b) * c" we are going to point at "a" not "(".
605 * But it should be plenty good enough for error reporting purposes.
607 * You might think that this code is overly general, for instance why check
608 * the operands of a FuncExpr node, when the function name can be expected
609 * to be to the left of them? There are a couple of reasons. The grammar
610 * sometimes builds expressions that aren't quite what the user wrote;
611 * for instance x IS NOT BETWEEN ... becomes a NOT-expression whose keyword
612 * pointer is to the right of its leftmost argument. Also, nodes that were
613 * inserted implicitly by parse analysis (such as FuncExprs for implicit
614 * coercions) will have location -1, and so we can have odd combinations of
615 * known and unknown locations in a tree.
618 exprLocation(Node
*expr
)
624 switch (nodeTag(expr
))
627 loc
= ((RangeVar
*) expr
)->location
;
630 loc
= ((Var
*) expr
)->location
;
633 loc
= ((Const
*) expr
)->location
;
636 loc
= ((Param
*) expr
)->location
;
639 /* function name should always be the first thing */
640 loc
= ((Aggref
*) expr
)->location
;
643 /* function name should always be the first thing */
644 loc
= ((WindowFunc
*) expr
)->location
;
647 /* just use array argument's location */
648 loc
= exprLocation((Node
*) ((ArrayRef
*) expr
)->refexpr
);
652 FuncExpr
*fexpr
= (FuncExpr
*) expr
;
654 /* consider both function name and leftmost arg */
655 loc
= leftmostLoc(fexpr
->location
,
656 exprLocation((Node
*) fexpr
->args
));
660 case T_DistinctExpr
: /* struct-equivalent to OpExpr */
661 case T_NullIfExpr
: /* struct-equivalent to OpExpr */
663 OpExpr
*opexpr
= (OpExpr
*) expr
;
665 /* consider both operator name and leftmost arg */
666 loc
= leftmostLoc(opexpr
->location
,
667 exprLocation((Node
*) opexpr
->args
));
670 case T_ScalarArrayOpExpr
:
672 ScalarArrayOpExpr
*saopexpr
= (ScalarArrayOpExpr
*) expr
;
674 /* consider both operator name and leftmost arg */
675 loc
= leftmostLoc(saopexpr
->location
,
676 exprLocation((Node
*) saopexpr
->args
));
681 BoolExpr
*bexpr
= (BoolExpr
*) expr
;
684 * Same as above, to handle either NOT or AND/OR. We can't
685 * special-case NOT because of the way that it's used for
686 * things like IS NOT BETWEEN.
688 loc
= leftmostLoc(bexpr
->location
,
689 exprLocation((Node
*) bexpr
->args
));
694 SubLink
*sublink
= (SubLink
*) expr
;
696 /* check the testexpr, if any, and the operator/keyword */
697 loc
= leftmostLoc(exprLocation(sublink
->testexpr
),
702 /* just use argument's location */
703 loc
= exprLocation((Node
*) ((FieldSelect
*) expr
)->arg
);
706 /* just use argument's location */
707 loc
= exprLocation((Node
*) ((FieldStore
*) expr
)->arg
);
711 RelabelType
*rexpr
= (RelabelType
*) expr
;
714 loc
= leftmostLoc(rexpr
->location
,
715 exprLocation((Node
*) rexpr
->arg
));
720 CoerceViaIO
*cexpr
= (CoerceViaIO
*) expr
;
723 loc
= leftmostLoc(cexpr
->location
,
724 exprLocation((Node
*) cexpr
->arg
));
727 case T_ArrayCoerceExpr
:
729 ArrayCoerceExpr
*cexpr
= (ArrayCoerceExpr
*) expr
;
732 loc
= leftmostLoc(cexpr
->location
,
733 exprLocation((Node
*) cexpr
->arg
));
736 case T_ConvertRowtypeExpr
:
738 ConvertRowtypeExpr
*cexpr
= (ConvertRowtypeExpr
*) expr
;
741 loc
= leftmostLoc(cexpr
->location
,
742 exprLocation((Node
*) cexpr
->arg
));
746 /* CASE keyword should always be the first thing */
747 loc
= ((CaseExpr
*) expr
)->location
;
750 /* WHEN keyword should always be the first thing */
751 loc
= ((CaseWhen
*) expr
)->location
;
754 /* the location points at ARRAY or [, which must be leftmost */
755 loc
= ((ArrayExpr
*) expr
)->location
;
758 /* the location points at ROW or (, which must be leftmost */
759 loc
= ((RowExpr
*) expr
)->location
;
761 case T_RowCompareExpr
:
762 /* just use leftmost argument's location */
763 loc
= exprLocation((Node
*) ((RowCompareExpr
*) expr
)->largs
);
766 /* COALESCE keyword should always be the first thing */
767 loc
= ((CoalesceExpr
*) expr
)->location
;
770 /* GREATEST/LEAST keyword should always be the first thing */
771 loc
= ((MinMaxExpr
*) expr
)->location
;
775 XmlExpr
*xexpr
= (XmlExpr
*) expr
;
777 /* consider both function name and leftmost arg */
778 loc
= leftmostLoc(xexpr
->location
,
779 exprLocation((Node
*) xexpr
->args
));
783 /* just use argument's location */
784 loc
= exprLocation((Node
*) ((NullTest
*) expr
)->arg
);
787 /* just use argument's location */
788 loc
= exprLocation((Node
*) ((BooleanTest
*) expr
)->arg
);
790 case T_CoerceToDomain
:
792 CoerceToDomain
*cexpr
= (CoerceToDomain
*) expr
;
795 loc
= leftmostLoc(cexpr
->location
,
796 exprLocation((Node
*) cexpr
->arg
));
799 case T_CoerceToDomainValue
:
800 loc
= ((CoerceToDomainValue
*) expr
)->location
;
803 loc
= ((SetToDefault
*) expr
)->location
;
806 /* just use argument's location */
807 loc
= exprLocation((Node
*) ((TargetEntry
*) expr
)->expr
);
810 /* use the contained RangeVar's location --- close enough */
811 loc
= exprLocation((Node
*) ((IntoClause
*) expr
)->rel
);
815 /* report location of first list member that has a location */
818 loc
= -1; /* just to suppress compiler warning */
819 foreach(lc
, (List
*) expr
)
821 loc
= exprLocation((Node
*) lfirst(lc
));
829 A_Expr
*aexpr
= (A_Expr
*) expr
;
831 /* use leftmost of operator or left operand (if any) */
832 /* we assume right operand can't be to left of operator */
833 loc
= leftmostLoc(aexpr
->location
,
834 exprLocation(aexpr
->lexpr
));
838 loc
= ((ColumnRef
*) expr
)->location
;
841 loc
= ((ParamRef
*) expr
)->location
;
844 loc
= ((A_Const
*) expr
)->location
;
848 FuncCall
*fc
= (FuncCall
*) expr
;
850 /* consider both function name and leftmost arg */
851 loc
= leftmostLoc(fc
->location
,
852 exprLocation((Node
*) fc
->args
));
856 /* the location points at ARRAY or [, which must be leftmost */
857 loc
= ((A_ArrayExpr
*) expr
)->location
;
860 /* we need not examine the contained expression (if any) */
861 loc
= ((ResTarget
*) expr
)->location
;
865 TypeCast
*tc
= (TypeCast
*) expr
;
868 * This could represent CAST(), ::, or TypeName 'literal',
869 * so any of the components might be leftmost.
871 loc
= exprLocation(tc
->arg
);
872 loc
= leftmostLoc(loc
, tc
->typename
->location
);
873 loc
= leftmostLoc(loc
, tc
->location
);
877 /* just use argument's location (ignore operator, if any) */
878 loc
= exprLocation(((SortBy
*) expr
)->node
);
881 loc
= ((WindowDef
*) expr
)->location
;
884 loc
= ((TypeName
*) expr
)->location
;
887 /* XMLSERIALIZE keyword should always be the first thing */
888 loc
= ((XmlSerialize
*) expr
)->location
;
891 loc
= ((WithClause
*) expr
)->location
;
893 case T_CommonTableExpr
:
894 loc
= ((CommonTableExpr
*) expr
)->location
;
896 case T_PlaceHolderVar
:
897 /* just use argument's location */
898 loc
= exprLocation((Node
*) ((PlaceHolderVar
*) expr
)->phexpr
);
901 /* for any other node type it's just unknown... */
909 * leftmostLoc - support for exprLocation
911 * Take the minimum of two parse location values, but ignore unknowns
914 leftmostLoc(int loc1
, int loc2
)
921 return Min(loc1
, loc2
);
926 * Standard expression-tree walking support
928 * We used to have near-duplicate code in many different routines that
929 * understood how to recurse through an expression node tree. That was
930 * a pain to maintain, and we frequently had bugs due to some particular
931 * routine neglecting to support a particular node type. In most cases,
932 * these routines only actually care about certain node types, and don't
933 * care about other types except insofar as they have to recurse through
934 * non-primitive node types. Therefore, we now provide generic tree-walking
935 * logic to consolidate the redundant "boilerplate" code. There are
936 * two versions: expression_tree_walker() and expression_tree_mutator().
940 * expression_tree_walker() is designed to support routines that traverse
941 * a tree in a read-only fashion (although it will also work for routines
942 * that modify nodes in-place but never add/delete/replace nodes).
943 * A walker routine should look like this:
945 * bool my_walker (Node *node, my_struct *context)
949 * // check for nodes that special work is required for, eg:
950 * if (IsA(node, Var))
952 * ... do special actions for Var nodes
954 * else if (IsA(node, ...))
956 * ... do special actions for other node types
958 * // for any node type not specially processed, do:
959 * return expression_tree_walker(node, my_walker, (void *) context);
962 * The "context" argument points to a struct that holds whatever context
963 * information the walker routine needs --- it can be used to return data
964 * gathered by the walker, too. This argument is not touched by
965 * expression_tree_walker, but it is passed down to recursive sub-invocations
966 * of my_walker. The tree walk is started from a setup routine that
967 * fills in the appropriate context struct, calls my_walker with the top-level
968 * node of the tree, and then examines the results.
970 * The walker routine should return "false" to continue the tree walk, or
971 * "true" to abort the walk and immediately return "true" to the top-level
972 * caller. This can be used to short-circuit the traversal if the walker
973 * has found what it came for. "false" is returned to the top-level caller
974 * iff no invocation of the walker returned "true".
976 * The node types handled by expression_tree_walker include all those
977 * normally found in target lists and qualifier clauses during the planning
978 * stage. In particular, it handles List nodes since a cnf-ified qual clause
979 * will have List structure at the top level, and it handles TargetEntry nodes
980 * so that a scan of a target list can be handled without additional code.
981 * Also, RangeTblRef, FromExpr, JoinExpr, and SetOperationStmt nodes are
982 * handled, so that query jointrees and setOperation trees can be processed
983 * without additional code.
985 * expression_tree_walker will handle SubLink nodes by recursing normally
986 * into the "testexpr" subtree (which is an expression belonging to the outer
987 * plan). It will also call the walker on the sub-Query node; however, when
988 * expression_tree_walker itself is called on a Query node, it does nothing
989 * and returns "false". The net effect is that unless the walker does
990 * something special at a Query node, sub-selects will not be visited during
991 * an expression tree walk. This is exactly the behavior wanted in many cases
992 * --- and for those walkers that do want to recurse into sub-selects, special
993 * behavior is typically needed anyway at the entry to a sub-select (such as
994 * incrementing a depth counter). A walker that wants to examine sub-selects
995 * should include code along the lines of:
997 * if (IsA(node, Query))
999 * adjust context for subquery;
1000 * result = query_tree_walker((Query *) node, my_walker, context,
1001 * 0); // adjust flags as needed
1002 * restore context if needed;
1006 * query_tree_walker is a convenience routine (see below) that calls the
1007 * walker on all the expression subtrees of the given Query node.
1009 * expression_tree_walker will handle SubPlan nodes by recursing normally
1010 * into the "testexpr" and the "args" list (which are expressions belonging to
1011 * the outer plan). It will not touch the completed subplan, however. Since
1012 * there is no link to the original Query, it is not possible to recurse into
1013 * subselects of an already-planned expression tree. This is OK for current
1014 * uses, but may need to be revisited in future.
1018 expression_tree_walker(Node
*node
,
1025 * The walker has already visited the current node, and so we need only
1026 * recurse into any sub-nodes it has.
1028 * We assume that the walker is not interested in List nodes per se, so
1029 * when we expect a List we just recurse directly to self without
1030 * bothering to call the walker.
1035 /* Guard against stack overflow due to overly complex expressions */
1036 check_stack_depth();
1038 switch (nodeTag(node
))
1043 case T_CoerceToDomainValue
:
1044 case T_CaseTestExpr
:
1045 case T_SetToDefault
:
1046 case T_CurrentOfExpr
:
1048 /* primitive node types with no expression subnodes */
1052 Aggref
*expr
= (Aggref
*) node
;
1054 /* recurse directly on List */
1055 if (expression_tree_walker((Node
*) expr
->args
,
1062 WindowFunc
*expr
= (WindowFunc
*) node
;
1064 /* recurse directly on List */
1065 if (expression_tree_walker((Node
*) expr
->args
,
1072 ArrayRef
*aref
= (ArrayRef
*) node
;
1074 /* recurse directly for upper/lower array index lists */
1075 if (expression_tree_walker((Node
*) aref
->refupperindexpr
,
1078 if (expression_tree_walker((Node
*) aref
->reflowerindexpr
,
1081 /* walker must see the refexpr and refassgnexpr, however */
1082 if (walker(aref
->refexpr
, context
))
1084 if (walker(aref
->refassgnexpr
, context
))
1090 FuncExpr
*expr
= (FuncExpr
*) node
;
1092 if (expression_tree_walker((Node
*) expr
->args
,
1099 OpExpr
*expr
= (OpExpr
*) node
;
1101 if (expression_tree_walker((Node
*) expr
->args
,
1106 case T_DistinctExpr
:
1108 DistinctExpr
*expr
= (DistinctExpr
*) node
;
1110 if (expression_tree_walker((Node
*) expr
->args
,
1115 case T_ScalarArrayOpExpr
:
1117 ScalarArrayOpExpr
*expr
= (ScalarArrayOpExpr
*) node
;
1119 if (expression_tree_walker((Node
*) expr
->args
,
1126 BoolExpr
*expr
= (BoolExpr
*) node
;
1128 if (expression_tree_walker((Node
*) expr
->args
,
1135 SubLink
*sublink
= (SubLink
*) node
;
1137 if (walker(sublink
->testexpr
, context
))
1141 * Also invoke the walker on the sublink's Query node, so it
1142 * can recurse into the sub-query if it wants to.
1144 return walker(sublink
->subselect
, context
);
1149 SubPlan
*subplan
= (SubPlan
*) node
;
1151 /* recurse into the testexpr, but not into the Plan */
1152 if (walker(subplan
->testexpr
, context
))
1154 /* also examine args list */
1155 if (expression_tree_walker((Node
*) subplan
->args
,
1160 case T_AlternativeSubPlan
:
1161 return walker(((AlternativeSubPlan
*) node
)->subplans
, context
);
1163 return walker(((FieldSelect
*) node
)->arg
, context
);
1166 FieldStore
*fstore
= (FieldStore
*) node
;
1168 if (walker(fstore
->arg
, context
))
1170 if (walker(fstore
->newvals
, context
))
1175 return walker(((RelabelType
*) node
)->arg
, context
);
1177 return walker(((CoerceViaIO
*) node
)->arg
, context
);
1178 case T_ArrayCoerceExpr
:
1179 return walker(((ArrayCoerceExpr
*) node
)->arg
, context
);
1180 case T_ConvertRowtypeExpr
:
1181 return walker(((ConvertRowtypeExpr
*) node
)->arg
, context
);
1184 CaseExpr
*caseexpr
= (CaseExpr
*) node
;
1186 if (walker(caseexpr
->arg
, context
))
1188 /* we assume walker doesn't care about CaseWhens, either */
1189 foreach(temp
, caseexpr
->args
)
1191 CaseWhen
*when
= (CaseWhen
*) lfirst(temp
);
1193 Assert(IsA(when
, CaseWhen
));
1194 if (walker(when
->expr
, context
))
1196 if (walker(when
->result
, context
))
1199 if (walker(caseexpr
->defresult
, context
))
1204 return walker(((ArrayExpr
*) node
)->elements
, context
);
1206 /* Assume colnames isn't interesting */
1207 return walker(((RowExpr
*) node
)->args
, context
);
1208 case T_RowCompareExpr
:
1210 RowCompareExpr
*rcexpr
= (RowCompareExpr
*) node
;
1212 if (walker(rcexpr
->largs
, context
))
1214 if (walker(rcexpr
->rargs
, context
))
1218 case T_CoalesceExpr
:
1219 return walker(((CoalesceExpr
*) node
)->args
, context
);
1221 return walker(((MinMaxExpr
*) node
)->args
, context
);
1224 XmlExpr
*xexpr
= (XmlExpr
*) node
;
1226 if (walker(xexpr
->named_args
, context
))
1228 /* we assume walker doesn't care about arg_names */
1229 if (walker(xexpr
->args
, context
))
1234 return walker(((NullIfExpr
*) node
)->args
, context
);
1236 return walker(((NullTest
*) node
)->arg
, context
);
1238 return walker(((BooleanTest
*) node
)->arg
, context
);
1239 case T_CoerceToDomain
:
1240 return walker(((CoerceToDomain
*) node
)->arg
, context
);
1242 return walker(((TargetEntry
*) node
)->expr
, context
);
1244 /* Do nothing with a sub-Query, per discussion above */
1246 case T_WindowClause
:
1248 WindowClause
*wc
= (WindowClause
*) node
;
1250 if (walker(wc
->partitionClause
, context
))
1252 if (walker(wc
->orderClause
, context
))
1256 case T_CommonTableExpr
:
1258 CommonTableExpr
*cte
= (CommonTableExpr
*) node
;
1261 * Invoke the walker on the CTE's Query node, so it
1262 * can recurse into the sub-query if it wants to.
1264 return walker(cte
->ctequery
, context
);
1268 foreach(temp
, (List
*) node
)
1270 if (walker((Node
*) lfirst(temp
), context
))
1276 FromExpr
*from
= (FromExpr
*) node
;
1278 if (walker(from
->fromlist
, context
))
1280 if (walker(from
->quals
, context
))
1286 JoinExpr
*join
= (JoinExpr
*) node
;
1288 if (walker(join
->larg
, context
))
1290 if (walker(join
->rarg
, context
))
1292 if (walker(join
->quals
, context
))
1296 * alias clause, using list are deemed uninteresting.
1300 case T_SetOperationStmt
:
1302 SetOperationStmt
*setop
= (SetOperationStmt
*) node
;
1304 if (walker(setop
->larg
, context
))
1306 if (walker(setop
->rarg
, context
))
1309 /* groupClauses are deemed uninteresting */
1312 case T_PlaceHolderVar
:
1313 return walker(((PlaceHolderVar
*) node
)->phexpr
, context
);
1314 case T_AppendRelInfo
:
1316 AppendRelInfo
*appinfo
= (AppendRelInfo
*) node
;
1318 if (expression_tree_walker((Node
*) appinfo
->translated_vars
,
1323 case T_PlaceHolderInfo
:
1324 return walker(((PlaceHolderInfo
*) node
)->ph_var
, context
);
1326 elog(ERROR
, "unrecognized node type: %d",
1327 (int) nodeTag(node
));
1334 * query_tree_walker --- initiate a walk of a Query's expressions
1336 * This routine exists just to reduce the number of places that need to know
1337 * where all the expression subtrees of a Query are. Note it can be used
1338 * for starting a walk at top level of a Query regardless of whether the
1339 * walker intends to descend into subqueries. It is also useful for
1340 * descending into subqueries within a walker.
1342 * Some callers want to suppress visitation of certain items in the sub-Query,
1343 * typically because they need to process them specially, or don't actually
1344 * want to recurse into subqueries. This is supported by the flags argument,
1345 * which is the bitwise OR of flag values to suppress visitation of
1346 * indicated items. (More flag bits may be added as needed.)
1349 query_tree_walker(Query
*query
,
1354 Assert(query
!= NULL
&& IsA(query
, Query
));
1356 if (walker((Node
*) query
->targetList
, context
))
1358 if (walker((Node
*) query
->returningList
, context
))
1360 if (walker((Node
*) query
->jointree
, context
))
1362 if (walker(query
->setOperations
, context
))
1364 if (walker(query
->havingQual
, context
))
1366 if (walker(query
->limitOffset
, context
))
1368 if (walker(query
->limitCount
, context
))
1370 if (!(flags
& QTW_IGNORE_CTE_SUBQUERIES
))
1372 if (walker((Node
*) query
->cteList
, context
))
1375 if (range_table_walker(query
->rtable
, walker
, context
, flags
))
1381 * range_table_walker is just the part of query_tree_walker that scans
1382 * a query's rangetable. This is split out since it can be useful on
1386 range_table_walker(List
*rtable
,
1395 RangeTblEntry
*rte
= (RangeTblEntry
*) lfirst(rt
);
1397 /* For historical reasons, visiting RTEs is not the default */
1398 if (flags
& QTW_EXAMINE_RTES
)
1399 if (walker(rte
, context
))
1402 switch (rte
->rtekind
)
1410 if (!(flags
& QTW_IGNORE_RT_SUBQUERIES
))
1411 if (walker(rte
->subquery
, context
))
1415 if (!(flags
& QTW_IGNORE_JOINALIASES
))
1416 if (walker(rte
->joinaliasvars
, context
))
1420 if (walker(rte
->funcexpr
, context
))
1424 if (walker(rte
->values_lists
, context
))
1434 * expression_tree_mutator() is designed to support routines that make a
1435 * modified copy of an expression tree, with some nodes being added,
1436 * removed, or replaced by new subtrees. The original tree is (normally)
1437 * not changed. Each recursion level is responsible for returning a copy of
1438 * (or appropriately modified substitute for) the subtree it is handed.
1439 * A mutator routine should look like this:
1441 * Node * my_mutator (Node *node, my_struct *context)
1445 * // check for nodes that special work is required for, eg:
1446 * if (IsA(node, Var))
1448 * ... create and return modified copy of Var node
1450 * else if (IsA(node, ...))
1452 * ... do special transformations of other node types
1454 * // for any node type not specially processed, do:
1455 * return expression_tree_mutator(node, my_mutator, (void *) context);
1458 * The "context" argument points to a struct that holds whatever context
1459 * information the mutator routine needs --- it can be used to return extra
1460 * data gathered by the mutator, too. This argument is not touched by
1461 * expression_tree_mutator, but it is passed down to recursive sub-invocations
1462 * of my_mutator. The tree walk is started from a setup routine that
1463 * fills in the appropriate context struct, calls my_mutator with the
1464 * top-level node of the tree, and does any required post-processing.
1466 * Each level of recursion must return an appropriately modified Node.
1467 * If expression_tree_mutator() is called, it will make an exact copy
1468 * of the given Node, but invoke my_mutator() to copy the sub-node(s)
1469 * of that Node. In this way, my_mutator() has full control over the
1470 * copying process but need not directly deal with expression trees
1471 * that it has no interest in.
1473 * Just as for expression_tree_walker, the node types handled by
1474 * expression_tree_mutator include all those normally found in target lists
1475 * and qualifier clauses during the planning stage.
1477 * expression_tree_mutator will handle SubLink nodes by recursing normally
1478 * into the "testexpr" subtree (which is an expression belonging to the outer
1479 * plan). It will also call the mutator on the sub-Query node; however, when
1480 * expression_tree_mutator itself is called on a Query node, it does nothing
1481 * and returns the unmodified Query node. The net effect is that unless the
1482 * mutator does something special at a Query node, sub-selects will not be
1483 * visited or modified; the original sub-select will be linked to by the new
1484 * SubLink node. Mutators that want to descend into sub-selects will usually
1485 * do so by recognizing Query nodes and calling query_tree_mutator (below).
1487 * expression_tree_mutator will handle a SubPlan node by recursing into the
1488 * "testexpr" and the "args" list (which belong to the outer plan), but it
1489 * will simply copy the link to the inner plan, since that's typically what
1490 * expression tree mutators want. A mutator that wants to modify the subplan
1491 * can force appropriate behavior by recognizing SubPlan expression nodes
1492 * and doing the right thing.
1496 expression_tree_mutator(Node
*node
,
1497 Node
*(*mutator
) (),
1501 * The mutator has already decided not to modify the current node, but we
1502 * must call the mutator for any sub-nodes.
1505 #define FLATCOPY(newnode, node, nodetype) \
1506 ( (newnode) = (nodetype *) palloc(sizeof(nodetype)), \
1507 memcpy((newnode), (node), sizeof(nodetype)) )
1509 #define CHECKFLATCOPY(newnode, node, nodetype) \
1510 ( AssertMacro(IsA((node), nodetype)), \
1511 (newnode) = (nodetype *) palloc(sizeof(nodetype)), \
1512 memcpy((newnode), (node), sizeof(nodetype)) )
1514 #define MUTATE(newfield, oldfield, fieldtype) \
1515 ( (newfield) = (fieldtype) mutator((Node *) (oldfield), context) )
1520 /* Guard against stack overflow due to overly complex expressions */
1521 check_stack_depth();
1523 switch (nodeTag(node
))
1526 * Primitive node types with no expression subnodes. Var and
1527 * Const are frequent enough to deserve special cases, the others
1528 * we just use copyObject for.
1532 Var
*var
= (Var
*) node
;
1535 FLATCOPY(newnode
, var
, Var
);
1536 return (Node
*) newnode
;
1541 Const
*oldnode
= (Const
*) node
;
1544 FLATCOPY(newnode
, oldnode
, Const
);
1545 /* XXX we don't bother with datumCopy; should we? */
1546 return (Node
*) newnode
;
1550 case T_CoerceToDomainValue
:
1551 case T_CaseTestExpr
:
1552 case T_SetToDefault
:
1553 case T_CurrentOfExpr
:
1555 return (Node
*) copyObject(node
);
1558 Aggref
*aggref
= (Aggref
*) node
;
1561 FLATCOPY(newnode
, aggref
, Aggref
);
1562 MUTATE(newnode
->args
, aggref
->args
, List
*);
1563 return (Node
*) newnode
;
1568 WindowFunc
*wfunc
= (WindowFunc
*) node
;
1569 WindowFunc
*newnode
;
1571 FLATCOPY(newnode
, wfunc
, WindowFunc
);
1572 MUTATE(newnode
->args
, wfunc
->args
, List
*);
1573 return (Node
*) newnode
;
1578 ArrayRef
*arrayref
= (ArrayRef
*) node
;
1581 FLATCOPY(newnode
, arrayref
, ArrayRef
);
1582 MUTATE(newnode
->refupperindexpr
, arrayref
->refupperindexpr
,
1584 MUTATE(newnode
->reflowerindexpr
, arrayref
->reflowerindexpr
,
1586 MUTATE(newnode
->refexpr
, arrayref
->refexpr
,
1588 MUTATE(newnode
->refassgnexpr
, arrayref
->refassgnexpr
,
1590 return (Node
*) newnode
;
1595 FuncExpr
*expr
= (FuncExpr
*) node
;
1598 FLATCOPY(newnode
, expr
, FuncExpr
);
1599 MUTATE(newnode
->args
, expr
->args
, List
*);
1600 return (Node
*) newnode
;
1605 OpExpr
*expr
= (OpExpr
*) node
;
1608 FLATCOPY(newnode
, expr
, OpExpr
);
1609 MUTATE(newnode
->args
, expr
->args
, List
*);
1610 return (Node
*) newnode
;
1613 case T_DistinctExpr
:
1615 DistinctExpr
*expr
= (DistinctExpr
*) node
;
1616 DistinctExpr
*newnode
;
1618 FLATCOPY(newnode
, expr
, DistinctExpr
);
1619 MUTATE(newnode
->args
, expr
->args
, List
*);
1620 return (Node
*) newnode
;
1623 case T_ScalarArrayOpExpr
:
1625 ScalarArrayOpExpr
*expr
= (ScalarArrayOpExpr
*) node
;
1626 ScalarArrayOpExpr
*newnode
;
1628 FLATCOPY(newnode
, expr
, ScalarArrayOpExpr
);
1629 MUTATE(newnode
->args
, expr
->args
, List
*);
1630 return (Node
*) newnode
;
1635 BoolExpr
*expr
= (BoolExpr
*) node
;
1638 FLATCOPY(newnode
, expr
, BoolExpr
);
1639 MUTATE(newnode
->args
, expr
->args
, List
*);
1640 return (Node
*) newnode
;
1645 SubLink
*sublink
= (SubLink
*) node
;
1648 FLATCOPY(newnode
, sublink
, SubLink
);
1649 MUTATE(newnode
->testexpr
, sublink
->testexpr
, Node
*);
1652 * Also invoke the mutator on the sublink's Query node, so it
1653 * can recurse into the sub-query if it wants to.
1655 MUTATE(newnode
->subselect
, sublink
->subselect
, Node
*);
1656 return (Node
*) newnode
;
1661 SubPlan
*subplan
= (SubPlan
*) node
;
1664 FLATCOPY(newnode
, subplan
, SubPlan
);
1665 /* transform testexpr */
1666 MUTATE(newnode
->testexpr
, subplan
->testexpr
, Node
*);
1667 /* transform args list (params to be passed to subplan) */
1668 MUTATE(newnode
->args
, subplan
->args
, List
*);
1669 /* but not the sub-Plan itself, which is referenced as-is */
1670 return (Node
*) newnode
;
1673 case T_AlternativeSubPlan
:
1675 AlternativeSubPlan
*asplan
= (AlternativeSubPlan
*) node
;
1676 AlternativeSubPlan
*newnode
;
1678 FLATCOPY(newnode
, asplan
, AlternativeSubPlan
);
1679 MUTATE(newnode
->subplans
, asplan
->subplans
, List
*);
1680 return (Node
*) newnode
;
1685 FieldSelect
*fselect
= (FieldSelect
*) node
;
1686 FieldSelect
*newnode
;
1688 FLATCOPY(newnode
, fselect
, FieldSelect
);
1689 MUTATE(newnode
->arg
, fselect
->arg
, Expr
*);
1690 return (Node
*) newnode
;
1695 FieldStore
*fstore
= (FieldStore
*) node
;
1696 FieldStore
*newnode
;
1698 FLATCOPY(newnode
, fstore
, FieldStore
);
1699 MUTATE(newnode
->arg
, fstore
->arg
, Expr
*);
1700 MUTATE(newnode
->newvals
, fstore
->newvals
, List
*);
1701 newnode
->fieldnums
= list_copy(fstore
->fieldnums
);
1702 return (Node
*) newnode
;
1707 RelabelType
*relabel
= (RelabelType
*) node
;
1708 RelabelType
*newnode
;
1710 FLATCOPY(newnode
, relabel
, RelabelType
);
1711 MUTATE(newnode
->arg
, relabel
->arg
, Expr
*);
1712 return (Node
*) newnode
;
1717 CoerceViaIO
*iocoerce
= (CoerceViaIO
*) node
;
1718 CoerceViaIO
*newnode
;
1720 FLATCOPY(newnode
, iocoerce
, CoerceViaIO
);
1721 MUTATE(newnode
->arg
, iocoerce
->arg
, Expr
*);
1722 return (Node
*) newnode
;
1725 case T_ArrayCoerceExpr
:
1727 ArrayCoerceExpr
*acoerce
= (ArrayCoerceExpr
*) node
;
1728 ArrayCoerceExpr
*newnode
;
1730 FLATCOPY(newnode
, acoerce
, ArrayCoerceExpr
);
1731 MUTATE(newnode
->arg
, acoerce
->arg
, Expr
*);
1732 return (Node
*) newnode
;
1735 case T_ConvertRowtypeExpr
:
1737 ConvertRowtypeExpr
*convexpr
= (ConvertRowtypeExpr
*) node
;
1738 ConvertRowtypeExpr
*newnode
;
1740 FLATCOPY(newnode
, convexpr
, ConvertRowtypeExpr
);
1741 MUTATE(newnode
->arg
, convexpr
->arg
, Expr
*);
1742 return (Node
*) newnode
;
1747 CaseExpr
*caseexpr
= (CaseExpr
*) node
;
1750 FLATCOPY(newnode
, caseexpr
, CaseExpr
);
1751 MUTATE(newnode
->arg
, caseexpr
->arg
, Expr
*);
1752 MUTATE(newnode
->args
, caseexpr
->args
, List
*);
1753 MUTATE(newnode
->defresult
, caseexpr
->defresult
, Expr
*);
1754 return (Node
*) newnode
;
1759 CaseWhen
*casewhen
= (CaseWhen
*) node
;
1762 FLATCOPY(newnode
, casewhen
, CaseWhen
);
1763 MUTATE(newnode
->expr
, casewhen
->expr
, Expr
*);
1764 MUTATE(newnode
->result
, casewhen
->result
, Expr
*);
1765 return (Node
*) newnode
;
1770 ArrayExpr
*arrayexpr
= (ArrayExpr
*) node
;
1773 FLATCOPY(newnode
, arrayexpr
, ArrayExpr
);
1774 MUTATE(newnode
->elements
, arrayexpr
->elements
, List
*);
1775 return (Node
*) newnode
;
1780 RowExpr
*rowexpr
= (RowExpr
*) node
;
1783 FLATCOPY(newnode
, rowexpr
, RowExpr
);
1784 MUTATE(newnode
->args
, rowexpr
->args
, List
*);
1785 /* Assume colnames needn't be duplicated */
1786 return (Node
*) newnode
;
1789 case T_RowCompareExpr
:
1791 RowCompareExpr
*rcexpr
= (RowCompareExpr
*) node
;
1792 RowCompareExpr
*newnode
;
1794 FLATCOPY(newnode
, rcexpr
, RowCompareExpr
);
1795 MUTATE(newnode
->largs
, rcexpr
->largs
, List
*);
1796 MUTATE(newnode
->rargs
, rcexpr
->rargs
, List
*);
1797 return (Node
*) newnode
;
1800 case T_CoalesceExpr
:
1802 CoalesceExpr
*coalesceexpr
= (CoalesceExpr
*) node
;
1803 CoalesceExpr
*newnode
;
1805 FLATCOPY(newnode
, coalesceexpr
, CoalesceExpr
);
1806 MUTATE(newnode
->args
, coalesceexpr
->args
, List
*);
1807 return (Node
*) newnode
;
1812 MinMaxExpr
*minmaxexpr
= (MinMaxExpr
*) node
;
1813 MinMaxExpr
*newnode
;
1815 FLATCOPY(newnode
, minmaxexpr
, MinMaxExpr
);
1816 MUTATE(newnode
->args
, minmaxexpr
->args
, List
*);
1817 return (Node
*) newnode
;
1822 XmlExpr
*xexpr
= (XmlExpr
*) node
;
1825 FLATCOPY(newnode
, xexpr
, XmlExpr
);
1826 MUTATE(newnode
->named_args
, xexpr
->named_args
, List
*);
1827 /* assume mutator does not care about arg_names */
1828 MUTATE(newnode
->args
, xexpr
->args
, List
*);
1829 return (Node
*) newnode
;
1834 NullIfExpr
*expr
= (NullIfExpr
*) node
;
1835 NullIfExpr
*newnode
;
1837 FLATCOPY(newnode
, expr
, NullIfExpr
);
1838 MUTATE(newnode
->args
, expr
->args
, List
*);
1839 return (Node
*) newnode
;
1844 NullTest
*ntest
= (NullTest
*) node
;
1847 FLATCOPY(newnode
, ntest
, NullTest
);
1848 MUTATE(newnode
->arg
, ntest
->arg
, Expr
*);
1849 return (Node
*) newnode
;
1854 BooleanTest
*btest
= (BooleanTest
*) node
;
1855 BooleanTest
*newnode
;
1857 FLATCOPY(newnode
, btest
, BooleanTest
);
1858 MUTATE(newnode
->arg
, btest
->arg
, Expr
*);
1859 return (Node
*) newnode
;
1862 case T_CoerceToDomain
:
1864 CoerceToDomain
*ctest
= (CoerceToDomain
*) node
;
1865 CoerceToDomain
*newnode
;
1867 FLATCOPY(newnode
, ctest
, CoerceToDomain
);
1868 MUTATE(newnode
->arg
, ctest
->arg
, Expr
*);
1869 return (Node
*) newnode
;
1874 TargetEntry
*targetentry
= (TargetEntry
*) node
;
1875 TargetEntry
*newnode
;
1877 FLATCOPY(newnode
, targetentry
, TargetEntry
);
1878 MUTATE(newnode
->expr
, targetentry
->expr
, Expr
*);
1879 return (Node
*) newnode
;
1883 /* Do nothing with a sub-Query, per discussion above */
1885 case T_WindowClause
:
1887 WindowClause
*wc
= (WindowClause
*) node
;
1888 WindowClause
*newnode
;
1890 FLATCOPY(newnode
, wc
, WindowClause
);
1891 MUTATE(newnode
->partitionClause
, wc
->partitionClause
, List
*);
1892 MUTATE(newnode
->orderClause
, wc
->orderClause
, List
*);
1893 return (Node
*) newnode
;
1896 case T_CommonTableExpr
:
1898 CommonTableExpr
*cte
= (CommonTableExpr
*) node
;
1899 CommonTableExpr
*newnode
;
1901 FLATCOPY(newnode
, cte
, CommonTableExpr
);
1904 * Also invoke the mutator on the CTE's Query node, so it
1905 * can recurse into the sub-query if it wants to.
1907 MUTATE(newnode
->ctequery
, cte
->ctequery
, Node
*);
1908 return (Node
*) newnode
;
1914 * We assume the mutator isn't interested in the list nodes
1915 * per se, so just invoke it on each list element. NOTE: this
1916 * would fail badly on a list with integer elements!
1922 foreach(temp
, (List
*) node
)
1924 resultlist
= lappend(resultlist
,
1925 mutator((Node
*) lfirst(temp
),
1928 return (Node
*) resultlist
;
1933 FromExpr
*from
= (FromExpr
*) node
;
1936 FLATCOPY(newnode
, from
, FromExpr
);
1937 MUTATE(newnode
->fromlist
, from
->fromlist
, List
*);
1938 MUTATE(newnode
->quals
, from
->quals
, Node
*);
1939 return (Node
*) newnode
;
1944 JoinExpr
*join
= (JoinExpr
*) node
;
1947 FLATCOPY(newnode
, join
, JoinExpr
);
1948 MUTATE(newnode
->larg
, join
->larg
, Node
*);
1949 MUTATE(newnode
->rarg
, join
->rarg
, Node
*);
1950 MUTATE(newnode
->quals
, join
->quals
, Node
*);
1951 /* We do not mutate alias or using by default */
1952 return (Node
*) newnode
;
1955 case T_SetOperationStmt
:
1957 SetOperationStmt
*setop
= (SetOperationStmt
*) node
;
1958 SetOperationStmt
*newnode
;
1960 FLATCOPY(newnode
, setop
, SetOperationStmt
);
1961 MUTATE(newnode
->larg
, setop
->larg
, Node
*);
1962 MUTATE(newnode
->rarg
, setop
->rarg
, Node
*);
1963 /* We do not mutate groupClauses by default */
1964 return (Node
*) newnode
;
1967 case T_PlaceHolderVar
:
1969 PlaceHolderVar
*phv
= (PlaceHolderVar
*) node
;
1970 PlaceHolderVar
*newnode
;
1972 FLATCOPY(newnode
, phv
, PlaceHolderVar
);
1973 MUTATE(newnode
->phexpr
, phv
->phexpr
, Expr
*);
1974 /* Assume we need not copy the relids bitmapset */
1975 return (Node
*) newnode
;
1978 case T_AppendRelInfo
:
1980 AppendRelInfo
*appinfo
= (AppendRelInfo
*) node
;
1981 AppendRelInfo
*newnode
;
1983 FLATCOPY(newnode
, appinfo
, AppendRelInfo
);
1984 MUTATE(newnode
->translated_vars
, appinfo
->translated_vars
, List
*);
1985 return (Node
*) newnode
;
1988 case T_PlaceHolderInfo
:
1990 PlaceHolderInfo
*phinfo
= (PlaceHolderInfo
*) node
;
1991 PlaceHolderInfo
*newnode
;
1993 FLATCOPY(newnode
, phinfo
, PlaceHolderInfo
);
1994 MUTATE(newnode
->ph_var
, phinfo
->ph_var
, PlaceHolderVar
*);
1995 /* Assume we need not copy the relids bitmapsets */
1996 return (Node
*) newnode
;
2000 elog(ERROR
, "unrecognized node type: %d",
2001 (int) nodeTag(node
));
2004 /* can't get here, but keep compiler happy */
2010 * query_tree_mutator --- initiate modification of a Query's expressions
2012 * This routine exists just to reduce the number of places that need to know
2013 * where all the expression subtrees of a Query are. Note it can be used
2014 * for starting a walk at top level of a Query regardless of whether the
2015 * mutator intends to descend into subqueries. It is also useful for
2016 * descending into subqueries within a mutator.
2018 * Some callers want to suppress mutating of certain items in the Query,
2019 * typically because they need to process them specially, or don't actually
2020 * want to recurse into subqueries. This is supported by the flags argument,
2021 * which is the bitwise OR of flag values to suppress mutating of
2022 * indicated items. (More flag bits may be added as needed.)
2024 * Normally the Query node itself is copied, but some callers want it to be
2025 * modified in-place; they must pass QTW_DONT_COPY_QUERY in flags. All
2026 * modified substructure is safely copied in any case.
2029 query_tree_mutator(Query
*query
,
2030 Node
*(*mutator
) (),
2034 Assert(query
!= NULL
&& IsA(query
, Query
));
2036 if (!(flags
& QTW_DONT_COPY_QUERY
))
2040 FLATCOPY(newquery
, query
, Query
);
2044 MUTATE(query
->targetList
, query
->targetList
, List
*);
2045 MUTATE(query
->returningList
, query
->returningList
, List
*);
2046 MUTATE(query
->jointree
, query
->jointree
, FromExpr
*);
2047 MUTATE(query
->setOperations
, query
->setOperations
, Node
*);
2048 MUTATE(query
->havingQual
, query
->havingQual
, Node
*);
2049 MUTATE(query
->limitOffset
, query
->limitOffset
, Node
*);
2050 MUTATE(query
->limitCount
, query
->limitCount
, Node
*);
2051 if (!(flags
& QTW_IGNORE_CTE_SUBQUERIES
))
2052 MUTATE(query
->cteList
, query
->cteList
, List
*);
2053 else /* else copy CTE list as-is */
2054 query
->cteList
= copyObject(query
->cteList
);
2055 query
->rtable
= range_table_mutator(query
->rtable
,
2056 mutator
, context
, flags
);
2061 * range_table_mutator is just the part of query_tree_mutator that processes
2062 * a query's rangetable. This is split out since it can be useful on
2066 range_table_mutator(List
*rtable
,
2067 Node
*(*mutator
) (),
2076 RangeTblEntry
*rte
= (RangeTblEntry
*) lfirst(rt
);
2077 RangeTblEntry
*newrte
;
2079 FLATCOPY(newrte
, rte
, RangeTblEntry
);
2080 switch (rte
->rtekind
)
2085 /* we don't bother to copy eref, aliases, etc; OK? */
2088 if (!(flags
& QTW_IGNORE_RT_SUBQUERIES
))
2090 CHECKFLATCOPY(newrte
->subquery
, rte
->subquery
, Query
);
2091 MUTATE(newrte
->subquery
, newrte
->subquery
, Query
*);
2095 /* else, copy RT subqueries as-is */
2096 newrte
->subquery
= copyObject(rte
->subquery
);
2100 if (!(flags
& QTW_IGNORE_JOINALIASES
))
2101 MUTATE(newrte
->joinaliasvars
, rte
->joinaliasvars
, List
*);
2104 /* else, copy join aliases as-is */
2105 newrte
->joinaliasvars
= copyObject(rte
->joinaliasvars
);
2109 MUTATE(newrte
->funcexpr
, rte
->funcexpr
, Node
*);
2112 MUTATE(newrte
->values_lists
, rte
->values_lists
, List
*);
2115 newrt
= lappend(newrt
, newrte
);
2121 * query_or_expression_tree_walker --- hybrid form
2123 * This routine will invoke query_tree_walker if called on a Query node,
2124 * else will invoke the walker directly. This is a useful way of starting
2125 * the recursion when the walker's normal change of state is not appropriate
2126 * for the outermost Query node.
2129 query_or_expression_tree_walker(Node
*node
,
2134 if (node
&& IsA(node
, Query
))
2135 return query_tree_walker((Query
*) node
,
2140 return walker(node
, context
);
2144 * query_or_expression_tree_mutator --- hybrid form
2146 * This routine will invoke query_tree_mutator if called on a Query node,
2147 * else will invoke the mutator directly. This is a useful way of starting
2148 * the recursion when the mutator's normal change of state is not appropriate
2149 * for the outermost Query node.
2152 query_or_expression_tree_mutator(Node
*node
,
2153 Node
*(*mutator
) (),
2157 if (node
&& IsA(node
, Query
))
2158 return (Node
*) query_tree_mutator((Query
*) node
,
2163 return mutator(node
, context
);
2168 * raw_expression_tree_walker --- walk raw parse trees
2170 * This has exactly the same API as expression_tree_walker, but instead of
2171 * walking post-analysis parse trees, it knows how to walk the node types
2172 * found in raw grammar output. (There is not currently any need for a
2173 * combined walker, so we keep them separate in the name of efficiency.)
2174 * Unlike expression_tree_walker, there is no special rule about query
2175 * boundaries: we descend to everything that's possibly interesting.
2177 * Currently, the node type coverage extends to SelectStmt and everything
2178 * that could appear under it, but not other statement types.
2181 raw_expression_tree_walker(Node
*node
, bool (*walker
) (), void *context
)
2186 * The walker has already visited the current node, and so we need only
2187 * recurse into any sub-nodes it has.
2192 /* Guard against stack overflow due to overly complex expressions */
2193 check_stack_depth();
2195 switch (nodeTag(node
))
2197 case T_SetToDefault
:
2198 case T_CurrentOfExpr
:
2207 /* primitive node types with no subnodes */
2210 /* we assume the colnames list isn't interesting */
2213 return walker(((RangeVar
*) node
)->alias
, context
);
2216 SubLink
*sublink
= (SubLink
*) node
;
2218 if (walker(sublink
->testexpr
, context
))
2220 /* we assume the operName is not interesting */
2221 if (walker(sublink
->subselect
, context
))
2227 CaseExpr
*caseexpr
= (CaseExpr
*) node
;
2229 if (walker(caseexpr
->arg
, context
))
2231 /* we assume walker doesn't care about CaseWhens, either */
2232 foreach(temp
, caseexpr
->args
)
2234 CaseWhen
*when
= (CaseWhen
*) lfirst(temp
);
2236 Assert(IsA(when
, CaseWhen
));
2237 if (walker(when
->expr
, context
))
2239 if (walker(when
->result
, context
))
2242 if (walker(caseexpr
->defresult
, context
))
2247 /* Assume colnames isn't interesting */
2248 return walker(((RowExpr
*) node
)->args
, context
);
2249 case T_CoalesceExpr
:
2250 return walker(((CoalesceExpr
*) node
)->args
, context
);
2252 return walker(((MinMaxExpr
*) node
)->args
, context
);
2255 XmlExpr
*xexpr
= (XmlExpr
*) node
;
2257 if (walker(xexpr
->named_args
, context
))
2259 /* we assume walker doesn't care about arg_names */
2260 if (walker(xexpr
->args
, context
))
2265 return walker(((NullTest
*) node
)->arg
, context
);
2267 return walker(((BooleanTest
*) node
)->arg
, context
);
2270 JoinExpr
*join
= (JoinExpr
*) node
;
2272 if (walker(join
->larg
, context
))
2274 if (walker(join
->rarg
, context
))
2276 if (walker(join
->quals
, context
))
2278 if (walker(join
->alias
, context
))
2280 /* using list is deemed uninteresting */
2285 IntoClause
*into
= (IntoClause
*) node
;
2287 if (walker(into
->rel
, context
))
2289 /* colNames, options are deemed uninteresting */
2293 foreach(temp
, (List
*) node
)
2295 if (walker((Node
*) lfirst(temp
), context
))
2301 SelectStmt
*stmt
= (SelectStmt
*) node
;
2303 if (walker(stmt
->distinctClause
, context
))
2305 if (walker(stmt
->intoClause
, context
))
2307 if (walker(stmt
->targetList
, context
))
2309 if (walker(stmt
->fromClause
, context
))
2311 if (walker(stmt
->whereClause
, context
))
2313 if (walker(stmt
->groupClause
, context
))
2315 if (walker(stmt
->havingClause
, context
))
2317 if (walker(stmt
->windowClause
, context
))
2319 if (walker(stmt
->withClause
, context
))
2321 if (walker(stmt
->valuesLists
, context
))
2323 if (walker(stmt
->sortClause
, context
))
2325 if (walker(stmt
->limitOffset
, context
))
2327 if (walker(stmt
->limitCount
, context
))
2329 if (walker(stmt
->lockingClause
, context
))
2331 if (walker(stmt
->larg
, context
))
2333 if (walker(stmt
->rarg
, context
))
2339 A_Expr
*expr
= (A_Expr
*) node
;
2341 if (walker(expr
->lexpr
, context
))
2343 if (walker(expr
->rexpr
, context
))
2345 /* operator name is deemed uninteresting */
2349 /* we assume the fields contain nothing interesting */
2353 FuncCall
*fcall
= (FuncCall
*) node
;
2355 if (walker(fcall
->args
, context
))
2357 if (walker(fcall
->over
, context
))
2359 /* function name is deemed uninteresting */
2364 A_Indices
*indices
= (A_Indices
*) node
;
2366 if (walker(indices
->lidx
, context
))
2368 if (walker(indices
->uidx
, context
))
2372 case T_A_Indirection
:
2374 A_Indirection
*indir
= (A_Indirection
*) node
;
2376 if (walker(indir
->arg
, context
))
2378 if (walker(indir
->indirection
, context
))
2383 return walker(((A_ArrayExpr
*) node
)->elements
, context
);
2386 ResTarget
*rt
= (ResTarget
*) node
;
2388 if (walker(rt
->indirection
, context
))
2390 if (walker(rt
->val
, context
))
2396 TypeCast
*tc
= (TypeCast
*) node
;
2398 if (walker(tc
->arg
, context
))
2400 if (walker(tc
->typename
, context
))
2405 return walker(((SortBy
*) node
)->node
, context
);
2408 WindowDef
*wd
= (WindowDef
*) node
;
2410 if (walker(wd
->partitionClause
, context
))
2412 if (walker(wd
->orderClause
, context
))
2416 case T_RangeSubselect
:
2418 RangeSubselect
*rs
= (RangeSubselect
*) node
;
2420 if (walker(rs
->subquery
, context
))
2422 if (walker(rs
->alias
, context
))
2426 case T_RangeFunction
:
2428 RangeFunction
*rf
= (RangeFunction
*) node
;
2430 if (walker(rf
->funccallnode
, context
))
2432 if (walker(rf
->alias
, context
))
2438 TypeName
*tn
= (TypeName
*) node
;
2440 if (walker(tn
->typmods
, context
))
2442 if (walker(tn
->arrayBounds
, context
))
2444 /* type name itself is deemed uninteresting */
2449 ColumnDef
*coldef
= (ColumnDef
*) node
;
2451 if (walker(coldef
->typename
, context
))
2453 if (walker(coldef
->raw_default
, context
))
2455 /* for now, constraints are ignored */
2458 case T_LockingClause
:
2459 return walker(((LockingClause
*) node
)->lockedRels
, context
);
2460 case T_XmlSerialize
:
2462 XmlSerialize
*xs
= (XmlSerialize
*) node
;
2464 if (walker(xs
->expr
, context
))
2466 if (walker(xs
->typename
, context
))
2471 return walker(((WithClause
*) node
)->ctes
, context
);
2472 case T_CommonTableExpr
:
2473 return walker(((CommonTableExpr
*) node
)->ctequery
, context
);
2475 elog(ERROR
, "unrecognized node type: %d",
2476 (int) nodeTag(node
));