1 /*-------------------------------------------------------------------------
4 * Execution of SQL-language functions
6 * Portions Copyright (c) 1996-2008, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
11 * $PostgreSQL: pgsql/src/backend/executor/functions.c,v 1.130 2008/11/30 20:51:25 tgl Exp $
13 *-------------------------------------------------------------------------
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"
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"
36 * Specialized DestReceiver for collecting query output in a SQL function
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 */
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.
53 F_EXEC_START, F_EXEC_RUN, F_EXEC_DONE
56 typedef struct execution_state
58 struct execution_state *next;
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 */
68 * An SQLFunctionCache record is built during the first call,
69 * and linked to from the fn_extra field of the FmgrInfo struct.
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
77 char *src; /* function body text (for error msgs) */
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 */
89 ParamListInfo paramLI; /* Param list representing current args */
91 Tuplestorestate *tstore; /* where we accumulate result tuples */
93 JunkFilter *junkFilter; /* will be NULL if function returns VOID */
95 /* head of linked list of execution_state records */
96 execution_state *func_state;
99 typedef SQLFunctionCache *SQLFunctionCachePtr;
102 /* non-export function prototypes */
103 static execution_state *init_execution_state(List *queryTree_list,
104 SQLFunctionCachePtr fcache,
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);
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,
130 execution_state *firstes = NULL;
131 execution_state *preves = NULL;
132 execution_state *lasttages = NULL;
135 foreach(qtl_item, queryTree_list)
137 Query *queryTree = (Query *) lfirst(qtl_item);
139 execution_state *newes;
141 Assert(IsA(queryTree, Query));
143 if (queryTree->commandType == CMD_UTILITY)
144 stmt = queryTree->utilityStmt;
146 stmt = (Node *) pg_plan_query(queryTree, 0, NULL);
148 /* Precheck all commands for validity in a function */
149 if (IsA(stmt, TransactionStmt))
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))));
156 if (fcache->readonly_func && !CommandIsReadOnly(stmt))
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))));
163 newes = (execution_state *) palloc(sizeof(execution_state));
165 preves->next = newes;
170 newes->status = F_EXEC_START;
171 newes->setsResult = false; /* might change below */
172 newes->lazyEval = false; /* might change below */
176 if (queryTree->canSetTag)
183 * Mark the last canSetTag query as delivering the function result;
184 * then, if it is a plain SELECT, mark it for lazy evaluation.
185 * If it's not a SELECT we must always run it to completion.
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
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
197 if (lasttages && fcache->junkFilter)
199 lasttages->setsResult = true;
201 IsA(lasttages->stmt, PlannedStmt))
203 PlannedStmt *ps = (PlannedStmt *) lasttages->stmt;
205 if (ps->commandType == CMD_SELECT &&
206 ps->utilityStmt == NULL &&
207 ps->intoClause == NULL)
208 fcache->lazyEval = lasttages->lazyEval = true;
215 /* Initialize the SQLFunctionCache for a SQL function */
217 init_sql_fcache(FmgrInfo *finfo, bool lazyEvalOK)
219 Oid foid = finfo->fn_oid;
221 HeapTuple procedureTuple;
222 Form_pg_proc procedureStruct;
223 SQLFunctionCachePtr fcache;
226 List *queryTree_list;
230 fcache = (SQLFunctionCachePtr) palloc0(sizeof(SQLFunctionCache));
233 * get the procedure tuple corresponding to the given function Oid
235 procedureTuple = SearchSysCache(PROCOID,
236 ObjectIdGetDatum(foid),
238 if (!HeapTupleIsValid(procedureTuple))
239 elog(ERROR, "cache lookup failed for function %u", foid);
240 procedureStruct = (Form_pg_proc) GETSTRUCT(procedureTuple);
243 * get the result type from the procedure tuple, and check for polymorphic
244 * result type; if so, find out the actual result type.
246 rettype = procedureStruct->prorettype;
248 if (IsPolymorphicType(rettype))
250 rettype = get_fn_expr_rettype(finfo);
251 if (rettype == InvalidOid) /* this probably should not happen */
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))));
258 fcache->rettype = rettype;
260 /* Fetch the typlen and byval info for the result type */
261 get_typlenbyval(rettype, &fcache->typlen, &fcache->typbyval);
263 /* Remember whether we're returning setof something */
264 fcache->returnsSet = procedureStruct->proretset;
266 /* Remember if function is STABLE/IMMUTABLE */
267 fcache->readonly_func =
268 (procedureStruct->provolatile != PROVOLATILE_VOLATILE);
271 * We need the actual argument types to pass to the parser.
273 nargs = procedureStruct->pronargs;
278 argOidVect = (Oid *) palloc(nargs * sizeof(Oid));
280 procedureStruct->proargtypes.values,
281 nargs * sizeof(Oid));
282 /* Resolve any polymorphic argument types */
283 for (argnum = 0; argnum < nargs; argnum++)
285 Oid argtype = argOidVect[argnum];
287 if (IsPolymorphicType(argtype))
289 argtype = get_fn_expr_argtype(finfo, argnum);
290 if (argtype == InvalidOid)
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;
301 fcache->argtypes = argOidVect;
304 * And of course we need the function body text.
306 tmp = SysCacheGetAttr(PROCOID,
311 elog(ERROR, "null prosrc for function %u", foid);
312 fcache->src = TextDatumGetCString(tmp);
315 * Parse and rewrite the queries in the function text.
317 queryTree_list = pg_parse_and_rewrite(fcache->src, argOidVect, nargs);
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.
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
330 * force lazy eval mode in that case; otherwise we'd need extra code to
331 * expand the rowtype column into multiple columns, since we have no
332 * way to notify the caller that it should do that.)
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).
338 fcache->returnsTuple = check_sql_fn_retval(foid,
342 &fcache->junkFilter);
344 if (fcache->returnsTuple)
346 /* Make sure output rowtype is properly blessed */
347 BlessTupleDesc(fcache->junkFilter->jf_resultSlot->tts_tupleDescriptor);
349 else if (fcache->returnsSet && type_is_rowtype(fcache->rettype))
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.
360 /* Finally, plan the queries */
361 fcache->func_state = init_execution_state(queryTree_list,
365 ReleaseSysCache(procedureTuple);
367 finfo->fn_extra = (void *) fcache;
370 /* Start up execution of one execution_state node */
372 postquel_start(execution_state *es, SQLFunctionCachePtr fcache)
377 Assert(es->qd == NULL);
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
385 if (fcache->readonly_func)
386 snapshot = GetActiveSnapshot();
389 CommandCounterIncrement();
390 snapshot = GetTransactionSnapshot();
394 * If this query produces the function result, send its output to the
395 * tuplestore; else discard any output.
399 DR_sqlfunction *myState;
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;
410 dest = None_Receiver;
412 if (IsA(es->stmt, PlannedStmt))
413 es->qd = CreateQueryDesc((PlannedStmt *) es->stmt,
414 snapshot, InvalidSnapshot,
416 fcache->paramLI, false);
418 es->qd = CreateUtilityQueryDesc(es->stmt,
423 /* We assume we don't need to set up ActiveSnapshot for ExecutorStart */
425 /* Utility commands don't need Executor. */
426 if (es->qd->utilitystmt == NULL)
429 * Only set up to collect queued triggers if it's not a SELECT. This
430 * isn't just an optimization, but is necessary in case a SELECT
431 * returns multiple rows to caller --- we mustn't exit from the
432 * function execution with a stacked AfterTrigger level still active.
434 if (es->qd->operation != CMD_SELECT)
435 AfterTriggerBeginQuery();
436 ExecutorStart(es->qd, 0);
439 es->status = F_EXEC_RUN;
442 /* Run one execution_state; either to completion or to first result row */
443 /* Returns true if we ran to completion */
445 postquel_getnext(execution_state *es, SQLFunctionCachePtr fcache)
449 /* Make our snapshot the active one for any called functions */
450 PushActiveSnapshot(es->qd->snapshot);
452 if (es->qd->utilitystmt)
454 /* ProcessUtility needs the PlannedStmt for DECLARE CURSOR */
455 ProcessUtility((es->qd->plannedstmt ?
456 (Node *) es->qd->plannedstmt :
457 es->qd->utilitystmt),
460 false, /* not top level */
463 result = true; /* never stops early */
467 /* Run regular commands to completion unless lazyEval */
468 long count = (es->lazyEval) ? 1L : 0L;
470 ExecutorRun(es->qd, ForwardScanDirection, count);
473 * If we requested run to completion OR there was no tuple returned,
474 * command must be complete.
476 result = (count == 0L || es->qd->estate->es_processed == 0);
484 /* Shut down execution of one execution_state node */
486 postquel_end(execution_state *es)
488 /* mark status done to ensure we don't do ExecutorEnd twice */
489 es->status = F_EXEC_DONE;
491 /* Utility commands don't need Executor. */
492 if (es->qd->utilitystmt == NULL)
494 /* Make our snapshot the active one for any called functions */
495 PushActiveSnapshot(es->qd->snapshot);
497 if (es->qd->operation != CMD_SELECT)
498 AfterTriggerEndQuery(es->qd->estate);
504 (*es->qd->dest->rDestroy) (es->qd->dest);
506 FreeQueryDesc(es->qd);
510 /* Build ParamListInfo array representing current arguments */
512 postquel_sub_params(SQLFunctionCachePtr fcache,
513 FunctionCallInfo fcinfo)
515 int nargs = fcinfo->nargs;
519 ParamListInfo paramLI;
522 if (fcache->paramLI == NULL)
524 /* sizeof(ParamListInfoData) includes the first array element */
525 paramLI = (ParamListInfo) palloc(sizeof(ParamListInfoData) +
526 (nargs - 1) *sizeof(ParamExternData));
527 paramLI->numParams = nargs;
528 fcache->paramLI = paramLI;
532 paramLI = fcache->paramLI;
533 Assert(paramLI->numParams == nargs);
536 for (i = 0; i < nargs; i++)
538 ParamExternData *prm = ¶mLI->params[i];
540 prm->value = fcinfo->arg[i];
541 prm->isnull = fcinfo->argnull[i];
543 prm->ptype = fcache->argtypes[i];
547 fcache->paramLI = NULL;
551 * Extract the SQL function's value from a single result row. This is used
552 * both for scalar (non-set) functions and for each row of a lazy-eval set
556 postquel_get_single_result(TupleTableSlot *slot,
557 FunctionCallInfo fcinfo,
558 SQLFunctionCachePtr fcache,
559 MemoryContext resultcontext)
562 MemoryContext oldcontext;
565 * Set up to return the function value. For pass-by-reference datatypes,
566 * be sure to allocate the result in resultcontext, not the current memory
567 * context (which has query lifespan). We can't leave the data in the
568 * TupleTableSlot because we intend to clear the slot before returning.
570 oldcontext = MemoryContextSwitchTo(resultcontext);
572 if (fcache->returnsTuple)
574 /* We must return the whole tuple as a Datum. */
575 fcinfo->isnull = false;
576 value = ExecFetchSlotTupleDatum(slot);
577 value = datumCopy(value, fcache->typbyval, fcache->typlen);
582 * Returning a scalar, which we have to extract from the first column
583 * of the SELECT result, and then copy into result context if needed.
585 value = slot_getattr(slot, 1, &(fcinfo->isnull));
588 value = datumCopy(value, fcache->typbyval, fcache->typlen);
591 MemoryContextSwitchTo(oldcontext);
597 * fmgr_sql: function call manager for SQL functions
600 fmgr_sql(PG_FUNCTION_ARGS)
602 MemoryContext oldcontext;
603 SQLFunctionCachePtr fcache;
604 ErrorContextCallback sqlerrcontext;
608 TupleTableSlot *slot;
612 * Switch to context in which the fcache lives. This ensures that
613 * parsetrees, plans, etc, will have sufficient lifetime. The
614 * sub-executor is responsible for deleting per-tuple information.
616 oldcontext = MemoryContextSwitchTo(fcinfo->flinfo->fn_mcxt);
619 * Setup error traceback support for ereport()
621 sqlerrcontext.callback = sql_exec_error_callback;
622 sqlerrcontext.arg = fcinfo->flinfo;
623 sqlerrcontext.previous = error_context_stack;
624 error_context_stack = &sqlerrcontext;
626 /* Check call context */
627 if (fcinfo->flinfo->fn_retset)
629 ReturnSetInfo *rsi = (ReturnSetInfo *) fcinfo->resultinfo;
632 * For simplicity, we require callers to support both set eval modes.
633 * There are cases where we must use one or must use the other, and
634 * it's not really worthwhile to postpone the check till we know.
636 if (!rsi || !IsA(rsi, ReturnSetInfo) ||
637 (rsi->allowedModes & SFRM_ValuePerCall) == 0 ||
638 (rsi->allowedModes & SFRM_Materialize) == 0 ||
639 rsi->expectedDesc == NULL)
641 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
642 errmsg("set-valued function called in context that cannot accept a set")));
643 randomAccess = rsi->allowedModes & SFRM_Materialize_Random;
644 lazyEvalOK = !(rsi->allowedModes & SFRM_Materialize_Preferred);
648 randomAccess = false;
653 * Initialize fcache (build plans) if first time through.
655 fcache = (SQLFunctionCachePtr) fcinfo->flinfo->fn_extra;
658 init_sql_fcache(fcinfo->flinfo, lazyEvalOK);
659 fcache = (SQLFunctionCachePtr) fcinfo->flinfo->fn_extra;
661 es = fcache->func_state;
664 * Convert params to appropriate format if starting a fresh execution. (If
665 * continuing execution, we can re-use prior params.)
667 if (es && es->status == F_EXEC_START)
668 postquel_sub_params(fcache, fcinfo);
671 * Build tuplestore to hold results, if we don't have one already.
672 * Note it's in the query-lifespan context.
675 fcache->tstore = tuplestore_begin_heap(randomAccess, false, work_mem);
678 * Find first unfinished query in function.
680 while (es && es->status == F_EXEC_DONE)
684 * Execute each command in the function one after another until we either
685 * run out of commands or get a result row from a lazily-evaluated SELECT.
691 if (es->status == F_EXEC_START)
692 postquel_start(es, fcache);
694 completed = postquel_getnext(es, fcache);
697 * If we ran the command to completion, we can shut it down now.
698 * Any row(s) we need to return are safely stashed in the tuplestore,
699 * and we want to be sure that, for example, AFTER triggers get fired
700 * before we return anything. Also, if the function doesn't return
701 * set, we can shut it down anyway because it must be a SELECT and
702 * we don't care about fetching any more result rows.
704 if (completed || !fcache->returnsSet)
708 * Break from loop if we didn't shut down (implying we got a
709 * lazily-evaluated row). Otherwise we'll press on till the
710 * whole function is done, relying on the tuplestore to keep hold
711 * of the data to eventually be returned. This is necessary since
712 * an INSERT/UPDATE/DELETE RETURNING that sets the result might be
713 * followed by additional rule-inserted commands, and we want to
714 * finish doing all those commands before we return anything.
716 if (es->status != F_EXEC_DONE)
722 * The tuplestore now contains whatever row(s) we are supposed to return.
724 if (fcache->returnsSet)
726 ReturnSetInfo *rsi = (ReturnSetInfo *) fcinfo->resultinfo;
731 * If we stopped short of being done, we must have a lazy-eval row.
733 Assert(es->lazyEval);
734 /* Re-use the junkfilter's output slot to fetch back the tuple */
735 Assert(fcache->junkFilter);
736 slot = fcache->junkFilter->jf_resultSlot;
737 if (!tuplestore_gettupleslot(fcache->tstore, true, slot))
738 elog(ERROR, "failed to fetch lazy-eval tuple");
739 /* Extract the result as a datum, and copy out from the slot */
740 result = postquel_get_single_result(slot, fcinfo,
742 /* Clear the tuplestore, but keep it for next time */
743 /* NB: this might delete the slot's content, but we don't care */
744 tuplestore_clear(fcache->tstore);
747 * Let caller know we're not finished.
749 rsi->isDone = ExprMultipleResult;
752 * Ensure we will get shut down cleanly if the exprcontext is not
755 if (!fcache->shutdown_reg)
757 RegisterExprContextCallback(rsi->econtext,
759 PointerGetDatum(fcache));
760 fcache->shutdown_reg = true;
763 else if (fcache->lazyEval)
766 * We are done with a lazy evaluation. Clean up.
768 tuplestore_clear(fcache->tstore);
771 * Let caller know we're finished.
773 rsi->isDone = ExprEndResult;
775 fcinfo->isnull = true;
778 /* Deregister shutdown callback, if we made one */
779 if (fcache->shutdown_reg)
781 UnregisterExprContextCallback(rsi->econtext,
783 PointerGetDatum(fcache));
784 fcache->shutdown_reg = false;
790 * We are done with a non-lazy evaluation. Return whatever is
791 * in the tuplestore. (It is now caller's responsibility to
792 * free the tuplestore when done.)
794 rsi->returnMode = SFRM_Materialize;
795 rsi->setResult = fcache->tstore;
796 fcache->tstore = NULL;
797 /* must copy desc because execQual will free it */
798 if (fcache->junkFilter)
799 rsi->setDesc = CreateTupleDescCopy(fcache->junkFilter->jf_cleanTupType);
801 fcinfo->isnull = true;
804 /* Deregister shutdown callback, if we made one */
805 if (fcache->shutdown_reg)
807 UnregisterExprContextCallback(rsi->econtext,
809 PointerGetDatum(fcache));
810 fcache->shutdown_reg = false;
817 * Non-set function. If we got a row, return it; else return NULL.
819 if (fcache->junkFilter)
821 /* Re-use the junkfilter's output slot to fetch back the tuple */
822 slot = fcache->junkFilter->jf_resultSlot;
823 if (tuplestore_gettupleslot(fcache->tstore, true, slot))
824 result = postquel_get_single_result(slot, fcinfo,
828 fcinfo->isnull = true;
834 /* Should only get here for VOID functions */
835 Assert(fcache->rettype == VOIDOID);
836 fcinfo->isnull = true;
840 /* Clear the tuplestore, but keep it for next time */
841 tuplestore_clear(fcache->tstore);
845 * If we've gone through every command in the function, we are done.
846 * Reset the execution states to start over again on next call.
850 es = fcache->func_state;
853 es->status = F_EXEC_START;
858 error_context_stack = sqlerrcontext.previous;
860 MemoryContextSwitchTo(oldcontext);
867 * error context callback to let us supply a call-stack traceback
870 sql_exec_error_callback(void *arg)
872 FmgrInfo *flinfo = (FmgrInfo *) arg;
873 SQLFunctionCachePtr fcache = (SQLFunctionCachePtr) flinfo->fn_extra;
874 HeapTuple func_tuple;
875 Form_pg_proc functup;
877 int syntaxerrposition;
879 /* Need access to function's pg_proc tuple */
880 func_tuple = SearchSysCache(PROCOID,
881 ObjectIdGetDatum(flinfo->fn_oid),
883 if (!HeapTupleIsValid(func_tuple))
884 return; /* shouldn't happen */
885 functup = (Form_pg_proc) GETSTRUCT(func_tuple);
886 fn_name = NameStr(functup->proname);
889 * If there is a syntax error position, convert to internal syntax error
891 syntaxerrposition = geterrposition();
892 if (syntaxerrposition > 0)
898 tmp = SysCacheGetAttr(PROCOID, func_tuple, Anum_pg_proc_prosrc,
901 elog(ERROR, "null prosrc");
902 prosrc = TextDatumGetCString(tmp);
904 internalerrposition(syntaxerrposition);
905 internalerrquery(prosrc);
910 * Try to determine where in the function we failed. If there is a query
911 * with non-null QueryDesc, finger it. (We check this rather than looking
912 * for F_EXEC_RUN state, so that errors during ExecutorStart or
913 * ExecutorEnd are blamed on the appropriate query; see postquel_start and
921 es = fcache->func_state;
927 errcontext("SQL function \"%s\" statement %d",
937 * couldn't identify a running query; might be function entry,
938 * function exit, or between queries.
940 errcontext("SQL function \"%s\"", fn_name);
945 /* must have failed during init_sql_fcache() */
946 errcontext("SQL function \"%s\" during startup", fn_name);
949 ReleaseSysCache(func_tuple);
954 * callback function in case a function-returning-set needs to be shut down
955 * before it has been run to completion
958 ShutdownSQLFunction(Datum arg)
960 SQLFunctionCachePtr fcache = (SQLFunctionCachePtr) DatumGetPointer(arg);
961 execution_state *es = fcache->func_state;
965 /* Shut down anything still running */
966 if (es->status == F_EXEC_RUN)
968 /* Reset states to START in case we're called again */
969 es->status = F_EXEC_START;
973 /* Release tuplestore if we have one */
975 tuplestore_end(fcache->tstore);
976 fcache->tstore = NULL;
978 /* execUtils will deregister the callback... */
979 fcache->shutdown_reg = false;
984 * check_sql_fn_retval() -- check return value of a list of sql parse trees.
986 * The return value of a sql function is the value returned by the last
987 * canSetTag query in the function. We do some ad-hoc type checking here
988 * to be sure that the user is returning the type he claims. There are
989 * also a couple of strange-looking features to assist callers in dealing
990 * with allowed special cases, such as binary-compatible result types.
992 * For a polymorphic function the passed rettype must be the actual resolved
993 * output type of the function; we should never see a polymorphic pseudotype
994 * such as ANYELEMENT as rettype. (This means we can't check the type during
995 * function definition of a polymorphic function.)
997 * This function returns true if the sql function returns the entire tuple
998 * result of its final statement, and false otherwise. Note that because we
999 * allow "SELECT rowtype_expression", this may be false even when the declared
1000 * function return type is a rowtype.
1002 * If insertRelabels is true, then binary-compatible cases are dealt with
1003 * by actually inserting RelabelType nodes into the output targetlist;
1004 * obviously the caller must pass a parsetree that it's okay to modify in this
1007 * If junkFilter isn't NULL, then *junkFilter is set to a JunkFilter defined
1008 * to convert the function's tuple result to the correct output tuple type.
1009 * Exception: if the function is defined to return VOID then *junkFilter is
1013 check_sql_fn_retval(Oid func_id, Oid rettype, List *queryTreeList,
1014 bool insertRelabels,
1015 JunkFilter **junkFilter)
1024 AssertArg(!IsPolymorphicType(rettype));
1027 *junkFilter = NULL; /* initialize in case of VOID result */
1030 * Find the last canSetTag query in the list. This isn't necessarily
1031 * the last parsetree, because rule rewriting can insert queries after
1032 * what the user wrote.
1035 foreach(lc, queryTreeList)
1037 Query *q = (Query *) lfirst(lc);
1044 * If it's a plain SELECT, it returns whatever the targetlist says.
1045 * Otherwise, if it's INSERT/UPDATE/DELETE with RETURNING, it returns that.
1046 * Otherwise, the function return type must be VOID.
1048 * Note: eventually replace this test with QueryReturnsTuples? We'd need
1049 * a more general method of determining the output type, though. Also,
1050 * it seems too dangerous to consider FETCH or EXECUTE as returning a
1051 * determinable rowtype, since they depend on relatively short-lived
1055 parse->commandType == CMD_SELECT &&
1056 parse->utilityStmt == NULL &&
1057 parse->intoClause == NULL)
1059 tlist = parse->targetList;
1062 (parse->commandType == CMD_INSERT ||
1063 parse->commandType == CMD_UPDATE ||
1064 parse->commandType == CMD_DELETE) &&
1065 parse->returningList)
1067 tlist = parse->returningList;
1071 /* Empty function body, or last statement is a utility command */
1072 if (rettype != VOIDOID)
1074 (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
1075 errmsg("return type mismatch in function declared to return %s",
1076 format_type_be(rettype)),
1077 errdetail("Function's final statement must be SELECT or INSERT/UPDATE/DELETE RETURNING.")));
1082 * OK, check that the targetlist returns something matching the declared
1083 * type. (We used to insist that the declared type not be VOID in this
1084 * case, but that makes it hard to write a void function that exits after
1085 * calling another void function. Instead, we insist that the tlist
1086 * return void ... so void is treated as if it were a scalar type below.)
1090 * Count the non-junk entries in the result targetlist.
1092 tlistlen = ExecCleanTargetListLength(tlist);
1094 fn_typtype = get_typtype(rettype);
1096 if (fn_typtype == TYPTYPE_BASE ||
1097 fn_typtype == TYPTYPE_DOMAIN ||
1098 fn_typtype == TYPTYPE_ENUM ||
1102 * For scalar-type returns, the target list must have exactly one
1103 * non-junk entry, and its type must agree with what the user
1104 * declared; except we allow binary-compatible types too.
1110 (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
1111 errmsg("return type mismatch in function declared to return %s",
1112 format_type_be(rettype)),
1113 errdetail("Final statement must return exactly one column.")));
1115 /* We assume here that non-junk TLEs must come first in tlists */
1116 tle = (TargetEntry *) linitial(tlist);
1117 Assert(!tle->resjunk);
1119 restype = exprType((Node *) tle->expr);
1120 if (!IsBinaryCoercible(restype, rettype))
1122 (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
1123 errmsg("return type mismatch in function declared to return %s",
1124 format_type_be(rettype)),
1125 errdetail("Actual return type is %s.",
1126 format_type_be(restype))));
1127 if (insertRelabels && restype != rettype)
1128 tle->expr = (Expr *) makeRelabelType(tle->expr,
1133 /* Set up junk filter if needed */
1135 *junkFilter = ExecInitJunkFilter(tlist, false, NULL);
1137 else if (fn_typtype == TYPTYPE_COMPOSITE || rettype == RECORDOID)
1139 /* Returns a rowtype */
1141 int tupnatts; /* physical number of columns in tuple */
1142 int tuplogcols; /* # of nondeleted columns in tuple */
1143 int colindex; /* physical column index */
1146 * If the target list is of length 1, and the type of the varnode in
1147 * the target list matches the declared return type, this is okay.
1148 * This can happen, for example, where the body of the function is
1149 * 'SELECT func2()', where func2 has the same composite return type
1150 * as the function that's calling it.
1154 TargetEntry *tle = (TargetEntry *) linitial(tlist);
1156 Assert(!tle->resjunk);
1157 restype = exprType((Node *) tle->expr);
1158 if (IsBinaryCoercible(restype, rettype))
1160 if (insertRelabels && restype != rettype)
1161 tle->expr = (Expr *) makeRelabelType(tle->expr,
1165 /* Set up junk filter if needed */
1167 *junkFilter = ExecInitJunkFilter(tlist, false, NULL);
1168 return false; /* NOT returning whole tuple */
1172 /* Is the rowtype fixed, or determined only at runtime? */
1173 if (get_func_result_type(func_id, NULL, &tupdesc) != TYPEFUNC_COMPOSITE)
1176 * Assume we are returning the whole tuple. Crosschecking against
1177 * what the caller expects will happen at runtime.
1180 *junkFilter = ExecInitJunkFilter(tlist, false, NULL);
1186 * Verify that the targetlist matches the return tuple type. We scan
1187 * the non-deleted attributes to ensure that they match the datatypes
1188 * of the non-resjunk columns.
1190 tupnatts = tupdesc->natts;
1191 tuplogcols = 0; /* we'll count nondeleted cols as we go */
1196 TargetEntry *tle = (TargetEntry *) lfirst(lc);
1197 Form_pg_attribute attr;
1207 if (colindex > tupnatts)
1209 (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
1210 errmsg("return type mismatch in function declared to return %s",
1211 format_type_be(rettype)),
1212 errdetail("Final statement returns too many columns.")));
1213 attr = tupdesc->attrs[colindex - 1];
1214 } while (attr->attisdropped);
1217 tletype = exprType((Node *) tle->expr);
1218 atttype = attr->atttypid;
1219 if (!IsBinaryCoercible(tletype, atttype))
1221 (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
1222 errmsg("return type mismatch in function declared to return %s",
1223 format_type_be(rettype)),
1224 errdetail("Final statement returns %s instead of %s at column %d.",
1225 format_type_be(tletype),
1226 format_type_be(atttype),
1228 if (insertRelabels && tletype != atttype)
1229 tle->expr = (Expr *) makeRelabelType(tle->expr,
1238 if (colindex > tupnatts)
1240 if (!tupdesc->attrs[colindex - 1]->attisdropped)
1244 if (tlistlen != tuplogcols)
1246 (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
1247 errmsg("return type mismatch in function declared to return %s",
1248 format_type_be(rettype)),
1249 errdetail("Final statement returns too few columns.")));
1251 /* Set up junk filter if needed */
1253 *junkFilter = ExecInitJunkFilterConversion(tlist,
1254 CreateTupleDescCopy(tupdesc),
1257 /* Report that we are returning entire tuple result */
1262 (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
1263 errmsg("return type %s is not supported for SQL functions",
1264 format_type_be(rettype))));
1271 * CreateSQLFunctionDestReceiver -- create a suitable DestReceiver object
1274 CreateSQLFunctionDestReceiver(void)
1276 DR_sqlfunction *self = (DR_sqlfunction *) palloc0(sizeof(DR_sqlfunction));
1278 self->pub.receiveSlot = sqlfunction_receive;
1279 self->pub.rStartup = sqlfunction_startup;
1280 self->pub.rShutdown = sqlfunction_shutdown;
1281 self->pub.rDestroy = sqlfunction_destroy;
1282 self->pub.mydest = DestSQLFunction;
1284 /* private fields will be set by postquel_start */
1286 return (DestReceiver *) self;
1290 * sqlfunction_startup --- executor startup
1293 sqlfunction_startup(DestReceiver *self, int operation, TupleDesc typeinfo)
1299 * sqlfunction_receive --- receive one tuple
1302 sqlfunction_receive(TupleTableSlot *slot, DestReceiver *self)
1304 DR_sqlfunction *myState = (DR_sqlfunction *) self;
1305 MemoryContext oldcxt;
1307 /* Filter tuple as needed */
1308 slot = ExecFilterJunk(myState->filter, slot);
1310 /* Store the filtered tuple into the tuplestore */
1311 oldcxt = MemoryContextSwitchTo(myState->cxt);
1312 tuplestore_puttupleslot(myState->tstore, slot);
1313 MemoryContextSwitchTo(oldcxt);
1317 * sqlfunction_shutdown --- executor end
1320 sqlfunction_shutdown(DestReceiver *self)
1326 * sqlfunction_destroy --- release DestReceiver object
1329 sqlfunction_destroy(DestReceiver *self)