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