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