1 /*-------------------------------------------------------------------------
4 * handle function calls in parser
6 * Portions Copyright (c) 1996-2009, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
13 *-------------------------------------------------------------------------
17 #include "catalog/pg_proc.h"
18 #include "catalog/pg_type.h"
20 #include "nodes/makefuncs.h"
21 #include "nodes/nodeFuncs.h"
22 #include "parser/parse_agg.h"
23 #include "parser/parse_coerce.h"
24 #include "parser/parse_func.h"
25 #include "parser/parse_relation.h"
26 #include "parser/parse_target.h"
27 #include "parser/parse_type.h"
28 #include "utils/builtins.h"
29 #include "utils/lsyscache.h"
30 #include "utils/syscache.h"
33 static Oid
FuncNameAsType(List
*funcname
);
34 static Node
*ParseComplexProjection(ParseState
*pstate
, char *funcname
,
35 Node
*first_arg
, int location
);
36 static void unknown_attribute(ParseState
*pstate
, Node
*relref
, char *attname
,
41 * Parse a function call
43 * For historical reasons, Postgres tries to treat the notations tab.col
44 * and col(tab) as equivalent: if a single-argument function call has an
45 * argument of complex type and the (unqualified) function name matches
46 * any attribute of the type, we take it as a column projection. Conversely
47 * a function of a single complex-type argument can be written like a
48 * column reference, allowing functions to act like computed columns.
50 * Hence, both cases come through here. The is_column parameter tells us
51 * which syntactic construct is actually being dealt with, but this is
52 * intended to be used only to deliver an appropriate error message,
53 * not to affect the semantics. When is_column is true, we should have
54 * a single argument (the putative table), unqualified function name
55 * equal to the column name, and no aggregate or variadic decoration.
57 * The argument expressions (in fargs) must have been transformed already.
60 ParseFuncOrColumn(ParseState
*pstate
, List
*funcname
, List
*fargs
,
61 bool agg_star
, bool agg_distinct
, bool func_variadic
,
62 WindowDef
*over
, bool is_column
, int location
)
68 Node
*first_arg
= NULL
;
71 Oid actual_arg_types
[FUNC_MAX_ARGS
];
72 Oid
*declared_arg_types
;
77 FuncDetailCode fdresult
;
80 * Most of the rest of the parser just assumes that functions do not have
81 * more than FUNC_MAX_ARGS parameters. We have to test here to protect
82 * against array overruns, etc. Of course, this may not be a function,
83 * but the test doesn't hurt.
85 if (list_length(fargs
) > FUNC_MAX_ARGS
)
87 (errcode(ERRCODE_TOO_MANY_ARGUMENTS
),
88 errmsg_plural("cannot pass more than %d argument to a function",
89 "cannot pass more than %d arguments to a function",
92 parser_errposition(pstate
, location
)));
95 * Extract arg type info in preparation for function lookup.
97 * If any arguments are Param markers of type VOID, we discard them from
98 * the parameter list. This is a hack to allow the JDBC driver to not
99 * have to distinguish "input" and "output" parameter symbols while
100 * parsing function-call constructs. We can't use foreach() because we
101 * may modify the list ...
104 for (l
= list_head(fargs
); l
!= NULL
; l
= nextl
)
106 Node
*arg
= lfirst(l
);
107 Oid argtype
= exprType(arg
);
111 if (argtype
== VOIDOID
&& IsA(arg
, Param
) &&!is_column
)
113 fargs
= list_delete_ptr(fargs
, arg
);
117 actual_arg_types
[nargs
++] = argtype
;
122 first_arg
= linitial(fargs
);
123 Assert(first_arg
!= NULL
);
127 * Check for column projection: if function has one argument, and that
128 * argument is of complex type, and function name is not qualified, then
129 * the "function call" could be a projection. We also check that there
130 * wasn't any aggregate or variadic decoration.
132 if (nargs
== 1 && !agg_star
&& !agg_distinct
&& over
== NULL
&&
133 !func_variadic
&& list_length(funcname
) == 1)
135 Oid argtype
= actual_arg_types
[0];
137 if (argtype
== RECORDOID
|| ISCOMPLEX(argtype
))
139 retval
= ParseComplexProjection(pstate
,
140 strVal(linitial(funcname
)),
147 * If ParseComplexProjection doesn't recognize it as a projection,
154 * Okay, it's not a column projection, so it must really be a function.
155 * func_get_detail looks up the function in the catalogs, does
156 * disambiguation for polymorphic functions, handles inheritance, and
157 * returns the funcid and type and set or singleton status of the
158 * function's return value. It also returns the true argument types to
159 * the function. In the case of a variadic function call, the reported
160 * "true" types aren't really what is in pg_proc: the variadic argument is
161 * replaced by a suitable number of copies of its element type. We'll fix
162 * it up below. We may also have to deal with default arguments.
164 fdresult
= func_get_detail(funcname
, fargs
, nargs
, actual_arg_types
,
165 !func_variadic
, true,
166 &funcid
, &rettype
, &retset
, &nvargs
,
167 &declared_arg_types
, &argdefaults
);
168 if (fdresult
== FUNCDETAIL_COERCION
)
171 * We interpreted it as a type coercion. coerce_type can handle these
172 * cases, so why duplicate code...
174 return coerce_type(pstate
, linitial(fargs
),
175 actual_arg_types
[0], rettype
, -1,
176 COERCION_EXPLICIT
, COERCE_EXPLICIT_CALL
, location
);
178 else if (fdresult
== FUNCDETAIL_NORMAL
)
181 * Normal function found; was there anything indicating it must be an
186 (errcode(ERRCODE_WRONG_OBJECT_TYPE
),
187 errmsg("%s(*) specified, but %s is not an aggregate function",
188 NameListToString(funcname
),
189 NameListToString(funcname
)),
190 parser_errposition(pstate
, location
)));
193 (errcode(ERRCODE_WRONG_OBJECT_TYPE
),
194 errmsg("DISTINCT specified, but %s is not an aggregate function",
195 NameListToString(funcname
)),
196 parser_errposition(pstate
, location
)));
199 (errcode(ERRCODE_WRONG_OBJECT_TYPE
),
200 errmsg("OVER specified, but %s is not a window function nor an aggregate function",
201 NameListToString(funcname
)),
202 parser_errposition(pstate
, location
)));
204 else if (!(fdresult
== FUNCDETAIL_AGGREGATE
||
205 fdresult
== FUNCDETAIL_WINDOWFUNC
))
210 * If we are dealing with the attribute notation rel.function, give an
211 * error message that is appropriate for that case.
216 Assert(list_length(funcname
) == 1);
217 unknown_attribute(pstate
, first_arg
, strVal(linitial(funcname
)),
222 * Else generate a detailed complaint for a function
224 if (fdresult
== FUNCDETAIL_MULTIPLE
)
226 (errcode(ERRCODE_AMBIGUOUS_FUNCTION
),
227 errmsg("function %s is not unique",
228 func_signature_string(funcname
, nargs
,
230 errhint("Could not choose a best candidate function. "
231 "You might need to add explicit type casts."),
232 parser_errposition(pstate
, location
)));
235 (errcode(ERRCODE_UNDEFINED_FUNCTION
),
236 errmsg("function %s does not exist",
237 func_signature_string(funcname
, nargs
,
239 errhint("No function matches the given name and argument types. "
240 "You might need to add explicit type casts."),
241 parser_errposition(pstate
, location
)));
245 * If there are default arguments, we have to include their types in
246 * actual_arg_types for the purpose of checking generic type consistency.
247 * However, we do NOT put them into the generated parse node, because
248 * their actual values might change before the query gets run. The
249 * planner has to insert the up-to-date values at plan time.
251 nargsplusdefs
= nargs
;
252 foreach(l
, argdefaults
)
254 Node
*expr
= (Node
*) lfirst(l
);
256 /* probably shouldn't happen ... */
257 if (nargsplusdefs
>= FUNC_MAX_ARGS
)
259 (errcode(ERRCODE_TOO_MANY_ARGUMENTS
),
260 errmsg_plural("cannot pass more than %d argument to a function",
261 "cannot pass more than %d arguments to a function",
264 parser_errposition(pstate
, location
)));
266 actual_arg_types
[nargsplusdefs
++] = exprType(expr
);
270 * enforce consistency with polymorphic argument and return types,
271 * possibly adjusting return type or declared_arg_types (which will be
272 * used as the cast destination by make_fn_arguments)
274 rettype
= enforce_generic_type_consistency(actual_arg_types
,
280 /* perform the necessary typecasting of arguments */
281 make_fn_arguments(pstate
, fargs
, actual_arg_types
, declared_arg_types
);
284 * If it's a variadic function call, transform the last nvargs arguments
285 * into an array --- unless it's an "any" variadic.
287 if (nvargs
> 0 && declared_arg_types
[nargs
- 1] != ANYOID
)
289 ArrayExpr
*newa
= makeNode(ArrayExpr
);
290 int non_var_args
= nargs
- nvargs
;
293 Assert(non_var_args
>= 0);
294 vargs
= list_copy_tail(fargs
, non_var_args
);
295 fargs
= list_truncate(fargs
, non_var_args
);
297 newa
->elements
= vargs
;
298 /* assume all the variadic arguments were coerced to the same type */
299 newa
->element_typeid
= exprType((Node
*) linitial(vargs
));
300 newa
->array_typeid
= get_array_type(newa
->element_typeid
);
301 if (!OidIsValid(newa
->array_typeid
))
303 (errcode(ERRCODE_UNDEFINED_OBJECT
),
304 errmsg("could not find array type for data type %s",
305 format_type_be(newa
->element_typeid
)),
306 parser_errposition(pstate
, exprLocation((Node
*) vargs
))));
307 newa
->multidims
= false;
308 newa
->location
= exprLocation((Node
*) vargs
);
310 fargs
= lappend(fargs
, newa
);
313 /* build the appropriate output structure */
314 if (fdresult
== FUNCDETAIL_NORMAL
)
316 FuncExpr
*funcexpr
= makeNode(FuncExpr
);
318 funcexpr
->funcid
= funcid
;
319 funcexpr
->funcresulttype
= rettype
;
320 funcexpr
->funcretset
= retset
;
321 funcexpr
->funcformat
= COERCE_EXPLICIT_CALL
;
322 funcexpr
->args
= fargs
;
323 funcexpr
->location
= location
;
325 retval
= (Node
*) funcexpr
;
327 else if (fdresult
== FUNCDETAIL_AGGREGATE
&& !over
)
329 /* aggregate function */
330 Aggref
*aggref
= makeNode(Aggref
);
332 aggref
->aggfnoid
= funcid
;
333 aggref
->aggtype
= rettype
;
334 aggref
->args
= fargs
;
335 aggref
->aggstar
= agg_star
;
336 aggref
->aggdistinct
= agg_distinct
;
337 aggref
->location
= location
;
340 * Reject attempt to call a parameterless aggregate without (*)
341 * syntax. This is mere pedantry but some folks insisted ...
343 if (fargs
== NIL
&& !agg_star
)
345 (errcode(ERRCODE_WRONG_OBJECT_TYPE
),
346 errmsg("%s(*) must be used to call a parameterless aggregate function",
347 NameListToString(funcname
)),
348 parser_errposition(pstate
, location
)));
352 (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION
),
353 errmsg("aggregates cannot return sets"),
354 parser_errposition(pstate
, location
)));
356 /* parse_agg.c does additional aggregate-specific processing */
357 transformAggregateCall(pstate
, aggref
);
359 retval
= (Node
*) aggref
;
363 /* window function */
364 WindowFunc
*wfunc
= makeNode(WindowFunc
);
367 * True window functions must be called with a window definition.
371 (errcode(ERRCODE_WRONG_OBJECT_TYPE
),
372 errmsg("window function call requires an OVER clause"),
373 parser_errposition(pstate
, location
)));
375 wfunc
->winfnoid
= funcid
;
376 wfunc
->wintype
= rettype
;
378 /* winref will be set by transformWindowFuncCall */
379 wfunc
->winstar
= agg_star
;
380 wfunc
->winagg
= (fdresult
== FUNCDETAIL_AGGREGATE
);
381 wfunc
->location
= location
;
384 * agg_star is allowed for aggregate functions but distinct isn't
388 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED
),
389 errmsg("DISTINCT is not implemented for window functions"),
390 parser_errposition(pstate
, location
)));
393 * Reject attempt to call a parameterless aggregate without (*)
394 * syntax. This is mere pedantry but some folks insisted ...
396 if (wfunc
->winagg
&& fargs
== NIL
&& !agg_star
)
398 (errcode(ERRCODE_WRONG_OBJECT_TYPE
),
399 errmsg("%s(*) must be used to call a parameterless aggregate function",
400 NameListToString(funcname
)),
401 parser_errposition(pstate
, location
)));
405 (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION
),
406 errmsg("window functions cannot return sets"),
407 parser_errposition(pstate
, location
)));
409 /* parse_agg.c does additional window-func-specific processing */
410 transformWindowFuncCall(pstate
, wfunc
, over
);
412 retval
= (Node
*) wfunc
;
419 /* func_match_argtypes()
421 * Given a list of candidate functions (having the right name and number
422 * of arguments) and an array of input datatype OIDs, produce a shortlist of
423 * those candidates that actually accept the input datatypes (either exactly
424 * or by coercion), and return the number of such candidates.
426 * Note that can_coerce_type will assume that UNKNOWN inputs are coercible to
427 * anything, so candidates will not be eliminated on that basis.
429 * NB: okay to modify input list structure, as long as we find at least
430 * one match. If no match at all, the list must remain unmodified.
433 func_match_argtypes(int nargs
,
435 FuncCandidateList raw_candidates
,
436 FuncCandidateList
*candidates
) /* return value */
438 FuncCandidateList current_candidate
;
439 FuncCandidateList next_candidate
;
444 for (current_candidate
= raw_candidates
;
445 current_candidate
!= NULL
;
446 current_candidate
= next_candidate
)
448 next_candidate
= current_candidate
->next
;
449 if (can_coerce_type(nargs
, input_typeids
, current_candidate
->args
,
452 current_candidate
->next
= *candidates
;
453 *candidates
= current_candidate
;
459 } /* func_match_argtypes() */
462 /* func_select_candidate()
463 * Given the input argtype array and more than one candidate
464 * for the function, attempt to resolve the conflict.
466 * Returns the selected candidate if the conflict can be resolved,
467 * otherwise returns NULL.
469 * Note that the caller has already determined that there is no candidate
470 * exactly matching the input argtypes, and has pruned away any "candidates"
471 * that aren't actually coercion-compatible with the input types.
473 * This is also used for resolving ambiguous operator references. Formerly
474 * parse_oper.c had its own, essentially duplicate code for the purpose.
475 * The following comments (formerly in parse_oper.c) are kept to record some
476 * of the history of these heuristics.
480 * This routine is new code, replacing binary_oper_select_candidate()
481 * which dates from v4.2/v1.0.x days. It tries very hard to match up
482 * operators with types, including allowing type coercions if necessary.
483 * The important thing is that the code do as much as possible,
484 * while _never_ doing the wrong thing, where "the wrong thing" would
485 * be returning an operator when other better choices are available,
486 * or returning an operator which is a non-intuitive possibility.
487 * - thomas 1998-05-21
489 * The comments below came from binary_oper_select_candidate(), and
490 * illustrate the issues and choices which are possible:
491 * - thomas 1998-05-20
493 * current wisdom holds that the default operator should be one in which
494 * both operands have the same type (there will only be one such
497 * 7.27.93 - I have decided not to do this; it's too hard to justify, and
498 * it's easy enough to typecast explicitly - avi
499 * [the rest of this routine was commented out since then - ay]
501 * 6/23/95 - I don't complete agree with avi. In particular, casting
502 * floats is a pain for users. Whatever the rationale behind not doing
503 * this is, I need the following special case to work.
505 * In the WHERE clause of a query, if a float is specified without
506 * quotes, we treat it as float8. I added the float48* operators so
507 * that we can operate on float4 and float8. But now we have more than
508 * one matching operator if the right arg is unknown (eg. float
509 * specified with quotes). This break some stuff in the regression
510 * test where there are floats in quotes not properly casted. Below is
511 * the solution. In addition to requiring the operator operates on the
512 * same type for both operands [as in the code Avi originally
513 * commented out], we also require that the operators be equivalent in
514 * some sense. (see equivalentOpersAfterPromotion for details.)
518 func_select_candidate(int nargs
,
520 FuncCandidateList candidates
)
522 FuncCandidateList current_candidate
;
523 FuncCandidateList last_candidate
;
524 Oid
*current_typeids
;
530 Oid input_base_typeids
[FUNC_MAX_ARGS
];
531 TYPCATEGORY slot_category
[FUNC_MAX_ARGS
],
533 bool current_is_preferred
;
534 bool slot_has_preferred_type
[FUNC_MAX_ARGS
];
535 bool resolved_unknowns
;
537 /* protect local fixed-size arrays */
538 if (nargs
> FUNC_MAX_ARGS
)
540 (errcode(ERRCODE_TOO_MANY_ARGUMENTS
),
541 errmsg_plural("cannot pass more than %d argument to a function",
542 "cannot pass more than %d arguments to a function",
547 * If any input types are domains, reduce them to their base types. This
548 * ensures that we will consider functions on the base type to be "exact
549 * matches" in the exact-match heuristic; it also makes it possible to do
550 * something useful with the type-category heuristics. Note that this
551 * makes it difficult, but not impossible, to use functions declared to
552 * take a domain as an input datatype. Such a function will be selected
553 * over the base-type function only if it is an exact match at all
554 * argument positions, and so was already chosen by our caller.
556 for (i
= 0; i
< nargs
; i
++)
557 input_base_typeids
[i
] = getBaseType(input_typeids
[i
]);
560 * Run through all candidates and keep those with the most matches on
561 * exact types. Keep all candidates if none match.
565 last_candidate
= NULL
;
566 for (current_candidate
= candidates
;
567 current_candidate
!= NULL
;
568 current_candidate
= current_candidate
->next
)
570 current_typeids
= current_candidate
->args
;
572 for (i
= 0; i
< nargs
; i
++)
574 if (input_base_typeids
[i
] != UNKNOWNOID
&&
575 current_typeids
[i
] == input_base_typeids
[i
])
579 /* take this one as the best choice so far? */
580 if ((nmatch
> nbestMatch
) || (last_candidate
== NULL
))
583 candidates
= current_candidate
;
584 last_candidate
= current_candidate
;
587 /* no worse than the last choice, so keep this one too? */
588 else if (nmatch
== nbestMatch
)
590 last_candidate
->next
= current_candidate
;
591 last_candidate
= current_candidate
;
594 /* otherwise, don't bother keeping this one... */
597 if (last_candidate
) /* terminate rebuilt list */
598 last_candidate
->next
= NULL
;
600 if (ncandidates
== 1)
604 * Still too many candidates? Now look for candidates which have either
605 * exact matches or preferred types at the args that will require
606 * coercion. (Restriction added in 7.4: preferred type must be of same
607 * category as input type; give no preference to cross-category
608 * conversions to preferred types.) Keep all candidates if none match.
610 for (i
= 0; i
< nargs
; i
++) /* avoid multiple lookups */
611 slot_category
[i
] = TypeCategory(input_base_typeids
[i
]);
614 last_candidate
= NULL
;
615 for (current_candidate
= candidates
;
616 current_candidate
!= NULL
;
617 current_candidate
= current_candidate
->next
)
619 current_typeids
= current_candidate
->args
;
621 for (i
= 0; i
< nargs
; i
++)
623 if (input_base_typeids
[i
] != UNKNOWNOID
)
625 if (current_typeids
[i
] == input_base_typeids
[i
] ||
626 IsPreferredType(slot_category
[i
], current_typeids
[i
]))
631 if ((nmatch
> nbestMatch
) || (last_candidate
== NULL
))
634 candidates
= current_candidate
;
635 last_candidate
= current_candidate
;
638 else if (nmatch
== nbestMatch
)
640 last_candidate
->next
= current_candidate
;
641 last_candidate
= current_candidate
;
646 if (last_candidate
) /* terminate rebuilt list */
647 last_candidate
->next
= NULL
;
649 if (ncandidates
== 1)
653 * Still too many candidates? Try assigning types for the unknown columns.
655 * NOTE: for a binary operator with one unknown and one non-unknown input,
656 * we already tried the heuristic of looking for a candidate with the
657 * known input type on both sides (see binary_oper_exact()). That's
658 * essentially a special case of the general algorithm we try next.
660 * We do this by examining each unknown argument position to see if we can
661 * determine a "type category" for it. If any candidate has an input
662 * datatype of STRING category, use STRING category (this bias towards
663 * STRING is appropriate since unknown-type literals look like strings).
664 * Otherwise, if all the candidates agree on the type category of this
665 * argument position, use that category. Otherwise, fail because we
666 * cannot determine a category.
668 * If we are able to determine a type category, also notice whether any of
669 * the candidates takes a preferred datatype within the category.
671 * Having completed this examination, remove candidates that accept the
672 * wrong category at any unknown position. Also, if at least one
673 * candidate accepted a preferred type at a position, remove candidates
674 * that accept non-preferred types.
676 * If we are down to one candidate at the end, we win.
678 resolved_unknowns
= false;
679 for (i
= 0; i
< nargs
; i
++)
683 if (input_base_typeids
[i
] != UNKNOWNOID
)
685 resolved_unknowns
= true; /* assume we can do it */
686 slot_category
[i
] = TYPCATEGORY_INVALID
;
687 slot_has_preferred_type
[i
] = false;
688 have_conflict
= false;
689 for (current_candidate
= candidates
;
690 current_candidate
!= NULL
;
691 current_candidate
= current_candidate
->next
)
693 current_typeids
= current_candidate
->args
;
694 current_type
= current_typeids
[i
];
695 get_type_category_preferred(current_type
,
697 ¤t_is_preferred
);
698 if (slot_category
[i
] == TYPCATEGORY_INVALID
)
700 /* first candidate */
701 slot_category
[i
] = current_category
;
702 slot_has_preferred_type
[i
] = current_is_preferred
;
704 else if (current_category
== slot_category
[i
])
706 /* more candidates in same category */
707 slot_has_preferred_type
[i
] |= current_is_preferred
;
711 /* category conflict! */
712 if (current_category
== TYPCATEGORY_STRING
)
714 /* STRING always wins if available */
715 slot_category
[i
] = current_category
;
716 slot_has_preferred_type
[i
] = current_is_preferred
;
721 * Remember conflict, but keep going (might find STRING)
723 have_conflict
= true;
727 if (have_conflict
&& slot_category
[i
] != TYPCATEGORY_STRING
)
729 /* Failed to resolve category conflict at this position */
730 resolved_unknowns
= false;
735 if (resolved_unknowns
)
737 /* Strip non-matching candidates */
739 last_candidate
= NULL
;
740 for (current_candidate
= candidates
;
741 current_candidate
!= NULL
;
742 current_candidate
= current_candidate
->next
)
746 current_typeids
= current_candidate
->args
;
747 for (i
= 0; i
< nargs
; i
++)
749 if (input_base_typeids
[i
] != UNKNOWNOID
)
751 current_type
= current_typeids
[i
];
752 get_type_category_preferred(current_type
,
754 ¤t_is_preferred
);
755 if (current_category
!= slot_category
[i
])
760 if (slot_has_preferred_type
[i
] && !current_is_preferred
)
768 /* keep this candidate */
769 last_candidate
= current_candidate
;
774 /* forget this candidate */
776 last_candidate
->next
= current_candidate
->next
;
778 candidates
= current_candidate
->next
;
781 if (last_candidate
) /* terminate rebuilt list */
782 last_candidate
->next
= NULL
;
785 if (ncandidates
== 1)
788 return NULL
; /* failed to select a best candidate */
789 } /* func_select_candidate() */
794 * Find the named function in the system catalogs.
796 * Attempt to find the named function in the system catalogs with
797 * arguments exactly as specified, so that the normal case (exact match)
798 * is as quick as possible.
800 * If an exact match isn't found:
801 * 1) check for possible interpretation as a type coercion request
802 * 2) apply the ambiguous-function resolution rules
804 * Note: we rely primarily on nargs/argtypes as the argument description.
805 * The actual expression node list is passed in fargs so that we can check
806 * for type coercion of a constant. Some callers pass fargs == NIL
807 * indicating they don't want that check made.
810 func_get_detail(List
*funcname
,
814 bool expand_variadic
,
815 bool expand_defaults
,
816 Oid
*funcid
, /* return value */
817 Oid
*rettype
, /* return value */
818 bool *retset
, /* return value */
819 int *nvargs
, /* return value */
820 Oid
**true_typeids
, /* return value */
821 List
**argdefaults
) /* optional return value */
823 FuncCandidateList raw_candidates
;
824 FuncCandidateList best_candidate
;
826 /* initialize output arguments to silence compiler warnings */
827 *funcid
= InvalidOid
;
828 *rettype
= InvalidOid
;
831 *true_typeids
= NULL
;
835 /* Get list of possible candidates from namespace search */
836 raw_candidates
= FuncnameGetCandidates(funcname
, nargs
,
837 expand_variadic
, expand_defaults
);
840 * Quickly check if there is an exact match to the input datatypes (there
843 for (best_candidate
= raw_candidates
;
844 best_candidate
!= NULL
;
845 best_candidate
= best_candidate
->next
)
847 if (memcmp(argtypes
, best_candidate
->args
, nargs
* sizeof(Oid
)) == 0)
851 if (best_candidate
== NULL
)
854 * If we didn't find an exact match, next consider the possibility
855 * that this is really a type-coercion request: a single-argument
856 * function call where the function name is a type name. If so, and
857 * if the coercion path is RELABELTYPE or COERCEVIAIO, then go ahead
858 * and treat the "function call" as a coercion.
860 * This interpretation needs to be given higher priority than
861 * interpretations involving a type coercion followed by a function
862 * call, otherwise we can produce surprising results. For example, we
863 * want "text(varchar)" to be interpreted as a simple coercion, not as
864 * "text(name(varchar))" which the code below this point is entirely
865 * capable of selecting.
867 * We also treat a coercion of a previously-unknown-type literal
868 * constant to a specific type this way.
870 * The reason we reject COERCION_PATH_FUNC here is that we expect the
871 * cast implementation function to be named after the target type.
872 * Thus the function will be found by normal lookup if appropriate.
874 * The reason we reject COERCION_PATH_ARRAYCOERCE is mainly that you
875 * can't write "foo[] (something)" as a function call. In theory
876 * someone might want to invoke it as "_foo (something)" but we have
877 * never supported that historically, so we can insist that people
878 * write it as a normal cast instead. Lack of historical support is
879 * also the reason for not considering composite-type casts here.
881 * NB: it's important that this code does not exceed what coerce_type
882 * can do, because the caller will try to apply coerce_type if we
883 * return FUNCDETAIL_COERCION. If we return that result for something
884 * coerce_type can't handle, we'll cause infinite recursion between
885 * this module and coerce_type!
887 if (nargs
== 1 && fargs
!= NIL
)
889 Oid targetType
= FuncNameAsType(funcname
);
891 if (OidIsValid(targetType
))
893 Oid sourceType
= argtypes
[0];
894 Node
*arg1
= linitial(fargs
);
897 if (sourceType
== UNKNOWNOID
&& IsA(arg1
, Const
))
899 /* always treat typename('literal') as coercion */
904 CoercionPathType cpathtype
;
907 cpathtype
= find_coercion_pathway(targetType
, sourceType
,
910 iscoercion
= (cpathtype
== COERCION_PATH_RELABELTYPE
||
911 cpathtype
== COERCION_PATH_COERCEVIAIO
);
916 /* Treat it as a type coercion */
917 *funcid
= InvalidOid
;
918 *rettype
= targetType
;
921 *true_typeids
= argtypes
;
922 return FUNCDETAIL_COERCION
;
928 * didn't find an exact match, so now try to match up candidates...
930 if (raw_candidates
!= NULL
)
932 FuncCandidateList current_candidates
;
935 ncandidates
= func_match_argtypes(nargs
,
938 ¤t_candidates
);
940 /* one match only? then run with it... */
941 if (ncandidates
== 1)
942 best_candidate
= current_candidates
;
945 * multiple candidates? then better decide or throw an error...
947 else if (ncandidates
> 1)
949 best_candidate
= func_select_candidate(nargs
,
954 * If we were able to choose a best candidate, we're done.
955 * Otherwise, ambiguous function call.
958 return FUNCDETAIL_MULTIPLE
;
967 FuncDetailCode result
;
970 * If expanding variadics or defaults, the "best candidate" might
971 * represent multiple equivalently good functions; treat this case as
974 if (!OidIsValid(best_candidate
->oid
))
975 return FUNCDETAIL_MULTIPLE
;
977 *funcid
= best_candidate
->oid
;
978 *nvargs
= best_candidate
->nvargs
;
979 *true_typeids
= best_candidate
->args
;
981 ftup
= SearchSysCache(PROCOID
,
982 ObjectIdGetDatum(best_candidate
->oid
),
984 if (!HeapTupleIsValid(ftup
)) /* should not happen */
985 elog(ERROR
, "cache lookup failed for function %u",
986 best_candidate
->oid
);
987 pform
= (Form_pg_proc
) GETSTRUCT(ftup
);
988 *rettype
= pform
->prorettype
;
989 *retset
= pform
->proretset
;
990 /* fetch default args if caller wants 'em */
993 if (best_candidate
->ndargs
> 0)
995 Datum proargdefaults
;
1001 /* shouldn't happen, FuncnameGetCandidates messed up */
1002 if (best_candidate
->ndargs
> pform
->pronargdefaults
)
1003 elog(ERROR
, "not enough default arguments");
1005 proargdefaults
= SysCacheGetAttr(PROCOID
, ftup
,
1006 Anum_pg_proc_proargdefaults
,
1009 str
= TextDatumGetCString(proargdefaults
);
1010 defaults
= (List
*) stringToNode(str
);
1011 Assert(IsA(defaults
, List
));
1013 /* Delete any unused defaults from the returned list */
1014 ndelete
= list_length(defaults
) - best_candidate
->ndargs
;
1015 while (ndelete
-- > 0)
1016 defaults
= list_delete_first(defaults
);
1017 *argdefaults
= defaults
;
1022 if (pform
->proisagg
)
1023 result
= FUNCDETAIL_AGGREGATE
;
1024 else if (pform
->proiswindow
)
1025 result
= FUNCDETAIL_WINDOWFUNC
;
1027 result
= FUNCDETAIL_NORMAL
;
1028 ReleaseSysCache(ftup
);
1032 return FUNCDETAIL_NOTFOUND
;
1037 * make_fn_arguments()
1039 * Given the actual argument expressions for a function, and the desired
1040 * input types for the function, add any necessary typecasting to the
1041 * expression tree. Caller should already have verified that casting is
1044 * Caution: given argument list is modified in-place.
1046 * As with coerce_type, pstate may be NULL if no special unknown-Param
1047 * processing is wanted.
1050 make_fn_arguments(ParseState
*pstate
,
1052 Oid
*actual_arg_types
,
1053 Oid
*declared_arg_types
)
1055 ListCell
*current_fargs
;
1058 foreach(current_fargs
, fargs
)
1060 /* types don't match? then force coercion using a function call... */
1061 if (actual_arg_types
[i
] != declared_arg_types
[i
])
1063 lfirst(current_fargs
) = coerce_type(pstate
,
1064 lfirst(current_fargs
),
1065 actual_arg_types
[i
],
1066 declared_arg_types
[i
], -1,
1068 COERCE_IMPLICIT_CAST
,
1077 * convenience routine to see if a function name matches a type name
1079 * Returns the OID of the matching type, or InvalidOid if none. We ignore
1080 * shell types and complex types.
1083 FuncNameAsType(List
*funcname
)
1088 typtup
= LookupTypeName(NULL
, makeTypeNameFromNameList(funcname
), NULL
);
1092 if (((Form_pg_type
) GETSTRUCT(typtup
))->typisdefined
&&
1093 !OidIsValid(typeTypeRelid(typtup
)))
1094 result
= typeTypeId(typtup
);
1096 result
= InvalidOid
;
1098 ReleaseSysCache(typtup
);
1103 * ParseComplexProjection -
1104 * handles function calls with a single argument that is of complex type.
1105 * If the function call is actually a column projection, return a suitably
1106 * transformed expression tree. If not, return NULL.
1109 ParseComplexProjection(ParseState
*pstate
, char *funcname
, Node
*first_arg
,
1116 * Special case for whole-row Vars so that we can resolve (foo.*).bar even
1117 * when foo is a reference to a subselect, join, or RECORD function. A
1118 * bonus is that we avoid generating an unnecessary FieldSelect; our
1119 * result can omit the whole-row Var and just be a Var for the selected
1122 * This case could be handled by expandRecordVariable, but it's more
1123 * efficient to do it this way when possible.
1125 if (IsA(first_arg
, Var
) &&
1126 ((Var
*) first_arg
)->varattno
== InvalidAttrNumber
)
1130 rte
= GetRTEByRangeTablePosn(pstate
,
1131 ((Var
*) first_arg
)->varno
,
1132 ((Var
*) first_arg
)->varlevelsup
);
1133 /* Return a Var if funcname matches a column, else NULL */
1134 return scanRTEForColumn(pstate
, rte
, funcname
, location
);
1138 * Else do it the hard way with get_expr_result_type().
1140 * If it's a Var of type RECORD, we have to work even harder: we have to
1141 * find what the Var refers to, and pass that to get_expr_result_type.
1142 * That task is handled by expandRecordVariable().
1144 if (IsA(first_arg
, Var
) &&
1145 ((Var
*) first_arg
)->vartype
== RECORDOID
)
1146 tupdesc
= expandRecordVariable(pstate
, (Var
*) first_arg
, 0);
1147 else if (get_expr_result_type(first_arg
, NULL
, &tupdesc
) != TYPEFUNC_COMPOSITE
)
1148 return NULL
; /* unresolvable RECORD type */
1151 for (i
= 0; i
< tupdesc
->natts
; i
++)
1153 Form_pg_attribute att
= tupdesc
->attrs
[i
];
1155 if (strcmp(funcname
, NameStr(att
->attname
)) == 0 &&
1158 /* Success, so generate a FieldSelect expression */
1159 FieldSelect
*fselect
= makeNode(FieldSelect
);
1161 fselect
->arg
= (Expr
*) first_arg
;
1162 fselect
->fieldnum
= i
+ 1;
1163 fselect
->resulttype
= att
->atttypid
;
1164 fselect
->resulttypmod
= att
->atttypmod
;
1165 return (Node
*) fselect
;
1169 return NULL
; /* funcname does not match any column */
1173 * helper routine for delivering "column does not exist" error message
1176 unknown_attribute(ParseState
*pstate
, Node
*relref
, char *attname
,
1181 if (IsA(relref
, Var
) &&
1182 ((Var
*) relref
)->varattno
== InvalidAttrNumber
)
1184 /* Reference the RTE by alias not by actual table name */
1185 rte
= GetRTEByRangeTablePosn(pstate
,
1186 ((Var
*) relref
)->varno
,
1187 ((Var
*) relref
)->varlevelsup
);
1189 (errcode(ERRCODE_UNDEFINED_COLUMN
),
1190 errmsg("column %s.%s does not exist",
1191 rte
->eref
->aliasname
, attname
),
1192 parser_errposition(pstate
, location
)));
1196 /* Have to do it by reference to the type of the expression */
1197 Oid relTypeId
= exprType(relref
);
1199 if (ISCOMPLEX(relTypeId
))
1201 (errcode(ERRCODE_UNDEFINED_COLUMN
),
1202 errmsg("column \"%s\" not found in data type %s",
1203 attname
, format_type_be(relTypeId
)),
1204 parser_errposition(pstate
, location
)));
1205 else if (relTypeId
== RECORDOID
)
1207 (errcode(ERRCODE_UNDEFINED_COLUMN
),
1208 errmsg("could not identify column \"%s\" in record data type",
1210 parser_errposition(pstate
, location
)));
1213 (errcode(ERRCODE_WRONG_OBJECT_TYPE
),
1214 errmsg("column notation .%s applied to type %s, "
1215 "which is not a composite type",
1216 attname
, format_type_be(relTypeId
)),
1217 parser_errposition(pstate
, location
)));
1222 * funcname_signature_string
1223 * Build a string representing a function name, including arg types.
1224 * The result is something like "foo(integer)".
1226 * This is typically used in the construction of function-not-found error
1230 funcname_signature_string(const char *funcname
,
1231 int nargs
, const Oid
*argtypes
)
1233 StringInfoData argbuf
;
1236 initStringInfo(&argbuf
);
1238 appendStringInfo(&argbuf
, "%s(", funcname
);
1240 for (i
= 0; i
< nargs
; i
++)
1243 appendStringInfoString(&argbuf
, ", ");
1244 appendStringInfoString(&argbuf
, format_type_be(argtypes
[i
]));
1247 appendStringInfoChar(&argbuf
, ')');
1249 return argbuf
.data
; /* return palloc'd string buffer */
1253 * func_signature_string
1254 * As above, but function name is passed as a qualified name list.
1257 func_signature_string(List
*funcname
, int nargs
, const Oid
*argtypes
)
1259 return funcname_signature_string(NameListToString(funcname
),
1265 * Given a possibly-qualified function name and a set of argument types,
1266 * look up the function.
1268 * If the function name is not schema-qualified, it is sought in the current
1269 * namespace search path.
1271 * If the function is not found, we return InvalidOid if noError is true,
1272 * else raise an error.
1275 LookupFuncName(List
*funcname
, int nargs
, const Oid
*argtypes
, bool noError
)
1277 FuncCandidateList clist
;
1279 clist
= FuncnameGetCandidates(funcname
, nargs
, false, false);
1283 if (memcmp(argtypes
, clist
->args
, nargs
* sizeof(Oid
)) == 0)
1285 clist
= clist
->next
;
1290 (errcode(ERRCODE_UNDEFINED_FUNCTION
),
1291 errmsg("function %s does not exist",
1292 func_signature_string(funcname
, nargs
, argtypes
))));
1299 * Convenience routine to look up a type, silently accepting shell types
1302 LookupTypeNameOid(const TypeName
*typename
)
1307 typtup
= LookupTypeName(NULL
, typename
, NULL
);
1310 (errcode(ERRCODE_UNDEFINED_OBJECT
),
1311 errmsg("type \"%s\" does not exist",
1312 TypeNameToString(typename
))));
1313 result
= typeTypeId(typtup
);
1314 ReleaseSysCache(typtup
);
1319 * LookupFuncNameTypeNames
1320 * Like LookupFuncName, but the argument types are specified by a
1321 * list of TypeName nodes.
1324 LookupFuncNameTypeNames(List
*funcname
, List
*argtypes
, bool noError
)
1326 Oid argoids
[FUNC_MAX_ARGS
];
1329 ListCell
*args_item
;
1331 argcount
= list_length(argtypes
);
1332 if (argcount
> FUNC_MAX_ARGS
)
1334 (errcode(ERRCODE_TOO_MANY_ARGUMENTS
),
1335 errmsg_plural("functions cannot have more than %d argument",
1336 "functions cannot have more than %d arguments",
1340 args_item
= list_head(argtypes
);
1341 for (i
= 0; i
< argcount
; i
++)
1343 TypeName
*t
= (TypeName
*) lfirst(args_item
);
1345 argoids
[i
] = LookupTypeNameOid(t
);
1346 args_item
= lnext(args_item
);
1349 return LookupFuncName(funcname
, argcount
, argoids
, noError
);
1353 * LookupAggNameTypeNames
1354 * Find an aggregate function given a name and list of TypeName nodes.
1356 * This is almost like LookupFuncNameTypeNames, but the error messages refer
1357 * to aggregates rather than plain functions, and we verify that the found
1358 * function really is an aggregate.
1361 LookupAggNameTypeNames(List
*aggname
, List
*argtypes
, bool noError
)
1363 Oid argoids
[FUNC_MAX_ARGS
];
1371 argcount
= list_length(argtypes
);
1372 if (argcount
> FUNC_MAX_ARGS
)
1374 (errcode(ERRCODE_TOO_MANY_ARGUMENTS
),
1375 errmsg_plural("functions cannot have more than %d argument",
1376 "functions cannot have more than %d arguments",
1381 foreach(lc
, argtypes
)
1383 TypeName
*t
= (TypeName
*) lfirst(lc
);
1385 argoids
[i
] = LookupTypeNameOid(t
);
1389 oid
= LookupFuncName(aggname
, argcount
, argoids
, true);
1391 if (!OidIsValid(oid
))
1397 (errcode(ERRCODE_UNDEFINED_FUNCTION
),
1398 errmsg("aggregate %s(*) does not exist",
1399 NameListToString(aggname
))));
1402 (errcode(ERRCODE_UNDEFINED_FUNCTION
),
1403 errmsg("aggregate %s does not exist",
1404 func_signature_string(aggname
,
1405 argcount
, argoids
))));
1408 /* Make sure it's an aggregate */
1409 ftup
= SearchSysCache(PROCOID
,
1410 ObjectIdGetDatum(oid
),
1412 if (!HeapTupleIsValid(ftup
)) /* should not happen */
1413 elog(ERROR
, "cache lookup failed for function %u", oid
);
1414 pform
= (Form_pg_proc
) GETSTRUCT(ftup
);
1416 if (!pform
->proisagg
)
1418 ReleaseSysCache(ftup
);
1421 /* we do not use the (*) notation for functions... */
1423 (errcode(ERRCODE_WRONG_OBJECT_TYPE
),
1424 errmsg("function %s is not an aggregate",
1425 func_signature_string(aggname
,
1426 argcount
, argoids
))));
1429 ReleaseSysCache(ftup
);