Branch data Line data Source code
1 : : /*-------------------------------------------------------------------------
2 : : *
3 : : * execSRF.c
4 : : * Routines implementing the API for set-returning functions
5 : : *
6 : : * This file serves nodeFunctionscan.c and nodeProjectSet.c, providing
7 : : * common code for calling set-returning functions according to the
8 : : * ReturnSetInfo API.
9 : : *
10 : : * Portions Copyright (c) 1996-2026, PostgreSQL Global Development Group
11 : : * Portions Copyright (c) 1994, Regents of the University of California
12 : : *
13 : : *
14 : : * IDENTIFICATION
15 : : * src/backend/executor/execSRF.c
16 : : *
17 : : *-------------------------------------------------------------------------
18 : : */
19 : : #include "postgres.h"
20 : :
21 : : #include "access/htup_details.h"
22 : : #include "catalog/objectaccess.h"
23 : : #include "catalog/pg_proc.h"
24 : : #include "funcapi.h"
25 : : #include "miscadmin.h"
26 : : #include "nodes/nodeFuncs.h"
27 : : #include "parser/parse_coerce.h"
28 : : #include "pgstat.h"
29 : : #include "utils/acl.h"
30 : : #include "utils/builtins.h"
31 : : #include "utils/lsyscache.h"
32 : : #include "utils/memutils.h"
33 : : #include "utils/tuplestore.h"
34 : : #include "utils/typcache.h"
35 : :
36 : :
37 : : /* static function decls */
38 : : static void init_sexpr(Oid foid, Oid input_collation, Expr *node,
39 : : SetExprState *sexpr, PlanState *parent,
40 : : MemoryContext sexprCxt, bool allowSRF, bool needDescForSRF);
41 : : static void ShutdownSetExpr(Datum arg);
42 : : static void ExecEvalFuncArgs(FunctionCallInfo fcinfo,
43 : : List *argList, ExprContext *econtext);
44 : : static void ExecPrepareTuplestoreResult(SetExprState *sexpr,
45 : : ExprContext *econtext,
46 : : Tuplestorestate *resultStore,
47 : : TupleDesc resultDesc);
48 : : static void ExecReleaseTuplestoreResult(SetExprState *sexpr);
49 : : static void tupledesc_match(TupleDesc dst_tupdesc, TupleDesc src_tupdesc);
50 : :
51 : :
52 : : /*
53 : : * Prepare function call in FROM (ROWS FROM) for execution.
54 : : *
55 : : * This is used by nodeFunctionscan.c.
56 : : */
57 : : SetExprState *
58 : 49287 : ExecInitTableFunctionResult(Expr *expr,
59 : : ExprContext *econtext, PlanState *parent)
60 : : {
61 : 49287 : SetExprState *state = makeNode(SetExprState);
62 : :
63 : 49287 : state->funcReturnsSet = false;
64 : 49287 : state->expr = expr;
65 : 49287 : state->func.fn_oid = InvalidOid;
66 : :
67 : : /*
68 : : * Normally the passed expression tree will be a FuncExpr, since the
69 : : * grammar only allows a function call at the top level of a table
70 : : * function reference. However, if the function doesn't return set then
71 : : * the planner might have replaced the function call via constant-folding
72 : : * or inlining. So if we see any other kind of expression node, execute
73 : : * it via the general ExecEvalExpr() code. That code path will not
74 : : * support set-returning functions buried in the expression, though.
75 : : */
76 [ + + ]: 49287 : if (IsA(expr, FuncExpr))
77 : : {
78 : 49211 : FuncExpr *func = (FuncExpr *) expr;
79 : :
80 : 49211 : state->funcReturnsSet = func->funcretset;
81 : 49211 : state->args = ExecInitExprList(func->args, parent);
82 : :
83 : 49211 : init_sexpr(func->funcid, func->inputcollid, expr, state, parent,
84 : 49211 : econtext->ecxt_per_query_memory, func->funcretset, false);
85 : : }
86 : : else
87 : : {
88 : 76 : state->elidedFuncState = ExecInitExpr(expr, parent);
89 : : }
90 : :
91 : 49283 : return state;
92 : : }
93 : :
94 : : /*
95 : : * ExecMakeTableFunctionResult
96 : : *
97 : : * Evaluate a table function, producing a materialized result in a Tuplestore
98 : : * object.
99 : : *
100 : : * This is used by nodeFunctionscan.c.
101 : : */
102 : : Tuplestorestate *
103 : 108086 : ExecMakeTableFunctionResult(SetExprState *setexpr,
104 : : ExprContext *econtext,
105 : : MemoryContext argContext,
106 : : TupleDesc expectedDesc,
107 : : bool randomAccess)
108 : : {
109 : 108086 : Tuplestorestate *tupstore = NULL;
110 : 108086 : TupleDesc tupdesc = NULL;
111 : : Oid funcrettype;
112 : : bool returnsTuple;
113 : 108086 : bool returnsSet = false;
114 : : FunctionCallInfo fcinfo;
115 : : PgStat_FunctionCallUsage fcusage;
116 : : ReturnSetInfo rsinfo;
117 : : HeapTupleData tmptup;
118 : : MemoryContext callerContext;
119 : 108086 : bool first_time = true;
120 : :
121 : : /*
122 : : * Execute per-tablefunc actions in appropriate context.
123 : : *
124 : : * The FunctionCallInfo needs to live across all the calls to a
125 : : * ValuePerCall function, so it can't be allocated in the per-tuple
126 : : * context. Similarly, the function arguments need to be evaluated in a
127 : : * context that is longer lived than the per-tuple context: The argument
128 : : * values would otherwise disappear when we reset that context in the
129 : : * inner loop. As the caller's CurrentMemoryContext is typically a
130 : : * query-lifespan context, we don't want to leak memory there. We require
131 : : * the caller to pass a separate memory context that can be used for this,
132 : : * and can be reset each time through to avoid bloat.
133 : : */
134 : 108086 : MemoryContextReset(argContext);
135 : 108086 : callerContext = MemoryContextSwitchTo(argContext);
136 : :
137 : 108086 : funcrettype = exprType((Node *) setexpr->expr);
138 : :
139 : 108086 : returnsTuple = type_is_rowtype(funcrettype);
140 : :
141 : : /*
142 : : * Prepare a resultinfo node for communication. We always do this even if
143 : : * not expecting a set result, so that we can pass expectedDesc. In the
144 : : * generic-expression case, the expression doesn't actually get to see the
145 : : * resultinfo, but set it up anyway because we use some of the fields as
146 : : * our own state variables.
147 : : */
148 : 108086 : rsinfo.type = T_ReturnSetInfo;
149 : 108086 : rsinfo.econtext = econtext;
150 : 108086 : rsinfo.expectedDesc = expectedDesc;
151 : 108086 : rsinfo.allowedModes = (int) (SFRM_ValuePerCall | SFRM_Materialize | SFRM_Materialize_Preferred);
152 [ + + ]: 108086 : if (randomAccess)
153 : 89 : rsinfo.allowedModes |= (int) SFRM_Materialize_Random;
154 : 108086 : rsinfo.returnMode = SFRM_ValuePerCall;
155 : : /* isDone is filled below */
156 : 108086 : rsinfo.setResult = NULL;
157 : 108086 : rsinfo.setDesc = NULL;
158 : :
159 : 108086 : fcinfo = palloc(SizeForFunctionCallInfo(list_length(setexpr->args)));
160 : :
161 : : /*
162 : : * Normally the passed expression tree will be a SetExprState, since the
163 : : * grammar only allows a function call at the top level of a table
164 : : * function reference. However, if the function doesn't return set then
165 : : * the planner might have replaced the function call via constant-folding
166 : : * or inlining. So if we see any other kind of expression node, execute
167 : : * it via the general ExecEvalExpr() code; the only difference is that we
168 : : * don't get a chance to pass a special ReturnSetInfo to any functions
169 : : * buried in the expression.
170 : : */
171 [ + + ]: 108086 : if (!setexpr->elidedFuncState)
172 : : {
173 : : /*
174 : : * This path is similar to ExecMakeFunctionResultSet.
175 : : */
176 : 108010 : returnsSet = setexpr->funcReturnsSet;
177 : 108010 : InitFunctionCallInfoData(*fcinfo, &(setexpr->func),
178 : : list_length(setexpr->args),
179 : : setexpr->fcinfo->fncollation,
180 : : NULL, (Node *) &rsinfo);
181 : : /* evaluate the function's argument list */
182 : : Assert(CurrentMemoryContext == argContext);
183 : 108010 : ExecEvalFuncArgs(fcinfo, setexpr->args, econtext);
184 : :
185 : : /*
186 : : * If function is strict, and there are any NULL arguments, skip
187 : : * calling the function and act like it returned NULL (or an empty
188 : : * set, in the returns-set case).
189 : : */
190 [ + + ]: 108002 : if (setexpr->func.fn_strict)
191 : : {
192 : : int i;
193 : :
194 [ + + ]: 208546 : for (i = 0; i < fcinfo->nargs; i++)
195 : : {
196 [ + + ]: 140695 : if (fcinfo->args[i].isnull)
197 : 27876 : goto no_function_result;
198 : : }
199 : : }
200 : : }
201 : : else
202 : : {
203 : : /* Treat setexpr as a generic expression */
204 : 76 : InitFunctionCallInfoData(*fcinfo, NULL, 0, InvalidOid, NULL, NULL);
205 : : }
206 : :
207 : : /*
208 : : * Switch to short-lived context for calling the function or expression.
209 : : */
210 : 80202 : MemoryContextSwitchTo(econtext->ecxt_per_tuple_memory);
211 : :
212 : : /*
213 : : * Loop to handle the ValuePerCall protocol (which is also the same
214 : : * behavior needed in the generic ExecEvalExpr path).
215 : : */
216 : : for (;;)
217 : 10218965 : {
218 : : Datum result;
219 : :
220 [ - + ]: 10299167 : CHECK_FOR_INTERRUPTS();
221 : :
222 : : /*
223 : : * Reset per-tuple memory context before each call of the function or
224 : : * expression. This cleans up any local memory the function may leak
225 : : * when called.
226 : : */
227 : 10299167 : ResetExprContext(econtext);
228 : :
229 : : /* Call the function or expression one time */
230 [ + + ]: 10299167 : if (!setexpr->elidedFuncState)
231 : : {
232 : 10299091 : pgstat_init_function_usage(fcinfo, &fcusage);
233 : :
234 : 10299091 : fcinfo->isnull = false;
235 : 10299091 : rsinfo.isDone = ExprSingleResult;
236 : 10299091 : result = FunctionCallInvoke(fcinfo);
237 : :
238 : 10296332 : pgstat_end_function_usage(&fcusage,
239 : 10296332 : rsinfo.isDone != ExprMultipleResult);
240 : : }
241 : : else
242 : : {
243 : 76 : result =
244 : 76 : ExecEvalExpr(setexpr->elidedFuncState, econtext, &fcinfo->isnull);
245 : 76 : rsinfo.isDone = ExprSingleResult;
246 : : }
247 : :
248 : : /* Which protocol does function want to use? */
249 [ + + ]: 10296408 : if (rsinfo.returnMode == SFRM_ValuePerCall)
250 : : {
251 : : /*
252 : : * Check for end of result set.
253 : : */
254 [ + + ]: 10281074 : if (rsinfo.isDone == ExprEndResult)
255 : 77439 : break;
256 : :
257 : : /*
258 : : * If first time through, build tuplestore for result. For a
259 : : * scalar function result type, also make a suitable tupdesc.
260 : : */
261 [ + + ]: 10244906 : if (first_time)
262 : : {
263 : : MemoryContext oldcontext =
264 : 61060 : MemoryContextSwitchTo(econtext->ecxt_per_query_memory);
265 : :
266 : 61060 : tupstore = tuplestore_begin_heap(randomAccess, false, work_mem);
267 : 61060 : rsinfo.setResult = tupstore;
268 [ + + ]: 61060 : if (!returnsTuple)
269 : : {
270 : 33359 : tupdesc = CreateTemplateTupleDesc(1);
271 : 33359 : TupleDescInitEntry(tupdesc,
272 : : (AttrNumber) 1,
273 : : "column",
274 : : funcrettype,
275 : : -1,
276 : : 0);
277 : 33359 : TupleDescFinalize(tupdesc);
278 : 33359 : rsinfo.setDesc = tupdesc;
279 : : }
280 : 61060 : MemoryContextSwitchTo(oldcontext);
281 : : }
282 : :
283 : : /*
284 : : * Store current resultset item.
285 : : */
286 [ + + ]: 10244906 : if (returnsTuple)
287 : : {
288 [ + + ]: 298993 : if (!fcinfo->isnull)
289 : : {
290 : 298940 : HeapTupleHeader td = DatumGetHeapTupleHeader(result);
291 : :
292 [ + + ]: 298940 : if (tupdesc == NULL)
293 : : {
294 : : MemoryContext oldcontext =
295 : 27664 : MemoryContextSwitchTo(econtext->ecxt_per_query_memory);
296 : :
297 : : /*
298 : : * This is the first non-NULL result from the
299 : : * function. Use the type info embedded in the
300 : : * rowtype Datum to look up the needed tupdesc. Make
301 : : * a copy for the query.
302 : : */
303 : 27664 : tupdesc = lookup_rowtype_tupdesc_copy(HeapTupleHeaderGetTypeId(td),
304 : : HeapTupleHeaderGetTypMod(td));
305 : 27664 : rsinfo.setDesc = tupdesc;
306 : 27664 : MemoryContextSwitchTo(oldcontext);
307 : : }
308 : : else
309 : : {
310 : : /*
311 : : * Verify all later returned rows have same subtype;
312 : : * necessary in case the type is RECORD.
313 : : */
314 [ + - ]: 271276 : if (HeapTupleHeaderGetTypeId(td) != tupdesc->tdtypeid ||
315 [ - + ]: 271276 : HeapTupleHeaderGetTypMod(td) != tupdesc->tdtypmod)
316 [ # # ]: 0 : ereport(ERROR,
317 : : (errcode(ERRCODE_DATATYPE_MISMATCH),
318 : : errmsg("rows returned by function are not all of the same row type")));
319 : : }
320 : :
321 [ + + ]: 298940 : if (tupdesc->tdtypeid != RECORDOID)
322 : : {
323 : : /*
324 : : * If it's not a record type, check that the datum and
325 : : * the tupledesc are still compatible.
326 : : *
327 : : * We do that here because after tuplestore_puttuple()
328 : : * we don't have the necessary information anymore.
329 : : * Right now tuplestore_puttuple() doesn't have the
330 : : * tupledesc and thus can't perform this check.
331 : : *
332 : : * Note that this would not protect against problems
333 : : * if the tupledesc could change across rows (we'd
334 : : * leave differently shaped tuples in the tuplestore,
335 : : * causing problems on retrieval), but the descriptor
336 : : * luckily can't change.
337 : : *
338 : : * Because of the version normalization in
339 : : * DatumGetHeapTupleHeader(), the tuple has to be
340 : : * marked as a datum, and because this is the !=
341 : : * RECORDOID branch, it should be versioned. For now
342 : : * just Assert() that that is the case.
343 : : */
344 : : Assert(HeapTupleHeaderIsVersionedDatum(td));
345 [ + - ]: 642 : if (HeapTupleHeaderIsVersionedDatum(td))
346 : 642 : heap_datum_check(td, tupdesc);
347 : : }
348 : :
349 : : /*
350 : : * tuplestore_puttuple needs a HeapTuple not a bare
351 : : * HeapTupleHeader, but it doesn't need all the fields.
352 : : */
353 : 298936 : tmptup.t_len = HeapTupleHeaderGetDatumLength(td);
354 : 298936 : tmptup.t_data = td;
355 : :
356 : 298936 : tuplestore_puttuple(tupstore, &tmptup);
357 : : }
358 : : else
359 : : {
360 : : /*
361 : : * NULL result from a tuple-returning function; expand it
362 : : * to a row of all nulls. We rely on the expectedDesc to
363 : : * form such rows. (Note: this would be problematic if
364 : : * tuplestore_putvalues saved the tdtypeid/tdtypmod from
365 : : * the provided descriptor, since that might not match
366 : : * what we get from the function itself. But it doesn't.)
367 : : */
368 : 53 : int natts = expectedDesc->natts;
369 : : bool *nullflags;
370 : :
371 : 53 : nullflags = palloc_array(bool, natts);
372 : 53 : memset(nullflags, true, natts * sizeof(bool));
373 : 53 : tuplestore_putvalues(tupstore, expectedDesc, NULL, nullflags);
374 : : }
375 : : }
376 : : else
377 : : {
378 : : /* Scalar-type case: just store the function result */
379 : 9945913 : tuplestore_putvalues(tupstore, tupdesc, &result, &fcinfo->isnull);
380 : : }
381 : :
382 : : /*
383 : : * Are we done?
384 : : */
385 [ + + ]: 10244902 : if (rsinfo.isDone != ExprMultipleResult)
386 : 25937 : break;
387 : :
388 : : /*
389 : : * Check that set-returning functions were properly declared.
390 : : * (Note: for historical reasons, we don't complain if a non-SRF
391 : : * returns ExprEndResult; that's treated as returning NULL.)
392 : : */
393 [ - + ]: 10218965 : if (!returnsSet)
394 [ # # ]: 0 : ereport(ERROR,
395 : : (errcode(ERRCODE_E_R_I_E_SRF_PROTOCOL_VIOLATED),
396 : : errmsg("table-function protocol for value-per-call mode was not followed")));
397 : : }
398 [ + - ]: 15334 : else if (rsinfo.returnMode == SFRM_Materialize)
399 : : {
400 : : /* check we're on the same page as the function author */
401 [ + - + - : 15334 : if (!first_time || rsinfo.isDone != ExprSingleResult || !returnsSet)
- + ]
402 [ # # ]: 0 : ereport(ERROR,
403 : : (errcode(ERRCODE_E_R_I_E_SRF_PROTOCOL_VIOLATED),
404 : : errmsg("table-function protocol for materialize mode was not followed")));
405 : : /* Done evaluating the set result */
406 : 15334 : break;
407 : : }
408 : : else
409 [ # # ]: 0 : ereport(ERROR,
410 : : (errcode(ERRCODE_E_R_I_E_SRF_PROTOCOL_VIOLATED),
411 : : errmsg("unrecognized table-function returnMode: %d",
412 : : (int) rsinfo.returnMode)));
413 : :
414 : 10218965 : first_time = false;
415 : : }
416 : :
417 : 105315 : no_function_result:
418 : :
419 : : /*
420 : : * If we got nothing from the function (ie, an empty-set or NULL result),
421 : : * we have to create the tuplestore to return, and if it's a
422 : : * non-set-returning function then insert a single all-nulls row. As
423 : : * above, we depend on the expectedDesc to manufacture the dummy row.
424 : : */
425 [ + + ]: 105315 : if (rsinfo.setResult == NULL)
426 : : {
427 : : MemoryContext oldcontext =
428 : 28942 : MemoryContextSwitchTo(econtext->ecxt_per_query_memory);
429 : :
430 : 28942 : tupstore = tuplestore_begin_heap(randomAccess, false, work_mem);
431 : 28942 : rsinfo.setResult = tupstore;
432 : 28942 : MemoryContextSwitchTo(oldcontext);
433 : :
434 [ + + ]: 28942 : if (!returnsSet)
435 : : {
436 : 24 : int natts = expectedDesc->natts;
437 : : bool *nullflags;
438 : :
439 : 24 : nullflags = palloc_array(bool, natts);
440 : 24 : memset(nullflags, true, natts * sizeof(bool));
441 : 24 : tuplestore_putvalues(tupstore, expectedDesc, NULL, nullflags);
442 : : }
443 : : }
444 : :
445 : : /*
446 : : * If function provided a tupdesc, cross-check it. We only really need to
447 : : * do this for functions returning RECORD, but might as well do it always.
448 : : */
449 [ + + ]: 105315 : if (rsinfo.setDesc)
450 : : {
451 : 76336 : tupledesc_match(expectedDesc, rsinfo.setDesc);
452 : :
453 : : /*
454 : : * If it is a dynamically-allocated TupleDesc, free it: it is
455 : : * typically allocated in a per-query context, so we must avoid
456 : : * leaking it across multiple usages.
457 : : */
458 [ + - ]: 76279 : if (rsinfo.setDesc->tdrefcount == -1)
459 : 76279 : FreeTupleDesc(rsinfo.setDesc);
460 : : }
461 : :
462 : 105258 : MemoryContextSwitchTo(callerContext);
463 : :
464 : : /* All done, pass back the tuplestore */
465 : 105258 : return rsinfo.setResult;
466 : : }
467 : :
468 : :
469 : : /*
470 : : * Prepare targetlist SRF function call for execution.
471 : : *
472 : : * This is used by nodeProjectSet.c.
473 : : */
474 : : SetExprState *
475 : 10318 : ExecInitFunctionResultSet(Expr *expr,
476 : : ExprContext *econtext, PlanState *parent)
477 : : {
478 : 10318 : SetExprState *state = makeNode(SetExprState);
479 : :
480 : 10318 : state->funcReturnsSet = true;
481 : 10318 : state->expr = expr;
482 : 10318 : state->func.fn_oid = InvalidOid;
483 : :
484 : : /*
485 : : * Initialize metadata. The expression node could be either a FuncExpr or
486 : : * an OpExpr.
487 : : */
488 [ + + ]: 10318 : if (IsA(expr, FuncExpr))
489 : : {
490 : 10314 : FuncExpr *func = (FuncExpr *) expr;
491 : :
492 : 10314 : state->args = ExecInitExprList(func->args, parent);
493 : 10314 : init_sexpr(func->funcid, func->inputcollid, expr, state, parent,
494 : : econtext->ecxt_per_query_memory, true, true);
495 : : }
496 [ + - ]: 4 : else if (IsA(expr, OpExpr))
497 : : {
498 : 4 : OpExpr *op = (OpExpr *) expr;
499 : :
500 : 4 : state->args = ExecInitExprList(op->args, parent);
501 : 4 : init_sexpr(op->opfuncid, op->inputcollid, expr, state, parent,
502 : : econtext->ecxt_per_query_memory, true, true);
503 : : }
504 : : else
505 [ # # ]: 0 : elog(ERROR, "unrecognized node type: %d",
506 : : (int) nodeTag(expr));
507 : :
508 : : /* shouldn't get here unless the selected function returns set */
509 : : Assert(state->func.fn_retset);
510 : :
511 : 10317 : return state;
512 : : }
513 : :
514 : : /*
515 : : * ExecMakeFunctionResultSet
516 : : *
517 : : * Evaluate the arguments to a set-returning function and then call the
518 : : * function itself. The argument expressions may not contain set-returning
519 : : * functions (the planner is supposed to have separated evaluation for those).
520 : : *
521 : : * This should be called in a short-lived (per-tuple) context, argContext
522 : : * needs to live until all rows have been returned (i.e. *isDone set to
523 : : * ExprEndResult or ExprSingleResult).
524 : : *
525 : : * This is used by nodeProjectSet.c.
526 : : */
527 : : Datum
528 : 3531213 : ExecMakeFunctionResultSet(SetExprState *fcache,
529 : : ExprContext *econtext,
530 : : MemoryContext argContext,
531 : : bool *isNull,
532 : : ExprDoneCond *isDone)
533 : : {
534 : : List *arguments;
535 : : Datum result;
536 : : FunctionCallInfo fcinfo;
537 : : PgStat_FunctionCallUsage fcusage;
538 : : ReturnSetInfo rsinfo;
539 : : bool callit;
540 : : int i;
541 : :
542 : 3540134 : restart:
543 : :
544 : : /* Guard against stack overflow due to overly complex expressions */
545 : 3540134 : check_stack_depth();
546 : :
547 : : /*
548 : : * If a previous call of the function returned a set result in the form of
549 : : * a tuplestore, continue reading rows from the tuplestore until it's
550 : : * empty.
551 : : */
552 [ + + ]: 3540134 : if (fcache->funcResultStore)
553 : : {
554 : 52249 : TupleTableSlot *slot = fcache->funcResultSlot;
555 : : MemoryContext oldContext;
556 : : bool foundTup;
557 : :
558 : : /*
559 : : * Have to make sure tuple in slot lives long enough, otherwise
560 : : * clearing the slot could end up trying to free something already
561 : : * freed.
562 : : */
563 : 52249 : oldContext = MemoryContextSwitchTo(slot->tts_mcxt);
564 : 52249 : foundTup = tuplestore_gettupleslot(fcache->funcResultStore, true, false,
565 : : fcache->funcResultSlot);
566 : 52249 : MemoryContextSwitchTo(oldContext);
567 : :
568 [ + + ]: 52249 : if (foundTup)
569 : : {
570 : 43356 : *isDone = ExprMultipleResult;
571 [ + + ]: 43356 : if (fcache->funcReturnsTuple)
572 : : {
573 : : /* We must return the whole tuple as a Datum. */
574 : 39264 : *isNull = false;
575 : 39264 : return ExecFetchSlotHeapTupleDatum(fcache->funcResultSlot);
576 : : }
577 : : else
578 : : {
579 : : /* Extract the first column and return it as a scalar. */
580 : 4092 : return slot_getattr(fcache->funcResultSlot, 1, isNull);
581 : : }
582 : : }
583 : : /* Exhausted the tuplestore, so clean up */
584 : 8893 : ExecReleaseTuplestoreResult(fcache);
585 : 8893 : *isDone = ExprEndResult;
586 : 8893 : *isNull = true;
587 : 8893 : return (Datum) 0;
588 : : }
589 : :
590 : : /*
591 : : * arguments is a list of expressions to evaluate before passing to the
592 : : * function manager. We skip the evaluation if it was already done in the
593 : : * previous call (ie, we are continuing the evaluation of a set-valued
594 : : * function). Otherwise, collect the current argument values into fcinfo.
595 : : *
596 : : * The arguments have to live in a context that lives at least until all
597 : : * rows from this SRF have been returned, otherwise ValuePerCall SRFs
598 : : * would reference freed memory after the first returned row.
599 : : */
600 : 3487885 : fcinfo = fcache->fcinfo;
601 : 3487885 : arguments = fcache->args;
602 [ + + ]: 3487885 : if (!fcache->setArgsValid)
603 : : {
604 : 191206 : MemoryContext oldContext = MemoryContextSwitchTo(argContext);
605 : :
606 : 191206 : ExecEvalFuncArgs(fcinfo, arguments, econtext);
607 : 191206 : MemoryContextSwitchTo(oldContext);
608 : : }
609 : : else
610 : : {
611 : : /* Reset flag (we may set it again below) */
612 : 3296679 : fcache->setArgsValid = false;
613 : : }
614 : :
615 : : /*
616 : : * Now call the function, passing the evaluated parameter values.
617 : : */
618 : :
619 : : /* Prepare a resultinfo node for communication. */
620 : 3487885 : fcinfo->resultinfo = (Node *) &rsinfo;
621 : 3487885 : rsinfo.type = T_ReturnSetInfo;
622 : 3487885 : rsinfo.econtext = econtext;
623 : 3487885 : rsinfo.expectedDesc = fcache->funcResultDesc;
624 : 3487885 : rsinfo.allowedModes = (int) (SFRM_ValuePerCall | SFRM_Materialize);
625 : : /* note we do not set SFRM_Materialize_Random or _Preferred */
626 : 3487885 : rsinfo.returnMode = SFRM_ValuePerCall;
627 : : /* isDone is filled below */
628 : 3487885 : rsinfo.setResult = NULL;
629 : 3487885 : rsinfo.setDesc = NULL;
630 : :
631 : : /*
632 : : * If function is strict, and there are any NULL arguments, skip calling
633 : : * the function.
634 : : */
635 : 3487885 : callit = true;
636 [ + + ]: 3487885 : if (fcache->func.fn_strict)
637 : : {
638 [ + + ]: 9730631 : for (i = 0; i < fcinfo->nargs; i++)
639 : : {
640 [ + + ]: 6289698 : if (fcinfo->args[i].isnull)
641 : : {
642 : 43818 : callit = false;
643 : 43818 : break;
644 : : }
645 : : }
646 : : }
647 : :
648 [ + + ]: 3487885 : if (callit)
649 : : {
650 : 3444067 : pgstat_init_function_usage(fcinfo, &fcusage);
651 : :
652 : 3444067 : fcinfo->isnull = false;
653 : 3444067 : rsinfo.isDone = ExprSingleResult;
654 : 3444067 : result = FunctionCallInvoke(fcinfo);
655 : 3442917 : *isNull = fcinfo->isnull;
656 : 3442917 : *isDone = rsinfo.isDone;
657 : :
658 : 3442917 : pgstat_end_function_usage(&fcusage,
659 : 3442917 : rsinfo.isDone != ExprMultipleResult);
660 : : }
661 : : else
662 : : {
663 : : /* for a strict SRF, result for NULL is an empty set */
664 : 43818 : result = (Datum) 0;
665 : 43818 : *isNull = true;
666 : 43818 : *isDone = ExprEndResult;
667 : : }
668 : :
669 : : /* Which protocol does function want to use? */
670 [ + + ]: 3486735 : if (rsinfo.returnMode == SFRM_ValuePerCall)
671 : : {
672 [ + + ]: 3477799 : if (*isDone != ExprEndResult)
673 : : {
674 : : /*
675 : : * Save the current argument values to re-use on the next call.
676 : : */
677 [ + + ]: 3296727 : if (*isDone == ExprMultipleResult)
678 : : {
679 : 3296724 : fcache->setArgsValid = true;
680 : : /* Register cleanup callback if we didn't already */
681 [ + + ]: 3296724 : if (!fcache->shutdown_reg)
682 : : {
683 : 13364 : RegisterExprContextCallback(econtext,
684 : : ShutdownSetExpr,
685 : : PointerGetDatum(fcache));
686 : 13364 : fcache->shutdown_reg = true;
687 : : }
688 : : }
689 : : }
690 : : }
691 [ + - ]: 8936 : else if (rsinfo.returnMode == SFRM_Materialize)
692 : : {
693 : : /* check we're on the same page as the function author */
694 [ - + ]: 8936 : if (rsinfo.isDone != ExprSingleResult)
695 [ # # ]: 0 : ereport(ERROR,
696 : : (errcode(ERRCODE_E_R_I_E_SRF_PROTOCOL_VIOLATED),
697 : : errmsg("table-function protocol for materialize mode was not followed")));
698 [ + + ]: 8936 : if (rsinfo.setResult != NULL)
699 : : {
700 : : /* prepare to return values from the tuplestore */
701 : 8921 : ExecPrepareTuplestoreResult(fcache, econtext,
702 : : rsinfo.setResult,
703 : : rsinfo.setDesc);
704 : : /* loop back to top to start returning from tuplestore */
705 : 8921 : goto restart;
706 : : }
707 : : /* if setResult was left null, treat it as empty set */
708 : 15 : *isDone = ExprEndResult;
709 : 15 : *isNull = true;
710 : 15 : result = (Datum) 0;
711 : : }
712 : : else
713 [ # # ]: 0 : ereport(ERROR,
714 : : (errcode(ERRCODE_E_R_I_E_SRF_PROTOCOL_VIOLATED),
715 : : errmsg("unrecognized table-function returnMode: %d",
716 : : (int) rsinfo.returnMode)));
717 : :
718 : 3477814 : return result;
719 : : }
720 : :
721 : :
722 : : /*
723 : : * init_sexpr - initialize a SetExprState node during first use
724 : : */
725 : : static void
726 : 59529 : init_sexpr(Oid foid, Oid input_collation, Expr *node,
727 : : SetExprState *sexpr, PlanState *parent,
728 : : MemoryContext sexprCxt, bool allowSRF, bool needDescForSRF)
729 : : {
730 : : AclResult aclresult;
731 : 59529 : size_t numargs = list_length(sexpr->args);
732 : :
733 : : /* Check permission to call function */
734 : 59529 : aclresult = object_aclcheck(ProcedureRelationId, foid, GetUserId(), ACL_EXECUTE);
735 [ + + ]: 59529 : if (aclresult != ACLCHECK_OK)
736 : 5 : aclcheck_error(aclresult, OBJECT_FUNCTION, get_func_name(foid));
737 [ - + ]: 59524 : InvokeFunctionExecuteHook(foid);
738 : :
739 : : /*
740 : : * Safety check on nargs. Under normal circumstances this should never
741 : : * fail, as parser should check sooner. But possibly it might fail if
742 : : * server has been compiled with FUNC_MAX_ARGS smaller than some functions
743 : : * declared in pg_proc?
744 : : */
745 [ - + ]: 59524 : if (list_length(sexpr->args) > FUNC_MAX_ARGS)
746 [ # # ]: 0 : ereport(ERROR,
747 : : (errcode(ERRCODE_TOO_MANY_ARGUMENTS),
748 : : errmsg_plural("cannot pass more than %d argument to a function",
749 : : "cannot pass more than %d arguments to a function",
750 : : FUNC_MAX_ARGS,
751 : : FUNC_MAX_ARGS)));
752 : :
753 : : /* Set up the primary fmgr lookup information */
754 : 59524 : fmgr_info_cxt(foid, &(sexpr->func), sexprCxt);
755 : 59524 : fmgr_info_set_expr((Node *) sexpr->expr, &(sexpr->func));
756 : :
757 : : /* Initialize the function call parameter struct as well */
758 : 59524 : sexpr->fcinfo =
759 : 59524 : (FunctionCallInfo) palloc(SizeForFunctionCallInfo(numargs));
760 : 59524 : InitFunctionCallInfoData(*sexpr->fcinfo, &(sexpr->func),
761 : : numargs,
762 : : input_collation, NULL, NULL);
763 : :
764 : : /* If function returns set, check if that's allowed by caller */
765 [ + + - + ]: 59524 : if (sexpr->func.fn_retset && !allowSRF)
766 [ # # # # ]: 0 : ereport(ERROR,
767 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
768 : : errmsg("set-valued function called in context that cannot accept a set"),
769 : : parent ? executor_errposition(parent->state,
770 : : exprLocation((Node *) node)) : 0));
771 : :
772 : : /* Otherwise, caller should have marked the sexpr correctly */
773 : : Assert(sexpr->func.fn_retset == sexpr->funcReturnsSet);
774 : :
775 : : /* If function returns set, prepare expected tuple descriptor */
776 [ + + + + ]: 59524 : if (sexpr->func.fn_retset && needDescForSRF)
777 : 10317 : {
778 : : TypeFuncClass functypclass;
779 : : Oid funcrettype;
780 : : TupleDesc tupdesc;
781 : : MemoryContext oldcontext;
782 : :
783 : 10317 : functypclass = get_expr_result_type(sexpr->func.fn_expr,
784 : : &funcrettype,
785 : : &tupdesc);
786 : :
787 : : /* Must save tupdesc in sexpr's context */
788 : 10317 : oldcontext = MemoryContextSwitchTo(sexprCxt);
789 : :
790 [ + + + + ]: 10317 : if (functypclass == TYPEFUNC_COMPOSITE ||
791 : : functypclass == TYPEFUNC_COMPOSITE_DOMAIN)
792 : : {
793 : : /* Composite data type, e.g. a table's row type */
794 : : Assert(tupdesc);
795 : : /* Must copy it out of typcache for safety */
796 : 808 : sexpr->funcResultDesc = CreateTupleDescCopy(tupdesc);
797 : 808 : sexpr->funcReturnsTuple = true;
798 : : }
799 [ + + ]: 9509 : else if (functypclass == TYPEFUNC_SCALAR)
800 : : {
801 : : /* Base data type, i.e. scalar */
802 : 9446 : tupdesc = CreateTemplateTupleDesc(1);
803 : 9446 : TupleDescInitEntry(tupdesc,
804 : : (AttrNumber) 1,
805 : : NULL,
806 : : funcrettype,
807 : : -1,
808 : : 0);
809 : 9446 : TupleDescFinalize(tupdesc);
810 : 9446 : sexpr->funcResultDesc = tupdesc;
811 : 9446 : sexpr->funcReturnsTuple = false;
812 : : }
813 [ + - ]: 63 : else if (functypclass == TYPEFUNC_RECORD)
814 : : {
815 : : /* This will work if function doesn't need an expectedDesc */
816 : 63 : sexpr->funcResultDesc = NULL;
817 : 63 : sexpr->funcReturnsTuple = true;
818 : : }
819 : : else
820 : : {
821 : : /* Else, we will fail if function needs an expectedDesc */
822 : 0 : sexpr->funcResultDesc = NULL;
823 : : }
824 : :
825 : 10317 : MemoryContextSwitchTo(oldcontext);
826 : : }
827 : : else
828 : 49207 : sexpr->funcResultDesc = NULL;
829 : :
830 : : /* Initialize additional state */
831 : 59524 : sexpr->funcResultStore = NULL;
832 : 59524 : sexpr->funcResultSlot = NULL;
833 : 59524 : sexpr->shutdown_reg = false;
834 : 59524 : }
835 : :
836 : : /*
837 : : * callback function in case a SetExprState needs to be shut down before it
838 : : * has been run to completion
839 : : */
840 : : static void
841 : 14175 : ShutdownSetExpr(Datum arg)
842 : : {
843 : 14175 : SetExprState *sexpr = castNode(SetExprState, DatumGetPointer(arg));
844 : :
845 : : /* Release any open tuplestore */
846 : 14175 : ExecReleaseTuplestoreResult(sexpr);
847 : :
848 : : /*
849 : : * If each invocation of the function can return a different row type,
850 : : * ExecReleaseTuplestoreResult will have already dropped the slot. If
851 : : * not, we must clear it here.
852 : : */
853 [ + + ]: 14175 : if (sexpr->funcResultSlot)
854 : 784 : ExecClearTuple(sexpr->funcResultSlot);
855 : :
856 : : /* Clear any active set-argument state */
857 : 14175 : sexpr->setArgsValid = false;
858 : :
859 : : /* execUtils will deregister the callback... */
860 : 14175 : sexpr->shutdown_reg = false;
861 : 14175 : }
862 : :
863 : : /*
864 : : * Evaluate arguments for a function.
865 : : */
866 : : static void
867 : 299216 : ExecEvalFuncArgs(FunctionCallInfo fcinfo,
868 : : List *argList,
869 : : ExprContext *econtext)
870 : : {
871 : : int i;
872 : : ListCell *arg;
873 : :
874 : 299216 : i = 0;
875 [ + + + + : 745724 : foreach(arg, argList)
+ + ]
876 : : {
877 : 446516 : ExprState *argstate = (ExprState *) lfirst(arg);
878 : :
879 : 446516 : fcinfo->args[i].value = ExecEvalExpr(argstate,
880 : : econtext,
881 : : &fcinfo->args[i].isnull);
882 : 446508 : i++;
883 : : }
884 : :
885 : : Assert(i == fcinfo->nargs);
886 : 299208 : }
887 : :
888 : : /*
889 : : * ExecPrepareTuplestoreResult
890 : : *
891 : : * Subroutine for ExecMakeFunctionResultSet: prepare to extract rows from a
892 : : * tuplestore function result. We must set up a funcResultSlot (unless
893 : : * already done in a previous call cycle) and verify that the function
894 : : * returned the expected tuple descriptor.
895 : : */
896 : : static void
897 : 8921 : ExecPrepareTuplestoreResult(SetExprState *sexpr,
898 : : ExprContext *econtext,
899 : : Tuplestorestate *resultStore,
900 : : TupleDesc resultDesc)
901 : : {
902 : : /*
903 : : * Any previous result must have been released. In particular, a slot not
904 : : * built from funcResultDesc must not survive to be reused here.
905 : : */
906 : : Assert(sexpr->funcResultStore == NULL);
907 : : Assert(sexpr->funcResultDesc != NULL || sexpr->funcResultSlot == NULL);
908 : :
909 : 8921 : sexpr->funcResultStore = resultStore;
910 : :
911 [ + + ]: 8921 : if (sexpr->funcResultSlot == NULL)
912 : : {
913 : : /* Create a slot so we can read data out of the tuplestore */
914 : : TupleDesc slotDesc;
915 : : MemoryContext oldcontext;
916 : :
917 : 832 : oldcontext = MemoryContextSwitchTo(sexpr->func.fn_mcxt);
918 : :
919 : : /*
920 : : * If we were not able to determine the result rowtype from context,
921 : : * and the function didn't return a tupdesc, we have to fail.
922 : : */
923 [ + + ]: 832 : if (sexpr->funcResultDesc)
924 : 784 : slotDesc = sexpr->funcResultDesc;
925 [ + - ]: 48 : else if (resultDesc)
926 : : {
927 : : /* don't assume resultDesc is long-lived */
928 : 48 : slotDesc = CreateTupleDescCopy(resultDesc);
929 : : }
930 : : else
931 : : {
932 [ # # ]: 0 : ereport(ERROR,
933 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
934 : : errmsg("function returning setof record called in "
935 : : "context that cannot accept type record")));
936 : : slotDesc = NULL; /* keep compiler quiet */
937 : : }
938 : :
939 : 832 : sexpr->funcResultSlot = MakeSingleTupleTableSlot(slotDesc,
940 : : &TTSOpsMinimalTuple);
941 : 832 : MemoryContextSwitchTo(oldcontext);
942 : : }
943 : :
944 : : /*
945 : : * If function provided a tupdesc, cross-check it. We only really need to
946 : : * do this for functions returning RECORD, but might as well do it always.
947 : : */
948 [ + - ]: 8921 : if (resultDesc)
949 : : {
950 [ + + ]: 8921 : if (sexpr->funcResultDesc)
951 : 8873 : tupledesc_match(sexpr->funcResultDesc, resultDesc);
952 : :
953 : : /*
954 : : * If it is a dynamically-allocated TupleDesc, free it: it is
955 : : * typically allocated in a per-query context, so we must avoid
956 : : * leaking it across multiple usages.
957 : : */
958 [ + - ]: 8921 : if (resultDesc->tdrefcount == -1)
959 : 8921 : FreeTupleDesc(resultDesc);
960 : : }
961 : :
962 : : /* Register cleanup callback if we didn't already */
963 [ + + ]: 8921 : if (!sexpr->shutdown_reg)
964 : : {
965 : 816 : RegisterExprContextCallback(econtext,
966 : : ShutdownSetExpr,
967 : : PointerGetDatum(sexpr));
968 : 816 : sexpr->shutdown_reg = true;
969 : : }
970 : 8921 : }
971 : :
972 : : /*
973 : : * ExecReleaseTuplestoreResult
974 : : *
975 : : * Release a tuplestore function result set up by ExecPrepareTuplestoreResult,
976 : : * if any.
977 : : */
978 : : static void
979 : 23068 : ExecReleaseTuplestoreResult(SetExprState *sexpr)
980 : : {
981 : : /*
982 : : * A slot built from a per-invocation record descriptor describes only
983 : : * this materialized result and owns a private copy of its descriptor.
984 : : * Drop it with the tuplestore so the next invocation builds a slot from
985 : : * its own result descriptor.
986 : : */
987 [ + + + + ]: 23068 : if (sexpr->funcResultSlot && sexpr->funcResultDesc == NULL)
988 : : {
989 : 48 : TupleDesc slotDesc = sexpr->funcResultSlot->tts_tupleDescriptor;
990 : :
991 : 48 : ExecDropSingleTupleTableSlot(sexpr->funcResultSlot);
992 : 48 : sexpr->funcResultSlot = NULL;
993 : :
994 : : /*
995 : : * The slot's descriptor is not reference counted, so we have to free
996 : : * the memory manually.
997 : : */
998 : 48 : FreeTupleDesc(slotDesc);
999 : : }
1000 : :
1001 [ + + ]: 23068 : if (sexpr->funcResultStore)
1002 : 8921 : tuplestore_end(sexpr->funcResultStore);
1003 : 23068 : sexpr->funcResultStore = NULL;
1004 : 23068 : }
1005 : :
1006 : : /*
1007 : : * Check that function result tuple type (src_tupdesc) matches or can
1008 : : * be considered to match what the query expects (dst_tupdesc). If
1009 : : * they don't match, ereport.
1010 : : *
1011 : : * We really only care about number of attributes and data type.
1012 : : * Also, we can ignore type mismatch on columns that are dropped in the
1013 : : * destination type, so long as the physical storage matches. This is
1014 : : * helpful in some cases involving out-of-date cached plans.
1015 : : */
1016 : : static void
1017 : 85209 : tupledesc_match(TupleDesc dst_tupdesc, TupleDesc src_tupdesc)
1018 : : {
1019 : : int i;
1020 : :
1021 [ + + ]: 85209 : if (dst_tupdesc->natts != src_tupdesc->natts)
1022 [ + - ]: 32 : ereport(ERROR,
1023 : : (errcode(ERRCODE_DATATYPE_MISMATCH),
1024 : : errmsg("function return row and query-specified return row do not match"),
1025 : : errdetail_plural("Returned row contains %d attribute, but query expects %d.",
1026 : : "Returned row contains %d attributes, but query expects %d.",
1027 : : src_tupdesc->natts,
1028 : : src_tupdesc->natts, dst_tupdesc->natts)));
1029 : :
1030 [ + + ]: 404140 : for (i = 0; i < dst_tupdesc->natts; i++)
1031 : : {
1032 : 318988 : Form_pg_attribute dattr = TupleDescAttr(dst_tupdesc, i);
1033 : 318988 : Form_pg_attribute sattr = TupleDescAttr(src_tupdesc, i);
1034 : :
1035 [ + + ]: 318988 : if (IsBinaryCoercible(sattr->atttypid, dattr->atttypid))
1036 : 318963 : continue; /* no worries */
1037 [ + - ]: 25 : if (!dattr->attisdropped)
1038 [ + - ]: 25 : ereport(ERROR,
1039 : : (errcode(ERRCODE_DATATYPE_MISMATCH),
1040 : : errmsg("function return row and query-specified return row do not match"),
1041 : : errdetail("Returned type %s at ordinal position %d, but query expects %s.",
1042 : : format_type_be(sattr->atttypid),
1043 : : i + 1,
1044 : : format_type_be(dattr->atttypid))));
1045 : :
1046 [ # # ]: 0 : if (dattr->attlen != sattr->attlen ||
1047 [ # # ]: 0 : dattr->attalign != sattr->attalign)
1048 [ # # ]: 0 : ereport(ERROR,
1049 : : (errcode(ERRCODE_DATATYPE_MISMATCH),
1050 : : errmsg("function return row and query-specified return row do not match"),
1051 : : errdetail("Physical storage mismatch on dropped attribute at ordinal position %d.",
1052 : : i + 1)));
1053 : : }
1054 : 85152 : }
|