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