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