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