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