1 /*-------------------------------------------------------------------------
2 *
3 * nodeFuncs.c
4 * Various general-purpose manipulations of Node trees
5 *
6 * Portions Copyright (c) 1996-2017, 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/relation.h"
24 #include "utils/builtins.h"
25 #include "utils/lsyscache.h"
26
27
28 static bool expression_returns_set_walker(Node *node, void *context);
29 static int leftmostLoc(int loc1, int loc2);
30 static bool fix_opfuncids_walker(Node *node, void *context);
31 static bool planstate_walk_subplans(List *plans, bool (*walker) (),
32 void *context);
33 static bool planstate_walk_members(List *plans, PlanState **planstates,
34 bool (*walker) (), void *context);
35
36
37 /*
38 * exprType -
39 * returns the Oid of the type of the expression's result.
40 */
41 Oid
exprType(const Node * expr)42 exprType(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_ArrayRef:
70 {
71 const ArrayRef *arrayref = (const ArrayRef *) expr;
72
73 /* slice and/or store operations yield the array type */
74 if (arrayref->reflowerindexpr || arrayref->refassgnexpr)
75 type = arrayref->refarraytype;
76 else
77 type = arrayref->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 */
275 int32
exprTypmod(const Node * expr)276 exprTypmod(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_ArrayRef:
290 /* typmod is the same for array or element */
291 return ((const ArrayRef *) 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 */
512 bool
exprIsLengthCoercion(const Node * expr,int32 * coercedTypmod)513 exprIsLengthCoercion(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 */
587 Node *
relabel_to_typmod(Node * expr,int32 typmod)588 relabel_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 */
611 Node *
strip_implicit_coercions(Node * node)612 strip_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 */
669 bool
expression_returns_set(Node * clause)670 expression_returns_set(Node *clause)
671 {
672 return expression_returns_set_walker(clause, NULL);
673 }
674
675 static bool
expression_returns_set_walker(Node * node,void * context)676 expression_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 */
719 Oid
exprCollation(const Node * expr)720 exprCollation(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_ArrayRef:
748 coll = ((const ArrayRef *) 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 coll = InvalidOid; /* all cases return non-collatable types */
866 break;
867 case T_XmlExpr:
868
869 /*
870 * XMLSERIALIZE returns text from non-collatable inputs, so its
871 * collation is always default. The other cases return boolean or
872 * XML, which are non-collatable.
873 */
874 if (((const XmlExpr *) expr)->op == IS_XMLSERIALIZE)
875 coll = DEFAULT_COLLATION_OID;
876 else
877 coll = InvalidOid;
878 break;
879 case T_NullTest:
880 coll = InvalidOid; /* result is always boolean */
881 break;
882 case T_BooleanTest:
883 coll = InvalidOid; /* result is always boolean */
884 break;
885 case T_CoerceToDomain:
886 coll = ((const CoerceToDomain *) expr)->resultcollid;
887 break;
888 case T_CoerceToDomainValue:
889 coll = ((const CoerceToDomainValue *) expr)->collation;
890 break;
891 case T_SetToDefault:
892 coll = ((const SetToDefault *) expr)->collation;
893 break;
894 case T_CurrentOfExpr:
895 coll = InvalidOid; /* result is always boolean */
896 break;
897 case T_NextValueExpr:
898 coll = InvalidOid; /* result is always an integer type */
899 break;
900 case T_InferenceElem:
901 coll = exprCollation((Node *) ((const InferenceElem *) expr)->expr);
902 break;
903 case T_PlaceHolderVar:
904 coll = exprCollation((Node *) ((const PlaceHolderVar *) expr)->phexpr);
905 break;
906 default:
907 elog(ERROR, "unrecognized node type: %d", (int) nodeTag(expr));
908 coll = InvalidOid; /* keep compiler quiet */
909 break;
910 }
911 return coll;
912 }
913
914 /*
915 * exprInputCollation -
916 * returns the Oid of the collation a function should use, if available.
917 *
918 * Result is InvalidOid if the node type doesn't store this information.
919 */
920 Oid
exprInputCollation(const Node * expr)921 exprInputCollation(const Node *expr)
922 {
923 Oid coll;
924
925 if (!expr)
926 return InvalidOid;
927
928 switch (nodeTag(expr))
929 {
930 case T_Aggref:
931 coll = ((const Aggref *) expr)->inputcollid;
932 break;
933 case T_WindowFunc:
934 coll = ((const WindowFunc *) expr)->inputcollid;
935 break;
936 case T_FuncExpr:
937 coll = ((const FuncExpr *) expr)->inputcollid;
938 break;
939 case T_OpExpr:
940 coll = ((const OpExpr *) expr)->inputcollid;
941 break;
942 case T_DistinctExpr:
943 coll = ((const DistinctExpr *) expr)->inputcollid;
944 break;
945 case T_NullIfExpr:
946 coll = ((const NullIfExpr *) expr)->inputcollid;
947 break;
948 case T_ScalarArrayOpExpr:
949 coll = ((const ScalarArrayOpExpr *) expr)->inputcollid;
950 break;
951 case T_MinMaxExpr:
952 coll = ((const MinMaxExpr *) expr)->inputcollid;
953 break;
954 default:
955 coll = InvalidOid;
956 break;
957 }
958 return coll;
959 }
960
961 /*
962 * exprSetCollation -
963 * Assign collation information to an expression tree node.
964 *
965 * Note: since this is only used during parse analysis, we don't need to
966 * worry about subplans or PlaceHolderVars.
967 */
968 void
exprSetCollation(Node * expr,Oid collation)969 exprSetCollation(Node *expr, Oid collation)
970 {
971 switch (nodeTag(expr))
972 {
973 case T_Var:
974 ((Var *) expr)->varcollid = collation;
975 break;
976 case T_Const:
977 ((Const *) expr)->constcollid = collation;
978 break;
979 case T_Param:
980 ((Param *) expr)->paramcollid = collation;
981 break;
982 case T_Aggref:
983 ((Aggref *) expr)->aggcollid = collation;
984 break;
985 case T_GroupingFunc:
986 Assert(!OidIsValid(collation));
987 break;
988 case T_WindowFunc:
989 ((WindowFunc *) expr)->wincollid = collation;
990 break;
991 case T_ArrayRef:
992 ((ArrayRef *) expr)->refcollid = collation;
993 break;
994 case T_FuncExpr:
995 ((FuncExpr *) expr)->funccollid = collation;
996 break;
997 case T_NamedArgExpr:
998 Assert(collation == exprCollation((Node *) ((NamedArgExpr *) expr)->arg));
999 break;
1000 case T_OpExpr:
1001 ((OpExpr *) expr)->opcollid = collation;
1002 break;
1003 case T_DistinctExpr:
1004 ((DistinctExpr *) expr)->opcollid = collation;
1005 break;
1006 case T_NullIfExpr:
1007 ((NullIfExpr *) expr)->opcollid = collation;
1008 break;
1009 case T_ScalarArrayOpExpr:
1010 Assert(!OidIsValid(collation)); /* result is always boolean */
1011 break;
1012 case T_BoolExpr:
1013 Assert(!OidIsValid(collation)); /* result is always boolean */
1014 break;
1015 case T_SubLink:
1016 #ifdef USE_ASSERT_CHECKING
1017 {
1018 SubLink *sublink = (SubLink *) expr;
1019
1020 if (sublink->subLinkType == EXPR_SUBLINK ||
1021 sublink->subLinkType == ARRAY_SUBLINK)
1022 {
1023 /* get the collation of subselect's first target column */
1024 Query *qtree = (Query *) sublink->subselect;
1025 TargetEntry *tent;
1026
1027 if (!qtree || !IsA(qtree, Query))
1028 elog(ERROR, "cannot set collation for untransformed sublink");
1029 tent = linitial_node(TargetEntry, qtree->targetList);
1030 Assert(!tent->resjunk);
1031 Assert(collation == exprCollation((Node *) tent->expr));
1032 }
1033 else
1034 {
1035 /* otherwise, result is RECORD or BOOLEAN */
1036 Assert(!OidIsValid(collation));
1037 }
1038 }
1039 #endif /* USE_ASSERT_CHECKING */
1040 break;
1041 case T_FieldSelect:
1042 ((FieldSelect *) expr)->resultcollid = collation;
1043 break;
1044 case T_FieldStore:
1045 Assert(!OidIsValid(collation)); /* result is always composite */
1046 break;
1047 case T_RelabelType:
1048 ((RelabelType *) expr)->resultcollid = collation;
1049 break;
1050 case T_CoerceViaIO:
1051 ((CoerceViaIO *) expr)->resultcollid = collation;
1052 break;
1053 case T_ArrayCoerceExpr:
1054 ((ArrayCoerceExpr *) expr)->resultcollid = collation;
1055 break;
1056 case T_ConvertRowtypeExpr:
1057 Assert(!OidIsValid(collation)); /* result is always composite */
1058 break;
1059 case T_CaseExpr:
1060 ((CaseExpr *) expr)->casecollid = collation;
1061 break;
1062 case T_ArrayExpr:
1063 ((ArrayExpr *) expr)->array_collid = collation;
1064 break;
1065 case T_RowExpr:
1066 Assert(!OidIsValid(collation)); /* result is always composite */
1067 break;
1068 case T_RowCompareExpr:
1069 Assert(!OidIsValid(collation)); /* result is always boolean */
1070 break;
1071 case T_CoalesceExpr:
1072 ((CoalesceExpr *) expr)->coalescecollid = collation;
1073 break;
1074 case T_MinMaxExpr:
1075 ((MinMaxExpr *) expr)->minmaxcollid = collation;
1076 break;
1077 case T_SQLValueFunction:
1078 Assert(!OidIsValid(collation)); /* no collatable results */
1079 break;
1080 case T_XmlExpr:
1081 Assert((((XmlExpr *) expr)->op == IS_XMLSERIALIZE) ?
1082 (collation == DEFAULT_COLLATION_OID) :
1083 (collation == InvalidOid));
1084 break;
1085 case T_NullTest:
1086 Assert(!OidIsValid(collation)); /* result is always boolean */
1087 break;
1088 case T_BooleanTest:
1089 Assert(!OidIsValid(collation)); /* result is always boolean */
1090 break;
1091 case T_CoerceToDomain:
1092 ((CoerceToDomain *) expr)->resultcollid = collation;
1093 break;
1094 case T_CoerceToDomainValue:
1095 ((CoerceToDomainValue *) expr)->collation = collation;
1096 break;
1097 case T_SetToDefault:
1098 ((SetToDefault *) expr)->collation = collation;
1099 break;
1100 case T_CurrentOfExpr:
1101 Assert(!OidIsValid(collation)); /* result is always boolean */
1102 break;
1103 case T_NextValueExpr:
1104 Assert(!OidIsValid(collation)); /* result is always an integer
1105 * type */
1106 break;
1107 default:
1108 elog(ERROR, "unrecognized node type: %d", (int) nodeTag(expr));
1109 break;
1110 }
1111 }
1112
1113 /*
1114 * exprSetInputCollation -
1115 * Assign input-collation information to an expression tree node.
1116 *
1117 * This is a no-op for node types that don't store their input collation.
1118 * Note we omit RowCompareExpr, which needs special treatment since it
1119 * contains multiple input collation OIDs.
1120 */
1121 void
exprSetInputCollation(Node * expr,Oid inputcollation)1122 exprSetInputCollation(Node *expr, Oid inputcollation)
1123 {
1124 switch (nodeTag(expr))
1125 {
1126 case T_Aggref:
1127 ((Aggref *) expr)->inputcollid = inputcollation;
1128 break;
1129 case T_WindowFunc:
1130 ((WindowFunc *) expr)->inputcollid = inputcollation;
1131 break;
1132 case T_FuncExpr:
1133 ((FuncExpr *) expr)->inputcollid = inputcollation;
1134 break;
1135 case T_OpExpr:
1136 ((OpExpr *) expr)->inputcollid = inputcollation;
1137 break;
1138 case T_DistinctExpr:
1139 ((DistinctExpr *) expr)->inputcollid = inputcollation;
1140 break;
1141 case T_NullIfExpr:
1142 ((NullIfExpr *) expr)->inputcollid = inputcollation;
1143 break;
1144 case T_ScalarArrayOpExpr:
1145 ((ScalarArrayOpExpr *) expr)->inputcollid = inputcollation;
1146 break;
1147 case T_MinMaxExpr:
1148 ((MinMaxExpr *) expr)->inputcollid = inputcollation;
1149 break;
1150 default:
1151 break;
1152 }
1153 }
1154
1155
1156 /*
1157 * exprLocation -
1158 * returns the parse location of an expression tree, for error reports
1159 *
1160 * -1 is returned if the location can't be determined.
1161 *
1162 * For expressions larger than a single token, the intent here is to
1163 * return the location of the expression's leftmost token, not necessarily
1164 * the topmost Node's location field. For example, an OpExpr's location
1165 * field will point at the operator name, but if it is not a prefix operator
1166 * then we should return the location of the left-hand operand instead.
1167 * The reason is that we want to reference the entire expression not just
1168 * that operator, and pointing to its start seems to be the most natural way.
1169 *
1170 * The location is not perfect --- for example, since the grammar doesn't
1171 * explicitly represent parentheses in the parsetree, given something that
1172 * had been written "(a + b) * c" we are going to point at "a" not "(".
1173 * But it should be plenty good enough for error reporting purposes.
1174 *
1175 * You might think that this code is overly general, for instance why check
1176 * the operands of a FuncExpr node, when the function name can be expected
1177 * to be to the left of them? There are a couple of reasons. The grammar
1178 * sometimes builds expressions that aren't quite what the user wrote;
1179 * for instance x IS NOT BETWEEN ... becomes a NOT-expression whose keyword
1180 * pointer is to the right of its leftmost argument. Also, nodes that were
1181 * inserted implicitly by parse analysis (such as FuncExprs for implicit
1182 * coercions) will have location -1, and so we can have odd combinations of
1183 * known and unknown locations in a tree.
1184 */
1185 int
exprLocation(const Node * expr)1186 exprLocation(const Node *expr)
1187 {
1188 int loc;
1189
1190 if (expr == NULL)
1191 return -1;
1192 switch (nodeTag(expr))
1193 {
1194 case T_RangeVar:
1195 loc = ((const RangeVar *) expr)->location;
1196 break;
1197 case T_TableFunc:
1198 loc = ((const TableFunc *) expr)->location;
1199 break;
1200 case T_Var:
1201 loc = ((const Var *) expr)->location;
1202 break;
1203 case T_Const:
1204 loc = ((const Const *) expr)->location;
1205 break;
1206 case T_Param:
1207 loc = ((const Param *) expr)->location;
1208 break;
1209 case T_Aggref:
1210 /* function name should always be the first thing */
1211 loc = ((const Aggref *) expr)->location;
1212 break;
1213 case T_GroupingFunc:
1214 loc = ((const GroupingFunc *) expr)->location;
1215 break;
1216 case T_WindowFunc:
1217 /* function name should always be the first thing */
1218 loc = ((const WindowFunc *) expr)->location;
1219 break;
1220 case T_ArrayRef:
1221 /* just use array argument's location */
1222 loc = exprLocation((Node *) ((const ArrayRef *) expr)->refexpr);
1223 break;
1224 case T_FuncExpr:
1225 {
1226 const FuncExpr *fexpr = (const FuncExpr *) expr;
1227
1228 /* consider both function name and leftmost arg */
1229 loc = leftmostLoc(fexpr->location,
1230 exprLocation((Node *) fexpr->args));
1231 }
1232 break;
1233 case T_NamedArgExpr:
1234 {
1235 const NamedArgExpr *na = (const NamedArgExpr *) expr;
1236
1237 /* consider both argument name and value */
1238 loc = leftmostLoc(na->location,
1239 exprLocation((Node *) na->arg));
1240 }
1241 break;
1242 case T_OpExpr:
1243 case T_DistinctExpr: /* struct-equivalent to OpExpr */
1244 case T_NullIfExpr: /* struct-equivalent to OpExpr */
1245 {
1246 const OpExpr *opexpr = (const OpExpr *) expr;
1247
1248 /* consider both operator name and leftmost arg */
1249 loc = leftmostLoc(opexpr->location,
1250 exprLocation((Node *) opexpr->args));
1251 }
1252 break;
1253 case T_ScalarArrayOpExpr:
1254 {
1255 const ScalarArrayOpExpr *saopexpr = (const ScalarArrayOpExpr *) expr;
1256
1257 /* consider both operator name and leftmost arg */
1258 loc = leftmostLoc(saopexpr->location,
1259 exprLocation((Node *) saopexpr->args));
1260 }
1261 break;
1262 case T_BoolExpr:
1263 {
1264 const BoolExpr *bexpr = (const BoolExpr *) expr;
1265
1266 /*
1267 * Same as above, to handle either NOT or AND/OR. We can't
1268 * special-case NOT because of the way that it's used for
1269 * things like IS NOT BETWEEN.
1270 */
1271 loc = leftmostLoc(bexpr->location,
1272 exprLocation((Node *) bexpr->args));
1273 }
1274 break;
1275 case T_SubLink:
1276 {
1277 const SubLink *sublink = (const SubLink *) expr;
1278
1279 /* check the testexpr, if any, and the operator/keyword */
1280 loc = leftmostLoc(exprLocation(sublink->testexpr),
1281 sublink->location);
1282 }
1283 break;
1284 case T_FieldSelect:
1285 /* just use argument's location */
1286 loc = exprLocation((Node *) ((const FieldSelect *) expr)->arg);
1287 break;
1288 case T_FieldStore:
1289 /* just use argument's location */
1290 loc = exprLocation((Node *) ((const FieldStore *) expr)->arg);
1291 break;
1292 case T_RelabelType:
1293 {
1294 const RelabelType *rexpr = (const RelabelType *) expr;
1295
1296 /* Much as above */
1297 loc = leftmostLoc(rexpr->location,
1298 exprLocation((Node *) rexpr->arg));
1299 }
1300 break;
1301 case T_CoerceViaIO:
1302 {
1303 const CoerceViaIO *cexpr = (const CoerceViaIO *) expr;
1304
1305 /* Much as above */
1306 loc = leftmostLoc(cexpr->location,
1307 exprLocation((Node *) cexpr->arg));
1308 }
1309 break;
1310 case T_ArrayCoerceExpr:
1311 {
1312 const ArrayCoerceExpr *cexpr = (const ArrayCoerceExpr *) expr;
1313
1314 /* Much as above */
1315 loc = leftmostLoc(cexpr->location,
1316 exprLocation((Node *) cexpr->arg));
1317 }
1318 break;
1319 case T_ConvertRowtypeExpr:
1320 {
1321 const ConvertRowtypeExpr *cexpr = (const ConvertRowtypeExpr *) expr;
1322
1323 /* Much as above */
1324 loc = leftmostLoc(cexpr->location,
1325 exprLocation((Node *) cexpr->arg));
1326 }
1327 break;
1328 case T_CollateExpr:
1329 /* just use argument's location */
1330 loc = exprLocation((Node *) ((const CollateExpr *) expr)->arg);
1331 break;
1332 case T_CaseExpr:
1333 /* CASE keyword should always be the first thing */
1334 loc = ((const CaseExpr *) expr)->location;
1335 break;
1336 case T_CaseWhen:
1337 /* WHEN keyword should always be the first thing */
1338 loc = ((const CaseWhen *) expr)->location;
1339 break;
1340 case T_ArrayExpr:
1341 /* the location points at ARRAY or [, which must be leftmost */
1342 loc = ((const ArrayExpr *) expr)->location;
1343 break;
1344 case T_RowExpr:
1345 /* the location points at ROW or (, which must be leftmost */
1346 loc = ((const RowExpr *) expr)->location;
1347 break;
1348 case T_RowCompareExpr:
1349 /* just use leftmost argument's location */
1350 loc = exprLocation((Node *) ((const RowCompareExpr *) expr)->largs);
1351 break;
1352 case T_CoalesceExpr:
1353 /* COALESCE keyword should always be the first thing */
1354 loc = ((const CoalesceExpr *) expr)->location;
1355 break;
1356 case T_MinMaxExpr:
1357 /* GREATEST/LEAST keyword should always be the first thing */
1358 loc = ((const MinMaxExpr *) expr)->location;
1359 break;
1360 case T_SQLValueFunction:
1361 /* function keyword should always be the first thing */
1362 loc = ((const SQLValueFunction *) expr)->location;
1363 break;
1364 case T_XmlExpr:
1365 {
1366 const XmlExpr *xexpr = (const XmlExpr *) expr;
1367
1368 /* consider both function name and leftmost arg */
1369 loc = leftmostLoc(xexpr->location,
1370 exprLocation((Node *) xexpr->args));
1371 }
1372 break;
1373 case T_NullTest:
1374 {
1375 const NullTest *nexpr = (const NullTest *) expr;
1376
1377 /* Much as above */
1378 loc = leftmostLoc(nexpr->location,
1379 exprLocation((Node *) nexpr->arg));
1380 }
1381 break;
1382 case T_BooleanTest:
1383 {
1384 const BooleanTest *bexpr = (const BooleanTest *) expr;
1385
1386 /* Much as above */
1387 loc = leftmostLoc(bexpr->location,
1388 exprLocation((Node *) bexpr->arg));
1389 }
1390 break;
1391 case T_CoerceToDomain:
1392 {
1393 const CoerceToDomain *cexpr = (const CoerceToDomain *) expr;
1394
1395 /* Much as above */
1396 loc = leftmostLoc(cexpr->location,
1397 exprLocation((Node *) cexpr->arg));
1398 }
1399 break;
1400 case T_CoerceToDomainValue:
1401 loc = ((const CoerceToDomainValue *) expr)->location;
1402 break;
1403 case T_SetToDefault:
1404 loc = ((const SetToDefault *) expr)->location;
1405 break;
1406 case T_TargetEntry:
1407 /* just use argument's location */
1408 loc = exprLocation((Node *) ((const TargetEntry *) expr)->expr);
1409 break;
1410 case T_IntoClause:
1411 /* use the contained RangeVar's location --- close enough */
1412 loc = exprLocation((Node *) ((const IntoClause *) expr)->rel);
1413 break;
1414 case T_List:
1415 {
1416 /* report location of first list member that has a location */
1417 ListCell *lc;
1418
1419 loc = -1; /* just to suppress compiler warning */
1420 foreach(lc, (const List *) expr)
1421 {
1422 loc = exprLocation((Node *) lfirst(lc));
1423 if (loc >= 0)
1424 break;
1425 }
1426 }
1427 break;
1428 case T_A_Expr:
1429 {
1430 const A_Expr *aexpr = (const A_Expr *) expr;
1431
1432 /* use leftmost of operator or left operand (if any) */
1433 /* we assume right operand can't be to left of operator */
1434 loc = leftmostLoc(aexpr->location,
1435 exprLocation(aexpr->lexpr));
1436 }
1437 break;
1438 case T_ColumnRef:
1439 loc = ((const ColumnRef *) expr)->location;
1440 break;
1441 case T_ParamRef:
1442 loc = ((const ParamRef *) expr)->location;
1443 break;
1444 case T_A_Const:
1445 loc = ((const A_Const *) expr)->location;
1446 break;
1447 case T_FuncCall:
1448 {
1449 const FuncCall *fc = (const FuncCall *) expr;
1450
1451 /* consider both function name and leftmost arg */
1452 /* (we assume any ORDER BY nodes must be to right of name) */
1453 loc = leftmostLoc(fc->location,
1454 exprLocation((Node *) fc->args));
1455 }
1456 break;
1457 case T_A_ArrayExpr:
1458 /* the location points at ARRAY or [, which must be leftmost */
1459 loc = ((const A_ArrayExpr *) expr)->location;
1460 break;
1461 case T_ResTarget:
1462 /* we need not examine the contained expression (if any) */
1463 loc = ((const ResTarget *) expr)->location;
1464 break;
1465 case T_MultiAssignRef:
1466 loc = exprLocation(((const MultiAssignRef *) expr)->source);
1467 break;
1468 case T_TypeCast:
1469 {
1470 const TypeCast *tc = (const TypeCast *) expr;
1471
1472 /*
1473 * This could represent CAST(), ::, or TypeName 'literal', so
1474 * any of the components might be leftmost.
1475 */
1476 loc = exprLocation(tc->arg);
1477 loc = leftmostLoc(loc, tc->typeName->location);
1478 loc = leftmostLoc(loc, tc->location);
1479 }
1480 break;
1481 case T_CollateClause:
1482 /* just use argument's location */
1483 loc = exprLocation(((const CollateClause *) expr)->arg);
1484 break;
1485 case T_SortBy:
1486 /* just use argument's location (ignore operator, if any) */
1487 loc = exprLocation(((const SortBy *) expr)->node);
1488 break;
1489 case T_WindowDef:
1490 loc = ((const WindowDef *) expr)->location;
1491 break;
1492 case T_RangeTableSample:
1493 loc = ((const RangeTableSample *) expr)->location;
1494 break;
1495 case T_TypeName:
1496 loc = ((const TypeName *) expr)->location;
1497 break;
1498 case T_ColumnDef:
1499 loc = ((const ColumnDef *) expr)->location;
1500 break;
1501 case T_Constraint:
1502 loc = ((const Constraint *) expr)->location;
1503 break;
1504 case T_FunctionParameter:
1505 /* just use typename's location */
1506 loc = exprLocation((Node *) ((const FunctionParameter *) expr)->argType);
1507 break;
1508 case T_XmlSerialize:
1509 /* XMLSERIALIZE keyword should always be the first thing */
1510 loc = ((const XmlSerialize *) expr)->location;
1511 break;
1512 case T_GroupingSet:
1513 loc = ((const GroupingSet *) expr)->location;
1514 break;
1515 case T_WithClause:
1516 loc = ((const WithClause *) expr)->location;
1517 break;
1518 case T_InferClause:
1519 loc = ((const InferClause *) expr)->location;
1520 break;
1521 case T_OnConflictClause:
1522 loc = ((const OnConflictClause *) expr)->location;
1523 break;
1524 case T_CommonTableExpr:
1525 loc = ((const CommonTableExpr *) expr)->location;
1526 break;
1527 case T_PlaceHolderVar:
1528 /* just use argument's location */
1529 loc = exprLocation((Node *) ((const PlaceHolderVar *) expr)->phexpr);
1530 break;
1531 case T_InferenceElem:
1532 /* just use nested expr's location */
1533 loc = exprLocation((Node *) ((const InferenceElem *) expr)->expr);
1534 break;
1535 case T_PartitionElem:
1536 loc = ((const PartitionElem *) expr)->location;
1537 break;
1538 case T_PartitionSpec:
1539 loc = ((const PartitionSpec *) expr)->location;
1540 break;
1541 case T_PartitionBoundSpec:
1542 loc = ((const PartitionBoundSpec *) expr)->location;
1543 break;
1544 case T_PartitionRangeDatum:
1545 loc = ((const PartitionRangeDatum *) expr)->location;
1546 break;
1547 default:
1548 /* for any other node type it's just unknown... */
1549 loc = -1;
1550 break;
1551 }
1552 return loc;
1553 }
1554
1555 /*
1556 * leftmostLoc - support for exprLocation
1557 *
1558 * Take the minimum of two parse location values, but ignore unknowns
1559 */
1560 static int
leftmostLoc(int loc1,int loc2)1561 leftmostLoc(int loc1, int loc2)
1562 {
1563 if (loc1 < 0)
1564 return loc2;
1565 else if (loc2 < 0)
1566 return loc1;
1567 else
1568 return Min(loc1, loc2);
1569 }
1570
1571
1572 /*
1573 * fix_opfuncids
1574 * Calculate opfuncid field from opno for each OpExpr node in given tree.
1575 * The given tree can be anything expression_tree_walker handles.
1576 *
1577 * The argument is modified in-place. (This is OK since we'd want the
1578 * same change for any node, even if it gets visited more than once due to
1579 * shared structure.)
1580 */
1581 void
fix_opfuncids(Node * node)1582 fix_opfuncids(Node *node)
1583 {
1584 /* This tree walk requires no special setup, so away we go... */
1585 fix_opfuncids_walker(node, NULL);
1586 }
1587
1588 static bool
fix_opfuncids_walker(Node * node,void * context)1589 fix_opfuncids_walker(Node *node, void *context)
1590 {
1591 if (node == NULL)
1592 return false;
1593 if (IsA(node, OpExpr))
1594 set_opfuncid((OpExpr *) node);
1595 else if (IsA(node, DistinctExpr))
1596 set_opfuncid((OpExpr *) node); /* rely on struct equivalence */
1597 else if (IsA(node, NullIfExpr))
1598 set_opfuncid((OpExpr *) node); /* rely on struct equivalence */
1599 else if (IsA(node, ScalarArrayOpExpr))
1600 set_sa_opfuncid((ScalarArrayOpExpr *) node);
1601 return expression_tree_walker(node, fix_opfuncids_walker, context);
1602 }
1603
1604 /*
1605 * set_opfuncid
1606 * Set the opfuncid (procedure OID) in an OpExpr node,
1607 * if it hasn't been set already.
1608 *
1609 * Because of struct equivalence, this can also be used for
1610 * DistinctExpr and NullIfExpr nodes.
1611 */
1612 void
set_opfuncid(OpExpr * opexpr)1613 set_opfuncid(OpExpr *opexpr)
1614 {
1615 if (opexpr->opfuncid == InvalidOid)
1616 opexpr->opfuncid = get_opcode(opexpr->opno);
1617 }
1618
1619 /*
1620 * set_sa_opfuncid
1621 * As above, for ScalarArrayOpExpr nodes.
1622 */
1623 void
set_sa_opfuncid(ScalarArrayOpExpr * opexpr)1624 set_sa_opfuncid(ScalarArrayOpExpr *opexpr)
1625 {
1626 if (opexpr->opfuncid == InvalidOid)
1627 opexpr->opfuncid = get_opcode(opexpr->opno);
1628 }
1629
1630
1631 /*
1632 * check_functions_in_node -
1633 * apply checker() to each function OID contained in given expression node
1634 *
1635 * Returns TRUE if the checker() function does; for nodes representing more
1636 * than one function call, returns TRUE if the checker() function does so
1637 * for any of those functions. Returns FALSE if node does not invoke any
1638 * SQL-visible function. Caller must not pass node == NULL.
1639 *
1640 * This function examines only the given node; it does not recurse into any
1641 * sub-expressions. Callers typically prefer to keep control of the recursion
1642 * for themselves, in case additional checks should be made, or because they
1643 * have special rules about which parts of the tree need to be visited.
1644 *
1645 * Note: we ignore MinMaxExpr, SQLValueFunction, XmlExpr, CoerceToDomain,
1646 * and NextValueExpr nodes, because they do not contain SQL function OIDs.
1647 * However, they can invoke SQL-visible functions, so callers should take
1648 * thought about how to treat them.
1649 */
1650 bool
check_functions_in_node(Node * node,check_function_callback checker,void * context)1651 check_functions_in_node(Node *node, check_function_callback checker,
1652 void *context)
1653 {
1654 switch (nodeTag(node))
1655 {
1656 case T_Aggref:
1657 {
1658 Aggref *expr = (Aggref *) node;
1659
1660 if (checker(expr->aggfnoid, context))
1661 return true;
1662 }
1663 break;
1664 case T_WindowFunc:
1665 {
1666 WindowFunc *expr = (WindowFunc *) node;
1667
1668 if (checker(expr->winfnoid, context))
1669 return true;
1670 }
1671 break;
1672 case T_FuncExpr:
1673 {
1674 FuncExpr *expr = (FuncExpr *) node;
1675
1676 if (checker(expr->funcid, context))
1677 return true;
1678 }
1679 break;
1680 case T_OpExpr:
1681 case T_DistinctExpr: /* struct-equivalent to OpExpr */
1682 case T_NullIfExpr: /* struct-equivalent to OpExpr */
1683 {
1684 OpExpr *expr = (OpExpr *) node;
1685
1686 /* Set opfuncid if it wasn't set already */
1687 set_opfuncid(expr);
1688 if (checker(expr->opfuncid, context))
1689 return true;
1690 }
1691 break;
1692 case T_ScalarArrayOpExpr:
1693 {
1694 ScalarArrayOpExpr *expr = (ScalarArrayOpExpr *) node;
1695
1696 set_sa_opfuncid(expr);
1697 if (checker(expr->opfuncid, context))
1698 return true;
1699 }
1700 break;
1701 case T_CoerceViaIO:
1702 {
1703 CoerceViaIO *expr = (CoerceViaIO *) node;
1704 Oid iofunc;
1705 Oid typioparam;
1706 bool typisvarlena;
1707
1708 /* check the result type's input function */
1709 getTypeInputInfo(expr->resulttype,
1710 &iofunc, &typioparam);
1711 if (checker(iofunc, context))
1712 return true;
1713 /* check the input type's output function */
1714 getTypeOutputInfo(exprType((Node *) expr->arg),
1715 &iofunc, &typisvarlena);
1716 if (checker(iofunc, context))
1717 return true;
1718 }
1719 break;
1720 case T_ArrayCoerceExpr:
1721 {
1722 ArrayCoerceExpr *expr = (ArrayCoerceExpr *) node;
1723
1724 if (OidIsValid(expr->elemfuncid) &&
1725 checker(expr->elemfuncid, context))
1726 return true;
1727 }
1728 break;
1729 case T_RowCompareExpr:
1730 {
1731 RowCompareExpr *rcexpr = (RowCompareExpr *) node;
1732 ListCell *opid;
1733
1734 foreach(opid, rcexpr->opnos)
1735 {
1736 Oid opfuncid = get_opcode(lfirst_oid(opid));
1737
1738 if (checker(opfuncid, context))
1739 return true;
1740 }
1741 }
1742 break;
1743 default:
1744 break;
1745 }
1746 return false;
1747 }
1748
1749
1750 /*
1751 * Standard expression-tree walking support
1752 *
1753 * We used to have near-duplicate code in many different routines that
1754 * understood how to recurse through an expression node tree. That was
1755 * a pain to maintain, and we frequently had bugs due to some particular
1756 * routine neglecting to support a particular node type. In most cases,
1757 * these routines only actually care about certain node types, and don't
1758 * care about other types except insofar as they have to recurse through
1759 * non-primitive node types. Therefore, we now provide generic tree-walking
1760 * logic to consolidate the redundant "boilerplate" code. There are
1761 * two versions: expression_tree_walker() and expression_tree_mutator().
1762 */
1763
1764 /*
1765 * expression_tree_walker() is designed to support routines that traverse
1766 * a tree in a read-only fashion (although it will also work for routines
1767 * that modify nodes in-place but never add/delete/replace nodes).
1768 * A walker routine should look like this:
1769 *
1770 * bool my_walker (Node *node, my_struct *context)
1771 * {
1772 * if (node == NULL)
1773 * return false;
1774 * // check for nodes that special work is required for, eg:
1775 * if (IsA(node, Var))
1776 * {
1777 * ... do special actions for Var nodes
1778 * }
1779 * else if (IsA(node, ...))
1780 * {
1781 * ... do special actions for other node types
1782 * }
1783 * // for any node type not specially processed, do:
1784 * return expression_tree_walker(node, my_walker, (void *) context);
1785 * }
1786 *
1787 * The "context" argument points to a struct that holds whatever context
1788 * information the walker routine needs --- it can be used to return data
1789 * gathered by the walker, too. This argument is not touched by
1790 * expression_tree_walker, but it is passed down to recursive sub-invocations
1791 * of my_walker. The tree walk is started from a setup routine that
1792 * fills in the appropriate context struct, calls my_walker with the top-level
1793 * node of the tree, and then examines the results.
1794 *
1795 * The walker routine should return "false" to continue the tree walk, or
1796 * "true" to abort the walk and immediately return "true" to the top-level
1797 * caller. This can be used to short-circuit the traversal if the walker
1798 * has found what it came for. "false" is returned to the top-level caller
1799 * iff no invocation of the walker returned "true".
1800 *
1801 * The node types handled by expression_tree_walker include all those
1802 * normally found in target lists and qualifier clauses during the planning
1803 * stage. In particular, it handles List nodes since a cnf-ified qual clause
1804 * will have List structure at the top level, and it handles TargetEntry nodes
1805 * so that a scan of a target list can be handled without additional code.
1806 * Also, RangeTblRef, FromExpr, JoinExpr, and SetOperationStmt nodes are
1807 * handled, so that query jointrees and setOperation trees can be processed
1808 * without additional code.
1809 *
1810 * expression_tree_walker will handle SubLink nodes by recursing normally
1811 * into the "testexpr" subtree (which is an expression belonging to the outer
1812 * plan). It will also call the walker on the sub-Query node; however, when
1813 * expression_tree_walker itself is called on a Query node, it does nothing
1814 * and returns "false". The net effect is that unless the walker does
1815 * something special at a Query node, sub-selects will not be visited during
1816 * an expression tree walk. This is exactly the behavior wanted in many cases
1817 * --- and for those walkers that do want to recurse into sub-selects, special
1818 * behavior is typically needed anyway at the entry to a sub-select (such as
1819 * incrementing a depth counter). A walker that wants to examine sub-selects
1820 * should include code along the lines of:
1821 *
1822 * if (IsA(node, Query))
1823 * {
1824 * adjust context for subquery;
1825 * result = query_tree_walker((Query *) node, my_walker, context,
1826 * 0); // adjust flags as needed
1827 * restore context if needed;
1828 * return result;
1829 * }
1830 *
1831 * query_tree_walker is a convenience routine (see below) that calls the
1832 * walker on all the expression subtrees of the given Query node.
1833 *
1834 * expression_tree_walker will handle SubPlan nodes by recursing normally
1835 * into the "testexpr" and the "args" list (which are expressions belonging to
1836 * the outer plan). It will not touch the completed subplan, however. Since
1837 * there is no link to the original Query, it is not possible to recurse into
1838 * subselects of an already-planned expression tree. This is OK for current
1839 * uses, but may need to be revisited in future.
1840 */
1841
1842 bool
expression_tree_walker(Node * node,bool (* walker)(),void * context)1843 expression_tree_walker(Node *node,
1844 bool (*walker) (),
1845 void *context)
1846 {
1847 ListCell *temp;
1848
1849 /*
1850 * The walker has already visited the current node, and so we need only
1851 * recurse into any sub-nodes it has.
1852 *
1853 * We assume that the walker is not interested in List nodes per se, so
1854 * when we expect a List we just recurse directly to self without
1855 * bothering to call the walker.
1856 */
1857 if (node == NULL)
1858 return false;
1859
1860 /* Guard against stack overflow due to overly complex expressions */
1861 check_stack_depth();
1862
1863 switch (nodeTag(node))
1864 {
1865 case T_Var:
1866 case T_Const:
1867 case T_Param:
1868 case T_CaseTestExpr:
1869 case T_SQLValueFunction:
1870 case T_CoerceToDomainValue:
1871 case T_SetToDefault:
1872 case T_CurrentOfExpr:
1873 case T_NextValueExpr:
1874 case T_RangeTblRef:
1875 case T_SortGroupClause:
1876 /* primitive node types with no expression subnodes */
1877 break;
1878 case T_WithCheckOption:
1879 return walker(((WithCheckOption *) node)->qual, context);
1880 case T_Aggref:
1881 {
1882 Aggref *expr = (Aggref *) node;
1883
1884 /* recurse directly on List */
1885 if (expression_tree_walker((Node *) expr->aggdirectargs,
1886 walker, context))
1887 return true;
1888 if (expression_tree_walker((Node *) expr->args,
1889 walker, context))
1890 return true;
1891 if (expression_tree_walker((Node *) expr->aggorder,
1892 walker, context))
1893 return true;
1894 if (expression_tree_walker((Node *) expr->aggdistinct,
1895 walker, context))
1896 return true;
1897 if (walker((Node *) expr->aggfilter, context))
1898 return true;
1899 }
1900 break;
1901 case T_GroupingFunc:
1902 {
1903 GroupingFunc *grouping = (GroupingFunc *) node;
1904
1905 if (expression_tree_walker((Node *) grouping->args,
1906 walker, context))
1907 return true;
1908 }
1909 break;
1910 case T_WindowFunc:
1911 {
1912 WindowFunc *expr = (WindowFunc *) node;
1913
1914 /* recurse directly on List */
1915 if (expression_tree_walker((Node *) expr->args,
1916 walker, context))
1917 return true;
1918 if (walker((Node *) expr->aggfilter, context))
1919 return true;
1920 }
1921 break;
1922 case T_ArrayRef:
1923 {
1924 ArrayRef *aref = (ArrayRef *) node;
1925
1926 /* recurse directly for upper/lower array index lists */
1927 if (expression_tree_walker((Node *) aref->refupperindexpr,
1928 walker, context))
1929 return true;
1930 if (expression_tree_walker((Node *) aref->reflowerindexpr,
1931 walker, context))
1932 return true;
1933 /* walker must see the refexpr and refassgnexpr, however */
1934 if (walker(aref->refexpr, context))
1935 return true;
1936 if (walker(aref->refassgnexpr, context))
1937 return true;
1938 }
1939 break;
1940 case T_FuncExpr:
1941 {
1942 FuncExpr *expr = (FuncExpr *) node;
1943
1944 if (expression_tree_walker((Node *) expr->args,
1945 walker, context))
1946 return true;
1947 }
1948 break;
1949 case T_NamedArgExpr:
1950 return walker(((NamedArgExpr *) node)->arg, context);
1951 case T_OpExpr:
1952 case T_DistinctExpr: /* struct-equivalent to OpExpr */
1953 case T_NullIfExpr: /* struct-equivalent to OpExpr */
1954 {
1955 OpExpr *expr = (OpExpr *) node;
1956
1957 if (expression_tree_walker((Node *) expr->args,
1958 walker, context))
1959 return true;
1960 }
1961 break;
1962 case T_ScalarArrayOpExpr:
1963 {
1964 ScalarArrayOpExpr *expr = (ScalarArrayOpExpr *) node;
1965
1966 if (expression_tree_walker((Node *) expr->args,
1967 walker, context))
1968 return true;
1969 }
1970 break;
1971 case T_BoolExpr:
1972 {
1973 BoolExpr *expr = (BoolExpr *) node;
1974
1975 if (expression_tree_walker((Node *) expr->args,
1976 walker, context))
1977 return true;
1978 }
1979 break;
1980 case T_SubLink:
1981 {
1982 SubLink *sublink = (SubLink *) node;
1983
1984 if (walker(sublink->testexpr, context))
1985 return true;
1986
1987 /*
1988 * Also invoke the walker on the sublink's Query node, so it
1989 * can recurse into the sub-query if it wants to.
1990 */
1991 return walker(sublink->subselect, context);
1992 }
1993 break;
1994 case T_SubPlan:
1995 {
1996 SubPlan *subplan = (SubPlan *) node;
1997
1998 /* recurse into the testexpr, but not into the Plan */
1999 if (walker(subplan->testexpr, context))
2000 return true;
2001 /* also examine args list */
2002 if (expression_tree_walker((Node *) subplan->args,
2003 walker, context))
2004 return true;
2005 }
2006 break;
2007 case T_AlternativeSubPlan:
2008 return walker(((AlternativeSubPlan *) node)->subplans, context);
2009 case T_FieldSelect:
2010 return walker(((FieldSelect *) node)->arg, context);
2011 case T_FieldStore:
2012 {
2013 FieldStore *fstore = (FieldStore *) node;
2014
2015 if (walker(fstore->arg, context))
2016 return true;
2017 if (walker(fstore->newvals, context))
2018 return true;
2019 }
2020 break;
2021 case T_RelabelType:
2022 return walker(((RelabelType *) node)->arg, context);
2023 case T_CoerceViaIO:
2024 return walker(((CoerceViaIO *) node)->arg, context);
2025 case T_ArrayCoerceExpr:
2026 return walker(((ArrayCoerceExpr *) node)->arg, context);
2027 case T_ConvertRowtypeExpr:
2028 return walker(((ConvertRowtypeExpr *) node)->arg, context);
2029 case T_CollateExpr:
2030 return walker(((CollateExpr *) node)->arg, context);
2031 case T_CaseExpr:
2032 {
2033 CaseExpr *caseexpr = (CaseExpr *) node;
2034
2035 if (walker(caseexpr->arg, context))
2036 return true;
2037 /* we assume walker doesn't care about CaseWhens, either */
2038 foreach(temp, caseexpr->args)
2039 {
2040 CaseWhen *when = lfirst_node(CaseWhen, temp);
2041
2042 if (walker(when->expr, context))
2043 return true;
2044 if (walker(when->result, context))
2045 return true;
2046 }
2047 if (walker(caseexpr->defresult, context))
2048 return true;
2049 }
2050 break;
2051 case T_ArrayExpr:
2052 return walker(((ArrayExpr *) node)->elements, context);
2053 case T_RowExpr:
2054 /* Assume colnames isn't interesting */
2055 return walker(((RowExpr *) node)->args, context);
2056 case T_RowCompareExpr:
2057 {
2058 RowCompareExpr *rcexpr = (RowCompareExpr *) node;
2059
2060 if (walker(rcexpr->largs, context))
2061 return true;
2062 if (walker(rcexpr->rargs, context))
2063 return true;
2064 }
2065 break;
2066 case T_CoalesceExpr:
2067 return walker(((CoalesceExpr *) node)->args, context);
2068 case T_MinMaxExpr:
2069 return walker(((MinMaxExpr *) node)->args, context);
2070 case T_XmlExpr:
2071 {
2072 XmlExpr *xexpr = (XmlExpr *) node;
2073
2074 if (walker(xexpr->named_args, context))
2075 return true;
2076 /* we assume walker doesn't care about arg_names */
2077 if (walker(xexpr->args, context))
2078 return true;
2079 }
2080 break;
2081 case T_NullTest:
2082 return walker(((NullTest *) node)->arg, context);
2083 case T_BooleanTest:
2084 return walker(((BooleanTest *) node)->arg, context);
2085 case T_CoerceToDomain:
2086 return walker(((CoerceToDomain *) node)->arg, context);
2087 case T_TargetEntry:
2088 return walker(((TargetEntry *) node)->expr, context);
2089 case T_Query:
2090 /* Do nothing with a sub-Query, per discussion above */
2091 break;
2092 case T_WindowClause:
2093 {
2094 WindowClause *wc = (WindowClause *) node;
2095
2096 if (walker(wc->partitionClause, context))
2097 return true;
2098 if (walker(wc->orderClause, context))
2099 return true;
2100 if (walker(wc->startOffset, context))
2101 return true;
2102 if (walker(wc->endOffset, context))
2103 return true;
2104 }
2105 break;
2106 case T_CommonTableExpr:
2107 {
2108 CommonTableExpr *cte = (CommonTableExpr *) node;
2109
2110 /*
2111 * Invoke the walker on the CTE's Query node, so it can
2112 * recurse into the sub-query if it wants to.
2113 */
2114 return walker(cte->ctequery, context);
2115 }
2116 break;
2117 case T_List:
2118 foreach(temp, (List *) node)
2119 {
2120 if (walker((Node *) lfirst(temp), context))
2121 return true;
2122 }
2123 break;
2124 case T_FromExpr:
2125 {
2126 FromExpr *from = (FromExpr *) node;
2127
2128 if (walker(from->fromlist, context))
2129 return true;
2130 if (walker(from->quals, context))
2131 return true;
2132 }
2133 break;
2134 case T_OnConflictExpr:
2135 {
2136 OnConflictExpr *onconflict = (OnConflictExpr *) node;
2137
2138 if (walker((Node *) onconflict->arbiterElems, context))
2139 return true;
2140 if (walker(onconflict->arbiterWhere, context))
2141 return true;
2142 if (walker(onconflict->onConflictSet, context))
2143 return true;
2144 if (walker(onconflict->onConflictWhere, context))
2145 return true;
2146 if (walker(onconflict->exclRelTlist, context))
2147 return true;
2148 }
2149 break;
2150 case T_JoinExpr:
2151 {
2152 JoinExpr *join = (JoinExpr *) node;
2153
2154 if (walker(join->larg, context))
2155 return true;
2156 if (walker(join->rarg, context))
2157 return true;
2158 if (walker(join->quals, context))
2159 return true;
2160
2161 /*
2162 * alias clause, using list are deemed uninteresting.
2163 */
2164 }
2165 break;
2166 case T_SetOperationStmt:
2167 {
2168 SetOperationStmt *setop = (SetOperationStmt *) node;
2169
2170 if (walker(setop->larg, context))
2171 return true;
2172 if (walker(setop->rarg, context))
2173 return true;
2174
2175 /* groupClauses are deemed uninteresting */
2176 }
2177 break;
2178 case T_PlaceHolderVar:
2179 return walker(((PlaceHolderVar *) node)->phexpr, context);
2180 case T_InferenceElem:
2181 return walker(((InferenceElem *) node)->expr, context);
2182 case T_AppendRelInfo:
2183 {
2184 AppendRelInfo *appinfo = (AppendRelInfo *) node;
2185
2186 if (expression_tree_walker((Node *) appinfo->translated_vars,
2187 walker, context))
2188 return true;
2189 }
2190 break;
2191 case T_PlaceHolderInfo:
2192 return walker(((PlaceHolderInfo *) node)->ph_var, context);
2193 case T_RangeTblFunction:
2194 return walker(((RangeTblFunction *) node)->funcexpr, context);
2195 case T_TableSampleClause:
2196 {
2197 TableSampleClause *tsc = (TableSampleClause *) node;
2198
2199 if (expression_tree_walker((Node *) tsc->args,
2200 walker, context))
2201 return true;
2202 if (walker((Node *) tsc->repeatable, context))
2203 return true;
2204 }
2205 break;
2206 case T_TableFunc:
2207 {
2208 TableFunc *tf = (TableFunc *) node;
2209
2210 if (walker(tf->ns_uris, context))
2211 return true;
2212 if (walker(tf->docexpr, context))
2213 return true;
2214 if (walker(tf->rowexpr, context))
2215 return true;
2216 if (walker(tf->colexprs, context))
2217 return true;
2218 if (walker(tf->coldefexprs, context))
2219 return true;
2220 }
2221 break;
2222 default:
2223 elog(ERROR, "unrecognized node type: %d",
2224 (int) nodeTag(node));
2225 break;
2226 }
2227 return false;
2228 }
2229
2230 /*
2231 * query_tree_walker --- initiate a walk of a Query's expressions
2232 *
2233 * This routine exists just to reduce the number of places that need to know
2234 * where all the expression subtrees of a Query are. Note it can be used
2235 * for starting a walk at top level of a Query regardless of whether the
2236 * walker intends to descend into subqueries. It is also useful for
2237 * descending into subqueries within a walker.
2238 *
2239 * Some callers want to suppress visitation of certain items in the sub-Query,
2240 * typically because they need to process them specially, or don't actually
2241 * want to recurse into subqueries. This is supported by the flags argument,
2242 * which is the bitwise OR of flag values to suppress visitation of
2243 * indicated items. (More flag bits may be added as needed.)
2244 */
2245 bool
query_tree_walker(Query * query,bool (* walker)(),void * context,int flags)2246 query_tree_walker(Query *query,
2247 bool (*walker) (),
2248 void *context,
2249 int flags)
2250 {
2251 Assert(query != NULL && IsA(query, Query));
2252
2253 /*
2254 * We don't walk any utilityStmt here. However, we can't easily assert
2255 * that it is absent, since there are at least two code paths by which
2256 * action statements from CREATE RULE end up here, and NOTIFY is allowed
2257 * in a rule action.
2258 */
2259
2260 if (walker((Node *) query->targetList, context))
2261 return true;
2262 if (walker((Node *) query->withCheckOptions, context))
2263 return true;
2264 if (walker((Node *) query->onConflict, context))
2265 return true;
2266 if (walker((Node *) query->returningList, context))
2267 return true;
2268 if (walker((Node *) query->jointree, context))
2269 return true;
2270 if (walker(query->setOperations, context))
2271 return true;
2272 if (walker(query->havingQual, context))
2273 return true;
2274 if (walker(query->limitOffset, context))
2275 return true;
2276 if (walker(query->limitCount, context))
2277 return true;
2278
2279 /*
2280 * Most callers aren't interested in SortGroupClause nodes since those
2281 * don't contain actual expressions. However they do contain OIDs which
2282 * may be needed by dependency walkers etc.
2283 */
2284 if ((flags & QTW_EXAMINE_SORTGROUP))
2285 {
2286 if (walker((Node *) query->groupClause, context))
2287 return true;
2288 if (walker((Node *) query->windowClause, context))
2289 return true;
2290 if (walker((Node *) query->sortClause, context))
2291 return true;
2292 if (walker((Node *) query->distinctClause, context))
2293 return true;
2294 }
2295 else
2296 {
2297 /*
2298 * But we need to walk the expressions under WindowClause nodes even
2299 * if we're not interested in SortGroupClause nodes.
2300 */
2301 ListCell *lc;
2302
2303 foreach(lc, query->windowClause)
2304 {
2305 WindowClause *wc = lfirst_node(WindowClause, lc);
2306
2307 if (walker(wc->startOffset, context))
2308 return true;
2309 if (walker(wc->endOffset, context))
2310 return true;
2311 }
2312 }
2313
2314 /*
2315 * groupingSets and rowMarks are not walked:
2316 *
2317 * groupingSets contain only ressortgrouprefs (integers) which are
2318 * meaningless without the corresponding groupClause or tlist.
2319 * Accordingly, any walker that needs to care about them needs to handle
2320 * them itself in its Query processing.
2321 *
2322 * rowMarks is not walked because it contains only rangetable indexes (and
2323 * flags etc.) and therefore should be handled at Query level similarly.
2324 */
2325
2326 if (!(flags & QTW_IGNORE_CTE_SUBQUERIES))
2327 {
2328 if (walker((Node *) query->cteList, context))
2329 return true;
2330 }
2331 if (!(flags & QTW_IGNORE_RANGE_TABLE))
2332 {
2333 if (range_table_walker(query->rtable, walker, context, flags))
2334 return true;
2335 }
2336 return false;
2337 }
2338
2339 /*
2340 * range_table_walker is just the part of query_tree_walker that scans
2341 * a query's rangetable. This is split out since it can be useful on
2342 * its own.
2343 */
2344 bool
range_table_walker(List * rtable,bool (* walker)(),void * context,int flags)2345 range_table_walker(List *rtable,
2346 bool (*walker) (),
2347 void *context,
2348 int flags)
2349 {
2350 ListCell *rt;
2351
2352 foreach(rt, rtable)
2353 {
2354 RangeTblEntry *rte = (RangeTblEntry *) lfirst(rt);
2355
2356 /* For historical reasons, visiting RTEs is not the default */
2357 if (flags & QTW_EXAMINE_RTES)
2358 if (walker(rte, context))
2359 return true;
2360
2361 switch (rte->rtekind)
2362 {
2363 case RTE_RELATION:
2364 if (walker(rte->tablesample, context))
2365 return true;
2366 break;
2367 case RTE_CTE:
2368 case RTE_NAMEDTUPLESTORE:
2369 /* nothing to do */
2370 break;
2371 case RTE_SUBQUERY:
2372 if (!(flags & QTW_IGNORE_RT_SUBQUERIES))
2373 if (walker(rte->subquery, context))
2374 return true;
2375 break;
2376 case RTE_JOIN:
2377 if (!(flags & QTW_IGNORE_JOINALIASES))
2378 if (walker(rte->joinaliasvars, context))
2379 return true;
2380 break;
2381 case RTE_FUNCTION:
2382 if (walker(rte->functions, context))
2383 return true;
2384 break;
2385 case RTE_TABLEFUNC:
2386 if (walker(rte->tablefunc, context))
2387 return true;
2388 break;
2389 case RTE_VALUES:
2390 if (walker(rte->values_lists, context))
2391 return true;
2392 break;
2393 }
2394
2395 if (walker(rte->securityQuals, context))
2396 return true;
2397 }
2398 return false;
2399 }
2400
2401
2402 /*
2403 * expression_tree_mutator() is designed to support routines that make a
2404 * modified copy of an expression tree, with some nodes being added,
2405 * removed, or replaced by new subtrees. The original tree is (normally)
2406 * not changed. Each recursion level is responsible for returning a copy of
2407 * (or appropriately modified substitute for) the subtree it is handed.
2408 * A mutator routine should look like this:
2409 *
2410 * Node * my_mutator (Node *node, my_struct *context)
2411 * {
2412 * if (node == NULL)
2413 * return NULL;
2414 * // check for nodes that special work is required for, eg:
2415 * if (IsA(node, Var))
2416 * {
2417 * ... create and return modified copy of Var node
2418 * }
2419 * else if (IsA(node, ...))
2420 * {
2421 * ... do special transformations of other node types
2422 * }
2423 * // for any node type not specially processed, do:
2424 * return expression_tree_mutator(node, my_mutator, (void *) context);
2425 * }
2426 *
2427 * The "context" argument points to a struct that holds whatever context
2428 * information the mutator routine needs --- it can be used to return extra
2429 * data gathered by the mutator, too. This argument is not touched by
2430 * expression_tree_mutator, but it is passed down to recursive sub-invocations
2431 * of my_mutator. The tree walk is started from a setup routine that
2432 * fills in the appropriate context struct, calls my_mutator with the
2433 * top-level node of the tree, and does any required post-processing.
2434 *
2435 * Each level of recursion must return an appropriately modified Node.
2436 * If expression_tree_mutator() is called, it will make an exact copy
2437 * of the given Node, but invoke my_mutator() to copy the sub-node(s)
2438 * of that Node. In this way, my_mutator() has full control over the
2439 * copying process but need not directly deal with expression trees
2440 * that it has no interest in.
2441 *
2442 * Just as for expression_tree_walker, the node types handled by
2443 * expression_tree_mutator include all those normally found in target lists
2444 * and qualifier clauses during the planning stage.
2445 *
2446 * expression_tree_mutator will handle SubLink nodes by recursing normally
2447 * into the "testexpr" subtree (which is an expression belonging to the outer
2448 * plan). It will also call the mutator on the sub-Query node; however, when
2449 * expression_tree_mutator itself is called on a Query node, it does nothing
2450 * and returns the unmodified Query node. The net effect is that unless the
2451 * mutator does something special at a Query node, sub-selects will not be
2452 * visited or modified; the original sub-select will be linked to by the new
2453 * SubLink node. Mutators that want to descend into sub-selects will usually
2454 * do so by recognizing Query nodes and calling query_tree_mutator (below).
2455 *
2456 * expression_tree_mutator will handle a SubPlan node by recursing into the
2457 * "testexpr" and the "args" list (which belong to the outer plan), but it
2458 * will simply copy the link to the inner plan, since that's typically what
2459 * expression tree mutators want. A mutator that wants to modify the subplan
2460 * can force appropriate behavior by recognizing SubPlan expression nodes
2461 * and doing the right thing.
2462 */
2463
2464 Node *
expression_tree_mutator(Node * node,Node * (* mutator)(),void * context)2465 expression_tree_mutator(Node *node,
2466 Node *(*mutator) (),
2467 void *context)
2468 {
2469 /*
2470 * The mutator has already decided not to modify the current node, but we
2471 * must call the mutator for any sub-nodes.
2472 */
2473
2474 #define FLATCOPY(newnode, node, nodetype) \
2475 ( (newnode) = (nodetype *) palloc(sizeof(nodetype)), \
2476 memcpy((newnode), (node), sizeof(nodetype)) )
2477
2478 #define CHECKFLATCOPY(newnode, node, nodetype) \
2479 ( AssertMacro(IsA((node), nodetype)), \
2480 (newnode) = (nodetype *) palloc(sizeof(nodetype)), \
2481 memcpy((newnode), (node), sizeof(nodetype)) )
2482
2483 #define MUTATE(newfield, oldfield, fieldtype) \
2484 ( (newfield) = (fieldtype) mutator((Node *) (oldfield), context) )
2485
2486 if (node == NULL)
2487 return NULL;
2488
2489 /* Guard against stack overflow due to overly complex expressions */
2490 check_stack_depth();
2491
2492 switch (nodeTag(node))
2493 {
2494 /*
2495 * Primitive node types with no expression subnodes. Var and
2496 * Const are frequent enough to deserve special cases, the others
2497 * we just use copyObject for.
2498 */
2499 case T_Var:
2500 {
2501 Var *var = (Var *) node;
2502 Var *newnode;
2503
2504 FLATCOPY(newnode, var, Var);
2505 return (Node *) newnode;
2506 }
2507 break;
2508 case T_Const:
2509 {
2510 Const *oldnode = (Const *) node;
2511 Const *newnode;
2512
2513 FLATCOPY(newnode, oldnode, Const);
2514 /* XXX we don't bother with datumCopy; should we? */
2515 return (Node *) newnode;
2516 }
2517 break;
2518 case T_Param:
2519 case T_CaseTestExpr:
2520 case T_SQLValueFunction:
2521 case T_CoerceToDomainValue:
2522 case T_SetToDefault:
2523 case T_CurrentOfExpr:
2524 case T_NextValueExpr:
2525 case T_RangeTblRef:
2526 case T_SortGroupClause:
2527 return (Node *) copyObject(node);
2528 case T_WithCheckOption:
2529 {
2530 WithCheckOption *wco = (WithCheckOption *) node;
2531 WithCheckOption *newnode;
2532
2533 FLATCOPY(newnode, wco, WithCheckOption);
2534 MUTATE(newnode->qual, wco->qual, Node *);
2535 return (Node *) newnode;
2536 }
2537 case T_Aggref:
2538 {
2539 Aggref *aggref = (Aggref *) node;
2540 Aggref *newnode;
2541
2542 FLATCOPY(newnode, aggref, Aggref);
2543 /* assume mutation doesn't change types of arguments */
2544 newnode->aggargtypes = list_copy(aggref->aggargtypes);
2545 MUTATE(newnode->aggdirectargs, aggref->aggdirectargs, List *);
2546 MUTATE(newnode->args, aggref->args, List *);
2547 MUTATE(newnode->aggorder, aggref->aggorder, List *);
2548 MUTATE(newnode->aggdistinct, aggref->aggdistinct, List *);
2549 MUTATE(newnode->aggfilter, aggref->aggfilter, Expr *);
2550 return (Node *) newnode;
2551 }
2552 break;
2553 case T_GroupingFunc:
2554 {
2555 GroupingFunc *grouping = (GroupingFunc *) node;
2556 GroupingFunc *newnode;
2557
2558 FLATCOPY(newnode, grouping, GroupingFunc);
2559 MUTATE(newnode->args, grouping->args, List *);
2560
2561 /*
2562 * We assume here that mutating the arguments does not change
2563 * the semantics, i.e. that the arguments are not mutated in a
2564 * way that makes them semantically different from their
2565 * previously matching expressions in the GROUP BY clause.
2566 *
2567 * If a mutator somehow wanted to do this, it would have to
2568 * handle the refs and cols lists itself as appropriate.
2569 */
2570 newnode->refs = list_copy(grouping->refs);
2571 newnode->cols = list_copy(grouping->cols);
2572
2573 return (Node *) newnode;
2574 }
2575 break;
2576 case T_WindowFunc:
2577 {
2578 WindowFunc *wfunc = (WindowFunc *) node;
2579 WindowFunc *newnode;
2580
2581 FLATCOPY(newnode, wfunc, WindowFunc);
2582 MUTATE(newnode->args, wfunc->args, List *);
2583 MUTATE(newnode->aggfilter, wfunc->aggfilter, Expr *);
2584 return (Node *) newnode;
2585 }
2586 break;
2587 case T_ArrayRef:
2588 {
2589 ArrayRef *arrayref = (ArrayRef *) node;
2590 ArrayRef *newnode;
2591
2592 FLATCOPY(newnode, arrayref, ArrayRef);
2593 MUTATE(newnode->refupperindexpr, arrayref->refupperindexpr,
2594 List *);
2595 MUTATE(newnode->reflowerindexpr, arrayref->reflowerindexpr,
2596 List *);
2597 MUTATE(newnode->refexpr, arrayref->refexpr,
2598 Expr *);
2599 MUTATE(newnode->refassgnexpr, arrayref->refassgnexpr,
2600 Expr *);
2601 return (Node *) newnode;
2602 }
2603 break;
2604 case T_FuncExpr:
2605 {
2606 FuncExpr *expr = (FuncExpr *) node;
2607 FuncExpr *newnode;
2608
2609 FLATCOPY(newnode, expr, FuncExpr);
2610 MUTATE(newnode->args, expr->args, List *);
2611 return (Node *) newnode;
2612 }
2613 break;
2614 case T_NamedArgExpr:
2615 {
2616 NamedArgExpr *nexpr = (NamedArgExpr *) node;
2617 NamedArgExpr *newnode;
2618
2619 FLATCOPY(newnode, nexpr, NamedArgExpr);
2620 MUTATE(newnode->arg, nexpr->arg, Expr *);
2621 return (Node *) newnode;
2622 }
2623 break;
2624 case T_OpExpr:
2625 {
2626 OpExpr *expr = (OpExpr *) node;
2627 OpExpr *newnode;
2628
2629 FLATCOPY(newnode, expr, OpExpr);
2630 MUTATE(newnode->args, expr->args, List *);
2631 return (Node *) newnode;
2632 }
2633 break;
2634 case T_DistinctExpr:
2635 {
2636 DistinctExpr *expr = (DistinctExpr *) node;
2637 DistinctExpr *newnode;
2638
2639 FLATCOPY(newnode, expr, DistinctExpr);
2640 MUTATE(newnode->args, expr->args, List *);
2641 return (Node *) newnode;
2642 }
2643 break;
2644 case T_NullIfExpr:
2645 {
2646 NullIfExpr *expr = (NullIfExpr *) node;
2647 NullIfExpr *newnode;
2648
2649 FLATCOPY(newnode, expr, NullIfExpr);
2650 MUTATE(newnode->args, expr->args, List *);
2651 return (Node *) newnode;
2652 }
2653 break;
2654 case T_ScalarArrayOpExpr:
2655 {
2656 ScalarArrayOpExpr *expr = (ScalarArrayOpExpr *) node;
2657 ScalarArrayOpExpr *newnode;
2658
2659 FLATCOPY(newnode, expr, ScalarArrayOpExpr);
2660 MUTATE(newnode->args, expr->args, List *);
2661 return (Node *) newnode;
2662 }
2663 break;
2664 case T_BoolExpr:
2665 {
2666 BoolExpr *expr = (BoolExpr *) node;
2667 BoolExpr *newnode;
2668
2669 FLATCOPY(newnode, expr, BoolExpr);
2670 MUTATE(newnode->args, expr->args, List *);
2671 return (Node *) newnode;
2672 }
2673 break;
2674 case T_SubLink:
2675 {
2676 SubLink *sublink = (SubLink *) node;
2677 SubLink *newnode;
2678
2679 FLATCOPY(newnode, sublink, SubLink);
2680 MUTATE(newnode->testexpr, sublink->testexpr, Node *);
2681
2682 /*
2683 * Also invoke the mutator on the sublink's Query node, so it
2684 * can recurse into the sub-query if it wants to.
2685 */
2686 MUTATE(newnode->subselect, sublink->subselect, Node *);
2687 return (Node *) newnode;
2688 }
2689 break;
2690 case T_SubPlan:
2691 {
2692 SubPlan *subplan = (SubPlan *) node;
2693 SubPlan *newnode;
2694
2695 FLATCOPY(newnode, subplan, SubPlan);
2696 /* transform testexpr */
2697 MUTATE(newnode->testexpr, subplan->testexpr, Node *);
2698 /* transform args list (params to be passed to subplan) */
2699 MUTATE(newnode->args, subplan->args, List *);
2700 /* but not the sub-Plan itself, which is referenced as-is */
2701 return (Node *) newnode;
2702 }
2703 break;
2704 case T_AlternativeSubPlan:
2705 {
2706 AlternativeSubPlan *asplan = (AlternativeSubPlan *) node;
2707 AlternativeSubPlan *newnode;
2708
2709 FLATCOPY(newnode, asplan, AlternativeSubPlan);
2710 MUTATE(newnode->subplans, asplan->subplans, List *);
2711 return (Node *) newnode;
2712 }
2713 break;
2714 case T_FieldSelect:
2715 {
2716 FieldSelect *fselect = (FieldSelect *) node;
2717 FieldSelect *newnode;
2718
2719 FLATCOPY(newnode, fselect, FieldSelect);
2720 MUTATE(newnode->arg, fselect->arg, Expr *);
2721 return (Node *) newnode;
2722 }
2723 break;
2724 case T_FieldStore:
2725 {
2726 FieldStore *fstore = (FieldStore *) node;
2727 FieldStore *newnode;
2728
2729 FLATCOPY(newnode, fstore, FieldStore);
2730 MUTATE(newnode->arg, fstore->arg, Expr *);
2731 MUTATE(newnode->newvals, fstore->newvals, List *);
2732 newnode->fieldnums = list_copy(fstore->fieldnums);
2733 return (Node *) newnode;
2734 }
2735 break;
2736 case T_RelabelType:
2737 {
2738 RelabelType *relabel = (RelabelType *) node;
2739 RelabelType *newnode;
2740
2741 FLATCOPY(newnode, relabel, RelabelType);
2742 MUTATE(newnode->arg, relabel->arg, Expr *);
2743 return (Node *) newnode;
2744 }
2745 break;
2746 case T_CoerceViaIO:
2747 {
2748 CoerceViaIO *iocoerce = (CoerceViaIO *) node;
2749 CoerceViaIO *newnode;
2750
2751 FLATCOPY(newnode, iocoerce, CoerceViaIO);
2752 MUTATE(newnode->arg, iocoerce->arg, Expr *);
2753 return (Node *) newnode;
2754 }
2755 break;
2756 case T_ArrayCoerceExpr:
2757 {
2758 ArrayCoerceExpr *acoerce = (ArrayCoerceExpr *) node;
2759 ArrayCoerceExpr *newnode;
2760
2761 FLATCOPY(newnode, acoerce, ArrayCoerceExpr);
2762 MUTATE(newnode->arg, acoerce->arg, Expr *);
2763 return (Node *) newnode;
2764 }
2765 break;
2766 case T_ConvertRowtypeExpr:
2767 {
2768 ConvertRowtypeExpr *convexpr = (ConvertRowtypeExpr *) node;
2769 ConvertRowtypeExpr *newnode;
2770
2771 FLATCOPY(newnode, convexpr, ConvertRowtypeExpr);
2772 MUTATE(newnode->arg, convexpr->arg, Expr *);
2773 return (Node *) newnode;
2774 }
2775 break;
2776 case T_CollateExpr:
2777 {
2778 CollateExpr *collate = (CollateExpr *) node;
2779 CollateExpr *newnode;
2780
2781 FLATCOPY(newnode, collate, CollateExpr);
2782 MUTATE(newnode->arg, collate->arg, Expr *);
2783 return (Node *) newnode;
2784 }
2785 break;
2786 case T_CaseExpr:
2787 {
2788 CaseExpr *caseexpr = (CaseExpr *) node;
2789 CaseExpr *newnode;
2790
2791 FLATCOPY(newnode, caseexpr, CaseExpr);
2792 MUTATE(newnode->arg, caseexpr->arg, Expr *);
2793 MUTATE(newnode->args, caseexpr->args, List *);
2794 MUTATE(newnode->defresult, caseexpr->defresult, Expr *);
2795 return (Node *) newnode;
2796 }
2797 break;
2798 case T_CaseWhen:
2799 {
2800 CaseWhen *casewhen = (CaseWhen *) node;
2801 CaseWhen *newnode;
2802
2803 FLATCOPY(newnode, casewhen, CaseWhen);
2804 MUTATE(newnode->expr, casewhen->expr, Expr *);
2805 MUTATE(newnode->result, casewhen->result, Expr *);
2806 return (Node *) newnode;
2807 }
2808 break;
2809 case T_ArrayExpr:
2810 {
2811 ArrayExpr *arrayexpr = (ArrayExpr *) node;
2812 ArrayExpr *newnode;
2813
2814 FLATCOPY(newnode, arrayexpr, ArrayExpr);
2815 MUTATE(newnode->elements, arrayexpr->elements, List *);
2816 return (Node *) newnode;
2817 }
2818 break;
2819 case T_RowExpr:
2820 {
2821 RowExpr *rowexpr = (RowExpr *) node;
2822 RowExpr *newnode;
2823
2824 FLATCOPY(newnode, rowexpr, RowExpr);
2825 MUTATE(newnode->args, rowexpr->args, List *);
2826 /* Assume colnames needn't be duplicated */
2827 return (Node *) newnode;
2828 }
2829 break;
2830 case T_RowCompareExpr:
2831 {
2832 RowCompareExpr *rcexpr = (RowCompareExpr *) node;
2833 RowCompareExpr *newnode;
2834
2835 FLATCOPY(newnode, rcexpr, RowCompareExpr);
2836 MUTATE(newnode->largs, rcexpr->largs, List *);
2837 MUTATE(newnode->rargs, rcexpr->rargs, List *);
2838 return (Node *) newnode;
2839 }
2840 break;
2841 case T_CoalesceExpr:
2842 {
2843 CoalesceExpr *coalesceexpr = (CoalesceExpr *) node;
2844 CoalesceExpr *newnode;
2845
2846 FLATCOPY(newnode, coalesceexpr, CoalesceExpr);
2847 MUTATE(newnode->args, coalesceexpr->args, List *);
2848 return (Node *) newnode;
2849 }
2850 break;
2851 case T_MinMaxExpr:
2852 {
2853 MinMaxExpr *minmaxexpr = (MinMaxExpr *) node;
2854 MinMaxExpr *newnode;
2855
2856 FLATCOPY(newnode, minmaxexpr, MinMaxExpr);
2857 MUTATE(newnode->args, minmaxexpr->args, List *);
2858 return (Node *) newnode;
2859 }
2860 break;
2861 case T_XmlExpr:
2862 {
2863 XmlExpr *xexpr = (XmlExpr *) node;
2864 XmlExpr *newnode;
2865
2866 FLATCOPY(newnode, xexpr, XmlExpr);
2867 MUTATE(newnode->named_args, xexpr->named_args, List *);
2868 /* assume mutator does not care about arg_names */
2869 MUTATE(newnode->args, xexpr->args, List *);
2870 return (Node *) newnode;
2871 }
2872 break;
2873 case T_NullTest:
2874 {
2875 NullTest *ntest = (NullTest *) node;
2876 NullTest *newnode;
2877
2878 FLATCOPY(newnode, ntest, NullTest);
2879 MUTATE(newnode->arg, ntest->arg, Expr *);
2880 return (Node *) newnode;
2881 }
2882 break;
2883 case T_BooleanTest:
2884 {
2885 BooleanTest *btest = (BooleanTest *) node;
2886 BooleanTest *newnode;
2887
2888 FLATCOPY(newnode, btest, BooleanTest);
2889 MUTATE(newnode->arg, btest->arg, Expr *);
2890 return (Node *) newnode;
2891 }
2892 break;
2893 case T_CoerceToDomain:
2894 {
2895 CoerceToDomain *ctest = (CoerceToDomain *) node;
2896 CoerceToDomain *newnode;
2897
2898 FLATCOPY(newnode, ctest, CoerceToDomain);
2899 MUTATE(newnode->arg, ctest->arg, Expr *);
2900 return (Node *) newnode;
2901 }
2902 break;
2903 case T_TargetEntry:
2904 {
2905 TargetEntry *targetentry = (TargetEntry *) node;
2906 TargetEntry *newnode;
2907
2908 FLATCOPY(newnode, targetentry, TargetEntry);
2909 MUTATE(newnode->expr, targetentry->expr, Expr *);
2910 return (Node *) newnode;
2911 }
2912 break;
2913 case T_Query:
2914 /* Do nothing with a sub-Query, per discussion above */
2915 return node;
2916 case T_WindowClause:
2917 {
2918 WindowClause *wc = (WindowClause *) node;
2919 WindowClause *newnode;
2920
2921 FLATCOPY(newnode, wc, WindowClause);
2922 MUTATE(newnode->partitionClause, wc->partitionClause, List *);
2923 MUTATE(newnode->orderClause, wc->orderClause, List *);
2924 MUTATE(newnode->startOffset, wc->startOffset, Node *);
2925 MUTATE(newnode->endOffset, wc->endOffset, Node *);
2926 return (Node *) newnode;
2927 }
2928 break;
2929 case T_CommonTableExpr:
2930 {
2931 CommonTableExpr *cte = (CommonTableExpr *) node;
2932 CommonTableExpr *newnode;
2933
2934 FLATCOPY(newnode, cte, CommonTableExpr);
2935
2936 /*
2937 * Also invoke the mutator on the CTE's Query node, so it can
2938 * recurse into the sub-query if it wants to.
2939 */
2940 MUTATE(newnode->ctequery, cte->ctequery, Node *);
2941 return (Node *) newnode;
2942 }
2943 break;
2944 case T_List:
2945 {
2946 /*
2947 * We assume the mutator isn't interested in the list nodes
2948 * per se, so just invoke it on each list element. NOTE: this
2949 * would fail badly on a list with integer elements!
2950 */
2951 List *resultlist;
2952 ListCell *temp;
2953
2954 resultlist = NIL;
2955 foreach(temp, (List *) node)
2956 {
2957 resultlist = lappend(resultlist,
2958 mutator((Node *) lfirst(temp),
2959 context));
2960 }
2961 return (Node *) resultlist;
2962 }
2963 break;
2964 case T_FromExpr:
2965 {
2966 FromExpr *from = (FromExpr *) node;
2967 FromExpr *newnode;
2968
2969 FLATCOPY(newnode, from, FromExpr);
2970 MUTATE(newnode->fromlist, from->fromlist, List *);
2971 MUTATE(newnode->quals, from->quals, Node *);
2972 return (Node *) newnode;
2973 }
2974 break;
2975 case T_OnConflictExpr:
2976 {
2977 OnConflictExpr *oc = (OnConflictExpr *) node;
2978 OnConflictExpr *newnode;
2979
2980 FLATCOPY(newnode, oc, OnConflictExpr);
2981 MUTATE(newnode->arbiterElems, oc->arbiterElems, List *);
2982 MUTATE(newnode->arbiterWhere, oc->arbiterWhere, Node *);
2983 MUTATE(newnode->onConflictSet, oc->onConflictSet, List *);
2984 MUTATE(newnode->onConflictWhere, oc->onConflictWhere, Node *);
2985 MUTATE(newnode->exclRelTlist, oc->exclRelTlist, List *);
2986
2987 return (Node *) newnode;
2988 }
2989 break;
2990 case T_JoinExpr:
2991 {
2992 JoinExpr *join = (JoinExpr *) node;
2993 JoinExpr *newnode;
2994
2995 FLATCOPY(newnode, join, JoinExpr);
2996 MUTATE(newnode->larg, join->larg, Node *);
2997 MUTATE(newnode->rarg, join->rarg, Node *);
2998 MUTATE(newnode->quals, join->quals, Node *);
2999 /* We do not mutate alias or using by default */
3000 return (Node *) newnode;
3001 }
3002 break;
3003 case T_SetOperationStmt:
3004 {
3005 SetOperationStmt *setop = (SetOperationStmt *) node;
3006 SetOperationStmt *newnode;
3007
3008 FLATCOPY(newnode, setop, SetOperationStmt);
3009 MUTATE(newnode->larg, setop->larg, Node *);
3010 MUTATE(newnode->rarg, setop->rarg, Node *);
3011 /* We do not mutate groupClauses by default */
3012 return (Node *) newnode;
3013 }
3014 break;
3015 case T_PlaceHolderVar:
3016 {
3017 PlaceHolderVar *phv = (PlaceHolderVar *) node;
3018 PlaceHolderVar *newnode;
3019
3020 FLATCOPY(newnode, phv, PlaceHolderVar);
3021 MUTATE(newnode->phexpr, phv->phexpr, Expr *);
3022 /* Assume we need not copy the relids bitmapset */
3023 return (Node *) newnode;
3024 }
3025 break;
3026 case T_InferenceElem:
3027 {
3028 InferenceElem *inferenceelemdexpr = (InferenceElem *) node;
3029 InferenceElem *newnode;
3030
3031 FLATCOPY(newnode, inferenceelemdexpr, InferenceElem);
3032 MUTATE(newnode->expr, newnode->expr, Node *);
3033 return (Node *) newnode;
3034 }
3035 break;
3036 case T_AppendRelInfo:
3037 {
3038 AppendRelInfo *appinfo = (AppendRelInfo *) node;
3039 AppendRelInfo *newnode;
3040
3041 FLATCOPY(newnode, appinfo, AppendRelInfo);
3042 MUTATE(newnode->translated_vars, appinfo->translated_vars, List *);
3043 return (Node *) newnode;
3044 }
3045 break;
3046 case T_PlaceHolderInfo:
3047 {
3048 PlaceHolderInfo *phinfo = (PlaceHolderInfo *) node;
3049 PlaceHolderInfo *newnode;
3050
3051 FLATCOPY(newnode, phinfo, PlaceHolderInfo);
3052 MUTATE(newnode->ph_var, phinfo->ph_var, PlaceHolderVar *);
3053 /* Assume we need not copy the relids bitmapsets */
3054 return (Node *) newnode;
3055 }
3056 break;
3057 case T_RangeTblFunction:
3058 {
3059 RangeTblFunction *rtfunc = (RangeTblFunction *) node;
3060 RangeTblFunction *newnode;
3061
3062 FLATCOPY(newnode, rtfunc, RangeTblFunction);
3063 MUTATE(newnode->funcexpr, rtfunc->funcexpr, Node *);
3064 /* Assume we need not copy the coldef info lists */
3065 return (Node *) newnode;
3066 }
3067 break;
3068 case T_TableSampleClause:
3069 {
3070 TableSampleClause *tsc = (TableSampleClause *) node;
3071 TableSampleClause *newnode;
3072
3073 FLATCOPY(newnode, tsc, TableSampleClause);
3074 MUTATE(newnode->args, tsc->args, List *);
3075 MUTATE(newnode->repeatable, tsc->repeatable, Expr *);
3076 return (Node *) newnode;
3077 }
3078 break;
3079 case T_TableFunc:
3080 {
3081 TableFunc *tf = (TableFunc *) node;
3082 TableFunc *newnode;
3083
3084 FLATCOPY(newnode, tf, TableFunc);
3085 MUTATE(newnode->ns_uris, tf->ns_uris, List *);
3086 MUTATE(newnode->docexpr, tf->docexpr, Node *);
3087 MUTATE(newnode->rowexpr, tf->rowexpr, Node *);
3088 MUTATE(newnode->colexprs, tf->colexprs, List *);
3089 MUTATE(newnode->coldefexprs, tf->coldefexprs, List *);
3090 return (Node *) newnode;
3091 }
3092 break;
3093 default:
3094 elog(ERROR, "unrecognized node type: %d",
3095 (int) nodeTag(node));
3096 break;
3097 }
3098 /* can't get here, but keep compiler happy */
3099 return NULL;
3100 }
3101
3102
3103 /*
3104 * query_tree_mutator --- initiate modification of a Query's expressions
3105 *
3106 * This routine exists just to reduce the number of places that need to know
3107 * where all the expression subtrees of a Query are. Note it can be used
3108 * for starting a walk at top level of a Query regardless of whether the
3109 * mutator intends to descend into subqueries. It is also useful for
3110 * descending into subqueries within a mutator.
3111 *
3112 * Some callers want to suppress mutating of certain items in the Query,
3113 * typically because they need to process them specially, or don't actually
3114 * want to recurse into subqueries. This is supported by the flags argument,
3115 * which is the bitwise OR of flag values to suppress mutating of
3116 * indicated items. (More flag bits may be added as needed.)
3117 *
3118 * Normally the Query node itself is copied, but some callers want it to be
3119 * modified in-place; they must pass QTW_DONT_COPY_QUERY in flags. All
3120 * modified substructure is safely copied in any case.
3121 */
3122 Query *
query_tree_mutator(Query * query,Node * (* mutator)(),void * context,int flags)3123 query_tree_mutator(Query *query,
3124 Node *(*mutator) (),
3125 void *context,
3126 int flags)
3127 {
3128 Assert(query != NULL && IsA(query, Query));
3129
3130 if (!(flags & QTW_DONT_COPY_QUERY))
3131 {
3132 Query *newquery;
3133
3134 FLATCOPY(newquery, query, Query);
3135 query = newquery;
3136 }
3137
3138 MUTATE(query->targetList, query->targetList, List *);
3139 MUTATE(query->withCheckOptions, query->withCheckOptions, List *);
3140 MUTATE(query->onConflict, query->onConflict, OnConflictExpr *);
3141 MUTATE(query->returningList, query->returningList, List *);
3142 MUTATE(query->jointree, query->jointree, FromExpr *);
3143 MUTATE(query->setOperations, query->setOperations, Node *);
3144 MUTATE(query->havingQual, query->havingQual, Node *);
3145 MUTATE(query->limitOffset, query->limitOffset, Node *);
3146 MUTATE(query->limitCount, query->limitCount, Node *);
3147
3148 /*
3149 * Most callers aren't interested in SortGroupClause nodes since those
3150 * don't contain actual expressions. However they do contain OIDs, which
3151 * may be of interest to some mutators.
3152 */
3153
3154 if ((flags & QTW_EXAMINE_SORTGROUP))
3155 {
3156 MUTATE(query->groupClause, query->groupClause, List *);
3157 MUTATE(query->windowClause, query->windowClause, List *);
3158 MUTATE(query->sortClause, query->sortClause, List *);
3159 MUTATE(query->distinctClause, query->distinctClause, List *);
3160 }
3161 else
3162 {
3163 /*
3164 * But we need to mutate the expressions under WindowClause nodes even
3165 * if we're not interested in SortGroupClause nodes.
3166 */
3167 List *resultlist;
3168 ListCell *temp;
3169
3170 resultlist = NIL;
3171 foreach(temp, query->windowClause)
3172 {
3173 WindowClause *wc = lfirst_node(WindowClause, temp);
3174 WindowClause *newnode;
3175
3176 FLATCOPY(newnode, wc, WindowClause);
3177 MUTATE(newnode->startOffset, wc->startOffset, Node *);
3178 MUTATE(newnode->endOffset, wc->endOffset, Node *);
3179
3180 resultlist = lappend(resultlist, (Node *) newnode);
3181 }
3182 query->windowClause = resultlist;
3183 }
3184
3185 /*
3186 * groupingSets and rowMarks are not mutated:
3187 *
3188 * groupingSets contain only ressortgroup refs (integers) which are
3189 * meaningless without the groupClause or tlist. Accordingly, any mutator
3190 * that needs to care about them needs to handle them itself in its Query
3191 * processing.
3192 *
3193 * rowMarks contains only rangetable indexes (and flags etc.) and
3194 * therefore should be handled at Query level similarly.
3195 */
3196
3197 if (!(flags & QTW_IGNORE_CTE_SUBQUERIES))
3198 MUTATE(query->cteList, query->cteList, List *);
3199 else /* else copy CTE list as-is */
3200 query->cteList = copyObject(query->cteList);
3201 query->rtable = range_table_mutator(query->rtable,
3202 mutator, context, flags);
3203 return query;
3204 }
3205
3206 /*
3207 * range_table_mutator is just the part of query_tree_mutator that processes
3208 * a query's rangetable. This is split out since it can be useful on
3209 * its own.
3210 */
3211 List *
range_table_mutator(List * rtable,Node * (* mutator)(),void * context,int flags)3212 range_table_mutator(List *rtable,
3213 Node *(*mutator) (),
3214 void *context,
3215 int flags)
3216 {
3217 List *newrt = NIL;
3218 ListCell *rt;
3219
3220 foreach(rt, rtable)
3221 {
3222 RangeTblEntry *rte = (RangeTblEntry *) lfirst(rt);
3223 RangeTblEntry *newrte;
3224
3225 FLATCOPY(newrte, rte, RangeTblEntry);
3226 switch (rte->rtekind)
3227 {
3228 case RTE_RELATION:
3229 MUTATE(newrte->tablesample, rte->tablesample,
3230 TableSampleClause *);
3231 /* we don't bother to copy eref, aliases, etc; OK? */
3232 break;
3233 case RTE_CTE:
3234 case RTE_NAMEDTUPLESTORE:
3235 /* nothing to do */
3236 break;
3237 case RTE_SUBQUERY:
3238 if (!(flags & QTW_IGNORE_RT_SUBQUERIES))
3239 {
3240 CHECKFLATCOPY(newrte->subquery, rte->subquery, Query);
3241 MUTATE(newrte->subquery, newrte->subquery, Query *);
3242 }
3243 else
3244 {
3245 /* else, copy RT subqueries as-is */
3246 newrte->subquery = copyObject(rte->subquery);
3247 }
3248 break;
3249 case RTE_JOIN:
3250 if (!(flags & QTW_IGNORE_JOINALIASES))
3251 MUTATE(newrte->joinaliasvars, rte->joinaliasvars, List *);
3252 else
3253 {
3254 /* else, copy join aliases as-is */
3255 newrte->joinaliasvars = copyObject(rte->joinaliasvars);
3256 }
3257 break;
3258 case RTE_FUNCTION:
3259 MUTATE(newrte->functions, rte->functions, List *);
3260 break;
3261 case RTE_TABLEFUNC:
3262 MUTATE(newrte->tablefunc, rte->tablefunc, TableFunc *);
3263 break;
3264 case RTE_VALUES:
3265 MUTATE(newrte->values_lists, rte->values_lists, List *);
3266 break;
3267 }
3268 MUTATE(newrte->securityQuals, rte->securityQuals, List *);
3269 newrt = lappend(newrt, newrte);
3270 }
3271 return newrt;
3272 }
3273
3274 /*
3275 * query_or_expression_tree_walker --- hybrid form
3276 *
3277 * This routine will invoke query_tree_walker if called on a Query node,
3278 * else will invoke the walker directly. This is a useful way of starting
3279 * the recursion when the walker's normal change of state is not appropriate
3280 * for the outermost Query node.
3281 */
3282 bool
query_or_expression_tree_walker(Node * node,bool (* walker)(),void * context,int flags)3283 query_or_expression_tree_walker(Node *node,
3284 bool (*walker) (),
3285 void *context,
3286 int flags)
3287 {
3288 if (node && IsA(node, Query))
3289 return query_tree_walker((Query *) node,
3290 walker,
3291 context,
3292 flags);
3293 else
3294 return walker(node, context);
3295 }
3296
3297 /*
3298 * query_or_expression_tree_mutator --- hybrid form
3299 *
3300 * This routine will invoke query_tree_mutator if called on a Query node,
3301 * else will invoke the mutator directly. This is a useful way of starting
3302 * the recursion when the mutator's normal change of state is not appropriate
3303 * for the outermost Query node.
3304 */
3305 Node *
query_or_expression_tree_mutator(Node * node,Node * (* mutator)(),void * context,int flags)3306 query_or_expression_tree_mutator(Node *node,
3307 Node *(*mutator) (),
3308 void *context,
3309 int flags)
3310 {
3311 if (node && IsA(node, Query))
3312 return (Node *) query_tree_mutator((Query *) node,
3313 mutator,
3314 context,
3315 flags);
3316 else
3317 return mutator(node, context);
3318 }
3319
3320
3321 /*
3322 * raw_expression_tree_walker --- walk raw parse trees
3323 *
3324 * This has exactly the same API as expression_tree_walker, but instead of
3325 * walking post-analysis parse trees, it knows how to walk the node types
3326 * found in raw grammar output. (There is not currently any need for a
3327 * combined walker, so we keep them separate in the name of efficiency.)
3328 * Unlike expression_tree_walker, there is no special rule about query
3329 * boundaries: we descend to everything that's possibly interesting.
3330 *
3331 * Currently, the node type coverage here extends only to DML statements
3332 * (SELECT/INSERT/UPDATE/DELETE) and nodes that can appear in them, because
3333 * this is used mainly during analysis of CTEs, and only DML statements can
3334 * appear in CTEs.
3335 */
3336 bool
raw_expression_tree_walker(Node * node,bool (* walker)(),void * context)3337 raw_expression_tree_walker(Node *node,
3338 bool (*walker) (),
3339 void *context)
3340 {
3341 ListCell *temp;
3342
3343 /*
3344 * The walker has already visited the current node, and so we need only
3345 * recurse into any sub-nodes it has.
3346 */
3347 if (node == NULL)
3348 return false;
3349
3350 /* Guard against stack overflow due to overly complex expressions */
3351 check_stack_depth();
3352
3353 switch (nodeTag(node))
3354 {
3355 case T_SetToDefault:
3356 case T_CurrentOfExpr:
3357 case T_SQLValueFunction:
3358 case T_Integer:
3359 case T_Float:
3360 case T_String:
3361 case T_BitString:
3362 case T_Null:
3363 case T_ParamRef:
3364 case T_A_Const:
3365 case T_A_Star:
3366 /* primitive node types with no subnodes */
3367 break;
3368 case T_Alias:
3369 /* we assume the colnames list isn't interesting */
3370 break;
3371 case T_RangeVar:
3372 return walker(((RangeVar *) node)->alias, context);
3373 case T_GroupingFunc:
3374 return walker(((GroupingFunc *) node)->args, context);
3375 case T_SubLink:
3376 {
3377 SubLink *sublink = (SubLink *) node;
3378
3379 if (walker(sublink->testexpr, context))
3380 return true;
3381 /* we assume the operName is not interesting */
3382 if (walker(sublink->subselect, context))
3383 return true;
3384 }
3385 break;
3386 case T_CaseExpr:
3387 {
3388 CaseExpr *caseexpr = (CaseExpr *) node;
3389
3390 if (walker(caseexpr->arg, context))
3391 return true;
3392 /* we assume walker doesn't care about CaseWhens, either */
3393 foreach(temp, caseexpr->args)
3394 {
3395 CaseWhen *when = lfirst_node(CaseWhen, temp);
3396
3397 if (walker(when->expr, context))
3398 return true;
3399 if (walker(when->result, context))
3400 return true;
3401 }
3402 if (walker(caseexpr->defresult, context))
3403 return true;
3404 }
3405 break;
3406 case T_RowExpr:
3407 /* Assume colnames isn't interesting */
3408 return walker(((RowExpr *) node)->args, context);
3409 case T_CoalesceExpr:
3410 return walker(((CoalesceExpr *) node)->args, context);
3411 case T_MinMaxExpr:
3412 return walker(((MinMaxExpr *) node)->args, context);
3413 case T_XmlExpr:
3414 {
3415 XmlExpr *xexpr = (XmlExpr *) node;
3416
3417 if (walker(xexpr->named_args, context))
3418 return true;
3419 /* we assume walker doesn't care about arg_names */
3420 if (walker(xexpr->args, context))
3421 return true;
3422 }
3423 break;
3424 case T_NullTest:
3425 return walker(((NullTest *) node)->arg, context);
3426 case T_BooleanTest:
3427 return walker(((BooleanTest *) node)->arg, context);
3428 case T_JoinExpr:
3429 {
3430 JoinExpr *join = (JoinExpr *) node;
3431
3432 if (walker(join->larg, context))
3433 return true;
3434 if (walker(join->rarg, context))
3435 return true;
3436 if (walker(join->quals, context))
3437 return true;
3438 if (walker(join->alias, context))
3439 return true;
3440 /* using list is deemed uninteresting */
3441 }
3442 break;
3443 case T_IntoClause:
3444 {
3445 IntoClause *into = (IntoClause *) node;
3446
3447 if (walker(into->rel, context))
3448 return true;
3449 /* colNames, options are deemed uninteresting */
3450 /* viewQuery should be null in raw parsetree, but check it */
3451 if (walker(into->viewQuery, context))
3452 return true;
3453 }
3454 break;
3455 case T_List:
3456 foreach(temp, (List *) node)
3457 {
3458 if (walker((Node *) lfirst(temp), context))
3459 return true;
3460 }
3461 break;
3462 case T_InsertStmt:
3463 {
3464 InsertStmt *stmt = (InsertStmt *) node;
3465
3466 if (walker(stmt->relation, context))
3467 return true;
3468 if (walker(stmt->cols, context))
3469 return true;
3470 if (walker(stmt->selectStmt, context))
3471 return true;
3472 if (walker(stmt->onConflictClause, context))
3473 return true;
3474 if (walker(stmt->returningList, context))
3475 return true;
3476 if (walker(stmt->withClause, context))
3477 return true;
3478 }
3479 break;
3480 case T_DeleteStmt:
3481 {
3482 DeleteStmt *stmt = (DeleteStmt *) node;
3483
3484 if (walker(stmt->relation, context))
3485 return true;
3486 if (walker(stmt->usingClause, context))
3487 return true;
3488 if (walker(stmt->whereClause, context))
3489 return true;
3490 if (walker(stmt->returningList, context))
3491 return true;
3492 if (walker(stmt->withClause, context))
3493 return true;
3494 }
3495 break;
3496 case T_UpdateStmt:
3497 {
3498 UpdateStmt *stmt = (UpdateStmt *) node;
3499
3500 if (walker(stmt->relation, context))
3501 return true;
3502 if (walker(stmt->targetList, context))
3503 return true;
3504 if (walker(stmt->whereClause, context))
3505 return true;
3506 if (walker(stmt->fromClause, context))
3507 return true;
3508 if (walker(stmt->returningList, context))
3509 return true;
3510 if (walker(stmt->withClause, context))
3511 return true;
3512 }
3513 break;
3514 case T_SelectStmt:
3515 {
3516 SelectStmt *stmt = (SelectStmt *) node;
3517
3518 if (walker(stmt->distinctClause, context))
3519 return true;
3520 if (walker(stmt->intoClause, context))
3521 return true;
3522 if (walker(stmt->targetList, context))
3523 return true;
3524 if (walker(stmt->fromClause, context))
3525 return true;
3526 if (walker(stmt->whereClause, context))
3527 return true;
3528 if (walker(stmt->groupClause, context))
3529 return true;
3530 if (walker(stmt->havingClause, context))
3531 return true;
3532 if (walker(stmt->windowClause, context))
3533 return true;
3534 if (walker(stmt->valuesLists, context))
3535 return true;
3536 if (walker(stmt->sortClause, context))
3537 return true;
3538 if (walker(stmt->limitOffset, context))
3539 return true;
3540 if (walker(stmt->limitCount, context))
3541 return true;
3542 if (walker(stmt->lockingClause, context))
3543 return true;
3544 if (walker(stmt->withClause, context))
3545 return true;
3546 if (walker(stmt->larg, context))
3547 return true;
3548 if (walker(stmt->rarg, context))
3549 return true;
3550 }
3551 break;
3552 case T_A_Expr:
3553 {
3554 A_Expr *expr = (A_Expr *) node;
3555
3556 if (walker(expr->lexpr, context))
3557 return true;
3558 if (walker(expr->rexpr, context))
3559 return true;
3560 /* operator name is deemed uninteresting */
3561 }
3562 break;
3563 case T_BoolExpr:
3564 {
3565 BoolExpr *expr = (BoolExpr *) node;
3566
3567 if (walker(expr->args, context))
3568 return true;
3569 }
3570 break;
3571 case T_ColumnRef:
3572 /* we assume the fields contain nothing interesting */
3573 break;
3574 case T_FuncCall:
3575 {
3576 FuncCall *fcall = (FuncCall *) node;
3577
3578 if (walker(fcall->args, context))
3579 return true;
3580 if (walker(fcall->agg_order, context))
3581 return true;
3582 if (walker(fcall->agg_filter, context))
3583 return true;
3584 if (walker(fcall->over, context))
3585 return true;
3586 /* function name is deemed uninteresting */
3587 }
3588 break;
3589 case T_NamedArgExpr:
3590 return walker(((NamedArgExpr *) node)->arg, context);
3591 case T_A_Indices:
3592 {
3593 A_Indices *indices = (A_Indices *) node;
3594
3595 if (walker(indices->lidx, context))
3596 return true;
3597 if (walker(indices->uidx, context))
3598 return true;
3599 }
3600 break;
3601 case T_A_Indirection:
3602 {
3603 A_Indirection *indir = (A_Indirection *) node;
3604
3605 if (walker(indir->arg, context))
3606 return true;
3607 if (walker(indir->indirection, context))
3608 return true;
3609 }
3610 break;
3611 case T_A_ArrayExpr:
3612 return walker(((A_ArrayExpr *) node)->elements, context);
3613 case T_ResTarget:
3614 {
3615 ResTarget *rt = (ResTarget *) node;
3616
3617 if (walker(rt->indirection, context))
3618 return true;
3619 if (walker(rt->val, context))
3620 return true;
3621 }
3622 break;
3623 case T_MultiAssignRef:
3624 return walker(((MultiAssignRef *) node)->source, context);
3625 case T_TypeCast:
3626 {
3627 TypeCast *tc = (TypeCast *) node;
3628
3629 if (walker(tc->arg, context))
3630 return true;
3631 if (walker(tc->typeName, context))
3632 return true;
3633 }
3634 break;
3635 case T_CollateClause:
3636 return walker(((CollateClause *) node)->arg, context);
3637 case T_SortBy:
3638 return walker(((SortBy *) node)->node, context);
3639 case T_WindowDef:
3640 {
3641 WindowDef *wd = (WindowDef *) node;
3642
3643 if (walker(wd->partitionClause, context))
3644 return true;
3645 if (walker(wd->orderClause, context))
3646 return true;
3647 if (walker(wd->startOffset, context))
3648 return true;
3649 if (walker(wd->endOffset, context))
3650 return true;
3651 }
3652 break;
3653 case T_RangeSubselect:
3654 {
3655 RangeSubselect *rs = (RangeSubselect *) node;
3656
3657 if (walker(rs->subquery, context))
3658 return true;
3659 if (walker(rs->alias, context))
3660 return true;
3661 }
3662 break;
3663 case T_RangeFunction:
3664 {
3665 RangeFunction *rf = (RangeFunction *) node;
3666
3667 if (walker(rf->functions, context))
3668 return true;
3669 if (walker(rf->alias, context))
3670 return true;
3671 if (walker(rf->coldeflist, context))
3672 return true;
3673 }
3674 break;
3675 case T_RangeTableSample:
3676 {
3677 RangeTableSample *rts = (RangeTableSample *) node;
3678
3679 if (walker(rts->relation, context))
3680 return true;
3681 /* method name is deemed uninteresting */
3682 if (walker(rts->args, context))
3683 return true;
3684 if (walker(rts->repeatable, context))
3685 return true;
3686 }
3687 break;
3688 case T_RangeTableFunc:
3689 {
3690 RangeTableFunc *rtf = (RangeTableFunc *) node;
3691
3692 if (walker(rtf->docexpr, context))
3693 return true;
3694 if (walker(rtf->rowexpr, context))
3695 return true;
3696 if (walker(rtf->namespaces, context))
3697 return true;
3698 if (walker(rtf->columns, context))
3699 return true;
3700 if (walker(rtf->alias, context))
3701 return true;
3702 }
3703 break;
3704 case T_RangeTableFuncCol:
3705 {
3706 RangeTableFuncCol *rtfc = (RangeTableFuncCol *) node;
3707
3708 if (walker(rtfc->colexpr, context))
3709 return true;
3710 if (walker(rtfc->coldefexpr, context))
3711 return true;
3712 }
3713 break;
3714 case T_TypeName:
3715 {
3716 TypeName *tn = (TypeName *) node;
3717
3718 if (walker(tn->typmods, context))
3719 return true;
3720 if (walker(tn->arrayBounds, context))
3721 return true;
3722 /* type name itself is deemed uninteresting */
3723 }
3724 break;
3725 case T_ColumnDef:
3726 {
3727 ColumnDef *coldef = (ColumnDef *) node;
3728
3729 if (walker(coldef->typeName, context))
3730 return true;
3731 if (walker(coldef->raw_default, context))
3732 return true;
3733 if (walker(coldef->collClause, context))
3734 return true;
3735 /* for now, constraints are ignored */
3736 }
3737 break;
3738 case T_IndexElem:
3739 {
3740 IndexElem *indelem = (IndexElem *) node;
3741
3742 if (walker(indelem->expr, context))
3743 return true;
3744 /* collation and opclass names are deemed uninteresting */
3745 }
3746 break;
3747 case T_GroupingSet:
3748 return walker(((GroupingSet *) node)->content, context);
3749 case T_LockingClause:
3750 return walker(((LockingClause *) node)->lockedRels, context);
3751 case T_XmlSerialize:
3752 {
3753 XmlSerialize *xs = (XmlSerialize *) node;
3754
3755 if (walker(xs->expr, context))
3756 return true;
3757 if (walker(xs->typeName, context))
3758 return true;
3759 }
3760 break;
3761 case T_WithClause:
3762 return walker(((WithClause *) node)->ctes, context);
3763 case T_InferClause:
3764 {
3765 InferClause *stmt = (InferClause *) node;
3766
3767 if (walker(stmt->indexElems, context))
3768 return true;
3769 if (walker(stmt->whereClause, context))
3770 return true;
3771 }
3772 break;
3773 case T_OnConflictClause:
3774 {
3775 OnConflictClause *stmt = (OnConflictClause *) node;
3776
3777 if (walker(stmt->infer, context))
3778 return true;
3779 if (walker(stmt->targetList, context))
3780 return true;
3781 if (walker(stmt->whereClause, context))
3782 return true;
3783 }
3784 break;
3785 case T_CommonTableExpr:
3786 return walker(((CommonTableExpr *) node)->ctequery, context);
3787 default:
3788 elog(ERROR, "unrecognized node type: %d",
3789 (int) nodeTag(node));
3790 break;
3791 }
3792 return false;
3793 }
3794
3795 /*
3796 * planstate_tree_walker --- walk plan state trees
3797 *
3798 * The walker has already visited the current node, and so we need only
3799 * recurse into any sub-nodes it has.
3800 */
3801 bool
planstate_tree_walker(PlanState * planstate,bool (* walker)(),void * context)3802 planstate_tree_walker(PlanState *planstate,
3803 bool (*walker) (),
3804 void *context)
3805 {
3806 Plan *plan = planstate->plan;
3807 ListCell *lc;
3808
3809 /* Guard against stack overflow due to overly complex plan trees */
3810 check_stack_depth();
3811
3812 /* initPlan-s */
3813 if (planstate_walk_subplans(planstate->initPlan, walker, context))
3814 return true;
3815
3816 /* lefttree */
3817 if (outerPlanState(planstate))
3818 {
3819 if (walker(outerPlanState(planstate), context))
3820 return true;
3821 }
3822
3823 /* righttree */
3824 if (innerPlanState(planstate))
3825 {
3826 if (walker(innerPlanState(planstate), context))
3827 return true;
3828 }
3829
3830 /* special child plans */
3831 switch (nodeTag(plan))
3832 {
3833 case T_ModifyTable:
3834 if (planstate_walk_members(((ModifyTable *) plan)->plans,
3835 ((ModifyTableState *) planstate)->mt_plans,
3836 walker, context))
3837 return true;
3838 break;
3839 case T_Append:
3840 if (planstate_walk_members(((Append *) plan)->appendplans,
3841 ((AppendState *) planstate)->appendplans,
3842 walker, context))
3843 return true;
3844 break;
3845 case T_MergeAppend:
3846 if (planstate_walk_members(((MergeAppend *) plan)->mergeplans,
3847 ((MergeAppendState *) planstate)->mergeplans,
3848 walker, context))
3849 return true;
3850 break;
3851 case T_BitmapAnd:
3852 if (planstate_walk_members(((BitmapAnd *) plan)->bitmapplans,
3853 ((BitmapAndState *) planstate)->bitmapplans,
3854 walker, context))
3855 return true;
3856 break;
3857 case T_BitmapOr:
3858 if (planstate_walk_members(((BitmapOr *) plan)->bitmapplans,
3859 ((BitmapOrState *) planstate)->bitmapplans,
3860 walker, context))
3861 return true;
3862 break;
3863 case T_SubqueryScan:
3864 if (walker(((SubqueryScanState *) planstate)->subplan, context))
3865 return true;
3866 break;
3867 case T_CustomScan:
3868 foreach(lc, ((CustomScanState *) planstate)->custom_ps)
3869 {
3870 if (walker((PlanState *) lfirst(lc), context))
3871 return true;
3872 }
3873 break;
3874 default:
3875 break;
3876 }
3877
3878 /* subPlan-s */
3879 if (planstate_walk_subplans(planstate->subPlan, walker, context))
3880 return true;
3881
3882 return false;
3883 }
3884
3885 /*
3886 * Walk a list of SubPlans (or initPlans, which also use SubPlan nodes).
3887 */
3888 static bool
planstate_walk_subplans(List * plans,bool (* walker)(),void * context)3889 planstate_walk_subplans(List *plans,
3890 bool (*walker) (),
3891 void *context)
3892 {
3893 ListCell *lc;
3894
3895 foreach(lc, plans)
3896 {
3897 SubPlanState *sps = lfirst_node(SubPlanState, lc);
3898
3899 if (walker(sps->planstate, context))
3900 return true;
3901 }
3902
3903 return false;
3904 }
3905
3906 /*
3907 * Walk the constituent plans of a ModifyTable, Append, MergeAppend,
3908 * BitmapAnd, or BitmapOr node.
3909 *
3910 * Note: we don't actually need to examine the Plan list members, but
3911 * we need the list in order to determine the length of the PlanState array.
3912 */
3913 static bool
planstate_walk_members(List * plans,PlanState ** planstates,bool (* walker)(),void * context)3914 planstate_walk_members(List *plans, PlanState **planstates,
3915 bool (*walker) (), void *context)
3916 {
3917 int nplans = list_length(plans);
3918 int j;
3919
3920 for (j = 0; j < nplans; j++)
3921 {
3922 if (walker(planstates[j], context))
3923 return true;
3924 }
3925
3926 return false;
3927 }
3928