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