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