1 /*-------------------------------------------------------------------------
4 * handle function calls in parser
6 * Portions Copyright (c) 1996-2002, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
11 * $Header: /cvsroot/pgsql/src/backend/parser/parse_func.c,v 1.147 2003/04/29 22:13:10 tgl Exp $
13 *-------------------------------------------------------------------------
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"
35 static Node *ParseComplexProjection(char *funcname, Node *first_arg);
36 static Oid **argtype_inherit(int nargs, Oid *argtypes);
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,
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,
52 * Parse a function call
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.
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.
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.
71 ParseFuncOrColumn(ParseState *pstate, List *funcname, List *fargs,
72 bool agg_star, bool agg_distinct, bool is_column)
77 Node *first_arg = NULL;
78 int nargs = length(fargs);
80 Oid actual_arg_types[FUNC_MAX_ARGS];
81 Oid *declared_arg_types;
84 FuncDetailCode fdresult;
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.
92 if (nargs > FUNC_MAX_ARGS)
93 elog(ERROR, "Cannot pass more than %d arguments to a function",
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));
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.
110 if (nargs == 1 && !agg_star && !agg_distinct && length(funcname) == 1)
112 char *cname = strVal(lfirst(funcname));
114 /* Is it a not-yet-transformed RangeVar node? */
115 if (IsA(first_arg, RangeVar))
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,
126 else if (ISCOMPLEX(exprType(first_arg)))
129 * Attempt to handle projection of a complex argument. If
130 * ParseComplexProjection can't handle the projection, we have
133 retval = ParseComplexProjection(cname, first_arg);
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.
144 MemSet(actual_arg_types, 0, FUNC_MAX_ARGS * sizeof(Oid));
149 Node *arg = lfirst(i);
152 if (IsA(arg, RangeVar))
161 * a relation: look it up in the range table, or add if needed
163 schemaname = ((RangeVar *) arg)->schemaname;
164 relname = ((RangeVar *) arg)->relname;
166 rte = refnameRangeTblEntry(pstate, schemaname, relname,
170 rte = addImplicitRTE(pstate, (RangeVar *) arg);
172 vnum = RTERangeTablePosn(pstate, rte, &sublevels_up);
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.
183 switch (rte->rtekind)
186 toid = get_rel_type_id(rte->relid);
187 if (!OidIsValid(toid))
188 elog(ERROR, "Cannot find type OID for relation %u",
190 /* replace RangeVar in the arg list */
191 lfirst(i) = makeVar(vnum,
198 toid = exprType(rte->funcexpr);
199 if (get_typtype(toid) == 'c')
201 /* func returns composite; same as relation case */
202 lfirst(i) = makeVar(vnum,
210 /* func returns scalar; use attno 1 instead */
211 lfirst(i) = makeVar(vnum,
221 * RTE is a join or subselect; must fail for lack of a
225 unknown_attribute(schemaname, relname,
226 strVal(lfirst(funcname)));
228 elog(ERROR, "Cannot pass result of sub-select or join %s to a function",
230 toid = InvalidOid; /* keep compiler quiet */
235 toid = exprType(arg);
237 actual_arg_types[argn++] = toid;
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
247 fdresult = func_get_detail(funcname, fargs, nargs, actual_arg_types,
248 &funcid, &rettype, &retset,
249 &declared_arg_types);
250 if (fdresult == FUNCDETAIL_COERCION)
253 * We can do it as a trivial coercion. coerce_type can handle
254 * these cases, so why duplicate code...
256 return coerce_type(pstate, lfirst(fargs), actual_arg_types[0],
258 COERCION_EXPLICIT, COERCE_EXPLICIT_CALL);
260 else if (fdresult == FUNCDETAIL_NORMAL)
263 * Normal function found; was there anything indicating it must be
267 elog(ERROR, "%s(*) specified, but %s is not an aggregate function",
268 NameListToString(funcname), NameListToString(funcname));
270 elog(ERROR, "DISTINCT specified, but %s is not an aggregate function",
271 NameListToString(funcname));
273 else if (fdresult != FUNCDETAIL_AGGREGATE)
278 * If we are dealing with the attribute notation rel.function, give
279 * an error message that is appropriate for that case.
283 char *colname = strVal(lfirst(funcname));
287 if (IsA(first_arg, RangeVar))
288 unknown_attribute(((RangeVar *) first_arg)->schemaname,
289 ((RangeVar *) first_arg)->relname,
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));
296 elog(ERROR, "Attribute \"%s\" not found in datatype %s",
297 colname, format_type_be(relTypeId));
301 * Else generate a detailed complaint for a function
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");
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)
314 rettype = enforce_generic_type_consistency(actual_arg_types,
319 /* perform the necessary typecasting of arguments */
320 make_fn_arguments(pstate, fargs, actual_arg_types, declared_arg_types);
322 /* build the appropriate output structure */
323 if (fdresult == FUNCDETAIL_NORMAL)
325 FuncExpr *funcexpr = makeNode(FuncExpr);
327 funcexpr->funcid = funcid;
328 funcexpr->funcresulttype = rettype;
329 funcexpr->funcretset = retset;
330 funcexpr->funcformat = COERCE_EXPLICIT_CALL;
331 funcexpr->args = fargs;
333 retval = (Node *) funcexpr;
337 /* aggregate function */
338 Aggref *aggref = makeNode(Aggref);
340 aggref->aggfnoid = funcid;
341 aggref->aggtype = rettype;
342 aggref->target = lfirst(fargs);
343 aggref->aggstar = agg_star;
344 aggref->aggdistinct = agg_distinct;
346 retval = (Node *) aggref;
349 elog(ERROR, "Aggregates may not return sets");
351 pstate->p_hasAggs = true;
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.
365 * NB: okay to modify input list structure, as long as we find at least
369 match_argtypes(int nargs,
371 FuncCandidateList function_typeids,
372 FuncCandidateList *candidates) /* return value */
374 FuncCandidateList current_candidate;
375 FuncCandidateList next_candidate;
380 for (current_candidate = function_typeids;
381 current_candidate != NULL;
382 current_candidate = next_candidate)
384 next_candidate = current_candidate->next;
385 if (can_coerce_type(nargs, input_typeids, current_candidate->args,
388 current_candidate->next = *candidates;
389 *candidates = current_candidate;
395 } /* match_argtypes() */
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.
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.
409 static FuncCandidateList
410 func_select_candidate(int nargs,
412 FuncCandidateList candidates)
414 FuncCandidateList current_candidate;
415 FuncCandidateList last_candidate;
416 Oid *current_typeids;
422 CATEGORY slot_category[FUNC_MAX_ARGS],
424 bool slot_has_preferred_type[FUNC_MAX_ARGS];
425 bool resolved_unknowns;
428 * Run through all candidates and keep those with the most matches on
429 * exact types. Keep all candidates if none match.
433 last_candidate = NULL;
434 for (current_candidate = candidates;
435 current_candidate != NULL;
436 current_candidate = current_candidate->next)
438 current_typeids = current_candidate->args;
440 for (i = 0; i < nargs; i++)
442 if (input_typeids[i] != UNKNOWNOID &&
443 current_typeids[i] == input_typeids[i])
447 /* take this one as the best choice so far? */
448 if ((nmatch > nbestMatch) || (last_candidate == NULL))
451 candidates = current_candidate;
452 last_candidate = current_candidate;
455 /* no worse than the last choice, so keep this one too? */
456 else if (nmatch == nbestMatch)
458 last_candidate->next = current_candidate;
459 last_candidate = current_candidate;
462 /* otherwise, don't bother keeping this one... */
465 if (last_candidate) /* terminate rebuilt list */
466 last_candidate->next = NULL;
468 if (ncandidates == 1)
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.
478 last_candidate = NULL;
479 for (current_candidate = candidates;
480 current_candidate != NULL;
481 current_candidate = current_candidate->next)
483 current_typeids = current_candidate->args;
485 for (i = 0; i < nargs; i++)
487 if (input_typeids[i] != UNKNOWNOID)
489 if (IsBinaryCoercible(input_typeids[i], current_typeids[i]))
494 /* take this one as the best choice so far? */
495 if ((nmatch > nbestMatch) || (last_candidate == NULL))
498 candidates = current_candidate;
499 last_candidate = current_candidate;
502 /* no worse than the last choice, so keep this one too? */
503 else if (nmatch == nbestMatch)
505 last_candidate->next = current_candidate;
506 last_candidate = current_candidate;
509 /* otherwise, don't bother keeping this one... */
512 if (last_candidate) /* terminate rebuilt list */
513 last_candidate->next = NULL;
515 if (ncandidates == 1)
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.
525 last_candidate = NULL;
526 for (current_candidate = candidates;
527 current_candidate != NULL;
528 current_candidate = current_candidate->next)
530 current_typeids = current_candidate->args;
532 for (i = 0; i < nargs; i++)
534 if (input_typeids[i] != UNKNOWNOID)
536 current_category = TypeCategory(current_typeids[i]);
537 if (current_typeids[i] == input_typeids[i] ||
538 IsPreferredType(current_category, current_typeids[i]))
543 if ((nmatch > nbestMatch) || (last_candidate == NULL))
546 candidates = current_candidate;
547 last_candidate = current_candidate;
550 else if (nmatch == nbestMatch)
552 last_candidate->next = current_candidate;
553 last_candidate = current_candidate;
558 if (last_candidate) /* terminate rebuilt list */
559 last_candidate->next = NULL;
561 if (ncandidates == 1)
565 * Still too many candidates? Try assigning types for the unknown
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.
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.
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.
584 * If we are down to one candidate at the end, we win.
586 resolved_unknowns = false;
587 for (i = 0; i < nargs; i++)
591 if (input_typeids[i] != UNKNOWNOID)
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)
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)
606 /* first candidate */
607 slot_category[i] = current_category;
608 slot_has_preferred_type[i] =
609 IsPreferredType(current_category, current_type);
611 else if (current_category == slot_category[i])
613 /* more candidates in same category */
614 slot_has_preferred_type[i] |=
615 IsPreferredType(current_category, current_type);
619 /* category conflict! */
620 if (current_category == STRING_TYPE)
622 /* STRING always wins if available */
623 slot_category[i] = current_category;
624 slot_has_preferred_type[i] =
625 IsPreferredType(current_category, current_type);
630 * Remember conflict, but keep going (might find
633 have_conflict = true;
637 if (have_conflict && slot_category[i] != STRING_TYPE)
639 /* Failed to resolve category conflict at this position */
640 resolved_unknowns = false;
645 if (resolved_unknowns)
647 /* Strip non-matching candidates */
649 last_candidate = NULL;
650 for (current_candidate = candidates;
651 current_candidate != NULL;
652 current_candidate = current_candidate->next)
656 current_typeids = current_candidate->args;
657 for (i = 0; i < nargs; i++)
659 if (input_typeids[i] != UNKNOWNOID)
661 current_type = current_typeids[i];
662 current_category = TypeCategory(current_type);
663 if (current_category != slot_category[i])
668 if (slot_has_preferred_type[i] &&
669 !IsPreferredType(current_category, current_type))
677 /* keep this candidate */
678 last_candidate = current_candidate;
683 /* forget this candidate */
685 last_candidate->next = current_candidate->next;
687 candidates = current_candidate->next;
690 if (last_candidate) /* terminate rebuilt list */
691 last_candidate->next = NULL;
694 if (ncandidates == 1)
697 return NULL; /* failed to determine a unique candidate */
698 } /* func_select_candidate() */
703 * Find the named function in the system catalogs.
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.
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
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.
728 func_get_detail(List *funcname,
732 Oid *funcid, /* return value */
733 Oid *rettype, /* return value */
734 bool *retset, /* return value */
735 Oid **true_typeids) /* return value */
737 FuncCandidateList function_typeids;
738 FuncCandidateList best_candidate;
740 /* Get list of possible candidates from namespace search */
741 function_typeids = FuncnameGetCandidates(funcname, nargs);
744 * See if there is an exact match
746 for (best_candidate = function_typeids;
747 best_candidate != NULL;
748 best_candidate = best_candidate->next)
750 if (memcmp(argtypes, best_candidate->args, nargs * sizeof(Oid)) == 0)
754 if (best_candidate == NULL)
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
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.
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.
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!
785 if (nargs == 1 && fargs != NIL)
788 TypeName *tn = makeNode(TypeName);
790 tn->names = funcname;
792 targetType = LookupTypeName(tn);
793 if (OidIsValid(targetType) &&
794 !ISCOMPLEX(targetType))
796 Oid sourceType = argtypes[0];
797 Node *arg1 = lfirst(fargs);
799 if ((sourceType == UNKNOWNOID && IsA(arg1, Const)) ||
800 (find_coercion_pathway(targetType, sourceType,
801 COERCION_EXPLICIT, funcid) &&
802 *funcid == InvalidOid))
804 /* Yup, it's a type coercion */
805 *funcid = InvalidOid;
806 *rettype = targetType;
808 *true_typeids = argtypes;
809 return FUNCDETAIL_COERCION;
815 * didn't find an exact match, so now try to match up
818 if (function_typeids != NULL)
820 Oid **input_typeid_vector = NULL;
821 Oid *current_input_typeids;
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.
828 current_input_typeids = argtypes;
832 FuncCandidateList current_function_typeids;
835 ncandidates = match_argtypes(nargs, current_input_typeids,
837 ¤t_function_typeids);
839 /* one match only? then run with it... */
840 if (ncandidates == 1)
842 best_candidate = current_function_typeids;
847 * multiple candidates? then better decide or throw an
852 best_candidate = func_select_candidate(nargs,
853 current_input_typeids,
854 current_function_typeids);
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.
866 * No match here, so try the next inherited type vector.
867 * First time through, we need to compute the list of
870 if (input_typeid_vector == NULL)
871 input_typeid_vector = argtype_inherit(nargs, argtypes);
873 current_input_typeids = *input_typeid_vector++;
875 while (current_input_typeids != NULL);
883 FuncDetailCode result;
885 *funcid = best_candidate->oid;
886 *true_typeids = best_candidate->args;
888 ftup = SearchSysCache(PROCOID,
889 ObjectIdGetDatum(best_candidate->oid),
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);
901 return FUNCDETAIL_NOTFOUND;
902 } /* func_get_detail() */
905 * argtype_inherit() -- Construct an argtype vector reflecting the
906 * inheritance properties of the supplied argv.
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.
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
927 argtype_inherit(int nargs, Oid *argtypes)
931 InhPaths arginh[FUNC_MAX_ARGS];
933 for (i = 0; i < FUNC_MAX_ARGS; i++)
937 arginh[i].self = argtypes[i];
938 if ((relid = typeidTypeRelid(argtypes[i])) != InvalidOid)
939 arginh[i].nsupers = find_inheritors(relid, &(arginh[i].supervec));
942 arginh[i].nsupers = 0;
943 arginh[i].supervec = (Oid *) NULL;
948 arginh[i].self = InvalidOid;
949 arginh[i].nsupers = 0;
950 arginh[i].supervec = (Oid *) NULL;
954 /* return an ordered cross-product of the classes involved */
955 return gen_cross_product(arginh, nargs);
959 find_inheritors(Oid relid, Oid **supervec)
962 HeapScanDesc inhscan;
976 inhrel = heap_openr(InheritsRelationName, AccessShareLock);
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.
987 /* find all types this relid inherits from, and add them to queue */
989 ScanKeyEntryInitialize(&skey, 0x0, Anum_pg_inherits_inhrelid,
991 ObjectIdGetDatum(relid));
993 inhscan = heap_beginscan(inhrel, SnapshotNow, 1, &skey);
995 while ((inhtup = heap_getnext(inhscan, ForwardScanDirection)) != NULL)
997 Form_pg_inherits inh = (Form_pg_inherits) GETSTRUCT(inhtup);
999 queue = lappendo(queue, inh->inhparent);
1002 heap_endscan(inhscan);
1004 /* pull next unvisited relid off the queue */
1007 while (queue != NIL)
1009 relid = lfirsto(queue);
1010 queue = lnext(queue);
1011 if (!oidMember(relid, visited))
1020 visited = lappendo(visited, relid);
1025 heap_close(inhrel, AccessShareLock);
1029 relidvec = (Oid *) palloc(nvisited * sizeof(Oid));
1030 *supervec = relidvec;
1032 foreach(elt, visited)
1034 /* return the type id, rather than the relation id */
1035 *relidvec++ = get_rel_type_id(lfirsto(elt));
1039 *supervec = (Oid *) NULL;
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.
1052 gen_cross_product(InhPaths *arginh, int nargs)
1060 int cur[FUNC_MAX_ARGS];
1063 for (i = 0; i < nargs; i++)
1065 nanswers *= (arginh[i].nsupers + 2);
1069 iter = result = (Oid **) palloc(sizeof(Oid *) * nanswers);
1071 /* compute the cross product from right to left */
1074 oneres = (Oid *) palloc0(FUNC_MAX_ARGS * sizeof(Oid));
1076 for (i = nargs - 1; i >= 0 && cur[i] > arginh[i].nsupers; i--)
1079 /* if we're done, terminate with NULL pointer */
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--)
1091 for (i = 0; i < nargs; i++)
1094 oneres[i] = arginh[i].self;
1095 else if (cur[i] > arginh[i].nsupers)
1096 oneres[i] = 0; /* wild card */
1098 oneres[i] = arginh[i].supervec[cur[i] - 1];
1107 * Given two type OIDs, determine whether the first is a complex type
1108 * (class type) that inherits from the second.
1111 typeInheritsFrom(Oid subclassTypeId, Oid superclassTypeId)
1119 if (!ISCOMPLEX(subclassTypeId) || !ISCOMPLEX(superclassTypeId))
1121 relid = typeidTypeRelid(subclassTypeId);
1122 if (relid == InvalidOid)
1124 nsupers = find_inheritors(relid, &supervec);
1126 for (i = 0; i < nsupers; i++)
1128 if (supervec[i] == superclassTypeId)
1141 * make_fn_arguments()
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
1148 * Caution: given argument list is modified in-place.
1150 * As with coerce_type, pstate may be NULL if no special unknown-Param
1151 * processing is wanted.
1154 make_fn_arguments(ParseState *pstate,
1156 Oid *actual_arg_types,
1157 Oid *declared_arg_types)
1159 List *current_fargs;
1162 foreach(current_fargs, fargs)
1164 /* types don't match? then force coercion using a function call... */
1165 if (actual_arg_types[i] != declared_arg_types[i])
1167 lfirst(current_fargs) = coerce_type(pstate,
1168 lfirst(current_fargs),
1169 actual_arg_types[i],
1170 declared_arg_types[i],
1172 COERCE_IMPLICIT_CAST);
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.
1184 static FieldSelect *
1185 setup_field_select(Node *input, char *attname, Oid relid)
1187 FieldSelect *fselect = makeNode(FieldSelect);
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);
1195 fselect->arg = (Expr *) input;
1196 fselect->fieldnum = attno;
1197 fselect->resulttype = get_atttype(relid, attno);
1198 fselect->resulttypmod = get_atttypmod(relid, attno);
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.
1209 * NB: argument is expected to be transformed already, ie, not a RangeVar.
1212 ParseComplexProjection(char *funcname, Node *first_arg)
1214 Oid argtype = exprType(first_arg);
1217 FieldSelect *fselect;
1219 argrelid = typeidTypeRelid(argtype);
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 */
1227 * Check for special cases where we don't want to return a
1230 switch (nodeTag(first_arg))
1234 Var *var = (Var *) first_arg;
1237 * If the Var is a whole-row tuple, we can just replace it
1238 * with a simple Var reference.
1240 if (var->varattno == InvalidAttrNumber)
1245 get_atttypetypmod(argrelid, attnum,
1246 &vartype, &vartypmod);
1248 return (Node *) makeVar(var->varno,
1260 /* Else generate a FieldSelect expression */
1261 fselect = setup_field_select(first_arg, funcname, argrelid);
1262 return (Node *) fselect;
1266 * Simple helper routine for delivering "No such attribute" error message
1269 unknown_attribute(const char *schemaname, const char *relname,
1270 const char *attname)
1273 elog(ERROR, "No such attribute %s.%s.%s",
1274 schemaname, relname, attname);
1276 elog(ERROR, "No such attribute %s.%s",
1281 * Error message when function lookup fails that gives details of the
1285 func_error(const char *caller, List *funcname,
1286 int nargs, const Oid *argtypes,
1289 StringInfoData argbuf;
1292 initStringInfo(&argbuf);
1294 for (i = 0; i < nargs; i++)
1297 appendStringInfoString(&argbuf, ", ");
1298 appendStringInfoString(&argbuf, format_type_be(argtypes[i]));
1303 elog(ERROR, "Function %s(%s) does not exist%s%s",
1304 NameListToString(funcname), argbuf.data,
1305 ((msg != NULL) ? "\n\t" : ""), ((msg != NULL) ? msg : ""));
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 : ""));
1316 * find_aggregate_func
1317 * Convenience routine to check that a function exists and is an
1320 * Note: basetype is ANYOID if we are looking for an aggregate on
1324 find_aggregate_func(const char *caller, List *aggname, Oid basetype)
1330 oid = LookupFuncName(aggname, 1, &basetype);
1332 if (!OidIsValid(oid))
1334 if (basetype == ANYOID)
1335 elog(ERROR, "%s: aggregate %s(*) does not exist",
1336 caller, NameListToString(aggname));
1338 elog(ERROR, "%s: aggregate %s(%s) does not exist",
1339 caller, NameListToString(aggname),
1340 format_type_be(basetype));
1343 /* Make sure it's an aggregate */
1344 ftup = SearchSysCache(PROCOID,
1345 ObjectIdGetDatum(oid),
1347 if (!HeapTupleIsValid(ftup)) /* should not happen */
1348 elog(ERROR, "function %u not found", oid);
1349 pform = (Form_pg_proc) GETSTRUCT(ftup);
1351 if (!pform->proisagg)
1353 if (basetype == ANYOID)
1354 elog(ERROR, "%s: function %s(*) is not an aggregate",
1355 caller, NameListToString(aggname));
1357 elog(ERROR, "%s: function %s(%s) is not an aggregate",
1358 caller, NameListToString(aggname),
1359 format_type_be(basetype));
1362 ReleaseSysCache(ftup);
1369 * Given a possibly-qualified function name and a set of argument types,
1370 * look up the function. Returns InvalidOid if no such function.
1372 * If the function name is not schema-qualified, it is sought in the current
1373 * namespace search path.
1376 LookupFuncName(List *funcname, int nargs, const Oid *argtypes)
1378 FuncCandidateList clist;
1380 clist = FuncnameGetCandidates(funcname, nargs);
1384 if (memcmp(argtypes, clist->args, nargs * sizeof(Oid)) == 0)
1386 clist = clist->next;
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.
1399 LookupFuncNameTypeNames(List *funcname, List *argtypes, const char *caller)
1402 Oid argoids[FUNC_MAX_ARGS];
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",
1412 for (i = 0; i < argcount; i++)
1414 TypeName *t = (TypeName *) lfirst(argtypes);
1416 argoids[i] = LookupTypeName(t);
1418 if (!OidIsValid(argoids[i]))
1419 elog(ERROR, "Type \"%s\" does not exist",
1420 TypeNameToString(t));
1422 argtypes = lnext(argtypes);
1425 funcoid = LookupFuncName(funcname, argcount, argoids);
1427 if (!OidIsValid(funcoid) && caller != NULL)
1428 func_error(caller, funcname, argcount, argoids, NULL);