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