LCOV - code coverage report
Current view: top level - src/backend/executor - functions.c (source / functions) Hit Total Coverage
Test: PostgreSQL 13beta1 Lines: 524 585 89.6 %
Date: 2020-06-05 19:06:29 Functions: 23 24 95.8 %
Legend: Lines: hit not hit

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

Generated by: LCOV version 1.13