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