PostgreSQL Source Code  git master
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros
parse_func.c
Go to the documentation of this file.
1 /*-------------------------------------------------------------------------
2  *
3  * parse_func.c
4  * handle function calls in parser
5  *
6  * Portions Copyright (c) 1996-2016, PostgreSQL Global Development Group
7  * Portions Copyright (c) 1994, Regents of the University of California
8  *
9  *
10  * IDENTIFICATION
11  * src/backend/parser/parse_func.c
12  *
13  *-------------------------------------------------------------------------
14  */
15 #include "postgres.h"
16 
17 #include "access/htup_details.h"
18 #include "catalog/pg_aggregate.h"
19 #include "catalog/pg_proc.h"
20 #include "catalog/pg_type.h"
21 #include "funcapi.h"
22 #include "lib/stringinfo.h"
23 #include "nodes/makefuncs.h"
24 #include "nodes/nodeFuncs.h"
25 #include "parser/parse_agg.h"
26 #include "parser/parse_clause.h"
27 #include "parser/parse_coerce.h"
28 #include "parser/parse_func.h"
29 #include "parser/parse_relation.h"
30 #include "parser/parse_target.h"
31 #include "parser/parse_type.h"
32 #include "utils/builtins.h"
33 #include "utils/lsyscache.h"
34 #include "utils/syscache.h"
35 
36 
37 static void unify_hypothetical_args(ParseState *pstate,
38  List *fargs, int numAggregatedArgs,
39  Oid *actual_arg_types, Oid *declared_arg_types);
40 static Oid FuncNameAsType(List *funcname);
41 static Node *ParseComplexProjection(ParseState *pstate, char *funcname,
42  Node *first_arg, int location);
43 
44 
45 /*
46  * Parse a function call
47  *
48  * For historical reasons, Postgres tries to treat the notations tab.col
49  * and col(tab) as equivalent: if a single-argument function call has an
50  * argument of complex type and the (unqualified) function name matches
51  * any attribute of the type, we take it as a column projection. Conversely
52  * a function of a single complex-type argument can be written like a
53  * column reference, allowing functions to act like computed columns.
54  *
55  * Hence, both cases come through here. If fn is null, we're dealing with
56  * column syntax not function syntax, but in principle that should not
57  * affect the lookup behavior, only which error messages we deliver.
58  * The FuncCall struct is needed however to carry various decoration that
59  * applies to aggregate and window functions.
60  *
61  * Also, when fn is null, we return NULL on failure rather than
62  * reporting a no-such-function error.
63  *
64  * The argument expressions (in fargs) must have been transformed
65  * already. However, nothing in *fn has been transformed.
66  */
67 Node *
68 ParseFuncOrColumn(ParseState *pstate, List *funcname, List *fargs,
69  FuncCall *fn, int location)
70 {
71  bool is_column = (fn == NULL);
72  List *agg_order = (fn ? fn->agg_order : NIL);
73  Expr *agg_filter = NULL;
74  bool agg_within_group = (fn ? fn->agg_within_group : false);
75  bool agg_star = (fn ? fn->agg_star : false);
76  bool agg_distinct = (fn ? fn->agg_distinct : false);
77  bool func_variadic = (fn ? fn->func_variadic : false);
78  WindowDef *over = (fn ? fn->over : NULL);
79  Oid rettype;
80  Oid funcid;
81  ListCell *l;
82  ListCell *nextl;
83  Node *first_arg = NULL;
84  int nargs;
85  int nargsplusdefs;
86  Oid actual_arg_types[FUNC_MAX_ARGS];
87  Oid *declared_arg_types;
88  List *argnames;
89  List *argdefaults;
90  Node *retval;
91  bool retset;
92  int nvargs;
93  Oid vatype;
94  FuncDetailCode fdresult;
95  char aggkind = 0;
96  ParseCallbackState pcbstate;
97 
98  /*
99  * If there's an aggregate filter, transform it using transformWhereClause
100  */
101  if (fn && fn->agg_filter != NULL)
102  agg_filter = (Expr *) transformWhereClause(pstate, fn->agg_filter,
104  "FILTER");
105 
106  /*
107  * Most of the rest of the parser just assumes that functions do not have
108  * more than FUNC_MAX_ARGS parameters. We have to test here to protect
109  * against array overruns, etc. Of course, this may not be a function,
110  * but the test doesn't hurt.
111  */
112  if (list_length(fargs) > FUNC_MAX_ARGS)
113  ereport(ERROR,
114  (errcode(ERRCODE_TOO_MANY_ARGUMENTS),
115  errmsg_plural("cannot pass more than %d argument to a function",
116  "cannot pass more than %d arguments to a function",
118  FUNC_MAX_ARGS),
119  parser_errposition(pstate, location)));
120 
121  /*
122  * Extract arg type info in preparation for function lookup.
123  *
124  * If any arguments are Param markers of type VOID, we discard them from
125  * the parameter list. This is a hack to allow the JDBC driver to not have
126  * to distinguish "input" and "output" parameter symbols while parsing
127  * function-call constructs. Don't do this if dealing with column syntax,
128  * nor if we had WITHIN GROUP (because in that case it's critical to keep
129  * the argument count unchanged). We can't use foreach() because we may
130  * modify the list ...
131  */
132  nargs = 0;
133  for (l = list_head(fargs); l != NULL; l = nextl)
134  {
135  Node *arg = lfirst(l);
136  Oid argtype = exprType(arg);
137 
138  nextl = lnext(l);
139 
140  if (argtype == VOIDOID && IsA(arg, Param) &&
141  !is_column && !agg_within_group)
142  {
143  fargs = list_delete_ptr(fargs, arg);
144  continue;
145  }
146 
147  actual_arg_types[nargs++] = argtype;
148  }
149 
150  /*
151  * Check for named arguments; if there are any, build a list of names.
152  *
153  * We allow mixed notation (some named and some not), but only with all
154  * the named parameters after all the unnamed ones. So the name list
155  * corresponds to the last N actual parameters and we don't need any extra
156  * bookkeeping to match things up.
157  */
158  argnames = NIL;
159  foreach(l, fargs)
160  {
161  Node *arg = lfirst(l);
162 
163  if (IsA(arg, NamedArgExpr))
164  {
165  NamedArgExpr *na = (NamedArgExpr *) arg;
166  ListCell *lc;
167 
168  /* Reject duplicate arg names */
169  foreach(lc, argnames)
170  {
171  if (strcmp(na->name, (char *) lfirst(lc)) == 0)
172  ereport(ERROR,
173  (errcode(ERRCODE_SYNTAX_ERROR),
174  errmsg("argument name \"%s\" used more than once",
175  na->name),
176  parser_errposition(pstate, na->location)));
177  }
178  argnames = lappend(argnames, na->name);
179  }
180  else
181  {
182  if (argnames != NIL)
183  ereport(ERROR,
184  (errcode(ERRCODE_SYNTAX_ERROR),
185  errmsg("positional argument cannot follow named argument"),
186  parser_errposition(pstate, exprLocation(arg))));
187  }
188  }
189 
190  if (fargs)
191  {
192  first_arg = linitial(fargs);
193  Assert(first_arg != NULL);
194  }
195 
196  /*
197  * Check for column projection: if function has one argument, and that
198  * argument is of complex type, and function name is not qualified, then
199  * the "function call" could be a projection. We also check that there
200  * wasn't any aggregate or variadic decoration, nor an argument name.
201  */
202  if (nargs == 1 && agg_order == NIL && agg_filter == NULL && !agg_star &&
203  !agg_distinct && over == NULL && !func_variadic && argnames == NIL &&
204  list_length(funcname) == 1)
205  {
206  Oid argtype = actual_arg_types[0];
207 
208  if (argtype == RECORDOID || ISCOMPLEX(argtype))
209  {
210  retval = ParseComplexProjection(pstate,
211  strVal(linitial(funcname)),
212  first_arg,
213  location);
214  if (retval)
215  return retval;
216 
217  /*
218  * If ParseComplexProjection doesn't recognize it as a projection,
219  * just press on.
220  */
221  }
222  }
223 
224  /*
225  * Okay, it's not a column projection, so it must really be a function.
226  * func_get_detail looks up the function in the catalogs, does
227  * disambiguation for polymorphic functions, handles inheritance, and
228  * returns the funcid and type and set or singleton status of the
229  * function's return value. It also returns the true argument types to
230  * the function.
231  *
232  * Note: for a named-notation or variadic function call, the reported
233  * "true" types aren't really what is in pg_proc: the types are reordered
234  * to match the given argument order of named arguments, and a variadic
235  * argument is replaced by a suitable number of copies of its element
236  * type. We'll fix up the variadic case below. We may also have to deal
237  * with default arguments.
238  */
239 
240  setup_parser_errposition_callback(&pcbstate, pstate, location);
241 
242  fdresult = func_get_detail(funcname, fargs, argnames, nargs,
243  actual_arg_types,
244  !func_variadic, true,
245  &funcid, &rettype, &retset,
246  &nvargs, &vatype,
247  &declared_arg_types, &argdefaults);
248 
250 
251  if (fdresult == FUNCDETAIL_COERCION)
252  {
253  /*
254  * We interpreted it as a type coercion. coerce_type can handle these
255  * cases, so why duplicate code...
256  */
257  return coerce_type(pstate, linitial(fargs),
258  actual_arg_types[0], rettype, -1,
260  }
261  else if (fdresult == FUNCDETAIL_NORMAL)
262  {
263  /*
264  * Normal function found; was there anything indicating it must be an
265  * aggregate?
266  */
267  if (agg_star)
268  ereport(ERROR,
269  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
270  errmsg("%s(*) specified, but %s is not an aggregate function",
271  NameListToString(funcname),
272  NameListToString(funcname)),
273  parser_errposition(pstate, location)));
274  if (agg_distinct)
275  ereport(ERROR,
276  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
277  errmsg("DISTINCT specified, but %s is not an aggregate function",
278  NameListToString(funcname)),
279  parser_errposition(pstate, location)));
280  if (agg_within_group)
281  ereport(ERROR,
282  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
283  errmsg("WITHIN GROUP specified, but %s is not an aggregate function",
284  NameListToString(funcname)),
285  parser_errposition(pstate, location)));
286  if (agg_order != NIL)
287  ereport(ERROR,
288  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
289  errmsg("ORDER BY specified, but %s is not an aggregate function",
290  NameListToString(funcname)),
291  parser_errposition(pstate, location)));
292  if (agg_filter)
293  ereport(ERROR,
294  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
295  errmsg("FILTER specified, but %s is not an aggregate function",
296  NameListToString(funcname)),
297  parser_errposition(pstate, location)));
298  if (over)
299  ereport(ERROR,
300  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
301  errmsg("OVER specified, but %s is not a window function nor an aggregate function",
302  NameListToString(funcname)),
303  parser_errposition(pstate, location)));
304  }
305  else if (fdresult == FUNCDETAIL_AGGREGATE)
306  {
307  /*
308  * It's an aggregate; fetch needed info from the pg_aggregate entry.
309  */
310  HeapTuple tup;
311  Form_pg_aggregate classForm;
312  int catDirectArgs;
313 
314  tup = SearchSysCache1(AGGFNOID, ObjectIdGetDatum(funcid));
315  if (!HeapTupleIsValid(tup)) /* should not happen */
316  elog(ERROR, "cache lookup failed for aggregate %u", funcid);
317  classForm = (Form_pg_aggregate) GETSTRUCT(tup);
318  aggkind = classForm->aggkind;
319  catDirectArgs = classForm->aggnumdirectargs;
320  ReleaseSysCache(tup);
321 
322  /* Now check various disallowed cases. */
323  if (AGGKIND_IS_ORDERED_SET(aggkind))
324  {
325  int numAggregatedArgs;
326  int numDirectArgs;
327 
328  if (!agg_within_group)
329  ereport(ERROR,
330  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
331  errmsg("WITHIN GROUP is required for ordered-set aggregate %s",
332  NameListToString(funcname)),
333  parser_errposition(pstate, location)));
334  if (over)
335  ereport(ERROR,
336  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
337  errmsg("OVER is not supported for ordered-set aggregate %s",
338  NameListToString(funcname)),
339  parser_errposition(pstate, location)));
340  /* gram.y rejects DISTINCT + WITHIN GROUP */
341  Assert(!agg_distinct);
342  /* gram.y rejects VARIADIC + WITHIN GROUP */
343  Assert(!func_variadic);
344 
345  /*
346  * Since func_get_detail was working with an undifferentiated list
347  * of arguments, it might have selected an aggregate that doesn't
348  * really match because it requires a different division of direct
349  * and aggregated arguments. Check that the number of direct
350  * arguments is actually OK; if not, throw an "undefined function"
351  * error, similarly to the case where a misplaced ORDER BY is used
352  * in a regular aggregate call.
353  */
354  numAggregatedArgs = list_length(agg_order);
355  numDirectArgs = nargs - numAggregatedArgs;
356  Assert(numDirectArgs >= 0);
357 
358  if (!OidIsValid(vatype))
359  {
360  /* Test is simple if aggregate isn't variadic */
361  if (numDirectArgs != catDirectArgs)
362  ereport(ERROR,
363  (errcode(ERRCODE_UNDEFINED_FUNCTION),
364  errmsg("function %s does not exist",
365  func_signature_string(funcname, nargs,
366  argnames,
367  actual_arg_types)),
368  errhint("There is an ordered-set aggregate %s, but it requires %d direct arguments, not %d.",
369  NameListToString(funcname),
370  catDirectArgs, numDirectArgs),
371  parser_errposition(pstate, location)));
372  }
373  else
374  {
375  /*
376  * If it's variadic, we have two cases depending on whether
377  * the agg was "... ORDER BY VARIADIC" or "..., VARIADIC ORDER
378  * BY VARIADIC". It's the latter if catDirectArgs equals
379  * pronargs; to save a catalog lookup, we reverse-engineer
380  * pronargs from the info we got from func_get_detail.
381  */
382  int pronargs;
383 
384  pronargs = nargs;
385  if (nvargs > 1)
386  pronargs -= nvargs - 1;
387  if (catDirectArgs < pronargs)
388  {
389  /* VARIADIC isn't part of direct args, so still easy */
390  if (numDirectArgs != catDirectArgs)
391  ereport(ERROR,
392  (errcode(ERRCODE_UNDEFINED_FUNCTION),
393  errmsg("function %s does not exist",
394  func_signature_string(funcname, nargs,
395  argnames,
396  actual_arg_types)),
397  errhint("There is an ordered-set aggregate %s, but it requires %d direct arguments, not %d.",
398  NameListToString(funcname),
399  catDirectArgs, numDirectArgs),
400  parser_errposition(pstate, location)));
401  }
402  else
403  {
404  /*
405  * Both direct and aggregated args were declared variadic.
406  * For a standard ordered-set aggregate, it's okay as long
407  * as there aren't too few direct args. For a
408  * hypothetical-set aggregate, we assume that the
409  * hypothetical arguments are those that matched the
410  * variadic parameter; there must be just as many of them
411  * as there are aggregated arguments.
412  */
413  if (aggkind == AGGKIND_HYPOTHETICAL)
414  {
415  if (nvargs != 2 * numAggregatedArgs)
416  ereport(ERROR,
417  (errcode(ERRCODE_UNDEFINED_FUNCTION),
418  errmsg("function %s does not exist",
419  func_signature_string(funcname, nargs,
420  argnames,
421  actual_arg_types)),
422  errhint("To use the hypothetical-set aggregate %s, the number of hypothetical direct arguments (here %d) must match the number of ordering columns (here %d).",
423  NameListToString(funcname),
424  nvargs - numAggregatedArgs, numAggregatedArgs),
425  parser_errposition(pstate, location)));
426  }
427  else
428  {
429  if (nvargs <= numAggregatedArgs)
430  ereport(ERROR,
431  (errcode(ERRCODE_UNDEFINED_FUNCTION),
432  errmsg("function %s does not exist",
433  func_signature_string(funcname, nargs,
434  argnames,
435  actual_arg_types)),
436  errhint("There is an ordered-set aggregate %s, but it requires at least %d direct arguments.",
437  NameListToString(funcname),
438  catDirectArgs),
439  parser_errposition(pstate, location)));
440  }
441  }
442  }
443 
444  /* Check type matching of hypothetical arguments */
445  if (aggkind == AGGKIND_HYPOTHETICAL)
446  unify_hypothetical_args(pstate, fargs, numAggregatedArgs,
447  actual_arg_types, declared_arg_types);
448  }
449  else
450  {
451  /* Normal aggregate, so it can't have WITHIN GROUP */
452  if (agg_within_group)
453  ereport(ERROR,
454  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
455  errmsg("%s is not an ordered-set aggregate, so it cannot have WITHIN GROUP",
456  NameListToString(funcname)),
457  parser_errposition(pstate, location)));
458  }
459  }
460  else if (fdresult == FUNCDETAIL_WINDOWFUNC)
461  {
462  /*
463  * True window functions must be called with a window definition.
464  */
465  if (!over)
466  ereport(ERROR,
467  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
468  errmsg("window function %s requires an OVER clause",
469  NameListToString(funcname)),
470  parser_errposition(pstate, location)));
471  /* And, per spec, WITHIN GROUP isn't allowed */
472  if (agg_within_group)
473  ereport(ERROR,
474  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
475  errmsg("window function %s cannot have WITHIN GROUP",
476  NameListToString(funcname)),
477  parser_errposition(pstate, location)));
478  }
479  else
480  {
481  /*
482  * Oops. Time to die.
483  *
484  * If we are dealing with the attribute notation rel.function, let the
485  * caller handle failure.
486  */
487  if (is_column)
488  return NULL;
489 
490  /*
491  * Else generate a detailed complaint for a function
492  */
493  if (fdresult == FUNCDETAIL_MULTIPLE)
494  ereport(ERROR,
495  (errcode(ERRCODE_AMBIGUOUS_FUNCTION),
496  errmsg("function %s is not unique",
497  func_signature_string(funcname, nargs, argnames,
498  actual_arg_types)),
499  errhint("Could not choose a best candidate function. "
500  "You might need to add explicit type casts."),
501  parser_errposition(pstate, location)));
502  else if (list_length(agg_order) > 1 && !agg_within_group)
503  {
504  /* It's agg(x, ORDER BY y,z) ... perhaps misplaced ORDER BY */
505  ereport(ERROR,
506  (errcode(ERRCODE_UNDEFINED_FUNCTION),
507  errmsg("function %s does not exist",
508  func_signature_string(funcname, nargs, argnames,
509  actual_arg_types)),
510  errhint("No aggregate function matches the given name and argument types. "
511  "Perhaps you misplaced ORDER BY; ORDER BY must appear "
512  "after all regular arguments of the aggregate."),
513  parser_errposition(pstate, location)));
514  }
515  else
516  ereport(ERROR,
517  (errcode(ERRCODE_UNDEFINED_FUNCTION),
518  errmsg("function %s does not exist",
519  func_signature_string(funcname, nargs, argnames,
520  actual_arg_types)),
521  errhint("No function matches the given name and argument types. "
522  "You might need to add explicit type casts."),
523  parser_errposition(pstate, location)));
524  }
525 
526  /*
527  * If there are default arguments, we have to include their types in
528  * actual_arg_types for the purpose of checking generic type consistency.
529  * However, we do NOT put them into the generated parse node, because
530  * their actual values might change before the query gets run. The
531  * planner has to insert the up-to-date values at plan time.
532  */
533  nargsplusdefs = nargs;
534  foreach(l, argdefaults)
535  {
536  Node *expr = (Node *) lfirst(l);
537 
538  /* probably shouldn't happen ... */
539  if (nargsplusdefs >= FUNC_MAX_ARGS)
540  ereport(ERROR,
541  (errcode(ERRCODE_TOO_MANY_ARGUMENTS),
542  errmsg_plural("cannot pass more than %d argument to a function",
543  "cannot pass more than %d arguments to a function",
545  FUNC_MAX_ARGS),
546  parser_errposition(pstate, location)));
547 
548  actual_arg_types[nargsplusdefs++] = exprType(expr);
549  }
550 
551  /*
552  * enforce consistency with polymorphic argument and return types,
553  * possibly adjusting return type or declared_arg_types (which will be
554  * used as the cast destination by make_fn_arguments)
555  */
556  rettype = enforce_generic_type_consistency(actual_arg_types,
557  declared_arg_types,
558  nargsplusdefs,
559  rettype,
560  false);
561 
562  /* perform the necessary typecasting of arguments */
563  make_fn_arguments(pstate, fargs, actual_arg_types, declared_arg_types);
564 
565  /*
566  * If the function isn't actually variadic, forget any VARIADIC decoration
567  * on the call. (Perhaps we should throw an error instead, but
568  * historically we've allowed people to write that.)
569  */
570  if (!OidIsValid(vatype))
571  {
572  Assert(nvargs == 0);
573  func_variadic = false;
574  }
575 
576  /*
577  * If it's a variadic function call, transform the last nvargs arguments
578  * into an array --- unless it's an "any" variadic.
579  */
580  if (nvargs > 0 && vatype != ANYOID)
581  {
582  ArrayExpr *newa = makeNode(ArrayExpr);
583  int non_var_args = nargs - nvargs;
584  List *vargs;
585 
586  Assert(non_var_args >= 0);
587  vargs = list_copy_tail(fargs, non_var_args);
588  fargs = list_truncate(fargs, non_var_args);
589 
590  newa->elements = vargs;
591  /* assume all the variadic arguments were coerced to the same type */
592  newa->element_typeid = exprType((Node *) linitial(vargs));
594  if (!OidIsValid(newa->array_typeid))
595  ereport(ERROR,
596  (errcode(ERRCODE_UNDEFINED_OBJECT),
597  errmsg("could not find array type for data type %s",
599  parser_errposition(pstate, exprLocation((Node *) vargs))));
600  /* array_collid will be set by parse_collate.c */
601  newa->multidims = false;
602  newa->location = exprLocation((Node *) vargs);
603 
604  fargs = lappend(fargs, newa);
605 
606  /* We could not have had VARIADIC marking before ... */
607  Assert(!func_variadic);
608  /* ... but now, it's a VARIADIC call */
609  func_variadic = true;
610  }
611 
612  /*
613  * If an "any" variadic is called with explicit VARIADIC marking, insist
614  * that the variadic parameter be of some array type.
615  */
616  if (nargs > 0 && vatype == ANYOID && func_variadic)
617  {
618  Oid va_arr_typid = actual_arg_types[nargs - 1];
619 
620  if (!OidIsValid(get_base_element_type(va_arr_typid)))
621  ereport(ERROR,
622  (errcode(ERRCODE_DATATYPE_MISMATCH),
623  errmsg("VARIADIC argument must be an array"),
624  parser_errposition(pstate,
625  exprLocation((Node *) llast(fargs)))));
626  }
627 
628  /* build the appropriate output structure */
629  if (fdresult == FUNCDETAIL_NORMAL)
630  {
631  FuncExpr *funcexpr = makeNode(FuncExpr);
632 
633  funcexpr->funcid = funcid;
634  funcexpr->funcresulttype = rettype;
635  funcexpr->funcretset = retset;
636  funcexpr->funcvariadic = func_variadic;
637  funcexpr->funcformat = COERCE_EXPLICIT_CALL;
638  /* funccollid and inputcollid will be set by parse_collate.c */
639  funcexpr->args = fargs;
640  funcexpr->location = location;
641 
642  retval = (Node *) funcexpr;
643  }
644  else if (fdresult == FUNCDETAIL_AGGREGATE && !over)
645  {
646  /* aggregate function */
647  Aggref *aggref = makeNode(Aggref);
648 
649  aggref->aggfnoid = funcid;
650  /* default the outputtype to be the same as aggtype */
651  aggref->aggtype = aggref->aggoutputtype = rettype;
652  /* aggcollid and inputcollid will be set by parse_collate.c */
653  /* aggdirectargs and args will be set by transformAggregateCall */
654  /* aggorder and aggdistinct will be set by transformAggregateCall */
655  aggref->aggfilter = agg_filter;
656  aggref->aggstar = agg_star;
657  aggref->aggvariadic = func_variadic;
658  aggref->aggkind = aggkind;
659  /* agglevelsup will be set by transformAggregateCall */
660  aggref->location = location;
661 
662  /*
663  * Reject attempt to call a parameterless aggregate without (*)
664  * syntax. This is mere pedantry but some folks insisted ...
665  */
666  if (fargs == NIL && !agg_star && !agg_within_group)
667  ereport(ERROR,
668  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
669  errmsg("%s(*) must be used to call a parameterless aggregate function",
670  NameListToString(funcname)),
671  parser_errposition(pstate, location)));
672 
673  if (retset)
674  ereport(ERROR,
675  (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
676  errmsg("aggregates cannot return sets"),
677  parser_errposition(pstate, location)));
678 
679  /*
680  * We might want to support named arguments later, but disallow it for
681  * now. We'd need to figure out the parsed representation (should the
682  * NamedArgExprs go above or below the TargetEntry nodes?) and then
683  * teach the planner to reorder the list properly. Or maybe we could
684  * make transformAggregateCall do that? However, if you'd also like
685  * to allow default arguments for aggregates, we'd need to do it in
686  * planning to avoid semantic problems.
687  */
688  if (argnames != NIL)
689  ereport(ERROR,
690  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
691  errmsg("aggregates cannot use named arguments"),
692  parser_errposition(pstate, location)));
693 
694  /* parse_agg.c does additional aggregate-specific processing */
695  transformAggregateCall(pstate, aggref, fargs, agg_order, agg_distinct);
696 
697  retval = (Node *) aggref;
698  }
699  else
700  {
701  /* window function */
702  WindowFunc *wfunc = makeNode(WindowFunc);
703 
704  Assert(over); /* lack of this was checked above */
705  Assert(!agg_within_group); /* also checked above */
706 
707  wfunc->winfnoid = funcid;
708  wfunc->wintype = rettype;
709  /* wincollid and inputcollid will be set by parse_collate.c */
710  wfunc->args = fargs;
711  /* winref will be set by transformWindowFuncCall */
712  wfunc->winstar = agg_star;
713  wfunc->winagg = (fdresult == FUNCDETAIL_AGGREGATE);
714  wfunc->aggfilter = agg_filter;
715  wfunc->location = location;
716 
717  /*
718  * agg_star is allowed for aggregate functions but distinct isn't
719  */
720  if (agg_distinct)
721  ereport(ERROR,
722  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
723  errmsg("DISTINCT is not implemented for window functions"),
724  parser_errposition(pstate, location)));
725 
726  /*
727  * Reject attempt to call a parameterless aggregate without (*)
728  * syntax. This is mere pedantry but some folks insisted ...
729  */
730  if (wfunc->winagg && fargs == NIL && !agg_star)
731  ereport(ERROR,
732  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
733  errmsg("%s(*) must be used to call a parameterless aggregate function",
734  NameListToString(funcname)),
735  parser_errposition(pstate, location)));
736 
737  /*
738  * ordered aggs not allowed in windows yet
739  */
740  if (agg_order != NIL)
741  ereport(ERROR,
742  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
743  errmsg("aggregate ORDER BY is not implemented for window functions"),
744  parser_errposition(pstate, location)));
745 
746  /*
747  * FILTER is not yet supported with true window functions
748  */
749  if (!wfunc->winagg && agg_filter)
750  ereport(ERROR,
751  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
752  errmsg("FILTER is not implemented for non-aggregate window functions"),
753  parser_errposition(pstate, location)));
754 
755  if (retset)
756  ereport(ERROR,
757  (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
758  errmsg("window functions cannot return sets"),
759  parser_errposition(pstate, location)));
760 
761  /* parse_agg.c does additional window-func-specific processing */
762  transformWindowFuncCall(pstate, wfunc, over);
763 
764  retval = (Node *) wfunc;
765  }
766 
767  return retval;
768 }
769 
770 
771 /* func_match_argtypes()
772  *
773  * Given a list of candidate functions (having the right name and number
774  * of arguments) and an array of input datatype OIDs, produce a shortlist of
775  * those candidates that actually accept the input datatypes (either exactly
776  * or by coercion), and return the number of such candidates.
777  *
778  * Note that can_coerce_type will assume that UNKNOWN inputs are coercible to
779  * anything, so candidates will not be eliminated on that basis.
780  *
781  * NB: okay to modify input list structure, as long as we find at least
782  * one match. If no match at all, the list must remain unmodified.
783  */
784 int
786  Oid *input_typeids,
787  FuncCandidateList raw_candidates,
788  FuncCandidateList *candidates) /* return value */
789 {
790  FuncCandidateList current_candidate;
791  FuncCandidateList next_candidate;
792  int ncandidates = 0;
793 
794  *candidates = NULL;
795 
796  for (current_candidate = raw_candidates;
797  current_candidate != NULL;
798  current_candidate = next_candidate)
799  {
800  next_candidate = current_candidate->next;
801  if (can_coerce_type(nargs, input_typeids, current_candidate->args,
803  {
804  current_candidate->next = *candidates;
805  *candidates = current_candidate;
806  ncandidates++;
807  }
808  }
809 
810  return ncandidates;
811 } /* func_match_argtypes() */
812 
813 
814 /* func_select_candidate()
815  * Given the input argtype array and more than one candidate
816  * for the function, attempt to resolve the conflict.
817  *
818  * Returns the selected candidate if the conflict can be resolved,
819  * otherwise returns NULL.
820  *
821  * Note that the caller has already determined that there is no candidate
822  * exactly matching the input argtypes, and has pruned away any "candidates"
823  * that aren't actually coercion-compatible with the input types.
824  *
825  * This is also used for resolving ambiguous operator references. Formerly
826  * parse_oper.c had its own, essentially duplicate code for the purpose.
827  * The following comments (formerly in parse_oper.c) are kept to record some
828  * of the history of these heuristics.
829  *
830  * OLD COMMENTS:
831  *
832  * This routine is new code, replacing binary_oper_select_candidate()
833  * which dates from v4.2/v1.0.x days. It tries very hard to match up
834  * operators with types, including allowing type coercions if necessary.
835  * The important thing is that the code do as much as possible,
836  * while _never_ doing the wrong thing, where "the wrong thing" would
837  * be returning an operator when other better choices are available,
838  * or returning an operator which is a non-intuitive possibility.
839  * - thomas 1998-05-21
840  *
841  * The comments below came from binary_oper_select_candidate(), and
842  * illustrate the issues and choices which are possible:
843  * - thomas 1998-05-20
844  *
845  * current wisdom holds that the default operator should be one in which
846  * both operands have the same type (there will only be one such
847  * operator)
848  *
849  * 7.27.93 - I have decided not to do this; it's too hard to justify, and
850  * it's easy enough to typecast explicitly - avi
851  * [the rest of this routine was commented out since then - ay]
852  *
853  * 6/23/95 - I don't complete agree with avi. In particular, casting
854  * floats is a pain for users. Whatever the rationale behind not doing
855  * this is, I need the following special case to work.
856  *
857  * In the WHERE clause of a query, if a float is specified without
858  * quotes, we treat it as float8. I added the float48* operators so
859  * that we can operate on float4 and float8. But now we have more than
860  * one matching operator if the right arg is unknown (eg. float
861  * specified with quotes). This break some stuff in the regression
862  * test where there are floats in quotes not properly casted. Below is
863  * the solution. In addition to requiring the operator operates on the
864  * same type for both operands [as in the code Avi originally
865  * commented out], we also require that the operators be equivalent in
866  * some sense. (see equivalentOpersAfterPromotion for details.)
867  * - ay 6/95
868  */
871  Oid *input_typeids,
872  FuncCandidateList candidates)
873 {
874  FuncCandidateList current_candidate,
875  first_candidate,
876  last_candidate;
877  Oid *current_typeids;
878  Oid current_type;
879  int i;
880  int ncandidates;
881  int nbestMatch,
882  nmatch,
883  nunknowns;
884  Oid input_base_typeids[FUNC_MAX_ARGS];
885  TYPCATEGORY slot_category[FUNC_MAX_ARGS],
886  current_category;
887  bool current_is_preferred;
888  bool slot_has_preferred_type[FUNC_MAX_ARGS];
889  bool resolved_unknowns;
890 
891  /* protect local fixed-size arrays */
892  if (nargs > FUNC_MAX_ARGS)
893  ereport(ERROR,
894  (errcode(ERRCODE_TOO_MANY_ARGUMENTS),
895  errmsg_plural("cannot pass more than %d argument to a function",
896  "cannot pass more than %d arguments to a function",
898  FUNC_MAX_ARGS)));
899 
900  /*
901  * If any input types are domains, reduce them to their base types. This
902  * ensures that we will consider functions on the base type to be "exact
903  * matches" in the exact-match heuristic; it also makes it possible to do
904  * something useful with the type-category heuristics. Note that this
905  * makes it difficult, but not impossible, to use functions declared to
906  * take a domain as an input datatype. Such a function will be selected
907  * over the base-type function only if it is an exact match at all
908  * argument positions, and so was already chosen by our caller.
909  *
910  * While we're at it, count the number of unknown-type arguments for use
911  * later.
912  */
913  nunknowns = 0;
914  for (i = 0; i < nargs; i++)
915  {
916  if (input_typeids[i] != UNKNOWNOID)
917  input_base_typeids[i] = getBaseType(input_typeids[i]);
918  else
919  {
920  /* no need to call getBaseType on UNKNOWNOID */
921  input_base_typeids[i] = UNKNOWNOID;
922  nunknowns++;
923  }
924  }
925 
926  /*
927  * Run through all candidates and keep those with the most matches on
928  * exact types. Keep all candidates if none match.
929  */
930  ncandidates = 0;
931  nbestMatch = 0;
932  last_candidate = NULL;
933  for (current_candidate = candidates;
934  current_candidate != NULL;
935  current_candidate = current_candidate->next)
936  {
937  current_typeids = current_candidate->args;
938  nmatch = 0;
939  for (i = 0; i < nargs; i++)
940  {
941  if (input_base_typeids[i] != UNKNOWNOID &&
942  current_typeids[i] == input_base_typeids[i])
943  nmatch++;
944  }
945 
946  /* take this one as the best choice so far? */
947  if ((nmatch > nbestMatch) || (last_candidate == NULL))
948  {
949  nbestMatch = nmatch;
950  candidates = current_candidate;
951  last_candidate = current_candidate;
952  ncandidates = 1;
953  }
954  /* no worse than the last choice, so keep this one too? */
955  else if (nmatch == nbestMatch)
956  {
957  last_candidate->next = current_candidate;
958  last_candidate = current_candidate;
959  ncandidates++;
960  }
961  /* otherwise, don't bother keeping this one... */
962  }
963 
964  if (last_candidate) /* terminate rebuilt list */
965  last_candidate->next = NULL;
966 
967  if (ncandidates == 1)
968  return candidates;
969 
970  /*
971  * Still too many candidates? Now look for candidates which have either
972  * exact matches or preferred types at the args that will require
973  * coercion. (Restriction added in 7.4: preferred type must be of same
974  * category as input type; give no preference to cross-category
975  * conversions to preferred types.) Keep all candidates if none match.
976  */
977  for (i = 0; i < nargs; i++) /* avoid multiple lookups */
978  slot_category[i] = TypeCategory(input_base_typeids[i]);
979  ncandidates = 0;
980  nbestMatch = 0;
981  last_candidate = NULL;
982  for (current_candidate = candidates;
983  current_candidate != NULL;
984  current_candidate = current_candidate->next)
985  {
986  current_typeids = current_candidate->args;
987  nmatch = 0;
988  for (i = 0; i < nargs; i++)
989  {
990  if (input_base_typeids[i] != UNKNOWNOID)
991  {
992  if (current_typeids[i] == input_base_typeids[i] ||
993  IsPreferredType(slot_category[i], current_typeids[i]))
994  nmatch++;
995  }
996  }
997 
998  if ((nmatch > nbestMatch) || (last_candidate == NULL))
999  {
1000  nbestMatch = nmatch;
1001  candidates = current_candidate;
1002  last_candidate = current_candidate;
1003  ncandidates = 1;
1004  }
1005  else if (nmatch == nbestMatch)
1006  {
1007  last_candidate->next = current_candidate;
1008  last_candidate = current_candidate;
1009  ncandidates++;
1010  }
1011  }
1012 
1013  if (last_candidate) /* terminate rebuilt list */
1014  last_candidate->next = NULL;
1015 
1016  if (ncandidates == 1)
1017  return candidates;
1018 
1019  /*
1020  * Still too many candidates? Try assigning types for the unknown inputs.
1021  *
1022  * If there are no unknown inputs, we have no more heuristics that apply,
1023  * and must fail.
1024  */
1025  if (nunknowns == 0)
1026  return NULL; /* failed to select a best candidate */
1027 
1028  /*
1029  * The next step examines each unknown argument position to see if we can
1030  * determine a "type category" for it. If any candidate has an input
1031  * datatype of STRING category, use STRING category (this bias towards
1032  * STRING is appropriate since unknown-type literals look like strings).
1033  * Otherwise, if all the candidates agree on the type category of this
1034  * argument position, use that category. Otherwise, fail because we
1035  * cannot determine a category.
1036  *
1037  * If we are able to determine a type category, also notice whether any of
1038  * the candidates takes a preferred datatype within the category.
1039  *
1040  * Having completed this examination, remove candidates that accept the
1041  * wrong category at any unknown position. Also, if at least one
1042  * candidate accepted a preferred type at a position, remove candidates
1043  * that accept non-preferred types. If just one candidate remains, return
1044  * that one. However, if this rule turns out to reject all candidates,
1045  * keep them all instead.
1046  */
1047  resolved_unknowns = false;
1048  for (i = 0; i < nargs; i++)
1049  {
1050  bool have_conflict;
1051 
1052  if (input_base_typeids[i] != UNKNOWNOID)
1053  continue;
1054  resolved_unknowns = true; /* assume we can do it */
1055  slot_category[i] = TYPCATEGORY_INVALID;
1056  slot_has_preferred_type[i] = false;
1057  have_conflict = false;
1058  for (current_candidate = candidates;
1059  current_candidate != NULL;
1060  current_candidate = current_candidate->next)
1061  {
1062  current_typeids = current_candidate->args;
1063  current_type = current_typeids[i];
1064  get_type_category_preferred(current_type,
1065  &current_category,
1066  &current_is_preferred);
1067  if (slot_category[i] == TYPCATEGORY_INVALID)
1068  {
1069  /* first candidate */
1070  slot_category[i] = current_category;
1071  slot_has_preferred_type[i] = current_is_preferred;
1072  }
1073  else if (current_category == slot_category[i])
1074  {
1075  /* more candidates in same category */
1076  slot_has_preferred_type[i] |= current_is_preferred;
1077  }
1078  else
1079  {
1080  /* category conflict! */
1081  if (current_category == TYPCATEGORY_STRING)
1082  {
1083  /* STRING always wins if available */
1084  slot_category[i] = current_category;
1085  slot_has_preferred_type[i] = current_is_preferred;
1086  }
1087  else
1088  {
1089  /*
1090  * Remember conflict, but keep going (might find STRING)
1091  */
1092  have_conflict = true;
1093  }
1094  }
1095  }
1096  if (have_conflict && slot_category[i] != TYPCATEGORY_STRING)
1097  {
1098  /* Failed to resolve category conflict at this position */
1099  resolved_unknowns = false;
1100  break;
1101  }
1102  }
1103 
1104  if (resolved_unknowns)
1105  {
1106  /* Strip non-matching candidates */
1107  ncandidates = 0;
1108  first_candidate = candidates;
1109  last_candidate = NULL;
1110  for (current_candidate = candidates;
1111  current_candidate != NULL;
1112  current_candidate = current_candidate->next)
1113  {
1114  bool keepit = true;
1115 
1116  current_typeids = current_candidate->args;
1117  for (i = 0; i < nargs; i++)
1118  {
1119  if (input_base_typeids[i] != UNKNOWNOID)
1120  continue;
1121  current_type = current_typeids[i];
1122  get_type_category_preferred(current_type,
1123  &current_category,
1124  &current_is_preferred);
1125  if (current_category != slot_category[i])
1126  {
1127  keepit = false;
1128  break;
1129  }
1130  if (slot_has_preferred_type[i] && !current_is_preferred)
1131  {
1132  keepit = false;
1133  break;
1134  }
1135  }
1136  if (keepit)
1137  {
1138  /* keep this candidate */
1139  last_candidate = current_candidate;
1140  ncandidates++;
1141  }
1142  else
1143  {
1144  /* forget this candidate */
1145  if (last_candidate)
1146  last_candidate->next = current_candidate->next;
1147  else
1148  first_candidate = current_candidate->next;
1149  }
1150  }
1151 
1152  /* if we found any matches, restrict our attention to those */
1153  if (last_candidate)
1154  {
1155  candidates = first_candidate;
1156  /* terminate rebuilt list */
1157  last_candidate->next = NULL;
1158  }
1159 
1160  if (ncandidates == 1)
1161  return candidates;
1162  }
1163 
1164  /*
1165  * Last gasp: if there are both known- and unknown-type inputs, and all
1166  * the known types are the same, assume the unknown inputs are also that
1167  * type, and see if that gives us a unique match. If so, use that match.
1168  *
1169  * NOTE: for a binary operator with one unknown and one non-unknown input,
1170  * we already tried this heuristic in binary_oper_exact(). However, that
1171  * code only finds exact matches, whereas here we will handle matches that
1172  * involve coercion, polymorphic type resolution, etc.
1173  */
1174  if (nunknowns < nargs)
1175  {
1176  Oid known_type = UNKNOWNOID;
1177 
1178  for (i = 0; i < nargs; i++)
1179  {
1180  if (input_base_typeids[i] == UNKNOWNOID)
1181  continue;
1182  if (known_type == UNKNOWNOID) /* first known arg? */
1183  known_type = input_base_typeids[i];
1184  else if (known_type != input_base_typeids[i])
1185  {
1186  /* oops, not all match */
1187  known_type = UNKNOWNOID;
1188  break;
1189  }
1190  }
1191 
1192  if (known_type != UNKNOWNOID)
1193  {
1194  /* okay, just one known type, apply the heuristic */
1195  for (i = 0; i < nargs; i++)
1196  input_base_typeids[i] = known_type;
1197  ncandidates = 0;
1198  last_candidate = NULL;
1199  for (current_candidate = candidates;
1200  current_candidate != NULL;
1201  current_candidate = current_candidate->next)
1202  {
1203  current_typeids = current_candidate->args;
1204  if (can_coerce_type(nargs, input_base_typeids, current_typeids,
1206  {
1207  if (++ncandidates > 1)
1208  break; /* not unique, give up */
1209  last_candidate = current_candidate;
1210  }
1211  }
1212  if (ncandidates == 1)
1213  {
1214  /* successfully identified a unique match */
1215  last_candidate->next = NULL;
1216  return last_candidate;
1217  }
1218  }
1219  }
1220 
1221  return NULL; /* failed to select a best candidate */
1222 } /* func_select_candidate() */
1223 
1224 
1225 /* func_get_detail()
1226  *
1227  * Find the named function in the system catalogs.
1228  *
1229  * Attempt to find the named function in the system catalogs with
1230  * arguments exactly as specified, so that the normal case (exact match)
1231  * is as quick as possible.
1232  *
1233  * If an exact match isn't found:
1234  * 1) check for possible interpretation as a type coercion request
1235  * 2) apply the ambiguous-function resolution rules
1236  *
1237  * Return values *funcid through *true_typeids receive info about the function.
1238  * If argdefaults isn't NULL, *argdefaults receives a list of any default
1239  * argument expressions that need to be added to the given arguments.
1240  *
1241  * When processing a named- or mixed-notation call (ie, fargnames isn't NIL),
1242  * the returned true_typeids and argdefaults are ordered according to the
1243  * call's argument ordering: first any positional arguments, then the named
1244  * arguments, then defaulted arguments (if needed and allowed by
1245  * expand_defaults). Some care is needed if this information is to be compared
1246  * to the function's pg_proc entry, but in practice the caller can usually
1247  * just work with the call's argument ordering.
1248  *
1249  * We rely primarily on fargnames/nargs/argtypes as the argument description.
1250  * The actual expression node list is passed in fargs so that we can check
1251  * for type coercion of a constant. Some callers pass fargs == NIL indicating
1252  * they don't need that check made. Note also that when fargnames isn't NIL,
1253  * the fargs list must be passed if the caller wants actual argument position
1254  * information to be returned into the NamedArgExpr nodes.
1255  */
1258  List *fargs,
1259  List *fargnames,
1260  int nargs,
1261  Oid *argtypes,
1262  bool expand_variadic,
1263  bool expand_defaults,
1264  Oid *funcid, /* return value */
1265  Oid *rettype, /* return value */
1266  bool *retset, /* return value */
1267  int *nvargs, /* return value */
1268  Oid *vatype, /* return value */
1269  Oid **true_typeids, /* return value */
1270  List **argdefaults) /* optional return value */
1271 {
1272  FuncCandidateList raw_candidates;
1273  FuncCandidateList best_candidate;
1274 
1275  /* Passing NULL for argtypes is no longer allowed */
1276  Assert(argtypes);
1277 
1278  /* initialize output arguments to silence compiler warnings */
1279  *funcid = InvalidOid;
1280  *rettype = InvalidOid;
1281  *retset = false;
1282  *nvargs = 0;
1283  *vatype = InvalidOid;
1284  *true_typeids = NULL;
1285  if (argdefaults)
1286  *argdefaults = NIL;
1287 
1288  /* Get list of possible candidates from namespace search */
1289  raw_candidates = FuncnameGetCandidates(funcname, nargs, fargnames,
1290  expand_variadic, expand_defaults,
1291  false);
1292 
1293  /*
1294  * Quickly check if there is an exact match to the input datatypes (there
1295  * can be only one)
1296  */
1297  for (best_candidate = raw_candidates;
1298  best_candidate != NULL;
1299  best_candidate = best_candidate->next)
1300  {
1301  if (memcmp(argtypes, best_candidate->args, nargs * sizeof(Oid)) == 0)
1302  break;
1303  }
1304 
1305  if (best_candidate == NULL)
1306  {
1307  /*
1308  * If we didn't find an exact match, next consider the possibility
1309  * that this is really a type-coercion request: a single-argument
1310  * function call where the function name is a type name. If so, and
1311  * if the coercion path is RELABELTYPE or COERCEVIAIO, then go ahead
1312  * and treat the "function call" as a coercion.
1313  *
1314  * This interpretation needs to be given higher priority than
1315  * interpretations involving a type coercion followed by a function
1316  * call, otherwise we can produce surprising results. For example, we
1317  * want "text(varchar)" to be interpreted as a simple coercion, not as
1318  * "text(name(varchar))" which the code below this point is entirely
1319  * capable of selecting.
1320  *
1321  * We also treat a coercion of a previously-unknown-type literal
1322  * constant to a specific type this way.
1323  *
1324  * The reason we reject COERCION_PATH_FUNC here is that we expect the
1325  * cast implementation function to be named after the target type.
1326  * Thus the function will be found by normal lookup if appropriate.
1327  *
1328  * The reason we reject COERCION_PATH_ARRAYCOERCE is mainly that you
1329  * can't write "foo[] (something)" as a function call. In theory
1330  * someone might want to invoke it as "_foo (something)" but we have
1331  * never supported that historically, so we can insist that people
1332  * write it as a normal cast instead.
1333  *
1334  * We also reject the specific case of COERCEVIAIO for a composite
1335  * source type and a string-category target type. This is a case that
1336  * find_coercion_pathway() allows by default, but experience has shown
1337  * that it's too commonly invoked by mistake. So, again, insist that
1338  * people use cast syntax if they want to do that.
1339  *
1340  * NB: it's important that this code does not exceed what coerce_type
1341  * can do, because the caller will try to apply coerce_type if we
1342  * return FUNCDETAIL_COERCION. If we return that result for something
1343  * coerce_type can't handle, we'll cause infinite recursion between
1344  * this module and coerce_type!
1345  */
1346  if (nargs == 1 && fargs != NIL && fargnames == NIL)
1347  {
1348  Oid targetType = FuncNameAsType(funcname);
1349 
1350  if (OidIsValid(targetType))
1351  {
1352  Oid sourceType = argtypes[0];
1353  Node *arg1 = linitial(fargs);
1354  bool iscoercion;
1355 
1356  if (sourceType == UNKNOWNOID && IsA(arg1, Const))
1357  {
1358  /* always treat typename('literal') as coercion */
1359  iscoercion = true;
1360  }
1361  else
1362  {
1363  CoercionPathType cpathtype;
1364  Oid cfuncid;
1365 
1366  cpathtype = find_coercion_pathway(targetType, sourceType,
1368  &cfuncid);
1369  switch (cpathtype)
1370  {
1372  iscoercion = true;
1373  break;
1375  if ((sourceType == RECORDOID ||
1376  ISCOMPLEX(sourceType)) &&
1377  TypeCategory(targetType) == TYPCATEGORY_STRING)
1378  iscoercion = false;
1379  else
1380  iscoercion = true;
1381  break;
1382  default:
1383  iscoercion = false;
1384  break;
1385  }
1386  }
1387 
1388  if (iscoercion)
1389  {
1390  /* Treat it as a type coercion */
1391  *funcid = InvalidOid;
1392  *rettype = targetType;
1393  *retset = false;
1394  *nvargs = 0;
1395  *vatype = InvalidOid;
1396  *true_typeids = argtypes;
1397  return FUNCDETAIL_COERCION;
1398  }
1399  }
1400  }
1401 
1402  /*
1403  * didn't find an exact match, so now try to match up candidates...
1404  */
1405  if (raw_candidates != NULL)
1406  {
1407  FuncCandidateList current_candidates;
1408  int ncandidates;
1409 
1410  ncandidates = func_match_argtypes(nargs,
1411  argtypes,
1412  raw_candidates,
1413  &current_candidates);
1414 
1415  /* one match only? then run with it... */
1416  if (ncandidates == 1)
1417  best_candidate = current_candidates;
1418 
1419  /*
1420  * multiple candidates? then better decide or throw an error...
1421  */
1422  else if (ncandidates > 1)
1423  {
1424  best_candidate = func_select_candidate(nargs,
1425  argtypes,
1426  current_candidates);
1427 
1428  /*
1429  * If we were able to choose a best candidate, we're done.
1430  * Otherwise, ambiguous function call.
1431  */
1432  if (!best_candidate)
1433  return FUNCDETAIL_MULTIPLE;
1434  }
1435  }
1436  }
1437 
1438  if (best_candidate)
1439  {
1440  HeapTuple ftup;
1441  Form_pg_proc pform;
1442  FuncDetailCode result;
1443 
1444  /*
1445  * If processing named args or expanding variadics or defaults, the
1446  * "best candidate" might represent multiple equivalently good
1447  * functions; treat this case as ambiguous.
1448  */
1449  if (!OidIsValid(best_candidate->oid))
1450  return FUNCDETAIL_MULTIPLE;
1451 
1452  /*
1453  * We disallow VARIADIC with named arguments unless the last argument
1454  * (the one with VARIADIC attached) actually matched the variadic
1455  * parameter. This is mere pedantry, really, but some folks insisted.
1456  */
1457  if (fargnames != NIL && !expand_variadic && nargs > 0 &&
1458  best_candidate->argnumbers[nargs - 1] != nargs - 1)
1459  return FUNCDETAIL_NOTFOUND;
1460 
1461  *funcid = best_candidate->oid;
1462  *nvargs = best_candidate->nvargs;
1463  *true_typeids = best_candidate->args;
1464 
1465  /*
1466  * If processing named args, return actual argument positions into
1467  * NamedArgExpr nodes in the fargs list. This is a bit ugly but not
1468  * worth the extra notation needed to do it differently.
1469  */
1470  if (best_candidate->argnumbers != NULL)
1471  {
1472  int i = 0;
1473  ListCell *lc;
1474 
1475  foreach(lc, fargs)
1476  {
1477  NamedArgExpr *na = (NamedArgExpr *) lfirst(lc);
1478 
1479  if (IsA(na, NamedArgExpr))
1480  na->argnumber = best_candidate->argnumbers[i];
1481  i++;
1482  }
1483  }
1484 
1485  ftup = SearchSysCache1(PROCOID,
1486  ObjectIdGetDatum(best_candidate->oid));
1487  if (!HeapTupleIsValid(ftup)) /* should not happen */
1488  elog(ERROR, "cache lookup failed for function %u",
1489  best_candidate->oid);
1490  pform = (Form_pg_proc) GETSTRUCT(ftup);
1491  *rettype = pform->prorettype;
1492  *retset = pform->proretset;
1493  *vatype = pform->provariadic;
1494  /* fetch default args if caller wants 'em */
1495  if (argdefaults && best_candidate->ndargs > 0)
1496  {
1497  Datum proargdefaults;
1498  bool isnull;
1499  char *str;
1500  List *defaults;
1501 
1502  /* shouldn't happen, FuncnameGetCandidates messed up */
1503  if (best_candidate->ndargs > pform->pronargdefaults)
1504  elog(ERROR, "not enough default arguments");
1505 
1506  proargdefaults = SysCacheGetAttr(PROCOID, ftup,
1508  &isnull);
1509  Assert(!isnull);
1510  str = TextDatumGetCString(proargdefaults);
1511  defaults = (List *) stringToNode(str);
1512  Assert(IsA(defaults, List));
1513  pfree(str);
1514 
1515  /* Delete any unused defaults from the returned list */
1516  if (best_candidate->argnumbers != NULL)
1517  {
1518  /*
1519  * This is a bit tricky in named notation, since the supplied
1520  * arguments could replace any subset of the defaults. We
1521  * work by making a bitmapset of the argnumbers of defaulted
1522  * arguments, then scanning the defaults list and selecting
1523  * the needed items. (This assumes that defaulted arguments
1524  * should be supplied in their positional order.)
1525  */
1526  Bitmapset *defargnumbers;
1527  int *firstdefarg;
1528  List *newdefaults;
1529  ListCell *lc;
1530  int i;
1531 
1532  defargnumbers = NULL;
1533  firstdefarg = &best_candidate->argnumbers[best_candidate->nargs - best_candidate->ndargs];
1534  for (i = 0; i < best_candidate->ndargs; i++)
1535  defargnumbers = bms_add_member(defargnumbers,
1536  firstdefarg[i]);
1537  newdefaults = NIL;
1538  i = pform->pronargs - pform->pronargdefaults;
1539  foreach(lc, defaults)
1540  {
1541  if (bms_is_member(i, defargnumbers))
1542  newdefaults = lappend(newdefaults, lfirst(lc));
1543  i++;
1544  }
1545  Assert(list_length(newdefaults) == best_candidate->ndargs);
1546  bms_free(defargnumbers);
1547  *argdefaults = newdefaults;
1548  }
1549  else
1550  {
1551  /*
1552  * Defaults for positional notation are lots easier; just
1553  * remove any unwanted ones from the front.
1554  */
1555  int ndelete;
1556 
1557  ndelete = list_length(defaults) - best_candidate->ndargs;
1558  while (ndelete-- > 0)
1559  defaults = list_delete_first(defaults);
1560  *argdefaults = defaults;
1561  }
1562  }
1563  if (pform->proisagg)
1564  result = FUNCDETAIL_AGGREGATE;
1565  else if (pform->proiswindow)
1566  result = FUNCDETAIL_WINDOWFUNC;
1567  else
1568  result = FUNCDETAIL_NORMAL;
1569  ReleaseSysCache(ftup);
1570  return result;
1571  }
1572 
1573  return FUNCDETAIL_NOTFOUND;
1574 }
1575 
1576 
1577 /*
1578  * unify_hypothetical_args()
1579  *
1580  * Ensure that each hypothetical direct argument of a hypothetical-set
1581  * aggregate has the same type as the corresponding aggregated argument.
1582  * Modify the expressions in the fargs list, if necessary, and update
1583  * actual_arg_types[].
1584  *
1585  * If the agg declared its args non-ANY (even ANYELEMENT), we need only a
1586  * sanity check that the declared types match; make_fn_arguments will coerce
1587  * the actual arguments to match the declared ones. But if the declaration
1588  * is ANY, nothing will happen in make_fn_arguments, so we need to fix any
1589  * mismatch here. We use the same type resolution logic as UNION etc.
1590  */
1591 static void
1593  List *fargs,
1594  int numAggregatedArgs,
1595  Oid *actual_arg_types,
1596  Oid *declared_arg_types)
1597 {
1599  int numDirectArgs,
1600  numNonHypotheticalArgs;
1601  int i;
1602  ListCell *lc;
1603 
1604  numDirectArgs = list_length(fargs) - numAggregatedArgs;
1605  numNonHypotheticalArgs = numDirectArgs - numAggregatedArgs;
1606  /* safety check (should only trigger with a misdeclared agg) */
1607  if (numNonHypotheticalArgs < 0)
1608  elog(ERROR, "incorrect number of arguments to hypothetical-set aggregate");
1609 
1610  /* Deconstruct fargs into an array for ease of subscripting */
1611  i = 0;
1612  foreach(lc, fargs)
1613  {
1614  args[i++] = (Node *) lfirst(lc);
1615  }
1616 
1617  /* Check each hypothetical arg and corresponding aggregated arg */
1618  for (i = numNonHypotheticalArgs; i < numDirectArgs; i++)
1619  {
1620  int aargpos = numDirectArgs + (i - numNonHypotheticalArgs);
1621  Oid commontype;
1622 
1623  /* A mismatch means AggregateCreate didn't check properly ... */
1624  if (declared_arg_types[i] != declared_arg_types[aargpos])
1625  elog(ERROR, "hypothetical-set aggregate has inconsistent declared argument types");
1626 
1627  /* No need to unify if make_fn_arguments will coerce */
1628  if (declared_arg_types[i] != ANYOID)
1629  continue;
1630 
1631  /*
1632  * Select common type, giving preference to the aggregated argument's
1633  * type (we'd rather coerce the direct argument once than coerce all
1634  * the aggregated values).
1635  */
1636  commontype = select_common_type(pstate,
1637  list_make2(args[aargpos], args[i]),
1638  "WITHIN GROUP",
1639  NULL);
1640 
1641  /*
1642  * Perform the coercions. We don't need to worry about NamedArgExprs
1643  * here because they aren't supported with aggregates.
1644  */
1645  args[i] = coerce_type(pstate,
1646  args[i],
1647  actual_arg_types[i],
1648  commontype, -1,
1651  -1);
1652  actual_arg_types[i] = commontype;
1653  args[aargpos] = coerce_type(pstate,
1654  args[aargpos],
1655  actual_arg_types[aargpos],
1656  commontype, -1,
1659  -1);
1660  actual_arg_types[aargpos] = commontype;
1661  }
1662 
1663  /* Reconstruct fargs from array */
1664  i = 0;
1665  foreach(lc, fargs)
1666  {
1667  lfirst(lc) = args[i++];
1668  }
1669 }
1670 
1671 
1672 /*
1673  * make_fn_arguments()
1674  *
1675  * Given the actual argument expressions for a function, and the desired
1676  * input types for the function, add any necessary typecasting to the
1677  * expression tree. Caller should already have verified that casting is
1678  * allowed.
1679  *
1680  * Caution: given argument list is modified in-place.
1681  *
1682  * As with coerce_type, pstate may be NULL if no special unknown-Param
1683  * processing is wanted.
1684  */
1685 void
1687  List *fargs,
1688  Oid *actual_arg_types,
1689  Oid *declared_arg_types)
1690 {
1691  ListCell *current_fargs;
1692  int i = 0;
1693 
1694  foreach(current_fargs, fargs)
1695  {
1696  /* types don't match? then force coercion using a function call... */
1697  if (actual_arg_types[i] != declared_arg_types[i])
1698  {
1699  Node *node = (Node *) lfirst(current_fargs);
1700 
1701  /*
1702  * If arg is a NamedArgExpr, coerce its input expr instead --- we
1703  * want the NamedArgExpr to stay at the top level of the list.
1704  */
1705  if (IsA(node, NamedArgExpr))
1706  {
1707  NamedArgExpr *na = (NamedArgExpr *) node;
1708 
1709  node = coerce_type(pstate,
1710  (Node *) na->arg,
1711  actual_arg_types[i],
1712  declared_arg_types[i], -1,
1715  -1);
1716  na->arg = (Expr *) node;
1717  }
1718  else
1719  {
1720  node = coerce_type(pstate,
1721  node,
1722  actual_arg_types[i],
1723  declared_arg_types[i], -1,
1726  -1);
1727  lfirst(current_fargs) = node;
1728  }
1729  }
1730  i++;
1731  }
1732 }
1733 
1734 /*
1735  * FuncNameAsType -
1736  * convenience routine to see if a function name matches a type name
1737  *
1738  * Returns the OID of the matching type, or InvalidOid if none. We ignore
1739  * shell types and complex types.
1740  */
1741 static Oid
1743 {
1744  Oid result;
1745  Type typtup;
1746 
1747  typtup = LookupTypeName(NULL, makeTypeNameFromNameList(funcname), NULL, false);
1748  if (typtup == NULL)
1749  return InvalidOid;
1750 
1751  if (((Form_pg_type) GETSTRUCT(typtup))->typisdefined &&
1752  !OidIsValid(typeTypeRelid(typtup)))
1753  result = typeTypeId(typtup);
1754  else
1755  result = InvalidOid;
1756 
1757  ReleaseSysCache(typtup);
1758  return result;
1759 }
1760 
1761 /*
1762  * ParseComplexProjection -
1763  * handles function calls with a single argument that is of complex type.
1764  * If the function call is actually a column projection, return a suitably
1765  * transformed expression tree. If not, return NULL.
1766  */
1767 static Node *
1768 ParseComplexProjection(ParseState *pstate, char *funcname, Node *first_arg,
1769  int location)
1770 {
1771  TupleDesc tupdesc;
1772  int i;
1773 
1774  /*
1775  * Special case for whole-row Vars so that we can resolve (foo.*).bar even
1776  * when foo is a reference to a subselect, join, or RECORD function. A
1777  * bonus is that we avoid generating an unnecessary FieldSelect; our
1778  * result can omit the whole-row Var and just be a Var for the selected
1779  * field.
1780  *
1781  * This case could be handled by expandRecordVariable, but it's more
1782  * efficient to do it this way when possible.
1783  */
1784  if (IsA(first_arg, Var) &&
1785  ((Var *) first_arg)->varattno == InvalidAttrNumber)
1786  {
1787  RangeTblEntry *rte;
1788 
1789  rte = GetRTEByRangeTablePosn(pstate,
1790  ((Var *) first_arg)->varno,
1791  ((Var *) first_arg)->varlevelsup);
1792  /* Return a Var if funcname matches a column, else NULL */
1793  return scanRTEForColumn(pstate, rte, funcname, location, 0, NULL);
1794  }
1795 
1796  /*
1797  * Else do it the hard way with get_expr_result_type().
1798  *
1799  * If it's a Var of type RECORD, we have to work even harder: we have to
1800  * find what the Var refers to, and pass that to get_expr_result_type.
1801  * That task is handled by expandRecordVariable().
1802  */
1803  if (IsA(first_arg, Var) &&
1804  ((Var *) first_arg)->vartype == RECORDOID)
1805  tupdesc = expandRecordVariable(pstate, (Var *) first_arg, 0);
1806  else if (get_expr_result_type(first_arg, NULL, &tupdesc) != TYPEFUNC_COMPOSITE)
1807  return NULL; /* unresolvable RECORD type */
1808  Assert(tupdesc);
1809 
1810  for (i = 0; i < tupdesc->natts; i++)
1811  {
1812  Form_pg_attribute att = tupdesc->attrs[i];
1813 
1814  if (strcmp(funcname, NameStr(att->attname)) == 0 &&
1815  !att->attisdropped)
1816  {
1817  /* Success, so generate a FieldSelect expression */
1818  FieldSelect *fselect = makeNode(FieldSelect);
1819 
1820  fselect->arg = (Expr *) first_arg;
1821  fselect->fieldnum = i + 1;
1822  fselect->resulttype = att->atttypid;
1823  fselect->resulttypmod = att->atttypmod;
1824  /* save attribute's collation for parse_collate.c */
1825  fselect->resultcollid = att->attcollation;
1826  return (Node *) fselect;
1827  }
1828  }
1829 
1830  return NULL; /* funcname does not match any column */
1831 }
1832 
1833 /*
1834  * funcname_signature_string
1835  * Build a string representing a function name, including arg types.
1836  * The result is something like "foo(integer)".
1837  *
1838  * If argnames isn't NIL, it is a list of C strings representing the actual
1839  * arg names for the last N arguments. This must be considered part of the
1840  * function signature too, when dealing with named-notation function calls.
1841  *
1842  * This is typically used in the construction of function-not-found error
1843  * messages.
1844  */
1845 const char *
1846 funcname_signature_string(const char *funcname, int nargs,
1847  List *argnames, const Oid *argtypes)
1848 {
1849  StringInfoData argbuf;
1850  int numposargs;
1851  ListCell *lc;
1852  int i;
1853 
1854  initStringInfo(&argbuf);
1855 
1856  appendStringInfo(&argbuf, "%s(", funcname);
1857 
1858  numposargs = nargs - list_length(argnames);
1859  lc = list_head(argnames);
1860 
1861  for (i = 0; i < nargs; i++)
1862  {
1863  if (i)
1864  appendStringInfoString(&argbuf, ", ");
1865  if (i >= numposargs)
1866  {
1867  appendStringInfo(&argbuf, "%s => ", (char *) lfirst(lc));
1868  lc = lnext(lc);
1869  }
1870  appendStringInfoString(&argbuf, format_type_be(argtypes[i]));
1871  }
1872 
1873  appendStringInfoChar(&argbuf, ')');
1874 
1875  return argbuf.data; /* return palloc'd string buffer */
1876 }
1877 
1878 /*
1879  * func_signature_string
1880  * As above, but function name is passed as a qualified name list.
1881  */
1882 const char *
1883 func_signature_string(List *funcname, int nargs,
1884  List *argnames, const Oid *argtypes)
1885 {
1887  nargs, argnames, argtypes);
1888 }
1889 
1890 /*
1891  * LookupFuncName
1892  * Given a possibly-qualified function name and a set of argument types,
1893  * look up the function.
1894  *
1895  * If the function name is not schema-qualified, it is sought in the current
1896  * namespace search path.
1897  *
1898  * If the function is not found, we return InvalidOid if noError is true,
1899  * else raise an error.
1900  */
1901 Oid
1902 LookupFuncName(List *funcname, int nargs, const Oid *argtypes, bool noError)
1903 {
1904  FuncCandidateList clist;
1905 
1906  /* Passing NULL for argtypes is no longer allowed */
1907  Assert(argtypes);
1908 
1909  clist = FuncnameGetCandidates(funcname, nargs, NIL, false, false, noError);
1910 
1911  while (clist)
1912  {
1913  if (memcmp(argtypes, clist->args, nargs * sizeof(Oid)) == 0)
1914  return clist->oid;
1915  clist = clist->next;
1916  }
1917 
1918  if (!noError)
1919  ereport(ERROR,
1920  (errcode(ERRCODE_UNDEFINED_FUNCTION),
1921  errmsg("function %s does not exist",
1922  func_signature_string(funcname, nargs,
1923  NIL, argtypes))));
1924 
1925  return InvalidOid;
1926 }
1927 
1928 /*
1929  * LookupFuncNameTypeNames
1930  * Like LookupFuncName, but the argument types are specified by a
1931  * list of TypeName nodes.
1932  */
1933 Oid
1934 LookupFuncNameTypeNames(List *funcname, List *argtypes, bool noError)
1935 {
1936  Oid argoids[FUNC_MAX_ARGS];
1937  int argcount;
1938  int i;
1939  ListCell *args_item;
1940 
1941  argcount = list_length(argtypes);
1942  if (argcount > FUNC_MAX_ARGS)
1943  ereport(ERROR,
1944  (errcode(ERRCODE_TOO_MANY_ARGUMENTS),
1945  errmsg_plural("functions cannot have more than %d argument",
1946  "functions cannot have more than %d arguments",
1947  FUNC_MAX_ARGS,
1948  FUNC_MAX_ARGS)));
1949 
1950  args_item = list_head(argtypes);
1951  for (i = 0; i < argcount; i++)
1952  {
1953  TypeName *t = (TypeName *) lfirst(args_item);
1954 
1955  argoids[i] = LookupTypeNameOid(NULL, t, noError);
1956  args_item = lnext(args_item);
1957  }
1958 
1959  return LookupFuncName(funcname, argcount, argoids, noError);
1960 }
1961 
1962 /*
1963  * LookupAggNameTypeNames
1964  * Find an aggregate function given a name and list of TypeName nodes.
1965  *
1966  * This is almost like LookupFuncNameTypeNames, but the error messages refer
1967  * to aggregates rather than plain functions, and we verify that the found
1968  * function really is an aggregate.
1969  */
1970 Oid
1971 LookupAggNameTypeNames(List *aggname, List *argtypes, bool noError)
1972 {
1973  Oid argoids[FUNC_MAX_ARGS];
1974  int argcount;
1975  int i;
1976  ListCell *lc;
1977  Oid oid;
1978  HeapTuple ftup;
1979  Form_pg_proc pform;
1980 
1981  argcount = list_length(argtypes);
1982  if (argcount > FUNC_MAX_ARGS)
1983  ereport(ERROR,
1984  (errcode(ERRCODE_TOO_MANY_ARGUMENTS),
1985  errmsg_plural("functions cannot have more than %d argument",
1986  "functions cannot have more than %d arguments",
1987  FUNC_MAX_ARGS,
1988  FUNC_MAX_ARGS)));
1989 
1990  i = 0;
1991  foreach(lc, argtypes)
1992  {
1993  TypeName *t = (TypeName *) lfirst(lc);
1994 
1995  argoids[i] = LookupTypeNameOid(NULL, t, noError);
1996  i++;
1997  }
1998 
1999  oid = LookupFuncName(aggname, argcount, argoids, true);
2000 
2001  if (!OidIsValid(oid))
2002  {
2003  if (noError)
2004  return InvalidOid;
2005  if (argcount == 0)
2006  ereport(ERROR,
2007  (errcode(ERRCODE_UNDEFINED_FUNCTION),
2008  errmsg("aggregate %s(*) does not exist",
2009  NameListToString(aggname))));
2010  else
2011  ereport(ERROR,
2012  (errcode(ERRCODE_UNDEFINED_FUNCTION),
2013  errmsg("aggregate %s does not exist",
2014  func_signature_string(aggname, argcount,
2015  NIL, argoids))));
2016  }
2017 
2018  /* Make sure it's an aggregate */
2020  if (!HeapTupleIsValid(ftup)) /* should not happen */
2021  elog(ERROR, "cache lookup failed for function %u", oid);
2022  pform = (Form_pg_proc) GETSTRUCT(ftup);
2023 
2024  if (!pform->proisagg)
2025  {
2026  ReleaseSysCache(ftup);
2027  if (noError)
2028  return InvalidOid;
2029  /* we do not use the (*) notation for functions... */
2030  ereport(ERROR,
2031  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2032  errmsg("function %s is not an aggregate",
2033  func_signature_string(aggname, argcount,
2034  NIL, argoids))));
2035  }
2036 
2037  ReleaseSysCache(ftup);
2038 
2039  return oid;
2040 }
#define list_make2(x1, x2)
Definition: pg_list.h:134
Node * scanRTEForColumn(ParseState *pstate, RangeTblEntry *rte, char *colname, int location, int fuzzy_rte_penalty, FuzzyAttrMatchState *fuzzystate)
Type LookupTypeName(ParseState *pstate, const TypeName *typeName, int32 *typmod_p, bool missing_ok)
Definition: parse_type.c:57
Oid funcresulttype
Definition: primnodes.h:425
static void unify_hypothetical_args(ParseState *pstate, List *fargs, int numAggregatedArgs, Oid *actual_arg_types, Oid *declared_arg_types)
Definition: parse_func.c:1592
bool multidims
Definition: primnodes.h:929
#define NIL
Definition: pg_list.h:69
bool aggvariadic
Definition: primnodes.h:281
void * stringToNode(char *str)
Definition: read.c:38
#define IsA(nodeptr, _type_)
Definition: nodes.h:542
int errhint(const char *fmt,...)
Definition: elog.c:987
#define GETSTRUCT(TUP)
Definition: htup_details.h:631
int exprLocation(const Node *expr)
Definition: nodeFuncs.c:1195
List * args
Definition: primnodes.h:335
List * args
Definition: primnodes.h:432
Oid LookupAggNameTypeNames(List *aggname, List *argtypes, bool noError)
Definition: parse_func.c:1971
int func_match_argtypes(int nargs, Oid *input_typeids, FuncCandidateList raw_candidates, FuncCandidateList *candidates)
Definition: parse_func.c:785
Oid resulttype
Definition: primnodes.h:717
int errmsg_plural(const char *fmt_singular, const char *fmt_plural, unsigned long n,...)
Definition: elog.c:850
static Oid FuncNameAsType(List *funcname)
Definition: parse_func.c:1742
Oid get_array_type(Oid typid)
Definition: lsyscache.c:2480
Node * agg_filter
Definition: parsenodes.h:334
Form_pg_attribute * attrs
Definition: tupdesc.h:74
#define llast(l)
Definition: pg_list.h:126
List * list_truncate(List *list, int new_size)
Definition: list.c:350
Node * coerce_type(ParseState *pstate, Node *node, Oid inputTypeId, Oid targetTypeId, int32 targetTypeMod, CoercionContext ccontext, CoercionForm cformat, int location)
Definition: parse_coerce.c:156
Definition: nodes.h:491
#define strVal(v)
Definition: value.h:54
int errcode(int sqlerrcode)
Definition: elog.c:575
Oid array_typeid
Definition: primnodes.h:925
char * format_type_be(Oid type_oid)
Definition: format_type.c:94
Expr * arg
Definition: primnodes.h:715
bool funcretset
Definition: primnodes.h:426
Node * ParseFuncOrColumn(ParseState *pstate, List *funcname, List *fargs, FuncCall *fn, int location)
Definition: parse_func.c:68
FormData_pg_type * Form_pg_type
Definition: pg_type.h:233
List * list_delete_ptr(List *list, void *datum)
Definition: list.c:590
void make_fn_arguments(ParseState *pstate, List *fargs, Oid *actual_arg_types, Oid *declared_arg_types)
Definition: parse_func.c:1686
List * list_copy_tail(const List *oldlist, int nskip)
Definition: list.c:1203
bool aggstar
Definition: primnodes.h:280
unsigned int Oid
Definition: postgres_ext.h:31
Definition: primnodes.h:148
TypeFuncClass get_expr_result_type(Node *expr, Oid *resultTypeId, TupleDesc *resultTupleDesc)
Definition: funcapi.c:228
#define OidIsValid(objectId)
Definition: c.h:530
int natts
Definition: tupdesc.h:73
List * agg_order
Definition: parsenodes.h:333
bool IsPreferredType(TYPCATEGORY category, Oid type)
CoercionPathType
Definition: parse_coerce.h:24
#define SearchSysCache1(cacheId, key1)
Definition: syscache.h:141
#define FUNC_MAX_ARGS
#define AGGKIND_IS_ORDERED_SET(kind)
Definition: pg_aggregate.h:132
char TYPCATEGORY
Definition: parse_coerce.h:21
CoercionForm funcformat
Definition: primnodes.h:429
Oid args[FLEXIBLE_ARRAY_MEMBER]
Definition: namespace.h:37
void pfree(void *pointer)
Definition: mcxt.c:995
void cancel_parser_errposition_callback(ParseCallbackState *pcbstate)
Definition: parse_node.c:158
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:78
#define linitial(l)
Definition: pg_list.h:110
#define VOIDOID
Definition: pg_type.h:678
Oid funcid
Definition: primnodes.h:424
#define ObjectIdGetDatum(X)
Definition: postgres.h:515
#define ERROR
Definition: elog.h:43
#define TYPCATEGORY_INVALID
Definition: pg_type.h:715
struct WindowDef * over
Definition: parsenodes.h:339
FuncCandidateList FuncnameGetCandidates(List *names, int nargs, List *argnames, bool expand_variadic, bool expand_defaults, bool missing_ok)
Definition: namespace.c:917
Oid enforce_generic_type_consistency(Oid *actual_arg_types, Oid *declared_arg_types, int nargs, Oid rettype, bool allow_poly)
int location
Definition: primnodes.h:287
Oid resultcollid
Definition: primnodes.h:720
void appendStringInfoString(StringInfo str, const char *s)
Definition: stringinfo.c:157
#define Anum_pg_proc_proargdefaults
Definition: pg_proc.h:113
#define ANYOID
Definition: pg_type.h:674
FuncDetailCode
Definition: parse_func.h:22
char * name
Definition: primnodes.h:454
static ListCell * list_head(const List *l)
Definition: pg_list.h:77
const char * funcname_signature_string(const char *funcname, int nargs, List *argnames, const Oid *argtypes)
Definition: parse_func.c:1846
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:184
Oid LookupFuncNameTypeNames(List *funcname, List *argtypes, bool noError)
Definition: parse_func.c:1934
Oid winfnoid
Definition: primnodes.h:331
#define RECORDOID
Definition: pg_type.h:668
List * elements
Definition: primnodes.h:928
TupleDesc expandRecordVariable(ParseState *pstate, Var *var, int levelsup)
struct _FuncCandidateList * next
Definition: namespace.h:30
Oid aggoutputtype
Definition: primnodes.h:272
#define lnext(lc)
Definition: pg_list.h:105
#define ereport(elevel, rest)
Definition: elog.h:122
void setup_parser_errposition_callback(ParseCallbackState *pcbstate, ParseState *pstate, int location)
Definition: parse_node.c:142
const char * func_signature_string(List *funcname, int nargs, List *argnames, const Oid *argtypes)
Definition: parse_func.c:1883
List * lappend(List *list, void *datum)
Definition: list.c:128
void appendStringInfoChar(StringInfo str, char ch)
Definition: stringinfo.c:169
void initStringInfo(StringInfo str)
Definition: stringinfo.c:46
void transformWindowFuncCall(ParseState *pstate, WindowFunc *wfunc, WindowDef *windef)
Definition: parse_agg.c:725
bool func_variadic
Definition: parsenodes.h:338
char * NameListToString(List *names)
Definition: namespace.c:2912
#define TextDatumGetCString(d)
Definition: builtins.h:807
int location
Definition: primnodes.h:930
uintptr_t Datum
Definition: postgres.h:374
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:990
Datum SysCacheGetAttr(int cacheId, HeapTuple tup, AttrNumber attributeNumber, bool *isNull)
Definition: syscache.c:1152
RangeTblEntry * GetRTEByRangeTablePosn(ParseState *pstate, int varno, int sublevels_up)
FormData_pg_proc * Form_pg_proc
Definition: pg_proc.h:83
#define InvalidOid
Definition: postgres_ext.h:36
TYPCATEGORY TypeCategory(Oid type)
Oid aggfnoid
Definition: primnodes.h:270
static void * fn(void *arg)
#define TYPCATEGORY_STRING
Definition: pg_type.h:726
void bms_free(Bitmapset *a)
Definition: bitmapset.c:200
#define makeNode(_type_)
Definition: nodes.h:539
Expr * arg
Definition: primnodes.h:453
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
int location
Definition: primnodes.h:340
#define NULL
Definition: c.h:226
#define Assert(condition)
Definition: c.h:667
#define lfirst(lc)
Definition: pg_list.h:106
Expr * aggfilter
Definition: primnodes.h:336
FormData_pg_aggregate * Form_pg_aggregate
Definition: pg_aggregate.h:89
Node * transformWhereClause(ParseState *pstate, Node *clause, ParseExprKind exprKind, const char *constructName)
#define ISCOMPLEX(typeid)
Definition: parse_type.h:53
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:41
static int list_length(const List *l)
Definition: pg_list.h:89
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:108
Expr * aggfilter
Definition: primnodes.h:279
Bitmapset * bms_add_member(Bitmapset *a, int x)
Definition: bitmapset.c:668
#define UNKNOWNOID
Definition: pg_type.h:423
FuncDetailCode func_get_detail(List *funcname, List *fargs, List *fargnames, int nargs, Oid *argtypes, bool expand_variadic, bool expand_defaults, Oid *funcid, Oid *rettype, bool *retset, int *nvargs, Oid *vatype, Oid **true_typeids, List **argdefaults)
Definition: parse_func.c:1257
#define InvalidAttrNumber
Definition: attnum.h:23
Oid element_typeid
Definition: primnodes.h:927
Oid wintype
Definition: primnodes.h:332
Oid LookupFuncName(List *funcname, int nargs, const Oid *argtypes, bool noError)
Definition: parse_func.c:1902
Oid get_base_element_type(Oid typid)
Definition: lsyscache.c:2525
bool can_coerce_type(int nargs, Oid *input_typeids, Oid *target_typeids, CoercionContext ccontext)
Definition: parse_coerce.c:527
FuncCandidateList func_select_candidate(int nargs, Oid *input_typeids, FuncCandidateList candidates)
Definition: parse_func.c:870
int errmsg(const char *fmt,...)
Definition: elog.c:797
CoercionPathType find_coercion_pathway(Oid targetTypeId, Oid sourceTypeId, CoercionContext ccontext, Oid *funcid)
Oid typeTypeRelid(Type typ)
Definition: parse_type.c:612
bool winagg
Definition: primnodes.h:339
int i
TypeName * makeTypeNameFromNameList(List *names)
Definition: makefuncs.c:453
#define NameStr(name)
Definition: c.h:494
void * arg
Oid select_common_type(ParseState *pstate, List *exprs, const char *context, Node **which_expr)
Oid aggtype
Definition: primnodes.h:271
char aggkind
Definition: primnodes.h:285
int location
Definition: primnodes.h:433
#define elog
Definition: elog.h:218
bool agg_within_group
Definition: parsenodes.h:335
Oid typeTypeId(Type tp)
Definition: parse_type.c:572
bool agg_distinct
Definition: parsenodes.h:337
#define AGGKIND_HYPOTHETICAL
Definition: pg_aggregate.h:129
Oid getBaseType(Oid typid)
Definition: lsyscache.c:2239
static Node * ParseComplexProjection(ParseState *pstate, char *funcname, Node *first_arg, int location)
Definition: parse_func.c:1768
void get_type_category_preferred(Oid typid, char *typcategory, bool *typispreferred)
Definition: lsyscache.c:2404
bool agg_star
Definition: parsenodes.h:336
Definition: pg_list.h:45
bool bms_is_member(int x, const Bitmapset *a)
Definition: bitmapset.c:419
bool funcvariadic
Definition: primnodes.h:427
List * list_delete_first(List *list)
Definition: list.c:666
Oid LookupTypeNameOid(ParseState *pstate, const TypeName *typeName, bool missing_ok)
Definition: parse_type.c:215
void transformAggregateCall(ParseState *pstate, Aggref *agg, List *args, List *aggorder, bool agg_distinct)
Definition: parse_agg.c:101
int32 resulttypmod
Definition: primnodes.h:719
bool winstar
Definition: primnodes.h:338
AttrNumber fieldnum
Definition: primnodes.h:716