LCOV - code coverage report
Current view: top level - src/backend/parser - parse_func.c (source / functions) Coverage Total Hit
Test: Code coverage Lines: 88.3 % 1053 930
Test Date: 2026-01-26 10:56:24 Functions: 100.0 % 15 15
Legend: Lines:     hit not hit
Branches: + taken - not taken # not executed
Branches: 66.0 % 996 657

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

Generated by: LCOV version 2.3.2-1