doc: Update links which returned 404
[pgsql.git] / src / backend / executor / functions.c
blob757f8068e21c0176ac175f7a244444667a49667a
1 /*-------------------------------------------------------------------------
3 * functions.c
4 * Execution of SQL-language functions
6 * Portions Copyright (c) 1996-2025, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
10 * IDENTIFICATION
11 * src/backend/executor/functions.c
13 *-------------------------------------------------------------------------
15 #include "postgres.h"
17 #include "access/htup_details.h"
18 #include "access/xact.h"
19 #include "catalog/pg_proc.h"
20 #include "catalog/pg_type.h"
21 #include "executor/functions.h"
22 #include "funcapi.h"
23 #include "miscadmin.h"
24 #include "nodes/makefuncs.h"
25 #include "nodes/nodeFuncs.h"
26 #include "parser/parse_coerce.h"
27 #include "parser/parse_collate.h"
28 #include "parser/parse_func.h"
29 #include "rewrite/rewriteHandler.h"
30 #include "storage/proc.h"
31 #include "tcop/utility.h"
32 #include "utils/builtins.h"
33 #include "utils/datum.h"
34 #include "utils/lsyscache.h"
35 #include "utils/memutils.h"
36 #include "utils/snapmgr.h"
37 #include "utils/syscache.h"
41 * Specialized DestReceiver for collecting query output in a SQL function
43 typedef struct
45 DestReceiver pub; /* publicly-known function pointers */
46 Tuplestorestate *tstore; /* where to put result tuples */
47 MemoryContext cxt; /* context containing tstore */
48 JunkFilter *filter; /* filter to convert tuple type */
49 } DR_sqlfunction;
52 * We have an execution_state record for each query in a function. Each
53 * record contains a plantree for its query. If the query is currently in
54 * F_EXEC_RUN state then there's a QueryDesc too.
56 * The "next" fields chain together all the execution_state records generated
57 * from a single original parsetree. (There will only be more than one in
58 * case of rule expansion of the original parsetree.)
60 typedef enum
62 F_EXEC_START, F_EXEC_RUN, F_EXEC_DONE,
63 } ExecStatus;
65 typedef struct execution_state
67 struct execution_state *next;
68 ExecStatus status;
69 bool setsResult; /* true if this query produces func's result */
70 bool lazyEval; /* true if should fetch one row at a time */
71 PlannedStmt *stmt; /* plan for this query */
72 QueryDesc *qd; /* null unless status == RUN */
73 } execution_state;
77 * An SQLFunctionCache record is built during the first call,
78 * and linked to from the fn_extra field of the FmgrInfo struct.
80 * Note that currently this has only the lifespan of the calling query.
81 * Someday we should rewrite this code to use plancache.c to save parse/plan
82 * results for longer than that.
84 * Physically, though, the data has the lifespan of the FmgrInfo that's used
85 * to call the function, and there are cases (particularly with indexes)
86 * where the FmgrInfo might survive across transactions. We cannot assume
87 * that the parse/plan trees are good for longer than the (sub)transaction in
88 * which parsing was done, so we must mark the record with the LXID/subxid of
89 * its creation time, and regenerate everything if that's obsolete. To avoid
90 * memory leakage when we do have to regenerate things, all the data is kept
91 * in a sub-context of the FmgrInfo's fn_mcxt.
93 typedef struct
95 char *fname; /* function name (for error msgs) */
96 char *src; /* function body text (for error msgs) */
98 SQLFunctionParseInfoPtr pinfo; /* data for parser callback hooks */
100 Oid rettype; /* actual return type */
101 int16 typlen; /* length of the return type */
102 bool typbyval; /* true if return type is pass by value */
103 bool returnsSet; /* true if returning multiple rows */
104 bool returnsTuple; /* true if returning whole tuple result */
105 bool shutdown_reg; /* true if registered shutdown callback */
106 bool readonly_func; /* true to run in "read only" mode */
107 bool lazyEval; /* true if using lazyEval for result query */
109 ParamListInfo paramLI; /* Param list representing current args */
111 Tuplestorestate *tstore; /* where we accumulate result tuples */
113 JunkFilter *junkFilter; /* will be NULL if function returns VOID */
116 * func_state is a List of execution_state records, each of which is the
117 * first for its original parsetree, with any additional records chained
118 * to it via the "next" fields. This sublist structure is needed to keep
119 * track of where the original query boundaries are.
121 List *func_state;
123 MemoryContext fcontext; /* memory context holding this struct and all
124 * subsidiary data */
126 LocalTransactionId lxid; /* lxid in which cache was made */
127 SubTransactionId subxid; /* subxid in which cache was made */
128 } SQLFunctionCache;
130 typedef SQLFunctionCache *SQLFunctionCachePtr;
133 /* non-export function prototypes */
134 static Node *sql_fn_param_ref(ParseState *pstate, ParamRef *pref);
135 static Node *sql_fn_post_column_ref(ParseState *pstate,
136 ColumnRef *cref, Node *var);
137 static Node *sql_fn_make_param(SQLFunctionParseInfoPtr pinfo,
138 int paramno, int location);
139 static Node *sql_fn_resolve_param_name(SQLFunctionParseInfoPtr pinfo,
140 const char *paramname, int location);
141 static List *init_execution_state(List *queryTree_list,
142 SQLFunctionCachePtr fcache,
143 bool lazyEvalOK);
144 static void init_sql_fcache(FunctionCallInfo fcinfo, Oid collation, bool lazyEvalOK);
145 static void postquel_start(execution_state *es, SQLFunctionCachePtr fcache);
146 static bool postquel_getnext(execution_state *es, SQLFunctionCachePtr fcache);
147 static void postquel_end(execution_state *es);
148 static void postquel_sub_params(SQLFunctionCachePtr fcache,
149 FunctionCallInfo fcinfo);
150 static Datum postquel_get_single_result(TupleTableSlot *slot,
151 FunctionCallInfo fcinfo,
152 SQLFunctionCachePtr fcache,
153 MemoryContext resultcontext);
154 static void sql_exec_error_callback(void *arg);
155 static void ShutdownSQLFunction(Datum arg);
156 static bool coerce_fn_result_column(TargetEntry *src_tle,
157 Oid res_type, int32 res_typmod,
158 bool tlist_is_modifiable,
159 List **upper_tlist,
160 bool *upper_tlist_nontrivial);
161 static void sqlfunction_startup(DestReceiver *self, int operation, TupleDesc typeinfo);
162 static bool sqlfunction_receive(TupleTableSlot *slot, DestReceiver *self);
163 static void sqlfunction_shutdown(DestReceiver *self);
164 static void sqlfunction_destroy(DestReceiver *self);
168 * Prepare the SQLFunctionParseInfo struct for parsing a SQL function body
170 * This includes resolving actual types of polymorphic arguments.
172 * call_expr can be passed as NULL, but then we will fail if there are any
173 * polymorphic arguments.
175 SQLFunctionParseInfoPtr
176 prepare_sql_fn_parse_info(HeapTuple procedureTuple,
177 Node *call_expr,
178 Oid inputCollation)
180 SQLFunctionParseInfoPtr pinfo;
181 Form_pg_proc procedureStruct = (Form_pg_proc) GETSTRUCT(procedureTuple);
182 int nargs;
184 pinfo = (SQLFunctionParseInfoPtr) palloc0(sizeof(SQLFunctionParseInfo));
186 /* Function's name (only) can be used to qualify argument names */
187 pinfo->fname = pstrdup(NameStr(procedureStruct->proname));
189 /* Save the function's input collation */
190 pinfo->collation = inputCollation;
193 * Copy input argument types from the pg_proc entry, then resolve any
194 * polymorphic types.
196 pinfo->nargs = nargs = procedureStruct->pronargs;
197 if (nargs > 0)
199 Oid *argOidVect;
200 int argnum;
202 argOidVect = (Oid *) palloc(nargs * sizeof(Oid));
203 memcpy(argOidVect,
204 procedureStruct->proargtypes.values,
205 nargs * sizeof(Oid));
207 for (argnum = 0; argnum < nargs; argnum++)
209 Oid argtype = argOidVect[argnum];
211 if (IsPolymorphicType(argtype))
213 argtype = get_call_expr_argtype(call_expr, argnum);
214 if (argtype == InvalidOid)
215 ereport(ERROR,
216 (errcode(ERRCODE_DATATYPE_MISMATCH),
217 errmsg("could not determine actual type of argument declared %s",
218 format_type_be(argOidVect[argnum]))));
219 argOidVect[argnum] = argtype;
223 pinfo->argtypes = argOidVect;
227 * Collect names of arguments, too, if any
229 if (nargs > 0)
231 Datum proargnames;
232 Datum proargmodes;
233 int n_arg_names;
234 bool isNull;
236 proargnames = SysCacheGetAttr(PROCNAMEARGSNSP, procedureTuple,
237 Anum_pg_proc_proargnames,
238 &isNull);
239 if (isNull)
240 proargnames = PointerGetDatum(NULL); /* just to be sure */
242 proargmodes = SysCacheGetAttr(PROCNAMEARGSNSP, procedureTuple,
243 Anum_pg_proc_proargmodes,
244 &isNull);
245 if (isNull)
246 proargmodes = PointerGetDatum(NULL); /* just to be sure */
248 n_arg_names = get_func_input_arg_names(proargnames, proargmodes,
249 &pinfo->argnames);
251 /* Paranoia: ignore the result if too few array entries */
252 if (n_arg_names < nargs)
253 pinfo->argnames = NULL;
255 else
256 pinfo->argnames = NULL;
258 return pinfo;
262 * Parser setup hook for parsing a SQL function body.
264 void
265 sql_fn_parser_setup(struct ParseState *pstate, SQLFunctionParseInfoPtr pinfo)
267 pstate->p_pre_columnref_hook = NULL;
268 pstate->p_post_columnref_hook = sql_fn_post_column_ref;
269 pstate->p_paramref_hook = sql_fn_param_ref;
270 /* no need to use p_coerce_param_hook */
271 pstate->p_ref_hook_state = pinfo;
275 * sql_fn_post_column_ref parser callback for ColumnRefs
277 static Node *
278 sql_fn_post_column_ref(ParseState *pstate, ColumnRef *cref, Node *var)
280 SQLFunctionParseInfoPtr pinfo = (SQLFunctionParseInfoPtr) pstate->p_ref_hook_state;
281 int nnames;
282 Node *field1;
283 Node *subfield = NULL;
284 const char *name1;
285 const char *name2 = NULL;
286 Node *param;
289 * Never override a table-column reference. This corresponds to
290 * considering the parameter names to appear in a scope outside the
291 * individual SQL commands, which is what we want.
293 if (var != NULL)
294 return NULL;
296 /*----------
297 * The allowed syntaxes are:
299 * A A = parameter name
300 * A.B A = function name, B = parameter name
301 * OR: A = record-typed parameter name, B = field name
302 * (the first possibility takes precedence)
303 * A.B.C A = function name, B = record-typed parameter name,
304 * C = field name
305 * A.* Whole-row reference to composite parameter A.
306 * A.B.* Same, with A = function name, B = parameter name
308 * Here, it's sufficient to ignore the "*" in the last two cases --- the
309 * main parser will take care of expanding the whole-row reference.
310 *----------
312 nnames = list_length(cref->fields);
314 if (nnames > 3)
315 return NULL;
317 if (IsA(llast(cref->fields), A_Star))
318 nnames--;
320 field1 = (Node *) linitial(cref->fields);
321 name1 = strVal(field1);
322 if (nnames > 1)
324 subfield = (Node *) lsecond(cref->fields);
325 name2 = strVal(subfield);
328 if (nnames == 3)
331 * Three-part name: if the first part doesn't match the function name,
332 * we can fail immediately. Otherwise, look up the second part, and
333 * take the third part to be a field reference.
335 if (strcmp(name1, pinfo->fname) != 0)
336 return NULL;
338 param = sql_fn_resolve_param_name(pinfo, name2, cref->location);
340 subfield = (Node *) lthird(cref->fields);
341 Assert(IsA(subfield, String));
343 else if (nnames == 2 && strcmp(name1, pinfo->fname) == 0)
346 * Two-part name with first part matching function name: first see if
347 * second part matches any parameter name.
349 param = sql_fn_resolve_param_name(pinfo, name2, cref->location);
351 if (param)
353 /* Yes, so this is a parameter reference, no subfield */
354 subfield = NULL;
356 else
358 /* No, so try to match as parameter name and subfield */
359 param = sql_fn_resolve_param_name(pinfo, name1, cref->location);
362 else
364 /* Single name, or parameter name followed by subfield */
365 param = sql_fn_resolve_param_name(pinfo, name1, cref->location);
368 if (!param)
369 return NULL; /* No match */
371 if (subfield)
374 * Must be a reference to a field of a composite parameter; otherwise
375 * ParseFuncOrColumn will return NULL, and we'll fail back at the
376 * caller.
378 param = ParseFuncOrColumn(pstate,
379 list_make1(subfield),
380 list_make1(param),
381 pstate->p_last_srf,
382 NULL,
383 false,
384 cref->location);
387 return param;
391 * sql_fn_param_ref parser callback for ParamRefs ($n symbols)
393 static Node *
394 sql_fn_param_ref(ParseState *pstate, ParamRef *pref)
396 SQLFunctionParseInfoPtr pinfo = (SQLFunctionParseInfoPtr) pstate->p_ref_hook_state;
397 int paramno = pref->number;
399 /* Check parameter number is valid */
400 if (paramno <= 0 || paramno > pinfo->nargs)
401 return NULL; /* unknown parameter number */
403 return sql_fn_make_param(pinfo, paramno, pref->location);
407 * sql_fn_make_param construct a Param node for the given paramno
409 static Node *
410 sql_fn_make_param(SQLFunctionParseInfoPtr pinfo,
411 int paramno, int location)
413 Param *param;
415 param = makeNode(Param);
416 param->paramkind = PARAM_EXTERN;
417 param->paramid = paramno;
418 param->paramtype = pinfo->argtypes[paramno - 1];
419 param->paramtypmod = -1;
420 param->paramcollid = get_typcollation(param->paramtype);
421 param->location = location;
424 * If we have a function input collation, allow it to override the
425 * type-derived collation for parameter symbols. (XXX perhaps this should
426 * not happen if the type collation is not default?)
428 if (OidIsValid(pinfo->collation) && OidIsValid(param->paramcollid))
429 param->paramcollid = pinfo->collation;
431 return (Node *) param;
435 * Search for a function parameter of the given name; if there is one,
436 * construct and return a Param node for it. If not, return NULL.
437 * Helper function for sql_fn_post_column_ref.
439 static Node *
440 sql_fn_resolve_param_name(SQLFunctionParseInfoPtr pinfo,
441 const char *paramname, int location)
443 int i;
445 if (pinfo->argnames == NULL)
446 return NULL;
448 for (i = 0; i < pinfo->nargs; i++)
450 if (pinfo->argnames[i] && strcmp(pinfo->argnames[i], paramname) == 0)
451 return sql_fn_make_param(pinfo, i + 1, location);
454 return NULL;
458 * Set up the per-query execution_state records for a SQL function.
460 * The input is a List of Lists of parsed and rewritten, but not planned,
461 * querytrees. The sublist structure denotes the original query boundaries.
463 static List *
464 init_execution_state(List *queryTree_list,
465 SQLFunctionCachePtr fcache,
466 bool lazyEvalOK)
468 List *eslist = NIL;
469 execution_state *lasttages = NULL;
470 ListCell *lc1;
472 foreach(lc1, queryTree_list)
474 List *qtlist = lfirst_node(List, lc1);
475 execution_state *firstes = NULL;
476 execution_state *preves = NULL;
477 ListCell *lc2;
479 foreach(lc2, qtlist)
481 Query *queryTree = lfirst_node(Query, lc2);
482 PlannedStmt *stmt;
483 execution_state *newes;
485 /* Plan the query if needed */
486 if (queryTree->commandType == CMD_UTILITY)
488 /* Utility commands require no planning. */
489 stmt = makeNode(PlannedStmt);
490 stmt->commandType = CMD_UTILITY;
491 stmt->canSetTag = queryTree->canSetTag;
492 stmt->utilityStmt = queryTree->utilityStmt;
493 stmt->stmt_location = queryTree->stmt_location;
494 stmt->stmt_len = queryTree->stmt_len;
495 stmt->queryId = queryTree->queryId;
497 else
498 stmt = pg_plan_query(queryTree,
499 fcache->src,
500 CURSOR_OPT_PARALLEL_OK,
501 NULL);
504 * Precheck all commands for validity in a function. This should
505 * generally match the restrictions spi.c applies.
507 if (stmt->commandType == CMD_UTILITY)
509 if (IsA(stmt->utilityStmt, CopyStmt) &&
510 ((CopyStmt *) stmt->utilityStmt)->filename == NULL)
511 ereport(ERROR,
512 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
513 errmsg("cannot COPY to/from client in an SQL function")));
515 if (IsA(stmt->utilityStmt, TransactionStmt))
516 ereport(ERROR,
517 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
518 /* translator: %s is a SQL statement name */
519 errmsg("%s is not allowed in an SQL function",
520 CreateCommandName(stmt->utilityStmt))));
523 if (fcache->readonly_func && !CommandIsReadOnly(stmt))
524 ereport(ERROR,
525 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
526 /* translator: %s is a SQL statement name */
527 errmsg("%s is not allowed in a non-volatile function",
528 CreateCommandName((Node *) stmt))));
530 /* OK, build the execution_state for this query */
531 newes = (execution_state *) palloc(sizeof(execution_state));
532 if (preves)
533 preves->next = newes;
534 else
535 firstes = newes;
537 newes->next = NULL;
538 newes->status = F_EXEC_START;
539 newes->setsResult = false; /* might change below */
540 newes->lazyEval = false; /* might change below */
541 newes->stmt = stmt;
542 newes->qd = NULL;
544 if (queryTree->canSetTag)
545 lasttages = newes;
547 preves = newes;
550 eslist = lappend(eslist, firstes);
554 * Mark the last canSetTag query as delivering the function result; then,
555 * if it is a plain SELECT, mark it for lazy evaluation. If it's not a
556 * SELECT we must always run it to completion.
558 * Note: at some point we might add additional criteria for whether to use
559 * lazy eval. However, we should prefer to use it whenever the function
560 * doesn't return set, since fetching more than one row is useless in that
561 * case.
563 * Note: don't set setsResult if the function returns VOID, as evidenced
564 * by not having made a junkfilter. This ensures we'll throw away any
565 * output from the last statement in such a function.
567 if (lasttages && fcache->junkFilter)
569 lasttages->setsResult = true;
570 if (lazyEvalOK &&
571 lasttages->stmt->commandType == CMD_SELECT &&
572 !lasttages->stmt->hasModifyingCTE)
573 fcache->lazyEval = lasttages->lazyEval = true;
576 return eslist;
580 * Initialize the SQLFunctionCache for a SQL function
582 static void
583 init_sql_fcache(FunctionCallInfo fcinfo, Oid collation, bool lazyEvalOK)
585 FmgrInfo *finfo = fcinfo->flinfo;
586 Oid foid = finfo->fn_oid;
587 MemoryContext fcontext;
588 MemoryContext oldcontext;
589 Oid rettype;
590 TupleDesc rettupdesc;
591 HeapTuple procedureTuple;
592 Form_pg_proc procedureStruct;
593 SQLFunctionCachePtr fcache;
594 List *queryTree_list;
595 List *resulttlist;
596 ListCell *lc;
597 Datum tmp;
598 bool isNull;
601 * Create memory context that holds all the SQLFunctionCache data. It
602 * must be a child of whatever context holds the FmgrInfo.
604 fcontext = AllocSetContextCreate(finfo->fn_mcxt,
605 "SQL function",
606 ALLOCSET_DEFAULT_SIZES);
608 oldcontext = MemoryContextSwitchTo(fcontext);
611 * Create the struct proper, link it to fcontext and fn_extra. Once this
612 * is done, we'll be able to recover the memory after failure, even if the
613 * FmgrInfo is long-lived.
615 fcache = (SQLFunctionCachePtr) palloc0(sizeof(SQLFunctionCache));
616 fcache->fcontext = fcontext;
617 finfo->fn_extra = fcache;
620 * get the procedure tuple corresponding to the given function Oid
622 procedureTuple = SearchSysCache1(PROCOID, ObjectIdGetDatum(foid));
623 if (!HeapTupleIsValid(procedureTuple))
624 elog(ERROR, "cache lookup failed for function %u", foid);
625 procedureStruct = (Form_pg_proc) GETSTRUCT(procedureTuple);
628 * copy function name immediately for use by error reporting callback, and
629 * for use as memory context identifier
631 fcache->fname = pstrdup(NameStr(procedureStruct->proname));
632 MemoryContextSetIdentifier(fcontext, fcache->fname);
635 * Resolve any polymorphism, obtaining the actual result type, and the
636 * corresponding tupdesc if it's a rowtype.
638 (void) get_call_result_type(fcinfo, &rettype, &rettupdesc);
640 fcache->rettype = rettype;
642 /* Fetch the typlen and byval info for the result type */
643 get_typlenbyval(rettype, &fcache->typlen, &fcache->typbyval);
645 /* Remember whether we're returning setof something */
646 fcache->returnsSet = procedureStruct->proretset;
648 /* Remember if function is STABLE/IMMUTABLE */
649 fcache->readonly_func =
650 (procedureStruct->provolatile != PROVOLATILE_VOLATILE);
653 * We need the actual argument types to pass to the parser. Also make
654 * sure that parameter symbols are considered to have the function's
655 * resolved input collation.
657 fcache->pinfo = prepare_sql_fn_parse_info(procedureTuple,
658 finfo->fn_expr,
659 collation);
662 * And of course we need the function body text.
664 tmp = SysCacheGetAttrNotNull(PROCOID, procedureTuple, Anum_pg_proc_prosrc);
665 fcache->src = TextDatumGetCString(tmp);
667 /* If we have prosqlbody, pay attention to that not prosrc. */
668 tmp = SysCacheGetAttr(PROCOID,
669 procedureTuple,
670 Anum_pg_proc_prosqlbody,
671 &isNull);
674 * Parse and rewrite the queries in the function text. Use sublists to
675 * keep track of the original query boundaries.
677 * Note: since parsing and planning is done in fcontext, we will generate
678 * a lot of cruft that lives as long as the fcache does. This is annoying
679 * but we'll not worry about it until the module is rewritten to use
680 * plancache.c.
682 queryTree_list = NIL;
683 if (!isNull)
685 Node *n;
686 List *stored_query_list;
688 n = stringToNode(TextDatumGetCString(tmp));
689 if (IsA(n, List))
690 stored_query_list = linitial_node(List, castNode(List, n));
691 else
692 stored_query_list = list_make1(n);
694 foreach(lc, stored_query_list)
696 Query *parsetree = lfirst_node(Query, lc);
697 List *queryTree_sublist;
699 AcquireRewriteLocks(parsetree, true, false);
700 queryTree_sublist = pg_rewrite_query(parsetree);
701 queryTree_list = lappend(queryTree_list, queryTree_sublist);
704 else
706 List *raw_parsetree_list;
708 raw_parsetree_list = pg_parse_query(fcache->src);
710 foreach(lc, raw_parsetree_list)
712 RawStmt *parsetree = lfirst_node(RawStmt, lc);
713 List *queryTree_sublist;
715 queryTree_sublist = pg_analyze_and_rewrite_withcb(parsetree,
716 fcache->src,
717 (ParserSetupHook) sql_fn_parser_setup,
718 fcache->pinfo,
719 NULL);
720 queryTree_list = lappend(queryTree_list, queryTree_sublist);
725 * Check that there are no statements we don't want to allow.
727 check_sql_fn_statements(queryTree_list);
730 * Check that the function returns the type it claims to. Although in
731 * simple cases this was already done when the function was defined, we
732 * have to recheck because database objects used in the function's queries
733 * might have changed type. We'd have to recheck anyway if the function
734 * had any polymorphic arguments. Moreover, check_sql_fn_retval takes
735 * care of injecting any required column type coercions. (But we don't
736 * ask it to insert nulls for dropped columns; the junkfilter handles
737 * that.)
739 * Note: we set fcache->returnsTuple according to whether we are returning
740 * the whole tuple result or just a single column. In the latter case we
741 * clear returnsTuple because we need not act different from the scalar
742 * result case, even if it's a rowtype column. (However, we have to force
743 * lazy eval mode in that case; otherwise we'd need extra code to expand
744 * the rowtype column into multiple columns, since we have no way to
745 * notify the caller that it should do that.)
747 fcache->returnsTuple = check_sql_fn_retval(queryTree_list,
748 rettype,
749 rettupdesc,
750 procedureStruct->prokind,
751 false,
752 &resulttlist);
755 * Construct a JunkFilter we can use to coerce the returned rowtype to the
756 * desired form, unless the result type is VOID, in which case there's
757 * nothing to coerce to. (XXX Frequently, the JunkFilter isn't doing
758 * anything very interesting, but much of this module expects it to be
759 * there anyway.)
761 if (rettype != VOIDOID)
763 TupleTableSlot *slot = MakeSingleTupleTableSlot(NULL,
764 &TTSOpsMinimalTuple);
767 * If the result is composite, *and* we are returning the whole tuple
768 * result, we need to insert nulls for any dropped columns. In the
769 * single-column-result case, there might be dropped columns within
770 * the composite column value, but it's not our problem here. There
771 * should be no resjunk entries in resulttlist, so in the second case
772 * the JunkFilter is certainly a no-op.
774 if (rettupdesc && fcache->returnsTuple)
775 fcache->junkFilter = ExecInitJunkFilterConversion(resulttlist,
776 rettupdesc,
777 slot);
778 else
779 fcache->junkFilter = ExecInitJunkFilter(resulttlist, slot);
782 if (fcache->returnsTuple)
784 /* Make sure output rowtype is properly blessed */
785 BlessTupleDesc(fcache->junkFilter->jf_resultSlot->tts_tupleDescriptor);
787 else if (fcache->returnsSet && type_is_rowtype(fcache->rettype))
790 * Returning rowtype as if it were scalar --- materialize won't work.
791 * Right now it's sufficient to override any caller preference for
792 * materialize mode, but to add more smarts in init_execution_state
793 * about this, we'd probably need a three-way flag instead of bool.
795 lazyEvalOK = true;
798 /* Finally, plan the queries */
799 fcache->func_state = init_execution_state(queryTree_list,
800 fcache,
801 lazyEvalOK);
803 /* Mark fcache with time of creation to show it's valid */
804 fcache->lxid = MyProc->vxid.lxid;
805 fcache->subxid = GetCurrentSubTransactionId();
807 ReleaseSysCache(procedureTuple);
809 MemoryContextSwitchTo(oldcontext);
812 /* Start up execution of one execution_state node */
813 static void
814 postquel_start(execution_state *es, SQLFunctionCachePtr fcache)
816 DestReceiver *dest;
818 Assert(es->qd == NULL);
820 /* Caller should have ensured a suitable snapshot is active */
821 Assert(ActiveSnapshotSet());
824 * If this query produces the function result, send its output to the
825 * tuplestore; else discard any output.
827 if (es->setsResult)
829 DR_sqlfunction *myState;
831 dest = CreateDestReceiver(DestSQLFunction);
832 /* pass down the needed info to the dest receiver routines */
833 myState = (DR_sqlfunction *) dest;
834 Assert(myState->pub.mydest == DestSQLFunction);
835 myState->tstore = fcache->tstore;
836 myState->cxt = CurrentMemoryContext;
837 myState->filter = fcache->junkFilter;
839 else
840 dest = None_Receiver;
842 es->qd = CreateQueryDesc(es->stmt,
843 fcache->src,
844 GetActiveSnapshot(),
845 InvalidSnapshot,
846 dest,
847 fcache->paramLI,
848 es->qd ? es->qd->queryEnv : NULL,
851 /* Utility commands don't need Executor. */
852 if (es->qd->operation != CMD_UTILITY)
855 * In lazyEval mode, do not let the executor set up an AfterTrigger
856 * context. This is necessary not just an optimization, because we
857 * mustn't exit from the function execution with a stacked
858 * AfterTrigger level still active. We are careful not to select
859 * lazyEval mode for any statement that could possibly queue triggers.
861 int eflags;
863 if (es->lazyEval)
864 eflags = EXEC_FLAG_SKIP_TRIGGERS;
865 else
866 eflags = 0; /* default run-to-completion flags */
867 ExecutorStart(es->qd, eflags);
870 es->status = F_EXEC_RUN;
873 /* Run one execution_state; either to completion or to first result row */
874 /* Returns true if we ran to completion */
875 static bool
876 postquel_getnext(execution_state *es, SQLFunctionCachePtr fcache)
878 bool result;
880 if (es->qd->operation == CMD_UTILITY)
882 ProcessUtility(es->qd->plannedstmt,
883 fcache->src,
884 true, /* protect function cache's parsetree */
885 PROCESS_UTILITY_QUERY,
886 es->qd->params,
887 es->qd->queryEnv,
888 es->qd->dest,
889 NULL);
890 result = true; /* never stops early */
892 else
894 /* Run regular commands to completion unless lazyEval */
895 uint64 count = (es->lazyEval) ? 1 : 0;
897 ExecutorRun(es->qd, ForwardScanDirection, count);
900 * If we requested run to completion OR there was no tuple returned,
901 * command must be complete.
903 result = (count == 0 || es->qd->estate->es_processed == 0);
906 return result;
909 /* Shut down execution of one execution_state node */
910 static void
911 postquel_end(execution_state *es)
913 /* mark status done to ensure we don't do ExecutorEnd twice */
914 es->status = F_EXEC_DONE;
916 /* Utility commands don't need Executor. */
917 if (es->qd->operation != CMD_UTILITY)
919 ExecutorFinish(es->qd);
920 ExecutorEnd(es->qd);
923 es->qd->dest->rDestroy(es->qd->dest);
925 FreeQueryDesc(es->qd);
926 es->qd = NULL;
929 /* Build ParamListInfo array representing current arguments */
930 static void
931 postquel_sub_params(SQLFunctionCachePtr fcache,
932 FunctionCallInfo fcinfo)
934 int nargs = fcinfo->nargs;
936 if (nargs > 0)
938 ParamListInfo paramLI;
939 Oid *argtypes = fcache->pinfo->argtypes;
941 if (fcache->paramLI == NULL)
943 paramLI = makeParamList(nargs);
944 fcache->paramLI = paramLI;
946 else
948 paramLI = fcache->paramLI;
949 Assert(paramLI->numParams == nargs);
952 for (int i = 0; i < nargs; i++)
954 ParamExternData *prm = &paramLI->params[i];
957 * If an incoming parameter value is a R/W expanded datum, we
958 * force it to R/O. We'd be perfectly entitled to scribble on it,
959 * but the problem is that if the parameter is referenced more
960 * than once in the function, earlier references might mutate the
961 * value seen by later references, which won't do at all. We
962 * could do better if we could be sure of the number of Param
963 * nodes in the function's plans; but we might not have planned
964 * all the statements yet, nor do we have plan tree walker
965 * infrastructure. (Examining the parse trees is not good enough,
966 * because of possible function inlining during planning.)
968 prm->isnull = fcinfo->args[i].isnull;
969 prm->value = MakeExpandedObjectReadOnly(fcinfo->args[i].value,
970 prm->isnull,
971 get_typlen(argtypes[i]));
972 prm->pflags = 0;
973 prm->ptype = argtypes[i];
976 else
977 fcache->paramLI = NULL;
981 * Extract the SQL function's value from a single result row. This is used
982 * both for scalar (non-set) functions and for each row of a lazy-eval set
983 * result.
985 static Datum
986 postquel_get_single_result(TupleTableSlot *slot,
987 FunctionCallInfo fcinfo,
988 SQLFunctionCachePtr fcache,
989 MemoryContext resultcontext)
991 Datum value;
992 MemoryContext oldcontext;
995 * Set up to return the function value. For pass-by-reference datatypes,
996 * be sure to allocate the result in resultcontext, not the current memory
997 * context (which has query lifespan). We can't leave the data in the
998 * TupleTableSlot because we intend to clear the slot before returning.
1000 oldcontext = MemoryContextSwitchTo(resultcontext);
1002 if (fcache->returnsTuple)
1004 /* We must return the whole tuple as a Datum. */
1005 fcinfo->isnull = false;
1006 value = ExecFetchSlotHeapTupleDatum(slot);
1008 else
1011 * Returning a scalar, which we have to extract from the first column
1012 * of the SELECT result, and then copy into result context if needed.
1014 value = slot_getattr(slot, 1, &(fcinfo->isnull));
1016 if (!fcinfo->isnull)
1017 value = datumCopy(value, fcache->typbyval, fcache->typlen);
1020 MemoryContextSwitchTo(oldcontext);
1022 return value;
1026 * fmgr_sql: function call manager for SQL functions
1028 Datum
1029 fmgr_sql(PG_FUNCTION_ARGS)
1031 SQLFunctionCachePtr fcache;
1032 ErrorContextCallback sqlerrcontext;
1033 MemoryContext oldcontext;
1034 bool randomAccess;
1035 bool lazyEvalOK;
1036 bool is_first;
1037 bool pushed_snapshot;
1038 execution_state *es;
1039 TupleTableSlot *slot;
1040 Datum result;
1041 List *eslist;
1042 ListCell *eslc;
1045 * Setup error traceback support for ereport()
1047 sqlerrcontext.callback = sql_exec_error_callback;
1048 sqlerrcontext.arg = fcinfo->flinfo;
1049 sqlerrcontext.previous = error_context_stack;
1050 error_context_stack = &sqlerrcontext;
1052 /* Check call context */
1053 if (fcinfo->flinfo->fn_retset)
1055 ReturnSetInfo *rsi = (ReturnSetInfo *) fcinfo->resultinfo;
1058 * For simplicity, we require callers to support both set eval modes.
1059 * There are cases where we must use one or must use the other, and
1060 * it's not really worthwhile to postpone the check till we know. But
1061 * note we do not require caller to provide an expectedDesc.
1063 if (!rsi || !IsA(rsi, ReturnSetInfo) ||
1064 (rsi->allowedModes & SFRM_ValuePerCall) == 0 ||
1065 (rsi->allowedModes & SFRM_Materialize) == 0)
1066 ereport(ERROR,
1067 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1068 errmsg("set-valued function called in context that cannot accept a set")));
1069 randomAccess = rsi->allowedModes & SFRM_Materialize_Random;
1070 lazyEvalOK = !(rsi->allowedModes & SFRM_Materialize_Preferred);
1072 else
1074 randomAccess = false;
1075 lazyEvalOK = true;
1079 * Initialize fcache (build plans) if first time through; or re-initialize
1080 * if the cache is stale.
1082 fcache = (SQLFunctionCachePtr) fcinfo->flinfo->fn_extra;
1084 if (fcache != NULL)
1086 if (fcache->lxid != MyProc->vxid.lxid ||
1087 !SubTransactionIsActive(fcache->subxid))
1089 /* It's stale; unlink and delete */
1090 fcinfo->flinfo->fn_extra = NULL;
1091 MemoryContextDelete(fcache->fcontext);
1092 fcache = NULL;
1096 if (fcache == NULL)
1098 init_sql_fcache(fcinfo, PG_GET_COLLATION(), lazyEvalOK);
1099 fcache = (SQLFunctionCachePtr) fcinfo->flinfo->fn_extra;
1103 * Switch to context in which the fcache lives. This ensures that our
1104 * tuplestore etc will have sufficient lifetime. The sub-executor is
1105 * responsible for deleting per-tuple information. (XXX in the case of a
1106 * long-lived FmgrInfo, this policy represents more memory leakage, but
1107 * it's not entirely clear where to keep stuff instead.)
1109 oldcontext = MemoryContextSwitchTo(fcache->fcontext);
1112 * Find first unfinished query in function, and note whether it's the
1113 * first query.
1115 eslist = fcache->func_state;
1116 es = NULL;
1117 is_first = true;
1118 foreach(eslc, eslist)
1120 es = (execution_state *) lfirst(eslc);
1122 while (es && es->status == F_EXEC_DONE)
1124 is_first = false;
1125 es = es->next;
1128 if (es)
1129 break;
1133 * Convert params to appropriate format if starting a fresh execution. (If
1134 * continuing execution, we can re-use prior params.)
1136 if (is_first && es && es->status == F_EXEC_START)
1137 postquel_sub_params(fcache, fcinfo);
1140 * Build tuplestore to hold results, if we don't have one already. Note
1141 * it's in the query-lifespan context.
1143 if (!fcache->tstore)
1144 fcache->tstore = tuplestore_begin_heap(randomAccess, false, work_mem);
1147 * Execute each command in the function one after another until we either
1148 * run out of commands or get a result row from a lazily-evaluated SELECT.
1150 * Notes about snapshot management:
1152 * In a read-only function, we just use the surrounding query's snapshot.
1154 * In a non-read-only function, we rely on the fact that we'll never
1155 * suspend execution between queries of the function: the only reason to
1156 * suspend execution before completion is if we are returning a row from a
1157 * lazily-evaluated SELECT. So, when first entering this loop, we'll
1158 * either start a new query (and push a fresh snapshot) or re-establish
1159 * the active snapshot from the existing query descriptor. If we need to
1160 * start a new query in a subsequent execution of the loop, either we need
1161 * a fresh snapshot (and pushed_snapshot is false) or the existing
1162 * snapshot is on the active stack and we can just bump its command ID.
1164 pushed_snapshot = false;
1165 while (es)
1167 bool completed;
1169 if (es->status == F_EXEC_START)
1172 * If not read-only, be sure to advance the command counter for
1173 * each command, so that all work to date in this transaction is
1174 * visible. Take a new snapshot if we don't have one yet,
1175 * otherwise just bump the command ID in the existing snapshot.
1177 if (!fcache->readonly_func)
1179 CommandCounterIncrement();
1180 if (!pushed_snapshot)
1182 PushActiveSnapshot(GetTransactionSnapshot());
1183 pushed_snapshot = true;
1185 else
1186 UpdateActiveSnapshotCommandId();
1189 postquel_start(es, fcache);
1191 else if (!fcache->readonly_func && !pushed_snapshot)
1193 /* Re-establish active snapshot when re-entering function */
1194 PushActiveSnapshot(es->qd->snapshot);
1195 pushed_snapshot = true;
1198 completed = postquel_getnext(es, fcache);
1201 * If we ran the command to completion, we can shut it down now. Any
1202 * row(s) we need to return are safely stashed in the tuplestore, and
1203 * we want to be sure that, for example, AFTER triggers get fired
1204 * before we return anything. Also, if the function doesn't return
1205 * set, we can shut it down anyway because it must be a SELECT and we
1206 * don't care about fetching any more result rows.
1208 if (completed || !fcache->returnsSet)
1209 postquel_end(es);
1212 * Break from loop if we didn't shut down (implying we got a
1213 * lazily-evaluated row). Otherwise we'll press on till the whole
1214 * function is done, relying on the tuplestore to keep hold of the
1215 * data to eventually be returned. This is necessary since an
1216 * INSERT/UPDATE/DELETE RETURNING that sets the result might be
1217 * followed by additional rule-inserted commands, and we want to
1218 * finish doing all those commands before we return anything.
1220 if (es->status != F_EXEC_DONE)
1221 break;
1224 * Advance to next execution_state, which might be in the next list.
1226 es = es->next;
1227 while (!es)
1229 eslc = lnext(eslist, eslc);
1230 if (!eslc)
1231 break; /* end of function */
1233 es = (execution_state *) lfirst(eslc);
1236 * Flush the current snapshot so that we will take a new one for
1237 * the new query list. This ensures that new snaps are taken at
1238 * original-query boundaries, matching the behavior of interactive
1239 * execution.
1241 if (pushed_snapshot)
1243 PopActiveSnapshot();
1244 pushed_snapshot = false;
1250 * The tuplestore now contains whatever row(s) we are supposed to return.
1252 if (fcache->returnsSet)
1254 ReturnSetInfo *rsi = (ReturnSetInfo *) fcinfo->resultinfo;
1256 if (es)
1259 * If we stopped short of being done, we must have a lazy-eval
1260 * row.
1262 Assert(es->lazyEval);
1263 /* Re-use the junkfilter's output slot to fetch back the tuple */
1264 Assert(fcache->junkFilter);
1265 slot = fcache->junkFilter->jf_resultSlot;
1266 if (!tuplestore_gettupleslot(fcache->tstore, true, false, slot))
1267 elog(ERROR, "failed to fetch lazy-eval tuple");
1268 /* Extract the result as a datum, and copy out from the slot */
1269 result = postquel_get_single_result(slot, fcinfo,
1270 fcache, oldcontext);
1271 /* Clear the tuplestore, but keep it for next time */
1272 /* NB: this might delete the slot's content, but we don't care */
1273 tuplestore_clear(fcache->tstore);
1276 * Let caller know we're not finished.
1278 rsi->isDone = ExprMultipleResult;
1281 * Ensure we will get shut down cleanly if the exprcontext is not
1282 * run to completion.
1284 if (!fcache->shutdown_reg)
1286 RegisterExprContextCallback(rsi->econtext,
1287 ShutdownSQLFunction,
1288 PointerGetDatum(fcache));
1289 fcache->shutdown_reg = true;
1292 else if (fcache->lazyEval)
1295 * We are done with a lazy evaluation. Clean up.
1297 tuplestore_clear(fcache->tstore);
1300 * Let caller know we're finished.
1302 rsi->isDone = ExprEndResult;
1304 fcinfo->isnull = true;
1305 result = (Datum) 0;
1307 /* Deregister shutdown callback, if we made one */
1308 if (fcache->shutdown_reg)
1310 UnregisterExprContextCallback(rsi->econtext,
1311 ShutdownSQLFunction,
1312 PointerGetDatum(fcache));
1313 fcache->shutdown_reg = false;
1316 else
1319 * We are done with a non-lazy evaluation. Return whatever is in
1320 * the tuplestore. (It is now caller's responsibility to free the
1321 * tuplestore when done.)
1323 rsi->returnMode = SFRM_Materialize;
1324 rsi->setResult = fcache->tstore;
1325 fcache->tstore = NULL;
1326 /* must copy desc because execSRF.c will free it */
1327 if (fcache->junkFilter)
1328 rsi->setDesc = CreateTupleDescCopy(fcache->junkFilter->jf_cleanTupType);
1330 fcinfo->isnull = true;
1331 result = (Datum) 0;
1333 /* Deregister shutdown callback, if we made one */
1334 if (fcache->shutdown_reg)
1336 UnregisterExprContextCallback(rsi->econtext,
1337 ShutdownSQLFunction,
1338 PointerGetDatum(fcache));
1339 fcache->shutdown_reg = false;
1343 else
1346 * Non-set function. If we got a row, return it; else return NULL.
1348 if (fcache->junkFilter)
1350 /* Re-use the junkfilter's output slot to fetch back the tuple */
1351 slot = fcache->junkFilter->jf_resultSlot;
1352 if (tuplestore_gettupleslot(fcache->tstore, true, false, slot))
1353 result = postquel_get_single_result(slot, fcinfo,
1354 fcache, oldcontext);
1355 else
1357 fcinfo->isnull = true;
1358 result = (Datum) 0;
1361 else
1363 /* Should only get here for VOID functions and procedures */
1364 Assert(fcache->rettype == VOIDOID);
1365 fcinfo->isnull = true;
1366 result = (Datum) 0;
1369 /* Clear the tuplestore, but keep it for next time */
1370 tuplestore_clear(fcache->tstore);
1373 /* Pop snapshot if we have pushed one */
1374 if (pushed_snapshot)
1375 PopActiveSnapshot();
1378 * If we've gone through every command in the function, we are done. Reset
1379 * the execution states to start over again on next call.
1381 if (es == NULL)
1383 foreach(eslc, fcache->func_state)
1385 es = (execution_state *) lfirst(eslc);
1386 while (es)
1388 es->status = F_EXEC_START;
1389 es = es->next;
1394 error_context_stack = sqlerrcontext.previous;
1396 MemoryContextSwitchTo(oldcontext);
1398 return result;
1403 * error context callback to let us supply a call-stack traceback
1405 static void
1406 sql_exec_error_callback(void *arg)
1408 FmgrInfo *flinfo = (FmgrInfo *) arg;
1409 SQLFunctionCachePtr fcache = (SQLFunctionCachePtr) flinfo->fn_extra;
1410 int syntaxerrposition;
1413 * We can do nothing useful if init_sql_fcache() didn't get as far as
1414 * saving the function name
1416 if (fcache == NULL || fcache->fname == NULL)
1417 return;
1420 * If there is a syntax error position, convert to internal syntax error
1422 syntaxerrposition = geterrposition();
1423 if (syntaxerrposition > 0 && fcache->src != NULL)
1425 errposition(0);
1426 internalerrposition(syntaxerrposition);
1427 internalerrquery(fcache->src);
1431 * Try to determine where in the function we failed. If there is a query
1432 * with non-null QueryDesc, finger it. (We check this rather than looking
1433 * for F_EXEC_RUN state, so that errors during ExecutorStart or
1434 * ExecutorEnd are blamed on the appropriate query; see postquel_start and
1435 * postquel_end.)
1437 if (fcache->func_state)
1439 execution_state *es;
1440 int query_num;
1441 ListCell *lc;
1443 es = NULL;
1444 query_num = 1;
1445 foreach(lc, fcache->func_state)
1447 es = (execution_state *) lfirst(lc);
1448 while (es)
1450 if (es->qd)
1452 errcontext("SQL function \"%s\" statement %d",
1453 fcache->fname, query_num);
1454 break;
1456 es = es->next;
1458 if (es)
1459 break;
1460 query_num++;
1462 if (es == NULL)
1465 * couldn't identify a running query; might be function entry,
1466 * function exit, or between queries.
1468 errcontext("SQL function \"%s\"", fcache->fname);
1471 else
1474 * Assume we failed during init_sql_fcache(). (It's possible that the
1475 * function actually has an empty body, but in that case we may as
1476 * well report all errors as being "during startup".)
1478 errcontext("SQL function \"%s\" during startup", fcache->fname);
1484 * callback function in case a function-returning-set needs to be shut down
1485 * before it has been run to completion
1487 static void
1488 ShutdownSQLFunction(Datum arg)
1490 SQLFunctionCachePtr fcache = (SQLFunctionCachePtr) DatumGetPointer(arg);
1491 execution_state *es;
1492 ListCell *lc;
1494 foreach(lc, fcache->func_state)
1496 es = (execution_state *) lfirst(lc);
1497 while (es)
1499 /* Shut down anything still running */
1500 if (es->status == F_EXEC_RUN)
1502 /* Re-establish active snapshot for any called functions */
1503 if (!fcache->readonly_func)
1504 PushActiveSnapshot(es->qd->snapshot);
1506 postquel_end(es);
1508 if (!fcache->readonly_func)
1509 PopActiveSnapshot();
1512 /* Reset states to START in case we're called again */
1513 es->status = F_EXEC_START;
1514 es = es->next;
1518 /* Release tuplestore if we have one */
1519 if (fcache->tstore)
1520 tuplestore_end(fcache->tstore);
1521 fcache->tstore = NULL;
1523 /* execUtils will deregister the callback... */
1524 fcache->shutdown_reg = false;
1528 * check_sql_fn_statements
1530 * Check statements in an SQL function. Error out if there is anything that
1531 * is not acceptable.
1533 void
1534 check_sql_fn_statements(List *queryTreeLists)
1536 ListCell *lc;
1538 /* We are given a list of sublists of Queries */
1539 foreach(lc, queryTreeLists)
1541 List *sublist = lfirst_node(List, lc);
1542 ListCell *lc2;
1544 foreach(lc2, sublist)
1546 Query *query = lfirst_node(Query, lc2);
1549 * Disallow calling procedures with output arguments. The current
1550 * implementation would just throw the output values away, unless
1551 * the statement is the last one. Per SQL standard, we should
1552 * assign the output values by name. By disallowing this here, we
1553 * preserve an opportunity for future improvement.
1555 if (query->commandType == CMD_UTILITY &&
1556 IsA(query->utilityStmt, CallStmt))
1558 CallStmt *stmt = (CallStmt *) query->utilityStmt;
1560 if (stmt->outargs != NIL)
1561 ereport(ERROR,
1562 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1563 errmsg("calling procedures with output arguments is not supported in SQL functions")));
1570 * check_sql_fn_retval()
1571 * Check return value of a list of lists of sql parse trees.
1573 * The return value of a sql function is the value returned by the last
1574 * canSetTag query in the function. We do some ad-hoc type checking and
1575 * coercion here to ensure that the function returns what it's supposed to.
1576 * Note that we may actually modify the last query to make it match!
1578 * This function returns true if the sql function returns the entire tuple
1579 * result of its final statement, or false if it returns just the first column
1580 * result of that statement. It throws an error if the final statement doesn't
1581 * return the right type at all.
1583 * Note that because we allow "SELECT rowtype_expression", the result can be
1584 * false even when the declared function return type is a rowtype.
1586 * For a polymorphic function the passed rettype must be the actual resolved
1587 * output type of the function. (This means we can't check the type during
1588 * function definition of a polymorphic function.) If we do see a polymorphic
1589 * rettype we'll throw an error, saying it is not a supported rettype.
1591 * If the function returns composite, the passed rettupdesc should describe
1592 * the expected output. If rettupdesc is NULL, we can't verify that the
1593 * output matches; that should only happen in fmgr_sql_validator(), or when
1594 * the function returns RECORD and the caller doesn't actually care which
1595 * composite type it is.
1597 * (Typically, rettype and rettupdesc are computed by get_call_result_type
1598 * or a sibling function.)
1600 * In addition to coercing individual output columns, we can modify the
1601 * output to include dummy NULL columns for any dropped columns appearing
1602 * in rettupdesc. This is done only if the caller asks for it.
1604 * If resultTargetList isn't NULL, then *resultTargetList is set to the
1605 * targetlist that defines the final statement's result. Exception: if the
1606 * function is defined to return VOID then *resultTargetList is set to NIL.
1608 bool
1609 check_sql_fn_retval(List *queryTreeLists,
1610 Oid rettype, TupleDesc rettupdesc,
1611 char prokind,
1612 bool insertDroppedCols,
1613 List **resultTargetList)
1615 bool is_tuple_result = false;
1616 Query *parse;
1617 ListCell *parse_cell;
1618 List *tlist;
1619 int tlistlen;
1620 bool tlist_is_modifiable;
1621 char fn_typtype;
1622 List *upper_tlist = NIL;
1623 bool upper_tlist_nontrivial = false;
1624 ListCell *lc;
1626 if (resultTargetList)
1627 *resultTargetList = NIL; /* initialize in case of VOID result */
1630 * If it's declared to return VOID, we don't care what's in the function.
1631 * (This takes care of procedures with no output parameters, as well.)
1633 if (rettype == VOIDOID)
1634 return false;
1637 * Find the last canSetTag query in the function body (which is presented
1638 * to us as a list of sublists of Query nodes). This isn't necessarily
1639 * the last parsetree, because rule rewriting can insert queries after
1640 * what the user wrote. Note that it might not even be in the last
1641 * sublist, for example if the last query rewrites to DO INSTEAD NOTHING.
1642 * (It might not be unreasonable to throw an error in such a case, but
1643 * this is the historical behavior and it doesn't seem worth changing.)
1645 parse = NULL;
1646 parse_cell = NULL;
1647 foreach(lc, queryTreeLists)
1649 List *sublist = lfirst_node(List, lc);
1650 ListCell *lc2;
1652 foreach(lc2, sublist)
1654 Query *q = lfirst_node(Query, lc2);
1656 if (q->canSetTag)
1658 parse = q;
1659 parse_cell = lc2;
1665 * If it's a plain SELECT, it returns whatever the targetlist says.
1666 * Otherwise, if it's INSERT/UPDATE/DELETE/MERGE with RETURNING, it
1667 * returns that. Otherwise, the function return type must be VOID.
1669 * Note: eventually replace this test with QueryReturnsTuples? We'd need
1670 * a more general method of determining the output type, though. Also, it
1671 * seems too dangerous to consider FETCH or EXECUTE as returning a
1672 * determinable rowtype, since they depend on relatively short-lived
1673 * entities.
1675 if (parse &&
1676 parse->commandType == CMD_SELECT)
1678 tlist = parse->targetList;
1679 /* tlist is modifiable unless it's a dummy in a setop query */
1680 tlist_is_modifiable = (parse->setOperations == NULL);
1682 else if (parse &&
1683 (parse->commandType == CMD_INSERT ||
1684 parse->commandType == CMD_UPDATE ||
1685 parse->commandType == CMD_DELETE ||
1686 parse->commandType == CMD_MERGE) &&
1687 parse->returningList)
1689 tlist = parse->returningList;
1690 /* returningList can always be modified */
1691 tlist_is_modifiable = true;
1693 else
1695 /* Empty function body, or last statement is a utility command */
1696 ereport(ERROR,
1697 (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
1698 errmsg("return type mismatch in function declared to return %s",
1699 format_type_be(rettype)),
1700 errdetail("Function's final statement must be SELECT or INSERT/UPDATE/DELETE/MERGE RETURNING.")));
1701 return false; /* keep compiler quiet */
1705 * OK, check that the targetlist returns something matching the declared
1706 * type, and modify it if necessary. If possible, we insert any coercion
1707 * steps right into the final statement's targetlist. However, that might
1708 * risk changes in the statement's semantics --- we can't safely change
1709 * the output type of a grouping column, for instance. In such cases we
1710 * handle coercions by inserting an extra level of Query that effectively
1711 * just does a projection.
1715 * Count the non-junk entries in the result targetlist.
1717 tlistlen = ExecCleanTargetListLength(tlist);
1719 fn_typtype = get_typtype(rettype);
1721 if (fn_typtype == TYPTYPE_BASE ||
1722 fn_typtype == TYPTYPE_DOMAIN ||
1723 fn_typtype == TYPTYPE_ENUM ||
1724 fn_typtype == TYPTYPE_RANGE ||
1725 fn_typtype == TYPTYPE_MULTIRANGE)
1728 * For scalar-type returns, the target list must have exactly one
1729 * non-junk entry, and its type must be coercible to rettype.
1731 TargetEntry *tle;
1733 if (tlistlen != 1)
1734 ereport(ERROR,
1735 (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
1736 errmsg("return type mismatch in function declared to return %s",
1737 format_type_be(rettype)),
1738 errdetail("Final statement must return exactly one column.")));
1740 /* We assume here that non-junk TLEs must come first in tlists */
1741 tle = (TargetEntry *) linitial(tlist);
1742 Assert(!tle->resjunk);
1744 if (!coerce_fn_result_column(tle, rettype, -1,
1745 tlist_is_modifiable,
1746 &upper_tlist,
1747 &upper_tlist_nontrivial))
1748 ereport(ERROR,
1749 (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
1750 errmsg("return type mismatch in function declared to return %s",
1751 format_type_be(rettype)),
1752 errdetail("Actual return type is %s.",
1753 format_type_be(exprType((Node *) tle->expr)))));
1755 else if (fn_typtype == TYPTYPE_COMPOSITE || rettype == RECORDOID)
1758 * Returns a rowtype.
1760 * Note that we will not consider a domain over composite to be a
1761 * "rowtype" return type; it goes through the scalar case above. This
1762 * is because we only provide column-by-column implicit casting, and
1763 * will not cast the complete record result. So the only way to
1764 * produce a domain-over-composite result is to compute it as an
1765 * explicit single-column result. The single-composite-column code
1766 * path just below could handle such cases, but it won't be reached.
1768 int tupnatts; /* physical number of columns in tuple */
1769 int tuplogcols; /* # of nondeleted columns in tuple */
1770 int colindex; /* physical column index */
1773 * If the target list has one non-junk entry, and that expression has
1774 * or can be coerced to the declared return type, take it as the
1775 * result. This allows, for example, 'SELECT func2()', where func2
1776 * has the same composite return type as the function that's calling
1777 * it. This provision creates some ambiguity --- maybe the expression
1778 * was meant to be the lone field of the composite result --- but it
1779 * works well enough as long as we don't get too enthusiastic about
1780 * inventing coercions from scalar to composite types.
1782 * XXX Note that if rettype is RECORD and the expression is of a named
1783 * composite type, or vice versa, this coercion will succeed, whether
1784 * or not the record type really matches. For the moment we rely on
1785 * runtime type checking to catch any discrepancy, but it'd be nice to
1786 * do better at parse time.
1788 * We must *not* do this for a procedure, however. Procedures with
1789 * output parameter(s) have rettype RECORD, and the CALL code expects
1790 * to get results corresponding to the list of output parameters, even
1791 * when there's just one parameter that's composite.
1793 if (tlistlen == 1 && prokind != PROKIND_PROCEDURE)
1795 TargetEntry *tle = (TargetEntry *) linitial(tlist);
1797 Assert(!tle->resjunk);
1798 if (coerce_fn_result_column(tle, rettype, -1,
1799 tlist_is_modifiable,
1800 &upper_tlist,
1801 &upper_tlist_nontrivial))
1803 /* Note that we're NOT setting is_tuple_result */
1804 goto tlist_coercion_finished;
1809 * If the caller didn't provide an expected tupdesc, we can't do any
1810 * further checking. Assume we're returning the whole tuple.
1812 if (rettupdesc == NULL)
1814 /* Return tlist if requested */
1815 if (resultTargetList)
1816 *resultTargetList = tlist;
1817 return true;
1821 * Verify that the targetlist matches the return tuple type. We scan
1822 * the non-resjunk columns, and coerce them if necessary to match the
1823 * datatypes of the non-deleted attributes. For deleted attributes,
1824 * insert NULL result columns if the caller asked for that.
1826 tupnatts = rettupdesc->natts;
1827 tuplogcols = 0; /* we'll count nondeleted cols as we go */
1828 colindex = 0;
1830 foreach(lc, tlist)
1832 TargetEntry *tle = (TargetEntry *) lfirst(lc);
1833 Form_pg_attribute attr;
1835 /* resjunk columns can simply be ignored */
1836 if (tle->resjunk)
1837 continue;
1841 colindex++;
1842 if (colindex > tupnatts)
1843 ereport(ERROR,
1844 (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
1845 errmsg("return type mismatch in function declared to return %s",
1846 format_type_be(rettype)),
1847 errdetail("Final statement returns too many columns.")));
1848 attr = TupleDescAttr(rettupdesc, colindex - 1);
1849 if (attr->attisdropped && insertDroppedCols)
1851 Expr *null_expr;
1853 /* The type of the null we insert isn't important */
1854 null_expr = (Expr *) makeConst(INT4OID,
1856 InvalidOid,
1857 sizeof(int32),
1858 (Datum) 0,
1859 true, /* isnull */
1860 true /* byval */ );
1861 upper_tlist = lappend(upper_tlist,
1862 makeTargetEntry(null_expr,
1863 list_length(upper_tlist) + 1,
1864 NULL,
1865 false));
1866 upper_tlist_nontrivial = true;
1868 } while (attr->attisdropped);
1869 tuplogcols++;
1871 if (!coerce_fn_result_column(tle,
1872 attr->atttypid, attr->atttypmod,
1873 tlist_is_modifiable,
1874 &upper_tlist,
1875 &upper_tlist_nontrivial))
1876 ereport(ERROR,
1877 (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
1878 errmsg("return type mismatch in function declared to return %s",
1879 format_type_be(rettype)),
1880 errdetail("Final statement returns %s instead of %s at column %d.",
1881 format_type_be(exprType((Node *) tle->expr)),
1882 format_type_be(attr->atttypid),
1883 tuplogcols)));
1886 /* remaining columns in rettupdesc had better all be dropped */
1887 for (colindex++; colindex <= tupnatts; colindex++)
1889 if (!TupleDescCompactAttr(rettupdesc, colindex - 1)->attisdropped)
1890 ereport(ERROR,
1891 (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
1892 errmsg("return type mismatch in function declared to return %s",
1893 format_type_be(rettype)),
1894 errdetail("Final statement returns too few columns.")));
1895 if (insertDroppedCols)
1897 Expr *null_expr;
1899 /* The type of the null we insert isn't important */
1900 null_expr = (Expr *) makeConst(INT4OID,
1902 InvalidOid,
1903 sizeof(int32),
1904 (Datum) 0,
1905 true, /* isnull */
1906 true /* byval */ );
1907 upper_tlist = lappend(upper_tlist,
1908 makeTargetEntry(null_expr,
1909 list_length(upper_tlist) + 1,
1910 NULL,
1911 false));
1912 upper_tlist_nontrivial = true;
1916 /* Report that we are returning entire tuple result */
1917 is_tuple_result = true;
1919 else
1920 ereport(ERROR,
1921 (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
1922 errmsg("return type %s is not supported for SQL functions",
1923 format_type_be(rettype))));
1925 tlist_coercion_finished:
1928 * If necessary, modify the final Query by injecting an extra Query level
1929 * that just performs a projection. (It'd be dubious to do this to a
1930 * non-SELECT query, but we never have to; RETURNING lists can always be
1931 * modified in-place.)
1933 if (upper_tlist_nontrivial)
1935 Query *newquery;
1936 List *colnames;
1937 RangeTblEntry *rte;
1938 RangeTblRef *rtr;
1940 Assert(parse->commandType == CMD_SELECT);
1942 /* Most of the upper Query struct can be left as zeroes/nulls */
1943 newquery = makeNode(Query);
1944 newquery->commandType = CMD_SELECT;
1945 newquery->querySource = parse->querySource;
1946 newquery->canSetTag = true;
1947 newquery->targetList = upper_tlist;
1949 /* We need a moderately realistic colnames list for the subquery RTE */
1950 colnames = NIL;
1951 foreach(lc, parse->targetList)
1953 TargetEntry *tle = (TargetEntry *) lfirst(lc);
1955 if (tle->resjunk)
1956 continue;
1957 colnames = lappend(colnames,
1958 makeString(tle->resname ? tle->resname : ""));
1961 /* Build a suitable RTE for the subquery */
1962 rte = makeNode(RangeTblEntry);
1963 rte->rtekind = RTE_SUBQUERY;
1964 rte->subquery = parse;
1965 rte->eref = rte->alias = makeAlias("*SELECT*", colnames);
1966 rte->lateral = false;
1967 rte->inh = false;
1968 rte->inFromCl = true;
1969 newquery->rtable = list_make1(rte);
1971 rtr = makeNode(RangeTblRef);
1972 rtr->rtindex = 1;
1973 newquery->jointree = makeFromExpr(list_make1(rtr), NULL);
1976 * Make sure the new query is marked as having row security if the
1977 * original one does.
1979 newquery->hasRowSecurity = parse->hasRowSecurity;
1981 /* Replace original query in the correct element of the query list */
1982 lfirst(parse_cell) = newquery;
1985 /* Return tlist (possibly modified) if requested */
1986 if (resultTargetList)
1987 *resultTargetList = upper_tlist;
1989 return is_tuple_result;
1993 * Process one function result column for check_sql_fn_retval
1995 * Coerce the output value to the required type/typmod, and add a column
1996 * to *upper_tlist for it. Set *upper_tlist_nontrivial to true if we
1997 * add an upper tlist item that's not just a Var.
1999 * Returns true if OK, false if could not coerce to required type
2000 * (in which case, no changes have been made)
2002 static bool
2003 coerce_fn_result_column(TargetEntry *src_tle,
2004 Oid res_type,
2005 int32 res_typmod,
2006 bool tlist_is_modifiable,
2007 List **upper_tlist,
2008 bool *upper_tlist_nontrivial)
2010 TargetEntry *new_tle;
2011 Expr *new_tle_expr;
2012 Node *cast_result;
2015 * If the TLE has a sortgroupref marking, don't change it, as it probably
2016 * is referenced by ORDER BY, DISTINCT, etc, and changing its type would
2017 * break query semantics. Otherwise, it's safe to modify in-place unless
2018 * the query as a whole has issues with that.
2020 if (tlist_is_modifiable && src_tle->ressortgroupref == 0)
2022 /* OK to modify src_tle in place, if necessary */
2023 cast_result = coerce_to_target_type(NULL,
2024 (Node *) src_tle->expr,
2025 exprType((Node *) src_tle->expr),
2026 res_type, res_typmod,
2027 COERCION_ASSIGNMENT,
2028 COERCE_IMPLICIT_CAST,
2029 -1);
2030 if (cast_result == NULL)
2031 return false;
2032 assign_expr_collations(NULL, cast_result);
2033 src_tle->expr = (Expr *) cast_result;
2034 /* Make a Var referencing the possibly-modified TLE */
2035 new_tle_expr = (Expr *) makeVarFromTargetEntry(1, src_tle);
2037 else
2039 /* Any casting must happen in the upper tlist */
2040 Var *var = makeVarFromTargetEntry(1, src_tle);
2042 cast_result = coerce_to_target_type(NULL,
2043 (Node *) var,
2044 var->vartype,
2045 res_type, res_typmod,
2046 COERCION_ASSIGNMENT,
2047 COERCE_IMPLICIT_CAST,
2048 -1);
2049 if (cast_result == NULL)
2050 return false;
2051 assign_expr_collations(NULL, cast_result);
2052 /* Did the coercion actually do anything? */
2053 if (cast_result != (Node *) var)
2054 *upper_tlist_nontrivial = true;
2055 new_tle_expr = (Expr *) cast_result;
2057 new_tle = makeTargetEntry(new_tle_expr,
2058 list_length(*upper_tlist) + 1,
2059 src_tle->resname, false);
2060 *upper_tlist = lappend(*upper_tlist, new_tle);
2061 return true;
2066 * CreateSQLFunctionDestReceiver -- create a suitable DestReceiver object
2068 DestReceiver *
2069 CreateSQLFunctionDestReceiver(void)
2071 DR_sqlfunction *self = (DR_sqlfunction *) palloc0(sizeof(DR_sqlfunction));
2073 self->pub.receiveSlot = sqlfunction_receive;
2074 self->pub.rStartup = sqlfunction_startup;
2075 self->pub.rShutdown = sqlfunction_shutdown;
2076 self->pub.rDestroy = sqlfunction_destroy;
2077 self->pub.mydest = DestSQLFunction;
2079 /* private fields will be set by postquel_start */
2081 return (DestReceiver *) self;
2085 * sqlfunction_startup --- executor startup
2087 static void
2088 sqlfunction_startup(DestReceiver *self, int operation, TupleDesc typeinfo)
2090 /* no-op */
2094 * sqlfunction_receive --- receive one tuple
2096 static bool
2097 sqlfunction_receive(TupleTableSlot *slot, DestReceiver *self)
2099 DR_sqlfunction *myState = (DR_sqlfunction *) self;
2101 /* Filter tuple as needed */
2102 slot = ExecFilterJunk(myState->filter, slot);
2104 /* Store the filtered tuple into the tuplestore */
2105 tuplestore_puttupleslot(myState->tstore, slot);
2107 return true;
2111 * sqlfunction_shutdown --- executor end
2113 static void
2114 sqlfunction_shutdown(DestReceiver *self)
2116 /* no-op */
2120 * sqlfunction_destroy --- release DestReceiver object
2122 static void
2123 sqlfunction_destroy(DestReceiver *self)
2125 pfree(self);