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