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