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