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