1 /*-------------------------------------------------------------------------
4 * The Postgres function manager.
6 * Portions Copyright (c) 1996-2016, 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)
1309 FunctionCallInfoData fcinfo;
1312 InitFunctionCallInfoData(fcinfo, flinfo, 2, collation, NULL, NULL);
1314 fcinfo.arg[0] = arg1;
1315 fcinfo.arg[1] = arg2;
1316 fcinfo.argnull[0] = false;
1317 fcinfo.argnull[1] = false;
1319 result = FunctionCallInvoke(&fcinfo);
1321 /* Check for null result, since caller is clearly not expecting one */
1323 elog(ERROR, "function %u returned NULL", fcinfo.flinfo->fn_oid);
1329 FunctionCall3Coll(FmgrInfo *flinfo, Oid collation, Datum arg1, Datum arg2,
1332 FunctionCallInfoData fcinfo;
1335 InitFunctionCallInfoData(fcinfo, flinfo, 3, collation, NULL, NULL);
1337 fcinfo.arg[0] = arg1;
1338 fcinfo.arg[1] = arg2;
1339 fcinfo.arg[2] = arg3;
1340 fcinfo.argnull[0] = false;
1341 fcinfo.argnull[1] = false;
1342 fcinfo.argnull[2] = false;
1344 result = FunctionCallInvoke(&fcinfo);
1346 /* Check for null result, since caller is clearly not expecting one */
1348 elog(ERROR, "function %u returned NULL", fcinfo.flinfo->fn_oid);
1354 FunctionCall4Coll(FmgrInfo *flinfo, Oid collation, Datum arg1, Datum arg2,
1355 Datum arg3, Datum arg4)
1357 FunctionCallInfoData fcinfo;
1360 InitFunctionCallInfoData(fcinfo, flinfo, 4, collation, NULL, NULL);
1362 fcinfo.arg[0] = arg1;
1363 fcinfo.arg[1] = arg2;
1364 fcinfo.arg[2] = arg3;
1365 fcinfo.arg[3] = arg4;
1366 fcinfo.argnull[0] = false;
1367 fcinfo.argnull[1] = false;
1368 fcinfo.argnull[2] = false;
1369 fcinfo.argnull[3] = false;
1371 result = FunctionCallInvoke(&fcinfo);
1373 /* Check for null result, since caller is clearly not expecting one */
1375 elog(ERROR, "function %u returned NULL", fcinfo.flinfo->fn_oid);
1381 FunctionCall5Coll(FmgrInfo *flinfo, Oid collation, Datum arg1, Datum arg2,
1382 Datum arg3, Datum arg4, Datum arg5)
1384 FunctionCallInfoData fcinfo;
1387 InitFunctionCallInfoData(fcinfo, flinfo, 5, collation, NULL, NULL);
1389 fcinfo.arg[0] = arg1;
1390 fcinfo.arg[1] = arg2;
1391 fcinfo.arg[2] = arg3;
1392 fcinfo.arg[3] = arg4;
1393 fcinfo.arg[4] = arg5;
1394 fcinfo.argnull[0] = false;
1395 fcinfo.argnull[1] = false;
1396 fcinfo.argnull[2] = false;
1397 fcinfo.argnull[3] = false;
1398 fcinfo.argnull[4] = false;
1400 result = FunctionCallInvoke(&fcinfo);
1402 /* Check for null result, since caller is clearly not expecting one */
1404 elog(ERROR, "function %u returned NULL", fcinfo.flinfo->fn_oid);
1410 FunctionCall6Coll(FmgrInfo *flinfo, Oid collation, Datum arg1, Datum arg2,
1411 Datum arg3, Datum arg4, Datum arg5,
1414 FunctionCallInfoData fcinfo;
1417 InitFunctionCallInfoData(fcinfo, flinfo, 6, collation, NULL, NULL);
1419 fcinfo.arg[0] = arg1;
1420 fcinfo.arg[1] = arg2;
1421 fcinfo.arg[2] = arg3;
1422 fcinfo.arg[3] = arg4;
1423 fcinfo.arg[4] = arg5;
1424 fcinfo.arg[5] = arg6;
1425 fcinfo.argnull[0] = false;
1426 fcinfo.argnull[1] = false;
1427 fcinfo.argnull[2] = false;
1428 fcinfo.argnull[3] = false;
1429 fcinfo.argnull[4] = false;
1430 fcinfo.argnull[5] = false;
1432 result = FunctionCallInvoke(&fcinfo);
1434 /* Check for null result, since caller is clearly not expecting one */
1436 elog(ERROR, "function %u returned NULL", fcinfo.flinfo->fn_oid);
1442 FunctionCall7Coll(FmgrInfo *flinfo, Oid collation, Datum arg1, Datum arg2,
1443 Datum arg3, Datum arg4, Datum arg5,
1444 Datum arg6, Datum arg7)
1446 FunctionCallInfoData fcinfo;
1449 InitFunctionCallInfoData(fcinfo, flinfo, 7, collation, NULL, NULL);
1451 fcinfo.arg[0] = arg1;
1452 fcinfo.arg[1] = arg2;
1453 fcinfo.arg[2] = arg3;
1454 fcinfo.arg[3] = arg4;
1455 fcinfo.arg[4] = arg5;
1456 fcinfo.arg[5] = arg6;
1457 fcinfo.arg[6] = arg7;
1458 fcinfo.argnull[0] = false;
1459 fcinfo.argnull[1] = false;
1460 fcinfo.argnull[2] = false;
1461 fcinfo.argnull[3] = false;
1462 fcinfo.argnull[4] = false;
1463 fcinfo.argnull[5] = false;
1464 fcinfo.argnull[6] = false;
1466 result = FunctionCallInvoke(&fcinfo);
1468 /* Check for null result, since caller is clearly not expecting one */
1470 elog(ERROR, "function %u returned NULL", fcinfo.flinfo->fn_oid);
1476 FunctionCall8Coll(FmgrInfo *flinfo, Oid collation, Datum arg1, Datum arg2,
1477 Datum arg3, Datum arg4, Datum arg5,
1478 Datum arg6, Datum arg7, Datum arg8)
1480 FunctionCallInfoData fcinfo;
1483 InitFunctionCallInfoData(fcinfo, flinfo, 8, collation, NULL, NULL);
1485 fcinfo.arg[0] = arg1;
1486 fcinfo.arg[1] = arg2;
1487 fcinfo.arg[2] = arg3;
1488 fcinfo.arg[3] = arg4;
1489 fcinfo.arg[4] = arg5;
1490 fcinfo.arg[5] = arg6;
1491 fcinfo.arg[6] = arg7;
1492 fcinfo.arg[7] = arg8;
1493 fcinfo.argnull[0] = false;
1494 fcinfo.argnull[1] = false;
1495 fcinfo.argnull[2] = false;
1496 fcinfo.argnull[3] = false;
1497 fcinfo.argnull[4] = false;
1498 fcinfo.argnull[5] = false;
1499 fcinfo.argnull[6] = false;
1500 fcinfo.argnull[7] = false;
1502 result = FunctionCallInvoke(&fcinfo);
1504 /* Check for null result, since caller is clearly not expecting one */
1506 elog(ERROR, "function %u returned NULL", fcinfo.flinfo->fn_oid);
1512 FunctionCall9Coll(FmgrInfo *flinfo, Oid collation, Datum arg1, Datum arg2,
1513 Datum arg3, Datum arg4, Datum arg5,
1514 Datum arg6, Datum arg7, Datum arg8,
1517 FunctionCallInfoData fcinfo;
1520 InitFunctionCallInfoData(fcinfo, flinfo, 9, collation, NULL, NULL);
1522 fcinfo.arg[0] = arg1;
1523 fcinfo.arg[1] = arg2;
1524 fcinfo.arg[2] = arg3;
1525 fcinfo.arg[3] = arg4;
1526 fcinfo.arg[4] = arg5;
1527 fcinfo.arg[5] = arg6;
1528 fcinfo.arg[6] = arg7;
1529 fcinfo.arg[7] = arg8;
1530 fcinfo.arg[8] = arg9;
1531 fcinfo.argnull[0] = false;
1532 fcinfo.argnull[1] = false;
1533 fcinfo.argnull[2] = false;
1534 fcinfo.argnull[3] = false;
1535 fcinfo.argnull[4] = false;
1536 fcinfo.argnull[5] = false;
1537 fcinfo.argnull[6] = false;
1538 fcinfo.argnull[7] = false;
1539 fcinfo.argnull[8] = false;
1541 result = FunctionCallInvoke(&fcinfo);
1543 /* Check for null result, since caller is clearly not expecting one */
1545 elog(ERROR, "function %u returned NULL", fcinfo.flinfo->fn_oid);
1552 * These are for invocation of a function identified by OID with a
1553 * directly-computed parameter list. Note that neither arguments nor result
1554 * are allowed to be NULL. These are essentially fmgr_info() followed
1555 * by FunctionCallN(). If the same function is to be invoked repeatedly,
1556 * do the fmgr_info() once and then use FunctionCallN().
1559 OidFunctionCall0Coll(Oid functionId, Oid collation)
1562 FunctionCallInfoData fcinfo;
1565 fmgr_info(functionId, &flinfo);
1567 InitFunctionCallInfoData(fcinfo, &flinfo, 0, collation, NULL, NULL);
1569 result = FunctionCallInvoke(&fcinfo);
1571 /* Check for null result, since caller is clearly not expecting one */
1573 elog(ERROR, "function %u returned NULL", flinfo.fn_oid);
1579 OidFunctionCall1Coll(Oid functionId, Oid collation, Datum arg1)
1582 FunctionCallInfoData fcinfo;
1585 fmgr_info(functionId, &flinfo);
1587 InitFunctionCallInfoData(fcinfo, &flinfo, 1, collation, NULL, NULL);
1589 fcinfo.arg[0] = arg1;
1590 fcinfo.argnull[0] = false;
1592 result = FunctionCallInvoke(&fcinfo);
1594 /* Check for null result, since caller is clearly not expecting one */
1596 elog(ERROR, "function %u returned NULL", flinfo.fn_oid);
1602 OidFunctionCall2Coll(Oid functionId, Oid collation, Datum arg1, Datum arg2)
1605 FunctionCallInfoData fcinfo;
1608 fmgr_info(functionId, &flinfo);
1610 InitFunctionCallInfoData(fcinfo, &flinfo, 2, collation, NULL, NULL);
1612 fcinfo.arg[0] = arg1;
1613 fcinfo.arg[1] = arg2;
1614 fcinfo.argnull[0] = false;
1615 fcinfo.argnull[1] = false;
1617 result = FunctionCallInvoke(&fcinfo);
1619 /* Check for null result, since caller is clearly not expecting one */
1621 elog(ERROR, "function %u returned NULL", flinfo.fn_oid);
1627 OidFunctionCall3Coll(Oid functionId, Oid collation, Datum arg1, Datum arg2,
1631 FunctionCallInfoData fcinfo;
1634 fmgr_info(functionId, &flinfo);
1636 InitFunctionCallInfoData(fcinfo, &flinfo, 3, collation, NULL, NULL);
1638 fcinfo.arg[0] = arg1;
1639 fcinfo.arg[1] = arg2;
1640 fcinfo.arg[2] = arg3;
1641 fcinfo.argnull[0] = false;
1642 fcinfo.argnull[1] = false;
1643 fcinfo.argnull[2] = false;
1645 result = FunctionCallInvoke(&fcinfo);
1647 /* Check for null result, since caller is clearly not expecting one */
1649 elog(ERROR, "function %u returned NULL", flinfo.fn_oid);
1655 OidFunctionCall4Coll(Oid functionId, Oid collation, Datum arg1, Datum arg2,
1656 Datum arg3, Datum arg4)
1659 FunctionCallInfoData fcinfo;
1662 fmgr_info(functionId, &flinfo);
1664 InitFunctionCallInfoData(fcinfo, &flinfo, 4, collation, NULL, NULL);
1666 fcinfo.arg[0] = arg1;
1667 fcinfo.arg[1] = arg2;
1668 fcinfo.arg[2] = arg3;
1669 fcinfo.arg[3] = arg4;
1670 fcinfo.argnull[0] = false;
1671 fcinfo.argnull[1] = false;
1672 fcinfo.argnull[2] = false;
1673 fcinfo.argnull[3] = false;
1675 result = FunctionCallInvoke(&fcinfo);
1677 /* Check for null result, since caller is clearly not expecting one */
1679 elog(ERROR, "function %u returned NULL", flinfo.fn_oid);
1685 OidFunctionCall5Coll(Oid functionId, Oid collation, Datum arg1, Datum arg2,
1686 Datum arg3, Datum arg4, Datum arg5)
1689 FunctionCallInfoData fcinfo;
1692 fmgr_info(functionId, &flinfo);
1694 InitFunctionCallInfoData(fcinfo, &flinfo, 5, collation, NULL, NULL);
1696 fcinfo.arg[0] = arg1;
1697 fcinfo.arg[1] = arg2;
1698 fcinfo.arg[2] = arg3;
1699 fcinfo.arg[3] = arg4;
1700 fcinfo.arg[4] = arg5;
1701 fcinfo.argnull[0] = false;
1702 fcinfo.argnull[1] = false;
1703 fcinfo.argnull[2] = false;
1704 fcinfo.argnull[3] = false;
1705 fcinfo.argnull[4] = false;
1707 result = FunctionCallInvoke(&fcinfo);
1709 /* Check for null result, since caller is clearly not expecting one */
1711 elog(ERROR, "function %u returned NULL", flinfo.fn_oid);
1717 OidFunctionCall6Coll(Oid functionId, Oid collation, Datum arg1, Datum arg2,
1718 Datum arg3, Datum arg4, Datum arg5,
1722 FunctionCallInfoData fcinfo;
1725 fmgr_info(functionId, &flinfo);
1727 InitFunctionCallInfoData(fcinfo, &flinfo, 6, collation, NULL, NULL);
1729 fcinfo.arg[0] = arg1;
1730 fcinfo.arg[1] = arg2;
1731 fcinfo.arg[2] = arg3;
1732 fcinfo.arg[3] = arg4;
1733 fcinfo.arg[4] = arg5;
1734 fcinfo.arg[5] = arg6;
1735 fcinfo.argnull[0] = false;
1736 fcinfo.argnull[1] = false;
1737 fcinfo.argnull[2] = false;
1738 fcinfo.argnull[3] = false;
1739 fcinfo.argnull[4] = false;
1740 fcinfo.argnull[5] = false;
1742 result = FunctionCallInvoke(&fcinfo);
1744 /* Check for null result, since caller is clearly not expecting one */
1746 elog(ERROR, "function %u returned NULL", flinfo.fn_oid);
1752 OidFunctionCall7Coll(Oid functionId, Oid collation, Datum arg1, Datum arg2,
1753 Datum arg3, Datum arg4, Datum arg5,
1754 Datum arg6, Datum arg7)
1757 FunctionCallInfoData fcinfo;
1760 fmgr_info(functionId, &flinfo);
1762 InitFunctionCallInfoData(fcinfo, &flinfo, 7, collation, NULL, NULL);
1764 fcinfo.arg[0] = arg1;
1765 fcinfo.arg[1] = arg2;
1766 fcinfo.arg[2] = arg3;
1767 fcinfo.arg[3] = arg4;
1768 fcinfo.arg[4] = arg5;
1769 fcinfo.arg[5] = arg6;
1770 fcinfo.arg[6] = arg7;
1771 fcinfo.argnull[0] = false;
1772 fcinfo.argnull[1] = false;
1773 fcinfo.argnull[2] = false;
1774 fcinfo.argnull[3] = false;
1775 fcinfo.argnull[4] = false;
1776 fcinfo.argnull[5] = false;
1777 fcinfo.argnull[6] = false;
1779 result = FunctionCallInvoke(&fcinfo);
1781 /* Check for null result, since caller is clearly not expecting one */
1783 elog(ERROR, "function %u returned NULL", flinfo.fn_oid);
1789 OidFunctionCall8Coll(Oid functionId, Oid collation, Datum arg1, Datum arg2,
1790 Datum arg3, Datum arg4, Datum arg5,
1791 Datum arg6, Datum arg7, Datum arg8)
1794 FunctionCallInfoData fcinfo;
1797 fmgr_info(functionId, &flinfo);
1799 InitFunctionCallInfoData(fcinfo, &flinfo, 8, collation, NULL, NULL);
1801 fcinfo.arg[0] = arg1;
1802 fcinfo.arg[1] = arg2;
1803 fcinfo.arg[2] = arg3;
1804 fcinfo.arg[3] = arg4;
1805 fcinfo.arg[4] = arg5;
1806 fcinfo.arg[5] = arg6;
1807 fcinfo.arg[6] = arg7;
1808 fcinfo.arg[7] = arg8;
1809 fcinfo.argnull[0] = false;
1810 fcinfo.argnull[1] = false;
1811 fcinfo.argnull[2] = false;
1812 fcinfo.argnull[3] = false;
1813 fcinfo.argnull[4] = false;
1814 fcinfo.argnull[5] = false;
1815 fcinfo.argnull[6] = false;
1816 fcinfo.argnull[7] = false;
1818 result = FunctionCallInvoke(&fcinfo);
1820 /* Check for null result, since caller is clearly not expecting one */
1822 elog(ERROR, "function %u returned NULL", flinfo.fn_oid);
1828 OidFunctionCall9Coll(Oid functionId, Oid collation, Datum arg1, Datum arg2,
1829 Datum arg3, Datum arg4, Datum arg5,
1830 Datum arg6, Datum arg7, Datum arg8,
1834 FunctionCallInfoData fcinfo;
1837 fmgr_info(functionId, &flinfo);
1839 InitFunctionCallInfoData(fcinfo, &flinfo, 9, collation, NULL, NULL);
1841 fcinfo.arg[0] = arg1;
1842 fcinfo.arg[1] = arg2;
1843 fcinfo.arg[2] = arg3;
1844 fcinfo.arg[3] = arg4;
1845 fcinfo.arg[4] = arg5;
1846 fcinfo.arg[5] = arg6;
1847 fcinfo.arg[6] = arg7;
1848 fcinfo.arg[7] = arg8;
1849 fcinfo.arg[8] = arg9;
1850 fcinfo.argnull[0] = false;
1851 fcinfo.argnull[1] = false;
1852 fcinfo.argnull[2] = false;
1853 fcinfo.argnull[3] = false;
1854 fcinfo.argnull[4] = false;
1855 fcinfo.argnull[5] = false;
1856 fcinfo.argnull[6] = false;
1857 fcinfo.argnull[7] = false;
1858 fcinfo.argnull[8] = false;
1860 result = FunctionCallInvoke(&fcinfo);
1862 /* Check for null result, since caller is clearly not expecting one */
1864 elog(ERROR, "function %u returned NULL", flinfo.fn_oid);
1871 * Special cases for convenient invocation of datatype I/O functions.
1875 * Call a previously-looked-up datatype input function.
1877 * "str" may be NULL to indicate we are reading a NULL. In this case
1878 * the caller should assume the result is NULL, but we'll call the input
1879 * function anyway if it's not strict. So this is almost but not quite
1880 * the same as FunctionCall3.
1882 * One important difference from the bare function call is that we will
1883 * push any active SPI context, allowing SPI-using I/O functions to be
1884 * called from other SPI functions without extra notation. This is a hack,
1885 * but the alternative of expecting all SPI functions to do SPI_push/SPI_pop
1886 * around I/O calls seems worse.
1889 InputFunctionCall(FmgrInfo *flinfo, char *str, Oid typioparam, int32 typmod)
1891 FunctionCallInfoData fcinfo;
1895 if (str == NULL && flinfo->fn_strict)
1896 return (Datum) 0; /* just return null result */
1898 pushed = SPI_push_conditional();
1900 InitFunctionCallInfoData(fcinfo, flinfo, 3, InvalidOid, NULL, NULL);
1902 fcinfo.arg[0] = CStringGetDatum(str);
1903 fcinfo.arg[1] = ObjectIdGetDatum(typioparam);
1904 fcinfo.arg[2] = Int32GetDatum(typmod);
1905 fcinfo.argnull[0] = (str == NULL);
1906 fcinfo.argnull[1] = false;
1907 fcinfo.argnull[2] = false;
1909 result = FunctionCallInvoke(&fcinfo);
1911 /* Should get null result if and only if str is NULL */
1915 elog(ERROR, "input function %u returned non-NULL",
1916 fcinfo.flinfo->fn_oid);
1921 elog(ERROR, "input function %u returned NULL",
1922 fcinfo.flinfo->fn_oid);
1925 SPI_pop_conditional(pushed);
1931 * Call a previously-looked-up datatype output function.
1933 * Do not call this on NULL datums.
1935 * This is almost just window dressing for FunctionCall1, but it includes
1936 * SPI context pushing for the same reasons as InputFunctionCall.
1939 OutputFunctionCall(FmgrInfo *flinfo, Datum val)
1944 pushed = SPI_push_conditional();
1946 result = DatumGetCString(FunctionCall1(flinfo, val));
1948 SPI_pop_conditional(pushed);
1954 * Call a previously-looked-up datatype binary-input function.
1956 * "buf" may be NULL to indicate we are reading a NULL. In this case
1957 * the caller should assume the result is NULL, but we'll call the receive
1958 * function anyway if it's not strict. So this is almost but not quite
1959 * the same as FunctionCall3. Also, this includes SPI context pushing for
1960 * the same reasons as InputFunctionCall.
1963 ReceiveFunctionCall(FmgrInfo *flinfo, StringInfo buf,
1964 Oid typioparam, int32 typmod)
1966 FunctionCallInfoData fcinfo;
1970 if (buf == NULL && flinfo->fn_strict)
1971 return (Datum) 0; /* just return null result */
1973 pushed = SPI_push_conditional();
1975 InitFunctionCallInfoData(fcinfo, flinfo, 3, InvalidOid, NULL, NULL);
1977 fcinfo.arg[0] = PointerGetDatum(buf);
1978 fcinfo.arg[1] = ObjectIdGetDatum(typioparam);
1979 fcinfo.arg[2] = Int32GetDatum(typmod);
1980 fcinfo.argnull[0] = (buf == NULL);
1981 fcinfo.argnull[1] = false;
1982 fcinfo.argnull[2] = false;
1984 result = FunctionCallInvoke(&fcinfo);
1986 /* Should get null result if and only if buf is NULL */
1990 elog(ERROR, "receive function %u returned non-NULL",
1991 fcinfo.flinfo->fn_oid);
1996 elog(ERROR, "receive function %u returned NULL",
1997 fcinfo.flinfo->fn_oid);
2000 SPI_pop_conditional(pushed);
2006 * Call a previously-looked-up datatype binary-output function.
2008 * Do not call this on NULL datums.
2010 * This is little more than window dressing for FunctionCall1, but it does
2011 * guarantee a non-toasted result, which strictly speaking the underlying
2012 * function doesn't. Also, this includes SPI context pushing for the same
2013 * reasons as InputFunctionCall.
2016 SendFunctionCall(FmgrInfo *flinfo, Datum val)
2021 pushed = SPI_push_conditional();
2023 result = DatumGetByteaP(FunctionCall1(flinfo, val));
2025 SPI_pop_conditional(pushed);
2031 * As above, for I/O functions identified by OID. These are only to be used
2032 * in seldom-executed code paths. They are not only slow but leak memory.
2035 OidInputFunctionCall(Oid functionId, char *str, Oid typioparam, int32 typmod)
2039 fmgr_info(functionId, &flinfo);
2040 return InputFunctionCall(&flinfo, str, typioparam, typmod);
2044 OidOutputFunctionCall(Oid functionId, Datum val)
2048 fmgr_info(functionId, &flinfo);
2049 return OutputFunctionCall(&flinfo, val);
2053 OidReceiveFunctionCall(Oid functionId, StringInfo buf,
2054 Oid typioparam, int32 typmod)
2058 fmgr_info(functionId, &flinfo);
2059 return ReceiveFunctionCall(&flinfo, buf, typioparam, typmod);
2063 OidSendFunctionCall(Oid functionId, Datum val)
2067 fmgr_info(functionId, &flinfo);
2068 return SendFunctionCall(&flinfo, val);
2073 * !!! OLD INTERFACE !!!
2075 * fmgr() is the only remaining vestige of the old-style caller support
2076 * functions. It's no longer used anywhere in the Postgres distribution,
2077 * but we should leave it around for a release or two to ease the transition
2078 * for user-supplied C functions. OidFunctionCallN() replaces it for new
2081 * DEPRECATED, DO NOT USE IN NEW CODE
2084 fmgr(Oid procedureId,...)
2087 FunctionCallInfoData fcinfo;
2091 fmgr_info(procedureId, &flinfo);
2093 MemSet(&fcinfo, 0, sizeof(fcinfo));
2094 fcinfo.flinfo = &flinfo;
2095 fcinfo.nargs = flinfo.fn_nargs;
2096 n_arguments = fcinfo.nargs;
2098 if (n_arguments > 0)
2103 if (n_arguments > FUNC_MAX_ARGS)
2105 (errcode(ERRCODE_TOO_MANY_ARGUMENTS),
2106 errmsg("function %u has too many arguments (%d, maximum is %d)",
2107 flinfo.fn_oid, n_arguments, FUNC_MAX_ARGS)));
2108 va_start(pvar, procedureId);
2109 for (i = 0; i < n_arguments; i++)
2110 fcinfo.arg[i] = PointerGetDatum(va_arg(pvar, char *));
2114 result = FunctionCallInvoke(&fcinfo);
2116 /* Check for null result, since caller is clearly not expecting one */
2118 elog(ERROR, "function %u returned NULL", flinfo.fn_oid);
2120 return DatumGetPointer(result);
2124 /*-------------------------------------------------------------------------
2125 * Support routines for standard maybe-pass-by-reference datatypes
2127 * int8, float4, and float8 can be passed by value if Datum is wide enough.
2128 * (For backwards-compatibility reasons, we allow pass-by-ref to be chosen
2129 * at compile time even if pass-by-val is possible.)
2131 * Note: there is only one switch controlling the pass-by-value option for
2132 * both int8 and float8; this is to avoid making things unduly complicated
2133 * for the timestamp types, which might have either representation.
2134 *-------------------------------------------------------------------------
2137 #ifndef USE_FLOAT8_BYVAL /* controls int8 too */
2140 Int64GetDatum(int64 X)
2142 int64 *retval = (int64 *) palloc(sizeof(int64));
2145 return PointerGetDatum(retval);
2147 #endif /* USE_FLOAT8_BYVAL */
2149 #ifndef USE_FLOAT4_BYVAL
2152 Float4GetDatum(float4 X)
2154 float4 *retval = (float4 *) palloc(sizeof(float4));
2157 return PointerGetDatum(retval);
2161 #ifndef USE_FLOAT8_BYVAL
2164 Float8GetDatum(float8 X)
2166 float8 *retval = (float8 *) palloc(sizeof(float8));
2169 return PointerGetDatum(retval);
2174 /*-------------------------------------------------------------------------
2175 * Support routines for toastable datatypes
2176 *-------------------------------------------------------------------------
2180 pg_detoast_datum(struct varlena * datum)
2182 if (VARATT_IS_EXTENDED(datum))
2183 return heap_tuple_untoast_attr(datum);
2189 pg_detoast_datum_copy(struct varlena * datum)
2191 if (VARATT_IS_EXTENDED(datum))
2192 return heap_tuple_untoast_attr(datum);
2195 /* Make a modifiable copy of the varlena object */
2196 Size len = VARSIZE(datum);
2197 struct varlena *result = (struct varlena *) palloc(len);
2199 memcpy(result, datum, len);
2205 pg_detoast_datum_slice(struct varlena * datum, int32 first, int32 count)
2207 /* Only get the specified portion from the toast rel */
2208 return heap_tuple_untoast_attr_slice(datum, first, count);
2212 pg_detoast_datum_packed(struct varlena * datum)
2214 if (VARATT_IS_COMPRESSED(datum) || VARATT_IS_EXTERNAL(datum))
2215 return heap_tuple_untoast_attr(datum);
2220 /*-------------------------------------------------------------------------
2221 * Support routines for extracting info from fn_expr parse tree
2223 * These are needed by polymorphic functions, which accept multiple possible
2224 * input types and need help from the parser to know what they've got.
2225 * Also, some functions might be interested in whether a parameter is constant.
2226 * Functions taking VARIADIC ANY also need to know about the VARIADIC keyword.
2227 *-------------------------------------------------------------------------
2231 * Get the actual type OID of the function return type
2233 * Returns InvalidOid if information is not available
2236 get_fn_expr_rettype(FmgrInfo *flinfo)
2241 * can't return anything useful if we have no FmgrInfo or if its fn_expr
2242 * node has not been initialized
2244 if (!flinfo || !flinfo->fn_expr)
2247 expr = flinfo->fn_expr;
2249 return exprType(expr);
2253 * Get the actual type OID of a specific function argument (counting from 0)
2255 * Returns InvalidOid if information is not available
2258 get_fn_expr_argtype(FmgrInfo *flinfo, int argnum)
2261 * can't return anything useful if we have no FmgrInfo or if its fn_expr
2262 * node has not been initialized
2264 if (!flinfo || !flinfo->fn_expr)
2267 return get_call_expr_argtype(flinfo->fn_expr, argnum);
2271 * Get the actual type OID of a specific function argument (counting from 0),
2272 * but working from the calling expression tree instead of FmgrInfo
2274 * Returns InvalidOid if information is not available
2277 get_call_expr_argtype(Node *expr, int argnum)
2285 if (IsA(expr, FuncExpr))
2286 args = ((FuncExpr *) expr)->args;
2287 else if (IsA(expr, OpExpr))
2288 args = ((OpExpr *) expr)->args;
2289 else if (IsA(expr, DistinctExpr))
2290 args = ((DistinctExpr *) expr)->args;
2291 else if (IsA(expr, ScalarArrayOpExpr))
2292 args = ((ScalarArrayOpExpr *) expr)->args;
2293 else if (IsA(expr, ArrayCoerceExpr))
2294 args = list_make1(((ArrayCoerceExpr *) expr)->arg);
2295 else if (IsA(expr, NullIfExpr))
2296 args = ((NullIfExpr *) expr)->args;
2297 else if (IsA(expr, WindowFunc))
2298 args = ((WindowFunc *) expr)->args;
2302 if (argnum < 0 || argnum >= list_length(args))
2305 argtype = exprType((Node *) list_nth(args, argnum));
2308 * special hack for ScalarArrayOpExpr and ArrayCoerceExpr: what the
2309 * underlying function will actually get passed is the element type of the
2312 if (IsA(expr, ScalarArrayOpExpr) &&
2314 argtype = get_base_element_type(argtype);
2315 else if (IsA(expr, ArrayCoerceExpr) &&
2317 argtype = get_base_element_type(argtype);
2323 * Find out whether a specific function argument is constant for the
2324 * duration of a query
2326 * Returns false if information is not available
2329 get_fn_expr_arg_stable(FmgrInfo *flinfo, int argnum)
2332 * can't return anything useful if we have no FmgrInfo or if its fn_expr
2333 * node has not been initialized
2335 if (!flinfo || !flinfo->fn_expr)
2338 return get_call_expr_arg_stable(flinfo->fn_expr, argnum);
2342 * Find out whether a specific function argument is constant for the
2343 * duration of a query, but working from the calling expression tree
2345 * Returns false if information is not available
2348 get_call_expr_arg_stable(Node *expr, int argnum)
2356 if (IsA(expr, FuncExpr))
2357 args = ((FuncExpr *) expr)->args;
2358 else if (IsA(expr, OpExpr))
2359 args = ((OpExpr *) expr)->args;
2360 else if (IsA(expr, DistinctExpr))
2361 args = ((DistinctExpr *) expr)->args;
2362 else if (IsA(expr, ScalarArrayOpExpr))
2363 args = ((ScalarArrayOpExpr *) expr)->args;
2364 else if (IsA(expr, ArrayCoerceExpr))
2365 args = list_make1(((ArrayCoerceExpr *) expr)->arg);
2366 else if (IsA(expr, NullIfExpr))
2367 args = ((NullIfExpr *) expr)->args;
2368 else if (IsA(expr, WindowFunc))
2369 args = ((WindowFunc *) expr)->args;
2373 if (argnum < 0 || argnum >= list_length(args))
2376 arg = (Node *) list_nth(args, argnum);
2379 * Either a true Const or an external Param will have a value that doesn't
2380 * change during the execution of the query. In future we might want to
2381 * consider other cases too, e.g. now().
2383 if (IsA(arg, Const))
2385 if (IsA(arg, Param) &&
2386 ((Param *) arg)->paramkind == PARAM_EXTERN)
2393 * Get the VARIADIC flag from the function invocation
2395 * Returns false (the default assumption) if information is not available
2397 * Note this is generally only of interest to VARIADIC ANY functions
2400 get_fn_expr_variadic(FmgrInfo *flinfo)
2405 * can't return anything useful if we have no FmgrInfo or if its fn_expr
2406 * node has not been initialized
2408 if (!flinfo || !flinfo->fn_expr)
2411 expr = flinfo->fn_expr;
2413 if (IsA(expr, FuncExpr))
2414 return ((FuncExpr *) expr)->funcvariadic;
2419 /*-------------------------------------------------------------------------
2420 * Support routines for procedural language implementations
2421 *-------------------------------------------------------------------------
2425 * Verify that a validator is actually associated with the language of a
2426 * particular function and that the user has access to both the language and
2427 * the function. All validators should call this before doing anything
2428 * substantial. Doing so ensures a user cannot achieve anything with explicit
2429 * calls to validators that he could not achieve with CREATE FUNCTION or by
2430 * simply calling an existing function.
2432 * When this function returns false, callers should skip all validation work
2433 * and call PG_RETURN_VOID(). This never happens at present; it is reserved
2434 * for future expansion.
2436 * In particular, checking that the validator corresponds to the function's
2437 * language allows untrusted language validators to assume they process only
2438 * superuser-chosen source code. (Untrusted language call handlers, by
2439 * definition, do assume that.) A user lacking the USAGE language privilege
2440 * would be unable to reach the validator through CREATE FUNCTION, so we check
2441 * that to block explicit calls as well. Checking the EXECUTE privilege on
2442 * the function is often superfluous, because most users can clone the
2443 * function to get an executable copy. It is meaningful against users with no
2444 * database TEMP right and no permanent schema CREATE right, thereby unable to
2445 * create any function. Also, if the function tracks persistent state by
2446 * function OID or name, validating the original function might permit more
2447 * mischief than creating and validating a clone thereof.
2450 CheckFunctionValidatorAccess(Oid validatorOid, Oid functionOid)
2454 Form_pg_proc procStruct;
2455 Form_pg_language langStruct;
2456 AclResult aclresult;
2458 /* Get the function's pg_proc entry */
2459 procTup = SearchSysCache1(PROCOID, ObjectIdGetDatum(functionOid));
2460 if (!HeapTupleIsValid(procTup))
2461 elog(ERROR, "cache lookup failed for function %u", functionOid);
2462 procStruct = (Form_pg_proc) GETSTRUCT(procTup);
2465 * Fetch pg_language entry to know if this is the correct validation
2466 * function for that pg_proc entry.
2468 langTup = SearchSysCache1(LANGOID, ObjectIdGetDatum(procStruct->prolang));
2469 if (!HeapTupleIsValid(langTup))
2470 elog(ERROR, "cache lookup failed for language %u", procStruct->prolang);
2471 langStruct = (Form_pg_language) GETSTRUCT(langTup);
2473 if (langStruct->lanvalidator != validatorOid)
2475 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
2476 errmsg("language validation function %u called for language %u instead of %u",
2477 validatorOid, procStruct->prolang,
2478 langStruct->lanvalidator)));
2480 /* first validate that we have permissions to use the language */
2481 aclresult = pg_language_aclcheck(procStruct->prolang, GetUserId(),
2483 if (aclresult != ACLCHECK_OK)
2484 aclcheck_error(aclresult, ACL_KIND_LANGUAGE,
2485 NameStr(langStruct->lanname));
2488 * Check whether we are allowed to execute the function itself. If we can
2489 * execute it, there should be no possible side-effect of
2490 * compiling/validation that execution can't have.
2492 aclresult = pg_proc_aclcheck(functionOid, GetUserId(), ACL_EXECUTE);
2493 if (aclresult != ACLCHECK_OK)
2494 aclcheck_error(aclresult, ACL_KIND_PROC, NameStr(procStruct->proname));
2496 ReleaseSysCache(procTup);
2497 ReleaseSysCache(langTup);