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