~vcs-imports/mammoth-replicator/trunk

« back to all changes in this revision

Viewing changes to src/backend/parser/parse_func.c

  • Committer: alvherre
  • Date: 2005-12-16 21:24:52 UTC
  • Revision ID: svn-v4:db760fc0-0f08-0410-9d63-cc6633f64896:trunk:1
Initial import of the REL8_0_3 sources from the Pgsql CVS repository.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
/*-------------------------------------------------------------------------
 
2
 *
 
3
 * parse_func.c
 
4
 *              handle function calls in parser
 
5
 *
 
6
 * Portions Copyright (c) 1996-2005, PostgreSQL Global Development Group
 
7
 * Portions Copyright (c) 1994, Regents of the University of California
 
8
 *
 
9
 *
 
10
 * IDENTIFICATION
 
11
 *        $PostgreSQL: pgsql/src/backend/parser/parse_func.c,v 1.175 2004-12-31 22:00:27 pgsql Exp $
 
12
 *
 
13
 *-------------------------------------------------------------------------
 
14
 */
 
15
#include "postgres.h"
 
16
 
 
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"
 
33
 
 
34
 
 
35
static Node *ParseComplexProjection(ParseState *pstate, char *funcname,
 
36
                                           Node *first_arg);
 
37
static Oid **argtype_inherit(int nargs, Oid *argtypes);
 
38
 
 
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);
 
42
 
 
43
 
 
44
/*
 
45
 *      Parse a function call
 
46
 *
 
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.
 
53
 *
 
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.
 
60
 *
 
61
 *      The argument expressions (in fargs) must have been transformed already.
 
62
 */
 
63
Node *
 
64
ParseFuncOrColumn(ParseState *pstate, List *funcname, List *fargs,
 
65
                                  bool agg_star, bool agg_distinct, bool is_column)
 
66
{
 
67
        Oid                     rettype;
 
68
        Oid                     funcid;
 
69
        ListCell   *l;
 
70
        Node       *first_arg = NULL;
 
71
        int                     nargs = list_length(fargs);
 
72
        int                     argn;
 
73
        Oid                     actual_arg_types[FUNC_MAX_ARGS];
 
74
        Oid                *declared_arg_types;
 
75
        Node       *retval;
 
76
        bool            retset;
 
77
        FuncDetailCode fdresult;
 
78
 
 
79
        /*
 
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.
 
84
         */
 
85
        if (nargs > FUNC_MAX_ARGS)
 
86
                ereport(ERROR,
 
87
                                (errcode(ERRCODE_TOO_MANY_ARGUMENTS),
 
88
                           errmsg("cannot pass more than %d arguments to a function",
 
89
                                          FUNC_MAX_ARGS)));
 
90
 
 
91
        if (fargs)
 
92
        {
 
93
                first_arg = linitial(fargs);
 
94
                Assert(first_arg != NULL);
 
95
        }
 
96
 
 
97
        /*
 
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.
 
102
         */
 
103
        if (nargs == 1 && !agg_star && !agg_distinct && list_length(funcname) == 1)
 
104
        {
 
105
                Oid                     argtype = exprType(first_arg);
 
106
 
 
107
                if (argtype == RECORDOID || ISCOMPLEX(argtype))
 
108
                {
 
109
                        retval = ParseComplexProjection(pstate,
 
110
                                                                                        strVal(linitial(funcname)),
 
111
                                                                                        first_arg);
 
112
                        if (retval)
 
113
                                return retval;
 
114
 
 
115
                        /*
 
116
                         * If ParseComplexProjection doesn't recognize it as a
 
117
                         * projection, just press on.
 
118
                         */
 
119
                }
 
120
        }
 
121
 
 
122
        /*
 
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.
 
125
         */
 
126
        MemSet(actual_arg_types, 0, FUNC_MAX_ARGS * sizeof(Oid));
 
127
 
 
128
        argn = 0;
 
129
        foreach(l, fargs)
 
130
        {
 
131
                Node       *arg = lfirst(l);
 
132
 
 
133
                actual_arg_types[argn++] = exprType(arg);
 
134
        }
 
135
 
 
136
        /*
 
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
 
141
         * to the function.
 
142
         */
 
143
        fdresult = func_get_detail(funcname, fargs, nargs, actual_arg_types,
 
144
                                                           &funcid, &rettype, &retset,
 
145
                                                           &declared_arg_types);
 
146
        if (fdresult == FUNCDETAIL_COERCION)
 
147
        {
 
148
                /*
 
149
                 * We can do it as a trivial coercion. coerce_type can handle
 
150
                 * these cases, so why duplicate code...
 
151
                 */
 
152
                return coerce_type(pstate, linitial(fargs),
 
153
                                                   actual_arg_types[0], rettype, -1,
 
154
                                                   COERCION_EXPLICIT, COERCE_EXPLICIT_CALL);
 
155
        }
 
156
        else if (fdresult == FUNCDETAIL_NORMAL)
 
157
        {
 
158
                /*
 
159
                 * Normal function found; was there anything indicating it must be
 
160
                 * an aggregate?
 
161
                 */
 
162
                if (agg_star)
 
163
                        ereport(ERROR,
 
164
                                        (errcode(ERRCODE_WRONG_OBJECT_TYPE),
 
165
                        errmsg("%s(*) specified, but %s is not an aggregate function",
 
166
                                   NameListToString(funcname),
 
167
                                   NameListToString(funcname))));
 
168
                if (agg_distinct)
 
169
                        ereport(ERROR,
 
170
                                        (errcode(ERRCODE_WRONG_OBJECT_TYPE),
 
171
                                         errmsg("DISTINCT specified, but %s is not an aggregate function",
 
172
                                                        NameListToString(funcname))));
 
173
        }
 
174
        else if (fdresult != FUNCDETAIL_AGGREGATE)
 
175
        {
 
176
                /*
 
177
                 * Oops.  Time to die.
 
178
                 *
 
179
                 * If we are dealing with the attribute notation rel.function, give
 
180
                 * an error message that is appropriate for that case.
 
181
                 */
 
182
                if (is_column)
 
183
                {
 
184
                        Assert(nargs == 1);
 
185
                        Assert(list_length(funcname) == 1);
 
186
                        unknown_attribute(pstate, first_arg, strVal(linitial(funcname)));
 
187
                }
 
188
 
 
189
                /*
 
190
                 * Else generate a detailed complaint for a function
 
191
                 */
 
192
                if (fdresult == FUNCDETAIL_MULTIPLE)
 
193
                        ereport(ERROR,
 
194
                                        (errcode(ERRCODE_AMBIGUOUS_FUNCTION),
 
195
                                         errmsg("function %s is not unique",
 
196
                                                        func_signature_string(funcname, nargs,
 
197
                                                                                                  actual_arg_types)),
 
198
                                   errhint("Could not choose a best candidate function. "
 
199
                                                   "You may need to add explicit type casts.")));
 
200
                else
 
201
                        ereport(ERROR,
 
202
                                        (errcode(ERRCODE_UNDEFINED_FUNCTION),
 
203
                                         errmsg("function %s does not exist",
 
204
                                                        func_signature_string(funcname, nargs,
 
205
                                                                                                  actual_arg_types)),
 
206
                                         errhint("No function matches the given name and argument types. "
 
207
                                                   "You may need to add explicit type casts.")));
 
208
        }
 
209
 
 
210
        /*
 
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)
 
214
         */
 
215
        rettype = enforce_generic_type_consistency(actual_arg_types,
 
216
                                                                                           declared_arg_types,
 
217
                                                                                           nargs,
 
218
                                                                                           rettype);
 
219
 
 
220
        /* perform the necessary typecasting of arguments */
 
221
        make_fn_arguments(pstate, fargs, actual_arg_types, declared_arg_types);
 
222
 
 
223
        /* build the appropriate output structure */
 
224
        if (fdresult == FUNCDETAIL_NORMAL)
 
225
        {
 
226
                FuncExpr   *funcexpr = makeNode(FuncExpr);
 
227
 
 
228
                funcexpr->funcid = funcid;
 
229
                funcexpr->funcresulttype = rettype;
 
230
                funcexpr->funcretset = retset;
 
231
                funcexpr->funcformat = COERCE_EXPLICIT_CALL;
 
232
                funcexpr->args = fargs;
 
233
 
 
234
                retval = (Node *) funcexpr;
 
235
        }
 
236
        else
 
237
        {
 
238
                /* aggregate function */
 
239
                Aggref     *aggref = makeNode(Aggref);
 
240
 
 
241
                aggref->aggfnoid = funcid;
 
242
                aggref->aggtype = rettype;
 
243
                aggref->target = linitial(fargs);
 
244
                aggref->aggstar = agg_star;
 
245
                aggref->aggdistinct = agg_distinct;
 
246
 
 
247
                /* parse_agg.c does additional aggregate-specific processing */
 
248
                transformAggregateCall(pstate, aggref);
 
249
 
 
250
                retval = (Node *) aggref;
 
251
 
 
252
                if (retset)
 
253
                        ereport(ERROR,
 
254
                                        (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
 
255
                                         errmsg("aggregates may not return sets")));
 
256
        }
 
257
 
 
258
        return retval;
 
259
}
 
