Header And Logo

PostgreSQL
| The world's most advanced open source database.

parse_func.c

Go to the documentation of this file.
00001 /*-------------------------------------------------------------------------
00002  *
00003  * parse_func.c
00004  *      handle function calls in parser
00005  *
00006  * Portions Copyright (c) 1996-2013, PostgreSQL Global Development Group
00007  * Portions Copyright (c) 1994, Regents of the University of California
00008  *
00009  *
00010  * IDENTIFICATION
00011  *    src/backend/parser/parse_func.c
00012  *
00013  *-------------------------------------------------------------------------
00014  */
00015 #include "postgres.h"
00016 
00017 #include "access/htup_details.h"
00018 #include "catalog/pg_proc.h"
00019 #include "catalog/pg_type.h"
00020 #include "funcapi.h"
00021 #include "lib/stringinfo.h"
00022 #include "nodes/makefuncs.h"
00023 #include "nodes/nodeFuncs.h"
00024 #include "parser/parse_agg.h"
00025 #include "parser/parse_coerce.h"
00026 #include "parser/parse_func.h"
00027 #include "parser/parse_relation.h"
00028 #include "parser/parse_target.h"
00029 #include "parser/parse_type.h"
00030 #include "utils/builtins.h"
00031 #include "utils/lsyscache.h"
00032 #include "utils/syscache.h"
00033 
00034 
00035 static Oid  FuncNameAsType(List *funcname);
00036 static Node *ParseComplexProjection(ParseState *pstate, char *funcname,
00037                        Node *first_arg, int location);
00038 
00039 
00040 /*
00041  *  Parse a function call
00042  *
00043  *  For historical reasons, Postgres tries to treat the notations tab.col
00044  *  and col(tab) as equivalent: if a single-argument function call has an
00045  *  argument of complex type and the (unqualified) function name matches
00046  *  any attribute of the type, we take it as a column projection.  Conversely
00047  *  a function of a single complex-type argument can be written like a
00048  *  column reference, allowing functions to act like computed columns.
00049  *
00050  *  Hence, both cases come through here.  The is_column parameter tells us
00051  *  which syntactic construct is actually being dealt with, but this is
00052  *  intended to be used only to deliver an appropriate error message,
00053  *  not to affect the semantics.  When is_column is true, we should have
00054  *  a single argument (the putative table), unqualified function name
00055  *  equal to the column name, and no aggregate or variadic decoration.
00056  *  Also, when is_column is true, we return NULL on failure rather than
00057  *  reporting a no-such-function error.
00058  *
00059  *  The argument expressions (in fargs) must have been transformed already.
00060  *  But the agg_order expressions, if any, have not been.
00061  */
00062 Node *
00063 ParseFuncOrColumn(ParseState *pstate, List *funcname, List *fargs,
00064                   List *agg_order, bool agg_star, bool agg_distinct,
00065                   bool func_variadic,
00066                   WindowDef *over, bool is_column, int location)
00067 {
00068     Oid         rettype;
00069     Oid         funcid;
00070     ListCell   *l;
00071     ListCell   *nextl;
00072     Node       *first_arg = NULL;
00073     int         nargs;
00074     int         nargsplusdefs;
00075     Oid         actual_arg_types[FUNC_MAX_ARGS];
00076     Oid        *declared_arg_types;
00077     List       *argnames;
00078     List       *argdefaults;
00079     Node       *retval;
00080     bool        retset;
00081     int         nvargs;
00082     FuncDetailCode fdresult;
00083 
00084     /*
00085      * Most of the rest of the parser just assumes that functions do not have
00086      * more than FUNC_MAX_ARGS parameters.  We have to test here to protect
00087      * against array overruns, etc.  Of course, this may not be a function,
00088      * but the test doesn't hurt.
00089      */
00090     if (list_length(fargs) > FUNC_MAX_ARGS)
00091         ereport(ERROR,
00092                 (errcode(ERRCODE_TOO_MANY_ARGUMENTS),
00093              errmsg_plural("cannot pass more than %d argument to a function",
00094                            "cannot pass more than %d arguments to a function",
00095                            FUNC_MAX_ARGS,
00096                            FUNC_MAX_ARGS),
00097                  parser_errposition(pstate, location)));
00098 
00099     /*
00100      * Extract arg type info in preparation for function lookup.
00101      *
00102      * If any arguments are Param markers of type VOID, we discard them from
00103      * the parameter list.  This is a hack to allow the JDBC driver to not
00104      * have to distinguish "input" and "output" parameter symbols while
00105      * parsing function-call constructs.  We can't use foreach() because we
00106      * may modify the list ...
00107      */
00108     nargs = 0;
00109     for (l = list_head(fargs); l != NULL; l = nextl)
00110     {
00111         Node       *arg = lfirst(l);
00112         Oid         argtype = exprType(arg);
00113 
00114         nextl = lnext(l);
00115 
00116         if (argtype == VOIDOID && IsA(arg, Param) &&!is_column)
00117         {
00118             fargs = list_delete_ptr(fargs, arg);
00119             continue;
00120         }
00121 
00122         actual_arg_types[nargs++] = argtype;
00123     }
00124 
00125     /*
00126      * Check for named arguments; if there are any, build a list of names.
00127      *
00128      * We allow mixed notation (some named and some not), but only with all
00129      * the named parameters after all the unnamed ones.  So the name list
00130      * corresponds to the last N actual parameters and we don't need any extra
00131      * bookkeeping to match things up.
00132      */
00133     argnames = NIL;
00134     foreach(l, fargs)
00135     {
00136         Node       *arg = lfirst(l);
00137 
00138         if (IsA(arg, NamedArgExpr))
00139         {
00140             NamedArgExpr *na = (NamedArgExpr *) arg;
00141             ListCell   *lc;
00142 
00143             /* Reject duplicate arg names */
00144             foreach(lc, argnames)
00145             {
00146                 if (strcmp(na->name, (char *) lfirst(lc)) == 0)
00147                     ereport(ERROR,
00148                             (errcode(ERRCODE_SYNTAX_ERROR),
00149                            errmsg("argument name \"%s\" used more than once",
00150                                   na->name),
00151                              parser_errposition(pstate, na->location)));
00152             }
00153             argnames = lappend(argnames, na->name);
00154         }
00155         else
00156         {
00157             if (argnames != NIL)
00158                 ereport(ERROR,
00159                         (errcode(ERRCODE_SYNTAX_ERROR),
00160                   errmsg("positional argument cannot follow named argument"),
00161                          parser_errposition(pstate, exprLocation(arg))));
00162         }
00163     }
00164 
00165     if (fargs)
00166     {
00167         first_arg = linitial(fargs);
00168         Assert(first_arg != NULL);
00169     }
00170 
00171     /*
00172      * Check for column projection: if function has one argument, and that
00173      * argument is of complex type, and function name is not qualified, then
00174      * the "function call" could be a projection.  We also check that there
00175      * wasn't any aggregate or variadic decoration, nor an argument name.
00176      */
00177     if (nargs == 1 && agg_order == NIL && !agg_star && !agg_distinct &&
00178         over == NULL && !func_variadic && argnames == NIL &&
00179         list_length(funcname) == 1)
00180     {
00181         Oid         argtype = actual_arg_types[0];
00182 
00183         if (argtype == RECORDOID || ISCOMPLEX(argtype))
00184         {
00185             retval = ParseComplexProjection(pstate,
00186                                             strVal(linitial(funcname)),
00187                                             first_arg,
00188                                             location);
00189             if (retval)
00190                 return retval;
00191 
00192             /*
00193              * If ParseComplexProjection doesn't recognize it as a projection,
00194              * just press on.
00195              */
00196         }
00197     }
00198 
00199     /*
00200      * Okay, it's not a column projection, so it must really be a function.
00201      * func_get_detail looks up the function in the catalogs, does
00202      * disambiguation for polymorphic functions, handles inheritance, and
00203      * returns the funcid and type and set or singleton status of the
00204      * function's return value.  It also returns the true argument types to
00205      * the function.
00206      *
00207      * Note: for a named-notation or variadic function call, the reported
00208      * "true" types aren't really what is in pg_proc: the types are reordered
00209      * to match the given argument order of named arguments, and a variadic
00210      * argument is replaced by a suitable number of copies of its element
00211      * type.  We'll fix up the variadic case below.  We may also have to deal
00212      * with default arguments.
00213      */
00214     fdresult = func_get_detail(funcname, fargs, argnames, nargs,
00215                                actual_arg_types,
00216                                !func_variadic, true,
00217                                &funcid, &rettype, &retset, &nvargs,
00218                                &declared_arg_types, &argdefaults);
00219     if (fdresult == FUNCDETAIL_COERCION)
00220     {
00221         /*
00222          * We interpreted it as a type coercion. coerce_type can handle these
00223          * cases, so why duplicate code...
00224          */
00225         return coerce_type(pstate, linitial(fargs),
00226                            actual_arg_types[0], rettype, -1,
00227                            COERCION_EXPLICIT, COERCE_EXPLICIT_CALL, location);
00228     }
00229     else if (fdresult == FUNCDETAIL_NORMAL)
00230     {
00231         /*
00232          * Normal function found; was there anything indicating it must be an
00233          * aggregate?
00234          */
00235         if (agg_star)
00236             ereport(ERROR,
00237                     (errcode(ERRCODE_WRONG_OBJECT_TYPE),
00238                errmsg("%s(*) specified, but %s is not an aggregate function",
00239                       NameListToString(funcname),
00240                       NameListToString(funcname)),
00241                      parser_errposition(pstate, location)));
00242         if (agg_distinct)
00243             ereport(ERROR,
00244                     (errcode(ERRCODE_WRONG_OBJECT_TYPE),
00245             errmsg("DISTINCT specified, but %s is not an aggregate function",
00246                    NameListToString(funcname)),
00247                      parser_errposition(pstate, location)));
00248         if (agg_order != NIL)
00249             ereport(ERROR,
00250                     (errcode(ERRCODE_WRONG_OBJECT_TYPE),
00251             errmsg("ORDER BY specified, but %s is not an aggregate function",
00252                    NameListToString(funcname)),
00253                      parser_errposition(pstate, location)));
00254         if (over)
00255             ereport(ERROR,
00256                     (errcode(ERRCODE_WRONG_OBJECT_TYPE),
00257                      errmsg("OVER specified, but %s is not a window function nor an aggregate function",
00258                             NameListToString(funcname)),
00259                      parser_errposition(pstate, location)));
00260     }
00261     else if (!(fdresult == FUNCDETAIL_AGGREGATE ||
00262                fdresult == FUNCDETAIL_WINDOWFUNC))
00263     {
00264         /*
00265          * Oops.  Time to die.
00266          *
00267          * If we are dealing with the attribute notation rel.function, let the
00268          * caller handle failure.
00269          */
00270         if (is_column)
00271             return NULL;
00272 
00273         /*
00274          * Else generate a detailed complaint for a function
00275          */
00276         if (fdresult == FUNCDETAIL_MULTIPLE)
00277             ereport(ERROR,
00278                     (errcode(ERRCODE_AMBIGUOUS_FUNCTION),
00279                      errmsg("function %s is not unique",
00280                             func_signature_string(funcname, nargs, argnames,
00281                                                   actual_arg_types)),
00282                      errhint("Could not choose a best candidate function. "
00283                              "You might need to add explicit type casts."),
00284                      parser_errposition(pstate, location)));
00285         else if (list_length(agg_order) > 1)
00286         {
00287             /* It's agg(x, ORDER BY y,z) ... perhaps misplaced ORDER BY */
00288             ereport(ERROR,
00289                     (errcode(ERRCODE_UNDEFINED_FUNCTION),
00290                      errmsg("function %s does not exist",
00291                             func_signature_string(funcname, nargs, argnames,
00292                                                   actual_arg_types)),
00293                      errhint("No aggregate function matches the given name and argument types. "
00294                       "Perhaps you misplaced ORDER BY; ORDER BY must appear "
00295                              "after all regular arguments of the aggregate."),
00296                      parser_errposition(pstate, location)));
00297         }
00298         else
00299             ereport(ERROR,
00300                     (errcode(ERRCODE_UNDEFINED_FUNCTION),
00301                      errmsg("function %s does not exist",
00302                             func_signature_string(funcname, nargs, argnames,
00303                                                   actual_arg_types)),
00304             errhint("No function matches the given name and argument types. "
00305                     "You might need to add explicit type casts."),
00306                      parser_errposition(pstate, location)));
00307     }
00308 
00309     /*
00310      * If there are default arguments, we have to include their types in
00311      * actual_arg_types for the purpose of checking generic type consistency.
00312      * However, we do NOT put them into the generated parse node, because
00313      * their actual values might change before the query gets run.  The
00314      * planner has to insert the up-to-date values at plan time.
00315      */
00316     nargsplusdefs = nargs;
00317     foreach(l, argdefaults)
00318     {
00319         Node       *expr = (Node *) lfirst(l);
00320 
00321         /* probably shouldn't happen ... */
00322         if (nargsplusdefs >= FUNC_MAX_ARGS)
00323             ereport(ERROR,
00324                     (errcode(ERRCODE_TOO_MANY_ARGUMENTS),
00325              errmsg_plural("cannot pass more than %d argument to a function",
00326                            "cannot pass more than %d arguments to a function",
00327                            FUNC_MAX_ARGS,
00328                            FUNC_MAX_ARGS),
00329                      parser_errposition(pstate, location)));
00330 
00331         actual_arg_types[nargsplusdefs++] = exprType(expr);
00332     }
00333 
00334     /*
00335      * enforce consistency with polymorphic argument and return types,
00336      * possibly adjusting return type or declared_arg_types (which will be
00337      * used as the cast destination by make_fn_arguments)
00338      */
00339     rettype = enforce_generic_type_consistency(actual_arg_types,
00340                                                declared_arg_types,
00341                                                nargsplusdefs,
00342                                                rettype,
00343                                                false);
00344 
00345     /* perform the necessary typecasting of arguments */
00346     make_fn_arguments(pstate, fargs, actual_arg_types, declared_arg_types);
00347 
00348     /*
00349      * If it's a variadic function call, transform the last nvargs arguments
00350      * into an array --- unless it's an "any" variadic.
00351      */
00352     if (nvargs > 0 && declared_arg_types[nargs - 1] != ANYOID)
00353     {
00354         ArrayExpr  *newa = makeNode(ArrayExpr);
00355         int         non_var_args = nargs - nvargs;
00356         List       *vargs;
00357 
00358         Assert(non_var_args >= 0);
00359         vargs = list_copy_tail(fargs, non_var_args);
00360         fargs = list_truncate(fargs, non_var_args);
00361 
00362         newa->elements = vargs;
00363         /* assume all the variadic arguments were coerced to the same type */
00364         newa->element_typeid = exprType((Node *) linitial(vargs));
00365         newa->array_typeid = get_array_type(newa->element_typeid);
00366         if (!OidIsValid(newa->array_typeid))
00367             ereport(ERROR,
00368                     (errcode(ERRCODE_UNDEFINED_OBJECT),
00369                      errmsg("could not find array type for data type %s",
00370                             format_type_be(newa->element_typeid)),
00371                   parser_errposition(pstate, exprLocation((Node *) vargs))));
00372         /* array_collid will be set by parse_collate.c */
00373         newa->multidims = false;
00374         newa->location = exprLocation((Node *) vargs);
00375 
00376         fargs = lappend(fargs, newa);
00377     }
00378 
00379     /* build the appropriate output structure */
00380     if (fdresult == FUNCDETAIL_NORMAL)
00381     {
00382         FuncExpr   *funcexpr = makeNode(FuncExpr);
00383 
00384         funcexpr->funcid = funcid;
00385         funcexpr->funcresulttype = rettype;
00386         funcexpr->funcretset = retset;
00387         funcexpr->funcvariadic = func_variadic;
00388         funcexpr->funcformat = COERCE_EXPLICIT_CALL;
00389         /* funccollid and inputcollid will be set by parse_collate.c */
00390         funcexpr->args = fargs;
00391         funcexpr->location = location;
00392 
00393         retval = (Node *) funcexpr;
00394     }
00395     else if (fdresult == FUNCDETAIL_AGGREGATE && !over)
00396     {
00397         /* aggregate function */
00398         Aggref     *aggref = makeNode(Aggref);
00399 
00400         aggref->aggfnoid = funcid;
00401         aggref->aggtype = rettype;
00402         /* aggcollid and inputcollid will be set by parse_collate.c */
00403         /* args, aggorder, aggdistinct will be set by transformAggregateCall */
00404         aggref->aggstar = agg_star;
00405         /* agglevelsup will be set by transformAggregateCall */
00406         aggref->location = location;
00407 
00408         /*
00409          * Reject attempt to call a parameterless aggregate without (*)
00410          * syntax.  This is mere pedantry but some folks insisted ...
00411          */
00412         if (fargs == NIL && !agg_star)
00413             ereport(ERROR,
00414                     (errcode(ERRCODE_WRONG_OBJECT_TYPE),
00415                      errmsg("%s(*) must be used to call a parameterless aggregate function",
00416                             NameListToString(funcname)),
00417                      parser_errposition(pstate, location)));
00418 
00419         if (retset)
00420             ereport(ERROR,
00421                     (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
00422                      errmsg("aggregates cannot return sets"),
00423                      parser_errposition(pstate, location)));
00424 
00425         /*
00426          * Currently it's not possible to define an aggregate with named
00427          * arguments, so this case should be impossible.  Check anyway because
00428          * the planner and executor wouldn't cope with NamedArgExprs in an
00429          * Aggref node.
00430          */
00431         if (argnames != NIL)
00432             ereport(ERROR,
00433                     (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
00434                      errmsg("aggregates cannot use named arguments"),
00435                      parser_errposition(pstate, location)));
00436 
00437         /* parse_agg.c does additional aggregate-specific processing */
00438         transformAggregateCall(pstate, aggref, fargs, agg_order, agg_distinct);
00439 
00440         retval = (Node *) aggref;
00441     }
00442     else
00443     {
00444         /* window function */
00445         WindowFunc *wfunc = makeNode(WindowFunc);
00446 
00447         /*
00448          * True window functions must be called with a window definition.
00449          */
00450         if (!over)
00451             ereport(ERROR,
00452                     (errcode(ERRCODE_WRONG_OBJECT_TYPE),
00453                      errmsg("window function call requires an OVER clause"),
00454                      parser_errposition(pstate, location)));
00455 
00456         wfunc->winfnoid = funcid;
00457         wfunc->wintype = rettype;
00458         /* wincollid and inputcollid will be set by parse_collate.c */
00459         wfunc->args = fargs;
00460         /* winref will be set by transformWindowFuncCall */
00461         wfunc->winstar = agg_star;
00462         wfunc->winagg = (fdresult == FUNCDETAIL_AGGREGATE);
00463         wfunc->location = location;
00464 
00465         /*
00466          * agg_star is allowed for aggregate functions but distinct isn't
00467          */
00468         if (agg_distinct)
00469             ereport(ERROR,
00470                     (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
00471                   errmsg("DISTINCT is not implemented for window functions"),
00472                      parser_errposition(pstate, location)));
00473 
00474         /*
00475          * Reject attempt to call a parameterless aggregate without (*)
00476          * syntax.  This is mere pedantry but some folks insisted ...
00477          */
00478         if (wfunc->winagg && fargs == NIL && !agg_star)
00479             ereport(ERROR,
00480                     (errcode(ERRCODE_WRONG_OBJECT_TYPE),
00481                      errmsg("%s(*) must be used to call a parameterless aggregate function",
00482                             NameListToString(funcname)),
00483                      parser_errposition(pstate, location)));
00484 
00485         /*
00486          * ordered aggs not allowed in windows yet
00487          */
00488         if (agg_order != NIL)
00489             ereport(ERROR,
00490                     (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
00491                      errmsg("aggregate ORDER BY is not implemented for window functions"),
00492                      parser_errposition(pstate, location)));
00493 
00494         if (retset)
00495             ereport(ERROR,
00496                     (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
00497                      errmsg("window functions cannot return sets"),
00498                      parser_errposition(pstate, location)));
00499 
00500         /*
00501          * We might want to support this later, but for now reject it because
00502          * the planner and executor wouldn't cope with NamedArgExprs in a
00503          * WindowFunc node.
00504          */
00505         if (argnames != NIL)
00506             ereport(ERROR,
00507                     (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
00508                      errmsg("window functions cannot use named arguments"),
00509                      parser_errposition(pstate, location)));
00510 
00511         /* parse_agg.c does additional window-func-specific processing */
00512         transformWindowFuncCall(pstate, wfunc, over);
00513 
00514         retval = (Node *) wfunc;
00515     }
00516 
00517     return retval;
00518 }
00519 
00520 
00521 /* func_match_argtypes()
00522  *
00523  * Given a list of candidate functions (having the right name and number
00524  * of arguments) and an array of input datatype OIDs, produce a shortlist of
00525  * those candidates that actually accept the input datatypes (either exactly
00526  * or by coercion), and return the number of such candidates.
00527  *
00528  * Note that can_coerce_type will assume that UNKNOWN inputs are coercible to
00529  * anything, so candidates will not be eliminated on that basis.
00530  *
00531  * NB: okay to modify input list structure, as long as we find at least
00532  * one match.  If no match at all, the list must remain unmodified.
00533  */
00534 int
00535 func_match_argtypes(int nargs,
00536                     Oid *input_typeids,
00537                     FuncCandidateList raw_candidates,
00538                     FuncCandidateList *candidates)      /* return value */
00539 {
00540     FuncCandidateList current_candidate;
00541     FuncCandidateList next_candidate;
00542     int         ncandidates = 0;
00543 
00544     *candidates = NULL;
00545 
00546     for (current_candidate = raw_candidates;
00547          current_candidate != NULL;
00548          current_candidate = next_candidate)
00549     {
00550         next_candidate = current_candidate->next;
00551         if (can_coerce_type(nargs, input_typeids, current_candidate->args,
00552                             COERCION_IMPLICIT))
00553         {
00554             current_candidate->next = *candidates;
00555             *candidates = current_candidate;
00556             ncandidates++;
00557         }
00558     }
00559 
00560     return ncandidates;
00561 }   /* func_match_argtypes() */
00562 
00563 
00564 /* func_select_candidate()
00565  *      Given the input argtype array and more than one candidate
00566  *      for the function, attempt to resolve the conflict.
00567  *
00568  * Returns the selected candidate if the conflict can be resolved,
00569  * otherwise returns NULL.
00570  *
00571  * Note that the caller has already determined that there is no candidate
00572  * exactly matching the input argtypes, and has pruned away any "candidates"
00573  * that aren't actually coercion-compatible with the input types.
00574  *
00575  * This is also used for resolving ambiguous operator references.  Formerly
00576  * parse_oper.c had its own, essentially duplicate code for the purpose.
00577  * The following comments (formerly in parse_oper.c) are kept to record some
00578  * of the history of these heuristics.
00579  *
00580  * OLD COMMENTS:
00581  *
00582  * This routine is new code, replacing binary_oper_select_candidate()
00583  * which dates from v4.2/v1.0.x days. It tries very hard to match up
00584  * operators with types, including allowing type coercions if necessary.
00585  * The important thing is that the code do as much as possible,
00586  * while _never_ doing the wrong thing, where "the wrong thing" would
00587  * be returning an operator when other better choices are available,
00588  * or returning an operator which is a non-intuitive possibility.
00589  * - thomas 1998-05-21
00590  *
00591  * The comments below came from binary_oper_select_candidate(), and
00592  * illustrate the issues and choices which are possible:
00593  * - thomas 1998-05-20
00594  *
00595  * current wisdom holds that the default operator should be one in which
00596  * both operands have the same type (there will only be one such
00597  * operator)
00598  *
00599  * 7.27.93 - I have decided not to do this; it's too hard to justify, and
00600  * it's easy enough to typecast explicitly - avi
00601  * [the rest of this routine was commented out since then - ay]
00602  *
00603  * 6/23/95 - I don't complete agree with avi. In particular, casting
00604  * floats is a pain for users. Whatever the rationale behind not doing
00605  * this is, I need the following special case to work.
00606  *
00607  * In the WHERE clause of a query, if a float is specified without
00608  * quotes, we treat it as float8. I added the float48* operators so
00609  * that we can operate on float4 and float8. But now we have more than
00610  * one matching operator if the right arg is unknown (eg. float
00611  * specified with quotes). This break some stuff in the regression
00612  * test where there are floats in quotes not properly casted. Below is
00613  * the solution. In addition to requiring the operator operates on the
00614  * same type for both operands [as in the code Avi originally
00615  * commented out], we also require that the operators be equivalent in
00616  * some sense. (see equivalentOpersAfterPromotion for details.)
00617  * - ay 6/95
00618  */
00619 FuncCandidateList
00620 func_select_candidate(int nargs,
00621                       Oid *input_typeids,
00622                       FuncCandidateList candidates)
00623 {
00624     FuncCandidateList current_candidate,
00625                 first_candidate,
00626                 last_candidate;
00627     Oid        *current_typeids;
00628     Oid         current_type;
00629     int         i;
00630     int         ncandidates;
00631     int         nbestMatch,
00632                 nmatch,
00633                 nunknowns;
00634     Oid         input_base_typeids[FUNC_MAX_ARGS];
00635     TYPCATEGORY slot_category[FUNC_MAX_ARGS],
00636                 current_category;
00637     bool        current_is_preferred;
00638     bool        slot_has_preferred_type[FUNC_MAX_ARGS];
00639     bool        resolved_unknowns;
00640 
00641     /* protect local fixed-size arrays */
00642     if (nargs > FUNC_MAX_ARGS)
00643         ereport(ERROR,
00644                 (errcode(ERRCODE_TOO_MANY_ARGUMENTS),
00645              errmsg_plural("cannot pass more than %d argument to a function",
00646                            "cannot pass more than %d arguments to a function",
00647                            FUNC_MAX_ARGS,
00648                            FUNC_MAX_ARGS)));
00649 
00650     /*
00651      * If any input types are domains, reduce them to their base types. This
00652      * ensures that we will consider functions on the base type to be "exact
00653      * matches" in the exact-match heuristic; it also makes it possible to do
00654      * something useful with the type-category heuristics. Note that this
00655      * makes it difficult, but not impossible, to use functions declared to
00656      * take a domain as an input datatype.  Such a function will be selected
00657      * over the base-type function only if it is an exact match at all
00658      * argument positions, and so was already chosen by our caller.
00659      *
00660      * While we're at it, count the number of unknown-type arguments for use
00661      * later.
00662      */
00663     nunknowns = 0;
00664     for (i = 0; i < nargs; i++)
00665     {
00666         if (input_typeids[i] != UNKNOWNOID)
00667             input_base_typeids[i] = getBaseType(input_typeids[i]);
00668         else
00669         {
00670             /* no need to call getBaseType on UNKNOWNOID */
00671             input_base_typeids[i] = UNKNOWNOID;
00672             nunknowns++;
00673         }
00674     }
00675 
00676     /*
00677      * Run through all candidates and keep those with the most matches on
00678      * exact types. Keep all candidates if none match.
00679      */
00680     ncandidates = 0;
00681     nbestMatch = 0;
00682     last_candidate = NULL;
00683     for (current_candidate = candidates;
00684          current_candidate != NULL;
00685          current_candidate = current_candidate->next)
00686     {
00687         current_typeids = current_candidate->args;
00688         nmatch = 0;
00689         for (i = 0; i < nargs; i++)
00690         {
00691             if (input_base_typeids[i] != UNKNOWNOID &&
00692                 current_typeids[i] == input_base_typeids[i])
00693                 nmatch++;
00694         }
00695 
00696         /* take this one as the best choice so far? */
00697         if ((nmatch > nbestMatch) || (last_candidate == NULL))
00698         {
00699             nbestMatch = nmatch;
00700             candidates = current_candidate;
00701             last_candidate = current_candidate;
00702             ncandidates = 1;
00703         }
00704         /* no worse than the last choice, so keep this one too? */
00705         else if (nmatch == nbestMatch)
00706         {
00707             last_candidate->next = current_candidate;
00708             last_candidate = current_candidate;
00709             ncandidates++;
00710         }
00711         /* otherwise, don't bother keeping this one... */
00712     }
00713 
00714     if (last_candidate)         /* terminate rebuilt list */
00715         last_candidate->next = NULL;
00716 
00717     if (ncandidates == 1)
00718         return candidates;
00719 
00720     /*
00721      * Still too many candidates? Now look for candidates which have either
00722      * exact matches or preferred types at the args that will require
00723      * coercion. (Restriction added in 7.4: preferred type must be of same
00724      * category as input type; give no preference to cross-category
00725      * conversions to preferred types.)  Keep all candidates if none match.
00726      */
00727     for (i = 0; i < nargs; i++) /* avoid multiple lookups */
00728         slot_category[i] = TypeCategory(input_base_typeids[i]);
00729     ncandidates = 0;
00730     nbestMatch = 0;
00731     last_candidate = NULL;
00732     for (current_candidate = candidates;
00733          current_candidate != NULL;
00734          current_candidate = current_candidate->next)
00735     {
00736         current_typeids = current_candidate->args;
00737         nmatch = 0;
00738         for (i = 0; i < nargs; i++)
00739         {
00740             if (input_base_typeids[i] != UNKNOWNOID)
00741             {
00742                 if (current_typeids[i] == input_base_typeids[i] ||
00743                     IsPreferredType(slot_category[i], current_typeids[i]))
00744                     nmatch++;
00745             }
00746         }
00747 
00748         if ((nmatch > nbestMatch) || (last_candidate == NULL))
00749         {
00750             nbestMatch = nmatch;
00751             candidates = current_candidate;
00752             last_candidate = current_candidate;
00753             ncandidates = 1;
00754         }
00755         else if (nmatch == nbestMatch)
00756         {
00757             last_candidate->next = current_candidate;
00758             last_candidate = current_candidate;
00759             ncandidates++;
00760         }
00761     }
00762 
00763     if (last_candidate)         /* terminate rebuilt list */
00764         last_candidate->next = NULL;
00765 
00766     if (ncandidates == 1)
00767         return candidates;
00768 
00769     /*
00770      * Still too many candidates?  Try assigning types for the unknown inputs.
00771      *
00772      * If there are no unknown inputs, we have no more heuristics that apply,
00773      * and must fail.
00774      */
00775     if (nunknowns == 0)
00776         return NULL;            /* failed to select a best candidate */
00777 
00778     /*
00779      * The next step examines each unknown argument position to see if we can
00780      * determine a "type category" for it.  If any candidate has an input
00781      * datatype of STRING category, use STRING category (this bias towards
00782      * STRING is appropriate since unknown-type literals look like strings).
00783      * Otherwise, if all the candidates agree on the type category of this
00784      * argument position, use that category.  Otherwise, fail because we
00785      * cannot determine a category.
00786      *
00787      * If we are able to determine a type category, also notice whether any of
00788      * the candidates takes a preferred datatype within the category.
00789      *
00790      * Having completed this examination, remove candidates that accept the
00791      * wrong category at any unknown position.  Also, if at least one
00792      * candidate accepted a preferred type at a position, remove candidates
00793      * that accept non-preferred types.  If just one candidate remains, return
00794      * that one.  However, if this rule turns out to reject all candidates,
00795      * keep them all instead.
00796      */
00797     resolved_unknowns = false;
00798     for (i = 0; i < nargs; i++)
00799     {
00800         bool        have_conflict;
00801 
00802         if (input_base_typeids[i] != UNKNOWNOID)
00803             continue;
00804         resolved_unknowns = true;       /* assume we can do it */
00805         slot_category[i] = TYPCATEGORY_INVALID;
00806         slot_has_preferred_type[i] = false;
00807         have_conflict = false;
00808         for (current_candidate = candidates;
00809              current_candidate != NULL;
00810              current_candidate = current_candidate->next)
00811         {
00812             current_typeids = current_candidate->args;
00813             current_type = current_typeids[i];
00814             get_type_category_preferred(current_type,
00815                                         &current_category,
00816                                         &current_is_preferred);
00817             if (slot_category[i] == TYPCATEGORY_INVALID)
00818             {
00819                 /* first candidate */
00820                 slot_category[i] = current_category;
00821                 slot_has_preferred_type[i] = current_is_preferred;
00822             }
00823             else if (current_category == slot_category[i])
00824             {
00825                 /* more candidates in same category */
00826                 slot_has_preferred_type[i] |= current_is_preferred;
00827             }
00828             else
00829             {
00830                 /* category conflict! */
00831                 if (current_category == TYPCATEGORY_STRING)
00832                 {
00833                     /* STRING always wins if available */
00834                     slot_category[i] = current_category;
00835                     slot_has_preferred_type[i] = current_is_preferred;
00836                 }
00837                 else
00838                 {
00839                     /*
00840                      * Remember conflict, but keep going (might find STRING)
00841                      */
00842                     have_conflict = true;
00843                 }
00844             }
00845         }
00846         if (have_conflict && slot_category[i] != TYPCATEGORY_STRING)
00847         {
00848             /* Failed to resolve category conflict at this position */
00849             resolved_unknowns = false;
00850             break;
00851         }
00852     }
00853 
00854     if (resolved_unknowns)
00855     {
00856         /* Strip non-matching candidates */
00857         ncandidates = 0;
00858         first_candidate = candidates;
00859         last_candidate = NULL;
00860         for (current_candidate = candidates;
00861              current_candidate != NULL;
00862              current_candidate = current_candidate->next)
00863         {
00864             bool        keepit = true;
00865 
00866             current_typeids = current_candidate->args;
00867             for (i = 0; i < nargs; i++)
00868             {
00869                 if (input_base_typeids[i] != UNKNOWNOID)
00870                     continue;
00871                 current_type = current_typeids[i];
00872                 get_type_category_preferred(current_type,
00873                                             &current_category,
00874                                             &current_is_preferred);
00875                 if (current_category != slot_category[i])
00876                 {
00877                     keepit = false;
00878                     break;
00879                 }
00880                 if (slot_has_preferred_type[i] && !current_is_preferred)
00881                 {
00882                     keepit = false;
00883                     break;
00884                 }
00885             }
00886             if (keepit)
00887             {
00888                 /* keep this candidate */
00889                 last_candidate = current_candidate;
00890                 ncandidates++;
00891             }
00892             else
00893             {
00894                 /* forget this candidate */
00895                 if (last_candidate)
00896                     last_candidate->next = current_candidate->next;
00897                 else
00898                     first_candidate = current_candidate->next;
00899             }
00900         }
00901 
00902         /* if we found any matches, restrict our attention to those */
00903         if (last_candidate)
00904         {
00905             candidates = first_candidate;
00906             /* terminate rebuilt list */
00907             last_candidate->next = NULL;
00908         }
00909 
00910         if (ncandidates == 1)
00911             return candidates;
00912     }
00913 
00914     /*
00915      * Last gasp: if there are both known- and unknown-type inputs, and all
00916      * the known types are the same, assume the unknown inputs are also that
00917      * type, and see if that gives us a unique match.  If so, use that match.
00918      *
00919      * NOTE: for a binary operator with one unknown and one non-unknown input,
00920      * we already tried this heuristic in binary_oper_exact().  However, that
00921      * code only finds exact matches, whereas here we will handle matches that
00922      * involve coercion, polymorphic type resolution, etc.
00923      */
00924     if (nunknowns < nargs)
00925     {
00926         Oid         known_type = UNKNOWNOID;
00927 
00928         for (i = 0; i < nargs; i++)
00929         {
00930             if (input_base_typeids[i] == UNKNOWNOID)
00931                 continue;
00932             if (known_type == UNKNOWNOID)       /* first known arg? */
00933                 known_type = input_base_typeids[i];
00934             else if (known_type != input_base_typeids[i])
00935             {
00936                 /* oops, not all match */
00937                 known_type = UNKNOWNOID;
00938                 break;
00939             }
00940         }
00941 
00942         if (known_type != UNKNOWNOID)
00943         {
00944             /* okay, just one known type, apply the heuristic */
00945             for (i = 0; i < nargs; i++)
00946                 input_base_typeids[i] = known_type;
00947             ncandidates = 0;
00948             last_candidate = NULL;
00949             for (current_candidate = candidates;
00950                  current_candidate != NULL;
00951                  current_candidate = current_candidate->next)
00952             {
00953                 current_typeids = current_candidate->args;
00954                 if (can_coerce_type(nargs, input_base_typeids, current_typeids,
00955                                     COERCION_IMPLICIT))
00956                 {
00957                     if (++ncandidates > 1)
00958                         break;  /* not unique, give up */
00959                     last_candidate = current_candidate;
00960                 }
00961             }
00962             if (ncandidates == 1)
00963             {
00964                 /* successfully identified a unique match */
00965                 last_candidate->next = NULL;
00966                 return last_candidate;
00967             }
00968         }
00969     }
00970 
00971     return NULL;                /* failed to select a best candidate */
00972 }   /* func_select_candidate() */
00973 
00974 
00975 /* func_get_detail()
00976  *
00977  * Find the named function in the system catalogs.
00978  *
00979  * Attempt to find the named function in the system catalogs with
00980  * arguments exactly as specified, so that the normal case (exact match)
00981  * is as quick as possible.
00982  *
00983  * If an exact match isn't found:
00984  *  1) check for possible interpretation as a type coercion request
00985  *  2) apply the ambiguous-function resolution rules
00986  *
00987  * Return values *funcid through *true_typeids receive info about the function.
00988  * If argdefaults isn't NULL, *argdefaults receives a list of any default
00989  * argument expressions that need to be added to the given arguments.
00990  *
00991  * When processing a named- or mixed-notation call (ie, fargnames isn't NIL),
00992  * the returned true_typeids and argdefaults are ordered according to the
00993  * call's argument ordering: first any positional arguments, then the named
00994  * arguments, then defaulted arguments (if needed and allowed by
00995  * expand_defaults).  Some care is needed if this information is to be compared
00996  * to the function's pg_proc entry, but in practice the caller can usually
00997  * just work with the call's argument ordering.
00998  *
00999  * We rely primarily on fargnames/nargs/argtypes as the argument description.
01000  * The actual expression node list is passed in fargs so that we can check
01001  * for type coercion of a constant.  Some callers pass fargs == NIL indicating
01002  * they don't need that check made.  Note also that when fargnames isn't NIL,
01003  * the fargs list must be passed if the caller wants actual argument position
01004  * information to be returned into the NamedArgExpr nodes.
01005  */
01006 FuncDetailCode
01007 func_get_detail(List *funcname,
01008                 List *fargs,
01009                 List *fargnames,
01010                 int nargs,
01011                 Oid *argtypes,
01012                 bool expand_variadic,
01013                 bool expand_defaults,
01014                 Oid *funcid,    /* return value */
01015                 Oid *rettype,   /* return value */
01016                 bool *retset,   /* return value */
01017                 int *nvargs,    /* return value */
01018                 Oid **true_typeids,     /* return value */
01019                 List **argdefaults)     /* optional return value */
01020 {
01021     FuncCandidateList raw_candidates;
01022     FuncCandidateList best_candidate;
01023 
01024     /* initialize output arguments to silence compiler warnings */
01025     *funcid = InvalidOid;
01026     *rettype = InvalidOid;
01027     *retset = false;
01028     *nvargs = 0;
01029     *true_typeids = NULL;
01030     if (argdefaults)
01031         *argdefaults = NIL;
01032 
01033     /* Get list of possible candidates from namespace search */
01034     raw_candidates = FuncnameGetCandidates(funcname, nargs, fargnames,
01035                                            expand_variadic, expand_defaults);
01036 
01037     /*
01038      * Quickly check if there is an exact match to the input datatypes (there
01039      * can be only one)
01040      */
01041     for (best_candidate = raw_candidates;
01042          best_candidate != NULL;
01043          best_candidate = best_candidate->next)
01044     {
01045         if (memcmp(argtypes, best_candidate->args, nargs * sizeof(Oid)) == 0)
01046             break;
01047     }
01048 
01049     if (best_candidate == NULL)
01050     {
01051         /*
01052          * If we didn't find an exact match, next consider the possibility
01053          * that this is really a type-coercion request: a single-argument
01054          * function call where the function name is a type name.  If so, and
01055          * if the coercion path is RELABELTYPE or COERCEVIAIO, then go ahead
01056          * and treat the "function call" as a coercion.
01057          *
01058          * This interpretation needs to be given higher priority than
01059          * interpretations involving a type coercion followed by a function
01060          * call, otherwise we can produce surprising results. For example, we
01061          * want "text(varchar)" to be interpreted as a simple coercion, not as
01062          * "text(name(varchar))" which the code below this point is entirely
01063          * capable of selecting.
01064          *
01065          * We also treat a coercion of a previously-unknown-type literal
01066          * constant to a specific type this way.
01067          *
01068          * The reason we reject COERCION_PATH_FUNC here is that we expect the
01069          * cast implementation function to be named after the target type.
01070          * Thus the function will be found by normal lookup if appropriate.
01071          *
01072          * The reason we reject COERCION_PATH_ARRAYCOERCE is mainly that you
01073          * can't write "foo[] (something)" as a function call.  In theory
01074          * someone might want to invoke it as "_foo (something)" but we have
01075          * never supported that historically, so we can insist that people
01076          * write it as a normal cast instead.
01077          *
01078          * We also reject the specific case of COERCEVIAIO for a composite
01079          * source type and a string-category target type.  This is a case that
01080          * find_coercion_pathway() allows by default, but experience has shown
01081          * that it's too commonly invoked by mistake.  So, again, insist that
01082          * people use cast syntax if they want to do that.
01083          *
01084          * NB: it's important that this code does not exceed what coerce_type
01085          * can do, because the caller will try to apply coerce_type if we
01086          * return FUNCDETAIL_COERCION.  If we return that result for something
01087          * coerce_type can't handle, we'll cause infinite recursion between
01088          * this module and coerce_type!
01089          */
01090         if (nargs == 1 && fargs != NIL && fargnames == NIL)
01091         {
01092             Oid         targetType = FuncNameAsType(funcname);
01093 
01094             if (OidIsValid(targetType))
01095             {
01096                 Oid         sourceType = argtypes[0];
01097                 Node       *arg1 = linitial(fargs);
01098                 bool        iscoercion;
01099 
01100                 if (sourceType == UNKNOWNOID && IsA(arg1, Const))
01101                 {
01102                     /* always treat typename('literal') as coercion */
01103                     iscoercion = true;
01104                 }
01105                 else
01106                 {
01107                     CoercionPathType cpathtype;
01108                     Oid         cfuncid;
01109 
01110                     cpathtype = find_coercion_pathway(targetType, sourceType,
01111                                                       COERCION_EXPLICIT,
01112                                                       &cfuncid);
01113                     switch (cpathtype)
01114                     {
01115                         case COERCION_PATH_RELABELTYPE:
01116                             iscoercion = true;
01117                             break;
01118                         case COERCION_PATH_COERCEVIAIO:
01119                             if ((sourceType == RECORDOID ||
01120                                  ISCOMPLEX(sourceType)) &&
01121                               TypeCategory(targetType) == TYPCATEGORY_STRING)
01122                                 iscoercion = false;
01123                             else
01124                                 iscoercion = true;
01125                             break;
01126                         default:
01127                             iscoercion = false;
01128                             break;
01129                     }
01130                 }
01131 
01132                 if (iscoercion)
01133                 {
01134                     /* Treat it as a type coercion */
01135                     *funcid = InvalidOid;
01136                     *rettype = targetType;
01137                     *retset = false;
01138                     *nvargs = 0;
01139                     *true_typeids = argtypes;
01140                     return FUNCDETAIL_COERCION;
01141                 }
01142             }
01143         }
01144 
01145         /*
01146          * didn't find an exact match, so now try to match up candidates...
01147          */
01148         if (raw_candidates != NULL)
01149         {
01150             FuncCandidateList current_candidates;
01151             int         ncandidates;
01152 
01153             ncandidates = func_match_argtypes(nargs,
01154                                               argtypes,
01155                                               raw_candidates,
01156                                               &current_candidates);
01157 
01158             /* one match only? then run with it... */
01159             if (ncandidates == 1)
01160                 best_candidate = current_candidates;
01161 
01162             /*
01163              * multiple candidates? then better decide or throw an error...
01164              */
01165             else if (ncandidates > 1)
01166             {
01167                 best_candidate = func_select_candidate(nargs,
01168                                                        argtypes,
01169                                                        current_candidates);
01170 
01171                 /*
01172                  * If we were able to choose a best candidate, we're done.
01173                  * Otherwise, ambiguous function call.
01174                  */
01175                 if (!best_candidate)
01176                     return FUNCDETAIL_MULTIPLE;
01177             }
01178         }
01179     }
01180 
01181     if (best_candidate)
01182     {
01183         HeapTuple   ftup;
01184         Form_pg_proc pform;
01185         FuncDetailCode result;
01186 
01187         /*
01188          * If processing named args or expanding variadics or defaults, the
01189          * "best candidate" might represent multiple equivalently good
01190          * functions; treat this case as ambiguous.
01191          */
01192         if (!OidIsValid(best_candidate->oid))
01193             return FUNCDETAIL_MULTIPLE;
01194 
01195         /*
01196          * We disallow VARIADIC with named arguments unless the last argument
01197          * (the one with VARIADIC attached) actually matched the variadic
01198          * parameter.  This is mere pedantry, really, but some folks insisted.
01199          */
01200         if (fargnames != NIL && !expand_variadic && nargs > 0 &&
01201             best_candidate->argnumbers[nargs - 1] != nargs - 1)
01202             return FUNCDETAIL_NOTFOUND;
01203 
01204         *funcid = best_candidate->oid;
01205         *nvargs = best_candidate->nvargs;
01206         *true_typeids = best_candidate->args;
01207 
01208         /*
01209          * If processing named args, return actual argument positions into
01210          * NamedArgExpr nodes in the fargs list.  This is a bit ugly but not
01211          * worth the extra notation needed to do it differently.
01212          */
01213         if (best_candidate->argnumbers != NULL)
01214         {
01215             int         i = 0;
01216             ListCell   *lc;
01217 
01218             foreach(lc, fargs)
01219             {
01220                 NamedArgExpr *na = (NamedArgExpr *) lfirst(lc);
01221 
01222                 if (IsA(na, NamedArgExpr))
01223                     na->argnumber = best_candidate->argnumbers[i];
01224                 i++;
01225             }
01226         }
01227 
01228         ftup = SearchSysCache1(PROCOID,
01229                                ObjectIdGetDatum(best_candidate->oid));
01230         if (!HeapTupleIsValid(ftup))    /* should not happen */
01231             elog(ERROR, "cache lookup failed for function %u",
01232                  best_candidate->oid);
01233         pform = (Form_pg_proc) GETSTRUCT(ftup);
01234         *rettype = pform->prorettype;
01235         *retset = pform->proretset;
01236         /* fetch default args if caller wants 'em */
01237         if (argdefaults && best_candidate->ndargs > 0)
01238         {
01239             Datum       proargdefaults;
01240             bool        isnull;
01241             char       *str;
01242             List       *defaults;
01243 
01244             /* shouldn't happen, FuncnameGetCandidates messed up */
01245             if (best_candidate->ndargs > pform->pronargdefaults)
01246                 elog(ERROR, "not enough default arguments");
01247 
01248             proargdefaults = SysCacheGetAttr(PROCOID, ftup,
01249                                              Anum_pg_proc_proargdefaults,
01250                                              &isnull);
01251             Assert(!isnull);
01252             str = TextDatumGetCString(proargdefaults);
01253             defaults = (List *) stringToNode(str);
01254             Assert(IsA(defaults, List));
01255             pfree(str);
01256 
01257             /* Delete any unused defaults from the returned list */
01258             if (best_candidate->argnumbers != NULL)
01259             {
01260                 /*
01261                  * This is a bit tricky in named notation, since the supplied
01262                  * arguments could replace any subset of the defaults.  We
01263                  * work by making a bitmapset of the argnumbers of defaulted
01264                  * arguments, then scanning the defaults list and selecting
01265                  * the needed items.  (This assumes that defaulted arguments
01266                  * should be supplied in their positional order.)
01267                  */
01268                 Bitmapset  *defargnumbers;
01269                 int        *firstdefarg;
01270                 List       *newdefaults;
01271                 ListCell   *lc;
01272                 int         i;
01273 
01274                 defargnumbers = NULL;
01275                 firstdefarg = &best_candidate->argnumbers[best_candidate->nargs - best_candidate->ndargs];
01276                 for (i = 0; i < best_candidate->ndargs; i++)
01277                     defargnumbers = bms_add_member(defargnumbers,
01278                                                    firstdefarg[i]);
01279                 newdefaults = NIL;
01280                 i = pform->pronargs - pform->pronargdefaults;
01281                 foreach(lc, defaults)
01282                 {
01283                     if (bms_is_member(i, defargnumbers))
01284                         newdefaults = lappend(newdefaults, lfirst(lc));
01285                     i++;
01286                 }
01287                 Assert(list_length(newdefaults) == best_candidate->ndargs);
01288                 bms_free(defargnumbers);
01289                 *argdefaults = newdefaults;
01290             }
01291             else
01292             {
01293                 /*
01294                  * Defaults for positional notation are lots easier; just
01295                  * remove any unwanted ones from the front.
01296                  */
01297                 int         ndelete;
01298 
01299                 ndelete = list_length(defaults) - best_candidate->ndargs;
01300                 while (ndelete-- > 0)
01301                     defaults = list_delete_first(defaults);
01302                 *argdefaults = defaults;
01303             }
01304         }
01305         if (pform->proisagg)
01306             result = FUNCDETAIL_AGGREGATE;
01307         else if (pform->proiswindow)
01308             result = FUNCDETAIL_WINDOWFUNC;
01309         else
01310             result = FUNCDETAIL_NORMAL;
01311         ReleaseSysCache(ftup);
01312         return result;
01313     }
01314 
01315     return FUNCDETAIL_NOTFOUND;
01316 }
01317 
01318 
01319 /*
01320  * make_fn_arguments()
01321  *
01322  * Given the actual argument expressions for a function, and the desired
01323  * input types for the function, add any necessary typecasting to the
01324  * expression tree.  Caller should already have verified that casting is
01325  * allowed.
01326  *
01327  * Caution: given argument list is modified in-place.
01328  *
01329  * As with coerce_type, pstate may be NULL if no special unknown-Param
01330  * processing is wanted.
01331  */
01332 void
01333 make_fn_arguments(ParseState *pstate,
01334                   List *fargs,
01335                   Oid *actual_arg_types,
01336                   Oid *declared_arg_types)
01337 {
01338     ListCell   *current_fargs;
01339     int         i = 0;
01340 
01341     foreach(current_fargs, fargs)
01342     {
01343         /* types don't match? then force coercion using a function call... */
01344         if (actual_arg_types[i] != declared_arg_types[i])
01345         {
01346             Node       *node = (Node *) lfirst(current_fargs);
01347 
01348             /*
01349              * If arg is a NamedArgExpr, coerce its input expr instead --- we
01350              * want the NamedArgExpr to stay at the top level of the list.
01351              */
01352             if (IsA(node, NamedArgExpr))
01353             {
01354                 NamedArgExpr *na = (NamedArgExpr *) node;
01355 
01356                 node = coerce_type(pstate,
01357                                    (Node *) na->arg,
01358                                    actual_arg_types[i],
01359                                    declared_arg_types[i], -1,
01360                                    COERCION_IMPLICIT,
01361                                    COERCE_IMPLICIT_CAST,
01362                                    -1);
01363                 na->arg = (Expr *) node;
01364             }
01365             else
01366             {
01367                 node = coerce_type(pstate,
01368                                    node,
01369                                    actual_arg_types[i],
01370                                    declared_arg_types[i], -1,
01371                                    COERCION_IMPLICIT,
01372                                    COERCE_IMPLICIT_CAST,
01373                                    -1);
01374                 lfirst(current_fargs) = node;
01375             }
01376         }
01377         i++;
01378     }
01379 }
01380 
01381 /*
01382  * FuncNameAsType -
01383  *    convenience routine to see if a function name matches a type name
01384  *
01385  * Returns the OID of the matching type, or InvalidOid if none.  We ignore
01386  * shell types and complex types.
01387  */
01388 static Oid
01389 FuncNameAsType(List *funcname)
01390 {
01391     Oid         result;
01392     Type        typtup;
01393 
01394     typtup = LookupTypeName(NULL, makeTypeNameFromNameList(funcname), NULL);
01395     if (typtup == NULL)
01396         return InvalidOid;
01397 
01398     if (((Form_pg_type) GETSTRUCT(typtup))->typisdefined &&
01399         !OidIsValid(typeTypeRelid(typtup)))
01400         result = typeTypeId(typtup);
01401     else
01402         result = InvalidOid;
01403 
01404     ReleaseSysCache(typtup);
01405     return result;
01406 }
01407 
01408 /*
01409  * ParseComplexProjection -
01410  *    handles function calls with a single argument that is of complex type.
01411  *    If the function call is actually a column projection, return a suitably
01412  *    transformed expression tree.  If not, return NULL.
01413  */
01414 static Node *
01415 ParseComplexProjection(ParseState *pstate, char *funcname, Node *first_arg,
01416                        int location)
01417 {
01418     TupleDesc   tupdesc;
01419     int         i;
01420 
01421     /*
01422      * Special case for whole-row Vars so that we can resolve (foo.*).bar even
01423      * when foo is a reference to a subselect, join, or RECORD function. A
01424      * bonus is that we avoid generating an unnecessary FieldSelect; our
01425      * result can omit the whole-row Var and just be a Var for the selected
01426      * field.
01427      *
01428      * This case could be handled by expandRecordVariable, but it's more
01429      * efficient to do it this way when possible.
01430      */
01431     if (IsA(first_arg, Var) &&
01432         ((Var *) first_arg)->varattno == InvalidAttrNumber)
01433     {
01434         RangeTblEntry *rte;
01435 
01436         rte = GetRTEByRangeTablePosn(pstate,
01437                                      ((Var *) first_arg)->varno,
01438                                      ((Var *) first_arg)->varlevelsup);
01439         /* Return a Var if funcname matches a column, else NULL */
01440         return scanRTEForColumn(pstate, rte, funcname, location);
01441     }
01442 
01443     /*
01444      * Else do it the hard way with get_expr_result_type().
01445      *
01446      * If it's a Var of type RECORD, we have to work even harder: we have to
01447      * find what the Var refers to, and pass that to get_expr_result_type.
01448      * That task is handled by expandRecordVariable().
01449      */
01450     if (IsA(first_arg, Var) &&
01451         ((Var *) first_arg)->vartype == RECORDOID)
01452         tupdesc = expandRecordVariable(pstate, (Var *) first_arg, 0);
01453     else if (get_expr_result_type(first_arg, NULL, &tupdesc) != TYPEFUNC_COMPOSITE)
01454         return NULL;            /* unresolvable RECORD type */
01455     Assert(tupdesc);
01456 
01457     for (i = 0; i < tupdesc->natts; i++)
01458     {
01459         Form_pg_attribute att = tupdesc->attrs[i];
01460 
01461         if (strcmp(funcname, NameStr(att->attname)) == 0 &&
01462             !att->attisdropped)
01463         {
01464             /* Success, so generate a FieldSelect expression */
01465             FieldSelect *fselect = makeNode(FieldSelect);
01466 
01467             fselect->arg = (Expr *) first_arg;
01468             fselect->fieldnum = i + 1;
01469             fselect->resulttype = att->atttypid;
01470             fselect->resulttypmod = att->atttypmod;
01471             /* save attribute's collation for parse_collate.c */
01472             fselect->resultcollid = att->attcollation;
01473             return (Node *) fselect;
01474         }
01475     }
01476 
01477     return NULL;                /* funcname does not match any column */
01478 }
01479 
01480 /*
01481  * funcname_signature_string
01482  *      Build a string representing a function name, including arg types.
01483  *      The result is something like "foo(integer)".
01484  *
01485  * If argnames isn't NIL, it is a list of C strings representing the actual
01486  * arg names for the last N arguments.  This must be considered part of the
01487  * function signature too, when dealing with named-notation function calls.
01488  *
01489  * This is typically used in the construction of function-not-found error
01490  * messages.
01491  */
01492 const char *
01493 funcname_signature_string(const char *funcname, int nargs,
01494                           List *argnames, const Oid *argtypes)
01495 {
01496     StringInfoData argbuf;
01497     int         numposargs;
01498     ListCell   *lc;
01499     int         i;
01500 
01501     initStringInfo(&argbuf);
01502 
01503     appendStringInfo(&argbuf, "%s(", funcname);
01504 
01505     numposargs = nargs - list_length(argnames);
01506     lc = list_head(argnames);
01507 
01508     for (i = 0; i < nargs; i++)
01509     {
01510         if (i)
01511             appendStringInfoString(&argbuf, ", ");
01512         if (i >= numposargs)
01513         {
01514             appendStringInfo(&argbuf, "%s := ", (char *) lfirst(lc));
01515             lc = lnext(lc);
01516         }
01517         appendStringInfoString(&argbuf, format_type_be(argtypes[i]));
01518     }
01519 
01520     appendStringInfoChar(&argbuf, ')');
01521 
01522     return argbuf.data;         /* return palloc'd string buffer */
01523 }
01524 
01525 /*
01526  * func_signature_string
01527  *      As above, but function name is passed as a qualified name list.
01528  */
01529 const char *
01530 func_signature_string(List *funcname, int nargs,
01531                       List *argnames, const Oid *argtypes)
01532 {
01533     return funcname_signature_string(NameListToString(funcname),
01534                                      nargs, argnames, argtypes);
01535 }
01536 
01537 /*
01538  * LookupFuncName
01539  *      Given a possibly-qualified function name and a set of argument types,
01540  *      look up the function.
01541  *
01542  * If the function name is not schema-qualified, it is sought in the current
01543  * namespace search path.
01544  *
01545  * If the function is not found, we return InvalidOid if noError is true,
01546  * else raise an error.
01547  */
01548 Oid
01549 LookupFuncName(List *funcname, int nargs, const Oid *argtypes, bool noError)
01550 {
01551     FuncCandidateList clist;
01552 
01553     clist = FuncnameGetCandidates(funcname, nargs, NIL, false, false);
01554 
01555     while (clist)
01556     {
01557         if (memcmp(argtypes, clist->args, nargs * sizeof(Oid)) == 0)
01558             return clist->oid;
01559         clist = clist->next;
01560     }
01561 
01562     if (!noError)
01563         ereport(ERROR,
01564                 (errcode(ERRCODE_UNDEFINED_FUNCTION),
01565                  errmsg("function %s does not exist",
01566                         func_signature_string(funcname, nargs,
01567                                               NIL, argtypes))));
01568 
01569     return InvalidOid;
01570 }
01571 
01572 /*
01573  * LookupTypeNameOid
01574  *      Convenience routine to look up a type, silently accepting shell types
01575  */
01576 static Oid
01577 LookupTypeNameOid(const TypeName *typename)
01578 {
01579     Oid         result;
01580     Type        typtup;
01581 
01582     typtup = LookupTypeName(NULL, typename, NULL);
01583     if (typtup == NULL)
01584         ereport(ERROR,
01585                 (errcode(ERRCODE_UNDEFINED_OBJECT),
01586                  errmsg("type \"%s\" does not exist",
01587                         TypeNameToString(typename))));
01588     result = typeTypeId(typtup);
01589     ReleaseSysCache(typtup);
01590     return result;
01591 }
01592 
01593 /*
01594  * LookupFuncNameTypeNames
01595  *      Like LookupFuncName, but the argument types are specified by a
01596  *      list of TypeName nodes.
01597  */
01598 Oid
01599 LookupFuncNameTypeNames(List *funcname, List *argtypes, bool noError)
01600 {
01601     Oid         argoids[FUNC_MAX_ARGS];
01602     int         argcount;
01603     int         i;
01604     ListCell   *args_item;
01605 
01606     argcount = list_length(argtypes);
01607     if (argcount > FUNC_MAX_ARGS)
01608         ereport(ERROR,
01609                 (errcode(ERRCODE_TOO_MANY_ARGUMENTS),
01610                  errmsg_plural("functions cannot have more than %d argument",
01611                                "functions cannot have more than %d arguments",
01612                                FUNC_MAX_ARGS,
01613                                FUNC_MAX_ARGS)));
01614 
01615     args_item = list_head(argtypes);
01616     for (i = 0; i < argcount; i++)
01617     {
01618         TypeName   *t = (TypeName *) lfirst(args_item);
01619 
01620         argoids[i] = LookupTypeNameOid(t);
01621         args_item = lnext(args_item);
01622     }
01623 
01624     return LookupFuncName(funcname, argcount, argoids, noError);
01625 }
01626 
01627 /*
01628  * LookupAggNameTypeNames
01629  *      Find an aggregate function given a name and list of TypeName nodes.
01630  *
01631  * This is almost like LookupFuncNameTypeNames, but the error messages refer
01632  * to aggregates rather than plain functions, and we verify that the found
01633  * function really is an aggregate.
01634  */
01635 Oid
01636 LookupAggNameTypeNames(List *aggname, List *argtypes, bool noError)
01637 {
01638     Oid         argoids[FUNC_MAX_ARGS];
01639     int         argcount;
01640     int         i;
01641     ListCell   *lc;
01642     Oid         oid;
01643     HeapTuple   ftup;
01644     Form_pg_proc pform;
01645 
01646     argcount = list_length(argtypes);
01647     if (argcount > FUNC_MAX_ARGS)
01648         ereport(ERROR,
01649                 (errcode(ERRCODE_TOO_MANY_ARGUMENTS),
01650                  errmsg_plural("functions cannot have more than %d argument",
01651                                "functions cannot have more than %d arguments",
01652                                FUNC_MAX_ARGS,
01653                                FUNC_MAX_ARGS)));
01654 
01655     i = 0;
01656     foreach(lc, argtypes)
01657     {
01658         TypeName   *t = (TypeName *) lfirst(lc);
01659 
01660         argoids[i] = LookupTypeNameOid(t);
01661         i++;
01662     }
01663 
01664     oid = LookupFuncName(aggname, argcount, argoids, true);
01665 
01666     if (!OidIsValid(oid))
01667     {
01668         if (noError)
01669             return InvalidOid;
01670         if (argcount == 0)
01671             ereport(ERROR,
01672                     (errcode(ERRCODE_UNDEFINED_FUNCTION),
01673                      errmsg("aggregate %s(*) does not exist",
01674                             NameListToString(aggname))));
01675         else
01676             ereport(ERROR,
01677                     (errcode(ERRCODE_UNDEFINED_FUNCTION),
01678                      errmsg("aggregate %s does not exist",
01679                             func_signature_string(aggname, argcount,
01680                                                   NIL, argoids))));
01681     }
01682 
01683     /* Make sure it's an aggregate */
01684     ftup = SearchSysCache1(PROCOID, ObjectIdGetDatum(oid));
01685     if (!HeapTupleIsValid(ftup))    /* should not happen */
01686         elog(ERROR, "cache lookup failed for function %u", oid);
01687     pform = (Form_pg_proc) GETSTRUCT(ftup);
01688 
01689     if (!pform->proisagg)
01690     {
01691         ReleaseSysCache(ftup);
01692         if (noError)
01693             return InvalidOid;
01694         /* we do not use the (*) notation for functions... */
01695         ereport(ERROR,
01696                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
01697                  errmsg("function %s is not an aggregate",
01698                         func_signature_string(aggname, argcount,
01699                                               NIL, argoids))));
01700     }
01701 
01702     ReleaseSysCache(ftup);
01703 
01704     return oid;
01705 }