]> granicus.if.org Git - postgresql/blob - src/backend/utils/fmgr/funcapi.c
pgindent run for 9.0
[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-2010, PostgreSQL Global Development Group
8  *
9  * IDENTIFICATION
10  *        $PostgreSQL: pgsql/src/backend/utils/fmgr/funcapi.c,v 1.49 2010/02/26 02:01:13 momjian Exp $
11  *
12  *-------------------------------------------------------------------------
13  */
14 #include "postgres.h"
15
16 #include "access/heapam.h"
17 #include "catalog/namespace.h"
18 #include "catalog/pg_proc.h"
19 #include "catalog/pg_type.h"
20 #include "funcapi.h"
21 #include "nodes/nodeFuncs.h"
22 #include "parser/parse_coerce.h"
23 #include "utils/array.h"
24 #include "utils/builtins.h"
25 #include "utils/lsyscache.h"
26 #include "utils/memutils.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_anynonarray = false;
411         bool            have_anyenum = false;
412         Oid                     anyelement_type = InvalidOid;
413         Oid                     anyarray_type = InvalidOid;
414         int                     i;
415
416         /* See if there are any polymorphic outputs; quick out if not */
417         for (i = 0; i < natts; i++)
418         {
419                 switch (tupdesc->attrs[i]->atttypid)
420                 {
421                         case ANYELEMENTOID:
422                                 have_anyelement_result = true;
423                                 break;
424                         case ANYARRAYOID:
425                                 have_anyarray_result = true;
426                                 break;
427                         case ANYNONARRAYOID:
428                                 have_anyelement_result = true;
429                                 have_anynonarray = true;
430                                 break;
431                         case ANYENUMOID:
432                                 have_anyelement_result = true;
433                                 have_anyenum = true;
434                                 break;
435                         default:
436                                 break;
437                 }
438         }
439         if (!have_anyelement_result && !have_anyarray_result)
440                 return true;
441
442         /*
443          * Otherwise, extract actual datatype(s) from input arguments.  (We assume
444          * the parser already validated consistency of the arguments.)
445          */
446         if (!call_expr)
447                 return false;                   /* no hope */
448
449         for (i = 0; i < nargs; i++)
450         {
451                 switch (declared_args->values[i])
452                 {
453                         case ANYELEMENTOID:
454                         case ANYNONARRAYOID:
455                         case ANYENUMOID:
456                                 if (!OidIsValid(anyelement_type))
457                                         anyelement_type = get_call_expr_argtype(call_expr, i);
458                                 break;
459                         case ANYARRAYOID:
460                                 if (!OidIsValid(anyarray_type))
461                                         anyarray_type = get_call_expr_argtype(call_expr, i);
462                                 break;
463                         default:
464                                 break;
465                 }
466         }
467
468         /* If nothing found, parser messed up */
469         if (!OidIsValid(anyelement_type) && !OidIsValid(anyarray_type))
470                 return false;
471
472         /* If needed, deduce one polymorphic type from the other */
473         if (have_anyelement_result && !OidIsValid(anyelement_type))
474                 anyelement_type = resolve_generic_type(ANYELEMENTOID,
475                                                                                            anyarray_type,
476                                                                                            ANYARRAYOID);
477         if (have_anyarray_result && !OidIsValid(anyarray_type))
478                 anyarray_type = resolve_generic_type(ANYARRAYOID,
479                                                                                          anyelement_type,
480                                                                                          ANYELEMENTOID);
481
482         /* Enforce ANYNONARRAY if needed */
483         if (have_anynonarray && type_is_array(anyelement_type))
484                 return false;
485
486         /* Enforce ANYENUM if needed */
487         if (have_anyenum && !type_is_enum(anyelement_type))
488                 return false;
489
490         /* And finally replace the tuple column types as needed */
491         for (i = 0; i < natts; i++)
492         {
493                 switch (tupdesc->attrs[i]->atttypid)
494                 {
495                         case ANYELEMENTOID:
496                         case ANYNONARRAYOID:
497                         case ANYENUMOID:
498                                 TupleDescInitEntry(tupdesc, i + 1,
499                                                                    NameStr(tupdesc->attrs[i]->attname),
500                                                                    anyelement_type,
501                                                                    -1,
502                                                                    0);
503                                 break;
504                         case ANYARRAYOID:
505                                 TupleDescInitEntry(tupdesc, i + 1,
506                                                                    NameStr(tupdesc->attrs[i]->attname),
507                                                                    anyarray_type,
508                                                                    -1,
509                                                                    0);
510                                 break;
511                         default:
512                                 break;
513                 }
514         }
515
516         return true;
517 }
518
519 /*
520  * Given the declared argument types and modes for a function, replace any
521  * polymorphic types (ANYELEMENT etc) with correct data types deduced from the
522  * input arguments.  Returns TRUE if able to deduce all types, FALSE if not.
523  * This is the same logic as resolve_polymorphic_tupdesc, but with a different
524  * argument representation.
525  *
526  * argmodes may be NULL, in which case all arguments are assumed to be IN mode.
527  */
528 bool
529 resolve_polymorphic_argtypes(int numargs, Oid *argtypes, char *argmodes,
530                                                          Node *call_expr)
531 {
532         bool            have_anyelement_result = false;
533         bool            have_anyarray_result = false;
534         Oid                     anyelement_type = InvalidOid;
535         Oid                     anyarray_type = InvalidOid;
536         int                     inargno;
537         int                     i;
538
539         /* First pass: resolve polymorphic inputs, check for outputs */
540         inargno = 0;
541         for (i = 0; i < numargs; i++)
542         {
543                 char            argmode = argmodes ? argmodes[i] : PROARGMODE_IN;
544
545                 switch (argtypes[i])
546                 {
547                         case ANYELEMENTOID:
548                         case ANYNONARRAYOID:
549                         case ANYENUMOID:
550                                 if (argmode == PROARGMODE_OUT || argmode == PROARGMODE_TABLE)
551                                         have_anyelement_result = true;
552                                 else
553                                 {
554                                         if (!OidIsValid(anyelement_type))
555                                         {
556                                                 anyelement_type = get_call_expr_argtype(call_expr,
557                                                                                                                                 inargno);
558                                                 if (!OidIsValid(anyelement_type))
559                                                         return false;
560                                         }
561                                         argtypes[i] = anyelement_type;
562                                 }
563                                 break;
564                         case ANYARRAYOID:
565                                 if (argmode == PROARGMODE_OUT || argmode == PROARGMODE_TABLE)
566                                         have_anyarray_result = true;
567                                 else
568                                 {
569                                         if (!OidIsValid(anyarray_type))
570                                         {
571                                                 anyarray_type = get_call_expr_argtype(call_expr,
572                                                                                                                           inargno);
573                                                 if (!OidIsValid(anyarray_type))
574                                                         return false;
575                                         }
576                                         argtypes[i] = anyarray_type;
577                                 }
578                                 break;
579                         default:
580                                 break;
581                 }
582                 if (argmode != PROARGMODE_OUT && argmode != PROARGMODE_TABLE)
583                         inargno++;
584         }
585
586         /* Done? */
587         if (!have_anyelement_result && !have_anyarray_result)
588                 return true;
589
590         /* If no input polymorphics, parser messed up */
591         if (!OidIsValid(anyelement_type) && !OidIsValid(anyarray_type))
592                 return false;
593
594         /* If needed, deduce one polymorphic type from the other */
595         if (have_anyelement_result && !OidIsValid(anyelement_type))
596                 anyelement_type = resolve_generic_type(ANYELEMENTOID,
597                                                                                            anyarray_type,
598                                                                                            ANYARRAYOID);
599         if (have_anyarray_result && !OidIsValid(anyarray_type))
600                 anyarray_type = resolve_generic_type(ANYARRAYOID,
601                                                                                          anyelement_type,
602                                                                                          ANYELEMENTOID);
603
604         /* XXX do we need to enforce ANYNONARRAY or ANYENUM here?  I think not */
605
606         /* And finally replace the output column types as needed */
607         for (i = 0; i < numargs; i++)
608         {
609                 switch (argtypes[i])
610                 {
611                         case ANYELEMENTOID:
612                         case ANYNONARRAYOID:
613                         case ANYENUMOID:
614                                 argtypes[i] = anyelement_type;
615                                 break;
616                         case ANYARRAYOID:
617                                 argtypes[i] = anyarray_type;
618                                 break;
619                         default:
620                                 break;
621                 }
622         }
623
624         return true;
625 }
626
627 /*
628  * get_type_func_class
629  *              Given the type OID, obtain its TYPEFUNC classification.
630  *
631  * This is intended to centralize a bunch of formerly ad-hoc code for
632  * classifying types.  The categories used here are useful for deciding
633  * how to handle functions returning the datatype.
634  */
635 static TypeFuncClass
636 get_type_func_class(Oid typid)
637 {
638         switch (get_typtype(typid))
639         {
640                 case TYPTYPE_COMPOSITE:
641                         return TYPEFUNC_COMPOSITE;
642                 case TYPTYPE_BASE:
643                 case TYPTYPE_DOMAIN:
644                 case TYPTYPE_ENUM:
645                         return TYPEFUNC_SCALAR;
646                 case TYPTYPE_PSEUDO:
647                         if (typid == RECORDOID)
648                                 return TYPEFUNC_RECORD;
649
650                         /*
651                          * We treat VOID and CSTRING as legitimate scalar datatypes,
652                          * mostly for the convenience of the JDBC driver (which wants to
653                          * be able to do "SELECT * FROM foo()" for all legitimately
654                          * user-callable functions).
655                          */
656                         if (typid == VOIDOID || typid == CSTRINGOID)
657                                 return TYPEFUNC_SCALAR;
658                         return TYPEFUNC_OTHER;
659         }
660         /* shouldn't get here, probably */
661         return TYPEFUNC_OTHER;
662 }
663
664
665 /*
666  * get_func_arg_info
667  *
668  * Fetch info about the argument types, names, and IN/OUT modes from the
669  * pg_proc tuple.  Return value is the total number of arguments.
670  * Other results are palloc'd.  *p_argtypes is always filled in, but
671  * *p_argnames and *p_argmodes will be set NULL in the default cases
672  * (no names, and all IN arguments, respectively).
673  *
674  * Note that this function simply fetches what is in the pg_proc tuple;
675  * it doesn't do any interpretation of polymorphic types.
676  */
677 int
678 get_func_arg_info(HeapTuple procTup,
679                                   Oid **p_argtypes, char ***p_argnames, char **p_argmodes)
680 {
681         Form_pg_proc procStruct = (Form_pg_proc) GETSTRUCT(procTup);
682         Datum           proallargtypes;
683         Datum           proargmodes;
684         Datum           proargnames;
685         bool            isNull;
686         ArrayType  *arr;
687         int                     numargs;
688         Datum      *elems;
689         int                     nelems;
690         int                     i;
691
692         /* First discover the total number of parameters and get their types */
693         proallargtypes = SysCacheGetAttr(PROCOID, procTup,
694                                                                          Anum_pg_proc_proallargtypes,
695                                                                          &isNull);
696         if (!isNull)
697         {
698                 /*
699                  * We expect the arrays to be 1-D arrays of the right types; verify
700                  * that.  For the OID and char arrays, we don't need to use
701                  * deconstruct_array() since the array data is just going to look like
702                  * a C array of values.
703                  */
704                 arr = DatumGetArrayTypeP(proallargtypes);               /* ensure not toasted */
705                 numargs = ARR_DIMS(arr)[0];
706                 if (ARR_NDIM(arr) != 1 ||
707                         numargs < 0 ||
708                         ARR_HASNULL(arr) ||
709                         ARR_ELEMTYPE(arr) != OIDOID)
710                         elog(ERROR, "proallargtypes is not a 1-D Oid array");
711                 Assert(numargs >= procStruct->pronargs);
712                 *p_argtypes = (Oid *) palloc(numargs * sizeof(Oid));
713                 memcpy(*p_argtypes, ARR_DATA_PTR(arr),
714                            numargs * sizeof(Oid));
715         }
716         else
717         {
718                 /* If no proallargtypes, use proargtypes */
719                 numargs = procStruct->proargtypes.dim1;
720                 Assert(numargs == procStruct->pronargs);
721                 *p_argtypes = (Oid *) palloc(numargs * sizeof(Oid));
722                 memcpy(*p_argtypes, procStruct->proargtypes.values,
723                            numargs * sizeof(Oid));
724         }
725
726         /* Get argument names, if available */
727         proargnames = SysCacheGetAttr(PROCOID, procTup,
728                                                                   Anum_pg_proc_proargnames,
729                                                                   &isNull);
730         if (isNull)
731                 *p_argnames = NULL;
732         else
733         {
734                 deconstruct_array(DatumGetArrayTypeP(proargnames),
735                                                   TEXTOID, -1, false, 'i',
736                                                   &elems, NULL, &nelems);
737                 if (nelems != numargs)  /* should not happen */
738                         elog(ERROR, "proargnames must have the same number of elements as the function has arguments");
739                 *p_argnames = (char **) palloc(sizeof(char *) * numargs);
740                 for (i = 0; i < numargs; i++)
741                         (*p_argnames)[i] = TextDatumGetCString(elems[i]);
742         }
743
744         /* Get argument modes, if available */
745         proargmodes = SysCacheGetAttr(PROCOID, procTup,
746                                                                   Anum_pg_proc_proargmodes,
747                                                                   &isNull);
748         if (isNull)
749                 *p_argmodes = NULL;
750         else
751         {
752                 arr = DatumGetArrayTypeP(proargmodes);  /* ensure not toasted */
753                 if (ARR_NDIM(arr) != 1 ||
754                         ARR_DIMS(arr)[0] != numargs ||
755                         ARR_HASNULL(arr) ||
756                         ARR_ELEMTYPE(arr) != CHAROID)
757                         elog(ERROR, "proargmodes is not a 1-D char array");
758                 *p_argmodes = (char *) palloc(numargs * sizeof(char));
759                 memcpy(*p_argmodes, ARR_DATA_PTR(arr),
760                            numargs * sizeof(char));
761         }
762
763         return numargs;
764 }
765
766
767 /*
768  * get_func_input_arg_names
769  *
770  * Extract the names of input arguments only, given a function's
771  * proargnames and proargmodes entries in Datum form.
772  *
773  * Returns the number of input arguments, which is the length of the
774  * palloc'd array returned to *arg_names.  Entries for unnamed args
775  * are set to NULL.  You don't get anything if proargnames is NULL.
776  */
777 int
778 get_func_input_arg_names(Datum proargnames, Datum proargmodes,
779                                                  char ***arg_names)
780 {
781         ArrayType  *arr;
782         int                     numargs;
783         Datum      *argnames;
784         char       *argmodes;
785         char      **inargnames;
786         int                     numinargs;
787         int                     i;
788
789         /* Do nothing if null proargnames */
790         if (proargnames == PointerGetDatum(NULL))
791         {
792                 *arg_names = NULL;
793                 return 0;
794         }
795
796         /*
797          * We expect the arrays to be 1-D arrays of the right types; verify that.
798          * For proargmodes, we don't need to use deconstruct_array() since the
799          * array data is just going to look like a C array of values.
800          */
801         arr = DatumGetArrayTypeP(proargnames);          /* ensure not toasted */
802         if (ARR_NDIM(arr) != 1 ||
803                 ARR_HASNULL(arr) ||
804                 ARR_ELEMTYPE(arr) != TEXTOID)
805                 elog(ERROR, "proargnames is not a 1-D text array");
806         deconstruct_array(arr, TEXTOID, -1, false, 'i',
807                                           &argnames, NULL, &numargs);
808         if (proargmodes != PointerGetDatum(NULL))
809         {
810                 arr = DatumGetArrayTypeP(proargmodes);  /* ensure not toasted */
811                 if (ARR_NDIM(arr) != 1 ||
812                         ARR_DIMS(arr)[0] != numargs ||
813                         ARR_HASNULL(arr) ||
814                         ARR_ELEMTYPE(arr) != CHAROID)
815                         elog(ERROR, "proargmodes is not a 1-D char array");
816                 argmodes = (char *) ARR_DATA_PTR(arr);
817         }
818         else
819                 argmodes = NULL;
820
821         /* zero elements probably shouldn't happen, but handle it gracefully */
822         if (numargs <= 0)
823         {
824                 *arg_names = NULL;
825                 return 0;
826         }
827
828         /* extract input-argument names */
829         inargnames = (char **) palloc(numargs * sizeof(char *));
830         numinargs = 0;
831         for (i = 0; i < numargs; i++)
832         {
833                 if (argmodes == NULL ||
834                         argmodes[i] == PROARGMODE_IN ||
835                         argmodes[i] == PROARGMODE_INOUT ||
836                         argmodes[i] == PROARGMODE_VARIADIC)
837                 {
838                         char       *pname = TextDatumGetCString(argnames[i]);
839
840                         if (pname[0] != '\0')
841                                 inargnames[numinargs] = pname;
842                         else
843                                 inargnames[numinargs] = NULL;
844                         numinargs++;
845                 }
846         }
847
848         *arg_names = inargnames;
849         return numinargs;
850 }
851
852
853 /*
854  * get_func_result_name
855  *
856  * If the function has exactly one output parameter, and that parameter
857  * is named, return the name (as a palloc'd string).  Else return NULL.
858  *
859  * This is used to determine the default output column name for functions
860  * returning scalar types.
861  */
862 char *
863 get_func_result_name(Oid functionId)
864 {
865         char       *result;
866         HeapTuple       procTuple;
867         Datum           proargmodes;
868         Datum           proargnames;
869         bool            isnull;
870         ArrayType  *arr;
871         int                     numargs;
872         char       *argmodes;
873         Datum      *argnames;
874         int                     numoutargs;
875         int                     nargnames;
876         int                     i;
877
878         /* First fetch the function's pg_proc row */
879         procTuple = SearchSysCache1(PROCOID, ObjectIdGetDatum(functionId));
880         if (!HeapTupleIsValid(procTuple))
881                 elog(ERROR, "cache lookup failed for function %u", functionId);
882
883         /* If there are no named OUT parameters, return NULL */
884         if (heap_attisnull(procTuple, Anum_pg_proc_proargmodes) ||
885                 heap_attisnull(procTuple, Anum_pg_proc_proargnames))
886                 result = NULL;
887         else
888         {
889                 /* Get the data out of the tuple */
890                 proargmodes = SysCacheGetAttr(PROCOID, procTuple,
891                                                                           Anum_pg_proc_proargmodes,
892                                                                           &isnull);
893                 Assert(!isnull);
894                 proargnames = SysCacheGetAttr(PROCOID, procTuple,
895                                                                           Anum_pg_proc_proargnames,
896                                                                           &isnull);
897                 Assert(!isnull);
898
899                 /*
900                  * We expect the arrays to be 1-D arrays of the right types; verify
901                  * that.  For the char array, we don't need to use deconstruct_array()
902                  * since the array data is just going to look like a C array of
903                  * values.
904                  */
905                 arr = DatumGetArrayTypeP(proargmodes);  /* ensure not toasted */
906                 numargs = ARR_DIMS(arr)[0];
907                 if (ARR_NDIM(arr) != 1 ||
908                         numargs < 0 ||
909                         ARR_HASNULL(arr) ||
910                         ARR_ELEMTYPE(arr) != CHAROID)
911                         elog(ERROR, "proargmodes is not a 1-D char array");
912                 argmodes = (char *) ARR_DATA_PTR(arr);
913                 arr = DatumGetArrayTypeP(proargnames);  /* ensure not toasted */
914                 if (ARR_NDIM(arr) != 1 ||
915                         ARR_DIMS(arr)[0] != numargs ||
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, &nargnames);
921                 Assert(nargnames == numargs);
922
923                 /* scan for output argument(s) */
924                 result = NULL;
925                 numoutargs = 0;
926                 for (i = 0; i < numargs; i++)
927                 {
928                         if (argmodes[i] == PROARGMODE_IN ||
929                                 argmodes[i] == PROARGMODE_VARIADIC)
930                                 continue;
931                         Assert(argmodes[i] == PROARGMODE_OUT ||
932                                    argmodes[i] == PROARGMODE_INOUT ||
933                                    argmodes[i] == PROARGMODE_TABLE);
934                         if (++numoutargs > 1)
935                         {
936                                 /* multiple out args, so forget it */
937                                 result = NULL;
938                                 break;
939                         }
940                         result = TextDatumGetCString(argnames[i]);
941                         if (result == NULL || result[0] == '\0')
942                         {
943                                 /* Parameter is not named, so forget it */
944                                 result = NULL;
945                                 break;
946                         }
947                 }
948         }
949
950         ReleaseSysCache(procTuple);
951
952         return result;
953 }
954
955
956 /*
957  * build_function_result_tupdesc_t
958  *
959  * Given a pg_proc row for a function, return a tuple descriptor for the
960  * result rowtype, or NULL if the function does not have OUT parameters.
961  *
962  * Note that this does not handle resolution of polymorphic types;
963  * that is deliberate.
964  */
965 TupleDesc
966 build_function_result_tupdesc_t(HeapTuple procTuple)
967 {
968         Form_pg_proc procform = (Form_pg_proc) GETSTRUCT(procTuple);
969         Datum           proallargtypes;
970         Datum           proargmodes;
971         Datum           proargnames;
972         bool            isnull;
973
974         /* Return NULL if the function isn't declared to return RECORD */
975         if (procform->prorettype != RECORDOID)
976                 return NULL;
977
978         /* If there are no OUT parameters, return NULL */
979         if (heap_attisnull(procTuple, Anum_pg_proc_proallargtypes) ||
980                 heap_attisnull(procTuple, Anum_pg_proc_proargmodes))
981                 return NULL;
982
983         /* Get the data out of the tuple */
984         proallargtypes = SysCacheGetAttr(PROCOID, procTuple,
985                                                                          Anum_pg_proc_proallargtypes,
986                                                                          &isnull);
987         Assert(!isnull);
988         proargmodes = SysCacheGetAttr(PROCOID, procTuple,
989                                                                   Anum_pg_proc_proargmodes,
990                                                                   &isnull);
991         Assert(!isnull);
992         proargnames = SysCacheGetAttr(PROCOID, procTuple,
993                                                                   Anum_pg_proc_proargnames,
994                                                                   &isnull);
995         if (isnull)
996                 proargnames = PointerGetDatum(NULL);    /* just to be sure */
997
998         return build_function_result_tupdesc_d(proallargtypes,
999                                                                                    proargmodes,
1000                                                                                    proargnames);
1001 }
1002
1003 /*
1004  * build_function_result_tupdesc_d
1005  *
1006  * Build a RECORD function's tupledesc from the pg_proc proallargtypes,
1007  * proargmodes, and proargnames arrays.  This is split out for the
1008  * convenience of ProcedureCreate, which needs to be able to compute the
1009  * tupledesc before actually creating the function.
1010  *
1011  * Returns NULL if there are not at least two OUT or INOUT arguments.
1012  */
1013 TupleDesc
1014 build_function_result_tupdesc_d(Datum proallargtypes,
1015                                                                 Datum proargmodes,
1016                                                                 Datum proargnames)
1017 {
1018         TupleDesc       desc;
1019         ArrayType  *arr;
1020         int                     numargs;
1021         Oid                *argtypes;
1022         char       *argmodes;
1023         Datum      *argnames = NULL;
1024         Oid                *outargtypes;
1025         char      **outargnames;
1026         int                     numoutargs;
1027         int                     nargnames;
1028         int                     i;
1029
1030         /* Can't have output args if columns are null */
1031         if (proallargtypes == PointerGetDatum(NULL) ||
1032                 proargmodes == PointerGetDatum(NULL))
1033                 return NULL;
1034
1035         /*
1036          * We expect the arrays to be 1-D arrays of the right types; verify that.
1037          * For the OID and char arrays, we don't need to use deconstruct_array()
1038          * since the array data is just going to look like a C array of values.
1039          */
1040         arr = DatumGetArrayTypeP(proallargtypes);       /* ensure not toasted */
1041         numargs = ARR_DIMS(arr)[0];
1042         if (ARR_NDIM(arr) != 1 ||
1043                 numargs < 0 ||
1044                 ARR_HASNULL(arr) ||
1045                 ARR_ELEMTYPE(arr) != OIDOID)
1046                 elog(ERROR, "proallargtypes is not a 1-D Oid array");
1047         argtypes = (Oid *) ARR_DATA_PTR(arr);
1048         arr = DatumGetArrayTypeP(proargmodes);          /* ensure not toasted */
1049         if (ARR_NDIM(arr) != 1 ||
1050                 ARR_DIMS(arr)[0] != numargs ||
1051                 ARR_HASNULL(arr) ||
1052                 ARR_ELEMTYPE(arr) != CHAROID)
1053                 elog(ERROR, "proargmodes is not a 1-D char array");
1054         argmodes = (char *) ARR_DATA_PTR(arr);
1055         if (proargnames != PointerGetDatum(NULL))
1056         {
1057                 arr = DatumGetArrayTypeP(proargnames);  /* ensure not toasted */
1058                 if (ARR_NDIM(arr) != 1 ||
1059                         ARR_DIMS(arr)[0] != numargs ||
1060                         ARR_HASNULL(arr) ||
1061                         ARR_ELEMTYPE(arr) != TEXTOID)
1062                         elog(ERROR, "proargnames is not a 1-D text array");
1063                 deconstruct_array(arr, TEXTOID, -1, false, 'i',
1064                                                   &argnames, NULL, &nargnames);
1065                 Assert(nargnames == numargs);
1066         }
1067
1068         /* zero elements probably shouldn't happen, but handle it gracefully */
1069         if (numargs <= 0)
1070                 return NULL;
1071
1072         /* extract output-argument types and names */
1073         outargtypes = (Oid *) palloc(numargs * sizeof(Oid));
1074         outargnames = (char **) palloc(numargs * sizeof(char *));
1075         numoutargs = 0;
1076         for (i = 0; i < numargs; i++)
1077         {
1078                 char       *pname;
1079
1080                 if (argmodes[i] == PROARGMODE_IN ||
1081                         argmodes[i] == PROARGMODE_VARIADIC)
1082                         continue;
1083                 Assert(argmodes[i] == PROARGMODE_OUT ||
1084                            argmodes[i] == PROARGMODE_INOUT ||
1085                            argmodes[i] == PROARGMODE_TABLE);
1086                 outargtypes[numoutargs] = argtypes[i];
1087                 if (argnames)
1088                         pname = TextDatumGetCString(argnames[i]);
1089                 else
1090                         pname = NULL;
1091                 if (pname == NULL || pname[0] == '\0')
1092                 {
1093                         /* Parameter is not named, so gin up a column name */
1094                         pname = (char *) palloc(32);
1095                         snprintf(pname, 32, "column%d", numoutargs + 1);
1096                 }
1097                 outargnames[numoutargs] = pname;
1098                 numoutargs++;
1099         }
1100
1101         /*
1102          * If there is no output argument, or only one, the function does not
1103          * return tuples.
1104          */
1105         if (numoutargs < 2)
1106                 return NULL;
1107
1108         desc = CreateTemplateTupleDesc(numoutargs, false);
1109         for (i = 0; i < numoutargs; i++)
1110         {
1111                 TupleDescInitEntry(desc, i + 1,
1112                                                    outargnames[i],
1113                                                    outargtypes[i],
1114                                                    -1,
1115                                                    0);
1116         }
1117
1118         return desc;
1119 }
1120
1121
1122 /*
1123  * RelationNameGetTupleDesc
1124  *
1125  * Given a (possibly qualified) relation name, build a TupleDesc.
1126  *
1127  * Note: while this works as advertised, it's seldom the best way to
1128  * build a tupdesc for a function's result type.  It's kept around
1129  * only for backwards compatibility with existing user-written code.
1130  */
1131 TupleDesc
1132 RelationNameGetTupleDesc(const char *relname)
1133 {
1134         RangeVar   *relvar;
1135         Relation        rel;
1136         TupleDesc       tupdesc;
1137         List       *relname_list;
1138
1139         /* Open relation and copy the tuple description */
1140         relname_list = stringToQualifiedNameList(relname);
1141         relvar = makeRangeVarFromNameList(relname_list);
1142         rel = relation_openrv(relvar, AccessShareLock);
1143         tupdesc = CreateTupleDescCopy(RelationGetDescr(rel));
1144         relation_close(rel, AccessShareLock);
1145
1146         return tupdesc;
1147 }
1148
1149 /*
1150  * TypeGetTupleDesc
1151  *
1152  * Given a type Oid, build a TupleDesc.  (In most cases you should be
1153  * using get_call_result_type or one of its siblings instead of this
1154  * routine, so that you can handle OUT parameters, RECORD result type,
1155  * and polymorphic results.)
1156  *
1157  * If the type is composite, *and* a colaliases List is provided, *and*
1158  * the List is of natts length, use the aliases instead of the relation
1159  * attnames.  (NB: this usage is deprecated since it may result in
1160  * creation of unnecessary transient record types.)
1161  *
1162  * If the type is a base type, a single item alias List is required.
1163  */
1164 TupleDesc
1165 TypeGetTupleDesc(Oid typeoid, List *colaliases)
1166 {
1167         TypeFuncClass functypclass = get_type_func_class(typeoid);
1168         TupleDesc       tupdesc = NULL;
1169
1170         /*
1171          * Build a suitable tupledesc representing the output rows
1172          */
1173         if (functypclass == TYPEFUNC_COMPOSITE)
1174         {
1175                 /* Composite data type, e.g. a table's row type */
1176                 tupdesc = lookup_rowtype_tupdesc_copy(typeoid, -1);
1177
1178                 if (colaliases != NIL)
1179                 {
1180                         int                     natts = tupdesc->natts;
1181                         int                     varattno;
1182
1183                         /* does the list length match the number of attributes? */
1184                         if (list_length(colaliases) != natts)
1185                                 ereport(ERROR,
1186                                                 (errcode(ERRCODE_DATATYPE_MISMATCH),
1187                                                  errmsg("number of aliases does not match number of columns")));
1188
1189                         /* OK, use the aliases instead */
1190                         for (varattno = 0; varattno < natts; varattno++)
1191                         {
1192                                 char       *label = strVal(list_nth(colaliases, varattno));
1193
1194                                 if (label != NULL)
1195                                         namestrcpy(&(tupdesc->attrs[varattno]->attname), label);
1196                         }
1197
1198                         /* The tuple type is now an anonymous record type */
1199                         tupdesc->tdtypeid = RECORDOID;
1200                         tupdesc->tdtypmod = -1;
1201                 }
1202         }
1203         else if (functypclass == TYPEFUNC_SCALAR)
1204         {
1205                 /* Base data type, i.e. scalar */
1206                 char       *attname;
1207
1208                 /* the alias list is required for base types */
1209                 if (colaliases == NIL)
1210                         ereport(ERROR,
1211                                         (errcode(ERRCODE_DATATYPE_MISMATCH),
1212                                          errmsg("no column alias was provided")));
1213
1214                 /* the alias list length must be 1 */
1215                 if (list_length(colaliases) != 1)
1216                         ereport(ERROR,
1217                                         (errcode(ERRCODE_DATATYPE_MISMATCH),
1218                           errmsg("number of aliases does not match number of columns")));
1219
1220                 /* OK, get the column alias */
1221                 attname = strVal(linitial(colaliases));
1222
1223                 tupdesc = CreateTemplateTupleDesc(1, false);
1224                 TupleDescInitEntry(tupdesc,
1225                                                    (AttrNumber) 1,
1226                                                    attname,
1227                                                    typeoid,
1228                                                    -1,
1229                                                    0);
1230         }
1231         else if (functypclass == TYPEFUNC_RECORD)
1232         {
1233                 /* XXX can't support this because typmod wasn't passed in ... */
1234                 ereport(ERROR,
1235                                 (errcode(ERRCODE_DATATYPE_MISMATCH),
1236                                  errmsg("could not determine row description for function returning record")));
1237         }
1238         else
1239         {
1240                 /* crummy error message, but parser should have caught this */
1241                 elog(ERROR, "function in FROM has unsupported return type");
1242         }
1243
1244         return tupdesc;
1245 }