260
 
 
261
 
 
262
/* func_match_argtypes()
 
263
 *
 
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.
 
268
 *
 
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.
 
271
 *
 
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.
 
274
 */
 
275
int
 
276
func_match_argtypes(int nargs,
 
277
                                        Oid *input_typeids,
 
278
                                        FuncCandidateList raw_candidates,
 
279
                                        FuncCandidateList *candidates)          /* return value */
 
280
{
 
281
        FuncCandidateList current_candidate;
 
282
        FuncCandidateList next_candidate;
 
283
        int                     ncandidates = 0;
 
284
 
 
285
        *candidates = NULL;
 
286
 
 
287
        for (current_candidate = raw_candidates;
 
288
                 current_candidate != NULL;
 
289
                 current_candidate = next_candidate)
 
290
        {
 
291
                next_candidate = current_candidate->next;
 
292
                if (can_coerce_type(nargs, input_typeids, current_candidate->args,
 
293
                                                        COERCION_IMPLICIT))
 
294
                {
 
295
                        current_candidate->next = *candidates;
 
296
                        *candidates = current_candidate;
 
297
                        ncandidates++;
 
298
                }
 
299
        }
 
300
 
 
301
        return ncandidates;
 
302
}       /* func_match_argtypes() */
 
303
 
 
304
 
 
305
/* func_select_candidate()
 
306
 *              Given the input argtype array and more than one candidate
 
307
 *              for the function, attempt to resolve the conflict.
 
308
 *
 
309
 * Returns the selected candidate if the conflict can be resolved,
 
310
 * otherwise returns NULL.
 
311
 *
 
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.
 
315
 *
 
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.
 
320
 *
 
321
 * OLD COMMENTS:
 
322
 *
 
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
 
331
 *
 
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
 
335
 *
 
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
 
338
 * operator)
 
339
 *
 
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]
 
343
 *
 
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.
 
347
 *
 
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.)
 
358
 * - ay 6/95
 
359
 */
 
360
FuncCandidateList
 
361
func_select_candidate(int nargs,
 
362
                                          Oid *input_typeids,
 
363
                                          FuncCandidateList candidates)
 
