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-2018, 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,
1562  Anum_pg_proc_proargdefaults,
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 
1618  switch (pform->prokind)
1619  {
1620  case PROKIND_AGGREGATE:
1621  result = FUNCDETAIL_AGGREGATE;
1622  break;
1623  case PROKIND_FUNCTION:
1624  result = FUNCDETAIL_NORMAL;
1625  break;
1626  case PROKIND_PROCEDURE:
1627  result = FUNCDETAIL_PROCEDURE;
1628  break;
1629  case PROKIND_WINDOW:
1630  result = FUNCDETAIL_WINDOWFUNC;
1631  break;
1632  default:
1633  elog(ERROR, "unrecognized prokind: %c", pform->prokind);
1634  result = FUNCDETAIL_NORMAL; /* keep compiler quiet */
1635  break;
1636  }
1637 
1638  ReleaseSysCache(ftup);
1639  return result;
1640  }
1641 
1642  return FUNCDETAIL_NOTFOUND;
1643 }
1644 
1645 
1646 /*
1647  * unify_hypothetical_args()
1648  *
1649  * Ensure that each hypothetical direct argument of a hypothetical-set
1650  * aggregate has the same type as the corresponding aggregated argument.
1651  * Modify the expressions in the fargs list, if necessary, and update
1652  * actual_arg_types[].
1653  *
1654  * If the agg declared its args non-ANY (even ANYELEMENT), we need only a
1655  * sanity check that the declared types match; make_fn_arguments will coerce
1656  * the actual arguments to match the declared ones. But if the declaration
1657  * is ANY, nothing will happen in make_fn_arguments, so we need to fix any
1658  * mismatch here. We use the same type resolution logic as UNION etc.
1659  */
1660 static void
1662  List *fargs,
1663  int numAggregatedArgs,
1664  Oid *actual_arg_types,
1665  Oid *declared_arg_types)
1666 {
1668  int numDirectArgs,
1669  numNonHypotheticalArgs;
1670  int i;
1671  ListCell *lc;
1672 
1673  numDirectArgs = list_length(fargs) - numAggregatedArgs;
1674  numNonHypotheticalArgs = numDirectArgs - numAggregatedArgs;
1675  /* safety check (should only trigger with a misdeclared agg) */
1676  if (numNonHypotheticalArgs < 0)
1677  elog(ERROR, "incorrect number of arguments to hypothetical-set aggregate");
1678 
1679  /* Deconstruct fargs into an array for ease of subscripting */
1680  i = 0;
1681  foreach(lc, fargs)
1682  {
1683  args[i++] = (Node *) lfirst(lc);
1684  }
1685 
1686  /* Check each hypothetical arg and corresponding aggregated arg */
1687  for (i = numNonHypotheticalArgs; i < numDirectArgs; i++)
1688  {
1689  int aargpos = numDirectArgs + (i - numNonHypotheticalArgs);
1690  Oid commontype;
1691 
1692  /* A mismatch means AggregateCreate didn't check properly ... */
1693  if (declared_arg_types[i] != declared_arg_types[aargpos])
1694  elog(ERROR, "hypothetical-set aggregate has inconsistent declared argument types");
1695 
1696  /* No need to unify if make_fn_arguments will coerce */
1697  if (declared_arg_types[i] != ANYOID)
1698  continue;
1699 
1700  /*
1701  * Select common type, giving preference to the aggregated argument's
1702  * type (we'd rather coerce the direct argument once than coerce all
1703  * the aggregated values).
1704  */
1705  commontype = select_common_type(pstate,
1706  list_make2(args[aargpos], args[i]),
1707  "WITHIN GROUP",
1708  NULL);
1709 
1710  /*
1711  * Perform the coercions. We don't need to worry about NamedArgExprs
1712  * here because they aren't supported with aggregates.
1713  */
1714  args[i] = coerce_type(pstate,
1715  args[i],
1716  actual_arg_types[i],
1717  commontype, -1,
1720  -1);
1721  actual_arg_types[i] = commontype;
1722  args[aargpos] = coerce_type(pstate,
1723  args[aargpos],
1724  actual_arg_types[aargpos],
1725  commontype, -1,
1728  -1);
1729  actual_arg_types[aargpos] = commontype;
1730  }
1731 
1732  /* Reconstruct fargs from array */
1733  i = 0;
1734  foreach(lc, fargs)
1735  {
1736  lfirst(lc) = args[i++];
1737  }
1738 }
1739 
1740 
1741 /*
1742  * make_fn_arguments()
1743  *
1744  * Given the actual argument expressions for a function, and the desired
1745  * input types for the function, add any necessary typecasting to the
1746  * expression tree. Caller should already have verified that casting is
1747  * allowed.
1748  *
1749  * Caution: given argument list is modified in-place.
1750  *
1751  * As with coerce_type, pstate may be NULL if no special unknown-Param
1752  * processing is wanted.
1753  */
1754 void
1756  List *fargs,
1757  Oid *actual_arg_types,
1758  Oid *declared_arg_types)
1759 {
1760  ListCell *current_fargs;
1761  int i = 0;
1762 
1763  foreach(current_fargs, fargs)
1764  {
1765  /* types don't match? then force coercion using a function call... */
1766  if (actual_arg_types[i] != declared_arg_types[i])
1767  {
1768  Node *node = (Node *) lfirst(current_fargs);
1769 
1770  /*
1771  * If arg is a NamedArgExpr, coerce its input expr instead --- we
1772  * want the NamedArgExpr to stay at the top level of the list.
1773  */
1774  if (IsA(node, NamedArgExpr))
1775  {
1776  NamedArgExpr *na = (NamedArgExpr *) node;
1777 
1778  node = coerce_type(pstate,
1779  (Node *) na->arg,
1780  actual_arg_types[i],
1781  declared_arg_types[i], -1,
1784  -1);
1785  na->arg = (Expr *) node;
1786  }
1787  else
1788  {
1789  node = coerce_type(pstate,
1790  node,
1791  actual_arg_types[i],
1792  declared_arg_types[i], -1,
1795  -1);
1796  lfirst(current_fargs) = node;
1797  }
1798  }
1799  i++;
1800  }
1801 }
1802 
1803 /*
1804  * FuncNameAsType -
1805  * convenience routine to see if a function name matches a type name
1806  *
1807  * Returns the OID of the matching type, or InvalidOid if none. We ignore
1808  * shell types and complex types.
1809  */
1810 static Oid
1812 {
1813  Oid result;
1814  Type typtup;
1815 
1816  typtup = LookupTypeName(NULL, makeTypeNameFromNameList(funcname), NULL, false);
1817  if (typtup == NULL)
1818  return InvalidOid;
1819 
1820  if (((Form_pg_type) GETSTRUCT(typtup))->typisdefined &&
1821  !OidIsValid(typeTypeRelid(typtup)))
1822  result = typeTypeId(typtup);
1823  else
1824  result = InvalidOid;
1825 
1826  ReleaseSysCache(typtup);
1827  return result;
1828 }
1829 
1830 /*
1831  * ParseComplexProjection -
1832  * handles function calls with a single argument that is of complex type.
1833  * If the function call is actually a column projection, return a suitably
1834  * transformed expression tree. If not, return NULL.
1835  */
1836 static Node *
1837 ParseComplexProjection(ParseState *pstate, const char *funcname, Node *first_arg,
1838  int location)
1839 {
1840  TupleDesc tupdesc;
1841  int i;
1842 
1843  /*
1844  * Special case for whole-row Vars so that we can resolve (foo.*).bar even
1845  * when foo is a reference to a subselect, join, or RECORD function. A
1846  * bonus is that we avoid generating an unnecessary FieldSelect; our
1847  * result can omit the whole-row Var and just be a Var for the selected
1848  * field.
1849  *
1850  * This case could be handled by expandRecordVariable, but it's more
1851  * efficient to do it this way when possible.
1852  */
1853  if (IsA(first_arg, Var) &&
1854  ((Var *) first_arg)->varattno == InvalidAttrNumber)
1855  {
1856  RangeTblEntry *rte;
1857 
1858  rte = GetRTEByRangeTablePosn(pstate,
1859  ((Var *) first_arg)->varno,
1860  ((Var *) first_arg)->varlevelsup);
1861  /* Return a Var if funcname matches a column, else NULL */
1862  return scanRTEForColumn(pstate, rte, funcname, location, 0, NULL);
1863  }
1864 
1865  /*
1866  * Else do it the hard way with get_expr_result_tupdesc().
1867  *
1868  * If it's a Var of type RECORD, we have to work even harder: we have to
1869  * find what the Var refers to, and pass that to get_expr_result_tupdesc.
1870  * That task is handled by expandRecordVariable().
1871  */
1872  if (IsA(first_arg, Var) &&
1873  ((Var *) first_arg)->vartype == RECORDOID)
1874  tupdesc = expandRecordVariable(pstate, (Var *) first_arg, 0);
1875  else
1876  tupdesc = get_expr_result_tupdesc(first_arg, true);
1877  if (!tupdesc)
1878  return NULL; /* unresolvable RECORD type */
1879 
1880  for (i = 0; i < tupdesc->natts; i++)
1881  {
1882  Form_pg_attribute att = TupleDescAttr(tupdesc, i);
1883 
1884  if (strcmp(funcname, NameStr(att->attname)) == 0 &&
1885  !att->attisdropped)
1886  {
1887  /* Success, so generate a FieldSelect expression */
1888  FieldSelect *fselect = makeNode(FieldSelect);
1889 
1890  fselect->arg = (Expr *) first_arg;
1891  fselect->fieldnum = i + 1;
1892  fselect->resulttype = att->atttypid;
1893  fselect->resulttypmod = att->atttypmod;
1894  /* save attribute's collation for parse_collate.c */
1895  fselect->resultcollid = att->attcollation;
1896  return (Node *) fselect;
1897  }
1898  }
1899 
1900  return NULL; /* funcname does not match any column */
1901 }
1902 
1903 /*
1904  * funcname_signature_string
1905  * Build a string representing a function name, including arg types.
1906  * The result is something like "foo(integer)".
1907  *
1908  * If argnames isn't NIL, it is a list of C strings representing the actual
1909  * arg names for the last N arguments. This must be considered part of the
1910  * function signature too, when dealing with named-notation function calls.
1911  *
1912  * This is typically used in the construction of function-not-found error
1913  * messages.
1914  */
1915 const char *
1916 funcname_signature_string(const char *funcname, int nargs,
1917  List *argnames, const Oid *argtypes)
1918 {
1919  StringInfoData argbuf;
1920  int numposargs;
1921  ListCell *lc;
1922  int i;
1923 
1924  initStringInfo(&argbuf);
1925 
1926  appendStringInfo(&argbuf, "%s(", funcname);
1927 
1928  numposargs = nargs - list_length(argnames);
1929  lc = list_head(argnames);
1930 
1931  for (i = 0; i < nargs; i++)
1932  {
1933  if (i)
1934  appendStringInfoString(&argbuf, ", ");
1935  if (i >= numposargs)
1936  {
1937  appendStringInfo(&argbuf, "%s => ", (char *) lfirst(lc));
1938  lc = lnext(lc);
1939  }
1940  appendStringInfoString(&argbuf, format_type_be(argtypes[i]));
1941  }
1942 
1943  appendStringInfoChar(&argbuf, ')');
1944 
1945  return argbuf.data; /* return palloc'd string buffer */
1946 }
1947 
1948 /*
1949  * func_signature_string
1950  * As above, but function name is passed as a qualified name list.
1951  */
1952 const char *
1953 func_signature_string(List *funcname, int nargs,
1954  List *argnames, const Oid *argtypes)
1955 {
1957  nargs, argnames, argtypes);
1958 }
1959 
1960 /*
1961  * LookupFuncName
1962  *
1963  * Given a possibly-qualified function name and optionally a set of argument
1964  * types, look up the function. Pass nargs == -1 to indicate that no argument
1965  * types are specified.
1966  *
1967  * If the function name is not schema-qualified, it is sought in the current
1968  * namespace search path.
1969  *
1970  * If the function is not found, we return InvalidOid if noError is true,
1971  * else raise an error.
1972  */
1973 Oid
1974 LookupFuncName(List *funcname, int nargs, const Oid *argtypes, bool noError)
1975 {
1976  FuncCandidateList clist;
1977 
1978  /* Passing NULL for argtypes is no longer allowed */
1979  Assert(argtypes);
1980 
1981  clist = FuncnameGetCandidates(funcname, nargs, NIL, false, false, noError);
1982 
1983  /*
1984  * If no arguments were specified, the name must yield a unique candidate.
1985  */
1986  if (nargs == -1)
1987  {
1988  if (clist)
1989  {
1990  if (clist->next)
1991  {
1992  if (!noError)
1993  ereport(ERROR,
1994  (errcode(ERRCODE_AMBIGUOUS_FUNCTION),
1995  errmsg("function name \"%s\" is not unique",
1996  NameListToString(funcname)),
1997  errhint("Specify the argument list to select the function unambiguously.")));
1998  }
1999  else
2000  return clist->oid;
2001  }
2002  else
2003  {
2004  if (!noError)
2005  ereport(ERROR,
2006  (errcode(ERRCODE_UNDEFINED_FUNCTION),
2007  errmsg("could not find a function named \"%s\"",
2008  NameListToString(funcname))));
2009  }
2010  }
2011 
2012  while (clist)
2013  {
2014  if (memcmp(argtypes, clist->args, nargs * sizeof(Oid)) == 0)
2015  return clist->oid;
2016  clist = clist->next;
2017  }
2018 
2019  if (!noError)
2020  ereport(ERROR,
2021  (errcode(ERRCODE_UNDEFINED_FUNCTION),
2022  errmsg("function %s does not exist",
2023  func_signature_string(funcname, nargs,
2024  NIL, argtypes))));
2025 
2026  return InvalidOid;
2027 }
2028 
2029 /*
2030  * LookupFuncWithArgs
2031  *
2032  * Like LookupFuncName, but the argument types are specified by a
2033  * ObjectWithArgs node. Also, this function can check whether the result is a
2034  * function, procedure, or aggregate, based on the objtype argument. Pass
2035  * OBJECT_ROUTINE to accept any of them.
2036  *
2037  * For historical reasons, we also accept aggregates when looking for a
2038  * function.
2039  */
2040 Oid
2041 LookupFuncWithArgs(ObjectType objtype, ObjectWithArgs *func, bool noError)
2042 {
2043  Oid argoids[FUNC_MAX_ARGS];
2044  int argcount;
2045  int i;
2046  ListCell *args_item;
2047  Oid oid;
2048 
2049  Assert(objtype == OBJECT_AGGREGATE ||
2050  objtype == OBJECT_FUNCTION ||
2051  objtype == OBJECT_PROCEDURE ||
2052  objtype == OBJECT_ROUTINE);
2053 
2054  argcount = list_length(func->objargs);
2055  if (argcount > FUNC_MAX_ARGS)
2056  ereport(ERROR,
2057  (errcode(ERRCODE_TOO_MANY_ARGUMENTS),
2058  errmsg_plural("functions cannot have more than %d argument",
2059  "functions cannot have more than %d arguments",
2060  FUNC_MAX_ARGS,
2061  FUNC_MAX_ARGS)));
2062 
2063  args_item = list_head(func->objargs);
2064  for (i = 0; i < argcount; i++)
2065  {
2066  TypeName *t = (TypeName *) lfirst(args_item);
2067 
2068  argoids[i] = LookupTypeNameOid(NULL, t, noError);
2069  args_item = lnext(args_item);
2070  }
2071 
2072  /*
2073  * When looking for a function or routine, we pass noError through to
2074  * LookupFuncName and let it make any error messages. Otherwise, we make
2075  * our own errors for the aggregate and procedure cases.
2076  */
2077  oid = LookupFuncName(func->objname, func->args_unspecified ? -1 : argcount, argoids,
2078  (objtype == OBJECT_FUNCTION || objtype == OBJECT_ROUTINE) ? noError : true);
2079 
2080  if (objtype == OBJECT_FUNCTION)
2081  {
2082  /* Make sure it's a function, not a procedure */
2083  if (oid && get_func_prokind(oid) == PROKIND_PROCEDURE)
2084  {
2085  if (noError)
2086  return InvalidOid;
2087  ereport(ERROR,
2088  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2089  errmsg("%s is not a function",
2090  func_signature_string(func->objname, argcount,
2091  NIL, argoids))));
2092  }
2093  }
2094  else if (objtype == OBJECT_PROCEDURE)
2095  {
2096  if (!OidIsValid(oid))
2097  {
2098  if (noError)
2099  return InvalidOid;
2100  else if (func->args_unspecified)
2101  ereport(ERROR,
2102  (errcode(ERRCODE_UNDEFINED_FUNCTION),
2103  errmsg("could not find a procedure named \"%s\"",
2104  NameListToString(func->objname))));
2105  else
2106  ereport(ERROR,
2107  (errcode(ERRCODE_UNDEFINED_FUNCTION),
2108  errmsg("procedure %s does not exist",
2109  func_signature_string(func->objname, argcount,
2110  NIL, argoids))));
2111  }
2112 
2113  /* Make sure it's a procedure */
2114  if (get_func_prokind(oid) != PROKIND_PROCEDURE)
2115  {
2116  if (noError)
2117  return InvalidOid;
2118  ereport(ERROR,
2119  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2120  errmsg("%s is not a procedure",
2121  func_signature_string(func->objname, argcount,
2122  NIL, argoids))));
2123  }
2124  }
2125  else if (objtype == OBJECT_AGGREGATE)
2126  {
2127  if (!OidIsValid(oid))
2128  {
2129  if (noError)
2130  return InvalidOid;
2131  else if (func->args_unspecified)
2132  ereport(ERROR,
2133  (errcode(ERRCODE_UNDEFINED_FUNCTION),
2134  errmsg("could not find a aggregate named \"%s\"",
2135  NameListToString(func->objname))));
2136  else if (argcount == 0)
2137  ereport(ERROR,
2138  (errcode(ERRCODE_UNDEFINED_FUNCTION),
2139  errmsg("aggregate %s(*) does not exist",
2140  NameListToString(func->objname))));
2141  else
2142  ereport(ERROR,
2143  (errcode(ERRCODE_UNDEFINED_FUNCTION),
2144  errmsg("aggregate %s does not exist",
2145  func_signature_string(func->objname, argcount,
2146  NIL, argoids))));
2147  }
2148 
2149  /* Make sure it's an aggregate */
2150  if (get_func_prokind(oid) != PROKIND_AGGREGATE)
2151  {
2152  if (noError)
2153  return InvalidOid;
2154  /* we do not use the (*) notation for functions... */
2155  ereport(ERROR,
2156  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2157  errmsg("function %s is not an aggregate",
2158  func_signature_string(func->objname, argcount,
2159  NIL, argoids))));
2160  }
2161  }
2162 
2163  return oid;
2164 }
2165 
2166 /*
2167  * check_srf_call_placement
2168  * Verify that a set-returning function is called in a valid place,
2169  * and throw a nice error if not.
2170  *
2171  * A side-effect is to set pstate->p_hasTargetSRFs true if appropriate.
2172  *
2173  * last_srf should be a copy of pstate->p_last_srf from just before we
2174  * started transforming the function's arguments. This allows detection
2175  * of whether the SRF's arguments contain any SRFs.
2176  */
2177 void
2178 check_srf_call_placement(ParseState *pstate, Node *last_srf, int location)
2179 {
2180  const char *err;
2181  bool errkind;
2182 
2183  /*
2184  * Check to see if the set-returning function is in an invalid place
2185  * within the query. Basically, we don't allow SRFs anywhere except in
2186  * the targetlist (which includes GROUP BY/ORDER BY expressions), VALUES,
2187  * and functions in FROM.
2188  *
2189  * For brevity we support two schemes for reporting an error here: set
2190  * "err" to a custom message, or set "errkind" true if the error context
2191  * is sufficiently identified by what ParseExprKindName will return, *and*
2192  * what it will return is just a SQL keyword. (Otherwise, use a custom
2193  * message to avoid creating translation problems.)
2194  */
2195  err = NULL;
2196  errkind = false;
2197  switch (pstate->p_expr_kind)
2198  {
2199  case EXPR_KIND_NONE:
2200  Assert(false); /* can't happen */
2201  break;
2202  case EXPR_KIND_OTHER:
2203  /* Accept SRF here; caller must throw error if wanted */
2204  break;
2205  case EXPR_KIND_JOIN_ON:
2206  case EXPR_KIND_JOIN_USING:
2207  err = _("set-returning functions are not allowed in JOIN conditions");
2208  break;
2210  /* can't get here, but just in case, throw an error */
2211  errkind = true;
2212  break;
2214  /* okay, but we don't allow nested SRFs here */
2215  /* errmsg is chosen to match transformRangeFunction() */
2216  /* errposition should point to the inner SRF */
2217  if (pstate->p_last_srf != last_srf)
2218  ereport(ERROR,
2219  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2220  errmsg("set-returning functions must appear at top level of FROM"),
2221  parser_errposition(pstate,
2222  exprLocation(pstate->p_last_srf))));
2223  break;
2224  case EXPR_KIND_WHERE:
2225  errkind = true;
2226  break;
2227  case EXPR_KIND_POLICY:
2228  err = _("set-returning functions are not allowed in policy expressions");
2229  break;
2230  case EXPR_KIND_HAVING:
2231  errkind = true;
2232  break;
2233  case EXPR_KIND_FILTER:
2234  errkind = true;
2235  break;
2238  /* okay, these are effectively GROUP BY/ORDER BY */
2239  pstate->p_hasTargetSRFs = true;
2240  break;
2244  err = _("set-returning functions are not allowed in window definitions");
2245  break;
2248  /* okay */
2249  pstate->p_hasTargetSRFs = true;
2250  break;
2253  /* disallowed because it would be ambiguous what to do */
2254  errkind = true;
2255  break;
2256  case EXPR_KIND_GROUP_BY:
2257  case EXPR_KIND_ORDER_BY:
2258  /* okay */
2259  pstate->p_hasTargetSRFs = true;
2260  break;
2261  case EXPR_KIND_DISTINCT_ON:
2262  /* okay */
2263  pstate->p_hasTargetSRFs = true;
2264  break;
2265  case EXPR_KIND_LIMIT:
2266  case EXPR_KIND_OFFSET:
2267  errkind = true;
2268  break;
2269  case EXPR_KIND_RETURNING:
2270  errkind = true;
2271  break;
2272  case EXPR_KIND_VALUES:
2273  /* SRFs are presently not supported by nodeValuesscan.c */
2274  errkind = true;
2275  break;
2277  /* okay, since we process this like a SELECT tlist */
2278  pstate->p_hasTargetSRFs = true;
2279  break;
2282  err = _("set-returning functions are not allowed in check constraints");
2283  break;
2286  err = _("set-returning functions are not allowed in DEFAULT expressions");
2287  break;
2289  err = _("set-returning functions are not allowed in index expressions");
2290  break;
2292  err = _("set-returning functions are not allowed in index predicates");
2293  break;
2295  err = _("set-returning functions are not allowed in transform expressions");
2296  break;
2298  err = _("set-returning functions are not allowed in EXECUTE parameters");
2299  break;
2301  err = _("set-returning functions are not allowed in trigger WHEN conditions");
2302  break;
2304  err = _("set-returning functions are not allowed in partition key expressions");
2305  break;
2307  err = _("set-returning functions are not allowed in CALL arguments");
2308  break;
2309 
2310  /*
2311  * There is intentionally no default: case here, so that the
2312  * compiler will warn if we add a new ParseExprKind without
2313  * extending this switch. If we do see an unrecognized value at
2314  * runtime, the behavior will be the same as for EXPR_KIND_OTHER,
2315  * which is sane anyway.
2316  */
2317  }
2318  if (err)
2319  ereport(ERROR,
2320  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2321  errmsg_internal("%s", err),
2322  parser_errposition(pstate, location)));
2323  if (errkind)
2324  ereport(ERROR,
2325  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2326  /* translator: %s is name of a SQL construct, eg GROUP BY */
2327  errmsg("set-returning functions are not allowed in %s",
2328  ParseExprKindName(pstate->p_expr_kind)),
2329  parser_errposition(pstate, location)));
2330 }
#define list_make2(x1, x2)
Definition: pg_list.h:140
Type LookupTypeName(ParseState *pstate, const TypeName *typeName, int32 *typmod_p, bool missing_ok)
Definition: parse_type.c:57
Oid funcresulttype
Definition: primnodes.h:451
static void unify_hypothetical_args(ParseState *pstate, List *fargs, int numAggregatedArgs, Oid *actual_arg_types, Oid *declared_arg_types)
Definition: parse_func.c:1661
bool multidims
Definition: primnodes.h:961
#define NIL
Definition: pg_list.h:69
bool aggvariadic
Definition: primnodes.h:307
void * stringToNode(char *str)
Definition: read.c:39
#define IsA(nodeptr, _type_)
Definition: nodes.h:568
int errhint(const char *fmt,...)
Definition: elog.c:987
#define GETSTRUCT(TUP)
Definition: htup_details.h:668
static Node * ParseComplexProjection(ParseState *pstate, const char *funcname, Node *first_arg, int location)
Definition: parse_func.c:1837
int exprLocation(const Node *expr)
Definition: nodeFuncs.c:1186
List * args
Definition: primnodes.h:360
List * args
Definition: primnodes.h:458
int func_match_argtypes(int nargs, Oid *input_typeids, FuncCandidateList raw_candidates, FuncCandidateList *candidates)
Definition: parse_func.c:840
Oid resulttype
Definition: primnodes.h:745
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:586
static Oid FuncNameAsType(List *funcname)
Definition: parse_func.c:1811
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:93
Oid get_array_type(Oid typid)
Definition: lsyscache.c:2530
Node * agg_filter
Definition: parsenodes.h:354
#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:202
Definition: nodes.h:517
#define strVal(v)
Definition: value.h:54
int errcode(int sqlerrcode)
Definition: elog.c:575
Oid array_typeid
Definition: primnodes.h:957
char * format_type_be(Oid type_oid)
Definition: format_type.c:328
Expr * arg
Definition: primnodes.h:743
bool funcretset
Definition: primnodes.h:452
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:1755
List * list_copy_tail(const List *oldlist, int nskip)
Definition: list.c:1203
int16 pronargs
Definition: pg_proc.h:80
bool aggstar
Definition: primnodes.h:306
unsigned int Oid
Definition: postgres_ext.h:31
Definition: primnodes.h:164
#define OidIsValid(objectId)
Definition: c.h:605
int natts
Definition: tupdesc.h:82
List * agg_order
Definition: parsenodes.h:353
bool IsPreferredType(TYPCATEGORY category, Oid type)
CoercionPathType
Definition: parse_coerce.h:24
const char * ParseExprKindName(ParseExprKind exprKind)
Definition: parse_expr.c:3402
#define FUNC_MAX_ARGS
char TYPCATEGORY
Definition: parse_coerce.h:21
CoercionForm funcformat
Definition: primnodes.h:455
Oid args[FLEXIBLE_ARRAY_MEMBER]
Definition: namespace.h:37
void pfree(void *pointer)
Definition: mcxt.c:1031
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
Node * scanRTEForColumn(ParseState *pstate, RangeTblEntry *rte, const char *colname, int location, int fuzzy_rte_penalty, FuzzyAttrMatchState *fuzzystate)
Oid funcid
Definition: primnodes.h:450
#define ObjectIdGetDatum(X)
Definition: postgres.h:492
#define ERROR
Definition: elog.h:43
struct WindowDef * over
Definition: parsenodes.h:359
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:922
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:312
Oid resultcollid
Definition: primnodes.h:748
void appendStringInfoString(StringInfo str, const char *s)
Definition: stringinfo.c:157
Oid LookupFuncWithArgs(ObjectType objtype, ObjectWithArgs *func, bool noError)
Definition: parse_func.c:2041
FuncDetailCode
Definition: parse_func.h:22
char * name
Definition: primnodes.h:480
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:1916
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:197
Oid winfnoid
Definition: primnodes.h:356
List * elements
Definition: primnodes.h:960
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:1953
ObjectType
Definition: parsenodes.h:1634
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:776
bool func_variadic
Definition: parsenodes.h:358
char * NameListToString(List *names)
Definition: namespace.c:3082
#define TextDatumGetCString(d)
Definition: builtins.h:96
char get_func_prokind(Oid funcid)
Definition: lsyscache.c:1607
int location
Definition: primnodes.h:962
Node * p_last_srf
Definition: parse_node.h:206
uintptr_t Datum
Definition: postgres.h:367
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:188
FormData_pg_proc * Form_pg_proc
Definition: pg_proc.h:132
#define InvalidOid
Definition: postgres_ext.h:36
TYPCATEGORY TypeCategory(Oid type)
Oid aggfnoid
Definition: primnodes.h:295
static void * fn(void *arg)
int errmsg_internal(const char *fmt,...)
Definition: elog.c:827
void bms_free(Bitmapset *a)
Definition: bitmapset.c:267
#define makeNode(_type_)
Definition: nodes.h:565
Expr * arg
Definition: primnodes.h:479
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
int location
Definition: primnodes.h:365
#define Assert(condition)
Definition: c.h:699
#define lfirst(lc)
Definition: pg_list.h:106
Expr * aggfilter
Definition: primnodes.h:361
FormData_pg_aggregate * Form_pg_aggregate
Definition: pg_aggregate.h:109
Node * transformWhereClause(ParseState *pstate, Node *clause, ParseExprKind exprKind, const char *constructName)
AggSplit aggsplit
Definition: primnodes.h:311
#define ISCOMPLEX(typeid)
Definition: parse_type.h:55
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:42
FormData_pg_type * Form_pg_type
Definition: pg_type.h:247
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:305
Bitmapset * bms_add_member(Bitmapset *a, int x)
Definition: bitmapset.c:764
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:959
Oid wintype
Definition: primnodes.h:357
Oid LookupFuncName(List *funcname, int nargs, const Oid *argtypes, bool noError)
Definition: parse_func.c:1974
Oid get_base_element_type(Oid typid)
Definition: lsyscache.c:2575
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:364
int i
TypeName * makeTypeNameFromNameList(List *names)
Definition: makefuncs.c:455
Oid aggtranstype
Definition: primnodes.h:299
#define NameStr(name)
Definition: c.h:576
void * arg
Oid select_common_type(ParseState *pstate, List *exprs, const char *context, Node **which_expr)
Oid aggtype
Definition: primnodes.h:296
void check_srf_call_placement(ParseState *pstate, Node *last_srf, int location)
Definition: parse_func.c:2178
char aggkind
Definition: primnodes.h:309
int location
Definition: primnodes.h:459
#define elog
Definition: elog.h:219
bool agg_within_group
Definition: parsenodes.h:355
Oid typeTypeId(Type tp)
Definition: parse_type.c:571
bool agg_distinct
Definition: parsenodes.h:357
Oid getBaseType(Oid typid)
Definition: lsyscache.c:2275
void get_type_category_preferred(Oid typid, char *typcategory, bool *typispreferred)
Definition: lsyscache.c:2454
bool agg_star
Definition: parsenodes.h:356
Definition: pg_list.h:45
bool bms_is_member(int x, const Bitmapset *a)
Definition: bitmapset.c:486
#define _(x)
Definition: elog.c:84
bool funcvariadic
Definition: primnodes.h:453
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:747
bool winstar
Definition: primnodes.h:363
AttrNumber fieldnum
Definition: primnodes.h:744