LCOV - differential code coverage report
Current view: top level - src/backend/executor - execSRF.c (source / functions) Coverage Total Hit UBC GNC CBC DCB
Current: 4b3c9325757dfd8f2312e9f1a8decf4431f344ae vs e87b024bfb8dd55e3049b1b6e6ab4e810cf1abc8 Lines: 95.4 % 306 292 14 2 290 2
Current Date: 2026-11-28 16:48:44 +0900 Functions: 100.0 % 10 10 1 9
Baseline: lcov-20261128-baseline Branches: 71.0 % 200 142 58 142
Baseline Date: 2026-11-28 16:48:48 +0900 Line coverage date bins:
Legend: Lines:     hit not hit
Branches: + taken - not taken # not executed
(7,30] days: 100.0 % 18 18 18
(30,360] days: 100.0 % 4 4 2 2
(360..) days: 95.1 % 284 270 14 270
Function coverage date bins:
(7,30] days: 100.0 % 1 1 1
(360..) days: 100.0 % 9 9 1 8
Branch coverage date bins:
(7,30] days: 77.8 % 18 14 4 14
(360..) days: 70.3 % 182 128 54 128

 Age         Owner                    Branch data    TLA  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 *
 3546 andres@anarazel.de         58                 :CBC       49255 : ExecInitTableFunctionResult(Expr *expr,
                                 59                 :                :                             ExprContext *econtext, PlanState *parent)
                                 60                 :                : {
                                 61                 :          49255 :     SetExprState *state = makeNode(SetExprState);
                                 62                 :                : 
                                 63                 :          49255 :     state->funcReturnsSet = false;
                                 64                 :          49255 :     state->expr = expr;
                                 65                 :          49255 :     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         [ +  + ]:          49255 :     if (IsA(expr, FuncExpr))
                                 77                 :                :     {
                                 78                 :          49179 :         FuncExpr   *func = (FuncExpr *) expr;
                                 79                 :                : 
                                 80                 :          49179 :         state->funcReturnsSet = func->funcretset;
                                 81                 :          49179 :         state->args = ExecInitExprList(func->args, parent);
                                 82                 :                : 
 3511 tgl@sss.pgh.pa.us          83                 :          49179 :         init_sexpr(func->funcid, func->inputcollid, expr, state, parent,
 3546 andres@anarazel.de         84                 :          49179 :                    econtext->ecxt_per_query_memory, func->funcretset, false);
                                 85                 :                :     }
                                 86                 :                :     else
                                 87                 :                :     {
                                 88                 :             76 :         state->elidedFuncState = ExecInitExpr(expr, parent);
                                 89                 :                :     }
                                 90                 :                : 
                                 91                 :          49251 :     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                 :         108045 : ExecMakeTableFunctionResult(SetExprState *setexpr,
                                104                 :                :                             ExprContext *econtext,
                                105                 :                :                             MemoryContext argContext,
                                106                 :                :                             TupleDesc expectedDesc,
                                107                 :                :                             bool randomAccess)
                                108                 :                : {
                                109                 :         108045 :     Tuplestorestate *tupstore = NULL;
                                110                 :         108045 :     TupleDesc   tupdesc = NULL;
                                111                 :                :     Oid         funcrettype;
                                112                 :                :     bool        returnsTuple;
                                113                 :         108045 :     bool        returnsSet = false;
                                114                 :                :     FunctionCallInfo fcinfo;
                                115                 :                :     PgStat_FunctionCallUsage fcusage;
                                116                 :                :     ReturnSetInfo rsinfo;
                                117                 :                :     HeapTupleData tmptup;
                                118                 :                :     MemoryContext callerContext;
                                119                 :         108045 :     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                 :                :      */
 2411                           134                 :         108045 :     MemoryContextReset(argContext);
                                135                 :         108045 :     callerContext = MemoryContextSwitchTo(argContext);
                                136                 :                : 
 3546                           137                 :         108045 :     funcrettype = exprType((Node *) setexpr->expr);
                                138                 :                : 
                                139                 :         108045 :     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                 :         108045 :     rsinfo.type = T_ReturnSetInfo;
                                149                 :         108045 :     rsinfo.econtext = econtext;
                                150                 :         108045 :     rsinfo.expectedDesc = expectedDesc;
                                151                 :         108045 :     rsinfo.allowedModes = (int) (SFRM_ValuePerCall | SFRM_Materialize | SFRM_Materialize_Preferred);
                                152         [ +  + ]:         108045 :     if (randomAccess)
                                153                 :             89 :         rsinfo.allowedModes |= (int) SFRM_Materialize_Random;
                                154                 :         108045 :     rsinfo.returnMode = SFRM_ValuePerCall;
                                155                 :                :     /* isDone is filled below */
                                156                 :         108045 :     rsinfo.setResult = NULL;
                                157                 :         108045 :     rsinfo.setDesc = NULL;
                                158                 :                : 
 2863                           159                 :         108045 :     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                 :                :      */
 3546                           171         [ +  + ]:         108045 :     if (!setexpr->elidedFuncState)
                                172                 :                :     {
                                173                 :                :         /*
                                174                 :                :          * This path is similar to ExecMakeFunctionResultSet.
                                175                 :                :          */
                                176                 :         107969 :         returnsSet = setexpr->funcReturnsSet;
 2863                           177                 :         107969 :         InitFunctionCallInfoData(*fcinfo, &(setexpr->func),
                                178                 :                :                                  list_length(setexpr->args),
                                179                 :                :                                  setexpr->fcinfo->fncollation,
                                180                 :                :                                  NULL, (Node *) &rsinfo);
                                181                 :                :         /* evaluate the function's argument list */
 2411                           182         [ -  + ]:         107969 :         Assert(CurrentMemoryContext == argContext);
 2863                           183                 :         107969 :         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                 :                :          */
 3546                           190         [ +  + ]:         107961 :         if (setexpr->func.fn_strict)
                                191                 :                :         {
                                192                 :                :             int         i;
                                193                 :                : 
 2863                           194         [ +  + ]:         208436 :             for (i = 0; i < fcinfo->nargs; i++)
                                195                 :                :             {
                                196         [ +  + ]:         140682 :                 if (fcinfo->args[i].isnull)
 3546                           197                 :          27870 :                     goto no_function_result;
                                198                 :                :             }
                                199                 :                :         }
                                200                 :                :     }
                                201                 :                :     else
                                202                 :                :     {
                                203                 :                :         /* Treat setexpr as a generic expression */
 2863                           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                 :                :      */
 3546                           210                 :          80167 :     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                 :       10182942 :     {
                                218                 :                :         Datum       result;
                                219                 :                : 
                                220         [ +  + ]:       10263109 :         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                 :       10263109 :         ResetExprContext(econtext);
                                228                 :                : 
                                229                 :                :         /* Call the function or expression one time */
                                230         [ +  + ]:       10263109 :         if (!setexpr->elidedFuncState)
                                231                 :                :         {
 2863                           232                 :       10263033 :             pgstat_init_function_usage(fcinfo, &fcusage);
                                233                 :                : 
                                234                 :       10263033 :             fcinfo->isnull = false;
 3546                           235                 :       10263033 :             rsinfo.isDone = ExprSingleResult;
 2863                           236                 :       10263033 :             result = FunctionCallInvoke(fcinfo);
                                237                 :                : 
 3546                           238                 :       10260272 :             pgstat_end_function_usage(&fcusage,
                                239                 :       10260272 :                                       rsinfo.isDone != ExprMultipleResult);
                                240                 :                :         }
                                241                 :                :         else
                                242                 :                :         {
                                243                 :             76 :             result =
 2863                           244                 :             76 :                 ExecEvalExpr(setexpr->elidedFuncState, econtext, &fcinfo->isnull);
 3546                           245                 :             76 :             rsinfo.isDone = ExprSingleResult;
                                246                 :                :         }
                                247                 :                : 
                                248                 :                :         /* Which protocol does function want to use? */
                                249         [ +  + ]:       10260348 :         if (rsinfo.returnMode == SFRM_ValuePerCall)
                                250                 :                :         {
                                251                 :                :             /*
                                252                 :                :              * Check for end of result set.
                                253                 :                :              */
                                254         [ +  + ]:       10244935 :             if (rsinfo.isDone == ExprEndResult)
                                255                 :          77402 :                 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         [ +  + ]:       10208888 :             if (first_time)
                                262                 :                :             {
                                263                 :                :                 MemoryContext oldcontext =
 1289 tgl@sss.pgh.pa.us         264                 :          60948 :                     MemoryContextSwitchTo(econtext->ecxt_per_query_memory);
                                265                 :                : 
 3546 andres@anarazel.de        266                 :          60948 :                 tupstore = tuplestore_begin_heap(randomAccess, false, work_mem);
                                267                 :          60948 :                 rsinfo.setResult = tupstore;
                                268         [ +  + ]:          60948 :                 if (!returnsTuple)
                                269                 :                :                 {
 2930                           270                 :          33370 :                     tupdesc = CreateTemplateTupleDesc(1);
 3546                           271                 :          33370 :                     TupleDescInitEntry(tupdesc,
                                272                 :                :                                        (AttrNumber) 1,
                                273                 :                :                                        "column",
                                274                 :                :                                        funcrettype,
                                275                 :                :                                        -1,
                                276                 :                :                                        0);
  257 drowley@postgresql.o      277                 :          33370 :                     TupleDescFinalize(tupdesc);
 3546 andres@anarazel.de        278                 :          33370 :                     rsinfo.setDesc = tupdesc;
                                279                 :                :                 }
                                280                 :          60948 :                 MemoryContextSwitchTo(oldcontext);
                                281                 :                :             }
                                282                 :                : 
                                283                 :                :             /*
                                284                 :                :              * Store current resultset item.
                                285                 :                :              */
                                286         [ +  + ]:       10208888 :             if (returnsTuple)
                                287                 :                :             {
 2863                           288         [ +  + ]:         302978 :                 if (!fcinfo->isnull)
                                289                 :                :                 {
 3546                           290                 :         302925 :                     HeapTupleHeader td = DatumGetHeapTupleHeader(result);
                                291                 :                : 
                                292         [ +  + ]:         302925 :                     if (tupdesc == NULL)
                                293                 :                :                     {
                                294                 :                :                         MemoryContext oldcontext =
 1289 tgl@sss.pgh.pa.us         295                 :          27541 :                             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                 :                :                          */
 3546 andres@anarazel.de        303                 :          27541 :                         tupdesc = lookup_rowtype_tupdesc_copy(HeapTupleHeaderGetTypeId(td),
                                304                 :                :                                                               HeapTupleHeaderGetTypMod(td));
                                305                 :          27541 :                         rsinfo.setDesc = tupdesc;
                                306                 :          27541 :                         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         [ +  - ]:         275384 :                         if (HeapTupleHeaderGetTypeId(td) != tupdesc->tdtypeid ||
                                315         [ -  + ]:         275384 :                             HeapTupleHeaderGetTypMod(td) != tupdesc->tdtypmod)
 3546 andres@anarazel.de        316         [ #  # ]:UBC           0 :                             ereport(ERROR,
                                317                 :                :                                     (errcode(ERRCODE_DATATYPE_MISMATCH),
                                318                 :                :                                      errmsg("rows returned by function are not all of the same row type")));
                                319                 :                :                     }
                                320                 :                : 
   19 andres@anarazel.de        321         [ +  + ]:CBC      302925 :                     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         [ -  + ]:            642 :                         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                 :                :                      */
 3546                           353                 :         302921 :                     tmptup.t_len = HeapTupleHeaderGetDatumLength(td);
                                354                 :         302921 :                     tmptup.t_data = td;
                                355                 :                : 
                                356                 :         302921 :                     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                 :                : 
  103 michael@paquier.xyz       371                 :GNC          53 :                     nullflags = palloc_array(bool, natts);
 3546 andres@anarazel.de        372                 :CBC          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 */
 2863                           379                 :        9905910 :                 tuplestore_putvalues(tupstore, tupdesc, &result, &fcinfo->isnull);
                                380                 :                :             }
                                381                 :                : 
                                382                 :                :             /*
                                383                 :                :              * Are we done?
                                384                 :                :              */
 3546                           385         [ +  + ]:       10208884 :             if (rsinfo.isDone != ExprMultipleResult)
                                386                 :          25942 :                 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                 :                :              */
 2091 tgl@sss.pgh.pa.us         393         [ -  + ]:       10182942 :             if (!returnsSet)
 2091 tgl@sss.pgh.pa.us         394         [ #  # ]:UBC           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                 :                :         }
 3546 andres@anarazel.de        398         [ +  - ]:CBC       15413 :         else if (rsinfo.returnMode == SFRM_Materialize)
                                399                 :                :         {
                                400                 :                :             /* check we're on the same page as the function author */
 2091 tgl@sss.pgh.pa.us         401   [ +  -  +  -  :          15413 :             if (!first_time || rsinfo.isDone != ExprSingleResult || !returnsSet)
                                              -  + ]
 3546 andres@anarazel.de        402         [ #  # ]:UBC           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 */
 3546 andres@anarazel.de        406                 :CBC       15413 :             break;
                                407                 :                :         }
                                408                 :                :         else
 3546 andres@anarazel.de        409         [ #  # ]:UBC           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                 :                : 
 3546 andres@anarazel.de        414                 :CBC    10182942 :         first_time = false;
                                415                 :                :     }
                                416                 :                : 
                                417                 :         105272 : 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         [ +  + ]:         105272 :     if (rsinfo.setResult == NULL)
                                426                 :                :     {
                                427                 :                :         MemoryContext oldcontext =
 1289 tgl@sss.pgh.pa.us         428                 :          28932 :             MemoryContextSwitchTo(econtext->ecxt_per_query_memory);
                                429                 :                : 
 3546 andres@anarazel.de        430                 :          28932 :         tupstore = tuplestore_begin_heap(randomAccess, false, work_mem);
                                431                 :          28932 :         rsinfo.setResult = tupstore;
 2411                           432                 :          28932 :         MemoryContextSwitchTo(oldcontext);
                                433                 :                : 
 3546                           434         [ +  + ]:          28932 :         if (!returnsSet)
                                435                 :                :         {
                                436                 :             24 :             int         natts = expectedDesc->natts;
                                437                 :                :             bool       *nullflags;
                                438                 :                : 
  103 michael@paquier.xyz       439                 :GNC          24 :             nullflags = palloc_array(bool, natts);
 3546 andres@anarazel.de        440                 :CBC          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         [ +  + ]:         105272 :     if (rsinfo.setDesc)
                                450                 :                :     {
                                451                 :          76303 :         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         [ +  - ]:          76246 :         if (rsinfo.setDesc->tdrefcount == -1)
                                459                 :          76246 :             FreeTupleDesc(rsinfo.setDesc);
                                460                 :                :     }
                                461                 :                : 
                                462                 :         105215 :     MemoryContextSwitchTo(callerContext);
                                463                 :                : 
                                464                 :                :     /* All done, pass back the tuplestore */
                                465                 :         105215 :     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                 :          10308 : ExecInitFunctionResultSet(Expr *expr,
                                476                 :                :                           ExprContext *econtext, PlanState *parent)
                                477                 :                : {
                                478                 :          10308 :     SetExprState *state = makeNode(SetExprState);
                                479                 :                : 
                                480                 :          10308 :     state->funcReturnsSet = true;
                                481                 :          10308 :     state->expr = expr;
                                482                 :          10308 :     state->func.fn_oid = InvalidOid;
                                483                 :                : 
                                484                 :                :     /*
                                485                 :                :      * Initialize metadata.  The expression node could be either a FuncExpr or
                                486                 :                :      * an OpExpr.
                                487                 :                :      */
                                488         [ +  + ]:          10308 :     if (IsA(expr, FuncExpr))
                                489                 :                :     {
                                490                 :          10304 :         FuncExpr   *func = (FuncExpr *) expr;
                                491                 :                : 
                                492                 :          10304 :         state->args = ExecInitExprList(func->args, parent);
 3511 tgl@sss.pgh.pa.us         493                 :          10304 :         init_sexpr(func->funcid, func->inputcollid, expr, state, parent,
                                494                 :                :                    econtext->ecxt_per_query_memory, true, true);
                                495                 :                :     }
 3546 andres@anarazel.de        496         [ +  - ]:              4 :     else if (IsA(expr, OpExpr))
                                497                 :                :     {
                                498                 :              4 :         OpExpr     *op = (OpExpr *) expr;
                                499                 :                : 
                                500                 :              4 :         state->args = ExecInitExprList(op->args, parent);
 3511 tgl@sss.pgh.pa.us         501                 :              4 :         init_sexpr(op->opfuncid, op->inputcollid, expr, state, parent,
                                502                 :                :                    econtext->ecxt_per_query_memory, true, true);
                                503                 :                :     }
                                504                 :                :     else
 3546 andres@anarazel.de        505         [ #  # ]:UBC           0 :         elog(ERROR, "unrecognized node type: %d",
                                506                 :                :              (int) nodeTag(expr));
                                507                 :                : 
                                508                 :                :     /* shouldn't get here unless the selected function returns set */
 3546 andres@anarazel.de        509         [ -  + ]:CBC       10307 :     Assert(state->func.fn_retset);
                                510                 :                : 
                                511                 :          10307 :     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                 :        3420545 : 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                 :        3429466 : restart:
                                543                 :                : 
                                544                 :                :     /* Guard against stack overflow due to overly complex expressions */
                                545                 :        3429466 :     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         [ +  + ]:        3429466 :     if (fcache->funcResultStore)
                                553                 :                :     {
 3338                           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                 :                :         {
 3546                           570                 :          43356 :             *isDone = ExprMultipleResult;
                                571         [ +  + ]:          43356 :             if (fcache->funcReturnsTuple)
                                572                 :                :             {
                                573                 :                :                 /* We must return the whole tuple as a Datum. */
                                574                 :          39264 :                 *isNull = false;
 2935                           575                 :          39264 :                 return ExecFetchSlotHeapTupleDatum(fcache->funcResultSlot);
                                576                 :                :             }
                                577                 :                :             else
                                578                 :                :             {
                                579                 :                :                 /* Extract the first column and return it as a scalar. */
 3546                           580                 :           4092 :                 return slot_getattr(fcache->funcResultSlot, 1, isNull);
                                581                 :                :             }
                                582                 :                :         }
                                583                 :                :         /* Exhausted the tuplestore, so clean up */
   19 rhaas@postgresql.org      584                 :           8893 :         ExecReleaseTuplestoreResult(fcache);
 3546 andres@anarazel.de        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                 :                :      */
 2863                           600                 :        3377217 :     fcinfo = fcache->fcinfo;
 3546                           601                 :        3377217 :     arguments = fcache->args;
                                602         [ +  + ]:        3377217 :     if (!fcache->setArgsValid)
                                603                 :                :     {
 3338                           604                 :         189800 :         MemoryContext oldContext = MemoryContextSwitchTo(argContext);
                                605                 :                : 
 3546                           606                 :         189800 :         ExecEvalFuncArgs(fcinfo, arguments, econtext);
 3338                           607                 :         189800 :         MemoryContextSwitchTo(oldContext);
                                608                 :                :     }
                                609                 :                :     else
                                610                 :                :     {
                                611                 :                :         /* Reset flag (we may set it again below) */
 3546                           612                 :        3187417 :         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                 :        3377217 :     fcinfo->resultinfo = (Node *) &rsinfo;
                                621                 :        3377217 :     rsinfo.type = T_ReturnSetInfo;
                                622                 :        3377217 :     rsinfo.econtext = econtext;
                                623                 :        3377217 :     rsinfo.expectedDesc = fcache->funcResultDesc;
                                624                 :        3377217 :     rsinfo.allowedModes = (int) (SFRM_ValuePerCall | SFRM_Materialize);
                                625                 :                :     /* note we do not set SFRM_Materialize_Random or _Preferred */
                                626                 :        3377217 :     rsinfo.returnMode = SFRM_ValuePerCall;
                                627                 :                :     /* isDone is filled below */
                                628                 :        3377217 :     rsinfo.setResult = NULL;
                                629                 :        3377217 :     rsinfo.setDesc = NULL;
                                630                 :                : 
                                631                 :                :     /*
                                632                 :                :      * If function is strict, and there are any NULL arguments, skip calling
                                633                 :                :      * the function.
                                634                 :                :      */
                                635                 :        3377217 :     callit = true;
                                636         [ +  + ]:        3377217 :     if (fcache->func.fn_strict)
                                637                 :                :     {
                                638         [ +  + ]:        9401284 :         for (i = 0; i < fcinfo->nargs; i++)
                                639                 :                :         {
 2863                           640         [ +  + ]:        6071021 :             if (fcinfo->args[i].isnull)
                                641                 :                :             {
 3546                           642                 :          43820 :                 callit = false;
                                643                 :          43820 :                 break;
                                644                 :                :             }
                                645                 :                :         }
                                646                 :                :     }
                                647                 :                : 
                                648         [ +  + ]:        3377217 :     if (callit)
                                649                 :                :     {
                                650                 :        3333397 :         pgstat_init_function_usage(fcinfo, &fcusage);
                                651                 :                : 
                                652                 :        3333397 :         fcinfo->isnull = false;
                                653                 :        3333397 :         rsinfo.isDone = ExprSingleResult;
                                654                 :        3333397 :         result = FunctionCallInvoke(fcinfo);
                                655                 :        3332247 :         *isNull = fcinfo->isnull;
                                656                 :        3332247 :         *isDone = rsinfo.isDone;
                                657                 :                : 
                                658                 :        3332247 :         pgstat_end_function_usage(&fcusage,
                                659                 :        3332247 :                                   rsinfo.isDone != ExprMultipleResult);
                                660                 :                :     }
                                661                 :                :     else
                                662                 :                :     {
                                663                 :                :         /* for a strict SRF, result for NULL is an empty set */
                                664                 :          43820 :         result = (Datum) 0;
                                665                 :          43820 :         *isNull = true;
                                666                 :          43820 :         *isDone = ExprEndResult;
                                667                 :                :     }
                                668                 :                : 
                                669                 :                :     /* Which protocol does function want to use? */
                                670         [ +  + ]:        3376067 :     if (rsinfo.returnMode == SFRM_ValuePerCall)
                                671                 :                :     {
                                672         [ +  + ]:        3367131 :         if (*isDone != ExprEndResult)
                                673                 :                :         {
                                674                 :                :             /*
                                675                 :                :              * Save the current argument values to re-use on the next call.
                                676                 :                :              */
                                677         [ +  + ]:        3187465 :             if (*isDone == ExprMultipleResult)
                                678                 :                :             {
                                679                 :        3187462 :                 fcache->setArgsValid = true;
                                680                 :                :                 /* Register cleanup callback if we didn't already */
                                681         [ +  + ]:        3187462 :                 if (!fcache->shutdown_reg)
                                682                 :                :                 {
                                683                 :          12690 :                     RegisterExprContextCallback(econtext,
                                684                 :                :                                                 ShutdownSetExpr,
                                685                 :                :                                                 PointerGetDatum(fcache));
                                686                 :          12690 :                     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)
 3546 andres@anarazel.de        695         [ #  # ]:UBC           0 :             ereport(ERROR,
                                696                 :                :                     (errcode(ERRCODE_E_R_I_E_SRF_PROTOCOL_VIOLATED),
                                697                 :                :                      errmsg("table-function protocol for materialize mode was not followed")));
 3546 andres@anarazel.de        698         [ +  + ]:CBC        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
 3546 andres@anarazel.de        713         [ #  # ]:UBC           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                 :                : 
 3546 andres@anarazel.de        718                 :CBC     3367146 :     return result;
                                719                 :                : }
                                720                 :                : 
                                721                 :                : 
                                722                 :                : /*
                                723                 :                :  * init_sexpr - initialize a SetExprState node during first use
                                724                 :                :  */
                                725                 :                : static void
 3511 tgl@sss.pgh.pa.us         726                 :          59487 : 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;
 2863 andres@anarazel.de        731                 :          59487 :     size_t      numargs = list_length(sexpr->args);
                                732                 :                : 
                                733                 :                :     /* Check permission to call function */
 1476 peter@eisentraut.org      734                 :          59487 :     aclresult = object_aclcheck(ProcedureRelationId, foid, GetUserId(), ACL_EXECUTE);
 3546 andres@anarazel.de        735         [ +  + ]:          59487 :     if (aclresult != ACLCHECK_OK)
 3283 peter_e@gmx.net           736                 :              5 :         aclcheck_error(aclresult, OBJECT_FUNCTION, get_func_name(foid));
 3546 andres@anarazel.de        737         [ -  + ]:          59482 :     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         [ -  + ]:          59482 :     if (list_length(sexpr->args) > FUNC_MAX_ARGS)
 3546 andres@anarazel.de        746         [ #  # ]:UBC           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 */
 3546 andres@anarazel.de        754                 :CBC       59482 :     fmgr_info_cxt(foid, &(sexpr->func), sexprCxt);
                                755                 :          59482 :     fmgr_info_set_expr((Node *) sexpr->expr, &(sexpr->func));
                                756                 :                : 
                                757                 :                :     /* Initialize the function call parameter struct as well */
 2863                           758                 :          59482 :     sexpr->fcinfo =
                                759                 :          59482 :         (FunctionCallInfo) palloc(SizeForFunctionCallInfo(numargs));
                                760                 :          59482 :     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 */
 3546                           765   [ +  +  -  + ]:          59482 :     if (sexpr->func.fn_retset && !allowSRF)
 3546 andres@anarazel.de        766   [ #  #  #  # ]:UBC           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 */
 3546 andres@anarazel.de        773         [ -  + ]:CBC       59482 :     Assert(sexpr->func.fn_retset == sexpr->funcReturnsSet);
                                774                 :                : 
                                775                 :                :     /* If function returns set, prepare expected tuple descriptor */
                                776   [ +  +  +  + ]:          59482 :     if (sexpr->func.fn_retset && needDescForSRF)
                                777                 :          10307 :     {
                                778                 :                :         TypeFuncClass functypclass;
                                779                 :                :         Oid         funcrettype;
                                780                 :                :         TupleDesc   tupdesc;
                                781                 :                :         MemoryContext oldcontext;
                                782                 :                : 
                                783                 :          10307 :         functypclass = get_expr_result_type(sexpr->func.fn_expr,
                                784                 :                :                                             &funcrettype,
                                785                 :                :                                             &tupdesc);
                                786                 :                : 
                                787                 :                :         /* Must save tupdesc in sexpr's context */
                                788                 :          10307 :         oldcontext = MemoryContextSwitchTo(sexprCxt);
                                789                 :                : 
 3320 tgl@sss.pgh.pa.us         790   [ +  +  +  + ]:          10307 :         if (functypclass == TYPEFUNC_COMPOSITE ||
                                791                 :                :             functypclass == TYPEFUNC_COMPOSITE_DOMAIN)
                                792                 :                :         {
                                793                 :                :             /* Composite data type, e.g. a table's row type */
 3546 andres@anarazel.de        794         [ -  + ]:            808 :             Assert(tupdesc);
                                795                 :                :             /* Must copy it out of typcache for safety */
                                796                 :            808 :             sexpr->funcResultDesc = CreateTupleDescCopy(tupdesc);
                                797                 :            808 :             sexpr->funcReturnsTuple = true;
                                798                 :                :         }
                                799         [ +  + ]:           9499 :         else if (functypclass == TYPEFUNC_SCALAR)
                                800                 :                :         {
                                801                 :                :             /* Base data type, i.e. scalar */
 2930                           802                 :           9436 :             tupdesc = CreateTemplateTupleDesc(1);
 3546                           803                 :           9436 :             TupleDescInitEntry(tupdesc,
                                804                 :                :                                (AttrNumber) 1,
                                805                 :                :                                NULL,
                                806                 :                :                                funcrettype,
                                807                 :                :                                -1,
                                808                 :                :                                0);
  257 drowley@postgresql.o      809                 :           9436 :             TupleDescFinalize(tupdesc);
 3546 andres@anarazel.de        810                 :           9436 :             sexpr->funcResultDesc = tupdesc;
                                811                 :           9436 :             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 */
 3546 andres@anarazel.de        822                 :UBC           0 :             sexpr->funcResultDesc = NULL;
                                823                 :                :         }
                                824                 :                : 
 3546 andres@anarazel.de        825                 :CBC       10307 :         MemoryContextSwitchTo(oldcontext);
                                826                 :                :     }
                                827                 :                :     else
                                828                 :          49175 :         sexpr->funcResultDesc = NULL;
                                829                 :                : 
                                830                 :                :     /* Initialize additional state */
                                831                 :          59482 :     sexpr->funcResultStore = NULL;
                                832                 :          59482 :     sexpr->funcResultSlot = NULL;
                                833                 :          59482 :     sexpr->shutdown_reg = false;
                                834                 :          59482 : }
                                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                 :          13509 : ShutdownSetExpr(Datum arg)
                                842                 :                : {
                                843                 :          13509 :     SetExprState *sexpr = castNode(SetExprState, DatumGetPointer(arg));
                                844                 :                : 
                                845                 :                :     /* Release any open tuplestore */
   19 rhaas@postgresql.org      846                 :          13509 :     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                 :                :      */
 3546 andres@anarazel.de        853         [ +  + ]:          13509 :     if (sexpr->funcResultSlot)
                                854                 :            792 :         ExecClearTuple(sexpr->funcResultSlot);
                                855                 :                : 
                                856                 :                :     /* Clear any active set-argument state */
                                857                 :          13509 :     sexpr->setArgsValid = false;
                                858                 :                : 
                                859                 :                :     /* execUtils will deregister the callback... */
                                860                 :          13509 :     sexpr->shutdown_reg = false;
                                861                 :          13509 : }
                                862                 :                : 
                                863                 :                : /*
                                864                 :                :  * Evaluate arguments for a function.
                                865                 :                :  */
                                866                 :                : static void
                                867                 :         297769 : ExecEvalFuncArgs(FunctionCallInfo fcinfo,
                                868                 :                :                  List *argList,
                                869                 :                :                  ExprContext *econtext)
                                870                 :                : {
                                871                 :                :     int         i;
                                872                 :                :     ListCell   *arg;
                                873                 :                : 
                                874                 :         297769 :     i = 0;
                                875   [ +  +  +  +  :         742075 :     foreach(arg, argList)
                                              +  + ]
                                876                 :                :     {
                                877                 :         444314 :         ExprState  *argstate = (ExprState *) lfirst(arg);
                                878                 :                : 
 2863                           879                 :         444314 :         fcinfo->args[i].value = ExecEvalExpr(argstate,
                                880                 :                :                                              econtext,
                                881                 :                :                                              &fcinfo->args[i].isnull);
 3546                           882                 :         444306 :         i++;
                                883                 :                :     }
                                884                 :                : 
                                885         [ -  + ]:         297761 :     Assert(i == fcinfo->nargs);
                                886                 :         297761 : }
                                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                 :                :      */
   19 rhaas@postgresql.org      906         [ -  + ]:           8921 :     Assert(sexpr->funcResultStore == NULL);
                                907   [ +  +  -  + ]:           8921 :     Assert(sexpr->funcResultDesc != NULL || sexpr->funcResultSlot == NULL);
                                908                 :                : 
 3546 andres@anarazel.de        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                 :            840 :         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         [ +  + ]:            840 :         if (sexpr->funcResultDesc)
                                924                 :            792 :             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                 :                :         {
 3546 andres@anarazel.de        932         [ #  # ]:UBC           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                 :                : 
 2935 andres@anarazel.de        939                 :CBC         840 :         sexpr->funcResultSlot = MakeSingleTupleTableSlot(slotDesc,
                                940                 :                :                                                          &TTSOpsMinimalTuple);
 3546                           941                 :            840 :         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                 :            824 :         RegisterExprContextCallback(econtext,
                                966                 :                :                                     ShutdownSetExpr,
                                967                 :                :                                     PointerGetDatum(sexpr));
                                968                 :            824 :         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
   19 rhaas@postgresql.org      979                 :          22402 : 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   [ +  +  +  + ]:          22402 :     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         [ +  + ]:          22402 :     if (sexpr->funcResultStore)
                               1002                 :           8921 :         tuplestore_end(sexpr->funcResultStore);
                               1003                 :          22402 :     sexpr->funcResultStore = NULL;
                               1004                 :          22402 : }
                               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
 3546 andres@anarazel.de       1017                 :          85176 : tupledesc_match(TupleDesc dst_tupdesc, TupleDesc src_tupdesc)
                               1018                 :                : {
                               1019                 :                :     int         i;
                               1020                 :                : 
                               1021         [ +  + ]:          85176 :     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         [ +  + ]:         406790 :     for (i = 0; i < dst_tupdesc->natts; i++)
                               1031                 :                :     {
 3387                          1032                 :         321671 :         Form_pg_attribute dattr = TupleDescAttr(dst_tupdesc, i);
                               1033                 :         321671 :         Form_pg_attribute sattr = TupleDescAttr(src_tupdesc, i);
                               1034                 :                : 
 3546                          1035         [ +  + ]:         321671 :         if (IsBinaryCoercible(sattr->atttypid, dattr->atttypid))
                               1036                 :         321646 :             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                 :                : 
 3546 andres@anarazel.de       1046         [ #  # ]:UBC           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                 :                :     }
 3546 andres@anarazel.de       1054                 :CBC       85119 : }
        

Generated by: LCOV version 2.0-1