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