1/*-------------------------------------------------------------------------
2 *
3 * nodeFuncs.c
4 * Various general-purpose manipulations of Node trees
5 *
6 * Portions Copyright (c) 1996-2019, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
8 *
9 *
10 * IDENTIFICATION
11 * src/backend/nodes/nodeFuncs.c
12 *
13 *-------------------------------------------------------------------------
14 */
15#include "postgres.h"
16
17#include "catalog/pg_collation.h"
18#include "catalog/pg_type.h"
19#include "miscadmin.h"
20#include "nodes/makefuncs.h"
21#include "nodes/execnodes.h"
22#include "nodes/nodeFuncs.h"
23#include "nodes/pathnodes.h"
24#include "utils/builtins.h"
25#include "utils/lsyscache.h"
26
27
28static bool expression_returns_set_walker(Node *node, void *context);
29static int leftmostLoc(int loc1, int loc2);
30static bool fix_opfuncids_walker(Node *node, void *context);
31static bool planstate_walk_subplans(List *plans, bool (*walker) (),
32 void *context);
33static bool planstate_walk_members(PlanState **planstates, int nplans,
34 bool (*walker) (), void *context);
35
36
37/*
38 * exprType -
39 * returns the Oid of the type of the expression's result.
40 */
41Oid
42exprType(const Node *expr)
43{
44 Oid type;
45
46 if (!expr)
47 return InvalidOid;
48
49 switch (nodeTag(expr))
50 {
51 case T_Var:
52 type = ((const Var *) expr)->vartype;
53 break;
54 case T_Const:
55 type = ((const Const *) expr)->consttype;
56 break;
57 case T_Param:
58 type = ((const Param *) expr)->paramtype;
59 break;
60 case T_Aggref:
61 type = ((const Aggref *) expr)->aggtype;
62 break;
63 case T_GroupingFunc:
64 type = INT4OID;
65 break;
66 case T_WindowFunc:
67 type = ((const WindowFunc *) expr)->wintype;
68 break;
69 case T_SubscriptingRef:
70 {
71 const SubscriptingRef *sbsref = (const SubscriptingRef *) expr;
72
73 /* slice and/or store operations yield the container type */
74 if (sbsref->reflowerindexpr || sbsref->refassgnexpr)
75 type = sbsref->refcontainertype;
76 else
77 type = sbsref->refelemtype;
78 }
79 break;
80 case T_FuncExpr:
81 type = ((const FuncExpr *) expr)->funcresulttype;
82 break;
83 case T_NamedArgExpr:
84 type = exprType((Node *) ((const NamedArgExpr *) expr)->arg);
85 break;
86 case T_OpExpr:
87 type = ((const OpExpr *) expr)->opresulttype;
88 break;
89 case T_DistinctExpr:
90 type = ((const DistinctExpr *) expr)->opresulttype;
91 break;
92 case T_NullIfExpr:
93 type = ((const NullIfExpr *) expr)->opresulttype;
94 break;
95 case T_ScalarArrayOpExpr:
96 type = BOOLOID;
97 break;
98 case T_BoolExpr:
99 type = BOOLOID;
100 break;
101 case T_SubLink:
102 {
103 const SubLink *sublink = (const SubLink *) expr;
104
105 if (sublink->subLinkType == EXPR_SUBLINK ||
106 sublink->subLinkType == ARRAY_SUBLINK)
107 {
108 /* get the type of the subselect's first target column */
109 Query *qtree = (Query *) sublink->subselect;
110 TargetEntry *tent;
111
112 if (!qtree || !IsA(qtree, Query))
113 elog(ERROR, "cannot get type for untransformed sublink");
114 tent = linitial_node(TargetEntry, qtree->targetList);
115 Assert(!tent->resjunk);
116 type = exprType((Node *) tent->expr);
117 if (sublink->subLinkType == ARRAY_SUBLINK)
118 {
119 type = get_promoted_array_type(type);
120 if (!OidIsValid(type))
121 ereport(ERROR,
122 (errcode(ERRCODE_UNDEFINED_OBJECT),
123 errmsg("could not find array type for data type %s",
124 format_type_be(exprType((Node *) tent->expr)))));
125 }
126 }
127 else if (sublink->subLinkType == MULTIEXPR_SUBLINK)
128 {
129 /* MULTIEXPR is always considered to return RECORD */
130 type = RECORDOID;
131 }
132 else
133 {
134 /* for all other sublink types, result is boolean */
135 type = BOOLOID;
136 }
137 }
138 break;
139 case T_SubPlan:
140 {
141 const SubPlan *subplan = (const SubPlan *) expr;
142
143 if (subplan->subLinkType == EXPR_SUBLINK ||
144 subplan->subLinkType == ARRAY_SUBLINK)
145 {
146 /* get the type of the subselect's first target column */
147 type = subplan->firstColType;
148 if (subplan->subLinkType == ARRAY_SUBLINK)
149 {
150 type = get_promoted_array_type(type);
151 if (!OidIsValid(type))
152 ereport(ERROR,
153 (errcode(ERRCODE_UNDEFINED_OBJECT),
154 errmsg("could not find array type for data type %s",
155 format_type_be(subplan->firstColType))));
156 }
157 }
158 else if (subplan->subLinkType == MULTIEXPR_SUBLINK)
159 {
160 /* MULTIEXPR is always considered to return RECORD */
161 type = RECORDOID;
162 }
163 else
164 {
165 /* for all other subplan types, result is boolean */
166 type = BOOLOID;
167 }
168 }
169 break;
170 case T_AlternativeSubPlan:
171 {
172 const AlternativeSubPlan *asplan = (const AlternativeSubPlan *) expr;
173
174 /* subplans should all return the same thing */
175 type = exprType((Node *) linitial(asplan->subplans));
176 }
177 break;
178 case T_FieldSelect:
179 type = ((const FieldSelect *) expr)->resulttype;
180 break;
181 case T_FieldStore:
182 type = ((const FieldStore *) expr)->resulttype;
183 break;
184 case T_RelabelType:
185 type = ((const RelabelType *) expr)->resulttype;
186 break;
187 case T_CoerceViaIO:
188 type = ((const CoerceViaIO *) expr)->resulttype;
189 break;
190 case T_ArrayCoerceExpr:
191 type = ((const ArrayCoerceExpr *) expr)->resulttype;
192 break;
193 case T_ConvertRowtypeExpr:
194 type = ((const ConvertRowtypeExpr *) expr)->resulttype;
195 break;
196 case T_CollateExpr:
197 type = exprType((Node *) ((const CollateExpr *) expr)->arg);
198 break;
199 case T_CaseExpr:
200 type = ((const CaseExpr *) expr)->casetype;
201 break;
202 case T_CaseTestExpr:
203 type = ((const CaseTestExpr *) expr)->typeId;
204 break;
205 case T_ArrayExpr:
206 type = ((const ArrayExpr *) expr)->array_typeid;
207 break;
208 case T_RowExpr:
209 type = ((const RowExpr *) expr)->row_typeid;
210 break;
211 case T_RowCompareExpr:
212 type = BOOLOID;
213 break;
214 case T_CoalesceExpr:
215 type = ((const CoalesceExpr *) expr)->coalescetype;
216 break;
217 case T_MinMaxExpr:
218 type = ((const MinMaxExpr *) expr)->minmaxtype;
219 break;
220 case T_SQLValueFunction:
221 type = ((const SQLValueFunction *) expr)->type;
222 break;
223 case T_XmlExpr:
224 if (((const XmlExpr *) expr)->op == IS_DOCUMENT)
225 type = BOOLOID;
226 else if (((const XmlExpr *) expr)->op == IS_XMLSERIALIZE)
227 type = TEXTOID;
228 else
229 type = XMLOID;
230 break;
231 case T_NullTest:
232 type = BOOLOID;
233 break;
234 case T_BooleanTest:
235 type = BOOLOID;
236 break;
237 case T_CoerceToDomain:
238 type = ((const CoerceToDomain *) expr)->resulttype;
239 break;
240 case T_CoerceToDomainValue:
241 type = ((const CoerceToDomainValue *) expr)->typeId;
242 break;
243 case T_SetToDefault:
244 type = ((const SetToDefault *) expr)->typeId;
245 break;
246 case T_CurrentOfExpr:
247 type = BOOLOID;
248 break;
249 case T_NextValueExpr:
250 type = ((const NextValueExpr *) expr)->typeId;
251 break;
252 case T_InferenceElem:
253 {
254 const InferenceElem *n = (const InferenceElem *) expr;
255
256 type = exprType((Node *) n->expr);
257 }
258 break;
259 case T_PlaceHolderVar:
260 type = exprType((Node *) ((const PlaceHolderVar *) expr)->phexpr);
261 break;
262 default:
263 elog(ERROR, "unrecognized node type: %d", (int) nodeTag(expr));
264 type = InvalidOid; /* keep compiler quiet */
265 break;
266 }
267 return type;
268}
269
270/*
271 * exprTypmod -
272 * returns the type-specific modifier of the expression's result type,
273 * if it can be determined. In many cases, it can't and we return -1.
274 */
275int32
276exprTypmod(const Node *expr)
277{
278 if (!expr)
279 return -1;
280
281 switch (nodeTag(expr))
282 {
283 case T_Var:
284 return ((const Var *) expr)->vartypmod;
285 case T_Const:
286 return ((const Const *) expr)->consttypmod;
287 case T_Param:
288 return ((const Param *) expr)->paramtypmod;
289 case T_SubscriptingRef:
290 /* typmod is the same for container or element */
291 return ((const SubscriptingRef *) expr)->reftypmod;
292 case T_FuncExpr:
293 {
294 int32 coercedTypmod;
295
296 /* Be smart about length-coercion functions... */
297 if (exprIsLengthCoercion(expr, &coercedTypmod))
298 return coercedTypmod;
299 }
300 break;
301 case T_NamedArgExpr:
302 return exprTypmod((Node *) ((const NamedArgExpr *) expr)->arg);
303 case T_NullIfExpr:
304 {
305 /*
306 * Result is either first argument or NULL, so we can report
307 * first argument's typmod if known.
308 */
309 const NullIfExpr *nexpr = (const NullIfExpr *) expr;
310
311 return exprTypmod((Node *) linitial(nexpr->args));
312 }
313 break;
314 case T_SubLink:
315 {
316 const SubLink *sublink = (const SubLink *) expr;
317
318 if (sublink->subLinkType == EXPR_SUBLINK ||
319 sublink->subLinkType == ARRAY_SUBLINK)
320 {
321 /* get the typmod of the subselect's first target column */
322 Query *qtree = (Query *) sublink->subselect;
323 TargetEntry *tent;
324
325 if (!qtree || !IsA(qtree, Query))
326 elog(ERROR, "cannot get type for untransformed sublink");
327 tent = linitial_node(TargetEntry, qtree->targetList);
328 Assert(!tent->resjunk);
329 return exprTypmod((Node *) tent->expr);
330 /* note we don't need to care if it's an array */
331 }
332 /* otherwise, result is RECORD or BOOLEAN, typmod is -1 */
333 }
334 break;
335 case T_SubPlan:
336 {
337 const SubPlan *subplan = (const SubPlan *) expr;
338
339 if (subplan->subLinkType == EXPR_SUBLINK ||
340 subplan->subLinkType == ARRAY_SUBLINK)
341 {
342 /* get the typmod of the subselect's first target column */
343 /* note we don't need to care if it's an array */
344 return subplan->firstColTypmod;
345 }
346 /* otherwise, result is RECORD or BOOLEAN, typmod is -1 */
347 }
348 break;
349 case T_AlternativeSubPlan:
350 {
351 const AlternativeSubPlan *asplan = (const AlternativeSubPlan *) expr;
352
353 /* subplans should all return the same thing */
354 return exprTypmod((Node *) linitial(asplan->subplans));
355 }
356 break;
357 case T_FieldSelect:
358 return ((const FieldSelect *) expr)->resulttypmod;
359 case T_RelabelType:
360 return ((const RelabelType *) expr)->resulttypmod;
361 case T_ArrayCoerceExpr:
362 return ((const ArrayCoerceExpr *) expr)->resulttypmod;
363 case T_CollateExpr:
364 return exprTypmod((Node *) ((const CollateExpr *) expr)->arg);
365 case T_CaseExpr:
366 {
367 /*
368 * If all the alternatives agree on type/typmod, return that
369 * typmod, else use -1
370 */
371 const CaseExpr *cexpr = (const CaseExpr *) expr;
372 Oid casetype = cexpr->casetype;
373 int32 typmod;
374 ListCell *arg;
375
376 if (!cexpr->defresult)
377 return -1;
378 if (exprType((Node *) cexpr->defresult) != casetype)
379 return -1;
380 typmod = exprTypmod((Node *) cexpr->defresult);
381 if (typmod < 0)
382 return -1; /* no point in trying harder */
383 foreach(arg, cexpr->args)
384 {
385 CaseWhen *w = lfirst_node(CaseWhen, arg);
386
387 if (exprType((Node *) w->result) != casetype)
388 return -1;
389 if (exprTypmod((Node *) w->result) != typmod)
390 return -1;
391 }
392 return typmod;
393 }
394 break;
395 case T_CaseTestExpr:
396 return ((const CaseTestExpr *) expr)->typeMod;
397 case T_ArrayExpr:
398 {
399 /*
400 * If all the elements agree on type/typmod, return that
401 * typmod, else use -1
402 */
403 const ArrayExpr *arrayexpr = (const ArrayExpr *) expr;
404 Oid commontype;
405 int32 typmod;
406 ListCell *elem;
407
408 if (arrayexpr->elements == NIL)
409 return -1;
410 typmod = exprTypmod((Node *) linitial(arrayexpr->elements));
411 if (typmod < 0)
412 return -1; /* no point in trying harder */
413 if (arrayexpr->multidims)
414 commontype = arrayexpr->array_typeid;
415 else
416 commontype = arrayexpr->element_typeid;
417 foreach(elem, arrayexpr->elements)
418 {
419 Node *e = (Node *) lfirst(elem);
420
421 if (exprType(e) != commontype)
422 return -1;
423 if (exprTypmod(e) != typmod)
424 return -1;
425 }
426 return typmod;
427 }
428 break;
429 case T_CoalesceExpr:
430 {
431 /*
432 * If all the alternatives agree on type/typmod, return that
433 * typmod, else use -1
434 */
435 const CoalesceExpr *cexpr = (const CoalesceExpr *) expr;
436 Oid coalescetype = cexpr->coalescetype;
437 int32 typmod;
438 ListCell *arg;
439
440 if (exprType((Node *) linitial(cexpr->args)) != coalescetype)
441 return -1;
442 typmod = exprTypmod((Node *) linitial(cexpr->args));
443 if (typmod < 0)
444 return -1; /* no point in trying harder */
445 for_each_cell(arg, lnext(list_head(cexpr->args)))
446 {
447 Node *e = (Node *) lfirst(arg);
448
449 if (exprType(e) != coalescetype)
450 return -1;
451 if (exprTypmod(e) != typmod)
452 return -1;
453 }
454 return typmod;
455 }
456 break;
457 case T_MinMaxExpr:
458 {
459 /*
460 * If all the alternatives agree on type/typmod, return that
461 * typmod, else use -1
462 */
463 const MinMaxExpr *mexpr = (const MinMaxExpr *) expr;
464 Oid minmaxtype = mexpr->minmaxtype;
465 int32 typmod;
466 ListCell *arg;
467
468 if (exprType((Node *) linitial(mexpr->args)) != minmaxtype)
469 return -1;
470 typmod = exprTypmod((Node *) linitial(mexpr->args));
471 if (typmod < 0)
472 return -1; /* no point in trying harder */
473 for_each_cell(arg, lnext(list_head(mexpr->args)))
474 {
475 Node *e = (Node *) lfirst(arg);
476
477 if (exprType(e) != minmaxtype)
478 return -1;
479 if (exprTypmod(e) != typmod)
480 return -1;
481 }
482 return typmod;
483 }
484 break;
485 case T_SQLValueFunction:
486 return ((const SQLValueFunction *) expr)->typmod;
487 case T_CoerceToDomain:
488 return ((const CoerceToDomain *) expr)->resulttypmod;
489 case T_CoerceToDomainValue:
490 return ((const CoerceToDomainValue *) expr)->typeMod;
491 case T_SetToDefault:
492 return ((const SetToDefault *) expr)->typeMod;
493 case T_PlaceHolderVar:
494 return exprTypmod((Node *) ((const PlaceHolderVar *) expr)->phexpr);
495 default:
496 break;
497 }
498 return -1;
499}
500
501/*
502 * exprIsLengthCoercion
503 * Detect whether an expression tree is an application of a datatype's
504 * typmod-coercion function. Optionally extract the result's typmod.
505 *
506 * If coercedTypmod is not NULL, the typmod is stored there if the expression
507 * is a length-coercion function, else -1 is stored there.
508 *
509 * Note that a combined type-and-length coercion will be treated as a
510 * length coercion by this routine.
511 */
512bool
513exprIsLengthCoercion(const Node *expr, int32 *coercedTypmod)
514{
515 if (coercedTypmod != NULL)
516 *coercedTypmod = -1; /* default result on failure */
517
518 /*
519 * Scalar-type length coercions are FuncExprs, array-type length coercions
520 * are ArrayCoerceExprs
521 */
522 if (expr && IsA(expr, FuncExpr))
523 {
524 const FuncExpr *func = (const FuncExpr *) expr;
525 int nargs;
526 Const *second_arg;
527
528 /*
529 * If it didn't come from a coercion context, reject.
530 */
531 if (func->funcformat != COERCE_EXPLICIT_CAST &&
532 func->funcformat != COERCE_IMPLICIT_CAST)
533 return false;
534
535 /*
536 * If it's not a two-argument or three-argument function with the
537 * second argument being an int4 constant, it can't have been created
538 * from a length coercion (it must be a type coercion, instead).
539 */
540 nargs = list_length(func->args);
541 if (nargs < 2 || nargs > 3)
542 return false;
543
544 second_arg = (Const *) lsecond(func->args);
545 if (!IsA(second_arg, Const) ||
546 second_arg->consttype != INT4OID ||
547 second_arg->constisnull)
548 return false;
549
550 /*
551 * OK, it is indeed a length-coercion function.
552 */
553 if (coercedTypmod != NULL)
554 *coercedTypmod = DatumGetInt32(second_arg->constvalue);
555
556 return true;
557 }
558
559 if (expr && IsA(expr, ArrayCoerceExpr))
560 {
561 const ArrayCoerceExpr *acoerce = (const ArrayCoerceExpr *) expr;
562
563 /* It's not a length coercion unless there's a nondefault typmod */
564 if (acoerce->resulttypmod < 0)
565 return false;
566
567 /*
568 * OK, it is indeed a length-coercion expression.
569 */
570 if (coercedTypmod != NULL)
571 *coercedTypmod = acoerce->resulttypmod;
572
573 return true;
574 }
575
576 return false;
577}
578
579/*
580 * relabel_to_typmod
581 * Add a RelabelType node that changes just the typmod of the expression.
582 *
583 * This is primarily intended to be used during planning. Therefore, it
584 * strips any existing RelabelType nodes to maintain the planner's invariant
585 * that there are not adjacent RelabelTypes.
586 */
587Node *
588relabel_to_typmod(Node *expr, int32 typmod)
589{
590 Oid type = exprType(expr);
591 Oid coll = exprCollation(expr);
592
593 /* Strip any existing RelabelType node(s) */
594 while (expr && IsA(expr, RelabelType))
595 expr = (Node *) ((RelabelType *) expr)->arg;
596
597 /* Apply new typmod, preserving the previous exposed type and collation */
598 return (Node *) makeRelabelType((Expr *) expr, type, typmod, coll,
599 COERCE_EXPLICIT_CAST);
600}
601
602/*
603 * strip_implicit_coercions: remove implicit coercions at top level of tree
604 *
605 * This doesn't modify or copy the input expression tree, just return a
606 * pointer to a suitable place within it.
607 *
608 * Note: there isn't any useful thing we can do with a RowExpr here, so
609 * just return it unchanged, even if it's marked as an implicit coercion.
610 */
611Node *
612strip_implicit_coercions(Node *node)
613{
614 if (node == NULL)
615 return NULL;
616 if (IsA(node, FuncExpr))
617 {
618 FuncExpr *f = (FuncExpr *) node;
619
620 if (f->funcformat == COERCE_IMPLICIT_CAST)
621 return strip_implicit_coercions(linitial(f->args));
622 }
623 else if (IsA(node, RelabelType))
624 {
625 RelabelType *r = (RelabelType *) node;
626
627 if (r->relabelformat == COERCE_IMPLICIT_CAST)
628 return strip_implicit_coercions((Node *) r->arg);
629 }
630 else if (IsA(node, CoerceViaIO))
631 {
632 CoerceViaIO *c = (CoerceViaIO *) node;
633
634 if (c->coerceformat == COERCE_IMPLICIT_CAST)
635 return strip_implicit_coercions((Node *) c->arg);
636 }
637 else if (IsA(node, ArrayCoerceExpr))
638 {
639 ArrayCoerceExpr *c = (ArrayCoerceExpr *) node;
640
641 if (c->coerceformat == COERCE_IMPLICIT_CAST)
642 return strip_implicit_coercions((Node *) c->arg);
643 }
644 else if (IsA(node, ConvertRowtypeExpr))
645 {
646 ConvertRowtypeExpr *c = (ConvertRowtypeExpr *) node;
647
648 if (c->convertformat == COERCE_IMPLICIT_CAST)
649 return strip_implicit_coercions((Node *) c->arg);
650 }
651 else if (IsA(node, CoerceToDomain))
652 {
653 CoerceToDomain *c = (CoerceToDomain *) node;
654
655 if (c->coercionformat == COERCE_IMPLICIT_CAST)
656 return strip_implicit_coercions((Node *) c->arg);
657 }
658 return node;
659}
660
661/*
662 * expression_returns_set
663 * Test whether an expression returns a set result.
664 *
665 * Because we use expression_tree_walker(), this can also be applied to
666 * whole targetlists; it'll produce true if any one of the tlist items
667 * returns a set.
668 */
669bool
670expression_returns_set(Node *clause)
671{
672 return expression_returns_set_walker(clause, NULL);
673}
674
675static bool
676expression_returns_set_walker(Node *node, void *context)
677{
678 if (node == NULL)
679 return false;
680 if (IsA(node, FuncExpr))
681 {
682 FuncExpr *expr = (FuncExpr *) node;
683
684 if (expr->funcretset)
685 return true;
686 /* else fall through to check args */
687 }
688 if (IsA(node, OpExpr))
689 {
690 OpExpr *expr = (OpExpr *) node;
691
692 if (expr->opretset)
693 return true;
694 /* else fall through to check args */
695 }
696
697 /* Avoid recursion for some cases that parser checks not to return a set */
698 if (IsA(node, Aggref))
699 return false;
700 if (IsA(node, WindowFunc))
701 return false;
702
703 return expression_tree_walker(node, expression_returns_set_walker,
704 context);
705}
706
707
708/*
709 * exprCollation -
710 * returns the Oid of the collation of the expression's result.
711 *
712 * Note: expression nodes that can invoke functions generally have an
713 * "inputcollid" field, which is what the function should use as collation.
714 * That is the resolved common collation of the node's inputs. It is often
715 * but not always the same as the result collation; in particular, if the
716 * function produces a non-collatable result type from collatable inputs
717 * or vice versa, the two are different.
718 */
719Oid
720exprCollation(const Node *expr)
721{
722 Oid coll;
723
724 if (!expr)
725 return InvalidOid;
726
727 switch (nodeTag(expr))
728 {
729 case T_Var:
730 coll = ((const Var *) expr)->varcollid;
731 break;
732 case T_Const:
733 coll = ((const Const *) expr)->constcollid;
734 break;
735 case T_Param:
736 coll = ((const Param *) expr)->paramcollid;
737 break;
738 case T_Aggref:
739 coll = ((const Aggref *) expr)->aggcollid;
740 break;
741 case T_GroupingFunc:
742 coll = InvalidOid;
743 break;
744 case T_WindowFunc:
745 coll = ((const WindowFunc *) expr)->wincollid;
746 break;
747 case T_SubscriptingRef:
748 coll = ((const SubscriptingRef *) expr)->refcollid;
749 break;
750 case T_FuncExpr:
751 coll = ((const FuncExpr *) expr)->funccollid;
752 break;
753 case T_NamedArgExpr:
754 coll = exprCollation((Node *) ((const NamedArgExpr *) expr)->arg);
755 break;
756 case T_OpExpr:
757 coll = ((const OpExpr *) expr)->opcollid;
758 break;
759 case T_DistinctExpr:
760 coll = ((const DistinctExpr *) expr)->opcollid;
761 break;
762 case T_NullIfExpr:
763 coll = ((const NullIfExpr *) expr)->opcollid;
764 break;
765 case T_ScalarArrayOpExpr:
766 coll = InvalidOid; /* result is always boolean */
767 break;
768 case T_BoolExpr:
769 coll = InvalidOid; /* result is always boolean */
770 break;
771 case T_SubLink:
772 {
773 const SubLink *sublink = (const SubLink *) expr;
774
775 if (sublink->subLinkType == EXPR_SUBLINK ||
776 sublink->subLinkType == ARRAY_SUBLINK)
777 {
778 /* get the collation of subselect's first target column */
779 Query *qtree = (Query *) sublink->subselect;
780 TargetEntry *tent;
781
782 if (!qtree || !IsA(qtree, Query))
783 elog(ERROR, "cannot get collation for untransformed sublink");
784 tent = linitial_node(TargetEntry, qtree->targetList);
785 Assert(!tent->resjunk);
786 coll = exprCollation((Node *) tent->expr);
787 /* collation doesn't change if it's converted to array */
788 }
789 else
790 {
791 /* otherwise, result is RECORD or BOOLEAN */
792 coll = InvalidOid;
793 }
794 }
795 break;
796 case T_SubPlan:
797 {
798 const SubPlan *subplan = (const SubPlan *) expr;
799
800 if (subplan->subLinkType == EXPR_SUBLINK ||
801 subplan->subLinkType == ARRAY_SUBLINK)
802 {
803 /* get the collation of subselect's first target column */
804 coll = subplan->firstColCollation;
805 /* collation doesn't change if it's converted to array */
806 }
807 else
808 {
809 /* otherwise, result is RECORD or BOOLEAN */
810 coll = InvalidOid;
811 }
812 }
813 break;
814 case T_AlternativeSubPlan:
815 {
816 const AlternativeSubPlan *asplan = (const AlternativeSubPlan *) expr;
817
818 /* subplans should all return the same thing */
819 coll = exprCollation((Node *) linitial(asplan->subplans));
820 }
821 break;
822 case T_FieldSelect:
823 coll = ((const FieldSelect *) expr)->resultcollid;
824 break;
825 case T_FieldStore:
826 coll = InvalidOid; /* result is always composite */
827 break;
828 case T_RelabelType:
829 coll = ((const RelabelType *) expr)->resultcollid;
830 break;
831 case T_CoerceViaIO:
832 coll = ((const CoerceViaIO *) expr)->resultcollid;
833 break;
834 case T_ArrayCoerceExpr:
835 coll = ((const ArrayCoerceExpr *) expr)->resultcollid;
836 break;
837 case T_ConvertRowtypeExpr:
838 coll = InvalidOid; /* result is always composite */
839 break;
840 case T_CollateExpr:
841 coll = ((const CollateExpr *) expr)->collOid;
842 break;
843 case T_CaseExpr:
844 coll = ((const CaseExpr *) expr)->casecollid;
845 break;
846 case T_CaseTestExpr:
847 coll = ((const CaseTestExpr *) expr)->collation;
848 break;
849 case T_ArrayExpr:
850 coll = ((const ArrayExpr *) expr)->array_collid;
851 break;
852 case T_RowExpr:
853 coll = InvalidOid; /* result is always composite */
854 break;
855 case T_RowCompareExpr:
856 coll = InvalidOid; /* result is always boolean */
857 break;
858 case T_CoalesceExpr:
859 coll = ((const CoalesceExpr *) expr)->coalescecollid;
860 break;
861 case T_MinMaxExpr:
862 coll = ((const MinMaxExpr *) expr)->minmaxcollid;
863 break;
864 case T_SQLValueFunction:
865 /* Returns either NAME or a non-collatable type */
866 if (((const SQLValueFunction *) expr)->type == NAMEOID)
867 coll = C_COLLATION_OID;
868 else
869 coll = InvalidOid;
870 break;
871 case T_XmlExpr:
872
873 /*
874 * XMLSERIALIZE returns text from non-collatable inputs, so its
875 * collation is always default. The other cases return boolean or
876 * XML, which are non-collatable.
877 */
878 if (((const XmlExpr *) expr)->op == IS_XMLSERIALIZE)
879 coll = DEFAULT_COLLATION_OID;
880 else
881 coll = InvalidOid;
882 break;
883 case T_NullTest:
884 coll = InvalidOid; /* result is always boolean */
885 break;
886 case T_BooleanTest:
887 coll = InvalidOid; /* result is always boolean */
888 break;
889 case T_CoerceToDomain:
890 coll = ((const CoerceToDomain *) expr)->resultcollid;
891 break;
892 case T_CoerceToDomainValue:
893 coll = ((const CoerceToDomainValue *) expr)->collation;
894 break;
895 case T_SetToDefault:
896 coll = ((const SetToDefault *) expr)->collation;
897 break;
898 case T_CurrentOfExpr:
899 coll = InvalidOid; /* result is always boolean */
900 break;
901 case T_NextValueExpr:
902 coll = InvalidOid; /* result is always an integer type */
903 break;
904 case T_InferenceElem:
905 coll = exprCollation((Node *) ((const InferenceElem *) expr)->expr);
906 break;
907 case T_PlaceHolderVar:
908 coll = exprCollation((Node *) ((const PlaceHolderVar *) expr)->phexpr);
909 break;
910 default:
911 elog(ERROR, "unrecognized node type: %d", (int) nodeTag(expr));
912 coll = InvalidOid; /* keep compiler quiet */
913 break;
914 }
915 return coll;
916}
917
918/*
919 * exprInputCollation -
920 * returns the Oid of the collation a function should use, if available.
921 *
922 * Result is InvalidOid if the node type doesn't store this information.
923 */
924Oid
925exprInputCollation(const Node *expr)
926{
927 Oid coll;
928
929 if (!expr)
930 return InvalidOid;
931
932 switch (nodeTag(expr))
933 {
934 case T_Aggref:
935 coll = ((const Aggref *) expr)->inputcollid;
936 break;
937 case T_WindowFunc:
938 coll = ((const WindowFunc *) expr)->inputcollid;
939 break;
940 case T_FuncExpr:
941 coll = ((const FuncExpr *) expr)->inputcollid;
942 break;
943 case T_OpExpr:
944 coll = ((const OpExpr *) expr)->inputcollid;
945 break;
946 case T_DistinctExpr:
947 coll = ((const DistinctExpr *) expr)->inputcollid;
948 break;
949 case T_NullIfExpr:
950 coll = ((const NullIfExpr *) expr)->inputcollid;
951 break;
952 case T_ScalarArrayOpExpr:
953 coll = ((const ScalarArrayOpExpr *) expr)->inputcollid;
954 break;
955 case T_MinMaxExpr:
956 coll = ((const MinMaxExpr *) expr)->inputcollid;
957 break;
958 default:
959 coll = InvalidOid;
960 break;
961 }
962 return coll;
963}
964
965/*
966 * exprSetCollation -
967 * Assign collation information to an expression tree node.
968 *
969 * Note: since this is only used during parse analysis, we don't need to
970 * worry about subplans or PlaceHolderVars.
971 */
972void
973exprSetCollation(Node *expr, Oid collation)
974{
975 switch (nodeTag(expr))
976 {
977 case T_Var:
978 ((Var *) expr)->varcollid = collation;
979 break;
980 case T_Const:
981 ((Const *) expr)->constcollid = collation;
982 break;
983 case T_Param:
984 ((Param *) expr)->paramcollid = collation;
985 break;
986 case T_Aggref:
987 ((Aggref *) expr)->aggcollid = collation;
988 break;
989 case T_GroupingFunc:
990 Assert(!OidIsValid(collation));
991 break;
992 case T_WindowFunc:
993 ((WindowFunc *) expr)->wincollid = collation;
994 break;
995 case T_SubscriptingRef:
996 ((SubscriptingRef *) expr)->refcollid = collation;
997 break;
998 case T_FuncExpr:
999 ((FuncExpr *) expr)->funccollid = collation;
1000 break;
1001 case T_NamedArgExpr:
1002 Assert(collation == exprCollation((Node *) ((NamedArgExpr *) expr)->arg));
1003 break;
1004 case T_OpExpr:
1005 ((OpExpr *) expr)->opcollid = collation;
1006 break;
1007 case T_DistinctExpr:
1008 ((DistinctExpr *) expr)->opcollid = collation;
1009 break;
1010 case T_NullIfExpr:
1011 ((NullIfExpr *) expr)->opcollid = collation;
1012 break;
1013 case T_ScalarArrayOpExpr:
1014 Assert(!OidIsValid(collation)); /* result is always boolean */
1015 break;
1016 case T_BoolExpr:
1017 Assert(!OidIsValid(collation)); /* result is always boolean */
1018 break;
1019 case T_SubLink:
1020#ifdef USE_ASSERT_CHECKING
1021 {
1022 SubLink *sublink = (SubLink *) expr;
1023
1024 if (sublink->subLinkType == EXPR_SUBLINK ||
1025 sublink->subLinkType == ARRAY_SUBLINK)
1026 {
1027 /* get the collation of subselect's first target column */
1028 Query *qtree = (Query *) sublink->subselect;
1029 TargetEntry *tent;
1030
1031 if (!qtree || !IsA(qtree, Query))
1032 elog(ERROR, "cannot set collation for untransformed sublink");
1033 tent = linitial_node(TargetEntry, qtree->targetList);
1034 Assert(!tent->resjunk);
1035 Assert(collation == exprCollation((Node *) tent->expr));
1036 }
1037 else
1038 {
1039 /* otherwise, result is RECORD or BOOLEAN */
1040 Assert(!OidIsValid(collation));
1041 }
1042 }
1043#endif /* USE_ASSERT_CHECKING */
1044 break;
1045 case T_FieldSelect:
1046 ((FieldSelect *) expr)->resultcollid = collation;
1047 break;
1048 case T_FieldStore:
1049 Assert(!OidIsValid(collation)); /* result is always composite */
1050 break;
1051 case T_RelabelType:
1052 ((RelabelType *) expr)->resultcollid = collation;
1053 break;
1054 case T_CoerceViaIO:
1055 ((CoerceViaIO *) expr)->resultcollid = collation;
1056 break;
1057 case T_ArrayCoerceExpr:
1058 ((ArrayCoerceExpr *) expr)->resultcollid = collation;
1059 break;
1060 case T_ConvertRowtypeExpr:
1061 Assert(!OidIsValid(collation)); /* result is always composite */
1062 break;
1063 case T_CaseExpr:
1064 ((CaseExpr *) expr)->casecollid = collation;
1065 break;
1066 case T_ArrayExpr:
1067 ((ArrayExpr *) expr)->array_collid = collation;
1068 break;
1069 case T_RowExpr:
1070 Assert(!OidIsValid(collation)); /* result is always composite */
1071 break;
1072 case T_RowCompareExpr:
1073 Assert(!OidIsValid(collation)); /* result is always boolean */
1074 break;
1075 case T_CoalesceExpr:
1076 ((CoalesceExpr *) expr)->coalescecollid = collation;
1077 break;
1078 case T_MinMaxExpr:
1079 ((MinMaxExpr *) expr)->minmaxcollid = collation;
1080 break;
1081 case T_SQLValueFunction:
1082 Assert((((SQLValueFunction *) expr)->type == NAMEOID) ?
1083 (collation == C_COLLATION_OID) :
1084 (collation == InvalidOid));
1085 break;
1086 case T_XmlExpr:
1087 Assert((((XmlExpr *) expr)->op == IS_XMLSERIALIZE) ?
1088 (collation == DEFAULT_COLLATION_OID) :
1089 (collation == InvalidOid));
1090 break;
1091 case T_NullTest:
1092 Assert(!OidIsValid(collation)); /* result is always boolean */
1093 break;
1094 case T_BooleanTest:
1095 Assert(!OidIsValid(collation)); /* result is always boolean */
1096 break;
1097 case T_CoerceToDomain:
1098 ((CoerceToDomain *) expr)->resultcollid = collation;
1099 break;
1100 case T_CoerceToDomainValue:
1101 ((CoerceToDomainValue *) expr)->collation = collation;
1102 break;
1103 case T_SetToDefault:
1104 ((SetToDefault *) expr)->collation = collation;
1105 break;
1106 case T_CurrentOfExpr:
1107 Assert(!OidIsValid(collation)); /* result is always boolean */
1108 break;
1109 case T_NextValueExpr:
1110 Assert(!OidIsValid(collation)); /* result is always an integer
1111 * type */
1112 break;
1113 default:
1114 elog(ERROR, "unrecognized node type: %d", (int) nodeTag(expr));
1115 break;
1116 }
1117}
1118
1119/*
1120 * exprSetInputCollation -
1121 * Assign input-collation information to an expression tree node.
1122 *
1123 * This is a no-op for node types that don't store their input collation.
1124 * Note we omit RowCompareExpr, which needs special treatment since it
1125 * contains multiple input collation OIDs.
1126 */
1127void
1128exprSetInputCollation(Node *expr, Oid inputcollation)
1129{
1130 switch (nodeTag(expr))
1131 {
1132 case T_Aggref:
1133 ((Aggref *) expr)->inputcollid = inputcollation;
1134 break;
1135 case T_WindowFunc:
1136 ((WindowFunc *) expr)->inputcollid = inputcollation;
1137 break;
1138 case T_FuncExpr:
1139 ((FuncExpr *) expr)->inputcollid = inputcollation;
1140 break;
1141 case T_OpExpr:
1142 ((OpExpr *) expr)->inputcollid = inputcollation;
1143 break;
1144 case T_DistinctExpr:
1145 ((DistinctExpr *) expr)->inputcollid = inputcollation;
1146 break;
1147 case T_NullIfExpr:
1148 ((NullIfExpr *) expr)->inputcollid = inputcollation;
1149 break;
1150 case T_ScalarArrayOpExpr:
1151 ((ScalarArrayOpExpr *) expr)->inputcollid = inputcollation;
1152 break;
1153 case T_MinMaxExpr:
1154 ((MinMaxExpr *) expr)->inputcollid = inputcollation;
1155 break;
1156 default:
1157 break;
1158 }
1159}
1160
1161
1162/*
1163 * exprLocation -
1164 * returns the parse location of an expression tree, for error reports
1165 *
1166 * -1 is returned if the location can't be determined.
1167 *
1168 * For expressions larger than a single token, the intent here is to
1169 * return the location of the expression's leftmost token, not necessarily
1170 * the topmost Node's location field. For example, an OpExpr's location
1171 * field will point at the operator name, but if it is not a prefix operator
1172 * then we should return the location of the left-hand operand instead.
1173 * The reason is that we want to reference the entire expression not just
1174 * that operator, and pointing to its start seems to be the most natural way.
1175 *
1176 * The location is not perfect --- for example, since the grammar doesn't
1177 * explicitly represent parentheses in the parsetree, given something that
1178 * had been written "(a + b) * c" we are going to point at "a" not "(".
1179 * But it should be plenty good enough for error reporting purposes.
1180 *
1181 * You might think that this code is overly general, for instance why check
1182 * the operands of a FuncExpr node, when the function name can be expected
1183 * to be to the left of them? There are a couple of reasons. The grammar
1184 * sometimes builds expressions that aren't quite what the user wrote;
1185 * for instance x IS NOT BETWEEN ... becomes a NOT-expression whose keyword
1186 * pointer is to the right of its leftmost argument. Also, nodes that were
1187 * inserted implicitly by parse analysis (such as FuncExprs for implicit
1188 * coercions) will have location -1, and so we can have odd combinations of
1189 * known and unknown locations in a tree.
1190 */
1191int
1192exprLocation(const Node *expr)
1193{
1194 int loc;
1195
1196 if (expr == NULL)
1197 return -1;
1198 switch (nodeTag(expr))
1199 {
1200 case T_RangeVar:
1201 loc = ((const RangeVar *) expr)->location;
1202 break;
1203 case T_TableFunc:
1204 loc = ((const TableFunc *) expr)->location;
1205 break;
1206 case T_Var:
1207 loc = ((const Var *) expr)->location;
1208 break;
1209 case T_Const:
1210 loc = ((const Const *) expr)->location;
1211 break;
1212 case T_Param:
1213 loc = ((const Param *) expr)->location;
1214 break;
1215 case T_Aggref:
1216 /* function name should always be the first thing */
1217 loc = ((const Aggref *) expr)->location;
1218 break;
1219 case T_GroupingFunc:
1220 loc = ((const GroupingFunc *) expr)->location;
1221 break;
1222 case T_WindowFunc:
1223 /* function name should always be the first thing */
1224 loc = ((const WindowFunc *) expr)->location;
1225 break;
1226 case T_SubscriptingRef:
1227 /* just use container argument's location */
1228 loc = exprLocation((Node *) ((const SubscriptingRef *) expr)->refexpr);
1229 break;
1230 case T_FuncExpr:
1231 {
1232 const FuncExpr *fexpr = (const FuncExpr *) expr;
1233
1234 /* consider both function name and leftmost arg */
1235 loc = leftmostLoc(fexpr->location,
1236 exprLocation((Node *) fexpr->args));
1237 }
1238 break;
1239 case T_NamedArgExpr:
1240 {
1241 const NamedArgExpr *na = (const NamedArgExpr *) expr;
1242
1243 /* consider both argument name and value */
1244 loc = leftmostLoc(na->location,
1245 exprLocation((Node *) na->arg));
1246 }
1247 break;
1248 case T_OpExpr:
1249 case T_DistinctExpr: /* struct-equivalent to OpExpr */
1250 case T_NullIfExpr: /* struct-equivalent to OpExpr */
1251 {
1252 const OpExpr *opexpr = (const OpExpr *) expr;
1253
1254 /* consider both operator name and leftmost arg */
1255 loc = leftmostLoc(opexpr->location,
1256 exprLocation((Node *) opexpr->args));
1257 }
1258 break;
1259 case T_ScalarArrayOpExpr:
1260 {
1261 const ScalarArrayOpExpr *saopexpr = (const ScalarArrayOpExpr *) expr;
1262
1263 /* consider both operator name and leftmost arg */
1264 loc = leftmostLoc(saopexpr->location,
1265 exprLocation((Node *) saopexpr->args));
1266 }
1267 break;
1268 case T_BoolExpr:
1269 {
1270 const BoolExpr *bexpr = (const BoolExpr *) expr;
1271
1272 /*
1273 * Same as above, to handle either NOT or AND/OR. We can't
1274 * special-case NOT because of the way that it's used for
1275 * things like IS NOT BETWEEN.
1276 */
1277 loc = leftmostLoc(bexpr->location,
1278 exprLocation((Node *) bexpr->args));
1279 }
1280 break;
1281 case T_SubLink:
1282 {
1283 const SubLink *sublink = (const SubLink *) expr;
1284
1285 /* check the testexpr, if any, and the operator/keyword */
1286 loc = leftmostLoc(exprLocation(sublink->testexpr),
1287 sublink->location);
1288 }
1289 break;
1290 case T_FieldSelect:
1291 /* just use argument's location */
1292 loc = exprLocation((Node *) ((const FieldSelect *) expr)->arg);
1293 break;
1294 case T_FieldStore:
1295 /* just use argument's location */
1296 loc = exprLocation((Node *) ((const FieldStore *) expr)->arg);
1297 break;
1298 case T_RelabelType:
1299 {
1300 const RelabelType *rexpr = (const RelabelType *) expr;
1301
1302 /* Much as above */
1303 loc = leftmostLoc(rexpr->location,
1304 exprLocation((Node *) rexpr->arg));
1305 }
1306 break;
1307 case T_CoerceViaIO:
1308 {
1309 const CoerceViaIO *cexpr = (const CoerceViaIO *) expr;
1310
1311 /* Much as above */
1312 loc = leftmostLoc(cexpr->location,
1313 exprLocation((Node *) cexpr->arg));
1314 }
1315 break;
1316 case T_ArrayCoerceExpr:
1317 {
1318 const ArrayCoerceExpr *cexpr = (const ArrayCoerceExpr *) expr;
1319
1320 /* Much as above */
1321 loc = leftmostLoc(cexpr->location,
1322 exprLocation((Node *) cexpr->arg));
1323 }
1324 break;
1325 case T_ConvertRowtypeExpr:
1326 {
1327 const ConvertRowtypeExpr *cexpr = (const ConvertRowtypeExpr *) expr;
1328
1329 /* Much as above */
1330 loc = leftmostLoc(cexpr->location,
1331 exprLocation((Node *) cexpr->arg));
1332 }
1333 break;
1334 case T_CollateExpr:
1335 /* just use argument's location */
1336 loc = exprLocation((Node *) ((const CollateExpr *) expr)->arg);
1337 break;
1338 case T_CaseExpr:
1339 /* CASE keyword should always be the first thing */
1340 loc = ((const CaseExpr *) expr)->location;
1341 break;
1342 case T_CaseWhen:
1343 /* WHEN keyword should always be the first thing */
1344 loc = ((const CaseWhen *) expr)->location;
1345 break;
1346 case T_ArrayExpr:
1347 /* the location points at ARRAY or [, which must be leftmost */
1348 loc = ((const ArrayExpr *) expr)->location;
1349 break;
1350 case T_RowExpr:
1351 /* the location points at ROW or (, which must be leftmost */
1352 loc = ((const RowExpr *) expr)->location;
1353 break;
1354 case T_RowCompareExpr:
1355 /* just use leftmost argument's location */
1356 loc = exprLocation((Node *) ((const RowCompareExpr *) expr)->largs);
1357 break;
1358 case T_CoalesceExpr:
1359 /* COALESCE keyword should always be the first thing */
1360 loc = ((const CoalesceExpr *) expr)->location;
1361 break;
1362 case T_MinMaxExpr:
1363 /* GREATEST/LEAST keyword should always be the first thing */
1364 loc = ((const MinMaxExpr *) expr)->location;
1365 break;
1366 case T_SQLValueFunction:
1367 /* function keyword should always be the first thing */
1368 loc = ((const SQLValueFunction *) expr)->location;
1369 break;
1370 case T_XmlExpr:
1371 {
1372 const XmlExpr *xexpr = (const XmlExpr *) expr;
1373
1374 /* consider both function name and leftmost arg */
1375 loc = leftmostLoc(xexpr->location,
1376 exprLocation((Node *) xexpr->args));
1377 }
1378 break;
1379 case T_NullTest:
1380 {
1381 const NullTest *nexpr = (const NullTest *) expr;
1382
1383 /* Much as above */
1384 loc = leftmostLoc(nexpr->location,
1385 exprLocation((Node *) nexpr->arg));
1386 }
1387 break;
1388 case T_BooleanTest:
1389 {
1390 const BooleanTest *bexpr = (const BooleanTest *) expr;
1391
1392 /* Much as above */
1393 loc = leftmostLoc(bexpr->location,
1394 exprLocation((Node *) bexpr->arg));
1395 }
1396 break;
1397 case T_CoerceToDomain:
1398 {
1399 const CoerceToDomain *cexpr = (const CoerceToDomain *) expr;
1400
1401 /* Much as above */
1402 loc = leftmostLoc(cexpr->location,
1403 exprLocation((Node *) cexpr->arg));
1404 }
1405 break;
1406 case T_CoerceToDomainValue:
1407 loc = ((const CoerceToDomainValue *) expr)->location;
1408 break;
1409 case T_SetToDefault:
1410 loc = ((const SetToDefault *) expr)->location;
1411 break;
1412 case T_TargetEntry:
1413 /* just use argument's location */
1414 loc = exprLocation((Node *) ((const TargetEntry *) expr)->expr);
1415 break;
1416 case T_IntoClause:
1417 /* use the contained RangeVar's location --- close enough */
1418 loc = exprLocation((Node *) ((const IntoClause *) expr)->rel);
1419 break;
1420 case T_List:
1421 {
1422 /* report location of first list member that has a location */
1423 ListCell *lc;
1424
1425 loc = -1; /* just to suppress compiler warning */
1426 foreach(lc, (const List *) expr)
1427 {
1428 loc = exprLocation((Node *) lfirst(lc));
1429 if (loc >= 0)
1430 break;
1431 }
1432 }
1433 break;
1434 case T_A_Expr:
1435 {
1436 const A_Expr *aexpr = (const A_Expr *) expr;
1437
1438 /* use leftmost of operator or left operand (if any) */
1439 /* we assume right operand can't be to left of operator */
1440 loc = leftmostLoc(aexpr->location,
1441 exprLocation(aexpr->lexpr));
1442 }
1443 break;
1444 case T_ColumnRef:
1445 loc = ((const ColumnRef *) expr)->location;
1446 break;
1447 case T_ParamRef:
1448 loc = ((const ParamRef *) expr)->location;
1449 break;
1450 case T_A_Const:
1451 loc = ((const A_Const *) expr)->location;
1452 break;
1453 case T_FuncCall:
1454 {
1455 const FuncCall *fc = (const FuncCall *) expr;
1456
1457 /* consider both function name and leftmost arg */
1458 /* (we assume any ORDER BY nodes must be to right of name) */
1459 loc = leftmostLoc(fc->location,
1460 exprLocation((Node *) fc->args));
1461 }
1462 break;
1463 case T_A_ArrayExpr:
1464 /* the location points at ARRAY or [, which must be leftmost */
1465 loc = ((const A_ArrayExpr *) expr)->location;
1466 break;
1467 case T_ResTarget:
1468 /* we need not examine the contained expression (if any) */
1469 loc = ((const ResTarget *) expr)->location;
1470 break;
1471 case T_MultiAssignRef:
1472 loc = exprLocation(((const MultiAssignRef *) expr)->source);
1473 break;
1474 case T_TypeCast:
1475 {
1476 const TypeCast *tc = (const TypeCast *) expr;
1477
1478 /*
1479 * This could represent CAST(), ::, or TypeName 'literal', so
1480 * any of the components might be leftmost.
1481 */
1482 loc = exprLocation(tc->arg);
1483 loc = leftmostLoc(loc, tc->typeName->location);
1484 loc = leftmostLoc(loc, tc->location);
1485 }
1486 break;
1487 case T_CollateClause:
1488 /* just use argument's location */
1489 loc = exprLocation(((const CollateClause *) expr)->arg);
1490 break;
1491 case T_SortBy:
1492 /* just use argument's location (ignore operator, if any) */
1493 loc = exprLocation(((const SortBy *) expr)->node);
1494 break;
1495 case T_WindowDef:
1496 loc = ((const WindowDef *) expr)->location;
1497 break;
1498 case T_RangeTableSample:
1499 loc = ((const RangeTableSample *) expr)->location;
1500 break;
1501 case T_TypeName:
1502 loc = ((const TypeName *) expr)->location;
1503 break;
1504 case T_ColumnDef:
1505 loc = ((const ColumnDef *) expr)->location;
1506 break;
1507 case T_Constraint:
1508 loc = ((const Constraint *) expr)->location;
1509 break;
1510 case T_FunctionParameter:
1511 /* just use typename's location */
1512 loc = exprLocation((Node *) ((const FunctionParameter *) expr)->argType);
1513 break;
1514 case T_XmlSerialize:
1515 /* XMLSERIALIZE keyword should always be the first thing */
1516 loc = ((const XmlSerialize *) expr)->location;
1517 break;
1518 case T_GroupingSet:
1519 loc = ((const GroupingSet *) expr)->location;
1520 break;
1521 case T_WithClause:
1522 loc = ((const WithClause *) expr)->location;
1523 break;
1524 case T_InferClause:
1525 loc = ((const InferClause *) expr)->location;
1526 break;
1527 case T_OnConflictClause:
1528 loc = ((const OnConflictClause *) expr)->location;
1529 break;
1530 case T_CommonTableExpr:
1531 loc = ((const CommonTableExpr *) expr)->location;
1532 break;
1533 case T_PlaceHolderVar:
1534 /* just use argument's location */
1535 loc = exprLocation((Node *) ((const PlaceHolderVar *) expr)->phexpr);
1536 break;
1537 case T_InferenceElem:
1538 /* just use nested expr's location */
1539 loc = exprLocation((Node *) ((const InferenceElem *) expr)->expr);
1540 break;
1541 case T_PartitionElem:
1542 loc = ((const PartitionElem *) expr)->location;
1543 break;
1544 case T_PartitionSpec:
1545 loc = ((const PartitionSpec *) expr)->location;
1546 break;
1547 case T_PartitionBoundSpec:
1548 loc = ((const PartitionBoundSpec *) expr)->location;
1549 break;
1550 case T_PartitionRangeDatum:
1551 loc = ((const PartitionRangeDatum *) expr)->location;
1552 break;
1553 default:
1554 /* for any other node type it's just unknown... */
1555 loc = -1;
1556 break;
1557 }
1558 return loc;
1559}
1560
1561/*
1562 * leftmostLoc - support for exprLocation
1563 *
1564 * Take the minimum of two parse location values, but ignore unknowns
1565 */
1566static int
1567leftmostLoc(int loc1, int loc2)
1568{
1569 if (loc1 < 0)
1570 return loc2;
1571 else if (loc2 < 0)
1572 return loc1;
1573 else
1574 return Min(loc1, loc2);
1575}
1576
1577
1578/*
1579 * fix_opfuncids
1580 * Calculate opfuncid field from opno for each OpExpr node in given tree.
1581 * The given tree can be anything expression_tree_walker handles.
1582 *
1583 * The argument is modified in-place. (This is OK since we'd want the
1584 * same change for any node, even if it gets visited more than once due to
1585 * shared structure.)
1586 */
1587void
1588fix_opfuncids(Node *node)
1589{
1590 /* This tree walk requires no special setup, so away we go... */
1591 fix_opfuncids_walker(node, NULL);
1592}
1593
1594static bool
1595fix_opfuncids_walker(Node *node, void *context)
1596{
1597 if (node == NULL)
1598 return false;
1599 if (IsA(node, OpExpr))
1600 set_opfuncid((OpExpr *) node);
1601 else if (IsA(node, DistinctExpr))
1602 set_opfuncid((OpExpr *) node); /* rely on struct equivalence */
1603 else if (IsA(node, NullIfExpr))
1604 set_opfuncid((OpExpr *) node); /* rely on struct equivalence */
1605 else if (IsA(node, ScalarArrayOpExpr))
1606 set_sa_opfuncid((ScalarArrayOpExpr *) node);
1607 return expression_tree_walker(node, fix_opfuncids_walker, context);
1608}
1609
1610/*
1611 * set_opfuncid
1612 * Set the opfuncid (procedure OID) in an OpExpr node,
1613 * if it hasn't been set already.
1614 *
1615 * Because of struct equivalence, this can also be used for
1616 * DistinctExpr and NullIfExpr nodes.
1617 */
1618void
1619set_opfuncid(OpExpr *opexpr)
1620{
1621 if (opexpr->opfuncid == InvalidOid)
1622 opexpr->opfuncid = get_opcode(opexpr->opno);
1623}
1624
1625/*
1626 * set_sa_opfuncid
1627 * As above, for ScalarArrayOpExpr nodes.
1628 */
1629void
1630set_sa_opfuncid(ScalarArrayOpExpr *opexpr)
1631{
1632 if (opexpr->opfuncid == InvalidOid)
1633 opexpr->opfuncid = get_opcode(opexpr->opno);
1634}
1635
1636
1637/*
1638 * check_functions_in_node -
1639 * apply checker() to each function OID contained in given expression node
1640 *
1641 * Returns true if the checker() function does; for nodes representing more
1642 * than one function call, returns true if the checker() function does so
1643 * for any of those functions. Returns false if node does not invoke any
1644 * SQL-visible function. Caller must not pass node == NULL.
1645 *
1646 * This function examines only the given node; it does not recurse into any
1647 * sub-expressions. Callers typically prefer to keep control of the recursion
1648 * for themselves, in case additional checks should be made, or because they
1649 * have special rules about which parts of the tree need to be visited.
1650 *
1651 * Note: we ignore MinMaxExpr, SQLValueFunction, XmlExpr, CoerceToDomain,
1652 * and NextValueExpr nodes, because they do not contain SQL function OIDs.
1653 * However, they can invoke SQL-visible functions, so callers should take
1654 * thought about how to treat them.
1655 */
1656bool
1657check_functions_in_node(Node *node, check_function_callback checker,
1658 void *context)
1659{
1660 switch (nodeTag(node))
1661 {
1662 case T_Aggref:
1663 {
1664 Aggref *expr = (Aggref *) node;
1665
1666 if (checker(expr->aggfnoid, context))
1667 return true;
1668 }
1669 break;
1670 case T_WindowFunc:
1671 {
1672 WindowFunc *expr = (WindowFunc *) node;
1673
1674 if (checker(expr->winfnoid, context))
1675 return true;
1676 }
1677 break;
1678 case T_FuncExpr:
1679 {
1680 FuncExpr *expr = (FuncExpr *) node;
1681
1682 if (checker(expr->funcid, context))
1683 return true;
1684 }
1685 break;
1686 case T_OpExpr:
1687 case T_DistinctExpr: /* struct-equivalent to OpExpr */
1688 case T_NullIfExpr: /* struct-equivalent to OpExpr */
1689 {
1690 OpExpr *expr = (OpExpr *) node;
1691
1692 /* Set opfuncid if it wasn't set already */
1693 set_opfuncid(expr);
1694 if (checker(expr->opfuncid, context))
1695 return true;
1696 }
1697 break;
1698 case T_ScalarArrayOpExpr:
1699 {
1700 ScalarArrayOpExpr *expr = (ScalarArrayOpExpr *) node;
1701
1702 set_sa_opfuncid(expr);
1703 if (checker(expr->opfuncid, context))
1704 return true;
1705 }
1706 break;
1707 case T_CoerceViaIO:
1708 {
1709 CoerceViaIO *expr = (CoerceViaIO *) node;
1710 Oid iofunc;
1711 Oid typioparam;
1712 bool typisvarlena;
1713
1714 /* check the result type's input function */
1715 getTypeInputInfo(expr->resulttype,
1716 &iofunc, &typioparam);
1717 if (checker(iofunc, context))
1718 return true;
1719 /* check the input type's output function */
1720 getTypeOutputInfo(exprType((Node *) expr->arg),
1721 &iofunc, &typisvarlena);
1722 if (checker(iofunc, context))
1723 return true;
1724 }
1725 break;
1726 case T_RowCompareExpr:
1727 {
1728 RowCompareExpr *rcexpr = (RowCompareExpr *) node;
1729 ListCell *opid;
1730
1731 foreach(opid, rcexpr->opnos)
1732 {
1733 Oid opfuncid = get_opcode(lfirst_oid(opid));
1734
1735 if (checker(opfuncid, context))
1736 return true;
1737 }
1738 }
1739 break;
1740 default:
1741 break;
1742 }
1743 return false;
1744}
1745
1746
1747/*
1748 * Standard expression-tree walking support
1749 *
1750 * We used to have near-duplicate code in many different routines that
1751 * understood how to recurse through an expression node tree. That was
1752 * a pain to maintain, and we frequently had bugs due to some particular
1753 * routine neglecting to support a particular node type. In most cases,
1754 * these routines only actually care about certain node types, and don't
1755 * care about other types except insofar as they have to recurse through
1756 * non-primitive node types. Therefore, we now provide generic tree-walking
1757 * logic to consolidate the redundant "boilerplate" code. There are
1758 * two versions: expression_tree_walker() and expression_tree_mutator().
1759 */
1760
1761/*
1762 * expression_tree_walker() is designed to support routines that traverse
1763 * a tree in a read-only fashion (although it will also work for routines
1764 * that modify nodes in-place but never add/delete/replace nodes).
1765 * A walker routine should look like this:
1766 *
1767 * bool my_walker (Node *node, my_struct *context)
1768 * {
1769 * if (node == NULL)
1770 * return false;
1771 * // check for nodes that special work is required for, eg:
1772 * if (IsA(node, Var))
1773 * {
1774 * ... do special actions for Var nodes
1775 * }
1776 * else if (IsA(node, ...))
1777 * {
1778 * ... do special actions for other node types
1779 * }
1780 * // for any node type not specially processed, do:
1781 * return expression_tree_walker(node, my_walker, (void *) context);
1782 * }
1783 *
1784 * The "context" argument points to a struct that holds whatever context
1785 * information the walker routine needs --- it can be used to return data
1786 * gathered by the walker, too. This argument is not touched by
1787 * expression_tree_walker, but it is passed down to recursive sub-invocations
1788 * of my_walker. The tree walk is started from a setup routine that
1789 * fills in the appropriate context struct, calls my_walker with the top-level
1790 * node of the tree, and then examines the results.
1791 *
1792 * The walker routine should return "false" to continue the tree walk, or
1793 * "true" to abort the walk and immediately return "true" to the top-level
1794 * caller. This can be used to short-circuit the traversal if the walker
1795 * has found what it came for. "false" is returned to the top-level caller
1796 * iff no invocation of the walker returned "true".
1797 *
1798 * The node types handled by expression_tree_walker include all those
1799 * normally found in target lists and qualifier clauses during the planning
1800 * stage. In particular, it handles List nodes since a cnf-ified qual clause
1801 * will have List structure at the top level, and it handles TargetEntry nodes
1802 * so that a scan of a target list can be handled without additional code.
1803 * Also, RangeTblRef, FromExpr, JoinExpr, and SetOperationStmt nodes are
1804 * handled, so that query jointrees and setOperation trees can be processed
1805 * without additional code.
1806 *
1807 * expression_tree_walker will handle SubLink nodes by recursing normally
1808 * into the "testexpr" subtree (which is an expression belonging to the outer
1809 * plan). It will also call the walker on the sub-Query node; however, when
1810 * expression_tree_walker itself is called on a Query node, it does nothing
1811 * and returns "false". The net effect is that unless the walker does
1812 * something special at a Query node, sub-selects will not be visited during
1813 * an expression tree walk. This is exactly the behavior wanted in many cases
1814 * --- and for those walkers that do want to recurse into sub-selects, special
1815 * behavior is typically needed anyway at the entry to a sub-select (such as
1816 * incrementing a depth counter). A walker that wants to examine sub-selects
1817 * should include code along the lines of:
1818 *
1819 * if (IsA(node, Query))
1820 * {
1821 * adjust context for subquery;
1822 * result = query_tree_walker((Query *) node, my_walker, context,
1823 * 0); // adjust flags as needed
1824 * restore context if needed;
1825 * return result;
1826 * }
1827 *
1828 * query_tree_walker is a convenience routine (see below) that calls the
1829 * walker on all the expression subtrees of the given Query node.
1830 *
1831 * expression_tree_walker will handle SubPlan nodes by recursing normally
1832 * into the "testexpr" and the "args" list (which are expressions belonging to
1833 * the outer plan). It will not touch the completed subplan, however. Since
1834 * there is no link to the original Query, it is not possible to recurse into
1835 * subselects of an already-planned expression tree. This is OK for current
1836 * uses, but may need to be revisited in future.
1837 */
1838
1839bool
1840expression_tree_walker(Node *node,
1841 bool (*walker) (),
1842 void *context)
1843{
1844 ListCell *temp;
1845
1846 /*
1847 * The walker has already visited the current node, and so we need only
1848 * recurse into any sub-nodes it has.
1849 *
1850 * We assume that the walker is not interested in List nodes per se, so
1851 * when we expect a List we just recurse directly to self without
1852 * bothering to call the walker.
1853 */
1854 if (node == NULL)
1855 return false;
1856
1857 /* Guard against stack overflow due to overly complex expressions */
1858 check_stack_depth();
1859
1860 switch (nodeTag(node))
1861 {
1862 case T_Var:
1863 case T_Const:
1864 case T_Param:
1865 case T_CaseTestExpr:
1866 case T_SQLValueFunction:
1867 case T_CoerceToDomainValue:
1868 case T_SetToDefault:
1869 case T_CurrentOfExpr:
1870 case T_NextValueExpr:
1871 case T_RangeTblRef:
1872 case T_SortGroupClause:
1873 /* primitive node types with no expression subnodes */
1874 break;
1875 case T_WithCheckOption:
1876 return walker(((WithCheckOption *) node)->qual, context);
1877 case T_Aggref:
1878 {
1879 Aggref *expr = (Aggref *) node;
1880
1881 /* recurse directly on List */
1882 if (expression_tree_walker((Node *) expr->aggdirectargs,
1883 walker, context))
1884 return true;
1885 if (expression_tree_walker((Node *) expr->args,
1886 walker, context))
1887 return true;
1888 if (expression_tree_walker((Node *) expr->aggorder,
1889 walker, context))
1890 return true;
1891 if (expression_tree_walker((Node *) expr->aggdistinct,
1892 walker, context))
1893 return true;
1894 if (walker((Node *) expr->aggfilter, context))
1895 return true;
1896 }
1897 break;
1898 case T_GroupingFunc:
1899 {
1900 GroupingFunc *grouping = (GroupingFunc *) node;
1901
1902 if (expression_tree_walker((Node *) grouping->args,
1903 walker, context))
1904 return true;
1905 }
1906 break;
1907 case T_WindowFunc:
1908 {
1909 WindowFunc *expr = (WindowFunc *) node;
1910
1911 /* recurse directly on List */
1912 if (expression_tree_walker((Node *) expr->args,
1913 walker, context))
1914 return true;
1915 if (walker((Node *) expr->aggfilter, context))
1916 return true;
1917 }
1918 break;
1919 case T_SubscriptingRef:
1920 {
1921 SubscriptingRef *sbsref = (SubscriptingRef *) node;
1922
1923 /* recurse directly for upper/lower container index lists */
1924 if (expression_tree_walker((Node *) sbsref->refupperindexpr,
1925 walker, context))
1926 return true;
1927 if (expression_tree_walker((Node *) sbsref->reflowerindexpr,
1928 walker, context))
1929 return true;
1930 /* walker must see the refexpr and refassgnexpr, however */
1931 if (walker(sbsref->refexpr, context))
1932 return true;
1933
1934 if (walker(sbsref->refassgnexpr, context))
1935 return true;
1936 }
1937 break;
1938 case T_FuncExpr:
1939 {
1940 FuncExpr *expr = (FuncExpr *) node;
1941
1942 if (expression_tree_walker((Node *) expr->args,
1943 walker, context))
1944 return true;
1945 }
1946 break;
1947 case T_NamedArgExpr:
1948 return walker(((NamedArgExpr *) node)->arg, context);
1949 case T_OpExpr:
1950 case T_DistinctExpr: /* struct-equivalent to OpExpr */
1951 case T_NullIfExpr: /* struct-equivalent to OpExpr */
1952 {
1953 OpExpr *expr = (OpExpr *) node;
1954
1955 if (expression_tree_walker((Node *) expr->args,
1956 walker, context))
1957 return true;
1958 }
1959 break;
1960 case T_ScalarArrayOpExpr:
1961 {
1962 ScalarArrayOpExpr *expr = (ScalarArrayOpExpr *) node;
1963
1964 if (expression_tree_walker((Node *) expr->args,
1965 walker, context))
1966 return true;
1967 }
1968 break;
1969 case T_BoolExpr:
1970 {
1971 BoolExpr *expr = (BoolExpr *) node;
1972
1973 if (expression_tree_walker((Node *) expr->args,
1974 walker, context))
1975 return true;
1976 }
1977 break;
1978 case T_SubLink:
1979 {
1980 SubLink *sublink = (SubLink *) node;
1981
1982 if (walker(sublink->testexpr, context))
1983 return true;
1984
1985 /*
1986 * Also invoke the walker on the sublink's Query node, so it
1987 * can recurse into the sub-query if it wants to.
1988 */
1989 return walker(sublink->subselect, context);
1990 }
1991 break;
1992 case T_SubPlan:
1993 {
1994 SubPlan *subplan = (SubPlan *) node;
1995
1996 /* recurse into the testexpr, but not into the Plan */
1997 if (walker(subplan->testexpr, context))
1998 return true;
1999 /* also examine args list */
2000 if (expression_tree_walker((Node *) subplan->args,
2001 walker, context))
2002 return true;
2003 }
2004 break;
2005 case T_AlternativeSubPlan:
2006 return walker(((AlternativeSubPlan *) node)->subplans, context);
2007 case T_FieldSelect:
2008 return walker(((FieldSelect *) node)->arg, context);
2009 case T_FieldStore:
2010 {
2011 FieldStore *fstore = (FieldStore *) node;
2012
2013 if (walker(fstore->arg, context))
2014 return true;
2015 if (walker(fstore->newvals, context))
2016 return true;
2017 }
2018 break;
2019 case T_RelabelType:
2020 return walker(((RelabelType *) node)->arg, context);
2021 case T_CoerceViaIO:
2022 return walker(((CoerceViaIO *) node)->arg, context);
2023 case T_ArrayCoerceExpr:
2024 {
2025 ArrayCoerceExpr *acoerce = (ArrayCoerceExpr *) node;
2026
2027 if (walker(acoerce->arg, context))
2028 return true;
2029 if (walker(acoerce->elemexpr, context))
2030 return true;
2031 }
2032 break;
2033 case T_ConvertRowtypeExpr:
2034 return walker(((ConvertRowtypeExpr *) node)->arg, context);
2035 case T_CollateExpr:
2036 return walker(((CollateExpr *) node)->arg, context);
2037 case T_CaseExpr:
2038 {
2039 CaseExpr *caseexpr = (CaseExpr *) node;
2040
2041 if (walker(caseexpr->arg, context))
2042 return true;
2043 /* we assume walker doesn't care about CaseWhens, either */
2044 foreach(temp, caseexpr->args)
2045 {
2046 CaseWhen *when = lfirst_node(CaseWhen, temp);
2047
2048 if (walker(when->expr, context))
2049 return true;
2050 if (walker(when->result, context))
2051 return true;
2052 }
2053 if (walker(caseexpr->defresult, context))
2054 return true;
2055 }
2056 break;
2057 case T_ArrayExpr:
2058 return walker(((ArrayExpr *) node)->elements, context);
2059 case T_RowExpr:
2060 /* Assume colnames isn't interesting */
2061 return walker(((RowExpr *) node)->args, context);
2062 case T_RowCompareExpr:
2063 {
2064 RowCompareExpr *rcexpr = (RowCompareExpr *) node;
2065
2066 if (walker(rcexpr->largs, context))
2067 return true;
2068 if (walker(rcexpr->rargs, context))
2069 return true;
2070 }
2071 break;
2072 case T_CoalesceExpr:
2073 return walker(((CoalesceExpr *) node)->args, context);
2074 case T_MinMaxExpr:
2075 return walker(((MinMaxExpr *) node)->args, context);
2076 case T_XmlExpr:
2077 {
2078 XmlExpr *xexpr = (XmlExpr *) node;
2079
2080 if (walker(xexpr->named_args, context))
2081 return true;
2082 /* we assume walker doesn't care about arg_names */
2083 if (walker(xexpr->args, context))
2084 return true;
2085 }
2086 break;
2087 case T_NullTest:
2088 return walker(((NullTest *) node)->arg, context);
2089 case T_BooleanTest:
2090 return walker(((BooleanTest *) node)->arg, context);
2091 case T_CoerceToDomain:
2092 return walker(((CoerceToDomain *) node)->arg, context);
2093 case T_TargetEntry:
2094 return walker(((TargetEntry *) node)->expr, context);
2095 case T_Query:
2096 /* Do nothing with a sub-Query, per discussion above */
2097 break;
2098 case T_WindowClause:
2099 {
2100 WindowClause *wc = (WindowClause *) node;
2101
2102 if (walker(wc->partitionClause, context))
2103 return true;
2104 if (walker(wc->orderClause, context))
2105 return true;
2106 if (walker(wc->startOffset, context))
2107 return true;
2108 if (walker(wc->endOffset, context))
2109 return true;
2110 }
2111 break;
2112 case T_CommonTableExpr:
2113 {
2114 CommonTableExpr *cte = (CommonTableExpr *) node;
2115
2116 /*
2117 * Invoke the walker on the CTE's Query node, so it can
2118 * recurse into the sub-query if it wants to.
2119 */
2120 return walker(cte->ctequery, context);
2121 }
2122 break;
2123 case T_List:
2124 foreach(temp, (List *) node)
2125 {
2126 if (walker((Node *) lfirst(temp), context))
2127 return true;
2128 }
2129 break;
2130 case T_FromExpr:
2131 {
2132 FromExpr *from = (FromExpr *) node;
2133
2134 if (walker(from->fromlist, context))
2135 return true;
2136 if (walker(from->quals, context))
2137 return true;
2138 }
2139 break;
2140 case T_OnConflictExpr:
2141 {
2142 OnConflictExpr *onconflict = (OnConflictExpr *) node;
2143
2144 if (walker((Node *) onconflict->arbiterElems, context))
2145 return true;
2146 if (walker(onconflict->arbiterWhere, context))
2147 return true;
2148 if (walker(onconflict->onConflictSet, context))
2149 return true;
2150 if (walker(onconflict->onConflictWhere, context))
2151 return true;
2152 if (walker(onconflict->exclRelTlist, context))
2153 return true;
2154 }
2155 break;
2156 case T_PartitionPruneStepOp:
2157 {
2158 PartitionPruneStepOp *opstep = (PartitionPruneStepOp *) node;
2159
2160 if (walker((Node *) opstep->exprs, context))
2161 return true;
2162 }
2163 break;
2164 case T_PartitionPruneStepCombine:
2165 /* no expression subnodes */
2166 break;
2167 case T_JoinExpr:
2168 {
2169 JoinExpr *join = (JoinExpr *) node;
2170
2171 if (walker(join->larg, context))
2172 return true;
2173 if (walker(join->rarg, context))
2174 return true;
2175 if (walker(join->quals, context))
2176 return true;
2177
2178 /*
2179 * alias clause, using list are deemed uninteresting.
2180 */
2181 }
2182 break;
2183 case T_SetOperationStmt:
2184 {
2185 SetOperationStmt *setop = (SetOperationStmt *) node;
2186
2187 if (walker(setop->larg, context))
2188 return true;
2189 if (walker(setop->rarg, context))
2190 return true;
2191
2192 /* groupClauses are deemed uninteresting */
2193 }
2194 break;
2195 case T_IndexClause:
2196 {
2197 IndexClause *iclause = (IndexClause *) node;
2198
2199 if (walker(iclause->rinfo, context))
2200 return true;
2201 if (expression_tree_walker((Node *) iclause->indexquals,
2202 walker, context))
2203 return true;
2204 }
2205 break;
2206 case T_PlaceHolderVar:
2207 return walker(((PlaceHolderVar *) node)->phexpr, context);
2208 case T_InferenceElem:
2209 return walker(((InferenceElem *) node)->expr, context);
2210 case T_AppendRelInfo:
2211 {
2212 AppendRelInfo *appinfo = (AppendRelInfo *) node;
2213
2214 if (expression_tree_walker((Node *) appinfo->translated_vars,
2215 walker, context))
2216 return true;
2217 }
2218 break;
2219 case T_PlaceHolderInfo:
2220 return walker(((PlaceHolderInfo *) node)->ph_var, context);
2221 case T_RangeTblFunction:
2222 return walker(((RangeTblFunction *) node)->funcexpr, context);
2223 case T_TableSampleClause:
2224 {
2225 TableSampleClause *tsc = (TableSampleClause *) node;
2226
2227 if (expression_tree_walker((Node *) tsc->args,
2228 walker, context))
2229 return true;
2230 if (walker((Node *) tsc->repeatable, context))
2231 return true;
2232 }
2233 break;
2234 case T_TableFunc:
2235 {
2236 TableFunc *tf = (TableFunc *) node;
2237
2238 if (walker(tf->ns_uris, context))
2239 return true;
2240 if (walker(tf->docexpr, context))
2241 return true;
2242 if (walker(tf->rowexpr, context))
2243 return true;
2244 if (walker(tf->colexprs, context))
2245 return true;
2246 if (walker(tf->coldefexprs, context))
2247 return true;
2248 }
2249 break;
2250 default:
2251 elog(ERROR, "unrecognized node type: %d",
2252 (int) nodeTag(node));
2253 break;
2254 }
2255 return false;
2256}
2257
2258/*
2259 * query_tree_walker --- initiate a walk of a Query's expressions
2260 *
2261 * This routine exists just to reduce the number of places that need to know
2262 * where all the expression subtrees of a Query are. Note it can be used
2263 * for starting a walk at top level of a Query regardless of whether the
2264 * walker intends to descend into subqueries. It is also useful for
2265 * descending into subqueries within a walker.
2266 *
2267 * Some callers want to suppress visitation of certain items in the sub-Query,
2268 * typically because they need to process them specially, or don't actually
2269 * want to recurse into subqueries. This is supported by the flags argument,
2270 * which is the bitwise OR of flag values to add or suppress visitation of
2271 * indicated items. (More flag bits may be added as needed.)
2272 */
2273bool
2274query_tree_walker(Query *query,
2275 bool (*walker) (),
2276 void *context,
2277 int flags)
2278{
2279 Assert(query != NULL && IsA(query, Query));
2280
2281 if (walker((Node *) query->targetList, context))
2282 return true;
2283 if (walker((Node *) query->withCheckOptions, context))
2284 return true;
2285 if (walker((Node *) query->onConflict, context))
2286 return true;
2287 if (walker((Node *) query->returningList, context))
2288 return true;
2289 if (walker((Node *) query->jointree, context))
2290 return true;
2291 if (walker(query->setOperations, context))
2292 return true;
2293 if (walker(query->havingQual, context))
2294 return true;
2295 if (walker(query->limitOffset, context))
2296 return true;
2297 if (walker(query->limitCount, context))
2298 return true;
2299 if (!(flags & QTW_IGNORE_CTE_SUBQUERIES))
2300 {
2301 if (walker((Node *) query->cteList, context))
2302 return true;
2303 }
2304 if (!(flags & QTW_IGNORE_RANGE_TABLE))
2305 {
2306 if (range_table_walker(query->rtable, walker, context, flags))
2307 return true;
2308 }
2309 return false;
2310}
2311
2312/*
2313 * range_table_walker is just the part of query_tree_walker that scans
2314 * a query's rangetable. This is split out since it can be useful on
2315 * its own.
2316 */
2317bool
2318range_table_walker(List *rtable,
2319 bool (*walker) (),
2320 void *context,
2321 int flags)
2322{
2323 ListCell *rt;
2324
2325 foreach(rt, rtable)
2326 {
2327 RangeTblEntry *rte = (RangeTblEntry *) lfirst(rt);
2328
2329 /*
2330 * Walkers might need to examine the RTE node itself either before or
2331 * after visiting its contents (or, conceivably, both). Note that if
2332 * you specify neither flag, the walker won't visit the RTE at all.
2333 */
2334 if (flags & QTW_EXAMINE_RTES_BEFORE)
2335 if (walker(rte, context))
2336 return true;
2337
2338 switch (rte->rtekind)
2339 {
2340 case RTE_RELATION:
2341 if (walker(rte->tablesample, context))
2342 return true;
2343 break;
2344 case RTE_SUBQUERY:
2345 if (!(flags & QTW_IGNORE_RT_SUBQUERIES))
2346 if (walker(rte->subquery, context))
2347 return true;
2348 break;
2349 case RTE_JOIN:
2350 if (!(flags & QTW_IGNORE_JOINALIASES))
2351 if (walker(rte->joinaliasvars, context))
2352 return true;
2353 break;
2354 case RTE_FUNCTION:
2355 if (walker(rte->functions, context))
2356 return true;
2357 break;
2358 case RTE_TABLEFUNC:
2359 if (walker(rte->tablefunc, context))
2360 return true;
2361 break;
2362 case RTE_VALUES:
2363 if (walker(rte->values_lists, context))
2364 return true;
2365 break;
2366 case RTE_CTE:
2367 case RTE_NAMEDTUPLESTORE:
2368 case RTE_RESULT:
2369 /* nothing to do */
2370 break;
2371 }
2372
2373 if (walker(rte->securityQuals, context))
2374 return true;
2375
2376 if (flags & QTW_EXAMINE_RTES_AFTER)
2377 if (walker(rte, context))
2378 return true;
2379 }
2380 return false;
2381}
2382
2383
2384/*
2385 * expression_tree_mutator() is designed to support routines that make a
2386 * modified copy of an expression tree, with some nodes being added,
2387 * removed, or replaced by new subtrees. The original tree is (normally)
2388 * not changed. Each recursion level is responsible for returning a copy of
2389 * (or appropriately modified substitute for) the subtree it is handed.
2390 * A mutator routine should look like this:
2391 *
2392 * Node * my_mutator (Node *node, my_struct *context)
2393 * {
2394 * if (node == NULL)
2395 * return NULL;
2396 * // check for nodes that special work is required for, eg:
2397 * if (IsA(node, Var))
2398 * {
2399 * ... create and return modified copy of Var node
2400 * }
2401 * else if (IsA(node, ...))
2402 * {
2403 * ... do special transformations of other node types
2404 * }
2405 * // for any node type not specially processed, do:
2406 * return expression_tree_mutator(node, my_mutator, (void *) context);
2407 * }
2408 *
2409 * The "context" argument points to a struct that holds whatever context
2410 * information the mutator routine needs --- it can be used to return extra
2411 * data gathered by the mutator, too. This argument is not touched by
2412 * expression_tree_mutator, but it is passed down to recursive sub-invocations
2413 * of my_mutator. The tree walk is started from a setup routine that
2414 * fills in the appropriate context struct, calls my_mutator with the
2415 * top-level node of the tree, and does any required post-processing.
2416 *
2417 * Each level of recursion must return an appropriately modified Node.
2418 * If expression_tree_mutator() is called, it will make an exact copy
2419 * of the given Node, but invoke my_mutator() to copy the sub-node(s)
2420 * of that Node. In this way, my_mutator() has full control over the
2421 * copying process but need not directly deal with expression trees
2422 * that it has no interest in.
2423 *
2424 * Just as for expression_tree_walker, the node types handled by
2425 * expression_tree_mutator include all those normally found in target lists
2426 * and qualifier clauses during the planning stage.
2427 *
2428 * expression_tree_mutator will handle SubLink nodes by recursing normally
2429 * into the "testexpr" subtree (which is an expression belonging to the outer
2430 * plan). It will also call the mutator on the sub-Query node; however, when
2431 * expression_tree_mutator itself is called on a Query node, it does nothing
2432 * and returns the unmodified Query node. The net effect is that unless the
2433 * mutator does something special at a Query node, sub-selects will not be
2434 * visited or modified; the original sub-select will be linked to by the new
2435 * SubLink node. Mutators that want to descend into sub-selects will usually
2436 * do so by recognizing Query nodes and calling query_tree_mutator (below).
2437 *
2438 * expression_tree_mutator will handle a SubPlan node by recursing into the
2439 * "testexpr" and the "args" list (which belong to the outer plan), but it
2440 * will simply copy the link to the inner plan, since that's typically what
2441 * expression tree mutators want. A mutator that wants to modify the subplan
2442 * can force appropriate behavior by recognizing SubPlan expression nodes
2443 * and doing the right thing.
2444 */
2445
2446Node *
2447expression_tree_mutator(Node *node,
2448 Node *(*mutator) (),
2449 void *context)
2450{
2451 /*
2452 * The mutator has already decided not to modify the current node, but we
2453 * must call the mutator for any sub-nodes.
2454 */
2455
2456#define FLATCOPY(newnode, node, nodetype) \
2457 ( (newnode) = (nodetype *) palloc(sizeof(nodetype)), \
2458 memcpy((newnode), (node), sizeof(nodetype)) )
2459
2460#define CHECKFLATCOPY(newnode, node, nodetype) \
2461 ( AssertMacro(IsA((node), nodetype)), \
2462 (newnode) = (nodetype *) palloc(sizeof(nodetype)), \
2463 memcpy((newnode), (node), sizeof(nodetype)) )
2464
2465#define MUTATE(newfield, oldfield, fieldtype) \
2466 ( (newfield) = (fieldtype) mutator((Node *) (oldfield), context) )
2467
2468 if (node == NULL)
2469 return NULL;
2470
2471 /* Guard against stack overflow due to overly complex expressions */
2472 check_stack_depth();
2473
2474 switch (nodeTag(node))
2475 {
2476 /*
2477 * Primitive node types with no expression subnodes. Var and
2478 * Const are frequent enough to deserve special cases, the others
2479 * we just use copyObject for.
2480 */
2481 case T_Var:
2482 {
2483 Var *var = (Var *) node;
2484 Var *newnode;
2485
2486 FLATCOPY(newnode, var, Var);
2487 return (Node *) newnode;
2488 }
2489 break;
2490 case T_Const:
2491 {
2492 Const *oldnode = (Const *) node;
2493 Const *newnode;
2494
2495 FLATCOPY(newnode, oldnode, Const);
2496 /* XXX we don't bother with datumCopy; should we? */
2497 return (Node *) newnode;
2498 }
2499 break;
2500 case T_Param:
2501 case T_CaseTestExpr:
2502 case T_SQLValueFunction:
2503 case T_CoerceToDomainValue:
2504 case T_SetToDefault:
2505 case T_CurrentOfExpr:
2506 case T_NextValueExpr:
2507 case T_RangeTblRef:
2508 case T_SortGroupClause:
2509 return (Node *) copyObject(node);
2510 case T_WithCheckOption:
2511 {
2512 WithCheckOption *wco = (WithCheckOption *) node;
2513 WithCheckOption *newnode;
2514
2515 FLATCOPY(newnode, wco, WithCheckOption);
2516 MUTATE(newnode->qual, wco->qual, Node *);
2517 return (Node *) newnode;
2518 }
2519 case T_Aggref:
2520 {
2521 Aggref *aggref = (Aggref *) node;
2522 Aggref *newnode;
2523
2524 FLATCOPY(newnode, aggref, Aggref);
2525 /* assume mutation doesn't change types of arguments */
2526 newnode->aggargtypes = list_copy(aggref->aggargtypes);
2527 MUTATE(newnode->aggdirectargs, aggref->aggdirectargs, List *);
2528 MUTATE(newnode->args, aggref->args, List *);
2529 MUTATE(newnode->aggorder, aggref->aggorder, List *);
2530 MUTATE(newnode->aggdistinct, aggref->aggdistinct, List *);
2531 MUTATE(newnode->aggfilter, aggref->aggfilter, Expr *);
2532 return (Node *) newnode;
2533 }
2534 break;
2535 case T_GroupingFunc:
2536 {
2537 GroupingFunc *grouping = (GroupingFunc *) node;
2538 GroupingFunc *newnode;
2539
2540 FLATCOPY(newnode, grouping, GroupingFunc);
2541 MUTATE(newnode->args, grouping->args, List *);
2542
2543 /*
2544 * We assume here that mutating the arguments does not change
2545 * the semantics, i.e. that the arguments are not mutated in a
2546 * way that makes them semantically different from their
2547 * previously matching expressions in the GROUP BY clause.
2548 *
2549 * If a mutator somehow wanted to do this, it would have to
2550 * handle the refs and cols lists itself as appropriate.
2551 */
2552 newnode->refs = list_copy(grouping->refs);
2553 newnode->cols = list_copy(grouping->cols);
2554
2555 return (Node *) newnode;
2556 }
2557 break;
2558 case T_WindowFunc:
2559 {
2560 WindowFunc *wfunc = (WindowFunc *) node;
2561 WindowFunc *newnode;
2562
2563 FLATCOPY(newnode, wfunc, WindowFunc);
2564 MUTATE(newnode->args, wfunc->args, List *);
2565 MUTATE(newnode->aggfilter, wfunc->aggfilter, Expr *);
2566 return (Node *) newnode;
2567 }
2568 break;
2569 case T_SubscriptingRef:
2570 {
2571 SubscriptingRef *sbsref = (SubscriptingRef *) node;
2572 SubscriptingRef *newnode;
2573
2574 FLATCOPY(newnode, sbsref, SubscriptingRef);
2575 MUTATE(newnode->refupperindexpr, sbsref->refupperindexpr,
2576 List *);
2577 MUTATE(newnode->reflowerindexpr, sbsref->reflowerindexpr,
2578 List *);
2579 MUTATE(newnode->refexpr, sbsref->refexpr,
2580 Expr *);
2581 MUTATE(newnode->refassgnexpr, sbsref->refassgnexpr,
2582 Expr *);
2583
2584 return (Node *) newnode;
2585 }
2586 break;
2587 case T_FuncExpr:
2588 {
2589 FuncExpr *expr = (FuncExpr *) node;
2590 FuncExpr *newnode;
2591
2592 FLATCOPY(newnode, expr, FuncExpr);
2593 MUTATE(newnode->args, expr->args, List *);
2594 return (Node *) newnode;
2595 }
2596 break;
2597 case T_NamedArgExpr:
2598 {
2599 NamedArgExpr *nexpr = (NamedArgExpr *) node;
2600 NamedArgExpr *newnode;
2601
2602 FLATCOPY(newnode, nexpr, NamedArgExpr);
2603 MUTATE(newnode->arg, nexpr->arg, Expr *);
2604 return (Node *) newnode;
2605 }
2606 break;
2607 case T_OpExpr:
2608 {
2609 OpExpr *expr = (OpExpr *) node;
2610 OpExpr *newnode;
2611
2612 FLATCOPY(newnode, expr, OpExpr);
2613 MUTATE(newnode->args, expr->args, List *);
2614 return (Node *) newnode;
2615 }
2616 break;
2617 case T_DistinctExpr:
2618 {
2619 DistinctExpr *expr = (DistinctExpr *) node;
2620 DistinctExpr *newnode;
2621
2622 FLATCOPY(newnode, expr, DistinctExpr);
2623 MUTATE(newnode->args, expr->args, List *);
2624 return (Node *) newnode;
2625 }
2626 break;
2627 case T_NullIfExpr:
2628 {
2629 NullIfExpr *expr = (NullIfExpr *) node;
2630 NullIfExpr *newnode;
2631
2632 FLATCOPY(newnode, expr, NullIfExpr);
2633 MUTATE(newnode->args, expr->args, List *);
2634 return (Node *) newnode;
2635 }
2636 break;
2637 case T_ScalarArrayOpExpr:
2638 {
2639 ScalarArrayOpExpr *expr = (ScalarArrayOpExpr *) node;
2640 ScalarArrayOpExpr *newnode;
2641
2642 FLATCOPY(newnode, expr, ScalarArrayOpExpr);
2643 MUTATE(newnode->args, expr->args, List *);
2644 return (Node *) newnode;
2645 }
2646 break;
2647 case T_BoolExpr:
2648 {
2649 BoolExpr *expr = (BoolExpr *) node;
2650 BoolExpr *newnode;
2651
2652 FLATCOPY(newnode, expr, BoolExpr);
2653 MUTATE(newnode->args, expr->args, List *);
2654 return (Node *) newnode;
2655 }
2656 break;
2657 case T_SubLink:
2658 {
2659 SubLink *sublink = (SubLink *) node;
2660 SubLink *newnode;
2661
2662 FLATCOPY(newnode, sublink, SubLink);
2663 MUTATE(newnode->testexpr, sublink->testexpr, Node *);
2664
2665 /*
2666 * Also invoke the mutator on the sublink's Query node, so it
2667 * can recurse into the sub-query if it wants to.
2668 */
2669 MUTATE(newnode->subselect, sublink->subselect, Node *);
2670 return (Node *) newnode;
2671 }
2672 break;
2673 case T_SubPlan:
2674 {
2675 SubPlan *subplan = (SubPlan *) node;
2676 SubPlan *newnode;
2677
2678 FLATCOPY(newnode, subplan, SubPlan);
2679 /* transform testexpr */
2680 MUTATE(newnode->testexpr, subplan->testexpr, Node *);
2681 /* transform args list (params to be passed to subplan) */
2682 MUTATE(newnode->args, subplan->args, List *);
2683 /* but not the sub-Plan itself, which is referenced as-is */
2684 return (Node *) newnode;
2685 }
2686 break;
2687 case T_AlternativeSubPlan:
2688 {
2689 AlternativeSubPlan *asplan = (AlternativeSubPlan *) node;
2690 AlternativeSubPlan *newnode;
2691
2692 FLATCOPY(newnode, asplan, AlternativeSubPlan);
2693 MUTATE(newnode->subplans, asplan->subplans, List *);
2694 return (Node *) newnode;
2695 }
2696 break;
2697 case T_FieldSelect:
2698 {
2699 FieldSelect *fselect = (FieldSelect *) node;
2700 FieldSelect *newnode;
2701
2702 FLATCOPY(newnode, fselect, FieldSelect);
2703 MUTATE(newnode->arg, fselect->arg, Expr *);
2704 return (Node *) newnode;
2705 }
2706 break;
2707 case T_FieldStore:
2708 {
2709 FieldStore *fstore = (FieldStore *) node;
2710 FieldStore *newnode;
2711
2712 FLATCOPY(newnode, fstore, FieldStore);
2713 MUTATE(newnode->arg, fstore->arg, Expr *);
2714 MUTATE(newnode->newvals, fstore->newvals, List *);
2715 newnode->fieldnums = list_copy(fstore->fieldnums);
2716 return (Node *) newnode;
2717 }
2718 break;
2719 case T_RelabelType:
2720 {
2721 RelabelType *relabel = (RelabelType *) node;
2722 RelabelType *newnode;
2723
2724 FLATCOPY(newnode, relabel, RelabelType);
2725 MUTATE(newnode->arg, relabel->arg, Expr *);
2726 return (Node *) newnode;
2727 }
2728 break;
2729 case T_CoerceViaIO:
2730 {
2731 CoerceViaIO *iocoerce = (CoerceViaIO *) node;
2732 CoerceViaIO *newnode;
2733
2734 FLATCOPY(newnode, iocoerce, CoerceViaIO);
2735 MUTATE(newnode->arg, iocoerce->arg, Expr *);
2736 return (Node *) newnode;
2737 }
2738 break;
2739 case T_ArrayCoerceExpr:
2740 {
2741 ArrayCoerceExpr *acoerce = (ArrayCoerceExpr *) node;
2742 ArrayCoerceExpr *newnode;
2743
2744 FLATCOPY(newnode, acoerce, ArrayCoerceExpr);
2745 MUTATE(newnode->arg, acoerce->arg, Expr *);
2746 MUTATE(newnode->elemexpr, acoerce->elemexpr, Expr *);
2747 return (Node *) newnode;
2748 }
2749 break;
2750 case T_ConvertRowtypeExpr:
2751 {
2752 ConvertRowtypeExpr *convexpr = (ConvertRowtypeExpr *) node;
2753 ConvertRowtypeExpr *newnode;
2754
2755 FLATCOPY(newnode, convexpr, ConvertRowtypeExpr);
2756 MUTATE(newnode->arg, convexpr->arg, Expr *);
2757 return (Node *) newnode;
2758 }
2759 break;
2760 case T_CollateExpr:
2761 {
2762 CollateExpr *collate = (CollateExpr *) node;
2763 CollateExpr *newnode;
2764
2765 FLATCOPY(newnode, collate, CollateExpr);
2766 MUTATE(newnode->arg, collate->arg, Expr *);
2767 return (Node *) newnode;
2768 }
2769 break;
2770 case T_CaseExpr:
2771 {
2772 CaseExpr *caseexpr = (CaseExpr *) node;
2773 CaseExpr *newnode;
2774
2775 FLATCOPY(newnode, caseexpr, CaseExpr);
2776 MUTATE(newnode->arg, caseexpr->arg, Expr *);
2777 MUTATE(newnode->args, caseexpr->args, List *);
2778 MUTATE(newnode->defresult, caseexpr->defresult, Expr *);
2779 return (Node *) newnode;
2780 }
2781 break;
2782 case T_CaseWhen:
2783 {
2784 CaseWhen *casewhen = (CaseWhen *) node;
2785 CaseWhen *newnode;
2786
2787 FLATCOPY(newnode, casewhen, CaseWhen);
2788 MUTATE(newnode->expr, casewhen->expr, Expr *);
2789 MUTATE(newnode->result, casewhen->result, Expr *);
2790 return (Node *) newnode;
2791 }
2792 break;
2793 case T_ArrayExpr:
2794 {
2795 ArrayExpr *arrayexpr = (ArrayExpr *) node;
2796 ArrayExpr *newnode;
2797
2798 FLATCOPY(newnode, arrayexpr, ArrayExpr);
2799 MUTATE(newnode->elements, arrayexpr->elements, List *);
2800 return (Node *) newnode;
2801 }
2802 break;
2803 case T_RowExpr:
2804 {
2805 RowExpr *rowexpr = (RowExpr *) node;
2806 RowExpr *newnode;
2807
2808 FLATCOPY(newnode, rowexpr, RowExpr);
2809 MUTATE(newnode->args, rowexpr->args, List *);
2810 /* Assume colnames needn't be duplicated */
2811 return (Node *) newnode;
2812 }
2813 break;
2814 case T_RowCompareExpr:
2815 {
2816 RowCompareExpr *rcexpr = (RowCompareExpr *) node;
2817 RowCompareExpr *newnode;
2818
2819 FLATCOPY(newnode, rcexpr, RowCompareExpr);
2820 MUTATE(newnode->largs, rcexpr->largs, List *);
2821 MUTATE(newnode->rargs, rcexpr->rargs, List *);
2822 return (Node *) newnode;
2823 }
2824 break;
2825 case T_CoalesceExpr:
2826 {
2827 CoalesceExpr *coalesceexpr = (CoalesceExpr *) node;
2828 CoalesceExpr *newnode;
2829
2830 FLATCOPY(newnode, coalesceexpr, CoalesceExpr);
2831 MUTATE(newnode->args, coalesceexpr->args, List *);
2832 return (Node *) newnode;
2833 }
2834 break;
2835 case T_MinMaxExpr:
2836 {
2837 MinMaxExpr *minmaxexpr = (MinMaxExpr *) node;
2838 MinMaxExpr *newnode;
2839
2840 FLATCOPY(newnode, minmaxexpr, MinMaxExpr);
2841 MUTATE(newnode->args, minmaxexpr->args, List *);
2842 return (Node *) newnode;
2843 }
2844 break;
2845 case T_XmlExpr:
2846 {
2847 XmlExpr *xexpr = (XmlExpr *) node;
2848 XmlExpr *newnode;
2849
2850 FLATCOPY(newnode, xexpr, XmlExpr);
2851 MUTATE(newnode->named_args, xexpr->named_args, List *);
2852 /* assume mutator does not care about arg_names */
2853 MUTATE(newnode->args, xexpr->args, List *);
2854 return (Node *) newnode;
2855 }
2856 break;
2857 case T_NullTest:
2858 {
2859 NullTest *ntest = (NullTest *) node;
2860 NullTest *newnode;
2861
2862 FLATCOPY(newnode, ntest, NullTest);
2863 MUTATE(newnode->arg, ntest->arg, Expr *);
2864 return (Node *) newnode;
2865 }
2866 break;
2867 case T_BooleanTest:
2868 {
2869 BooleanTest *btest = (BooleanTest *) node;
2870 BooleanTest *newnode;
2871
2872 FLATCOPY(newnode, btest, BooleanTest);
2873 MUTATE(newnode->arg, btest->arg, Expr *);
2874 return (Node *) newnode;
2875 }
2876 break;
2877 case T_CoerceToDomain:
2878 {
2879 CoerceToDomain *ctest = (CoerceToDomain *) node;
2880 CoerceToDomain *newnode;
2881
2882 FLATCOPY(newnode, ctest, CoerceToDomain);
2883 MUTATE(newnode->arg, ctest->arg, Expr *);
2884 return (Node *) newnode;
2885 }
2886 break;
2887 case T_TargetEntry:
2888 {
2889 TargetEntry *targetentry = (TargetEntry *) node;
2890 TargetEntry *newnode;
2891
2892 FLATCOPY(newnode, targetentry, TargetEntry);
2893 MUTATE(newnode->expr, targetentry->expr, Expr *);
2894 return (Node *) newnode;
2895 }
2896 break;
2897 case T_Query:
2898 /* Do nothing with a sub-Query, per discussion above */
2899 return node;
2900 case T_WindowClause:
2901 {
2902 WindowClause *wc = (WindowClause *) node;
2903 WindowClause *newnode;
2904
2905 FLATCOPY(newnode, wc, WindowClause);
2906 MUTATE(newnode->partitionClause, wc->partitionClause, List *);
2907 MUTATE(newnode->orderClause, wc->orderClause, List *);
2908 MUTATE(newnode->startOffset, wc->startOffset, Node *);
2909 MUTATE(newnode->endOffset, wc->endOffset, Node *);
2910 return (Node *) newnode;
2911 }
2912 break;
2913 case T_CommonTableExpr:
2914 {
2915 CommonTableExpr *cte = (CommonTableExpr *) node;
2916 CommonTableExpr *newnode;
2917
2918 FLATCOPY(newnode, cte, CommonTableExpr);
2919
2920 /*
2921 * Also invoke the mutator on the CTE's Query node, so it can
2922 * recurse into the sub-query if it wants to.
2923 */
2924 MUTATE(newnode->ctequery, cte->ctequery, Node *);
2925 return (Node *) newnode;
2926 }
2927 break;
2928 case T_List:
2929 {
2930 /*
2931 * We assume the mutator isn't interested in the list nodes
2932 * per se, so just invoke it on each list element. NOTE: this
2933 * would fail badly on a list with integer elements!
2934 */
2935 List *resultlist;
2936 ListCell *temp;
2937
2938 resultlist = NIL;
2939 foreach(temp, (List *) node)
2940 {
2941 resultlist = lappend(resultlist,
2942 mutator((Node *) lfirst(temp),
2943 context));
2944 }
2945 return (Node *) resultlist;
2946 }
2947 break;
2948 case T_FromExpr:
2949 {
2950 FromExpr *from = (FromExpr *) node;
2951 FromExpr *newnode;
2952
2953 FLATCOPY(newnode, from, FromExpr);
2954 MUTATE(newnode->fromlist, from->fromlist, List *);
2955 MUTATE(newnode->quals, from->quals, Node *);
2956 return (Node *) newnode;
2957 }
2958 break;
2959 case T_OnConflictExpr:
2960 {
2961 OnConflictExpr *oc = (OnConflictExpr *) node;
2962 OnConflictExpr *newnode;
2963
2964 FLATCOPY(newnode, oc, OnConflictExpr);
2965 MUTATE(newnode->arbiterElems, oc->arbiterElems, List *);
2966 MUTATE(newnode->arbiterWhere, oc->arbiterWhere, Node *);
2967 MUTATE(newnode->onConflictSet, oc->onConflictSet, List *);
2968 MUTATE(newnode->onConflictWhere, oc->onConflictWhere, Node *);
2969 MUTATE(newnode->exclRelTlist, oc->exclRelTlist, List *);
2970
2971 return (Node *) newnode;
2972 }
2973 break;
2974 case T_PartitionPruneStepOp:
2975 {
2976 PartitionPruneStepOp *opstep = (PartitionPruneStepOp *) node;
2977 PartitionPruneStepOp *newnode;
2978
2979 FLATCOPY(newnode, opstep, PartitionPruneStepOp);
2980 MUTATE(newnode->exprs, opstep->exprs, List *);
2981
2982 return (Node *) newnode;
2983 }
2984 break;
2985 case T_PartitionPruneStepCombine:
2986 /* no expression sub-nodes */
2987 return (Node *) copyObject(node);
2988 case T_JoinExpr:
2989 {
2990 JoinExpr *join = (JoinExpr *) node;
2991 JoinExpr *newnode;
2992
2993 FLATCOPY(newnode, join, JoinExpr);
2994 MUTATE(newnode->larg, join->larg, Node *);
2995 MUTATE(newnode->rarg, join->rarg, Node *);
2996 MUTATE(newnode->quals, join->quals, Node *);
2997 /* We do not mutate alias or using by default */
2998 return (Node *) newnode;
2999 }
3000 break;
3001 case T_SetOperationStmt:
3002 {
3003 SetOperationStmt *setop = (SetOperationStmt *) node;
3004 SetOperationStmt *newnode;
3005
3006 FLATCOPY(newnode, setop, SetOperationStmt);
3007 MUTATE(newnode->larg, setop->larg, Node *);
3008 MUTATE(newnode->rarg, setop->rarg, Node *);
3009 /* We do not mutate groupClauses by default */
3010 return (Node *) newnode;
3011 }
3012 break;
3013 case T_IndexClause:
3014 {
3015 IndexClause *iclause = (IndexClause *) node;
3016 IndexClause *newnode;
3017
3018 FLATCOPY(newnode, iclause, IndexClause);
3019 MUTATE(newnode->rinfo, iclause->rinfo, RestrictInfo *);
3020 MUTATE(newnode->indexquals, iclause->indexquals, List *);
3021 return (Node *) newnode;
3022 }
3023 break;
3024 case T_PlaceHolderVar:
3025 {
3026 PlaceHolderVar *phv = (PlaceHolderVar *) node;
3027 PlaceHolderVar *newnode;
3028
3029 FLATCOPY(newnode, phv, PlaceHolderVar);
3030 MUTATE(newnode->phexpr, phv->phexpr, Expr *);
3031 /* Assume we need not copy the relids bitmapset */
3032 return (Node *) newnode;
3033 }
3034 break;
3035 case T_InferenceElem:
3036 {
3037 InferenceElem *inferenceelemdexpr = (InferenceElem *) node;
3038 InferenceElem *newnode;
3039
3040 FLATCOPY(newnode, inferenceelemdexpr, InferenceElem);
3041 MUTATE(newnode->expr, newnode->expr, Node *);
3042 return (Node *) newnode;
3043 }
3044 break;
3045 case T_AppendRelInfo:
3046 {
3047 AppendRelInfo *appinfo = (AppendRelInfo *) node;
3048 AppendRelInfo *newnode;
3049
3050 FLATCOPY(newnode, appinfo, AppendRelInfo);
3051 MUTATE(newnode->translated_vars, appinfo->translated_vars, List *);
3052 return (Node *) newnode;
3053 }
3054 break;
3055 case T_PlaceHolderInfo:
3056 {
3057 PlaceHolderInfo *phinfo = (PlaceHolderInfo *) node;
3058 PlaceHolderInfo *newnode;
3059
3060 FLATCOPY(newnode, phinfo, PlaceHolderInfo);
3061 MUTATE(newnode->ph_var, phinfo->ph_var, PlaceHolderVar *);
3062 /* Assume we need not copy the relids bitmapsets */
3063 return (Node *) newnode;
3064 }
3065 break;
3066 case T_RangeTblFunction:
3067 {
3068 RangeTblFunction *rtfunc = (RangeTblFunction *) node;
3069 RangeTblFunction *newnode;
3070
3071 FLATCOPY(newnode, rtfunc, RangeTblFunction);
3072 MUTATE(newnode->funcexpr, rtfunc->funcexpr, Node *);
3073 /* Assume we need not copy the coldef info lists */
3074 return (Node *) newnode;
3075 }
3076 break;
3077 case T_TableSampleClause:
3078 {
3079 TableSampleClause *tsc = (TableSampleClause *) node;
3080 TableSampleClause *newnode;
3081
3082 FLATCOPY(newnode, tsc, TableSampleClause);
3083 MUTATE(newnode->args, tsc->args, List *);
3084 MUTATE(newnode->repeatable, tsc->repeatable, Expr *);
3085 return (Node *) newnode;
3086 }
3087 break;
3088 case T_TableFunc:
3089 {
3090 TableFunc *tf = (TableFunc *) node;
3091 TableFunc *newnode;
3092
3093 FLATCOPY(newnode, tf, TableFunc);
3094 MUTATE(newnode->ns_uris, tf->ns_uris, List *);
3095 MUTATE(newnode->docexpr, tf->docexpr, Node *);
3096 MUTATE(newnode->rowexpr, tf->rowexpr, Node *);
3097 MUTATE(newnode->colexprs, tf->colexprs, List *);
3098 MUTATE(newnode->coldefexprs, tf->coldefexprs, List *);
3099 return (Node *) newnode;
3100 }
3101 break;
3102 default:
3103 elog(ERROR, "unrecognized node type: %d",
3104 (int) nodeTag(node));
3105 break;
3106 }
3107 /* can't get here, but keep compiler happy */
3108 return NULL;
3109}
3110
3111
3112/*
3113 * query_tree_mutator --- initiate modification of a Query's expressions
3114 *
3115 * This routine exists just to reduce the number of places that need to know
3116 * where all the expression subtrees of a Query are. Note it can be used
3117 * for starting a walk at top level of a Query regardless of whether the
3118 * mutator intends to descend into subqueries. It is also useful for
3119 * descending into subqueries within a mutator.
3120 *
3121 * Some callers want to suppress mutating of certain items in the Query,
3122 * typically because they need to process them specially, or don't actually
3123 * want to recurse into subqueries. This is supported by the flags argument,
3124 * which is the bitwise OR of flag values to suppress mutating of
3125 * indicated items. (More flag bits may be added as needed.)
3126 *
3127 * Normally the Query node itself is copied, but some callers want it to be
3128 * modified in-place; they must pass QTW_DONT_COPY_QUERY in flags. All
3129 * modified substructure is safely copied in any case.
3130 */
3131Query *
3132query_tree_mutator(Query *query,
3133 Node *(*mutator) (),
3134 void *context,
3135 int flags)
3136{
3137 Assert(query != NULL && IsA(query, Query));
3138
3139 if (!(flags & QTW_DONT_COPY_QUERY))
3140 {
3141 Query *newquery;
3142
3143 FLATCOPY(newquery, query, Query);
3144 query = newquery;
3145 }
3146
3147 MUTATE(query->targetList, query->targetList, List *);
3148 MUTATE(query->withCheckOptions, query->withCheckOptions, List *);
3149 MUTATE(query->onConflict, query->onConflict, OnConflictExpr *);
3150 MUTATE(query->returningList, query->returningList, List *);
3151 MUTATE(query->jointree, query->jointree, FromExpr *);
3152 MUTATE(query->setOperations, query->setOperations, Node *);
3153 MUTATE(query->havingQual, query->havingQual, Node *);
3154 MUTATE(query->limitOffset, query->limitOffset, Node *);
3155 MUTATE(query->limitCount, query->limitCount, Node *);
3156 if (!(flags & QTW_IGNORE_CTE_SUBQUERIES))
3157 MUTATE(query->cteList, query->cteList, List *);
3158 else /* else copy CTE list as-is */
3159 query->cteList = copyObject(query->cteList);
3160 query->rtable = range_table_mutator(query->rtable,
3161 mutator, context, flags);
3162 return query;
3163}
3164
3165/*
3166 * range_table_mutator is just the part of query_tree_mutator that processes
3167 * a query's rangetable. This is split out since it can be useful on
3168 * its own.
3169 */
3170List *
3171range_table_mutator(List *rtable,
3172 Node *(*mutator) (),
3173 void *context,
3174 int flags)
3175{
3176 List *newrt = NIL;
3177 ListCell *rt;
3178
3179 foreach(rt, rtable)
3180 {
3181 RangeTblEntry *rte = (RangeTblEntry *) lfirst(rt);
3182 RangeTblEntry *newrte;
3183
3184 FLATCOPY(newrte, rte, RangeTblEntry);
3185 switch (rte->rtekind)
3186 {
3187 case RTE_RELATION:
3188 MUTATE(newrte->tablesample, rte->tablesample,
3189 TableSampleClause *);
3190 /* we don't bother to copy eref, aliases, etc; OK? */
3191 break;
3192 case RTE_SUBQUERY:
3193 if (!(flags & QTW_IGNORE_RT_SUBQUERIES))
3194 {
3195 CHECKFLATCOPY(newrte->subquery, rte->subquery, Query);
3196 MUTATE(newrte->subquery, newrte->subquery, Query *);
3197 }
3198 else
3199 {
3200 /* else, copy RT subqueries as-is */
3201 newrte->subquery = copyObject(rte->subquery);
3202 }
3203 break;
3204 case RTE_JOIN:
3205 if (!(flags & QTW_IGNORE_JOINALIASES))
3206 MUTATE(newrte->joinaliasvars, rte->joinaliasvars, List *);
3207 else
3208 {
3209 /* else, copy join aliases as-is */
3210 newrte->joinaliasvars = copyObject(rte->joinaliasvars);
3211 }
3212 break;
3213 case RTE_FUNCTION:
3214 MUTATE(newrte->functions, rte->functions, List *);
3215 break;
3216 case RTE_TABLEFUNC:
3217 MUTATE(newrte->tablefunc, rte->tablefunc, TableFunc *);
3218 break;
3219 case RTE_VALUES:
3220 MUTATE(newrte->values_lists, rte->values_lists, List *);
3221 break;
3222 case RTE_CTE:
3223 case RTE_NAMEDTUPLESTORE:
3224 case RTE_RESULT:
3225 /* nothing to do */
3226 break;
3227 }
3228 MUTATE(newrte->securityQuals, rte->securityQuals, List *);
3229 newrt = lappend(newrt, newrte);
3230 }
3231 return newrt;
3232}
3233
3234/*
3235 * query_or_expression_tree_walker --- hybrid form
3236 *
3237 * This routine will invoke query_tree_walker if called on a Query node,
3238 * else will invoke the walker directly. This is a useful way of starting
3239 * the recursion when the walker's normal change of state is not appropriate
3240 * for the outermost Query node.
3241 */
3242bool
3243query_or_expression_tree_walker(Node *node,
3244 bool (*walker) (),
3245 void *context,
3246 int flags)
3247{
3248 if (node && IsA(node, Query))
3249 return query_tree_walker((Query *) node,
3250 walker,
3251 context,
3252 flags);
3253 else
3254 return walker(node, context);
3255}
3256
3257/*
3258 * query_or_expression_tree_mutator --- hybrid form
3259 *
3260 * This routine will invoke query_tree_mutator if called on a Query node,
3261 * else will invoke the mutator directly. This is a useful way of starting
3262 * the recursion when the mutator's normal change of state is not appropriate
3263 * for the outermost Query node.
3264 */
3265Node *
3266query_or_expression_tree_mutator(Node *node,
3267 Node *(*mutator) (),
3268 void *context,
3269 int flags)
3270{
3271 if (node && IsA(node, Query))
3272 return (Node *) query_tree_mutator((Query *) node,
3273 mutator,
3274 context,
3275 flags);
3276 else
3277 return mutator(node, context);
3278}
3279
3280
3281/*
3282 * raw_expression_tree_walker --- walk raw parse trees
3283 *
3284 * This has exactly the same API as expression_tree_walker, but instead of
3285 * walking post-analysis parse trees, it knows how to walk the node types
3286 * found in raw grammar output. (There is not currently any need for a
3287 * combined walker, so we keep them separate in the name of efficiency.)
3288 * Unlike expression_tree_walker, there is no special rule about query
3289 * boundaries: we descend to everything that's possibly interesting.
3290 *
3291 * Currently, the node type coverage here extends only to DML statements
3292 * (SELECT/INSERT/UPDATE/DELETE) and nodes that can appear in them, because
3293 * this is used mainly during analysis of CTEs, and only DML statements can
3294 * appear in CTEs.
3295 */
3296bool
3297raw_expression_tree_walker(Node *node,
3298 bool (*walker) (),
3299 void *context)
3300{
3301 ListCell *temp;
3302
3303 /*
3304 * The walker has already visited the current node, and so we need only
3305 * recurse into any sub-nodes it has.
3306 */
3307 if (node == NULL)
3308 return false;
3309
3310 /* Guard against stack overflow due to overly complex expressions */
3311 check_stack_depth();
3312
3313 switch (nodeTag(node))
3314 {
3315 case T_SetToDefault:
3316 case T_CurrentOfExpr:
3317 case T_SQLValueFunction:
3318 case T_Integer:
3319 case T_Float:
3320 case T_String:
3321 case T_BitString:
3322 case T_Null:
3323 case T_ParamRef:
3324 case T_A_Const:
3325 case T_A_Star:
3326 /* primitive node types with no subnodes */
3327 break;
3328 case T_Alias:
3329 /* we assume the colnames list isn't interesting */
3330 break;
3331 case T_RangeVar:
3332 return walker(((RangeVar *) node)->alias, context);
3333 case T_GroupingFunc:
3334 return walker(((GroupingFunc *) node)->args, context);
3335 case T_SubLink:
3336 {
3337 SubLink *sublink = (SubLink *) node;
3338
3339 if (walker(sublink->testexpr, context))
3340 return true;
3341 /* we assume the operName is not interesting */
3342 if (walker(sublink->subselect, context))
3343 return true;
3344 }
3345 break;
3346 case T_CaseExpr:
3347 {
3348 CaseExpr *caseexpr = (CaseExpr *) node;
3349
3350 if (walker(caseexpr->arg, context))
3351 return true;
3352 /* we assume walker doesn't care about CaseWhens, either */
3353 foreach(temp, caseexpr->args)
3354 {
3355 CaseWhen *when = lfirst_node(CaseWhen, temp);
3356
3357 if (walker(when->expr, context))
3358 return true;
3359 if (walker(when->result, context))
3360 return true;
3361 }
3362 if (walker(caseexpr->defresult, context))
3363 return true;
3364 }
3365 break;
3366 case T_RowExpr:
3367 /* Assume colnames isn't interesting */
3368 return walker(((RowExpr *) node)->args, context);
3369 case T_CoalesceExpr:
3370 return walker(((CoalesceExpr *) node)->args, context);
3371 case T_MinMaxExpr:
3372 return walker(((MinMaxExpr *) node)->args, context);
3373 case T_XmlExpr:
3374 {
3375 XmlExpr *xexpr = (XmlExpr *) node;
3376
3377 if (walker(xexpr->named_args, context))
3378 return true;
3379 /* we assume walker doesn't care about arg_names */
3380 if (walker(xexpr->args, context))
3381 return true;
3382 }
3383 break;
3384 case T_NullTest:
3385 return walker(((NullTest *) node)->arg, context);
3386 case T_BooleanTest:
3387 return walker(((BooleanTest *) node)->arg, context);
3388 case T_JoinExpr:
3389 {
3390 JoinExpr *join = (JoinExpr *) node;
3391
3392 if (walker(join->larg, context))
3393 return true;
3394 if (walker(join->rarg, context))
3395 return true;
3396 if (walker(join->quals, context))
3397 return true;
3398 if (walker(join->alias, context))
3399 return true;
3400 /* using list is deemed uninteresting */
3401 }
3402 break;
3403 case T_IntoClause:
3404 {
3405 IntoClause *into = (IntoClause *) node;
3406
3407 if (walker(into->rel, context))
3408 return true;
3409 /* colNames, options are deemed uninteresting */
3410 /* viewQuery should be null in raw parsetree, but check it */
3411 if (walker(into->viewQuery, context))
3412 return true;
3413 }
3414 break;
3415 case T_List:
3416 foreach(temp, (List *) node)
3417 {
3418 if (walker((Node *) lfirst(temp), context))
3419 return true;
3420 }
3421 break;
3422 case T_InsertStmt:
3423 {
3424 InsertStmt *stmt = (InsertStmt *) node;
3425
3426 if (walker(stmt->relation, context))
3427 return true;
3428 if (walker(stmt->cols, context))
3429 return true;
3430 if (walker(stmt->selectStmt, context))
3431 return true;
3432 if (walker(stmt->onConflictClause, context))
3433 return true;
3434 if (walker(stmt->returningList, context))
3435 return true;
3436 if (walker(stmt->withClause, context))
3437 return true;
3438 }
3439 break;
3440 case T_DeleteStmt:
3441 {
3442 DeleteStmt *stmt = (DeleteStmt *) node;
3443
3444 if (walker(stmt->relation, context))
3445 return true;
3446 if (walker(stmt->usingClause, context))
3447 return true;
3448 if (walker(stmt->whereClause, context))
3449 return true;
3450 if (walker(stmt->returningList, context))
3451 return true;
3452 if (walker(stmt->withClause, context))
3453 return true;
3454 }
3455 break;
3456 case T_UpdateStmt:
3457 {
3458 UpdateStmt *stmt = (UpdateStmt *) node;
3459
3460 if (walker(stmt->relation, context))
3461 return true;
3462 if (walker(stmt->targetList, context))
3463 return true;
3464 if (walker(stmt->whereClause, context))
3465 return true;
3466 if (walker(stmt->fromClause, context))
3467 return true;
3468 if (walker(stmt->returningList, context))
3469 return true;
3470 if (walker(stmt->withClause, context))
3471 return true;
3472 }
3473 break;
3474 case T_SelectStmt:
3475 {
3476 SelectStmt *stmt = (SelectStmt *) node;
3477
3478 if (walker(stmt->distinctClause, context))
3479 return true;
3480 if (walker(stmt->intoClause, context))
3481 return true;
3482 if (walker(stmt->targetList, context))
3483 return true;
3484 if (walker(stmt->fromClause, context))
3485 return true;
3486 if (walker(stmt->whereClause, context))
3487 return true;
3488 if (walker(stmt->groupClause, context))
3489 return true;
3490 if (walker(stmt->havingClause, context))
3491 return true;
3492 if (walker(stmt->windowClause, context))
3493 return true;
3494 if (walker(stmt->valuesLists, context))
3495 return true;
3496 if (walker(stmt->sortClause, context))
3497 return true;
3498 if (walker(stmt->limitOffset, context))
3499 return true;
3500 if (walker(stmt->limitCount, context))
3501 return true;
3502 if (walker(stmt->lockingClause, context))
3503 return true;
3504 if (walker(stmt->withClause, context))
3505 return true;
3506 if (walker(stmt->larg, context))
3507 return true;
3508 if (walker(stmt->rarg, context))
3509 return true;
3510 }
3511 break;
3512 case T_A_Expr:
3513 {
3514 A_Expr *expr = (A_Expr *) node;
3515
3516 if (walker(expr->lexpr, context))
3517 return true;
3518 if (walker(expr->rexpr, context))
3519 return true;
3520 /* operator name is deemed uninteresting */
3521 }
3522 break;
3523 case T_BoolExpr:
3524 {
3525 BoolExpr *expr = (BoolExpr *) node;
3526
3527 if (walker(expr->args, context))
3528 return true;
3529 }
3530 break;
3531 case T_ColumnRef:
3532 /* we assume the fields contain nothing interesting */
3533 break;
3534 case T_FuncCall:
3535 {
3536 FuncCall *fcall = (FuncCall *) node;
3537
3538 if (walker(fcall->args, context))
3539 return true;
3540 if (walker(fcall->agg_order, context))
3541 return true;
3542 if (walker(fcall->agg_filter, context))
3543 return true;
3544 if (walker(fcall->over, context))
3545 return true;
3546 /* function name is deemed uninteresting */
3547 }
3548 break;
3549 case T_NamedArgExpr:
3550 return walker(((NamedArgExpr *) node)->arg, context);
3551 case T_A_Indices:
3552 {
3553 A_Indices *indices = (A_Indices *) node;
3554
3555 if (walker(indices->lidx, context))
3556 return true;
3557 if (walker(indices->uidx, context))
3558 return true;
3559 }
3560 break;
3561 case T_A_Indirection:
3562 {
3563 A_Indirection *indir = (A_Indirection *) node;
3564
3565 if (walker(indir->arg, context))
3566 return true;
3567 if (walker(indir->indirection, context))
3568 return true;
3569 }
3570 break;
3571 case T_A_ArrayExpr:
3572 return walker(((A_ArrayExpr *) node)->elements, context);
3573 case T_ResTarget:
3574 {
3575 ResTarget *rt = (ResTarget *) node;
3576
3577 if (walker(rt->indirection, context))
3578 return true;
3579 if (walker(rt->val, context))
3580 return true;
3581 }
3582 break;
3583 case T_MultiAssignRef:
3584 return walker(((MultiAssignRef *) node)->source, context);
3585 case T_TypeCast:
3586 {
3587 TypeCast *tc = (TypeCast *) node;
3588
3589 if (walker(tc->arg, context))
3590 return true;
3591 if (walker(tc->typeName, context))
3592 return true;
3593 }
3594 break;
3595 case T_CollateClause:
3596 return walker(((CollateClause *) node)->arg, context);
3597 case T_SortBy:
3598 return walker(((SortBy *) node)->node, context);
3599 case T_WindowDef:
3600 {
3601 WindowDef *wd = (WindowDef *) node;
3602
3603 if (walker(wd->partitionClause, context))
3604 return true;
3605 if (walker(wd->orderClause, context))
3606 return true;
3607 if (walker(wd->startOffset, context))
3608 return true;
3609 if (walker(wd->endOffset, context))
3610 return true;
3611 }
3612 break;
3613 case T_RangeSubselect:
3614 {
3615 RangeSubselect *rs = (RangeSubselect *) node;
3616
3617 if (walker(rs->subquery, context))
3618 return true;
3619 if (walker(rs->alias, context))
3620 return true;
3621 }
3622 break;
3623 case T_RangeFunction:
3624 {
3625 RangeFunction *rf = (RangeFunction *) node;
3626
3627 if (walker(rf->functions, context))
3628 return true;
3629 if (walker(rf->alias, context))
3630 return true;
3631 if (walker(rf->coldeflist, context))
3632 return true;
3633 }
3634 break;
3635 case T_RangeTableSample:
3636 {
3637 RangeTableSample *rts = (RangeTableSample *) node;
3638
3639 if (walker(rts->relation, context))
3640 return true;
3641 /* method name is deemed uninteresting */
3642 if (walker(rts->args, context))
3643 return true;
3644 if (walker(rts->repeatable, context))
3645 return true;
3646 }
3647 break;
3648 case T_RangeTableFunc:
3649 {
3650 RangeTableFunc *rtf = (RangeTableFunc *) node;
3651
3652 if (walker(rtf->docexpr, context))
3653 return true;
3654 if (walker(rtf->rowexpr, context))
3655 return true;
3656 if (walker(rtf->namespaces, context))
3657 return true;
3658 if (walker(rtf->columns, context))
3659 return true;
3660 if (walker(rtf->alias, context))
3661 return true;
3662 }
3663 break;
3664 case T_RangeTableFuncCol:
3665 {
3666 RangeTableFuncCol *rtfc = (RangeTableFuncCol *) node;
3667
3668 if (walker(rtfc->colexpr, context))
3669 return true;
3670 if (walker(rtfc->coldefexpr, context))
3671 return true;
3672 }
3673 break;
3674 case T_TypeName:
3675 {
3676 TypeName *tn = (TypeName *) node;
3677
3678 if (walker(tn->typmods, context))
3679 return true;
3680 if (walker(tn->arrayBounds, context))
3681 return true;
3682 /* type name itself is deemed uninteresting */
3683 }
3684 break;
3685 case T_ColumnDef:
3686 {
3687 ColumnDef *coldef = (ColumnDef *) node;
3688
3689 if (walker(coldef->typeName, context))
3690 return true;
3691 if (walker(coldef->raw_default, context))
3692 return true;
3693 if (walker(coldef->collClause, context))
3694 return true;
3695 /* for now, constraints are ignored */
3696 }
3697 break;
3698 case T_IndexElem:
3699 {
3700 IndexElem *indelem = (IndexElem *) node;
3701
3702 if (walker(indelem->expr, context))
3703 return true;
3704 /* collation and opclass names are deemed uninteresting */
3705 }
3706 break;
3707 case T_GroupingSet:
3708 return walker(((GroupingSet *) node)->content, context);
3709 case T_LockingClause:
3710 return walker(((LockingClause *) node)->lockedRels, context);
3711 case T_XmlSerialize:
3712 {
3713 XmlSerialize *xs = (XmlSerialize *) node;
3714
3715 if (walker(xs->expr, context))
3716 return true;
3717 if (walker(xs->typeName, context))
3718 return true;
3719 }
3720 break;
3721 case T_WithClause:
3722 return walker(((WithClause *) node)->ctes, context);
3723 case T_InferClause:
3724 {
3725 InferClause *stmt = (InferClause *) node;
3726
3727 if (walker(stmt->indexElems, context))
3728 return true;
3729 if (walker(stmt->whereClause, context))
3730 return true;
3731 }
3732 break;
3733 case T_OnConflictClause:
3734 {
3735 OnConflictClause *stmt = (OnConflictClause *) node;
3736
3737 if (walker(stmt->infer, context))
3738 return true;
3739 if (walker(stmt->targetList, context))
3740 return true;
3741 if (walker(stmt->whereClause, context))
3742 return true;
3743 }
3744 break;
3745 case T_CommonTableExpr:
3746 return walker(((CommonTableExpr *) node)->ctequery, context);
3747 default:
3748 elog(ERROR, "unrecognized node type: %d",
3749 (int) nodeTag(node));
3750 break;
3751 }
3752 return false;
3753}
3754
3755/*
3756 * planstate_tree_walker --- walk plan state trees
3757 *
3758 * The walker has already visited the current node, and so we need only
3759 * recurse into any sub-nodes it has.
3760 */
3761bool
3762planstate_tree_walker(PlanState *planstate,
3763 bool (*walker) (),
3764 void *context)
3765{
3766 Plan *plan = planstate->plan;
3767 ListCell *lc;
3768
3769 /* Guard against stack overflow due to overly complex plan trees */
3770 check_stack_depth();
3771
3772 /* initPlan-s */
3773 if (planstate_walk_subplans(planstate->initPlan, walker, context))
3774 return true;
3775
3776 /* lefttree */
3777 if (outerPlanState(planstate))
3778 {
3779 if (walker(outerPlanState(planstate), context))
3780 return true;
3781 }
3782
3783 /* righttree */
3784 if (innerPlanState(planstate))
3785 {
3786 if (walker(innerPlanState(planstate), context))
3787 return true;
3788 }
3789
3790 /* special child plans */
3791 switch (nodeTag(plan))
3792 {
3793 case T_ModifyTable:
3794 if (planstate_walk_members(((ModifyTableState *) planstate)->mt_plans,
3795 ((ModifyTableState *) planstate)->mt_nplans,
3796 walker, context))
3797 return true;
3798 break;
3799 case T_Append:
3800 if (planstate_walk_members(((AppendState *) planstate)->appendplans,
3801 ((AppendState *) planstate)->as_nplans,
3802 walker, context))
3803 return true;
3804 break;
3805 case T_MergeAppend:
3806 if (planstate_walk_members(((MergeAppendState *) planstate)->mergeplans,
3807 ((MergeAppendState *) planstate)->ms_nplans,
3808 walker, context))
3809 return true;
3810 break;
3811 case T_BitmapAnd:
3812 if (planstate_walk_members(((BitmapAndState *) planstate)->bitmapplans,
3813 ((BitmapAndState *) planstate)->nplans,
3814 walker, context))
3815 return true;
3816 break;
3817 case T_BitmapOr:
3818 if (planstate_walk_members(((BitmapOrState *) planstate)->bitmapplans,
3819 ((BitmapOrState *) planstate)->nplans,
3820 walker, context))
3821 return true;
3822 break;
3823 case T_SubqueryScan:
3824 if (walker(((SubqueryScanState *) planstate)->subplan, context))
3825 return true;
3826 break;
3827 case T_CustomScan:
3828 foreach(lc, ((CustomScanState *) planstate)->custom_ps)
3829 {
3830 if (walker((PlanState *) lfirst(lc), context))
3831 return true;
3832 }
3833 break;
3834 default:
3835 break;
3836 }
3837
3838 /* subPlan-s */
3839 if (planstate_walk_subplans(planstate->subPlan, walker, context))
3840 return true;
3841
3842 return false;
3843}
3844
3845/*
3846 * Walk a list of SubPlans (or initPlans, which also use SubPlan nodes).
3847 */
3848static bool
3849planstate_walk_subplans(List *plans,
3850 bool (*walker) (),
3851 void *context)
3852{
3853 ListCell *lc;
3854
3855 foreach(lc, plans)
3856 {
3857 SubPlanState *sps = lfirst_node(SubPlanState, lc);
3858
3859 if (walker(sps->planstate, context))
3860 return true;
3861 }
3862
3863 return false;
3864}
3865
3866/*
3867 * Walk the constituent plans of a ModifyTable, Append, MergeAppend,
3868 * BitmapAnd, or BitmapOr node.
3869 */
3870static bool
3871planstate_walk_members(PlanState **planstates, int nplans,
3872 bool (*walker) (), void *context)
3873{
3874 int j;
3875
3876 for (j = 0; j < nplans; j++)
3877 {
3878 if (walker(planstates[j], context))
3879 return true;
3880 }
3881
3882 return false;
3883}
3884