1 /*-------------------------------------------------------------------------
4 * Utility and convenience functions for fmgr functions that return
5 * sets and/or composite types.
7 * Copyright (c) 2002-2005, PostgreSQL Global Development Group
10 * $PostgreSQL: pgsql/src/backend/utils/fmgr/funcapi.c,v 1.21 2005/04/25 20:59:44 tgl Exp $
12 *-------------------------------------------------------------------------
16 #include "access/heapam.h"
18 #include "catalog/namespace.h"
19 #include "catalog/pg_proc.h"
20 #include "catalog/pg_type.h"
21 #include "parser/parse_coerce.h"
22 #include "parser/parse_expr.h"
23 #include "utils/array.h"
24 #include "utils/builtins.h"
25 #include "utils/lsyscache.h"
26 #include "utils/syscache.h"
27 #include "utils/typcache.h"
30 static void shutdown_MultiFuncCall(Datum arg);
31 static TypeFuncClass internal_get_result_type(Oid funcid,
33 ReturnSetInfo *rsinfo,
35 TupleDesc *resultTupleDesc);
36 static bool resolve_polymorphic_tupdesc(TupleDesc tupdesc,
37 oidvector *declared_args,
39 static TypeFuncClass get_type_func_class(Oid typid);
44 * Create an empty FuncCallContext data structure
45 * and do some other basic Multi-function call setup
49 init_MultiFuncCall(PG_FUNCTION_ARGS)
51 FuncCallContext *retval;
54 * Bail if we're called in the wrong context
56 if (fcinfo->resultinfo == NULL || !IsA(fcinfo->resultinfo, ReturnSetInfo))
58 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
59 errmsg("set-valued function called in context that cannot accept a set")));
61 if (fcinfo->flinfo->fn_extra == NULL)
66 ReturnSetInfo *rsi = (ReturnSetInfo *) fcinfo->resultinfo;
69 * Allocate suitably long-lived space and zero it
71 retval = (FuncCallContext *)
72 MemoryContextAllocZero(fcinfo->flinfo->fn_mcxt,
73 sizeof(FuncCallContext));
76 * initialize the elements
78 retval->call_cntr = 0;
79 retval->max_calls = 0;
81 retval->user_fctx = NULL;
82 retval->attinmeta = NULL;
83 retval->tuple_desc = NULL;
84 retval->multi_call_memory_ctx = fcinfo->flinfo->fn_mcxt;
87 * save the pointer for cross-call use
89 fcinfo->flinfo->fn_extra = retval;
92 * Ensure we will get shut down cleanly if the exprcontext is not
95 RegisterExprContextCallback(rsi->econtext,
96 shutdown_MultiFuncCall,
97 PointerGetDatum(fcinfo->flinfo));
101 /* second and subsequent calls */
102 elog(ERROR, "init_MultiFuncCall may not be called more than once");
104 /* never reached, but keep compiler happy */
114 * Do Multi-function per-call setup
117 per_MultiFuncCall(PG_FUNCTION_ARGS)
119 FuncCallContext *retval = (FuncCallContext *) fcinfo->flinfo->fn_extra;
122 * Clear the TupleTableSlot, if present. This is for safety's sake:
123 * the Slot will be in a long-lived context (it better be, if the
124 * FuncCallContext is pointing to it), but in most usage patterns the
125 * tuples stored in it will be in the function's per-tuple context. So
126 * at the beginning of each call, the Slot will hold a dangling
127 * pointer to an already-recycled tuple. We clear it out here.
129 * Note: use of retval->slot is obsolete as of 8.0, and we expect that it
130 * will always be NULL. This is just here for backwards compatibility
131 * in case someone creates a slot anyway.
133 if (retval->slot != NULL)
134 ExecClearTuple(retval->slot);
141 * Clean up after init_MultiFuncCall
144 end_MultiFuncCall(PG_FUNCTION_ARGS, FuncCallContext *funcctx)
146 ReturnSetInfo *rsi = (ReturnSetInfo *) fcinfo->resultinfo;
148 /* Deregister the shutdown callback */
149 UnregisterExprContextCallback(rsi->econtext,
150 shutdown_MultiFuncCall,
151 PointerGetDatum(fcinfo->flinfo));
153 /* But use it to do the real work */
154 shutdown_MultiFuncCall(PointerGetDatum(fcinfo->flinfo));
158 * shutdown_MultiFuncCall
159 * Shutdown function to clean up after init_MultiFuncCall
162 shutdown_MultiFuncCall(Datum arg)
164 FmgrInfo *flinfo = (FmgrInfo *) DatumGetPointer(arg);
165 FuncCallContext *funcctx = (FuncCallContext *) flinfo->fn_extra;
167 /* unbind from flinfo */
168 flinfo->fn_extra = NULL;
171 * Caller is responsible to free up memory for individual struct
172 * elements other than att_in_funcinfo and elements.
174 if (funcctx->attinmeta != NULL)
175 pfree(funcctx->attinmeta);
182 * get_call_result_type
183 * Given a function's call info record, determine the kind of datatype
184 * it is supposed to return. If resultTypeId isn't NULL, *resultTypeId
185 * receives the actual datatype OID (this is mainly useful for scalar
186 * result types). If resultTupleDesc isn't NULL, *resultTupleDesc
187 * receives a pointer to a TupleDesc when the result is of a composite
188 * type, or NULL when it's a scalar result. NB: the tupledesc should
189 * be copied if it is to be accessed over a long period.
191 * One hard case that this handles is resolution of actual rowtypes for
192 * functions returning RECORD (from either the function's OUT parameter
193 * list, or a ReturnSetInfo context node). TYPEFUNC_RECORD is returned
194 * only when we couldn't resolve the actual rowtype for lack of information.
196 * The other hard case that this handles is resolution of polymorphism.
197 * We will never return ANYELEMENT or ANYARRAY, either as a scalar result
198 * type or as a component of a rowtype.
200 * This function is relatively expensive --- in a function returning set,
201 * try to call it only the first time through.
204 get_call_result_type(FunctionCallInfo fcinfo,
206 TupleDesc *resultTupleDesc)
208 return internal_get_result_type(fcinfo->flinfo->fn_oid,
209 fcinfo->flinfo->fn_expr,
210 (ReturnSetInfo *) fcinfo->resultinfo,
216 * get_expr_result_type
217 * As above, but work from a calling expression node tree
220 get_expr_result_type(Node *expr,
222 TupleDesc *resultTupleDesc)
224 TypeFuncClass result;
226 if (expr && IsA(expr, FuncExpr))
227 result = internal_get_result_type(((FuncExpr *) expr)->funcid,
232 else if (expr && IsA(expr, OpExpr))
233 result = internal_get_result_type(get_opcode(((OpExpr *) expr)->opno),
240 /* handle as a generic expression; no chance to resolve RECORD */
241 Oid typid = exprType(expr);
244 *resultTypeId = typid;
246 *resultTupleDesc = NULL;
247 result = get_type_func_class(typid);
248 if (result == TYPEFUNC_COMPOSITE && resultTupleDesc)
249 *resultTupleDesc = lookup_rowtype_tupdesc(typid, -1);
256 * get_func_result_type
257 * As above, but work from a function's OID only
259 * This will not be able to resolve pure-RECORD results nor polymorphism.
262 get_func_result_type(Oid functionId,
264 TupleDesc *resultTupleDesc)
266 return internal_get_result_type(functionId,
274 * internal_get_result_type -- workhorse code implementing all the above
276 * funcid must always be supplied. call_expr and rsinfo can be NULL if not
277 * available. We will return TYPEFUNC_RECORD, and store NULL into
278 * *resultTupleDesc, if we cannot deduce the complete result rowtype from
279 * the available information.
282 internal_get_result_type(Oid funcid,
284 ReturnSetInfo *rsinfo,
286 TupleDesc *resultTupleDesc)
288 TypeFuncClass result;
290 Form_pg_proc procform;
294 /* First fetch the function's pg_proc row to inspect its rettype */
295 tp = SearchSysCache(PROCOID,
296 ObjectIdGetDatum(funcid),
298 if (!HeapTupleIsValid(tp))
299 elog(ERROR, "cache lookup failed for function %u", funcid);
300 procform = (Form_pg_proc) GETSTRUCT(tp);
302 rettype = procform->prorettype;
304 /* Check for OUT parameters defining a RECORD result */
305 tupdesc = build_function_result_tupdesc_t(tp);
309 * It has OUT parameters, so it's basically like a regular
310 * composite type, except we have to be able to resolve any
311 * polymorphic OUT parameters.
314 *resultTypeId = rettype;
316 if (resolve_polymorphic_tupdesc(tupdesc,
317 &procform->proargtypes,
320 if (tupdesc->tdtypeid == RECORDOID &&
321 tupdesc->tdtypmod < 0)
322 assign_record_type_typmod(tupdesc);
324 *resultTupleDesc = tupdesc;
325 result = TYPEFUNC_COMPOSITE;
330 *resultTupleDesc = NULL;
331 result = TYPEFUNC_RECORD;
340 * If scalar polymorphic result, try to resolve it.
342 if (rettype == ANYARRAYOID || rettype == ANYELEMENTOID)
344 Oid newrettype = exprType(call_expr);
346 if (newrettype == InvalidOid) /* this probably should not happen */
348 (errcode(ERRCODE_DATATYPE_MISMATCH),
349 errmsg("could not determine actual result type for function \"%s\" declared to return type %s",
350 NameStr(procform->proname),
351 format_type_be(rettype))));
352 rettype = newrettype;
356 *resultTypeId = rettype;
358 *resultTupleDesc = NULL; /* default result */
360 /* Classify the result type */
361 result = get_type_func_class(rettype);
364 case TYPEFUNC_COMPOSITE:
366 *resultTupleDesc = lookup_rowtype_tupdesc(rettype, -1);
367 /* Named composite types can't have any polymorphic columns */
369 case TYPEFUNC_SCALAR:
371 case TYPEFUNC_RECORD:
372 /* We must get the tupledesc from call context */
373 if (rsinfo && IsA(rsinfo, ReturnSetInfo) &&
374 rsinfo->expectedDesc != NULL)
376 result = TYPEFUNC_COMPOSITE;
378 *resultTupleDesc = rsinfo->expectedDesc;
379 /* Assume no polymorphic columns here, either */
392 * Given the result tuple descriptor for a function with OUT parameters,
393 * replace any polymorphic columns (ANYELEMENT/ANYARRAY) with correct data
394 * types deduced from the input arguments. Returns TRUE if able to deduce
395 * all types, FALSE if not.
398 resolve_polymorphic_tupdesc(TupleDesc tupdesc, oidvector *declared_args,
401 int natts = tupdesc->natts;
402 int nargs = declared_args->dim1;
403 bool have_anyelement_result = false;
404 bool have_anyarray_result = false;
405 Oid anyelement_type = InvalidOid;
406 Oid anyarray_type = InvalidOid;
409 /* See if there are any polymorphic outputs; quick out if not */
410 for (i = 0; i < natts; i++)
412 switch (tupdesc->attrs[i]->atttypid)
415 have_anyelement_result = true;
418 have_anyarray_result = true;
424 if (!have_anyelement_result && !have_anyarray_result)
428 * Otherwise, extract actual datatype(s) from input arguments. (We assume
429 * the parser already validated consistency of the arguments.)
432 return false; /* no hope */
434 for (i = 0; i < nargs; i++)
436 switch (declared_args->values[i])
439 if (!OidIsValid(anyelement_type))
440 anyelement_type = get_call_expr_argtype(call_expr, i);
443 if (!OidIsValid(anyarray_type))
444 anyarray_type = get_call_expr_argtype(call_expr, i);
451 /* If nothing found, parser messed up */
452 if (!OidIsValid(anyelement_type) && !OidIsValid(anyarray_type))
455 /* If needed, deduce one polymorphic type from the other */
456 if (have_anyelement_result && !OidIsValid(anyelement_type))
457 anyelement_type = resolve_generic_type(ANYELEMENTOID,
460 if (have_anyarray_result && !OidIsValid(anyarray_type))
461 anyarray_type = resolve_generic_type(ANYARRAYOID,
465 /* And finally replace the tuple column types as needed */
466 for (i = 0; i < natts; i++)
468 switch (tupdesc->attrs[i]->atttypid)
471 TupleDescInitEntry(tupdesc, i+1,
472 NameStr(tupdesc->attrs[i]->attname),
478 TupleDescInitEntry(tupdesc, i+1,
479 NameStr(tupdesc->attrs[i]->attname),
493 * Given the declared argument types and modes for a function,
494 * replace any polymorphic types (ANYELEMENT/ANYARRAY) with correct data
495 * types deduced from the input arguments. Returns TRUE if able to deduce
496 * all types, FALSE if not. This is the same logic as
497 * resolve_polymorphic_tupdesc, but with a different argument representation.
499 * argmodes may be NULL, in which case all arguments are assumed to be IN mode.
502 resolve_polymorphic_argtypes(int numargs, Oid *argtypes, char *argmodes,
505 bool have_anyelement_result = false;
506 bool have_anyarray_result = false;
507 Oid anyelement_type = InvalidOid;
508 Oid anyarray_type = InvalidOid;
512 /* First pass: resolve polymorphic inputs, check for outputs */
514 for (i = 0; i < numargs; i++)
516 char argmode = argmodes ? argmodes[i] : PROARGMODE_IN;
521 if (argmode == PROARGMODE_OUT)
522 have_anyelement_result = true;
525 if (!OidIsValid(anyelement_type))
527 anyelement_type = get_call_expr_argtype(call_expr,
529 if (!OidIsValid(anyelement_type))
532 argtypes[i] = anyelement_type;
536 if (argmode == PROARGMODE_OUT)
537 have_anyarray_result = true;
540 if (!OidIsValid(anyarray_type))
542 anyarray_type = get_call_expr_argtype(call_expr,
544 if (!OidIsValid(anyarray_type))
547 argtypes[i] = anyarray_type;
553 if (argmode != PROARGMODE_OUT)
558 if (!have_anyelement_result && !have_anyarray_result)
561 /* If no input polymorphics, parser messed up */
562 if (!OidIsValid(anyelement_type) && !OidIsValid(anyarray_type))
565 /* If needed, deduce one polymorphic type from the other */
566 if (have_anyelement_result && !OidIsValid(anyelement_type))
567 anyelement_type = resolve_generic_type(ANYELEMENTOID,
570 if (have_anyarray_result && !OidIsValid(anyarray_type))
571 anyarray_type = resolve_generic_type(ANYARRAYOID,
575 /* And finally replace the output column types as needed */
576 for (i = 0; i < numargs; i++)
581 argtypes[i] = anyelement_type;
584 argtypes[i] = anyarray_type;
595 * get_type_func_class
596 * Given the type OID, obtain its TYPEFUNC classification.
598 * This is intended to centralize a bunch of formerly ad-hoc code for
599 * classifying types. The categories used here are useful for deciding
600 * how to handle functions returning the datatype.
603 get_type_func_class(Oid typid)
605 switch (get_typtype(typid))
608 return TYPEFUNC_COMPOSITE;
611 return TYPEFUNC_SCALAR;
613 if (typid == RECORDOID)
614 return TYPEFUNC_RECORD;
616 * We treat VOID and CSTRING as legitimate scalar datatypes,
617 * mostly for the convenience of the JDBC driver (which wants
618 * to be able to do "SELECT * FROM foo()" for all legitimately
619 * user-callable functions).
621 if (typid == VOIDOID || typid == CSTRINGOID)
622 return TYPEFUNC_SCALAR;
623 return TYPEFUNC_OTHER;
625 /* shouldn't get here, probably */
626 return TYPEFUNC_OTHER;
631 * build_function_result_tupdesc_t
633 * Given a pg_proc row for a function, return a tuple descriptor for the
634 * result rowtype, or NULL if the function does not have OUT parameters.
636 * Note that this does not handle resolution of ANYELEMENT/ANYARRAY types;
637 * that is deliberate.
640 build_function_result_tupdesc_t(HeapTuple procTuple)
642 Form_pg_proc procform = (Form_pg_proc) GETSTRUCT(procTuple);
643 Datum proallargtypes;
648 /* Return NULL if the function isn't declared to return RECORD */
649 if (procform->prorettype != RECORDOID)
652 /* If there are no OUT parameters, return NULL */
653 if (heap_attisnull(procTuple, Anum_pg_proc_proallargtypes) ||
654 heap_attisnull(procTuple, Anum_pg_proc_proargmodes))
657 /* Get the data out of the tuple */
658 proallargtypes = SysCacheGetAttr(PROCOID, procTuple,
659 Anum_pg_proc_proallargtypes,
662 proargmodes = SysCacheGetAttr(PROCOID, procTuple,
663 Anum_pg_proc_proargmodes,
666 proargnames = SysCacheGetAttr(PROCOID, procTuple,
667 Anum_pg_proc_proargnames,
670 proargnames = PointerGetDatum(NULL); /* just to be sure */
672 return build_function_result_tupdesc_d(proallargtypes,
678 * build_function_result_tupdesc_d
680 * Build a RECORD function's tupledesc from the pg_proc proallargtypes,
681 * proargmodes, and proargnames arrays. This is split out for the
682 * convenience of ProcedureCreate, which needs to be able to compute the
683 * tupledesc before actually creating the function.
685 * Returns NULL if there are not at least two OUT or INOUT arguments.
688 build_function_result_tupdesc_d(Datum proallargtypes,
697 Datum *argnames = NULL;
704 /* Can't have output args if columns are null */
705 if (proallargtypes == PointerGetDatum(NULL) ||
706 proargmodes == PointerGetDatum(NULL))
710 * We expect the arrays to be 1-D arrays of the right types; verify that.
711 * For the OID and char arrays, we don't need to use deconstruct_array()
712 * since the array data is just going to look like a C array of values.
714 arr = DatumGetArrayTypeP(proallargtypes); /* ensure not toasted */
715 numargs = ARR_DIMS(arr)[0];
716 if (ARR_NDIM(arr) != 1 ||
718 ARR_ELEMTYPE(arr) != OIDOID)
719 elog(ERROR, "proallargtypes is not a 1-D Oid array");
720 argtypes = (Oid *) ARR_DATA_PTR(arr);
721 arr = DatumGetArrayTypeP(proargmodes); /* ensure not toasted */
722 if (ARR_NDIM(arr) != 1 ||
723 ARR_DIMS(arr)[0] != numargs ||
724 ARR_ELEMTYPE(arr) != CHAROID)
725 elog(ERROR, "proargmodes is not a 1-D char array");
726 argmodes = (char *) ARR_DATA_PTR(arr);
727 if (proargnames != PointerGetDatum(NULL))
729 arr = DatumGetArrayTypeP(proargnames); /* ensure not toasted */
730 if (ARR_NDIM(arr) != 1 ||
731 ARR_DIMS(arr)[0] != numargs ||
732 ARR_ELEMTYPE(arr) != TEXTOID)
733 elog(ERROR, "proargnames is not a 1-D text array");
734 deconstruct_array(arr, TEXTOID, -1, false, 'i',
735 &argnames, &nargnames);
736 Assert(nargnames == numargs);
739 /* zero elements probably shouldn't happen, but handle it gracefully */
743 /* extract output-argument types and names */
744 outargtypes = (Oid *) palloc(numargs * sizeof(Oid));
745 outargnames = (char **) palloc(numargs * sizeof(char *));
747 for (i = 0; i < numargs; i++)
751 if (argmodes[i] == PROARGMODE_IN)
753 Assert(argmodes[i] == PROARGMODE_OUT ||
754 argmodes[i] == PROARGMODE_INOUT);
755 outargtypes[numoutargs] = argtypes[i];
757 pname = DatumGetCString(DirectFunctionCall1(textout, argnames[i]));
760 if (pname == NULL || pname[0] == '\0')
762 /* Parameter is not named, so gin up a column name */
763 pname = (char *) palloc(32);
764 snprintf(pname, 32, "column%d", numoutargs + 1);
766 outargnames[numoutargs] = pname;
771 * If there is no output argument, or only one, the function does not
777 desc = CreateTemplateTupleDesc(numoutargs, false);
778 for (i = 0; i < numoutargs; i++)
780 TupleDescInitEntry(desc, i+1,
792 * RelationNameGetTupleDesc
794 * Given a (possibly qualified) relation name, build a TupleDesc.
797 RelationNameGetTupleDesc(const char *relname)
804 /* Open relation and copy the tuple description */
805 relname_list = stringToQualifiedNameList(relname, "RelationNameGetTupleDesc");
806 relvar = makeRangeVarFromNameList(relname_list);
807 rel = relation_openrv(relvar, AccessShareLock);
808 tupdesc = CreateTupleDescCopy(RelationGetDescr(rel));
809 relation_close(rel, AccessShareLock);
817 * Given a type Oid, build a TupleDesc.
819 * If the type is composite, *and* a colaliases List is provided, *and*
820 * the List is of natts length, use the aliases instead of the relation
821 * attnames. (NB: this usage is deprecated since it may result in
822 * creation of unnecessary transient record types.)
824 * If the type is a base type, a single item alias List is required.
827 TypeGetTupleDesc(Oid typeoid, List *colaliases)
829 TypeFuncClass functypclass = get_type_func_class(typeoid);
830 TupleDesc tupdesc = NULL;
833 * Build a suitable tupledesc representing the output rows
835 if (functypclass == TYPEFUNC_COMPOSITE)
837 /* Composite data type, e.g. a table's row type */
838 tupdesc = CreateTupleDescCopy(lookup_rowtype_tupdesc(typeoid, -1));
840 if (colaliases != NIL)
842 int natts = tupdesc->natts;
845 /* does the list length match the number of attributes? */
846 if (list_length(colaliases) != natts)
848 (errcode(ERRCODE_DATATYPE_MISMATCH),
849 errmsg("number of aliases does not match number of columns")));
851 /* OK, use the aliases instead */
852 for (varattno = 0; varattno < natts; varattno++)
854 char *label = strVal(list_nth(colaliases, varattno));
857 namestrcpy(&(tupdesc->attrs[varattno]->attname), label);
860 /* The tuple type is now an anonymous record type */
861 tupdesc->tdtypeid = RECORDOID;
862 tupdesc->tdtypmod = -1;
865 else if (functypclass == TYPEFUNC_SCALAR)
867 /* Base data type, i.e. scalar */
870 /* the alias list is required for base types */
871 if (colaliases == NIL)
873 (errcode(ERRCODE_DATATYPE_MISMATCH),
874 errmsg("no column alias was provided")));
876 /* the alias list length must be 1 */
877 if (list_length(colaliases) != 1)
879 (errcode(ERRCODE_DATATYPE_MISMATCH),
880 errmsg("number of aliases does not match number of columns")));
882 /* OK, get the column alias */
883 attname = strVal(linitial(colaliases));
885 tupdesc = CreateTemplateTupleDesc(1, false);
886 TupleDescInitEntry(tupdesc,
893 else if (functypclass == TYPEFUNC_RECORD)
895 /* XXX can't support this because typmod wasn't passed in ... */
897 (errcode(ERRCODE_DATATYPE_MISMATCH),
898 errmsg("could not determine row description for function returning record")));
902 /* crummy error message, but parser should have caught this */
903 elog(ERROR, "function in FROM has unsupported return type");