LCOV - differential code coverage report
Current view: top level - src/backend/parser - parse_func.c (source / functions) Coverage Total Hit LBC UIC UBC GBC GIC GNC CBC EUB ECB DCB
Current: Differential Code Coverage HEAD vs 15 Lines: 85.3 % 846 722 23 36 65 19 282 2 419 40 277 3
Current Date: 2023-04-08 17:13:01 Functions: 100.0 % 14 14 13 1 13
Baseline: 15 Line coverage date bins:
Baseline Date: 2023-04-08 15:09:40 [..60] days: 100.0 % 1 1 1
Legend: Lines: hit not hit (240..) days: 85.3 % 845 721 23 36 65 19 282 1 419 40 277
Function coverage date bins:
(240..) days: 51.9 % 27 14 13 1 13

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

Generated by: LCOV version v1.16-55-g56c0a2a