1/*-------------------------------------------------------------------------
4 * handle function calls in parser
6 * Portions Copyright (c) 1996-2025, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
11 * src/backend/parser/parse_func.c
13 *-------------------------------------------------------------------------
38/* Possible error codes from LookupFuncNameInternal */
48 List *fargs,
int numAggregatedArgs,
49 Oid *actual_arg_types,
Oid *declared_arg_types);
52 Node *first_arg,
int location);
54 int nargs,
const Oid *argtypes,
55 bool include_out_arguments,
bool missing_ok,
60 * Parse a function call
62 * For historical reasons, Postgres tries to treat the notations tab.col
63 * and col(tab) as equivalent: if a single-argument function call has an
64 * argument of complex type and the (unqualified) function name matches
65 * any attribute of the type, we can interpret it as a column projection.
66 * Conversely a function of a single complex-type argument can be written
67 * like a column reference, allowing functions to act like computed columns.
69 * If both interpretations are possible, we prefer the one matching the
70 * syntactic form, but otherwise the form does not matter.
72 * Hence, both cases come through here. If fn is null, we're dealing with
73 * column syntax not function syntax. In the function-syntax case,
74 * the FuncCall struct is needed to carry various decoration that applies
75 * to aggregate and window functions.
77 * Also, when fn is null, we return NULL on failure rather than
78 * reporting a no-such-function error.
80 * The argument expressions (in fargs) must have been transformed
81 * already. However, nothing in *fn has been transformed.
83 * last_srf should be a copy of pstate->p_last_srf from just before we
84 * started transforming fargs. If the caller knows that fargs couldn't
85 * contain any SRF calls, last_srf can just be pstate->p_last_srf.
87 * proc_call is true if we are considering a CALL statement, so that the
88 * name must resolve to a procedure name, not anything else. This flag
89 * also specifies that the argument list includes any OUT-mode arguments.
95 bool is_column = (
fn == NULL);
97 Expr *agg_filter = NULL;
99 bool agg_within_group = (
fn ?
fn->agg_within_group :
false);
100 bool agg_star = (
fn ?
fn->agg_star :
false);
101 bool agg_distinct = (
fn ?
fn->agg_distinct :
false);
102 bool func_variadic = (
fn ?
fn->func_variadic :
false);
105 bool could_be_projection;
109 Node *first_arg = NULL;
113 Oid *declared_arg_types;
126 * If there's an aggregate filter, transform it using transformWhereClause
128 if (
fn &&
fn->agg_filter != NULL)
134 * Most of the rest of the parser just assumes that functions do not have
135 * more than FUNC_MAX_ARGS parameters. We have to test here to protect
136 * against array overruns, etc. Of course, this may not be a function,
137 * but the test doesn't hurt.
141 (
errcode(ERRCODE_TOO_MANY_ARGUMENTS),
142 errmsg_plural(
"cannot pass more than %d argument to a function",
143 "cannot pass more than %d arguments to a function",
149 * Extract arg type info in preparation for function lookup.
151 * If any arguments are Param markers of type VOID, we discard them from
152 * the parameter list. This is a hack to allow the JDBC driver to not have
153 * to distinguish "input" and "output" parameter symbols while parsing
154 * function-call constructs. Don't do this if dealing with column syntax,
155 * nor if we had WITHIN GROUP (because in that case it's critical to keep
156 * the argument count unchanged).
165 !is_column && !agg_within_group)
171 actual_arg_types[nargs++] = argtype;
175 * Check for named arguments; if there are any, build a list of names.
177 * We allow mixed notation (some named and some not), but only with all
178 * the named parameters after all the unnamed ones. So the name list
179 * corresponds to the last N actual parameters and we don't need any extra
180 * bookkeeping to match things up.
192 /* Reject duplicate arg names */
193 foreach(lc, argnames)
195 if (strcmp(na->name, (
char *)
lfirst(lc)) == 0)
197 (
errcode(ERRCODE_SYNTAX_ERROR),
198 errmsg(
"argument name \"%s\" used more than once",
202 argnames =
lappend(argnames, na->name);
208 (
errcode(ERRCODE_SYNTAX_ERROR),
209 errmsg(
"positional argument cannot follow named argument"),
217 Assert(first_arg != NULL);
221 * Decide whether it's legitimate to consider the construct to be a column
222 * projection. For that, there has to be a single argument of complex
223 * type, the function name must not be qualified, and there cannot be any
224 * syntactic decoration that'd require it to be a function (such as
225 * aggregate or variadic decoration, or named arguments).
227 could_be_projection = (nargs == 1 && !proc_call &&
228 agg_order ==
NIL && agg_filter == NULL &&
229 !agg_star && !agg_distinct && over == NULL &&
230 !func_variadic && argnames ==
NIL &&
232 (actual_arg_types[0] == RECORDOID ||
236 * If it's column syntax, check for column projection case first.
238 if (could_be_projection && is_column)
248 * If ParseComplexProjection doesn't recognize it as a projection,
254 * func_get_detail looks up the function in the catalogs, does
255 * disambiguation for polymorphic functions, handles inheritance, and
256 * returns the funcid and type and set or singleton status of the
257 * function's return value. It also returns the true argument types to
260 * Note: for a named-notation or variadic function call, the reported
261 * "true" types aren't really what is in pg_proc: the types are reordered
262 * to match the given argument order of named arguments, and a variadic
263 * argument is replaced by a suitable number of copies of its element
264 * type. We'll fix up the variadic case below. We may also have to deal
265 * with default arguments.
272 !func_variadic,
true, proc_call,
274 &funcid, &rettype, &retset,
276 &declared_arg_types, &argdefaults);
281 * Check for various wrong-kind-of-routine cases.
284 /* If this is a CALL, reject things that aren't procedures */
291 (
errcode(ERRCODE_WRONG_OBJECT_TYPE),
292 errmsg(
"%s is not a procedure",
296 errhint(
"To call a function, use SELECT."),
298 /* Conversely, if not a CALL, reject procedures */
301 (
errcode(ERRCODE_WRONG_OBJECT_TYPE),
302 errmsg(
"%s is a procedure",
306 errhint(
"To call a procedure, use CALL."),
314 * In these cases, complain if there was anything indicating it must
315 * be an aggregate or window function.
319 (
errcode(ERRCODE_WRONG_OBJECT_TYPE),
320 errmsg(
"%s(*) specified, but %s is not an aggregate function",
326 (
errcode(ERRCODE_WRONG_OBJECT_TYPE),
327 errmsg(
"DISTINCT specified, but %s is not an aggregate function",
330 if (agg_within_group)
332 (
errcode(ERRCODE_WRONG_OBJECT_TYPE),
333 errmsg(
"WITHIN GROUP specified, but %s is not an aggregate function",
336 if (agg_order !=
NIL)
338 (
errcode(ERRCODE_WRONG_OBJECT_TYPE),
339 errmsg(
"ORDER BY specified, but %s is not an aggregate function",
344 (
errcode(ERRCODE_WRONG_OBJECT_TYPE),
345 errmsg(
"FILTER specified, but %s is not an aggregate function",
350 (
errcode(ERRCODE_WRONG_OBJECT_TYPE),
351 errmsg(
"OVER specified, but %s is not a window function nor an aggregate function",
357 * So far so good, so do some fdresult-type-specific processing.
361 /* Nothing special to do for these cases. */
366 * It's an aggregate; fetch needed info from the pg_aggregate entry.
374 elog(
ERROR,
"cache lookup failed for aggregate %u", funcid);
376 aggkind = classForm->aggkind;
377 catDirectArgs = classForm->aggnumdirectargs;
380 /* Now check various disallowed cases. */
381 if (AGGKIND_IS_ORDERED_SET(aggkind))
383 int numAggregatedArgs;
386 if (!agg_within_group)
388 (
errcode(ERRCODE_WRONG_OBJECT_TYPE),
389 errmsg(
"WITHIN GROUP is required for ordered-set aggregate %s",
394 (
errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
395 errmsg(
"OVER is not supported for ordered-set aggregate %s",
398 /* gram.y rejects DISTINCT + WITHIN GROUP */
400 /* gram.y rejects VARIADIC + WITHIN GROUP */
404 * Since func_get_detail was working with an undifferentiated list
405 * of arguments, it might have selected an aggregate that doesn't
406 * really match because it requires a different division of direct
407 * and aggregated arguments. Check that the number of direct
408 * arguments is actually OK; if not, throw an "undefined function"
409 * error, similarly to the case where a misplaced ORDER BY is used
410 * in a regular aggregate call.
413 numDirectArgs = nargs - numAggregatedArgs;
414 Assert(numDirectArgs >= 0);
418 /* Test is simple if aggregate isn't variadic */
419 if (numDirectArgs != catDirectArgs)
421 (
errcode(ERRCODE_UNDEFINED_FUNCTION),
422 errmsg(
"function %s does not exist",
426 errhint_plural(
"There is an ordered-set aggregate %s, but it requires %d direct argument, not %d.",
427 "There is an ordered-set aggregate %s, but it requires %d direct arguments, not %d.",
430 catDirectArgs, numDirectArgs),
436 * If it's variadic, we have two cases depending on whether
437 * the agg was "... ORDER BY VARIADIC" or "..., VARIADIC ORDER
438 * BY VARIADIC". It's the latter if catDirectArgs equals
439 * pronargs; to save a catalog lookup, we reverse-engineer
440 * pronargs from the info we got from func_get_detail.
449 /* VARIADIC isn't part of direct args, so still easy */
450 if (numDirectArgs != catDirectArgs)
452 (
errcode(ERRCODE_UNDEFINED_FUNCTION),
453 errmsg(
"function %s does not exist",
457 errhint_plural(
"There is an ordered-set aggregate %s, but it requires %d direct argument, not %d.",
458 "There is an ordered-set aggregate %s, but it requires %d direct arguments, not %d.",
461 catDirectArgs, numDirectArgs),
467 * Both direct and aggregated args were declared variadic.
468 * For a standard ordered-set aggregate, it's okay as long
469 * as there aren't too few direct args. For a
470 * hypothetical-set aggregate, we assume that the
471 * hypothetical arguments are those that matched the
472 * variadic parameter; there must be just as many of them
473 * as there are aggregated arguments.
475 if (aggkind == AGGKIND_HYPOTHETICAL)
477 if (nvargs != 2 * numAggregatedArgs)
479 (
errcode(ERRCODE_UNDEFINED_FUNCTION),
480 errmsg(
"function %s does not exist",
484 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).",
486 nvargs - numAggregatedArgs, numAggregatedArgs),
491 if (nvargs <= numAggregatedArgs)
493 (
errcode(ERRCODE_UNDEFINED_FUNCTION),
494 errmsg(
"function %s does not exist",
498 errhint_plural(
"There is an ordered-set aggregate %s, but it requires at least %d direct argument.",
499 "There is an ordered-set aggregate %s, but it requires at least %d direct arguments.",
508 /* Check type matching of hypothetical arguments */
509 if (aggkind == AGGKIND_HYPOTHETICAL)
511 actual_arg_types, declared_arg_types);
515 /* Normal aggregate, so it can't have WITHIN GROUP */
516 if (agg_within_group)
518 (
errcode(ERRCODE_WRONG_OBJECT_TYPE),
519 errmsg(
"%s is not an ordered-set aggregate, so it cannot have WITHIN GROUP",
523 /* It also can't treat nulls as a window function */
526 (
errcode(ERRCODE_WRONG_OBJECT_TYPE),
527 errmsg(
"aggregate functions do not accept RESPECT/IGNORE NULLS"),
534 * True window functions must be called with a window definition.
538 (
errcode(ERRCODE_WRONG_OBJECT_TYPE),
539 errmsg(
"window function %s requires an OVER clause",
542 /* And, per spec, WITHIN GROUP isn't allowed */
543 if (agg_within_group)
545 (
errcode(ERRCODE_WRONG_OBJECT_TYPE),
546 errmsg(
"window function %s cannot have WITHIN GROUP",
553 * We interpreted it as a type coercion. coerce_type can handle these
554 * cases, so why duplicate code...
557 actual_arg_types[0], rettype, -1,
563 * We found multiple possible functional matches. If we are dealing
564 * with attribute notation, return failure, letting the caller report
565 * "no such column" (we already determined there wasn't one). If
566 * dealing with function notation, report "ambiguous function",
567 * regardless of whether there's also a column by this name.
574 (
errcode(ERRCODE_AMBIGUOUS_FUNCTION),
575 errmsg(
"procedure %s is not unique",
578 errdetail(
"Could not choose a best candidate procedure."),
579 errhint(
"You might need to add explicit type casts."),
583 (
errcode(ERRCODE_AMBIGUOUS_FUNCTION),
584 errmsg(
"function %s is not unique",
587 errdetail(
"Could not choose a best candidate function."),
588 errhint(
"You might need to add explicit type casts."),
594 * Not found as a function. If we are dealing with attribute
595 * notation, return failure, letting the caller report "no such
596 * column" (we already determined there wasn't one).
602 * Check for column projection interpretation, since we didn't before.
604 if (could_be_projection)
615 * No function, and no column either. Since we're dealing with
616 * function notation, report "function/procedure does not exist".
617 * Depending on what was returned in fgc_flags, we can add some color
618 * to that with detail or hint messages.
620 if (
list_length(agg_order) > 1 && !agg_within_group)
622 /* It's agg(x, ORDER BY y,z) ... perhaps misplaced ORDER BY */
624 (
errcode(ERRCODE_UNDEFINED_FUNCTION),
625 errmsg(
"function %s does not exist",
628 errdetail(
"No aggregate function matches the given name and argument types."),
629 errhint(
"Perhaps you misplaced ORDER BY; ORDER BY must appear "
630 "after all regular arguments of the aggregate."),
635 (
errcode(ERRCODE_UNDEFINED_FUNCTION),
636 errmsg(
"procedure %s does not exist",
644 (
errcode(ERRCODE_UNDEFINED_FUNCTION),
645 errmsg(
"function %s does not exist",
654 * If there are default arguments, we have to include their types in
655 * actual_arg_types for the purpose of checking generic type consistency.
656 * However, we do NOT put them into the generated parse node, because
657 * their actual values might change before the query gets run. The
658 * planner has to insert the up-to-date values at plan time.
660 nargsplusdefs = nargs;
661 foreach(l, argdefaults)
665 /* probably shouldn't happen ... */
668 (
errcode(ERRCODE_TOO_MANY_ARGUMENTS),
669 errmsg_plural(
"cannot pass more than %d argument to a function",
670 "cannot pass more than %d arguments to a function",
675 actual_arg_types[nargsplusdefs++] =
exprType(expr);
679 * enforce consistency with polymorphic argument and return types,
680 * possibly adjusting return type or declared_arg_types (which will be
681 * used as the cast destination by make_fn_arguments)
689 /* perform the necessary typecasting of arguments */
693 * If the function isn't actually variadic, forget any VARIADIC decoration
694 * on the call. (Perhaps we should throw an error instead, but
695 * historically we've allowed people to write that.)
700 func_variadic =
false;
704 * If it's a variadic function call, transform the last nvargs arguments
705 * into an array --- unless it's an "any" variadic.
707 if (nvargs > 0 && vatype != ANYOID)
710 int non_var_args = nargs - nvargs;
713 Assert(non_var_args >= 0);
717 newa->elements = vargs;
718 /* assume all the variadic arguments were coerced to the same type */
723 (
errcode(ERRCODE_UNDEFINED_OBJECT),
724 errmsg(
"could not find array type for data type %s",
727 /* array_collid will be set by parse_collate.c */
728 newa->multidims =
false;
733 /* We could not have had VARIADIC marking before ... */
735 /* ... but now, it's a VARIADIC call */
736 func_variadic =
true;
740 * If an "any" variadic is called with explicit VARIADIC marking, insist
741 * that the variadic parameter be of some array type.
743 if (nargs > 0 && vatype == ANYOID && func_variadic)
745 Oid va_arr_typid = actual_arg_types[nargs - 1];
749 (
errcode(ERRCODE_DATATYPE_MISMATCH),
750 errmsg(
"VARIADIC argument must be an array"),
755 /* if it returns a set, check that's OK */
759 /* build the appropriate output structure */
764 funcexpr->
funcid = funcid;
765 funcexpr->funcresulttype = rettype;
766 funcexpr->funcretset = retset;
767 funcexpr->funcvariadic = func_variadic;
768 funcexpr->funcformat = funcformat;
769 /* funccollid and inputcollid will be set by parse_collate.c */
770 funcexpr->
args = fargs;
773 retval = (
Node *) funcexpr;
777 /* aggregate function */
781 aggref->aggtype = rettype;
782 /* aggcollid and inputcollid will be set by parse_collate.c */
783 aggref->aggtranstype =
InvalidOid;
/* will be set by planner */
784 /* aggargtypes will be set by transformAggregateCall */
785 /* aggdirectargs and args will be set by transformAggregateCall */
786 /* aggorder and aggdistinct will be set by transformAggregateCall */
788 aggref->aggstar = agg_star;
789 aggref->aggvariadic = func_variadic;
790 aggref->aggkind = aggkind;
791 aggref->aggpresorted =
false;
792 /* agglevelsup will be set by transformAggregateCall */
794 aggref->aggno = -1;
/* planner will set aggno and aggtransno */
795 aggref->aggtransno = -1;
799 * Reject attempt to call a parameterless aggregate without (*)
800 * syntax. This is mere pedantry but some folks insisted ...
802 if (fargs ==
NIL && !agg_star && !agg_within_group)
804 (
errcode(ERRCODE_WRONG_OBJECT_TYPE),
805 errmsg(
"%s(*) must be used to call a parameterless aggregate function",
811 (
errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
812 errmsg(
"aggregates cannot return sets"),
816 * We might want to support named arguments later, but disallow it for
817 * now. We'd need to figure out the parsed representation (should the
818 * NamedArgExprs go above or below the TargetEntry nodes?) and then
819 * teach the planner to reorder the list properly. Or maybe we could
820 * make transformAggregateCall do that? However, if you'd also like
821 * to allow default arguments for aggregates, we'd need to do it in
822 * planning to avoid semantic problems.
826 (
errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
827 errmsg(
"aggregates cannot use named arguments"),
830 /* parse_agg.c does additional aggregate-specific processing */
833 retval = (
Node *) aggref;
837 /* window function */
840 Assert(over);
/* lack of this was checked above */
841 Assert(!agg_within_group);
/* also checked above */
844 wfunc->wintype = rettype;
845 /* wincollid and inputcollid will be set by parse_collate.c */
847 /* winref will be set by transformWindowFuncCall */
848 wfunc->winstar = agg_star;
852 wfunc->runCondition =
NIL;
856 * agg_star is allowed for aggregate functions but distinct isn't
860 (
errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
861 errmsg(
"DISTINCT is not implemented for window functions"),
865 * Reject attempt to call a parameterless aggregate without (*)
866 * syntax. This is mere pedantry but some folks insisted ...
868 if (wfunc->winagg && fargs ==
NIL && !agg_star)
870 (
errcode(ERRCODE_WRONG_OBJECT_TYPE),
871 errmsg(
"%s(*) must be used to call a parameterless aggregate function",
876 * ordered aggs not allowed in windows yet
878 if (agg_order !=
NIL)
880 (
errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
881 errmsg(
"aggregate ORDER BY is not implemented for window functions"),
885 * FILTER is not yet supported with true window functions
887 if (!wfunc->winagg && agg_filter)
889 (
errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
890 errmsg(
"FILTER is not implemented for non-aggregate window functions"),
894 * Window functions can't either take or return sets
898 (
errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
899 errmsg(
"window function calls cannot contain set-returning function calls"),
900 errhint(
"You might be able to move the set-returning function into a LATERAL FROM item."),
906 (
errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
907 errmsg(
"window functions cannot return sets"),
910 /* parse_agg.c does additional window-func-specific processing */
913 retval = (
Node *) wfunc;
916 /* if it returns a set, remember it for error checks at higher levels */
924 * Interpret the fgc_flags and issue a suitable detail or hint message.
926 * Helper function to reduce code duplication while throwing a
927 * function-not-found error.
933 * If not FGC_NAME_VISIBLE, we shouldn't raise the question of whether the
934 * arguments are wrong. If the function name was not schema-qualified,
935 * it's helpful to distinguish between doesn't-exist-anywhere and
936 * not-in-search-path; but if it was, there's really nothing to add to the
937 * basic "function/procedure %s does not exist" message.
939 * Note: we passed missing_ok = false to FuncnameGetCandidates, so there's
940 * no need to consider FGC_SCHEMA_EXISTS here: we'd have already thrown an
941 * error if an explicitly-given schema doesn't exist.
946 return 0;
/* schema-qualified name */
950 return errdetail(
"There is no procedure of that name.");
952 return errdetail(
"There is no function of that name.");
957 return errdetail(
"A procedure of that name exists, but it is not in the search_path.");
959 return errdetail(
"A function of that name exists, but it is not in the search_path.");
964 * Next, complain if nothing had the right number of arguments. (This
965 * takes precedence over wrong-argnames cases because we won't even look
966 * at the argnames unless there's a workable number of arguments.)
971 return errdetail(
"No procedure of that name accepts the given number of arguments.");
973 return errdetail(
"No function of that name accepts the given number of arguments.");
977 * If there are argnames, and we failed to match them, again we should
978 * mention that and not bring up the argument types.
983 return errdetail(
"No procedure of that name accepts the given argument names.");
985 return errdetail(
"No function of that name accepts the given argument names.");
989 * We could have matched all the given argnames and still not have had a
990 * valid call, either because of improper use of mixed notation, or
991 * because of missing arguments, or because the user misused VARIADIC. The
992 * rules about named-argument matching are finicky enough that it's worth
993 * trying to be specific about the problem. (The messages here are chosen
994 * with full knowledge of the steps that namespace.c uses while checking a
998 return errdetail(
"In the closest available match, "
999 "an argument was specified both positionally and by name.");
1002 return errdetail(
"In the closest available match, "
1003 "not all required arguments were supplied.");
1006 return errhint(
"This call would be correct if the variadic array were labeled VARIADIC and placed last.");
1009 return errhint(
"The VARIADIC parameter must be placed last, even when using argument names.");
1012 * Otherwise, the problem must be incorrect argument types.
1015 (void)
errdetail(
"No procedure of that name accepts the given argument types.");
1017 (
void)
errdetail(
"No function of that name accepts the given argument types.");
1018 return errhint(
"You might need to add explicit type casts.");
1022/* func_match_argtypes()
1024 * Given a list of candidate functions (having the right name and number
1025 * of arguments) and an array of input datatype OIDs, produce a shortlist of
1026 * those candidates that actually accept the input datatypes (either exactly
1027 * or by coercion), and return the number of such candidates.
1029 * Note that can_coerce_type will assume that UNKNOWN inputs are coercible to
1030 * anything, so candidates will not be eliminated on that basis.
1032 * NB: okay to modify input list structure, as long as we find at least
1033 * one match. If no match at all, the list must remain unmodified.
1043 int ncandidates = 0;
1047 for (current_candidate = raw_candidates;
1048 current_candidate != NULL;
1049 current_candidate = next_candidate)
1051 next_candidate = current_candidate->
next;
1055 current_candidate->
next = *candidates;
1056 *candidates = current_candidate;
1062}
/* func_match_argtypes() */
1065/* func_select_candidate()
1066 * Given the input argtype array and more than one candidate
1067 * for the function, attempt to resolve the conflict.
1069 * Returns the selected candidate if the conflict can be resolved,
1070 * otherwise returns NULL.
1072 * Note that the caller has already determined that there is no candidate
1073 * exactly matching the input argtypes, and has pruned away any "candidates"
1074 * that aren't actually coercion-compatible with the input types.
1076 * This is also used for resolving ambiguous operator references. Formerly
1077 * parse_oper.c had its own, essentially duplicate code for the purpose.
1078 * The following comments (formerly in parse_oper.c) are kept to record some
1079 * of the history of these heuristics.
1083 * This routine is new code, replacing binary_oper_select_candidate()
1084 * which dates from v4.2/v1.0.x days. It tries very hard to match up
1085 * operators with types, including allowing type coercions if necessary.
1086 * The important thing is that the code do as much as possible,
1087 * while _never_ doing the wrong thing, where "the wrong thing" would
1088 * be returning an operator when other better choices are available,
1089 * or returning an operator which is a non-intuitive possibility.
1090 * - thomas 1998年05月21日
1092 * The comments below came from binary_oper_select_candidate(), and
1093 * illustrate the issues and choices which are possible:
1094 * - thomas 1998年05月20日
1096 * current wisdom holds that the default operator should be one in which
1097 * both operands have the same type (there will only be one such
1100 * 7.27.93 - I have decided not to do this; it's too hard to justify, and
1101 * it's easy enough to typecast explicitly - avi
1102 * [the rest of this routine was commented out since then - ay]
1104 * 6/23/95 - I don't complete agree with avi. In particular, casting
1105 * floats is a pain for users. Whatever the rationale behind not doing
1106 * this is, I need the following special case to work.
1108 * In the WHERE clause of a query, if a float is specified without
1109 * quotes, we treat it as float8. I added the float48* operators so
1110 * that we can operate on float4 and float8. But now we have more than
1111 * one matching operator if the right arg is unknown (eg. float
1112 * specified with quotes). This break some stuff in the regression
1113 * test where there are floats in quotes not properly casted. Below is
1114 * the solution. In addition to requiring the operator operates on the
1115 * same type for both operands [as in the code Avi originally
1116 * commented out], we also require that the operators be equivalent in
1117 * some sense. (see equivalentOpersAfterPromotion for details.)
1128 Oid *current_typeids;
1138 bool current_is_preferred;
1140 bool resolved_unknowns;
1142 /* protect local fixed-size arrays */
1145 (
errcode(ERRCODE_TOO_MANY_ARGUMENTS),
1146 errmsg_plural(
"cannot pass more than %d argument to a function",
1147 "cannot pass more than %d arguments to a function",
1152 * If any input types are domains, reduce them to their base types. This
1153 * ensures that we will consider functions on the base type to be "exact
1154 * matches" in the exact-match heuristic; it also makes it possible to do
1155 * something useful with the type-category heuristics. Note that this
1156 * makes it difficult, but not impossible, to use functions declared to
1157 * take a domain as an input datatype. Such a function will be selected
1158 * over the base-type function only if it is an exact match at all
1159 * argument positions, and so was already chosen by our caller.
1161 * While we're at it, count the number of unknown-type arguments for use
1165 for (
i = 0;
i < nargs;
i++)
1167 if (input_typeids[
i] != UNKNOWNOID)
1171 /* no need to call getBaseType on UNKNOWNOID */
1172 input_base_typeids[
i] = UNKNOWNOID;
1178 * Run through all candidates and keep those with the most matches on
1179 * exact types. Keep all candidates if none match.
1183 last_candidate = NULL;
1184 for (current_candidate = candidates;
1185 current_candidate != NULL;
1186 current_candidate = current_candidate->
next)
1188 current_typeids = current_candidate->
args;
1190 for (
i = 0;
i < nargs;
i++)
1192 if (input_base_typeids[
i] != UNKNOWNOID &&
1193 current_typeids[
i] == input_base_typeids[
i])
1197 /* take this one as the best choice so far? */
1198 if ((nmatch > nbestMatch) || (last_candidate == NULL))
1200 nbestMatch = nmatch;
1201 candidates = current_candidate;
1202 last_candidate = current_candidate;
1205 /* no worse than the last choice, so keep this one too? */
1206 else if (nmatch == nbestMatch)
1208 last_candidate->
next = current_candidate;
1209 last_candidate = current_candidate;
1212 /* otherwise, don't bother keeping this one... */
1215 if (last_candidate)
/* terminate rebuilt list */
1216 last_candidate->
next = NULL;
1218 if (ncandidates == 1)
1222 * Still too many candidates? Now look for candidates which have either
1223 * exact matches or preferred types at the args that will require
1224 * coercion. (Restriction added in 7.4: preferred type must be of same
1225 * category as input type; give no preference to cross-category
1226 * conversions to preferred types.) Keep all candidates if none match.
1228 for (
i = 0;
i < nargs;
i++)
/* avoid multiple lookups */
1232 last_candidate = NULL;
1233 for (current_candidate = candidates;
1234 current_candidate != NULL;
1235 current_candidate = current_candidate->
next)
1237 current_typeids = current_candidate->
args;
1239 for (
i = 0;
i < nargs;
i++)
1241 if (input_base_typeids[
i] != UNKNOWNOID)
1243 if (current_typeids[
i] == input_base_typeids[
i] ||
1249 if ((nmatch > nbestMatch) || (last_candidate == NULL))
1251 nbestMatch = nmatch;
1252 candidates = current_candidate;
1253 last_candidate = current_candidate;
1256 else if (nmatch == nbestMatch)
1258 last_candidate->
next = current_candidate;
1259 last_candidate = current_candidate;
1264 if (last_candidate)
/* terminate rebuilt list */
1265 last_candidate->
next = NULL;
1267 if (ncandidates == 1)
1271 * Still too many candidates? Try assigning types for the unknown inputs.
1273 * If there are no unknown inputs, we have no more heuristics that apply,
1277 return NULL;
/* failed to select a best candidate */
1280 * The next step examines each unknown argument position to see if we can
1281 * determine a "type category" for it. If any candidate has an input
1282 * datatype of STRING category, use STRING category (this bias towards
1283 * STRING is appropriate since unknown-type literals look like strings).
1284 * Otherwise, if all the candidates agree on the type category of this
1285 * argument position, use that category. Otherwise, fail because we
1286 * cannot determine a category.
1288 * If we are able to determine a type category, also notice whether any of
1289 * the candidates takes a preferred datatype within the category.
1291 * Having completed this examination, remove candidates that accept the
1292 * wrong category at any unknown position. Also, if at least one
1293 * candidate accepted a preferred type at a position, remove candidates
1294 * that accept non-preferred types. If just one candidate remains, return
1295 * that one. However, if this rule turns out to reject all candidates,
1296 * keep them all instead.
1298 resolved_unknowns =
false;
1299 for (
i = 0;
i < nargs;
i++)
1303 if (input_base_typeids[
i] != UNKNOWNOID)
1305 resolved_unknowns =
true;
/* assume we can do it */
1306 slot_category[
i] = TYPCATEGORY_INVALID;
1307 slot_has_preferred_type[
i] =
false;
1308 have_conflict =
false;
1309 for (current_candidate = candidates;
1310 current_candidate != NULL;
1311 current_candidate = current_candidate->
next)
1313 current_typeids = current_candidate->
args;
1314 current_type = current_typeids[
i];
1317 ¤t_is_preferred);
1318 if (slot_category[
i] == TYPCATEGORY_INVALID)
1320 /* first candidate */
1321 slot_category[
i] = current_category;
1322 slot_has_preferred_type[
i] = current_is_preferred;
1324 else if (current_category == slot_category[
i])
1326 /* more candidates in same category */
1327 slot_has_preferred_type[
i] |= current_is_preferred;
1331 /* category conflict! */
1332 if (current_category == TYPCATEGORY_STRING)
1334 /* STRING always wins if available */
1335 slot_category[
i] = current_category;
1336 slot_has_preferred_type[
i] = current_is_preferred;
1341 * Remember conflict, but keep going (might find STRING)
1343 have_conflict =
true;
1347 if (have_conflict && slot_category[
i] != TYPCATEGORY_STRING)
1349 /* Failed to resolve category conflict at this position */
1350 resolved_unknowns =
false;
1355 if (resolved_unknowns)
1357 /* Strip non-matching candidates */
1359 first_candidate = candidates;
1360 last_candidate = NULL;
1361 for (current_candidate = candidates;
1362 current_candidate != NULL;
1363 current_candidate = current_candidate->
next)
1367 current_typeids = current_candidate->
args;
1368 for (
i = 0;
i < nargs;
i++)
1370 if (input_base_typeids[
i] != UNKNOWNOID)
1372 current_type = current_typeids[
i];
1375 ¤t_is_preferred);
1376 if (current_category != slot_category[
i])
1381 if (slot_has_preferred_type[
i] && !current_is_preferred)
1389 /* keep this candidate */
1390 last_candidate = current_candidate;
1395 /* forget this candidate */
1397 last_candidate->
next = current_candidate->
next;
1399 first_candidate = current_candidate->
next;
1403 /* if we found any matches, restrict our attention to those */
1406 candidates = first_candidate;
1407 /* terminate rebuilt list */
1408 last_candidate->
next = NULL;
1411 if (ncandidates == 1)
1416 * Last gasp: if there are both known- and unknown-type inputs, and all
1417 * the known types are the same, assume the unknown inputs are also that
1418 * type, and see if that gives us a unique match. If so, use that match.
1420 * NOTE: for a binary operator with one unknown and one non-unknown input,
1421 * we already tried this heuristic in binary_oper_exact(). However, that
1422 * code only finds exact matches, whereas here we will handle matches that
1423 * involve coercion, polymorphic type resolution, etc.
1425 if (nunknowns < nargs)
1427 Oid known_type = UNKNOWNOID;
1429 for (
i = 0;
i < nargs;
i++)
1431 if (input_base_typeids[
i] == UNKNOWNOID)
1433 if (known_type == UNKNOWNOID)
/* first known arg? */
1434 known_type = input_base_typeids[
i];
1435 else if (known_type != input_base_typeids[
i])
1437 /* oops, not all match */
1438 known_type = UNKNOWNOID;
1443 if (known_type != UNKNOWNOID)
1445 /* okay, just one known type, apply the heuristic */
1446 for (
i = 0;
i < nargs;
i++)
1447 input_base_typeids[
i] = known_type;
1449 last_candidate = NULL;
1450 for (current_candidate = candidates;
1451 current_candidate != NULL;
1452 current_candidate = current_candidate->
next)
1454 current_typeids = current_candidate->
args;
1458 if (++ncandidates > 1)
1459 break;
/* not unique, give up */
1460 last_candidate = current_candidate;
1463 if (ncandidates == 1)
1465 /* successfully identified a unique match */
1466 last_candidate->
next = NULL;
1467 return last_candidate;
1472 return NULL;
/* failed to select a best candidate */
1473}
/* func_select_candidate() */
1478 * Find the named function in the system catalogs.
1480 * Attempt to find the named function in the system catalogs with
1481 * arguments exactly as specified, so that the normal case (exact match)
1482 * is as quick as possible.
1484 * If an exact match isn't found:
1485 * 1) check for possible interpretation as a type coercion request
1486 * 2) apply the ambiguous-function resolution rules
1488 * If there is no match at all, we return FUNCDETAIL_NOTFOUND, and *fgc_flags
1489 * is filled with some flags that may be useful for issuing an on-point error
1490 * message (see FuncnameGetCandidates).
1492 * On success, return values *funcid through *true_typeids receive info about
1493 * the function. If argdefaults isn't NULL, *argdefaults receives a list of
1494 * any default argument expressions that need to be added to the given
1497 * When processing a named- or mixed-notation call (ie, fargnames isn't NIL),
1498 * the returned true_typeids and argdefaults are ordered according to the
1499 * call's argument ordering: first any positional arguments, then the named
1500 * arguments, then defaulted arguments (if needed and allowed by
1501 * expand_defaults). Some care is needed if this information is to be compared
1502 * to the function's pg_proc entry, but in practice the caller can usually
1503 * just work with the call's argument ordering.
1505 * We rely primarily on fargnames/nargs/argtypes as the argument description.
1506 * The actual expression node list is passed in fargs so that we can check
1507 * for type coercion of a constant. Some callers pass fargs == NIL indicating
1508 * they don't need that check made. Note also that when fargnames isn't NIL,
1509 * the fargs list must be passed if the caller wants actual argument position
1510 * information to be returned into the NamedArgExpr nodes.
1518 bool expand_variadic,
1519 bool expand_defaults,
1520 bool include_out_arguments,
1521 int *fgc_flags,
/* return value */
1522 Oid *funcid,
/* return value */
1523 Oid *rettype,
/* return value */
1524 bool *retset,
/* return value */
1525 int *nvargs,
/* return value */
1526 Oid *vatype,
/* return value */
1527 Oid **true_typeids,
/* return value */
1528 List **argdefaults)
/* optional return value */
1533 /* initialize output arguments to silence compiler warnings */
1539 *true_typeids = NULL;
1543 /* Get list of possible candidates from namespace search */
1545 expand_variadic, expand_defaults,
1546 include_out_arguments,
false,
1550 * Quickly check if there is an exact match to the input datatypes (there
1553 for (best_candidate = raw_candidates;
1554 best_candidate != NULL;
1555 best_candidate = best_candidate->
next)
1557 /* if nargs==0, argtypes can be null; don't pass that to memcmp */
1559 memcmp(argtypes, best_candidate->
args, nargs *
sizeof(
Oid)) == 0)
1563 if (best_candidate == NULL)
1566 * If we didn't find an exact match, next consider the possibility
1567 * that this is really a type-coercion request: a single-argument
1568 * function call where the function name is a type name. If so, and
1569 * if the coercion path is RELABELTYPE or COERCEVIAIO, then go ahead
1570 * and treat the "function call" as a coercion.
1572 * This interpretation needs to be given higher priority than
1573 * interpretations involving a type coercion followed by a function
1574 * call, otherwise we can produce surprising results. For example, we
1575 * want "text(varchar)" to be interpreted as a simple coercion, not as
1576 * "text(name(varchar))" which the code below this point is entirely
1577 * capable of selecting.
1579 * We also treat a coercion of a previously-unknown-type literal
1580 * constant to a specific type this way.
1582 * The reason we reject COERCION_PATH_FUNC here is that we expect the
1583 * cast implementation function to be named after the target type.
1584 * Thus the function will be found by normal lookup if appropriate.
1586 * The reason we reject COERCION_PATH_ARRAYCOERCE is mainly that you
1587 * can't write "foo[] (something)" as a function call. In theory
1588 * someone might want to invoke it as "_foo (something)" but we have
1589 * never supported that historically, so we can insist that people
1590 * write it as a normal cast instead.
1592 * We also reject the specific case of COERCEVIAIO for a composite
1593 * source type and a string-category target type. This is a case that
1594 * find_coercion_pathway() allows by default, but experience has shown
1595 * that it's too commonly invoked by mistake. So, again, insist that
1596 * people use cast syntax if they want to do that.
1598 * NB: it's important that this code does not exceed what coerce_type
1599 * can do, because the caller will try to apply coerce_type if we
1600 * return FUNCDETAIL_COERCION. If we return that result for something
1601 * coerce_type can't handle, we'll cause infinite recursion between
1602 * this module and coerce_type!
1604 if (nargs == 1 && fargs !=
NIL && fargnames ==
NIL)
1610 Oid sourceType = argtypes[0];
1614 if (sourceType == UNKNOWNOID &&
IsA(arg1,
Const))
1616 /* always treat typename('literal') as coercion */
1633 if ((sourceType == RECORDOID ||
1648 /* Treat it as a type coercion */
1650 *rettype = targetType;
1654 *true_typeids = argtypes;
1661 * didn't find an exact match, so now try to match up candidates...
1663 if (raw_candidates != NULL)
1671 ¤t_candidates);
1673 /* one match only? then run with it... */
1674 if (ncandidates == 1)
1675 best_candidate = current_candidates;
1678 * multiple candidates? then better decide or throw an error...
1680 else if (ncandidates > 1)
1684 current_candidates);
1687 * If we were able to choose a best candidate, we're done.
1688 * Otherwise, ambiguous function call.
1690 if (!best_candidate)
1703 * If processing named args or expanding variadics or defaults, the
1704 * "best candidate" might represent multiple equivalently good
1705 * functions; treat this case as ambiguous.
1711 * We disallow VARIADIC with named arguments unless the last argument
1712 * (the one with VARIADIC attached) actually matched the variadic
1713 * parameter. This is mere pedantry, really, but some folks insisted.
1715 if (fargnames !=
NIL && !expand_variadic && nargs > 0 &&
1716 best_candidate->
argnumbers[nargs - 1] != nargs - 1)
1722 *funcid = best_candidate->
oid;
1723 *nvargs = best_candidate->
nvargs;
1724 *true_typeids = best_candidate->
args;
1727 * If processing named args, return actual argument positions into
1728 * NamedArgExpr nodes in the fargs list. This is a bit ugly but not
1729 * worth the extra notation needed to do it differently.
1749 elog(
ERROR,
"cache lookup failed for function %u",
1750 best_candidate->
oid);
1752 *rettype = pform->prorettype;
1753 *retset = pform->proretset;
1754 *vatype = pform->provariadic;
1755 /* fetch default args if caller wants 'em */
1756 if (argdefaults && best_candidate->
ndargs > 0)
1758 Datum proargdefaults;
1762 /* shouldn't happen, FuncnameGetCandidates messed up */
1763 if (best_candidate->
ndargs > pform->pronargdefaults)
1764 elog(
ERROR,
"not enough default arguments");
1767 Anum_pg_proc_proargdefaults);
1772 /* Delete any unused defaults from the returned list */
1776 * This is a bit tricky in named notation, since the supplied
1777 * arguments could replace any subset of the defaults. We
1778 * work by making a bitmapset of the argnumbers of defaulted
1779 * arguments, then scanning the defaults list and selecting
1780 * the needed items. (This assumes that defaulted arguments
1781 * should be supplied in their positional order.)
1789 defargnumbers = NULL;
1791 for (
i = 0;
i < best_candidate->
ndargs;
i++)
1796 foreach(lc, defaults)
1804 *argdefaults = newdefaults;
1809 * Defaults for positional notation are lots easier; just
1810 * remove any unwanted ones from the front.
1817 *argdefaults = defaults;
1821 switch (pform->prokind)
1823 case PROKIND_AGGREGATE:
1826 case PROKIND_FUNCTION:
1829 case PROKIND_PROCEDURE:
1832 case PROKIND_WINDOW:
1836 elog(
ERROR,
"unrecognized prokind: %c", pform->prokind);
1850 * unify_hypothetical_args()
1852 * Ensure that each hypothetical direct argument of a hypothetical-set
1853 * aggregate has the same type as the corresponding aggregated argument.
1854 * Modify the expressions in the fargs list, if necessary, and update
1855 * actual_arg_types[].
1857 * If the agg declared its args non-ANY (even ANYELEMENT), we need only a
1858 * sanity check that the declared types match; make_fn_arguments will coerce
1859 * the actual arguments to match the declared ones. But if the declaration
1860 * is ANY, nothing will happen in make_fn_arguments, so we need to fix any
1861 * mismatch here. We use the same type resolution logic as UNION etc.
1866 int numAggregatedArgs,
1867 Oid *actual_arg_types,
1868 Oid *declared_arg_types)
1871 numNonHypotheticalArgs;
1874 numDirectArgs =
list_length(fargs) - numAggregatedArgs;
1875 numNonHypotheticalArgs = numDirectArgs - numAggregatedArgs;
1876 /* safety check (should only trigger with a misdeclared agg) */
1877 if (numNonHypotheticalArgs < 0)
1878 elog(
ERROR,
"incorrect number of arguments to hypothetical-set aggregate");
1880 /* Check each hypothetical arg and corresponding aggregated arg */
1881 for (hargpos = numNonHypotheticalArgs; hargpos < numDirectArgs; hargpos++)
1883 int aargpos = numDirectArgs + (hargpos - numNonHypotheticalArgs);
1889 /* A mismatch means AggregateCreate didn't check properly ... */
1890 if (declared_arg_types[hargpos] != declared_arg_types[aargpos])
1891 elog(
ERROR,
"hypothetical-set aggregate has inconsistent declared argument types");
1893 /* No need to unify if make_fn_arguments will coerce */
1894 if (declared_arg_types[hargpos] != ANYOID)
1898 * Select common type, giving preference to the aggregated argument's
1899 * type (we'd rather coerce the direct argument once than coerce all
1900 * the aggregated values).
1911 * Perform the coercions. We don't need to worry about NamedArgExprs
1912 * here because they aren't supported with aggregates.
1916 actual_arg_types[hargpos],
1917 commontype, commontypmod,
1921 actual_arg_types[hargpos] = commontype;
1924 actual_arg_types[aargpos],
1925 commontype, commontypmod,
1929 actual_arg_types[aargpos] = commontype;
1935 * make_fn_arguments()
1937 * Given the actual argument expressions for a function, and the desired
1938 * input types for the function, add any necessary typecasting to the
1939 * expression tree. Caller should already have verified that casting is
1942 * Caution: given argument list is modified in-place.
1944 * As with coerce_type, pstate may be NULL if no special unknown-Param
1945 * processing is wanted.
1950 Oid *actual_arg_types,
1951 Oid *declared_arg_types)
1956 foreach(current_fargs, fargs)
1958 /* types don't match? then force coercion using a function call... */
1959 if (actual_arg_types[
i] != declared_arg_types[
i])
1964 * If arg is a NamedArgExpr, coerce its input expr instead --- we
1965 * want the NamedArgExpr to stay at the top level of the list.
1973 actual_arg_types[
i],
1974 declared_arg_types[
i], -1,
1984 actual_arg_types[
i],
1985 declared_arg_types[
i], -1,
1989 lfirst(current_fargs) = node;
1998 * convenience routine to see if a function name matches a type name
2000 * Returns the OID of the matching type, or InvalidOid if none. We ignore
2001 * shell types and complex types.
2010 * temp_ok=false protects the <refsect1 id="sql-createfunction-security">
2011 * contract for writing SECURITY DEFINER functions safely.
2014 NULL,
false,
false);
2029 * ParseComplexProjection -
2030 * handles function calls with a single argument that is of complex type.
2031 * If the function call is actually a column projection, return a suitably
2032 * transformed expression tree. If not, return NULL.
2042 * Special case for whole-row Vars so that we can resolve (foo.*).bar even
2043 * when foo is a reference to a subselect, join, or RECORD function. A
2044 * bonus is that we avoid generating an unnecessary FieldSelect; our
2045 * result can omit the whole-row Var and just be a Var for the selected
2048 * This case could be handled by expandRecordVariable, but it's more
2049 * efficient to do it this way when possible.
2051 if (
IsA(first_arg,
Var) &&
2057 ((
Var *) first_arg)->varno,
2058 ((
Var *) first_arg)->varlevelsup);
2059 /* Return a Var if funcname matches a column, else NULL */
2061 ((
Var *) first_arg)->varlevelsup,
2066 * Else do it the hard way with get_expr_result_tupdesc().
2068 * If it's a Var of type RECORD, we have to work even harder: we have to
2069 * find what the Var refers to, and pass that to get_expr_result_tupdesc.
2070 * That task is handled by expandRecordVariable().
2072 if (
IsA(first_arg,
Var) &&
2073 ((
Var *) first_arg)->vartype == RECORDOID)
2078 return NULL;
/* unresolvable RECORD type */
2080 for (
i = 0;
i < tupdesc->
natts;
i++)
2087 /* Success, so generate a FieldSelect expression */
2090 fselect->
arg = (
Expr *) first_arg;
2092 fselect->resulttype = att->atttypid;
2093 fselect->resulttypmod = att->atttypmod;
2094 /* save attribute's collation for parse_collate.c */
2095 fselect->resultcollid = att->attcollation;
2096 return (
Node *) fselect;
2100 return NULL;
/* funcname does not match any column */
2104 * funcname_signature_string
2105 * Build a string representing a function name, including arg types.
2106 * The result is something like "foo(integer)".
2108 * If argnames isn't NIL, it is a list of C strings representing the actual
2109 * arg names for the last N arguments. This must be considered part of the
2110 * function signature too, when dealing with named-notation function calls.
2112 * This is typically used in the construction of function-not-found error
2117 List *argnames,
const Oid *argtypes)
2131 for (
i = 0;
i < nargs;
i++)
2135 if (
i >= numposargs)
2138 lc =
lnext(argnames, lc);
2145 return argbuf.
data;
/* return palloc'd string buffer */
2149 * func_signature_string
2150 * As above, but function name is passed as a qualified name list.
2154 List *argnames,
const Oid *argtypes)
2157 nargs, argnames, argtypes);
2161 * LookupFuncNameInternal
2162 * Workhorse for LookupFuncName/LookupFuncWithArgs
2164 * In an error situation, e.g. can't find the function, then we return
2165 * InvalidOid and set *lookupError to indicate what went wrong.
2168 * FUNCLOOKUP_NOSUCHFUNC: we can't find a function of this name.
2169 * FUNCLOOKUP_AMBIGUOUS: more than one function matches.
2173 int nargs,
const Oid *argtypes,
2174 bool include_out_arguments,
bool missing_ok,
2181 /* NULL argtypes allowed for nullary functions only */
2182 Assert(argtypes != NULL || nargs == 0);
2184 /* Always set *lookupError, to forestall uninitialized-variable warnings */
2187 /* Get list of candidate objects */
2189 include_out_arguments, missing_ok,
2192 /* Scan list for a match to the arg types (if specified) and the objtype */
2193 for (; clist != NULL; clist = clist->
next)
2195 /* Check arg type match, if specified */
2198 /* if nargs==0, argtypes can be null; don't pass that to memcmp */
2200 memcmp(argtypes, clist->
args, nargs *
sizeof(
Oid)) != 0)
2204 /* Check for duplicates reported by FuncnameGetCandidates */
2211 /* Check objtype match, if specified */
2216 /* Ignore procedures */
2221 /* Ignore non-procedures */
2226 /* no restriction */
2232 /* Check for multiple matches */
2239 /* OK, we have a candidate */
2240 result = clist->
oid;
2249 * Given a possibly-qualified function name and optionally a set of argument
2250 * types, look up the function. Pass nargs == -1 to indicate that the number
2251 * and types of the arguments are unspecified (this is NOT the same as
2252 * specifying that there are no arguments).
2254 * If the function name is not schema-qualified, it is sought in the current
2255 * namespace search path.
2257 * If the function is not found, we return InvalidOid if missing_ok is true,
2258 * else raise an error.
2260 * If nargs == -1 and multiple functions are found matching this function name
2261 * we will raise an ambiguous-function error, regardless of what missing_ok is
2264 * Only functions will be found; procedures will be ignored even if they
2265 * match the name and argument types. (However, we don't trouble to reject
2266 * aggregates or window functions here.)
2282 switch (lookupError)
2285 /* Let the caller deal with it when missing_ok is true */
2291 (
errcode(ERRCODE_UNDEFINED_FUNCTION),
2292 errmsg(
"could not find a function named \"%s\"",
2296 (
errcode(ERRCODE_UNDEFINED_FUNCTION),
2297 errmsg(
"function %s does not exist",
2303 /* Raise an error regardless of missing_ok */
2305 (
errcode(ERRCODE_AMBIGUOUS_FUNCTION),
2306 errmsg(
"function name \"%s\" is not unique",
2308 errhint(
"Specify the argument list to select the function unambiguously.")));
2316 * LookupFuncWithArgs
2318 * Like LookupFuncName, but the argument types are specified by an
2319 * ObjectWithArgs node. Also, this function can check whether the result is a
2320 * function, procedure, or aggregate, based on the objtype argument. Pass
2321 * OBJECT_ROUTINE to accept any of them.
2323 * For historical reasons, we also accept aggregates when looking for a
2326 * When missing_ok is true we don't generate any error for missing objects and
2327 * return InvalidOid. Other types of errors can still be raised, regardless
2328 * of the value of missing_ok.
2351 (
errcode(ERRCODE_TOO_MANY_ARGUMENTS),
2352 errmsg_plural(
"procedures cannot have more than %d argument",
2353 "procedures cannot have more than %d arguments",
2358 (
errcode(ERRCODE_TOO_MANY_ARGUMENTS),
2359 errmsg_plural(
"functions cannot have more than %d argument",
2360 "functions cannot have more than %d arguments",
2366 * First, perform a lookup considering only input arguments (traditional
2370 foreach(args_item, func->
objargs)
2376 return InvalidOid;
/* missing_ok must be true */
2381 * Set nargs for LookupFuncNameInternal. It expects -1 to mean no args
2387 * In args_unspecified mode, also tell LookupFuncNameInternal to consider
2388 * the object type, since there seems no reason not to. However, if we
2389 * have an argument list, disable the objtype check, because we'd rather
2390 * complain about "object is of wrong type" than "object doesn't exist".
2391 * (Note that with args, FuncnameGetCandidates will have ensured there's
2392 * only one argtype match, so we're not risking an ambiguity failure via
2396 func->
objname, nargs, argoids,
2401 * If PROCEDURE or ROUTINE was specified, and we have an argument list
2402 * that contains no parameter mode markers, and we didn't already discover
2403 * that there's ambiguity, perform a lookup considering all arguments.
2404 * (Note: for a zero-argument procedure, or in args_unspecified mode, the
2405 * normal lookup is sufficient; so it's OK to require non-NIL objfuncargs
2406 * to perform this lookup.)
2412 bool have_param_mode =
false;
2415 * Check for non-default parameter mode markers. If there are any,
2416 * then the command does not conform to SQL-spec syntax, so we may
2417 * assume that the traditional Postgres lookup method of considering
2418 * only input parameters is sufficient. (Note that because the spec
2419 * doesn't have OUT arguments for functions, we also don't need this
2420 * hack in FUNCTION or AGGREGATE mode.)
2428 have_param_mode =
true;
2433 if (!have_param_mode)
2437 /* Without mode marks, objargs surely includes all params */
2440 /* For objtype == OBJECT_PROCEDURE, we can ignore non-procedures */
2446 /* Combine results, handling ambiguity */
2451 /* oops, we got hits both ways, on different objects */
2466 * Even if we found the function, perform validation that the objtype
2467 * matches the prokind of the found function. For historical reasons
2468 * we allow the objtype of FUNCTION to include aggregates and window
2469 * functions; but we draw the line if the object is a procedure. That
2470 * is a new enough feature that this historical rule does not apply.
2472 * (This check is partially redundant with the objtype check in
2473 * LookupFuncNameInternal; but not entirely, since we often don't tell
2474 * LookupFuncNameInternal to apply that check at all.)
2479 /* Only complain if it's a procedure. */
2482 (
errcode(ERRCODE_WRONG_OBJECT_TYPE),
2483 errmsg(
"%s is not a function",
2489 /* Reject if found object is not a procedure. */
2492 (
errcode(ERRCODE_WRONG_OBJECT_TYPE),
2493 errmsg(
"%s is not a procedure",
2499 /* Reject if found object is not an aggregate. */
2502 (
errcode(ERRCODE_WRONG_OBJECT_TYPE),
2503 errmsg(
"function %s is not an aggregate",
2509 /* OBJECT_ROUTINE accepts anything. */
2513 return oid;
/* All good */
2517 /* Deal with cases where the lookup failed */
2518 switch (lookupError)
2521 /* Suppress no-such-func errors when missing_ok is true */
2530 (
errcode(ERRCODE_UNDEFINED_FUNCTION),
2531 errmsg(
"could not find a procedure named \"%s\"",
2535 (
errcode(ERRCODE_UNDEFINED_FUNCTION),
2536 errmsg(
"procedure %s does not exist",
2544 (
errcode(ERRCODE_UNDEFINED_FUNCTION),
2545 errmsg(
"could not find an aggregate named \"%s\"",
2547 else if (argcount == 0)
2549 (
errcode(ERRCODE_UNDEFINED_FUNCTION),
2550 errmsg(
"aggregate %s(*) does not exist",
2554 (
errcode(ERRCODE_UNDEFINED_FUNCTION),
2555 errmsg(
"aggregate %s does not exist",
2561 /* FUNCTION and ROUTINE */
2564 (
errcode(ERRCODE_UNDEFINED_FUNCTION),
2565 errmsg(
"could not find a function named \"%s\"",
2569 (
errcode(ERRCODE_UNDEFINED_FUNCTION),
2570 errmsg(
"function %s does not exist",
2582 (
errcode(ERRCODE_AMBIGUOUS_FUNCTION),
2583 errmsg(
"function name \"%s\" is not unique",
2586 errhint(
"Specify the argument list to select the function unambiguously.") : 0));
2590 (
errcode(ERRCODE_AMBIGUOUS_FUNCTION),
2591 errmsg(
"procedure name \"%s\" is not unique",
2594 errhint(
"Specify the argument list to select the procedure unambiguously.") : 0));
2598 (
errcode(ERRCODE_AMBIGUOUS_FUNCTION),
2599 errmsg(
"aggregate name \"%s\" is not unique",
2602 errhint(
"Specify the argument list to select the aggregate unambiguously.") : 0));
2606 (
errcode(ERRCODE_AMBIGUOUS_FUNCTION),
2607 errmsg(
"routine name \"%s\" is not unique",
2610 errhint(
"Specify the argument list to select the routine unambiguously.") : 0));
2614 Assert(
false);
/* Disallowed by Assert above */
2625 * check_srf_call_placement
2626 * Verify that a set-returning function is called in a valid place,
2627 * and throw a nice error if not.
2629 * A side-effect is to set pstate->p_hasTargetSRFs true if appropriate.
2631 * last_srf should be a copy of pstate->p_last_srf from just before we
2632 * started transforming the function's arguments. This allows detection
2633 * of whether the SRF's arguments contain any SRFs.
2642 * Check to see if the set-returning function is in an invalid place
2643 * within the query. Basically, we don't allow SRFs anywhere except in
2644 * the targetlist (which includes GROUP BY/ORDER BY expressions), VALUES,
2645 * and functions in FROM.
2647 * For brevity we support two schemes for reporting an error here: set
2648 * "err" to a custom message, or set "errkind" true if the error context
2649 * is sufficiently identified by what ParseExprKindName will return, *and*
2650 * what it will return is just a SQL keyword. (Otherwise, use a custom
2651 * message to avoid creating translation problems.)
2658 Assert(
false);
/* can't happen */
2661 /* Accept SRF here; caller must throw error if wanted */
2665 err =
_(
"set-returning functions are not allowed in JOIN conditions");
2668 /* can't get here, but just in case, throw an error */
2672 /* okay, but we don't allow nested SRFs here */
2673 /* errmsg is chosen to match transformRangeFunction() */
2674 /* errposition should point to the inner SRF */
2677 (
errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2678 errmsg(
"set-returning functions must appear at top level of FROM"),
2686 err =
_(
"set-returning functions are not allowed in policy expressions");
2696 /* okay, these are effectively GROUP BY/ORDER BY */
2702 err =
_(
"set-returning functions are not allowed in window definitions");
2711 /* disallowed because it would be ambiguous what to do */
2732 /* SRFs are presently not supported by nodeValuesscan.c */
2736 /* okay, since we process this like a SELECT tlist */
2740 err =
_(
"set-returning functions are not allowed in MERGE WHEN conditions");
2744 err =
_(
"set-returning functions are not allowed in check constraints");
2748 err =
_(
"set-returning functions are not allowed in DEFAULT expressions");
2751 err =
_(
"set-returning functions are not allowed in index expressions");
2754 err =
_(
"set-returning functions are not allowed in index predicates");
2757 err =
_(
"set-returning functions are not allowed in statistics expressions");
2760 err =
_(
"set-returning functions are not allowed in transform expressions");
2763 err =
_(
"set-returning functions are not allowed in EXECUTE parameters");
2766 err =
_(
"set-returning functions are not allowed in trigger WHEN conditions");
2769 err =
_(
"set-returning functions are not allowed in partition bound");
2772 err =
_(
"set-returning functions are not allowed in partition key expressions");
2775 err =
_(
"set-returning functions are not allowed in CALL arguments");
2778 err =
_(
"set-returning functions are not allowed in COPY FROM WHERE conditions");
2781 err =
_(
"set-returning functions are not allowed in column generation expressions");
2788 * There is intentionally no default: case here, so that the
2789 * compiler will warn if we add a new ParseExprKind without
2790 * extending this switch. If we do see an unrecognized value at
2791 * runtime, the behavior will be the same as for EXPR_KIND_OTHER,
2792 * which is sane anyway.
2797 (
errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2802 (
errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2803 /* translator: %s is name of a SQL construct, eg GROUP BY */
2804 errmsg(
"set-returning functions are not allowed in %s",
#define InvalidAttrNumber
void bms_free(Bitmapset *a)
bool bms_is_member(int x, const Bitmapset *a)
Bitmapset * bms_add_member(Bitmapset *a, int x)
#define TextDatumGetCString(d)
#define OidIsValid(objectId)
int errmsg_plural(const char *fmt_singular, const char *fmt_plural, unsigned long n,...)
int errmsg_internal(const char *fmt,...)
int errdetail(const char *fmt,...)
int errhint(const char *fmt,...)
int errcode(int sqlerrcode)
int errmsg(const char *fmt,...)
int errhint_plural(const char *fmt_singular, const char *fmt_plural, unsigned long n,...)
#define ereport(elevel,...)
void err(int eval, const char *fmt,...)
TupleDesc get_expr_result_tupdesc(Node *expr, bool noError)
Assert(PointerIsAligned(start, uint64))
#define HeapTupleIsValid(tuple)
static void * GETSTRUCT(const HeapTupleData *tuple)
List * lappend(List *list, void *datum)
List * list_copy_tail(const List *oldlist, int nskip)
List * list_delete_first_n(List *list, int n)
List * list_truncate(List *list, int new_size)
char get_func_prokind(Oid funcid)
Oid get_base_element_type(Oid typid)
Oid getBaseType(Oid typid)
Oid get_array_type(Oid typid)
void get_type_category_preferred(Oid typid, char *typcategory, bool *typispreferred)
TypeName * makeTypeNameFromNameList(List *names)
void pfree(void *pointer)
char * NameListToString(const List *names)
FuncCandidateList FuncnameGetCandidates(List *names, int nargs, List *argnames, bool expand_variadic, bool expand_defaults, bool include_out_arguments, bool missing_ok, int *fgc_flags)
#define FGC_ARGNAMES_VALID
#define FGC_ARGNAMES_MATCH
#define FGC_ARGCOUNT_MATCH
#define FGC_ARGNAMES_NONDUP
#define FGC_VARIADIC_FAIL
Oid exprType(const Node *expr)
int exprLocation(const Node *expr)
#define IsA(nodeptr, _type_)
#define castNode(_type_, nodeptr)
void transformWindowFuncCall(ParseState *pstate, WindowFunc *wfunc, WindowDef *windef)
void transformAggregateCall(ParseState *pstate, Aggref *agg, List *args, List *aggorder, bool agg_distinct)
Node * transformWhereClause(ParseState *pstate, Node *clause, ParseExprKind exprKind, const char *constructName)
TYPCATEGORY TypeCategory(Oid type)
Oid enforce_generic_type_consistency(const Oid *actual_arg_types, Oid *declared_arg_types, int nargs, Oid rettype, bool allow_poly)
CoercionPathType find_coercion_pathway(Oid targetTypeId, Oid sourceTypeId, CoercionContext ccontext, Oid *funcid)
int32 select_common_typmod(ParseState *pstate, List *exprs, Oid common_type)
Node * coerce_type(ParseState *pstate, Node *node, Oid inputTypeId, Oid targetTypeId, int32 targetTypeMod, CoercionContext ccontext, CoercionForm cformat, int location)
bool IsPreferredType(TYPCATEGORY category, Oid type)
Oid select_common_type(ParseState *pstate, List *exprs, const char *context, Node **which_expr)
bool can_coerce_type(int nargs, const Oid *input_typeids, const Oid *target_typeids, CoercionContext ccontext)
@ COERCION_PATH_COERCEVIAIO
@ COERCION_PATH_RELABELTYPE
const char * ParseExprKindName(ParseExprKind exprKind)
FuncDetailCode func_get_detail(List *funcname, List *fargs, List *fargnames, int nargs, Oid *argtypes, bool expand_variadic, bool expand_defaults, bool include_out_arguments, int *fgc_flags, Oid *funcid, Oid *rettype, bool *retset, int *nvargs, Oid *vatype, Oid **true_typeids, List **argdefaults)
const char * funcname_signature_string(const char *funcname, int nargs, List *argnames, const Oid *argtypes)
static Node * ParseComplexProjection(ParseState *pstate, const char *funcname, Node *first_arg, int location)
void make_fn_arguments(ParseState *pstate, List *fargs, Oid *actual_arg_types, Oid *declared_arg_types)
static Oid LookupFuncNameInternal(ObjectType objtype, List *funcname, int nargs, const Oid *argtypes, bool include_out_arguments, bool missing_ok, FuncLookupError *lookupError)
FuncCandidateList func_select_candidate(int nargs, Oid *input_typeids, FuncCandidateList candidates)
static void unify_hypothetical_args(ParseState *pstate, List *fargs, int numAggregatedArgs, Oid *actual_arg_types, Oid *declared_arg_types)
Node * ParseFuncOrColumn(ParseState *pstate, List *funcname, List *fargs, Node *last_srf, FuncCall *fn, bool proc_call, int location)
const char * func_signature_string(List *funcname, int nargs, List *argnames, const Oid *argtypes)
void check_srf_call_placement(ParseState *pstate, Node *last_srf, int location)
static Oid FuncNameAsType(List *funcname)
static int func_lookup_failure_details(int fgc_flags, List *argnames, bool proc_call)
Oid LookupFuncWithArgs(ObjectType objtype, ObjectWithArgs *func, bool missing_ok)
int func_match_argtypes(int nargs, Oid *input_typeids, FuncCandidateList raw_candidates, FuncCandidateList *candidates)
Oid LookupFuncName(List *funcname, int nargs, const Oid *argtypes, bool missing_ok)
void cancel_parser_errposition_callback(ParseCallbackState *pcbstate)
int parser_errposition(ParseState *pstate, int location)
void setup_parser_errposition_callback(ParseCallbackState *pcbstate, ParseState *pstate, int location)
@ EXPR_KIND_EXECUTE_PARAMETER
@ EXPR_KIND_COLUMN_DEFAULT
@ EXPR_KIND_STATS_EXPRESSION
@ EXPR_KIND_INDEX_EXPRESSION
@ EXPR_KIND_MERGE_RETURNING
@ EXPR_KIND_PARTITION_BOUND
@ EXPR_KIND_FUNCTION_DEFAULT
@ EXPR_KIND_WINDOW_FRAME_RANGE
@ EXPR_KIND_FROM_SUBSELECT
@ EXPR_KIND_WINDOW_FRAME_GROUPS
@ EXPR_KIND_PARTITION_EXPRESSION
@ EXPR_KIND_INDEX_PREDICATE
@ EXPR_KIND_INSERT_TARGET
@ EXPR_KIND_ALTER_COL_TRANSFORM
@ EXPR_KIND_UPDATE_TARGET
@ EXPR_KIND_SELECT_TARGET
@ EXPR_KIND_GENERATED_COLUMN
@ EXPR_KIND_CALL_ARGUMENT
@ EXPR_KIND_FROM_FUNCTION
@ EXPR_KIND_UPDATE_SOURCE
@ EXPR_KIND_CHECK_CONSTRAINT
@ EXPR_KIND_WINDOW_PARTITION
@ EXPR_KIND_WINDOW_FRAME_ROWS
@ EXPR_KIND_VALUES_SINGLE
ParseNamespaceItem * GetNSItemByRangeTablePosn(ParseState *pstate, int varno, int sublevels_up)
Node * scanNSItemForColumn(ParseState *pstate, ParseNamespaceItem *nsitem, int sublevels_up, const char *colname, int location)
TupleDesc expandRecordVariable(ParseState *pstate, Var *var, int levelsup)
Oid typeTypeRelid(Type typ)
Type LookupTypeNameExtended(ParseState *pstate, const TypeName *typeName, int32 *typmod_p, bool temp_ok, bool missing_ok)
Oid LookupTypeNameOid(ParseState *pstate, const TypeName *typeName, bool missing_ok)
#define ISCOMPLEX(typeid)
FormData_pg_aggregate * Form_pg_aggregate
FormData_pg_attribute * Form_pg_attribute
#define lfirst_node(type, lc)
static int list_length(const List *l)
#define foreach_delete_current(lst, var_or_cell)
static ListCell * list_nth_cell(const List *list, int n)
static ListCell * list_head(const List *l)
static ListCell * lnext(const List *l, const ListCell *c)
#define list_make2(x1, x2)
FormData_pg_proc * Form_pg_proc
FormData_pg_type * Form_pg_type
static Datum ObjectIdGetDatum(Oid X)
void * stringToNode(const char *str)
void appendStringInfo(StringInfo str, const char *fmt,...)
void appendStringInfoString(StringInfo str, const char *s)
void appendStringInfoChar(StringInfo str, char ch)
void initStringInfo(StringInfo str)
FunctionParameterMode mode
ParseExprKind p_expr_kind
struct _FuncCandidateList * next
Oid args[FLEXIBLE_ARRAY_MEMBER]
void ReleaseSysCache(HeapTuple tuple)
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Datum SysCacheGetAttrNotNull(int cacheId, HeapTuple tup, AttrNumber attributeNumber)
static void * fn(void *arg)
static FormData_pg_attribute * TupleDescAttr(TupleDesc tupdesc, int i)