]> granicus.if.org Git - postgresql/blob - src/backend/executor/functions.c
893a54b21bb0d587bb4b975d0979c850d72bdb8a
[postgresql] / src / backend / executor / functions.c
1 /*-------------------------------------------------------------------------
2  *
3  * functions.c
4  *        Execution of SQL-language functions
5  *
6  * Portions Copyright (c) 1996-2013, PostgreSQL Global Development Group
7  * Portions Copyright (c) 1994, Regents of the University of California
8  *
9  *
10  * IDENTIFICATION
11  *        src/backend/executor/functions.c
12  *
13  *-------------------------------------------------------------------------
14  */
15 #include "postgres.h"
16
17 #include "access/htup_details.h"
18 #include "access/xact.h"
19 #include "catalog/pg_proc.h"
20 #include "catalog/pg_type.h"
21 #include "executor/functions.h"
22 #include "funcapi.h"
23 #include "miscadmin.h"
24 #include "nodes/makefuncs.h"
25 #include "nodes/nodeFuncs.h"
26 #include "parser/parse_coerce.h"
27 #include "parser/parse_func.h"
28 #include "storage/proc.h"
29 #include "tcop/utility.h"
30 #include "utils/builtins.h"
31 #include "utils/datum.h"
32 #include "utils/lsyscache.h"
33 #include "utils/memutils.h"
34 #include "utils/snapmgr.h"
35 #include "utils/syscache.h"
36
37
38 /*
39  * Specialized DestReceiver for collecting query output in a SQL function
40  */
41 typedef struct
42 {
43         DestReceiver pub;                       /* publicly-known function pointers */
44         Tuplestorestate *tstore;        /* where to put result tuples */
45         MemoryContext cxt;                      /* context containing tstore */
46         JunkFilter *filter;                     /* filter to convert tuple type */
47 } DR_sqlfunction;
48
49 /*
50  * We have an execution_state record for each query in a function.      Each
51  * record contains a plantree for its query.  If the query is currently in
52  * F_EXEC_RUN state then there's a QueryDesc too.
53  *
54  * The "next" fields chain together all the execution_state records generated
55  * from a single original parsetree.  (There will only be more than one in
56  * case of rule expansion of the original parsetree.)
57  */
58 typedef enum
59 {
60         F_EXEC_START, F_EXEC_RUN, F_EXEC_DONE
61 } ExecStatus;
62
63 typedef struct execution_state
64 {
65         struct execution_state *next;
66         ExecStatus      status;
67         bool            setsResult;             /* true if this query produces func's result */
68         bool            lazyEval;               /* true if should fetch one row at a time */
69         Node       *stmt;                       /* PlannedStmt or utility statement */
70         QueryDesc  *qd;                         /* null unless status == RUN */
71 } execution_state;
72
73
74 /*
75  * An SQLFunctionCache record is built during the first call,
76  * and linked to from the fn_extra field of the FmgrInfo struct.
77  *
78  * Note that currently this has only the lifespan of the calling query.
79  * Someday we should rewrite this code to use plancache.c to save parse/plan
80  * results for longer than that.
81  *
82  * Physically, though, the data has the lifespan of the FmgrInfo that's used
83  * to call the function, and there are cases (particularly with indexes)
84  * where the FmgrInfo might survive across transactions.  We cannot assume
85  * that the parse/plan trees are good for longer than the (sub)transaction in
86  * which parsing was done, so we must mark the record with the LXID/subxid of
87  * its creation time, and regenerate everything if that's obsolete.  To avoid
88  * memory leakage when we do have to regenerate things, all the data is kept
89  * in a sub-context of the FmgrInfo's fn_mcxt.
90  */
91 typedef struct
92 {
93         char       *fname;                      /* function name (for error msgs) */
94         char       *src;                        /* function body text (for error msgs) */
95
96         SQLFunctionParseInfoPtr pinfo;          /* data for parser callback hooks */
97
98         Oid                     rettype;                /* actual return type */
99         int16           typlen;                 /* length of the return type */
100         bool            typbyval;               /* true if return type is pass by value */
101         bool            returnsSet;             /* true if returning multiple rows */
102         bool            returnsTuple;   /* true if returning whole tuple result */
103         bool            shutdown_reg;   /* true if registered shutdown callback */
104         bool            readonly_func;  /* true to run in "read only" mode */
105         bool            lazyEval;               /* true if using lazyEval for result query */
106
107         ParamListInfo paramLI;          /* Param list representing current args */
108
109         Tuplestorestate *tstore;        /* where we accumulate result tuples */
110
111         JunkFilter *junkFilter;         /* will be NULL if function returns VOID */
112
113         /*
114          * func_state is a List of execution_state records, each of which is the
115          * first for its original parsetree, with any additional records chained
116          * to it via the "next" fields.  This sublist structure is needed to keep
117          * track of where the original query boundaries are.
118          */
119         List       *func_state;
120
121         MemoryContext fcontext;         /* memory context holding this struct and all
122                                                                  * subsidiary data */
123
124         LocalTransactionId lxid;        /* lxid in which cache was made */
125         SubTransactionId subxid;        /* subxid in which cache was made */
126 } SQLFunctionCache;
127
128 typedef SQLFunctionCache *SQLFunctionCachePtr;
129
130 /*
131  * Data structure needed by the parser callback hooks to resolve parameter
132  * references during parsing of a SQL function's body.  This is separate from
133  * SQLFunctionCache since we sometimes do parsing separately from execution.
134  */
135 typedef struct SQLFunctionParseInfo
136 {
137         char       *fname;                      /* function's name */
138         int                     nargs;                  /* number of input arguments */
139         Oid                *argtypes;           /* resolved types of input arguments */
140         char      **argnames;           /* names of input arguments; NULL if none */
141         /* Note that argnames[i] can be NULL, if some args are unnamed */
142         Oid                     collation;              /* function's input collation, if known */
143 }       SQLFunctionParseInfo;
144
145
146 /* non-export function prototypes */
147 static Node *sql_fn_param_ref(ParseState *pstate, ParamRef *pref);
148 static Node *sql_fn_post_column_ref(ParseState *pstate,
149                                            ColumnRef *cref, Node *var);
150 static Node *sql_fn_make_param(SQLFunctionParseInfoPtr pinfo,
151                                   int paramno, int location);
152 static Node *sql_fn_resolve_param_name(SQLFunctionParseInfoPtr pinfo,
153                                                   const char *paramname, int location);
154 static List *init_execution_state(List *queryTree_list,
155                                          SQLFunctionCachePtr fcache,
156                                          bool lazyEvalOK);
157 static void init_sql_fcache(FmgrInfo *finfo, Oid collation, bool lazyEvalOK);
158 static void postquel_start(execution_state *es, SQLFunctionCachePtr fcache);
159 static bool postquel_getnext(execution_state *es, SQLFunctionCachePtr fcache);
160 static void postquel_end(execution_state *es);
161 static void postquel_sub_params(SQLFunctionCachePtr fcache,
162                                         FunctionCallInfo fcinfo);
163 static Datum postquel_get_single_result(TupleTableSlot *slot,
164                                                    FunctionCallInfo fcinfo,
165                                                    SQLFunctionCachePtr fcache,
166                                                    MemoryContext resultcontext);
167 static void sql_exec_error_callback(void *arg);
168 static void ShutdownSQLFunction(Datum arg);
169 static void sqlfunction_startup(DestReceiver *self, int operation, TupleDesc typeinfo);
170 static void sqlfunction_receive(TupleTableSlot *slot, DestReceiver *self);
171 static void sqlfunction_shutdown(DestReceiver *self);
172 static void sqlfunction_destroy(DestReceiver *self);
173
174
175 /*
176  * Prepare the SQLFunctionParseInfo struct for parsing a SQL function body
177  *
178  * This includes resolving actual types of polymorphic arguments.
179  *
180  * call_expr can be passed as NULL, but then we will fail if there are any
181  * polymorphic arguments.
182  */
183 SQLFunctionParseInfoPtr
184 prepare_sql_fn_parse_info(HeapTuple procedureTuple,
185                                                   Node *call_expr,
186                                                   Oid inputCollation)
187 {
188         SQLFunctionParseInfoPtr pinfo;
189         Form_pg_proc procedureStruct = (Form_pg_proc) GETSTRUCT(procedureTuple);
190         int                     nargs;
191
192         pinfo = (SQLFunctionParseInfoPtr) palloc0(sizeof(SQLFunctionParseInfo));
193
194         /* Function's name (only) can be used to qualify argument names */
195         pinfo->fname = pstrdup(NameStr(procedureStruct->proname));
196
197         /* Save the function's input collation */
198         pinfo->collation = inputCollation;
199
200         /*
201          * Copy input argument types from the pg_proc entry, then resolve any
202          * polymorphic types.
203          */
204         pinfo->nargs = nargs = procedureStruct->pronargs;
205         if (nargs > 0)
206         {
207                 Oid                *argOidVect;
208                 int                     argnum;
209
210                 argOidVect = (Oid *) palloc(nargs * sizeof(Oid));
211                 memcpy(argOidVect,
212                            procedureStruct->proargtypes.values,
213                            nargs * sizeof(Oid));
214
215                 for (argnum = 0; argnum < nargs; argnum++)
216                 {
217                         Oid                     argtype = argOidVect[argnum];
218
219                         if (IsPolymorphicType(argtype))
220                         {
221                                 argtype = get_call_expr_argtype(call_expr, argnum);
222                                 if (argtype == InvalidOid)
223                                         ereport(ERROR,
224                                                         (errcode(ERRCODE_DATATYPE_MISMATCH),
225                                                          errmsg("could not determine actual type of argument declared %s",
226                                                                         format_type_be(argOidVect[argnum]))));
227                                 argOidVect[argnum] = argtype;
228                         }
229                 }
230
231                 pinfo->argtypes = argOidVect;
232         }
233
234         /*
235          * Collect names of arguments, too, if any
236          */
237         if (nargs > 0)
238         {
239                 Datum           proargnames;
240                 Datum           proargmodes;
241                 int                     n_arg_names;
242                 bool            isNull;
243
244                 proargnames = SysCacheGetAttr(PROCNAMEARGSNSP, procedureTuple,
245                                                                           Anum_pg_proc_proargnames,
246                                                                           &isNull);
247                 if (isNull)
248                         proargnames = PointerGetDatum(NULL);            /* just to be sure */
249
250                 proargmodes = SysCacheGetAttr(PROCNAMEARGSNSP, procedureTuple,
251                                                                           Anum_pg_proc_proargmodes,
252                                                                           &isNull);
253                 if (isNull)
254                         proargmodes = PointerGetDatum(NULL);            /* just to be sure */
255
256                 n_arg_names = get_func_input_arg_names(proargnames, proargmodes,
257                                                                                            &pinfo->argnames);
258
259                 /* Paranoia: ignore the result if too few array entries */
260                 if (n_arg_names < nargs)
261                         pinfo->argnames = NULL;
262         }
263         else
264                 pinfo->argnames = NULL;
265
266         return pinfo;
267 }
268
269 /*
270  * Parser setup hook for parsing a SQL function body.
271  */
272 void
273 sql_fn_parser_setup(struct ParseState *pstate, SQLFunctionParseInfoPtr pinfo)
274 {
275         pstate->p_pre_columnref_hook = NULL;
276         pstate->p_post_columnref_hook = sql_fn_post_column_ref;
277         pstate->p_paramref_hook = sql_fn_param_ref;
278         /* no need to use p_coerce_param_hook */
279         pstate->p_ref_hook_state = (void *) pinfo;
280 }
281
282 /*
283  * sql_fn_post_column_ref               parser callback for ColumnRefs
284  */
285 static Node *
286 sql_fn_post_column_ref(ParseState *pstate, ColumnRef *cref, Node *var)
287 {
288         SQLFunctionParseInfoPtr pinfo = (SQLFunctionParseInfoPtr) pstate->p_ref_hook_state;
289         int                     nnames;
290         Node       *field1;
291         Node       *subfield = NULL;
292         const char *name1;
293         const char *name2 = NULL;
294         Node       *param;
295
296         /*
297          * Never override a table-column reference.  This corresponds to
298          * considering the parameter names to appear in a scope outside the
299          * individual SQL commands, which is what we want.
300          */
301         if (var != NULL)
302                 return NULL;
303
304         /*----------
305          * The allowed syntaxes are:
306          *
307          * A            A = parameter name
308          * A.B          A = function name, B = parameter name
309          *                      OR: A = record-typed parameter name, B = field name
310          *                      (the first possibility takes precedence)
311          * A.B.C        A = function name, B = record-typed parameter name,
312          *                      C = field name
313          *----------
314          */
315         nnames = list_length(cref->fields);
316
317         if (nnames > 3)
318                 return NULL;
319
320         field1 = (Node *) linitial(cref->fields);
321         Assert(IsA(field1, String));
322         name1 = strVal(field1);
323         if (nnames > 1)
324         {
325                 subfield = (Node *) lsecond(cref->fields);
326                 Assert(IsA(subfield, String));
327                 name2 = strVal(subfield);
328         }
329
330         if (nnames == 3)
331         {
332                 /*
333                  * Three-part name: if the first part doesn't match the function name,
334                  * we can fail immediately. Otherwise, look up the second part, and
335                  * take the third part to be a field reference.
336                  */
337                 if (strcmp(name1, pinfo->fname) != 0)
338                         return NULL;
339
340                 param = sql_fn_resolve_param_name(pinfo, name2, cref->location);
341
342                 subfield = (Node *) lthird(cref->fields);
343                 Assert(IsA(subfield, String));
344         }
345         else if (nnames == 2 && strcmp(name1, pinfo->fname) == 0)
346         {
347                 /*
348                  * Two-part name with first part matching function name: first see if
349                  * second part matches any parameter name.
350                  */
351                 param = sql_fn_resolve_param_name(pinfo, name2, cref->location);
352
353                 if (param)
354                 {
355                         /* Yes, so this is a parameter reference, no subfield */
356                         subfield = NULL;
357                 }
358                 else
359                 {
360                         /* No, so try to match as parameter name and subfield */
361                         param = sql_fn_resolve_param_name(pinfo, name1, cref->location);
362                 }
363         }
364         else
365         {
366                 /* Single name, or parameter name followed by subfield */
367                 param = sql_fn_resolve_param_name(pinfo, name1, cref->location);
368         }
369
370         if (!param)
371                 return NULL;                    /* No match */
372
373         if (subfield)
374         {
375                 /*
376                  * Must be a reference to a field of a composite parameter; otherwise
377                  * ParseFuncOrColumn will return NULL, and we'll fail back at the
378                  * caller.
379                  */
380                 param = ParseFuncOrColumn(pstate,
381                                                                   list_make1(subfield),
382                                                                   list_make1(param),
383                                                                   NULL,
384                                                                   cref->location);
385         }
386
387         return param;
388 }
389
390 /*
391  * sql_fn_param_ref             parser callback for ParamRefs ($n symbols)
392  */
393 static Node *
394 sql_fn_param_ref(ParseState *pstate, ParamRef *pref)
395 {
396         SQLFunctionParseInfoPtr pinfo = (SQLFunctionParseInfoPtr) pstate->p_ref_hook_state;
397         int                     paramno = pref->number;
398
399         /* Check parameter number is valid */
400         if (paramno <= 0 || paramno > pinfo->nargs)
401                 return NULL;                    /* unknown parameter number */
402
403         return sql_fn_make_param(pinfo, paramno, pref->location);
404 }
405
406 /*
407  * sql_fn_make_param            construct a Param node for the given paramno
408  */
409 static Node *
410 sql_fn_make_param(SQLFunctionParseInfoPtr pinfo,
411                                   int paramno, int location)
412 {
413         Param      *param;
414
415         param = makeNode(Param);
416         param->paramkind = PARAM_EXTERN;
417         param->paramid = paramno;
418         param->paramtype = pinfo->argtypes[paramno - 1];
419         param->paramtypmod = -1;
420         param->paramcollid = get_typcollation(param->paramtype);
421         param->location = location;
422
423         /*
424          * If we have a function input collation, allow it to override the
425          * type-derived collation for parameter symbols.  (XXX perhaps this should
426          * not happen if the type collation is not default?)
427          */
428         if (OidIsValid(pinfo->collation) && OidIsValid(param->paramcollid))
429                 param->paramcollid = pinfo->collation;
430
431         return (Node *) param;
432 }
433
434 /*
435  * Search for a function parameter of the given name; if there is one,
436  * construct and return a Param node for it.  If not, return NULL.
437  * Helper function for sql_fn_post_column_ref.
438  */
439 static Node *
440 sql_fn_resolve_param_name(SQLFunctionParseInfoPtr pinfo,
441                                                   const char *paramname, int location)
442 {
443         int                     i;
444
445         if (pinfo->argnames == NULL)
446                 return NULL;
447
448         for (i = 0; i < pinfo->nargs; i++)
449         {
450                 if (pinfo->argnames[i] && strcmp(pinfo->argnames[i], paramname) == 0)
451                         return sql_fn_make_param(pinfo, i + 1, location);
452         }
453
454         return NULL;
455 }
456
457 /*
458  * Set up the per-query execution_state records for a SQL function.
459  *
460  * The input is a List of Lists of parsed and rewritten, but not planned,
461  * querytrees.  The sublist structure denotes the original query boundaries.
462  */
463 static List *
464 init_execution_state(List *queryTree_list,
465                                          SQLFunctionCachePtr fcache,
466                                          bool lazyEvalOK)
467 {
468         List       *eslist = NIL;
469         execution_state *lasttages = NULL;
470         ListCell   *lc1;
471
472         foreach(lc1, queryTree_list)
473         {
474                 List       *qtlist = (List *) lfirst(lc1);
475                 execution_state *firstes = NULL;
476                 execution_state *preves = NULL;
477                 ListCell   *lc2;
478
479                 foreach(lc2, qtlist)
480                 {
481                         Query      *queryTree = (Query *) lfirst(lc2);
482                         Node       *stmt;
483                         execution_state *newes;
484
485                         Assert(IsA(queryTree, Query));
486
487                         /* Plan the query if needed */
488                         if (queryTree->commandType == CMD_UTILITY)
489                                 stmt = queryTree->utilityStmt;
490                         else
491                                 stmt = (Node *) pg_plan_query(queryTree, 0, NULL);
492
493                         /* Precheck all commands for validity in a function */
494                         if (IsA(stmt, TransactionStmt))
495                                 ereport(ERROR,
496                                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
497                                 /* translator: %s is a SQL statement name */
498                                                  errmsg("%s is not allowed in a SQL function",
499                                                                 CreateCommandTag(stmt))));
500
501                         if (fcache->readonly_func && !CommandIsReadOnly(stmt))
502                                 ereport(ERROR,
503                                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
504                                 /* translator: %s is a SQL statement name */
505                                            errmsg("%s is not allowed in a non-volatile function",
506                                                           CreateCommandTag(stmt))));
507
508                         /* OK, build the execution_state for this query */
509                         newes = (execution_state *) palloc(sizeof(execution_state));
510                         if (preves)
511                                 preves->next = newes;
512                         else
513                                 firstes = newes;
514
515                         newes->next = NULL;
516                         newes->status = F_EXEC_START;
517                         newes->setsResult = false;      /* might change below */
518                         newes->lazyEval = false;        /* might change below */
519                         newes->stmt = stmt;
520                         newes->qd = NULL;
521
522                         if (queryTree->canSetTag)
523                                 lasttages = newes;
524
525                         preves = newes;
526                 }
527
528                 eslist = lappend(eslist, firstes);
529         }
530
531         /*
532          * Mark the last canSetTag query as delivering the function result; then,
533          * if it is a plain SELECT, mark it for lazy evaluation. If it's not a
534          * SELECT we must always run it to completion.
535          *
536          * Note: at some point we might add additional criteria for whether to use
537          * lazy eval.  However, we should prefer to use it whenever the function
538          * doesn't return set, since fetching more than one row is useless in that
539          * case.
540          *
541          * Note: don't set setsResult if the function returns VOID, as evidenced
542          * by not having made a junkfilter.  This ensures we'll throw away any
543          * output from a utility statement that check_sql_fn_retval deemed to not
544          * have output.
545          */
546         if (lasttages && fcache->junkFilter)
547         {
548                 lasttages->setsResult = true;
549                 if (lazyEvalOK &&
550                         IsA(lasttages->stmt, PlannedStmt))
551                 {
552                         PlannedStmt *ps = (PlannedStmt *) lasttages->stmt;
553
554                         if (ps->commandType == CMD_SELECT &&
555                                 ps->utilityStmt == NULL &&
556                                 !ps->hasModifyingCTE)
557                                 fcache->lazyEval = lasttages->lazyEval = true;
558                 }
559         }
560
561         return eslist;
562 }
563
564 /*
565  * Initialize the SQLFunctionCache for a SQL function
566  */
567 static void
568 init_sql_fcache(FmgrInfo *finfo, Oid collation, bool lazyEvalOK)
569 {
570         Oid                     foid = finfo->fn_oid;
571         MemoryContext fcontext;
572         MemoryContext oldcontext;
573         Oid                     rettype;
574         HeapTuple       procedureTuple;
575         Form_pg_proc procedureStruct;
576         SQLFunctionCachePtr fcache;
577         List       *raw_parsetree_list;
578         List       *queryTree_list;
579         List       *flat_query_list;
580         ListCell   *lc;
581         Datum           tmp;
582         bool            isNull;
583
584         /*
585          * Create memory context that holds all the SQLFunctionCache data.      It
586          * must be a child of whatever context holds the FmgrInfo.
587          */
588         fcontext = AllocSetContextCreate(finfo->fn_mcxt,
589                                                                          "SQL function data",
590                                                                          ALLOCSET_DEFAULT_MINSIZE,
591                                                                          ALLOCSET_DEFAULT_INITSIZE,
592                                                                          ALLOCSET_DEFAULT_MAXSIZE);
593
594         oldcontext = MemoryContextSwitchTo(fcontext);
595
596         /*
597          * Create the struct proper, link it to fcontext and fn_extra.  Once this
598          * is done, we'll be able to recover the memory after failure, even if the
599          * FmgrInfo is long-lived.
600          */
601         fcache = (SQLFunctionCachePtr) palloc0(sizeof(SQLFunctionCache));
602         fcache->fcontext = fcontext;
603         finfo->fn_extra = (void *) fcache;
604
605         /*
606          * get the procedure tuple corresponding to the given function Oid
607          */
608         procedureTuple = SearchSysCache1(PROCOID, ObjectIdGetDatum(foid));
609         if (!HeapTupleIsValid(procedureTuple))
610                 elog(ERROR, "cache lookup failed for function %u", foid);
611         procedureStruct = (Form_pg_proc) GETSTRUCT(procedureTuple);
612
613         /*
614          * copy function name immediately for use by error reporting callback
615          */
616         fcache->fname = pstrdup(NameStr(procedureStruct->proname));
617
618         /*
619          * get the result type from the procedure tuple, and check for polymorphic
620          * result type; if so, find out the actual result type.
621          */
622         rettype = procedureStruct->prorettype;
623
624         if (IsPolymorphicType(rettype))
625         {
626                 rettype = get_fn_expr_rettype(finfo);
627                 if (rettype == InvalidOid)              /* this probably should not happen */
628                         ereport(ERROR,
629                                         (errcode(ERRCODE_DATATYPE_MISMATCH),
630                                          errmsg("could not determine actual result type for function declared to return type %s",
631                                                         format_type_be(procedureStruct->prorettype))));
632         }
633
634         fcache->rettype = rettype;
635
636         /* Fetch the typlen and byval info for the result type */
637         get_typlenbyval(rettype, &fcache->typlen, &fcache->typbyval);
638
639         /* Remember whether we're returning setof something */
640         fcache->returnsSet = procedureStruct->proretset;
641
642         /* Remember if function is STABLE/IMMUTABLE */
643         fcache->readonly_func =
644                 (procedureStruct->provolatile != PROVOLATILE_VOLATILE);
645
646         /*
647          * We need the actual argument types to pass to the parser.  Also make
648          * sure that parameter symbols are considered to have the function's
649          * resolved input collation.
650          */
651         fcache->pinfo = prepare_sql_fn_parse_info(procedureTuple,
652                                                                                           finfo->fn_expr,
653                                                                                           collation);
654
655         /*
656          * And of course we need the function body text.
657          */
658         tmp = SysCacheGetAttr(PROCOID,
659                                                   procedureTuple,
660                                                   Anum_pg_proc_prosrc,
661                                                   &isNull);
662         if (isNull)
663                 elog(ERROR, "null prosrc for function %u", foid);
664         fcache->src = TextDatumGetCString(tmp);
665
666         /*
667          * Parse and rewrite the queries in the function text.  Use sublists to
668          * keep track of the original query boundaries.  But we also build a
669          * "flat" list of the rewritten queries to pass to check_sql_fn_retval.
670          * This is because the last canSetTag query determines the result type
671          * independently of query boundaries --- and it might not be in the last
672          * sublist, for example if the last query rewrites to DO INSTEAD NOTHING.
673          * (It might not be unreasonable to throw an error in such a case, but
674          * this is the historical behavior and it doesn't seem worth changing.)
675          *
676          * Note: since parsing and planning is done in fcontext, we will generate
677          * a lot of cruft that lives as long as the fcache does.  This is annoying
678          * but we'll not worry about it until the module is rewritten to use
679          * plancache.c.
680          */
681         raw_parsetree_list = pg_parse_query(fcache->src);
682
683         queryTree_list = NIL;
684         flat_query_list = NIL;
685         foreach(lc, raw_parsetree_list)
686         {
687                 Node       *parsetree = (Node *) lfirst(lc);
688                 List       *queryTree_sublist;
689
690                 queryTree_sublist = pg_analyze_and_rewrite_params(parsetree,
691                                                                                                                   fcache->src,
692                                                                            (ParserSetupHook) sql_fn_parser_setup,
693                                                                                                                   fcache->pinfo);
694                 queryTree_list = lappend(queryTree_list, queryTree_sublist);
695                 flat_query_list = list_concat(flat_query_list,
696                                                                           list_copy(queryTree_sublist));
697         }
698
699         /*
700          * Check that the function returns the type it claims to.  Although in
701          * simple cases this was already done when the function was defined, we
702          * have to recheck because database objects used in the function's queries
703          * might have changed type.  We'd have to do it anyway if the function had
704          * any polymorphic arguments.
705          *
706          * Note: we set fcache->returnsTuple according to whether we are returning
707          * the whole tuple result or just a single column.      In the latter case we
708          * clear returnsTuple because we need not act different from the scalar
709          * result case, even if it's a rowtype column.  (However, we have to force
710          * lazy eval mode in that case; otherwise we'd need extra code to expand
711          * the rowtype column into multiple columns, since we have no way to
712          * notify the caller that it should do that.)
713          *
714          * check_sql_fn_retval will also construct a JunkFilter we can use to
715          * coerce the returned rowtype to the desired form (unless the result type
716          * is VOID, in which case there's nothing to coerce to).
717          */
718         fcache->returnsTuple = check_sql_fn_retval(foid,
719                                                                                            rettype,
720                                                                                            flat_query_list,
721                                                                                            NULL,
722                                                                                            &fcache->junkFilter);
723
724         if (fcache->returnsTuple)
725         {
726                 /* Make sure output rowtype is properly blessed */
727                 BlessTupleDesc(fcache->junkFilter->jf_resultSlot->tts_tupleDescriptor);
728         }
729         else if (fcache->returnsSet && type_is_rowtype(fcache->rettype))
730         {
731                 /*
732                  * Returning rowtype as if it were scalar --- materialize won't work.
733                  * Right now it's sufficient to override any caller preference for
734                  * materialize mode, but to add more smarts in init_execution_state
735                  * about this, we'd probably need a three-way flag instead of bool.
736                  */
737                 lazyEvalOK = true;
738         }
739
740         /* Finally, plan the queries */
741         fcache->func_state = init_execution_state(queryTree_list,
742                                                                                           fcache,
743                                                                                           lazyEvalOK);
744
745         /* Mark fcache with time of creation to show it's valid */
746         fcache->lxid = MyProc->lxid;
747         fcache->subxid = GetCurrentSubTransactionId();
748
749         ReleaseSysCache(procedureTuple);
750
751         MemoryContextSwitchTo(oldcontext);
752 }
753
754 /* Start up execution of one execution_state node */
755 static void
756 postquel_start(execution_state *es, SQLFunctionCachePtr fcache)
757 {
758         DestReceiver *dest;
759
760         Assert(es->qd == NULL);
761
762         /* Caller should have ensured a suitable snapshot is active */
763         Assert(ActiveSnapshotSet());
764
765         /*
766          * If this query produces the function result, send its output to the
767          * tuplestore; else discard any output.
768          */
769         if (es->setsResult)
770         {
771                 DR_sqlfunction *myState;
772
773                 dest = CreateDestReceiver(DestSQLFunction);
774                 /* pass down the needed info to the dest receiver routines */
775                 myState = (DR_sqlfunction *) dest;
776                 Assert(myState->pub.mydest == DestSQLFunction);
777                 myState->tstore = fcache->tstore;
778                 myState->cxt = CurrentMemoryContext;
779                 myState->filter = fcache->junkFilter;
780         }
781         else
782                 dest = None_Receiver;
783
784         if (IsA(es->stmt, PlannedStmt))
785                 es->qd = CreateQueryDesc((PlannedStmt *) es->stmt,
786                                                                  fcache->src,
787                                                                  GetActiveSnapshot(),
788                                                                  InvalidSnapshot,
789                                                                  dest,
790                                                                  fcache->paramLI, 0);
791         else
792                 es->qd = CreateUtilityQueryDesc(es->stmt,
793                                                                                 fcache->src,
794                                                                                 GetActiveSnapshot(),
795                                                                                 dest,
796                                                                                 fcache->paramLI);
797
798         /* Utility commands don't need Executor. */
799         if (es->qd->utilitystmt == NULL)
800         {
801                 /*
802                  * In lazyEval mode, do not let the executor set up an AfterTrigger
803                  * context.  This is necessary not just an optimization, because we
804                  * mustn't exit from the function execution with a stacked
805                  * AfterTrigger level still active.  We are careful not to select
806                  * lazyEval mode for any statement that could possibly queue triggers.
807                  */
808                 int                     eflags;
809
810                 if (es->lazyEval)
811                         eflags = EXEC_FLAG_SKIP_TRIGGERS;
812                 else
813                         eflags = 0;                     /* default run-to-completion flags */
814                 ExecutorStart(es->qd, eflags);
815         }
816
817         es->status = F_EXEC_RUN;
818 }
819
820 /* Run one execution_state; either to completion or to first result row */
821 /* Returns true if we ran to completion */
822 static bool
823 postquel_getnext(execution_state *es, SQLFunctionCachePtr fcache)
824 {
825         bool            result;
826
827         if (es->qd->utilitystmt)
828         {
829                 /* ProcessUtility needs the PlannedStmt for DECLARE CURSOR */
830                 ProcessUtility((es->qd->plannedstmt ?
831                                                 (Node *) es->qd->plannedstmt :
832                                                 es->qd->utilitystmt),
833                                            fcache->src,
834                                            PROCESS_UTILITY_QUERY,
835                                            es->qd->params,
836                                            es->qd->dest,
837                                            NULL);
838                 result = true;                  /* never stops early */
839         }
840         else
841         {
842                 /* Run regular commands to completion unless lazyEval */
843                 long            count = (es->lazyEval) ? 1L : 0L;
844
845                 ExecutorRun(es->qd, ForwardScanDirection, count);
846
847                 /*
848                  * If we requested run to completion OR there was no tuple returned,
849                  * command must be complete.
850                  */
851                 result = (count == 0L || es->qd->estate->es_processed == 0);
852         }
853
854         return result;
855 }
856
857 /* Shut down execution of one execution_state node */
858 static void
859 postquel_end(execution_state *es)
860 {
861         /* mark status done to ensure we don't do ExecutorEnd twice */
862         es->status = F_EXEC_DONE;
863
864         /* Utility commands don't need Executor. */
865         if (es->qd->utilitystmt == NULL)
866         {
867                 ExecutorFinish(es->qd);
868                 ExecutorEnd(es->qd);
869         }
870
871         (*es->qd->dest->rDestroy) (es->qd->dest);
872
873         FreeQueryDesc(es->qd);
874         es->qd = NULL;
875 }
876
877 /* Build ParamListInfo array representing current arguments */
878 static void
879 postquel_sub_params(SQLFunctionCachePtr fcache,
880                                         FunctionCallInfo fcinfo)
881 {
882         int                     nargs = fcinfo->nargs;
883
884         if (nargs > 0)
885         {
886                 ParamListInfo paramLI;
887                 int                     i;
888
889                 if (fcache->paramLI == NULL)
890                 {
891                         /* sizeof(ParamListInfoData) includes the first array element */
892                         paramLI = (ParamListInfo) palloc(sizeof(ParamListInfoData) +
893                                                                           (nargs - 1) * sizeof(ParamExternData));
894                         /* we have static list of params, so no hooks needed */
895                         paramLI->paramFetch = NULL;
896                         paramLI->paramFetchArg = NULL;
897                         paramLI->parserSetup = NULL;
898                         paramLI->parserSetupArg = NULL;
899                         paramLI->numParams = nargs;
900                         fcache->paramLI = paramLI;
901                 }
902                 else
903                 {
904                         paramLI = fcache->paramLI;
905                         Assert(paramLI->numParams == nargs);
906                 }
907
908                 for (i = 0; i < nargs; i++)
909                 {
910                         ParamExternData *prm = &paramLI->params[i];
911
912                         prm->value = fcinfo->arg[i];
913                         prm->isnull = fcinfo->argnull[i];
914                         prm->pflags = 0;
915                         prm->ptype = fcache->pinfo->argtypes[i];
916                 }
917         }
918         else
919                 fcache->paramLI = NULL;
920 }
921
922 /*
923  * Extract the SQL function's value from a single result row.  This is used
924  * both for scalar (non-set) functions and for each row of a lazy-eval set
925  * result.
926  */
927 static Datum
928 postquel_get_single_result(TupleTableSlot *slot,
929                                                    FunctionCallInfo fcinfo,
930                                                    SQLFunctionCachePtr fcache,
931                                                    MemoryContext resultcontext)
932 {
933         Datum           value;
934         MemoryContext oldcontext;
935
936         /*
937          * Set up to return the function value.  For pass-by-reference datatypes,
938          * be sure to allocate the result in resultcontext, not the current memory
939          * context (which has query lifespan).  We can't leave the data in the
940          * TupleTableSlot because we intend to clear the slot before returning.
941          */
942         oldcontext = MemoryContextSwitchTo(resultcontext);
943
944         if (fcache->returnsTuple)
945         {
946                 /* We must return the whole tuple as a Datum. */
947                 fcinfo->isnull = false;
948                 value = ExecFetchSlotTupleDatum(slot);
949                 value = datumCopy(value, fcache->typbyval, fcache->typlen);
950         }
951         else
952         {
953                 /*
954                  * Returning a scalar, which we have to extract from the first column
955                  * of the SELECT result, and then copy into result context if needed.
956                  */
957                 value = slot_getattr(slot, 1, &(fcinfo->isnull));
958
959                 if (!fcinfo->isnull)
960                         value = datumCopy(value, fcache->typbyval, fcache->typlen);
961         }
962
963         MemoryContextSwitchTo(oldcontext);
964
965         return value;
966 }
967
968 /*
969  * fmgr_sql: function call manager for SQL functions
970  */
971 Datum
972 fmgr_sql(PG_FUNCTION_ARGS)
973 {
974         SQLFunctionCachePtr fcache;
975         ErrorContextCallback sqlerrcontext;
976         MemoryContext oldcontext;
977         bool            randomAccess;
978         bool            lazyEvalOK;
979         bool            is_first;
980         bool            pushed_snapshot;
981         execution_state *es;
982         TupleTableSlot *slot;
983         Datum           result;
984         List       *eslist;
985         ListCell   *eslc;
986
987         /*
988          * Setup error traceback support for ereport()
989          */
990         sqlerrcontext.callback = sql_exec_error_callback;
991         sqlerrcontext.arg = fcinfo->flinfo;
992         sqlerrcontext.previous = error_context_stack;
993         error_context_stack = &sqlerrcontext;
994
995         /* Check call context */
996         if (fcinfo->flinfo->fn_retset)
997         {
998                 ReturnSetInfo *rsi = (ReturnSetInfo *) fcinfo->resultinfo;
999
1000                 /*
1001                  * For simplicity, we require callers to support both set eval modes.
1002                  * There are cases where we must use one or must use the other, and
1003                  * it's not really worthwhile to postpone the check till we know. But
1004                  * note we do not require caller to provide an expectedDesc.
1005                  */
1006                 if (!rsi || !IsA(rsi, ReturnSetInfo) ||
1007                         (rsi->allowedModes & SFRM_ValuePerCall) == 0 ||
1008                         (rsi->allowedModes & SFRM_Materialize) == 0)
1009                         ereport(ERROR,
1010                                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1011                                          errmsg("set-valued function called in context that cannot accept a set")));
1012                 randomAccess = rsi->allowedModes & SFRM_Materialize_Random;
1013                 lazyEvalOK = !(rsi->allowedModes & SFRM_Materialize_Preferred);
1014         }
1015         else
1016         {
1017                 randomAccess = false;
1018                 lazyEvalOK = true;
1019         }
1020
1021         /*
1022          * Initialize fcache (build plans) if first time through; or re-initialize
1023          * if the cache is stale.
1024          */
1025         fcache = (SQLFunctionCachePtr) fcinfo->flinfo->fn_extra;
1026
1027         if (fcache != NULL)
1028         {
1029                 if (fcache->lxid != MyProc->lxid ||
1030                         !SubTransactionIsActive(fcache->subxid))
1031                 {
1032                         /* It's stale; unlink and delete */
1033                         fcinfo->flinfo->fn_extra = NULL;
1034                         MemoryContextDelete(fcache->fcontext);
1035                         fcache = NULL;
1036                 }
1037         }
1038
1039         if (fcache == NULL)
1040         {
1041                 init_sql_fcache(fcinfo->flinfo, PG_GET_COLLATION(), lazyEvalOK);
1042                 fcache = (SQLFunctionCachePtr) fcinfo->flinfo->fn_extra;
1043         }
1044
1045         /*
1046          * Switch to context in which the fcache lives.  This ensures that our
1047          * tuplestore etc will have sufficient lifetime.  The sub-executor is
1048          * responsible for deleting per-tuple information.      (XXX in the case of a
1049          * long-lived FmgrInfo, this policy represents more memory leakage, but
1050          * it's not entirely clear where to keep stuff instead.)
1051          */
1052         oldcontext = MemoryContextSwitchTo(fcache->fcontext);
1053
1054         /*
1055          * Find first unfinished query in function, and note whether it's the
1056          * first query.
1057          */
1058         eslist = fcache->func_state;
1059         es = NULL;
1060         is_first = true;
1061         foreach(eslc, eslist)
1062         {
1063                 es = (execution_state *) lfirst(eslc);
1064
1065                 while (es && es->status == F_EXEC_DONE)
1066                 {
1067                         is_first = false;
1068                         es = es->next;
1069                 }
1070
1071                 if (es)
1072                         break;
1073         }
1074
1075         /*
1076          * Convert params to appropriate format if starting a fresh execution. (If
1077          * continuing execution, we can re-use prior params.)
1078          */
1079         if (is_first && es && es->status == F_EXEC_START)
1080                 postquel_sub_params(fcache, fcinfo);
1081
1082         /*
1083          * Build tuplestore to hold results, if we don't have one already. Note
1084          * it's in the query-lifespan context.
1085          */
1086         if (!fcache->tstore)
1087                 fcache->tstore = tuplestore_begin_heap(randomAccess, false, work_mem);
1088
1089         /*
1090          * Execute each command in the function one after another until we either
1091          * run out of commands or get a result row from a lazily-evaluated SELECT.
1092          *
1093          * Notes about snapshot management:
1094          *
1095          * In a read-only function, we just use the surrounding query's snapshot.
1096          *
1097          * In a non-read-only function, we rely on the fact that we'll never
1098          * suspend execution between queries of the function: the only reason to
1099          * suspend execution before completion is if we are returning a row from a
1100          * lazily-evaluated SELECT.  So, when first entering this loop, we'll
1101          * either start a new query (and push a fresh snapshot) or re-establish
1102          * the active snapshot from the existing query descriptor.      If we need to
1103          * start a new query in a subsequent execution of the loop, either we need
1104          * a fresh snapshot (and pushed_snapshot is false) or the existing
1105          * snapshot is on the active stack and we can just bump its command ID.
1106          */
1107         pushed_snapshot = false;
1108         while (es)
1109         {
1110                 bool            completed;
1111
1112                 if (es->status == F_EXEC_START)
1113                 {
1114                         /*
1115                          * If not read-only, be sure to advance the command counter for
1116                          * each command, so that all work to date in this transaction is
1117                          * visible.  Take a new snapshot if we don't have one yet,
1118                          * otherwise just bump the command ID in the existing snapshot.
1119                          */
1120                         if (!fcache->readonly_func)
1121                         {
1122                                 CommandCounterIncrement();
1123                                 if (!pushed_snapshot)
1124                                 {
1125                                         PushActiveSnapshot(GetTransactionSnapshot());
1126                                         pushed_snapshot = true;
1127                                 }
1128                                 else
1129                                         UpdateActiveSnapshotCommandId();
1130                         }
1131
1132                         postquel_start(es, fcache);
1133                 }
1134                 else if (!fcache->readonly_func && !pushed_snapshot)
1135                 {
1136                         /* Re-establish active snapshot when re-entering function */
1137                         PushActiveSnapshot(es->qd->snapshot);
1138                         pushed_snapshot = true;
1139                 }
1140
1141                 completed = postquel_getnext(es, fcache);
1142
1143                 /*
1144                  * If we ran the command to completion, we can shut it down now. Any
1145                  * row(s) we need to return are safely stashed in the tuplestore, and
1146                  * we want to be sure that, for example, AFTER triggers get fired
1147                  * before we return anything.  Also, if the function doesn't return
1148                  * set, we can shut it down anyway because it must be a SELECT and we
1149                  * don't care about fetching any more result rows.
1150                  */
1151                 if (completed || !fcache->returnsSet)
1152                         postquel_end(es);
1153
1154                 /*
1155                  * Break from loop if we didn't shut down (implying we got a
1156                  * lazily-evaluated row).  Otherwise we'll press on till the whole
1157                  * function is done, relying on the tuplestore to keep hold of the
1158                  * data to eventually be returned.      This is necessary since an
1159                  * INSERT/UPDATE/DELETE RETURNING that sets the result might be
1160                  * followed by additional rule-inserted commands, and we want to
1161                  * finish doing all those commands before we return anything.
1162                  */
1163                 if (es->status != F_EXEC_DONE)
1164                         break;
1165
1166                 /*
1167                  * Advance to next execution_state, which might be in the next list.
1168                  */
1169                 es = es->next;
1170                 while (!es)
1171                 {
1172                         eslc = lnext(eslc);
1173                         if (!eslc)
1174                                 break;                  /* end of function */
1175
1176                         es = (execution_state *) lfirst(eslc);
1177
1178                         /*
1179                          * Flush the current snapshot so that we will take a new one for
1180                          * the new query list.  This ensures that new snaps are taken at
1181                          * original-query boundaries, matching the behavior of interactive
1182                          * execution.
1183                          */
1184                         if (pushed_snapshot)
1185                         {
1186                                 PopActiveSnapshot();
1187                                 pushed_snapshot = false;
1188                         }
1189                 }
1190         }
1191
1192         /*
1193          * The tuplestore now contains whatever row(s) we are supposed to return.
1194          */
1195         if (fcache->returnsSet)
1196         {
1197                 ReturnSetInfo *rsi = (ReturnSetInfo *) fcinfo->resultinfo;
1198
1199                 if (es)
1200                 {
1201                         /*
1202                          * If we stopped short of being done, we must have a lazy-eval
1203                          * row.
1204                          */
1205                         Assert(es->lazyEval);
1206                         /* Re-use the junkfilter's output slot to fetch back the tuple */
1207                         Assert(fcache->junkFilter);
1208                         slot = fcache->junkFilter->jf_resultSlot;
1209                         if (!tuplestore_gettupleslot(fcache->tstore, true, false, slot))
1210                                 elog(ERROR, "failed to fetch lazy-eval tuple");
1211                         /* Extract the result as a datum, and copy out from the slot */
1212                         result = postquel_get_single_result(slot, fcinfo,
1213                                                                                                 fcache, oldcontext);
1214                         /* Clear the tuplestore, but keep it for next time */
1215                         /* NB: this might delete the slot's content, but we don't care */
1216                         tuplestore_clear(fcache->tstore);
1217
1218                         /*
1219                          * Let caller know we're not finished.
1220                          */
1221                         rsi->isDone = ExprMultipleResult;
1222
1223                         /*
1224                          * Ensure we will get shut down cleanly if the exprcontext is not
1225                          * run to completion.
1226                          */
1227                         if (!fcache->shutdown_reg)
1228                         {
1229                                 RegisterExprContextCallback(rsi->econtext,
1230                                                                                         ShutdownSQLFunction,
1231                                                                                         PointerGetDatum(fcache));
1232                                 fcache->shutdown_reg = true;
1233                         }
1234                 }
1235                 else if (fcache->lazyEval)
1236                 {
1237                         /*
1238                          * We are done with a lazy evaluation.  Clean up.
1239                          */
1240                         tuplestore_clear(fcache->tstore);
1241
1242                         /*
1243                          * Let caller know we're finished.
1244                          */
1245                         rsi->isDone = ExprEndResult;
1246
1247                         fcinfo->isnull = true;
1248                         result = (Datum) 0;
1249
1250                         /* Deregister shutdown callback, if we made one */
1251                         if (fcache->shutdown_reg)
1252                         {
1253                                 UnregisterExprContextCallback(rsi->econtext,
1254                                                                                           ShutdownSQLFunction,
1255                                                                                           PointerGetDatum(fcache));
1256                                 fcache->shutdown_reg = false;
1257                         }
1258                 }
1259                 else
1260                 {
1261                         /*
1262                          * We are done with a non-lazy evaluation.      Return whatever is in
1263                          * the tuplestore.      (It is now caller's responsibility to free the
1264                          * tuplestore when done.)
1265                          */
1266                         rsi->returnMode = SFRM_Materialize;
1267                         rsi->setResult = fcache->tstore;
1268                         fcache->tstore = NULL;
1269                         /* must copy desc because execQual will free it */
1270                         if (fcache->junkFilter)
1271                                 rsi->setDesc = CreateTupleDescCopy(fcache->junkFilter->jf_cleanTupType);
1272
1273                         fcinfo->isnull = true;
1274                         result = (Datum) 0;
1275
1276                         /* Deregister shutdown callback, if we made one */
1277                         if (fcache->shutdown_reg)
1278                         {
1279                                 UnregisterExprContextCallback(rsi->econtext,
1280                                                                                           ShutdownSQLFunction,
1281                                                                                           PointerGetDatum(fcache));
1282                                 fcache->shutdown_reg = false;
1283                         }
1284                 }
1285         }
1286         else
1287         {
1288                 /*
1289                  * Non-set function.  If we got a row, return it; else return NULL.
1290                  */
1291                 if (fcache->junkFilter)
1292                 {
1293                         /* Re-use the junkfilter's output slot to fetch back the tuple */
1294                         slot = fcache->junkFilter->jf_resultSlot;
1295                         if (tuplestore_gettupleslot(fcache->tstore, true, false, slot))
1296                                 result = postquel_get_single_result(slot, fcinfo,
1297                                                                                                         fcache, oldcontext);
1298                         else
1299                         {
1300                                 fcinfo->isnull = true;
1301                                 result = (Datum) 0;
1302                         }
1303                 }
1304                 else
1305                 {
1306                         /* Should only get here for VOID functions */
1307                         Assert(fcache->rettype == VOIDOID);
1308                         fcinfo->isnull = true;
1309                         result = (Datum) 0;
1310                 }
1311
1312                 /* Clear the tuplestore, but keep it for next time */
1313                 tuplestore_clear(fcache->tstore);
1314         }
1315
1316         /* Pop snapshot if we have pushed one */
1317         if (pushed_snapshot)
1318                 PopActiveSnapshot();
1319
1320         /*
1321          * If we've gone through every command in the function, we are done. Reset
1322          * the execution states to start over again on next call.
1323          */
1324         if (es == NULL)
1325         {
1326                 foreach(eslc, fcache->func_state)
1327                 {
1328                         es = (execution_state *) lfirst(eslc);
1329                         while (es)
1330                         {
1331                                 es->status = F_EXEC_START;
1332                                 es = es->next;
1333                         }
1334                 }
1335         }
1336
1337         error_context_stack = sqlerrcontext.previous;
1338
1339         MemoryContextSwitchTo(oldcontext);
1340
1341         return result;
1342 }
1343
1344
1345 /*
1346  * error context callback to let us supply a call-stack traceback
1347  */
1348 static void
1349 sql_exec_error_callback(void *arg)
1350 {
1351         FmgrInfo   *flinfo = (FmgrInfo *) arg;
1352         SQLFunctionCachePtr fcache = (SQLFunctionCachePtr) flinfo->fn_extra;
1353         int                     syntaxerrposition;
1354
1355         /*
1356          * We can do nothing useful if init_sql_fcache() didn't get as far as
1357          * saving the function name
1358          */
1359         if (fcache == NULL || fcache->fname == NULL)
1360                 return;
1361
1362         /*
1363          * If there is a syntax error position, convert to internal syntax error
1364          */
1365         syntaxerrposition = geterrposition();
1366         if (syntaxerrposition > 0 && fcache->src != NULL)
1367         {
1368                 errposition(0);
1369                 internalerrposition(syntaxerrposition);
1370                 internalerrquery(fcache->src);
1371         }
1372
1373         /*
1374          * Try to determine where in the function we failed.  If there is a query
1375          * with non-null QueryDesc, finger it.  (We check this rather than looking
1376          * for F_EXEC_RUN state, so that errors during ExecutorStart or
1377          * ExecutorEnd are blamed on the appropriate query; see postquel_start and
1378          * postquel_end.)
1379          */
1380         if (fcache->func_state)
1381         {
1382                 execution_state *es;
1383                 int                     query_num;
1384                 ListCell   *lc;
1385
1386                 es = NULL;
1387                 query_num = 1;
1388                 foreach(lc, fcache->func_state)
1389                 {
1390                         es = (execution_state *) lfirst(lc);
1391                         while (es)
1392                         {
1393                                 if (es->qd)
1394                                 {
1395                                         errcontext("SQL function \"%s\" statement %d",
1396                                                            fcache->fname, query_num);
1397                                         break;
1398                                 }
1399                                 es = es->next;
1400                         }
1401                         if (es)
1402                                 break;
1403                         query_num++;
1404                 }
1405                 if (es == NULL)
1406                 {
1407                         /*
1408                          * couldn't identify a running query; might be function entry,
1409                          * function exit, or between queries.
1410                          */
1411                         errcontext("SQL function \"%s\"", fcache->fname);
1412                 }
1413         }
1414         else
1415         {
1416                 /*
1417                  * Assume we failed during init_sql_fcache().  (It's possible that the
1418                  * function actually has an empty body, but in that case we may as
1419                  * well report all errors as being "during startup".)
1420                  */
1421                 errcontext("SQL function \"%s\" during startup", fcache->fname);
1422         }
1423 }
1424
1425
1426 /*
1427  * callback function in case a function-returning-set needs to be shut down
1428  * before it has been run to completion
1429  */
1430 static void
1431 ShutdownSQLFunction(Datum arg)
1432 {
1433         SQLFunctionCachePtr fcache = (SQLFunctionCachePtr) DatumGetPointer(arg);
1434         execution_state *es;
1435         ListCell   *lc;
1436
1437         foreach(lc, fcache->func_state)
1438         {
1439                 es = (execution_state *) lfirst(lc);
1440                 while (es)
1441                 {
1442                         /* Shut down anything still running */
1443                         if (es->status == F_EXEC_RUN)
1444                         {
1445                                 /* Re-establish active snapshot for any called functions */
1446                                 if (!fcache->readonly_func)
1447                                         PushActiveSnapshot(es->qd->snapshot);
1448
1449                                 postquel_end(es);
1450
1451                                 if (!fcache->readonly_func)
1452                                         PopActiveSnapshot();
1453                         }
1454
1455                         /* Reset states to START in case we're called again */
1456                         es->status = F_EXEC_START;
1457                         es = es->next;
1458                 }
1459         }
1460
1461         /* Release tuplestore if we have one */
1462         if (fcache->tstore)
1463                 tuplestore_end(fcache->tstore);
1464         fcache->tstore = NULL;
1465
1466         /* execUtils will deregister the callback... */
1467         fcache->shutdown_reg = false;
1468 }
1469
1470
1471 /*
1472  * check_sql_fn_retval() -- check return value of a list of sql parse trees.
1473  *
1474  * The return value of a sql function is the value returned by the last
1475  * canSetTag query in the function.  We do some ad-hoc type checking here
1476  * to be sure that the user is returning the type he claims.  There are
1477  * also a couple of strange-looking features to assist callers in dealing
1478  * with allowed special cases, such as binary-compatible result types.
1479  *
1480  * For a polymorphic function the passed rettype must be the actual resolved
1481  * output type of the function; we should never see a polymorphic pseudotype
1482  * such as ANYELEMENT as rettype.  (This means we can't check the type during
1483  * function definition of a polymorphic function.)
1484  *
1485  * This function returns true if the sql function returns the entire tuple
1486  * result of its final statement, or false if it returns just the first column
1487  * result of that statement.  It throws an error if the final statement doesn't
1488  * return the right type at all.
1489  *
1490  * Note that because we allow "SELECT rowtype_expression", the result can be
1491  * false even when the declared function return type is a rowtype.
1492  *
1493  * If modifyTargetList isn't NULL, the function will modify the final
1494  * statement's targetlist in two cases:
1495  * (1) if the tlist returns values that are binary-coercible to the expected
1496  * type rather than being exactly the expected type.  RelabelType nodes will
1497  * be inserted to make the result types match exactly.
1498  * (2) if there are dropped columns in the declared result rowtype.  NULL
1499  * output columns will be inserted in the tlist to match them.
1500  * (Obviously the caller must pass a parsetree that is okay to modify when
1501  * using this flag.)  Note that this flag does not affect whether the tlist is
1502  * considered to be a legal match to the result type, only how we react to
1503  * allowed not-exact-match cases.  *modifyTargetList will be set true iff
1504  * we had to make any "dangerous" changes that could modify the semantics of
1505  * the statement.  If it is set true, the caller should not use the modified
1506  * statement, but for simplicity we apply the changes anyway.
1507  *
1508  * If junkFilter isn't NULL, then *junkFilter is set to a JunkFilter defined
1509  * to convert the function's tuple result to the correct output tuple type.
1510  * Exception: if the function is defined to return VOID then *junkFilter is
1511  * set to NULL.
1512  */
1513 bool
1514 check_sql_fn_retval(Oid func_id, Oid rettype, List *queryTreeList,
1515                                         bool *modifyTargetList,
1516                                         JunkFilter **junkFilter)
1517 {
1518         Query      *parse;
1519         List      **tlist_ptr;
1520         List       *tlist;
1521         int                     tlistlen;
1522         char            fn_typtype;
1523         Oid                     restype;
1524         ListCell   *lc;
1525
1526         AssertArg(!IsPolymorphicType(rettype));
1527
1528         if (modifyTargetList)
1529                 *modifyTargetList = false;              /* initialize for no change */
1530         if (junkFilter)
1531                 *junkFilter = NULL;             /* initialize in case of VOID result */
1532
1533         /*
1534          * Find the last canSetTag query in the list.  This isn't necessarily the
1535          * last parsetree, because rule rewriting can insert queries after what
1536          * the user wrote.
1537          */
1538         parse = NULL;
1539         foreach(lc, queryTreeList)
1540         {
1541                 Query      *q = (Query *) lfirst(lc);
1542
1543                 if (q->canSetTag)
1544                         parse = q;
1545         }
1546
1547         /*
1548          * If it's a plain SELECT, it returns whatever the targetlist says.
1549          * Otherwise, if it's INSERT/UPDATE/DELETE with RETURNING, it returns
1550          * that. Otherwise, the function return type must be VOID.
1551          *
1552          * Note: eventually replace this test with QueryReturnsTuples?  We'd need
1553          * a more general method of determining the output type, though.  Also, it
1554          * seems too dangerous to consider FETCH or EXECUTE as returning a
1555          * determinable rowtype, since they depend on relatively short-lived
1556          * entities.
1557          */
1558         if (parse &&
1559                 parse->commandType == CMD_SELECT &&
1560                 parse->utilityStmt == NULL)
1561         {
1562                 tlist_ptr = &parse->targetList;
1563                 tlist = parse->targetList;
1564         }
1565         else if (parse &&
1566                          (parse->commandType == CMD_INSERT ||
1567                           parse->commandType == CMD_UPDATE ||
1568                           parse->commandType == CMD_DELETE) &&
1569                          parse->returningList)
1570         {
1571                 tlist_ptr = &parse->returningList;
1572                 tlist = parse->returningList;
1573         }
1574         else
1575         {
1576                 /* Empty function body, or last statement is a utility command */
1577                 if (rettype != VOIDOID)
1578                         ereport(ERROR,
1579                                         (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
1580                          errmsg("return type mismatch in function declared to return %s",
1581                                         format_type_be(rettype)),
1582                                          errdetail("Function's final statement must be SELECT or INSERT/UPDATE/DELETE RETURNING.")));
1583                 return false;
1584         }
1585
1586         /*
1587          * OK, check that the targetlist returns something matching the declared
1588          * type.  (We used to insist that the declared type not be VOID in this
1589          * case, but that makes it hard to write a void function that exits after
1590          * calling another void function.  Instead, we insist that the tlist
1591          * return void ... so void is treated as if it were a scalar type below.)
1592          */
1593
1594         /*
1595          * Count the non-junk entries in the result targetlist.
1596          */
1597         tlistlen = ExecCleanTargetListLength(tlist);
1598
1599         fn_typtype = get_typtype(rettype);
1600
1601         if (fn_typtype == TYPTYPE_BASE ||
1602                 fn_typtype == TYPTYPE_DOMAIN ||
1603                 fn_typtype == TYPTYPE_ENUM ||
1604                 fn_typtype == TYPTYPE_RANGE ||
1605                 rettype == VOIDOID)
1606         {
1607                 /*
1608                  * For scalar-type returns, the target list must have exactly one
1609                  * non-junk entry, and its type must agree with what the user
1610                  * declared; except we allow binary-compatible types too.
1611                  */
1612                 TargetEntry *tle;
1613
1614                 if (tlistlen != 1)
1615                         ereport(ERROR,
1616                                         (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
1617                          errmsg("return type mismatch in function declared to return %s",
1618                                         format_type_be(rettype)),
1619                           errdetail("Final statement must return exactly one column.")));
1620
1621                 /* We assume here that non-junk TLEs must come first in tlists */
1622                 tle = (TargetEntry *) linitial(tlist);
1623                 Assert(!tle->resjunk);
1624
1625                 restype = exprType((Node *) tle->expr);
1626                 if (!IsBinaryCoercible(restype, rettype))
1627                         ereport(ERROR,
1628                                         (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
1629                          errmsg("return type mismatch in function declared to return %s",
1630                                         format_type_be(rettype)),
1631                                          errdetail("Actual return type is %s.",
1632                                                            format_type_be(restype))));
1633                 if (modifyTargetList && restype != rettype)
1634                 {
1635                         tle->expr = (Expr *) makeRelabelType(tle->expr,
1636                                                                                                  rettype,
1637                                                                                                  -1,
1638                                                                                                  get_typcollation(rettype),
1639                                                                                                  COERCE_IMPLICIT_CAST);
1640                         /* Relabel is dangerous if TLE is a sort/group or setop column */
1641                         if (tle->ressortgroupref != 0 || parse->setOperations)
1642                                 *modifyTargetList = true;
1643                 }
1644
1645                 /* Set up junk filter if needed */
1646                 if (junkFilter)
1647                         *junkFilter = ExecInitJunkFilter(tlist, false, NULL);
1648         }
1649         else if (fn_typtype == TYPTYPE_COMPOSITE || rettype == RECORDOID)
1650         {
1651                 /* Returns a rowtype */
1652                 TupleDesc       tupdesc;
1653                 int                     tupnatts;       /* physical number of columns in tuple */
1654                 int                     tuplogcols; /* # of nondeleted columns in tuple */
1655                 int                     colindex;       /* physical column index */
1656                 List       *newtlist;   /* new non-junk tlist entries */
1657                 List       *junkattrs;  /* new junk tlist entries */
1658
1659                 /*
1660                  * If the target list is of length 1, and the type of the varnode in
1661                  * the target list matches the declared return type, this is okay.
1662                  * This can happen, for example, where the body of the function is
1663                  * 'SELECT func2()', where func2 has the same composite return type as
1664                  * the function that's calling it.
1665                  *
1666                  * XXX Note that if rettype is RECORD, the IsBinaryCoercible check
1667                  * will succeed for any composite restype.      For the moment we rely on
1668                  * runtime type checking to catch any discrepancy, but it'd be nice to
1669                  * do better at parse time.
1670                  */
1671                 if (tlistlen == 1)
1672                 {
1673                         TargetEntry *tle = (TargetEntry *) linitial(tlist);
1674
1675                         Assert(!tle->resjunk);
1676                         restype = exprType((Node *) tle->expr);
1677                         if (IsBinaryCoercible(restype, rettype))
1678                         {
1679                                 if (modifyTargetList && restype != rettype)
1680                                 {
1681                                         tle->expr = (Expr *) makeRelabelType(tle->expr,
1682                                                                                                                  rettype,
1683                                                                                                                  -1,
1684                                                                                                    get_typcollation(rettype),
1685                                                                                                            COERCE_IMPLICIT_CAST);
1686                                         /* Relabel is dangerous if sort/group or setop column */
1687                                         if (tle->ressortgroupref != 0 || parse->setOperations)
1688                                                 *modifyTargetList = true;
1689                                 }
1690                                 /* Set up junk filter if needed */
1691                                 if (junkFilter)
1692                                         *junkFilter = ExecInitJunkFilter(tlist, false, NULL);
1693                                 return false;   /* NOT returning whole tuple */
1694                         }
1695                 }
1696
1697                 /* Is the rowtype fixed, or determined only at runtime? */
1698                 if (get_func_result_type(func_id, NULL, &tupdesc) != TYPEFUNC_COMPOSITE)
1699                 {
1700                         /*
1701                          * Assume we are returning the whole tuple. Crosschecking against
1702                          * what the caller expects will happen at runtime.
1703                          */
1704                         if (junkFilter)
1705                                 *junkFilter = ExecInitJunkFilter(tlist, false, NULL);
1706                         return true;
1707                 }
1708                 Assert(tupdesc);
1709
1710                 /*
1711                  * Verify that the targetlist matches the return tuple type. We scan
1712                  * the non-deleted attributes to ensure that they match the datatypes
1713                  * of the non-resjunk columns.  For deleted attributes, insert NULL
1714                  * result columns if the caller asked for that.
1715                  */
1716                 tupnatts = tupdesc->natts;
1717                 tuplogcols = 0;                 /* we'll count nondeleted cols as we go */
1718                 colindex = 0;
1719                 newtlist = NIL;                 /* these are only used if modifyTargetList */
1720                 junkattrs = NIL;
1721
1722                 foreach(lc, tlist)
1723                 {
1724                         TargetEntry *tle = (TargetEntry *) lfirst(lc);
1725                         Form_pg_attribute attr;
1726                         Oid                     tletype;
1727                         Oid                     atttype;
1728
1729                         if (tle->resjunk)
1730                         {
1731                                 if (modifyTargetList)
1732                                         junkattrs = lappend(junkattrs, tle);
1733                                 continue;
1734                         }
1735
1736                         do
1737                         {
1738                                 colindex++;
1739                                 if (colindex > tupnatts)
1740                                         ereport(ERROR,
1741                                                         (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
1742                                                          errmsg("return type mismatch in function declared to return %s",
1743                                                                         format_type_be(rettype)),
1744                                         errdetail("Final statement returns too many columns.")));
1745                                 attr = tupdesc->attrs[colindex - 1];
1746                                 if (attr->attisdropped && modifyTargetList)
1747                                 {
1748                                         Expr       *null_expr;
1749
1750                                         /* The type of the null we insert isn't important */
1751                                         null_expr = (Expr *) makeConst(INT4OID,
1752                                                                                                    -1,
1753                                                                                                    InvalidOid,
1754                                                                                                    sizeof(int32),
1755                                                                                                    (Datum) 0,
1756                                                                                                    true,                /* isnull */
1757                                                                                                    true /* byval */ );
1758                                         newtlist = lappend(newtlist,
1759                                                                            makeTargetEntry(null_expr,
1760                                                                                                            colindex,
1761                                                                                                            NULL,
1762                                                                                                            false));
1763                                         /* NULL insertion is dangerous in a setop */
1764                                         if (parse->setOperations)
1765                                                 *modifyTargetList = true;
1766                                 }
1767                         } while (attr->attisdropped);
1768                         tuplogcols++;
1769
1770                         tletype = exprType((Node *) tle->expr);
1771                         atttype = attr->atttypid;
1772                         if (!IsBinaryCoercible(tletype, atttype))
1773                                 ereport(ERROR,
1774                                                 (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
1775                                                  errmsg("return type mismatch in function declared to return %s",
1776                                                                 format_type_be(rettype)),
1777                                                  errdetail("Final statement returns %s instead of %s at column %d.",
1778                                                                    format_type_be(tletype),
1779                                                                    format_type_be(atttype),
1780                                                                    tuplogcols)));
1781                         if (modifyTargetList)
1782                         {
1783                                 if (tletype != atttype)
1784                                 {
1785                                         tle->expr = (Expr *) makeRelabelType(tle->expr,
1786                                                                                                                  atttype,
1787                                                                                                                  -1,
1788                                                                                                    get_typcollation(atttype),
1789                                                                                                            COERCE_IMPLICIT_CAST);
1790                                         /* Relabel is dangerous if sort/group or setop column */
1791                                         if (tle->ressortgroupref != 0 || parse->setOperations)
1792                                                 *modifyTargetList = true;
1793                                 }
1794                                 tle->resno = colindex;
1795                                 newtlist = lappend(newtlist, tle);
1796                         }
1797                 }
1798
1799                 /* remaining columns in tupdesc had better all be dropped */
1800                 for (colindex++; colindex <= tupnatts; colindex++)
1801                 {
1802                         if (!tupdesc->attrs[colindex - 1]->attisdropped)
1803                                 ereport(ERROR,
1804                                                 (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
1805                                                  errmsg("return type mismatch in function declared to return %s",
1806                                                                 format_type_be(rettype)),
1807                                          errdetail("Final statement returns too few columns.")));
1808                         if (modifyTargetList)
1809                         {
1810                                 Expr       *null_expr;
1811
1812                                 /* The type of the null we insert isn't important */
1813                                 null_expr = (Expr *) makeConst(INT4OID,
1814                                                                                            -1,
1815                                                                                            InvalidOid,
1816                                                                                            sizeof(int32),
1817                                                                                            (Datum) 0,
1818                                                                                            true,        /* isnull */
1819                                                                                            true /* byval */ );
1820                                 newtlist = lappend(newtlist,
1821                                                                    makeTargetEntry(null_expr,
1822                                                                                                    colindex,
1823                                                                                                    NULL,
1824                                                                                                    false));
1825                                 /* NULL insertion is dangerous in a setop */
1826                                 if (parse->setOperations)
1827                                         *modifyTargetList = true;
1828                         }
1829                 }
1830
1831                 if (modifyTargetList)
1832                 {
1833                         /* ensure resjunk columns are numbered correctly */
1834                         foreach(lc, junkattrs)
1835                         {
1836                                 TargetEntry *tle = (TargetEntry *) lfirst(lc);
1837
1838                                 tle->resno = colindex++;
1839                         }
1840                         /* replace the tlist with the modified one */
1841                         *tlist_ptr = list_concat(newtlist, junkattrs);
1842                 }
1843
1844                 /* Set up junk filter if needed */
1845                 if (junkFilter)
1846                         *junkFilter = ExecInitJunkFilterConversion(tlist,
1847                                                                                                 CreateTupleDescCopy(tupdesc),
1848                                                                                                            NULL);
1849
1850                 /* Report that we are returning entire tuple result */
1851                 return true;
1852         }
1853         else
1854                 ereport(ERROR,
1855                                 (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
1856                                  errmsg("return type %s is not supported for SQL functions",
1857                                                 format_type_be(rettype))));
1858
1859         return false;
1860 }
1861
1862
1863 /*
1864  * CreateSQLFunctionDestReceiver -- create a suitable DestReceiver object
1865  */
1866 DestReceiver *
1867 CreateSQLFunctionDestReceiver(void)
1868 {
1869         DR_sqlfunction *self = (DR_sqlfunction *) palloc0(sizeof(DR_sqlfunction));
1870
1871         self->pub.receiveSlot = sqlfunction_receive;
1872         self->pub.rStartup = sqlfunction_startup;
1873         self->pub.rShutdown = sqlfunction_shutdown;
1874         self->pub.rDestroy = sqlfunction_destroy;
1875         self->pub.mydest = DestSQLFunction;
1876
1877         /* private fields will be set by postquel_start */
1878
1879         return (DestReceiver *) self;
1880 }
1881
1882 /*
1883  * sqlfunction_startup --- executor startup
1884  */
1885 static void
1886 sqlfunction_startup(DestReceiver *self, int operation, TupleDesc typeinfo)
1887 {
1888         /* no-op */
1889 }
1890
1891 /*
1892  * sqlfunction_receive --- receive one tuple
1893  */
1894 static void
1895 sqlfunction_receive(TupleTableSlot *slot, DestReceiver *self)
1896 {
1897         DR_sqlfunction *myState = (DR_sqlfunction *) self;
1898
1899         /* Filter tuple as needed */
1900         slot = ExecFilterJunk(myState->filter, slot);
1901
1902         /* Store the filtered tuple into the tuplestore */
1903         tuplestore_puttupleslot(myState->tstore, slot);
1904 }
1905
1906 /*
1907  * sqlfunction_shutdown --- executor end
1908  */
1909 static void
1910 sqlfunction_shutdown(DestReceiver *self)
1911 {
1912         /* no-op */
1913 }
1914
1915 /*
1916  * sqlfunction_destroy --- release DestReceiver object
1917  */
1918 static void
1919 sqlfunction_destroy(DestReceiver *self)
1920 {
1921         pfree(self);
1922 }