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