Line data Source code
1 : /*-------------------------------------------------------------------------
2 : *
3 : * functions.c
4 : * Execution of SQL-language functions
5 : *
6 : * Portions Copyright (c) 1996-2025, PostgreSQL Global Development Group
7 : * Portions Copyright (c) 1994, Regents of the University of California
8 : *
9 : *
10 : * IDENTIFICATION
11 : * src/backend/executor/functions.c
12 : *
13 : *-------------------------------------------------------------------------
14 : */
15 : #include "postgres.h"
16 :
17 : #include "access/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"
38 :
39 :
40 : /*
41 : * Specialized DestReceiver for collecting query output in a SQL function
42 : */
43 : typedef struct
44 : {
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;
50 :
51 : /*
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.
55 : *
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.)
59 : */
60 : typedef enum
61 : {
62 : F_EXEC_START, F_EXEC_RUN, F_EXEC_DONE,
63 : } ExecStatus;
64 :
65 : typedef struct execution_state
66 : {
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;
74 :
75 :
76 : /*
77 : * An SQLFunctionCache record is built during the first call,
78 : * and linked to from the fn_extra field of the FmgrInfo struct.
79 : *
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.
83 : *
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.
92 : */
93 : typedef struct
94 : {
95 : char *fname; /* function name (for error msgs) */
96 : char *src; /* function body text (for error msgs) */
97 :
98 : SQLFunctionParseInfoPtr pinfo; /* data for parser callback hooks */
99 :
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 */
108 :
109 : ParamListInfo paramLI; /* Param list representing current args */
110 :
111 : Tuplestorestate *tstore; /* where we accumulate result tuples */
112 :
113 : JunkFilter *junkFilter; /* will be NULL if function returns VOID */
114 :
115 : /*
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.
120 : */
121 : List *func_state;
122 :
123 : MemoryContext fcontext; /* memory context holding this struct and all
124 : * subsidiary data */
125 :
126 : LocalTransactionId lxid; /* lxid in which cache was made */
127 : SubTransactionId subxid; /* subxid in which cache was made */
128 : } SQLFunctionCache;
129 :
130 : typedef SQLFunctionCache *SQLFunctionCachePtr;
131 :
132 :
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);
165 :
166 :
167 : /*
168 : * Prepare the SQLFunctionParseInfo struct for parsing a SQL function body
169 : *
170 : * This includes resolving actual types of polymorphic arguments.
171 : *
172 : * call_expr can be passed as NULL, but then we will fail if there are any
173 : * polymorphic arguments.
174 : */
175 : SQLFunctionParseInfoPtr
176 56692 : prepare_sql_fn_parse_info(HeapTuple procedureTuple,
177 : Node *call_expr,
178 : Oid inputCollation)
179 : {
180 : SQLFunctionParseInfoPtr pinfo;
181 56692 : Form_pg_proc procedureStruct = (Form_pg_proc) GETSTRUCT(procedureTuple);
182 : int nargs;
183 :
184 56692 : pinfo = (SQLFunctionParseInfoPtr) palloc0(sizeof(SQLFunctionParseInfo));
185 :
186 : /* Function's name (only) can be used to qualify argument names */
187 56692 : pinfo->fname = pstrdup(NameStr(procedureStruct->proname));
188 :
189 : /* Save the function's input collation */
190 56692 : pinfo->collation = inputCollation;
191 :
192 : /*
193 : * Copy input argument types from the pg_proc entry, then resolve any
194 : * polymorphic types.
195 : */
196 56692 : pinfo->nargs = nargs = procedureStruct->pronargs;
197 56692 : if (nargs > 0)
198 : {
199 : Oid *argOidVect;
200 : int argnum;
201 :
202 37300 : argOidVect = (Oid *) palloc(nargs * sizeof(Oid));
203 37300 : memcpy(argOidVect,
204 37300 : procedureStruct->proargtypes.values,
205 : nargs * sizeof(Oid));
206 :
207 109424 : for (argnum = 0; argnum < nargs; argnum++)
208 : {
209 72124 : Oid argtype = argOidVect[argnum];
210 :
211 72124 : if (IsPolymorphicType(argtype))
212 : {
213 2968 : argtype = get_call_expr_argtype(call_expr, argnum);
214 2968 : if (argtype == InvalidOid)
215 0 : 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 2968 : argOidVect[argnum] = argtype;
220 : }
221 : }
222 :
223 37300 : pinfo->argtypes = argOidVect;
224 : }
225 :
226 : /*
227 : * Collect names of arguments, too, if any
228 : */
229 56692 : if (nargs > 0)
230 : {
231 : Datum proargnames;
232 : Datum proargmodes;
233 : int n_arg_names;
234 : bool isNull;
235 :
236 37300 : proargnames = SysCacheGetAttr(PROCNAMEARGSNSP, procedureTuple,
237 : Anum_pg_proc_proargnames,
238 : &isNull);
239 37300 : if (isNull)
240 30406 : proargnames = PointerGetDatum(NULL); /* just to be sure */
241 :
242 37300 : proargmodes = SysCacheGetAttr(PROCNAMEARGSNSP, procedureTuple,
243 : Anum_pg_proc_proargmodes,
244 : &isNull);
245 37300 : if (isNull)
246 36404 : proargmodes = PointerGetDatum(NULL); /* just to be sure */
247 :
248 37300 : n_arg_names = get_func_input_arg_names(proargnames, proargmodes,
249 : &pinfo->argnames);
250 :
251 : /* Paranoia: ignore the result if too few array entries */
252 37300 : if (n_arg_names < nargs)
253 30406 : pinfo->argnames = NULL;
254 : }
255 : else
256 19392 : pinfo->argnames = NULL;
257 :
258 56692 : return pinfo;
259 : }
260 :
261 : /*
262 : * Parser setup hook for parsing a SQL function body.
263 : */
264 : void
265 56534 : sql_fn_parser_setup(struct ParseState *pstate, SQLFunctionParseInfoPtr pinfo)
266 : {
267 56534 : pstate->p_pre_columnref_hook = NULL;
268 56534 : pstate->p_post_columnref_hook = sql_fn_post_column_ref;
269 56534 : pstate->p_paramref_hook = sql_fn_param_ref;
270 : /* no need to use p_coerce_param_hook */
271 56534 : pstate->p_ref_hook_state = pinfo;
272 56534 : }
273 :
274 : /*
275 : * sql_fn_post_column_ref parser callback for ColumnRefs
276 : */
277 : static Node *
278 12684 : sql_fn_post_column_ref(ParseState *pstate, ColumnRef *cref, Node *var)
279 : {
280 12684 : SQLFunctionParseInfoPtr pinfo = (SQLFunctionParseInfoPtr) pstate->p_ref_hook_state;
281 : int nnames;
282 : Node *field1;
283 12684 : Node *subfield = NULL;
284 : const char *name1;
285 12684 : const char *name2 = NULL;
286 : Node *param;
287 :
288 : /*
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.
292 : */
293 12684 : if (var != NULL)
294 9900 : return NULL;
295 :
296 : /*----------
297 : * The allowed syntaxes are:
298 : *
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
307 : *
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 : *----------
311 : */
312 2784 : nnames = list_length(cref->fields);
313 :
314 2784 : if (nnames > 3)
315 0 : return NULL;
316 :
317 2784 : if (IsA(llast(cref->fields), A_Star))
318 54 : nnames--;
319 :
320 2784 : field1 = (Node *) linitial(cref->fields);
321 2784 : name1 = strVal(field1);
322 2784 : if (nnames > 1)
323 : {
324 156 : subfield = (Node *) lsecond(cref->fields);
325 156 : name2 = strVal(subfield);
326 : }
327 :
328 2784 : if (nnames == 3)
329 : {
330 : /*
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.
334 : */
335 24 : if (strcmp(name1, pinfo->fname) != 0)
336 0 : return NULL;
337 :
338 24 : param = sql_fn_resolve_param_name(pinfo, name2, cref->location);
339 :
340 24 : subfield = (Node *) lthird(cref->fields);
341 : Assert(IsA(subfield, String));
342 : }
343 2760 : else if (nnames == 2 && strcmp(name1, pinfo->fname) == 0)
344 : {
345 : /*
346 : * Two-part name with first part matching function name: first see if
347 : * second part matches any parameter name.
348 : */
349 24 : param = sql_fn_resolve_param_name(pinfo, name2, cref->location);
350 :
351 24 : if (param)
352 : {
353 : /* Yes, so this is a parameter reference, no subfield */
354 24 : subfield = NULL;
355 : }
356 : else
357 : {
358 : /* No, so try to match as parameter name and subfield */
359 0 : param = sql_fn_resolve_param_name(pinfo, name1, cref->location);
360 : }
361 : }
362 : else
363 : {
364 : /* Single name, or parameter name followed by subfield */
365 2736 : param = sql_fn_resolve_param_name(pinfo, name1, cref->location);
366 : }
367 :
368 2784 : if (!param)
369 0 : return NULL; /* No match */
370 :
371 2784 : if (subfield)
372 : {
373 : /*
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.
377 : */
378 132 : param = ParseFuncOrColumn(pstate,
379 132 : list_make1(subfield),
380 132 : list_make1(param),
381 : pstate->p_last_srf,
382 : NULL,
383 : false,
384 : cref->location);
385 : }
386 :
387 2784 : return param;
388 : }
389 :
390 : /*
391 : * sql_fn_param_ref parser callback for ParamRefs ($n symbols)
392 : */
393 : static Node *
394 121730 : sql_fn_param_ref(ParseState *pstate, ParamRef *pref)
395 : {
396 121730 : SQLFunctionParseInfoPtr pinfo = (SQLFunctionParseInfoPtr) pstate->p_ref_hook_state;
397 121730 : int paramno = pref->number;
398 :
399 : /* Check parameter number is valid */
400 121730 : if (paramno <= 0 || paramno > pinfo->nargs)
401 6 : return NULL; /* unknown parameter number */
402 :
403 121724 : return sql_fn_make_param(pinfo, paramno, pref->location);
404 : }
405 :
406 : /*
407 : * sql_fn_make_param construct a Param node for the given paramno
408 : */
409 : static Node *
410 124508 : sql_fn_make_param(SQLFunctionParseInfoPtr pinfo,
411 : int paramno, int location)
412 : {
413 : Param *param;
414 :
415 124508 : param = makeNode(Param);
416 124508 : param->paramkind = PARAM_EXTERN;
417 124508 : param->paramid = paramno;
418 124508 : param->paramtype = pinfo->argtypes[paramno - 1];
419 124508 : param->paramtypmod = -1;
420 124508 : param->paramcollid = get_typcollation(param->paramtype);
421 124508 : param->location = location;
422 :
423 : /*
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?)
427 : */
428 124508 : if (OidIsValid(pinfo->collation) && OidIsValid(param->paramcollid))
429 2522 : param->paramcollid = pinfo->collation;
430 :
431 124508 : return (Node *) param;
432 : }
433 :
434 : /*
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.
438 : */
439 : static Node *
440 2784 : sql_fn_resolve_param_name(SQLFunctionParseInfoPtr pinfo,
441 : const char *paramname, int location)
442 : {
443 : int i;
444 :
445 2784 : if (pinfo->argnames == NULL)
446 0 : return NULL;
447 :
448 3986 : for (i = 0; i < pinfo->nargs; i++)
449 : {
450 3986 : if (pinfo->argnames[i] && strcmp(pinfo->argnames[i], paramname) == 0)
451 2784 : return sql_fn_make_param(pinfo, i + 1, location);
452 : }
453 :
454 0 : return NULL;
455 : }
456 :
457 : /*
458 : * Set up the per-query execution_state records for a SQL function.
459 : *
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.
462 : */
463 : static List *
464 35856 : init_execution_state(List *queryTree_list,
465 : SQLFunctionCachePtr fcache,
466 : bool lazyEvalOK)
467 : {
468 35856 : List *eslist = NIL;
469 35856 : execution_state *lasttages = NULL;
470 : ListCell *lc1;
471 :
472 71836 : foreach(lc1, queryTree_list)
473 : {
474 35986 : List *qtlist = lfirst_node(List, lc1);
475 35986 : execution_state *firstes = NULL;
476 35986 : execution_state *preves = NULL;
477 : ListCell *lc2;
478 :
479 71972 : foreach(lc2, qtlist)
480 : {
481 35992 : Query *queryTree = lfirst_node(Query, lc2);
482 : PlannedStmt *stmt;
483 : execution_state *newes;
484 :
485 : /* Plan the query if needed */
486 35992 : if (queryTree->commandType == CMD_UTILITY)
487 : {
488 : /* Utility commands require no planning. */
489 168 : stmt = makeNode(PlannedStmt);
490 168 : stmt->commandType = CMD_UTILITY;
491 168 : stmt->canSetTag = queryTree->canSetTag;
492 168 : stmt->utilityStmt = queryTree->utilityStmt;
493 168 : stmt->stmt_location = queryTree->stmt_location;
494 168 : stmt->stmt_len = queryTree->stmt_len;
495 168 : stmt->queryId = queryTree->queryId;
496 : }
497 : else
498 35824 : stmt = pg_plan_query(queryTree,
499 35824 : fcache->src,
500 : CURSOR_OPT_PARALLEL_OK,
501 : NULL);
502 :
503 : /*
504 : * Precheck all commands for validity in a function. This should
505 : * generally match the restrictions spi.c applies.
506 : */
507 35986 : if (stmt->commandType == CMD_UTILITY)
508 : {
509 168 : if (IsA(stmt->utilityStmt, CopyStmt) &&
510 0 : ((CopyStmt *) stmt->utilityStmt)->filename == NULL)
511 0 : ereport(ERROR,
512 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
513 : errmsg("cannot COPY to/from client in an SQL function")));
514 :
515 168 : if (IsA(stmt->utilityStmt, TransactionStmt))
516 0 : 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))));
521 : }
522 :
523 35986 : if (fcache->readonly_func && !CommandIsReadOnly(stmt))
524 0 : 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))));
529 :
530 : /* OK, build the execution_state for this query */
531 35986 : newes = (execution_state *) palloc(sizeof(execution_state));
532 35986 : if (preves)
533 6 : preves->next = newes;
534 : else
535 35980 : firstes = newes;
536 :
537 35986 : newes->next = NULL;
538 35986 : newes->status = F_EXEC_START;
539 35986 : newes->setsResult = false; /* might change below */
540 35986 : newes->lazyEval = false; /* might change below */
541 35986 : newes->stmt = stmt;
542 35986 : newes->qd = NULL;
543 :
544 35986 : if (queryTree->canSetTag)
545 35980 : lasttages = newes;
546 :
547 35986 : preves = newes;
548 : }
549 :
550 35980 : eslist = lappend(eslist, firstes);
551 : }
552 :
553 : /*
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.
557 : *
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.
562 : *
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.
566 : */
567 35850 : if (lasttages && fcache->junkFilter)
568 : {
569 35562 : lasttages->setsResult = true;
570 35562 : if (lazyEvalOK &&
571 34914 : lasttages->stmt->commandType == CMD_SELECT &&
572 34848 : !lasttages->stmt->hasModifyingCTE)
573 34848 : fcache->lazyEval = lasttages->lazyEval = true;
574 : }
575 :
576 35850 : return eslist;
577 : }
578 :
579 : /*
580 : * Initialize the SQLFunctionCache for a SQL function
581 : */
582 : static void
583 35864 : init_sql_fcache(FunctionCallInfo fcinfo, Oid collation, bool lazyEvalOK)
584 : {
585 35864 : FmgrInfo *finfo = fcinfo->flinfo;
586 35864 : 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;
599 :
600 : /*
601 : * Create memory context that holds all the SQLFunctionCache data. It
602 : * must be a child of whatever context holds the FmgrInfo.
603 : */
604 35864 : fcontext = AllocSetContextCreate(finfo->fn_mcxt,
605 : "SQL function",
606 : ALLOCSET_DEFAULT_SIZES);
607 :
608 35864 : oldcontext = MemoryContextSwitchTo(fcontext);
609 :
610 : /*
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.
614 : */
615 35864 : fcache = (SQLFunctionCachePtr) palloc0(sizeof(SQLFunctionCache));
616 35864 : fcache->fcontext = fcontext;
617 35864 : finfo->fn_extra = fcache;
618 :
619 : /*
620 : * get the procedure tuple corresponding to the given function Oid
621 : */
622 35864 : procedureTuple = SearchSysCache1(PROCOID, ObjectIdGetDatum(foid));
623 35864 : if (!HeapTupleIsValid(procedureTuple))
624 0 : elog(ERROR, "cache lookup failed for function %u", foid);
625 35864 : procedureStruct = (Form_pg_proc) GETSTRUCT(procedureTuple);
626 :
627 : /*
628 : * copy function name immediately for use by error reporting callback, and
629 : * for use as memory context identifier
630 : */
631 35864 : fcache->fname = pstrdup(NameStr(procedureStruct->proname));
632 35864 : MemoryContextSetIdentifier(fcontext, fcache->fname);
633 :
634 : /*
635 : * Resolve any polymorphism, obtaining the actual result type, and the
636 : * corresponding tupdesc if it's a rowtype.
637 : */
638 35864 : (void) get_call_result_type(fcinfo, &rettype, &rettupdesc);
639 :
640 35864 : fcache->rettype = rettype;
641 :
642 : /* Fetch the typlen and byval info for the result type */
643 35864 : get_typlenbyval(rettype, &fcache->typlen, &fcache->typbyval);
644 :
645 : /* Remember whether we're returning setof something */
646 35864 : fcache->returnsSet = procedureStruct->proretset;
647 :
648 : /* Remember if function is STABLE/IMMUTABLE */
649 35864 : fcache->readonly_func =
650 35864 : (procedureStruct->provolatile != PROVOLATILE_VOLATILE);
651 :
652 : /*
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.
656 : */
657 71728 : fcache->pinfo = prepare_sql_fn_parse_info(procedureTuple,
658 35864 : finfo->fn_expr,
659 : collation);
660 :
661 : /*
662 : * And of course we need the function body text.
663 : */
664 35864 : tmp = SysCacheGetAttrNotNull(PROCOID, procedureTuple, Anum_pg_proc_prosrc);
665 35864 : fcache->src = TextDatumGetCString(tmp);
666 :
667 : /* If we have prosqlbody, pay attention to that not prosrc. */
668 35864 : tmp = SysCacheGetAttr(PROCOID,
669 : procedureTuple,
670 : Anum_pg_proc_prosqlbody,
671 : &isNull);
672 :
673 : /*
674 : * Parse and rewrite the queries in the function text. Use sublists to
675 : * keep track of the original query boundaries.
676 : *
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.
681 : */
682 35864 : queryTree_list = NIL;
683 35864 : if (!isNull)
684 : {
685 : Node *n;
686 : List *stored_query_list;
687 :
688 5430 : n = stringToNode(TextDatumGetCString(tmp));
689 5430 : if (IsA(n, List))
690 2160 : stored_query_list = linitial_node(List, castNode(List, n));
691 : else
692 3270 : stored_query_list = list_make1(n);
693 :
694 10860 : foreach(lc, stored_query_list)
695 : {
696 5430 : Query *parsetree = lfirst_node(Query, lc);
697 : List *queryTree_sublist;
698 :
699 5430 : AcquireRewriteLocks(parsetree, true, false);
700 5430 : queryTree_sublist = pg_rewrite_query(parsetree);
701 5430 : queryTree_list = lappend(queryTree_list, queryTree_sublist);
702 : }
703 : }
704 : else
705 : {
706 : List *raw_parsetree_list;
707 :
708 30434 : raw_parsetree_list = pg_parse_query(fcache->src);
709 :
710 60996 : foreach(lc, raw_parsetree_list)
711 : {
712 30564 : RawStmt *parsetree = lfirst_node(RawStmt, lc);
713 : List *queryTree_sublist;
714 :
715 30564 : queryTree_sublist = pg_analyze_and_rewrite_withcb(parsetree,
716 30564 : fcache->src,
717 : (ParserSetupHook) sql_fn_parser_setup,
718 30564 : fcache->pinfo,
719 : NULL);
720 30562 : queryTree_list = lappend(queryTree_list, queryTree_sublist);
721 : }
722 : }
723 :
724 : /*
725 : * Check that there are no statements we don't want to allow.
726 : */
727 35862 : check_sql_fn_statements(queryTree_list);
728 :
729 : /*
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.)
738 : *
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.)
746 : */
747 71718 : fcache->returnsTuple = check_sql_fn_retval(queryTree_list,
748 : rettype,
749 : rettupdesc,
750 35862 : procedureStruct->prokind,
751 : false,
752 : &resulttlist);
753 :
754 : /*
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.)
760 : */
761 35856 : if (rettype != VOIDOID)
762 : {
763 35568 : TupleTableSlot *slot = MakeSingleTupleTableSlot(NULL,
764 : &TTSOpsMinimalTuple);
765 :
766 : /*
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.
773 : */
774 35568 : if (rettupdesc && fcache->returnsTuple)
775 1272 : fcache->junkFilter = ExecInitJunkFilterConversion(resulttlist,
776 : rettupdesc,
777 : slot);
778 : else
779 34296 : fcache->junkFilter = ExecInitJunkFilter(resulttlist, slot);
780 : }
781 :
782 35856 : if (fcache->returnsTuple)
783 : {
784 : /* Make sure output rowtype is properly blessed */
785 1296 : BlessTupleDesc(fcache->junkFilter->jf_resultSlot->tts_tupleDescriptor);
786 : }
787 34560 : else if (fcache->returnsSet && type_is_rowtype(fcache->rettype))
788 : {
789 : /*
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.
794 : */
795 0 : lazyEvalOK = true;
796 : }
797 :
798 : /* Finally, plan the queries */
799 35856 : fcache->func_state = init_execution_state(queryTree_list,
800 : fcache,
801 : lazyEvalOK);
802 :
803 : /* Mark fcache with time of creation to show it's valid */
804 35850 : fcache->lxid = MyProc->vxid.lxid;
805 35850 : fcache->subxid = GetCurrentSubTransactionId();
806 :
807 35850 : ReleaseSysCache(procedureTuple);
808 :
809 35850 : MemoryContextSwitchTo(oldcontext);
810 35850 : }
811 :
812 : /* Start up execution of one execution_state node */
813 : static void
814 167524 : postquel_start(execution_state *es, SQLFunctionCachePtr fcache)
815 : {
816 : DestReceiver *dest;
817 :
818 : Assert(es->qd == NULL);
819 :
820 : /* Caller should have ensured a suitable snapshot is active */
821 : Assert(ActiveSnapshotSet());
822 :
823 : /*
824 : * If this query produces the function result, send its output to the
825 : * tuplestore; else discard any output.
826 : */
827 167524 : if (es->setsResult)
828 : {
829 : DR_sqlfunction *myState;
830 :
831 127110 : dest = CreateDestReceiver(DestSQLFunction);
832 : /* pass down the needed info to the dest receiver routines */
833 127110 : myState = (DR_sqlfunction *) dest;
834 : Assert(myState->pub.mydest == DestSQLFunction);
835 127110 : myState->tstore = fcache->tstore;
836 127110 : myState->cxt = CurrentMemoryContext;
837 127110 : myState->filter = fcache->junkFilter;
838 : }
839 : else
840 40414 : dest = None_Receiver;
841 :
842 167524 : es->qd = CreateQueryDesc(es->stmt,
843 : NULL,
844 167524 : fcache->src,
845 : GetActiveSnapshot(),
846 : InvalidSnapshot,
847 : dest,
848 : fcache->paramLI,
849 167524 : es->qd ? es->qd->queryEnv : NULL,
850 : 0);
851 :
852 : /* Utility commands don't need Executor. */
853 167524 : if (es->qd->operation != CMD_UTILITY)
854 : {
855 : /*
856 : * In lazyEval mode, do not let the executor set up an AfterTrigger
857 : * context. This is necessary not just an optimization, because we
858 : * mustn't exit from the function execution with a stacked
859 : * AfterTrigger level still active. We are careful not to select
860 : * lazyEval mode for any statement that could possibly queue triggers.
861 : */
862 : int eflags;
863 :
864 167356 : if (es->lazyEval)
865 126198 : eflags = EXEC_FLAG_SKIP_TRIGGERS;
866 : else
867 41158 : eflags = 0; /* default run-to-completion flags */
868 167356 : if (!ExecutorStart(es->qd, eflags))
869 0 : elog(ERROR, "ExecutorStart() failed unexpectedly");
870 : }
871 :
872 167524 : es->status = F_EXEC_RUN;
873 167524 : }
874 :
875 : /* Run one execution_state; either to completion or to first result row */
876 : /* Returns true if we ran to completion */
877 : static bool
878 168488 : postquel_getnext(execution_state *es, SQLFunctionCachePtr fcache)
879 : {
880 : bool result;
881 :
882 168488 : if (es->qd->operation == CMD_UTILITY)
883 : {
884 168 : ProcessUtility(es->qd->plannedstmt,
885 168 : fcache->src,
886 : true, /* protect function cache's parsetree */
887 : PROCESS_UTILITY_QUERY,
888 168 : es->qd->params,
889 168 : es->qd->queryEnv,
890 168 : es->qd->dest,
891 : NULL);
892 78 : result = true; /* never stops early */
893 : }
894 : else
895 : {
896 : /* Run regular commands to completion unless lazyEval */
897 168320 : uint64 count = (es->lazyEval) ? 1 : 0;
898 :
899 168320 : ExecutorRun(es->qd, ForwardScanDirection, count);
900 :
901 : /*
902 : * If we requested run to completion OR there was no tuple returned,
903 : * command must be complete.
904 : */
905 160272 : result = (count == 0 || es->qd->estate->es_processed == 0);
906 : }
907 :
908 160350 : return result;
909 : }
910 :
911 : /* Shut down execution of one execution_state node */
912 : static void
913 159386 : postquel_end(execution_state *es)
914 : {
915 : /* mark status done to ensure we don't do ExecutorEnd twice */
916 159386 : es->status = F_EXEC_DONE;
917 :
918 : /* Utility commands don't need Executor. */
919 159386 : if (es->qd->operation != CMD_UTILITY)
920 : {
921 159308 : ExecutorFinish(es->qd);
922 159290 : ExecutorEnd(es->qd);
923 : }
924 :
925 159368 : es->qd->dest->rDestroy(es->qd->dest);
926 :
927 159368 : FreeQueryDesc(es->qd);
928 159368 : es->qd = NULL;
929 159368 : }
930 :
931 : /* Build ParamListInfo array representing current arguments */
932 : static void
933 127422 : postquel_sub_params(SQLFunctionCachePtr fcache,
934 : FunctionCallInfo fcinfo)
935 : {
936 127422 : int nargs = fcinfo->nargs;
937 :
938 127422 : if (nargs > 0)
939 : {
940 : ParamListInfo paramLI;
941 116824 : Oid *argtypes = fcache->pinfo->argtypes;
942 :
943 116824 : if (fcache->paramLI == NULL)
944 : {
945 25282 : paramLI = makeParamList(nargs);
946 25282 : fcache->paramLI = paramLI;
947 : }
948 : else
949 : {
950 91542 : paramLI = fcache->paramLI;
951 : Assert(paramLI->numParams == nargs);
952 : }
953 :
954 346458 : for (int i = 0; i < nargs; i++)
955 : {
956 229634 : ParamExternData *prm = ¶mLI->params[i];
957 :
958 : /*
959 : * If an incoming parameter value is a R/W expanded datum, we
960 : * force it to R/O. We'd be perfectly entitled to scribble on it,
961 : * but the problem is that if the parameter is referenced more
962 : * than once in the function, earlier references might mutate the
963 : * value seen by later references, which won't do at all. We
964 : * could do better if we could be sure of the number of Param
965 : * nodes in the function's plans; but we might not have planned
966 : * all the statements yet, nor do we have plan tree walker
967 : * infrastructure. (Examining the parse trees is not good enough,
968 : * because of possible function inlining during planning.)
969 : */
970 229634 : prm->isnull = fcinfo->args[i].isnull;
971 229634 : prm->value = MakeExpandedObjectReadOnly(fcinfo->args[i].value,
972 : prm->isnull,
973 : get_typlen(argtypes[i]));
974 229634 : prm->pflags = 0;
975 229634 : prm->ptype = argtypes[i];
976 : }
977 : }
978 : else
979 10598 : fcache->paramLI = NULL;
980 127422 : }
981 :
982 : /*
983 : * Extract the SQL function's value from a single result row. This is used
984 : * both for scalar (non-set) functions and for each row of a lazy-eval set
985 : * result.
986 : */
987 : static Datum
988 111604 : postquel_get_single_result(TupleTableSlot *slot,
989 : FunctionCallInfo fcinfo,
990 : SQLFunctionCachePtr fcache,
991 : MemoryContext resultcontext)
992 : {
993 : Datum value;
994 : MemoryContext oldcontext;
995 :
996 : /*
997 : * Set up to return the function value. For pass-by-reference datatypes,
998 : * be sure to allocate the result in resultcontext, not the current memory
999 : * context (which has query lifespan). We can't leave the data in the
1000 : * TupleTableSlot because we intend to clear the slot before returning.
1001 : */
1002 111604 : oldcontext = MemoryContextSwitchTo(resultcontext);
1003 :
1004 111604 : if (fcache->returnsTuple)
1005 : {
1006 : /* We must return the whole tuple as a Datum. */
1007 1470 : fcinfo->isnull = false;
1008 1470 : value = ExecFetchSlotHeapTupleDatum(slot);
1009 : }
1010 : else
1011 : {
1012 : /*
1013 : * Returning a scalar, which we have to extract from the first column
1014 : * of the SELECT result, and then copy into result context if needed.
1015 : */
1016 110134 : value = slot_getattr(slot, 1, &(fcinfo->isnull));
1017 :
1018 110134 : if (!fcinfo->isnull)
1019 109798 : value = datumCopy(value, fcache->typbyval, fcache->typlen);
1020 : }
1021 :
1022 111604 : MemoryContextSwitchTo(oldcontext);
1023 :
1024 111604 : return value;
1025 : }
1026 :
1027 : /*
1028 : * fmgr_sql: function call manager for SQL functions
1029 : */
1030 : Datum
1031 128406 : fmgr_sql(PG_FUNCTION_ARGS)
1032 : {
1033 : SQLFunctionCachePtr fcache;
1034 : ErrorContextCallback sqlerrcontext;
1035 : MemoryContext oldcontext;
1036 : bool randomAccess;
1037 : bool lazyEvalOK;
1038 : bool is_first;
1039 : bool pushed_snapshot;
1040 : execution_state *es;
1041 : TupleTableSlot *slot;
1042 : Datum result;
1043 : List *eslist;
1044 : ListCell *eslc;
1045 :
1046 : /*
1047 : * Setup error traceback support for ereport()
1048 : */
1049 128406 : sqlerrcontext.callback = sql_exec_error_callback;
1050 128406 : sqlerrcontext.arg = fcinfo->flinfo;
1051 128406 : sqlerrcontext.previous = error_context_stack;
1052 128406 : error_context_stack = &sqlerrcontext;
1053 :
1054 : /* Check call context */
1055 128406 : if (fcinfo->flinfo->fn_retset)
1056 : {
1057 5010 : ReturnSetInfo *rsi = (ReturnSetInfo *) fcinfo->resultinfo;
1058 :
1059 : /*
1060 : * For simplicity, we require callers to support both set eval modes.
1061 : * There are cases where we must use one or must use the other, and
1062 : * it's not really worthwhile to postpone the check till we know. But
1063 : * note we do not require caller to provide an expectedDesc.
1064 : */
1065 5010 : if (!rsi || !IsA(rsi, ReturnSetInfo) ||
1066 5010 : (rsi->allowedModes & SFRM_ValuePerCall) == 0 ||
1067 5010 : (rsi->allowedModes & SFRM_Materialize) == 0)
1068 0 : ereport(ERROR,
1069 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1070 : errmsg("set-valued function called in context that cannot accept a set")));
1071 5010 : randomAccess = rsi->allowedModes & SFRM_Materialize_Random;
1072 5010 : lazyEvalOK = !(rsi->allowedModes & SFRM_Materialize_Preferred);
1073 : }
1074 : else
1075 : {
1076 123396 : randomAccess = false;
1077 123396 : lazyEvalOK = true;
1078 : }
1079 :
1080 : /*
1081 : * Initialize fcache (build plans) if first time through; or re-initialize
1082 : * if the cache is stale.
1083 : */
1084 128406 : fcache = (SQLFunctionCachePtr) fcinfo->flinfo->fn_extra;
1085 :
1086 128406 : if (fcache != NULL)
1087 : {
1088 92584 : if (fcache->lxid != MyProc->vxid.lxid ||
1089 92542 : !SubTransactionIsActive(fcache->subxid))
1090 : {
1091 : /* It's stale; unlink and delete */
1092 42 : fcinfo->flinfo->fn_extra = NULL;
1093 42 : MemoryContextDelete(fcache->fcontext);
1094 42 : fcache = NULL;
1095 : }
1096 : }
1097 :
1098 128406 : if (fcache == NULL)
1099 : {
1100 35864 : init_sql_fcache(fcinfo, PG_GET_COLLATION(), lazyEvalOK);
1101 35850 : fcache = (SQLFunctionCachePtr) fcinfo->flinfo->fn_extra;
1102 : }
1103 :
1104 : /*
1105 : * Switch to context in which the fcache lives. This ensures that our
1106 : * tuplestore etc will have sufficient lifetime. The sub-executor is
1107 : * responsible for deleting per-tuple information. (XXX in the case of a
1108 : * long-lived FmgrInfo, this policy represents more memory leakage, but
1109 : * it's not entirely clear where to keep stuff instead.)
1110 : */
1111 128392 : oldcontext = MemoryContextSwitchTo(fcache->fcontext);
1112 :
1113 : /*
1114 : * Find first unfinished query in function, and note whether it's the
1115 : * first query.
1116 : */
1117 128392 : eslist = fcache->func_state;
1118 128392 : es = NULL;
1119 128392 : is_first = true;
1120 128392 : foreach(eslc, eslist)
1121 : {
1122 128386 : es = (execution_state *) lfirst(eslc);
1123 :
1124 128386 : while (es && es->status == F_EXEC_DONE)
1125 : {
1126 0 : is_first = false;
1127 0 : es = es->next;
1128 : }
1129 :
1130 128386 : if (es)
1131 128386 : break;
1132 : }
1133 :
1134 : /*
1135 : * Convert params to appropriate format if starting a fresh execution. (If
1136 : * continuing execution, we can re-use prior params.)
1137 : */
1138 128392 : if (is_first && es && es->status == F_EXEC_START)
1139 127422 : postquel_sub_params(fcache, fcinfo);
1140 :
1141 : /*
1142 : * Build tuplestore to hold results, if we don't have one already. Note
1143 : * it's in the query-lifespan context.
1144 : */
1145 128392 : if (!fcache->tstore)
1146 36036 : fcache->tstore = tuplestore_begin_heap(randomAccess, false, work_mem);
1147 :
1148 : /*
1149 : * Execute each command in the function one after another until we either
1150 : * run out of commands or get a result row from a lazily-evaluated SELECT.
1151 : *
1152 : * Notes about snapshot management:
1153 : *
1154 : * In a read-only function, we just use the surrounding query's snapshot.
1155 : *
1156 : * In a non-read-only function, we rely on the fact that we'll never
1157 : * suspend execution between queries of the function: the only reason to
1158 : * suspend execution before completion is if we are returning a row from a
1159 : * lazily-evaluated SELECT. So, when first entering this loop, we'll
1160 : * either start a new query (and push a fresh snapshot) or re-establish
1161 : * the active snapshot from the existing query descriptor. If we need to
1162 : * start a new query in a subsequent execution of the loop, either we need
1163 : * a fresh snapshot (and pushed_snapshot is false) or the existing
1164 : * snapshot is on the active stack and we can just bump its command ID.
1165 : */
1166 128392 : pushed_snapshot = false;
1167 287760 : while (es)
1168 : {
1169 : bool completed;
1170 :
1171 168488 : if (es->status == F_EXEC_START)
1172 : {
1173 : /*
1174 : * If not read-only, be sure to advance the command counter for
1175 : * each command, so that all work to date in this transaction is
1176 : * visible. Take a new snapshot if we don't have one yet,
1177 : * otherwise just bump the command ID in the existing snapshot.
1178 : */
1179 167524 : if (!fcache->readonly_func)
1180 : {
1181 153564 : CommandCounterIncrement();
1182 153564 : if (!pushed_snapshot)
1183 : {
1184 153558 : PushActiveSnapshot(GetTransactionSnapshot());
1185 153558 : pushed_snapshot = true;
1186 : }
1187 : else
1188 6 : UpdateActiveSnapshotCommandId();
1189 : }
1190 :
1191 167524 : postquel_start(es, fcache);
1192 : }
1193 964 : else if (!fcache->readonly_func && !pushed_snapshot)
1194 : {
1195 : /* Re-establish active snapshot when re-entering function */
1196 616 : PushActiveSnapshot(es->qd->snapshot);
1197 616 : pushed_snapshot = true;
1198 : }
1199 :
1200 168488 : completed = postquel_getnext(es, fcache);
1201 :
1202 : /*
1203 : * If we ran the command to completion, we can shut it down now. Any
1204 : * row(s) we need to return are safely stashed in the tuplestore, and
1205 : * we want to be sure that, for example, AFTER triggers get fired
1206 : * before we return anything. Also, if the function doesn't return
1207 : * set, we can shut it down anyway because it must be a SELECT and we
1208 : * don't care about fetching any more result rows.
1209 : */
1210 160350 : if (completed || !fcache->returnsSet)
1211 159386 : postquel_end(es);
1212 :
1213 : /*
1214 : * Break from loop if we didn't shut down (implying we got a
1215 : * lazily-evaluated row). Otherwise we'll press on till the whole
1216 : * function is done, relying on the tuplestore to keep hold of the
1217 : * data to eventually be returned. This is necessary since an
1218 : * INSERT/UPDATE/DELETE RETURNING that sets the result might be
1219 : * followed by additional rule-inserted commands, and we want to
1220 : * finish doing all those commands before we return anything.
1221 : */
1222 160332 : if (es->status != F_EXEC_DONE)
1223 964 : break;
1224 :
1225 : /*
1226 : * Advance to next execution_state, which might be in the next list.
1227 : */
1228 159368 : es = es->next;
1229 199464 : while (!es)
1230 : {
1231 159362 : eslc = lnext(eslist, eslc);
1232 159362 : if (!eslc)
1233 119266 : break; /* end of function */
1234 :
1235 40096 : es = (execution_state *) lfirst(eslc);
1236 :
1237 : /*
1238 : * Flush the current snapshot so that we will take a new one for
1239 : * the new query list. This ensures that new snaps are taken at
1240 : * original-query boundaries, matching the behavior of interactive
1241 : * execution.
1242 : */
1243 40096 : if (pushed_snapshot)
1244 : {
1245 40096 : PopActiveSnapshot();
1246 40096 : pushed_snapshot = false;
1247 : }
1248 : }
1249 : }
1250 :
1251 : /*
1252 : * The tuplestore now contains whatever row(s) we are supposed to return.
1253 : */
1254 120236 : if (fcache->returnsSet)
1255 : {
1256 5004 : ReturnSetInfo *rsi = (ReturnSetInfo *) fcinfo->resultinfo;
1257 :
1258 5004 : if (es)
1259 : {
1260 : /*
1261 : * If we stopped short of being done, we must have a lazy-eval
1262 : * row.
1263 : */
1264 : Assert(es->lazyEval);
1265 : /* Re-use the junkfilter's output slot to fetch back the tuple */
1266 : Assert(fcache->junkFilter);
1267 964 : slot = fcache->junkFilter->jf_resultSlot;
1268 964 : if (!tuplestore_gettupleslot(fcache->tstore, true, false, slot))
1269 0 : elog(ERROR, "failed to fetch lazy-eval tuple");
1270 : /* Extract the result as a datum, and copy out from the slot */
1271 964 : result = postquel_get_single_result(slot, fcinfo,
1272 : fcache, oldcontext);
1273 : /* Clear the tuplestore, but keep it for next time */
1274 : /* NB: this might delete the slot's content, but we don't care */
1275 964 : tuplestore_clear(fcache->tstore);
1276 :
1277 : /*
1278 : * Let caller know we're not finished.
1279 : */
1280 964 : rsi->isDone = ExprMultipleResult;
1281 :
1282 : /*
1283 : * Ensure we will get shut down cleanly if the exprcontext is not
1284 : * run to completion.
1285 : */
1286 964 : if (!fcache->shutdown_reg)
1287 : {
1288 720 : RegisterExprContextCallback(rsi->econtext,
1289 : ShutdownSQLFunction,
1290 : PointerGetDatum(fcache));
1291 720 : fcache->shutdown_reg = true;
1292 : }
1293 : }
1294 4040 : else if (fcache->lazyEval)
1295 : {
1296 : /*
1297 : * We are done with a lazy evaluation. Clean up.
1298 : */
1299 3170 : tuplestore_clear(fcache->tstore);
1300 :
1301 : /*
1302 : * Let caller know we're finished.
1303 : */
1304 3170 : rsi->isDone = ExprEndResult;
1305 :
1306 3170 : fcinfo->isnull = true;
1307 3170 : result = (Datum) 0;
1308 :
1309 : /* Deregister shutdown callback, if we made one */
1310 3170 : if (fcache->shutdown_reg)
1311 : {
1312 720 : UnregisterExprContextCallback(rsi->econtext,
1313 : ShutdownSQLFunction,
1314 : PointerGetDatum(fcache));
1315 720 : fcache->shutdown_reg = false;
1316 : }
1317 : }
1318 : else
1319 : {
1320 : /*
1321 : * We are done with a non-lazy evaluation. Return whatever is in
1322 : * the tuplestore. (It is now caller's responsibility to free the
1323 : * tuplestore when done.)
1324 : */
1325 870 : rsi->returnMode = SFRM_Materialize;
1326 870 : rsi->setResult = fcache->tstore;
1327 870 : fcache->tstore = NULL;
1328 : /* must copy desc because execSRF.c will free it */
1329 870 : if (fcache->junkFilter)
1330 864 : rsi->setDesc = CreateTupleDescCopy(fcache->junkFilter->jf_cleanTupType);
1331 :
1332 870 : fcinfo->isnull = true;
1333 870 : result = (Datum) 0;
1334 :
1335 : /* Deregister shutdown callback, if we made one */
1336 870 : if (fcache->shutdown_reg)
1337 : {
1338 0 : UnregisterExprContextCallback(rsi->econtext,
1339 : ShutdownSQLFunction,
1340 : PointerGetDatum(fcache));
1341 0 : fcache->shutdown_reg = false;
1342 : }
1343 : }
1344 : }
1345 : else
1346 : {
1347 : /*
1348 : * Non-set function. If we got a row, return it; else return NULL.
1349 : */
1350 115232 : if (fcache->junkFilter)
1351 : {
1352 : /* Re-use the junkfilter's output slot to fetch back the tuple */
1353 115030 : slot = fcache->junkFilter->jf_resultSlot;
1354 115030 : if (tuplestore_gettupleslot(fcache->tstore, true, false, slot))
1355 110640 : result = postquel_get_single_result(slot, fcinfo,
1356 : fcache, oldcontext);
1357 : else
1358 : {
1359 4390 : fcinfo->isnull = true;
1360 4390 : result = (Datum) 0;
1361 : }
1362 : }
1363 : else
1364 : {
1365 : /* Should only get here for VOID functions and procedures */
1366 : Assert(fcache->rettype == VOIDOID);
1367 202 : fcinfo->isnull = true;
1368 202 : result = (Datum) 0;
1369 : }
1370 :
1371 : /* Clear the tuplestore, but keep it for next time */
1372 115232 : tuplestore_clear(fcache->tstore);
1373 : }
1374 :
1375 : /* Pop snapshot if we have pushed one */
1376 120236 : if (pushed_snapshot)
1377 105978 : PopActiveSnapshot();
1378 :
1379 : /*
1380 : * If we've gone through every command in the function, we are done. Reset
1381 : * the execution states to start over again on next call.
1382 : */
1383 120236 : if (es == NULL)
1384 : {
1385 278634 : foreach(eslc, fcache->func_state)
1386 : {
1387 159362 : es = (execution_state *) lfirst(eslc);
1388 318730 : while (es)
1389 : {
1390 159368 : es->status = F_EXEC_START;
1391 159368 : es = es->next;
1392 : }
1393 : }
1394 : }
1395 :
1396 120236 : error_context_stack = sqlerrcontext.previous;
1397 :
1398 120236 : MemoryContextSwitchTo(oldcontext);
1399 :
1400 120236 : return result;
1401 : }
1402 :
1403 :
1404 : /*
1405 : * error context callback to let us supply a call-stack traceback
1406 : */
1407 : static void
1408 8218 : sql_exec_error_callback(void *arg)
1409 : {
1410 8218 : FmgrInfo *flinfo = (FmgrInfo *) arg;
1411 8218 : SQLFunctionCachePtr fcache = (SQLFunctionCachePtr) flinfo->fn_extra;
1412 : int syntaxerrposition;
1413 :
1414 : /*
1415 : * We can do nothing useful if init_sql_fcache() didn't get as far as
1416 : * saving the function name
1417 : */
1418 8218 : if (fcache == NULL || fcache->fname == NULL)
1419 0 : return;
1420 :
1421 : /*
1422 : * If there is a syntax error position, convert to internal syntax error
1423 : */
1424 8218 : syntaxerrposition = geterrposition();
1425 8218 : if (syntaxerrposition > 0 && fcache->src != NULL)
1426 : {
1427 2 : errposition(0);
1428 2 : internalerrposition(syntaxerrposition);
1429 2 : internalerrquery(fcache->src);
1430 : }
1431 :
1432 : /*
1433 : * Try to determine where in the function we failed. If there is a query
1434 : * with non-null QueryDesc, finger it. (We check this rather than looking
1435 : * for F_EXEC_RUN state, so that errors during ExecutorStart or
1436 : * ExecutorEnd are blamed on the appropriate query; see postquel_start and
1437 : * postquel_end.)
1438 : */
1439 8218 : if (fcache->func_state)
1440 : {
1441 : execution_state *es;
1442 : int query_num;
1443 : ListCell *lc;
1444 :
1445 8204 : es = NULL;
1446 8204 : query_num = 1;
1447 8204 : foreach(lc, fcache->func_state)
1448 : {
1449 8204 : es = (execution_state *) lfirst(lc);
1450 8204 : while (es)
1451 : {
1452 8204 : if (es->qd)
1453 : {
1454 8204 : errcontext("SQL function \"%s\" statement %d",
1455 : fcache->fname, query_num);
1456 8204 : break;
1457 : }
1458 0 : es = es->next;
1459 : }
1460 8204 : if (es)
1461 8204 : break;
1462 0 : query_num++;
1463 : }
1464 8204 : if (es == NULL)
1465 : {
1466 : /*
1467 : * couldn't identify a running query; might be function entry,
1468 : * function exit, or between queries.
1469 : */
1470 0 : errcontext("SQL function \"%s\"", fcache->fname);
1471 : }
1472 : }
1473 : else
1474 : {
1475 : /*
1476 : * Assume we failed during init_sql_fcache(). (It's possible that the
1477 : * function actually has an empty body, but in that case we may as
1478 : * well report all errors as being "during startup".)
1479 : */
1480 14 : errcontext("SQL function \"%s\" during startup", fcache->fname);
1481 : }
1482 : }
1483 :
1484 :
1485 : /*
1486 : * callback function in case a function-returning-set needs to be shut down
1487 : * before it has been run to completion
1488 : */
1489 : static void
1490 0 : ShutdownSQLFunction(Datum arg)
1491 : {
1492 0 : SQLFunctionCachePtr fcache = (SQLFunctionCachePtr) DatumGetPointer(arg);
1493 : execution_state *es;
1494 : ListCell *lc;
1495 :
1496 0 : foreach(lc, fcache->func_state)
1497 : {
1498 0 : es = (execution_state *) lfirst(lc);
1499 0 : while (es)
1500 : {
1501 : /* Shut down anything still running */
1502 0 : if (es->status == F_EXEC_RUN)
1503 : {
1504 : /* Re-establish active snapshot for any called functions */
1505 0 : if (!fcache->readonly_func)
1506 0 : PushActiveSnapshot(es->qd->snapshot);
1507 :
1508 0 : postquel_end(es);
1509 :
1510 0 : if (!fcache->readonly_func)
1511 0 : PopActiveSnapshot();
1512 : }
1513 :
1514 : /* Reset states to START in case we're called again */
1515 0 : es->status = F_EXEC_START;
1516 0 : es = es->next;
1517 : }
1518 : }
1519 :
1520 : /* Release tuplestore if we have one */
1521 0 : if (fcache->tstore)
1522 0 : tuplestore_end(fcache->tstore);
1523 0 : fcache->tstore = NULL;
1524 :
1525 : /* execUtils will deregister the callback... */
1526 0 : fcache->shutdown_reg = false;
1527 0 : }
1528 :
1529 : /*
1530 : * check_sql_fn_statements
1531 : *
1532 : * Check statements in an SQL function. Error out if there is anything that
1533 : * is not acceptable.
1534 : */
1535 : void
1536 42522 : check_sql_fn_statements(List *queryTreeLists)
1537 : {
1538 : ListCell *lc;
1539 :
1540 : /* We are given a list of sublists of Queries */
1541 85294 : foreach(lc, queryTreeLists)
1542 : {
1543 42778 : List *sublist = lfirst_node(List, lc);
1544 : ListCell *lc2;
1545 :
1546 85556 : foreach(lc2, sublist)
1547 : {
1548 42784 : Query *query = lfirst_node(Query, lc2);
1549 :
1550 : /*
1551 : * Disallow calling procedures with output arguments. The current
1552 : * implementation would just throw the output values away, unless
1553 : * the statement is the last one. Per SQL standard, we should
1554 : * assign the output values by name. By disallowing this here, we
1555 : * preserve an opportunity for future improvement.
1556 : */
1557 42784 : if (query->commandType == CMD_UTILITY &&
1558 236 : IsA(query->utilityStmt, CallStmt))
1559 : {
1560 30 : CallStmt *stmt = (CallStmt *) query->utilityStmt;
1561 :
1562 30 : if (stmt->outargs != NIL)
1563 6 : ereport(ERROR,
1564 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1565 : errmsg("calling procedures with output arguments is not supported in SQL functions")));
1566 : }
1567 : }
1568 : }
1569 42516 : }
1570 :
1571 : /*
1572 : * check_sql_fn_retval()
1573 : * Check return value of a list of lists of sql parse trees.
1574 : *
1575 : * The return value of a sql function is the value returned by the last
1576 : * canSetTag query in the function. We do some ad-hoc type checking and
1577 : * coercion here to ensure that the function returns what it's supposed to.
1578 : * Note that we may actually modify the last query to make it match!
1579 : *
1580 : * This function returns true if the sql function returns the entire tuple
1581 : * result of its final statement, or false if it returns just the first column
1582 : * result of that statement. It throws an error if the final statement doesn't
1583 : * return the right type at all.
1584 : *
1585 : * Note that because we allow "SELECT rowtype_expression", the result can be
1586 : * false even when the declared function return type is a rowtype.
1587 : *
1588 : * For a polymorphic function the passed rettype must be the actual resolved
1589 : * output type of the function. (This means we can't check the type during
1590 : * function definition of a polymorphic function.) If we do see a polymorphic
1591 : * rettype we'll throw an error, saying it is not a supported rettype.
1592 : *
1593 : * If the function returns composite, the passed rettupdesc should describe
1594 : * the expected output. If rettupdesc is NULL, we can't verify that the
1595 : * output matches; that should only happen in fmgr_sql_validator(), or when
1596 : * the function returns RECORD and the caller doesn't actually care which
1597 : * composite type it is.
1598 : *
1599 : * (Typically, rettype and rettupdesc are computed by get_call_result_type
1600 : * or a sibling function.)
1601 : *
1602 : * In addition to coercing individual output columns, we can modify the
1603 : * output to include dummy NULL columns for any dropped columns appearing
1604 : * in rettupdesc. This is done only if the caller asks for it.
1605 : *
1606 : * If resultTargetList isn't NULL, then *resultTargetList is set to the
1607 : * targetlist that defines the final statement's result. Exception: if the
1608 : * function is defined to return VOID then *resultTargetList is set to NIL.
1609 : */
1610 : bool
1611 62080 : check_sql_fn_retval(List *queryTreeLists,
1612 : Oid rettype, TupleDesc rettupdesc,
1613 : char prokind,
1614 : bool insertDroppedCols,
1615 : List **resultTargetList)
1616 : {
1617 62080 : bool is_tuple_result = false;
1618 : Query *parse;
1619 : ListCell *parse_cell;
1620 : List *tlist;
1621 : int tlistlen;
1622 : bool tlist_is_modifiable;
1623 : char fn_typtype;
1624 62080 : List *upper_tlist = NIL;
1625 62080 : bool upper_tlist_nontrivial = false;
1626 : ListCell *lc;
1627 :
1628 62080 : if (resultTargetList)
1629 35862 : *resultTargetList = NIL; /* initialize in case of VOID result */
1630 :
1631 : /*
1632 : * If it's declared to return VOID, we don't care what's in the function.
1633 : * (This takes care of procedures with no output parameters, as well.)
1634 : */
1635 62080 : if (rettype == VOIDOID)
1636 724 : return false;
1637 :
1638 : /*
1639 : * Find the last canSetTag query in the function body (which is presented
1640 : * to us as a list of sublists of Query nodes). This isn't necessarily
1641 : * the last parsetree, because rule rewriting can insert queries after
1642 : * what the user wrote. Note that it might not even be in the last
1643 : * sublist, for example if the last query rewrites to DO INSTEAD NOTHING.
1644 : * (It might not be unreasonable to throw an error in such a case, but
1645 : * this is the historical behavior and it doesn't seem worth changing.)
1646 : */
1647 61356 : parse = NULL;
1648 61356 : parse_cell = NULL;
1649 122938 : foreach(lc, queryTreeLists)
1650 : {
1651 61582 : List *sublist = lfirst_node(List, lc);
1652 : ListCell *lc2;
1653 :
1654 123170 : foreach(lc2, sublist)
1655 : {
1656 61588 : Query *q = lfirst_node(Query, lc2);
1657 :
1658 61588 : if (q->canSetTag)
1659 : {
1660 61582 : parse = q;
1661 61582 : parse_cell = lc2;
1662 : }
1663 : }
1664 : }
1665 :
1666 : /*
1667 : * If it's a plain SELECT, it returns whatever the targetlist says.
1668 : * Otherwise, if it's INSERT/UPDATE/DELETE/MERGE with RETURNING, it
1669 : * returns that. Otherwise, the function return type must be VOID.
1670 : *
1671 : * Note: eventually replace this test with QueryReturnsTuples? We'd need
1672 : * a more general method of determining the output type, though. Also, it
1673 : * seems too dangerous to consider FETCH or EXECUTE as returning a
1674 : * determinable rowtype, since they depend on relatively short-lived
1675 : * entities.
1676 : */
1677 61356 : if (parse &&
1678 61356 : parse->commandType == CMD_SELECT)
1679 : {
1680 61224 : tlist = parse->targetList;
1681 : /* tlist is modifiable unless it's a dummy in a setop query */
1682 61224 : tlist_is_modifiable = (parse->setOperations == NULL);
1683 : }
1684 132 : else if (parse &&
1685 132 : (parse->commandType == CMD_INSERT ||
1686 30 : parse->commandType == CMD_UPDATE ||
1687 30 : parse->commandType == CMD_DELETE ||
1688 30 : parse->commandType == CMD_MERGE) &&
1689 132 : parse->returningList)
1690 : {
1691 132 : tlist = parse->returningList;
1692 : /* returningList can always be modified */
1693 132 : tlist_is_modifiable = true;
1694 : }
1695 : else
1696 : {
1697 : /* Empty function body, or last statement is a utility command */
1698 0 : ereport(ERROR,
1699 : (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
1700 : errmsg("return type mismatch in function declared to return %s",
1701 : format_type_be(rettype)),
1702 : errdetail("Function's final statement must be SELECT or INSERT/UPDATE/DELETE/MERGE RETURNING.")));
1703 : return false; /* keep compiler quiet */
1704 : }
1705 :
1706 : /*
1707 : * OK, check that the targetlist returns something matching the declared
1708 : * type, and modify it if necessary. If possible, we insert any coercion
1709 : * steps right into the final statement's targetlist. However, that might
1710 : * risk changes in the statement's semantics --- we can't safely change
1711 : * the output type of a grouping column, for instance. In such cases we
1712 : * handle coercions by inserting an extra level of Query that effectively
1713 : * just does a projection.
1714 : */
1715 :
1716 : /*
1717 : * Count the non-junk entries in the result targetlist.
1718 : */
1719 61356 : tlistlen = ExecCleanTargetListLength(tlist);
1720 :
1721 61356 : fn_typtype = get_typtype(rettype);
1722 :
1723 61356 : if (fn_typtype == TYPTYPE_BASE ||
1724 2100 : fn_typtype == TYPTYPE_DOMAIN ||
1725 2094 : fn_typtype == TYPTYPE_ENUM ||
1726 2058 : fn_typtype == TYPTYPE_RANGE ||
1727 : fn_typtype == TYPTYPE_MULTIRANGE)
1728 59322 : {
1729 : /*
1730 : * For scalar-type returns, the target list must have exactly one
1731 : * non-junk entry, and its type must be coercible to rettype.
1732 : */
1733 : TargetEntry *tle;
1734 :
1735 59334 : if (tlistlen != 1)
1736 6 : ereport(ERROR,
1737 : (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
1738 : errmsg("return type mismatch in function declared to return %s",
1739 : format_type_be(rettype)),
1740 : errdetail("Final statement must return exactly one column.")));
1741 :
1742 : /* We assume here that non-junk TLEs must come first in tlists */
1743 59328 : tle = (TargetEntry *) linitial(tlist);
1744 : Assert(!tle->resjunk);
1745 :
1746 59328 : if (!coerce_fn_result_column(tle, rettype, -1,
1747 : tlist_is_modifiable,
1748 : &upper_tlist,
1749 : &upper_tlist_nontrivial))
1750 6 : ereport(ERROR,
1751 : (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
1752 : errmsg("return type mismatch in function declared to return %s",
1753 : format_type_be(rettype)),
1754 : errdetail("Actual return type is %s.",
1755 : format_type_be(exprType((Node *) tle->expr)))));
1756 : }
1757 2022 : else if (fn_typtype == TYPTYPE_COMPOSITE || rettype == RECORDOID)
1758 1884 : {
1759 : /*
1760 : * Returns a rowtype.
1761 : *
1762 : * Note that we will not consider a domain over composite to be a
1763 : * "rowtype" return type; it goes through the scalar case above. This
1764 : * is because we only provide column-by-column implicit casting, and
1765 : * will not cast the complete record result. So the only way to
1766 : * produce a domain-over-composite result is to compute it as an
1767 : * explicit single-column result. The single-composite-column code
1768 : * path just below could handle such cases, but it won't be reached.
1769 : */
1770 : int tupnatts; /* physical number of columns in tuple */
1771 : int tuplogcols; /* # of nondeleted columns in tuple */
1772 : int colindex; /* physical column index */
1773 :
1774 : /*
1775 : * If the target list has one non-junk entry, and that expression has
1776 : * or can be coerced to the declared return type, take it as the
1777 : * result. This allows, for example, 'SELECT func2()', where func2
1778 : * has the same composite return type as the function that's calling
1779 : * it. This provision creates some ambiguity --- maybe the expression
1780 : * was meant to be the lone field of the composite result --- but it
1781 : * works well enough as long as we don't get too enthusiastic about
1782 : * inventing coercions from scalar to composite types.
1783 : *
1784 : * XXX Note that if rettype is RECORD and the expression is of a named
1785 : * composite type, or vice versa, this coercion will succeed, whether
1786 : * or not the record type really matches. For the moment we rely on
1787 : * runtime type checking to catch any discrepancy, but it'd be nice to
1788 : * do better at parse time.
1789 : *
1790 : * We must *not* do this for a procedure, however. Procedures with
1791 : * output parameter(s) have rettype RECORD, and the CALL code expects
1792 : * to get results corresponding to the list of output parameters, even
1793 : * when there's just one parameter that's composite.
1794 : */
1795 2016 : if (tlistlen == 1 && prokind != PROKIND_PROCEDURE)
1796 : {
1797 216 : TargetEntry *tle = (TargetEntry *) linitial(tlist);
1798 :
1799 : Assert(!tle->resjunk);
1800 216 : if (coerce_fn_result_column(tle, rettype, -1,
1801 : tlist_is_modifiable,
1802 : &upper_tlist,
1803 : &upper_tlist_nontrivial))
1804 : {
1805 : /* Note that we're NOT setting is_tuple_result */
1806 72 : goto tlist_coercion_finished;
1807 : }
1808 : }
1809 :
1810 : /*
1811 : * If the caller didn't provide an expected tupdesc, we can't do any
1812 : * further checking. Assume we're returning the whole tuple.
1813 : */
1814 1944 : if (rettupdesc == NULL)
1815 : {
1816 : /* Return tlist if requested */
1817 48 : if (resultTargetList)
1818 24 : *resultTargetList = tlist;
1819 48 : return true;
1820 : }
1821 :
1822 : /*
1823 : * Verify that the targetlist matches the return tuple type. We scan
1824 : * the non-resjunk columns, and coerce them if necessary to match the
1825 : * datatypes of the non-deleted attributes. For deleted attributes,
1826 : * insert NULL result columns if the caller asked for that.
1827 : */
1828 1896 : tupnatts = rettupdesc->natts;
1829 1896 : tuplogcols = 0; /* we'll count nondeleted cols as we go */
1830 1896 : colindex = 0;
1831 :
1832 7104 : foreach(lc, tlist)
1833 : {
1834 5220 : TargetEntry *tle = (TargetEntry *) lfirst(lc);
1835 : Form_pg_attribute attr;
1836 :
1837 : /* resjunk columns can simply be ignored */
1838 5220 : if (tle->resjunk)
1839 0 : continue;
1840 :
1841 : do
1842 : {
1843 5304 : colindex++;
1844 5304 : if (colindex > tupnatts)
1845 0 : ereport(ERROR,
1846 : (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
1847 : errmsg("return type mismatch in function declared to return %s",
1848 : format_type_be(rettype)),
1849 : errdetail("Final statement returns too many columns.")));
1850 5304 : attr = TupleDescAttr(rettupdesc, colindex - 1);
1851 5304 : if (attr->attisdropped && insertDroppedCols)
1852 : {
1853 : Expr *null_expr;
1854 :
1855 : /* The type of the null we insert isn't important */
1856 6 : null_expr = (Expr *) makeConst(INT4OID,
1857 : -1,
1858 : InvalidOid,
1859 : sizeof(int32),
1860 : (Datum) 0,
1861 : true, /* isnull */
1862 : true /* byval */ );
1863 6 : upper_tlist = lappend(upper_tlist,
1864 6 : makeTargetEntry(null_expr,
1865 6 : list_length(upper_tlist) + 1,
1866 : NULL,
1867 : false));
1868 6 : upper_tlist_nontrivial = true;
1869 : }
1870 5304 : } while (attr->attisdropped);
1871 5220 : tuplogcols++;
1872 :
1873 5220 : if (!coerce_fn_result_column(tle,
1874 : attr->atttypid, attr->atttypmod,
1875 : tlist_is_modifiable,
1876 : &upper_tlist,
1877 : &upper_tlist_nontrivial))
1878 12 : ereport(ERROR,
1879 : (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
1880 : errmsg("return type mismatch in function declared to return %s",
1881 : format_type_be(rettype)),
1882 : errdetail("Final statement returns %s instead of %s at column %d.",
1883 : format_type_be(exprType((Node *) tle->expr)),
1884 : format_type_be(attr->atttypid),
1885 : tuplogcols)));
1886 : }
1887 :
1888 : /* remaining columns in rettupdesc had better all be dropped */
1889 1884 : for (colindex++; colindex <= tupnatts; colindex++)
1890 : {
1891 0 : if (!TupleDescCompactAttr(rettupdesc, colindex - 1)->attisdropped)
1892 0 : ereport(ERROR,
1893 : (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
1894 : errmsg("return type mismatch in function declared to return %s",
1895 : format_type_be(rettype)),
1896 : errdetail("Final statement returns too few columns.")));
1897 0 : if (insertDroppedCols)
1898 : {
1899 : Expr *null_expr;
1900 :
1901 : /* The type of the null we insert isn't important */
1902 0 : null_expr = (Expr *) makeConst(INT4OID,
1903 : -1,
1904 : InvalidOid,
1905 : sizeof(int32),
1906 : (Datum) 0,
1907 : true, /* isnull */
1908 : true /* byval */ );
1909 0 : upper_tlist = lappend(upper_tlist,
1910 0 : makeTargetEntry(null_expr,
1911 0 : list_length(upper_tlist) + 1,
1912 : NULL,
1913 : false));
1914 0 : upper_tlist_nontrivial = true;
1915 : }
1916 : }
1917 :
1918 : /* Report that we are returning entire tuple result */
1919 1884 : is_tuple_result = true;
1920 : }
1921 : else
1922 6 : ereport(ERROR,
1923 : (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
1924 : errmsg("return type %s is not supported for SQL functions",
1925 : format_type_be(rettype))));
1926 :
1927 61278 : tlist_coercion_finished:
1928 :
1929 : /*
1930 : * If necessary, modify the final Query by injecting an extra Query level
1931 : * that just performs a projection. (It'd be dubious to do this to a
1932 : * non-SELECT query, but we never have to; RETURNING lists can always be
1933 : * modified in-place.)
1934 : */
1935 61278 : if (upper_tlist_nontrivial)
1936 : {
1937 : Query *newquery;
1938 : List *colnames;
1939 : RangeTblEntry *rte;
1940 : RangeTblRef *rtr;
1941 :
1942 : Assert(parse->commandType == CMD_SELECT);
1943 :
1944 : /* Most of the upper Query struct can be left as zeroes/nulls */
1945 84 : newquery = makeNode(Query);
1946 84 : newquery->commandType = CMD_SELECT;
1947 84 : newquery->querySource = parse->querySource;
1948 84 : newquery->canSetTag = true;
1949 84 : newquery->targetList = upper_tlist;
1950 :
1951 : /* We need a moderately realistic colnames list for the subquery RTE */
1952 84 : colnames = NIL;
1953 216 : foreach(lc, parse->targetList)
1954 : {
1955 132 : TargetEntry *tle = (TargetEntry *) lfirst(lc);
1956 :
1957 132 : if (tle->resjunk)
1958 0 : continue;
1959 132 : colnames = lappend(colnames,
1960 132 : makeString(tle->resname ? tle->resname : ""));
1961 : }
1962 :
1963 : /* Build a suitable RTE for the subquery */
1964 84 : rte = makeNode(RangeTblEntry);
1965 84 : rte->rtekind = RTE_SUBQUERY;
1966 84 : rte->subquery = parse;
1967 84 : rte->eref = rte->alias = makeAlias("*SELECT*", colnames);
1968 84 : rte->lateral = false;
1969 84 : rte->inh = false;
1970 84 : rte->inFromCl = true;
1971 84 : newquery->rtable = list_make1(rte);
1972 :
1973 84 : rtr = makeNode(RangeTblRef);
1974 84 : rtr->rtindex = 1;
1975 84 : newquery->jointree = makeFromExpr(list_make1(rtr), NULL);
1976 :
1977 : /*
1978 : * Make sure the new query is marked as having row security if the
1979 : * original one does.
1980 : */
1981 84 : newquery->hasRowSecurity = parse->hasRowSecurity;
1982 :
1983 : /* Replace original query in the correct element of the query list */
1984 84 : lfirst(parse_cell) = newquery;
1985 : }
1986 :
1987 : /* Return tlist (possibly modified) if requested */
1988 61278 : if (resultTargetList)
1989 35544 : *resultTargetList = upper_tlist;
1990 :
1991 61278 : return is_tuple_result;
1992 : }
1993 :
1994 : /*
1995 : * Process one function result column for check_sql_fn_retval
1996 : *
1997 : * Coerce the output value to the required type/typmod, and add a column
1998 : * to *upper_tlist for it. Set *upper_tlist_nontrivial to true if we
1999 : * add an upper tlist item that's not just a Var.
2000 : *
2001 : * Returns true if OK, false if could not coerce to required type
2002 : * (in which case, no changes have been made)
2003 : */
2004 : static bool
2005 64764 : coerce_fn_result_column(TargetEntry *src_tle,
2006 : Oid res_type,
2007 : int32 res_typmod,
2008 : bool tlist_is_modifiable,
2009 : List **upper_tlist,
2010 : bool *upper_tlist_nontrivial)
2011 : {
2012 : TargetEntry *new_tle;
2013 : Expr *new_tle_expr;
2014 : Node *cast_result;
2015 :
2016 : /*
2017 : * If the TLE has a sortgroupref marking, don't change it, as it probably
2018 : * is referenced by ORDER BY, DISTINCT, etc, and changing its type would
2019 : * break query semantics. Otherwise, it's safe to modify in-place unless
2020 : * the query as a whole has issues with that.
2021 : */
2022 64764 : if (tlist_is_modifiable && src_tle->ressortgroupref == 0)
2023 : {
2024 : /* OK to modify src_tle in place, if necessary */
2025 128576 : cast_result = coerce_to_target_type(NULL,
2026 64288 : (Node *) src_tle->expr,
2027 64288 : exprType((Node *) src_tle->expr),
2028 : res_type, res_typmod,
2029 : COERCION_ASSIGNMENT,
2030 : COERCE_IMPLICIT_CAST,
2031 : -1);
2032 64288 : if (cast_result == NULL)
2033 144 : return false;
2034 64144 : assign_expr_collations(NULL, cast_result);
2035 64144 : src_tle->expr = (Expr *) cast_result;
2036 : /* Make a Var referencing the possibly-modified TLE */
2037 64144 : new_tle_expr = (Expr *) makeVarFromTargetEntry(1, src_tle);
2038 : }
2039 : else
2040 : {
2041 : /* Any casting must happen in the upper tlist */
2042 476 : Var *var = makeVarFromTargetEntry(1, src_tle);
2043 :
2044 476 : cast_result = coerce_to_target_type(NULL,
2045 : (Node *) var,
2046 : var->vartype,
2047 : res_type, res_typmod,
2048 : COERCION_ASSIGNMENT,
2049 : COERCE_IMPLICIT_CAST,
2050 : -1);
2051 476 : if (cast_result == NULL)
2052 18 : return false;
2053 458 : assign_expr_collations(NULL, cast_result);
2054 : /* Did the coercion actually do anything? */
2055 458 : if (cast_result != (Node *) var)
2056 102 : *upper_tlist_nontrivial = true;
2057 458 : new_tle_expr = (Expr *) cast_result;
2058 : }
2059 129204 : new_tle = makeTargetEntry(new_tle_expr,
2060 64602 : list_length(*upper_tlist) + 1,
2061 : src_tle->resname, false);
2062 64602 : *upper_tlist = lappend(*upper_tlist, new_tle);
2063 64602 : return true;
2064 : }
2065 :
2066 :
2067 : /*
2068 : * CreateSQLFunctionDestReceiver -- create a suitable DestReceiver object
2069 : */
2070 : DestReceiver *
2071 127110 : CreateSQLFunctionDestReceiver(void)
2072 : {
2073 127110 : DR_sqlfunction *self = (DR_sqlfunction *) palloc0(sizeof(DR_sqlfunction));
2074 :
2075 127110 : self->pub.receiveSlot = sqlfunction_receive;
2076 127110 : self->pub.rStartup = sqlfunction_startup;
2077 127110 : self->pub.rShutdown = sqlfunction_shutdown;
2078 127110 : self->pub.rDestroy = sqlfunction_destroy;
2079 127110 : self->pub.mydest = DestSQLFunction;
2080 :
2081 : /* private fields will be set by postquel_start */
2082 :
2083 127110 : return (DestReceiver *) self;
2084 : }
2085 :
2086 : /*
2087 : * sqlfunction_startup --- executor startup
2088 : */
2089 : static void
2090 128074 : sqlfunction_startup(DestReceiver *self, int operation, TupleDesc typeinfo)
2091 : {
2092 : /* no-op */
2093 128074 : }
2094 :
2095 : /*
2096 : * sqlfunction_receive --- receive one tuple
2097 : */
2098 : static bool
2099 233954 : sqlfunction_receive(TupleTableSlot *slot, DestReceiver *self)
2100 : {
2101 233954 : DR_sqlfunction *myState = (DR_sqlfunction *) self;
2102 :
2103 : /* Filter tuple as needed */
2104 233954 : slot = ExecFilterJunk(myState->filter, slot);
2105 :
2106 : /* Store the filtered tuple into the tuplestore */
2107 233954 : tuplestore_puttupleslot(myState->tstore, slot);
2108 :
2109 233954 : return true;
2110 : }
2111 :
2112 : /*
2113 : * sqlfunction_shutdown --- executor end
2114 : */
2115 : static void
2116 120028 : sqlfunction_shutdown(DestReceiver *self)
2117 : {
2118 : /* no-op */
2119 120028 : }
2120 :
2121 : /*
2122 : * sqlfunction_destroy --- release DestReceiver object
2123 : */
2124 : static void
2125 119064 : sqlfunction_destroy(DestReceiver *self)
2126 : {
2127 119064 : pfree(self);
2128 119064 : }
|