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