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