1 /*-------------------------------------------------------------------------
4 * Utility and convenience functions for fmgr functions that return
5 * sets and/or composite types.
7 * Copyright (c) 2002-2013, PostgreSQL Global Development Group
10 * src/backend/utils/fmgr/funcapi.c
12 *-------------------------------------------------------------------------
16 #include "access/htup_details.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/rel.h"
28 #include "utils/syscache.h"
29 #include "utils/typcache.h"
32 static void shutdown_MultiFuncCall(Datum arg);
33 static TypeFuncClass internal_get_result_type(Oid funcid,
35 ReturnSetInfo *rsinfo,
37 TupleDesc *resultTupleDesc);
38 static bool resolve_polymorphic_tupdesc(TupleDesc tupdesc,
39 oidvector *declared_args,
41 static TypeFuncClass get_type_func_class(Oid typid);
46 * Create an empty FuncCallContext data structure
47 * and do some other basic Multi-function call setup
51 init_MultiFuncCall(PG_FUNCTION_ARGS)
53 FuncCallContext *retval;
56 * Bail if we're called in the wrong context
58 if (fcinfo->resultinfo == NULL || !IsA(fcinfo->resultinfo, ReturnSetInfo))
60 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
61 errmsg("set-valued function called in context that cannot accept a set")));
63 if (fcinfo->flinfo->fn_extra == NULL)
68 ReturnSetInfo *rsi = (ReturnSetInfo *) fcinfo->resultinfo;
69 MemoryContext multi_call_ctx;
72 * Create a suitably long-lived context to hold cross-call data
74 multi_call_ctx = AllocSetContextCreate(fcinfo->flinfo->fn_mcxt,
75 "SRF multi-call context",
76 ALLOCSET_SMALL_MINSIZE,
77 ALLOCSET_SMALL_INITSIZE,
78 ALLOCSET_SMALL_MAXSIZE);
81 * Allocate suitably long-lived space and zero it
83 retval = (FuncCallContext *)
84 MemoryContextAllocZero(multi_call_ctx,
85 sizeof(FuncCallContext));
88 * initialize the elements
90 retval->call_cntr = 0;
91 retval->max_calls = 0;
93 retval->user_fctx = NULL;
94 retval->attinmeta = NULL;
95 retval->tuple_desc = NULL;
96 retval->multi_call_memory_ctx = multi_call_ctx;
99 * save the pointer for cross-call use
101 fcinfo->flinfo->fn_extra = retval;
104 * Ensure we will get shut down cleanly if the exprcontext is not run
107 RegisterExprContextCallback(rsi->econtext,
108 shutdown_MultiFuncCall,
109 PointerGetDatum(fcinfo->flinfo));
113 /* second and subsequent calls */
114 elog(ERROR, "init_MultiFuncCall cannot be called more than once");
116 /* never reached, but keep compiler happy */
126 * Do Multi-function per-call setup
129 per_MultiFuncCall(PG_FUNCTION_ARGS)
131 FuncCallContext *retval = (FuncCallContext *) fcinfo->flinfo->fn_extra;
134 * Clear the TupleTableSlot, if present. This is for safety's sake: the
135 * Slot will be in a long-lived context (it better be, if the
136 * FuncCallContext is pointing to it), but in most usage patterns the
137 * tuples stored in it will be in the function's per-tuple context. So at
138 * the beginning of each call, the Slot will hold a dangling pointer to an
139 * already-recycled tuple. We clear it out here.
141 * Note: use of retval->slot is obsolete as of 8.0, and we expect that it
142 * will always be NULL. This is just here for backwards compatibility in
143 * case someone creates a slot anyway.
145 if (retval->slot != NULL)
146 ExecClearTuple(retval->slot);
153 * Clean up after init_MultiFuncCall
156 end_MultiFuncCall(PG_FUNCTION_ARGS, FuncCallContext *funcctx)
158 ReturnSetInfo *rsi = (ReturnSetInfo *) fcinfo->resultinfo;
160 /* Deregister the shutdown callback */
161 UnregisterExprContextCallback(rsi->econtext,
162 shutdown_MultiFuncCall,
163 PointerGetDatum(fcinfo->flinfo));
165 /* But use it to do the real work */
166 shutdown_MultiFuncCall(PointerGetDatum(fcinfo->flinfo));
170 * shutdown_MultiFuncCall
171 * Shutdown function to clean up after init_MultiFuncCall
174 shutdown_MultiFuncCall(Datum arg)
176 FmgrInfo *flinfo = (FmgrInfo *) DatumGetPointer(arg);
177 FuncCallContext *funcctx = (FuncCallContext *) flinfo->fn_extra;
179 /* unbind from flinfo */
180 flinfo->fn_extra = NULL;
183 * Delete context that holds all multi-call data, including the
184 * FuncCallContext itself
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 = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcid));
304 if (!HeapTupleIsValid(tp))
305 elog(ERROR, "cache lookup failed for function %u", funcid);
306 procform = (Form_pg_proc) GETSTRUCT(tp);
308 rettype = procform->prorettype;
310 /* Check for OUT parameters defining a RECORD result */
311 tupdesc = build_function_result_tupdesc_t(tp);
315 * It has OUT parameters, so it's basically like a regular composite
316 * type, except we have to be able to resolve any polymorphic OUT
320 *resultTypeId = rettype;
322 if (resolve_polymorphic_tupdesc(tupdesc,
323 &procform->proargtypes,
326 if (tupdesc->tdtypeid == RECORDOID &&
327 tupdesc->tdtypmod < 0)
328 assign_record_type_typmod(tupdesc);
330 *resultTupleDesc = tupdesc;
331 result = TYPEFUNC_COMPOSITE;
336 *resultTupleDesc = NULL;
337 result = TYPEFUNC_RECORD;
346 * If scalar polymorphic result, try to resolve it.
348 if (IsPolymorphicType(rettype))
350 Oid newrettype = exprType(call_expr);
352 if (newrettype == InvalidOid) /* this probably should not happen */
354 (errcode(ERRCODE_DATATYPE_MISMATCH),
355 errmsg("could not determine actual result type for function \"%s\" declared to return type %s",
356 NameStr(procform->proname),
357 format_type_be(rettype))));
358 rettype = newrettype;
362 *resultTypeId = rettype;
364 *resultTupleDesc = NULL; /* default result */
366 /* Classify the result type */
367 result = get_type_func_class(rettype);
370 case TYPEFUNC_COMPOSITE:
372 *resultTupleDesc = lookup_rowtype_tupdesc_copy(rettype, -1);
373 /* Named composite types can't have any polymorphic columns */
375 case TYPEFUNC_SCALAR:
377 case TYPEFUNC_RECORD:
378 /* We must get the tupledesc from call context */
379 if (rsinfo && IsA(rsinfo, ReturnSetInfo) &&
380 rsinfo->expectedDesc != NULL)
382 result = TYPEFUNC_COMPOSITE;
384 *resultTupleDesc = rsinfo->expectedDesc;
385 /* Assume no polymorphic columns here, either */
398 * Given the result tuple descriptor for a function with OUT parameters,
399 * replace any polymorphic columns (ANYELEMENT etc) with correct data types
400 * deduced from the input arguments. Returns TRUE if able to deduce all types,
404 resolve_polymorphic_tupdesc(TupleDesc tupdesc, oidvector *declared_args,
407 int natts = tupdesc->natts;
408 int nargs = declared_args->dim1;
409 bool have_anyelement_result = false;
410 bool have_anyarray_result = false;
411 bool have_anyrange_result = false;
412 bool have_anynonarray = false;
413 bool have_anyenum = false;
414 Oid anyelement_type = InvalidOid;
415 Oid anyarray_type = InvalidOid;
416 Oid anyrange_type = InvalidOid;
417 Oid anycollation = InvalidOid;
420 /* See if there are any polymorphic outputs; quick out if not */
421 for (i = 0; i < natts; i++)
423 switch (tupdesc->attrs[i]->atttypid)
426 have_anyelement_result = true;
429 have_anyarray_result = true;
432 have_anyelement_result = true;
433 have_anynonarray = true;
436 have_anyelement_result = true;
440 have_anyrange_result = true;
446 if (!have_anyelement_result && !have_anyarray_result &&
447 !have_anyrange_result)
451 * Otherwise, extract actual datatype(s) from input arguments. (We assume
452 * the parser already validated consistency of the arguments.)
455 return false; /* no hope */
457 for (i = 0; i < nargs; i++)
459 switch (declared_args->values[i])
464 if (!OidIsValid(anyelement_type))
465 anyelement_type = get_call_expr_argtype(call_expr, i);
468 if (!OidIsValid(anyarray_type))
469 anyarray_type = get_call_expr_argtype(call_expr, i);
472 if (!OidIsValid(anyrange_type))
473 anyrange_type = get_call_expr_argtype(call_expr, i);
480 /* If nothing found, parser messed up */
481 if (!OidIsValid(anyelement_type) && !OidIsValid(anyarray_type) &&
482 !OidIsValid(anyrange_type))
485 /* If needed, deduce one polymorphic type from others */
486 if (have_anyelement_result && !OidIsValid(anyelement_type))
488 if (OidIsValid(anyarray_type))
489 anyelement_type = resolve_generic_type(ANYELEMENTOID,
492 if (OidIsValid(anyrange_type))
494 Oid subtype = resolve_generic_type(ANYELEMENTOID,
498 /* check for inconsistent array and range results */
499 if (OidIsValid(anyelement_type) && anyelement_type != subtype)
501 anyelement_type = subtype;
505 if (have_anyarray_result && !OidIsValid(anyarray_type))
506 anyarray_type = resolve_generic_type(ANYARRAYOID,
511 * We can't deduce a range type from other polymorphic inputs, because
512 * there may be multiple range types for the same subtype.
514 if (have_anyrange_result && !OidIsValid(anyrange_type))
517 /* Enforce ANYNONARRAY if needed */
518 if (have_anynonarray && type_is_array(anyelement_type))
521 /* Enforce ANYENUM if needed */
522 if (have_anyenum && !type_is_enum(anyelement_type))
526 * Identify the collation to use for polymorphic OUT parameters. (It'll
527 * necessarily be the same for both anyelement and anyarray.) Note that
528 * range types are not collatable, so any possible internal collation of a
529 * range type is not considered here.
531 if (OidIsValid(anyelement_type))
532 anycollation = get_typcollation(anyelement_type);
533 else if (OidIsValid(anyarray_type))
534 anycollation = get_typcollation(anyarray_type);
536 if (OidIsValid(anycollation))
539 * The types are collatable, so consider whether to use a nondefault
540 * collation. We do so if we can identify the input collation used
543 Oid inputcollation = exprInputCollation(call_expr);
545 if (OidIsValid(inputcollation))
546 anycollation = inputcollation;
549 /* And finally replace the tuple column types as needed */
550 for (i = 0; i < natts; i++)
552 switch (tupdesc->attrs[i]->atttypid)
557 TupleDescInitEntry(tupdesc, i + 1,
558 NameStr(tupdesc->attrs[i]->attname),
562 TupleDescInitEntryCollation(tupdesc, i + 1, anycollation);
565 TupleDescInitEntry(tupdesc, i + 1,
566 NameStr(tupdesc->attrs[i]->attname),
570 TupleDescInitEntryCollation(tupdesc, i + 1, anycollation);
573 TupleDescInitEntry(tupdesc, i + 1,
574 NameStr(tupdesc->attrs[i]->attname),
578 /* no collation should be attached to a range type */
589 * Given the declared argument types and modes for a function, replace any
590 * polymorphic types (ANYELEMENT etc) with correct data types deduced from the
591 * input arguments. Returns TRUE if able to deduce all types, FALSE if not.
592 * This is the same logic as resolve_polymorphic_tupdesc, but with a different
593 * argument representation.
595 * argmodes may be NULL, in which case all arguments are assumed to be IN mode.
598 resolve_polymorphic_argtypes(int numargs, Oid *argtypes, char *argmodes,
601 bool have_anyelement_result = false;
602 bool have_anyarray_result = false;
603 bool have_anyrange_result = false;
604 Oid anyelement_type = InvalidOid;
605 Oid anyarray_type = InvalidOid;
606 Oid anyrange_type = InvalidOid;
610 /* First pass: resolve polymorphic inputs, check for outputs */
612 for (i = 0; i < numargs; i++)
614 char argmode = argmodes ? argmodes[i] : PROARGMODE_IN;
621 if (argmode == PROARGMODE_OUT || argmode == PROARGMODE_TABLE)
622 have_anyelement_result = true;
625 if (!OidIsValid(anyelement_type))
627 anyelement_type = get_call_expr_argtype(call_expr,
629 if (!OidIsValid(anyelement_type))
632 argtypes[i] = anyelement_type;
636 if (argmode == PROARGMODE_OUT || argmode == PROARGMODE_TABLE)
637 have_anyarray_result = true;
640 if (!OidIsValid(anyarray_type))
642 anyarray_type = get_call_expr_argtype(call_expr,
644 if (!OidIsValid(anyarray_type))
647 argtypes[i] = anyarray_type;
651 if (argmode == PROARGMODE_OUT || argmode == PROARGMODE_TABLE)
652 have_anyrange_result = true;
655 if (!OidIsValid(anyrange_type))
657 anyrange_type = get_call_expr_argtype(call_expr,
659 if (!OidIsValid(anyrange_type))
662 argtypes[i] = anyrange_type;
668 if (argmode != PROARGMODE_OUT && argmode != PROARGMODE_TABLE)
673 if (!have_anyelement_result && !have_anyarray_result &&
674 !have_anyrange_result)
677 /* If no input polymorphics, parser messed up */
678 if (!OidIsValid(anyelement_type) && !OidIsValid(anyarray_type) &&
679 !OidIsValid(anyrange_type))
682 /* If needed, deduce one polymorphic type from others */
683 if (have_anyelement_result && !OidIsValid(anyelement_type))
685 if (OidIsValid(anyarray_type))
686 anyelement_type = resolve_generic_type(ANYELEMENTOID,
689 if (OidIsValid(anyrange_type))
691 Oid subtype = resolve_generic_type(ANYELEMENTOID,
695 /* check for inconsistent array and range results */
696 if (OidIsValid(anyelement_type) && anyelement_type != subtype)
698 anyelement_type = subtype;
702 if (have_anyarray_result && !OidIsValid(anyarray_type))
703 anyarray_type = resolve_generic_type(ANYARRAYOID,
708 * We can't deduce a range type from other polymorphic inputs, because
709 * there may be multiple range types for the same subtype.
711 if (have_anyrange_result && !OidIsValid(anyrange_type))
714 /* XXX do we need to enforce ANYNONARRAY or ANYENUM here? I think not */
716 /* And finally replace the output column types as needed */
717 for (i = 0; i < numargs; i++)
724 argtypes[i] = anyelement_type;
727 argtypes[i] = anyarray_type;
730 argtypes[i] = anyrange_type;
741 * get_type_func_class
742 * Given the type OID, obtain its TYPEFUNC classification.
744 * This is intended to centralize a bunch of formerly ad-hoc code for
745 * classifying types. The categories used here are useful for deciding
746 * how to handle functions returning the datatype.
749 get_type_func_class(Oid typid)
751 switch (get_typtype(typid))
753 case TYPTYPE_COMPOSITE:
754 return TYPEFUNC_COMPOSITE;
759 return TYPEFUNC_SCALAR;
761 if (typid == RECORDOID)
762 return TYPEFUNC_RECORD;
765 * We treat VOID and CSTRING as legitimate scalar datatypes,
766 * mostly for the convenience of the JDBC driver (which wants to
767 * be able to do "SELECT * FROM foo()" for all legitimately
768 * user-callable functions).
770 if (typid == VOIDOID || typid == CSTRINGOID)
771 return TYPEFUNC_SCALAR;
772 return TYPEFUNC_OTHER;
774 /* shouldn't get here, probably */
775 return TYPEFUNC_OTHER;
782 * Fetch info about the argument types, names, and IN/OUT modes from the
783 * pg_proc tuple. Return value is the total number of arguments.
784 * Other results are palloc'd. *p_argtypes is always filled in, but
785 * *p_argnames and *p_argmodes will be set NULL in the default cases
786 * (no names, and all IN arguments, respectively).
788 * Note that this function simply fetches what is in the pg_proc tuple;
789 * it doesn't do any interpretation of polymorphic types.
792 get_func_arg_info(HeapTuple procTup,
793 Oid **p_argtypes, char ***p_argnames, char **p_argmodes)
795 Form_pg_proc procStruct = (Form_pg_proc) GETSTRUCT(procTup);
796 Datum proallargtypes;
806 /* First discover the total number of parameters and get their types */
807 proallargtypes = SysCacheGetAttr(PROCOID, procTup,
808 Anum_pg_proc_proallargtypes,
813 * We expect the arrays to be 1-D arrays of the right types; verify
814 * that. For the OID and char arrays, we don't need to use
815 * deconstruct_array() since the array data is just going to look like
816 * a C array of values.
818 arr = DatumGetArrayTypeP(proallargtypes); /* ensure not toasted */
819 numargs = ARR_DIMS(arr)[0];
820 if (ARR_NDIM(arr) != 1 ||
823 ARR_ELEMTYPE(arr) != OIDOID)
824 elog(ERROR, "proallargtypes is not a 1-D Oid array");
825 Assert(numargs >= procStruct->pronargs);
826 *p_argtypes = (Oid *) palloc(numargs * sizeof(Oid));
827 memcpy(*p_argtypes, ARR_DATA_PTR(arr),
828 numargs * sizeof(Oid));
832 /* If no proallargtypes, use proargtypes */
833 numargs = procStruct->proargtypes.dim1;
834 Assert(numargs == procStruct->pronargs);
835 *p_argtypes = (Oid *) palloc(numargs * sizeof(Oid));
836 memcpy(*p_argtypes, procStruct->proargtypes.values,
837 numargs * sizeof(Oid));
840 /* Get argument names, if available */
841 proargnames = SysCacheGetAttr(PROCOID, procTup,
842 Anum_pg_proc_proargnames,
848 deconstruct_array(DatumGetArrayTypeP(proargnames),
849 TEXTOID, -1, false, 'i',
850 &elems, NULL, &nelems);
851 if (nelems != numargs) /* should not happen */
852 elog(ERROR, "proargnames must have the same number of elements as the function has arguments");
853 *p_argnames = (char **) palloc(sizeof(char *) * numargs);
854 for (i = 0; i < numargs; i++)
855 (*p_argnames)[i] = TextDatumGetCString(elems[i]);
858 /* Get argument modes, if available */
859 proargmodes = SysCacheGetAttr(PROCOID, procTup,
860 Anum_pg_proc_proargmodes,
866 arr = DatumGetArrayTypeP(proargmodes); /* ensure not toasted */
867 if (ARR_NDIM(arr) != 1 ||
868 ARR_DIMS(arr)[0] != numargs ||
870 ARR_ELEMTYPE(arr) != CHAROID)
871 elog(ERROR, "proargmodes is not a 1-D char array");
872 *p_argmodes = (char *) palloc(numargs * sizeof(char));
873 memcpy(*p_argmodes, ARR_DATA_PTR(arr),
874 numargs * sizeof(char));
882 * get_func_input_arg_names
884 * Extract the names of input arguments only, given a function's
885 * proargnames and proargmodes entries in Datum form.
887 * Returns the number of input arguments, which is the length of the
888 * palloc'd array returned to *arg_names. Entries for unnamed args
889 * are set to NULL. You don't get anything if proargnames is NULL.
892 get_func_input_arg_names(Datum proargnames, Datum proargmodes,
903 /* Do nothing if null proargnames */
904 if (proargnames == PointerGetDatum(NULL))
911 * We expect the arrays to be 1-D arrays of the right types; verify that.
912 * For proargmodes, we don't need to use deconstruct_array() since the
913 * array data is just going to look like a C array of values.
915 arr = DatumGetArrayTypeP(proargnames); /* ensure not toasted */
916 if (ARR_NDIM(arr) != 1 ||
918 ARR_ELEMTYPE(arr) != TEXTOID)
919 elog(ERROR, "proargnames is not a 1-D text array");
920 deconstruct_array(arr, TEXTOID, -1, false, 'i',
921 &argnames, NULL, &numargs);
922 if (proargmodes != PointerGetDatum(NULL))
924 arr = DatumGetArrayTypeP(proargmodes); /* ensure not toasted */
925 if (ARR_NDIM(arr) != 1 ||
926 ARR_DIMS(arr)[0] != numargs ||
928 ARR_ELEMTYPE(arr) != CHAROID)
929 elog(ERROR, "proargmodes is not a 1-D char array");
930 argmodes = (char *) ARR_DATA_PTR(arr);
935 /* zero elements probably shouldn't happen, but handle it gracefully */
942 /* extract input-argument names */
943 inargnames = (char **) palloc(numargs * sizeof(char *));
945 for (i = 0; i < numargs; i++)
947 if (argmodes == NULL ||
948 argmodes[i] == PROARGMODE_IN ||
949 argmodes[i] == PROARGMODE_INOUT ||
950 argmodes[i] == PROARGMODE_VARIADIC)
952 char *pname = TextDatumGetCString(argnames[i]);
954 if (pname[0] != '\0')
955 inargnames[numinargs] = pname;
957 inargnames[numinargs] = NULL;
962 *arg_names = inargnames;
968 * get_func_result_name
970 * If the function has exactly one output parameter, and that parameter
971 * is named, return the name (as a palloc'd string). Else return NULL.
973 * This is used to determine the default output column name for functions
974 * returning scalar types.
977 get_func_result_name(Oid functionId)
992 /* First fetch the function's pg_proc row */
993 procTuple = SearchSysCache1(PROCOID, ObjectIdGetDatum(functionId));
994 if (!HeapTupleIsValid(procTuple))
995 elog(ERROR, "cache lookup failed for function %u", functionId);
997 /* If there are no named OUT parameters, return NULL */
998 if (heap_attisnull(procTuple, Anum_pg_proc_proargmodes) ||
999 heap_attisnull(procTuple, Anum_pg_proc_proargnames))
1003 /* Get the data out of the tuple */
1004 proargmodes = SysCacheGetAttr(PROCOID, procTuple,
1005 Anum_pg_proc_proargmodes,
1008 proargnames = SysCacheGetAttr(PROCOID, procTuple,
1009 Anum_pg_proc_proargnames,
1014 * We expect the arrays to be 1-D arrays of the right types; verify
1015 * that. For the char array, we don't need to use deconstruct_array()
1016 * since the array data is just going to look like a C array of
1019 arr = DatumGetArrayTypeP(proargmodes); /* ensure not toasted */
1020 numargs = ARR_DIMS(arr)[0];
1021 if (ARR_NDIM(arr) != 1 ||
1024 ARR_ELEMTYPE(arr) != CHAROID)
1025 elog(ERROR, "proargmodes is not a 1-D char array");
1026 argmodes = (char *) ARR_DATA_PTR(arr);
1027 arr = DatumGetArrayTypeP(proargnames); /* ensure not toasted */
1028 if (ARR_NDIM(arr) != 1 ||
1029 ARR_DIMS(arr)[0] != numargs ||
1031 ARR_ELEMTYPE(arr) != TEXTOID)
1032 elog(ERROR, "proargnames is not a 1-D text array");
1033 deconstruct_array(arr, TEXTOID, -1, false, 'i',
1034 &argnames, NULL, &nargnames);
1035 Assert(nargnames == numargs);
1037 /* scan for output argument(s) */
1040 for (i = 0; i < numargs; i++)
1042 if (argmodes[i] == PROARGMODE_IN ||
1043 argmodes[i] == PROARGMODE_VARIADIC)
1045 Assert(argmodes[i] == PROARGMODE_OUT ||
1046 argmodes[i] == PROARGMODE_INOUT ||
1047 argmodes[i] == PROARGMODE_TABLE);
1048 if (++numoutargs > 1)
1050 /* multiple out args, so forget it */
1054 result = TextDatumGetCString(argnames[i]);
1055 if (result == NULL || result[0] == '\0')
1057 /* Parameter is not named, so forget it */
1064 ReleaseSysCache(procTuple);
1071 * build_function_result_tupdesc_t
1073 * Given a pg_proc row for a function, return a tuple descriptor for the
1074 * result rowtype, or NULL if the function does not have OUT parameters.
1076 * Note that this does not handle resolution of polymorphic types;
1077 * that is deliberate.
1080 build_function_result_tupdesc_t(HeapTuple procTuple)
1082 Form_pg_proc procform = (Form_pg_proc) GETSTRUCT(procTuple);
1083 Datum proallargtypes;
1088 /* Return NULL if the function isn't declared to return RECORD */
1089 if (procform->prorettype != RECORDOID)
1092 /* If there are no OUT parameters, return NULL */
1093 if (heap_attisnull(procTuple, Anum_pg_proc_proallargtypes) ||
1094 heap_attisnull(procTuple, Anum_pg_proc_proargmodes))
1097 /* Get the data out of the tuple */
1098 proallargtypes = SysCacheGetAttr(PROCOID, procTuple,
1099 Anum_pg_proc_proallargtypes,
1102 proargmodes = SysCacheGetAttr(PROCOID, procTuple,
1103 Anum_pg_proc_proargmodes,
1106 proargnames = SysCacheGetAttr(PROCOID, procTuple,
1107 Anum_pg_proc_proargnames,
1110 proargnames = PointerGetDatum(NULL); /* just to be sure */
1112 return build_function_result_tupdesc_d(proallargtypes,
1118 * build_function_result_tupdesc_d
1120 * Build a RECORD function's tupledesc from the pg_proc proallargtypes,
1121 * proargmodes, and proargnames arrays. This is split out for the
1122 * convenience of ProcedureCreate, which needs to be able to compute the
1123 * tupledesc before actually creating the function.
1125 * Returns NULL if there are not at least two OUT or INOUT arguments.
1128 build_function_result_tupdesc_d(Datum proallargtypes,
1137 Datum *argnames = NULL;
1144 /* Can't have output args if columns are null */
1145 if (proallargtypes == PointerGetDatum(NULL) ||
1146 proargmodes == PointerGetDatum(NULL))
1150 * We expect the arrays to be 1-D arrays of the right types; verify that.
1151 * For the OID and char arrays, we don't need to use deconstruct_array()
1152 * since the array data is just going to look like a C array of values.
1154 arr = DatumGetArrayTypeP(proallargtypes); /* ensure not toasted */
1155 numargs = ARR_DIMS(arr)[0];
1156 if (ARR_NDIM(arr) != 1 ||
1159 ARR_ELEMTYPE(arr) != OIDOID)
1160 elog(ERROR, "proallargtypes is not a 1-D Oid array");
1161 argtypes = (Oid *) ARR_DATA_PTR(arr);
1162 arr = DatumGetArrayTypeP(proargmodes); /* ensure not toasted */
1163 if (ARR_NDIM(arr) != 1 ||
1164 ARR_DIMS(arr)[0] != numargs ||
1166 ARR_ELEMTYPE(arr) != CHAROID)
1167 elog(ERROR, "proargmodes is not a 1-D char array");
1168 argmodes = (char *) ARR_DATA_PTR(arr);
1169 if (proargnames != PointerGetDatum(NULL))
1171 arr = DatumGetArrayTypeP(proargnames); /* ensure not toasted */
1172 if (ARR_NDIM(arr) != 1 ||
1173 ARR_DIMS(arr)[0] != numargs ||
1175 ARR_ELEMTYPE(arr) != TEXTOID)
1176 elog(ERROR, "proargnames is not a 1-D text array");
1177 deconstruct_array(arr, TEXTOID, -1, false, 'i',
1178 &argnames, NULL, &nargnames);
1179 Assert(nargnames == numargs);
1182 /* zero elements probably shouldn't happen, but handle it gracefully */
1186 /* extract output-argument types and names */
1187 outargtypes = (Oid *) palloc(numargs * sizeof(Oid));
1188 outargnames = (char **) palloc(numargs * sizeof(char *));
1190 for (i = 0; i < numargs; i++)
1194 if (argmodes[i] == PROARGMODE_IN ||
1195 argmodes[i] == PROARGMODE_VARIADIC)
1197 Assert(argmodes[i] == PROARGMODE_OUT ||
1198 argmodes[i] == PROARGMODE_INOUT ||
1199 argmodes[i] == PROARGMODE_TABLE);
1200 outargtypes[numoutargs] = argtypes[i];
1202 pname = TextDatumGetCString(argnames[i]);
1205 if (pname == NULL || pname[0] == '\0')
1207 /* Parameter is not named, so gin up a column name */
1208 pname = psprintf("column%d", numoutargs + 1);
1210 outargnames[numoutargs] = pname;
1215 * If there is no output argument, or only one, the function does not
1221 desc = CreateTemplateTupleDesc(numoutargs, false);
1222 for (i = 0; i < numoutargs; i++)
1224 TupleDescInitEntry(desc, i + 1,
1236 * RelationNameGetTupleDesc
1238 * Given a (possibly qualified) relation name, build a TupleDesc.
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.
1245 RelationNameGetTupleDesc(const char *relname)
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);
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.)
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.)
1275 * If the type is a base type, a single item alias List is required.
1278 TypeGetTupleDesc(Oid typeoid, List *colaliases)
1280 TypeFuncClass functypclass = get_type_func_class(typeoid);
1281 TupleDesc tupdesc = NULL;
1284 * Build a suitable tupledesc representing the output rows
1286 if (functypclass == TYPEFUNC_COMPOSITE)
1288 /* Composite data type, e.g. a table's row type */
1289 tupdesc = lookup_rowtype_tupdesc_copy(typeoid, -1);
1291 if (colaliases != NIL)
1293 int natts = tupdesc->natts;
1296 /* does the list length match the number of attributes? */
1297 if (list_length(colaliases) != natts)
1299 (errcode(ERRCODE_DATATYPE_MISMATCH),
1300 errmsg("number of aliases does not match number of columns")));
1302 /* OK, use the aliases instead */
1303 for (varattno = 0; varattno < natts; varattno++)
1305 char *label = strVal(list_nth(colaliases, varattno));
1308 namestrcpy(&(tupdesc->attrs[varattno]->attname), label);
1311 /* The tuple type is now an anonymous record type */
1312 tupdesc->tdtypeid = RECORDOID;
1313 tupdesc->tdtypmod = -1;
1316 else if (functypclass == TYPEFUNC_SCALAR)
1318 /* Base data type, i.e. scalar */
1321 /* the alias list is required for base types */
1322 if (colaliases == NIL)
1324 (errcode(ERRCODE_DATATYPE_MISMATCH),
1325 errmsg("no column alias was provided")));
1327 /* the alias list length must be 1 */
1328 if (list_length(colaliases) != 1)
1330 (errcode(ERRCODE_DATATYPE_MISMATCH),
1331 errmsg("number of aliases does not match number of columns")));
1333 /* OK, get the column alias */
1334 attname = strVal(linitial(colaliases));
1336 tupdesc = CreateTemplateTupleDesc(1, false);
1337 TupleDescInitEntry(tupdesc,
1344 else if (functypclass == TYPEFUNC_RECORD)
1346 /* XXX can't support this because typmod wasn't passed in ... */
1348 (errcode(ERRCODE_DATATYPE_MISMATCH),
1349 errmsg("could not determine row description for function returning record")));
1353 /* crummy error message, but parser should have caught this */
1354 elog(ERROR, "function in FROM has unsupported return type");