PostgreSQL Source Code  git master
pl_exec.c
Go to the documentation of this file.
1 /*-------------------------------------------------------------------------
2  *
3  * pl_exec.c - Executor for the PL/pgSQL
4  * procedural language
5  *
6  * Portions Copyright (c) 1996-2020, PostgreSQL Global Development Group
7  * Portions Copyright (c) 1994, Regents of the University of California
8  *
9  *
10  * IDENTIFICATION
11  * src/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/transam.h"
23 #include "access/tupconvert.h"
24 #include "catalog/pg_proc.h"
25 #include "catalog/pg_type.h"
26 #include "commands/defrem.h"
27 #include "executor/execExpr.h"
28 #include "executor/spi.h"
29 #include "executor/spi_priv.h"
30 #include "funcapi.h"
31 #include "mb/stringinfo_mb.h"
32 #include "miscadmin.h"
33 #include "nodes/nodeFuncs.h"
34 #include "optimizer/optimizer.h"
35 #include "parser/parse_coerce.h"
36 #include "parser/parse_type.h"
37 #include "parser/scansup.h"
38 #include "plpgsql.h"
39 #include "storage/proc.h"
40 #include "tcop/cmdtag.h"
41 #include "tcop/tcopprot.h"
42 #include "tcop/utility.h"
43 #include "utils/array.h"
44 #include "utils/builtins.h"
45 #include "utils/datum.h"
46 #include "utils/fmgroids.h"
47 #include "utils/lsyscache.h"
48 #include "utils/memutils.h"
49 #include "utils/rel.h"
50 #include "utils/snapmgr.h"
51 #include "utils/syscache.h"
52 #include "utils/typcache.h"
53 
54 typedef struct
55 {
56  int nargs; /* number of arguments */
57  Oid *types; /* types of arguments */
58  Datum *values; /* evaluated argument values */
59  char *nulls; /* null markers (' '/'n' style) */
61 
62 /*
63  * All plpgsql function executions within a single transaction share the same
64  * executor EState for evaluating "simple" expressions. Each function call
65  * creates its own "eval_econtext" ExprContext within this estate for
66  * per-evaluation workspace. eval_econtext is freed at normal function exit,
67  * and the EState is freed at transaction end (in case of error, we assume
68  * that the abort mechanisms clean it all up). Furthermore, any exception
69  * block within a function has to have its own eval_econtext separate from
70  * the containing function's, so that we can clean up ExprContext callbacks
71  * properly at subtransaction exit. We maintain a stack that tracks the
72  * individual econtexts so that we can clean up correctly at subxact exit.
73  *
74  * This arrangement is a bit tedious to maintain, but it's worth the trouble
75  * so that we don't have to re-prepare simple expressions on each trip through
76  * a function. (We assume the case to optimize is many repetitions of a
77  * function within a transaction.)
78  *
79  * However, there's no value in trying to amortize simple expression setup
80  * across multiple executions of a DO block (inline code block), since there
81  * can never be any. If we use the shared EState for a DO block, the expr
82  * state trees are effectively leaked till end of transaction, and that can
83  * add up if the user keeps on submitting DO blocks. Therefore, each DO block
84  * has its own simple-expression EState, which is cleaned up at exit from
85  * plpgsql_inline_handler(). DO blocks still use the simple_econtext_stack,
86  * though, so that subxact abort cleanup does the right thing.
87  *
88  * (However, if a DO block executes COMMIT or ROLLBACK, then exec_stmt_commit
89  * or exec_stmt_rollback will unlink it from the DO's simple-expression EState
90  * and create a new shared EState that will be used thenceforth. The original
91  * EState will be cleaned up when we get back to plpgsql_inline_handler. This
92  * is a bit ugly, but it isn't worth doing better, since scenarios like this
93  * can't result in indefinite accumulation of state trees.)
94  */
96 {
97  ExprContext *stack_econtext; /* a stacked econtext */
98  SubTransactionId xact_subxid; /* ID for current subxact */
99  struct SimpleEcontextStackEntry *next; /* next stack entry up */
101 
104 
105 /*
106  * In addition to the shared simple-eval EState, we have a shared resource
107  * owner that holds refcounts on the CachedPlans for any "simple" expressions
108  * we have evaluated in the current transaction. This allows us to avoid
109  * continually grabbing and releasing a plan refcount when a simple expression
110  * is used over and over. (DO blocks use their own resowner, in exactly the
111  * same way described above for shared_simple_eval_estate.)
112  */
114 
115 /*
116  * Memory management within a plpgsql function generally works with three
117  * contexts:
118  *
119  * 1. Function-call-lifespan data, such as variable values, is kept in the
120  * "main" context, a/k/a the "SPI Proc" context established by SPI_connect().
121  * This is usually the CurrentMemoryContext while running code in this module
122  * (which is not good, because careless coding can easily cause
123  * function-lifespan memory leaks, but we live with it for now).
124  *
125  * 2. Some statement-execution routines need statement-lifespan workspace.
126  * A suitable context is created on-demand by get_stmt_mcontext(), and must
127  * be reset at the end of the requesting routine. Error recovery will clean
128  * it up automatically. Nested statements requiring statement-lifespan
129  * workspace will result in a stack of such contexts, see push_stmt_mcontext().
130  *
131  * 3. We use the eval_econtext's per-tuple memory context for expression
132  * evaluation, and as a general-purpose workspace for short-lived allocations.
133  * Such allocations usually aren't explicitly freed, but are left to be
134  * cleaned up by a context reset, typically done by exec_eval_cleanup().
135  *
136  * These macros are for use in making short-lived allocations:
137  */
138 #define get_eval_mcontext(estate) \
139  ((estate)->eval_econtext->ecxt_per_tuple_memory)
140 #define eval_mcontext_alloc(estate, sz) \
141  MemoryContextAlloc(get_eval_mcontext(estate), sz)
142 #define eval_mcontext_alloc0(estate, sz) \
143  MemoryContextAllocZero(get_eval_mcontext(estate), sz)
144 
145 /*
146  * We use a session-wide hash table for caching cast information.
147  *
148  * Once built, the compiled expression trees (cast_expr fields) survive for
149  * the life of the session. At some point it might be worth invalidating
150  * those after pg_cast changes, but for the moment we don't bother.
151  *
152  * The evaluation state trees (cast_exprstate) are managed in the same way as
153  * simple expressions (i.e., we assume cast expressions are always simple).
154  *
155  * As with simple expressions, DO blocks don't use the shared hash table but
156  * must have their own. This isn't ideal, but we don't want to deal with
157  * multiple simple_eval_estates within a DO block.
158  */
159 typedef struct /* lookup key for cast info */
160 {
161  /* NB: we assume this struct contains no padding bytes */
162  Oid srctype; /* source type for cast */
163  Oid dsttype; /* destination type for cast */
164  int32 srctypmod; /* source typmod for cast */
165  int32 dsttypmod; /* destination typmod for cast */
167 
168 typedef struct /* cast_hash table entry */
169 {
170  plpgsql_CastHashKey key; /* hash key --- MUST BE FIRST */
171  Expr *cast_expr; /* cast expression, or NULL if no-op cast */
172  CachedExpression *cast_cexpr; /* cached expression backing the above */
173  /* ExprState is valid only when cast_lxid matches current LXID */
174  ExprState *cast_exprstate; /* expression's eval tree */
175  bool cast_in_use; /* true while we're executing eval tree */
178 
180 static HTAB *shared_cast_hash = NULL;
181 
182 /*
183  * LOOP_RC_PROCESSING encapsulates common logic for looping statements to
184  * handle return/exit/continue result codes from the loop body statement(s).
185  * It's meant to be used like this:
186  *
187  * int rc = PLPGSQL_RC_OK;
188  * for (...)
189  * {
190  * ...
191  * rc = exec_stmts(estate, stmt->body);
192  * LOOP_RC_PROCESSING(stmt->label, break);
193  * ...
194  * }
195  * return rc;
196  *
197  * If execution of the loop should terminate, LOOP_RC_PROCESSING will execute
198  * "exit_action" (typically a "break" or "goto"), after updating "rc" to the
199  * value the current statement should return. If execution should continue,
200  * LOOP_RC_PROCESSING will do nothing except reset "rc" to PLPGSQL_RC_OK.
201  *
202  * estate and rc are implicit arguments to the macro.
203  * estate->exitlabel is examined and possibly updated.
204  */
205 #define LOOP_RC_PROCESSING(looplabel, exit_action) \
206  if (rc == PLPGSQL_RC_RETURN) \
207  { \
208  /* RETURN, so propagate RC_RETURN out */ \
209  exit_action; \
210  } \
211  else if (rc == PLPGSQL_RC_EXIT) \
212  { \
213  if (estate->exitlabel == NULL) \
214  { \
215  /* unlabelled EXIT terminates this loop */ \
216  rc = PLPGSQL_RC_OK; \
217  exit_action; \
218  } \
219  else if ((looplabel) != NULL && \
220  strcmp(looplabel, estate->exitlabel) == 0) \
221  { \
222  /* labelled EXIT matching this loop, so terminate loop */ \
223  estate->exitlabel = NULL; \
224  rc = PLPGSQL_RC_OK; \
225  exit_action; \
226  } \
227  else \
228  { \
229  /* non-matching labelled EXIT, propagate RC_EXIT out */ \
230  exit_action; \
231  } \
232  } \
233  else if (rc == PLPGSQL_RC_CONTINUE) \
234  { \
235  if (estate->exitlabel == NULL) \
236  { \
237  /* unlabelled CONTINUE matches this loop, so continue in loop */ \
238  rc = PLPGSQL_RC_OK; \
239  } \
240  else if ((looplabel) != NULL && \
241  strcmp(looplabel, estate->exitlabel) == 0) \
242  { \
243  /* labelled CONTINUE matching this loop, so continue in loop */ \
244  estate->exitlabel = NULL; \
245  rc = PLPGSQL_RC_OK; \
246  } \
247  else \
248  { \
249  /* non-matching labelled CONTINUE, propagate RC_CONTINUE out */ \
250  exit_action; \
251  } \
252  } \
253  else \
254  Assert(rc == PLPGSQL_RC_OK)
255 
256 /************************************************************
257  * Local function forward declarations
258  ************************************************************/
260  TupleDesc tupdesc);
261 static void plpgsql_exec_error_callback(void *arg);
262 static void copy_plpgsql_datums(PLpgSQL_execstate *estate,
263  PLpgSQL_function *func);
264 static void plpgsql_fulfill_promise(PLpgSQL_execstate *estate,
265  PLpgSQL_var *var);
267 static void push_stmt_mcontext(PLpgSQL_execstate *estate);
268 static void pop_stmt_mcontext(PLpgSQL_execstate *estate);
269 
270 static int exec_stmt_block(PLpgSQL_execstate *estate,
271  PLpgSQL_stmt_block *block);
272 static int exec_stmts(PLpgSQL_execstate *estate,
273  List *stmts);
274 static int exec_stmt(PLpgSQL_execstate *estate,
275  PLpgSQL_stmt *stmt);
276 static int exec_stmt_assign(PLpgSQL_execstate *estate,
277  PLpgSQL_stmt_assign *stmt);
278 static int exec_stmt_perform(PLpgSQL_execstate *estate,
279  PLpgSQL_stmt_perform *stmt);
280 static int exec_stmt_call(PLpgSQL_execstate *estate,
281  PLpgSQL_stmt_call *stmt);
282 static int exec_stmt_getdiag(PLpgSQL_execstate *estate,
283  PLpgSQL_stmt_getdiag *stmt);
284 static int exec_stmt_if(PLpgSQL_execstate *estate,
285  PLpgSQL_stmt_if *stmt);
286 static int exec_stmt_case(PLpgSQL_execstate *estate,
287  PLpgSQL_stmt_case *stmt);
288 static int exec_stmt_loop(PLpgSQL_execstate *estate,
289  PLpgSQL_stmt_loop *stmt);
290 static int exec_stmt_while(PLpgSQL_execstate *estate,
291  PLpgSQL_stmt_while *stmt);
292 static int exec_stmt_fori(PLpgSQL_execstate *estate,
293  PLpgSQL_stmt_fori *stmt);
294 static int exec_stmt_fors(PLpgSQL_execstate *estate,
295  PLpgSQL_stmt_fors *stmt);
296 static int exec_stmt_forc(PLpgSQL_execstate *estate,
297  PLpgSQL_stmt_forc *stmt);
298 static int exec_stmt_foreach_a(PLpgSQL_execstate *estate,
299  PLpgSQL_stmt_foreach_a *stmt);
300 static int exec_stmt_open(PLpgSQL_execstate *estate,
301  PLpgSQL_stmt_open *stmt);
302 static int exec_stmt_fetch(PLpgSQL_execstate *estate,
303  PLpgSQL_stmt_fetch *stmt);
304 static int exec_stmt_close(PLpgSQL_execstate *estate,
305  PLpgSQL_stmt_close *stmt);
306 static int exec_stmt_exit(PLpgSQL_execstate *estate,
307  PLpgSQL_stmt_exit *stmt);
308 static int exec_stmt_return(PLpgSQL_execstate *estate,
309  PLpgSQL_stmt_return *stmt);
310 static int exec_stmt_return_next(PLpgSQL_execstate *estate,
312 static int exec_stmt_return_query(PLpgSQL_execstate *estate,
314 static int exec_stmt_raise(PLpgSQL_execstate *estate,
315  PLpgSQL_stmt_raise *stmt);
316 static int exec_stmt_assert(PLpgSQL_execstate *estate,
317  PLpgSQL_stmt_assert *stmt);
318 static int exec_stmt_execsql(PLpgSQL_execstate *estate,
319  PLpgSQL_stmt_execsql *stmt);
320 static int exec_stmt_dynexecute(PLpgSQL_execstate *estate,
322 static int exec_stmt_dynfors(PLpgSQL_execstate *estate,
323  PLpgSQL_stmt_dynfors *stmt);
324 static int exec_stmt_commit(PLpgSQL_execstate *estate,
325  PLpgSQL_stmt_commit *stmt);
326 static int exec_stmt_rollback(PLpgSQL_execstate *estate,
327  PLpgSQL_stmt_rollback *stmt);
328 static int exec_stmt_set(PLpgSQL_execstate *estate,
329  PLpgSQL_stmt_set *stmt);
330 
331 static void plpgsql_estate_setup(PLpgSQL_execstate *estate,
332  PLpgSQL_function *func,
333  ReturnSetInfo *rsi,
334  EState *simple_eval_estate,
335  ResourceOwner simple_eval_resowner);
336 static void exec_eval_cleanup(PLpgSQL_execstate *estate);
337 
338 static void exec_prepare_plan(PLpgSQL_execstate *estate,
339  PLpgSQL_expr *expr, int cursorOptions,
340  bool keepplan);
341 static void exec_simple_check_plan(PLpgSQL_execstate *estate, PLpgSQL_expr *expr);
342 static void exec_save_simple_expr(PLpgSQL_expr *expr, CachedPlan *cplan);
343 static void exec_check_rw_parameter(PLpgSQL_expr *expr, int target_dno);
344 static bool contains_target_param(Node *node, int *target_dno);
345 static bool exec_eval_simple_expr(PLpgSQL_execstate *estate,
346  PLpgSQL_expr *expr,
347  Datum *result,
348  bool *isNull,
349  Oid *rettype,
350  int32 *rettypmod);
351 
352 static void exec_assign_expr(PLpgSQL_execstate *estate,
353  PLpgSQL_datum *target,
354  PLpgSQL_expr *expr);
355 static void exec_assign_c_string(PLpgSQL_execstate *estate,
356  PLpgSQL_datum *target,
357  const char *str);
358 static void exec_assign_value(PLpgSQL_execstate *estate,
359  PLpgSQL_datum *target,
360  Datum value, bool isNull,
361  Oid valtype, int32 valtypmod);
362 static void exec_eval_datum(PLpgSQL_execstate *estate,
363  PLpgSQL_datum *datum,
364  Oid *typeid,
365  int32 *typetypmod,
366  Datum *value,
367  bool *isnull);
368 static int exec_eval_integer(PLpgSQL_execstate *estate,
369  PLpgSQL_expr *expr,
370  bool *isNull);
371 static bool exec_eval_boolean(PLpgSQL_execstate *estate,
372  PLpgSQL_expr *expr,
373  bool *isNull);
374 static Datum exec_eval_expr(PLpgSQL_execstate *estate,
375  PLpgSQL_expr *expr,
376  bool *isNull,
377  Oid *rettype,
378  int32 *rettypmod);
379 static int exec_run_select(PLpgSQL_execstate *estate,
380  PLpgSQL_expr *expr, long maxtuples, Portal *portalP);
381 static int exec_for_query(PLpgSQL_execstate *estate, PLpgSQL_stmt_forq *stmt,
382  Portal portal, bool prefetch_ok);
384  PLpgSQL_expr *expr);
386  int paramid, bool speculative,
387  ParamExternData *workspace);
388 static void plpgsql_param_compile(ParamListInfo params, Param *param,
389  ExprState *state,
390  Datum *resv, bool *resnull);
392  ExprContext *econtext);
394  ExprContext *econtext);
396  ExprContext *econtext);
398  ExprContext *econtext);
400  ExprContext *econtext);
401 static void exec_move_row(PLpgSQL_execstate *estate,
402  PLpgSQL_variable *target,
403  HeapTuple tup, TupleDesc tupdesc);
404 static void revalidate_rectypeid(PLpgSQL_rec *rec);
406  PLpgSQL_rec *rec,
407  TupleDesc srctupdesc,
408  ExpandedRecordHeader *srcerh);
409 static void exec_move_row_from_fields(PLpgSQL_execstate *estate,
410  PLpgSQL_variable *target,
411  ExpandedRecordHeader *newerh,
412  Datum *values, bool *nulls,
413  TupleDesc tupdesc);
414 static bool compatible_tupdescs(TupleDesc src_tupdesc, TupleDesc dst_tupdesc);
416  PLpgSQL_row *row,
417  TupleDesc tupdesc);
419  HeapTupleData *tmptup);
420 static void exec_move_row_from_datum(PLpgSQL_execstate *estate,
421  PLpgSQL_variable *target,
422  Datum value);
424  PLpgSQL_rec *rec);
425 static char *convert_value_to_string(PLpgSQL_execstate *estate,
426  Datum value, Oid valtype);
428  Datum value, bool *isnull,
429  Oid valtype, int32 valtypmod,
430  Oid reqtype, int32 reqtypmod);
432  Oid srctype, int32 srctypmod,
433  Oid dsttype, int32 dsttypmod);
434 static void exec_init_tuple_store(PLpgSQL_execstate *estate);
435 static void exec_set_found(PLpgSQL_execstate *estate, bool state);
436 static void plpgsql_create_econtext(PLpgSQL_execstate *estate);
437 static void plpgsql_destroy_econtext(PLpgSQL_execstate *estate);
438 static void assign_simple_var(PLpgSQL_execstate *estate, PLpgSQL_var *var,
439  Datum newvalue, bool isnull, bool freeable);
440 static void assign_text_var(PLpgSQL_execstate *estate, PLpgSQL_var *var,
441  const char *str);
442 static void assign_record_var(PLpgSQL_execstate *estate, PLpgSQL_rec *rec,
443  ExpandedRecordHeader *erh);
445  List *params);
447  PLpgSQL_expr *dynquery, List *params,
448  const char *portalname, int cursorOptions);
449 static char *format_expr_params(PLpgSQL_execstate *estate,
450  const PLpgSQL_expr *expr);
451 static char *format_preparedparamsdata(PLpgSQL_execstate *estate,
452  const PreparedParamsData *ppd);
453 
454 
455 /* ----------
456  * plpgsql_exec_function Called by the call handler for
457  * function execution.
458  *
459  * This is also used to execute inline code blocks (DO blocks). The only
460  * difference that this code is aware of is that for a DO block, we want
461  * to use a private simple_eval_estate and a private simple_eval_resowner,
462  * which are created and passed in by the caller. For regular functions,
463  * pass NULL, which implies using shared_simple_eval_estate and
464  * shared_simple_eval_resowner. (When using a private simple_eval_estate,
465  * we must also use a private cast hashtable, but that's taken care of
466  * within plpgsql_estate_setup.)
467  * ----------
468  */
469 Datum
471  EState *simple_eval_estate,
472  ResourceOwner simple_eval_resowner,
473  bool atomic)
474 {
475  PLpgSQL_execstate estate;
476  ErrorContextCallback plerrcontext;
477  int i;
478  int rc;
479 
480  /*
481  * Setup the execution state
482  */
483  plpgsql_estate_setup(&estate, func, (ReturnSetInfo *) fcinfo->resultinfo,
484  simple_eval_estate, simple_eval_resowner);
485  estate.atomic = atomic;
486 
487  /*
488  * Setup error traceback support for ereport()
489  */
490  plerrcontext.callback = plpgsql_exec_error_callback;
491  plerrcontext.arg = &estate;
492  plerrcontext.previous = error_context_stack;
493  error_context_stack = &plerrcontext;
494 
495  /*
496  * Make local execution copies of all the datums
497  */
498  estate.err_text = gettext_noop("during initialization of execution state");
499  copy_plpgsql_datums(&estate, func);
500 
501  /*
502  * Store the actual call argument values into the appropriate variables
503  */
504  estate.err_text = gettext_noop("while storing call arguments into local variables");
505  for (i = 0; i < func->fn_nargs; i++)
506  {
507  int n = func->fn_argvarnos[i];
508 
509  switch (estate.datums[n]->dtype)
510  {
511  case PLPGSQL_DTYPE_VAR:
512  {
513  PLpgSQL_var *var = (PLpgSQL_var *) estate.datums[n];
514 
515  assign_simple_var(&estate, var,
516  fcinfo->args[i].value,
517  fcinfo->args[i].isnull,
518  false);
519 
520  /*
521  * Force any array-valued parameter to be stored in
522  * expanded form in our local variable, in hopes of
523  * improving efficiency of uses of the variable. (This is
524  * a hack, really: why only arrays? Need more thought
525  * about which cases are likely to win. See also
526  * typisarray-specific heuristic in exec_assign_value.)
527  *
528  * Special cases: If passed a R/W expanded pointer, assume
529  * we can commandeer the object rather than having to copy
530  * it. If passed a R/O expanded pointer, just keep it as
531  * the value of the variable for the moment. (We'll force
532  * it to R/W if the variable gets modified, but that may
533  * very well never happen.)
534  */
535  if (!var->isnull && var->datatype->typisarray)
536  {
538  {
539  /* take ownership of R/W object */
540  assign_simple_var(&estate, var,
542  estate.datum_context),
543  false,
544  true);
545  }
547  {
548  /* R/O pointer, keep it as-is until assigned to */
549  }
550  else
551  {
552  /* flat array, so force to expanded form */
553  assign_simple_var(&estate, var,
554  expand_array(var->value,
555  estate.datum_context,
556  NULL),
557  false,
558  true);
559  }
560  }
561  }
562  break;
563 
564  case PLPGSQL_DTYPE_REC:
565  {
566  PLpgSQL_rec *rec = (PLpgSQL_rec *) estate.datums[n];
567 
568  if (!fcinfo->args[i].isnull)
569  {
570  /* Assign row value from composite datum */
571  exec_move_row_from_datum(&estate,
572  (PLpgSQL_variable *) rec,
573  fcinfo->args[i].value);
574  }
575  else
576  {
577  /* If arg is null, set variable to null */
578  exec_move_row(&estate, (PLpgSQL_variable *) rec,
579  NULL, NULL);
580  }
581  /* clean up after exec_move_row() */
582  exec_eval_cleanup(&estate);
583  }
584  break;
585 
586  default:
587  /* Anything else should not be an argument variable */
588  elog(ERROR, "unrecognized dtype: %d", func->datums[i]->dtype);
589  }
590  }
591 
592  estate.err_text = gettext_noop("during function entry");
593 
594  /*
595  * Set the magic variable FOUND to false
596  */
597  exec_set_found(&estate, false);
598 
599  /*
600  * Let the instrumentation plugin peek at this function
601  */
602  if (*plpgsql_plugin_ptr && (*plpgsql_plugin_ptr)->func_beg)
603  ((*plpgsql_plugin_ptr)->func_beg) (&estate, func);
604 
605  /*
606  * Now call the toplevel block of statements
607  */
608  estate.err_text = NULL;
609  estate.err_stmt = (PLpgSQL_stmt *) (func->action);
610  rc = exec_stmt(&estate, (PLpgSQL_stmt *) func->action);
611  if (rc != PLPGSQL_RC_RETURN)
612  {
613  estate.err_stmt = NULL;
614  estate.err_text = NULL;
615  ereport(ERROR,
616  (errcode(ERRCODE_S_R_E_FUNCTION_EXECUTED_NO_RETURN_STATEMENT),
617  errmsg("control reached end of function without RETURN")));
618  }
619 
620  /*
621  * We got a return value - process it
622  */
623  estate.err_stmt = NULL;
624  estate.err_text = gettext_noop("while casting return value to function's return type");
625 
626  fcinfo->isnull = estate.retisnull;
627 
628  if (estate.retisset)
629  {
630  ReturnSetInfo *rsi = estate.rsi;
631 
632  /* Check caller can handle a set result */
633  if (!rsi || !IsA(rsi, ReturnSetInfo) ||
634  (rsi->allowedModes & SFRM_Materialize) == 0)
635  ereport(ERROR,
636  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
637  errmsg("set-valued function called in context that cannot accept a set")));
639 
640  /* If we produced any tuples, send back the result */
641  if (estate.tuple_store)
642  {
643  MemoryContext oldcxt;
644 
645  rsi->setResult = estate.tuple_store;
646  oldcxt = MemoryContextSwitchTo(estate.tuple_store_cxt);
648  MemoryContextSwitchTo(oldcxt);
649  }
650  estate.retval = (Datum) 0;
651  fcinfo->isnull = true;
652  }
653  else if (!estate.retisnull)
654  {
655  /*
656  * Cast result value to function's declared result type, and copy it
657  * out to the upper executor memory context. We must treat tuple
658  * results specially in order to deal with cases like rowtypes
659  * involving dropped columns.
660  */
661  if (estate.retistuple)
662  {
663  /* Don't need coercion if rowtype is known to match */
664  if (func->fn_rettype == estate.rettype &&
665  func->fn_rettype != RECORDOID)
666  {
667  /*
668  * Copy the tuple result into upper executor memory context.
669  * However, if we have a R/W expanded datum, we can just
670  * transfer its ownership out to the upper context.
671  */
672  estate.retval = SPI_datumTransfer(estate.retval,
673  false,
674  -1);
675  }
676  else
677  {
678  /*
679  * Need to look up the expected result type. XXX would be
680  * better to cache the tupdesc instead of repeating
681  * get_call_result_type(), but the only easy place to save it
682  * is in the PLpgSQL_function struct, and that's too
683  * long-lived: composite types could change during the
684  * existence of a PLpgSQL_function.
685  */
686  Oid resultTypeId;
687  TupleDesc tupdesc;
688 
689  switch (get_call_result_type(fcinfo, &resultTypeId, &tupdesc))
690  {
691  case TYPEFUNC_COMPOSITE:
692  /* got the expected result rowtype, now coerce it */
693  coerce_function_result_tuple(&estate, tupdesc);
694  break;
696  /* got the expected result rowtype, now coerce it */
697  coerce_function_result_tuple(&estate, tupdesc);
698  /* and check domain constraints */
699  /* XXX allowing caching here would be good, too */
700  domain_check(estate.retval, false, resultTypeId,
701  NULL, NULL);
702  break;
703  case TYPEFUNC_RECORD:
704 
705  /*
706  * Failed to determine actual type of RECORD. We
707  * could raise an error here, but what this means in
708  * practice is that the caller is expecting any old
709  * generic rowtype, so we don't really need to be
710  * restrictive. Pass back the generated result as-is.
711  */
712  estate.retval = SPI_datumTransfer(estate.retval,
713  false,
714  -1);
715  break;
716  default:
717  /* shouldn't get here if retistuple is true ... */
718  elog(ERROR, "return type must be a row type");
719  break;
720  }
721  }
722  }
723  else
724  {
725  /* Scalar case: use exec_cast_value */
726  estate.retval = exec_cast_value(&estate,
727  estate.retval,
728  &fcinfo->isnull,
729  estate.rettype,
730  -1,
731  func->fn_rettype,
732  -1);
733 
734  /*
735  * If the function's return type isn't by value, copy the value
736  * into upper executor memory context. However, if we have a R/W
737  * expanded datum, we can just transfer its ownership out to the
738  * upper executor context.
739  */
740  if (!fcinfo->isnull && !func->fn_retbyval)
741  estate.retval = SPI_datumTransfer(estate.retval,
742  false,
743  func->fn_rettyplen);
744  }
745  }
746  else
747  {
748  /*
749  * We're returning a NULL, which normally requires no conversion work
750  * regardless of datatypes. But, if we are casting it to a domain
751  * return type, we'd better check that the domain's constraints pass.
752  */
753  if (func->fn_retisdomain)
754  estate.retval = exec_cast_value(&estate,
755  estate.retval,
756  &fcinfo->isnull,
757  estate.rettype,
758  -1,
759  func->fn_rettype,
760  -1);
761  }
762 
763  estate.err_text = gettext_noop("during function exit");
764 
765  /*
766  * Let the instrumentation plugin peek at this function
767  */
768  if (*plpgsql_plugin_ptr && (*plpgsql_plugin_ptr)->func_end)
769  ((*plpgsql_plugin_ptr)->func_end) (&estate, func);
770 
771  /* Clean up any leftover temporary memory */
772  plpgsql_destroy_econtext(&estate);
773  exec_eval_cleanup(&estate);
774  /* stmt_mcontext will be destroyed when function's main context is */
775 
776  /*
777  * Pop the error context stack
778  */
779  error_context_stack = plerrcontext.previous;
780 
781  /*
782  * Return the function's result
783  */
784  return estate.retval;
785 }
786 
787 /*
788  * Helper for plpgsql_exec_function: coerce composite result to the specified
789  * tuple descriptor, and copy it out to upper executor memory. This is split
790  * out mostly for cosmetic reasons --- the logic would be very deeply nested
791  * otherwise.
792  *
793  * estate->retval is updated in-place.
794  */
795 static void
797 {
798  HeapTuple rettup;
799  TupleDesc retdesc;
800  TupleConversionMap *tupmap;
801 
802  /* We assume exec_stmt_return verified that result is composite */
803  Assert(type_is_rowtype(estate->rettype));
804 
805  /* We can special-case expanded records for speed */
807  {
809 
810  Assert(erh->er_magic == ER_MAGIC);
811 
812  /* Extract record's TupleDesc */
813  retdesc = expanded_record_get_tupdesc(erh);
814 
815  /* check rowtype compatibility */
816  tupmap = convert_tuples_by_position(retdesc,
817  tupdesc,
818  gettext_noop("returned record type does not match expected record type"));
819 
820  /* it might need conversion */
821  if (tupmap)
822  {
823  rettup = expanded_record_get_tuple(erh);
824  Assert(rettup);
825  rettup = execute_attr_map_tuple(rettup, tupmap);
826 
827  /*
828  * Copy tuple to upper executor memory, as a tuple Datum. Make
829  * sure it is labeled with the caller-supplied tuple type.
830  */
831  estate->retval = PointerGetDatum(SPI_returntuple(rettup, tupdesc));
832  /* no need to free map, we're about to return anyway */
833  }
834  else if (!(tupdesc->tdtypeid == erh->er_decltypeid ||
835  (tupdesc->tdtypeid == RECORDOID &&
836  !ExpandedRecordIsDomain(erh))))
837  {
838  /*
839  * The expanded record has the right physical tupdesc, but the
840  * wrong type ID. (Typically, the expanded record is RECORDOID
841  * but the function is declared to return a named composite type.
842  * As in exec_move_row_from_datum, we don't allow returning a
843  * composite-domain record from a function declared to return
844  * RECORD.) So we must flatten the record to a tuple datum and
845  * overwrite its type fields with the right thing. spi.c doesn't
846  * provide any easy way to deal with this case, so we end up
847  * duplicating the guts of datumCopy() :-(
848  */
849  Size resultsize;
850  HeapTupleHeader tuphdr;
851 
852  resultsize = EOH_get_flat_size(&erh->hdr);
853  tuphdr = (HeapTupleHeader) SPI_palloc(resultsize);
854  EOH_flatten_into(&erh->hdr, (void *) tuphdr, resultsize);
855  HeapTupleHeaderSetTypeId(tuphdr, tupdesc->tdtypeid);
856  HeapTupleHeaderSetTypMod(tuphdr, tupdesc->tdtypmod);
857  estate->retval = PointerGetDatum(tuphdr);
858  }
859  else
860  {
861  /*
862  * We need only copy result into upper executor memory context.
863  * However, if we have a R/W expanded datum, we can just transfer
864  * its ownership out to the upper executor context.
865  */
866  estate->retval = SPI_datumTransfer(estate->retval,
867  false,
868  -1);
869  }
870  }
871  else
872  {
873  /* Convert composite datum to a HeapTuple and TupleDesc */
874  HeapTupleData tmptup;
875 
876  retdesc = deconstruct_composite_datum(estate->retval, &tmptup);
877  rettup = &tmptup;
878 
879  /* check rowtype compatibility */
880  tupmap = convert_tuples_by_position(retdesc,
881  tupdesc,
882  gettext_noop("returned record type does not match expected record type"));
883 
884  /* it might need conversion */
885  if (tupmap)
886  rettup = execute_attr_map_tuple(rettup, tupmap);
887 
888  /*
889  * Copy tuple to upper executor memory, as a tuple Datum. Make sure
890  * it is labeled with the caller-supplied tuple type.
891  */
892  estate->retval = PointerGetDatum(SPI_returntuple(rettup, tupdesc));
893 
894  /* no need to free map, we're about to return anyway */
895 
896  ReleaseTupleDesc(retdesc);
897  }
898 }
899 
900 
901 /* ----------
902  * plpgsql_exec_trigger Called by the call handler for
903  * trigger execution.
904  * ----------
905  */
906 HeapTuple
908  TriggerData *trigdata)
909 {
910  PLpgSQL_execstate estate;
911  ErrorContextCallback plerrcontext;
912  int rc;
913  TupleDesc tupdesc;
914  PLpgSQL_rec *rec_new,
915  *rec_old;
916  HeapTuple rettup;
917 
918  /*
919  * Setup the execution state
920  */
921  plpgsql_estate_setup(&estate, func, NULL, NULL, NULL);
922  estate.trigdata = trigdata;
923 
924  /*
925  * Setup error traceback support for ereport()
926  */
927  plerrcontext.callback = plpgsql_exec_error_callback;
928  plerrcontext.arg = &estate;
929  plerrcontext.previous = error_context_stack;
930  error_context_stack = &plerrcontext;
931 
932  /*
933  * Make local execution copies of all the datums
934  */
935  estate.err_text = gettext_noop("during initialization of execution state");
936  copy_plpgsql_datums(&estate, func);
937 
938  /*
939  * Put the OLD and NEW tuples into record variables
940  *
941  * We set up expanded records for both variables even though only one may
942  * have a value. This allows record references to succeed in functions
943  * that are used for multiple trigger types. For example, we might have a
944  * test like "if (TG_OP = 'INSERT' and NEW.foo = 'xyz')", which should
945  * work regardless of the current trigger type. If a value is actually
946  * fetched from an unsupplied tuple, it will read as NULL.
947  */
948  tupdesc = RelationGetDescr(trigdata->tg_relation);
949 
950  rec_new = (PLpgSQL_rec *) (estate.datums[func->new_varno]);
951  rec_old = (PLpgSQL_rec *) (estate.datums[func->old_varno]);
952 
953  rec_new->erh = make_expanded_record_from_tupdesc(tupdesc,
954  estate.datum_context);
955  rec_old->erh = make_expanded_record_from_exprecord(rec_new->erh,
956  estate.datum_context);
957 
958  if (!TRIGGER_FIRED_FOR_ROW(trigdata->tg_event))
959  {
960  /*
961  * Per-statement triggers don't use OLD/NEW variables
962  */
963  }
964  else if (TRIGGER_FIRED_BY_INSERT(trigdata->tg_event))
965  {
966  expanded_record_set_tuple(rec_new->erh, trigdata->tg_trigtuple,
967  false, false);
968  }
969  else if (TRIGGER_FIRED_BY_UPDATE(trigdata->tg_event))
970  {
971  expanded_record_set_tuple(rec_new->erh, trigdata->tg_newtuple,
972  false, false);
973  expanded_record_set_tuple(rec_old->erh, trigdata->tg_trigtuple,
974  false, false);
975 
976  /*
977  * In BEFORE trigger, stored generated columns are not computed yet,
978  * so make them null in the NEW row. (Only needed in UPDATE branch;
979  * in the INSERT case, they are already null, but in UPDATE, the field
980  * still contains the old value.) Alternatively, we could construct a
981  * whole new row structure without the generated columns, but this way
982  * seems more efficient and potentially less confusing.
983  */
984  if (tupdesc->constr && tupdesc->constr->has_generated_stored &&
985  TRIGGER_FIRED_BEFORE(trigdata->tg_event))
986  {
987  for (int i = 0; i < tupdesc->natts; i++)
988  if (TupleDescAttr(tupdesc, i)->attgenerated == ATTRIBUTE_GENERATED_STORED)
990  i + 1,
991  (Datum) 0,
992  true, /* isnull */
993  false, false);
994  }
995  }
996  else if (TRIGGER_FIRED_BY_DELETE(trigdata->tg_event))
997  {
998  expanded_record_set_tuple(rec_old->erh, trigdata->tg_trigtuple,
999  false, false);
1000  }
1001  else
1002  elog(ERROR, "unrecognized trigger action: not INSERT, DELETE, or UPDATE");
1003 
1004  /* Make transition tables visible to this SPI connection */
1005  rc = SPI_register_trigger_data(trigdata);
1006  Assert(rc >= 0);
1007 
1008  estate.err_text = gettext_noop("during function entry");
1009 
1010  /*
1011  * Set the magic variable FOUND to false
1012  */
1013  exec_set_found(&estate, false);
1014 
1015  /*
1016  * Let the instrumentation plugin peek at this function
1017  */
1018  if (*plpgsql_plugin_ptr && (*plpgsql_plugin_ptr)->func_beg)
1019  ((*plpgsql_plugin_ptr)->func_beg) (&estate, func);
1020 
1021  /*
1022  * Now call the toplevel block of statements
1023  */
1024  estate.err_text = NULL;
1025  estate.err_stmt = (PLpgSQL_stmt *) (func->action);
1026  rc = exec_stmt(&estate, (PLpgSQL_stmt *) func->action);
1027  if (rc != PLPGSQL_RC_RETURN)
1028  {
1029  estate.err_stmt = NULL;
1030  estate.err_text = NULL;
1031  ereport(ERROR,
1032  (errcode(ERRCODE_S_R_E_FUNCTION_EXECUTED_NO_RETURN_STATEMENT),
1033  errmsg("control reached end of trigger procedure without RETURN")));
1034  }
1035 
1036  estate.err_stmt = NULL;
1037  estate.err_text = gettext_noop("during function exit");
1038 
1039  if (estate.retisset)
1040  ereport(ERROR,
1041  (errcode(ERRCODE_DATATYPE_MISMATCH),
1042  errmsg("trigger procedure cannot return a set")));
1043 
1044  /*
1045  * Check that the returned tuple structure has the same attributes, the
1046  * relation that fired the trigger has. A per-statement trigger always
1047  * needs to return NULL, so we ignore any return value the function itself
1048  * produces (XXX: is this a good idea?)
1049  *
1050  * XXX This way it is possible, that the trigger returns a tuple where
1051  * attributes don't have the correct atttypmod's length. It's up to the
1052  * trigger's programmer to ensure that this doesn't happen. Jan
1053  */
1054  if (estate.retisnull || !TRIGGER_FIRED_FOR_ROW(trigdata->tg_event))
1055  rettup = NULL;
1056  else
1057  {
1058  TupleDesc retdesc;
1059  TupleConversionMap *tupmap;
1060 
1061  /* We assume exec_stmt_return verified that result is composite */
1062  Assert(type_is_rowtype(estate.rettype));
1063 
1064  /* We can special-case expanded records for speed */
1066  {
1068 
1069  Assert(erh->er_magic == ER_MAGIC);
1070 
1071  /* Extract HeapTuple and TupleDesc */
1072  rettup = expanded_record_get_tuple(erh);
1073  Assert(rettup);
1074  retdesc = expanded_record_get_tupdesc(erh);
1075 
1076  if (retdesc != RelationGetDescr(trigdata->tg_relation))
1077  {
1078  /* check rowtype compatibility */
1079  tupmap = convert_tuples_by_position(retdesc,
1080  RelationGetDescr(trigdata->tg_relation),
1081  gettext_noop("returned row structure does not match the structure of the triggering table"));
1082  /* it might need conversion */
1083  if (tupmap)
1084  rettup = execute_attr_map_tuple(rettup, tupmap);
1085  /* no need to free map, we're about to return anyway */
1086  }
1087 
1088  /*
1089  * Copy tuple to upper executor memory. But if user just did
1090  * "return new" or "return old" without changing anything, there's
1091  * no need to copy; we can return the original tuple (which will
1092  * save a few cycles in trigger.c as well as here).
1093  */
1094  if (rettup != trigdata->tg_newtuple &&
1095  rettup != trigdata->tg_trigtuple)
1096  rettup = SPI_copytuple(rettup);
1097  }
1098  else
1099  {
1100  /* Convert composite datum to a HeapTuple and TupleDesc */
1101  HeapTupleData tmptup;
1102 
1103  retdesc = deconstruct_composite_datum(estate.retval, &tmptup);
1104  rettup = &tmptup;
1105 
1106  /* check rowtype compatibility */
1107  tupmap = convert_tuples_by_position(retdesc,
1108  RelationGetDescr(trigdata->tg_relation),
1109  gettext_noop("returned row structure does not match the structure of the triggering table"));
1110  /* it might need conversion */
1111  if (tupmap)
1112  rettup = execute_attr_map_tuple(rettup, tupmap);
1113 
1114  ReleaseTupleDesc(retdesc);
1115  /* no need to free map, we're about to return anyway */
1116 
1117  /* Copy tuple to upper executor memory */
1118  rettup = SPI_copytuple(rettup);
1119  }
1120  }
1121 
1122  /*
1123  * Let the instrumentation plugin peek at this function
1124  */
1125  if (*plpgsql_plugin_ptr && (*plpgsql_plugin_ptr)->func_end)
1126  ((*plpgsql_plugin_ptr)->func_end) (&estate, func);
1127 
1128  /* Clean up any leftover temporary memory */
1129  plpgsql_destroy_econtext(&estate);
1130  exec_eval_cleanup(&estate);
1131  /* stmt_mcontext will be destroyed when function's main context is */
1132 
1133  /*
1134  * Pop the error context stack
1135  */
1136  error_context_stack = plerrcontext.previous;
1137 
1138  /*
1139  * Return the trigger's result
1140  */
1141  return rettup;
1142 }
1143 
1144 /* ----------
1145  * plpgsql_exec_event_trigger Called by the call handler for
1146  * event trigger execution.
1147  * ----------
1148  */
1149 void
1151 {
1152  PLpgSQL_execstate estate;
1153  ErrorContextCallback plerrcontext;
1154  int rc;
1155 
1156  /*
1157  * Setup the execution state
1158  */
1159  plpgsql_estate_setup(&estate, func, NULL, NULL, NULL);
1160  estate.evtrigdata = trigdata;
1161 
1162  /*
1163  * Setup error traceback support for ereport()
1164  */
1165  plerrcontext.callback = plpgsql_exec_error_callback;
1166  plerrcontext.arg = &estate;
1167  plerrcontext.previous = error_context_stack;
1168  error_context_stack = &plerrcontext;
1169 
1170  /*
1171  * Make local execution copies of all the datums
1172  */
1173  estate.err_text = gettext_noop("during initialization of execution state");
1174  copy_plpgsql_datums(&estate, func);
1175 
1176  /*
1177  * Let the instrumentation plugin peek at this function
1178  */
1179  if (*plpgsql_plugin_ptr && (*plpgsql_plugin_ptr)->func_beg)
1180  ((*plpgsql_plugin_ptr)->func_beg) (&estate, func);
1181 
1182  /*
1183  * Now call the toplevel block of statements
1184  */
1185  estate.err_text = NULL;
1186  estate.err_stmt = (PLpgSQL_stmt *) (func->action);
1187  rc = exec_stmt(&estate, (PLpgSQL_stmt *) func->action);
1188  if (rc != PLPGSQL_RC_RETURN)
1189  {
1190  estate.err_stmt = NULL;
1191  estate.err_text = NULL;
1192  ereport(ERROR,
1193  (errcode(ERRCODE_S_R_E_FUNCTION_EXECUTED_NO_RETURN_STATEMENT),
1194  errmsg("control reached end of trigger procedure without RETURN")));
1195  }
1196 
1197  estate.err_stmt = NULL;
1198  estate.err_text = gettext_noop("during function exit");
1199 
1200  /*
1201  * Let the instrumentation plugin peek at this function
1202  */
1203  if (*plpgsql_plugin_ptr && (*plpgsql_plugin_ptr)->func_end)
1204  ((*plpgsql_plugin_ptr)->func_end) (&estate, func);
1205 
1206  /* Clean up any leftover temporary memory */
1207  plpgsql_destroy_econtext(&estate);
1208  exec_eval_cleanup(&estate);
1209  /* stmt_mcontext will be destroyed when function's main context is */
1210 
1211  /*
1212  * Pop the error context stack
1213  */
1214  error_context_stack = plerrcontext.previous;
1215 }
1216 
1217 /*
1218  * error context callback to let us supply a call-stack traceback
1219  */
1220 static void
1222 {
1223  PLpgSQL_execstate *estate = (PLpgSQL_execstate *) arg;
1224 
1225  if (estate->err_text != NULL)
1226  {
1227  /*
1228  * We don't expend the cycles to run gettext() on err_text unless we
1229  * actually need it. Therefore, places that set up err_text should
1230  * use gettext_noop() to ensure the strings get recorded in the
1231  * message dictionary.
1232  *
1233  * If both err_text and err_stmt are set, use the err_text as
1234  * description, but report the err_stmt's line number. When err_stmt
1235  * is not set, we're in function entry/exit, or some such place not
1236  * attached to a specific line number.
1237  */
1238  if (estate->err_stmt != NULL)
1239  {
1240  /*
1241  * translator: last %s is a phrase such as "during statement block
1242  * local variable initialization"
1243  */
1244  errcontext("PL/pgSQL function %s line %d %s",
1245  estate->func->fn_signature,
1246  estate->err_stmt->lineno,
1247  _(estate->err_text));
1248  }
1249  else
1250  {
1251  /*
1252  * translator: last %s is a phrase such as "while storing call
1253  * arguments into local variables"
1254  */
1255  errcontext("PL/pgSQL function %s %s",
1256  estate->func->fn_signature,
1257  _(estate->err_text));
1258  }
1259  }
1260  else if (estate->err_stmt != NULL)
1261  {
1262  /* translator: last %s is a plpgsql statement type name */
1263  errcontext("PL/pgSQL function %s line %d at %s",
1264  estate->func->fn_signature,
1265  estate->err_stmt->lineno,
1266  plpgsql_stmt_typename(estate->err_stmt));
1267  }
1268  else
1269  errcontext("PL/pgSQL function %s",
1270  estate->func->fn_signature);
1271 }
1272 
1273 
1274 /* ----------
1275  * Support function for initializing local execution variables
1276  * ----------
1277  */
1278 static void
1280  PLpgSQL_function *func)
1281 {
1282  int ndatums = estate->ndatums;
1283  PLpgSQL_datum **indatums;
1284  PLpgSQL_datum **outdatums;
1285  char *workspace;
1286  char *ws_next;
1287  int i;
1288 
1289  /* Allocate local datum-pointer array */
1290  estate->datums = (PLpgSQL_datum **)
1291  palloc(sizeof(PLpgSQL_datum *) * ndatums);
1292 
1293  /*
1294  * To reduce palloc overhead, we make a single palloc request for all the
1295  * space needed for locally-instantiated datums.
1296  */
1297  workspace = palloc(func->copiable_size);
1298  ws_next = workspace;
1299 
1300  /* Fill datum-pointer array, copying datums into workspace as needed */
1301  indatums = func->datums;
1302  outdatums = estate->datums;
1303  for (i = 0; i < ndatums; i++)
1304  {
1305  PLpgSQL_datum *indatum = indatums[i];
1306  PLpgSQL_datum *outdatum;
1307 
1308  /* This must agree with plpgsql_finish_datums on what is copiable */
1309  switch (indatum->dtype)
1310  {
1311  case PLPGSQL_DTYPE_VAR:
1312  case PLPGSQL_DTYPE_PROMISE:
1313  outdatum = (PLpgSQL_datum *) ws_next;
1314  memcpy(outdatum, indatum, sizeof(PLpgSQL_var));
1315  ws_next += MAXALIGN(sizeof(PLpgSQL_var));
1316  break;
1317 
1318  case PLPGSQL_DTYPE_REC:
1319  outdatum = (PLpgSQL_datum *) ws_next;
1320  memcpy(outdatum, indatum, sizeof(PLpgSQL_rec));
1321  ws_next += MAXALIGN(sizeof(PLpgSQL_rec));
1322  break;
1323 
1324  case PLPGSQL_DTYPE_ROW:
1327 
1328  /*
1329  * These datum records are read-only at runtime, so no need to
1330  * copy them (well, RECFIELD and ARRAYELEM contain cached
1331  * data, but we'd just as soon centralize the caching anyway).
1332  */
1333  outdatum = indatum;
1334  break;
1335 
1336  default:
1337  elog(ERROR, "unrecognized dtype: %d", indatum->dtype);
1338  outdatum = NULL; /* keep compiler quiet */
1339  break;
1340  }
1341 
1342  outdatums[i] = outdatum;
1343  }
1344 
1345  Assert(ws_next == workspace + func->copiable_size);
1346 }
1347 
1348 /*
1349  * If the variable has an armed "promise", compute the promised value
1350  * and assign it to the variable.
1351  * The assignment automatically disarms the promise.
1352  */
1353 static void
1355  PLpgSQL_var *var)
1356 {
1357  MemoryContext oldcontext;
1358 
1359  if (var->promise == PLPGSQL_PROMISE_NONE)
1360  return; /* nothing to do */
1361 
1362  /*
1363  * This will typically be invoked in a short-lived context such as the
1364  * mcontext. We must create variable values in the estate's datum
1365  * context. This quick-and-dirty solution risks leaking some additional
1366  * cruft there, but since any one promise is honored at most once per
1367  * function call, it's probably not worth being more careful.
1368  */
1369  oldcontext = MemoryContextSwitchTo(estate->datum_context);
1370 
1371  switch (var->promise)
1372  {
1374  if (estate->trigdata == NULL)
1375  elog(ERROR, "trigger promise is not in a trigger function");
1376  assign_simple_var(estate, var,
1379  false, true);
1380  break;
1381 
1383  if (estate->trigdata == NULL)
1384  elog(ERROR, "trigger promise is not in a trigger function");
1385  if (TRIGGER_FIRED_BEFORE(estate->trigdata->tg_event))
1386  assign_text_var(estate, var, "BEFORE");
1387  else if (TRIGGER_FIRED_AFTER(estate->trigdata->tg_event))
1388  assign_text_var(estate, var, "AFTER");
1389  else if (TRIGGER_FIRED_INSTEAD(estate->trigdata->tg_event))
1390  assign_text_var(estate, var, "INSTEAD OF");
1391  else
1392  elog(ERROR, "unrecognized trigger execution time: not BEFORE, AFTER, or INSTEAD OF");
1393  break;
1394 
1396  if (estate->trigdata == NULL)
1397  elog(ERROR, "trigger promise is not in a trigger function");
1398  if (TRIGGER_FIRED_FOR_ROW(estate->trigdata->tg_event))
1399  assign_text_var(estate, var, "ROW");
1400  else if (TRIGGER_FIRED_FOR_STATEMENT(estate->trigdata->tg_event))
1401  assign_text_var(estate, var, "STATEMENT");
1402  else
1403  elog(ERROR, "unrecognized trigger event type: not ROW or STATEMENT");
1404  break;
1405 
1406  case PLPGSQL_PROMISE_TG_OP:
1407  if (estate->trigdata == NULL)
1408  elog(ERROR, "trigger promise is not in a trigger function");
1410  assign_text_var(estate, var, "INSERT");
1411  else if (TRIGGER_FIRED_BY_UPDATE(estate->trigdata->tg_event))
1412  assign_text_var(estate, var, "UPDATE");
1413  else if (TRIGGER_FIRED_BY_DELETE(estate->trigdata->tg_event))
1414  assign_text_var(estate, var, "DELETE");
1415  else if (TRIGGER_FIRED_BY_TRUNCATE(estate->trigdata->tg_event))
1416  assign_text_var(estate, var, "TRUNCATE");
1417  else
1418  elog(ERROR, "unrecognized trigger action: not INSERT, DELETE, UPDATE, or TRUNCATE");
1419  break;
1420 
1422  if (estate->trigdata == NULL)
1423  elog(ERROR, "trigger promise is not in a trigger function");
1424  assign_simple_var(estate, var,
1426  false, false);
1427  break;
1428 
1430  if (estate->trigdata == NULL)
1431  elog(ERROR, "trigger promise is not in a trigger function");
1432  assign_simple_var(estate, var,
1435  false, true);
1436  break;
1437 
1439  if (estate->trigdata == NULL)
1440  elog(ERROR, "trigger promise is not in a trigger function");
1441  assign_simple_var(estate, var,
1444  false, true);
1445  break;
1446 
1448  if (estate->trigdata == NULL)
1449  elog(ERROR, "trigger promise is not in a trigger function");
1450  assign_simple_var(estate, var,
1452  false, false);
1453  break;
1454 
1456  if (estate->trigdata == NULL)
1457  elog(ERROR, "trigger promise is not in a trigger function");
1458  if (estate->trigdata->tg_trigger->tgnargs > 0)
1459  {
1460  /*
1461  * For historical reasons, tg_argv[] subscripts start at zero
1462  * not one. So we can't use construct_array().
1463  */
1464  int nelems = estate->trigdata->tg_trigger->tgnargs;
1465  Datum *elems;
1466  int dims[1];
1467  int lbs[1];
1468  int i;
1469 
1470  elems = palloc(sizeof(Datum) * nelems);
1471  for (i = 0; i < nelems; i++)
1472  elems[i] = CStringGetTextDatum(estate->trigdata->tg_trigger->tgargs[i]);
1473  dims[0] = nelems;
1474  lbs[0] = 0;
1475 
1476  assign_simple_var(estate, var,
1477  PointerGetDatum(construct_md_array(elems, NULL,
1478  1, dims, lbs,
1479  TEXTOID,
1480  -1, false, TYPALIGN_INT)),
1481  false, true);
1482  }
1483  else
1484  {
1485  assign_simple_var(estate, var, (Datum) 0, true, false);
1486  }
1487  break;
1488 
1490  if (estate->evtrigdata == NULL)
1491  elog(ERROR, "event trigger promise is not in an event trigger function");
1492  assign_text_var(estate, var, estate->evtrigdata->event);
1493  break;
1494 
1496  if (estate->evtrigdata == NULL)
1497  elog(ERROR, "event trigger promise is not in an event trigger function");
1498  assign_text_var(estate, var, GetCommandTagName(estate->evtrigdata->tag));
1499  break;
1500 
1501  default:
1502  elog(ERROR, "unrecognized promise type: %d", var->promise);
1503  }
1504 
1505  MemoryContextSwitchTo(oldcontext);
1506 }
1507 
1508 /*
1509  * Create a memory context for statement-lifespan variables, if we don't
1510  * have one already. It will be a child of stmt_mcontext_parent, which is
1511  * either the function's main context or a pushed-down outer stmt_mcontext.
1512  */
1513 static MemoryContext
1515 {
1516  if (estate->stmt_mcontext == NULL)
1517  {
1518  estate->stmt_mcontext =
1520  "PLpgSQL per-statement data",
1522  }
1523  return estate->stmt_mcontext;
1524 }
1525 
1526 /*
1527  * Push down the current stmt_mcontext so that called statements won't use it.
1528  * This is needed by statements that have statement-lifespan data and need to
1529  * preserve it across some inner statements. The caller should eventually do
1530  * pop_stmt_mcontext().
1531  */
1532 static void
1534 {
1535  /* Should have done get_stmt_mcontext() first */
1536  Assert(estate->stmt_mcontext != NULL);
1537  /* Assert we've not messed up the stack linkage */
1539  /* Push it down to become the parent of any nested stmt mcontext */
1540  estate->stmt_mcontext_parent = estate->stmt_mcontext;
1541  /* And make it not available for use directly */
1542  estate->stmt_mcontext = NULL;
1543 }
1544 
1545 /*
1546  * Undo push_stmt_mcontext(). We assume this is done just before or after
1547  * resetting the caller's stmt_mcontext; since that action will also delete
1548  * any child contexts, there's no need to explicitly delete whatever context
1549  * might currently be estate->stmt_mcontext.
1550  */
1551 static void
1553 {
1554  /* We need only pop the stack */
1555  estate->stmt_mcontext = estate->stmt_mcontext_parent;
1557 }
1558 
1559 
1560 /*
1561  * Subroutine for exec_stmt_block: does any condition in the condition list
1562  * match the current exception?
1563  */
1564 static bool
1566 {
1567  for (; cond != NULL; cond = cond->next)
1568  {
1569  int sqlerrstate = cond->sqlerrstate;
1570 
1571  /*
1572  * OTHERS matches everything *except* query-canceled and
1573  * assert-failure. If you're foolish enough, you can match those
1574  * explicitly.
1575  */
1576  if (sqlerrstate == 0)
1577  {
1578  if (edata->sqlerrcode != ERRCODE_QUERY_CANCELED &&
1579  edata->sqlerrcode != ERRCODE_ASSERT_FAILURE)
1580  return true;
1581  }
1582  /* Exact match? */
1583  else if (edata->sqlerrcode == sqlerrstate)
1584  return true;
1585  /* Category match? */
1586  else if (ERRCODE_IS_CATEGORY(sqlerrstate) &&
1587  ERRCODE_TO_CATEGORY(edata->sqlerrcode) == sqlerrstate)
1588  return true;
1589  }
1590  return false;
1591 }
1592 
1593 
1594 /* ----------
1595  * exec_stmt_block Execute a block of statements
1596  * ----------
1597  */
1598 static int
1600 {
1601  volatile int rc = -1;
1602  int i;
1603 
1604  /*
1605  * First initialize all variables declared in this block
1606  */
1607  estate->err_text = gettext_noop("during statement block local variable initialization");
1608 
1609  for (i = 0; i < block->n_initvars; i++)
1610  {
1611  int n = block->initvarnos[i];
1612  PLpgSQL_datum *datum = estate->datums[n];
1613 
1614  /*
1615  * The set of dtypes handled here must match plpgsql_add_initdatums().
1616  *
1617  * Note that we currently don't support promise datums within blocks,
1618  * only at a function's outermost scope, so we needn't handle those
1619  * here.
1620  */
1621  switch (datum->dtype)
1622  {
1623  case PLPGSQL_DTYPE_VAR:
1624  {
1625  PLpgSQL_var *var = (PLpgSQL_var *) datum;
1626 
1627  /*
1628  * Free any old value, in case re-entering block, and
1629  * initialize to NULL
1630  */
1631  assign_simple_var(estate, var, (Datum) 0, true, false);
1632 
1633  if (var->default_val == NULL)
1634  {
1635  /*
1636  * If needed, give the datatype a chance to reject
1637  * NULLs, by assigning a NULL to the variable. We
1638  * claim the value is of type UNKNOWN, not the var's
1639  * datatype, else coercion will be skipped.
1640  */
1641  if (var->datatype->typtype == TYPTYPE_DOMAIN)
1642  exec_assign_value(estate,
1643  (PLpgSQL_datum *) var,
1644  (Datum) 0,
1645  true,
1646  UNKNOWNOID,
1647  -1);
1648 
1649  /* parser should have rejected NOT NULL */
1650  Assert(!var->notnull);
1651  }
1652  else
1653  {
1654  exec_assign_expr(estate, (PLpgSQL_datum *) var,
1655  var->default_val);
1656  }
1657  }
1658  break;
1659 
1660  case PLPGSQL_DTYPE_REC:
1661  {
1662  PLpgSQL_rec *rec = (PLpgSQL_rec *) datum;
1663 
1664  /*
1665  * Deletion of any existing object will be handled during
1666  * the assignments below, and in some cases it's more
1667  * efficient for us not to get rid of it beforehand.
1668  */
1669  if (rec->default_val == NULL)
1670  {
1671  /*
1672  * If needed, give the datatype a chance to reject
1673  * NULLs, by assigning a NULL to the variable.
1674  */
1675  exec_move_row(estate, (PLpgSQL_variable *) rec,
1676  NULL, NULL);
1677 
1678  /* parser should have rejected NOT NULL */
1679  Assert(!rec->notnull);
1680  }
1681  else
1682  {
1683  exec_assign_expr(estate, (PLpgSQL_datum *) rec,
1684  rec->default_val);
1685  }
1686  }
1687  break;
1688 
1689  default:
1690  elog(ERROR, "unrecognized dtype: %d", datum->dtype);
1691  }
1692  }
1693 
1694  if (block->exceptions)
1695  {
1696  /*
1697  * Execute the statements in the block's body inside a sub-transaction
1698  */
1699  MemoryContext oldcontext = CurrentMemoryContext;
1701  ExprContext *old_eval_econtext = estate->eval_econtext;
1702  ErrorData *save_cur_error = estate->cur_error;
1703  MemoryContext stmt_mcontext;
1704 
1705  estate->err_text = gettext_noop("during statement block entry");
1706 
1707  /*
1708  * We will need a stmt_mcontext to hold the error data if an error
1709  * occurs. It seems best to force it to exist before entering the
1710  * subtransaction, so that we reduce the risk of out-of-memory during
1711  * error recovery, and because this greatly simplifies restoring the
1712  * stmt_mcontext stack to the correct state after an error. We can
1713  * ameliorate the cost of this by allowing the called statements to
1714  * use this mcontext too; so we don't push it down here.
1715  */
1716  stmt_mcontext = get_stmt_mcontext(estate);
1717 
1719  /* Want to run statements inside function's memory context */
1720  MemoryContextSwitchTo(oldcontext);
1721 
1722  PG_TRY();
1723  {
1724  /*
1725  * We need to run the block's statements with a new eval_econtext
1726  * that belongs to the current subtransaction; if we try to use
1727  * the outer econtext then ExprContext shutdown callbacks will be
1728  * called at the wrong times.
1729  */
1730  plpgsql_create_econtext(estate);
1731 
1732  estate->err_text = NULL;
1733 
1734  /* Run the block's statements */
1735  rc = exec_stmts(estate, block->body);
1736 
1737  estate->err_text = gettext_noop("during statement block exit");
1738 
1739  /*
1740  * If the block ended with RETURN, we may need to copy the return
1741  * value out of the subtransaction eval_context. We can avoid a
1742  * physical copy if the value happens to be a R/W expanded object.
1743  */
1744  if (rc == PLPGSQL_RC_RETURN &&
1745  !estate->retisset &&
1746  !estate->retisnull)
1747  {
1748  int16 resTypLen;
1749  bool resTypByVal;
1750 
1751  get_typlenbyval(estate->rettype, &resTypLen, &resTypByVal);
1752  estate->retval = datumTransfer(estate->retval,
1753  resTypByVal, resTypLen);
1754  }
1755 
1756  /* Commit the inner transaction, return to outer xact context */
1758  MemoryContextSwitchTo(oldcontext);
1759  CurrentResourceOwner = oldowner;
1760 
1761  /* Assert that the stmt_mcontext stack is unchanged */
1762  Assert(stmt_mcontext == estate->stmt_mcontext);
1763 
1764  /*
1765  * Revert to outer eval_econtext. (The inner one was
1766  * automatically cleaned up during subxact exit.)
1767  */
1768  estate->eval_econtext = old_eval_econtext;
1769  }
1770  PG_CATCH();
1771  {
1772  ErrorData *edata;
1773  ListCell *e;
1774 
1775  estate->err_text = gettext_noop("during exception cleanup");
1776 
1777  /* Save error info in our stmt_mcontext */
1778  MemoryContextSwitchTo(stmt_mcontext);
1779  edata = CopyErrorData();
1780  FlushErrorState();
1781 
1782  /* Abort the inner transaction */
1784  MemoryContextSwitchTo(oldcontext);
1785  CurrentResourceOwner = oldowner;
1786 
1787  /*
1788  * Set up the stmt_mcontext stack as though we had restored our
1789  * previous state and then done push_stmt_mcontext(). The push is
1790  * needed so that statements in the exception handler won't
1791  * clobber the error data that's in our stmt_mcontext.
1792  */
1793  estate->stmt_mcontext_parent = stmt_mcontext;
1794  estate->stmt_mcontext = NULL;
1795 
1796  /*
1797  * Now we can delete any nested stmt_mcontexts that might have
1798  * been created as children of ours. (Note: we do not immediately
1799  * release any statement-lifespan data that might have been left
1800  * behind in stmt_mcontext itself. We could attempt that by doing
1801  * a MemoryContextReset on it before collecting the error data
1802  * above, but it seems too risky to do any significant amount of
1803  * work before collecting the error.)
1804  */
1805  MemoryContextDeleteChildren(stmt_mcontext);
1806 
1807  /* Revert to outer eval_econtext */
1808  estate->eval_econtext = old_eval_econtext;
1809 
1810  /*
1811  * Must clean up the econtext too. However, any tuple table made
1812  * in the subxact will have been thrown away by SPI during subxact
1813  * abort, so we don't need to (and mustn't try to) free the
1814  * eval_tuptable.
1815  */
1816  estate->eval_tuptable = NULL;
1817  exec_eval_cleanup(estate);
1818 
1819  /* Look for a matching exception handler */
1820  foreach(e, block->exceptions->exc_list)
1821  {
1822  PLpgSQL_exception *exception = (PLpgSQL_exception *) lfirst(e);
1823 
1824  if (exception_matches_conditions(edata, exception->conditions))
1825  {
1826  /*
1827  * Initialize the magic SQLSTATE and SQLERRM variables for
1828  * the exception block; this also frees values from any
1829  * prior use of the same exception. We needn't do this
1830  * until we have found a matching exception.
1831  */
1832  PLpgSQL_var *state_var;
1833  PLpgSQL_var *errm_var;
1834 
1835  state_var = (PLpgSQL_var *)
1836  estate->datums[block->exceptions->sqlstate_varno];
1837  errm_var = (PLpgSQL_var *)
1838  estate->datums[block->exceptions->sqlerrm_varno];
1839 
1840  assign_text_var(estate, state_var,
1841  unpack_sql_state(edata->sqlerrcode));
1842  assign_text_var(estate, errm_var, edata->message);
1843 
1844  /*
1845  * Also set up cur_error so the error data is accessible
1846  * inside the handler.
1847  */
1848  estate->cur_error = edata;
1849 
1850  estate->err_text = NULL;
1851 
1852  rc = exec_stmts(estate, exception->action);
1853 
1854  break;
1855  }
1856  }
1857 
1858  /*
1859  * Restore previous state of cur_error, whether or not we executed
1860  * a handler. This is needed in case an error got thrown from
1861  * some inner block's exception handler.
1862  */
1863  estate->cur_error = save_cur_error;
1864 
1865  /* If no match found, re-throw the error */
1866  if (e == NULL)
1867  ReThrowError(edata);
1868 
1869  /* Restore stmt_mcontext stack and release the error data */
1870  pop_stmt_mcontext(estate);
1871  MemoryContextReset(stmt_mcontext);
1872  }
1873  PG_END_TRY();
1874 
1875  Assert(save_cur_error == estate->cur_error);
1876  }
1877  else
1878  {
1879  /*
1880  * Just execute the statements in the block's body
1881  */
1882  estate->err_text = NULL;
1883 
1884  rc = exec_stmts(estate, block->body);
1885  }
1886 
1887  estate->err_text = NULL;
1888 
1889  /*
1890  * Handle the return code. This is intentionally different from
1891  * LOOP_RC_PROCESSING(): CONTINUE never matches a block, and EXIT matches
1892  * a block only if there is a label match.
1893  */
1894  switch (rc)
1895  {
1896  case PLPGSQL_RC_OK:
1897  case PLPGSQL_RC_RETURN:
1898  case PLPGSQL_RC_CONTINUE:
1899  return rc;
1900 
1901  case PLPGSQL_RC_EXIT:
1902  if (estate->exitlabel == NULL)
1903  return PLPGSQL_RC_EXIT;
1904  if (block->label == NULL)
1905  return PLPGSQL_RC_EXIT;
1906  if (strcmp(block->label, estate->exitlabel) != 0)
1907  return PLPGSQL_RC_EXIT;
1908  estate->exitlabel = NULL;
1909  return PLPGSQL_RC_OK;
1910 
1911  default:
1912  elog(ERROR, "unrecognized rc: %d", rc);
1913  }
1914 
1915  return PLPGSQL_RC_OK;
1916 }
1917 
1918 
1919 /* ----------
1920  * exec_stmts Iterate over a list of statements
1921  * as long as their return code is OK
1922  * ----------
1923  */
1924 static int
1926 {
1927  ListCell *s;
1928 
1929  if (stmts == NIL)
1930  {
1931  /*
1932  * Ensure we do a CHECK_FOR_INTERRUPTS() even though there is no
1933  * statement. This prevents hangup in a tight loop if, for instance,
1934  * there is a LOOP construct with an empty body.
1935  */
1937  return PLPGSQL_RC_OK;
1938  }
1939 
1940  foreach(s, stmts)
1941  {
1942  PLpgSQL_stmt *stmt = (PLpgSQL_stmt *) lfirst(s);
1943  int rc = exec_stmt(estate, stmt);
1944 
1945  if (rc != PLPGSQL_RC_OK)
1946  return rc;
1947  }
1948 
1949  return PLPGSQL_RC_OK;
1950 }
1951 
1952 
1953 /* ----------
1954  * exec_stmt Distribute one statement to the statements
1955  * type specific execution function.
1956  * ----------
1957  */
1958 static int
1960 {
1961  PLpgSQL_stmt *save_estmt;
1962  int rc = -1;
1963 
1964  save_estmt = estate->err_stmt;
1965  estate->err_stmt = stmt;
1966 
1967  /* Let the plugin know that we are about to execute this statement */
1968  if (*plpgsql_plugin_ptr && (*plpgsql_plugin_ptr)->stmt_beg)
1969  ((*plpgsql_plugin_ptr)->stmt_beg) (estate, stmt);
1970 
1972 
1973  switch (stmt->cmd_type)
1974  {
1975  case PLPGSQL_STMT_BLOCK:
1976  rc = exec_stmt_block(estate, (PLpgSQL_stmt_block *) stmt);
1977  break;
1978 
1979  case PLPGSQL_STMT_ASSIGN:
1980  rc = exec_stmt_assign(estate, (PLpgSQL_stmt_assign *) stmt);
1981  break;
1982 
1983  case PLPGSQL_STMT_PERFORM:
1984  rc = exec_stmt_perform(estate, (PLpgSQL_stmt_perform *) stmt);
1985  break;
1986 
1987  case PLPGSQL_STMT_CALL:
1988  rc = exec_stmt_call(estate, (PLpgSQL_stmt_call *) stmt);
1989  break;
1990 
1991  case PLPGSQL_STMT_GETDIAG:
1992  rc = exec_stmt_getdiag(estate, (PLpgSQL_stmt_getdiag *) stmt);
1993  break;
1994 
1995  case PLPGSQL_STMT_IF:
1996  rc = exec_stmt_if(estate, (PLpgSQL_stmt_if *) stmt);
1997  break;
1998 
1999  case PLPGSQL_STMT_CASE:
2000  rc = exec_stmt_case(estate, (PLpgSQL_stmt_case *) stmt);
2001  break;
2002 
2003  case PLPGSQL_STMT_LOOP:
2004  rc = exec_stmt_loop(estate, (PLpgSQL_stmt_loop *) stmt);
2005  break;
2006 
2007  case PLPGSQL_STMT_WHILE:
2008  rc = exec_stmt_while(estate, (PLpgSQL_stmt_while *) stmt);
2009  break;
2010 
2011  case PLPGSQL_STMT_FORI:
2012  rc = exec_stmt_fori(estate, (PLpgSQL_stmt_fori *) stmt);
2013  break;
2014 
2015  case PLPGSQL_STMT_FORS:
2016  rc = exec_stmt_fors(estate, (PLpgSQL_stmt_fors *) stmt);
2017  break;
2018 
2019  case PLPGSQL_STMT_FORC:
2020  rc = exec_stmt_forc(estate, (PLpgSQL_stmt_forc *) stmt);
2021  break;
2022 
2024  rc = exec_stmt_foreach_a(estate, (PLpgSQL_stmt_foreach_a *) stmt);
2025  break;
2026 
2027  case PLPGSQL_STMT_EXIT:
2028  rc = exec_stmt_exit(estate, (PLpgSQL_stmt_exit *) stmt);
2029  break;
2030 
2031  case PLPGSQL_STMT_RETURN:
2032  rc = exec_stmt_return(estate, (PLpgSQL_stmt_return *) stmt);
2033  break;
2034 
2036  rc = exec_stmt_return_next(estate, (PLpgSQL_stmt_return_next *) stmt);
2037  break;
2038 
2040  rc = exec_stmt_return_query(estate, (PLpgSQL_stmt_return_query *) stmt);
2041  break;
2042 
2043  case PLPGSQL_STMT_RAISE:
2044  rc = exec_stmt_raise(estate, (PLpgSQL_stmt_raise *) stmt);
2045  break;
2046 
2047  case PLPGSQL_STMT_ASSERT:
2048  rc = exec_stmt_assert(estate, (PLpgSQL_stmt_assert *) stmt);
2049  break;
2050 
2051  case PLPGSQL_STMT_EXECSQL:
2052  rc = exec_stmt_execsql(estate, (PLpgSQL_stmt_execsql *) stmt);
2053  break;
2054 
2056  rc = exec_stmt_dynexecute(estate, (PLpgSQL_stmt_dynexecute *) stmt);
2057  break;
2058 
2059  case PLPGSQL_STMT_DYNFORS:
2060  rc = exec_stmt_dynfors(estate, (PLpgSQL_stmt_dynfors *) stmt);
2061  break;
2062 
2063  case PLPGSQL_STMT_OPEN:
2064  rc = exec_stmt_open(estate, (PLpgSQL_stmt_open *) stmt);
2065  break;
2066 
2067  case PLPGSQL_STMT_FETCH:
2068  rc = exec_stmt_fetch(estate, (PLpgSQL_stmt_fetch *) stmt);
2069  break;
2070 
2071  case PLPGSQL_STMT_CLOSE:
2072  rc = exec_stmt_close(estate, (PLpgSQL_stmt_close *) stmt);
2073  break;
2074 
2075  case PLPGSQL_STMT_COMMIT:
2076  rc = exec_stmt_commit(estate, (PLpgSQL_stmt_commit *) stmt);
2077  break;
2078 
2079  case PLPGSQL_STMT_ROLLBACK:
2080  rc = exec_stmt_rollback(estate, (PLpgSQL_stmt_rollback *) stmt);
2081  break;
2082 
2083  case PLPGSQL_STMT_SET:
2084  rc = exec_stmt_set(estate, (PLpgSQL_stmt_set *) stmt);
2085  break;
2086 
2087  default:
2088  estate->err_stmt = save_estmt;
2089  elog(ERROR, "unrecognized cmd_type: %d", stmt->cmd_type);
2090  }
2091 
2092  /* Let the plugin know that we have finished executing this statement */
2093  if (*plpgsql_plugin_ptr && (*plpgsql_plugin_ptr)->stmt_end)
2094  ((*plpgsql_plugin_ptr)->stmt_end) (estate, stmt);
2095 
2096  estate->err_stmt = save_estmt;
2097 
2098  return rc;
2099 }
2100 
2101 
2102 /* ----------
2103  * exec_stmt_assign Evaluate an expression and
2104  * put the result into a variable.
2105  * ----------
2106  */
2107 static int
2109 {
2110  Assert(stmt->varno >= 0);
2111 
2112  exec_assign_expr(estate, estate->datums[stmt->varno], stmt->expr);
2113 
2114  return PLPGSQL_RC_OK;
2115 }
2116 
2117 /* ----------
2118  * exec_stmt_perform Evaluate query and discard result (but set
2119  * FOUND depending on whether at least one row
2120  * was returned).
2121  * ----------
2122  */
2123 static int
2125 {
2126  PLpgSQL_expr *expr = stmt->expr;
2127 
2128  (void) exec_run_select(estate, expr, 0, NULL);
2129  exec_set_found(estate, (estate->eval_processed != 0));
2130  exec_eval_cleanup(estate);
2131 
2132  return PLPGSQL_RC_OK;
2133 }
2134 
2135 /*
2136  * exec_stmt_call
2137  */
2138 static int
2140 {
2141  PLpgSQL_expr *expr = stmt->expr;
2142  volatile LocalTransactionId before_lxid;
2143  LocalTransactionId after_lxid;
2144  volatile bool pushed_active_snap = false;
2145  volatile int rc;
2146 
2147  /* PG_TRY to ensure we clear the plan link, if needed, on failure */
2148  PG_TRY();
2149  {
2150  SPIPlanPtr plan = expr->plan;
2151  ParamListInfo paramLI;
2152 
2153  if (plan == NULL)
2154  {
2155 
2156  /*
2157  * Don't save the plan if not in atomic context. Otherwise,
2158  * transaction ends would cause errors about plancache leaks.
2159  *
2160  * XXX This would be fixable with some plancache/resowner surgery
2161  * elsewhere, but for now we'll just work around this here.
2162  */
2163  exec_prepare_plan(estate, expr, 0, estate->atomic);
2164 
2165  /*
2166  * The procedure call could end transactions, which would upset
2167  * the snapshot management in SPI_execute*, so don't let it do it.
2168  * Instead, we set the snapshots ourselves below.
2169  */
2170  plan = expr->plan;
2171  plan->no_snapshots = true;
2172 
2173  /*
2174  * Force target to be recalculated whenever the plan changes, in
2175  * case the procedure's argument list has changed.
2176  */
2177  stmt->target = NULL;
2178  }
2179 
2180  /*
2181  * We construct a DTYPE_ROW datum representing the plpgsql variables
2182  * associated with the procedure's output arguments. Then we can use
2183  * exec_move_row() to do the assignments.
2184  */
2185  if (stmt->is_call && stmt->target == NULL)
2186  {
2187  Node *node;
2188  FuncExpr *funcexpr;
2189  HeapTuple func_tuple;
2190  List *funcargs;
2191  Oid *argtypes;
2192  char **argnames;
2193  char *argmodes;
2194  MemoryContext oldcontext;
2195  PLpgSQL_row *row;
2196  int nfields;
2197  int i;
2198  ListCell *lc;
2199 
2200  /*
2201  * Get the parsed CallStmt, and look up the called procedure
2202  */
2203  node = linitial_node(Query,
2204  ((CachedPlanSource *) linitial(plan->plancache_list))->query_list)->utilityStmt;
2205  if (node == NULL || !IsA(node, CallStmt))
2206  elog(ERROR, "query for CALL statement is not a CallStmt");
2207 
2208  funcexpr = ((CallStmt *) node)->funcexpr;
2209 
2210  func_tuple = SearchSysCache1(PROCOID,
2211  ObjectIdGetDatum(funcexpr->funcid));
2212  if (!HeapTupleIsValid(func_tuple))
2213  elog(ERROR, "cache lookup failed for function %u",
2214  funcexpr->funcid);
2215 
2216  /*
2217  * Extract function arguments, and expand any named-arg notation
2218  */
2219  funcargs = expand_function_arguments(funcexpr->args,
2220  funcexpr->funcresulttype,
2221  func_tuple);
2222 
2223  /*
2224  * Get the argument names and modes, too
2225  */
2226  get_func_arg_info(func_tuple, &argtypes, &argnames, &argmodes);
2227 
2228  ReleaseSysCache(func_tuple);
2229 
2230  /*
2231  * Begin constructing row Datum
2232  */
2233  oldcontext = MemoryContextSwitchTo(estate->func->fn_cxt);
2234 
2235  row = (PLpgSQL_row *) palloc0(sizeof(PLpgSQL_row));
2236  row->dtype = PLPGSQL_DTYPE_ROW;
2237  row->refname = "(unnamed row)";
2238  row->lineno = -1;
2239  row->varnos = (int *) palloc(sizeof(int) * list_length(funcargs));
2240 
2241  MemoryContextSwitchTo(oldcontext);
2242 
2243  /*
2244  * Examine procedure's argument list. Each output arg position
2245  * should be an unadorned plpgsql variable (Datum), which we can
2246  * insert into the row Datum.
2247  */
2248  nfields = 0;
2249  i = 0;
2250  foreach(lc, funcargs)
2251  {
2252  Node *n = lfirst(lc);
2253 
2254  if (argmodes &&
2255  (argmodes[i] == PROARGMODE_INOUT ||
2256  argmodes[i] == PROARGMODE_OUT))
2257  {
2258  if (IsA(n, Param))
2259  {
2260  Param *param = (Param *) n;
2261 
2262  /* paramid is offset by 1 (see make_datum_param()) */
2263  row->varnos[nfields++] = param->paramid - 1;
2264  }
2265  else
2266  {
2267  /* report error using parameter name, if available */
2268  if (argnames && argnames[i] && argnames[i][0])
2269  ereport(ERROR,
2270  (errcode(ERRCODE_SYNTAX_ERROR),
2271  errmsg("procedure parameter \"%s\" is an output parameter but corresponding argument is not writable",
2272  argnames[i])));
2273  else
2274  ereport(ERROR,
2275  (errcode(ERRCODE_SYNTAX_ERROR),
2276  errmsg("procedure parameter %d is an output parameter but corresponding argument is not writable",
2277  i + 1)));
2278  }
2279  }
2280  i++;
2281  }
2282 
2283  row->nfields = nfields;
2284 
2285  stmt->target = (PLpgSQL_variable *) row;
2286  }
2287 
2288  paramLI = setup_param_list(estate, expr);
2289 
2290  before_lxid = MyProc->lxid;
2291 
2292  /*
2293  * Set snapshot only for non-read-only procedures, similar to SPI
2294  * behavior.
2295  */
2296  if (!estate->readonly_func)
2297  {
2299  pushed_active_snap = true;
2300  }
2301 
2302  rc = SPI_execute_plan_with_paramlist(expr->plan, paramLI,
2303  estate->readonly_func, 0);
2304  }
2305  PG_CATCH();
2306  {
2307  /*
2308  * If we aren't saving the plan, unset the pointer. Note that it
2309  * could have been unset already, in case of a recursive call.
2310  */
2311  if (expr->plan && !expr->plan->saved)
2312  expr->plan = NULL;
2313  PG_RE_THROW();
2314  }
2315  PG_END_TRY();
2316 
2317  if (expr->plan && !expr->plan->saved)
2318  expr->plan = NULL;
2319 
2320  if (rc < 0)
2321  elog(ERROR, "SPI_execute_plan_with_paramlist failed executing query \"%s\": %s",
2322  expr->query, SPI_result_code_string(rc));
2323 
2324  after_lxid = MyProc->lxid;
2325 
2326  if (before_lxid == after_lxid)
2327  {
2328  /*
2329  * If we are still in the same transaction after the call, pop the
2330  * snapshot that we might have pushed. (If it's a new transaction,
2331  * then all the snapshots are gone already.)
2332  */
2333  if (pushed_active_snap)
2335  }
2336  else
2337  {
2338  /*
2339  * If we are in a new transaction after the call, we need to build new
2340  * simple-expression infrastructure.
2341  */
2342  estate->simple_eval_estate = NULL;
2343  estate->simple_eval_resowner = NULL;
2344  plpgsql_create_econtext(estate);
2345  }
2346 
2347  /*
2348  * Check result rowcount; if there's one row, assign procedure's output
2349  * values back to the appropriate variables.
2350  */
2351  if (SPI_processed == 1)
2352  {
2353  SPITupleTable *tuptab = SPI_tuptable;
2354 
2355  if (!stmt->target)
2356  elog(ERROR, "DO statement returned a row");
2357 
2358  exec_move_row(estate, stmt->target, tuptab->vals[0], tuptab->tupdesc);
2359  }
2360  else if (SPI_processed > 1)
2361  elog(ERROR, "procedure call returned more than one row");
2362 
2363  exec_eval_cleanup(estate);
2365 
2366  return PLPGSQL_RC_OK;
2367 }
2368 
2369 /* ----------
2370  * exec_stmt_getdiag Put internal PG information into
2371  * specified variables.
2372  * ----------
2373  */
2374 static int
2376 {
2377  ListCell *lc;
2378 
2379  /*
2380  * GET STACKED DIAGNOSTICS is only valid inside an exception handler.
2381  *
2382  * Note: we trust the grammar to have disallowed the relevant item kinds
2383  * if not is_stacked, otherwise we'd dump core below.
2384  */
2385  if (stmt->is_stacked && estate->cur_error == NULL)
2386  ereport(ERROR,
2387  (errcode(ERRCODE_STACKED_DIAGNOSTICS_ACCESSED_WITHOUT_ACTIVE_HANDLER),
2388  errmsg("GET STACKED DIAGNOSTICS cannot be used outside an exception handler")));
2389 
2390  foreach(lc, stmt->diag_items)
2391  {
2392  PLpgSQL_diag_item *diag_item = (PLpgSQL_diag_item *) lfirst(lc);
2393  PLpgSQL_datum *var = estate->datums[diag_item->target];
2394 
2395  switch (diag_item->kind)
2396  {
2398  exec_assign_value(estate, var,
2399  UInt64GetDatum(estate->eval_processed),
2400  false, INT8OID, -1);
2401  break;
2402 
2404  exec_assign_c_string(estate, var,
2405  estate->cur_error->context);
2406  break;
2407 
2409  exec_assign_c_string(estate, var,
2410  estate->cur_error->detail);
2411  break;
2412 
2414  exec_assign_c_string(estate, var,
2415  estate->cur_error->hint);
2416  break;
2417 
2419  exec_assign_c_string(estate, var,
2421  break;
2422 
2424  exec_assign_c_string(estate, var,
2425  estate->cur_error->column_name);
2426  break;
2427 
2429  exec_assign_c_string(estate, var,
2430  estate->cur_error->constraint_name);
2431  break;
2432 
2434  exec_assign_c_string(estate, var,
2435  estate->cur_error->datatype_name);
2436  break;
2437 
2439  exec_assign_c_string(estate, var,
2440  estate->cur_error->message);
2441  break;
2442 
2444  exec_assign_c_string(estate, var,
2445  estate->cur_error->table_name);
2446  break;
2447 
2449  exec_assign_c_string(estate, var,
2450  estate->cur_error->schema_name);
2451  break;
2452 
2454  {
2455  char *contextstackstr;
2456  MemoryContext oldcontext;
2457 
2458  /* Use eval_mcontext for short-lived string */
2459  oldcontext = MemoryContextSwitchTo(get_eval_mcontext(estate));
2460  contextstackstr = GetErrorContextStack();
2461  MemoryContextSwitchTo(oldcontext);
2462 
2463  exec_assign_c_string(estate, var, contextstackstr);
2464  }
2465  break;
2466 
2467  default:
2468  elog(ERROR, "unrecognized diagnostic item kind: %d",
2469  diag_item->kind);
2470  }
2471  }
2472 
2473  exec_eval_cleanup(estate);
2474 
2475  return PLPGSQL_RC_OK;
2476 }
2477 
2478 /* ----------
2479  * exec_stmt_if Evaluate a bool expression and
2480  * execute the true or false body
2481  * conditionally.
2482  * ----------
2483  */
2484 static int
2486 {
2487  bool value;
2488  bool isnull;
2489  ListCell *lc;
2490 
2491  value = exec_eval_boolean(estate, stmt->cond, &isnull);
2492  exec_eval_cleanup(estate);
2493  if (!isnull && value)
2494  return exec_stmts(estate, stmt->then_body);
2495 
2496  foreach(lc, stmt->elsif_list)
2497  {
2498  PLpgSQL_if_elsif *elif = (PLpgSQL_if_elsif *) lfirst(lc);
2499 
2500  value = exec_eval_boolean(estate, elif->cond, &isnull);
2501  exec_eval_cleanup(estate);
2502  if (!isnull && value)
2503  return exec_stmts(estate, elif->stmts);
2504  }
2505 
2506  return exec_stmts(estate, stmt->else_body);
2507 }
2508 
2509 
2510 /*-----------
2511  * exec_stmt_case
2512  *-----------
2513  */
2514 static int
2516 {
2517  PLpgSQL_var *t_var = NULL;
2518  bool isnull;
2519  ListCell *l;
2520 
2521  if (stmt->t_expr != NULL)
2522  {
2523  /* simple case */
2524  Datum t_val;
2525  Oid t_typoid;
2526  int32 t_typmod;
2527 
2528  t_val = exec_eval_expr(estate, stmt->t_expr,
2529  &isnull, &t_typoid, &t_typmod);
2530 
2531  t_var = (PLpgSQL_var *) estate->datums[stmt->t_varno];
2532 
2533  /*
2534  * When expected datatype is different from real, change it. Note that
2535  * what we're modifying here is an execution copy of the datum, so
2536  * this doesn't affect the originally stored function parse tree. (In
2537  * theory, if the expression datatype keeps changing during execution,
2538  * this could cause a function-lifespan memory leak. Doesn't seem
2539  * worth worrying about though.)
2540  */
2541  if (t_var->datatype->typoid != t_typoid ||
2542  t_var->datatype->atttypmod != t_typmod)
2543  t_var->datatype = plpgsql_build_datatype(t_typoid,
2544  t_typmod,
2545  estate->func->fn_input_collation,
2546  NULL);
2547 
2548  /* now we can assign to the variable */
2549  exec_assign_value(estate,
2550  (PLpgSQL_datum *) t_var,
2551  t_val,
2552  isnull,
2553  t_typoid,
2554  t_typmod);
2555 
2556  exec_eval_cleanup(estate);
2557  }
2558 
2559  /* Now search for a successful WHEN clause */
2560  foreach(l, stmt->case_when_list)
2561  {
2563  bool value;
2564 
2565  value = exec_eval_boolean(estate, cwt->expr, &isnull);
2566  exec_eval_cleanup(estate);
2567  if (!isnull && value)
2568  {
2569  /* Found it */
2570 
2571  /* We can now discard any value we had for the temp variable */
2572  if (t_var != NULL)
2573  assign_simple_var(estate, t_var, (Datum) 0, true, false);
2574 
2575  /* Evaluate the statement(s), and we're done */
2576  return exec_stmts(estate, cwt->stmts);
2577  }
2578  }
2579 
2580  /* We can now discard any value we had for the temp variable */
2581  if (t_var != NULL)
2582  assign_simple_var(estate, t_var, (Datum) 0, true, false);
2583 
2584  /* SQL2003 mandates this error if there was no ELSE clause */
2585  if (!stmt->have_else)
2586  ereport(ERROR,
2587  (errcode(ERRCODE_CASE_NOT_FOUND),
2588  errmsg("case not found"),
2589  errhint("CASE statement is missing ELSE part.")));
2590 
2591  /* Evaluate the ELSE statements, and we're done */
2592  return exec_stmts(estate, stmt->else_stmts);
2593 }
2594 
2595 
2596 /* ----------
2597  * exec_stmt_loop Loop over statements until
2598  * an exit occurs.
2599  * ----------
2600  */
2601 static int
2603 {
2604  int rc = PLPGSQL_RC_OK;
2605 
2606  for (;;)
2607  {
2608  rc = exec_stmts(estate, stmt->body);
2609 
2610  LOOP_RC_PROCESSING(stmt->label, break);
2611  }
2612 
2613  return rc;
2614 }
2615 
2616 
2617 /* ----------
2618  * exec_stmt_while Loop over statements as long
2619  * as an expression evaluates to
2620  * true or an exit occurs.
2621  * ----------
2622  */
2623 static int
2625 {
2626  int rc = PLPGSQL_RC_OK;
2627 
2628  for (;;)
2629  {
2630  bool value;
2631  bool isnull;
2632 
2633  value = exec_eval_boolean(estate, stmt->cond, &isnull);
2634  exec_eval_cleanup(estate);
2635 
2636  if (isnull || !value)
2637  break;
2638 
2639  rc = exec_stmts(estate, stmt->body);
2640 
2641  LOOP_RC_PROCESSING(stmt->label, break);
2642  }
2643 
2644  return rc;
2645 }
2646 
2647 
2648 /* ----------
2649  * exec_stmt_fori Iterate an integer variable
2650  * from a lower to an upper value
2651  * incrementing or decrementing by the BY value
2652  * ----------
2653  */
2654 static int
2656 {
2657  PLpgSQL_var *var;
2658  Datum value;
2659  bool isnull;
2660  Oid valtype;
2661  int32 valtypmod;
2662  int32 loop_value;
2663  int32 end_value;
2664  int32 step_value;
2665  bool found = false;
2666  int rc = PLPGSQL_RC_OK;
2667 
2668  var = (PLpgSQL_var *) (estate->datums[stmt->var->dno]);
2669 
2670  /*
2671  * Get the value of the lower bound
2672  */
2673  value = exec_eval_expr(estate, stmt->lower,
2674  &isnull, &valtype, &valtypmod);
2675  value = exec_cast_value(estate, value, &isnull,
2676  valtype, valtypmod,
2677  var->datatype->typoid,
2678  var->datatype->atttypmod);
2679  if (isnull)
2680  ereport(ERROR,
2681  (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
2682  errmsg("lower bound of FOR loop cannot be null")));
2683  loop_value = DatumGetInt32(value);
2684  exec_eval_cleanup(estate);
2685 
2686  /*
2687  * Get the value of the upper bound
2688  */
2689  value = exec_eval_expr(estate, stmt->upper,
2690  &isnull, &valtype, &valtypmod);
2691  value = exec_cast_value(estate, value, &isnull,
2692  valtype, valtypmod,
2693  var->datatype->typoid,
2694  var->datatype->atttypmod);
2695  if (isnull)
2696  ereport(ERROR,
2697  (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
2698  errmsg("upper bound of FOR loop cannot be null")));
2699  end_value = DatumGetInt32(value);
2700  exec_eval_cleanup(estate);
2701 
2702  /*
2703  * Get the step value
2704  */
2705  if (stmt->step)
2706  {
2707  value = exec_eval_expr(estate, stmt->step,
2708  &isnull, &valtype, &valtypmod);
2709  value = exec_cast_value(estate, value, &isnull,
2710  valtype, valtypmod,
2711  var->datatype->typoid,
2712  var->datatype->atttypmod);
2713  if (isnull)
2714  ereport(ERROR,
2715  (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
2716  errmsg("BY value of FOR loop cannot be null")));
2717  step_value = DatumGetInt32(value);
2718  exec_eval_cleanup(estate);
2719  if (step_value <= 0)
2720  ereport(ERROR,
2721  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
2722  errmsg("BY value of FOR loop must be greater than zero")));
2723  }
2724  else
2725  step_value = 1;
2726 
2727  /*
2728  * Now do the loop
2729  */
2730  for (;;)
2731  {
2732  /*
2733  * Check against upper bound
2734  */
2735  if (stmt->reverse)
2736  {
2737  if (loop_value < end_value)
2738  break;
2739  }
2740  else
2741  {
2742  if (loop_value > end_value)
2743  break;
2744  }
2745 
2746  found = true; /* looped at least once */
2747 
2748  /*
2749  * Assign current value to loop var
2750  */
2751  assign_simple_var(estate, var, Int32GetDatum(loop_value), false, false);
2752 
2753  /*
2754  * Execute the statements
2755  */
2756  rc = exec_stmts(estate, stmt->body);
2757 
2758  LOOP_RC_PROCESSING(stmt->label, break);
2759 
2760  /*
2761  * Increase/decrease loop value, unless it would overflow, in which
2762  * case exit the loop.
2763  */
2764  if (stmt->reverse)
2765  {
2766  if (loop_value < (PG_INT32_MIN + step_value))
2767  break;
2768  loop_value -= step_value;
2769  }
2770  else
2771  {
2772  if (loop_value > (PG_INT32_MAX - step_value))
2773  break;
2774  loop_value += step_value;
2775  }
2776  }
2777 
2778  /*
2779  * Set the FOUND variable to indicate the result of executing the loop
2780  * (namely, whether we looped one or more times). This must be set here so
2781  * that it does not interfere with the value of the FOUND variable inside
2782  * the loop processing itself.
2783  */
2784  exec_set_found(estate, found);
2785 
2786  return rc;
2787 }
2788 
2789 
2790 /* ----------
2791  * exec_stmt_fors Execute a query, assign each
2792  * tuple to a record or row and
2793  * execute a group of statements
2794  * for it.
2795  * ----------
2796  */
2797 static int
2799 {
2800  Portal portal;
2801  int rc;
2802 
2803  /*
2804  * Open the implicit cursor for the statement using exec_run_select
2805  */
2806  exec_run_select(estate, stmt->query, 0, &portal);
2807 
2808  /*
2809  * Execute the loop
2810  */
2811  rc = exec_for_query(estate, (PLpgSQL_stmt_forq *) stmt, portal, true);
2812 
2813  /*
2814  * Close the implicit cursor
2815  */
2816  SPI_cursor_close(portal);
2817 
2818  return rc;
2819 }
2820 
2821 
2822 /* ----------
2823  * exec_stmt_forc Execute a loop for each row from a cursor.
2824  * ----------
2825  */
2826 static int
2828 {
2829  PLpgSQL_var *curvar;
2830  MemoryContext stmt_mcontext = NULL;
2831  char *curname = NULL;
2832  PLpgSQL_expr *query;
2833  ParamListInfo paramLI;
2834  Portal portal;
2835  int rc;
2836 
2837  /* ----------
2838  * Get the cursor variable and if it has an assigned name, check
2839  * that it's not in use currently.
2840  * ----------
2841  */
2842  curvar = (PLpgSQL_var *) (estate->datums[stmt->curvar]);
2843  if (!curvar->isnull)
2844  {
2845  MemoryContext oldcontext;
2846 
2847  /* We only need stmt_mcontext to hold the cursor name string */
2848  stmt_mcontext = get_stmt_mcontext(estate);
2849  oldcontext = MemoryContextSwitchTo(stmt_mcontext);
2850  curname = TextDatumGetCString(curvar->value);
2851  MemoryContextSwitchTo(oldcontext);
2852 
2853  if (SPI_cursor_find(curname) != NULL)
2854  ereport(ERROR,
2855  (errcode(ERRCODE_DUPLICATE_CURSOR),
2856  errmsg("cursor \"%s\" already in use", curname)));
2857  }
2858 
2859  /* ----------
2860  * Open the cursor just like an OPEN command
2861  *
2862  * Note: parser should already have checked that statement supplies
2863  * args iff cursor needs them, but we check again to be safe.
2864  * ----------
2865  */
2866  if (stmt->argquery != NULL)
2867  {
2868  /* ----------
2869  * OPEN CURSOR with args. We fake a SELECT ... INTO ...
2870  * statement to evaluate the args and put 'em into the
2871  * internal row.
2872  * ----------
2873  */
2874  PLpgSQL_stmt_execsql set_args;
2875 
2876  if (curvar->cursor_explicit_argrow < 0)
2877  ereport(ERROR,
2878  (errcode(ERRCODE_SYNTAX_ERROR),
2879  errmsg("arguments given for cursor without arguments")));
2880 
2881  memset(&set_args, 0, sizeof(set_args));
2882  set_args.cmd_type = PLPGSQL_STMT_EXECSQL;
2883  set_args.lineno = stmt->lineno;
2884  set_args.sqlstmt = stmt->argquery;
2885  set_args.into = true;
2886  /* XXX historically this has not been STRICT */
2887  set_args.target = (PLpgSQL_variable *)
2888  (estate->datums[curvar->cursor_explicit_argrow]);
2889 
2890  if (exec_stmt_execsql(estate, &set_args) != PLPGSQL_RC_OK)
2891  elog(ERROR, "open cursor failed during argument processing");
2892  }
2893  else
2894  {
2895  if (curvar->cursor_explicit_argrow >= 0)
2896  ereport(ERROR,
2897  (errcode(ERRCODE_SYNTAX_ERROR),
2898  errmsg("arguments required for cursor")));
2899  }
2900 
2901  query = curvar->cursor_explicit_expr;
2902  Assert(query);
2903 
2904  if (query->plan == NULL)
2905  exec_prepare_plan(estate, query, curvar->cursor_options, true);
2906 
2907  /*
2908  * Set up ParamListInfo for this query
2909  */
2910  paramLI = setup_param_list(estate, query);
2911 
2912  /*
2913  * Open the cursor (the paramlist will get copied into the portal)
2914  */
2915  portal = SPI_cursor_open_with_paramlist(curname, query->plan,
2916  paramLI,
2917  estate->readonly_func);
2918  if (portal == NULL)
2919  elog(ERROR, "could not open cursor: %s",
2921 
2922  /*
2923  * If cursor variable was NULL, store the generated portal name in it
2924  */
2925  if (curname == NULL)
2926  assign_text_var(estate, curvar, portal->name);
2927 
2928  /*
2929  * Clean up before entering exec_for_query
2930  */
2931  exec_eval_cleanup(estate);
2932  if (stmt_mcontext)
2933  MemoryContextReset(stmt_mcontext);
2934 
2935  /*
2936  * Execute the loop. We can't prefetch because the cursor is accessible
2937  * to the user, for instance via UPDATE WHERE CURRENT OF within the loop.
2938  */
2939  rc = exec_for_query(estate, (PLpgSQL_stmt_forq *) stmt, portal, false);
2940 
2941  /* ----------
2942  * Close portal, and restore cursor variable if it was initially NULL.
2943  * ----------
2944  */
2945  SPI_cursor_close(portal);
2946 
2947  if (curname == NULL)
2948  assign_simple_var(estate, curvar, (Datum) 0, true, false);
2949 
2950  return rc;
2951 }
2952 
2953 
2954 /* ----------
2955  * exec_stmt_foreach_a Loop over elements or slices of an array
2956  *
2957  * When looping over elements, the loop variable is the same type that the
2958  * array stores (eg: integer), when looping through slices, the loop variable
2959  * is an array of size and dimensions to match the size of the slice.
2960  * ----------
2961  */
2962 static int
2964 {
2965  ArrayType *arr;
2966  Oid arrtype;
2967  int32 arrtypmod;
2968  PLpgSQL_datum *loop_var;
2969  Oid loop_var_elem_type;
2970  bool found = false;
2971  int rc = PLPGSQL_RC_OK;
2972  MemoryContext stmt_mcontext;
2973  MemoryContext oldcontext;
2975  Oid iterator_result_type;
2976  int32 iterator_result_typmod;
2977  Datum value;
2978  bool isnull;
2979 
2980  /* get the value of the array expression */
2981  value = exec_eval_expr(estate, stmt->expr, &isnull, &arrtype, &arrtypmod);
2982  if (isnull)
2983  ereport(ERROR,
2984  (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
2985  errmsg("FOREACH expression must not be null")));
2986 
2987  /*
2988  * Do as much as possible of the code below in stmt_mcontext, to avoid any
2989  * leaks from called subroutines. We need a private stmt_mcontext since
2990  * we'll be calling arbitrary statement code.
2991  */
2992  stmt_mcontext = get_stmt_mcontext(estate);
2993  push_stmt_mcontext(estate);
2994  oldcontext = MemoryContextSwitchTo(stmt_mcontext);
2995 
2996  /* check the type of the expression - must be an array */
2997  if (!OidIsValid(get_element_type(arrtype)))
2998  ereport(ERROR,
2999  (errcode(ERRCODE_DATATYPE_MISMATCH),
3000  errmsg("FOREACH expression must yield an array, not type %s",
3001  format_type_be(arrtype))));
3002 
3003  /*
3004  * We must copy the array into stmt_mcontext, else it will disappear in
3005  * exec_eval_cleanup. This is annoying, but cleanup will certainly happen
3006  * while running the loop body, so we have little choice.
3007  */
3008  arr = DatumGetArrayTypePCopy(value);
3009 
3010  /* Clean up any leftover temporary memory */
3011  exec_eval_cleanup(estate);
3012 
3013  /* Slice dimension must be less than or equal to array dimension */
3014  if (stmt->slice < 0 || stmt->slice > ARR_NDIM(arr))
3015  ereport(ERROR,
3016  (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
3017  errmsg("slice dimension (%d) is out of the valid range 0..%d",
3018  stmt->slice, ARR_NDIM(arr))));
3019 
3020  /* Set up the loop variable and see if it is of an array type */
3021  loop_var = estate->datums[stmt->varno];
3022  if (loop_var->dtype == PLPGSQL_DTYPE_REC ||
3023  loop_var->dtype == PLPGSQL_DTYPE_ROW)
3024  {
3025  /*
3026  * Record/row variable is certainly not of array type, and might not
3027  * be initialized at all yet, so don't try to get its type
3028  */
3029  loop_var_elem_type = InvalidOid;
3030  }
3031  else
3032  loop_var_elem_type = get_element_type(plpgsql_exec_get_datum_type(estate,
3033  loop_var));
3034 
3035  /*
3036  * Sanity-check the loop variable type. We don't try very hard here, and
3037  * should not be too picky since it's possible that exec_assign_value can
3038  * coerce values of different types. But it seems worthwhile to complain
3039  * if the array-ness of the loop variable is not right.
3040  */
3041  if (stmt->slice > 0 && loop_var_elem_type == InvalidOid)
3042  ereport(ERROR,
3043  (errcode(ERRCODE_DATATYPE_MISMATCH),
3044  errmsg("FOREACH ... SLICE loop variable must be of an array type")));
3045  if (stmt->slice == 0 && loop_var_elem_type != InvalidOid)
3046  ereport(ERROR,
3047  (errcode(ERRCODE_DATATYPE_MISMATCH),
3048  errmsg("FOREACH loop variable must not be of an array type")));
3049 
3050  /* Create an iterator to step through the array */
3051  array_iterator = array_create_iterator(arr, stmt->slice, NULL);
3052 
3053  /* Identify iterator result type */
3054  if (stmt->slice > 0)
3055  {
3056  /* When slicing, nominal type of result is same as array type */
3057  iterator_result_type = arrtype;
3058  iterator_result_typmod = arrtypmod;
3059  }
3060  else
3061  {
3062  /* Without slicing, results are individual array elements */
3063  iterator_result_type = ARR_ELEMTYPE(arr);
3064  iterator_result_typmod = arrtypmod;
3065  }
3066 
3067  /* Iterate over the array elements or slices */
3068  while (array_iterate(array_iterator, &value, &isnull))
3069  {
3070  found = true; /* looped at least once */
3071 
3072  /* exec_assign_value and exec_stmts must run in the main context */
3073  MemoryContextSwitchTo(oldcontext);
3074 
3075  /* Assign current element/slice to the loop variable */
3076  exec_assign_value(estate, loop_var, value, isnull,
3077  iterator_result_type, iterator_result_typmod);
3078 
3079  /* In slice case, value is temporary; must free it to avoid leakage */
3080  if (stmt->slice > 0)
3081  pfree(DatumGetPointer(value));
3082 
3083  /*
3084  * Execute the statements
3085  */
3086  rc = exec_stmts(estate, stmt->body);
3087 
3088  LOOP_RC_PROCESSING(stmt->label, break);
3089 
3090  MemoryContextSwitchTo(stmt_mcontext);
3091  }
3092 
3093  /* Restore memory context state */
3094  MemoryContextSwitchTo(oldcontext);
3095  pop_stmt_mcontext(estate);
3096 
3097  /* Release temporary memory, including the array value */
3098  MemoryContextReset(stmt_mcontext);
3099 
3100  /*
3101  * Set the FOUND variable to indicate the result of executing the loop
3102  * (namely, whether we looped one or more times). This must be set here so
3103  * that it does not interfere with the value of the FOUND variable inside
3104  * the loop processing itself.
3105  */
3106  exec_set_found(estate, found);
3107 
3108  return rc;
3109 }
3110 
3111 
3112 /* ----------
3113  * exec_stmt_exit Implements EXIT and CONTINUE
3114  *
3115  * This begins the process of exiting / restarting a loop.
3116  * ----------
3117  */
3118 static int
3120 {
3121  /*
3122  * If the exit / continue has a condition, evaluate it
3123  */
3124  if (stmt->cond != NULL)
3125  {
3126  bool value;
3127  bool isnull;
3128 
3129  value = exec_eval_boolean(estate, stmt->cond, &isnull);
3130  exec_eval_cleanup(estate);
3131  if (isnull || value == false)
3132  return PLPGSQL_RC_OK;
3133  }
3134 
3135  estate->exitlabel = stmt->label;
3136  if (stmt->is_exit)
3137  return PLPGSQL_RC_EXIT;
3138  else
3139  return PLPGSQL_RC_CONTINUE;
3140 }
3141 
3142 
3143 /* ----------
3144  * exec_stmt_return Evaluate an expression and start
3145  * returning from the function.
3146  *
3147  * Note: The result may be in the eval_mcontext. Therefore, we must not
3148  * do exec_eval_cleanup while unwinding the control stack.
3149  * ----------
3150  */
3151 static int
3153 {
3154  /*
3155  * If processing a set-returning PL/pgSQL function, the final RETURN
3156  * indicates that the function is finished producing tuples. The rest of
3157  * the work will be done at the top level.
3158  */
3159  if (estate->retisset)
3160  return PLPGSQL_RC_RETURN;
3161 
3162  /* initialize for null result */
3163  estate->retval = (Datum) 0;
3164  estate->retisnull = true;
3165  estate->rettype = InvalidOid;
3166 
3167  /*
3168  * Special case path when the RETURN expression is a simple variable
3169  * reference; in particular, this path is always taken in functions with
3170  * one or more OUT parameters.
3171  *
3172  * This special case is especially efficient for returning variables that
3173  * have R/W expanded values: we can put the R/W pointer directly into
3174  * estate->retval, leading to transferring the value to the caller's
3175  * context cheaply. If we went through exec_eval_expr we'd end up with a
3176  * R/O pointer. It's okay to skip MakeExpandedObjectReadOnly here since
3177  * we know we won't need the variable's value within the function anymore.
3178  */
3179  if (stmt->retvarno >= 0)
3180  {
3181  PLpgSQL_datum *retvar = estate->datums[stmt->retvarno];
3182 
3183  switch (retvar->dtype)
3184  {
3185  case PLPGSQL_DTYPE_PROMISE:
3186  /* fulfill promise if needed, then handle like regular var */
3187  plpgsql_fulfill_promise(estate, (PLpgSQL_var *) retvar);
3188 
3189  /* FALL THRU */
3190 
3191  case PLPGSQL_DTYPE_VAR:
3192  {
3193  PLpgSQL_var *var = (PLpgSQL_var *) retvar;
3194 
3195  estate->retval = var->value;
3196  estate->retisnull = var->isnull;
3197  estate->rettype = var->datatype->typoid;
3198 
3199  /*
3200  * A PLpgSQL_var could not be of composite type, so
3201  * conversion must fail if retistuple. We throw a custom
3202  * error mainly for consistency with historical behavior.
3203  * For the same reason, we don't throw error if the result
3204  * is NULL. (Note that plpgsql_exec_trigger assumes that
3205  * any non-null result has been verified to be composite.)
3206  */
3207  if (estate->retistuple && !estate->retisnull)
3208  ereport(ERROR,
3209  (errcode(ERRCODE_DATATYPE_MISMATCH),
3210  errmsg("cannot return non-composite value from function returning composite type")));
3211  }
3212  break;
3213 
3214  case PLPGSQL_DTYPE_REC:
3215  {
3216  PLpgSQL_rec *rec = (PLpgSQL_rec *) retvar;
3217 
3218  /* If record is empty, we return NULL not a row of nulls */
3219  if (rec->erh && !ExpandedRecordIsEmpty(rec->erh))
3220  {
3221  estate->retval = ExpandedRecordGetDatum(rec->erh);
3222  estate->retisnull = false;
3223  estate->rettype = rec->rectypeid;
3224  }
3225  }
3226  break;
3227 
3228  case PLPGSQL_DTYPE_ROW:
3229  {
3230  PLpgSQL_row *row = (PLpgSQL_row *) retvar;
3231  int32 rettypmod;
3232 
3233  /* We get here if there are multiple OUT parameters */
3234  exec_eval_datum(estate,
3235  (PLpgSQL_datum *) row,
3236  &estate->rettype,
3237  &rettypmod,
3238  &estate->retval,
3239  &estate->retisnull);
3240  }
3241  break;
3242 
3243  default:
3244  elog(ERROR, "unrecognized dtype: %d", retvar->dtype);
3245  }
3246 
3247  return PLPGSQL_RC_RETURN;
3248  }
3249 
3250  if (stmt->expr != NULL)
3251  {
3252  int32 rettypmod;
3253 
3254  estate->retval = exec_eval_expr(estate, stmt->expr,
3255  &(estate->retisnull),
3256  &(estate->rettype),
3257  &rettypmod);
3258 
3259  /*
3260  * As in the DTYPE_VAR case above, throw a custom error if a non-null,
3261  * non-composite value is returned in a function returning tuple.
3262  */
3263  if (estate->retistuple && !estate->retisnull &&
3264  !type_is_rowtype(estate->rettype))
3265  ereport(ERROR,
3266  (errcode(ERRCODE_DATATYPE_MISMATCH),
3267  errmsg("cannot return non-composite value from function returning composite type")));
3268 
3269  return PLPGSQL_RC_RETURN;
3270  }
3271 
3272  /*
3273  * Special hack for function returning VOID: instead of NULL, return a
3274  * non-null VOID value. This is of dubious importance but is kept for
3275  * backwards compatibility. We don't do it for procedures, though.
3276  */
3277  if (estate->fn_rettype == VOIDOID &&
3278  estate->func->fn_prokind != PROKIND_PROCEDURE)
3279  {
3280  estate->retval = (Datum) 0;
3281  estate->retisnull = false;
3282  estate->rettype = VOIDOID;
3283  }
3284 
3285  return PLPGSQL_RC_RETURN;
3286 }
3287 
3288 /* ----------
3289  * exec_stmt_return_next Evaluate an expression and add it to the
3290  * list of tuples returned by the current
3291  * SRF.
3292  * ----------
3293  */
3294 static int
3297 {
3298  TupleDesc tupdesc;
3299  int natts;
3300  HeapTuple tuple;
3301  MemoryContext oldcontext;
3302 
3303  if (!estate->retisset)
3304  ereport(ERROR,
3305  (errcode(ERRCODE_SYNTAX_ERROR),
3306  errmsg("cannot use RETURN NEXT in a non-SETOF function")));
3307 
3308  if (estate->tuple_store == NULL)
3309  exec_init_tuple_store(estate);
3310 
3311  /* tuple_store_desc will be filled by exec_init_tuple_store */
3312  tupdesc = estate->tuple_store_desc;
3313  natts = tupdesc->natts;
3314 
3315  /*
3316  * Special case path when the RETURN NEXT expression is a simple variable
3317  * reference; in particular, this path is always taken in functions with
3318  * one or more OUT parameters.
3319  *
3320  * Unlike exec_stmt_return, there's no special win here for R/W expanded
3321  * values, since they'll have to get flattened to go into the tuplestore.
3322  * Indeed, we'd better make them R/O to avoid any risk of the casting step
3323  * changing them in-place.
3324  */
3325  if (stmt->retvarno >= 0)
3326  {
3327  PLpgSQL_datum *retvar = estate->datums[stmt->retvarno];
3328 
3329  switch (retvar->dtype)
3330  {
3331  case PLPGSQL_DTYPE_PROMISE:
3332  /* fulfill promise if needed, then handle like regular var */
3333  plpgsql_fulfill_promise(estate, (PLpgSQL_var *) retvar);
3334 
3335  /* FALL THRU */
3336 
3337  case PLPGSQL_DTYPE_VAR:
3338  {
3339  PLpgSQL_var *var = (PLpgSQL_var *) retvar;
3340  Datum retval = var->value;
3341  bool isNull = var->isnull;
3342  Form_pg_attribute attr = TupleDescAttr(tupdesc, 0);
3343 
3344  if (natts != 1)
3345  ereport(ERROR,
3346  (errcode(ERRCODE_DATATYPE_MISMATCH),
3347  errmsg("wrong result type supplied in RETURN NEXT")));
3348 
3349  /* let's be very paranoid about the cast step */
3350  retval = MakeExpandedObjectReadOnly(retval,
3351  isNull,
3352  var->datatype->typlen);
3353 
3354  /* coerce type if needed */
3355  retval = exec_cast_value(estate,
3356  retval,
3357  &isNull,
3358  var->datatype->typoid,
3359  var->datatype->atttypmod,
3360  attr->atttypid,
3361  attr->atttypmod);
3362 
3363  tuplestore_putvalues(estate->tuple_store, tupdesc,
3364  &retval, &isNull);
3365  }
3366  break;
3367 
3368  case PLPGSQL_DTYPE_REC:
3369  {
3370  PLpgSQL_rec *rec = (PLpgSQL_rec *) retvar;
3371  TupleDesc rec_tupdesc;
3372  TupleConversionMap *tupmap;
3373 
3374  /* If rec is null, try to convert it to a row of nulls */
3375  if (rec->erh == NULL)
3376  instantiate_empty_record_variable(estate, rec);
3377  if (ExpandedRecordIsEmpty(rec->erh))
3379 
3380  /* Use eval_mcontext for tuple conversion work */
3381  oldcontext = MemoryContextSwitchTo(get_eval_mcontext(estate));
3382  rec_tupdesc = expanded_record_get_tupdesc(rec->erh);
3383  tupmap = convert_tuples_by_position(rec_tupdesc,
3384  tupdesc,
3385  gettext_noop("wrong record type supplied in RETURN NEXT"));
3386  tuple = expanded_record_get_tuple(rec->erh);
3387  if (tupmap)
3388  tuple = execute_attr_map_tuple(tuple, tupmap);
3389  tuplestore_puttuple(estate->tuple_store, tuple);
3390  MemoryContextSwitchTo(oldcontext);
3391  }
3392  break;
3393 
3394  case PLPGSQL_DTYPE_ROW:
3395  {
3396  PLpgSQL_row *row = (PLpgSQL_row *) retvar;
3397 
3398  /* We get here if there are multiple OUT parameters */
3399 
3400  /* Use eval_mcontext for tuple conversion work */
3401  oldcontext = MemoryContextSwitchTo(get_eval_mcontext(estate));
3402  tuple = make_tuple_from_row(estate, row, tupdesc);
3403  if (tuple == NULL) /* should not happen */
3404  ereport(ERROR,
3405  (errcode(ERRCODE_DATATYPE_MISMATCH),
3406  errmsg("wrong record type supplied in RETURN NEXT")));
3407  tuplestore_puttuple(estate->tuple_store, tuple);
3408  MemoryContextSwitchTo(oldcontext);
3409  }
3410  break;
3411 
3412  default:
3413  elog(ERROR, "unrecognized dtype: %d", retvar->dtype);
3414  break;
3415  }
3416  }
3417  else if (stmt->expr)
3418  {
3419  Datum retval;
3420  bool isNull;
3421  Oid rettype;
3422  int32 rettypmod;
3423 
3424  retval = exec_eval_expr(estate,
3425  stmt->expr,
3426  &isNull,
3427  &rettype,
3428  &rettypmod);
3429 
3430  if (estate->retistuple)
3431  {
3432  /* Expression should be of RECORD or composite type */
3433  if (!isNull)
3434  {
3435  HeapTupleData tmptup;
3436  TupleDesc retvaldesc;
3437  TupleConversionMap *tupmap;
3438 
3439  if (!type_is_rowtype(rettype))
3440  ereport(ERROR,
3441  (errcode(ERRCODE_DATATYPE_MISMATCH),
3442  errmsg("cannot return non-composite value from function returning composite type")));
3443 
3444  /* Use eval_mcontext for tuple conversion work */
3445  oldcontext = MemoryContextSwitchTo(get_eval_mcontext(estate));
3446  retvaldesc = deconstruct_composite_datum(retval, &tmptup);
3447  tuple = &tmptup;
3448  tupmap = convert_tuples_by_position(retvaldesc, tupdesc,
3449  gettext_noop("returned record type does not match expected record type"));
3450  if (tupmap)
3451  tuple = execute_attr_map_tuple(tuple, tupmap);
3452  tuplestore_puttuple(estate->tuple_store, tuple);
3453  ReleaseTupleDesc(retvaldesc);
3454  MemoryContextSwitchTo(oldcontext);
3455  }
3456  else
3457  {
3458  /* Composite NULL --- store a row of nulls */
3459  Datum *nulldatums;
3460  bool *nullflags;
3461 
3462  nulldatums = (Datum *)
3463  eval_mcontext_alloc0(estate, natts * sizeof(Datum));
3464  nullflags = (bool *)
3465  eval_mcontext_alloc(estate, natts * sizeof(bool));
3466  memset(nullflags, true, natts * sizeof(bool));
3467  tuplestore_putvalues(estate->tuple_store, tupdesc,
3468  nulldatums, nullflags);
3469  }
3470  }
3471  else
3472  {
3473  Form_pg_attribute attr = TupleDescAttr(tupdesc, 0);
3474 
3475  /* Simple scalar result */
3476  if (natts != 1)
3477  ereport(ERROR,
3478  (errcode(ERRCODE_DATATYPE_MISMATCH),
3479  errmsg("wrong result type supplied in RETURN NEXT")));
3480 
3481  /* coerce type if needed */
3482  retval = exec_cast_value(estate,
3483  retval,
3484  &isNull,
3485  rettype,
3486  rettypmod,
3487  attr->atttypid,
3488  attr->atttypmod);
3489 
3490  tuplestore_putvalues(estate->tuple_store, tupdesc,
3491  &retval, &isNull);
3492  }
3493  }
3494  else
3495  {
3496  ereport(ERROR,
3497  (errcode(ERRCODE_SYNTAX_ERROR),
3498  errmsg("RETURN NEXT must have a parameter")));
3499  }
3500 
3501  exec_eval_cleanup(estate);
3502 
3503  return PLPGSQL_RC_OK;
3504 }
3505 
3506 /* ----------
3507  * exec_stmt_return_query Evaluate a query and add it to the
3508  * list of tuples returned by the current
3509  * SRF.
3510  * ----------
3511  */
3512 static int
3515 {
3516  Portal portal;
3517  uint64 processed = 0;
3518  TupleConversionMap *tupmap;
3519  MemoryContext oldcontext;
3520 
3521  if (!estate->retisset)
3522  ereport(ERROR,
3523  (errcode(ERRCODE_SYNTAX_ERROR),
3524  errmsg("cannot use RETURN QUERY in a non-SETOF function")));
3525 
3526  if (estate->tuple_store == NULL)
3527  exec_init_tuple_store(estate);
3528 
3529  if (stmt->query != NULL)
3530  {
3531  /* static query */
3532  exec_run_select(estate, stmt->query, 0, &portal);
3533  }
3534  else
3535  {
3536  /* RETURN QUERY EXECUTE */
3537  Assert(stmt->dynquery != NULL);
3538  portal = exec_dynquery_with_params(estate, stmt->dynquery,
3539  stmt->params, NULL,
3540  0);
3541  }
3542 
3543  /* Use eval_mcontext for tuple conversion work */
3544  oldcontext = MemoryContextSwitchTo(get_eval_mcontext(estate));
3545 
3546  tupmap = convert_tuples_by_position(portal->tupDesc,
3547  estate->tuple_store_desc,
3548  gettext_noop("structure of query does not match function result type"));
3549 
3550  while (true)
3551  {
3552  uint64 i;
3553 
3554  SPI_cursor_fetch(portal, true, 50);
3555 
3556  /* SPI will have changed CurrentMemoryContext */
3558 
3559  if (SPI_processed == 0)
3560  break;
3561 
3562  for (i = 0; i < SPI_processed; i++)
3563  {
3564  HeapTuple tuple = SPI_tuptable->vals[i];
3565 
3566  if (tupmap)
3567  tuple = execute_attr_map_tuple(tuple, tupmap);
3568  tuplestore_puttuple(estate->tuple_store, tuple);
3569  if (tupmap)
3570  heap_freetuple(tuple);
3571  processed++;
3572  }
3573 
3575  }
3576 
3578  SPI_cursor_close(portal);
3579 
3580  MemoryContextSwitchTo(oldcontext);
3581  exec_eval_cleanup(estate);
3582 
3583  estate->eval_processed = processed;
3584  exec_set_found(estate, processed != 0);
3585 
3586  return PLPGSQL_RC_OK;
3587 }
3588 
3589 static void
3591 {
3592  ReturnSetInfo *rsi = estate->rsi;
3593  MemoryContext oldcxt;
3594  ResourceOwner oldowner;
3595 
3596  /*
3597  * Check caller can handle a set result in the way we want
3598  */
3599  if (!rsi || !IsA(rsi, ReturnSetInfo) ||
3600  (rsi->allowedModes & SFRM_Materialize) == 0 ||
3601  rsi->expectedDesc == NULL)
3602  ereport(ERROR,
3603  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3604  errmsg("set-valued function called in context that cannot accept a set")));
3605 
3606  /*
3607  * Switch to the right memory context and resource owner for storing the
3608  * tuplestore for return set. If we're within a subtransaction opened for
3609  * an exception-block, for example, we must still create the tuplestore in
3610  * the resource owner that was active when this function was entered, and
3611  * not in the subtransaction resource owner.
3612  */
3613  oldcxt = MemoryContextSwitchTo(estate->tuple_store_cxt);
3614  oldowner = CurrentResourceOwner;
3616 
3617  estate->tuple_store =
3619  false, work_mem);
3620 
3621  CurrentResourceOwner = oldowner;
3622  MemoryContextSwitchTo(oldcxt);
3623 
3624  estate->tuple_store_desc = rsi->expectedDesc;
3625 }
3626 
3627 #define SET_RAISE_OPTION_TEXT(opt, name) \
3628 do { \
3629  if (opt) \
3630  ereport(ERROR, \
3631  (errcode(ERRCODE_SYNTAX_ERROR), \
3632  errmsg("RAISE option already specified: %s", \
3633  name))); \
3634  opt = MemoryContextStrdup(stmt_mcontext, extval); \
3635 } while (0)
3636 
3637 /* ----------
3638  * exec_stmt_raise Build a message and throw it with elog()
3639  * ----------
3640  */
3641 static int
3643 {
3644  int err_code = 0;
3645  char *condname = NULL;
3646  char *err_message = NULL;
3647  char *err_detail = NULL;
3648  char *err_hint = NULL;
3649  char *err_column = NULL;
3650  char *err_constraint = NULL;
3651  char *err_datatype = NULL;
3652  char *err_table = NULL;
3653  char *err_schema = NULL;
3654  MemoryContext stmt_mcontext;
3655  ListCell *lc;
3656 
3657  /* RAISE with no parameters: re-throw current exception */
3658  if (stmt->condname == NULL && stmt->message == NULL &&
3659  stmt->options == NIL)
3660  {
3661  if (estate->cur_error != NULL)
3662  ReThrowError(estate->cur_error);
3663  /* oops, we're not inside a handler */
3664  ereport(ERROR,
3665  (errcode(ERRCODE_STACKED_DIAGNOSTICS_ACCESSED_WITHOUT_ACTIVE_HANDLER),
3666  errmsg("RAISE without parameters cannot be used outside an exception handler")));
3667  }
3668 
3669  /* We'll need to accumulate the various strings in stmt_mcontext */
3670  stmt_mcontext = get_stmt_mcontext(estate);
3671 
3672  if (stmt->condname)
3673  {
3674  err_code = plpgsql_recognize_err_condition(stmt->condname, true);
3675  condname = MemoryContextStrdup(stmt_mcontext, stmt->condname);
3676  }
3677 
3678  if (stmt->message)
3679  {
3680  StringInfoData ds;
3681  ListCell *current_param;
3682  char *cp;
3683  MemoryContext oldcontext;
3684 
3685  /* build string in stmt_mcontext */
3686  oldcontext = MemoryContextSwitchTo(stmt_mcontext);
3687  initStringInfo(&ds);
3688  MemoryContextSwitchTo(oldcontext);
3689 
3690  current_param = list_head(stmt->params);
3691 
3692  for (cp = stmt->message; *cp; cp++)
3693  {
3694  /*
3695  * Occurrences of a single % are replaced by the next parameter's
3696  * external representation. Double %'s are converted to one %.
3697  */
3698  if (cp[0] == '%')
3699  {
3700  Oid paramtypeid;
3701  int32 paramtypmod;
3702  Datum paramvalue;
3703  bool paramisnull;
3704  char *extval;
3705 
3706  if (cp[1] == '%')
3707  {
3708  appendStringInfoChar(&ds, '%');
3709  cp++;
3710  continue;
3711  }
3712 
3713  /* should have been checked at compile time */
3714  if (current_param == NULL)
3715  elog(ERROR, "unexpected RAISE parameter list length");
3716 
3717  paramvalue = exec_eval_expr(estate,
3718  (PLpgSQL_expr *) lfirst(current_param),
3719  &paramisnull,
3720  &paramtypeid,
3721  &paramtypmod);
3722 
3723  if (paramisnull)
3724  extval = "<NULL>";
3725  else
3726  extval = convert_value_to_string(estate,
3727  paramvalue,
3728  paramtypeid);
3729  appendStringInfoString(&ds, extval);
3730  current_param = lnext(stmt->params, current_param);
3731  exec_eval_cleanup(estate);
3732  }
3733  else
3734  appendStringInfoChar(&ds, cp[0]);
3735  }
3736 
3737  /* should have been checked at compile time */
3738  if (current_param != NULL)
3739  elog(ERROR, "unexpected RAISE parameter list length");
3740 
3741  err_message = ds.data;
3742  }
3743 
3744  foreach(lc, stmt->options)
3745  {
3747  Datum optionvalue;
3748  bool optionisnull;
3749  Oid optiontypeid;
3750  int32 optiontypmod;
3751  char *extval;
3752 
3753  optionvalue = exec_eval_expr(estate, opt->expr,
3754  &optionisnull,
3755  &optiontypeid,
3756  &optiontypmod);
3757  if (optionisnull)
3758  ereport(ERROR,
3759  (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
3760  errmsg("RAISE statement option cannot be null")));
3761 
3762  extval = convert_value_to_string(estate, optionvalue, optiontypeid);
3763 
3764  switch (opt->opt_type)
3765  {
3767  if (err_code)
3768  ereport(ERROR,
3769  (errcode(ERRCODE_SYNTAX_ERROR),
3770  errmsg("RAISE option already specified: %s",
3771  "ERRCODE")));
3772  err_code = plpgsql_recognize_err_condition(extval, true);
3773  condname = MemoryContextStrdup(stmt_mcontext, extval);
3774  break;
3776  SET_RAISE_OPTION_TEXT(err_message, "MESSAGE");
3777  break;
3779  SET_RAISE_OPTION_TEXT(err_detail, "DETAIL");
3780  break;
3782  SET_RAISE_OPTION_TEXT(err_hint, "HINT");
3783  break;
3785  SET_RAISE_OPTION_TEXT(err_column, "COLUMN");
3786  break;
3788  SET_RAISE_OPTION_TEXT(err_constraint, "CONSTRAINT");
3789  break;
3791  SET_RAISE_OPTION_TEXT(err_datatype, "DATATYPE");
3792  break;
3794  SET_RAISE_OPTION_TEXT(err_table, "TABLE");
3795  break;
3797  SET_RAISE_OPTION_TEXT(err_schema, "SCHEMA");
3798  break;
3799  default:
3800  elog(ERROR, "unrecognized raise option: %d", opt->opt_type);
3801  }
3802 
3803  exec_eval_cleanup(estate);
3804  }
3805 
3806  /* Default code if nothing specified */
3807  if (err_code == 0 && stmt->elog_level >= ERROR)
3808  err_code = ERRCODE_RAISE_EXCEPTION;
3809 
3810  /* Default error message if nothing specified */
3811  if (err_message == NULL)
3812  {
3813  if (condname)
3814  {
3815  err_message = condname;
3816  condname = NULL;
3817  }
3818  else
3819  err_message = MemoryContextStrdup(stmt_mcontext,
3820  unpack_sql_state(err_code));
3821  }
3822 
3823  /*
3824  * Throw the error (may or may not come back)
3825  */
3826  ereport(stmt->elog_level,
3827  (err_code ? errcode(err_code) : 0,
3828  errmsg_internal("%s", err_message),
3829  (err_detail != NULL) ? errdetail_internal("%s", err_detail) : 0,
3830  (err_hint != NULL) ? errhint("%s", err_hint) : 0,
3831  (err_column != NULL) ?
3832  err_generic_string(PG_DIAG_COLUMN_NAME, err_column) : 0,
3833  (err_constraint != NULL) ?
3834  err_generic_string(PG_DIAG_CONSTRAINT_NAME, err_constraint) : 0,
3835  (err_datatype != NULL) ?
3836  err_generic_string(PG_DIAG_DATATYPE_NAME, err_datatype) : 0,
3837  (err_table != NULL) ?
3838  err_generic_string(PG_DIAG_TABLE_NAME, err_table) : 0,
3839  (err_schema != NULL) ?
3840  err_generic_string(PG_DIAG_SCHEMA_NAME, err_schema) : 0));
3841 
3842  /* Clean up transient strings */
3843  MemoryContextReset(stmt_mcontext);
3844 
3845  return PLPGSQL_RC_OK;
3846 }
3847 
3848 /* ----------
3849  * exec_stmt_assert Assert statement
3850  * ----------
3851  */
3852 static int
3854 {
3855  bool value;
3856  bool isnull;
3857 
3858  /* do nothing when asserts are not enabled */
3859  if (!plpgsql_check_asserts)
3860  return PLPGSQL_RC_OK;
3861 
3862  value = exec_eval_boolean(estate, stmt->cond, &isnull);
3863  exec_eval_cleanup(estate);
3864 
3865  if (isnull || !value)
3866  {
3867  char *message = NULL;
3868 
3869  if (stmt->message != NULL)
3870  {
3871  Datum val;
3872  Oid typeid;
3873  int32 typmod;
3874 
3875  val = exec_eval_expr(estate, stmt->message,
3876  &isnull, &typeid, &typmod);
3877  if (!isnull)
3878  message = convert_value_to_string(estate, val, typeid);
3879  /* we mustn't do exec_eval_cleanup here */
3880  }
3881 
3882  ereport(ERROR,
3883  (errcode(ERRCODE_ASSERT_FAILURE),
3884  message ? errmsg_internal("%s", message) :
3885  errmsg("assertion failed")));
3886  }
3887 
3888  return PLPGSQL_RC_OK;
3889 }
3890 
3891 /* ----------
3892  * Initialize a mostly empty execution state
3893  * ----------
3894  */
3895 static void
3897  PLpgSQL_function *func,
3898  ReturnSetInfo *rsi,
3899  EState *simple_eval_estate,
3900  ResourceOwner simple_eval_resowner)
3901 {
3902  HASHCTL ctl;
3903 
3904  /* this link will be restored at exit from plpgsql_call_handler */
3905  func->cur_estate = estate;
3906 
3907  estate->func = func;
3908  estate->trigdata = NULL;
3909  estate->evtrigdata = NULL;
3910 
3911  estate->retval = (Datum) 0;
3912  estate->retisnull = true;
3913  estate->rettype = InvalidOid;
3914 
3915  estate->fn_rettype = func->fn_rettype;
3916  estate->retistuple = func->fn_retistuple;
3917  estate->retisset = func->fn_retset;
3918 
3919  estate->readonly_func = func->fn_readonly;
3920  estate->atomic = true;
3921 
3922  estate->exitlabel = NULL;
3923  estate->cur_error = NULL;
3924 
3925  estate->tuple_store = NULL;
3926  estate->tuple_store_desc = NULL;
3927  if (rsi)
3928  {
3931  }
3932  else
3933  {
3934  estate->tuple_store_cxt = NULL;
3935  estate->tuple_store_owner = NULL;
3936  }
3937  estate->rsi = rsi;
3938 
3939  estate->found_varno = func->found_varno;
3940  estate->ndatums = func->ndatums;
3941  estate->datums = NULL;
3942  /* the datums array will be filled by copy_plpgsql_datums() */
3944 
3945  /* initialize our ParamListInfo with appropriate hook functions */
3946  estate->paramLI = makeParamList(0);
3948  estate->paramLI->paramFetchArg = (void *) estate;
3950  estate->paramLI->paramCompileArg = NULL; /* not needed */
3952  estate->paramLI->parserSetupArg = NULL; /* filled during use */
3953  estate->paramLI->numParams = estate->ndatums;
3954 
3955  /* set up for use of appropriate simple-expression EState and cast hash */
3956  if (simple_eval_estate)
3957  {
3958  estate->simple_eval_estate = simple_eval_estate;
3959  /* Private cast hash just lives in function's main context */
3960  memset(&ctl, 0, sizeof(ctl));
3961  ctl.keysize = sizeof(plpgsql_CastHashKey);
3962  ctl.entrysize = sizeof(plpgsql_CastHashEntry);
3963  ctl.hcxt = CurrentMemoryContext;
3964  estate->cast_hash = hash_create("PLpgSQL private cast cache",
3965  16, /* start small and extend */
3966  &ctl,
3969  }
3970  else
3971  {
3973  /* Create the session-wide cast-info hash table if we didn't already */
3974  if (shared_cast_hash == NULL)
3975  {
3976  shared_cast_context = AllocSetContextCreate(TopMemoryContext,
3977  "PLpgSQL cast info",
3979  memset(&ctl, 0, sizeof(ctl));
3980  ctl.keysize = sizeof(plpgsql_CastHashKey);
3981  ctl.entrysize = sizeof(plpgsql_CastHashEntry);
3982  ctl.hcxt = shared_cast_context;
3983  shared_cast_hash = hash_create("PLpgSQL cast cache",
3984  16, /* start small and extend */
3985  &ctl,
3987  }
3988  estate->cast_hash = shared_cast_hash;
3990  }
3991  /* likewise for the simple-expression resource owner */
3992  if (simple_eval_resowner)
3993  estate->simple_eval_resowner = simple_eval_resowner;
3994  else
3996 
3997  /*
3998  * We start with no stmt_mcontext; one will be created only if needed.
3999  * That context will be a direct child of the function's main execution
4000  * context. Additional stmt_mcontexts might be created as children of it.
4001  */
4002  estate->stmt_mcontext = NULL;
4004 
4005  estate->eval_tuptable = NULL;
4006  estate->eval_processed = 0;
4007  estate->eval_econtext = NULL;
4008 
4009  estate->err_stmt = NULL;
4010  estate->err_text = NULL;
4011 
4012  estate->plugin_info = NULL;
4013 
4014  /*
4015  * Create an EState and ExprContext for evaluation of simple expressions.
4016  */
4017  plpgsql_create_econtext(estate);
4018 
4019  /*
4020  * Let the plugin see this function before we initialize any local
4021  * PL/pgSQL variables - note that we also give the plugin a few function
4022  * pointers so it can call back into PL/pgSQL for doing things like
4023  * variable assignments and stack traces
4024  */
4025  if (*plpgsql_plugin_ptr)
4026  {
4027  (*plpgsql_plugin_ptr)->error_callback = plpgsql_exec_error_callback;
4028  (*plpgsql_plugin_ptr)->assign_expr = exec_assign_expr;
4029 
4030  if ((*plpgsql_plugin_ptr)->func_setup)
4031  ((*plpgsql_plugin_ptr)->func_setup) (estate, func);
4032  }
4033 }
4034 
4035 /* ----------
4036  * Release temporary memory used by expression/subselect evaluation
4037  *
4038  * NB: the result of the evaluation is no longer valid after this is done,
4039  * unless it is a pass-by-value datatype.
4040  *
4041  * NB: if you change this code, see also the hacks in exec_assign_value's
4042  * PLPGSQL_DTYPE_ARRAYELEM case for partial cleanup after subscript evals.
4043  * ----------
4044  */
4045 static void
4047 {
4048  /* Clear result of a full SPI_execute */
4049  if (estate->eval_tuptable != NULL)
4051  estate->eval_tuptable = NULL;
4052 
4053  /*
4054  * Clear result of exec_eval_simple_expr (but keep the econtext). This
4055  * also clears any short-lived allocations done via get_eval_mcontext.
4056  */
4057  if (estate->eval_econtext != NULL)
4059 }
4060 
4061 
4062 /* ----------
4063  * Generate a prepared plan
4064  * ----------
4065  */
4066 static void
4068  PLpgSQL_expr *expr, int cursorOptions,
4069  bool keepplan)
4070 {
4071  SPIPlanPtr plan;
4072 
4073  /*
4074  * The grammar can't conveniently set expr->func while building the parse
4075  * tree, so make sure it's set before parser hooks need it.
4076  */
4077  expr->func = estate->func;
4078 
4079  /*
4080  * Generate and save the plan
4081  */
4082  plan = SPI_prepare_params(expr->query,
4084  (void *) expr,
4085  cursorOptions);
4086  if (plan == NULL)
4087  elog(ERROR, "SPI_prepare_params failed for \"%s\": %s",
4088  expr->query, SPI_result_code_string(SPI_result));
4089  if (keepplan)
4090  SPI_keepplan(plan);
4091  expr->plan = plan;
4092 
4093  /* Check to see if it's a simple expression */
4094  exec_simple_check_plan(estate, expr);
4095 
4096  /*
4097  * Mark expression as not using a read-write param. exec_assign_value has
4098  * to take steps to override this if appropriate; that seems cleaner than
4099  * adding parameters to all other callers.
4100  */
4101  expr->rwparam = -1;
4102 }
4103 
4104 
4105 /* ----------
4106  * exec_stmt_execsql Execute an SQL statement (possibly with INTO).
4107  *
4108  * Note: some callers rely on this not touching stmt_mcontext. If it ever
4109  * needs to use that, fix those callers to push/pop stmt_mcontext.
4110  * ----------
4111  */
4112 static int
4114  PLpgSQL_stmt_execsql *stmt)
4115 {
4116  ParamListInfo paramLI;
4117  long tcount;
4118  int rc;
4119  PLpgSQL_expr *expr = stmt->sqlstmt;
4120  int too_many_rows_level = 0;
4121 
4123  too_many_rows_level = ERROR;
4124  else if (plpgsql_extra_warnings & PLPGSQL_XCHECK_TOOMANYROWS)
4125  too_many_rows_level = WARNING;
4126 
4127  /*
4128  * On the first call for this statement generate the plan, and detect
4129  * whether the statement is INSERT/UPDATE/DELETE
4130  */
4131  if (expr->plan == NULL)
4132  {
4133  ListCell *l;
4134 
4135  exec_prepare_plan(estate, expr, CURSOR_OPT_PARALLEL_OK, true);
4136  stmt->mod_stmt = false;
4137  foreach(l, SPI_plan_get_plan_sources(expr->plan))
4138  {
4139  CachedPlanSource *plansource = (CachedPlanSource *) lfirst(l);
4140 
4141  /*
4142  * We could look at the raw_parse_tree, but it seems simpler to
4143  * check the command tag. Note we should *not* look at the Query
4144  * tree(s), since those are the result of rewriting and could have
4145  * been transmogrified into something else entirely.
4146  */
4147  if (plansource->commandTag == CMDTAG_INSERT ||
4148  plansource->commandTag == CMDTAG_UPDATE ||
4149  plansource->commandTag == CMDTAG_DELETE)
4150  {
4151  stmt->mod_stmt = true;
4152  break;
4153  }
4154  }
4155  }
4156 
4157  /*
4158  * Set up ParamListInfo to pass to executor
4159  */
4160  paramLI = setup_param_list(estate, expr);
4161 
4162  /*
4163  * If we have INTO, then we only need one row back ... but if we have INTO
4164  * STRICT or extra check too_many_rows, ask for two rows, so that we can
4165  * verify the statement returns only one. INSERT/UPDATE/DELETE are always
4166  * treated strictly. Without INTO, just run the statement to completion
4167  * (tcount = 0).
4168  *
4169  * We could just ask for two rows always when using INTO, but there are
4170  * some cases where demanding the extra row costs significant time, eg by
4171  * forcing completion of a sequential scan. So don't do it unless we need
4172  * to enforce strictness.
4173  */
4174  if (stmt->into)
4175  {
4176  if (stmt->strict || stmt->mod_stmt || too_many_rows_level)
4177  tcount = 2;
4178  else
4179  tcount = 1;
4180  }
4181  else
4182  tcount = 0;
4183 
4184  /*
4185  * Execute the plan
4186  */
4187  rc = SPI_execute_plan_with_paramlist(expr->plan, paramLI,
4188  estate->readonly_func, tcount);
4189 
4190  /*
4191  * Check for error, and set FOUND if appropriate (for historical reasons
4192  * we set FOUND only for certain query types). Also Assert that we
4193  * identified the statement type the same as SPI did.
4194  */
4195  switch (rc)
4196  {
4197  case SPI_OK_SELECT:
4198  Assert(!stmt->mod_stmt);
4199  exec_set_found(estate, (SPI_processed != 0));
4200  break;
4201 
4202  case SPI_OK_INSERT:
4203  case SPI_OK_UPDATE:
4204  case SPI_OK_DELETE:
4208  Assert(stmt->mod_stmt);
4209  exec_set_found(estate, (SPI_processed != 0));
4210  break;
4211 
4212  case SPI_OK_SELINTO:
4213  case SPI_OK_UTILITY:
4214  Assert(!stmt->mod_stmt);
4215  break;
4216 
4217  case SPI_OK_REWRITTEN:
4218 
4219  /*
4220  * The command was rewritten into another kind of command. It's
4221  * not clear what FOUND would mean in that case (and SPI doesn't
4222  * return the row count either), so just set it to false. Note
4223  * that we can't assert anything about mod_stmt here.
4224  */
4225  exec_set_found(estate, false);
4226  break;
4227 
4228  /* Some SPI errors deserve specific error messages */
4229  case SPI_ERROR_COPY:
4230  ereport(ERROR,
4231  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4232  errmsg("cannot COPY to/from client in PL/pgSQL")));
4233  break;
4234 
4235  case SPI_ERROR_TRANSACTION:
4236  ereport(ERROR,
4237  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4238  errmsg("unsupported transaction command in PL/pgSQL")));
4239  break;
4240 
4241  default:
4242  elog(ERROR, "SPI_execute_plan_with_paramlist failed executing query \"%s\": %s",
4243  expr->query, SPI_result_code_string(rc));
4244  break;
4245  }
4246 
4247  /* All variants should save result info for GET DIAGNOSTICS */
4248  estate->eval_processed = SPI_processed;
4249 
4250  /* Process INTO if present */
4251  if (stmt->into)
4252  {
4253  SPITupleTable *tuptab = SPI_tuptable;
4254  uint64 n = SPI_processed;
4255  PLpgSQL_variable *target;
4256 
4257  /* If the statement did not return a tuple table, complain */
4258  if (tuptab == NULL)
4259  ereport(ERROR,
4260  (errcode(ERRCODE_SYNTAX_ERROR),
4261  errmsg("INTO used with a command that cannot return data")));
4262 
4263  /* Fetch target's datum entry */
4264  target = (PLpgSQL_variable *) estate->datums[stmt->target->dno];
4265 
4266  /*
4267  * If SELECT ... INTO specified STRICT, and the query didn't find
4268  * exactly one row, throw an error. If STRICT was not specified, then
4269  * allow the query to find any number of rows.
4270  */
4271  if (n == 0)
4272  {
4273  if (stmt->strict)
4274  {
4275  char *errdetail;
4276 
4277  if (estate->func->print_strict_params)
4278  errdetail = format_expr_params(estate, expr);
4279  else
4280  errdetail = NULL;
4281 
4282  ereport(ERROR,
4283  (errcode(ERRCODE_NO_DATA_FOUND),
4284  errmsg("query returned no rows"),
4285  errdetail ? errdetail_internal("parameters: %s", errdetail) : 0));
4286  }
4287  /* set the target to NULL(s) */
4288  exec_move_row(estate, target, NULL, tuptab->tupdesc);
4289  }
4290  else
4291  {
4292  if (n > 1 && (stmt->strict || stmt->mod_stmt || too_many_rows_level))
4293  {
4294  char *errdetail;
4295  int errlevel;
4296 
4297  if (estate->func->print_strict_params)
4298  errdetail = format_expr_params(estate, expr);
4299  else
4300  errdetail = NULL;
4301 
4302  errlevel = (stmt->strict || stmt->mod_stmt) ? ERROR : too_many_rows_level;
4303 
4304  ereport(errlevel,
4305  (errcode(ERRCODE_TOO_MANY_ROWS),
4306  errmsg("query returned more than one row"),
4307  errdetail ? errdetail_internal("parameters: %s", errdetail) : 0,
4308  errhint("Make sure the query returns a single row, or use LIMIT 1.")));
4309  }
4310  /* Put the first result row into the target */
4311  exec_move_row(estate, target, tuptab->vals[0], tuptab->tupdesc);
4312  }
4313 
4314  /* Clean up */
4315  exec_eval_cleanup(estate);
4317  }
4318  else
4319  {
4320  /* If the statement returned a tuple table, complain */
4321  if (SPI_tuptable != NULL)
4322  ereport(ERROR,
4323  (errcode(ERRCODE_SYNTAX_ERROR),
4324  errmsg("query has no destination for result data"),
4325  (rc == SPI_OK_SELECT) ? errhint("If you want to discard the results of a SELECT, use PERFORM instead.") : 0));
4326  }
4327 
4328  return PLPGSQL_RC_OK;
4329 }
4330 
4331 
4332 /* ----------
4333  * exec_stmt_dynexecute Execute a dynamic SQL query
4334  * (possibly with INTO).
4335  * ----------
4336  */
4337 static int
4340 {
4341  Datum query;
4342  bool isnull;
4343  Oid restype;
4344  int32 restypmod;
4345  char *querystr;
4346  int exec_res;
4347  PreparedParamsData *ppd = NULL;
4348  MemoryContext stmt_mcontext = get_stmt_mcontext(estate);
4349 
4350  /*
4351  * First we evaluate the string expression after the EXECUTE keyword. Its
4352  * result is the querystring we have to execute.
4353  */
4354  query = exec_eval_expr(estate, stmt->query, &isnull, &restype, &restypmod);
4355  if (isnull)
4356  ereport(ERROR,
4357  (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
4358  errmsg("query string argument of EXECUTE is null")));
4359 
4360  /* Get the C-String representation */
4361  querystr = convert_value_to_string(estate, query, restype);
4362 
4363  /* copy it into the stmt_mcontext before we clean up */
4364  querystr = MemoryContextStrdup(stmt_mcontext, querystr);
4365 
4366  exec_eval_cleanup(estate);
4367 
4368  /*
4369  * Execute the query without preparing a saved plan.
4370  */
4371  if (stmt->params)
4372  {
4373  ppd = exec_eval_using_params(estate, stmt->params);
4374  exec_res = SPI_execute_with_args(querystr,
4375  ppd->nargs, ppd->types,
4376  ppd->values, ppd->nulls,
4377  estate->readonly_func, 0);
4378  }
4379  else
4380  exec_res = SPI_execute(querystr, estate->readonly_func, 0);
4381 
4382  switch (exec_res)
4383  {
4384  case SPI_OK_SELECT:
4385  case SPI_OK_INSERT:
4386  case SPI_OK_UPDATE:
4387  case SPI_OK_DELETE:
4391  case SPI_OK_UTILITY:
4392  case SPI_OK_REWRITTEN:
4393  break;
4394 
4395  case 0:
4396 
4397  /*
4398  * Also allow a zero return, which implies the querystring
4399  * contained no commands.
4400  */
4401  break;
4402 
4403  case SPI_OK_SELINTO:
4404 
4405  /*
4406  * We want to disallow SELECT INTO for now, because its behavior
4407  * is not consistent with SELECT INTO in a normal plpgsql context.
4408  * (We need to reimplement EXECUTE to parse the string as a
4409  * plpgsql command, not just feed it to SPI_execute.) This is not
4410  * a functional limitation because CREATE TABLE AS is allowed.
4411  */
4412  ereport(ERROR,
4413  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4414  errmsg("EXECUTE of SELECT ... INTO is not implemented"),
4415  errhint("You might want to use EXECUTE ... INTO or EXECUTE CREATE TABLE ... AS instead.")));
4416  break;
4417 
4418  /* Some SPI errors deserve specific error messages */
4419  case SPI_ERROR_COPY:
4420  ereport(ERROR,
4421  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4422  errmsg("cannot COPY to/from client in PL/pgSQL")));
4423  break;
4424 
4425  case SPI_ERROR_TRANSACTION:
4426  ereport(ERROR,
4427  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4428  errmsg("EXECUTE of transaction commands is not implemented")));
4429  break;
4430 
4431  default:
4432  elog(ERROR, "SPI_execute failed executing query \"%s\": %s",
4433  querystr, SPI_result_code_string(exec_res));
4434  break;
4435  }
4436 
4437  /* Save result info for GET DIAGNOSTICS */
4438  estate->eval_processed = SPI_processed;
4439 
4440  /* Process INTO if present */
4441  if (stmt->into)
4442  {
4443  SPITupleTable *tuptab = SPI_tuptable;
4444  uint64 n = SPI_processed;
4445  PLpgSQL_variable *target;
4446 
4447  /* If the statement did not return a tuple table, complain */
4448  if (tuptab == NULL)
4449  ereport(ERROR,
4450  (errcode(ERRCODE_SYNTAX_ERROR),
4451  errmsg("INTO used with a command that cannot return data")));
4452 
4453  /* Fetch target's datum entry */
4454  target = (PLpgSQL_variable *) estate->datums[stmt->target->dno];
4455 
4456  /*
4457  * If SELECT ... INTO specified STRICT, and the query didn't find
4458  * exactly one row, throw an error. If STRICT was not specified, then
4459  * allow the query to find any number of rows.
4460  */
4461  if (n == 0)
4462  {
4463  if (stmt->strict)
4464  {
4465  char *errdetail;
4466 
4467  if (estate->func->print_strict_params)
4468  errdetail = format_preparedparamsdata(estate, ppd);
4469  else
4470  errdetail = NULL;
4471 
4472  ereport(ERROR,
4473  (errcode(ERRCODE_NO_DATA_FOUND),
4474  errmsg("query returned no rows"),
4475  errdetail ? errdetail_internal("parameters: %s", errdetail) : 0));
4476  }
4477  /* set the target to NULL(s) */
4478  exec_move_row(estate, target, NULL, tuptab->tupdesc);
4479  }
4480  else
4481  {
4482  if (n > 1 && stmt->strict)
4483  {
4484  char *errdetail;
4485 
4486  if (estate->func->print_strict_params)
4487  errdetail = format_preparedparamsdata(estate, ppd);
4488  else
4489  errdetail = NULL;
4490 
4491  ereport(ERROR,
4492  (errcode(ERRCODE_TOO_MANY_ROWS),
4493  errmsg("query returned more than one row"),
4494  errdetail ? errdetail_internal("parameters: %s", errdetail) : 0));
4495  }
4496 
4497  /* Put the first result row into the target */
4498  exec_move_row(estate, target, tuptab->vals[0], tuptab->tupdesc);
4499  }
4500  /* clean up after exec_move_row() */
4501  exec_eval_cleanup(estate);
4502  }
4503  else
4504  {
4505  /*
4506  * It might be a good idea to raise an error if the query returned
4507  * tuples that are being ignored, but historically we have not done
4508  * that.
4509  */
4510  }
4511 
4512  /* Release any result from SPI_execute, as well as transient data */
4514  MemoryContextReset(stmt_mcontext);
4515 
4516  return PLPGSQL_RC_OK;
4517 }
4518 
4519 
4520 /* ----------
4521  * exec_stmt_dynfors Execute a dynamic query, assign each
4522  * tuple to a record or row and
4523  * execute a group of statements
4524  * for it.
4525  * ----------
4526  */
4527 static int
4529 {
4530  Portal portal;
4531  int rc;
4532 
4533  portal = exec_dynquery_with_params(estate, stmt->query, stmt->params,
4534  NULL, 0);
4535 
4536  /*
4537  * Execute the loop
4538  */
4539  rc = exec_for_query(estate, (PLpgSQL_stmt_forq *) stmt, portal, true);
4540 
4541  /*
4542  * Close the implicit cursor
4543  */
4544  SPI_cursor_close(portal);
4545 
4546  return rc;
4547 }
4548 
4549 
4550 /* ----------
4551  * exec_stmt_open Execute an OPEN cursor statement
4552  * ----------
4553  */
4554 static int
4556 {
4557  PLpgSQL_var *curvar;
4558  MemoryContext stmt_mcontext = NULL;
4559  char *curname = NULL;
4560  PLpgSQL_expr *query;
4561  Portal portal;
4562  ParamListInfo paramLI;
4563 
4564  /* ----------
4565  * Get the cursor variable and if it has an assigned name, check
4566  * that it's not in use currently.
4567  * ----------
4568  */
4569  curvar = (PLpgSQL_var *) (estate->datums[stmt->curvar]);
4570  if (!curvar->isnull)
4571  {
4572  MemoryContext oldcontext;
4573 
4574  /* We only need stmt_mcontext to hold the cursor name string */
4575  stmt_mcontext = get_stmt_mcontext(estate);
4576  oldcontext = MemoryContextSwitchTo(stmt_mcontext);
4577  curname = TextDatumGetCString(curvar->value);
4578  MemoryContextSwitchTo(oldcontext);
4579 
4580  if (SPI_cursor_find(curname) != NULL)
4581  ereport(ERROR,
4582  (errcode(ERRCODE_DUPLICATE_CURSOR),
4583  errmsg("cursor \"%s\" already in use", curname)));
4584  }
4585 
4586  /* ----------
4587  * Process the OPEN according to it's type.
4588  * ----------
4589  */
4590  if (stmt->query != NULL)
4591  {
4592  /* ----------
4593  * This is an OPEN refcursor FOR SELECT ...
4594  *
4595  * We just make sure the query is planned. The real work is
4596  * done downstairs.
4597  * ----------
4598  */
4599  query = stmt->query;
4600  if (query->plan == NULL)
4601  exec_prepare_plan(estate, query, stmt->cursor_options, true);
4602  }
4603  else if (stmt->dynquery != NULL)
4604  {
4605  /* ----------
4606  * This is an OPEN refcursor FOR EXECUTE ...
4607  * ----------
4608  */
4609  portal = exec_dynquery_with_params(estate,
4610  stmt->dynquery,
4611  stmt->params,
4612  curname,
4613  stmt->cursor_options);
4614 
4615  /*
4616  * If cursor variable was NULL, store the generated portal name in it.
4617  * Note: exec_dynquery_with_params already reset the stmt_mcontext, so
4618  * curname is a dangling pointer here; but testing it for nullness is
4619  * OK.
4620  */
4621  if (curname == NULL)
4622  assign_text_var(estate, curvar, portal->name);
4623 
4624  return PLPGSQL_RC_OK;
4625  }
4626  else
4627  {
4628  /* ----------
4629  * This is an OPEN cursor
4630  *
4631  * Note: parser should already have checked that statement supplies
4632  * args iff cursor needs them, but we check again to be safe.
4633  * ----------
4634  */
4635  if (stmt->argquery != NULL)
4636  {
4637  /* ----------
4638  * OPEN CURSOR with args. We fake a SELECT ... INTO ...
4639  * statement to evaluate the args and put 'em into the
4640  * internal row.
4641  * ----------
4642  */
4643  PLpgSQL_stmt_execsql set_args;
4644 
4645  if (curvar->cursor_explicit_argrow < 0)
4646  ereport(ERROR,
4647  (errcode(ERRCODE_SYNTAX_ERROR),
4648  errmsg("arguments given for cursor without arguments")));
4649 
4650  memset(&set_args, 0, sizeof(set_args));
4651  set_args.cmd_type = PLPGSQL_STMT_EXECSQL;
4652  set_args.lineno = stmt->lineno;
4653  set_args.sqlstmt = stmt->argquery;
4654  set_args.into = true;
4655  /* XXX historically this has not been STRICT */
4656  set_args.target = (PLpgSQL_variable *)
4657  (estate->datums[curvar->cursor_explicit_argrow]);
4658 
4659  if (exec_stmt_execsql(estate, &set_args) != PLPGSQL_RC_OK)
4660  elog(ERROR, "open cursor failed during argument processing");
4661  }
4662  else
4663  {
4664  if (curvar->cursor_explicit_argrow >= 0)
4665  ereport(ERROR,
4666  (errcode(ERRCODE_SYNTAX_ERROR),
4667  errmsg("arguments required for cursor")));
4668  }
4669 
4670  query = curvar->cursor_explicit_expr;
4671  if (query->plan == NULL)
4672  exec_prepare_plan(estate, query, curvar->cursor_options, true);
4673  }
4674 
4675  /*
4676  * Set up ParamListInfo for this query
4677  */
4678  paramLI = setup_param_list(estate, query);
4679 
4680  /*
4681  * Open the cursor (the paramlist will get copied into the portal)
4682  */
4683  portal = SPI_cursor_open_with_paramlist(curname, query->plan,
4684  paramLI,
4685  estate->readonly_func);
4686  if (portal == NULL)
4687  elog(ERROR, "could not open cursor: %s",
4689 
4690  /*
4691  * If cursor variable was NULL, store the generated portal name in it
4692  */
4693  if (curname == NULL)
4694  assign_text_var(estate, curvar, portal->name);
4695 
4696  /* If we had any transient data, clean it up */
4697  exec_eval_cleanup(estate);
4698  if (stmt_mcontext)
4699  MemoryContextReset(stmt_mcontext);
4700 
4701  return PLPGSQL_RC_OK;
4702 }
4703 
4704 
4705 /* ----------
4706  * exec_stmt_fetch Fetch from a cursor into a target, or just
4707  * move the current position of the cursor
4708  * ----------
4709  */
4710 static int
4712 {
4713  PLpgSQL_var *curvar;
4714  long how_many = stmt->how_many;
4715  SPITupleTable *tuptab;
4716  Portal portal;
4717  char *curname;
4718  uint64 n;
4719  MemoryContext oldcontext;
4720 
4721  /* ----------
4722  * Get the portal of the cursor by name
4723  * ----------
4724  */
4725  curvar = (PLpgSQL_var *) (estate->datums[stmt->curvar]);
4726  if (curvar->isnull)
4727  ereport(ERROR,
4728  (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
4729  errmsg("cursor variable \"%s\" is null", curvar->refname)));
4730 
4731  /* Use eval_mcontext for short-lived string */
4732  oldcontext = MemoryContextSwitchTo(get_eval_mcontext(estate));
4733  curname = TextDatumGetCString(curvar->value);
4734  MemoryContextSwitchTo(oldcontext);
4735 
4736  portal = SPI_cursor_find(curname);
4737  if (portal == NULL)
4738  ereport(ERROR,
4739  (errcode(ERRCODE_UNDEFINED_CURSOR),
4740  errmsg("cursor \"%s\" does not exist", curname)));
4741 
4742  /* Calculate position for FETCH_RELATIVE or FETCH_ABSOLUTE */
4743  if (stmt->expr)
4744  {
4745  bool isnull;
4746 
4747  /* XXX should be doing this in LONG not INT width */
4748  how_many = exec_eval_integer(estate, stmt->expr, &isnull);
4749 
4750  if (isnull)
4751  ereport(ERROR,
4752  (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
4753  errmsg("relative or absolute cursor position is null")));
4754 
4755  exec_eval_cleanup(estate);
4756  }
4757 
4758  if (!stmt->is_move)
4759  {
4760  PLpgSQL_variable *target;
4761 
4762  /* ----------
4763  * Fetch 1 tuple from the cursor
4764  * ----------
4765  */
4766  SPI_scroll_cursor_fetch(portal, stmt->direction, how_many);
4767  tuptab = SPI_tuptable;
4768  n = SPI_processed;
4769 
4770  /* ----------
4771  * Set the target appropriately.
4772  * ----------
4773  */
4774  target = (PLpgSQL_variable *) estate->datums[stmt->target->dno];
4775  if (n == 0)
4776  exec_move_row(estate, target, NULL, tuptab->tupdesc);
4777  else
4778  exec_move_row(estate, target, tuptab->vals[0], tuptab->tupdesc);
4779 
4780  exec_eval_cleanup(estate);
4781  SPI_freetuptable(tuptab);
4782  }
4783  else
4784  {
4785  /* Move the cursor */
4786  SPI_scroll_cursor_move(portal, stmt->direction, how_many);
4787  n = SPI_processed;
4788  }
4789 
4790  /* Set the ROW_COUNT and the global FOUND variable appropriately. */
4791  estate->eval_processed = n;
4792  exec_set_found(estate, n != 0);
4793 
4794  return PLPGSQL_RC_OK;
4795 }
4796 
4797 /* ----------
4798  * exec_stmt_close Close a cursor
4799  * ----------
4800  */
4801 static int
4803 {
4804  PLpgSQL_var *curvar;
4805  Portal portal;
4806  char *curname;
4807  MemoryContext oldcontext;
4808 
4809  /* ----------
4810  * Get the portal of the cursor by name
4811  * ----------
4812  */
4813  curvar = (PLpgSQL_var *) (estate->datums[stmt->curvar]);
4814  if (curvar->isnull)
4815  ereport(ERROR,
4816  (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
4817  errmsg("cursor variable \"%s\" is null", curvar->refname)));
4818 
4819  /* Use eval_mcontext for short-lived string */
4820  oldcontext = MemoryContextSwitchTo(get_eval_mcontext(estate));
4821  curname = TextDatumGetCString(curvar->value);
4822  MemoryContextSwitchTo(oldcontext);
4823 
4824  portal = SPI_cursor_find(curname);
4825  if (portal == NULL)
4826  ereport(ERROR,
4827  (errcode(ERRCODE_UNDEFINED_CURSOR),
4828  errmsg("cursor \"%s\" does not exist", curname)));
4829 
4830  /* ----------
4831  * And close it.
4832  * ----------
4833  */
4834  SPI_cursor_close(portal);
4835 
4836  return PLPGSQL_RC_OK;
4837 }
4838 
4839 /*
4840  * exec_stmt_commit
4841  *
4842  * Commit the transaction.
4843  */
4844 static int
4846 {
4847  if (stmt->chain)
4849  else
4850  {
4851  SPI_commit();
4853  }
4854 
4855  /*
4856  * We need to build new simple-expression infrastructure, since the old
4857  * data structures are gone.
4858  */
4859  estate->simple_eval_estate = NULL;
4860  estate->simple_eval_resowner = NULL;
4861  plpgsql_create_econtext(estate);
4862 
4863  return PLPGSQL_RC_OK;
4864 }
4865 
4866 /*
4867  * exec_stmt_rollback
4868  *
4869  * Abort the transaction.
4870  */
4871 static int
4873 {
4874  if (stmt->chain)
4876  else
4877  {
4878  SPI_rollback();
4880  }
4881 
4882  /*
4883  * We need to build new simple-expression infrastructure, since the old
4884  * data structures are gone.
4885  */
4886  estate->simple_eval_estate = NULL;
4887  estate->simple_eval_resowner = NULL;
4888  plpgsql_create_econtext(estate);
4889 
4890  return PLPGSQL_RC_OK;
4891 }
4892 
4893 /*
4894  * exec_stmt_set
4895  *
4896  * Execute SET/RESET statement.
4897  *
4898  * We just parse and execute the statement normally, but we have to do it
4899  * without setting a snapshot, for things like SET TRANSACTION.
4900  */
4901 static int
4903 {
4904  PLpgSQL_expr *expr = stmt->expr;
4905  int rc;
4906 
4907  if (expr->plan == NULL)
4908  {
4909  exec_prepare_plan(estate, expr, 0, true);
4910  expr->plan->no_snapshots = true;
4911  }
4912 
4913  rc = SPI_execute_plan(expr->plan, NULL, NULL, estate->readonly_func, 0);
4914 
4915  if (rc != SPI_OK_UTILITY)
4916  elog(ERROR, "SPI_execute_plan failed executing query \"%s\": %s",
4917  expr->query, SPI_result_code_string(rc));
4918 
4919  return PLPGSQL_RC_OK;
4920 }
4921 
4922 /* ----------
4923  * exec_assign_expr Put an expression's result into a variable.
4924  * ----------
4925  */
4926 static void
4928  PLpgSQL_expr *expr)
4929 {
4930  Datum value;
4931  bool isnull;
4932  Oid valtype;
4933  int32 valtypmod;
4934 
4935  /*
4936  * If first time through, create a plan for this expression, and then see
4937  * if we can pass the target variable as a read-write parameter to the
4938  * expression. (This is a bit messy, but it seems cleaner than modifying
4939  * the API of exec_eval_expr for the purpose.)
4940  */
4941  if (expr->plan == NULL)
4942  {
4943  exec_prepare_plan(estate, expr, 0, true);
4944  if (target->dtype == PLPGSQL_DTYPE_VAR)
4945  exec_check_rw_parameter(expr, target->dno);
4946  }
4947 
4948  value = exec_eval_expr(estate, expr, &isnull, &valtype, &valtypmod);
4949  exec_assign_value(estate, target, value, isnull, valtype, valtypmod);
4950  exec_eval_cleanup(estate);
4951 }
4952 
4953 
4954 /* ----------
4955  * exec_assign_c_string Put a C string into a text variable.
4956  *
4957  * We take a NULL pointer as signifying empty string, not SQL null.
4958  *
4959  * As with the underlying exec_assign_value, caller is expected to do
4960  * exec_eval_cleanup later.
4961  * ----------
4962  */
4963 static void
4965  const char *str)
4966 {
4967  text *value;
4968  MemoryContext oldcontext;
4969 
4970  /* Use eval_mcontext for short-lived text value */
4971  oldcontext = MemoryContextSwitchTo(get_eval_mcontext(estate));
4972  if (str != NULL)
4973  value = cstring_to_text(str);
4974  else
4975  value = cstring_to_text("");
4976  MemoryContextSwitchTo(oldcontext);
4977 
4978  exec_assign_value(estate, target, PointerGetDatum(value), false,
4979  TEXTOID, -1);
4980 }
4981 
4982 
4983 /* ----------
4984  * exec_assign_value Put a value into a target datum
4985  *
4986  * Note: in some code paths, this will leak memory in the eval_mcontext;
4987  * we assume that will be cleaned up later by exec_eval_cleanup. We cannot
4988  * call exec_eval_cleanup here for fear of destroying the input Datum value.
4989  * ----------
4990  */
4991 static void
4993  PLpgSQL_datum *target,
4994  Datum value, bool isNull,
4995  Oid valtype, int32 valtypmod)
4996 {
4997  switch (target->dtype)
4998  {
4999  case PLPGSQL_DTYPE_VAR:
5000  case PLPGSQL_DTYPE_PROMISE:
5001  {
5002  /*
5003  * Target is a variable
5004  */
5005  PLpgSQL_var *var = (PLpgSQL_var *) target;
5006  Datum newvalue;
5007 
5008  newvalue = exec_cast_value(estate,
5009  value,
5010  &isNull,
5011  valtype,
5012  valtypmod,
5013  var->datatype->typoid,
5014  var->datatype->atttypmod);
5015 
5016  if (isNull && var->notnull)
5017  ereport(ERROR,
5018  (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
5019  errmsg("null value cannot be assigned to variable \"%s\" declared NOT NULL",
5020  var->refname)));
5021 
5022  /*
5023  * If type is by-reference, copy the new value (which is
5024  * probably in the eval_mcontext) into the procedure's main
5025  * memory context. But if it's a read/write reference to an
5026  * expanded object, no physical copy needs to happen; at most
5027  * we need to reparent the object's memory context.
5028  *
5029  * If it's an array, we force the value to be stored in R/W
5030  * expanded form. This wins if the function later does, say,
5031  * a lot of array subscripting operations on the variable, and
5032  * otherwise might lose. We might need to use a different
5033  * heuristic, but it's too soon to tell. Also, are there
5034  * cases where it'd be useful to force non-array values into
5035  * expanded form?
5036  */
5037  if (!var->datatype->typbyval && !isNull)
5038  {
5039  if (var->datatype->typisarray &&
5041  {
5042  /* array and not already R/W, so apply expand_array */
5043  newvalue = expand_array(newvalue,
5044  estate->datum_context,
5045  NULL);
5046  }
5047  else
5048  {
5049  /* else transfer value if R/W, else just datumCopy */
5050  newvalue = datumTransfer(newvalue,
5051  false,
5052  var->datatype->typlen);
5053  }
5054  }
5055 
5056  /*
5057  * Now free the old value, if any, and assign the new one. But
5058  * skip the assignment if old and new values are the same.
5059  * Note that for expanded objects, this test is necessary and
5060  * cannot reliably be made any earlier; we have to be looking
5061  * at the object's standard R/W pointer to be sure pointer
5062  * equality is meaningful.
5063  *
5064  * Also, if it's a promise variable, we should disarm the
5065  * promise in any case --- otherwise, assigning null to an
5066  * armed promise variable would fail to disarm the promise.
5067  */
5068  if (var->value != newvalue || var->isnull || isNull)
5069  assign_simple_var(estate, var, newvalue, isNull,
5070  (!var->datatype->typbyval && !isNull));
5071  else
5073  break;
5074  }
5075 
5076  case PLPGSQL_DTYPE_ROW:
5077  {
5078  /*
5079  * Target is a row variable
5080  */
5081  PLpgSQL_row *row = (PLpgSQL_row *) target;
5082 
5083  if (isNull)
5084  {
5085  /* If source is null, just assign nulls to the row */
5086  exec_move_row(estate, (PLpgSQL_variable *) row,
5087  NULL, NULL);
5088  }
5089  else
5090  {
5091  /* Source must be of RECORD or composite type */
5092  if (!type_is_rowtype(valtype))
5093  ereport(ERROR,
5094  (errcode(ERRCODE_DATATYPE_MISMATCH),
5095  errmsg("cannot assign non-composite value to a row variable")));
5097  value);
5098  }
5099  break;
5100  }
5101 
5102  case PLPGSQL_DTYPE_REC:
5103  {
5104  /*
5105  * Target is a record variable
5106  */
5107  PLpgSQL_rec *rec = (PLpgSQL_rec *) target;
5108 
5109  if (isNull)
5110  {
5111  if (rec->notnull)
5112  ereport(ERROR,
5113  (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
5114  errmsg("null value cannot be assigned to variable \"%s\" declared NOT NULL",
5115  rec->refname)));
5116 
5117  /* Set variable to a simple NULL */
5118  exec_move_row(estate, (PLpgSQL_variable *) rec,
5119  NULL, NULL);
5120  }
5121  else
5122  {
5123  /* Source must be of RECORD or composite type */
5124  if (!type_is_rowtype(valtype))
5125  ereport(ERROR,
5126  (errcode(ERRCODE_DATATYPE_MISMATCH),
5127  errmsg("cannot assign non-composite value to a record variable")));
5129  value);
5130  }
5131  break;
5132  }
5133 
5135  {
5136  /*
5137  * Target is a field of a record
5138  */
5139  PLpgSQL_recfield *recfield = (PLpgSQL_recfield *) target;
5140  PLpgSQL_rec *rec;
5141  ExpandedRecordHeader *erh;
5142 
5143  rec = (PLpgSQL_rec *) (estate->datums[recfield->recparentno]);
5144  erh = rec->erh;
5145 
5146  /*
5147  * If record variable is NULL, instantiate it if it has a
5148  * named composite type, else complain. (This won't change
5149  * the logical state of the record, but if we successfully
5150  * assign below, the unassigned fields will all become NULLs.)
5151  */
5152  if (erh == NULL)
5153  {
5154  instantiate_empty_record_variable(estate, rec);
5155  erh = rec->erh;
5156  }
5157 
5158  /*
5159  * Look up the field's properties if we have not already, or
5160  * if the tuple descriptor ID changed since last time.
5161  */
5162  if (unlikely(recfield->rectupledescid != erh->er_tupdesc_id))
5163  {
5165  recfield->fieldname,
5166  &recfield->finfo))
5167  ereport(ERROR,
5168  (errcode(ERRCODE_UNDEFINED_COLUMN),
5169  errmsg("record \"%s\" has no field \"%s\"",
5170  rec->refname, recfield->fieldname)));
5171  recfield->rectupledescid = erh->er_tupdesc_id;
5172  }
5173 
5174  /* We don't support assignments to system columns. */
5175  if (recfield->finfo.fnumber <= 0)
5176  ereport(ERROR,
5177  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5178  errmsg("cannot assign to system column \"%s\"",
5179  recfield->fieldname)));
5180 
5181  /* Cast the new value to the right type, if needed. */
5182  value = exec_cast_value(estate,
5183  value,
5184  &isNull,
5185  valtype,
5186  valtypmod,
5187  recfield->finfo.ftypeid,
5188  recfield->finfo.ftypmod);
5189 
5190  /* And assign it. */
5191  expanded_record_set_field(erh, recfield->finfo.fnumber,
5192  value, isNull, !estate->atomic);
5193  break;
5194  }
5195 
5197  {
5198  /*
5199  * Target is an element of an array
5200  */
5201  PLpgSQL_arrayelem *arrayelem;
5202  int nsubscripts;
5203  int i;
5204  PLpgSQL_expr *subscripts[MAXDIM];
5205  int subscriptvals[MAXDIM];
5206  Datum oldarraydatum,
5207  newarraydatum,
5208  coerced_value;
5209  bool oldarrayisnull;
5210  Oid parenttypoid;
5211  int32 parenttypmod;
5212  SPITupleTable *save_eval_tuptable;
5213  MemoryContext oldcontext;
5214 
5215  /*
5216  * We need to do subscript evaluation, which might require
5217  * evaluating general expressions; and the caller might have
5218  * done that too in order to prepare the input Datum. We have
5219  * to save and restore the caller's SPI_execute result, if
5220  * any.
5221  */
5222  save_eval_tuptable = estate->eval_tuptable;
5223  estate->eval_tuptable = NULL;
5224 
5225  /*
5226  * To handle constructs like x[1][2] := something, we have to
5227  * be prepared to deal with a chain of arrayelem datums. Chase
5228  * back to find the base array datum, and save the subscript
5229  * expressions as we go. (We are scanning right to left here,
5230  * but want to evaluate the subscripts left-to-right to
5231  * minimize surprises.) Note that arrayelem is left pointing
5232  * to the leftmost arrayelem datum, where we will cache the
5233  * array element type data.
5234  */
5235  nsubscripts = 0;
5236  do
5237  {
5238  arrayelem = (PLpgSQL_arrayelem *) target;
5239  if (nsubscripts >= MAXDIM)
5240  ereport(ERROR,
5241  (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
5242  errmsg("number of array dimensions (%d) exceeds the maximum allowed (%d)",
5243  nsubscripts + 1, MAXDIM)));
5244  subscripts[nsubscripts++] = arrayelem->subscript;
5245  target = estate->datums[arrayelem->arrayparentno];
5246  } while (target->dtype == PLPGSQL_DTYPE_ARRAYELEM);
5247 
5248  /* Fetch current value of array datum */
5249  exec_eval_datum(estate, target,
5250  &parenttypoid, &parenttypmod,
5251  &oldarraydatum, &oldarrayisnull);
5252 
5253  /* Update cached type data if necessary */
5254  if (arrayelem->parenttypoid != parenttypoid ||
5255  arrayelem->parenttypmod != parenttypmod)
5256  {
5257  Oid arraytypoid;
5258  int32 arraytypmod = parenttypmod;
5259  int16 arraytyplen;
5260  Oid elemtypoid;
5261  int16 elemtyplen;
5262  bool elemtypbyval;
5263  char elemtypalign;
5264 
5265  /* If target is domain over array, reduce to base type */
5266  arraytypoid = getBaseTypeAndTypmod(parenttypoid,
5267  &arraytypmod);
5268 
5269  /* ... and identify the element type */
5270  elemtypoid = get_element_type(arraytypoid);
5271  if (!OidIsValid(elemtypoid))
5272  ereport(ERROR,
5273  (errcode(ERRCODE_DATATYPE_MISMATCH),
5274  errmsg("subscripted object is not an array")));
5275 
5276  /* Collect needed data about the types */
5277  arraytyplen = get_typlen(arraytypoid);
5278 
5279  get_typlenbyvalalign(elemtypoid,
5280  &elemtyplen,
5281  &elemtypbyval,
5282  &elemtypalign);
5283 
5284  /* Now safe to update the cached data */
5285  arrayelem->parenttypoid = parenttypoid;
5286  arrayelem->parenttypmod = parenttypmod;
5287  arrayelem->arraytypoid = arraytypoid;
5288  arrayelem->arraytypmod = arraytypmod;
5289  arrayelem->arraytyplen = arraytyplen;
5290  arrayelem->elemtypoid = elemtypoid;
5291  arrayelem->elemtyplen = elemtyplen;
5292  arrayelem->elemtypbyval = elemtypbyval;
5293  arrayelem->elemtypalign = elemtypalign;
5294  }
5295 
5296  /*
5297  * Evaluate the subscripts, switch into left-to-right order.
5298  * Like the expression built by ExecInitSubscriptingRef(),
5299  * complain if any subscript is null.
5300  */
5301  for (i = 0; i < nsubscripts; i++)
5302  {
5303  bool subisnull;
5304 
5305  subscriptvals[i] =
5306  exec_eval_integer(estate,
5307  subscripts[nsubscripts - 1 - i],
5308  &subisnull);
5309  if (subisnull)
5310  ereport(ERROR,
5311  (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
5312  errmsg("array subscript in assignment must not be null")));
5313 
5314  /*
5315  * Clean up in case the subscript expression wasn't
5316  * simple. We can't do exec_eval_cleanup, but we can do
5317  * this much (which is safe because the integer subscript
5318  * value is surely pass-by-value), and we must do it in
5319  * case the next subscript expression isn't simple either.
5320  */
5321  if (estate->eval_tuptable != NULL)
5323  estate->eval_tuptable = NULL;
5324  }
5325 
5326  /* Now we can restore caller's SPI_execute result if any. */
5327  Assert(estate->eval_tuptable == NULL);
5328  estate->eval_tuptable = save_eval_tuptable;
5329 
5330  /* Coerce source value to match array element type. */
5331  coerced_value = exec_cast_value(estate,
5332  value,
5333  &isNull,
5334  valtype,
5335  valtypmod,
5336  arrayelem->elemtypoid,
5337  arrayelem->arraytypmod);
5338 
5339  /*
5340  * If the original array is null, cons up an empty array so
5341  * that the assignment can proceed; we'll end with a
5342  * one-element array containing just the assigned-to
5343  * subscript. This only works for varlena arrays, though; for
5344  * fixed-length array types we skip the assignment. We can't
5345  * support assignment of a null entry into a fixed-length
5346  * array, either, so that's a no-op too. This is all ugly but
5347  * corresponds to the current behavior of execExpr*.c.
5348  */
5349  if (arrayelem->arraytyplen > 0 && /* fixed-length array? */
5350  (oldarrayisnull || isNull))
5351  return;
5352 
5353  /* empty array, if any, and newarraydatum are short-lived */
5354  oldcontext = MemoryContextSwitchTo(get_eval_mcontext(estate));
5355 
5356  if (oldarrayisnull)
5357  oldarraydatum = PointerGetDatum(construct_empty_array(arrayelem->elemtypoid));
5358 
5359  /*
5360  * Build the modified array value.
5361  */
5362  newarraydatum = array_set_element(oldarraydatum,
5363  nsubscripts,
5364  subscriptvals,
5365  coerced_value,
5366  isNull,
5367  arrayelem->arraytyplen,
5368  arrayelem->elemtyplen,
5369  arrayelem->elemtypbyval,
5370  arrayelem->elemtypalign);
5371 
5372  MemoryContextSwitchTo(oldcontext);
5373 
5374  /*
5375  * Assign the new array to the base variable. It's never NULL
5376  * at this point. Note that if the target is a domain,
5377  * coercing the base array type back up to the domain will
5378  * happen within exec_assign_value.
5379  */
5380  exec_assign_value(estate, target,
5381  newarraydatum,
5382  false,
5383  arrayelem->arraytypoid,
5384  arrayelem->arraytypmod);
5385  break;
5386  }
5387 
5388  default:
5389  elog(ERROR, "unrecognized dtype: %d", target->dtype);
5390  }
5391 }
5392 
5393 /*
5394  * exec_eval_datum Get current value of a PLpgSQL_datum
5395  *
5396  * The type oid, typmod, value in Datum format, and null flag are returned.
5397  *
5398  * At present this doesn't handle PLpgSQL_expr or PLpgSQL_arrayelem datums;
5399  * that's not needed because we never pass references to such datums to SPI.
5400  *
5401  * NOTE: the returned Datum points right at the stored value in the case of
5402  * pass-by-reference datatypes. Generally callers should take care not to
5403  * modify the stored value. Some callers intentionally manipulate variables
5404  * referenced by R/W expanded pointers, though; it is those callers'
5405  * responsibility that the results are semantically OK.
5406  *
5407  * In some cases we have to palloc a return value, and in such cases we put
5408  * it into the estate's eval_mcontext.
5409  */
5410 static void
5412  PLpgSQL_datum *datum,
5413  Oid *typeid,
5414  int32 *typetypmod,
5415  Datum *value,
5416  bool *isnull)
5417 {
5418  MemoryContext oldcontext;
5419 
5420  switch (datum->dtype)
5421  {
5422  case PLPGSQL_DTYPE_PROMISE:
5423  /* fulfill promise if needed, then handle like regular var */
5424  plpgsql_fulfill_promise(estate, (PLpgSQL_var *) datum);
5425 
5426  /* FALL THRU */
5427 
5428  case PLPGSQL_DTYPE_VAR:
5429  {
5430  PLpgSQL_var *var = (PLpgSQL_var *) datum;
5431 
5432  *typeid = var->datatype->typoid;
5433  *typetypmod = var->datatype->atttypmod;
5434  *value = var->value;
5435  *isnull = var->isnull;
5436  break;
5437  }
5438 
5439  case PLPGSQL_DTYPE_ROW:
5440  {
5441  PLpgSQL_row *row = (PLpgSQL_row *) datum;
5442  HeapTuple tup;
5443 
5444  /* We get here if there are multiple OUT parameters */
5445  if (!row->rowtupdesc) /* should not happen */
5446  elog(ERROR, "row variable has no tupdesc");
5447  /* Make sure we have a valid type/typmod setting */
5448  BlessTupleDesc(row->rowtupdesc);
5449  oldcontext = MemoryContextSwitchTo(get_eval_mcontext(estate));
5450  tup = make_tuple_from_row(estate, row, row->rowtupdesc);
5451  if (tup == NULL) /* should not happen */
5452  elog(ERROR, "row not compatible with its own tupdesc");
5453  *typeid = row->rowtupdesc->tdtypeid;
5454  *typetypmod = row->rowtupdesc->tdtypmod;
5455  *value = HeapTupleGetDatum(tup);
5456  *isnull = false;
5457  MemoryContextSwitchTo(oldcontext);
5458  break;
5459  }
5460 
5461  case PLPGSQL_DTYPE_REC:
5462  {
5463  PLpgSQL_rec *rec = (PLpgSQL_rec *) datum;
5464 
5465  if (rec->erh == NULL)
5466  {
5467  /* Treat uninstantiated record as a simple NULL */
5468  *value = (Datum) 0;
5469  *isnull = true;
5470  /* Report variable's declared type */
5471  *typeid = rec->rectypeid;
5472  *typetypmod = -1;
5473  }
5474  else
5475  {
5476  if (ExpandedRecordIsEmpty(rec->erh))
5477  {
5478  /* Empty record is also a NULL */
5479  *value = (Datum) 0;
5480  *isnull = true;
5481  }
5482  else
5483  {
5484  *value = ExpandedRecordGetDatum(rec->erh);
5485  *isnull = false;
5486  }
5487  if (rec->rectypeid != RECORDOID)
5488  {
5489  /* Report variable's declared type, if not RECORD */
5490  *typeid = rec->rectypeid;
5491  *typetypmod = -1;
5492  }
5493  else
5494  {
5495  /* Report record's actual type if declared RECORD */
5496  *typeid = rec->erh->er_typeid;
5497  *typetypmod = rec->erh->er_typmod;
5498  }
5499  }
5500  break;
5501  }
5502 
5504  {
5505  PLpgSQL_recfield *recfield = (PLpgSQL_recfield *) datum;
5506  PLpgSQL_rec *rec;
5507  ExpandedRecordHeader *erh;
5508 
5509  rec = (PLpgSQL_rec *) (estate->datums[recfield->recparentno]);
5510  erh = rec->erh;
5511 
5512  /*
5513  * If record variable is NULL, instantiate it if it has a
5514  * named composite type, else complain. (This won't change
5515  * the logical state of the record: it's still NULL.)
5516  */
5517  if (erh == NULL)
5518  {
5519  instantiate_empty_record_variable(estate, rec);
5520  erh = rec->erh;
5521  }
5522 
5523  /*
5524  * Look up the field's properties if we have not already, or
5525  * if the tuple descriptor ID changed since last time.
5526  */
5527  if (unlikely(recfield->rectupledescid != erh->er_tupdesc_id))
5528  {
5530  recfield->fieldname,
5531  &recfield->finfo))
5532  ereport(ERROR,
5533  (errcode(ERRCODE_UNDEFINED_COLUMN),
5534  errmsg("record \"%s\" has no field \"%s\"",
5535  rec->refname, recfield->fieldname)));
5536  recfield->rectupledescid = erh->er_tupdesc_id;
5537  }
5538 
5539  /* Report type data. */
5540  *typeid = recfield->finfo.ftypeid;
5541  *typetypmod = recfield->finfo.ftypmod;
5542 
5543  /* And fetch the field value. */
5544  *value = expanded_record_get_field(erh,
5545  recfield->finfo.fnumber,
5546  isnull);
5547  break;
5548  }
5549 
5550  default:
5551  elog(ERROR, "unrecognized dtype: %d", datum->dtype);
5552  }
5553 }
5554 
5555 /*
5556  * plpgsql_exec_get_datum_type Get datatype of a PLpgSQL_datum
5557  *
5558  * This is the same logic as in exec_eval_datum, but we skip acquiring
5559  * the actual value of the variable. Also, needn't support DTYPE_ROW.
5560  */
5561 Oid
5563  PLpgSQL_datum *datum)
5564 {
5565  Oid typeid;
5566 
5567  switch (datum->dtype)
5568  {
5569  case PLPGSQL_DTYPE_VAR:
5570  case PLPGSQL_DTYPE_PROMISE:
5571  {
5572  PLpgSQL_var *var = (PLpgSQL_var *) datum;
5573 
5574  typeid = var->datatype->typoid;
5575  break;
5576  }
5577 
5578  case PLPGSQL_DTYPE_REC:
5579  {
5580  PLpgSQL_rec *rec = (PLpgSQL_rec *) datum;
5581 
5582  if (rec->erh == NULL || rec->rectypeid != RECORDOID)
5583  {
5584  /* Report variable's declared type */
5585  typeid = rec->rectypeid;
5586  }
5587  else
5588  {
5589  /* Report record's actual type if declared RECORD */
5590  typeid = rec->erh->er_typeid;
5591  }
5592  break;
5593  }
5594 
5596  {
5597  PLpgSQL_recfield *recfield = (PLpgSQL_recfield *) datum;
5598  PLpgSQL_rec *rec;
5599 
5600  rec = (PLpgSQL_rec *) (estate->datums[recfield->recparentno]);
5601 
5602  /*
5603  * If record variable is NULL, instantiate it if it has a
5604  * named composite type, else complain. (This won't change
5605  * the logical state of the record: it's still NULL.)
5606  */
5607  if (rec->erh == NULL)
5608  instantiate_empty_record_variable(estate, rec);
5609 
5610  /*
5611  * Look up the field's properties if we have not already, or
5612  * if the tuple descriptor ID changed since last time.
5613  */
5614  if (unlikely(recfield->rectupledescid != rec->erh->er_tupdesc_id))
5615  {
5617  recfield->fieldname,
5618  &recfield->finfo))
5619  ereport(ERROR,
5620  (errcode(ERRCODE_UNDEFINED_COLUMN),
5621  errmsg("record \"%s\" has no field \"%s\"",
5622  rec->refname, recfield->fieldname)));
5623  recfield->rectupledescid = rec->erh->er_tupdesc_id;
5624  }
5625 
5626  typeid = recfield->finfo.ftypeid;
5627  break;
5628  }
5629 
5630  default:
5631  elog(ERROR, "unrecognized dtype: %d", datum->dtype);
5632  typeid = InvalidOid; /* keep compiler quiet */
5633  break;
5634  }
5635 
5636  return typeid;
5637 }
5638 
5639 /*
5640  * plpgsql_exec_get_datum_type_info Get datatype etc of a PLpgSQL_datum
5641  *
5642  * An extended version of plpgsql_exec_get_datum_type, which also retrieves the
5643  * typmod and collation of the datum. Note however that we don't report the
5644  * possibly-mutable typmod of RECORD values, but say -1 always.
5645  */
5646 void
5648  PLpgSQL_datum *datum,
5649  Oid *typeId, int32 *typMod, Oid *collation)
5650 {
5651  switch (datum->dtype)
5652  {
5653  case PLPGSQL_DTYPE_VAR:
5654  case PLPGSQL_DTYPE_PROMISE:
5655  {
5656  PLpgSQL_var *var = (PLpgSQL_var *) datum;
5657 
5658  *typeId = var->datatype->typoid;
5659  *typMod = var->datatype->atttypmod;
5660  *collation = var->datatype->collation;
5661  break;
5662  }
5663 
5664  case PLPGSQL_DTYPE_REC:
5665  {
5666  PLpgSQL_rec *rec = (PLpgSQL_rec *) datum;
5667 
5668  if (rec->erh == NULL || rec->rectypeid != RECORDOID)
5669  {
5670  /* Report variable's declared type */
5671  *typeId = rec->rectypeid;
5672  *typMod = -1;
5673  }
5674  else
5675  {
5676  /* Report record's actual type if declared RECORD */
5677  *typeId = rec->erh->er_typeid;
5678  /* do NOT return the