Thanks to visit codestin.com
Credit goes to doxygen.postgresql.org

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