1 /*-------------------------------------------------------------------------
4 * Execution of SQL-language functions
6 * Portions Copyright (c) 1996-2010, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
11 * src/backend/executor/functions.c
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 *fname; /* function name (for error msgs) */
78 char *src; /* function body text (for error msgs) */
80 Oid *argtypes; /* resolved types of arguments */
81 Oid rettype; /* actual return type */
82 int16 typlen; /* length of the return type */
83 bool typbyval; /* true if return type is pass by value */
84 bool returnsSet; /* true if returning multiple rows */
85 bool returnsTuple; /* true if returning whole tuple result */
86 bool shutdown_reg; /* true if registered shutdown callback */
87 bool readonly_func; /* true to run in "read only" mode */
88 bool lazyEval; /* true if using lazyEval for result query */
90 ParamListInfo paramLI; /* Param list representing current args */
92 Tuplestorestate *tstore; /* where we accumulate result tuples */
94 JunkFilter *junkFilter; /* will be NULL if function returns VOID */
96 /* head of linked list of execution_state records */
97 execution_state *func_state;
100 typedef SQLFunctionCache *SQLFunctionCachePtr;
103 /* non-export function prototypes */
104 static execution_state *init_execution_state(List *queryTree_list,
105 SQLFunctionCachePtr fcache,
107 static void init_sql_fcache(FmgrInfo *finfo, bool lazyEvalOK);
108 static void postquel_start(execution_state *es, SQLFunctionCachePtr fcache);
109 static bool postquel_getnext(execution_state *es, SQLFunctionCachePtr fcache);
110 static void postquel_end(execution_state *es);
111 static void postquel_sub_params(SQLFunctionCachePtr fcache,
112 FunctionCallInfo fcinfo);
113 static Datum postquel_get_single_result(TupleTableSlot *slot,
114 FunctionCallInfo fcinfo,
115 SQLFunctionCachePtr fcache,
116 MemoryContext resultcontext);
117 static void sql_exec_error_callback(void *arg);
118 static void ShutdownSQLFunction(Datum arg);
119 static void sqlfunction_startup(DestReceiver *self, int operation, TupleDesc typeinfo);
120 static void sqlfunction_receive(TupleTableSlot *slot, DestReceiver *self);
121 static void sqlfunction_shutdown(DestReceiver *self);
122 static void sqlfunction_destroy(DestReceiver *self);
125 /* Set up the list of per-query execution_state records for a SQL function */
126 static execution_state *
127 init_execution_state(List *queryTree_list,
128 SQLFunctionCachePtr fcache,
131 execution_state *firstes = NULL;
132 execution_state *preves = NULL;
133 execution_state *lasttages = NULL;
136 foreach(qtl_item, queryTree_list)
138 Query *queryTree = (Query *) lfirst(qtl_item);
140 execution_state *newes;
142 Assert(IsA(queryTree, Query));
144 if (queryTree->commandType == CMD_UTILITY)
145 stmt = queryTree->utilityStmt;
147 stmt = (Node *) pg_plan_query(queryTree, 0, NULL);
149 /* Precheck all commands for validity in a function */
150 if (IsA(stmt, TransactionStmt))
152 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
153 /* translator: %s is a SQL statement name */
154 errmsg("%s is not allowed in a SQL function",
155 CreateCommandTag(stmt))));
157 if (fcache->readonly_func && !CommandIsReadOnly(stmt))
159 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
160 /* translator: %s is a SQL statement name */
161 errmsg("%s is not allowed in a non-volatile function",
162 CreateCommandTag(stmt))));
164 newes = (execution_state *) palloc(sizeof(execution_state));
166 preves->next = newes;
171 newes->status = F_EXEC_START;
172 newes->setsResult = false; /* might change below */
173 newes->lazyEval = false; /* might change below */
177 if (queryTree->canSetTag)
184 * Mark the last canSetTag query as delivering the function result; then,
185 * if it is a plain SELECT, mark it for lazy evaluation. If it's not a
186 * SELECT we must always run it to completion.
188 * Note: at some point we might add additional criteria for whether to use
189 * lazy eval. However, we should prefer to use it whenever the function
190 * doesn't return set, since fetching more than one row is useless in that
193 * Note: don't set setsResult if the function returns VOID, as evidenced
194 * by not having made a junkfilter. This ensures we'll throw away any
195 * output from a utility statement that check_sql_fn_retval deemed to not
198 if (lasttages && fcache->junkFilter)
200 lasttages->setsResult = true;
202 IsA(lasttages->stmt, PlannedStmt))
204 PlannedStmt *ps = (PlannedStmt *) lasttages->stmt;
206 if (ps->commandType == CMD_SELECT &&
207 ps->utilityStmt == NULL &&
208 ps->intoClause == NULL)
209 fcache->lazyEval = lasttages->lazyEval = true;
216 /* Initialize the SQLFunctionCache for a SQL function */
218 init_sql_fcache(FmgrInfo *finfo, bool lazyEvalOK)
220 Oid foid = finfo->fn_oid;
222 HeapTuple procedureTuple;
223 Form_pg_proc procedureStruct;
224 SQLFunctionCachePtr fcache;
227 List *queryTree_list;
231 fcache = (SQLFunctionCachePtr) palloc0(sizeof(SQLFunctionCache));
232 finfo->fn_extra = (void *) fcache;
235 * get the procedure tuple corresponding to the given function Oid
237 procedureTuple = SearchSysCache1(PROCOID, ObjectIdGetDatum(foid));
238 if (!HeapTupleIsValid(procedureTuple))
239 elog(ERROR, "cache lookup failed for function %u", foid);
240 procedureStruct = (Form_pg_proc) GETSTRUCT(procedureTuple);
243 * copy function name immediately for use by error reporting callback
245 fcache->fname = pstrdup(NameStr(procedureStruct->proname));
248 * get the result type from the procedure tuple, and check for polymorphic
249 * result type; if so, find out the actual result type.
251 rettype = procedureStruct->prorettype;
253 if (IsPolymorphicType(rettype))
255 rettype = get_fn_expr_rettype(finfo);
256 if (rettype == InvalidOid) /* this probably should not happen */
258 (errcode(ERRCODE_DATATYPE_MISMATCH),
259 errmsg("could not determine actual result type for function declared to return type %s",
260 format_type_be(procedureStruct->prorettype))));
263 fcache->rettype = rettype;
265 /* Fetch the typlen and byval info for the result type */
266 get_typlenbyval(rettype, &fcache->typlen, &fcache->typbyval);
268 /* Remember whether we're returning setof something */
269 fcache->returnsSet = procedureStruct->proretset;
271 /* Remember if function is STABLE/IMMUTABLE */
272 fcache->readonly_func =
273 (procedureStruct->provolatile != PROVOLATILE_VOLATILE);
276 * We need the actual argument types to pass to the parser.
278 nargs = procedureStruct->pronargs;
283 argOidVect = (Oid *) palloc(nargs * sizeof(Oid));
285 procedureStruct->proargtypes.values,
286 nargs * sizeof(Oid));
287 /* Resolve any polymorphic argument types */
288 for (argnum = 0; argnum < nargs; argnum++)
290 Oid argtype = argOidVect[argnum];
292 if (IsPolymorphicType(argtype))
294 argtype = get_fn_expr_argtype(finfo, argnum);
295 if (argtype == InvalidOid)
297 (errcode(ERRCODE_DATATYPE_MISMATCH),
298 errmsg("could not determine actual type of argument declared %s",
299 format_type_be(argOidVect[argnum]))));
300 argOidVect[argnum] = argtype;
306 fcache->argtypes = argOidVect;
309 * And of course we need the function body text.
311 tmp = SysCacheGetAttr(PROCOID,
316 elog(ERROR, "null prosrc for function %u", foid);
317 fcache->src = TextDatumGetCString(tmp);
320 * Parse and rewrite the queries in the function text.
322 queryTree_list = pg_parse_and_rewrite(fcache->src, argOidVect, nargs);
325 * Check that the function returns the type it claims to. Although in
326 * simple cases this was already done when the function was defined, we
327 * have to recheck because database objects used in the function's queries
328 * might have changed type. We'd have to do it anyway if the function had
329 * any polymorphic arguments.
331 * Note: we set fcache->returnsTuple according to whether we are returning
332 * the whole tuple result or just a single column. In the latter case we
333 * clear returnsTuple because we need not act different from the scalar
334 * result case, even if it's a rowtype column. (However, we have to force
335 * lazy eval mode in that case; otherwise we'd need extra code to expand
336 * the rowtype column into multiple columns, since we have no way to
337 * notify the caller that it should do that.)
339 * check_sql_fn_retval will also construct a JunkFilter we can use to
340 * coerce the returned rowtype to the desired form (unless the result type
341 * is VOID, in which case there's nothing to coerce to).
343 fcache->returnsTuple = check_sql_fn_retval(foid,
347 &fcache->junkFilter);
349 if (fcache->returnsTuple)
351 /* Make sure output rowtype is properly blessed */
352 BlessTupleDesc(fcache->junkFilter->jf_resultSlot->tts_tupleDescriptor);
354 else if (fcache->returnsSet && type_is_rowtype(fcache->rettype))
357 * Returning rowtype as if it were scalar --- materialize won't work.
358 * Right now it's sufficient to override any caller preference for
359 * materialize mode, but to add more smarts in init_execution_state
360 * about this, we'd probably need a three-way flag instead of bool.
365 /* Finally, plan the queries */
366 fcache->func_state = init_execution_state(queryTree_list,
370 ReleaseSysCache(procedureTuple);
373 /* Start up execution of one execution_state node */
375 postquel_start(execution_state *es, SQLFunctionCachePtr fcache)
380 Assert(es->qd == NULL);
383 * In a read-only function, use the surrounding query's snapshot;
384 * otherwise take a new snapshot for each query. The snapshot should
385 * include a fresh command ID so that all work to date in this transaction
388 if (fcache->readonly_func)
389 snapshot = GetActiveSnapshot();
392 CommandCounterIncrement();
393 snapshot = GetTransactionSnapshot();
397 * If this query produces the function result, send its output to the
398 * tuplestore; else discard any output.
402 DR_sqlfunction *myState;
404 dest = CreateDestReceiver(DestSQLFunction);
405 /* pass down the needed info to the dest receiver routines */
406 myState = (DR_sqlfunction *) dest;
407 Assert(myState->pub.mydest == DestSQLFunction);
408 myState->tstore = fcache->tstore;
409 myState->cxt = CurrentMemoryContext;
410 myState->filter = fcache->junkFilter;
413 dest = None_Receiver;
415 if (IsA(es->stmt, PlannedStmt))
416 es->qd = CreateQueryDesc((PlannedStmt *) es->stmt,
418 snapshot, InvalidSnapshot,
422 es->qd = CreateUtilityQueryDesc(es->stmt,
428 /* We assume we don't need to set up ActiveSnapshot for ExecutorStart */
430 /* Utility commands don't need Executor. */
431 if (es->qd->utilitystmt == NULL)
434 * Only set up to collect queued triggers if it's not a SELECT. This
435 * isn't just an optimization, but is necessary in case a SELECT
436 * returns multiple rows to caller --- we mustn't exit from the
437 * function execution with a stacked AfterTrigger level still active.
439 if (es->qd->operation != CMD_SELECT)
440 AfterTriggerBeginQuery();
441 ExecutorStart(es->qd, 0);
444 es->status = F_EXEC_RUN;
447 /* Run one execution_state; either to completion or to first result row */
448 /* Returns true if we ran to completion */
450 postquel_getnext(execution_state *es, SQLFunctionCachePtr fcache)
454 /* Make our snapshot the active one for any called functions */
455 PushActiveSnapshot(es->qd->snapshot);
457 if (es->qd->utilitystmt)
459 /* ProcessUtility needs the PlannedStmt for DECLARE CURSOR */
460 ProcessUtility((es->qd->plannedstmt ?
461 (Node *) es->qd->plannedstmt :
462 es->qd->utilitystmt),
465 false, /* not top level */
468 result = true; /* never stops early */
472 /* Run regular commands to completion unless lazyEval */
473 long count = (es->lazyEval) ? 1L : 0L;
475 ExecutorRun(es->qd, ForwardScanDirection, count);
478 * If we requested run to completion OR there was no tuple returned,
479 * command must be complete.
481 result = (count == 0L || es->qd->estate->es_processed == 0);
489 /* Shut down execution of one execution_state node */
491 postquel_end(execution_state *es)
493 /* mark status done to ensure we don't do ExecutorEnd twice */
494 es->status = F_EXEC_DONE;
496 /* Utility commands don't need Executor. */
497 if (es->qd->utilitystmt == NULL)
499 /* Make our snapshot the active one for any called functions */
500 PushActiveSnapshot(es->qd->snapshot);
502 if (es->qd->operation != CMD_SELECT)
503 AfterTriggerEndQuery(es->qd->estate);
509 (*es->qd->dest->rDestroy) (es->qd->dest);
511 FreeQueryDesc(es->qd);
515 /* Build ParamListInfo array representing current arguments */
517 postquel_sub_params(SQLFunctionCachePtr fcache,
518 FunctionCallInfo fcinfo)
520 int nargs = fcinfo->nargs;
524 ParamListInfo paramLI;
527 if (fcache->paramLI == NULL)
529 /* sizeof(ParamListInfoData) includes the first array element */
530 paramLI = (ParamListInfo) palloc(sizeof(ParamListInfoData) +
531 (nargs - 1) *sizeof(ParamExternData));
532 /* we have static list of params, so no hooks needed */
533 paramLI->paramFetch = NULL;
534 paramLI->paramFetchArg = NULL;
535 paramLI->parserSetup = NULL;
536 paramLI->parserSetupArg = NULL;
537 paramLI->numParams = nargs;
538 fcache->paramLI = paramLI;
542 paramLI = fcache->paramLI;
543 Assert(paramLI->numParams == nargs);
546 for (i = 0; i < nargs; i++)
548 ParamExternData *prm = ¶mLI->params[i];
550 prm->value = fcinfo->arg[i];
551 prm->isnull = fcinfo->argnull[i];
553 prm->ptype = fcache->argtypes[i];
557 fcache->paramLI = NULL;
561 * Extract the SQL function's value from a single result row. This is used
562 * both for scalar (non-set) functions and for each row of a lazy-eval set
566 postquel_get_single_result(TupleTableSlot *slot,
567 FunctionCallInfo fcinfo,
568 SQLFunctionCachePtr fcache,
569 MemoryContext resultcontext)
572 MemoryContext oldcontext;
575 * Set up to return the function value. For pass-by-reference datatypes,
576 * be sure to allocate the result in resultcontext, not the current memory
577 * context (which has query lifespan). We can't leave the data in the
578 * TupleTableSlot because we intend to clear the slot before returning.
580 oldcontext = MemoryContextSwitchTo(resultcontext);
582 if (fcache->returnsTuple)
584 /* We must return the whole tuple as a Datum. */
585 fcinfo->isnull = false;
586 value = ExecFetchSlotTupleDatum(slot);
587 value = datumCopy(value, fcache->typbyval, fcache->typlen);
592 * Returning a scalar, which we have to extract from the first column
593 * of the SELECT result, and then copy into result context if needed.
595 value = slot_getattr(slot, 1, &(fcinfo->isnull));
598 value = datumCopy(value, fcache->typbyval, fcache->typlen);
601 MemoryContextSwitchTo(oldcontext);
607 * fmgr_sql: function call manager for SQL functions
610 fmgr_sql(PG_FUNCTION_ARGS)
612 MemoryContext oldcontext;
613 SQLFunctionCachePtr fcache;
614 ErrorContextCallback sqlerrcontext;
618 TupleTableSlot *slot;
622 * Switch to context in which the fcache lives. This ensures that
623 * parsetrees, plans, etc, will have sufficient lifetime. The
624 * sub-executor is responsible for deleting per-tuple information.
626 oldcontext = MemoryContextSwitchTo(fcinfo->flinfo->fn_mcxt);
629 * Setup error traceback support for ereport()
631 sqlerrcontext.callback = sql_exec_error_callback;
632 sqlerrcontext.arg = fcinfo->flinfo;
633 sqlerrcontext.previous = error_context_stack;
634 error_context_stack = &sqlerrcontext;
636 /* Check call context */
637 if (fcinfo->flinfo->fn_retset)
639 ReturnSetInfo *rsi = (ReturnSetInfo *) fcinfo->resultinfo;
642 * For simplicity, we require callers to support both set eval modes.
643 * There are cases where we must use one or must use the other, and
644 * it's not really worthwhile to postpone the check till we know. But
645 * note we do not require caller to provide an expectedDesc.
647 if (!rsi || !IsA(rsi, ReturnSetInfo) ||
648 (rsi->allowedModes & SFRM_ValuePerCall) == 0 ||
649 (rsi->allowedModes & SFRM_Materialize) == 0)
651 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
652 errmsg("set-valued function called in context that cannot accept a set")));
653 randomAccess = rsi->allowedModes & SFRM_Materialize_Random;
654 lazyEvalOK = !(rsi->allowedModes & SFRM_Materialize_Preferred);
658 randomAccess = false;
663 * Initialize fcache (build plans) if first time through.
665 fcache = (SQLFunctionCachePtr) fcinfo->flinfo->fn_extra;
668 init_sql_fcache(fcinfo->flinfo, lazyEvalOK);
669 fcache = (SQLFunctionCachePtr) fcinfo->flinfo->fn_extra;
671 es = fcache->func_state;
674 * Convert params to appropriate format if starting a fresh execution. (If
675 * continuing execution, we can re-use prior params.)
677 if (es && es->status == F_EXEC_START)
678 postquel_sub_params(fcache, fcinfo);
681 * Build tuplestore to hold results, if we don't have one already. Note
682 * it's in the query-lifespan context.
685 fcache->tstore = tuplestore_begin_heap(randomAccess, false, work_mem);
688 * Find first unfinished query in function.
690 while (es && es->status == F_EXEC_DONE)
694 * Execute each command in the function one after another until we either
695 * run out of commands or get a result row from a lazily-evaluated SELECT.
701 if (es->status == F_EXEC_START)
702 postquel_start(es, fcache);
704 completed = postquel_getnext(es, fcache);
707 * If we ran the command to completion, we can shut it down now. Any
708 * row(s) we need to return are safely stashed in the tuplestore, and
709 * we want to be sure that, for example, AFTER triggers get fired
710 * before we return anything. Also, if the function doesn't return
711 * set, we can shut it down anyway because it must be a SELECT and we
712 * don't care about fetching any more result rows.
714 if (completed || !fcache->returnsSet)
718 * Break from loop if we didn't shut down (implying we got a
719 * lazily-evaluated row). Otherwise we'll press on till the whole
720 * function is done, relying on the tuplestore to keep hold of the
721 * data to eventually be returned. This is necessary since an
722 * INSERT/UPDATE/DELETE RETURNING that sets the result might be
723 * followed by additional rule-inserted commands, and we want to
724 * finish doing all those commands before we return anything.
726 if (es->status != F_EXEC_DONE)
732 * The tuplestore now contains whatever row(s) we are supposed to return.
734 if (fcache->returnsSet)
736 ReturnSetInfo *rsi = (ReturnSetInfo *) fcinfo->resultinfo;
741 * If we stopped short of being done, we must have a lazy-eval
744 Assert(es->lazyEval);
745 /* Re-use the junkfilter's output slot to fetch back the tuple */
746 Assert(fcache->junkFilter);
747 slot = fcache->junkFilter->jf_resultSlot;
748 if (!tuplestore_gettupleslot(fcache->tstore, true, false, slot))
749 elog(ERROR, "failed to fetch lazy-eval tuple");
750 /* Extract the result as a datum, and copy out from the slot */
751 result = postquel_get_single_result(slot, fcinfo,
753 /* Clear the tuplestore, but keep it for next time */
754 /* NB: this might delete the slot's content, but we don't care */
755 tuplestore_clear(fcache->tstore);
758 * Let caller know we're not finished.
760 rsi->isDone = ExprMultipleResult;
763 * Ensure we will get shut down cleanly if the exprcontext is not
766 if (!fcache->shutdown_reg)
768 RegisterExprContextCallback(rsi->econtext,
770 PointerGetDatum(fcache));
771 fcache->shutdown_reg = true;
774 else if (fcache->lazyEval)
777 * We are done with a lazy evaluation. Clean up.
779 tuplestore_clear(fcache->tstore);
782 * Let caller know we're finished.
784 rsi->isDone = ExprEndResult;
786 fcinfo->isnull = true;
789 /* Deregister shutdown callback, if we made one */
790 if (fcache->shutdown_reg)
792 UnregisterExprContextCallback(rsi->econtext,
794 PointerGetDatum(fcache));
795 fcache->shutdown_reg = false;
801 * We are done with a non-lazy evaluation. Return whatever is in
802 * the tuplestore. (It is now caller's responsibility to free the
803 * tuplestore when done.)
805 rsi->returnMode = SFRM_Materialize;
806 rsi->setResult = fcache->tstore;
807 fcache->tstore = NULL;
808 /* must copy desc because execQual will free it */
809 if (fcache->junkFilter)
810 rsi->setDesc = CreateTupleDescCopy(fcache->junkFilter->jf_cleanTupType);
812 fcinfo->isnull = true;
815 /* Deregister shutdown callback, if we made one */
816 if (fcache->shutdown_reg)
818 UnregisterExprContextCallback(rsi->econtext,
820 PointerGetDatum(fcache));
821 fcache->shutdown_reg = false;
828 * Non-set function. If we got a row, return it; else return NULL.
830 if (fcache->junkFilter)
832 /* Re-use the junkfilter's output slot to fetch back the tuple */
833 slot = fcache->junkFilter->jf_resultSlot;
834 if (tuplestore_gettupleslot(fcache->tstore, true, false, slot))
835 result = postquel_get_single_result(slot, fcinfo,
839 fcinfo->isnull = true;
845 /* Should only get here for VOID functions */
846 Assert(fcache->rettype == VOIDOID);
847 fcinfo->isnull = true;
851 /* Clear the tuplestore, but keep it for next time */
852 tuplestore_clear(fcache->tstore);
856 * If we've gone through every command in the function, we are done. Reset
857 * the execution states to start over again on next call.
861 es = fcache->func_state;
864 es->status = F_EXEC_START;
869 error_context_stack = sqlerrcontext.previous;
871 MemoryContextSwitchTo(oldcontext);
878 * error context callback to let us supply a call-stack traceback
881 sql_exec_error_callback(void *arg)
883 FmgrInfo *flinfo = (FmgrInfo *) arg;
884 SQLFunctionCachePtr fcache = (SQLFunctionCachePtr) flinfo->fn_extra;
885 int syntaxerrposition;
888 * We can do nothing useful if init_sql_fcache() didn't get as far as
889 * saving the function name
891 if (fcache == NULL || fcache->fname == NULL)
895 * If there is a syntax error position, convert to internal syntax error
897 syntaxerrposition = geterrposition();
898 if (syntaxerrposition > 0 && fcache->src != NULL)
901 internalerrposition(syntaxerrposition);
902 internalerrquery(fcache->src);
906 * Try to determine where in the function we failed. If there is a query
907 * with non-null QueryDesc, finger it. (We check this rather than looking
908 * for F_EXEC_RUN state, so that errors during ExecutorStart or
909 * ExecutorEnd are blamed on the appropriate query; see postquel_start and
912 if (fcache->func_state)
917 es = fcache->func_state;
923 errcontext("SQL function \"%s\" statement %d",
924 fcache->fname, query_num);
933 * couldn't identify a running query; might be function entry,
934 * function exit, or between queries.
936 errcontext("SQL function \"%s\"", fcache->fname);
942 * Assume we failed during init_sql_fcache(). (It's possible that the
943 * function actually has an empty body, but in that case we may as
944 * well report all errors as being "during startup".)
946 errcontext("SQL function \"%s\" during startup", fcache->fname);
952 * callback function in case a function-returning-set needs to be shut down
953 * before it has been run to completion
956 ShutdownSQLFunction(Datum arg)
958 SQLFunctionCachePtr fcache = (SQLFunctionCachePtr) DatumGetPointer(arg);
959 execution_state *es = fcache->func_state;
963 /* Shut down anything still running */
964 if (es->status == F_EXEC_RUN)
966 /* Reset states to START in case we're called again */
967 es->status = F_EXEC_START;
971 /* Release tuplestore if we have one */
973 tuplestore_end(fcache->tstore);
974 fcache->tstore = NULL;
976 /* execUtils will deregister the callback... */
977 fcache->shutdown_reg = false;
982 * check_sql_fn_retval() -- check return value of a list of sql parse trees.
984 * The return value of a sql function is the value returned by the last
985 * canSetTag query in the function. We do some ad-hoc type checking here
986 * to be sure that the user is returning the type he claims. There are
987 * also a couple of strange-looking features to assist callers in dealing
988 * with allowed special cases, such as binary-compatible result types.
990 * For a polymorphic function the passed rettype must be the actual resolved
991 * output type of the function; we should never see a polymorphic pseudotype
992 * such as ANYELEMENT as rettype. (This means we can't check the type during
993 * function definition of a polymorphic function.)
995 * This function returns true if the sql function returns the entire tuple
996 * result of its final statement, or false if it returns just the first column
997 * result of that statement. It throws an error if the final statement doesn't
998 * return the right type at all.
1000 * Note that because we allow "SELECT rowtype_expression", the result can be
1001 * false even when the declared function return type is a rowtype.
1003 * If modifyTargetList isn't NULL, the function will modify the final
1004 * statement's targetlist in two cases:
1005 * (1) if the tlist returns values that are binary-coercible to the expected
1006 * type rather than being exactly the expected type. RelabelType nodes will
1007 * be inserted to make the result types match exactly.
1008 * (2) if there are dropped columns in the declared result rowtype. NULL
1009 * output columns will be inserted in the tlist to match them.
1010 * (Obviously the caller must pass a parsetree that is okay to modify when
1011 * using this flag.) Note that this flag does not affect whether the tlist is
1012 * considered to be a legal match to the result type, only how we react to
1013 * allowed not-exact-match cases. *modifyTargetList will be set true iff
1014 * we had to make any "dangerous" changes that could modify the semantics of
1015 * the statement. If it is set true, the caller should not use the modified
1016 * statement, but for simplicity we apply the changes anyway.
1018 * If junkFilter isn't NULL, then *junkFilter is set to a JunkFilter defined
1019 * to convert the function's tuple result to the correct output tuple type.
1020 * Exception: if the function is defined to return VOID then *junkFilter is
1024 check_sql_fn_retval(Oid func_id, Oid rettype, List *queryTreeList,
1025 bool *modifyTargetList,
1026 JunkFilter **junkFilter)
1036 AssertArg(!IsPolymorphicType(rettype));
1038 if (modifyTargetList)
1039 *modifyTargetList = false; /* initialize for no change */
1041 *junkFilter = NULL; /* initialize in case of VOID result */
1044 * Find the last canSetTag query in the list. This isn't necessarily the
1045 * last parsetree, because rule rewriting can insert queries after what
1049 foreach(lc, queryTreeList)
1051 Query *q = (Query *) lfirst(lc);
1058 * If it's a plain SELECT, it returns whatever the targetlist says.
1059 * Otherwise, if it's INSERT/UPDATE/DELETE with RETURNING, it returns
1060 * that. Otherwise, the function return type must be VOID.
1062 * Note: eventually replace this test with QueryReturnsTuples? We'd need
1063 * a more general method of determining the output type, though. Also, it
1064 * seems too dangerous to consider FETCH or EXECUTE as returning a
1065 * determinable rowtype, since they depend on relatively short-lived
1069 parse->commandType == CMD_SELECT &&
1070 parse->utilityStmt == NULL &&
1071 parse->intoClause == NULL)
1073 tlist_ptr = &parse->targetList;
1074 tlist = parse->targetList;
1077 (parse->commandType == CMD_INSERT ||
1078 parse->commandType == CMD_UPDATE ||
1079 parse->commandType == CMD_DELETE) &&
1080 parse->returningList)
1082 tlist_ptr = &parse->returningList;
1083 tlist = parse->returningList;
1087 /* Empty function body, or last statement is a utility command */
1088 if (rettype != VOIDOID)
1090 (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
1091 errmsg("return type mismatch in function declared to return %s",
1092 format_type_be(rettype)),
1093 errdetail("Function's final statement must be SELECT or INSERT/UPDATE/DELETE RETURNING.")));
1098 * OK, check that the targetlist returns something matching the declared
1099 * type. (We used to insist that the declared type not be VOID in this
1100 * case, but that makes it hard to write a void function that exits after
1101 * calling another void function. Instead, we insist that the tlist
1102 * return void ... so void is treated as if it were a scalar type below.)
1106 * Count the non-junk entries in the result targetlist.
1108 tlistlen = ExecCleanTargetListLength(tlist);
1110 fn_typtype = get_typtype(rettype);
1112 if (fn_typtype == TYPTYPE_BASE ||
1113 fn_typtype == TYPTYPE_DOMAIN ||
1114 fn_typtype == TYPTYPE_ENUM ||
1118 * For scalar-type returns, the target list must have exactly one
1119 * non-junk entry, and its type must agree with what the user
1120 * declared; except we allow binary-compatible types too.
1126 (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
1127 errmsg("return type mismatch in function declared to return %s",
1128 format_type_be(rettype)),
1129 errdetail("Final statement must return exactly one column.")));
1131 /* We assume here that non-junk TLEs must come first in tlists */
1132 tle = (TargetEntry *) linitial(tlist);
1133 Assert(!tle->resjunk);
1135 restype = exprType((Node *) tle->expr);
1136 if (!IsBinaryCoercible(restype, rettype))
1138 (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
1139 errmsg("return type mismatch in function declared to return %s",
1140 format_type_be(rettype)),
1141 errdetail("Actual return type is %s.",
1142 format_type_be(restype))));
1143 if (modifyTargetList && restype != rettype)
1145 tle->expr = (Expr *) makeRelabelType(tle->expr,
1149 /* Relabel is dangerous if TLE is a sort/group or setop column */
1150 if (tle->ressortgroupref != 0 || parse->setOperations)
1151 *modifyTargetList = true;
1154 /* Set up junk filter if needed */
1156 *junkFilter = ExecInitJunkFilter(tlist, false, NULL);
1158 else if (fn_typtype == TYPTYPE_COMPOSITE || rettype == RECORDOID)
1160 /* Returns a rowtype */
1162 int tupnatts; /* physical number of columns in tuple */
1163 int tuplogcols; /* # of nondeleted columns in tuple */
1164 int colindex; /* physical column index */
1165 List *newtlist; /* new non-junk tlist entries */
1166 List *junkattrs; /* new junk tlist entries */
1169 * If the target list is of length 1, and the type of the varnode in
1170 * the target list matches the declared return type, this is okay.
1171 * This can happen, for example, where the body of the function is
1172 * 'SELECT func2()', where func2 has the same composite return type as
1173 * the function that's calling it.
1177 TargetEntry *tle = (TargetEntry *) linitial(tlist);
1179 Assert(!tle->resjunk);
1180 restype = exprType((Node *) tle->expr);
1181 if (IsBinaryCoercible(restype, rettype))
1183 if (modifyTargetList && restype != rettype)
1185 tle->expr = (Expr *) makeRelabelType(tle->expr,
1189 /* Relabel is dangerous if sort/group or setop column */
1190 if (tle->ressortgroupref != 0 || parse->setOperations)
1191 *modifyTargetList = true;
1193 /* Set up junk filter if needed */
1195 *junkFilter = ExecInitJunkFilter(tlist, false, NULL);
1196 return false; /* NOT returning whole tuple */
1200 /* Is the rowtype fixed, or determined only at runtime? */
1201 if (get_func_result_type(func_id, NULL, &tupdesc) != TYPEFUNC_COMPOSITE)
1204 * Assume we are returning the whole tuple. Crosschecking against
1205 * what the caller expects will happen at runtime.
1208 *junkFilter = ExecInitJunkFilter(tlist, false, NULL);
1214 * Verify that the targetlist matches the return tuple type. We scan
1215 * the non-deleted attributes to ensure that they match the datatypes
1216 * of the non-resjunk columns. For deleted attributes, insert NULL
1217 * result columns if the caller asked for that.
1219 tupnatts = tupdesc->natts;
1220 tuplogcols = 0; /* we'll count nondeleted cols as we go */
1222 newtlist = NIL; /* these are only used if modifyTargetList */
1227 TargetEntry *tle = (TargetEntry *) lfirst(lc);
1228 Form_pg_attribute attr;
1234 if (modifyTargetList)
1235 junkattrs = lappend(junkattrs, tle);
1242 if (colindex > tupnatts)
1244 (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
1245 errmsg("return type mismatch in function declared to return %s",
1246 format_type_be(rettype)),
1247 errdetail("Final statement returns too many columns.")));
1248 attr = tupdesc->attrs[colindex - 1];
1249 if (attr->attisdropped && modifyTargetList)
1253 /* The type of the null we insert isn't important */
1254 null_expr = (Expr *) makeConst(INT4OID,
1260 newtlist = lappend(newtlist,
1261 makeTargetEntry(null_expr,
1265 /* NULL insertion is dangerous in a setop */
1266 if (parse->setOperations)
1267 *modifyTargetList = true;
1269 } while (attr->attisdropped);
1272 tletype = exprType((Node *) tle->expr);
1273 atttype = attr->atttypid;
1274 if (!IsBinaryCoercible(tletype, atttype))
1276 (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
1277 errmsg("return type mismatch in function declared to return %s",
1278 format_type_be(rettype)),
1279 errdetail("Final statement returns %s instead of %s at column %d.",
1280 format_type_be(tletype),
1281 format_type_be(atttype),
1283 if (modifyTargetList)
1285 if (tletype != atttype)
1287 tle->expr = (Expr *) makeRelabelType(tle->expr,
1291 /* Relabel is dangerous if sort/group or setop column */
1292 if (tle->ressortgroupref != 0 || parse->setOperations)
1293 *modifyTargetList = true;
1295 tle->resno = colindex;
1296 newtlist = lappend(newtlist, tle);
1300 /* remaining columns in tupdesc had better all be dropped */
1301 for (colindex++; colindex <= tupnatts; colindex++)
1303 if (!tupdesc->attrs[colindex - 1]->attisdropped)
1305 (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
1306 errmsg("return type mismatch in function declared to return %s",
1307 format_type_be(rettype)),
1308 errdetail("Final statement returns too few columns.")));
1309 if (modifyTargetList)
1313 /* The type of the null we insert isn't important */
1314 null_expr = (Expr *) makeConst(INT4OID,
1320 newtlist = lappend(newtlist,
1321 makeTargetEntry(null_expr,
1325 /* NULL insertion is dangerous in a setop */
1326 if (parse->setOperations)
1327 *modifyTargetList = true;
1331 if (modifyTargetList)
1333 /* ensure resjunk columns are numbered correctly */
1334 foreach(lc, junkattrs)
1336 TargetEntry *tle = (TargetEntry *) lfirst(lc);
1338 tle->resno = colindex++;
1340 /* replace the tlist with the modified one */
1341 *tlist_ptr = list_concat(newtlist, junkattrs);
1344 /* Set up junk filter if needed */
1346 *junkFilter = ExecInitJunkFilterConversion(tlist,
1347 CreateTupleDescCopy(tupdesc),
1350 /* Report that we are returning entire tuple result */
1355 (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
1356 errmsg("return type %s is not supported for SQL functions",
1357 format_type_be(rettype))));
1364 * CreateSQLFunctionDestReceiver -- create a suitable DestReceiver object
1367 CreateSQLFunctionDestReceiver(void)
1369 DR_sqlfunction *self = (DR_sqlfunction *) palloc0(sizeof(DR_sqlfunction));
1371 self->pub.receiveSlot = sqlfunction_receive;
1372 self->pub.rStartup = sqlfunction_startup;
1373 self->pub.rShutdown = sqlfunction_shutdown;
1374 self->pub.rDestroy = sqlfunction_destroy;
1375 self->pub.mydest = DestSQLFunction;
1377 /* private fields will be set by postquel_start */
1379 return (DestReceiver *) self;
1383 * sqlfunction_startup --- executor startup
1386 sqlfunction_startup(DestReceiver *self, int operation, TupleDesc typeinfo)
1392 * sqlfunction_receive --- receive one tuple
1395 sqlfunction_receive(TupleTableSlot *slot, DestReceiver *self)
1397 DR_sqlfunction *myState = (DR_sqlfunction *) self;
1399 /* Filter tuple as needed */
1400 slot = ExecFilterJunk(myState->filter, slot);
1402 /* Store the filtered tuple into the tuplestore */
1403 tuplestore_puttupleslot(myState->tstore, slot);
1407 * sqlfunction_shutdown --- executor end
1410 sqlfunction_shutdown(DestReceiver *self)
1416 * sqlfunction_destroy --- release DestReceiver object
1419 sqlfunction_destroy(DestReceiver *self)