]> granicus.if.org Git - postgresql/blob - src/backend/utils/fmgr/funcapi.c
Run pgindent on 9.2 source tree in preparation for first 9.3
[postgresql] / src / backend / utils / fmgr / funcapi.c
1 /*-------------------------------------------------------------------------
2  *
3  * funcapi.c
4  *        Utility and convenience functions for fmgr functions that return
5  *        sets and/or composite types.
6  *
7  * Copyright (c) 2002-2012, PostgreSQL Global Development Group
8  *
9  * IDENTIFICATION
10  *        src/backend/utils/fmgr/funcapi.c
11  *
12  *-------------------------------------------------------------------------
13  */
14 #include "postgres.h"
15
16 #include "catalog/namespace.h"
17 #include "catalog/pg_proc.h"
18 #include "catalog/pg_type.h"
19 #include "funcapi.h"
20 #include "nodes/nodeFuncs.h"
21 #include "parser/parse_coerce.h"
22 #include "utils/array.h"
23 #include "utils/builtins.h"
24 #include "utils/lsyscache.h"
25 #include "utils/memutils.h"
26 #include "utils/rel.h"
27 #include "utils/syscache.h"
28 #include "utils/typcache.h"
29
30
31 static void shutdown_MultiFuncCall(Datum arg);
32 static TypeFuncClass internal_get_result_type(Oid funcid,
33                                                  Node *call_expr,
34                                                  ReturnSetInfo *rsinfo,
35                                                  Oid *resultTypeId,
36                                                  TupleDesc *resultTupleDesc);
37 static bool resolve_polymorphic_tupdesc(TupleDesc tupdesc,
38                                                         oidvector *declared_args,
39                                                         Node *call_expr);
40 static TypeFuncClass get_type_func_class(Oid typid);
41
42
43 /*
44  * init_MultiFuncCall
45  * Create an empty FuncCallContext data structure
46  * and do some other basic Multi-function call setup
47  * and error checking
48  */
49 FuncCallContext *
50 init_MultiFuncCall(PG_FUNCTION_ARGS)
51 {
52         FuncCallContext *retval;
53
54         /*
55          * Bail if we're called in the wrong context
56          */
57         if (fcinfo->resultinfo == NULL || !IsA(fcinfo->resultinfo, ReturnSetInfo))
58                 ereport(ERROR,
59                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
60                                  errmsg("set-valued function called in context that cannot accept a set")));
61
62         if (fcinfo->flinfo->fn_extra == NULL)
63         {
64                 /*
65                  * First call
66                  */
67                 ReturnSetInfo *rsi = (ReturnSetInfo *) fcinfo->resultinfo;
68                 MemoryContext multi_call_ctx;
69
70                 /*
71                  * Create a suitably long-lived context to hold cross-call data
72                  */
73                 multi_call_ctx = AllocSetContextCreate(fcinfo->flinfo->fn_mcxt,
74                                                                                            "SRF multi-call context",
75                                                                                            ALLOCSET_SMALL_MINSIZE,
76                                                                                            ALLOCSET_SMALL_INITSIZE,
77                                                                                            ALLOCSET_SMALL_MAXSIZE);
78
79                 /*
80                  * Allocate suitably long-lived space and zero it
81                  */
82                 retval = (FuncCallContext *)
83                         MemoryContextAllocZero(multi_call_ctx,
84                                                                    sizeof(FuncCallContext));
85
86                 /*
87                  * initialize the elements
88                  */
89                 retval->call_cntr = 0;
90                 retval->max_calls = 0;
91                 retval->slot = NULL;
92                 retval->user_fctx = NULL;
93                 retval->attinmeta = NULL;
94                 retval->tuple_desc = NULL;
95                 retval->multi_call_memory_ctx = multi_call_ctx;
96
97                 /*
98                  * save the pointer for cross-call use
99                  */
100                 fcinfo->flinfo->fn_extra = retval;
101
102                 /*
103                  * Ensure we will get shut down cleanly if the exprcontext is not run
104                  * to completion.
105                  */
106                 RegisterExprContextCallback(rsi->econtext,
107                                                                         shutdown_MultiFuncCall,
108                                                                         PointerGetDatum(fcinfo->flinfo));
109         }
110         else
111         {
112                 /* second and subsequent calls */
113                 elog(ERROR, "init_MultiFuncCall cannot be called more than once");
114
115                 /* never reached, but keep compiler happy */
116                 retval = NULL;
117         }
118
119         return retval;
120 }
121
122 /*
123  * per_MultiFuncCall
124  *
125  * Do Multi-function per-call setup
126  */
127 FuncCallContext *
128 per_MultiFuncCall(PG_FUNCTION_ARGS)
129 {
130         FuncCallContext *retval = (FuncCallContext *) fcinfo->flinfo->fn_extra;
131
132         /*
133          * Clear the TupleTableSlot, if present.  This is for safety's sake: the
134          * Slot will be in a long-lived context (it better be, if the
135          * FuncCallContext is pointing to it), but in most usage patterns the
136          * tuples stored in it will be in the function's per-tuple context. So at
137          * the beginning of each call, the Slot will hold a dangling pointer to an
138          * already-recycled tuple.      We clear it out here.
139          *
140          * Note: use of retval->slot is obsolete as of 8.0, and we expect that it
141          * will always be NULL.  This is just here for backwards compatibility in
142          * case someone creates a slot anyway.
143          */
144         if (retval->slot != NULL)
145                 ExecClearTuple(retval->slot);
146
147         return retval;
148 }
149
150 /*
151  * end_MultiFuncCall
152  * Clean up after init_MultiFuncCall
153  */
154 void
155 end_MultiFuncCall(PG_FUNCTION_ARGS, FuncCallContext *funcctx)
156 {
157         ReturnSetInfo *rsi = (ReturnSetInfo *) fcinfo->resultinfo;
158
159         /* Deregister the shutdown callback */
160         UnregisterExprContextCallback(rsi->econtext,
161                                                                   shutdown_MultiFuncCall,
162                                                                   PointerGetDatum(fcinfo->flinfo));
163
164         /* But use it to do the real work */
165         shutdown_MultiFuncCall(PointerGetDatum(fcinfo->flinfo));
166 }
167
168 /*
169  * shutdown_MultiFuncCall
170  * Shutdown function to clean up after init_MultiFuncCall
171  */
172 static void
173 shutdown_MultiFuncCall(Datum arg)
174 {
175         FmgrInfo   *flinfo = (FmgrInfo *) DatumGetPointer(arg);
176         FuncCallContext *funcctx = (FuncCallContext *) flinfo->fn_extra;
177
178         /* unbind from flinfo */
179         flinfo->fn_extra = NULL;
180
181         /*
182          * Delete context that holds all multi-call data, including the
183          * FuncCallContext itself
184          */
185         MemoryContextDelete(funcctx->multi_call_memory_ctx);
186 }
187
188
189 /*
190  * get_call_result_type
191  *              Given a function's call info record, determine the kind of datatype
192  *              it is supposed to return.  If resultTypeId isn't NULL, *resultTypeId
193  *              receives the actual datatype OID (this is mainly useful for scalar
194  *              result types).  If resultTupleDesc isn't NULL, *resultTupleDesc
195  *              receives a pointer to a TupleDesc when the result is of a composite
196  *              type, or NULL when it's a scalar result.
197  *
198  * One hard case that this handles is resolution of actual rowtypes for
199  * functions returning RECORD (from either the function's OUT parameter
200  * list, or a ReturnSetInfo context node).      TYPEFUNC_RECORD is returned
201  * only when we couldn't resolve the actual rowtype for lack of information.
202  *
203  * The other hard case that this handles is resolution of polymorphism.
204  * We will never return polymorphic pseudotypes (ANYELEMENT etc), either
205  * as a scalar result type or as a component of a rowtype.
206  *
207  * This function is relatively expensive --- in a function returning set,
208  * try to call it only the first time through.
209  */
210 TypeFuncClass
211 get_call_result_type(FunctionCallInfo fcinfo,
212                                          Oid *resultTypeId,
213                                          TupleDesc *resultTupleDesc)
214 {
215         return internal_get_result_type(fcinfo->flinfo->fn_oid,
216                                                                         fcinfo->flinfo->fn_expr,
217                                                                         (ReturnSetInfo *) fcinfo->resultinfo,
218                                                                         resultTypeId,
219                                                                         resultTupleDesc);
220 }
221
222 /*
223  * get_expr_result_type
224  *              As above, but work from a calling expression node tree
225  */
226 TypeFuncClass
227 get_expr_result_type(Node *expr,
228                                          Oid *resultTypeId,
229                                          TupleDesc *resultTupleDesc)
230 {
231         TypeFuncClass result;
232
233         if (expr && IsA(expr, FuncExpr))
234                 result = internal_get_result_type(((FuncExpr *) expr)->funcid,
235                                                                                   expr,
236                                                                                   NULL,
237                                                                                   resultTypeId,
238                                                                                   resultTupleDesc);
239         else if (expr && IsA(expr, OpExpr))
240                 result = internal_get_result_type(get_opcode(((OpExpr *) expr)->opno),
241                                                                                   expr,
242                                                                                   NULL,
243                                                                                   resultTypeId,
244                                                                                   resultTupleDesc);
245         else
246         {
247                 /* handle as a generic expression; no chance to resolve RECORD */
248                 Oid                     typid = exprType(expr);
249
250                 if (resultTypeId)
251                         *resultTypeId = typid;
252                 if (resultTupleDesc)
253                         *resultTupleDesc = NULL;
254                 result = get_type_func_class(typid);
255                 if (result == TYPEFUNC_COMPOSITE && resultTupleDesc)
256                         *resultTupleDesc = lookup_rowtype_tupdesc_copy(typid, -1);
257         }
258
259         return result;
260 }
261
262 /*
263  * get_func_result_type
264  *              As above, but work from a function's OID only
265  *
266  * This will not be able to resolve pure-RECORD results nor polymorphism.
267  */
268 TypeFuncClass
269 get_func_result_type(Oid functionId,
270                                          Oid *resultTypeId,
271                                          TupleDesc *resultTupleDesc)
272 {
273         return internal_get_result_type(functionId,
274                                                                         NULL,
275                                                                         NULL,
276                                                                         resultTypeId,
277                                                                         resultTupleDesc);
278 }
279
280 /*
281  * internal_get_result_type -- workhorse code implementing all the above
282  *
283  * funcid must always be supplied.      call_expr and rsinfo can be NULL if not
284  * available.  We will return TYPEFUNC_RECORD, and store NULL into
285  * *resultTupleDesc, if we cannot deduce the complete result rowtype from
286  * the available information.
287  */
288 static TypeFuncClass
289 internal_get_result_type(Oid funcid,
290                                                  Node *call_expr,
291                                                  ReturnSetInfo *rsinfo,
292                                                  Oid *resultTypeId,
293                                                  TupleDesc *resultTupleDesc)
294 {
295         TypeFuncClass result;
296         HeapTuple       tp;
297         Form_pg_proc procform;
298         Oid                     rettype;
299         TupleDesc       tupdesc;
300
301         /* First fetch the function's pg_proc row to inspect its rettype */
302         tp = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcid));
303         if (!HeapTupleIsValid(tp))
304                 elog(ERROR, "cache lookup failed for function %u", funcid);
305         procform = (Form_pg_proc) GETSTRUCT(tp);
306
307         rettype = procform->prorettype;
308
309         /* Check for OUT parameters defining a RECORD result */
310         tupdesc = build_function_result_tupdesc_t(tp);
311         if (tupdesc)
312         {
313                 /*
314                  * It has OUT parameters, so it's basically like a regular composite
315                  * type, except we have to be able to resolve any polymorphic OUT
316                  * parameters.
317                  */
318                 if (resultTypeId)
319                         *resultTypeId = rettype;
320
321                 if (resolve_polymorphic_tupdesc(tupdesc,
322                                                                                 &procform->proargtypes,
323                                                                                 call_expr))
324                 {
325                         if (tupdesc->tdtypeid == RECORDOID &&
326                                 tupdesc->tdtypmod < 0)
327                                 assign_record_type_typmod(tupdesc);
328                         if (resultTupleDesc)
329                                 *resultTupleDesc = tupdesc;
330                         result = TYPEFUNC_COMPOSITE;
331                 }
332                 else
333                 {
334                         if (resultTupleDesc)
335                                 *resultTupleDesc = NULL;
336                         result = TYPEFUNC_RECORD;
337                 }
338
339                 ReleaseSysCache(tp);
340
341                 return result;
342         }
343
344         /*
345          * If scalar polymorphic result, try to resolve it.
346          */
347         if (IsPolymorphicType(rettype))
348         {
349                 Oid                     newrettype = exprType(call_expr);
350
351                 if (newrettype == InvalidOid)   /* this probably should not happen */
352                         ereport(ERROR,
353                                         (errcode(ERRCODE_DATATYPE_MISMATCH),
354                                          errmsg("could not determine actual result type for function \"%s\" declared to return type %s",
355                                                         NameStr(procform->proname),
356                                                         format_type_be(rettype))));
357                 rettype = newrettype;
358         }
359
360         if (resultTypeId)
361                 *resultTypeId = rettype;
362         if (resultTupleDesc)
363                 *resultTupleDesc = NULL;        /* default result */
364
365         /* Classify the result type */
366         result = get_type_func_class(rettype);
367         switch (result)
368         {
369                 case TYPEFUNC_COMPOSITE:
370                         if (resultTupleDesc)
371                                 *resultTupleDesc = lookup_rowtype_tupdesc_copy(rettype, -1);
372                         /* Named composite types can't have any polymorphic columns */
373                         break;
374                 case TYPEFUNC_SCALAR:
375                         break;
376                 case TYPEFUNC_RECORD:
377                         /* We must get the tupledesc from call context */
378                         if (rsinfo && IsA(rsinfo, ReturnSetInfo) &&
379                                 rsinfo->expectedDesc != NULL)
380                         {
381                                 result = TYPEFUNC_COMPOSITE;
382                                 if (resultTupleDesc)
383                                         *resultTupleDesc = rsinfo->expectedDesc;
384                                 /* Assume no polymorphic columns here, either */
385                         }
386                         break;
387                 default:
388                         break;
389         }
390
391         ReleaseSysCache(tp);
392
393         return result;
394 }
395
396 /*
397  * Given the result tuple descriptor for a function with OUT parameters,
398  * replace any polymorphic columns (ANYELEMENT etc) with correct data types
399  * deduced from the input arguments. Returns TRUE if able to deduce all types,
400  * FALSE if not.
401  */
402 static bool
403 resolve_polymorphic_tupdesc(TupleDesc tupdesc, oidvector *declared_args,
404                                                         Node *call_expr)
405 {
406         int                     natts = tupdesc->natts;
407         int                     nargs = declared_args->dim1;
408         bool            have_anyelement_result = false;
409         bool            have_anyarray_result = false;
410         bool            have_anyrange_result = false;
411         bool            have_anynonarray = false;
412         bool            have_anyenum = false;
413         Oid                     anyelement_type = InvalidOid;
414         Oid                     anyarray_type = InvalidOid;
415         Oid                     anyrange_type = InvalidOid;
416         Oid                     anycollation = InvalidOid;
417         int                     i;
418
419         /* See if there are any polymorphic outputs; quick out if not */
420         for (i = 0; i < natts; i++)
421         {
422                 switch (tupdesc->attrs[i]->atttypid)
423                 {
424                         case ANYELEMENTOID:
425                                 have_anyelement_result = true;
426                                 break;
427                         case ANYARRAYOID:
428                                 have_anyarray_result = true;
429                                 break;
430                         case ANYNONARRAYOID:
431                                 have_anyelement_result = true;
432                                 have_anynonarray = true;
433                                 break;
434                         case ANYENUMOID:
435                                 have_anyelement_result = true;
436                                 have_anyenum = true;
437                                 break;
438                         case ANYRANGEOID:
439                                 have_anyrange_result = true;
440                                 break;
441                         default:
442                                 break;
443                 }
444         }
445         if (!have_anyelement_result && !have_anyarray_result &&
446                 !have_anyrange_result)
447                 return true;
448
449         /*
450          * Otherwise, extract actual datatype(s) from input arguments.  (We assume
451          * the parser already validated consistency of the arguments.)
452          */
453         if (!call_expr)
454                 return false;                   /* no hope */
455
456         for (i = 0; i < nargs; i++)
457         {
458                 switch (declared_args->values[i])
459                 {
460                         case ANYELEMENTOID:
461                         case ANYNONARRAYOID:
462                         case ANYENUMOID:
463                                 if (!OidIsValid(anyelement_type))
464                                         anyelement_type = get_call_expr_argtype(call_expr, i);
465                                 break;
466                         case ANYARRAYOID:
467                                 if (!OidIsValid(anyarray_type))
468                                         anyarray_type = get_call_expr_argtype(call_expr, i);
469                                 break;
470                         case ANYRANGEOID:
471                                 if (!OidIsValid(anyrange_type))
472                                         anyrange_type = get_call_expr_argtype(call_expr, i);
473                                 break;
474                         default:
475                                 break;
476                 }
477         }
478
479         /* If nothing found, parser messed up */
480         if (!OidIsValid(anyelement_type) && !OidIsValid(anyarray_type) &&
481                 !OidIsValid(anyrange_type))
482                 return false;
483
484         /* If needed, deduce one polymorphic type from others */
485         if (have_anyelement_result && !OidIsValid(anyelement_type))
486         {
487                 if (OidIsValid(anyarray_type))
488                         anyelement_type = resolve_generic_type(ANYELEMENTOID,
489                                                                                                    anyarray_type,
490                                                                                                    ANYARRAYOID);
491                 if (OidIsValid(anyrange_type))
492                 {
493                         Oid                     subtype = resolve_generic_type(ANYELEMENTOID,
494                                                                                                            anyrange_type,
495                                                                                                            ANYRANGEOID);
496
497                         /* check for inconsistent array and range results */
498                         if (OidIsValid(anyelement_type) && anyelement_type != subtype)
499                                 return false;
500                         anyelement_type = subtype;
501                 }
502         }
503
504         if (have_anyarray_result && !OidIsValid(anyarray_type))
505                 anyarray_type = resolve_generic_type(ANYARRAYOID,
506                                                                                          anyelement_type,
507                                                                                          ANYELEMENTOID);
508
509         /*
510          * We can't deduce a range type from other polymorphic inputs, because
511          * there may be multiple range types for the same subtype.
512          */
513         if (have_anyrange_result && !OidIsValid(anyrange_type))
514                 return false;
515
516         /* Enforce ANYNONARRAY if needed */
517         if (have_anynonarray && type_is_array(anyelement_type))
518                 return false;
519
520         /* Enforce ANYENUM if needed */
521         if (have_anyenum && !type_is_enum(anyelement_type))
522                 return false;
523
524         /*
525          * Identify the collation to use for polymorphic OUT parameters. (It'll
526          * necessarily be the same for both anyelement and anyarray.)  Note that
527          * range types are not collatable, so any possible internal collation of a
528          * range type is not considered here.
529          */
530         if (OidIsValid(anyelement_type))
531                 anycollation = get_typcollation(anyelement_type);
532         else if (OidIsValid(anyarray_type))
533                 anycollation = get_typcollation(anyarray_type);
534
535         if (OidIsValid(anycollation))
536         {
537                 /*
538                  * The types are collatable, so consider whether to use a nondefault
539                  * collation.  We do so if we can identify the input collation used
540                  * for the function.
541                  */
542                 Oid                     inputcollation = exprInputCollation(call_expr);
543
544                 if (OidIsValid(inputcollation))
545                         anycollation = inputcollation;
546         }
547
548         /* And finally replace the tuple column types as needed */
549         for (i = 0; i < natts; i++)
550         {
551                 switch (tupdesc->attrs[i]->atttypid)
552                 {
553                         case ANYELEMENTOID:
554                         case ANYNONARRAYOID:
555                         case ANYENUMOID:
556                                 TupleDescInitEntry(tupdesc, i + 1,
557                                                                    NameStr(tupdesc->attrs[i]->attname),
558                                                                    anyelement_type,
559                                                                    -1,
560                                                                    0);
561                                 TupleDescInitEntryCollation(tupdesc, i + 1, anycollation);
562                                 break;
563                         case ANYARRAYOID:
564                                 TupleDescInitEntry(tupdesc, i + 1,
565                                                                    NameStr(tupdesc->attrs[i]->attname),
566                                                                    anyarray_type,
567                                                                    -1,
568                                                                    0);
569                                 TupleDescInitEntryCollation(tupdesc, i + 1, anycollation);
570                                 break;
571                         case ANYRANGEOID:
572                                 TupleDescInitEntry(tupdesc, i + 1,
573                                                                    NameStr(tupdesc->attrs[i]->attname),
574                                                                    anyrange_type,
575                                                                    -1,
576                                                                    0);
577                                 /* no collation should be attached to a range type */
578                                 break;
579                         default:
580                                 break;
581                 }
582         }
583
584         return true;
585 }
586
587 /*
588  * Given the declared argument types and modes for a function, replace any
589  * polymorphic types (ANYELEMENT etc) with correct data types deduced from the
590  * input arguments.  Returns TRUE if able to deduce all types, FALSE if not.
591  * This is the same logic as resolve_polymorphic_tupdesc, but with a different
592  * argument representation.
593  *
594  * argmodes may be NULL, in which case all arguments are assumed to be IN mode.
595  */
596 bool
597 resolve_polymorphic_argtypes(int numargs, Oid *argtypes, char *argmodes,
598                                                          Node *call_expr)
599 {
600         bool            have_anyelement_result = false;
601         bool            have_anyarray_result = false;
602         bool            have_anyrange_result = false;
603         Oid                     anyelement_type = InvalidOid;
604         Oid                     anyarray_type = InvalidOid;
605         Oid                     anyrange_type = InvalidOid;
606         int                     inargno;
607         int                     i;
608
609         /* First pass: resolve polymorphic inputs, check for outputs */
610         inargno = 0;
611         for (i = 0; i < numargs; i++)
612         {
613                 char            argmode = argmodes ? argmodes[i] : PROARGMODE_IN;
614
615                 switch (argtypes[i])
616                 {
617                         case ANYELEMENTOID:
618                         case ANYNONARRAYOID:
619                         case ANYENUMOID:
620                                 if (argmode == PROARGMODE_OUT || argmode == PROARGMODE_TABLE)
621                                         have_anyelement_result = true;
622                                 else
623                                 {
624                                         if (!OidIsValid(anyelement_type))
625                                         {
626                                                 anyelement_type = get_call_expr_argtype(call_expr,
627                                                                                                                                 inargno);
628                                                 if (!OidIsValid(anyelement_type))
629                                                         return false;
630                                         }
631                                         argtypes[i] = anyelement_type;
632                                 }
633                                 break;
634                         case ANYARRAYOID:
635                                 if (argmode == PROARGMODE_OUT || argmode == PROARGMODE_TABLE)
636                                         have_anyarray_result = true;
637                                 else
638                                 {
639                                         if (!OidIsValid(anyarray_type))
640                                         {
641                                                 anyarray_type = get_call_expr_argtype(call_expr,
642                                                                                                                           inargno);
643                                                 if (!OidIsValid(anyarray_type))
644                                                         return false;
645                                         }
646                                         argtypes[i] = anyarray_type;
647                                 }
648                                 break;
649                         case ANYRANGEOID:
650                                 if (argmode == PROARGMODE_OUT || argmode == PROARGMODE_TABLE)
651                                         have_anyrange_result = true;
652                                 else
653                                 {
654                                         if (!OidIsValid(anyrange_type))
655                                         {
656                                                 anyrange_type = get_call_expr_argtype(call_expr,
657                                                                                                                           inargno);
658                                                 if (!OidIsValid(anyrange_type))
659                                                         return false;
660                                         }
661                                         argtypes[i] = anyrange_type;
662                                 }
663                                 break;
664                         default:
665                                 break;
666                 }
667                 if (argmode != PROARGMODE_OUT && argmode != PROARGMODE_TABLE)
668                         inargno++;
669         }
670
671         /* Done? */
672         if (!have_anyelement_result && !have_anyarray_result &&
673                 !have_anyrange_result)
674                 return true;
675
676         /* If no input polymorphics, parser messed up */
677         if (!OidIsValid(anyelement_type) && !OidIsValid(anyarray_type) &&
678                 !OidIsValid(anyrange_type))
679                 return false;
680
681         /* If needed, deduce one polymorphic type from others */
682         if (have_anyelement_result && !OidIsValid(anyelement_type))
683         {
684                 if (OidIsValid(anyarray_type))
685                         anyelement_type = resolve_generic_type(ANYELEMENTOID,
686                                                                                                    anyarray_type,
687                                                                                                    ANYARRAYOID);
688                 if (OidIsValid(anyrange_type))
689                 {
690                         Oid                     subtype = resolve_generic_type(ANYELEMENTOID,
691                                                                                                            anyrange_type,
692                                                                                                            ANYRANGEOID);
693
694                         /* check for inconsistent array and range results */
695                         if (OidIsValid(anyelement_type) && anyelement_type != subtype)
696                                 return false;
697                         anyelement_type = subtype;
698                 }
699         }
700
701         if (have_anyarray_result && !OidIsValid(anyarray_type))
702                 anyarray_type = resolve_generic_type(ANYARRAYOID,
703                                                                                          anyelement_type,
704                                                                                          ANYELEMENTOID);
705
706         /*
707          * We can't deduce a range type from other polymorphic inputs, because
708          * there may be multiple range types for the same subtype.
709          */
710         if (have_anyrange_result && !OidIsValid(anyrange_type))
711                 return false;
712
713         /* XXX do we need to enforce ANYNONARRAY or ANYENUM here?  I think not */
714
715         /* And finally replace the output column types as needed */
716         for (i = 0; i < numargs; i++)
717         {
718                 switch (argtypes[i])
719                 {
720                         case ANYELEMENTOID:
721                         case ANYNONARRAYOID:
722                         case ANYENUMOID:
723                                 argtypes[i] = anyelement_type;
724                                 break;
725                         case ANYARRAYOID:
726                                 argtypes[i] = anyarray_type;
727                                 break;
728                         case ANYRANGEOID:
729                                 argtypes[i] = anyrange_type;
730                                 break;
731                         default:
732                                 break;
733                 }
734         }
735
736         return true;
737 }
738
739 /*
740  * get_type_func_class
741  *              Given the type OID, obtain its TYPEFUNC classification.
742  *
743  * This is intended to centralize a bunch of formerly ad-hoc code for
744  * classifying types.  The categories used here are useful for deciding
745  * how to handle functions returning the datatype.
746  */
747 static TypeFuncClass
748 get_type_func_class(Oid typid)
749 {
750         switch (get_typtype(typid))
751         {
752                 case TYPTYPE_COMPOSITE:
753                         return TYPEFUNC_COMPOSITE;
754                 case TYPTYPE_BASE:
755                 case TYPTYPE_DOMAIN:
756                 case TYPTYPE_ENUM:
757                 case TYPTYPE_RANGE:
758                         return TYPEFUNC_SCALAR;
759                 case TYPTYPE_PSEUDO:
760                         if (typid == RECORDOID)
761                                 return TYPEFUNC_RECORD;
762
763                         /*
764                          * We treat VOID and CSTRING as legitimate scalar datatypes,
765                          * mostly for the convenience of the JDBC driver (which wants to
766                          * be able to do "SELECT * FROM foo()" for all legitimately
767                          * user-callable functions).
768                          */
769                         if (typid == VOIDOID || typid == CSTRINGOID)
770                                 return TYPEFUNC_SCALAR;
771                         return TYPEFUNC_OTHER;
772         }
773         /* shouldn't get here, probably */
774         return TYPEFUNC_OTHER;
775 }
776
777
778 /*
779  * get_func_arg_info
780  *
781  * Fetch info about the argument types, names, and IN/OUT modes from the
782  * pg_proc tuple.  Return value is the total number of arguments.
783  * Other results are palloc'd.  *p_argtypes is always filled in, but
784  * *p_argnames and *p_argmodes will be set NULL in the default cases
785  * (no names, and all IN arguments, respectively).
786  *
787  * Note that this function simply fetches what is in the pg_proc tuple;
788  * it doesn't do any interpretation of polymorphic types.
789  */
790 int
791 get_func_arg_info(HeapTuple procTup,
792                                   Oid **p_argtypes, char ***p_argnames, char **p_argmodes)
793 {
794         Form_pg_proc procStruct = (Form_pg_proc) GETSTRUCT(procTup);
795         Datum           proallargtypes;
796         Datum           proargmodes;
797         Datum           proargnames;
798         bool            isNull;
799         ArrayType  *arr;
800         int                     numargs;
801         Datum      *elems;
802         int                     nelems;
803         int                     i;
804
805         /* First discover the total number of parameters and get their types */
806         proallargtypes = SysCacheGetAttr(PROCOID, procTup,
807                                                                          Anum_pg_proc_proallargtypes,
808                                                                          &isNull);
809         if (!isNull)
810         {
811                 /*
812                  * We expect the arrays to be 1-D arrays of the right types; verify
813                  * that.  For the OID and char arrays, we don't need to use
814                  * deconstruct_array() since the array data is just going to look like
815                  * a C array of values.
816                  */
817                 arr = DatumGetArrayTypeP(proallargtypes);               /* ensure not toasted */
818                 numargs = ARR_DIMS(arr)[0];
819                 if (ARR_NDIM(arr) != 1 ||
820                         numargs < 0 ||
821                         ARR_HASNULL(arr) ||
822                         ARR_ELEMTYPE(arr) != OIDOID)
823                         elog(ERROR, "proallargtypes is not a 1-D Oid array");
824                 Assert(numargs >= procStruct->pronargs);
825                 *p_argtypes = (Oid *) palloc(numargs * sizeof(Oid));
826                 memcpy(*p_argtypes, ARR_DATA_PTR(arr),
827                            numargs * sizeof(Oid));
828         }
829         else
830         {
831                 /* If no proallargtypes, use proargtypes */
832                 numargs = procStruct->proargtypes.dim1;
833                 Assert(numargs == procStruct->pronargs);
834                 *p_argtypes = (Oid *) palloc(numargs * sizeof(Oid));
835                 memcpy(*p_argtypes, procStruct->proargtypes.values,
836                            numargs * sizeof(Oid));
837         }
838
839         /* Get argument names, if available */
840         proargnames = SysCacheGetAttr(PROCOID, procTup,
841                                                                   Anum_pg_proc_proargnames,
842                                                                   &isNull);
843         if (isNull)
844                 *p_argnames = NULL;
845         else
846         {
847                 deconstruct_array(DatumGetArrayTypeP(proargnames),
848                                                   TEXTOID, -1, false, 'i',
849                                                   &elems, NULL, &nelems);
850                 if (nelems != numargs)  /* should not happen */
851                         elog(ERROR, "proargnames must have the same number of elements as the function has arguments");
852                 *p_argnames = (char **) palloc(sizeof(char *) * numargs);
853                 for (i = 0; i < numargs; i++)
854                         (*p_argnames)[i] = TextDatumGetCString(elems[i]);
855         }
856
857         /* Get argument modes, if available */
858         proargmodes = SysCacheGetAttr(PROCOID, procTup,
859                                                                   Anum_pg_proc_proargmodes,
860                                                                   &isNull);
861         if (isNull)
862                 *p_argmodes = NULL;
863         else
864         {
865                 arr = DatumGetArrayTypeP(proargmodes);  /* ensure not toasted */
866                 if (ARR_NDIM(arr) != 1 ||
867                         ARR_DIMS(arr)[0] != numargs ||
868                         ARR_HASNULL(arr) ||
869                         ARR_ELEMTYPE(arr) != CHAROID)
870                         elog(ERROR, "proargmodes is not a 1-D char array");
871                 *p_argmodes = (char *) palloc(numargs * sizeof(char));
872                 memcpy(*p_argmodes, ARR_DATA_PTR(arr),
873                            numargs * sizeof(char));
874         }
875
876         return numargs;
877 }
878
879
880 /*
881  * get_func_input_arg_names
882  *
883  * Extract the names of input arguments only, given a function's
884  * proargnames and proargmodes entries in Datum form.
885  *
886  * Returns the number of input arguments, which is the length of the
887  * palloc'd array returned to *arg_names.  Entries for unnamed args
888  * are set to NULL.  You don't get anything if proargnames is NULL.
889  */
890 int
891 get_func_input_arg_names(Datum proargnames, Datum proargmodes,
892                                                  char ***arg_names)
893 {
894         ArrayType  *arr;
895         int                     numargs;
896         Datum      *argnames;
897         char       *argmodes;
898         char      **inargnames;
899         int                     numinargs;
900         int                     i;
901
902         /* Do nothing if null proargnames */
903         if (proargnames == PointerGetDatum(NULL))
904         {
905                 *arg_names = NULL;
906                 return 0;
907         }
908
909         /*
910          * We expect the arrays to be 1-D arrays of the right types; verify that.
911          * For proargmodes, we don't need to use deconstruct_array() since the
912          * array data is just going to look like a C array of values.
913          */
914         arr = DatumGetArrayTypeP(proargnames);          /* ensure not toasted */
915         if (ARR_NDIM(arr) != 1 ||
916                 ARR_HASNULL(arr) ||
917                 ARR_ELEMTYPE(arr) != TEXTOID)
918                 elog(ERROR, "proargnames is not a 1-D text array");
919         deconstruct_array(arr, TEXTOID, -1, false, 'i',
920                                           &argnames, NULL, &numargs);
921         if (proargmodes != PointerGetDatum(NULL))
922         {
923                 arr = DatumGetArrayTypeP(proargmodes);  /* ensure not toasted */
924                 if (ARR_NDIM(arr) != 1 ||
925                         ARR_DIMS(arr)[0] != numargs ||
926                         ARR_HASNULL(arr) ||
927                         ARR_ELEMTYPE(arr) != CHAROID)
928                         elog(ERROR, "proargmodes is not a 1-D char array");
929                 argmodes = (char *) ARR_DATA_PTR(arr);
930         }
931         else
932                 argmodes = NULL;
933
934         /* zero elements probably shouldn't happen, but handle it gracefully */
935         if (numargs <= 0)
936         {
937                 *arg_names = NULL;
938                 return 0;
939         }
940
941         /* extract input-argument names */
942         inargnames = (char **) palloc(numargs * sizeof(char *));
943         numinargs = 0;
944         for (i = 0; i < numargs; i++)
945         {
946                 if (argmodes == NULL ||
947                         argmodes[i] == PROARGMODE_IN ||
948                         argmodes[i] == PROARGMODE_INOUT ||
949                         argmodes[i] == PROARGMODE_VARIADIC)
950                 {
951                         char       *pname = TextDatumGetCString(argnames[i]);
952
953                         if (pname[0] != '\0')
954                                 inargnames[numinargs] = pname;
955                         else
956                                 inargnames[numinargs] = NULL;
957                         numinargs++;
958                 }
959         }
960
961         *arg_names = inargnames;
962         return numinargs;
963 }
964
965
966 /*
967  * get_func_result_name
968  *
969  * If the function has exactly one output parameter, and that parameter
970  * is named, return the name (as a palloc'd string).  Else return NULL.
971  *
972  * This is used to determine the default output column name for functions
973  * returning scalar types.
974  */
975 char *
976 get_func_result_name(Oid functionId)
977 {
978         char       *result;
979         HeapTuple       procTuple;
980         Datum           proargmodes;
981         Datum           proargnames;
982         bool            isnull;
983         ArrayType  *arr;
984         int                     numargs;
985         char       *argmodes;
986         Datum      *argnames;
987         int                     numoutargs;
988         int                     nargnames;
989         int                     i;
990
991         /* First fetch the function's pg_proc row */
992         procTuple = SearchSysCache1(PROCOID, ObjectIdGetDatum(functionId));
993         if (!HeapTupleIsValid(procTuple))
994                 elog(ERROR, "cache lookup failed for function %u", functionId);
995
996         /* If there are no named OUT parameters, return NULL */
997         if (heap_attisnull(procTuple, Anum_pg_proc_proargmodes) ||
998                 heap_attisnull(procTuple, Anum_pg_proc_proargnames))
999                 result = NULL;
1000         else
1001         {
1002                 /* Get the data out of the tuple */
1003                 proargmodes = SysCacheGetAttr(PROCOID, procTuple,
1004                                                                           Anum_pg_proc_proargmodes,
1005                                                                           &isnull);
1006                 Assert(!isnull);
1007                 proargnames = SysCacheGetAttr(PROCOID, procTuple,
1008                                                                           Anum_pg_proc_proargnames,
1009                                                                           &isnull);
1010                 Assert(!isnull);
1011
1012                 /*
1013                  * We expect the arrays to be 1-D arrays of the right types; verify
1014                  * that.  For the char array, we don't need to use deconstruct_array()
1015                  * since the array data is just going to look like a C array of
1016                  * values.
1017                  */
1018                 arr = DatumGetArrayTypeP(proargmodes);  /* ensure not toasted */
1019                 numargs = ARR_DIMS(arr)[0];
1020                 if (ARR_NDIM(arr) != 1 ||
1021                         numargs < 0 ||
1022                         ARR_HASNULL(arr) ||
1023                         ARR_ELEMTYPE(arr) != CHAROID)
1024                         elog(ERROR, "proargmodes is not a 1-D char array");
1025                 argmodes = (char *) ARR_DATA_PTR(arr);
1026                 arr = DatumGetArrayTypeP(proargnames);  /* ensure not toasted */
1027                 if (ARR_NDIM(arr) != 1 ||
1028                         ARR_DIMS(arr)[0] != numargs ||
1029                         ARR_HASNULL(arr) ||
1030                         ARR_ELEMTYPE(arr) != TEXTOID)
1031                         elog(ERROR, "proargnames is not a 1-D text array");
1032                 deconstruct_array(arr, TEXTOID, -1, false, 'i',
1033                                                   &argnames, NULL, &nargnames);
1034                 Assert(nargnames == numargs);
1035
1036                 /* scan for output argument(s) */
1037                 result = NULL;
1038                 numoutargs = 0;
1039                 for (i = 0; i < numargs; i++)
1040                 {
1041                         if (argmodes[i] == PROARGMODE_IN ||
1042                                 argmodes[i] == PROARGMODE_VARIADIC)
1043                                 continue;
1044                         Assert(argmodes[i] == PROARGMODE_OUT ||
1045                                    argmodes[i] == PROARGMODE_INOUT ||
1046                                    argmodes[i] == PROARGMODE_TABLE);
1047                         if (++numoutargs > 1)
1048                         {
1049                                 /* multiple out args, so forget it */
1050                                 result = NULL;
1051                                 break;
1052                         }
1053                         result = TextDatumGetCString(argnames[i]);
1054                         if (result == NULL || result[0] == '\0')
1055                         {
1056                                 /* Parameter is not named, so forget it */
1057                                 result = NULL;
1058                                 break;
1059                         }
1060                 }
1061         }
1062
1063         ReleaseSysCache(procTuple);
1064
1065         return result;
1066 }
1067
1068
1069 /*
1070  * build_function_result_tupdesc_t
1071  *
1072  * Given a pg_proc row for a function, return a tuple descriptor for the
1073  * result rowtype, or NULL if the function does not have OUT parameters.
1074  *
1075  * Note that this does not handle resolution of polymorphic types;
1076  * that is deliberate.
1077  */
1078 TupleDesc
1079 build_function_result_tupdesc_t(HeapTuple procTuple)
1080 {
1081         Form_pg_proc procform = (Form_pg_proc) GETSTRUCT(procTuple);
1082         Datum           proallargtypes;
1083         Datum           proargmodes;
1084         Datum           proargnames;
1085         bool            isnull;
1086
1087         /* Return NULL if the function isn't declared to return RECORD */
1088         if (procform->prorettype != RECORDOID)
1089                 return NULL;
1090
1091         /* If there are no OUT parameters, return NULL */
1092         if (heap_attisnull(procTuple, Anum_pg_proc_proallargtypes) ||
1093                 heap_attisnull(procTuple, Anum_pg_proc_proargmodes))
1094                 return NULL;
1095
1096         /* Get the data out of the tuple */
1097         proallargtypes = SysCacheGetAttr(PROCOID, procTuple,
1098                                                                          Anum_pg_proc_proallargtypes,
1099                                                                          &isnull);
1100         Assert(!isnull);
1101         proargmodes = SysCacheGetAttr(PROCOID, procTuple,
1102                                                                   Anum_pg_proc_proargmodes,
1103                                                                   &isnull);
1104         Assert(!isnull);
1105         proargnames = SysCacheGetAttr(PROCOID, procTuple,
1106                                                                   Anum_pg_proc_proargnames,
1107                                                                   &isnull);
1108         if (isnull)
1109                 proargnames = PointerGetDatum(NULL);    /* just to be sure */
1110
1111         return build_function_result_tupdesc_d(proallargtypes,
1112                                                                                    proargmodes,
1113                                                                                    proargnames);
1114 }
1115
1116 /*
1117  * build_function_result_tupdesc_d
1118  *
1119  * Build a RECORD function's tupledesc from the pg_proc proallargtypes,
1120  * proargmodes, and proargnames arrays.  This is split out for the
1121  * convenience of ProcedureCreate, which needs to be able to compute the
1122  * tupledesc before actually creating the function.
1123  *
1124  * Returns NULL if there are not at least two OUT or INOUT arguments.
1125  */
1126 TupleDesc
1127 build_function_result_tupdesc_d(Datum proallargtypes,
1128                                                                 Datum proargmodes,
1129                                                                 Datum proargnames)
1130 {
1131         TupleDesc       desc;
1132         ArrayType  *arr;
1133         int                     numargs;
1134         Oid                *argtypes;
1135         char       *argmodes;
1136         Datum      *argnames = NULL;
1137         Oid                *outargtypes;
1138         char      **outargnames;
1139         int                     numoutargs;
1140         int                     nargnames;
1141         int                     i;
1142
1143         /* Can't have output args if columns are null */
1144         if (proallargtypes == PointerGetDatum(NULL) ||
1145                 proargmodes == PointerGetDatum(NULL))
1146                 return NULL;
1147
1148         /*
1149          * We expect the arrays to be 1-D arrays of the right types; verify that.
1150          * For the OID and char arrays, we don't need to use deconstruct_array()
1151          * since the array data is just going to look like a C array of values.
1152          */
1153         arr = DatumGetArrayTypeP(proallargtypes);       /* ensure not toasted */
1154         numargs = ARR_DIMS(arr)[0];
1155         if (ARR_NDIM(arr) != 1 ||
1156                 numargs < 0 ||
1157                 ARR_HASNULL(arr) ||
1158                 ARR_ELEMTYPE(arr) != OIDOID)
1159                 elog(ERROR, "proallargtypes is not a 1-D Oid array");
1160         argtypes = (Oid *) ARR_DATA_PTR(arr);
1161         arr = DatumGetArrayTypeP(proargmodes);          /* ensure not toasted */
1162         if (ARR_NDIM(arr) != 1 ||
1163                 ARR_DIMS(arr)[0] != numargs ||
1164                 ARR_HASNULL(arr) ||
1165                 ARR_ELEMTYPE(arr) != CHAROID)
1166                 elog(ERROR, "proargmodes is not a 1-D char array");
1167         argmodes = (char *) ARR_DATA_PTR(arr);
1168         if (proargnames != PointerGetDatum(NULL))
1169         {
1170                 arr = DatumGetArrayTypeP(proargnames);  /* ensure not toasted */
1171                 if (ARR_NDIM(arr) != 1 ||
1172                         ARR_DIMS(arr)[0] != numargs ||
1173                         ARR_HASNULL(arr) ||
1174                         ARR_ELEMTYPE(arr) != TEXTOID)
1175                         elog(ERROR, "proargnames is not a 1-D text array");
1176                 deconstruct_array(arr, TEXTOID, -1, false, 'i',
1177                                                   &argnames, NULL, &nargnames);
1178                 Assert(nargnames == numargs);
1179         }
1180
1181         /* zero elements probably shouldn't happen, but handle it gracefully */
1182         if (numargs <= 0)
1183                 return NULL;
1184
1185         /* extract output-argument types and names */
1186         outargtypes = (Oid *) palloc(numargs * sizeof(Oid));
1187         outargnames = (char **) palloc(numargs * sizeof(char *));
1188         numoutargs = 0;
1189         for (i = 0; i < numargs; i++)
1190         {
1191                 char       *pname;
1192
1193                 if (argmodes[i] == PROARGMODE_IN ||
1194                         argmodes[i] == PROARGMODE_VARIADIC)
1195                         continue;
1196                 Assert(argmodes[i] == PROARGMODE_OUT ||
1197                            argmodes[i] == PROARGMODE_INOUT ||
1198                            argmodes[i] == PROARGMODE_TABLE);
1199                 outargtypes[numoutargs] = argtypes[i];
1200                 if (argnames)
1201                         pname = TextDatumGetCString(argnames[i]);
1202                 else
1203                         pname = NULL;
1204                 if (pname == NULL || pname[0] == '\0')
1205                 {
1206                         /* Parameter is not named, so gin up a column name */
1207                         pname = (char *) palloc(32);
1208                         snprintf(pname, 32, "column%d", numoutargs + 1);
1209                 }
1210                 outargnames[numoutargs] = pname;
1211                 numoutargs++;
1212         }
1213
1214         /*
1215          * If there is no output argument, or only one, the function does not
1216          * return tuples.
1217          */
1218         if (numoutargs < 2)
1219                 return NULL;
1220
1221         desc = CreateTemplateTupleDesc(numoutargs, false);
1222         for (i = 0; i < numoutargs; i++)
1223         {
1224                 TupleDescInitEntry(desc, i + 1,
1225                                                    outargnames[i],
1226                                                    outargtypes[i],
1227                                                    -1,
1228                                                    0);
1229         }
1230
1231         return desc;
1232 }
1233
1234
1235 /*
1236  * RelationNameGetTupleDesc
1237  *
1238  * Given a (possibly qualified) relation name, build a TupleDesc.
1239  *
1240  * Note: while this works as advertised, it's seldom the best way to
1241  * build a tupdesc for a function's result type.  It's kept around
1242  * only for backwards compatibility with existing user-written code.
1243  */
1244 TupleDesc
1245 RelationNameGetTupleDesc(const char *relname)
1246 {
1247         RangeVar   *relvar;
1248         Relation        rel;
1249         TupleDesc       tupdesc;
1250         List       *relname_list;
1251
1252         /* Open relation and copy the tuple description */
1253         relname_list = stringToQualifiedNameList(relname);
1254         relvar = makeRangeVarFromNameList(relname_list);
1255         rel = relation_openrv(relvar, AccessShareLock);
1256         tupdesc = CreateTupleDescCopy(RelationGetDescr(rel));
1257         relation_close(rel, AccessShareLock);
1258
1259         return tupdesc;
1260 }
1261
1262 /*
1263  * TypeGetTupleDesc
1264  *
1265  * Given a type Oid, build a TupleDesc.  (In most cases you should be
1266  * using get_call_result_type or one of its siblings instead of this
1267  * routine, so that you can handle OUT parameters, RECORD result type,
1268  * and polymorphic results.)
1269  *
1270  * If the type is composite, *and* a colaliases List is provided, *and*
1271  * the List is of natts length, use the aliases instead of the relation
1272  * attnames.  (NB: this usage is deprecated since it may result in
1273  * creation of unnecessary transient record types.)
1274  *
1275  * If the type is a base type, a single item alias List is required.
1276  */
1277 TupleDesc
1278 TypeGetTupleDesc(Oid typeoid, List *colaliases)
1279 {
1280         TypeFuncClass functypclass = get_type_func_class(typeoid);
1281         TupleDesc       tupdesc = NULL;
1282
1283         /*
1284          * Build a suitable tupledesc representing the output rows
1285          */
1286         if (functypclass == TYPEFUNC_COMPOSITE)
1287         {
1288                 /* Composite data type, e.g. a table's row type */
1289                 tupdesc = lookup_rowtype_tupdesc_copy(typeoid, -1);
1290
1291                 if (colaliases != NIL)
1292                 {
1293                         int                     natts = tupdesc->natts;
1294                         int                     varattno;
1295
1296                         /* does the list length match the number of attributes? */
1297                         if (list_length(colaliases) != natts)
1298                                 ereport(ERROR,
1299                                                 (errcode(ERRCODE_DATATYPE_MISMATCH),
1300                                                  errmsg("number of aliases does not match number of columns")));
1301
1302                         /* OK, use the aliases instead */
1303                         for (varattno = 0; varattno < natts; varattno++)
1304                         {
1305                                 char       *label = strVal(list_nth(colaliases, varattno));
1306
1307                                 if (label != NULL)
1308                                         namestrcpy(&(tupdesc->attrs[varattno]->attname), label);
1309                         }
1310
1311                         /* The tuple type is now an anonymous record type */
1312                         tupdesc->tdtypeid = RECORDOID;
1313                         tupdesc->tdtypmod = -1;
1314                 }
1315         }
1316         else if (functypclass == TYPEFUNC_SCALAR)
1317         {
1318                 /* Base data type, i.e. scalar */
1319                 char       *attname;
1320
1321                 /* the alias list is required for base types */
1322                 if (colaliases == NIL)
1323                         ereport(ERROR,
1324                                         (errcode(ERRCODE_DATATYPE_MISMATCH),
1325                                          errmsg("no column alias was provided")));
1326
1327                 /* the alias list length must be 1 */
1328                 if (list_length(colaliases) != 1)
1329                         ereport(ERROR,
1330                                         (errcode(ERRCODE_DATATYPE_MISMATCH),
1331                           errmsg("number of aliases does not match number of columns")));
1332
1333                 /* OK, get the column alias */
1334                 attname = strVal(linitial(colaliases));
1335
1336                 tupdesc = CreateTemplateTupleDesc(1, false);
1337                 TupleDescInitEntry(tupdesc,
1338                                                    (AttrNumber) 1,
1339                                                    attname,
1340                                                    typeoid,
1341                                                    -1,
1342                                                    0);
1343         }
1344         else if (functypclass == TYPEFUNC_RECORD)
1345         {
1346                 /* XXX can't support this because typmod wasn't passed in ... */
1347                 ereport(ERROR,
1348                                 (errcode(ERRCODE_DATATYPE_MISMATCH),
1349                                  errmsg("could not determine row description for function returning record")));
1350         }
1351         else
1352         {
1353                 /* crummy error message, but parser should have caught this */
1354                 elog(ERROR, "function in FROM has unsupported return type");
1355         }
1356
1357         return tupdesc;
1358 }