Line data Source code
1 : /*-------------------------------------------------------------------------
2 : *
3 : * parse_func.c
4 : * handle function calls in parser
5 : *
6 : * Portions Copyright (c) 1996-2025, 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 380474 : ParseFuncOrColumn(ParseState *pstate, List *funcname, List *fargs,
93 : Node *last_srf, FuncCall *fn, bool proc_call, int location)
94 : {
95 380474 : bool is_column = (fn == NULL);
96 380474 : List *agg_order = (fn ? fn->agg_order : NIL);
97 380474 : Expr *agg_filter = NULL;
98 380474 : WindowDef *over = (fn ? fn->over : NULL);
99 380474 : bool agg_within_group = (fn ? fn->agg_within_group : false);
100 380474 : bool agg_star = (fn ? fn->agg_star : false);
101 380474 : bool agg_distinct = (fn ? fn->agg_distinct : false);
102 380474 : bool func_variadic = (fn ? fn->func_variadic : false);
103 380474 : int ignore_nulls = (fn ? fn->ignore_nulls : NO_NULLTREATMENT);
104 380474 : CoercionForm funcformat = (fn ? fn->funcformat : COERCE_EXPLICIT_CALL);
105 : bool could_be_projection;
106 : Oid rettype;
107 : Oid funcid;
108 : ListCell *l;
109 380474 : 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 380474 : char aggkind = 0;
123 : ParseCallbackState pcbstate;
124 :
125 : /*
126 : * If there's an aggregate filter, transform it using transformWhereClause
127 : */
128 380474 : if (fn && fn->agg_filter != NULL)
129 820 : 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 380462 : 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 380462 : nargs = 0;
159 1003816 : foreach(l, fargs)
160 : {
161 623354 : Node *arg = lfirst(l);
162 623354 : Oid argtype = exprType(arg);
163 :
164 623354 : 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 623354 : 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 380462 : argnames = NIL;
183 1003798 : foreach(l, fargs)
184 : {
185 623354 : Node *arg = lfirst(l);
186 :
187 623354 : if (IsA(arg, NamedArgExpr))
188 : {
189 47122 : NamedArgExpr *na = (NamedArgExpr *) arg;
190 : ListCell *lc;
191 :
192 : /* Reject duplicate arg names */
193 101720 : foreach(lc, argnames)
194 : {
195 54604 : if (strcmp(na->name, (char *) lfirst(lc)) == 0)
196 6 : 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 47116 : argnames = lappend(argnames, na->name);
203 : }
204 : else
205 : {
206 576232 : if (argnames != NIL)
207 12 : 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 380444 : if (fargs)
215 : {
216 334974 : 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 150912 : could_be_projection = (nargs == 1 && !proc_call &&
228 148916 : agg_order == NIL && agg_filter == NULL &&
229 148350 : !agg_star && !agg_distinct && over == NULL &&
230 289938 : !func_variadic && argnames == NIL &&
231 675952 : list_length(funcname) == 1 &&
232 193992 : (actual_arg_types[0] == RECORDOID ||
233 95398 : ISCOMPLEX(actual_arg_types[0])));
234 :
235 : /*
236 : * If it's column syntax, check for column projection case first.
237 : */
238 380444 : if (could_be_projection && is_column)
239 : {
240 11572 : retval = ParseComplexProjection(pstate,
241 11572 : strVal(linitial(funcname)),
242 : first_arg,
243 : location);
244 11572 : if (retval)
245 11354 : 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 369090 : setup_parser_errposition_callback(&pcbstate, pstate, location);
269 :
270 369090 : fdresult = func_get_detail(funcname, fargs, argnames, nargs,
271 : actual_arg_types,
272 369090 : !func_variadic, true, proc_call,
273 : &fgc_flags,
274 : &funcid, &rettype, &retset,
275 : &nvargs, &vatype,
276 369090 : &declared_arg_types, &argdefaults);
277 :
278 369090 : 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 369090 : if (proc_call &&
286 518 : (fdresult == FUNCDETAIL_NORMAL ||
287 512 : fdresult == FUNCDETAIL_AGGREGATE ||
288 512 : fdresult == FUNCDETAIL_WINDOWFUNC ||
289 : fdresult == FUNCDETAIL_COERCION))
290 18 : 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 369072 : if (fdresult == FUNCDETAIL_PROCEDURE && !proc_call)
300 6 : 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 369066 : if (fdresult == FUNCDETAIL_NORMAL ||
310 47368 : 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 322298 : 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 322298 : 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 322298 : 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 322298 : 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 322298 : 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 322298 : if (over)
349 6 : 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 369060 : if (fdresult == FUNCDETAIL_NORMAL || fdresult == FUNCDETAIL_PROCEDURE)
360 : {
361 : /* Nothing special to do for these cases. */
362 : }
363 47368 : 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 43914 : tup = SearchSysCache1(AGGFNOID, ObjectIdGetDatum(funcid));
373 43914 : if (!HeapTupleIsValid(tup)) /* should not happen */
374 0 : elog(ERROR, "cache lookup failed for aggregate %u", funcid);
375 43914 : classForm = (Form_pg_aggregate) GETSTRUCT(tup);
376 43914 : aggkind = classForm->aggkind;
377 43914 : catDirectArgs = classForm->aggnumdirectargs;
378 43914 : ReleaseSysCache(tup);
379 :
380 : /* Now check various disallowed cases. */
381 43914 : if (AGGKIND_IS_ORDERED_SET(aggkind))
382 : {
383 : int numAggregatedArgs;
384 : int numDirectArgs;
385 :
386 342 : if (!agg_within_group)
387 6 : 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 336 : 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 336 : numAggregatedArgs = list_length(agg_order);
413 336 : numDirectArgs = nargs - numAggregatedArgs;
414 : Assert(numDirectArgs >= 0);
415 :
416 336 : if (!OidIsValid(vatype))
417 : {
418 : /* Test is simple if aggregate isn't variadic */
419 186 : 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 150 : pronargs = nargs;
445 150 : if (nvargs > 1)
446 150 : pronargs -= nvargs - 1;
447 150 : 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 150 : if (aggkind == AGGKIND_HYPOTHETICAL)
476 : {
477 150 : if (nvargs != 2 * numAggregatedArgs)
478 6 : 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 330 : if (aggkind == AGGKIND_HYPOTHETICAL)
510 144 : 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 43572 : if (agg_within_group)
517 6 : 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 43566 : if (ignore_nulls != NO_NULLTREATMENT)
525 12 : 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 3454 : else if (fdresult == FUNCDETAIL_WINDOWFUNC)
532 : {
533 : /*
534 : * True window functions must be called with a window definition.
535 : */
536 2230 : 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 2230 : 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 1224 : 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 600 : return coerce_type(pstate, linitial(fargs),
557 : actual_arg_types[0], rettype, -1,
558 : COERCION_EXPLICIT, COERCE_EXPLICIT_CALL, location);
559 : }
560 624 : 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 30 : if (is_column)
570 0 : return NULL;
571 :
572 30 : 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 30 : 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 594 : if (is_column)
599 104 : return NULL;
600 :
601 : /*
602 : * Check for column projection interpretation, since we didn't before.
603 : */
604 490 : if (could_be_projection)
605 : {
606 156 : retval = ParseComplexProjection(pstate,
607 156 : strVal(linitial(funcname)),
608 : first_arg,
609 : location);
610 156 : if (retval)
611 144 : 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 346 : 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 346 : else if (proc_call)
634 14 : 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 332 : 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 367794 : nargsplusdefs = nargs;
661 394462 : foreach(l, argdefaults)
662 : {
663 26668 : Node *expr = (Node *) lfirst(l);
664 :
665 : /* probably shouldn't happen ... */
666 26668 : 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 26668 : 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 367794 : 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 367728 : 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 367658 : if (!OidIsValid(vatype))
698 : {
699 : Assert(nvargs == 0);
700 358380 : 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 367658 : if (nvargs > 0 && vatype != ANYOID)
708 : {
709 2204 : ArrayExpr *newa = makeNode(ArrayExpr);
710 2204 : int non_var_args = nargs - nvargs;
711 : List *vargs;
712 :
713 : Assert(non_var_args >= 0);
714 2204 : vargs = list_copy_tail(fargs, non_var_args);
715 2204 : fargs = list_truncate(fargs, non_var_args);
716 :
717 2204 : newa->elements = vargs;
718 : /* assume all the variadic arguments were coerced to the same type */
719 2204 : newa->element_typeid = exprType((Node *) linitial(vargs));
720 2204 : newa->array_typeid = get_array_type(newa->element_typeid);
721 2204 : 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 2204 : newa->multidims = false;
729 2204 : newa->location = exprLocation((Node *) vargs);
730 :
731 2204 : 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 2204 : 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 367658 : if (nargs > 0 && vatype == ANYOID && func_variadic)
744 : {
745 354 : Oid va_arr_typid = actual_arg_types[nargs - 1];
746 :
747 354 : if (!OidIsValid(get_base_element_type(va_arr_typid)))
748 6 : 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 367652 : if (retset)
757 53146 : check_srf_call_placement(pstate, last_srf, location);
758 :
759 : /* build the appropriate output structure */
760 367580 : if (fdresult == FUNCDETAIL_NORMAL || fdresult == FUNCDETAIL_PROCEDURE)
761 321478 : {
762 321478 : FuncExpr *funcexpr = makeNode(FuncExpr);
763 :
764 321478 : funcexpr->funcid = funcid;
765 321478 : funcexpr->funcresulttype = rettype;
766 321478 : funcexpr->funcretset = retset;
767 321478 : funcexpr->funcvariadic = func_variadic;
768 321478 : funcexpr->funcformat = funcformat;
769 : /* funccollid and inputcollid will be set by parse_collate.c */
770 321478 : funcexpr->args = fargs;
771 321478 : funcexpr->location = location;
772 :
773 321478 : retval = (Node *) funcexpr;
774 : }
775 46102 : else if (fdresult == FUNCDETAIL_AGGREGATE && !over)
776 42082 : {
777 : /* aggregate function */
778 42262 : Aggref *aggref = makeNode(Aggref);
779 :
780 42262 : aggref->aggfnoid = funcid;
781 42262 : aggref->aggtype = rettype;
782 : /* aggcollid and inputcollid will be set by parse_collate.c */
783 42262 : 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 42262 : aggref->aggfilter = agg_filter;
788 42262 : aggref->aggstar = agg_star;
789 42262 : aggref->aggvariadic = func_variadic;
790 42262 : aggref->aggkind = aggkind;
791 42262 : aggref->aggpresorted = false;
792 : /* agglevelsup will be set by transformAggregateCall */
793 42262 : aggref->aggsplit = AGGSPLIT_SIMPLE; /* planner might change this */
794 42262 : aggref->aggno = -1; /* planner will set aggno and aggtransno */
795 42262 : aggref->aggtransno = -1;
796 42262 : 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 42262 : 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 42262 : 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 42262 : 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 42262 : transformAggregateCall(pstate, aggref, fargs, agg_order, agg_distinct);
832 :
833 42082 : retval = (Node *) aggref;
834 : }
835 : else
836 : {
837 : /* window function */
838 3840 : WindowFunc *wfunc = makeNode(WindowFunc);
839 :
840 : Assert(over); /* lack of this was checked above */
841 : Assert(!agg_within_group); /* also checked above */
842 :
843 3840 : wfunc->winfnoid = funcid;
844 3840 : wfunc->wintype = rettype;
845 : /* wincollid and inputcollid will be set by parse_collate.c */
846 3840 : wfunc->args = fargs;
847 : /* winref will be set by transformWindowFuncCall */
848 3840 : wfunc->winstar = agg_star;
849 3840 : wfunc->winagg = (fdresult == FUNCDETAIL_AGGREGATE);
850 3840 : wfunc->aggfilter = agg_filter;
851 3840 : wfunc->ignore_nulls = ignore_nulls;
852 3840 : wfunc->runCondition = NIL;
853 3840 : wfunc->location = location;
854 :
855 : /*
856 : * agg_star is allowed for aggregate functions but distinct isn't
857 : */
858 3840 : 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 3840 : if (wfunc->winagg && fargs == NIL && !agg_star)
869 6 : 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 3834 : 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 3834 : 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 3834 : if (pstate->p_last_srf != last_srf)
897 6 : 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 3828 : 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 3828 : transformWindowFuncCall(pstate, wfunc, over);
912 :
913 3774 : retval = (Node *) wfunc;
914 : }
915 :
916 : /* if it returns a set, remember it for error checks at higher levels */
917 367334 : if (retset)
918 53074 : pstate->p_last_srf = retval;
919 :
920 367334 : 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 346 : 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 346 : if (!(fgc_flags & FGC_NAME_VISIBLE))
944 : {
945 42 : if (fgc_flags & FGC_SCHEMA_GIVEN)
946 2 : return 0; /* schema-qualified name */
947 40 : else if (!(fgc_flags & FGC_NAME_EXISTS))
948 : {
949 34 : if (proc_call)
950 6 : return errdetail("There is no procedure of that name.");
951 : else
952 28 : return errdetail("There is no function of that name.");
953 : }
954 : else
955 : {
956 6 : if (proc_call)
957 0 : return errdetail("A procedure of that name exists, but it is not in the search_path.");
958 : else
959 6 : 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 304 : if (!(fgc_flags & FGC_ARGCOUNT_MATCH))
969 : {
970 36 : if (proc_call)
971 0 : return errdetail("No procedure of that name accepts the given number of arguments.");
972 : else
973 36 : 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 268 : if (argnames != NIL && !(fgc_flags & FGC_ARGNAMES_MATCH))
981 : {
982 12 : if (proc_call)
983 0 : return errdetail("No procedure of that name accepts the given argument names.");
984 : else
985 12 : 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 256 : if (argnames != NIL && !(fgc_flags & FGC_ARGNAMES_NONDUP))
998 12 : return errdetail("In the closest available match, "
999 : "an argument was specified both positionally and by name.");
1000 :
1001 244 : if (argnames != NIL && !(fgc_flags & FGC_ARGNAMES_ALL))
1002 6 : return errdetail("In the closest available match, "
1003 : "not all required arguments were supplied.");
1004 :
1005 238 : if (argnames != NIL && !(fgc_flags & FGC_ARGNAMES_VALID))
1006 6 : return errhint("This call would be correct if the variadic array were labeled VARIADIC and placed last.");
1007 :
1008 232 : if (fgc_flags & FGC_VARIADIC_FAIL)
1009 6 : 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 226 : if (proc_call)
1015 8 : (void) errdetail("No procedure of that name accepts the given argument types.");
1016 : else
1017 218 : (void) errdetail("No function of that name accepts the given argument types.");
1018 226 : return errhint("You might need to add explicit type casts.");
1019 : }
1020 :
1021 :
1022 : /* func_match_argtypes()
1023 : *
1024 : * Given a list of candidate functions (having the right name and number
1025 : * of arguments) and an array of input datatype OIDs, produce a shortlist of
1026 : * those candidates that actually accept the input datatypes (either exactly
1027 : * or by coercion), and return the number of such candidates.
1028 : *
1029 : * Note that can_coerce_type will assume that UNKNOWN inputs are coercible to
1030 : * anything, so candidates will not be eliminated on that basis.
1031 : *
1032 : * NB: okay to modify input list structure, as long as we find at least
1033 : * one match. If no match at all, the list must remain unmodified.
1034 : */
1035 : int
1036 195146 : func_match_argtypes(int nargs,
1037 : Oid *input_typeids,
1038 : FuncCandidateList raw_candidates,
1039 : FuncCandidateList *candidates) /* return value */
1040 : {
1041 : FuncCandidateList current_candidate;
1042 : FuncCandidateList next_candidate;
1043 195146 : int ncandidates = 0;
1044 :
1045 195146 : *candidates = NULL;
1046 :
1047 195146 : for (current_candidate = raw_candidates;
1048 1286608 : current_candidate != NULL;
1049 1091462 : current_candidate = next_candidate)
1050 : {
1051 1091462 : next_candidate = current_candidate->next;
1052 1091462 : if (can_coerce_type(nargs, input_typeids, current_candidate->args,
1053 : COERCION_IMPLICIT))
1054 : {
1055 225522 : current_candidate->next = *candidates;
1056 225522 : *candidates = current_candidate;
1057 225522 : ncandidates++;
1058 : }
1059 : }
1060 :
1061 195146 : return ncandidates;
1062 : } /* func_match_argtypes() */
1063 :
1064 :
1065 : /* func_select_candidate()
1066 : * Given the input argtype array and more than one candidate
1067 : * for the function, attempt to resolve the conflict.
1068 : *
1069 : * Returns the selected candidate if the conflict can be resolved,
1070 : * otherwise returns NULL.
1071 : *
1072 : * Note that the caller has already determined that there is no candidate
1073 : * exactly matching the input argtypes, and has pruned away any "candidates"
1074 : * that aren't actually coercion-compatible with the input types.
1075 : *
1076 : * This is also used for resolving ambiguous operator references. Formerly
1077 : * parse_oper.c had its own, essentially duplicate code for the purpose.
1078 : * The following comments (formerly in parse_oper.c) are kept to record some
1079 : * of the history of these heuristics.
1080 : *
1081 : * OLD COMMENTS:
1082 : *
1083 : * This routine is new code, replacing binary_oper_select_candidate()
1084 : * which dates from v4.2/v1.0.x days. It tries very hard to match up
1085 : * operators with types, including allowing type coercions if necessary.
1086 : * The important thing is that the code do as much as possible,
1087 : * while _never_ doing the wrong thing, where "the wrong thing" would
1088 : * be returning an operator when other better choices are available,
1089 : * or returning an operator which is a non-intuitive possibility.
1090 : * - thomas 1998-05-21
1091 : *
1092 : * The comments below came from binary_oper_select_candidate(), and
1093 : * illustrate the issues and choices which are possible:
1094 : * - thomas 1998-05-20
1095 : *
1096 : * current wisdom holds that the default operator should be one in which
1097 : * both operands have the same type (there will only be one such
1098 : * operator)
1099 : *
1100 : * 7.27.93 - I have decided not to do this; it's too hard to justify, and
1101 : * it's easy enough to typecast explicitly - avi
1102 : * [the rest of this routine was commented out since then - ay]
1103 : *
1104 : * 6/23/95 - I don't complete agree with avi. In particular, casting
1105 : * floats is a pain for users. Whatever the rationale behind not doing
1106 : * this is, I need the following special case to work.
1107 : *
1108 : * In the WHERE clause of a query, if a float is specified without
1109 : * quotes, we treat it as float8. I added the float48* operators so
1110 : * that we can operate on float4 and float8. But now we have more than
1111 : * one matching operator if the right arg is unknown (eg. float
1112 : * specified with quotes). This break some stuff in the regression
1113 : * test where there are floats in quotes not properly casted. Below is
1114 : * the solution. In addition to requiring the operator operates on the
1115 : * same type for both operands [as in the code Avi originally
1116 : * commented out], we also require that the operators be equivalent in
1117 : * some sense. (see equivalentOpersAfterPromotion for details.)
1118 : * - ay 6/95
1119 : */
1120 : FuncCandidateList
1121 12852 : func_select_candidate(int nargs,
1122 : Oid *input_typeids,
1123 : FuncCandidateList candidates)
1124 : {
1125 : FuncCandidateList current_candidate,
1126 : first_candidate,
1127 : last_candidate;
1128 : Oid *current_typeids;
1129 : Oid current_type;
1130 : int i;
1131 : int ncandidates;
1132 : int nbestMatch,
1133 : nmatch,
1134 : nunknowns;
1135 : Oid input_base_typeids[FUNC_MAX_ARGS];
1136 : TYPCATEGORY slot_category[FUNC_MAX_ARGS],
1137 : current_category;
1138 : bool current_is_preferred;
1139 : bool slot_has_preferred_type[FUNC_MAX_ARGS];
1140 : bool resolved_unknowns;
1141 :
1142 : /* protect local fixed-size arrays */
1143 12852 : if (nargs > FUNC_MAX_ARGS)
1144 0 : ereport(ERROR,
1145 : (errcode(ERRCODE_TOO_MANY_ARGUMENTS),
1146 : errmsg_plural("cannot pass more than %d argument to a function",
1147 : "cannot pass more than %d arguments to a function",
1148 : FUNC_MAX_ARGS,
1149 : FUNC_MAX_ARGS)));
1150 :
1151 : /*
1152 : * If any input types are domains, reduce them to their base types. This
1153 : * ensures that we will consider functions on the base type to be "exact
1154 : * matches" in the exact-match heuristic; it also makes it possible to do
1155 : * something useful with the type-category heuristics. Note that this
1156 : * makes it difficult, but not impossible, to use functions declared to
1157 : * take a domain as an input datatype. Such a function will be selected
1158 : * over the base-type function only if it is an exact match at all
1159 : * argument positions, and so was already chosen by our caller.
1160 : *
1161 : * While we're at it, count the number of unknown-type arguments for use
1162 : * later.
1163 : */
1164 12852 : nunknowns = 0;
1165 40302 : for (i = 0; i < nargs; i++)
1166 : {
1167 27450 : if (input_typeids[i] != UNKNOWNOID)
1168 13812 : input_base_typeids[i] = getBaseType(input_typeids[i]);
1169 : else
1170 : {
1171 : /* no need to call getBaseType on UNKNOWNOID */
1172 13638 : input_base_typeids[i] = UNKNOWNOID;
1173 13638 : nunknowns++;
1174 : }
1175 : }
1176 :
1177 : /*
1178 : * Run through all candidates and keep those with the most matches on
1179 : * exact types. Keep all candidates if none match.
1180 : */
1181 12852 : ncandidates = 0;
1182 12852 : nbestMatch = 0;
1183 12852 : last_candidate = NULL;
1184 12852 : for (current_candidate = candidates;
1185 56716 : current_candidate != NULL;
1186 43864 : current_candidate = current_candidate->next)
1187 : {
1188 43864 : current_typeids = current_candidate->args;
1189 43864 : nmatch = 0;
1190 136266 : for (i = 0; i < nargs; i++)
1191 : {
1192 92402 : if (input_base_typeids[i] != UNKNOWNOID &&
1193 42868 : current_typeids[i] == input_base_typeids[i])
1194 14394 : nmatch++;
1195 : }
1196 :
1197 : /* take this one as the best choice so far? */
1198 43864 : if ((nmatch > nbestMatch) || (last_candidate == NULL))
1199 : {
1200 15560 : nbestMatch = nmatch;
1201 15560 : candidates = current_candidate;
1202 15560 : last_candidate = current_candidate;
1203 15560 : ncandidates = 1;
1204 : }
1205 : /* no worse than the last choice, so keep this one too? */
1206 28304 : else if (nmatch == nbestMatch)
1207 : {
1208 19732 : last_candidate->next = current_candidate;
1209 19732 : last_candidate = current_candidate;
1210 19732 : ncandidates++;
1211 : }
1212 : /* otherwise, don't bother keeping this one... */
1213 : }
1214 :
1215 12852 : if (last_candidate) /* terminate rebuilt list */
1216 12852 : last_candidate->next = NULL;
1217 :
1218 12852 : if (ncandidates == 1)
1219 5660 : return candidates;
1220 :
1221 : /*
1222 : * Still too many candidates? Now look for candidates which have either
1223 : * exact matches or preferred types at the args that will require
1224 : * coercion. (Restriction added in 7.4: preferred type must be of same
1225 : * category as input type; give no preference to cross-category
1226 : * conversions to preferred types.) Keep all candidates if none match.
1227 : */
1228 23058 : for (i = 0; i < nargs; i++) /* avoid multiple lookups */
1229 15866 : slot_category[i] = TypeCategory(input_base_typeids[i]);
1230 7192 : ncandidates = 0;
1231 7192 : nbestMatch = 0;
1232 7192 : last_candidate = NULL;
1233 7192 : for (current_candidate = candidates;
1234 31670 : current_candidate != NULL;
1235 24478 : current_candidate = current_candidate->next)
1236 : {
1237 24478 : current_typeids = current_candidate->args;
1238 24478 : nmatch = 0;
1239 77630 : for (i = 0; i < nargs; i++)
1240 : {
1241 53152 : if (input_base_typeids[i] != UNKNOWNOID)
1242 : {
1243 23822 : if (current_typeids[i] == input_base_typeids[i] ||
1244 8378 : IsPreferredType(slot_category[i], current_typeids[i]))
1245 10604 : nmatch++;
1246 : }
1247 : }
1248 :
1249 24478 : if ((nmatch > nbestMatch) || (last_candidate == NULL))
1250 : {
1251 8956 : nbestMatch = nmatch;
1252 8956 : candidates = current_candidate;
1253 8956 : last_candidate = current_candidate;
1254 8956 : ncandidates = 1;
1255 : }
1256 15522 : else if (nmatch == nbestMatch)
1257 : {
1258 14220 : last_candidate->next = current_candidate;
1259 14220 : last_candidate = current_candidate;
1260 14220 : ncandidates++;
1261 : }
1262 : }
1263 :
1264 7192 : if (last_candidate) /* terminate rebuilt list */
1265 7192 : last_candidate->next = NULL;
1266 :
1267 7192 : if (ncandidates == 1)
1268 1626 : return candidates;
1269 :
1270 : /*
1271 : * Still too many candidates? Try assigning types for the unknown inputs.
1272 : *
1273 : * If there are no unknown inputs, we have no more heuristics that apply,
1274 : * and must fail.
1275 : */
1276 5566 : if (nunknowns == 0)
1277 6 : return NULL; /* failed to select a best candidate */
1278 :
1279 : /*
1280 : * The next step examines each unknown argument position to see if we can
1281 : * determine a "type category" for it. If any candidate has an input
1282 : * datatype of STRING category, use STRING category (this bias towards
1283 : * STRING is appropriate since unknown-type literals look like strings).
1284 : * Otherwise, if all the candidates agree on the type category of this
1285 : * argument position, use that category. Otherwise, fail because we
1286 : * cannot determine a category.
1287 : *
1288 : * If we are able to determine a type category, also notice whether any of
1289 : * the candidates takes a preferred datatype within the category.
1290 : *
1291 : * Having completed this examination, remove candidates that accept the
1292 : * wrong category at any unknown position. Also, if at least one
1293 : * candidate accepted a preferred type at a position, remove candidates
1294 : * that accept non-preferred types. If just one candidate remains, return
1295 : * that one. However, if this rule turns out to reject all candidates,
1296 : * keep them all instead.
1297 : */
1298 5560 : resolved_unknowns = false;
1299 18230 : for (i = 0; i < nargs; i++)
1300 : {
1301 : bool have_conflict;
1302 :
1303 12670 : if (input_base_typeids[i] != UNKNOWNOID)
1304 3200 : continue;
1305 9470 : resolved_unknowns = true; /* assume we can do it */
1306 9470 : slot_category[i] = TYPCATEGORY_INVALID;
1307 9470 : slot_has_preferred_type[i] = false;
1308 9470 : have_conflict = false;
1309 9470 : for (current_candidate = candidates;
1310 45546 : current_candidate != NULL;
1311 36076 : current_candidate = current_candidate->next)
1312 : {
1313 36076 : current_typeids = current_candidate->args;
1314 36076 : current_type = current_typeids[i];
1315 36076 : get_type_category_preferred(current_type,
1316 : ¤t_category,
1317 : ¤t_is_preferred);
1318 36076 : if (slot_category[i] == TYPCATEGORY_INVALID)
1319 : {
1320 : /* first candidate */
1321 9470 : slot_category[i] = current_category;
1322 9470 : slot_has_preferred_type[i] = current_is_preferred;
1323 : }
1324 26606 : else if (current_category == slot_category[i])
1325 : {
1326 : /* more candidates in same category */
1327 7520 : slot_has_preferred_type[i] |= current_is_preferred;
1328 : }
1329 : else
1330 : {
1331 : /* category conflict! */
1332 19086 : if (current_category == TYPCATEGORY_STRING)
1333 : {
1334 : /* STRING always wins if available */
1335 2584 : slot_category[i] = current_category;
1336 2584 : slot_has_preferred_type[i] = current_is_preferred;
1337 : }
1338 : else
1339 : {
1340 : /*
1341 : * Remember conflict, but keep going (might find STRING)
1342 : */
1343 16502 : have_conflict = true;
1344 : }
1345 : }
1346 : }
1347 9470 : if (have_conflict && slot_category[i] != TYPCATEGORY_STRING)
1348 : {
1349 : /* Failed to resolve category conflict at this position */
1350 0 : resolved_unknowns = false;
1351 0 : break;
1352 : }
1353 : }
1354 :
1355 5560 : if (resolved_unknowns)
1356 : {
1357 : /* Strip non-matching candidates */
1358 5560 : ncandidates = 0;
1359 5560 : first_candidate = candidates;
1360 5560 : last_candidate = NULL;
1361 5560 : for (current_candidate = candidates;
1362 24842 : current_candidate != NULL;
1363 19282 : current_candidate = current_candidate->next)
1364 : {
1365 19282 : bool keepit = true;
1366 :
1367 19282 : current_typeids = current_candidate->args;
1368 36152 : for (i = 0; i < nargs; i++)
1369 : {
1370 30482 : if (input_base_typeids[i] != UNKNOWNOID)
1371 4676 : continue;
1372 25806 : current_type = current_typeids[i];
1373 25806 : get_type_category_preferred(current_type,
1374 : ¤t_category,
1375 : ¤t_is_preferred);
1376 25806 : if (current_category != slot_category[i])
1377 : {
1378 12532 : keepit = false;
1379 12532 : break;
1380 : }
1381 13274 : if (slot_has_preferred_type[i] && !current_is_preferred)
1382 : {
1383 1080 : keepit = false;
1384 1080 : break;
1385 : }
1386 : }
1387 19282 : if (keepit)
1388 : {
1389 : /* keep this candidate */
1390 5670 : last_candidate = current_candidate;
1391 5670 : ncandidates++;
1392 : }
1393 : else
1394 : {
1395 : /* forget this candidate */
1396 13612 : if (last_candidate)
1397 9850 : last_candidate->next = current_candidate->next;
1398 : else
1399 3762 : first_candidate = current_candidate->next;
1400 : }
1401 : }
1402 :
1403 : /* if we found any matches, restrict our attention to those */
1404 5560 : if (last_candidate)
1405 : {
1406 5560 : candidates = first_candidate;
1407 : /* terminate rebuilt list */
1408 5560 : last_candidate->next = NULL;
1409 : }
1410 :
1411 5560 : if (ncandidates == 1)
1412 5510 : return candidates;
1413 : }
1414 :
1415 : /*
1416 : * Last gasp: if there are both known- and unknown-type inputs, and all
1417 : * the known types are the same, assume the unknown inputs are also that
1418 : * type, and see if that gives us a unique match. If so, use that match.
1419 : *
1420 : * NOTE: for a binary operator with one unknown and one non-unknown input,
1421 : * we already tried this heuristic in binary_oper_exact(). However, that
1422 : * code only finds exact matches, whereas here we will handle matches that
1423 : * involve coercion, polymorphic type resolution, etc.
1424 : */
1425 50 : if (nunknowns < nargs)
1426 : {
1427 50 : Oid known_type = UNKNOWNOID;
1428 :
1429 150 : for (i = 0; i < nargs; i++)
1430 : {
1431 100 : if (input_base_typeids[i] == UNKNOWNOID)
1432 50 : continue;
1433 50 : if (known_type == UNKNOWNOID) /* first known arg? */
1434 50 : known_type = input_base_typeids[i];
1435 0 : else if (known_type != input_base_typeids[i])
1436 : {
1437 : /* oops, not all match */
1438 0 : known_type = UNKNOWNOID;
1439 0 : break;
1440 : }
1441 : }
1442 :
1443 50 : if (known_type != UNKNOWNOID)
1444 : {
1445 : /* okay, just one known type, apply the heuristic */
1446 150 : for (i = 0; i < nargs; i++)
1447 100 : input_base_typeids[i] = known_type;
1448 50 : ncandidates = 0;
1449 50 : last_candidate = NULL;
1450 50 : for (current_candidate = candidates;
1451 210 : current_candidate != NULL;
1452 160 : current_candidate = current_candidate->next)
1453 : {
1454 160 : current_typeids = current_candidate->args;
1455 160 : if (can_coerce_type(nargs, input_base_typeids, current_typeids,
1456 : COERCION_IMPLICIT))
1457 : {
1458 50 : if (++ncandidates > 1)
1459 0 : break; /* not unique, give up */
1460 50 : last_candidate = current_candidate;
1461 : }
1462 : }
1463 50 : if (ncandidates == 1)
1464 : {
1465 : /* successfully identified a unique match */
1466 50 : last_candidate->next = NULL;
1467 50 : return last_candidate;
1468 : }
1469 : }
1470 : }
1471 :
1472 0 : return NULL; /* failed to select a best candidate */
1473 : } /* func_select_candidate() */
1474 :
1475 :
1476 : /* func_get_detail()
1477 : *
1478 : * Find the named function in the system catalogs.
1479 : *
1480 : * Attempt to find the named function in the system catalogs with
1481 : * arguments exactly as specified, so that the normal case (exact match)
1482 : * is as quick as possible.
1483 : *
1484 : * If an exact match isn't found:
1485 : * 1) check for possible interpretation as a type coercion request
1486 : * 2) apply the ambiguous-function resolution rules
1487 : *
1488 : * If there is no match at all, we return FUNCDETAIL_NOTFOUND, and *fgc_flags
1489 : * is filled with some flags that may be useful for issuing an on-point error
1490 : * message (see FuncnameGetCandidates).
1491 : *
1492 : * On success, return values *funcid through *true_typeids receive info about
1493 : * the function. If argdefaults isn't NULL, *argdefaults receives a list of
1494 : * any default argument expressions that need to be added to the given
1495 : * arguments.
1496 : *
1497 : * When processing a named- or mixed-notation call (ie, fargnames isn't NIL),
1498 : * the returned true_typeids and argdefaults are ordered according to the
1499 : * call's argument ordering: first any positional arguments, then the named
1500 : * arguments, then defaulted arguments (if needed and allowed by
1501 : * expand_defaults). Some care is needed if this information is to be compared
1502 : * to the function's pg_proc entry, but in practice the caller can usually
1503 : * just work with the call's argument ordering.
1504 : *
1505 : * We rely primarily on fargnames/nargs/argtypes as the argument description.
1506 : * The actual expression node list is passed in fargs so that we can check
1507 : * for type coercion of a constant. Some callers pass fargs == NIL indicating
1508 : * they don't need that check made. Note also that when fargnames isn't NIL,
1509 : * the fargs list must be passed if the caller wants actual argument position
1510 : * information to be returned into the NamedArgExpr nodes.
1511 : */
1512 : FuncDetailCode
1513 385206 : func_get_detail(List *funcname,
1514 : List *fargs,
1515 : List *fargnames,
1516 : int nargs,
1517 : Oid *argtypes,
1518 : bool expand_variadic,
1519 : bool expand_defaults,
1520 : bool include_out_arguments,
1521 : int *fgc_flags, /* return value */
1522 : Oid *funcid, /* return value */
1523 : Oid *rettype, /* return value */
1524 : bool *retset, /* return value */
1525 : int *nvargs, /* return value */
1526 : Oid *vatype, /* return value */
1527 : Oid **true_typeids, /* return value */
1528 : List **argdefaults) /* optional return value */
1529 : {
1530 : FuncCandidateList raw_candidates;
1531 : FuncCandidateList best_candidate;
1532 :
1533 : /* initialize output arguments to silence compiler warnings */
1534 385206 : *funcid = InvalidOid;
1535 385206 : *rettype = InvalidOid;
1536 385206 : *retset = false;
1537 385206 : *nvargs = 0;
1538 385206 : *vatype = InvalidOid;
1539 385206 : *true_typeids = NULL;
1540 385206 : if (argdefaults)
1541 369090 : *argdefaults = NIL;
1542 :
1543 : /* Get list of possible candidates from namespace search */
1544 385206 : raw_candidates = FuncnameGetCandidates(funcname, nargs, fargnames,
1545 : expand_variadic, expand_defaults,
1546 : include_out_arguments, false,
1547 : fgc_flags);
1548 :
1549 : /*
1550 : * Quickly check if there is an exact match to the input datatypes (there
1551 : * can be only one)
1552 : */
1553 385206 : for (best_candidate = raw_candidates;
1554 778518 : best_candidate != NULL;
1555 393312 : best_candidate = best_candidate->next)
1556 : {
1557 : /* if nargs==0, argtypes can be null; don't pass that to memcmp */
1558 599812 : if (nargs == 0 ||
1559 551618 : memcmp(argtypes, best_candidate->args, nargs * sizeof(Oid)) == 0)
1560 : break;
1561 : }
1562 :
1563 385206 : if (best_candidate == NULL)
1564 : {
1565 : /*
1566 : * If we didn't find an exact match, next consider the possibility
1567 : * that this is really a type-coercion request: a single-argument
1568 : * function call where the function name is a type name. If so, and
1569 : * if the coercion path is RELABELTYPE or COERCEVIAIO, then go ahead
1570 : * and treat the "function call" as a coercion.
1571 : *
1572 : * This interpretation needs to be given higher priority than
1573 : * interpretations involving a type coercion followed by a function
1574 : * call, otherwise we can produce surprising results. For example, we
1575 : * want "text(varchar)" to be interpreted as a simple coercion, not as
1576 : * "text(name(varchar))" which the code below this point is entirely
1577 : * capable of selecting.
1578 : *
1579 : * We also treat a coercion of a previously-unknown-type literal
1580 : * constant to a specific type this way.
1581 : *
1582 : * The reason we reject COERCION_PATH_FUNC here is that we expect the
1583 : * cast implementation function to be named after the target type.
1584 : * Thus the function will be found by normal lookup if appropriate.
1585 : *
1586 : * The reason we reject COERCION_PATH_ARRAYCOERCE is mainly that you
1587 : * can't write "foo[] (something)" as a function call. In theory
1588 : * someone might want to invoke it as "_foo (something)" but we have
1589 : * never supported that historically, so we can insist that people
1590 : * write it as a normal cast instead.
1591 : *
1592 : * We also reject the specific case of COERCEVIAIO for a composite
1593 : * source type and a string-category target type. This is a case that
1594 : * find_coercion_pathway() allows by default, but experience has shown
1595 : * that it's too commonly invoked by mistake. So, again, insist that
1596 : * people use cast syntax if they want to do that.
1597 : *
1598 : * NB: it's important that this code does not exceed what coerce_type
1599 : * can do, because the caller will try to apply coerce_type if we
1600 : * return FUNCDETAIL_COERCION. If we return that result for something
1601 : * coerce_type can't handle, we'll cause infinite recursion between
1602 : * this module and coerce_type!
1603 : */
1604 178706 : if (nargs == 1 && fargs != NIL && fargnames == NIL)
1605 : {
1606 63068 : Oid targetType = FuncNameAsType(funcname);
1607 :
1608 63068 : if (OidIsValid(targetType))
1609 : {
1610 814 : Oid sourceType = argtypes[0];
1611 814 : Node *arg1 = linitial(fargs);
1612 : bool iscoercion;
1613 :
1614 814 : if (sourceType == UNKNOWNOID && IsA(arg1, Const))
1615 : {
1616 : /* always treat typename('literal') as coercion */
1617 538 : iscoercion = true;
1618 : }
1619 : else
1620 : {
1621 : CoercionPathType cpathtype;
1622 : Oid cfuncid;
1623 :
1624 276 : cpathtype = find_coercion_pathway(targetType, sourceType,
1625 : COERCION_EXPLICIT,
1626 : &cfuncid);
1627 276 : switch (cpathtype)
1628 : {
1629 24 : case COERCION_PATH_RELABELTYPE:
1630 24 : iscoercion = true;
1631 24 : break;
1632 200 : case COERCION_PATH_COERCEVIAIO:
1633 388 : if ((sourceType == RECORDOID ||
1634 350 : ISCOMPLEX(sourceType)) &&
1635 162 : TypeCategory(targetType) == TYPCATEGORY_STRING)
1636 162 : iscoercion = false;
1637 : else
1638 38 : iscoercion = true;
1639 200 : break;
1640 52 : default:
1641 52 : iscoercion = false;
1642 52 : break;
1643 : }
1644 : }
1645 :
1646 814 : if (iscoercion)
1647 : {
1648 : /* Treat it as a type coercion */
1649 600 : *funcid = InvalidOid;
1650 600 : *rettype = targetType;
1651 600 : *retset = false;
1652 600 : *nvargs = 0;
1653 600 : *vatype = InvalidOid;
1654 600 : *true_typeids = argtypes;
1655 600 : return FUNCDETAIL_COERCION;
1656 : }
1657 : }
1658 : }
1659 :
1660 : /*
1661 : * didn't find an exact match, so now try to match up candidates...
1662 : */
1663 178106 : if (raw_candidates != NULL)
1664 : {
1665 : FuncCandidateList current_candidates;
1666 : int ncandidates;
1667 :
1668 176746 : ncandidates = func_match_argtypes(nargs,
1669 : argtypes,
1670 : raw_candidates,
1671 : ¤t_candidates);
1672 :
1673 : /* one match only? then run with it... */
1674 176746 : if (ncandidates == 1)
1675 169394 : best_candidate = current_candidates;
1676 :
1677 : /*
1678 : * multiple candidates? then better decide or throw an error...
1679 : */
1680 7352 : else if (ncandidates > 1)
1681 : {
1682 6838 : best_candidate = func_select_candidate(nargs,
1683 : argtypes,
1684 : current_candidates);
1685 :
1686 : /*
1687 : * If we were able to choose a best candidate, we're done.
1688 : * Otherwise, ambiguous function call.
1689 : */
1690 6838 : if (!best_candidate)
1691 0 : return FUNCDETAIL_MULTIPLE;
1692 : }
1693 : }
1694 : }
1695 :
1696 384606 : if (best_candidate)
1697 : {
1698 : HeapTuple ftup;
1699 : Form_pg_proc pform;
1700 : FuncDetailCode result;
1701 :
1702 : /*
1703 : * If processing named args or expanding variadics or defaults, the
1704 : * "best candidate" might represent multiple equivalently good
1705 : * functions; treat this case as ambiguous.
1706 : */
1707 382732 : if (!OidIsValid(best_candidate->oid))
1708 30 : return FUNCDETAIL_MULTIPLE;
1709 :
1710 : /*
1711 : * We disallow VARIADIC with named arguments unless the last argument
1712 : * (the one with VARIADIC attached) actually matched the variadic
1713 : * parameter. This is mere pedantry, really, but some folks insisted.
1714 : */
1715 382702 : if (fargnames != NIL && !expand_variadic && nargs > 0 &&
1716 18 : best_candidate->argnumbers[nargs - 1] != nargs - 1)
1717 : {
1718 6 : *fgc_flags |= FGC_VARIADIC_FAIL;
1719 6 : return FUNCDETAIL_NOTFOUND;
1720 : }
1721 :
1722 382696 : *funcid = best_candidate->oid;
1723 382696 : *nvargs = best_candidate->nvargs;
1724 382696 : *true_typeids = best_candidate->args;
1725 :
1726 : /*
1727 : * If processing named args, return actual argument positions into
1728 : * NamedArgExpr nodes in the fargs list. This is a bit ugly but not
1729 : * worth the extra notation needed to do it differently.
1730 : */
1731 382696 : if (best_candidate->argnumbers != NULL)
1732 : {
1733 16146 : int i = 0;
1734 : ListCell *lc;
1735 :
1736 65596 : foreach(lc, fargs)
1737 : {
1738 49450 : NamedArgExpr *na = (NamedArgExpr *) lfirst(lc);
1739 :
1740 49450 : if (IsA(na, NamedArgExpr))
1741 46984 : na->argnumber = best_candidate->argnumbers[i];
1742 49450 : i++;
1743 : }
1744 : }
1745 :
1746 382696 : ftup = SearchSysCache1(PROCOID,
1747 : ObjectIdGetDatum(best_candidate->oid));
1748 382696 : if (!HeapTupleIsValid(ftup)) /* should not happen */
1749 0 : elog(ERROR, "cache lookup failed for function %u",
1750 : best_candidate->oid);
1751 382696 : pform = (Form_pg_proc) GETSTRUCT(ftup);
1752 382696 : *rettype = pform->prorettype;
1753 382696 : *retset = pform->proretset;
1754 382696 : *vatype = pform->provariadic;
1755 : /* fetch default args if caller wants 'em */
1756 382696 : if (argdefaults && best_candidate->ndargs > 0)
1757 : {
1758 : Datum proargdefaults;
1759 : char *str;
1760 : List *defaults;
1761 :
1762 : /* shouldn't happen, FuncnameGetCandidates messed up */
1763 13838 : if (best_candidate->ndargs > pform->pronargdefaults)
1764 0 : elog(ERROR, "not enough default arguments");
1765 :
1766 13838 : proargdefaults = SysCacheGetAttrNotNull(PROCOID, ftup,
1767 : Anum_pg_proc_proargdefaults);
1768 13838 : str = TextDatumGetCString(proargdefaults);
1769 13838 : defaults = castNode(List, stringToNode(str));
1770 13838 : pfree(str);
1771 :
1772 : /* Delete any unused defaults from the returned list */
1773 13838 : if (best_candidate->argnumbers != NULL)
1774 : {
1775 : /*
1776 : * This is a bit tricky in named notation, since the supplied
1777 : * arguments could replace any subset of the defaults. We
1778 : * work by making a bitmapset of the argnumbers of defaulted
1779 : * arguments, then scanning the defaults list and selecting
1780 : * the needed items. (This assumes that defaulted arguments
1781 : * should be supplied in their positional order.)
1782 : */
1783 : Bitmapset *defargnumbers;
1784 : int *firstdefarg;
1785 : List *newdefaults;
1786 : ListCell *lc;
1787 : int i;
1788 :
1789 7506 : defargnumbers = NULL;
1790 7506 : firstdefarg = &best_candidate->argnumbers[best_candidate->nargs - best_candidate->ndargs];
1791 22726 : for (i = 0; i < best_candidate->ndargs; i++)
1792 15220 : defargnumbers = bms_add_member(defargnumbers,
1793 15220 : firstdefarg[i]);
1794 7506 : newdefaults = NIL;
1795 7506 : i = best_candidate->nominalnargs - pform->pronargdefaults;
1796 42978 : foreach(lc, defaults)
1797 : {
1798 35472 : if (bms_is_member(i, defargnumbers))
1799 15220 : newdefaults = lappend(newdefaults, lfirst(lc));
1800 35472 : i++;
1801 : }
1802 : Assert(list_length(newdefaults) == best_candidate->ndargs);
1803 7506 : bms_free(defargnumbers);
1804 7506 : *argdefaults = newdefaults;
1805 : }
1806 : else
1807 : {
1808 : /*
1809 : * Defaults for positional notation are lots easier; just
1810 : * remove any unwanted ones from the front.
1811 : */
1812 : int ndelete;
1813 :
1814 6332 : ndelete = list_length(defaults) - best_candidate->ndargs;
1815 6332 : if (ndelete > 0)
1816 220 : defaults = list_delete_first_n(defaults, ndelete);
1817 6332 : *argdefaults = defaults;
1818 : }
1819 : }
1820 :
1821 382696 : switch (pform->prokind)
1822 : {
1823 48040 : case PROKIND_AGGREGATE:
1824 48040 : result = FUNCDETAIL_AGGREGATE;
1825 48040 : break;
1826 331796 : case PROKIND_FUNCTION:
1827 331796 : result = FUNCDETAIL_NORMAL;
1828 331796 : break;
1829 504 : case PROKIND_PROCEDURE:
1830 504 : result = FUNCDETAIL_PROCEDURE;
1831 504 : break;
1832 2356 : case PROKIND_WINDOW:
1833 2356 : result = FUNCDETAIL_WINDOWFUNC;
1834 2356 : break;
1835 0 : default:
1836 0 : elog(ERROR, "unrecognized prokind: %c", pform->prokind);
1837 : result = FUNCDETAIL_NORMAL; /* keep compiler quiet */
1838 : break;
1839 : }
1840 :
1841 382696 : ReleaseSysCache(ftup);
1842 382696 : return result;
1843 : }
1844 :
1845 1874 : return FUNCDETAIL_NOTFOUND;
1846 : }
1847 :
1848 :
1849 : /*
1850 : * unify_hypothetical_args()
1851 : *
1852 : * Ensure that each hypothetical direct argument of a hypothetical-set
1853 : * aggregate has the same type as the corresponding aggregated argument.
1854 : * Modify the expressions in the fargs list, if necessary, and update
1855 : * actual_arg_types[].
1856 : *
1857 : * If the agg declared its args non-ANY (even ANYELEMENT), we need only a
1858 : * sanity check that the declared types match; make_fn_arguments will coerce
1859 : * the actual arguments to match the declared ones. But if the declaration
1860 : * is ANY, nothing will happen in make_fn_arguments, so we need to fix any
1861 : * mismatch here. We use the same type resolution logic as UNION etc.
1862 : */
1863 : static void
1864 144 : unify_hypothetical_args(ParseState *pstate,
1865 : List *fargs,
1866 : int numAggregatedArgs,
1867 : Oid *actual_arg_types,
1868 : Oid *declared_arg_types)
1869 : {
1870 : int numDirectArgs,
1871 : numNonHypotheticalArgs;
1872 : int hargpos;
1873 :
1874 144 : numDirectArgs = list_length(fargs) - numAggregatedArgs;
1875 144 : numNonHypotheticalArgs = numDirectArgs - numAggregatedArgs;
1876 : /* safety check (should only trigger with a misdeclared agg) */
1877 144 : if (numNonHypotheticalArgs < 0)
1878 0 : elog(ERROR, "incorrect number of arguments to hypothetical-set aggregate");
1879 :
1880 : /* Check each hypothetical arg and corresponding aggregated arg */
1881 330 : for (hargpos = numNonHypotheticalArgs; hargpos < numDirectArgs; hargpos++)
1882 : {
1883 198 : int aargpos = numDirectArgs + (hargpos - numNonHypotheticalArgs);
1884 198 : ListCell *harg = list_nth_cell(fargs, hargpos);
1885 198 : ListCell *aarg = list_nth_cell(fargs, aargpos);
1886 : Oid commontype;
1887 : int32 commontypmod;
1888 :
1889 : /* A mismatch means AggregateCreate didn't check properly ... */
1890 198 : if (declared_arg_types[hargpos] != declared_arg_types[aargpos])
1891 0 : elog(ERROR, "hypothetical-set aggregate has inconsistent declared argument types");
1892 :
1893 : /* No need to unify if make_fn_arguments will coerce */
1894 198 : if (declared_arg_types[hargpos] != ANYOID)
1895 0 : continue;
1896 :
1897 : /*
1898 : * Select common type, giving preference to the aggregated argument's
1899 : * type (we'd rather coerce the direct argument once than coerce all
1900 : * the aggregated values).
1901 : */
1902 198 : commontype = select_common_type(pstate,
1903 198 : list_make2(lfirst(aarg), lfirst(harg)),
1904 : "WITHIN GROUP",
1905 : NULL);
1906 192 : commontypmod = select_common_typmod(pstate,
1907 192 : list_make2(lfirst(aarg), lfirst(harg)),
1908 : commontype);
1909 :
1910 : /*
1911 : * Perform the coercions. We don't need to worry about NamedArgExprs
1912 : * here because they aren't supported with aggregates.
1913 : */
1914 378 : lfirst(harg) = coerce_type(pstate,
1915 192 : (Node *) lfirst(harg),
1916 192 : actual_arg_types[hargpos],
1917 : commontype, commontypmod,
1918 : COERCION_IMPLICIT,
1919 : COERCE_IMPLICIT_CAST,
1920 : -1);
1921 186 : actual_arg_types[hargpos] = commontype;
1922 372 : lfirst(aarg) = coerce_type(pstate,
1923 186 : (Node *) lfirst(aarg),
1924 186 : actual_arg_types[aargpos],
1925 : commontype, commontypmod,
1926 : COERCION_IMPLICIT,
1927 : COERCE_IMPLICIT_CAST,
1928 : -1);
1929 186 : actual_arg_types[aargpos] = commontype;
1930 : }
1931 132 : }
1932 :
1933 :
1934 : /*
1935 : * make_fn_arguments()
1936 : *
1937 : * Given the actual argument expressions for a function, and the desired
1938 : * input types for the function, add any necessary typecasting to the
1939 : * expression tree. Caller should already have verified that casting is
1940 : * allowed.
1941 : *
1942 : * Caution: given argument list is modified in-place.
1943 : *
1944 : * As with coerce_type, pstate may be NULL if no special unknown-Param
1945 : * processing is wanted.
1946 : */
1947 : void
1948 1025926 : make_fn_arguments(ParseState *pstate,
1949 : List *fargs,
1950 : Oid *actual_arg_types,
1951 : Oid *declared_arg_types)
1952 : {
1953 : ListCell *current_fargs;
1954 1025926 : int i = 0;
1955 :
1956 2994888 : foreach(current_fargs, fargs)
1957 : {
1958 : /* types don't match? then force coercion using a function call... */
1959 1969038 : if (actual_arg_types[i] != declared_arg_types[i])
1960 : {
1961 598442 : Node *node = (Node *) lfirst(current_fargs);
1962 :
1963 : /*
1964 : * If arg is a NamedArgExpr, coerce its input expr instead --- we
1965 : * want the NamedArgExpr to stay at the top level of the list.
1966 : */
1967 598442 : if (IsA(node, NamedArgExpr))
1968 : {
1969 22538 : NamedArgExpr *na = (NamedArgExpr *) node;
1970 :
1971 22538 : node = coerce_type(pstate,
1972 22538 : (Node *) na->arg,
1973 22538 : actual_arg_types[i],
1974 22538 : declared_arg_types[i], -1,
1975 : COERCION_IMPLICIT,
1976 : COERCE_IMPLICIT_CAST,
1977 : -1);
1978 22538 : na->arg = (Expr *) node;
1979 : }
1980 : else
1981 : {
1982 575904 : node = coerce_type(pstate,
1983 : node,
1984 575904 : actual_arg_types[i],
1985 575904 : declared_arg_types[i], -1,
1986 : COERCION_IMPLICIT,
1987 : COERCE_IMPLICIT_CAST,
1988 : -1);
1989 575828 : lfirst(current_fargs) = node;
1990 : }
1991 : }
1992 1968962 : i++;
1993 : }
1994 1025850 : }
1995 :
1996 : /*
1997 : * FuncNameAsType -
1998 : * convenience routine to see if a function name matches a type name
1999 : *
2000 : * Returns the OID of the matching type, or InvalidOid if none. We ignore
2001 : * shell types and complex types.
2002 : */
2003 : static Oid
2004 63068 : FuncNameAsType(List *funcname)
2005 : {
2006 : Oid result;
2007 : Type typtup;
2008 :
2009 : /*
2010 : * temp_ok=false protects the <refsect1 id="sql-createfunction-security">
2011 : * contract for writing SECURITY DEFINER functions safely.
2012 : */
2013 63068 : typtup = LookupTypeNameExtended(NULL, makeTypeNameFromNameList(funcname),
2014 : NULL, false, false);
2015 63068 : if (typtup == NULL)
2016 62242 : return InvalidOid;
2017 :
2018 1652 : if (((Form_pg_type) GETSTRUCT(typtup))->typisdefined &&
2019 826 : !OidIsValid(typeTypeRelid(typtup)))
2020 814 : result = typeTypeId(typtup);
2021 : else
2022 12 : result = InvalidOid;
2023 :
2024 826 : ReleaseSysCache(typtup);
2025 826 : return result;
2026 : }
2027 :
2028 : /*
2029 : * ParseComplexProjection -
2030 : * handles function calls with a single argument that is of complex type.
2031 : * If the function call is actually a column projection, return a suitably
2032 : * transformed expression tree. If not, return NULL.
2033 : */
2034 : static Node *
2035 11728 : ParseComplexProjection(ParseState *pstate, const char *funcname, Node *first_arg,
2036 : int location)
2037 : {
2038 : TupleDesc tupdesc;
2039 : int i;
2040 :
2041 : /*
2042 : * Special case for whole-row Vars so that we can resolve (foo.*).bar even
2043 : * when foo is a reference to a subselect, join, or RECORD function. A
2044 : * bonus is that we avoid generating an unnecessary FieldSelect; our
2045 : * result can omit the whole-row Var and just be a Var for the selected
2046 : * field.
2047 : *
2048 : * This case could be handled by expandRecordVariable, but it's more
2049 : * efficient to do it this way when possible.
2050 : */
2051 11728 : if (IsA(first_arg, Var) &&
2052 9414 : ((Var *) first_arg)->varattno == InvalidAttrNumber)
2053 : {
2054 : ParseNamespaceItem *nsitem;
2055 :
2056 180 : nsitem = GetNSItemByRangeTablePosn(pstate,
2057 : ((Var *) first_arg)->varno,
2058 180 : ((Var *) first_arg)->varlevelsup);
2059 : /* Return a Var if funcname matches a column, else NULL */
2060 180 : return scanNSItemForColumn(pstate, nsitem,
2061 180 : ((Var *) first_arg)->varlevelsup,
2062 : funcname, location);
2063 : }
2064 :
2065 : /*
2066 : * Else do it the hard way with get_expr_result_tupdesc().
2067 : *
2068 : * If it's a Var of type RECORD, we have to work even harder: we have to
2069 : * find what the Var refers to, and pass that to get_expr_result_tupdesc.
2070 : * That task is handled by expandRecordVariable().
2071 : */
2072 11548 : if (IsA(first_arg, Var) &&
2073 9234 : ((Var *) first_arg)->vartype == RECORDOID)
2074 1938 : tupdesc = expandRecordVariable(pstate, (Var *) first_arg, 0);
2075 : else
2076 9610 : tupdesc = get_expr_result_tupdesc(first_arg, true);
2077 11548 : if (!tupdesc)
2078 2 : return NULL; /* unresolvable RECORD type */
2079 :
2080 133250 : for (i = 0; i < tupdesc->natts; i++)
2081 : {
2082 133190 : Form_pg_attribute att = TupleDescAttr(tupdesc, i);
2083 :
2084 133190 : if (strcmp(funcname, NameStr(att->attname)) == 0 &&
2085 11486 : !att->attisdropped)
2086 : {
2087 : /* Success, so generate a FieldSelect expression */
2088 11486 : FieldSelect *fselect = makeNode(FieldSelect);
2089 :
2090 11486 : fselect->arg = (Expr *) first_arg;
2091 11486 : fselect->fieldnum = i + 1;
2092 11486 : fselect->resulttype = att->atttypid;
2093 11486 : fselect->resulttypmod = att->atttypmod;
2094 : /* save attribute's collation for parse_collate.c */
2095 11486 : fselect->resultcollid = att->attcollation;
2096 11486 : return (Node *) fselect;
2097 : }
2098 : }
2099 :
2100 60 : return NULL; /* funcname does not match any column */
2101 : }
2102 :
2103 : /*
2104 : * funcname_signature_string
2105 : * Build a string representing a function name, including arg types.
2106 : * The result is something like "foo(integer)".
2107 : *
2108 : * If argnames isn't NIL, it is a list of C strings representing the actual
2109 : * arg names for the last N arguments. This must be considered part of the
2110 : * function signature too, when dealing with named-notation function calls.
2111 : *
2112 : * This is typically used in the construction of function-not-found error
2113 : * messages.
2114 : */
2115 : const char *
2116 828 : funcname_signature_string(const char *funcname, int nargs,
2117 : List *argnames, const Oid *argtypes)
2118 : {
2119 : StringInfoData argbuf;
2120 : int numposargs;
2121 : ListCell *lc;
2122 : int i;
2123 :
2124 828 : initStringInfo(&argbuf);
2125 :
2126 828 : appendStringInfo(&argbuf, "%s(", funcname);
2127 :
2128 828 : numposargs = nargs - list_length(argnames);
2129 828 : lc = list_head(argnames);
2130 :
2131 2106 : for (i = 0; i < nargs; i++)
2132 : {
2133 1278 : if (i)
2134 580 : appendStringInfoString(&argbuf, ", ");
2135 1278 : if (i >= numposargs)
2136 : {
2137 108 : appendStringInfo(&argbuf, "%s => ", (char *) lfirst(lc));
2138 108 : lc = lnext(argnames, lc);
2139 : }
2140 1278 : appendStringInfoString(&argbuf, format_type_be(argtypes[i]));
2141 : }
2142 :
2143 828 : appendStringInfoChar(&argbuf, ')');
2144 :
2145 828 : return argbuf.data; /* return palloc'd string buffer */
2146 : }
2147 :
2148 : /*
2149 : * func_signature_string
2150 : * As above, but function name is passed as a qualified name list.
2151 : */
2152 : const char *
2153 804 : func_signature_string(List *funcname, int nargs,
2154 : List *argnames, const Oid *argtypes)
2155 : {
2156 804 : return funcname_signature_string(NameListToString(funcname),
2157 : nargs, argnames, argtypes);
2158 : }
2159 :
2160 : /*
2161 : * LookupFuncNameInternal
2162 : * Workhorse for LookupFuncName/LookupFuncWithArgs
2163 : *
2164 : * In an error situation, e.g. can't find the function, then we return
2165 : * InvalidOid and set *lookupError to indicate what went wrong.
2166 : *
2167 : * Possible errors:
2168 : * FUNCLOOKUP_NOSUCHFUNC: we can't find a function of this name.
2169 : * FUNCLOOKUP_AMBIGUOUS: more than one function matches.
2170 : */
2171 : static Oid
2172 43258 : LookupFuncNameInternal(ObjectType objtype, List *funcname,
2173 : int nargs, const Oid *argtypes,
2174 : bool include_out_arguments, bool missing_ok,
2175 : FuncLookupError *lookupError)
2176 : {
2177 43258 : Oid result = InvalidOid;
2178 : FuncCandidateList clist;
2179 : int fgc_flags;
2180 :
2181 : /* NULL argtypes allowed for nullary functions only */
2182 : Assert(argtypes != NULL || nargs == 0);
2183 :
2184 : /* Always set *lookupError, to forestall uninitialized-variable warnings */
2185 43258 : *lookupError = FUNCLOOKUP_NOSUCHFUNC;
2186 :
2187 : /* Get list of candidate objects */
2188 43258 : clist = FuncnameGetCandidates(funcname, nargs, NIL, false, false,
2189 : include_out_arguments, missing_ok,
2190 : &fgc_flags);
2191 :
2192 : /* Scan list for a match to the arg types (if specified) and the objtype */
2193 94106 : for (; clist != NULL; clist = clist->next)
2194 : {
2195 : /* Check arg type match, if specified */
2196 50932 : if (nargs >= 0)
2197 : {
2198 : /* if nargs==0, argtypes can be null; don't pass that to memcmp */
2199 50498 : if (nargs > 0 &&
2200 28456 : memcmp(argtypes, clist->args, nargs * sizeof(Oid)) != 0)
2201 9684 : continue;
2202 : }
2203 :
2204 : /* Check for duplicates reported by FuncnameGetCandidates */
2205 41248 : if (!OidIsValid(clist->oid))
2206 : {
2207 6 : *lookupError = FUNCLOOKUP_AMBIGUOUS;
2208 6 : return InvalidOid;
2209 : }
2210 :
2211 : /* Check objtype match, if specified */
2212 41242 : switch (objtype)
2213 : {
2214 22670 : case OBJECT_FUNCTION:
2215 : case OBJECT_AGGREGATE:
2216 : /* Ignore procedures */
2217 22670 : if (get_func_prokind(clist->oid) == PROKIND_PROCEDURE)
2218 0 : continue;
2219 22670 : break;
2220 186 : case OBJECT_PROCEDURE:
2221 : /* Ignore non-procedures */
2222 186 : if (get_func_prokind(clist->oid) != PROKIND_PROCEDURE)
2223 12 : continue;
2224 174 : break;
2225 18386 : case OBJECT_ROUTINE:
2226 : /* no restriction */
2227 18386 : break;
2228 41230 : default:
2229 : Assert(false);
2230 : }
2231 :
2232 : /* Check for multiple matches */
2233 41230 : if (OidIsValid(result))
2234 : {
2235 42 : *lookupError = FUNCLOOKUP_AMBIGUOUS;
2236 42 : return InvalidOid;
2237 : }
2238 :
2239 : /* OK, we have a candidate */
2240 41188 : result = clist->oid;
2241 : }
2242 :
2243 43174 : return result;
2244 : }
2245 :
2246 : /*
2247 : * LookupFuncName
2248 : *
2249 : * Given a possibly-qualified function name and optionally a set of argument
2250 : * types, look up the function. Pass nargs == -1 to indicate that the number
2251 : * and types of the arguments are unspecified (this is NOT the same as
2252 : * specifying that there are no arguments).
2253 : *
2254 : * If the function name is not schema-qualified, it is sought in the current
2255 : * namespace search path.
2256 : *
2257 : * If the function is not found, we return InvalidOid if missing_ok is true,
2258 : * else raise an error.
2259 : *
2260 : * If nargs == -1 and multiple functions are found matching this function name
2261 : * we will raise an ambiguous-function error, regardless of what missing_ok is
2262 : * set to.
2263 : *
2264 : * Only functions will be found; procedures will be ignored even if they
2265 : * match the name and argument types. (However, we don't trouble to reject
2266 : * aggregates or window functions here.)
2267 : */
2268 : Oid
2269 24128 : LookupFuncName(List *funcname, int nargs, const Oid *argtypes, bool missing_ok)
2270 : {
2271 : Oid funcoid;
2272 : FuncLookupError lookupError;
2273 :
2274 24128 : funcoid = LookupFuncNameInternal(OBJECT_FUNCTION,
2275 : funcname, nargs, argtypes,
2276 : false, missing_ok,
2277 : &lookupError);
2278 :
2279 24128 : if (OidIsValid(funcoid))
2280 22350 : return funcoid;
2281 :
2282 1778 : switch (lookupError)
2283 : {
2284 1778 : case FUNCLOOKUP_NOSUCHFUNC:
2285 : /* Let the caller deal with it when missing_ok is true */
2286 1778 : if (missing_ok)
2287 1738 : return InvalidOid;
2288 :
2289 40 : if (nargs < 0)
2290 0 : ereport(ERROR,
2291 : (errcode(ERRCODE_UNDEFINED_FUNCTION),
2292 : errmsg("could not find a function named \"%s\"",
2293 : NameListToString(funcname))));
2294 : else
2295 40 : ereport(ERROR,
2296 : (errcode(ERRCODE_UNDEFINED_FUNCTION),
2297 : errmsg("function %s does not exist",
2298 : func_signature_string(funcname, nargs,
2299 : NIL, argtypes))));
2300 : break;
2301 :
2302 0 : case FUNCLOOKUP_AMBIGUOUS:
2303 : /* Raise an error regardless of missing_ok */
2304 0 : ereport(ERROR,
2305 : (errcode(ERRCODE_AMBIGUOUS_FUNCTION),
2306 : errmsg("function name \"%s\" is not unique",
2307 : NameListToString(funcname)),
2308 : errhint("Specify the argument list to select the function unambiguously.")));
2309 : break;
2310 : }
2311 :
2312 0 : return InvalidOid; /* Keep compiler quiet */
2313 : }
2314 :
2315 : /*
2316 : * LookupFuncWithArgs
2317 : *
2318 : * Like LookupFuncName, but the argument types are specified by an
2319 : * ObjectWithArgs node. Also, this function can check whether the result is a
2320 : * function, procedure, or aggregate, based on the objtype argument. Pass
2321 : * OBJECT_ROUTINE to accept any of them.
2322 : *
2323 : * For historical reasons, we also accept aggregates when looking for a
2324 : * function.
2325 : *
2326 : * When missing_ok is true we don't generate any error for missing objects and
2327 : * return InvalidOid. Other types of errors can still be raised, regardless
2328 : * of the value of missing_ok.
2329 : */
2330 : Oid
2331 19040 : LookupFuncWithArgs(ObjectType objtype, ObjectWithArgs *func, bool missing_ok)
2332 : {
2333 : Oid argoids[FUNC_MAX_ARGS];
2334 : int argcount;
2335 : int nargs;
2336 : int i;
2337 : ListCell *args_item;
2338 : Oid oid;
2339 : FuncLookupError lookupError;
2340 :
2341 : Assert(objtype == OBJECT_AGGREGATE ||
2342 : objtype == OBJECT_FUNCTION ||
2343 : objtype == OBJECT_PROCEDURE ||
2344 : objtype == OBJECT_ROUTINE);
2345 :
2346 19040 : argcount = list_length(func->objargs);
2347 19040 : if (argcount > FUNC_MAX_ARGS)
2348 : {
2349 0 : if (objtype == OBJECT_PROCEDURE)
2350 0 : ereport(ERROR,
2351 : (errcode(ERRCODE_TOO_MANY_ARGUMENTS),
2352 : errmsg_plural("procedures cannot have more than %d argument",
2353 : "procedures cannot have more than %d arguments",
2354 : FUNC_MAX_ARGS,
2355 : FUNC_MAX_ARGS)));
2356 : else
2357 0 : ereport(ERROR,
2358 : (errcode(ERRCODE_TOO_MANY_ARGUMENTS),
2359 : errmsg_plural("functions cannot have more than %d argument",
2360 : "functions cannot have more than %d arguments",
2361 : FUNC_MAX_ARGS,
2362 : FUNC_MAX_ARGS)));
2363 : }
2364 :
2365 : /*
2366 : * First, perform a lookup considering only input arguments (traditional
2367 : * Postgres rules).
2368 : */
2369 19040 : i = 0;
2370 42936 : foreach(args_item, func->objargs)
2371 : {
2372 23926 : TypeName *t = lfirst_node(TypeName, args_item);
2373 :
2374 23926 : argoids[i] = LookupTypeNameOid(NULL, t, missing_ok);
2375 23920 : if (!OidIsValid(argoids[i]))
2376 24 : return InvalidOid; /* missing_ok must be true */
2377 23896 : i++;
2378 : }
2379 :
2380 : /*
2381 : * Set nargs for LookupFuncNameInternal. It expects -1 to mean no args
2382 : * were specified.
2383 : */
2384 19010 : nargs = func->args_unspecified ? -1 : argcount;
2385 :
2386 : /*
2387 : * In args_unspecified mode, also tell LookupFuncNameInternal to consider
2388 : * the object type, since there seems no reason not to. However, if we
2389 : * have an argument list, disable the objtype check, because we'd rather
2390 : * complain about "object is of wrong type" than "object doesn't exist".
2391 : * (Note that with args, FuncnameGetCandidates will have ensured there's
2392 : * only one argtype match, so we're not risking an ambiguity failure via
2393 : * this choice.)
2394 : */
2395 19010 : oid = LookupFuncNameInternal(func->args_unspecified ? objtype : OBJECT_ROUTINE,
2396 : func->objname, nargs, argoids,
2397 : false, missing_ok,
2398 : &lookupError);
2399 :
2400 : /*
2401 : * If PROCEDURE or ROUTINE was specified, and we have an argument list
2402 : * that contains no parameter mode markers, and we didn't already discover
2403 : * that there's ambiguity, perform a lookup considering all arguments.
2404 : * (Note: for a zero-argument procedure, or in args_unspecified mode, the
2405 : * normal lookup is sufficient; so it's OK to require non-NIL objfuncargs
2406 : * to perform this lookup.)
2407 : */
2408 18974 : if ((objtype == OBJECT_PROCEDURE || objtype == OBJECT_ROUTINE) &&
2409 324 : func->objfuncargs != NIL &&
2410 156 : lookupError != FUNCLOOKUP_AMBIGUOUS)
2411 : {
2412 156 : bool have_param_mode = false;
2413 :
2414 : /*
2415 : * Check for non-default parameter mode markers. If there are any,
2416 : * then the command does not conform to SQL-spec syntax, so we may
2417 : * assume that the traditional Postgres lookup method of considering
2418 : * only input parameters is sufficient. (Note that because the spec
2419 : * doesn't have OUT arguments for functions, we also don't need this
2420 : * hack in FUNCTION or AGGREGATE mode.)
2421 : */
2422 320 : foreach(args_item, func->objfuncargs)
2423 : {
2424 200 : FunctionParameter *fp = lfirst_node(FunctionParameter, args_item);
2425 :
2426 200 : if (fp->mode != FUNC_PARAM_DEFAULT)
2427 : {
2428 36 : have_param_mode = true;
2429 36 : break;
2430 : }
2431 : }
2432 :
2433 156 : if (!have_param_mode)
2434 : {
2435 : Oid poid;
2436 :
2437 : /* Without mode marks, objargs surely includes all params */
2438 : Assert(list_length(func->objfuncargs) == argcount);
2439 :
2440 : /* For objtype == OBJECT_PROCEDURE, we can ignore non-procedures */
2441 120 : poid = LookupFuncNameInternal(objtype, func->objname,
2442 : argcount, argoids,
2443 : true, missing_ok,
2444 : &lookupError);
2445 :
2446 : /* Combine results, handling ambiguity */
2447 120 : if (OidIsValid(poid))
2448 : {
2449 102 : if (OidIsValid(oid) && oid != poid)
2450 : {
2451 : /* oops, we got hits both ways, on different objects */
2452 0 : oid = InvalidOid;
2453 0 : lookupError = FUNCLOOKUP_AMBIGUOUS;
2454 : }
2455 : else
2456 102 : oid = poid;
2457 : }
2458 18 : else if (lookupError == FUNCLOOKUP_AMBIGUOUS)
2459 6 : oid = InvalidOid;
2460 : }
2461 : }
2462 :
2463 18974 : if (OidIsValid(oid))
2464 : {
2465 : /*
2466 : * Even if we found the function, perform validation that the objtype
2467 : * matches the prokind of the found function. For historical reasons
2468 : * we allow the objtype of FUNCTION to include aggregates and window
2469 : * functions; but we draw the line if the object is a procedure. That
2470 : * is a new enough feature that this historical rule does not apply.
2471 : *
2472 : * (This check is partially redundant with the objtype check in
2473 : * LookupFuncNameInternal; but not entirely, since we often don't tell
2474 : * LookupFuncNameInternal to apply that check at all.)
2475 : */
2476 18696 : switch (objtype)
2477 : {
2478 18128 : case OBJECT_FUNCTION:
2479 : /* Only complain if it's a procedure. */
2480 18128 : if (get_func_prokind(oid) == PROKIND_PROCEDURE)
2481 18 : ereport(ERROR,
2482 : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2483 : errmsg("%s is not a function",
2484 : func_signature_string(func->objname, argcount,
2485 : NIL, argoids))));
2486 18110 : break;
2487 :
2488 216 : case OBJECT_PROCEDURE:
2489 : /* Reject if found object is not a procedure. */
2490 216 : if (get_func_prokind(oid) != PROKIND_PROCEDURE)
2491 12 : ereport(ERROR,
2492 : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2493 : errmsg("%s is not a procedure",
2494 : func_signature_string(func->objname, argcount,
2495 : NIL, argoids))));
2496 204 : break;
2497 :
2498 310 : case OBJECT_AGGREGATE:
2499 : /* Reject if found object is not an aggregate. */
2500 310 : if (get_func_prokind(oid) != PROKIND_AGGREGATE)
2501 18 : ereport(ERROR,
2502 : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2503 : errmsg("function %s is not an aggregate",
2504 : func_signature_string(func->objname, argcount,
2505 : NIL, argoids))));
2506 292 : break;
2507 :
2508 42 : default:
2509 : /* OBJECT_ROUTINE accepts anything. */
2510 42 : break;
2511 : }
2512 :
2513 18648 : return oid; /* All good */
2514 : }
2515 : else
2516 : {
2517 : /* Deal with cases where the lookup failed */
2518 278 : switch (lookupError)
2519 : {
2520 230 : case FUNCLOOKUP_NOSUCHFUNC:
2521 : /* Suppress no-such-func errors when missing_ok is true */
2522 230 : if (missing_ok)
2523 52 : break;
2524 :
2525 : switch (objtype)
2526 : {
2527 36 : case OBJECT_PROCEDURE:
2528 36 : if (func->args_unspecified)
2529 0 : ereport(ERROR,
2530 : (errcode(ERRCODE_UNDEFINED_FUNCTION),
2531 : errmsg("could not find a procedure named \"%s\"",
2532 : NameListToString(func->objname))));
2533 : else
2534 36 : ereport(ERROR,
2535 : (errcode(ERRCODE_UNDEFINED_FUNCTION),
2536 : errmsg("procedure %s does not exist",
2537 : func_signature_string(func->objname, argcount,
2538 : NIL, argoids))));
2539 : break;
2540 :
2541 60 : case OBJECT_AGGREGATE:
2542 60 : if (func->args_unspecified)
2543 0 : ereport(ERROR,
2544 : (errcode(ERRCODE_UNDEFINED_FUNCTION),
2545 : errmsg("could not find an aggregate named \"%s\"",
2546 : NameListToString(func->objname))));
2547 60 : else if (argcount == 0)
2548 24 : ereport(ERROR,
2549 : (errcode(ERRCODE_UNDEFINED_FUNCTION),
2550 : errmsg("aggregate %s(*) does not exist",
2551 : NameListToString(func->objname))));
2552 : else
2553 36 : ereport(ERROR,
2554 : (errcode(ERRCODE_UNDEFINED_FUNCTION),
2555 : errmsg("aggregate %s does not exist",
2556 : func_signature_string(func->objname, argcount,
2557 : NIL, argoids))));
2558 : break;
2559 :
2560 82 : default:
2561 : /* FUNCTION and ROUTINE */
2562 82 : if (func->args_unspecified)
2563 6 : ereport(ERROR,
2564 : (errcode(ERRCODE_UNDEFINED_FUNCTION),
2565 : errmsg("could not find a function named \"%s\"",
2566 : NameListToString(func->objname))));
2567 : else
2568 76 : ereport(ERROR,
2569 : (errcode(ERRCODE_UNDEFINED_FUNCTION),
2570 : errmsg("function %s does not exist",
2571 : func_signature_string(func->objname, argcount,
2572 : NIL, argoids))));
2573 : break;
2574 : }
2575 : break;
2576 :
2577 48 : case FUNCLOOKUP_AMBIGUOUS:
2578 : switch (objtype)
2579 : {
2580 18 : case OBJECT_FUNCTION:
2581 18 : ereport(ERROR,
2582 : (errcode(ERRCODE_AMBIGUOUS_FUNCTION),
2583 : errmsg("function name \"%s\" is not unique",
2584 : NameListToString(func->objname)),
2585 : func->args_unspecified ?
2586 : errhint("Specify the argument list to select the function unambiguously.") : 0));
2587 : break;
2588 24 : case OBJECT_PROCEDURE:
2589 24 : ereport(ERROR,
2590 : (errcode(ERRCODE_AMBIGUOUS_FUNCTION),
2591 : errmsg("procedure name \"%s\" is not unique",
2592 : NameListToString(func->objname)),
2593 : func->args_unspecified ?
2594 : errhint("Specify the argument list to select the procedure unambiguously.") : 0));
2595 : break;
2596 0 : case OBJECT_AGGREGATE:
2597 0 : ereport(ERROR,
2598 : (errcode(ERRCODE_AMBIGUOUS_FUNCTION),
2599 : errmsg("aggregate name \"%s\" is not unique",
2600 : NameListToString(func->objname)),
2601 : func->args_unspecified ?
2602 : errhint("Specify the argument list to select the aggregate unambiguously.") : 0));
2603 : break;
2604 6 : case OBJECT_ROUTINE:
2605 6 : ereport(ERROR,
2606 : (errcode(ERRCODE_AMBIGUOUS_FUNCTION),
2607 : errmsg("routine name \"%s\" is not unique",
2608 : NameListToString(func->objname)),
2609 : func->args_unspecified ?
2610 : errhint("Specify the argument list to select the routine unambiguously.") : 0));
2611 : break;
2612 :
2613 0 : default:
2614 : Assert(false); /* Disallowed by Assert above */
2615 0 : break;
2616 : }
2617 0 : break;
2618 : }
2619 :
2620 52 : return InvalidOid;
2621 : }
2622 : }
2623 :
2624 : /*
2625 : * check_srf_call_placement
2626 : * Verify that a set-returning function is called in a valid place,
2627 : * and throw a nice error if not.
2628 : *
2629 : * A side-effect is to set pstate->p_hasTargetSRFs true if appropriate.
2630 : *
2631 : * last_srf should be a copy of pstate->p_last_srf from just before we
2632 : * started transforming the function's arguments. This allows detection
2633 : * of whether the SRF's arguments contain any SRFs.
2634 : */
2635 : void
2636 53152 : check_srf_call_placement(ParseState *pstate, Node *last_srf, int location)
2637 : {
2638 : const char *err;
2639 : bool errkind;
2640 :
2641 : /*
2642 : * Check to see if the set-returning function is in an invalid place
2643 : * within the query. Basically, we don't allow SRFs anywhere except in
2644 : * the targetlist (which includes GROUP BY/ORDER BY expressions), VALUES,
2645 : * and functions in FROM.
2646 : *
2647 : * For brevity we support two schemes for reporting an error here: set
2648 : * "err" to a custom message, or set "errkind" true if the error context
2649 : * is sufficiently identified by what ParseExprKindName will return, *and*
2650 : * what it will return is just a SQL keyword. (Otherwise, use a custom
2651 : * message to avoid creating translation problems.)
2652 : */
2653 53152 : err = NULL;
2654 53152 : errkind = false;
2655 53152 : switch (pstate->p_expr_kind)
2656 : {
2657 0 : case EXPR_KIND_NONE:
2658 : Assert(false); /* can't happen */
2659 0 : break;
2660 0 : case EXPR_KIND_OTHER:
2661 : /* Accept SRF here; caller must throw error if wanted */
2662 0 : break;
2663 0 : case EXPR_KIND_JOIN_ON:
2664 : case EXPR_KIND_JOIN_USING:
2665 0 : err = _("set-returning functions are not allowed in JOIN conditions");
2666 0 : break;
2667 0 : case EXPR_KIND_FROM_SUBSELECT:
2668 : /* can't get here, but just in case, throw an error */
2669 0 : errkind = true;
2670 0 : break;
2671 38934 : case EXPR_KIND_FROM_FUNCTION:
2672 : /* okay, but we don't allow nested SRFs here */
2673 : /* errmsg is chosen to match transformRangeFunction() */
2674 : /* errposition should point to the inner SRF */
2675 38934 : if (pstate->p_last_srf != last_srf)
2676 6 : ereport(ERROR,
2677 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2678 : errmsg("set-returning functions must appear at top level of FROM"),
2679 : parser_errposition(pstate,
2680 : exprLocation(pstate->p_last_srf))));
2681 38928 : break;
2682 0 : case EXPR_KIND_WHERE:
2683 0 : errkind = true;
2684 0 : break;
2685 0 : case EXPR_KIND_POLICY:
2686 0 : err = _("set-returning functions are not allowed in policy expressions");
2687 0 : break;
2688 0 : case EXPR_KIND_HAVING:
2689 0 : errkind = true;
2690 0 : break;
2691 0 : case EXPR_KIND_FILTER:
2692 0 : errkind = true;
2693 0 : break;
2694 12 : case EXPR_KIND_WINDOW_PARTITION:
2695 : case EXPR_KIND_WINDOW_ORDER:
2696 : /* okay, these are effectively GROUP BY/ORDER BY */
2697 12 : pstate->p_hasTargetSRFs = true;
2698 12 : break;
2699 0 : case EXPR_KIND_WINDOW_FRAME_RANGE:
2700 : case EXPR_KIND_WINDOW_FRAME_ROWS:
2701 : case EXPR_KIND_WINDOW_FRAME_GROUPS:
2702 0 : err = _("set-returning functions are not allowed in window definitions");
2703 0 : break;
2704 14016 : case EXPR_KIND_SELECT_TARGET:
2705 : case EXPR_KIND_INSERT_TARGET:
2706 : /* okay */
2707 14016 : pstate->p_hasTargetSRFs = true;
2708 14016 : break;
2709 6 : case EXPR_KIND_UPDATE_SOURCE:
2710 : case EXPR_KIND_UPDATE_TARGET:
2711 : /* disallowed because it would be ambiguous what to do */
2712 6 : errkind = true;
2713 6 : break;
2714 36 : case EXPR_KIND_GROUP_BY:
2715 : case EXPR_KIND_ORDER_BY:
2716 : /* okay */
2717 36 : pstate->p_hasTargetSRFs = true;
2718 36 : break;
2719 0 : case EXPR_KIND_DISTINCT_ON:
2720 : /* okay */
2721 0 : pstate->p_hasTargetSRFs = true;
2722 0 : break;
2723 6 : case EXPR_KIND_LIMIT:
2724 : case EXPR_KIND_OFFSET:
2725 6 : errkind = true;
2726 6 : break;
2727 6 : case EXPR_KIND_RETURNING:
2728 : case EXPR_KIND_MERGE_RETURNING:
2729 6 : errkind = true;
2730 6 : break;
2731 6 : case EXPR_KIND_VALUES:
2732 : /* SRFs are presently not supported by nodeValuesscan.c */
2733 6 : errkind = true;
2734 6 : break;
2735 88 : case EXPR_KIND_VALUES_SINGLE:
2736 : /* okay, since we process this like a SELECT tlist */
2737 88 : pstate->p_hasTargetSRFs = true;
2738 88 : break;
2739 0 : case EXPR_KIND_MERGE_WHEN:
2740 0 : err = _("set-returning functions are not allowed in MERGE WHEN conditions");
2741 0 : break;
2742 0 : case EXPR_KIND_CHECK_CONSTRAINT:
2743 : case EXPR_KIND_DOMAIN_CHECK:
2744 0 : err = _("set-returning functions are not allowed in check constraints");
2745 0 : break;
2746 6 : case EXPR_KIND_COLUMN_DEFAULT:
2747 : case EXPR_KIND_FUNCTION_DEFAULT:
2748 6 : err = _("set-returning functions are not allowed in DEFAULT expressions");
2749 6 : break;
2750 0 : case EXPR_KIND_INDEX_EXPRESSION:
2751 0 : err = _("set-returning functions are not allowed in index expressions");
2752 0 : break;
2753 0 : case EXPR_KIND_INDEX_PREDICATE:
2754 0 : err = _("set-returning functions are not allowed in index predicates");
2755 0 : break;
2756 0 : case EXPR_KIND_STATS_EXPRESSION:
2757 0 : err = _("set-returning functions are not allowed in statistics expressions");
2758 0 : break;
2759 0 : case EXPR_KIND_ALTER_COL_TRANSFORM:
2760 0 : err = _("set-returning functions are not allowed in transform expressions");
2761 0 : break;
2762 0 : case EXPR_KIND_EXECUTE_PARAMETER:
2763 0 : err = _("set-returning functions are not allowed in EXECUTE parameters");
2764 0 : break;
2765 0 : case EXPR_KIND_TRIGGER_WHEN:
2766 0 : err = _("set-returning functions are not allowed in trigger WHEN conditions");
2767 0 : break;
2768 12 : case EXPR_KIND_PARTITION_BOUND:
2769 12 : err = _("set-returning functions are not allowed in partition bound");
2770 12 : break;
2771 6 : case EXPR_KIND_PARTITION_EXPRESSION:
2772 6 : err = _("set-returning functions are not allowed in partition key expressions");
2773 6 : break;
2774 0 : case EXPR_KIND_CALL_ARGUMENT:
2775 0 : err = _("set-returning functions are not allowed in CALL arguments");
2776 0 : break;
2777 6 : case EXPR_KIND_COPY_WHERE:
2778 6 : err = _("set-returning functions are not allowed in COPY FROM WHERE conditions");
2779 6 : break;
2780 12 : case EXPR_KIND_GENERATED_COLUMN:
2781 12 : err = _("set-returning functions are not allowed in column generation expressions");
2782 12 : break;
2783 0 : case EXPR_KIND_CYCLE_MARK:
2784 0 : errkind = true;
2785 0 : break;
2786 :
2787 : /*
2788 : * There is intentionally no default: case here, so that the
2789 : * compiler will warn if we add a new ParseExprKind without
2790 : * extending this switch. If we do see an unrecognized value at
2791 : * runtime, the behavior will be the same as for EXPR_KIND_OTHER,
2792 : * which is sane anyway.
2793 : */
2794 : }
2795 53146 : if (err)
2796 42 : ereport(ERROR,
2797 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2798 : errmsg_internal("%s", err),
2799 : parser_errposition(pstate, location)));
2800 53104 : if (errkind)
2801 24 : ereport(ERROR,
2802 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2803 : /* translator: %s is name of a SQL construct, eg GROUP BY */
2804 : errmsg("set-returning functions are not allowed in %s",
2805 : ParseExprKindName(pstate->p_expr_kind)),
2806 : parser_errposition(pstate, location)));
2807 53080 : }
|