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