LCOV - code coverage report
Current view: top level - src/backend/parser - parse_func.c (source / functions) Hit Total Coverage
Test: PostgreSQL 15devel Lines: 702 823 85.3 %
Date: 2021-12-04 22:09:09 Functions: 14 14 100.0 %
Legend: Lines: hit not hit

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

Generated by: LCOV version 1.14