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 255414 : ParseFuncOrColumn(ParseState *pstate, List *funcname, List *fargs,
93 : Node *last_srf, FuncCall *fn, bool proc_call, int location)
94 : {
95 255414 : bool is_column = (fn == NULL);
96 255414 : List *agg_order = (fn ? fn->agg_order : NIL);
97 255414 : Expr *agg_filter = NULL;
98 255414 : WindowDef *over = (fn ? fn->over : NULL);
99 255414 : bool agg_within_group = (fn ? fn->agg_within_group : false);
100 255414 : bool agg_star = (fn ? fn->agg_star : false);
101 255414 : bool agg_distinct = (fn ? fn->agg_distinct : false);
102 255414 : bool func_variadic = (fn ? fn->func_variadic : false);
103 255414 : int ignore_nulls = (fn ? fn->ignore_nulls : NO_NULLTREATMENT);
104 255414 : CoercionForm funcformat = (fn ? fn->funcformat : COERCE_EXPLICIT_CALL);
105 : bool could_be_projection;
106 : Oid rettype;
107 : Oid funcid;
108 : ListCell *l;
109 255414 : 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 255414 : char aggkind = 0;
123 : ParseCallbackState pcbstate;
124 :
125 : /*
126 : * If there's an aggregate filter, transform it using transformWhereClause
127 : */
128 255414 : 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 255406 : 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 255406 : nargs = 0;
159 665243 : foreach(l, fargs)
160 : {
161 409837 : Node *arg = lfirst(l);
162 409837 : Oid argtype = exprType(arg);
163 :
164 409837 : 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 409837 : 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 255406 : argnames = NIL;
183 665231 : foreach(l, fargs)
184 : {
185 409837 : Node *arg = lfirst(l);
186 :
187 409837 : if (IsA(arg, NamedArgExpr))
188 : {
189 25484 : NamedArgExpr *na = (NamedArgExpr *) arg;
190 : ListCell *lc;
191 :
192 : /* Reject duplicate arg names */
193 54816 : foreach(lc, argnames)
194 : {
195 29336 : 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 25480 : argnames = lappend(argnames, na->name);
203 : }
204 : else
205 : {
206 384353 : 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 255394 : if (fargs)
215 : {
216 223894 : 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 102134 : could_be_projection = (nargs == 1 && !proc_call &&
228 100792 : agg_order == NIL && agg_filter == NULL &&
229 100680 : !agg_star && !agg_distinct && over == NULL &&
230 196721 : !func_variadic && argnames == NIL &&
231 455660 : list_length(funcname) == 1 &&
232 128054 : (actual_arg_types[0] == RECORDOID ||
233 62950 : ISCOMPLEX(actual_arg_types[0])));
234 :
235 : /*
236 : * If it's column syntax, check for column projection case first.
237 : */
238 255394 : if (could_be_projection && is_column)
239 : {
240 8700 : retval = ParseComplexProjection(pstate,
241 8700 : strVal(linitial(funcname)),
242 : first_arg,
243 : location);
244 8700 : if (retval)
245 8555 : 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 246839 : setup_parser_errposition_callback(&pcbstate, pstate, location);
269 :
270 246839 : 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 246839 : &declared_arg_types, &argdefaults);
277 :
278 246839 : 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 246839 : 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 246827 : 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 246823 : if (fdresult == FUNCDETAIL_NORMAL ||
310 33976 : 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 213249 : 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 213249 : 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 213249 : 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 213249 : 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 213249 : 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 213249 : 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 246819 : if (fdresult == FUNCDETAIL_NORMAL || fdresult == FUNCDETAIL_PROCEDURE)
360 : {
361 : /* Nothing special to do for these cases. */
362 : }
363 33976 : 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 31665 : tup = SearchSysCache1(AGGFNOID, ObjectIdGetDatum(funcid));
373 31665 : if (!HeapTupleIsValid(tup)) /* should not happen */
374 0 : elog(ERROR, "cache lookup failed for aggregate %u", funcid);
375 31665 : classForm = (Form_pg_aggregate) GETSTRUCT(tup);
376 31665 : aggkind = classForm->aggkind;
377 31665 : catDirectArgs = classForm->aggnumdirectargs;
378 31665 : ReleaseSysCache(tup);
379 :
380 : /* Now check various disallowed cases. */
381 31665 : 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 31441 : 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 31437 : 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 245973 : nargsplusdefs = nargs;
661 262298 : foreach(l, argdefaults)
662 : {
663 16325 : Node *expr = (Node *) lfirst(l);
664 :
665 : /* probably shouldn't happen ... */
666 16325 : 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 16325 : 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 245973 : 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 245929 : 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 245882 : if (!OidIsValid(vatype))
698 : {
699 : Assert(nvargs == 0);
700 240259 : 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 245882 : if (nvargs > 0 && vatype != ANYOID)
708 : {
709 952 : ArrayExpr *newa = makeNode(ArrayExpr);
710 952 : int non_var_args = nargs - nvargs;
711 : List *vargs;
712 :
713 : Assert(non_var_args >= 0);
714 952 : vargs = list_copy_tail(fargs, non_var_args);
715 952 : fargs = list_truncate(fargs, non_var_args);
716 :
717 952 : newa->elements = vargs;
718 : /* assume all the variadic arguments were coerced to the same type */
719 952 : newa->element_typeid = exprType((Node *) linitial(vargs));
720 952 : newa->array_typeid = get_array_type(newa->element_typeid);
721 952 : 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 952 : newa->multidims = false;
729 952 : newa->location = exprLocation((Node *) vargs);
730 :
731 952 : 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 952 : 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 245882 : 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 245878 : if (retset)
757 34716 : check_srf_call_placement(pstate, last_srf, location);
758 :
759 : /* build the appropriate output structure */
760 245830 : if (fdresult == FUNCDETAIL_NORMAL || fdresult == FUNCDETAIL_PROCEDURE)
761 212700 : {
762 212700 : FuncExpr *funcexpr = makeNode(FuncExpr);
763 :
764 212700 : funcexpr->funcid = funcid;
765 212700 : funcexpr->funcresulttype = rettype;
766 212700 : funcexpr->funcretset = retset;
767 212700 : funcexpr->funcvariadic = func_variadic;
768 212700 : funcexpr->funcformat = funcformat;
769 : /* funccollid and inputcollid will be set by parse_collate.c */
770 212700 : funcexpr->args = fargs;
771 212700 : funcexpr->location = location;
772 :
773 212700 : retval = (Node *) funcexpr;
774 : }
775 33130 : else if (fdresult == FUNCDETAIL_AGGREGATE && !over)
776 30364 : {
777 : /* aggregate function */
778 30488 : Aggref *aggref = makeNode(Aggref);
779 :
780 30488 : aggref->aggfnoid = funcid;
781 30488 : aggref->aggtype = rettype;
782 : /* aggcollid and inputcollid will be set by parse_collate.c */
783 30488 : 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 30488 : aggref->aggfilter = agg_filter;
788 30488 : aggref->aggstar = agg_star;
789 30488 : aggref->aggvariadic = func_variadic;
790 30488 : aggref->aggkind = aggkind;
791 30488 : aggref->aggpresorted = false;
792 : /* agglevelsup will be set by transformAggregateCall */
793 30488 : aggref->aggsplit = AGGSPLIT_SIMPLE; /* planner might change this */
794 30488 : aggref->aggno = -1; /* planner will set aggno and aggtransno */
795 30488 : aggref->aggtransno = -1;
796 30488 : 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 30488 : 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 30488 : 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 30488 : 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 30488 : transformAggregateCall(pstate, aggref, fargs, agg_order, agg_distinct);
832 :
833 30364 : 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 245662 : if (retset)
918 34668 : pstate->p_last_srf = retval;
919 :
920 245662 : 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 132628 : 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 132628 : int ncandidates = 0;
1045 :
1046 132628 : *candidates = NULL;
1047 :
1048 132628 : for (current_candidate = raw_candidates;
1049 867900 : current_candidate != NULL;
1050 735272 : current_candidate = next_candidate)
1051 : {
1052 735272 : next_candidate = current_candidate->next;
1053 735272 : if (can_coerce_type(nargs, input_typeids, current_candidate->args,
1054 : COERCION_IMPLICIT))
1055 : {
1056 153239 : current_candidate->next = *candidates;
1057 153239 : *candidates = current_candidate;
1058 153239 : ncandidates++;
1059 : }
1060 : }
1061 :
1062 132628 : 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 8376 : 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 8376 : 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 8376 : nunknowns = 0;
1167 26245 : for (i = 0; i < nargs; i++)
1168 : {
1169 17869 : if (input_typeids[i] != UNKNOWNOID)
1170 8964 : input_base_typeids[i] = getBaseType(input_typeids[i]);
1171 : else
1172 : {
1173 : /* no need to call getBaseType on UNKNOWNOID */
1174 8905 : input_base_typeids[i] = UNKNOWNOID;
1175 8905 : 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 8376 : ncandidates = 0;
1184 8376 : nbestMatch = 0;
1185 8376 : last_candidate = NULL;
1186 8376 : for (current_candidate = candidates;
1187 37784 : current_candidate != NULL;
1188 29408 : current_candidate = current_candidate->next)
1189 : {
1190 29408 : current_typeids = current_candidate->args;
1191 29408 : nmatch = 0;
1192 91104 : for (i = 0; i < nargs; i++)
1193 : {
1194 61696 : if (input_base_typeids[i] != UNKNOWNOID &&
1195 27851 : current_typeids[i] == input_base_typeids[i])
1196 9336 : nmatch++;
1197 : }
1198 :
1199 : /* take this one as the best choice so far? */
1200 29408 : if ((nmatch > nbestMatch) || (last_candidate == NULL))
1201 : {
1202 10095 : nbestMatch = nmatch;
1203 10095 : candidates = current_candidate;
1204 10095 : last_candidate = current_candidate;
1205 10095 : ncandidates = 1;
1206 : }
1207 : /* no worse than the last choice, so keep this one too? */
1208 19313 : else if (nmatch == nbestMatch)
1209 : {
1210 13698 : last_candidate->next = current_candidate;
1211 13698 : last_candidate = current_candidate;
1212 13698 : ncandidates++;
1213 : }
1214 : /* otherwise, don't bother keeping this one... */
1215 : }
1216 :
1217 8376 : if (last_candidate) /* terminate rebuilt list */
1218 8376 : last_candidate->next = NULL;
1219 :
1220 8376 : if (ncandidates == 1)
1221 3667 : 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 15078 : for (i = 0; i < nargs; i++) /* avoid multiple lookups */
1231 10369 : slot_category[i] = TypeCategory(input_base_typeids[i]);
1232 4709 : ncandidates = 0;
1233 4709 : nbestMatch = 0;
1234 4709 : last_candidate = NULL;
1235 4709 : for (current_candidate = candidates;
1236 21541 : current_candidate != NULL;
1237 16832 : current_candidate = current_candidate->next)
1238 : {
1239 16832 : current_typeids = current_candidate->args;
1240 16832 : nmatch = 0;
1241 53075 : for (i = 0; i < nargs; i++)
1242 : {
1243 36243 : if (input_base_typeids[i] != UNKNOWNOID)
1244 : {
1245 15714 : if (current_typeids[i] == input_base_typeids[i] ||
1246 5520 : IsPreferredType(slot_category[i], current_typeids[i]))
1247 6986 : nmatch++;
1248 : }
1249 : }
1250 :
1251 16832 : if ((nmatch > nbestMatch) || (last_candidate == NULL))
1252 : {
1253 5853 : nbestMatch = nmatch;
1254 5853 : candidates = current_candidate;
1255 5853 : last_candidate = current_candidate;
1256 5853 : ncandidates = 1;
1257 : }
1258 10979 : else if (nmatch == nbestMatch)
1259 : {
1260 10105 : last_candidate->next = current_candidate;
1261 10105 : last_candidate = current_candidate;
1262 10105 : ncandidates++;
1263 : }
1264 : }
1265 :
1266 4709 : if (last_candidate) /* terminate rebuilt list */
1267 4709 : last_candidate->next = NULL;
1268 :
1269 4709 : if (ncandidates == 1)
1270 1042 : 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 3667 : 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 3663 : resolved_unknowns = false;
1301 11987 : for (i = 0; i < nargs; i++)
1302 : {
1303 : bool have_conflict;
1304 :
1305 8324 : if (input_base_typeids[i] != UNKNOWNOID)
1306 2161 : continue;
1307 6163 : resolved_unknowns = true; /* assume we can do it */
1308 6163 : slot_category[i] = TYPCATEGORY_INVALID;
1309 6163 : slot_has_preferred_type[i] = false;
1310 6163 : have_conflict = false;
1311 6163 : for (current_candidate = candidates;
1312 31087 : current_candidate != NULL;
1313 24924 : current_candidate = current_candidate->next)
1314 : {
1315 24924 : current_typeids = current_candidate->args;
1316 24924 : current_type = current_typeids[i];
1317 24924 : get_type_category_preferred(current_type,
1318 : ¤t_category,
1319 : ¤t_is_preferred);
1320 24924 : if (slot_category[i] == TYPCATEGORY_INVALID)
1321 : {
1322 : /* first candidate */
1323 6163 : slot_category[i] = current_category;
1324 6163 : slot_has_preferred_type[i] = current_is_preferred;
1325 : }
1326 18761 : else if (current_category == slot_category[i])
1327 : {
1328 : /* more candidates in same category */
1329 4951 : slot_has_preferred_type[i] |= current_is_preferred;
1330 : }
1331 : else
1332 : {
1333 : /* category conflict! */
1334 13810 : if (current_category == TYPCATEGORY_STRING)
1335 : {
1336 : /* STRING always wins if available */
1337 1706 : slot_category[i] = current_category;
1338 1706 : slot_has_preferred_type[i] = current_is_preferred;
1339 : }
1340 : else
1341 : {
1342 : /*
1343 : * Remember conflict, but keep going (might find STRING)
1344 : */
1345 12104 : have_conflict = true;
1346 : }
1347 : }
1348 : }
1349 6163 : 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 3663 : if (resolved_unknowns)
1358 : {
1359 : /* Strip non-matching candidates */
1360 3663 : ncandidates = 0;
1361 3663 : first_candidate = candidates;
1362 3663 : last_candidate = NULL;
1363 3663 : for (current_candidate = candidates;
1364 17096 : current_candidate != NULL;
1365 13433 : current_candidate = current_candidate->next)
1366 : {
1367 13433 : bool keepit = true;
1368 :
1369 13433 : current_typeids = current_candidate->args;
1370 24563 : for (i = 0; i < nargs; i++)
1371 : {
1372 20825 : if (input_base_typeids[i] != UNKNOWNOID)
1373 3168 : continue;
1374 17657 : current_type = current_typeids[i];
1375 17657 : get_type_category_preferred(current_type,
1376 : ¤t_category,
1377 : ¤t_is_preferred);
1378 17657 : if (current_category != slot_category[i])
1379 : {
1380 8961 : keepit = false;
1381 8961 : break;
1382 : }
1383 8696 : if (slot_has_preferred_type[i] && !current_is_preferred)
1384 : {
1385 734 : keepit = false;
1386 734 : break;
1387 : }
1388 : }
1389 13433 : if (keepit)
1390 : {
1391 : /* keep this candidate */
1392 3738 : last_candidate = current_candidate;
1393 3738 : ncandidates++;
1394 : }
1395 : else
1396 : {
1397 : /* forget this candidate */
1398 9695 : if (last_candidate)
1399 7083 : last_candidate->next = current_candidate->next;
1400 : else
1401 2612 : first_candidate = current_candidate->next;
1402 : }
1403 : }
1404 :
1405 : /* if we found any matches, restrict our attention to those */
1406 3663 : if (last_candidate)
1407 : {
1408 3663 : candidates = first_candidate;
1409 : /* terminate rebuilt list */
1410 3663 : last_candidate->next = NULL;
1411 : }
1412 :
1413 3663 : if (ncandidates == 1)
1414 3628 : 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 257284 : 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 257284 : *funcid = InvalidOid;
1538 257284 : *rettype = InvalidOid;
1539 257284 : *retset = false;
1540 257284 : *nvargs = 0;
1541 257284 : *vatype = InvalidOid;
1542 257284 : *true_typeids = NULL;
1543 257284 : if (argdefaults)
1544 246839 : *argdefaults = NIL;
1545 :
1546 : /* Get list of possible candidates from namespace search */
1547 257284 : 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 257284 : for (best_candidate = raw_candidates;
1557 523475 : best_candidate != NULL;
1558 266191 : best_candidate = best_candidate->next)
1559 : {
1560 : /* if nargs==0, argtypes can be null; don't pass that to memcmp */
1561 401981 : if (nargs == 0 ||
1562 368688 : memcmp(argtypes, best_candidate->args, nargs * sizeof(Oid)) == 0)
1563 : break;
1564 : }
1565 :
1566 257284 : 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 121494 : if (nargs == 1 && fargs != NIL && fargnames == NIL)
1608 : {
1609 45211 : Oid targetType = FuncNameAsType(funcname);
1610 :
1611 45211 : 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 121092 : if (raw_candidates != NULL)
1667 : {
1668 : FuncCandidateList current_candidates;
1669 : int ncandidates;
1670 :
1671 120366 : ncandidates = func_match_argtypes(nargs,
1672 : argtypes,
1673 : raw_candidates,
1674 : ¤t_candidates);
1675 :
1676 : /* one match only? then run with it... */
1677 120366 : if (ncandidates == 1)
1678 115603 : best_candidate = current_candidates;
1679 :
1680 : /*
1681 : * multiple candidates? then better decide or throw an error...
1682 : */
1683 4763 : else if (ncandidates > 1)
1684 : {
1685 4421 : 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 4421 : if (!best_candidate)
1694 0 : return FUNCDETAIL_MULTIPLE;
1695 : }
1696 : }
1697 : }
1698 :
1699 256882 : 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 255814 : 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 255794 : 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 255790 : *funcid = best_candidate->oid;
1726 255790 : *nvargs = best_candidate->nvargs;
1727 255790 : *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 255790 : if (best_candidate->argnumbers != NULL)
1735 : {
1736 8855 : int i = 0;
1737 : ListCell *lc;
1738 :
1739 35878 : foreach(lc, fargs)
1740 : {
1741 27023 : NamedArgExpr *na = (NamedArgExpr *) lfirst(lc);
1742 :
1743 27023 : if (IsA(na, NamedArgExpr))
1744 25392 : na->argnumber = best_candidate->argnumbers[i];
1745 27023 : i++;
1746 : }
1747 : }
1748 :
1749 255790 : ftup = SearchSysCache1(PROCOID,
1750 : ObjectIdGetDatum(best_candidate->oid));
1751 255790 : if (!HeapTupleIsValid(ftup)) /* should not happen */
1752 0 : elog(ERROR, "cache lookup failed for function %u",
1753 : best_candidate->oid);
1754 255790 : pform = (Form_pg_proc) GETSTRUCT(ftup);
1755 255790 : *rettype = pform->prorettype;
1756 255790 : *retset = pform->proretset;
1757 255790 : *vatype = pform->provariadic;
1758 : /* fetch default args if caller wants 'em */
1759 255790 : 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 8573 : if (best_candidate->ndargs > pform->pronargdefaults)
1767 0 : elog(ERROR, "not enough default arguments");
1768 :
1769 8573 : proargdefaults = SysCacheGetAttrNotNull(PROCOID, ftup,
1770 : Anum_pg_proc_proargdefaults);
1771 8573 : str = TextDatumGetCString(proargdefaults);
1772 8573 : defaults = castNode(List, stringToNode(str));
1773 8573 : pfree(str);
1774 :
1775 : /* Delete any unused defaults from the returned list */
1776 8573 : 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 4428 : ndelete = list_length(defaults) - best_candidate->ndargs;
1818 4428 : if (ndelete > 0)
1819 140 : defaults = list_delete_first_n(defaults, ndelete);
1820 4428 : *argdefaults = defaults;
1821 : }
1822 : }
1823 :
1824 255790 : switch (pform->prokind)
1825 : {
1826 34369 : case PROKIND_AGGREGATE:
1827 34369 : result = FUNCDETAIL_AGGREGATE;
1828 34369 : break;
1829 219549 : case PROKIND_FUNCTION:
1830 219549 : result = FUNCDETAIL_NORMAL;
1831 219549 : 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 255790 : ReleaseSysCache(ftup);
1845 255790 : 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 690689 : make_fn_arguments(ParseState *pstate,
1952 : List *fargs,
1953 : Oid *actual_arg_types,
1954 : Oid *declared_arg_types)
1955 : {
1956 : ListCell *current_fargs;
1957 690689 : int i = 0;
1958 :
1959 2006889 : foreach(current_fargs, fargs)
1960 : {
1961 : /* types don't match? then force coercion using a function call... */
1962 1316251 : if (actual_arg_types[i] != declared_arg_types[i])
1963 : {
1964 404105 : 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 404105 : 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 391946 : node = coerce_type(pstate,
1986 : node,
1987 391946 : actual_arg_types[i],
1988 391946 : declared_arg_types[i], -1,
1989 : COERCION_IMPLICIT,
1990 : COERCE_IMPLICIT_CAST,
1991 : -1);
1992 391895 : lfirst(current_fargs) = node;
1993 : }
1994 : }
1995 1316200 : i++;
1996 : }
1997 690638 : }
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 45211 : 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 45211 : typtup = LookupTypeNameExtended(NULL, makeTypeNameFromNameList(funcname),
2017 : NULL, false, false);
2018 45211 : if (typtup == NULL)
2019 44663 : 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 8804 : 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 8804 : if (IsA(first_arg, Var) &&
2055 7385 : ((Var *) first_arg)->varattno == InvalidAttrNumber)
2056 : {
2057 : ParseNamespaceItem *nsitem;
2058 :
2059 120 : nsitem = GetNSItemByRangeTablePosn(pstate,
2060 : ((Var *) first_arg)->varno,
2061 120 : ((Var *) first_arg)->varlevelsup);
2062 : /* Return a Var if funcname matches a column, else NULL */
2063 120 : return scanNSItemForColumn(pstate, nsitem,
2064 120 : ((Var *) first_arg)->varlevelsup,
2065 : funcname, location);
2066 : }
2067 :
2068 : /*
2069 : * Else do it the hard way with get_expr_result_tupdesc().
2070 : *
2071 : * If it's a Var of type RECORD, we have to work even harder: we have to
2072 : * find what the Var refers to, and pass that to get_expr_result_tupdesc.
2073 : * That task is handled by expandRecordVariable().
2074 : */
2075 8684 : if (IsA(first_arg, Var) &&
2076 7265 : ((Var *) first_arg)->vartype == RECORDOID)
2077 1396 : tupdesc = expandRecordVariable(pstate, (Var *) first_arg, 0);
2078 : else
2079 7288 : tupdesc = get_expr_result_tupdesc(first_arg, true);
2080 8684 : if (!tupdesc)
2081 1 : return NULL; /* unresolvable RECORD type */
2082 :
2083 106947 : for (i = 0; i < tupdesc->natts; i++)
2084 : {
2085 106907 : Form_pg_attribute att = TupleDescAttr(tupdesc, i);
2086 :
2087 106907 : if (strcmp(funcname, NameStr(att->attname)) == 0 &&
2088 8643 : !att->attisdropped)
2089 : {
2090 : /* Success, so generate a FieldSelect expression */
2091 8643 : FieldSelect *fselect = makeNode(FieldSelect);
2092 :
2093 8643 : fselect->arg = (Expr *) first_arg;
2094 8643 : fselect->fieldnum = i + 1;
2095 8643 : fselect->resulttype = att->atttypid;
2096 8643 : fselect->resulttypmod = att->atttypmod;
2097 : /* save attribute's collation for parse_collate.c */
2098 8643 : fselect->resultcollid = att->attcollation;
2099 8643 : return (Node *) fselect;
2100 : }
2101 : }
2102 :
2103 40 : return NULL; /* funcname does not match any column */
2104 : }
2105 :
2106 : /*
2107 : * funcname_signature_string
2108 : * Build a string representing a function name, including arg types.
2109 : * The result is something like "foo(integer)".
2110 : *
2111 : * If argnames isn't NIL, it is a list of C strings representing the actual
2112 : * arg names for the last N arguments. This must be considered part of the
2113 : * function signature too, when dealing with named-notation function calls.
2114 : *
2115 : * This is typically used in the construction of function-not-found error
2116 : * messages.
2117 : */
2118 : const char *
2119 547 : funcname_signature_string(const char *funcname, int nargs,
2120 : List *argnames, const Oid *argtypes)
2121 : {
2122 : StringInfoData argbuf;
2123 : int numposargs;
2124 : ListCell *lc;
2125 : int i;
2126 :
2127 547 : initStringInfo(&argbuf);
2128 :
2129 547 : appendStringInfo(&argbuf, "%s(", funcname);
2130 :
2131 547 : numposargs = nargs - list_length(argnames);
2132 547 : lc = list_head(argnames);
2133 :
2134 1397 : for (i = 0; i < nargs; i++)
2135 : {
2136 850 : if (i)
2137 386 : appendStringInfoString(&argbuf, ", ");
2138 850 : if (i >= numposargs)
2139 : {
2140 72 : appendStringInfo(&argbuf, "%s => ", (char *) lfirst(lc));
2141 72 : lc = lnext(argnames, lc);
2142 : }
2143 850 : appendStringInfoString(&argbuf, format_type_be(argtypes[i]));
2144 : }
2145 :
2146 547 : appendStringInfoChar(&argbuf, ')');
2147 :
2148 547 : return argbuf.data; /* return palloc'd string buffer */
2149 : }
2150 :
2151 : /*
2152 : * func_signature_string
2153 : * As above, but function name is passed as a qualified name list.
2154 : */
2155 : const char *
2156 531 : func_signature_string(List *funcname, int nargs,
2157 : List *argnames, const Oid *argtypes)
2158 : {
2159 531 : return funcname_signature_string(NameListToString(funcname),
2160 : nargs, argnames, argtypes);
2161 : }
2162 :
2163 : /*
2164 : * LookupFuncNameInternal
2165 : * Workhorse for LookupFuncName/LookupFuncWithArgs
2166 : *
2167 : * In an error situation, e.g. can't find the function, then we return
2168 : * InvalidOid and set *lookupError to indicate what went wrong.
2169 : *
2170 : * Possible errors:
2171 : * FUNCLOOKUP_NOSUCHFUNC: we can't find a function of this name.
2172 : * FUNCLOOKUP_AMBIGUOUS: more than one function matches.
2173 : */
2174 : static Oid
2175 21341 : LookupFuncNameInternal(ObjectType objtype, List *funcname,
2176 : int nargs, const Oid *argtypes,
2177 : bool include_out_arguments, bool missing_ok,
2178 : FuncLookupError *lookupError)
2179 : {
2180 21341 : Oid result = InvalidOid;
2181 : FuncCandidateList clist;
2182 : int fgc_flags;
2183 :
2184 : /* NULL argtypes allowed for nullary functions only */
2185 : Assert(argtypes != NULL || nargs == 0);
2186 :
2187 : /* Always set *lookupError, to forestall uninitialized-variable warnings */
2188 21341 : *lookupError = FUNCLOOKUP_NOSUCHFUNC;
2189 :
2190 : /* Get list of candidate objects */
2191 21341 : clist = FuncnameGetCandidates(funcname, nargs, NIL, false, false,
2192 : include_out_arguments, missing_ok,
2193 : &fgc_flags);
2194 :
2195 : /* Scan list for a match to the arg types (if specified) and the objtype */
2196 46405 : for (; clist != NULL; clist = clist->next)
2197 : {
2198 : /* Check arg type match, if specified */
2199 25120 : if (nargs >= 0)
2200 : {
2201 : /* if nargs==0, argtypes can be null; don't pass that to memcmp */
2202 24778 : if (nargs > 0 &&
2203 12499 : memcmp(argtypes, clist->args, nargs * sizeof(Oid)) != 0)
2204 4864 : continue;
2205 : }
2206 :
2207 : /* Check for duplicates reported by FuncnameGetCandidates */
2208 20256 : if (!OidIsValid(clist->oid))
2209 : {
2210 4 : *lookupError = FUNCLOOKUP_AMBIGUOUS;
2211 4 : return InvalidOid;
2212 : }
2213 :
2214 : /* Check objtype match, if specified */
2215 20252 : switch (objtype)
2216 : {
2217 14774 : case OBJECT_FUNCTION:
2218 : case OBJECT_AGGREGATE:
2219 : /* Ignore procedures */
2220 14774 : if (get_func_prokind(clist->oid) == PROKIND_PROCEDURE)
2221 0 : continue;
2222 14774 : break;
2223 125 : case OBJECT_PROCEDURE:
2224 : /* Ignore non-procedures */
2225 125 : if (get_func_prokind(clist->oid) != PROKIND_PROCEDURE)
2226 8 : continue;
2227 117 : break;
2228 5353 : case OBJECT_ROUTINE:
2229 : /* no restriction */
2230 5353 : break;
2231 20244 : default:
2232 : Assert(false);
2233 : }
2234 :
2235 : /* Check for multiple matches */
2236 20244 : if (OidIsValid(result))
2237 : {
2238 28 : *lookupError = FUNCLOOKUP_AMBIGUOUS;
2239 28 : return InvalidOid;
2240 : }
2241 :
2242 : /* OK, we have a candidate */
2243 20216 : result = clist->oid;
2244 : }
2245 :
2246 21285 : return result;
2247 : }
2248 :
2249 : /*
2250 : * LookupFuncName
2251 : *
2252 : * Given a possibly-qualified function name and optionally a set of argument
2253 : * types, look up the function. Pass nargs == -1 to indicate that the number
2254 : * and types of the arguments are unspecified (this is NOT the same as
2255 : * specifying that there are no arguments).
2256 : *
2257 : * If the function name is not schema-qualified, it is sought in the current
2258 : * namespace search path.
2259 : *
2260 : * If the function is not found, we return InvalidOid if missing_ok is true,
2261 : * else raise an error.
2262 : *
2263 : * If nargs == -1 and multiple functions are found matching this function name
2264 : * we will raise an ambiguous-function error, regardless of what missing_ok is
2265 : * set to.
2266 : *
2267 : * Only functions will be found; procedures will be ignored even if they
2268 : * match the name and argument types. (However, we don't trouble to reject
2269 : * aggregates or window functions here.)
2270 : */
2271 : Oid
2272 15440 : LookupFuncName(List *funcname, int nargs, const Oid *argtypes, bool missing_ok)
2273 : {
2274 : Oid funcoid;
2275 : FuncLookupError lookupError;
2276 :
2277 15440 : funcoid = LookupFuncNameInternal(OBJECT_FUNCTION,
2278 : funcname, nargs, argtypes,
2279 : false, missing_ok,
2280 : &lookupError);
2281 :
2282 15440 : if (OidIsValid(funcoid))
2283 14506 : return funcoid;
2284 :
2285 934 : switch (lookupError)
2286 : {
2287 934 : case FUNCLOOKUP_NOSUCHFUNC:
2288 : /* Let the caller deal with it when missing_ok is true */
2289 934 : if (missing_ok)
2290 908 : return InvalidOid;
2291 :
2292 26 : if (nargs < 0)
2293 0 : ereport(ERROR,
2294 : (errcode(ERRCODE_UNDEFINED_FUNCTION),
2295 : errmsg("could not find a function named \"%s\"",
2296 : NameListToString(funcname))));
2297 : else
2298 26 : ereport(ERROR,
2299 : (errcode(ERRCODE_UNDEFINED_FUNCTION),
2300 : errmsg("function %s does not exist",
2301 : func_signature_string(funcname, nargs,
2302 : NIL, argtypes))));
2303 : break;
2304 :
2305 0 : case FUNCLOOKUP_AMBIGUOUS:
2306 : /* Raise an error regardless of missing_ok */
2307 0 : ereport(ERROR,
2308 : (errcode(ERRCODE_AMBIGUOUS_FUNCTION),
2309 : errmsg("function name \"%s\" is not unique",
2310 : NameListToString(funcname)),
2311 : errhint("Specify the argument list to select the function unambiguously.")));
2312 : break;
2313 : }
2314 :
2315 0 : return InvalidOid; /* Keep compiler quiet */
2316 : }
2317 :
2318 : /*
2319 : * LookupFuncWithArgs
2320 : *
2321 : * Like LookupFuncName, but the argument types are specified by an
2322 : * ObjectWithArgs node. Also, this function can check whether the result is a
2323 : * function, procedure, or aggregate, based on the objtype argument. Pass
2324 : * OBJECT_ROUTINE to accept any of them.
2325 : *
2326 : * For historical reasons, we also accept aggregates when looking for a
2327 : * function.
2328 : *
2329 : * When missing_ok is true we don't generate any error for missing objects and
2330 : * return InvalidOid. Other types of errors can still be raised, regardless
2331 : * of the value of missing_ok.
2332 : */
2333 : Oid
2334 5838 : LookupFuncWithArgs(ObjectType objtype, ObjectWithArgs *func, bool missing_ok)
2335 : {
2336 : Oid argoids[FUNC_MAX_ARGS];
2337 : int argcount;
2338 : int nargs;
2339 : int i;
2340 : ListCell *args_item;
2341 : Oid oid;
2342 : FuncLookupError lookupError;
2343 :
2344 : Assert(objtype == OBJECT_AGGREGATE ||
2345 : objtype == OBJECT_FUNCTION ||
2346 : objtype == OBJECT_PROCEDURE ||
2347 : objtype == OBJECT_ROUTINE);
2348 :
2349 5838 : argcount = list_length(func->objargs);
2350 5838 : if (argcount > FUNC_MAX_ARGS)
2351 : {
2352 0 : if (objtype == OBJECT_PROCEDURE)
2353 0 : ereport(ERROR,
2354 : (errcode(ERRCODE_TOO_MANY_ARGUMENTS),
2355 : errmsg_plural("procedures cannot have more than %d argument",
2356 : "procedures cannot have more than %d arguments",
2357 : FUNC_MAX_ARGS,
2358 : FUNC_MAX_ARGS)));
2359 : else
2360 0 : ereport(ERROR,
2361 : (errcode(ERRCODE_TOO_MANY_ARGUMENTS),
2362 : errmsg_plural("functions cannot have more than %d argument",
2363 : "functions cannot have more than %d arguments",
2364 : FUNC_MAX_ARGS,
2365 : FUNC_MAX_ARGS)));
2366 : }
2367 :
2368 : /*
2369 : * First, perform a lookup considering only input arguments (traditional
2370 : * Postgres rules).
2371 : */
2372 5838 : i = 0;
2373 13965 : foreach(args_item, func->objargs)
2374 : {
2375 8147 : TypeName *t = lfirst_node(TypeName, args_item);
2376 :
2377 8147 : argoids[i] = LookupTypeNameOid(NULL, t, missing_ok);
2378 8143 : if (!OidIsValid(argoids[i]))
2379 16 : return InvalidOid; /* missing_ok must be true */
2380 8127 : i++;
2381 : }
2382 :
2383 : /*
2384 : * Set nargs for LookupFuncNameInternal. It expects -1 to mean no args
2385 : * were specified.
2386 : */
2387 5818 : nargs = func->args_unspecified ? -1 : argcount;
2388 :
2389 : /*
2390 : * In args_unspecified mode, also tell LookupFuncNameInternal to consider
2391 : * the object type, since there seems no reason not to. However, if we
2392 : * have an argument list, disable the objtype check, because we'd rather
2393 : * complain about "object is of wrong type" than "object doesn't exist".
2394 : * (Note that with args, FuncnameGetCandidates will have ensured there's
2395 : * only one argtype match, so we're not risking an ambiguity failure via
2396 : * this choice.)
2397 : */
2398 5818 : oid = LookupFuncNameInternal(func->args_unspecified ? objtype : OBJECT_ROUTINE,
2399 : func->objname, nargs, argoids,
2400 : false, missing_ok,
2401 : &lookupError);
2402 :
2403 : /*
2404 : * If PROCEDURE or ROUTINE was specified, and we have an argument list
2405 : * that contains no parameter mode markers, and we didn't already discover
2406 : * that there's ambiguity, perform a lookup considering all arguments.
2407 : * (Note: for a zero-argument procedure, or in args_unspecified mode, the
2408 : * normal lookup is sufficient; so it's OK to require non-NIL objfuncargs
2409 : * to perform this lookup.)
2410 : */
2411 5794 : if ((objtype == OBJECT_PROCEDURE || objtype == OBJECT_ROUTINE) &&
2412 213 : func->objfuncargs != NIL &&
2413 103 : lookupError != FUNCLOOKUP_AMBIGUOUS)
2414 : {
2415 103 : bool have_param_mode = false;
2416 :
2417 : /*
2418 : * Check for non-default parameter mode markers. If there are any,
2419 : * then the command does not conform to SQL-spec syntax, so we may
2420 : * assume that the traditional Postgres lookup method of considering
2421 : * only input parameters is sufficient. (Note that because the spec
2422 : * doesn't have OUT arguments for functions, we also don't need this
2423 : * hack in FUNCTION or AGGREGATE mode.)
2424 : */
2425 214 : foreach(args_item, func->objfuncargs)
2426 : {
2427 131 : FunctionParameter *fp = lfirst_node(FunctionParameter, args_item);
2428 :
2429 131 : if (fp->mode != FUNC_PARAM_DEFAULT)
2430 : {
2431 20 : have_param_mode = true;
2432 20 : break;
2433 : }
2434 : }
2435 :
2436 103 : if (!have_param_mode)
2437 : {
2438 : Oid poid;
2439 :
2440 : /* Without mode marks, objargs surely includes all params */
2441 : Assert(list_length(func->objfuncargs) == argcount);
2442 :
2443 : /* For objtype == OBJECT_PROCEDURE, we can ignore non-procedures */
2444 83 : poid = LookupFuncNameInternal(objtype, func->objname,
2445 : argcount, argoids,
2446 : true, missing_ok,
2447 : &lookupError);
2448 :
2449 : /* Combine results, handling ambiguity */
2450 83 : if (OidIsValid(poid))
2451 : {
2452 71 : if (OidIsValid(oid) && oid != poid)
2453 : {
2454 : /* oops, we got hits both ways, on different objects */
2455 0 : oid = InvalidOid;
2456 0 : lookupError = FUNCLOOKUP_AMBIGUOUS;
2457 : }
2458 : else
2459 71 : oid = poid;
2460 : }
2461 12 : else if (lookupError == FUNCLOOKUP_AMBIGUOUS)
2462 4 : oid = InvalidOid;
2463 : }
2464 : }
2465 :
2466 5794 : if (OidIsValid(oid))
2467 : {
2468 : /*
2469 : * Even if we found the function, perform validation that the objtype
2470 : * matches the prokind of the found function. For historical reasons
2471 : * we allow the objtype of FUNCTION to include aggregates and window
2472 : * functions; but we draw the line if the object is a procedure. That
2473 : * is a new enough feature that this historical rule does not apply.
2474 : *
2475 : * (This check is partially redundant with the objtype check in
2476 : * LookupFuncNameInternal; but not entirely, since we often don't tell
2477 : * LookupFuncNameInternal to apply that check at all.)
2478 : */
2479 5612 : switch (objtype)
2480 : {
2481 5257 : case OBJECT_FUNCTION:
2482 : /* Only complain if it's a procedure. */
2483 5257 : if (get_func_prokind(oid) == PROKIND_PROCEDURE)
2484 12 : ereport(ERROR,
2485 : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2486 : errmsg("%s is not a function",
2487 : func_signature_string(func->objname, argcount,
2488 : NIL, argoids))));
2489 5245 : break;
2490 :
2491 141 : case OBJECT_PROCEDURE:
2492 : /* Reject if found object is not a procedure. */
2493 141 : if (get_func_prokind(oid) != PROKIND_PROCEDURE)
2494 8 : ereport(ERROR,
2495 : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2496 : errmsg("%s is not a procedure",
2497 : func_signature_string(func->objname, argcount,
2498 : NIL, argoids))));
2499 133 : break;
2500 :
2501 186 : case OBJECT_AGGREGATE:
2502 : /* Reject if found object is not an aggregate. */
2503 186 : if (get_func_prokind(oid) != PROKIND_AGGREGATE)
2504 12 : ereport(ERROR,
2505 : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2506 : errmsg("function %s is not an aggregate",
2507 : func_signature_string(func->objname, argcount,
2508 : NIL, argoids))));
2509 174 : break;
2510 :
2511 28 : default:
2512 : /* OBJECT_ROUTINE accepts anything. */
2513 28 : break;
2514 : }
2515 :
2516 5580 : return oid; /* All good */
2517 : }
2518 : else
2519 : {
2520 : /* Deal with cases where the lookup failed */
2521 182 : switch (lookupError)
2522 : {
2523 150 : case FUNCLOOKUP_NOSUCHFUNC:
2524 : /* Suppress no-such-func errors when missing_ok is true */
2525 150 : if (missing_ok)
2526 32 : break;
2527 :
2528 118 : switch (objtype)
2529 : {
2530 24 : case OBJECT_PROCEDURE:
2531 24 : if (func->args_unspecified)
2532 0 : ereport(ERROR,
2533 : (errcode(ERRCODE_UNDEFINED_FUNCTION),
2534 : errmsg("could not find a procedure named \"%s\"",
2535 : NameListToString(func->objname))));
2536 : else
2537 24 : ereport(ERROR,
2538 : (errcode(ERRCODE_UNDEFINED_FUNCTION),
2539 : errmsg("procedure %s does not exist",
2540 : func_signature_string(func->objname, argcount,
2541 : NIL, argoids))));
2542 : break;
2543 :
2544 40 : case OBJECT_AGGREGATE:
2545 40 : if (func->args_unspecified)
2546 0 : ereport(ERROR,
2547 : (errcode(ERRCODE_UNDEFINED_FUNCTION),
2548 : errmsg("could not find an aggregate named \"%s\"",
2549 : NameListToString(func->objname))));
2550 40 : else if (argcount == 0)
2551 16 : ereport(ERROR,
2552 : (errcode(ERRCODE_UNDEFINED_FUNCTION),
2553 : errmsg("aggregate %s(*) does not exist",
2554 : NameListToString(func->objname))));
2555 : else
2556 24 : ereport(ERROR,
2557 : (errcode(ERRCODE_UNDEFINED_FUNCTION),
2558 : errmsg("aggregate %s does not exist",
2559 : func_signature_string(func->objname, argcount,
2560 : NIL, argoids))));
2561 : break;
2562 :
2563 54 : default:
2564 : /* FUNCTION and ROUTINE */
2565 54 : if (func->args_unspecified)
2566 4 : ereport(ERROR,
2567 : (errcode(ERRCODE_UNDEFINED_FUNCTION),
2568 : errmsg("could not find a function named \"%s\"",
2569 : NameListToString(func->objname))));
2570 : else
2571 50 : ereport(ERROR,
2572 : (errcode(ERRCODE_UNDEFINED_FUNCTION),
2573 : errmsg("function %s does not exist",
2574 : func_signature_string(func->objname, argcount,
2575 : NIL, argoids))));
2576 : break;
2577 : }
2578 : break;
2579 :
2580 32 : case FUNCLOOKUP_AMBIGUOUS:
2581 32 : switch (objtype)
2582 : {
2583 12 : case OBJECT_FUNCTION:
2584 12 : ereport(ERROR,
2585 : (errcode(ERRCODE_AMBIGUOUS_FUNCTION),
2586 : errmsg("function name \"%s\" is not unique",
2587 : NameListToString(func->objname)),
2588 : func->args_unspecified ?
2589 : errhint("Specify the argument list to select the function unambiguously.") : 0));
2590 : break;
2591 16 : case OBJECT_PROCEDURE:
2592 16 : ereport(ERROR,
2593 : (errcode(ERRCODE_AMBIGUOUS_FUNCTION),
2594 : errmsg("procedure name \"%s\" is not unique",
2595 : NameListToString(func->objname)),
2596 : func->args_unspecified ?
2597 : errhint("Specify the argument list to select the procedure unambiguously.") : 0));
2598 : break;
2599 0 : case OBJECT_AGGREGATE:
2600 0 : ereport(ERROR,
2601 : (errcode(ERRCODE_AMBIGUOUS_FUNCTION),
2602 : errmsg("aggregate name \"%s\" is not unique",
2603 : NameListToString(func->objname)),
2604 : func->args_unspecified ?
2605 : errhint("Specify the argument list to select the aggregate unambiguously.") : 0));
2606 : break;
2607 4 : case OBJECT_ROUTINE:
2608 4 : ereport(ERROR,
2609 : (errcode(ERRCODE_AMBIGUOUS_FUNCTION),
2610 : errmsg("routine name \"%s\" is not unique",
2611 : NameListToString(func->objname)),
2612 : func->args_unspecified ?
2613 : errhint("Specify the argument list to select the routine unambiguously.") : 0));
2614 : break;
2615 :
2616 0 : default:
2617 : Assert(false); /* Disallowed by Assert above */
2618 0 : break;
2619 : }
2620 0 : break;
2621 : }
2622 :
2623 32 : return InvalidOid;
2624 : }
2625 : }
2626 :
2627 : /*
2628 : * check_srf_call_placement
2629 : * Verify that a set-returning function is called in a valid place,
2630 : * and throw a nice error if not.
2631 : *
2632 : * A side-effect is to set pstate->p_hasTargetSRFs true if appropriate.
2633 : *
2634 : * last_srf should be a copy of pstate->p_last_srf from just before we
2635 : * started transforming the function's arguments. This allows detection
2636 : * of whether the SRF's arguments contain any SRFs.
2637 : */
2638 : void
2639 34720 : check_srf_call_placement(ParseState *pstate, Node *last_srf, int location)
2640 : {
2641 : const char *err;
2642 : bool errkind;
2643 :
2644 : /*
2645 : * Check to see if the set-returning function is in an invalid place
2646 : * within the query. Basically, we don't allow SRFs anywhere except in
2647 : * the targetlist (which includes GROUP BY/ORDER BY expressions), VALUES,
2648 : * and functions in FROM.
2649 : *
2650 : * For brevity we support two schemes for reporting an error here: set
2651 : * "err" to a custom message, or set "errkind" true if the error context
2652 : * is sufficiently identified by what ParseExprKindName will return, *and*
2653 : * what it will return is just a SQL keyword. (Otherwise, use a custom
2654 : * message to avoid creating translation problems.)
2655 : */
2656 34720 : err = NULL;
2657 34720 : errkind = false;
2658 34720 : switch (pstate->p_expr_kind)
2659 : {
2660 0 : case EXPR_KIND_NONE:
2661 : Assert(false); /* can't happen */
2662 0 : break;
2663 0 : case EXPR_KIND_OTHER:
2664 : /* Accept SRF here; caller must throw error if wanted */
2665 0 : break;
2666 0 : case EXPR_KIND_JOIN_ON:
2667 : case EXPR_KIND_JOIN_USING:
2668 0 : err = _("set-returning functions are not allowed in JOIN conditions");
2669 0 : break;
2670 0 : case EXPR_KIND_FROM_SUBSELECT:
2671 : /* can't get here, but just in case, throw an error */
2672 0 : errkind = true;
2673 0 : break;
2674 24545 : case EXPR_KIND_FROM_FUNCTION:
2675 : /* okay, but we don't allow nested SRFs here */
2676 : /* errmsg is chosen to match transformRangeFunction() */
2677 : /* errposition should point to the inner SRF */
2678 24545 : if (pstate->p_last_srf != last_srf)
2679 4 : ereport(ERROR,
2680 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2681 : errmsg("set-returning functions must appear at top level of FROM"),
2682 : parser_errposition(pstate,
2683 : exprLocation(pstate->p_last_srf))));
2684 24541 : break;
2685 0 : case EXPR_KIND_WHERE:
2686 0 : errkind = true;
2687 0 : break;
2688 0 : case EXPR_KIND_POLICY:
2689 0 : err = _("set-returning functions are not allowed in policy expressions");
2690 0 : break;
2691 0 : case EXPR_KIND_HAVING:
2692 0 : errkind = true;
2693 0 : break;
2694 0 : case EXPR_KIND_FILTER:
2695 0 : errkind = true;
2696 0 : break;
2697 8 : case EXPR_KIND_WINDOW_PARTITION:
2698 : case EXPR_KIND_WINDOW_ORDER:
2699 : /* okay, these are effectively GROUP BY/ORDER BY */
2700 8 : pstate->p_hasTargetSRFs = true;
2701 8 : break;
2702 0 : case EXPR_KIND_WINDOW_FRAME_RANGE:
2703 : case EXPR_KIND_WINDOW_FRAME_ROWS:
2704 : case EXPR_KIND_WINDOW_FRAME_GROUPS:
2705 0 : err = _("set-returning functions are not allowed in window definitions");
2706 0 : break;
2707 10028 : case EXPR_KIND_SELECT_TARGET:
2708 : case EXPR_KIND_INSERT_TARGET:
2709 : /* okay */
2710 10028 : pstate->p_hasTargetSRFs = true;
2711 10028 : break;
2712 4 : case EXPR_KIND_UPDATE_SOURCE:
2713 : case EXPR_KIND_UPDATE_TARGET:
2714 : /* disallowed because it would be ambiguous what to do */
2715 4 : errkind = true;
2716 4 : break;
2717 24 : case EXPR_KIND_GROUP_BY:
2718 : case EXPR_KIND_ORDER_BY:
2719 : /* okay */
2720 24 : pstate->p_hasTargetSRFs = true;
2721 24 : break;
2722 0 : case EXPR_KIND_DISTINCT_ON:
2723 : /* okay */
2724 0 : pstate->p_hasTargetSRFs = true;
2725 0 : break;
2726 4 : case EXPR_KIND_LIMIT:
2727 : case EXPR_KIND_OFFSET:
2728 4 : errkind = true;
2729 4 : break;
2730 4 : case EXPR_KIND_RETURNING:
2731 : case EXPR_KIND_MERGE_RETURNING:
2732 4 : errkind = true;
2733 4 : break;
2734 4 : case EXPR_KIND_VALUES:
2735 : /* SRFs are presently not supported by nodeValuesscan.c */
2736 4 : errkind = true;
2737 4 : break;
2738 71 : case EXPR_KIND_VALUES_SINGLE:
2739 : /* okay, since we process this like a SELECT tlist */
2740 71 : pstate->p_hasTargetSRFs = true;
2741 71 : break;
2742 0 : case EXPR_KIND_MERGE_WHEN:
2743 0 : err = _("set-returning functions are not allowed in MERGE WHEN conditions");
2744 0 : break;
2745 0 : case EXPR_KIND_CHECK_CONSTRAINT:
2746 : case EXPR_KIND_DOMAIN_CHECK:
2747 0 : err = _("set-returning functions are not allowed in check constraints");
2748 0 : break;
2749 4 : case EXPR_KIND_COLUMN_DEFAULT:
2750 : case EXPR_KIND_FUNCTION_DEFAULT:
2751 4 : err = _("set-returning functions are not allowed in DEFAULT expressions");
2752 4 : break;
2753 0 : case EXPR_KIND_INDEX_EXPRESSION:
2754 0 : err = _("set-returning functions are not allowed in index expressions");
2755 0 : break;
2756 0 : case EXPR_KIND_INDEX_PREDICATE:
2757 0 : err = _("set-returning functions are not allowed in index predicates");
2758 0 : break;
2759 0 : case EXPR_KIND_STATS_EXPRESSION:
2760 0 : err = _("set-returning functions are not allowed in statistics expressions");
2761 0 : break;
2762 0 : case EXPR_KIND_ALTER_COL_TRANSFORM:
2763 0 : err = _("set-returning functions are not allowed in transform expressions");
2764 0 : break;
2765 0 : case EXPR_KIND_EXECUTE_PARAMETER:
2766 0 : err = _("set-returning functions are not allowed in EXECUTE parameters");
2767 0 : break;
2768 0 : case EXPR_KIND_TRIGGER_WHEN:
2769 0 : err = _("set-returning functions are not allowed in trigger WHEN conditions");
2770 0 : break;
2771 8 : case EXPR_KIND_PARTITION_BOUND:
2772 8 : err = _("set-returning functions are not allowed in partition bound");
2773 8 : break;
2774 4 : case EXPR_KIND_PARTITION_EXPRESSION:
2775 4 : err = _("set-returning functions are not allowed in partition key expressions");
2776 4 : break;
2777 0 : case EXPR_KIND_CALL_ARGUMENT:
2778 0 : err = _("set-returning functions are not allowed in CALL arguments");
2779 0 : break;
2780 4 : case EXPR_KIND_COPY_WHERE:
2781 4 : err = _("set-returning functions are not allowed in COPY FROM WHERE conditions");
2782 4 : break;
2783 8 : case EXPR_KIND_GENERATED_COLUMN:
2784 8 : err = _("set-returning functions are not allowed in column generation expressions");
2785 8 : break;
2786 0 : case EXPR_KIND_CYCLE_MARK:
2787 0 : errkind = true;
2788 0 : break;
2789 0 : case EXPR_KIND_PROPGRAPH_PROPERTY:
2790 0 : err = _("set-returning functions are not allowed in property definition expressions");
2791 0 : break;
2792 0 : case EXPR_KIND_FOR_PORTION:
2793 0 : err = _("set-returning functions are not allowed in FOR PORTION OF expressions");
2794 0 : break;
2795 :
2796 : /*
2797 : * There is intentionally no default: case here, so that the
2798 : * compiler will warn if we add a new ParseExprKind without
2799 : * extending this switch. If we do see an unrecognized value at
2800 : * runtime, the behavior will be the same as for EXPR_KIND_OTHER,
2801 : * which is sane anyway.
2802 : */
2803 : }
2804 34716 : if (err)
2805 28 : ereport(ERROR,
2806 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2807 : errmsg_internal("%s", err),
2808 : parser_errposition(pstate, location)));
2809 34688 : if (errkind)
2810 16 : ereport(ERROR,
2811 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2812 : /* translator: %s is name of a SQL construct, eg GROUP BY */
2813 : errmsg("set-returning functions are not allowed in %s",
2814 : ParseExprKindName(pstate->p_expr_kind)),
2815 : parser_errposition(pstate, location)));
2816 34672 : }
|