364
{
 
365
        FuncCandidateList current_candidate;
 
366
        FuncCandidateList last_candidate;
 
367
        Oid                *current_typeids;
 
368
        Oid                     current_type;
 
369
        int                     i;
 
370
        int                     ncandidates;
 
371
        int                     nbestMatch,
 
372
                                nmatch;
 
373
        Oid                     input_base_typeids[FUNC_MAX_ARGS];
 
374
        CATEGORY        slot_category[FUNC_MAX_ARGS],
 
375
                                current_category;
 
376
        bool            slot_has_preferred_type[FUNC_MAX_ARGS];
 
377
        bool            resolved_unknowns;
 
378
 
 
379
        /*
 
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
 
388
         * by our caller.
 
389
         */
 
390
        for (i = 0; i < nargs; i++)
 
391
                input_base_typeids[i] = getBaseType(input_typeids[i]);
 
392
 
 
393
        /*
 
394
         * Run through all candidates and keep those with the most matches on
 
395
         * exact types. Keep all candidates if none match.
 
396
         */
 
397
        ncandidates = 0;
 
398
        nbestMatch = 0;
 
399
        last_candidate = NULL;
 
400
        for (current_candidate = candidates;
 
401
                 current_candidate != NULL;
 
402
                 current_candidate = current_candidate->next)
 
403
        {
 
404
                current_typeids = current_candidate->args;
 
405
                nmatch = 0;
 
406
                for (i = 0; i < nargs; i++)
 
407
                {
 
408
                        if (input_base_typeids[i] != UNKNOWNOID &&
 
409
                                current_typeids[i] == input_base_typeids[i])
 
410
                                nmatch++;
 
411
                }
 
412
 
 
413
                /* take this one as the best choice so far? */
 
414
                if ((nmatch > nbestMatch) || (last_candidate == NULL))
 
415
                {
 
416
                        nbestMatch = nmatch;
 
417
                        candidates = current_candidate;
 
418
                        last_candidate = current_candidate;
 
419
                        ncandidates = 1;
 
420
                }
 
421
                /* no worse than the last choice, so keep this one too? */
 
422
                else if (nmatch == nbestMatch)
 
423
                {
 
424
                        last_candidate->next = current_candidate;
 
425
                        last_candidate = current_candidate;
 
426
                        ncandidates++;
 
427
                }
 
428
                /* otherwise, don't bother keeping this one... */
 
429
        }
 
430
 
 
431
        if (last_candidate)                     /* terminate rebuilt list */
 
432
                last_candidate->next = NULL;
 
433
 
 
434
        if (ncandidates == 1)
 
435
                return candidates;
 
436
 
 
437
        /*
 
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.
 
444
         */
 
445
        for (i = 0; i < nargs; i++) /* avoid multiple lookups */
 
446
                slot_category[i] = TypeCategory(input_base_typeids[i]);
 
447
        ncandidates = 0;
 
448
        nbestMatch = 0;
 
449
        last_candidate = NULL;
 
450
        for (current_candidate = candidates;
 
451
                 current_candidate != NULL;
 
452
                 current_candidate = current_candidate->next)
 
453
        {
 
454
                current_typeids = current_candidate->args;
 
455
                nmatch = 0;
 
456
                for (i = 0; i < nargs; i++)
 
457
                {
 
458
                        if (input_base_typeids[i] != UNKNOWNOID)
 
459
                        {
 
460
                                if (current_typeids[i] == input_base_typeids[i] ||
 
461
                                        IsPreferredType(slot_category[i], current_typeids[i]))
 
462
                                        nmatch++;
 
463
                        }
 
464
                }
 
465
 
 
466
                if ((nmatch > nbestMatch) || (last_candidate == NULL))
 
467
                {
 
468
                        nbestMatch = nmatch;
 
469
                        candidates = current_candidate;
 
470
                        last_candidate = current_candidate;
 
471
                        ncandidates = 1;
 
472
                }
 
473
                else if (nmatch == nbestMatch)
 
474
                {
 
475
                        last_candidate->next = current_candidate;
 
476
                        last_candidate = current_candidate;
 
477
                        ncandidates++;
 
478
                }
 
479
        }
 
480
 
 
481
        if (last_candidate)                     /* terminate rebuilt list */
 
482
                last_candidate->next = NULL;
 
483
 
 
484
        if (ncandidates == 1)
 
485
                return candidates;
 
486
 
 
487
        /*
 
488
         * Still too many candidates? Try assigning types for the unknown
 
489
         * columns.
 
490
         *
 
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
 
495
         * next.
 
496
         *
 
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.
 
504
         *
 
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.
 
507
         *
 
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.
 
512
         *
 
513
         * If we are down to one candidate at the end, we win.
 
514
         */
 
515
        resolved_unknowns = false;
 
516
        for (i = 0; i < nargs; i++)
 
517
        {
 
518
                bool            have_conflict;
 
519
 
 
520
                if (input_base_typeids[i] != UNKNOWNOID)
 
521
                        continue;
 
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)
 
529
                {
 
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)
 
534
                        {
 
535
                                /* first candidate */
 
536
                                slot_category[i] = current_category;
 
537
                                slot_has_preferred_type[i] =
 
538
                                        IsPreferredType(current_category, current_type);
 
539
                        }
 
540
                        else if (current_category == slot_category[i])
 
541
                        {
 
542
                                /* more candidates in same category */
 
543
                                slot_has_preferred_type[i] |=
 
544
                                        IsPreferredType(current_category, current_type);
 
545
                        }
 
546
                        else
 
547
                        {
 
548
                                /* category conflict! */
 
549
                                if (current_category == STRING_TYPE)
 
550
                                {
 
551
                                        /* STRING always wins if available */
 
552
                                        slot_category[i] = current_category;
 
553
                                        slot_has_preferred_type[i] =
 
554
                                                IsPreferredType(current_category, current_type);
 
555
                                }
 
556
                                else
 
557
                                {
 
558
                                        /*
 
559
                                         * Remember conflict, but keep going (might find
 
560
                                         * STRING)
 
561
                                         */
 
562
                                        have_conflict = true;
 
563
                                }
 
564
                        }
 
565
                }
 
