]> granicus.if.org Git - postgresql/blob - src/backend/executor/functions.c
498bcba5816e4b24a07025392a68fb3872110951
[postgresql] / src / backend / executor / functions.c
1 /*-------------------------------------------------------------------------
2  *
3  * functions.c
4  *        Execution of SQL-language functions
5  *
6  * Portions Copyright (c) 1996-2010, 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/xact.h"
18 #include "catalog/pg_proc.h"
19 #include "catalog/pg_type.h"
20 #include "commands/trigger.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 "tcop/utility.h"
28 #include "utils/builtins.h"
29 #include "utils/datum.h"
30 #include "utils/lsyscache.h"
31 #include "utils/snapmgr.h"
32 #include "utils/syscache.h"
33
34
35 /*
36  * Specialized DestReceiver for collecting query output in a SQL function
37  */
38 typedef struct
39 {
40         DestReceiver pub;                       /* publicly-known function pointers */
41         Tuplestorestate *tstore;        /* where to put result tuples */
42         MemoryContext cxt;                      /* context containing tstore */
43         JunkFilter *filter;                     /* filter to convert tuple type */
44 } DR_sqlfunction;
45
46 /*
47  * We have an execution_state record for each query in a function.      Each
48  * record contains a plantree for its query.  If the query is currently in
49  * F_EXEC_RUN state then there's a QueryDesc too.
50  */
51 typedef enum
52 {
53         F_EXEC_START, F_EXEC_RUN, F_EXEC_DONE
54 } ExecStatus;
55
56 typedef struct execution_state
57 {
58         struct execution_state *next;
59         ExecStatus      status;
60         bool            setsResult;             /* true if this query produces func's result */
61         bool            lazyEval;               /* true if should fetch one row at a time */
62         Node       *stmt;                       /* PlannedStmt or utility statement */
63         QueryDesc  *qd;                         /* null unless status == RUN */
64 } execution_state;
65
66
67 /*
68  * An SQLFunctionCache record is built during the first call,
69  * and linked to from the fn_extra field of the FmgrInfo struct.
70  *
71  * Note that currently this has only the lifespan of the calling query.
72  * Someday we might want to consider caching the parse/plan results longer
73  * than that.
74  */
75 typedef struct
76 {
77         char       *fname;                      /* function name (for error msgs) */
78         char       *src;                        /* function body text (for error msgs) */
79
80         Oid                *argtypes;           /* resolved types of arguments */
81         Oid                     rettype;                /* actual return type */
82         int16           typlen;                 /* length of the return type */
83         bool            typbyval;               /* true if return type is pass by value */
84         bool            returnsSet;             /* true if returning multiple rows */
85         bool            returnsTuple;   /* true if returning whole tuple result */
86         bool            shutdown_reg;   /* true if registered shutdown callback */
87         bool            readonly_func;  /* true to run in "read only" mode */
88         bool            lazyEval;               /* true if using lazyEval for result query */
89
90         ParamListInfo paramLI;          /* Param list representing current args */
91
92         Tuplestorestate *tstore;        /* where we accumulate result tuples */
93
94         JunkFilter *junkFilter;         /* will be NULL if function returns VOID */
95
96         /* head of linked list of execution_state records */
97         execution_state *func_state;
98 } SQLFunctionCache;
99
100 typedef SQLFunctionCache *SQLFunctionCachePtr;
101
102
103 /* non-export function prototypes */
104 static execution_state *init_execution_state(List *queryTree_list,
105                                          SQLFunctionCachePtr fcache,
106                                          bool lazyEvalOK);
107 static void init_sql_fcache(FmgrInfo *finfo, bool lazyEvalOK);
108 static void postquel_start(execution_state *es, SQLFunctionCachePtr fcache);
109 static bool postquel_getnext(execution_state *es, SQLFunctionCachePtr fcache);
110 static void postquel_end(execution_state *es);
111 static void postquel_sub_params(SQLFunctionCachePtr fcache,
112                                         FunctionCallInfo fcinfo);
113 static Datum postquel_get_single_result(TupleTableSlot *slot,
114                                                    FunctionCallInfo fcinfo,
115                                                    SQLFunctionCachePtr fcache,
116                                                    MemoryContext resultcontext);
117 static void sql_exec_error_callback(void *arg);
118 static void ShutdownSQLFunction(Datum arg);
119 static void sqlfunction_startup(DestReceiver *self, int operation, TupleDesc typeinfo);
120 static void sqlfunction_receive(TupleTableSlot *slot, DestReceiver *self);
121 static void sqlfunction_shutdown(DestReceiver *self);
122 static void sqlfunction_destroy(DestReceiver *self);
123
124
125 /* Set up the list of per-query execution_state records for a SQL function */
126 static execution_state *
127 init_execution_state(List *queryTree_list,
128                                          SQLFunctionCachePtr fcache,
129                                          bool lazyEvalOK)
130 {
131         execution_state *firstes = NULL;
132         execution_state *preves = NULL;
133         execution_state *lasttages = NULL;
134         ListCell   *qtl_item;
135
136         foreach(qtl_item, queryTree_list)
137         {
138                 Query      *queryTree = (Query *) lfirst(qtl_item);
139                 Node       *stmt;
140                 execution_state *newes;
141
142                 Assert(IsA(queryTree, Query));
143
144                 if (queryTree->commandType == CMD_UTILITY)
145                         stmt = queryTree->utilityStmt;
146                 else
147                         stmt = (Node *) pg_plan_query(queryTree, 0, NULL);
148
149                 /* Precheck all commands for validity in a function */
150                 if (IsA(stmt, TransactionStmt))
151                         ereport(ERROR,
152                                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
153                         /* translator: %s is a SQL statement name */
154                                          errmsg("%s is not allowed in a SQL function",
155                                                         CreateCommandTag(stmt))));
156
157                 if (fcache->readonly_func && !CommandIsReadOnly(stmt))
158                         ereport(ERROR,
159                                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
160                         /* translator: %s is a SQL statement name */
161                                          errmsg("%s is not allowed in a non-volatile function",
162                                                         CreateCommandTag(stmt))));
163
164                 newes = (execution_state *) palloc(sizeof(execution_state));
165                 if (preves)
166                         preves->next = newes;
167                 else
168                         firstes = newes;
169
170                 newes->next = NULL;
171                 newes->status = F_EXEC_START;
172                 newes->setsResult = false;              /* might change below */
173                 newes->lazyEval = false;        /* might change below */
174                 newes->stmt = stmt;
175                 newes->qd = NULL;
176
177                 if (queryTree->canSetTag)
178                         lasttages = newes;
179
180                 preves = newes;
181         }
182
183         /*
184          * Mark the last canSetTag query as delivering the function result; then,
185          * if it is a plain SELECT, mark it for lazy evaluation. If it's not a
186          * SELECT we must always run it to completion.
187          *
188          * Note: at some point we might add additional criteria for whether to use
189          * lazy eval.  However, we should prefer to use it whenever the function
190          * doesn't return set, since fetching more than one row is useless in that
191          * case.
192          *
193          * Note: don't set setsResult if the function returns VOID, as evidenced
194          * by not having made a junkfilter.  This ensures we'll throw away any
195          * output from a utility statement that check_sql_fn_retval deemed to not
196          * have output.
197          */
198         if (lasttages && fcache->junkFilter)
199         {
200                 lasttages->setsResult = true;
201                 if (lazyEvalOK &&
202                         IsA(lasttages->stmt, PlannedStmt))
203                 {
204                         PlannedStmt *ps = (PlannedStmt *) lasttages->stmt;
205
206                         if (ps->commandType == CMD_SELECT &&
207                                 ps->utilityStmt == NULL &&
208                                 ps->intoClause == NULL)
209                                 fcache->lazyEval = lasttages->lazyEval = true;
210                 }
211         }
212
213         return firstes;
214 }
215
216 /* Initialize the SQLFunctionCache for a SQL function */
217 static void
218 init_sql_fcache(FmgrInfo *finfo, bool lazyEvalOK)
219 {
220         Oid                     foid = finfo->fn_oid;
221         Oid                     rettype;
222         HeapTuple       procedureTuple;
223         Form_pg_proc procedureStruct;
224         SQLFunctionCachePtr fcache;
225         Oid                *argOidVect;
226         int                     nargs;
227         List       *queryTree_list;
228         Datum           tmp;
229         bool            isNull;
230
231         fcache = (SQLFunctionCachePtr) palloc0(sizeof(SQLFunctionCache));
232         finfo->fn_extra = (void *) fcache;
233
234         /*
235          * get the procedure tuple corresponding to the given function Oid
236          */
237         procedureTuple = SearchSysCache1(PROCOID, ObjectIdGetDatum(foid));
238         if (!HeapTupleIsValid(procedureTuple))
239                 elog(ERROR, "cache lookup failed for function %u", foid);
240         procedureStruct = (Form_pg_proc) GETSTRUCT(procedureTuple);
241
242         /*
243          * copy function name immediately for use by error reporting callback
244          */
245         fcache->fname = pstrdup(NameStr(procedureStruct->proname));
246
247         /*
248          * get the result type from the procedure tuple, and check for polymorphic
249          * result type; if so, find out the actual result type.
250          */
251         rettype = procedureStruct->prorettype;
252
253         if (IsPolymorphicType(rettype))
254         {
255                 rettype = get_fn_expr_rettype(finfo);
256                 if (rettype == InvalidOid)              /* this probably should not happen */
257                         ereport(ERROR,
258                                         (errcode(ERRCODE_DATATYPE_MISMATCH),
259                                          errmsg("could not determine actual result type for function declared to return type %s",
260                                                         format_type_be(procedureStruct->prorettype))));
261         }
262
263         fcache->rettype = rettype;
264
265         /* Fetch the typlen and byval info for the result type */
266         get_typlenbyval(rettype, &fcache->typlen, &fcache->typbyval);
267
268         /* Remember whether we're returning setof something */
269         fcache->returnsSet = procedureStruct->proretset;
270
271         /* Remember if function is STABLE/IMMUTABLE */
272         fcache->readonly_func =
273                 (procedureStruct->provolatile != PROVOLATILE_VOLATILE);
274
275         /*
276          * We need the actual argument types to pass to the parser.
277          */
278         nargs = procedureStruct->pronargs;
279         if (nargs > 0)
280         {
281                 int                     argnum;
282
283                 argOidVect = (Oid *) palloc(nargs * sizeof(Oid));
284                 memcpy(argOidVect,
285                            procedureStruct->proargtypes.values,
286                            nargs * sizeof(Oid));
287                 /* Resolve any polymorphic argument types */
288                 for (argnum = 0; argnum < nargs; argnum++)
289                 {
290                         Oid                     argtype = argOidVect[argnum];
291
292                         if (IsPolymorphicType(argtype))
293                         {
294                                 argtype = get_fn_expr_argtype(finfo, argnum);
295                                 if (argtype == InvalidOid)
296                                         ereport(ERROR,
297                                                         (errcode(ERRCODE_DATATYPE_MISMATCH),
298                                                          errmsg("could not determine actual type of argument declared %s",
299                                                                         format_type_be(argOidVect[argnum]))));
300                                 argOidVect[argnum] = argtype;
301                         }
302                 }
303         }
304         else
305                 argOidVect = NULL;
306         fcache->argtypes = argOidVect;
307
308         /*
309          * And of course we need the function body text.
310          */
311         tmp = SysCacheGetAttr(PROCOID,
312                                                   procedureTuple,
313                                                   Anum_pg_proc_prosrc,
314                                                   &isNull);
315         if (isNull)
316                 elog(ERROR, "null prosrc for function %u", foid);
317         fcache->src = TextDatumGetCString(tmp);
318
319         /*
320          * Parse and rewrite the queries in the function text.
321          */
322         queryTree_list = pg_parse_and_rewrite(fcache->src, argOidVect, nargs);
323
324         /*
325          * Check that the function returns the type it claims to.  Although in
326          * simple cases this was already done when the function was defined, we
327          * have to recheck because database objects used in the function's queries
328          * might have changed type.  We'd have to do it anyway if the function had
329          * any polymorphic arguments.
330          *
331          * Note: we set fcache->returnsTuple according to whether we are returning
332          * the whole tuple result or just a single column.      In the latter case we
333          * clear returnsTuple because we need not act different from the scalar
334          * result case, even if it's a rowtype column.  (However, we have to force
335          * lazy eval mode in that case; otherwise we'd need extra code to expand
336          * the rowtype column into multiple columns, since we have no way to
337          * notify the caller that it should do that.)
338          *
339          * check_sql_fn_retval will also construct a JunkFilter we can use to
340          * coerce the returned rowtype to the desired form (unless the result type
341          * is VOID, in which case there's nothing to coerce to).
342          */
343         fcache->returnsTuple = check_sql_fn_retval(foid,
344                                                                                            rettype,
345                                                                                            queryTree_list,
346                                                                                            NULL,
347                                                                                            &fcache->junkFilter);
348
349         if (fcache->returnsTuple)
350         {
351                 /* Make sure output rowtype is properly blessed */
352                 BlessTupleDesc(fcache->junkFilter->jf_resultSlot->tts_tupleDescriptor);
353         }
354         else if (fcache->returnsSet && type_is_rowtype(fcache->rettype))
355         {
356                 /*
357                  * Returning rowtype as if it were scalar --- materialize won't work.
358                  * Right now it's sufficient to override any caller preference for
359                  * materialize mode, but to add more smarts in init_execution_state
360                  * about this, we'd probably need a three-way flag instead of bool.
361                  */
362                 lazyEvalOK = true;
363         }
364
365         /* Finally, plan the queries */
366         fcache->func_state = init_execution_state(queryTree_list,
367                                                                                           fcache,
368                                                                                           lazyEvalOK);
369
370         ReleaseSysCache(procedureTuple);
371 }
372
373 /* Start up execution of one execution_state node */
374 static void
375 postquel_start(execution_state *es, SQLFunctionCachePtr fcache)
376 {
377         Snapshot        snapshot;
378         DestReceiver *dest;
379
380         Assert(es->qd == NULL);
381
382         /*
383          * In a read-only function, use the surrounding query's snapshot;
384          * otherwise take a new snapshot for each query.  The snapshot should
385          * include a fresh command ID so that all work to date in this transaction
386          * is visible.
387          */
388         if (fcache->readonly_func)
389                 snapshot = GetActiveSnapshot();
390         else
391         {
392                 CommandCounterIncrement();
393                 snapshot = GetTransactionSnapshot();
394         }
395
396         /*
397          * If this query produces the function result, send its output to the
398          * tuplestore; else discard any output.
399          */
400         if (es->setsResult)
401         {
402                 DR_sqlfunction *myState;
403
404                 dest = CreateDestReceiver(DestSQLFunction);
405                 /* pass down the needed info to the dest receiver routines */
406                 myState = (DR_sqlfunction *) dest;
407                 Assert(myState->pub.mydest == DestSQLFunction);
408                 myState->tstore = fcache->tstore;
409                 myState->cxt = CurrentMemoryContext;
410                 myState->filter = fcache->junkFilter;
411         }
412         else
413                 dest = None_Receiver;
414
415         if (IsA(es->stmt, PlannedStmt))
416                 es->qd = CreateQueryDesc((PlannedStmt *) es->stmt,
417                                                                  fcache->src,
418                                                                  snapshot, InvalidSnapshot,
419                                                                  dest,
420                                                                  fcache->paramLI, 0);
421         else
422                 es->qd = CreateUtilityQueryDesc(es->stmt,
423                                                                                 fcache->src,
424                                                                                 snapshot,
425                                                                                 dest,
426                                                                                 fcache->paramLI);
427
428         /* We assume we don't need to set up ActiveSnapshot for ExecutorStart */
429
430         /* Utility commands don't need Executor. */
431         if (es->qd->utilitystmt == NULL)
432         {
433                 /*
434                  * Only set up to collect queued triggers if it's not a SELECT. This
435                  * isn't just an optimization, but is necessary in case a SELECT
436                  * returns multiple rows to caller --- we mustn't exit from the
437                  * function execution with a stacked AfterTrigger level still active.
438                  */
439                 if (es->qd->operation != CMD_SELECT)
440                         AfterTriggerBeginQuery();
441                 ExecutorStart(es->qd, 0);
442         }
443
444         es->status = F_EXEC_RUN;
445 }
446
447 /* Run one execution_state; either to completion or to first result row */
448 /* Returns true if we ran to completion */
449 static bool
450 postquel_getnext(execution_state *es, SQLFunctionCachePtr fcache)
451 {
452         bool            result;
453
454         /* Make our snapshot the active one for any called functions */
455         PushActiveSnapshot(es->qd->snapshot);
456
457         if (es->qd->utilitystmt)
458         {
459                 /* ProcessUtility needs the PlannedStmt for DECLARE CURSOR */
460                 ProcessUtility((es->qd->plannedstmt ?
461                                                 (Node *) es->qd->plannedstmt :
462                                                 es->qd->utilitystmt),
463                                            fcache->src,
464                                            es->qd->params,
465                                            false,       /* not top level */
466                                            es->qd->dest,
467                                            NULL);
468                 result = true;                  /* never stops early */
469         }
470         else
471         {
472                 /* Run regular commands to completion unless lazyEval */
473                 long            count = (es->lazyEval) ? 1L : 0L;
474
475                 ExecutorRun(es->qd, ForwardScanDirection, count);
476
477                 /*
478                  * If we requested run to completion OR there was no tuple returned,
479                  * command must be complete.
480                  */
481                 result = (count == 0L || es->qd->estate->es_processed == 0);
482         }
483
484         PopActiveSnapshot();
485
486         return result;
487 }
488
489 /* Shut down execution of one execution_state node */
490 static void
491 postquel_end(execution_state *es)
492 {
493         /* mark status done to ensure we don't do ExecutorEnd twice */
494         es->status = F_EXEC_DONE;
495
496         /* Utility commands don't need Executor. */
497         if (es->qd->utilitystmt == NULL)
498         {
499                 /* Make our snapshot the active one for any called functions */
500                 PushActiveSnapshot(es->qd->snapshot);
501
502                 if (es->qd->operation != CMD_SELECT)
503                         AfterTriggerEndQuery(es->qd->estate);
504                 ExecutorEnd(es->qd);
505
506                 PopActiveSnapshot();
507         }
508
509         (*es->qd->dest->rDestroy) (es->qd->dest);
510
511         FreeQueryDesc(es->qd);
512         es->qd = NULL;
513 }
514
515 /* Build ParamListInfo array representing current arguments */
516 static void
517 postquel_sub_params(SQLFunctionCachePtr fcache,
518                                         FunctionCallInfo fcinfo)
519 {
520         int                     nargs = fcinfo->nargs;
521
522         if (nargs > 0)
523         {
524                 ParamListInfo paramLI;
525                 int                     i;
526
527                 if (fcache->paramLI == NULL)
528                 {
529                         /* sizeof(ParamListInfoData) includes the first array element */
530                         paramLI = (ParamListInfo) palloc(sizeof(ParamListInfoData) +
531                                                                            (nargs - 1) *sizeof(ParamExternData));
532                         /* we have static list of params, so no hooks needed */
533                         paramLI->paramFetch = NULL;
534                         paramLI->paramFetchArg = NULL;
535                         paramLI->parserSetup = NULL;
536                         paramLI->parserSetupArg = NULL;
537                         paramLI->numParams = nargs;
538                         fcache->paramLI = paramLI;
539                 }
540                 else
541                 {
542                         paramLI = fcache->paramLI;
543                         Assert(paramLI->numParams == nargs);
544                 }
545
546                 for (i = 0; i < nargs; i++)
547                 {
548                         ParamExternData *prm = &paramLI->params[i];
549
550                         prm->value = fcinfo->arg[i];
551                         prm->isnull = fcinfo->argnull[i];
552                         prm->pflags = 0;
553                         prm->ptype = fcache->argtypes[i];
554                 }
555         }
556         else
557                 fcache->paramLI = NULL;
558 }
559
560 /*
561  * Extract the SQL function's value from a single result row.  This is used
562  * both for scalar (non-set) functions and for each row of a lazy-eval set
563  * result.
564  */
565 static Datum
566 postquel_get_single_result(TupleTableSlot *slot,
567                                                    FunctionCallInfo fcinfo,
568                                                    SQLFunctionCachePtr fcache,
569                                                    MemoryContext resultcontext)
570 {
571         Datum           value;
572         MemoryContext oldcontext;
573
574         /*
575          * Set up to return the function value.  For pass-by-reference datatypes,
576          * be sure to allocate the result in resultcontext, not the current memory
577          * context (which has query lifespan).  We can't leave the data in the
578          * TupleTableSlot because we intend to clear the slot before returning.
579          */
580         oldcontext = MemoryContextSwitchTo(resultcontext);
581
582         if (fcache->returnsTuple)
583         {
584                 /* We must return the whole tuple as a Datum. */
585                 fcinfo->isnull = false;
586                 value = ExecFetchSlotTupleDatum(slot);
587                 value = datumCopy(value, fcache->typbyval, fcache->typlen);
588         }
589         else
590         {
591                 /*
592                  * Returning a scalar, which we have to extract from the first column
593                  * of the SELECT result, and then copy into result context if needed.
594                  */
595                 value = slot_getattr(slot, 1, &(fcinfo->isnull));
596
597                 if (!fcinfo->isnull)
598                         value = datumCopy(value, fcache->typbyval, fcache->typlen);
599         }
600
601         MemoryContextSwitchTo(oldcontext);
602
603         return value;
604 }
605
606 /*
607  * fmgr_sql: function call manager for SQL functions
608  */
609 Datum
610 fmgr_sql(PG_FUNCTION_ARGS)
611 {
612         MemoryContext oldcontext;
613         SQLFunctionCachePtr fcache;
614         ErrorContextCallback sqlerrcontext;
615         bool            randomAccess;
616         bool            lazyEvalOK;
617         execution_state *es;
618         TupleTableSlot *slot;
619         Datum           result;
620
621         /*
622          * Switch to context in which the fcache lives.  This ensures that
623          * parsetrees, plans, etc, will have sufficient lifetime.  The
624          * sub-executor is responsible for deleting per-tuple information.
625          */
626         oldcontext = MemoryContextSwitchTo(fcinfo->flinfo->fn_mcxt);
627
628         /*
629          * Setup error traceback support for ereport()
630          */
631         sqlerrcontext.callback = sql_exec_error_callback;
632         sqlerrcontext.arg = fcinfo->flinfo;
633         sqlerrcontext.previous = error_context_stack;
634         error_context_stack = &sqlerrcontext;
635
636         /* Check call context */
637         if (fcinfo->flinfo->fn_retset)
638         {
639                 ReturnSetInfo *rsi = (ReturnSetInfo *) fcinfo->resultinfo;
640
641                 /*
642                  * For simplicity, we require callers to support both set eval modes.
643                  * There are cases where we must use one or must use the other, and
644                  * it's not really worthwhile to postpone the check till we know. But
645                  * note we do not require caller to provide an expectedDesc.
646                  */
647                 if (!rsi || !IsA(rsi, ReturnSetInfo) ||
648                         (rsi->allowedModes & SFRM_ValuePerCall) == 0 ||
649                         (rsi->allowedModes & SFRM_Materialize) == 0)
650                         ereport(ERROR,
651                                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
652                                          errmsg("set-valued function called in context that cannot accept a set")));
653                 randomAccess = rsi->allowedModes & SFRM_Materialize_Random;
654                 lazyEvalOK = !(rsi->allowedModes & SFRM_Materialize_Preferred);
655         }
656         else
657         {
658                 randomAccess = false;
659                 lazyEvalOK = true;
660         }
661
662         /*
663          * Initialize fcache (build plans) if first time through.
664          */
665         fcache = (SQLFunctionCachePtr) fcinfo->flinfo->fn_extra;
666         if (fcache == NULL)
667         {
668                 init_sql_fcache(fcinfo->flinfo, lazyEvalOK);
669                 fcache = (SQLFunctionCachePtr) fcinfo->flinfo->fn_extra;
670         }
671         es = fcache->func_state;
672
673         /*
674          * Convert params to appropriate format if starting a fresh execution. (If
675          * continuing execution, we can re-use prior params.)
676          */
677         if (es && es->status == F_EXEC_START)
678                 postquel_sub_params(fcache, fcinfo);
679
680         /*
681          * Build tuplestore to hold results, if we don't have one already. Note
682          * it's in the query-lifespan context.
683          */
684         if (!fcache->tstore)
685                 fcache->tstore = tuplestore_begin_heap(randomAccess, false, work_mem);
686
687         /*
688          * Find first unfinished query in function.
689          */
690         while (es && es->status == F_EXEC_DONE)
691                 es = es->next;
692
693         /*
694          * Execute each command in the function one after another until we either
695          * run out of commands or get a result row from a lazily-evaluated SELECT.
696          */
697         while (es)
698         {
699                 bool            completed;
700
701                 if (es->status == F_EXEC_START)
702                         postquel_start(es, fcache);
703
704                 completed = postquel_getnext(es, fcache);
705
706                 /*
707                  * If we ran the command to completion, we can shut it down now. Any
708                  * row(s) we need to return are safely stashed in the tuplestore, and
709                  * we want to be sure that, for example, AFTER triggers get fired
710                  * before we return anything.  Also, if the function doesn't return
711                  * set, we can shut it down anyway because it must be a SELECT and we
712                  * don't care about fetching any more result rows.
713                  */
714                 if (completed || !fcache->returnsSet)
715                         postquel_end(es);
716
717                 /*
718                  * Break from loop if we didn't shut down (implying we got a
719                  * lazily-evaluated row).  Otherwise we'll press on till the whole
720                  * function is done, relying on the tuplestore to keep hold of the
721                  * data to eventually be returned.      This is necessary since an
722                  * INSERT/UPDATE/DELETE RETURNING that sets the result might be
723                  * followed by additional rule-inserted commands, and we want to
724                  * finish doing all those commands before we return anything.
725                  */
726                 if (es->status != F_EXEC_DONE)
727                         break;
728                 es = es->next;
729         }
730
731         /*
732          * The tuplestore now contains whatever row(s) we are supposed to return.
733          */
734         if (fcache->returnsSet)
735         {
736                 ReturnSetInfo *rsi = (ReturnSetInfo *) fcinfo->resultinfo;
737
738                 if (es)
739                 {
740                         /*
741                          * If we stopped short of being done, we must have a lazy-eval
742                          * row.
743                          */
744                         Assert(es->lazyEval);
745                         /* Re-use the junkfilter's output slot to fetch back the tuple */
746                         Assert(fcache->junkFilter);
747                         slot = fcache->junkFilter->jf_resultSlot;
748                         if (!tuplestore_gettupleslot(fcache->tstore, true, false, slot))
749                                 elog(ERROR, "failed to fetch lazy-eval tuple");
750                         /* Extract the result as a datum, and copy out from the slot */
751                         result = postquel_get_single_result(slot, fcinfo,
752                                                                                                 fcache, oldcontext);
753                         /* Clear the tuplestore, but keep it for next time */
754                         /* NB: this might delete the slot's content, but we don't care */
755                         tuplestore_clear(fcache->tstore);
756
757                         /*
758                          * Let caller know we're not finished.
759                          */
760                         rsi->isDone = ExprMultipleResult;
761
762                         /*
763                          * Ensure we will get shut down cleanly if the exprcontext is not
764                          * run to completion.
765                          */
766                         if (!fcache->shutdown_reg)
767                         {
768                                 RegisterExprContextCallback(rsi->econtext,
769                                                                                         ShutdownSQLFunction,
770                                                                                         PointerGetDatum(fcache));
771                                 fcache->shutdown_reg = true;
772                         }
773                 }
774                 else if (fcache->lazyEval)
775                 {
776                         /*
777                          * We are done with a lazy evaluation.  Clean up.
778                          */
779                         tuplestore_clear(fcache->tstore);
780
781                         /*
782                          * Let caller know we're finished.
783                          */
784                         rsi->isDone = ExprEndResult;
785
786                         fcinfo->isnull = true;
787                         result = (Datum) 0;
788
789                         /* Deregister shutdown callback, if we made one */
790                         if (fcache->shutdown_reg)
791                         {
792                                 UnregisterExprContextCallback(rsi->econtext,
793                                                                                           ShutdownSQLFunction,
794                                                                                           PointerGetDatum(fcache));
795                                 fcache->shutdown_reg = false;
796                         }
797                 }
798                 else
799                 {
800                         /*
801                          * We are done with a non-lazy evaluation.      Return whatever is in
802                          * the tuplestore.      (It is now caller's responsibility to free the
803                          * tuplestore when done.)
804                          */
805                         rsi->returnMode = SFRM_Materialize;
806                         rsi->setResult = fcache->tstore;
807                         fcache->tstore = NULL;
808                         /* must copy desc because execQual will free it */
809                         if (fcache->junkFilter)
810                                 rsi->setDesc = CreateTupleDescCopy(fcache->junkFilter->jf_cleanTupType);
811
812                         fcinfo->isnull = true;
813                         result = (Datum) 0;
814
815                         /* Deregister shutdown callback, if we made one */
816                         if (fcache->shutdown_reg)
817                         {
818                                 UnregisterExprContextCallback(rsi->econtext,
819                                                                                           ShutdownSQLFunction,
820                                                                                           PointerGetDatum(fcache));
821                                 fcache->shutdown_reg = false;
822                         }
823                 }
824         }
825         else
826         {
827                 /*
828                  * Non-set function.  If we got a row, return it; else return NULL.
829                  */
830                 if (fcache->junkFilter)
831                 {
832                         /* Re-use the junkfilter's output slot to fetch back the tuple */
833                         slot = fcache->junkFilter->jf_resultSlot;
834                         if (tuplestore_gettupleslot(fcache->tstore, true, false, slot))
835                                 result = postquel_get_single_result(slot, fcinfo,
836                                                                                                         fcache, oldcontext);
837                         else
838                         {
839                                 fcinfo->isnull = true;
840                                 result = (Datum) 0;
841                         }
842                 }
843                 else
844                 {
845                         /* Should only get here for VOID functions */
846                         Assert(fcache->rettype == VOIDOID);
847                         fcinfo->isnull = true;
848                         result = (Datum) 0;
849                 }
850
851                 /* Clear the tuplestore, but keep it for next time */
852                 tuplestore_clear(fcache->tstore);
853         }
854
855         /*
856          * If we've gone through every command in the function, we are done. Reset
857          * the execution states to start over again on next call.
858          */
859         if (es == NULL)
860         {
861                 es = fcache->func_state;
862                 while (es)
863                 {
864                         es->status = F_EXEC_START;
865                         es = es->next;
866                 }
867         }
868
869         error_context_stack = sqlerrcontext.previous;
870
871         MemoryContextSwitchTo(oldcontext);
872
873         return result;
874 }
875
876
877 /*
878  * error context callback to let us supply a call-stack traceback
879  */
880 static void
881 sql_exec_error_callback(void *arg)
882 {
883         FmgrInfo   *flinfo = (FmgrInfo *) arg;
884         SQLFunctionCachePtr fcache = (SQLFunctionCachePtr) flinfo->fn_extra;
885         int                     syntaxerrposition;
886
887         /*
888          * We can do nothing useful if init_sql_fcache() didn't get as far as
889          * saving the function name
890          */
891         if (fcache == NULL || fcache->fname == NULL)
892                 return;
893
894         /*
895          * If there is a syntax error position, convert to internal syntax error
896          */
897         syntaxerrposition = geterrposition();
898         if (syntaxerrposition > 0 && fcache->src != NULL)
899         {
900                 errposition(0);
901                 internalerrposition(syntaxerrposition);
902                 internalerrquery(fcache->src);
903         }
904
905         /*
906          * Try to determine where in the function we failed.  If there is a query
907          * with non-null QueryDesc, finger it.  (We check this rather than looking
908          * for F_EXEC_RUN state, so that errors during ExecutorStart or
909          * ExecutorEnd are blamed on the appropriate query; see postquel_start and
910          * postquel_end.)
911          */
912         if (fcache->func_state)
913         {
914                 execution_state *es;
915                 int                     query_num;
916
917                 es = fcache->func_state;
918                 query_num = 1;
919                 while (es)
920                 {
921                         if (es->qd)
922                         {
923                                 errcontext("SQL function \"%s\" statement %d",
924                                                    fcache->fname, query_num);
925                                 break;
926                         }
927                         es = es->next;
928                         query_num++;
929                 }
930                 if (es == NULL)
931                 {
932                         /*
933                          * couldn't identify a running query; might be function entry,
934                          * function exit, or between queries.
935                          */
936                         errcontext("SQL function \"%s\"", fcache->fname);
937                 }
938         }
939         else
940         {
941                 /*
942                  * Assume we failed during init_sql_fcache().  (It's possible that the
943                  * function actually has an empty body, but in that case we may as
944                  * well report all errors as being "during startup".)
945                  */
946                 errcontext("SQL function \"%s\" during startup", fcache->fname);
947         }
948 }
949
950
951 /*
952  * callback function in case a function-returning-set needs to be shut down
953  * before it has been run to completion
954  */
955 static void
956 ShutdownSQLFunction(Datum arg)
957 {
958         SQLFunctionCachePtr fcache = (SQLFunctionCachePtr) DatumGetPointer(arg);
959         execution_state *es = fcache->func_state;
960
961         while (es != NULL)
962         {
963                 /* Shut down anything still running */
964                 if (es->status == F_EXEC_RUN)
965                         postquel_end(es);
966                 /* Reset states to START in case we're called again */
967                 es->status = F_EXEC_START;
968                 es = es->next;
969         }
970
971         /* Release tuplestore if we have one */
972         if (fcache->tstore)
973                 tuplestore_end(fcache->tstore);
974         fcache->tstore = NULL;
975
976         /* execUtils will deregister the callback... */
977         fcache->shutdown_reg = false;
978 }
979
980
981 /*
982  * check_sql_fn_retval() -- check return value of a list of sql parse trees.
983  *
984  * The return value of a sql function is the value returned by the last
985  * canSetTag query in the function.  We do some ad-hoc type checking here
986  * to be sure that the user is returning the type he claims.  There are
987  * also a couple of strange-looking features to assist callers in dealing
988  * with allowed special cases, such as binary-compatible result types.
989  *
990  * For a polymorphic function the passed rettype must be the actual resolved
991  * output type of the function; we should never see a polymorphic pseudotype
992  * such as ANYELEMENT as rettype.  (This means we can't check the type during
993  * function definition of a polymorphic function.)
994  *
995  * This function returns true if the sql function returns the entire tuple
996  * result of its final statement, or false if it returns just the first column
997  * result of that statement.  It throws an error if the final statement doesn't
998  * return the right type at all.
999  *
1000  * Note that because we allow "SELECT rowtype_expression", the result can be
1001  * false even when the declared function return type is a rowtype.
1002  *
1003  * If modifyTargetList isn't NULL, the function will modify the final
1004  * statement's targetlist in two cases:
1005  * (1) if the tlist returns values that are binary-coercible to the expected
1006  * type rather than being exactly the expected type.  RelabelType nodes will
1007  * be inserted to make the result types match exactly.
1008  * (2) if there are dropped columns in the declared result rowtype.  NULL
1009  * output columns will be inserted in the tlist to match them.
1010  * (Obviously the caller must pass a parsetree that is okay to modify when
1011  * using this flag.)  Note that this flag does not affect whether the tlist is
1012  * considered to be a legal match to the result type, only how we react to
1013  * allowed not-exact-match cases.  *modifyTargetList will be set true iff
1014  * we had to make any "dangerous" changes that could modify the semantics of
1015  * the statement.  If it is set true, the caller should not use the modified
1016  * statement, but for simplicity we apply the changes anyway.
1017  *
1018  * If junkFilter isn't NULL, then *junkFilter is set to a JunkFilter defined
1019  * to convert the function's tuple result to the correct output tuple type.
1020  * Exception: if the function is defined to return VOID then *junkFilter is
1021  * set to NULL.
1022  */
1023 bool
1024 check_sql_fn_retval(Oid func_id, Oid rettype, List *queryTreeList,
1025                                         bool *modifyTargetList,
1026                                         JunkFilter **junkFilter)
1027 {
1028         Query      *parse;
1029         List      **tlist_ptr;
1030         List       *tlist;
1031         int                     tlistlen;
1032         char            fn_typtype;
1033         Oid                     restype;
1034         ListCell   *lc;
1035
1036         AssertArg(!IsPolymorphicType(rettype));
1037
1038         if (modifyTargetList)
1039                 *modifyTargetList = false;              /* initialize for no change */
1040         if (junkFilter)
1041                 *junkFilter = NULL;             /* initialize in case of VOID result */
1042
1043         /*
1044          * Find the last canSetTag query in the list.  This isn't necessarily the
1045          * last parsetree, because rule rewriting can insert queries after what
1046          * the user wrote.
1047          */
1048         parse = NULL;
1049         foreach(lc, queryTreeList)
1050         {
1051                 Query      *q = (Query *) lfirst(lc);
1052
1053                 if (q->canSetTag)
1054                         parse = q;
1055         }
1056
1057         /*
1058          * If it's a plain SELECT, it returns whatever the targetlist says.
1059          * Otherwise, if it's INSERT/UPDATE/DELETE with RETURNING, it returns
1060          * that. Otherwise, the function return type must be VOID.
1061          *
1062          * Note: eventually replace this test with QueryReturnsTuples?  We'd need
1063          * a more general method of determining the output type, though.  Also, it
1064          * seems too dangerous to consider FETCH or EXECUTE as returning a
1065          * determinable rowtype, since they depend on relatively short-lived
1066          * entities.
1067          */
1068         if (parse &&
1069                 parse->commandType == CMD_SELECT &&
1070                 parse->utilityStmt == NULL &&
1071                 parse->intoClause == NULL)
1072         {
1073                 tlist_ptr = &parse->targetList;
1074                 tlist = parse->targetList;
1075         }
1076         else if (parse &&
1077                          (parse->commandType == CMD_INSERT ||
1078                           parse->commandType == CMD_UPDATE ||
1079                           parse->commandType == CMD_DELETE) &&
1080                          parse->returningList)
1081         {
1082                 tlist_ptr = &parse->returningList;
1083                 tlist = parse->returningList;
1084         }
1085         else
1086         {
1087                 /* Empty function body, or last statement is a utility command */
1088                 if (rettype != VOIDOID)
1089                         ereport(ERROR,
1090                                         (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
1091                          errmsg("return type mismatch in function declared to return %s",
1092                                         format_type_be(rettype)),
1093                                          errdetail("Function's final statement must be SELECT or INSERT/UPDATE/DELETE RETURNING.")));
1094                 return false;
1095         }
1096
1097         /*
1098          * OK, check that the targetlist returns something matching the declared
1099          * type.  (We used to insist that the declared type not be VOID in this
1100          * case, but that makes it hard to write a void function that exits after
1101          * calling another void function.  Instead, we insist that the tlist
1102          * return void ... so void is treated as if it were a scalar type below.)
1103          */
1104
1105         /*
1106          * Count the non-junk entries in the result targetlist.
1107          */
1108         tlistlen = ExecCleanTargetListLength(tlist);
1109
1110         fn_typtype = get_typtype(rettype);
1111
1112         if (fn_typtype == TYPTYPE_BASE ||
1113                 fn_typtype == TYPTYPE_DOMAIN ||
1114                 fn_typtype == TYPTYPE_ENUM ||
1115                 rettype == VOIDOID)
1116         {
1117                 /*
1118                  * For scalar-type returns, the target list must have exactly one
1119                  * non-junk entry, and its type must agree with what the user
1120                  * declared; except we allow binary-compatible types too.
1121                  */
1122                 TargetEntry *tle;
1123
1124                 if (tlistlen != 1)
1125                         ereport(ERROR,
1126                                         (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
1127                          errmsg("return type mismatch in function declared to return %s",
1128                                         format_type_be(rettype)),
1129                           errdetail("Final statement must return exactly one column.")));
1130
1131                 /* We assume here that non-junk TLEs must come first in tlists */
1132                 tle = (TargetEntry *) linitial(tlist);
1133                 Assert(!tle->resjunk);
1134
1135                 restype = exprType((Node *) tle->expr);
1136                 if (!IsBinaryCoercible(restype, rettype))
1137                         ereport(ERROR,
1138                                         (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
1139                          errmsg("return type mismatch in function declared to return %s",
1140                                         format_type_be(rettype)),
1141                                          errdetail("Actual return type is %s.",
1142                                                            format_type_be(restype))));
1143                 if (modifyTargetList && restype != rettype)
1144                 {
1145                         tle->expr = (Expr *) makeRelabelType(tle->expr,
1146                                                                                                  rettype,
1147                                                                                                  -1,
1148                                                                                                  COERCE_DONTCARE);
1149                         /* Relabel is dangerous if TLE is a sort/group or setop column */
1150                         if (tle->ressortgroupref != 0 || parse->setOperations)
1151                                 *modifyTargetList = true;
1152                 }
1153
1154                 /* Set up junk filter if needed */
1155                 if (junkFilter)
1156                         *junkFilter = ExecInitJunkFilter(tlist, false, NULL);
1157         }
1158         else if (fn_typtype == TYPTYPE_COMPOSITE || rettype == RECORDOID)
1159         {
1160                 /* Returns a rowtype */
1161                 TupleDesc       tupdesc;
1162                 int                     tupnatts;       /* physical number of columns in tuple */
1163                 int                     tuplogcols; /* # of nondeleted columns in tuple */
1164                 int                     colindex;       /* physical column index */
1165                 List       *newtlist;   /* new non-junk tlist entries */
1166                 List       *junkattrs;  /* new junk tlist entries */
1167
1168                 /*
1169                  * If the target list is of length 1, and the type of the varnode in
1170                  * the target list matches the declared return type, this is okay.
1171                  * This can happen, for example, where the body of the function is
1172                  * 'SELECT func2()', where func2 has the same composite return type as
1173                  * the function that's calling it.
1174                  */
1175                 if (tlistlen == 1)
1176                 {
1177                         TargetEntry *tle = (TargetEntry *) linitial(tlist);
1178
1179                         Assert(!tle->resjunk);
1180                         restype = exprType((Node *) tle->expr);
1181                         if (IsBinaryCoercible(restype, rettype))
1182                         {
1183                                 if (modifyTargetList && restype != rettype)
1184                                 {
1185                                         tle->expr = (Expr *) makeRelabelType(tle->expr,
1186                                                                                                                  rettype,
1187                                                                                                                  -1,
1188                                                                                                                  COERCE_DONTCARE);
1189                                         /* Relabel is dangerous if sort/group or setop column */
1190                                         if (tle->ressortgroupref != 0 || parse->setOperations)
1191                                                 *modifyTargetList = true;
1192                                 }
1193                                 /* Set up junk filter if needed */
1194                                 if (junkFilter)
1195                                         *junkFilter = ExecInitJunkFilter(tlist, false, NULL);
1196                                 return false;   /* NOT returning whole tuple */
1197                         }
1198                 }
1199
1200                 /* Is the rowtype fixed, or determined only at runtime? */
1201                 if (get_func_result_type(func_id, NULL, &tupdesc) != TYPEFUNC_COMPOSITE)
1202                 {
1203                         /*
1204                          * Assume we are returning the whole tuple. Crosschecking against
1205                          * what the caller expects will happen at runtime.
1206                          */
1207                         if (junkFilter)
1208                                 *junkFilter = ExecInitJunkFilter(tlist, false, NULL);
1209                         return true;
1210                 }
1211                 Assert(tupdesc);
1212
1213                 /*
1214                  * Verify that the targetlist matches the return tuple type. We scan
1215                  * the non-deleted attributes to ensure that they match the datatypes
1216                  * of the non-resjunk columns.  For deleted attributes, insert NULL
1217                  * result columns if the caller asked for that.
1218                  */
1219                 tupnatts = tupdesc->natts;
1220                 tuplogcols = 0;                 /* we'll count nondeleted cols as we go */
1221                 colindex = 0;
1222                 newtlist = NIL;                 /* these are only used if modifyTargetList */
1223                 junkattrs = NIL;
1224
1225                 foreach(lc, tlist)
1226                 {
1227                         TargetEntry *tle = (TargetEntry *) lfirst(lc);
1228                         Form_pg_attribute attr;
1229                         Oid                     tletype;
1230                         Oid                     atttype;
1231
1232                         if (tle->resjunk)
1233                         {
1234                                 if (modifyTargetList)
1235                                         junkattrs = lappend(junkattrs, tle);
1236                                 continue;
1237                         }
1238
1239                         do
1240                         {
1241                                 colindex++;
1242                                 if (colindex > tupnatts)
1243                                         ereport(ERROR,
1244                                                         (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
1245                                                          errmsg("return type mismatch in function declared to return %s",
1246                                                                         format_type_be(rettype)),
1247                                         errdetail("Final statement returns too many columns.")));
1248                                 attr = tupdesc->attrs[colindex - 1];
1249                                 if (attr->attisdropped && modifyTargetList)
1250                                 {
1251                                         Expr       *null_expr;
1252
1253                                         /* The type of the null we insert isn't important */
1254                                         null_expr = (Expr *) makeConst(INT4OID,
1255                                                                                                    -1,
1256                                                                                                    sizeof(int32),
1257                                                                                                    (Datum) 0,
1258                                                                                                    true,                /* isnull */
1259                                                                                                    true /* byval */ );
1260                                         newtlist = lappend(newtlist,
1261                                                                            makeTargetEntry(null_expr,
1262                                                                                                            colindex,
1263                                                                                                            NULL,
1264                                                                                                            false));
1265                                         /* NULL insertion is dangerous in a setop */
1266                                         if (parse->setOperations)
1267                                                 *modifyTargetList = true;
1268                                 }
1269                         } while (attr->attisdropped);
1270                         tuplogcols++;
1271
1272                         tletype = exprType((Node *) tle->expr);
1273                         atttype = attr->atttypid;
1274                         if (!IsBinaryCoercible(tletype, atttype))
1275                                 ereport(ERROR,
1276                                                 (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
1277                                                  errmsg("return type mismatch in function declared to return %s",
1278                                                                 format_type_be(rettype)),
1279                                                  errdetail("Final statement returns %s instead of %s at column %d.",
1280                                                                    format_type_be(tletype),
1281                                                                    format_type_be(atttype),
1282                                                                    tuplogcols)));
1283                         if (modifyTargetList)
1284                         {
1285                                 if (tletype != atttype)
1286                                 {
1287                                         tle->expr = (Expr *) makeRelabelType(tle->expr,
1288                                                                                                                  atttype,
1289                                                                                                                  -1,
1290                                                                                                                  COERCE_DONTCARE);
1291                                         /* Relabel is dangerous if sort/group or setop column */
1292                                         if (tle->ressortgroupref != 0 || parse->setOperations)
1293                                                 *modifyTargetList = true;
1294                                 }
1295                                 tle->resno = colindex;
1296                                 newtlist = lappend(newtlist, tle);
1297                         }
1298                 }
1299
1300                 /* remaining columns in tupdesc had better all be dropped */
1301                 for (colindex++; colindex <= tupnatts; colindex++)
1302                 {
1303                         if (!tupdesc->attrs[colindex - 1]->attisdropped)
1304                                 ereport(ERROR,
1305                                                 (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
1306                                                  errmsg("return type mismatch in function declared to return %s",
1307                                                                 format_type_be(rettype)),
1308                                          errdetail("Final statement returns too few columns.")));
1309                         if (modifyTargetList)
1310                         {
1311                                 Expr       *null_expr;
1312
1313                                 /* The type of the null we insert isn't important */
1314                                 null_expr = (Expr *) makeConst(INT4OID,
1315                                                                                            -1,
1316                                                                                            sizeof(int32),
1317                                                                                            (Datum) 0,
1318                                                                                            true,        /* isnull */
1319                                                                                            true /* byval */ );
1320                                 newtlist = lappend(newtlist,
1321                                                                    makeTargetEntry(null_expr,
1322                                                                                                    colindex,
1323                                                                                                    NULL,
1324                                                                                                    false));
1325                                 /* NULL insertion is dangerous in a setop */
1326                                 if (parse->setOperations)
1327                                         *modifyTargetList = true;
1328                         }
1329                 }
1330
1331                 if (modifyTargetList)
1332                 {
1333                         /* ensure resjunk columns are numbered correctly */
1334                         foreach(lc, junkattrs)
1335                         {
1336                                 TargetEntry *tle = (TargetEntry *) lfirst(lc);
1337
1338                                 tle->resno = colindex++;
1339                         }
1340                         /* replace the tlist with the modified one */
1341                         *tlist_ptr = list_concat(newtlist, junkattrs);
1342                 }
1343
1344                 /* Set up junk filter if needed */
1345                 if (junkFilter)
1346                         *junkFilter = ExecInitJunkFilterConversion(tlist,
1347                                                                                                 CreateTupleDescCopy(tupdesc),
1348                                                                                                            NULL);
1349
1350                 /* Report that we are returning entire tuple result */
1351                 return true;
1352         }
1353         else
1354                 ereport(ERROR,
1355                                 (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
1356                                  errmsg("return type %s is not supported for SQL functions",
1357                                                 format_type_be(rettype))));
1358
1359         return false;
1360 }
1361
1362
1363 /*
1364  * CreateSQLFunctionDestReceiver -- create a suitable DestReceiver object
1365  */
1366 DestReceiver *
1367 CreateSQLFunctionDestReceiver(void)
1368 {
1369         DR_sqlfunction *self = (DR_sqlfunction *) palloc0(sizeof(DR_sqlfunction));
1370
1371         self->pub.receiveSlot = sqlfunction_receive;
1372         self->pub.rStartup = sqlfunction_startup;
1373         self->pub.rShutdown = sqlfunction_shutdown;
1374         self->pub.rDestroy = sqlfunction_destroy;
1375         self->pub.mydest = DestSQLFunction;
1376
1377         /* private fields will be set by postquel_start */
1378
1379         return (DestReceiver *) self;
1380 }
1381
1382 /*
1383  * sqlfunction_startup --- executor startup
1384  */
1385 static void
1386 sqlfunction_startup(DestReceiver *self, int operation, TupleDesc typeinfo)
1387 {
1388         /* no-op */
1389 }
1390
1391 /*
1392  * sqlfunction_receive --- receive one tuple
1393  */
1394 static void
1395 sqlfunction_receive(TupleTableSlot *slot, DestReceiver *self)
1396 {
1397         DR_sqlfunction *myState = (DR_sqlfunction *) self;
1398
1399         /* Filter tuple as needed */
1400         slot = ExecFilterJunk(myState->filter, slot);
1401
1402         /* Store the filtered tuple into the tuplestore */
1403         tuplestore_puttupleslot(myState->tstore, slot);
1404 }
1405
1406 /*
1407  * sqlfunction_shutdown --- executor end
1408  */
1409 static void
1410 sqlfunction_shutdown(DestReceiver *self)
1411 {
1412         /* no-op */
1413 }
1414
1415 /*
1416  * sqlfunction_destroy --- release DestReceiver object
1417  */
1418 static void
1419 sqlfunction_destroy(DestReceiver *self)
1420 {
1421         pfree(self);
1422 }