]> granicus.if.org Git - postgresql/blob - src/backend/parser/parse_func.c
When a GUC string variable is not set, print the empty string (in SHOW etc.),
[postgresql] / src / backend / parser / parse_func.c
1 /*-------------------------------------------------------------------------
2  *
3  * parse_func.c
4  *              handle function calls in parser
5  *
6  * Portions Copyright (c) 1996-2006, 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.188 2006/07/14 14:52:22 momjian Exp $
12  *
13  *-------------------------------------------------------------------------
14  */
15 #include "postgres.h"
16
17 #include "access/heapam.h"
18 #include "catalog/pg_inherits.h"
19 #include "catalog/pg_proc.h"
20 #include "catalog/pg_type.h"
21 #include "funcapi.h"
22 #include "nodes/makefuncs.h"
23 #include "parser/parse_agg.h"
24 #include "parser/parse_coerce.h"
25 #include "parser/parse_expr.h"
26 #include "parser/parse_func.h"
27 #include "parser/parse_relation.h"
28 #include "parser/parse_target.h"
29 #include "parser/parse_type.h"
30 #include "utils/builtins.h"
31 #include "utils/fmgroids.h"
32 #include "utils/lsyscache.h"
33 #include "utils/syscache.h"
34
35
36 static Node *ParseComplexProjection(ParseState *pstate, char *funcname,
37                                            Node *first_arg, int location);
38 static void unknown_attribute(ParseState *pstate, Node *relref, char *attname,
39                                                           int location);
40
41
42 /*
43  *      Parse a function call
44  *
45  *      For historical reasons, Postgres tries to treat the notations tab.col
46  *      and col(tab) as equivalent: if a single-argument function call has an
47  *      argument of complex type and the (unqualified) function name matches
48  *      any attribute of the type, we take it as a column projection.  Conversely
49  *      a function of a single complex-type argument can be written like a
50  *      column reference, allowing functions to act like computed columns.
51  *
52  *      Hence, both cases come through here.  The is_column parameter tells us
53  *      which syntactic construct is actually being dealt with, but this is
54  *      intended to be used only to deliver an appropriate error message,
55  *      not to affect the semantics.  When is_column is true, we should have
56  *      a single argument (the putative table), unqualified function name
57  *      equal to the column name, and no aggregate decoration.
58  *
59  *      The argument expressions (in fargs) must have been transformed already.
60  */
61 Node *
62 ParseFuncOrColumn(ParseState *pstate, List *funcname, List *fargs,
63                                   bool agg_star, bool agg_distinct, bool is_column,
64                                   int location)
65 {
66         Oid                     rettype;
67         Oid                     funcid;
68         ListCell   *l;
69         ListCell   *nextl;
70         Node       *first_arg = NULL;
71         int                     nargs;
72         Oid                     actual_arg_types[FUNC_MAX_ARGS];
73         Oid                *declared_arg_types;
74         Node       *retval;
75         bool            retset;
76         FuncDetailCode fdresult;
77
78         /*
79          * Most of the rest of the parser just assumes that functions do not have
80          * more than FUNC_MAX_ARGS parameters.  We have to test here to protect
81          * against array overruns, etc.  Of course, this may not be a function,
82          * but the test doesn't hurt.
83          */
84         if (list_length(fargs) > FUNC_MAX_ARGS)
85                 ereport(ERROR,
86                                 (errcode(ERRCODE_TOO_MANY_ARGUMENTS),
87                                  errmsg("cannot pass more than %d arguments to a function",
88                                                 FUNC_MAX_ARGS),
89                                  parser_errposition(pstate, location)));
90
91         /*
92          * Extract arg type info in preparation for function lookup.
93          *
94          * If any arguments are Param markers of type VOID, we discard them from
95          * the parameter list.  This is a hack to allow the JDBC driver to not
96          * have to distinguish "input" and "output" parameter symbols while
97          * parsing function-call constructs.  We can't use foreach() because we
98          * may modify the list ...
99          */
100         nargs = 0;
101         for (l = list_head(fargs); l != NULL; l = nextl)
102         {
103                 Node       *arg = lfirst(l);
104                 Oid                     argtype = exprType(arg);
105
106                 nextl = lnext(l);
107
108                 if (argtype == VOIDOID && IsA(arg, Param) &&!is_column)
109                 {
110                         fargs = list_delete_ptr(fargs, arg);
111                         continue;
112                 }
113
114                 actual_arg_types[nargs++] = argtype;
115         }
116
117         if (fargs)
118         {
119                 first_arg = linitial(fargs);
120                 Assert(first_arg != NULL);
121         }
122
123         /*
124          * Check for column projection: if function has one argument, and that
125          * argument is of complex type, and function name is not qualified, then
126          * the "function call" could be a projection.  We also check that there
127          * wasn't any aggregate decoration.
128          */
129         if (nargs == 1 && !agg_star && !agg_distinct && list_length(funcname) == 1)
130         {
131                 Oid                     argtype = actual_arg_types[0];
132
133                 if (argtype == RECORDOID || ISCOMPLEX(argtype))
134                 {
135                         retval = ParseComplexProjection(pstate,
136                                                                                         strVal(linitial(funcname)),
137                                                                                         first_arg,
138                                                                                         location);
139                         if (retval)
140                                 return retval;
141
142                         /*
143                          * If ParseComplexProjection doesn't recognize it as a projection,
144                          * just press on.
145                          */
146                 }
147         }
148
149         /*
150          * Okay, it's not a column projection, so it must really be a function.
151          * func_get_detail looks up the function in the catalogs, does
152          * disambiguation for polymorphic functions, handles inheritance, and
153          * returns the funcid and type and set or singleton status of the
154          * function's return value.  it also returns the true argument types to
155          * the function.
156          */
157         fdresult = func_get_detail(funcname, fargs, nargs, actual_arg_types,
158                                                            &funcid, &rettype, &retset,
159                                                            &declared_arg_types);
160         if (fdresult == FUNCDETAIL_COERCION)
161         {
162                 /*
163                  * We can do it as a trivial coercion. coerce_type can handle these
164                  * cases, so why duplicate code...
165                  */
166                 return coerce_type(pstate, linitial(fargs),
167                                                    actual_arg_types[0], rettype, -1,
168                                                    COERCION_EXPLICIT, COERCE_EXPLICIT_CALL);
169         }
170         else if (fdresult == FUNCDETAIL_NORMAL)
171         {
172                 /*
173                  * Normal function found; was there anything indicating it must be an
174                  * aggregate?
175                  */
176                 if (agg_star)
177                         ereport(ERROR,
178                                         (errcode(ERRCODE_WRONG_OBJECT_TYPE),
179                            errmsg("%s(*) specified, but %s is not an aggregate function",
180                                           NameListToString(funcname),
181                                           NameListToString(funcname)),
182                                          parser_errposition(pstate, location)));
183                 if (agg_distinct)
184                         ereport(ERROR,
185                                         (errcode(ERRCODE_WRONG_OBJECT_TYPE),
186                         errmsg("DISTINCT specified, but %s is not an aggregate function",
187                                    NameListToString(funcname)),
188                                          parser_errposition(pstate, location)));
189         }
190         else if (fdresult != FUNCDETAIL_AGGREGATE)
191         {
192                 /*
193                  * Oops.  Time to die.
194                  *
195                  * If we are dealing with the attribute notation rel.function, give an
196                  * error message that is appropriate for that case.
197                  */
198                 if (is_column)
199                 {
200                         Assert(nargs == 1);
201                         Assert(list_length(funcname) == 1);
202                         unknown_attribute(pstate, first_arg, strVal(linitial(funcname)),
203                                                           location);
204                 }
205
206                 /*
207                  * Else generate a detailed complaint for a function
208                  */
209                 if (fdresult == FUNCDETAIL_MULTIPLE)
210                         ereport(ERROR,
211                                         (errcode(ERRCODE_AMBIGUOUS_FUNCTION),
212                                          errmsg("function %s is not unique",
213                                                         func_signature_string(funcname, nargs,
214                                                                                                   actual_arg_types)),
215                                          errhint("Could not choose a best candidate function. "
216                                                          "You may need to add explicit type casts."),
217                                          parser_errposition(pstate, location)));
218                 else
219                         ereport(ERROR,
220                                         (errcode(ERRCODE_UNDEFINED_FUNCTION),
221                                          errmsg("function %s does not exist",
222                                                         func_signature_string(funcname, nargs,
223                                                                                                   actual_arg_types)),
224                         errhint("No function matches the given name and argument types. "
225                                         "You may need to add explicit type casts."),
226                                          parser_errposition(pstate, location)));
227         }
228
229         /*
230          * enforce consistency with ANYARRAY and ANYELEMENT argument and return
231          * types, possibly adjusting return type or declared_arg_types (which will
232          * be used as the cast destination by make_fn_arguments)
233          */
234         rettype = enforce_generic_type_consistency(actual_arg_types,
235                                                                                            declared_arg_types,
236                                                                                            nargs,
237                                                                                            rettype);
238
239         /* perform the necessary typecasting of arguments */
240         make_fn_arguments(pstate, fargs, actual_arg_types, declared_arg_types);
241
242         /* build the appropriate output structure */
243         if (fdresult == FUNCDETAIL_NORMAL)
244         {
245                 FuncExpr   *funcexpr = makeNode(FuncExpr);
246
247                 funcexpr->funcid = funcid;
248                 funcexpr->funcresulttype = rettype;
249                 funcexpr->funcretset = retset;
250                 funcexpr->funcformat = COERCE_EXPLICIT_CALL;
251                 funcexpr->args = fargs;
252
253                 retval = (Node *) funcexpr;
254         }
255         else
256         {
257                 /* aggregate function */
258                 Aggref     *aggref = makeNode(Aggref);
259
260                 aggref->aggfnoid = funcid;
261                 aggref->aggtype = rettype;
262                 aggref->target = linitial(fargs);
263                 aggref->aggstar = agg_star;
264                 aggref->aggdistinct = agg_distinct;
265
266                 /* parse_agg.c does additional aggregate-specific processing */
267                 transformAggregateCall(pstate, aggref);
268
269                 retval = (Node *) aggref;
270
271                 if (retset)
272                         ereport(ERROR,
273                                         (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
274                                          errmsg("aggregates may not return sets"),
275                                          parser_errposition(pstate, location)));
276         }
277
278         return retval;
279 }
280
281
282 /* func_match_argtypes()
283  *
284  * Given a list of candidate functions (having the right name and number
285  * of arguments) and an array of input datatype OIDs, produce a shortlist of
286  * those candidates that actually accept the input datatypes (either exactly
287  * or by coercion), and return the number of such candidates.
288  *
289  * Note that can_coerce_type will assume that UNKNOWN inputs are coercible to
290  * anything, so candidates will not be eliminated on that basis.
291  *
292  * NB: okay to modify input list structure, as long as we find at least
293  * one match.  If no match at all, the list must remain unmodified.
294  */
295 int
296 func_match_argtypes(int nargs,
297                                         Oid *input_typeids,
298                                         FuncCandidateList raw_candidates,
299                                         FuncCandidateList *candidates)          /* return value */
300 {
301         FuncCandidateList current_candidate;
302         FuncCandidateList next_candidate;
303         int                     ncandidates = 0;
304
305         *candidates = NULL;
306
307         for (current_candidate = raw_candidates;
308                  current_candidate != NULL;
309                  current_candidate = next_candidate)
310         {
311                 next_candidate = current_candidate->next;
312                 if (can_coerce_type(nargs, input_typeids, current_candidate->args,
313                                                         COERCION_IMPLICIT))
314                 {
315                         current_candidate->next = *candidates;
316                         *candidates = current_candidate;
317                         ncandidates++;
318                 }
319         }
320
321         return ncandidates;
322 }       /* func_match_argtypes() */
323
324
325 /* func_select_candidate()
326  *              Given the input argtype array and more than one candidate
327  *              for the function, attempt to resolve the conflict.
328  *
329  * Returns the selected candidate if the conflict can be resolved,
330  * otherwise returns NULL.
331  *
332  * Note that the caller has already determined that there is no candidate
333  * exactly matching the input argtypes, and has pruned away any "candidates"
334  * that aren't actually coercion-compatible with the input types.
335  *
336  * This is also used for resolving ambiguous operator references.  Formerly
337  * parse_oper.c had its own, essentially duplicate code for the purpose.
338  * The following comments (formerly in parse_oper.c) are kept to record some
339  * of the history of these heuristics.
340  *
341  * OLD COMMENTS:
342  *
343  * This routine is new code, replacing binary_oper_select_candidate()
344  * which dates from v4.2/v1.0.x days. It tries very hard to match up
345  * operators with types, including allowing type coercions if necessary.
346  * The important thing is that the code do as much as possible,
347  * while _never_ doing the wrong thing, where "the wrong thing" would
348  * be returning an operator when other better choices are available,
349  * or returning an operator which is a non-intuitive possibility.
350  * - thomas 1998-05-21
351  *
352  * The comments below came from binary_oper_select_candidate(), and
353  * illustrate the issues and choices which are possible:
354  * - thomas 1998-05-20
355  *
356  * current wisdom holds that the default operator should be one in which
357  * both operands have the same type (there will only be one such
358  * operator)
359  *
360  * 7.27.93 - I have decided not to do this; it's too hard to justify, and
361  * it's easy enough to typecast explicitly - avi
362  * [the rest of this routine was commented out since then - ay]
363  *
364  * 6/23/95 - I don't complete agree with avi. In particular, casting
365  * floats is a pain for users. Whatever the rationale behind not doing
366  * this is, I need the following special case to work.
367  *
368  * In the WHERE clause of a query, if a float is specified without
369  * quotes, we treat it as float8. I added the float48* operators so
370  * that we can operate on float4 and float8. But now we have more than
371  * one matching operator if the right arg is unknown (eg. float
372  * specified with quotes). This break some stuff in the regression
373  * test where there are floats in quotes not properly casted. Below is
374  * the solution. In addition to requiring the operator operates on the
375  * same type for both operands [as in the code Avi originally
376  * commented out], we also require that the operators be equivalent in
377  * some sense. (see equivalentOpersAfterPromotion for details.)
378  * - ay 6/95
379  */
380 FuncCandidateList
381 func_select_candidate(int nargs,
382                                           Oid *input_typeids,
383                                           FuncCandidateList candidates)
384 {
385         FuncCandidateList current_candidate;
386         FuncCandidateList last_candidate;
387         Oid                *current_typeids;
388         Oid                     current_type;
389         int                     i;
390         int                     ncandidates;
391         int                     nbestMatch,
392                                 nmatch;
393         Oid                     input_base_typeids[FUNC_MAX_ARGS];
394         CATEGORY        slot_category[FUNC_MAX_ARGS],
395                                 current_category;
396         bool            slot_has_preferred_type[FUNC_MAX_ARGS];
397         bool            resolved_unknowns;
398
399         /* protect local fixed-size arrays */
400         if (nargs > FUNC_MAX_ARGS)
401                 ereport(ERROR,
402                                 (errcode(ERRCODE_TOO_MANY_ARGUMENTS),
403                                  errmsg("cannot pass more than %d arguments to a function",
404                                                 FUNC_MAX_ARGS)));
405
406         /*
407          * If any input types are domains, reduce them to their base types. This
408          * ensures that we will consider functions on the base type to be "exact
409          * matches" in the exact-match heuristic; it also makes it possible to do
410          * something useful with the type-category heuristics. Note that this
411          * makes it difficult, but not impossible, to use functions declared to
412          * take a domain as an input datatype.  Such a function will be selected
413          * over the base-type function only if it is an exact match at all
414          * argument positions, and so was already chosen by our caller.
415          */
416         for (i = 0; i < nargs; i++)
417                 input_base_typeids[i] = getBaseType(input_typeids[i]);
418
419         /*
420          * Run through all candidates and keep those with the most matches on
421          * exact types. Keep all candidates if none match.
422          */
423         ncandidates = 0;
424         nbestMatch = 0;
425         last_candidate = NULL;
426         for (current_candidate = candidates;
427                  current_candidate != NULL;
428                  current_candidate = current_candidate->next)
429         {
430                 current_typeids = current_candidate->args;
431                 nmatch = 0;
432                 for (i = 0; i < nargs; i++)
433                 {
434                         if (input_base_typeids[i] != UNKNOWNOID &&
435                                 current_typeids[i] == input_base_typeids[i])
436                                 nmatch++;
437                 }
438
439                 /* take this one as the best choice so far? */
440                 if ((nmatch > nbestMatch) || (last_candidate == NULL))
441                 {
442                         nbestMatch = nmatch;
443                         candidates = current_candidate;
444                         last_candidate = current_candidate;
445                         ncandidates = 1;
446                 }
447                 /* no worse than the last choice, so keep this one too? */
448                 else if (nmatch == nbestMatch)
449                 {
450                         last_candidate->next = current_candidate;
451                         last_candidate = current_candidate;
452                         ncandidates++;
453                 }
454                 /* otherwise, don't bother keeping this one... */
455         }
456
457         if (last_candidate)                     /* terminate rebuilt list */
458                 last_candidate->next = NULL;
459
460         if (ncandidates == 1)
461                 return candidates;
462
463         /*
464          * Still too many candidates? Now look for candidates which have either
465          * exact matches or preferred types at the args that will require
466          * coercion. (Restriction added in 7.4: preferred type must be of same
467          * category as input type; give no preference to cross-category
468          * conversions to preferred types.)  Keep all candidates if none match.
469          */
470         for (i = 0; i < nargs; i++) /* avoid multiple lookups */
471                 slot_category[i] = TypeCategory(input_base_typeids[i]);
472         ncandidates = 0;
473         nbestMatch = 0;
474         last_candidate = NULL;
475         for (current_candidate = candidates;
476                  current_candidate != NULL;
477                  current_candidate = current_candidate->next)
478         {
479                 current_typeids = current_candidate->args;
480                 nmatch = 0;
481                 for (i = 0; i < nargs; i++)
482                 {
483                         if (input_base_typeids[i] != UNKNOWNOID)
484                         {
485                                 if (current_typeids[i] == input_base_typeids[i] ||
486                                         IsPreferredType(slot_category[i], current_typeids[i]))
487                                         nmatch++;
488                         }
489                 }
490
491                 if ((nmatch > nbestMatch) || (last_candidate == NULL))
492                 {
493                         nbestMatch = nmatch;
494                         candidates = current_candidate;
495                         last_candidate = current_candidate;
496                         ncandidates = 1;
497                 }
498                 else if (nmatch == nbestMatch)
499                 {
500                         last_candidate->next = current_candidate;
501                         last_candidate = current_candidate;
502                         ncandidates++;
503                 }
504         }
505
506         if (last_candidate)                     /* terminate rebuilt list */
507                 last_candidate->next = NULL;
508
509         if (ncandidates == 1)
510                 return candidates;
511
512         /*
513          * Still too many candidates? Try assigning types for the unknown columns.
514          *
515          * NOTE: for a binary operator with one unknown and one non-unknown input,
516          * we already tried the heuristic of looking for a candidate with the
517          * known input type on both sides (see binary_oper_exact()). That's
518          * essentially a special case of the general algorithm we try next.
519          *
520          * We do this by examining each unknown argument position to see if we can
521          * determine a "type category" for it.  If any candidate has an input
522          * datatype of STRING category, use STRING category (this bias towards
523          * STRING is appropriate since unknown-type literals look like strings).
524          * Otherwise, if all the candidates agree on the type category of this
525          * argument position, use that category.  Otherwise, fail because we
526          * cannot determine a category.
527          *
528          * If we are able to determine a type category, also notice whether any of
529          * the candidates takes a preferred datatype within the category.
530          *
531          * Having completed this examination, remove candidates that accept the
532          * wrong category at any unknown position.      Also, if at least one
533          * candidate accepted a preferred type at a position, remove candidates
534          * that accept non-preferred types.
535          *
536          * If we are down to one candidate at the end, we win.
537          */
538         resolved_unknowns = false;
539         for (i = 0; i < nargs; i++)
540         {
541                 bool            have_conflict;
542
543                 if (input_base_typeids[i] != UNKNOWNOID)
544                         continue;
545                 resolved_unknowns = true;               /* assume we can do it */
546                 slot_category[i] = INVALID_TYPE;
547                 slot_has_preferred_type[i] = false;
548                 have_conflict = false;
549                 for (current_candidate = candidates;
550                          current_candidate != NULL;
551                          current_candidate = current_candidate->next)
552                 {
553                         current_typeids = current_candidate->args;
554                         current_type = current_typeids[i];
555                         current_category = TypeCategory(current_type);
556                         if (slot_category[i] == INVALID_TYPE)
557                         {
558                                 /* first candidate */
559                                 slot_category[i] = current_category;
560                                 slot_has_preferred_type[i] =
561                                         IsPreferredType(current_category, current_type);
562                         }
563                         else if (current_category == slot_category[i])
564                         {
565                                 /* more candidates in same category */
566                                 slot_has_preferred_type[i] |=
567                                         IsPreferredType(current_category, current_type);
568                         }
569                         else
570                         {
571                                 /* category conflict! */
572                                 if (current_category == STRING_TYPE)
573                                 {
574                                         /* STRING always wins if available */
575                                         slot_category[i] = current_category;
576                                         slot_has_preferred_type[i] =
577                                                 IsPreferredType(current_category, current_type);
578                                 }
579                                 else
580                                 {
581                                         /*
582                                          * Remember conflict, but keep going (might find STRING)
583                                          */
584                                         have_conflict = true;
585                                 }
586                         }
587                 }
588                 if (have_conflict && slot_category[i] != STRING_TYPE)
589                 {
590                         /* Failed to resolve category conflict at this position */
591                         resolved_unknowns = false;
592                         break;
593                 }
594         }
595
596         if (resolved_unknowns)
597         {
598                 /* Strip non-matching candidates */
599                 ncandidates = 0;
600                 last_candidate = NULL;
601                 for (current_candidate = candidates;
602                          current_candidate != NULL;
603                          current_candidate = current_candidate->next)
604                 {
605                         bool            keepit = true;
606
607                         current_typeids = current_candidate->args;
608                         for (i = 0; i < nargs; i++)
609                         {
610                                 if (input_base_typeids[i] != UNKNOWNOID)
611                                         continue;
612                                 current_type = current_typeids[i];
613                                 current_category = TypeCategory(current_type);
614                                 if (current_category != slot_category[i])
615                                 {
616                                         keepit = false;
617                                         break;
618                                 }
619                                 if (slot_has_preferred_type[i] &&
620                                         !IsPreferredType(current_category, current_type))
621                                 {
622                                         keepit = false;
623                                         break;
624                                 }
625                         }
626                         if (keepit)
627                         {
628                                 /* keep this candidate */
629                                 last_candidate = current_candidate;
630                                 ncandidates++;
631                         }
632                         else
633                         {
634                                 /* forget this candidate */
635                                 if (last_candidate)
636                                         last_candidate->next = current_candidate->next;
637                                 else
638                                         candidates = current_candidate->next;
639                         }
640                 }
641                 if (last_candidate)             /* terminate rebuilt list */
642                         last_candidate->next = NULL;
643         }
644
645         if (ncandidates == 1)
646                 return candidates;
647
648         return NULL;                            /* failed to select a best candidate */
649 }       /* func_select_candidate() */
650
651
652 /* func_get_detail()
653  *
654  * Find the named function in the system catalogs.
655  *
656  * Attempt to find the named function in the system catalogs with
657  *      arguments exactly as specified, so that the normal case
658  *      (exact match) is as quick as possible.
659  *
660  * If an exact match isn't found:
661  *      1) check for possible interpretation as a trivial type coercion
662  *      2) get a vector of all possible input arg type arrays constructed
663  *         from the superclasses of the original input arg types
664  *      3) get a list of all possible argument type arrays to the function
665  *         with given name and number of arguments
666  *      4) for each input arg type array from vector #1:
667  *       a) find how many of the function arg type arrays from list #2
668  *              it can be coerced to
669  *       b) if the answer is one, we have our function
670  *       c) if the answer is more than one, attempt to resolve the conflict
671  *       d) if the answer is zero, try the next array from vector #1
672  *
673  * Note: we rely primarily on nargs/argtypes as the argument description.
674  * The actual expression node list is passed in fargs so that we can check
675  * for type coercion of a constant.  Some callers pass fargs == NIL
676  * indicating they don't want that check made.
677  */
678 FuncDetailCode
679 func_get_detail(List *funcname,
680                                 List *fargs,
681                                 int nargs,
682                                 Oid *argtypes,
683                                 Oid *funcid,    /* return value */
684                                 Oid *rettype,   /* return value */
685                                 bool *retset,   /* return value */
686                                 Oid **true_typeids)             /* return value */
687 {
688         FuncCandidateList raw_candidates;
689         FuncCandidateList best_candidate;
690
691         /* Get list of possible candidates from namespace search */
692         raw_candidates = FuncnameGetCandidates(funcname, nargs);
693
694         /*
695          * Quickly check if there is an exact match to the input datatypes (there
696          * can be only one)
697          */
698         for (best_candidate = raw_candidates;
699                  best_candidate != NULL;
700                  best_candidate = best_candidate->next)
701         {
702                 if (memcmp(argtypes, best_candidate->args, nargs * sizeof(Oid)) == 0)
703                         break;
704         }
705
706         if (best_candidate == NULL)
707         {
708                 /*
709                  * If we didn't find an exact match, next consider the possibility
710                  * that this is really a type-coercion request: a single-argument
711                  * function call where the function name is a type name.  If so, and
712                  * if we can do the coercion trivially (no run-time function call
713                  * needed), then go ahead and treat the "function call" as a coercion.
714                  * This interpretation needs to be given higher priority than
715                  * interpretations involving a type coercion followed by a function
716                  * call, otherwise we can produce surprising results. For example, we
717                  * want "text(varchar)" to be interpreted as a trivial coercion, not
718                  * as "text(name(varchar))" which the code below this point is
719                  * entirely capable of selecting.
720                  *
721                  * "Trivial" coercions are ones that involve binary-compatible types
722                  * and ones that are coercing a previously-unknown-type literal
723                  * constant to a specific type.
724                  *
725                  * The reason we can restrict our check to binary-compatible coercions
726                  * here is that we expect non-binary-compatible coercions to have an
727                  * implementation function named after the target type. That function
728                  * will be found by normal lookup if appropriate.
729                  *
730                  * NB: it's important that this code stays in sync with what
731                  * coerce_type can do, because the caller will try to apply
732                  * coerce_type if we return FUNCDETAIL_COERCION.  If we return that
733                  * result for something coerce_type can't handle, we'll cause infinite
734                  * recursion between this module and coerce_type!
735                  */
736                 if (nargs == 1 && fargs != NIL)
737                 {
738                         Oid                     targetType;
739
740                         targetType = LookupTypeName(NULL,
741                                                                                 makeTypeNameFromNameList(funcname));
742                         if (OidIsValid(targetType) &&
743                                 !ISCOMPLEX(targetType))
744                         {
745                                 Oid                     sourceType = argtypes[0];
746                                 Node       *arg1 = linitial(fargs);
747                                 Oid                     cfuncid;
748
749                                 if ((sourceType == UNKNOWNOID && IsA(arg1, Const)) ||
750                                         (find_coercion_pathway(targetType, sourceType,
751                                                                                    COERCION_EXPLICIT, &cfuncid) &&
752                                          cfuncid == InvalidOid))
753                                 {
754                                         /* Yup, it's a type coercion */
755                                         *funcid = InvalidOid;
756                                         *rettype = targetType;
757                                         *retset = false;
758                                         *true_typeids = argtypes;
759                                         return FUNCDETAIL_COERCION;
760                                 }
761                         }
762                 }
763
764                 /*
765                  * didn't find an exact match, so now try to match up candidates...
766                  */
767                 if (raw_candidates != NULL)
768                 {
769                         FuncCandidateList current_candidates;
770                         int                     ncandidates;
771
772                         ncandidates = func_match_argtypes(nargs,
773                                                                                           argtypes,
774                                                                                           raw_candidates,
775                                                                                           &current_candidates);
776
777                         /* one match only? then run with it... */
778                         if (ncandidates == 1)
779                                 best_candidate = current_candidates;
780
781                         /*
782                          * multiple candidates? then better decide or throw an error...
783                          */
784                         else if (ncandidates > 1)
785                         {
786                                 best_candidate = func_select_candidate(nargs,
787                                                                                                            argtypes,
788                                                                                                            current_candidates);
789
790                                 /*
791                                  * If we were able to choose a best candidate, we're done.
792                                  * Otherwise, ambiguous function call.
793                                  */
794                                 if (!best_candidate)
795                                         return FUNCDETAIL_MULTIPLE;
796                         }
797                 }
798         }
799
800         if (best_candidate)
801         {
802                 HeapTuple       ftup;
803                 Form_pg_proc pform;
804                 FuncDetailCode result;
805
806                 *funcid = best_candidate->oid;
807                 *true_typeids = best_candidate->args;
808
809                 ftup = SearchSysCache(PROCOID,
810                                                           ObjectIdGetDatum(best_candidate->oid),
811                                                           0, 0, 0);
812                 if (!HeapTupleIsValid(ftup))    /* should not happen */
813                         elog(ERROR, "cache lookup failed for function %u",
814                                  best_candidate->oid);
815                 pform = (Form_pg_proc) GETSTRUCT(ftup);
816                 *rettype = pform->prorettype;
817                 *retset = pform->proretset;
818                 result = pform->proisagg ? FUNCDETAIL_AGGREGATE : FUNCDETAIL_NORMAL;
819                 ReleaseSysCache(ftup);
820                 return result;
821         }
822
823         return FUNCDETAIL_NOTFOUND;
824 }
825
826
827 /*
828  * Given two type OIDs, determine whether the first is a complex type
829  * (class type) that inherits from the second.
830  */
831 bool
832 typeInheritsFrom(Oid subclassTypeId, Oid superclassTypeId)
833 {
834         bool            result = false;
835         Oid                     relid;
836         Relation        inhrel;
837         List       *visited,
838                            *queue;
839         ListCell   *queue_item;
840
841         if (!ISCOMPLEX(subclassTypeId) || !ISCOMPLEX(superclassTypeId))
842                 return false;
843         relid = typeidTypeRelid(subclassTypeId);
844         if (relid == InvalidOid)
845                 return false;
846
847         /*
848          * Begin the search at the relation itself, so add relid to the queue.
849          */
850         queue = list_make1_oid(relid);
851         visited = NIL;
852
853         inhrel = heap_open(InheritsRelationId, AccessShareLock);
854
855         /*
856          * Use queue to do a breadth-first traversal of the inheritance graph from
857          * the relid supplied up to the root.  Notice that we append to the queue
858          * inside the loop --- this is okay because the foreach() macro doesn't
859          * advance queue_item until the next loop iteration begins.
860          */
861         foreach(queue_item, queue)
862         {
863                 Oid                     this_relid = lfirst_oid(queue_item);
864                 ScanKeyData skey;
865                 HeapScanDesc inhscan;
866                 HeapTuple       inhtup;
867
868                 /* If we've seen this relid already, skip it */
869                 if (list_member_oid(visited, this_relid))
870                         continue;
871
872                 /*
873                  * Okay, this is a not-yet-seen relid. Add it to the list of
874                  * already-visited OIDs, then find all the types this relid inherits
875                  * from and add them to the queue. The one exception is we don't add
876                  * the original relation to 'visited'.
877                  */
878                 if (queue_item != list_head(queue))
879                         visited = lappend_oid(visited, this_relid);
880
881                 ScanKeyInit(&skey,
882                                         Anum_pg_inherits_inhrelid,
883                                         BTEqualStrategyNumber, F_OIDEQ,
884                                         ObjectIdGetDatum(this_relid));
885
886                 inhscan = heap_beginscan(inhrel, SnapshotNow, 1, &skey);
887
888                 while ((inhtup = heap_getnext(inhscan, ForwardScanDirection)) != NULL)
889                 {
890                         Form_pg_inherits inh = (Form_pg_inherits) GETSTRUCT(inhtup);
891                         Oid                     inhparent = inh->inhparent;
892
893                         /* If this is the target superclass, we're done */
894                         if (get_rel_type_id(inhparent) == superclassTypeId)
895                         {
896                                 result = true;
897                                 break;
898                         }
899
900                         /* Else add to queue */
901                         queue = lappend_oid(queue, inhparent);
902                 }
903
904                 heap_endscan(inhscan);
905
906                 if (result)
907                         break;
908         }
909
910         heap_close(inhrel, AccessShareLock);
911
912         list_free(visited);
913         list_free(queue);
914
915         return result;
916 }
917
918
919 /*
920  * make_fn_arguments()
921  *
922  * Given the actual argument expressions for a function, and the desired
923  * input types for the function, add any necessary typecasting to the
924  * expression tree.  Caller should already have verified that casting is
925  * allowed.
926  *
927  * Caution: given argument list is modified in-place.
928  *
929  * As with coerce_type, pstate may be NULL if no special unknown-Param
930  * processing is wanted.
931  */
932 void
933 make_fn_arguments(ParseState *pstate,
934                                   List *fargs,
935                                   Oid *actual_arg_types,
936                                   Oid *declared_arg_types)
937 {
938         ListCell   *current_fargs;
939         int                     i = 0;
940
941         foreach(current_fargs, fargs)
942         {
943                 /* types don't match? then force coercion using a function call... */
944                 if (actual_arg_types[i] != declared_arg_types[i])
945                 {
946                         lfirst(current_fargs) = coerce_type(pstate,
947                                                                                                 lfirst(current_fargs),
948                                                                                                 actual_arg_types[i],
949                                                                                                 declared_arg_types[i], -1,
950                                                                                                 COERCION_IMPLICIT,
951                                                                                                 COERCE_IMPLICIT_CAST);
952                 }
953                 i++;
954         }
955 }
956
957 /*
958  * ParseComplexProjection -
959  *        handles function calls with a single argument that is of complex type.
960  *        If the function call is actually a column projection, return a suitably
961  *        transformed expression tree.  If not, return NULL.
962  */
963 static Node *
964 ParseComplexProjection(ParseState *pstate, char *funcname, Node *first_arg,
965                                            int location)
966 {
967         TupleDesc       tupdesc;
968         int                     i;
969
970         /*
971          * Special case for whole-row Vars so that we can resolve (foo.*).bar even
972          * when foo is a reference to a subselect, join, or RECORD function. A
973          * bonus is that we avoid generating an unnecessary FieldSelect; our
974          * result can omit the whole-row Var and just be a Var for the selected
975          * field.
976          *
977          * This case could be handled by expandRecordVariable, but it's more
978          * efficient to do it this way when possible.
979          */
980         if (IsA(first_arg, Var) &&
981                 ((Var *) first_arg)->varattno == InvalidAttrNumber)
982         {
983                 RangeTblEntry *rte;
984
985                 rte = GetRTEByRangeTablePosn(pstate,
986                                                                          ((Var *) first_arg)->varno,
987                                                                          ((Var *) first_arg)->varlevelsup);
988                 /* Return a Var if funcname matches a column, else NULL */
989                 return scanRTEForColumn(pstate, rte, funcname, location);
990         }
991
992         /*
993          * Else do it the hard way with get_expr_result_type().
994          *
995          * If it's a Var of type RECORD, we have to work even harder: we have to
996          * find what the Var refers to, and pass that to get_expr_result_type.
997          * That task is handled by expandRecordVariable().
998          */
999         if (IsA(first_arg, Var) &&
1000                 ((Var *) first_arg)->vartype == RECORDOID)
1001                 tupdesc = expandRecordVariable(pstate, (Var *) first_arg, 0);
1002         else if (get_expr_result_type(first_arg, NULL, &tupdesc) != TYPEFUNC_COMPOSITE)
1003                 return NULL;                    /* unresolvable RECORD type */
1004         Assert(tupdesc);
1005
1006         for (i = 0; i < tupdesc->natts; i++)
1007         {
1008                 Form_pg_attribute att = tupdesc->attrs[i];
1009
1010                 if (strcmp(funcname, NameStr(att->attname)) == 0 &&
1011                         !att->attisdropped)
1012                 {
1013                         /* Success, so generate a FieldSelect expression */
1014                         FieldSelect *fselect = makeNode(FieldSelect);
1015
1016                         fselect->arg = (Expr *) first_arg;
1017                         fselect->fieldnum = i + 1;
1018                         fselect->resulttype = att->atttypid;
1019                         fselect->resulttypmod = att->atttypmod;
1020                         return (Node *) fselect;
1021                 }
1022         }
1023
1024         return NULL;                            /* funcname does not match any column */
1025 }
1026
1027 /*
1028  * helper routine for delivering "column does not exist" error message
1029  */
1030 static void
1031 unknown_attribute(ParseState *pstate, Node *relref, char *attname,
1032                                   int location)
1033 {
1034         RangeTblEntry *rte;
1035
1036         if (IsA(relref, Var) &&
1037                 ((Var *) relref)->varattno == InvalidAttrNumber)
1038         {
1039                 /* Reference the RTE by alias not by actual table name */
1040                 rte = GetRTEByRangeTablePosn(pstate,
1041                                                                          ((Var *) relref)->varno,
1042                                                                          ((Var *) relref)->varlevelsup);
1043                 ereport(ERROR,
1044                                 (errcode(ERRCODE_UNDEFINED_COLUMN),
1045                                  errmsg("column %s.%s does not exist",
1046                                                 rte->eref->aliasname, attname),
1047                                  parser_errposition(pstate, location)));
1048         }
1049         else
1050         {
1051                 /* Have to do it by reference to the type of the expression */
1052                 Oid                     relTypeId = exprType(relref);
1053
1054                 if (ISCOMPLEX(relTypeId))
1055                         ereport(ERROR,
1056                                         (errcode(ERRCODE_UNDEFINED_COLUMN),
1057                                          errmsg("column \"%s\" not found in data type %s",
1058                                                         attname, format_type_be(relTypeId)),
1059                                          parser_errposition(pstate, location)));
1060                 else if (relTypeId == RECORDOID)
1061                         ereport(ERROR,
1062                                         (errcode(ERRCODE_UNDEFINED_COLUMN),
1063                            errmsg("could not identify column \"%s\" in record data type",
1064                                           attname),
1065                                          parser_errposition(pstate, location)));
1066                 else
1067                         ereport(ERROR,
1068                                         (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1069                                          errmsg("column notation .%s applied to type %s, "
1070                                                         "which is not a composite type",
1071                                                         attname, format_type_be(relTypeId)),
1072                                          parser_errposition(pstate, location)));
1073         }
1074 }
1075
1076 /*
1077  * funcname_signature_string
1078  *              Build a string representing a function name, including arg types.
1079  *              The result is something like "foo(integer)".
1080  *
1081  * This is typically used in the construction of function-not-found error
1082  * messages.
1083  */
1084 const char *
1085 funcname_signature_string(const char *funcname,
1086                                                   int nargs, const Oid *argtypes)
1087 {
1088         StringInfoData argbuf;
1089         int                     i;
1090
1091         initStringInfo(&argbuf);
1092
1093         appendStringInfo(&argbuf, "%s(", funcname);
1094
1095         for (i = 0; i < nargs; i++)
1096         {
1097                 if (i)
1098                         appendStringInfoString(&argbuf, ", ");
1099                 appendStringInfoString(&argbuf, format_type_be(argtypes[i]));
1100         }
1101
1102         appendStringInfoChar(&argbuf, ')');
1103
1104         return argbuf.data;                     /* return palloc'd string buffer */
1105 }
1106
1107 /*
1108  * func_signature_string
1109  *              As above, but function name is passed as a qualified name list.
1110  */
1111 const char *
1112 func_signature_string(List *funcname, int nargs, const Oid *argtypes)
1113 {
1114         return funcname_signature_string(NameListToString(funcname),
1115                                                                          nargs, argtypes);
1116 }
1117
1118 /*
1119  * LookupFuncName
1120  *              Given a possibly-qualified function name and a set of argument types,
1121  *              look up the function.
1122  *
1123  * If the function name is not schema-qualified, it is sought in the current
1124  * namespace search path.
1125  *
1126  * If the function is not found, we return InvalidOid if noError is true,
1127  * else raise an error.
1128  */
1129 Oid
1130 LookupFuncName(List *funcname, int nargs, const Oid *argtypes, bool noError)
1131 {
1132         FuncCandidateList clist;
1133
1134         clist = FuncnameGetCandidates(funcname, nargs);
1135
1136         while (clist)
1137         {
1138                 if (memcmp(argtypes, clist->args, nargs * sizeof(Oid)) == 0)
1139                         return clist->oid;
1140                 clist = clist->next;
1141         }
1142
1143         if (!noError)
1144                 ereport(ERROR,
1145                                 (errcode(ERRCODE_UNDEFINED_FUNCTION),
1146                                  errmsg("function %s does not exist",
1147                                                 func_signature_string(funcname, nargs, argtypes))));
1148
1149         return InvalidOid;
1150 }
1151
1152 /*
1153  * LookupFuncNameTypeNames
1154  *              Like LookupFuncName, but the argument types are specified by a
1155  *              list of TypeName nodes.
1156  */
1157 Oid
1158 LookupFuncNameTypeNames(List *funcname, List *argtypes, bool noError)
1159 {
1160         Oid                     argoids[FUNC_MAX_ARGS];
1161         int                     argcount;
1162         int                     i;
1163         ListCell   *args_item;
1164
1165         argcount = list_length(argtypes);
1166         if (argcount > FUNC_MAX_ARGS)
1167                 ereport(ERROR,
1168                                 (errcode(ERRCODE_TOO_MANY_ARGUMENTS),
1169                                  errmsg("functions cannot have more than %d arguments",
1170                                                 FUNC_MAX_ARGS)));
1171
1172         args_item = list_head(argtypes);
1173         for (i = 0; i < argcount; i++)
1174         {
1175                 TypeName   *t = (TypeName *) lfirst(args_item);
1176
1177                 argoids[i] = LookupTypeName(NULL, t);
1178
1179                 if (!OidIsValid(argoids[i]))
1180                         ereport(ERROR,
1181                                         (errcode(ERRCODE_UNDEFINED_OBJECT),
1182                                          errmsg("type \"%s\" does not exist",
1183                                                         TypeNameToString(t))));
1184
1185                 args_item = lnext(args_item);
1186         }
1187
1188         return LookupFuncName(funcname, argcount, argoids, noError);
1189 }
1190
1191 /*
1192  * LookupAggNameTypeNames
1193  *              Find an aggregate function given a name and list of TypeName nodes.
1194  *
1195  * This is almost like LookupFuncNameTypeNames, but the error messages refer
1196  * to aggregates rather than plain functions, and we verify that the found
1197  * function really is an aggregate, and we recognize the convention used by
1198  * the grammar that agg(*) translates to a NIL list, which we have to treat
1199  * as one ANY argument.  (XXX this ought to be changed)
1200  */
1201 Oid
1202 LookupAggNameTypeNames(List *aggname, List *argtypes, bool noError)
1203 {
1204         Oid                     argoids[FUNC_MAX_ARGS];
1205         int                     argcount;
1206         int                     i;
1207         ListCell   *args_item;
1208         Oid                     oid;
1209         HeapTuple       ftup;
1210         Form_pg_proc pform;
1211
1212         argcount = list_length(argtypes);
1213         if (argcount > FUNC_MAX_ARGS)
1214                 ereport(ERROR,
1215                                 (errcode(ERRCODE_TOO_MANY_ARGUMENTS),
1216                                  errmsg("functions cannot have more than %d arguments",
1217                                                 FUNC_MAX_ARGS)));
1218
1219         if (argcount == 0)
1220         {
1221                 /* special case for agg(*) */
1222                 argoids[0] = ANYOID;
1223                 argcount = 1;
1224         }
1225         else
1226         {
1227                 args_item = list_head(argtypes);
1228                 for (i = 0; i < argcount; i++)
1229                 {
1230                         TypeName   *t = (TypeName *) lfirst(args_item);
1231
1232                         argoids[i] = LookupTypeName(NULL, t);
1233
1234                         if (!OidIsValid(argoids[i]))
1235                                 ereport(ERROR,
1236                                                 (errcode(ERRCODE_UNDEFINED_OBJECT),
1237                                                  errmsg("type \"%s\" does not exist",
1238                                                                 TypeNameToString(t))));
1239
1240                         args_item = lnext(args_item);
1241                 }
1242         }
1243
1244         oid = LookupFuncName(aggname, argcount, argoids, true);
1245
1246         if (!OidIsValid(oid))
1247         {
1248                 if (noError)
1249                         return InvalidOid;
1250                 if (argcount == 1 && argoids[0] == ANYOID)
1251                         ereport(ERROR,
1252                                         (errcode(ERRCODE_UNDEFINED_FUNCTION),
1253                                          errmsg("aggregate %s(*) does not exist",
1254                                                         NameListToString(aggname))));
1255                 else
1256                         ereport(ERROR,
1257                                         (errcode(ERRCODE_UNDEFINED_FUNCTION),
1258                                          errmsg("aggregate %s does not exist",
1259                                                         func_signature_string(aggname,
1260                                                                                                   argcount, argoids))));
1261         }
1262
1263         /* Make sure it's an aggregate */
1264         ftup = SearchSysCache(PROCOID,
1265                                                   ObjectIdGetDatum(oid),
1266                                                   0, 0, 0);
1267         if (!HeapTupleIsValid(ftup))    /* should not happen */
1268                 elog(ERROR, "cache lookup failed for function %u", oid);
1269         pform = (Form_pg_proc) GETSTRUCT(ftup);
1270
1271         if (!pform->proisagg)
1272         {
1273                 ReleaseSysCache(ftup);
1274                 if (noError)
1275                         return InvalidOid;
1276                 /* we do not use the (*) notation for functions... */
1277                 ereport(ERROR,
1278                                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1279                                  errmsg("function %s is not an aggregate",
1280                                                 func_signature_string(aggname,
1281                                                                                           argcount, argoids))));
1282         }
1283
1284         ReleaseSysCache(ftup);
1285
1286         return oid;
1287 }