566
                if (have_conflict && slot_category[i] != STRING_TYPE)
 
567
                {
 
568
                        /* Failed to resolve category conflict at this position */
 
569
                        resolved_unknowns = false;
 
570
                        break;
 
571
                }
 
572
        }
 
573
 
 
574
        if (resolved_unknowns)
 
575
        {
 
576
                /* Strip non-matching candidates */
 
577
                ncandidates = 0;
 
578
                last_candidate = NULL;
 
579
                for (current_candidate = candidates;
 
580
                         current_candidate != NULL;
 
581
                         current_candidate = current_candidate->next)
 
582
                {
 
583
                        bool            keepit = true;
 
584
 
 
585
                        current_typeids = current_candidate->args;
 
586
                        for (i = 0; i < nargs; i++)
 
587
                        {
 
588
                                if (input_base_typeids[i] != UNKNOWNOID)
 
589
                                        continue;
 
590
                                current_type = current_typeids[i];
 
591
                                current_category = TypeCategory(current_type);
 
592
                                if (current_category != slot_category[i])
 
593
                                {
 
594
                                        keepit = false;
 
595
                                        break;
 
596
                                }
 
597
                                if (slot_has_preferred_type[i] &&
 
598
                                        !IsPreferredType(current_category, current_type))
 
599
                                {
 
600
                                        keepit = false;
 
601
                                        break;
 
602
                                }
 
603
                        }
 
604
                        if (keepit)
 
605
                        {
 
606
                                /* keep this candidate */
 
607
                                last_candidate = current_candidate;
 
608
                                ncandidates++;
 
609
                        }
 
610
                        else
 
611
                        {
 
612
                                /* forget this candidate */
 
613
                                if (last_candidate)
 
614
                                        last_candidate->next = current_candidate->next;
 
615
                                else
 
616
                                        candidates = current_candidate->next;
 
617
                        }
 
618
                }
 
619
                if (last_candidate)             /* terminate rebuilt list */
 
620
                        last_candidate->next = NULL;
 
621
        }
 
622
 
 
623
        if (ncandidates == 1)
 
624
                return candidates;
 
625
 
 
626
        return NULL;                            /* failed to select a best candidate */
 
627
}       /* func_select_candidate() */
 
628
 
 
629
 
 
630
/* func_get_detail()
 
631
 *
 
632
 * Find the named function in the system catalogs.
 
633
 *
 
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.
 
637
 *
 
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
 
650
 *
 
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.
 
655
 */
 
656
FuncDetailCode
 
657
func_get_detail(List *funcname,
 
658
                                List *fargs,
 
659
                                int nargs,
 
660
                                Oid *argtypes,
 
661
                                Oid *funcid,    /* return value */
 
662
                                Oid *rettype,   /* return value */
 
663
                                bool *retset,   /* return value */
 
664
                                Oid **true_typeids)             /* return value */
 
