1 /*-------------------------------------------------------------------------
4 * handle function calls in parser
6 * Portions Copyright (c) 1996-2019, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
11 * src/backend/parser/parse_func.c
13 *-------------------------------------------------------------------------
17 #include "access/htup_details.h"
18 #include "catalog/pg_aggregate.h"
19 #include "catalog/pg_proc.h"
20 #include "catalog/pg_type.h"
22 #include "lib/stringinfo.h"
23 #include "nodes/makefuncs.h"
24 #include "nodes/nodeFuncs.h"
25 #include "parser/parse_agg.h"
26 #include "parser/parse_clause.h"
27 #include "parser/parse_coerce.h"
28 #include "parser/parse_expr.h"
29 #include "parser/parse_func.h"
30 #include "parser/parse_relation.h"
31 #include "parser/parse_target.h"
32 #include "parser/parse_type.h"
33 #include "utils/builtins.h"
34 #include "utils/lsyscache.h"
35 #include "utils/syscache.h"
38 static void unify_hypothetical_args(ParseState *pstate,
39 List *fargs, int numAggregatedArgs,
40 Oid *actual_arg_types, Oid *declared_arg_types);
41 static Oid FuncNameAsType(List *funcname);
42 static Node *ParseComplexProjection(ParseState *pstate, const char *funcname,
43 Node *first_arg, int location);
47 * Parse a function call
49 * For historical reasons, Postgres tries to treat the notations tab.col
50 * and col(tab) as equivalent: if a single-argument function call has an
51 * argument of complex type and the (unqualified) function name matches
52 * any attribute of the type, we can interpret it as a column projection.
53 * Conversely a function of a single complex-type argument can be written
54 * like a column reference, allowing functions to act like computed columns.
56 * If both interpretations are possible, we prefer the one matching the
57 * syntactic form, but otherwise the form does not matter.
59 * Hence, both cases come through here. If fn is null, we're dealing with
60 * column syntax not function syntax. In the function-syntax case,
61 * the FuncCall struct is needed to carry various decoration that applies
62 * to aggregate and window functions.
64 * Also, when fn is null, we return NULL on failure rather than
65 * reporting a no-such-function error.
67 * The argument expressions (in fargs) must have been transformed
68 * already. However, nothing in *fn has been transformed.
70 * last_srf should be a copy of pstate->p_last_srf from just before we
71 * started transforming fargs. If the caller knows that fargs couldn't
72 * contain any SRF calls, last_srf can just be pstate->p_last_srf.
74 * proc_call is true if we are considering a CALL statement, so that the
75 * name must resolve to a procedure name, not anything else.
78 ParseFuncOrColumn(ParseState *pstate, List *funcname, List *fargs,
79 Node *last_srf, FuncCall *fn, bool proc_call, int location)
81 bool is_column = (fn == NULL);
82 List *agg_order = (fn ? fn->agg_order : NIL);
83 Expr *agg_filter = NULL;
84 bool agg_within_group = (fn ? fn->agg_within_group : false);
85 bool agg_star = (fn ? fn->agg_star : false);
86 bool agg_distinct = (fn ? fn->agg_distinct : false);
87 bool func_variadic = (fn ? fn->func_variadic : false);
88 WindowDef *over = (fn ? fn->over : NULL);
89 bool could_be_projection;
94 Node *first_arg = NULL;
97 Oid actual_arg_types[FUNC_MAX_ARGS];
98 Oid *declared_arg_types;
105 FuncDetailCode fdresult;
107 ParseCallbackState pcbstate;
110 * If there's an aggregate filter, transform it using transformWhereClause
112 if (fn && fn->agg_filter != NULL)
113 agg_filter = (Expr *) transformWhereClause(pstate, fn->agg_filter,
118 * Most of the rest of the parser just assumes that functions do not have
119 * more than FUNC_MAX_ARGS parameters. We have to test here to protect
120 * against array overruns, etc. Of course, this may not be a function,
121 * but the test doesn't hurt.
123 if (list_length(fargs) > FUNC_MAX_ARGS)
125 (errcode(ERRCODE_TOO_MANY_ARGUMENTS),
126 errmsg_plural("cannot pass more than %d argument to a function",
127 "cannot pass more than %d arguments to a function",
130 parser_errposition(pstate, location)));
133 * Extract arg type info in preparation for function lookup.
135 * If any arguments are Param markers of type VOID, we discard them from
136 * the parameter list. This is a hack to allow the JDBC driver to not have
137 * to distinguish "input" and "output" parameter symbols while parsing
138 * function-call constructs. Don't do this if dealing with column syntax,
139 * nor if we had WITHIN GROUP (because in that case it's critical to keep
140 * the argument count unchanged). We can't use foreach() because we may
141 * modify the list ...
144 for (l = list_head(fargs); l != NULL; l = nextl)
146 Node *arg = lfirst(l);
147 Oid argtype = exprType(arg);
151 if (argtype == VOIDOID && IsA(arg, Param) &&
152 !is_column && !agg_within_group)
154 fargs = list_delete_ptr(fargs, arg);
158 actual_arg_types[nargs++] = argtype;
162 * Check for named arguments; if there are any, build a list of names.
164 * We allow mixed notation (some named and some not), but only with all
165 * the named parameters after all the unnamed ones. So the name list
166 * corresponds to the last N actual parameters and we don't need any extra
167 * bookkeeping to match things up.
172 Node *arg = lfirst(l);
174 if (IsA(arg, NamedArgExpr))
176 NamedArgExpr *na = (NamedArgExpr *) arg;
179 /* Reject duplicate arg names */
180 foreach(lc, argnames)
182 if (strcmp(na->name, (char *) lfirst(lc)) == 0)
184 (errcode(ERRCODE_SYNTAX_ERROR),
185 errmsg("argument name \"%s\" used more than once",
187 parser_errposition(pstate, na->location)));
189 argnames = lappend(argnames, na->name);
195 (errcode(ERRCODE_SYNTAX_ERROR),
196 errmsg("positional argument cannot follow named argument"),
197 parser_errposition(pstate, exprLocation(arg))));
203 first_arg = linitial(fargs);
204 Assert(first_arg != NULL);
208 * Decide whether it's legitimate to consider the construct to be a column
209 * projection. For that, there has to be a single argument of complex
210 * type, the function name must not be qualified, and there cannot be any
211 * syntactic decoration that'd require it to be a function (such as
212 * aggregate or variadic decoration, or named arguments).
214 could_be_projection = (nargs == 1 && !proc_call &&
215 agg_order == NIL && agg_filter == NULL &&
216 !agg_star && !agg_distinct && over == NULL &&
217 !func_variadic && argnames == NIL &&
218 list_length(funcname) == 1 &&
219 (actual_arg_types[0] == RECORDOID ||
220 ISCOMPLEX(actual_arg_types[0])));
223 * If it's column syntax, check for column projection case first.
225 if (could_be_projection && is_column)
227 retval = ParseComplexProjection(pstate,
228 strVal(linitial(funcname)),
235 * If ParseComplexProjection doesn't recognize it as a projection,
241 * func_get_detail looks up the function in the catalogs, does
242 * disambiguation for polymorphic functions, handles inheritance, and
243 * returns the funcid and type and set or singleton status of the
244 * function's return value. It also returns the true argument types to
247 * Note: for a named-notation or variadic function call, the reported
248 * "true" types aren't really what is in pg_proc: the types are reordered
249 * to match the given argument order of named arguments, and a variadic
250 * argument is replaced by a suitable number of copies of its element
251 * type. We'll fix up the variadic case below. We may also have to deal
252 * with default arguments.
255 setup_parser_errposition_callback(&pcbstate, pstate, location);
257 fdresult = func_get_detail(funcname, fargs, argnames, nargs,
259 !func_variadic, true,
260 &funcid, &rettype, &retset,
262 &declared_arg_types, &argdefaults);
264 cancel_parser_errposition_callback(&pcbstate);
267 * Check for various wrong-kind-of-routine cases.
270 /* If this is a CALL, reject things that aren't procedures */
272 (fdresult == FUNCDETAIL_NORMAL ||
273 fdresult == FUNCDETAIL_AGGREGATE ||
274 fdresult == FUNCDETAIL_WINDOWFUNC ||
275 fdresult == FUNCDETAIL_COERCION))
277 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
278 errmsg("%s is not a procedure",
279 func_signature_string(funcname, nargs,
282 errhint("To call a function, use SELECT."),
283 parser_errposition(pstate, location)));
284 /* Conversely, if not a CALL, reject procedures */
285 if (fdresult == FUNCDETAIL_PROCEDURE && !proc_call)
287 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
288 errmsg("%s is a procedure",
289 func_signature_string(funcname, nargs,
292 errhint("To call a procedure, use CALL."),
293 parser_errposition(pstate, location)));
295 if (fdresult == FUNCDETAIL_NORMAL ||
296 fdresult == FUNCDETAIL_PROCEDURE ||
297 fdresult == FUNCDETAIL_COERCION)
300 * In these cases, complain if there was anything indicating it must
301 * be an aggregate or window function.
305 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
306 errmsg("%s(*) specified, but %s is not an aggregate function",
307 NameListToString(funcname),
308 NameListToString(funcname)),
309 parser_errposition(pstate, location)));
312 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
313 errmsg("DISTINCT specified, but %s is not an aggregate function",
314 NameListToString(funcname)),
315 parser_errposition(pstate, location)));
316 if (agg_within_group)
318 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
319 errmsg("WITHIN GROUP specified, but %s is not an aggregate function",
320 NameListToString(funcname)),
321 parser_errposition(pstate, location)));
322 if (agg_order != NIL)
324 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
325 errmsg("ORDER BY specified, but %s is not an aggregate function",
326 NameListToString(funcname)),
327 parser_errposition(pstate, location)));
330 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
331 errmsg("FILTER specified, but %s is not an aggregate function",
332 NameListToString(funcname)),
333 parser_errposition(pstate, location)));
336 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
337 errmsg("OVER specified, but %s is not a window function nor an aggregate function",
338 NameListToString(funcname)),
339 parser_errposition(pstate, location)));
343 * So far so good, so do some fdresult-type-specific processing.
345 if (fdresult == FUNCDETAIL_NORMAL || fdresult == FUNCDETAIL_PROCEDURE)
347 /* Nothing special to do for these cases. */
349 else if (fdresult == FUNCDETAIL_AGGREGATE)
352 * It's an aggregate; fetch needed info from the pg_aggregate entry.
355 Form_pg_aggregate classForm;
358 tup = SearchSysCache1(AGGFNOID, ObjectIdGetDatum(funcid));
359 if (!HeapTupleIsValid(tup)) /* should not happen */
360 elog(ERROR, "cache lookup failed for aggregate %u", funcid);
361 classForm = (Form_pg_aggregate) GETSTRUCT(tup);
362 aggkind = classForm->aggkind;
363 catDirectArgs = classForm->aggnumdirectargs;
364 ReleaseSysCache(tup);
366 /* Now check various disallowed cases. */
367 if (AGGKIND_IS_ORDERED_SET(aggkind))
369 int numAggregatedArgs;
372 if (!agg_within_group)
374 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
375 errmsg("WITHIN GROUP is required for ordered-set aggregate %s",
376 NameListToString(funcname)),
377 parser_errposition(pstate, location)));
380 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
381 errmsg("OVER is not supported for ordered-set aggregate %s",
382 NameListToString(funcname)),
383 parser_errposition(pstate, location)));
384 /* gram.y rejects DISTINCT + WITHIN GROUP */
385 Assert(!agg_distinct);
386 /* gram.y rejects VARIADIC + WITHIN GROUP */
387 Assert(!func_variadic);
390 * Since func_get_detail was working with an undifferentiated list
391 * of arguments, it might have selected an aggregate that doesn't
392 * really match because it requires a different division of direct
393 * and aggregated arguments. Check that the number of direct
394 * arguments is actually OK; if not, throw an "undefined function"
395 * error, similarly to the case where a misplaced ORDER BY is used
396 * in a regular aggregate call.
398 numAggregatedArgs = list_length(agg_order);
399 numDirectArgs = nargs - numAggregatedArgs;
400 Assert(numDirectArgs >= 0);
402 if (!OidIsValid(vatype))
404 /* Test is simple if aggregate isn't variadic */
405 if (numDirectArgs != catDirectArgs)
407 (errcode(ERRCODE_UNDEFINED_FUNCTION),
408 errmsg("function %s does not exist",
409 func_signature_string(funcname, nargs,
412 errhint("There is an ordered-set aggregate %s, but it requires %d direct arguments, not %d.",
413 NameListToString(funcname),
414 catDirectArgs, numDirectArgs),
415 parser_errposition(pstate, location)));
420 * If it's variadic, we have two cases depending on whether
421 * the agg was "... ORDER BY VARIADIC" or "..., VARIADIC ORDER
422 * BY VARIADIC". It's the latter if catDirectArgs equals
423 * pronargs; to save a catalog lookup, we reverse-engineer
424 * pronargs from the info we got from func_get_detail.
430 pronargs -= nvargs - 1;
431 if (catDirectArgs < pronargs)
433 /* VARIADIC isn't part of direct args, so still easy */
434 if (numDirectArgs != catDirectArgs)
436 (errcode(ERRCODE_UNDEFINED_FUNCTION),
437 errmsg("function %s does not exist",
438 func_signature_string(funcname, nargs,
441 errhint("There is an ordered-set aggregate %s, but it requires %d direct arguments, not %d.",
442 NameListToString(funcname),
443 catDirectArgs, numDirectArgs),
444 parser_errposition(pstate, location)));
449 * Both direct and aggregated args were declared variadic.
450 * For a standard ordered-set aggregate, it's okay as long
451 * as there aren't too few direct args. For a
452 * hypothetical-set aggregate, we assume that the
453 * hypothetical arguments are those that matched the
454 * variadic parameter; there must be just as many of them
455 * as there are aggregated arguments.
457 if (aggkind == AGGKIND_HYPOTHETICAL)
459 if (nvargs != 2 * numAggregatedArgs)
461 (errcode(ERRCODE_UNDEFINED_FUNCTION),
462 errmsg("function %s does not exist",
463 func_signature_string(funcname, nargs,
466 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).",
467 NameListToString(funcname),
468 nvargs - numAggregatedArgs, numAggregatedArgs),
469 parser_errposition(pstate, location)));
473 if (nvargs <= numAggregatedArgs)
475 (errcode(ERRCODE_UNDEFINED_FUNCTION),
476 errmsg("function %s does not exist",
477 func_signature_string(funcname, nargs,
480 errhint("There is an ordered-set aggregate %s, but it requires at least %d direct arguments.",
481 NameListToString(funcname),
483 parser_errposition(pstate, location)));
488 /* Check type matching of hypothetical arguments */
489 if (aggkind == AGGKIND_HYPOTHETICAL)
490 unify_hypothetical_args(pstate, fargs, numAggregatedArgs,
491 actual_arg_types, declared_arg_types);
495 /* Normal aggregate, so it can't have WITHIN GROUP */
496 if (agg_within_group)
498 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
499 errmsg("%s is not an ordered-set aggregate, so it cannot have WITHIN GROUP",
500 NameListToString(funcname)),
501 parser_errposition(pstate, location)));
504 else if (fdresult == FUNCDETAIL_WINDOWFUNC)
507 * True window functions must be called with a window definition.
511 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
512 errmsg("window function %s requires an OVER clause",
513 NameListToString(funcname)),
514 parser_errposition(pstate, location)));
515 /* And, per spec, WITHIN GROUP isn't allowed */
516 if (agg_within_group)
518 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
519 errmsg("window function %s cannot have WITHIN GROUP",
520 NameListToString(funcname)),
521 parser_errposition(pstate, location)));
523 else if (fdresult == FUNCDETAIL_COERCION)
526 * We interpreted it as a type coercion. coerce_type can handle these
527 * cases, so why duplicate code...
529 return coerce_type(pstate, linitial(fargs),
530 actual_arg_types[0], rettype, -1,
531 COERCION_EXPLICIT, COERCE_EXPLICIT_CALL, location);
533 else if (fdresult == FUNCDETAIL_MULTIPLE)
536 * We found multiple possible functional matches. If we are dealing
537 * with attribute notation, return failure, letting the caller report
538 * "no such column" (we already determined there wasn't one). If
539 * dealing with function notation, report "ambiguous function",
540 * regardless of whether there's also a column by this name.
547 (errcode(ERRCODE_AMBIGUOUS_FUNCTION),
548 errmsg("procedure %s is not unique",
549 func_signature_string(funcname, nargs, argnames,
551 errhint("Could not choose a best candidate procedure. "
552 "You might need to add explicit type casts."),
553 parser_errposition(pstate, location)));
556 (errcode(ERRCODE_AMBIGUOUS_FUNCTION),
557 errmsg("function %s is not unique",
558 func_signature_string(funcname, nargs, argnames,
560 errhint("Could not choose a best candidate function. "
561 "You might need to add explicit type casts."),
562 parser_errposition(pstate, location)));
567 * Not found as a function. If we are dealing with attribute
568 * notation, return failure, letting the caller report "no such
569 * column" (we already determined there wasn't one).
575 * Check for column projection interpretation, since we didn't before.
577 if (could_be_projection)
579 retval = ParseComplexProjection(pstate,
580 strVal(linitial(funcname)),
588 * No function, and no column either. Since we're dealing with
589 * function notation, report "function does not exist".
591 if (list_length(agg_order) > 1 && !agg_within_group)
593 /* It's agg(x, ORDER BY y,z) ... perhaps misplaced ORDER BY */
595 (errcode(ERRCODE_UNDEFINED_FUNCTION),
596 errmsg("function %s does not exist",
597 func_signature_string(funcname, nargs, argnames,
599 errhint("No aggregate function matches the given name and argument types. "
600 "Perhaps you misplaced ORDER BY; ORDER BY must appear "
601 "after all regular arguments of the aggregate."),
602 parser_errposition(pstate, location)));
606 (errcode(ERRCODE_UNDEFINED_FUNCTION),
607 errmsg("procedure %s does not exist",
608 func_signature_string(funcname, nargs, argnames,
610 errhint("No procedure matches the given name and argument types. "
611 "You might need to add explicit type casts."),
612 parser_errposition(pstate, location)));
615 (errcode(ERRCODE_UNDEFINED_FUNCTION),
616 errmsg("function %s does not exist",
617 func_signature_string(funcname, nargs, argnames,
619 errhint("No function matches the given name and argument types. "
620 "You might need to add explicit type casts."),
621 parser_errposition(pstate, location)));
625 * If there are default arguments, we have to include their types in
626 * actual_arg_types for the purpose of checking generic type consistency.
627 * However, we do NOT put them into the generated parse node, because
628 * their actual values might change before the query gets run. The
629 * planner has to insert the up-to-date values at plan time.
631 nargsplusdefs = nargs;
632 foreach(l, argdefaults)
634 Node *expr = (Node *) lfirst(l);
636 /* probably shouldn't happen ... */
637 if (nargsplusdefs >= FUNC_MAX_ARGS)
639 (errcode(ERRCODE_TOO_MANY_ARGUMENTS),
640 errmsg_plural("cannot pass more than %d argument to a function",
641 "cannot pass more than %d arguments to a function",
644 parser_errposition(pstate, location)));
646 actual_arg_types[nargsplusdefs++] = exprType(expr);
650 * enforce consistency with polymorphic argument and return types,
651 * possibly adjusting return type or declared_arg_types (which will be
652 * used as the cast destination by make_fn_arguments)
654 rettype = enforce_generic_type_consistency(actual_arg_types,
660 /* perform the necessary typecasting of arguments */
661 make_fn_arguments(pstate, fargs, actual_arg_types, declared_arg_types);
664 * If the function isn't actually variadic, forget any VARIADIC decoration
665 * on the call. (Perhaps we should throw an error instead, but
666 * historically we've allowed people to write that.)
668 if (!OidIsValid(vatype))
671 func_variadic = false;
675 * If it's a variadic function call, transform the last nvargs arguments
676 * into an array --- unless it's an "any" variadic.
678 if (nvargs > 0 && vatype != ANYOID)
680 ArrayExpr *newa = makeNode(ArrayExpr);
681 int non_var_args = nargs - nvargs;
684 Assert(non_var_args >= 0);
685 vargs = list_copy_tail(fargs, non_var_args);
686 fargs = list_truncate(fargs, non_var_args);
688 newa->elements = vargs;
689 /* assume all the variadic arguments were coerced to the same type */
690 newa->element_typeid = exprType((Node *) linitial(vargs));
691 newa->array_typeid = get_array_type(newa->element_typeid);
692 if (!OidIsValid(newa->array_typeid))
694 (errcode(ERRCODE_UNDEFINED_OBJECT),
695 errmsg("could not find array type for data type %s",
696 format_type_be(newa->element_typeid)),
697 parser_errposition(pstate, exprLocation((Node *) vargs))));
698 /* array_collid will be set by parse_collate.c */
699 newa->multidims = false;
700 newa->location = exprLocation((Node *) vargs);
702 fargs = lappend(fargs, newa);
704 /* We could not have had VARIADIC marking before ... */
705 Assert(!func_variadic);
706 /* ... but now, it's a VARIADIC call */
707 func_variadic = true;
711 * If an "any" variadic is called with explicit VARIADIC marking, insist
712 * that the variadic parameter be of some array type.
714 if (nargs > 0 && vatype == ANYOID && func_variadic)
716 Oid va_arr_typid = actual_arg_types[nargs - 1];
718 if (!OidIsValid(get_base_element_type(va_arr_typid)))
720 (errcode(ERRCODE_DATATYPE_MISMATCH),
721 errmsg("VARIADIC argument must be an array"),
722 parser_errposition(pstate,
723 exprLocation((Node *) llast(fargs)))));
726 /* if it returns a set, check that's OK */
728 check_srf_call_placement(pstate, last_srf, location);
730 /* build the appropriate output structure */
731 if (fdresult == FUNCDETAIL_NORMAL || fdresult == FUNCDETAIL_PROCEDURE)
733 FuncExpr *funcexpr = makeNode(FuncExpr);
735 funcexpr->funcid = funcid;
736 funcexpr->funcresulttype = rettype;
737 funcexpr->funcretset = retset;
738 funcexpr->funcvariadic = func_variadic;
739 funcexpr->funcformat = COERCE_EXPLICIT_CALL;
740 /* funccollid and inputcollid will be set by parse_collate.c */
741 funcexpr->args = fargs;
742 funcexpr->location = location;
744 retval = (Node *) funcexpr;
746 else if (fdresult == FUNCDETAIL_AGGREGATE && !over)
748 /* aggregate function */
749 Aggref *aggref = makeNode(Aggref);
751 aggref->aggfnoid = funcid;
752 aggref->aggtype = rettype;
753 /* aggcollid and inputcollid will be set by parse_collate.c */
754 aggref->aggtranstype = InvalidOid; /* will be set by planner */
755 /* aggargtypes will be set by transformAggregateCall */
756 /* aggdirectargs and args will be set by transformAggregateCall */
757 /* aggorder and aggdistinct will be set by transformAggregateCall */
758 aggref->aggfilter = agg_filter;
759 aggref->aggstar = agg_star;
760 aggref->aggvariadic = func_variadic;
761 aggref->aggkind = aggkind;
762 /* agglevelsup will be set by transformAggregateCall */
763 aggref->aggsplit = AGGSPLIT_SIMPLE; /* planner might change this */
764 aggref->location = location;
767 * Reject attempt to call a parameterless aggregate without (*)
768 * syntax. This is mere pedantry but some folks insisted ...
770 if (fargs == NIL && !agg_star && !agg_within_group)
772 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
773 errmsg("%s(*) must be used to call a parameterless aggregate function",
774 NameListToString(funcname)),
775 parser_errposition(pstate, location)));
779 (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
780 errmsg("aggregates cannot return sets"),
781 parser_errposition(pstate, location)));
784 * We might want to support named arguments later, but disallow it for
785 * now. We'd need to figure out the parsed representation (should the
786 * NamedArgExprs go above or below the TargetEntry nodes?) and then
787 * teach the planner to reorder the list properly. Or maybe we could
788 * make transformAggregateCall do that? However, if you'd also like
789 * to allow default arguments for aggregates, we'd need to do it in
790 * planning to avoid semantic problems.
794 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
795 errmsg("aggregates cannot use named arguments"),
796 parser_errposition(pstate, location)));
798 /* parse_agg.c does additional aggregate-specific processing */
799 transformAggregateCall(pstate, aggref, fargs, agg_order, agg_distinct);
801 retval = (Node *) aggref;
805 /* window function */
806 WindowFunc *wfunc = makeNode(WindowFunc);
808 Assert(over); /* lack of this was checked above */
809 Assert(!agg_within_group); /* also checked above */
811 wfunc->winfnoid = funcid;
812 wfunc->wintype = rettype;
813 /* wincollid and inputcollid will be set by parse_collate.c */
815 /* winref will be set by transformWindowFuncCall */
816 wfunc->winstar = agg_star;
817 wfunc->winagg = (fdresult == FUNCDETAIL_AGGREGATE);
818 wfunc->aggfilter = agg_filter;
819 wfunc->location = location;
822 * agg_star is allowed for aggregate functions but distinct isn't
826 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
827 errmsg("DISTINCT is not implemented for window functions"),
828 parser_errposition(pstate, location)));
831 * Reject attempt to call a parameterless aggregate without (*)
832 * syntax. This is mere pedantry but some folks insisted ...
834 if (wfunc->winagg && fargs == NIL && !agg_star)
836 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
837 errmsg("%s(*) must be used to call a parameterless aggregate function",
838 NameListToString(funcname)),
839 parser_errposition(pstate, location)));
842 * ordered aggs not allowed in windows yet
844 if (agg_order != NIL)
846 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
847 errmsg("aggregate ORDER BY is not implemented for window functions"),
848 parser_errposition(pstate, location)));
851 * FILTER is not yet supported with true window functions
853 if (!wfunc->winagg && agg_filter)
855 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
856 errmsg("FILTER is not implemented for non-aggregate window functions"),
857 parser_errposition(pstate, location)));
860 * Window functions can't either take or return sets
862 if (pstate->p_last_srf != last_srf)
864 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
865 errmsg("window function calls cannot contain set-returning function calls"),
866 errhint("You might be able to move the set-returning function into a LATERAL FROM item."),
867 parser_errposition(pstate,
868 exprLocation(pstate->p_last_srf))));
872 (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
873 errmsg("window functions cannot return sets"),
874 parser_errposition(pstate, location)));
876 /* parse_agg.c does additional window-func-specific processing */
877 transformWindowFuncCall(pstate, wfunc, over);
879 retval = (Node *) wfunc;
882 /* if it returns a set, remember it for error checks at higher levels */
884 pstate->p_last_srf = retval;
890 /* func_match_argtypes()
892 * Given a list of candidate functions (having the right name and number
893 * of arguments) and an array of input datatype OIDs, produce a shortlist of
894 * those candidates that actually accept the input datatypes (either exactly
895 * or by coercion), and return the number of such candidates.
897 * Note that can_coerce_type will assume that UNKNOWN inputs are coercible to
898 * anything, so candidates will not be eliminated on that basis.
900 * NB: okay to modify input list structure, as long as we find at least
901 * one match. If no match at all, the list must remain unmodified.
904 func_match_argtypes(int nargs,
906 FuncCandidateList raw_candidates,
907 FuncCandidateList *candidates) /* return value */
909 FuncCandidateList current_candidate;
910 FuncCandidateList next_candidate;
915 for (current_candidate = raw_candidates;
916 current_candidate != NULL;
917 current_candidate = next_candidate)
919 next_candidate = current_candidate->next;
920 if (can_coerce_type(nargs, input_typeids, current_candidate->args,
923 current_candidate->next = *candidates;
924 *candidates = current_candidate;
930 } /* func_match_argtypes() */
933 /* func_select_candidate()
934 * Given the input argtype array and more than one candidate
935 * for the function, attempt to resolve the conflict.
937 * Returns the selected candidate if the conflict can be resolved,
938 * otherwise returns NULL.
940 * Note that the caller has already determined that there is no candidate
941 * exactly matching the input argtypes, and has pruned away any "candidates"
942 * that aren't actually coercion-compatible with the input types.
944 * This is also used for resolving ambiguous operator references. Formerly
945 * parse_oper.c had its own, essentially duplicate code for the purpose.
946 * The following comments (formerly in parse_oper.c) are kept to record some
947 * of the history of these heuristics.
951 * This routine is new code, replacing binary_oper_select_candidate()
952 * which dates from v4.2/v1.0.x days. It tries very hard to match up
953 * operators with types, including allowing type coercions if necessary.
954 * The important thing is that the code do as much as possible,
955 * while _never_ doing the wrong thing, where "the wrong thing" would
956 * be returning an operator when other better choices are available,
957 * or returning an operator which is a non-intuitive possibility.
958 * - thomas 1998-05-21
960 * The comments below came from binary_oper_select_candidate(), and
961 * illustrate the issues and choices which are possible:
962 * - thomas 1998-05-20
964 * current wisdom holds that the default operator should be one in which
965 * both operands have the same type (there will only be one such
968 * 7.27.93 - I have decided not to do this; it's too hard to justify, and
969 * it's easy enough to typecast explicitly - avi
970 * [the rest of this routine was commented out since then - ay]
972 * 6/23/95 - I don't complete agree with avi. In particular, casting
973 * floats is a pain for users. Whatever the rationale behind not doing
974 * this is, I need the following special case to work.
976 * In the WHERE clause of a query, if a float is specified without
977 * quotes, we treat it as float8. I added the float48* operators so
978 * that we can operate on float4 and float8. But now we have more than
979 * one matching operator if the right arg is unknown (eg. float
980 * specified with quotes). This break some stuff in the regression
981 * test where there are floats in quotes not properly casted. Below is
982 * the solution. In addition to requiring the operator operates on the
983 * same type for both operands [as in the code Avi originally
984 * commented out], we also require that the operators be equivalent in
985 * some sense. (see equivalentOpersAfterPromotion for details.)
989 func_select_candidate(int nargs,
991 FuncCandidateList candidates)
993 FuncCandidateList current_candidate,
996 Oid *current_typeids;
1003 Oid input_base_typeids[FUNC_MAX_ARGS];
1004 TYPCATEGORY slot_category[FUNC_MAX_ARGS],
1006 bool current_is_preferred;
1007 bool slot_has_preferred_type[FUNC_MAX_ARGS];
1008 bool resolved_unknowns;
1010 /* protect local fixed-size arrays */
1011 if (nargs > FUNC_MAX_ARGS)
1013 (errcode(ERRCODE_TOO_MANY_ARGUMENTS),
1014 errmsg_plural("cannot pass more than %d argument to a function",
1015 "cannot pass more than %d arguments to a function",
1020 * If any input types are domains, reduce them to their base types. This
1021 * ensures that we will consider functions on the base type to be "exact
1022 * matches" in the exact-match heuristic; it also makes it possible to do
1023 * something useful with the type-category heuristics. Note that this
1024 * makes it difficult, but not impossible, to use functions declared to
1025 * take a domain as an input datatype. Such a function will be selected
1026 * over the base-type function only if it is an exact match at all
1027 * argument positions, and so was already chosen by our caller.
1029 * While we're at it, count the number of unknown-type arguments for use
1033 for (i = 0; i < nargs; i++)
1035 if (input_typeids[i] != UNKNOWNOID)
1036 input_base_typeids[i] = getBaseType(input_typeids[i]);
1039 /* no need to call getBaseType on UNKNOWNOID */
1040 input_base_typeids[i] = UNKNOWNOID;
1046 * Run through all candidates and keep those with the most matches on
1047 * exact types. Keep all candidates if none match.
1051 last_candidate = NULL;
1052 for (current_candidate = candidates;
1053 current_candidate != NULL;
1054 current_candidate = current_candidate->next)
1056 current_typeids = current_candidate->args;
1058 for (i = 0; i < nargs; i++)
1060 if (input_base_typeids[i] != UNKNOWNOID &&
1061 current_typeids[i] == input_base_typeids[i])
1065 /* take this one as the best choice so far? */
1066 if ((nmatch > nbestMatch) || (last_candidate == NULL))
1068 nbestMatch = nmatch;
1069 candidates = current_candidate;
1070 last_candidate = current_candidate;
1073 /* no worse than the last choice, so keep this one too? */
1074 else if (nmatch == nbestMatch)
1076 last_candidate->next = current_candidate;
1077 last_candidate = current_candidate;
1080 /* otherwise, don't bother keeping this one... */
1083 if (last_candidate) /* terminate rebuilt list */
1084 last_candidate->next = NULL;
1086 if (ncandidates == 1)
1090 * Still too many candidates? Now look for candidates which have either
1091 * exact matches or preferred types at the args that will require
1092 * coercion. (Restriction added in 7.4: preferred type must be of same
1093 * category as input type; give no preference to cross-category
1094 * conversions to preferred types.) Keep all candidates if none match.
1096 for (i = 0; i < nargs; i++) /* avoid multiple lookups */
1097 slot_category[i] = TypeCategory(input_base_typeids[i]);
1100 last_candidate = NULL;
1101 for (current_candidate = candidates;
1102 current_candidate != NULL;
1103 current_candidate = current_candidate->next)
1105 current_typeids = current_candidate->args;
1107 for (i = 0; i < nargs; i++)
1109 if (input_base_typeids[i] != UNKNOWNOID)
1111 if (current_typeids[i] == input_base_typeids[i] ||
1112 IsPreferredType(slot_category[i], current_typeids[i]))
1117 if ((nmatch > nbestMatch) || (last_candidate == NULL))
1119 nbestMatch = nmatch;
1120 candidates = current_candidate;
1121 last_candidate = current_candidate;
1124 else if (nmatch == nbestMatch)
1126 last_candidate->next = current_candidate;
1127 last_candidate = current_candidate;
1132 if (last_candidate) /* terminate rebuilt list */
1133 last_candidate->next = NULL;
1135 if (ncandidates == 1)
1139 * Still too many candidates? Try assigning types for the unknown inputs.
1141 * If there are no unknown inputs, we have no more heuristics that apply,
1145 return NULL; /* failed to select a best candidate */
1148 * The next step examines each unknown argument position to see if we can
1149 * determine a "type category" for it. If any candidate has an input
1150 * datatype of STRING category, use STRING category (this bias towards
1151 * STRING is appropriate since unknown-type literals look like strings).
1152 * Otherwise, if all the candidates agree on the type category of this
1153 * argument position, use that category. Otherwise, fail because we
1154 * cannot determine a category.
1156 * If we are able to determine a type category, also notice whether any of
1157 * the candidates takes a preferred datatype within the category.
1159 * Having completed this examination, remove candidates that accept the
1160 * wrong category at any unknown position. Also, if at least one
1161 * candidate accepted a preferred type at a position, remove candidates
1162 * that accept non-preferred types. If just one candidate remains, return
1163 * that one. However, if this rule turns out to reject all candidates,
1164 * keep them all instead.
1166 resolved_unknowns = false;
1167 for (i = 0; i < nargs; i++)
1171 if (input_base_typeids[i] != UNKNOWNOID)
1173 resolved_unknowns = true; /* assume we can do it */
1174 slot_category[i] = TYPCATEGORY_INVALID;
1175 slot_has_preferred_type[i] = false;
1176 have_conflict = false;
1177 for (current_candidate = candidates;
1178 current_candidate != NULL;
1179 current_candidate = current_candidate->next)
1181 current_typeids = current_candidate->args;
1182 current_type = current_typeids[i];
1183 get_type_category_preferred(current_type,
1185 ¤t_is_preferred);
1186 if (slot_category[i] == TYPCATEGORY_INVALID)
1188 /* first candidate */
1189 slot_category[i] = current_category;
1190 slot_has_preferred_type[i] = current_is_preferred;
1192 else if (current_category == slot_category[i])
1194 /* more candidates in same category */
1195 slot_has_preferred_type[i] |= current_is_preferred;
1199 /* category conflict! */
1200 if (current_category == TYPCATEGORY_STRING)
1202 /* STRING always wins if available */
1203 slot_category[i] = current_category;
1204 slot_has_preferred_type[i] = current_is_preferred;
1209 * Remember conflict, but keep going (might find STRING)
1211 have_conflict = true;
1215 if (have_conflict && slot_category[i] != TYPCATEGORY_STRING)
1217 /* Failed to resolve category conflict at this position */
1218 resolved_unknowns = false;
1223 if (resolved_unknowns)
1225 /* Strip non-matching candidates */
1227 first_candidate = candidates;
1228 last_candidate = NULL;
1229 for (current_candidate = candidates;
1230 current_candidate != NULL;
1231 current_candidate = current_candidate->next)
1235 current_typeids = current_candidate->args;
1236 for (i = 0; i < nargs; i++)
1238 if (input_base_typeids[i] != UNKNOWNOID)
1240 current_type = current_typeids[i];
1241 get_type_category_preferred(current_type,
1243 ¤t_is_preferred);
1244 if (current_category != slot_category[i])
1249 if (slot_has_preferred_type[i] && !current_is_preferred)
1257 /* keep this candidate */
1258 last_candidate = current_candidate;
1263 /* forget this candidate */
1265 last_candidate->next = current_candidate->next;
1267 first_candidate = current_candidate->next;
1271 /* if we found any matches, restrict our attention to those */
1274 candidates = first_candidate;
1275 /* terminate rebuilt list */
1276 last_candidate->next = NULL;
1279 if (ncandidates == 1)
1284 * Last gasp: if there are both known- and unknown-type inputs, and all
1285 * the known types are the same, assume the unknown inputs are also that
1286 * type, and see if that gives us a unique match. If so, use that match.
1288 * NOTE: for a binary operator with one unknown and one non-unknown input,
1289 * we already tried this heuristic in binary_oper_exact(). However, that
1290 * code only finds exact matches, whereas here we will handle matches that
1291 * involve coercion, polymorphic type resolution, etc.
1293 if (nunknowns < nargs)
1295 Oid known_type = UNKNOWNOID;
1297 for (i = 0; i < nargs; i++)
1299 if (input_base_typeids[i] == UNKNOWNOID)
1301 if (known_type == UNKNOWNOID) /* first known arg? */
1302 known_type = input_base_typeids[i];
1303 else if (known_type != input_base_typeids[i])
1305 /* oops, not all match */
1306 known_type = UNKNOWNOID;
1311 if (known_type != UNKNOWNOID)
1313 /* okay, just one known type, apply the heuristic */
1314 for (i = 0; i < nargs; i++)
1315 input_base_typeids[i] = known_type;
1317 last_candidate = NULL;
1318 for (current_candidate = candidates;
1319 current_candidate != NULL;
1320 current_candidate = current_candidate->next)
1322 current_typeids = current_candidate->args;
1323 if (can_coerce_type(nargs, input_base_typeids, current_typeids,
1326 if (++ncandidates > 1)
1327 break; /* not unique, give up */
1328 last_candidate = current_candidate;
1331 if (ncandidates == 1)
1333 /* successfully identified a unique match */
1334 last_candidate->next = NULL;
1335 return last_candidate;
1340 return NULL; /* failed to select a best candidate */
1341 } /* func_select_candidate() */
1344 /* func_get_detail()
1346 * Find the named function in the system catalogs.
1348 * Attempt to find the named function in the system catalogs with
1349 * arguments exactly as specified, so that the normal case (exact match)
1350 * is as quick as possible.
1352 * If an exact match isn't found:
1353 * 1) check for possible interpretation as a type coercion request
1354 * 2) apply the ambiguous-function resolution rules
1356 * Return values *funcid through *true_typeids receive info about the function.
1357 * If argdefaults isn't NULL, *argdefaults receives a list of any default
1358 * argument expressions that need to be added to the given arguments.
1360 * When processing a named- or mixed-notation call (ie, fargnames isn't NIL),
1361 * the returned true_typeids and argdefaults are ordered according to the
1362 * call's argument ordering: first any positional arguments, then the named
1363 * arguments, then defaulted arguments (if needed and allowed by
1364 * expand_defaults). Some care is needed if this information is to be compared
1365 * to the function's pg_proc entry, but in practice the caller can usually
1366 * just work with the call's argument ordering.
1368 * We rely primarily on fargnames/nargs/argtypes as the argument description.
1369 * The actual expression node list is passed in fargs so that we can check
1370 * for type coercion of a constant. Some callers pass fargs == NIL indicating
1371 * they don't need that check made. Note also that when fargnames isn't NIL,
1372 * the fargs list must be passed if the caller wants actual argument position
1373 * information to be returned into the NamedArgExpr nodes.
1376 func_get_detail(List *funcname,
1381 bool expand_variadic,
1382 bool expand_defaults,
1383 Oid *funcid, /* return value */
1384 Oid *rettype, /* return value */
1385 bool *retset, /* return value */
1386 int *nvargs, /* return value */
1387 Oid *vatype, /* return value */
1388 Oid **true_typeids, /* return value */
1389 List **argdefaults) /* optional return value */
1391 FuncCandidateList raw_candidates;
1392 FuncCandidateList best_candidate;
1394 /* Passing NULL for argtypes is no longer allowed */
1397 /* initialize output arguments to silence compiler warnings */
1398 *funcid = InvalidOid;
1399 *rettype = InvalidOid;
1402 *vatype = InvalidOid;
1403 *true_typeids = NULL;
1407 /* Get list of possible candidates from namespace search */
1408 raw_candidates = FuncnameGetCandidates(funcname, nargs, fargnames,
1409 expand_variadic, expand_defaults,
1413 * Quickly check if there is an exact match to the input datatypes (there
1416 for (best_candidate = raw_candidates;
1417 best_candidate != NULL;
1418 best_candidate = best_candidate->next)
1420 if (memcmp(argtypes, best_candidate->args, nargs * sizeof(Oid)) == 0)
1424 if (best_candidate == NULL)
1427 * If we didn't find an exact match, next consider the possibility
1428 * that this is really a type-coercion request: a single-argument
1429 * function call where the function name is a type name. If so, and
1430 * if the coercion path is RELABELTYPE or COERCEVIAIO, then go ahead
1431 * and treat the "function call" as a coercion.
1433 * This interpretation needs to be given higher priority than
1434 * interpretations involving a type coercion followed by a function
1435 * call, otherwise we can produce surprising results. For example, we
1436 * want "text(varchar)" to be interpreted as a simple coercion, not as
1437 * "text(name(varchar))" which the code below this point is entirely
1438 * capable of selecting.
1440 * We also treat a coercion of a previously-unknown-type literal
1441 * constant to a specific type this way.
1443 * The reason we reject COERCION_PATH_FUNC here is that we expect the
1444 * cast implementation function to be named after the target type.
1445 * Thus the function will be found by normal lookup if appropriate.
1447 * The reason we reject COERCION_PATH_ARRAYCOERCE is mainly that you
1448 * can't write "foo[] (something)" as a function call. In theory
1449 * someone might want to invoke it as "_foo (something)" but we have
1450 * never supported that historically, so we can insist that people
1451 * write it as a normal cast instead.
1453 * We also reject the specific case of COERCEVIAIO for a composite
1454 * source type and a string-category target type. This is a case that
1455 * find_coercion_pathway() allows by default, but experience has shown
1456 * that it's too commonly invoked by mistake. So, again, insist that
1457 * people use cast syntax if they want to do that.
1459 * NB: it's important that this code does not exceed what coerce_type
1460 * can do, because the caller will try to apply coerce_type if we
1461 * return FUNCDETAIL_COERCION. If we return that result for something
1462 * coerce_type can't handle, we'll cause infinite recursion between
1463 * this module and coerce_type!
1465 if (nargs == 1 && fargs != NIL && fargnames == NIL)
1467 Oid targetType = FuncNameAsType(funcname);
1469 if (OidIsValid(targetType))
1471 Oid sourceType = argtypes[0];
1472 Node *arg1 = linitial(fargs);
1475 if (sourceType == UNKNOWNOID && IsA(arg1, Const))
1477 /* always treat typename('literal') as coercion */
1482 CoercionPathType cpathtype;
1485 cpathtype = find_coercion_pathway(targetType, sourceType,
1490 case COERCION_PATH_RELABELTYPE:
1493 case COERCION_PATH_COERCEVIAIO:
1494 if ((sourceType == RECORDOID ||
1495 ISCOMPLEX(sourceType)) &&
1496 TypeCategory(targetType) == TYPCATEGORY_STRING)
1509 /* Treat it as a type coercion */
1510 *funcid = InvalidOid;
1511 *rettype = targetType;
1514 *vatype = InvalidOid;
1515 *true_typeids = argtypes;
1516 return FUNCDETAIL_COERCION;
1522 * didn't find an exact match, so now try to match up candidates...
1524 if (raw_candidates != NULL)
1526 FuncCandidateList current_candidates;
1529 ncandidates = func_match_argtypes(nargs,
1532 ¤t_candidates);
1534 /* one match only? then run with it... */
1535 if (ncandidates == 1)
1536 best_candidate = current_candidates;
1539 * multiple candidates? then better decide or throw an error...
1541 else if (ncandidates > 1)
1543 best_candidate = func_select_candidate(nargs,
1545 current_candidates);
1548 * If we were able to choose a best candidate, we're done.
1549 * Otherwise, ambiguous function call.
1551 if (!best_candidate)
1552 return FUNCDETAIL_MULTIPLE;
1561 FuncDetailCode result;
1564 * If processing named args or expanding variadics or defaults, the
1565 * "best candidate" might represent multiple equivalently good
1566 * functions; treat this case as ambiguous.
1568 if (!OidIsValid(best_candidate->oid))
1569 return FUNCDETAIL_MULTIPLE;
1572 * We disallow VARIADIC with named arguments unless the last argument
1573 * (the one with VARIADIC attached) actually matched the variadic
1574 * parameter. This is mere pedantry, really, but some folks insisted.
1576 if (fargnames != NIL && !expand_variadic && nargs > 0 &&
1577 best_candidate->argnumbers[nargs - 1] != nargs - 1)
1578 return FUNCDETAIL_NOTFOUND;
1580 *funcid = best_candidate->oid;
1581 *nvargs = best_candidate->nvargs;
1582 *true_typeids = best_candidate->args;
1585 * If processing named args, return actual argument positions into
1586 * NamedArgExpr nodes in the fargs list. This is a bit ugly but not
1587 * worth the extra notation needed to do it differently.
1589 if (best_candidate->argnumbers != NULL)
1596 NamedArgExpr *na = (NamedArgExpr *) lfirst(lc);
1598 if (IsA(na, NamedArgExpr))
1599 na->argnumber = best_candidate->argnumbers[i];
1604 ftup = SearchSysCache1(PROCOID,
1605 ObjectIdGetDatum(best_candidate->oid));
1606 if (!HeapTupleIsValid(ftup)) /* should not happen */
1607 elog(ERROR, "cache lookup failed for function %u",
1608 best_candidate->oid);
1609 pform = (Form_pg_proc) GETSTRUCT(ftup);
1610 *rettype = pform->prorettype;
1611 *retset = pform->proretset;
1612 *vatype = pform->provariadic;
1613 /* fetch default args if caller wants 'em */
1614 if (argdefaults && best_candidate->ndargs > 0)
1616 Datum proargdefaults;
1621 /* shouldn't happen, FuncnameGetCandidates messed up */
1622 if (best_candidate->ndargs > pform->pronargdefaults)
1623 elog(ERROR, "not enough default arguments");
1625 proargdefaults = SysCacheGetAttr(PROCOID, ftup,
1626 Anum_pg_proc_proargdefaults,
1629 str = TextDatumGetCString(proargdefaults);
1630 defaults = castNode(List, stringToNode(str));
1633 /* Delete any unused defaults from the returned list */
1634 if (best_candidate->argnumbers != NULL)
1637 * This is a bit tricky in named notation, since the supplied
1638 * arguments could replace any subset of the defaults. We
1639 * work by making a bitmapset of the argnumbers of defaulted
1640 * arguments, then scanning the defaults list and selecting
1641 * the needed items. (This assumes that defaulted arguments
1642 * should be supplied in their positional order.)
1644 Bitmapset *defargnumbers;
1650 defargnumbers = NULL;
1651 firstdefarg = &best_candidate->argnumbers[best_candidate->nargs - best_candidate->ndargs];
1652 for (i = 0; i < best_candidate->ndargs; i++)
1653 defargnumbers = bms_add_member(defargnumbers,
1656 i = pform->pronargs - pform->pronargdefaults;
1657 foreach(lc, defaults)
1659 if (bms_is_member(i, defargnumbers))
1660 newdefaults = lappend(newdefaults, lfirst(lc));
1663 Assert(list_length(newdefaults) == best_candidate->ndargs);
1664 bms_free(defargnumbers);
1665 *argdefaults = newdefaults;
1670 * Defaults for positional notation are lots easier; just
1671 * remove any unwanted ones from the front.
1675 ndelete = list_length(defaults) - best_candidate->ndargs;
1676 while (ndelete-- > 0)
1677 defaults = list_delete_first(defaults);
1678 *argdefaults = defaults;
1682 switch (pform->prokind)
1684 case PROKIND_AGGREGATE:
1685 result = FUNCDETAIL_AGGREGATE;
1687 case PROKIND_FUNCTION:
1688 result = FUNCDETAIL_NORMAL;
1690 case PROKIND_PROCEDURE:
1691 result = FUNCDETAIL_PROCEDURE;
1693 case PROKIND_WINDOW:
1694 result = FUNCDETAIL_WINDOWFUNC;
1697 elog(ERROR, "unrecognized prokind: %c", pform->prokind);
1698 result = FUNCDETAIL_NORMAL; /* keep compiler quiet */
1702 ReleaseSysCache(ftup);
1706 return FUNCDETAIL_NOTFOUND;
1711 * unify_hypothetical_args()
1713 * Ensure that each hypothetical direct argument of a hypothetical-set
1714 * aggregate has the same type as the corresponding aggregated argument.
1715 * Modify the expressions in the fargs list, if necessary, and update
1716 * actual_arg_types[].
1718 * If the agg declared its args non-ANY (even ANYELEMENT), we need only a
1719 * sanity check that the declared types match; make_fn_arguments will coerce
1720 * the actual arguments to match the declared ones. But if the declaration
1721 * is ANY, nothing will happen in make_fn_arguments, so we need to fix any
1722 * mismatch here. We use the same type resolution logic as UNION etc.
1725 unify_hypothetical_args(ParseState *pstate,
1727 int numAggregatedArgs,
1728 Oid *actual_arg_types,
1729 Oid *declared_arg_types)
1731 Node *args[FUNC_MAX_ARGS];
1733 numNonHypotheticalArgs;
1737 numDirectArgs = list_length(fargs) - numAggregatedArgs;
1738 numNonHypotheticalArgs = numDirectArgs - numAggregatedArgs;
1739 /* safety check (should only trigger with a misdeclared agg) */
1740 if (numNonHypotheticalArgs < 0)
1741 elog(ERROR, "incorrect number of arguments to hypothetical-set aggregate");
1743 /* Deconstruct fargs into an array for ease of subscripting */
1747 args[i++] = (Node *) lfirst(lc);
1750 /* Check each hypothetical arg and corresponding aggregated arg */
1751 for (i = numNonHypotheticalArgs; i < numDirectArgs; i++)
1753 int aargpos = numDirectArgs + (i - numNonHypotheticalArgs);
1756 /* A mismatch means AggregateCreate didn't check properly ... */
1757 if (declared_arg_types[i] != declared_arg_types[aargpos])
1758 elog(ERROR, "hypothetical-set aggregate has inconsistent declared argument types");
1760 /* No need to unify if make_fn_arguments will coerce */
1761 if (declared_arg_types[i] != ANYOID)
1765 * Select common type, giving preference to the aggregated argument's
1766 * type (we'd rather coerce the direct argument once than coerce all
1767 * the aggregated values).
1769 commontype = select_common_type(pstate,
1770 list_make2(args[aargpos], args[i]),
1775 * Perform the coercions. We don't need to worry about NamedArgExprs
1776 * here because they aren't supported with aggregates.
1778 args[i] = coerce_type(pstate,
1780 actual_arg_types[i],
1783 COERCE_IMPLICIT_CAST,
1785 actual_arg_types[i] = commontype;
1786 args[aargpos] = coerce_type(pstate,
1788 actual_arg_types[aargpos],
1791 COERCE_IMPLICIT_CAST,
1793 actual_arg_types[aargpos] = commontype;
1796 /* Reconstruct fargs from array */
1800 lfirst(lc) = args[i++];
1806 * make_fn_arguments()
1808 * Given the actual argument expressions for a function, and the desired
1809 * input types for the function, add any necessary typecasting to the
1810 * expression tree. Caller should already have verified that casting is
1813 * Caution: given argument list is modified in-place.
1815 * As with coerce_type, pstate may be NULL if no special unknown-Param
1816 * processing is wanted.
1819 make_fn_arguments(ParseState *pstate,
1821 Oid *actual_arg_types,
1822 Oid *declared_arg_types)
1824 ListCell *current_fargs;
1827 foreach(current_fargs, fargs)
1829 /* types don't match? then force coercion using a function call... */
1830 if (actual_arg_types[i] != declared_arg_types[i])
1832 Node *node = (Node *) lfirst(current_fargs);
1835 * If arg is a NamedArgExpr, coerce its input expr instead --- we
1836 * want the NamedArgExpr to stay at the top level of the list.
1838 if (IsA(node, NamedArgExpr))
1840 NamedArgExpr *na = (NamedArgExpr *) node;
1842 node = coerce_type(pstate,
1844 actual_arg_types[i],
1845 declared_arg_types[i], -1,
1847 COERCE_IMPLICIT_CAST,
1849 na->arg = (Expr *) node;
1853 node = coerce_type(pstate,
1855 actual_arg_types[i],
1856 declared_arg_types[i], -1,
1858 COERCE_IMPLICIT_CAST,
1860 lfirst(current_fargs) = node;
1869 * convenience routine to see if a function name matches a type name
1871 * Returns the OID of the matching type, or InvalidOid if none. We ignore
1872 * shell types and complex types.
1875 FuncNameAsType(List *funcname)
1880 typtup = LookupTypeName(NULL, makeTypeNameFromNameList(funcname), NULL, false);
1884 if (((Form_pg_type) GETSTRUCT(typtup))->typisdefined &&
1885 !OidIsValid(typeTypeRelid(typtup)))
1886 result = typeTypeId(typtup);
1888 result = InvalidOid;
1890 ReleaseSysCache(typtup);
1895 * ParseComplexProjection -
1896 * handles function calls with a single argument that is of complex type.
1897 * If the function call is actually a column projection, return a suitably
1898 * transformed expression tree. If not, return NULL.
1901 ParseComplexProjection(ParseState *pstate, const char *funcname, Node *first_arg,
1908 * Special case for whole-row Vars so that we can resolve (foo.*).bar even
1909 * when foo is a reference to a subselect, join, or RECORD function. A
1910 * bonus is that we avoid generating an unnecessary FieldSelect; our
1911 * result can omit the whole-row Var and just be a Var for the selected
1914 * This case could be handled by expandRecordVariable, but it's more
1915 * efficient to do it this way when possible.
1917 if (IsA(first_arg, Var) &&
1918 ((Var *) first_arg)->varattno == InvalidAttrNumber)
1922 rte = GetRTEByRangeTablePosn(pstate,
1923 ((Var *) first_arg)->varno,
1924 ((Var *) first_arg)->varlevelsup);
1925 /* Return a Var if funcname matches a column, else NULL */
1926 return scanRTEForColumn(pstate, rte, funcname, location, 0, NULL);
1930 * Else do it the hard way with get_expr_result_tupdesc().
1932 * If it's a Var of type RECORD, we have to work even harder: we have to
1933 * find what the Var refers to, and pass that to get_expr_result_tupdesc.
1934 * That task is handled by expandRecordVariable().
1936 if (IsA(first_arg, Var) &&
1937 ((Var *) first_arg)->vartype == RECORDOID)
1938 tupdesc = expandRecordVariable(pstate, (Var *) first_arg, 0);
1940 tupdesc = get_expr_result_tupdesc(first_arg, true);
1942 return NULL; /* unresolvable RECORD type */
1944 for (i = 0; i < tupdesc->natts; i++)
1946 Form_pg_attribute att = TupleDescAttr(tupdesc, i);
1948 if (strcmp(funcname, NameStr(att->attname)) == 0 &&
1951 /* Success, so generate a FieldSelect expression */
1952 FieldSelect *fselect = makeNode(FieldSelect);
1954 fselect->arg = (Expr *) first_arg;
1955 fselect->fieldnum = i + 1;
1956 fselect->resulttype = att->atttypid;
1957 fselect->resulttypmod = att->atttypmod;
1958 /* save attribute's collation for parse_collate.c */
1959 fselect->resultcollid = att->attcollation;
1960 return (Node *) fselect;
1964 return NULL; /* funcname does not match any column */
1968 * funcname_signature_string
1969 * Build a string representing a function name, including arg types.
1970 * The result is something like "foo(integer)".
1972 * If argnames isn't NIL, it is a list of C strings representing the actual
1973 * arg names for the last N arguments. This must be considered part of the
1974 * function signature too, when dealing with named-notation function calls.
1976 * This is typically used in the construction of function-not-found error
1980 funcname_signature_string(const char *funcname, int nargs,
1981 List *argnames, const Oid *argtypes)
1983 StringInfoData argbuf;
1988 initStringInfo(&argbuf);
1990 appendStringInfo(&argbuf, "%s(", funcname);
1992 numposargs = nargs - list_length(argnames);
1993 lc = list_head(argnames);
1995 for (i = 0; i < nargs; i++)
1998 appendStringInfoString(&argbuf, ", ");
1999 if (i >= numposargs)
2001 appendStringInfo(&argbuf, "%s => ", (char *) lfirst(lc));
2004 appendStringInfoString(&argbuf, format_type_be(argtypes[i]));
2007 appendStringInfoChar(&argbuf, ')');
2009 return argbuf.data; /* return palloc'd string buffer */
2013 * func_signature_string
2014 * As above, but function name is passed as a qualified name list.
2017 func_signature_string(List *funcname, int nargs,
2018 List *argnames, const Oid *argtypes)
2020 return funcname_signature_string(NameListToString(funcname),
2021 nargs, argnames, argtypes);
2027 * Given a possibly-qualified function name and optionally a set of argument
2028 * types, look up the function. Pass nargs == -1 to indicate that no argument
2029 * types are specified.
2031 * If the function name is not schema-qualified, it is sought in the current
2032 * namespace search path.
2034 * If the function is not found, we return InvalidOid if noError is true,
2035 * else raise an error.
2038 LookupFuncName(List *funcname, int nargs, const Oid *argtypes, bool noError)
2040 FuncCandidateList clist;
2042 /* Passing NULL for argtypes is no longer allowed */
2045 clist = FuncnameGetCandidates(funcname, nargs, NIL, false, false, noError);
2048 * If no arguments were specified, the name must yield a unique candidate.
2058 (errcode(ERRCODE_AMBIGUOUS_FUNCTION),
2059 errmsg("function name \"%s\" is not unique",
2060 NameListToString(funcname)),
2061 errhint("Specify the argument list to select the function unambiguously.")));
2070 (errcode(ERRCODE_UNDEFINED_FUNCTION),
2071 errmsg("could not find a function named \"%s\"",
2072 NameListToString(funcname))));
2078 if (memcmp(argtypes, clist->args, nargs * sizeof(Oid)) == 0)
2080 clist = clist->next;
2085 (errcode(ERRCODE_UNDEFINED_FUNCTION),
2086 errmsg("function %s does not exist",
2087 func_signature_string(funcname, nargs,
2094 * LookupFuncWithArgs
2096 * Like LookupFuncName, but the argument types are specified by a
2097 * ObjectWithArgs node. Also, this function can check whether the result is a
2098 * function, procedure, or aggregate, based on the objtype argument. Pass
2099 * OBJECT_ROUTINE to accept any of them.
2101 * For historical reasons, we also accept aggregates when looking for a
2105 LookupFuncWithArgs(ObjectType objtype, ObjectWithArgs *func, bool noError)
2107 Oid argoids[FUNC_MAX_ARGS];
2110 ListCell *args_item;
2113 Assert(objtype == OBJECT_AGGREGATE ||
2114 objtype == OBJECT_FUNCTION ||
2115 objtype == OBJECT_PROCEDURE ||
2116 objtype == OBJECT_ROUTINE);
2118 argcount = list_length(func->objargs);
2119 if (argcount > FUNC_MAX_ARGS)
2121 (errcode(ERRCODE_TOO_MANY_ARGUMENTS),
2122 errmsg_plural("functions cannot have more than %d argument",
2123 "functions cannot have more than %d arguments",
2127 args_item = list_head(func->objargs);
2128 for (i = 0; i < argcount; i++)
2130 TypeName *t = (TypeName *) lfirst(args_item);
2132 argoids[i] = LookupTypeNameOid(NULL, t, noError);
2133 args_item = lnext(args_item);
2137 * When looking for a function or routine, we pass noError through to
2138 * LookupFuncName and let it make any error messages. Otherwise, we make
2139 * our own errors for the aggregate and procedure cases.
2141 oid = LookupFuncName(func->objname, func->args_unspecified ? -1 : argcount, argoids,
2142 (objtype == OBJECT_FUNCTION || objtype == OBJECT_ROUTINE) ? noError : true);
2144 if (objtype == OBJECT_FUNCTION)
2146 /* Make sure it's a function, not a procedure */
2147 if (oid && get_func_prokind(oid) == PROKIND_PROCEDURE)
2152 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2153 errmsg("%s is not a function",
2154 func_signature_string(func->objname, argcount,
2158 else if (objtype == OBJECT_PROCEDURE)
2160 if (!OidIsValid(oid))
2164 else if (func->args_unspecified)
2166 (errcode(ERRCODE_UNDEFINED_FUNCTION),
2167 errmsg("could not find a procedure named \"%s\"",
2168 NameListToString(func->objname))));
2171 (errcode(ERRCODE_UNDEFINED_FUNCTION),
2172 errmsg("procedure %s does not exist",
2173 func_signature_string(func->objname, argcount,
2177 /* Make sure it's a procedure */
2178 if (get_func_prokind(oid) != PROKIND_PROCEDURE)
2183 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2184 errmsg("%s is not a procedure",
2185 func_signature_string(func->objname, argcount,
2189 else if (objtype == OBJECT_AGGREGATE)
2191 if (!OidIsValid(oid))
2195 else if (func->args_unspecified)
2197 (errcode(ERRCODE_UNDEFINED_FUNCTION),
2198 errmsg("could not find an aggregate named \"%s\"",
2199 NameListToString(func->objname))));
2200 else if (argcount == 0)
2202 (errcode(ERRCODE_UNDEFINED_FUNCTION),
2203 errmsg("aggregate %s(*) does not exist",
2204 NameListToString(func->objname))));
2207 (errcode(ERRCODE_UNDEFINED_FUNCTION),
2208 errmsg("aggregate %s does not exist",
2209 func_signature_string(func->objname, argcount,
2213 /* Make sure it's an aggregate */
2214 if (get_func_prokind(oid) != PROKIND_AGGREGATE)
2218 /* we do not use the (*) notation for functions... */
2220 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2221 errmsg("function %s is not an aggregate",
2222 func_signature_string(func->objname, argcount,
2231 * check_srf_call_placement
2232 * Verify that a set-returning function is called in a valid place,
2233 * and throw a nice error if not.
2235 * A side-effect is to set pstate->p_hasTargetSRFs true if appropriate.
2237 * last_srf should be a copy of pstate->p_last_srf from just before we
2238 * started transforming the function's arguments. This allows detection
2239 * of whether the SRF's arguments contain any SRFs.
2242 check_srf_call_placement(ParseState *pstate, Node *last_srf, int location)
2248 * Check to see if the set-returning function is in an invalid place
2249 * within the query. Basically, we don't allow SRFs anywhere except in
2250 * the targetlist (which includes GROUP BY/ORDER BY expressions), VALUES,
2251 * and functions in FROM.
2253 * For brevity we support two schemes for reporting an error here: set
2254 * "err" to a custom message, or set "errkind" true if the error context
2255 * is sufficiently identified by what ParseExprKindName will return, *and*
2256 * what it will return is just a SQL keyword. (Otherwise, use a custom
2257 * message to avoid creating translation problems.)
2261 switch (pstate->p_expr_kind)
2263 case EXPR_KIND_NONE:
2264 Assert(false); /* can't happen */
2266 case EXPR_KIND_OTHER:
2267 /* Accept SRF here; caller must throw error if wanted */
2269 case EXPR_KIND_JOIN_ON:
2270 case EXPR_KIND_JOIN_USING:
2271 err = _("set-returning functions are not allowed in JOIN conditions");
2273 case EXPR_KIND_FROM_SUBSELECT:
2274 /* can't get here, but just in case, throw an error */
2277 case EXPR_KIND_FROM_FUNCTION:
2278 /* okay, but we don't allow nested SRFs here */
2279 /* errmsg is chosen to match transformRangeFunction() */
2280 /* errposition should point to the inner SRF */
2281 if (pstate->p_last_srf != last_srf)
2283 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2284 errmsg("set-returning functions must appear at top level of FROM"),
2285 parser_errposition(pstate,
2286 exprLocation(pstate->p_last_srf))));
2288 case EXPR_KIND_WHERE:
2291 case EXPR_KIND_POLICY:
2292 err = _("set-returning functions are not allowed in policy expressions");
2294 case EXPR_KIND_HAVING:
2297 case EXPR_KIND_FILTER:
2300 case EXPR_KIND_WINDOW_PARTITION:
2301 case EXPR_KIND_WINDOW_ORDER:
2302 /* okay, these are effectively GROUP BY/ORDER BY */
2303 pstate->p_hasTargetSRFs = true;
2305 case EXPR_KIND_WINDOW_FRAME_RANGE:
2306 case EXPR_KIND_WINDOW_FRAME_ROWS:
2307 case EXPR_KIND_WINDOW_FRAME_GROUPS:
2308 err = _("set-returning functions are not allowed in window definitions");
2310 case EXPR_KIND_SELECT_TARGET:
2311 case EXPR_KIND_INSERT_TARGET:
2313 pstate->p_hasTargetSRFs = true;
2315 case EXPR_KIND_UPDATE_SOURCE:
2316 case EXPR_KIND_UPDATE_TARGET:
2317 /* disallowed because it would be ambiguous what to do */
2320 case EXPR_KIND_GROUP_BY:
2321 case EXPR_KIND_ORDER_BY:
2323 pstate->p_hasTargetSRFs = true;
2325 case EXPR_KIND_DISTINCT_ON:
2327 pstate->p_hasTargetSRFs = true;
2329 case EXPR_KIND_LIMIT:
2330 case EXPR_KIND_OFFSET:
2333 case EXPR_KIND_RETURNING:
2336 case EXPR_KIND_VALUES:
2337 /* SRFs are presently not supported by nodeValuesscan.c */
2340 case EXPR_KIND_VALUES_SINGLE:
2341 /* okay, since we process this like a SELECT tlist */
2342 pstate->p_hasTargetSRFs = true;
2344 case EXPR_KIND_CHECK_CONSTRAINT:
2345 case EXPR_KIND_DOMAIN_CHECK:
2346 err = _("set-returning functions are not allowed in check constraints");
2348 case EXPR_KIND_COLUMN_DEFAULT:
2349 case EXPR_KIND_FUNCTION_DEFAULT:
2350 err = _("set-returning functions are not allowed in DEFAULT expressions");
2352 case EXPR_KIND_INDEX_EXPRESSION:
2353 err = _("set-returning functions are not allowed in index expressions");
2355 case EXPR_KIND_INDEX_PREDICATE:
2356 err = _("set-returning functions are not allowed in index predicates");
2358 case EXPR_KIND_ALTER_COL_TRANSFORM:
2359 err = _("set-returning functions are not allowed in transform expressions");
2361 case EXPR_KIND_EXECUTE_PARAMETER:
2362 err = _("set-returning functions are not allowed in EXECUTE parameters");
2364 case EXPR_KIND_TRIGGER_WHEN:
2365 err = _("set-returning functions are not allowed in trigger WHEN conditions");
2367 case EXPR_KIND_PARTITION_EXPRESSION:
2368 err = _("set-returning functions are not allowed in partition key expressions");
2370 case EXPR_KIND_CALL_ARGUMENT:
2371 err = _("set-returning functions are not allowed in CALL arguments");
2375 * There is intentionally no default: case here, so that the
2376 * compiler will warn if we add a new ParseExprKind without
2377 * extending this switch. If we do see an unrecognized value at
2378 * runtime, the behavior will be the same as for EXPR_KIND_OTHER,
2379 * which is sane anyway.
2384 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2385 errmsg_internal("%s", err),
2386 parser_errposition(pstate, location)));
2389 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2390 /* translator: %s is name of a SQL construct, eg GROUP BY */
2391 errmsg("set-returning functions are not allowed in %s",
2392 ParseExprKindName(pstate->p_expr_kind)),
2393 parser_errposition(pstate, location)));