LCOV - code coverage report
Current view: top level - src/backend/parser - parse_func.c (source / functions) Coverage Total Hit
Test: PostgreSQL 20devel Lines: 85.5 % 873 746
Test Date: 2026-07-15 09:15:47 Functions: 100.0 % 15 15
Legend: Lines:     hit not hit
Branches: + taken - not taken # not executed
Branches: 73.4 % 820 602

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

Generated by: LCOV version 2.0-1