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

Generated by: LCOV version 1.13