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