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