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