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