]> granicus.if.org Git - postgresql/blob - src/backend/utils/fmgr/fmgr.c
pgindent run before PG 9.1 beta 1.
[postgresql] / src / backend / utils / fmgr / fmgr.c
1 /*-------------------------------------------------------------------------
2  *
3  * fmgr.c
4  *        The Postgres function manager.
5  *
6  * Portions Copyright (c) 1996-2011, PostgreSQL Global Development Group
7  * Portions Copyright (c) 1994, Regents of the University of California
8  *
9  *
10  * IDENTIFICATION
11  *        src/backend/utils/fmgr/fmgr.c
12  *
13  *-------------------------------------------------------------------------
14  */
15
16 #include "postgres.h"
17
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"
26 #include "pgstat.h"
27 #include "utils/builtins.h"
28 #include "utils/fmgrtab.h"
29 #include "utils/guc.h"
30 #include "utils/lsyscache.h"
31 #include "utils/syscache.h"
32
33 /*
34  * Hooks for function calls
35  */
36 PGDLLIMPORT needs_fmgr_hook_type needs_fmgr_hook = NULL;
37 PGDLLIMPORT fmgr_hook_type fmgr_hook = NULL;
38
39 /*
40  * Declaration for old-style function pointer type.  This is now used only
41  * in fmgr_oldstyle() and is no longer exported.
42  *
43  * The m68k SVR4 ABI defines that pointers are returned in %a0 instead of
44  * %d0. So if a function pointer is declared to return a pointer, the
45  * compiler may look only into %a0, but if the called function was declared
46  * to return an integer type, it puts its value only into %d0. So the
47  * caller doesn't pick up the correct return value. The solution is to
48  * declare the function pointer to return int, so the compiler picks up the
49  * return value from %d0. (Functions returning pointers put their value
50  * *additionally* into %d0 for compatibility.) The price is that there are
51  * some warnings about int->pointer conversions ... which we can suppress
52  * with suitably ugly casts in fmgr_oldstyle().
53  */
54 #if (defined(__mc68000__) || (defined(__m68k__))) && defined(__ELF__)
55 typedef int32 (*func_ptr) ();
56 #else
57 typedef char *(*func_ptr) ();
58 #endif
59
60 /*
61  * For an oldstyle function, fn_extra points to a record like this:
62  */
63 typedef struct
64 {
65         func_ptr        func;                   /* Address of the oldstyle function */
66         bool            arg_toastable[FUNC_MAX_ARGS];   /* is n'th arg of a toastable
67                                                                                                  * datatype? */
68 } Oldstyle_fnextra;
69
70 /*
71  * Hashtable for fast lookup of external C functions
72  */
73 typedef struct
74 {
75         /* fn_oid is the hash key and so must be first! */
76         Oid                     fn_oid;                 /* OID of an external C function */
77         TransactionId fn_xmin;          /* for checking up-to-dateness */
78         ItemPointerData fn_tid;
79         PGFunction      user_fn;                /* the function's address */
80         const Pg_finfo_record *inforec;         /* address of its info record */
81 } CFuncHashTabEntry;
82
83 static HTAB *CFuncHash = NULL;
84
85
86 static void fmgr_info_cxt_security(Oid functionId, FmgrInfo *finfo, MemoryContext mcxt,
87                                            bool ignore_security);
88 static void fmgr_info_C_lang(Oid functionId, FmgrInfo *finfo, HeapTuple procedureTuple);
89 static void fmgr_info_other_lang(Oid functionId, FmgrInfo *finfo, HeapTuple procedureTuple);
90 static CFuncHashTabEntry *lookup_C_func(HeapTuple procedureTuple);
91 static void record_C_func(HeapTuple procedureTuple,
92                           PGFunction user_fn, const Pg_finfo_record *inforec);
93 static Datum fmgr_oldstyle(PG_FUNCTION_ARGS);
94 static Datum fmgr_security_definer(PG_FUNCTION_ARGS);
95
96
97 /*
98  * Lookup routines for builtin-function table.  We can search by either Oid
99  * or name, but search by Oid is much faster.
100  */
101
102 static const FmgrBuiltin *
103 fmgr_isbuiltin(Oid id)
104 {
105         int                     low = 0;
106         int                     high = fmgr_nbuiltins - 1;
107
108         /*
109          * Loop invariant: low is the first index that could contain target entry,
110          * and high is the last index that could contain it.
111          */
112         while (low <= high)
113         {
114                 int                     i = (high + low) / 2;
115                 const FmgrBuiltin *ptr = &fmgr_builtins[i];
116
117                 if (id == ptr->foid)
118                         return ptr;
119                 else if (id > ptr->foid)
120                         low = i + 1;
121                 else
122                         high = i - 1;
123         }
124         return NULL;
125 }
126
127 /*
128  * Lookup a builtin by name.  Note there can be more than one entry in
129  * the array with the same name, but they should all point to the same
130  * routine.
131  */
132 static const FmgrBuiltin *
133 fmgr_lookupByName(const char *name)
134 {
135         int                     i;
136
137         for (i = 0; i < fmgr_nbuiltins; i++)
138         {
139                 if (strcmp(name, fmgr_builtins[i].funcName) == 0)
140                         return fmgr_builtins + i;
141         }
142         return NULL;
143 }
144
145 /*
146  * This routine fills a FmgrInfo struct, given the OID
147  * of the function to be called.
148  *
149  * The caller's CurrentMemoryContext is used as the fn_mcxt of the info
150  * struct; this means that any subsidiary data attached to the info struct
151  * (either by fmgr_info itself, or later on by a function call handler)
152  * will be allocated in that context.  The caller must ensure that this
153  * context is at least as long-lived as the info struct itself.  This is
154  * not a problem in typical cases where the info struct is on the stack or
155  * in freshly-palloc'd space.  However, if one intends to store an info
156  * struct in a long-lived table, it's better to use fmgr_info_cxt.
157  */
158 void
159 fmgr_info(Oid functionId, FmgrInfo *finfo)
160 {
161         fmgr_info_cxt(functionId, finfo, CurrentMemoryContext);
162 }
163
164 /*
165  * Fill a FmgrInfo struct, specifying a memory context in which its
166  * subsidiary data should go.
167  */
168 void
169 fmgr_info_cxt(Oid functionId, FmgrInfo *finfo, MemoryContext mcxt)
170 {
171         fmgr_info_cxt_security(functionId, finfo, mcxt, false);
172 }
173
174 /*
175  * This one does the actual work.  ignore_security is ordinarily false
176  * but is set to true by fmgr_security_definer to avoid recursion.
177  */
178 static void
179 fmgr_info_cxt_security(Oid functionId, FmgrInfo *finfo, MemoryContext mcxt,
180                                            bool ignore_security)
181 {
182         const FmgrBuiltin *fbp;
183         HeapTuple       procedureTuple;
184         Form_pg_proc procedureStruct;
185         Datum           prosrcdatum;
186         bool            isnull;
187         char       *prosrc;
188
189         /*
190          * fn_oid *must* be filled in last.  Some code assumes that if fn_oid is
191          * valid, the whole struct is valid.  Some FmgrInfo struct's do survive
192          * elogs.
193          */
194         finfo->fn_oid = InvalidOid;
195         finfo->fn_collation = InvalidOid;       /* caller may set this later */
196         finfo->fn_extra = NULL;
197         finfo->fn_mcxt = mcxt;
198         finfo->fn_expr = NULL;          /* caller may set this later */
199
200         if ((fbp = fmgr_isbuiltin(functionId)) != NULL)
201         {
202                 /*
203                  * Fast path for builtin functions: don't bother consulting pg_proc
204                  */
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;
211                 return;
212         }
213
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);
219
220         finfo->fn_nargs = procedureStruct->pronargs;
221         finfo->fn_strict = procedureStruct->proisstrict;
222         finfo->fn_retset = procedureStruct->proretset;
223
224         /*
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.
228          *
229          * When using fmgr_security_definer, function stats tracking is always
230          * disabled at the outer level, and instead we set the flag properly in
231          * fmgr_security_definer's private flinfo and implement the tracking
232          * inside fmgr_security_definer.  This loses the ability to charge the
233          * overhead of fmgr_security_definer to the function, but gains the
234          * ability to set the track_functions GUC as a local GUC parameter of an
235          * interesting function and have the right things happen.
236          */
237         if (!ignore_security &&
238                 (procedureStruct->prosecdef ||
239                  !heap_attisnull(procedureTuple, Anum_pg_proc_proconfig) ||
240                  FmgrHookIsNeeded(functionId)))
241         {
242                 finfo->fn_addr = fmgr_security_definer;
243                 finfo->fn_stats = TRACK_FUNC_ALL;               /* ie, never track */
244                 finfo->fn_oid = functionId;
245                 ReleaseSysCache(procedureTuple);
246                 return;
247         }
248
249         switch (procedureStruct->prolang)
250         {
251                 case INTERNALlanguageId:
252
253                         /*
254                          * For an ordinary builtin function, we should never get here
255                          * because the isbuiltin() search above will have succeeded.
256                          * However, if the user has done a CREATE FUNCTION to create an
257                          * alias for a builtin function, we can end up here.  In that case
258                          * we have to look up the function by name.  The name of the
259                          * internal function is stored in prosrc (it doesn't have to be
260                          * the same as the name of the alias!)
261                          */
262                         prosrcdatum = SysCacheGetAttr(PROCOID, procedureTuple,
263                                                                                   Anum_pg_proc_prosrc, &isnull);
264                         if (isnull)
265                                 elog(ERROR, "null prosrc");
266                         prosrc = TextDatumGetCString(prosrcdatum);
267                         fbp = fmgr_lookupByName(prosrc);
268                         if (fbp == NULL)
269                                 ereport(ERROR,
270                                                 (errcode(ERRCODE_UNDEFINED_FUNCTION),
271                                                  errmsg("internal function \"%s\" is not in internal lookup table",
272                                                                 prosrc)));
273                         pfree(prosrc);
274                         /* Should we check that nargs, strict, retset match the table? */
275                         finfo->fn_addr = fbp->func;
276                         /* note this policy is also assumed in fast path above */
277                         finfo->fn_stats = TRACK_FUNC_ALL;       /* ie, never track */
278                         break;
279
280                 case ClanguageId:
281                         fmgr_info_C_lang(functionId, finfo, procedureTuple);
282                         finfo->fn_stats = TRACK_FUNC_PL;        /* ie, track if ALL */
283                         break;
284
285                 case SQLlanguageId:
286                         finfo->fn_addr = fmgr_sql;
287                         finfo->fn_stats = TRACK_FUNC_PL;        /* ie, track if ALL */
288                         break;
289
290                 default:
291                         fmgr_info_other_lang(functionId, finfo, procedureTuple);
292                         finfo->fn_stats = TRACK_FUNC_OFF;       /* ie, track if not OFF */
293                         break;
294         }
295
296         finfo->fn_oid = functionId;
297         ReleaseSysCache(procedureTuple);
298 }
299
300 /*
301  * Special fmgr_info processing for C-language functions.  Note that
302  * finfo->fn_oid is not valid yet.
303  */
304 static void
305 fmgr_info_C_lang(Oid functionId, FmgrInfo *finfo, HeapTuple procedureTuple)
306 {
307         Form_pg_proc procedureStruct = (Form_pg_proc) GETSTRUCT(procedureTuple);
308         CFuncHashTabEntry *hashentry;
309         PGFunction      user_fn;
310         const Pg_finfo_record *inforec;
311         Oldstyle_fnextra *fnextra;
312         bool            isnull;
313         int                     i;
314
315         /*
316          * See if we have the function address cached already
317          */
318         hashentry = lookup_C_func(procedureTuple);
319         if (hashentry)
320         {
321                 user_fn = hashentry->user_fn;
322                 inforec = hashentry->inforec;
323         }
324         else
325         {
326                 Datum           prosrcattr,
327                                         probinattr;
328                 char       *prosrcstring,
329                                    *probinstring;
330                 void       *libraryhandle;
331
332                 /*
333                  * Get prosrc and probin strings (link symbol and library filename).
334                  * While in general these columns might be null, that's not allowed
335                  * for C-language functions.
336                  */
337                 prosrcattr = SysCacheGetAttr(PROCOID, procedureTuple,
338                                                                          Anum_pg_proc_prosrc, &isnull);
339                 if (isnull)
340                         elog(ERROR, "null prosrc for C function %u", functionId);
341                 prosrcstring = TextDatumGetCString(prosrcattr);
342
343                 probinattr = SysCacheGetAttr(PROCOID, procedureTuple,
344                                                                          Anum_pg_proc_probin, &isnull);
345                 if (isnull)
346                         elog(ERROR, "null probin for C function %u", functionId);
347                 probinstring = TextDatumGetCString(probinattr);
348
349                 /* Look up the function itself */
350                 user_fn = load_external_function(probinstring, prosrcstring, true,
351                                                                                  &libraryhandle);
352
353                 /* Get the function information record (real or default) */
354                 inforec = fetch_finfo_record(libraryhandle, prosrcstring);
355
356                 /* Cache the addresses for later calls */
357                 record_C_func(procedureTuple, user_fn, inforec);
358
359                 pfree(prosrcstring);
360                 pfree(probinstring);
361         }
362
363         switch (inforec->api_version)
364         {
365                 case 0:
366                         /* Old style: need to use a handler */
367                         finfo->fn_addr = fmgr_oldstyle;
368                         fnextra = (Oldstyle_fnextra *)
369                                 MemoryContextAllocZero(finfo->fn_mcxt,
370                                                                            sizeof(Oldstyle_fnextra));
371                         finfo->fn_extra = (void *) fnextra;
372                         fnextra->func = (func_ptr) user_fn;
373                         for (i = 0; i < procedureStruct->pronargs; i++)
374                         {
375                                 fnextra->arg_toastable[i] =
376                                         TypeIsToastable(procedureStruct->proargtypes.values[i]);
377                         }
378                         break;
379                 case 1:
380                         /* New style: call directly */
381                         finfo->fn_addr = user_fn;
382                         break;
383                 default:
384                         /* Shouldn't get here if fetch_finfo_record did its job */
385                         elog(ERROR, "unrecognized function API version: %d",
386                                  inforec->api_version);
387                         break;
388         }
389 }
390
391 /*
392  * Special fmgr_info processing for other-language functions.  Note
393  * that finfo->fn_oid is not valid yet.
394  */
395 static void
396 fmgr_info_other_lang(Oid functionId, FmgrInfo *finfo, HeapTuple procedureTuple)
397 {
398         Form_pg_proc procedureStruct = (Form_pg_proc) GETSTRUCT(procedureTuple);
399         Oid                     language = procedureStruct->prolang;
400         HeapTuple       languageTuple;
401         Form_pg_language languageStruct;
402         FmgrInfo        plfinfo;
403
404         languageTuple = SearchSysCache1(LANGOID, ObjectIdGetDatum(language));
405         if (!HeapTupleIsValid(languageTuple))
406                 elog(ERROR, "cache lookup failed for language %u", language);
407         languageStruct = (Form_pg_language) GETSTRUCT(languageTuple);
408
409         fmgr_info(languageStruct->lanplcallfoid, &plfinfo);
410         finfo->fn_addr = plfinfo.fn_addr;
411
412         /*
413          * If lookup of the PL handler function produced nonnull fn_extra,
414          * complain --- it must be an oldstyle function! We no longer support
415          * oldstyle PL handlers.
416          */
417         if (plfinfo.fn_extra != NULL)
418                 elog(ERROR, "language %u has old-style handler", language);
419
420         ReleaseSysCache(languageTuple);
421 }
422
423 /*
424  * Fetch and validate the information record for the given external function.
425  * The function is specified by a handle for the containing library
426  * (obtained from load_external_function) as well as the function name.
427  *
428  * If no info function exists for the given name, it is not an error.
429  * Instead we return a default info record for a version-0 function.
430  * We want to raise an error here only if the info function returns
431  * something bogus.
432  *
433  * This function is broken out of fmgr_info_C_lang so that fmgr_c_validator
434  * can validate the information record for a function not yet entered into
435  * pg_proc.
436  */
437 const Pg_finfo_record *
438 fetch_finfo_record(void *filehandle, char *funcname)
439 {
440         char       *infofuncname;
441         PGFInfoFunction infofunc;
442         const Pg_finfo_record *inforec;
443         static Pg_finfo_record default_inforec = {0};
444
445         /* Compute name of info func */
446         infofuncname = (char *) palloc(strlen(funcname) + 10);
447         strcpy(infofuncname, "pg_finfo_");
448         strcat(infofuncname, funcname);
449
450         /* Try to look up the info function */
451         infofunc = (PGFInfoFunction) lookup_external_function(filehandle,
452                                                                                                                   infofuncname);
453         if (infofunc == NULL)
454         {
455                 /* Not found --- assume version 0 */
456                 pfree(infofuncname);
457                 return &default_inforec;
458         }
459
460         /* Found, so call it */
461         inforec = (*infofunc) ();
462
463         /* Validate result as best we can */
464         if (inforec == NULL)
465                 elog(ERROR, "null result from info function \"%s\"", infofuncname);
466         switch (inforec->api_version)
467         {
468                 case 0:
469                 case 1:
470                         /* OK, no additional fields to validate */
471                         break;
472                 default:
473                         ereport(ERROR,
474                                         (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
475                                          errmsg("unrecognized API version %d reported by info function \"%s\"",
476                                                         inforec->api_version, infofuncname)));
477                         break;
478         }
479
480         pfree(infofuncname);
481         return inforec;
482 }
483
484
485 /*-------------------------------------------------------------------------
486  *              Routines for caching lookup information for external C functions.
487  *
488  * The routines in dfmgr.c are relatively slow, so we try to avoid running
489  * them more than once per external function per session.  We use a hash table
490  * with the function OID as the lookup key.
491  *-------------------------------------------------------------------------
492  */
493
494 /*
495  * lookup_C_func: try to find a C function in the hash table
496  *
497  * If an entry exists and is up to date, return it; else return NULL
498  */
499 static CFuncHashTabEntry *
500 lookup_C_func(HeapTuple procedureTuple)
501 {
502         Oid                     fn_oid = HeapTupleGetOid(procedureTuple);
503         CFuncHashTabEntry *entry;
504
505         if (CFuncHash == NULL)
506                 return NULL;                    /* no table yet */
507         entry = (CFuncHashTabEntry *)
508                 hash_search(CFuncHash,
509                                         &fn_oid,
510                                         HASH_FIND,
511                                         NULL);
512         if (entry == NULL)
513                 return NULL;                    /* no such entry */
514         if (entry->fn_xmin == HeapTupleHeaderGetXmin(procedureTuple->t_data) &&
515                 ItemPointerEquals(&entry->fn_tid, &procedureTuple->t_self))
516                 return entry;                   /* OK */
517         return NULL;                            /* entry is out of date */
518 }
519
520 /*
521  * record_C_func: enter (or update) info about a C function in the hash table
522  */
523 static void
524 record_C_func(HeapTuple procedureTuple,
525                           PGFunction user_fn, const Pg_finfo_record *inforec)
526 {
527         Oid                     fn_oid = HeapTupleGetOid(procedureTuple);
528         CFuncHashTabEntry *entry;
529         bool            found;
530
531         /* Create the hash table if it doesn't exist yet */
532         if (CFuncHash == NULL)
533         {
534                 HASHCTL         hash_ctl;
535
536                 MemSet(&hash_ctl, 0, sizeof(hash_ctl));
537                 hash_ctl.keysize = sizeof(Oid);
538                 hash_ctl.entrysize = sizeof(CFuncHashTabEntry);
539                 hash_ctl.hash = oid_hash;
540                 CFuncHash = hash_create("CFuncHash",
541                                                                 100,
542                                                                 &hash_ctl,
543                                                                 HASH_ELEM | HASH_FUNCTION);
544         }
545
546         entry = (CFuncHashTabEntry *)
547                 hash_search(CFuncHash,
548                                         &fn_oid,
549                                         HASH_ENTER,
550                                         &found);
551         /* OID is already filled in */
552         entry->fn_xmin = HeapTupleHeaderGetXmin(procedureTuple->t_data);
553         entry->fn_tid = procedureTuple->t_self;
554         entry->user_fn = user_fn;
555         entry->inforec = inforec;
556 }
557
558 /*
559  * clear_external_function_hash: remove entries for a library being closed
560  *
561  * Presently we just zap the entire hash table, but later it might be worth
562  * the effort to remove only the entries associated with the given handle.
563  */
564 void
565 clear_external_function_hash(void *filehandle)
566 {
567         if (CFuncHash)
568                 hash_destroy(CFuncHash);
569         CFuncHash = NULL;
570 }
571
572
573 /*
574  * Copy an FmgrInfo struct
575  *
576  * This is inherently somewhat bogus since we can't reliably duplicate
577  * language-dependent subsidiary info.  We cheat by zeroing fn_extra,
578  * instead, meaning that subsidiary info will have to be recomputed.
579  */
580 void
581 fmgr_info_copy(FmgrInfo *dstinfo, FmgrInfo *srcinfo,
582                            MemoryContext destcxt)
583 {
584         memcpy(dstinfo, srcinfo, sizeof(FmgrInfo));
585         dstinfo->fn_mcxt = destcxt;
586         if (dstinfo->fn_addr == fmgr_oldstyle)
587         {
588                 /* For oldstyle functions we must copy fn_extra */
589                 Oldstyle_fnextra *fnextra;
590
591                 fnextra = (Oldstyle_fnextra *)
592                         MemoryContextAlloc(destcxt, sizeof(Oldstyle_fnextra));
593                 memcpy(fnextra, srcinfo->fn_extra, sizeof(Oldstyle_fnextra));
594                 dstinfo->fn_extra = (void *) fnextra;
595         }
596         else
597                 dstinfo->fn_extra = NULL;
598 }
599
600
601 /*
602  * Specialized lookup routine for fmgr_internal_validator: given the alleged
603  * name of an internal function, return the OID of the function.
604  * If the name is not recognized, return InvalidOid.
605  */
606 Oid
607 fmgr_internal_function(const char *proname)
608 {
609         const FmgrBuiltin *fbp = fmgr_lookupByName(proname);
610
611         if (fbp == NULL)
612                 return InvalidOid;
613         return fbp->foid;
614 }
615
616
617 /*
618  * Handler for old-style "C" language functions
619  */
620 static Datum
621 fmgr_oldstyle(PG_FUNCTION_ARGS)
622 {
623         Oldstyle_fnextra *fnextra;
624         int                     n_arguments = fcinfo->nargs;
625         int                     i;
626         bool            isnull;
627         func_ptr        user_fn;
628         char       *returnValue;
629
630         if (fcinfo->flinfo == NULL || fcinfo->flinfo->fn_extra == NULL)
631                 elog(ERROR, "fmgr_oldstyle received NULL pointer");
632         fnextra = (Oldstyle_fnextra *) fcinfo->flinfo->fn_extra;
633
634         /*
635          * Result is NULL if any argument is NULL, but we still call the function
636          * (peculiar, but that's the way it worked before, and after all this is a
637          * backwards-compatibility wrapper).  Note, however, that we'll never get
638          * here with NULL arguments if the function is marked strict.
639          *
640          * We also need to detoast any TOAST-ed inputs, since it's unlikely that
641          * an old-style function knows about TOASTing.
642          */
643         isnull = false;
644         for (i = 0; i < n_arguments; i++)
645         {
646                 if (PG_ARGISNULL(i))
647                         isnull = true;
648                 else if (fnextra->arg_toastable[i])
649                         fcinfo->arg[i] = PointerGetDatum(PG_DETOAST_DATUM(fcinfo->arg[i]));
650         }
651         fcinfo->isnull = isnull;
652
653         user_fn = fnextra->func;
654
655         switch (n_arguments)
656         {
657                 case 0:
658                         returnValue = (char *) (*user_fn) ();
659                         break;
660                 case 1:
661
662                         /*
663                          * nullvalue() used to use isNull to check if arg is NULL; perhaps
664                          * there are other functions still out there that also rely on
665                          * this undocumented hack?
666                          */
667                         returnValue = (char *) (*user_fn) (fcinfo->arg[0],
668                                                                                            &fcinfo->isnull);
669                         break;
670                 case 2:
671                         returnValue = (char *) (*user_fn) (fcinfo->arg[0],
672                                                                                            fcinfo->arg[1]);
673                         break;
674                 case 3:
675                         returnValue = (char *) (*user_fn) (fcinfo->arg[0],
676                                                                                            fcinfo->arg[1],
677                                                                                            fcinfo->arg[2]);
678                         break;
679                 case 4:
680                         returnValue = (char *) (*user_fn) (fcinfo->arg[0],
681                                                                                            fcinfo->arg[1],
682                                                                                            fcinfo->arg[2],
683                                                                                            fcinfo->arg[3]);
684                         break;
685                 case 5:
686                         returnValue = (char *) (*user_fn) (fcinfo->arg[0],
687                                                                                            fcinfo->arg[1],
688                                                                                            fcinfo->arg[2],
689                                                                                            fcinfo->arg[3],
690                                                                                            fcinfo->arg[4]);
691                         break;
692                 case 6:
693                         returnValue = (char *) (*user_fn) (fcinfo->arg[0],
694                                                                                            fcinfo->arg[1],
695                                                                                            fcinfo->arg[2],
696                                                                                            fcinfo->arg[3],
697                                                                                            fcinfo->arg[4],
698                                                                                            fcinfo->arg[5]);
699                         break;
700                 case 7:
701                         returnValue = (char *) (*user_fn) (fcinfo->arg[0],
702                                                                                            fcinfo->arg[1],
703                                                                                            fcinfo->arg[2],
704                                                                                            fcinfo->arg[3],
705                                                                                            fcinfo->arg[4],
706                                                                                            fcinfo->arg[5],
707                                                                                            fcinfo->arg[6]);
708                         break;
709                 case 8:
710                         returnValue = (char *) (*user_fn) (fcinfo->arg[0],
711                                                                                            fcinfo->arg[1],
712                                                                                            fcinfo->arg[2],
713                                                                                            fcinfo->arg[3],
714                                                                                            fcinfo->arg[4],
715                                                                                            fcinfo->arg[5],
716                                                                                            fcinfo->arg[6],
717                                                                                            fcinfo->arg[7]);
718                         break;
719                 case 9:
720                         returnValue = (char *) (*user_fn) (fcinfo->arg[0],
721                                                                                            fcinfo->arg[1],
722                                                                                            fcinfo->arg[2],
723                                                                                            fcinfo->arg[3],
724                                                                                            fcinfo->arg[4],
725                                                                                            fcinfo->arg[5],
726                                                                                            fcinfo->arg[6],
727                                                                                            fcinfo->arg[7],
728                                                                                            fcinfo->arg[8]);
729                         break;
730                 case 10:
731                         returnValue = (char *) (*user_fn) (fcinfo->arg[0],
732                                                                                            fcinfo->arg[1],
733                                                                                            fcinfo->arg[2],
734                                                                                            fcinfo->arg[3],
735                                                                                            fcinfo->arg[4],
736                                                                                            fcinfo->arg[5],
737                                                                                            fcinfo->arg[6],
738                                                                                            fcinfo->arg[7],
739                                                                                            fcinfo->arg[8],
740                                                                                            fcinfo->arg[9]);
741                         break;
742                 case 11:
743                         returnValue = (char *) (*user_fn) (fcinfo->arg[0],
744                                                                                            fcinfo->arg[1],
745                                                                                            fcinfo->arg[2],
746                                                                                            fcinfo->arg[3],
747                                                                                            fcinfo->arg[4],
748                                                                                            fcinfo->arg[5],
749                                                                                            fcinfo->arg[6],
750                                                                                            fcinfo->arg[7],
751                                                                                            fcinfo->arg[8],
752                                                                                            fcinfo->arg[9],
753                                                                                            fcinfo->arg[10]);
754                         break;
755                 case 12:
756                         returnValue = (char *) (*user_fn) (fcinfo->arg[0],
757                                                                                            fcinfo->arg[1],
758                                                                                            fcinfo->arg[2],
759                                                                                            fcinfo->arg[3],
760                                                                                            fcinfo->arg[4],
761                                                                                            fcinfo->arg[5],
762                                                                                            fcinfo->arg[6],
763                                                                                            fcinfo->arg[7],
764                                                                                            fcinfo->arg[8],
765                                                                                            fcinfo->arg[9],
766                                                                                            fcinfo->arg[10],
767                                                                                            fcinfo->arg[11]);
768                         break;
769                 case 13:
770                         returnValue = (char *) (*user_fn) (fcinfo->arg[0],
771                                                                                            fcinfo->arg[1],
772                                                                                            fcinfo->arg[2],
773                                                                                            fcinfo->arg[3],
774                                                                                            fcinfo->arg[4],
775                                                                                            fcinfo->arg[5],
776                                                                                            fcinfo->arg[6],
777                                                                                            fcinfo->arg[7],
778                                                                                            fcinfo->arg[8],
779                                                                                            fcinfo->arg[9],
780                                                                                            fcinfo->arg[10],
781                                                                                            fcinfo->arg[11],
782                                                                                            fcinfo->arg[12]);
783                         break;
784                 case 14:
785                         returnValue = (char *) (*user_fn) (fcinfo->arg[0],
786                                                                                            fcinfo->arg[1],
787                                                                                            fcinfo->arg[2],
788                                                                                            fcinfo->arg[3],
789                                                                                            fcinfo->arg[4],
790                                                                                            fcinfo->arg[5],
791                                                                                            fcinfo->arg[6],
792                                                                                            fcinfo->arg[7],
793                                                                                            fcinfo->arg[8],
794                                                                                            fcinfo->arg[9],
795                                                                                            fcinfo->arg[10],
796                                                                                            fcinfo->arg[11],
797                                                                                            fcinfo->arg[12],
798                                                                                            fcinfo->arg[13]);
799                         break;
800                 case 15:
801                         returnValue = (char *) (*user_fn) (fcinfo->arg[0],
802                                                                                            fcinfo->arg[1],
803                                                                                            fcinfo->arg[2],
804                                                                                            fcinfo->arg[3],
805                                                                                            fcinfo->arg[4],
806                                                                                            fcinfo->arg[5],
807                                                                                            fcinfo->arg[6],
808                                                                                            fcinfo->arg[7],
809                                                                                            fcinfo->arg[8],
810                                                                                            fcinfo->arg[9],
811                                                                                            fcinfo->arg[10],
812                                                                                            fcinfo->arg[11],
813                                                                                            fcinfo->arg[12],
814                                                                                            fcinfo->arg[13],
815                                                                                            fcinfo->arg[14]);
816                         break;
817                 case 16:
818                         returnValue = (char *) (*user_fn) (fcinfo->arg[0],
819                                                                                            fcinfo->arg[1],
820                                                                                            fcinfo->arg[2],
821                                                                                            fcinfo->arg[3],
822                                                                                            fcinfo->arg[4],
823                                                                                            fcinfo->arg[5],
824                                                                                            fcinfo->arg[6],
825                                                                                            fcinfo->arg[7],
826                                                                                            fcinfo->arg[8],
827                                                                                            fcinfo->arg[9],
828                                                                                            fcinfo->arg[10],
829                                                                                            fcinfo->arg[11],
830                                                                                            fcinfo->arg[12],
831                                                                                            fcinfo->arg[13],
832                                                                                            fcinfo->arg[14],
833                                                                                            fcinfo->arg[15]);
834                         break;
835                 default:
836
837                         /*
838                          * Increasing FUNC_MAX_ARGS doesn't automatically add cases to the
839                          * above code, so mention the actual value in this error not
840                          * FUNC_MAX_ARGS.  You could add cases to the above if you needed
841                          * to support old-style functions with many arguments, but making
842                          * 'em be new-style is probably a better idea.
843                          */
844                         ereport(ERROR,
845                                         (errcode(ERRCODE_TOO_MANY_ARGUMENTS),
846                          errmsg("function %u has too many arguments (%d, maximum is %d)",
847                                         fcinfo->flinfo->fn_oid, n_arguments, 16)));
848                         returnValue = NULL; /* keep compiler quiet */
849                         break;
850         }
851
852         return PointerGetDatum(returnValue);
853 }
854
855
856 /*
857  * Support for security-definer and proconfig-using functions.  We support
858  * both of these features using the same call handler, because they are
859  * often used together and it would be inefficient (as well as notationally
860  * messy) to have two levels of call handler involved.
861  */
862 struct fmgr_security_definer_cache
863 {
864         FmgrInfo        flinfo;                 /* lookup info for target function */
865         Oid                     userid;                 /* userid to set, or InvalidOid */
866         ArrayType  *proconfig;          /* GUC values to set, or NULL */
867         Datum           arg;                    /* passthrough argument for plugin modules */
868 };
869
870 /*
871  * Function handler for security-definer/proconfig/plugin-hooked functions.
872  * We extract the OID of the actual function and do a fmgr lookup again.
873  * Then we fetch the pg_proc row and copy the owner ID and proconfig fields.
874  * (All this info is cached for the duration of the current query.)
875  * To execute a call, we temporarily replace the flinfo with the cached
876  * and looked-up one, while keeping the outer fcinfo (which contains all
877  * the actual arguments, etc.) intact.  This is not re-entrant, but then
878  * the fcinfo itself can't be used re-entrantly anyway.
879  */
880 static Datum
881 fmgr_security_definer(PG_FUNCTION_ARGS)
882 {
883         Datum           result;
884         struct fmgr_security_definer_cache *volatile fcache;
885         FmgrInfo   *save_flinfo;
886         Oid                     save_userid;
887         int                     save_sec_context;
888         volatile int save_nestlevel;
889         PgStat_FunctionCallUsage fcusage;
890
891         if (!fcinfo->flinfo->fn_extra)
892         {
893                 HeapTuple       tuple;
894                 Form_pg_proc procedureStruct;
895                 Datum           datum;
896                 bool            isnull;
897                 MemoryContext oldcxt;
898
899                 fcache = MemoryContextAllocZero(fcinfo->flinfo->fn_mcxt,
900                                                                                 sizeof(*fcache));
901
902                 fmgr_info_cxt_security(fcinfo->flinfo->fn_oid, &fcache->flinfo,
903                                                            fcinfo->flinfo->fn_mcxt, true);
904                 fcache->flinfo.fn_collation = fcinfo->flinfo->fn_collation;
905                 fcache->flinfo.fn_expr = fcinfo->flinfo->fn_expr;
906
907                 tuple = SearchSysCache1(PROCOID,
908                                                                 ObjectIdGetDatum(fcinfo->flinfo->fn_oid));
909                 if (!HeapTupleIsValid(tuple))
910                         elog(ERROR, "cache lookup failed for function %u",
911                                  fcinfo->flinfo->fn_oid);
912                 procedureStruct = (Form_pg_proc) GETSTRUCT(tuple);
913
914                 if (procedureStruct->prosecdef)
915                         fcache->userid = procedureStruct->proowner;
916
917                 datum = SysCacheGetAttr(PROCOID, tuple, Anum_pg_proc_proconfig,
918                                                                 &isnull);
919                 if (!isnull)
920                 {
921                         oldcxt = MemoryContextSwitchTo(fcinfo->flinfo->fn_mcxt);
922                         fcache->proconfig = DatumGetArrayTypePCopy(datum);
923                         MemoryContextSwitchTo(oldcxt);
924                 }
925
926                 ReleaseSysCache(tuple);
927
928                 fcinfo->flinfo->fn_extra = fcache;
929         }
930         else
931                 fcache = fcinfo->flinfo->fn_extra;
932
933         /* GetUserIdAndSecContext is cheap enough that no harm in a wasted call */
934         GetUserIdAndSecContext(&save_userid, &save_sec_context);
935         if (fcache->proconfig)          /* Need a new GUC nesting level */
936                 save_nestlevel = NewGUCNestLevel();
937         else
938                 save_nestlevel = 0;             /* keep compiler quiet */
939
940         if (OidIsValid(fcache->userid))
941                 SetUserIdAndSecContext(fcache->userid,
942                                                         save_sec_context | SECURITY_LOCAL_USERID_CHANGE);
943
944         if (fcache->proconfig)
945         {
946                 ProcessGUCArray(fcache->proconfig,
947                                                 (superuser() ? PGC_SUSET : PGC_USERSET),
948                                                 PGC_S_SESSION,
949                                                 GUC_ACTION_SAVE);
950         }
951
952         /* function manager hook */
953         if (fmgr_hook)
954                 (*fmgr_hook) (FHET_START, &fcache->flinfo, &fcache->arg);
955
956         /*
957          * We don't need to restore GUC or userid settings on error, because the
958          * ensuing xact or subxact abort will do that.  The PG_TRY block is only
959          * needed to clean up the flinfo link.
960          */
961         save_flinfo = fcinfo->flinfo;
962
963         PG_TRY();
964         {
965                 fcinfo->flinfo = &fcache->flinfo;
966
967                 /* See notes in fmgr_info_cxt_security */
968                 pgstat_init_function_usage(fcinfo, &fcusage);
969
970                 result = FunctionCallInvoke(fcinfo);
971
972                 /*
973                  * We could be calling either a regular or a set-returning function,
974                  * so we have to test to see what finalize flag to use.
975                  */
976                 pgstat_end_function_usage(&fcusage,
977                                                                   (fcinfo->resultinfo == NULL ||
978                                                                    !IsA(fcinfo->resultinfo, ReturnSetInfo) ||
979                                                                    ((ReturnSetInfo *) fcinfo->resultinfo)->isDone != ExprMultipleResult));
980         }
981         PG_CATCH();
982         {
983                 fcinfo->flinfo = save_flinfo;
984                 if (fmgr_hook)
985                         (*fmgr_hook) (FHET_ABORT, &fcache->flinfo, &fcache->arg);
986                 PG_RE_THROW();
987         }
988         PG_END_TRY();
989
990         fcinfo->flinfo = save_flinfo;
991
992         if (fcache->proconfig)
993                 AtEOXact_GUC(true, save_nestlevel);
994         if (OidIsValid(fcache->userid))
995                 SetUserIdAndSecContext(save_userid, save_sec_context);
996         if (fmgr_hook)
997                 (*fmgr_hook) (FHET_END, &fcache->flinfo, &fcache->arg);
998
999         return result;
1000 }
1001
1002
1003 /*-------------------------------------------------------------------------
1004  *              Support routines for callers of fmgr-compatible functions
1005  *-------------------------------------------------------------------------
1006  */
1007
1008 /*
1009  * These are for invocation of a specifically named function with a
1010  * directly-computed parameter list.  Note that neither arguments nor result
1011  * are allowed to be NULL.      Also, the function cannot be one that needs to
1012  * look at FmgrInfo, since there won't be any.
1013  */
1014 Datum
1015 DirectFunctionCall1(PGFunction func, Datum arg1)
1016 {
1017         FunctionCallInfoData fcinfo;
1018         Datum           result;
1019
1020         InitFunctionCallInfoData(fcinfo, NULL, 1, NULL, NULL);
1021
1022         fcinfo.arg[0] = arg1;
1023         fcinfo.argnull[0] = false;
1024
1025         result = (*func) (&fcinfo);
1026
1027         /* Check for null result, since caller is clearly not expecting one */
1028         if (fcinfo.isnull)
1029                 elog(ERROR, "function %p returned NULL", (void *) func);
1030
1031         return result;
1032 }
1033
1034 Datum
1035 DirectFunctionCall2(PGFunction func, Datum arg1, Datum arg2)
1036 {
1037         FunctionCallInfoData fcinfo;
1038         Datum           result;
1039
1040         InitFunctionCallInfoData(fcinfo, NULL, 2, NULL, NULL);
1041
1042         fcinfo.arg[0] = arg1;
1043         fcinfo.arg[1] = arg2;
1044         fcinfo.argnull[0] = false;
1045         fcinfo.argnull[1] = false;
1046
1047         result = (*func) (&fcinfo);
1048
1049         /* Check for null result, since caller is clearly not expecting one */
1050         if (fcinfo.isnull)
1051                 elog(ERROR, "function %p returned NULL", (void *) func);
1052
1053         return result;
1054 }
1055
1056 Datum
1057 DirectFunctionCall3(PGFunction func, Datum arg1, Datum arg2,
1058                                         Datum arg3)
1059 {
1060         FunctionCallInfoData fcinfo;
1061         Datum           result;
1062
1063         InitFunctionCallInfoData(fcinfo, NULL, 3, NULL, NULL);
1064
1065         fcinfo.arg[0] = arg1;
1066         fcinfo.arg[1] = arg2;
1067         fcinfo.arg[2] = arg3;
1068         fcinfo.argnull[0] = false;
1069         fcinfo.argnull[1] = false;
1070         fcinfo.argnull[2] = false;
1071
1072         result = (*func) (&fcinfo);
1073
1074         /* Check for null result, since caller is clearly not expecting one */
1075         if (fcinfo.isnull)
1076                 elog(ERROR, "function %p returned NULL", (void *) func);
1077
1078         return result;
1079 }
1080
1081 Datum
1082 DirectFunctionCall4(PGFunction func, Datum arg1, Datum arg2,
1083                                         Datum arg3, Datum arg4)
1084 {
1085         FunctionCallInfoData fcinfo;
1086         Datum           result;
1087
1088         InitFunctionCallInfoData(fcinfo, NULL, 4, NULL, NULL);
1089
1090         fcinfo.arg[0] = arg1;
1091         fcinfo.arg[1] = arg2;
1092         fcinfo.arg[2] = arg3;
1093         fcinfo.arg[3] = arg4;
1094         fcinfo.argnull[0] = false;
1095         fcinfo.argnull[1] = false;
1096         fcinfo.argnull[2] = false;
1097         fcinfo.argnull[3] = false;
1098
1099         result = (*func) (&fcinfo);
1100
1101         /* Check for null result, since caller is clearly not expecting one */
1102         if (fcinfo.isnull)
1103                 elog(ERROR, "function %p returned NULL", (void *) func);
1104
1105         return result;
1106 }
1107
1108 Datum
1109 DirectFunctionCall5(PGFunction func, Datum arg1, Datum arg2,
1110                                         Datum arg3, Datum arg4, Datum arg5)
1111 {
1112         FunctionCallInfoData fcinfo;
1113         Datum           result;
1114
1115         InitFunctionCallInfoData(fcinfo, NULL, 5, NULL, NULL);
1116
1117         fcinfo.arg[0] = arg1;
1118         fcinfo.arg[1] = arg2;
1119         fcinfo.arg[2] = arg3;
1120         fcinfo.arg[3] = arg4;
1121         fcinfo.arg[4] = arg5;
1122         fcinfo.argnull[0] = false;
1123         fcinfo.argnull[1] = false;
1124         fcinfo.argnull[2] = false;
1125         fcinfo.argnull[3] = false;
1126         fcinfo.argnull[4] = false;
1127
1128         result = (*func) (&fcinfo);
1129
1130         /* Check for null result, since caller is clearly not expecting one */
1131         if (fcinfo.isnull)
1132                 elog(ERROR, "function %p returned NULL", (void *) func);
1133
1134         return result;
1135 }
1136
1137 Datum
1138 DirectFunctionCall6(PGFunction func, Datum arg1, Datum arg2,
1139                                         Datum arg3, Datum arg4, Datum arg5,
1140                                         Datum arg6)
1141 {
1142         FunctionCallInfoData fcinfo;
1143         Datum           result;
1144
1145         InitFunctionCallInfoData(fcinfo, NULL, 6, NULL, NULL);
1146
1147         fcinfo.arg[0] = arg1;
1148         fcinfo.arg[1] = arg2;
1149         fcinfo.arg[2] = arg3;
1150         fcinfo.arg[3] = arg4;
1151         fcinfo.arg[4] = arg5;
1152         fcinfo.arg[5] = arg6;
1153         fcinfo.argnull[0] = false;
1154         fcinfo.argnull[1] = false;
1155         fcinfo.argnull[2] = false;
1156         fcinfo.argnull[3] = false;
1157         fcinfo.argnull[4] = false;
1158         fcinfo.argnull[5] = false;
1159
1160         result = (*func) (&fcinfo);
1161
1162         /* Check for null result, since caller is clearly not expecting one */
1163         if (fcinfo.isnull)
1164                 elog(ERROR, "function %p returned NULL", (void *) func);
1165
1166         return result;
1167 }
1168
1169 Datum
1170 DirectFunctionCall7(PGFunction func, Datum arg1, Datum arg2,
1171                                         Datum arg3, Datum arg4, Datum arg5,
1172                                         Datum arg6, Datum arg7)
1173 {
1174         FunctionCallInfoData fcinfo;
1175         Datum           result;
1176
1177         InitFunctionCallInfoData(fcinfo, NULL, 7, NULL, NULL);
1178
1179         fcinfo.arg[0] = arg1;
1180         fcinfo.arg[1] = arg2;
1181         fcinfo.arg[2] = arg3;
1182         fcinfo.arg[3] = arg4;
1183         fcinfo.arg[4] = arg5;
1184         fcinfo.arg[5] = arg6;
1185         fcinfo.arg[6] = arg7;
1186         fcinfo.argnull[0] = false;
1187         fcinfo.argnull[1] = false;
1188         fcinfo.argnull[2] = false;
1189         fcinfo.argnull[3] = false;
1190         fcinfo.argnull[4] = false;
1191         fcinfo.argnull[5] = false;
1192         fcinfo.argnull[6] = false;
1193
1194         result = (*func) (&fcinfo);
1195
1196         /* Check for null result, since caller is clearly not expecting one */
1197         if (fcinfo.isnull)
1198                 elog(ERROR, "function %p returned NULL", (void *) func);
1199
1200         return result;
1201 }
1202
1203 Datum
1204 DirectFunctionCall8(PGFunction func, Datum arg1, Datum arg2,
1205                                         Datum arg3, Datum arg4, Datum arg5,
1206                                         Datum arg6, Datum arg7, Datum arg8)
1207 {
1208         FunctionCallInfoData fcinfo;
1209         Datum           result;
1210
1211         InitFunctionCallInfoData(fcinfo, NULL, 8, NULL, NULL);
1212
1213         fcinfo.arg[0] = arg1;
1214         fcinfo.arg[1] = arg2;
1215         fcinfo.arg[2] = arg3;
1216         fcinfo.arg[3] = arg4;
1217         fcinfo.arg[4] = arg5;
1218         fcinfo.arg[5] = arg6;
1219         fcinfo.arg[6] = arg7;
1220         fcinfo.arg[7] = arg8;
1221         fcinfo.argnull[0] = false;
1222         fcinfo.argnull[1] = false;
1223         fcinfo.argnull[2] = false;
1224         fcinfo.argnull[3] = false;
1225         fcinfo.argnull[4] = false;
1226         fcinfo.argnull[5] = false;
1227         fcinfo.argnull[6] = false;
1228         fcinfo.argnull[7] = false;
1229
1230         result = (*func) (&fcinfo);
1231
1232         /* Check for null result, since caller is clearly not expecting one */
1233         if (fcinfo.isnull)
1234                 elog(ERROR, "function %p returned NULL", (void *) func);
1235
1236         return result;
1237 }
1238
1239 Datum
1240 DirectFunctionCall9(PGFunction func, Datum arg1, Datum arg2,
1241                                         Datum arg3, Datum arg4, Datum arg5,
1242                                         Datum arg6, Datum arg7, Datum arg8,
1243                                         Datum arg9)
1244 {
1245         FunctionCallInfoData fcinfo;
1246         Datum           result;
1247
1248         InitFunctionCallInfoData(fcinfo, NULL, 9, NULL, NULL);
1249
1250         fcinfo.arg[0] = arg1;
1251         fcinfo.arg[1] = arg2;
1252         fcinfo.arg[2] = arg3;
1253         fcinfo.arg[3] = arg4;
1254         fcinfo.arg[4] = arg5;
1255         fcinfo.arg[5] = arg6;
1256         fcinfo.arg[6] = arg7;
1257         fcinfo.arg[7] = arg8;
1258         fcinfo.arg[8] = arg9;
1259         fcinfo.argnull[0] = false;
1260         fcinfo.argnull[1] = false;
1261         fcinfo.argnull[2] = false;
1262         fcinfo.argnull[3] = false;
1263         fcinfo.argnull[4] = false;
1264         fcinfo.argnull[5] = false;
1265         fcinfo.argnull[6] = false;
1266         fcinfo.argnull[7] = false;
1267         fcinfo.argnull[8] = false;
1268
1269         result = (*func) (&fcinfo);
1270
1271         /* Check for null result, since caller is clearly not expecting one */
1272         if (fcinfo.isnull)
1273                 elog(ERROR, "function %p returned NULL", (void *) func);
1274
1275         return result;
1276 }
1277
1278
1279 /*
1280  * These are the same as DirectFunctionCallN except that a nonzero
1281  * collation can be specified.  No other fields of FmgrInfo are made valid.
1282  */
1283 Datum
1284 DirectFunctionCall1WithCollation(PGFunction func, Oid collation, Datum arg1)
1285 {
1286         FunctionCallInfoData fcinfo;
1287         FmgrInfo        flinfo;
1288         Datum           result;
1289
1290         MemSet(&flinfo, 0, sizeof(flinfo));
1291         flinfo.fn_collation = collation;
1292         InitFunctionCallInfoData(fcinfo, &flinfo, 1, NULL, NULL);
1293
1294         fcinfo.arg[0] = arg1;
1295         fcinfo.argnull[0] = false;
1296
1297         result = (*func) (&fcinfo);
1298
1299         /* Check for null result, since caller is clearly not expecting one */
1300         if (fcinfo.isnull)
1301                 elog(ERROR, "function %p returned NULL", (void *) func);
1302
1303         return result;
1304 }
1305
1306 Datum
1307 DirectFunctionCall2WithCollation(PGFunction func, Oid collation,
1308                                                                  Datum arg1, Datum arg2)
1309 {
1310         FunctionCallInfoData fcinfo;
1311         FmgrInfo        flinfo;
1312         Datum           result;
1313
1314         MemSet(&flinfo, 0, sizeof(flinfo));
1315         flinfo.fn_collation = collation;
1316         InitFunctionCallInfoData(fcinfo, &flinfo, 2, NULL, NULL);
1317
1318         fcinfo.arg[0] = arg1;
1319         fcinfo.arg[1] = arg2;
1320         fcinfo.argnull[0] = false;
1321         fcinfo.argnull[1] = false;
1322
1323         result = (*func) (&fcinfo);
1324
1325         /* Check for null result, since caller is clearly not expecting one */
1326         if (fcinfo.isnull)
1327                 elog(ERROR, "function %p returned NULL", (void *) func);
1328
1329         return result;
1330 }
1331
1332
1333 /*
1334  * These are for invocation of a previously-looked-up function with a
1335  * directly-computed parameter list.  Note that neither arguments nor result
1336  * are allowed to be NULL.
1337  */
1338 Datum
1339 FunctionCall1(FmgrInfo *flinfo, Datum arg1)
1340 {
1341         FunctionCallInfoData fcinfo;
1342         Datum           result;
1343
1344         InitFunctionCallInfoData(fcinfo, flinfo, 1, NULL, NULL);
1345
1346         fcinfo.arg[0] = arg1;
1347         fcinfo.argnull[0] = false;
1348
1349         result = FunctionCallInvoke(&fcinfo);
1350
1351         /* Check for null result, since caller is clearly not expecting one */
1352         if (fcinfo.isnull)
1353                 elog(ERROR, "function %u returned NULL", fcinfo.flinfo->fn_oid);
1354
1355         return result;
1356 }
1357
1358 Datum
1359 FunctionCall2(FmgrInfo *flinfo, Datum arg1, Datum arg2)
1360 {
1361         /*
1362          * XXX if you change this routine, see also the inlined version in
1363          * utils/sort/tuplesort.c!
1364          */
1365         FunctionCallInfoData fcinfo;
1366         Datum           result;
1367
1368         InitFunctionCallInfoData(fcinfo, flinfo, 2, NULL, NULL);
1369
1370         fcinfo.arg[0] = arg1;
1371         fcinfo.arg[1] = arg2;
1372         fcinfo.argnull[0] = false;
1373         fcinfo.argnull[1] = false;
1374
1375         result = FunctionCallInvoke(&fcinfo);
1376
1377         /* Check for null result, since caller is clearly not expecting one */
1378         if (fcinfo.isnull)
1379                 elog(ERROR, "function %u returned NULL", fcinfo.flinfo->fn_oid);
1380
1381         return result;
1382 }
1383
1384 Datum
1385 FunctionCall3(FmgrInfo *flinfo, Datum arg1, Datum arg2,
1386                           Datum arg3)
1387 {
1388         FunctionCallInfoData fcinfo;
1389         Datum           result;
1390
1391         InitFunctionCallInfoData(fcinfo, flinfo, 3, NULL, NULL);
1392
1393         fcinfo.arg[0] = arg1;
1394         fcinfo.arg[1] = arg2;
1395         fcinfo.arg[2] = arg3;
1396         fcinfo.argnull[0] = false;
1397         fcinfo.argnull[1] = false;
1398         fcinfo.argnull[2] = false;
1399
1400         result = FunctionCallInvoke(&fcinfo);
1401
1402         /* Check for null result, since caller is clearly not expecting one */
1403         if (fcinfo.isnull)
1404                 elog(ERROR, "function %u returned NULL", fcinfo.flinfo->fn_oid);
1405
1406         return result;
1407 }
1408
1409 Datum
1410 FunctionCall4(FmgrInfo *flinfo, Datum arg1, Datum arg2,
1411                           Datum arg3, Datum arg4)
1412 {
1413         FunctionCallInfoData fcinfo;
1414         Datum           result;
1415
1416         InitFunctionCallInfoData(fcinfo, flinfo, 4, NULL, NULL);
1417
1418         fcinfo.arg[0] = arg1;
1419         fcinfo.arg[1] = arg2;
1420         fcinfo.arg[2] = arg3;
1421         fcinfo.arg[3] = arg4;
1422         fcinfo.argnull[0] = false;
1423         fcinfo.argnull[1] = false;
1424         fcinfo.argnull[2] = false;
1425         fcinfo.argnull[3] = false;
1426
1427         result = FunctionCallInvoke(&fcinfo);
1428
1429         /* Check for null result, since caller is clearly not expecting one */
1430         if (fcinfo.isnull)
1431                 elog(ERROR, "function %u returned NULL", fcinfo.flinfo->fn_oid);
1432
1433         return result;
1434 }
1435
1436 Datum
1437 FunctionCall5(FmgrInfo *flinfo, Datum arg1, Datum arg2,
1438                           Datum arg3, Datum arg4, Datum arg5)
1439 {
1440         FunctionCallInfoData fcinfo;
1441         Datum           result;
1442
1443         InitFunctionCallInfoData(fcinfo, flinfo, 5, NULL, NULL);
1444
1445         fcinfo.arg[0] = arg1;
1446         fcinfo.arg[1] = arg2;
1447         fcinfo.arg[2] = arg3;
1448         fcinfo.arg[3] = arg4;
1449         fcinfo.arg[4] = arg5;
1450         fcinfo.argnull[0] = false;
1451         fcinfo.argnull[1] = false;
1452         fcinfo.argnull[2] = false;
1453         fcinfo.argnull[3] = false;
1454         fcinfo.argnull[4] = false;
1455
1456         result = FunctionCallInvoke(&fcinfo);
1457
1458         /* Check for null result, since caller is clearly not expecting one */
1459         if (fcinfo.isnull)
1460                 elog(ERROR, "function %u returned NULL", fcinfo.flinfo->fn_oid);
1461
1462         return result;
1463 }
1464
1465 Datum
1466 FunctionCall6(FmgrInfo *flinfo, Datum arg1, Datum arg2,
1467                           Datum arg3, Datum arg4, Datum arg5,
1468                           Datum arg6)
1469 {
1470         FunctionCallInfoData fcinfo;
1471         Datum           result;
1472
1473         InitFunctionCallInfoData(fcinfo, flinfo, 6, NULL, NULL);
1474
1475         fcinfo.arg[0] = arg1;
1476         fcinfo.arg[1] = arg2;
1477         fcinfo.arg[2] = arg3;
1478         fcinfo.arg[3] = arg4;
1479         fcinfo.arg[4] = arg5;
1480         fcinfo.arg[5] = arg6;
1481         fcinfo.argnull[0] = false;
1482         fcinfo.argnull[1] = false;
1483         fcinfo.argnull[2] = false;
1484         fcinfo.argnull[3] = false;
1485         fcinfo.argnull[4] = false;
1486         fcinfo.argnull[5] = false;
1487
1488         result = FunctionCallInvoke(&fcinfo);
1489
1490         /* Check for null result, since caller is clearly not expecting one */
1491         if (fcinfo.isnull)
1492                 elog(ERROR, "function %u returned NULL", fcinfo.flinfo->fn_oid);
1493
1494         return result;
1495 }
1496
1497 Datum
1498 FunctionCall7(FmgrInfo *flinfo, Datum arg1, Datum arg2,
1499                           Datum arg3, Datum arg4, Datum arg5,
1500                           Datum arg6, Datum arg7)
1501 {
1502         FunctionCallInfoData fcinfo;
1503         Datum           result;
1504
1505         InitFunctionCallInfoData(fcinfo, flinfo, 7, NULL, NULL);
1506
1507         fcinfo.arg[0] = arg1;
1508         fcinfo.arg[1] = arg2;
1509         fcinfo.arg[2] = arg3;
1510         fcinfo.arg[3] = arg4;
1511         fcinfo.arg[4] = arg5;
1512         fcinfo.arg[5] = arg6;
1513         fcinfo.arg[6] = arg7;
1514         fcinfo.argnull[0] = false;
1515         fcinfo.argnull[1] = false;
1516         fcinfo.argnull[2] = false;
1517         fcinfo.argnull[3] = false;
1518         fcinfo.argnull[4] = false;
1519         fcinfo.argnull[5] = false;
1520         fcinfo.argnull[6] = false;
1521
1522         result = FunctionCallInvoke(&fcinfo);
1523
1524         /* Check for null result, since caller is clearly not expecting one */
1525         if (fcinfo.isnull)
1526                 elog(ERROR, "function %u returned NULL", fcinfo.flinfo->fn_oid);
1527
1528         return result;
1529 }
1530
1531 Datum
1532 FunctionCall8(FmgrInfo *flinfo, Datum arg1, Datum arg2,
1533                           Datum arg3, Datum arg4, Datum arg5,
1534                           Datum arg6, Datum arg7, Datum arg8)
1535 {
1536         FunctionCallInfoData fcinfo;
1537         Datum           result;
1538
1539         InitFunctionCallInfoData(fcinfo, flinfo, 8, NULL, NULL);
1540
1541         fcinfo.arg[0] = arg1;
1542         fcinfo.arg[1] = arg2;
1543         fcinfo.arg[2] = arg3;
1544         fcinfo.arg[3] = arg4;
1545         fcinfo.arg[4] = arg5;
1546         fcinfo.arg[5] = arg6;
1547         fcinfo.arg[6] = arg7;
1548         fcinfo.arg[7] = arg8;
1549         fcinfo.argnull[0] = false;
1550         fcinfo.argnull[1] = false;
1551         fcinfo.argnull[2] = false;
1552         fcinfo.argnull[3] = false;
1553         fcinfo.argnull[4] = false;
1554         fcinfo.argnull[5] = false;
1555         fcinfo.argnull[6] = false;
1556         fcinfo.argnull[7] = false;
1557
1558         result = FunctionCallInvoke(&fcinfo);
1559
1560         /* Check for null result, since caller is clearly not expecting one */
1561         if (fcinfo.isnull)
1562                 elog(ERROR, "function %u returned NULL", fcinfo.flinfo->fn_oid);
1563
1564         return result;
1565 }
1566
1567 Datum
1568 FunctionCall9(FmgrInfo *flinfo, Datum arg1, Datum arg2,
1569                           Datum arg3, Datum arg4, Datum arg5,
1570                           Datum arg6, Datum arg7, Datum arg8,
1571                           Datum arg9)
1572 {
1573         FunctionCallInfoData fcinfo;
1574         Datum           result;
1575
1576         InitFunctionCallInfoData(fcinfo, flinfo, 9, NULL, NULL);
1577
1578         fcinfo.arg[0] = arg1;
1579         fcinfo.arg[1] = arg2;
1580         fcinfo.arg[2] = arg3;
1581         fcinfo.arg[3] = arg4;
1582         fcinfo.arg[4] = arg5;
1583         fcinfo.arg[5] = arg6;
1584         fcinfo.arg[6] = arg7;
1585         fcinfo.arg[7] = arg8;
1586         fcinfo.arg[8] = arg9;
1587         fcinfo.argnull[0] = false;
1588         fcinfo.argnull[1] = false;
1589         fcinfo.argnull[2] = false;
1590         fcinfo.argnull[3] = false;
1591         fcinfo.argnull[4] = false;
1592         fcinfo.argnull[5] = false;
1593         fcinfo.argnull[6] = false;
1594         fcinfo.argnull[7] = false;
1595         fcinfo.argnull[8] = false;
1596
1597         result = FunctionCallInvoke(&fcinfo);
1598
1599         /* Check for null result, since caller is clearly not expecting one */
1600         if (fcinfo.isnull)
1601                 elog(ERROR, "function %u returned NULL", fcinfo.flinfo->fn_oid);
1602
1603         return result;
1604 }
1605
1606
1607 /*
1608  * These are for invocation of a function identified by OID with a
1609  * directly-computed parameter list.  Note that neither arguments nor result
1610  * are allowed to be NULL.      These are essentially fmgr_info() followed
1611  * by FunctionCallN().  If the same function is to be invoked repeatedly,
1612  * do the fmgr_info() once and then use FunctionCallN().
1613  */
1614 Datum
1615 OidFunctionCall0(Oid functionId)
1616 {
1617         FmgrInfo        flinfo;
1618         FunctionCallInfoData fcinfo;
1619         Datum           result;
1620
1621         fmgr_info(functionId, &flinfo);
1622
1623         InitFunctionCallInfoData(fcinfo, &flinfo, 0, NULL, NULL);
1624
1625         result = FunctionCallInvoke(&fcinfo);
1626
1627         /* Check for null result, since caller is clearly not expecting one */
1628         if (fcinfo.isnull)
1629                 elog(ERROR, "function %u returned NULL", flinfo.fn_oid);
1630
1631         return result;
1632 }
1633
1634 Datum
1635 OidFunctionCall1(Oid functionId, Datum arg1)
1636 {
1637         FmgrInfo        flinfo;
1638         FunctionCallInfoData fcinfo;
1639         Datum           result;
1640
1641         fmgr_info(functionId, &flinfo);
1642
1643         InitFunctionCallInfoData(fcinfo, &flinfo, 1, NULL, NULL);
1644
1645         fcinfo.arg[0] = arg1;
1646         fcinfo.argnull[0] = false;
1647
1648         result = FunctionCallInvoke(&fcinfo);
1649
1650         /* Check for null result, since caller is clearly not expecting one */
1651         if (fcinfo.isnull)
1652                 elog(ERROR, "function %u returned NULL", flinfo.fn_oid);
1653
1654         return result;
1655 }
1656
1657 Datum
1658 OidFunctionCall2(Oid functionId, Datum arg1, Datum arg2)
1659 {
1660         FmgrInfo        flinfo;
1661         FunctionCallInfoData fcinfo;
1662         Datum           result;
1663
1664         fmgr_info(functionId, &flinfo);
1665
1666         InitFunctionCallInfoData(fcinfo, &flinfo, 2, NULL, NULL);
1667
1668         fcinfo.arg[0] = arg1;
1669         fcinfo.arg[1] = arg2;
1670         fcinfo.argnull[0] = false;
1671         fcinfo.argnull[1] = false;
1672
1673         result = FunctionCallInvoke(&fcinfo);
1674
1675         /* Check for null result, since caller is clearly not expecting one */
1676         if (fcinfo.isnull)
1677                 elog(ERROR, "function %u returned NULL", flinfo.fn_oid);
1678
1679         return result;
1680 }
1681
1682 Datum
1683 OidFunctionCall3(Oid functionId, Datum arg1, Datum arg2,
1684                                  Datum arg3)
1685 {
1686         FmgrInfo        flinfo;
1687         FunctionCallInfoData fcinfo;
1688         Datum           result;
1689
1690         fmgr_info(functionId, &flinfo);
1691
1692         InitFunctionCallInfoData(fcinfo, &flinfo, 3, NULL, NULL);
1693
1694         fcinfo.arg[0] = arg1;
1695         fcinfo.arg[1] = arg2;
1696         fcinfo.arg[2] = arg3;
1697         fcinfo.argnull[0] = false;
1698         fcinfo.argnull[1] = false;
1699         fcinfo.argnull[2] = false;
1700
1701         result = FunctionCallInvoke(&fcinfo);
1702
1703         /* Check for null result, since caller is clearly not expecting one */
1704         if (fcinfo.isnull)
1705                 elog(ERROR, "function %u returned NULL", flinfo.fn_oid);
1706
1707         return result;
1708 }
1709
1710 Datum
1711 OidFunctionCall4(Oid functionId, Datum arg1, Datum arg2,
1712                                  Datum arg3, Datum arg4)
1713 {
1714         FmgrInfo        flinfo;
1715         FunctionCallInfoData fcinfo;
1716         Datum           result;
1717
1718         fmgr_info(functionId, &flinfo);
1719
1720         InitFunctionCallInfoData(fcinfo, &flinfo, 4, NULL, NULL);
1721
1722         fcinfo.arg[0] = arg1;
1723         fcinfo.arg[1] = arg2;
1724         fcinfo.arg[2] = arg3;
1725         fcinfo.arg[3] = arg4;
1726         fcinfo.argnull[0] = false;
1727         fcinfo.argnull[1] = false;
1728         fcinfo.argnull[2] = false;
1729         fcinfo.argnull[3] = false;
1730
1731         result = FunctionCallInvoke(&fcinfo);
1732
1733         /* Check for null result, since caller is clearly not expecting one */
1734         if (fcinfo.isnull)
1735                 elog(ERROR, "function %u returned NULL", flinfo.fn_oid);
1736
1737         return result;
1738 }
1739
1740 Datum
1741 OidFunctionCall5(Oid functionId, Datum arg1, Datum arg2,
1742                                  Datum arg3, Datum arg4, Datum arg5)
1743 {
1744         FmgrInfo        flinfo;
1745         FunctionCallInfoData fcinfo;
1746         Datum           result;
1747
1748         fmgr_info(functionId, &flinfo);
1749
1750         InitFunctionCallInfoData(fcinfo, &flinfo, 5, NULL, NULL);
1751
1752         fcinfo.arg[0] = arg1;
1753         fcinfo.arg[1] = arg2;
1754         fcinfo.arg[2] = arg3;
1755         fcinfo.arg[3] = arg4;
1756         fcinfo.arg[4] = arg5;
1757         fcinfo.argnull[0] = false;
1758         fcinfo.argnull[1] = false;
1759         fcinfo.argnull[2] = false;
1760         fcinfo.argnull[3] = false;
1761         fcinfo.argnull[4] = false;
1762
1763         result = FunctionCallInvoke(&fcinfo);
1764
1765         /* Check for null result, since caller is clearly not expecting one */
1766         if (fcinfo.isnull)
1767                 elog(ERROR, "function %u returned NULL", flinfo.fn_oid);
1768
1769         return result;
1770 }
1771
1772 Datum
1773 OidFunctionCall6(Oid functionId, Datum arg1, Datum arg2,
1774                                  Datum arg3, Datum arg4, Datum arg5,
1775                                  Datum arg6)
1776 {
1777         FmgrInfo        flinfo;
1778         FunctionCallInfoData fcinfo;
1779         Datum           result;
1780
1781         fmgr_info(functionId, &flinfo);
1782
1783         InitFunctionCallInfoData(fcinfo, &flinfo, 6, NULL, NULL);
1784
1785         fcinfo.arg[0] = arg1;
1786         fcinfo.arg[1] = arg2;
1787         fcinfo.arg[2] = arg3;
1788         fcinfo.arg[3] = arg4;
1789         fcinfo.arg[4] = arg5;
1790         fcinfo.arg[5] = arg6;
1791         fcinfo.argnull[0] = false;
1792         fcinfo.argnull[1] = false;
1793         fcinfo.argnull[2] = false;
1794         fcinfo.argnull[3] = false;
1795         fcinfo.argnull[4] = false;
1796         fcinfo.argnull[5] = false;
1797
1798         result = FunctionCallInvoke(&fcinfo);
1799
1800         /* Check for null result, since caller is clearly not expecting one */
1801         if (fcinfo.isnull)
1802                 elog(ERROR, "function %u returned NULL", flinfo.fn_oid);
1803
1804         return result;
1805 }
1806
1807 Datum
1808 OidFunctionCall7(Oid functionId, Datum arg1, Datum arg2,
1809                                  Datum arg3, Datum arg4, Datum arg5,
1810                                  Datum arg6, Datum arg7)
1811 {
1812         FmgrInfo        flinfo;
1813         FunctionCallInfoData fcinfo;
1814         Datum           result;
1815
1816         fmgr_info(functionId, &flinfo);
1817
1818         InitFunctionCallInfoData(fcinfo, &flinfo, 7, NULL, NULL);
1819
1820         fcinfo.arg[0] = arg1;
1821         fcinfo.arg[1] = arg2;
1822         fcinfo.arg[2] = arg3;
1823         fcinfo.arg[3] = arg4;
1824         fcinfo.arg[4] = arg5;
1825         fcinfo.arg[5] = arg6;
1826         fcinfo.arg[6] = arg7;
1827         fcinfo.argnull[0] = false;
1828         fcinfo.argnull[1] = false;
1829         fcinfo.argnull[2] = false;
1830         fcinfo.argnull[3] = false;
1831         fcinfo.argnull[4] = false;
1832         fcinfo.argnull[5] = false;
1833         fcinfo.argnull[6] = false;
1834
1835         result = FunctionCallInvoke(&fcinfo);
1836
1837         /* Check for null result, since caller is clearly not expecting one */
1838         if (fcinfo.isnull)
1839                 elog(ERROR, "function %u returned NULL", flinfo.fn_oid);
1840
1841         return result;
1842 }
1843
1844 Datum
1845 OidFunctionCall8(Oid functionId, Datum arg1, Datum arg2,
1846                                  Datum arg3, Datum arg4, Datum arg5,
1847                                  Datum arg6, Datum arg7, Datum arg8)
1848 {
1849         FmgrInfo        flinfo;
1850         FunctionCallInfoData fcinfo;
1851         Datum           result;
1852
1853         fmgr_info(functionId, &flinfo);
1854
1855         InitFunctionCallInfoData(fcinfo, &flinfo, 8, NULL, NULL);
1856
1857         fcinfo.arg[0] = arg1;
1858         fcinfo.arg[1] = arg2;
1859         fcinfo.arg[2] = arg3;
1860         fcinfo.arg[3] = arg4;
1861         fcinfo.arg[4] = arg5;
1862         fcinfo.arg[5] = arg6;
1863         fcinfo.arg[6] = arg7;
1864         fcinfo.arg[7] = arg8;
1865         fcinfo.argnull[0] = false;
1866         fcinfo.argnull[1] = false;
1867         fcinfo.argnull[2] = false;
1868         fcinfo.argnull[3] = false;
1869         fcinfo.argnull[4] = false;
1870         fcinfo.argnull[5] = false;
1871         fcinfo.argnull[6] = false;
1872         fcinfo.argnull[7] = false;
1873
1874         result = FunctionCallInvoke(&fcinfo);
1875
1876         /* Check for null result, since caller is clearly not expecting one */
1877         if (fcinfo.isnull)
1878                 elog(ERROR, "function %u returned NULL", flinfo.fn_oid);
1879
1880         return result;
1881 }
1882
1883 Datum
1884 OidFunctionCall9(Oid functionId, Datum arg1, Datum arg2,
1885                                  Datum arg3, Datum arg4, Datum arg5,
1886                                  Datum arg6, Datum arg7, Datum arg8,
1887                                  Datum arg9)
1888 {
1889         FmgrInfo        flinfo;
1890         FunctionCallInfoData fcinfo;
1891         Datum           result;
1892
1893         fmgr_info(functionId, &flinfo);
1894
1895         InitFunctionCallInfoData(fcinfo, &flinfo, 9, NULL, NULL);
1896
1897         fcinfo.arg[0] = arg1;
1898         fcinfo.arg[1] = arg2;
1899         fcinfo.arg[2] = arg3;
1900         fcinfo.arg[3] = arg4;
1901         fcinfo.arg[4] = arg5;
1902         fcinfo.arg[5] = arg6;
1903         fcinfo.arg[6] = arg7;
1904         fcinfo.arg[7] = arg8;
1905         fcinfo.arg[8] = arg9;
1906         fcinfo.argnull[0] = false;
1907         fcinfo.argnull[1] = false;
1908         fcinfo.argnull[2] = false;
1909         fcinfo.argnull[3] = false;
1910         fcinfo.argnull[4] = false;
1911         fcinfo.argnull[5] = false;
1912         fcinfo.argnull[6] = false;
1913         fcinfo.argnull[7] = false;
1914         fcinfo.argnull[8] = false;
1915
1916         result = FunctionCallInvoke(&fcinfo);
1917
1918         /* Check for null result, since caller is clearly not expecting one */
1919         if (fcinfo.isnull)
1920                 elog(ERROR, "function %u returned NULL", flinfo.fn_oid);
1921
1922         return result;
1923 }
1924
1925
1926 /*
1927  * Special cases for convenient invocation of datatype I/O functions.
1928  */
1929
1930 /*
1931  * Call a previously-looked-up datatype input function.
1932  *
1933  * "str" may be NULL to indicate we are reading a NULL.  In this case
1934  * the caller should assume the result is NULL, but we'll call the input
1935  * function anyway if it's not strict.  So this is almost but not quite
1936  * the same as FunctionCall3.
1937  *
1938  * One important difference from the bare function call is that we will
1939  * push any active SPI context, allowing SPI-using I/O functions to be
1940  * called from other SPI functions without extra notation.      This is a hack,
1941  * but the alternative of expecting all SPI functions to do SPI_push/SPI_pop
1942  * around I/O calls seems worse.
1943  */
1944 Datum
1945 InputFunctionCall(FmgrInfo *flinfo, char *str, Oid typioparam, int32 typmod)
1946 {
1947         FunctionCallInfoData fcinfo;
1948         Datum           result;
1949         bool            pushed;
1950
1951         if (str == NULL && flinfo->fn_strict)
1952                 return (Datum) 0;               /* just return null result */
1953
1954         pushed = SPI_push_conditional();
1955
1956         InitFunctionCallInfoData(fcinfo, flinfo, 3, NULL, NULL);
1957
1958         fcinfo.arg[0] = CStringGetDatum(str);
1959         fcinfo.arg[1] = ObjectIdGetDatum(typioparam);
1960         fcinfo.arg[2] = Int32GetDatum(typmod);
1961         fcinfo.argnull[0] = (str == NULL);
1962         fcinfo.argnull[1] = false;
1963         fcinfo.argnull[2] = false;
1964
1965         result = FunctionCallInvoke(&fcinfo);
1966
1967         /* Should get null result if and only if str is NULL */
1968         if (str == NULL)
1969         {
1970                 if (!fcinfo.isnull)
1971                         elog(ERROR, "input function %u returned non-NULL",
1972                                  fcinfo.flinfo->fn_oid);
1973         }
1974         else
1975         {
1976                 if (fcinfo.isnull)
1977                         elog(ERROR, "input function %u returned NULL",
1978                                  fcinfo.flinfo->fn_oid);
1979         }
1980
1981         SPI_pop_conditional(pushed);
1982
1983         return result;
1984 }
1985
1986 /*
1987  * Call a previously-looked-up datatype output function.
1988  *
1989  * Do not call this on NULL datums.
1990  *
1991  * This is almost just window dressing for FunctionCall1, but it includes
1992  * SPI context pushing for the same reasons as InputFunctionCall.
1993  */
1994 char *
1995 OutputFunctionCall(FmgrInfo *flinfo, Datum val)
1996 {
1997         char       *result;
1998         bool            pushed;
1999
2000         pushed = SPI_push_conditional();
2001
2002         result = DatumGetCString(FunctionCall1(flinfo, val));
2003
2004         SPI_pop_conditional(pushed);
2005
2006         return result;
2007 }
2008
2009 /*
2010  * Call a previously-looked-up datatype binary-input function.
2011  *
2012  * "buf" may be NULL to indicate we are reading a NULL.  In this case
2013  * the caller should assume the result is NULL, but we'll call the receive
2014  * function anyway if it's not strict.  So this is almost but not quite
2015  * the same as FunctionCall3.  Also, this includes SPI context pushing for
2016  * the same reasons as InputFunctionCall.
2017  */
2018 Datum
2019 ReceiveFunctionCall(FmgrInfo *flinfo, StringInfo buf,
2020                                         Oid typioparam, int32 typmod)
2021 {
2022         FunctionCallInfoData fcinfo;
2023         Datum           result;
2024         bool            pushed;
2025
2026         if (buf == NULL && flinfo->fn_strict)
2027                 return (Datum) 0;               /* just return null result */
2028
2029         pushed = SPI_push_conditional();
2030
2031         InitFunctionCallInfoData(fcinfo, flinfo, 3, NULL, NULL);
2032
2033         fcinfo.arg[0] = PointerGetDatum(buf);
2034         fcinfo.arg[1] = ObjectIdGetDatum(typioparam);
2035         fcinfo.arg[2] = Int32GetDatum(typmod);
2036         fcinfo.argnull[0] = (buf == NULL);
2037         fcinfo.argnull[1] = false;
2038         fcinfo.argnull[2] = false;
2039
2040         result = FunctionCallInvoke(&fcinfo);
2041
2042         /* Should get null result if and only if buf is NULL */
2043         if (buf == NULL)
2044         {
2045                 if (!fcinfo.isnull)
2046                         elog(ERROR, "receive function %u returned non-NULL",
2047                                  fcinfo.flinfo->fn_oid);
2048         }
2049         else
2050         {
2051                 if (fcinfo.isnull)
2052                         elog(ERROR, "receive function %u returned NULL",
2053                                  fcinfo.flinfo->fn_oid);
2054         }
2055
2056         SPI_pop_conditional(pushed);
2057
2058         return result;
2059 }
2060
2061 /*
2062  * Call a previously-looked-up datatype binary-output function.
2063  *
2064  * Do not call this on NULL datums.
2065  *
2066  * This is little more than window dressing for FunctionCall1, but it does
2067  * guarantee a non-toasted result, which strictly speaking the underlying
2068  * function doesn't.  Also, this includes SPI context pushing for the same
2069  * reasons as InputFunctionCall.
2070  */
2071 bytea *
2072 SendFunctionCall(FmgrInfo *flinfo, Datum val)
2073 {
2074         bytea      *result;
2075         bool            pushed;
2076
2077         pushed = SPI_push_conditional();
2078
2079         result = DatumGetByteaP(FunctionCall1(flinfo, val));
2080
2081         SPI_pop_conditional(pushed);
2082
2083         return result;
2084 }
2085
2086 /*
2087  * As above, for I/O functions identified by OID.  These are only to be used
2088  * in seldom-executed code paths.  They are not only slow but leak memory.
2089  */
2090 Datum
2091 OidInputFunctionCall(Oid functionId, char *str, Oid typioparam, int32 typmod)
2092 {
2093         FmgrInfo        flinfo;
2094
2095         fmgr_info(functionId, &flinfo);
2096         return InputFunctionCall(&flinfo, str, typioparam, typmod);
2097 }
2098
2099 char *
2100 OidOutputFunctionCall(Oid functionId, Datum val)
2101 {
2102         FmgrInfo        flinfo;
2103
2104         fmgr_info(functionId, &flinfo);
2105         return OutputFunctionCall(&flinfo, val);
2106 }
2107
2108 Datum
2109 OidReceiveFunctionCall(Oid functionId, StringInfo buf,
2110                                            Oid typioparam, int32 typmod)
2111 {
2112         FmgrInfo        flinfo;
2113
2114         fmgr_info(functionId, &flinfo);
2115         return ReceiveFunctionCall(&flinfo, buf, typioparam, typmod);
2116 }
2117
2118 bytea *
2119 OidSendFunctionCall(Oid functionId, Datum val)
2120 {
2121         FmgrInfo        flinfo;
2122
2123         fmgr_info(functionId, &flinfo);
2124         return SendFunctionCall(&flinfo, val);
2125 }
2126
2127
2128 /*
2129  * !!! OLD INTERFACE !!!
2130  *
2131  * fmgr() is the only remaining vestige of the old-style caller support
2132  * functions.  It's no longer used anywhere in the Postgres distribution,
2133  * but we should leave it around for a release or two to ease the transition
2134  * for user-supplied C functions.  OidFunctionCallN() replaces it for new
2135  * code.
2136  *
2137  * DEPRECATED, DO NOT USE IN NEW CODE
2138  */
2139 char *
2140 fmgr(Oid procedureId,...)
2141 {
2142         FmgrInfo        flinfo;
2143         FunctionCallInfoData fcinfo;
2144         int                     n_arguments;
2145         Datum           result;
2146
2147         fmgr_info(procedureId, &flinfo);
2148
2149         MemSet(&fcinfo, 0, sizeof(fcinfo));
2150         fcinfo.flinfo = &flinfo;
2151         fcinfo.nargs = flinfo.fn_nargs;
2152         n_arguments = fcinfo.nargs;
2153
2154         if (n_arguments > 0)
2155         {
2156                 va_list         pvar;
2157                 int                     i;
2158
2159                 if (n_arguments > FUNC_MAX_ARGS)
2160                         ereport(ERROR,
2161                                         (errcode(ERRCODE_TOO_MANY_ARGUMENTS),
2162                          errmsg("function %u has too many arguments (%d, maximum is %d)",
2163                                         flinfo.fn_oid, n_arguments, FUNC_MAX_ARGS)));
2164                 va_start(pvar, procedureId);
2165                 for (i = 0; i < n_arguments; i++)
2166                         fcinfo.arg[i] = PointerGetDatum(va_arg(pvar, char *));
2167                 va_end(pvar);
2168         }
2169
2170         result = FunctionCallInvoke(&fcinfo);
2171
2172         /* Check for null result, since caller is clearly not expecting one */
2173         if (fcinfo.isnull)
2174                 elog(ERROR, "function %u returned NULL", flinfo.fn_oid);
2175
2176         return DatumGetPointer(result);
2177 }
2178
2179
2180 /*-------------------------------------------------------------------------
2181  *              Support routines for standard maybe-pass-by-reference datatypes
2182  *
2183  * int8, float4, and float8 can be passed by value if Datum is wide enough.
2184  * (For backwards-compatibility reasons, we allow pass-by-ref to be chosen
2185  * at compile time even if pass-by-val is possible.)  For the float types,
2186  * we need a support routine even if we are passing by value, because many
2187  * machines pass int and float function parameters/results differently;
2188  * so we need to play weird games with unions.
2189  *
2190  * Note: there is only one switch controlling the pass-by-value option for
2191  * both int8 and float8; this is to avoid making things unduly complicated
2192  * for the timestamp types, which might have either representation.
2193  *-------------------------------------------------------------------------
2194  */
2195
2196 #ifndef USE_FLOAT8_BYVAL                /* controls int8 too */
2197
2198 Datum
2199 Int64GetDatum(int64 X)
2200 {
2201         int64      *retval = (int64 *) palloc(sizeof(int64));
2202
2203         *retval = X;
2204         return PointerGetDatum(retval);
2205 }
2206 #endif   /* USE_FLOAT8_BYVAL */
2207
2208 Datum
2209 Float4GetDatum(float4 X)
2210 {
2211 #ifdef USE_FLOAT4_BYVAL
2212         union
2213         {
2214                 float4          value;
2215                 int32           retval;
2216         }                       myunion;
2217
2218         myunion.value = X;
2219         return SET_4_BYTES(myunion.retval);
2220 #else
2221         float4     *retval = (float4 *) palloc(sizeof(float4));
2222
2223         *retval = X;
2224         return PointerGetDatum(retval);
2225 #endif
2226 }
2227
2228 #ifdef USE_FLOAT4_BYVAL
2229
2230 float4
2231 DatumGetFloat4(Datum X)
2232 {
2233         union
2234         {
2235                 int32           value;
2236                 float4          retval;
2237         }                       myunion;
2238
2239         myunion.value = GET_4_BYTES(X);
2240         return myunion.retval;
2241 }
2242 #endif   /* USE_FLOAT4_BYVAL */
2243
2244 Datum
2245 Float8GetDatum(float8 X)
2246 {
2247 #ifdef USE_FLOAT8_BYVAL
2248         union
2249         {
2250                 float8          value;
2251                 int64           retval;
2252         }                       myunion;
2253
2254         myunion.value = X;
2255         return SET_8_BYTES(myunion.retval);
2256 #else
2257         float8     *retval = (float8 *) palloc(sizeof(float8));
2258
2259         *retval = X;
2260         return PointerGetDatum(retval);
2261 #endif
2262 }
2263
2264 #ifdef USE_FLOAT8_BYVAL
2265
2266 float8
2267 DatumGetFloat8(Datum X)
2268 {
2269         union
2270         {
2271                 int64           value;
2272                 float8          retval;
2273         }                       myunion;
2274
2275         myunion.value = GET_8_BYTES(X);
2276         return myunion.retval;
2277 }
2278 #endif   /* USE_FLOAT8_BYVAL */
2279
2280
2281 /*-------------------------------------------------------------------------
2282  *              Support routines for toastable datatypes
2283  *-------------------------------------------------------------------------
2284  */
2285
2286 struct varlena *
2287 pg_detoast_datum(struct varlena * datum)
2288 {
2289         if (VARATT_IS_EXTENDED(datum))
2290                 return heap_tuple_untoast_attr(datum);
2291         else
2292                 return datum;
2293 }
2294
2295 struct varlena *
2296 pg_detoast_datum_copy(struct varlena * datum)
2297 {
2298         if (VARATT_IS_EXTENDED(datum))
2299                 return heap_tuple_untoast_attr(datum);
2300         else
2301         {
2302                 /* Make a modifiable copy of the varlena object */
2303                 Size            len = VARSIZE(datum);
2304                 struct varlena *result = (struct varlena *) palloc(len);
2305
2306                 memcpy(result, datum, len);
2307                 return result;
2308         }
2309 }
2310
2311 struct varlena *
2312 pg_detoast_datum_slice(struct varlena * datum, int32 first, int32 count)
2313 {
2314         /* Only get the specified portion from the toast rel */
2315         return heap_tuple_untoast_attr_slice(datum, first, count);
2316 }
2317
2318 struct varlena *
2319 pg_detoast_datum_packed(struct varlena * datum)
2320 {
2321         if (VARATT_IS_COMPRESSED(datum) || VARATT_IS_EXTERNAL(datum))
2322                 return heap_tuple_untoast_attr(datum);
2323         else
2324                 return datum;
2325 }
2326
2327 /*-------------------------------------------------------------------------
2328  *              Support routines for extracting info from fn_expr parse tree
2329  *
2330  * These are needed by polymorphic functions, which accept multiple possible
2331  * input types and need help from the parser to know what they've got.
2332  * Also, some functions might be interested in whether a parameter is constant.
2333  *-------------------------------------------------------------------------
2334  */
2335
2336 /*
2337  * Get the actual type OID of the function return type
2338  *
2339  * Returns InvalidOid if information is not available
2340  */
2341 Oid
2342 get_fn_expr_rettype(FmgrInfo *flinfo)
2343 {
2344         Node       *expr;
2345
2346         /*
2347          * can't return anything useful if we have no FmgrInfo or if its fn_expr
2348          * node has not been initialized
2349          */
2350         if (!flinfo || !flinfo->fn_expr)
2351                 return InvalidOid;
2352
2353         expr = flinfo->fn_expr;
2354
2355         return exprType(expr);
2356 }
2357
2358 /*
2359  * Get the actual type OID of a specific function argument (counting from 0)
2360  *
2361  * Returns InvalidOid if information is not available
2362  */
2363 Oid
2364 get_fn_expr_argtype(FmgrInfo *flinfo, int argnum)
2365 {
2366         /*
2367          * can't return anything useful if we have no FmgrInfo or if its fn_expr
2368          * node has not been initialized
2369          */
2370         if (!flinfo || !flinfo->fn_expr)
2371                 return InvalidOid;
2372
2373         return get_call_expr_argtype(flinfo->fn_expr, argnum);
2374 }
2375
2376 /*
2377  * Get the actual type OID of a specific function argument (counting from 0),
2378  * but working from the calling expression tree instead of FmgrInfo
2379  *
2380  * Returns InvalidOid if information is not available
2381  */
2382 Oid
2383 get_call_expr_argtype(Node *expr, int argnum)
2384 {
2385         List       *args;
2386         Oid                     argtype;
2387
2388         if (expr == NULL)
2389                 return InvalidOid;
2390
2391         if (IsA(expr, FuncExpr))
2392                 args = ((FuncExpr *) expr)->args;
2393         else if (IsA(expr, OpExpr))
2394                 args = ((OpExpr *) expr)->args;
2395         else if (IsA(expr, DistinctExpr))
2396                 args = ((DistinctExpr *) expr)->args;
2397         else if (IsA(expr, ScalarArrayOpExpr))
2398                 args = ((ScalarArrayOpExpr *) expr)->args;
2399         else if (IsA(expr, ArrayCoerceExpr))
2400                 args = list_make1(((ArrayCoerceExpr *) expr)->arg);
2401         else if (IsA(expr, NullIfExpr))
2402                 args = ((NullIfExpr *) expr)->args;
2403         else if (IsA(expr, WindowFunc))
2404                 args = ((WindowFunc *) expr)->args;
2405         else
2406                 return InvalidOid;
2407
2408         if (argnum < 0 || argnum >= list_length(args))
2409                 return InvalidOid;
2410
2411         argtype = exprType((Node *) list_nth(args, argnum));
2412
2413         /*
2414          * special hack for ScalarArrayOpExpr and ArrayCoerceExpr: what the
2415          * underlying function will actually get passed is the element type of the
2416          * array.
2417          */
2418         if (IsA(expr, ScalarArrayOpExpr) &&
2419                 argnum == 1)
2420                 argtype = get_base_element_type(argtype);
2421         else if (IsA(expr, ArrayCoerceExpr) &&
2422                          argnum == 0)
2423                 argtype = get_base_element_type(argtype);
2424
2425         return argtype;
2426 }
2427
2428 /*
2429  * Find out whether a specific function argument is constant for the
2430  * duration of a query
2431  *
2432  * Returns false if information is not available
2433  */
2434 bool
2435 get_fn_expr_arg_stable(FmgrInfo *flinfo, int argnum)
2436 {
2437         /*
2438          * can't return anything useful if we have no FmgrInfo or if its fn_expr
2439          * node has not been initialized
2440          */
2441         if (!flinfo || !flinfo->fn_expr)
2442                 return false;
2443
2444         return get_call_expr_arg_stable(flinfo->fn_expr, argnum);
2445 }
2446
2447 /*
2448  * Find out whether a specific function argument is constant for the
2449  * duration of a query, but working from the calling expression tree
2450  *
2451  * Returns false if information is not available
2452  */
2453 bool
2454 get_call_expr_arg_stable(Node *expr, int argnum)
2455 {
2456         List       *args;
2457         Node       *arg;
2458
2459         if (expr == NULL)
2460                 return false;
2461
2462         if (IsA(expr, FuncExpr))
2463                 args = ((FuncExpr *) expr)->args;
2464         else if (IsA(expr, OpExpr))
2465                 args = ((OpExpr *) expr)->args;
2466         else if (IsA(expr, DistinctExpr))
2467                 args = ((DistinctExpr *) expr)->args;
2468         else if (IsA(expr, ScalarArrayOpExpr))
2469                 args = ((ScalarArrayOpExpr *) expr)->args;
2470         else if (IsA(expr, ArrayCoerceExpr))
2471                 args = list_make1(((ArrayCoerceExpr *) expr)->arg);
2472         else if (IsA(expr, NullIfExpr))
2473                 args = ((NullIfExpr *) expr)->args;
2474         else if (IsA(expr, WindowFunc))
2475                 args = ((WindowFunc *) expr)->args;
2476         else
2477                 return false;
2478
2479         if (argnum < 0 || argnum >= list_length(args))
2480                 return false;
2481
2482         arg = (Node *) list_nth(args, argnum);
2483
2484         /*
2485          * Either a true Const or an external Param will have a value that doesn't
2486          * change during the execution of the query.  In future we might want to
2487          * consider other cases too, e.g. now().
2488          */
2489         if (IsA(arg, Const))
2490                 return true;
2491         if (IsA(arg, Param) &&
2492                 ((Param *) arg)->paramkind == PARAM_EXTERN)
2493                 return true;
2494
2495         return false;
2496 }