1 /*-------------------------------------------------------------------------
4 * The Postgres function manager.
6 * Portions Copyright (c) 1996-2014, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
11 * src/backend/utils/fmgr/fmgr.c
13 *-------------------------------------------------------------------------
18 #include "access/tuptoaster.h"
19 #include "catalog/pg_language.h"
20 #include "catalog/pg_proc.h"
21 #include "executor/functions.h"
22 #include "executor/spi.h"
23 #include "lib/stringinfo.h"
24 #include "miscadmin.h"
25 #include "nodes/nodeFuncs.h"
27 #include "utils/acl.h"
28 #include "utils/builtins.h"
29 #include "utils/fmgrtab.h"
30 #include "utils/guc.h"
31 #include "utils/lsyscache.h"
32 #include "utils/syscache.h"
35 * Hooks for function calls
37 PGDLLIMPORT needs_fmgr_hook_type needs_fmgr_hook = NULL;
38 PGDLLIMPORT fmgr_hook_type fmgr_hook = NULL;
41 * Declaration for old-style function pointer type. This is now used only
42 * in fmgr_oldstyle() and is no longer exported.
44 * The m68k SVR4 ABI defines that pointers are returned in %a0 instead of
45 * %d0. So if a function pointer is declared to return a pointer, the
46 * compiler may look only into %a0, but if the called function was declared
47 * to return an integer type, it puts its value only into %d0. So the
48 * caller doesn't pick up the correct return value. The solution is to
49 * declare the function pointer to return int, so the compiler picks up the
50 * return value from %d0. (Functions returning pointers put their value
51 * *additionally* into %d0 for compatibility.) The price is that there are
52 * some warnings about int->pointer conversions ... which we can suppress
53 * with suitably ugly casts in fmgr_oldstyle().
55 #if (defined(__mc68000__) || (defined(__m68k__))) && defined(__ELF__)
56 typedef int32 (*func_ptr) ();
58 typedef char *(*func_ptr) ();
62 * For an oldstyle function, fn_extra points to a record like this:
66 func_ptr func; /* Address of the oldstyle function */
67 bool arg_toastable[FUNC_MAX_ARGS]; /* is n'th arg of a toastable
72 * Hashtable for fast lookup of external C functions
76 /* fn_oid is the hash key and so must be first! */
77 Oid fn_oid; /* OID of an external C function */
78 TransactionId fn_xmin; /* for checking up-to-dateness */
79 ItemPointerData fn_tid;
80 PGFunction user_fn; /* the function's address */
81 const Pg_finfo_record *inforec; /* address of its info record */
84 static HTAB *CFuncHash = NULL;
87 static void fmgr_info_cxt_security(Oid functionId, FmgrInfo *finfo, MemoryContext mcxt,
88 bool ignore_security);
89 static void fmgr_info_C_lang(Oid functionId, FmgrInfo *finfo, HeapTuple procedureTuple);
90 static void fmgr_info_other_lang(Oid functionId, FmgrInfo *finfo, HeapTuple procedureTuple);
91 static CFuncHashTabEntry *lookup_C_func(HeapTuple procedureTuple);
92 static void record_C_func(HeapTuple procedureTuple,
93 PGFunction user_fn, const Pg_finfo_record *inforec);
94 static Datum fmgr_oldstyle(PG_FUNCTION_ARGS);
95 static Datum fmgr_security_definer(PG_FUNCTION_ARGS);
99 * Lookup routines for builtin-function table. We can search by either Oid
100 * or name, but search by Oid is much faster.
103 static const FmgrBuiltin *
104 fmgr_isbuiltin(Oid id)
107 int high = fmgr_nbuiltins - 1;
110 * Loop invariant: low is the first index that could contain target entry,
111 * and high is the last index that could contain it.
115 int i = (high + low) / 2;
116 const FmgrBuiltin *ptr = &fmgr_builtins[i];
120 else if (id > ptr->foid)
129 * Lookup a builtin by name. Note there can be more than one entry in
130 * the array with the same name, but they should all point to the same
133 static const FmgrBuiltin *
134 fmgr_lookupByName(const char *name)
138 for (i = 0; i < fmgr_nbuiltins; i++)
140 if (strcmp(name, fmgr_builtins[i].funcName) == 0)
141 return fmgr_builtins + i;
147 * This routine fills a FmgrInfo struct, given the OID
148 * of the function to be called.
150 * The caller's CurrentMemoryContext is used as the fn_mcxt of the info
151 * struct; this means that any subsidiary data attached to the info struct
152 * (either by fmgr_info itself, or later on by a function call handler)
153 * will be allocated in that context. The caller must ensure that this
154 * context is at least as long-lived as the info struct itself. This is
155 * not a problem in typical cases where the info struct is on the stack or
156 * in freshly-palloc'd space. However, if one intends to store an info
157 * struct in a long-lived table, it's better to use fmgr_info_cxt.
160 fmgr_info(Oid functionId, FmgrInfo *finfo)
162 fmgr_info_cxt_security(functionId, finfo, CurrentMemoryContext, false);
166 * Fill a FmgrInfo struct, specifying a memory context in which its
167 * subsidiary data should go.
170 fmgr_info_cxt(Oid functionId, FmgrInfo *finfo, MemoryContext mcxt)
172 fmgr_info_cxt_security(functionId, finfo, mcxt, false);
176 * This one does the actual work. ignore_security is ordinarily false
177 * but is set to true when we need to avoid recursion.
180 fmgr_info_cxt_security(Oid functionId, FmgrInfo *finfo, MemoryContext mcxt,
181 bool ignore_security)
183 const FmgrBuiltin *fbp;
184 HeapTuple procedureTuple;
185 Form_pg_proc procedureStruct;
191 * fn_oid *must* be filled in last. Some code assumes that if fn_oid is
192 * valid, the whole struct is valid. Some FmgrInfo struct's do survive
195 finfo->fn_oid = InvalidOid;
196 finfo->fn_extra = NULL;
197 finfo->fn_mcxt = mcxt;
198 finfo->fn_expr = NULL; /* caller may set this later */
200 if ((fbp = fmgr_isbuiltin(functionId)) != NULL)
203 * Fast path for builtin functions: don't bother consulting pg_proc
205 finfo->fn_nargs = fbp->nargs;
206 finfo->fn_strict = fbp->strict;
207 finfo->fn_retset = fbp->retset;
208 finfo->fn_stats = TRACK_FUNC_ALL; /* ie, never track */
209 finfo->fn_addr = fbp->func;
210 finfo->fn_oid = functionId;
214 /* Otherwise we need the pg_proc entry */
215 procedureTuple = SearchSysCache1(PROCOID, ObjectIdGetDatum(functionId));
216 if (!HeapTupleIsValid(procedureTuple))
217 elog(ERROR, "cache lookup failed for function %u", functionId);
218 procedureStruct = (Form_pg_proc) GETSTRUCT(procedureTuple);
220 finfo->fn_nargs = procedureStruct->pronargs;
221 finfo->fn_strict = procedureStruct->proisstrict;
222 finfo->fn_retset = procedureStruct->proretset;
225 * If it has prosecdef set, non-null proconfig, or if a plugin wants to
226 * hook function entry/exit, use fmgr_security_definer call handler ---
227 * unless we are being called again by fmgr_security_definer or
228 * fmgr_info_other_lang.
230 * When using fmgr_security_definer, function stats tracking is always
231 * disabled at the outer level, and instead we set the flag properly in
232 * fmgr_security_definer's private flinfo and implement the tracking
233 * inside fmgr_security_definer. This loses the ability to charge the
234 * overhead of fmgr_security_definer to the function, but gains the
235 * ability to set the track_functions GUC as a local GUC parameter of an
236 * interesting function and have the right things happen.
238 if (!ignore_security &&
239 (procedureStruct->prosecdef ||
240 !heap_attisnull(procedureTuple, Anum_pg_proc_proconfig) ||
241 FmgrHookIsNeeded(functionId)))
243 finfo->fn_addr = fmgr_security_definer;
244 finfo->fn_stats = TRACK_FUNC_ALL; /* ie, never track */
245 finfo->fn_oid = functionId;
246 ReleaseSysCache(procedureTuple);
250 switch (procedureStruct->prolang)
252 case INTERNALlanguageId:
255 * For an ordinary builtin function, we should never get here
256 * because the isbuiltin() search above will have succeeded.
257 * However, if the user has done a CREATE FUNCTION to create an
258 * alias for a builtin function, we can end up here. In that case
259 * we have to look up the function by name. The name of the
260 * internal function is stored in prosrc (it doesn't have to be
261 * the same as the name of the alias!)
263 prosrcdatum = SysCacheGetAttr(PROCOID, procedureTuple,
264 Anum_pg_proc_prosrc, &isnull);
266 elog(ERROR, "null prosrc");
267 prosrc = TextDatumGetCString(prosrcdatum);
268 fbp = fmgr_lookupByName(prosrc);
271 (errcode(ERRCODE_UNDEFINED_FUNCTION),
272 errmsg("internal function \"%s\" is not in internal lookup table",
275 /* Should we check that nargs, strict, retset match the table? */
276 finfo->fn_addr = fbp->func;
277 /* note this policy is also assumed in fast path above */
278 finfo->fn_stats = TRACK_FUNC_ALL; /* ie, never track */
282 fmgr_info_C_lang(functionId, finfo, procedureTuple);
283 finfo->fn_stats = TRACK_FUNC_PL; /* ie, track if ALL */
287 finfo->fn_addr = fmgr_sql;
288 finfo->fn_stats = TRACK_FUNC_PL; /* ie, track if ALL */
292 fmgr_info_other_lang(functionId, finfo, procedureTuple);
293 finfo->fn_stats = TRACK_FUNC_OFF; /* ie, track if not OFF */
297 finfo->fn_oid = functionId;
298 ReleaseSysCache(procedureTuple);
302 * Special fmgr_info processing for C-language functions. Note that
303 * finfo->fn_oid is not valid yet.
306 fmgr_info_C_lang(Oid functionId, FmgrInfo *finfo, HeapTuple procedureTuple)
308 Form_pg_proc procedureStruct = (Form_pg_proc) GETSTRUCT(procedureTuple);
309 CFuncHashTabEntry *hashentry;
311 const Pg_finfo_record *inforec;
312 Oldstyle_fnextra *fnextra;
317 * See if we have the function address cached already
319 hashentry = lookup_C_func(procedureTuple);
322 user_fn = hashentry->user_fn;
323 inforec = hashentry->inforec;
334 * Get prosrc and probin strings (link symbol and library filename).
335 * While in general these columns might be null, that's not allowed
336 * for C-language functions.
338 prosrcattr = SysCacheGetAttr(PROCOID, procedureTuple,
339 Anum_pg_proc_prosrc, &isnull);
341 elog(ERROR, "null prosrc for C function %u", functionId);
342 prosrcstring = TextDatumGetCString(prosrcattr);
344 probinattr = SysCacheGetAttr(PROCOID, procedureTuple,
345 Anum_pg_proc_probin, &isnull);
347 elog(ERROR, "null probin for C function %u", functionId);
348 probinstring = TextDatumGetCString(probinattr);
350 /* Look up the function itself */
351 user_fn = load_external_function(probinstring, prosrcstring, true,
354 /* Get the function information record (real or default) */
355 inforec = fetch_finfo_record(libraryhandle, prosrcstring);
357 /* Cache the addresses for later calls */
358 record_C_func(procedureTuple, user_fn, inforec);
364 switch (inforec->api_version)
367 /* Old style: need to use a handler */
368 finfo->fn_addr = fmgr_oldstyle;
369 fnextra = (Oldstyle_fnextra *)
370 MemoryContextAllocZero(finfo->fn_mcxt,
371 sizeof(Oldstyle_fnextra));
372 finfo->fn_extra = (void *) fnextra;
373 fnextra->func = (func_ptr) user_fn;
374 for (i = 0; i < procedureStruct->pronargs; i++)
376 fnextra->arg_toastable[i] =
377 TypeIsToastable(procedureStruct->proargtypes.values[i]);
381 /* New style: call directly */
382 finfo->fn_addr = user_fn;
385 /* Shouldn't get here if fetch_finfo_record did its job */
386 elog(ERROR, "unrecognized function API version: %d",
387 inforec->api_version);
393 * Special fmgr_info processing for other-language functions. Note
394 * that finfo->fn_oid is not valid yet.
397 fmgr_info_other_lang(Oid functionId, FmgrInfo *finfo, HeapTuple procedureTuple)
399 Form_pg_proc procedureStruct = (Form_pg_proc) GETSTRUCT(procedureTuple);
400 Oid language = procedureStruct->prolang;
401 HeapTuple languageTuple;
402 Form_pg_language languageStruct;
405 languageTuple = SearchSysCache1(LANGOID, ObjectIdGetDatum(language));
406 if (!HeapTupleIsValid(languageTuple))
407 elog(ERROR, "cache lookup failed for language %u", language);
408 languageStruct = (Form_pg_language) GETSTRUCT(languageTuple);
411 * Look up the language's call handler function, ignoring any attributes
412 * that would normally cause insertion of fmgr_security_definer. We need
413 * to get back a bare pointer to the actual C-language function.
415 fmgr_info_cxt_security(languageStruct->lanplcallfoid, &plfinfo,
416 CurrentMemoryContext, true);
417 finfo->fn_addr = plfinfo.fn_addr;
420 * If lookup of the PL handler function produced nonnull fn_extra,
421 * complain --- it must be an oldstyle function! We no longer support
422 * oldstyle PL handlers.
424 if (plfinfo.fn_extra != NULL)
425 elog(ERROR, "language %u has old-style handler", language);
427 ReleaseSysCache(languageTuple);
431 * Fetch and validate the information record for the given external function.
432 * The function is specified by a handle for the containing library
433 * (obtained from load_external_function) as well as the function name.
435 * If no info function exists for the given name, it is not an error.
436 * Instead we return a default info record for a version-0 function.
437 * We want to raise an error here only if the info function returns
440 * This function is broken out of fmgr_info_C_lang so that fmgr_c_validator
441 * can validate the information record for a function not yet entered into
444 const Pg_finfo_record *
445 fetch_finfo_record(void *filehandle, char *funcname)
448 PGFInfoFunction infofunc;
449 const Pg_finfo_record *inforec;
450 static Pg_finfo_record default_inforec = {0};
452 infofuncname = psprintf("pg_finfo_%s", funcname);
454 /* Try to look up the info function */
455 infofunc = (PGFInfoFunction) lookup_external_function(filehandle,
457 if (infofunc == NULL)
459 /* Not found --- assume version 0 */
461 return &default_inforec;
464 /* Found, so call it */
465 inforec = (*infofunc) ();
467 /* Validate result as best we can */
469 elog(ERROR, "null result from info function \"%s\"", infofuncname);
470 switch (inforec->api_version)
474 /* OK, no additional fields to validate */
478 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
479 errmsg("unrecognized API version %d reported by info function \"%s\"",
480 inforec->api_version, infofuncname)));
489 /*-------------------------------------------------------------------------
490 * Routines for caching lookup information for external C functions.
492 * The routines in dfmgr.c are relatively slow, so we try to avoid running
493 * them more than once per external function per session. We use a hash table
494 * with the function OID as the lookup key.
495 *-------------------------------------------------------------------------
499 * lookup_C_func: try to find a C function in the hash table
501 * If an entry exists and is up to date, return it; else return NULL
503 static CFuncHashTabEntry *
504 lookup_C_func(HeapTuple procedureTuple)
506 Oid fn_oid = HeapTupleGetOid(procedureTuple);
507 CFuncHashTabEntry *entry;
509 if (CFuncHash == NULL)
510 return NULL; /* no table yet */
511 entry = (CFuncHashTabEntry *)
512 hash_search(CFuncHash,
517 return NULL; /* no such entry */
518 if (entry->fn_xmin == HeapTupleHeaderGetRawXmin(procedureTuple->t_data) &&
519 ItemPointerEquals(&entry->fn_tid, &procedureTuple->t_self))
520 return entry; /* OK */
521 return NULL; /* entry is out of date */
525 * record_C_func: enter (or update) info about a C function in the hash table
528 record_C_func(HeapTuple procedureTuple,
529 PGFunction user_fn, const Pg_finfo_record *inforec)
531 Oid fn_oid = HeapTupleGetOid(procedureTuple);
532 CFuncHashTabEntry *entry;
535 /* Create the hash table if it doesn't exist yet */
536 if (CFuncHash == NULL)
540 MemSet(&hash_ctl, 0, sizeof(hash_ctl));
541 hash_ctl.keysize = sizeof(Oid);
542 hash_ctl.entrysize = sizeof(CFuncHashTabEntry);
543 CFuncHash = hash_create("CFuncHash",
546 HASH_ELEM | HASH_BLOBS);
549 entry = (CFuncHashTabEntry *)
550 hash_search(CFuncHash,
554 /* OID is already filled in */
555 entry->fn_xmin = HeapTupleHeaderGetRawXmin(procedureTuple->t_data);
556 entry->fn_tid = procedureTuple->t_self;
557 entry->user_fn = user_fn;
558 entry->inforec = inforec;
562 * clear_external_function_hash: remove entries for a library being closed
564 * Presently we just zap the entire hash table, but later it might be worth
565 * the effort to remove only the entries associated with the given handle.
568 clear_external_function_hash(void *filehandle)
571 hash_destroy(CFuncHash);
577 * Copy an FmgrInfo struct
579 * This is inherently somewhat bogus since we can't reliably duplicate
580 * language-dependent subsidiary info. We cheat by zeroing fn_extra,
581 * instead, meaning that subsidiary info will have to be recomputed.
584 fmgr_info_copy(FmgrInfo *dstinfo, FmgrInfo *srcinfo,
585 MemoryContext destcxt)
587 memcpy(dstinfo, srcinfo, sizeof(FmgrInfo));
588 dstinfo->fn_mcxt = destcxt;
589 if (dstinfo->fn_addr == fmgr_oldstyle)
591 /* For oldstyle functions we must copy fn_extra */
592 Oldstyle_fnextra *fnextra;
594 fnextra = (Oldstyle_fnextra *)
595 MemoryContextAlloc(destcxt, sizeof(Oldstyle_fnextra));
596 memcpy(fnextra, srcinfo->fn_extra, sizeof(Oldstyle_fnextra));
597 dstinfo->fn_extra = (void *) fnextra;
600 dstinfo->fn_extra = NULL;
605 * Specialized lookup routine for fmgr_internal_validator: given the alleged
606 * name of an internal function, return the OID of the function.
607 * If the name is not recognized, return InvalidOid.
610 fmgr_internal_function(const char *proname)
612 const FmgrBuiltin *fbp = fmgr_lookupByName(proname);
621 * Handler for old-style "C" language functions
624 fmgr_oldstyle(PG_FUNCTION_ARGS)
626 Oldstyle_fnextra *fnextra;
627 int n_arguments = fcinfo->nargs;
633 if (fcinfo->flinfo == NULL || fcinfo->flinfo->fn_extra == NULL)
634 elog(ERROR, "fmgr_oldstyle received NULL pointer");
635 fnextra = (Oldstyle_fnextra *) fcinfo->flinfo->fn_extra;
638 * Result is NULL if any argument is NULL, but we still call the function
639 * (peculiar, but that's the way it worked before, and after all this is a
640 * backwards-compatibility wrapper). Note, however, that we'll never get
641 * here with NULL arguments if the function is marked strict.
643 * We also need to detoast any TOAST-ed inputs, since it's unlikely that
644 * an old-style function knows about TOASTing.
647 for (i = 0; i < n_arguments; i++)
651 else if (fnextra->arg_toastable[i])
652 fcinfo->arg[i] = PointerGetDatum(PG_DETOAST_DATUM(fcinfo->arg[i]));
654 fcinfo->isnull = isnull;
656 user_fn = fnextra->func;
661 returnValue = (char *) (*user_fn) ();
666 * nullvalue() used to use isNull to check if arg is NULL; perhaps
667 * there are other functions still out there that also rely on
668 * this undocumented hack?
670 returnValue = (char *) (*user_fn) (fcinfo->arg[0],
674 returnValue = (char *) (*user_fn) (fcinfo->arg[0],
678 returnValue = (char *) (*user_fn) (fcinfo->arg[0],
683 returnValue = (char *) (*user_fn) (fcinfo->arg[0],
689 returnValue = (char *) (*user_fn) (fcinfo->arg[0],
696 returnValue = (char *) (*user_fn) (fcinfo->arg[0],
704 returnValue = (char *) (*user_fn) (fcinfo->arg[0],
713 returnValue = (char *) (*user_fn) (fcinfo->arg[0],
723 returnValue = (char *) (*user_fn) (fcinfo->arg[0],
734 returnValue = (char *) (*user_fn) (fcinfo->arg[0],
746 returnValue = (char *) (*user_fn) (fcinfo->arg[0],
759 returnValue = (char *) (*user_fn) (fcinfo->arg[0],
773 returnValue = (char *) (*user_fn) (fcinfo->arg[0],
788 returnValue = (char *) (*user_fn) (fcinfo->arg[0],
804 returnValue = (char *) (*user_fn) (fcinfo->arg[0],
821 returnValue = (char *) (*user_fn) (fcinfo->arg[0],
841 * Increasing FUNC_MAX_ARGS doesn't automatically add cases to the
842 * above code, so mention the actual value in this error not
843 * FUNC_MAX_ARGS. You could add cases to the above if you needed
844 * to support old-style functions with many arguments, but making
845 * 'em be new-style is probably a better idea.
848 (errcode(ERRCODE_TOO_MANY_ARGUMENTS),
849 errmsg("function %u has too many arguments (%d, maximum is %d)",
850 fcinfo->flinfo->fn_oid, n_arguments, 16)));
851 returnValue = NULL; /* keep compiler quiet */
855 return PointerGetDatum(returnValue);
860 * Support for security-definer and proconfig-using functions. We support
861 * both of these features using the same call handler, because they are
862 * often used together and it would be inefficient (as well as notationally
863 * messy) to have two levels of call handler involved.
865 struct fmgr_security_definer_cache
867 FmgrInfo flinfo; /* lookup info for target function */
868 Oid userid; /* userid to set, or InvalidOid */
869 ArrayType *proconfig; /* GUC values to set, or NULL */
870 Datum arg; /* passthrough argument for plugin modules */
874 * Function handler for security-definer/proconfig/plugin-hooked functions.
875 * We extract the OID of the actual function and do a fmgr lookup again.
876 * Then we fetch the pg_proc row and copy the owner ID and proconfig fields.
877 * (All this info is cached for the duration of the current query.)
878 * To execute a call, we temporarily replace the flinfo with the cached
879 * and looked-up one, while keeping the outer fcinfo (which contains all
880 * the actual arguments, etc.) intact. This is not re-entrant, but then
881 * the fcinfo itself can't be used re-entrantly anyway.
884 fmgr_security_definer(PG_FUNCTION_ARGS)
887 struct fmgr_security_definer_cache *volatile fcache;
888 FmgrInfo *save_flinfo;
890 int save_sec_context;
891 volatile int save_nestlevel;
892 PgStat_FunctionCallUsage fcusage;
894 if (!fcinfo->flinfo->fn_extra)
897 Form_pg_proc procedureStruct;
900 MemoryContext oldcxt;
902 fcache = MemoryContextAllocZero(fcinfo->flinfo->fn_mcxt,
905 fmgr_info_cxt_security(fcinfo->flinfo->fn_oid, &fcache->flinfo,
906 fcinfo->flinfo->fn_mcxt, true);
907 fcache->flinfo.fn_expr = fcinfo->flinfo->fn_expr;
909 tuple = SearchSysCache1(PROCOID,
910 ObjectIdGetDatum(fcinfo->flinfo->fn_oid));
911 if (!HeapTupleIsValid(tuple))
912 elog(ERROR, "cache lookup failed for function %u",
913 fcinfo->flinfo->fn_oid);
914 procedureStruct = (Form_pg_proc) GETSTRUCT(tuple);
916 if (procedureStruct->prosecdef)
917 fcache->userid = procedureStruct->proowner;
919 datum = SysCacheGetAttr(PROCOID, tuple, Anum_pg_proc_proconfig,
923 oldcxt = MemoryContextSwitchTo(fcinfo->flinfo->fn_mcxt);
924 fcache->proconfig = DatumGetArrayTypePCopy(datum);
925 MemoryContextSwitchTo(oldcxt);
928 ReleaseSysCache(tuple);
930 fcinfo->flinfo->fn_extra = fcache;
933 fcache = fcinfo->flinfo->fn_extra;
935 /* GetUserIdAndSecContext is cheap enough that no harm in a wasted call */
936 GetUserIdAndSecContext(&save_userid, &save_sec_context);
937 if (fcache->proconfig) /* Need a new GUC nesting level */
938 save_nestlevel = NewGUCNestLevel();
940 save_nestlevel = 0; /* keep compiler quiet */
942 if (OidIsValid(fcache->userid))
943 SetUserIdAndSecContext(fcache->userid,
944 save_sec_context | SECURITY_LOCAL_USERID_CHANGE);
946 if (fcache->proconfig)
948 ProcessGUCArray(fcache->proconfig,
949 (superuser() ? PGC_SUSET : PGC_USERSET),
954 /* function manager hook */
956 (*fmgr_hook) (FHET_START, &fcache->flinfo, &fcache->arg);
959 * We don't need to restore GUC or userid settings on error, because the
960 * ensuing xact or subxact abort will do that. The PG_TRY block is only
961 * needed to clean up the flinfo link.
963 save_flinfo = fcinfo->flinfo;
967 fcinfo->flinfo = &fcache->flinfo;
969 /* See notes in fmgr_info_cxt_security */
970 pgstat_init_function_usage(fcinfo, &fcusage);
972 result = FunctionCallInvoke(fcinfo);
975 * We could be calling either a regular or a set-returning function,
976 * so we have to test to see what finalize flag to use.
978 pgstat_end_function_usage(&fcusage,
979 (fcinfo->resultinfo == NULL ||
980 !IsA(fcinfo->resultinfo, ReturnSetInfo) ||
981 ((ReturnSetInfo *) fcinfo->resultinfo)->isDone != ExprMultipleResult));
985 fcinfo->flinfo = save_flinfo;
987 (*fmgr_hook) (FHET_ABORT, &fcache->flinfo, &fcache->arg);
992 fcinfo->flinfo = save_flinfo;
994 if (fcache->proconfig)
995 AtEOXact_GUC(true, save_nestlevel);
996 if (OidIsValid(fcache->userid))
997 SetUserIdAndSecContext(save_userid, save_sec_context);
999 (*fmgr_hook) (FHET_END, &fcache->flinfo, &fcache->arg);
1005 /*-------------------------------------------------------------------------
1006 * Support routines for callers of fmgr-compatible functions
1007 *-------------------------------------------------------------------------
1011 * These are for invocation of a specifically named function with a
1012 * directly-computed parameter list. Note that neither arguments nor result
1013 * are allowed to be NULL. Also, the function cannot be one that needs to
1014 * look at FmgrInfo, since there won't be any.
1017 DirectFunctionCall1Coll(PGFunction func, Oid collation, Datum arg1)
1019 FunctionCallInfoData fcinfo;
1022 InitFunctionCallInfoData(fcinfo, NULL, 1, collation, NULL, NULL);
1024 fcinfo.arg[0] = arg1;
1025 fcinfo.argnull[0] = false;
1027 result = (*func) (&fcinfo);
1029 /* Check for null result, since caller is clearly not expecting one */
1031 elog(ERROR, "function %p returned NULL", (void *) func);
1037 DirectFunctionCall2Coll(PGFunction func, Oid collation, Datum arg1, Datum arg2)
1039 FunctionCallInfoData fcinfo;
1042 InitFunctionCallInfoData(fcinfo, NULL, 2, collation, NULL, NULL);
1044 fcinfo.arg[0] = arg1;
1045 fcinfo.arg[1] = arg2;
1046 fcinfo.argnull[0] = false;
1047 fcinfo.argnull[1] = false;
1049 result = (*func) (&fcinfo);
1051 /* Check for null result, since caller is clearly not expecting one */
1053 elog(ERROR, "function %p returned NULL", (void *) func);
1059 DirectFunctionCall3Coll(PGFunction func, Oid collation, Datum arg1, Datum arg2,
1062 FunctionCallInfoData fcinfo;
1065 InitFunctionCallInfoData(fcinfo, NULL, 3, collation, NULL, NULL);
1067 fcinfo.arg[0] = arg1;
1068 fcinfo.arg[1] = arg2;
1069 fcinfo.arg[2] = arg3;
1070 fcinfo.argnull[0] = false;
1071 fcinfo.argnull[1] = false;
1072 fcinfo.argnull[2] = false;
1074 result = (*func) (&fcinfo);
1076 /* Check for null result, since caller is clearly not expecting one */
1078 elog(ERROR, "function %p returned NULL", (void *) func);
1084 DirectFunctionCall4Coll(PGFunction func, Oid collation, Datum arg1, Datum arg2,
1085 Datum arg3, Datum arg4)
1087 FunctionCallInfoData fcinfo;
1090 InitFunctionCallInfoData(fcinfo, NULL, 4, collation, NULL, NULL);
1092 fcinfo.arg[0] = arg1;
1093 fcinfo.arg[1] = arg2;
1094 fcinfo.arg[2] = arg3;
1095 fcinfo.arg[3] = arg4;
1096 fcinfo.argnull[0] = false;
1097 fcinfo.argnull[1] = false;
1098 fcinfo.argnull[2] = false;
1099 fcinfo.argnull[3] = false;
1101 result = (*func) (&fcinfo);
1103 /* Check for null result, since caller is clearly not expecting one */
1105 elog(ERROR, "function %p returned NULL", (void *) func);
1111 DirectFunctionCall5Coll(PGFunction func, Oid collation, Datum arg1, Datum arg2,
1112 Datum arg3, Datum arg4, Datum arg5)
1114 FunctionCallInfoData fcinfo;
1117 InitFunctionCallInfoData(fcinfo, NULL, 5, collation, NULL, NULL);
1119 fcinfo.arg[0] = arg1;
1120 fcinfo.arg[1] = arg2;
1121 fcinfo.arg[2] = arg3;
1122 fcinfo.arg[3] = arg4;
1123 fcinfo.arg[4] = arg5;
1124 fcinfo.argnull[0] = false;
1125 fcinfo.argnull[1] = false;
1126 fcinfo.argnull[2] = false;
1127 fcinfo.argnull[3] = false;
1128 fcinfo.argnull[4] = false;
1130 result = (*func) (&fcinfo);
1132 /* Check for null result, since caller is clearly not expecting one */
1134 elog(ERROR, "function %p returned NULL", (void *) func);
1140 DirectFunctionCall6Coll(PGFunction func, Oid collation, Datum arg1, Datum arg2,
1141 Datum arg3, Datum arg4, Datum arg5,
1144 FunctionCallInfoData fcinfo;
1147 InitFunctionCallInfoData(fcinfo, NULL, 6, collation, NULL, NULL);
1149 fcinfo.arg[0] = arg1;
1150 fcinfo.arg[1] = arg2;
1151 fcinfo.arg[2] = arg3;
1152 fcinfo.arg[3] = arg4;
1153 fcinfo.arg[4] = arg5;
1154 fcinfo.arg[5] = arg6;
1155 fcinfo.argnull[0] = false;
1156 fcinfo.argnull[1] = false;
1157 fcinfo.argnull[2] = false;
1158 fcinfo.argnull[3] = false;
1159 fcinfo.argnull[4] = false;
1160 fcinfo.argnull[5] = false;
1162 result = (*func) (&fcinfo);
1164 /* Check for null result, since caller is clearly not expecting one */
1166 elog(ERROR, "function %p returned NULL", (void *) func);
1172 DirectFunctionCall7Coll(PGFunction func, Oid collation, Datum arg1, Datum arg2,
1173 Datum arg3, Datum arg4, Datum arg5,
1174 Datum arg6, Datum arg7)
1176 FunctionCallInfoData fcinfo;
1179 InitFunctionCallInfoData(fcinfo, NULL, 7, collation, NULL, NULL);
1181 fcinfo.arg[0] = arg1;
1182 fcinfo.arg[1] = arg2;
1183 fcinfo.arg[2] = arg3;
1184 fcinfo.arg[3] = arg4;
1185 fcinfo.arg[4] = arg5;
1186 fcinfo.arg[5] = arg6;
1187 fcinfo.arg[6] = arg7;
1188 fcinfo.argnull[0] = false;
1189 fcinfo.argnull[1] = false;
1190 fcinfo.argnull[2] = false;
1191 fcinfo.argnull[3] = false;
1192 fcinfo.argnull[4] = false;
1193 fcinfo.argnull[5] = false;
1194 fcinfo.argnull[6] = false;
1196 result = (*func) (&fcinfo);
1198 /* Check for null result, since caller is clearly not expecting one */
1200 elog(ERROR, "function %p returned NULL", (void *) func);
1206 DirectFunctionCall8Coll(PGFunction func, Oid collation, Datum arg1, Datum arg2,
1207 Datum arg3, Datum arg4, Datum arg5,
1208 Datum arg6, Datum arg7, Datum arg8)
1210 FunctionCallInfoData fcinfo;
1213 InitFunctionCallInfoData(fcinfo, NULL, 8, collation, NULL, NULL);
1215 fcinfo.arg[0] = arg1;
1216 fcinfo.arg[1] = arg2;
1217 fcinfo.arg[2] = arg3;
1218 fcinfo.arg[3] = arg4;
1219 fcinfo.arg[4] = arg5;
1220 fcinfo.arg[5] = arg6;
1221 fcinfo.arg[6] = arg7;
1222 fcinfo.arg[7] = arg8;
1223 fcinfo.argnull[0] = false;
1224 fcinfo.argnull[1] = false;
1225 fcinfo.argnull[2] = false;
1226 fcinfo.argnull[3] = false;
1227 fcinfo.argnull[4] = false;
1228 fcinfo.argnull[5] = false;
1229 fcinfo.argnull[6] = false;
1230 fcinfo.argnull[7] = false;
1232 result = (*func) (&fcinfo);
1234 /* Check for null result, since caller is clearly not expecting one */
1236 elog(ERROR, "function %p returned NULL", (void *) func);
1242 DirectFunctionCall9Coll(PGFunction func, Oid collation, Datum arg1, Datum arg2,
1243 Datum arg3, Datum arg4, Datum arg5,
1244 Datum arg6, Datum arg7, Datum arg8,
1247 FunctionCallInfoData fcinfo;
1250 InitFunctionCallInfoData(fcinfo, NULL, 9, collation, NULL, NULL);
1252 fcinfo.arg[0] = arg1;
1253 fcinfo.arg[1] = arg2;
1254 fcinfo.arg[2] = arg3;
1255 fcinfo.arg[3] = arg4;
1256 fcinfo.arg[4] = arg5;
1257 fcinfo.arg[5] = arg6;
1258 fcinfo.arg[6] = arg7;
1259 fcinfo.arg[7] = arg8;
1260 fcinfo.arg[8] = arg9;
1261 fcinfo.argnull[0] = false;
1262 fcinfo.argnull[1] = false;
1263 fcinfo.argnull[2] = false;
1264 fcinfo.argnull[3] = false;
1265 fcinfo.argnull[4] = false;
1266 fcinfo.argnull[5] = false;
1267 fcinfo.argnull[6] = false;
1268 fcinfo.argnull[7] = false;
1269 fcinfo.argnull[8] = false;
1271 result = (*func) (&fcinfo);
1273 /* Check for null result, since caller is clearly not expecting one */
1275 elog(ERROR, "function %p returned NULL", (void *) func);
1282 * These are for invocation of a previously-looked-up function with a
1283 * directly-computed parameter list. Note that neither arguments nor result
1284 * are allowed to be NULL.
1287 FunctionCall1Coll(FmgrInfo *flinfo, Oid collation, Datum arg1)
1289 FunctionCallInfoData fcinfo;
1292 InitFunctionCallInfoData(fcinfo, flinfo, 1, collation, NULL, NULL);
1294 fcinfo.arg[0] = arg1;
1295 fcinfo.argnull[0] = false;
1297 result = FunctionCallInvoke(&fcinfo);
1299 /* Check for null result, since caller is clearly not expecting one */
1301 elog(ERROR, "function %u returned NULL", fcinfo.flinfo->fn_oid);
1307 FunctionCall2Coll(FmgrInfo *flinfo, Oid collation, Datum arg1, Datum arg2)
1310 * XXX if you change this routine, see also the inlined version in
1311 * utils/sort/tuplesort.c!
1313 FunctionCallInfoData fcinfo;
1316 InitFunctionCallInfoData(fcinfo, flinfo, 2, collation, NULL, NULL);
1318 fcinfo.arg[0] = arg1;
1319 fcinfo.arg[1] = arg2;
1320 fcinfo.argnull[0] = false;
1321 fcinfo.argnull[1] = false;
1323 result = FunctionCallInvoke(&fcinfo);
1325 /* Check for null result, since caller is clearly not expecting one */
1327 elog(ERROR, "function %u returned NULL", fcinfo.flinfo->fn_oid);
1333 FunctionCall3Coll(FmgrInfo *flinfo, Oid collation, Datum arg1, Datum arg2,
1336 FunctionCallInfoData fcinfo;
1339 InitFunctionCallInfoData(fcinfo, flinfo, 3, collation, NULL, NULL);
1341 fcinfo.arg[0] = arg1;
1342 fcinfo.arg[1] = arg2;
1343 fcinfo.arg[2] = arg3;
1344 fcinfo.argnull[0] = false;
1345 fcinfo.argnull[1] = false;
1346 fcinfo.argnull[2] = false;
1348 result = FunctionCallInvoke(&fcinfo);
1350 /* Check for null result, since caller is clearly not expecting one */
1352 elog(ERROR, "function %u returned NULL", fcinfo.flinfo->fn_oid);
1358 FunctionCall4Coll(FmgrInfo *flinfo, Oid collation, Datum arg1, Datum arg2,
1359 Datum arg3, Datum arg4)
1361 FunctionCallInfoData fcinfo;
1364 InitFunctionCallInfoData(fcinfo, flinfo, 4, collation, NULL, NULL);
1366 fcinfo.arg[0] = arg1;
1367 fcinfo.arg[1] = arg2;
1368 fcinfo.arg[2] = arg3;
1369 fcinfo.arg[3] = arg4;
1370 fcinfo.argnull[0] = false;
1371 fcinfo.argnull[1] = false;
1372 fcinfo.argnull[2] = false;
1373 fcinfo.argnull[3] = false;
1375 result = FunctionCallInvoke(&fcinfo);
1377 /* Check for null result, since caller is clearly not expecting one */
1379 elog(ERROR, "function %u returned NULL", fcinfo.flinfo->fn_oid);
1385 FunctionCall5Coll(FmgrInfo *flinfo, Oid collation, Datum arg1, Datum arg2,
1386 Datum arg3, Datum arg4, Datum arg5)
1388 FunctionCallInfoData fcinfo;
1391 InitFunctionCallInfoData(fcinfo, flinfo, 5, collation, NULL, NULL);
1393 fcinfo.arg[0] = arg1;
1394 fcinfo.arg[1] = arg2;
1395 fcinfo.arg[2] = arg3;
1396 fcinfo.arg[3] = arg4;
1397 fcinfo.arg[4] = arg5;
1398 fcinfo.argnull[0] = false;
1399 fcinfo.argnull[1] = false;
1400 fcinfo.argnull[2] = false;
1401 fcinfo.argnull[3] = false;
1402 fcinfo.argnull[4] = false;
1404 result = FunctionCallInvoke(&fcinfo);
1406 /* Check for null result, since caller is clearly not expecting one */
1408 elog(ERROR, "function %u returned NULL", fcinfo.flinfo->fn_oid);
1414 FunctionCall6Coll(FmgrInfo *flinfo, Oid collation, Datum arg1, Datum arg2,
1415 Datum arg3, Datum arg4, Datum arg5,
1418 FunctionCallInfoData fcinfo;
1421 InitFunctionCallInfoData(fcinfo, flinfo, 6, collation, NULL, NULL);
1423 fcinfo.arg[0] = arg1;
1424 fcinfo.arg[1] = arg2;
1425 fcinfo.arg[2] = arg3;
1426 fcinfo.arg[3] = arg4;
1427 fcinfo.arg[4] = arg5;
1428 fcinfo.arg[5] = arg6;
1429 fcinfo.argnull[0] = false;
1430 fcinfo.argnull[1] = false;
1431 fcinfo.argnull[2] = false;
1432 fcinfo.argnull[3] = false;
1433 fcinfo.argnull[4] = false;
1434 fcinfo.argnull[5] = false;
1436 result = FunctionCallInvoke(&fcinfo);
1438 /* Check for null result, since caller is clearly not expecting one */
1440 elog(ERROR, "function %u returned NULL", fcinfo.flinfo->fn_oid);
1446 FunctionCall7Coll(FmgrInfo *flinfo, Oid collation, Datum arg1, Datum arg2,
1447 Datum arg3, Datum arg4, Datum arg5,
1448 Datum arg6, Datum arg7)
1450 FunctionCallInfoData fcinfo;
1453 InitFunctionCallInfoData(fcinfo, flinfo, 7, collation, NULL, NULL);
1455 fcinfo.arg[0] = arg1;
1456 fcinfo.arg[1] = arg2;
1457 fcinfo.arg[2] = arg3;
1458 fcinfo.arg[3] = arg4;
1459 fcinfo.arg[4] = arg5;
1460 fcinfo.arg[5] = arg6;
1461 fcinfo.arg[6] = arg7;
1462 fcinfo.argnull[0] = false;
1463 fcinfo.argnull[1] = false;
1464 fcinfo.argnull[2] = false;
1465 fcinfo.argnull[3] = false;
1466 fcinfo.argnull[4] = false;
1467 fcinfo.argnull[5] = false;
1468 fcinfo.argnull[6] = false;
1470 result = FunctionCallInvoke(&fcinfo);
1472 /* Check for null result, since caller is clearly not expecting one */
1474 elog(ERROR, "function %u returned NULL", fcinfo.flinfo->fn_oid);
1480 FunctionCall8Coll(FmgrInfo *flinfo, Oid collation, Datum arg1, Datum arg2,
1481 Datum arg3, Datum arg4, Datum arg5,
1482 Datum arg6, Datum arg7, Datum arg8)
1484 FunctionCallInfoData fcinfo;
1487 InitFunctionCallInfoData(fcinfo, flinfo, 8, collation, NULL, NULL);
1489 fcinfo.arg[0] = arg1;
1490 fcinfo.arg[1] = arg2;
1491 fcinfo.arg[2] = arg3;
1492 fcinfo.arg[3] = arg4;
1493 fcinfo.arg[4] = arg5;
1494 fcinfo.arg[5] = arg6;
1495 fcinfo.arg[6] = arg7;
1496 fcinfo.arg[7] = arg8;
1497 fcinfo.argnull[0] = false;
1498 fcinfo.argnull[1] = false;
1499 fcinfo.argnull[2] = false;
1500 fcinfo.argnull[3] = false;
1501 fcinfo.argnull[4] = false;
1502 fcinfo.argnull[5] = false;
1503 fcinfo.argnull[6] = false;
1504 fcinfo.argnull[7] = false;
1506 result = FunctionCallInvoke(&fcinfo);
1508 /* Check for null result, since caller is clearly not expecting one */
1510 elog(ERROR, "function %u returned NULL", fcinfo.flinfo->fn_oid);
1516 FunctionCall9Coll(FmgrInfo *flinfo, Oid collation, Datum arg1, Datum arg2,
1517 Datum arg3, Datum arg4, Datum arg5,
1518 Datum arg6, Datum arg7, Datum arg8,
1521 FunctionCallInfoData fcinfo;
1524 InitFunctionCallInfoData(fcinfo, flinfo, 9, collation, NULL, NULL);
1526 fcinfo.arg[0] = arg1;
1527 fcinfo.arg[1] = arg2;
1528 fcinfo.arg[2] = arg3;
1529 fcinfo.arg[3] = arg4;
1530 fcinfo.arg[4] = arg5;
1531 fcinfo.arg[5] = arg6;
1532 fcinfo.arg[6] = arg7;
1533 fcinfo.arg[7] = arg8;
1534 fcinfo.arg[8] = arg9;
1535 fcinfo.argnull[0] = false;
1536 fcinfo.argnull[1] = false;
1537 fcinfo.argnull[2] = false;
1538 fcinfo.argnull[3] = false;
1539 fcinfo.argnull[4] = false;
1540 fcinfo.argnull[5] = false;
1541 fcinfo.argnull[6] = false;
1542 fcinfo.argnull[7] = false;
1543 fcinfo.argnull[8] = false;
1545 result = FunctionCallInvoke(&fcinfo);
1547 /* Check for null result, since caller is clearly not expecting one */
1549 elog(ERROR, "function %u returned NULL", fcinfo.flinfo->fn_oid);
1556 * These are for invocation of a function identified by OID with a
1557 * directly-computed parameter list. Note that neither arguments nor result
1558 * are allowed to be NULL. These are essentially fmgr_info() followed
1559 * by FunctionCallN(). If the same function is to be invoked repeatedly,
1560 * do the fmgr_info() once and then use FunctionCallN().
1563 OidFunctionCall0Coll(Oid functionId, Oid collation)
1566 FunctionCallInfoData fcinfo;
1569 fmgr_info(functionId, &flinfo);
1571 InitFunctionCallInfoData(fcinfo, &flinfo, 0, collation, NULL, NULL);
1573 result = FunctionCallInvoke(&fcinfo);
1575 /* Check for null result, since caller is clearly not expecting one */
1577 elog(ERROR, "function %u returned NULL", flinfo.fn_oid);
1583 OidFunctionCall1Coll(Oid functionId, Oid collation, Datum arg1)
1586 FunctionCallInfoData fcinfo;
1589 fmgr_info(functionId, &flinfo);
1591 InitFunctionCallInfoData(fcinfo, &flinfo, 1, collation, NULL, NULL);
1593 fcinfo.arg[0] = arg1;
1594 fcinfo.argnull[0] = false;
1596 result = FunctionCallInvoke(&fcinfo);
1598 /* Check for null result, since caller is clearly not expecting one */
1600 elog(ERROR, "function %u returned NULL", flinfo.fn_oid);
1606 OidFunctionCall2Coll(Oid functionId, Oid collation, Datum arg1, Datum arg2)
1609 FunctionCallInfoData fcinfo;
1612 fmgr_info(functionId, &flinfo);
1614 InitFunctionCallInfoData(fcinfo, &flinfo, 2, collation, NULL, NULL);
1616 fcinfo.arg[0] = arg1;
1617 fcinfo.arg[1] = arg2;
1618 fcinfo.argnull[0] = false;
1619 fcinfo.argnull[1] = false;
1621 result = FunctionCallInvoke(&fcinfo);
1623 /* Check for null result, since caller is clearly not expecting one */
1625 elog(ERROR, "function %u returned NULL", flinfo.fn_oid);
1631 OidFunctionCall3Coll(Oid functionId, Oid collation, Datum arg1, Datum arg2,
1635 FunctionCallInfoData fcinfo;
1638 fmgr_info(functionId, &flinfo);
1640 InitFunctionCallInfoData(fcinfo, &flinfo, 3, collation, NULL, NULL);
1642 fcinfo.arg[0] = arg1;
1643 fcinfo.arg[1] = arg2;
1644 fcinfo.arg[2] = arg3;
1645 fcinfo.argnull[0] = false;
1646 fcinfo.argnull[1] = false;
1647 fcinfo.argnull[2] = false;
1649 result = FunctionCallInvoke(&fcinfo);
1651 /* Check for null result, since caller is clearly not expecting one */
1653 elog(ERROR, "function %u returned NULL", flinfo.fn_oid);
1659 OidFunctionCall4Coll(Oid functionId, Oid collation, Datum arg1, Datum arg2,
1660 Datum arg3, Datum arg4)
1663 FunctionCallInfoData fcinfo;
1666 fmgr_info(functionId, &flinfo);
1668 InitFunctionCallInfoData(fcinfo, &flinfo, 4, collation, NULL, NULL);
1670 fcinfo.arg[0] = arg1;
1671 fcinfo.arg[1] = arg2;
1672 fcinfo.arg[2] = arg3;
1673 fcinfo.arg[3] = arg4;
1674 fcinfo.argnull[0] = false;
1675 fcinfo.argnull[1] = false;
1676 fcinfo.argnull[2] = false;
1677 fcinfo.argnull[3] = false;
1679 result = FunctionCallInvoke(&fcinfo);
1681 /* Check for null result, since caller is clearly not expecting one */
1683 elog(ERROR, "function %u returned NULL", flinfo.fn_oid);
1689 OidFunctionCall5Coll(Oid functionId, Oid collation, Datum arg1, Datum arg2,
1690 Datum arg3, Datum arg4, Datum arg5)
1693 FunctionCallInfoData fcinfo;
1696 fmgr_info(functionId, &flinfo);
1698 InitFunctionCallInfoData(fcinfo, &flinfo, 5, collation, NULL, NULL);
1700 fcinfo.arg[0] = arg1;
1701 fcinfo.arg[1] = arg2;
1702 fcinfo.arg[2] = arg3;
1703 fcinfo.arg[3] = arg4;
1704 fcinfo.arg[4] = arg5;
1705 fcinfo.argnull[0] = false;
1706 fcinfo.argnull[1] = false;
1707 fcinfo.argnull[2] = false;
1708 fcinfo.argnull[3] = false;
1709 fcinfo.argnull[4] = false;
1711 result = FunctionCallInvoke(&fcinfo);
1713 /* Check for null result, since caller is clearly not expecting one */
1715 elog(ERROR, "function %u returned NULL", flinfo.fn_oid);
1721 OidFunctionCall6Coll(Oid functionId, Oid collation, Datum arg1, Datum arg2,
1722 Datum arg3, Datum arg4, Datum arg5,
1726 FunctionCallInfoData fcinfo;
1729 fmgr_info(functionId, &flinfo);
1731 InitFunctionCallInfoData(fcinfo, &flinfo, 6, collation, NULL, NULL);
1733 fcinfo.arg[0] = arg1;
1734 fcinfo.arg[1] = arg2;
1735 fcinfo.arg[2] = arg3;
1736 fcinfo.arg[3] = arg4;
1737 fcinfo.arg[4] = arg5;
1738 fcinfo.arg[5] = arg6;
1739 fcinfo.argnull[0] = false;
1740 fcinfo.argnull[1] = false;
1741 fcinfo.argnull[2] = false;
1742 fcinfo.argnull[3] = false;
1743 fcinfo.argnull[4] = false;
1744 fcinfo.argnull[5] = false;
1746 result = FunctionCallInvoke(&fcinfo);
1748 /* Check for null result, since caller is clearly not expecting one */
1750 elog(ERROR, "function %u returned NULL", flinfo.fn_oid);
1756 OidFunctionCall7Coll(Oid functionId, Oid collation, Datum arg1, Datum arg2,
1757 Datum arg3, Datum arg4, Datum arg5,
1758 Datum arg6, Datum arg7)
1761 FunctionCallInfoData fcinfo;
1764 fmgr_info(functionId, &flinfo);
1766 InitFunctionCallInfoData(fcinfo, &flinfo, 7, collation, NULL, NULL);
1768 fcinfo.arg[0] = arg1;
1769 fcinfo.arg[1] = arg2;
1770 fcinfo.arg[2] = arg3;
1771 fcinfo.arg[3] = arg4;
1772 fcinfo.arg[4] = arg5;
1773 fcinfo.arg[5] = arg6;
1774 fcinfo.arg[6] = arg7;
1775 fcinfo.argnull[0] = false;
1776 fcinfo.argnull[1] = false;
1777 fcinfo.argnull[2] = false;
1778 fcinfo.argnull[3] = false;
1779 fcinfo.argnull[4] = false;
1780 fcinfo.argnull[5] = false;
1781 fcinfo.argnull[6] = false;
1783 result = FunctionCallInvoke(&fcinfo);
1785 /* Check for null result, since caller is clearly not expecting one */
1787 elog(ERROR, "function %u returned NULL", flinfo.fn_oid);
1793 OidFunctionCall8Coll(Oid functionId, Oid collation, Datum arg1, Datum arg2,
1794 Datum arg3, Datum arg4, Datum arg5,
1795 Datum arg6, Datum arg7, Datum arg8)
1798 FunctionCallInfoData fcinfo;
1801 fmgr_info(functionId, &flinfo);
1803 InitFunctionCallInfoData(fcinfo, &flinfo, 8, collation, NULL, NULL);
1805 fcinfo.arg[0] = arg1;
1806 fcinfo.arg[1] = arg2;
1807 fcinfo.arg[2] = arg3;
1808 fcinfo.arg[3] = arg4;
1809 fcinfo.arg[4] = arg5;
1810 fcinfo.arg[5] = arg6;
1811 fcinfo.arg[6] = arg7;
1812 fcinfo.arg[7] = arg8;
1813 fcinfo.argnull[0] = false;
1814 fcinfo.argnull[1] = false;
1815 fcinfo.argnull[2] = false;
1816 fcinfo.argnull[3] = false;
1817 fcinfo.argnull[4] = false;
1818 fcinfo.argnull[5] = false;
1819 fcinfo.argnull[6] = false;
1820 fcinfo.argnull[7] = false;
1822 result = FunctionCallInvoke(&fcinfo);
1824 /* Check for null result, since caller is clearly not expecting one */
1826 elog(ERROR, "function %u returned NULL", flinfo.fn_oid);
1832 OidFunctionCall9Coll(Oid functionId, Oid collation, Datum arg1, Datum arg2,
1833 Datum arg3, Datum arg4, Datum arg5,
1834 Datum arg6, Datum arg7, Datum arg8,
1838 FunctionCallInfoData fcinfo;
1841 fmgr_info(functionId, &flinfo);
1843 InitFunctionCallInfoData(fcinfo, &flinfo, 9, collation, NULL, NULL);
1845 fcinfo.arg[0] = arg1;
1846 fcinfo.arg[1] = arg2;
1847 fcinfo.arg[2] = arg3;
1848 fcinfo.arg[3] = arg4;
1849 fcinfo.arg[4] = arg5;
1850 fcinfo.arg[5] = arg6;
1851 fcinfo.arg[6] = arg7;
1852 fcinfo.arg[7] = arg8;
1853 fcinfo.arg[8] = arg9;
1854 fcinfo.argnull[0] = false;
1855 fcinfo.argnull[1] = false;
1856 fcinfo.argnull[2] = false;
1857 fcinfo.argnull[3] = false;
1858 fcinfo.argnull[4] = false;
1859 fcinfo.argnull[5] = false;
1860 fcinfo.argnull[6] = false;
1861 fcinfo.argnull[7] = false;
1862 fcinfo.argnull[8] = false;
1864 result = FunctionCallInvoke(&fcinfo);
1866 /* Check for null result, since caller is clearly not expecting one */
1868 elog(ERROR, "function %u returned NULL", flinfo.fn_oid);
1875 * Special cases for convenient invocation of datatype I/O functions.
1879 * Call a previously-looked-up datatype input function.
1881 * "str" may be NULL to indicate we are reading a NULL. In this case
1882 * the caller should assume the result is NULL, but we'll call the input
1883 * function anyway if it's not strict. So this is almost but not quite
1884 * the same as FunctionCall3.
1886 * One important difference from the bare function call is that we will
1887 * push any active SPI context, allowing SPI-using I/O functions to be
1888 * called from other SPI functions without extra notation. This is a hack,
1889 * but the alternative of expecting all SPI functions to do SPI_push/SPI_pop
1890 * around I/O calls seems worse.
1893 InputFunctionCall(FmgrInfo *flinfo, char *str, Oid typioparam, int32 typmod)
1895 FunctionCallInfoData fcinfo;
1899 if (str == NULL && flinfo->fn_strict)
1900 return (Datum) 0; /* just return null result */
1902 pushed = SPI_push_conditional();
1904 InitFunctionCallInfoData(fcinfo, flinfo, 3, InvalidOid, NULL, NULL);
1906 fcinfo.arg[0] = CStringGetDatum(str);
1907 fcinfo.arg[1] = ObjectIdGetDatum(typioparam);
1908 fcinfo.arg[2] = Int32GetDatum(typmod);
1909 fcinfo.argnull[0] = (str == NULL);
1910 fcinfo.argnull[1] = false;
1911 fcinfo.argnull[2] = false;
1913 result = FunctionCallInvoke(&fcinfo);
1915 /* Should get null result if and only if str is NULL */
1919 elog(ERROR, "input function %u returned non-NULL",
1920 fcinfo.flinfo->fn_oid);
1925 elog(ERROR, "input function %u returned NULL",
1926 fcinfo.flinfo->fn_oid);
1929 SPI_pop_conditional(pushed);
1935 * Call a previously-looked-up datatype output function.
1937 * Do not call this on NULL datums.
1939 * This is almost just window dressing for FunctionCall1, but it includes
1940 * SPI context pushing for the same reasons as InputFunctionCall.
1943 OutputFunctionCall(FmgrInfo *flinfo, Datum val)
1948 pushed = SPI_push_conditional();
1950 result = DatumGetCString(FunctionCall1(flinfo, val));
1952 SPI_pop_conditional(pushed);
1958 * Call a previously-looked-up datatype binary-input function.
1960 * "buf" may be NULL to indicate we are reading a NULL. In this case
1961 * the caller should assume the result is NULL, but we'll call the receive
1962 * function anyway if it's not strict. So this is almost but not quite
1963 * the same as FunctionCall3. Also, this includes SPI context pushing for
1964 * the same reasons as InputFunctionCall.
1967 ReceiveFunctionCall(FmgrInfo *flinfo, StringInfo buf,
1968 Oid typioparam, int32 typmod)
1970 FunctionCallInfoData fcinfo;
1974 if (buf == NULL && flinfo->fn_strict)
1975 return (Datum) 0; /* just return null result */
1977 pushed = SPI_push_conditional();
1979 InitFunctionCallInfoData(fcinfo, flinfo, 3, InvalidOid, NULL, NULL);
1981 fcinfo.arg[0] = PointerGetDatum(buf);
1982 fcinfo.arg[1] = ObjectIdGetDatum(typioparam);
1983 fcinfo.arg[2] = Int32GetDatum(typmod);
1984 fcinfo.argnull[0] = (buf == NULL);
1985 fcinfo.argnull[1] = false;
1986 fcinfo.argnull[2] = false;
1988 result = FunctionCallInvoke(&fcinfo);
1990 /* Should get null result if and only if buf is NULL */
1994 elog(ERROR, "receive function %u returned non-NULL",
1995 fcinfo.flinfo->fn_oid);
2000 elog(ERROR, "receive function %u returned NULL",
2001 fcinfo.flinfo->fn_oid);
2004 SPI_pop_conditional(pushed);
2010 * Call a previously-looked-up datatype binary-output function.
2012 * Do not call this on NULL datums.
2014 * This is little more than window dressing for FunctionCall1, but it does
2015 * guarantee a non-toasted result, which strictly speaking the underlying
2016 * function doesn't. Also, this includes SPI context pushing for the same
2017 * reasons as InputFunctionCall.
2020 SendFunctionCall(FmgrInfo *flinfo, Datum val)
2025 pushed = SPI_push_conditional();
2027 result = DatumGetByteaP(FunctionCall1(flinfo, val));
2029 SPI_pop_conditional(pushed);
2035 * As above, for I/O functions identified by OID. These are only to be used
2036 * in seldom-executed code paths. They are not only slow but leak memory.
2039 OidInputFunctionCall(Oid functionId, char *str, Oid typioparam, int32 typmod)
2043 fmgr_info(functionId, &flinfo);
2044 return InputFunctionCall(&flinfo, str, typioparam, typmod);
2048 OidOutputFunctionCall(Oid functionId, Datum val)
2052 fmgr_info(functionId, &flinfo);
2053 return OutputFunctionCall(&flinfo, val);
2057 OidReceiveFunctionCall(Oid functionId, StringInfo buf,
2058 Oid typioparam, int32 typmod)
2062 fmgr_info(functionId, &flinfo);
2063 return ReceiveFunctionCall(&flinfo, buf, typioparam, typmod);
2067 OidSendFunctionCall(Oid functionId, Datum val)
2071 fmgr_info(functionId, &flinfo);
2072 return SendFunctionCall(&flinfo, val);
2077 * !!! OLD INTERFACE !!!
2079 * fmgr() is the only remaining vestige of the old-style caller support
2080 * functions. It's no longer used anywhere in the Postgres distribution,
2081 * but we should leave it around for a release or two to ease the transition
2082 * for user-supplied C functions. OidFunctionCallN() replaces it for new
2085 * DEPRECATED, DO NOT USE IN NEW CODE
2088 fmgr(Oid procedureId,...)
2091 FunctionCallInfoData fcinfo;
2095 fmgr_info(procedureId, &flinfo);
2097 MemSet(&fcinfo, 0, sizeof(fcinfo));
2098 fcinfo.flinfo = &flinfo;
2099 fcinfo.nargs = flinfo.fn_nargs;
2100 n_arguments = fcinfo.nargs;
2102 if (n_arguments > 0)
2107 if (n_arguments > FUNC_MAX_ARGS)
2109 (errcode(ERRCODE_TOO_MANY_ARGUMENTS),
2110 errmsg("function %u has too many arguments (%d, maximum is %d)",
2111 flinfo.fn_oid, n_arguments, FUNC_MAX_ARGS)));
2112 va_start(pvar, procedureId);
2113 for (i = 0; i < n_arguments; i++)
2114 fcinfo.arg[i] = PointerGetDatum(va_arg(pvar, char *));
2118 result = FunctionCallInvoke(&fcinfo);
2120 /* Check for null result, since caller is clearly not expecting one */
2122 elog(ERROR, "function %u returned NULL", flinfo.fn_oid);
2124 return DatumGetPointer(result);
2128 /*-------------------------------------------------------------------------
2129 * Support routines for standard maybe-pass-by-reference datatypes
2131 * int8, float4, and float8 can be passed by value if Datum is wide enough.
2132 * (For backwards-compatibility reasons, we allow pass-by-ref to be chosen
2133 * at compile time even if pass-by-val is possible.) For the float types,
2134 * we need a support routine even if we are passing by value, because many
2135 * machines pass int and float function parameters/results differently;
2136 * so we need to play weird games with unions.
2138 * Note: there is only one switch controlling the pass-by-value option for
2139 * both int8 and float8; this is to avoid making things unduly complicated
2140 * for the timestamp types, which might have either representation.
2141 *-------------------------------------------------------------------------
2144 #ifndef USE_FLOAT8_BYVAL /* controls int8 too */
2147 Int64GetDatum(int64 X)
2149 int64 *retval = (int64 *) palloc(sizeof(int64));
2152 return PointerGetDatum(retval);
2154 #endif /* USE_FLOAT8_BYVAL */
2157 Float4GetDatum(float4 X)
2159 #ifdef USE_FLOAT4_BYVAL
2167 return SET_4_BYTES(myunion.retval);
2169 float4 *retval = (float4 *) palloc(sizeof(float4));
2172 return PointerGetDatum(retval);
2176 #ifdef USE_FLOAT4_BYVAL
2179 DatumGetFloat4(Datum X)
2187 myunion.value = GET_4_BYTES(X);
2188 return myunion.retval;
2190 #endif /* USE_FLOAT4_BYVAL */
2193 Float8GetDatum(float8 X)
2195 #ifdef USE_FLOAT8_BYVAL
2203 return SET_8_BYTES(myunion.retval);
2205 float8 *retval = (float8 *) palloc(sizeof(float8));
2208 return PointerGetDatum(retval);
2212 #ifdef USE_FLOAT8_BYVAL
2215 DatumGetFloat8(Datum X)
2223 myunion.value = GET_8_BYTES(X);
2224 return myunion.retval;
2226 #endif /* USE_FLOAT8_BYVAL */
2229 /*-------------------------------------------------------------------------
2230 * Support routines for toastable datatypes
2231 *-------------------------------------------------------------------------
2235 pg_detoast_datum(struct varlena * datum)
2237 if (VARATT_IS_EXTENDED(datum))
2238 return heap_tuple_untoast_attr(datum);
2244 pg_detoast_datum_copy(struct varlena * datum)
2246 if (VARATT_IS_EXTENDED(datum))
2247 return heap_tuple_untoast_attr(datum);
2250 /* Make a modifiable copy of the varlena object */
2251 Size len = VARSIZE(datum);
2252 struct varlena *result = (struct varlena *) palloc(len);
2254 memcpy(result, datum, len);
2260 pg_detoast_datum_slice(struct varlena * datum, int32 first, int32 count)
2262 /* Only get the specified portion from the toast rel */
2263 return heap_tuple_untoast_attr_slice(datum, first, count);
2267 pg_detoast_datum_packed(struct varlena * datum)
2269 if (VARATT_IS_COMPRESSED(datum) || VARATT_IS_EXTERNAL(datum))
2270 return heap_tuple_untoast_attr(datum);
2275 /*-------------------------------------------------------------------------
2276 * Support routines for extracting info from fn_expr parse tree
2278 * These are needed by polymorphic functions, which accept multiple possible
2279 * input types and need help from the parser to know what they've got.
2280 * Also, some functions might be interested in whether a parameter is constant.
2281 * Functions taking VARIADIC ANY also need to know about the VARIADIC keyword.
2282 *-------------------------------------------------------------------------
2286 * Get the actual type OID of the function return type
2288 * Returns InvalidOid if information is not available
2291 get_fn_expr_rettype(FmgrInfo *flinfo)
2296 * can't return anything useful if we have no FmgrInfo or if its fn_expr
2297 * node has not been initialized
2299 if (!flinfo || !flinfo->fn_expr)
2302 expr = flinfo->fn_expr;
2304 return exprType(expr);
2308 * Get the actual type OID of a specific function argument (counting from 0)
2310 * Returns InvalidOid if information is not available
2313 get_fn_expr_argtype(FmgrInfo *flinfo, int argnum)
2316 * can't return anything useful if we have no FmgrInfo or if its fn_expr
2317 * node has not been initialized
2319 if (!flinfo || !flinfo->fn_expr)
2322 return get_call_expr_argtype(flinfo->fn_expr, argnum);
2326 * Get the actual type OID of a specific function argument (counting from 0),
2327 * but working from the calling expression tree instead of FmgrInfo
2329 * Returns InvalidOid if information is not available
2332 get_call_expr_argtype(Node *expr, int argnum)
2340 if (IsA(expr, FuncExpr))
2341 args = ((FuncExpr *) expr)->args;
2342 else if (IsA(expr, OpExpr))
2343 args = ((OpExpr *) expr)->args;
2344 else if (IsA(expr, DistinctExpr))
2345 args = ((DistinctExpr *) expr)->args;
2346 else if (IsA(expr, ScalarArrayOpExpr))
2347 args = ((ScalarArrayOpExpr *) expr)->args;
2348 else if (IsA(expr, ArrayCoerceExpr))
2349 args = list_make1(((ArrayCoerceExpr *) expr)->arg);
2350 else if (IsA(expr, NullIfExpr))
2351 args = ((NullIfExpr *) expr)->args;
2352 else if (IsA(expr, WindowFunc))
2353 args = ((WindowFunc *) expr)->args;
2357 if (argnum < 0 || argnum >= list_length(args))
2360 argtype = exprType((Node *) list_nth(args, argnum));
2363 * special hack for ScalarArrayOpExpr and ArrayCoerceExpr: what the
2364 * underlying function will actually get passed is the element type of the
2367 if (IsA(expr, ScalarArrayOpExpr) &&
2369 argtype = get_base_element_type(argtype);
2370 else if (IsA(expr, ArrayCoerceExpr) &&
2372 argtype = get_base_element_type(argtype);
2378 * Find out whether a specific function argument is constant for the
2379 * duration of a query
2381 * Returns false if information is not available
2384 get_fn_expr_arg_stable(FmgrInfo *flinfo, int argnum)
2387 * can't return anything useful if we have no FmgrInfo or if its fn_expr
2388 * node has not been initialized
2390 if (!flinfo || !flinfo->fn_expr)
2393 return get_call_expr_arg_stable(flinfo->fn_expr, argnum);
2397 * Find out whether a specific function argument is constant for the
2398 * duration of a query, but working from the calling expression tree
2400 * Returns false if information is not available
2403 get_call_expr_arg_stable(Node *expr, int argnum)
2411 if (IsA(expr, FuncExpr))
2412 args = ((FuncExpr *) expr)->args;
2413 else if (IsA(expr, OpExpr))
2414 args = ((OpExpr *) expr)->args;
2415 else if (IsA(expr, DistinctExpr))
2416 args = ((DistinctExpr *) expr)->args;
2417 else if (IsA(expr, ScalarArrayOpExpr))
2418 args = ((ScalarArrayOpExpr *) expr)->args;
2419 else if (IsA(expr, ArrayCoerceExpr))
2420 args = list_make1(((ArrayCoerceExpr *) expr)->arg);
2421 else if (IsA(expr, NullIfExpr))
2422 args = ((NullIfExpr *) expr)->args;
2423 else if (IsA(expr, WindowFunc))
2424 args = ((WindowFunc *) expr)->args;
2428 if (argnum < 0 || argnum >= list_length(args))
2431 arg = (Node *) list_nth(args, argnum);
2434 * Either a true Const or an external Param will have a value that doesn't
2435 * change during the execution of the query. In future we might want to
2436 * consider other cases too, e.g. now().
2438 if (IsA(arg, Const))
2440 if (IsA(arg, Param) &&
2441 ((Param *) arg)->paramkind == PARAM_EXTERN)
2448 * Get the VARIADIC flag from the function invocation
2450 * Returns false (the default assumption) if information is not available
2452 * Note this is generally only of interest to VARIADIC ANY functions
2455 get_fn_expr_variadic(FmgrInfo *flinfo)
2460 * can't return anything useful if we have no FmgrInfo or if its fn_expr
2461 * node has not been initialized
2463 if (!flinfo || !flinfo->fn_expr)
2466 expr = flinfo->fn_expr;
2468 if (IsA(expr, FuncExpr))
2469 return ((FuncExpr *) expr)->funcvariadic;
2474 /*-------------------------------------------------------------------------
2475 * Support routines for procedural language implementations
2476 *-------------------------------------------------------------------------
2480 * Verify that a validator is actually associated with the language of a
2481 * particular function and that the user has access to both the language and
2482 * the function. All validators should call this before doing anything
2483 * substantial. Doing so ensures a user cannot achieve anything with explicit
2484 * calls to validators that he could not achieve with CREATE FUNCTION or by
2485 * simply calling an existing function.
2487 * When this function returns false, callers should skip all validation work
2488 * and call PG_RETURN_VOID(). This never happens at present; it is reserved
2489 * for future expansion.
2491 * In particular, checking that the validator corresponds to the function's
2492 * language allows untrusted language validators to assume they process only
2493 * superuser-chosen source code. (Untrusted language call handlers, by
2494 * definition, do assume that.) A user lacking the USAGE language privilege
2495 * would be unable to reach the validator through CREATE FUNCTION, so we check
2496 * that to block explicit calls as well. Checking the EXECUTE privilege on
2497 * the function is often superfluous, because most users can clone the
2498 * function to get an executable copy. It is meaningful against users with no
2499 * database TEMP right and no permanent schema CREATE right, thereby unable to
2500 * create any function. Also, if the function tracks persistent state by
2501 * function OID or name, validating the original function might permit more
2502 * mischief than creating and validating a clone thereof.
2505 CheckFunctionValidatorAccess(Oid validatorOid, Oid functionOid)
2509 Form_pg_proc procStruct;
2510 Form_pg_language langStruct;
2511 AclResult aclresult;
2513 /* Get the function's pg_proc entry */
2514 procTup = SearchSysCache1(PROCOID, ObjectIdGetDatum(functionOid));
2515 if (!HeapTupleIsValid(procTup))
2516 elog(ERROR, "cache lookup failed for function %u", functionOid);
2517 procStruct = (Form_pg_proc) GETSTRUCT(procTup);
2520 * Fetch pg_language entry to know if this is the correct validation
2521 * function for that pg_proc entry.
2523 langTup = SearchSysCache1(LANGOID, ObjectIdGetDatum(procStruct->prolang));
2524 if (!HeapTupleIsValid(langTup))
2525 elog(ERROR, "cache lookup failed for language %u", procStruct->prolang);
2526 langStruct = (Form_pg_language) GETSTRUCT(langTup);
2528 if (langStruct->lanvalidator != validatorOid)
2530 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
2531 errmsg("language validation function %u called for language %u instead of %u",
2532 validatorOid, procStruct->prolang,
2533 langStruct->lanvalidator)));
2535 /* first validate that we have permissions to use the language */
2536 aclresult = pg_language_aclcheck(procStruct->prolang, GetUserId(),
2538 if (aclresult != ACLCHECK_OK)
2539 aclcheck_error(aclresult, ACL_KIND_LANGUAGE,
2540 NameStr(langStruct->lanname));
2543 * Check whether we are allowed to execute the function itself. If we can
2544 * execute it, there should be no possible side-effect of
2545 * compiling/validation that execution can't have.
2547 aclresult = pg_proc_aclcheck(functionOid, GetUserId(), ACL_EXECUTE);
2548 if (aclresult != ACLCHECK_OK)
2549 aclcheck_error(aclresult, ACL_KIND_PROC, NameStr(procStruct->proname));
2551 ReleaseSysCache(procTup);
2552 ReleaseSysCache(langTup);