LCOV - code coverage report
Current view: top level - src/backend/executor - functions.c (source / functions) Hit Total Coverage
Test: PostgreSQL 15devel Lines: 533 593 89.9 %
Date: 2021-12-03 03:09:03 Functions: 23 24 95.8 %
Legend: Lines: hit not hit

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

Generated by: LCOV version 1.14