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