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