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