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