1 /*-------------------------------------------------------------------------
4 * Utility and convenience functions for fmgr functions that return
5 * sets and/or composite types.
7 * Copyright (c) 2002-2008, PostgreSQL Global Development Group
12 *-------------------------------------------------------------------------
16 #include "access/heapam.h"
17 #include "catalog/namespace.h"
18 #include "catalog/pg_proc.h"
19 #include "catalog/pg_type.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"
31 static void shutdown_MultiFuncCall(Datum arg
);
32 static TypeFuncClass
internal_get_result_type(Oid funcid
,
34 ReturnSetInfo
*rsinfo
,
36 TupleDesc
*resultTupleDesc
);
37 static bool resolve_polymorphic_tupdesc(TupleDesc tupdesc
,
38 oidvector
*declared_args
,
40 static TypeFuncClass
get_type_func_class(Oid typid
);
45 * Create an empty FuncCallContext data structure
46 * and do some other basic Multi-function call setup
50 init_MultiFuncCall(PG_FUNCTION_ARGS
)
52 FuncCallContext
*retval
;
55 * Bail if we're called in the wrong context
57 if (fcinfo
->resultinfo
== NULL
|| !IsA(fcinfo
->resultinfo
, ReturnSetInfo
))
59 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED
),
60 errmsg("set-valued function called in context that cannot accept a set")));
62 if (fcinfo
->flinfo
->fn_extra
== NULL
)
67 ReturnSetInfo
*rsi
= (ReturnSetInfo
*) fcinfo
->resultinfo
;
68 MemoryContext multi_call_ctx
;
71 * Create a suitably long-lived context to hold cross-call data
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
);
80 * Allocate suitably long-lived space and zero it
82 retval
= (FuncCallContext
*)
83 MemoryContextAllocZero(multi_call_ctx
,
84 sizeof(FuncCallContext
));
87 * initialize the elements
89 retval
->call_cntr
= 0;
90 retval
->max_calls
= 0;
92 retval
->user_fctx
= NULL
;
93 retval
->attinmeta
= NULL
;
94 retval
->tuple_desc
= NULL
;
95 retval
->multi_call_memory_ctx
= multi_call_ctx
;
98 * save the pointer for cross-call use
100 fcinfo
->flinfo
->fn_extra
= retval
;
103 * Ensure we will get shut down cleanly if the exprcontext is not run
106 RegisterExprContextCallback(rsi
->econtext
,
107 shutdown_MultiFuncCall
,
108 PointerGetDatum(fcinfo
->flinfo
));
112 /* second and subsequent calls */
113 elog(ERROR
, "init_MultiFuncCall cannot be called more than once");
115 /* never reached, but keep compiler happy */
125 * Do Multi-function per-call setup
128 per_MultiFuncCall(PG_FUNCTION_ARGS
)
130 FuncCallContext
*retval
= (FuncCallContext
*) fcinfo
->flinfo
->fn_extra
;
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.
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.
144 if (retval
->slot
!= NULL
)
145 ExecClearTuple(retval
->slot
);
152 * Clean up after init_MultiFuncCall
155 end_MultiFuncCall(PG_FUNCTION_ARGS
, FuncCallContext
*funcctx
)
157 ReturnSetInfo
*rsi
= (ReturnSetInfo
*) fcinfo
->resultinfo
;
159 /* Deregister the shutdown callback */
160 UnregisterExprContextCallback(rsi
->econtext
,
161 shutdown_MultiFuncCall
,
162 PointerGetDatum(fcinfo
->flinfo
));
164 /* But use it to do the real work */
165 shutdown_MultiFuncCall(PointerGetDatum(fcinfo
->flinfo
));
169 * shutdown_MultiFuncCall
170 * Shutdown function to clean up after init_MultiFuncCall
173 shutdown_MultiFuncCall(Datum arg
)
175 FmgrInfo
*flinfo
= (FmgrInfo
*) DatumGetPointer(arg
);
176 FuncCallContext
*funcctx
= (FuncCallContext
*) flinfo
->fn_extra
;
178 /* unbind from flinfo */
179 flinfo
->fn_extra
= NULL
;
182 * Delete context that holds all multi-call data, including the
183 * FuncCallContext itself
185 MemoryContextSwitchTo(flinfo
->fn_mcxt
);
186 MemoryContextDelete(funcctx
->multi_call_memory_ctx
);
191 * get_call_result_type
192 * Given a function's call info record, determine the kind of datatype
193 * it is supposed to return. If resultTypeId isn't NULL, *resultTypeId
194 * receives the actual datatype OID (this is mainly useful for scalar
195 * result types). If resultTupleDesc isn't NULL, *resultTupleDesc
196 * receives a pointer to a TupleDesc when the result is of a composite
197 * type, or NULL when it's a scalar result.
199 * One hard case that this handles is resolution of actual rowtypes for
200 * functions returning RECORD (from either the function's OUT parameter
201 * list, or a ReturnSetInfo context node). TYPEFUNC_RECORD is returned
202 * only when we couldn't resolve the actual rowtype for lack of information.
204 * The other hard case that this handles is resolution of polymorphism.
205 * We will never return polymorphic pseudotypes (ANYELEMENT etc), either
206 * as a scalar result type or as a component of a rowtype.
208 * This function is relatively expensive --- in a function returning set,
209 * try to call it only the first time through.
212 get_call_result_type(FunctionCallInfo fcinfo
,
214 TupleDesc
*resultTupleDesc
)
216 return internal_get_result_type(fcinfo
->flinfo
->fn_oid
,
217 fcinfo
->flinfo
->fn_expr
,
218 (ReturnSetInfo
*) fcinfo
->resultinfo
,
224 * get_expr_result_type
225 * As above, but work from a calling expression node tree
228 get_expr_result_type(Node
*expr
,
230 TupleDesc
*resultTupleDesc
)
232 TypeFuncClass result
;
234 if (expr
&& IsA(expr
, FuncExpr
))
235 result
= internal_get_result_type(((FuncExpr
*) expr
)->funcid
,
240 else if (expr
&& IsA(expr
, OpExpr
))
241 result
= internal_get_result_type(get_opcode(((OpExpr
*) expr
)->opno
),
248 /* handle as a generic expression; no chance to resolve RECORD */
249 Oid typid
= exprType(expr
);
252 *resultTypeId
= typid
;
254 *resultTupleDesc
= NULL
;
255 result
= get_type_func_class(typid
);
256 if (result
== TYPEFUNC_COMPOSITE
&& resultTupleDesc
)
257 *resultTupleDesc
= lookup_rowtype_tupdesc_copy(typid
, -1);
264 * get_func_result_type
265 * As above, but work from a function's OID only
267 * This will not be able to resolve pure-RECORD results nor polymorphism.
270 get_func_result_type(Oid functionId
,
272 TupleDesc
*resultTupleDesc
)
274 return internal_get_result_type(functionId
,
282 * internal_get_result_type -- workhorse code implementing all the above
284 * funcid must always be supplied. call_expr and rsinfo can be NULL if not
285 * available. We will return TYPEFUNC_RECORD, and store NULL into
286 * *resultTupleDesc, if we cannot deduce the complete result rowtype from
287 * the available information.
290 internal_get_result_type(Oid funcid
,
292 ReturnSetInfo
*rsinfo
,
294 TupleDesc
*resultTupleDesc
)
296 TypeFuncClass result
;
298 Form_pg_proc procform
;
302 /* First fetch the function's pg_proc row to inspect its rettype */
303 tp
= SearchSysCache(PROCOID
,
304 ObjectIdGetDatum(funcid
),
306 if (!HeapTupleIsValid(tp
))
307 elog(ERROR
, "cache lookup failed for function %u", funcid
);
308 procform
= (Form_pg_proc
) GETSTRUCT(tp
);
310 rettype
= procform
->prorettype
;
312 /* Check for OUT parameters defining a RECORD result */
313 tupdesc
= build_function_result_tupdesc_t(tp
);
317 * It has OUT parameters, so it's basically like a regular composite
318 * type, except we have to be able to resolve any polymorphic OUT
322 *resultTypeId
= rettype
;
324 if (resolve_polymorphic_tupdesc(tupdesc
,
325 &procform
->proargtypes
,
328 if (tupdesc
->tdtypeid
== RECORDOID
&&
329 tupdesc
->tdtypmod
< 0)
330 assign_record_type_typmod(tupdesc
);
332 *resultTupleDesc
= tupdesc
;
333 result
= TYPEFUNC_COMPOSITE
;
338 *resultTupleDesc
= NULL
;
339 result
= TYPEFUNC_RECORD
;
348 * If scalar polymorphic result, try to resolve it.
350 if (IsPolymorphicType(rettype
))
352 Oid newrettype
= exprType(call_expr
);
354 if (newrettype
== InvalidOid
) /* this probably should not happen */
356 (errcode(ERRCODE_DATATYPE_MISMATCH
),
357 errmsg("could not determine actual result type for function \"%s\" declared to return type %s",
358 NameStr(procform
->proname
),
359 format_type_be(rettype
))));
360 rettype
= newrettype
;
364 *resultTypeId
= rettype
;
366 *resultTupleDesc
= NULL
; /* default result */
368 /* Classify the result type */
369 result
= get_type_func_class(rettype
);
372 case TYPEFUNC_COMPOSITE
:
374 *resultTupleDesc
= lookup_rowtype_tupdesc_copy(rettype
, -1);
375 /* Named composite types can't have any polymorphic columns */
377 case TYPEFUNC_SCALAR
:
379 case TYPEFUNC_RECORD
:
380 /* We must get the tupledesc from call context */
381 if (rsinfo
&& IsA(rsinfo
, ReturnSetInfo
) &&
382 rsinfo
->expectedDesc
!= NULL
)
384 result
= TYPEFUNC_COMPOSITE
;
386 *resultTupleDesc
= rsinfo
->expectedDesc
;
387 /* Assume no polymorphic columns here, either */
400 * Given the result tuple descriptor for a function with OUT parameters,
401 * replace any polymorphic columns (ANYELEMENT etc) with correct data types
402 * deduced from the input arguments. Returns TRUE if able to deduce all types,
406 resolve_polymorphic_tupdesc(TupleDesc tupdesc
, oidvector
*declared_args
,
409 int natts
= tupdesc
->natts
;
410 int nargs
= declared_args
->dim1
;
411 bool have_anyelement_result
= false;
412 bool have_anyarray_result
= false;
413 bool have_anynonarray
= false;
414 bool have_anyenum
= false;
415 Oid anyelement_type
= InvalidOid
;
416 Oid anyarray_type
= InvalidOid
;
419 /* See if there are any polymorphic outputs; quick out if not */
420 for (i
= 0; i
< natts
; i
++)
422 switch (tupdesc
->attrs
[i
]->atttypid
)
425 have_anyelement_result
= true;
428 have_anyarray_result
= true;
431 have_anyelement_result
= true;
432 have_anynonarray
= true;
435 have_anyelement_result
= true;
442 if (!have_anyelement_result
&& !have_anyarray_result
)
446 * Otherwise, extract actual datatype(s) from input arguments. (We assume
447 * the parser already validated consistency of the arguments.)
450 return false; /* no hope */
452 for (i
= 0; i
< nargs
; i
++)
454 switch (declared_args
->values
[i
])
459 if (!OidIsValid(anyelement_type
))
460 anyelement_type
= get_call_expr_argtype(call_expr
, i
);
463 if (!OidIsValid(anyarray_type
))
464 anyarray_type
= get_call_expr_argtype(call_expr
, i
);
471 /* If nothing found, parser messed up */
472 if (!OidIsValid(anyelement_type
) && !OidIsValid(anyarray_type
))
475 /* If needed, deduce one polymorphic type from the other */
476 if (have_anyelement_result
&& !OidIsValid(anyelement_type
))
477 anyelement_type
= resolve_generic_type(ANYELEMENTOID
,
480 if (have_anyarray_result
&& !OidIsValid(anyarray_type
))
481 anyarray_type
= resolve_generic_type(ANYARRAYOID
,
485 /* Enforce ANYNONARRAY if needed */
486 if (have_anynonarray
&& type_is_array(anyelement_type
))
489 /* Enforce ANYENUM if needed */
490 if (have_anyenum
&& !type_is_enum(anyelement_type
))
493 /* And finally replace the tuple column types as needed */
494 for (i
= 0; i
< natts
; i
++)
496 switch (tupdesc
->attrs
[i
]->atttypid
)
501 TupleDescInitEntry(tupdesc
, i
+ 1,
502 NameStr(tupdesc
->attrs
[i
]->attname
),
508 TupleDescInitEntry(tupdesc
, i
+ 1,
509 NameStr(tupdesc
->attrs
[i
]->attname
),
523 * Given the declared argument types and modes for a function, replace any
524 * polymorphic types (ANYELEMENT etc) with correct data types deduced from the
525 * input arguments. Returns TRUE if able to deduce all types, FALSE if not.
526 * This is the same logic as resolve_polymorphic_tupdesc, but with a different
527 * argument representation.
529 * argmodes may be NULL, in which case all arguments are assumed to be IN mode.
532 resolve_polymorphic_argtypes(int numargs
, Oid
*argtypes
, char *argmodes
,
535 bool have_anyelement_result
= false;
536 bool have_anyarray_result
= false;
537 Oid anyelement_type
= InvalidOid
;
538 Oid anyarray_type
= InvalidOid
;
542 /* First pass: resolve polymorphic inputs, check for outputs */
544 for (i
= 0; i
< numargs
; i
++)
546 char argmode
= argmodes
? argmodes
[i
] : PROARGMODE_IN
;
553 if (argmode
== PROARGMODE_OUT
|| argmode
== PROARGMODE_TABLE
)
554 have_anyelement_result
= true;
557 if (!OidIsValid(anyelement_type
))
559 anyelement_type
= get_call_expr_argtype(call_expr
,
561 if (!OidIsValid(anyelement_type
))
564 argtypes
[i
] = anyelement_type
;
568 if (argmode
== PROARGMODE_OUT
|| argmode
== PROARGMODE_TABLE
)
569 have_anyarray_result
= true;
572 if (!OidIsValid(anyarray_type
))
574 anyarray_type
= get_call_expr_argtype(call_expr
,
576 if (!OidIsValid(anyarray_type
))
579 argtypes
[i
] = anyarray_type
;
585 if (argmode
!= PROARGMODE_OUT
&& argmode
!= PROARGMODE_TABLE
)
590 if (!have_anyelement_result
&& !have_anyarray_result
)
593 /* If no input polymorphics, parser messed up */
594 if (!OidIsValid(anyelement_type
) && !OidIsValid(anyarray_type
))
597 /* If needed, deduce one polymorphic type from the other */
598 if (have_anyelement_result
&& !OidIsValid(anyelement_type
))
599 anyelement_type
= resolve_generic_type(ANYELEMENTOID
,
602 if (have_anyarray_result
&& !OidIsValid(anyarray_type
))
603 anyarray_type
= resolve_generic_type(ANYARRAYOID
,
607 /* XXX do we need to enforce ANYNONARRAY or ANYENUM here? I think not */
609 /* And finally replace the output column types as needed */
610 for (i
= 0; i
< numargs
; i
++)
617 argtypes
[i
] = anyelement_type
;
620 argtypes
[i
] = anyarray_type
;
631 * get_type_func_class
632 * Given the type OID, obtain its TYPEFUNC classification.
634 * This is intended to centralize a bunch of formerly ad-hoc code for
635 * classifying types. The categories used here are useful for deciding
636 * how to handle functions returning the datatype.
639 get_type_func_class(Oid typid
)
641 switch (get_typtype(typid
))
643 case TYPTYPE_COMPOSITE
:
644 return TYPEFUNC_COMPOSITE
;
648 return TYPEFUNC_SCALAR
;
650 if (typid
== RECORDOID
)
651 return TYPEFUNC_RECORD
;
654 * We treat VOID and CSTRING as legitimate scalar datatypes,
655 * mostly for the convenience of the JDBC driver (which wants to
656 * be able to do "SELECT * FROM foo()" for all legitimately
657 * user-callable functions).
659 if (typid
== VOIDOID
|| typid
== CSTRINGOID
)
660 return TYPEFUNC_SCALAR
;
661 return TYPEFUNC_OTHER
;
663 /* shouldn't get here, probably */
664 return TYPEFUNC_OTHER
;
671 * Fetch info about the argument types, names, and IN/OUT modes from the
672 * pg_proc tuple. Return value is the total number of arguments.
673 * Other results are palloc'd. *p_argtypes is always filled in, but
674 * *p_argnames and *p_argmodes will be set NULL in the default cases
675 * (no names, and all IN arguments, respectively).
677 * Note that this function simply fetches what is in the pg_proc tuple;
678 * it doesn't do any interpretation of polymorphic types.
681 get_func_arg_info(HeapTuple procTup
,
682 Oid
**p_argtypes
, char ***p_argnames
, char **p_argmodes
)
684 Form_pg_proc procStruct
= (Form_pg_proc
) GETSTRUCT(procTup
);
685 Datum proallargtypes
;
695 /* First discover the total number of parameters and get their types */
696 proallargtypes
= SysCacheGetAttr(PROCOID
, procTup
,
697 Anum_pg_proc_proallargtypes
,
702 * We expect the arrays to be 1-D arrays of the right types; verify
703 * that. For the OID and char arrays, we don't need to use
704 * deconstruct_array() since the array data is just going to look like
705 * a C array of values.
707 arr
= DatumGetArrayTypeP(proallargtypes
); /* ensure not toasted */
708 numargs
= ARR_DIMS(arr
)[0];
709 if (ARR_NDIM(arr
) != 1 ||
712 ARR_ELEMTYPE(arr
) != OIDOID
)
713 elog(ERROR
, "proallargtypes is not a 1-D Oid array");
714 Assert(numargs
>= procStruct
->pronargs
);
715 *p_argtypes
= (Oid
*) palloc(numargs
* sizeof(Oid
));
716 memcpy(*p_argtypes
, ARR_DATA_PTR(arr
),
717 numargs
* sizeof(Oid
));
721 /* If no proallargtypes, use proargtypes */
722 numargs
= procStruct
->proargtypes
.dim1
;
723 Assert(numargs
== procStruct
->pronargs
);
724 *p_argtypes
= (Oid
*) palloc(numargs
* sizeof(Oid
));
725 memcpy(*p_argtypes
, procStruct
->proargtypes
.values
,
726 numargs
* sizeof(Oid
));
729 /* Get argument names, if available */
730 proargnames
= SysCacheGetAttr(PROCOID
, procTup
,
731 Anum_pg_proc_proargnames
,
737 deconstruct_array(DatumGetArrayTypeP(proargnames
),
738 TEXTOID
, -1, false, 'i',
739 &elems
, NULL
, &nelems
);
740 if (nelems
!= numargs
) /* should not happen */
741 elog(ERROR
, "proargnames must have the same number of elements as the function has arguments");
742 *p_argnames
= (char **) palloc(sizeof(char *) * numargs
);
743 for (i
= 0; i
< numargs
; i
++)
744 (*p_argnames
)[i
] = TextDatumGetCString(elems
[i
]);
747 /* Get argument modes, if available */
748 proargmodes
= SysCacheGetAttr(PROCOID
, procTup
,
749 Anum_pg_proc_proargmodes
,
755 arr
= DatumGetArrayTypeP(proargmodes
); /* ensure not toasted */
756 if (ARR_NDIM(arr
) != 1 ||
757 ARR_DIMS(arr
)[0] != numargs
||
759 ARR_ELEMTYPE(arr
) != CHAROID
)
760 elog(ERROR
, "proargmodes is not a 1-D char array");
761 *p_argmodes
= (char *) palloc(numargs
* sizeof(char));
762 memcpy(*p_argmodes
, ARR_DATA_PTR(arr
),
763 numargs
* sizeof(char));
771 * get_func_result_name
773 * If the function has exactly one output parameter, and that parameter
774 * is named, return the name (as a palloc'd string). Else return NULL.
776 * This is used to determine the default output column name for functions
777 * returning scalar types.
780 get_func_result_name(Oid functionId
)
795 /* First fetch the function's pg_proc row */
796 procTuple
= SearchSysCache(PROCOID
,
797 ObjectIdGetDatum(functionId
),
799 if (!HeapTupleIsValid(procTuple
))
800 elog(ERROR
, "cache lookup failed for function %u", functionId
);
802 /* If there are no named OUT parameters, return NULL */
803 if (heap_attisnull(procTuple
, Anum_pg_proc_proargmodes
) ||
804 heap_attisnull(procTuple
, Anum_pg_proc_proargnames
))
808 /* Get the data out of the tuple */
809 proargmodes
= SysCacheGetAttr(PROCOID
, procTuple
,
810 Anum_pg_proc_proargmodes
,
813 proargnames
= SysCacheGetAttr(PROCOID
, procTuple
,
814 Anum_pg_proc_proargnames
,
819 * We expect the arrays to be 1-D arrays of the right types; verify
820 * that. For the char array, we don't need to use deconstruct_array()
821 * since the array data is just going to look like a C array of
824 arr
= DatumGetArrayTypeP(proargmodes
); /* ensure not toasted */
825 numargs
= ARR_DIMS(arr
)[0];
826 if (ARR_NDIM(arr
) != 1 ||
829 ARR_ELEMTYPE(arr
) != CHAROID
)
830 elog(ERROR
, "proargmodes is not a 1-D char array");
831 argmodes
= (char *) ARR_DATA_PTR(arr
);
832 arr
= DatumGetArrayTypeP(proargnames
); /* ensure not toasted */
833 if (ARR_NDIM(arr
) != 1 ||
834 ARR_DIMS(arr
)[0] != numargs
||
836 ARR_ELEMTYPE(arr
) != TEXTOID
)
837 elog(ERROR
, "proargnames is not a 1-D text array");
838 deconstruct_array(arr
, TEXTOID
, -1, false, 'i',
839 &argnames
, NULL
, &nargnames
);
840 Assert(nargnames
== numargs
);
842 /* scan for output argument(s) */
845 for (i
= 0; i
< numargs
; i
++)
847 if (argmodes
[i
] == PROARGMODE_IN
||
848 argmodes
[i
] == PROARGMODE_VARIADIC
)
850 Assert(argmodes
[i
] == PROARGMODE_OUT
||
851 argmodes
[i
] == PROARGMODE_INOUT
||
852 argmodes
[i
] == PROARGMODE_TABLE
);
853 if (++numoutargs
> 1)
855 /* multiple out args, so forget it */
859 result
= TextDatumGetCString(argnames
[i
]);
860 if (result
== NULL
|| result
[0] == '\0')
862 /* Parameter is not named, so forget it */
869 ReleaseSysCache(procTuple
);
876 * build_function_result_tupdesc_t
878 * Given a pg_proc row for a function, return a tuple descriptor for the
879 * result rowtype, or NULL if the function does not have OUT parameters.
881 * Note that this does not handle resolution of polymorphic types;
882 * that is deliberate.
885 build_function_result_tupdesc_t(HeapTuple procTuple
)
887 Form_pg_proc procform
= (Form_pg_proc
) GETSTRUCT(procTuple
);
888 Datum proallargtypes
;
893 /* Return NULL if the function isn't declared to return RECORD */
894 if (procform
->prorettype
!= RECORDOID
)
897 /* If there are no OUT parameters, return NULL */
898 if (heap_attisnull(procTuple
, Anum_pg_proc_proallargtypes
) ||
899 heap_attisnull(procTuple
, Anum_pg_proc_proargmodes
))
902 /* Get the data out of the tuple */
903 proallargtypes
= SysCacheGetAttr(PROCOID
, procTuple
,
904 Anum_pg_proc_proallargtypes
,
907 proargmodes
= SysCacheGetAttr(PROCOID
, procTuple
,
908 Anum_pg_proc_proargmodes
,
911 proargnames
= SysCacheGetAttr(PROCOID
, procTuple
,
912 Anum_pg_proc_proargnames
,
915 proargnames
= PointerGetDatum(NULL
); /* just to be sure */
917 return build_function_result_tupdesc_d(proallargtypes
,
923 * build_function_result_tupdesc_d
925 * Build a RECORD function's tupledesc from the pg_proc proallargtypes,
926 * proargmodes, and proargnames arrays. This is split out for the
927 * convenience of ProcedureCreate, which needs to be able to compute the
928 * tupledesc before actually creating the function.
930 * Returns NULL if there are not at least two OUT or INOUT arguments.
933 build_function_result_tupdesc_d(Datum proallargtypes
,
942 Datum
*argnames
= NULL
;
949 /* Can't have output args if columns are null */
950 if (proallargtypes
== PointerGetDatum(NULL
) ||
951 proargmodes
== PointerGetDatum(NULL
))
955 * We expect the arrays to be 1-D arrays of the right types; verify that.
956 * For the OID and char arrays, we don't need to use deconstruct_array()
957 * since the array data is just going to look like a C array of values.
959 arr
= DatumGetArrayTypeP(proallargtypes
); /* ensure not toasted */
960 numargs
= ARR_DIMS(arr
)[0];
961 if (ARR_NDIM(arr
) != 1 ||
964 ARR_ELEMTYPE(arr
) != OIDOID
)
965 elog(ERROR
, "proallargtypes is not a 1-D Oid array");
966 argtypes
= (Oid
*) ARR_DATA_PTR(arr
);
967 arr
= DatumGetArrayTypeP(proargmodes
); /* ensure not toasted */
968 if (ARR_NDIM(arr
) != 1 ||
969 ARR_DIMS(arr
)[0] != numargs
||
971 ARR_ELEMTYPE(arr
) != CHAROID
)
972 elog(ERROR
, "proargmodes is not a 1-D char array");
973 argmodes
= (char *) ARR_DATA_PTR(arr
);
974 if (proargnames
!= PointerGetDatum(NULL
))
976 arr
= DatumGetArrayTypeP(proargnames
); /* ensure not toasted */
977 if (ARR_NDIM(arr
) != 1 ||
978 ARR_DIMS(arr
)[0] != numargs
||
980 ARR_ELEMTYPE(arr
) != TEXTOID
)
981 elog(ERROR
, "proargnames is not a 1-D text array");
982 deconstruct_array(arr
, TEXTOID
, -1, false, 'i',
983 &argnames
, NULL
, &nargnames
);
984 Assert(nargnames
== numargs
);
987 /* zero elements probably shouldn't happen, but handle it gracefully */
991 /* extract output-argument types and names */
992 outargtypes
= (Oid
*) palloc(numargs
* sizeof(Oid
));
993 outargnames
= (char **) palloc(numargs
* sizeof(char *));
995 for (i
= 0; i
< numargs
; i
++)
999 if (argmodes
[i
] == PROARGMODE_IN
||
1000 argmodes
[i
] == PROARGMODE_VARIADIC
)
1002 Assert(argmodes
[i
] == PROARGMODE_OUT
||
1003 argmodes
[i
] == PROARGMODE_INOUT
||
1004 argmodes
[i
] == PROARGMODE_TABLE
);
1005 outargtypes
[numoutargs
] = argtypes
[i
];
1007 pname
= TextDatumGetCString(argnames
[i
]);
1010 if (pname
== NULL
|| pname
[0] == '\0')
1012 /* Parameter is not named, so gin up a column name */
1013 pname
= (char *) palloc(32);
1014 snprintf(pname
, 32, "column%d", numoutargs
+ 1);
1016 outargnames
[numoutargs
] = pname
;
1021 * If there is no output argument, or only one, the function does not
1027 desc
= CreateTemplateTupleDesc(numoutargs
, false);
1028 for (i
= 0; i
< numoutargs
; i
++)
1030 TupleDescInitEntry(desc
, i
+ 1,
1042 * RelationNameGetTupleDesc
1044 * Given a (possibly qualified) relation name, build a TupleDesc.
1046 * Note: while this works as advertised, it's seldom the best way to
1047 * build a tupdesc for a function's result type. It's kept around
1048 * only for backwards compatibility with existing user-written code.
1051 RelationNameGetTupleDesc(const char *relname
)
1058 /* Open relation and copy the tuple description */
1059 relname_list
= stringToQualifiedNameList(relname
);
1060 relvar
= makeRangeVarFromNameList(relname_list
);
1061 rel
= relation_openrv(relvar
, AccessShareLock
);
1062 tupdesc
= CreateTupleDescCopy(RelationGetDescr(rel
));
1063 relation_close(rel
, AccessShareLock
);
1071 * Given a type Oid, build a TupleDesc. (In most cases you should be
1072 * using get_call_result_type or one of its siblings instead of this
1073 * routine, so that you can handle OUT parameters, RECORD result type,
1074 * and polymorphic results.)
1076 * If the type is composite, *and* a colaliases List is provided, *and*
1077 * the List is of natts length, use the aliases instead of the relation
1078 * attnames. (NB: this usage is deprecated since it may result in
1079 * creation of unnecessary transient record types.)
1081 * If the type is a base type, a single item alias List is required.
1084 TypeGetTupleDesc(Oid typeoid
, List
*colaliases
)
1086 TypeFuncClass functypclass
= get_type_func_class(typeoid
);
1087 TupleDesc tupdesc
= NULL
;
1090 * Build a suitable tupledesc representing the output rows
1092 if (functypclass
== TYPEFUNC_COMPOSITE
)
1094 /* Composite data type, e.g. a table's row type */
1095 tupdesc
= lookup_rowtype_tupdesc_copy(typeoid
, -1);
1097 if (colaliases
!= NIL
)
1099 int natts
= tupdesc
->natts
;
1102 /* does the list length match the number of attributes? */
1103 if (list_length(colaliases
) != natts
)
1105 (errcode(ERRCODE_DATATYPE_MISMATCH
),
1106 errmsg("number of aliases does not match number of columns")));
1108 /* OK, use the aliases instead */
1109 for (varattno
= 0; varattno
< natts
; varattno
++)
1111 char *label
= strVal(list_nth(colaliases
, varattno
));
1114 namestrcpy(&(tupdesc
->attrs
[varattno
]->attname
), label
);
1117 /* The tuple type is now an anonymous record type */
1118 tupdesc
->tdtypeid
= RECORDOID
;
1119 tupdesc
->tdtypmod
= -1;
1122 else if (functypclass
== TYPEFUNC_SCALAR
)
1124 /* Base data type, i.e. scalar */
1127 /* the alias list is required for base types */
1128 if (colaliases
== NIL
)
1130 (errcode(ERRCODE_DATATYPE_MISMATCH
),
1131 errmsg("no column alias was provided")));
1133 /* the alias list length must be 1 */
1134 if (list_length(colaliases
) != 1)
1136 (errcode(ERRCODE_DATATYPE_MISMATCH
),
1137 errmsg("number of aliases does not match number of columns")));
1139 /* OK, get the column alias */
1140 attname
= strVal(linitial(colaliases
));
1142 tupdesc
= CreateTemplateTupleDesc(1, false);
1143 TupleDescInitEntry(tupdesc
,
1150 else if (functypclass
== TYPEFUNC_RECORD
)
1152 /* XXX can't support this because typmod wasn't passed in ... */
1154 (errcode(ERRCODE_DATATYPE_MISMATCH
),
1155 errmsg("could not determine row description for function returning record")));
1159 /* crummy error message, but parser should have caught this */
1160 elog(ERROR
, "function in FROM has unsupported return type");