665
{
 
666
        FuncCandidateList raw_candidates;
 
667
        FuncCandidateList best_candidate;
 
668
 
 
669
        /* Get list of possible candidates from namespace search */
 
670
        raw_candidates = FuncnameGetCandidates(funcname, nargs);
 
671
 
 
672
        /*
 
673
         * Quickly check if there is an exact match to the input datatypes
 
674
         * (there can be only one)
 
675
         */
 
676
        for (best_candidate = raw_candidates;
 
677
                 best_candidate != NULL;
 
678
                 best_candidate = best_candidate->next)
 
679
        {
 
680
                if (memcmp(argtypes, best_candidate->args, nargs * sizeof(Oid)) == 0)
 
681
                        break;
 
682
        }
 
683
 
 
684
        if (best_candidate == NULL)
 
685
        {
 
686
                /*
 
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
 
698
                 * selecting.
 
699
                 *
 
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.
 
703
                 *
 
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
 
708
                 * appropriate.
 
709
                 *
 
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!
 
715
                 */
 
716
                if (nargs == 1 && fargs != NIL)
 
717
                {
 
718
                        Oid                     targetType;
 
719
                        TypeName   *tn = makeNode(TypeName);
 
720
 
 
721
                        tn->names = funcname;
 
722
                        tn->typmod = -1;
 
723
                        targetType = LookupTypeName(tn);
 
724
                        if (OidIsValid(targetType) &&
 
725
                                !ISCOMPLEX(targetType))
 
726
                        {
 
727
                                Oid                     sourceType = argtypes[0];
 
728
                                Node       *arg1 = linitial(fargs);
 
729
                                Oid                     cfuncid;
 
730
 
 
731
                                if ((sourceType == UNKNOWNOID && IsA(arg1, Const)) ||
 
732
                                        (find_coercion_pathway(targetType, sourceType,
 
733
                                                                                   COERCION_EXPLICIT, &cfuncid) &&
 
734
                                         cfuncid == InvalidOid))
 
735
                                {
 
736
                                        /* Yup, it's a type coercion */
 
737
                                        *funcid = InvalidOid;
 
738
                                        *rettype = targetType;
 
739
                                        *retset = false;
 
740
                                        *true_typeids = argtypes;
 
741
                                        return FUNCDETAIL_COERCION;
 
742
                                }
 
743
                        }
 
744
                }
 
745
 
 
746
                /*
 
747
                 * didn't find an exact match, so now try to match up
 
748
                 * candidates...
 
749
                 */
 
750
                if (raw_candidates != NULL)
 
751
                {
 
752
                        Oid               **input_typeid_vector = NULL;
 
753
                        Oid                *current_input_typeids;
 
754
 
 
755
                        /*
 
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.
 
759
                         */
 
760
                        current_input_typeids = argtypes;
 
761
 
 
762
                        do
 
763
                        {
 
764
                                FuncCandidateList current_candidates;
 
765
                                int                     ncandidates;
 
766
 
 
767
                                ncandidates = func_match_argtypes(nargs,
 
768
                                                                                                  current_input_typeids,
 
769
                                                                                                  raw_candidates,
 
770
                                                                                                  &current_candidates);
 
771
 
 
772
                                /* one match only? then run with it... */
 
773
                                if (ncandidates == 1)
 
774
                                {
 
775
                                        best_candidate = current_candidates;
 
776
                                        break;
 
777
                                }
 
778
 
 
779
                                /*
 
780
                                 * multiple candidates? then better decide or throw an
 
781
                                 * error...
 
782
                                 */
 
783
                                if (ncandidates > 1)
 
784
                                {
 
785
                                        best_candidate = func_select_candidate(nargs,
 
786
                                                                                                   current_input_typeids,
 
787
                                                                                                         current_candidates);
 
788
 
 
789
                                        /*
 
790
                                         * If we were able to choose a best candidate, we're
 
791
                                         * done.  Otherwise, ambiguous function call.
 
792
                                         */
 
793
                                        if (best_candidate)
 
794
                                                break;
 
795
                                        return FUNCDETAIL_MULTIPLE;
 
796
                                }
 
797
 
 
798
                                /*
 
799
                                 * No match here, so try the next inherited type vector.
 
800
                                 * First time through, we need to compute the list of
 
801
                                 * vectors.
 
802
                                 */
 
803
                                if (input_typeid_vector == NULL)
 
804
                                        input_typeid_vector = argtype_inherit(nargs, argtypes);
 
805
 
 
806
                                current_input_typeids = *input_typeid_vector++;
 
807
                        }
 
808
                        while (current_input_typeids != NULL);
 
809
                }
 
810
        }
 
811
 
 
812
        if (best_candidate)
 
813
        {
 
814
                HeapTuple       ftup;
 
815
                Form_pg_proc pform;
 
816
                FuncDetailCode result;
 
817
 
 
818
                *funcid = best_candidate->oid;
 
819
                *true_typeids = best_candidate->args;
 
820
 
 
821
                ftup = SearchSysCache(PROCOID,
 
822
                                                          ObjectIdGetDatum(best_candidate->oid),
 
823
                                                          0, 0, 0);
 
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);
 
832
                return result;
 
833
        }
 
834
 
 
835
        return FUNCDETAIL_NOTFOUND;
 
836
}
 
837
 
 
838
/*
 
839
 *      argtype_inherit() -- Construct an argtype vector reflecting the
 
840
 *                                               inheritance properties of the supplied argv.
 
841
 *
 
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).
 
846
 *
 
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.
 
854
 *
 
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.
 
861
 *
 
862
 *              The vector does not include the case where no complex classes have
 
863
 *              been promoted, since that was already tried before this routine
 
864
 *              got called.
 
865
 */
 
866
static Oid **
 
867
argtype_inherit(int nargs, Oid *argtypes)
 
868
{
 
869
        Oid                     relid;
 
870
        int                     i;
 
871
        InhPaths        arginh[FUNC_MAX_ARGS];
 
872
 
 
873
        for (i = 0; i < nargs; i++)
 
874
        {
 
875
                arginh[i].self = argtypes[i];
 
876
                if ((relid = typeidTypeRelid(argtypes[i])) != InvalidOid)
 
877
                        arginh[i].nsupers = find_inheritors(relid, &(arginh[i].supervec));
 
878
                else
 
879
                {
 
880
                        arginh[i].nsupers = 0;
 
881
                        arginh[i].supervec = NULL;
 
882
                }
 
883
        }
 
884
 
 
885
        /* return an ordered cross-product of the classes involved */
 
886
        return gen_cross_product(arginh, nargs);
 
887
}
 
888
 
 
889
/*
 
890
 * Look up the parent superclass(es) of the given relation.
 
891
 *
 
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.
 
895
 */
 
896
static int
 
897
find_inheritors(Oid relid, Oid **supervec)
 
