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;
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);
252 *resultTypeId = typid;
254 *resultTupleDesc = NULL;
255 result = get_type_func_class(typid, &base_typid);
256 if ((result == TYPEFUNC_COMPOSITE ||
257 result == TYPEFUNC_COMPOSITE_DOMAIN) &&
259 *resultTupleDesc = lookup_rowtype_tupdesc_copy(base_typid, -1);
266 * get_func_result_type
267 * As above, but work from a function's OID only
269 * This will not be able to resolve pure-RECORD results nor polymorphism.
272 get_func_result_type(Oid functionId,
274 TupleDesc *resultTupleDesc)
276 return internal_get_result_type(functionId,
284 * internal_get_result_type -- workhorse code implementing all the above
286 * funcid must always be supplied. call_expr and rsinfo can be NULL if not
287 * available. We will return TYPEFUNC_RECORD, and store NULL into
288 * *resultTupleDesc, if we cannot deduce the complete result rowtype from
289 * the available information.
292 internal_get_result_type(Oid funcid,
294 ReturnSetInfo *rsinfo,
296 TupleDesc *resultTupleDesc)
298 TypeFuncClass result;
300 Form_pg_proc procform;
305 /* First fetch the function's pg_proc row to inspect its rettype */
306 tp = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcid));
307 if (!HeapTupleIsValid(tp))
308 elog(ERROR, "cache lookup failed for function %u", funcid);
309 procform = (Form_pg_proc) GETSTRUCT(tp);
311 rettype = procform->prorettype;
313 /* Check for OUT parameters defining a RECORD result */
314 tupdesc = build_function_result_tupdesc_t(tp);
318 * It has OUT parameters, so it's basically like a regular composite
319 * type, except we have to be able to resolve any polymorphic OUT
323 *resultTypeId = rettype;
325 if (resolve_polymorphic_tupdesc(tupdesc,
326 &procform->proargtypes,
329 if (tupdesc->tdtypeid == RECORDOID &&
330 tupdesc->tdtypmod < 0)
331 assign_record_type_typmod(tupdesc);
333 *resultTupleDesc = tupdesc;
334 result = TYPEFUNC_COMPOSITE;
339 *resultTupleDesc = NULL;
340 result = TYPEFUNC_RECORD;
349 * If scalar polymorphic result, try to resolve it.
351 if (IsPolymorphicType(rettype))
353 Oid newrettype = exprType(call_expr);
355 if (newrettype == InvalidOid) /* this probably should not happen */
357 (errcode(ERRCODE_DATATYPE_MISMATCH),
358 errmsg("could not determine actual result type for function \"%s\" declared to return type %s",
359 NameStr(procform->proname),
360 format_type_be(rettype))));
361 rettype = newrettype;
365 *resultTypeId = rettype;
367 *resultTupleDesc = NULL; /* default result */
369 /* Classify the result type */
370 result = get_type_func_class(rettype, &base_rettype);
373 case TYPEFUNC_COMPOSITE:
374 case TYPEFUNC_COMPOSITE_DOMAIN:
376 *resultTupleDesc = lookup_rowtype_tupdesc_copy(base_rettype, -1);
377 /* Named composite types can't have any polymorphic columns */
379 case TYPEFUNC_SCALAR:
381 case TYPEFUNC_RECORD:
382 /* We must get the tupledesc from call context */
383 if (rsinfo && IsA(rsinfo, ReturnSetInfo) &&
384 rsinfo->expectedDesc != NULL)
386 result = TYPEFUNC_COMPOSITE;
388 *resultTupleDesc = rsinfo->expectedDesc;
389 /* Assume no polymorphic columns here, either */
402 * get_expr_result_tupdesc
403 * Get a tupdesc describing the result of a composite-valued expression
405 * If expression is not composite or rowtype can't be determined, returns NULL
406 * if noError is true, else throws error.
408 * This is a simpler version of get_expr_result_type() for use when the caller
409 * is only interested in determinate rowtype results.
412 get_expr_result_tupdesc(Node *expr, bool noError)
415 TypeFuncClass functypclass;
417 functypclass = get_expr_result_type(expr, NULL, &tupleDesc);
419 if (functypclass == TYPEFUNC_COMPOSITE ||
420 functypclass == TYPEFUNC_COMPOSITE_DOMAIN)
425 Oid exprTypeId = exprType(expr);
427 if (exprTypeId != RECORDOID)
429 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
430 errmsg("type %s is not composite",
431 format_type_be(exprTypeId))));
434 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
435 errmsg("record type has not been registered")));
442 * Given the result tuple descriptor for a function with OUT parameters,
443 * replace any polymorphic columns (ANYELEMENT etc) with correct data types
444 * deduced from the input arguments. Returns true if able to deduce all types,
448 resolve_polymorphic_tupdesc(TupleDesc tupdesc, oidvector *declared_args,
451 int natts = tupdesc->natts;
452 int nargs = declared_args->dim1;
453 bool have_anyelement_result = false;
454 bool have_anyarray_result = false;
455 bool have_anyrange_result = false;
456 bool have_anynonarray = false;
457 bool have_anyenum = false;
458 Oid anyelement_type = InvalidOid;
459 Oid anyarray_type = InvalidOid;
460 Oid anyrange_type = InvalidOid;
461 Oid anycollation = InvalidOid;
464 /* See if there are any polymorphic outputs; quick out if not */
465 for (i = 0; i < natts; i++)
467 switch (TupleDescAttr(tupdesc, i)->atttypid)
470 have_anyelement_result = true;
473 have_anyarray_result = true;
476 have_anyelement_result = true;
477 have_anynonarray = true;
480 have_anyelement_result = true;
484 have_anyrange_result = true;
490 if (!have_anyelement_result && !have_anyarray_result &&
491 !have_anyrange_result)
495 * Otherwise, extract actual datatype(s) from input arguments. (We assume
496 * the parser already validated consistency of the arguments.)
499 return false; /* no hope */
501 for (i = 0; i < nargs; i++)
503 switch (declared_args->values[i])
508 if (!OidIsValid(anyelement_type))
509 anyelement_type = get_call_expr_argtype(call_expr, i);
512 if (!OidIsValid(anyarray_type))
513 anyarray_type = get_call_expr_argtype(call_expr, i);
516 if (!OidIsValid(anyrange_type))
517 anyrange_type = get_call_expr_argtype(call_expr, i);
524 /* If nothing found, parser messed up */
525 if (!OidIsValid(anyelement_type) && !OidIsValid(anyarray_type) &&
526 !OidIsValid(anyrange_type))
529 /* If needed, deduce one polymorphic type from others */
530 if (have_anyelement_result && !OidIsValid(anyelement_type))
532 if (OidIsValid(anyarray_type))
533 anyelement_type = resolve_generic_type(ANYELEMENTOID,
536 if (OidIsValid(anyrange_type))
538 Oid subtype = resolve_generic_type(ANYELEMENTOID,
542 /* check for inconsistent array and range results */
543 if (OidIsValid(anyelement_type) && anyelement_type != subtype)
545 anyelement_type = subtype;
549 if (have_anyarray_result && !OidIsValid(anyarray_type))
550 anyarray_type = resolve_generic_type(ANYARRAYOID,
555 * We can't deduce a range type from other polymorphic inputs, because
556 * there may be multiple range types for the same subtype.
558 if (have_anyrange_result && !OidIsValid(anyrange_type))
561 /* Enforce ANYNONARRAY if needed */
562 if (have_anynonarray && type_is_array(anyelement_type))
565 /* Enforce ANYENUM if needed */
566 if (have_anyenum && !type_is_enum(anyelement_type))
570 * Identify the collation to use for polymorphic OUT parameters. (It'll
571 * necessarily be the same for both anyelement and anyarray.) Note that
572 * range types are not collatable, so any possible internal collation of a
573 * range type is not considered here.
575 if (OidIsValid(anyelement_type))
576 anycollation = get_typcollation(anyelement_type);
577 else if (OidIsValid(anyarray_type))
578 anycollation = get_typcollation(anyarray_type);
580 if (OidIsValid(anycollation))
583 * The types are collatable, so consider whether to use a nondefault
584 * collation. We do so if we can identify the input collation used
587 Oid inputcollation = exprInputCollation(call_expr);
589 if (OidIsValid(inputcollation))
590 anycollation = inputcollation;
593 /* And finally replace the tuple column types as needed */
594 for (i = 0; i < natts; i++)
596 Form_pg_attribute att = TupleDescAttr(tupdesc, i);
598 switch (att->atttypid)
603 TupleDescInitEntry(tupdesc, i + 1,
604 NameStr(att->attname),
608 TupleDescInitEntryCollation(tupdesc, i + 1, anycollation);
611 TupleDescInitEntry(tupdesc, i + 1,
612 NameStr(att->attname),
616 TupleDescInitEntryCollation(tupdesc, i + 1, anycollation);
619 TupleDescInitEntry(tupdesc, i + 1,
620 NameStr(att->attname),
624 /* no collation should be attached to a range type */
635 * Given the declared argument types and modes for a function, replace any
636 * polymorphic types (ANYELEMENT etc) with correct data types deduced from the
637 * input arguments. Returns true if able to deduce all types, false if not.
638 * This is the same logic as resolve_polymorphic_tupdesc, but with a different
639 * argument representation.
641 * argmodes may be NULL, in which case all arguments are assumed to be IN mode.
644 resolve_polymorphic_argtypes(int numargs, Oid *argtypes, char *argmodes,
647 bool have_anyelement_result = false;
648 bool have_anyarray_result = false;
649 bool have_anyrange_result = false;
650 Oid anyelement_type = InvalidOid;
651 Oid anyarray_type = InvalidOid;
652 Oid anyrange_type = InvalidOid;
656 /* First pass: resolve polymorphic inputs, check for outputs */
658 for (i = 0; i < numargs; i++)
660 char argmode = argmodes ? argmodes[i] : PROARGMODE_IN;
667 if (argmode == PROARGMODE_OUT || argmode == PROARGMODE_TABLE)
668 have_anyelement_result = true;
671 if (!OidIsValid(anyelement_type))
673 anyelement_type = get_call_expr_argtype(call_expr,
675 if (!OidIsValid(anyelement_type))
678 argtypes[i] = anyelement_type;
682 if (argmode == PROARGMODE_OUT || argmode == PROARGMODE_TABLE)
683 have_anyarray_result = true;
686 if (!OidIsValid(anyarray_type))
688 anyarray_type = get_call_expr_argtype(call_expr,
690 if (!OidIsValid(anyarray_type))
693 argtypes[i] = anyarray_type;
697 if (argmode == PROARGMODE_OUT || argmode == PROARGMODE_TABLE)
698 have_anyrange_result = true;
701 if (!OidIsValid(anyrange_type))
703 anyrange_type = get_call_expr_argtype(call_expr,
705 if (!OidIsValid(anyrange_type))
708 argtypes[i] = anyrange_type;
714 if (argmode != PROARGMODE_OUT && argmode != PROARGMODE_TABLE)
719 if (!have_anyelement_result && !have_anyarray_result &&
720 !have_anyrange_result)
723 /* If no input polymorphics, parser messed up */
724 if (!OidIsValid(anyelement_type) && !OidIsValid(anyarray_type) &&
725 !OidIsValid(anyrange_type))
728 /* If needed, deduce one polymorphic type from others */
729 if (have_anyelement_result && !OidIsValid(anyelement_type))
731 if (OidIsValid(anyarray_type))
732 anyelement_type = resolve_generic_type(ANYELEMENTOID,
735 if (OidIsValid(anyrange_type))
737 Oid subtype = resolve_generic_type(ANYELEMENTOID,
741 /* check for inconsistent array and range results */
742 if (OidIsValid(anyelement_type) && anyelement_type != subtype)
744 anyelement_type = subtype;
748 if (have_anyarray_result && !OidIsValid(anyarray_type))
749 anyarray_type = resolve_generic_type(ANYARRAYOID,
754 * We can't deduce a range type from other polymorphic inputs, because
755 * there may be multiple range types for the same subtype.
757 if (have_anyrange_result && !OidIsValid(anyrange_type))
760 /* XXX do we need to enforce ANYNONARRAY or ANYENUM here? I think not */
762 /* And finally replace the output column types as needed */
763 for (i = 0; i < numargs; i++)
770 argtypes[i] = anyelement_type;
773 argtypes[i] = anyarray_type;
776 argtypes[i] = anyrange_type;
787 * get_type_func_class
788 * Given the type OID, obtain its TYPEFUNC classification.
789 * Also, if it's a domain, return the base type OID.
791 * This is intended to centralize a bunch of formerly ad-hoc code for
792 * classifying types. The categories used here are useful for deciding
793 * how to handle functions returning the datatype.
796 get_type_func_class(Oid typid, Oid *base_typeid)
798 *base_typeid = typid;
800 switch (get_typtype(typid))
802 case TYPTYPE_COMPOSITE:
803 return TYPEFUNC_COMPOSITE;
807 return TYPEFUNC_SCALAR;
809 *base_typeid = typid = getBaseType(typid);
810 if (get_typtype(typid) == TYPTYPE_COMPOSITE)
811 return TYPEFUNC_COMPOSITE_DOMAIN;
812 else /* domain base type can't be a pseudotype */
813 return TYPEFUNC_SCALAR;
815 if (typid == RECORDOID)
816 return TYPEFUNC_RECORD;
819 * We treat VOID and CSTRING as legitimate scalar datatypes,
820 * mostly for the convenience of the JDBC driver (which wants to
821 * be able to do "SELECT * FROM foo()" for all legitimately
822 * user-callable functions).
824 if (typid == VOIDOID || typid == CSTRINGOID)
825 return TYPEFUNC_SCALAR;
826 return TYPEFUNC_OTHER;
828 /* shouldn't get here, probably */
829 return TYPEFUNC_OTHER;
836 * Fetch info about the argument types, names, and IN/OUT modes from the
837 * pg_proc tuple. Return value is the total number of arguments.
838 * Other results are palloc'd. *p_argtypes is always filled in, but
839 * *p_argnames and *p_argmodes will be set NULL in the default cases
840 * (no names, and all IN arguments, respectively).
842 * Note that this function simply fetches what is in the pg_proc tuple;
843 * it doesn't do any interpretation of polymorphic types.
846 get_func_arg_info(HeapTuple procTup,
847 Oid **p_argtypes, char ***p_argnames, char **p_argmodes)
849 Form_pg_proc procStruct = (Form_pg_proc) GETSTRUCT(procTup);
850 Datum proallargtypes;
860 /* First discover the total number of parameters and get their types */
861 proallargtypes = SysCacheGetAttr(PROCOID, procTup,
862 Anum_pg_proc_proallargtypes,
867 * We expect the arrays to be 1-D arrays of the right types; verify
868 * that. For the OID and char arrays, we don't need to use
869 * deconstruct_array() since the array data is just going to look like
870 * a C array of values.
872 arr = DatumGetArrayTypeP(proallargtypes); /* ensure not toasted */
873 numargs = ARR_DIMS(arr)[0];
874 if (ARR_NDIM(arr) != 1 ||
877 ARR_ELEMTYPE(arr) != OIDOID)
878 elog(ERROR, "proallargtypes is not a 1-D Oid array");
879 Assert(numargs >= procStruct->pronargs);
880 *p_argtypes = (Oid *) palloc(numargs * sizeof(Oid));
881 memcpy(*p_argtypes, ARR_DATA_PTR(arr),
882 numargs * sizeof(Oid));
886 /* If no proallargtypes, use proargtypes */
887 numargs = procStruct->proargtypes.dim1;
888 Assert(numargs == procStruct->pronargs);
889 *p_argtypes = (Oid *) palloc(numargs * sizeof(Oid));
890 memcpy(*p_argtypes, procStruct->proargtypes.values,
891 numargs * sizeof(Oid));
894 /* Get argument names, if available */
895 proargnames = SysCacheGetAttr(PROCOID, procTup,
896 Anum_pg_proc_proargnames,
902 deconstruct_array(DatumGetArrayTypeP(proargnames),
903 TEXTOID, -1, false, 'i',
904 &elems, NULL, &nelems);
905 if (nelems != numargs) /* should not happen */
906 elog(ERROR, "proargnames must have the same number of elements as the function has arguments");
907 *p_argnames = (char **) palloc(sizeof(char *) * numargs);
908 for (i = 0; i < numargs; i++)
909 (*p_argnames)[i] = TextDatumGetCString(elems[i]);
912 /* Get argument modes, if available */
913 proargmodes = SysCacheGetAttr(PROCOID, procTup,
914 Anum_pg_proc_proargmodes,
920 arr = DatumGetArrayTypeP(proargmodes); /* ensure not toasted */
921 if (ARR_NDIM(arr) != 1 ||
922 ARR_DIMS(arr)[0] != numargs ||
924 ARR_ELEMTYPE(arr) != CHAROID)
925 elog(ERROR, "proargmodes is not a 1-D char array");
926 *p_argmodes = (char *) palloc(numargs * sizeof(char));
927 memcpy(*p_argmodes, ARR_DATA_PTR(arr),
928 numargs * sizeof(char));
937 * Returns the number of transformed types used by function.
940 get_func_trftypes(HeapTuple procTup,
948 protrftypes = SysCacheGetAttr(PROCOID, procTup,
949 Anum_pg_proc_protrftypes,
954 * We expect the arrays to be 1-D arrays of the right types; verify
955 * that. For the OID and char arrays, we don't need to use
956 * deconstruct_array() since the array data is just going to look like
957 * a C array of values.
959 arr = DatumGetArrayTypeP(protrftypes); /* ensure not toasted */
960 nelems = ARR_DIMS(arr)[0];
961 if (ARR_NDIM(arr) != 1 ||
964 ARR_ELEMTYPE(arr) != OIDOID)
965 elog(ERROR, "protrftypes is not a 1-D Oid array");
966 Assert(nelems >= ((Form_pg_proc) GETSTRUCT(procTup))->pronargs);
967 *p_trftypes = (Oid *) palloc(nelems * sizeof(Oid));
968 memcpy(*p_trftypes, ARR_DATA_PTR(arr),
969 nelems * sizeof(Oid));
978 * get_func_input_arg_names
980 * Extract the names of input arguments only, given a function's
981 * proargnames and proargmodes entries in Datum form.
983 * Returns the number of input arguments, which is the length of the
984 * palloc'd array returned to *arg_names. Entries for unnamed args
985 * are set to NULL. You don't get anything if proargnames is NULL.
988 get_func_input_arg_names(Datum proargnames, Datum proargmodes,
999 /* Do nothing if null proargnames */
1000 if (proargnames == PointerGetDatum(NULL))
1007 * We expect the arrays to be 1-D arrays of the right types; verify that.
1008 * For proargmodes, we don't need to use deconstruct_array() since the
1009 * array data is just going to look like a C array of values.
1011 arr = DatumGetArrayTypeP(proargnames); /* ensure not toasted */
1012 if (ARR_NDIM(arr) != 1 ||
1014 ARR_ELEMTYPE(arr) != TEXTOID)
1015 elog(ERROR, "proargnames is not a 1-D text array");
1016 deconstruct_array(arr, TEXTOID, -1, false, 'i',
1017 &argnames, NULL, &numargs);
1018 if (proargmodes != PointerGetDatum(NULL))
1020 arr = DatumGetArrayTypeP(proargmodes); /* ensure not toasted */
1021 if (ARR_NDIM(arr) != 1 ||
1022 ARR_DIMS(arr)[0] != numargs ||
1024 ARR_ELEMTYPE(arr) != CHAROID)
1025 elog(ERROR, "proargmodes is not a 1-D char array");
1026 argmodes = (char *) ARR_DATA_PTR(arr);
1031 /* zero elements probably shouldn't happen, but handle it gracefully */
1038 /* extract input-argument names */
1039 inargnames = (char **) palloc(numargs * sizeof(char *));
1041 for (i = 0; i < numargs; i++)
1043 if (argmodes == NULL ||
1044 argmodes[i] == PROARGMODE_IN ||
1045 argmodes[i] == PROARGMODE_INOUT ||
1046 argmodes[i] == PROARGMODE_VARIADIC)
1048 char *pname = TextDatumGetCString(argnames[i]);
1050 if (pname[0] != '\0')
1051 inargnames[numinargs] = pname;
1053 inargnames[numinargs] = NULL;
1058 *arg_names = inargnames;
1064 * get_func_result_name
1066 * If the function has exactly one output parameter, and that parameter
1067 * is named, return the name (as a palloc'd string). Else return NULL.
1069 * This is used to determine the default output column name for functions
1070 * returning scalar types.
1073 get_func_result_name(Oid functionId)
1076 HeapTuple procTuple;
1088 /* First fetch the function's pg_proc row */
1089 procTuple = SearchSysCache1(PROCOID, ObjectIdGetDatum(functionId));
1090 if (!HeapTupleIsValid(procTuple))
1091 elog(ERROR, "cache lookup failed for function %u", functionId);
1093 /* If there are no named OUT parameters, return NULL */
1094 if (heap_attisnull(procTuple, Anum_pg_proc_proargmodes, NULL) ||
1095 heap_attisnull(procTuple, Anum_pg_proc_proargnames, NULL))
1099 /* Get the data out of the tuple */
1100 proargmodes = SysCacheGetAttr(PROCOID, procTuple,
1101 Anum_pg_proc_proargmodes,
1104 proargnames = SysCacheGetAttr(PROCOID, procTuple,
1105 Anum_pg_proc_proargnames,
1110 * We expect the arrays to be 1-D arrays of the right types; verify
1111 * that. For the char array, we don't need to use deconstruct_array()
1112 * since the array data is just going to look like a C array of
1115 arr = DatumGetArrayTypeP(proargmodes); /* ensure not toasted */
1116 numargs = ARR_DIMS(arr)[0];
1117 if (ARR_NDIM(arr) != 1 ||
1120 ARR_ELEMTYPE(arr) != CHAROID)
1121 elog(ERROR, "proargmodes is not a 1-D char array");
1122 argmodes = (char *) ARR_DATA_PTR(arr);
1123 arr = DatumGetArrayTypeP(proargnames); /* ensure not toasted */
1124 if (ARR_NDIM(arr) != 1 ||
1125 ARR_DIMS(arr)[0] != numargs ||
1127 ARR_ELEMTYPE(arr) != TEXTOID)
1128 elog(ERROR, "proargnames is not a 1-D text array");
1129 deconstruct_array(arr, TEXTOID, -1, false, 'i',
1130 &argnames, NULL, &nargnames);
1131 Assert(nargnames == numargs);
1133 /* scan for output argument(s) */
1136 for (i = 0; i < numargs; i++)
1138 if (argmodes[i] == PROARGMODE_IN ||
1139 argmodes[i] == PROARGMODE_VARIADIC)
1141 Assert(argmodes[i] == PROARGMODE_OUT ||
1142 argmodes[i] == PROARGMODE_INOUT ||
1143 argmodes[i] == PROARGMODE_TABLE);
1144 if (++numoutargs > 1)
1146 /* multiple out args, so forget it */
1150 result = TextDatumGetCString(argnames[i]);
1151 if (result == NULL || result[0] == '\0')
1153 /* Parameter is not named, so forget it */
1160 ReleaseSysCache(procTuple);
1167 * build_function_result_tupdesc_t
1169 * Given a pg_proc row for a function, return a tuple descriptor for the
1170 * result rowtype, or NULL if the function does not have OUT parameters.
1172 * Note that this does not handle resolution of polymorphic types;
1173 * that is deliberate.
1176 build_function_result_tupdesc_t(HeapTuple procTuple)
1178 Form_pg_proc procform = (Form_pg_proc) GETSTRUCT(procTuple);
1179 Datum proallargtypes;
1184 /* Return NULL if the function isn't declared to return RECORD */
1185 if (procform->prorettype != RECORDOID)
1188 /* If there are no OUT parameters, return NULL */
1189 if (heap_attisnull(procTuple, Anum_pg_proc_proallargtypes, NULL) ||
1190 heap_attisnull(procTuple, Anum_pg_proc_proargmodes, NULL))
1193 /* Get the data out of the tuple */
1194 proallargtypes = SysCacheGetAttr(PROCOID, procTuple,
1195 Anum_pg_proc_proallargtypes,
1198 proargmodes = SysCacheGetAttr(PROCOID, procTuple,
1199 Anum_pg_proc_proargmodes,
1202 proargnames = SysCacheGetAttr(PROCOID, procTuple,
1203 Anum_pg_proc_proargnames,
1206 proargnames = PointerGetDatum(NULL); /* just to be sure */
1208 return build_function_result_tupdesc_d(procform->prokind,
1215 * build_function_result_tupdesc_d
1217 * Build a RECORD function's tupledesc from the pg_proc proallargtypes,
1218 * proargmodes, and proargnames arrays. This is split out for the
1219 * convenience of ProcedureCreate, which needs to be able to compute the
1220 * tupledesc before actually creating the function.
1222 * For functions (but not for procedures), returns NULL if there are not at
1223 * least two OUT or INOUT arguments.
1226 build_function_result_tupdesc_d(char prokind,
1227 Datum proallargtypes,
1236 Datum *argnames = NULL;
1243 /* Can't have output args if columns are null */
1244 if (proallargtypes == PointerGetDatum(NULL) ||
1245 proargmodes == PointerGetDatum(NULL))
1249 * We expect the arrays to be 1-D arrays of the right types; verify that.
1250 * For the OID and char arrays, we don't need to use deconstruct_array()
1251 * since the array data is just going to look like a C array of values.
1253 arr = DatumGetArrayTypeP(proallargtypes); /* ensure not toasted */
1254 numargs = ARR_DIMS(arr)[0];
1255 if (ARR_NDIM(arr) != 1 ||
1258 ARR_ELEMTYPE(arr) != OIDOID)
1259 elog(ERROR, "proallargtypes is not a 1-D Oid array");
1260 argtypes = (Oid *) ARR_DATA_PTR(arr);
1261 arr = DatumGetArrayTypeP(proargmodes); /* ensure not toasted */
1262 if (ARR_NDIM(arr) != 1 ||
1263 ARR_DIMS(arr)[0] != numargs ||
1265 ARR_ELEMTYPE(arr) != CHAROID)
1266 elog(ERROR, "proargmodes is not a 1-D char array");
1267 argmodes = (char *) ARR_DATA_PTR(arr);
1268 if (proargnames != PointerGetDatum(NULL))
1270 arr = DatumGetArrayTypeP(proargnames); /* ensure not toasted */
1271 if (ARR_NDIM(arr) != 1 ||
1272 ARR_DIMS(arr)[0] != numargs ||
1274 ARR_ELEMTYPE(arr) != TEXTOID)
1275 elog(ERROR, "proargnames is not a 1-D text array");
1276 deconstruct_array(arr, TEXTOID, -1, false, 'i',
1277 &argnames, NULL, &nargnames);
1278 Assert(nargnames == numargs);
1281 /* zero elements probably shouldn't happen, but handle it gracefully */
1285 /* extract output-argument types and names */
1286 outargtypes = (Oid *) palloc(numargs * sizeof(Oid));
1287 outargnames = (char **) palloc(numargs * sizeof(char *));
1289 for (i = 0; i < numargs; i++)
1293 if (argmodes[i] == PROARGMODE_IN ||
1294 argmodes[i] == PROARGMODE_VARIADIC)
1296 Assert(argmodes[i] == PROARGMODE_OUT ||
1297 argmodes[i] == PROARGMODE_INOUT ||
1298 argmodes[i] == PROARGMODE_TABLE);
1299 outargtypes[numoutargs] = argtypes[i];
1301 pname = TextDatumGetCString(argnames[i]);
1304 if (pname == NULL || pname[0] == '\0')
1306 /* Parameter is not named, so gin up a column name */
1307 pname = psprintf("column%d", numoutargs + 1);
1309 outargnames[numoutargs] = pname;
1314 * If there is no output argument, or only one, the function does not
1317 if (numoutargs < 2 && prokind != PROKIND_PROCEDURE)
1320 desc = CreateTemplateTupleDesc(numoutargs, false);
1321 for (i = 0; i < numoutargs; i++)
1323 TupleDescInitEntry(desc, i + 1,
1335 * RelationNameGetTupleDesc
1337 * Given a (possibly qualified) relation name, build a TupleDesc.
1339 * Note: while this works as advertised, it's seldom the best way to
1340 * build a tupdesc for a function's result type. It's kept around
1341 * only for backwards compatibility with existing user-written code.
1344 RelationNameGetTupleDesc(const char *relname)
1351 /* Open relation and copy the tuple description */
1352 relname_list = stringToQualifiedNameList(relname);
1353 relvar = makeRangeVarFromNameList(relname_list);
1354 rel = relation_openrv(relvar, AccessShareLock);
1355 tupdesc = CreateTupleDescCopy(RelationGetDescr(rel));
1356 relation_close(rel, AccessShareLock);
1364 * Given a type Oid, build a TupleDesc. (In most cases you should be
1365 * using get_call_result_type or one of its siblings instead of this
1366 * routine, so that you can handle OUT parameters, RECORD result type,
1367 * and polymorphic results.)
1369 * If the type is composite, *and* a colaliases List is provided, *and*
1370 * the List is of natts length, use the aliases instead of the relation
1371 * attnames. (NB: this usage is deprecated since it may result in
1372 * creation of unnecessary transient record types.)
1374 * If the type is a base type, a single item alias List is required.
1377 TypeGetTupleDesc(Oid typeoid, List *colaliases)
1380 TypeFuncClass functypclass = get_type_func_class(typeoid, &base_typeoid);
1381 TupleDesc tupdesc = NULL;
1384 * Build a suitable tupledesc representing the output rows. We
1385 * intentionally do not support TYPEFUNC_COMPOSITE_DOMAIN here, as it's
1386 * unlikely that legacy callers of this obsolete function would be
1387 * prepared to apply domain constraints.
1389 if (functypclass == TYPEFUNC_COMPOSITE)
1391 /* Composite data type, e.g. a table's row type */
1392 tupdesc = lookup_rowtype_tupdesc_copy(base_typeoid, -1);
1394 if (colaliases != NIL)
1396 int natts = tupdesc->natts;
1399 /* does the list length match the number of attributes? */
1400 if (list_length(colaliases) != natts)
1402 (errcode(ERRCODE_DATATYPE_MISMATCH),
1403 errmsg("number of aliases does not match number of columns")));
1405 /* OK, use the aliases instead */
1406 for (varattno = 0; varattno < natts; varattno++)
1408 char *label = strVal(list_nth(colaliases, varattno));
1409 Form_pg_attribute attr = TupleDescAttr(tupdesc, varattno);
1412 namestrcpy(&(attr->attname), label);
1415 /* The tuple type is now an anonymous record type */
1416 tupdesc->tdtypeid = RECORDOID;
1417 tupdesc->tdtypmod = -1;
1420 else if (functypclass == TYPEFUNC_SCALAR)
1422 /* Base data type, i.e. scalar */
1425 /* the alias list is required for base types */
1426 if (colaliases == NIL)
1428 (errcode(ERRCODE_DATATYPE_MISMATCH),
1429 errmsg("no column alias was provided")));
1431 /* the alias list length must be 1 */
1432 if (list_length(colaliases) != 1)
1434 (errcode(ERRCODE_DATATYPE_MISMATCH),
1435 errmsg("number of aliases does not match number of columns")));
1437 /* OK, get the column alias */
1438 attname = strVal(linitial(colaliases));
1440 tupdesc = CreateTemplateTupleDesc(1, false);
1441 TupleDescInitEntry(tupdesc,
1448 else if (functypclass == TYPEFUNC_RECORD)
1450 /* XXX can't support this because typmod wasn't passed in ... */
1452 (errcode(ERRCODE_DATATYPE_MISMATCH),
1453 errmsg("could not determine row description for function returning record")));
1457 /* crummy error message, but parser should have caught this */
1458 elog(ERROR, "function in FROM has unsupported return type");
1465 * extract_variadic_args
1467 * Extract a set of argument values, types and NULL markers for a given
1468 * input function which makes use of a VARIADIC input whose argument list
1469 * depends on the caller context. When doing a VARIADIC call, the caller
1470 * has provided one argument made of an array of values, so deconstruct the
1471 * array data before using it for the next processing. If no VARIADIC call
1472 * is used, just fill in the status data based on all the arguments given
1475 * This function returns the number of arguments generated, or -1 in the
1476 * case of "VARIADIC NULL".
1479 extract_variadic_args(FunctionCallInfo fcinfo, int variadic_start,
1480 bool convert_unknown, Datum **args, Oid **types,
1483 bool variadic = get_fn_expr_variadic(fcinfo->flinfo);
1496 ArrayType *array_in;
1502 Assert(PG_NARGS() == variadic_start + 1);
1504 if (PG_ARGISNULL(variadic_start))
1507 array_in = PG_GETARG_ARRAYTYPE_P(variadic_start);
1508 element_type = ARR_ELEMTYPE(array_in);
1510 get_typlenbyvalalign(element_type,
1511 &typlen, &typbyval, &typalign);
1512 deconstruct_array(array_in, element_type, typlen, typbyval,
1513 typalign, &args_res, &nulls_res,
1516 /* All the elements of the array have the same type */
1517 types_res = (Oid *) palloc0(nargs * sizeof(Oid));
1518 for (i = 0; i < nargs; i++)
1519 types_res[i] = element_type;
1523 nargs = PG_NARGS() - variadic_start;
1525 nulls_res = (bool *) palloc0(nargs * sizeof(bool));
1526 args_res = (Datum *) palloc0(nargs * sizeof(Datum));
1527 types_res = (Oid *) palloc0(nargs * sizeof(Oid));
1529 for (i = 0; i < nargs; i++)
1531 nulls_res[i] = PG_ARGISNULL(i + variadic_start);
1532 types_res[i] = get_fn_expr_argtype(fcinfo->flinfo,
1533 i + variadic_start);
1536 * Turn a constant (more or less literal) value that's of unknown
1537 * type into text if required. Unknowns come in as a cstring
1538 * pointer. Note: for functions declared as taking type "any", the
1539 * parser will not do any type conversion on unknown-type literals
1540 * (that is, undecorated strings or NULLs).
1542 if (convert_unknown &&
1543 types_res[i] == UNKNOWNOID &&
1544 get_fn_expr_arg_stable(fcinfo->flinfo, i + variadic_start))
1546 types_res[i] = TEXTOID;
1548 if (PG_ARGISNULL(i + variadic_start))
1549 args_res[i] = (Datum) 0;
1552 CStringGetTextDatum(PG_GETARG_POINTER(i + variadic_start));
1556 /* no conversion needed, just take the datum as given */
1557 args_res[i] = PG_GETARG_DATUM(i + variadic_start);
1560 if (!OidIsValid(types_res[i]) ||
1561 (convert_unknown && types_res[i] == UNKNOWNOID))
1563 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1564 errmsg("could not determine data type for argument %d",
1569 /* Fill in results */