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