1 /*-------------------------------------------------------------------------
4 * handle function calls in parser
6 * Portions Copyright (c) 1996-2006, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
11 * $PostgreSQL: pgsql/src/backend/parser/parse_func.c,v 1.188 2006/07/14 14:52:22 momjian Exp $
13 *-------------------------------------------------------------------------
17 #include "access/heapam.h"
18 #include "catalog/pg_inherits.h"
19 #include "catalog/pg_proc.h"
20 #include "catalog/pg_type.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"
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,
43 * Parse a function call
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.
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.
59 * The argument expressions (in fargs) must have been transformed already.
62 ParseFuncOrColumn(ParseState *pstate, List *funcname, List *fargs,
63 bool agg_star, bool agg_distinct, bool is_column,
70 Node *first_arg = NULL;
72 Oid actual_arg_types[FUNC_MAX_ARGS];
73 Oid *declared_arg_types;
76 FuncDetailCode fdresult;
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.
84 if (list_length(fargs) > FUNC_MAX_ARGS)
86 (errcode(ERRCODE_TOO_MANY_ARGUMENTS),
87 errmsg("cannot pass more than %d arguments to a function",
89 parser_errposition(pstate, location)));
92 * Extract arg type info in preparation for function lookup.
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 ...
101 for (l = list_head(fargs); l != NULL; l = nextl)
103 Node *arg = lfirst(l);
104 Oid argtype = exprType(arg);
108 if (argtype == VOIDOID && IsA(arg, Param) &&!is_column)
110 fargs = list_delete_ptr(fargs, arg);
114 actual_arg_types[nargs++] = argtype;
119 first_arg = linitial(fargs);
120 Assert(first_arg != NULL);
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.
129 if (nargs == 1 && !agg_star && !agg_distinct && list_length(funcname) == 1)
131 Oid argtype = actual_arg_types[0];
133 if (argtype == RECORDOID || ISCOMPLEX(argtype))
135 retval = ParseComplexProjection(pstate,
136 strVal(linitial(funcname)),
143 * If ParseComplexProjection doesn't recognize it as a projection,
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
157 fdresult = func_get_detail(funcname, fargs, nargs, actual_arg_types,
158 &funcid, &rettype, &retset,
159 &declared_arg_types);
160 if (fdresult == FUNCDETAIL_COERCION)
163 * We can do it as a trivial coercion. coerce_type can handle these
164 * cases, so why duplicate code...
166 return coerce_type(pstate, linitial(fargs),
167 actual_arg_types[0], rettype, -1,
168 COERCION_EXPLICIT, COERCE_EXPLICIT_CALL);
170 else if (fdresult == FUNCDETAIL_NORMAL)
173 * Normal function found; was there anything indicating it must be an
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)));
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)));
190 else if (fdresult != FUNCDETAIL_AGGREGATE)
195 * If we are dealing with the attribute notation rel.function, give an
196 * error message that is appropriate for that case.
201 Assert(list_length(funcname) == 1);
202 unknown_attribute(pstate, first_arg, strVal(linitial(funcname)),
207 * Else generate a detailed complaint for a function
209 if (fdresult == FUNCDETAIL_MULTIPLE)
211 (errcode(ERRCODE_AMBIGUOUS_FUNCTION),
212 errmsg("function %s is not unique",
213 func_signature_string(funcname, nargs,
215 errhint("Could not choose a best candidate function. "
216 "You may need to add explicit type casts."),
217 parser_errposition(pstate, location)));
220 (errcode(ERRCODE_UNDEFINED_FUNCTION),
221 errmsg("function %s does not exist",
222 func_signature_string(funcname, nargs,
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)));
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)
234 rettype = enforce_generic_type_consistency(actual_arg_types,
239 /* perform the necessary typecasting of arguments */
240 make_fn_arguments(pstate, fargs, actual_arg_types, declared_arg_types);
242 /* build the appropriate output structure */
243 if (fdresult == FUNCDETAIL_NORMAL)
245 FuncExpr *funcexpr = makeNode(FuncExpr);
247 funcexpr->funcid = funcid;
248 funcexpr->funcresulttype = rettype;
249 funcexpr->funcretset = retset;
250 funcexpr->funcformat = COERCE_EXPLICIT_CALL;
251 funcexpr->args = fargs;
253 retval = (Node *) funcexpr;
257 /* aggregate function */
258 Aggref *aggref = makeNode(Aggref);
260 aggref->aggfnoid = funcid;
261 aggref->aggtype = rettype;
262 aggref->target = linitial(fargs);
263 aggref->aggstar = agg_star;
264 aggref->aggdistinct = agg_distinct;
266 /* parse_agg.c does additional aggregate-specific processing */
267 transformAggregateCall(pstate, aggref);
269 retval = (Node *) aggref;
273 (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
274 errmsg("aggregates may not return sets"),
275 parser_errposition(pstate, location)));
282 /* func_match_argtypes()
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.
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.
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.
296 func_match_argtypes(int nargs,
298 FuncCandidateList raw_candidates,
299 FuncCandidateList *candidates) /* return value */
301 FuncCandidateList current_candidate;
302 FuncCandidateList next_candidate;
307 for (current_candidate = raw_candidates;
308 current_candidate != NULL;
309 current_candidate = next_candidate)
311 next_candidate = current_candidate->next;
312 if (can_coerce_type(nargs, input_typeids, current_candidate->args,
315 current_candidate->next = *candidates;
316 *candidates = current_candidate;
322 } /* func_match_argtypes() */
325 /* func_select_candidate()
326 * Given the input argtype array and more than one candidate
327 * for the function, attempt to resolve the conflict.
329 * Returns the selected candidate if the conflict can be resolved,
330 * otherwise returns NULL.
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.
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.
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
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
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
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]
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.
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.)
381 func_select_candidate(int nargs,
383 FuncCandidateList candidates)
385 FuncCandidateList current_candidate;
386 FuncCandidateList last_candidate;
387 Oid *current_typeids;
393 Oid input_base_typeids[FUNC_MAX_ARGS];
394 CATEGORY slot_category[FUNC_MAX_ARGS],
396 bool slot_has_preferred_type[FUNC_MAX_ARGS];
397 bool resolved_unknowns;
399 /* protect local fixed-size arrays */
400 if (nargs > FUNC_MAX_ARGS)
402 (errcode(ERRCODE_TOO_MANY_ARGUMENTS),
403 errmsg("cannot pass more than %d arguments to a function",
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.
416 for (i = 0; i < nargs; i++)
417 input_base_typeids[i] = getBaseType(input_typeids[i]);
420 * Run through all candidates and keep those with the most matches on
421 * exact types. Keep all candidates if none match.
425 last_candidate = NULL;
426 for (current_candidate = candidates;
427 current_candidate != NULL;
428 current_candidate = current_candidate->next)
430 current_typeids = current_candidate->args;
432 for (i = 0; i < nargs; i++)
434 if (input_base_typeids[i] != UNKNOWNOID &&
435 current_typeids[i] == input_base_typeids[i])
439 /* take this one as the best choice so far? */
440 if ((nmatch > nbestMatch) || (last_candidate == NULL))
443 candidates = current_candidate;
444 last_candidate = current_candidate;
447 /* no worse than the last choice, so keep this one too? */
448 else if (nmatch == nbestMatch)
450 last_candidate->next = current_candidate;
451 last_candidate = current_candidate;
454 /* otherwise, don't bother keeping this one... */
457 if (last_candidate) /* terminate rebuilt list */
458 last_candidate->next = NULL;
460 if (ncandidates == 1)
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.
470 for (i = 0; i < nargs; i++) /* avoid multiple lookups */
471 slot_category[i] = TypeCategory(input_base_typeids[i]);
474 last_candidate = NULL;
475 for (current_candidate = candidates;
476 current_candidate != NULL;
477 current_candidate = current_candidate->next)
479 current_typeids = current_candidate->args;
481 for (i = 0; i < nargs; i++)
483 if (input_base_typeids[i] != UNKNOWNOID)
485 if (current_typeids[i] == input_base_typeids[i] ||
486 IsPreferredType(slot_category[i], current_typeids[i]))
491 if ((nmatch > nbestMatch) || (last_candidate == NULL))
494 candidates = current_candidate;
495 last_candidate = current_candidate;
498 else if (nmatch == nbestMatch)
500 last_candidate->next = current_candidate;
501 last_candidate = current_candidate;
506 if (last_candidate) /* terminate rebuilt list */
507 last_candidate->next = NULL;
509 if (ncandidates == 1)
513 * Still too many candidates? Try assigning types for the unknown columns.
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.
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.
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.
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.
536 * If we are down to one candidate at the end, we win.
538 resolved_unknowns = false;
539 for (i = 0; i < nargs; i++)
543 if (input_base_typeids[i] != UNKNOWNOID)
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)
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)
558 /* first candidate */
559 slot_category[i] = current_category;
560 slot_has_preferred_type[i] =
561 IsPreferredType(current_category, current_type);
563 else if (current_category == slot_category[i])
565 /* more candidates in same category */
566 slot_has_preferred_type[i] |=
567 IsPreferredType(current_category, current_type);
571 /* category conflict! */
572 if (current_category == STRING_TYPE)
574 /* STRING always wins if available */
575 slot_category[i] = current_category;
576 slot_has_preferred_type[i] =
577 IsPreferredType(current_category, current_type);
582 * Remember conflict, but keep going (might find STRING)
584 have_conflict = true;
588 if (have_conflict && slot_category[i] != STRING_TYPE)
590 /* Failed to resolve category conflict at this position */
591 resolved_unknowns = false;
596 if (resolved_unknowns)
598 /* Strip non-matching candidates */
600 last_candidate = NULL;
601 for (current_candidate = candidates;
602 current_candidate != NULL;
603 current_candidate = current_candidate->next)
607 current_typeids = current_candidate->args;
608 for (i = 0; i < nargs; i++)
610 if (input_base_typeids[i] != UNKNOWNOID)
612 current_type = current_typeids[i];
613 current_category = TypeCategory(current_type);
614 if (current_category != slot_category[i])
619 if (slot_has_preferred_type[i] &&
620 !IsPreferredType(current_category, current_type))
628 /* keep this candidate */
629 last_candidate = current_candidate;
634 /* forget this candidate */
636 last_candidate->next = current_candidate->next;
638 candidates = current_candidate->next;
641 if (last_candidate) /* terminate rebuilt list */
642 last_candidate->next = NULL;
645 if (ncandidates == 1)
648 return NULL; /* failed to select a best candidate */
649 } /* func_select_candidate() */
654 * Find the named function in the system catalogs.
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.
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
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.
679 func_get_detail(List *funcname,
683 Oid *funcid, /* return value */
684 Oid *rettype, /* return value */
685 bool *retset, /* return value */
686 Oid **true_typeids) /* return value */
688 FuncCandidateList raw_candidates;
689 FuncCandidateList best_candidate;
691 /* Get list of possible candidates from namespace search */
692 raw_candidates = FuncnameGetCandidates(funcname, nargs);
695 * Quickly check if there is an exact match to the input datatypes (there
698 for (best_candidate = raw_candidates;
699 best_candidate != NULL;
700 best_candidate = best_candidate->next)
702 if (memcmp(argtypes, best_candidate->args, nargs * sizeof(Oid)) == 0)
706 if (best_candidate == NULL)
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.
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.
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.
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!
736 if (nargs == 1 && fargs != NIL)
740 targetType = LookupTypeName(NULL,
741 makeTypeNameFromNameList(funcname));
742 if (OidIsValid(targetType) &&
743 !ISCOMPLEX(targetType))
745 Oid sourceType = argtypes[0];
746 Node *arg1 = linitial(fargs);
749 if ((sourceType == UNKNOWNOID && IsA(arg1, Const)) ||
750 (find_coercion_pathway(targetType, sourceType,
751 COERCION_EXPLICIT, &cfuncid) &&
752 cfuncid == InvalidOid))
754 /* Yup, it's a type coercion */
755 *funcid = InvalidOid;
756 *rettype = targetType;
758 *true_typeids = argtypes;
759 return FUNCDETAIL_COERCION;
765 * didn't find an exact match, so now try to match up candidates...
767 if (raw_candidates != NULL)
769 FuncCandidateList current_candidates;
772 ncandidates = func_match_argtypes(nargs,
775 ¤t_candidates);
777 /* one match only? then run with it... */
778 if (ncandidates == 1)
779 best_candidate = current_candidates;
782 * multiple candidates? then better decide or throw an error...
784 else if (ncandidates > 1)
786 best_candidate = func_select_candidate(nargs,
791 * If we were able to choose a best candidate, we're done.
792 * Otherwise, ambiguous function call.
795 return FUNCDETAIL_MULTIPLE;
804 FuncDetailCode result;
806 *funcid = best_candidate->oid;
807 *true_typeids = best_candidate->args;
809 ftup = SearchSysCache(PROCOID,
810 ObjectIdGetDatum(best_candidate->oid),
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);
823 return FUNCDETAIL_NOTFOUND;
828 * Given two type OIDs, determine whether the first is a complex type
829 * (class type) that inherits from the second.
832 typeInheritsFrom(Oid subclassTypeId, Oid superclassTypeId)
839 ListCell *queue_item;
841 if (!ISCOMPLEX(subclassTypeId) || !ISCOMPLEX(superclassTypeId))
843 relid = typeidTypeRelid(subclassTypeId);
844 if (relid == InvalidOid)
848 * Begin the search at the relation itself, so add relid to the queue.
850 queue = list_make1_oid(relid);
853 inhrel = heap_open(InheritsRelationId, AccessShareLock);
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.
861 foreach(queue_item, queue)
863 Oid this_relid = lfirst_oid(queue_item);
865 HeapScanDesc inhscan;
868 /* If we've seen this relid already, skip it */
869 if (list_member_oid(visited, this_relid))
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'.
878 if (queue_item != list_head(queue))
879 visited = lappend_oid(visited, this_relid);
882 Anum_pg_inherits_inhrelid,
883 BTEqualStrategyNumber, F_OIDEQ,
884 ObjectIdGetDatum(this_relid));
886 inhscan = heap_beginscan(inhrel, SnapshotNow, 1, &skey);
888 while ((inhtup = heap_getnext(inhscan, ForwardScanDirection)) != NULL)
890 Form_pg_inherits inh = (Form_pg_inherits) GETSTRUCT(inhtup);
891 Oid inhparent = inh->inhparent;
893 /* If this is the target superclass, we're done */
894 if (get_rel_type_id(inhparent) == superclassTypeId)
900 /* Else add to queue */
901 queue = lappend_oid(queue, inhparent);
904 heap_endscan(inhscan);
910 heap_close(inhrel, AccessShareLock);
920 * make_fn_arguments()
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
927 * Caution: given argument list is modified in-place.
929 * As with coerce_type, pstate may be NULL if no special unknown-Param
930 * processing is wanted.
933 make_fn_arguments(ParseState *pstate,
935 Oid *actual_arg_types,
936 Oid *declared_arg_types)
938 ListCell *current_fargs;
941 foreach(current_fargs, fargs)
943 /* types don't match? then force coercion using a function call... */
944 if (actual_arg_types[i] != declared_arg_types[i])
946 lfirst(current_fargs) = coerce_type(pstate,
947 lfirst(current_fargs),
949 declared_arg_types[i], -1,
951 COERCE_IMPLICIT_CAST);
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.
964 ParseComplexProjection(ParseState *pstate, char *funcname, Node *first_arg,
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
977 * This case could be handled by expandRecordVariable, but it's more
978 * efficient to do it this way when possible.
980 if (IsA(first_arg, Var) &&
981 ((Var *) first_arg)->varattno == InvalidAttrNumber)
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);
993 * Else do it the hard way with get_expr_result_type().
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().
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 */
1006 for (i = 0; i < tupdesc->natts; i++)
1008 Form_pg_attribute att = tupdesc->attrs[i];
1010 if (strcmp(funcname, NameStr(att->attname)) == 0 &&
1013 /* Success, so generate a FieldSelect expression */
1014 FieldSelect *fselect = makeNode(FieldSelect);
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;
1024 return NULL; /* funcname does not match any column */
1028 * helper routine for delivering "column does not exist" error message
1031 unknown_attribute(ParseState *pstate, Node *relref, char *attname,
1036 if (IsA(relref, Var) &&
1037 ((Var *) relref)->varattno == InvalidAttrNumber)
1039 /* Reference the RTE by alias not by actual table name */
1040 rte = GetRTEByRangeTablePosn(pstate,
1041 ((Var *) relref)->varno,
1042 ((Var *) relref)->varlevelsup);
1044 (errcode(ERRCODE_UNDEFINED_COLUMN),
1045 errmsg("column %s.%s does not exist",
1046 rte->eref->aliasname, attname),
1047 parser_errposition(pstate, location)));
1051 /* Have to do it by reference to the type of the expression */
1052 Oid relTypeId = exprType(relref);
1054 if (ISCOMPLEX(relTypeId))
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)
1062 (errcode(ERRCODE_UNDEFINED_COLUMN),
1063 errmsg("could not identify column \"%s\" in record data type",
1065 parser_errposition(pstate, location)));
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)));
1077 * funcname_signature_string
1078 * Build a string representing a function name, including arg types.
1079 * The result is something like "foo(integer)".
1081 * This is typically used in the construction of function-not-found error
1085 funcname_signature_string(const char *funcname,
1086 int nargs, const Oid *argtypes)
1088 StringInfoData argbuf;
1091 initStringInfo(&argbuf);
1093 appendStringInfo(&argbuf, "%s(", funcname);
1095 for (i = 0; i < nargs; i++)
1098 appendStringInfoString(&argbuf, ", ");
1099 appendStringInfoString(&argbuf, format_type_be(argtypes[i]));
1102 appendStringInfoChar(&argbuf, ')');
1104 return argbuf.data; /* return palloc'd string buffer */
1108 * func_signature_string
1109 * As above, but function name is passed as a qualified name list.
1112 func_signature_string(List *funcname, int nargs, const Oid *argtypes)
1114 return funcname_signature_string(NameListToString(funcname),
1120 * Given a possibly-qualified function name and a set of argument types,
1121 * look up the function.
1123 * If the function name is not schema-qualified, it is sought in the current
1124 * namespace search path.
1126 * If the function is not found, we return InvalidOid if noError is true,
1127 * else raise an error.
1130 LookupFuncName(List *funcname, int nargs, const Oid *argtypes, bool noError)
1132 FuncCandidateList clist;
1134 clist = FuncnameGetCandidates(funcname, nargs);
1138 if (memcmp(argtypes, clist->args, nargs * sizeof(Oid)) == 0)
1140 clist = clist->next;
1145 (errcode(ERRCODE_UNDEFINED_FUNCTION),
1146 errmsg("function %s does not exist",
1147 func_signature_string(funcname, nargs, argtypes))));
1153 * LookupFuncNameTypeNames
1154 * Like LookupFuncName, but the argument types are specified by a
1155 * list of TypeName nodes.
1158 LookupFuncNameTypeNames(List *funcname, List *argtypes, bool noError)
1160 Oid argoids[FUNC_MAX_ARGS];
1163 ListCell *args_item;
1165 argcount = list_length(argtypes);
1166 if (argcount > FUNC_MAX_ARGS)
1168 (errcode(ERRCODE_TOO_MANY_ARGUMENTS),
1169 errmsg("functions cannot have more than %d arguments",
1172 args_item = list_head(argtypes);
1173 for (i = 0; i < argcount; i++)
1175 TypeName *t = (TypeName *) lfirst(args_item);
1177 argoids[i] = LookupTypeName(NULL, t);
1179 if (!OidIsValid(argoids[i]))
1181 (errcode(ERRCODE_UNDEFINED_OBJECT),
1182 errmsg("type \"%s\" does not exist",
1183 TypeNameToString(t))));
1185 args_item = lnext(args_item);
1188 return LookupFuncName(funcname, argcount, argoids, noError);
1192 * LookupAggNameTypeNames
1193 * Find an aggregate function given a name and list of TypeName nodes.
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)
1202 LookupAggNameTypeNames(List *aggname, List *argtypes, bool noError)
1204 Oid argoids[FUNC_MAX_ARGS];
1207 ListCell *args_item;
1212 argcount = list_length(argtypes);
1213 if (argcount > FUNC_MAX_ARGS)
1215 (errcode(ERRCODE_TOO_MANY_ARGUMENTS),
1216 errmsg("functions cannot have more than %d arguments",
1221 /* special case for agg(*) */
1222 argoids[0] = ANYOID;
1227 args_item = list_head(argtypes);
1228 for (i = 0; i < argcount; i++)
1230 TypeName *t = (TypeName *) lfirst(args_item);
1232 argoids[i] = LookupTypeName(NULL, t);
1234 if (!OidIsValid(argoids[i]))
1236 (errcode(ERRCODE_UNDEFINED_OBJECT),
1237 errmsg("type \"%s\" does not exist",
1238 TypeNameToString(t))));
1240 args_item = lnext(args_item);
1244 oid = LookupFuncName(aggname, argcount, argoids, true);
1246 if (!OidIsValid(oid))
1250 if (argcount == 1 && argoids[0] == ANYOID)
1252 (errcode(ERRCODE_UNDEFINED_FUNCTION),
1253 errmsg("aggregate %s(*) does not exist",
1254 NameListToString(aggname))));
1257 (errcode(ERRCODE_UNDEFINED_FUNCTION),
1258 errmsg("aggregate %s does not exist",
1259 func_signature_string(aggname,
1260 argcount, argoids))));
1263 /* Make sure it's an aggregate */
1264 ftup = SearchSysCache(PROCOID,
1265 ObjectIdGetDatum(oid),
1267 if (!HeapTupleIsValid(ftup)) /* should not happen */
1268 elog(ERROR, "cache lookup failed for function %u", oid);
1269 pform = (Form_pg_proc) GETSTRUCT(ftup);
1271 if (!pform->proisagg)
1273 ReleaseSysCache(ftup);
1276 /* we do not use the (*) notation for functions... */
1278 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1279 errmsg("function %s is not an aggregate",
1280 func_signature_string(aggname,
1281 argcount, argoids))));
1284 ReleaseSysCache(ftup);