]> granicus.if.org Git - postgresql/blob - src/backend/parser/parse_func.c
Implement feature of new FE/BE protocol whereby RowDescription identifies
[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-2002, PostgreSQL Global Development Group
7  * Portions Copyright (c) 1994, Regents of the University of California
8  *
9  *
10  * IDENTIFICATION
11  *        $Header: /cvsroot/pgsql/src/backend/parser/parse_func.c,v 1.147 2003/04/29 22:13:10 tgl Exp $
12  *
13  *-------------------------------------------------------------------------
14  */
15 #include "postgres.h"
16
17 #include "access/heapam.h"
18 #include "catalog/catname.h"
19 #include "catalog/namespace.h"
20 #include "catalog/pg_inherits.h"
21 #include "catalog/pg_proc.h"
22 #include "lib/stringinfo.h"
23 #include "nodes/makefuncs.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_type.h"
29 #include "utils/builtins.h"
30 #include "utils/fmgroids.h"
31 #include "utils/lsyscache.h"
32 #include "utils/syscache.h"
33
34
35 static Node *ParseComplexProjection(char *funcname, Node *first_arg);
36 static Oid **argtype_inherit(int nargs, Oid *argtypes);
37
38 static int      find_inheritors(Oid relid, Oid **supervec);
39 static Oid **gen_cross_product(InhPaths *arginh, int nargs);
40 static int match_argtypes(int nargs,
41                            Oid *input_typeids,
42                            FuncCandidateList function_typeids,
43                            FuncCandidateList *candidates);
44 static FieldSelect *setup_field_select(Node *input, char *attname, Oid relid);
45 static FuncCandidateList func_select_candidate(int nargs, Oid *input_typeids,
46                                           FuncCandidateList candidates);
47 static void unknown_attribute(const char *schemaname, const char *relname,
48                                   const char *attname);
49
50
51 /*
52  *      Parse a function call
53  *
54  *      For historical reasons, Postgres tries to treat the notations tab.col
55  *      and col(tab) as equivalent: if a single-argument function call has an
56  *      argument of complex type and the (unqualified) function name matches
57  *      any attribute of the type, we take it as a column projection.
58  *
59  *      Hence, both cases come through here.  The is_column parameter tells us
60  *      which syntactic construct is actually being dealt with, but this is
61  *      intended to be used only to deliver an appropriate error message,
62  *      not to affect the semantics.  When is_column is true, we should have
63  *      a single argument (the putative table), unqualified function name
64  *      equal to the column name, and no aggregate decoration.
65  *
66  *      In the function-call case, the argument expressions have been transformed
67  *      already.  In the column case, we may get either a transformed expression
68  *      or a RangeVar node as argument.
69  */
70 Node *
71 ParseFuncOrColumn(ParseState *pstate, List *funcname, List *fargs,
72                                   bool agg_star, bool agg_distinct, bool is_column)
73 {
74         Oid                     rettype;
75         Oid                     funcid;
76         List       *i;
77         Node       *first_arg = NULL;
78         int                     nargs = length(fargs);
79         int                     argn;
80         Oid                     actual_arg_types[FUNC_MAX_ARGS];
81         Oid                *declared_arg_types;
82         Node       *retval;
83         bool            retset;
84         FuncDetailCode fdresult;
85
86         /*
87          * Most of the rest of the parser just assumes that functions do not
88          * have more than FUNC_MAX_ARGS parameters.  We have to test here to
89          * protect against array overruns, etc.  Of course, this may not be a
90          * function, but the test doesn't hurt.
91          */
92         if (nargs > FUNC_MAX_ARGS)
93                 elog(ERROR, "Cannot pass more than %d arguments to a function",
94                          FUNC_MAX_ARGS);
95
96         if (fargs)
97         {
98                 first_arg = lfirst(fargs);
99                 if (first_arg == NULL)  /* should not happen */
100                         elog(ERROR, "Function '%s' does not allow NULL input",
101                                  NameListToString(funcname));
102         }
103
104         /*
105          * check for column projection: if function has one argument, and that
106          * argument is of complex type, and function name is not qualified,
107          * then the "function call" could be a projection.      We also check that
108          * there wasn't any aggregate decoration.
109          */
110         if (nargs == 1 && !agg_star && !agg_distinct && length(funcname) == 1)
111         {
112                 char       *cname = strVal(lfirst(funcname));
113
114                 /* Is it a not-yet-transformed RangeVar node? */
115                 if (IsA(first_arg, RangeVar))
116                 {
117                         /* First arg is a relation. This could be a projection. */
118                         retval = qualifiedNameToVar(pstate,
119                                                                         ((RangeVar *) first_arg)->schemaname,
120                                                                                 ((RangeVar *) first_arg)->relname,
121                                                                                 cname,
122                                                                                 true);
123                         if (retval)
124                                 return retval;
125                 }
126                 else if (ISCOMPLEX(exprType(first_arg)))
127                 {
128                         /*
129                          * Attempt to handle projection of a complex argument. If
130                          * ParseComplexProjection can't handle the projection, we have
131                          * to keep going.
132                          */
133                         retval = ParseComplexProjection(cname, first_arg);
134                         if (retval)
135                                 return retval;
136                 }
137         }
138
139         /*
140          * Okay, it's not a column projection, so it must really be a
141          * function. Extract arg type info and transform RangeVar arguments
142          * into varnodes of the appropriate form.
143          */
144         MemSet(actual_arg_types, 0, FUNC_MAX_ARGS * sizeof(Oid));
145
146         argn = 0;
147         foreach(i, fargs)
148         {
149                 Node       *arg = lfirst(i);
150                 Oid                     toid;
151
152                 if (IsA(arg, RangeVar))
153                 {
154                         char       *schemaname;
155                         char       *relname;
156                         RangeTblEntry *rte;
157                         int                     vnum;
158                         int                     sublevels_up;
159
160                         /*
161                          * a relation: look it up in the range table, or add if needed
162                          */
163                         schemaname = ((RangeVar *) arg)->schemaname;
164                         relname = ((RangeVar *) arg)->relname;
165
166                         rte = refnameRangeTblEntry(pstate, schemaname, relname,
167                                                                            &sublevels_up);
168
169                         if (rte == NULL)
170                                 rte = addImplicitRTE(pstate, (RangeVar *) arg);
171
172                         vnum = RTERangeTablePosn(pstate, rte, &sublevels_up);
173
174                         /*
175                          * The parameter to be passed to the function is the whole
176                          * tuple from the relation.  We build a special VarNode to
177                          * reflect this -- it has varno set to the correct range table
178                          * entry, but has varattno == 0 to signal that the whole tuple
179                          * is the argument.  Also, it has typmod set to
180                          * sizeof(Pointer) to signal that the runtime representation
181                          * will be a pointer not an Oid.
182                          */
183                         switch (rte->rtekind)
184                         {
185                                 case RTE_RELATION:
186                                         toid = get_rel_type_id(rte->relid);
187                                         if (!OidIsValid(toid))
188                                                 elog(ERROR, "Cannot find type OID for relation %u",
189                                                          rte->relid);
190                                         /* replace RangeVar in the arg list */
191                                         lfirst(i) = makeVar(vnum,
192                                                                                 InvalidAttrNumber,
193                                                                                 toid,
194                                                                                 sizeof(Pointer),
195                                                                                 sublevels_up);
196                                         break;
197                                 case RTE_FUNCTION:
198                                         toid = exprType(rte->funcexpr);
199                                         if (get_typtype(toid) == 'c')
200                                         {
201                                                 /* func returns composite; same as relation case */
202                                                 lfirst(i) = makeVar(vnum,
203                                                                                         InvalidAttrNumber,
204                                                                                         toid,
205                                                                                         sizeof(Pointer),
206                                                                                         sublevels_up);
207                                         }
208                                         else
209                                         {
210                                                 /* func returns scalar; use attno 1 instead */
211                                                 lfirst(i) = makeVar(vnum,
212                                                                                         1,
213                                                                                         toid,
214                                                                                         -1,
215                                                                                         sublevels_up);
216                                         }
217                                         break;
218                                 default:
219
220                                         /*
221                                          * RTE is a join or subselect; must fail for lack of a
222                                          * named tuple type
223                                          */
224                                         if (is_column)
225                                                 unknown_attribute(schemaname, relname,
226                                                                                   strVal(lfirst(funcname)));
227                                         else
228                                                 elog(ERROR, "Cannot pass result of sub-select or join %s to a function",
229                                                          relname);
230                                         toid = InvalidOid;      /* keep compiler quiet */
231                                         break;
232                         }
233                 }
234                 else
235                         toid = exprType(arg);
236
237                 actual_arg_types[argn++] = toid;
238         }
239
240         /*
241          * func_get_detail looks up the function in the catalogs, does
242          * disambiguation for polymorphic functions, handles inheritance, and
243          * returns the funcid and type and set or singleton status of the
244          * function's return value.  it also returns the true argument types
245          * to the function.
246          */
247         fdresult = func_get_detail(funcname, fargs, nargs, actual_arg_types,
248                                                            &funcid, &rettype, &retset,
249                                                            &declared_arg_types);
250         if (fdresult == FUNCDETAIL_COERCION)
251         {
252                 /*
253                  * We can do it as a trivial coercion. coerce_type can handle
254                  * these cases, so why duplicate code...
255                  */
256                 return coerce_type(pstate, lfirst(fargs), actual_arg_types[0],
257                                                    rettype,
258                                                    COERCION_EXPLICIT, COERCE_EXPLICIT_CALL);
259         }
260         else if (fdresult == FUNCDETAIL_NORMAL)
261         {
262                 /*
263                  * Normal function found; was there anything indicating it must be
264                  * an aggregate?
265                  */
266                 if (agg_star)
267                         elog(ERROR, "%s(*) specified, but %s is not an aggregate function",
268                                  NameListToString(funcname), NameListToString(funcname));
269                 if (agg_distinct)
270                         elog(ERROR, "DISTINCT specified, but %s is not an aggregate function",
271                                  NameListToString(funcname));
272         }
273         else if (fdresult != FUNCDETAIL_AGGREGATE)
274         {
275                 /*
276                  * Oops.  Time to die.
277                  *
278                  * If we are dealing with the attribute notation rel.function, give
279                  * an error message that is appropriate for that case.
280                  */
281                 if (is_column)
282                 {
283                         char       *colname = strVal(lfirst(funcname));
284                         Oid                     relTypeId;
285
286                         Assert(nargs == 1);
287                         if (IsA(first_arg, RangeVar))
288                                 unknown_attribute(((RangeVar *) first_arg)->schemaname,
289                                                                   ((RangeVar *) first_arg)->relname,
290                                                                   colname);
291                         relTypeId = exprType(first_arg);
292                         if (!ISCOMPLEX(relTypeId))
293                                 elog(ERROR, "Attribute notation .%s applied to type %s, which is not a complex type",
294                                          colname, format_type_be(relTypeId));
295                         else
296                                 elog(ERROR, "Attribute \"%s\" not found in datatype %s",
297                                          colname, format_type_be(relTypeId));
298                 }
299
300                 /*
301                  * Else generate a detailed complaint for a function
302                  */
303                 func_error(NULL, funcname, nargs, actual_arg_types,
304                                    "Unable to identify a function that satisfies the "
305                                    "given argument types"
306                                    "\n\tYou may need to add explicit typecasts");
307         }
308
309         /*
310          * enforce consistency with ANYARRAY and ANYELEMENT argument and
311          * return types, possibly adjusting return type or declared_arg_types
312          * (which will be used as the cast destination by make_fn_arguments)
313          */
314         rettype = enforce_generic_type_consistency(actual_arg_types,
315                                                                                            declared_arg_types,
316                                                                                            nargs,
317                                                                                            rettype);
318
319         /* perform the necessary typecasting of arguments */
320         make_fn_arguments(pstate, fargs, actual_arg_types, declared_arg_types);
321
322         /* build the appropriate output structure */
323         if (fdresult == FUNCDETAIL_NORMAL)
324         {
325                 FuncExpr   *funcexpr = makeNode(FuncExpr);
326
327                 funcexpr->funcid = funcid;
328                 funcexpr->funcresulttype = rettype;
329                 funcexpr->funcretset = retset;
330                 funcexpr->funcformat = COERCE_EXPLICIT_CALL;
331                 funcexpr->args = fargs;
332
333                 retval = (Node *) funcexpr;
334         }
335         else
336         {
337                 /* aggregate function */
338                 Aggref     *aggref = makeNode(Aggref);
339
340                 aggref->aggfnoid = funcid;
341                 aggref->aggtype = rettype;
342                 aggref->target = lfirst(fargs);
343                 aggref->aggstar = agg_star;
344                 aggref->aggdistinct = agg_distinct;
345
346                 retval = (Node *) aggref;
347
348                 if (retset)
349                         elog(ERROR, "Aggregates may not return sets");
350
351                 pstate->p_hasAggs = true;
352         }
353
354         return retval;
355 }
356
357
358 /* match_argtypes()
359  *
360  * Given a list of possible typeid arrays to a function and an array of
361  * input typeids, produce a shortlist of those function typeid arrays
362  * that match the input typeids (either exactly or by coercion), and
363  * return the number of such arrays.
364  *
365  * NB: okay to modify input list structure, as long as we find at least
366  * one match.
367  */
368 static int
369 match_argtypes(int nargs,
370                            Oid *input_typeids,
371                            FuncCandidateList function_typeids,
372                            FuncCandidateList *candidates)       /* return value */
373 {
374         FuncCandidateList current_candidate;
375         FuncCandidateList next_candidate;
376         int                     ncandidates = 0;
377
378         *candidates = NULL;
379
380         for (current_candidate = function_typeids;
381                  current_candidate != NULL;
382                  current_candidate = next_candidate)
383         {
384                 next_candidate = current_candidate->next;
385                 if (can_coerce_type(nargs, input_typeids, current_candidate->args,
386                                                         COERCION_IMPLICIT))
387                 {
388                         current_candidate->next = *candidates;
389                         *candidates = current_candidate;
390                         ncandidates++;
391                 }
392         }
393
394         return ncandidates;
395 }       /* match_argtypes() */
396
397
398 /* func_select_candidate()
399  * Given the input argtype array and more than one candidate
400  * for the function, attempt to resolve the conflict.
401  * Returns the selected candidate if the conflict can be resolved,
402  * otherwise returns NULL.
403  *
404  * By design, this is pretty similar to oper_select_candidate in parse_oper.c.
405  * However, the calling convention is a little different: we assume the caller
406  * already pruned away "candidates" that aren't actually coercion-compatible
407  * with the input types, whereas oper_select_candidate must do that itself.
408  */
409 static FuncCandidateList
410 func_select_candidate(int nargs,
411                                           Oid *input_typeids,
412                                           FuncCandidateList candidates)
413 {
414         FuncCandidateList current_candidate;
415         FuncCandidateList last_candidate;
416         Oid                *current_typeids;
417         Oid                     current_type;
418         int                     i;
419         int                     ncandidates;
420         int                     nbestMatch,
421                                 nmatch;
422         CATEGORY        slot_category[FUNC_MAX_ARGS],
423                                 current_category;
424         bool            slot_has_preferred_type[FUNC_MAX_ARGS];
425         bool            resolved_unknowns;
426
427         /*
428          * Run through all candidates and keep those with the most matches on
429          * exact types. Keep all candidates if none match.
430          */
431         ncandidates = 0;
432         nbestMatch = 0;
433         last_candidate = NULL;
434         for (current_candidate = candidates;
435                  current_candidate != NULL;
436                  current_candidate = current_candidate->next)
437         {
438                 current_typeids = current_candidate->args;
439                 nmatch = 0;
440                 for (i = 0; i < nargs; i++)
441                 {
442                         if (input_typeids[i] != UNKNOWNOID &&
443                                 current_typeids[i] == input_typeids[i])
444                                 nmatch++;
445                 }
446
447                 /* take this one as the best choice so far? */
448                 if ((nmatch > nbestMatch) || (last_candidate == NULL))
449                 {
450                         nbestMatch = nmatch;
451                         candidates = current_candidate;
452                         last_candidate = current_candidate;
453                         ncandidates = 1;
454                 }
455                 /* no worse than the last choice, so keep this one too? */
456                 else if (nmatch == nbestMatch)
457                 {
458                         last_candidate->next = current_candidate;
459                         last_candidate = current_candidate;
460                         ncandidates++;
461                 }
462                 /* otherwise, don't bother keeping this one... */
463         }
464
465         if (last_candidate)                     /* terminate rebuilt list */
466                 last_candidate->next = NULL;
467
468         if (ncandidates == 1)
469                 return candidates;
470
471         /*
472          * Still too many candidates? Run through all candidates and keep
473          * those with the most matches on exact types + binary-compatible
474          * types. Keep all candidates if none match.
475          */
476         ncandidates = 0;
477         nbestMatch = 0;
478         last_candidate = NULL;
479         for (current_candidate = candidates;
480                  current_candidate != NULL;
481                  current_candidate = current_candidate->next)
482         {
483                 current_typeids = current_candidate->args;
484                 nmatch = 0;
485                 for (i = 0; i < nargs; i++)
486                 {
487                         if (input_typeids[i] != UNKNOWNOID)
488                         {
489                                 if (IsBinaryCoercible(input_typeids[i], current_typeids[i]))
490                                         nmatch++;
491                         }
492                 }
493
494                 /* take this one as the best choice so far? */
495                 if ((nmatch > nbestMatch) || (last_candidate == NULL))
496                 {
497                         nbestMatch = nmatch;
498                         candidates = current_candidate;
499                         last_candidate = current_candidate;
500                         ncandidates = 1;
501                 }
502                 /* no worse than the last choice, so keep this one too? */
503                 else if (nmatch == nbestMatch)
504                 {
505                         last_candidate->next = current_candidate;
506                         last_candidate = current_candidate;
507                         ncandidates++;
508                 }
509                 /* otherwise, don't bother keeping this one... */
510         }
511
512         if (last_candidate)                     /* terminate rebuilt list */
513                 last_candidate->next = NULL;
514
515         if (ncandidates == 1)
516                 return candidates;
517
518         /*
519          * Still too many candidates? Now look for candidates which are
520          * preferred types at the args that will require coercion. Keep all
521          * candidates if none match.
522          */
523         ncandidates = 0;
524         nbestMatch = 0;
525         last_candidate = NULL;
526         for (current_candidate = candidates;
527                  current_candidate != NULL;
528                  current_candidate = current_candidate->next)
529         {
530                 current_typeids = current_candidate->args;
531                 nmatch = 0;
532                 for (i = 0; i < nargs; i++)
533                 {
534                         if (input_typeids[i] != UNKNOWNOID)
535                         {
536                                 current_category = TypeCategory(current_typeids[i]);
537                                 if (current_typeids[i] == input_typeids[i] ||
538                                         IsPreferredType(current_category, current_typeids[i]))
539                                         nmatch++;
540                         }
541                 }
542
543                 if ((nmatch > nbestMatch) || (last_candidate == NULL))
544                 {
545                         nbestMatch = nmatch;
546                         candidates = current_candidate;
547                         last_candidate = current_candidate;
548                         ncandidates = 1;
549                 }
550                 else if (nmatch == nbestMatch)
551                 {
552                         last_candidate->next = current_candidate;
553                         last_candidate = current_candidate;
554                         ncandidates++;
555                 }
556         }
557
558         if (last_candidate)                     /* terminate rebuilt list */
559                 last_candidate->next = NULL;
560
561         if (ncandidates == 1)
562                 return candidates;
563
564         /*
565          * Still too many candidates? Try assigning types for the unknown
566          * columns.
567          *
568          * We do this by examining each unknown argument position to see if we
569          * can determine a "type category" for it.      If any candidate has an
570          * input datatype of STRING category, use STRING category (this bias
571          * towards STRING is appropriate since unknown-type literals look like
572          * strings).  Otherwise, if all the candidates agree on the type
573          * category of this argument position, use that category.  Otherwise,
574          * fail because we cannot determine a category.
575          *
576          * If we are able to determine a type category, also notice whether any
577          * of the candidates takes a preferred datatype within the category.
578          *
579          * Having completed this examination, remove candidates that accept the
580          * wrong category at any unknown position.      Also, if at least one
581          * candidate accepted a preferred type at a position, remove
582          * candidates that accept non-preferred types.
583          *
584          * If we are down to one candidate at the end, we win.
585          */
586         resolved_unknowns = false;
587         for (i = 0; i < nargs; i++)
588         {
589                 bool            have_conflict;
590
591                 if (input_typeids[i] != UNKNOWNOID)
592                         continue;
593                 resolved_unknowns = true;               /* assume we can do it */
594                 slot_category[i] = INVALID_TYPE;
595                 slot_has_preferred_type[i] = false;
596                 have_conflict = false;
597                 for (current_candidate = candidates;
598                          current_candidate != NULL;
599                          current_candidate = current_candidate->next)
600                 {
601                         current_typeids = current_candidate->args;
602                         current_type = current_typeids[i];
603                         current_category = TypeCategory(current_type);
604                         if (slot_category[i] == INVALID_TYPE)
605                         {
606                                 /* first candidate */
607                                 slot_category[i] = current_category;
608                                 slot_has_preferred_type[i] =
609                                         IsPreferredType(current_category, current_type);
610                         }
611                         else if (current_category == slot_category[i])
612                         {
613                                 /* more candidates in same category */
614                                 slot_has_preferred_type[i] |=
615                                         IsPreferredType(current_category, current_type);
616                         }
617                         else
618                         {
619                                 /* category conflict! */
620                                 if (current_category == STRING_TYPE)
621                                 {
622                                         /* STRING always wins if available */
623                                         slot_category[i] = current_category;
624                                         slot_has_preferred_type[i] =
625                                                 IsPreferredType(current_category, current_type);
626                                 }
627                                 else
628                                 {
629                                         /*
630                                          * Remember conflict, but keep going (might find
631                                          * STRING)
632                                          */
633                                         have_conflict = true;
634                                 }
635                         }
636                 }
637                 if (have_conflict && slot_category[i] != STRING_TYPE)
638                 {
639                         /* Failed to resolve category conflict at this position */
640                         resolved_unknowns = false;
641                         break;
642                 }
643         }
644
645         if (resolved_unknowns)
646         {
647                 /* Strip non-matching candidates */
648                 ncandidates = 0;
649                 last_candidate = NULL;
650                 for (current_candidate = candidates;
651                          current_candidate != NULL;
652                          current_candidate = current_candidate->next)
653                 {
654                         bool            keepit = true;
655
656                         current_typeids = current_candidate->args;
657                         for (i = 0; i < nargs; i++)
658                         {
659                                 if (input_typeids[i] != UNKNOWNOID)
660                                         continue;
661                                 current_type = current_typeids[i];
662                                 current_category = TypeCategory(current_type);
663                                 if (current_category != slot_category[i])
664                                 {
665                                         keepit = false;
666                                         break;
667                                 }
668                                 if (slot_has_preferred_type[i] &&
669                                         !IsPreferredType(current_category, current_type))
670                                 {
671                                         keepit = false;
672                                         break;
673                                 }
674                         }
675                         if (keepit)
676                         {
677                                 /* keep this candidate */
678                                 last_candidate = current_candidate;
679                                 ncandidates++;
680                         }
681                         else
682                         {
683                                 /* forget this candidate */
684                                 if (last_candidate)
685                                         last_candidate->next = current_candidate->next;
686                                 else
687                                         candidates = current_candidate->next;
688                         }
689                 }
690                 if (last_candidate)             /* terminate rebuilt list */
691                         last_candidate->next = NULL;
692         }
693
694         if (ncandidates == 1)
695                 return candidates;
696
697         return NULL;                            /* failed to determine a unique candidate */
698 }       /* func_select_candidate() */
699
700
701 /* func_get_detail()
702  *
703  * Find the named function in the system catalogs.
704  *
705  * Attempt to find the named function in the system catalogs with
706  *      arguments exactly as specified, so that the normal case
707  *      (exact match) is as quick as possible.
708  *
709  * If an exact match isn't found:
710  *      1) check for possible interpretation as a trivial type coercion
711  *      2) get a vector of all possible input arg type arrays constructed
712  *         from the superclasses of the original input arg types
713  *      3) get a list of all possible argument type arrays to the function
714  *         with given name and number of arguments
715  *      4) for each input arg type array from vector #1:
716  *       a) find how many of the function arg type arrays from list #2
717  *              it can be coerced to
718  *       b) if the answer is one, we have our function
719  *       c) if the answer is more than one, attempt to resolve the conflict
720  *       d) if the answer is zero, try the next array from vector #1
721  *
722  * Note: we rely primarily on nargs/argtypes as the argument description.
723  * The actual expression node list is passed in fargs so that we can check
724  * for type coercion of a constant.  Some callers pass fargs == NIL
725  * indicating they don't want that check made.
726  */
727 FuncDetailCode
728 func_get_detail(List *funcname,
729                                 List *fargs,
730                                 int nargs,
731                                 Oid *argtypes,
732                                 Oid *funcid,    /* return value */
733                                 Oid *rettype,   /* return value */
734                                 bool *retset,   /* return value */
735                                 Oid **true_typeids)             /* return value */
736 {
737         FuncCandidateList function_typeids;
738         FuncCandidateList best_candidate;
739
740         /* Get list of possible candidates from namespace search */
741         function_typeids = FuncnameGetCandidates(funcname, nargs);
742
743         /*
744          * See if there is an exact match
745          */
746         for (best_candidate = function_typeids;
747                  best_candidate != NULL;
748                  best_candidate = best_candidate->next)
749         {
750                 if (memcmp(argtypes, best_candidate->args, nargs * sizeof(Oid)) == 0)
751                         break;
752         }
753
754         if (best_candidate == NULL)
755         {
756                 /*
757                  * If we didn't find an exact match, next consider the possibility
758                  * that this is really a type-coercion request: a single-argument
759                  * function call where the function name is a type name.  If so,
760                  * and if we can do the coercion trivially (no run-time function
761                  * call needed), then go ahead and treat the "function call" as a
762                  * coercion.  This interpretation needs to be given higher
763                  * priority than interpretations involving a type coercion
764                  * followed by a function call, otherwise we can produce
765                  * surprising results. For example, we want "text(varchar)" to be
766                  * interpreted as a trivial coercion, not as "text(name(varchar))"
767                  * which the code below this point is entirely capable of
768                  * selecting.
769                  *
770                  * "Trivial" coercions are ones that involve binary-compatible types
771                  * and ones that are coercing a previously-unknown-type literal
772                  * constant to a specific type.
773                  *
774                  * The reason we can restrict our check to binary-compatible
775                  * coercions here is that we expect non-binary-compatible coercions
776                  * to have an implementation function named after the target type.
777                  * That function will be found by normal lookup if appropriate.
778                  *
779                  * NB: it's important that this code stays in sync with what
780                  * coerce_type can do, because the caller will try to apply
781                  * coerce_type if we return FUNCDETAIL_COERCION.  If we return
782                  * that result for something coerce_type can't handle, we'll cause
783                  * infinite recursion between this module and coerce_type!
784                  */
785                 if (nargs == 1 && fargs != NIL)
786                 {
787                         Oid                     targetType;
788                         TypeName   *tn = makeNode(TypeName);
789
790                         tn->names = funcname;
791                         tn->typmod = -1;
792                         targetType = LookupTypeName(tn);
793                         if (OidIsValid(targetType) &&
794                                 !ISCOMPLEX(targetType))
795                         {
796                                 Oid                     sourceType = argtypes[0];
797                                 Node       *arg1 = lfirst(fargs);
798
799                                 if ((sourceType == UNKNOWNOID && IsA(arg1, Const)) ||
800                                         (find_coercion_pathway(targetType, sourceType,
801                                                                                    COERCION_EXPLICIT, funcid) &&
802                                          *funcid == InvalidOid))
803                                 {
804                                         /* Yup, it's a type coercion */
805                                         *funcid = InvalidOid;
806                                         *rettype = targetType;
807                                         *retset = false;
808                                         *true_typeids = argtypes;
809                                         return FUNCDETAIL_COERCION;
810                                 }
811                         }
812                 }
813
814                 /*
815                  * didn't find an exact match, so now try to match up
816                  * candidates...
817                  */
818                 if (function_typeids != NULL)
819                 {
820                         Oid               **input_typeid_vector = NULL;
821                         Oid                *current_input_typeids;
822
823                         /*
824                          * First we will search with the given argtypes, then with
825                          * variants based on replacing complex types with their
826                          * inheritance ancestors.  Stop as soon as any match is found.
827                          */
828                         current_input_typeids = argtypes;
829
830                         do
831                         {
832                                 FuncCandidateList current_function_typeids;
833                                 int                     ncandidates;
834
835                                 ncandidates = match_argtypes(nargs, current_input_typeids,
836                                                                                          function_typeids,
837                                                                                          &current_function_typeids);
838
839                                 /* one match only? then run with it... */
840                                 if (ncandidates == 1)
841                                 {
842                                         best_candidate = current_function_typeids;
843                                         break;
844                                 }
845
846                                 /*
847                                  * multiple candidates? then better decide or throw an
848                                  * error...
849                                  */
850                                 if (ncandidates > 1)
851                                 {
852                                         best_candidate = func_select_candidate(nargs,
853                                                                                                    current_input_typeids,
854                                                                                            current_function_typeids);
855
856                                         /*
857                                          * If we were able to choose a best candidate, we're
858                                          * done.  Otherwise, ambiguous function call, so fail
859                                          * by exiting loop with best_candidate still NULL.
860                                          * Either way, we're outta here.
861                                          */
862                                         break;
863                                 }
864
865                                 /*
866                                  * No match here, so try the next inherited type vector.
867                                  * First time through, we need to compute the list of
868                                  * vectors.
869                                  */
870                                 if (input_typeid_vector == NULL)
871                                         input_typeid_vector = argtype_inherit(nargs, argtypes);
872
873                                 current_input_typeids = *input_typeid_vector++;
874                         }
875                         while (current_input_typeids != NULL);
876                 }
877         }
878
879         if (best_candidate)
880         {
881                 HeapTuple       ftup;
882                 Form_pg_proc pform;
883                 FuncDetailCode result;
884
885                 *funcid = best_candidate->oid;
886                 *true_typeids = best_candidate->args;
887
888                 ftup = SearchSysCache(PROCOID,
889                                                           ObjectIdGetDatum(best_candidate->oid),
890                                                           0, 0, 0);
891                 if (!HeapTupleIsValid(ftup))    /* should not happen */
892                         elog(ERROR, "function %u not found", best_candidate->oid);
893                 pform = (Form_pg_proc) GETSTRUCT(ftup);
894                 *rettype = pform->prorettype;
895                 *retset = pform->proretset;
896                 result = pform->proisagg ? FUNCDETAIL_AGGREGATE : FUNCDETAIL_NORMAL;
897                 ReleaseSysCache(ftup);
898                 return result;
899         }
900
901         return FUNCDETAIL_NOTFOUND;
902 }       /* func_get_detail() */
903
904 /*
905  *      argtype_inherit() -- Construct an argtype vector reflecting the
906  *                                               inheritance properties of the supplied argv.
907  *
908  *              This function is used to disambiguate among functions with the
909  *              same name but different signatures.  It takes an array of input
910  *              type ids.  For each type id in the array that's a complex type
911  *              (a class), it walks up the inheritance tree, finding all
912  *              superclasses of that type.      A vector of new Oid type arrays
913  *              is returned to the caller, reflecting the structure of the
914  *              inheritance tree above the supplied arguments.
915  *
916  *              The order of this vector is as follows:  all superclasses of the
917  *              rightmost complex class are explored first.  The exploration
918  *              continues from right to left.  This policy means that we favor
919  *              keeping the leftmost argument type as low in the inheritance tree
920  *              as possible.  This is intentional; it is exactly what we need to
921  *              do for method dispatch.  The last type array we return is all
922  *              zeroes.  This will match any functions for which return types are
923  *              not defined.  There are lots of these (mostly builtins) in the
924  *              catalogs.
925  */
926 static Oid **
927 argtype_inherit(int nargs, Oid *argtypes)
928 {
929         Oid                     relid;
930         int                     i;
931         InhPaths        arginh[FUNC_MAX_ARGS];
932
933         for (i = 0; i < FUNC_MAX_ARGS; i++)
934         {
935                 if (i < nargs)
936                 {
937                         arginh[i].self = argtypes[i];
938                         if ((relid = typeidTypeRelid(argtypes[i])) != InvalidOid)
939                                 arginh[i].nsupers = find_inheritors(relid, &(arginh[i].supervec));
940                         else
941                         {
942                                 arginh[i].nsupers = 0;
943                                 arginh[i].supervec = (Oid *) NULL;
944                         }
945                 }
946                 else
947                 {
948                         arginh[i].self = InvalidOid;
949                         arginh[i].nsupers = 0;
950                         arginh[i].supervec = (Oid *) NULL;
951                 }
952         }
953
954         /* return an ordered cross-product of the classes involved */
955         return gen_cross_product(arginh, nargs);
956 }
957
958 static int
959 find_inheritors(Oid relid, Oid **supervec)
960 {
961         Relation        inhrel;
962         HeapScanDesc inhscan;
963         ScanKeyData skey;
964         HeapTuple       inhtup;
965         Oid                *relidvec;
966         int                     nvisited;
967         List       *visited,
968                            *queue;
969         List       *elt;
970         bool            newrelid;
971
972         nvisited = 0;
973         queue = NIL;
974         visited = NIL;
975
976         inhrel = heap_openr(InheritsRelationName, AccessShareLock);
977
978         /*
979          * Use queue to do a breadth-first traversal of the inheritance graph
980          * from the relid supplied up to the root.      At the top of the loop,
981          * relid is the OID of the reltype to check next, queue is the list of
982          * pending relids to check after this one, and visited is the list of
983          * relids we need to output.
984          */
985         do
986         {
987                 /* find all types this relid inherits from, and add them to queue */
988
989                 ScanKeyEntryInitialize(&skey, 0x0, Anum_pg_inherits_inhrelid,
990                                                            F_OIDEQ,
991                                                            ObjectIdGetDatum(relid));
992
993                 inhscan = heap_beginscan(inhrel, SnapshotNow, 1, &skey);
994
995                 while ((inhtup = heap_getnext(inhscan, ForwardScanDirection)) != NULL)
996                 {
997                         Form_pg_inherits inh = (Form_pg_inherits) GETSTRUCT(inhtup);
998
999                         queue = lappendo(queue, inh->inhparent);
1000                 }
1001
1002                 heap_endscan(inhscan);
1003
1004                 /* pull next unvisited relid off the queue */
1005
1006                 newrelid = false;
1007                 while (queue != NIL)
1008                 {
1009                         relid = lfirsto(queue);
1010                         queue = lnext(queue);
1011                         if (!oidMember(relid, visited))
1012                         {
1013                                 newrelid = true;
1014                                 break;
1015                         }
1016                 }
1017
1018                 if (newrelid)
1019                 {
1020                         visited = lappendo(visited, relid);
1021                         nvisited++;
1022                 }
1023         } while (newrelid);
1024
1025         heap_close(inhrel, AccessShareLock);
1026
1027         if (nvisited > 0)
1028         {
1029                 relidvec = (Oid *) palloc(nvisited * sizeof(Oid));
1030                 *supervec = relidvec;
1031
1032                 foreach(elt, visited)
1033                 {
1034                         /* return the type id, rather than the relation id */
1035                         *relidvec++ = get_rel_type_id(lfirsto(elt));
1036                 }
1037         }
1038         else
1039                 *supervec = (Oid *) NULL;
1040
1041         freeList(visited);
1042
1043         /*
1044          * there doesn't seem to be any equally easy way to release the queue
1045          * list cells, but since they're palloc'd space it's not critical.
1046          */
1047
1048         return nvisited;
1049 }
1050
1051 static Oid **
1052 gen_cross_product(InhPaths *arginh, int nargs)
1053 {
1054         int                     nanswers;
1055         Oid               **result,
1056                           **iter;
1057         Oid                *oneres;
1058         int                     i,
1059                                 j;
1060         int                     cur[FUNC_MAX_ARGS];
1061
1062         nanswers = 1;
1063         for (i = 0; i < nargs; i++)
1064         {
1065                 nanswers *= (arginh[i].nsupers + 2);
1066                 cur[i] = 0;
1067         }
1068
1069         iter = result = (Oid **) palloc(sizeof(Oid *) * nanswers);
1070
1071         /* compute the cross product from right to left */
1072         for (;;)
1073         {
1074                 oneres = (Oid *) palloc0(FUNC_MAX_ARGS * sizeof(Oid));
1075
1076                 for (i = nargs - 1; i >= 0 && cur[i] > arginh[i].nsupers; i--)
1077                         continue;
1078
1079                 /* if we're done, terminate with NULL pointer */
1080                 if (i < 0)
1081                 {
1082                         *iter = NULL;
1083                         return result;
1084                 }
1085
1086                 /* no, increment this column and zero the ones after it */
1087                 cur[i] = cur[i] + 1;
1088                 for (j = nargs - 1; j > i; j--)
1089                         cur[j] = 0;
1090
1091                 for (i = 0; i < nargs; i++)
1092                 {
1093                         if (cur[i] == 0)
1094                                 oneres[i] = arginh[i].self;
1095                         else if (cur[i] > arginh[i].nsupers)
1096                                 oneres[i] = 0;  /* wild card */
1097                         else
1098                                 oneres[i] = arginh[i].supervec[cur[i] - 1];
1099                 }
1100
1101                 *iter++ = oneres;
1102         }
1103 }
1104
1105
1106 /*
1107  * Given two type OIDs, determine whether the first is a complex type
1108  * (class type) that inherits from the second.
1109  */
1110 bool
1111 typeInheritsFrom(Oid subclassTypeId, Oid superclassTypeId)
1112 {
1113         Oid                     relid;
1114         Oid                *supervec;
1115         int                     nsupers,
1116                                 i;
1117         bool            result;
1118
1119         if (!ISCOMPLEX(subclassTypeId) || !ISCOMPLEX(superclassTypeId))
1120                 return false;
1121         relid = typeidTypeRelid(subclassTypeId);
1122         if (relid == InvalidOid)
1123                 return false;
1124         nsupers = find_inheritors(relid, &supervec);
1125         result = false;
1126         for (i = 0; i < nsupers; i++)
1127         {
1128                 if (supervec[i] == superclassTypeId)
1129                 {
1130                         result = true;
1131                         break;
1132                 }
1133         }
1134         if (supervec)
1135                 pfree(supervec);
1136         return result;
1137 }
1138
1139
1140 /*
1141  * make_fn_arguments()
1142  *
1143  * Given the actual argument expressions for a function, and the desired
1144  * input types for the function, add any necessary typecasting to the
1145  * expression tree.  Caller should already have verified that casting is
1146  * allowed.
1147  *
1148  * Caution: given argument list is modified in-place.
1149  *
1150  * As with coerce_type, pstate may be NULL if no special unknown-Param
1151  * processing is wanted.
1152  */
1153 void
1154 make_fn_arguments(ParseState *pstate,
1155                                   List *fargs,
1156                                   Oid *actual_arg_types,
1157                                   Oid *declared_arg_types)
1158 {
1159         List       *current_fargs;
1160         int                     i = 0;
1161
1162         foreach(current_fargs, fargs)
1163         {
1164                 /* types don't match? then force coercion using a function call... */
1165                 if (actual_arg_types[i] != declared_arg_types[i])
1166                 {
1167                         lfirst(current_fargs) = coerce_type(pstate,
1168                                                                                                 lfirst(current_fargs),
1169                                                                                                 actual_arg_types[i],
1170                                                                                                 declared_arg_types[i],
1171                                                                                                 COERCION_IMPLICIT,
1172                                                                                                 COERCE_IMPLICIT_CAST);
1173                 }
1174                 i++;
1175         }
1176 }
1177
1178 /*
1179  * setup_field_select
1180  *              Build a FieldSelect node that says which attribute to project to.
1181  *              This routine is called by ParseFuncOrColumn() when we have found
1182  *              a projection on a function result or parameter.
1183  */
1184 static FieldSelect *
1185 setup_field_select(Node *input, char *attname, Oid relid)
1186 {
1187         FieldSelect *fselect = makeNode(FieldSelect);
1188         AttrNumber      attno;
1189
1190         attno = get_attnum(relid, attname);
1191         if (attno == InvalidAttrNumber)
1192                 elog(ERROR, "Relation \"%s\" has no column \"%s\"",
1193                          get_rel_name(relid), attname);
1194
1195         fselect->arg = (Expr *) input;
1196         fselect->fieldnum = attno;
1197         fselect->resulttype = get_atttype(relid, attno);
1198         fselect->resulttypmod = get_atttypmod(relid, attno);
1199
1200         return fselect;
1201 }
1202
1203 /*
1204  * ParseComplexProjection -
1205  *        handles function calls with a single argument that is of complex type.
1206  *        If the function call is actually a column projection, return a suitably
1207  *        transformed expression tree.  If not, return NULL.
1208  *
1209  * NB: argument is expected to be transformed already, ie, not a RangeVar.
1210  */
1211 static Node *
1212 ParseComplexProjection(char *funcname, Node *first_arg)
1213 {
1214         Oid                     argtype = exprType(first_arg);
1215         Oid                     argrelid;
1216         AttrNumber      attnum;
1217         FieldSelect *fselect;
1218
1219         argrelid = typeidTypeRelid(argtype);
1220         if (!argrelid)
1221                 return NULL;                    /* probably should not happen */
1222         attnum = get_attnum(argrelid, funcname);
1223         if (attnum == InvalidAttrNumber)
1224                 return NULL;                    /* funcname does not match any column */
1225
1226         /*
1227          * Check for special cases where we don't want to return a
1228          * FieldSelect.
1229          */
1230         switch (nodeTag(first_arg))
1231         {
1232                 case T_Var:
1233                         {
1234                                 Var                *var = (Var *) first_arg;
1235
1236                                 /*
1237                                  * If the Var is a whole-row tuple, we can just replace it
1238                                  * with a simple Var reference.
1239                                  */
1240                                 if (var->varattno == InvalidAttrNumber)
1241                                 {
1242                                         Oid                     vartype;
1243                                         int32           vartypmod;
1244
1245                                         get_atttypetypmod(argrelid, attnum,
1246                                                                           &vartype, &vartypmod);
1247
1248                                         return (Node *) makeVar(var->varno,
1249                                                                                         attnum,
1250                                                                                         vartype,
1251                                                                                         vartypmod,
1252                                                                                         var->varlevelsup);
1253                                 }
1254                                 break;
1255                         }
1256                 default:
1257                         break;
1258         }
1259
1260         /* Else generate a FieldSelect expression */
1261         fselect = setup_field_select(first_arg, funcname, argrelid);
1262         return (Node *) fselect;
1263 }
1264
1265 /*
1266  * Simple helper routine for delivering "No such attribute" error message
1267  */
1268 static void
1269 unknown_attribute(const char *schemaname, const char *relname,
1270                                   const char *attname)
1271 {
1272         if (schemaname)
1273                 elog(ERROR, "No such attribute %s.%s.%s",
1274                          schemaname, relname, attname);
1275         else
1276                 elog(ERROR, "No such attribute %s.%s",
1277                          relname, attname);
1278 }
1279
1280 /*
1281  * Error message when function lookup fails that gives details of the
1282  * argument types
1283  */
1284 void
1285 func_error(const char *caller, List *funcname,
1286                    int nargs, const Oid *argtypes,
1287                    const char *msg)
1288 {
1289         StringInfoData argbuf;
1290         int                     i;
1291
1292         initStringInfo(&argbuf);
1293
1294         for (i = 0; i < nargs; i++)
1295         {
1296                 if (i)
1297                         appendStringInfoString(&argbuf, ", ");
1298                 appendStringInfoString(&argbuf, format_type_be(argtypes[i]));
1299         }
1300
1301         if (caller == NULL)
1302         {
1303                 elog(ERROR, "Function %s(%s) does not exist%s%s",
1304                          NameListToString(funcname), argbuf.data,
1305                          ((msg != NULL) ? "\n\t" : ""), ((msg != NULL) ? msg : ""));
1306         }
1307         else
1308         {
1309                 elog(ERROR, "%s: function %s(%s) does not exist%s%s",
1310                          caller, NameListToString(funcname), argbuf.data,
1311                          ((msg != NULL) ? "\n\t" : ""), ((msg != NULL) ? msg : ""));
1312         }
1313 }
1314
1315 /*
1316  * find_aggregate_func
1317  *              Convenience routine to check that a function exists and is an
1318  *              aggregate.
1319  *
1320  * Note: basetype is ANYOID if we are looking for an aggregate on
1321  * all types.
1322  */
1323 Oid
1324 find_aggregate_func(const char *caller, List *aggname, Oid basetype)
1325 {
1326         Oid                     oid;
1327         HeapTuple       ftup;
1328         Form_pg_proc pform;
1329
1330         oid = LookupFuncName(aggname, 1, &basetype);
1331
1332         if (!OidIsValid(oid))
1333         {
1334                 if (basetype == ANYOID)
1335                         elog(ERROR, "%s: aggregate %s(*) does not exist",
1336                                  caller, NameListToString(aggname));
1337                 else
1338                         elog(ERROR, "%s: aggregate %s(%s) does not exist",
1339                                  caller, NameListToString(aggname),
1340                                  format_type_be(basetype));
1341         }
1342
1343         /* Make sure it's an aggregate */
1344         ftup = SearchSysCache(PROCOID,
1345                                                   ObjectIdGetDatum(oid),
1346                                                   0, 0, 0);
1347         if (!HeapTupleIsValid(ftup))    /* should not happen */
1348                 elog(ERROR, "function %u not found", oid);
1349         pform = (Form_pg_proc) GETSTRUCT(ftup);
1350
1351         if (!pform->proisagg)
1352         {
1353                 if (basetype == ANYOID)
1354                         elog(ERROR, "%s: function %s(*) is not an aggregate",
1355                                  caller, NameListToString(aggname));
1356                 else
1357                         elog(ERROR, "%s: function %s(%s) is not an aggregate",
1358                                  caller, NameListToString(aggname),
1359                                  format_type_be(basetype));
1360         }
1361
1362         ReleaseSysCache(ftup);
1363
1364         return oid;
1365 }
1366
1367 /*
1368  * LookupFuncName
1369  *              Given a possibly-qualified function name and a set of argument types,
1370  *              look up the function.  Returns InvalidOid if no such function.
1371  *
1372  * If the function name is not schema-qualified, it is sought in the current
1373  * namespace search path.
1374  */
1375 Oid
1376 LookupFuncName(List *funcname, int nargs, const Oid *argtypes)
1377 {
1378         FuncCandidateList clist;
1379
1380         clist = FuncnameGetCandidates(funcname, nargs);
1381
1382         while (clist)
1383         {
1384                 if (memcmp(argtypes, clist->args, nargs * sizeof(Oid)) == 0)
1385                         return clist->oid;
1386                 clist = clist->next;
1387         }
1388
1389         return InvalidOid;
1390 }
1391
1392 /*
1393  * LookupFuncNameTypeNames
1394  *              Like LookupFuncName, but the argument types are specified by a
1395  *              list of TypeName nodes.  Also, if we fail to find the function
1396  *              and caller is not NULL, then an error is reported via func_error.
1397  */
1398 Oid
1399 LookupFuncNameTypeNames(List *funcname, List *argtypes, const char *caller)
1400 {
1401         Oid                     funcoid;
1402         Oid                     argoids[FUNC_MAX_ARGS];
1403         int                     argcount;
1404         int                     i;
1405
1406         MemSet(argoids, 0, FUNC_MAX_ARGS * sizeof(Oid));
1407         argcount = length(argtypes);
1408         if (argcount > FUNC_MAX_ARGS)
1409                 elog(ERROR, "functions cannot have more than %d arguments",
1410                          FUNC_MAX_ARGS);
1411
1412         for (i = 0; i < argcount; i++)
1413         {
1414                 TypeName   *t = (TypeName *) lfirst(argtypes);
1415
1416                 argoids[i] = LookupTypeName(t);
1417
1418                 if (!OidIsValid(argoids[i]))
1419                         elog(ERROR, "Type \"%s\" does not exist",
1420                                  TypeNameToString(t));
1421
1422                 argtypes = lnext(argtypes);
1423         }
1424
1425         funcoid = LookupFuncName(funcname, argcount, argoids);
1426
1427         if (!OidIsValid(funcoid) && caller != NULL)
1428                 func_error(caller, funcname, argcount, argoids, NULL);
1429
1430         return funcoid;
1431 }