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-2018, 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, Oid *base_typeid);
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;
91 retval->user_fctx = NULL;
92 retval->attinmeta = NULL;
93 retval->tuple_desc = NULL;
94 retval->multi_call_memory_ctx = multi_call_ctx;
97 * save the pointer for cross-call use
99 fcinfo->flinfo->fn_extra = retval;
102 * Ensure we will get shut down cleanly if the exprcontext is not run
105 RegisterExprContextCallback(rsi->econtext,
106 shutdown_MultiFuncCall,
107 PointerGetDatum(fcinfo->flinfo));
111 /* second and subsequent calls */
112 elog(ERROR, "init_MultiFuncCall cannot be called more than once");
114 /* never reached, but keep compiler happy */
124 * Do Multi-function per-call setup
127 per_MultiFuncCall(PG_FUNCTION_ARGS)
129 FuncCallContext *retval = (FuncCallContext *) fcinfo->flinfo->fn_extra;
136 * Clean up after init_MultiFuncCall
139 end_MultiFuncCall(PG_FUNCTION_ARGS, FuncCallContext *funcctx)
141 ReturnSetInfo *rsi = (ReturnSetInfo *) fcinfo->resultinfo;
143 /* Deregister the shutdown callback */
144 UnregisterExprContextCallback(rsi->econtext,
145 shutdown_MultiFuncCall,
146 PointerGetDatum(fcinfo->flinfo));
148 /* But use it to do the real work */
149 shutdown_MultiFuncCall(PointerGetDatum(fcinfo->flinfo));
153 * shutdown_MultiFuncCall
154 * Shutdown function to clean up after init_MultiFuncCall
157 shutdown_MultiFuncCall(Datum arg)
159 FmgrInfo *flinfo = (FmgrInfo *) DatumGetPointer(arg);
160 FuncCallContext *funcctx = (FuncCallContext *) flinfo->fn_extra;
162 /* unbind from flinfo */
163 flinfo->fn_extra = NULL;
166 * Delete context that holds all multi-call data, including the
167 * FuncCallContext itself
169 MemoryContextDelete(funcctx->multi_call_memory_ctx);
174 * get_call_result_type
175 * Given a function's call info record, determine the kind of datatype
176 * it is supposed to return. If resultTypeId isn't NULL, *resultTypeId
177 * receives the actual datatype OID (this is mainly useful for scalar
178 * result types). If resultTupleDesc isn't NULL, *resultTupleDesc
179 * receives a pointer to a TupleDesc when the result is of a composite
180 * type, or NULL when it's a scalar result.
182 * One hard case that this handles is resolution of actual rowtypes for
183 * functions returning RECORD (from either the function's OUT parameter
184 * list, or a ReturnSetInfo context node). TYPEFUNC_RECORD is returned
185 * only when we couldn't resolve the actual rowtype for lack of information.
187 * The other hard case that this handles is resolution of polymorphism.
188 * We will never return polymorphic pseudotypes (ANYELEMENT etc), either
189 * as a scalar result type or as a component of a rowtype.
191 * This function is relatively expensive --- in a function returning set,
192 * try to call it only the first time through.
195 get_call_result_type(FunctionCallInfo fcinfo,
197 TupleDesc *resultTupleDesc)
199 return internal_get_result_type(fcinfo->flinfo->fn_oid,
200 fcinfo->flinfo->fn_expr,
201 (ReturnSetInfo *) fcinfo->resultinfo,
207 * get_expr_result_type
208 * As above, but work from a calling expression node tree
211 get_expr_result_type(Node *expr,
213 TupleDesc *resultTupleDesc)
215 TypeFuncClass result;
217 if (expr && IsA(expr, FuncExpr))
218 result = internal_get_result_type(((FuncExpr *) expr)->funcid,
223 else if (expr && IsA(expr, OpExpr))
224 result = internal_get_result_type(get_opcode(((OpExpr *) expr)->opno),
231 /* handle as a generic expression; no chance to resolve RECORD */
232 Oid typid = exprType(expr);
236 *resultTypeId = typid;
238 *resultTupleDesc = NULL;
239 result = get_type_func_class(typid, &base_typid);
240 if ((result == TYPEFUNC_COMPOSITE ||
241 result == TYPEFUNC_COMPOSITE_DOMAIN) &&
243 *resultTupleDesc = lookup_rowtype_tupdesc_copy(base_typid, -1);
250 * get_func_result_type
251 * As above, but work from a function's OID only
253 * This will not be able to resolve pure-RECORD results nor polymorphism.
256 get_func_result_type(Oid functionId,
258 TupleDesc *resultTupleDesc)
260 return internal_get_result_type(functionId,
268 * internal_get_result_type -- workhorse code implementing all the above
270 * funcid must always be supplied. call_expr and rsinfo can be NULL if not
271 * available. We will return TYPEFUNC_RECORD, and store NULL into
272 * *resultTupleDesc, if we cannot deduce the complete result rowtype from
273 * the available information.
276 internal_get_result_type(Oid funcid,
278 ReturnSetInfo *rsinfo,
280 TupleDesc *resultTupleDesc)
282 TypeFuncClass result;
284 Form_pg_proc procform;
289 /* First fetch the function's pg_proc row to inspect its rettype */
290 tp = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcid));
291 if (!HeapTupleIsValid(tp))
292 elog(ERROR, "cache lookup failed for function %u", funcid);
293 procform = (Form_pg_proc) GETSTRUCT(tp);
295 rettype = procform->prorettype;
297 /* Check for OUT parameters defining a RECORD result */
298 tupdesc = build_function_result_tupdesc_t(tp);
302 * It has OUT parameters, so it's basically like a regular composite
303 * type, except we have to be able to resolve any polymorphic OUT
307 *resultTypeId = rettype;
309 if (resolve_polymorphic_tupdesc(tupdesc,
310 &procform->proargtypes,
313 if (tupdesc->tdtypeid == RECORDOID &&
314 tupdesc->tdtypmod < 0)
315 assign_record_type_typmod(tupdesc);
317 *resultTupleDesc = tupdesc;
318 result = TYPEFUNC_COMPOSITE;
323 *resultTupleDesc = NULL;
324 result = TYPEFUNC_RECORD;
333 * If scalar polymorphic result, try to resolve it.
335 if (IsPolymorphicType(rettype))
337 Oid newrettype = exprType(call_expr);
339 if (newrettype == InvalidOid) /* this probably should not happen */
341 (errcode(ERRCODE_DATATYPE_MISMATCH),
342 errmsg("could not determine actual result type for function \"%s\" declared to return type %s",
343 NameStr(procform->proname),
344 format_type_be(rettype))));
345 rettype = newrettype;
349 *resultTypeId = rettype;
351 *resultTupleDesc = NULL; /* default result */
353 /* Classify the result type */
354 result = get_type_func_class(rettype, &base_rettype);
357 case TYPEFUNC_COMPOSITE:
358 case TYPEFUNC_COMPOSITE_DOMAIN:
360 *resultTupleDesc = lookup_rowtype_tupdesc_copy(base_rettype, -1);
361 /* Named composite types can't have any polymorphic columns */
363 case TYPEFUNC_SCALAR:
365 case TYPEFUNC_RECORD:
366 /* We must get the tupledesc from call context */
367 if (rsinfo && IsA(rsinfo, ReturnSetInfo) &&
368 rsinfo->expectedDesc != NULL)
370 result = TYPEFUNC_COMPOSITE;
372 *resultTupleDesc = rsinfo->expectedDesc;
373 /* Assume no polymorphic columns here, either */
386 * get_expr_result_tupdesc
387 * Get a tupdesc describing the result of a composite-valued expression
389 * If expression is not composite or rowtype can't be determined, returns NULL
390 * if noError is true, else throws error.
392 * This is a simpler version of get_expr_result_type() for use when the caller
393 * is only interested in determinate rowtype results.
396 get_expr_result_tupdesc(Node *expr, bool noError)
399 TypeFuncClass functypclass;
401 functypclass = get_expr_result_type(expr, NULL, &tupleDesc);
403 if (functypclass == TYPEFUNC_COMPOSITE ||
404 functypclass == TYPEFUNC_COMPOSITE_DOMAIN)
409 Oid exprTypeId = exprType(expr);
411 if (exprTypeId != RECORDOID)
413 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
414 errmsg("type %s is not composite",
415 format_type_be(exprTypeId))));
418 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
419 errmsg("record type has not been registered")));
426 * Given the result tuple descriptor for a function with OUT parameters,
427 * replace any polymorphic columns (ANYELEMENT etc) with correct data types
428 * deduced from the input arguments. Returns true if able to deduce all types,
432 resolve_polymorphic_tupdesc(TupleDesc tupdesc, oidvector *declared_args,
435 int natts = tupdesc->natts;
436 int nargs = declared_args->dim1;
437 bool have_anyelement_result = false;
438 bool have_anyarray_result = false;
439 bool have_anyrange_result = false;
440 bool have_anynonarray = false;
441 bool have_anyenum = false;
442 Oid anyelement_type = InvalidOid;
443 Oid anyarray_type = InvalidOid;
444 Oid anyrange_type = InvalidOid;
445 Oid anycollation = InvalidOid;
448 /* See if there are any polymorphic outputs; quick out if not */
449 for (i = 0; i < natts; i++)
451 switch (TupleDescAttr(tupdesc, i)->atttypid)
454 have_anyelement_result = true;
457 have_anyarray_result = true;
460 have_anyelement_result = true;
461 have_anynonarray = true;
464 have_anyelement_result = true;
468 have_anyrange_result = true;
474 if (!have_anyelement_result && !have_anyarray_result &&
475 !have_anyrange_result)
479 * Otherwise, extract actual datatype(s) from input arguments. (We assume
480 * the parser already validated consistency of the arguments.)
483 return false; /* no hope */
485 for (i = 0; i < nargs; i++)
487 switch (declared_args->values[i])
492 if (!OidIsValid(anyelement_type))
493 anyelement_type = get_call_expr_argtype(call_expr, i);
496 if (!OidIsValid(anyarray_type))
497 anyarray_type = get_call_expr_argtype(call_expr, i);
500 if (!OidIsValid(anyrange_type))
501 anyrange_type = get_call_expr_argtype(call_expr, i);
508 /* If nothing found, parser messed up */
509 if (!OidIsValid(anyelement_type) && !OidIsValid(anyarray_type) &&
510 !OidIsValid(anyrange_type))
513 /* If needed, deduce one polymorphic type from others */
514 if (have_anyelement_result && !OidIsValid(anyelement_type))
516 if (OidIsValid(anyarray_type))
517 anyelement_type = resolve_generic_type(ANYELEMENTOID,
520 if (OidIsValid(anyrange_type))
522 Oid subtype = resolve_generic_type(ANYELEMENTOID,
526 /* check for inconsistent array and range results */
527 if (OidIsValid(anyelement_type) && anyelement_type != subtype)
529 anyelement_type = subtype;
533 if (have_anyarray_result && !OidIsValid(anyarray_type))
534 anyarray_type = resolve_generic_type(ANYARRAYOID,
539 * We can't deduce a range type from other polymorphic inputs, because
540 * there may be multiple range types for the same subtype.
542 if (have_anyrange_result && !OidIsValid(anyrange_type))
545 /* Enforce ANYNONARRAY if needed */
546 if (have_anynonarray && type_is_array(anyelement_type))
549 /* Enforce ANYENUM if needed */
550 if (have_anyenum && !type_is_enum(anyelement_type))
554 * Identify the collation to use for polymorphic OUT parameters. (It'll
555 * necessarily be the same for both anyelement and anyarray.) Note that
556 * range types are not collatable, so any possible internal collation of a
557 * range type is not considered here.
559 if (OidIsValid(anyelement_type))
560 anycollation = get_typcollation(anyelement_type);
561 else if (OidIsValid(anyarray_type))
562 anycollation = get_typcollation(anyarray_type);
564 if (OidIsValid(anycollation))
567 * The types are collatable, so consider whether to use a nondefault
568 * collation. We do so if we can identify the input collation used
571 Oid inputcollation = exprInputCollation(call_expr);
573 if (OidIsValid(inputcollation))
574 anycollation = inputcollation;
577 /* And finally replace the tuple column types as needed */
578 for (i = 0; i < natts; i++)
580 Form_pg_attribute att = TupleDescAttr(tupdesc, i);
582 switch (att->atttypid)
587 TupleDescInitEntry(tupdesc, i + 1,
588 NameStr(att->attname),
592 TupleDescInitEntryCollation(tupdesc, i + 1, anycollation);
595 TupleDescInitEntry(tupdesc, i + 1,
596 NameStr(att->attname),
600 TupleDescInitEntryCollation(tupdesc, i + 1, anycollation);
603 TupleDescInitEntry(tupdesc, i + 1,
604 NameStr(att->attname),
608 /* no collation should be attached to a range type */
619 * Given the declared argument types and modes for a function, replace any
620 * polymorphic types (ANYELEMENT etc) with correct data types deduced from the
621 * input arguments. Returns true if able to deduce all types, false if not.
622 * This is the same logic as resolve_polymorphic_tupdesc, but with a different
623 * argument representation.
625 * argmodes may be NULL, in which case all arguments are assumed to be IN mode.
628 resolve_polymorphic_argtypes(int numargs, Oid *argtypes, char *argmodes,
631 bool have_anyelement_result = false;
632 bool have_anyarray_result = false;
633 bool have_anyrange_result = false;
634 Oid anyelement_type = InvalidOid;
635 Oid anyarray_type = InvalidOid;
636 Oid anyrange_type = InvalidOid;
640 /* First pass: resolve polymorphic inputs, check for outputs */
642 for (i = 0; i < numargs; i++)
644 char argmode = argmodes ? argmodes[i] : PROARGMODE_IN;
651 if (argmode == PROARGMODE_OUT || argmode == PROARGMODE_TABLE)
652 have_anyelement_result = true;
655 if (!OidIsValid(anyelement_type))
657 anyelement_type = get_call_expr_argtype(call_expr,
659 if (!OidIsValid(anyelement_type))
662 argtypes[i] = anyelement_type;
666 if (argmode == PROARGMODE_OUT || argmode == PROARGMODE_TABLE)
667 have_anyarray_result = true;
670 if (!OidIsValid(anyarray_type))
672 anyarray_type = get_call_expr_argtype(call_expr,
674 if (!OidIsValid(anyarray_type))
677 argtypes[i] = anyarray_type;
681 if (argmode == PROARGMODE_OUT || argmode == PROARGMODE_TABLE)
682 have_anyrange_result = true;
685 if (!OidIsValid(anyrange_type))
687 anyrange_type = get_call_expr_argtype(call_expr,
689 if (!OidIsValid(anyrange_type))
692 argtypes[i] = anyrange_type;
698 if (argmode != PROARGMODE_OUT && argmode != PROARGMODE_TABLE)
703 if (!have_anyelement_result && !have_anyarray_result &&
704 !have_anyrange_result)
707 /* If no input polymorphics, parser messed up */
708 if (!OidIsValid(anyelement_type) && !OidIsValid(anyarray_type) &&
709 !OidIsValid(anyrange_type))
712 /* If needed, deduce one polymorphic type from others */
713 if (have_anyelement_result && !OidIsValid(anyelement_type))
715 if (OidIsValid(anyarray_type))
716 anyelement_type = resolve_generic_type(ANYELEMENTOID,
719 if (OidIsValid(anyrange_type))
721 Oid subtype = resolve_generic_type(ANYELEMENTOID,
725 /* check for inconsistent array and range results */
726 if (OidIsValid(anyelement_type) && anyelement_type != subtype)
728 anyelement_type = subtype;
732 if (have_anyarray_result && !OidIsValid(anyarray_type))
733 anyarray_type = resolve_generic_type(ANYARRAYOID,
738 * We can't deduce a range type from other polymorphic inputs, because
739 * there may be multiple range types for the same subtype.
741 if (have_anyrange_result && !OidIsValid(anyrange_type))
744 /* XXX do we need to enforce ANYNONARRAY or ANYENUM here? I think not */
746 /* And finally replace the output column types as needed */
747 for (i = 0; i < numargs; i++)
754 argtypes[i] = anyelement_type;
757 argtypes[i] = anyarray_type;
760 argtypes[i] = anyrange_type;
771 * get_type_func_class
772 * Given the type OID, obtain its TYPEFUNC classification.
773 * Also, if it's a domain, return the base type OID.
775 * This is intended to centralize a bunch of formerly ad-hoc code for
776 * classifying types. The categories used here are useful for deciding
777 * how to handle functions returning the datatype.
780 get_type_func_class(Oid typid, Oid *base_typeid)
782 *base_typeid = typid;
784 switch (get_typtype(typid))
786 case TYPTYPE_COMPOSITE:
787 return TYPEFUNC_COMPOSITE;
791 return TYPEFUNC_SCALAR;
793 *base_typeid = typid = getBaseType(typid);
794 if (get_typtype(typid) == TYPTYPE_COMPOSITE)
795 return TYPEFUNC_COMPOSITE_DOMAIN;
796 else /* domain base type can't be a pseudotype */
797 return TYPEFUNC_SCALAR;
799 if (typid == RECORDOID)
800 return TYPEFUNC_RECORD;
803 * We treat VOID and CSTRING as legitimate scalar datatypes,
804 * mostly for the convenience of the JDBC driver (which wants to
805 * be able to do "SELECT * FROM foo()" for all legitimately
806 * user-callable functions).
808 if (typid == VOIDOID || typid == CSTRINGOID)
809 return TYPEFUNC_SCALAR;
810 return TYPEFUNC_OTHER;
812 /* shouldn't get here, probably */
813 return TYPEFUNC_OTHER;
820 * Fetch info about the argument types, names, and IN/OUT modes from the
821 * pg_proc tuple. Return value is the total number of arguments.
822 * Other results are palloc'd. *p_argtypes is always filled in, but
823 * *p_argnames and *p_argmodes will be set NULL in the default cases
824 * (no names, and all IN arguments, respectively).
826 * Note that this function simply fetches what is in the pg_proc tuple;
827 * it doesn't do any interpretation of polymorphic types.
830 get_func_arg_info(HeapTuple procTup,
831 Oid **p_argtypes, char ***p_argnames, char **p_argmodes)
833 Form_pg_proc procStruct = (Form_pg_proc) GETSTRUCT(procTup);
834 Datum proallargtypes;
844 /* First discover the total number of parameters and get their types */
845 proallargtypes = SysCacheGetAttr(PROCOID, procTup,
846 Anum_pg_proc_proallargtypes,
851 * We expect the arrays to be 1-D arrays of the right types; verify
852 * that. For the OID and char arrays, we don't need to use
853 * deconstruct_array() since the array data is just going to look like
854 * a C array of values.
856 arr = DatumGetArrayTypeP(proallargtypes); /* ensure not toasted */
857 numargs = ARR_DIMS(arr)[0];
858 if (ARR_NDIM(arr) != 1 ||
861 ARR_ELEMTYPE(arr) != OIDOID)
862 elog(ERROR, "proallargtypes is not a 1-D Oid array");
863 Assert(numargs >= procStruct->pronargs);
864 *p_argtypes = (Oid *) palloc(numargs * sizeof(Oid));
865 memcpy(*p_argtypes, ARR_DATA_PTR(arr),
866 numargs * sizeof(Oid));
870 /* If no proallargtypes, use proargtypes */
871 numargs = procStruct->proargtypes.dim1;
872 Assert(numargs == procStruct->pronargs);
873 *p_argtypes = (Oid *) palloc(numargs * sizeof(Oid));
874 memcpy(*p_argtypes, procStruct->proargtypes.values,
875 numargs * sizeof(Oid));
878 /* Get argument names, if available */
879 proargnames = SysCacheGetAttr(PROCOID, procTup,
880 Anum_pg_proc_proargnames,
886 deconstruct_array(DatumGetArrayTypeP(proargnames),
887 TEXTOID, -1, false, 'i',
888 &elems, NULL, &nelems);
889 if (nelems != numargs) /* should not happen */
890 elog(ERROR, "proargnames must have the same number of elements as the function has arguments");
891 *p_argnames = (char **) palloc(sizeof(char *) * numargs);
892 for (i = 0; i < numargs; i++)
893 (*p_argnames)[i] = TextDatumGetCString(elems[i]);
896 /* Get argument modes, if available */
897 proargmodes = SysCacheGetAttr(PROCOID, procTup,
898 Anum_pg_proc_proargmodes,
904 arr = DatumGetArrayTypeP(proargmodes); /* ensure not toasted */
905 if (ARR_NDIM(arr) != 1 ||
906 ARR_DIMS(arr)[0] != numargs ||
908 ARR_ELEMTYPE(arr) != CHAROID)
909 elog(ERROR, "proargmodes is not a 1-D char array");
910 *p_argmodes = (char *) palloc(numargs * sizeof(char));
911 memcpy(*p_argmodes, ARR_DATA_PTR(arr),
912 numargs * sizeof(char));
921 * Returns the number of transformed types used by function.
924 get_func_trftypes(HeapTuple procTup,
932 protrftypes = SysCacheGetAttr(PROCOID, procTup,
933 Anum_pg_proc_protrftypes,
938 * We expect the arrays to be 1-D arrays of the right types; verify
939 * that. For the OID and char arrays, we don't need to use
940 * deconstruct_array() since the array data is just going to look like
941 * a C array of values.
943 arr = DatumGetArrayTypeP(protrftypes); /* ensure not toasted */
944 nelems = ARR_DIMS(arr)[0];
945 if (ARR_NDIM(arr) != 1 ||
948 ARR_ELEMTYPE(arr) != OIDOID)
949 elog(ERROR, "protrftypes is not a 1-D Oid array");
950 Assert(nelems >= ((Form_pg_proc) GETSTRUCT(procTup))->pronargs);
951 *p_trftypes = (Oid *) palloc(nelems * sizeof(Oid));
952 memcpy(*p_trftypes, ARR_DATA_PTR(arr),
953 nelems * sizeof(Oid));
962 * get_func_input_arg_names
964 * Extract the names of input arguments only, given a function's
965 * proargnames and proargmodes entries in Datum form.
967 * Returns the number of input arguments, which is the length of the
968 * palloc'd array returned to *arg_names. Entries for unnamed args
969 * are set to NULL. You don't get anything if proargnames is NULL.
972 get_func_input_arg_names(Datum proargnames, Datum proargmodes,
983 /* Do nothing if null proargnames */
984 if (proargnames == PointerGetDatum(NULL))
991 * We expect the arrays to be 1-D arrays of the right types; verify that.
992 * For proargmodes, we don't need to use deconstruct_array() since the
993 * array data is just going to look like a C array of values.
995 arr = DatumGetArrayTypeP(proargnames); /* ensure not toasted */
996 if (ARR_NDIM(arr) != 1 ||
998 ARR_ELEMTYPE(arr) != TEXTOID)
999 elog(ERROR, "proargnames is not a 1-D text array");
1000 deconstruct_array(arr, TEXTOID, -1, false, 'i',
1001 &argnames, NULL, &numargs);
1002 if (proargmodes != PointerGetDatum(NULL))
1004 arr = DatumGetArrayTypeP(proargmodes); /* ensure not toasted */
1005 if (ARR_NDIM(arr) != 1 ||
1006 ARR_DIMS(arr)[0] != numargs ||
1008 ARR_ELEMTYPE(arr) != CHAROID)
1009 elog(ERROR, "proargmodes is not a 1-D char array");
1010 argmodes = (char *) ARR_DATA_PTR(arr);
1015 /* zero elements probably shouldn't happen, but handle it gracefully */
1022 /* extract input-argument names */
1023 inargnames = (char **) palloc(numargs * sizeof(char *));
1025 for (i = 0; i < numargs; i++)
1027 if (argmodes == NULL ||
1028 argmodes[i] == PROARGMODE_IN ||
1029 argmodes[i] == PROARGMODE_INOUT ||
1030 argmodes[i] == PROARGMODE_VARIADIC)
1032 char *pname = TextDatumGetCString(argnames[i]);
1034 if (pname[0] != '\0')
1035 inargnames[numinargs] = pname;
1037 inargnames[numinargs] = NULL;
1042 *arg_names = inargnames;
1048 * get_func_result_name
1050 * If the function has exactly one output parameter, and that parameter
1051 * is named, return the name (as a palloc'd string). Else return NULL.
1053 * This is used to determine the default output column name for functions
1054 * returning scalar types.
1057 get_func_result_name(Oid functionId)
1060 HeapTuple procTuple;
1072 /* First fetch the function's pg_proc row */
1073 procTuple = SearchSysCache1(PROCOID, ObjectIdGetDatum(functionId));
1074 if (!HeapTupleIsValid(procTuple))
1075 elog(ERROR, "cache lookup failed for function %u", functionId);
1077 /* If there are no named OUT parameters, return NULL */
1078 if (heap_attisnull(procTuple, Anum_pg_proc_proargmodes, NULL) ||
1079 heap_attisnull(procTuple, Anum_pg_proc_proargnames, NULL))
1083 /* Get the data out of the tuple */
1084 proargmodes = SysCacheGetAttr(PROCOID, procTuple,
1085 Anum_pg_proc_proargmodes,
1088 proargnames = SysCacheGetAttr(PROCOID, procTuple,
1089 Anum_pg_proc_proargnames,
1094 * We expect the arrays to be 1-D arrays of the right types; verify
1095 * that. For the char array, we don't need to use deconstruct_array()
1096 * since the array data is just going to look like a C array of
1099 arr = DatumGetArrayTypeP(proargmodes); /* ensure not toasted */
1100 numargs = ARR_DIMS(arr)[0];
1101 if (ARR_NDIM(arr) != 1 ||
1104 ARR_ELEMTYPE(arr) != CHAROID)
1105 elog(ERROR, "proargmodes is not a 1-D char array");
1106 argmodes = (char *) ARR_DATA_PTR(arr);
1107 arr = DatumGetArrayTypeP(proargnames); /* ensure not toasted */
1108 if (ARR_NDIM(arr) != 1 ||
1109 ARR_DIMS(arr)[0] != numargs ||
1111 ARR_ELEMTYPE(arr) != TEXTOID)
1112 elog(ERROR, "proargnames is not a 1-D text array");
1113 deconstruct_array(arr, TEXTOID, -1, false, 'i',
1114 &argnames, NULL, &nargnames);
1115 Assert(nargnames == numargs);
1117 /* scan for output argument(s) */
1120 for (i = 0; i < numargs; i++)
1122 if (argmodes[i] == PROARGMODE_IN ||
1123 argmodes[i] == PROARGMODE_VARIADIC)
1125 Assert(argmodes[i] == PROARGMODE_OUT ||
1126 argmodes[i] == PROARGMODE_INOUT ||
1127 argmodes[i] == PROARGMODE_TABLE);
1128 if (++numoutargs > 1)
1130 /* multiple out args, so forget it */
1134 result = TextDatumGetCString(argnames[i]);
1135 if (result == NULL || result[0] == '\0')
1137 /* Parameter is not named, so forget it */
1144 ReleaseSysCache(procTuple);
1151 * build_function_result_tupdesc_t
1153 * Given a pg_proc row for a function, return a tuple descriptor for the
1154 * result rowtype, or NULL if the function does not have OUT parameters.
1156 * Note that this does not handle resolution of polymorphic types;
1157 * that is deliberate.
1160 build_function_result_tupdesc_t(HeapTuple procTuple)
1162 Form_pg_proc procform = (Form_pg_proc) GETSTRUCT(procTuple);
1163 Datum proallargtypes;
1168 /* Return NULL if the function isn't declared to return RECORD */
1169 if (procform->prorettype != RECORDOID)
1172 /* If there are no OUT parameters, return NULL */
1173 if (heap_attisnull(procTuple, Anum_pg_proc_proallargtypes, NULL) ||
1174 heap_attisnull(procTuple, Anum_pg_proc_proargmodes, NULL))
1177 /* Get the data out of the tuple */
1178 proallargtypes = SysCacheGetAttr(PROCOID, procTuple,
1179 Anum_pg_proc_proallargtypes,
1182 proargmodes = SysCacheGetAttr(PROCOID, procTuple,
1183 Anum_pg_proc_proargmodes,
1186 proargnames = SysCacheGetAttr(PROCOID, procTuple,
1187 Anum_pg_proc_proargnames,
1190 proargnames = PointerGetDatum(NULL); /* just to be sure */
1192 return build_function_result_tupdesc_d(procform->prokind,
1199 * build_function_result_tupdesc_d
1201 * Build a RECORD function's tupledesc from the pg_proc proallargtypes,
1202 * proargmodes, and proargnames arrays. This is split out for the
1203 * convenience of ProcedureCreate, which needs to be able to compute the
1204 * tupledesc before actually creating the function.
1206 * For functions (but not for procedures), returns NULL if there are not at
1207 * least two OUT or INOUT arguments.
1210 build_function_result_tupdesc_d(char prokind,
1211 Datum proallargtypes,
1220 Datum *argnames = NULL;
1227 /* Can't have output args if columns are null */
1228 if (proallargtypes == PointerGetDatum(NULL) ||
1229 proargmodes == PointerGetDatum(NULL))
1233 * We expect the arrays to be 1-D arrays of the right types; verify that.
1234 * For the OID and char arrays, we don't need to use deconstruct_array()
1235 * since the array data is just going to look like a C array of values.
1237 arr = DatumGetArrayTypeP(proallargtypes); /* ensure not toasted */
1238 numargs = ARR_DIMS(arr)[0];
1239 if (ARR_NDIM(arr) != 1 ||
1242 ARR_ELEMTYPE(arr) != OIDOID)
1243 elog(ERROR, "proallargtypes is not a 1-D Oid array");
1244 argtypes = (Oid *) ARR_DATA_PTR(arr);
1245 arr = DatumGetArrayTypeP(proargmodes); /* ensure not toasted */
1246 if (ARR_NDIM(arr) != 1 ||
1247 ARR_DIMS(arr)[0] != numargs ||
1249 ARR_ELEMTYPE(arr) != CHAROID)
1250 elog(ERROR, "proargmodes is not a 1-D char array");
1251 argmodes = (char *) ARR_DATA_PTR(arr);
1252 if (proargnames != PointerGetDatum(NULL))
1254 arr = DatumGetArrayTypeP(proargnames); /* ensure not toasted */
1255 if (ARR_NDIM(arr) != 1 ||
1256 ARR_DIMS(arr)[0] != numargs ||
1258 ARR_ELEMTYPE(arr) != TEXTOID)
1259 elog(ERROR, "proargnames is not a 1-D text array");
1260 deconstruct_array(arr, TEXTOID, -1, false, 'i',
1261 &argnames, NULL, &nargnames);
1262 Assert(nargnames == numargs);
1265 /* zero elements probably shouldn't happen, but handle it gracefully */
1269 /* extract output-argument types and names */
1270 outargtypes = (Oid *) palloc(numargs * sizeof(Oid));
1271 outargnames = (char **) palloc(numargs * sizeof(char *));
1273 for (i = 0; i < numargs; i++)
1277 if (argmodes[i] == PROARGMODE_IN ||
1278 argmodes[i] == PROARGMODE_VARIADIC)
1280 Assert(argmodes[i] == PROARGMODE_OUT ||
1281 argmodes[i] == PROARGMODE_INOUT ||
1282 argmodes[i] == PROARGMODE_TABLE);
1283 outargtypes[numoutargs] = argtypes[i];
1285 pname = TextDatumGetCString(argnames[i]);
1288 if (pname == NULL || pname[0] == '\0')
1290 /* Parameter is not named, so gin up a column name */
1291 pname = psprintf("column%d", numoutargs + 1);
1293 outargnames[numoutargs] = pname;
1298 * If there is no output argument, or only one, the function does not
1301 if (numoutargs < 2 && prokind != PROKIND_PROCEDURE)
1304 desc = CreateTemplateTupleDesc(numoutargs);
1305 for (i = 0; i < numoutargs; i++)
1307 TupleDescInitEntry(desc, i + 1,
1319 * RelationNameGetTupleDesc
1321 * Given a (possibly qualified) relation name, build a TupleDesc.
1323 * Note: while this works as advertised, it's seldom the best way to
1324 * build a tupdesc for a function's result type. It's kept around
1325 * only for backwards compatibility with existing user-written code.
1328 RelationNameGetTupleDesc(const char *relname)
1335 /* Open relation and copy the tuple description */
1336 relname_list = stringToQualifiedNameList(relname);
1337 relvar = makeRangeVarFromNameList(relname_list);
1338 rel = relation_openrv(relvar, AccessShareLock);
1339 tupdesc = CreateTupleDescCopy(RelationGetDescr(rel));
1340 relation_close(rel, AccessShareLock);
1348 * Given a type Oid, build a TupleDesc. (In most cases you should be
1349 * using get_call_result_type or one of its siblings instead of this
1350 * routine, so that you can handle OUT parameters, RECORD result type,
1351 * and polymorphic results.)
1353 * If the type is composite, *and* a colaliases List is provided, *and*
1354 * the List is of natts length, use the aliases instead of the relation
1355 * attnames. (NB: this usage is deprecated since it may result in
1356 * creation of unnecessary transient record types.)
1358 * If the type is a base type, a single item alias List is required.
1361 TypeGetTupleDesc(Oid typeoid, List *colaliases)
1364 TypeFuncClass functypclass = get_type_func_class(typeoid, &base_typeoid);
1365 TupleDesc tupdesc = NULL;
1368 * Build a suitable tupledesc representing the output rows. We
1369 * intentionally do not support TYPEFUNC_COMPOSITE_DOMAIN here, as it's
1370 * unlikely that legacy callers of this obsolete function would be
1371 * prepared to apply domain constraints.
1373 if (functypclass == TYPEFUNC_COMPOSITE)
1375 /* Composite data type, e.g. a table's row type */
1376 tupdesc = lookup_rowtype_tupdesc_copy(base_typeoid, -1);
1378 if (colaliases != NIL)
1380 int natts = tupdesc->natts;
1383 /* does the list length match the number of attributes? */
1384 if (list_length(colaliases) != natts)
1386 (errcode(ERRCODE_DATATYPE_MISMATCH),
1387 errmsg("number of aliases does not match number of columns")));
1389 /* OK, use the aliases instead */
1390 for (varattno = 0; varattno < natts; varattno++)
1392 char *label = strVal(list_nth(colaliases, varattno));
1393 Form_pg_attribute attr = TupleDescAttr(tupdesc, varattno);
1396 namestrcpy(&(attr->attname), label);
1399 /* The tuple type is now an anonymous record type */
1400 tupdesc->tdtypeid = RECORDOID;
1401 tupdesc->tdtypmod = -1;
1404 else if (functypclass == TYPEFUNC_SCALAR)
1406 /* Base data type, i.e. scalar */
1409 /* the alias list is required for base types */
1410 if (colaliases == NIL)
1412 (errcode(ERRCODE_DATATYPE_MISMATCH),
1413 errmsg("no column alias was provided")));
1415 /* the alias list length must be 1 */
1416 if (list_length(colaliases) != 1)
1418 (errcode(ERRCODE_DATATYPE_MISMATCH),
1419 errmsg("number of aliases does not match number of columns")));
1421 /* OK, get the column alias */
1422 attname = strVal(linitial(colaliases));
1424 tupdesc = CreateTemplateTupleDesc(1);
1425 TupleDescInitEntry(tupdesc,
1432 else if (functypclass == TYPEFUNC_RECORD)
1434 /* XXX can't support this because typmod wasn't passed in ... */
1436 (errcode(ERRCODE_DATATYPE_MISMATCH),
1437 errmsg("could not determine row description for function returning record")));
1441 /* crummy error message, but parser should have caught this */
1442 elog(ERROR, "function in FROM has unsupported return type");
1449 * extract_variadic_args
1451 * Extract a set of argument values, types and NULL markers for a given
1452 * input function which makes use of a VARIADIC input whose argument list
1453 * depends on the caller context. When doing a VARIADIC call, the caller
1454 * has provided one argument made of an array of values, so deconstruct the
1455 * array data before using it for the next processing. If no VARIADIC call
1456 * is used, just fill in the status data based on all the arguments given
1459 * This function returns the number of arguments generated, or -1 in the
1460 * case of "VARIADIC NULL".
1463 extract_variadic_args(FunctionCallInfo fcinfo, int variadic_start,
1464 bool convert_unknown, Datum **args, Oid **types,
1467 bool variadic = get_fn_expr_variadic(fcinfo->flinfo);
1480 ArrayType *array_in;
1486 Assert(PG_NARGS() == variadic_start + 1);
1488 if (PG_ARGISNULL(variadic_start))
1491 array_in = PG_GETARG_ARRAYTYPE_P(variadic_start);
1492 element_type = ARR_ELEMTYPE(array_in);
1494 get_typlenbyvalalign(element_type,
1495 &typlen, &typbyval, &typalign);
1496 deconstruct_array(array_in, element_type, typlen, typbyval,
1497 typalign, &args_res, &nulls_res,
1500 /* All the elements of the array have the same type */
1501 types_res = (Oid *) palloc0(nargs * sizeof(Oid));
1502 for (i = 0; i < nargs; i++)
1503 types_res[i] = element_type;
1507 nargs = PG_NARGS() - variadic_start;
1509 nulls_res = (bool *) palloc0(nargs * sizeof(bool));
1510 args_res = (Datum *) palloc0(nargs * sizeof(Datum));
1511 types_res = (Oid *) palloc0(nargs * sizeof(Oid));
1513 for (i = 0; i < nargs; i++)
1515 nulls_res[i] = PG_ARGISNULL(i + variadic_start);
1516 types_res[i] = get_fn_expr_argtype(fcinfo->flinfo,
1517 i + variadic_start);
1520 * Turn a constant (more or less literal) value that's of unknown
1521 * type into text if required. Unknowns come in as a cstring
1522 * pointer. Note: for functions declared as taking type "any", the
1523 * parser will not do any type conversion on unknown-type literals
1524 * (that is, undecorated strings or NULLs).
1526 if (convert_unknown &&
1527 types_res[i] == UNKNOWNOID &&
1528 get_fn_expr_arg_stable(fcinfo->flinfo, i + variadic_start))
1530 types_res[i] = TEXTOID;
1532 if (PG_ARGISNULL(i + variadic_start))
1533 args_res[i] = (Datum) 0;
1536 CStringGetTextDatum(PG_GETARG_POINTER(i + variadic_start));
1540 /* no conversion needed, just take the datum as given */
1541 args_res[i] = PG_GETARG_DATUM(i + variadic_start);
1544 if (!OidIsValid(types_res[i]) ||
1545 (convert_unknown && types_res[i] == UNKNOWNOID))
1547 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1548 errmsg("could not determine data type for argument %d",
1553 /* Fill in results */