1 /*-------------------------------------------------------------------------
4 * Utility and convenience functions for fmgr functions that return
5 * sets and/or composite types, or deal with VARIADIC inputs.
7 * Copyright (c) 2002-2017, 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/regproc.h"
28 #include "utils/rel.h"
29 #include "utils/syscache.h"
30 #include "utils/typcache.h"
33 static void shutdown_MultiFuncCall(Datum arg);
34 static TypeFuncClass internal_get_result_type(Oid funcid,
36 ReturnSetInfo *rsinfo,
38 TupleDesc *resultTupleDesc);
39 static bool resolve_polymorphic_tupdesc(TupleDesc tupdesc,
40 oidvector *declared_args,
42 static TypeFuncClass get_type_func_class(Oid typid);
47 * Create an empty FuncCallContext data structure
48 * and do some other basic Multi-function call setup
52 init_MultiFuncCall(PG_FUNCTION_ARGS)
54 FuncCallContext *retval;
57 * Bail if we're called in the wrong context
59 if (fcinfo->resultinfo == NULL || !IsA(fcinfo->resultinfo, ReturnSetInfo))
61 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
62 errmsg("set-valued function called in context that cannot accept a set")));
64 if (fcinfo->flinfo->fn_extra == NULL)
69 ReturnSetInfo *rsi = (ReturnSetInfo *) fcinfo->resultinfo;
70 MemoryContext multi_call_ctx;
73 * Create a suitably long-lived context to hold cross-call data
75 multi_call_ctx = AllocSetContextCreate(fcinfo->flinfo->fn_mcxt,
76 "SRF multi-call context",
77 ALLOCSET_SMALL_SIZES);
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 MemoryContextDelete(funcctx->multi_call_memory_ctx);
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.
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.
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.
207 * This function is relatively expensive --- in a function returning set,
208 * try to call it only the first time through.
211 get_call_result_type(FunctionCallInfo fcinfo,
213 TupleDesc *resultTupleDesc)
215 return internal_get_result_type(fcinfo->flinfo->fn_oid,
216 fcinfo->flinfo->fn_expr,
217 (ReturnSetInfo *) fcinfo->resultinfo,
223 * get_expr_result_type
224 * As above, but work from a calling expression node tree
227 get_expr_result_type(Node *expr,
229 TupleDesc *resultTupleDesc)
231 TypeFuncClass result;
233 if (expr && IsA(expr, FuncExpr))
234 result = internal_get_result_type(((FuncExpr *) expr)->funcid,
239 else if (expr && IsA(expr, OpExpr))
240 result = internal_get_result_type(get_opcode(((OpExpr *) expr)->opno),
247 /* handle as a generic expression; no chance to resolve RECORD */
248 Oid typid = exprType(expr);
251 *resultTypeId = typid;
253 *resultTupleDesc = NULL;
254 result = get_type_func_class(typid);
255 if (result == TYPEFUNC_COMPOSITE && resultTupleDesc)
256 *resultTupleDesc = lookup_rowtype_tupdesc_copy(typid, -1);
263 * get_func_result_type
264 * As above, but work from a function's OID only
266 * This will not be able to resolve pure-RECORD results nor polymorphism.
269 get_func_result_type(Oid functionId,
271 TupleDesc *resultTupleDesc)
273 return internal_get_result_type(functionId,
281 * internal_get_result_type -- workhorse code implementing all the above
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.
289 internal_get_result_type(Oid funcid,
291 ReturnSetInfo *rsinfo,
293 TupleDesc *resultTupleDesc)
295 TypeFuncClass result;
297 Form_pg_proc procform;
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);
307 rettype = procform->prorettype;
309 /* Check for OUT parameters defining a RECORD result */
310 tupdesc = build_function_result_tupdesc_t(tp);
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
319 *resultTypeId = rettype;
321 if (resolve_polymorphic_tupdesc(tupdesc,
322 &procform->proargtypes,
325 if (tupdesc->tdtypeid == RECORDOID &&
326 tupdesc->tdtypmod < 0)
327 assign_record_type_typmod(tupdesc);
329 *resultTupleDesc = tupdesc;
330 result = TYPEFUNC_COMPOSITE;
335 *resultTupleDesc = NULL;
336 result = TYPEFUNC_RECORD;
345 * If scalar polymorphic result, try to resolve it.
347 if (IsPolymorphicType(rettype))
349 Oid newrettype = exprType(call_expr);
351 if (newrettype == InvalidOid) /* this probably should not happen */
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;
361 *resultTypeId = rettype;
363 *resultTupleDesc = NULL; /* default result */
365 /* Classify the result type */
366 result = get_type_func_class(rettype);
369 case TYPEFUNC_COMPOSITE:
371 *resultTupleDesc = lookup_rowtype_tupdesc_copy(rettype, -1);
372 /* Named composite types can't have any polymorphic columns */
374 case TYPEFUNC_SCALAR:
376 case TYPEFUNC_RECORD:
377 /* We must get the tupledesc from call context */
378 if (rsinfo && IsA(rsinfo, ReturnSetInfo) &&
379 rsinfo->expectedDesc != NULL)
381 result = TYPEFUNC_COMPOSITE;
383 *resultTupleDesc = rsinfo->expectedDesc;
384 /* Assume no polymorphic columns here, either */
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,
403 resolve_polymorphic_tupdesc(TupleDesc tupdesc, oidvector *declared_args,
406 int natts = tupdesc->natts;
407 int nargs = declared_args->dim1;
408 bool have_anyelement_result = false;
409 bool have_anyarray_result = false;
410 bool have_anyrange_result = false;
411 bool have_anynonarray = false;
412 bool have_anyenum = false;
413 Oid anyelement_type = InvalidOid;
414 Oid anyarray_type = InvalidOid;
415 Oid anyrange_type = InvalidOid;
416 Oid anycollation = InvalidOid;
419 /* See if there are any polymorphic outputs; quick out if not */
420 for (i = 0; i < natts; i++)
422 switch (TupleDescAttr(tupdesc, 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;
439 have_anyrange_result = true;
445 if (!have_anyelement_result && !have_anyarray_result &&
446 !have_anyrange_result)
450 * Otherwise, extract actual datatype(s) from input arguments. (We assume
451 * the parser already validated consistency of the arguments.)
454 return false; /* no hope */
456 for (i = 0; i < nargs; i++)
458 switch (declared_args->values[i])
463 if (!OidIsValid(anyelement_type))
464 anyelement_type = get_call_expr_argtype(call_expr, i);
467 if (!OidIsValid(anyarray_type))
468 anyarray_type = get_call_expr_argtype(call_expr, i);
471 if (!OidIsValid(anyrange_type))
472 anyrange_type = get_call_expr_argtype(call_expr, i);
479 /* If nothing found, parser messed up */
480 if (!OidIsValid(anyelement_type) && !OidIsValid(anyarray_type) &&
481 !OidIsValid(anyrange_type))
484 /* If needed, deduce one polymorphic type from others */
485 if (have_anyelement_result && !OidIsValid(anyelement_type))
487 if (OidIsValid(anyarray_type))
488 anyelement_type = resolve_generic_type(ANYELEMENTOID,
491 if (OidIsValid(anyrange_type))
493 Oid subtype = resolve_generic_type(ANYELEMENTOID,
497 /* check for inconsistent array and range results */
498 if (OidIsValid(anyelement_type) && anyelement_type != subtype)
500 anyelement_type = subtype;
504 if (have_anyarray_result && !OidIsValid(anyarray_type))
505 anyarray_type = resolve_generic_type(ANYARRAYOID,
510 * We can't deduce a range type from other polymorphic inputs, because
511 * there may be multiple range types for the same subtype.
513 if (have_anyrange_result && !OidIsValid(anyrange_type))
516 /* Enforce ANYNONARRAY if needed */
517 if (have_anynonarray && type_is_array(anyelement_type))
520 /* Enforce ANYENUM if needed */
521 if (have_anyenum && !type_is_enum(anyelement_type))
525 * Identify the collation to use for polymorphic OUT parameters. (It'll
526 * necessarily be the same for both anyelement and anyarray.) Note that
527 * range types are not collatable, so any possible internal collation of a
528 * range type is not considered here.
530 if (OidIsValid(anyelement_type))
531 anycollation = get_typcollation(anyelement_type);
532 else if (OidIsValid(anyarray_type))
533 anycollation = get_typcollation(anyarray_type);
535 if (OidIsValid(anycollation))
538 * The types are collatable, so consider whether to use a nondefault
539 * collation. We do so if we can identify the input collation used
542 Oid inputcollation = exprInputCollation(call_expr);
544 if (OidIsValid(inputcollation))
545 anycollation = inputcollation;
548 /* And finally replace the tuple column types as needed */
549 for (i = 0; i < natts; i++)
551 Form_pg_attribute att = TupleDescAttr(tupdesc, i);
553 switch (att->atttypid)
558 TupleDescInitEntry(tupdesc, i + 1,
559 NameStr(att->attname),
563 TupleDescInitEntryCollation(tupdesc, i + 1, anycollation);
566 TupleDescInitEntry(tupdesc, i + 1,
567 NameStr(att->attname),
571 TupleDescInitEntryCollation(tupdesc, i + 1, anycollation);
574 TupleDescInitEntry(tupdesc, i + 1,
575 NameStr(att->attname),
579 /* no collation should be attached to a range type */
590 * Given the declared argument types and modes for a function, replace any
591 * polymorphic types (ANYELEMENT etc) with correct data types deduced from the
592 * input arguments. Returns TRUE if able to deduce all types, FALSE if not.
593 * This is the same logic as resolve_polymorphic_tupdesc, but with a different
594 * argument representation.
596 * argmodes may be NULL, in which case all arguments are assumed to be IN mode.
599 resolve_polymorphic_argtypes(int numargs, Oid *argtypes, char *argmodes,
602 bool have_anyelement_result = false;
603 bool have_anyarray_result = false;
604 bool have_anyrange_result = false;
605 Oid anyelement_type = InvalidOid;
606 Oid anyarray_type = InvalidOid;
607 Oid anyrange_type = InvalidOid;
611 /* First pass: resolve polymorphic inputs, check for outputs */
613 for (i = 0; i < numargs; i++)
615 char argmode = argmodes ? argmodes[i] : PROARGMODE_IN;
622 if (argmode == PROARGMODE_OUT || argmode == PROARGMODE_TABLE)
623 have_anyelement_result = true;
626 if (!OidIsValid(anyelement_type))
628 anyelement_type = get_call_expr_argtype(call_expr,
630 if (!OidIsValid(anyelement_type))
633 argtypes[i] = anyelement_type;
637 if (argmode == PROARGMODE_OUT || argmode == PROARGMODE_TABLE)
638 have_anyarray_result = true;
641 if (!OidIsValid(anyarray_type))
643 anyarray_type = get_call_expr_argtype(call_expr,
645 if (!OidIsValid(anyarray_type))
648 argtypes[i] = anyarray_type;
652 if (argmode == PROARGMODE_OUT || argmode == PROARGMODE_TABLE)
653 have_anyrange_result = true;
656 if (!OidIsValid(anyrange_type))
658 anyrange_type = get_call_expr_argtype(call_expr,
660 if (!OidIsValid(anyrange_type))
663 argtypes[i] = anyrange_type;
669 if (argmode != PROARGMODE_OUT && argmode != PROARGMODE_TABLE)
674 if (!have_anyelement_result && !have_anyarray_result &&
675 !have_anyrange_result)
678 /* If no input polymorphics, parser messed up */
679 if (!OidIsValid(anyelement_type) && !OidIsValid(anyarray_type) &&
680 !OidIsValid(anyrange_type))
683 /* If needed, deduce one polymorphic type from others */
684 if (have_anyelement_result && !OidIsValid(anyelement_type))
686 if (OidIsValid(anyarray_type))
687 anyelement_type = resolve_generic_type(ANYELEMENTOID,
690 if (OidIsValid(anyrange_type))
692 Oid subtype = resolve_generic_type(ANYELEMENTOID,
696 /* check for inconsistent array and range results */
697 if (OidIsValid(anyelement_type) && anyelement_type != subtype)
699 anyelement_type = subtype;
703 if (have_anyarray_result && !OidIsValid(anyarray_type))
704 anyarray_type = resolve_generic_type(ANYARRAYOID,
709 * We can't deduce a range type from other polymorphic inputs, because
710 * there may be multiple range types for the same subtype.
712 if (have_anyrange_result && !OidIsValid(anyrange_type))
715 /* XXX do we need to enforce ANYNONARRAY or ANYENUM here? I think not */
717 /* And finally replace the output column types as needed */
718 for (i = 0; i < numargs; i++)
725 argtypes[i] = anyelement_type;
728 argtypes[i] = anyarray_type;
731 argtypes[i] = anyrange_type;
742 * get_type_func_class
743 * Given the type OID, obtain its TYPEFUNC classification.
745 * This is intended to centralize a bunch of formerly ad-hoc code for
746 * classifying types. The categories used here are useful for deciding
747 * how to handle functions returning the datatype.
750 get_type_func_class(Oid typid)
752 switch (get_typtype(typid))
754 case TYPTYPE_COMPOSITE:
755 return TYPEFUNC_COMPOSITE;
760 return TYPEFUNC_SCALAR;
762 if (typid == RECORDOID)
763 return TYPEFUNC_RECORD;
766 * We treat VOID and CSTRING as legitimate scalar datatypes,
767 * mostly for the convenience of the JDBC driver (which wants to
768 * be able to do "SELECT * FROM foo()" for all legitimately
769 * user-callable functions).
771 if (typid == VOIDOID || typid == CSTRINGOID)
772 return TYPEFUNC_SCALAR;
773 return TYPEFUNC_OTHER;
775 /* shouldn't get here, probably */
776 return TYPEFUNC_OTHER;
783 * Fetch info about the argument types, names, and IN/OUT modes from the
784 * pg_proc tuple. Return value is the total number of arguments.
785 * Other results are palloc'd. *p_argtypes is always filled in, but
786 * *p_argnames and *p_argmodes will be set NULL in the default cases
787 * (no names, and all IN arguments, respectively).
789 * Note that this function simply fetches what is in the pg_proc tuple;
790 * it doesn't do any interpretation of polymorphic types.
793 get_func_arg_info(HeapTuple procTup,
794 Oid **p_argtypes, char ***p_argnames, char **p_argmodes)
796 Form_pg_proc procStruct = (Form_pg_proc) GETSTRUCT(procTup);
797 Datum proallargtypes;
807 /* First discover the total number of parameters and get their types */
808 proallargtypes = SysCacheGetAttr(PROCOID, procTup,
809 Anum_pg_proc_proallargtypes,
814 * We expect the arrays to be 1-D arrays of the right types; verify
815 * that. For the OID and char arrays, we don't need to use
816 * deconstruct_array() since the array data is just going to look like
817 * a C array of values.
819 arr = DatumGetArrayTypeP(proallargtypes); /* ensure not toasted */
820 numargs = ARR_DIMS(arr)[0];
821 if (ARR_NDIM(arr) != 1 ||
824 ARR_ELEMTYPE(arr) != OIDOID)
825 elog(ERROR, "proallargtypes is not a 1-D Oid array");
826 Assert(numargs >= procStruct->pronargs);
827 *p_argtypes = (Oid *) palloc(numargs * sizeof(Oid));
828 memcpy(*p_argtypes, ARR_DATA_PTR(arr),
829 numargs * sizeof(Oid));
833 /* If no proallargtypes, use proargtypes */
834 numargs = procStruct->proargtypes.dim1;
835 Assert(numargs == procStruct->pronargs);
836 *p_argtypes = (Oid *) palloc(numargs * sizeof(Oid));
837 memcpy(*p_argtypes, procStruct->proargtypes.values,
838 numargs * sizeof(Oid));
841 /* Get argument names, if available */
842 proargnames = SysCacheGetAttr(PROCOID, procTup,
843 Anum_pg_proc_proargnames,
849 deconstruct_array(DatumGetArrayTypeP(proargnames),
850 TEXTOID, -1, false, 'i',
851 &elems, NULL, &nelems);
852 if (nelems != numargs) /* should not happen */
853 elog(ERROR, "proargnames must have the same number of elements as the function has arguments");
854 *p_argnames = (char **) palloc(sizeof(char *) * numargs);
855 for (i = 0; i < numargs; i++)
856 (*p_argnames)[i] = TextDatumGetCString(elems[i]);
859 /* Get argument modes, if available */
860 proargmodes = SysCacheGetAttr(PROCOID, procTup,
861 Anum_pg_proc_proargmodes,
867 arr = DatumGetArrayTypeP(proargmodes); /* ensure not toasted */
868 if (ARR_NDIM(arr) != 1 ||
869 ARR_DIMS(arr)[0] != numargs ||
871 ARR_ELEMTYPE(arr) != CHAROID)
872 elog(ERROR, "proargmodes is not a 1-D char array");
873 *p_argmodes = (char *) palloc(numargs * sizeof(char));
874 memcpy(*p_argmodes, ARR_DATA_PTR(arr),
875 numargs * sizeof(char));
884 * Returns the number of transformed types used by function.
887 get_func_trftypes(HeapTuple procTup,
895 protrftypes = SysCacheGetAttr(PROCOID, procTup,
896 Anum_pg_proc_protrftypes,
901 * We expect the arrays to be 1-D arrays of the right types; verify
902 * that. For the OID and char arrays, we don't need to use
903 * deconstruct_array() since the array data is just going to look like
904 * a C array of values.
906 arr = DatumGetArrayTypeP(protrftypes); /* ensure not toasted */
907 nelems = ARR_DIMS(arr)[0];
908 if (ARR_NDIM(arr) != 1 ||
911 ARR_ELEMTYPE(arr) != OIDOID)
912 elog(ERROR, "protrftypes is not a 1-D Oid array");
913 Assert(nelems >= ((Form_pg_proc) GETSTRUCT(procTup))->pronargs);
914 *p_trftypes = (Oid *) palloc(nelems * sizeof(Oid));
915 memcpy(*p_trftypes, ARR_DATA_PTR(arr),
916 nelems * sizeof(Oid));
925 * get_func_input_arg_names
927 * Extract the names of input arguments only, given a function's
928 * proargnames and proargmodes entries in Datum form.
930 * Returns the number of input arguments, which is the length of the
931 * palloc'd array returned to *arg_names. Entries for unnamed args
932 * are set to NULL. You don't get anything if proargnames is NULL.
935 get_func_input_arg_names(Datum proargnames, Datum proargmodes,
946 /* Do nothing if null proargnames */
947 if (proargnames == PointerGetDatum(NULL))
954 * We expect the arrays to be 1-D arrays of the right types; verify that.
955 * For proargmodes, we don't need to use deconstruct_array() since the
956 * array data is just going to look like a C array of values.
958 arr = DatumGetArrayTypeP(proargnames); /* ensure not toasted */
959 if (ARR_NDIM(arr) != 1 ||
961 ARR_ELEMTYPE(arr) != TEXTOID)
962 elog(ERROR, "proargnames is not a 1-D text array");
963 deconstruct_array(arr, TEXTOID, -1, false, 'i',
964 &argnames, NULL, &numargs);
965 if (proargmodes != PointerGetDatum(NULL))
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);
978 /* zero elements probably shouldn't happen, but handle it gracefully */
985 /* extract input-argument names */
986 inargnames = (char **) palloc(numargs * sizeof(char *));
988 for (i = 0; i < numargs; i++)
990 if (argmodes == NULL ||
991 argmodes[i] == PROARGMODE_IN ||
992 argmodes[i] == PROARGMODE_INOUT ||
993 argmodes[i] == PROARGMODE_VARIADIC)
995 char *pname = TextDatumGetCString(argnames[i]);
997 if (pname[0] != '\0')
998 inargnames[numinargs] = pname;
1000 inargnames[numinargs] = NULL;
1005 *arg_names = inargnames;
1011 * get_func_result_name
1013 * If the function has exactly one output parameter, and that parameter
1014 * is named, return the name (as a palloc'd string). Else return NULL.
1016 * This is used to determine the default output column name for functions
1017 * returning scalar types.
1020 get_func_result_name(Oid functionId)
1023 HeapTuple procTuple;
1035 /* First fetch the function's pg_proc row */
1036 procTuple = SearchSysCache1(PROCOID, ObjectIdGetDatum(functionId));
1037 if (!HeapTupleIsValid(procTuple))
1038 elog(ERROR, "cache lookup failed for function %u", functionId);
1040 /* If there are no named OUT parameters, return NULL */
1041 if (heap_attisnull(procTuple, Anum_pg_proc_proargmodes) ||
1042 heap_attisnull(procTuple, Anum_pg_proc_proargnames))
1046 /* Get the data out of the tuple */
1047 proargmodes = SysCacheGetAttr(PROCOID, procTuple,
1048 Anum_pg_proc_proargmodes,
1051 proargnames = SysCacheGetAttr(PROCOID, procTuple,
1052 Anum_pg_proc_proargnames,
1057 * We expect the arrays to be 1-D arrays of the right types; verify
1058 * that. For the char array, we don't need to use deconstruct_array()
1059 * since the array data is just going to look like a C array of
1062 arr = DatumGetArrayTypeP(proargmodes); /* ensure not toasted */
1063 numargs = ARR_DIMS(arr)[0];
1064 if (ARR_NDIM(arr) != 1 ||
1067 ARR_ELEMTYPE(arr) != CHAROID)
1068 elog(ERROR, "proargmodes is not a 1-D char array");
1069 argmodes = (char *) ARR_DATA_PTR(arr);
1070 arr = DatumGetArrayTypeP(proargnames); /* ensure not toasted */
1071 if (ARR_NDIM(arr) != 1 ||
1072 ARR_DIMS(arr)[0] != numargs ||
1074 ARR_ELEMTYPE(arr) != TEXTOID)
1075 elog(ERROR, "proargnames is not a 1-D text array");
1076 deconstruct_array(arr, TEXTOID, -1, false, 'i',
1077 &argnames, NULL, &nargnames);
1078 Assert(nargnames == numargs);
1080 /* scan for output argument(s) */
1083 for (i = 0; i < numargs; i++)
1085 if (argmodes[i] == PROARGMODE_IN ||
1086 argmodes[i] == PROARGMODE_VARIADIC)
1088 Assert(argmodes[i] == PROARGMODE_OUT ||
1089 argmodes[i] == PROARGMODE_INOUT ||
1090 argmodes[i] == PROARGMODE_TABLE);
1091 if (++numoutargs > 1)
1093 /* multiple out args, so forget it */
1097 result = TextDatumGetCString(argnames[i]);
1098 if (result == NULL || result[0] == '\0')
1100 /* Parameter is not named, so forget it */
1107 ReleaseSysCache(procTuple);
1114 * build_function_result_tupdesc_t
1116 * Given a pg_proc row for a function, return a tuple descriptor for the
1117 * result rowtype, or NULL if the function does not have OUT parameters.
1119 * Note that this does not handle resolution of polymorphic types;
1120 * that is deliberate.
1123 build_function_result_tupdesc_t(HeapTuple procTuple)
1125 Form_pg_proc procform = (Form_pg_proc) GETSTRUCT(procTuple);
1126 Datum proallargtypes;
1131 /* Return NULL if the function isn't declared to return RECORD */
1132 if (procform->prorettype != RECORDOID)
1135 /* If there are no OUT parameters, return NULL */
1136 if (heap_attisnull(procTuple, Anum_pg_proc_proallargtypes) ||
1137 heap_attisnull(procTuple, Anum_pg_proc_proargmodes))
1140 /* Get the data out of the tuple */
1141 proallargtypes = SysCacheGetAttr(PROCOID, procTuple,
1142 Anum_pg_proc_proallargtypes,
1145 proargmodes = SysCacheGetAttr(PROCOID, procTuple,
1146 Anum_pg_proc_proargmodes,
1149 proargnames = SysCacheGetAttr(PROCOID, procTuple,
1150 Anum_pg_proc_proargnames,
1153 proargnames = PointerGetDatum(NULL); /* just to be sure */
1155 return build_function_result_tupdesc_d(proallargtypes,
1161 * build_function_result_tupdesc_d
1163 * Build a RECORD function's tupledesc from the pg_proc proallargtypes,
1164 * proargmodes, and proargnames arrays. This is split out for the
1165 * convenience of ProcedureCreate, which needs to be able to compute the
1166 * tupledesc before actually creating the function.
1168 * Returns NULL if there are not at least two OUT or INOUT arguments.
1171 build_function_result_tupdesc_d(Datum proallargtypes,
1180 Datum *argnames = NULL;
1187 /* Can't have output args if columns are null */
1188 if (proallargtypes == PointerGetDatum(NULL) ||
1189 proargmodes == PointerGetDatum(NULL))
1193 * We expect the arrays to be 1-D arrays of the right types; verify that.
1194 * For the OID and char arrays, we don't need to use deconstruct_array()
1195 * since the array data is just going to look like a C array of values.
1197 arr = DatumGetArrayTypeP(proallargtypes); /* ensure not toasted */
1198 numargs = ARR_DIMS(arr)[0];
1199 if (ARR_NDIM(arr) != 1 ||
1202 ARR_ELEMTYPE(arr) != OIDOID)
1203 elog(ERROR, "proallargtypes is not a 1-D Oid array");
1204 argtypes = (Oid *) ARR_DATA_PTR(arr);
1205 arr = DatumGetArrayTypeP(proargmodes); /* ensure not toasted */
1206 if (ARR_NDIM(arr) != 1 ||
1207 ARR_DIMS(arr)[0] != numargs ||
1209 ARR_ELEMTYPE(arr) != CHAROID)
1210 elog(ERROR, "proargmodes is not a 1-D char array");
1211 argmodes = (char *) ARR_DATA_PTR(arr);
1212 if (proargnames != PointerGetDatum(NULL))
1214 arr = DatumGetArrayTypeP(proargnames); /* ensure not toasted */
1215 if (ARR_NDIM(arr) != 1 ||
1216 ARR_DIMS(arr)[0] != numargs ||
1218 ARR_ELEMTYPE(arr) != TEXTOID)
1219 elog(ERROR, "proargnames is not a 1-D text array");
1220 deconstruct_array(arr, TEXTOID, -1, false, 'i',
1221 &argnames, NULL, &nargnames);
1222 Assert(nargnames == numargs);
1225 /* zero elements probably shouldn't happen, but handle it gracefully */
1229 /* extract output-argument types and names */
1230 outargtypes = (Oid *) palloc(numargs * sizeof(Oid));
1231 outargnames = (char **) palloc(numargs * sizeof(char *));
1233 for (i = 0; i < numargs; i++)
1237 if (argmodes[i] == PROARGMODE_IN ||
1238 argmodes[i] == PROARGMODE_VARIADIC)
1240 Assert(argmodes[i] == PROARGMODE_OUT ||
1241 argmodes[i] == PROARGMODE_INOUT ||
1242 argmodes[i] == PROARGMODE_TABLE);
1243 outargtypes[numoutargs] = argtypes[i];
1245 pname = TextDatumGetCString(argnames[i]);
1248 if (pname == NULL || pname[0] == '\0')
1250 /* Parameter is not named, so gin up a column name */
1251 pname = psprintf("column%d", numoutargs + 1);
1253 outargnames[numoutargs] = pname;
1258 * If there is no output argument, or only one, the function does not
1264 desc = CreateTemplateTupleDesc(numoutargs, false);
1265 for (i = 0; i < numoutargs; i++)
1267 TupleDescInitEntry(desc, i + 1,
1279 * RelationNameGetTupleDesc
1281 * Given a (possibly qualified) relation name, build a TupleDesc.
1283 * Note: while this works as advertised, it's seldom the best way to
1284 * build a tupdesc for a function's result type. It's kept around
1285 * only for backwards compatibility with existing user-written code.
1288 RelationNameGetTupleDesc(const char *relname)
1295 /* Open relation and copy the tuple description */
1296 relname_list = stringToQualifiedNameList(relname);
1297 relvar = makeRangeVarFromNameList(relname_list);
1298 rel = relation_openrv(relvar, AccessShareLock);
1299 tupdesc = CreateTupleDescCopy(RelationGetDescr(rel));
1300 relation_close(rel, AccessShareLock);
1308 * Given a type Oid, build a TupleDesc. (In most cases you should be
1309 * using get_call_result_type or one of its siblings instead of this
1310 * routine, so that you can handle OUT parameters, RECORD result type,
1311 * and polymorphic results.)
1313 * If the type is composite, *and* a colaliases List is provided, *and*
1314 * the List is of natts length, use the aliases instead of the relation
1315 * attnames. (NB: this usage is deprecated since it may result in
1316 * creation of unnecessary transient record types.)
1318 * If the type is a base type, a single item alias List is required.
1321 TypeGetTupleDesc(Oid typeoid, List *colaliases)
1323 TypeFuncClass functypclass = get_type_func_class(typeoid);
1324 TupleDesc tupdesc = NULL;
1327 * Build a suitable tupledesc representing the output rows
1329 if (functypclass == TYPEFUNC_COMPOSITE)
1331 /* Composite data type, e.g. a table's row type */
1332 tupdesc = lookup_rowtype_tupdesc_copy(typeoid, -1);
1334 if (colaliases != NIL)
1336 int natts = tupdesc->natts;
1339 /* does the list length match the number of attributes? */
1340 if (list_length(colaliases) != natts)
1342 (errcode(ERRCODE_DATATYPE_MISMATCH),
1343 errmsg("number of aliases does not match number of columns")));
1345 /* OK, use the aliases instead */
1346 for (varattno = 0; varattno < natts; varattno++)
1348 char *label = strVal(list_nth(colaliases, varattno));
1349 Form_pg_attribute attr = TupleDescAttr(tupdesc, varattno);
1352 namestrcpy(&(attr->attname), label);
1355 /* The tuple type is now an anonymous record type */
1356 tupdesc->tdtypeid = RECORDOID;
1357 tupdesc->tdtypmod = -1;
1360 else if (functypclass == TYPEFUNC_SCALAR)
1362 /* Base data type, i.e. scalar */
1365 /* the alias list is required for base types */
1366 if (colaliases == NIL)
1368 (errcode(ERRCODE_DATATYPE_MISMATCH),
1369 errmsg("no column alias was provided")));
1371 /* the alias list length must be 1 */
1372 if (list_length(colaliases) != 1)
1374 (errcode(ERRCODE_DATATYPE_MISMATCH),
1375 errmsg("number of aliases does not match number of columns")));
1377 /* OK, get the column alias */
1378 attname = strVal(linitial(colaliases));
1380 tupdesc = CreateTemplateTupleDesc(1, false);
1381 TupleDescInitEntry(tupdesc,
1388 else if (functypclass == TYPEFUNC_RECORD)
1390 /* XXX can't support this because typmod wasn't passed in ... */
1392 (errcode(ERRCODE_DATATYPE_MISMATCH),
1393 errmsg("could not determine row description for function returning record")));
1397 /* crummy error message, but parser should have caught this */
1398 elog(ERROR, "function in FROM has unsupported return type");
1405 * extract_variadic_args
1407 * Extract a set of argument values, types and NULL markers for a given
1408 * input function which makes use of a VARIADIC input whose argument list
1409 * depends on the caller context. When doing a VARIADIC call, the caller
1410 * has provided one argument made of an array of values, so deconstruct the
1411 * array data before using it for the next processing. If no VARIADIC call
1412 * is used, just fill in the status data based on all the arguments given
1415 * This function returns the number of arguments generated, or -1 in the
1416 * case of "VARIADIC NULL".
1419 extract_variadic_args(FunctionCallInfo fcinfo, int variadic_start,
1420 bool convert_unknown, Datum **args, Oid **types,
1423 bool variadic = get_fn_expr_variadic(fcinfo->flinfo);
1435 ArrayType *array_in;
1441 Assert(PG_NARGS() == variadic_start + 1);
1443 if (PG_ARGISNULL(variadic_start))
1446 array_in = PG_GETARG_ARRAYTYPE_P(variadic_start);
1447 element_type = ARR_ELEMTYPE(array_in);
1449 get_typlenbyvalalign(element_type,
1450 &typlen, &typbyval, &typalign);
1451 deconstruct_array(array_in, element_type, typlen, typbyval,
1452 typalign, &args_res, &nulls_res,
1455 /* All the elements of the array have the same type */
1456 types_res = (Oid *) palloc0(nargs * sizeof(Oid));
1457 for (i = 0; i < nargs; i++)
1458 types_res[i] = element_type;
1462 nargs = PG_NARGS() - variadic_start;
1464 nulls_res = (bool *) palloc0(nargs * sizeof(bool));
1465 args_res = (Datum *) palloc0(nargs * sizeof(Datum));
1466 types_res = (Oid *) palloc0(nargs * sizeof(Oid));
1468 for (i = 0; i < nargs; i++)
1470 nulls_res[i] = PG_ARGISNULL(i + variadic_start);
1471 types_res[i] = get_fn_expr_argtype(fcinfo->flinfo,
1472 i + variadic_start);
1475 * Turn a constant (more or less literal) value that's of unknown
1476 * type into text if required . Unknowns come in as a cstring
1478 * Note: for functions declared as taking type "any", the parser
1479 * will not do any type conversion on unknown-type literals (that
1480 * is, undecorated strings or NULLs).
1482 if (convert_unknown &&
1483 types_res[i] == UNKNOWNOID &&
1484 get_fn_expr_arg_stable(fcinfo->flinfo, i + variadic_start))
1486 types_res[i] = TEXTOID;
1488 if (PG_ARGISNULL(i + variadic_start))
1489 args_res[i] = (Datum) 0;
1492 CStringGetTextDatum(PG_GETARG_POINTER(i + variadic_start));
1496 /* no conversion needed, just take the datum as given */
1497 args_res[i] = PG_GETARG_DATUM(i + variadic_start);
1500 if (!OidIsValid(types_res[i]) ||
1501 (convert_unknown && types_res[i] == UNKNOWNOID))
1503 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1504 errmsg("could not determine data type for argument %d",
1509 /* Fill in results */