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 *
ParseFuncOrColumn(ParseState * pstate,List * funcname,List * fargs,Node * last_srf,FuncCall * fn,int location)73 ParseFuncOrColumn(ParseState *pstate, List *funcname, List *fargs,
74 				  Node *last_srf, FuncCall *fn, int location)
75 {
76 	bool		is_column = (fn == NULL);
77 	List	   *agg_order = (fn ? fn->agg_order : NIL);
78 	Expr	   *agg_filter = NULL;
79 	bool		agg_within_group = (fn ? fn->agg_within_group : false);
80 	bool		agg_star = (fn ? fn->agg_star : false);
81 	bool		agg_distinct = (fn ? fn->agg_distinct : false);
82 	bool		func_variadic = (fn ? fn->func_variadic : false);
83 	WindowDef  *over = (fn ? fn->over : NULL);
84 	Oid			rettype;
85 	Oid			funcid;
86 	ListCell   *l;
87 	ListCell   *nextl;
88 	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 	char		aggkind = 0;
101 	ParseCallbackState pcbstate;
102 
103 	/*
104 	 * If there's an aggregate filter, transform it using transformWhereClause
105 	 */
106 	if (fn && fn->agg_filter != NULL)
107 		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 	if (list_length(fargs) > FUNC_MAX_ARGS)
118 		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 	nargs = 0;
138 	for (l = list_head(fargs); l != NULL; l = nextl)
139 	{
140 		Node	   *arg = lfirst(l);
141 		Oid			argtype = exprType(arg);
142 
143 		nextl = lnext(l);
144 
145 		if (argtype == VOIDOID && IsA(arg, Param) &&
146 			!is_column && !agg_within_group)
147 		{
148 			fargs = list_delete_ptr(fargs, arg);
149 			continue;
150 		}
151 
152 		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 	argnames = NIL;
164 	foreach(l, fargs)
165 	{
166 		Node	   *arg = lfirst(l);
167 
168 		if (IsA(arg, NamedArgExpr))
169 		{
170 			NamedArgExpr *na = (NamedArgExpr *) arg;
171 			ListCell   *lc;
172 
173 			/* Reject duplicate arg names */
174 			foreach(lc, argnames)
175 			{
176 				if (strcmp(na->name, (char *) lfirst(lc)) == 0)
177 					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 			argnames = lappend(argnames, na->name);
184 		}
185 		else
186 		{
187 			if (argnames != NIL)
188 				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 	if (fargs)
196 	{
197 		first_arg = linitial(fargs);
198 		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 	if (nargs == 1 && agg_order == NIL && agg_filter == NULL && !agg_star &&
208 		!agg_distinct && over == NULL && !func_variadic && argnames == NIL &&
209 		list_length(funcname) == 1)
210 	{
211 		Oid			argtype = actual_arg_types[0];
212 
213 		if (argtype == RECORDOID || ISCOMPLEX(argtype))
214 		{
215 			retval = ParseComplexProjection(pstate,
216 											strVal(linitial(funcname)),
217 											first_arg,
218 											location);
219 			if (retval)
220 				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 	setup_parser_errposition_callback(&pcbstate, pstate, location);
246 
247 	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 	cancel_parser_errposition_callback(&pcbstate);
255 
256 	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 		return coerce_type(pstate, linitial(fargs),
263 						   actual_arg_types[0], rettype, -1,
264 						   COERCION_EXPLICIT, COERCE_EXPLICIT_CALL, location);
265 	}
266 	else if (fdresult == FUNCDETAIL_NORMAL)
267 	{
268 		/*
269 		 * Normal function found; was there anything indicating it must be an
270 		 * aggregate?
271 		 */
272 		if (agg_star)
273 			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 		if (agg_distinct)
280 			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 		if (agg_within_group)
286 			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 		if (agg_order != NIL)
292 			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 		if (agg_filter)
298 			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 		if (over)
304 			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 	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 		tup = SearchSysCache1(AGGFNOID, ObjectIdGetDatum(funcid));
320 		if (!HeapTupleIsValid(tup)) /* should not happen */
321 			elog(ERROR, "cache lookup failed for aggregate %u", funcid);
322 		classForm = (Form_pg_aggregate) GETSTRUCT(tup);
323 		aggkind = classForm->aggkind;
324 		catDirectArgs = classForm->aggnumdirectargs;
325 		ReleaseSysCache(tup);
326 
327 		/* Now check various disallowed cases. */
328 		if (AGGKIND_IS_ORDERED_SET(aggkind))
329 		{
330 			int			numAggregatedArgs;
331 			int			numDirectArgs;
332 
333 			if (!agg_within_group)
334 				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 			if (over)
340 				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 			Assert(!agg_distinct);
347 			/* gram.y rejects VARIADIC + WITHIN GROUP */
348 			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 			numAggregatedArgs = list_length(agg_order);
360 			numDirectArgs = nargs - numAggregatedArgs;
361 			Assert(numDirectArgs >= 0);
362 
363 			if (!OidIsValid(vatype))
364 			{
365 				/* Test is simple if aggregate isn't variadic */
366 				if (numDirectArgs != catDirectArgs)
367 					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 				pronargs = nargs;
390 				if (nvargs > 1)
391 					pronargs -= nvargs - 1;
392 				if (catDirectArgs < pronargs)
393 				{
394 					/* VARIADIC isn't part of direct args, so still easy */
395 					if (numDirectArgs != catDirectArgs)
396 						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 					if (aggkind == AGGKIND_HYPOTHETICAL)
419 					{
420 						if (nvargs != 2 * numAggregatedArgs)
421 							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 						if (nvargs <= numAggregatedArgs)
435 							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 			if (aggkind == AGGKIND_HYPOTHETICAL)
451 				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 			if (agg_within_group)
458 				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 	else if (fdresult == FUNCDETAIL_WINDOWFUNC)
466 	{
467 		/*
468 		 * True window functions must be called with a window definition.
469 		 */
470 		if (!over)
471 			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 		if (agg_within_group)
478 			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 		if (is_column)
493 			return NULL;
494 
495 		/*
496 		 * Else generate a detailed complaint for a function
497 		 */
498 		if (fdresult == FUNCDETAIL_MULTIPLE)
499 			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 		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 			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 			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 	nargsplusdefs = nargs;
539 	foreach(l, argdefaults)
540 	{
541 		Node	   *expr = (Node *) lfirst(l);
542 
543 		/* probably shouldn't happen ... */
544 		if (nargsplusdefs >= FUNC_MAX_ARGS)
545 			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 		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 	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 	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 	if (!OidIsValid(vatype))
576 	{
577 		Assert(nvargs == 0);
578 		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 	if (nvargs > 0 && vatype != ANYOID)
586 	{
587 		ArrayExpr  *newa = makeNode(ArrayExpr);
588 		int			non_var_args = nargs - nvargs;
589 		List	   *vargs;
590 
591 		Assert(non_var_args >= 0);
592 		vargs = list_copy_tail(fargs, non_var_args);
593 		fargs = list_truncate(fargs, non_var_args);
594 
595 		newa->elements = vargs;
596 		/* assume all the variadic arguments were coerced to the same type */
597 		newa->element_typeid = exprType((Node *) linitial(vargs));
598 		newa->array_typeid = get_array_type(newa->element_typeid);
599 		if (!OidIsValid(newa->array_typeid))
600 			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 		newa->multidims = false;
607 		newa->location = exprLocation((Node *) vargs);
608 
609 		fargs = lappend(fargs, newa);
610 
611 		/* We could not have had VARIADIC marking before ... */
612 		Assert(!func_variadic);
613 		/* ... but now, it's a VARIADIC call */
614 		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 	if (nargs > 0 && vatype == ANYOID && func_variadic)
622 	{
623 		Oid			va_arr_typid = actual_arg_types[nargs - 1];
624 
625 		if (!OidIsValid(get_base_element_type(va_arr_typid)))
626 			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 	if (retset)
635 		check_srf_call_placement(pstate, last_srf, location);
636 
637 	/* build the appropriate output structure */
638 	if (fdresult == FUNCDETAIL_NORMAL)
639 	{
640 		FuncExpr   *funcexpr = makeNode(FuncExpr);
641 
642 		funcexpr->funcid = funcid;
643 		funcexpr->funcresulttype = rettype;
644 		funcexpr->funcretset = retset;
645 		funcexpr->funcvariadic = func_variadic;
646 		funcexpr->funcformat = COERCE_EXPLICIT_CALL;
647 		/* funccollid and inputcollid will be set by parse_collate.c */
648 		funcexpr->args = fargs;
649 		funcexpr->location = location;
650 
651 		retval = (Node *) funcexpr;
652 	}
653 	else if (fdresult == FUNCDETAIL_AGGREGATE && !over)
654 	{
655 		/* aggregate function */
656 		Aggref	   *aggref = makeNode(Aggref);
657 
658 		aggref->aggfnoid = funcid;
659 		aggref->aggtype = rettype;
660 		/* aggcollid and inputcollid will be set by parse_collate.c */
661 		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 		aggref->aggfilter = agg_filter;
666 		aggref->aggstar = agg_star;
667 		aggref->aggvariadic = func_variadic;
668 		aggref->aggkind = aggkind;
669 		/* agglevelsup will be set by transformAggregateCall */
670 		aggref->aggsplit = AGGSPLIT_SIMPLE; /* planner might change this */
671 		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 		if (fargs == NIL && !agg_star && !agg_within_group)
678 			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 		if (retset)
685 			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 		if (argnames != NIL)
700 			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 		transformAggregateCall(pstate, aggref, fargs, agg_order, agg_distinct);
707 
708 		retval = (Node *) aggref;
709 	}
710 	else
711 	{
712 		/* window function */
713 		WindowFunc *wfunc = makeNode(WindowFunc);
714 
715 		Assert(over);			/* lack of this was checked above */
716 		Assert(!agg_within_group);	/* also checked above */
717 
718 		wfunc->winfnoid = funcid;
719 		wfunc->wintype = rettype;
720 		/* wincollid and inputcollid will be set by parse_collate.c */
721 		wfunc->args = fargs;
722 		/* winref will be set by transformWindowFuncCall */
723 		wfunc->winstar = agg_star;
724 		wfunc->winagg = (fdresult == FUNCDETAIL_AGGREGATE);
725 		wfunc->aggfilter = agg_filter;
726 		wfunc->location = location;
727 
728 		/*
729 		 * agg_star is allowed for aggregate functions but distinct isn't
730 		 */
731 		if (agg_distinct)
732 			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 		if (wfunc->winagg && fargs == NIL && !agg_star)
742 			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 		if (agg_order != NIL)
752 			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 		if (!wfunc->winagg && agg_filter)
761 			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 		if (pstate->p_last_srf != last_srf)
770 			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 		if (retset)
778 			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 		transformWindowFuncCall(pstate, wfunc, over);
785 
786 		retval = (Node *) wfunc;
787 	}
788 
789 	/* if it returns a set, remember it for error checks at higher levels */
790 	if (retset)
791 		pstate->p_last_srf = retval;
792 
793 	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
func_match_argtypes(int nargs,Oid * input_typeids,FuncCandidateList raw_candidates,FuncCandidateList * candidates)811 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 	int			ncandidates = 0;
819 
820 	*candidates = NULL;
821 
822 	for (current_candidate = raw_candidates;
823 		 current_candidate != NULL;
824 		 current_candidate = next_candidate)
825 	{
826 		next_candidate = current_candidate->next;
827 		if (can_coerce_type(nargs, input_typeids, current_candidate->args,
828 							COERCION_IMPLICIT))
829 		{
830 			current_candidate->next = *candidates;
831 			*candidates = current_candidate;
832 			ncandidates++;
833 		}
834 	}
835 
836 	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
func_select_candidate(int nargs,Oid * input_typeids,FuncCandidateList candidates)896 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 	if (nargs > FUNC_MAX_ARGS)
919 		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 	nunknowns = 0;
940 	for (i = 0; i < nargs; i++)
941 	{
942 		if (input_typeids[i] != UNKNOWNOID)
943 			input_base_typeids[i] = getBaseType(input_typeids[i]);
944 		else
945 		{
946 			/* no need to call getBaseType on UNKNOWNOID */
947 			input_base_typeids[i] = UNKNOWNOID;
948 			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 	ncandidates = 0;
957 	nbestMatch = 0;
958 	last_candidate = NULL;
959 	for (current_candidate = candidates;
960 		 current_candidate != NULL;
961 		 current_candidate = current_candidate->next)
962 	{
963 		current_typeids = current_candidate->args;
964 		nmatch = 0;
965 		for (i = 0; i < nargs; i++)
966 		{
967 			if (input_base_typeids[i] != UNKNOWNOID &&
968 				current_typeids[i] == input_base_typeids[i])
969 				nmatch++;
970 		}
971 
972 		/* take this one as the best choice so far? */
973 		if ((nmatch > nbestMatch) || (last_candidate == NULL))
974 		{
975 			nbestMatch = nmatch;
976 			candidates = current_candidate;
977 			last_candidate = current_candidate;
978 			ncandidates = 1;
979 		}
980 		/* no worse than the last choice, so keep this one too? */
981 		else if (nmatch == nbestMatch)
982 		{
983 			last_candidate->next = current_candidate;
984 			last_candidate = current_candidate;
985 			ncandidates++;
986 		}
987 		/* otherwise, don't bother keeping this one... */
988 	}
989 
990 	if (last_candidate)			/* terminate rebuilt list */
991 		last_candidate->next = NULL;
992 
993 	if (ncandidates == 1)
994 		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 	for (i = 0; i < nargs; i++) /* avoid multiple lookups */
1004 		slot_category[i] = TypeCategory(input_base_typeids[i]);
1005 	ncandidates = 0;
1006 	nbestMatch = 0;
1007 	last_candidate = NULL;
1008 	for (current_candidate = candidates;
1009 		 current_candidate != NULL;
1010 		 current_candidate = current_candidate->next)
1011 	{
1012 		current_typeids = current_candidate->args;
1013 		nmatch = 0;
1014 		for (i = 0; i < nargs; i++)
1015 		{
1016 			if (input_base_typeids[i] != UNKNOWNOID)
1017 			{
1018 				if (current_typeids[i] == input_base_typeids[i] ||
1019 					IsPreferredType(slot_category[i], current_typeids[i]))
1020 					nmatch++;
1021 			}
1022 		}
1023 
1024 		if ((nmatch > nbestMatch) || (last_candidate == NULL))
1025 		{
1026 			nbestMatch = nmatch;
1027 			candidates = current_candidate;
1028 			last_candidate = current_candidate;
1029 			ncandidates = 1;
1030 		}
1031 		else if (nmatch == nbestMatch)
1032 		{
1033 			last_candidate->next = current_candidate;
1034 			last_candidate = current_candidate;
1035 			ncandidates++;
1036 		}
1037 	}
1038 
1039 	if (last_candidate)			/* terminate rebuilt list */
1040 		last_candidate->next = NULL;
1041 
1042 	if (ncandidates == 1)
1043 		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 	if (nunknowns == 0)
1052 		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 	resolved_unknowns = false;
1074 	for (i = 0; i < nargs; i++)
1075 	{
1076 		bool		have_conflict;
1077 
1078 		if (input_base_typeids[i] != UNKNOWNOID)
1079 			continue;
1080 		resolved_unknowns = true;	/* assume we can do it */
1081 		slot_category[i] = TYPCATEGORY_INVALID;
1082 		slot_has_preferred_type[i] = false;
1083 		have_conflict = false;
1084 		for (current_candidate = candidates;
1085 			 current_candidate != NULL;
1086 			 current_candidate = current_candidate->next)
1087 		{
1088 			current_typeids = current_candidate->args;
1089 			current_type = current_typeids[i];
1090 			get_type_category_preferred(current_type,
1091 										&current_category,
1092 										&current_is_preferred);
1093 			if (slot_category[i] == TYPCATEGORY_INVALID)
1094 			{
1095 				/* first candidate */
1096 				slot_category[i] = current_category;
1097 				slot_has_preferred_type[i] = current_is_preferred;
1098 			}
1099 			else if (current_category == slot_category[i])
1100 			{
1101 				/* more candidates in same category */
1102 				slot_has_preferred_type[i] |= current_is_preferred;
1103 			}
1104 			else
1105 			{
1106 				/* category conflict! */
1107 				if (current_category == TYPCATEGORY_STRING)
1108 				{
1109 					/* STRING always wins if available */
1110 					slot_category[i] = current_category;
1111 					slot_has_preferred_type[i] = current_is_preferred;
1112 				}
1113 				else
1114 				{
1115 					/*
1116 					 * Remember conflict, but keep going (might find STRING)
1117 					 */
1118 					have_conflict = true;
1119 				}
1120 			}
1121 		}
1122 		if (have_conflict && slot_category[i] != TYPCATEGORY_STRING)
1123 		{
1124 			/* Failed to resolve category conflict at this position */
1125 			resolved_unknowns = false;
1126 			break;
1127 		}
1128 	}
1129 
1130 	if (resolved_unknowns)
1131 	{
1132 		/* Strip non-matching candidates */
1133 		ncandidates = 0;
1134 		first_candidate = candidates;
1135 		last_candidate = NULL;
1136 		for (current_candidate = candidates;
1137 			 current_candidate != NULL;
1138 			 current_candidate = current_candidate->next)
1139 		{
1140 			bool		keepit = true;
1141 
1142 			current_typeids = current_candidate->args;
1143 			for (i = 0; i < nargs; i++)
1144 			{
1145 				if (input_base_typeids[i] != UNKNOWNOID)
1146 					continue;
1147 				current_type = current_typeids[i];
1148 				get_type_category_preferred(current_type,
1149 											&current_category,
1150 											&current_is_preferred);
1151 				if (current_category != slot_category[i])
1152 				{
1153 					keepit = false;
1154 					break;
1155 				}
1156 				if (slot_has_preferred_type[i] && !current_is_preferred)
1157 				{
1158 					keepit = false;
1159 					break;
1160 				}
1161 			}
1162 			if (keepit)
1163 			{
1164 				/* keep this candidate */
1165 				last_candidate = current_candidate;
1166 				ncandidates++;
1167 			}
1168 			else
1169 			{
1170 				/* forget this candidate */
1171 				if (last_candidate)
1172 					last_candidate->next = current_candidate->next;
1173 				else
1174 					first_candidate = current_candidate->next;
1175 			}
1176 		}
1177 
1178 		/* if we found any matches, restrict our attention to those */
1179 		if (last_candidate)
1180 		{
1181 			candidates = first_candidate;
1182 			/* terminate rebuilt list */
1183 			last_candidate->next = NULL;
1184 		}
1185 
1186 		if (ncandidates == 1)
1187 			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 	if (nunknowns < nargs)
1201 	{
1202 		Oid			known_type = UNKNOWNOID;
1203 
1204 		for (i = 0; i < nargs; i++)
1205 		{
1206 			if (input_base_typeids[i] == UNKNOWNOID)
1207 				continue;
1208 			if (known_type == UNKNOWNOID)	/* first known arg? */
1209 				known_type = input_base_typeids[i];
1210 			else if (known_type != input_base_typeids[i])
1211 			{
1212 				/* oops, not all match */
1213 				known_type = UNKNOWNOID;
1214 				break;
1215 			}
1216 		}
1217 
1218 		if (known_type != UNKNOWNOID)
1219 		{
1220 			/* okay, just one known type, apply the heuristic */
1221 			for (i = 0; i < nargs; i++)
1222 				input_base_typeids[i] = known_type;
1223 			ncandidates = 0;
1224 			last_candidate = NULL;
1225 			for (current_candidate = candidates;
1226 				 current_candidate != NULL;
1227 				 current_candidate = current_candidate->next)
1228 			{
1229 				current_typeids = current_candidate->args;
1230 				if (can_coerce_type(nargs, input_base_typeids, current_typeids,
1231 									COERCION_IMPLICIT))
1232 				{
1233 					if (++ncandidates > 1)
1234 						break;	/* not unique, give up */
1235 					last_candidate = current_candidate;
1236 				}
1237 			}
1238 			if (ncandidates == 1)
1239 			{
1240 				/* successfully identified a unique match */
1241 				last_candidate->next = NULL;
1242 				return last_candidate;
1243 			}
1244 		}
1245 	}
1246 
1247 	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
func_get_detail(List * funcname,List * fargs,List * fargnames,int nargs,Oid * argtypes,bool expand_variadic,bool expand_defaults,Oid * funcid,Oid * rettype,bool * retset,int * nvargs,Oid * vatype,Oid ** true_typeids,List ** argdefaults)1283 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 	Assert(argtypes);
1303 
1304 	/* initialize output arguments to silence compiler warnings */
1305 	*funcid = InvalidOid;
1306 	*rettype = InvalidOid;
1307 	*retset = false;
1308 	*nvargs = 0;
1309 	*vatype = InvalidOid;
1310 	*true_typeids = NULL;
1311 	if (argdefaults)
1312 		*argdefaults = NIL;
1313 
1314 	/* Get list of possible candidates from namespace search */
1315 	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 	for (best_candidate = raw_candidates;
1324 		 best_candidate != NULL;
1325 		 best_candidate = best_candidate->next)
1326 	{
1327 		if (memcmp(argtypes, best_candidate->args, nargs * sizeof(Oid)) == 0)
1328 			break;
1329 	}
1330 
1331 	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 		if (nargs == 1 && fargs != NIL && fargnames == NIL)
1373 		{
1374 			Oid			targetType = FuncNameAsType(funcname);
1375 
1376 			if (OidIsValid(targetType))
1377 			{
1378 				Oid			sourceType = argtypes[0];
1379 				Node	   *arg1 = linitial(fargs);
1380 				bool		iscoercion;
1381 
1382 				if (sourceType == UNKNOWNOID && IsA(arg1, Const))
1383 				{
1384 					/* always treat typename('literal') as coercion */
1385 					iscoercion = true;
1386 				}
1387 				else
1388 				{
1389 					CoercionPathType cpathtype;
1390 					Oid			cfuncid;
1391 
1392 					cpathtype = find_coercion_pathway(targetType, sourceType,
1393 													  COERCION_EXPLICIT,
1394 													  &cfuncid);
1395 					switch (cpathtype)
1396 					{
1397 						case COERCION_PATH_RELABELTYPE:
1398 							iscoercion = true;
1399 							break;
1400 						case COERCION_PATH_COERCEVIAIO:
1401 							if ((sourceType == RECORDOID ||
1402 								 ISCOMPLEX(sourceType)) &&
1403 								TypeCategory(targetType) == TYPCATEGORY_STRING)
1404 								iscoercion = false;
1405 							else
1406 								iscoercion = true;
1407 							break;
1408 						default:
1409 							iscoercion = false;
1410 							break;
1411 					}
1412 				}
1413 
1414 				if (iscoercion)
1415 				{
1416 					/* Treat it as a type coercion */
1417 					*funcid = InvalidOid;
1418 					*rettype = targetType;
1419 					*retset = false;
1420 					*nvargs = 0;
1421 					*vatype = InvalidOid;
1422 					*true_typeids = argtypes;
1423 					return FUNCDETAIL_COERCION;
1424 				}
1425 			}
1426 		}
1427 
1428 		/*
1429 		 * didn't find an exact match, so now try to match up candidates...
1430 		 */
1431 		if (raw_candidates != NULL)
1432 		{
1433 			FuncCandidateList current_candidates;
1434 			int			ncandidates;
1435 
1436 			ncandidates = func_match_argtypes(nargs,
1437 											  argtypes,
1438 											  raw_candidates,
1439 											  &current_candidates);
1440 
1441 			/* one match only? then run with it... */
1442 			if (ncandidates == 1)
1443 				best_candidate = current_candidates;
1444 
1445 			/*
1446 			 * multiple candidates? then better decide or throw an error...
1447 			 */
1448 			else if (ncandidates > 1)
1449 			{
1450 				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 				if (!best_candidate)
1459 					return FUNCDETAIL_MULTIPLE;
1460 			}
1461 		}
1462 	}
1463 
1464 	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 		if (!OidIsValid(best_candidate->oid))
1476 			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 		if (fargnames != NIL && !expand_variadic && nargs > 0 &&
1484 			best_candidate->argnumbers[nargs - 1] != nargs - 1)
1485 			return FUNCDETAIL_NOTFOUND;
1486 
1487 		*funcid = best_candidate->oid;
1488 		*nvargs = best_candidate->nvargs;
1489 		*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 		if (best_candidate->argnumbers != NULL)
1497 		{
1498 			int			i = 0;
1499 			ListCell   *lc;
1500 
1501 			foreach(lc, fargs)
1502 			{
1503 				NamedArgExpr *na = (NamedArgExpr *) lfirst(lc);
1504 
1505 				if (IsA(na, NamedArgExpr))
1506 					na->argnumber = best_candidate->argnumbers[i];
1507 				i++;
1508 			}
1509 		}
1510 
1511 		ftup = SearchSysCache1(PROCOID,
1512 							   ObjectIdGetDatum(best_candidate->oid));
1513 		if (!HeapTupleIsValid(ftup))	/* should not happen */
1514 			elog(ERROR, "cache lookup failed for function %u",
1515 				 best_candidate->oid);
1516 		pform = (Form_pg_proc) GETSTRUCT(ftup);
1517 		*rettype = pform->prorettype;
1518 		*retset = pform->proretset;
1519 		*vatype = pform->provariadic;
1520 		/* fetch default args if caller wants 'em */
1521 		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 			if (best_candidate->ndargs > pform->pronargdefaults)
1530 				elog(ERROR, "not enough default arguments");
1531 
1532 			proargdefaults = SysCacheGetAttr(PROCOID, ftup,
1533 											 Anum_pg_proc_proargdefaults,
1534 											 &isnull);
1535 			Assert(!isnull);
1536 			str = TextDatumGetCString(proargdefaults);
1537 			defaults = castNode(List, stringToNode(str));
1538 			pfree(str);
1539 
1540 			/* Delete any unused defaults from the returned list */
1541 			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 				defargnumbers = NULL;
1558 				firstdefarg = &best_candidate->argnumbers[best_candidate->nargs - best_candidate->ndargs];
1559 				for (i = 0; i < best_candidate->ndargs; i++)
1560 					defargnumbers = bms_add_member(defargnumbers,
1561 												   firstdefarg[i]);
1562 				newdefaults = NIL;
1563 				i = pform->pronargs - pform->pronargdefaults;
1564 				foreach(lc, defaults)
1565 				{
1566 					if (bms_is_member(i, defargnumbers))
1567 						newdefaults = lappend(newdefaults, lfirst(lc));
1568 					i++;
1569 				}
1570 				Assert(list_length(newdefaults) == best_candidate->ndargs);
1571 				bms_free(defargnumbers);
1572 				*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 				ndelete = list_length(defaults) - best_candidate->ndargs;
1583 				while (ndelete-- > 0)
1584 					defaults = list_delete_first(defaults);
1585 				*argdefaults = defaults;
1586 			}
1587 		}
1588 		if (pform->proisagg)
1589 			result = FUNCDETAIL_AGGREGATE;
1590 		else if (pform->proiswindow)
1591 			result = FUNCDETAIL_WINDOWFUNC;
1592 		else
1593 			result = FUNCDETAIL_NORMAL;
1594 		ReleaseSysCache(ftup);
1595 		return result;
1596 	}
1597 
1598 	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
unify_hypothetical_args(ParseState * pstate,List * fargs,int numAggregatedArgs,Oid * actual_arg_types,Oid * declared_arg_types)1617 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 	numDirectArgs = list_length(fargs) - numAggregatedArgs;
1630 	numNonHypotheticalArgs = numDirectArgs - numAggregatedArgs;
1631 	/* safety check (should only trigger with a misdeclared agg) */
1632 	if (numNonHypotheticalArgs < 0)
1633 		elog(ERROR, "incorrect number of arguments to hypothetical-set aggregate");
1634 
1635 	/* Deconstruct fargs into an array for ease of subscripting */
1636 	i = 0;
1637 	foreach(lc, fargs)
1638 	{
1639 		args[i++] = (Node *) lfirst(lc);
1640 	}
1641 
1642 	/* Check each hypothetical arg and corresponding aggregated arg */
1643 	for (i = numNonHypotheticalArgs; i < numDirectArgs; i++)
1644 	{
1645 		int			aargpos = numDirectArgs + (i - numNonHypotheticalArgs);
1646 		Oid			commontype;
1647 
1648 		/* A mismatch means AggregateCreate didn't check properly ... */
1649 		if (declared_arg_types[i] != declared_arg_types[aargpos])
1650 			elog(ERROR, "hypothetical-set aggregate has inconsistent declared argument types");
1651 
1652 		/* No need to unify if make_fn_arguments will coerce */
1653 		if (declared_arg_types[i] != ANYOID)
1654 			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 		commontype = select_common_type(pstate,
1662 										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 		args[i] = coerce_type(pstate,
1671 							  args[i],
1672 							  actual_arg_types[i],
1673 							  commontype, -1,
1674 							  COERCION_IMPLICIT,
1675 							  COERCE_IMPLICIT_CAST,
1676 							  -1);
1677 		actual_arg_types[i] = commontype;
1678 		args[aargpos] = coerce_type(pstate,
1679 									args[aargpos],
1680 									actual_arg_types[aargpos],
1681 									commontype, -1,
1682 									COERCION_IMPLICIT,
1683 									COERCE_IMPLICIT_CAST,
1684 									-1);
1685 		actual_arg_types[aargpos] = commontype;
1686 	}
1687 
1688 	/* Reconstruct fargs from array */
1689 	i = 0;
1690 	foreach(lc, fargs)
1691 	{
1692 		lfirst(lc) = args[i++];
1693 	}
1694 }
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
make_fn_arguments(ParseState * pstate,List * fargs,Oid * actual_arg_types,Oid * declared_arg_types)1711 make_fn_arguments(ParseState *pstate,
1712 				  List *fargs,
1713 				  Oid *actual_arg_types,
1714 				  Oid *declared_arg_types)
1715 {
1716 	ListCell   *current_fargs;
1717 	int			i = 0;
1718 
1719 	foreach(current_fargs, fargs)
1720 	{
1721 		/* types don't match? then force coercion using a function call... */
1722 		if (actual_arg_types[i] != declared_arg_types[i])
1723 		{
1724 			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 			if (IsA(node, NamedArgExpr))
1731 			{
1732 				NamedArgExpr *na = (NamedArgExpr *) node;
1733 
1734 				node = coerce_type(pstate,
1735 								   (Node *) na->arg,
1736 								   actual_arg_types[i],
1737 								   declared_arg_types[i], -1,
1738 								   COERCION_IMPLICIT,
1739 								   COERCE_IMPLICIT_CAST,
1740 								   -1);
1741 				na->arg = (Expr *) node;
1742 			}
1743 			else
1744 			{
1745 				node = coerce_type(pstate,
1746 								   node,
1747 								   actual_arg_types[i],
1748 								   declared_arg_types[i], -1,
1749 								   COERCION_IMPLICIT,
1750 								   COERCE_IMPLICIT_CAST,
1751 								   -1);
1752 				lfirst(current_fargs) = node;
1753 			}
1754 		}
1755 		i++;
1756 	}
1757 }
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
FuncNameAsType(List * funcname)1767 FuncNameAsType(List *funcname)
1768 {
1769 	Oid			result;
1770 	Type		typtup;
1771 
1772 	/*
1773 	 * temp_ok=false protects the <refsect1 id="sql-createfunction-security">
1774 	 * contract for writing SECURITY DEFINER functions safely.
1775 	 */
1776 	typtup = LookupTypeNameExtended(NULL, makeTypeNameFromNameList(funcname),
1777 									NULL, false, false);
1778 	if (typtup == NULL)
1779 		return InvalidOid;
1780 
1781 	if (((Form_pg_type) GETSTRUCT(typtup))->typisdefined &&
1782 		!OidIsValid(typeTypeRelid(typtup)))
1783 		result = typeTypeId(typtup);
1784 	else
1785 		result = InvalidOid;
1786 
1787 	ReleaseSysCache(typtup);
1788 	return result;
1789 }
1790 
1791 /*
1792  * ParseComplexProjection -
1793  *	  handles function calls with a single argument that is of complex type.
1794  *	  If the function call is actually a column projection, return a suitably
1795  *	  transformed expression tree.  If not, return NULL.
1796  */
1797 static Node *
ParseComplexProjection(ParseState * pstate,char * funcname,Node * first_arg,int location)1798 ParseComplexProjection(ParseState *pstate, char *funcname, Node *first_arg,
1799 					   int location)
1800 {
1801 	TupleDesc	tupdesc;
1802 	int			i;
1803 
1804 	/*
1805 	 * Special case for whole-row Vars so that we can resolve (foo.*).bar even
1806 	 * when foo is a reference to a subselect, join, or RECORD function. A
1807 	 * bonus is that we avoid generating an unnecessary FieldSelect; our
1808 	 * result can omit the whole-row Var and just be a Var for the selected
1809 	 * field.
1810 	 *
1811 	 * This case could be handled by expandRecordVariable, but it's more
1812 	 * efficient to do it this way when possible.
1813 	 */
1814 	if (IsA(first_arg, Var) &&
1815 		((Var *) first_arg)->varattno == InvalidAttrNumber)
1816 	{
1817 		RangeTblEntry *rte;
1818 
1819 		rte = GetRTEByRangeTablePosn(pstate,
1820 									 ((Var *) first_arg)->varno,
1821 									 ((Var *) first_arg)->varlevelsup);
1822 		/* Return a Var if funcname matches a column, else NULL */
1823 		return scanRTEForColumn(pstate, rte, funcname, location, 0, NULL);
1824 	}
1825 
1826 	/*
1827 	 * Else do it the hard way with get_expr_result_type().
1828 	 *
1829 	 * If it's a Var of type RECORD, we have to work even harder: we have to
1830 	 * find what the Var refers to, and pass that to get_expr_result_type.
1831 	 * That task is handled by expandRecordVariable().
1832 	 */
1833 	if (IsA(first_arg, Var) &&
1834 		((Var *) first_arg)->vartype == RECORDOID)
1835 		tupdesc = expandRecordVariable(pstate, (Var *) first_arg, 0);
1836 	else if (get_expr_result_type(first_arg, NULL, &tupdesc) != TYPEFUNC_COMPOSITE)
1837 		return NULL;			/* unresolvable RECORD type */
1838 	Assert(tupdesc);
1839 
1840 	for (i = 0; i < tupdesc->natts; i++)
1841 	{
1842 		Form_pg_attribute att = tupdesc->attrs[i];
1843 
1844 		if (strcmp(funcname, NameStr(att->attname)) == 0 &&
1845 			!att->attisdropped)
1846 		{
1847 			/* Success, so generate a FieldSelect expression */
1848 			FieldSelect *fselect = makeNode(FieldSelect);
1849 
1850 			fselect->arg = (Expr *) first_arg;
1851 			fselect->fieldnum = i + 1;
1852 			fselect->resulttype = att->atttypid;
1853 			fselect->resulttypmod = att->atttypmod;
1854 			/* save attribute's collation for parse_collate.c */
1855 			fselect->resultcollid = att->attcollation;
1856 			return (Node *) fselect;
1857 		}
1858 	}
1859 
1860 	return NULL;				/* funcname does not match any column */
1861 }
1862 
1863 /*
1864  * funcname_signature_string
1865  *		Build a string representing a function name, including arg types.
1866  *		The result is something like "foo(integer)".
1867  *
1868  * If argnames isn't NIL, it is a list of C strings representing the actual
1869  * arg names for the last N arguments.  This must be considered part of the
1870  * function signature too, when dealing with named-notation function calls.
1871  *
1872  * This is typically used in the construction of function-not-found error
1873  * messages.
1874  */
1875 const char *
funcname_signature_string(const char * funcname,int nargs,List * argnames,const Oid * argtypes)1876 funcname_signature_string(const char *funcname, int nargs,
1877 						  List *argnames, const Oid *argtypes)
1878 {
1879 	StringInfoData argbuf;
1880 	int			numposargs;
1881 	ListCell   *lc;
1882 	int			i;
1883 
1884 	initStringInfo(&argbuf);
1885 
1886 	appendStringInfo(&argbuf, "%s(", funcname);
1887 
1888 	numposargs = nargs - list_length(argnames);
1889 	lc = list_head(argnames);
1890 
1891 	for (i = 0; i < nargs; i++)
1892 	{
1893 		if (i)
1894 			appendStringInfoString(&argbuf, ", ");
1895 		if (i >= numposargs)
1896 		{
1897 			appendStringInfo(&argbuf, "%s => ", (char *) lfirst(lc));
1898 			lc = lnext(lc);
1899 		}
1900 		appendStringInfoString(&argbuf, format_type_be(argtypes[i]));
1901 	}
1902 
1903 	appendStringInfoChar(&argbuf, ')');
1904 
1905 	return argbuf.data;			/* return palloc'd string buffer */
1906 }
1907 
1908 /*
1909  * func_signature_string
1910  *		As above, but function name is passed as a qualified name list.
1911  */
1912 const char *
func_signature_string(List * funcname,int nargs,List * argnames,const Oid * argtypes)1913 func_signature_string(List *funcname, int nargs,
1914 					  List *argnames, const Oid *argtypes)
1915 {
1916 	return funcname_signature_string(NameListToString(funcname),
1917 									 nargs, argnames, argtypes);
1918 }
1919 
1920 /*
1921  * LookupFuncName
1922  *
1923  * Given a possibly-qualified function name and optionally a set of argument
1924  * types, look up the function.  Pass nargs == -1 to indicate that no argument
1925  * types are specified.
1926  *
1927  * If the function name is not schema-qualified, it is sought in the current
1928  * namespace search path.
1929  *
1930  * If the function is not found, we return InvalidOid if noError is true,
1931  * else raise an error.
1932  */
1933 Oid
LookupFuncName(List * funcname,int nargs,const Oid * argtypes,bool noError)1934 LookupFuncName(List *funcname, int nargs, const Oid *argtypes, bool noError)
1935 {
1936 	FuncCandidateList clist;
1937 
1938 	/* Passing NULL for argtypes is no longer allowed */
1939 	Assert(argtypes);
1940 
1941 	clist = FuncnameGetCandidates(funcname, nargs, NIL, false, false, noError);
1942 
1943 	/*
1944 	 * If no arguments were specified, the name must yield a unique candidate.
1945 	 */
1946 	if (nargs == -1)
1947 	{
1948 		if (clist)
1949 		{
1950 			if (clist->next)
1951 			{
1952 				if (!noError)
1953 					ereport(ERROR,
1954 							(errcode(ERRCODE_AMBIGUOUS_FUNCTION),
1955 							 errmsg("function name \"%s\" is not unique",
1956 									NameListToString(funcname)),
1957 							 errhint("Specify the argument list to select the function unambiguously.")));
1958 				return InvalidOid;
1959 			}
1960 			/* Otherwise return the match */
1961 			return clist->oid;
1962 		}
1963 		else
1964 		{
1965 			if (!noError)
1966 				ereport(ERROR,
1967 						(errcode(ERRCODE_UNDEFINED_FUNCTION),
1968 						 errmsg("could not find a function named \"%s\"",
1969 								NameListToString(funcname))));
1970 			return InvalidOid;
1971 		}
1972 	}
1973 
1974 	/*
1975 	 * Otherwise, look for a match to the arg types.  FuncnameGetCandidates
1976 	 * has ensured that there's at most one match in the returned list.
1977 	 */
1978 	while (clist)
1979 	{
1980 		if (memcmp(argtypes, clist->args, nargs * sizeof(Oid)) == 0)
1981 			return clist->oid;
1982 		clist = clist->next;
1983 	}
1984 
1985 	if (!noError)
1986 		ereport(ERROR,
1987 				(errcode(ERRCODE_UNDEFINED_FUNCTION),
1988 				 errmsg("function %s does not exist",
1989 						func_signature_string(funcname, nargs,
1990 											  NIL, argtypes))));
1991 
1992 	return InvalidOid;
1993 }
1994 
1995 /*
1996  * LookupFuncWithArgs
1997  *		Like LookupFuncName, but the argument types are specified by a
1998  *		ObjectWithArgs node.
1999  */
2000 Oid
LookupFuncWithArgs(ObjectWithArgs * func,bool noError)2001 LookupFuncWithArgs(ObjectWithArgs *func, bool noError)
2002 {
2003 	Oid			argoids[FUNC_MAX_ARGS];
2004 	int			argcount;
2005 	int			i;
2006 	ListCell   *args_item;
2007 
2008 	argcount = list_length(func->objargs);
2009 	if (argcount > FUNC_MAX_ARGS)
2010 		ereport(ERROR,
2011 				(errcode(ERRCODE_TOO_MANY_ARGUMENTS),
2012 				 errmsg_plural("functions cannot have more than %d argument",
2013 							   "functions cannot have more than %d arguments",
2014 							   FUNC_MAX_ARGS,
2015 							   FUNC_MAX_ARGS)));
2016 
2017 	args_item = list_head(func->objargs);
2018 	for (i = 0; i < argcount; i++)
2019 	{
2020 		TypeName   *t = (TypeName *) lfirst(args_item);
2021 
2022 		argoids[i] = LookupTypeNameOid(NULL, t, noError);
2023 		args_item = lnext(args_item);
2024 	}
2025 
2026 	return LookupFuncName(func->objname, func->args_unspecified ? -1 : argcount, argoids, noError);
2027 }
2028 
2029 /*
2030  * LookupAggWithArgs
2031  *		Find an aggregate function from a given ObjectWithArgs node.
2032  *
2033  * This is almost like LookupFuncWithArgs, but the error messages refer
2034  * to aggregates rather than plain functions, and we verify that the found
2035  * function really is an aggregate.
2036  */
2037 Oid
LookupAggWithArgs(ObjectWithArgs * agg,bool noError)2038 LookupAggWithArgs(ObjectWithArgs *agg, bool noError)
2039 {
2040 	Oid			argoids[FUNC_MAX_ARGS];
2041 	int			argcount;
2042 	int			i;
2043 	ListCell   *lc;
2044 	Oid			oid;
2045 	HeapTuple	ftup;
2046 	Form_pg_proc pform;
2047 
2048 	argcount = list_length(agg->objargs);
2049 	if (argcount > FUNC_MAX_ARGS)
2050 		ereport(ERROR,
2051 				(errcode(ERRCODE_TOO_MANY_ARGUMENTS),
2052 				 errmsg_plural("functions cannot have more than %d argument",
2053 							   "functions cannot have more than %d arguments",
2054 							   FUNC_MAX_ARGS,
2055 							   FUNC_MAX_ARGS)));
2056 
2057 	i = 0;
2058 	foreach(lc, agg->objargs)
2059 	{
2060 		TypeName   *t = (TypeName *) lfirst(lc);
2061 
2062 		argoids[i] = LookupTypeNameOid(NULL, t, noError);
2063 		i++;
2064 	}
2065 
2066 	oid = LookupFuncName(agg->objname, argcount, argoids, true);
2067 
2068 	if (!OidIsValid(oid))
2069 	{
2070 		if (noError)
2071 			return InvalidOid;
2072 		if (argcount == 0)
2073 			ereport(ERROR,
2074 					(errcode(ERRCODE_UNDEFINED_FUNCTION),
2075 					 errmsg("aggregate %s(*) does not exist",
2076 							NameListToString(agg->objname))));
2077 		else
2078 			ereport(ERROR,
2079 					(errcode(ERRCODE_UNDEFINED_FUNCTION),
2080 					 errmsg("aggregate %s does not exist",
2081 							func_signature_string(agg->objname, argcount,
2082 												  NIL, argoids))));
2083 	}
2084 
2085 	/* Make sure it's an aggregate */
2086 	ftup = SearchSysCache1(PROCOID, ObjectIdGetDatum(oid));
2087 	if (!HeapTupleIsValid(ftup))	/* should not happen */
2088 		elog(ERROR, "cache lookup failed for function %u", oid);
2089 	pform = (Form_pg_proc) GETSTRUCT(ftup);
2090 
2091 	if (!pform->proisagg)
2092 	{
2093 		ReleaseSysCache(ftup);
2094 		if (noError)
2095 			return InvalidOid;
2096 		/* we do not use the (*) notation for functions... */
2097 		ereport(ERROR,
2098 				(errcode(ERRCODE_WRONG_OBJECT_TYPE),
2099 				 errmsg("function %s is not an aggregate",
2100 						func_signature_string(agg->objname, argcount,
2101 											  NIL, argoids))));
2102 	}
2103 
2104 	ReleaseSysCache(ftup);
2105 
2106 	return oid;
2107 }
2108 
2109 
2110 /*
2111  * check_srf_call_placement
2112  *		Verify that a set-returning function is called in a valid place,
2113  *		and throw a nice error if not.
2114  *
2115  * A side-effect is to set pstate->p_hasTargetSRFs true if appropriate.
2116  *
2117  * last_srf should be a copy of pstate->p_last_srf from just before we
2118  * started transforming the function's arguments.  This allows detection
2119  * of whether the SRF's arguments contain any SRFs.
2120  */
2121 void
check_srf_call_placement(ParseState * pstate,Node * last_srf,int location)2122 check_srf_call_placement(ParseState *pstate, Node *last_srf, int location)
2123 {
2124 	const char *err;
2125 	bool		errkind;
2126 
2127 	/*
2128 	 * Check to see if the set-returning function is in an invalid place
2129 	 * within the query.  Basically, we don't allow SRFs anywhere except in
2130 	 * the targetlist (which includes GROUP BY/ORDER BY expressions), VALUES,
2131 	 * and functions in FROM.
2132 	 *
2133 	 * For brevity we support two schemes for reporting an error here: set
2134 	 * "err" to a custom message, or set "errkind" true if the error context
2135 	 * is sufficiently identified by what ParseExprKindName will return, *and*
2136 	 * what it will return is just a SQL keyword.  (Otherwise, use a custom
2137 	 * message to avoid creating translation problems.)
2138 	 */
2139 	err = NULL;
2140 	errkind = false;
2141 	switch (pstate->p_expr_kind)
2142 	{
2143 		case EXPR_KIND_NONE:
2144 			Assert(false);		/* can't happen */
2145 			break;
2146 		case EXPR_KIND_OTHER:
2147 			/* Accept SRF here; caller must throw error if wanted */
2148 			break;
2149 		case EXPR_KIND_JOIN_ON:
2150 		case EXPR_KIND_JOIN_USING:
2151 			err = _("set-returning functions are not allowed in JOIN conditions");
2152 			break;
2153 		case EXPR_KIND_FROM_SUBSELECT:
2154 			/* can't get here, but just in case, throw an error */
2155 			errkind = true;
2156 			break;
2157 		case EXPR_KIND_FROM_FUNCTION:
2158 			/* okay, but we don't allow nested SRFs here */
2159 			/* errmsg is chosen to match transformRangeFunction() */
2160 			/* errposition should point to the inner SRF */
2161 			if (pstate->p_last_srf != last_srf)
2162 				ereport(ERROR,
2163 						(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2164 						 errmsg("set-returning functions must appear at top level of FROM"),
2165 						 parser_errposition(pstate,
2166 											exprLocation(pstate->p_last_srf))));
2167 			break;
2168 		case EXPR_KIND_WHERE:
2169 			errkind = true;
2170 			break;
2171 		case EXPR_KIND_POLICY:
2172 			err = _("set-returning functions are not allowed in policy expressions");
2173 			break;
2174 		case EXPR_KIND_HAVING:
2175 			errkind = true;
2176 			break;
2177 		case EXPR_KIND_FILTER:
2178 			errkind = true;
2179 			break;
2180 		case EXPR_KIND_WINDOW_PARTITION:
2181 		case EXPR_KIND_WINDOW_ORDER:
2182 			/* okay, these are effectively GROUP BY/ORDER BY */
2183 			pstate->p_hasTargetSRFs = true;
2184 			break;
2185 		case EXPR_KIND_WINDOW_FRAME_RANGE:
2186 		case EXPR_KIND_WINDOW_FRAME_ROWS:
2187 			err = _("set-returning functions are not allowed in window definitions");
2188 			break;
2189 		case EXPR_KIND_SELECT_TARGET:
2190 		case EXPR_KIND_INSERT_TARGET:
2191 			/* okay */
2192 			pstate->p_hasTargetSRFs = true;
2193 			break;
2194 		case EXPR_KIND_UPDATE_SOURCE:
2195 		case EXPR_KIND_UPDATE_TARGET:
2196 			/* disallowed because it would be ambiguous what to do */
2197 			errkind = true;
2198 			break;
2199 		case EXPR_KIND_GROUP_BY:
2200 		case EXPR_KIND_ORDER_BY:
2201 			/* okay */
2202 			pstate->p_hasTargetSRFs = true;
2203 			break;
2204 		case EXPR_KIND_DISTINCT_ON:
2205 			/* okay */
2206 			pstate->p_hasTargetSRFs = true;
2207 			break;
2208 		case EXPR_KIND_LIMIT:
2209 		case EXPR_KIND_OFFSET:
2210 			errkind = true;
2211 			break;
2212 		case EXPR_KIND_RETURNING:
2213 			errkind = true;
2214 			break;
2215 		case EXPR_KIND_VALUES:
2216 			/* SRFs are presently not supported by nodeValuesscan.c */
2217 			errkind = true;
2218 			break;
2219 		case EXPR_KIND_VALUES_SINGLE:
2220 			/* okay, since we process this like a SELECT tlist */
2221 			pstate->p_hasTargetSRFs = true;
2222 			break;
2223 		case EXPR_KIND_CHECK_CONSTRAINT:
2224 		case EXPR_KIND_DOMAIN_CHECK:
2225 			err = _("set-returning functions are not allowed in check constraints");
2226 			break;
2227 		case EXPR_KIND_COLUMN_DEFAULT:
2228 		case EXPR_KIND_FUNCTION_DEFAULT:
2229 			err = _("set-returning functions are not allowed in DEFAULT expressions");
2230 			break;
2231 		case EXPR_KIND_INDEX_EXPRESSION:
2232 			err = _("set-returning functions are not allowed in index expressions");
2233 			break;
2234 		case EXPR_KIND_INDEX_PREDICATE:
2235 			err = _("set-returning functions are not allowed in index predicates");
2236 			break;
2237 		case EXPR_KIND_ALTER_COL_TRANSFORM:
2238 			err = _("set-returning functions are not allowed in transform expressions");
2239 			break;
2240 		case EXPR_KIND_EXECUTE_PARAMETER:
2241 			err = _("set-returning functions are not allowed in EXECUTE parameters");
2242 			break;
2243 		case EXPR_KIND_TRIGGER_WHEN:
2244 			err = _("set-returning functions are not allowed in trigger WHEN conditions");
2245 			break;
2246 		case EXPR_KIND_PARTITION_EXPRESSION:
2247 			err = _("set-returning functions are not allowed in partition key expressions");
2248 			break;
2249 
2250 			/*
2251 			 * There is intentionally no default: case here, so that the
2252 			 * compiler will warn if we add a new ParseExprKind without
2253 			 * extending this switch.  If we do see an unrecognized value at
2254 			 * runtime, the behavior will be the same as for EXPR_KIND_OTHER,
2255 			 * which is sane anyway.
2256 			 */
2257 	}
2258 	if (err)
2259 		ereport(ERROR,
2260 				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2261 				 errmsg_internal("%s", err),
2262 				 parser_errposition(pstate, location)));
2263 	if (errkind)
2264 		ereport(ERROR,
2265 				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2266 		/* translator: %s is name of a SQL construct, eg GROUP BY */
2267 				 errmsg("set-returning functions are not allowed in %s",
2268 						ParseExprKindName(pstate->p_expr_kind)),
2269 				 parser_errposition(pstate, location)));
2270 }
2271