1 /*-------------------------------------------------------------------------
4 * handle function calls in parser
6 * Portions Copyright (c) 1996-2010, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
11 * $PostgreSQL: pgsql/src/backend/parser/parse_func.c,v 1.220 2010/01/02 16:57:49 momjian Exp $
13 *-------------------------------------------------------------------------
17 #include "catalog/pg_proc.h"
18 #include "catalog/pg_type.h"
20 #include "nodes/makefuncs.h"
21 #include "nodes/nodeFuncs.h"
22 #include "parser/parse_agg.h"
23 #include "parser/parse_coerce.h"
24 #include "parser/parse_func.h"
25 #include "parser/parse_relation.h"
26 #include "parser/parse_target.h"
27 #include "parser/parse_type.h"
28 #include "utils/builtins.h"
29 #include "utils/lsyscache.h"
30 #include "utils/syscache.h"
33 static Oid FuncNameAsType(List *funcname);
34 static Node *ParseComplexProjection(ParseState *pstate, char *funcname,
35 Node *first_arg, int location);
39 * Parse a function call
41 * For historical reasons, Postgres tries to treat the notations tab.col
42 * and col(tab) as equivalent: if a single-argument function call has an
43 * argument of complex type and the (unqualified) function name matches
44 * any attribute of the type, we take it as a column projection. Conversely
45 * a function of a single complex-type argument can be written like a
46 * column reference, allowing functions to act like computed columns.
48 * Hence, both cases come through here. The is_column parameter tells us
49 * which syntactic construct is actually being dealt with, but this is
50 * intended to be used only to deliver an appropriate error message,
51 * not to affect the semantics. When is_column is true, we should have
52 * a single argument (the putative table), unqualified function name
53 * equal to the column name, and no aggregate or variadic decoration.
54 * Also, when is_column is true, we return NULL on failure rather than
55 * reporting a no-such-function error.
57 * The argument expressions (in fargs) must have been transformed already.
58 * But the agg_order expressions, if any, have not been.
61 ParseFuncOrColumn(ParseState *pstate, List *funcname, List *fargs,
62 List *agg_order, bool agg_star, bool agg_distinct,
64 WindowDef *over, bool is_column, int location)
70 Node *first_arg = NULL;
73 Oid actual_arg_types[FUNC_MAX_ARGS];
74 Oid *declared_arg_types;
80 FuncDetailCode fdresult;
83 * Most of the rest of the parser just assumes that functions do not have
84 * more than FUNC_MAX_ARGS parameters. We have to test here to protect
85 * against array overruns, etc. Of course, this may not be a function,
86 * but the test doesn't hurt.
88 if (list_length(fargs) > FUNC_MAX_ARGS)
90 (errcode(ERRCODE_TOO_MANY_ARGUMENTS),
91 errmsg_plural("cannot pass more than %d argument to a function",
92 "cannot pass more than %d arguments to a function",
95 parser_errposition(pstate, location)));
98 * Extract arg type info in preparation for function lookup.
100 * If any arguments are Param markers of type VOID, we discard them from
101 * the parameter list. This is a hack to allow the JDBC driver to not
102 * have to distinguish "input" and "output" parameter symbols while
103 * parsing function-call constructs. We can't use foreach() because we
104 * may modify the list ...
107 for (l = list_head(fargs); l != NULL; l = nextl)
109 Node *arg = lfirst(l);
110 Oid argtype = exprType(arg);
114 if (argtype == VOIDOID && IsA(arg, Param) &&!is_column)
116 fargs = list_delete_ptr(fargs, arg);
120 actual_arg_types[nargs++] = argtype;
124 * Check for named arguments; if there are any, build a list of names.
126 * We allow mixed notation (some named and some not), but only with all
127 * the named parameters after all the unnamed ones. So the name list
128 * corresponds to the last N actual parameters and we don't need any
129 * extra bookkeeping to match things up.
134 Node *arg = lfirst(l);
136 if (IsA(arg, NamedArgExpr))
138 NamedArgExpr *na = (NamedArgExpr *) arg;
141 /* Reject duplicate arg names */
142 foreach(lc, argnames)
144 if (strcmp(na->name, (char *) lfirst(lc)) == 0)
146 (errcode(ERRCODE_SYNTAX_ERROR),
147 errmsg("argument name \"%s\" used more than once",
149 parser_errposition(pstate, na->location)));
151 argnames = lappend(argnames, na->name);
157 (errcode(ERRCODE_SYNTAX_ERROR),
158 errmsg("positional argument cannot follow named argument"),
159 parser_errposition(pstate, exprLocation(arg))));
165 first_arg = linitial(fargs);
166 Assert(first_arg != NULL);
170 * Check for column projection: if function has one argument, and that
171 * argument is of complex type, and function name is not qualified, then
172 * the "function call" could be a projection. We also check that there
173 * wasn't any aggregate or variadic decoration, nor an argument name.
175 if (nargs == 1 && agg_order == NIL && !agg_star && !agg_distinct &&
176 over == NULL && !func_variadic && argnames == NIL &&
177 list_length(funcname) == 1)
179 Oid argtype = actual_arg_types[0];
181 if (argtype == RECORDOID || ISCOMPLEX(argtype))
183 retval = ParseComplexProjection(pstate,
184 strVal(linitial(funcname)),
191 * If ParseComplexProjection doesn't recognize it as a projection,
198 * Okay, it's not a column projection, so it must really be a function.
199 * func_get_detail looks up the function in the catalogs, does
200 * disambiguation for polymorphic functions, handles inheritance, and
201 * returns the funcid and type and set or singleton status of the
202 * function's return value. It also returns the true argument types to
205 * Note: for a named-notation or variadic function call, the reported
206 * "true" types aren't really what is in pg_proc: the types are reordered
207 * to match the given argument order of named arguments, and a variadic
208 * argument is replaced by a suitable number of copies of its element
209 * type. We'll fix up the variadic case below. We may also have to deal
210 * with default arguments.
212 fdresult = func_get_detail(funcname, fargs, argnames, nargs,
214 !func_variadic, true,
215 &funcid, &rettype, &retset, &nvargs,
216 &declared_arg_types, &argdefaults);
217 if (fdresult == FUNCDETAIL_COERCION)
220 * We interpreted it as a type coercion. coerce_type can handle these
221 * cases, so why duplicate code...
223 return coerce_type(pstate, linitial(fargs),
224 actual_arg_types[0], rettype, -1,
225 COERCION_EXPLICIT, COERCE_EXPLICIT_CALL, location);
227 else if (fdresult == FUNCDETAIL_NORMAL)
230 * Normal function found; was there anything indicating it must be an
235 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
236 errmsg("%s(*) specified, but %s is not an aggregate function",
237 NameListToString(funcname),
238 NameListToString(funcname)),
239 parser_errposition(pstate, location)));
242 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
243 errmsg("DISTINCT specified, but %s is not an aggregate function",
244 NameListToString(funcname)),
245 parser_errposition(pstate, location)));
246 if (agg_order != NIL)
248 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
249 errmsg("ORDER BY specified, but %s is not an aggregate function",
250 NameListToString(funcname)),
251 parser_errposition(pstate, location)));
254 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
255 errmsg("OVER specified, but %s is not a window function nor an aggregate function",
256 NameListToString(funcname)),
257 parser_errposition(pstate, location)));
259 else if (!(fdresult == FUNCDETAIL_AGGREGATE ||
260 fdresult == FUNCDETAIL_WINDOWFUNC))
265 * If we are dealing with the attribute notation rel.function,
266 * let the caller handle failure.
272 * Else generate a detailed complaint for a function
274 if (fdresult == FUNCDETAIL_MULTIPLE)
276 (errcode(ERRCODE_AMBIGUOUS_FUNCTION),
277 errmsg("function %s is not unique",
278 func_signature_string(funcname, nargs, argnames,
280 errhint("Could not choose a best candidate function. "
281 "You might need to add explicit type casts."),
282 parser_errposition(pstate, location)));
285 (errcode(ERRCODE_UNDEFINED_FUNCTION),
286 errmsg("function %s does not exist",
287 func_signature_string(funcname, nargs, argnames,
289 errhint("No function matches the given name and argument types. "
290 "You might need to add explicit type casts."),
291 parser_errposition(pstate, location)));
295 * If there are default arguments, we have to include their types in
296 * actual_arg_types for the purpose of checking generic type consistency.
297 * However, we do NOT put them into the generated parse node, because
298 * their actual values might change before the query gets run. The
299 * planner has to insert the up-to-date values at plan time.
301 nargsplusdefs = nargs;
302 foreach(l, argdefaults)
304 Node *expr = (Node *) lfirst(l);
306 /* probably shouldn't happen ... */
307 if (nargsplusdefs >= FUNC_MAX_ARGS)
309 (errcode(ERRCODE_TOO_MANY_ARGUMENTS),
310 errmsg_plural("cannot pass more than %d argument to a function",
311 "cannot pass more than %d arguments to a function",
314 parser_errposition(pstate, location)));
316 actual_arg_types[nargsplusdefs++] = exprType(expr);
320 * enforce consistency with polymorphic argument and return types,
321 * possibly adjusting return type or declared_arg_types (which will be
322 * used as the cast destination by make_fn_arguments)
324 rettype = enforce_generic_type_consistency(actual_arg_types,
330 /* perform the necessary typecasting of arguments */
331 make_fn_arguments(pstate, fargs, actual_arg_types, declared_arg_types);
334 * If it's a variadic function call, transform the last nvargs arguments
335 * into an array --- unless it's an "any" variadic.
337 if (nvargs > 0 && declared_arg_types[nargs - 1] != ANYOID)
339 ArrayExpr *newa = makeNode(ArrayExpr);
340 int non_var_args = nargs - nvargs;
343 Assert(non_var_args >= 0);
344 vargs = list_copy_tail(fargs, non_var_args);
345 fargs = list_truncate(fargs, non_var_args);
347 newa->elements = vargs;
348 /* assume all the variadic arguments were coerced to the same type */
349 newa->element_typeid = exprType((Node *) linitial(vargs));
350 newa->array_typeid = get_array_type(newa->element_typeid);
351 if (!OidIsValid(newa->array_typeid))
353 (errcode(ERRCODE_UNDEFINED_OBJECT),
354 errmsg("could not find array type for data type %s",
355 format_type_be(newa->element_typeid)),
356 parser_errposition(pstate, exprLocation((Node *) vargs))));
357 newa->multidims = false;
358 newa->location = exprLocation((Node *) vargs);
360 fargs = lappend(fargs, newa);
363 /* build the appropriate output structure */
364 if (fdresult == FUNCDETAIL_NORMAL)
366 FuncExpr *funcexpr = makeNode(FuncExpr);
368 funcexpr->funcid = funcid;
369 funcexpr->funcresulttype = rettype;
370 funcexpr->funcretset = retset;
371 funcexpr->funcformat = COERCE_EXPLICIT_CALL;
372 funcexpr->args = fargs;
373 funcexpr->location = location;
375 retval = (Node *) funcexpr;
377 else if (fdresult == FUNCDETAIL_AGGREGATE && !over)
379 /* aggregate function */
380 Aggref *aggref = makeNode(Aggref);
382 aggref->aggfnoid = funcid;
383 aggref->aggtype = rettype;
384 /* args and aggorder will be modified by transformAggregateCall */
385 aggref->args = fargs;
386 aggref->aggorder = agg_order;
387 /* aggdistinct will be set by transformAggregateCall */
388 aggref->aggstar = agg_star;
389 /* agglevelsup will be set by transformAggregateCall */
390 aggref->location = location;
393 * Reject attempt to call a parameterless aggregate without (*)
394 * syntax. This is mere pedantry but some folks insisted ...
396 if (fargs == NIL && !agg_star)
398 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
399 errmsg("%s(*) must be used to call a parameterless aggregate function",
400 NameListToString(funcname)),
401 parser_errposition(pstate, location)));
405 (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
406 errmsg("aggregates cannot return sets"),
407 parser_errposition(pstate, location)));
410 * Currently it's not possible to define an aggregate with named
411 * arguments, so this case should be impossible. Check anyway
412 * because the planner and executor wouldn't cope with NamedArgExprs
417 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
418 errmsg("aggregates cannot use named arguments"),
419 parser_errposition(pstate, location)));
421 /* parse_agg.c does additional aggregate-specific processing */
422 transformAggregateCall(pstate, aggref, agg_distinct);
424 retval = (Node *) aggref;
428 /* window function */
429 WindowFunc *wfunc = makeNode(WindowFunc);
432 * True window functions must be called with a window definition.
436 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
437 errmsg("window function call requires an OVER clause"),
438 parser_errposition(pstate, location)));
440 wfunc->winfnoid = funcid;
441 wfunc->wintype = rettype;
443 /* winref will be set by transformWindowFuncCall */
444 wfunc->winstar = agg_star;
445 wfunc->winagg = (fdresult == FUNCDETAIL_AGGREGATE);
446 wfunc->location = location;
449 * agg_star is allowed for aggregate functions but distinct isn't
453 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
454 errmsg("DISTINCT is not implemented for window functions"),
455 parser_errposition(pstate, location)));
458 * Reject attempt to call a parameterless aggregate without (*)
459 * syntax. This is mere pedantry but some folks insisted ...
461 if (wfunc->winagg && fargs == NIL && !agg_star)
463 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
464 errmsg("%s(*) must be used to call a parameterless aggregate function",
465 NameListToString(funcname)),
466 parser_errposition(pstate, location)));
469 * ordered aggs not allowed in windows yet
471 if (agg_order != NIL)
473 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
474 errmsg("aggregate ORDER BY is not implemented for window functions"),
475 parser_errposition(pstate, location)));
479 (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
480 errmsg("window functions cannot return sets"),
481 parser_errposition(pstate, location)));
484 * We might want to support this later, but for now reject it
485 * because the planner and executor wouldn't cope with NamedArgExprs
486 * in a WindowFunc node.
490 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
491 errmsg("window functions cannot use named arguments"),
492 parser_errposition(pstate, location)));
494 /* parse_agg.c does additional window-func-specific processing */
495 transformWindowFuncCall(pstate, wfunc, over);
497 retval = (Node *) wfunc;
504 /* func_match_argtypes()
506 * Given a list of candidate functions (having the right name and number
507 * of arguments) and an array of input datatype OIDs, produce a shortlist of
508 * those candidates that actually accept the input datatypes (either exactly
509 * or by coercion), and return the number of such candidates.
511 * Note that can_coerce_type will assume that UNKNOWN inputs are coercible to
512 * anything, so candidates will not be eliminated on that basis.
514 * NB: okay to modify input list structure, as long as we find at least
515 * one match. If no match at all, the list must remain unmodified.
518 func_match_argtypes(int nargs,
520 FuncCandidateList raw_candidates,
521 FuncCandidateList *candidates) /* return value */
523 FuncCandidateList current_candidate;
524 FuncCandidateList next_candidate;
529 for (current_candidate = raw_candidates;
530 current_candidate != NULL;
531 current_candidate = next_candidate)
533 next_candidate = current_candidate->next;
534 if (can_coerce_type(nargs, input_typeids, current_candidate->args,
537 current_candidate->next = *candidates;
538 *candidates = current_candidate;
544 } /* func_match_argtypes() */
547 /* func_select_candidate()
548 * Given the input argtype array and more than one candidate
549 * for the function, attempt to resolve the conflict.
551 * Returns the selected candidate if the conflict can be resolved,
552 * otherwise returns NULL.
554 * Note that the caller has already determined that there is no candidate
555 * exactly matching the input argtypes, and has pruned away any "candidates"
556 * that aren't actually coercion-compatible with the input types.
558 * This is also used for resolving ambiguous operator references. Formerly
559 * parse_oper.c had its own, essentially duplicate code for the purpose.
560 * The following comments (formerly in parse_oper.c) are kept to record some
561 * of the history of these heuristics.
565 * This routine is new code, replacing binary_oper_select_candidate()
566 * which dates from v4.2/v1.0.x days. It tries very hard to match up
567 * operators with types, including allowing type coercions if necessary.
568 * The important thing is that the code do as much as possible,
569 * while _never_ doing the wrong thing, where "the wrong thing" would
570 * be returning an operator when other better choices are available,
571 * or returning an operator which is a non-intuitive possibility.
572 * - thomas 1998-05-21
574 * The comments below came from binary_oper_select_candidate(), and
575 * illustrate the issues and choices which are possible:
576 * - thomas 1998-05-20
578 * current wisdom holds that the default operator should be one in which
579 * both operands have the same type (there will only be one such
582 * 7.27.93 - I have decided not to do this; it's too hard to justify, and
583 * it's easy enough to typecast explicitly - avi
584 * [the rest of this routine was commented out since then - ay]
586 * 6/23/95 - I don't complete agree with avi. In particular, casting
587 * floats is a pain for users. Whatever the rationale behind not doing
588 * this is, I need the following special case to work.
590 * In the WHERE clause of a query, if a float is specified without
591 * quotes, we treat it as float8. I added the float48* operators so
592 * that we can operate on float4 and float8. But now we have more than
593 * one matching operator if the right arg is unknown (eg. float
594 * specified with quotes). This break some stuff in the regression
595 * test where there are floats in quotes not properly casted. Below is
596 * the solution. In addition to requiring the operator operates on the
597 * same type for both operands [as in the code Avi originally
598 * commented out], we also require that the operators be equivalent in
599 * some sense. (see equivalentOpersAfterPromotion for details.)
603 func_select_candidate(int nargs,
605 FuncCandidateList candidates)
607 FuncCandidateList current_candidate;
608 FuncCandidateList last_candidate;
609 Oid *current_typeids;
615 Oid input_base_typeids[FUNC_MAX_ARGS];
616 TYPCATEGORY slot_category[FUNC_MAX_ARGS],
618 bool current_is_preferred;
619 bool slot_has_preferred_type[FUNC_MAX_ARGS];
620 bool resolved_unknowns;
622 /* protect local fixed-size arrays */
623 if (nargs > FUNC_MAX_ARGS)
625 (errcode(ERRCODE_TOO_MANY_ARGUMENTS),
626 errmsg_plural("cannot pass more than %d argument to a function",
627 "cannot pass more than %d arguments to a function",
632 * If any input types are domains, reduce them to their base types. This
633 * ensures that we will consider functions on the base type to be "exact
634 * matches" in the exact-match heuristic; it also makes it possible to do
635 * something useful with the type-category heuristics. Note that this
636 * makes it difficult, but not impossible, to use functions declared to
637 * take a domain as an input datatype. Such a function will be selected
638 * over the base-type function only if it is an exact match at all
639 * argument positions, and so was already chosen by our caller.
641 for (i = 0; i < nargs; i++)
642 input_base_typeids[i] = getBaseType(input_typeids[i]);
645 * Run through all candidates and keep those with the most matches on
646 * exact types. Keep all candidates if none match.
650 last_candidate = NULL;
651 for (current_candidate = candidates;
652 current_candidate != NULL;
653 current_candidate = current_candidate->next)
655 current_typeids = current_candidate->args;
657 for (i = 0; i < nargs; i++)
659 if (input_base_typeids[i] != UNKNOWNOID &&
660 current_typeids[i] == input_base_typeids[i])
664 /* take this one as the best choice so far? */
665 if ((nmatch > nbestMatch) || (last_candidate == NULL))
668 candidates = current_candidate;
669 last_candidate = current_candidate;
672 /* no worse than the last choice, so keep this one too? */
673 else if (nmatch == nbestMatch)
675 last_candidate->next = current_candidate;
676 last_candidate = current_candidate;
679 /* otherwise, don't bother keeping this one... */
682 if (last_candidate) /* terminate rebuilt list */
683 last_candidate->next = NULL;
685 if (ncandidates == 1)
689 * Still too many candidates? Now look for candidates which have either
690 * exact matches or preferred types at the args that will require
691 * coercion. (Restriction added in 7.4: preferred type must be of same
692 * category as input type; give no preference to cross-category
693 * conversions to preferred types.) Keep all candidates if none match.
695 for (i = 0; i < nargs; i++) /* avoid multiple lookups */
696 slot_category[i] = TypeCategory(input_base_typeids[i]);
699 last_candidate = NULL;
700 for (current_candidate = candidates;
701 current_candidate != NULL;
702 current_candidate = current_candidate->next)
704 current_typeids = current_candidate->args;
706 for (i = 0; i < nargs; i++)
708 if (input_base_typeids[i] != UNKNOWNOID)
710 if (current_typeids[i] == input_base_typeids[i] ||
711 IsPreferredType(slot_category[i], current_typeids[i]))
716 if ((nmatch > nbestMatch) || (last_candidate == NULL))
719 candidates = current_candidate;
720 last_candidate = current_candidate;
723 else if (nmatch == nbestMatch)
725 last_candidate->next = current_candidate;
726 last_candidate = current_candidate;
731 if (last_candidate) /* terminate rebuilt list */
732 last_candidate->next = NULL;
734 if (ncandidates == 1)
738 * Still too many candidates? Try assigning types for the unknown columns.
740 * NOTE: for a binary operator with one unknown and one non-unknown input,
741 * we already tried the heuristic of looking for a candidate with the
742 * known input type on both sides (see binary_oper_exact()). That's
743 * essentially a special case of the general algorithm we try next.
745 * We do this by examining each unknown argument position to see if we can
746 * determine a "type category" for it. If any candidate has an input
747 * datatype of STRING category, use STRING category (this bias towards
748 * STRING is appropriate since unknown-type literals look like strings).
749 * Otherwise, if all the candidates agree on the type category of this
750 * argument position, use that category. Otherwise, fail because we
751 * cannot determine a category.
753 * If we are able to determine a type category, also notice whether any of
754 * the candidates takes a preferred datatype within the category.
756 * Having completed this examination, remove candidates that accept the
757 * wrong category at any unknown position. Also, if at least one
758 * candidate accepted a preferred type at a position, remove candidates
759 * that accept non-preferred types.
761 * If we are down to one candidate at the end, we win.
763 resolved_unknowns = false;
764 for (i = 0; i < nargs; i++)
768 if (input_base_typeids[i] != UNKNOWNOID)
770 resolved_unknowns = true; /* assume we can do it */
771 slot_category[i] = TYPCATEGORY_INVALID;
772 slot_has_preferred_type[i] = false;
773 have_conflict = false;
774 for (current_candidate = candidates;
775 current_candidate != NULL;
776 current_candidate = current_candidate->next)
778 current_typeids = current_candidate->args;
779 current_type = current_typeids[i];
780 get_type_category_preferred(current_type,
782 ¤t_is_preferred);
783 if (slot_category[i] == TYPCATEGORY_INVALID)
785 /* first candidate */
786 slot_category[i] = current_category;
787 slot_has_preferred_type[i] = current_is_preferred;
789 else if (current_category == slot_category[i])
791 /* more candidates in same category */
792 slot_has_preferred_type[i] |= current_is_preferred;
796 /* category conflict! */
797 if (current_category == TYPCATEGORY_STRING)
799 /* STRING always wins if available */
800 slot_category[i] = current_category;
801 slot_has_preferred_type[i] = current_is_preferred;
806 * Remember conflict, but keep going (might find STRING)
808 have_conflict = true;
812 if (have_conflict && slot_category[i] != TYPCATEGORY_STRING)
814 /* Failed to resolve category conflict at this position */
815 resolved_unknowns = false;
820 if (resolved_unknowns)
822 /* Strip non-matching candidates */
824 last_candidate = NULL;
825 for (current_candidate = candidates;
826 current_candidate != NULL;
827 current_candidate = current_candidate->next)
831 current_typeids = current_candidate->args;
832 for (i = 0; i < nargs; i++)
834 if (input_base_typeids[i] != UNKNOWNOID)
836 current_type = current_typeids[i];
837 get_type_category_preferred(current_type,
839 ¤t_is_preferred);
840 if (current_category != slot_category[i])
845 if (slot_has_preferred_type[i] && !current_is_preferred)
853 /* keep this candidate */
854 last_candidate = current_candidate;
859 /* forget this candidate */
861 last_candidate->next = current_candidate->next;
863 candidates = current_candidate->next;
866 if (last_candidate) /* terminate rebuilt list */
867 last_candidate->next = NULL;
870 if (ncandidates == 1)
873 return NULL; /* failed to select a best candidate */
874 } /* func_select_candidate() */
879 * Find the named function in the system catalogs.
881 * Attempt to find the named function in the system catalogs with
882 * arguments exactly as specified, so that the normal case (exact match)
883 * is as quick as possible.
885 * If an exact match isn't found:
886 * 1) check for possible interpretation as a type coercion request
887 * 2) apply the ambiguous-function resolution rules
889 * Return values *funcid through *true_typeids receive info about the function.
890 * If argdefaults isn't NULL, *argdefaults receives a list of any default
891 * argument expressions that need to be added to the given arguments.
893 * When processing a named- or mixed-notation call (ie, fargnames isn't NIL),
894 * the returned true_typeids and argdefaults are ordered according to the
895 * call's argument ordering: first any positional arguments, then the named
896 * arguments, then defaulted arguments (if needed and allowed by
897 * expand_defaults). Some care is needed if this information is to be compared
898 * to the function's pg_proc entry, but in practice the caller can usually
899 * just work with the call's argument ordering.
901 * We rely primarily on fargnames/nargs/argtypes as the argument description.
902 * The actual expression node list is passed in fargs so that we can check
903 * for type coercion of a constant. Some callers pass fargs == NIL indicating
904 * they don't need that check made. Note also that when fargnames isn't NIL,
905 * the fargs list must be passed if the caller wants actual argument position
906 * information to be returned into the NamedArgExpr nodes.
909 func_get_detail(List *funcname,
914 bool expand_variadic,
915 bool expand_defaults,
916 Oid *funcid, /* return value */
917 Oid *rettype, /* return value */
918 bool *retset, /* return value */
919 int *nvargs, /* return value */
920 Oid **true_typeids, /* return value */
921 List **argdefaults) /* optional return value */
923 FuncCandidateList raw_candidates;
924 FuncCandidateList best_candidate;
926 /* initialize output arguments to silence compiler warnings */
927 *funcid = InvalidOid;
928 *rettype = InvalidOid;
931 *true_typeids = NULL;
935 /* Get list of possible candidates from namespace search */
936 raw_candidates = FuncnameGetCandidates(funcname, nargs, fargnames,
937 expand_variadic, expand_defaults);
940 * Quickly check if there is an exact match to the input datatypes (there
943 for (best_candidate = raw_candidates;
944 best_candidate != NULL;
945 best_candidate = best_candidate->next)
947 if (memcmp(argtypes, best_candidate->args, nargs * sizeof(Oid)) == 0)
951 if (best_candidate == NULL)
954 * If we didn't find an exact match, next consider the possibility
955 * that this is really a type-coercion request: a single-argument
956 * function call where the function name is a type name. If so, and
957 * if the coercion path is RELABELTYPE or COERCEVIAIO, then go ahead
958 * and treat the "function call" as a coercion.
960 * This interpretation needs to be given higher priority than
961 * interpretations involving a type coercion followed by a function
962 * call, otherwise we can produce surprising results. For example, we
963 * want "text(varchar)" to be interpreted as a simple coercion, not as
964 * "text(name(varchar))" which the code below this point is entirely
965 * capable of selecting.
967 * We also treat a coercion of a previously-unknown-type literal
968 * constant to a specific type this way.
970 * The reason we reject COERCION_PATH_FUNC here is that we expect the
971 * cast implementation function to be named after the target type.
972 * Thus the function will be found by normal lookup if appropriate.
974 * The reason we reject COERCION_PATH_ARRAYCOERCE is mainly that you
975 * can't write "foo[] (something)" as a function call. In theory
976 * someone might want to invoke it as "_foo (something)" but we have
977 * never supported that historically, so we can insist that people
978 * write it as a normal cast instead. Lack of historical support is
979 * also the reason for not considering composite-type casts here.
981 * NB: it's important that this code does not exceed what coerce_type
982 * can do, because the caller will try to apply coerce_type if we
983 * return FUNCDETAIL_COERCION. If we return that result for something
984 * coerce_type can't handle, we'll cause infinite recursion between
985 * this module and coerce_type!
987 if (nargs == 1 && fargs != NIL && fargnames == NIL)
989 Oid targetType = FuncNameAsType(funcname);
991 if (OidIsValid(targetType))
993 Oid sourceType = argtypes[0];
994 Node *arg1 = linitial(fargs);
997 if (sourceType == UNKNOWNOID && IsA(arg1, Const))
999 /* always treat typename('literal') as coercion */
1004 CoercionPathType cpathtype;
1007 cpathtype = find_coercion_pathway(targetType, sourceType,
1010 iscoercion = (cpathtype == COERCION_PATH_RELABELTYPE ||
1011 cpathtype == COERCION_PATH_COERCEVIAIO);
1016 /* Treat it as a type coercion */
1017 *funcid = InvalidOid;
1018 *rettype = targetType;
1021 *true_typeids = argtypes;
1022 return FUNCDETAIL_COERCION;
1028 * didn't find an exact match, so now try to match up candidates...
1030 if (raw_candidates != NULL)
1032 FuncCandidateList current_candidates;
1035 ncandidates = func_match_argtypes(nargs,
1038 ¤t_candidates);
1040 /* one match only? then run with it... */
1041 if (ncandidates == 1)
1042 best_candidate = current_candidates;
1045 * multiple candidates? then better decide or throw an error...
1047 else if (ncandidates > 1)
1049 best_candidate = func_select_candidate(nargs,
1051 current_candidates);
1054 * If we were able to choose a best candidate, we're done.
1055 * Otherwise, ambiguous function call.
1057 if (!best_candidate)
1058 return FUNCDETAIL_MULTIPLE;
1067 FuncDetailCode result;
1070 * If processing named args or expanding variadics or defaults, the
1071 * "best candidate" might represent multiple equivalently good
1072 * functions; treat this case as ambiguous.
1074 if (!OidIsValid(best_candidate->oid))
1075 return FUNCDETAIL_MULTIPLE;
1078 * We disallow VARIADIC with named arguments unless the last
1079 * argument (the one with VARIADIC attached) actually matched the
1080 * variadic parameter. This is mere pedantry, really, but some
1083 if (fargnames != NIL && !expand_variadic && nargs > 0 &&
1084 best_candidate->argnumbers[nargs - 1] != nargs - 1)
1085 return FUNCDETAIL_NOTFOUND;
1087 *funcid = best_candidate->oid;
1088 *nvargs = best_candidate->nvargs;
1089 *true_typeids = best_candidate->args;
1092 * If processing named args, return actual argument positions into
1093 * NamedArgExpr nodes in the fargs list. This is a bit ugly but not
1094 * worth the extra notation needed to do it differently.
1096 if (best_candidate->argnumbers != NULL)
1103 NamedArgExpr *na = (NamedArgExpr *) lfirst(lc);
1105 if (IsA(na, NamedArgExpr))
1106 na->argnumber = best_candidate->argnumbers[i];
1111 ftup = SearchSysCache(PROCOID,
1112 ObjectIdGetDatum(best_candidate->oid),
1114 if (!HeapTupleIsValid(ftup)) /* should not happen */
1115 elog(ERROR, "cache lookup failed for function %u",
1116 best_candidate->oid);
1117 pform = (Form_pg_proc) GETSTRUCT(ftup);
1118 *rettype = pform->prorettype;
1119 *retset = pform->proretset;
1120 /* fetch default args if caller wants 'em */
1121 if (argdefaults && best_candidate->ndargs > 0)
1123 Datum proargdefaults;
1128 /* shouldn't happen, FuncnameGetCandidates messed up */
1129 if (best_candidate->ndargs > pform->pronargdefaults)
1130 elog(ERROR, "not enough default arguments");
1132 proargdefaults = SysCacheGetAttr(PROCOID, ftup,
1133 Anum_pg_proc_proargdefaults,
1136 str = TextDatumGetCString(proargdefaults);
1137 defaults = (List *) stringToNode(str);
1138 Assert(IsA(defaults, List));
1141 /* Delete any unused defaults from the returned list */
1142 if (best_candidate->argnumbers != NULL)
1145 * This is a bit tricky in named notation, since the supplied
1146 * arguments could replace any subset of the defaults. We
1147 * work by making a bitmapset of the argnumbers of defaulted
1148 * arguments, then scanning the defaults list and selecting
1149 * the needed items. (This assumes that defaulted arguments
1150 * should be supplied in their positional order.)
1152 Bitmapset *defargnumbers;
1158 defargnumbers = NULL;
1159 firstdefarg = &best_candidate->argnumbers[best_candidate->nargs - best_candidate->ndargs];
1160 for (i = 0; i < best_candidate->ndargs; i++)
1161 defargnumbers = bms_add_member(defargnumbers,
1164 i = pform->pronargs - pform->pronargdefaults;
1165 foreach(lc, defaults)
1167 if (bms_is_member(i, defargnumbers))
1168 newdefaults = lappend(newdefaults, lfirst(lc));
1171 Assert(list_length(newdefaults) == best_candidate->ndargs);
1172 bms_free(defargnumbers);
1173 *argdefaults = newdefaults;
1178 * Defaults for positional notation are lots easier;
1179 * just remove any unwanted ones from the front.
1183 ndelete = list_length(defaults) - best_candidate->ndargs;
1184 while (ndelete-- > 0)
1185 defaults = list_delete_first(defaults);
1186 *argdefaults = defaults;
1189 if (pform->proisagg)
1190 result = FUNCDETAIL_AGGREGATE;
1191 else if (pform->proiswindow)
1192 result = FUNCDETAIL_WINDOWFUNC;
1194 result = FUNCDETAIL_NORMAL;
1195 ReleaseSysCache(ftup);
1199 return FUNCDETAIL_NOTFOUND;
1204 * make_fn_arguments()
1206 * Given the actual argument expressions for a function, and the desired
1207 * input types for the function, add any necessary typecasting to the
1208 * expression tree. Caller should already have verified that casting is
1211 * Caution: given argument list is modified in-place.
1213 * As with coerce_type, pstate may be NULL if no special unknown-Param
1214 * processing is wanted.
1217 make_fn_arguments(ParseState *pstate,
1219 Oid *actual_arg_types,
1220 Oid *declared_arg_types)
1222 ListCell *current_fargs;
1225 foreach(current_fargs, fargs)
1227 /* types don't match? then force coercion using a function call... */
1228 if (actual_arg_types[i] != declared_arg_types[i])
1230 Node *node = (Node *) lfirst(current_fargs);
1233 * If arg is a NamedArgExpr, coerce its input expr instead ---
1234 * we want the NamedArgExpr to stay at the top level of the list.
1236 if (IsA(node, NamedArgExpr))
1238 NamedArgExpr *na = (NamedArgExpr *) node;
1240 node = coerce_type(pstate,
1242 actual_arg_types[i],
1243 declared_arg_types[i], -1,
1245 COERCE_IMPLICIT_CAST,
1247 na->arg = (Expr *) node;
1251 node = coerce_type(pstate,
1253 actual_arg_types[i],
1254 declared_arg_types[i], -1,
1256 COERCE_IMPLICIT_CAST,
1258 lfirst(current_fargs) = node;
1267 * convenience routine to see if a function name matches a type name
1269 * Returns the OID of the matching type, or InvalidOid if none. We ignore
1270 * shell types and complex types.
1273 FuncNameAsType(List *funcname)
1278 typtup = LookupTypeName(NULL, makeTypeNameFromNameList(funcname), NULL);
1282 if (((Form_pg_type) GETSTRUCT(typtup))->typisdefined &&
1283 !OidIsValid(typeTypeRelid(typtup)))
1284 result = typeTypeId(typtup);
1286 result = InvalidOid;
1288 ReleaseSysCache(typtup);
1293 * ParseComplexProjection -
1294 * handles function calls with a single argument that is of complex type.
1295 * If the function call is actually a column projection, return a suitably
1296 * transformed expression tree. If not, return NULL.
1299 ParseComplexProjection(ParseState *pstate, char *funcname, Node *first_arg,
1306 * Special case for whole-row Vars so that we can resolve (foo.*).bar even
1307 * when foo is a reference to a subselect, join, or RECORD function. A
1308 * bonus is that we avoid generating an unnecessary FieldSelect; our
1309 * result can omit the whole-row Var and just be a Var for the selected
1312 * This case could be handled by expandRecordVariable, but it's more
1313 * efficient to do it this way when possible.
1315 if (IsA(first_arg, Var) &&
1316 ((Var *) first_arg)->varattno == InvalidAttrNumber)
1320 rte = GetRTEByRangeTablePosn(pstate,
1321 ((Var *) first_arg)->varno,
1322 ((Var *) first_arg)->varlevelsup);
1323 /* Return a Var if funcname matches a column, else NULL */
1324 return scanRTEForColumn(pstate, rte, funcname, location);
1328 * Else do it the hard way with get_expr_result_type().
1330 * If it's a Var of type RECORD, we have to work even harder: we have to
1331 * find what the Var refers to, and pass that to get_expr_result_type.
1332 * That task is handled by expandRecordVariable().
1334 if (IsA(first_arg, Var) &&
1335 ((Var *) first_arg)->vartype == RECORDOID)
1336 tupdesc = expandRecordVariable(pstate, (Var *) first_arg, 0);
1337 else if (get_expr_result_type(first_arg, NULL, &tupdesc) != TYPEFUNC_COMPOSITE)
1338 return NULL; /* unresolvable RECORD type */
1341 for (i = 0; i < tupdesc->natts; i++)
1343 Form_pg_attribute att = tupdesc->attrs[i];
1345 if (strcmp(funcname, NameStr(att->attname)) == 0 &&
1348 /* Success, so generate a FieldSelect expression */
1349 FieldSelect *fselect = makeNode(FieldSelect);
1351 fselect->arg = (Expr *) first_arg;
1352 fselect->fieldnum = i + 1;
1353 fselect->resulttype = att->atttypid;
1354 fselect->resulttypmod = att->atttypmod;
1355 return (Node *) fselect;
1359 return NULL; /* funcname does not match any column */
1363 * funcname_signature_string
1364 * Build a string representing a function name, including arg types.
1365 * The result is something like "foo(integer)".
1367 * If argnames isn't NIL, it is a list of C strings representing the actual
1368 * arg names for the last N arguments. This must be considered part of the
1369 * function signature too, when dealing with named-notation function calls.
1371 * This is typically used in the construction of function-not-found error
1375 funcname_signature_string(const char *funcname, int nargs,
1376 List *argnames, const Oid *argtypes)
1378 StringInfoData argbuf;
1383 initStringInfo(&argbuf);
1385 appendStringInfo(&argbuf, "%s(", funcname);
1387 numposargs = nargs - list_length(argnames);
1388 lc = list_head(argnames);
1390 for (i = 0; i < nargs; i++)
1393 appendStringInfoString(&argbuf, ", ");
1394 appendStringInfoString(&argbuf, format_type_be(argtypes[i]));
1395 if (i >= numposargs)
1397 appendStringInfo(&argbuf, " AS %s", (char *) lfirst(lc));
1402 appendStringInfoChar(&argbuf, ')');
1404 return argbuf.data; /* return palloc'd string buffer */
1408 * func_signature_string
1409 * As above, but function name is passed as a qualified name list.
1412 func_signature_string(List *funcname, int nargs,
1413 List *argnames, const Oid *argtypes)
1415 return funcname_signature_string(NameListToString(funcname),
1416 nargs, argnames, argtypes);
1421 * Given a possibly-qualified function name and a set of argument types,
1422 * look up the function.
1424 * If the function name is not schema-qualified, it is sought in the current
1425 * namespace search path.
1427 * If the function is not found, we return InvalidOid if noError is true,
1428 * else raise an error.
1431 LookupFuncName(List *funcname, int nargs, const Oid *argtypes, bool noError)
1433 FuncCandidateList clist;
1435 clist = FuncnameGetCandidates(funcname, nargs, NIL, false, false);
1439 if (memcmp(argtypes, clist->args, nargs * sizeof(Oid)) == 0)
1441 clist = clist->next;
1446 (errcode(ERRCODE_UNDEFINED_FUNCTION),
1447 errmsg("function %s does not exist",
1448 func_signature_string(funcname, nargs,
1456 * Convenience routine to look up a type, silently accepting shell types
1459 LookupTypeNameOid(const TypeName *typename)
1464 typtup = LookupTypeName(NULL, typename, NULL);
1467 (errcode(ERRCODE_UNDEFINED_OBJECT),
1468 errmsg("type \"%s\" does not exist",
1469 TypeNameToString(typename))));
1470 result = typeTypeId(typtup);
1471 ReleaseSysCache(typtup);
1476 * LookupFuncNameTypeNames
1477 * Like LookupFuncName, but the argument types are specified by a
1478 * list of TypeName nodes.
1481 LookupFuncNameTypeNames(List *funcname, List *argtypes, bool noError)
1483 Oid argoids[FUNC_MAX_ARGS];
1486 ListCell *args_item;
1488 argcount = list_length(argtypes);
1489 if (argcount > FUNC_MAX_ARGS)
1491 (errcode(ERRCODE_TOO_MANY_ARGUMENTS),
1492 errmsg_plural("functions cannot have more than %d argument",
1493 "functions cannot have more than %d arguments",
1497 args_item = list_head(argtypes);
1498 for (i = 0; i < argcount; i++)
1500 TypeName *t = (TypeName *) lfirst(args_item);
1502 argoids[i] = LookupTypeNameOid(t);
1503 args_item = lnext(args_item);
1506 return LookupFuncName(funcname, argcount, argoids, noError);
1510 * LookupAggNameTypeNames
1511 * Find an aggregate function given a name and list of TypeName nodes.
1513 * This is almost like LookupFuncNameTypeNames, but the error messages refer
1514 * to aggregates rather than plain functions, and we verify that the found
1515 * function really is an aggregate.
1518 LookupAggNameTypeNames(List *aggname, List *argtypes, bool noError)
1520 Oid argoids[FUNC_MAX_ARGS];
1528 argcount = list_length(argtypes);
1529 if (argcount > FUNC_MAX_ARGS)
1531 (errcode(ERRCODE_TOO_MANY_ARGUMENTS),
1532 errmsg_plural("functions cannot have more than %d argument",
1533 "functions cannot have more than %d arguments",
1538 foreach(lc, argtypes)
1540 TypeName *t = (TypeName *) lfirst(lc);
1542 argoids[i] = LookupTypeNameOid(t);
1546 oid = LookupFuncName(aggname, argcount, argoids, true);
1548 if (!OidIsValid(oid))
1554 (errcode(ERRCODE_UNDEFINED_FUNCTION),
1555 errmsg("aggregate %s(*) does not exist",
1556 NameListToString(aggname))));
1559 (errcode(ERRCODE_UNDEFINED_FUNCTION),
1560 errmsg("aggregate %s does not exist",
1561 func_signature_string(aggname, argcount,
1565 /* Make sure it's an aggregate */
1566 ftup = SearchSysCache(PROCOID,
1567 ObjectIdGetDatum(oid),
1569 if (!HeapTupleIsValid(ftup)) /* should not happen */
1570 elog(ERROR, "cache lookup failed for function %u", oid);
1571 pform = (Form_pg_proc) GETSTRUCT(ftup);
1573 if (!pform->proisagg)
1575 ReleaseSysCache(ftup);
1578 /* we do not use the (*) notation for functions... */
1580 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1581 errmsg("function %s is not an aggregate",
1582 func_signature_string(aggname, argcount,
1586 ReleaseSysCache(ftup);