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