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

Generated by: LCOV version 2.0-1