898
{
 
899
        Relation        inhrel;
 
900
        int                     nvisited;
 
901
        List       *visited,
 
902
                           *queue;
 
903
        ListCell   *queue_item;
 
904
 
 
905
        /*
 
906
         * Begin the search at the relation itself, so add relid to the queue.
 
907
         */
 
908
        queue = list_make1_oid(relid);
 
909
        visited = NIL;
 
910
 
 
911
        inhrel = heap_openr(InheritsRelationName, AccessShareLock);
 
912
 
 
913
        /*
 
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
 
918
         * begins.
 
919
         */
 
920
        foreach(queue_item, queue)
 
921
        {
 
922
                Oid                     this_relid = lfirst_oid(queue_item);
 
923
                ScanKeyData skey;
 
924
                HeapScanDesc inhscan;
 
925
                HeapTuple       inhtup;
 
926
 
 
927
                /* If we've seen this relid already, skip it */
 
928
                if (list_member_oid(visited, this_relid))
 
929
                        continue;
 
930
 
 
931
                /*
 
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'.
 
936
                 */
 
937
                if (queue_item != list_head(queue))
 
938
                        visited = lappend_oid(visited, this_relid);
 
939
 
 
940
                ScanKeyInit(&skey,
 
941
                                        Anum_pg_inherits_inhrelid,
 
942
                                        BTEqualStrategyNumber, F_OIDEQ,
 
943
                                        ObjectIdGetDatum(this_relid));
 
944
 
 
945
                inhscan = heap_beginscan(inhrel, SnapshotNow, 1, &skey);
 
946
 
 
947
                while ((inhtup = heap_getnext(inhscan, ForwardScanDirection)) != NULL)
 
948
                {
 
949
                        Form_pg_inherits inh = (Form_pg_inherits) GETSTRUCT(inhtup);
 
950
 
 
951
                        queue = lappend_oid(queue, inh->inhparent);
 
952
                }
 
953
 
 
954
                heap_endscan(inhscan);
 
955
        }
 
956
 
 
957
        heap_close(inhrel, AccessShareLock);
 
958
 
 
959
        nvisited = list_length(visited);
 
960
        if (nvisited > 0)
 
961
        {
 
962
                Oid                *relidvec;
 
963
                ListCell   *l;
 
964
 
 
965
                relidvec = (Oid *) palloc(nvisited * sizeof(*relidvec));
 
966
                *supervec = relidvec;
 
967
 
 
968
                foreach(l, visited)
 
969
                {
 
970
                        /* return the type id, rather than the relation id */
 
971
                        *relidvec++ = get_rel_type_id(lfirst_oid(l));
 
972
                }
 
973
        }
 
974
        else
 
975
                *supervec = NULL;
 
976
 
 
977
        list_free(visited);
 
978
        list_free(queue);
 
979
 
 
980
        return nvisited;
 
981
}
 
982
 
 
983
/*
 
984
 * Generate the ordered list of substitute argtype vectors to try.
 
985
 *
 
986
 * See comments for argtype_inherit.
 
987
 */
 
988
static Oid **
 
989
gen_cross_product(InhPaths *arginh, int nargs)
 
990
{
 
991
        int                     nanswers;
 
992
        Oid               **result;
 
993
        Oid                *oneres;
 
994
        int                     i,
 
995
                                j;
 
996
        int                     cur[FUNC_MAX_ARGS];
 
997
 
 
998
        /*
 
999
         * At each position we want to try the original datatype, plus each
 
1000
         * supertype.  So the number of possible combinations is this:
 
1001
         */
 
1002
        nanswers = 1;
 
1003
        for (i = 0; i < nargs; i++)
 
1004
                nanswers *= (arginh[i].nsupers + 1);
 
1005
 
 
1006
        /*
 
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.
 
1010
         */
 
1011
        result = (Oid **) palloc(sizeof(Oid *) * nanswers);
 
1012
        j = 0;
 
1013
 
 
1014
        /*
 
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.
 
1018
         */
 
1019
        MemSet(cur, 0, sizeof(cur));
 
1020
 
 
1021
        for (;;)
 
1022
        {
 
1023
                /*
 
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[].)
 
1027
                 */
 
1028
                for (i = nargs - 1; i >= 0 && cur[i] >= arginh[i].nsupers; i--)
 
1029
                        cur[i] = 0;
 
1030
 
 
1031
                /* if none, we're done */
 
1032
                if (i < 0)
 
1033
                        break;
 
1034
 
 
1035
                /* increment this column */
 
1036
                cur[i] += 1;
 
1037
 
 
1038
                /* Generate the proper output type-OID vector */
 
1039
                oneres = (Oid *) palloc0(FUNC_MAX_ARGS * sizeof(Oid));
 
1040
 
 
1041
                for (i = 0; i < nargs; i++)
 
1042
                {
 
1043
                        if (cur[i] == 0)
 
1044
                                oneres[i] = arginh[i].self;
 
1045
                        else
 
1046
                                oneres[i] = arginh[i].supervec[cur[i] - 1];
 
1047
                }
 
1048
 
 
1049
                result[j++] = oneres;
 
1050
        }
 
1051
 
 
1052
        /* terminate result vector with NULL pointer */
 
1053
        result[j++] = NULL;
 
1054
 
 
1055
        Assert(j == nanswers);
 
1056
 
 
1057
        return result;
 
1058
}
 
1059
 
 
1060
 
 
1061
/*
 
1062
 * Given two type OIDs, determine whether the first is a complex type
 
1063
 * (class type) that inherits from the second.
 
1064
 */
 
1065
bool
 
1066
typeInheritsFrom(Oid subclassTypeId, Oid superclassTypeId)
 
1067
{
 
1068
        Oid                     relid;
 
1069
        Oid                *supervec;
 
1070
        int                     nsupers,
 
1071
                                i;
 
1072
        bool            result;
 
1073
 
 
1074
        if (!ISCOMPLEX(subclassTypeId) || !ISCOMPLEX(superclassTypeId))
 
1075
                return false;
 
1076
        relid = typeidTypeRelid(subclassTypeId);
 
1077
        if (relid == InvalidOid)
 
1078
                return false;
 
1079
        nsupers = find_inheritors(relid, &supervec);
 
1080
        result = false;
 
1081
        for (i = 0; i < nsupers; i++)
 
1082
        {
 
1083
                if (supervec[i] == superclassTypeId)
 
1084
                {
 
1085
                        result = true;
 
1086
                        break;
 
1087
                }
 
1088
        }
 
1089
        if (supervec)
 
1090
                pfree(supervec);
 
1091
        return result;
 
1092
}
 
1093
 
 
1094
 
 
1095
/*
 
1096
 * make_fn_arguments()
 
1097
 *
 
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
 
1101
 * allowed.
 
1102
 *
 
1103
 * Caution: given argument list is modified in-place.
 
1104
 *
 
1105
 * As with coerce_type, pstate may be NULL if no special unknown-Param
 
1106
 * processing is wanted.
 
1107
 */
 
1108
void
 
