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