OSDN Git Service

Update copyright for the year 2010.
[pg-rex/syncrep.git] / src / backend / parser / parse_func.c
1 /*-------------------------------------------------------------------------
2  *
3  * parse_func.c
4  *              handle function calls in parser
5  *
6  * Portions Copyright (c) 1996-2010, PostgreSQL Global Development Group
7  * Portions Copyright (c) 1994, Regents of the University of California
8  *
9  *
10  * IDENTIFICATION
11  *        $PostgreSQL: pgsql/src/backend/parser/parse_func.c,v 1.220 2010/01/02 16:57:49 momjian Exp $
12  *
13  *-------------------------------------------------------------------------
14  */
15 #include "postgres.h"
16
17 #include "catalog/pg_proc.h"
18 #include "catalog/pg_type.h"
19 #include "funcapi.h"
20 #include "nodes/makefuncs.h"
21 #include "nodes/nodeFuncs.h"
22 #include "parser/parse_agg.h"
23 #include "parser/parse_coerce.h"
24 #include "parser/parse_func.h"
25 #include "parser/parse_relation.h"
26 #include "parser/parse_target.h"
27 #include "parser/parse_type.h"
28 #include "utils/builtins.h"
29 #include "utils/lsyscache.h"
30 #include "utils/syscache.h"
31
32
33 static Oid      FuncNameAsType(List *funcname);
34 static Node *ParseComplexProjection(ParseState *pstate, char *funcname,
35                                            Node *first_arg, int location);
36
37
38 /*
39  *      Parse a function call
40  *
41  *      For historical reasons, Postgres tries to treat the notations tab.col
42  *      and col(tab) as equivalent: if a single-argument function call has an
43  *      argument of complex type and the (unqualified) function name matches
44  *      any attribute of the type, we take it as a column projection.  Conversely
45  *      a function of a single complex-type argument can be written like a
46  *      column reference, allowing functions to act like computed columns.
47  *
48  *      Hence, both cases come through here.  The is_column parameter tells us
49  *      which syntactic construct is actually being dealt with, but this is
50  *      intended to be used only to deliver an appropriate error message,
51  *      not to affect the semantics.  When is_column is true, we should have
52  *      a single argument (the putative table), unqualified function name
53  *      equal to the column name, and no aggregate or variadic decoration.
54  *      Also, when is_column is true, we return NULL on failure rather than
55  *      reporting a no-such-function error.
56  *
57  *      The argument expressions (in fargs) must have been transformed already.
58  *      But the agg_order expressions, if any, have not been.
59  */
60 Node *
61 ParseFuncOrColumn(ParseState *pstate, List *funcname, List *fargs,
62                                   List *agg_order, bool agg_star, bool agg_distinct,
63                                   bool func_variadic,
64                                   WindowDef *over, bool is_column, int location)
65 {
66         Oid                     rettype;
67         Oid                     funcid;
68         ListCell   *l;
69         ListCell   *nextl;
70         Node       *first_arg = NULL;
71         int                     nargs;
72         int                     nargsplusdefs;
73         Oid                     actual_arg_types[FUNC_MAX_ARGS];
74         Oid                *declared_arg_types;
75         List       *argnames;
76         List       *argdefaults;
77         Node       *retval;
78         bool            retset;
79         int                     nvargs;
80         FuncDetailCode fdresult;
81
82         /*
83          * Most of the rest of the parser just assumes that functions do not have
84          * more than FUNC_MAX_ARGS parameters.  We have to test here to protect
85          * against array overruns, etc.  Of course, this may not be a function,
86          * but the test doesn't hurt.
87          */
88         if (list_length(fargs) > FUNC_MAX_ARGS)
89                 ereport(ERROR,
90                                 (errcode(ERRCODE_TOO_MANY_ARGUMENTS),
91                          errmsg_plural("cannot pass more than %d argument to a function",
92                                                    "cannot pass more than %d arguments to a function",
93                                                    FUNC_MAX_ARGS,
94                                                    FUNC_MAX_ARGS),
95                                  parser_errposition(pstate, location)));
96
97         /*
98          * Extract arg type info in preparation for function lookup.
99          *
100          * If any arguments are Param markers of type VOID, we discard them from
101          * the parameter list.  This is a hack to allow the JDBC driver to not
102          * have to distinguish "input" and "output" parameter symbols while
103          * parsing function-call constructs.  We can't use foreach() because we
104          * may modify the list ...
105          */
106         nargs = 0;
107         for (l = list_head(fargs); l != NULL; l = nextl)
108         {
109                 Node       *arg = lfirst(l);
110                 Oid                     argtype = exprType(arg);
111
112                 nextl = lnext(l);
113
114                 if (argtype == VOIDOID && IsA(arg, Param) &&!is_column)
115                 {
116                         fargs = list_delete_ptr(fargs, arg);
117                         continue;
118                 }
119
120                 actual_arg_types[nargs++] = argtype;
121         }
122
123         /*
124          * Check for named arguments; if there are any, build a list of names.
125          *
126          * We allow mixed notation (some named and some not), but only with all
127          * the named parameters after all the unnamed ones.  So the name list
128          * corresponds to the last N actual parameters and we don't need any
129          * extra bookkeeping to match things up.
130          */
131         argnames = NIL;
132         foreach(l, fargs)
133         {
134                 Node   *arg = lfirst(l);
135
136                 if (IsA(arg, NamedArgExpr))
137                 {
138                         NamedArgExpr *na = (NamedArgExpr *) arg;
139                         ListCell   *lc;
140
141                         /* Reject duplicate arg names */
142                         foreach(lc, argnames)
143                         {
144                                 if (strcmp(na->name, (char *) lfirst(lc)) == 0)
145                                         ereport(ERROR,
146                                                         (errcode(ERRCODE_SYNTAX_ERROR),
147                                                          errmsg("argument name \"%s\" used more than once",
148                                                                         na->name),
149                                                          parser_errposition(pstate, na->location)));
150                         }
151                         argnames = lappend(argnames, na->name);
152                 }
153                 else
154                 {
155                         if (argnames != NIL)
156                                 ereport(ERROR,
157                                                 (errcode(ERRCODE_SYNTAX_ERROR),
158                                                  errmsg("positional argument cannot follow named argument"),
159                                                  parser_errposition(pstate, exprLocation(arg))));
160                 }
161         }
162
163         if (fargs)
164         {
165                 first_arg = linitial(fargs);
166                 Assert(first_arg != NULL);
167         }
168
169         /*
170          * Check for column projection: if function has one argument, and that
171          * argument is of complex type, and function name is not qualified, then
172          * the "function call" could be a projection.  We also check that there
173          * wasn't any aggregate or variadic decoration, nor an argument name.
174          */
175         if (nargs == 1 && agg_order == NIL && !agg_star && !agg_distinct &&
176                 over == NULL && !func_variadic && argnames == NIL &&
177                 list_length(funcname) == 1)
178         {
179                 Oid                     argtype = actual_arg_types[0];
180
181                 if (argtype == RECORDOID || ISCOMPLEX(argtype))
182                 {
183                         retval = ParseComplexProjection(pstate,
184                                                                                         strVal(linitial(funcname)),
185                                                                                         first_arg,
186                                                                                         location);
187                         if (retval)
188                                 return retval;
189
190                         /*
191                          * If ParseComplexProjection doesn't recognize it as a projection,
192                          * just press on.
193                          */
194                 }
195         }
196
197         /*
198          * Okay, it's not a column projection, so it must really be a function.
199          * func_get_detail looks up the function in the catalogs, does
200          * disambiguation for polymorphic functions, handles inheritance, and
201          * returns the funcid and type and set or singleton status of the
202          * function's return value.  It also returns the true argument types to
203          * the function.
204          *
205          * Note: for a named-notation or variadic function call, the reported
206          * "true" types aren't really what is in pg_proc: the types are reordered
207          * to match the given argument order of named arguments, and a variadic
208          * argument is replaced by a suitable number of copies of its element
209          * type.  We'll fix up the variadic case below.  We may also have to deal
210          * with default arguments.
211          */
212         fdresult = func_get_detail(funcname, fargs, argnames, nargs,
213                                                            actual_arg_types,
214                                                            !func_variadic, true,
215                                                            &funcid, &rettype, &retset, &nvargs,
216                                                            &declared_arg_types, &argdefaults);
217         if (fdresult == FUNCDETAIL_COERCION)
218         {
219                 /*
220                  * We interpreted it as a type coercion. coerce_type can handle these
221                  * cases, so why duplicate code...
222                  */
223                 return coerce_type(pstate, linitial(fargs),
224                                                    actual_arg_types[0], rettype, -1,
225                                                    COERCION_EXPLICIT, COERCE_EXPLICIT_CALL, location);
226         }
227         else if (fdresult == FUNCDETAIL_NORMAL)
228         {
229                 /*
230                  * Normal function found; was there anything indicating it must be an
231                  * aggregate?
232                  */
233                 if (agg_star)
234                         ereport(ERROR,
235                                         (errcode(ERRCODE_WRONG_OBJECT_TYPE),
236                            errmsg("%s(*) specified, but %s is not an aggregate function",
237                                           NameListToString(funcname),
238                                           NameListToString(funcname)),
239                                          parser_errposition(pstate, location)));
240                 if (agg_distinct)
241                         ereport(ERROR,
242                                         (errcode(ERRCODE_WRONG_OBJECT_TYPE),
243                         errmsg("DISTINCT specified, but %s is not an aggregate function",
244                                    NameListToString(funcname)),
245                                          parser_errposition(pstate, location)));
246                 if (agg_order != NIL)
247                         ereport(ERROR,
248                                         (errcode(ERRCODE_WRONG_OBJECT_TYPE),
249                            errmsg("ORDER BY specified, but %s is not an aggregate function",
250                                           NameListToString(funcname)),
251                                          parser_errposition(pstate, location)));
252                 if (over)
253                         ereport(ERROR,
254                                         (errcode(ERRCODE_WRONG_OBJECT_TYPE),
255                                          errmsg("OVER specified, but %s is not a window function nor an aggregate function",
256                                                         NameListToString(funcname)),
257                                          parser_errposition(pstate, location)));
258         }
259         else if (!(fdresult == FUNCDETAIL_AGGREGATE ||
260                            fdresult == FUNCDETAIL_WINDOWFUNC))
261         {
262                 /*
263                  * Oops.  Time to die.
264                  *
265                  * If we are dealing with the attribute notation rel.function,
266                  * let the caller handle failure.
267                  */
268                 if (is_column)
269                         return NULL;
270
271                 /*
272                  * Else generate a detailed complaint for a function
273                  */
274                 if (fdresult == FUNCDETAIL_MULTIPLE)
275                         ereport(ERROR,
276                                         (errcode(ERRCODE_AMBIGUOUS_FUNCTION),
277                                          errmsg("function %s is not unique",
278                                                         func_signature_string(funcname, nargs, argnames,
279                                                                                                   actual_arg_types)),
280                                          errhint("Could not choose a best candidate function. "
281                                                          "You might need to add explicit type casts."),
282                                          parser_errposition(pstate, location)));
283                 else
284                         ereport(ERROR,
285                                         (errcode(ERRCODE_UNDEFINED_FUNCTION),
286                                          errmsg("function %s does not exist",
287                                                         func_signature_string(funcname, nargs, argnames,
288                                                                                                   actual_arg_types)),
289                         errhint("No function matches the given name and argument types. "
290                                         "You might need to add explicit type casts."),
291                                          parser_errposition(pstate, location)));
292         }
293
294         /*
295          * If there are default arguments, we have to include their types in
296          * actual_arg_types for the purpose of checking generic type consistency.
297          * However, we do NOT put them into the generated parse node, because
298          * their actual values might change before the query gets run.  The
299          * planner has to insert the up-to-date values at plan time.
300          */
301         nargsplusdefs = nargs;
302         foreach(l, argdefaults)
303         {
304                 Node       *expr = (Node *) lfirst(l);
305
306                 /* probably shouldn't happen ... */
307                 if (nargsplusdefs >= FUNC_MAX_ARGS)
308                         ereport(ERROR,
309                                         (errcode(ERRCODE_TOO_MANY_ARGUMENTS),
310                          errmsg_plural("cannot pass more than %d argument to a function",
311                                                    "cannot pass more than %d arguments to a function",
312                                                    FUNC_MAX_ARGS,
313                                                    FUNC_MAX_ARGS),
314                                          parser_errposition(pstate, location)));
315
316                 actual_arg_types[nargsplusdefs++] = exprType(expr);
317         }
318
319         /*
320          * enforce consistency with polymorphic argument and return types,
321          * possibly adjusting return type or declared_arg_types (which will be
322          * used as the cast destination by make_fn_arguments)
323          */
324         rettype = enforce_generic_type_consistency(actual_arg_types,
325                                                                                            declared_arg_types,
326                                                                                            nargsplusdefs,
327                                                                                            rettype,
328                                                                                            false);
329
330         /* perform the necessary typecasting of arguments */
331         make_fn_arguments(pstate, fargs, actual_arg_types, declared_arg_types);
332
333         /*
334          * If it's a variadic function call, transform the last nvargs arguments
335          * into an array --- unless it's an "any" variadic.
336          */
337         if (nvargs > 0 && declared_arg_types[nargs - 1] != ANYOID)
338         {
339                 ArrayExpr  *newa = makeNode(ArrayExpr);
340                 int                     non_var_args = nargs - nvargs;
341                 List       *vargs;
342
343                 Assert(non_var_args >= 0);
344                 vargs = list_copy_tail(fargs, non_var_args);
345                 fargs = list_truncate(fargs, non_var_args);
346
347                 newa->elements = vargs;
348                 /* assume all the variadic arguments were coerced to the same type */
349                 newa->element_typeid = exprType((Node *) linitial(vargs));
350                 newa->array_typeid = get_array_type(newa->element_typeid);
351                 if (!OidIsValid(newa->array_typeid))
352                         ereport(ERROR,
353                                         (errcode(ERRCODE_UNDEFINED_OBJECT),
354                                          errmsg("could not find array type for data type %s",
355                                                         format_type_be(newa->element_typeid)),
356                                   parser_errposition(pstate, exprLocation((Node *) vargs))));
357                 newa->multidims = false;
358                 newa->location = exprLocation((Node *) vargs);
359
360                 fargs = lappend(fargs, newa);
361         }
362
363         /* build the appropriate output structure */
364         if (fdresult == FUNCDETAIL_NORMAL)
365         {
366                 FuncExpr   *funcexpr = makeNode(FuncExpr);
367
368                 funcexpr->funcid = funcid;
369                 funcexpr->funcresulttype = rettype;
370                 funcexpr->funcretset = retset;
371                 funcexpr->funcformat = COERCE_EXPLICIT_CALL;
372                 funcexpr->args = fargs;
373                 funcexpr->location = location;
374
375                 retval = (Node *) funcexpr;
376         }
377         else if (fdresult == FUNCDETAIL_AGGREGATE && !over)
378         {
379                 /* aggregate function */
380                 Aggref     *aggref = makeNode(Aggref);
381
382                 aggref->aggfnoid = funcid;
383                 aggref->aggtype = rettype;
384                 /* args and aggorder will be modified by transformAggregateCall */
385                 aggref->args = fargs;
386                 aggref->aggorder = agg_order;
387                 /* aggdistinct will be set by transformAggregateCall */
388                 aggref->aggstar = agg_star;
389                 /* agglevelsup will be set by transformAggregateCall */
390                 aggref->location = location;
391
392                 /*
393                  * Reject attempt to call a parameterless aggregate without (*)
394                  * syntax.      This is mere pedantry but some folks insisted ...
395                  */
396                 if (fargs == NIL && !agg_star)
397                         ereport(ERROR,
398                                         (errcode(ERRCODE_WRONG_OBJECT_TYPE),
399                                          errmsg("%s(*) must be used to call a parameterless aggregate function",
400                                                         NameListToString(funcname)),
401                                          parser_errposition(pstate, location)));
402
403                 if (retset)
404                         ereport(ERROR,
405                                         (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
406                                          errmsg("aggregates cannot return sets"),
407                                          parser_errposition(pstate, location)));
408
409                 /*
410                  * Currently it's not possible to define an aggregate with named
411                  * arguments, so this case should be impossible.  Check anyway
412                  * because the planner and executor wouldn't cope with NamedArgExprs
413                  * in an Aggref node.
414                  */
415                 if (argnames != NIL)
416                         ereport(ERROR,
417                                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
418                                          errmsg("aggregates cannot use named arguments"),
419                                          parser_errposition(pstate, location)));
420
421                 /* parse_agg.c does additional aggregate-specific processing */
422                 transformAggregateCall(pstate, aggref, agg_distinct);
423
424                 retval = (Node *) aggref;
425         }
426         else
427         {
428                 /* window function */
429                 WindowFunc *wfunc = makeNode(WindowFunc);
430
431                 /*
432                  * True window functions must be called with a window definition.
433                  */
434                 if (!over)
435                         ereport(ERROR,
436                                         (errcode(ERRCODE_WRONG_OBJECT_TYPE),
437                                          errmsg("window function call requires an OVER clause"),
438                                          parser_errposition(pstate, location)));
439
440                 wfunc->winfnoid = funcid;
441                 wfunc->wintype = rettype;
442                 wfunc->args = fargs;
443                 /* winref will be set by transformWindowFuncCall */
444                 wfunc->winstar = agg_star;
445                 wfunc->winagg = (fdresult == FUNCDETAIL_AGGREGATE);
446                 wfunc->location = location;
447
448                 /*
449                  * agg_star is allowed for aggregate functions but distinct isn't
450                  */
451                 if (agg_distinct)
452                         ereport(ERROR,
453                                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
454                                   errmsg("DISTINCT is not implemented for window functions"),
455                                          parser_errposition(pstate, location)));
456
457                 /*
458                  * Reject attempt to call a parameterless aggregate without (*)
459                  * syntax.      This is mere pedantry but some folks insisted ...
460                  */
461                 if (wfunc->winagg && fargs == NIL && !agg_star)
462                         ereport(ERROR,
463                                         (errcode(ERRCODE_WRONG_OBJECT_TYPE),
464                                          errmsg("%s(*) must be used to call a parameterless aggregate function",
465                                                         NameListToString(funcname)),
466                                          parser_errposition(pstate, location)));
467
468                 /*
469                  * ordered aggs not allowed in windows yet
470                  */
471                 if (agg_order != NIL)
472                         ereport(ERROR,
473                                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
474                                          errmsg("aggregate ORDER BY is not implemented for window functions"),
475                                          parser_errposition(pstate, location)));
476
477                 if (retset)
478                         ereport(ERROR,
479                                         (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
480                                          errmsg("window functions cannot return sets"),
481                                          parser_errposition(pstate, location)));
482
483                 /*
484                  * We might want to support this later, but for now reject it
485                  * because the planner and executor wouldn't cope with NamedArgExprs
486                  * in a WindowFunc node.
487                  */
488                 if (argnames != NIL)
489                         ereport(ERROR,
490                                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
491                                          errmsg("window functions cannot use named arguments"),
492                                          parser_errposition(pstate, location)));
493
494                 /* parse_agg.c does additional window-func-specific processing */
495                 transformWindowFuncCall(pstate, wfunc, over);
496
497                 retval = (Node *) wfunc;
498         }
499
500         return retval;
501 }
502
503
504 /* func_match_argtypes()
505  *
506  * Given a list of candidate functions (having the right name and number
507  * of arguments) and an array of input datatype OIDs, produce a shortlist of
508  * those candidates that actually accept the input datatypes (either exactly
509  * or by coercion), and return the number of such candidates.
510  *
511  * Note that can_coerce_type will assume that UNKNOWN inputs are coercible to
512  * anything, so candidates will not be eliminated on that basis.
513  *
514  * NB: okay to modify input list structure, as long as we find at least
515  * one match.  If no match at all, the list must remain unmodified.
516  */
517 int
518 func_match_argtypes(int nargs,
519                                         Oid *input_typeids,
520                                         FuncCandidateList raw_candidates,
521                                         FuncCandidateList *candidates)          /* return value */
522 {
523         FuncCandidateList current_candidate;
524         FuncCandidateList next_candidate;
525         int                     ncandidates = 0;
526
527         *candidates = NULL;
528
529         for (current_candidate = raw_candidates;
530                  current_candidate != NULL;
531                  current_candidate = next_candidate)
532         {
533                 next_candidate = current_candidate->next;
534                 if (can_coerce_type(nargs, input_typeids, current_candidate->args,
535                                                         COERCION_IMPLICIT))
536                 {
537                         current_candidate->next = *candidates;
538                         *candidates = current_candidate;
539                         ncandidates++;
540                 }
541         }
542
543         return ncandidates;
544 }       /* func_match_argtypes() */
545
546
547 /* func_select_candidate()
548  *              Given the input argtype array and more than one candidate
549  *              for the function, attempt to resolve the conflict.
550  *
551  * Returns the selected candidate if the conflict can be resolved,
552  * otherwise returns NULL.
553  *
554  * Note that the caller has already determined that there is no candidate
555  * exactly matching the input argtypes, and has pruned away any "candidates"
556  * that aren't actually coercion-compatible with the input types.
557  *
558  * This is also used for resolving ambiguous operator references.  Formerly
559  * parse_oper.c had its own, essentially duplicate code for the purpose.
560  * The following comments (formerly in parse_oper.c) are kept to record some
561  * of the history of these heuristics.
562  *
563  * OLD COMMENTS:
564  *
565  * This routine is new code, replacing binary_oper_select_candidate()
566  * which dates from v4.2/v1.0.x days. It tries very hard to match up
567  * operators with types, including allowing type coercions if necessary.
568  * The important thing is that the code do as much as possible,
569  * while _never_ doing the wrong thing, where "the wrong thing" would
570  * be returning an operator when other better choices are available,
571  * or returning an operator which is a non-intuitive possibility.
572  * - thomas 1998-05-21
573  *
574  * The comments below came from binary_oper_select_candidate(), and
575  * illustrate the issues and choices which are possible:
576  * - thomas 1998-05-20
577  *
578  * current wisdom holds that the default operator should be one in which
579  * both operands have the same type (there will only be one such
580  * operator)
581  *
582  * 7.27.93 - I have decided not to do this; it's too hard to justify, and
583  * it's easy enough to typecast explicitly - avi
584  * [the rest of this routine was commented out since then - ay]
585  *
586  * 6/23/95 - I don't complete agree with avi. In particular, casting
587  * floats is a pain for users. Whatever the rationale behind not doing
588  * this is, I need the following special case to work.
589  *
590  * In the WHERE clause of a query, if a float is specified without
591  * quotes, we treat it as float8. I added the float48* operators so
592  * that we can operate on float4 and float8. But now we have more than
593  * one matching operator if the right arg is unknown (eg. float
594  * specified with quotes). This break some stuff in the regression
595  * test where there are floats in quotes not properly casted. Below is
596  * the solution. In addition to requiring the operator operates on the
597  * same type for both operands [as in the code Avi originally
598  * commented out], we also require that the operators be equivalent in
599  * some sense. (see equivalentOpersAfterPromotion for details.)
600  * - ay 6/95
601  */
602 FuncCandidateList
603 func_select_candidate(int nargs,
604                                           Oid *input_typeids,
605                                           FuncCandidateList candidates)
606 {
607         FuncCandidateList current_candidate;
608         FuncCandidateList last_candidate;
609         Oid                *current_typeids;
610         Oid                     current_type;
611         int                     i;
612         int                     ncandidates;
613         int                     nbestMatch,
614                                 nmatch;
615         Oid                     input_base_typeids[FUNC_MAX_ARGS];
616         TYPCATEGORY slot_category[FUNC_MAX_ARGS],
617                                 current_category;
618         bool            current_is_preferred;
619         bool            slot_has_preferred_type[FUNC_MAX_ARGS];
620         bool            resolved_unknowns;
621
622         /* protect local fixed-size arrays */
623         if (nargs > FUNC_MAX_ARGS)
624                 ereport(ERROR,
625                                 (errcode(ERRCODE_TOO_MANY_ARGUMENTS),
626                          errmsg_plural("cannot pass more than %d argument to a function",
627                                                    "cannot pass more than %d arguments to a function",
628                                                    FUNC_MAX_ARGS,
629                                                    FUNC_MAX_ARGS)));
630
631         /*
632          * If any input types are domains, reduce them to their base types. This
633          * ensures that we will consider functions on the base type to be "exact
634          * matches" in the exact-match heuristic; it also makes it possible to do
635          * something useful with the type-category heuristics. Note that this
636          * makes it difficult, but not impossible, to use functions declared to
637          * take a domain as an input datatype.  Such a function will be selected
638          * over the base-type function only if it is an exact match at all
639          * argument positions, and so was already chosen by our caller.
640          */
641         for (i = 0; i < nargs; i++)
642                 input_base_typeids[i] = getBaseType(input_typeids[i]);
643
644         /*
645          * Run through all candidates and keep those with the most matches on
646          * exact types. Keep all candidates if none match.
647          */
648         ncandidates = 0;
649         nbestMatch = 0;
650         last_candidate = NULL;
651         for (current_candidate = candidates;
652                  current_candidate != NULL;
653                  current_candidate = current_candidate->next)
654         {
655                 current_typeids = current_candidate->args;
656                 nmatch = 0;
657                 for (i = 0; i < nargs; i++)
658                 {
659                         if (input_base_typeids[i] != UNKNOWNOID &&
660                                 current_typeids[i] == input_base_typeids[i])
661                                 nmatch++;
662                 }
663
664                 /* take this one as the best choice so far? */
665                 if ((nmatch > nbestMatch) || (last_candidate == NULL))
666                 {
667                         nbestMatch = nmatch;
668                         candidates = current_candidate;
669                         last_candidate = current_candidate;
670                         ncandidates = 1;
671                 }
672                 /* no worse than the last choice, so keep this one too? */
673                 else if (nmatch == nbestMatch)
674                 {
675                         last_candidate->next = current_candidate;
676                         last_candidate = current_candidate;
677                         ncandidates++;
678                 }
679                 /* otherwise, don't bother keeping this one... */
680         }
681
682         if (last_candidate)                     /* terminate rebuilt list */
683                 last_candidate->next = NULL;
684
685         if (ncandidates == 1)
686                 return candidates;
687
688         /*
689          * Still too many candidates? Now look for candidates which have either
690          * exact matches or preferred types at the args that will require
691          * coercion. (Restriction added in 7.4: preferred type must be of same
692          * category as input type; give no preference to cross-category
693          * conversions to preferred types.)  Keep all candidates if none match.
694          */
695         for (i = 0; i < nargs; i++) /* avoid multiple lookups */
696                 slot_category[i] = TypeCategory(input_base_typeids[i]);
697         ncandidates = 0;
698         nbestMatch = 0;
699         last_candidate = NULL;
700         for (current_candidate = candidates;
701                  current_candidate != NULL;
702                  current_candidate = current_candidate->next)
703         {
704                 current_typeids = current_candidate->args;
705                 nmatch = 0;
706                 for (i = 0; i < nargs; i++)
707                 {
708                         if (input_base_typeids[i] != UNKNOWNOID)
709                         {
710                                 if (current_typeids[i] == input_base_typeids[i] ||
711                                         IsPreferredType(slot_category[i], current_typeids[i]))
712                                         nmatch++;
713                         }
714                 }
715
716                 if ((nmatch > nbestMatch) || (last_candidate == NULL))
717                 {
718                         nbestMatch = nmatch;
719                         candidates = current_candidate;
720                         last_candidate = current_candidate;
721                         ncandidates = 1;
722                 }
723                 else if (nmatch == nbestMatch)
724                 {
725                         last_candidate->next = current_candidate;
726                         last_candidate = current_candidate;
727                         ncandidates++;
728                 }
729         }
730
731         if (last_candidate)                     /* terminate rebuilt list */
732                 last_candidate->next = NULL;
733
734         if (ncandidates == 1)
735                 return candidates;
736
737         /*
738          * Still too many candidates? Try assigning types for the unknown columns.
739          *
740          * NOTE: for a binary operator with one unknown and one non-unknown input,
741          * we already tried the heuristic of looking for a candidate with the
742          * known input type on both sides (see binary_oper_exact()). That's
743          * essentially a special case of the general algorithm we try next.
744          *
745          * We do this by examining each unknown argument position to see if we can
746          * determine a "type category" for it.  If any candidate has an input
747          * datatype of STRING category, use STRING category (this bias towards
748          * STRING is appropriate since unknown-type literals look like strings).
749          * Otherwise, if all the candidates agree on the type category of this
750          * argument position, use that category.  Otherwise, fail because we
751          * cannot determine a category.
752          *
753          * If we are able to determine a type category, also notice whether any of
754          * the candidates takes a preferred datatype within the category.
755          *
756          * Having completed this examination, remove candidates that accept the
757          * wrong category at any unknown position.      Also, if at least one
758          * candidate accepted a preferred type at a position, remove candidates
759          * that accept non-preferred types.
760          *
761          * If we are down to one candidate at the end, we win.
762          */
763         resolved_unknowns = false;
764         for (i = 0; i < nargs; i++)
765         {
766                 bool            have_conflict;
767
768                 if (input_base_typeids[i] != UNKNOWNOID)
769                         continue;
770                 resolved_unknowns = true;               /* assume we can do it */
771                 slot_category[i] = TYPCATEGORY_INVALID;
772                 slot_has_preferred_type[i] = false;
773                 have_conflict = false;
774                 for (current_candidate = candidates;
775                          current_candidate != NULL;
776                          current_candidate = current_candidate->next)
777                 {
778                         current_typeids = current_candidate->args;
779                         current_type = current_typeids[i];
780                         get_type_category_preferred(current_type,
781                                                                                 &current_category,
782                                                                                 &current_is_preferred);
783                         if (slot_category[i] == TYPCATEGORY_INVALID)
784                         {
785                                 /* first candidate */
786                                 slot_category[i] = current_category;
787                                 slot_has_preferred_type[i] = current_is_preferred;
788                         }
789                         else if (current_category == slot_category[i])
790                         {
791                                 /* more candidates in same category */
792                                 slot_has_preferred_type[i] |= current_is_preferred;
793                         }
794                         else
795                         {
796                                 /* category conflict! */
797                                 if (current_category == TYPCATEGORY_STRING)
798                                 {
799                                         /* STRING always wins if available */
800                                         slot_category[i] = current_category;
801                                         slot_has_preferred_type[i] = current_is_preferred;
802                                 }
803                                 else
804                                 {
805                                         /*
806                                          * Remember conflict, but keep going (might find STRING)
807                                          */
808                                         have_conflict = true;
809                                 }
810                         }
811                 }
812                 if (have_conflict && slot_category[i] != TYPCATEGORY_STRING)
813                 {
814                         /* Failed to resolve category conflict at this position */
815                         resolved_unknowns = false;
816                         break;
817                 }
818         }
819
820         if (resolved_unknowns)
821         {
822                 /* Strip non-matching candidates */
823                 ncandidates = 0;
824                 last_candidate = NULL;
825                 for (current_candidate = candidates;
826                          current_candidate != NULL;
827                          current_candidate = current_candidate->next)
828                 {
829                         bool            keepit = true;
830
831                         current_typeids = current_candidate->args;
832                         for (i = 0; i < nargs; i++)
833                         {
834                                 if (input_base_typeids[i] != UNKNOWNOID)
835                                         continue;
836                                 current_type = current_typeids[i];
837                                 get_type_category_preferred(current_type,
838                                                                                         &current_category,
839                                                                                         &current_is_preferred);
840                                 if (current_category != slot_category[i])
841                                 {
842                                         keepit = false;
843                                         break;
844                                 }
845                                 if (slot_has_preferred_type[i] && !current_is_preferred)
846                                 {
847                                         keepit = false;
848                                         break;
849                                 }
850                         }
851                         if (keepit)
852                         {
853                                 /* keep this candidate */
854                                 last_candidate = current_candidate;
855                                 ncandidates++;
856                         }
857                         else
858                         {
859                                 /* forget this candidate */
860                                 if (last_candidate)
861                                         last_candidate->next = current_candidate->next;
862                                 else
863                                         candidates = current_candidate->next;
864                         }
865                 }
866                 if (last_candidate)             /* terminate rebuilt list */
867                         last_candidate->next = NULL;
868         }
869
870         if (ncandidates == 1)
871                 return candidates;
872
873         return NULL;                            /* failed to select a best candidate */
874 }       /* func_select_candidate() */
875
876
877 /* func_get_detail()
878  *
879  * Find the named function in the system catalogs.
880  *
881  * Attempt to find the named function in the system catalogs with
882  * arguments exactly as specified, so that the normal case (exact match)
883  * is as quick as possible.
884  *
885  * If an exact match isn't found:
886  *      1) check for possible interpretation as a type coercion request
887  *      2) apply the ambiguous-function resolution rules
888  *
889  * Return values *funcid through *true_typeids receive info about the function.
890  * If argdefaults isn't NULL, *argdefaults receives a list of any default
891  * argument expressions that need to be added to the given arguments.
892  *
893  * When processing a named- or mixed-notation call (ie, fargnames isn't NIL),
894  * the returned true_typeids and argdefaults are ordered according to the
895  * call's argument ordering: first any positional arguments, then the named
896  * arguments, then defaulted arguments (if needed and allowed by
897  * expand_defaults).  Some care is needed if this information is to be compared
898  * to the function's pg_proc entry, but in practice the caller can usually
899  * just work with the call's argument ordering.
900  *
901  * We rely primarily on fargnames/nargs/argtypes as the argument description.
902  * The actual expression node list is passed in fargs so that we can check
903  * for type coercion of a constant.  Some callers pass fargs == NIL indicating
904  * they don't need that check made.  Note also that when fargnames isn't NIL,
905  * the fargs list must be passed if the caller wants actual argument position
906  * information to be returned into the NamedArgExpr nodes.
907  */
908 FuncDetailCode
909 func_get_detail(List *funcname,
910                                 List *fargs,
911                                 List *fargnames,
912                                 int nargs,
913                                 Oid *argtypes,
914                                 bool expand_variadic,
915                                 bool expand_defaults,
916                                 Oid *funcid,    /* return value */
917                                 Oid *rettype,   /* return value */
918                                 bool *retset,   /* return value */
919                                 int *nvargs,    /* return value */
920                                 Oid **true_typeids,             /* return value */
921                                 List **argdefaults)             /* optional return value */
922 {
923         FuncCandidateList raw_candidates;
924         FuncCandidateList best_candidate;
925
926         /* initialize output arguments to silence compiler warnings */
927         *funcid = InvalidOid;
928         *rettype = InvalidOid;
929         *retset = false;
930         *nvargs = 0;
931         *true_typeids = NULL;
932         if (argdefaults)
933                 *argdefaults = NIL;
934
935         /* Get list of possible candidates from namespace search */
936         raw_candidates = FuncnameGetCandidates(funcname, nargs, fargnames,
937                                                                                    expand_variadic, expand_defaults);
938
939         /*
940          * Quickly check if there is an exact match to the input datatypes (there
941          * can be only one)
942          */
943         for (best_candidate = raw_candidates;
944                  best_candidate != NULL;
945                  best_candidate = best_candidate->next)
946         {
947                 if (memcmp(argtypes, best_candidate->args, nargs * sizeof(Oid)) == 0)
948                         break;
949         }
950
951         if (best_candidate == NULL)
952         {
953                 /*
954                  * If we didn't find an exact match, next consider the possibility
955                  * that this is really a type-coercion request: a single-argument
956                  * function call where the function name is a type name.  If so, and
957                  * if the coercion path is RELABELTYPE or COERCEVIAIO, then go ahead
958                  * and treat the "function call" as a coercion.
959                  *
960                  * This interpretation needs to be given higher priority than
961                  * interpretations involving a type coercion followed by a function
962                  * call, otherwise we can produce surprising results. For example, we
963                  * want "text(varchar)" to be interpreted as a simple coercion, not as
964                  * "text(name(varchar))" which the code below this point is entirely
965                  * capable of selecting.
966                  *
967                  * We also treat a coercion of a previously-unknown-type literal
968                  * constant to a specific type this way.
969                  *
970                  * The reason we reject COERCION_PATH_FUNC here is that we expect the
971                  * cast implementation function to be named after the target type.
972                  * Thus the function will be found by normal lookup if appropriate.
973                  *
974                  * The reason we reject COERCION_PATH_ARRAYCOERCE is mainly that you
975                  * can't write "foo[] (something)" as a function call.  In theory
976                  * someone might want to invoke it as "_foo (something)" but we have
977                  * never supported that historically, so we can insist that people
978                  * write it as a normal cast instead.  Lack of historical support is
979                  * also the reason for not considering composite-type casts here.
980                  *
981                  * NB: it's important that this code does not exceed what coerce_type
982                  * can do, because the caller will try to apply coerce_type if we
983                  * return FUNCDETAIL_COERCION.  If we return that result for something
984                  * coerce_type can't handle, we'll cause infinite recursion between
985                  * this module and coerce_type!
986                  */
987                 if (nargs == 1 && fargs != NIL && fargnames == NIL)
988                 {
989                         Oid                     targetType = FuncNameAsType(funcname);
990
991                         if (OidIsValid(targetType))
992                         {
993                                 Oid                     sourceType = argtypes[0];
994                                 Node       *arg1 = linitial(fargs);
995                                 bool            iscoercion;
996
997                                 if (sourceType == UNKNOWNOID && IsA(arg1, Const))
998                                 {
999                                         /* always treat typename('literal') as coercion */
1000                                         iscoercion = true;
1001                                 }
1002                                 else
1003                                 {
1004                                         CoercionPathType cpathtype;
1005                                         Oid                     cfuncid;
1006
1007                                         cpathtype = find_coercion_pathway(targetType, sourceType,
1008                                                                                                           COERCION_EXPLICIT,
1009                                                                                                           &cfuncid);
1010                                         iscoercion = (cpathtype == COERCION_PATH_RELABELTYPE ||
1011                                                                   cpathtype == COERCION_PATH_COERCEVIAIO);
1012                                 }
1013
1014                                 if (iscoercion)
1015                                 {
1016                                         /* Treat it as a type coercion */
1017                                         *funcid = InvalidOid;
1018                                         *rettype = targetType;
1019                                         *retset = false;
1020                                         *nvargs = 0;
1021                                         *true_typeids = argtypes;
1022                                         return FUNCDETAIL_COERCION;
1023                                 }
1024                         }
1025                 }
1026
1027                 /*
1028                  * didn't find an exact match, so now try to match up candidates...
1029                  */
1030                 if (raw_candidates != NULL)
1031                 {
1032                         FuncCandidateList current_candidates;
1033                         int                     ncandidates;
1034
1035                         ncandidates = func_match_argtypes(nargs,
1036                                                                                           argtypes,
1037                                                                                           raw_candidates,
1038                                                                                           &current_candidates);
1039
1040                         /* one match only? then run with it... */
1041                         if (ncandidates == 1)
1042                                 best_candidate = current_candidates;
1043
1044                         /*
1045                          * multiple candidates? then better decide or throw an error...
1046                          */
1047                         else if (ncandidates > 1)
1048                         {
1049                                 best_candidate = func_select_candidate(nargs,
1050                                                                                                            argtypes,
1051                                                                                                            current_candidates);
1052
1053                                 /*
1054                                  * If we were able to choose a best candidate, we're done.
1055                                  * Otherwise, ambiguous function call.
1056                                  */
1057                                 if (!best_candidate)
1058                                         return FUNCDETAIL_MULTIPLE;
1059                         }
1060                 }
1061         }
1062
1063         if (best_candidate)
1064         {
1065                 HeapTuple       ftup;
1066                 Form_pg_proc pform;
1067                 FuncDetailCode result;
1068
1069                 /*
1070                  * If processing named args or expanding variadics or defaults, the
1071                  * "best candidate" might represent multiple equivalently good
1072                  * functions; treat this case as ambiguous.
1073                  */
1074                 if (!OidIsValid(best_candidate->oid))
1075                         return FUNCDETAIL_MULTIPLE;
1076
1077                 /*
1078                  * We disallow VARIADIC with named arguments unless the last
1079                  * argument (the one with VARIADIC attached) actually matched the
1080                  * variadic parameter.  This is mere pedantry, really, but some
1081                  * folks insisted.
1082                  */
1083                 if (fargnames != NIL && !expand_variadic && nargs > 0 &&
1084                         best_candidate->argnumbers[nargs - 1] != nargs - 1)
1085                         return FUNCDETAIL_NOTFOUND;
1086
1087                 *funcid = best_candidate->oid;
1088                 *nvargs = best_candidate->nvargs;
1089                 *true_typeids = best_candidate->args;
1090
1091                 /*
1092                  * If processing named args, return actual argument positions into
1093                  * NamedArgExpr nodes in the fargs list.  This is a bit ugly but not
1094                  * worth the extra notation needed to do it differently.
1095                  */
1096                 if (best_candidate->argnumbers != NULL)
1097                 {
1098                         int                     i = 0;
1099                         ListCell   *lc;
1100
1101                         foreach(lc, fargs)
1102                         {
1103                                 NamedArgExpr *na = (NamedArgExpr *) lfirst(lc);
1104
1105                                 if (IsA(na, NamedArgExpr))
1106                                         na->argnumber = best_candidate->argnumbers[i];
1107                                 i++;
1108                         }
1109                 }
1110
1111                 ftup = SearchSysCache(PROCOID,
1112                                                           ObjectIdGetDatum(best_candidate->oid),
1113                                                           0, 0, 0);
1114                 if (!HeapTupleIsValid(ftup))    /* should not happen */
1115                         elog(ERROR, "cache lookup failed for function %u",
1116                                  best_candidate->oid);
1117                 pform = (Form_pg_proc) GETSTRUCT(ftup);
1118                 *rettype = pform->prorettype;
1119                 *retset = pform->proretset;
1120                 /* fetch default args if caller wants 'em */
1121                 if (argdefaults && best_candidate->ndargs > 0)
1122                 {
1123                         Datum           proargdefaults;
1124                         bool            isnull;
1125                         char       *str;
1126                         List       *defaults;
1127
1128                         /* shouldn't happen, FuncnameGetCandidates messed up */
1129                         if (best_candidate->ndargs > pform->pronargdefaults)
1130                                 elog(ERROR, "not enough default arguments");
1131
1132                         proargdefaults = SysCacheGetAttr(PROCOID, ftup,
1133                                                                                          Anum_pg_proc_proargdefaults,
1134                                                                                          &isnull);
1135                         Assert(!isnull);
1136                         str = TextDatumGetCString(proargdefaults);
1137                         defaults = (List *) stringToNode(str);
1138                         Assert(IsA(defaults, List));
1139                         pfree(str);
1140
1141                         /* Delete any unused defaults from the returned list */
1142                         if (best_candidate->argnumbers != NULL)
1143                         {
1144                                 /*
1145                                  * This is a bit tricky in named notation, since the supplied
1146                                  * arguments could replace any subset of the defaults.  We
1147                                  * work by making a bitmapset of the argnumbers of defaulted
1148                                  * arguments, then scanning the defaults list and selecting
1149                                  * the needed items.  (This assumes that defaulted arguments
1150                                  * should be supplied in their positional order.)
1151                                  */
1152                                 Bitmapset *defargnumbers;
1153                                 int        *firstdefarg;
1154                                 List   *newdefaults;
1155                                 ListCell *lc;
1156                                 int             i;
1157
1158                                 defargnumbers = NULL;
1159                                 firstdefarg = &best_candidate->argnumbers[best_candidate->nargs - best_candidate->ndargs];
1160                                 for (i = 0; i < best_candidate->ndargs; i++)
1161                                         defargnumbers = bms_add_member(defargnumbers,
1162                                                                                                    firstdefarg[i]);
1163                                 newdefaults = NIL;
1164                                 i = pform->pronargs - pform->pronargdefaults;
1165                                 foreach(lc, defaults)
1166                                 {
1167                                         if (bms_is_member(i, defargnumbers))
1168                                                 newdefaults = lappend(newdefaults, lfirst(lc));
1169                                         i++;
1170                                 }
1171                                 Assert(list_length(newdefaults) == best_candidate->ndargs);
1172                                 bms_free(defargnumbers);
1173                                 *argdefaults = newdefaults;
1174                         }
1175                         else
1176                         {
1177                                 /*
1178                                  * Defaults for positional notation are lots easier;
1179                                  * just remove any unwanted ones from the front.
1180                                  */
1181                                 int                     ndelete;
1182
1183                                 ndelete = list_length(defaults) - best_candidate->ndargs;
1184                                 while (ndelete-- > 0)
1185                                         defaults = list_delete_first(defaults);
1186                                 *argdefaults = defaults;
1187                         }
1188                 }
1189                 if (pform->proisagg)
1190                         result = FUNCDETAIL_AGGREGATE;
1191                 else if (pform->proiswindow)
1192                         result = FUNCDETAIL_WINDOWFUNC;
1193                 else
1194                         result = FUNCDETAIL_NORMAL;
1195                 ReleaseSysCache(ftup);
1196                 return result;
1197         }
1198
1199         return FUNCDETAIL_NOTFOUND;
1200 }
1201
1202
1203 /*
1204  * make_fn_arguments()
1205  *
1206  * Given the actual argument expressions for a function, and the desired
1207  * input types for the function, add any necessary typecasting to the
1208  * expression tree.  Caller should already have verified that casting is
1209  * allowed.
1210  *
1211  * Caution: given argument list is modified in-place.
1212  *
1213  * As with coerce_type, pstate may be NULL if no special unknown-Param
1214  * processing is wanted.
1215  */
1216 void
1217 make_fn_arguments(ParseState *pstate,
1218                                   List *fargs,
1219                                   Oid *actual_arg_types,
1220                                   Oid *declared_arg_types)
1221 {
1222         ListCell   *current_fargs;
1223         int                     i = 0;
1224
1225         foreach(current_fargs, fargs)
1226         {
1227                 /* types don't match? then force coercion using a function call... */
1228                 if (actual_arg_types[i] != declared_arg_types[i])
1229                 {
1230                         Node   *node = (Node *) lfirst(current_fargs);
1231
1232                         /*
1233                          * If arg is a NamedArgExpr, coerce its input expr instead ---
1234                          * we want the NamedArgExpr to stay at the top level of the list.
1235                          */
1236                         if (IsA(node, NamedArgExpr))
1237                         {
1238                                 NamedArgExpr *na = (NamedArgExpr *) node;
1239
1240                                 node = coerce_type(pstate,
1241                                                                    (Node *) na->arg,
1242                                                                    actual_arg_types[i],
1243                                                                    declared_arg_types[i], -1,
1244                                                                    COERCION_IMPLICIT,
1245                                                                    COERCE_IMPLICIT_CAST,
1246                                                                    -1);
1247                                 na->arg = (Expr *) node;
1248                         }
1249                         else
1250                         {
1251                                 node = coerce_type(pstate,
1252                                                                    node,
1253                                                                    actual_arg_types[i],
1254                                                                    declared_arg_types[i], -1,
1255                                                                    COERCION_IMPLICIT,
1256                                                                    COERCE_IMPLICIT_CAST,
1257                                                                    -1);
1258                                 lfirst(current_fargs) = node;
1259                         }
1260                 }
1261                 i++;
1262         }
1263 }
1264
1265 /*
1266  * FuncNameAsType -
1267  *        convenience routine to see if a function name matches a type name
1268  *
1269  * Returns the OID of the matching type, or InvalidOid if none.  We ignore
1270  * shell types and complex types.
1271  */
1272 static Oid
1273 FuncNameAsType(List *funcname)
1274 {
1275         Oid                     result;
1276         Type            typtup;
1277
1278         typtup = LookupTypeName(NULL, makeTypeNameFromNameList(funcname), NULL);
1279         if (typtup == NULL)
1280                 return InvalidOid;
1281
1282         if (((Form_pg_type) GETSTRUCT(typtup))->typisdefined &&
1283                 !OidIsValid(typeTypeRelid(typtup)))
1284                 result = typeTypeId(typtup);
1285         else
1286                 result = InvalidOid;
1287
1288         ReleaseSysCache(typtup);
1289         return result;
1290 }
1291
1292 /*
1293  * ParseComplexProjection -
1294  *        handles function calls with a single argument that is of complex type.
1295  *        If the function call is actually a column projection, return a suitably
1296  *        transformed expression tree.  If not, return NULL.
1297  */
1298 static Node *
1299 ParseComplexProjection(ParseState *pstate, char *funcname, Node *first_arg,
1300                                            int location)
1301 {
1302         TupleDesc       tupdesc;
1303         int                     i;
1304
1305         /*
1306          * Special case for whole-row Vars so that we can resolve (foo.*).bar even
1307          * when foo is a reference to a subselect, join, or RECORD function. A
1308          * bonus is that we avoid generating an unnecessary FieldSelect; our
1309          * result can omit the whole-row Var and just be a Var for the selected
1310          * field.
1311          *
1312          * This case could be handled by expandRecordVariable, but it's more
1313          * efficient to do it this way when possible.
1314          */
1315         if (IsA(first_arg, Var) &&
1316                 ((Var *) first_arg)->varattno == InvalidAttrNumber)
1317         {
1318                 RangeTblEntry *rte;
1319
1320                 rte = GetRTEByRangeTablePosn(pstate,
1321                                                                          ((Var *) first_arg)->varno,
1322                                                                          ((Var *) first_arg)->varlevelsup);
1323                 /* Return a Var if funcname matches a column, else NULL */
1324                 return scanRTEForColumn(pstate, rte, funcname, location);
1325         }
1326
1327         /*
1328          * Else do it the hard way with get_expr_result_type().
1329          *
1330          * If it's a Var of type RECORD, we have to work even harder: we have to
1331          * find what the Var refers to, and pass that to get_expr_result_type.
1332          * That task is handled by expandRecordVariable().
1333          */
1334         if (IsA(first_arg, Var) &&
1335                 ((Var *) first_arg)->vartype == RECORDOID)
1336                 tupdesc = expandRecordVariable(pstate, (Var *) first_arg, 0);
1337         else if (get_expr_result_type(first_arg, NULL, &tupdesc) != TYPEFUNC_COMPOSITE)
1338                 return NULL;                    /* unresolvable RECORD type */
1339         Assert(tupdesc);
1340
1341         for (i = 0; i < tupdesc->natts; i++)
1342         {
1343                 Form_pg_attribute att = tupdesc->attrs[i];
1344
1345                 if (strcmp(funcname, NameStr(att->attname)) == 0 &&
1346                         !att->attisdropped)
1347                 {
1348                         /* Success, so generate a FieldSelect expression */
1349                         FieldSelect *fselect = makeNode(FieldSelect);
1350
1351                         fselect->arg = (Expr *) first_arg;
1352                         fselect->fieldnum = i + 1;
1353                         fselect->resulttype = att->atttypid;
1354                         fselect->resulttypmod = att->atttypmod;
1355                         return (Node *) fselect;
1356                 }
1357         }
1358
1359         return NULL;                            /* funcname does not match any column */
1360 }
1361
1362 /*
1363  * funcname_signature_string
1364  *              Build a string representing a function name, including arg types.
1365  *              The result is something like "foo(integer)".
1366  *
1367  * If argnames isn't NIL, it is a list of C strings representing the actual
1368  * arg names for the last N arguments.  This must be considered part of the
1369  * function signature too, when dealing with named-notation function calls.
1370  *
1371  * This is typically used in the construction of function-not-found error
1372  * messages.
1373  */
1374 const char *
1375 funcname_signature_string(const char *funcname, int nargs,
1376                                                   List *argnames, const Oid *argtypes)
1377 {
1378         StringInfoData argbuf;
1379         int                     numposargs;
1380         ListCell   *lc;
1381         int                     i;
1382
1383         initStringInfo(&argbuf);
1384
1385         appendStringInfo(&argbuf, "%s(", funcname);
1386
1387         numposargs = nargs - list_length(argnames);
1388         lc = list_head(argnames);
1389
1390         for (i = 0; i < nargs; i++)
1391         {
1392                 if (i)
1393                         appendStringInfoString(&argbuf, ", ");
1394                 appendStringInfoString(&argbuf, format_type_be(argtypes[i]));
1395                 if (i >= numposargs)
1396                 {
1397                         appendStringInfo(&argbuf, " AS %s", (char *) lfirst(lc));
1398                         lc = lnext(lc);
1399                 }
1400         }
1401
1402         appendStringInfoChar(&argbuf, ')');
1403
1404         return argbuf.data;                     /* return palloc'd string buffer */
1405 }
1406
1407 /*
1408  * func_signature_string
1409  *              As above, but function name is passed as a qualified name list.
1410  */
1411 const char *
1412 func_signature_string(List *funcname, int nargs,
1413                                           List *argnames, const Oid *argtypes)
1414 {
1415         return funcname_signature_string(NameListToString(funcname),
1416                                                                          nargs, argnames, argtypes);
1417 }
1418
1419 /*
1420  * LookupFuncName
1421  *              Given a possibly-qualified function name and a set of argument types,
1422  *              look up the function.
1423  *
1424  * If the function name is not schema-qualified, it is sought in the current
1425  * namespace search path.
1426  *
1427  * If the function is not found, we return InvalidOid if noError is true,
1428  * else raise an error.
1429  */
1430 Oid
1431 LookupFuncName(List *funcname, int nargs, const Oid *argtypes, bool noError)
1432 {
1433         FuncCandidateList clist;
1434
1435         clist = FuncnameGetCandidates(funcname, nargs, NIL, false, false);
1436
1437         while (clist)
1438         {
1439                 if (memcmp(argtypes, clist->args, nargs * sizeof(Oid)) == 0)
1440                         return clist->oid;
1441                 clist = clist->next;
1442         }
1443
1444         if (!noError)
1445                 ereport(ERROR,
1446                                 (errcode(ERRCODE_UNDEFINED_FUNCTION),
1447                                  errmsg("function %s does not exist",
1448                                                 func_signature_string(funcname, nargs,
1449                                                                                           NIL, argtypes))));
1450
1451         return InvalidOid;
1452 }
1453
1454 /*
1455  * LookupTypeNameOid
1456  *              Convenience routine to look up a type, silently accepting shell types
1457  */
1458 static Oid
1459 LookupTypeNameOid(const TypeName *typename)
1460 {
1461         Oid                     result;
1462         Type            typtup;
1463
1464         typtup = LookupTypeName(NULL, typename, NULL);
1465         if (typtup == NULL)
1466                 ereport(ERROR,
1467                                 (errcode(ERRCODE_UNDEFINED_OBJECT),
1468                                  errmsg("type \"%s\" does not exist",
1469                                                 TypeNameToString(typename))));
1470         result = typeTypeId(typtup);
1471         ReleaseSysCache(typtup);
1472         return result;
1473 }
1474
1475 /*
1476  * LookupFuncNameTypeNames
1477  *              Like LookupFuncName, but the argument types are specified by a
1478  *              list of TypeName nodes.
1479  */
1480 Oid
1481 LookupFuncNameTypeNames(List *funcname, List *argtypes, bool noError)
1482 {
1483         Oid                     argoids[FUNC_MAX_ARGS];
1484         int                     argcount;
1485         int                     i;
1486         ListCell   *args_item;
1487
1488         argcount = list_length(argtypes);
1489         if (argcount > FUNC_MAX_ARGS)
1490                 ereport(ERROR,
1491                                 (errcode(ERRCODE_TOO_MANY_ARGUMENTS),
1492                                  errmsg_plural("functions cannot have more than %d argument",
1493                                                            "functions cannot have more than %d arguments",
1494                                                            FUNC_MAX_ARGS,
1495                                                            FUNC_MAX_ARGS)));
1496
1497         args_item = list_head(argtypes);
1498         for (i = 0; i < argcount; i++)
1499         {
1500                 TypeName   *t = (TypeName *) lfirst(args_item);
1501
1502                 argoids[i] = LookupTypeNameOid(t);
1503                 args_item = lnext(args_item);
1504         }
1505
1506         return LookupFuncName(funcname, argcount, argoids, noError);
1507 }
1508
1509 /*
1510  * LookupAggNameTypeNames
1511  *              Find an aggregate function given a name and list of TypeName nodes.
1512  *
1513  * This is almost like LookupFuncNameTypeNames, but the error messages refer
1514  * to aggregates rather than plain functions, and we verify that the found
1515  * function really is an aggregate.
1516  */
1517 Oid
1518 LookupAggNameTypeNames(List *aggname, List *argtypes, bool noError)
1519 {
1520         Oid                     argoids[FUNC_MAX_ARGS];
1521         int                     argcount;
1522         int                     i;
1523         ListCell   *lc;
1524         Oid                     oid;
1525         HeapTuple       ftup;
1526         Form_pg_proc pform;
1527
1528         argcount = list_length(argtypes);
1529         if (argcount > FUNC_MAX_ARGS)
1530                 ereport(ERROR,
1531                                 (errcode(ERRCODE_TOO_MANY_ARGUMENTS),
1532                                  errmsg_plural("functions cannot have more than %d argument",
1533                                                            "functions cannot have more than %d arguments",
1534                                                            FUNC_MAX_ARGS,
1535                                                            FUNC_MAX_ARGS)));
1536
1537         i = 0;
1538         foreach(lc, argtypes)
1539         {
1540                 TypeName   *t = (TypeName *) lfirst(lc);
1541
1542                 argoids[i] = LookupTypeNameOid(t);
1543                 i++;
1544         }
1545
1546         oid = LookupFuncName(aggname, argcount, argoids, true);
1547
1548         if (!OidIsValid(oid))
1549         {
1550                 if (noError)
1551                         return InvalidOid;
1552                 if (argcount == 0)
1553                         ereport(ERROR,
1554                                         (errcode(ERRCODE_UNDEFINED_FUNCTION),
1555                                          errmsg("aggregate %s(*) does not exist",
1556                                                         NameListToString(aggname))));
1557                 else
1558                         ereport(ERROR,
1559                                         (errcode(ERRCODE_UNDEFINED_FUNCTION),
1560                                          errmsg("aggregate %s does not exist",
1561                                                         func_signature_string(aggname, argcount,
1562                                                                                                   NIL, argoids))));
1563         }
1564
1565         /* Make sure it's an aggregate */
1566         ftup = SearchSysCache(PROCOID,
1567                                                   ObjectIdGetDatum(oid),
1568                                                   0, 0, 0);
1569         if (!HeapTupleIsValid(ftup))    /* should not happen */
1570                 elog(ERROR, "cache lookup failed for function %u", oid);
1571         pform = (Form_pg_proc) GETSTRUCT(ftup);
1572
1573         if (!pform->proisagg)
1574         {
1575                 ReleaseSysCache(ftup);
1576                 if (noError)
1577                         return InvalidOid;
1578                 /* we do not use the (*) notation for functions... */
1579                 ereport(ERROR,
1580                                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1581                                  errmsg("function %s is not an aggregate",
1582                                                 func_signature_string(aggname, argcount,
1583                                                                                           NIL, argoids))));
1584         }
1585
1586         ReleaseSysCache(ftup);
1587
1588         return oid;
1589 }