1109
make_fn_arguments(ParseState *pstate,
 
1110
                                  List *fargs,
 
1111
                                  Oid *actual_arg_types,
 
1112
                                  Oid *declared_arg_types)
 
1113
{
 
1114
        ListCell   *current_fargs;
 
1115
        int                     i = 0;
 
1116
 
 
1117
        foreach(current_fargs, fargs)
 
1118
        {
 
1119
                /* types don't match? then force coercion using a function call... */
 
1120
                if (actual_arg_types[i] != declared_arg_types[i])
 
1121
                {
 
1122
                        lfirst(current_fargs) = coerce_type(pstate,
 
1123
                                                                                                lfirst(current_fargs),
 
1124
                                                                                                actual_arg_types[i],
 
1125
                                                                                                declared_arg_types[i], -1,
 
1126
                                                                                                COERCION_IMPLICIT,
 
1127
                                                                                                COERCE_IMPLICIT_CAST);
 
1128
                }
 
1129
                i++;
 
1130
        }
 
1131
}
 
1132
 
 
1133
/*
 
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.
 
1138
 */
 
1139
static Node *
 
1140
ParseComplexProjection(ParseState *pstate, char *funcname, Node *first_arg)
 
1141
{
 
1142
        Oid                     argtype;
 
1143
        Oid                     argrelid;
 
1144
        AttrNumber      attnum;
 
1145
        FieldSelect *fselect;
 
1146
 
 
1147
        /*
 
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.
 
1153
         */
 
1154
        if (IsA(first_arg, Var) &&
 
1155
                ((Var *) first_arg)->varattno == InvalidAttrNumber)
 
1156
        {
 
1157
                RangeTblEntry *rte;
 
1158
 
 
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);
 
1164
        }
 
1165
 
 
1166
        /*
 
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.
 
1170
         */
 
1171
        argtype = exprType(first_arg);
 
1172
        argrelid = typeidTypeRelid(argtype);
 
1173
        if (!argrelid)
 
1174
                return NULL;                    /* can only happen if RECORD */
 
1175
 
 
1176
        attnum = get_attnum(argrelid, funcname);
 
1177
        if (attnum == InvalidAttrNumber)
 
1178
                return NULL;                    /* funcname does not match any column */
 
1179
 
 
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);
 
1187
 
 
1188
        return (Node *) fselect;
 
1189
}
 
1190
 
 
1191
/*
 
1192
 * helper routine for delivering "column does not exist" error message
 
1193
 */
 
1194
static void
 
1195
unknown_attribute(ParseState *pstate, Node *relref, char *attname)
 
1196
{
 
1197
        RangeTblEntry *rte;
 
1198
 
 
1199
        if (IsA(relref, Var) &&
 
1200
                ((Var *) relref)->varattno == InvalidAttrNumber)
 
1201
        {
 
1202
                /* Reference the RTE by alias not by actual table name */
 
1203
                rte = GetRTEByRangeTablePosn(pstate,
 
1204
                                                                         ((Var *) relref)->varno,
 
1205
                                                                         ((Var *) relref)->varlevelsup);
 
1206
                ereport(ERROR,
 
1207
                                (errcode(ERRCODE_UNDEFINED_COLUMN),
 
1208
                                 errmsg("column %s.%s does not exist",
 
1209
                                                rte->eref->aliasname, attname)));
 
1210
        }
 
1211
        else
 
1212
        {
 
1213
                /* Have to do it by reference to the type of the expression */
 
1214
                Oid                     relTypeId = exprType(relref);
 
1215
 
 
1216
                if (ISCOMPLEX(relTypeId))
 
1217
                        ereport(ERROR,
 
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)
 
1222
                        ereport(ERROR,
 
1223
                                        (errcode(ERRCODE_UNDEFINED_COLUMN),
 
1224
                        errmsg("could not identify column \"%s\" in record data type",
 
1225
                                   attname)));
 
1226
                else
 
1227
                        ereport(ERROR,
 
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))));
 
1232
        }
 
1233
}
 
1234
 
 
1235
/*
 
1236
 * funcname_signature_string
 
1237
 *              Build a string representing a function name, including arg types.
 
1238
 *              The result is something like "foo(integer)".
 
1239
 *
 
1240
 * This is typically used in the construction of function-not-found error
 
1241
 * messages.
 
1242
 */
 
1243
const char *
 
1244
funcname_signature_string(const char *funcname,
 
1245
                                                  int nargs, const Oid *argtypes)
 
1246
{
 
1247
        StringInfoData argbuf;
 
1248
        int                     i;
 
1249
 
 
1250
        initStringInfo(&argbuf);
 
1251
 
 
1252
        appendStringInfo(&argbuf, "%s(", funcname);
 
1253
 
 
1254
        for (i = 0; i < nargs; i++)
 
1255
        {
 
1256
                if (i)
 
1257
                        appendStringInfoString(&argbuf, ", ");
 
1258
                appendStringInfoString(&argbuf, format_type_be(argtypes[i]));
 
1259
        }
 
1260
 
 
1261
        appendStringInfoChar(&argbuf, ')');
 
1262
 
 
1263
        return argbuf.data;                     /* return palloc'd string buffer */
 
1264
}
 
1265
 
 
1266
/*
 
1267
 * func_signature_string
 
1268
 *              As above, but function name is passed as a qualified name list.
 
1269
 */
 
1270
const char *
 
1271
func_signature_string(List *funcname, int nargs, const Oid *argtypes)
 
1272
{
 
1273
        return funcname_signature_string(NameListToString(funcname),
 
1274
                                                                         nargs, argtypes);
 
1275
}
 
1276
 
 
1277
/*
 
1278
 * find_aggregate_func
 
1279
 *              Convenience routine to check that a function exists and is an
 
1280
 *              aggregate.
 
1281
 *
 
1282
 * Note: basetype is ANYOID if we are looking for an aggregate on
 
1283
 * all types.
 
1284
 */
 
