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