LCOV - code coverage report
Current view: top level - src/pl/plpgsql/src - pl_exec.c (source / functions) Coverage Total Hit
Test: PostgreSQL 20devel Lines: 90.9 % 2780 2526
Test Date: 2026-11-25 01:16:13 Functions: 100.0 % 100 100
Legend: Lines:     hit not hit
Branches: + taken - not taken # not executed
Branches: 68.4 % 1950 1334

             Branch data     Line data    Source code
       1                 :             : /*-------------------------------------------------------------------------
       2                 :             :  *
       3                 :             :  * pl_exec.c        - Executor for the PL/pgSQL
       4                 :             :  *            procedural language
       5                 :             :  *
       6                 :             :  * Portions Copyright (c) 1996-2026, PostgreSQL Global Development Group
       7                 :             :  * Portions Copyright (c) 1994, Regents of the University of California
       8                 :             :  *
       9                 :             :  *
      10                 :             :  * IDENTIFICATION
      11                 :             :  *    src/pl/plpgsql/src/pl_exec.c
      12                 :             :  *
      13                 :             :  *-------------------------------------------------------------------------
      14                 :             :  */
      15                 :             : 
      16                 :             : #include "postgres.h"
      17                 :             : 
      18                 :             : #include <ctype.h>
      19                 :             : 
      20                 :             : #include "access/detoast.h"
      21                 :             : #include "access/htup_details.h"
      22                 :             : #include "access/tupconvert.h"
      23                 :             : #include "catalog/pg_proc.h"
      24                 :             : #include "catalog/pg_type.h"
      25                 :             : #include "executor/execExpr.h"
      26                 :             : #include "executor/spi.h"
      27                 :             : #include "executor/tstoreReceiver.h"
      28                 :             : #include "funcapi.h"
      29                 :             : #include "mb/stringinfo_mb.h"
      30                 :             : #include "miscadmin.h"
      31                 :             : #include "nodes/nodeFuncs.h"
      32                 :             : #include "nodes/supportnodes.h"
      33                 :             : #include "optimizer/optimizer.h"
      34                 :             : #include "parser/parse_coerce.h"
      35                 :             : #include "parser/parse_type.h"
      36                 :             : #include "plpgsql.h"
      37                 :             : #include "storage/proc.h"
      38                 :             : #include "tcop/cmdtag.h"
      39                 :             : #include "tcop/pquery.h"
      40                 :             : #include "utils/array.h"
      41                 :             : #include "utils/builtins.h"
      42                 :             : #include "utils/datum.h"
      43                 :             : #include "utils/fmgroids.h"
      44                 :             : #include "utils/lsyscache.h"
      45                 :             : #include "utils/memutils.h"
      46                 :             : #include "utils/rel.h"
      47                 :             : #include "utils/snapmgr.h"
      48                 :             : #include "utils/syscache.h"
      49                 :             : #include "utils/typcache.h"
      50                 :             : 
      51                 :             : /*
      52                 :             :  * All plpgsql function executions within a single transaction share the same
      53                 :             :  * executor EState for evaluating "simple" expressions.  Each function call
      54                 :             :  * creates its own "eval_econtext" ExprContext within this estate for
      55                 :             :  * per-evaluation workspace.  eval_econtext is freed at normal function exit,
      56                 :             :  * and the EState is freed at transaction end (in case of error, we assume
      57                 :             :  * that the abort mechanisms clean it all up).  Furthermore, any exception
      58                 :             :  * block within a function has to have its own eval_econtext separate from
      59                 :             :  * the containing function's, so that we can clean up ExprContext callbacks
      60                 :             :  * properly at subtransaction exit.  We maintain a stack that tracks the
      61                 :             :  * individual econtexts so that we can clean up correctly at subxact exit.
      62                 :             :  *
      63                 :             :  * This arrangement is a bit tedious to maintain, but it's worth the trouble
      64                 :             :  * so that we don't have to re-prepare simple expressions on each trip through
      65                 :             :  * a function.  (We assume the case to optimize is many repetitions of a
      66                 :             :  * function within a transaction.)
      67                 :             :  *
      68                 :             :  * However, there's no value in trying to amortize simple expression setup
      69                 :             :  * across multiple executions of a DO block (inline code block), since there
      70                 :             :  * can never be any.  If we use the shared EState for a DO block, the expr
      71                 :             :  * state trees are effectively leaked till end of transaction, and that can
      72                 :             :  * add up if the user keeps on submitting DO blocks.  Therefore, each DO block
      73                 :             :  * has its own simple-expression EState, which is cleaned up at exit from
      74                 :             :  * plpgsql_inline_handler().  DO blocks still use the simple_econtext_stack,
      75                 :             :  * though, so that subxact abort cleanup does the right thing.
      76                 :             :  *
      77                 :             :  * (However, if a DO block executes COMMIT or ROLLBACK, then exec_stmt_commit
      78                 :             :  * or exec_stmt_rollback will unlink it from the DO's simple-expression EState
      79                 :             :  * and create a new shared EState that will be used thenceforth.  The original
      80                 :             :  * EState will be cleaned up when we get back to plpgsql_inline_handler.  This
      81                 :             :  * is a bit ugly, but it isn't worth doing better, since scenarios like this
      82                 :             :  * can't result in indefinite accumulation of state trees.)
      83                 :             :  */
      84                 :             : typedef struct SimpleEcontextStackEntry
      85                 :             : {
      86                 :             :     ExprContext *stack_econtext;    /* a stacked econtext */
      87                 :             :     SubTransactionId xact_subxid;   /* ID for current subxact */
      88                 :             :     struct SimpleEcontextStackEntry *next;  /* next stack entry up */
      89                 :             : } SimpleEcontextStackEntry;
      90                 :             : 
      91                 :             : static EState *shared_simple_eval_estate = NULL;
      92                 :             : static SimpleEcontextStackEntry *simple_econtext_stack = NULL;
      93                 :             : 
      94                 :             : /*
      95                 :             :  * In addition to the shared simple-eval EState, we have a shared resource
      96                 :             :  * owner that holds refcounts on the CachedPlans for any "simple" expressions
      97                 :             :  * we have evaluated in the current transaction.  This allows us to avoid
      98                 :             :  * continually grabbing and releasing a plan refcount when a simple expression
      99                 :             :  * is used over and over.  (DO blocks use their own resowner, in exactly the
     100                 :             :  * same way described above for shared_simple_eval_estate.)
     101                 :             :  */
     102                 :             : static ResourceOwner shared_simple_eval_resowner = NULL;
     103                 :             : 
     104                 :             : /*
     105                 :             :  * Memory management within a plpgsql function generally works with three
     106                 :             :  * contexts:
     107                 :             :  *
     108                 :             :  * 1. Function-call-lifespan data, such as variable values, is kept in the
     109                 :             :  * "main" context, a/k/a the "SPI Proc" context established by SPI_connect().
     110                 :             :  * This is usually the CurrentMemoryContext while running code in this module
     111                 :             :  * (which is not good, because careless coding can easily cause
     112                 :             :  * function-lifespan memory leaks, but we live with it for now).
     113                 :             :  *
     114                 :             :  * 2. Some statement-execution routines need statement-lifespan workspace.
     115                 :             :  * A suitable context is created on-demand by get_stmt_mcontext(), and must
     116                 :             :  * be reset at the end of the requesting routine.  Error recovery will clean
     117                 :             :  * it up automatically.  Nested statements requiring statement-lifespan
     118                 :             :  * workspace will result in a stack of such contexts, see push_stmt_mcontext().
     119                 :             :  *
     120                 :             :  * 3. We use the eval_econtext's per-tuple memory context for expression
     121                 :             :  * evaluation, and as a general-purpose workspace for short-lived allocations.
     122                 :             :  * Such allocations usually aren't explicitly freed, but are left to be
     123                 :             :  * cleaned up by a context reset, typically done by exec_eval_cleanup().
     124                 :             :  *
     125                 :             :  * These macros are for use in making short-lived allocations:
     126                 :             :  */
     127                 :             : #define get_eval_mcontext(estate) \
     128                 :             :     ((estate)->eval_econtext->ecxt_per_tuple_memory)
     129                 :             : #define eval_mcontext_alloc(estate, sz) \
     130                 :             :     MemoryContextAlloc(get_eval_mcontext(estate), sz)
     131                 :             : #define eval_mcontext_alloc0(estate, sz) \
     132                 :             :     MemoryContextAllocZero(get_eval_mcontext(estate), sz)
     133                 :             : 
     134                 :             : /*
     135                 :             :  * We use two session-wide hash tables for caching cast information.
     136                 :             :  *
     137                 :             :  * cast_expr_hash entries (of type plpgsql_CastExprHashEntry) hold compiled
     138                 :             :  * expression trees for casts.  These survive for the life of the session and
     139                 :             :  * are shared across all PL/pgSQL functions and DO blocks.  At some point it
     140                 :             :  * might be worth invalidating them after pg_cast changes, but for the moment
     141                 :             :  * we don't bother.
     142                 :             :  *
     143                 :             :  * There is a separate hash table shared_cast_hash (with entries of type
     144                 :             :  * plpgsql_CastHashEntry) containing evaluation state trees for these
     145                 :             :  * expressions, which are managed in the same way as simple expressions
     146                 :             :  * (i.e., we assume cast expressions are always simple).
     147                 :             :  *
     148                 :             :  * As with simple expressions, DO blocks don't use the shared_cast_hash table
     149                 :             :  * but must have their own evaluation state trees.  This isn't ideal, but we
     150                 :             :  * don't want to deal with multiple simple_eval_estates within a DO block.
     151                 :             :  */
     152                 :             : typedef struct                  /* lookup key for cast info */
     153                 :             : {
     154                 :             :     /* NB: we assume this struct contains no padding bytes */
     155                 :             :     Oid         srctype;        /* source type for cast */
     156                 :             :     Oid         dsttype;        /* destination type for cast */
     157                 :             :     int32       srctypmod;      /* source typmod for cast */
     158                 :             :     int32       dsttypmod;      /* destination typmod for cast */
     159                 :             : } plpgsql_CastHashKey;
     160                 :             : 
     161                 :             : typedef struct                  /* cast_expr_hash table entry */
     162                 :             : {
     163                 :             :     plpgsql_CastHashKey key;    /* hash key --- MUST BE FIRST */
     164                 :             :     Expr       *cast_expr;      /* cast expression, or NULL if no-op cast */
     165                 :             :     CachedExpression *cast_cexpr;   /* cached expression backing the above */
     166                 :             : } plpgsql_CastExprHashEntry;
     167                 :             : 
     168                 :             : typedef struct                  /* cast_hash table entry */
     169                 :             : {
     170                 :             :     plpgsql_CastHashKey key;    /* hash key --- MUST BE FIRST */
     171                 :             :     plpgsql_CastExprHashEntry *cast_centry; /* link to matching expr entry */
     172                 :             :     /* ExprState is valid only when cast_lxid matches current LXID */
     173                 :             :     ExprState  *cast_exprstate; /* expression's eval tree */
     174                 :             :     bool        cast_in_use;    /* true while we're executing eval tree */
     175                 :             :     LocalTransactionId cast_lxid;
     176                 :             : } plpgsql_CastHashEntry;
     177                 :             : 
     178                 :             : static HTAB *cast_expr_hash = NULL;
     179                 :             : static HTAB *shared_cast_hash = NULL;
     180                 :             : 
     181                 :             : /*
     182                 :             :  * LOOP_RC_PROCESSING encapsulates common logic for looping statements to
     183                 :             :  * handle return/exit/continue result codes from the loop body statement(s).
     184                 :             :  * It's meant to be used like this:
     185                 :             :  *
     186                 :             :  *      int rc = PLPGSQL_RC_OK;
     187                 :             :  *      for (...)
     188                 :             :  *      {
     189                 :             :  *          ...
     190                 :             :  *          rc = exec_stmts(estate, stmt->body);
     191                 :             :  *          LOOP_RC_PROCESSING(stmt->label, break);
     192                 :             :  *          ...
     193                 :             :  *      }
     194                 :             :  *      return rc;
     195                 :             :  *
     196                 :             :  * If execution of the loop should terminate, LOOP_RC_PROCESSING will execute
     197                 :             :  * "exit_action" (typically a "break" or "goto"), after updating "rc" to the
     198                 :             :  * value the current statement should return.  If execution should continue,
     199                 :             :  * LOOP_RC_PROCESSING will do nothing except reset "rc" to PLPGSQL_RC_OK.
     200                 :             :  *
     201                 :             :  * estate and rc are implicit arguments to the macro.
     202                 :             :  * estate->exitlabel is examined and possibly updated.
     203                 :             :  */
     204                 :             : #define LOOP_RC_PROCESSING(looplabel, exit_action) \
     205                 :             :     if (rc == PLPGSQL_RC_RETURN) \
     206                 :             :     { \
     207                 :             :         /* RETURN, so propagate RC_RETURN out */ \
     208                 :             :         exit_action; \
     209                 :             :     } \
     210                 :             :     else if (rc == PLPGSQL_RC_EXIT) \
     211                 :             :     { \
     212                 :             :         if (estate->exitlabel == NULL) \
     213                 :             :         { \
     214                 :             :             /* unlabeled EXIT terminates this loop */ \
     215                 :             :             rc = PLPGSQL_RC_OK; \
     216                 :             :             exit_action; \
     217                 :             :         } \
     218                 :             :         else if ((looplabel) != NULL && \
     219                 :             :                  strcmp(looplabel, estate->exitlabel) == 0) \
     220                 :             :         { \
     221                 :             :             /* labeled EXIT matching this loop, so terminate loop */ \
     222                 :             :             estate->exitlabel = NULL; \
     223                 :             :             rc = PLPGSQL_RC_OK; \
     224                 :             :             exit_action; \
     225                 :             :         } \
     226                 :             :         else \
     227                 :             :         { \
     228                 :             :             /* non-matching labeled EXIT, propagate RC_EXIT out */ \
     229                 :             :             exit_action; \
     230                 :             :         } \
     231                 :             :     } \
     232                 :             :     else if (rc == PLPGSQL_RC_CONTINUE) \
     233                 :             :     { \
     234                 :             :         if (estate->exitlabel == NULL) \
     235                 :             :         { \
     236                 :             :             /* unlabeled CONTINUE matches this loop, so continue in loop */ \
     237                 :             :             rc = PLPGSQL_RC_OK; \
     238                 :             :         } \
     239                 :             :         else if ((looplabel) != NULL && \
     240                 :             :                  strcmp(looplabel, estate->exitlabel) == 0) \
     241                 :             :         { \
     242                 :             :             /* labeled CONTINUE matching this loop, so continue in loop */ \
     243                 :             :             estate->exitlabel = NULL; \
     244                 :             :             rc = PLPGSQL_RC_OK; \
     245                 :             :         } \
     246                 :             :         else \
     247                 :             :         { \
     248                 :             :             /* non-matching labeled CONTINUE, propagate RC_CONTINUE out */ \
     249                 :             :             exit_action; \
     250                 :             :         } \
     251                 :             :     } \
     252                 :             :     else \
     253                 :             :         Assert(rc == PLPGSQL_RC_OK)
     254                 :             : 
     255                 :             : /* State struct for count_param_references */
     256                 :             : typedef struct count_param_references_context
     257                 :             : {
     258                 :             :     int         paramid;
     259                 :             :     int         count;
     260                 :             :     Param      *last_param;
     261                 :             : } count_param_references_context;
     262                 :             : 
     263                 :             : 
     264                 :             : /************************************************************
     265                 :             :  * Local function forward declarations
     266                 :             :  ************************************************************/
     267                 :             : static void coerce_function_result_tuple(PLpgSQL_execstate *estate,
     268                 :             :                                          TupleDesc tupdesc);
     269                 :             : static void plpgsql_exec_error_callback(void *arg);
     270                 :             : static void plpgsql_execsql_error_callback(void *arg);
     271                 :             : static void copy_plpgsql_datums(PLpgSQL_execstate *estate,
     272                 :             :                                 PLpgSQL_function *func);
     273                 :             : static void plpgsql_fulfill_promise(PLpgSQL_execstate *estate,
     274                 :             :                                     PLpgSQL_var *var);
     275                 :             : static MemoryContext get_stmt_mcontext(PLpgSQL_execstate *estate);
     276                 :             : static void push_stmt_mcontext(PLpgSQL_execstate *estate);
     277                 :             : static void pop_stmt_mcontext(PLpgSQL_execstate *estate);
     278                 :             : 
     279                 :             : static int  exec_toplevel_block(PLpgSQL_execstate *estate,
     280                 :             :                                 PLpgSQL_stmt_block *block);
     281                 :             : static int  exec_stmt_block(PLpgSQL_execstate *estate,
     282                 :             :                             PLpgSQL_stmt_block *block);
     283                 :             : static int  exec_stmts(PLpgSQL_execstate *estate,
     284                 :             :                        List *stmts);
     285                 :             : static int  exec_stmt_assign(PLpgSQL_execstate *estate,
     286                 :             :                              PLpgSQL_stmt_assign *stmt);
     287                 :             : static int  exec_stmt_perform(PLpgSQL_execstate *estate,
     288                 :             :                               PLpgSQL_stmt_perform *stmt);
     289                 :             : static int  exec_stmt_call(PLpgSQL_execstate *estate,
     290                 :             :                            PLpgSQL_stmt_call *stmt);
     291                 :             : static int  exec_stmt_getdiag(PLpgSQL_execstate *estate,
     292                 :             :                               PLpgSQL_stmt_getdiag *stmt);
     293                 :             : static int  exec_stmt_if(PLpgSQL_execstate *estate,
     294                 :             :                          PLpgSQL_stmt_if *stmt);
     295                 :             : static int  exec_stmt_case(PLpgSQL_execstate *estate,
     296                 :             :                            PLpgSQL_stmt_case *stmt);
     297                 :             : static int  exec_stmt_loop(PLpgSQL_execstate *estate,
     298                 :             :                            PLpgSQL_stmt_loop *stmt);
     299                 :             : static int  exec_stmt_while(PLpgSQL_execstate *estate,
     300                 :             :                             PLpgSQL_stmt_while *stmt);
     301                 :             : static int  exec_stmt_fori(PLpgSQL_execstate *estate,
     302                 :             :                            PLpgSQL_stmt_fori *stmt);
     303                 :             : static int  exec_stmt_fors(PLpgSQL_execstate *estate,
     304                 :             :                            PLpgSQL_stmt_fors *stmt);
     305                 :             : static int  exec_stmt_forc(PLpgSQL_execstate *estate,
     306                 :             :                            PLpgSQL_stmt_forc *stmt);
     307                 :             : static int  exec_stmt_foreach_a(PLpgSQL_execstate *estate,
     308                 :             :                                 PLpgSQL_stmt_foreach_a *stmt);
     309                 :             : static int  exec_stmt_open(PLpgSQL_execstate *estate,
     310                 :             :                            PLpgSQL_stmt_open *stmt);
     311                 :             : static int  exec_stmt_fetch(PLpgSQL_execstate *estate,
     312                 :             :                             PLpgSQL_stmt_fetch *stmt);
     313                 :             : static int  exec_stmt_close(PLpgSQL_execstate *estate,
     314                 :             :                             PLpgSQL_stmt_close *stmt);
     315                 :             : static int  exec_stmt_exit(PLpgSQL_execstate *estate,
     316                 :             :                            PLpgSQL_stmt_exit *stmt);
     317                 :             : static int  exec_stmt_return(PLpgSQL_execstate *estate,
     318                 :             :                              PLpgSQL_stmt_return *stmt);
     319                 :             : static int  exec_stmt_return_next(PLpgSQL_execstate *estate,
     320                 :             :                                   PLpgSQL_stmt_return_next *stmt);
     321                 :             : static int  exec_stmt_return_query(PLpgSQL_execstate *estate,
     322                 :             :                                    PLpgSQL_stmt_return_query *stmt);
     323                 :             : static int  exec_stmt_raise(PLpgSQL_execstate *estate,
     324                 :             :                             PLpgSQL_stmt_raise *stmt);
     325                 :             : static int  exec_stmt_assert(PLpgSQL_execstate *estate,
     326                 :             :                              PLpgSQL_stmt_assert *stmt);
     327                 :             : static int  exec_stmt_execsql(PLpgSQL_execstate *estate,
     328                 :             :                               PLpgSQL_stmt_execsql *stmt);
     329                 :             : static int  exec_stmt_dynexecute(PLpgSQL_execstate *estate,
     330                 :             :                                  PLpgSQL_stmt_dynexecute *stmt);
     331                 :             : static int  exec_stmt_dynfors(PLpgSQL_execstate *estate,
     332                 :             :                               PLpgSQL_stmt_dynfors *stmt);
     333                 :             : static int  exec_stmt_commit(PLpgSQL_execstate *estate,
     334                 :             :                              PLpgSQL_stmt_commit *stmt);
     335                 :             : static int  exec_stmt_rollback(PLpgSQL_execstate *estate,
     336                 :             :                                PLpgSQL_stmt_rollback *stmt);
     337                 :             : 
     338                 :             : static void plpgsql_estate_setup(PLpgSQL_execstate *estate,
     339                 :             :                                  PLpgSQL_function *func,
     340                 :             :                                  ReturnSetInfo *rsi,
     341                 :             :                                  EState *simple_eval_estate,
     342                 :             :                                  ResourceOwner simple_eval_resowner);
     343                 :             : static void exec_eval_cleanup(PLpgSQL_execstate *estate);
     344                 :             : 
     345                 :             : static void exec_prepare_plan(PLpgSQL_execstate *estate,
     346                 :             :                               PLpgSQL_expr *expr, int cursorOptions);
     347                 :             : static void exec_simple_check_plan(PLpgSQL_execstate *estate, PLpgSQL_expr *expr);
     348                 :             : static bool exec_is_simple_query(PLpgSQL_expr *expr);
     349                 :             : static void exec_save_simple_expr(PLpgSQL_expr *expr, CachedPlan *cplan);
     350                 :             : static void exec_check_rw_parameter(PLpgSQL_expr *expr, int paramid);
     351                 :             : static bool count_param_references(Node *node,
     352                 :             :                                    count_param_references_context *context);
     353                 :             : static void exec_check_assignable(PLpgSQL_execstate *estate, int dno);
     354                 :             : static bool exec_eval_simple_expr(PLpgSQL_execstate *estate,
     355                 :             :                                   PLpgSQL_expr *expr,
     356                 :             :                                   Datum *result,
     357                 :             :                                   bool *isNull,
     358                 :             :                                   Oid *rettype,
     359                 :             :                                   int32 *rettypmod);
     360                 :             : 
     361                 :             : static void exec_assign_expr(PLpgSQL_execstate *estate,
     362                 :             :                              PLpgSQL_datum *target,
     363                 :             :                              PLpgSQL_expr *expr);
     364                 :             : static void exec_assign_c_string(PLpgSQL_execstate *estate,
     365                 :             :                                  PLpgSQL_datum *target,
     366                 :             :                                  const char *str);
     367                 :             : static void exec_assign_value(PLpgSQL_execstate *estate,
     368                 :             :                               PLpgSQL_datum *target,
     369                 :             :                               Datum value, bool isNull,
     370                 :             :                               Oid valtype, int32 valtypmod);
     371                 :             : static void exec_eval_datum(PLpgSQL_execstate *estate,
     372                 :             :                             PLpgSQL_datum *datum,
     373                 :             :                             Oid *typeid,
     374                 :             :                             int32 *typetypmod,
     375                 :             :                             Datum *value,
     376                 :             :                             bool *isnull);
     377                 :             : static int  exec_eval_integer(PLpgSQL_execstate *estate,
     378                 :             :                               PLpgSQL_expr *expr,
     379                 :             :                               bool *isNull);
     380                 :             : static bool exec_eval_boolean(PLpgSQL_execstate *estate,
     381                 :             :                               PLpgSQL_expr *expr,
     382                 :             :                               bool *isNull);
     383                 :             : static Datum exec_eval_expr(PLpgSQL_execstate *estate,
     384                 :             :                             PLpgSQL_expr *expr,
     385                 :             :                             bool *isNull,
     386                 :             :                             Oid *rettype,
     387                 :             :                             int32 *rettypmod);
     388                 :             : static int  exec_run_select(PLpgSQL_execstate *estate,
     389                 :             :                             PLpgSQL_expr *expr, long maxtuples, Portal *portalP);
     390                 :             : static int  exec_for_query(PLpgSQL_execstate *estate, PLpgSQL_stmt_forq *stmt,
     391                 :             :                            Portal portal, bool prefetch_ok);
     392                 :             : static ParamListInfo setup_param_list(PLpgSQL_execstate *estate,
     393                 :             :                                       PLpgSQL_expr *expr);
     394                 :             : static ParamExternData *plpgsql_param_fetch(ParamListInfo params,
     395                 :             :                                             int paramid, bool speculative,
     396                 :             :                                             ParamExternData *prm);
     397                 :             : static void plpgsql_param_compile(ParamListInfo params, Param *param,
     398                 :             :                                   ExprState *state,
     399                 :             :                                   Datum *resv, bool *resnull);
     400                 :             : static void plpgsql_param_eval_var_check(ExprState *state, ExprEvalStep *op,
     401                 :             :                                          ExprContext *econtext);
     402                 :             : static void plpgsql_param_eval_var_transfer(ExprState *state, ExprEvalStep *op,
     403                 :             :                                             ExprContext *econtext);
     404                 :             : static void plpgsql_param_eval_var(ExprState *state, ExprEvalStep *op,
     405                 :             :                                    ExprContext *econtext);
     406                 :             : static void plpgsql_param_eval_var_ro(ExprState *state, ExprEvalStep *op,
     407                 :             :                                       ExprContext *econtext);
     408                 :             : static void plpgsql_param_eval_recfield(ExprState *state, ExprEvalStep *op,
     409                 :             :                                         ExprContext *econtext);
     410                 :             : static void plpgsql_param_eval_generic(ExprState *state, ExprEvalStep *op,
     411                 :             :                                        ExprContext *econtext);
     412                 :             : static void plpgsql_param_eval_generic_ro(ExprState *state, ExprEvalStep *op,
     413                 :             :                                           ExprContext *econtext);
     414                 :             : static void exec_move_row(PLpgSQL_execstate *estate,
     415                 :             :                           PLpgSQL_variable *target,
     416                 :             :                           HeapTuple tup, TupleDesc tupdesc);
     417                 :             : static void revalidate_rectypeid(PLpgSQL_rec *rec);
     418                 :             : static ExpandedRecordHeader *make_expanded_record_for_rec(PLpgSQL_execstate *estate,
     419                 :             :                                                           PLpgSQL_rec *rec,
     420                 :             :                                                           TupleDesc srctupdesc,
     421                 :             :                                                           ExpandedRecordHeader *srcerh);
     422                 :             : static void exec_move_row_from_fields(PLpgSQL_execstate *estate,
     423                 :             :                                       PLpgSQL_variable *target,
     424                 :             :                                       ExpandedRecordHeader *newerh,
     425                 :             :                                       Datum *values, bool *nulls,
     426                 :             :                                       TupleDesc tupdesc);
     427                 :             : static bool compatible_tupdescs(TupleDesc src_tupdesc, TupleDesc dst_tupdesc);
     428                 :             : static HeapTuple make_tuple_from_row(PLpgSQL_execstate *estate,
     429                 :             :                                      PLpgSQL_row *row,
     430                 :             :                                      TupleDesc tupdesc);
     431                 :             : static void check_record_tupdescs_match(ExpandedRecordHeader *srcerh,
     432                 :             :                                         ExpandedRecordHeader *dsterh);
     433                 :             : static TupleDesc deconstruct_composite_datum(Datum value,
     434                 :             :                                              HeapTupleData *tmptup);
     435                 :             : static void exec_move_row_from_datum(PLpgSQL_execstate *estate,
     436                 :             :                                      PLpgSQL_variable *target,
     437                 :             :                                      Datum value);
     438                 :             : static void instantiate_empty_record_variable(PLpgSQL_execstate *estate,
     439                 :             :                                               PLpgSQL_rec *rec);
     440                 :             : static char *convert_value_to_string(PLpgSQL_execstate *estate,
     441                 :             :                                      Datum value, Oid valtype);
     442                 :             : static inline Datum exec_cast_value(PLpgSQL_execstate *estate,
     443                 :             :                                     Datum value, bool *isnull,
     444                 :             :                                     Oid valtype, int32 valtypmod,
     445                 :             :                                     Oid reqtype, int32 reqtypmod);
     446                 :             : static Datum do_cast_value(PLpgSQL_execstate *estate,
     447                 :             :                            Datum value, bool *isnull,
     448                 :             :                            Oid valtype, int32 valtypmod,
     449                 :             :                            Oid reqtype, int32 reqtypmod);
     450                 :             : static plpgsql_CastHashEntry *get_cast_hashentry(PLpgSQL_execstate *estate,
     451                 :             :                                                  Oid srctype, int32 srctypmod,
     452                 :             :                                                  Oid dsttype, int32 dsttypmod);
     453                 :             : static void exec_init_tuple_store(PLpgSQL_execstate *estate);
     454                 :             : static void exec_set_found(PLpgSQL_execstate *estate, bool state);
     455                 :             : static void plpgsql_create_econtext(PLpgSQL_execstate *estate);
     456                 :             : static void plpgsql_destroy_econtext(PLpgSQL_execstate *estate);
     457                 :             : static void assign_simple_var(PLpgSQL_execstate *estate, PLpgSQL_var *var,
     458                 :             :                               Datum newvalue, bool isnull, bool freeable);
     459                 :             : static void assign_text_var(PLpgSQL_execstate *estate, PLpgSQL_var *var,
     460                 :             :                             const char *str);
     461                 :             : static void assign_record_var(PLpgSQL_execstate *estate, PLpgSQL_rec *rec,
     462                 :             :                               ExpandedRecordHeader *erh);
     463                 :             : static ParamListInfo exec_eval_using_params(PLpgSQL_execstate *estate,
     464                 :             :                                             List *params);
     465                 :             : static Portal exec_dynquery_with_params(PLpgSQL_execstate *estate,
     466                 :             :                                         PLpgSQL_expr *dynquery, List *params,
     467                 :             :                                         const char *portalname, int cursorOptions);
     468                 :             : static char *format_expr_params(PLpgSQL_execstate *estate,
     469                 :             :                                 const PLpgSQL_expr *expr);
     470                 :             : static char *format_preparedparamsdata(PLpgSQL_execstate *estate,
     471                 :             :                                        ParamListInfo paramLI);
     472                 :             : static PLpgSQL_variable *make_callstmt_target(PLpgSQL_execstate *estate,
     473                 :             :                                               PLpgSQL_expr *expr);
     474                 :             : 
     475                 :             : 
     476                 :             : /* ----------
     477                 :             :  * plpgsql_exec_function    Called by the call handler for
     478                 :             :  *              function execution.
     479                 :             :  *
     480                 :             :  * This is also used to execute inline code blocks (DO blocks).  The only
     481                 :             :  * difference that this code is aware of is that for a DO block, we want
     482                 :             :  * to use a private simple_eval_estate and a private simple_eval_resowner,
     483                 :             :  * which are created and passed in by the caller.  For regular functions,
     484                 :             :  * pass NULL, which implies using shared_simple_eval_estate and
     485                 :             :  * shared_simple_eval_resowner.  (When using a private simple_eval_estate,
     486                 :             :  * we must also use a private cast hashtable, but that's taken care of
     487                 :             :  * within plpgsql_estate_setup.)
     488                 :             :  * procedure_resowner is a resowner that will survive for the duration
     489                 :             :  * of execution of this function/procedure.  It is needed only if we
     490                 :             :  * are doing non-atomic execution and there are CALL or DO statements
     491                 :             :  * in the function; otherwise it can be NULL.  We use it to hold refcounts
     492                 :             :  * on the CALL/DO statements' plans.
     493                 :             :  * ----------
     494                 :             :  */
     495                 :             : Datum
     496                 :       53976 : plpgsql_exec_function(PLpgSQL_function *func, FunctionCallInfo fcinfo,
     497                 :             :                       EState *simple_eval_estate,
     498                 :             :                       ResourceOwner simple_eval_resowner,
     499                 :             :                       ResourceOwner procedure_resowner,
     500                 :             :                       bool atomic)
     501                 :             : {
     502                 :             :     PLpgSQL_execstate estate;
     503                 :             :     ErrorContextCallback plerrcontext;
     504                 :             :     int         i;
     505                 :             :     int         rc;
     506                 :             : 
     507                 :             :     /*
     508                 :             :      * Setup the execution state
     509                 :             :      */
     510                 :       53976 :     plpgsql_estate_setup(&estate, func, (ReturnSetInfo *) fcinfo->resultinfo,
     511                 :             :                          simple_eval_estate, simple_eval_resowner);
     512                 :       53976 :     estate.procedure_resowner = procedure_resowner;
     513                 :       53976 :     estate.atomic = atomic;
     514                 :             : 
     515                 :             :     /*
     516                 :             :      * Setup error traceback support for ereport()
     517                 :             :      */
     518                 :       53976 :     plerrcontext.callback = plpgsql_exec_error_callback;
     519                 :       53976 :     plerrcontext.arg = &estate;
     520                 :       53976 :     plerrcontext.previous = error_context_stack;
     521                 :       53976 :     error_context_stack = &plerrcontext;
     522                 :             : 
     523                 :             :     /*
     524                 :             :      * Make local execution copies of all the datums
     525                 :             :      */
     526                 :       53976 :     estate.err_text = gettext_noop("during initialization of execution state");
     527                 :       53976 :     copy_plpgsql_datums(&estate, func);
     528                 :             : 
     529                 :             :     /*
     530                 :             :      * Store the actual call argument values into the appropriate variables
     531                 :             :      */
     532                 :       53976 :     estate.err_text = gettext_noop("while storing call arguments into local variables");
     533         [ +  + ]:      120354 :     for (i = 0; i < func->fn_nargs; i++)
     534                 :             :     {
     535                 :       66382 :         int         n = func->fn_argvarnos[i];
     536                 :             : 
     537      [ +  +  - ]:       66382 :         switch (estate.datums[n]->dtype)
     538                 :             :         {
     539                 :       65685 :             case PLPGSQL_DTYPE_VAR:
     540                 :             :                 {
     541                 :       65685 :                     PLpgSQL_var *var = (PLpgSQL_var *) estate.datums[n];
     542                 :             : 
     543                 :       65685 :                     assign_simple_var(&estate, var,
     544                 :             :                                       fcinfo->args[i].value,
     545                 :       65685 :                                       fcinfo->args[i].isnull,
     546                 :             :                                       false);
     547                 :             : 
     548                 :             :                     /*
     549                 :             :                      * If it's a varlena type, check to see if we received a
     550                 :             :                      * R/W expanded-object pointer.  If so, we can commandeer
     551                 :             :                      * the object rather than having to copy it.  If passed a
     552                 :             :                      * R/O expanded pointer, just keep it as the value of the
     553                 :             :                      * variable for the moment.  (We can change it to R/W if
     554                 :             :                      * the variable gets modified, but that may very well
     555                 :             :                      * never happen.)
     556                 :             :                      *
     557                 :             :                      * Also, force any flat array value to be stored in
     558                 :             :                      * expanded form in our local variable, in hopes of
     559                 :             :                      * improving efficiency of uses of the variable.  (This is
     560                 :             :                      * a hack, really: why only arrays? Need more thought
     561                 :             :                      * about which cases are likely to win.  See also
     562                 :             :                      * typisarray-specific heuristic in exec_assign_value.)
     563                 :             :                      */
     564   [ +  +  +  + ]:       65685 :                     if (!var->isnull && var->datatype->typlen == -1)
     565                 :             :                     {
     566         [ +  + ]:       20834 :                         if (VARATT_IS_EXTERNAL_EXPANDED_RW(DatumGetPointer(var->value)))
     567                 :             :                         {
     568                 :             :                             /* take ownership of R/W object */
     569                 :           4 :                             assign_simple_var(&estate, var,
     570                 :             :                                               TransferExpandedObject(var->value,
     571                 :             :                                                                      estate.datum_context),
     572                 :             :                                               false,
     573                 :             :                                               true);
     574                 :             :                         }
     575         [ +  + ]:       20830 :                         else if (VARATT_IS_EXTERNAL_EXPANDED_RO(DatumGetPointer(var->value)))
     576                 :             :                         {
     577                 :             :                             /* R/O pointer, keep it as-is until assigned to */
     578                 :             :                         }
     579         [ +  + ]:       20786 :                         else if (var->datatype->typisarray)
     580                 :             :                         {
     581                 :             :                             /* flat array, so force to expanded form */
     582                 :        1881 :                             assign_simple_var(&estate, var,
     583                 :             :                                               expand_array(var->value,
     584                 :             :                                                            estate.datum_context,
     585                 :             :                                                            NULL),
     586                 :             :                                               false,
     587                 :             :                                               true);
     588                 :             :                         }
     589                 :             :                     }
     590                 :             :                 }
     591                 :       65685 :                 break;
     592                 :             : 
     593                 :         697 :             case PLPGSQL_DTYPE_REC:
     594                 :             :                 {
     595                 :         697 :                     PLpgSQL_rec *rec = (PLpgSQL_rec *) estate.datums[n];
     596                 :             : 
     597         [ +  + ]:         697 :                     if (!fcinfo->args[i].isnull)
     598                 :             :                     {
     599                 :             :                         /* Assign row value from composite datum */
     600                 :         657 :                         exec_move_row_from_datum(&estate,
     601                 :             :                                                  (PLpgSQL_variable *) rec,
     602                 :             :                                                  fcinfo->args[i].value);
     603                 :             :                     }
     604                 :             :                     else
     605                 :             :                     {
     606                 :             :                         /* If arg is null, set variable to null */
     607                 :          40 :                         exec_move_row(&estate, (PLpgSQL_variable *) rec,
     608                 :             :                                       NULL, NULL);
     609                 :             :                     }
     610                 :             :                     /* clean up after exec_move_row() */
     611                 :         693 :                     exec_eval_cleanup(&estate);
     612                 :             :                 }
     613                 :         693 :                 break;
     614                 :             : 
     615                 :           0 :             default:
     616                 :             :                 /* Anything else should not be an argument variable */
     617         [ #  # ]:           0 :                 elog(ERROR, "unrecognized dtype: %d", func->datums[i]->dtype);
     618                 :             :         }
     619                 :             :     }
     620                 :             : 
     621                 :       53972 :     estate.err_text = gettext_noop("during function entry");
     622                 :             : 
     623                 :             :     /*
     624                 :             :      * Set the magic variable FOUND to false
     625                 :             :      */
     626                 :       53972 :     exec_set_found(&estate, false);
     627                 :             : 
     628                 :             :     /*
     629                 :             :      * Let the instrumentation plugin peek at this function
     630                 :             :      */
     631   [ -  +  -  - ]:       53972 :     if (*plpgsql_plugin_ptr && (*plpgsql_plugin_ptr)->func_beg)
     632                 :           0 :         ((*plpgsql_plugin_ptr)->func_beg) (&estate, func);
     633                 :             : 
     634                 :             :     /*
     635                 :             :      * Now call the toplevel block of statements
     636                 :             :      */
     637                 :       53972 :     estate.err_text = NULL;
     638                 :       53972 :     rc = exec_toplevel_block(&estate, func->action);
     639         [ +  + ]:       53130 :     if (rc != PLPGSQL_RC_RETURN)
     640                 :             :     {
     641                 :           4 :         estate.err_text = NULL;
     642         [ +  - ]:           4 :         ereport(ERROR,
     643                 :             :                 (errcode(ERRCODE_S_R_E_FUNCTION_EXECUTED_NO_RETURN_STATEMENT),
     644                 :             :                  errmsg("control reached end of function without RETURN")));
     645                 :             :     }
     646                 :             : 
     647                 :             :     /*
     648                 :             :      * We got a return value - process it
     649                 :             :      */
     650                 :       53126 :     estate.err_text = gettext_noop("while casting return value to function's return type");
     651                 :             : 
     652                 :       53126 :     fcinfo->isnull = estate.retisnull;
     653                 :             : 
     654         [ +  + ]:       53126 :     if (estate.retisset)
     655                 :             :     {
     656                 :        2526 :         ReturnSetInfo *rsi = estate.rsi;
     657                 :             : 
     658                 :             :         /* Check caller can handle a set result */
     659   [ +  -  -  + ]:        2526 :         if (!rsi || !IsA(rsi, ReturnSetInfo))
     660         [ #  # ]:           0 :             ereport(ERROR,
     661                 :             :                     (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
     662                 :             :                      errmsg("set-valued function called in context that cannot accept a set")));
     663                 :             : 
     664         [ -  + ]:        2526 :         if (!(rsi->allowedModes & SFRM_Materialize))
     665         [ #  # ]:           0 :             ereport(ERROR,
     666                 :             :                     (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
     667                 :             :                      errmsg("materialize mode required, but it is not allowed in this context")));
     668                 :             : 
     669                 :        2526 :         rsi->returnMode = SFRM_Materialize;
     670                 :             : 
     671                 :             :         /* If we produced any tuples, send back the result */
     672         [ +  + ]:        2526 :         if (estate.tuple_store)
     673                 :             :         {
     674                 :             :             MemoryContext oldcxt;
     675                 :             : 
     676                 :        2514 :             rsi->setResult = estate.tuple_store;
     677                 :        2514 :             oldcxt = MemoryContextSwitchTo(estate.tuple_store_cxt);
     678                 :        2514 :             rsi->setDesc = CreateTupleDescCopy(estate.tuple_store_desc);
     679                 :        2514 :             MemoryContextSwitchTo(oldcxt);
     680                 :             :         }
     681                 :        2526 :         estate.retval = (Datum) 0;
     682                 :        2526 :         fcinfo->isnull = true;
     683                 :             :     }
     684         [ +  + ]:       50600 :     else if (!estate.retisnull)
     685                 :             :     {
     686                 :             :         /*
     687                 :             :          * Cast result value to function's declared result type, and copy it
     688                 :             :          * out to the upper executor memory context.  We must treat tuple
     689                 :             :          * results specially in order to deal with cases like rowtypes
     690                 :             :          * involving dropped columns.
     691                 :             :          */
     692         [ +  + ]:       49861 :         if (estate.retistuple)
     693                 :             :         {
     694                 :             :             /* Don't need coercion if rowtype is known to match */
     695         [ +  + ]:       11511 :             if (func->fn_rettype == estate.rettype &&
     696         [ +  + ]:        3456 :                 func->fn_rettype != RECORDOID)
     697                 :             :             {
     698                 :             :                 /*
     699                 :             :                  * Copy the tuple result into upper executor memory context.
     700                 :             :                  * However, if we have a R/W expanded datum, we can just
     701                 :             :                  * transfer its ownership out to the upper context.
     702                 :             :                  */
     703                 :         154 :                 estate.retval = SPI_datumTransfer(estate.retval,
     704                 :             :                                                   false,
     705                 :             :                                                   -1);
     706                 :             :             }
     707                 :             :             else
     708                 :             :             {
     709                 :             :                 /*
     710                 :             :                  * Need to look up the expected result type.  XXX would be
     711                 :             :                  * better to cache the tupdesc instead of repeating
     712                 :             :                  * get_call_result_type(), but the only easy place to save it
     713                 :             :                  * is in the PLpgSQL_function struct, and that's too
     714                 :             :                  * long-lived: composite types could change during the
     715                 :             :                  * existence of a PLpgSQL_function.
     716                 :             :                  */
     717                 :             :                 Oid         resultTypeId;
     718                 :             :                 TupleDesc   tupdesc;
     719                 :             : 
     720   [ +  +  +  - ]:       11357 :                 switch (get_call_result_type(fcinfo, &resultTypeId, &tupdesc))
     721                 :             :                 {
     722                 :       11313 :                     case TYPEFUNC_COMPOSITE:
     723                 :             :                         /* got the expected result rowtype, now coerce it */
     724                 :       11313 :                         coerce_function_result_tuple(&estate, tupdesc);
     725                 :       11289 :                         break;
     726                 :           8 :                     case TYPEFUNC_COMPOSITE_DOMAIN:
     727                 :             :                         /* got the expected result rowtype, now coerce it */
     728                 :           8 :                         coerce_function_result_tuple(&estate, tupdesc);
     729                 :             :                         /* and check domain constraints */
     730                 :             :                         /* XXX allowing caching here would be good, too */
     731                 :           8 :                         domain_check(estate.retval, false, resultTypeId,
     732                 :             :                                      NULL, NULL);
     733                 :           4 :                         break;
     734                 :          36 :                     case TYPEFUNC_RECORD:
     735                 :             : 
     736                 :             :                         /*
     737                 :             :                          * Failed to determine actual type of RECORD.  We
     738                 :             :                          * could raise an error here, but what this means in
     739                 :             :                          * practice is that the caller is expecting any old
     740                 :             :                          * generic rowtype, so we don't really need to be
     741                 :             :                          * restrictive.  Pass back the generated result as-is.
     742                 :             :                          */
     743                 :          36 :                         estate.retval = SPI_datumTransfer(estate.retval,
     744                 :             :                                                           false,
     745                 :             :                                                           -1);
     746                 :          36 :                         break;
     747                 :           0 :                     default:
     748                 :             :                         /* shouldn't get here if retistuple is true ... */
     749         [ #  # ]:           0 :                         elog(ERROR, "return type must be a row type");
     750                 :             :                         break;
     751                 :             :                 }
     752                 :             :             }
     753                 :             :         }
     754                 :             :         else
     755                 :             :         {
     756                 :             :             /* Scalar case: use exec_cast_value */
     757                 :       38350 :             estate.retval = exec_cast_value(&estate,
     758                 :             :                                             estate.retval,
     759                 :             :                                             &fcinfo->isnull,
     760                 :             :                                             estate.rettype,
     761                 :             :                                             -1,
     762                 :             :                                             func->fn_rettype,
     763                 :             :                                             -1);
     764                 :             : 
     765                 :             :             /*
     766                 :             :              * If the function's return type isn't by value, copy the value
     767                 :             :              * into upper executor memory context.  However, if we have a R/W
     768                 :             :              * expanded datum, we can just transfer its ownership out to the
     769                 :             :              * upper executor context.
     770                 :             :              */
     771   [ +  -  +  + ]:       38328 :             if (!fcinfo->isnull && !func->fn_retbyval)
     772                 :        3536 :                 estate.retval = SPI_datumTransfer(estate.retval,
     773                 :             :                                                   false,
     774                 :             :                                                   func->fn_rettyplen);
     775                 :             :         }
     776                 :             :     }
     777                 :             :     else
     778                 :             :     {
     779                 :             :         /*
     780                 :             :          * We're returning a NULL, which normally requires no conversion work
     781                 :             :          * regardless of datatypes.  But, if we are casting it to a domain
     782                 :             :          * return type, we'd better check that the domain's constraints pass.
     783                 :             :          */
     784         [ +  + ]:         739 :         if (func->fn_retisdomain)
     785                 :           3 :             estate.retval = exec_cast_value(&estate,
     786                 :             :                                             estate.retval,
     787                 :             :                                             &fcinfo->isnull,
     788                 :             :                                             estate.rettype,
     789                 :             :                                             -1,
     790                 :             :                                             func->fn_rettype,
     791                 :             :                                             -1);
     792                 :             :     }
     793                 :             : 
     794                 :       53075 :     estate.err_text = gettext_noop("during function exit");
     795                 :             : 
     796                 :             :     /*
     797                 :             :      * Let the instrumentation plugin peek at this function
     798                 :             :      */
     799   [ -  +  -  - ]:       53075 :     if (*plpgsql_plugin_ptr && (*plpgsql_plugin_ptr)->func_end)
     800                 :           0 :         ((*plpgsql_plugin_ptr)->func_end) (&estate, func);
     801                 :             : 
     802                 :             :     /* Clean up any leftover temporary memory */
     803                 :       53075 :     plpgsql_destroy_econtext(&estate);
     804                 :       53075 :     exec_eval_cleanup(&estate);
     805                 :             :     /* stmt_mcontext will be destroyed when function's main context is */
     806                 :             : 
     807                 :             :     /*
     808                 :             :      * Pop the error context stack
     809                 :             :      */
     810                 :       53075 :     error_context_stack = plerrcontext.previous;
     811                 :             : 
     812                 :             :     /*
     813                 :             :      * Return the function's result
     814                 :             :      */
     815                 :       53075 :     return estate.retval;
     816                 :             : }
     817                 :             : 
     818                 :             : /*
     819                 :             :  * Helper for plpgsql_exec_function: coerce composite result to the specified
     820                 :             :  * tuple descriptor, and copy it out to upper executor memory.  This is split
     821                 :             :  * out mostly for cosmetic reasons --- the logic would be very deeply nested
     822                 :             :  * otherwise.
     823                 :             :  *
     824                 :             :  * estate->retval is updated in-place.
     825                 :             :  */
     826                 :             : static void
     827                 :       11321 : coerce_function_result_tuple(PLpgSQL_execstate *estate, TupleDesc tupdesc)
     828                 :             : {
     829                 :             :     HeapTuple   rettup;
     830                 :             :     TupleDesc   retdesc;
     831                 :             :     TupleConversionMap *tupmap;
     832                 :             : 
     833                 :             :     /* We assume exec_stmt_return verified that result is composite */
     834                 :             :     Assert(type_is_rowtype(estate->rettype));
     835                 :             : 
     836                 :             :     /* We can special-case expanded records for speed */
     837         [ +  + ]:       11321 :     if (VARATT_IS_EXTERNAL_EXPANDED(DatumGetPointer(estate->retval)))
     838                 :             :     {
     839                 :          30 :         ExpandedRecordHeader *erh = (ExpandedRecordHeader *) DatumGetEOHP(estate->retval);
     840                 :             : 
     841                 :             :         Assert(erh->er_magic == ER_MAGIC);
     842                 :             : 
     843                 :             :         /* Extract record's TupleDesc */
     844                 :          30 :         retdesc = expanded_record_get_tupdesc(erh);
     845                 :             : 
     846                 :             :         /* check rowtype compatibility */
     847                 :          30 :         tupmap = convert_tuples_by_position(retdesc,
     848                 :             :                                             tupdesc,
     849                 :             :                                             gettext_noop("returned record type does not match expected record type"));
     850                 :             : 
     851                 :             :         /* it might need conversion */
     852         [ +  + ]:          24 :         if (tupmap)
     853                 :             :         {
     854                 :           1 :             rettup = expanded_record_get_tuple(erh);
     855                 :             :             Assert(rettup);
     856                 :           1 :             rettup = execute_attr_map_tuple(rettup, tupmap);
     857                 :             : 
     858                 :             :             /*
     859                 :             :              * Copy tuple to upper executor memory, as a tuple Datum.  Make
     860                 :             :              * sure it is labeled with the caller-supplied tuple type.
     861                 :             :              */
     862                 :           1 :             estate->retval = PointerGetDatum(SPI_returntuple(rettup, tupdesc));
     863                 :             :             /* no need to free map, we're about to return anyway */
     864                 :             :         }
     865         [ +  + ]:          23 :         else if (!(tupdesc->tdtypeid == erh->er_decltypeid ||
     866         [ -  + ]:          12 :                    (tupdesc->tdtypeid == RECORDOID &&
     867         [ #  # ]:           0 :                     !ExpandedRecordIsDomain(erh))))
     868                 :           8 :         {
     869                 :             :             /*
     870                 :             :              * The expanded record has the right physical tupdesc, but the
     871                 :             :              * wrong type ID.  (Typically, the expanded record is RECORDOID
     872                 :             :              * but the function is declared to return a named composite type.
     873                 :             :              * As in exec_move_row_from_datum, we don't allow returning a
     874                 :             :              * composite-domain record from a function declared to return
     875                 :             :              * RECORD.)  So we must flatten the record to a tuple datum and
     876                 :             :              * overwrite its type fields with the right thing.  spi.c doesn't
     877                 :             :              * provide any easy way to deal with this case, so we end up
     878                 :             :              * duplicating the guts of datumCopy() :-(
     879                 :             :              */
     880                 :             :             Size        resultsize;
     881                 :             :             HeapTupleHeader tuphdr;
     882                 :             : 
     883                 :          12 :             resultsize = EOH_get_flat_size(&erh->hdr);
     884                 :          12 :             tuphdr = (HeapTupleHeader) SPI_palloc(resultsize);
     885                 :          12 :             EOH_flatten_into(&erh->hdr, tuphdr, resultsize);
     886                 :          12 :             heap_datum_update_type(tuphdr, tupdesc);
     887                 :           8 :             estate->retval = PointerGetDatum(tuphdr);
     888                 :             :         }
     889                 :             :         else
     890                 :             :         {
     891                 :             :             /*
     892                 :             :              * We need only copy result into upper executor memory context.
     893                 :             :              * However, if we have a R/W expanded datum, we can just transfer
     894                 :             :              * its ownership out to the upper executor context.
     895                 :             :              */
     896                 :          11 :             estate->retval = SPI_datumTransfer(estate->retval,
     897                 :             :                                                false,
     898                 :             :                                                -1);
     899                 :             :         }
     900                 :             :     }
     901                 :             :     else
     902                 :             :     {
     903                 :             :         /* Convert composite datum to a HeapTuple and TupleDesc */
     904                 :             :         HeapTupleData tmptup;
     905                 :             : 
     906                 :       11291 :         retdesc = deconstruct_composite_datum(estate->retval, &tmptup);
     907                 :       11287 :         rettup = &tmptup;
     908                 :             : 
     909                 :             :         /* check rowtype compatibility */
     910                 :       11287 :         tupmap = convert_tuples_by_position(retdesc,
     911                 :             :                                             tupdesc,
     912                 :             :                                             gettext_noop("returned record type does not match expected record type"));
     913                 :             : 
     914                 :             :         /* it might need conversion */
     915         [ +  + ]:       11277 :         if (tupmap)
     916                 :           1 :             rettup = execute_attr_map_tuple(rettup, tupmap);
     917                 :             : 
     918                 :             :         /*
     919                 :             :          * Copy tuple to upper executor memory, as a tuple Datum.  Make sure
     920                 :             :          * it is labeled with the caller-supplied tuple type.
     921                 :             :          */
     922                 :       11277 :         estate->retval = PointerGetDatum(SPI_returntuple(rettup, tupdesc));
     923                 :             : 
     924                 :             :         /* no need to free map, we're about to return anyway */
     925                 :             : 
     926         [ +  + ]:       11277 :         ReleaseTupleDesc(retdesc);
     927                 :             :     }
     928                 :       11297 : }
     929                 :             : 
     930                 :             : 
     931                 :             : /* ----------
     932                 :             :  * plpgsql_exec_trigger     Called by the call handler for
     933                 :             :  *              trigger execution.
     934                 :             :  * ----------
     935                 :             :  */
     936                 :             : HeapTuple
     937                 :       10289 : plpgsql_exec_trigger(PLpgSQL_function *func,
     938                 :             :                      TriggerData *trigdata)
     939                 :             : {
     940                 :             :     PLpgSQL_execstate estate;
     941                 :             :     ErrorContextCallback plerrcontext;
     942                 :             :     int         rc;
     943                 :             :     TupleDesc   tupdesc;
     944                 :             :     PLpgSQL_rec *rec_new,
     945                 :             :                *rec_old;
     946                 :             :     HeapTuple   rettup;
     947                 :             : 
     948                 :             :     /*
     949                 :             :      * Setup the execution state
     950                 :             :      */
     951                 :       10289 :     plpgsql_estate_setup(&estate, func, NULL, NULL, NULL);
     952                 :       10289 :     estate.trigdata = trigdata;
     953                 :             : 
     954                 :             :     /*
     955                 :             :      * Setup error traceback support for ereport()
     956                 :             :      */
     957                 :       10289 :     plerrcontext.callback = plpgsql_exec_error_callback;
     958                 :       10289 :     plerrcontext.arg = &estate;
     959                 :       10289 :     plerrcontext.previous = error_context_stack;
     960                 :       10289 :     error_context_stack = &plerrcontext;
     961                 :             : 
     962                 :             :     /*
     963                 :             :      * Make local execution copies of all the datums
     964                 :             :      */
     965                 :       10289 :     estate.err_text = gettext_noop("during initialization of execution state");
     966                 :       10289 :     copy_plpgsql_datums(&estate, func);
     967                 :             : 
     968                 :             :     /*
     969                 :             :      * Put the OLD and NEW tuples into record variables
     970                 :             :      *
     971                 :             :      * We set up expanded records for both variables even though only one may
     972                 :             :      * have a value.  This allows record references to succeed in functions
     973                 :             :      * that are used for multiple trigger types.  For example, we might have a
     974                 :             :      * test like "if (TG_OP = 'INSERT' and NEW.foo = 'xyz')", which should
     975                 :             :      * work regardless of the current trigger type.  If a value is actually
     976                 :             :      * fetched from an unsupplied tuple, it will read as NULL.
     977                 :             :      */
     978                 :       10289 :     tupdesc = RelationGetDescr(trigdata->tg_relation);
     979                 :             : 
     980                 :       10289 :     rec_new = (PLpgSQL_rec *) (estate.datums[func->new_varno]);
     981                 :       10289 :     rec_old = (PLpgSQL_rec *) (estate.datums[func->old_varno]);
     982                 :             : 
     983                 :       10289 :     rec_new->erh = make_expanded_record_from_tupdesc(tupdesc,
     984                 :             :                                                      estate.datum_context);
     985                 :       10289 :     rec_old->erh = make_expanded_record_from_exprecord(rec_new->erh,
     986                 :             :                                                        estate.datum_context);
     987                 :             : 
     988         [ +  + ]:       10289 :     if (!TRIGGER_FIRED_FOR_ROW(trigdata->tg_event))
     989                 :             :     {
     990                 :             :         /*
     991                 :             :          * Per-statement triggers don't use OLD/NEW variables
     992                 :             :          */
     993                 :             :     }
     994         [ +  + ]:        9297 :     else if (TRIGGER_FIRED_BY_INSERT(trigdata->tg_event))
     995                 :             :     {
     996                 :        4708 :         expanded_record_set_tuple(rec_new->erh, trigdata->tg_trigtuple,
     997                 :             :                                   false, false);
     998                 :             :     }
     999         [ +  + ]:        4589 :     else if (TRIGGER_FIRED_BY_UPDATE(trigdata->tg_event))
    1000                 :             :     {
    1001                 :        4077 :         expanded_record_set_tuple(rec_new->erh, trigdata->tg_newtuple,
    1002                 :             :                                   false, false);
    1003                 :        4077 :         expanded_record_set_tuple(rec_old->erh, trigdata->tg_trigtuple,
    1004                 :             :                                   false, false);
    1005                 :             : 
    1006                 :             :         /*
    1007                 :             :          * In BEFORE trigger, stored generated columns are not computed yet,
    1008                 :             :          * so make them null in the NEW row.  (Only needed in UPDATE branch;
    1009                 :             :          * in the INSERT case, they are already null, but in UPDATE, the field
    1010                 :             :          * still contains the old value.)  Alternatively, we could construct a
    1011                 :             :          * whole new row structure without the generated columns, but this way
    1012                 :             :          * seems more efficient and potentially less confusing.
    1013                 :             :          */
    1014   [ +  +  +  + ]:        4077 :         if (tupdesc->constr && tupdesc->constr->has_generated_stored &&
    1015         [ +  + ]:          29 :             TRIGGER_FIRED_BEFORE(trigdata->tg_event))
    1016                 :             :         {
    1017         [ +  + ]:          65 :             for (int i = 0; i < tupdesc->natts; i++)
    1018         [ +  + ]:          44 :                 if (TupleDescAttr(tupdesc, i)->attgenerated == ATTRIBUTE_GENERATED_STORED)
    1019                 :          21 :                     expanded_record_set_field_internal(rec_new->erh,
    1020                 :             :                                                        i + 1,
    1021                 :             :                                                        (Datum) 0,
    1022                 :             :                                                        true,    /* isnull */
    1023                 :             :                                                        false, false);
    1024                 :             :         }
    1025                 :             :     }
    1026         [ +  - ]:         512 :     else if (TRIGGER_FIRED_BY_DELETE(trigdata->tg_event))
    1027                 :             :     {
    1028                 :         512 :         expanded_record_set_tuple(rec_old->erh, trigdata->tg_trigtuple,
    1029                 :             :                                   false, false);
    1030                 :             :     }
    1031                 :             :     else
    1032         [ #  # ]:           0 :         elog(ERROR, "unrecognized trigger action: not INSERT, DELETE, or UPDATE");
    1033                 :             : 
    1034                 :             :     /* Make transition tables visible to this SPI connection */
    1035                 :       10289 :     rc = SPI_register_trigger_data(trigdata);
    1036                 :             :     Assert(rc >= 0);
    1037                 :             : 
    1038                 :       10289 :     estate.err_text = gettext_noop("during function entry");
    1039                 :             : 
    1040                 :             :     /*
    1041                 :             :      * Set the magic variable FOUND to false
    1042                 :             :      */
    1043                 :       10289 :     exec_set_found(&estate, false);
    1044                 :             : 
    1045                 :             :     /*
    1046                 :             :      * Let the instrumentation plugin peek at this function
    1047                 :             :      */
    1048   [ -  +  -  - ]:       10289 :     if (*plpgsql_plugin_ptr && (*plpgsql_plugin_ptr)->func_beg)
    1049                 :           0 :         ((*plpgsql_plugin_ptr)->func_beg) (&estate, func);
    1050                 :             : 
    1051                 :             :     /*
    1052                 :             :      * Now call the toplevel block of statements
    1053                 :             :      */
    1054                 :       10289 :     estate.err_text = NULL;
    1055                 :       10289 :     rc = exec_toplevel_block(&estate, func->action);
    1056         [ -  + ]:       10066 :     if (rc != PLPGSQL_RC_RETURN)
    1057                 :             :     {
    1058                 :           0 :         estate.err_text = NULL;
    1059         [ #  # ]:           0 :         ereport(ERROR,
    1060                 :             :                 (errcode(ERRCODE_S_R_E_FUNCTION_EXECUTED_NO_RETURN_STATEMENT),
    1061                 :             :                  errmsg("control reached end of trigger procedure without RETURN")));
    1062                 :             :     }
    1063                 :             : 
    1064                 :       10066 :     estate.err_text = gettext_noop("during function exit");
    1065                 :             : 
    1066         [ -  + ]:       10066 :     if (estate.retisset)
    1067         [ #  # ]:           0 :         ereport(ERROR,
    1068                 :             :                 (errcode(ERRCODE_DATATYPE_MISMATCH),
    1069                 :             :                  errmsg("trigger procedure cannot return a set")));
    1070                 :             : 
    1071                 :             :     /*
    1072                 :             :      * Check that the returned tuple structure has the same attributes, the
    1073                 :             :      * relation that fired the trigger has. A per-statement trigger always
    1074                 :             :      * needs to return NULL, so we ignore any return value the function itself
    1075                 :             :      * produces (XXX: is this a good idea?)
    1076                 :             :      *
    1077                 :             :      * XXX This way it is possible, that the trigger returns a tuple where
    1078                 :             :      * attributes don't have the correct atttypmod's length. It's up to the
    1079                 :             :      * trigger's programmer to ensure that this doesn't happen. Jan
    1080                 :             :      */
    1081   [ +  +  +  + ]:       10066 :     if (estate.retisnull || !TRIGGER_FIRED_FOR_ROW(trigdata->tg_event))
    1082                 :        1794 :         rettup = NULL;
    1083                 :             :     else
    1084                 :             :     {
    1085                 :             :         TupleDesc   retdesc;
    1086                 :             :         TupleConversionMap *tupmap;
    1087                 :             : 
    1088                 :             :         /* We assume exec_stmt_return verified that result is composite */
    1089                 :             :         Assert(type_is_rowtype(estate.rettype));
    1090                 :             : 
    1091                 :             :         /* We can special-case expanded records for speed */
    1092         [ +  + ]:        8272 :         if (VARATT_IS_EXTERNAL_EXPANDED(DatumGetPointer(estate.retval)))
    1093                 :             :         {
    1094                 :        8230 :             ExpandedRecordHeader *erh = (ExpandedRecordHeader *) DatumGetEOHP(estate.retval);
    1095                 :             : 
    1096                 :             :             Assert(erh->er_magic == ER_MAGIC);
    1097                 :             : 
    1098                 :             :             /* Extract HeapTuple and TupleDesc */
    1099                 :        8230 :             rettup = expanded_record_get_tuple(erh);
    1100                 :             :             Assert(rettup);
    1101                 :        8230 :             retdesc = expanded_record_get_tupdesc(erh);
    1102                 :             : 
    1103         [ +  + ]:        8230 :             if (retdesc != RelationGetDescr(trigdata->tg_relation))
    1104                 :             :             {
    1105                 :             :                 /* check rowtype compatibility */
    1106                 :           6 :                 tupmap = convert_tuples_by_position(retdesc,
    1107                 :           6 :                                                     RelationGetDescr(trigdata->tg_relation),
    1108                 :             :                                                     gettext_noop("returned row structure does not match the structure of the triggering table"));
    1109                 :             :                 /* it might need conversion */
    1110         [ +  + ]:           6 :                 if (tupmap)
    1111                 :           2 :                     rettup = execute_attr_map_tuple(rettup, tupmap);
    1112                 :             :                 /* no need to free map, we're about to return anyway */
    1113                 :             :             }
    1114                 :             : 
    1115                 :             :             /*
    1116                 :             :              * Copy tuple to upper executor memory.  But if user just did
    1117                 :             :              * "return new" or "return old" without changing anything, there's
    1118                 :             :              * no need to copy; we can return the original tuple (which will
    1119                 :             :              * save a few cycles in trigger.c as well as here).
    1120                 :             :              */
    1121         [ +  + ]:        8230 :             if (rettup != trigdata->tg_newtuple &&
    1122         [ +  + ]:        5271 :                 rettup != trigdata->tg_trigtuple)
    1123                 :        1367 :                 rettup = SPI_copytuple(rettup);
    1124                 :             :         }
    1125                 :             :         else
    1126                 :             :         {
    1127                 :             :             /* Convert composite datum to a HeapTuple and TupleDesc */
    1128                 :             :             HeapTupleData tmptup;
    1129                 :             : 
    1130                 :          42 :             retdesc = deconstruct_composite_datum(estate.retval, &tmptup);
    1131                 :          38 :             rettup = &tmptup;
    1132                 :             : 
    1133                 :             :             /* check rowtype compatibility */
    1134                 :          38 :             tupmap = convert_tuples_by_position(retdesc,
    1135                 :          38 :                                                 RelationGetDescr(trigdata->tg_relation),
    1136                 :             :                                                 gettext_noop("returned row structure does not match the structure of the triggering table"));
    1137                 :             :             /* it might need conversion */
    1138         [ +  + ]:          38 :             if (tupmap)
    1139                 :           2 :                 rettup = execute_attr_map_tuple(rettup, tupmap);
    1140                 :             : 
    1141         [ +  - ]:          38 :             ReleaseTupleDesc(retdesc);
    1142                 :             :             /* no need to free map, we're about to return anyway */
    1143                 :             : 
    1144                 :             :             /* Copy tuple to upper executor memory */
    1145                 :          38 :             rettup = SPI_copytuple(rettup);
    1146                 :             :         }
    1147                 :             :     }
    1148                 :             : 
    1149                 :             :     /*
    1150                 :             :      * Let the instrumentation plugin peek at this function
    1151                 :             :      */
    1152   [ -  +  -  - ]:       10062 :     if (*plpgsql_plugin_ptr && (*plpgsql_plugin_ptr)->func_end)
    1153                 :           0 :         ((*plpgsql_plugin_ptr)->func_end) (&estate, func);
    1154                 :             : 
    1155                 :             :     /* Clean up any leftover temporary memory */
    1156                 :       10062 :     plpgsql_destroy_econtext(&estate);
    1157                 :       10062 :     exec_eval_cleanup(&estate);
    1158                 :             :     /* stmt_mcontext will be destroyed when function's main context is */
    1159                 :             : 
    1160                 :             :     /*
    1161                 :             :      * Pop the error context stack
    1162                 :             :      */
    1163                 :       10062 :     error_context_stack = plerrcontext.previous;
    1164                 :             : 
    1165                 :             :     /*
    1166                 :             :      * Return the trigger's result
    1167                 :             :      */
    1168                 :       10062 :     return rettup;
    1169                 :             : }
    1170                 :             : 
    1171                 :             : /* ----------
    1172                 :             :  * plpgsql_exec_event_trigger       Called by the call handler for
    1173                 :             :  *              event trigger execution.
    1174                 :             :  * ----------
    1175                 :             :  */
    1176                 :             : void
    1177                 :        1151 : plpgsql_exec_event_trigger(PLpgSQL_function *func, EventTriggerData *trigdata)
    1178                 :             : {
    1179                 :             :     PLpgSQL_execstate estate;
    1180                 :             :     ErrorContextCallback plerrcontext;
    1181                 :             :     int         rc;
    1182                 :             : 
    1183                 :             :     /*
    1184                 :             :      * Setup the execution state
    1185                 :             :      */
    1186                 :        1151 :     plpgsql_estate_setup(&estate, func, NULL, NULL, NULL);
    1187                 :        1151 :     estate.evtrigdata = trigdata;
    1188                 :             : 
    1189                 :             :     /*
    1190                 :             :      * Setup error traceback support for ereport()
    1191                 :             :      */
    1192                 :        1151 :     plerrcontext.callback = plpgsql_exec_error_callback;
    1193                 :        1151 :     plerrcontext.arg = &estate;
    1194                 :        1151 :     plerrcontext.previous = error_context_stack;
    1195                 :        1151 :     error_context_stack = &plerrcontext;
    1196                 :             : 
    1197                 :             :     /*
    1198                 :             :      * Make local execution copies of all the datums
    1199                 :             :      */
    1200                 :        1151 :     estate.err_text = gettext_noop("during initialization of execution state");
    1201                 :        1151 :     copy_plpgsql_datums(&estate, func);
    1202                 :             : 
    1203                 :        1151 :     estate.err_text = gettext_noop("during function entry");
    1204                 :             : 
    1205                 :             :     /*
    1206                 :             :      * Set the magic variable FOUND to false
    1207                 :             :      */
    1208                 :        1151 :     exec_set_found(&estate, false);
    1209                 :             : 
    1210                 :             :     /*
    1211                 :             :      * Let the instrumentation plugin peek at this function
    1212                 :             :      */
    1213   [ -  +  -  - ]:        1151 :     if (*plpgsql_plugin_ptr && (*plpgsql_plugin_ptr)->func_beg)
    1214                 :           0 :         ((*plpgsql_plugin_ptr)->func_beg) (&estate, func);
    1215                 :             : 
    1216                 :             :     /*
    1217                 :             :      * Now call the toplevel block of statements
    1218                 :             :      */
    1219                 :        1151 :     estate.err_text = NULL;
    1220                 :        1151 :     rc = exec_toplevel_block(&estate, func->action);
    1221         [ -  + ]:        1135 :     if (rc != PLPGSQL_RC_RETURN)
    1222                 :             :     {
    1223                 :           0 :         estate.err_text = NULL;
    1224         [ #  # ]:           0 :         ereport(ERROR,
    1225                 :             :                 (errcode(ERRCODE_S_R_E_FUNCTION_EXECUTED_NO_RETURN_STATEMENT),
    1226                 :             :                  errmsg("control reached end of trigger procedure without RETURN")));
    1227                 :             :     }
    1228                 :             : 
    1229                 :        1135 :     estate.err_text = gettext_noop("during function exit");
    1230                 :             : 
    1231                 :             :     /*
    1232                 :             :      * Let the instrumentation plugin peek at this function
    1233                 :             :      */
    1234   [ -  +  -  - ]:        1135 :     if (*plpgsql_plugin_ptr && (*plpgsql_plugin_ptr)->func_end)
    1235                 :           0 :         ((*plpgsql_plugin_ptr)->func_end) (&estate, func);
    1236                 :             : 
    1237                 :             :     /* Clean up any leftover temporary memory */
    1238                 :        1135 :     plpgsql_destroy_econtext(&estate);
    1239                 :        1135 :     exec_eval_cleanup(&estate);
    1240                 :             :     /* stmt_mcontext will be destroyed when function's main context is */
    1241                 :             : 
    1242                 :             :     /*
    1243                 :             :      * Pop the error context stack
    1244                 :             :      */
    1245                 :        1135 :     error_context_stack = plerrcontext.previous;
    1246                 :        1135 : }
    1247                 :             : 
    1248                 :             : /*
    1249                 :             :  * error context callback to let us supply a call-stack traceback
    1250                 :             :  */
    1251                 :             : static void
    1252                 :       15366 : plpgsql_exec_error_callback(void *arg)
    1253                 :             : {
    1254                 :       15366 :     PLpgSQL_execstate *estate = (PLpgSQL_execstate *) arg;
    1255                 :             :     int         err_lineno;
    1256                 :             : 
    1257                 :             :     /*
    1258                 :             :      * If err_var is set, report the variable's declaration line number.
    1259                 :             :      * Otherwise, if err_stmt is set, report the err_stmt's line number.  When
    1260                 :             :      * err_stmt is not set, we're in function entry/exit, or some such place
    1261                 :             :      * not attached to a specific line number.
    1262                 :             :      */
    1263         [ +  + ]:       15366 :     if (estate->err_var != NULL)
    1264                 :          34 :         err_lineno = estate->err_var->lineno;
    1265         [ +  + ]:       15332 :     else if (estate->err_stmt != NULL)
    1266                 :       15253 :         err_lineno = estate->err_stmt->lineno;
    1267                 :             :     else
    1268                 :          79 :         err_lineno = 0;
    1269                 :             : 
    1270         [ +  + ]:       15366 :     if (estate->err_text != NULL)
    1271                 :             :     {
    1272                 :             :         /*
    1273                 :             :          * We don't expend the cycles to run gettext() on err_text unless we
    1274                 :             :          * actually need it.  Therefore, places that set up err_text should
    1275                 :             :          * use gettext_noop() to ensure the strings get recorded in the
    1276                 :             :          * message dictionary.
    1277                 :             :          */
    1278         [ +  + ]:         109 :         if (err_lineno > 0)
    1279                 :             :         {
    1280                 :             :             /*
    1281                 :             :              * translator: last %s is a phrase such as "during statement block
    1282                 :             :              * local variable initialization"
    1283                 :             :              */
    1284                 :          34 :             errcontext("PL/pgSQL function %s line %d %s",
    1285                 :          34 :                        estate->func->fn_signature,
    1286                 :             :                        err_lineno,
    1287                 :             :                        _(estate->err_text));
    1288                 :             :         }
    1289                 :             :         else
    1290                 :             :         {
    1291                 :             :             /*
    1292                 :             :              * translator: last %s is a phrase such as "while storing call
    1293                 :             :              * arguments into local variables"
    1294                 :             :              */
    1295                 :          75 :             errcontext("PL/pgSQL function %s %s",
    1296                 :          75 :                        estate->func->fn_signature,
    1297                 :             :                        _(estate->err_text));
    1298                 :             :         }
    1299                 :             :     }
    1300   [ +  +  +  - ]:       15257 :     else if (estate->err_stmt != NULL && err_lineno > 0)
    1301                 :             :     {
    1302                 :             :         /* translator: last %s is a plpgsql statement type name */
    1303                 :       15253 :         errcontext("PL/pgSQL function %s line %d at %s",
    1304                 :       15253 :                    estate->func->fn_signature,
    1305                 :             :                    err_lineno,
    1306                 :             :                    plpgsql_stmt_typename(estate->err_stmt));
    1307                 :             :     }
    1308                 :             :     else
    1309                 :           4 :         errcontext("PL/pgSQL function %s",
    1310                 :           4 :                    estate->func->fn_signature);
    1311                 :       15366 : }
    1312                 :             : 
    1313                 :             : /*
    1314                 :             :  * error context callback used for "SELECT simple-expr INTO var"
    1315                 :             :  *
    1316                 :             :  * This should match the behavior of spi.c's _SPI_error_callback(),
    1317                 :             :  * so that the construct still reports errors the same as it did
    1318                 :             :  * before we optimized it with the simple-expression code path.
    1319                 :             :  */
    1320                 :             : static void
    1321                 :           6 : plpgsql_execsql_error_callback(void *arg)
    1322                 :             : {
    1323                 :           6 :     PLpgSQL_expr *expr = (PLpgSQL_expr *) arg;
    1324                 :           6 :     const char *query = expr->query;
    1325                 :             :     int         syntaxerrposition;
    1326                 :             : 
    1327                 :             :     /*
    1328                 :             :      * If there is a syntax error position, convert to internal syntax error;
    1329                 :             :      * otherwise treat the query as an item of context stack
    1330                 :             :      */
    1331                 :           6 :     syntaxerrposition = geterrposition();
    1332         [ -  + ]:           6 :     if (syntaxerrposition > 0)
    1333                 :             :     {
    1334                 :           0 :         errposition(0);
    1335                 :           0 :         internalerrposition(syntaxerrposition);
    1336                 :           0 :         internalerrquery(query);
    1337                 :             :     }
    1338                 :             :     else
    1339                 :             :     {
    1340                 :           6 :         errcontext("SQL statement \"%s\"", query);
    1341                 :             :     }
    1342                 :           6 : }
    1343                 :             : 
    1344                 :             : 
    1345                 :             : /* ----------
    1346                 :             :  * Support function for initializing local execution variables
    1347                 :             :  * ----------
    1348                 :             :  */
    1349                 :             : static void
    1350                 :       65416 : copy_plpgsql_datums(PLpgSQL_execstate *estate,
    1351                 :             :                     PLpgSQL_function *func)
    1352                 :             : {
    1353                 :       65416 :     int         ndatums = estate->ndatums;
    1354                 :             :     PLpgSQL_datum **indatums;
    1355                 :             :     PLpgSQL_datum **outdatums;
    1356                 :             :     char       *workspace;
    1357                 :             :     char       *ws_next;
    1358                 :             :     int         i;
    1359                 :             : 
    1360                 :             :     /* Allocate local datum-pointer array */
    1361                 :       65416 :     estate->datums = palloc_array(PLpgSQL_datum *, ndatums);
    1362                 :             : 
    1363                 :             :     /*
    1364                 :             :      * To reduce palloc overhead, we make a single palloc request for all the
    1365                 :             :      * space needed for locally-instantiated datums.
    1366                 :             :      */
    1367                 :       65416 :     workspace = palloc(func->copiable_size);
    1368                 :       65416 :     ws_next = workspace;
    1369                 :             : 
    1370                 :             :     /* Fill datum-pointer array, copying datums into workspace as needed */
    1371                 :       65416 :     indatums = func->datums;
    1372                 :       65416 :     outdatums = estate->datums;
    1373         [ +  + ]:      407689 :     for (i = 0; i < ndatums; i++)
    1374                 :             :     {
    1375                 :      342273 :         PLpgSQL_datum *indatum = indatums[i];
    1376                 :             :         PLpgSQL_datum *outdatum;
    1377                 :             : 
    1378                 :             :         /* This must agree with plpgsql_finish_datums on what is copiable */
    1379   [ +  +  +  - ]:      342273 :         switch (indatum->dtype)
    1380                 :             :         {
    1381                 :      278923 :             case PLPGSQL_DTYPE_VAR:
    1382                 :             :             case PLPGSQL_DTYPE_PROMISE:
    1383                 :      278923 :                 outdatum = (PLpgSQL_datum *) ws_next;
    1384                 :      278923 :                 memcpy(outdatum, indatum, sizeof(PLpgSQL_var));
    1385                 :      278923 :                 ws_next += MAXALIGN(sizeof(PLpgSQL_var));
    1386                 :      278923 :                 break;
    1387                 :             : 
    1388                 :       24993 :             case PLPGSQL_DTYPE_REC:
    1389                 :       24993 :                 outdatum = (PLpgSQL_datum *) ws_next;
    1390                 :       24993 :                 memcpy(outdatum, indatum, sizeof(PLpgSQL_rec));
    1391                 :       24993 :                 ws_next += MAXALIGN(sizeof(PLpgSQL_rec));
    1392                 :       24993 :                 break;
    1393                 :             : 
    1394                 :       38357 :             case PLPGSQL_DTYPE_ROW:
    1395                 :             :             case PLPGSQL_DTYPE_RECFIELD:
    1396                 :             : 
    1397                 :             :                 /*
    1398                 :             :                  * These datum records are read-only at runtime, so no need to
    1399                 :             :                  * copy them (well, RECFIELD contains cached data, but we'd
    1400                 :             :                  * just as soon centralize the caching anyway).
    1401                 :             :                  */
    1402                 :       38357 :                 outdatum = indatum;
    1403                 :       38357 :                 break;
    1404                 :             : 
    1405                 :           0 :             default:
    1406         [ #  # ]:           0 :                 elog(ERROR, "unrecognized dtype: %d", indatum->dtype);
    1407                 :             :                 outdatum = NULL;    /* keep compiler quiet */
    1408                 :             :                 break;
    1409                 :             :         }
    1410                 :             : 
    1411                 :      342273 :         outdatums[i] = outdatum;
    1412                 :             :     }
    1413                 :             : 
    1414                 :             :     Assert(ws_next == workspace + func->copiable_size);
    1415                 :       65416 : }
    1416                 :             : 
    1417                 :             : /*
    1418                 :             :  * If the variable has an armed "promise", compute the promised value
    1419                 :             :  * and assign it to the variable.
    1420                 :             :  * The assignment automatically disarms the promise.
    1421                 :             :  */
    1422                 :             : static void
    1423                 :       14721 : plpgsql_fulfill_promise(PLpgSQL_execstate *estate,
    1424                 :             :                         PLpgSQL_var *var)
    1425                 :             : {
    1426                 :             :     MemoryContext oldcontext;
    1427                 :             : 
    1428         [ +  + ]:       14721 :     if (var->promise == PLPGSQL_PROMISE_NONE)
    1429                 :        4476 :         return;                 /* nothing to do */
    1430                 :             : 
    1431                 :             :     /*
    1432                 :             :      * This will typically be invoked in a short-lived context such as the
    1433                 :             :      * mcontext.  We must create variable values in the estate's datum
    1434                 :             :      * context.  This quick-and-dirty solution risks leaking some additional
    1435                 :             :      * cruft there, but since any one promise is honored at most once per
    1436                 :             :      * function call, it's probably not worth being more careful.
    1437                 :             :      */
    1438                 :       10245 :     oldcontext = MemoryContextSwitchTo(estate->datum_context);
    1439                 :             : 
    1440   [ +  +  +  +  :       10245 :     switch (var->promise)
          +  +  +  +  +  
                +  +  - ]
    1441                 :             :     {
    1442                 :        1011 :         case PLPGSQL_PROMISE_TG_NAME:
    1443         [ -  + ]:        1011 :             if (estate->trigdata == NULL)
    1444         [ #  # ]:           0 :                 elog(ERROR, "trigger promise is not in a trigger function");
    1445                 :        1011 :             assign_simple_var(estate, var,
    1446                 :        1011 :                               DirectFunctionCall1(namein,
    1447                 :             :                                                   CStringGetDatum(estate->trigdata->tg_trigger->tgname)),
    1448                 :             :                               false, true);
    1449                 :        1011 :             break;
    1450                 :             : 
    1451                 :        1555 :         case PLPGSQL_PROMISE_TG_WHEN:
    1452         [ -  + ]:        1555 :             if (estate->trigdata == NULL)
    1453         [ #  # ]:           0 :                 elog(ERROR, "trigger promise is not in a trigger function");
    1454         [ +  + ]:        1555 :             if (TRIGGER_FIRED_BEFORE(estate->trigdata->tg_event))
    1455                 :         650 :                 assign_text_var(estate, var, "BEFORE");
    1456         [ +  + ]:         905 :             else if (TRIGGER_FIRED_AFTER(estate->trigdata->tg_event))
    1457                 :         865 :                 assign_text_var(estate, var, "AFTER");
    1458         [ +  - ]:          40 :             else if (TRIGGER_FIRED_INSTEAD(estate->trigdata->tg_event))
    1459                 :          40 :                 assign_text_var(estate, var, "INSTEAD OF");
    1460                 :             :             else
    1461         [ #  # ]:           0 :                 elog(ERROR, "unrecognized trigger execution time: not BEFORE, AFTER, or INSTEAD OF");
    1462                 :        1555 :             break;
    1463                 :             : 
    1464                 :        1439 :         case PLPGSQL_PROMISE_TG_LEVEL:
    1465         [ -  + ]:        1439 :             if (estate->trigdata == NULL)
    1466         [ #  # ]:           0 :                 elog(ERROR, "trigger promise is not in a trigger function");
    1467         [ +  + ]:        1439 :             if (TRIGGER_FIRED_FOR_ROW(estate->trigdata->tg_event))
    1468                 :         899 :                 assign_text_var(estate, var, "ROW");
    1469         [ +  - ]:         540 :             else if (TRIGGER_FIRED_FOR_STATEMENT(estate->trigdata->tg_event))
    1470                 :         540 :                 assign_text_var(estate, var, "STATEMENT");
    1471                 :             :             else
    1472         [ #  # ]:           0 :                 elog(ERROR, "unrecognized trigger event type: not ROW or STATEMENT");
    1473                 :        1439 :             break;
    1474                 :             : 
    1475                 :        3977 :         case PLPGSQL_PROMISE_TG_OP:
    1476         [ -  + ]:        3977 :             if (estate->trigdata == NULL)
    1477         [ #  # ]:           0 :                 elog(ERROR, "trigger promise is not in a trigger function");
    1478         [ +  + ]:        3977 :             if (TRIGGER_FIRED_BY_INSERT(estate->trigdata->tg_event))
    1479                 :        1901 :                 assign_text_var(estate, var, "INSERT");
    1480         [ +  + ]:        2076 :             else if (TRIGGER_FIRED_BY_UPDATE(estate->trigdata->tg_event))
    1481                 :        1795 :                 assign_text_var(estate, var, "UPDATE");
    1482         [ +  + ]:         281 :             else if (TRIGGER_FIRED_BY_DELETE(estate->trigdata->tg_event))
    1483                 :         271 :                 assign_text_var(estate, var, "DELETE");
    1484         [ +  - ]:          10 :             else if (TRIGGER_FIRED_BY_TRUNCATE(estate->trigdata->tg_event))
    1485                 :          10 :                 assign_text_var(estate, var, "TRUNCATE");
    1486                 :             :             else
    1487         [ #  # ]:           0 :                 elog(ERROR, "unrecognized trigger action: not INSERT, DELETE, UPDATE, or TRUNCATE");
    1488                 :        3977 :             break;
    1489                 :             : 
    1490                 :          64 :         case PLPGSQL_PROMISE_TG_RELID:
    1491         [ -  + ]:          64 :             if (estate->trigdata == NULL)
    1492         [ #  # ]:           0 :                 elog(ERROR, "trigger promise is not in a trigger function");
    1493                 :          64 :             assign_simple_var(estate, var,
    1494                 :          64 :                               ObjectIdGetDatum(estate->trigdata->tg_relation->rd_id),
    1495                 :             :                               false, false);
    1496                 :          64 :             break;
    1497                 :             : 
    1498                 :         583 :         case PLPGSQL_PROMISE_TG_TABLE_NAME:
    1499         [ -  + ]:         583 :             if (estate->trigdata == NULL)
    1500         [ #  # ]:           0 :                 elog(ERROR, "trigger promise is not in a trigger function");
    1501                 :         583 :             assign_simple_var(estate, var,
    1502                 :         583 :                               DirectFunctionCall1(namein,
    1503                 :             :                                                   CStringGetDatum(RelationGetRelationName(estate->trigdata->tg_relation))),
    1504                 :             :                               false, true);
    1505                 :         583 :             break;
    1506                 :             : 
    1507                 :          12 :         case PLPGSQL_PROMISE_TG_TABLE_SCHEMA:
    1508         [ -  + ]:          12 :             if (estate->trigdata == NULL)
    1509         [ #  # ]:           0 :                 elog(ERROR, "trigger promise is not in a trigger function");
    1510                 :          12 :             assign_simple_var(estate, var,
    1511                 :          12 :                               DirectFunctionCall1(namein,
    1512                 :             :                                                   CStringGetDatum(get_namespace_name(RelationGetNamespace(estate->trigdata->tg_relation)))),
    1513                 :             :                               false, true);
    1514                 :          12 :             break;
    1515                 :             : 
    1516                 :         176 :         case PLPGSQL_PROMISE_TG_NARGS:
    1517         [ -  + ]:         176 :             if (estate->trigdata == NULL)
    1518         [ #  # ]:           0 :                 elog(ERROR, "trigger promise is not in a trigger function");
    1519                 :         176 :             assign_simple_var(estate, var,
    1520                 :         176 :                               Int16GetDatum(estate->trigdata->tg_trigger->tgnargs),
    1521                 :             :                               false, false);
    1522                 :         176 :             break;
    1523                 :             : 
    1524                 :        1128 :         case PLPGSQL_PROMISE_TG_ARGV:
    1525         [ -  + ]:        1128 :             if (estate->trigdata == NULL)
    1526         [ #  # ]:           0 :                 elog(ERROR, "trigger promise is not in a trigger function");
    1527         [ +  + ]:        1128 :             if (estate->trigdata->tg_trigger->tgnargs > 0)
    1528                 :             :             {
    1529                 :             :                 /*
    1530                 :             :                  * For historical reasons, tg_argv[] subscripts start at zero
    1531                 :             :                  * not one.  So we can't use construct_array().
    1532                 :             :                  */
    1533                 :        1116 :                 int         nelems = estate->trigdata->tg_trigger->tgnargs;
    1534                 :             :                 Datum      *elems;
    1535                 :             :                 int         dims[1];
    1536                 :             :                 int         lbs[1];
    1537                 :             :                 int         i;
    1538                 :             : 
    1539                 :        1116 :                 elems = palloc_array(Datum, nelems);
    1540         [ +  + ]:        2308 :                 for (i = 0; i < nelems; i++)
    1541                 :        1192 :                     elems[i] = CStringGetTextDatum(estate->trigdata->tg_trigger->tgargs[i]);
    1542                 :        1116 :                 dims[0] = nelems;
    1543                 :        1116 :                 lbs[0] = 0;
    1544                 :             : 
    1545                 :        1116 :                 assign_simple_var(estate, var,
    1546                 :        1116 :                                   PointerGetDatum(construct_md_array(elems, NULL,
    1547                 :             :                                                                      1, dims, lbs,
    1548                 :             :                                                                      TEXTOID,
    1549                 :             :                                                                      -1, false, TYPALIGN_INT)),
    1550                 :             :                                   false, true);
    1551                 :             :             }
    1552                 :             :             else
    1553                 :             :             {
    1554                 :          12 :                 assign_simple_var(estate, var, (Datum) 0, true, false);
    1555                 :             :             }
    1556                 :        1128 :             break;
    1557                 :             : 
    1558                 :         130 :         case PLPGSQL_PROMISE_TG_EVENT:
    1559         [ -  + ]:         130 :             if (estate->evtrigdata == NULL)
    1560         [ #  # ]:           0 :                 elog(ERROR, "event trigger promise is not in an event trigger function");
    1561                 :         130 :             assign_text_var(estate, var, estate->evtrigdata->event);
    1562                 :         130 :             break;
    1563                 :             : 
    1564                 :         170 :         case PLPGSQL_PROMISE_TG_TAG:
    1565         [ -  + ]:         170 :             if (estate->evtrigdata == NULL)
    1566         [ #  # ]:           0 :                 elog(ERROR, "event trigger promise is not in an event trigger function");
    1567                 :         170 :             assign_text_var(estate, var, GetCommandTagName(estate->evtrigdata->tag));
    1568                 :         170 :             break;
    1569                 :             : 
    1570                 :           0 :         default:
    1571         [ #  # ]:           0 :             elog(ERROR, "unrecognized promise type: %d", var->promise);
    1572                 :             :     }
    1573                 :             : 
    1574                 :       10245 :     MemoryContextSwitchTo(oldcontext);
    1575                 :             : }
    1576                 :             : 
    1577                 :             : /*
    1578                 :             :  * Create a memory context for statement-lifespan variables, if we don't
    1579                 :             :  * have one already.  It will be a child of stmt_mcontext_parent, which is
    1580                 :             :  * either the function's main context or a pushed-down outer stmt_mcontext.
    1581                 :             :  */
    1582                 :             : static MemoryContext
    1583                 :       54236 : get_stmt_mcontext(PLpgSQL_execstate *estate)
    1584                 :             : {
    1585         [ +  + ]:       54236 :     if (estate->stmt_mcontext == NULL)
    1586                 :             :     {
    1587                 :       15274 :         estate->stmt_mcontext =
    1588                 :       15274 :             AllocSetContextCreate(estate->stmt_mcontext_parent,
    1589                 :             :                                   "PLpgSQL per-statement data",
    1590                 :             :                                   ALLOCSET_DEFAULT_SIZES);
    1591                 :             :     }
    1592                 :       54236 :     return estate->stmt_mcontext;
    1593                 :             : }
    1594                 :             : 
    1595                 :             : /*
    1596                 :             :  * Push down the current stmt_mcontext so that called statements won't use it.
    1597                 :             :  * This is needed by statements that have statement-lifespan data and need to
    1598                 :             :  * preserve it across some inner statements.  The caller should eventually do
    1599                 :             :  * pop_stmt_mcontext().
    1600                 :             :  */
    1601                 :             : static void
    1602                 :         121 : push_stmt_mcontext(PLpgSQL_execstate *estate)
    1603                 :             : {
    1604                 :             :     /* Should have done get_stmt_mcontext() first */
    1605                 :             :     Assert(estate->stmt_mcontext != NULL);
    1606                 :             :     /* Assert we've not messed up the stack linkage */
    1607                 :             :     Assert(MemoryContextGetParent(estate->stmt_mcontext) == estate->stmt_mcontext_parent);
    1608                 :             :     /* Push it down to become the parent of any nested stmt mcontext */
    1609                 :         121 :     estate->stmt_mcontext_parent = estate->stmt_mcontext;
    1610                 :             :     /* And make it not available for use directly */
    1611                 :         121 :     estate->stmt_mcontext = NULL;
    1612                 :         121 : }
    1613                 :             : 
    1614                 :             : /*
    1615                 :             :  * Undo push_stmt_mcontext().  We assume this is done just before or after
    1616                 :             :  * resetting the caller's stmt_mcontext; since that action will also delete
    1617                 :             :  * any child contexts, there's no need to explicitly delete whatever context
    1618                 :             :  * might currently be estate->stmt_mcontext.
    1619                 :             :  */
    1620                 :             : static void
    1621                 :        3755 : pop_stmt_mcontext(PLpgSQL_execstate *estate)
    1622                 :             : {
    1623                 :             :     /* We need only pop the stack */
    1624                 :        3755 :     estate->stmt_mcontext = estate->stmt_mcontext_parent;
    1625                 :        3755 :     estate->stmt_mcontext_parent = MemoryContextGetParent(estate->stmt_mcontext);
    1626                 :        3755 : }
    1627                 :             : 
    1628                 :             : 
    1629                 :             : /*
    1630                 :             :  * Subroutine for exec_stmt_block: does any condition in the condition list
    1631                 :             :  * match the current exception?
    1632                 :             :  */
    1633                 :             : static bool
    1634                 :        3696 : exception_matches_conditions(ErrorData *edata, PLpgSQL_condition *cond)
    1635                 :             : {
    1636         [ +  + ]:        4114 :     for (; cond != NULL; cond = cond->next)
    1637                 :             :     {
    1638                 :        4097 :         int         sqlerrstate = cond->sqlerrstate;
    1639                 :             : 
    1640                 :             :         /*
    1641                 :             :          * OTHERS matches everything *except* query-canceled and
    1642                 :             :          * assert-failure.  If you're foolish enough, you can match those
    1643                 :             :          * explicitly.
    1644                 :             :          */
    1645         [ +  + ]:        4097 :         if (sqlerrstate == PLPGSQL_OTHERS)
    1646                 :             :         {
    1647         [ +  + ]:        3023 :             if (edata->sqlerrcode != ERRCODE_QUERY_CANCELED &&
    1648         [ +  + ]:        3022 :                 edata->sqlerrcode != ERRCODE_ASSERT_FAILURE)
    1649                 :        3018 :                 return true;
    1650                 :             :         }
    1651                 :             :         /* Exact match? */
    1652         [ +  + ]:        1074 :         else if (edata->sqlerrcode == sqlerrstate)
    1653                 :         659 :             return true;
    1654                 :             :         /* Category match? */
    1655         [ +  + ]:         415 :         else if (ERRCODE_IS_CATEGORY(sqlerrstate) &&
    1656         [ +  + ]:           3 :                  ERRCODE_TO_CATEGORY(edata->sqlerrcode) == sqlerrstate)
    1657                 :           2 :             return true;
    1658                 :             :     }
    1659                 :          17 :     return false;
    1660                 :             : }
    1661                 :             : 
    1662                 :             : 
    1663                 :             : /* ----------
    1664                 :             :  * exec_toplevel_block          Execute the toplevel block
    1665                 :             :  *
    1666                 :             :  * This is intentionally equivalent to executing exec_stmts() with a
    1667                 :             :  * list consisting of the one statement.  One tiny difference is that
    1668                 :             :  * we do not bother to save the entry value of estate->err_stmt;
    1669                 :             :  * that's assumed to be NULL.
    1670                 :             :  * ----------
    1671                 :             :  */
    1672                 :             : static int
    1673                 :       65412 : exec_toplevel_block(PLpgSQL_execstate *estate, PLpgSQL_stmt_block *block)
    1674                 :             : {
    1675                 :             :     int         rc;
    1676                 :             : 
    1677                 :       65412 :     estate->err_stmt = (PLpgSQL_stmt *) block;
    1678                 :             : 
    1679                 :             :     /* Let the plugin know that we are about to execute this statement */
    1680   [ -  +  -  - ]:       65412 :     if (*plpgsql_plugin_ptr && (*plpgsql_plugin_ptr)->stmt_beg)
    1681                 :           0 :         ((*plpgsql_plugin_ptr)->stmt_beg) (estate, (PLpgSQL_stmt *) block);
    1682                 :             : 
    1683         [ +  + ]:       65412 :     CHECK_FOR_INTERRUPTS();
    1684                 :             : 
    1685                 :       65412 :     rc = exec_stmt_block(estate, block);
    1686                 :             : 
    1687                 :             :     /* Let the plugin know that we have finished executing this statement */
    1688   [ -  +  -  - ]:       64331 :     if (*plpgsql_plugin_ptr && (*plpgsql_plugin_ptr)->stmt_end)
    1689                 :           0 :         ((*plpgsql_plugin_ptr)->stmt_end) (estate, (PLpgSQL_stmt *) block);
    1690                 :             : 
    1691                 :       64331 :     estate->err_stmt = NULL;
    1692                 :             : 
    1693                 :       64331 :     return rc;
    1694                 :             : }
    1695                 :             : 
    1696                 :             : 
    1697                 :             : /* ----------
    1698                 :             :  * exec_stmt_block          Execute a block of statements
    1699                 :             :  * ----------
    1700                 :             :  */
    1701                 :             : static int
    1702                 :       84985 : exec_stmt_block(PLpgSQL_execstate *estate, PLpgSQL_stmt_block *block)
    1703                 :             : {
    1704                 :       84985 :     volatile int rc = -1;
    1705                 :             :     int         i;
    1706                 :             : 
    1707                 :             :     /*
    1708                 :             :      * First initialize all variables declared in this block
    1709                 :             :      */
    1710                 :       84985 :     estate->err_text = gettext_noop("during statement block local variable initialization");
    1711                 :             : 
    1712         [ +  + ]:      107496 :     for (i = 0; i < block->n_initvars; i++)
    1713                 :             :     {
    1714                 :       22545 :         int         n = block->initvarnos[i];
    1715                 :       22545 :         PLpgSQL_datum *datum = estate->datums[n];
    1716                 :             : 
    1717                 :             :         /*
    1718                 :             :          * The set of dtypes handled here must match plpgsql_add_initdatums().
    1719                 :             :          *
    1720                 :             :          * Note that we currently don't support promise datums within blocks,
    1721                 :             :          * only at a function's outermost scope, so we needn't handle those
    1722                 :             :          * here.
    1723                 :             :          *
    1724                 :             :          * Since RECFIELD isn't a supported case either, it's okay to cast the
    1725                 :             :          * PLpgSQL_datum to PLpgSQL_variable.
    1726                 :             :          */
    1727                 :       22545 :         estate->err_var = (PLpgSQL_variable *) datum;
    1728                 :             : 
    1729      [ +  +  - ]:       22545 :         switch (datum->dtype)
    1730                 :             :         {
    1731                 :       19124 :             case PLPGSQL_DTYPE_VAR:
    1732                 :             :                 {
    1733                 :       19124 :                     PLpgSQL_var *var = (PLpgSQL_var *) datum;
    1734                 :             : 
    1735                 :             :                     /*
    1736                 :             :                      * Free any old value, in case re-entering block, and
    1737                 :             :                      * initialize to NULL
    1738                 :             :                      */
    1739                 :       19124 :                     assign_simple_var(estate, var, (Datum) 0, true, false);
    1740                 :             : 
    1741         [ +  + ]:       19124 :                     if (var->default_val == NULL)
    1742                 :             :                     {
    1743                 :             :                         /*
    1744                 :             :                          * If needed, give the datatype a chance to reject
    1745                 :             :                          * NULLs, by assigning a NULL to the variable.  We
    1746                 :             :                          * claim the value is of type UNKNOWN, not the var's
    1747                 :             :                          * datatype, else coercion will be skipped.
    1748                 :             :                          */
    1749         [ +  + ]:       16658 :                         if (var->datatype->typtype == TYPTYPE_DOMAIN)
    1750                 :          85 :                             exec_assign_value(estate,
    1751                 :             :                                               (PLpgSQL_datum *) var,
    1752                 :             :                                               (Datum) 0,
    1753                 :             :                                               true,
    1754                 :             :                                               UNKNOWNOID,
    1755                 :             :                                               -1);
    1756                 :             : 
    1757                 :             :                         /* parser should have rejected NOT NULL */
    1758                 :             :                         Assert(!var->notnull);
    1759                 :             :                     }
    1760                 :             :                     else
    1761                 :             :                     {
    1762                 :        2466 :                         exec_assign_expr(estate, (PLpgSQL_datum *) var,
    1763                 :             :                                          var->default_val);
    1764                 :             :                     }
    1765                 :             :                 }
    1766                 :       19099 :                 break;
    1767                 :             : 
    1768                 :        3421 :             case PLPGSQL_DTYPE_REC:
    1769                 :             :                 {
    1770                 :        3421 :                     PLpgSQL_rec *rec = (PLpgSQL_rec *) datum;
    1771                 :             : 
    1772                 :             :                     /*
    1773                 :             :                      * Deletion of any existing object will be handled during
    1774                 :             :                      * the assignments below, and in some cases it's more
    1775                 :             :                      * efficient for us not to get rid of it beforehand.
    1776                 :             :                      */
    1777         [ +  + ]:        3421 :                     if (rec->default_val == NULL)
    1778                 :             :                     {
    1779                 :             :                         /*
    1780                 :             :                          * If needed, give the datatype a chance to reject
    1781                 :             :                          * NULLs, by assigning a NULL to the variable.
    1782                 :             :                          */
    1783                 :        3402 :                         exec_move_row(estate, (PLpgSQL_variable *) rec,
    1784                 :             :                                       NULL, NULL);
    1785                 :             : 
    1786                 :             :                         /* parser should have rejected NOT NULL */
    1787                 :             :                         Assert(!rec->notnull);
    1788                 :             :                     }
    1789                 :             :                     else
    1790                 :             :                     {
    1791                 :          19 :                         exec_assign_expr(estate, (PLpgSQL_datum *) rec,
    1792                 :             :                                          rec->default_val);
    1793                 :             :                     }
    1794                 :             :                 }
    1795                 :        3412 :                 break;
    1796                 :             : 
    1797                 :           0 :             default:
    1798         [ #  # ]:           0 :                 elog(ERROR, "unrecognized dtype: %d", datum->dtype);
    1799                 :             :         }
    1800                 :             :     }
    1801                 :             : 
    1802                 :       84951 :     estate->err_var = NULL;
    1803                 :             : 
    1804         [ +  + ]:       84951 :     if (block->exceptions)
    1805                 :             :     {
    1806                 :             :         /*
    1807                 :             :          * Execute the statements in the block's body inside a sub-transaction
    1808                 :             :          */
    1809                 :       19723 :         MemoryContext oldcontext = CurrentMemoryContext;
    1810                 :       19723 :         ResourceOwner oldowner = CurrentResourceOwner;
    1811                 :       19723 :         ExprContext *old_eval_econtext = estate->eval_econtext;
    1812                 :       19723 :         ErrorData  *save_cur_error = estate->cur_error;
    1813                 :             :         MemoryContext stmt_mcontext;
    1814                 :             : 
    1815                 :       19723 :         estate->err_text = gettext_noop("during statement block entry");
    1816                 :             : 
    1817                 :             :         /*
    1818                 :             :          * We will need a stmt_mcontext to hold the error data if an error
    1819                 :             :          * occurs.  It seems best to force it to exist before entering the
    1820                 :             :          * subtransaction, so that we reduce the risk of out-of-memory during
    1821                 :             :          * error recovery, and because this greatly simplifies restoring the
    1822                 :             :          * stmt_mcontext stack to the correct state after an error.  We can
    1823                 :             :          * ameliorate the cost of this by allowing the called statements to
    1824                 :             :          * use this mcontext too; so we don't push it down here.
    1825                 :             :          */
    1826                 :       19723 :         stmt_mcontext = get_stmt_mcontext(estate);
    1827                 :             : 
    1828                 :       19723 :         BeginInternalSubTransaction(NULL);
    1829                 :             :         /* Want to run statements inside function's memory context */
    1830                 :       19723 :         MemoryContextSwitchTo(oldcontext);
    1831                 :             : 
    1832         [ +  + ]:       19723 :         PG_TRY();
    1833                 :             :         {
    1834                 :             :             /*
    1835                 :             :              * We need to run the block's statements with a new eval_econtext
    1836                 :             :              * that belongs to the current subtransaction; if we try to use
    1837                 :             :              * the outer econtext then ExprContext shutdown callbacks will be
    1838                 :             :              * called at the wrong times.
    1839                 :             :              */
    1840                 :       19723 :             plpgsql_create_econtext(estate);
    1841                 :             : 
    1842                 :       19723 :             estate->err_text = NULL;
    1843                 :             : 
    1844                 :             :             /* Run the block's statements */
    1845                 :       19723 :             rc = exec_stmts(estate, block->body);
    1846                 :             : 
    1847                 :       16036 :             estate->err_text = gettext_noop("during statement block exit");
    1848                 :             : 
    1849                 :             :             /*
    1850                 :             :              * If the block ended with RETURN, we may need to copy the return
    1851                 :             :              * value out of the subtransaction eval_context.  We can avoid a
    1852                 :             :              * physical copy if the value happens to be a R/W expanded object.
    1853                 :             :              */
    1854         [ +  + ]:       16036 :             if (rc == PLPGSQL_RC_RETURN &&
    1855         [ +  - ]:        1035 :                 !estate->retisset &&
    1856         [ +  - ]:        1035 :                 !estate->retisnull)
    1857                 :             :             {
    1858                 :             :                 int16       resTypLen;
    1859                 :             :                 bool        resTypByVal;
    1860                 :             : 
    1861                 :        1035 :                 get_typlenbyval(estate->rettype, &resTypLen, &resTypByVal);
    1862                 :        1035 :                 estate->retval = datumTransfer(estate->retval,
    1863                 :             :                                                resTypByVal, resTypLen);
    1864                 :             :             }
    1865                 :             : 
    1866                 :             :             /* Commit the inner transaction, return to outer xact context */
    1867                 :       16036 :             ReleaseCurrentSubTransaction();
    1868                 :       16036 :             MemoryContextSwitchTo(oldcontext);
    1869                 :       16036 :             CurrentResourceOwner = oldowner;
    1870                 :             : 
    1871                 :             :             /* Assert that the stmt_mcontext stack is unchanged */
    1872                 :             :             Assert(stmt_mcontext == estate->stmt_mcontext);
    1873                 :             : 
    1874                 :             :             /*
    1875                 :             :              * Revert to outer eval_econtext.  (The inner one was
    1876                 :             :              * automatically cleaned up during subxact exit.)
    1877                 :             :              */
    1878                 :       16036 :             estate->eval_econtext = old_eval_econtext;
    1879                 :             :         }
    1880                 :        3687 :         PG_CATCH();
    1881                 :             :         {
    1882                 :             :             ErrorData  *edata;
    1883                 :             :             ListCell   *e;
    1884                 :             : 
    1885                 :        3687 :             estate->err_text = gettext_noop("during exception cleanup");
    1886                 :             : 
    1887                 :             :             /* Save error info in our stmt_mcontext */
    1888                 :        3687 :             MemoryContextSwitchTo(stmt_mcontext);
    1889                 :        3687 :             edata = CopyErrorData();
    1890                 :        3687 :             FlushErrorState();
    1891                 :             : 
    1892                 :             :             /* Abort the inner transaction */
    1893                 :        3687 :             RollbackAndReleaseCurrentSubTransaction();
    1894                 :        3687 :             MemoryContextSwitchTo(oldcontext);
    1895                 :        3687 :             CurrentResourceOwner = oldowner;
    1896                 :             : 
    1897                 :             :             /*
    1898                 :             :              * Set up the stmt_mcontext stack as though we had restored our
    1899                 :             :              * previous state and then done push_stmt_mcontext().  The push is
    1900                 :             :              * needed so that statements in the exception handler won't
    1901                 :             :              * clobber the error data that's in our stmt_mcontext.
    1902                 :             :              */
    1903                 :        3687 :             estate->stmt_mcontext_parent = stmt_mcontext;
    1904                 :        3687 :             estate->stmt_mcontext = NULL;
    1905                 :             : 
    1906                 :             :             /*
    1907                 :             :              * Now we can delete any nested stmt_mcontexts that might have
    1908                 :             :              * been created as children of ours.  (Note: we do not immediately
    1909                 :             :              * release any statement-lifespan data that might have been left
    1910                 :             :              * behind in stmt_mcontext itself.  We could attempt that by doing
    1911                 :             :              * a MemoryContextReset on it before collecting the error data
    1912                 :             :              * above, but it seems too risky to do any significant amount of
    1913                 :             :              * work before collecting the error.)
    1914                 :             :              */
    1915                 :        3687 :             MemoryContextDeleteChildren(stmt_mcontext);
    1916                 :             : 
    1917                 :             :             /* Revert to outer eval_econtext */
    1918                 :        3687 :             estate->eval_econtext = old_eval_econtext;
    1919                 :             : 
    1920                 :             :             /*
    1921                 :             :              * Must clean up the econtext too.  However, any tuple table made
    1922                 :             :              * in the subxact will have been thrown away by SPI during subxact
    1923                 :             :              * abort, so we don't need to (and mustn't try to) free the
    1924                 :             :              * eval_tuptable.
    1925                 :             :              */
    1926                 :        3687 :             estate->eval_tuptable = NULL;
    1927                 :        3687 :             exec_eval_cleanup(estate);
    1928                 :             : 
    1929                 :             :             /* Look for a matching exception handler */
    1930   [ +  -  +  +  :        3704 :             foreach(e, block->exceptions->exc_list)
                   +  + ]
    1931                 :             :             {
    1932                 :        3696 :                 PLpgSQL_exception *exception = (PLpgSQL_exception *) lfirst(e);
    1933                 :             : 
    1934         [ +  + ]:        3696 :                 if (exception_matches_conditions(edata, exception->conditions))
    1935                 :             :                 {
    1936                 :             :                     /*
    1937                 :             :                      * Initialize the magic SQLSTATE and SQLERRM variables for
    1938                 :             :                      * the exception block; this also frees values from any
    1939                 :             :                      * prior use of the same exception. We needn't do this
    1940                 :             :                      * until we have found a matching exception.
    1941                 :             :                      */
    1942                 :             :                     PLpgSQL_var *state_var;
    1943                 :             :                     PLpgSQL_var *errm_var;
    1944                 :             : 
    1945                 :        3679 :                     state_var = (PLpgSQL_var *)
    1946                 :        3679 :                         estate->datums[block->exceptions->sqlstate_varno];
    1947                 :        3679 :                     errm_var = (PLpgSQL_var *)
    1948                 :        3679 :                         estate->datums[block->exceptions->sqlerrm_varno];
    1949                 :             : 
    1950                 :        3679 :                     assign_text_var(estate, state_var,
    1951                 :        3679 :                                     unpack_sql_state(edata->sqlerrcode));
    1952                 :        3679 :                     assign_text_var(estate, errm_var, edata->message);
    1953                 :             : 
    1954                 :             :                     /*
    1955                 :             :                      * Also set up cur_error so the error data is accessible
    1956                 :             :                      * inside the handler.
    1957                 :             :                      */
    1958                 :        3679 :                     estate->cur_error = edata;
    1959                 :             : 
    1960                 :        3679 :                     estate->err_text = NULL;
    1961                 :             : 
    1962                 :        3679 :                     rc = exec_stmts(estate, exception->action);
    1963                 :             : 
    1964                 :        3646 :                     break;
    1965                 :             :                 }
    1966                 :             :             }
    1967                 :             : 
    1968                 :             :             /*
    1969                 :             :              * Restore previous state of cur_error, whether or not we executed
    1970                 :             :              * a handler.  This is needed in case an error got thrown from
    1971                 :             :              * some inner block's exception handler.
    1972                 :             :              */
    1973                 :        3654 :             estate->cur_error = save_cur_error;
    1974                 :             : 
    1975                 :             :             /* If no match found, re-throw the error */
    1976         [ +  + ]:        3654 :             if (e == NULL)
    1977                 :           8 :                 ReThrowError(edata);
    1978                 :             : 
    1979                 :             :             /* Restore stmt_mcontext stack and release the error data */
    1980                 :        3646 :             pop_stmt_mcontext(estate);
    1981                 :        3646 :             MemoryContextReset(stmt_mcontext);
    1982                 :             :         }
    1983         [ -  + ]:       19682 :         PG_END_TRY();
    1984                 :             : 
    1985                 :             :         Assert(save_cur_error == estate->cur_error);
    1986                 :             :     }
    1987                 :             :     else
    1988                 :             :     {
    1989                 :             :         /*
    1990                 :             :          * Just execute the statements in the block's body
    1991                 :             :          */
    1992                 :       65228 :         estate->err_text = NULL;
    1993                 :             : 
    1994                 :       65228 :         rc = exec_stmts(estate, block->body);
    1995                 :             :     }
    1996                 :             : 
    1997                 :       83851 :     estate->err_text = NULL;
    1998                 :             : 
    1999                 :             :     /*
    2000                 :             :      * Handle the return code.  This is intentionally different from
    2001                 :             :      * LOOP_RC_PROCESSING(): CONTINUE never matches a block, and EXIT matches
    2002                 :             :      * a block only if there is a label match.
    2003                 :             :      */
    2004      [ +  +  - ]:       83851 :     switch (rc)
    2005                 :             :     {
    2006                 :       83839 :         case PLPGSQL_RC_OK:
    2007                 :             :         case PLPGSQL_RC_RETURN:
    2008                 :             :         case PLPGSQL_RC_CONTINUE:
    2009                 :       83839 :             return rc;
    2010                 :             : 
    2011                 :          12 :         case PLPGSQL_RC_EXIT:
    2012         [ +  + ]:          12 :             if (estate->exitlabel == NULL)
    2013                 :           6 :                 return PLPGSQL_RC_EXIT;
    2014         [ +  + ]:           6 :             if (block->label == NULL)
    2015                 :           1 :                 return PLPGSQL_RC_EXIT;
    2016         [ +  + ]:           5 :             if (strcmp(block->label, estate->exitlabel) != 0)
    2017                 :           2 :                 return PLPGSQL_RC_EXIT;
    2018                 :           3 :             estate->exitlabel = NULL;
    2019                 :           3 :             return PLPGSQL_RC_OK;
    2020                 :             : 
    2021                 :           0 :         default:
    2022         [ #  # ]:           0 :             elog(ERROR, "unrecognized rc: %d", rc);
    2023                 :             :     }
    2024                 :             : 
    2025                 :             :     return PLPGSQL_RC_OK;
    2026                 :             : }
    2027                 :             : 
    2028                 :             : 
    2029                 :             : /* ----------
    2030                 :             :  * exec_stmts           Iterate over a list of statements
    2031                 :             :  *              as long as their return code is OK
    2032                 :             :  * ----------
    2033                 :             :  */
    2034                 :             : static int
    2035                 :      245755 : exec_stmts(PLpgSQL_execstate *estate, List *stmts)
    2036                 :             : {
    2037                 :      245755 :     PLpgSQL_stmt *save_estmt = estate->err_stmt;
    2038                 :             :     ListCell   *s;
    2039                 :             : 
    2040         [ +  + ]:      245755 :     if (stmts == NIL)
    2041                 :             :     {
    2042                 :             :         /*
    2043                 :             :          * Ensure we do a CHECK_FOR_INTERRUPTS() even though there is no
    2044                 :             :          * statement.  This prevents hangup in a tight loop if, for instance,
    2045                 :             :          * there is a LOOP construct with an empty body.
    2046                 :             :          */
    2047         [ -  + ]:       57014 :         CHECK_FOR_INTERRUPTS();
    2048                 :       57014 :         return PLPGSQL_RC_OK;
    2049                 :             :     }
    2050                 :             : 
    2051   [ +  -  +  +  :      456295 :     foreach(s, stmts)
                   +  + ]
    2052                 :             :     {
    2053                 :      345953 :         PLpgSQL_stmt *stmt = (PLpgSQL_stmt *) lfirst(s);
    2054                 :             :         int         rc;
    2055                 :             : 
    2056                 :      345953 :         estate->err_stmt = stmt;
    2057                 :             : 
    2058                 :             :         /* Let the plugin know that we are about to execute this statement */
    2059   [ -  +  -  - ]:      345953 :         if (*plpgsql_plugin_ptr && (*plpgsql_plugin_ptr)->stmt_beg)
    2060                 :           0 :             ((*plpgsql_plugin_ptr)->stmt_beg) (estate, stmt);
    2061                 :             : 
    2062         [ -  + ]:      345953 :         CHECK_FOR_INTERRUPTS();
    2063                 :             : 
    2064   [ +  +  +  +  :      345953 :         switch (stmt->cmd_type)
          +  +  +  +  +  
          +  +  +  +  +  
          +  +  +  +  +  
          +  +  +  +  +  
             +  +  +  - ]
    2065                 :             :         {
    2066                 :       19573 :             case PLPGSQL_STMT_BLOCK:
    2067                 :       19573 :                 rc = exec_stmt_block(estate, (PLpgSQL_stmt_block *) stmt);
    2068                 :       19520 :                 break;
    2069                 :             : 
    2070                 :       68302 :             case PLPGSQL_STMT_ASSIGN:
    2071                 :       68302 :                 rc = exec_stmt_assign(estate, (PLpgSQL_stmt_assign *) stmt);
    2072                 :       68112 :                 break;
    2073                 :             : 
    2074                 :        3991 :             case PLPGSQL_STMT_PERFORM:
    2075                 :        3991 :                 rc = exec_stmt_perform(estate, (PLpgSQL_stmt_perform *) stmt);
    2076                 :        2999 :                 break;
    2077                 :             : 
    2078                 :          65 :             case PLPGSQL_STMT_CALL:
    2079                 :          65 :                 rc = exec_stmt_call(estate, (PLpgSQL_stmt_call *) stmt);
    2080                 :          58 :                 break;
    2081                 :             : 
    2082                 :         101 :             case PLPGSQL_STMT_GETDIAG:
    2083                 :         101 :                 rc = exec_stmt_getdiag(estate, (PLpgSQL_stmt_getdiag *) stmt);
    2084                 :          97 :                 break;
    2085                 :             : 
    2086                 :       77472 :             case PLPGSQL_STMT_IF:
    2087                 :       77472 :                 rc = exec_stmt_if(estate, (PLpgSQL_stmt_if *) stmt);
    2088                 :       77202 :                 break;
    2089                 :             : 
    2090                 :         154 :             case PLPGSQL_STMT_CASE:
    2091                 :         154 :                 rc = exec_stmt_case(estate, (PLpgSQL_stmt_case *) stmt);
    2092                 :         142 :                 break;
    2093                 :             : 
    2094                 :          62 :             case PLPGSQL_STMT_LOOP:
    2095                 :          62 :                 rc = exec_stmt_loop(estate, (PLpgSQL_stmt_loop *) stmt);
    2096                 :          62 :                 break;
    2097                 :             : 
    2098                 :         286 :             case PLPGSQL_STMT_WHILE:
    2099                 :         286 :                 rc = exec_stmt_while(estate, (PLpgSQL_stmt_while *) stmt);
    2100                 :         286 :                 break;
    2101                 :             : 
    2102                 :        2976 :             case PLPGSQL_STMT_FORI:
    2103                 :        2976 :                 rc = exec_stmt_fori(estate, (PLpgSQL_stmt_fori *) stmt);
    2104                 :        2957 :                 break;
    2105                 :             : 
    2106                 :        1668 :             case PLPGSQL_STMT_FORS:
    2107                 :        1668 :                 rc = exec_stmt_fors(estate, (PLpgSQL_stmt_fors *) stmt);
    2108                 :        1624 :                 break;
    2109                 :             : 
    2110                 :          69 :             case PLPGSQL_STMT_FORC:
    2111                 :          69 :                 rc = exec_stmt_forc(estate, (PLpgSQL_stmt_forc *) stmt);
    2112                 :          69 :                 break;
    2113                 :             : 
    2114                 :         121 :             case PLPGSQL_STMT_FOREACH_A:
    2115                 :         121 :                 rc = exec_stmt_foreach_a(estate, (PLpgSQL_stmt_foreach_a *) stmt);
    2116                 :         109 :                 break;
    2117                 :             : 
    2118                 :        2367 :             case PLPGSQL_STMT_EXIT:
    2119                 :        2367 :                 rc = exec_stmt_exit(estate, (PLpgSQL_stmt_exit *) stmt);
    2120                 :        2367 :                 break;
    2121                 :             : 
    2122                 :       64392 :             case PLPGSQL_STMT_RETURN:
    2123                 :       64392 :                 rc = exec_stmt_return(estate, (PLpgSQL_stmt_return *) stmt);
    2124                 :       64327 :                 break;
    2125                 :             : 
    2126                 :        4041 :             case PLPGSQL_STMT_RETURN_NEXT:
    2127                 :        4041 :                 rc = exec_stmt_return_next(estate, (PLpgSQL_stmt_return_next *) stmt);
    2128                 :        4035 :                 break;
    2129                 :             : 
    2130                 :        1861 :             case PLPGSQL_STMT_RETURN_QUERY:
    2131                 :        1861 :                 rc = exec_stmt_return_query(estate, (PLpgSQL_stmt_return_query *) stmt);
    2132                 :        1848 :                 break;
    2133                 :             : 
    2134                 :       12529 :             case PLPGSQL_STMT_RAISE:
    2135                 :       12529 :                 rc = exec_stmt_raise(estate, (PLpgSQL_stmt_raise *) stmt);
    2136                 :       11643 :                 break;
    2137                 :             : 
    2138                 :        8483 :             case PLPGSQL_STMT_ASSERT:
    2139                 :        8483 :                 rc = exec_stmt_assert(estate, (PLpgSQL_stmt_assert *) stmt);
    2140                 :        8467 :                 break;
    2141                 :             : 
    2142                 :       55097 :             case PLPGSQL_STMT_EXECSQL:
    2143                 :       55097 :                 rc = exec_stmt_execsql(estate, (PLpgSQL_stmt_execsql *) stmt);
    2144                 :       52829 :                 break;
    2145                 :             : 
    2146                 :       13299 :             case PLPGSQL_STMT_DYNEXECUTE:
    2147                 :       13299 :                 rc = exec_stmt_dynexecute(estate, (PLpgSQL_stmt_dynexecute *) stmt);
    2148                 :       13102 :                 break;
    2149                 :             : 
    2150                 :        6358 :             case PLPGSQL_STMT_DYNFORS:
    2151                 :        6358 :                 rc = exec_stmt_dynfors(estate, (PLpgSQL_stmt_dynfors *) stmt);
    2152                 :        6350 :                 break;
    2153                 :             : 
    2154                 :         125 :             case PLPGSQL_STMT_OPEN:
    2155                 :         125 :                 rc = exec_stmt_open(estate, (PLpgSQL_stmt_open *) stmt);
    2156                 :         101 :                 break;
    2157                 :             : 
    2158                 :         249 :             case PLPGSQL_STMT_FETCH:
    2159                 :         249 :                 rc = exec_stmt_fetch(estate, (PLpgSQL_stmt_fetch *) stmt);
    2160                 :         241 :                 break;
    2161                 :             : 
    2162                 :          52 :             case PLPGSQL_STMT_CLOSE:
    2163                 :          52 :                 rc = exec_stmt_close(estate, (PLpgSQL_stmt_close *) stmt);
    2164                 :          52 :                 break;
    2165                 :             : 
    2166                 :        2162 :             case PLPGSQL_STMT_COMMIT:
    2167                 :        2162 :                 rc = exec_stmt_commit(estate, (PLpgSQL_stmt_commit *) stmt);
    2168                 :        2151 :                 break;
    2169                 :             : 
    2170                 :          98 :             case PLPGSQL_STMT_ROLLBACK:
    2171                 :          98 :                 rc = exec_stmt_rollback(estate, (PLpgSQL_stmt_rollback *) stmt);
    2172                 :          95 :                 break;
    2173                 :             : 
    2174                 :           0 :             default:
    2175                 :             :                 /* point err_stmt to parent, since this one seems corrupt */
    2176                 :           0 :                 estate->err_stmt = save_estmt;
    2177         [ #  # ]:           0 :                 elog(ERROR, "unrecognized cmd_type: %d", stmt->cmd_type);
    2178                 :             :                 rc = -1;        /* keep compiler quiet */
    2179                 :             :         }
    2180                 :             : 
    2181                 :             :         /* Let the plugin know that we have finished executing this statement */
    2182   [ -  +  -  - ]:      340845 :         if (*plpgsql_plugin_ptr && (*plpgsql_plugin_ptr)->stmt_end)
    2183                 :           0 :             ((*plpgsql_plugin_ptr)->stmt_end) (estate, stmt);
    2184                 :             : 
    2185         [ +  + ]:      340845 :         if (rc != PLPGSQL_RC_OK)
    2186                 :             :         {
    2187                 :       73291 :             estate->err_stmt = save_estmt;
    2188                 :       73291 :             return rc;
    2189                 :             :         }
    2190                 :             :     }                           /* end of loop over statements */
    2191                 :             : 
    2192                 :      110342 :     estate->err_stmt = save_estmt;
    2193                 :      110342 :     return PLPGSQL_RC_OK;
    2194                 :             : }
    2195                 :             : 
    2196                 :             : 
    2197                 :             : /* ----------
    2198                 :             :  * exec_stmt_assign         Evaluate an expression and
    2199                 :             :  *                  put the result into a variable.
    2200                 :             :  * ----------
    2201                 :             :  */
    2202                 :             : static int
    2203                 :       68302 : exec_stmt_assign(PLpgSQL_execstate *estate, PLpgSQL_stmt_assign *stmt)
    2204                 :             : {
    2205                 :             :     Assert(stmt->varno >= 0);
    2206                 :             : 
    2207                 :       68302 :     exec_assign_expr(estate, estate->datums[stmt->varno], stmt->expr);
    2208                 :             : 
    2209                 :       68112 :     return PLPGSQL_RC_OK;
    2210                 :             : }
    2211                 :             : 
    2212                 :             : /* ----------
    2213                 :             :  * exec_stmt_perform        Evaluate query and discard result (but set
    2214                 :             :  *                          FOUND depending on whether at least one row
    2215                 :             :  *                          was returned).
    2216                 :             :  * ----------
    2217                 :             :  */
    2218                 :             : static int
    2219                 :        3991 : exec_stmt_perform(PLpgSQL_execstate *estate, PLpgSQL_stmt_perform *stmt)
    2220                 :             : {
    2221                 :        3991 :     PLpgSQL_expr *expr = stmt->expr;
    2222                 :             : 
    2223                 :        3991 :     (void) exec_run_select(estate, expr, 0, NULL);
    2224                 :        2999 :     exec_set_found(estate, (estate->eval_processed != 0));
    2225                 :        2999 :     exec_eval_cleanup(estate);
    2226                 :             : 
    2227                 :        2999 :     return PLPGSQL_RC_OK;
    2228                 :             : }
    2229                 :             : 
    2230                 :             : /*
    2231                 :             :  * exec_stmt_call
    2232                 :             :  *
    2233                 :             :  * NOTE: this is used for both CALL and DO statements.
    2234                 :             :  */
    2235                 :             : static int
    2236                 :          65 : exec_stmt_call(PLpgSQL_execstate *estate, PLpgSQL_stmt_call *stmt)
    2237                 :             : {
    2238                 :          65 :     PLpgSQL_expr *expr = stmt->expr;
    2239                 :             :     LocalTransactionId before_lxid;
    2240                 :             :     LocalTransactionId after_lxid;
    2241                 :             :     ParamListInfo paramLI;
    2242                 :             :     SPIExecuteOptions options;
    2243                 :             :     int         rc;
    2244                 :             : 
    2245                 :             :     /*
    2246                 :             :      * Make a plan if we don't have one already.
    2247                 :             :      */
    2248         [ +  + ]:          65 :     if (expr->plan == NULL)
    2249                 :          52 :         exec_prepare_plan(estate, expr, 0);
    2250                 :             : 
    2251                 :             :     /*
    2252                 :             :      * A CALL or DO can never be a simple expression.
    2253                 :             :      */
    2254                 :             :     Assert(!expr->expr_simple_expr);
    2255                 :             : 
    2256                 :             :     /*
    2257                 :             :      * Also construct a DTYPE_ROW datum representing the plpgsql variables
    2258                 :             :      * associated with the procedure's output arguments.  Then we can use
    2259                 :             :      * exec_move_row() to do the assignments.
    2260                 :             :      */
    2261   [ +  +  +  + ]:          64 :     if (stmt->is_call && stmt->target == NULL)
    2262                 :          50 :         stmt->target = make_callstmt_target(estate, expr);
    2263                 :             : 
    2264                 :          59 :     paramLI = setup_param_list(estate, expr);
    2265                 :             : 
    2266                 :          59 :     before_lxid = MyProc->vxid.lxid;
    2267                 :             : 
    2268                 :             :     /*
    2269                 :             :      * If we have a procedure-lifespan resowner, use that to hold the refcount
    2270                 :             :      * for the plan.  This avoids refcount leakage complaints if the called
    2271                 :             :      * procedure ends the current transaction.
    2272                 :             :      *
    2273                 :             :      * Also, tell SPI to allow non-atomic execution.
    2274                 :             :      */
    2275                 :          59 :     memset(&options, 0, sizeof(options));
    2276                 :          59 :     options.params = paramLI;
    2277                 :          59 :     options.read_only = estate->readonly_func;
    2278                 :          59 :     options.allow_nonatomic = true;
    2279                 :          59 :     options.owner = estate->procedure_resowner;
    2280                 :             : 
    2281                 :          59 :     rc = SPI_execute_plan_extended(expr->plan, &options);
    2282                 :             : 
    2283         [ -  + ]:          58 :     if (rc < 0)
    2284         [ #  # ]:           0 :         elog(ERROR, "SPI_execute_plan_extended failed executing query \"%s\": %s",
    2285                 :             :              expr->query, SPI_result_code_string(rc));
    2286                 :             : 
    2287                 :          58 :     after_lxid = MyProc->vxid.lxid;
    2288                 :             : 
    2289         [ +  + ]:          58 :     if (before_lxid != after_lxid)
    2290                 :             :     {
    2291                 :             :         /*
    2292                 :             :          * If we are in a new transaction after the call, we need to build new
    2293                 :             :          * simple-expression infrastructure.
    2294                 :             :          */
    2295                 :           4 :         estate->simple_eval_estate = NULL;
    2296                 :           4 :         estate->simple_eval_resowner = NULL;
    2297                 :           4 :         plpgsql_create_econtext(estate);
    2298                 :             :     }
    2299                 :             : 
    2300                 :             :     /*
    2301                 :             :      * Check result rowcount; if there's one row, assign procedure's output
    2302                 :             :      * values back to the appropriate variables.
    2303                 :             :      */
    2304         [ +  + ]:          58 :     if (SPI_processed == 1)
    2305                 :             :     {
    2306                 :          38 :         SPITupleTable *tuptab = SPI_tuptable;
    2307                 :             : 
    2308         [ -  + ]:          38 :         if (!stmt->is_call)
    2309         [ #  # ]:           0 :             elog(ERROR, "DO statement returned a row");
    2310                 :             : 
    2311                 :          38 :         exec_move_row(estate, stmt->target, tuptab->vals[0], tuptab->tupdesc);
    2312                 :             :     }
    2313         [ -  + ]:          20 :     else if (SPI_processed > 1)
    2314         [ #  # ]:           0 :         elog(ERROR, "procedure call returned more than one row");
    2315                 :             : 
    2316                 :          58 :     exec_eval_cleanup(estate);
    2317                 :          58 :     SPI_freetuptable(SPI_tuptable);
    2318                 :             : 
    2319                 :          58 :     return PLPGSQL_RC_OK;
    2320                 :             : }
    2321                 :             : 
    2322                 :             : /*
    2323                 :             :  * We construct a DTYPE_ROW datum representing the plpgsql variables
    2324                 :             :  * associated with the procedure's output arguments.  Then we can use
    2325                 :             :  * exec_move_row() to do the assignments.
    2326                 :             :  */
    2327                 :             : static PLpgSQL_variable *
    2328                 :          50 : make_callstmt_target(PLpgSQL_execstate *estate, PLpgSQL_expr *expr)
    2329                 :             : {
    2330                 :             :     CachedPlan *cplan;
    2331                 :             :     PlannedStmt *pstmt;
    2332                 :             :     CallStmt   *stmt;
    2333                 :             :     FuncExpr   *funcexpr;
    2334                 :             :     HeapTuple   func_tuple;
    2335                 :             :     Oid        *argtypes;
    2336                 :             :     char      **argnames;
    2337                 :             :     char       *argmodes;
    2338                 :             :     int         numargs;
    2339                 :             :     MemoryContext oldcontext;
    2340                 :             :     PLpgSQL_row *row;
    2341                 :             :     int         nfields;
    2342                 :             :     int         i;
    2343                 :             : 
    2344                 :             :     /* Use eval_mcontext for any cruft accumulated here */
    2345                 :          50 :     oldcontext = MemoryContextSwitchTo(get_eval_mcontext(estate));
    2346                 :             : 
    2347                 :             :     /*
    2348                 :             :      * Get the parsed CallStmt, and look up the called procedure.  We use
    2349                 :             :      * SPI_plan_get_cached_plan to cover the edge case where expr->plan is
    2350                 :             :      * already stale and needs to be updated.
    2351                 :             :      */
    2352                 :          50 :     cplan = SPI_plan_get_cached_plan(expr->plan);
    2353   [ +  -  -  + ]:          50 :     if (cplan == NULL || list_length(cplan->stmt_list) != 1)
    2354         [ #  # ]:           0 :         elog(ERROR, "query for CALL statement is not a CallStmt");
    2355                 :          50 :     pstmt = linitial_node(PlannedStmt, cplan->stmt_list);
    2356                 :          50 :     stmt = (CallStmt *) pstmt->utilityStmt;
    2357   [ +  -  -  + ]:          50 :     if (stmt == NULL || !IsA(stmt, CallStmt))
    2358         [ #  # ]:           0 :         elog(ERROR, "query for CALL statement is not a CallStmt");
    2359                 :             : 
    2360                 :          50 :     funcexpr = stmt->funcexpr;
    2361                 :             : 
    2362                 :          50 :     func_tuple = SearchSysCache1(PROCOID,
    2363                 :             :                                  ObjectIdGetDatum(funcexpr->funcid));
    2364         [ -  + ]:          50 :     if (!HeapTupleIsValid(func_tuple))
    2365         [ #  # ]:           0 :         elog(ERROR, "cache lookup failed for function %u",
    2366                 :             :              funcexpr->funcid);
    2367                 :             : 
    2368                 :             :     /*
    2369                 :             :      * Get the argument names and modes, so that we can deliver on-point error
    2370                 :             :      * messages when something is wrong.
    2371                 :             :      */
    2372                 :          50 :     numargs = get_func_arg_info(func_tuple, &argtypes, &argnames, &argmodes);
    2373                 :             : 
    2374                 :          50 :     ReleaseSysCache(func_tuple);
    2375                 :             : 
    2376                 :             :     /*
    2377                 :             :      * Begin constructing row Datum; keep it in fn_cxt so it's adequately
    2378                 :             :      * long-lived.
    2379                 :             :      */
    2380                 :          50 :     MemoryContextSwitchTo(estate->func->fn_cxt);
    2381                 :             : 
    2382                 :          50 :     row = palloc0_object(PLpgSQL_row);
    2383                 :          50 :     row->dtype = PLPGSQL_DTYPE_ROW;
    2384                 :          50 :     row->refname = "(unnamed row)";
    2385                 :          50 :     row->lineno = -1;
    2386                 :          50 :     row->varnos = palloc_array(int, numargs);
    2387                 :             : 
    2388                 :          50 :     MemoryContextSwitchTo(get_eval_mcontext(estate));
    2389                 :             : 
    2390                 :             :     /*
    2391                 :             :      * Examine procedure's argument list.  Each output arg position should be
    2392                 :             :      * an unadorned plpgsql variable (Datum), which we can insert into the row
    2393                 :             :      * Datum.
    2394                 :             :      */
    2395                 :          50 :     nfields = 0;
    2396         [ +  + ]:         152 :     for (i = 0; i < numargs; i++)
    2397                 :             :     {
    2398         [ +  + ]:         107 :         if (argmodes &&
    2399         [ +  + ]:          89 :             (argmodes[i] == PROARGMODE_INOUT ||
    2400         [ +  + ]:          46 :              argmodes[i] == PROARGMODE_OUT))
    2401                 :             :         {
    2402                 :          57 :             Node       *n = list_nth(stmt->outargs, nfields);
    2403                 :             : 
    2404         [ +  + ]:          57 :             if (IsA(n, Param))
    2405                 :             :             {
    2406                 :          53 :                 Param      *param = (Param *) n;
    2407                 :             :                 int         dno;
    2408                 :             : 
    2409                 :             :                 /* paramid is offset by 1 (see make_datum_param()) */
    2410                 :          53 :                 dno = param->paramid - 1;
    2411                 :             :                 /* must check assignability now, because grammar can't */
    2412                 :          53 :                 exec_check_assignable(estate, dno);
    2413                 :          52 :                 row->varnos[nfields++] = dno;
    2414                 :             :             }
    2415                 :             :             else
    2416                 :             :             {
    2417                 :             :                 /* report error using parameter name, if available */
    2418   [ +  -  +  -  :           4 :                 if (argnames && argnames[i] && argnames[i][0])
                   +  - ]
    2419         [ +  - ]:           4 :                     ereport(ERROR,
    2420                 :             :                             (errcode(ERRCODE_SYNTAX_ERROR),
    2421                 :             :                              errmsg("procedure parameter \"%s\" is an output parameter but corresponding argument is not writable",
    2422                 :             :                                     argnames[i])));
    2423                 :             :                 else
    2424         [ #  # ]:           0 :                     ereport(ERROR,
    2425                 :             :                             (errcode(ERRCODE_SYNTAX_ERROR),
    2426                 :             :                              errmsg("procedure parameter %d is an output parameter but corresponding argument is not writable",
    2427                 :             :                                     i + 1)));
    2428                 :             :             }
    2429                 :             :         }
    2430                 :             :     }
    2431                 :             : 
    2432                 :             :     Assert(nfields == list_length(stmt->outargs));
    2433                 :             : 
    2434                 :          45 :     row->nfields = nfields;
    2435                 :             : 
    2436                 :          45 :     ReleaseCachedPlan(cplan, CurrentResourceOwner);
    2437                 :             : 
    2438                 :          45 :     MemoryContextSwitchTo(oldcontext);
    2439                 :             : 
    2440                 :          45 :     return (PLpgSQL_variable *) row;
    2441                 :             : }
    2442                 :             : 
    2443                 :             : /* ----------
    2444                 :             :  * exec_stmt_getdiag                    Put internal PG information into
    2445                 :             :  *                                      specified variables.
    2446                 :             :  * ----------
    2447                 :             :  */
    2448                 :             : static int
    2449                 :         101 : exec_stmt_getdiag(PLpgSQL_execstate *estate, PLpgSQL_stmt_getdiag *stmt)
    2450                 :             : {
    2451                 :             :     ListCell   *lc;
    2452                 :             : 
    2453                 :             :     /*
    2454                 :             :      * GET STACKED DIAGNOSTICS is only valid inside an exception handler.
    2455                 :             :      *
    2456                 :             :      * Note: we trust the grammar to have disallowed the relevant item kinds
    2457                 :             :      * if not is_stacked, otherwise we'd dump core below.
    2458                 :             :      */
    2459   [ +  +  +  + ]:         101 :     if (stmt->is_stacked && estate->cur_error == NULL)
    2460         [ +  - ]:           4 :         ereport(ERROR,
    2461                 :             :                 (errcode(ERRCODE_STACKED_DIAGNOSTICS_ACCESSED_WITHOUT_ACTIVE_HANDLER),
    2462                 :             :                  errmsg("GET STACKED DIAGNOSTICS cannot be used outside an exception handler")));
    2463                 :             : 
    2464   [ +  -  +  +  :         234 :     foreach(lc, stmt->diag_items)
                   +  + ]
    2465                 :             :     {
    2466                 :         137 :         PLpgSQL_diag_item *diag_item = (PLpgSQL_diag_item *) lfirst(lc);
    2467                 :         137 :         PLpgSQL_datum *var = estate->datums[diag_item->target];
    2468                 :             : 
    2469   [ +  +  +  +  :         137 :         switch (diag_item->kind)
          +  +  +  +  +  
             +  +  +  +  
                      - ]
    2470                 :             :         {
    2471                 :          44 :             case PLPGSQL_GETDIAG_ROW_COUNT:
    2472                 :          44 :                 exec_assign_value(estate, var,
    2473                 :             :                                   UInt64GetDatum(estate->eval_processed),
    2474                 :             :                                   false, INT8OID, -1);
    2475                 :          44 :                 break;
    2476                 :             : 
    2477                 :           8 :             case PLPGSQL_GETDIAG_ROUTINE_OID:
    2478                 :           8 :                 exec_assign_value(estate, var,
    2479                 :           8 :                                   ObjectIdGetDatum(estate->func->fn_oid),
    2480                 :             :                                   false, OIDOID, -1);
    2481                 :           8 :                 break;
    2482                 :             : 
    2483                 :           4 :             case PLPGSQL_GETDIAG_ERROR_CONTEXT:
    2484                 :           4 :                 exec_assign_c_string(estate, var,
    2485                 :           4 :                                      estate->cur_error->context);
    2486                 :           4 :                 break;
    2487                 :             : 
    2488                 :           5 :             case PLPGSQL_GETDIAG_ERROR_DETAIL:
    2489                 :           5 :                 exec_assign_c_string(estate, var,
    2490                 :           5 :                                      estate->cur_error->detail);
    2491                 :           5 :                 break;
    2492                 :             : 
    2493                 :           5 :             case PLPGSQL_GETDIAG_ERROR_HINT:
    2494                 :           5 :                 exec_assign_c_string(estate, var,
    2495                 :           5 :                                      estate->cur_error->hint);
    2496                 :           5 :                 break;
    2497                 :             : 
    2498                 :           5 :             case PLPGSQL_GETDIAG_RETURNED_SQLSTATE:
    2499                 :           5 :                 exec_assign_c_string(estate, var,
    2500                 :           5 :                                      unpack_sql_state(estate->cur_error->sqlerrcode));
    2501                 :           5 :                 break;
    2502                 :             : 
    2503                 :           5 :             case PLPGSQL_GETDIAG_COLUMN_NAME:
    2504                 :           5 :                 exec_assign_c_string(estate, var,
    2505                 :           5 :                                      estate->cur_error->column_name);
    2506                 :           5 :                 break;
    2507                 :             : 
    2508                 :           5 :             case PLPGSQL_GETDIAG_CONSTRAINT_NAME:
    2509                 :           5 :                 exec_assign_c_string(estate, var,
    2510                 :           5 :                                      estate->cur_error->constraint_name);
    2511                 :           5 :                 break;
    2512                 :             : 
    2513                 :           5 :             case PLPGSQL_GETDIAG_DATATYPE_NAME:
    2514                 :           5 :                 exec_assign_c_string(estate, var,
    2515                 :           5 :                                      estate->cur_error->datatype_name);
    2516                 :           5 :                 break;
    2517                 :             : 
    2518                 :           9 :             case PLPGSQL_GETDIAG_MESSAGE_TEXT:
    2519                 :           9 :                 exec_assign_c_string(estate, var,
    2520                 :           9 :                                      estate->cur_error->message);
    2521                 :           9 :                 break;
    2522                 :             : 
    2523                 :           5 :             case PLPGSQL_GETDIAG_TABLE_NAME:
    2524                 :           5 :                 exec_assign_c_string(estate, var,
    2525                 :           5 :                                      estate->cur_error->table_name);
    2526                 :           5 :                 break;
    2527                 :             : 
    2528                 :           5 :             case PLPGSQL_GETDIAG_SCHEMA_NAME:
    2529                 :           5 :                 exec_assign_c_string(estate, var,
    2530                 :           5 :                                      estate->cur_error->schema_name);
    2531                 :           5 :                 break;
    2532                 :             : 
    2533                 :          32 :             case PLPGSQL_GETDIAG_CONTEXT:
    2534                 :             :                 {
    2535                 :             :                     char       *contextstackstr;
    2536                 :             :                     MemoryContext oldcontext;
    2537                 :             : 
    2538                 :             :                     /* Use eval_mcontext for short-lived string */
    2539                 :          32 :                     oldcontext = MemoryContextSwitchTo(get_eval_mcontext(estate));
    2540                 :          32 :                     contextstackstr = GetErrorContextStack();
    2541                 :          32 :                     MemoryContextSwitchTo(oldcontext);
    2542                 :             : 
    2543                 :          32 :                     exec_assign_c_string(estate, var, contextstackstr);
    2544                 :             :                 }
    2545                 :          32 :                 break;
    2546                 :             : 
    2547                 :           0 :             default:
    2548         [ #  # ]:           0 :                 elog(ERROR, "unrecognized diagnostic item kind: %d",
    2549                 :             :                      diag_item->kind);
    2550                 :             :         }
    2551                 :             :     }
    2552                 :             : 
    2553                 :          97 :     exec_eval_cleanup(estate);
    2554                 :             : 
    2555                 :          97 :     return PLPGSQL_RC_OK;
    2556                 :             : }
    2557                 :             : 
    2558                 :             : /* ----------
    2559                 :             :  * exec_stmt_if             Evaluate a bool expression and
    2560                 :             :  *                  execute the true or false body
    2561                 :             :  *                  conditionally.
    2562                 :             :  * ----------
    2563                 :             :  */
    2564                 :             : static int
    2565                 :       77472 : exec_stmt_if(PLpgSQL_execstate *estate, PLpgSQL_stmt_if *stmt)
    2566                 :             : {
    2567                 :             :     bool        value;
    2568                 :             :     bool        isnull;
    2569                 :             :     ListCell   *lc;
    2570                 :             : 
    2571                 :       77472 :     value = exec_eval_boolean(estate, stmt->cond, &isnull);
    2572                 :       77472 :     exec_eval_cleanup(estate);
    2573   [ +  +  +  + ]:       77472 :     if (!isnull && value)
    2574                 :       14604 :         return exec_stmts(estate, stmt->then_body);
    2575                 :             : 
    2576   [ +  +  +  +  :       63184 :     foreach(lc, stmt->elsif_list)
                   +  + ]
    2577                 :             :     {
    2578                 :         825 :         PLpgSQL_if_elsif *elif = (PLpgSQL_if_elsif *) lfirst(lc);
    2579                 :             : 
    2580                 :         825 :         value = exec_eval_boolean(estate, elif->cond, &isnull);
    2581                 :         825 :         exec_eval_cleanup(estate);
    2582   [ +  +  +  + ]:         825 :         if (!isnull && value)
    2583                 :         509 :             return exec_stmts(estate, elif->stmts);
    2584                 :             :     }
    2585                 :             : 
    2586                 :       62359 :     return exec_stmts(estate, stmt->else_body);
    2587                 :             : }
    2588                 :             : 
    2589                 :             : 
    2590                 :             : /*-----------
    2591                 :             :  * exec_stmt_case
    2592                 :             :  *-----------
    2593                 :             :  */
    2594                 :             : static int
    2595                 :         154 : exec_stmt_case(PLpgSQL_execstate *estate, PLpgSQL_stmt_case *stmt)
    2596                 :             : {
    2597                 :         154 :     PLpgSQL_var *t_var = NULL;
    2598                 :             :     bool        isnull;
    2599                 :             :     ListCell   *l;
    2600                 :             : 
    2601         [ +  + ]:         154 :     if (stmt->t_expr != NULL)
    2602                 :             :     {
    2603                 :             :         /* simple case */
    2604                 :             :         Datum       t_val;
    2605                 :             :         Oid         t_typoid;
    2606                 :             :         int32       t_typmod;
    2607                 :             : 
    2608                 :         150 :         t_val = exec_eval_expr(estate, stmt->t_expr,
    2609                 :             :                                &isnull, &t_typoid, &t_typmod);
    2610                 :             : 
    2611                 :         150 :         t_var = (PLpgSQL_var *) estate->datums[stmt->t_varno];
    2612                 :             : 
    2613                 :             :         /*
    2614                 :             :          * When expected datatype is different from real, change it. Note that
    2615                 :             :          * what we're modifying here is an execution copy of the datum, so
    2616                 :             :          * this doesn't affect the originally stored function parse tree. (In
    2617                 :             :          * theory, if the expression datatype keeps changing during execution,
    2618                 :             :          * this could cause a function-lifespan memory leak.  Doesn't seem
    2619                 :             :          * worth worrying about though.)
    2620                 :             :          */
    2621         [ +  + ]:         150 :         if (t_var->datatype->typoid != t_typoid ||
    2622         [ -  + ]:         113 :             t_var->datatype->atttypmod != t_typmod)
    2623                 :          37 :             t_var->datatype = plpgsql_build_datatype(t_typoid,
    2624                 :             :                                                      t_typmod,
    2625                 :          37 :                                                      estate->func->fn_input_collation,
    2626                 :             :                                                      NULL);
    2627                 :             : 
    2628                 :             :         /* now we can assign to the variable */
    2629                 :         150 :         exec_assign_value(estate,
    2630                 :             :                           (PLpgSQL_datum *) t_var,
    2631                 :             :                           t_val,
    2632                 :             :                           isnull,
    2633                 :             :                           t_typoid,
    2634                 :             :                           t_typmod);
    2635                 :             : 
    2636                 :         150 :         exec_eval_cleanup(estate);
    2637                 :             :     }
    2638                 :             : 
    2639                 :             :     /* Now search for a successful WHEN clause */
    2640   [ +  -  +  +  :         308 :     foreach(l, stmt->case_when_list)
                   +  + ]
    2641                 :             :     {
    2642                 :         303 :         PLpgSQL_case_when *cwt = (PLpgSQL_case_when *) lfirst(l);
    2643                 :             :         bool        value;
    2644                 :             : 
    2645                 :         303 :         value = exec_eval_boolean(estate, cwt->expr, &isnull);
    2646                 :         303 :         exec_eval_cleanup(estate);
    2647   [ +  -  +  + ]:         303 :         if (!isnull && value)
    2648                 :             :         {
    2649                 :             :             /* Found it */
    2650                 :             : 
    2651                 :             :             /* We can now discard any value we had for the temp variable */
    2652         [ +  + ]:         149 :             if (t_var != NULL)
    2653                 :         147 :                 assign_simple_var(estate, t_var, (Datum) 0, true, false);
    2654                 :             : 
    2655                 :             :             /* Evaluate the statement(s), and we're done */
    2656                 :         149 :             return exec_stmts(estate, cwt->stmts);
    2657                 :             :         }
    2658                 :             :     }
    2659                 :             : 
    2660                 :             :     /* We can now discard any value we had for the temp variable */
    2661         [ +  + ]:           5 :     if (t_var != NULL)
    2662                 :           3 :         assign_simple_var(estate, t_var, (Datum) 0, true, false);
    2663                 :             : 
    2664                 :             :     /* SQL2003 mandates this error if there was no ELSE clause */
    2665         [ +  + ]:           5 :     if (!stmt->have_else)
    2666         [ +  - ]:           3 :         ereport(ERROR,
    2667                 :             :                 (errcode(ERRCODE_CASE_NOT_FOUND),
    2668                 :             :                  errmsg("case not found"),
    2669                 :             :                  errhint("CASE statement is missing ELSE part.")));
    2670                 :             : 
    2671                 :             :     /* Evaluate the ELSE statements, and we're done */
    2672                 :           2 :     return exec_stmts(estate, stmt->else_stmts);
    2673                 :             : }
    2674                 :             : 
    2675                 :             : 
    2676                 :             : /* ----------
    2677                 :             :  * exec_stmt_loop           Loop over statements until
    2678                 :             :  *                  an exit occurs.
    2679                 :             :  * ----------
    2680                 :             :  */
    2681                 :             : static int
    2682                 :          62 : exec_stmt_loop(PLpgSQL_execstate *estate, PLpgSQL_stmt_loop *stmt)
    2683                 :             : {
    2684                 :          62 :     int         rc = PLPGSQL_RC_OK;
    2685                 :             : 
    2686                 :             :     for (;;)
    2687                 :             :     {
    2688                 :        6892 :         rc = exec_stmts(estate, stmt->body);
    2689                 :             : 
    2690   [ -  +  +  +  :        6892 :         LOOP_RC_PROCESSING(stmt->label, break);
          +  +  +  +  +  
          -  +  +  +  +  
             +  +  +  - ]
    2691                 :             :     }
    2692                 :             : 
    2693                 :          62 :     return rc;
    2694                 :             : }
    2695                 :             : 
    2696                 :             : 
    2697                 :             : /* ----------
    2698                 :             :  * exec_stmt_while          Loop over statements as long
    2699                 :             :  *                  as an expression evaluates to
    2700                 :             :  *                  true or an exit occurs.
    2701                 :             :  * ----------
    2702                 :             :  */
    2703                 :             : static int
    2704                 :         286 : exec_stmt_while(PLpgSQL_execstate *estate, PLpgSQL_stmt_while *stmt)
    2705                 :             : {
    2706                 :         286 :     int         rc = PLPGSQL_RC_OK;
    2707                 :             : 
    2708                 :             :     for (;;)
    2709                 :        2098 :     {
    2710                 :             :         bool        value;
    2711                 :             :         bool        isnull;
    2712                 :             : 
    2713                 :        2384 :         value = exec_eval_boolean(estate, stmt->cond, &isnull);
    2714                 :        2384 :         exec_eval_cleanup(estate);
    2715                 :             : 
    2716   [ +  -  +  + ]:        2384 :         if (isnull || !value)
    2717                 :             :             break;
    2718                 :             : 
    2719                 :        2108 :         rc = exec_stmts(estate, stmt->body);
    2720                 :             : 
    2721   [ +  +  +  +  :        2108 :         LOOP_RC_PROCESSING(stmt->label, break);
          +  +  +  +  +  
          +  +  +  +  +  
             +  -  +  + ]
    2722                 :             :     }
    2723                 :             : 
    2724                 :         286 :     return rc;
    2725                 :             : }
    2726                 :             : 
    2727                 :             : 
    2728                 :             : /* ----------
    2729                 :             :  * exec_stmt_fori           Iterate an integer variable
    2730                 :             :  *                  from a lower to an upper value
    2731                 :             :  *                  incrementing or decrementing by the BY value
    2732                 :             :  * ----------
    2733                 :             :  */
    2734                 :             : static int
    2735                 :        2976 : exec_stmt_fori(PLpgSQL_execstate *estate, PLpgSQL_stmt_fori *stmt)
    2736                 :             : {
    2737                 :             :     PLpgSQL_var *var;
    2738                 :             :     Datum       value;
    2739                 :             :     bool        isnull;
    2740                 :             :     Oid         valtype;
    2741                 :             :     int32       valtypmod;
    2742                 :             :     int32       loop_value;
    2743                 :             :     int32       end_value;
    2744                 :             :     int32       step_value;
    2745                 :        2976 :     bool        found = false;
    2746                 :        2976 :     int         rc = PLPGSQL_RC_OK;
    2747                 :             : 
    2748                 :        2976 :     var = (PLpgSQL_var *) (estate->datums[stmt->var->dno]);
    2749                 :             : 
    2750                 :             :     /*
    2751                 :             :      * Get the value of the lower bound
    2752                 :             :      */
    2753                 :        2976 :     value = exec_eval_expr(estate, stmt->lower,
    2754                 :             :                            &isnull, &valtype, &valtypmod);
    2755                 :        2976 :     value = exec_cast_value(estate, value, &isnull,
    2756                 :             :                             valtype, valtypmod,
    2757                 :        2976 :                             var->datatype->typoid,
    2758                 :        2976 :                             var->datatype->atttypmod);
    2759         [ -  + ]:        2976 :     if (isnull)
    2760         [ #  # ]:           0 :         ereport(ERROR,
    2761                 :             :                 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
    2762                 :             :                  errmsg("lower bound of FOR loop cannot be null")));
    2763                 :        2976 :     loop_value = DatumGetInt32(value);
    2764                 :        2976 :     exec_eval_cleanup(estate);
    2765                 :             : 
    2766                 :             :     /*
    2767                 :             :      * Get the value of the upper bound
    2768                 :             :      */
    2769                 :        2976 :     value = exec_eval_expr(estate, stmt->upper,
    2770                 :             :                            &isnull, &valtype, &valtypmod);
    2771                 :        2976 :     value = exec_cast_value(estate, value, &isnull,
    2772                 :             :                             valtype, valtypmod,
    2773                 :        2976 :                             var->datatype->typoid,
    2774                 :        2976 :                             var->datatype->atttypmod);
    2775         [ -  + ]:        2976 :     if (isnull)
    2776         [ #  # ]:           0 :         ereport(ERROR,
    2777                 :             :                 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
    2778                 :             :                  errmsg("upper bound of FOR loop cannot be null")));
    2779                 :        2976 :     end_value = DatumGetInt32(value);
    2780                 :        2976 :     exec_eval_cleanup(estate);
    2781                 :             : 
    2782                 :             :     /*
    2783                 :             :      * Get the step value
    2784                 :             :      */
    2785         [ +  + ]:        2976 :     if (stmt->step)
    2786                 :             :     {
    2787                 :           9 :         value = exec_eval_expr(estate, stmt->step,
    2788                 :             :                                &isnull, &valtype, &valtypmod);
    2789                 :           9 :         value = exec_cast_value(estate, value, &isnull,
    2790                 :             :                                 valtype, valtypmod,
    2791                 :           9 :                                 var->datatype->typoid,
    2792                 :           9 :                                 var->datatype->atttypmod);
    2793         [ -  + ]:           9 :         if (isnull)
    2794         [ #  # ]:           0 :             ereport(ERROR,
    2795                 :             :                     (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
    2796                 :             :                      errmsg("BY value of FOR loop cannot be null")));
    2797                 :           9 :         step_value = DatumGetInt32(value);
    2798                 :           9 :         exec_eval_cleanup(estate);
    2799         [ +  + ]:           9 :         if (step_value <= 0)
    2800         [ +  - ]:           3 :             ereport(ERROR,
    2801                 :             :                     (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
    2802                 :             :                      errmsg("BY value of FOR loop must be greater than zero")));
    2803                 :             :     }
    2804                 :             :     else
    2805                 :        2967 :         step_value = 1;
    2806                 :             : 
    2807                 :             :     /*
    2808                 :             :      * Now do the loop
    2809                 :             :      */
    2810                 :             :     for (;;)
    2811                 :             :     {
    2812                 :             :         /*
    2813                 :             :          * Check against upper bound
    2814                 :             :          */
    2815         [ +  + ]:       33992 :         if (stmt->reverse)
    2816                 :             :         {
    2817         [ +  + ]:           8 :             if (loop_value < end_value)
    2818                 :           1 :                 break;
    2819                 :             :         }
    2820                 :             :         else
    2821                 :             :         {
    2822         [ +  + ]:       33984 :             if (loop_value > end_value)
    2823                 :        2942 :                 break;
    2824                 :             :         }
    2825                 :             : 
    2826                 :       31049 :         found = true;           /* looped at least once */
    2827                 :             : 
    2828                 :             :         /*
    2829                 :             :          * Assign current value to loop var
    2830                 :             :          */
    2831                 :       31049 :         assign_simple_var(estate, var, Int32GetDatum(loop_value), false, false);
    2832                 :             : 
    2833                 :             :         /*
    2834                 :             :          * Execute the statements
    2835                 :             :          */
    2836                 :       31049 :         rc = exec_stmts(estate, stmt->body);
    2837                 :             : 
    2838   [ +  +  +  +  :       31033 :         LOOP_RC_PROCESSING(stmt->label, break);
          +  +  +  -  +  
          -  +  +  +  +  
             +  -  +  + ]
    2839                 :             : 
    2840                 :             :         /*
    2841                 :             :          * Increase/decrease loop value, unless it would overflow, in which
    2842                 :             :          * case exit the loop.
    2843                 :             :          */
    2844         [ +  + ]:       31021 :         if (stmt->reverse)
    2845                 :             :         {
    2846         [ +  + ]:           7 :             if (loop_value < (PG_INT32_MIN + step_value))
    2847                 :           1 :                 break;
    2848                 :           6 :             loop_value -= step_value;
    2849                 :             :         }
    2850                 :             :         else
    2851                 :             :         {
    2852         [ +  + ]:       31014 :             if (loop_value > (PG_INT32_MAX - step_value))
    2853                 :           1 :                 break;
    2854                 :       31013 :             loop_value += step_value;
    2855                 :             :         }
    2856                 :             :     }
    2857                 :             : 
    2858                 :             :     /*
    2859                 :             :      * Set the FOUND variable to indicate the result of executing the loop
    2860                 :             :      * (namely, whether we looped one or more times). This must be set here so
    2861                 :             :      * that it does not interfere with the value of the FOUND variable inside
    2862                 :             :      * the loop processing itself.
    2863                 :             :      */
    2864                 :        2957 :     exec_set_found(estate, found);
    2865                 :             : 
    2866                 :        2957 :     return rc;
    2867                 :             : }
    2868                 :             : 
    2869                 :             : 
    2870                 :             : /* ----------
    2871                 :             :  * exec_stmt_fors           Execute a query, assign each
    2872                 :             :  *                  tuple to a record or row and
    2873                 :             :  *                  execute a group of statements
    2874                 :             :  *                  for it.
    2875                 :             :  * ----------
    2876                 :             :  */
    2877                 :             : static int
    2878                 :        1668 : exec_stmt_fors(PLpgSQL_execstate *estate, PLpgSQL_stmt_fors *stmt)
    2879                 :             : {
    2880                 :             :     Portal      portal;
    2881                 :             :     int         rc;
    2882                 :             : 
    2883                 :             :     /*
    2884                 :             :      * Open the implicit cursor for the statement using exec_run_select
    2885                 :             :      */
    2886                 :        1668 :     exec_run_select(estate, stmt->query, 0, &portal);
    2887                 :             : 
    2888                 :             :     /*
    2889                 :             :      * Execute the loop
    2890                 :             :      */
    2891                 :        1660 :     rc = exec_for_query(estate, (PLpgSQL_stmt_forq *) stmt, portal, true);
    2892                 :             : 
    2893                 :             :     /*
    2894                 :             :      * Close the implicit cursor
    2895                 :             :      */
    2896                 :        1624 :     SPI_cursor_close(portal);
    2897                 :             : 
    2898                 :        1624 :     return rc;
    2899                 :             : }
    2900                 :             : 
    2901                 :             : 
    2902                 :             : /* ----------
    2903                 :             :  * exec_stmt_forc           Execute a loop for each row from a cursor.
    2904                 :             :  * ----------
    2905                 :             :  */
    2906                 :             : static int
    2907                 :          69 : exec_stmt_forc(PLpgSQL_execstate *estate, PLpgSQL_stmt_forc *stmt)
    2908                 :             : {
    2909                 :             :     PLpgSQL_var *curvar;
    2910                 :          69 :     MemoryContext stmt_mcontext = NULL;
    2911                 :          69 :     char       *curname = NULL;
    2912                 :             :     PLpgSQL_expr *query;
    2913                 :             :     ParamListInfo paramLI;
    2914                 :             :     Portal      portal;
    2915                 :             :     int         rc;
    2916                 :             : 
    2917                 :             :     /* ----------
    2918                 :             :      * Get the cursor variable and if it has an assigned name, check
    2919                 :             :      * that it's not in use currently.
    2920                 :             :      * ----------
    2921                 :             :      */
    2922                 :          69 :     curvar = (PLpgSQL_var *) (estate->datums[stmt->curvar]);
    2923         [ +  + ]:          69 :     if (!curvar->isnull)
    2924                 :             :     {
    2925                 :             :         MemoryContext oldcontext;
    2926                 :             : 
    2927                 :             :         /* We only need stmt_mcontext to hold the cursor name string */
    2928                 :          16 :         stmt_mcontext = get_stmt_mcontext(estate);
    2929                 :          16 :         oldcontext = MemoryContextSwitchTo(stmt_mcontext);
    2930                 :          16 :         curname = TextDatumGetCString(curvar->value);
    2931                 :          16 :         MemoryContextSwitchTo(oldcontext);
    2932                 :             : 
    2933         [ -  + ]:          16 :         if (SPI_cursor_find(curname) != NULL)
    2934         [ #  # ]:           0 :             ereport(ERROR,
    2935                 :             :                     (errcode(ERRCODE_DUPLICATE_CURSOR),
    2936                 :             :                      errmsg("cursor \"%s\" already in use", curname)));
    2937                 :             :     }
    2938                 :             : 
    2939                 :             :     /* ----------
    2940                 :             :      * Open the cursor just like an OPEN command
    2941                 :             :      *
    2942                 :             :      * Note: parser should already have checked that statement supplies
    2943                 :             :      * args iff cursor needs them, but we check again to be safe.
    2944                 :             :      * ----------
    2945                 :             :      */
    2946         [ +  + ]:          69 :     if (stmt->argquery != NULL)
    2947                 :             :     {
    2948                 :             :         /* ----------
    2949                 :             :          * OPEN CURSOR with args.  We fake a SELECT ... INTO ...
    2950                 :             :          * statement to evaluate the args and put 'em into the
    2951                 :             :          * internal row.
    2952                 :             :          * ----------
    2953                 :             :          */
    2954                 :             :         PLpgSQL_stmt_execsql set_args;
    2955                 :             : 
    2956         [ -  + ]:           8 :         if (curvar->cursor_explicit_argrow < 0)
    2957         [ #  # ]:           0 :             ereport(ERROR,
    2958                 :             :                     (errcode(ERRCODE_SYNTAX_ERROR),
    2959                 :             :                      errmsg("arguments given for cursor without arguments")));
    2960                 :             : 
    2961                 :           8 :         memset(&set_args, 0, sizeof(set_args));
    2962                 :           8 :         set_args.cmd_type = PLPGSQL_STMT_EXECSQL;
    2963                 :           8 :         set_args.lineno = stmt->lineno;
    2964                 :           8 :         set_args.sqlstmt = stmt->argquery;
    2965                 :           8 :         set_args.into = true;
    2966                 :             :         /* XXX historically this has not been STRICT */
    2967                 :           8 :         set_args.target = (PLpgSQL_variable *)
    2968                 :           8 :             (estate->datums[curvar->cursor_explicit_argrow]);
    2969                 :             : 
    2970         [ -  + ]:           8 :         if (exec_stmt_execsql(estate, &set_args) != PLPGSQL_RC_OK)
    2971         [ #  # ]:           0 :             elog(ERROR, "open cursor failed during argument processing");
    2972                 :             :     }
    2973                 :             :     else
    2974                 :             :     {
    2975         [ -  + ]:          61 :         if (curvar->cursor_explicit_argrow >= 0)
    2976         [ #  # ]:           0 :             ereport(ERROR,
    2977                 :             :                     (errcode(ERRCODE_SYNTAX_ERROR),
    2978                 :             :                      errmsg("arguments required for cursor")));
    2979                 :             :     }
    2980                 :             : 
    2981                 :          69 :     query = curvar->cursor_explicit_expr;
    2982                 :             :     Assert(query);
    2983                 :             : 
    2984         [ +  + ]:          69 :     if (query->plan == NULL)
    2985                 :          21 :         exec_prepare_plan(estate, query, curvar->cursor_options);
    2986                 :             : 
    2987                 :             :     /*
    2988                 :             :      * Set up ParamListInfo for this query
    2989                 :             :      */
    2990                 :          69 :     paramLI = setup_param_list(estate, query);
    2991                 :             : 
    2992                 :             :     /*
    2993                 :             :      * Open the cursor (the paramlist will get copied into the portal)
    2994                 :             :      */
    2995                 :          69 :     portal = SPI_cursor_open_with_paramlist(curname, query->plan,
    2996                 :             :                                             paramLI,
    2997                 :          69 :                                             estate->readonly_func);
    2998         [ -  + ]:          69 :     if (portal == NULL)
    2999         [ #  # ]:           0 :         elog(ERROR, "could not open cursor: %s",
    3000                 :             :              SPI_result_code_string(SPI_result));
    3001                 :             : 
    3002                 :             :     /*
    3003                 :             :      * If cursor variable was NULL, store the generated portal name in it,
    3004                 :             :      * after verifying it's okay to assign to.
    3005                 :             :      */
    3006         [ +  + ]:          69 :     if (curname == NULL)
    3007                 :             :     {
    3008                 :          53 :         exec_check_assignable(estate, stmt->curvar);
    3009                 :          53 :         assign_text_var(estate, curvar, portal->name);
    3010                 :             :     }
    3011                 :             : 
    3012                 :             :     /*
    3013                 :             :      * Clean up before entering exec_for_query
    3014                 :             :      */
    3015                 :          69 :     exec_eval_cleanup(estate);
    3016         [ +  + ]:          69 :     if (stmt_mcontext)
    3017                 :          16 :         MemoryContextReset(stmt_mcontext);
    3018                 :             : 
    3019                 :             :     /*
    3020                 :             :      * Execute the loop.  We can't prefetch because the cursor is accessible
    3021                 :             :      * to the user, for instance via UPDATE WHERE CURRENT OF within the loop.
    3022                 :             :      */
    3023                 :          69 :     rc = exec_for_query(estate, (PLpgSQL_stmt_forq *) stmt, portal, false);
    3024                 :             : 
    3025                 :             :     /* ----------
    3026                 :             :      * Close portal, and restore cursor variable if it was initially NULL.
    3027                 :             :      * ----------
    3028                 :             :      */
    3029                 :          69 :     SPI_cursor_close(portal);
    3030                 :             : 
    3031         [ +  + ]:          69 :     if (curname == NULL)
    3032                 :          53 :         assign_simple_var(estate, curvar, (Datum) 0, true, false);
    3033                 :             : 
    3034                 :          69 :     return rc;
    3035                 :             : }
    3036                 :             : 
    3037                 :             : 
    3038                 :             : /* ----------
    3039                 :             :  * exec_stmt_foreach_a          Loop over elements or slices of an array
    3040                 :             :  *
    3041                 :             :  * When looping over elements, the loop variable is the same type that the
    3042                 :             :  * array stores (eg: integer), when looping through slices, the loop variable
    3043                 :             :  * is an array of size and dimensions to match the size of the slice.
    3044                 :             :  * ----------
    3045                 :             :  */
    3046                 :             : static int
    3047                 :         121 : exec_stmt_foreach_a(PLpgSQL_execstate *estate, PLpgSQL_stmt_foreach_a *stmt)
    3048                 :             : {
    3049                 :             :     ArrayType  *arr;
    3050                 :             :     Oid         arrtype;
    3051                 :             :     int32       arrtypmod;
    3052                 :             :     PLpgSQL_datum *loop_var;
    3053                 :             :     Oid         loop_var_elem_type;
    3054                 :         121 :     bool        found = false;
    3055                 :         121 :     int         rc = PLPGSQL_RC_OK;
    3056                 :             :     MemoryContext stmt_mcontext;
    3057                 :             :     MemoryContext oldcontext;
    3058                 :             :     ArrayIterator array_iterator;
    3059                 :             :     Oid         iterator_result_type;
    3060                 :             :     int32       iterator_result_typmod;
    3061                 :             :     Datum       value;
    3062                 :             :     bool        isnull;
    3063                 :             : 
    3064                 :             :     /* get the value of the array expression */
    3065                 :         121 :     value = exec_eval_expr(estate, stmt->expr, &isnull, &arrtype, &arrtypmod);
    3066         [ -  + ]:         121 :     if (isnull)
    3067         [ #  # ]:           0 :         ereport(ERROR,
    3068                 :             :                 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
    3069                 :             :                  errmsg("FOREACH expression must not be null")));
    3070                 :             : 
    3071                 :             :     /*
    3072                 :             :      * Do as much as possible of the code below in stmt_mcontext, to avoid any
    3073                 :             :      * leaks from called subroutines.  We need a private stmt_mcontext since
    3074                 :             :      * we'll be calling arbitrary statement code.
    3075                 :             :      */
    3076                 :         121 :     stmt_mcontext = get_stmt_mcontext(estate);
    3077                 :         121 :     push_stmt_mcontext(estate);
    3078                 :         121 :     oldcontext = MemoryContextSwitchTo(stmt_mcontext);
    3079                 :             : 
    3080                 :             :     /* check the type of the expression - must be an array */
    3081         [ -  + ]:         121 :     if (!OidIsValid(get_element_type(arrtype)))
    3082         [ #  # ]:           0 :         ereport(ERROR,
    3083                 :             :                 (errcode(ERRCODE_DATATYPE_MISMATCH),
    3084                 :             :                  errmsg("FOREACH expression must yield an array, not type %s",
    3085                 :             :                         format_type_be(arrtype))));
    3086                 :             : 
    3087                 :             :     /*
    3088                 :             :      * We must copy the array into stmt_mcontext, else it will disappear in
    3089                 :             :      * exec_eval_cleanup.  This is annoying, but cleanup will certainly happen
    3090                 :             :      * while running the loop body, so we have little choice.
    3091                 :             :      */
    3092                 :         121 :     arr = DatumGetArrayTypePCopy(value);
    3093                 :             : 
    3094                 :             :     /* Clean up any leftover temporary memory */
    3095                 :         121 :     exec_eval_cleanup(estate);
    3096                 :             : 
    3097                 :             :     /* Slice dimension must be less than or equal to array dimension */
    3098   [ +  -  +  + ]:         121 :     if (stmt->slice < 0 || stmt->slice > ARR_NDIM(arr))
    3099         [ +  - ]:           4 :         ereport(ERROR,
    3100                 :             :                 (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
    3101                 :             :                  errmsg("slice dimension (%d) is out of the valid range 0..%d",
    3102                 :             :                         stmt->slice, ARR_NDIM(arr))));
    3103                 :             : 
    3104                 :             :     /* Set up the loop variable and see if it is of an array type */
    3105                 :         117 :     loop_var = estate->datums[stmt->varno];
    3106         [ +  + ]:         117 :     if (loop_var->dtype == PLPGSQL_DTYPE_REC ||
    3107         [ +  + ]:         109 :         loop_var->dtype == PLPGSQL_DTYPE_ROW)
    3108                 :             :     {
    3109                 :             :         /*
    3110                 :             :          * Record/row variable is certainly not of array type, and might not
    3111                 :             :          * be initialized at all yet, so don't try to get its type
    3112                 :             :          */
    3113                 :          16 :         loop_var_elem_type = InvalidOid;
    3114                 :             :     }
    3115                 :             :     else
    3116                 :         101 :         loop_var_elem_type = get_element_type(plpgsql_exec_get_datum_type(estate,
    3117                 :             :                                                                           loop_var));
    3118                 :             : 
    3119                 :             :     /*
    3120                 :             :      * Sanity-check the loop variable type.  We don't try very hard here, and
    3121                 :             :      * should not be too picky since it's possible that exec_assign_value can
    3122                 :             :      * coerce values of different types.  But it seems worthwhile to complain
    3123                 :             :      * if the array-ness of the loop variable is not right.
    3124                 :             :      */
    3125   [ +  +  +  + ]:         117 :     if (stmt->slice > 0 && loop_var_elem_type == InvalidOid)
    3126         [ +  - ]:           8 :         ereport(ERROR,
    3127                 :             :                 (errcode(ERRCODE_DATATYPE_MISMATCH),
    3128                 :             :                  errmsg("FOREACH ... SLICE loop variable must be of an array type")));
    3129   [ +  +  -  + ]:         109 :     if (stmt->slice == 0 && loop_var_elem_type != InvalidOid)
    3130         [ #  # ]:           0 :         ereport(ERROR,
    3131                 :             :                 (errcode(ERRCODE_DATATYPE_MISMATCH),
    3132                 :             :                  errmsg("FOREACH loop variable must not be of an array type")));
    3133                 :             : 
    3134                 :             :     /* Create an iterator to step through the array */
    3135                 :         109 :     array_iterator = array_create_iterator(arr, stmt->slice, NULL);
    3136                 :             : 
    3137                 :             :     /* Identify iterator result type */
    3138         [ +  + ]:         109 :     if (stmt->slice > 0)
    3139                 :             :     {
    3140                 :             :         /* When slicing, nominal type of result is same as array type */
    3141                 :          24 :         iterator_result_type = arrtype;
    3142                 :          24 :         iterator_result_typmod = arrtypmod;
    3143                 :             :     }
    3144                 :             :     else
    3145                 :             :     {
    3146                 :             :         /* Without slicing, results are individual array elements */
    3147                 :          85 :         iterator_result_type = ARR_ELEMTYPE(arr);
    3148                 :          85 :         iterator_result_typmod = arrtypmod;
    3149                 :             :     }
    3150                 :             : 
    3151                 :             :     /* Iterate over the array elements or slices */
    3152         [ +  + ]:        3705 :     while (array_iterate(array_iterator, &value, &isnull))
    3153                 :             :     {
    3154                 :        3596 :         found = true;           /* looped at least once */
    3155                 :             : 
    3156                 :             :         /* exec_assign_value and exec_stmts must run in the main context */
    3157                 :        3596 :         MemoryContextSwitchTo(oldcontext);
    3158                 :             : 
    3159                 :             :         /* Assign current element/slice to the loop variable */
    3160                 :        3596 :         exec_assign_value(estate, loop_var, value, isnull,
    3161                 :             :                           iterator_result_type, iterator_result_typmod);
    3162                 :             : 
    3163                 :             :         /* In slice case, value is temporary; must free it to avoid leakage */
    3164         [ +  + ]:        3596 :         if (stmt->slice > 0)
    3165                 :          36 :             pfree(DatumGetPointer(value));
    3166                 :             : 
    3167                 :             :         /*
    3168                 :             :          * Execute the statements
    3169                 :             :          */
    3170                 :        3596 :         rc = exec_stmts(estate, stmt->body);
    3171                 :             : 
    3172   [ -  +  -  +  :        3596 :         LOOP_RC_PROCESSING(stmt->label, break);
          -  -  -  -  -  
          -  -  +  -  -  
             -  -  -  - ]
    3173                 :             : 
    3174                 :        3596 :         MemoryContextSwitchTo(stmt_mcontext);
    3175                 :             :     }
    3176                 :             : 
    3177                 :             :     /* Restore memory context state */
    3178                 :         109 :     MemoryContextSwitchTo(oldcontext);
    3179                 :         109 :     pop_stmt_mcontext(estate);
    3180                 :             : 
    3181                 :             :     /* Release temporary memory, including the array value */
    3182                 :         109 :     MemoryContextReset(stmt_mcontext);
    3183                 :             : 
    3184                 :             :     /*
    3185                 :             :      * Set the FOUND variable to indicate the result of executing the loop
    3186                 :             :      * (namely, whether we looped one or more times). This must be set here so
    3187                 :             :      * that it does not interfere with the value of the FOUND variable inside
    3188                 :             :      * the loop processing itself.
    3189                 :             :      */
    3190                 :         109 :     exec_set_found(estate, found);
    3191                 :             : 
    3192                 :         109 :     return rc;
    3193                 :             : }
    3194                 :             : 
    3195                 :             : 
    3196                 :             : /* ----------
    3197                 :             :  * exec_stmt_exit           Implements EXIT and CONTINUE
    3198                 :             :  *
    3199                 :             :  * This begins the process of exiting / restarting a loop.
    3200                 :             :  * ----------
    3201                 :             :  */
    3202                 :             : static int
    3203                 :        2367 : exec_stmt_exit(PLpgSQL_execstate *estate, PLpgSQL_stmt_exit *stmt)
    3204                 :             : {
    3205                 :             :     /*
    3206                 :             :      * If the exit / continue has a condition, evaluate it
    3207                 :             :      */
    3208         [ +  + ]:        2367 :     if (stmt->cond != NULL)
    3209                 :             :     {
    3210                 :             :         bool        value;
    3211                 :             :         bool        isnull;
    3212                 :             : 
    3213                 :        1962 :         value = exec_eval_boolean(estate, stmt->cond, &isnull);
    3214                 :        1962 :         exec_eval_cleanup(estate);
    3215   [ +  -  +  + ]:        1962 :         if (isnull || value == false)
    3216                 :        1821 :             return PLPGSQL_RC_OK;
    3217                 :             :     }
    3218                 :             : 
    3219                 :         546 :     estate->exitlabel = stmt->label;
    3220         [ +  + ]:         546 :     if (stmt->is_exit)
    3221                 :          64 :         return PLPGSQL_RC_EXIT;
    3222                 :             :     else
    3223                 :         482 :         return PLPGSQL_RC_CONTINUE;
    3224                 :             : }
    3225                 :             : 
    3226                 :             : 
    3227                 :             : /* ----------
    3228                 :             :  * exec_stmt_return         Evaluate an expression and start
    3229                 :             :  *                  returning from the function.
    3230                 :             :  *
    3231                 :             :  * Note: The result may be in the eval_mcontext.  Therefore, we must not
    3232                 :             :  * do exec_eval_cleanup while unwinding the control stack.
    3233                 :             :  * ----------
    3234                 :             :  */
    3235                 :             : static int
    3236                 :       64392 : exec_stmt_return(PLpgSQL_execstate *estate, PLpgSQL_stmt_return *stmt)
    3237                 :             : {
    3238                 :             :     /*
    3239                 :             :      * If processing a set-returning PL/pgSQL function, the final RETURN
    3240                 :             :      * indicates that the function is finished producing tuples.  The rest of
    3241                 :             :      * the work will be done at the top level.
    3242                 :             :      */
    3243         [ +  + ]:       64392 :     if (estate->retisset)
    3244                 :        2526 :         return PLPGSQL_RC_RETURN;
    3245                 :             : 
    3246                 :             :     /* initialize for null result */
    3247                 :       61866 :     estate->retval = (Datum) 0;
    3248                 :       61866 :     estate->retisnull = true;
    3249                 :       61866 :     estate->rettype = InvalidOid;
    3250                 :             : 
    3251                 :             :     /*
    3252                 :             :      * Special case path when the RETURN expression is a simple variable
    3253                 :             :      * reference; in particular, this path is always taken in functions with
    3254                 :             :      * one or more OUT parameters.
    3255                 :             :      *
    3256                 :             :      * This special case is especially efficient for returning variables that
    3257                 :             :      * have R/W expanded values: we can put the R/W pointer directly into
    3258                 :             :      * estate->retval, leading to transferring the value to the caller's
    3259                 :             :      * context cheaply.  If we went through exec_eval_expr we'd end up with a
    3260                 :             :      * R/O pointer.  It's okay to skip MakeExpandedObjectReadOnly here since
    3261                 :             :      * we know we won't need the variable's value within the function anymore.
    3262                 :             :      */
    3263         [ +  + ]:       61866 :     if (stmt->retvarno >= 0)
    3264                 :             :     {
    3265                 :       35992 :         PLpgSQL_datum *retvar = estate->datums[stmt->retvarno];
    3266                 :             : 
    3267   [ -  +  +  - ]:       35992 :         switch (retvar->dtype)
    3268                 :             :         {
    3269                 :           0 :             case PLPGSQL_DTYPE_PROMISE:
    3270                 :             :                 /* fulfill promise if needed, then handle like regular var */
    3271                 :           0 :                 plpgsql_fulfill_promise(estate, (PLpgSQL_var *) retvar);
    3272                 :             : 
    3273                 :             :                 pg_fallthrough;
    3274                 :             : 
    3275                 :       24172 :             case PLPGSQL_DTYPE_VAR:
    3276                 :             :                 {
    3277                 :       24172 :                     PLpgSQL_var *var = (PLpgSQL_var *) retvar;
    3278                 :             : 
    3279                 :       24172 :                     estate->retval = var->value;
    3280                 :       24172 :                     estate->retisnull = var->isnull;
    3281                 :       24172 :                     estate->rettype = var->datatype->typoid;
    3282                 :             : 
    3283                 :             :                     /*
    3284                 :             :                      * A PLpgSQL_var could not be of composite type, so
    3285                 :             :                      * conversion must fail if retistuple.  We throw a custom
    3286                 :             :                      * error mainly for consistency with historical behavior.
    3287                 :             :                      * For the same reason, we don't throw error if the result
    3288                 :             :                      * is NULL.  (Note that plpgsql_exec_trigger assumes that
    3289                 :             :                      * any non-null result has been verified to be composite.)
    3290                 :             :                      */
    3291   [ +  +  +  - ]:       24172 :                     if (estate->retistuple && !estate->retisnull)
    3292         [ +  - ]:           4 :                         ereport(ERROR,
    3293                 :             :                                 (errcode(ERRCODE_DATATYPE_MISMATCH),
    3294                 :             :                                  errmsg("cannot return non-composite value from function returning composite type")));
    3295                 :             :                 }
    3296                 :       24168 :                 break;
    3297                 :             : 
    3298                 :       11820 :             case PLPGSQL_DTYPE_ROW:
    3299                 :             :             case PLPGSQL_DTYPE_REC:
    3300                 :             :                 {
    3301                 :             :                     /* exec_eval_datum can handle these cases */
    3302                 :             :                     int32       rettypmod;
    3303                 :             : 
    3304                 :       11820 :                     exec_eval_datum(estate,
    3305                 :             :                                     retvar,
    3306                 :             :                                     &estate->rettype,
    3307                 :             :                                     &rettypmod,
    3308                 :             :                                     &estate->retval,
    3309                 :             :                                     &estate->retisnull);
    3310                 :             :                 }
    3311                 :       11820 :                 break;
    3312                 :             : 
    3313                 :           0 :             default:
    3314         [ #  # ]:           0 :                 elog(ERROR, "unrecognized dtype: %d", retvar->dtype);
    3315                 :             :         }
    3316                 :             : 
    3317                 :       35988 :         return PLPGSQL_RC_RETURN;
    3318                 :             :     }
    3319                 :             : 
    3320         [ +  + ]:       25874 :     if (stmt->expr != NULL)
    3321                 :             :     {
    3322                 :             :         int32       rettypmod;
    3323                 :             : 
    3324                 :       22432 :         estate->retval = exec_eval_expr(estate, stmt->expr,
    3325                 :             :                                         &(estate->retisnull),
    3326                 :             :                                         &(estate->rettype),
    3327                 :             :                                         &rettypmod);
    3328                 :             : 
    3329                 :             :         /*
    3330                 :             :          * As in the DTYPE_VAR case above, throw a custom error if a non-null,
    3331                 :             :          * non-composite value is returned in a function returning tuple.
    3332                 :             :          */
    3333   [ +  +  +  + ]:       22375 :         if (estate->retistuple && !estate->retisnull &&
    3334         [ +  + ]:        8115 :             !type_is_rowtype(estate->rettype))
    3335         [ +  - ]:           4 :             ereport(ERROR,
    3336                 :             :                     (errcode(ERRCODE_DATATYPE_MISMATCH),
    3337                 :             :                      errmsg("cannot return non-composite value from function returning composite type")));
    3338                 :             : 
    3339                 :       22371 :         return PLPGSQL_RC_RETURN;
    3340                 :             :     }
    3341                 :             : 
    3342                 :             :     /*
    3343                 :             :      * Special hack for function returning VOID: instead of NULL, return a
    3344                 :             :      * non-null VOID value.  This is of dubious importance but is kept for
    3345                 :             :      * backwards compatibility.  We don't do it for procedures, though.
    3346                 :             :      */
    3347         [ +  - ]:        3442 :     if (estate->fn_rettype == VOIDOID &&
    3348         [ +  + ]:        3442 :         estate->func->fn_prokind != PROKIND_PROCEDURE)
    3349                 :             :     {
    3350                 :        3383 :         estate->retval = (Datum) 0;
    3351                 :        3383 :         estate->retisnull = false;
    3352                 :        3383 :         estate->rettype = VOIDOID;
    3353                 :             :     }
    3354                 :             : 
    3355                 :        3442 :     return PLPGSQL_RC_RETURN;
    3356                 :             : }
    3357                 :             : 
    3358                 :             : /* ----------
    3359                 :             :  * exec_stmt_return_next        Evaluate an expression and add it to the
    3360                 :             :  *                              list of tuples returned by the current
    3361                 :             :  *                              SRF.
    3362                 :             :  * ----------
    3363                 :             :  */
    3364                 :             : static int
    3365                 :        4041 : exec_stmt_return_next(PLpgSQL_execstate *estate,
    3366                 :             :                       PLpgSQL_stmt_return_next *stmt)
    3367                 :             : {
    3368                 :             :     TupleDesc   tupdesc;
    3369                 :             :     int         natts;
    3370                 :             :     HeapTuple   tuple;
    3371                 :             :     MemoryContext oldcontext;
    3372                 :             : 
    3373         [ -  + ]:        4041 :     if (!estate->retisset)
    3374         [ #  # ]:           0 :         ereport(ERROR,
    3375                 :             :                 (errcode(ERRCODE_SYNTAX_ERROR),
    3376                 :             :                  errmsg("cannot use RETURN NEXT in a non-SETOF function")));
    3377                 :             : 
    3378         [ +  + ]:        4041 :     if (estate->tuple_store == NULL)
    3379                 :         709 :         exec_init_tuple_store(estate);
    3380                 :             : 
    3381                 :             :     /* tuple_store_desc will be filled by exec_init_tuple_store */
    3382                 :        4041 :     tupdesc = estate->tuple_store_desc;
    3383                 :        4041 :     natts = tupdesc->natts;
    3384                 :             : 
    3385                 :             :     /*
    3386                 :             :      * Special case path when the RETURN NEXT expression is a simple variable
    3387                 :             :      * reference; in particular, this path is always taken in functions with
    3388                 :             :      * one or more OUT parameters.
    3389                 :             :      *
    3390                 :             :      * Unlike exec_stmt_return, there's no special win here for R/W expanded
    3391                 :             :      * values, since they'll have to get flattened to go into the tuplestore.
    3392                 :             :      * Indeed, we'd better make them R/O to avoid any risk of the casting step
    3393                 :             :      * changing them in-place.
    3394                 :             :      */
    3395         [ +  + ]:        4041 :     if (stmt->retvarno >= 0)
    3396                 :             :     {
    3397                 :        3670 :         PLpgSQL_datum *retvar = estate->datums[stmt->retvarno];
    3398                 :             : 
    3399   [ -  +  +  +  :        3670 :         switch (retvar->dtype)
                      - ]
    3400                 :             :         {
    3401                 :           0 :             case PLPGSQL_DTYPE_PROMISE:
    3402                 :             :                 /* fulfill promise if needed, then handle like regular var */
    3403                 :           0 :                 plpgsql_fulfill_promise(estate, (PLpgSQL_var *) retvar);
    3404                 :             : 
    3405                 :             :                 pg_fallthrough;
    3406                 :             : 
    3407                 :        3394 :             case PLPGSQL_DTYPE_VAR:
    3408                 :             :                 {
    3409                 :        3394 :                     PLpgSQL_var *var = (PLpgSQL_var *) retvar;
    3410                 :        3394 :                     Datum       retval = var->value;
    3411                 :        3394 :                     bool        isNull = var->isnull;
    3412                 :             :                     Form_pg_attribute attr;
    3413                 :             : 
    3414         [ -  + ]:        3394 :                     if (natts != 1)
    3415         [ #  # ]:           0 :                         ereport(ERROR,
    3416                 :             :                                 (errcode(ERRCODE_DATATYPE_MISMATCH),
    3417                 :             :                                  errmsg("wrong result type supplied in RETURN NEXT")));
    3418                 :             : 
    3419                 :             :                     /* let's be very paranoid about the cast step */
    3420   [ +  -  +  + ]:        3394 :                     retval = MakeExpandedObjectReadOnly(retval,
    3421                 :             :                                                         isNull,
    3422                 :             :                                                         var->datatype->typlen);
    3423                 :             : 
    3424                 :             :                     /* coerce type if needed */
    3425                 :        3394 :                     attr = TupleDescAttr(tupdesc, 0);
    3426                 :        6788 :                     retval = exec_cast_value(estate,
    3427                 :             :                                              retval,
    3428                 :             :                                              &isNull,
    3429                 :        3394 :                                              var->datatype->typoid,
    3430                 :        3394 :                                              var->datatype->atttypmod,
    3431                 :             :                                              attr->atttypid,
    3432                 :             :                                              attr->atttypmod);
    3433                 :             : 
    3434                 :        3394 :                     tuplestore_putvalues(estate->tuple_store, tupdesc,
    3435                 :             :                                          &retval, &isNull);
    3436                 :             :                 }
    3437                 :        3394 :                 break;
    3438                 :             : 
    3439                 :         140 :             case PLPGSQL_DTYPE_REC:
    3440                 :             :                 {
    3441                 :         140 :                     PLpgSQL_rec *rec = (PLpgSQL_rec *) retvar;
    3442                 :             :                     TupleDesc   rec_tupdesc;
    3443                 :             :                     TupleConversionMap *tupmap;
    3444                 :             : 
    3445                 :             :                     /* If rec is null, try to convert it to a row of nulls */
    3446         [ +  + ]:         140 :                     if (rec->erh == NULL)
    3447                 :           2 :                         instantiate_empty_record_variable(estate, rec);
    3448         [ +  + ]:         139 :                     if (ExpandedRecordIsEmpty(rec->erh))
    3449                 :           1 :                         deconstruct_expanded_record(rec->erh);
    3450                 :             : 
    3451                 :             :                     /* Use eval_mcontext for tuple conversion work */
    3452                 :         139 :                     oldcontext = MemoryContextSwitchTo(get_eval_mcontext(estate));
    3453                 :         139 :                     rec_tupdesc = expanded_record_get_tupdesc(rec->erh);
    3454                 :         139 :                     tupmap = convert_tuples_by_position(rec_tupdesc,
    3455                 :             :                                                         tupdesc,
    3456                 :             :                                                         gettext_noop("wrong record type supplied in RETURN NEXT"));
    3457                 :         139 :                     tuple = expanded_record_get_tuple(rec->erh);
    3458         [ +  + ]:         139 :                     if (tupmap)
    3459                 :          29 :                         tuple = execute_attr_map_tuple(tuple, tupmap);
    3460                 :             :                     else
    3461                 :             :                     {
    3462                 :             :                         /*
    3463                 :             :                          * Expanded records should always have valid contents,
    3464                 :             :                          * so we don't need a version check here.
    3465                 :             :                          */
    3466                 :             :                     }
    3467                 :         139 :                     tuplestore_puttuple(estate->tuple_store, tuple);
    3468                 :         139 :                     MemoryContextSwitchTo(oldcontext);
    3469                 :             :                 }
    3470                 :         139 :                 break;
    3471                 :             : 
    3472                 :         136 :             case PLPGSQL_DTYPE_ROW:
    3473                 :             :                 {
    3474                 :         136 :                     PLpgSQL_row *row = (PLpgSQL_row *) retvar;
    3475                 :             : 
    3476                 :             :                     /* We get here if there are multiple OUT parameters */
    3477                 :             : 
    3478                 :             :                     /* Use eval_mcontext for tuple conversion work */
    3479                 :         136 :                     oldcontext = MemoryContextSwitchTo(get_eval_mcontext(estate));
    3480                 :         136 :                     tuple = make_tuple_from_row(estate, row, tupdesc);
    3481         [ -  + ]:         136 :                     if (tuple == NULL)  /* should not happen */
    3482         [ #  # ]:           0 :                         ereport(ERROR,
    3483                 :             :                                 (errcode(ERRCODE_DATATYPE_MISMATCH),
    3484                 :             :                                  errmsg("wrong record type supplied in RETURN NEXT")));
    3485                 :         136 :                     tuplestore_puttuple(estate->tuple_store, tuple);
    3486                 :         136 :                     MemoryContextSwitchTo(oldcontext);
    3487                 :             :                 }
    3488                 :         136 :                 break;
    3489                 :             : 
    3490                 :           0 :             default:
    3491         [ #  # ]:           0 :                 elog(ERROR, "unrecognized dtype: %d", retvar->dtype);
    3492                 :             :                 break;
    3493                 :             :         }
    3494                 :             :     }
    3495         [ +  - ]:         371 :     else if (stmt->expr)
    3496                 :             :     {
    3497                 :             :         Datum       retval;
    3498                 :             :         bool        isNull;
    3499                 :             :         Oid         rettype;
    3500                 :             :         int32       rettypmod;
    3501                 :             : 
    3502                 :         371 :         retval = exec_eval_expr(estate,
    3503                 :             :                                 stmt->expr,
    3504                 :             :                                 &isNull,
    3505                 :             :                                 &rettype,
    3506                 :             :                                 &rettypmod);
    3507                 :             : 
    3508         [ +  + ]:         371 :         if (estate->retistuple)
    3509                 :             :         {
    3510                 :             :             /* Expression should be of RECORD or composite type */
    3511         [ +  + ]:         331 :             if (!isNull)
    3512                 :             :             {
    3513                 :             :                 HeapTupleData tmptup;
    3514                 :             :                 TupleDesc   retvaldesc;
    3515                 :             :                 TupleConversionMap *tupmap;
    3516                 :             : 
    3517         [ -  + ]:         327 :                 if (!type_is_rowtype(rettype))
    3518         [ #  # ]:           0 :                     ereport(ERROR,
    3519                 :             :                             (errcode(ERRCODE_DATATYPE_MISMATCH),
    3520                 :             :                              errmsg("cannot return non-composite value from function returning composite type")));
    3521                 :             : 
    3522                 :             :                 /* Use eval_mcontext for tuple conversion work */
    3523                 :         327 :                 oldcontext = MemoryContextSwitchTo(get_eval_mcontext(estate));
    3524                 :         327 :                 retvaldesc = deconstruct_composite_datum(retval, &tmptup);
    3525                 :         323 :                 tuple = &tmptup;
    3526                 :         323 :                 tupmap = convert_tuples_by_position(retvaldesc, tupdesc,
    3527                 :             :                                                     gettext_noop("returned record type does not match expected record type"));
    3528         [ +  + ]:         322 :                 if (tupmap)
    3529                 :           1 :                     tuple = execute_attr_map_tuple(tuple, tupmap);
    3530                 :             :                 else
    3531                 :             :                 {
    3532                 :             :                     /*
    3533                 :             :                      * No need to check the version here, due to
    3534                 :             :                      * deconstruct_composite_datum() already having checked.
    3535                 :             :                      */
    3536                 :             :                 }
    3537                 :             : 
    3538                 :         322 :                 tuplestore_puttuple(estate->tuple_store, tuple);
    3539         [ +  - ]:         322 :                 ReleaseTupleDesc(retvaldesc);
    3540                 :         322 :                 MemoryContextSwitchTo(oldcontext);
    3541                 :             :             }
    3542                 :             :             else
    3543                 :             :             {
    3544                 :             :                 /* Composite NULL --- store a row of nulls */
    3545                 :             :                 Datum      *nulldatums;
    3546                 :             :                 bool       *nullflags;
    3547                 :             : 
    3548                 :             :                 nulldatums = (Datum *)
    3549                 :           4 :                     eval_mcontext_alloc0(estate, natts * sizeof(Datum));
    3550                 :             :                 nullflags = (bool *)
    3551                 :           4 :                     eval_mcontext_alloc(estate, natts * sizeof(bool));
    3552                 :           4 :                 memset(nullflags, true, natts * sizeof(bool));
    3553                 :           4 :                 tuplestore_putvalues(estate->tuple_store, tupdesc,
    3554                 :             :                                      nulldatums, nullflags);
    3555                 :             :             }
    3556                 :             :         }
    3557                 :             :         else
    3558                 :             :         {
    3559                 :             :             Form_pg_attribute attr;
    3560                 :             : 
    3561                 :             :             /* Simple scalar result */
    3562         [ -  + ]:          40 :             if (natts != 1)
    3563         [ #  # ]:           0 :                 ereport(ERROR,
    3564                 :             :                         (errcode(ERRCODE_DATATYPE_MISMATCH),
    3565                 :             :                          errmsg("wrong result type supplied in RETURN NEXT")));
    3566                 :             : 
    3567                 :             :             /* coerce type if needed */
    3568                 :          40 :             attr = TupleDescAttr(tupdesc, 0);
    3569                 :          40 :             retval = exec_cast_value(estate,
    3570                 :             :                                      retval,
    3571                 :             :                                      &isNull,
    3572                 :             :                                      rettype,
    3573                 :             :                                      rettypmod,
    3574                 :             :                                      attr->atttypid,
    3575                 :             :                                      attr->atttypmod);
    3576                 :             : 
    3577                 :          40 :             tuplestore_putvalues(estate->tuple_store, tupdesc,
    3578                 :             :                                  &retval, &isNull);
    3579                 :             :         }
    3580                 :             :     }
    3581                 :             :     else
    3582                 :             :     {
    3583         [ #  # ]:           0 :         ereport(ERROR,
    3584                 :             :                 (errcode(ERRCODE_SYNTAX_ERROR),
    3585                 :             :                  errmsg("RETURN NEXT must have a parameter")));
    3586                 :             :     }
    3587                 :             : 
    3588                 :        4035 :     exec_eval_cleanup(estate);
    3589                 :             : 
    3590                 :        4035 :     return PLPGSQL_RC_OK;
    3591                 :             : }
    3592                 :             : 
    3593                 :             : /* ----------
    3594                 :             :  * exec_stmt_return_query       Evaluate a query and add it to the
    3595                 :             :  *                              list of tuples returned by the current
    3596                 :             :  *                              SRF.
    3597                 :             :  * ----------
    3598                 :             :  */
    3599                 :             : static int
    3600                 :        1861 : exec_stmt_return_query(PLpgSQL_execstate *estate,
    3601                 :             :                        PLpgSQL_stmt_return_query *stmt)
    3602                 :             : {
    3603                 :             :     int64       tcount;
    3604                 :             :     DestReceiver *treceiver;
    3605                 :             :     int         rc;
    3606                 :             :     uint64      processed;
    3607                 :        1861 :     MemoryContext stmt_mcontext = get_stmt_mcontext(estate);
    3608                 :             :     MemoryContext oldcontext;
    3609                 :             : 
    3610         [ -  + ]:        1861 :     if (!estate->retisset)
    3611         [ #  # ]:           0 :         ereport(ERROR,
    3612                 :             :                 (errcode(ERRCODE_SYNTAX_ERROR),
    3613                 :             :                  errmsg("cannot use RETURN QUERY in a non-SETOF function")));
    3614                 :             : 
    3615         [ +  + ]:        1861 :     if (estate->tuple_store == NULL)
    3616                 :        1824 :         exec_init_tuple_store(estate);
    3617                 :             :     /* There might be some tuples in the tuplestore already */
    3618                 :        1861 :     tcount = tuplestore_tuple_count(estate->tuple_store);
    3619                 :             : 
    3620                 :             :     /*
    3621                 :             :      * Set up DestReceiver to transfer results directly to tuplestore,
    3622                 :             :      * converting rowtype if necessary.  DestReceiver lives in mcontext.
    3623                 :             :      */
    3624                 :        1861 :     oldcontext = MemoryContextSwitchTo(stmt_mcontext);
    3625                 :        1861 :     treceiver = CreateDestReceiver(DestTuplestore);
    3626                 :        1861 :     SetTuplestoreDestReceiverParams(treceiver,
    3627                 :             :                                     estate->tuple_store,
    3628                 :             :                                     estate->tuple_store_cxt,
    3629                 :             :                                     false,
    3630                 :             :                                     estate->tuple_store_desc,
    3631                 :             :                                     gettext_noop("structure of query does not match function result type"));
    3632                 :        1861 :     MemoryContextSwitchTo(oldcontext);
    3633                 :             : 
    3634         [ +  + ]:        1861 :     if (stmt->query != NULL)
    3635                 :             :     {
    3636                 :             :         /* static query */
    3637                 :        1689 :         PLpgSQL_expr *expr = stmt->query;
    3638                 :             :         ParamListInfo paramLI;
    3639                 :             :         SPIExecuteOptions options;
    3640                 :             : 
    3641                 :             :         /*
    3642                 :             :          * On the first call for this expression generate the plan.
    3643                 :             :          */
    3644         [ +  + ]:        1689 :         if (expr->plan == NULL)
    3645                 :          52 :             exec_prepare_plan(estate, expr, CURSOR_OPT_PARALLEL_OK);
    3646                 :             : 
    3647                 :             :         /*
    3648                 :             :          * Set up ParamListInfo to pass to executor
    3649                 :             :          */
    3650                 :        1689 :         paramLI = setup_param_list(estate, expr);
    3651                 :             : 
    3652                 :             :         /*
    3653                 :             :          * Execute the query
    3654                 :             :          */
    3655                 :        1689 :         memset(&options, 0, sizeof(options));
    3656                 :        1689 :         options.params = paramLI;
    3657                 :        1689 :         options.read_only = estate->readonly_func;
    3658                 :        1689 :         options.must_return_tuples = true;
    3659                 :        1689 :         options.dest = treceiver;
    3660                 :             : 
    3661                 :        1689 :         rc = SPI_execute_plan_extended(expr->plan, &options);
    3662         [ -  + ]:        1680 :         if (rc < 0)
    3663         [ #  # ]:           0 :             elog(ERROR, "SPI_execute_plan_extended failed executing query \"%s\": %s",
    3664                 :             :                  expr->query, SPI_result_code_string(rc));
    3665                 :             :     }
    3666                 :             :     else
    3667                 :             :     {
    3668                 :             :         /* RETURN QUERY EXECUTE */
    3669                 :             :         Datum       query;
    3670                 :             :         bool        isnull;
    3671                 :             :         Oid         restype;
    3672                 :             :         int32       restypmod;
    3673                 :             :         char       *querystr;
    3674                 :             :         SPIExecuteOptions options;
    3675                 :             : 
    3676                 :             :         /*
    3677                 :             :          * Evaluate the string expression after the EXECUTE keyword. Its
    3678                 :             :          * result is the querystring we have to execute.
    3679                 :             :          */
    3680                 :             :         Assert(stmt->dynquery != NULL);
    3681                 :         172 :         query = exec_eval_expr(estate, stmt->dynquery,
    3682                 :             :                                &isnull, &restype, &restypmod);
    3683         [ -  + ]:         172 :         if (isnull)
    3684         [ #  # ]:           0 :             ereport(ERROR,
    3685                 :             :                     (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
    3686                 :             :                      errmsg("query string argument of EXECUTE is null")));
    3687                 :             : 
    3688                 :             :         /* Get the C-String representation */
    3689                 :         172 :         querystr = convert_value_to_string(estate, query, restype);
    3690                 :             : 
    3691                 :             :         /* copy it into the stmt_mcontext before we clean up */
    3692                 :         172 :         querystr = MemoryContextStrdup(stmt_mcontext, querystr);
    3693                 :             : 
    3694                 :         172 :         exec_eval_cleanup(estate);
    3695                 :             : 
    3696                 :             :         /* Execute query, passing params if necessary */
    3697                 :         172 :         memset(&options, 0, sizeof(options));
    3698                 :         172 :         options.params = exec_eval_using_params(estate,
    3699                 :             :                                                 stmt->params);
    3700                 :         172 :         options.read_only = estate->readonly_func;
    3701                 :         172 :         options.must_return_tuples = true;
    3702                 :         172 :         options.dest = treceiver;
    3703                 :             : 
    3704                 :         172 :         rc = SPI_execute_extended(querystr, &options);
    3705         [ -  + ]:         168 :         if (rc < 0)
    3706         [ #  # ]:           0 :             elog(ERROR, "SPI_execute_extended failed executing query \"%s\": %s",
    3707                 :             :                  querystr, SPI_result_code_string(rc));
    3708                 :             :     }
    3709                 :             : 
    3710                 :             :     /* Clean up */
    3711                 :        1848 :     treceiver->rDestroy(treceiver);
    3712                 :        1848 :     exec_eval_cleanup(estate);
    3713                 :        1848 :     MemoryContextReset(stmt_mcontext);
    3714                 :             : 
    3715                 :             :     /* Count how many tuples we got */
    3716                 :        1848 :     processed = tuplestore_tuple_count(estate->tuple_store) - tcount;
    3717                 :             : 
    3718                 :        1848 :     estate->eval_processed = processed;
    3719                 :        1848 :     exec_set_found(estate, processed != 0);
    3720                 :             : 
    3721                 :        1848 :     return PLPGSQL_RC_OK;
    3722                 :             : }
    3723                 :             : 
    3724                 :             : static void
    3725                 :        2533 : exec_init_tuple_store(PLpgSQL_execstate *estate)
    3726                 :             : {
    3727                 :        2533 :     ReturnSetInfo *rsi = estate->rsi;
    3728                 :             :     MemoryContext oldcxt;
    3729                 :             :     ResourceOwner oldowner;
    3730                 :             : 
    3731                 :             :     /*
    3732                 :             :      * Check caller can handle a set result in the way we want
    3733                 :             :      */
    3734   [ +  -  -  + ]:        2533 :     if (!rsi || !IsA(rsi, ReturnSetInfo))
    3735         [ #  # ]:           0 :         ereport(ERROR,
    3736                 :             :                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    3737                 :             :                  errmsg("set-valued function called in context that cannot accept a set")));
    3738                 :             : 
    3739         [ +  - ]:        2533 :     if (!(rsi->allowedModes & SFRM_Materialize) ||
    3740         [ -  + ]:        2533 :         rsi->expectedDesc == NULL)
    3741         [ #  # ]:           0 :         ereport(ERROR,
    3742                 :             :                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    3743                 :             :                  errmsg("materialize mode required, but it is not allowed in this context")));
    3744                 :             : 
    3745                 :             :     /*
    3746                 :             :      * Switch to the right memory context and resource owner for storing the
    3747                 :             :      * tuplestore for return set. If we're within a subtransaction opened for
    3748                 :             :      * an exception-block, for example, we must still create the tuplestore in
    3749                 :             :      * the resource owner that was active when this function was entered, and
    3750                 :             :      * not in the subtransaction resource owner.
    3751                 :             :      */
    3752                 :        2533 :     oldcxt = MemoryContextSwitchTo(estate->tuple_store_cxt);
    3753                 :        2533 :     oldowner = CurrentResourceOwner;
    3754                 :        2533 :     CurrentResourceOwner = estate->tuple_store_owner;
    3755                 :             : 
    3756                 :        2533 :     estate->tuple_store =
    3757                 :        2533 :         tuplestore_begin_heap(rsi->allowedModes & SFRM_Materialize_Random,
    3758                 :             :                               false, work_mem);
    3759                 :             : 
    3760                 :        2533 :     CurrentResourceOwner = oldowner;
    3761                 :        2533 :     MemoryContextSwitchTo(oldcxt);
    3762                 :             : 
    3763                 :        2533 :     estate->tuple_store_desc = rsi->expectedDesc;
    3764                 :        2533 : }
    3765                 :             : 
    3766                 :             : #define SET_RAISE_OPTION_TEXT(opt, name) \
    3767                 :             : do { \
    3768                 :             :     if (opt) \
    3769                 :             :         ereport(ERROR, \
    3770                 :             :                 (errcode(ERRCODE_SYNTAX_ERROR), \
    3771                 :             :                  errmsg("RAISE option already specified: %s", \
    3772                 :             :                         name))); \
    3773                 :             :     opt = MemoryContextStrdup(stmt_mcontext, extval); \
    3774                 :             : } while (0)
    3775                 :             : 
    3776                 :             : /* ----------
    3777                 :             :  * exec_stmt_raise          Build a message and throw it with elog()
    3778                 :             :  * ----------
    3779                 :             :  */
    3780                 :             : static int
    3781                 :       12529 : exec_stmt_raise(PLpgSQL_execstate *estate, PLpgSQL_stmt_raise *stmt)
    3782                 :             : {
    3783                 :       12529 :     int         err_code = 0;
    3784                 :       12529 :     char       *condname = NULL;
    3785                 :       12529 :     char       *err_message = NULL;
    3786                 :       12529 :     char       *err_detail = NULL;
    3787                 :       12529 :     char       *err_hint = NULL;
    3788                 :       12529 :     char       *err_column = NULL;
    3789                 :       12529 :     char       *err_constraint = NULL;
    3790                 :       12529 :     char       *err_datatype = NULL;
    3791                 :       12529 :     char       *err_table = NULL;
    3792                 :       12529 :     char       *err_schema = NULL;
    3793                 :             :     MemoryContext stmt_mcontext;
    3794                 :             :     ListCell   *lc;
    3795                 :             : 
    3796                 :             :     /* RAISE with no parameters: re-throw current exception */
    3797   [ +  +  +  + ]:       12529 :     if (stmt->condname == NULL && stmt->message == NULL &&
    3798         [ +  + ]:          36 :         stmt->options == NIL)
    3799                 :             :     {
    3800         [ +  + ]:          24 :         if (estate->cur_error != NULL)
    3801                 :          20 :             ReThrowError(estate->cur_error);
    3802                 :             :         /* oops, we're not inside a handler */
    3803         [ +  - ]:           4 :         ereport(ERROR,
    3804                 :             :                 (errcode(ERRCODE_STACKED_DIAGNOSTICS_ACCESSED_WITHOUT_ACTIVE_HANDLER),
    3805                 :             :                  errmsg("RAISE without parameters cannot be used outside an exception handler")));
    3806                 :             :     }
    3807                 :             : 
    3808                 :             :     /* We'll need to accumulate the various strings in stmt_mcontext */
    3809                 :       12505 :     stmt_mcontext = get_stmt_mcontext(estate);
    3810                 :             : 
    3811         [ +  + ]:       12505 :     if (stmt->condname)
    3812                 :             :     {
    3813                 :         454 :         err_code = plpgsql_recognize_err_condition(stmt->condname, true);
    3814                 :         454 :         condname = MemoryContextStrdup(stmt_mcontext, stmt->condname);
    3815                 :             :     }
    3816                 :             : 
    3817         [ +  + ]:       12505 :     if (stmt->message)
    3818                 :             :     {
    3819                 :             :         StringInfoData ds;
    3820                 :             :         ListCell   *current_param;
    3821                 :             :         char       *cp;
    3822                 :             :         MemoryContext oldcontext;
    3823                 :             : 
    3824                 :             :         /* build string in stmt_mcontext */
    3825                 :       12039 :         oldcontext = MemoryContextSwitchTo(stmt_mcontext);
    3826                 :       12039 :         initStringInfo(&ds);
    3827                 :       12039 :         MemoryContextSwitchTo(oldcontext);
    3828                 :             : 
    3829                 :       12039 :         current_param = list_head(stmt->params);
    3830                 :             : 
    3831         [ +  + ]:      211041 :         for (cp = stmt->message; *cp; cp++)
    3832                 :             :         {
    3833                 :             :             /*
    3834                 :             :              * Occurrences of a single % are replaced by the next parameter's
    3835                 :             :              * external representation. Double %'s are converted to one %.
    3836                 :             :              */
    3837         [ +  + ]:      199138 :             if (cp[0] == '%')
    3838                 :             :             {
    3839                 :             :                 Oid         paramtypeid;
    3840                 :             :                 int32       paramtypmod;
    3841                 :             :                 Datum       paramvalue;
    3842                 :             :                 bool        paramisnull;
    3843                 :             :                 char       *extval;
    3844                 :             : 
    3845         [ +  + ]:       29571 :                 if (cp[1] == '%')
    3846                 :             :                 {
    3847                 :           4 :                     appendStringInfoChar(&ds, '%');
    3848                 :           4 :                     cp++;
    3849                 :           4 :                     continue;
    3850                 :             :                 }
    3851                 :             : 
    3852                 :             :                 /* should have been checked at compile time */
    3853         [ -  + ]:       29567 :                 if (current_param == NULL)
    3854         [ #  # ]:           0 :                     elog(ERROR, "unexpected RAISE parameter list length");
    3855                 :             : 
    3856                 :       29567 :                 paramvalue = exec_eval_expr(estate,
    3857                 :       29567 :                                             (PLpgSQL_expr *) lfirst(current_param),
    3858                 :             :                                             &paramisnull,
    3859                 :             :                                             &paramtypeid,
    3860                 :             :                                             &paramtypmod);
    3861                 :             : 
    3862         [ +  + ]:       29542 :                 if (paramisnull)
    3863                 :         259 :                     extval = "<NULL>";
    3864                 :             :                 else
    3865                 :       29283 :                     extval = convert_value_to_string(estate,
    3866                 :             :                                                      paramvalue,
    3867                 :             :                                                      paramtypeid);
    3868                 :       29431 :                 appendStringInfoString(&ds, extval);
    3869                 :       29431 :                 current_param = lnext(stmt->params, current_param);
    3870                 :       29431 :                 exec_eval_cleanup(estate);
    3871                 :             :             }
    3872                 :             :             else
    3873                 :      169567 :                 appendStringInfoChar(&ds, cp[0]);
    3874                 :             :         }
    3875                 :             : 
    3876                 :             :         /* should have been checked at compile time */
    3877         [ -  + ]:       11903 :         if (current_param != NULL)
    3878         [ #  # ]:           0 :             elog(ERROR, "unexpected RAISE parameter list length");
    3879                 :             : 
    3880                 :       11903 :         err_message = ds.data;
    3881                 :             :     }
    3882                 :             : 
    3883   [ +  +  +  +  :       12879 :     foreach(lc, stmt->options)
                   +  + ]
    3884                 :             :     {
    3885                 :         518 :         PLpgSQL_raise_option *opt = (PLpgSQL_raise_option *) lfirst(lc);
    3886                 :             :         Datum       optionvalue;
    3887                 :             :         bool        optionisnull;
    3888                 :             :         Oid         optiontypeid;
    3889                 :             :         int32       optiontypmod;
    3890                 :             :         char       *extval;
    3891                 :             : 
    3892                 :         518 :         optionvalue = exec_eval_expr(estate, opt->expr,
    3893                 :             :                                      &optionisnull,
    3894                 :             :                                      &optiontypeid,
    3895                 :             :                                      &optiontypmod);
    3896         [ -  + ]:         518 :         if (optionisnull)
    3897         [ #  # ]:           0 :             ereport(ERROR,
    3898                 :             :                     (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
    3899                 :             :                      errmsg("RAISE statement option cannot be null")));
    3900                 :             : 
    3901                 :         518 :         extval = convert_value_to_string(estate, optionvalue, optiontypeid);
    3902                 :             : 
    3903   [ +  +  +  +  :         518 :         switch (opt->opt_type)
          +  +  +  +  +  
                      - ]
    3904                 :             :         {
    3905                 :          28 :             case PLPGSQL_RAISEOPTION_ERRCODE:
    3906         [ +  + ]:          28 :                 if (err_code)
    3907         [ +  - ]:           4 :                     ereport(ERROR,
    3908                 :             :                             (errcode(ERRCODE_SYNTAX_ERROR),
    3909                 :             :                              errmsg("RAISE option already specified: %s",
    3910                 :             :                                     "ERRCODE")));
    3911                 :          24 :                 err_code = plpgsql_recognize_err_condition(extval, true);
    3912                 :          24 :                 condname = MemoryContextStrdup(stmt_mcontext, extval);
    3913                 :          24 :                 break;
    3914                 :         426 :             case PLPGSQL_RAISEOPTION_MESSAGE:
    3915   [ +  +  +  - ]:         426 :                 SET_RAISE_OPTION_TEXT(err_message, "MESSAGE");
    3916                 :         422 :                 break;
    3917                 :          30 :             case PLPGSQL_RAISEOPTION_DETAIL:
    3918   [ -  +  -  - ]:          30 :                 SET_RAISE_OPTION_TEXT(err_detail, "DETAIL");
    3919                 :          30 :                 break;
    3920                 :           9 :             case PLPGSQL_RAISEOPTION_HINT:
    3921   [ -  +  -  - ]:           9 :                 SET_RAISE_OPTION_TEXT(err_hint, "HINT");
    3922                 :           9 :                 break;
    3923                 :           5 :             case PLPGSQL_RAISEOPTION_COLUMN:
    3924   [ -  +  -  - ]:           5 :                 SET_RAISE_OPTION_TEXT(err_column, "COLUMN");
    3925                 :           5 :                 break;
    3926                 :           5 :             case PLPGSQL_RAISEOPTION_CONSTRAINT:
    3927   [ -  +  -  - ]:           5 :                 SET_RAISE_OPTION_TEXT(err_constraint, "CONSTRAINT");
    3928                 :           5 :                 break;
    3929                 :           5 :             case PLPGSQL_RAISEOPTION_DATATYPE:
    3930   [ -  +  -  - ]:           5 :                 SET_RAISE_OPTION_TEXT(err_datatype, "DATATYPE");
    3931                 :           5 :                 break;
    3932                 :           5 :             case PLPGSQL_RAISEOPTION_TABLE:
    3933   [ -  +  -  - ]:           5 :                 SET_RAISE_OPTION_TEXT(err_table, "TABLE");
    3934                 :           5 :                 break;
    3935                 :           5 :             case PLPGSQL_RAISEOPTION_SCHEMA:
    3936   [ -  +  -  - ]:           5 :                 SET_RAISE_OPTION_TEXT(err_schema, "SCHEMA");
    3937                 :           5 :                 break;
    3938                 :           0 :             default:
    3939         [ #  # ]:           0 :                 elog(ERROR, "unrecognized raise option: %d", opt->opt_type);
    3940                 :             :         }
    3941                 :             : 
    3942                 :         510 :         exec_eval_cleanup(estate);
    3943                 :             :     }
    3944                 :             : 
    3945                 :             :     /* Default code if nothing specified */
    3946   [ +  +  +  + ]:       12361 :     if (err_code == 0 && stmt->elog_level >= ERROR)
    3947                 :         248 :         err_code = ERRCODE_RAISE_EXCEPTION;
    3948                 :             : 
    3949                 :             :     /* Default error message if nothing specified */
    3950         [ +  + ]:       12361 :     if (err_message == NULL)
    3951                 :             :     {
    3952         [ +  + ]:          44 :         if (condname)
    3953                 :             :         {
    3954                 :          40 :             err_message = condname;
    3955                 :          40 :             condname = NULL;
    3956                 :             :         }
    3957                 :             :         else
    3958                 :           4 :             err_message = MemoryContextStrdup(stmt_mcontext,
    3959                 :           4 :                                               unpack_sql_state(err_code));
    3960                 :             :     }
    3961                 :             : 
    3962                 :             :     /*
    3963                 :             :      * Throw the error (may or may not come back)
    3964                 :             :      */
    3965   [ +  +  +  +  :       12361 :     ereport(stmt->elog_level,
          +  +  +  +  +  
          +  +  +  +  +  
             +  +  +  + ]
    3966                 :             :             (err_code ? errcode(err_code) : 0,
    3967                 :             :              errmsg_internal("%s", err_message),
    3968                 :             :              (err_detail != NULL) ? errdetail_internal("%s", err_detail) : 0,
    3969                 :             :              (err_hint != NULL) ? errhint("%s", err_hint) : 0,
    3970                 :             :              (err_column != NULL) ?
    3971                 :             :              err_generic_string(PG_DIAG_COLUMN_NAME, err_column) : 0,
    3972                 :             :              (err_constraint != NULL) ?
    3973                 :             :              err_generic_string(PG_DIAG_CONSTRAINT_NAME, err_constraint) : 0,
    3974                 :             :              (err_datatype != NULL) ?
    3975                 :             :              err_generic_string(PG_DIAG_DATATYPE_NAME, err_datatype) : 0,
    3976                 :             :              (err_table != NULL) ?
    3977                 :             :              err_generic_string(PG_DIAG_TABLE_NAME, err_table) : 0,
    3978                 :             :              (err_schema != NULL) ?
    3979                 :             :              err_generic_string(PG_DIAG_SCHEMA_NAME, err_schema) : 0));
    3980                 :             : 
    3981                 :             :     /* Clean up transient strings */
    3982                 :       11643 :     MemoryContextReset(stmt_mcontext);
    3983                 :             : 
    3984                 :       11643 :     return PLPGSQL_RC_OK;
    3985                 :             : }
    3986                 :             : 
    3987                 :             : /* ----------
    3988                 :             :  * exec_stmt_assert         Assert statement
    3989                 :             :  * ----------
    3990                 :             :  */
    3991                 :             : static int
    3992                 :        8483 : exec_stmt_assert(PLpgSQL_execstate *estate, PLpgSQL_stmt_assert *stmt)
    3993                 :             : {
    3994                 :             :     bool        value;
    3995                 :             :     bool        isnull;
    3996                 :             : 
    3997                 :             :     /* do nothing when asserts are not enabled */
    3998         [ +  + ]:        8483 :     if (!plpgsql_check_asserts)
    3999                 :           4 :         return PLPGSQL_RC_OK;
    4000                 :             : 
    4001                 :        8479 :     value = exec_eval_boolean(estate, stmt->cond, &isnull);
    4002                 :        8479 :     exec_eval_cleanup(estate);
    4003                 :             : 
    4004   [ +  +  +  + ]:        8479 :     if (isnull || !value)
    4005                 :             :     {
    4006                 :          16 :         char       *message = NULL;
    4007                 :             : 
    4008         [ +  + ]:          16 :         if (stmt->message != NULL)
    4009                 :             :         {
    4010                 :             :             Datum       val;
    4011                 :             :             Oid         typeid;
    4012                 :             :             int32       typmod;
    4013                 :             : 
    4014                 :           8 :             val = exec_eval_expr(estate, stmt->message,
    4015                 :             :                                  &isnull, &typeid, &typmod);
    4016         [ +  - ]:           8 :             if (!isnull)
    4017                 :           8 :                 message = convert_value_to_string(estate, val, typeid);
    4018                 :             :             /* we mustn't do exec_eval_cleanup here */
    4019                 :             :         }
    4020                 :             : 
    4021   [ +  -  +  + ]:          16 :         ereport(ERROR,
    4022                 :             :                 (errcode(ERRCODE_ASSERT_FAILURE),
    4023                 :             :                  message ? errmsg_internal("%s", message) :
    4024                 :             :                  errmsg("assertion failed")));
    4025                 :             :     }
    4026                 :             : 
    4027                 :        8463 :     return PLPGSQL_RC_OK;
    4028                 :             : }
    4029                 :             : 
    4030                 :             : /* ----------
    4031                 :             :  * Initialize a mostly empty execution state
    4032                 :             :  * ----------
    4033                 :             :  */
    4034                 :             : static void
    4035                 :       65416 : plpgsql_estate_setup(PLpgSQL_execstate *estate,
    4036                 :             :                      PLpgSQL_function *func,
    4037                 :             :                      ReturnSetInfo *rsi,
    4038                 :             :                      EState *simple_eval_estate,
    4039                 :             :                      ResourceOwner simple_eval_resowner)
    4040                 :             : {
    4041                 :             :     HASHCTL     ctl;
    4042                 :             : 
    4043                 :             :     /* this link will be restored at exit from plpgsql_call_handler */
    4044                 :       65416 :     func->cur_estate = estate;
    4045                 :             : 
    4046                 :       65416 :     estate->func = func;
    4047                 :       65416 :     estate->trigdata = NULL;
    4048                 :       65416 :     estate->evtrigdata = NULL;
    4049                 :             : 
    4050                 :       65416 :     estate->retval = (Datum) 0;
    4051                 :       65416 :     estate->retisnull = true;
    4052                 :       65416 :     estate->rettype = InvalidOid;
    4053                 :             : 
    4054                 :       65416 :     estate->fn_rettype = func->fn_rettype;
    4055                 :       65416 :     estate->retistuple = func->fn_retistuple;
    4056                 :       65416 :     estate->retisset = func->fn_retset;
    4057                 :             : 
    4058                 :       65416 :     estate->readonly_func = func->fn_readonly;
    4059                 :       65416 :     estate->atomic = true;
    4060                 :             : 
    4061                 :       65416 :     estate->exitlabel = NULL;
    4062                 :       65416 :     estate->cur_error = NULL;
    4063                 :             : 
    4064                 :       65416 :     estate->tuple_store = NULL;
    4065                 :       65416 :     estate->tuple_store_desc = NULL;
    4066         [ +  + ]:       65416 :     if (rsi)
    4067                 :             :     {
    4068                 :        2756 :         estate->tuple_store_cxt = rsi->econtext->ecxt_per_query_memory;
    4069                 :        2756 :         estate->tuple_store_owner = CurrentResourceOwner;
    4070                 :             :     }
    4071                 :             :     else
    4072                 :             :     {
    4073                 :       62660 :         estate->tuple_store_cxt = NULL;
    4074                 :       62660 :         estate->tuple_store_owner = NULL;
    4075                 :             :     }
    4076                 :       65416 :     estate->rsi = rsi;
    4077                 :             : 
    4078                 :       65416 :     estate->found_varno = func->found_varno;
    4079                 :       65416 :     estate->ndatums = func->ndatums;
    4080                 :       65416 :     estate->datums = NULL;
    4081                 :             :     /* the datums array will be filled by copy_plpgsql_datums() */
    4082                 :       65416 :     estate->datum_context = CurrentMemoryContext;
    4083                 :             : 
    4084                 :             :     /* initialize our ParamListInfo with appropriate hook functions */
    4085                 :       65416 :     estate->paramLI = makeParamList(0);
    4086                 :       65416 :     estate->paramLI->paramFetch = plpgsql_param_fetch;
    4087                 :       65416 :     estate->paramLI->paramFetchArg = estate;
    4088                 :       65416 :     estate->paramLI->paramCompile = plpgsql_param_compile;
    4089                 :       65416 :     estate->paramLI->paramCompileArg = NULL;  /* not needed */
    4090                 :       65416 :     estate->paramLI->parserSetup = (ParserSetupHook) plpgsql_parser_setup;
    4091                 :       65416 :     estate->paramLI->parserSetupArg = NULL; /* filled during use */
    4092                 :       65416 :     estate->paramLI->numParams = estate->ndatums;
    4093                 :             : 
    4094                 :             :     /* Create the session-wide cast-expression hash if we didn't already */
    4095         [ +  + ]:       65416 :     if (cast_expr_hash == NULL)
    4096                 :             :     {
    4097                 :         745 :         ctl.keysize = sizeof(plpgsql_CastHashKey);
    4098                 :         745 :         ctl.entrysize = sizeof(plpgsql_CastExprHashEntry);
    4099                 :         745 :         cast_expr_hash = hash_create("PLpgSQL cast expressions",
    4100                 :             :                                      16,    /* start small and extend */
    4101                 :             :                                      &ctl,
    4102                 :             :                                      HASH_ELEM | HASH_BLOBS);
    4103                 :             :     }
    4104                 :             : 
    4105                 :             :     /* set up for use of appropriate simple-expression EState and cast hash */
    4106         [ +  + ]:       65416 :     if (simple_eval_estate)
    4107                 :             :     {
    4108                 :        1063 :         estate->simple_eval_estate = simple_eval_estate;
    4109                 :             :         /* Private cast hash just lives in function's main context */
    4110                 :        1063 :         ctl.keysize = sizeof(plpgsql_CastHashKey);
    4111                 :        1063 :         ctl.entrysize = sizeof(plpgsql_CastHashEntry);
    4112                 :        1063 :         ctl.hcxt = CurrentMemoryContext;
    4113                 :        1063 :         estate->cast_hash = hash_create("PLpgSQL private cast cache",
    4114                 :             :                                         16, /* start small and extend */
    4115                 :             :                                         &ctl,
    4116                 :             :                                         HASH_ELEM | HASH_BLOBS | HASH_CONTEXT);
    4117                 :             :     }
    4118                 :             :     else
    4119                 :             :     {
    4120                 :       64353 :         estate->simple_eval_estate = shared_simple_eval_estate;
    4121                 :             :         /* Create the session-wide cast-info hash table if we didn't already */
    4122         [ +  + ]:       64353 :         if (shared_cast_hash == NULL)
    4123                 :             :         {
    4124                 :         618 :             ctl.keysize = sizeof(plpgsql_CastHashKey);
    4125                 :         618 :             ctl.entrysize = sizeof(plpgsql_CastHashEntry);
    4126                 :         618 :             shared_cast_hash = hash_create("PLpgSQL cast cache",
    4127                 :             :                                            16,  /* start small and extend */
    4128                 :             :                                            &ctl,
    4129                 :             :                                            HASH_ELEM | HASH_BLOBS);
    4130                 :             :         }
    4131                 :       64353 :         estate->cast_hash = shared_cast_hash;
    4132                 :             :     }
    4133                 :             :     /* likewise for the simple-expression resource owner */
    4134         [ +  + ]:       65416 :     if (simple_eval_resowner)
    4135                 :        1063 :         estate->simple_eval_resowner = simple_eval_resowner;
    4136                 :             :     else
    4137                 :       64353 :         estate->simple_eval_resowner = shared_simple_eval_resowner;
    4138                 :             : 
    4139                 :             :     /* if there's a procedure resowner, it'll be filled in later */
    4140                 :       65416 :     estate->procedure_resowner = NULL;
    4141                 :             : 
    4142                 :             :     /*
    4143                 :             :      * We start with no stmt_mcontext; one will be created only if needed.
    4144                 :             :      * That context will be a direct child of the function's main execution
    4145                 :             :      * context.  Additional stmt_mcontexts might be created as children of it.
    4146                 :             :      */
    4147                 :       65416 :     estate->stmt_mcontext = NULL;
    4148                 :       65416 :     estate->stmt_mcontext_parent = CurrentMemoryContext;
    4149                 :             : 
    4150                 :       65416 :     estate->eval_tuptable = NULL;
    4151                 :       65416 :     estate->eval_processed = 0;
    4152                 :       65416 :     estate->eval_econtext = NULL;
    4153                 :             : 
    4154                 :       65416 :     estate->err_stmt = NULL;
    4155                 :       65416 :     estate->err_var = NULL;
    4156                 :       65416 :     estate->err_text = NULL;
    4157                 :             : 
    4158                 :       65416 :     estate->plugin_info = NULL;
    4159                 :             : 
    4160                 :             :     /*
    4161                 :             :      * Create an EState and ExprContext for evaluation of simple expressions.
    4162                 :             :      */
    4163                 :       65416 :     plpgsql_create_econtext(estate);
    4164                 :             : 
    4165                 :             :     /*
    4166                 :             :      * Let the plugin, if any, see this function before we initialize local
    4167                 :             :      * PL/pgSQL variables.  Note that we also give the plugin a few function
    4168                 :             :      * pointers, so it can call back into PL/pgSQL for doing things like
    4169                 :             :      * variable assignments and stack traces.
    4170                 :             :      */
    4171         [ -  + ]:       65416 :     if (*plpgsql_plugin_ptr)
    4172                 :             :     {
    4173                 :           0 :         (*plpgsql_plugin_ptr)->error_callback = plpgsql_exec_error_callback;
    4174                 :           0 :         (*plpgsql_plugin_ptr)->assign_expr = exec_assign_expr;
    4175                 :           0 :         (*plpgsql_plugin_ptr)->assign_value = exec_assign_value;
    4176                 :           0 :         (*plpgsql_plugin_ptr)->eval_datum = exec_eval_datum;
    4177                 :           0 :         (*plpgsql_plugin_ptr)->cast_value = exec_cast_value;
    4178                 :             : 
    4179         [ #  # ]:           0 :         if ((*plpgsql_plugin_ptr)->func_setup)
    4180                 :           0 :             ((*plpgsql_plugin_ptr)->func_setup) (estate, func);
    4181                 :             :     }
    4182                 :       65416 : }
    4183                 :             : 
    4184                 :             : /* ----------
    4185                 :             :  * Release temporary memory used by expression/subselect evaluation
    4186                 :             :  *
    4187                 :             :  * NB: the result of the evaluation is no longer valid after this is done,
    4188                 :             :  * unless it is a pass-by-value datatype.
    4189                 :             :  * ----------
    4190                 :             :  */
    4191                 :             : static void
    4192                 :      348720 : exec_eval_cleanup(PLpgSQL_execstate *estate)
    4193                 :             : {
    4194                 :             :     /* Clear result of a full SPI_execute */
    4195         [ +  + ]:      348720 :     if (estate->eval_tuptable != NULL)
    4196                 :       10505 :         SPI_freetuptable(estate->eval_tuptable);
    4197                 :      348720 :     estate->eval_tuptable = NULL;
    4198                 :             : 
    4199                 :             :     /*
    4200                 :             :      * Clear result of exec_eval_simple_expr (but keep the econtext).  This
    4201                 :             :      * also clears any short-lived allocations done via get_eval_mcontext.
    4202                 :             :      */
    4203         [ +  + ]:      348720 :     if (estate->eval_econtext != NULL)
    4204                 :      284448 :         ResetExprContext(estate->eval_econtext);
    4205                 :      348720 : }
    4206                 :             : 
    4207                 :             : 
    4208                 :             : /* ----------
    4209                 :             :  * Generate a prepared plan
    4210                 :             :  *
    4211                 :             :  * CAUTION: it is possible for this function to throw an error after it has
    4212                 :             :  * built a SPIPlan and saved it in expr->plan.  Therefore, be wary of doing
    4213                 :             :  * additional things contingent on expr->plan being NULL.  That is, given
    4214                 :             :  * code like
    4215                 :             :  *
    4216                 :             :  *  if (query->plan == NULL)
    4217                 :             :  *  {
    4218                 :             :  *      // okay to put setup code here
    4219                 :             :  *      exec_prepare_plan(estate, query, ...);
    4220                 :             :  *      // NOT okay to put more logic here
    4221                 :             :  *  }
    4222                 :             :  *
    4223                 :             :  * extra steps at the end are unsafe because they will not be executed when
    4224                 :             :  * re-executing the calling statement, if exec_prepare_plan failed the first
    4225                 :             :  * time.  This is annoyingly error-prone, but the alternatives are worse.
    4226                 :             :  * ----------
    4227                 :             :  */
    4228                 :             : static void
    4229                 :       18723 : exec_prepare_plan(PLpgSQL_execstate *estate,
    4230                 :             :                   PLpgSQL_expr *expr, int cursorOptions)
    4231                 :             : {
    4232                 :             :     SPIPlanPtr  plan;
    4233                 :             :     SPIPrepareOptions options;
    4234                 :             : 
    4235                 :             :     /*
    4236                 :             :      * Generate and save the plan
    4237                 :             :      */
    4238                 :       18723 :     memset(&options, 0, sizeof(options));
    4239                 :       18723 :     options.parserSetup = (ParserSetupHook) plpgsql_parser_setup;
    4240                 :       18723 :     options.parserSetupArg = expr;
    4241                 :       18723 :     options.parseMode = expr->parseMode;
    4242                 :       18723 :     options.cursorOptions = cursorOptions;
    4243                 :       18723 :     plan = SPI_prepare_extended(expr->query, &options);
    4244         [ -  + ]:       18662 :     if (plan == NULL)
    4245         [ #  # ]:           0 :         elog(ERROR, "SPI_prepare_extended failed for \"%s\": %s",
    4246                 :             :              expr->query, SPI_result_code_string(SPI_result));
    4247                 :             : 
    4248                 :       18662 :     SPI_keepplan(plan);
    4249                 :       18662 :     expr->plan = plan;
    4250                 :             : 
    4251                 :             :     /* Check to see if it's a simple expression */
    4252                 :       18662 :     exec_simple_check_plan(estate, expr);
    4253                 :       18633 : }
    4254                 :             : 
    4255                 :             : 
    4256                 :             : /* ----------
    4257                 :             :  * exec_stmt_execsql            Execute an SQL statement (possibly with INTO).
    4258                 :             :  *
    4259                 :             :  * Note: some callers rely on this not touching stmt_mcontext.  If it ever
    4260                 :             :  * needs to use that, fix those callers to push/pop stmt_mcontext.
    4261                 :             :  * ----------
    4262                 :             :  */
    4263                 :             : static int
    4264                 :       55137 : exec_stmt_execsql(PLpgSQL_execstate *estate,
    4265                 :             :                   PLpgSQL_stmt_execsql *stmt)
    4266                 :             : {
    4267                 :             :     ParamListInfo paramLI;
    4268                 :             :     long        tcount;
    4269                 :             :     int         rc;
    4270                 :       55137 :     PLpgSQL_expr *expr = stmt->sqlstmt;
    4271                 :       55137 :     int         too_many_rows_level = 0;
    4272                 :             : 
    4273         [ +  + ]:       55137 :     if (plpgsql_extra_errors & PLPGSQL_XCHECK_TOOMANYROWS)
    4274                 :           4 :         too_many_rows_level = ERROR;
    4275         [ +  + ]:       55133 :     else if (plpgsql_extra_warnings & PLPGSQL_XCHECK_TOOMANYROWS)
    4276                 :           4 :         too_many_rows_level = WARNING;
    4277                 :             : 
    4278                 :             :     /*
    4279                 :             :      * On the first call for this statement generate the plan, and detect
    4280                 :             :      * whether the statement is INSERT/UPDATE/DELETE/MERGE
    4281                 :             :      */
    4282         [ +  + ]:       55137 :     if (expr->plan == NULL)
    4283                 :        2154 :         exec_prepare_plan(estate, expr, CURSOR_OPT_PARALLEL_OK);
    4284                 :             : 
    4285         [ +  + ]:       55123 :     if (!stmt->mod_stmt_set)
    4286                 :             :     {
    4287                 :             :         ListCell   *l;
    4288                 :             : 
    4289                 :        2150 :         stmt->mod_stmt = false;
    4290   [ +  -  +  +  :        3733 :         foreach(l, SPI_plan_get_plan_sources(expr->plan))
                   +  + ]
    4291                 :             :         {
    4292                 :        2150 :             CachedPlanSource *plansource = (CachedPlanSource *) lfirst(l);
    4293                 :             : 
    4294                 :             :             /*
    4295                 :             :              * We could look at the raw_parse_tree, but it seems simpler to
    4296                 :             :              * check the command tag.  Note we should *not* look at the Query
    4297                 :             :              * tree(s), since those are the result of rewriting and could be
    4298                 :             :              * stale, or could have been transmogrified into something else
    4299                 :             :              * entirely.
    4300                 :             :              */
    4301         [ +  + ]:        2150 :             if (plansource->commandTag == CMDTAG_INSERT ||
    4302         [ +  + ]:        1808 :                 plansource->commandTag == CMDTAG_UPDATE ||
    4303         [ +  + ]:        1673 :                 plansource->commandTag == CMDTAG_DELETE ||
    4304         [ +  + ]:        1619 :                 plansource->commandTag == CMDTAG_MERGE)
    4305                 :             :             {
    4306                 :         567 :                 stmt->mod_stmt = true;
    4307                 :         567 :                 break;
    4308                 :             :             }
    4309                 :             :         }
    4310                 :        2150 :         stmt->mod_stmt_set = true;
    4311                 :             :     }
    4312                 :             : 
    4313                 :             :     /*
    4314                 :             :      * Some users write "SELECT expr INTO var" instead of "var := expr".  If
    4315                 :             :      * the expression is simple and the INTO target is a single variable, we
    4316                 :             :      * can bypass SPI and call ExecEvalExpr() directly.  (exec_eval_expr would
    4317                 :             :      * actually work for non-simple expressions too, but such an expression
    4318                 :             :      * might return more or less than one row, complicating matters greatly.
    4319                 :             :      * The potential performance win is small if it's non-simple, and any
    4320                 :             :      * errors we might issue would likely look different, so avoid using this
    4321                 :             :      * code path for non-simple cases.)
    4322                 :             :      */
    4323   [ +  +  +  + ]:       55123 :     if (expr->expr_simple_expr && stmt->into)
    4324                 :             :     {
    4325                 :        2943 :         PLpgSQL_datum *target = estate->datums[stmt->target->dno];
    4326                 :             : 
    4327         [ +  + ]:        2943 :         if (target->dtype == PLPGSQL_DTYPE_ROW)
    4328                 :             :         {
    4329                 :        2934 :             PLpgSQL_row *row = (PLpgSQL_row *) target;
    4330                 :             : 
    4331         [ +  + ]:        2934 :             if (row->nfields == 1)
    4332                 :             :             {
    4333                 :             :                 /* OK, there is a single target variable */
    4334                 :             :                 ErrorContextCallback plerrcontext;
    4335                 :             :                 Datum       value;
    4336                 :             :                 bool        isnull;
    4337                 :             :                 Oid         valtype;
    4338                 :             :                 int32       valtypmod;
    4339                 :             :                 bool        simple;
    4340                 :             : 
    4341                 :             :                 /*
    4342                 :             :                  * Setup error traceback support for ereport().  This is so
    4343                 :             :                  * that error reports for the expression will look similar
    4344                 :             :                  * whether or not we take this code path.
    4345                 :             :                  */
    4346                 :        2926 :                 plerrcontext.callback = plpgsql_execsql_error_callback;
    4347                 :        2926 :                 plerrcontext.arg = expr;
    4348                 :        2926 :                 plerrcontext.previous = error_context_stack;
    4349                 :        2926 :                 error_context_stack = &plerrcontext;
    4350                 :             : 
    4351                 :             :                 /*
    4352                 :             :                  * Evaluate the already-planned expression.  This fails if the
    4353                 :             :                  * expression is busy, or if replanning occurs and we find it
    4354                 :             :                  * is no longer simple.  In such cases, fall through to the
    4355                 :             :                  * SPI code below.
    4356                 :             :                  */
    4357                 :        2926 :                 simple = exec_eval_simple_expr(estate, expr,
    4358                 :             :                                                &value, &isnull,
    4359                 :             :                                                &valtype, &valtypmod);
    4360                 :             : 
    4361                 :             :                 /*
    4362                 :             :                  * Pop the error context stack: the code below would not use
    4363                 :             :                  * SPI's error handling during the assignment step.
    4364                 :             :                  */
    4365                 :        2920 :                 error_context_stack = plerrcontext.previous;
    4366                 :             : 
    4367         [ +  - ]:        2920 :                 if (simple)
    4368                 :             :                 {
    4369                 :             :                     /* Success; assign the result to the INTO target */
    4370                 :        2920 :                     exec_assign_value(estate, estate->datums[row->varnos[0]],
    4371                 :             :                                       value, isnull, valtype, valtypmod);
    4372                 :        2915 :                     exec_eval_cleanup(estate);
    4373                 :             : 
    4374                 :             :                     /*
    4375                 :             :                      * We must duplicate the other effects of the code below,
    4376                 :             :                      * as well.  We know that exactly one row was returned, so
    4377                 :             :                      * it doesn't matter whether the INTO was STRICT or not.
    4378                 :             :                      */
    4379                 :        2915 :                     exec_set_found(estate, true);
    4380                 :        2915 :                     estate->eval_processed = 1;
    4381                 :             : 
    4382                 :        2915 :                     return PLPGSQL_RC_OK;
    4383                 :             :                 }
    4384                 :             :             }
    4385                 :             :         }
    4386                 :             :     }
    4387                 :             : 
    4388                 :             :     /*
    4389                 :             :      * Set up ParamListInfo to pass to executor
    4390                 :             :      */
    4391                 :       52197 :     paramLI = setup_param_list(estate, expr);
    4392                 :             : 
    4393                 :             :     /*
    4394                 :             :      * If we have INTO, then we only need one row back ... but if we have INTO
    4395                 :             :      * STRICT or extra check too_many_rows, ask for two rows, so that we can
    4396                 :             :      * verify the statement returns only one.  INSERT/UPDATE/DELETE/MERGE are
    4397                 :             :      * always treated strictly. Without INTO, just run the statement to
    4398                 :             :      * completion (tcount = 0).
    4399                 :             :      *
    4400                 :             :      * We could just ask for two rows always when using INTO, but there are
    4401                 :             :      * some cases where demanding the extra row costs significant time, eg by
    4402                 :             :      * forcing completion of a sequential scan.  So don't do it unless we need
    4403                 :             :      * to enforce strictness.
    4404                 :             :      */
    4405         [ +  + ]:       52197 :     if (stmt->into)
    4406                 :             :     {
    4407   [ +  +  +  +  :        8622 :         if (stmt->strict || stmt->mod_stmt || too_many_rows_level)
                   +  + ]
    4408                 :        1185 :             tcount = 2;
    4409                 :             :         else
    4410                 :        7437 :             tcount = 1;
    4411                 :             :     }
    4412                 :             :     else
    4413                 :       43575 :         tcount = 0;
    4414                 :             : 
    4415                 :             :     /*
    4416                 :             :      * Execute the plan
    4417                 :             :      */
    4418                 :       52197 :     rc = SPI_execute_plan_with_paramlist(expr->plan, paramLI,
    4419                 :       52197 :                                          estate->readonly_func, tcount);
    4420                 :             : 
    4421                 :             :     /*
    4422                 :             :      * Check for error, and set FOUND if appropriate (for historical reasons
    4423                 :             :      * we set FOUND only for certain query types).  Also Assert that we
    4424                 :             :      * identified the statement type the same as SPI did.
    4425                 :             :      */
    4426   [ +  +  +  -  :       50009 :     switch (rc)
                +  +  - ]
    4427                 :             :     {
    4428                 :        5543 :         case SPI_OK_SELECT:
    4429                 :             :             Assert(!stmt->mod_stmt);
    4430                 :        5543 :             exec_set_found(estate, (SPI_processed != 0));
    4431                 :        5543 :             break;
    4432                 :             : 
    4433                 :       31905 :         case SPI_OK_INSERT:
    4434                 :             :         case SPI_OK_UPDATE:
    4435                 :             :         case SPI_OK_DELETE:
    4436                 :             :         case SPI_OK_MERGE:
    4437                 :             :         case SPI_OK_INSERT_RETURNING:
    4438                 :             :         case SPI_OK_UPDATE_RETURNING:
    4439                 :             :         case SPI_OK_DELETE_RETURNING:
    4440                 :             :         case SPI_OK_MERGE_RETURNING:
    4441                 :             :             Assert(stmt->mod_stmt);
    4442                 :       31905 :             exec_set_found(estate, (SPI_processed != 0));
    4443                 :       31905 :             break;
    4444                 :             : 
    4445                 :       12558 :         case SPI_OK_SELINTO:
    4446                 :             :         case SPI_OK_UTILITY:
    4447                 :             :             Assert(!stmt->mod_stmt);
    4448                 :       12558 :             break;
    4449                 :             : 
    4450                 :           0 :         case SPI_OK_REWRITTEN:
    4451                 :             : 
    4452                 :             :             /*
    4453                 :             :              * The command was rewritten into another kind of command. It's
    4454                 :             :              * not clear what FOUND would mean in that case (and SPI doesn't
    4455                 :             :              * return the row count either), so just set it to false.  Note
    4456                 :             :              * that we can't assert anything about mod_stmt here.
    4457                 :             :              */
    4458                 :           0 :             exec_set_found(estate, false);
    4459                 :           0 :             break;
    4460                 :             : 
    4461                 :             :             /* Some SPI errors deserve specific error messages */
    4462                 :           2 :         case SPI_ERROR_COPY:
    4463         [ +  - ]:           2 :             ereport(ERROR,
    4464                 :             :                     (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    4465                 :             :                      errmsg("cannot COPY to/from client in PL/pgSQL")));
    4466                 :             :             break;
    4467                 :             : 
    4468                 :           1 :         case SPI_ERROR_TRANSACTION:
    4469         [ +  - ]:           1 :             ereport(ERROR,
    4470                 :             :                     (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    4471                 :             :                      errmsg("unsupported transaction command in PL/pgSQL")));
    4472                 :             :             break;
    4473                 :             : 
    4474                 :           0 :         default:
    4475         [ #  # ]:           0 :             elog(ERROR, "SPI_execute_plan_with_paramlist failed executing query \"%s\": %s",
    4476                 :             :                  expr->query, SPI_result_code_string(rc));
    4477                 :             :             break;
    4478                 :             :     }
    4479                 :             : 
    4480                 :             :     /* All variants should save result info for GET DIAGNOSTICS */
    4481                 :       50006 :     estate->eval_processed = SPI_processed;
    4482                 :             : 
    4483                 :             :     /* Process INTO if present */
    4484         [ +  + ]:       50006 :     if (stmt->into)
    4485                 :             :     {
    4486                 :        6621 :         SPITupleTable *tuptab = SPI_tuptable;
    4487                 :        6621 :         uint64      n = SPI_processed;
    4488                 :             :         PLpgSQL_variable *target;
    4489                 :             : 
    4490                 :             :         /* If the statement did not return a tuple table, complain */
    4491         [ -  + ]:        6621 :         if (tuptab == NULL)
    4492         [ #  # ]:           0 :             ereport(ERROR,
    4493                 :             :                     (errcode(ERRCODE_SYNTAX_ERROR),
    4494                 :             :                      errmsg("INTO used with a command that cannot return data")));
    4495                 :             : 
    4496                 :             :         /* Fetch target's datum entry */
    4497                 :        6621 :         target = (PLpgSQL_variable *) estate->datums[stmt->target->dno];
    4498                 :             : 
    4499                 :             :         /*
    4500                 :             :          * If SELECT ... INTO specified STRICT, and the query didn't find
    4501                 :             :          * exactly one row, throw an error.  If STRICT was not specified, then
    4502                 :             :          * allow the query to find any number of rows.
    4503                 :             :          */
    4504         [ +  + ]:        6621 :         if (n == 0)
    4505                 :             :         {
    4506         [ +  + ]:          41 :             if (stmt->strict)
    4507                 :             :             {
    4508                 :             :                 char       *errdetail;
    4509                 :             : 
    4510         [ +  + ]:          12 :                 if (estate->func->print_strict_params)
    4511                 :           8 :                     errdetail = format_expr_params(estate, expr);
    4512                 :             :                 else
    4513                 :           4 :                     errdetail = NULL;
    4514                 :             : 
    4515   [ +  -  +  + ]:          12 :                 ereport(ERROR,
    4516                 :             :                         (errcode(ERRCODE_NO_DATA_FOUND),
    4517                 :             :                          errmsg("query returned no rows"),
    4518                 :             :                          errdetail ? errdetail_internal("parameters: %s", errdetail) : 0));
    4519                 :             :             }
    4520                 :             :             /* set the target to NULL(s) */
    4521                 :          29 :             exec_move_row(estate, target, NULL, tuptab->tupdesc);
    4522                 :             :         }
    4523                 :             :         else
    4524                 :             :         {
    4525   [ +  +  +  +  :        6580 :             if (n > 1 && (stmt->strict || stmt->mod_stmt || too_many_rows_level))
             +  +  +  - ]
    4526                 :             :             {
    4527                 :             :                 char       *errdetail;
    4528                 :             :                 int         errlevel;
    4529                 :             : 
    4530         [ +  + ]:          32 :                 if (estate->func->print_strict_params)
    4531                 :          12 :                     errdetail = format_expr_params(estate, expr);
    4532                 :             :                 else
    4533                 :          20 :                     errdetail = NULL;
    4534                 :             : 
    4535   [ +  +  +  + ]:          32 :                 errlevel = (stmt->strict || stmt->mod_stmt) ? ERROR : too_many_rows_level;
    4536                 :             : 
    4537   [ +  -  +  + ]:          32 :                 ereport(errlevel,
    4538                 :             :                         (errcode(ERRCODE_TOO_MANY_ROWS),
    4539                 :             :                          errmsg("query returned more than one row"),
    4540                 :             :                          errdetail ? errdetail_internal("parameters: %s", errdetail) : 0,
    4541                 :             :                          errhint("Make sure the query returns a single row, for example by using LIMIT 1 with SELECT.")));
    4542                 :             :             }
    4543                 :             :             /* Put the first result row into the target */
    4544                 :        6552 :             exec_move_row(estate, target, tuptab->vals[0], tuptab->tupdesc);
    4545                 :             :         }
    4546                 :             : 
    4547                 :             :         /* Clean up */
    4548                 :        6565 :         exec_eval_cleanup(estate);
    4549                 :        6565 :         SPI_freetuptable(SPI_tuptable);
    4550                 :             :     }
    4551                 :             :     else
    4552                 :             :     {
    4553                 :             :         /* If the statement returned a tuple table, complain */
    4554         [ -  + ]:       43385 :         if (SPI_tuptable != NULL)
    4555   [ #  #  #  # ]:           0 :             ereport(ERROR,
    4556                 :             :                     (errcode(ERRCODE_SYNTAX_ERROR),
    4557                 :             :                      errmsg("query has no destination for result data"),
    4558                 :             :                      (rc == SPI_OK_SELECT) ? errhint("If you want to discard the results of a SELECT, use PERFORM instead.") : 0));
    4559                 :             :     }
    4560                 :             : 
    4561                 :       49950 :     return PLPGSQL_RC_OK;
    4562                 :             : }
    4563                 :             : 
    4564                 :             : 
    4565                 :             : /* ----------
    4566                 :             :  * exec_stmt_dynexecute         Execute a dynamic SQL query
    4567                 :             :  *                  (possibly with INTO).
    4568                 :             :  * ----------
    4569                 :             :  */
    4570                 :             : static int
    4571                 :       13299 : exec_stmt_dynexecute(PLpgSQL_execstate *estate,
    4572                 :             :                      PLpgSQL_stmt_dynexecute *stmt)
    4573                 :             : {
    4574                 :             :     Datum       query;
    4575                 :             :     bool        isnull;
    4576                 :             :     Oid         restype;
    4577                 :             :     int32       restypmod;
    4578                 :             :     char       *querystr;
    4579                 :             :     int         exec_res;
    4580                 :             :     ParamListInfo paramLI;
    4581                 :             :     SPIExecuteOptions options;
    4582                 :       13299 :     MemoryContext stmt_mcontext = get_stmt_mcontext(estate);
    4583                 :       13299 :     int         too_many_rows_level = 0;
    4584                 :             : 
    4585         [ +  + ]:       13299 :     if (plpgsql_extra_errors & PLPGSQL_XCHECK_TOOMANYROWS)
    4586                 :           4 :         too_many_rows_level = ERROR;
    4587         [ +  + ]:       13295 :     else if (plpgsql_extra_warnings & PLPGSQL_XCHECK_TOOMANYROWS)
    4588                 :           4 :         too_many_rows_level = WARNING;
    4589                 :             : 
    4590                 :             :     /*
    4591                 :             :      * First we evaluate the string expression after the EXECUTE keyword. Its
    4592                 :             :      * result is the querystring we have to execute.
    4593                 :             :      */
    4594                 :       13299 :     query = exec_eval_expr(estate, stmt->query, &isnull, &restype, &restypmod);
    4595         [ -  + ]:       13299 :     if (isnull)
    4596         [ #  # ]:           0 :         ereport(ERROR,
    4597                 :             :                 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
    4598                 :             :                  errmsg("query string argument of EXECUTE is null")));
    4599                 :             : 
    4600                 :             :     /* Get the C-String representation */
    4601                 :       13299 :     querystr = convert_value_to_string(estate, query, restype);
    4602                 :             : 
    4603                 :             :     /* copy it into the stmt_mcontext before we clean up */
    4604                 :       13299 :     querystr = MemoryContextStrdup(stmt_mcontext, querystr);
    4605                 :             : 
    4606                 :       13299 :     exec_eval_cleanup(estate);
    4607                 :             : 
    4608                 :             :     /*
    4609                 :             :      * Execute the query without preparing a saved plan.
    4610                 :             :      */
    4611                 :       13299 :     paramLI = exec_eval_using_params(estate, stmt->params);
    4612                 :             : 
    4613                 :       13299 :     memset(&options, 0, sizeof(options));
    4614                 :       13299 :     options.params = paramLI;
    4615                 :       13299 :     options.read_only = estate->readonly_func;
    4616                 :             : 
    4617                 :       13299 :     exec_res = SPI_execute_extended(querystr, &options);
    4618                 :             : 
    4619   [ +  -  -  +  :       13129 :     switch (exec_res)
                   +  - ]
    4620                 :             :     {
    4621                 :       13126 :         case SPI_OK_SELECT:
    4622                 :             :         case SPI_OK_INSERT:
    4623                 :             :         case SPI_OK_UPDATE:
    4624                 :             :         case SPI_OK_DELETE:
    4625                 :             :         case SPI_OK_MERGE:
    4626                 :             :         case SPI_OK_INSERT_RETURNING:
    4627                 :             :         case SPI_OK_UPDATE_RETURNING:
    4628                 :             :         case SPI_OK_DELETE_RETURNING:
    4629                 :             :         case SPI_OK_MERGE_RETURNING:
    4630                 :             :         case SPI_OK_UTILITY:
    4631                 :             :         case SPI_OK_REWRITTEN:
    4632                 :       13126 :             break;
    4633                 :             : 
    4634                 :           0 :         case 0:
    4635                 :             : 
    4636                 :             :             /*
    4637                 :             :              * Also allow a zero return, which implies the querystring
    4638                 :             :              * contained no commands.
    4639                 :             :              */
    4640                 :           0 :             break;
    4641                 :             : 
    4642                 :           0 :         case SPI_OK_SELINTO:
    4643                 :             : 
    4644                 :             :             /*
    4645                 :             :              * We want to disallow SELECT INTO for now, because its behavior
    4646                 :             :              * is not consistent with SELECT INTO in a normal plpgsql context.
    4647                 :             :              * (We need to reimplement EXECUTE to parse the string as a
    4648                 :             :              * plpgsql command, not just feed it to SPI_execute.)  This is not
    4649                 :             :              * a functional limitation because CREATE TABLE AS is allowed.
    4650                 :             :              */
    4651         [ #  # ]:           0 :             ereport(ERROR,
    4652                 :             :                     (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    4653                 :             :                      errmsg("EXECUTE of SELECT ... INTO is not implemented"),
    4654                 :             :                      errhint("You might want to use EXECUTE ... INTO or EXECUTE CREATE TABLE ... AS instead.")));
    4655                 :             :             break;
    4656                 :             : 
    4657                 :             :             /* Some SPI errors deserve specific error messages */
    4658                 :           2 :         case SPI_ERROR_COPY:
    4659         [ +  - ]:           2 :             ereport(ERROR,
    4660                 :             :                     (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    4661                 :             :                      errmsg("cannot COPY to/from client in PL/pgSQL")));
    4662                 :             :             break;
    4663                 :             : 
    4664                 :           1 :         case SPI_ERROR_TRANSACTION:
    4665         [ +  - ]:           1 :             ereport(ERROR,
    4666                 :             :                     (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    4667                 :             :                      errmsg("EXECUTE of transaction commands is not implemented")));
    4668                 :             :             break;
    4669                 :             : 
    4670                 :           0 :         default:
    4671         [ #  # ]:           0 :             elog(ERROR, "SPI_execute_extended failed executing query \"%s\": %s",
    4672                 :             :                  querystr, SPI_result_code_string(exec_res));
    4673                 :             :             break;
    4674                 :             :     }
    4675                 :             : 
    4676                 :             :     /* Save result info for GET DIAGNOSTICS */
    4677                 :       13126 :     estate->eval_processed = SPI_processed;
    4678                 :             : 
    4679                 :             :     /* Process INTO if present */
    4680         [ +  + ]:       13126 :     if (stmt->into)
    4681                 :             :     {
    4682                 :        3952 :         SPITupleTable *tuptab = SPI_tuptable;
    4683                 :        3952 :         uint64      n = SPI_processed;
    4684                 :             :         PLpgSQL_variable *target;
    4685                 :             : 
    4686                 :             :         /* If the statement did not return a tuple table, complain */
    4687         [ -  + ]:        3952 :         if (tuptab == NULL)
    4688         [ #  # ]:           0 :             ereport(ERROR,
    4689                 :             :                     (errcode(ERRCODE_SYNTAX_ERROR),
    4690                 :             :                      errmsg("INTO used with a command that cannot return data")));
    4691                 :             : 
    4692                 :             :         /* Fetch target's datum entry */
    4693                 :        3952 :         target = (PLpgSQL_variable *) estate->datums[stmt->target->dno];
    4694                 :             : 
    4695                 :             :         /*
    4696                 :             :          * If STRICT was specified, require exactly one row.  Otherwise, allow
    4697                 :             :          * any number of rows, but report a warning or error for multiple rows
    4698                 :             :          * if the too_many_rows extra check is enabled.
    4699                 :             :          */
    4700         [ +  + ]:        3952 :         if (n == 0)
    4701                 :             :         {
    4702         [ +  - ]:           8 :             if (stmt->strict)
    4703                 :             :             {
    4704                 :             :                 char       *errdetail;
    4705                 :             : 
    4706         [ +  + ]:           8 :                 if (estate->func->print_strict_params)
    4707                 :           4 :                     errdetail = format_preparedparamsdata(estate, paramLI);
    4708                 :             :                 else
    4709                 :           4 :                     errdetail = NULL;
    4710                 :             : 
    4711   [ +  -  +  + ]:           8 :                 ereport(ERROR,
    4712                 :             :                         (errcode(ERRCODE_NO_DATA_FOUND),
    4713                 :             :                          errmsg("query returned no rows"),
    4714                 :             :                          errdetail ? errdetail_internal("parameters: %s", errdetail) : 0));
    4715                 :             :             }
    4716                 :             :             /* set the target to NULL(s) */
    4717                 :           0 :             exec_move_row(estate, target, NULL, tuptab->tupdesc);
    4718                 :             :         }
    4719                 :             :         else
    4720                 :             :         {
    4721   [ +  +  +  +  :        3944 :             if (n > 1 && (stmt->strict || too_many_rows_level))
                   +  + ]
    4722                 :             :             {
    4723                 :             :                 char       *errdetail;
    4724                 :             :                 int         errlevel;
    4725                 :             : 
    4726         [ +  + ]:          20 :                 if (estate->func->print_strict_params)
    4727                 :           8 :                     errdetail = format_preparedparamsdata(estate, paramLI);
    4728                 :             :                 else
    4729                 :          12 :                     errdetail = NULL;
    4730                 :             : 
    4731         [ +  + ]:          20 :                 errlevel = stmt->strict ? ERROR : too_many_rows_level;
    4732                 :             : 
    4733   [ +  -  +  + ]:          20 :                 ereport(errlevel,
    4734                 :             :                         (errcode(ERRCODE_TOO_MANY_ROWS),
    4735                 :             :                          errmsg("query returned more than one row"),
    4736                 :             :                          errdetail ? errdetail_internal("parameters: %s", errdetail) : 0,
    4737                 :             :                          errhint("Make sure the query returns a single row, for example by using LIMIT 1 with SELECT.")));
    4738                 :             :             }
    4739                 :             : 
    4740                 :             :             /* Put the first result row into the target */
    4741                 :        3928 :             exec_move_row(estate, target, tuptab->vals[0], tuptab->tupdesc);
    4742                 :             :         }
    4743                 :             :         /* clean up after exec_move_row() */
    4744                 :        3928 :         exec_eval_cleanup(estate);
    4745                 :             :     }
    4746                 :             :     else
    4747                 :             :     {
    4748                 :             :         /*
    4749                 :             :          * It might be a good idea to raise an error if the query returned
    4750                 :             :          * tuples that are being ignored, but historically we have not done
    4751                 :             :          * that.
    4752                 :             :          */
    4753                 :             :     }
    4754                 :             : 
    4755                 :             :     /* Release any result from SPI_execute, as well as transient data */
    4756                 :       13102 :     SPI_freetuptable(SPI_tuptable);
    4757                 :       13102 :     MemoryContextReset(stmt_mcontext);
    4758                 :             : 
    4759                 :       13102 :     return PLPGSQL_RC_OK;
    4760                 :             : }
    4761                 :             : 
    4762                 :             : 
    4763                 :             : /* ----------
    4764                 :             :  * exec_stmt_dynfors            Execute a dynamic query, assign each
    4765                 :             :  *                  tuple to a record or row and
    4766                 :             :  *                  execute a group of statements
    4767                 :             :  *                  for it.
    4768                 :             :  * ----------
    4769                 :             :  */
    4770                 :             : static int
    4771                 :        6358 : exec_stmt_dynfors(PLpgSQL_execstate *estate, PLpgSQL_stmt_dynfors *stmt)
    4772                 :             : {
    4773                 :             :     Portal      portal;
    4774                 :             :     int         rc;
    4775                 :             : 
    4776                 :        6358 :     portal = exec_dynquery_with_params(estate, stmt->query, stmt->params,
    4777                 :             :                                        NULL, CURSOR_OPT_NO_SCROLL);
    4778                 :             : 
    4779                 :             :     /*
    4780                 :             :      * Execute the loop
    4781                 :             :      */
    4782                 :        6358 :     rc = exec_for_query(estate, (PLpgSQL_stmt_forq *) stmt, portal, true);
    4783                 :             : 
    4784                 :             :     /*
    4785                 :             :      * Close the implicit cursor
    4786                 :             :      */
    4787                 :        6350 :     SPI_cursor_close(portal);
    4788                 :             : 
    4789                 :        6350 :     return rc;
    4790                 :             : }
    4791                 :             : 
    4792                 :             : 
    4793                 :             : /* ----------
    4794                 :             :  * exec_stmt_open           Execute an OPEN cursor statement
    4795                 :             :  * ----------
    4796                 :             :  */
    4797                 :             : static int
    4798                 :         125 : exec_stmt_open(PLpgSQL_execstate *estate, PLpgSQL_stmt_open *stmt)
    4799                 :             : {
    4800                 :             :     PLpgSQL_var *curvar;
    4801                 :         125 :     MemoryContext stmt_mcontext = NULL;
    4802                 :         125 :     char       *curname = NULL;
    4803                 :             :     PLpgSQL_expr *query;
    4804                 :             :     Portal      portal;
    4805                 :             :     ParamListInfo paramLI;
    4806                 :             : 
    4807                 :             :     /* ----------
    4808                 :             :      * Get the cursor variable and if it has an assigned name, check
    4809                 :             :      * that it's not in use currently.
    4810                 :             :      * ----------
    4811                 :             :      */
    4812                 :         125 :     curvar = (PLpgSQL_var *) (estate->datums[stmt->curvar]);
    4813         [ +  + ]:         125 :     if (!curvar->isnull)
    4814                 :             :     {
    4815                 :             :         MemoryContext oldcontext;
    4816                 :             : 
    4817                 :             :         /* We only need stmt_mcontext to hold the cursor name string */
    4818                 :          44 :         stmt_mcontext = get_stmt_mcontext(estate);
    4819                 :          44 :         oldcontext = MemoryContextSwitchTo(stmt_mcontext);
    4820                 :          44 :         curname = TextDatumGetCString(curvar->value);
    4821                 :          44 :         MemoryContextSwitchTo(oldcontext);
    4822                 :             : 
    4823         [ -  + ]:          44 :         if (SPI_cursor_find(curname) != NULL)
    4824         [ #  # ]:           0 :             ereport(ERROR,
    4825                 :             :                     (errcode(ERRCODE_DUPLICATE_CURSOR),
    4826                 :             :                      errmsg("cursor \"%s\" already in use", curname)));
    4827                 :             :     }
    4828                 :             : 
    4829                 :             :     /* ----------
    4830                 :             :      * Process the OPEN according to its type.
    4831                 :             :      * ----------
    4832                 :             :      */
    4833         [ +  + ]:         125 :     if (stmt->query != NULL)
    4834                 :             :     {
    4835                 :             :         /* ----------
    4836                 :             :          * This is an OPEN refcursor FOR SELECT ...
    4837                 :             :          *
    4838                 :             :          * We just make sure the query is planned. The real work is
    4839                 :             :          * done downstairs.
    4840                 :             :          * ----------
    4841                 :             :          */
    4842                 :          57 :         query = stmt->query;
    4843         [ +  + ]:          57 :         if (query->plan == NULL)
    4844                 :          45 :             exec_prepare_plan(estate, query, stmt->cursor_options);
    4845                 :             :     }
    4846         [ +  + ]:          68 :     else if (stmt->dynquery != NULL)
    4847                 :             :     {
    4848                 :             :         /* ----------
    4849                 :             :          * This is an OPEN refcursor FOR EXECUTE ...
    4850                 :             :          * ----------
    4851                 :             :          */
    4852                 :          12 :         portal = exec_dynquery_with_params(estate,
    4853                 :             :                                            stmt->dynquery,
    4854                 :             :                                            stmt->params,
    4855                 :             :                                            curname,
    4856                 :             :                                            stmt->cursor_options);
    4857                 :             : 
    4858                 :             :         /*
    4859                 :             :          * If cursor variable was NULL, store the generated portal name in it,
    4860                 :             :          * after verifying it's okay to assign to.
    4861                 :             :          *
    4862                 :             :          * Note: exec_dynquery_with_params already reset the stmt_mcontext, so
    4863                 :             :          * curname is a dangling pointer here; but testing it for nullness is
    4864                 :             :          * OK.
    4865                 :             :          */
    4866         [ +  - ]:          12 :         if (curname == NULL)
    4867                 :             :         {
    4868                 :          12 :             exec_check_assignable(estate, stmt->curvar);
    4869                 :          12 :             assign_text_var(estate, curvar, portal->name);
    4870                 :             :         }
    4871                 :             : 
    4872                 :          12 :         return PLPGSQL_RC_OK;
    4873                 :             :     }
    4874                 :             :     else
    4875                 :             :     {
    4876                 :             :         /* ----------
    4877                 :             :          * This is an OPEN cursor
    4878                 :             :          *
    4879                 :             :          * Note: parser should already have checked that statement supplies
    4880                 :             :          * args iff cursor needs them, but we check again to be safe.
    4881                 :             :          * ----------
    4882                 :             :          */
    4883         [ +  + ]:          56 :         if (stmt->argquery != NULL)
    4884                 :             :         {
    4885                 :             :             /* ----------
    4886                 :             :              * OPEN CURSOR with args.  We fake a SELECT ... INTO ...
    4887                 :             :              * statement to evaluate the args and put 'em into the
    4888                 :             :              * internal row.
    4889                 :             :              * ----------
    4890                 :             :              */
    4891                 :             :             PLpgSQL_stmt_execsql set_args;
    4892                 :             : 
    4893         [ -  + ]:          32 :             if (curvar->cursor_explicit_argrow < 0)
    4894         [ #  # ]:           0 :                 ereport(ERROR,
    4895                 :             :                         (errcode(ERRCODE_SYNTAX_ERROR),
    4896                 :             :                          errmsg("arguments given for cursor without arguments")));
    4897                 :             : 
    4898                 :          32 :             memset(&set_args, 0, sizeof(set_args));
    4899                 :          32 :             set_args.cmd_type = PLPGSQL_STMT_EXECSQL;
    4900                 :          32 :             set_args.lineno = stmt->lineno;
    4901                 :          32 :             set_args.sqlstmt = stmt->argquery;
    4902                 :          32 :             set_args.into = true;
    4903                 :             :             /* XXX historically this has not been STRICT */
    4904                 :          32 :             set_args.target = (PLpgSQL_variable *)
    4905                 :          32 :                 (estate->datums[curvar->cursor_explicit_argrow]);
    4906                 :             : 
    4907         [ -  + ]:          32 :             if (exec_stmt_execsql(estate, &set_args) != PLPGSQL_RC_OK)
    4908         [ #  # ]:           0 :                 elog(ERROR, "open cursor failed during argument processing");
    4909                 :             :         }
    4910                 :             :         else
    4911                 :             :         {
    4912         [ -  + ]:          24 :             if (curvar->cursor_explicit_argrow >= 0)
    4913         [ #  # ]:           0 :                 ereport(ERROR,
    4914                 :             :                         (errcode(ERRCODE_SYNTAX_ERROR),
    4915                 :             :                          errmsg("arguments required for cursor")));
    4916                 :             :         }
    4917                 :             : 
    4918                 :          52 :         query = curvar->cursor_explicit_expr;
    4919         [ +  + ]:          52 :         if (query->plan == NULL)
    4920                 :          40 :             exec_prepare_plan(estate, query, curvar->cursor_options);
    4921                 :             :     }
    4922                 :             : 
    4923                 :             :     /*
    4924                 :             :      * Set up ParamListInfo for this query
    4925                 :             :      */
    4926                 :         109 :     paramLI = setup_param_list(estate, query);
    4927                 :             : 
    4928                 :             :     /*
    4929                 :             :      * Open the cursor (the paramlist will get copied into the portal)
    4930                 :             :      */
    4931                 :         109 :     portal = SPI_cursor_open_with_paramlist(curname, query->plan,
    4932                 :             :                                             paramLI,
    4933                 :         109 :                                             estate->readonly_func);
    4934         [ -  + ]:          93 :     if (portal == NULL)
    4935         [ #  # ]:           0 :         elog(ERROR, "could not open cursor: %s",
    4936                 :             :              SPI_result_code_string(SPI_result));
    4937                 :             : 
    4938                 :             :     /*
    4939                 :             :      * If cursor variable was NULL, store the generated portal name in it,
    4940                 :             :      * after verifying it's okay to assign to.
    4941                 :             :      */
    4942         [ +  + ]:          93 :     if (curname == NULL)
    4943                 :             :     {
    4944                 :          65 :         exec_check_assignable(estate, stmt->curvar);
    4945                 :          61 :         assign_text_var(estate, curvar, portal->name);
    4946                 :             :     }
    4947                 :             : 
    4948                 :             :     /* If we had any transient data, clean it up */
    4949                 :          89 :     exec_eval_cleanup(estate);
    4950         [ +  + ]:          89 :     if (stmt_mcontext)
    4951                 :          28 :         MemoryContextReset(stmt_mcontext);
    4952                 :             : 
    4953                 :          89 :     return PLPGSQL_RC_OK;
    4954                 :             : }
    4955                 :             : 
    4956                 :             : 
    4957                 :             : /* ----------
    4958                 :             :  * exec_stmt_fetch          Fetch from a cursor into a target, or just
    4959                 :             :  *                          move the current position of the cursor
    4960                 :             :  * ----------
    4961                 :             :  */
    4962                 :             : static int
    4963                 :         249 : exec_stmt_fetch(PLpgSQL_execstate *estate, PLpgSQL_stmt_fetch *stmt)
    4964                 :             : {
    4965                 :             :     PLpgSQL_var *curvar;
    4966                 :         249 :     long        how_many = stmt->how_many;
    4967                 :             :     SPITupleTable *tuptab;
    4968                 :             :     Portal      portal;
    4969                 :             :     char       *curname;
    4970                 :             :     uint64      n;
    4971                 :             :     MemoryContext oldcontext;
    4972                 :             : 
    4973                 :             :     /* ----------
    4974                 :             :      * Get the portal of the cursor by name
    4975                 :             :      * ----------
    4976                 :             :      */
    4977                 :         249 :     curvar = (PLpgSQL_var *) (estate->datums[stmt->curvar]);
    4978         [ -  + ]:         249 :     if (curvar->isnull)
    4979         [ #  # ]:           0 :         ereport(ERROR,
    4980                 :             :                 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
    4981                 :             :                  errmsg("cursor variable \"%s\" is null", curvar->refname)));
    4982                 :             : 
    4983                 :             :     /* Use eval_mcontext for short-lived string */
    4984                 :         249 :     oldcontext = MemoryContextSwitchTo(get_eval_mcontext(estate));
    4985                 :         249 :     curname = TextDatumGetCString(curvar->value);
    4986                 :         249 :     MemoryContextSwitchTo(oldcontext);
    4987                 :             : 
    4988                 :         249 :     portal = SPI_cursor_find(curname);
    4989         [ -  + ]:         249 :     if (portal == NULL)
    4990         [ #  # ]:           0 :         ereport(ERROR,
    4991                 :             :                 (errcode(ERRCODE_UNDEFINED_CURSOR),
    4992                 :             :                  errmsg("cursor \"%s\" does not exist", curname)));
    4993                 :             : 
    4994                 :             :     /* Calculate position for FETCH_RELATIVE or FETCH_ABSOLUTE */
    4995         [ +  + ]:         249 :     if (stmt->expr)
    4996                 :             :     {
    4997                 :             :         bool        isnull;
    4998                 :             : 
    4999                 :             :         /* XXX should be doing this in LONG not INT width */
    5000                 :          44 :         how_many = exec_eval_integer(estate, stmt->expr, &isnull);
    5001                 :             : 
    5002         [ -  + ]:          44 :         if (isnull)
    5003         [ #  # ]:           0 :             ereport(ERROR,
    5004                 :             :                     (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
    5005                 :             :                      errmsg("relative or absolute cursor position is null")));
    5006                 :             : 
    5007                 :          44 :         exec_eval_cleanup(estate);
    5008                 :             :     }
    5009                 :             : 
    5010         [ +  + ]:         249 :     if (!stmt->is_move)
    5011                 :             :     {
    5012                 :             :         PLpgSQL_variable *target;
    5013                 :             : 
    5014                 :             :         /* ----------
    5015                 :             :          * Fetch 1 tuple from the cursor
    5016                 :             :          * ----------
    5017                 :             :          */
    5018                 :         221 :         SPI_scroll_cursor_fetch(portal, stmt->direction, how_many);
    5019                 :         213 :         tuptab = SPI_tuptable;
    5020                 :         213 :         n = SPI_processed;
    5021                 :             : 
    5022                 :             :         /* ----------
    5023                 :             :          * Set the target appropriately.
    5024                 :             :          * ----------
    5025                 :             :          */
    5026                 :         213 :         target = (PLpgSQL_variable *) estate->datums[stmt->target->dno];
    5027         [ +  + ]:         213 :         if (n == 0)
    5028                 :          32 :             exec_move_row(estate, target, NULL, tuptab->tupdesc);
    5029                 :             :         else
    5030                 :         181 :             exec_move_row(estate, target, tuptab->vals[0], tuptab->tupdesc);
    5031                 :             : 
    5032                 :         213 :         exec_eval_cleanup(estate);
    5033                 :         213 :         SPI_freetuptable(tuptab);
    5034                 :             :     }
    5035                 :             :     else
    5036                 :             :     {
    5037                 :             :         /* Move the cursor */
    5038                 :          28 :         SPI_scroll_cursor_move(portal, stmt->direction, how_many);
    5039                 :          28 :         n = SPI_processed;
    5040                 :             :     }
    5041                 :             : 
    5042                 :             :     /* Set the ROW_COUNT and the global FOUND variable appropriately. */
    5043                 :         241 :     estate->eval_processed = n;
    5044                 :         241 :     exec_set_found(estate, n != 0);
    5045                 :             : 
    5046                 :         241 :     return PLPGSQL_RC_OK;
    5047                 :             : }
    5048                 :             : 
    5049                 :             : /* ----------
    5050                 :             :  * exec_stmt_close          Close a cursor
    5051                 :             :  * ----------
    5052                 :             :  */
    5053                 :             : static int
    5054                 :          52 : exec_stmt_close(PLpgSQL_execstate *estate, PLpgSQL_stmt_close *stmt)
    5055                 :             : {
    5056                 :             :     PLpgSQL_var *curvar;
    5057                 :             :     Portal      portal;
    5058                 :             :     char       *curname;
    5059                 :             :     MemoryContext oldcontext;
    5060                 :             : 
    5061                 :             :     /* ----------
    5062                 :             :      * Get the portal of the cursor by name
    5063                 :             :      * ----------
    5064                 :             :      */
    5065                 :          52 :     curvar = (PLpgSQL_var *) (estate->datums[stmt->curvar]);
    5066         [ -  + ]:          52 :     if (curvar->isnull)
    5067         [ #  # ]:           0 :         ereport(ERROR,
    5068                 :             :                 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
    5069                 :             :                  errmsg("cursor variable \"%s\" is null", curvar->refname)));
    5070                 :             : 
    5071                 :             :     /* Use eval_mcontext for short-lived string */
    5072                 :          52 :     oldcontext = MemoryContextSwitchTo(get_eval_mcontext(estate));
    5073                 :          52 :     curname = TextDatumGetCString(curvar->value);
    5074                 :          52 :     MemoryContextSwitchTo(oldcontext);
    5075                 :             : 
    5076                 :          52 :     portal = SPI_cursor_find(curname);
    5077         [ -  + ]:          52 :     if (portal == NULL)
    5078         [ #  # ]:           0 :         ereport(ERROR,
    5079                 :             :                 (errcode(ERRCODE_UNDEFINED_CURSOR),
    5080                 :             :                  errmsg("cursor \"%s\" does not exist", curname)));
    5081                 :             : 
    5082                 :             :     /* ----------
    5083                 :             :      * And close it.
    5084                 :             :      * ----------
    5085                 :             :      */
    5086                 :          52 :     SPI_cursor_close(portal);
    5087                 :             : 
    5088                 :          52 :     return PLPGSQL_RC_OK;
    5089                 :             : }
    5090                 :             : 
    5091                 :             : /*
    5092                 :             :  * exec_stmt_commit
    5093                 :             :  *
    5094                 :             :  * Commit the transaction.
    5095                 :             :  */
    5096                 :             : static int
    5097                 :        2162 : exec_stmt_commit(PLpgSQL_execstate *estate, PLpgSQL_stmt_commit *stmt)
    5098                 :             : {
    5099         [ +  + ]:        2162 :     if (stmt->chain)
    5100                 :          74 :         SPI_commit_and_chain();
    5101                 :             :     else
    5102                 :        2088 :         SPI_commit();
    5103                 :             : 
    5104                 :             :     /*
    5105                 :             :      * We need to build new simple-expression infrastructure, since the old
    5106                 :             :      * data structures are gone.
    5107                 :             :      */
    5108                 :        2151 :     estate->simple_eval_estate = NULL;
    5109                 :        2151 :     estate->simple_eval_resowner = NULL;
    5110                 :        2151 :     plpgsql_create_econtext(estate);
    5111                 :             : 
    5112                 :        2151 :     return PLPGSQL_RC_OK;
    5113                 :             : }
    5114                 :             : 
    5115                 :             : /*
    5116                 :             :  * exec_stmt_rollback
    5117                 :             :  *
    5118                 :             :  * Abort the transaction.
    5119                 :             :  */
    5120                 :             : static int
    5121                 :          98 : exec_stmt_rollback(PLpgSQL_execstate *estate, PLpgSQL_stmt_rollback *stmt)
    5122                 :             : {
    5123         [ +  + ]:          98 :     if (stmt->chain)
    5124                 :          38 :         SPI_rollback_and_chain();
    5125                 :             :     else
    5126                 :          60 :         SPI_rollback();
    5127                 :             : 
    5128                 :             :     /*
    5129                 :             :      * We need to build new simple-expression infrastructure, since the old
    5130                 :             :      * data structures are gone.
    5131                 :             :      */
    5132                 :          95 :     estate->simple_eval_estate = NULL;
    5133                 :          95 :     estate->simple_eval_resowner = NULL;
    5134                 :          95 :     plpgsql_create_econtext(estate);
    5135                 :             : 
    5136                 :          95 :     return PLPGSQL_RC_OK;
    5137                 :             : }
    5138                 :             : 
    5139                 :             : /* ----------
    5140                 :             :  * exec_assign_expr         Put an expression's result into a variable.
    5141                 :             :  * ----------
    5142                 :             :  */
    5143                 :             : static void
    5144                 :       70787 : exec_assign_expr(PLpgSQL_execstate *estate, PLpgSQL_datum *target,
    5145                 :             :                  PLpgSQL_expr *expr)
    5146                 :             : {
    5147                 :             :     Datum       value;
    5148                 :             :     bool        isnull;
    5149                 :             :     Oid         valtype;
    5150                 :             :     int32       valtypmod;
    5151                 :             : 
    5152                 :             :     /*
    5153                 :             :      * If first time through, create a plan for this expression.
    5154                 :             :      */
    5155         [ +  + ]:       70787 :     if (expr->plan == NULL)
    5156                 :        3143 :         exec_prepare_plan(estate, expr, 0);
    5157                 :             : 
    5158                 :       70765 :     value = exec_eval_expr(estate, expr, &isnull, &valtype, &valtypmod);
    5159                 :       70642 :     exec_assign_value(estate, target, value, isnull, valtype, valtypmod);
    5160                 :       70570 :     exec_eval_cleanup(estate);
    5161                 :       70570 : }
    5162                 :             : 
    5163                 :             : 
    5164                 :             : /* ----------
    5165                 :             :  * exec_assign_c_string     Put a C string into a text variable.
    5166                 :             :  *
    5167                 :             :  * We take a NULL pointer as signifying empty string, not SQL null.
    5168                 :             :  *
    5169                 :             :  * As with the underlying exec_assign_value, caller is expected to do
    5170                 :             :  * exec_eval_cleanup later.
    5171                 :             :  * ----------
    5172                 :             :  */
    5173                 :             : static void
    5174                 :          85 : exec_assign_c_string(PLpgSQL_execstate *estate, PLpgSQL_datum *target,
    5175                 :             :                      const char *str)
    5176                 :             : {
    5177                 :             :     text       *value;
    5178                 :             :     MemoryContext oldcontext;
    5179                 :             : 
    5180                 :             :     /* Use eval_mcontext for short-lived text value */
    5181                 :          85 :     oldcontext = MemoryContextSwitchTo(get_eval_mcontext(estate));
    5182         [ +  - ]:          85 :     if (str != NULL)
    5183                 :          85 :         value = cstring_to_text(str);
    5184                 :             :     else
    5185                 :           0 :         value = cstring_to_text("");
    5186                 :          85 :     MemoryContextSwitchTo(oldcontext);
    5187                 :             : 
    5188                 :          85 :     exec_assign_value(estate, target, PointerGetDatum(value), false,
    5189                 :             :                       TEXTOID, -1);
    5190                 :          85 : }
    5191                 :             : 
    5192                 :             : 
    5193                 :             : /* ----------
    5194                 :             :  * exec_assign_value            Put a value into a target datum
    5195                 :             :  *
    5196                 :             :  * Note: in some code paths, this will leak memory in the eval_mcontext;
    5197                 :             :  * we assume that will be cleaned up later by exec_eval_cleanup.  We cannot
    5198                 :             :  * call exec_eval_cleanup here for fear of destroying the input Datum value.
    5199                 :             :  * ----------
    5200                 :             :  */
    5201                 :             : static void
    5202                 :      120887 : exec_assign_value(PLpgSQL_execstate *estate,
    5203                 :             :                   PLpgSQL_datum *target,
    5204                 :             :                   Datum value, bool isNull,
    5205                 :             :                   Oid valtype, int32 valtypmod)
    5206                 :             : {
    5207   [ +  +  +  +  :      120887 :     switch (target->dtype)
                      - ]
    5208                 :             :     {
    5209                 :      118649 :         case PLPGSQL_DTYPE_VAR:
    5210                 :             :         case PLPGSQL_DTYPE_PROMISE:
    5211                 :             :             {
    5212                 :             :                 /*
    5213                 :             :                  * Target is a variable
    5214                 :             :                  */
    5215                 :      118649 :                 PLpgSQL_var *var = (PLpgSQL_var *) target;
    5216                 :             :                 Datum       newvalue;
    5217                 :             : 
    5218                 :      118649 :                 newvalue = exec_cast_value(estate,
    5219                 :             :                                            value,
    5220                 :             :                                            &isNull,
    5221                 :             :                                            valtype,
    5222                 :             :                                            valtypmod,
    5223                 :      118649 :                                            var->datatype->typoid,
    5224                 :      118649 :                                            var->datatype->atttypmod);
    5225                 :             : 
    5226   [ +  +  +  + ]:      118629 :                 if (isNull && var->notnull)
    5227         [ +  - ]:           6 :                     ereport(ERROR,
    5228                 :             :                             (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
    5229                 :             :                              errmsg("null value cannot be assigned to variable \"%s\" declared NOT NULL",
    5230                 :             :                                     var->refname)));
    5231                 :             : 
    5232                 :             :                 /*
    5233                 :             :                  * If type is by-reference, copy the new value (which is
    5234                 :             :                  * probably in the eval_mcontext) into the procedure's main
    5235                 :             :                  * memory context.  But if it's a read/write reference to an
    5236                 :             :                  * expanded object, no physical copy needs to happen; at most
    5237                 :             :                  * we need to reparent the object's memory context.
    5238                 :             :                  *
    5239                 :             :                  * If it's an array, we force the value to be stored in R/W
    5240                 :             :                  * expanded form.  This wins if the function later does, say,
    5241                 :             :                  * a lot of array subscripting operations on the variable, and
    5242                 :             :                  * otherwise might lose.  We might need to use a different
    5243                 :             :                  * heuristic, but it's too soon to tell.  Also, are there
    5244                 :             :                  * cases where it'd be useful to force non-array values into
    5245                 :             :                  * expanded form?
    5246                 :             :                  */
    5247   [ +  +  +  + ]:      118623 :                 if (!var->datatype->typbyval && !isNull)
    5248                 :             :                 {
    5249         [ +  + ]:       77894 :                     if (var->datatype->typisarray &&
    5250         [ +  + ]:        6974 :                         !VARATT_IS_EXTERNAL_EXPANDED_RW(DatumGetPointer(newvalue)))
    5251                 :             :                     {
    5252                 :             :                         /* array and not already R/W, so apply expand_array */
    5253                 :        6849 :                         newvalue = expand_array(newvalue,
    5254                 :             :                                                 estate->datum_context,
    5255                 :             :                                                 NULL);
    5256                 :             :                     }
    5257                 :             :                     else
    5258                 :             :                     {
    5259                 :             :                         /* else transfer value if R/W, else just datumCopy */
    5260                 :       71045 :                         newvalue = datumTransfer(newvalue,
    5261                 :             :                                                  false,
    5262                 :       71045 :                                                  var->datatype->typlen);
    5263                 :             :                     }
    5264                 :             :                 }
    5265                 :             : 
    5266                 :             :                 /*
    5267                 :             :                  * Now free the old value, if any, and assign the new one. But
    5268                 :             :                  * skip the assignment if old and new values are the same.
    5269                 :             :                  * Note that for expanded objects, this test is necessary and
    5270                 :             :                  * cannot reliably be made any earlier; we have to be looking
    5271                 :             :                  * at the object's standard R/W pointer to be sure pointer
    5272                 :             :                  * equality is meaningful.
    5273                 :             :                  *
    5274                 :             :                  * Also, if it's a promise variable, we should disarm the
    5275                 :             :                  * promise in any case --- otherwise, assigning null to an
    5276                 :             :                  * armed promise variable would fail to disarm the promise.
    5277                 :             :                  */
    5278   [ +  +  +  +  :      118623 :                 if (var->value != newvalue || var->isnull || isNull)
                   +  + ]
    5279                 :      116899 :                     assign_simple_var(estate, var, newvalue, isNull,
    5280   [ +  +  +  + ]:      116899 :                                       (!var->datatype->typbyval && !isNull));
    5281                 :             :                 else
    5282                 :        1724 :                     var->promise = PLPGSQL_PROMISE_NONE;
    5283                 :      118623 :                 break;
    5284                 :             :             }
    5285                 :             : 
    5286                 :          28 :         case PLPGSQL_DTYPE_ROW:
    5287                 :             :             {
    5288                 :             :                 /*
    5289                 :             :                  * Target is a row variable
    5290                 :             :                  */
    5291                 :          28 :                 PLpgSQL_row *row = (PLpgSQL_row *) target;
    5292                 :             : 
    5293         [ -  + ]:          28 :                 if (isNull)
    5294                 :             :                 {
    5295                 :             :                     /* If source is null, just assign nulls to the row */
    5296                 :           0 :                     exec_move_row(estate, (PLpgSQL_variable *) row,
    5297                 :             :                                   NULL, NULL);
    5298                 :             :                 }
    5299                 :             :                 else
    5300                 :             :                 {
    5301                 :             :                     /* Source must be of RECORD or composite type */
    5302         [ -  + ]:          28 :                     if (!type_is_rowtype(valtype))
    5303         [ #  # ]:           0 :                         ereport(ERROR,
    5304                 :             :                                 (errcode(ERRCODE_DATATYPE_MISMATCH),
    5305                 :             :                                  errmsg("cannot assign non-composite value to a row variable")));
    5306                 :          28 :                     exec_move_row_from_datum(estate, (PLpgSQL_variable *) row,
    5307                 :             :                                              value);
    5308                 :             :                 }
    5309                 :          28 :                 break;
    5310                 :             :             }
    5311                 :             : 
    5312                 :         690 :         case PLPGSQL_DTYPE_REC:
    5313                 :             :             {
    5314                 :             :                 /*
    5315                 :             :                  * Target is a record variable
    5316                 :             :                  */
    5317                 :         690 :                 PLpgSQL_rec *rec = (PLpgSQL_rec *) target;
    5318                 :             : 
    5319         [ +  + ]:         690 :                 if (isNull)
    5320                 :             :                 {
    5321         [ +  + ]:          89 :                     if (rec->notnull)
    5322         [ +  - ]:           4 :                         ereport(ERROR,
    5323                 :             :                                 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
    5324                 :             :                                  errmsg("null value cannot be assigned to variable \"%s\" declared NOT NULL",
    5325                 :             :                                         rec->refname)));
    5326                 :             : 
    5327                 :             :                     /* Set variable to a simple NULL */
    5328                 :          85 :                     exec_move_row(estate, (PLpgSQL_variable *) rec,
    5329                 :             :                                   NULL, NULL);
    5330                 :             :                 }
    5331                 :             :                 else
    5332                 :             :                 {
    5333                 :             :                     /* Source must be of RECORD or composite type */
    5334         [ -  + ]:         601 :                     if (!type_is_rowtype(valtype))
    5335         [ #  # ]:           0 :                         ereport(ERROR,
    5336                 :             :                                 (errcode(ERRCODE_DATATYPE_MISMATCH),
    5337                 :             :                                  errmsg("cannot assign non-composite value to a record variable")));
    5338                 :         601 :                     exec_move_row_from_datum(estate, (PLpgSQL_variable *) rec,
    5339                 :             :                                              value);
    5340                 :             :                 }
    5341                 :         639 :                 break;
    5342                 :             :             }
    5343                 :             : 
    5344                 :        1520 :         case PLPGSQL_DTYPE_RECFIELD:
    5345                 :             :             {
    5346                 :             :                 /*
    5347                 :             :                  * Target is a field of a record
    5348                 :             :                  */
    5349                 :        1520 :                 PLpgSQL_recfield *recfield = (PLpgSQL_recfield *) target;
    5350                 :             :                 PLpgSQL_rec *rec;
    5351                 :             :                 ExpandedRecordHeader *erh;
    5352                 :             : 
    5353                 :        1520 :                 rec = (PLpgSQL_rec *) (estate->datums[recfield->recparentno]);
    5354                 :        1520 :                 erh = rec->erh;
    5355                 :             : 
    5356                 :             :                 /*
    5357                 :             :                  * If record variable is NULL, instantiate it if it has a
    5358                 :             :                  * named composite type, else complain.  (This won't change
    5359                 :             :                  * the logical state of the record, but if we successfully
    5360                 :             :                  * assign below, the unassigned fields will all become NULLs.)
    5361                 :             :                  */
    5362         [ +  + ]:        1520 :                 if (erh == NULL)
    5363                 :             :                 {
    5364                 :          41 :                     instantiate_empty_record_variable(estate, rec);
    5365                 :          40 :                     erh = rec->erh;
    5366                 :             :                 }
    5367                 :             : 
    5368                 :             :                 /*
    5369                 :             :                  * Look up the field's properties if we have not already, or
    5370                 :             :                  * if the tuple descriptor ID changed since last time.
    5371                 :             :                  */
    5372         [ +  + ]:        1519 :                 if (unlikely(recfield->rectupledescid != erh->er_tupdesc_id))
    5373                 :             :                 {
    5374         [ +  + ]:          30 :                     if (!expanded_record_lookup_field(erh,
    5375                 :          30 :                                                       recfield->fieldname,
    5376                 :             :                                                       &recfield->finfo))
    5377         [ +  - ]:           1 :                         ereport(ERROR,
    5378                 :             :                                 (errcode(ERRCODE_UNDEFINED_COLUMN),
    5379                 :             :                                  errmsg("record \"%s\" has no field \"%s\"",
    5380                 :             :                                         rec->refname, recfield->fieldname)));
    5381                 :          29 :                     recfield->rectupledescid = erh->er_tupdesc_id;
    5382                 :             :                 }
    5383                 :             : 
    5384                 :             :                 /* Cast the new value to the right type, if needed. */
    5385                 :        1518 :                 value = exec_cast_value(estate,
    5386                 :             :                                         value,
    5387                 :             :                                         &isNull,
    5388                 :             :                                         valtype,
    5389                 :             :                                         valtypmod,
    5390                 :             :                                         recfield->finfo.ftypeid,
    5391                 :             :                                         recfield->finfo.ftypmod);
    5392                 :             : 
    5393                 :             :                 /*
    5394                 :             :                  * Edge case: the cast step can run user-defined code, which
    5395                 :             :                  * could call the current plpgsql function recursively, and
    5396                 :             :                  * potentially change the recfield datum underneath us.  If we
    5397                 :             :                  * see the tupdesc ID change, repeat the lookup, and allow it
    5398                 :             :                  * so long as the field datatype didn't change.
    5399                 :             :                  */
    5400         [ -  + ]:        1518 :                 if (unlikely(recfield->rectupledescid != erh->er_tupdesc_id))
    5401                 :             :                 {
    5402                 :           0 :                     ExpandedRecordFieldInfo save_finfo = recfield->finfo;
    5403                 :             : 
    5404         [ #  # ]:           0 :                     if (!expanded_record_lookup_field(erh,
    5405                 :           0 :                                                       recfield->fieldname,
    5406                 :             :                                                       &recfield->finfo))
    5407         [ #  # ]:           0 :                         ereport(ERROR,
    5408                 :             :                                 (errcode(ERRCODE_UNDEFINED_COLUMN),
    5409                 :             :                                  errmsg("record \"%s\" has no field \"%s\"",
    5410                 :             :                                         rec->refname, recfield->fieldname)));
    5411                 :           0 :                     recfield->rectupledescid = erh->er_tupdesc_id;
    5412         [ #  # ]:           0 :                     if (save_finfo.ftypeid != recfield->finfo.ftypeid ||
    5413         [ #  # ]:           0 :                         save_finfo.ftypmod != recfield->finfo.ftypmod)
    5414         [ #  # ]:           0 :                         ereport(ERROR,
    5415                 :             :                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    5416                 :             :                                  errmsg("record \"%s\" field \"%s\" changed type during assignment",
    5417                 :             :                                         rec->refname, recfield->fieldname)));
    5418                 :             :                 }
    5419                 :             : 
    5420                 :             :                 /* We don't support assignments to system columns. */
    5421         [ -  + ]:        1518 :                 if (recfield->finfo.fnumber <= 0)
    5422         [ #  # ]:           0 :                     ereport(ERROR,
    5423                 :             :                             (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    5424                 :             :                              errmsg("cannot assign to system column \"%s\"",
    5425                 :             :                                     recfield->fieldname)));
    5426                 :             : 
    5427                 :             :                 /* All OK, assign it. */
    5428                 :        1518 :                 expanded_record_set_field(erh, recfield->finfo.fnumber,
    5429                 :             :                                           value, isNull, !estate->atomic);
    5430                 :        1515 :                 break;
    5431                 :             :             }
    5432                 :             : 
    5433                 :           0 :         default:
    5434         [ #  # ]:           0 :             elog(ERROR, "unrecognized dtype: %d", target->dtype);
    5435                 :             :     }
    5436                 :      120805 : }
    5437                 :             : 
    5438                 :             : /*
    5439                 :             :  * exec_eval_datum              Get current value of a PLpgSQL_datum
    5440                 :             :  *
    5441                 :             :  * The type oid, typmod, value in Datum format, and null flag are returned.
    5442                 :             :  *
    5443                 :             :  * At present this doesn't handle PLpgSQL_expr datums; that's not needed
    5444                 :             :  * because we never pass references to such datums to SPI.
    5445                 :             :  *
    5446                 :             :  * NOTE: the returned Datum points right at the stored value in the case of
    5447                 :             :  * pass-by-reference datatypes.  Generally callers should take care not to
    5448                 :             :  * modify the stored value.  Some callers intentionally manipulate variables
    5449                 :             :  * referenced by R/W expanded pointers, though; it is those callers'
    5450                 :             :  * responsibility that the results are semantically OK.
    5451                 :             :  *
    5452                 :             :  * In some cases we have to palloc a return value, and in such cases we put
    5453                 :             :  * it into the estate's eval_mcontext.
    5454                 :             :  */
    5455                 :             : static void
    5456                 :       44466 : exec_eval_datum(PLpgSQL_execstate *estate,
    5457                 :             :                 PLpgSQL_datum *datum,
    5458                 :             :                 Oid *typeid,
    5459                 :             :                 int32 *typetypmod,
    5460                 :             :                 Datum *value,
    5461                 :             :                 bool *isnull)
    5462                 :             : {
    5463                 :             :     MemoryContext oldcontext;
    5464                 :             : 
    5465   [ +  +  +  +  :       44466 :     switch (datum->dtype)
                   +  - ]
    5466                 :             :     {
    5467                 :       14721 :         case PLPGSQL_DTYPE_PROMISE:
    5468                 :             :             /* fulfill promise if needed, then handle like regular var */
    5469                 :       14721 :             plpgsql_fulfill_promise(estate, (PLpgSQL_var *) datum);
    5470                 :             : 
    5471                 :             :             pg_fallthrough;
    5472                 :             : 
    5473                 :       27710 :         case PLPGSQL_DTYPE_VAR:
    5474                 :             :             {
    5475                 :       27710 :                 PLpgSQL_var *var = (PLpgSQL_var *) datum;
    5476                 :             : 
    5477                 :       27710 :                 *typeid = var->datatype->typoid;
    5478                 :       27710 :                 *typetypmod = var->datatype->atttypmod;
    5479                 :       27710 :                 *value = var->value;
    5480                 :       27710 :                 *isnull = var->isnull;
    5481                 :       27710 :                 break;
    5482                 :             :             }
    5483                 :             : 
    5484                 :        3258 :         case PLPGSQL_DTYPE_ROW:
    5485                 :             :             {
    5486                 :        3258 :                 PLpgSQL_row *row = (PLpgSQL_row *) datum;
    5487                 :             :                 HeapTuple   tup;
    5488                 :             : 
    5489                 :             :                 /* We get here if there are multiple OUT parameters */
    5490         [ -  + ]:        3258 :                 if (!row->rowtupdesc)    /* should not happen */
    5491         [ #  # ]:           0 :                     elog(ERROR, "row variable has no tupdesc");
    5492                 :             :                 /* Make sure we have a valid type/typmod setting */
    5493                 :        3258 :                 BlessTupleDesc(row->rowtupdesc);
    5494                 :        3258 :                 oldcontext = MemoryContextSwitchTo(get_eval_mcontext(estate));
    5495                 :        3258 :                 tup = make_tuple_from_row(estate, row, row->rowtupdesc);
    5496         [ -  + ]:        3258 :                 if (tup == NULL)    /* should not happen */
    5497         [ #  # ]:           0 :                     elog(ERROR, "row not compatible with its own tupdesc");
    5498                 :        3258 :                 *typeid = row->rowtupdesc->tdtypeid;
    5499                 :        3258 :                 *typetypmod = row->rowtupdesc->tdtypmod;
    5500                 :        3258 :                 *value = HeapTupleGetDatum(tup);
    5501                 :        3258 :                 *isnull = false;
    5502                 :        3258 :                 MemoryContextSwitchTo(oldcontext);
    5503                 :        3258 :                 break;
    5504                 :             :             }
    5505                 :             : 
    5506                 :       11930 :         case PLPGSQL_DTYPE_REC:
    5507                 :             :             {
    5508                 :       11930 :                 PLpgSQL_rec *rec = (PLpgSQL_rec *) datum;
    5509                 :             : 
    5510         [ +  + ]:       11930 :                 if (rec->erh == NULL)
    5511                 :             :                 {
    5512                 :             :                     /* Treat uninstantiated record as a simple NULL */
    5513                 :         124 :                     *value = (Datum) 0;
    5514                 :         124 :                     *isnull = true;
    5515                 :             :                     /* Report variable's declared type */
    5516                 :         124 :                     *typeid = rec->rectypeid;
    5517                 :         124 :                     *typetypmod = -1;
    5518                 :             :                 }
    5519                 :             :                 else
    5520                 :             :                 {
    5521         [ +  + ]:       11806 :                     if (ExpandedRecordIsEmpty(rec->erh))
    5522                 :             :                     {
    5523                 :             :                         /* Empty record is also a NULL */
    5524                 :          99 :                         *value = (Datum) 0;
    5525                 :          99 :                         *isnull = true;
    5526                 :             :                     }
    5527                 :             :                     else
    5528                 :             :                     {
    5529                 :       11707 :                         *value = ExpandedRecordGetDatum(rec->erh);
    5530                 :       11707 :                         *isnull = false;
    5531                 :             :                     }
    5532         [ +  + ]:       11806 :                     if (rec->rectypeid != RECORDOID)
    5533                 :             :                     {
    5534                 :             :                         /* Report variable's declared type, if not RECORD */
    5535                 :        1357 :                         *typeid = rec->rectypeid;
    5536                 :        1357 :                         *typetypmod = -1;
    5537                 :             :                     }
    5538                 :             :                     else
    5539                 :             :                     {
    5540                 :             :                         /* Report record's actual type if declared RECORD */
    5541                 :       10449 :                         *typeid = rec->erh->er_typeid;
    5542                 :       10449 :                         *typetypmod = rec->erh->er_typmod;
    5543                 :             :                     }
    5544                 :             :                 }
    5545                 :       11930 :                 break;
    5546                 :             :             }
    5547                 :             : 
    5548                 :        1568 :         case PLPGSQL_DTYPE_RECFIELD:
    5549                 :             :             {
    5550                 :        1568 :                 PLpgSQL_recfield *recfield = (PLpgSQL_recfield *) datum;
    5551                 :             :                 PLpgSQL_rec *rec;
    5552                 :             :                 ExpandedRecordHeader *erh;
    5553                 :             : 
    5554                 :        1568 :                 rec = (PLpgSQL_rec *) (estate->datums[recfield->recparentno]);
    5555                 :        1568 :                 erh = rec->erh;
    5556                 :             : 
    5557                 :             :                 /*
    5558                 :             :                  * If record variable is NULL, instantiate it if it has a
    5559                 :             :                  * named composite type, else complain.  (This won't change
    5560                 :             :                  * the logical state of the record: it's still NULL.)
    5561                 :             :                  */
    5562         [ -  + ]:        1568 :                 if (erh == NULL)
    5563                 :             :                 {
    5564                 :           0 :                     instantiate_empty_record_variable(estate, rec);
    5565                 :           0 :                     erh = rec->erh;
    5566                 :             :                 }
    5567                 :             : 
    5568                 :             :                 /*
    5569                 :             :                  * Look up the field's properties if we have not already, or
    5570                 :             :                  * if the tuple descriptor ID changed since last time.
    5571                 :             :                  */
    5572         [ -  + ]:        1568 :                 if (unlikely(recfield->rectupledescid != erh->er_tupdesc_id))
    5573                 :             :                 {
    5574         [ #  # ]:           0 :                     if (!expanded_record_lookup_field(erh,
    5575                 :           0 :                                                       recfield->fieldname,
    5576                 :             :                                                       &recfield->finfo))
    5577         [ #  # ]:           0 :                         ereport(ERROR,
    5578                 :             :                                 (errcode(ERRCODE_UNDEFINED_COLUMN),
    5579                 :             :                                  errmsg("record \"%s\" has no field \"%s\"",
    5580                 :             :                                         rec->refname, recfield->fieldname)));
    5581                 :           0 :                     recfield->rectupledescid = erh->er_tupdesc_id;
    5582                 :             :                 }
    5583                 :             : 
    5584                 :             :                 /* Report type data. */
    5585                 :        1568 :                 *typeid = recfield->finfo.ftypeid;
    5586                 :        1568 :                 *typetypmod = recfield->finfo.ftypmod;
    5587                 :             : 
    5588                 :             :                 /* And fetch the field value. */
    5589                 :        1568 :                 *value = expanded_record_get_field(erh,
    5590                 :             :                                                    recfield->finfo.fnumber,
    5591                 :             :                                                    isnull);
    5592                 :        1568 :                 break;
    5593                 :             :             }
    5594                 :             : 
    5595                 :           0 :         default:
    5596         [ #  # ]:           0 :             elog(ERROR, "unrecognized dtype: %d", datum->dtype);
    5597                 :             :     }
    5598                 :       44466 : }
    5599                 :             : 
    5600                 :             : /*
    5601                 :             :  * plpgsql_exec_get_datum_type              Get datatype of a PLpgSQL_datum
    5602                 :             :  *
    5603                 :             :  * This is the same logic as in exec_eval_datum, but we skip acquiring
    5604                 :             :  * the actual value of the variable.  Also, needn't support DTYPE_ROW.
    5605                 :             :  */
    5606                 :             : Oid
    5607                 :         101 : plpgsql_exec_get_datum_type(PLpgSQL_execstate *estate,
    5608                 :             :                             PLpgSQL_datum *datum)
    5609                 :             : {
    5610                 :             :     Oid         typeid;
    5611                 :             : 
    5612   [ +  -  -  - ]:         101 :     switch (datum->dtype)
    5613                 :             :     {
    5614                 :         101 :         case PLPGSQL_DTYPE_VAR:
    5615                 :             :         case PLPGSQL_DTYPE_PROMISE:
    5616                 :             :             {
    5617                 :         101 :                 PLpgSQL_var *var = (PLpgSQL_var *) datum;
    5618                 :             : 
    5619                 :         101 :                 typeid = var->datatype->typoid;
    5620                 :         101 :                 break;
    5621                 :             :             }
    5622                 :             : 
    5623                 :           0 :         case PLPGSQL_DTYPE_REC:
    5624                 :             :             {
    5625                 :           0 :                 PLpgSQL_rec *rec = (PLpgSQL_rec *) datum;
    5626                 :             : 
    5627   [ #  #  #  # ]:           0 :                 if (rec->erh == NULL || rec->rectypeid != RECORDOID)
    5628                 :             :                 {
    5629                 :             :                     /* Report variable's declared type */
    5630                 :           0 :                     typeid = rec->rectypeid;
    5631                 :             :                 }
    5632                 :             :                 else
    5633                 :             :                 {
    5634                 :             :                     /* Report record's actual type if declared RECORD */
    5635                 :           0 :                     typeid = rec->erh->er_typeid;
    5636                 :             :                 }
    5637                 :           0 :                 break;
    5638                 :             :             }
    5639                 :             : 
    5640                 :           0 :         case PLPGSQL_DTYPE_RECFIELD:
    5641                 :             :             {
    5642                 :           0 :                 PLpgSQL_recfield *recfield = (PLpgSQL_recfield *) datum;
    5643                 :             :                 PLpgSQL_rec *rec;
    5644                 :             : 
    5645                 :           0 :                 rec = (PLpgSQL_rec *) (estate->datums[recfield->recparentno]);
    5646                 :             : 
    5647                 :             :                 /*
    5648                 :             :                  * If record variable is NULL, instantiate it if it has a
    5649                 :             :                  * named composite type, else complain.  (This won't change
    5650                 :             :                  * the logical state of the record: it's still NULL.)
    5651                 :             :                  */
    5652         [ #  # ]:           0 :                 if (rec->erh == NULL)
    5653                 :           0 :                     instantiate_empty_record_variable(estate, rec);
    5654                 :             : 
    5655                 :             :                 /*
    5656                 :             :                  * Look up the field's properties if we have not already, or
    5657                 :             :                  * if the tuple descriptor ID changed since last time.
    5658                 :             :                  */
    5659         [ #  # ]:           0 :                 if (unlikely(recfield->rectupledescid != rec->erh->er_tupdesc_id))
    5660                 :             :                 {
    5661         [ #  # ]:           0 :                     if (!expanded_record_lookup_field(rec->erh,
    5662                 :           0 :                                                       recfield->fieldname,
    5663                 :             :                                                       &recfield->finfo))
    5664         [ #  # ]:           0 :                         ereport(ERROR,
    5665                 :             :                                 (errcode(ERRCODE_UNDEFINED_COLUMN),
    5666                 :             :                                  errmsg("record \"%s\" has no field \"%s\"",
    5667                 :             :                                         rec->refname, recfield->fieldname)));
    5668                 :           0 :                     recfield->rectupledescid = rec->erh->er_tupdesc_id;
    5669                 :             :                 }
    5670                 :             : 
    5671                 :           0 :                 typeid = recfield->finfo.ftypeid;
    5672                 :           0 :                 break;
    5673                 :             :             }
    5674                 :             : 
    5675                 :           0 :         default:
    5676         [ #  # ]:           0 :             elog(ERROR, "unrecognized dtype: %d", datum->dtype);
    5677                 :             :             typeid = InvalidOid;    /* keep compiler quiet */
    5678                 :             :             break;
    5679                 :             :     }
    5680                 :             : 
    5681                 :         101 :     return typeid;
    5682                 :             : }
    5683                 :             : 
    5684                 :             : /*
    5685                 :             :  * plpgsql_exec_get_datum_type_info         Get datatype etc of a PLpgSQL_datum
    5686                 :             :  *
    5687                 :             :  * An extended version of plpgsql_exec_get_datum_type, which also retrieves the
    5688                 :             :  * typmod and collation of the datum.  Note however that we don't report the
    5689                 :             :  * possibly-mutable typmod of RECORD values, but say -1 always.
    5690                 :             :  */
    5691                 :             : void
    5692                 :       23433 : plpgsql_exec_get_datum_type_info(PLpgSQL_execstate *estate,
    5693                 :             :                                  PLpgSQL_datum *datum,
    5694                 :             :                                  Oid *typeId, int32 *typMod, Oid *collation)
    5695                 :             : {
    5696   [ +  +  +  - ]:       23433 :     switch (datum->dtype)
    5697                 :             :     {
    5698                 :       17504 :         case PLPGSQL_DTYPE_VAR:
    5699                 :             :         case PLPGSQL_DTYPE_PROMISE:
    5700                 :             :             {
    5701                 :       17504 :                 PLpgSQL_var *var = (PLpgSQL_var *) datum;
    5702                 :             : 
    5703                 :       17504 :                 *typeId = var->datatype->typoid;
    5704                 :       17504 :                 *typMod = var->datatype->atttypmod;
    5705                 :       17504 :                 *collation = var->datatype->collation;
    5706                 :       17504 :                 break;
    5707                 :             :             }
    5708                 :             : 
    5709                 :        2162 :         case PLPGSQL_DTYPE_REC:
    5710                 :             :             {
    5711                 :        2162 :                 PLpgSQL_rec *rec = (PLpgSQL_rec *) datum;
    5712                 :             : 
    5713   [ +  +  +  + ]:        2162 :                 if (rec->erh == NULL || rec->rectypeid != RECORDOID)
    5714                 :             :                 {
    5715                 :             :                     /* Report variable's declared type */
    5716                 :         774 :                     *typeId = rec->rectypeid;
    5717                 :         774 :                     *typMod = -1;
    5718                 :             :                 }
    5719                 :             :                 else
    5720                 :             :                 {
    5721                 :             :                     /* Report record's actual type if declared RECORD */
    5722                 :        1388 :                     *typeId = rec->erh->er_typeid;
    5723                 :             :                     /* do NOT return the mutable typmod of a RECORD variable */
    5724                 :        1388 :                     *typMod = -1;
    5725                 :             :                 }
    5726                 :             :                 /* composite types are never collatable */
    5727                 :        2162 :                 *collation = InvalidOid;
    5728                 :        2162 :                 break;
    5729                 :             :             }
    5730                 :             : 
    5731                 :        3767 :         case PLPGSQL_DTYPE_RECFIELD:
    5732                 :             :             {
    5733                 :        3767 :                 PLpgSQL_recfield *recfield = (PLpgSQL_recfield *) datum;
    5734                 :             :                 PLpgSQL_rec *rec;
    5735                 :             : 
    5736                 :        3767 :                 rec = (PLpgSQL_rec *) (estate->datums[recfield->recparentno]);
    5737                 :             : 
    5738                 :             :                 /*
    5739                 :             :                  * If record variable is NULL, instantiate it if it has a
    5740                 :             :                  * named composite type, else complain.  (This won't change
    5741                 :             :                  * the logical state of the record: it's still NULL.)
    5742                 :             :                  */
    5743         [ +  + ]:        3767 :                 if (rec->erh == NULL)
    5744                 :          28 :                     instantiate_empty_record_variable(estate, rec);
    5745                 :             : 
    5746                 :             :                 /*
    5747                 :             :                  * Look up the field's properties if we have not already, or
    5748                 :             :                  * if the tuple descriptor ID changed since last time.
    5749                 :             :                  */
    5750         [ +  + ]:        3766 :                 if (unlikely(recfield->rectupledescid != rec->erh->er_tupdesc_id))
    5751                 :             :                 {
    5752         [ +  + ]:        2023 :                     if (!expanded_record_lookup_field(rec->erh,
    5753                 :        2023 :                                                       recfield->fieldname,
    5754                 :             :                                                       &recfield->finfo))
    5755         [ +  - ]:          10 :                         ereport(ERROR,
    5756                 :             :                                 (errcode(ERRCODE_UNDEFINED_COLUMN),
    5757                 :             :                                  errmsg("record \"%s\" has no field \"%s\"",
    5758                 :             :                                         rec->refname, recfield->fieldname)));
    5759                 :        2013 :                     recfield->rectupledescid = rec->erh->er_tupdesc_id;
    5760                 :             :                 }
    5761                 :             : 
    5762                 :        3756 :                 *typeId = recfield->finfo.ftypeid;
    5763                 :        3756 :                 *typMod = recfield->finfo.ftypmod;
    5764                 :        3756 :                 *collation = recfield->finfo.fcollation;
    5765                 :        3756 :                 break;
    5766                 :             :             }
    5767                 :             : 
    5768                 :           0 :         default:
    5769         [ #  # ]:           0 :             elog(ERROR, "unrecognized dtype: %d", datum->dtype);
    5770                 :             :             *typeId = InvalidOid;   /* keep compiler quiet */
    5771                 :             :             *typMod = -1;
    5772                 :             :             *collation = InvalidOid;
    5773                 :             :             break;
    5774                 :             :     }
    5775                 :       23422 : }
    5776                 :             : 
    5777                 :             : /* ----------
    5778                 :             :  * exec_eval_integer        Evaluate an expression, coerce result to int4
    5779                 :             :  *
    5780                 :             :  * Note we do not do exec_eval_cleanup here; the caller must do it at
    5781                 :             :  * some later point.  (We do this because the caller may be holding the
    5782                 :             :  * results of other, pass-by-reference, expression evaluations, such as
    5783                 :             :  * an array value to be subscripted.)
    5784                 :             :  * ----------
    5785                 :             :  */
    5786                 :             : static int
    5787                 :          44 : exec_eval_integer(PLpgSQL_execstate *estate,
    5788                 :             :                   PLpgSQL_expr *expr,
    5789                 :             :                   bool *isNull)
    5790                 :             : {
    5791                 :             :     Datum       exprdatum;
    5792                 :             :     Oid         exprtypeid;
    5793                 :             :     int32       exprtypmod;
    5794                 :             : 
    5795                 :          44 :     exprdatum = exec_eval_expr(estate, expr, isNull, &exprtypeid, &exprtypmod);
    5796                 :          44 :     exprdatum = exec_cast_value(estate, exprdatum, isNull,
    5797                 :             :                                 exprtypeid, exprtypmod,
    5798                 :             :                                 INT4OID, -1);
    5799                 :          44 :     return DatumGetInt32(exprdatum);
    5800                 :             : }
    5801                 :             : 
    5802                 :             : /* ----------
    5803                 :             :  * exec_eval_boolean        Evaluate an expression, coerce result to bool
    5804                 :             :  *
    5805                 :             :  * Note we do not do exec_eval_cleanup here; the caller must do it at
    5806                 :             :  * some later point.
    5807                 :             :  * ----------
    5808                 :             :  */
    5809                 :             : static bool
    5810                 :       91425 : exec_eval_boolean(PLpgSQL_execstate *estate,
    5811                 :             :                   PLpgSQL_expr *expr,
    5812                 :             :                   bool *isNull)
    5813                 :             : {
    5814                 :             :     Datum       exprdatum;
    5815                 :             :     Oid         exprtypeid;
    5816                 :             :     int32       exprtypmod;
    5817                 :             : 
    5818                 :       91425 :     exprdatum = exec_eval_expr(estate, expr, isNull, &exprtypeid, &exprtypmod);
    5819                 :       91425 :     exprdatum = exec_cast_value(estate, exprdatum, isNull,
    5820                 :             :                                 exprtypeid, exprtypmod,
    5821                 :             :                                 BOOLOID, -1);
    5822                 :       91425 :     return DatumGetBool(exprdatum);
    5823                 :             : }
    5824                 :             : 
    5825                 :             : /* ----------
    5826                 :             :  * exec_eval_expr           Evaluate an expression and return
    5827                 :             :  *                  the result Datum, along with data type/typmod.
    5828                 :             :  *
    5829                 :             :  * NOTE: caller must do exec_eval_cleanup when done with the Datum.
    5830                 :             :  * ----------
    5831                 :             :  */
    5832                 :             : static Datum
    5833                 :      241785 : exec_eval_expr(PLpgSQL_execstate *estate,
    5834                 :             :                PLpgSQL_expr *expr,
    5835                 :             :                bool *isNull,
    5836                 :             :                Oid *rettype,
    5837                 :             :                int32 *rettypmod)
    5838                 :             : {
    5839                 :      241785 :     Datum       result = 0;
    5840                 :             :     int         rc;
    5841                 :             :     Form_pg_attribute attr;
    5842                 :             : 
    5843                 :             :     /*
    5844                 :             :      * If first time through, create a plan for this expression.
    5845                 :             :      */
    5846         [ +  + ]:      241785 :     if (expr->plan == NULL)
    5847                 :       12460 :         exec_prepare_plan(estate, expr, CURSOR_OPT_PARALLEL_OK);
    5848                 :             : 
    5849                 :             :     /*
    5850                 :             :      * If this is a simple expression, bypass SPI and use the executor
    5851                 :             :      * directly
    5852                 :             :      */
    5853         [ +  + ]:      241761 :     if (exec_eval_simple_expr(estate, expr,
    5854                 :             :                               &result, isNull, rettype, rettypmod))
    5855                 :      234066 :         return result;
    5856                 :             : 
    5857                 :             :     /*
    5858                 :             :      * Else do it the hard way via exec_run_select
    5859                 :             :      */
    5860                 :        7532 :     rc = exec_run_select(estate, expr, 0, NULL);
    5861         [ -  + ]:        7515 :     if (rc != SPI_OK_SELECT)
    5862         [ #  # ]:           0 :         ereport(ERROR,
    5863                 :             :                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
    5864                 :             :                  errmsg("query did not return data"),
    5865                 :             :                  errcontext("query: %s", expr->query)));
    5866                 :             : 
    5867                 :             :     /*
    5868                 :             :      * Check that the expression returns exactly one column...
    5869                 :             :      */
    5870         [ -  + ]:        7515 :     if (estate->eval_tuptable->tupdesc->natts != 1)
    5871         [ #  # ]:           0 :         ereport(ERROR,
    5872                 :             :                 (errcode(ERRCODE_SYNTAX_ERROR),
    5873                 :             :                  errmsg_plural("query returned %d column",
    5874                 :             :                                "query returned %d columns",
    5875                 :             :                                estate->eval_tuptable->tupdesc->natts,
    5876                 :             :                                estate->eval_tuptable->tupdesc->natts),
    5877                 :             :                  errcontext("query: %s", expr->query)));
    5878                 :             : 
    5879                 :             :     /*
    5880                 :             :      * ... and get the column's datatype.
    5881                 :             :      */
    5882                 :        7515 :     attr = TupleDescAttr(estate->eval_tuptable->tupdesc, 0);
    5883                 :        7515 :     *rettype = attr->atttypid;
    5884                 :        7515 :     *rettypmod = attr->atttypmod;
    5885                 :             : 
    5886                 :             :     /*
    5887                 :             :      * If there are no rows selected, the result is a NULL of that type.
    5888                 :             :      */
    5889         [ -  + ]:        7515 :     if (estate->eval_processed == 0)
    5890                 :             :     {
    5891                 :           0 :         *isNull = true;
    5892                 :           0 :         return (Datum) 0;
    5893                 :             :     }
    5894                 :             : 
    5895                 :             :     /*
    5896                 :             :      * Check that the expression returned no more than one row.
    5897                 :             :      */
    5898         [ +  + ]:        7515 :     if (estate->eval_processed != 1)
    5899         [ +  - ]:           1 :         ereport(ERROR,
    5900                 :             :                 (errcode(ERRCODE_CARDINALITY_VIOLATION),
    5901                 :             :                  errmsg("query returned more than one row"),
    5902                 :             :                  errcontext("query: %s", expr->query)));
    5903                 :             : 
    5904                 :             :     /*
    5905                 :             :      * Return the single result Datum.
    5906                 :             :      */
    5907                 :        7514 :     return SPI_getbinval(estate->eval_tuptable->vals[0],
    5908                 :        7514 :                          estate->eval_tuptable->tupdesc, 1, isNull);
    5909                 :             : }
    5910                 :             : 
    5911                 :             : 
    5912                 :             : /* ----------
    5913                 :             :  * exec_run_select          Execute a select query
    5914                 :             :  *
    5915                 :             :  * Note: passing maxtuples different from 0 ("return all tuples") is
    5916                 :             :  * deprecated because it will prevent parallel execution of the query.
    5917                 :             :  * However, we retain the parameter in case we need it someday.
    5918                 :             :  * ----------
    5919                 :             :  */
    5920                 :             : static int
    5921                 :       13191 : exec_run_select(PLpgSQL_execstate *estate,
    5922                 :             :                 PLpgSQL_expr *expr, long maxtuples, Portal *portalP)
    5923                 :             : {
    5924                 :             :     ParamListInfo paramLI;
    5925                 :             :     int         rc;
    5926                 :             : 
    5927                 :             :     /*
    5928                 :             :      * On the first call for this expression generate the plan.
    5929                 :             :      *
    5930                 :             :      * If we don't need to return a portal, then we're just going to execute
    5931                 :             :      * the query immediately, which means it's OK to use a parallel plan, even
    5932                 :             :      * if the number of rows being fetched is limited.  If we do need to
    5933                 :             :      * return a portal (i.e., this is for a FOR loop), the user's code might
    5934                 :             :      * invoke additional operations inside the FOR loop, making parallel query
    5935                 :             :      * unsafe.  In any case, we don't expect any cursor operations to be done,
    5936                 :             :      * so specify NO_SCROLL for efficiency and semantic safety.
    5937                 :             :      */
    5938         [ +  + ]:       13191 :     if (expr->plan == NULL)
    5939                 :             :     {
    5940                 :         756 :         int         cursorOptions = CURSOR_OPT_NO_SCROLL;
    5941                 :             : 
    5942         [ +  + ]:         756 :         if (portalP == NULL)
    5943                 :         535 :             cursorOptions |= CURSOR_OPT_PARALLEL_OK;
    5944                 :         756 :         exec_prepare_plan(estate, expr, cursorOptions);
    5945                 :             :     }
    5946                 :             : 
    5947                 :             :     /*
    5948                 :             :      * Set up ParamListInfo to pass to executor
    5949                 :             :      */
    5950                 :       13162 :     paramLI = setup_param_list(estate, expr);
    5951                 :             : 
    5952                 :             :     /*
    5953                 :             :      * If a portal was requested, put the query and paramlist into the portal
    5954                 :             :      */
    5955         [ +  + ]:       13162 :     if (portalP != NULL)
    5956                 :             :     {
    5957                 :        3320 :         *portalP = SPI_cursor_open_with_paramlist(NULL, expr->plan,
    5958                 :             :                                                   paramLI,
    5959                 :        1660 :                                                   estate->readonly_func);
    5960         [ -  + ]:        1660 :         if (*portalP == NULL)
    5961         [ #  # ]:           0 :             elog(ERROR, "could not open implicit cursor for query \"%s\": %s",
    5962                 :             :                  expr->query, SPI_result_code_string(SPI_result));
    5963                 :        1660 :         exec_eval_cleanup(estate);
    5964                 :        1660 :         return SPI_OK_CURSOR;
    5965                 :             :     }
    5966                 :             : 
    5967                 :             :     /*
    5968                 :             :      * Execute the query
    5969                 :             :      */
    5970                 :       11502 :     rc = SPI_execute_plan_with_paramlist(expr->plan, paramLI,
    5971                 :       11502 :                                          estate->readonly_func, maxtuples);
    5972         [ -  + ]:       10514 :     if (rc != SPI_OK_SELECT)
    5973                 :             :     {
    5974                 :             :         /*
    5975                 :             :          * SELECT INTO deserves a special error message, because "query is not
    5976                 :             :          * a SELECT" is not very helpful in that case.
    5977                 :             :          */
    5978         [ #  # ]:           0 :         if (rc == SPI_OK_SELINTO)
    5979         [ #  # ]:           0 :             ereport(ERROR,
    5980                 :             :                     (errcode(ERRCODE_SYNTAX_ERROR),
    5981                 :             :                      errmsg("query is SELECT INTO, but it should be plain SELECT"),
    5982                 :             :                      errcontext("query: %s", expr->query)));
    5983                 :             :         else
    5984         [ #  # ]:           0 :             ereport(ERROR,
    5985                 :             :                     (errcode(ERRCODE_SYNTAX_ERROR),
    5986                 :             :                      errmsg("query is not a SELECT"),
    5987                 :             :                      errcontext("query: %s", expr->query)));
    5988                 :             :     }
    5989                 :             : 
    5990                 :             :     /* Save query results for eventual cleanup */
    5991                 :             :     Assert(estate->eval_tuptable == NULL);
    5992                 :       10514 :     estate->eval_tuptable = SPI_tuptable;
    5993                 :       10514 :     estate->eval_processed = SPI_processed;
    5994                 :             : 
    5995                 :       10514 :     return rc;
    5996                 :             : }
    5997                 :             : 
    5998                 :             : 
    5999                 :             : /*
    6000                 :             :  * exec_for_query --- execute body of FOR loop for each row from a portal
    6001                 :             :  *
    6002                 :             :  * Used by exec_stmt_fors, exec_stmt_forc and exec_stmt_dynfors
    6003                 :             :  */
    6004                 :             : static int
    6005                 :        8087 : exec_for_query(PLpgSQL_execstate *estate, PLpgSQL_stmt_forq *stmt,
    6006                 :             :                Portal portal, bool prefetch_ok)
    6007                 :             : {
    6008                 :             :     PLpgSQL_variable *var;
    6009                 :             :     SPITupleTable *tuptab;
    6010                 :        8087 :     bool        found = false;
    6011                 :        8087 :     int         rc = PLPGSQL_RC_OK;
    6012                 :        8087 :     uint64      previous_id = INVALID_TUPLEDESC_IDENTIFIER;
    6013                 :        8087 :     bool        tupdescs_match = true;
    6014                 :             :     uint64      n;
    6015                 :             : 
    6016                 :             :     /* Fetch loop variable's datum entry */
    6017                 :        8087 :     var = (PLpgSQL_variable *) estate->datums[stmt->var->dno];
    6018                 :             : 
    6019                 :             :     /*
    6020                 :             :      * Make sure the portal doesn't get closed by the user statements we
    6021                 :             :      * execute.
    6022                 :             :      */
    6023                 :        8087 :     PinPortal(portal);
    6024                 :             : 
    6025                 :             :     /*
    6026                 :             :      * In a non-atomic context, we dare not prefetch, even if it would
    6027                 :             :      * otherwise be safe.  Aside from any semantic hazards that that might
    6028                 :             :      * create, if we prefetch toasted data and then the user commits the
    6029                 :             :      * transaction, the toast references could turn into dangling pointers.
    6030                 :             :      * (Rows we haven't yet fetched from the cursor are safe, because the
    6031                 :             :      * PersistHoldablePortal mechanism handles this scenario.)
    6032                 :             :      */
    6033         [ +  + ]:        8087 :     if (!estate->atomic)
    6034                 :        4998 :         prefetch_ok = false;
    6035                 :             : 
    6036                 :             :     /*
    6037                 :             :      * Fetch the initial tuple(s).  If prefetching is allowed then we grab a
    6038                 :             :      * few more rows to avoid multiple trips through executor startup
    6039                 :             :      * overhead.
    6040                 :             :      */
    6041         [ +  + ]:        8087 :     SPI_cursor_fetch(portal, true, prefetch_ok ? 10 : 1);
    6042                 :        8079 :     tuptab = SPI_tuptable;
    6043                 :        8079 :     n = SPI_processed;
    6044                 :             : 
    6045                 :             :     /*
    6046                 :             :      * If the query didn't return any rows, set the target to NULL and fall
    6047                 :             :      * through with found = false.
    6048                 :             :      */
    6049         [ +  + ]:        8079 :     if (n == 0)
    6050                 :             :     {
    6051                 :        1100 :         exec_move_row(estate, var, NULL, tuptab->tupdesc);
    6052                 :        1100 :         exec_eval_cleanup(estate);
    6053                 :             :     }
    6054                 :             :     else
    6055                 :        6979 :         found = true;           /* processed at least one tuple */
    6056                 :             : 
    6057                 :             :     /*
    6058                 :             :      * Now do the loop
    6059                 :             :      */
    6060         [ +  + ]:       29296 :     while (n > 0)
    6061                 :             :     {
    6062                 :             :         uint64      i;
    6063                 :             : 
    6064         [ +  + ]:       57076 :         for (i = 0; i < n; i++)
    6065                 :             :         {
    6066                 :             :             /*
    6067                 :             :              * Assign the tuple to the target.  Here, because we know that all
    6068                 :             :              * loop iterations should be assigning the same tupdesc, we can
    6069                 :             :              * optimize away repeated creations of expanded records with
    6070                 :             :              * identical tupdescs.  Testing for changes of er_tupdesc_id is
    6071                 :             :              * reliable even if the loop body contains assignments that
    6072                 :             :              * replace the target's value entirely, because it's assigned from
    6073                 :             :              * a process-global counter.  The case where the tupdescs don't
    6074                 :             :              * match could possibly be handled more efficiently than this
    6075                 :             :              * coding does, but it's not clear extra effort is worthwhile.
    6076                 :             :              */
    6077         [ +  + ]:       35859 :             if (var->dtype == PLPGSQL_DTYPE_REC)
    6078                 :             :             {
    6079                 :        4602 :                 PLpgSQL_rec *rec = (PLpgSQL_rec *) var;
    6080                 :             : 
    6081         [ +  + ]:        4602 :                 if (rec->erh &&
    6082   [ +  +  +  + ]:        4019 :                     rec->erh->er_tupdesc_id == previous_id &&
    6083                 :             :                     tupdescs_match)
    6084                 :             :                 {
    6085                 :             :                     /* Only need to assign a new tuple value */
    6086                 :        3971 :                     expanded_record_set_tuple(rec->erh, tuptab->vals[i],
    6087                 :        3971 :                                               true, !estate->atomic);
    6088                 :             :                 }
    6089                 :             :                 else
    6090                 :             :                 {
    6091                 :             :                     /*
    6092                 :             :                      * First time through, or var's tupdesc changed in loop,
    6093                 :             :                      * or we have to do it the hard way because type coercion
    6094                 :             :                      * is needed.
    6095                 :             :                      */
    6096                 :         631 :                     exec_move_row(estate, var,
    6097                 :         631 :                                   tuptab->vals[i], tuptab->tupdesc);
    6098                 :             : 
    6099                 :             :                     /*
    6100                 :             :                      * Check to see if physical assignment is OK next time.
    6101                 :             :                      * Once the tupdesc comparison has failed once, we don't
    6102                 :             :                      * bother rechecking in subsequent loop iterations.
    6103                 :             :                      */
    6104         [ +  + ]:         630 :                     if (tupdescs_match)
    6105                 :             :                     {
    6106                 :         626 :                         tupdescs_match =
    6107                 :         638 :                             (rec->rectypeid == RECORDOID ||
    6108   [ +  +  +  -  :         638 :                              rec->rectypeid == tuptab->tupdesc->tdtypeid ||
                   +  + ]
    6109                 :          12 :                              compatible_tupdescs(tuptab->tupdesc,
    6110                 :             :                                                  expanded_record_get_tupdesc(rec->erh)));
    6111                 :             :                     }
    6112                 :         630 :                     previous_id = rec->erh->er_tupdesc_id;
    6113                 :             :                 }
    6114                 :             :             }
    6115                 :             :             else
    6116                 :       31257 :                 exec_move_row(estate, var, tuptab->vals[i], tuptab->tupdesc);
    6117                 :             : 
    6118                 :       35857 :             exec_eval_cleanup(estate);
    6119                 :             : 
    6120                 :             :             /*
    6121                 :             :              * Execute the statements
    6122                 :             :              */
    6123                 :       35857 :             rc = exec_stmts(estate, stmt->body);
    6124                 :             : 
    6125   [ +  +  -  +  :       35823 :             LOOP_RC_PROCESSING(stmt->label, goto loop_exit);
          -  -  -  -  -  
          -  +  +  +  -  
             -  -  -  - ]
    6126                 :             :         }
    6127                 :             : 
    6128                 :       21217 :         SPI_freetuptable(tuptab);
    6129                 :             : 
    6130                 :             :         /*
    6131                 :             :          * Fetch more tuples.  If prefetching is allowed, grab 50 at a time.
    6132                 :             :          */
    6133         [ +  + ]:       21217 :         SPI_cursor_fetch(portal, true, prefetch_ok ? 50 : 1);
    6134                 :       21217 :         tuptab = SPI_tuptable;
    6135                 :       21217 :         n = SPI_processed;
    6136                 :             :     }
    6137                 :             : 
    6138                 :        7794 : loop_exit:
    6139                 :             : 
    6140                 :             :     /*
    6141                 :             :      * Release last group of tuples (if any)
    6142                 :             :      */
    6143                 :        8043 :     SPI_freetuptable(tuptab);
    6144                 :             : 
    6145                 :        8043 :     UnpinPortal(portal);
    6146                 :             : 
    6147                 :             :     /*
    6148                 :             :      * Set the FOUND variable to indicate the result of executing the loop
    6149                 :             :      * (namely, whether we looped one or more times). This must be set last so
    6150                 :             :      * that it does not interfere with the value of the FOUND variable inside
    6151                 :             :      * the loop processing itself.
    6152                 :             :      */
    6153                 :        8043 :     exec_set_found(estate, found);
    6154                 :             : 
    6155                 :        8043 :     return rc;
    6156                 :             : }
    6157                 :             : 
    6158                 :             : 
    6159                 :             : /* ----------
    6160                 :             :  * exec_eval_simple_expr -      Evaluate a simple expression returning
    6161                 :             :  *                              a Datum by directly calling ExecEvalExpr().
    6162                 :             :  *
    6163                 :             :  * If successful, store results into *result, *isNull, *rettype, *rettypmod
    6164                 :             :  * and return true.  If the expression cannot be handled by simple evaluation,
    6165                 :             :  * return false.
    6166                 :             :  *
    6167                 :             :  * Because we only store one execution tree for a simple expression, we
    6168                 :             :  * can't handle recursion cases.  So, if we see the tree is already busy
    6169                 :             :  * with an evaluation in the current xact, we just return false and let the
    6170                 :             :  * caller run the expression the hard way.  (Other alternatives such as
    6171                 :             :  * creating a new tree for a recursive call either introduce memory leaks,
    6172                 :             :  * or add enough bookkeeping to be doubtful wins anyway.)  Another case that
    6173                 :             :  * is covered by the expr_simple_in_use test is where a previous execution
    6174                 :             :  * of the tree was aborted by an error: the tree may contain bogus state
    6175                 :             :  * so we dare not re-use it.
    6176                 :             :  *
    6177                 :             :  * It is possible that we'd need to replan a simple expression; for example,
    6178                 :             :  * someone might redefine a SQL function that had been inlined into the simple
    6179                 :             :  * expression.  That cannot cause a simple expression to become non-simple (or
    6180                 :             :  * vice versa), but we do have to handle replacing the expression tree.
    6181                 :             :  *
    6182                 :             :  * Note: if pass-by-reference, the result is in the eval_mcontext.
    6183                 :             :  * It will be freed when exec_eval_cleanup is done.
    6184                 :             :  * ----------
    6185                 :             :  */
    6186                 :             : static bool
    6187                 :      244687 : exec_eval_simple_expr(PLpgSQL_execstate *estate,
    6188                 :             :                       PLpgSQL_expr *expr,
    6189                 :             :                       Datum *result,
    6190                 :             :                       bool *isNull,
    6191                 :             :                       Oid *rettype,
    6192                 :             :                       int32 *rettypmod)
    6193                 :             : {
    6194                 :      244687 :     ExprContext *econtext = estate->eval_econtext;
    6195                 :      244687 :     LocalTransactionId curlxid = MyProc->vxid.lxid;
    6196                 :             :     ParamListInfo paramLI;
    6197                 :             :     void       *save_setup_arg;
    6198                 :             :     bool        need_snapshot;
    6199                 :             :     MemoryContext oldcontext;
    6200                 :             : 
    6201                 :             :     /*
    6202                 :             :      * Forget it if expression wasn't simple before.
    6203                 :             :      */
    6204         [ +  + ]:      244687 :     if (expr->expr_simple_expr == NULL)
    6205                 :        7161 :         return false;
    6206                 :             : 
    6207                 :             :     /*
    6208                 :             :      * If expression is in use in current xact, don't touch it.
    6209                 :             :      */
    6210         [ +  + ]:      237526 :     if (unlikely(expr->expr_simple_in_use) &&
    6211         [ +  + ]:         415 :         expr->expr_simple_lxid == curlxid)
    6212                 :         370 :         return false;
    6213                 :             : 
    6214                 :             :     /*
    6215                 :             :      * Ensure that there's a portal-level snapshot, in case this simple
    6216                 :             :      * expression is the first thing evaluated after a COMMIT or ROLLBACK.
    6217                 :             :      * We'd have to do this anyway before executing the expression, so we
    6218                 :             :      * might as well do it now to ensure that any possible replanning doesn't
    6219                 :             :      * need to take a new snapshot.
    6220                 :             :      */
    6221                 :      237156 :     EnsurePortalSnapshotExists();
    6222                 :             : 
    6223                 :             :     /*
    6224                 :             :      * Check to see if the cached plan has been invalidated.  If not, and this
    6225                 :             :      * is the first use in the current transaction, save a plan refcount in
    6226                 :             :      * the simple-expression resowner.
    6227                 :             :      */
    6228   [ +  +  +  + ]:      237156 :     if (likely(CachedPlanIsSimplyValid(expr->expr_simple_plansource,
    6229                 :             :                                        expr->expr_simple_plan,
    6230                 :             :                                        (expr->expr_simple_plan_lxid != curlxid ?
    6231                 :             :                                         estate->simple_eval_resowner : NULL))))
    6232                 :             :     {
    6233                 :             :         /*
    6234                 :             :          * It's still good, so just remember that we have a refcount on the
    6235                 :             :          * plan in the current transaction.  (If we already had one, this
    6236                 :             :          * assignment is a no-op.)
    6237                 :             :          */
    6238                 :      233447 :         expr->expr_simple_plan_lxid = curlxid;
    6239                 :             :     }
    6240                 :             :     else
    6241                 :             :     {
    6242                 :             :         /* Need to replan */
    6243                 :             :         CachedPlan *cplan;
    6244                 :             : 
    6245                 :             :         /*
    6246                 :             :          * If we have a valid refcount on some previous version of the plan,
    6247                 :             :          * release it, so we don't leak plans intra-transaction.
    6248                 :             :          */
    6249         [ +  + ]:        3709 :         if (expr->expr_simple_plan_lxid == curlxid)
    6250                 :        1757 :             ReleaseCachedPlan(expr->expr_simple_plan,
    6251                 :             :                               estate->simple_eval_resowner);
    6252                 :             : 
    6253                 :             :         /*
    6254                 :             :          * Reset to "not simple" to leave sane state (with no dangling
    6255                 :             :          * pointers) in case we fail while replanning.  We'll need to
    6256                 :             :          * re-determine simplicity and R/W optimizability anyway, since those
    6257                 :             :          * could change with the new plan.  expr_simple_plansource can be left
    6258                 :             :          * alone however, as that cannot move.
    6259                 :             :          */
    6260                 :        3709 :         expr->expr_simple_expr = NULL;
    6261                 :        3709 :         expr->expr_rwopt = PLPGSQL_RWOPT_UNKNOWN;
    6262                 :        3709 :         expr->expr_rw_param = NULL;
    6263                 :        3709 :         expr->expr_simple_plan = NULL;
    6264                 :        3709 :         expr->expr_simple_plan_lxid = InvalidLocalTransactionId;
    6265                 :             : 
    6266                 :             :         /* Do the replanning work in the eval_mcontext */
    6267                 :        3709 :         oldcontext = MemoryContextSwitchTo(get_eval_mcontext(estate));
    6268                 :        3709 :         cplan = SPI_plan_get_cached_plan(expr->plan);
    6269                 :        3709 :         MemoryContextSwitchTo(oldcontext);
    6270                 :             : 
    6271                 :             :         /*
    6272                 :             :          * We can't get a failure here, because the number of
    6273                 :             :          * CachedPlanSources in the SPI plan can't change from what
    6274                 :             :          * exec_simple_check_plan saw; it's a property of the raw parsetree
    6275                 :             :          * generated from the query text.
    6276                 :             :          */
    6277                 :             :         Assert(cplan != NULL);
    6278                 :             : 
    6279                 :             :         /*
    6280                 :             :          * Recheck exec_is_simple_query, which could now report false in
    6281                 :             :          * edge-case scenarios such as a non-SRF having been replaced with a
    6282                 :             :          * SRF.  Also recheck CachedPlanAllowsSimpleValidityCheck, just to be
    6283                 :             :          * sure.  If either test fails, cope by declaring the plan to be
    6284                 :             :          * non-simple.  On success, we'll acquire a refcount on the new plan,
    6285                 :             :          * stored in simple_eval_resowner.
    6286                 :             :          */
    6287   [ +  +  +  - ]:        7417 :         if (exec_is_simple_query(expr) &&
    6288                 :        3708 :             CachedPlanAllowsSimpleValidityCheck(expr->expr_simple_plansource,
    6289                 :             :                                                 cplan,
    6290                 :             :                                                 estate->simple_eval_resowner))
    6291                 :             :         {
    6292                 :             :             /* Remember that we have the refcount */
    6293                 :        3708 :             expr->expr_simple_plan = cplan;
    6294                 :        3708 :             expr->expr_simple_plan_lxid = curlxid;
    6295                 :             :         }
    6296                 :             :         else
    6297                 :             :         {
    6298                 :             :             /* Release SPI_plan_get_cached_plan's refcount */
    6299                 :           1 :             ReleaseCachedPlan(cplan, CurrentResourceOwner);
    6300                 :           1 :             return false;
    6301                 :             :         }
    6302                 :             : 
    6303                 :             :         /*
    6304                 :             :          * SPI_plan_get_cached_plan acquired a plan refcount stored in the
    6305                 :             :          * active resowner.  We don't need that anymore, so release it.
    6306                 :             :          */
    6307                 :        3708 :         ReleaseCachedPlan(cplan, CurrentResourceOwner);
    6308                 :             : 
    6309                 :             :         /* Extract desired scalar expression from cached plan */
    6310                 :        3708 :         exec_save_simple_expr(expr, cplan);
    6311                 :             :     }
    6312                 :             : 
    6313                 :             :     /*
    6314                 :             :      * Pass back previously-determined result type.
    6315                 :             :      */
    6316                 :      237155 :     *rettype = expr->expr_simple_type;
    6317                 :      237155 :     *rettypmod = expr->expr_simple_typmod;
    6318                 :             : 
    6319                 :             :     /*
    6320                 :             :      * Set up ParamListInfo to pass to executor.  For safety, save and restore
    6321                 :             :      * estate->paramLI->parserSetupArg around our use of the param list.
    6322                 :             :      */
    6323                 :      237155 :     paramLI = estate->paramLI;
    6324                 :      237155 :     save_setup_arg = paramLI->parserSetupArg;
    6325                 :             : 
    6326                 :             :     /*
    6327                 :             :      * We can skip using setup_param_list() in favor of just doing this
    6328                 :             :      * unconditionally, because there's no need for the optimization of
    6329                 :             :      * possibly setting ecxt_param_list_info to NULL; we've already forced use
    6330                 :             :      * of a generic plan.
    6331                 :             :      */
    6332                 :      237155 :     paramLI->parserSetupArg = expr;
    6333                 :      237155 :     econtext->ecxt_param_list_info = paramLI;
    6334                 :             : 
    6335                 :             :     /*
    6336                 :             :      * Prepare the expression for execution, if it's not been done already in
    6337                 :             :      * the current transaction.  (This will be forced to happen if we called
    6338                 :             :      * exec_save_simple_expr above.)
    6339                 :             :      */
    6340         [ +  + ]:      237155 :     if (unlikely(expr->expr_simple_lxid != curlxid))
    6341                 :             :     {
    6342                 :       52918 :         oldcontext = MemoryContextSwitchTo(estate->simple_eval_estate->es_query_cxt);
    6343                 :       52918 :         expr->expr_simple_state =
    6344                 :       52918 :             ExecInitExprWithParams(expr->expr_simple_expr,
    6345                 :             :                                    econtext->ecxt_param_list_info);
    6346                 :       52918 :         expr->expr_simple_in_use = false;
    6347                 :       52918 :         expr->expr_simple_lxid = curlxid;
    6348                 :       52918 :         MemoryContextSwitchTo(oldcontext);
    6349                 :             :     }
    6350                 :             : 
    6351                 :             :     /*
    6352                 :             :      * We have to do some of the things SPI_execute_plan would do, in
    6353                 :             :      * particular push a new snapshot so that stable functions within the
    6354                 :             :      * expression can see updates made so far by our own function.  However,
    6355                 :             :      * we can skip doing that (and just invoke the expression with the same
    6356                 :             :      * snapshot passed to our function) in some cases, which is useful because
    6357                 :             :      * it's quite expensive relative to the cost of a simple expression.  We
    6358                 :             :      * can skip it if the expression contains no stable or volatile functions;
    6359                 :             :      * immutable functions shouldn't need to see our updates.  Also, if this
    6360                 :             :      * is a read-only function, we haven't made any updates so again it's okay
    6361                 :             :      * to skip.
    6362                 :             :      */
    6363                 :      237155 :     oldcontext = MemoryContextSwitchTo(get_eval_mcontext(estate));
    6364   [ +  +  +  + ]:      237155 :     need_snapshot = (expr->expr_simple_mutable && !estate->readonly_func);
    6365         [ +  + ]:      237155 :     if (need_snapshot)
    6366                 :             :     {
    6367                 :       28553 :         CommandCounterIncrement();
    6368                 :       28553 :         PushActiveSnapshot(GetTransactionSnapshot());
    6369                 :             :     }
    6370                 :             : 
    6371                 :             :     /*
    6372                 :             :      * Mark expression as busy for the duration of the ExecEvalExpr call.
    6373                 :             :      */
    6374                 :      237155 :     expr->expr_simple_in_use = true;
    6375                 :             : 
    6376                 :             :     /*
    6377                 :             :      * Finally we can call the executor to evaluate the expression
    6378                 :             :      */
    6379                 :      237155 :     *result = ExecEvalExpr(expr->expr_simple_state,
    6380                 :             :                            econtext,
    6381                 :             :                            isNull);
    6382                 :             : 
    6383                 :             :     /* Assorted cleanup */
    6384                 :      236986 :     expr->expr_simple_in_use = false;
    6385                 :             : 
    6386                 :      236986 :     econtext->ecxt_param_list_info = NULL;
    6387                 :             : 
    6388                 :      236986 :     paramLI->parserSetupArg = save_setup_arg;
    6389                 :             : 
    6390         [ +  + ]:      236986 :     if (need_snapshot)
    6391                 :       28514 :         PopActiveSnapshot();
    6392                 :             : 
    6393                 :      236986 :     MemoryContextSwitchTo(oldcontext);
    6394                 :             : 
    6395                 :             :     /*
    6396                 :             :      * That's it.
    6397                 :             :      */
    6398                 :      236986 :     return true;
    6399                 :             : }
    6400                 :             : 
    6401                 :             : 
    6402                 :             : /*
    6403                 :             :  * Create a ParamListInfo to pass to SPI
    6404                 :             :  *
    6405                 :             :  * We use a single ParamListInfo struct for all SPI calls made to evaluate
    6406                 :             :  * PLpgSQL_exprs in this estate.  It contains no per-param data, just hook
    6407                 :             :  * functions, so it's effectively read-only for SPI.
    6408                 :             :  *
    6409                 :             :  * An exception from pure read-only-ness is that the parserSetupArg points
    6410                 :             :  * to the specific PLpgSQL_expr being evaluated.  This is not an issue for
    6411                 :             :  * statement-level callers, but lower-level callers must save and restore
    6412                 :             :  * estate->paramLI->parserSetupArg just in case there's an active evaluation
    6413                 :             :  * at an outer call level.  (A plausible alternative design would be to
    6414                 :             :  * create a ParamListInfo struct for each PLpgSQL_expr, but for the moment
    6415                 :             :  * that seems like a waste of memory.)
    6416                 :             :  */
    6417                 :             : static ParamListInfo
    6418                 :       67285 : setup_param_list(PLpgSQL_execstate *estate, PLpgSQL_expr *expr)
    6419                 :             : {
    6420                 :             :     ParamListInfo paramLI;
    6421                 :             : 
    6422                 :             :     /*
    6423                 :             :      * We must have created the SPIPlan already (hence, query text has been
    6424                 :             :      * parsed/analyzed at least once); else we cannot rely on expr->paramnos.
    6425                 :             :      */
    6426                 :             :     Assert(expr->plan != NULL);
    6427                 :             : 
    6428                 :             :     /*
    6429                 :             :      * We only need a ParamListInfo if the expression has parameters.
    6430                 :             :      */
    6431         [ +  + ]:       67285 :     if (!bms_is_empty(expr->paramnos))
    6432                 :             :     {
    6433                 :             :         /* Use the common ParamListInfo */
    6434                 :       34839 :         paramLI = estate->paramLI;
    6435                 :             : 
    6436                 :             :         /*
    6437                 :             :          * Set up link to active expr where the hook functions can find it.
    6438                 :             :          * Callers must save and restore parserSetupArg if there is any chance
    6439                 :             :          * that they are interrupting an active use of parameters.
    6440                 :             :          */
    6441                 :       34839 :         paramLI->parserSetupArg = expr;
    6442                 :             :     }
    6443                 :             :     else
    6444                 :             :     {
    6445                 :             :         /*
    6446                 :             :          * Expression requires no parameters.  Be sure we represent this case
    6447                 :             :          * as a NULL ParamListInfo, so that plancache.c knows there is no
    6448                 :             :          * point in a custom plan.
    6449                 :             :          */
    6450                 :       32446 :         paramLI = NULL;
    6451                 :             :     }
    6452                 :       67285 :     return paramLI;
    6453                 :             : }
    6454                 :             : 
    6455                 :             : /*
    6456                 :             :  * plpgsql_param_fetch      paramFetch callback for dynamic parameter fetch
    6457                 :             :  *
    6458                 :             :  * We always use the caller's workspace to construct the returned struct.
    6459                 :             :  *
    6460                 :             :  * Note: this is no longer used during query execution.  It is used during
    6461                 :             :  * planning (with speculative == true) and when the ParamListInfo we supply
    6462                 :             :  * to the executor is copied into a cursor portal or transferred to a
    6463                 :             :  * parallel child process.
    6464                 :             :  */
    6465                 :             : static ParamExternData *
    6466                 :        7405 : plpgsql_param_fetch(ParamListInfo params,
    6467                 :             :                     int paramid, bool speculative,
    6468                 :             :                     ParamExternData *prm)
    6469                 :             : {
    6470                 :             :     int         dno;
    6471                 :             :     PLpgSQL_execstate *estate;
    6472                 :             :     PLpgSQL_expr *expr;
    6473                 :             :     PLpgSQL_datum *datum;
    6474                 :        7405 :     bool        ok = true;
    6475                 :             :     int32       prmtypmod;
    6476                 :             : 
    6477                 :             :     /* paramid's are 1-based, but dnos are 0-based */
    6478                 :        7405 :     dno = paramid - 1;
    6479                 :             :     Assert(dno >= 0 && dno < params->numParams);
    6480                 :             : 
    6481                 :             :     /* fetch back the hook data */
    6482                 :        7405 :     estate = (PLpgSQL_execstate *) params->paramFetchArg;
    6483                 :        7405 :     expr = (PLpgSQL_expr *) params->parserSetupArg;
    6484                 :             :     Assert(params->numParams == estate->ndatums);
    6485                 :             : 
    6486                 :             :     /* now we can access the target datum */
    6487                 :        7405 :     datum = estate->datums[dno];
    6488                 :             : 
    6489                 :             :     /*
    6490                 :             :      * Since copyParamList() or SerializeParamList() will try to materialize
    6491                 :             :      * every single parameter slot, it's important to return a dummy param
    6492                 :             :      * when asked for a datum that's not supposed to be used by this SQL
    6493                 :             :      * expression.  Otherwise we risk failures in exec_eval_datum(), or
    6494                 :             :      * copying a lot more data than necessary.
    6495                 :             :      */
    6496         [ +  + ]:        7405 :     if (!bms_is_member(dno, expr->paramnos))
    6497                 :        2437 :         ok = false;
    6498                 :             : 
    6499                 :             :     /*
    6500                 :             :      * If the access is speculative, we prefer to return no data rather than
    6501                 :             :      * to fail in exec_eval_datum().  Check the likely failure cases.
    6502                 :             :      */
    6503         [ +  + ]:        4968 :     else if (speculative)
    6504                 :             :     {
    6505   [ +  -  +  +  :        4298 :         switch (datum->dtype)
                      - ]
    6506                 :             :         {
    6507                 :        2443 :             case PLPGSQL_DTYPE_VAR:
    6508                 :             :             case PLPGSQL_DTYPE_PROMISE:
    6509                 :             :                 /* always safe */
    6510                 :        2443 :                 break;
    6511                 :             : 
    6512                 :           0 :             case PLPGSQL_DTYPE_ROW:
    6513                 :             :                 /* should be safe in all interesting cases */
    6514                 :           0 :                 break;
    6515                 :             : 
    6516                 :         325 :             case PLPGSQL_DTYPE_REC:
    6517                 :             :                 /* always safe (might return NULL, that's fine) */
    6518                 :         325 :                 break;
    6519                 :             : 
    6520                 :        1530 :             case PLPGSQL_DTYPE_RECFIELD:
    6521                 :             :                 {
    6522                 :        1530 :                     PLpgSQL_recfield *recfield = (PLpgSQL_recfield *) datum;
    6523                 :             :                     PLpgSQL_rec *rec;
    6524                 :             : 
    6525                 :        1530 :                     rec = (PLpgSQL_rec *) (estate->datums[recfield->recparentno]);
    6526                 :             : 
    6527                 :             :                     /*
    6528                 :             :                      * If record variable is NULL, don't risk anything.
    6529                 :             :                      */
    6530         [ -  + ]:        1530 :                     if (rec->erh == NULL)
    6531                 :           0 :                         ok = false;
    6532                 :             : 
    6533                 :             :                     /*
    6534                 :             :                      * Look up the field's properties if we have not already,
    6535                 :             :                      * or if the tuple descriptor ID changed since last time.
    6536                 :             :                      */
    6537         [ +  + ]:        1530 :                     else if (unlikely(recfield->rectupledescid != rec->erh->er_tupdesc_id))
    6538                 :             :                     {
    6539         [ +  - ]:          11 :                         if (expanded_record_lookup_field(rec->erh,
    6540                 :          11 :                                                          recfield->fieldname,
    6541                 :             :                                                          &recfield->finfo))
    6542                 :          11 :                             recfield->rectupledescid = rec->erh->er_tupdesc_id;
    6543                 :             :                         else
    6544                 :           0 :                             ok = false;
    6545                 :             :                     }
    6546                 :        1530 :                     break;
    6547                 :             :                 }
    6548                 :             : 
    6549                 :           0 :             default:
    6550                 :           0 :                 ok = false;
    6551                 :           0 :                 break;
    6552                 :             :         }
    6553                 :             :     }
    6554                 :             : 
    6555                 :             :     /* Return "no such parameter" if not ok */
    6556         [ +  + ]:        7405 :     if (!ok)
    6557                 :             :     {
    6558                 :        2437 :         prm->value = (Datum) 0;
    6559                 :        2437 :         prm->isnull = true;
    6560                 :        2437 :         prm->pflags = 0;
    6561                 :        2437 :         prm->ptype = InvalidOid;
    6562                 :        2437 :         return prm;
    6563                 :             :     }
    6564                 :             : 
    6565                 :             :     /* OK, evaluate the value and store into the return struct */
    6566                 :        4968 :     exec_eval_datum(estate, datum,
    6567                 :             :                     &prm->ptype, &prmtypmod,
    6568                 :             :                     &prm->value, &prm->isnull);
    6569                 :             :     /* We can always mark params as "const" for executor's purposes */
    6570                 :        4968 :     prm->pflags = PARAM_FLAG_CONST;
    6571                 :             : 
    6572                 :             :     /*
    6573                 :             :      * If it's a read/write expanded datum, convert reference to read-only.
    6574                 :             :      * (There's little point in trying to optimize read/write parameters,
    6575                 :             :      * given the cases in which this function is used.)
    6576                 :             :      */
    6577         [ +  + ]:        4968 :     if (datum->dtype == PLPGSQL_DTYPE_VAR)
    6578   [ +  +  +  + ]:        2937 :         prm->value = MakeExpandedObjectReadOnly(prm->value,
    6579                 :             :                                                 prm->isnull,
    6580                 :             :                                                 ((PLpgSQL_var *) datum)->datatype->typlen);
    6581         [ +  + ]:        2031 :     else if (datum->dtype == PLPGSQL_DTYPE_REC)
    6582         [ -  + ]:         333 :         prm->value = MakeExpandedObjectReadOnly(prm->value,
    6583                 :             :                                                 prm->isnull,
    6584                 :             :                                                 -1);
    6585                 :             : 
    6586                 :        4968 :     return prm;
    6587                 :             : }
    6588                 :             : 
    6589                 :             : /*
    6590                 :             :  * plpgsql_param_compile        paramCompile callback for plpgsql parameters
    6591                 :             :  */
    6592                 :             : static void
    6593                 :      108673 : plpgsql_param_compile(ParamListInfo params, Param *param,
    6594                 :             :                       ExprState *state,
    6595                 :             :                       Datum *resv, bool *resnull)
    6596                 :             : {
    6597                 :             :     PLpgSQL_execstate *estate;
    6598                 :             :     PLpgSQL_expr *expr;
    6599                 :             :     int         dno;
    6600                 :             :     PLpgSQL_datum *datum;
    6601                 :             :     ExprEvalStep scratch;
    6602                 :             : 
    6603                 :             :     /* fetch back the hook data */
    6604                 :      108673 :     estate = (PLpgSQL_execstate *) params->paramFetchArg;
    6605                 :      108673 :     expr = (PLpgSQL_expr *) params->parserSetupArg;
    6606                 :             : 
    6607                 :             :     /* paramid's are 1-based, but dnos are 0-based */
    6608                 :      108673 :     dno = param->paramid - 1;
    6609                 :             :     Assert(dno >= 0 && dno < estate->ndatums);
    6610                 :             : 
    6611                 :             :     /* now we can access the target datum */
    6612                 :      108673 :     datum = estate->datums[dno];
    6613                 :             : 
    6614                 :      108673 :     scratch.opcode = EEOP_PARAM_CALLBACK;
    6615                 :      108673 :     scratch.resvalue = resv;
    6616                 :      108673 :     scratch.resnull = resnull;
    6617                 :             : 
    6618                 :             :     /*
    6619                 :             :      * Select appropriate eval function.
    6620                 :             :      *
    6621                 :             :      * First, if this Param references the same varlena-type DTYPE_VAR datum
    6622                 :             :      * that is the target of the assignment containing this simple expression,
    6623                 :             :      * then it's possible we will be able to optimize handling of R/W expanded
    6624                 :             :      * datums.  We don't want to do the work needed to determine that unless
    6625                 :             :      * we actually see a R/W expanded datum at runtime, so install a checking
    6626                 :             :      * function that will figure that out when needed.
    6627                 :             :      *
    6628                 :             :      * Otherwise, it seems worth special-casing DTYPE_VAR and DTYPE_RECFIELD
    6629                 :             :      * for performance.  Also, we can determine in advance whether
    6630                 :             :      * MakeExpandedObjectReadOnly() will be required.  Currently, only
    6631                 :             :      * VAR/PROMISE and REC datums could contain read/write expanded objects.
    6632                 :             :      */
    6633         [ +  + ]:      108673 :     if (datum->dtype == PLPGSQL_DTYPE_VAR)
    6634                 :             :     {
    6635                 :       74523 :         bool        isvarlena = (((PLpgSQL_var *) datum)->datatype->typlen == -1);
    6636                 :             : 
    6637   [ +  +  +  +  :       74523 :         if (isvarlena && dno == expr->target_param && expr->expr_simple_expr)
                   +  - ]
    6638                 :        1984 :             scratch.d.cparam.paramfunc = plpgsql_param_eval_var_check;
    6639         [ +  + ]:       72539 :         else if (isvarlena)
    6640                 :       41147 :             scratch.d.cparam.paramfunc = plpgsql_param_eval_var_ro;
    6641                 :             :         else
    6642                 :       31392 :             scratch.d.cparam.paramfunc = plpgsql_param_eval_var;
    6643                 :             :     }
    6644         [ +  + ]:       34150 :     else if (datum->dtype == PLPGSQL_DTYPE_RECFIELD)
    6645                 :       17784 :         scratch.d.cparam.paramfunc = plpgsql_param_eval_recfield;
    6646         [ +  + ]:       16366 :     else if (datum->dtype == PLPGSQL_DTYPE_PROMISE)
    6647                 :             :     {
    6648         [ +  + ]:       13409 :         if (((PLpgSQL_var *) datum)->datatype->typlen == -1)
    6649                 :       11675 :             scratch.d.cparam.paramfunc = plpgsql_param_eval_generic_ro;
    6650                 :             :         else
    6651                 :        1734 :             scratch.d.cparam.paramfunc = plpgsql_param_eval_generic;
    6652                 :             :     }
    6653         [ +  - ]:        2957 :     else if (datum->dtype == PLPGSQL_DTYPE_REC)
    6654                 :        2957 :         scratch.d.cparam.paramfunc = plpgsql_param_eval_generic_ro;
    6655                 :             :     else
    6656                 :           0 :         scratch.d.cparam.paramfunc = plpgsql_param_eval_generic;
    6657                 :             : 
    6658                 :             :     /*
    6659                 :             :      * Note: it's tempting to use paramarg to store the estate pointer and
    6660                 :             :      * thereby save an indirection or two in the eval functions.  But that
    6661                 :             :      * doesn't work because the compiled expression might be used with
    6662                 :             :      * different estates for the same PL/pgSQL function.  Instead, store
    6663                 :             :      * pointers to the PLpgSQL_expr as well as this specific Param, to support
    6664                 :             :      * plpgsql_param_eval_var_check().
    6665                 :             :      */
    6666                 :      108673 :     scratch.d.cparam.paramarg = expr;
    6667                 :      108673 :     scratch.d.cparam.paramarg2 = param;
    6668                 :      108673 :     scratch.d.cparam.paramid = param->paramid;
    6669                 :      108673 :     scratch.d.cparam.paramtype = param->paramtype;
    6670                 :      108673 :     ExprEvalPushStep(state, &scratch);
    6671                 :      108673 : }
    6672                 :             : 
    6673                 :             : /*
    6674                 :             :  * plpgsql_param_eval_var_check     evaluation of EEOP_PARAM_CALLBACK step
    6675                 :             :  *
    6676                 :             :  * This is specialized to the case of DTYPE_VAR variables for which
    6677                 :             :  * we may need to determine the applicability of a read/write optimization,
    6678                 :             :  * but we've not done that yet.  The work to determine applicability will
    6679                 :             :  * be done at most once (per construction of the PL/pgSQL function's cache
    6680                 :             :  * entry) when we first see that the target variable's old value is a R/W
    6681                 :             :  * expanded object.  If we never do see that, nothing is lost: the amount
    6682                 :             :  * of work done by this function in that case is just about the same as
    6683                 :             :  * what would be done by plpgsql_param_eval_var_ro, which is what we'd
    6684                 :             :  * have used otherwise.
    6685                 :             :  */
    6686                 :             : static void
    6687                 :       20912 : plpgsql_param_eval_var_check(ExprState *state, ExprEvalStep *op,
    6688                 :             :                              ExprContext *econtext)
    6689                 :             : {
    6690                 :             :     ParamListInfo params;
    6691                 :             :     PLpgSQL_execstate *estate;
    6692                 :       20912 :     int         dno = op->d.cparam.paramid - 1;
    6693                 :             :     PLpgSQL_var *var;
    6694                 :             : 
    6695                 :             :     /* fetch back the hook data */
    6696                 :       20912 :     params = econtext->ecxt_param_list_info;
    6697                 :       20912 :     estate = (PLpgSQL_execstate *) params->paramFetchArg;
    6698                 :             :     Assert(dno >= 0 && dno < estate->ndatums);
    6699                 :             : 
    6700                 :             :     /* now we can access the target datum */
    6701                 :       20912 :     var = (PLpgSQL_var *) estate->datums[dno];
    6702                 :             :     Assert(var->dtype == PLPGSQL_DTYPE_VAR);
    6703                 :             : 
    6704                 :             :     /*
    6705                 :             :      * If the variable's current value is a R/W expanded object, it's time to
    6706                 :             :      * decide whether/how to optimize the assignment.
    6707                 :             :      */
    6708   [ +  +  +  + ]:       41783 :     if (!var->isnull &&
    6709                 :       20871 :         VARATT_IS_EXTERNAL_EXPANDED_RW(DatumGetPointer(var->value)))
    6710                 :             :     {
    6711                 :         106 :         PLpgSQL_expr *expr = (PLpgSQL_expr *) op->d.cparam.paramarg;
    6712                 :         106 :         Param      *param = (Param *) op->d.cparam.paramarg2;
    6713                 :             : 
    6714                 :             :         /*
    6715                 :             :          * We might have already figured this out while evaluating some other
    6716                 :             :          * Param referencing the same variable, so check expr_rwopt first.
    6717                 :             :          */
    6718         [ +  + ]:         106 :         if (expr->expr_rwopt == PLPGSQL_RWOPT_UNKNOWN)
    6719                 :          65 :             exec_check_rw_parameter(expr, op->d.cparam.paramid);
    6720                 :             : 
    6721                 :             :         /*
    6722                 :             :          * Update the callback pointer to match what we decided to do, so that
    6723                 :             :          * this function will not be called again.  Then pass off this
    6724                 :             :          * execution to the newly-selected function.
    6725                 :             :          */
    6726   [ -  +  +  +  :         106 :         switch (expr->expr_rwopt)
                      - ]
    6727                 :             :         {
    6728                 :           0 :             case PLPGSQL_RWOPT_UNKNOWN:
    6729                 :             :                 Assert(false);
    6730                 :           0 :                 break;
    6731                 :           2 :             case PLPGSQL_RWOPT_NOPE:
    6732                 :             :                 /* Force the value to read-only in all future executions */
    6733                 :           2 :                 op->d.cparam.paramfunc = plpgsql_param_eval_var_ro;
    6734                 :           2 :                 plpgsql_param_eval_var_ro(state, op, econtext);
    6735                 :           2 :                 break;
    6736                 :          98 :             case PLPGSQL_RWOPT_TRANSFER:
    6737                 :             :                 /* There can be only one matching Param in this case */
    6738                 :             :                 Assert(param == expr->expr_rw_param);
    6739                 :             :                 /* When the value is read/write, transfer to exec context */
    6740                 :          98 :                 op->d.cparam.paramfunc = plpgsql_param_eval_var_transfer;
    6741                 :          98 :                 plpgsql_param_eval_var_transfer(state, op, econtext);
    6742                 :          98 :                 break;
    6743                 :           6 :             case PLPGSQL_RWOPT_INPLACE:
    6744         [ +  + ]:           6 :                 if (param == expr->expr_rw_param)
    6745                 :             :                 {
    6746                 :             :                     /* When the value is read/write, deliver it as-is */
    6747                 :           3 :                     op->d.cparam.paramfunc = plpgsql_param_eval_var;
    6748                 :           3 :                     plpgsql_param_eval_var(state, op, econtext);
    6749                 :             :                 }
    6750                 :             :                 else
    6751                 :             :                 {
    6752                 :             :                     /* Not the optimizable reference, so force to read-only */
    6753                 :           3 :                     op->d.cparam.paramfunc = plpgsql_param_eval_var_ro;
    6754                 :           3 :                     plpgsql_param_eval_var_ro(state, op, econtext);
    6755                 :             :                 }
    6756                 :           6 :                 break;
    6757                 :             :         }
    6758                 :         106 :         return;
    6759                 :             :     }
    6760                 :             : 
    6761                 :             :     /*
    6762                 :             :      * Otherwise, continue to postpone that decision, and execute an inlined
    6763                 :             :      * version of exec_eval_datum().  Although this value could potentially
    6764                 :             :      * need MakeExpandedObjectReadOnly, we know it doesn't right now.
    6765                 :             :      */
    6766                 :       20806 :     *op->resvalue = var->value;
    6767                 :       20806 :     *op->resnull = var->isnull;
    6768                 :             : 
    6769                 :             :     /* safety check -- an assertion should be sufficient */
    6770                 :             :     Assert(var->datatype->typoid == op->d.cparam.paramtype);
    6771                 :             : }
    6772                 :             : 
    6773                 :             : /*
    6774                 :             :  * plpgsql_param_eval_var_transfer      evaluation of EEOP_PARAM_CALLBACK step
    6775                 :             :  *
    6776                 :             :  * This is specialized to the case of DTYPE_VAR variables for which
    6777                 :             :  * we have determined that a read/write expanded value can be handed off
    6778                 :             :  * into execution of the expression (and then possibly returned to our
    6779                 :             :  * function's ownership afterwards).  We have to test though, because the
    6780                 :             :  * variable might not contain a read/write expanded value during this
    6781                 :             :  * execution.
    6782                 :             :  */
    6783                 :             : static void
    6784                 :         150 : plpgsql_param_eval_var_transfer(ExprState *state, ExprEvalStep *op,
    6785                 :             :                                 ExprContext *econtext)
    6786                 :             : {
    6787                 :             :     ParamListInfo params;
    6788                 :             :     PLpgSQL_execstate *estate;
    6789                 :         150 :     int         dno = op->d.cparam.paramid - 1;
    6790                 :             :     PLpgSQL_var *var;
    6791                 :             : 
    6792                 :             :     /* fetch back the hook data */
    6793                 :         150 :     params = econtext->ecxt_param_list_info;
    6794                 :         150 :     estate = (PLpgSQL_execstate *) params->paramFetchArg;
    6795                 :             :     Assert(dno >= 0 && dno < estate->ndatums);
    6796                 :             : 
    6797                 :             :     /* now we can access the target datum */
    6798                 :         150 :     var = (PLpgSQL_var *) estate->datums[dno];
    6799                 :             :     Assert(var->dtype == PLPGSQL_DTYPE_VAR);
    6800                 :             : 
    6801                 :             :     /*
    6802                 :             :      * If the variable's current value is a R/W expanded object, transfer its
    6803                 :             :      * ownership into the expression execution context, then drop our own
    6804                 :             :      * reference to the value by setting the variable to NULL.  That'll be
    6805                 :             :      * overwritten (perhaps with this same object) when control comes back
    6806                 :             :      * from the expression.
    6807                 :             :      */
    6808   [ +  -  +  - ]:         300 :     if (!var->isnull &&
    6809                 :         150 :         VARATT_IS_EXTERNAL_EXPANDED_RW(DatumGetPointer(var->value)))
    6810                 :             :     {
    6811                 :         300 :         *op->resvalue = TransferExpandedObject(var->value,
    6812                 :         150 :                                                get_eval_mcontext(estate));
    6813                 :         150 :         *op->resnull = false;
    6814                 :             : 
    6815                 :         150 :         var->value = (Datum) 0;
    6816                 :         150 :         var->isnull = true;
    6817                 :         150 :         var->freeval = false;
    6818                 :             :     }
    6819                 :             :     else
    6820                 :             :     {
    6821                 :             :         /*
    6822                 :             :          * Otherwise we can pass the variable's value directly; we now know
    6823                 :             :          * that MakeExpandedObjectReadOnly isn't needed.
    6824                 :             :          */
    6825                 :           0 :         *op->resvalue = var->value;
    6826                 :           0 :         *op->resnull = var->isnull;
    6827                 :             :     }
    6828                 :             : 
    6829                 :             :     /* safety check -- an assertion should be sufficient */
    6830                 :             :     Assert(var->datatype->typoid == op->d.cparam.paramtype);
    6831                 :         150 : }
    6832                 :             : 
    6833                 :             : /*
    6834                 :             :  * plpgsql_param_eval_var       evaluation of EEOP_PARAM_CALLBACK step
    6835                 :             :  *
    6836                 :             :  * This is specialized to the case of DTYPE_VAR variables for which
    6837                 :             :  * we do not need to invoke MakeExpandedObjectReadOnly.
    6838                 :             :  */
    6839                 :             : static void
    6840                 :      136726 : plpgsql_param_eval_var(ExprState *state, ExprEvalStep *op,
    6841                 :             :                        ExprContext *econtext)
    6842                 :             : {
    6843                 :             :     ParamListInfo params;
    6844                 :             :     PLpgSQL_execstate *estate;
    6845                 :      136726 :     int         dno = op->d.cparam.paramid - 1;
    6846                 :             :     PLpgSQL_var *var;
    6847                 :             : 
    6848                 :             :     /* fetch back the hook data */
    6849                 :      136726 :     params = econtext->ecxt_param_list_info;
    6850                 :      136726 :     estate = (PLpgSQL_execstate *) params->paramFetchArg;
    6851                 :             :     Assert(dno >= 0 && dno < estate->ndatums);
    6852                 :             : 
    6853                 :             :     /* now we can access the target datum */
    6854                 :      136726 :     var = (PLpgSQL_var *) estate->datums[dno];
    6855                 :             :     Assert(var->dtype == PLPGSQL_DTYPE_VAR);
    6856                 :             : 
    6857                 :             :     /* inlined version of exec_eval_datum() */
    6858                 :      136726 :     *op->resvalue = var->value;
    6859                 :      136726 :     *op->resnull = var->isnull;
    6860                 :             : 
    6861                 :             :     /* safety check -- an assertion should be sufficient */
    6862                 :             :     Assert(var->datatype->typoid == op->d.cparam.paramtype);
    6863                 :      136726 : }
    6864                 :             : 
    6865                 :             : /*
    6866                 :             :  * plpgsql_param_eval_var_ro        evaluation of EEOP_PARAM_CALLBACK step
    6867                 :             :  *
    6868                 :             :  * This is specialized to the case of DTYPE_VAR variables for which
    6869                 :             :  * we need to invoke MakeExpandedObjectReadOnly.
    6870                 :             :  */
    6871                 :             : static void
    6872                 :       98978 : plpgsql_param_eval_var_ro(ExprState *state, ExprEvalStep *op,
    6873                 :             :                           ExprContext *econtext)
    6874                 :             : {
    6875                 :             :     ParamListInfo params;
    6876                 :             :     PLpgSQL_execstate *estate;
    6877                 :       98978 :     int         dno = op->d.cparam.paramid - 1;
    6878                 :             :     PLpgSQL_var *var;
    6879                 :             : 
    6880                 :             :     /* fetch back the hook data */
    6881                 :       98978 :     params = econtext->ecxt_param_list_info;
    6882                 :       98978 :     estate = (PLpgSQL_execstate *) params->paramFetchArg;
    6883                 :             :     Assert(dno >= 0 && dno < estate->ndatums);
    6884                 :             : 
    6885                 :             :     /* now we can access the target datum */
    6886                 :       98978 :     var = (PLpgSQL_var *) estate->datums[dno];
    6887                 :             :     Assert(var->dtype == PLPGSQL_DTYPE_VAR);
    6888                 :             : 
    6889                 :             :     /*
    6890                 :             :      * Inlined version of exec_eval_datum() ... and while we're at it, force
    6891                 :             :      * expanded datums to read-only.
    6892                 :             :      */
    6893         [ +  + ]:       98978 :     *op->resvalue = MakeExpandedObjectReadOnly(var->value,
    6894                 :             :                                                var->isnull,
    6895                 :             :                                                -1);
    6896                 :       98978 :     *op->resnull = var->isnull;
    6897                 :             : 
    6898                 :             :     /* safety check -- an assertion should be sufficient */
    6899                 :             :     Assert(var->datatype->typoid == op->d.cparam.paramtype);
    6900                 :       98978 : }
    6901                 :             : 
    6902                 :             : /*
    6903                 :             :  * plpgsql_param_eval_recfield      evaluation of EEOP_PARAM_CALLBACK step
    6904                 :             :  *
    6905                 :             :  * This is specialized to the case of DTYPE_RECFIELD variables, for which
    6906                 :             :  * we never need to invoke MakeExpandedObjectReadOnly.
    6907                 :             :  */
    6908                 :             : static void
    6909                 :       43821 : plpgsql_param_eval_recfield(ExprState *state, ExprEvalStep *op,
    6910                 :             :                             ExprContext *econtext)
    6911                 :             : {
    6912                 :             :     ParamListInfo params;
    6913                 :             :     PLpgSQL_execstate *estate;
    6914                 :       43821 :     int         dno = op->d.cparam.paramid - 1;
    6915                 :             :     PLpgSQL_recfield *recfield;
    6916                 :             :     PLpgSQL_rec *rec;
    6917                 :             :     ExpandedRecordHeader *erh;
    6918                 :             : 
    6919                 :             :     /* fetch back the hook data */
    6920                 :       43821 :     params = econtext->ecxt_param_list_info;
    6921                 :       43821 :     estate = (PLpgSQL_execstate *) params->paramFetchArg;
    6922                 :             :     Assert(dno >= 0 && dno < estate->ndatums);
    6923                 :             : 
    6924                 :             :     /* now we can access the target datum */
    6925                 :       43821 :     recfield = (PLpgSQL_recfield *) estate->datums[dno];
    6926                 :             :     Assert(recfield->dtype == PLPGSQL_DTYPE_RECFIELD);
    6927                 :             : 
    6928                 :             :     /* inline the relevant part of exec_eval_datum */
    6929                 :       43821 :     rec = (PLpgSQL_rec *) (estate->datums[recfield->recparentno]);
    6930                 :       43821 :     erh = rec->erh;
    6931                 :             : 
    6932                 :             :     /*
    6933                 :             :      * If record variable is NULL, instantiate it if it has a named composite
    6934                 :             :      * type, else complain.  (This won't change the logical state of the
    6935                 :             :      * record: it's still NULL.)
    6936                 :             :      */
    6937         [ +  + ]:       43821 :     if (erh == NULL)
    6938                 :             :     {
    6939                 :           1 :         instantiate_empty_record_variable(estate, rec);
    6940                 :           1 :         erh = rec->erh;
    6941                 :             :     }
    6942                 :             : 
    6943                 :             :     /*
    6944                 :             :      * Look up the field's properties if we have not already, or if the tuple
    6945                 :             :      * descriptor ID changed since last time.
    6946                 :             :      */
    6947         [ +  + ]:       43821 :     if (unlikely(recfield->rectupledescid != erh->er_tupdesc_id))
    6948                 :             :     {
    6949         [ +  + ]:        2769 :         if (!expanded_record_lookup_field(erh,
    6950                 :        2769 :                                           recfield->fieldname,
    6951                 :             :                                           &recfield->finfo))
    6952         [ +  - ]:           1 :             ereport(ERROR,
    6953                 :             :                     (errcode(ERRCODE_UNDEFINED_COLUMN),
    6954                 :             :                      errmsg("record \"%s\" has no field \"%s\"",
    6955                 :             :                             rec->refname, recfield->fieldname)));
    6956                 :        2768 :         recfield->rectupledescid = erh->er_tupdesc_id;
    6957                 :             :     }
    6958                 :             : 
    6959                 :             :     /* OK to fetch the field value. */
    6960                 :       43820 :     *op->resvalue = expanded_record_get_field(erh,
    6961                 :             :                                               recfield->finfo.fnumber,
    6962                 :             :                                               op->resnull);
    6963                 :             : 
    6964                 :             :     /* safety check -- needed for, eg, record fields */
    6965         [ +  + ]:       43820 :     if (unlikely(recfield->finfo.ftypeid != op->d.cparam.paramtype))
    6966         [ +  - ]:           2 :         ereport(ERROR,
    6967                 :             :                 (errcode(ERRCODE_DATATYPE_MISMATCH),
    6968                 :             :                  errmsg("type of parameter %d (%s) does not match that when preparing the plan (%s)",
    6969                 :             :                         op->d.cparam.paramid,
    6970                 :             :                         format_type_be(recfield->finfo.ftypeid),
    6971                 :             :                         format_type_be(op->d.cparam.paramtype))));
    6972                 :       43818 : }
    6973                 :             : 
    6974                 :             : /*
    6975                 :             :  * plpgsql_param_eval_generic       evaluation of EEOP_PARAM_CALLBACK step
    6976                 :             :  *
    6977                 :             :  * This handles all variable types, but assumes we do not need to invoke
    6978                 :             :  * MakeExpandedObjectReadOnly.
    6979                 :             :  */
    6980                 :             : static void
    6981                 :        1891 : plpgsql_param_eval_generic(ExprState *state, ExprEvalStep *op,
    6982                 :             :                            ExprContext *econtext)
    6983                 :             : {
    6984                 :             :     ParamListInfo params;
    6985                 :             :     PLpgSQL_execstate *estate;
    6986                 :        1891 :     int         dno = op->d.cparam.paramid - 1;
    6987                 :             :     PLpgSQL_datum *datum;
    6988                 :             :     Oid         datumtype;
    6989                 :             :     int32       datumtypmod;
    6990                 :             : 
    6991                 :             :     /* fetch back the hook data */
    6992                 :        1891 :     params = econtext->ecxt_param_list_info;
    6993                 :        1891 :     estate = (PLpgSQL_execstate *) params->paramFetchArg;
    6994                 :             :     Assert(dno >= 0 && dno < estate->ndatums);
    6995                 :             : 
    6996                 :             :     /* now we can access the target datum */
    6997                 :        1891 :     datum = estate->datums[dno];
    6998                 :             : 
    6999                 :             :     /* fetch datum's value */
    7000                 :        1891 :     exec_eval_datum(estate, datum,
    7001                 :             :                     &datumtype, &datumtypmod,
    7002                 :             :                     op->resvalue, op->resnull);
    7003                 :             : 
    7004                 :             :     /* safety check -- needed for, eg, record fields */
    7005         [ -  + ]:        1891 :     if (unlikely(datumtype != op->d.cparam.paramtype))
    7006         [ #  # ]:           0 :         ereport(ERROR,
    7007                 :             :                 (errcode(ERRCODE_DATATYPE_MISMATCH),
    7008                 :             :                  errmsg("type of parameter %d (%s) does not match that when preparing the plan (%s)",
    7009                 :             :                         op->d.cparam.paramid,
    7010                 :             :                         format_type_be(datumtype),
    7011                 :             :                         format_type_be(op->d.cparam.paramtype))));
    7012                 :        1891 : }
    7013                 :             : 
    7014                 :             : /*
    7015                 :             :  * plpgsql_param_eval_generic_ro    evaluation of EEOP_PARAM_CALLBACK step
    7016                 :             :  *
    7017                 :             :  * This handles all variable types, but assumes we need to invoke
    7018                 :             :  * MakeExpandedObjectReadOnly (hence, variable must be of a varlena type).
    7019                 :             :  */
    7020                 :             : static void
    7021                 :       15723 : plpgsql_param_eval_generic_ro(ExprState *state, ExprEvalStep *op,
    7022                 :             :                               ExprContext *econtext)
    7023                 :             : {
    7024                 :             :     ParamListInfo params;
    7025                 :             :     PLpgSQL_execstate *estate;
    7026                 :       15723 :     int         dno = op->d.cparam.paramid - 1;
    7027                 :             :     PLpgSQL_datum *datum;
    7028                 :             :     Oid         datumtype;
    7029                 :             :     int32       datumtypmod;
    7030                 :             : 
    7031                 :             :     /* fetch back the hook data */
    7032                 :       15723 :     params = econtext->ecxt_param_list_info;
    7033                 :       15723 :     estate = (PLpgSQL_execstate *) params->paramFetchArg;
    7034                 :             :     Assert(dno >= 0 && dno < estate->ndatums);
    7035                 :             : 
    7036                 :             :     /* now we can access the target datum */
    7037                 :       15723 :     datum = estate->datums[dno];
    7038                 :             : 
    7039                 :             :     /* fetch datum's value */
    7040                 :       15723 :     exec_eval_datum(estate, datum,
    7041                 :             :                     &datumtype, &datumtypmod,
    7042                 :             :                     op->resvalue, op->resnull);
    7043                 :             : 
    7044                 :             :     /* safety check -- needed for, eg, record fields */
    7045         [ -  + ]:       15723 :     if (unlikely(datumtype != op->d.cparam.paramtype))
    7046         [ #  # ]:           0 :         ereport(ERROR,
    7047                 :             :                 (errcode(ERRCODE_DATATYPE_MISMATCH),
    7048                 :             :                  errmsg("type of parameter %d (%s) does not match that when preparing the plan (%s)",
    7049                 :             :                         op->d.cparam.paramid,
    7050                 :             :                         format_type_be(datumtype),
    7051                 :             :                         format_type_be(op->d.cparam.paramtype))));
    7052                 :             : 
    7053                 :             :     /* force the value to read-only */
    7054         [ +  + ]:       15723 :     *op->resvalue = MakeExpandedObjectReadOnly(*op->resvalue,
    7055                 :             :                                                *op->resnull,
    7056                 :             :                                                -1);
    7057                 :       15723 : }
    7058                 :             : 
    7059                 :             : 
    7060                 :             : /*
    7061                 :             :  * exec_move_row            Move one tuple's values into a record or row
    7062                 :             :  *
    7063                 :             :  * tup and tupdesc may both be NULL if we're just assigning an indeterminate
    7064                 :             :  * composite NULL to the target.  Alternatively, can have tup be NULL and
    7065                 :             :  * tupdesc not NULL, in which case we assign a row of NULLs to the target.
    7066                 :             :  *
    7067                 :             :  * Since this uses the mcontext for workspace, caller should eventually call
    7068                 :             :  * exec_eval_cleanup to prevent long-term memory leaks.
    7069                 :             :  */
    7070                 :             : static void
    7071                 :       47383 : exec_move_row(PLpgSQL_execstate *estate,
    7072                 :             :               PLpgSQL_variable *target,
    7073                 :             :               HeapTuple tup, TupleDesc tupdesc)
    7074                 :             : {
    7075                 :       47383 :     ExpandedRecordHeader *newerh = NULL;
    7076                 :             : 
    7077                 :             :     /*
    7078                 :             :      * If target is RECORD, we may be able to avoid field-by-field processing.
    7079                 :             :      */
    7080         [ +  + ]:       47383 :     if (target->dtype == PLPGSQL_DTYPE_REC)
    7081                 :             :     {
    7082                 :        7390 :         PLpgSQL_rec *rec = (PLpgSQL_rec *) target;
    7083                 :             : 
    7084                 :             :         /*
    7085                 :             :          * If we have no source tupdesc, just set the record variable to NULL.
    7086                 :             :          * (If we have a source tupdesc but not a tuple, we'll set the
    7087                 :             :          * variable to a row of nulls, instead.  This is odd perhaps, but
    7088                 :             :          * backwards compatible.)
    7089                 :             :          */
    7090         [ +  + ]:        7390 :         if (tupdesc == NULL)
    7091                 :             :         {
    7092         [ +  - ]:        3527 :             if (rec->datatype &&
    7093         [ +  + ]:        3527 :                 rec->datatype->typtype == TYPTYPE_DOMAIN)
    7094                 :             :             {
    7095                 :             :                 /*
    7096                 :             :                  * If it's a composite domain, NULL might not be a legal
    7097                 :             :                  * value, so we instead need to make an empty expanded record
    7098                 :             :                  * and ensure that domain type checking gets done.  If there
    7099                 :             :                  * is already an expanded record, piggyback on its lookups.
    7100                 :             :                  */
    7101                 :          30 :                 newerh = make_expanded_record_for_rec(estate, rec,
    7102                 :             :                                                       NULL, rec->erh);
    7103                 :          30 :                 expanded_record_set_tuple(newerh, NULL, false, false);
    7104                 :          26 :                 assign_record_var(estate, rec, newerh);
    7105                 :             :             }
    7106                 :             :             else
    7107                 :             :             {
    7108                 :             :                 /* Just clear it to NULL */
    7109         [ +  + ]:        3497 :                 if (rec->erh)
    7110                 :          81 :                     DeleteExpandedObject(ExpandedRecordGetDatum(rec->erh));
    7111                 :        3497 :                 rec->erh = NULL;
    7112                 :             :             }
    7113                 :        3523 :             return;
    7114                 :             :         }
    7115                 :             : 
    7116                 :             :         /*
    7117                 :             :          * Build a new expanded record with appropriate tupdesc.
    7118                 :             :          */
    7119                 :        3863 :         newerh = make_expanded_record_for_rec(estate, rec, tupdesc, NULL);
    7120                 :             : 
    7121                 :             :         /*
    7122                 :             :          * If the rowtypes match, or if we have no tuple anyway, we can
    7123                 :             :          * complete the assignment without field-by-field processing.
    7124                 :             :          *
    7125                 :             :          * The tests here are ordered more or less in order of cheapness.  We
    7126                 :             :          * can easily detect it will work if the target is declared RECORD or
    7127                 :             :          * has the same typeid as the source.  But when assigning from a query
    7128                 :             :          * result, it's common to have a source tupdesc that's labeled RECORD
    7129                 :             :          * but is actually physically compatible with a named-composite-type
    7130                 :             :          * target, so it's worth spending extra cycles to check for that.
    7131                 :             :          */
    7132         [ +  + ]:        3863 :         if (rec->rectypeid == RECORDOID ||
    7133   [ +  +  +  - ]:         189 :             rec->rectypeid == tupdesc->tdtypeid ||
    7134         [ +  + ]:         188 :             !HeapTupleIsValid(tup) ||
    7135                 :         188 :             compatible_tupdescs(tupdesc, expanded_record_get_tupdesc(newerh)))
    7136                 :             :         {
    7137         [ +  + ]:        3781 :             if (!HeapTupleIsValid(tup))
    7138                 :             :             {
    7139                 :             :                 /* No data, so force the record into all-nulls state */
    7140                 :        1036 :                 deconstruct_expanded_record(newerh);
    7141                 :             :             }
    7142                 :             :             else
    7143                 :             :             {
    7144                 :             :                 /* No coercion is needed, so just assign the row value */
    7145                 :        2745 :                 expanded_record_set_tuple(newerh, tup, true, !estate->atomic);
    7146                 :             :             }
    7147                 :             : 
    7148                 :             :             /* Complete the assignment */
    7149                 :        3778 :             assign_record_var(estate, rec, newerh);
    7150                 :             : 
    7151                 :        3778 :             return;
    7152                 :             :         }
    7153                 :             :     }
    7154                 :             : 
    7155                 :             :     /*
    7156                 :             :      * Otherwise, deconstruct the tuple and do field-by-field assignment,
    7157                 :             :      * using exec_move_row_from_fields.
    7158                 :             :      */
    7159   [ +  -  +  + ]:       40075 :     if (tupdesc && HeapTupleIsValid(tup))
    7160                 :       39929 :     {
    7161                 :       39950 :         int         td_natts = tupdesc->natts;
    7162                 :             :         Datum      *values;
    7163                 :             :         bool       *nulls;
    7164                 :             :         Datum       values_local[64];
    7165                 :             :         bool        nulls_local[64];
    7166                 :             : 
    7167                 :             :         /*
    7168                 :             :          * Need workspace arrays.  If td_natts is small enough, use local
    7169                 :             :          * arrays to save doing a palloc.  Even if it's not small, we can
    7170                 :             :          * allocate both the Datum and isnull arrays in one palloc chunk.
    7171                 :             :          */
    7172         [ +  - ]:       39950 :         if (td_natts <= lengthof(values_local))
    7173                 :             :         {
    7174                 :       39950 :             values = values_local;
    7175                 :       39950 :             nulls = nulls_local;
    7176                 :             :         }
    7177                 :             :         else
    7178                 :             :         {
    7179                 :             :             char       *chunk;
    7180                 :             : 
    7181                 :           0 :             chunk = eval_mcontext_alloc(estate,
    7182                 :             :                                         td_natts * (sizeof(Datum) + sizeof(bool)));
    7183                 :           0 :             values = (Datum *) chunk;
    7184                 :           0 :             nulls = (bool *) (chunk + td_natts * sizeof(Datum));
    7185                 :             :         }
    7186                 :             : 
    7187                 :       39950 :         heap_deform_tuple(tup, tupdesc, values, nulls);
    7188                 :             : 
    7189                 :       39950 :         exec_move_row_from_fields(estate, target, newerh,
    7190                 :             :                                   values, nulls, tupdesc);
    7191                 :             :     }
    7192                 :             :     else
    7193                 :             :     {
    7194                 :             :         /*
    7195                 :             :          * Assign all-nulls.
    7196                 :             :          */
    7197                 :         125 :         exec_move_row_from_fields(estate, target, newerh,
    7198                 :             :                                   NULL, NULL, NULL);
    7199                 :             :     }
    7200                 :             : }
    7201                 :             : 
    7202                 :             : /*
    7203                 :             :  * Verify that a PLpgSQL_rec's rectypeid is up-to-date.
    7204                 :             :  */
    7205                 :             : static void
    7206                 :         508 : revalidate_rectypeid(PLpgSQL_rec *rec)
    7207                 :             : {
    7208                 :         508 :     PLpgSQL_type *typ = rec->datatype;
    7209                 :             :     TypeCacheEntry *typentry;
    7210                 :             : 
    7211         [ +  + ]:         508 :     if (rec->rectypeid == RECORDOID)
    7212                 :         152 :         return;                 /* it's RECORD, so nothing to do */
    7213                 :             :     Assert(typ != NULL);
    7214         [ +  - ]:         356 :     if (typ->tcache &&
    7215         [ +  + ]:         356 :         typ->tcache->tupDesc_identifier == typ->tupdesc_id)
    7216                 :             :     {
    7217                 :             :         /*
    7218                 :             :          * Although *typ is known up-to-date, it's possible that rectypeid
    7219                 :             :          * isn't, because *rec is cloned during each function startup from a
    7220                 :             :          * copy that we don't have a good way to update.  Hence, forcibly fix
    7221                 :             :          * rectypeid before returning.
    7222                 :             :          */
    7223                 :         320 :         rec->rectypeid = typ->typoid;
    7224                 :         320 :         return;
    7225                 :             :     }
    7226                 :             : 
    7227                 :             :     /*
    7228                 :             :      * typcache entry has suffered invalidation, so re-look-up the type name
    7229                 :             :      * if possible, and then recheck the type OID.  If we don't have a
    7230                 :             :      * TypeName, then we just have to soldier on with the OID we've got.
    7231                 :             :      */
    7232         [ +  + ]:          36 :     if (typ->origtypname != NULL)
    7233                 :             :     {
    7234                 :             :         /* this bit should match parse_datatype() in pl_gram.y */
    7235                 :          33 :         typenameTypeIdAndMod(NULL, typ->origtypname,
    7236                 :             :                              &typ->typoid,
    7237                 :             :                              &typ->atttypmod);
    7238                 :             :     }
    7239                 :             : 
    7240                 :             :     /* this bit should match build_datatype() in pl_comp.c */
    7241                 :          35 :     typentry = lookup_type_cache(typ->typoid,
    7242                 :             :                                  TYPECACHE_TUPDESC |
    7243                 :             :                                  TYPECACHE_DOMAIN_BASE_INFO);
    7244         [ -  + ]:          35 :     if (typentry->typtype == TYPTYPE_DOMAIN)
    7245                 :           0 :         typentry = lookup_type_cache(typentry->domainBaseType,
    7246                 :             :                                      TYPECACHE_TUPDESC);
    7247         [ -  + ]:          35 :     if (typentry->tupDesc == NULL)
    7248                 :             :     {
    7249                 :             :         /*
    7250                 :             :          * If we get here, user tried to replace a composite type with a
    7251                 :             :          * non-composite one.  We're not gonna support that.
    7252                 :             :          */
    7253         [ #  # ]:           0 :         ereport(ERROR,
    7254                 :             :                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
    7255                 :             :                  errmsg("type %s is not composite",
    7256                 :             :                         format_type_be(typ->typoid))));
    7257                 :             :     }
    7258                 :             : 
    7259                 :             :     /*
    7260                 :             :      * Update tcache and tupdesc_id.  Since we don't support changing to a
    7261                 :             :      * non-composite type, none of the rest of *typ needs to change.
    7262                 :             :      */
    7263                 :          35 :     typ->tcache = typentry;
    7264                 :          35 :     typ->tupdesc_id = typentry->tupDesc_identifier;
    7265                 :             : 
    7266                 :             :     /*
    7267                 :             :      * Update *rec, too.  (We'll deal with subsidiary RECFIELDs as needed.)
    7268                 :             :      */
    7269                 :          35 :     rec->rectypeid = typ->typoid;
    7270                 :             : }
    7271                 :             : 
    7272                 :             : /*
    7273                 :             :  * Build an expanded record object suitable for assignment to "rec".
    7274                 :             :  *
    7275                 :             :  * Caller must supply either a source tuple descriptor or a source expanded
    7276                 :             :  * record (not both).  If the record variable has declared type RECORD,
    7277                 :             :  * it'll adopt the source's rowtype.  Even if it doesn't, we may be able to
    7278                 :             :  * piggyback on a source expanded record to save a typcache lookup.
    7279                 :             :  *
    7280                 :             :  * Caller must fill the object with data, then do assign_record_var().
    7281                 :             :  *
    7282                 :             :  * The new record is initially put into the mcontext, so it will be cleaned up
    7283                 :             :  * if we fail before reaching assign_record_var().
    7284                 :             :  */
    7285                 :             : static ExpandedRecordHeader *
    7286                 :        4065 : make_expanded_record_for_rec(PLpgSQL_execstate *estate,
    7287                 :             :                              PLpgSQL_rec *rec,
    7288                 :             :                              TupleDesc srctupdesc,
    7289                 :             :                              ExpandedRecordHeader *srcerh)
    7290                 :             : {
    7291                 :             :     ExpandedRecordHeader *newerh;
    7292                 :        4065 :     MemoryContext mcontext = get_eval_mcontext(estate);
    7293                 :             : 
    7294         [ +  + ]:        4065 :     if (rec->rectypeid != RECORDOID)
    7295                 :             :     {
    7296                 :             :         /*
    7297                 :             :          * Make sure rec->rectypeid is up-to-date before using it.
    7298                 :             :          */
    7299                 :         240 :         revalidate_rectypeid(rec);
    7300                 :             : 
    7301                 :             :         /*
    7302                 :             :          * New record must be of desired type, but maybe srcerh has already
    7303                 :             :          * done all the same lookups.
    7304                 :             :          */
    7305   [ +  +  +  + ]:         240 :         if (srcerh && rec->rectypeid == srcerh->er_decltypeid)
    7306                 :          14 :             newerh = make_expanded_record_from_exprecord(srcerh,
    7307                 :             :                                                          mcontext);
    7308                 :             :         else
    7309                 :         226 :             newerh = make_expanded_record_from_typeid(rec->rectypeid, -1,
    7310                 :             :                                                       mcontext);
    7311                 :             :     }
    7312                 :             :     else
    7313                 :             :     {
    7314                 :             :         /*
    7315                 :             :          * We'll adopt the input tupdesc.  We can still use
    7316                 :             :          * make_expanded_record_from_exprecord, if srcerh isn't a composite
    7317                 :             :          * domain.  (If it is, we effectively adopt its base type.)
    7318                 :             :          */
    7319   [ +  +  +  + ]:        3825 :         if (srcerh && !ExpandedRecordIsDomain(srcerh))
    7320                 :         149 :             newerh = make_expanded_record_from_exprecord(srcerh,
    7321                 :             :                                                          mcontext);
    7322                 :             :         else
    7323                 :             :         {
    7324         [ +  + ]:        3676 :             if (!srctupdesc)
    7325                 :           2 :                 srctupdesc = expanded_record_get_tupdesc(srcerh);
    7326                 :        3676 :             newerh = make_expanded_record_from_tupdesc(srctupdesc,
    7327                 :             :                                                        mcontext);
    7328                 :             :         }
    7329                 :             :     }
    7330                 :             : 
    7331                 :        4065 :     return newerh;
    7332                 :             : }
    7333                 :             : 
    7334                 :             : /*
    7335                 :             :  * exec_move_row_from_fields    Move arrays of field values into a record or row
    7336                 :             :  *
    7337                 :             :  * When assigning to a record, the caller must have already created a suitable
    7338                 :             :  * new expanded record object, newerh.  Pass NULL when assigning to a row.
    7339                 :             :  *
    7340                 :             :  * tupdesc describes the input row, which might have different column
    7341                 :             :  * types and/or different dropped-column positions than the target.
    7342                 :             :  * values/nulls/tupdesc can all be NULL if we just want to assign nulls to
    7343                 :             :  * all fields of the record or row.
    7344                 :             :  *
    7345                 :             :  * Since this uses the mcontext for workspace, caller should eventually call
    7346                 :             :  * exec_eval_cleanup to prevent long-term memory leaks.
    7347                 :             :  */
    7348                 :             : static void
    7349                 :       40086 : exec_move_row_from_fields(PLpgSQL_execstate *estate,
    7350                 :             :                           PLpgSQL_variable *target,
    7351                 :             :                           ExpandedRecordHeader *newerh,
    7352                 :             :                           Datum *values, bool *nulls,
    7353                 :             :                           TupleDesc tupdesc)
    7354                 :             : {
    7355         [ +  + ]:       40086 :     int         td_natts = tupdesc ? tupdesc->natts : 0;
    7356                 :             :     int         fnum;
    7357                 :             :     int         anum;
    7358                 :       40086 :     int         strict_multiassignment_level = 0;
    7359                 :             : 
    7360                 :             :     /*
    7361                 :             :      * The extra check strict strict_multi_assignment can be active, only when
    7362                 :             :      * input tupdesc is specified.
    7363                 :             :      */
    7364         [ +  + ]:       40086 :     if (tupdesc != NULL)
    7365                 :             :     {
    7366         [ +  + ]:       39961 :         if (plpgsql_extra_errors & PLPGSQL_XCHECK_STRICTMULTIASSIGNMENT)
    7367                 :          24 :             strict_multiassignment_level = ERROR;
    7368         [ +  + ]:       39937 :         else if (plpgsql_extra_warnings & PLPGSQL_XCHECK_STRICTMULTIASSIGNMENT)
    7369                 :          12 :             strict_multiassignment_level = WARNING;
    7370                 :             :     }
    7371                 :             : 
    7372                 :             :     /* Handle RECORD-target case */
    7373         [ +  + ]:       40086 :     if (target->dtype == PLPGSQL_DTYPE_REC)
    7374                 :             :     {
    7375                 :          93 :         PLpgSQL_rec *rec = (PLpgSQL_rec *) target;
    7376                 :             :         TupleDesc   var_tupdesc;
    7377                 :             :         Datum       newvalues_local[64];
    7378                 :             :         bool        newnulls_local[64];
    7379                 :             : 
    7380                 :             :         Assert(newerh != NULL); /* caller must have built new object */
    7381                 :             : 
    7382                 :          93 :         var_tupdesc = expanded_record_get_tupdesc(newerh);
    7383                 :             : 
    7384                 :             :         /*
    7385                 :             :          * Coerce field values if needed.  This might involve dealing with
    7386                 :             :          * different sets of dropped columns and/or coercing individual column
    7387                 :             :          * types.  That's sort of a pain, but historically plpgsql has allowed
    7388                 :             :          * it, so we preserve the behavior.  However, it's worth a quick check
    7389                 :             :          * to see if the tupdescs are identical.  (Since expandedrecord.c
    7390                 :             :          * prefers to use refcounted tupdescs from the typcache, expanded
    7391                 :             :          * records with the same rowtype will have pointer-equal tupdescs.)
    7392                 :             :          */
    7393         [ +  + ]:          93 :         if (var_tupdesc != tupdesc)
    7394                 :             :         {
    7395                 :          86 :             int         vtd_natts = var_tupdesc->natts;
    7396                 :             :             Datum      *newvalues;
    7397                 :             :             bool       *newnulls;
    7398                 :             : 
    7399                 :             :             /*
    7400                 :             :              * Need workspace arrays.  If vtd_natts is small enough, use local
    7401                 :             :              * arrays to save doing a palloc.  Even if it's not small, we can
    7402                 :             :              * allocate both the Datum and isnull arrays in one palloc chunk.
    7403                 :             :              */
    7404         [ +  - ]:          86 :             if (vtd_natts <= lengthof(newvalues_local))
    7405                 :             :             {
    7406                 :          86 :                 newvalues = newvalues_local;
    7407                 :          86 :                 newnulls = newnulls_local;
    7408                 :             :             }
    7409                 :             :             else
    7410                 :             :             {
    7411                 :             :                 char       *chunk;
    7412                 :             : 
    7413                 :           0 :                 chunk = eval_mcontext_alloc(estate,
    7414                 :             :                                             vtd_natts * (sizeof(Datum) + sizeof(bool)));
    7415                 :           0 :                 newvalues = (Datum *) chunk;
    7416                 :           0 :                 newnulls = (bool *) (chunk + vtd_natts * sizeof(Datum));
    7417                 :             :             }
    7418                 :             : 
    7419                 :             :             /* Walk over destination columns */
    7420                 :          86 :             anum = 0;
    7421         [ +  + ]:         244 :             for (fnum = 0; fnum < vtd_natts; fnum++)
    7422                 :             :             {
    7423                 :         163 :                 Form_pg_attribute attr = TupleDescAttr(var_tupdesc, fnum);
    7424                 :             :                 Datum       value;
    7425                 :             :                 bool        isnull;
    7426                 :             :                 Oid         valtype;
    7427                 :             :                 int32       valtypmod;
    7428                 :             : 
    7429         [ +  + ]:         163 :                 if (attr->attisdropped)
    7430                 :             :                 {
    7431                 :             :                     /* expanded_record_set_fields should ignore this column */
    7432                 :          13 :                     continue;   /* skip dropped column in record */
    7433                 :             :                 }
    7434                 :             : 
    7435         [ +  + ]:         150 :                 while (anum < td_natts &&
    7436         [ -  + ]:         146 :                        TupleDescAttr(tupdesc, anum)->attisdropped)
    7437                 :           0 :                     anum++;     /* skip dropped column in tuple */
    7438                 :             : 
    7439         [ +  + ]:         150 :                 if (anum < td_natts)
    7440                 :             :                 {
    7441                 :         146 :                     value = values[anum];
    7442                 :         146 :                     isnull = nulls[anum];
    7443                 :         146 :                     valtype = TupleDescAttr(tupdesc, anum)->atttypid;
    7444                 :         146 :                     valtypmod = TupleDescAttr(tupdesc, anum)->atttypmod;
    7445                 :         146 :                     anum++;
    7446                 :             :                 }
    7447                 :             :                 else
    7448                 :             :                 {
    7449                 :             :                     /* no source for destination column */
    7450                 :           4 :                     value = (Datum) 0;
    7451                 :           4 :                     isnull = true;
    7452                 :           4 :                     valtype = UNKNOWNOID;
    7453                 :           4 :                     valtypmod = -1;
    7454                 :             : 
    7455                 :             :                     /* When source value is missing */
    7456         [ +  - ]:           4 :                     if (strict_multiassignment_level)
    7457   [ +  -  +  - ]:           4 :                         ereport(strict_multiassignment_level,
    7458                 :             :                                 (errcode(ERRCODE_DATATYPE_MISMATCH),
    7459                 :             :                                  errmsg("number of source and target fields in assignment does not match"),
    7460                 :             :                         /* translator: %s represents a name of an extra check */
    7461                 :             :                                  errdetail("%s check of %s is active.",
    7462                 :             :                                            "strict_multi_assignment",
    7463                 :             :                                            strict_multiassignment_level == ERROR ? "extra_errors" :
    7464                 :             :                                            "extra_warnings"),
    7465                 :             :                                  errhint("Make sure the query returns the exact list of columns.")));
    7466                 :             :                 }
    7467                 :             : 
    7468                 :             :                 /* Cast the new value to the right type, if needed. */
    7469                 :         146 :                 newvalues[fnum] = exec_cast_value(estate,
    7470                 :             :                                                   value,
    7471                 :             :                                                   &isnull,
    7472                 :             :                                                   valtype,
    7473                 :             :                                                   valtypmod,
    7474                 :             :                                                   attr->atttypid,
    7475                 :             :                                                   attr->atttypmod);
    7476                 :         145 :                 newnulls[fnum] = isnull;
    7477                 :             :             }
    7478                 :             : 
    7479                 :             :             /*
    7480                 :             :              * When strict_multiassignment extra check is active, then ensure
    7481                 :             :              * there are no unassigned source attributes.
    7482                 :             :              */
    7483   [ +  +  +  + ]:          81 :             if (strict_multiassignment_level && anum < td_natts)
    7484                 :             :             {
    7485                 :             :                 /* skip dropped columns in the source descriptor */
    7486         [ +  - ]:           4 :                 while (anum < td_natts &&
    7487         [ -  + ]:           4 :                        TupleDescAttr(tupdesc, anum)->attisdropped)
    7488                 :           0 :                     anum++;
    7489                 :             : 
    7490         [ +  - ]:           4 :                 if (anum < td_natts)
    7491   [ +  -  +  - ]:           4 :                     ereport(strict_multiassignment_level,
    7492                 :             :                             (errcode(ERRCODE_DATATYPE_MISMATCH),
    7493                 :             :                              errmsg("number of source and target fields in assignment does not match"),
    7494                 :             :                     /* translator: %s represents a name of an extra check */
    7495                 :             :                              errdetail("%s check of %s is active.",
    7496                 :             :                                        "strict_multi_assignment",
    7497                 :             :                                        strict_multiassignment_level == ERROR ? "extra_errors" :
    7498                 :             :                                        "extra_warnings"),
    7499                 :             :                              errhint("Make sure the query returns the exact list of columns.")));
    7500                 :             :             }
    7501                 :             : 
    7502                 :          77 :             values = newvalues;
    7503                 :          77 :             nulls = newnulls;
    7504                 :             :         }
    7505                 :             : 
    7506                 :             :         /* Insert the coerced field values into the new expanded record */
    7507                 :          84 :         expanded_record_set_fields(newerh, values, nulls, !estate->atomic);
    7508                 :             : 
    7509                 :             :         /* Complete the assignment */
    7510                 :          80 :         assign_record_var(estate, rec, newerh);
    7511                 :             : 
    7512                 :          80 :         return;
    7513                 :             :     }
    7514                 :             : 
    7515                 :             :     /* newerh should not have been passed in non-RECORD cases */
    7516                 :             :     Assert(newerh == NULL);
    7517                 :             : 
    7518                 :             :     /*
    7519                 :             :      * For a row, we assign the individual field values to the variables the
    7520                 :             :      * row points to.
    7521                 :             :      *
    7522                 :             :      * NOTE: both this code and the record code above silently ignore extra
    7523                 :             :      * columns in the source and assume NULL for missing columns.  This is
    7524                 :             :      * pretty dubious but it's the historical behavior.
    7525                 :             :      *
    7526                 :             :      * If we have no input data at all, we'll assign NULL to all columns of
    7527                 :             :      * the row variable.
    7528                 :             :      */
    7529         [ +  - ]:       39993 :     if (target->dtype == PLPGSQL_DTYPE_ROW)
    7530                 :             :     {
    7531                 :       39993 :         PLpgSQL_row *row = (PLpgSQL_row *) target;
    7532                 :             : 
    7533                 :       39993 :         anum = 0;
    7534         [ +  + ]:       83350 :         for (fnum = 0; fnum < row->nfields; fnum++)
    7535                 :             :         {
    7536                 :             :             PLpgSQL_var *var;
    7537                 :             :             Datum       value;
    7538                 :             :             bool        isnull;
    7539                 :             :             Oid         valtype;
    7540                 :             :             int32       valtypmod;
    7541                 :             : 
    7542                 :       43361 :             var = (PLpgSQL_var *) (estate->datums[row->varnos[fnum]]);
    7543                 :             : 
    7544         [ +  + ]:       43361 :             while (anum < td_natts &&
    7545         [ -  + ]:       43224 :                    TupleDescAttr(tupdesc, anum)->attisdropped)
    7546                 :           0 :                 anum++;         /* skip dropped column in tuple */
    7547                 :             : 
    7548         [ +  + ]:       43361 :             if (anum < td_natts)
    7549                 :             :             {
    7550                 :       43224 :                 value = values[anum];
    7551                 :       43224 :                 isnull = nulls[anum];
    7552                 :       43224 :                 valtype = TupleDescAttr(tupdesc, anum)->atttypid;
    7553                 :       43224 :                 valtypmod = TupleDescAttr(tupdesc, anum)->atttypmod;
    7554                 :       43224 :                 anum++;
    7555                 :             :             }
    7556                 :             :             else
    7557                 :             :             {
    7558                 :             :                 /* no source for destination column */
    7559                 :         137 :                 value = (Datum) 0;
    7560                 :         137 :                 isnull = true;
    7561                 :         137 :                 valtype = UNKNOWNOID;
    7562                 :         137 :                 valtypmod = -1;
    7563                 :             : 
    7564         [ +  + ]:         137 :                 if (strict_multiassignment_level)
    7565   [ +  -  +  + ]:           8 :                     ereport(strict_multiassignment_level,
    7566                 :             :                             (errcode(ERRCODE_DATATYPE_MISMATCH),
    7567                 :             :                              errmsg("number of source and target fields in assignment does not match"),
    7568                 :             :                     /* translator: %s represents a name of an extra check */
    7569                 :             :                              errdetail("%s check of %s is active.",
    7570                 :             :                                        "strict_multi_assignment",
    7571                 :             :                                        strict_multiassignment_level == ERROR ? "extra_errors" :
    7572                 :             :                                        "extra_warnings"),
    7573                 :             :                              errhint("Make sure the query returns the exact list of columns.")));
    7574                 :             :             }
    7575                 :             : 
    7576                 :       43357 :             exec_assign_value(estate, (PLpgSQL_datum *) var,
    7577                 :             :                               value, isnull, valtype, valtypmod);
    7578                 :             :         }
    7579                 :             : 
    7580                 :             :         /*
    7581                 :             :          * When strict_multiassignment extra check is active, ensure there are
    7582                 :             :          * no unassigned source attributes.
    7583                 :             :          */
    7584   [ +  +  +  + ]:       39989 :         if (strict_multiassignment_level && anum < td_natts)
    7585                 :             :         {
    7586         [ +  - ]:           8 :             while (anum < td_natts &&
    7587         [ -  + ]:           8 :                    TupleDescAttr(tupdesc, anum)->attisdropped)
    7588                 :           0 :                 anum++;         /* skip dropped column in tuple */
    7589                 :             : 
    7590         [ +  - ]:           8 :             if (anum < td_natts)
    7591   [ +  -  +  + ]:           8 :                 ereport(strict_multiassignment_level,
    7592                 :             :                         (errcode(ERRCODE_DATATYPE_MISMATCH),
    7593                 :             :                          errmsg("number of source and target fields in assignment does not match"),
    7594                 :             :                 /* translator: %s represents a name of an extra check */
    7595                 :             :                          errdetail("%s check of %s is active.",
    7596                 :             :                                    "strict_multi_assignment",
    7597                 :             :                                    strict_multiassignment_level == ERROR ? "extra_errors" :
    7598                 :             :                                    "extra_warnings"),
    7599                 :             :                          errhint("Make sure the query returns the exact list of columns.")));
    7600                 :             :         }
    7601                 :             : 
    7602                 :       39985 :         return;
    7603                 :             :     }
    7604                 :             : 
    7605         [ #  # ]:           0 :     elog(ERROR, "unsupported target type: %d", target->dtype);
    7606                 :             : }
    7607                 :             : 
    7608                 :             : /*
    7609                 :             :  * compatible_tupdescs: detect whether two tupdescs are physically compatible
    7610                 :             :  *
    7611                 :             :  * TRUE indicates that a tuple satisfying src_tupdesc can be used directly as
    7612                 :             :  * a value for a composite variable using dst_tupdesc.
    7613                 :             :  */
    7614                 :             : static bool
    7615                 :         229 : compatible_tupdescs(TupleDesc src_tupdesc, TupleDesc dst_tupdesc)
    7616                 :             : {
    7617                 :             :     int         i;
    7618                 :             : 
    7619                 :             :     /* Possibly we could allow src_tupdesc to have extra columns? */
    7620         [ +  + ]:         229 :     if (dst_tupdesc->natts != src_tupdesc->natts)
    7621                 :          15 :         return false;
    7622                 :             : 
    7623         [ +  + ]:         483 :     for (i = 0; i < dst_tupdesc->natts; i++)
    7624                 :             :     {
    7625                 :         361 :         Form_pg_attribute dattr = TupleDescAttr(dst_tupdesc, i);
    7626                 :         361 :         Form_pg_attribute sattr = TupleDescAttr(src_tupdesc, i);
    7627                 :             : 
    7628         [ +  + ]:         361 :         if (dattr->attisdropped != sattr->attisdropped)
    7629                 :           5 :             return false;
    7630         [ +  - ]:         356 :         if (!dattr->attisdropped)
    7631                 :             :         {
    7632                 :             :             /* Normal columns must match by type and typmod */
    7633         [ +  + ]:         356 :             if (dattr->atttypid != sattr->atttypid ||
    7634         [ +  + ]:         269 :                 (dattr->atttypmod >= 0 &&
    7635         [ -  + ]:           8 :                  dattr->atttypmod != sattr->atttypmod))
    7636                 :          87 :                 return false;
    7637                 :             :         }
    7638                 :             :         else
    7639                 :             :         {
    7640                 :             :             /* Dropped columns are OK as long as length/alignment match */
    7641         [ #  # ]:           0 :             if (dattr->attlen != sattr->attlen ||
    7642         [ #  # ]:           0 :                 dattr->attalign != sattr->attalign)
    7643                 :           0 :                 return false;
    7644                 :             :         }
    7645                 :             :     }
    7646                 :         122 :     return true;
    7647                 :             : }
    7648                 :             : 
    7649                 :             : /* ----------
    7650                 :             :  * make_tuple_from_row      Make a tuple from the values of a row object
    7651                 :             :  *
    7652                 :             :  * A NULL return indicates rowtype mismatch; caller must raise suitable error
    7653                 :             :  *
    7654                 :             :  * The result tuple is freshly palloc'd in caller's context.  Some junk
    7655                 :             :  * may be left behind in eval_mcontext, too.
    7656                 :             :  * ----------
    7657                 :             :  */
    7658                 :             : static HeapTuple
    7659                 :        3394 : make_tuple_from_row(PLpgSQL_execstate *estate,
    7660                 :             :                     PLpgSQL_row *row,
    7661                 :             :                     TupleDesc tupdesc)
    7662                 :             : {
    7663                 :        3394 :     int         natts = tupdesc->natts;
    7664                 :             :     HeapTuple   tuple;
    7665                 :             :     Datum      *dvalues;
    7666                 :             :     bool       *nulls;
    7667                 :             :     int         i;
    7668                 :             : 
    7669         [ -  + ]:        3394 :     if (natts != row->nfields)
    7670                 :           0 :         return NULL;
    7671                 :             : 
    7672                 :        3394 :     dvalues = (Datum *) eval_mcontext_alloc0(estate, natts * sizeof(Datum));
    7673                 :        3394 :     nulls = (bool *) eval_mcontext_alloc(estate, natts * sizeof(bool));
    7674                 :             : 
    7675         [ +  + ]:       13426 :     for (i = 0; i < natts; i++)
    7676                 :             :     {
    7677                 :             :         Oid         fieldtypeid;
    7678                 :             :         int32       fieldtypmod;
    7679                 :             : 
    7680         [ -  + ]:       10032 :         if (TupleDescAttr(tupdesc, i)->attisdropped)
    7681                 :             :         {
    7682                 :           0 :             nulls[i] = true;    /* leave the column as null */
    7683                 :           0 :             continue;
    7684                 :             :         }
    7685                 :             : 
    7686                 :       10032 :         exec_eval_datum(estate, estate->datums[row->varnos[i]],
    7687                 :             :                         &fieldtypeid, &fieldtypmod,
    7688                 :       10032 :                         &dvalues[i], &nulls[i]);
    7689         [ -  + ]:       10032 :         if (fieldtypeid != TupleDescAttr(tupdesc, i)->atttypid)
    7690                 :           0 :             return NULL;
    7691                 :             :         /* XXX should we insist on typmod match, too? */
    7692                 :             :     }
    7693                 :             : 
    7694                 :        3394 :     tuple = heap_form_tuple(tupdesc, dvalues, nulls);
    7695                 :             : 
    7696                 :        3394 :     return tuple;
    7697                 :             : }
    7698                 :             : 
    7699                 :             : /*
    7700                 :             :  * deconstruct_composite_datum      extract tuple+tupdesc from composite Datum
    7701                 :             :  *
    7702                 :             :  * The caller must supply a HeapTupleData variable, in which we set up a
    7703                 :             :  * tuple header pointing to the composite datum's body.  To make the tuple
    7704                 :             :  * value outlive that variable, caller would need to apply heap_copytuple...
    7705                 :             :  * but current callers only need a short-lived tuple value anyway.
    7706                 :             :  *
    7707                 :             :  * Returns a pointer to the TupleDesc of the datum's rowtype.
    7708                 :             :  * Caller is responsible for calling ReleaseTupleDesc when done with it.
    7709                 :             :  *
    7710                 :             :  * Note: it's caller's responsibility to be sure value is of composite type.
    7711                 :             :  * Also, best to call this in a short-lived context, as it might leak memory.
    7712                 :             :  */
    7713                 :             : static TupleDesc
    7714                 :       11660 : deconstruct_composite_datum(Datum value, HeapTupleData *tmptup)
    7715                 :             : {
    7716                 :             :     HeapTupleHeader td;
    7717                 :             :     TupleDesc   tupdesc;
    7718                 :             :     Oid         tupType;
    7719                 :             :     int32       tupTypmod;
    7720                 :             : 
    7721                 :             :     /* Get tuple body (note this could involve detoasting) */
    7722                 :       11660 :     td = DatumGetHeapTupleHeader(value);
    7723                 :             : 
    7724                 :             :     /* Build a temporary HeapTuple control structure */
    7725                 :       11660 :     tmptup->t_len = HeapTupleHeaderGetDatumLength(td);
    7726                 :       11660 :     ItemPointerSetInvalid(&(tmptup->t_self));
    7727                 :       11660 :     tmptup->t_tableOid = InvalidOid;
    7728                 :       11660 :     tmptup->t_data = td;
    7729                 :             : 
    7730                 :             :     /* Extract rowtype info and find a tupdesc */
    7731                 :       11660 :     tupType = HeapTupleHeaderGetTypeId(td);
    7732                 :       11660 :     tupTypmod = HeapTupleHeaderGetTypMod(td);
    7733                 :       11660 :     tupdesc = lookup_rowtype_tupdesc(tupType, tupTypmod);
    7734                 :             : 
    7735                 :             :     /*
    7736                 :             :      * The tuple might have a different version than the tupledesc. We could
    7737                 :             :      * check this in all callers instead, but duplicating the check doesn't
    7738                 :             :      * make a whole lot of sense.
    7739                 :             :      *
    7740                 :             :      * XXX: It'd be much better if we had a core API that wrapped all this,
    7741                 :             :      * there are many copies of this around our tree and extensions.
    7742                 :             :      */
    7743         [ +  + ]:       11660 :     if (HeapTupleHeaderIsVersionedDatum(td))
    7744                 :          64 :         heap_datum_check(td, tupdesc);
    7745                 :             : 
    7746                 :       11648 :     return tupdesc;
    7747                 :             : }
    7748                 :             : 
    7749                 :             : /*
    7750                 :             :  * Verify that the tuple held by srcerh may be copied directly into dsterh.
    7751                 :             :  *
    7752                 :             :  * It's possible that the tupledescs for the source and target have been built
    7753                 :             :  * at different times. If so, check if they're incompatible - in that case we
    7754                 :             :  * have no choice but to error out.
    7755                 :             :  *
    7756                 :             :  * XXX: It'd be nicer to do this in the ERH layer, but that'd require a few
    7757                 :             :  * more changes and would make it harder to emit a somewhat understandable
    7758                 :             :  * error message.
    7759                 :             :  */
    7760                 :             : static void
    7761                 :         184 : check_record_tupdescs_match(ExpandedRecordHeader *srcerh, ExpandedRecordHeader *dsterh)
    7762                 :             : {
    7763                 :             :     Assert(srcerh->er_typeid == dsterh->er_typeid);
    7764                 :             : 
    7765                 :             :     /* very common fastpath */
    7766         [ +  + ]:         184 :     if (srcerh->er_tupdesc_id == dsterh->er_tupdesc_id)
    7767                 :         155 :         return;
    7768                 :             : 
    7769                 :             :     /*
    7770                 :             :      * Note that we intentionally don't use equalTupleDescs() here, since that
    7771                 :             :      * flags even harmless differences between the descriptors.
    7772                 :             :      */
    7773         [ +  + ]:          29 :     if (!compatible_tupdescs(expanded_record_get_tupdesc(srcerh),
    7774                 :             :                              expanded_record_get_tupdesc(dsterh)))
    7775         [ +  - ]:          22 :         ereport(ERROR,
    7776                 :             :                 errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
    7777                 :             :                 errmsg("assigned value is incompatible with the variable's type"),
    7778                 :             :                 errdetail("A variable can retain the type definition established when it was first used."));
    7779                 :             : }
    7780                 :             : 
    7781                 :             : /*
    7782                 :             :  * exec_move_row_from_datum     Move a composite Datum into a record or row
    7783                 :             :  *
    7784                 :             :  * This is equivalent to deconstruct_composite_datum() followed by
    7785                 :             :  * exec_move_row(), but we can optimize things if the Datum is an
    7786                 :             :  * expanded-record reference.
    7787                 :             :  *
    7788                 :             :  * Note: it's caller's responsibility to be sure value is of composite type.
    7789                 :             :  */
    7790                 :             : static void
    7791                 :        1286 : exec_move_row_from_datum(PLpgSQL_execstate *estate,
    7792                 :             :                          PLpgSQL_variable *target,
    7793                 :             :                          Datum value)
    7794                 :             : {
    7795                 :             :     /* Check to see if source is an expanded record */
    7796         [ +  + ]:        1286 :     if (VARATT_IS_EXTERNAL_EXPANDED(DatumGetPointer(value)))
    7797                 :             :     {
    7798                 :         199 :         ExpandedRecordHeader *erh = (ExpandedRecordHeader *) DatumGetEOHP(value);
    7799                 :         199 :         ExpandedRecordHeader *newerh = NULL;
    7800                 :             : 
    7801                 :             :         Assert(erh->er_magic == ER_MAGIC);
    7802                 :             : 
    7803                 :             :         /* These cases apply if the target is record not row... */
    7804         [ +  - ]:         199 :         if (target->dtype == PLPGSQL_DTYPE_REC)
    7805                 :             :         {
    7806                 :         199 :             PLpgSQL_rec *rec = (PLpgSQL_rec *) target;
    7807                 :             : 
    7808                 :             :             /*
    7809                 :             :              * If it's the same record already stored in the variable, do
    7810                 :             :              * nothing.  This would happen only in silly cases like "r := r",
    7811                 :             :              * but we need some check to avoid possibly freeing the variable's
    7812                 :             :              * live value below.  Note that this applies even if what we have
    7813                 :             :              * is a R/O pointer.
    7814                 :             :              */
    7815         [ +  + ]:         199 :             if (erh == rec->erh)
    7816                 :           1 :                 return;
    7817                 :             : 
    7818                 :             :             /*
    7819                 :             :              * Make sure rec->rectypeid is up-to-date before using it.
    7820                 :             :              */
    7821                 :         198 :             revalidate_rectypeid(rec);
    7822                 :             : 
    7823                 :             :             /*
    7824                 :             :              * If we have a R/W pointer, we're allowed to just commandeer
    7825                 :             :              * ownership of the expanded record.  If it's of the right type to
    7826                 :             :              * put into the record variable, do that.  (Note we don't accept
    7827                 :             :              * an expanded record of a composite-domain type as a RECORD
    7828                 :             :              * value.  We'll treat it as the base composite type instead;
    7829                 :             :              * compare logic in make_expanded_record_for_rec.)
    7830                 :             :              */
    7831         [ +  + ]:         198 :             if (VARATT_IS_EXTERNAL_EXPANDED_RW(DatumGetPointer(value)) &&
    7832         [ +  + ]:           3 :                 (rec->rectypeid == erh->er_decltypeid ||
    7833         [ +  - ]:           1 :                  (rec->rectypeid == RECORDOID &&
    7834         [ +  - ]:           1 :                   !ExpandedRecordIsDomain(erh))))
    7835                 :             :             {
    7836                 :           3 :                 assign_record_var(estate, rec, erh);
    7837                 :           3 :                 return;
    7838                 :             :             }
    7839                 :             : 
    7840                 :             :             /*
    7841                 :             :              * If we already have an expanded record object in the target
    7842                 :             :              * variable, and the source record contains a valid tuple
    7843                 :             :              * representation with the right rowtype, then we can skip making
    7844                 :             :              * a new expanded record and just assign the tuple with
    7845                 :             :              * expanded_record_set_tuple.  (We can't do the equivalent if we
    7846                 :             :              * have to do field-by-field assignment, since that wouldn't be
    7847                 :             :              * atomic if there's an error.)  We consider that there's a
    7848                 :             :              * rowtype match only if it's the same named composite type or
    7849                 :             :              * same registered rowtype; checking for matches of anonymous
    7850                 :             :              * rowtypes would be more expensive than this is worth.
    7851                 :             :              */
    7852         [ +  + ]:         195 :             if (rec->erh &&
    7853         [ +  + ]:          26 :                 (erh->flags & ER_FLAG_FVALUE_VALID) &&
    7854         [ +  + ]:          24 :                 erh->er_typeid == rec->erh->er_typeid &&
    7855         [ -  + ]:          23 :                 (erh->er_typeid != RECORDOID ||
    7856         [ #  # ]:           0 :                  (erh->er_typmod == rec->erh->er_typmod &&
    7857         [ #  # ]:           0 :                   erh->er_typmod >= 0)))
    7858                 :             :             {
    7859                 :             :                 /*
    7860                 :             :                  * Check if the tuple descriptors are compatible. It may seem
    7861                 :             :                  * tempting to just not enter the surrounding "if" if the
    7862                 :             :                  * er_tupdesc_id doesn't match, but the fieldwise-assignment
    7863                 :             :                  * path differs behaviorally, due to not copying the ctid
    7864                 :             :                  * along. As the er_tupdesc_id can increment due to
    7865                 :             :                  * invalidation processing, that would lead to unpredictable
    7866                 :             :                  * behavior.
    7867                 :             :                  */
    7868                 :          23 :                 check_record_tupdescs_match(erh, rec->erh);
    7869                 :           5 :                 expanded_record_set_tuple(rec->erh, erh->fvalue,
    7870                 :           5 :                                           true, !estate->atomic);
    7871                 :           4 :                 return;
    7872                 :             :             }
    7873                 :             : 
    7874                 :             :             /*
    7875                 :             :              * Otherwise we're gonna need a new expanded record object.  Make
    7876                 :             :              * it here in hopes of piggybacking on the source object's
    7877                 :             :              * previous typcache lookup.
    7878                 :             :              */
    7879                 :         172 :             newerh = make_expanded_record_for_rec(estate, rec, NULL, erh);
    7880                 :             : 
    7881                 :             :             /*
    7882                 :             :              * If the expanded record contains a valid tuple representation,
    7883                 :             :              * and we don't need rowtype conversion, then just copying the
    7884                 :             :              * tuple is probably faster than field-by-field processing.  (This
    7885                 :             :              * isn't duplicative of the previous check, since here we will
    7886                 :             :              * catch the case where the record variable was previously empty.)
    7887                 :             :              */
    7888         [ +  + ]:         172 :             if ((erh->flags & ER_FLAG_FVALUE_VALID) &&
    7889         [ +  + ]:         163 :                 (rec->rectypeid == RECORDOID ||
    7890         [ +  + ]:          13 :                  rec->rectypeid == erh->er_typeid))
    7891                 :             :             {
    7892                 :             :                 /* check comment above previous call */
    7893                 :         161 :                 check_record_tupdescs_match(erh, newerh);
    7894                 :         157 :                 expanded_record_set_tuple(newerh, erh->fvalue,
    7895                 :         157 :                                           true, !estate->atomic);
    7896                 :         157 :                 assign_record_var(estate, rec, newerh);
    7897                 :         157 :                 return;
    7898                 :             :             }
    7899                 :             : 
    7900                 :             :             /*
    7901                 :             :              * Need to special-case empty source record, else code below would
    7902                 :             :              * leak newerh.
    7903                 :             :              */
    7904         [ -  + ]:          11 :             if (ExpandedRecordIsEmpty(erh))
    7905                 :             :             {
    7906                 :             :                 /* Set newerh to a row of NULLs */
    7907                 :           0 :                 deconstruct_expanded_record(newerh);
    7908                 :           0 :                 assign_record_var(estate, rec, newerh);
    7909                 :           0 :                 return;
    7910                 :             :             }
    7911                 :             :         }                       /* end of record-target-only cases */
    7912                 :             : 
    7913                 :             :         /*
    7914                 :             :          * If the source expanded record is empty, we should treat that like a
    7915                 :             :          * NULL tuple value.  (We're unlikely to see such a case, but we must
    7916                 :             :          * check this; deconstruct_expanded_record would cause a change of
    7917                 :             :          * logical state, which is not OK.)
    7918                 :             :          */
    7919         [ -  + ]:          11 :         if (ExpandedRecordIsEmpty(erh))
    7920                 :             :         {
    7921                 :           0 :             exec_move_row(estate, target, NULL,
    7922                 :             :                           expanded_record_get_tupdesc(erh));
    7923                 :           0 :             return;
    7924                 :             :         }
    7925                 :             : 
    7926                 :             :         /*
    7927                 :             :          * Otherwise, ensure that the source record is deconstructed, and
    7928                 :             :          * assign from its field values.
    7929                 :             :          */
    7930                 :          11 :         deconstruct_expanded_record(erh);
    7931                 :          11 :         exec_move_row_from_fields(estate, target, newerh,
    7932                 :             :                                   erh->dvalues, erh->dnulls,
    7933                 :             :                                   expanded_record_get_tupdesc(erh));
    7934                 :             :     }
    7935                 :             :     else
    7936                 :             :     {
    7937                 :             :         /*
    7938                 :             :          * Nope, we've got a plain composite Datum.  Deconstruct it; but we
    7939                 :             :          * don't use deconstruct_composite_datum(), because we may be able to
    7940                 :             :          * skip calling lookup_rowtype_tupdesc().
    7941                 :             :          */
    7942                 :             :         HeapTupleHeader td;
    7943                 :             :         HeapTupleData tmptup;
    7944                 :             :         Oid         tupType;
    7945                 :             :         int32       tupTypmod;
    7946                 :             :         TupleDesc   tupdesc;
    7947                 :             :         MemoryContext oldcontext;
    7948                 :             : 
    7949                 :             :         /* Ensure that any detoasted data winds up in the eval_mcontext */
    7950                 :        1087 :         oldcontext = MemoryContextSwitchTo(get_eval_mcontext(estate));
    7951                 :             :         /* Get tuple body (note this could involve detoasting) */
    7952                 :        1087 :         td = DatumGetHeapTupleHeader(value);
    7953                 :        1087 :         MemoryContextSwitchTo(oldcontext);
    7954                 :             : 
    7955                 :             :         /* Build a temporary HeapTuple control structure */
    7956                 :        1087 :         tmptup.t_len = HeapTupleHeaderGetDatumLength(td);
    7957                 :        1087 :         ItemPointerSetInvalid(&(tmptup.t_self));
    7958                 :        1087 :         tmptup.t_tableOid = InvalidOid;
    7959                 :        1087 :         tmptup.t_data = td;
    7960                 :             : 
    7961                 :             :         /* Extract rowtype info */
    7962                 :        1087 :         tupType = HeapTupleHeaderGetTypeId(td);
    7963                 :        1087 :         tupTypmod = HeapTupleHeaderGetTypMod(td);
    7964                 :             : 
    7965                 :             :         /* Now, if the target is record not row, maybe we can optimize ... */
    7966         [ +  + ]:        1087 :         if (target->dtype == PLPGSQL_DTYPE_REC)
    7967                 :             :         {
    7968                 :        1059 :             PLpgSQL_rec *rec = (PLpgSQL_rec *) target;
    7969                 :             : 
    7970                 :             :             /*
    7971                 :             :              * If we already have an expanded record object in the target
    7972                 :             :              * variable, and the source datum has a matching rowtype, then we
    7973                 :             :              * can skip making a new expanded record and just assign the tuple
    7974                 :             :              * with expanded_record_set_tuple.  We consider that there's a
    7975                 :             :              * rowtype match only if it's the same named composite type or
    7976                 :             :              * same registered rowtype.  (Checking to reject an anonymous
    7977                 :             :              * rowtype here should be redundant, but let's be safe.)
    7978                 :             :              */
    7979         [ +  + ]:        1059 :             if (rec->erh &&
    7980   [ +  +  +  + ]:         127 :                 tupType == rec->erh->er_typeid &&
    7981                 :           6 :                 (tupType != RECORDOID ||
    7982   [ -  +  -  - ]:           6 :                  (tupTypmod == rec->erh->er_typmod &&
    7983                 :             :                   tupTypmod >= 0)))
    7984                 :             :             {
    7985                 :         109 :                 expanded_record_set_tuple(rec->erh, &tmptup,
    7986                 :         109 :                                           true, !estate->atomic);
    7987                 :         960 :                 return;
    7988                 :             :             }
    7989                 :             : 
    7990                 :             :             /*
    7991                 :             :              * If the source datum has a rowtype compatible with the target
    7992                 :             :              * variable, just build a new expanded record and assign the tuple
    7993                 :             :              * into it.  Using make_expanded_record_from_typeid() here saves
    7994                 :             :              * one typcache lookup compared to the code below.
    7995                 :             :              */
    7996   [ +  +  +  + ]:         950 :             if (rec->rectypeid == RECORDOID || rec->rectypeid == tupType)
    7997                 :             :             {
    7998                 :             :                 ExpandedRecordHeader *newerh;
    7999                 :         870 :                 MemoryContext mcontext = get_eval_mcontext(estate);
    8000                 :             : 
    8001                 :         870 :                 newerh = make_expanded_record_from_typeid(tupType, tupTypmod,
    8002                 :             :                                                           mcontext);
    8003                 :         870 :                 expanded_record_set_tuple(newerh, &tmptup,
    8004                 :         870 :                                           true, !estate->atomic);
    8005                 :         858 :                 assign_record_var(estate, rec, newerh);
    8006                 :         858 :                 return;
    8007                 :             :             }
    8008                 :             : 
    8009                 :             :             /*
    8010                 :             :              * Otherwise, we're going to need conversion, so fall through to
    8011                 :             :              * do it the hard way.
    8012                 :             :              */
    8013                 :             :         }
    8014                 :             : 
    8015                 :             :         /*
    8016                 :             :          * ROW target, or unoptimizable RECORD target, so we have to expend a
    8017                 :             :          * lookup to obtain the source datum's tupdesc.
    8018                 :             :          */
    8019                 :         108 :         tupdesc = lookup_rowtype_tupdesc(tupType, tupTypmod);
    8020                 :             : 
    8021                 :             :         /* Do the move */
    8022                 :         108 :         exec_move_row(estate, target, &tmptup, tupdesc);
    8023                 :             : 
    8024                 :             :         /* Release tupdesc usage count */
    8025         [ +  - ]:         101 :         ReleaseTupleDesc(tupdesc);
    8026                 :             :     }
    8027                 :             : }
    8028                 :             : 
    8029                 :             : /*
    8030                 :             :  * If we have not created an expanded record to hold the record variable's
    8031                 :             :  * value, do so.  The expanded record will be "empty", so this does not
    8032                 :             :  * change the logical state of the record variable: it's still NULL.
    8033                 :             :  * However, now we'll have a tupdesc with which we can e.g. look up fields.
    8034                 :             :  */
    8035                 :             : static void
    8036                 :          72 : instantiate_empty_record_variable(PLpgSQL_execstate *estate, PLpgSQL_rec *rec)
    8037                 :             : {
    8038                 :             :     Assert(rec->erh == NULL);    /* else caller error */
    8039                 :             : 
    8040                 :             :     /* If declared type is RECORD, we can't instantiate */
    8041         [ +  + ]:          72 :     if (rec->rectypeid == RECORDOID)
    8042         [ +  - ]:           2 :         ereport(ERROR,
    8043                 :             :                 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
    8044                 :             :                  errmsg("record \"%s\" is not assigned yet", rec->refname),
    8045                 :             :                  errdetail("The tuple structure of a not-yet-assigned record is indeterminate.")));
    8046                 :             : 
    8047                 :             :     /* Make sure rec->rectypeid is up-to-date before using it */
    8048                 :          70 :     revalidate_rectypeid(rec);
    8049                 :             : 
    8050                 :             :     /* OK, do it */
    8051                 :          69 :     rec->erh = make_expanded_record_from_typeid(rec->rectypeid, -1,
    8052                 :             :                                                 estate->datum_context);
    8053                 :          69 : }
    8054                 :             : 
    8055                 :             : /* ----------
    8056                 :             :  * convert_value_to_string          Convert a non-null Datum to C string
    8057                 :             :  *
    8058                 :             :  * Note: the result is in the estate's eval_mcontext, and will be cleared
    8059                 :             :  * by the next exec_eval_cleanup() call.  The invoked output function might
    8060                 :             :  * leave additional cruft there as well, so just pfree'ing the result string
    8061                 :             :  * would not be enough to avoid memory leaks if we did not do it like this.
    8062                 :             :  * In most usages the Datum being passed in is also in that context (if
    8063                 :             :  * pass-by-reference) and so an exec_eval_cleanup() call is needed anyway.
    8064                 :             :  *
    8065                 :             :  * Note: not caching the conversion function lookup is bad for performance.
    8066                 :             :  * However, this function isn't currently used in any places where an extra
    8067                 :             :  * catalog lookup or two seems like a big deal.
    8068                 :             :  * ----------
    8069                 :             :  */
    8070                 :             : static char *
    8071                 :       49694 : convert_value_to_string(PLpgSQL_execstate *estate, Datum value, Oid valtype)
    8072                 :             : {
    8073                 :             :     char       *result;
    8074                 :             :     MemoryContext oldcontext;
    8075                 :             :     Oid         typoutput;
    8076                 :             :     bool        typIsVarlena;
    8077                 :             : 
    8078                 :       49694 :     oldcontext = MemoryContextSwitchTo(get_eval_mcontext(estate));
    8079                 :       49694 :     getTypeOutputInfo(valtype, &typoutput, &typIsVarlena);
    8080                 :       49694 :     result = OidOutputFunctionCall(typoutput, value);
    8081                 :       49583 :     MemoryContextSwitchTo(oldcontext);
    8082                 :             : 
    8083                 :       49583 :     return result;
    8084                 :             : }
    8085                 :             : 
    8086                 :             : /* ----------
    8087                 :             :  * exec_cast_value          Cast a value if required
    8088                 :             :  *
    8089                 :             :  * Note that *isnull is an input and also an output parameter.  While it's
    8090                 :             :  * unlikely that a cast operation would produce null from non-null or vice
    8091                 :             :  * versa, that could happen in principle.
    8092                 :             :  *
    8093                 :             :  * Note: the estate's eval_mcontext is used for temporary storage, and may
    8094                 :             :  * also contain the result Datum if we have to do a conversion to a pass-
    8095                 :             :  * by-reference data type.  Be sure to do an exec_eval_cleanup() call when
    8096                 :             :  * done with the result.
    8097                 :             :  * ----------
    8098                 :             :  */
    8099                 :             : static inline Datum
    8100                 :      259530 : exec_cast_value(PLpgSQL_execstate *estate,
    8101                 :             :                 Datum value, bool *isnull,
    8102                 :             :                 Oid valtype, int32 valtypmod,
    8103                 :             :                 Oid reqtype, int32 reqtypmod)
    8104                 :             : {
    8105                 :             :     /*
    8106                 :             :      * If the type of the given value isn't what's requested, convert it.
    8107                 :             :      */
    8108   [ +  +  -  + ]:      259530 :     if (valtype != reqtype ||
    8109         [ #  # ]:           0 :         (valtypmod != reqtypmod && reqtypmod != -1))
    8110                 :             :     {
    8111                 :             :         /* We keep the slow path out-of-line. */
    8112                 :        2231 :         value = do_cast_value(estate, value, isnull, valtype, valtypmod,
    8113                 :             :                               reqtype, reqtypmod);
    8114                 :             :     }
    8115                 :             : 
    8116                 :      259486 :     return value;
    8117                 :             : }
    8118                 :             : 
    8119                 :             : /* ----------
    8120                 :             :  * do_cast_value            Slow path for exec_cast_value.
    8121                 :             :  * ----------
    8122                 :             :  */
    8123                 :             : static Datum
    8124                 :        2231 : do_cast_value(PLpgSQL_execstate *estate,
    8125                 :             :               Datum value, bool *isnull,
    8126                 :             :               Oid valtype, int32 valtypmod,
    8127                 :             :               Oid reqtype, int32 reqtypmod)
    8128                 :             : {
    8129                 :             :     plpgsql_CastHashEntry *cast_entry;
    8130                 :             : 
    8131                 :        2231 :     cast_entry = get_cast_hashentry(estate,
    8132                 :             :                                     valtype, valtypmod,
    8133                 :             :                                     reqtype, reqtypmod);
    8134         [ +  - ]:        2231 :     if (cast_entry)
    8135                 :             :     {
    8136                 :        2231 :         ExprContext *econtext = estate->eval_econtext;
    8137                 :             :         MemoryContext oldcontext;
    8138                 :             : 
    8139                 :        2231 :         oldcontext = MemoryContextSwitchTo(get_eval_mcontext(estate));
    8140                 :             : 
    8141                 :        2231 :         econtext->caseValue_datum = value;
    8142                 :        2231 :         econtext->caseValue_isNull = *isnull;
    8143                 :             : 
    8144                 :        2231 :         cast_entry->cast_in_use = true;
    8145                 :             : 
    8146                 :        2231 :         value = ExecEvalExpr(cast_entry->cast_exprstate, econtext,
    8147                 :             :                              isnull);
    8148                 :             : 
    8149                 :        2187 :         cast_entry->cast_in_use = false;
    8150                 :             : 
    8151                 :        2187 :         MemoryContextSwitchTo(oldcontext);
    8152                 :             :     }
    8153                 :             : 
    8154                 :        2187 :     return value;
    8155                 :             : }
    8156                 :             : 
    8157                 :             : /* ----------
    8158                 :             :  * get_cast_hashentry           Look up how to perform a type cast
    8159                 :             :  *
    8160                 :             :  * Returns a plpgsql_CastHashEntry if an expression has to be evaluated,
    8161                 :             :  * or NULL if the cast is a mere no-op relabeling.  If there's work to be
    8162                 :             :  * done, the cast_exprstate field contains an expression evaluation tree
    8163                 :             :  * based on a CaseTestExpr input, and the cast_in_use field should be set
    8164                 :             :  * true while executing it.
    8165                 :             :  * ----------
    8166                 :             :  */
    8167                 :             : static plpgsql_CastHashEntry *
    8168                 :        2231 : get_cast_hashentry(PLpgSQL_execstate *estate,
    8169                 :             :                    Oid srctype, int32 srctypmod,
    8170                 :             :                    Oid dsttype, int32 dsttypmod)
    8171                 :             : {
    8172                 :             :     plpgsql_CastHashKey cast_key;
    8173                 :             :     plpgsql_CastHashEntry *cast_entry;
    8174                 :             :     plpgsql_CastExprHashEntry *expr_entry;
    8175                 :             :     bool        found;
    8176                 :             :     LocalTransactionId curlxid;
    8177                 :             :     MemoryContext oldcontext;
    8178                 :             : 
    8179                 :             :     /* Look for existing entry */
    8180                 :        2231 :     cast_key.srctype = srctype;
    8181                 :        2231 :     cast_key.dsttype = dsttype;
    8182                 :        2231 :     cast_key.srctypmod = srctypmod;
    8183                 :        2231 :     cast_key.dsttypmod = dsttypmod;
    8184                 :        2231 :     cast_entry = (plpgsql_CastHashEntry *) hash_search(estate->cast_hash,
    8185                 :             :                                                        &cast_key,
    8186                 :             :                                                        HASH_ENTER, &found);
    8187         [ +  + ]:        2231 :     if (!found)                 /* initialize if new entry */
    8188                 :             :     {
    8189                 :             :         /* We need a second lookup to see if a cast_expr_hash entry exists */
    8190                 :         310 :         expr_entry = (plpgsql_CastExprHashEntry *) hash_search(cast_expr_hash,
    8191                 :             :                                                                &cast_key,
    8192                 :             :                                                                HASH_ENTER,
    8193                 :             :                                                                &found);
    8194         [ +  + ]:         310 :         if (!found)             /* initialize if new expr entry */
    8195                 :         241 :             expr_entry->cast_cexpr = NULL;
    8196                 :             : 
    8197                 :         310 :         cast_entry->cast_centry = expr_entry;
    8198                 :         310 :         cast_entry->cast_exprstate = NULL;
    8199                 :         310 :         cast_entry->cast_in_use = false;
    8200                 :         310 :         cast_entry->cast_lxid = InvalidLocalTransactionId;
    8201                 :             :     }
    8202                 :             :     else
    8203                 :             :     {
    8204                 :             :         /* Use always-valid link to avoid a second hash lookup */
    8205                 :        1921 :         expr_entry = cast_entry->cast_centry;
    8206                 :             :     }
    8207                 :             : 
    8208         [ +  + ]:        2231 :     if (expr_entry->cast_cexpr == NULL ||
    8209         [ +  + ]:        1990 :         !expr_entry->cast_cexpr->is_valid)
    8210                 :             :     {
    8211                 :             :         /*
    8212                 :             :          * We've not looked up this coercion before, or we have but the cached
    8213                 :             :          * expression has been invalidated.
    8214                 :             :          */
    8215                 :             :         Node       *cast_expr;
    8216                 :             :         CachedExpression *cast_cexpr;
    8217                 :             :         CaseTestExpr *placeholder;
    8218                 :             : 
    8219                 :             :         /*
    8220                 :             :          * Drop old cached expression if there is one.
    8221                 :             :          */
    8222         [ +  + ]:         302 :         if (expr_entry->cast_cexpr)
    8223                 :             :         {
    8224                 :          61 :             FreeCachedExpression(expr_entry->cast_cexpr);
    8225                 :          61 :             expr_entry->cast_cexpr = NULL;
    8226                 :             :         }
    8227                 :             : 
    8228                 :             :         /*
    8229                 :             :          * Since we could easily fail (no such coercion), construct a
    8230                 :             :          * temporary coercion expression tree in the short-lived
    8231                 :             :          * eval_mcontext, then if successful save it as a CachedExpression.
    8232                 :             :          */
    8233                 :         302 :         oldcontext = MemoryContextSwitchTo(get_eval_mcontext(estate));
    8234                 :             : 
    8235                 :             :         /*
    8236                 :             :          * We use a CaseTestExpr as the base of the coercion tree, since it's
    8237                 :             :          * very cheap to insert the source value for that.
    8238                 :             :          */
    8239                 :         302 :         placeholder = makeNode(CaseTestExpr);
    8240                 :         302 :         placeholder->typeId = srctype;
    8241                 :         302 :         placeholder->typeMod = srctypmod;
    8242                 :         302 :         placeholder->collation = get_typcollation(srctype);
    8243                 :             : 
    8244                 :             :         /*
    8245                 :             :          * Apply coercion.  We use the special coercion context
    8246                 :             :          * COERCION_PLPGSQL to match plpgsql's historical behavior, namely
    8247                 :             :          * that any cast not available at ASSIGNMENT level will be implemented
    8248                 :             :          * as an I/O coercion.  (It's somewhat dubious that we prefer I/O
    8249                 :             :          * coercion over cast pathways that exist at EXPLICIT level.  Changing
    8250                 :             :          * that would cause assorted minor behavioral differences though, and
    8251                 :             :          * a user who wants the explicit-cast behavior can always write an
    8252                 :             :          * explicit cast.)
    8253                 :             :          *
    8254                 :             :          * If source type is UNKNOWN, coerce_to_target_type will fail (it only
    8255                 :             :          * expects to see that for Const input nodes), so don't call it; we'll
    8256                 :             :          * apply CoerceViaIO instead.  Likewise, it doesn't currently work for
    8257                 :             :          * coercing RECORD to some other type, so skip for that too.
    8258                 :             :          */
    8259   [ +  +  +  + ]:         302 :         if (srctype == UNKNOWNOID || srctype == RECORDOID)
    8260                 :          93 :             cast_expr = NULL;
    8261                 :             :         else
    8262                 :         209 :             cast_expr = coerce_to_target_type(NULL,
    8263                 :             :                                               (Node *) placeholder, srctype,
    8264                 :             :                                               dsttype, dsttypmod,
    8265                 :             :                                               COERCION_PLPGSQL,
    8266                 :             :                                               COERCE_IMPLICIT_CAST,
    8267                 :             :                                               -1);
    8268                 :             : 
    8269                 :             :         /*
    8270                 :             :          * If there's no cast path according to the parser, fall back to using
    8271                 :             :          * an I/O coercion; this is semantically dubious but matches plpgsql's
    8272                 :             :          * historical behavior.  We would need something of the sort for
    8273                 :             :          * UNKNOWN literals in any case.  The only case we reject is casting
    8274                 :             :          * to/from INTERNAL.  (Other than that case, this is probably now only
    8275                 :             :          * reachable in the case where srctype is UNKNOWN/RECORD.)
    8276                 :             :          */
    8277         [ +  + ]:         302 :         if (cast_expr == NULL)
    8278                 :             :         {
    8279                 :          93 :             CoerceViaIO *iocoerce = makeNode(CoerceViaIO);
    8280                 :             : 
    8281   [ +  -  -  + ]:          93 :             if (srctype == INTERNALOID || dsttype == INTERNALOID)
    8282         [ #  # ]:           0 :                 ereport(ERROR,
    8283                 :             :                         (errcode(ERRCODE_CANNOT_COERCE),
    8284                 :             :                          errmsg("cannot cast type %s to %s",
    8285                 :             :                                 format_type_be(srctype),
    8286                 :             :                                 format_type_be(dsttype))));
    8287                 :             : 
    8288                 :          93 :             iocoerce->arg = (Expr *) placeholder;
    8289                 :          93 :             iocoerce->resulttype = dsttype;
    8290                 :          93 :             iocoerce->resultcollid = InvalidOid;
    8291                 :          93 :             iocoerce->coerceformat = COERCE_IMPLICIT_CAST;
    8292                 :          93 :             iocoerce->location = -1;
    8293                 :          93 :             cast_expr = (Node *) iocoerce;
    8294         [ -  + ]:          93 :             if (dsttypmod != -1)
    8295                 :           0 :                 cast_expr = coerce_to_target_type(NULL,
    8296                 :             :                                                   cast_expr, dsttype,
    8297                 :             :                                                   dsttype, dsttypmod,
    8298                 :             :                                                   COERCION_ASSIGNMENT,
    8299                 :             :                                                   COERCE_IMPLICIT_CAST,
    8300                 :             :                                                   -1);
    8301                 :             :         }
    8302                 :             : 
    8303                 :             :         /* Note: we don't bother labeling the expression tree with collation */
    8304                 :             : 
    8305                 :             :         /* Plan the expression and build a CachedExpression */
    8306                 :         302 :         cast_cexpr = GetCachedExpression(cast_expr);
    8307                 :         302 :         cast_expr = cast_cexpr->expr;
    8308                 :             : 
    8309                 :             :         /* Detect whether we have a no-op (RelabelType) coercion */
    8310         [ +  + ]:         302 :         if (IsA(cast_expr, RelabelType) &&
    8311         [ -  + ]:          20 :             ((RelabelType *) cast_expr)->arg == (Expr *) placeholder)
    8312                 :           0 :             cast_expr = NULL;
    8313                 :             : 
    8314                 :             :         /* Now we can fill in the expression hashtable entry. */
    8315                 :         302 :         expr_entry->cast_cexpr = cast_cexpr;
    8316                 :         302 :         expr_entry->cast_expr = (Expr *) cast_expr;
    8317                 :             : 
    8318                 :             :         /* Be sure to reset the exprstate hashtable entry, too. */
    8319                 :         302 :         cast_entry->cast_exprstate = NULL;
    8320                 :         302 :         cast_entry->cast_in_use = false;
    8321                 :         302 :         cast_entry->cast_lxid = InvalidLocalTransactionId;
    8322                 :             : 
    8323                 :         302 :         MemoryContextSwitchTo(oldcontext);
    8324                 :             :     }
    8325                 :             : 
    8326                 :             :     /* Done if we have determined that this is a no-op cast. */
    8327         [ -  + ]:        2231 :     if (expr_entry->cast_expr == NULL)
    8328                 :           0 :         return NULL;
    8329                 :             : 
    8330                 :             :     /*
    8331                 :             :      * Prepare the expression for execution, if it's not been done already in
    8332                 :             :      * the current transaction; also, if it's marked busy in the current
    8333                 :             :      * transaction, abandon that expression tree and build a new one, so as to
    8334                 :             :      * avoid potential problems with recursive cast expressions and failed
    8335                 :             :      * executions.  (We will leak some memory intra-transaction if that
    8336                 :             :      * happens a lot, but we don't expect it to.)  It's okay to update the
    8337                 :             :      * hash table with the new tree because all plpgsql functions within a
    8338                 :             :      * given transaction share the same simple_eval_estate.  (Well, regular
    8339                 :             :      * functions do; DO blocks have private simple_eval_estates, and private
    8340                 :             :      * cast hash tables to go with them.)
    8341                 :             :      */
    8342                 :        2231 :     curlxid = MyProc->vxid.lxid;
    8343   [ +  +  +  + ]:        2231 :     if (cast_entry->cast_lxid != curlxid || cast_entry->cast_in_use)
    8344                 :             :     {
    8345                 :         569 :         oldcontext = MemoryContextSwitchTo(estate->simple_eval_estate->es_query_cxt);
    8346                 :         569 :         cast_entry->cast_exprstate = ExecInitExpr(expr_entry->cast_expr, NULL);
    8347                 :         569 :         cast_entry->cast_in_use = false;
    8348                 :         569 :         cast_entry->cast_lxid = curlxid;
    8349                 :         569 :         MemoryContextSwitchTo(oldcontext);
    8350                 :             :     }
    8351                 :             : 
    8352                 :        2231 :     return cast_entry;
    8353                 :             : }
    8354                 :             : 
    8355                 :             : 
    8356                 :             : /* ----------
    8357                 :             :  * exec_simple_check_plan -     Check if a plan is simple enough to
    8358                 :             :  *                              be evaluated by ExecEvalExpr() instead
    8359                 :             :  *                              of SPI.
    8360                 :             :  *
    8361                 :             :  * Note: the refcount manipulations in this function assume that expr->plan
    8362                 :             :  * is a "saved" SPI plan.  That's a bit annoying from the caller's standpoint,
    8363                 :             :  * but it's otherwise difficult to avoid leaking the plan on failure.
    8364                 :             :  * ----------
    8365                 :             :  */
    8366                 :             : static void
    8367                 :       18662 : exec_simple_check_plan(PLpgSQL_execstate *estate, PLpgSQL_expr *expr)
    8368                 :             : {
    8369                 :             :     List       *plansources;
    8370                 :             :     CachedPlanSource *plansource;
    8371                 :             :     CachedPlan *cplan;
    8372                 :             :     MemoryContext oldcontext;
    8373                 :             : 
    8374                 :             :     /*
    8375                 :             :      * Initialize to "not simple", and reset R/W optimizability.
    8376                 :             :      */
    8377                 :       18662 :     expr->expr_simple_expr = NULL;
    8378                 :       18662 :     expr->expr_rwopt = PLPGSQL_RWOPT_UNKNOWN;
    8379                 :       18662 :     expr->expr_rw_param = NULL;
    8380                 :             : 
    8381                 :             :     /*
    8382                 :             :      * Check the analyzed-and-rewritten form of the query to see if we will be
    8383                 :             :      * able to treat it as a simple expression.  Since this function is only
    8384                 :             :      * called immediately after creating the CachedPlanSource, we need not
    8385                 :             :      * worry about the query being stale.
    8386                 :             :      */
    8387         [ +  + ]:       18662 :     if (!exec_is_simple_query(expr))
    8388                 :        2972 :         return;
    8389                 :             : 
    8390                 :             :     /* exec_is_simple_query verified that there's just one CachedPlanSource */
    8391                 :       15690 :     plansources = SPI_plan_get_plan_sources(expr->plan);
    8392                 :       15690 :     plansource = (CachedPlanSource *) linitial(plansources);
    8393                 :             : 
    8394                 :             :     /*
    8395                 :             :      * Get the generic plan for the query.  If replanning is needed, do that
    8396                 :             :      * work in the eval_mcontext.  (Note that replanning could throw an error,
    8397                 :             :      * in which case the expr is left marked "not simple", which is fine.)
    8398                 :             :      */
    8399                 :       15690 :     oldcontext = MemoryContextSwitchTo(get_eval_mcontext(estate));
    8400                 :       15690 :     cplan = SPI_plan_get_cached_plan(expr->plan);
    8401                 :       15661 :     MemoryContextSwitchTo(oldcontext);
    8402                 :             : 
    8403                 :             :     /* Can't fail, because we checked for a single CachedPlanSource above */
    8404                 :             :     Assert(cplan != NULL);
    8405                 :             : 
    8406                 :             :     /*
    8407                 :             :      * Verify that plancache.c thinks the plan is simple enough to use
    8408                 :             :      * CachedPlanIsSimplyValid.  Given the restrictions above, it's unlikely
    8409                 :             :      * that this could fail, but if it does, just treat plan as not simple. On
    8410                 :             :      * success, save a refcount on the plan in the simple-expression resowner.
    8411                 :             :      */
    8412         [ +  - ]:       15661 :     if (CachedPlanAllowsSimpleValidityCheck(plansource, cplan,
    8413                 :             :                                             estate->simple_eval_resowner))
    8414                 :             :     {
    8415                 :             :         /* Remember that we have the refcount */
    8416                 :       15661 :         expr->expr_simple_plansource = plansource;
    8417                 :       15661 :         expr->expr_simple_plan = cplan;
    8418                 :       15661 :         expr->expr_simple_plan_lxid = MyProc->vxid.lxid;
    8419                 :             : 
    8420                 :             :         /* Share the remaining work with the replan code path */
    8421                 :       15661 :         exec_save_simple_expr(expr, cplan);
    8422                 :             :     }
    8423                 :             : 
    8424                 :             :     /*
    8425                 :             :      * Release the plan refcount obtained by SPI_plan_get_cached_plan.  (This
    8426                 :             :      * refcount is held by the wrong resowner, so we can't just repurpose it.)
    8427                 :             :      */
    8428                 :       15661 :     ReleaseCachedPlan(cplan, CurrentResourceOwner);
    8429                 :             : }
    8430                 :             : 
    8431                 :             : /*
    8432                 :             :  * exec_is_simple_query - precheck a query tree to see if it might be simple
    8433                 :             :  *
    8434                 :             :  * Check the analyzed-and-rewritten form of a query to see if we will be
    8435                 :             :  * able to treat it as a simple expression.  It is caller's responsibility
    8436                 :             :  * that the CachedPlanSource be up-to-date.
    8437                 :             :  */
    8438                 :             : static bool
    8439                 :       22371 : exec_is_simple_query(PLpgSQL_expr *expr)
    8440                 :             : {
    8441                 :             :     List       *plansources;
    8442                 :             :     CachedPlanSource *plansource;
    8443                 :             :     Query      *query;
    8444                 :             : 
    8445                 :             :     /*
    8446                 :             :      * We can only test queries that resulted in exactly one CachedPlanSource.
    8447                 :             :      */
    8448                 :       22371 :     plansources = SPI_plan_get_plan_sources(expr->plan);
    8449         [ -  + ]:       22371 :     if (list_length(plansources) != 1)
    8450                 :           0 :         return false;
    8451                 :       22371 :     plansource = (CachedPlanSource *) linitial(plansources);
    8452                 :             : 
    8453                 :             :     /*
    8454                 :             :      * 1. There must be one single querytree.
    8455                 :             :      */
    8456         [ -  + ]:       22371 :     if (list_length(plansource->query_list) != 1)
    8457                 :           0 :         return false;
    8458                 :       22371 :     query = (Query *) linitial(plansource->query_list);
    8459                 :             : 
    8460                 :             :     /*
    8461                 :             :      * 2. It must be a plain SELECT query without any input tables.
    8462                 :             :      */
    8463         [ -  + ]:       22371 :     if (!IsA(query, Query))
    8464                 :           0 :         return false;
    8465         [ +  + ]:       22371 :     if (query->commandType != CMD_SELECT)
    8466                 :        1632 :         return false;
    8467         [ +  + ]:       20739 :     if (query->rtable != NIL)
    8468                 :         855 :         return false;
    8469                 :             : 
    8470                 :             :     /*
    8471                 :             :      * 3. Can't have any subplans, aggregates, qual clauses either.  (These
    8472                 :             :      * tests should generally match what inline_function() checks before
    8473                 :             :      * inlining a SQL function; otherwise, inlining could change our
    8474                 :             :      * conclusion about whether an expression is simple, which we don't want.)
    8475                 :             :      */
    8476         [ +  - ]:       19884 :     if (query->hasAggs ||
    8477         [ +  - ]:       19884 :         query->hasWindowFuncs ||
    8478         [ +  + ]:       19884 :         query->hasTargetSRFs ||
    8479         [ +  + ]:       19853 :         query->hasSubLinks ||
    8480         [ +  - ]:       19475 :         query->cteList ||
    8481         [ +  - ]:       19475 :         query->jointree->fromlist ||
    8482         [ +  - ]:       19475 :         query->jointree->quals ||
    8483         [ +  - ]:       19475 :         query->groupClause ||
    8484         [ +  - ]:       19475 :         query->groupingSets ||
    8485         [ +  - ]:       19475 :         query->havingQual ||
    8486         [ +  - ]:       19475 :         query->windowClause ||
    8487         [ +  - ]:       19475 :         query->distinctClause ||
    8488         [ +  - ]:       19475 :         query->sortClause ||
    8489         [ +  - ]:       19475 :         query->limitOffset ||
    8490         [ +  - ]:       19475 :         query->limitCount ||
    8491         [ -  + ]:       19475 :         query->setOperations)
    8492                 :         409 :         return false;
    8493                 :             : 
    8494                 :             :     /*
    8495                 :             :      * 4. The query must have a single attribute as result.
    8496                 :             :      */
    8497         [ +  + ]:       19475 :     if (list_length(query->targetList) != 1)
    8498                 :          77 :         return false;
    8499                 :             : 
    8500                 :             :     /*
    8501                 :             :      * OK, we can treat it as a simple plan.
    8502                 :             :      */
    8503                 :       19398 :     return true;
    8504                 :             : }
    8505                 :             : 
    8506                 :             : /*
    8507                 :             :  * exec_save_simple_expr --- extract simple expression from CachedPlan
    8508                 :             :  */
    8509                 :             : static void
    8510                 :       19369 : exec_save_simple_expr(PLpgSQL_expr *expr, CachedPlan *cplan)
    8511                 :             : {
    8512                 :             :     PlannedStmt *stmt;
    8513                 :             :     Plan       *plan;
    8514                 :             :     Expr       *tle_expr;
    8515                 :             : 
    8516                 :             :     /*
    8517                 :             :      * Given the checks that exec_simple_check_plan did, none of the Asserts
    8518                 :             :      * here should ever fail.
    8519                 :             :      */
    8520                 :             : 
    8521                 :             :     /* Extract the single PlannedStmt */
    8522                 :             :     Assert(list_length(cplan->stmt_list) == 1);
    8523                 :       19369 :     stmt = linitial_node(PlannedStmt, cplan->stmt_list);
    8524                 :             :     Assert(stmt->commandType == CMD_SELECT);
    8525                 :             : 
    8526                 :             :     /*
    8527                 :             :      * Ordinarily, the plan node should be a simple Result.  However, if
    8528                 :             :      * debug_parallel_query is on, the planner might've stuck a Gather node
    8529                 :             :      * atop that; and/or if this plan is for a scrollable cursor, the planner
    8530                 :             :      * might've stuck a Material node atop it.  The simplest way to deal with
    8531                 :             :      * this is to look through the Gather and/or Material nodes.  The upper
    8532                 :             :      * node's tlist would normally contain a Var referencing the child node's
    8533                 :             :      * output ... but setrefs.c might also have copied a Const as-is.
    8534                 :             :      */
    8535                 :       19369 :     plan = stmt->planTree;
    8536                 :             :     for (;;)
    8537                 :             :     {
    8538                 :             :         /* Extract the single tlist expression */
    8539                 :           0 :         Assert(list_length(plan->targetlist) == 1);
    8540                 :       19369 :         tle_expr = linitial_node(TargetEntry, plan->targetlist)->expr;
    8541                 :             : 
    8542         [ +  + ]:       19369 :         if (IsA(plan, Result))
    8543                 :             :         {
    8544                 :             :             Assert(plan->lefttree == NULL &&
    8545                 :             :                    plan->righttree == NULL &&
    8546                 :             :                    plan->initPlan == NULL &&
    8547                 :             :                    plan->qual == NULL &&
    8548                 :             :                    ((Result *) plan)->resconstantqual == NULL);
    8549                 :       19368 :             break;
    8550                 :             :         }
    8551   [ +  -  +  - ]:           1 :         else if (IsA(plan, Gather) || IsA(plan, Material))
    8552                 :             :         {
    8553                 :             :             Assert(plan->lefttree != NULL &&
    8554                 :             :                    plan->righttree == NULL &&
    8555                 :             :                    plan->initPlan == NULL &&
    8556                 :             :                    plan->qual == NULL);
    8557                 :             :             /* If setrefs.c copied up a Const, no need to look further */
    8558         [ +  - ]:           1 :             if (IsA(tle_expr, Const))
    8559                 :           1 :                 break;
    8560                 :             :             /* Otherwise, it better be an outer Var */
    8561                 :             :             Assert(IsA(tle_expr, Var));
    8562                 :             :             Assert(((Var *) tle_expr)->varno == OUTER_VAR);
    8563                 :             :             /* Descend to the child node */
    8564                 :           0 :             plan = plan->lefttree;
    8565                 :             :         }
    8566                 :             :         else
    8567         [ #  # ]:           0 :             elog(ERROR, "unexpected plan node type: %d",
    8568                 :             :                  (int) nodeTag(plan));
    8569                 :             :     }
    8570                 :             : 
    8571                 :             :     /*
    8572                 :             :      * Save the simple expression, and initialize state to "not valid in
    8573                 :             :      * current transaction".
    8574                 :             :      */
    8575                 :       19369 :     expr->expr_simple_expr = tle_expr;
    8576                 :       19369 :     expr->expr_simple_state = NULL;
    8577                 :       19369 :     expr->expr_simple_in_use = false;
    8578                 :       19369 :     expr->expr_simple_lxid = InvalidLocalTransactionId;
    8579                 :             :     /* Also stash away the expression result type */
    8580                 :       19369 :     expr->expr_simple_type = exprType((Node *) tle_expr);
    8581                 :       19369 :     expr->expr_simple_typmod = exprTypmod((Node *) tle_expr);
    8582                 :             :     /* We also want to remember if it is immutable or not */
    8583                 :       19369 :     expr->expr_simple_mutable = contain_mutable_functions((Node *) tle_expr);
    8584                 :       19369 : }
    8585                 :             : 
    8586                 :             : /*
    8587                 :             :  * exec_check_rw_parameter --- can we pass expanded object as read/write param?
    8588                 :             :  *
    8589                 :             :  * There are two separate cases in which we can optimize an update to a
    8590                 :             :  * variable that has a read/write expanded value by letting the called
    8591                 :             :  * expression operate directly on the expanded value.  In both cases we
    8592                 :             :  * are considering assignments like "var := array_append(var, foo)" where
    8593                 :             :  * the assignment target is also an input to the RHS expression.
    8594                 :             :  *
    8595                 :             :  * Case 1 (RWOPT_TRANSFER rule): if the variable is "local" in the sense that
    8596                 :             :  * its declaration is not outside any BEGIN...EXCEPTION block surrounding the
    8597                 :             :  * assignment, then we do not need to worry about preserving its value if the
    8598                 :             :  * RHS expression throws an error.  If in addition the variable is referenced
    8599                 :             :  * exactly once in the RHS expression, then we can optimize by converting the
    8600                 :             :  * read/write expanded value into a transient value within the expression
    8601                 :             :  * evaluation context, and then setting the variable's recorded value to NULL
    8602                 :             :  * to prevent double-free attempts.  This works regardless of any other
    8603                 :             :  * details of the RHS expression.  If the expression eventually returns that
    8604                 :             :  * same expanded object (possibly modified) then the variable will re-acquire
    8605                 :             :  * ownership; while if it returns something else or throws an error, the
    8606                 :             :  * expanded object will be discarded as part of cleanup of the evaluation
    8607                 :             :  * context.
    8608                 :             :  *
    8609                 :             :  * Case 2 (RWOPT_INPLACE rule): if we have a non-local assignment or if
    8610                 :             :  * it looks like "var := array_append(var, var[1])" with multiple references
    8611                 :             :  * to the target variable, then we can't use case 1.  Nonetheless, if the
    8612                 :             :  * top-level function is trusted not to corrupt its argument in case of an
    8613                 :             :  * error, then when the var has an expanded object as value, it is safe to
    8614                 :             :  * pass the value as a read/write pointer to the top-level function and let
    8615                 :             :  * the function modify the value in-place.  (Any other references have to be
    8616                 :             :  * passed as read-only pointers as usual.)  Only the top-level function has to
    8617                 :             :  * be trusted, since if anything further down fails, the object hasn't been
    8618                 :             :  * modified yet.
    8619                 :             :  *
    8620                 :             :  * This function checks to see if the assignment is optimizable according
    8621                 :             :  * to either rule, and updates expr->expr_rwopt accordingly.  In addition,
    8622                 :             :  * it sets expr->expr_rw_param to the address of the Param within the
    8623                 :             :  * expression that can be passed as read/write (there can be only one);
    8624                 :             :  * or to NULL when there is no safe Param.
    8625                 :             :  *
    8626                 :             :  * Note that this mechanism intentionally allows just one Param to emit a
    8627                 :             :  * read/write pointer; in case 2, the expression could contain other Params
    8628                 :             :  * referencing the target variable, but those must be treated as read-only.
    8629                 :             :  *
    8630                 :             :  * Also note that we only apply this optimization within simple expressions.
    8631                 :             :  * There's no point in it for non-simple expressions, because the
    8632                 :             :  * exec_run_select code path will flatten any expanded result anyway.
    8633                 :             :  */
    8634                 :             : static void
    8635                 :          65 : exec_check_rw_parameter(PLpgSQL_expr *expr, int paramid)
    8636                 :             : {
    8637                 :          65 :     Expr       *sexpr = expr->expr_simple_expr;
    8638                 :             :     Oid         funcid;
    8639                 :             :     List       *fargs;
    8640                 :             :     Oid         prosupport;
    8641                 :             : 
    8642                 :             :     /* Assume unsafe */
    8643                 :          65 :     expr->expr_rwopt = PLPGSQL_RWOPT_NOPE;
    8644                 :          65 :     expr->expr_rw_param = NULL;
    8645                 :             : 
    8646                 :             :     /* Shouldn't be here for non-simple expression */
    8647                 :             :     Assert(sexpr != NULL);
    8648                 :             : 
    8649                 :             :     /* Param should match the expression's assignment target, too */
    8650                 :             :     Assert(paramid == expr->target_param + 1);
    8651                 :             : 
    8652                 :             :     /*
    8653                 :             :      * If the assignment is to a "local" variable (one whose value won't
    8654                 :             :      * matter anymore if expression evaluation fails), and this Param is the
    8655                 :             :      * only reference to that variable in the expression, then we can
    8656                 :             :      * unconditionally optimize using the "transfer" method.
    8657                 :             :      */
    8658         [ +  - ]:          65 :     if (expr->target_is_local)
    8659                 :             :     {
    8660                 :             :         count_param_references_context context;
    8661                 :             : 
    8662                 :             :         /* See how many references there are, and find one of them */
    8663                 :          65 :         context.paramid = paramid;
    8664                 :          65 :         context.count = 0;
    8665                 :          65 :         context.last_param = NULL;
    8666                 :          65 :         (void) count_param_references((Node *) sexpr, &context);
    8667                 :             : 
    8668                 :             :         /* If we're here, the expr must contain some reference to the var */
    8669                 :             :         Assert(context.count > 0);
    8670                 :             : 
    8671                 :             :         /* If exactly one reference, success! */
    8672         [ +  + ]:          65 :         if (context.count == 1)
    8673                 :             :         {
    8674                 :          61 :             expr->expr_rwopt = PLPGSQL_RWOPT_TRANSFER;
    8675                 :          61 :             expr->expr_rw_param = context.last_param;
    8676                 :          61 :             return;
    8677                 :             :         }
    8678                 :             :     }
    8679                 :             : 
    8680                 :             :     /*
    8681                 :             :      * Otherwise, see if we can trust the expression's top-level function to
    8682                 :             :      * apply the "inplace" method.
    8683                 :             :      *
    8684                 :             :      * Top level of expression must be a simple FuncExpr, OpExpr, or
    8685                 :             :      * SubscriptingRef, else we can't identify which function is relevant. But
    8686                 :             :      * it's okay to look through any RelabelType above that, since that can't
    8687                 :             :      * fail.
    8688                 :             :      */
    8689         [ -  + ]:           4 :     if (IsA(sexpr, RelabelType))
    8690                 :           0 :         sexpr = ((RelabelType *) sexpr)->arg;
    8691         [ -  + ]:           4 :     if (IsA(sexpr, FuncExpr))
    8692                 :             :     {
    8693                 :           0 :         FuncExpr   *fexpr = (FuncExpr *) sexpr;
    8694                 :             : 
    8695                 :           0 :         funcid = fexpr->funcid;
    8696                 :           0 :         fargs = fexpr->args;
    8697                 :             :     }
    8698         [ +  + ]:           4 :     else if (IsA(sexpr, OpExpr))
    8699                 :             :     {
    8700                 :           3 :         OpExpr     *opexpr = (OpExpr *) sexpr;
    8701                 :             : 
    8702                 :           3 :         funcid = opexpr->opfuncid;
    8703                 :           3 :         fargs = opexpr->args;
    8704                 :             :     }
    8705         [ +  - ]:           1 :     else if (IsA(sexpr, SubscriptingRef))
    8706                 :             :     {
    8707                 :           1 :         SubscriptingRef *sbsref = (SubscriptingRef *) sexpr;
    8708                 :             : 
    8709                 :           1 :         funcid = get_typsubscript(sbsref->refcontainertype, NULL);
    8710                 :             : 
    8711                 :             :         /*
    8712                 :             :          * We assume that only the refexpr and refassgnexpr (if any) are
    8713                 :             :          * relevant to the support function's decision.  If that turns out to
    8714                 :             :          * be a bad idea, we could incorporate the subscript expressions into
    8715                 :             :          * the fargs list somehow.
    8716                 :             :          */
    8717                 :           1 :         fargs = list_make2(sbsref->refexpr, sbsref->refassgnexpr);
    8718                 :             :     }
    8719                 :             :     else
    8720                 :           0 :         return;
    8721                 :             : 
    8722                 :             :     /*
    8723                 :             :      * The top-level function must be one that can handle in-place update
    8724                 :             :      * safely.  We allow functions to declare their ability to do that via a
    8725                 :             :      * support function request.
    8726                 :             :      */
    8727                 :           4 :     prosupport = get_func_support(funcid);
    8728         [ +  + ]:           4 :     if (OidIsValid(prosupport))
    8729                 :             :     {
    8730                 :             :         SupportRequestModifyInPlace req;
    8731                 :             :         Param      *param;
    8732                 :             : 
    8733                 :           3 :         req.type = T_SupportRequestModifyInPlace;
    8734                 :           3 :         req.funcid = funcid;
    8735                 :           3 :         req.args = fargs;
    8736                 :           3 :         req.paramid = paramid;
    8737                 :             : 
    8738                 :             :         param = (Param *)
    8739                 :           3 :             DatumGetPointer(OidFunctionCall1(prosupport,
    8740                 :             :                                              PointerGetDatum(&req)));
    8741                 :             : 
    8742         [ -  + ]:           3 :         if (param == NULL)
    8743                 :           0 :             return;             /* support function fails */
    8744                 :             : 
    8745                 :             :         /* Verify support function followed the API */
    8746                 :             :         Assert(IsA(param, Param));
    8747                 :             :         Assert(param->paramkind == PARAM_EXTERN);
    8748                 :             :         Assert(param->paramid == paramid);
    8749                 :             : 
    8750                 :             :         /* Found the Param we want to pass as read/write */
    8751                 :           3 :         expr->expr_rwopt = PLPGSQL_RWOPT_INPLACE;
    8752                 :           3 :         expr->expr_rw_param = param;
    8753                 :           3 :         return;
    8754                 :             :     }
    8755                 :             : }
    8756                 :             : 
    8757                 :             : /*
    8758                 :             :  * Count Params referencing the specified paramid, and return one of them
    8759                 :             :  * if there are any.
    8760                 :             :  *
    8761                 :             :  * We actually only need to distinguish 0, 1, and N references; so we can
    8762                 :             :  * abort the tree traversal as soon as we've found two.
    8763                 :             :  */
    8764                 :             : static bool
    8765                 :         307 : count_param_references(Node *node, count_param_references_context *context)
    8766                 :             : {
    8767         [ +  + ]:         307 :     if (node == NULL)
    8768                 :           1 :         return false;
    8769         [ +  + ]:         306 :     else if (IsA(node, Param))
    8770                 :             :     {
    8771                 :         110 :         Param      *param = (Param *) node;
    8772                 :             : 
    8773         [ +  - ]:         110 :         if (param->paramkind == PARAM_EXTERN &&
    8774         [ +  + ]:         110 :             param->paramid == context->paramid)
    8775                 :             :         {
    8776                 :          69 :             context->last_param = param;
    8777         [ +  + ]:          69 :             if (++(context->count) > 1)
    8778                 :           4 :                 return true;    /* abort tree traversal */
    8779                 :             :         }
    8780                 :         106 :         return false;
    8781                 :             :     }
    8782                 :             :     else
    8783                 :         196 :         return expression_tree_walker(node, count_param_references, context);
    8784                 :             : }
    8785                 :             : 
    8786                 :             : /*
    8787                 :             :  * exec_check_assignable --- is it OK to assign to the indicated datum?
    8788                 :             :  *
    8789                 :             :  * This should match pl_gram.y's check_assignable().
    8790                 :             :  */
    8791                 :             : static void
    8792                 :         185 : exec_check_assignable(PLpgSQL_execstate *estate, int dno)
    8793                 :             : {
    8794                 :             :     PLpgSQL_datum *datum;
    8795                 :             : 
    8796                 :             :     Assert(dno >= 0 && dno < estate->ndatums);
    8797                 :         185 :     datum = estate->datums[dno];
    8798   [ +  -  +  - ]:         185 :     switch (datum->dtype)
    8799                 :             :     {
    8800                 :         183 :         case PLPGSQL_DTYPE_VAR:
    8801                 :             :         case PLPGSQL_DTYPE_PROMISE:
    8802                 :             :         case PLPGSQL_DTYPE_REC:
    8803         [ +  + ]:         183 :             if (((PLpgSQL_variable *) datum)->isconst)
    8804         [ +  - ]:           5 :                 ereport(ERROR,
    8805                 :             :                         (errcode(ERRCODE_ERROR_IN_ASSIGNMENT),
    8806                 :             :                          errmsg("variable \"%s\" is declared CONSTANT",
    8807                 :             :                                 ((PLpgSQL_variable *) datum)->refname)));
    8808                 :         178 :             break;
    8809                 :           0 :         case PLPGSQL_DTYPE_ROW:
    8810                 :             :             /* always assignable; member vars were checked at compile time */
    8811                 :           0 :             break;
    8812                 :           2 :         case PLPGSQL_DTYPE_RECFIELD:
    8813                 :             :             /* assignable if parent record is */
    8814                 :           2 :             exec_check_assignable(estate,
    8815                 :             :                                   ((PLpgSQL_recfield *) datum)->recparentno);
    8816                 :           2 :             break;
    8817                 :           0 :         default:
    8818         [ #  # ]:           0 :             elog(ERROR, "unrecognized dtype: %d", datum->dtype);
    8819                 :             :             break;
    8820                 :             :     }
    8821                 :         180 : }
    8822                 :             : 
    8823                 :             : /* ----------
    8824                 :             :  * exec_set_found           Set the global found variable to true/false
    8825                 :             :  * ----------
    8826                 :             :  */
    8827                 :             : static void
    8828                 :      121972 : exec_set_found(PLpgSQL_execstate *estate, bool state)
    8829                 :             : {
    8830                 :             :     PLpgSQL_var *var;
    8831                 :             : 
    8832                 :      121972 :     var = (PLpgSQL_var *) (estate->datums[estate->found_varno]);
    8833                 :             : 
    8834                 :             :     /*
    8835                 :             :      * Use pg_assume() to avoid a spurious warning with some compilers, by
    8836                 :             :      * telling the compiler that the VARATT_IS_EXTERNAL_NON_EXPANDED() branch
    8837                 :             :      * in assign_simple_var() will never be reached when called from here, due
    8838                 :             :      * to "found" being a boolean (i.e. a byvalue type), not a varlena.
    8839                 :             :      */
    8840         [ -  + ]:      121972 :     pg_assume(var->datatype->typlen != -1);
    8841                 :             : 
    8842                 :      121972 :     assign_simple_var(estate, var, BoolGetDatum(state), false, false);
    8843                 :      121972 : }
    8844                 :             : 
    8845                 :             : /*
    8846                 :             :  * plpgsql_create_econtext --- create an eval_econtext for the current function
    8847                 :             :  *
    8848                 :             :  * We may need to create a new shared_simple_eval_estate too, if there's not
    8849                 :             :  * one already for the current transaction.  The EState will be cleaned up at
    8850                 :             :  * transaction end.  Ditto for shared_simple_eval_resowner.
    8851                 :             :  */
    8852                 :             : static void
    8853                 :       87389 : plpgsql_create_econtext(PLpgSQL_execstate *estate)
    8854                 :             : {
    8855                 :             :     SimpleEcontextStackEntry *entry;
    8856                 :             : 
    8857                 :             :     /*
    8858                 :             :      * Create an EState for evaluation of simple expressions, if there's not
    8859                 :             :      * one already in the current transaction.  The EState is made a child of
    8860                 :             :      * TopTransactionContext so it will have the right lifespan.
    8861                 :             :      *
    8862                 :             :      * Note that this path is never taken when beginning a DO block; the
    8863                 :             :      * required EState was already made by plpgsql_inline_handler.  However,
    8864                 :             :      * if the DO block executes COMMIT or ROLLBACK, then we'll come here and
    8865                 :             :      * make a shared EState to use for the rest of the DO block.  That's OK;
    8866                 :             :      * see the comments for shared_simple_eval_estate.  (Note also that a DO
    8867                 :             :      * block will continue to use its private cast hash table for the rest of
    8868                 :             :      * the block.  That's okay for now, but it might cause problems someday.)
    8869                 :             :      */
    8870         [ +  + ]:       87389 :     if (estate->simple_eval_estate == NULL)
    8871                 :             :     {
    8872                 :             :         MemoryContext oldcontext;
    8873                 :             : 
    8874         [ +  + ]:       10659 :         if (shared_simple_eval_estate == NULL)
    8875                 :             :         {
    8876                 :       10655 :             oldcontext = MemoryContextSwitchTo(TopTransactionContext);
    8877                 :       10655 :             shared_simple_eval_estate = CreateExecutorState();
    8878                 :       10655 :             MemoryContextSwitchTo(oldcontext);
    8879                 :             :         }
    8880                 :       10659 :         estate->simple_eval_estate = shared_simple_eval_estate;
    8881                 :             :     }
    8882                 :             : 
    8883                 :             :     /*
    8884                 :             :      * Likewise for the simple-expression resource owner.
    8885                 :             :      */
    8886         [ +  + ]:       87389 :     if (estate->simple_eval_resowner == NULL)
    8887                 :             :     {
    8888         [ +  + ]:       10659 :         if (shared_simple_eval_resowner == NULL)
    8889                 :       10655 :             shared_simple_eval_resowner =
    8890                 :       10655 :                 ResourceOwnerCreate(TopTransactionResourceOwner,
    8891                 :             :                                     "PL/pgSQL simple expressions");
    8892                 :       10659 :         estate->simple_eval_resowner = shared_simple_eval_resowner;
    8893                 :             :     }
    8894                 :             : 
    8895                 :             :     /*
    8896                 :             :      * Create a child econtext for the current function.
    8897                 :             :      */
    8898                 :       87389 :     estate->eval_econtext = CreateExprContext(estate->simple_eval_estate);
    8899                 :             : 
    8900                 :             :     /*
    8901                 :             :      * Make a stack entry so we can clean up the econtext at subxact end.
    8902                 :             :      * Stack entries are kept in TopTransactionContext for simplicity.
    8903                 :             :      */
    8904                 :             :     entry = (SimpleEcontextStackEntry *)
    8905                 :       87389 :         MemoryContextAlloc(TopTransactionContext,
    8906                 :             :                            sizeof(SimpleEcontextStackEntry));
    8907                 :             : 
    8908                 :       87389 :     entry->stack_econtext = estate->eval_econtext;
    8909                 :       87389 :     entry->xact_subxid = GetCurrentSubTransactionId();
    8910                 :             : 
    8911                 :       87389 :     entry->next = simple_econtext_stack;
    8912                 :       87389 :     simple_econtext_stack = entry;
    8913                 :       87389 : }
    8914                 :             : 
    8915                 :             : /*
    8916                 :             :  * plpgsql_destroy_econtext --- destroy function's econtext
    8917                 :             :  *
    8918                 :             :  * We check that it matches the top stack entry, and destroy the stack
    8919                 :             :  * entry along with the context.
    8920                 :             :  */
    8921                 :             : static void
    8922                 :       64272 : plpgsql_destroy_econtext(PLpgSQL_execstate *estate)
    8923                 :             : {
    8924                 :             :     SimpleEcontextStackEntry *next;
    8925                 :             : 
    8926                 :             :     Assert(simple_econtext_stack != NULL);
    8927                 :             :     Assert(simple_econtext_stack->stack_econtext == estate->eval_econtext);
    8928                 :             : 
    8929                 :       64272 :     next = simple_econtext_stack->next;
    8930                 :       64272 :     pfree(simple_econtext_stack);
    8931                 :       64272 :     simple_econtext_stack = next;
    8932                 :             : 
    8933                 :       64272 :     FreeExprContext(estate->eval_econtext, true);
    8934                 :       64272 :     estate->eval_econtext = NULL;
    8935                 :       64272 : }
    8936                 :             : 
    8937                 :             : /*
    8938                 :             :  * plpgsql_xact_cb --- post-transaction-commit-or-abort cleanup
    8939                 :             :  *
    8940                 :             :  * If a simple-expression EState was created in the current transaction,
    8941                 :             :  * it has to be cleaned up.  The same for the simple-expression resowner.
    8942                 :             :  */
    8943                 :             : void
    8944                 :      214141 : plpgsql_xact_cb(XactEvent event, void *arg)
    8945                 :             : {
    8946                 :             :     /*
    8947                 :             :      * If we are doing a clean transaction shutdown, free the EState and tell
    8948                 :             :      * the resowner to release whatever plancache references it has, so that
    8949                 :             :      * all remaining resources will be released correctly.  (We don't need to
    8950                 :             :      * actually delete the resowner here; deletion of the
    8951                 :             :      * TopTransactionResourceOwner will take care of that.)
    8952                 :             :      *
    8953                 :             :      * In an abort, we expect the regular abort recovery procedures to release
    8954                 :             :      * everything of interest, so just clear our pointers.
    8955                 :             :      */
    8956   [ +  +  +  + ]:      214141 :     if (event == XACT_EVENT_COMMIT ||
    8957         [ +  + ]:      112267 :         event == XACT_EVENT_PARALLEL_COMMIT ||
    8958                 :             :         event == XACT_EVENT_PREPARE)
    8959                 :             :     {
    8960                 :      101892 :         simple_econtext_stack = NULL;
    8961                 :             : 
    8962         [ +  + ]:      101892 :         if (shared_simple_eval_estate)
    8963                 :        9458 :             FreeExecutorState(shared_simple_eval_estate);
    8964                 :      101892 :         shared_simple_eval_estate = NULL;
    8965         [ +  + ]:      101892 :         if (shared_simple_eval_resowner)
    8966                 :        9458 :             ReleaseAllPlanCacheRefsInOwner(shared_simple_eval_resowner);
    8967                 :      101892 :         shared_simple_eval_resowner = NULL;
    8968                 :             :     }
    8969   [ +  +  +  + ]:      112249 :     else if (event == XACT_EVENT_ABORT ||
    8970                 :             :              event == XACT_EVENT_PARALLEL_ABORT)
    8971                 :             :     {
    8972                 :       10305 :         simple_econtext_stack = NULL;
    8973                 :       10305 :         shared_simple_eval_estate = NULL;
    8974                 :       10305 :         shared_simple_eval_resowner = NULL;
    8975                 :             :     }
    8976                 :      214141 : }
    8977                 :             : 
    8978                 :             : /*
    8979                 :             :  * plpgsql_subxact_cb --- post-subtransaction-commit-or-abort cleanup
    8980                 :             :  *
    8981                 :             :  * Make sure any simple-expression econtexts created in the current
    8982                 :             :  * subtransaction get cleaned up.  We have to do this explicitly because
    8983                 :             :  * no other code knows which econtexts belong to which level of subxact.
    8984                 :             :  */
    8985                 :             : void
    8986                 :       57802 : plpgsql_subxact_cb(SubXactEvent event, SubTransactionId mySubid,
    8987                 :             :                    SubTransactionId parentSubid, void *arg)
    8988                 :             : {
    8989   [ +  +  +  + ]:       57802 :     if (event == SUBXACT_EVENT_COMMIT_SUB || event == SUBXACT_EVENT_ABORT_SUB)
    8990                 :             :     {
    8991         [ +  + ]:       41220 :         while (simple_econtext_stack != NULL &&
    8992         [ +  + ]:       40053 :                simple_econtext_stack->xact_subxid == mySubid)
    8993                 :             :         {
    8994                 :             :             SimpleEcontextStackEntry *next;
    8995                 :             : 
    8996                 :       20281 :             FreeExprContext(simple_econtext_stack->stack_econtext,
    8997                 :             :                             (event == SUBXACT_EVENT_COMMIT_SUB));
    8998                 :       20281 :             next = simple_econtext_stack->next;
    8999                 :       20281 :             pfree(simple_econtext_stack);
    9000                 :       20281 :             simple_econtext_stack = next;
    9001                 :             :         }
    9002                 :             :     }
    9003                 :       57802 : }
    9004                 :             : 
    9005                 :             : /*
    9006                 :             :  * assign_simple_var --- assign a new value to any VAR datum.
    9007                 :             :  *
    9008                 :             :  * This should be the only mechanism for assignment to simple variables,
    9009                 :             :  * lest we do the release of the old value incorrectly (not to mention
    9010                 :             :  * the detoasting business).
    9011                 :             :  */
    9012                 :             : static void
    9013                 :      374546 : assign_simple_var(PLpgSQL_execstate *estate, PLpgSQL_var *var,
    9014                 :             :                   Datum newvalue, bool isnull, bool freeable)
    9015                 :             : {
    9016                 :             :     Assert(var->dtype == PLPGSQL_DTYPE_VAR ||
    9017                 :             :            var->dtype == PLPGSQL_DTYPE_PROMISE);
    9018                 :             : 
    9019                 :             :     /*
    9020                 :             :      * In non-atomic contexts, we do not want to store TOAST pointers in
    9021                 :             :      * variables, because such pointers might become stale after a commit.
    9022                 :             :      * Forcibly detoast in such cases.  We don't want to detoast (flatten)
    9023                 :             :      * expanded objects, however; those should be OK across a transaction
    9024                 :             :      * boundary since they're just memory-resident objects.  (Elsewhere in
    9025                 :             :      * this module, operations on expanded records likewise need to request
    9026                 :             :      * detoasting of record fields when !estate->atomic.  Expanded arrays are
    9027                 :             :      * not a problem since all array entries are always detoasted.)
    9028                 :             :      */
    9029   [ +  +  +  +  :      404085 :     if (!estate->atomic && !isnull && var->datatype->typlen == -1 &&
             +  +  +  + ]
    9030                 :       29539 :         VARATT_IS_EXTERNAL_NON_EXPANDED(DatumGetPointer(newvalue)))
    9031                 :             :     {
    9032                 :             :         MemoryContext oldcxt;
    9033                 :             :         Datum       detoasted;
    9034                 :             : 
    9035                 :             :         /*
    9036                 :             :          * Do the detoasting in the eval_mcontext to avoid long-term leakage
    9037                 :             :          * of whatever memory toast fetching might leak.  Then we have to copy
    9038                 :             :          * the detoasted datum to the function's main context, which is a
    9039                 :             :          * pain, but there's little choice.
    9040                 :             :          */
    9041                 :           8 :         oldcxt = MemoryContextSwitchTo(get_eval_mcontext(estate));
    9042                 :           8 :         detoasted = PointerGetDatum(detoast_external_attr((varlena *) DatumGetPointer(newvalue)));
    9043                 :           8 :         MemoryContextSwitchTo(oldcxt);
    9044                 :             :         /* Now's a good time to not leak the input value if it's freeable */
    9045         [ +  - ]:           8 :         if (freeable)
    9046                 :           8 :             pfree(DatumGetPointer(newvalue));
    9047                 :             :         /* Once we copy the value, it's definitely freeable */
    9048                 :           8 :         newvalue = datumCopy(detoasted, false, -1);
    9049                 :           8 :         freeable = true;
    9050                 :             :         /* Can't clean up eval_mcontext here, but it'll happen before long */
    9051                 :             :     }
    9052                 :             : 
    9053                 :             :     /* Free the old value if needed */
    9054         [ +  + ]:      374546 :     if (var->freeval)
    9055                 :             :     {
    9056   [ +  -  +  +  :       64015 :         if (DatumIsReadWriteExpandedObject(var->value,
                   +  + ]
    9057                 :             :                                            var->isnull,
    9058                 :             :                                            var->datatype->typlen))
    9059                 :        4747 :             DeleteExpandedObject(var->value);
    9060                 :             :         else
    9061                 :       59268 :             pfree(DatumGetPointer(var->value));
    9062                 :             :     }
    9063                 :             :     /* Assign new value to datum */
    9064                 :      374546 :     var->value = newvalue;
    9065                 :      374546 :     var->isnull = isnull;
    9066                 :      374546 :     var->freeval = freeable;
    9067                 :             : 
    9068                 :             :     /*
    9069                 :             :      * If it's a promise variable, then either we just assigned the promised
    9070                 :             :      * value, or the user explicitly assigned an overriding value.  Either
    9071                 :             :      * way, cancel the promise.
    9072                 :             :      */
    9073                 :      374546 :     var->promise = PLPGSQL_PROMISE_NONE;
    9074                 :      374546 : }
    9075                 :             : 
    9076                 :             : /*
    9077                 :             :  * free old value of a text variable and assign new value from C string
    9078                 :             :  */
    9079                 :             : static void
    9080                 :       14755 : assign_text_var(PLpgSQL_execstate *estate, PLpgSQL_var *var, const char *str)
    9081                 :             : {
    9082                 :       14755 :     assign_simple_var(estate, var, CStringGetTextDatum(str), false, true);
    9083                 :       14755 : }
    9084                 :             : 
    9085                 :             : /*
    9086                 :             :  * assign_record_var --- assign a new value to any REC datum.
    9087                 :             :  */
    9088                 :             : static void
    9089                 :        4902 : assign_record_var(PLpgSQL_execstate *estate, PLpgSQL_rec *rec,
    9090                 :             :                   ExpandedRecordHeader *erh)
    9091                 :             : {
    9092                 :             :     Assert(rec->dtype == PLPGSQL_DTYPE_REC);
    9093                 :             : 
    9094                 :             :     /* Transfer new record object into datum_context */
    9095                 :        4902 :     TransferExpandedRecord(erh, estate->datum_context);
    9096                 :             : 
    9097                 :             :     /* Free the old value ... */
    9098         [ +  + ]:        4902 :     if (rec->erh)
    9099                 :        1197 :         DeleteExpandedObject(ExpandedRecordGetDatum(rec->erh));
    9100                 :             : 
    9101                 :             :     /* ... and install the new */
    9102                 :        4902 :     rec->erh = erh;
    9103                 :        4902 : }
    9104                 :             : 
    9105                 :             : /*
    9106                 :             :  * exec_eval_using_params --- evaluate params of USING clause
    9107                 :             :  *
    9108                 :             :  * The result data structure is created in the stmt_mcontext, and should
    9109                 :             :  * be freed by resetting that context.
    9110                 :             :  */
    9111                 :             : static ParamListInfo
    9112                 :       19841 : exec_eval_using_params(PLpgSQL_execstate *estate, List *params)
    9113                 :             : {
    9114                 :             :     ParamListInfo paramLI;
    9115                 :             :     int         nargs;
    9116                 :             :     MemoryContext stmt_mcontext;
    9117                 :             :     MemoryContext oldcontext;
    9118                 :             :     int         i;
    9119                 :             :     ListCell   *lc;
    9120                 :             : 
    9121                 :             :     /* Fast path for no parameters: we can just return NULL */
    9122         [ +  + ]:       19841 :     if (params == NIL)
    9123                 :       19544 :         return NULL;
    9124                 :             : 
    9125                 :         297 :     nargs = list_length(params);
    9126                 :         297 :     stmt_mcontext = get_stmt_mcontext(estate);
    9127                 :         297 :     oldcontext = MemoryContextSwitchTo(stmt_mcontext);
    9128                 :         297 :     paramLI = makeParamList(nargs);
    9129                 :         297 :     MemoryContextSwitchTo(oldcontext);
    9130                 :             : 
    9131                 :         297 :     i = 0;
    9132   [ +  -  +  +  :         879 :     foreach(lc, params)
                   +  + ]
    9133                 :             :     {
    9134                 :         582 :         PLpgSQL_expr *param = (PLpgSQL_expr *) lfirst(lc);
    9135                 :         582 :         ParamExternData *prm = &paramLI->params[i];
    9136                 :             :         int32       ppdtypmod;
    9137                 :             : 
    9138                 :             :         /*
    9139                 :             :          * Always mark params as const, since we only use the result with
    9140                 :             :          * one-shot plans.
    9141                 :             :          */
    9142                 :         582 :         prm->pflags = PARAM_FLAG_CONST;
    9143                 :             : 
    9144                 :         582 :         prm->value = exec_eval_expr(estate, param,
    9145                 :             :                                     &prm->isnull,
    9146                 :             :                                     &prm->ptype,
    9147                 :             :                                     &ppdtypmod);
    9148                 :             : 
    9149                 :         582 :         oldcontext = MemoryContextSwitchTo(stmt_mcontext);
    9150                 :             : 
    9151         [ -  + ]:         582 :         if (prm->ptype == UNKNOWNOID)
    9152                 :             :         {
    9153                 :             :             /*
    9154                 :             :              * Treat 'unknown' parameters as text, since that's what most
    9155                 :             :              * people would expect.  The SPI functions can coerce unknown
    9156                 :             :              * constants in a more intelligent way, but not unknown Params.
    9157                 :             :              * This code also takes care of copying into the right context.
    9158                 :             :              * Note we assume 'unknown' has the representation of C-string.
    9159                 :             :              */
    9160                 :           0 :             prm->ptype = TEXTOID;
    9161         [ #  # ]:           0 :             if (!prm->isnull)
    9162                 :           0 :                 prm->value = CStringGetTextDatum(DatumGetCString(prm->value));
    9163                 :             :         }
    9164                 :             :         /* pass-by-ref non null values must be copied into stmt_mcontext */
    9165         [ +  - ]:         582 :         else if (!prm->isnull)
    9166                 :             :         {
    9167                 :             :             int16       typLen;
    9168                 :             :             bool        typByVal;
    9169                 :             : 
    9170                 :         582 :             get_typlenbyval(prm->ptype, &typLen, &typByVal);
    9171         [ +  + ]:         582 :             if (!typByVal)
    9172                 :         554 :                 prm->value = datumCopy(prm->value, typByVal, typLen);
    9173                 :             :         }
    9174                 :             : 
    9175                 :         582 :         MemoryContextSwitchTo(oldcontext);
    9176                 :             : 
    9177                 :         582 :         exec_eval_cleanup(estate);
    9178                 :             : 
    9179                 :         582 :         i++;
    9180                 :             :     }
    9181                 :             : 
    9182                 :         297 :     return paramLI;
    9183                 :             : }
    9184                 :             : 
    9185                 :             : /*
    9186                 :             :  * Open portal for dynamic query
    9187                 :             :  *
    9188                 :             :  * Caution: this resets the stmt_mcontext at exit.  We might eventually need
    9189                 :             :  * to move that responsibility to the callers, but currently no caller needs
    9190                 :             :  * to have statement-lifetime temp data that survives past this, so it's
    9191                 :             :  * simpler to do it here.
    9192                 :             :  */
    9193                 :             : static Portal
    9194                 :        6370 : exec_dynquery_with_params(PLpgSQL_execstate *estate,
    9195                 :             :                           PLpgSQL_expr *dynquery,
    9196                 :             :                           List *params,
    9197                 :             :                           const char *portalname,
    9198                 :             :                           int cursorOptions)
    9199                 :             : {
    9200                 :             :     Portal      portal;
    9201                 :             :     Datum       query;
    9202                 :             :     bool        isnull;
    9203                 :             :     Oid         restype;
    9204                 :             :     int32       restypmod;
    9205                 :             :     char       *querystr;
    9206                 :             :     SPIParseOpenOptions options;
    9207                 :        6370 :     MemoryContext stmt_mcontext = get_stmt_mcontext(estate);
    9208                 :             : 
    9209                 :             :     /*
    9210                 :             :      * Evaluate the string expression after the EXECUTE keyword. Its result is
    9211                 :             :      * the querystring we have to execute.
    9212                 :             :      */
    9213                 :        6370 :     query = exec_eval_expr(estate, dynquery, &isnull, &restype, &restypmod);
    9214         [ -  + ]:        6370 :     if (isnull)
    9215         [ #  # ]:           0 :         ereport(ERROR,
    9216                 :             :                 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
    9217                 :             :                  errmsg("query string argument of EXECUTE is null")));
    9218                 :             : 
    9219                 :             :     /* Get the C-String representation */
    9220                 :        6370 :     querystr = convert_value_to_string(estate, query, restype);
    9221                 :             : 
    9222                 :             :     /* copy it into the stmt_mcontext before we clean up */
    9223                 :        6370 :     querystr = MemoryContextStrdup(stmt_mcontext, querystr);
    9224                 :             : 
    9225                 :        6370 :     exec_eval_cleanup(estate);
    9226                 :             : 
    9227                 :             :     /*
    9228                 :             :      * Open an implicit cursor for the query.  We use SPI_cursor_parse_open
    9229                 :             :      * even when there are no params, because this avoids making and freeing
    9230                 :             :      * one copy of the plan.
    9231                 :             :      */
    9232                 :        6370 :     memset(&options, 0, sizeof(options));
    9233                 :        6370 :     options.params = exec_eval_using_params(estate, params);
    9234                 :        6370 :     options.cursorOptions = cursorOptions;
    9235                 :        6370 :     options.read_only = estate->readonly_func;
    9236                 :             : 
    9237                 :        6370 :     portal = SPI_cursor_parse_open(portalname, querystr, &options);
    9238                 :             : 
    9239         [ -  + ]:        6370 :     if (portal == NULL)
    9240         [ #  # ]:           0 :         elog(ERROR, "could not open implicit cursor for query \"%s\": %s",
    9241                 :             :              querystr, SPI_result_code_string(SPI_result));
    9242                 :             : 
    9243                 :             :     /* Release transient data */
    9244                 :        6370 :     MemoryContextReset(stmt_mcontext);
    9245                 :             : 
    9246                 :        6370 :     return portal;
    9247                 :             : }
    9248                 :             : 
    9249                 :             : /*
    9250                 :             :  * Return a formatted string with information about an expression's parameters,
    9251                 :             :  * or NULL if the expression does not take any parameters.
    9252                 :             :  * The result is in the eval_mcontext.
    9253                 :             :  */
    9254                 :             : static char *
    9255                 :          20 : format_expr_params(PLpgSQL_execstate *estate,
    9256                 :             :                    const PLpgSQL_expr *expr)
    9257                 :             : {
    9258                 :             :     int         paramno;
    9259                 :             :     int         dno;
    9260                 :             :     StringInfoData paramstr;
    9261                 :             :     MemoryContext oldcontext;
    9262                 :             : 
    9263         [ +  + ]:          20 :     if (!expr->paramnos)
    9264                 :           4 :         return NULL;
    9265                 :             : 
    9266                 :          16 :     oldcontext = MemoryContextSwitchTo(get_eval_mcontext(estate));
    9267                 :             : 
    9268                 :          16 :     initStringInfo(&paramstr);
    9269                 :          16 :     paramno = 0;
    9270                 :          16 :     dno = -1;
    9271         [ +  + ]:          48 :     while ((dno = bms_next_member(expr->paramnos, dno)) >= 0)
    9272                 :             :     {
    9273                 :             :         Datum       paramdatum;
    9274                 :             :         Oid         paramtypeid;
    9275                 :             :         bool        paramisnull;
    9276                 :             :         int32       paramtypmod;
    9277                 :             :         PLpgSQL_var *curvar;
    9278                 :             : 
    9279                 :          32 :         curvar = (PLpgSQL_var *) estate->datums[dno];
    9280                 :             : 
    9281                 :          32 :         exec_eval_datum(estate, (PLpgSQL_datum *) curvar,
    9282                 :             :                         &paramtypeid, &paramtypmod,
    9283                 :             :                         &paramdatum, &paramisnull);
    9284                 :             : 
    9285         [ +  + ]:          32 :         appendStringInfo(&paramstr, "%s%s = ",
    9286                 :             :                          paramno > 0 ? ", " : "",
    9287                 :             :                          curvar->refname);
    9288                 :             : 
    9289         [ -  + ]:          32 :         if (paramisnull)
    9290                 :           0 :             appendStringInfoString(&paramstr, "NULL");
    9291                 :             :         else
    9292                 :          32 :             appendStringInfoStringQuoted(&paramstr,
    9293                 :          32 :                                          convert_value_to_string(estate,
    9294                 :             :                                                                  paramdatum,
    9295                 :             :                                                                  paramtypeid),
    9296                 :             :                                          -1);
    9297                 :             : 
    9298                 :          32 :         paramno++;
    9299                 :             :     }
    9300                 :             : 
    9301                 :          16 :     MemoryContextSwitchTo(oldcontext);
    9302                 :             : 
    9303                 :          16 :     return paramstr.data;
    9304                 :             : }
    9305                 :             : 
    9306                 :             : /*
    9307                 :             :  * Return a formatted string with information about the parameter values,
    9308                 :             :  * or NULL if there are no parameters.
    9309                 :             :  * The result is in the eval_mcontext.
    9310                 :             :  */
    9311                 :             : static char *
    9312                 :          12 : format_preparedparamsdata(PLpgSQL_execstate *estate,
    9313                 :             :                           ParamListInfo paramLI)
    9314                 :             : {
    9315                 :             :     int         paramno;
    9316                 :             :     StringInfoData paramstr;
    9317                 :             :     MemoryContext oldcontext;
    9318                 :             : 
    9319         [ +  + ]:          12 :     if (!paramLI)
    9320                 :           4 :         return NULL;
    9321                 :             : 
    9322                 :           8 :     oldcontext = MemoryContextSwitchTo(get_eval_mcontext(estate));
    9323                 :             : 
    9324                 :           8 :     initStringInfo(&paramstr);
    9325         [ +  + ]:          20 :     for (paramno = 0; paramno < paramLI->numParams; paramno++)
    9326                 :             :     {
    9327                 :          12 :         ParamExternData *prm = &paramLI->params[paramno];
    9328                 :             : 
    9329                 :             :         /*
    9330                 :             :          * Note: for now, this is only used on ParamListInfos produced by
    9331                 :             :          * exec_eval_using_params(), so we don't worry about invoking the
    9332                 :             :          * paramFetch hook or skipping unused parameters.
    9333                 :             :          */
    9334         [ +  + ]:          12 :         appendStringInfo(&paramstr, "%s$%d = ",
    9335                 :             :                          paramno > 0 ? ", " : "",
    9336                 :             :                          paramno + 1);
    9337                 :             : 
    9338         [ -  + ]:          12 :         if (prm->isnull)
    9339                 :           0 :             appendStringInfoString(&paramstr, "NULL");
    9340                 :             :         else
    9341                 :          12 :             appendStringInfoStringQuoted(&paramstr,
    9342                 :          12 :                                          convert_value_to_string(estate,
    9343                 :             :                                                                  prm->value,
    9344                 :             :                                                                  prm->ptype),
    9345                 :             :                                          -1);
    9346                 :             :     }
    9347                 :             : 
    9348                 :           8 :     MemoryContextSwitchTo(oldcontext);
    9349                 :             : 
    9350                 :           8 :     return paramstr.data;
    9351                 :             : }
        

Generated by: LCOV version 2.0-1