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