LCOV - code coverage report
Current view: top level - src/backend/parser - parse_func.c (source / functions) Coverage Total Hit
Test: PostgreSQL 20devel Lines: 85.1 % 882 751
Test Date: 2026-08-13 18:15:43 Functions: 100.0 % 15 15
Legend: Lines:     hit not hit
Branches: + taken - not taken # not executed
Branches: 72.6 % 840 610

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

Generated by: LCOV version 2.0-1