1285
Oid
 
1286
find_aggregate_func(List *aggname, Oid basetype, bool noError)
 
1287
{
 
1288
        Oid                     oid;
 
1289
        HeapTuple       ftup;
 
1290
        Form_pg_proc pform;
 
1291
 
 
1292
        oid = LookupFuncName(aggname, 1, &basetype, true);
 
1293
 
 
1294
        if (!OidIsValid(oid))
 
1295
        {
 
1296
                if (noError)
 
1297
                        return InvalidOid;
 
1298
                if (basetype == ANYOID)
 
1299
                        ereport(ERROR,
 
1300
                                        (errcode(ERRCODE_UNDEFINED_FUNCTION),
 
1301
                                         errmsg("aggregate %s(*) does not exist",
 
1302
                                                        NameListToString(aggname))));
 
1303
                else
 
1304
                        ereport(ERROR,
 
1305
                                        (errcode(ERRCODE_UNDEFINED_FUNCTION),
 
1306
                                         errmsg("aggregate %s(%s) does not exist",
 
1307
                                                        NameListToString(aggname),
 
1308
                                                        format_type_be(basetype))));
 
1309
        }
 
1310
 
 
1311
        /* Make sure it's an aggregate */
 
1312
        ftup = SearchSysCache(PROCOID,
 
1313
                                                  ObjectIdGetDatum(oid),
 
1314
                                                  0, 0, 0);
 
1315
        if (!HeapTupleIsValid(ftup))    /* should not happen */
 
1316
                elog(ERROR, "cache lookup failed for function %u", oid);
 
1317
        pform = (Form_pg_proc) GETSTRUCT(ftup);
 
1318
 
 
1319
        if (!pform->proisagg)
 
1320
        {
 
1321
                ReleaseSysCache(ftup);
 
1322
                if (noError)
 
1323
                        return InvalidOid;
 
1324
                /* we do not use the (*) notation for functions... */
 
1325
                ereport(ERROR,
 
1326
                                (errcode(ERRCODE_WRONG_OBJECT_TYPE),
 
1327
                                 errmsg("function %s(%s) is not an aggregate",
 
1328
                                  NameListToString(aggname), format_type_be(basetype))));
 
1329
        }
 
1330
 
 
1331
        ReleaseSysCache(ftup);
 
1332
 
 
1333
        return oid;
 
1334
}
 
1335
 
 
1336
/*
 
1337
 * LookupFuncName
 
1338
 *              Given a possibly-qualified function name and a set of argument types,
 
1339
 *              look up the function.
 
1340
 *
 
1341
 * If the function name is not schema-qualified, it is sought in the current
 
1342
 * namespace search path.
 
1343
 *
 
1344
 * If the function is not found, we return InvalidOid if noError is true,
 
1345
 * else raise an error.
 
1346
 */
 
1347
Oid
 
1348
LookupFuncName(List *funcname, int nargs, const Oid *argtypes, bool noError)
 
1349
{
 
1350
        FuncCandidateList clist;
 
1351
 
 
1352
        clist = FuncnameGetCandidates(funcname, nargs);
 
1353
 
 
1354
        while (clist)
 
1355
        {
 
1356
                if (memcmp(argtypes, clist->args, nargs * sizeof(Oid)) == 0)
 
1357
                        return clist->oid;
 
1358
                clist = clist->next;
 
1359
        }
 
1360
 
 
1361
        if (!noError)
 
1362
                ereport(ERROR,
 
1363
                                (errcode(ERRCODE_UNDEFINED_FUNCTION),
 
1364
                                 errmsg("function %s does not exist",
 
1365
                                         func_signature_string(funcname, nargs, argtypes))));
 
1366
 
 
1367
        return InvalidOid;
 
1368
}
 
1369
 
 
1370
/*
 
1371
 * LookupFuncNameTypeNames
 
1372
 *              Like LookupFuncName, but the argument types are specified by a
 
1373
 *              list of TypeName nodes.
 
1374
 */
 
1375
Oid
 
1376
LookupFuncNameTypeNames(List *funcname, List *argtypes, bool noError)
 
1377
{
 
1378
        Oid                     argoids[FUNC_MAX_ARGS];
 
1379
        int                     argcount;
 
1380
        int                     i;
 
1381
        ListCell   *args_item;
 
1382
 
 
1383
        MemSet(argoids, 0, FUNC_MAX_ARGS * sizeof(Oid));
 
1384
        argcount = list_length(argtypes);
 
1385
        if (argcount > FUNC_MAX_ARGS)
 
1386
                ereport(ERROR,
 
1387
                                (errcode(ERRCODE_TOO_MANY_ARGUMENTS),
 
1388
                                 errmsg("functions cannot have more than %d arguments",
 
1389
                                                FUNC_MAX_ARGS)));
 
1390
 
 
1391
        args_item = list_head(argtypes);
 
1392
        for (i = 0; i < argcount; i++)
 
1393
        {
 
1394
                TypeName   *t = (TypeName *) lfirst(args_item);
 
1395
 
 
1396
                argoids[i] = LookupTypeName(t);
 
1397
 
 
1398
                if (!OidIsValid(argoids[i]))
 
1399
                        ereport(ERROR,
 
1400
                                        (errcode(ERRCODE_UNDEFINED_OBJECT),
 
1401
                                         errmsg("type \"%s\" does not exist",
 
1402
                                                        TypeNameToString(t))));
 
1403
 
 
1404
                args_item = lnext(args_item);
 
1405
        }
 
1406
 
 
1407
        return LookupFuncName(funcname, argcount, argoids, noError);
 
1408
}