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

Generated by: LCOV version 1.13