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 static int
2151 {
2152  PLpgSQL_expr *expr = stmt->expr;
2153  volatile LocalTransactionId before_lxid;
2154  LocalTransactionId after_lxid;
2155  volatile bool pushed_active_snap = false;
2156  volatile int rc;
2157 
2158  /* PG_TRY to ensure we clear the plan link, if needed, on failure */
2159  PG_TRY();
2160  {
2161  SPIPlanPtr plan = expr->plan;
2162  ParamListInfo paramLI;
2163 
2164  if (plan == NULL)
2165  {
2166 
2167  /*
2168  * Don't save the plan if not in atomic context. Otherwise,
2169  * transaction ends would cause errors about plancache leaks.
2170  *
2171  * XXX This would be fixable with some plancache/resowner surgery
2172  * elsewhere, but for now we'll just work around this here.
2173  */
2174  exec_prepare_plan(estate, expr, 0, estate->atomic);
2175 
2176  /*
2177  * The procedure call could end transactions, which would upset
2178  * the snapshot management in SPI_execute*, so don't let it do it.
2179  * Instead, we set the snapshots ourselves below.
2180  */
2181  plan = expr->plan;
2182  plan->no_snapshots = true;
2183 
2184  /*
2185  * Force target to be recalculated whenever the plan changes, in
2186  * case the procedure's argument list has changed.
2187  */
2188  stmt->target = NULL;
2189  }
2190 
2191  /*
2192  * We construct a DTYPE_ROW datum representing the plpgsql variables
2193  * associated with the procedure's output arguments. Then we can use
2194  * exec_move_row() to do the assignments.
2195  */
2196  if (stmt->is_call && stmt->target == NULL)
2197  {
2198  Node *node;
2199  FuncExpr *funcexpr;
2200  HeapTuple func_tuple;
2201  List *funcargs;
2202  Oid *argtypes;
2203  char **argnames;
2204  char *argmodes;
2205  MemoryContext oldcontext;
2206  PLpgSQL_row *row;
2207  int nfields;
2208  int i;
2209  ListCell *lc;
2210 
2211  /*
2212  * Get the parsed CallStmt, and look up the called procedure
2213  */
2214  node = linitial_node(Query,
2215  ((CachedPlanSource *) linitial(plan->plancache_list))->query_list)->utilityStmt;
2216  if (node == NULL || !IsA(node, CallStmt))
2217  elog(ERROR, "query for CALL statement is not a CallStmt");
2218 
2219  funcexpr = ((CallStmt *) node)->funcexpr;
2220 
2221  func_tuple = SearchSysCache1(PROCOID,
2222  ObjectIdGetDatum(funcexpr->funcid));
2223  if (!HeapTupleIsValid(func_tuple))
2224  elog(ERROR, "cache lookup failed for function %u",
2225  funcexpr->funcid);
2226 
2227  /*
2228  * Extract function arguments, and expand any named-arg notation
2229  */
2230  funcargs = expand_function_arguments(funcexpr->args,
2231  funcexpr->funcresulttype,
2232  func_tuple);
2233 
2234  /*
2235  * Get the argument names and modes, too
2236  */
2237  get_func_arg_info(func_tuple, &argtypes, &argnames, &argmodes);
2238 
2239  ReleaseSysCache(func_tuple);
2240 
2241  /*
2242  * Begin constructing row Datum
2243  */
2244  oldcontext = MemoryContextSwitchTo(estate->func->fn_cxt);
2245 
2246  row = (PLpgSQL_row *) palloc0(sizeof(PLpgSQL_row));
2247  row->dtype = PLPGSQL_DTYPE_ROW;
2248  row->refname = "(unnamed row)";
2249  row->lineno = -1;
2250  row->varnos = (int *) palloc(sizeof(int) * list_length(funcargs));
2251 
2252  MemoryContextSwitchTo(oldcontext);
2253 
2254  /*
2255  * Examine procedure's argument list. Each output arg position
2256  * should be an unadorned plpgsql variable (Datum), which we can
2257  * insert into the row Datum.
2258  */
2259  nfields = 0;
2260  i = 0;
2261  foreach(lc, funcargs)
2262  {
2263  Node *n = lfirst(lc);
2264 
2265  if (argmodes &&
2266  (argmodes[i] == PROARGMODE_INOUT ||
2267  argmodes[i] == PROARGMODE_OUT))
2268  {
2269  if (IsA(n, Param))
2270  {
2271  Param *param = (Param *) n;
2272 
2273  /* paramid is offset by 1 (see make_datum_param()) */
2274  row->varnos[nfields++] = param->paramid - 1;
2275  }
2276  else
2277  {
2278  /* report error using parameter name, if available */
2279  if (argnames && argnames[i] && argnames[i][0])
2280  ereport(ERROR,
2281  (errcode(ERRCODE_SYNTAX_ERROR),
2282  errmsg("procedure parameter \"%s\" is an output parameter but corresponding argument is not writable",
2283  argnames[i])));
2284  else
2285  ereport(ERROR,
2286  (errcode(ERRCODE_SYNTAX_ERROR),
2287  errmsg("procedure parameter %d is an output parameter but corresponding argument is not writable",
2288  i + 1)));
2289  }
2290  }
2291  i++;
2292  }
2293 
2294  row->nfields = nfields;
2295 
2296  stmt->target = (PLpgSQL_variable *) row;
2297  }
2298 
2299  paramLI = setup_param_list(estate, expr);
2300 
2301  before_lxid = MyProc->lxid;
2302 
2303  /*
2304  * Set snapshot only for non-read-only procedures, similar to SPI
2305  * behavior.
2306  */
2307  if (!estate->readonly_func)
2308  {
2310  pushed_active_snap = true;
2311  }
2312 
2313  rc = SPI_execute_plan_with_paramlist(expr->plan, paramLI,
2314  estate->readonly_func, 0);
2315  }
2316  PG_CATCH();
2317  {
2318  /*
2319  * If we aren't saving the plan, unset the pointer. Note that it
2320  * could have been unset already, in case of a recursive call.
2321  */
2322  if (expr->plan && !expr->plan->saved)
2323  expr->plan = NULL;
2324  PG_RE_THROW();
2325  }
2326  PG_END_TRY();
2327 
2328  if (expr->plan && !expr->plan->saved)
2329  expr->plan = NULL;
2330 
2331  if (rc < 0)
2332  elog(ERROR, "SPI_execute_plan_with_paramlist failed executing query \"%s\": %s",
2333  expr->query, SPI_result_code_string(rc));
2334 
2335  after_lxid = MyProc->lxid;
2336 
2337  if (before_lxid == after_lxid)
2338  {
2339  /*
2340  * If we are still in the same transaction after the call, pop the
2341  * snapshot that we might have pushed. (If it's a new transaction,
2342  * then all the snapshots are gone already.)
2343  */
2344  if (pushed_active_snap)
2346  }
2347  else
2348  {
2349  /*
2350  * If we are in a new transaction after the call, we need to build new
2351  * simple-expression infrastructure.
2352  */
2353  estate->simple_eval_estate = NULL;
2354  estate->simple_eval_resowner = NULL;
2355  plpgsql_create_econtext(estate);
2356  }
2357 
2358  /*
2359  * Check result rowcount; if there's one row, assign procedure's output
2360  * values back to the appropriate variables.
2361  */
2362  if (SPI_processed == 1)
2363  {
2364  SPITupleTable *tuptab = SPI_tuptable;
2365 
2366  if (!stmt->target)
2367  elog(ERROR, "DO statement returned a row");
2368 
2369  exec_move_row(estate, stmt->target, tuptab->vals[0], tuptab->tupdesc);
2370  }
2371  else if (SPI_processed > 1)
2372  elog(ERROR, "procedure call returned more than one row");
2373 
2374  exec_eval_cleanup(estate);
2376 
2377  return PLPGSQL_RC_OK;
2378 }
2379 
2380 /* ----------
2381  * exec_stmt_getdiag Put internal PG information into
2382  * specified variables.
2383  * ----------
2384  */
2385 static int
2387 {
2388  ListCell *lc;
2389 
2390  /*
2391  * GET STACKED DIAGNOSTICS is only valid inside an exception handler.
2392  *
2393  * Note: we trust the grammar to have disallowed the relevant item kinds
2394  * if not is_stacked, otherwise we'd dump core below.
2395  */
2396  if (stmt->is_stacked && estate->cur_error == NULL)
2397  ereport(ERROR,
2398  (errcode(ERRCODE_STACKED_DIAGNOSTICS_ACCESSED_WITHOUT_ACTIVE_HANDLER),
2399  errmsg("GET STACKED DIAGNOSTICS cannot be used outside an exception handler")));
2400 
2401  foreach(lc, stmt->diag_items)
2402  {
2403  PLpgSQL_diag_item *diag_item = (PLpgSQL_diag_item *) lfirst(lc);
2404  PLpgSQL_datum *var = estate->datums[diag_item->target];
2405 
2406  switch (diag_item->kind)
2407  {
2409  exec_assign_value(estate, var,
2410  UInt64GetDatum(estate->eval_processed),
2411  false, INT8OID, -1);
2412  break;
2413 
2415  exec_assign_c_string(estate, var,
2416  estate->cur_error->context);
2417  break;
2418 
2420  exec_assign_c_string(estate, var,
2421  estate->cur_error->detail);
2422  break;
2423 
2425  exec_assign_c_string(estate, var,
2426  estate->cur_error->hint);
2427  break;
2428 
2430  exec_assign_c_string(estate, var,
2432  break;
2433 
2435  exec_assign_c_string(estate, var,
2436  estate->cur_error->column_name);
2437  break;
2438 
2440  exec_assign_c_string(estate, var,
2441  estate->cur_error->constraint_name);
2442  break;
2443 
2445  exec_assign_c_string(estate, var,
2446  estate->cur_error->datatype_name);
2447  break;
2448 
2450  exec_assign_c_string(estate, var,
2451  estate->cur_error->message);
2452  break;
2453 
2455  exec_assign_c_string(estate, var,
2456  estate->cur_error->table_name);
2457  break;
2458 
2460  exec_assign_c_string(estate, var,
2461  estate->cur_error->schema_name);
2462  break;
2463 
2465  {
2466  char *contextstackstr;
2467  MemoryContext oldcontext;
2468 
2469  /* Use eval_mcontext for short-lived string */
2470  oldcontext = MemoryContextSwitchTo(get_eval_mcontext(estate));
2471  contextstackstr = GetErrorContextStack();
2472  MemoryContextSwitchTo(oldcontext);
2473 
2474  exec_assign_c_string(estate, var, contextstackstr);
2475  }
2476  break;
2477 
2478  default:
2479  elog(ERROR, "unrecognized diagnostic item kind: %d",
2480  diag_item->kind);
2481  }
2482  }
2483 
2484  exec_eval_cleanup(estate);
2485 
2486  return PLPGSQL_RC_OK;
2487 }
2488 
2489 /* ----------
2490  * exec_stmt_if Evaluate a bool expression and
2491  * execute the true or false body
2492  * conditionally.
2493  * ----------
2494  */
2495 static int
2497 {
2498  bool value;
2499  bool isnull;
2500  ListCell *lc;
2501 
2502  value = exec_eval_boolean(estate, stmt->cond, &isnull);
2503  exec_eval_cleanup(estate);
2504  if (!isnull && value)
2505  return exec_stmts(estate, stmt->then_body);
2506 
2507  foreach(lc, stmt->elsif_list)
2508  {
2509  PLpgSQL_if_elsif *elif = (PLpgSQL_if_elsif *) lfirst(lc);
2510 
2511  value = exec_eval_boolean(estate, elif->cond, &isnull);
2512  exec_eval_cleanup(estate);
2513  if (!isnull && value)
2514  return exec_stmts(estate, elif->stmts);
2515  }
2516 
2517  return exec_stmts(estate, stmt->else_body);
2518 }
2519 
2520 
2521 /*-----------
2522  * exec_stmt_case
2523  *-----------
2524  */
2525 static int
2527 {
2528  PLpgSQL_var *t_var = NULL;
2529  bool isnull;
2530  ListCell *l;
2531 
2532  if (stmt->t_expr != NULL)
2533  {
2534  /* simple case */
2535  Datum t_val;
2536  Oid t_typoid;
2537  int32 t_typmod;
2538 
2539  t_val = exec_eval_expr(estate, stmt->t_expr,
2540  &isnull, &t_typoid, &t_typmod);
2541 
2542  t_var = (PLpgSQL_var *) estate->datums[stmt->t_varno];
2543 
2544  /*
2545  * When expected datatype is different from real, change it. Note that
2546  * what we're modifying here is an execution copy of the datum, so
2547  * this doesn't affect the originally stored function parse tree. (In
2548  * theory, if the expression datatype keeps changing during execution,
2549  * this could cause a function-lifespan memory leak. Doesn't seem
2550  * worth worrying about though.)
2551  */
2552  if (t_var->datatype->typoid != t_typoid ||
2553  t_var->datatype->atttypmod != t_typmod)
2554  t_var->datatype = plpgsql_build_datatype(t_typoid,
2555  t_typmod,
2556  estate->func->fn_input_collation,
2557  NULL);
2558 
2559  /* now we can assign to the variable */
2560  exec_assign_value(estate,
2561  (PLpgSQL_datum *) t_var,
2562  t_val,
2563  isnull,
2564  t_typoid,
2565  t_typmod);
2566 
2567  exec_eval_cleanup(estate);
2568  }
2569 
2570  /* Now search for a successful WHEN clause */
2571  foreach(l, stmt->case_when_list)
2572  {
2574  bool value;
2575 
2576  value = exec_eval_boolean(estate, cwt->expr, &isnull);
2577  exec_eval_cleanup(estate);
2578  if (!isnull && value)
2579  {
2580  /* Found it */
2581 
2582  /* We can now discard any value we had for the temp variable */
2583  if (t_var != NULL)
2584  assign_simple_var(estate, t_var, (Datum) 0, true, false);
2585 
2586  /* Evaluate the statement(s), and we're done */
2587  return exec_stmts(estate, cwt->stmts);
2588  }
2589  }
2590 
2591  /* We can now discard any value we had for the temp variable */
2592  if (t_var != NULL)
2593  assign_simple_var(estate, t_var, (Datum) 0, true, false);
2594 
2595  /* SQL2003 mandates this error if there was no ELSE clause */
2596  if (!stmt->have_else)
2597  ereport(ERROR,
2598  (errcode(ERRCODE_CASE_NOT_FOUND),
2599  errmsg("case not found"),
2600  errhint("CASE statement is missing ELSE part.")));
2601 
2602  /* Evaluate the ELSE statements, and we're done */
2603  return exec_stmts(estate, stmt->else_stmts);
2604 }
2605 
2606 
2607 /* ----------
2608  * exec_stmt_loop Loop over statements until
2609  * an exit occurs.
2610  * ----------
2611  */
2612 static int
2614 {
2615  int rc = PLPGSQL_RC_OK;
2616 
2617  for (;;)
2618  {
2619  rc = exec_stmts(estate, stmt->body);
2620 
2621  LOOP_RC_PROCESSING(stmt->label, break);
2622  }
2623 
2624  return rc;
2625 }
2626 
2627 
2628 /* ----------
2629  * exec_stmt_while Loop over statements as long
2630  * as an expression evaluates to
2631  * true or an exit occurs.
2632  * ----------
2633  */
2634 static int
2636 {
2637  int rc = PLPGSQL_RC_OK;
2638 
2639  for (;;)
2640  {
2641  bool value;
2642  bool isnull;
2643 
2644  value = exec_eval_boolean(estate, stmt->cond, &isnull);
2645  exec_eval_cleanup(estate);
2646 
2647  if (isnull || !value)
2648  break;
2649 
2650  rc = exec_stmts(estate, stmt->body);
2651 
2652  LOOP_RC_PROCESSING(stmt->label, break);
2653  }
2654 
2655  return rc;
2656 }
2657 
2658 
2659 /* ----------
2660  * exec_stmt_fori Iterate an integer variable
2661  * from a lower to an upper value
2662  * incrementing or decrementing by the BY value
2663  * ----------
2664  */
2665 static int
2667 {
2668  PLpgSQL_var *var;
2669  Datum value;
2670  bool isnull;
2671  Oid valtype;
2672  int32 valtypmod;
2673  int32 loop_value;
2674  int32 end_value;
2675  int32 step_value;
2676  bool found = false;
2677  int rc = PLPGSQL_RC_OK;
2678 
2679  var = (PLpgSQL_var *) (estate->datums[stmt->var->dno]);
2680 
2681  /*
2682  * Get the value of the lower bound
2683  */
2684  value = exec_eval_expr(estate, stmt->lower,
2685  &isnull, &valtype, &valtypmod);
2686  value = exec_cast_value(estate, value, &isnull,
2687  valtype, valtypmod,
2688  var->datatype->typoid,
2689  var->datatype->atttypmod);
2690  if (isnull)
2691  ereport(ERROR,
2692  (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
2693  errmsg("lower bound of FOR loop cannot be null")));
2694  loop_value = DatumGetInt32(value);
2695  exec_eval_cleanup(estate);
2696 
2697  /*
2698  * Get the value of the upper bound
2699  */
2700  value = exec_eval_expr(estate, stmt->upper,
2701  &isnull, &valtype, &valtypmod);
2702  value = exec_cast_value(estate, value, &isnull,
2703  valtype, valtypmod,
2704  var->datatype->typoid,
2705  var->datatype->atttypmod);
2706  if (isnull)
2707  ereport(ERROR,
2708  (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
2709  errmsg("upper bound of FOR loop cannot be null")));
2710  end_value = DatumGetInt32(value);
2711  exec_eval_cleanup(estate);
2712 
2713  /*
2714  * Get the step value
2715  */
2716  if (stmt->step)
2717  {
2718  value = exec_eval_expr(estate, stmt->step,
2719  &isnull, &valtype, &valtypmod);
2720  value = exec_cast_value(estate, value, &isnull,
2721  valtype, valtypmod,
2722  var->datatype->typoid,
2723  var->datatype->atttypmod);
2724  if (isnull)
2725  ereport(ERROR,
2726  (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
2727  errmsg("BY value of FOR loop cannot be null")));
2728  step_value = DatumGetInt32(value);
2729  exec_eval_cleanup(estate);
2730  if (step_value <= 0)
2731  ereport(ERROR,
2732  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
2733  errmsg("BY value of FOR loop must be greater than zero")));
2734  }
2735  else
2736  step_value = 1;
2737 
2738  /*
2739  * Now do the loop
2740  */
2741  for (;;)
2742  {
2743  /*
2744  * Check against upper bound
2745  */
2746  if (stmt->reverse)
2747  {
2748  if (loop_value < end_value)
2749  break;
2750  }
2751  else
2752  {
2753  if (loop_value > end_value)
2754  break;
2755  }
2756 
2757  found = true; /* looped at least once */
2758 
2759  /*
2760  * Assign current value to loop var
2761  */
2762  assign_simple_var(estate, var, Int32GetDatum(loop_value), false, false);
2763 
2764  /*
2765  * Execute the statements
2766  */
2767  rc = exec_stmts(estate, stmt->body);
2768 
2769  LOOP_RC_PROCESSING(stmt->label, break);
2770 
2771  /*
2772  * Increase/decrease loop value, unless it would overflow, in which
2773  * case exit the loop.
2774  */
2775  if (stmt->reverse)
2776  {
2777  if (loop_value < (PG_INT32_MIN + step_value))
2778  break;
2779  loop_value -= step_value;
2780  }
2781  else
2782  {
2783  if (loop_value > (PG_INT32_MAX - step_value))
2784  break;
2785  loop_value += step_value;
2786  }
2787  }
2788 
2789  /*
2790  * Set the FOUND variable to indicate the result of executing the loop
2791  * (namely, whether we looped one or more times). This must be set here so
2792  * that it does not interfere with the value of the FOUND variable inside
2793  * the loop processing itself.
2794  */
2795  exec_set_found(estate, found);
2796 
2797  return rc;
2798 }
2799 
2800 
2801 /* ----------
2802  * exec_stmt_fors Execute a query, assign each
2803  * tuple to a record or row and
2804  * execute a group of statements
2805  * for it.
2806  * ----------
2807  */
2808 static int
2810 {
2811  Portal portal;
2812  int rc;
2813 
2814  /*
2815  * Open the implicit cursor for the statement using exec_run_select
2816  */
2817  exec_run_select(estate, stmt->query, 0, &portal);
2818 
2819  /*
2820  * Execute the loop
2821  */
2822  rc = exec_for_query(estate, (PLpgSQL_stmt_forq *) stmt, portal, true);
2823 
2824  /*
2825  * Close the implicit cursor
2826  */
2827  SPI_cursor_close(portal);
2828 
2829  return rc;
2830 }
2831 
2832 
2833 /* ----------
2834  * exec_stmt_forc Execute a loop for each row from a cursor.
2835  * ----------
2836  */
2837 static int
2839 {
2840  PLpgSQL_var *curvar;
2841  MemoryContext stmt_mcontext = NULL;
2842  char *curname = NULL;
2843  PLpgSQL_expr *query;
2844  ParamListInfo paramLI;
2845  Portal portal;
2846  int rc;
2847 
2848  /* ----------
2849  * Get the cursor variable and if it has an assigned name, check
2850  * that it's not in use currently.
2851  * ----------
2852  */
2853  curvar = (PLpgSQL_var *) (estate->datums[stmt->curvar]);
2854  if (!curvar->isnull)
2855  {
2856  MemoryContext oldcontext;
2857 
2858  /* We only need stmt_mcontext to hold the cursor name string */
2859  stmt_mcontext = get_stmt_mcontext(estate);
2860  oldcontext = MemoryContextSwitchTo(stmt_mcontext);
2861  curname = TextDatumGetCString(curvar->value);
2862  MemoryContextSwitchTo(oldcontext);
2863 
2864  if (SPI_cursor_find(curname) != NULL)
2865  ereport(ERROR,
2866  (errcode(ERRCODE_DUPLICATE_CURSOR),
2867  errmsg("cursor \"%s\" already in use", curname)));
2868  }
2869 
2870  /* ----------
2871  * Open the cursor just like an OPEN command
2872  *
2873  * Note: parser should already have checked that statement supplies
2874  * args iff cursor needs them, but we check again to be safe.
2875  * ----------
2876  */
2877  if (stmt->argquery != NULL)
2878  {
2879  /* ----------
2880  * OPEN CURSOR with args. We fake a SELECT ... INTO ...
2881  * statement to evaluate the args and put 'em into the
2882  * internal row.
2883  * ----------
2884  */
2885  PLpgSQL_stmt_execsql set_args;
2886 
2887  if (curvar->cursor_explicit_argrow < 0)
2888  ereport(ERROR,
2889  (errcode(ERRCODE_SYNTAX_ERROR),
2890  errmsg("arguments given for cursor without arguments")));
2891 
2892  memset(&set_args, 0, sizeof(set_args));
2893  set_args.cmd_type = PLPGSQL_STMT_EXECSQL;
2894  set_args.lineno = stmt->lineno;
2895  set_args.sqlstmt = stmt->argquery;
2896  set_args.into = true;
2897  /* XXX historically this has not been STRICT */
2898  set_args.target = (PLpgSQL_variable *)
2899  (estate->datums[curvar->cursor_explicit_argrow]);
2900 
2901  if (exec_stmt_execsql(estate, &set_args) != PLPGSQL_RC_OK)
2902  elog(ERROR, "open cursor failed during argument processing");
2903  }
2904  else
2905  {
2906  if (curvar->cursor_explicit_argrow >= 0)
2907  ereport(ERROR,
2908  (errcode(ERRCODE_SYNTAX_ERROR),
2909  errmsg("arguments required for cursor")));
2910  }
2911 
2912  query = curvar->cursor_explicit_expr;
2913  Assert(query);
2914 
2915  if (query->plan == NULL)
2916  exec_prepare_plan(estate, query, curvar->cursor_options, true);
2917 
2918  /*
2919  * Set up ParamListInfo for this query
2920  */
2921  paramLI = setup_param_list(estate, query);
2922 
2923  /*
2924  * Open the cursor (the paramlist will get copied into the portal)
2925  */
2926  portal = SPI_cursor_open_with_paramlist(curname, query->plan,
2927  paramLI,
2928  estate->readonly_func);
2929  if (portal == NULL)
2930  elog(ERROR, "could not open cursor: %s",
2932 
2933  /*
2934  * If cursor variable was NULL, store the generated portal name in it
2935  */
2936  if (curname == NULL)
2937  assign_text_var(estate, curvar, portal->name);
2938 
2939  /*
2940  * Clean up before entering exec_for_query
2941  */
2942  exec_eval_cleanup(estate);
2943  if (stmt_mcontext)
2944  MemoryContextReset(stmt_mcontext);
2945 
2946  /*
2947  * Execute the loop. We can't prefetch because the cursor is accessible
2948  * to the user, for instance via UPDATE WHERE CURRENT OF within the loop.
2949  */
2950  rc = exec_for_query(estate, (PLpgSQL_stmt_forq *) stmt, portal, false);
2951 
2952  /* ----------
2953  * Close portal, and restore cursor variable if it was initially NULL.
2954  * ----------
2955  */
2956  SPI_cursor_close(portal);
2957 
2958  if (curname == NULL)
2959  assign_simple_var(estate, curvar, (Datum) 0, true, false);
2960 
2961  return rc;
2962 }
2963 
2964 
2965 /* ----------
2966  * exec_stmt_foreach_a Loop over elements or slices of an array
2967  *
2968  * When looping over elements, the loop variable is the same type that the
2969  * array stores (eg: integer), when looping through slices, the loop variable
2970  * is an array of size and dimensions to match the size of the slice.
2971  * ----------
2972  */
2973 static int
2975 {
2976  ArrayType *arr;
2977  Oid arrtype;
2978  int32 arrtypmod;
2979  PLpgSQL_datum *loop_var;
2980  Oid loop_var_elem_type;
2981  bool found = false;
2982  int rc = PLPGSQL_RC_OK;
2983  MemoryContext stmt_mcontext;
2984  MemoryContext oldcontext;
2986  Oid iterator_result_type;
2987  int32 iterator_result_typmod;
2988  Datum value;
2989  bool isnull;
2990 
2991  /* get the value of the array expression */
2992  value = exec_eval_expr(estate, stmt->expr, &isnull, &arrtype, &arrtypmod);
2993  if (isnull)
2994  ereport(ERROR,
2995  (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
2996  errmsg("FOREACH expression must not be null")));
2997 
2998  /*
2999  * Do as much as possible of the code below in stmt_mcontext, to avoid any
3000  * leaks from called subroutines. We need a private stmt_mcontext since
3001  * we'll be calling arbitrary statement code.
3002  */
3003  stmt_mcontext = get_stmt_mcontext(estate);
3004  push_stmt_mcontext(estate);
3005  oldcontext = MemoryContextSwitchTo(stmt_mcontext);
3006 
3007  /* check the type of the expression - must be an array */
3008  if (!OidIsValid(get_element_type(arrtype)))
3009  ereport(ERROR,
3010  (errcode(ERRCODE_DATATYPE_MISMATCH),
3011  errmsg("FOREACH expression must yield an array, not type %s",
3012  format_type_be(arrtype))));
3013 
3014  /*
3015  * We must copy the array into stmt_mcontext, else it will disappear in
3016  * exec_eval_cleanup. This is annoying, but cleanup will certainly happen
3017  * while running the loop body, so we have little choice.
3018  */
3019  arr = DatumGetArrayTypePCopy(value);
3020 
3021  /* Clean up any leftover temporary memory */
3022  exec_eval_cleanup(estate);
3023 
3024  /* Slice dimension must be less than or equal to array dimension */
3025  if (stmt->slice < 0 || stmt->slice > ARR_NDIM(arr))
3026  ereport(ERROR,
3027  (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
3028  errmsg("slice dimension (%d) is out of the valid range 0..%d",
3029  stmt->slice, ARR_NDIM(arr))));
3030 
3031  /* Set up the loop variable and see if it is of an array type */
3032  loop_var = estate->datums[stmt->varno];
3033  if (loop_var->dtype == PLPGSQL_DTYPE_REC ||
3034  loop_var->dtype == PLPGSQL_DTYPE_ROW)
3035  {
3036  /*
3037  * Record/row variable is certainly not of array type, and might not
3038  * be initialized at all yet, so don't try to get its type
3039  */
3040  loop_var_elem_type = InvalidOid;
3041  }
3042  else
3043  loop_var_elem_type = get_element_type(plpgsql_exec_get_datum_type(estate,
3044  loop_var));
3045 
3046  /*
3047  * Sanity-check the loop variable type. We don't try very hard here, and
3048  * should not be too picky since it's possible that exec_assign_value can
3049  * coerce values of different types. But it seems worthwhile to complain
3050  * if the array-ness of the loop variable is not right.
3051  */
3052  if (stmt->slice > 0 && loop_var_elem_type == InvalidOid)
3053  ereport(ERROR,
3054  (errcode(ERRCODE_DATATYPE_MISMATCH),
3055  errmsg("FOREACH ... SLICE loop variable must be of an array type")));
3056  if (stmt->slice == 0 && loop_var_elem_type != InvalidOid)
3057  ereport(ERROR,
3058  (errcode(ERRCODE_DATATYPE_MISMATCH),
3059  errmsg("FOREACH loop variable must not be of an array type")));
3060 
3061  /* Create an iterator to step through the array */
3062  array_iterator = array_create_iterator(arr, stmt->slice, NULL);
3063 
3064  /* Identify iterator result type */
3065  if (stmt->slice > 0)
3066  {
3067  /* When slicing, nominal type of result is same as array type */
3068  iterator_result_type = arrtype;
3069  iterator_result_typmod = arrtypmod;
3070  }
3071  else
3072  {
3073  /* Without slicing, results are individual array elements */
3074  iterator_result_type = ARR_ELEMTYPE(arr);
3075  iterator_result_typmod = arrtypmod;
3076  }
3077 
3078  /* Iterate over the array elements or slices */
3079  while (array_iterate(array_iterator, &value, &isnull))
3080  {
3081  found = true; /* looped at least once */
3082 
3083  /* exec_assign_value and exec_stmts must run in the main context */
3084  MemoryContextSwitchTo(oldcontext);
3085 
3086  /* Assign current element/slice to the loop variable */
3087  exec_assign_value(estate, loop_var, value, isnull,
3088  iterator_result_type, iterator_result_typmod);
3089 
3090  /* In slice case, value is temporary; must free it to avoid leakage */
3091  if (stmt->slice > 0)
3092  pfree(DatumGetPointer(value));
3093 
3094  /*
3095  * Execute the statements
3096  */
3097  rc = exec_stmts(estate, stmt->body);
3098 
3099  LOOP_RC_PROCESSING(stmt->label, break);
3100 
3101  MemoryContextSwitchTo(stmt_mcontext);
3102  }
3103 
3104  /* Restore memory context state */
3105  MemoryContextSwitchTo(oldcontext);
3106  pop_stmt_mcontext(estate);
3107 
3108  /* Release temporary memory, including the array value */
3109  MemoryContextReset(stmt_mcontext);
3110 
3111  /*
3112  * Set the FOUND variable to indicate the result of executing the loop
3113  * (namely, whether we looped one or more times). This must be set here so
3114  * that it does not interfere with the value of the FOUND variable inside
3115  * the loop processing itself.
3116  */
3117  exec_set_found(estate, found);
3118 
3119  return rc;
3120 }
3121 
3122 
3123 /* ----------
3124  * exec_stmt_exit Implements EXIT and CONTINUE
3125  *
3126  * This begins the process of exiting / restarting a loop.
3127  * ----------
3128  */
3129 static int
3131 {
3132  /*
3133  * If the exit / continue has a condition, evaluate it
3134  */
3135  if (stmt->cond != NULL)
3136  {
3137  bool value;
3138  bool isnull;
3139 
3140  value = exec_eval_boolean(estate, stmt->cond, &isnull);
3141  exec_eval_cleanup(estate);
3142  if (isnull || value == false)
3143  return PLPGSQL_RC_OK;
3144  }
3145 
3146  estate->exitlabel = stmt->label;
3147  if (stmt->is_exit)
3148  return PLPGSQL_RC_EXIT;
3149  else
3150  return PLPGSQL_RC_CONTINUE;
3151 }
3152 
3153 
3154 /* ----------
3155  * exec_stmt_return Evaluate an expression and start
3156  * returning from the function.
3157  *
3158  * Note: The result may be in the eval_mcontext. Therefore, we must not
3159  * do exec_eval_cleanup while unwinding the control stack.
3160  * ----------
3161  */
3162 static int
3164 {
3165  /*
3166  * If processing a set-returning PL/pgSQL function, the final RETURN
3167  * indicates that the function is finished producing tuples. The rest of
3168  * the work will be done at the top level.
3169  */
3170  if (estate->retisset)
3171  return PLPGSQL_RC_RETURN;
3172 
3173  /* initialize for null result */
3174  estate->retval = (Datum) 0;
3175  estate->retisnull = true;
3176  estate->rettype = InvalidOid;
3177 
3178  /*
3179  * Special case path when the RETURN expression is a simple variable
3180  * reference; in particular, this path is always taken in functions with
3181  * one or more OUT parameters.
3182  *
3183  * This special case is especially efficient for returning variables that
3184  * have R/W expanded values: we can put the R/W pointer directly into
3185  * estate->retval, leading to transferring the value to the caller's
3186  * context cheaply. If we went through exec_eval_expr we'd end up with a
3187  * R/O pointer. It's okay to skip MakeExpandedObjectReadOnly here since
3188  * we know we won't need the variable's value within the function anymore.
3189  */
3190  if (stmt->retvarno >= 0)
3191  {
3192  PLpgSQL_datum *retvar = estate->datums[stmt->retvarno];
3193 
3194  switch (retvar->dtype)
3195  {
3196  case PLPGSQL_DTYPE_PROMISE:
3197  /* fulfill promise if needed, then handle like regular var */
3198  plpgsql_fulfill_promise(estate, (PLpgSQL_var *) retvar);
3199 
3200  /* FALL THRU */
3201 
3202  case PLPGSQL_DTYPE_VAR:
3203  {
3204  PLpgSQL_var *var = (PLpgSQL_var *) retvar;
3205 
3206  estate->retval = var->value;
3207  estate->retisnull = var->isnull;
3208  estate->rettype = var->datatype->typoid;
3209 
3210  /*
3211  * A PLpgSQL_var could not be of composite type, so
3212  * conversion must fail if retistuple. We throw a custom
3213  * error mainly for consistency with historical behavior.
3214  * For the same reason, we don't throw error if the result
3215  * is NULL. (Note that plpgsql_exec_trigger assumes that
3216  * any non-null result has been verified to be composite.)
3217  */
3218  if (estate->retistuple && !estate->retisnull)
3219  ereport(ERROR,
3220  (errcode(ERRCODE_DATATYPE_MISMATCH),
3221  errmsg("cannot return non-composite value from function returning composite type")));
3222  }
3223  break;
3224 
3225  case PLPGSQL_DTYPE_REC:
3226  {
3227  PLpgSQL_rec *rec = (PLpgSQL_rec *) retvar;
3228 
3229  /* If record is empty, we return NULL not a row of nulls */
3230  if (rec->erh && !ExpandedRecordIsEmpty(rec->erh))
3231  {
3232  estate->retval = ExpandedRecordGetDatum(rec->erh);
3233  estate->retisnull = false;
3234  estate->rettype = rec->rectypeid;
3235  }
3236  }
3237  break;
3238 
3239  case PLPGSQL_DTYPE_ROW:
3240  {
3241  PLpgSQL_row *row = (PLpgSQL_row *) retvar;
3242  int32 rettypmod;
3243 
3244  /* We get here if there are multiple OUT parameters */
3245  exec_eval_datum(estate,
3246  (PLpgSQL_datum *) row,
3247  &estate->rettype,
3248  &rettypmod,
3249  &estate->retval,
3250  &estate->retisnull);
3251  }
3252  break;
3253 
3254  default:
3255  elog(ERROR, "unrecognized dtype: %d", retvar->dtype);
3256  }
3257 
3258  return PLPGSQL_RC_RETURN;
3259  }
3260 
3261  if (stmt->expr != NULL)
3262  {
3263  int32 rettypmod;
3264 
3265  estate->retval = exec_eval_expr(estate, stmt->expr,
3266  &(estate->retisnull),
3267  &(estate->rettype),
3268  &rettypmod);
3269 
3270  /*
3271  * As in the DTYPE_VAR case above, throw a custom error if a non-null,
3272  * non-composite value is returned in a function returning tuple.
3273  */
3274  if (estate->retistuple && !estate->retisnull &&
3275  !type_is_rowtype(estate->rettype))
3276  ereport(ERROR,
3277  (errcode(ERRCODE_DATATYPE_MISMATCH),
3278  errmsg("cannot return non-composite value from function returning composite type")));
3279 
3280  return PLPGSQL_RC_RETURN;
3281  }
3282 
3283  /*
3284  * Special hack for function returning VOID: instead of NULL, return a
3285  * non-null VOID value. This is of dubious importance but is kept for
3286  * backwards compatibility. We don't do it for procedures, though.
3287  */
3288  if (estate->fn_rettype == VOIDOID &&
3289  estate->func->fn_prokind != PROKIND_PROCEDURE)
3290  {
3291  estate->retval = (Datum) 0;
3292  estate->retisnull = false;
3293  estate->rettype = VOIDOID;
3294  }
3295 
3296  return PLPGSQL_RC_RETURN;
3297 }
3298 
3299 /* ----------
3300  * exec_stmt_return_next Evaluate an expression and add it to the
3301  * list of tuples returned by the current
3302  * SRF.
3303  * ----------
3304  */
3305 static int
3308 {
3309  TupleDesc tupdesc;
3310  int natts;
3311  HeapTuple tuple;
3312  MemoryContext oldcontext;
3313 
3314  if (!estate->retisset)
3315  ereport(ERROR,
3316  (errcode(ERRCODE_SYNTAX_ERROR),
3317  errmsg("cannot use RETURN NEXT in a non-SETOF function")));
3318 
3319  if (estate->tuple_store == NULL)
3320  exec_init_tuple_store(estate);
3321 
3322  /* tuple_store_desc will be filled by exec_init_tuple_store */
3323  tupdesc = estate->tuple_store_desc;
3324  natts = tupdesc->natts;
3325 
3326  /*
3327  * Special case path when the RETURN NEXT expression is a simple variable
3328  * reference; in particular, this path is always taken in functions with
3329  * one or more OUT parameters.
3330  *
3331  * Unlike exec_stmt_return, there's no special win here for R/W expanded
3332  * values, since they'll have to get flattened to go into the tuplestore.
3333  * Indeed, we'd better make them R/O to avoid any risk of the casting step
3334  * changing them in-place.
3335  */
3336  if (stmt->retvarno >= 0)
3337  {
3338  PLpgSQL_datum *retvar = estate->datums[stmt->retvarno];
3339 
3340  switch (retvar->dtype)
3341  {
3342  case PLPGSQL_DTYPE_PROMISE:
3343  /* fulfill promise if needed, then handle like regular var */
3344  plpgsql_fulfill_promise(estate, (PLpgSQL_var *) retvar);
3345 
3346  /* FALL THRU */
3347 
3348  case PLPGSQL_DTYPE_VAR:
3349  {
3350  PLpgSQL_var *var = (PLpgSQL_var *) retvar;
3351  Datum retval = var->value;
3352  bool isNull = var->isnull;
3353  Form_pg_attribute attr = TupleDescAttr(tupdesc, 0);
3354 
3355  if (natts != 1)
3356  ereport(ERROR,
3357  (errcode(ERRCODE_DATATYPE_MISMATCH),
3358  errmsg("wrong result type supplied in RETURN NEXT")));
3359 
3360  /* let's be very paranoid about the cast step */
3361  retval = MakeExpandedObjectReadOnly(retval,
3362  isNull,
3363  var->datatype->typlen);
3364 
3365  /* coerce type if needed */
3366  retval = exec_cast_value(estate,
3367  retval,
3368  &isNull,
3369  var->datatype->typoid,
3370  var->datatype->atttypmod,
3371  attr->atttypid,
3372  attr->atttypmod);
3373 
3374  tuplestore_putvalues(estate->tuple_store, tupdesc,
3375  &retval, &isNull);
3376  }
3377  break;
3378 
3379  case PLPGSQL_DTYPE_REC:
3380  {
3381  PLpgSQL_rec *rec = (PLpgSQL_rec *) retvar;
3382  TupleDesc rec_tupdesc;
3383  TupleConversionMap *tupmap;
3384 
3385  /* If rec is null, try to convert it to a row of nulls */
3386  if (rec->erh == NULL)
3387  instantiate_empty_record_variable(estate, rec);
3388  if (ExpandedRecordIsEmpty(rec->erh))
3390 
3391  /* Use eval_mcontext for tuple conversion work */
3392  oldcontext = MemoryContextSwitchTo(get_eval_mcontext(estate));
3393  rec_tupdesc = expanded_record_get_tupdesc(rec->erh);
3394  tupmap = convert_tuples_by_position(rec_tupdesc,
3395  tupdesc,
3396  gettext_noop("wrong record type supplied in RETURN NEXT"));
3397  tuple = expanded_record_get_tuple(rec->erh);
3398  if (tupmap)
3399  tuple = execute_attr_map_tuple(tuple, tupmap);
3400  tuplestore_puttuple(estate->tuple_store, tuple);
3401  MemoryContextSwitchTo(oldcontext);
3402  }
3403  break;
3404 
3405  case PLPGSQL_DTYPE_ROW:
3406  {
3407  PLpgSQL_row *row = (PLpgSQL_row *) retvar;
3408 
3409  /* We get here if there are multiple OUT parameters */
3410 
3411  /* Use eval_mcontext for tuple conversion work */
3412  oldcontext = MemoryContextSwitchTo(get_eval_mcontext(estate));
3413  tuple = make_tuple_from_row(estate, row, tupdesc);
3414  if (tuple == NULL) /* should not happen */
3415  ereport(ERROR,
3416  (errcode(ERRCODE_DATATYPE_MISMATCH),
3417  errmsg("wrong record type supplied in RETURN NEXT")));
3418  tuplestore_puttuple(estate->tuple_store, tuple);
3419  MemoryContextSwitchTo(oldcontext);
3420  }
3421  break;
3422 
3423  default:
3424  elog(ERROR, "unrecognized dtype: %d", retvar->dtype);
3425  break;
3426  }
3427  }
3428  else if (stmt->expr)
3429  {
3430  Datum retval;
3431  bool isNull;
3432  Oid rettype;
3433  int32 rettypmod;
3434 
3435  retval = exec_eval_expr(estate,
3436  stmt->expr,
3437  &isNull,
3438  &rettype,
3439  &rettypmod);
3440 
3441  if (estate->retistuple)
3442  {
3443  /* Expression should be of RECORD or composite type */
3444  if (!isNull)
3445  {
3446  HeapTupleData tmptup;
3447  TupleDesc retvaldesc;
3448  TupleConversionMap *tupmap;
3449 
3450  if (!type_is_rowtype(rettype))
3451  ereport(ERROR,
3452  (errcode(ERRCODE_DATATYPE_MISMATCH),
3453  errmsg("cannot return non-composite value from function returning composite type")));
3454 
3455  /* Use eval_mcontext for tuple conversion work */
3456  oldcontext = MemoryContextSwitchTo(get_eval_mcontext(estate));
3457  retvaldesc = deconstruct_composite_datum(retval, &tmptup);
3458  tuple = &tmptup;
3459  tupmap = convert_tuples_by_position(retvaldesc, tupdesc,
3460  gettext_noop("returned record type does not match expected record type"));
3461  if (tupmap)
3462  tuple = execute_attr_map_tuple(tuple, tupmap);
3463  tuplestore_puttuple(estate->tuple_store, tuple);
3464  ReleaseTupleDesc(retvaldesc);
3465  MemoryContextSwitchTo(oldcontext);
3466  }
3467  else
3468  {
3469  /* Composite NULL --- store a row of nulls */
3470  Datum *nulldatums;
3471  bool *nullflags;
3472 
3473  nulldatums = (Datum *)
3474  eval_mcontext_alloc0(estate, natts * sizeof(Datum));
3475  nullflags = (bool *)
3476  eval_mcontext_alloc(estate, natts * sizeof(bool));
3477  memset(nullflags, true, natts * sizeof(bool));
3478  tuplestore_putvalues(estate->tuple_store, tupdesc,
3479  nulldatums, nullflags);
3480  }
3481  }
3482  else
3483  {
3484  Form_pg_attribute attr = TupleDescAttr(tupdesc, 0);
3485 
3486  /* Simple scalar result */
3487  if (natts != 1)
3488  ereport(ERROR,
3489  (errcode(ERRCODE_DATATYPE_MISMATCH),
3490  errmsg("wrong result type supplied in RETURN NEXT")));
3491 
3492  /* coerce type if needed */
3493  retval = exec_cast_value(estate,
3494  retval,
3495  &isNull,
3496  rettype,
3497  rettypmod,
3498  attr->atttypid,
3499  attr->atttypmod);
3500 
3501  tuplestore_putvalues(estate->tuple_store, tupdesc,
3502  &retval, &isNull);
3503  }
3504  }
3505  else
3506  {
3507  ereport(ERROR,
3508  (errcode(ERRCODE_SYNTAX_ERROR),
3509  errmsg("RETURN NEXT must have a parameter")));
3510  }
3511 
3512  exec_eval_cleanup(estate);
3513 
3514  return PLPGSQL_RC_OK;
3515 }
3516 
3517 /* ----------
3518  * exec_stmt_return_query Evaluate a query and add it to the
3519  * list of tuples returned by the current
3520  * SRF.
3521  * ----------
3522  */
3523 static int
3526 {
3527  int64 tcount;
3528  DestReceiver *treceiver;
3529  int rc;
3530  uint64 processed;
3531  MemoryContext stmt_mcontext = get_stmt_mcontext(estate);
3532  MemoryContext oldcontext;
3533 
3534  if (!estate->retisset)
3535  ereport(ERROR,
3536  (errcode(ERRCODE_SYNTAX_ERROR),
3537  errmsg("cannot use RETURN QUERY in a non-SETOF function")));
3538 
3539  if (estate->tuple_store == NULL)
3540  exec_init_tuple_store(estate);
3541  /* There might be some tuples in the tuplestore already */
3542  tcount = tuplestore_tuple_count(estate->tuple_store);
3543 
3544  /*
3545  * Set up DestReceiver to transfer results directly to tuplestore,
3546  * converting rowtype if necessary. DestReceiver lives in mcontext.
3547  */
3548  oldcontext = MemoryContextSwitchTo(stmt_mcontext);
3549  treceiver = CreateDestReceiver(DestTuplestore);
3551  estate->tuple_store,
3552  estate->tuple_store_cxt,
3553  false,
3554  estate->tuple_store_desc,
3555  gettext_noop("structure of query does not match function result type"));
3556  MemoryContextSwitchTo(oldcontext);
3557 
3558  if (stmt->query != NULL)
3559  {
3560  /* static query */
3561  PLpgSQL_expr *expr = stmt->query;
3562  ParamListInfo paramLI;
3563 
3564  /*
3565  * On the first call for this expression generate the plan.
3566  */
3567  if (expr->plan == NULL)
3568  exec_prepare_plan(estate, expr, CURSOR_OPT_PARALLEL_OK, true);
3569 
3570  /*
3571  * Set up ParamListInfo to pass to executor
3572  */
3573  paramLI = setup_param_list(estate, expr);
3574 
3575  /*
3576  * Execute the query
3577  */
3578  rc = SPI_execute_plan_with_receiver(expr->plan, paramLI,
3579  estate->readonly_func, 0,
3580  treceiver);
3581  if (rc != SPI_OK_SELECT)
3582  ereport(ERROR,
3583  (errcode(ERRCODE_SYNTAX_ERROR),
3584  errmsg("query \"%s\" is not a SELECT", expr->query)));
3585  }
3586  else
3587  {
3588  /* RETURN QUERY EXECUTE */
3589  Datum query;
3590  bool isnull;
3591  Oid restype;
3592  int32 restypmod;
3593  char *querystr;
3594 
3595  /*
3596  * Evaluate the string expression after the EXECUTE keyword. Its
3597  * result is the querystring we have to execute.
3598  */
3599  Assert(stmt->dynquery != NULL);
3600  query = exec_eval_expr(estate, stmt->dynquery,
3601  &isnull, &restype, &restypmod);
3602  if (isnull)
3603  ereport(ERROR,
3604  (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
3605  errmsg("query string argument of EXECUTE is null")));
3606 
3607  /* Get the C-String representation */
3608  querystr = convert_value_to_string(estate, query, restype);
3609 
3610  /* copy it into the stmt_mcontext before we clean up */
3611  querystr = MemoryContextStrdup(stmt_mcontext, querystr);
3612 
3613  exec_eval_cleanup(estate);
3614 
3615  /* Execute query, passing params if necessary */
3616  rc = SPI_execute_with_receiver(querystr,
3617  exec_eval_using_params(estate,
3618  stmt->params),
3619  estate->readonly_func,
3620  0,
3621  treceiver);
3622  if (rc < 0)
3623  elog(ERROR, "SPI_execute_with_receiver failed executing query \"%s\": %s",
3624  querystr, SPI_result_code_string(rc));
3625  }
3626 
3627  /* Clean up */
3628  treceiver->rDestroy(treceiver);
3629  exec_eval_cleanup(estate);
3630  MemoryContextReset(stmt_mcontext);
3631 
3632  /* Count how many tuples we got */
3633  processed = tuplestore_tuple_count(estate->tuple_store) - tcount;
3634 
3635  estate->eval_processed = processed;
3636  exec_set_found(estate, processed != 0);
3637 
3638  return PLPGSQL_RC_OK;
3639 }
3640 
3641 static void
3643 {
3644  ReturnSetInfo *rsi = estate->rsi;
3645  MemoryContext oldcxt;
3646  ResourceOwner oldowner;
3647 
3648  /*
3649  * Check caller can handle a set result in the way we want
3650  */
3651  if (!rsi || !IsA(rsi, ReturnSetInfo) ||
3652  (rsi->allowedModes & SFRM_Materialize) == 0 ||
3653  rsi->expectedDesc == NULL)
3654  ereport(ERROR,
3655  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3656  errmsg("set-valued function called in context that cannot accept a set")));
3657 
3658  /*
3659  * Switch to the right memory context and resource owner for storing the
3660  * tuplestore for return set. If we're within a subtransaction opened for
3661  * an exception-block, for example, we must still create the tuplestore in
3662  * the resource owner that was active when this function was entered, and
3663  * not in the subtransaction resource owner.
3664  */
3665  oldcxt = MemoryContextSwitchTo(estate->tuple_store_cxt);
3666  oldowner = CurrentResourceOwner;
3668 
3669  estate->tuple_store =
3671  false, work_mem);
3672 
3673  CurrentResourceOwner = oldowner;
3674  MemoryContextSwitchTo(oldcxt);
3675 
3676  estate->tuple_store_desc = rsi->expectedDesc;
3677 }
3678 
3679 #define SET_RAISE_OPTION_TEXT(opt, name) \
3680 do { \
3681  if (opt) \
3682  ereport(ERROR, \
3683  (errcode(ERRCODE_SYNTAX_ERROR), \
3684  errmsg("RAISE option already specified: %s", \
3685  name))); \
3686  opt = MemoryContextStrdup(stmt_mcontext, extval); \
3687 } while (0)
3688 
3689 /* ----------
3690  * exec_stmt_raise Build a message and throw it with elog()
3691  * ----------
3692  */
3693 static int
3695 {
3696  int err_code = 0;
3697  char *condname = NULL;
3698  char *err_message = NULL;
3699  char *err_detail = NULL;
3700  char *err_hint = NULL;
3701  char *err_column = NULL;
3702  char *err_constraint = NULL;
3703  char *err_datatype = NULL;
3704  char *err_table = NULL;
3705  char *err_schema = NULL;
3706  MemoryContext stmt_mcontext;
3707  ListCell *lc;
3708 
3709  /* RAISE with no parameters: re-throw current exception */
3710  if (stmt->condname == NULL && stmt->message == NULL &&
3711  stmt->options == NIL)
3712  {
3713  if (estate->cur_error != NULL)
3714  ReThrowError(estate->cur_error);
3715  /* oops, we're not inside a handler */
3716  ereport(ERROR,
3717  (errcode(ERRCODE_STACKED_DIAGNOSTICS_ACCESSED_WITHOUT_ACTIVE_HANDLER),
3718  errmsg("RAISE without parameters cannot be used outside an exception handler")));
3719  }
3720 
3721  /* We'll need to accumulate the various strings in stmt_mcontext */
3722  stmt_mcontext = get_stmt_mcontext(estate);
3723 
3724  if (stmt->condname)
3725  {
3726  err_code = plpgsql_recognize_err_condition(stmt->condname, true);
3727  condname = MemoryContextStrdup(stmt_mcontext, stmt->condname);
3728  }
3729 
3730  if (stmt->message)
3731  {
3732  StringInfoData ds;
3733  ListCell *current_param;
3734  char *cp;
3735  MemoryContext oldcontext;
3736 
3737  /* build string in stmt_mcontext */
3738  oldcontext = MemoryContextSwitchTo(stmt_mcontext);
3739  initStringInfo(&ds);
3740  MemoryContextSwitchTo(oldcontext);
3741 
3742  current_param = list_head(stmt->params);
3743 
3744  for (cp = stmt->message; *cp; cp++)
3745  {
3746  /*
3747  * Occurrences of a single % are replaced by the next parameter's
3748  * external representation. Double %'s are converted to one %.
3749  */
3750  if (cp[0] == '%')
3751  {
3752  Oid paramtypeid;
3753  int32 paramtypmod;
3754  Datum paramvalue;
3755  bool paramisnull;
3756  char *extval;
3757 
3758  if (cp[1] == '%')
3759  {
3760  appendStringInfoChar(&ds, '%');
3761  cp++;
3762  continue;
3763  }
3764 
3765  /* should have been checked at compile time */
3766  if (current_param == NULL)
3767  elog(ERROR, "unexpected RAISE parameter list length");
3768 
3769  paramvalue = exec_eval_expr(estate,
3770  (PLpgSQL_expr *) lfirst(current_param),
3771  &paramisnull,
3772  &paramtypeid,
3773  &paramtypmod);
3774 
3775  if (paramisnull)
3776  extval = "<NULL>";
3777  else
3778  extval = convert_value_to_string(estate,
3779  paramvalue,
3780  paramtypeid);
3781  appendStringInfoString(&ds, extval);
3782  current_param = lnext(stmt->params, current_param);
3783  exec_eval_cleanup(estate);
3784  }
3785  else
3786  appendStringInfoChar(&ds, cp[0]);
3787  }
3788 
3789  /* should have been checked at compile time */
3790  if (current_param != NULL)
3791  elog(ERROR, "unexpected RAISE parameter list length");
3792 
3793  err_message = ds.data;
3794  }
3795 
3796  foreach(lc, stmt->options)
3797  {
3799  Datum optionvalue;
3800  bool optionisnull;
3801  Oid optiontypeid;
3802  int32 optiontypmod;
3803  char *extval;
3804 
3805  optionvalue = exec_eval_expr(estate, opt->expr,
3806  &optionisnull,
3807  &optiontypeid,
3808  &optiontypmod);
3809  if (optionisnull)
3810  ereport(ERROR,
3811  (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
3812  errmsg("RAISE statement option cannot be null")));
3813 
3814  extval = convert_value_to_string(estate, optionvalue, optiontypeid);
3815 
3816  switch (opt->opt_type)
3817  {
3819  if (err_code)
3820  ereport(ERROR,
3821  (errcode(ERRCODE_SYNTAX_ERROR),
3822  errmsg("RAISE option already specified: %s",
3823  "ERRCODE")));
3824  err_code = plpgsql_recognize_err_condition(extval, true);
3825  condname = MemoryContextStrdup(stmt_mcontext, extval);
3826  break;
3828  SET_RAISE_OPTION_TEXT(err_message, "MESSAGE");
3829  break;
3831  SET_RAISE_OPTION_TEXT(err_detail, "DETAIL");
3832  break;
3834  SET_RAISE_OPTION_TEXT(err_hint, "HINT");
3835  break;
3837  SET_RAISE_OPTION_TEXT(err_column, "COLUMN");
3838  break;
3840  SET_RAISE_OPTION_TEXT(err_constraint, "CONSTRAINT");
3841  break;
3843  SET_RAISE_OPTION_TEXT(err_datatype, "DATATYPE");
3844  break;
3846  SET_RAISE_OPTION_TEXT(err_table, "TABLE");
3847  break;
3849  SET_RAISE_OPTION_TEXT(err_schema, "SCHEMA");
3850  break;
3851  default:
3852  elog(ERROR, "unrecognized raise option: %d", opt->opt_type);
3853  }
3854 
3855  exec_eval_cleanup(estate);
3856  }
3857 
3858  /* Default code if nothing specified */
3859  if (err_code == 0 && stmt->elog_level >= ERROR)
3860  err_code = ERRCODE_RAISE_EXCEPTION;
3861 
3862  /* Default error message if nothing specified */
3863  if (err_message == NULL)
3864  {
3865  if (condname)
3866  {
3867  err_message = condname;
3868  condname = NULL;
3869  }
3870  else
3871  err_message = MemoryContextStrdup(stmt_mcontext,
3872  unpack_sql_state(err_code));
3873  }
3874 
3875  /*
3876  * Throw the error (may or may not come back)
3877  */
3878  ereport(stmt->elog_level,
3879  (err_code ? errcode(err_code) : 0,
3880  errmsg_internal("%s", err_message),
3881  (err_detail != NULL) ? errdetail_internal("%s", err_detail) : 0,
3882  (err_hint != NULL) ? errhint("%s", err_hint) : 0,
3883  (err_column != NULL) ?
3884  err_generic_string(PG_DIAG_COLUMN_NAME, err_column) : 0,
3885  (err_constraint != NULL) ?
3886  err_generic_string(PG_DIAG_CONSTRAINT_NAME, err_constraint) : 0,
3887  (err_datatype != NULL) ?
3888  err_generic_string(PG_DIAG_DATATYPE_NAME, err_datatype) : 0,
3889  (err_table != NULL) ?
3890  err_generic_string(PG_DIAG_TABLE_NAME, err_table) : 0,
3891  (err_schema != NULL) ?
3892  err_generic_string(PG_DIAG_SCHEMA_NAME, err_schema) : 0));
3893 
3894  /* Clean up transient strings */
3895  MemoryContextReset(stmt_mcontext);
3896 
3897  return PLPGSQL_RC_OK;
3898 }
3899 
3900 /* ----------
3901  * exec_stmt_assert Assert statement
3902  * ----------
3903  */
3904 static int
3906 {
3907  bool value;
3908  bool isnull;
3909 
3910  /* do nothing when asserts are not enabled */
3911  if (!plpgsql_check_asserts)
3912  return PLPGSQL_RC_OK;
3913 
3914  value = exec_eval_boolean(estate, stmt->cond, &isnull);
3915  exec_eval_cleanup(estate);
3916 
3917  if (isnull || !value)
3918  {
3919  char *message = NULL;
3920 
3921  if (stmt->message != NULL)
3922  {
3923  Datum val;
3924  Oid typeid;
3925  int32 typmod;
3926 
3927  val = exec_eval_expr(estate, stmt->message,
3928  &isnull, &typeid, &typmod);
3929  if (!isnull)
3930  message = convert_value_to_string(estate, val, typeid);
3931  /* we mustn't do exec_eval_cleanup here */
3932  }
3933 
3934  ereport(ERROR,
3935  (errcode(ERRCODE_ASSERT_FAILURE),
3936  message ? errmsg_internal("%s", message) :
3937  errmsg("assertion failed")));
3938  }
3939 
3940  return PLPGSQL_RC_OK;
3941 }
3942 
3943 /* ----------
3944  * Initialize a mostly empty execution state
3945  * ----------
3946  */
3947 static void
3949  PLpgSQL_function *func,
3950  ReturnSetInfo *rsi,
3951  EState *simple_eval_estate,
3952  ResourceOwner simple_eval_resowner)
3953 {
3954  HASHCTL ctl;
3955 
3956  /* this link will be restored at exit from plpgsql_call_handler */
3957  func->cur_estate = estate;
3958 
3959  estate->func = func;
3960  estate->trigdata = NULL;
3961  estate->evtrigdata = NULL;
3962 
3963  estate->retval = (Datum) 0;
3964  estate->retisnull = true;
3965  estate->rettype = InvalidOid;
3966 
3967  estate->fn_rettype = func->fn_rettype;
3968  estate->retistuple = func->fn_retistuple;
3969  estate->retisset = func->fn_retset;
3970 
3971  estate->readonly_func = func->fn_readonly;
3972  estate->atomic = true;
3973 
3974  estate->exitlabel = NULL;
3975  estate->cur_error = NULL;
3976 
3977  estate->tuple_store = NULL;
3978  estate->tuple_store_desc = NULL;
3979  if (rsi)
3980  {
3983  }
3984  else
3985  {
3986  estate->tuple_store_cxt = NULL;
3987  estate->tuple_store_owner = NULL;
3988  }
3989  estate->rsi = rsi;
3990 
3991  estate->found_varno = func->found_varno;
3992  estate->ndatums = func->ndatums;
3993  estate->datums = NULL;
3994  /* the datums array will be filled by copy_plpgsql_datums() */
3996 
3997  /* initialize our ParamListInfo with appropriate hook functions */
3998  estate->paramLI = makeParamList(0);
4000  estate->paramLI->paramFetchArg = (void *) estate;
4002  estate->paramLI->paramCompileArg = NULL; /* not needed */
4004  estate->paramLI->parserSetupArg = NULL; /* filled during use */
4005  estate->paramLI->numParams = estate->ndatums;
4006 
4007  /* set up for use of appropriate simple-expression EState and cast hash */
4008  if (simple_eval_estate)
4009  {
4010  estate->simple_eval_estate = simple_eval_estate;
4011  /* Private cast hash just lives in function's main context */
4012  memset(&ctl, 0, sizeof(ctl));
4013  ctl.keysize = sizeof(plpgsql_CastHashKey);
4014  ctl.entrysize = sizeof(plpgsql_CastHashEntry);
4015  ctl.hcxt = CurrentMemoryContext;
4016  estate->cast_hash = hash_create("PLpgSQL private cast cache",
4017  16, /* start small and extend */
4018  &ctl,
4021  }
4022  else
4023  {
4025  /* Create the session-wide cast-info hash table if we didn't already */
4026  if (shared_cast_hash == NULL)
4027  {
4028  shared_cast_context = AllocSetContextCreate(TopMemoryContext,
4029  "PLpgSQL cast info",
4031  memset(&ctl, 0, sizeof(ctl));
4032  ctl.keysize = sizeof(plpgsql_CastHashKey);
4033  ctl.entrysize = sizeof(plpgsql_CastHashEntry);
4034  ctl.hcxt = shared_cast_context;
4035  shared_cast_hash = hash_create("PLpgSQL cast cache",
4036  16, /* start small and extend */
4037  &ctl,
4039  }
4040  estate->cast_hash = shared_cast_hash;
4042  }
4043  /* likewise for the simple-expression resource owner */
4044  if (simple_eval_resowner)
4045  estate->simple_eval_resowner = simple_eval_resowner;
4046  else
4048 
4049  /*
4050  * We start with no stmt_mcontext; one will be created only if needed.
4051  * That context will be a direct child of the function's main execution
4052  * context. Additional stmt_mcontexts might be created as children of it.
4053  */
4054  estate->stmt_mcontext = NULL;
4056 
4057  estate->eval_tuptable = NULL;
4058  estate->eval_processed = 0;
4059  estate->eval_econtext = NULL;
4060 
4061  estate->err_stmt = NULL;
4062  estate->err_text = NULL;
4063 
4064  estate->plugin_info = NULL;
4065 
4066  /*
4067  * Create an EState and ExprContext for evaluation of simple expressions.
4068  */
4069  plpgsql_create_econtext(estate);
4070 
4071  /*
4072  * Let the plugin see this function before we initialize any local
4073  * PL/pgSQL variables - note that we also give the plugin a few function
4074  * pointers so it can call back into PL/pgSQL for doing things like
4075  * variable assignments and stack traces
4076  */
4077  if (*plpgsql_plugin_ptr)
4078  {
4079  (*plpgsql_plugin_ptr)->error_callback = plpgsql_exec_error_callback;
4080  (*plpgsql_plugin_ptr)->assign_expr = exec_assign_expr;
4081 
4082  if ((*plpgsql_plugin_ptr)->func_setup)
4083  ((*plpgsql_plugin_ptr)->func_setup) (estate, func);
4084  }
4085 }
4086 
4087 /* ----------
4088  * Release temporary memory used by expression/subselect evaluation
4089  *
4090  * NB: the result of the evaluation is no longer valid after this is done,
4091  * unless it is a pass-by-value datatype.
4092  *
4093  * NB: if you change this code, see also the hacks in exec_assign_value's
4094  * PLPGSQL_DTYPE_ARRAYELEM case for partial cleanup after subscript evals.
4095  * ----------
4096  */
4097 static void
4099 {
4100  /* Clear result of a full SPI_execute */
4101  if (estate->eval_tuptable != NULL)
4103  estate->eval_tuptable = NULL;
4104 
4105  /*
4106  * Clear result of exec_eval_simple_expr (but keep the econtext). This
4107  * also clears any short-lived allocations done via get_eval_mcontext.
4108  */
4109  if (estate->eval_econtext != NULL)
4111 }
4112 
4113 
4114 /* ----------
4115  * Generate a prepared plan
4116  * ----------
4117  */
4118 static void
4120  PLpgSQL_expr *expr, int cursorOptions,
4121  bool keepplan)
4122 {
4123  SPIPlanPtr plan;
4124 
4125  /*
4126  * The grammar can't conveniently set expr->func while building the parse
4127  * tree, so make sure it's set before parser hooks need it.
4128  */
4129  expr->func = estate->func;
4130 
4131  /*
4132  * Generate and save the plan
4133  */
4134  plan = SPI_prepare_params(expr->query,
4136  (void *) expr,
4137  cursorOptions);
4138  if (plan == NULL)
4139  elog(ERROR, "SPI_prepare_params failed for \"%s\": %s",
4140  expr->query, SPI_result_code_string(SPI_result));
4141  if (keepplan)
4142  SPI_keepplan(plan);
4143  expr->plan = plan;
4144 
4145  /* Check to see if it's a simple expression */
4146  exec_simple_check_plan(estate, expr);
4147 
4148  /*
4149  * Mark expression as not using a read-write param. exec_assign_value has
4150  * to take steps to override this if appropriate; that seems cleaner than
4151  * adding parameters to all other callers.
4152  */
4153  expr->rwparam = -1;
4154 }
4155 
4156 
4157 /* ----------
4158  * exec_stmt_execsql Execute an SQL statement (possibly with INTO).
4159  *
4160  * Note: some callers rely on this not touching stmt_mcontext. If it ever
4161  * needs to use that, fix those callers to push/pop stmt_mcontext.
4162  * ----------
4163  */
4164 static int
4166  PLpgSQL_stmt_execsql *stmt)
4167 {
4168  ParamListInfo paramLI;
4169  long tcount;
4170  int rc;
4171  PLpgSQL_expr *expr = stmt->sqlstmt;
4172  int too_many_rows_level = 0;
4173 
4175  too_many_rows_level = ERROR;
4176  else if (plpgsql_extra_warnings & PLPGSQL_XCHECK_TOOMANYROWS)
4177  too_many_rows_level = WARNING;
4178 
4179  /*
4180  * On the first call for this statement generate the plan, and detect
4181  * whether the statement is INSERT/UPDATE/DELETE
4182  */
4183  if (expr->plan == NULL)
4184  {
4185  ListCell *l;
4186 
4187  exec_prepare_plan(estate, expr, CURSOR_OPT_PARALLEL_OK, true);
4188  stmt->mod_stmt = false;
4189  foreach(l, SPI_plan_get_plan_sources(expr->plan))
4190  {
4191  CachedPlanSource *plansource = (CachedPlanSource *) lfirst(l);
4192 
4193  /*
4194  * We could look at the raw_parse_tree, but it seems simpler to
4195  * check the command tag. Note we should *not* look at the Query
4196  * tree(s), since those are the result of rewriting and could have
4197  * been transmogrified into something else entirely.
4198  */
4199  if (plansource->commandTag == CMDTAG_INSERT ||
4200  plansource->commandTag == CMDTAG_UPDATE ||
4201  plansource->commandTag == CMDTAG_DELETE)
4202  {
4203  stmt->mod_stmt = true;
4204  break;
4205  }
4206  }
4207  }
4208 
4209  /*
4210  * Set up ParamListInfo to pass to executor
4211  */
4212  paramLI = setup_param_list(estate, expr);
4213 
4214  /*
4215  * If we have INTO, then we only need one row back ... but if we have INTO
4216  * STRICT or extra check too_many_rows, ask for two rows, so that we can
4217  * verify the statement returns only one. INSERT/UPDATE/DELETE are always
4218  * treated strictly. Without INTO, just run the statement to completion
4219  * (tcount = 0).
4220  *
4221  * We could just ask for two rows always when using INTO, but there are
4222  * some cases where demanding the extra row costs significant time, eg by
4223  * forcing completion of a sequential scan. So don't do it unless we need
4224  * to enforce strictness.
4225  */
4226  if (stmt->into)
4227  {
4228  if (stmt->strict || stmt->mod_stmt || too_many_rows_level)
4229  tcount = 2;
4230  else
4231  tcount = 1;
4232  }
4233  else
4234  tcount = 0;
4235 
4236  /*
4237  * Execute the plan
4238  */
4239  rc = SPI_execute_plan_with_paramlist(expr->plan, paramLI,
4240  estate->readonly_func, tcount);
4241 
4242  /*
4243  * Check for error, and set FOUND if appropriate (for historical reasons
4244  * we set FOUND only for certain query types). Also Assert that we
4245  * identified the statement type the same as SPI did.
4246  */
4247  switch (rc)
4248  {
4249  case SPI_OK_SELECT:
4250  Assert(!stmt->mod_stmt);
4251  exec_set_found(estate, (SPI_processed != 0));
4252  break;
4253 
4254  case SPI_OK_INSERT:
4255  case SPI_OK_UPDATE:
4256  case SPI_OK_DELETE:
4260  Assert(stmt->mod_stmt);
4261  exec_set_found(estate, (SPI_processed != 0));
4262  break;
4263 
4264  case SPI_OK_SELINTO:
4265  case SPI_OK_UTILITY:
4266  Assert(!stmt->mod_stmt);
4267  break;
4268 
4269  case SPI_OK_REWRITTEN:
4270 
4271  /*
4272  * The command was rewritten into another kind of command. It's
4273  * not clear what FOUND would mean in that case (and SPI doesn't
4274  * return the row count either), so just set it to false. Note
4275  * that we can't assert anything about mod_stmt here.
4276  */
4277  exec_set_found(estate, false);
4278  break;
4279 
4280  /* Some SPI errors deserve specific error messages */
4281  case SPI_ERROR_COPY:
4282  ereport(ERROR,
4283  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4284  errmsg("cannot COPY to/from client in PL/pgSQL")));
4285  break;
4286 
4287  case SPI_ERROR_TRANSACTION:
4288  ereport(ERROR,
4289  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4290  errmsg("unsupported transaction command in PL/pgSQL")));
4291  break;
4292 
4293  default:
4294  elog(ERROR, "SPI_execute_plan_with_paramlist failed executing query \"%s\": %s",
4295  expr->query, SPI_result_code_string(rc));
4296  break;
4297  }
4298 
4299  /* All variants should save result info for GET DIAGNOSTICS */
4300  estate->eval_processed = SPI_processed;
4301 
4302  /* Process INTO if present */
4303  if (stmt->into)
4304  {
4305  SPITupleTable *tuptab = SPI_tuptable;
4306  uint64 n = SPI_processed;
4307  PLpgSQL_variable *target;
4308 
4309  /* If the statement did not return a tuple table, complain */
4310  if (tuptab == NULL)
4311  ereport(ERROR,
4312  (errcode(ERRCODE_SYNTAX_ERROR),
4313  errmsg("INTO used with a command that cannot return data")));
4314 
4315  /* Fetch target's datum entry */
4316  target = (PLpgSQL_variable *) estate->datums[stmt->target->dno];
4317 
4318  /*
4319  * If SELECT ... INTO specified STRICT, and the query didn't find
4320  * exactly one row, throw an error. If STRICT was not specified, then
4321  * allow the query to find any number of rows.
4322  */
4323  if (n == 0)
4324  {
4325  if (stmt->strict)
4326  {
4327  char *errdetail;
4328 
4329  if (estate->func->print_strict_params)
4330  errdetail = format_expr_params(estate, expr);
4331  else
4332  errdetail = NULL;
4333 
4334  ereport(ERROR,
4335  (errcode(ERRCODE_NO_DATA_FOUND),
4336  errmsg("query returned no rows"),
4337  errdetail ? errdetail_internal("parameters: %s", errdetail) : 0));
4338  }
4339  /* set the target to NULL(s) */
4340  exec_move_row(estate, target, NULL, tuptab->tupdesc);
4341  }
4342  else
4343  {
4344  if (n > 1 && (stmt->strict || stmt->mod_stmt || too_many_rows_level))
4345  {
4346  char *errdetail;
4347  int errlevel;
4348 
4349  if (estate->func->print_strict_params)
4350  errdetail = format_expr_params(estate, expr);
4351  else
4352  errdetail = NULL;
4353 
4354  errlevel = (stmt->strict || stmt->mod_stmt) ? ERROR : too_many_rows_level;
4355 
4356  ereport(errlevel,
4357  (errcode(ERRCODE_TOO_MANY_ROWS),
4358  errmsg("query returned more than one row"),
4359  errdetail ? errdetail_internal("parameters: %s", errdetail) : 0,
4360  errhint("Make sure the query returns a single row, or use LIMIT 1.")));
4361  }
4362  /* Put the first result row into the target */
4363  exec_move_row(estate, target, tuptab->vals[0], tuptab->tupdesc);
4364  }
4365 
4366  /* Clean up */
4367  exec_eval_cleanup(estate);
4369  }
4370  else
4371  {
4372  /* If the statement returned a tuple table, complain */
4373  if (SPI_tuptable != NULL)
4374  ereport(ERROR,
4375  (errcode(ERRCODE_SYNTAX_ERROR),
4376  errmsg("query has no destination for result data"),
4377  (rc == SPI_OK_SELECT) ? errhint("If you want to discard the results of a SELECT, use PERFORM instead.") : 0));
4378  }
4379 
4380  return PLPGSQL_RC_OK;
4381 }
4382 
4383 
4384 /* ----------
4385  * exec_stmt_dynexecute Execute a dynamic SQL query
4386  * (possibly with INTO).
4387  * ----------
4388  */
4389 static int
4392 {
4393  Datum query;
4394  bool isnull;
4395  Oid restype;
4396  int32 restypmod;
4397  char *querystr;
4398  int exec_res;
4399  ParamListInfo paramLI;
4400  MemoryContext stmt_mcontext = get_stmt_mcontext(estate);
4401 
4402  /*
4403  * First we evaluate the string expression after the EXECUTE keyword. Its
4404  * result is the querystring we have to execute.
4405  */
4406  query = exec_eval_expr(estate, stmt->query, &isnull, &restype, &restypmod);
4407  if (isnull)
4408  ereport(ERROR,
4409  (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
4410  errmsg("query string argument of EXECUTE is null")));
4411 
4412  /* Get the C-String representation */
4413  querystr = convert_value_to_string(estate, query, restype);
4414 
4415  /* copy it into the stmt_mcontext before we clean up */
4416  querystr = MemoryContextStrdup(stmt_mcontext, querystr);
4417 
4418  exec_eval_cleanup(estate);
4419 
4420  /*
4421  * Execute the query without preparing a saved plan.
4422  */
4423  paramLI = exec_eval_using_params(estate, stmt->params);
4424  exec_res = SPI_execute_with_receiver(querystr, paramLI,
4425  estate->readonly_func, 0, NULL);
4426 
4427  switch (exec_res)
4428  {
4429  case SPI_OK_SELECT:
4430  case SPI_OK_INSERT:
4431  case SPI_OK_UPDATE:
4432  case SPI_OK_DELETE:
4436  case SPI_OK_UTILITY:
4437  case SPI_OK_REWRITTEN:
4438  break;
4439 
4440  case 0:
4441 
4442  /*
4443  * Also allow a zero return, which implies the querystring
4444  * contained no commands.
4445  */
4446  break;
4447 
4448  case SPI_OK_SELINTO:
4449 
4450  /*
4451  * We want to disallow SELECT INTO for now, because its behavior
4452  * is not consistent with SELECT INTO in a normal plpgsql context.
4453  * (We need to reimplement EXECUTE to parse the string as a
4454  * plpgsql command, not just feed it to SPI_execute.) This is not
4455  * a functional limitation because CREATE TABLE AS is allowed.
4456  */
4457  ereport(ERROR,
4458  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4459  errmsg("EXECUTE of SELECT ... INTO is not implemented"),
4460  errhint("You might want to use EXECUTE ... INTO or EXECUTE CREATE TABLE ... AS instead.")));
4461  break;
4462 
4463  /* Some SPI errors deserve specific error messages */
4464  case SPI_ERROR_COPY:
4465  ereport(ERROR,
4466  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4467  errmsg("cannot COPY to/from client in PL/pgSQL")));
4468  break;
4469 
4470  case SPI_ERROR_TRANSACTION:
4471  ereport(ERROR,
4472  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
4473  errmsg("EXECUTE of transaction commands is not implemented")));
4474  break;
4475 
4476  default:
4477  elog(ERROR, "SPI_execute_with_receiver failed executing query \"%s\": %s",
4478  querystr, SPI_result_code_string(exec_res));
4479  break;
4480  }
4481 
4482  /* Save result info for GET DIAGNOSTICS */
4483  estate->eval_processed = SPI_processed;
4484 
4485  /* Process INTO if present */
4486  if (stmt->into)
4487  {
4488  SPITupleTable *tuptab = SPI_tuptable;
4489  uint64 n = SPI_processed;
4490  PLpgSQL_variable *target;
4491 
4492  /* If the statement did not return a tuple table, complain */
4493  if (tuptab == NULL)
4494  ereport(ERROR,
4495  (errcode(ERRCODE_SYNTAX_ERROR),
4496  errmsg("INTO used with a command that cannot return data")));
4497 
4498  /* Fetch target's datum entry */
4499  target = (PLpgSQL_variable *) estate->datums[stmt->target->dno];
4500 
4501  /*
4502  * If SELECT ... INTO specified STRICT, and the query didn't find
4503  * exactly one row, throw an error. If STRICT was not specified, then
4504  * allow the query to find any number of rows.
4505  */
4506  if (n == 0)
4507  {
4508  if (stmt->strict)
4509  {
4510  char *errdetail;
4511 
4512  if (estate->func->print_strict_params)
4513  errdetail = format_preparedparamsdata(estate, paramLI);
4514  else
4515  errdetail = NULL;
4516 
4517  ereport(ERROR,
4518  (errcode(ERRCODE_NO_DATA_FOUND),
4519  errmsg("query returned no rows"),
4520  errdetail ? errdetail_internal("parameters: %s", errdetail) : 0));
4521  }
4522  /* set the target to NULL(s) */
4523  exec_move_row(estate, target, NULL, tuptab->tupdesc);
4524  }
4525  else
4526  {
4527  if (n > 1 && stmt->strict)
4528  {
4529  char *errdetail;
4530 
4531  if (estate->func->print_strict_params)
4532  errdetail = format_preparedparamsdata(estate, paramLI);
4533  else
4534  errdetail = NULL;
4535 
4536  ereport(ERROR,
4537  (errcode(ERRCODE_TOO_MANY_ROWS),
4538  errmsg("query returned more than one row"),
4539  errdetail ? errdetail_internal("parameters: %s", errdetail) : 0));
4540  }
4541 
4542  /* Put the first result row into the target */
4543  exec_move_row(estate, target, tuptab->vals[0], tuptab->tupdesc);
4544  }
4545  /* clean up after exec_move_row() */
4546  exec_eval_cleanup(estate);
4547  }
4548  else
4549  {
4550  /*
4551  * It might be a good idea to raise an error if the query returned
4552  * tuples that are being ignored, but historically we have not done
4553  * that.
4554  */
4555  }
4556 
4557  /* Release any result from SPI_execute, as well as transient data */
4559  MemoryContextReset(stmt_mcontext);
4560 
4561  return PLPGSQL_RC_OK;
4562 }
4563 
4564 
4565 /* ----------
4566  * exec_stmt_dynfors Execute a dynamic query, assign each
4567  * tuple to a record or row and
4568  * execute a group of statements
4569  * for it.
4570  * ----------
4571  */
4572 static int
4574 {
4575  Portal portal;
4576  int rc;
4577 
4578  portal = exec_dynquery_with_params(estate, stmt->query, stmt->params,
4579  NULL, 0);
4580 
4581  /*
4582  * Execute the loop
4583  */
4584  rc = exec_for_query(estate, (PLpgSQL_stmt_forq *) stmt, portal, true);
4585 
4586  /*
4587  * Close the implicit cursor
4588  */
4589  SPI_cursor_close(portal);
4590 
4591  return rc;
4592 }
4593 
4594 
4595 /* ----------
4596  * exec_stmt_open Execute an OPEN cursor statement
4597  * ----------
4598  */
4599 static int
4601 {
4602  PLpgSQL_var *curvar;
4603  MemoryContext stmt_mcontext = NULL;
4604  char *curname = NULL;
4605  PLpgSQL_expr *query;
4606  Portal portal;
4607  ParamListInfo paramLI;
4608 
4609  /* ----------
4610  * Get the cursor variable and if it has an assigned name, check
4611  * that it's not in use currently.
4612  * ----------
4613  */
4614  curvar = (PLpgSQL_var *) (estate->datums[stmt->curvar]);
4615  if (!curvar->isnull)
4616  {
4617  MemoryContext oldcontext;
4618 
4619  /* We only need stmt_mcontext to hold the cursor name string */
4620  stmt_mcontext = get_stmt_mcontext(estate);
4621  oldcontext = MemoryContextSwitchTo(stmt_mcontext);
4622  curname = TextDatumGetCString(curvar->value);
4623  MemoryContextSwitchTo(oldcontext);
4624 
4625  if (SPI_cursor_find(curname) != NULL)
4626  ereport(ERROR,
4627  (errcode(ERRCODE_DUPLICATE_CURSOR),
4628  errmsg("cursor \"%s\" already in use", curname)));
4629  }
4630 
4631  /* ----------
4632  * Process the OPEN according to it's type.
4633  * ----------
4634  */
4635  if (stmt->query != NULL)
4636  {
4637  /* ----------
4638  * This is an OPEN refcursor FOR SELECT ...
4639  *
4640  * We just make sure the query is planned. The real work is
4641  * done downstairs.
4642  * ----------
4643  */
4644  query = stmt->query;
4645  if (query->plan == NULL)
4646  exec_prepare_plan(estate, query, stmt->cursor_options, true);
4647  }
4648  else if (stmt->dynquery != NULL)
4649  {
4650  /* ----------
4651  * This is an OPEN refcursor FOR EXECUTE ...
4652  * ----------
4653  */
4654  portal = exec_dynquery_with_params(estate,
4655  stmt->dynquery,
4656  stmt->params,
4657  curname,
4658  stmt->cursor_options);
4659 
4660  /*
4661  * If cursor variable was NULL, store the generated portal name in it.
4662  * Note: exec_dynquery_with_params already reset the stmt_mcontext, so
4663  * curname is a dangling pointer here; but testing it for nullness is
4664  * OK.
4665  */
4666  if (curname == NULL)
4667  assign_text_var(estate, curvar, portal->name);
4668 
4669  return PLPGSQL_RC_OK;
4670  }
4671  else
4672  {
4673  /* ----------
4674  * This is an OPEN cursor
4675  *
4676  * Note: parser should already have checked that statement supplies
4677  * args iff cursor needs them, but we check again to be safe.
4678  * ----------
4679  */
4680  if (stmt->argquery != NULL)
4681  {
4682  /* ----------
4683  * OPEN CURSOR with args. We fake a SELECT ... INTO ...
4684  * statement to evaluate the args and put 'em into the
4685  * internal row.
4686  * ----------
4687  */
4688  PLpgSQL_stmt_execsql set_args;
4689 
4690  if (curvar->cursor_explicit_argrow < 0)
4691  ereport(ERROR,
4692  (errcode(ERRCODE_SYNTAX_ERROR),
4693  errmsg("arguments given for cursor without arguments")));
4694 
4695  memset(&set_args, 0, sizeof(set_args));
4696  set_args.cmd_type = PLPGSQL_STMT_EXECSQL;
4697  set_args.lineno = stmt->lineno;
4698  set_args.sqlstmt = stmt->argquery;
4699  set_args.into = true;
4700  /* XXX historically this has not been STRICT */
4701  set_args.target = (PLpgSQL_variable *)
4702  (estate->datums[curvar->cursor_explicit_argrow]);
4703 
4704  if (exec_stmt_execsql(estate, &set_args) != PLPGSQL_RC_OK)
4705  elog(ERROR, "open cursor failed during argument processing");
4706  }
4707  else
4708  {
4709  if (curvar->cursor_explicit_argrow >= 0)
4710  ereport(ERROR,
4711  (errcode(ERRCODE_SYNTAX_ERROR),
4712  errmsg("arguments required for cursor")));
4713  }
4714 
4715  query = curvar->cursor_explicit_expr;
4716  if (query->plan == NULL)
4717  exec_prepare_plan(estate, query, curvar->cursor_options, true);
4718  }
4719 
4720  /*
4721  * Set up ParamListInfo for this query
4722  */
4723  paramLI = setup_param_list(estate, query);
4724 
4725  /*
4726  * Open the cursor (the paramlist will get copied into the portal)
4727  */
4728  portal = SPI_cursor_open_with_paramlist(curname, query->plan,
4729  paramLI,
4730  estate->readonly_func);
4731  if (portal == NULL)
4732  elog(ERROR, "could not open cursor: %s",
4734 
4735  /*
4736  * If cursor variable was NULL, store the generated portal name in it
4737  */
4738  if (curname == NULL)
4739  assign_text_var(estate, curvar, portal->name);
4740 
4741  /* If we had any transient data, clean it up */
4742  exec_eval_cleanup(estate);
4743  if (stmt_mcontext)
4744  MemoryContextReset(stmt_mcontext);
4745 
4746  return PLPGSQL_RC_OK;
4747 }
4748 
4749 
4750 /* ----------
4751  * exec_stmt_fetch Fetch from a cursor into a target, or just
4752  * move the current position of the cursor
4753  * ----------
4754  */
4755 static int
4757 {
4758  PLpgSQL_var *curvar;
4759  long how_many = stmt->how_many;
4760  SPITupleTable *tuptab;
4761  Portal portal;
4762  char *curname;
4763  uint64 n;
4764  MemoryContext oldcontext;
4765 
4766  /* ----------
4767  * Get the portal of the cursor by name
4768  * ----------
4769  */
4770  curvar = (PLpgSQL_var *) (estate->datums[stmt->curvar]);
4771  if (curvar->isnull)
4772  ereport(ERROR,
4773  (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
4774  errmsg("cursor variable \"%s\" is null", curvar->refname)));
4775 
4776  /* Use eval_mcontext for short-lived string */
4777  oldcontext = MemoryContextSwitchTo(get_eval_mcontext(estate));
4778  curname = TextDatumGetCString(curvar->value);
4779  MemoryContextSwitchTo(oldcontext);
4780 
4781  portal = SPI_cursor_find(curname);
4782  if (portal == NULL)
4783  ereport(ERROR,
4784  (errcode(ERRCODE_UNDEFINED_CURSOR),
4785  errmsg("cursor \"%s\" does not exist", curname)));
4786 
4787  /* Calculate position for FETCH_RELATIVE or FETCH_ABSOLUTE */
4788  if (stmt->expr)
4789  {
4790  bool isnull;
4791 
4792  /* XXX should be doing this in LONG not INT width */
4793  how_many = exec_eval_integer(estate, stmt->expr, &isnull);
4794 
4795  if (isnull)
4796  ereport(ERROR,
4797  (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
4798  errmsg("relative or absolute cursor position is null")));
4799 
4800  exec_eval_cleanup(estate);
4801  }
4802 
4803  if (!stmt->is_move)
4804  {
4805  PLpgSQL_variable *target;
4806 
4807  /* ----------
4808  * Fetch 1 tuple from the cursor
4809  * ----------
4810  */
4811  SPI_scroll_cursor_fetch(portal, stmt->direction, how_many);
4812  tuptab = SPI_tuptable;
4813  n = SPI_processed;
4814 
4815  /* ----------
4816  * Set the target appropriately.
4817  * ----------
4818  */
4819  target = (PLpgSQL_variable *) estate->datums[stmt->target->dno];
4820  if (n == 0)
4821  exec_move_row(estate, target, NULL, tuptab->tupdesc);
4822  else
4823  exec_move_row(estate, target, tuptab->vals[0], tuptab->tupdesc);
4824 
4825  exec_eval_cleanup(estate);
4826  SPI_freetuptable(tuptab);
4827  }
4828  else
4829  {
4830  /* Move the cursor */
4831  SPI_scroll_cursor_move(portal, stmt->direction, how_many);
4832  n = SPI_processed;
4833  }
4834 
4835  /* Set the ROW_COUNT and the global FOUND variable appropriately. */
4836  estate->eval_processed = n;
4837  exec_set_found(estate, n != 0);
4838 
4839  return PLPGSQL_RC_OK;
4840 }
4841 
4842 /* ----------
4843  * exec_stmt_close Close a cursor
4844  * ----------
4845  */
4846 static int
4848 {
4849  PLpgSQL_var *curvar;
4850  Portal portal;
4851  char *curname;
4852  MemoryContext oldcontext;
4853 
4854  /* ----------
4855  * Get the portal of the cursor by name
4856  * ----------
4857  */
4858  curvar = (PLpgSQL_var *) (estate->datums[stmt->curvar]);
4859  if (curvar->isnull)
4860  ereport(ERROR,
4861  (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
4862  errmsg("cursor variable \"%s\" is null", curvar->refname)));
4863 
4864  /* Use eval_mcontext for short-lived string */
4865  oldcontext = MemoryContextSwitchTo(get_eval_mcontext(estate));
4866  curname = TextDatumGetCString(curvar->value);
4867  MemoryContextSwitchTo(oldcontext);
4868 
4869  portal = SPI_cursor_find(curname);
4870  if (portal == NULL)
4871  ereport(ERROR,
4872  (errcode(ERRCODE_UNDEFINED_CURSOR),
4873  errmsg("cursor \"%s\" does not exist", curname)));
4874 
4875  /* ----------
4876  * And close it.
4877  * ----------
4878  */
4879  SPI_cursor_close(portal);
4880 
4881  return PLPGSQL_RC_OK;
4882 }
4883 
4884 /*
4885  * exec_stmt_commit
4886  *
4887  * Commit the transaction.
4888  */
4889 static int
4891 {
4892  if (stmt->chain)
4894  else
4895  {
4896  SPI_commit();
4898  }
4899 
4900  /*
4901  * We need to build new simple-expression infrastructure, since the old
4902  * data structures are gone.
4903  */
4904  estate->simple_eval_estate = NULL;
4905  estate->simple_eval_resowner = NULL;
4906  plpgsql_create_econtext(estate);
4907 
4908  return PLPGSQL_RC_OK;
4909 }
4910 
4911 /*
4912  * exec_stmt_rollback
4913  *
4914  * Abort the transaction.
4915  */
4916 static int
4918 {
4919  if (stmt->chain)
4921  else
4922  {
4923  SPI_rollback();
4925  }
4926 
4927  /*
4928  * We need to build new simple-expression infrastructure, since the old
4929  * data structures are gone.
4930  */
4931  estate->simple_eval_estate = NULL;
4932  estate->simple_eval_resowner = NULL;
4933  plpgsql_create_econtext(estate);
4934 
4935  return PLPGSQL_RC_OK;
4936 }
4937 
4938 /*
4939  * exec_stmt_set
4940  *
4941  * Execute SET/RESET statement.
4942  *
4943  * We just parse and execute the statement normally, but we have to do it
4944  * without setting a snapshot, for things like SET TRANSACTION.
4945  */
4946 static int
4948 {
4949  PLpgSQL_expr *expr = stmt->expr;
4950  int rc;
4951 
4952  if (expr->plan == NULL)
4953  {
4954  exec_prepare_plan(estate, expr, 0, true);
4955  expr->plan->no_snapshots = true;
4956  }
4957 
4958  rc = SPI_execute_plan(expr->plan, NULL, NULL, estate->readonly_func, 0);
4959 
4960  if (rc != SPI_OK_UTILITY)
4961  elog(ERROR, "SPI_execute_plan failed executing query \"%s\": %s",
4962  expr->query, SPI_result_code_string(rc));
4963 
4964  return PLPGSQL_RC_OK;
4965 }
4966 
4967 /* ----------
4968  * exec_assign_expr Put an expression's result into a variable.
4969  * ----------
4970  */
4971 static void
4973  PLpgSQL_expr *expr)
4974 {
4975  Datum value;
4976  bool isnull;
4977  Oid valtype;
4978  int32 valtypmod;
4979 
4980  /*
4981  * If first time through, create a plan for this expression, and then see
4982  * if we can pass the target variable as a read-write parameter to the
4983  * expression. (This is a bit messy, but it seems cleaner than modifying
4984  * the API of exec_eval_expr for the purpose.)
4985  */
4986  if (expr->plan == NULL)
4987  {
4988  exec_prepare_plan(estate, expr, 0, true);
4989  if (target->dtype == PLPGSQL_DTYPE_VAR)
4990  exec_check_rw_parameter(expr, target->dno);
4991  }
4992 
4993  value = exec_eval_expr(estate, expr, &isnull, &valtype, &valtypmod);
4994  exec_assign_value(estate, target, value, isnull, valtype, valtypmod);
4995  exec_eval_cleanup(estate);
4996 }
4997 
4998 
4999 /* ----------
5000  * exec_assign_c_string Put a C string into a text variable.
5001  *
5002  * We take a NULL pointer as signifying empty string, not SQL null.
5003  *
5004  * As with the underlying exec_assign_value, caller is expected to do
5005  * exec_eval_cleanup later.
5006  * ----------
5007  */
5008 static void
5010  const char *str)
5011 {
5012  text *value;
5013  MemoryContext oldcontext;
5014 
5015  /* Use eval_mcontext for short-lived text value */
5016  oldcontext = MemoryContextSwitchTo(get_eval_mcontext(estate));
5017  if (str != NULL)
5018  value = cstring_to_text(str);
5019  else
5020  value = cstring_to_text("");
5021  MemoryContextSwitchTo(oldcontext);
5022 
5023  exec_assign_value(estate, target, PointerGetDatum(value), false,
5024  TEXTOID, -1);
5025 }
5026 
5027 
5028 /* ----------
5029  * exec_assign_value Put a value into a target datum
5030  *
5031  * Note: in some code paths, this will leak memory in the eval_mcontext;
5032  * we assume that will be cleaned up later by exec_eval_cleanup. We cannot
5033  * call exec_eval_cleanup here for fear of destroying the input Datum value.
5034  * ----------
5035  */
5036 static void
5038  PLpgSQL_datum *target,
5039  Datum value, bool isNull,
5040  Oid valtype, int32 valtypmod)
5041 {
5042  switch (target->dtype)
5043  {
5044  case PLPGSQL_DTYPE_VAR:
5045  case PLPGSQL_DTYPE_PROMISE:
5046  {
5047  /*
5048  * Target is a variable
5049  */
5050  PLpgSQL_var *var = (PLpgSQL_var *) target;
5051  Datum newvalue;
5052 
5053  newvalue = exec_cast_value(estate,
5054  value,
5055  &isNull,
5056  valtype,
5057  valtypmod,
5058  var->datatype->typoid,
5059  var->datatype->atttypmod);
5060 
5061  if (isNull && var->notnull)
5062  ereport(ERROR,
5063  (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
5064  errmsg("null value cannot be assigned to variable \"%s\" declared NOT NULL",
5065  var->refname)));
5066 
5067  /*
5068  * If type is by-reference, copy the new value (which is
5069  * probably in the eval_mcontext) into the procedure's main
5070  * memory context. But if it's a read/write reference to an
5071  * expanded object, no physical copy needs to happen; at most
5072  * we need to reparent the object's memory context.
5073  *
5074  * If it's an array, we force the value to be stored in R/W
5075  * expanded form. This wins if the function later does, say,
5076  * a lot of array subscripting operations on the variable, and
5077  * otherwise might lose. We might need to use a different
5078  * heuristic, but it's too soon to tell. Also, are there
5079  * cases where it'd be useful to force non-array values into
5080  * expanded form?
5081  */
5082  if (!var->datatype->typbyval && !isNull)
5083  {
5084  if (var->datatype->typisarray &&
5086  {
5087  /* array and not already R/W, so apply expand_array */
5088  newvalue = expand_array(newvalue,
5089  estate->datum_context,
5090  NULL);
5091  }
5092  else
5093  {
5094  /* else transfer value if R/W, else just datumCopy */
5095  newvalue = datumTransfer(newvalue,
5096  false,
5097  var->datatype->typlen);
5098  }
5099  }
5100 
5101  /*
5102  * Now free the old value, if any, and assign the new one. But
5103  * skip the assignment if old and new values are the same.
5104  * Note that for expanded objects, this test is necessary and
5105  * cannot reliably be made any earlier; we have to be looking
5106  * at the object's standard R/W pointer to be sure pointer
5107  * equality is meaningful.
5108  *
5109  * Also, if it's a promise variable, we should disarm the
5110  * promise in any case --- otherwise, assigning null to an
5111  * armed promise variable would fail to disarm the promise.
5112  */
5113  if (var->value != newvalue || var->isnull || isNull)
5114  assign_simple_var(estate, var, newvalue, isNull,
5115  (!var->datatype->typbyval && !isNull));
5116  else
5118  break;
5119  }
5120 
5121  case PLPGSQL_DTYPE_ROW:
5122  {
5123  /*
5124  * Target is a row variable
5125  */
5126  PLpgSQL_row *row = (PLpgSQL_row *) target;
5127 
5128  if (isNull)
5129  {
5130  /* If source is null, just assign nulls to the row */
5131  exec_move_row(estate, (PLpgSQL_variable *) row,
5132  NULL, NULL);
5133  }
5134  else
5135  {
5136  /* Source must be of RECORD or composite type */
5137  if (!type_is_rowtype(valtype))
5138  ereport(ERROR,
5139  (errcode(ERRCODE_DATATYPE_MISMATCH),
5140  errmsg("cannot assign non-composite value to a row variable")));
5142  value);
5143  }
5144  break;
5145  }
5146 
5147  case PLPGSQL_DTYPE_REC:
5148  {
5149  /*
5150  * Target is a record variable
5151  */
5152  PLpgSQL_rec *rec = (PLpgSQL_rec *) target;
5153 
5154  if (isNull)
5155  {
5156  if (rec->notnull)
5157  ereport(ERROR,
5158  (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
5159  errmsg("null value cannot be assigned to variable \"%s\" declared NOT NULL",
5160  rec->refname)));
5161 
5162  /* Set variable to a simple NULL */
5163  exec_move_row(estate, (PLpgSQL_variable *) rec,
5164  NULL, NULL);
5165  }
5166  else
5167  {
5168  /* Source must be of RECORD or composite type */
5169  if (!type_is_rowtype(valtype))
5170  ereport(ERROR,
5171  (errcode(ERRCODE_DATATYPE_MISMATCH),
5172  errmsg("cannot assign non-composite value to a record variable")));
5174  value);
5175  }
5176  break;
5177  }
5178 
5180  {
5181  /*
5182  * Target is a field of a record
5183  */
5184  PLpgSQL_recfield *recfield = (PLpgSQL_recfield *) target;
5185  PLpgSQL_rec *rec;
5186  ExpandedRecordHeader *erh;
5187 
5188  rec = (PLpgSQL_rec *) (estate->datums[recfield->recparentno]);
5189  erh = rec->erh;
5190 
5191  /*
5192  * If record variable is NULL, instantiate it if it has a
5193  * named composite type, else complain. (This won't change
5194  * the logical state of the record, but if we successfully
5195  * assign below, the unassigned fields will all become NULLs.)
5196  */
5197  if (erh == NULL)
5198  {
5199  instantiate_empty_record_variable(estate, rec);
5200  erh = rec->erh;
5201  }
5202 
5203  /*
5204  * Look up the field's properties if we have not already, or
5205  * if the tuple descriptor ID changed since last time.
5206  */
5207  if (unlikely(recfield->rectupledescid != erh->er_tupdesc_id))
5208  {
5210  recfield->fieldname,
5211  &recfield->finfo))
5212  ereport(ERROR,
5213  (errcode(ERRCODE_UNDEFINED_COLUMN),
5214  errmsg("record \"%s\" has no field \"%s\"",
5215  rec->refname, recfield->fieldname)));
5216  recfield->rectupledescid = erh->er_tupdesc_id;
5217  }
5218 
5219  /* We don't support assignments to system columns. */
5220  if (recfield->finfo.fnumber <= 0)
5221  ereport(ERROR,
5222  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5223  errmsg("cannot assign to system column \"%s\"",
5224  recfield->fieldname)));
5225 
5226  /* Cast the new value to the right type, if needed. */
5227  value = exec_cast_value(estate,
5228  value,
5229  &isNull,
5230  valtype,
5231  valtypmod,
5232  recfield->finfo.ftypeid,
5233  recfield->finfo.ftypmod);
5234 
5235  /* And assign it. */
5236  expanded_record_set_field(erh, recfield->finfo.fnumber,
5237  value, isNull, !estate->atomic);
5238  break;
5239  }
5240 
5242  {
5243  /*
5244  * Target is an element of an array
5245  */
5246  PLpgSQL_arrayelem *arrayelem;
5247  int nsubscripts;
5248  int i;
5249  PLpgSQL_expr *subscripts[MAXDIM];
5250  int subscriptvals[MAXDIM];
5251  Datum oldarraydatum,
5252  newarraydatum,
5253  coerced_value;
5254  bool oldarrayisnull;
5255  Oid parenttypoid;
5256  int32 parenttypmod;
5257  SPITupleTable *save_eval_tuptable;
5258  MemoryContext oldcontext;
5259 
5260  /*
5261  * We need to do subscript evaluation, which might require
5262  * evaluating general expressions; and the caller might have
5263  * done that too in order to prepare the input Datum. We have
5264  * to save and restore the caller's SPI_execute result, if
5265  * any.
5266  */
5267  save_eval_tuptable = estate->eval_tuptable;
5268  estate->eval_tuptable = NULL;
5269 
5270  /*
5271  * To handle constructs like x[1][2] := something, we have to
5272  * be prepared to deal with a chain of arrayelem datums. Chase
5273  * back to find the base array datum, and save the subscript
5274  * expressions as we go. (We are scanning right to left here,
5275  * but want to evaluate the subscripts left-to-right to
5276  * minimize surprises.) Note that arrayelem is left pointing
5277  * to the leftmost arrayelem datum, where we will cache the
5278  * array element type data.
5279  */
5280  nsubscripts = 0;
5281  do
5282  {
5283  arrayelem = (PLpgSQL_arrayelem *) target;
5284  if (nsubscripts >= MAXDIM)
5285  ereport(ERROR,
5286  (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
5287  errmsg("number of array dimensions (%d) exceeds the maximum allowed (%d)",
5288  nsubscripts + 1, MAXDIM)));
5289  subscripts[nsubscripts++] = arrayelem->subscript;
5290  target = estate->datums[arrayelem->arrayparentno];
5291  } while (target->dtype == PLPGSQL_DTYPE_ARRAYELEM);
5292 
5293  /* Fetch current value of array datum */
5294  exec_eval_datum(estate, target,
5295  &parenttypoid, &parenttypmod,
5296  &oldarraydatum, &oldarrayisnull);
5297 
5298  /* Update cached type data if necessary */
5299  if (arrayelem->parenttypoid != parenttypoid ||
5300  arrayelem->parenttypmod != parenttypmod)
5301  {
5302  Oid arraytypoid;
5303  int32 arraytypmod = parenttypmod;
5304  int16 arraytyplen;
5305  Oid elemtypoid;
5306  int16 elemtyplen;
5307  bool elemtypbyval;
5308  char elemtypalign;
5309 
5310  /* If target is domain over array, reduce to base type */
5311  arraytypoid = getBaseTypeAndTypmod(parenttypoid,
5312  &arraytypmod);
5313 
5314  /* ... and identify the element type */
5315  elemtypoid = get_element_type(arraytypoid);
5316  if (!OidIsValid(elemtypoid))
5317  ereport(ERROR,
5318  (errcode(ERRCODE_DATATYPE_MISMATCH),
5319  errmsg("subscripted object is not an array")));
5320 
5321  /* Collect needed data about the types */
5322  arraytyplen = get_typlen(arraytypoid);
5323 
5324  get_typlenbyvalalign(elemtypoid,
5325  &elemtyplen,
5326  &elemtypbyval,
5327  &elemtypalign);
5328 
5329  /* Now safe to update the cached data */
5330  arrayelem->parenttypoid = parenttypoid;
5331  arrayelem->parenttypmod = parenttypmod;
5332  arrayelem->arraytypoid = arraytypoid;
5333  arrayelem->arraytypmod = arraytypmod;
5334  arrayelem->arraytyplen = arraytyplen;
5335  arrayelem->elemtypoid = elemtypoid;
5336  arrayelem->elemtyplen = elemtyplen;
5337  arrayelem->elemtypbyval = elemtypbyval;
5338  arrayelem->elemtypalign = elemtypalign;
5339  }
5340 
5341  /*
5342  * Evaluate the subscripts, switch into left-to-right order.
5343  * Like the expression built by ExecInitSubscriptingRef(),
5344  * complain if any subscript is null.
5345  */
5346  for (i = 0; i < nsubscripts; i++)
5347  {
5348  bool subisnull;
5349 
5350  subscriptvals[i] =
5351  exec_eval_integer(estate,
5352  subscripts[nsubscripts - 1 - i],
5353  &subisnull);
5354  if (subisnull)
5355  ereport(ERROR,
5356  (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
5357  errmsg("array subscript in assignment must not be null")));
5358 
5359  /*
5360  * Clean up in case the subscript expression wasn't
5361  * simple. We can't do exec_eval_cleanup, but we can do
5362  * this much (which is safe because the integer subscript
5363  * value is surely pass-by-value), and we must do it in
5364  * case the next subscript expression isn't simple either.
5365  */
5366  if (estate->eval_tuptable != NULL)
5368  estate->eval_tuptable = NULL;
5369  }
5370 
5371  /* Now we can restore caller's SPI_execute result if any. */
5372  Assert(estate->eval_tuptable == NULL);
5373  estate->eval_tuptable = save_eval_tuptable;
5374 
5375  /* Coerce source value to match array element type. */
5376  coerced_value = exec_cast_value(estate,
5377  value,
5378  &isNull,
5379  valtype,
5380  valtypmod,
5381  arrayelem->elemtypoid,
5382  arrayelem->arraytypmod);
5383 
5384  /*
5385  * If the original array is null, cons up an empty array so
5386  * that the assignment can proceed; we'll end with a
5387  * one-element array containing just the assigned-to
5388  * subscript. This only works for varlena arrays, though; for
5389  * fixed-length array types we skip the assignment. We can't
5390  * support assignment of a null entry into a fixed-length
5391  * array, either, so that's a no-op too. This is all ugly but
5392  * corresponds to the current behavior of execExpr*.c.
5393  */
5394  if (arrayelem->arraytyplen > 0 && /* fixed-length array? */
5395  (oldarrayisnull || isNull))
5396  return;
5397 
5398  /* empty array, if any, and newarraydatum are short-lived */
5399  oldcontext = MemoryContextSwitchTo(get_eval_mcontext(estate));
5400 
5401  if (oldarrayisnull)
5402  oldarraydatum = PointerGetDatum(construct_empty_array(arrayelem->elemtypoid));
5403 
5404  /*
5405  * Build the modified array value.
5406  */
5407  newarraydatum = array_set_element(oldarraydatum,
5408  nsubscripts,
5409  subscriptvals,
5410  coerced_value,
5411  isNull,
5412  arrayelem->arraytyplen,
5413  arrayelem->elemtyplen,
5414  arrayelem->elemtypbyval,
5415  arrayelem->elemtypalign);
5416 
5417  MemoryContextSwitchTo(oldcontext);
5418 
5419  /*
5420  * Assign the new array to the base variable. It's never NULL
5421  * at this point. Note that if the target is a domain,
5422  * coercing the base array type back up to the domain will
5423  * happen within exec_assign_value.
5424  */
5425  exec_assign_value(estate, target,
5426  newarraydatum,
5427  false,
5428  arrayelem->arraytypoid,
5429  arrayelem->arraytypmod);
5430  break;
5431  }
5432 
5433  default:
5434  elog(ERROR, "unrecognized dtype: %d", target->dtype);
5435  }
5436 }
5437 
5438 /*
5439  * exec_eval_datum Get current value of a PLpgSQL_datum
5440  *
5441  * The type oid, typmod, value in Datum format, and null flag are returned.
5442  *
5443  * At present this doesn't handle PLpgSQL_expr or PLpgSQL_arrayelem datums;
5444  * that's not needed because we never pass references to such datums to SPI.
5445  *
5446  * NOTE: the returned Datum points right at the stored value in the case of
5447  * pass-by-reference datatypes. Generally callers should take care not to
5448  * modify the stored value. Some callers intentionally manipulate variables
5449  * referenced by R/W expanded pointers, though; it is those callers'
5450  * responsibility that the results are semantically OK.
5451  *
5452  * In some cases we have to palloc a return value, and in such cases we put
5453  * it into the estate's eval_mcontext.
5454  */
5455 static void
5457  PLpgSQL_datum *datum,
5458  Oid *typeid,
5459  int32 *typetypmod,
5460  Datum *value,
5461  bool *isnull)
5462 {
5463  MemoryContext oldcontext;
5464 
5465  switch (datum->dtype)
5466  {
5467  case PLPGSQL_DTYPE_PROMISE:
5468  /* fulfill promise if needed, then handle like regular var */
5469  plpgsql_fulfill_promise(estate, (PLpgSQL_var *) datum);
5470 
5471  /* FALL THRU */
5472 
5473  case PLPGSQL_DTYPE_VAR:
5474  {
5475  PLpgSQL_var *var = (PLpgSQL_var *) datum;
5476 
5477  *typeid = var->datatype->typoid;
5478  *typetypmod = var->datatype->atttypmod;
5479  *value = var->value;
5480  *isnull = var->isnull;
5481  break;
5482  }
5483 
5484  case PLPGSQL_DTYPE_ROW:
5485  {
5486  PLpgSQL_row *row = (PLpgSQL_row *) datum;
5487  HeapTuple tup;
5488 
5489  /* We get here if there are multiple OUT parameters */
5490  if (!row->rowtupdesc) /* should not happen */
5491  elog(ERROR, "row variable has no tupdesc");
5492  /* Make sure we have a valid type/typmod setting */
5493  BlessTupleDesc(row->rowtupdesc);
5494  oldcontext = MemoryContextSwitchTo(get_eval_mcontext(estate));
5495  tup = make_tuple_from_row(estate, row, row->rowtupdesc);
5496  if (tup == NULL) /* should not happen */
5497  elog(ERROR, "row not compatible with its own tupdesc");
5498  *typeid = row->rowtupdesc->tdtypeid;
5499  *typetypmod = row->rowtupdesc->tdtypmod;
5500  *value = HeapTupleGetDatum(tup);
5501  *isnull = false;
5502  MemoryContextSwitchTo(oldcontext);
5503  break;
5504  }
5505 
5506  case PLPGSQL_DTYPE_REC:
5507  {
5508  PLpgSQL_rec *rec = (PLpgSQL_rec *) datum;
5509 
5510  if (rec->erh == NULL)
5511  {
5512  /* Treat uninstantiated record as a simple NULL */
5513  *value = (Datum) 0;
5514  *isnull = true;
5515  /* Report variable's declared type */
5516  *typeid = rec->rectypeid;
5517  *typetypmod = -1;
5518  }
5519  else
5520  {
5521  if (ExpandedRecordIsEmpty(rec->erh))
5522  {
5523  /* Empty record is also a NULL */
5524  *value = (Datum) 0;
5525  *isnull = true;
5526  }
5527  else
5528  {
5529  *value = ExpandedRecordGetDatum(rec->erh);
5530  *isnull = false;
5531  }
5532  if (rec->rectypeid != RECORDOID)
5533  {
5534  /* Report variable's declared type, if not RECORD */
5535  *typeid = rec->rectypeid;
5536  *typetypmod = -1;
5537  }
5538  else
5539  {
5540  /* Report record's actual type if declared RECORD */
5541  *typeid = rec->erh->er_typeid;
5542  *typetypmod = rec->erh->er_typmod;
5543  }
5544  }
5545  break;
5546  }
5547 
5549  {
5550  PLpgSQL_recfield *recfield = (PLpgSQL_recfield *) datum;
5551  PLpgSQL_rec *rec;
5552  ExpandedRecordHeader *erh;
5553 
5554  rec = (PLpgSQL_rec *) (estate->datums[recfield->recparentno]);
5555  erh = rec->erh;
5556 
5557  /*
5558  * If record variable is NULL, instantiate it if it has a
5559  * named composite type, else complain. (This won't change
5560  * the logical state of the record: it's still NULL.)
5561  */
5562  if (erh == NULL)
5563  {
5564  instantiate_empty_record_variable(estate, rec);
5565  erh = rec->erh;
5566  }
5567 
5568  /*
5569  * Look up the field's properties if we have not already, or
5570  * if the tuple descriptor ID changed since last time.
5571  */
5572  if (unlikely(recfield->rectupledescid != erh->er_tupdesc_id))
5573  {
5575  recfield->fieldname,
5576  &recfield->finfo))
5577  ereport(ERROR,
5578  (errcode(ERRCODE_UNDEFINED_COLUMN),
5579  errmsg("record \"%s\" has no field \"%s\"",
5580  rec->refname, recfield->fieldname)));
5581  recfield->rectupledescid = erh->er_tupdesc_id;
5582  }
5583 
5584  /* Report type data. */
5585  *typeid = recfield->finfo.ftypeid;
5586  *typetypmod = recfield->finfo.ftypmod;
5587 
5588  /* And fetch the field value. */
5589  *value = expanded_record_get_field(erh,
5590  recfield->finfo.fnumber,
5591  isnull);
5592  break;
5593  }
5594 
5595  default:
5596  elog(ERROR, "unrecognized dtype: %d", datum->dtype);
5597  }
5598 }
5599 
5600 /*
5601  * plpgsql_exec_get_datum_type Get datatype of a PLpgSQL_datum
5602  *
5603  * This is the same logic as in exec_eval_datum, but we skip acquiring
5604  * the actual value of the variable. Also, needn't support DTYPE_ROW.
5605  */
5606 Oid
5608  PLpgSQL_datum *datum)
5609 {
5610  Oid typeid;
5611 
5612  switch (datum->dtype)
5613  {
5614  case PLPGSQL_DTYPE_VAR:
5615  case PLPGSQL_DTYPE_PROMISE:
5616  {
5617  PLpgSQL_var *var = (PLpgSQL_var *) datum;
5618 
5619  typeid = var->datatype->typoid;
5620  break;
5621  }
5622 
5623  case PLPGSQL_DTYPE_REC:
5624  {
5625  PLpgSQL_rec *rec = (PLpgSQL_rec *) datum;
5626 
5627  if (rec->erh == NULL || rec->rectypeid != RECORDOID)
5628  {
5629  /* Report variable's declared type */
5630  typeid = rec->rectypeid;
5631  }
5632  else
5633  {
5634  /* Report record's actual type if declared RECORD */
5635  typeid = rec->erh->er_typeid;
5636  }
5637  break;
5638  }
5639 
5641  {
5642  PLpgSQL_recfield *recfield = (PLpgSQL_recfield *) datum;
5643  PLpgSQL_rec *rec;
5644 
5645  rec = (PLpgSQL_rec *) (estate->datums[recfield->recparentno]);
5646 
5647  /*
5648  * If record variable is NULL, instantiate it if it has a
5649  * named composite type, else complain. (This won't change
5650  * the logical state of the record: it's still NULL.)
5651  */
5652  if (rec->erh == NULL)
5653  instantiate_empty_record_variable(estate, rec);
5654 
5655  /*
5656  * Look up the field's properties if we have not already, or
5657  * if the tuple descriptor ID changed since last time.
5658  */
5659  if (unlikely(recfield->rectupledescid != rec->erh->er_tupdesc_id))
5660  {
5662  recfield->fieldname,
5663  &recfield->finfo))
5664  ereport(ERROR,
5665  (errcode(ERRCODE_UNDEFINED_COLUMN),
5666  errmsg("record \"%s\" has no field \"%s\"",
5667  rec->refname, recfield->fieldname)));
5668  recfield->rectupledescid = rec->erh->er_tupdesc_id;
5669  }
5670 
5671  typeid = recfield->finfo.ftypeid;
5672  break;
5673  }
5674 
5675  default:
5676  elog(ERROR, "unrecognized dtype: %d", datum->dtype);
5677  typeid = InvalidOid; /* keep compiler quiet */
5678  break;
5679  }
5680 
5681