1
/*-------------------------------------------------------------------------
4
* handle function calls in parser
6
* Portions Copyright (c) 1996-2005, 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.175 2004-12-31 22:00:27 pgsql Exp $
13
*-------------------------------------------------------------------------
17
#include "access/heapam.h"
18
#include "catalog/catname.h"
19
#include "catalog/pg_inherits.h"
20
#include "catalog/pg_proc.h"
21
#include "lib/stringinfo.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_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(ParseState *pstate, char *funcname,
37
static Oid **argtype_inherit(int nargs, Oid *argtypes);
39
static int find_inheritors(Oid relid, Oid **supervec);
40
static Oid **gen_cross_product(InhPaths *arginh, int nargs);
41
static void unknown_attribute(ParseState *pstate, Node *relref, char *attname);
45
* Parse a function call
47
* For historical reasons, Postgres tries to treat the notations tab.col
48
* and col(tab) as equivalent: if a single-argument function call has an
49
* argument of complex type and the (unqualified) function name matches
50
* any attribute of the type, we take it as a column projection. Conversely
51
* a function of a single complex-type argument can be written like a
52
* column reference, allowing functions to act like computed columns.
54
* Hence, both cases come through here. The is_column parameter tells us
55
* which syntactic construct is actually being dealt with, but this is
56
* intended to be used only to deliver an appropriate error message,
57
* not to affect the semantics. When is_column is true, we should have
58
* a single argument (the putative table), unqualified function name
59
* equal to the column name, and no aggregate decoration.
61
* The argument expressions (in fargs) must have been transformed already.
64
ParseFuncOrColumn(ParseState *pstate, List *funcname, List *fargs,
65
bool agg_star, bool agg_distinct, bool is_column)
70
Node *first_arg = NULL;
71
int nargs = list_length(fargs);
73
Oid actual_arg_types[FUNC_MAX_ARGS];
74
Oid *declared_arg_types;
77
FuncDetailCode fdresult;
80
* Most of the rest of the parser just assumes that functions do not
81
* have more than FUNC_MAX_ARGS parameters. We have to test here to
82
* protect against array overruns, etc. Of course, this may not be a
83
* function, but the test doesn't hurt.
85
if (nargs > FUNC_MAX_ARGS)
87
(errcode(ERRCODE_TOO_MANY_ARGUMENTS),
88
errmsg("cannot pass more than %d arguments to a function",
93
first_arg = linitial(fargs);
94
Assert(first_arg != NULL);
98
* Check for column projection: if function has one argument, and that
99
* argument is of complex type, and function name is not qualified,
100
* then the "function call" could be a projection. We also check that
101
* there wasn't any aggregate decoration.
103
if (nargs == 1 && !agg_star && !agg_distinct && list_length(funcname) == 1)
105
Oid argtype = exprType(first_arg);
107
if (argtype == RECORDOID || ISCOMPLEX(argtype))
109
retval = ParseComplexProjection(pstate,
110
strVal(linitial(funcname)),
116
* If ParseComplexProjection doesn't recognize it as a
117
* projection, just press on.
123
* Okay, it's not a column projection, so it must really be a
124
* function. Extract arg type info in preparation for function lookup.
126
MemSet(actual_arg_types, 0, FUNC_MAX_ARGS * sizeof(Oid));
131
Node *arg = lfirst(l);
133
actual_arg_types[argn++] = exprType(arg);
137
* func_get_detail looks up the function in the catalogs, does
138
* disambiguation for polymorphic functions, handles inheritance, and
139
* returns the funcid and type and set or singleton status of the
140
* function's return value. it also returns the true argument types
143
fdresult = func_get_detail(funcname, fargs, nargs, actual_arg_types,
144
&funcid, &rettype, &retset,
145
&declared_arg_types);
146
if (fdresult == FUNCDETAIL_COERCION)
149
* We can do it as a trivial coercion. coerce_type can handle
150
* these cases, so why duplicate code...
152
return coerce_type(pstate, linitial(fargs),
153
actual_arg_types[0], rettype, -1,
154
COERCION_EXPLICIT, COERCE_EXPLICIT_CALL);
156
else if (fdresult == FUNCDETAIL_NORMAL)
159
* Normal function found; was there anything indicating it must be
164
(errcode(ERRCODE_WRONG_OBJECT_TYPE),
165
errmsg("%s(*) specified, but %s is not an aggregate function",
166
NameListToString(funcname),
167
NameListToString(funcname))));
170
(errcode(ERRCODE_WRONG_OBJECT_TYPE),
171
errmsg("DISTINCT specified, but %s is not an aggregate function",
172
NameListToString(funcname))));
174
else if (fdresult != FUNCDETAIL_AGGREGATE)
179
* If we are dealing with the attribute notation rel.function, give
180
* an error message that is appropriate for that case.
185
Assert(list_length(funcname) == 1);
186
unknown_attribute(pstate, first_arg, strVal(linitial(funcname)));
190
* Else generate a detailed complaint for a function
192
if (fdresult == FUNCDETAIL_MULTIPLE)
194
(errcode(ERRCODE_AMBIGUOUS_FUNCTION),
195
errmsg("function %s is not unique",
196
func_signature_string(funcname, nargs,
198
errhint("Could not choose a best candidate function. "
199
"You may need to add explicit type casts.")));
202
(errcode(ERRCODE_UNDEFINED_FUNCTION),
203
errmsg("function %s does not exist",
204
func_signature_string(funcname, nargs,
206
errhint("No function matches the given name and argument types. "
207
"You may need to add explicit type casts.")));
211
* enforce consistency with ANYARRAY and ANYELEMENT argument and
212
* return types, possibly adjusting return type or declared_arg_types
213
* (which will be used as the cast destination by make_fn_arguments)
215
rettype = enforce_generic_type_consistency(actual_arg_types,
220
/* perform the necessary typecasting of arguments */
221
make_fn_arguments(pstate, fargs, actual_arg_types, declared_arg_types);
223
/* build the appropriate output structure */
224
if (fdresult == FUNCDETAIL_NORMAL)
226
FuncExpr *funcexpr = makeNode(FuncExpr);
228
funcexpr->funcid = funcid;
229
funcexpr->funcresulttype = rettype;
230
funcexpr->funcretset = retset;
231
funcexpr->funcformat = COERCE_EXPLICIT_CALL;
232
funcexpr->args = fargs;
234
retval = (Node *) funcexpr;
238
/* aggregate function */
239
Aggref *aggref = makeNode(Aggref);
241
aggref->aggfnoid = funcid;
242
aggref->aggtype = rettype;
243
aggref->target = linitial(fargs);
244
aggref->aggstar = agg_star;
245
aggref->aggdistinct = agg_distinct;
247
/* parse_agg.c does additional aggregate-specific processing */
248
transformAggregateCall(pstate, aggref);
250
retval = (Node *) aggref;
254
(errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
255
errmsg("aggregates may not return sets")));
262
/* func_match_argtypes()
264
* Given a list of candidate functions (having the right name and number
265
* of arguments) and an array of input datatype OIDs, produce a shortlist of
266
* those candidates that actually accept the input datatypes (either exactly
267
* or by coercion), and return the number of such candidates.
269
* Note that can_coerce_type will assume that UNKNOWN inputs are coercible to
270
* anything, so candidates will not be eliminated on that basis.
272
* NB: okay to modify input list structure, as long as we find at least
273
* one match. If no match at all, the list must remain unmodified.
276
func_match_argtypes(int nargs,
278
FuncCandidateList raw_candidates,
279
FuncCandidateList *candidates) /* return value */
281
FuncCandidateList current_candidate;
282
FuncCandidateList next_candidate;
287
for (current_candidate = raw_candidates;
288
current_candidate != NULL;
289
current_candidate = next_candidate)
291
next_candidate = current_candidate->next;
292
if (can_coerce_type(nargs, input_typeids, current_candidate->args,
295
current_candidate->next = *candidates;
296
*candidates = current_candidate;
302
} /* func_match_argtypes() */
305
/* func_select_candidate()
306
* Given the input argtype array and more than one candidate
307
* for the function, attempt to resolve the conflict.
309
* Returns the selected candidate if the conflict can be resolved,
310
* otherwise returns NULL.
312
* Note that the caller has already determined that there is no candidate
313
* exactly matching the input argtypes, and has pruned away any "candidates"
314
* that aren't actually coercion-compatible with the input types.
316
* This is also used for resolving ambiguous operator references. Formerly
317
* parse_oper.c had its own, essentially duplicate code for the purpose.
318
* The following comments (formerly in parse_oper.c) are kept to record some
319
* of the history of these heuristics.
323
* This routine is new code, replacing binary_oper_select_candidate()
324
* which dates from v4.2/v1.0.x days. It tries very hard to match up
325
* operators with types, including allowing type coercions if necessary.
326
* The important thing is that the code do as much as possible,
327
* while _never_ doing the wrong thing, where "the wrong thing" would
328
* be returning an operator when other better choices are available,
329
* or returning an operator which is a non-intuitive possibility.
330
* - thomas 1998-05-21
332
* The comments below came from binary_oper_select_candidate(), and
333
* illustrate the issues and choices which are possible:
334
* - thomas 1998-05-20
336
* current wisdom holds that the default operator should be one in which
337
* both operands have the same type (there will only be one such
340
* 7.27.93 - I have decided not to do this; it's too hard to justify, and
341
* it's easy enough to typecast explicitly - avi
342
* [the rest of this routine was commented out since then - ay]
344
* 6/23/95 - I don't complete agree with avi. In particular, casting
345
* floats is a pain for users. Whatever the rationale behind not doing
346
* this is, I need the following special case to work.
348
* In the WHERE clause of a query, if a float is specified without
349
* quotes, we treat it as float8. I added the float48* operators so
350
* that we can operate on float4 and float8. But now we have more than
351
* one matching operator if the right arg is unknown (eg. float
352
* specified with quotes). This break some stuff in the regression
353
* test where there are floats in quotes not properly casted. Below is
354
* the solution. In addition to requiring the operator operates on the
355
* same type for both operands [as in the code Avi originally
356
* commented out], we also require that the operators be equivalent in
357
* some sense. (see equivalentOpersAfterPromotion for details.)
361
func_select_candidate(int nargs,
363
FuncCandidateList candidates)
365
FuncCandidateList current_candidate;
366
FuncCandidateList last_candidate;
367
Oid *current_typeids;
373
Oid input_base_typeids[FUNC_MAX_ARGS];
374
CATEGORY slot_category[FUNC_MAX_ARGS],
376
bool slot_has_preferred_type[FUNC_MAX_ARGS];
377
bool resolved_unknowns;
380
* If any input types are domains, reduce them to their base types.
381
* This ensures that we will consider functions on the base type to be
382
* "exact matches" in the exact-match heuristic; it also makes it
383
* possible to do something useful with the type-category heuristics.
384
* Note that this makes it difficult, but not impossible, to use
385
* functions declared to take a domain as an input datatype. Such a
386
* function will be selected over the base-type function only if it is
387
* an exact match at all argument positions, and so was already chosen
390
for (i = 0; i < nargs; i++)
391
input_base_typeids[i] = getBaseType(input_typeids[i]);
394
* Run through all candidates and keep those with the most matches on
395
* exact types. Keep all candidates if none match.
399
last_candidate = NULL;
400
for (current_candidate = candidates;
401
current_candidate != NULL;
402
current_candidate = current_candidate->next)
404
current_typeids = current_candidate->args;
406
for (i = 0; i < nargs; i++)
408
if (input_base_typeids[i] != UNKNOWNOID &&
409
current_typeids[i] == input_base_typeids[i])
413
/* take this one as the best choice so far? */
414
if ((nmatch > nbestMatch) || (last_candidate == NULL))
417
candidates = current_candidate;
418
last_candidate = current_candidate;
421
/* no worse than the last choice, so keep this one too? */
422
else if (nmatch == nbestMatch)
424
last_candidate->next = current_candidate;
425
last_candidate = current_candidate;
428
/* otherwise, don't bother keeping this one... */
431
if (last_candidate) /* terminate rebuilt list */
432
last_candidate->next = NULL;
434
if (ncandidates == 1)
438
* Still too many candidates? Now look for candidates which have
439
* either exact matches or preferred types at the args that will
440
* require coercion. (Restriction added in 7.4: preferred type must be
441
* of same category as input type; give no preference to
442
* cross-category conversions to preferred types.) Keep all
443
* candidates if none match.
445
for (i = 0; i < nargs; i++) /* avoid multiple lookups */
446
slot_category[i] = TypeCategory(input_base_typeids[i]);
449
last_candidate = NULL;
450
for (current_candidate = candidates;
451
current_candidate != NULL;
452
current_candidate = current_candidate->next)
454
current_typeids = current_candidate->args;
456
for (i = 0; i < nargs; i++)
458
if (input_base_typeids[i] != UNKNOWNOID)
460
if (current_typeids[i] == input_base_typeids[i] ||
461
IsPreferredType(slot_category[i], current_typeids[i]))
466
if ((nmatch > nbestMatch) || (last_candidate == NULL))
469
candidates = current_candidate;
470
last_candidate = current_candidate;
473
else if (nmatch == nbestMatch)
475
last_candidate->next = current_candidate;
476
last_candidate = current_candidate;
481
if (last_candidate) /* terminate rebuilt list */
482
last_candidate->next = NULL;
484
if (ncandidates == 1)
488
* Still too many candidates? Try assigning types for the unknown
491
* NOTE: for a binary operator with one unknown and one non-unknown
492
* input, we already tried the heuristic of looking for a candidate
493
* with the known input type on both sides (see binary_oper_exact()).
494
* That's essentially a special case of the general algorithm we try
497
* We do this by examining each unknown argument position to see if we
498
* can determine a "type category" for it. If any candidate has an
499
* input datatype of STRING category, use STRING category (this bias
500
* towards STRING is appropriate since unknown-type literals look like
501
* strings). Otherwise, if all the candidates agree on the type
502
* category of this argument position, use that category. Otherwise,
503
* fail because we cannot determine a category.
505
* If we are able to determine a type category, also notice whether any
506
* of the candidates takes a preferred datatype within the category.
508
* Having completed this examination, remove candidates that accept the
509
* wrong category at any unknown position. Also, if at least one
510
* candidate accepted a preferred type at a position, remove
511
* candidates that accept non-preferred types.
513
* If we are down to one candidate at the end, we win.
515
resolved_unknowns = false;
516
for (i = 0; i < nargs; i++)
520
if (input_base_typeids[i] != UNKNOWNOID)
522
resolved_unknowns = true; /* assume we can do it */
523
slot_category[i] = INVALID_TYPE;
524
slot_has_preferred_type[i] = false;
525
have_conflict = false;
526
for (current_candidate = candidates;
527
current_candidate != NULL;
528
current_candidate = current_candidate->next)
530
current_typeids = current_candidate->args;
531
current_type = current_typeids[i];
532
current_category = TypeCategory(current_type);
533
if (slot_category[i] == INVALID_TYPE)
535
/* first candidate */
536
slot_category[i] = current_category;
537
slot_has_preferred_type[i] =
538
IsPreferredType(current_category, current_type);
540
else if (current_category == slot_category[i])
542
/* more candidates in same category */
543
slot_has_preferred_type[i] |=
544
IsPreferredType(current_category, current_type);
548
/* category conflict! */
549
if (current_category == STRING_TYPE)
551
/* STRING always wins if available */
552
slot_category[i] = current_category;
553
slot_has_preferred_type[i] =
554
IsPreferredType(current_category, current_type);
559
* Remember conflict, but keep going (might find
562
have_conflict = true;
566
if (have_conflict && slot_category[i] != STRING_TYPE)
568
/* Failed to resolve category conflict at this position */
569
resolved_unknowns = false;
574
if (resolved_unknowns)
576
/* Strip non-matching candidates */
578
last_candidate = NULL;
579
for (current_candidate = candidates;
580
current_candidate != NULL;
581
current_candidate = current_candidate->next)
585
current_typeids = current_candidate->args;
586
for (i = 0; i < nargs; i++)
588
if (input_base_typeids[i] != UNKNOWNOID)
590
current_type = current_typeids[i];
591
current_category = TypeCategory(current_type);
592
if (current_category != slot_category[i])
597
if (slot_has_preferred_type[i] &&
598
!IsPreferredType(current_category, current_type))
606
/* keep this candidate */
607
last_candidate = current_candidate;
612
/* forget this candidate */
614
last_candidate->next = current_candidate->next;
616
candidates = current_candidate->next;
619
if (last_candidate) /* terminate rebuilt list */
620
last_candidate->next = NULL;
623
if (ncandidates == 1)
626
return NULL; /* failed to select a best candidate */
627
} /* func_select_candidate() */
632
* Find the named function in the system catalogs.
634
* Attempt to find the named function in the system catalogs with
635
* arguments exactly as specified, so that the normal case
636
* (exact match) is as quick as possible.
638
* If an exact match isn't found:
639
* 1) check for possible interpretation as a trivial type coercion
640
* 2) get a vector of all possible input arg type arrays constructed
641
* from the superclasses of the original input arg types
642
* 3) get a list of all possible argument type arrays to the function
643
* with given name and number of arguments
644
* 4) for each input arg type array from vector #1:
645
* a) find how many of the function arg type arrays from list #2
646
* it can be coerced to
647
* b) if the answer is one, we have our function
648
* c) if the answer is more than one, attempt to resolve the conflict
649
* d) if the answer is zero, try the next array from vector #1
651
* Note: we rely primarily on nargs/argtypes as the argument description.
652
* The actual expression node list is passed in fargs so that we can check
653
* for type coercion of a constant. Some callers pass fargs == NIL
654
* indicating they don't want that check made.
657
func_get_detail(List *funcname,
661
Oid *funcid, /* return value */
662
Oid *rettype, /* return value */
663
bool *retset, /* return value */
664
Oid **true_typeids) /* return value */
666
FuncCandidateList raw_candidates;
667
FuncCandidateList best_candidate;
669
/* Get list of possible candidates from namespace search */
670
raw_candidates = FuncnameGetCandidates(funcname, nargs);
673
* Quickly check if there is an exact match to the input datatypes
674
* (there can be only one)
676
for (best_candidate = raw_candidates;
677
best_candidate != NULL;
678
best_candidate = best_candidate->next)
680
if (memcmp(argtypes, best_candidate->args, nargs * sizeof(Oid)) == 0)
684
if (best_candidate == NULL)
687
* If we didn't find an exact match, next consider the possibility
688
* that this is really a type-coercion request: a single-argument
689
* function call where the function name is a type name. If so,
690
* and if we can do the coercion trivially (no run-time function
691
* call needed), then go ahead and treat the "function call" as a
692
* coercion. This interpretation needs to be given higher
693
* priority than interpretations involving a type coercion
694
* followed by a function call, otherwise we can produce
695
* surprising results. For example, we want "text(varchar)" to be
696
* interpreted as a trivial coercion, not as "text(name(varchar))"
697
* which the code below this point is entirely capable of
700
* "Trivial" coercions are ones that involve binary-compatible types
701
* and ones that are coercing a previously-unknown-type literal
702
* constant to a specific type.
704
* The reason we can restrict our check to binary-compatible
705
* coercions here is that we expect non-binary-compatible
706
* coercions to have an implementation function named after the
707
* target type. That function will be found by normal lookup if
710
* NB: it's important that this code stays in sync with what
711
* coerce_type can do, because the caller will try to apply
712
* coerce_type if we return FUNCDETAIL_COERCION. If we return
713
* that result for something coerce_type can't handle, we'll cause
714
* infinite recursion between this module and coerce_type!
716
if (nargs == 1 && fargs != NIL)
719
TypeName *tn = makeNode(TypeName);
721
tn->names = funcname;
723
targetType = LookupTypeName(tn);
724
if (OidIsValid(targetType) &&
725
!ISCOMPLEX(targetType))
727
Oid sourceType = argtypes[0];
728
Node *arg1 = linitial(fargs);
731
if ((sourceType == UNKNOWNOID && IsA(arg1, Const)) ||
732
(find_coercion_pathway(targetType, sourceType,
733
COERCION_EXPLICIT, &cfuncid) &&
734
cfuncid == InvalidOid))
736
/* Yup, it's a type coercion */
737
*funcid = InvalidOid;
738
*rettype = targetType;
740
*true_typeids = argtypes;
741
return FUNCDETAIL_COERCION;
747
* didn't find an exact match, so now try to match up
750
if (raw_candidates != NULL)
752
Oid **input_typeid_vector = NULL;
753
Oid *current_input_typeids;
756
* First we will search with the given argtypes, then with
757
* variants based on replacing complex types with their
758
* inheritance ancestors. Stop as soon as any match is found.
760
current_input_typeids = argtypes;
764
FuncCandidateList current_candidates;
767
ncandidates = func_match_argtypes(nargs,
768
current_input_typeids,
770
¤t_candidates);
772
/* one match only? then run with it... */
773
if (ncandidates == 1)
775
best_candidate = current_candidates;
780
* multiple candidates? then better decide or throw an
785
best_candidate = func_select_candidate(nargs,
786
current_input_typeids,
790
* If we were able to choose a best candidate, we're
791
* done. Otherwise, ambiguous function call.
795
return FUNCDETAIL_MULTIPLE;
799
* No match here, so try the next inherited type vector.
800
* First time through, we need to compute the list of
803
if (input_typeid_vector == NULL)
804
input_typeid_vector = argtype_inherit(nargs, argtypes);
806
current_input_typeids = *input_typeid_vector++;
808
while (current_input_typeids != NULL);
816
FuncDetailCode result;
818
*funcid = best_candidate->oid;
819
*true_typeids = best_candidate->args;
821
ftup = SearchSysCache(PROCOID,
822
ObjectIdGetDatum(best_candidate->oid),
824
if (!HeapTupleIsValid(ftup)) /* should not happen */
825
elog(ERROR, "cache lookup failed for function %u",
826
best_candidate->oid);
827
pform = (Form_pg_proc) GETSTRUCT(ftup);
828
*rettype = pform->prorettype;
829
*retset = pform->proretset;
830
result = pform->proisagg ? FUNCDETAIL_AGGREGATE : FUNCDETAIL_NORMAL;
831
ReleaseSysCache(ftup);
835
return FUNCDETAIL_NOTFOUND;
839
* argtype_inherit() -- Construct an argtype vector reflecting the
840
* inheritance properties of the supplied argv.
842
* This function is used to handle resolution of function calls when
843
* there is no match to the given argument types, but there might be
844
* matches based on considering complex types as members of their
845
* superclass types (parent classes).
847
* It takes an array of input type ids. For each type id in the array
848
* that's a complex type (a class), it walks up the inheritance tree,
849
* finding all superclasses of that type. A vector of new Oid type
850
* arrays is returned to the caller, listing possible alternative
851
* interpretations of the input typeids as members of their superclasses
852
* rather than the actually given argument types. The vector is
853
* terminated by a NULL pointer.
855
* The order of this vector is as follows: all superclasses of the
856
* rightmost complex class are explored first. The exploration
857
* continues from right to left. This policy means that we favor
858
* keeping the leftmost argument type as low in the inheritance tree
859
* as possible. This is intentional; it is exactly what we need to
860
* do for method dispatch.
862
* The vector does not include the case where no complex classes have
863
* been promoted, since that was already tried before this routine
867
argtype_inherit(int nargs, Oid *argtypes)
871
InhPaths arginh[FUNC_MAX_ARGS];
873
for (i = 0; i < nargs; i++)
875
arginh[i].self = argtypes[i];
876
if ((relid = typeidTypeRelid(argtypes[i])) != InvalidOid)
877
arginh[i].nsupers = find_inheritors(relid, &(arginh[i].supervec));
880
arginh[i].nsupers = 0;
881
arginh[i].supervec = NULL;
885
/* return an ordered cross-product of the classes involved */
886
return gen_cross_product(arginh, nargs);
890
* Look up the parent superclass(es) of the given relation.
892
* *supervec is set to an array of the type OIDs (not the relation OIDs)
893
* of the parents, with nearest ancestors listed first. It's set to NULL
894
* if there are no parents. The return value is the number of parents.
897
find_inheritors(Oid relid, Oid **supervec)
903
ListCell *queue_item;
906
* Begin the search at the relation itself, so add relid to the queue.
908
queue = list_make1_oid(relid);
911
inhrel = heap_openr(InheritsRelationName, AccessShareLock);
914
* Use queue to do a breadth-first traversal of the inheritance graph
915
* from the relid supplied up to the root. Notice that we append to
916
* the queue inside the loop --- this is okay because the foreach()
917
* macro doesn't advance queue_item until the next loop iteration
920
foreach(queue_item, queue)
922
Oid this_relid = lfirst_oid(queue_item);
924
HeapScanDesc inhscan;
927
/* If we've seen this relid already, skip it */
928
if (list_member_oid(visited, this_relid))
932
* Okay, this is a not-yet-seen relid. Add it to the list of
933
* already-visited OIDs, then find all the types this relid
934
* inherits from and add them to the queue. The one exception is
935
* we don't add the original relation to 'visited'.
937
if (queue_item != list_head(queue))
938
visited = lappend_oid(visited, this_relid);
941
Anum_pg_inherits_inhrelid,
942
BTEqualStrategyNumber, F_OIDEQ,
943
ObjectIdGetDatum(this_relid));
945
inhscan = heap_beginscan(inhrel, SnapshotNow, 1, &skey);
947
while ((inhtup = heap_getnext(inhscan, ForwardScanDirection)) != NULL)
949
Form_pg_inherits inh = (Form_pg_inherits) GETSTRUCT(inhtup);
951
queue = lappend_oid(queue, inh->inhparent);
954
heap_endscan(inhscan);
957
heap_close(inhrel, AccessShareLock);
959
nvisited = list_length(visited);
965
relidvec = (Oid *) palloc(nvisited * sizeof(*relidvec));
966
*supervec = relidvec;
970
/* return the type id, rather than the relation id */
971
*relidvec++ = get_rel_type_id(lfirst_oid(l));
984
* Generate the ordered list of substitute argtype vectors to try.
986
* See comments for argtype_inherit.
989
gen_cross_product(InhPaths *arginh, int nargs)
996
int cur[FUNC_MAX_ARGS];
999
* At each position we want to try the original datatype, plus each
1000
* supertype. So the number of possible combinations is this:
1003
for (i = 0; i < nargs; i++)
1004
nanswers *= (arginh[i].nsupers + 1);
1007
* We also need an extra slot for the terminating NULL in the result
1008
* array, but that cancels out with the fact that we don't want to
1009
* generate the zero-changes case. So we need exactly nanswers slots.
1011
result = (Oid **) palloc(sizeof(Oid *) * nanswers);
1015
* Compute the cross product from right to left. When cur[i] == 0,
1016
* generate the original input type at position i. When cur[i] == k
1017
* for k > 0, generate its k'th supertype.
1019
MemSet(cur, 0, sizeof(cur));
1024
* Find a column we can increment. All the columns after it get
1025
* reset to zero. (Essentially, we're adding one to the multi-
1026
* digit number represented by cur[].)
1028
for (i = nargs - 1; i >= 0 && cur[i] >= arginh[i].nsupers; i--)
1031
/* if none, we're done */
1035
/* increment this column */
1038
/* Generate the proper output type-OID vector */
1039
oneres = (Oid *) palloc0(FUNC_MAX_ARGS * sizeof(Oid));
1041
for (i = 0; i < nargs; i++)
1044
oneres[i] = arginh[i].self;
1046
oneres[i] = arginh[i].supervec[cur[i] - 1];
1049
result[j++] = oneres;
1052
/* terminate result vector with NULL pointer */
1055
Assert(j == nanswers);
1062
* Given two type OIDs, determine whether the first is a complex type
1063
* (class type) that inherits from the second.
1066
typeInheritsFrom(Oid subclassTypeId, Oid superclassTypeId)
1074
if (!ISCOMPLEX(subclassTypeId) || !ISCOMPLEX(superclassTypeId))
1076
relid = typeidTypeRelid(subclassTypeId);
1077
if (relid == InvalidOid)
1079
nsupers = find_inheritors(relid, &supervec);
1081
for (i = 0; i < nsupers; i++)
1083
if (supervec[i] == superclassTypeId)
1096
* make_fn_arguments()
1098
* Given the actual argument expressions for a function, and the desired
1099
* input types for the function, add any necessary typecasting to the
1100
* expression tree. Caller should already have verified that casting is
1103
* Caution: given argument list is modified in-place.
1105
* As with coerce_type, pstate may be NULL if no special unknown-Param
1106
* processing is wanted.
1109
make_fn_arguments(ParseState *pstate,
1111
Oid *actual_arg_types,
1112
Oid *declared_arg_types)
1114
ListCell *current_fargs;
1117
foreach(current_fargs, fargs)
1119
/* types don't match? then force coercion using a function call... */
1120
if (actual_arg_types[i] != declared_arg_types[i])
1122
lfirst(current_fargs) = coerce_type(pstate,
1123
lfirst(current_fargs),
1124
actual_arg_types[i],
1125
declared_arg_types[i], -1,
1127
COERCE_IMPLICIT_CAST);
1134
* ParseComplexProjection -
1135
* handles function calls with a single argument that is of complex type.
1136
* If the function call is actually a column projection, return a suitably
1137
* transformed expression tree. If not, return NULL.
1140
ParseComplexProjection(ParseState *pstate, char *funcname, Node *first_arg)
1145
FieldSelect *fselect;
1148
* Special case for whole-row Vars so that we can resolve (foo.*).bar
1149
* even when foo is a reference to a subselect, join, or RECORD
1150
* function. A bonus is that we avoid generating an unnecessary
1151
* FieldSelect; our result can omit the whole-row Var and just be a
1152
* Var for the selected field.
1154
if (IsA(first_arg, Var) &&
1155
((Var *) first_arg)->varattno == InvalidAttrNumber)
1159
rte = GetRTEByRangeTablePosn(pstate,
1160
((Var *) first_arg)->varno,
1161
((Var *) first_arg)->varlevelsup);
1162
/* Return a Var if funcname matches a column, else NULL */
1163
return scanRTEForColumn(pstate, rte, funcname);
1167
* Else do it the hard way. Note that if the arg is of RECORD type,
1168
* we will never recognize a column name, and always assume the item
1169
* must be a function.
1171
argtype = exprType(first_arg);
1172
argrelid = typeidTypeRelid(argtype);
1174
return NULL; /* can only happen if RECORD */
1176
attnum = get_attnum(argrelid, funcname);
1177
if (attnum == InvalidAttrNumber)
1178
return NULL; /* funcname does not match any column */
1180
/* Success, so generate a FieldSelect expression */
1181
fselect = makeNode(FieldSelect);
1182
fselect->arg = (Expr *) first_arg;
1183
fselect->fieldnum = attnum;
1184
get_atttypetypmod(argrelid, attnum,
1185
&fselect->resulttype,
1186
&fselect->resulttypmod);
1188
return (Node *) fselect;
1192
* helper routine for delivering "column does not exist" error message
1195
unknown_attribute(ParseState *pstate, Node *relref, char *attname)
1199
if (IsA(relref, Var) &&
1200
((Var *) relref)->varattno == InvalidAttrNumber)
1202
/* Reference the RTE by alias not by actual table name */
1203
rte = GetRTEByRangeTablePosn(pstate,
1204
((Var *) relref)->varno,
1205
((Var *) relref)->varlevelsup);
1207
(errcode(ERRCODE_UNDEFINED_COLUMN),
1208
errmsg("column %s.%s does not exist",
1209
rte->eref->aliasname, attname)));
1213
/* Have to do it by reference to the type of the expression */
1214
Oid relTypeId = exprType(relref);
1216
if (ISCOMPLEX(relTypeId))
1218
(errcode(ERRCODE_UNDEFINED_COLUMN),
1219
errmsg("column \"%s\" not found in data type %s",
1220
attname, format_type_be(relTypeId))));
1221
else if (relTypeId == RECORDOID)
1223
(errcode(ERRCODE_UNDEFINED_COLUMN),
1224
errmsg("could not identify column \"%s\" in record data type",
1228
(errcode(ERRCODE_WRONG_OBJECT_TYPE),
1229
errmsg("column notation .%s applied to type %s, "
1230
"which is not a composite type",
1231
attname, format_type_be(relTypeId))));
1236
* funcname_signature_string
1237
* Build a string representing a function name, including arg types.
1238
* The result is something like "foo(integer)".
1240
* This is typically used in the construction of function-not-found error
1244
funcname_signature_string(const char *funcname,
1245
int nargs, const Oid *argtypes)
1247
StringInfoData argbuf;
1250
initStringInfo(&argbuf);
1252
appendStringInfo(&argbuf, "%s(", funcname);
1254
for (i = 0; i < nargs; i++)
1257
appendStringInfoString(&argbuf, ", ");
1258
appendStringInfoString(&argbuf, format_type_be(argtypes[i]));
1261
appendStringInfoChar(&argbuf, ')');
1263
return argbuf.data; /* return palloc'd string buffer */
1267
* func_signature_string
1268
* As above, but function name is passed as a qualified name list.
1271
func_signature_string(List *funcname, int nargs, const Oid *argtypes)
1273
return funcname_signature_string(NameListToString(funcname),
1278
* find_aggregate_func
1279
* Convenience routine to check that a function exists and is an
1282
* Note: basetype is ANYOID if we are looking for an aggregate on
1286
find_aggregate_func(List *aggname, Oid basetype, bool noError)
1292
oid = LookupFuncName(aggname, 1, &basetype, true);
1294
if (!OidIsValid(oid))
1298
if (basetype == ANYOID)
1300
(errcode(ERRCODE_UNDEFINED_FUNCTION),
1301
errmsg("aggregate %s(*) does not exist",
1302
NameListToString(aggname))));
1305
(errcode(ERRCODE_UNDEFINED_FUNCTION),
1306
errmsg("aggregate %s(%s) does not exist",
1307
NameListToString(aggname),
1308
format_type_be(basetype))));
1311
/* Make sure it's an aggregate */
1312
ftup = SearchSysCache(PROCOID,
1313
ObjectIdGetDatum(oid),
1315
if (!HeapTupleIsValid(ftup)) /* should not happen */
1316
elog(ERROR, "cache lookup failed for function %u", oid);
1317
pform = (Form_pg_proc) GETSTRUCT(ftup);
1319
if (!pform->proisagg)
1321
ReleaseSysCache(ftup);
1324
/* we do not use the (*) notation for functions... */
1326
(errcode(ERRCODE_WRONG_OBJECT_TYPE),
1327
errmsg("function %s(%s) is not an aggregate",
1328
NameListToString(aggname), format_type_be(basetype))));
1331
ReleaseSysCache(ftup);
1338
* Given a possibly-qualified function name and a set of argument types,
1339
* look up the function.
1341
* If the function name is not schema-qualified, it is sought in the current
1342
* namespace search path.
1344
* If the function is not found, we return InvalidOid if noError is true,
1345
* else raise an error.
1348
LookupFuncName(List *funcname, int nargs, const Oid *argtypes, bool noError)
1350
FuncCandidateList clist;
1352
clist = FuncnameGetCandidates(funcname, nargs);
1356
if (memcmp(argtypes, clist->args, nargs * sizeof(Oid)) == 0)
1358
clist = clist->next;
1363
(errcode(ERRCODE_UNDEFINED_FUNCTION),
1364
errmsg("function %s does not exist",
1365
func_signature_string(funcname, nargs, argtypes))));
1371
* LookupFuncNameTypeNames
1372
* Like LookupFuncName, but the argument types are specified by a
1373
* list of TypeName nodes.
1376
LookupFuncNameTypeNames(List *funcname, List *argtypes, bool noError)
1378
Oid argoids[FUNC_MAX_ARGS];
1381
ListCell *args_item;
1383
MemSet(argoids, 0, FUNC_MAX_ARGS * sizeof(Oid));
1384
argcount = list_length(argtypes);
1385
if (argcount > FUNC_MAX_ARGS)
1387
(errcode(ERRCODE_TOO_MANY_ARGUMENTS),
1388
errmsg("functions cannot have more than %d arguments",
1391
args_item = list_head(argtypes);
1392
for (i = 0; i < argcount; i++)
1394
TypeName *t = (TypeName *) lfirst(args_item);
1396
argoids[i] = LookupTypeName(t);
1398
if (!OidIsValid(argoids[i]))
1400
(errcode(ERRCODE_UNDEFINED_OBJECT),
1401
errmsg("type \"%s\" does not exist",
1402
TypeNameToString(t))));
1404
args_item = lnext(args_item);
1407
return LookupFuncName(funcname, argcount, argoids, noError);