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